<commit_before>/**
 * Copyright 2016 Confluent Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package kafka

import (
	"fmt"
	"reflect"
	"sort"
	"testing"
)

// TestConsumerAPIs dry-tests most Consumer APIs, no broker is needed.
func TestConsumerAPIs(t *testing.T) {

	c, err := NewConsumer(&ConfigMap{})
	if err == nil {
		t.Fatalf("Expected NewConsumer() to fail without group.id")
	}

	c, err = NewConsumer(&ConfigMap{
		"group.id":           "gotest",
		"socket.timeout.ms":  10,
		"session.timeout.ms": 10})
	if err != nil {
		t.Fatalf("%s", err)
	}

	t.Logf("Consumer %s", c)

	err = c.Subscribe("gotest", nil)
	if err != nil {
		t.Errorf("Subscribe failed: %s", err)
	}

	err = c.SubscribeTopics([]string{"gotest1", "gotest2"},
		func(my_c *Consumer, ev Event) error {
			t.Logf("%s", ev)
			return nil
		})
	if err != nil {
		t.Errorf("SubscribeTopics failed: %s", err)
	}
	_, err = c.Commit()
	if err != nil && err.(Error).Code() != ErrNoOffset {
		t.Errorf("Commit() failed: %s", err)
	}

	err = c.Unsubscribe()
	if err != nil {
		t.Errorf("Unsubscribe failed: %s", err)
	}

	topic := "gotest"
	stored, err := c.StoreOffsets([]TopicPartition{{Topic: &topic, Partition: 0, Offset: 1}})
	if err != nil && err.(Error).Code() != ErrUnknownPartition {
		t.Errorf("StoreOffsets() failed: %s", err)
		toppar := stored[0]
		if toppar.Error.(Error).Code() == ErrUnknownPartition {
			t.Errorf("StoreOffsets() TopicPartition error: %s", toppar.Error)
		}
	}
	stored, err = c.StoreOffsets(nil)
	if err != nil {
		t.Errorf("StoreOffsets(nil) failed: %s", err)
	}

	topic1 := "gotest1"
	topic2 := "gotest2"
	err = c.Assign([]TopicPartition{{Topic: &topic1, Partition: 2},
		{Topic: &topic2, Partition: 1}})
	if err != nil {
		t.Errorf("Assign failed: %s", err)
	}

	err = c.Seek(TopicPartition{Topic: &topic1, Partition: 2, Offset: -1}, 1000)
	if err != nil {
		t.Errorf("Seek failed: %s", err)
	}

	err = c.Unassign()
	if err != nil {
		t.Errorf("Unassign failed: %s", err)
	}

	err = c.Close()
	if err != nil {
		t.Errorf("Close failed: %s", err)
	}
}

func TestConsumerSubscription(t *testing.T) {
	c, err := NewConsumer(&ConfigMap{"group.id": "gotest"})
	if err != nil {
		t.Fatalf("%s", err)
	}

	topics := []string{"gotest1", "gotest2", "gotest3"}
	sort.Strings(topics)

	err = c.SubscribeTopics(topics, nil)
	if err != nil {
		t.Fatalf("SubscribeTopics failed: %s", err)
	}

	subscription, err := c.Subscription()
	if err != nil {
		t.Fatalf("Subscription() failed: %s", err)
	}

	sort.Strings(subscription)

	t.Logf("Compare Subscription %v to original list of topics %v\n",
		subscription, topics)

	r := reflect.DeepEqual(topics, subscription)
	if r != true {
		t.Fatalf("Subscription() %v does not match original topics %v",
			subscription, topics)
	}
	c.Close()
}

func TestConsumerAssignment(t *testing.T) {
	c, err := NewConsumer(&ConfigMap{"group.id": "gotest"})
	if err != nil {
		t.Fatalf("%s", err)
	}

	topic0 := "topic0"
	topic1 := "topic1"
	partitions := TopicPartitions{
		{Topic: &topic1, Partition: 1},
		{Topic: &topic1, Partition: 3},
		{Topic: &topic0, Partition: 2}}
	sort.Sort(partitions)

	err = c.Assign(partitions)
	if err != nil {
		t.Fatalf("Assign failed: %s", err)
	}

	assignment, err := c.Assignment()
	if err != nil {
		t.Fatalf("Assignment() failed: %s", err)
	}

	sort.Sort(TopicPartitions(assignment))

	t.Logf("Compare Assignment %v to original list of partitions %v\n",
		assignment, partitions)

	// reflect.DeepEqual() can't be used since TopicPartition.Topic
	// is a pointer to a string rather than a string and the pointer
	// will differ between partitions and assignment.
	// Instead do a simple stringification + string compare.
	if fmt.Sprintf("%v", assignment) != fmt.Sprintf("%v", partitions) {
		t.Fatalf("Assignment() %v does not match original partitions %v",
			assignment, partitions)
	}
	c.Close()
}
<commit_msg>fixup! Added Consumer.OffsetsStore()<commit_after>/**
 * Copyright 2016 Confluent Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package kafka

import (
	"fmt"
	"reflect"
	"sort"
	"testing"
)

// TestConsumerAPIs dry-tests most Consumer APIs, no broker is needed.
func TestConsumerAPIs(t *testing.T) {

	c, err := NewConsumer(&ConfigMap{})
	if err == nil {
		t.Fatalf("Expected NewConsumer() to fail without group.id")
	}

	c, err = NewConsumer(&ConfigMap{
		"group.id":           "gotest",
		"socket.timeout.ms":  10,
		"session.timeout.ms": 10})
	if err != nil {
		t.Fatalf("%s", err)
	}

	t.Logf("Consumer %s", c)

	err = c.Subscribe("gotest", nil)
	if err != nil {
		t.Errorf("Subscribe failed: %s", err)
	}

	err = c.SubscribeTopics([]string{"gotest1", "gotest2"},
		func(my_c *Consumer, ev Event) error {
			t.Logf("%s", ev)
			return nil
		})
	if err != nil {
		t.Errorf("SubscribeTopics failed: %s", err)
	}
	_, err = c.Commit()
	if err != nil && err.(Error).Code() != ErrNoOffset {
		t.Errorf("Commit() failed: %s", err)
	}

	err = c.Unsubscribe()
	if err != nil {
		t.Errorf("Unsubscribe failed: %s", err)
	}

	topic := "gotest"
	stored, err := c.StoreOffsets([]TopicPartition{{Topic: &topic, Partition: 0, Offset: 1}})
	if err != nil && err.(Error).Code() != ErrUnknownPartition {
		t.Errorf("StoreOffsets() failed: %s", err)
		toppar := stored[0]
		if toppar.Error.(Error).Code() == ErrUnknownPartition {
			t.Errorf("StoreOffsets() TopicPartition error: %s", toppar.Error)
		}
	}
	var empty []TopicPartition
	stored, err = c.StoreOffsets(empty)
	if err != nil {
		t.Errorf("StoreOffsets(empty) failed: %s", err)
	}

	topic1 := "gotest1"
	topic2 := "gotest2"
	err = c.Assign([]TopicPartition{{Topic: &topic1, Partition: 2},
		{Topic: &topic2, Partition: 1}})
	if err != nil {
		t.Errorf("Assign failed: %s", err)
	}

	err = c.Seek(TopicPartition{Topic: &topic1, Partition: 2, Offset: -1}, 1000)
	if err != nil {
		t.Errorf("Seek failed: %s", err)
	}

	err = c.Unassign()
	if err != nil {
		t.Errorf("Unassign failed: %s", err)
	}

	err = c.Close()
	if err != nil {
		t.Errorf("Close failed: %s", err)
	}
}

func TestConsumerSubscription(t *testing.T) {
	c, err := NewConsumer(&ConfigMap{"group.id": "gotest"})
	if err != nil {
		t.Fatalf("%s", err)
	}

	topics := []string{"gotest1", "gotest2", "gotest3"}
	sort.Strings(topics)

	err = c.SubscribeTopics(topics, nil)
	if err != nil {
		t.Fatalf("SubscribeTopics failed: %s", err)
	}

	subscription, err := c.Subscription()
	if err != nil {
		t.Fatalf("Subscription() failed: %s", err)
	}

	sort.Strings(subscription)

	t.Logf("Compare Subscription %v to original list of topics %v\n",
		subscription, topics)

	r := reflect.DeepEqual(topics, subscription)
	if r != true {
		t.Fatalf("Subscription() %v does not match original topics %v",
			subscription, topics)
	}
	c.Close()
}

func TestConsumerAssignment(t *testing.T) {
	c, err := NewConsumer(&ConfigMap{"group.id": "gotest"})
	if err != nil {
		t.Fatalf("%s", err)
	}

	topic0 := "topic0"
	topic1 := "topic1"
	partitions := TopicPartitions{
		{Topic: &topic1, Partition: 1},
		{Topic: &topic1, Partition: 3},
		{Topic: &topic0, Partition: 2}}
	sort.Sort(partitions)

	err = c.Assign(partitions)
	if err != nil {
		t.Fatalf("Assign failed: %s", err)
	}

	assignment, err := c.Assignment()
	if err != nil {
		t.Fatalf("Assignment() failed: %s", err)
	}

	sort.Sort(TopicPartitions(assignment))

	t.Logf("Compare Assignment %v to original list of partitions %v\n",
		assignment, partitions)

	// reflect.DeepEqual() can't be used since TopicPartition.Topic
	// is a pointer to a string rather than a string and the pointer
	// will differ between partitions and assignment.
	// Instead do a simple stringification + string compare.
	if fmt.Sprintf("%v", assignment) != fmt.Sprintf("%v", partitions) {
		t.Fatalf("Assignment() %v does not match original partitions %v",
			assignment, partitions)
	}
	c.Close()
}
<|endoftext|>


<commit_before>// beehive's central module system.
package modules

import (
	"encoding/json"
	"io/ioutil"
	"log"
)

// Interface which all modules need to implement
type ModuleInterface interface {
	// Name of the module
	Name() string
	// Description of the module
	Description() string
	// Events defined by module
	Events() []EventDescriptor
	// Actions supported by module
	Actions() []ActionDescriptor

	// Activates the module
	Run(eventChannel chan Event)
	// Handles an action
	Action(action Action) []Placeholder
}

// An Event
type Event struct {
	Namespace string
	Name      string
	Options   []Placeholder
}

// An Action
type Action struct {
	Namespace string
	Name      string
	Options   []Placeholder
}

// A Placeholder used by ins & outs of a module.
type Placeholder struct {
	Name  string
	Type  string
	Value interface{}
}

// Descriptors

// Modules provide events, which are described in an EventDescriptor.
type EventDescriptor struct {
	Namespace   string
	Name        string
	Description string
	Options     []PlaceholderDescriptor
}

// Modules offer actions, which are described in an ActionDescriptor.
type ActionDescriptor struct {
	Namespace   string
	Name        string
	Description string
	Options     []PlaceholderDescriptor
}

// A PlaceholderDescriptor shows which in & out values a module expects and returns.
type PlaceholderDescriptor struct {
	Name        string
	Description string
	Type        string
}

// An element in a Chain
type ChainElement struct {
	Action  Action
	Mapping map[string]string
}

// A user defined Chain
type Chain struct {
	Name        string
	Description string
	Event       *Event
	Elements    []ChainElement
}

var (
	config = "./beehive.conf"

	EventsIn                             = make(chan Event)
	modules  map[string]*ModuleInterface = make(map[string]*ModuleInterface)
	chains   []Chain
)

// Returns the ActionDescriptor matching an action.
func GetActionDescriptor(action *Action) ActionDescriptor {
	mod := (*GetModule(action.Namespace))
	for _, ac := range mod.Actions() {
		if ac.Name == action.Name {
			return ac
		}
	}

	return ActionDescriptor{}
}

// Returns the EventDescriptor matching an event.
func GetEventDescriptor(event *Event) EventDescriptor {
	mod := (*GetModule(event.Namespace))
	for _, ev := range mod.Events() {
		if ev.Name == event.Name {
			return ev
		}
	}

	return EventDescriptor{}
}

func execChains(event *Event) {
	for _, c := range chains {
		if c.Event.Name != event.Name || c.Event.Namespace != event.Namespace {
			continue
		}

		log.Println("Executing chain:", c.Name, "-", c.Description)
		for _, el := range c.Elements {
			action := el.Action
			for k, v := range el.Mapping {
				for _, ov := range event.Options {
					if ov.Name == k {
						opt := Placeholder{
							Name:  v,
							Type:  ov.Type,
							Value: ov.Value,
						}
						action.Options = append(action.Options, opt)
					}
				}
			}

			log.Println("\tExecuting action:", action.Namespace, "/", action.Name, "-", GetActionDescriptor(&action).Description)
			for _, v := range action.Options {
				log.Println("\t\tOptions:", v)
			}
			(*GetModule(action.Namespace)).Action(action)
		}
	}
}

// Handles incoming events and executes matching Chains.
func handleEvents() {
	for {
		event := <-EventsIn

		log.Println()
		log.Println("Event received:", event.Namespace, "/", event.Name, "-", GetEventDescriptor(&event).Description)
		for _, v := range event.Options {
			log.Println("\tOptions:", v)
		}

		execChains(&event)
	}
}

// Modules need to call this method to register themselves
func RegisterModule(mod ModuleInterface) {
	log.Println("Worker bee ready:", mod.Name(), "-", mod.Description())
	for _, ev := range mod.Events() {
		log.Println("\tProvides event:", ev.Name, "-", ev.Description)
		for _, opt := range ev.Options {
			log.Println("\t\tPlaceholder:", opt.Name, "-", opt.Description)
		}
	}
	for _, ac := range mod.Actions() {
		log.Println("\tOffers action:", ac.Name, "-", ac.Description)
		for _, opt := range ac.Options {
			log.Println("\t\tPlaceholder:", opt.Name, "-", opt.Description)
		}
	}

	log.Println()
	modules[mod.Name()] = &mod
}

// Returns module with this name
func GetModule(identifier string) *ModuleInterface {
	mod, ok := modules[identifier]
	if ok {
		return mod
	}

	return nil
}

// Loads chains from config
func LoadChains() {
	j, err := ioutil.ReadFile(config)
	if err == nil {
		err = json.Unmarshal(j, &chains)
		if err != nil {
			panic(err)
		}
	}
}

// Saves chains to config
func SaveChains() {
	j, err := json.MarshalIndent(chains, "", "  ")
	if err != nil {
		panic(err)
	}

	err = ioutil.WriteFile(config, j, 0644)
}

// Starts all registered modules
func StartModules() {
	for _, mod := range modules {
		(*mod).Run(EventsIn)
	}

	LoadChains()
	//	SaveChains()
}

func init() {
	log.Println("Waking the bees...")

	go handleEvents()
}
<commit_msg>* Added doc.<commit_after>// beehive's central module system.
package modules

import (
	"encoding/json"
	"io/ioutil"
	"log"
)

// Interface which all modules need to implement
type ModuleInterface interface {
	// Name of the module
	Name() string
	// Description of the module
	Description() string
	// Events defined by module
	Events() []EventDescriptor
	// Actions supported by module
	Actions() []ActionDescriptor

	// Activates the module
	Run(eventChannel chan Event)
	// Handles an action
	Action(action Action) []Placeholder
}

// An Event
type Event struct {
	Namespace string
	Name      string
	Options   []Placeholder
}

// An Action
type Action struct {
	Namespace string
	Name      string
	Options   []Placeholder
}

// A Placeholder used by ins & outs of a module.
type Placeholder struct {
	Name  string
	Type  string
	Value interface{}
}

// Descriptors

// Modules provide events, which are described in an EventDescriptor.
type EventDescriptor struct {
	Namespace   string
	Name        string
	Description string
	Options     []PlaceholderDescriptor
}

// Modules offer actions, which are described in an ActionDescriptor.
type ActionDescriptor struct {
	Namespace   string
	Name        string
	Description string
	Options     []PlaceholderDescriptor
}

// A PlaceholderDescriptor shows which in & out values a module expects and returns.
type PlaceholderDescriptor struct {
	Name        string
	Description string
	Type        string
}

// An element in a Chain
type ChainElement struct {
	Action  Action
	Mapping map[string]string
}

// A user defined Chain
type Chain struct {
	Name        string
	Description string
	Event       *Event
	Elements    []ChainElement
}

var (
	config = "./beehive.conf"

	EventsIn                             = make(chan Event)
	modules  map[string]*ModuleInterface = make(map[string]*ModuleInterface)
	chains   []Chain
)

// Returns the ActionDescriptor matching an action.
func GetActionDescriptor(action *Action) ActionDescriptor {
	mod := (*GetModule(action.Namespace))
	for _, ac := range mod.Actions() {
		if ac.Name == action.Name {
			return ac
		}
	}

	return ActionDescriptor{}
}

// Returns the EventDescriptor matching an event.
func GetEventDescriptor(event *Event) EventDescriptor {
	mod := (*GetModule(event.Namespace))
	for _, ev := range mod.Events() {
		if ev.Name == event.Name {
			return ev
		}
	}

	return EventDescriptor{}
}

// Execute chains for an event we received.
func execChains(event *Event) {
	for _, c := range chains {
		if c.Event.Name != event.Name || c.Event.Namespace != event.Namespace {
			continue
		}

		log.Println("Executing chain:", c.Name, "-", c.Description)
		for _, el := range c.Elements {
			action := el.Action
			for k, v := range el.Mapping {
				for _, ov := range event.Options {
					if ov.Name == k {
						opt := Placeholder{
							Name:  v,
							Type:  ov.Type,
							Value: ov.Value,
						}
						action.Options = append(action.Options, opt)
					}
				}
			}

			log.Println("\tExecuting action:", action.Namespace, "/", action.Name, "-", GetActionDescriptor(&action).Description)
			for _, v := range action.Options {
				log.Println("\t\tOptions:", v)
			}
			(*GetModule(action.Namespace)).Action(action)
		}
	}
}

// Handles incoming events and executes matching Chains.
func handleEvents() {
	for {
		event := <-EventsIn

		log.Println()
		log.Println("Event received:", event.Namespace, "/", event.Name, "-", GetEventDescriptor(&event).Description)
		for _, v := range event.Options {
			log.Println("\tOptions:", v)
		}

		execChains(&event)
	}
}

// Modules need to call this method to register themselves
func RegisterModule(mod ModuleInterface) {
	log.Println("Worker bee ready:", mod.Name(), "-", mod.Description())
	for _, ev := range mod.Events() {
		log.Println("\tProvides event:", ev.Name, "-", ev.Description)
		for _, opt := range ev.Options {
			log.Println("\t\tPlaceholder:", opt.Name, "-", opt.Description)
		}
	}
	for _, ac := range mod.Actions() {
		log.Println("\tOffers action:", ac.Name, "-", ac.Description)
		for _, opt := range ac.Options {
			log.Println("\t\tPlaceholder:", opt.Name, "-", opt.Description)
		}
	}

	log.Println()
	modules[mod.Name()] = &mod
}

// Returns module with this name
func GetModule(identifier string) *ModuleInterface {
	mod, ok := modules[identifier]
	if ok {
		return mod
	}

	return nil
}

// Loads chains from config
func LoadChains() {
	j, err := ioutil.ReadFile(config)
	if err == nil {
		err = json.Unmarshal(j, &chains)
		if err != nil {
			panic(err)
		}
	}
}

// Saves chains to config
func SaveChains() {
	j, err := json.MarshalIndent(chains, "", "  ")
	if err != nil {
		panic(err)
	}

	err = ioutil.WriteFile(config, j, 0644)
}

// Starts all registered modules
func StartModules() {
	for _, mod := range modules {
		(*mod).Run(EventsIn)
	}

	LoadChains()
	//	SaveChains()
}

func init() {
	log.Println("Waking the bees...")

	go handleEvents()
}
<|endoftext|>


<commit_before>/*
 * ZDNS Copyright 2016 Regents of the University of Michigan
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy
 * of the License at http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

package ptr

import (
	"github.com/miekg/dns"
	"github.com/zmap/zdns"
	"github.com/zmap/zdns/modules/miekg"
)

// Per Connection Lookup ======================================================
//
type Lookup struct {
	Factory *RoutineLookupFactory
	miekg.Lookup
}

func (s *Lookup) DoLookup(name string) (interface{}, zdns.Status, error) {
	nameServer := s.Factory.Factory.RandomNameServer()
	name, _ = dns.ReverseAddr(name)
	name = name[:len(name)-1]
	return miekg.DoLookup(s.Factory.Client, s.Factory.TCPClient, nameServer, dns.TypePTR, name)
}

// Per GoRoutine Factory ======================================================
//
type RoutineLookupFactory struct {
	miekg.RoutineLookupFactory
	Factory *GlobalLookupFactory
}

func (s *RoutineLookupFactory) MakeLookup() (zdns.Lookup, error) {
	a := Lookup{Factory: s}
	return &a, nil
}

// Global Factory =============================================================
//
type GlobalLookupFactory struct {
	zdns.BaseGlobalLookupFactory
}

// Command-line Help Documentation. This is the descriptive text what is
// returned when you run zdns module --help
func (s *GlobalLookupFactory) Help() string {
	return ""
}

func (s *GlobalLookupFactory) MakeRoutineFactory() (zdns.RoutineLookupFactory, error) {
	r := new(RoutineLookupFactory)
	r.Factory = s
	r.Initialize(s.GlobalConf.Timeout)
	return r, nil
}

// Global Registration ========================================================
//
func init() {
	s := new(GlobalLookupFactory)
	zdns.RegisterLookup("PTR", s)
}
<commit_msg>Ptr (#30)<commit_after>/*
 * ZDNS Copyright 2016 Regents of the University of Michigan
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy
 * of the License at http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

package ptr

import (
	"log"

	"github.com/miekg/dns"
	"github.com/zmap/zdns"
	"github.com/zmap/zdns/modules/miekg"
)

// Per Connection Lookup ======================================================
//
type Lookup struct {
	Factory *RoutineLookupFactory
	miekg.Lookup
}

func (s *Lookup) DoLookup(name string) (interface{}, zdns.Status, error) {
	nameServer := s.Factory.Factory.RandomNameServer()
	name, err := dns.ReverseAddr(name)
	if err != nil {
		log.Fatal("Invalid IP address received:", name)
	}
	name, _ = dns.ReverseAddr(name)
	name = name[:len(name)-1]
	return miekg.DoLookup(s.Factory.Client, s.Factory.TCPClient, nameServer, dns.TypePTR, name)
}

// Per GoRoutine Factory ======================================================
//
type RoutineLookupFactory struct {
	miekg.RoutineLookupFactory
	Factory *GlobalLookupFactory
}

func (s *RoutineLookupFactory) MakeLookup() (zdns.Lookup, error) {
	a := Lookup{Factory: s}
	return &a, nil
}

// Global Factory =============================================================
//
type GlobalLookupFactory struct {
	zdns.BaseGlobalLookupFactory
}

// Command-line Help Documentation. This is the descriptive text what is
// returned when you run zdns module --help
func (s *GlobalLookupFactory) Help() string {
	return ""
}

func (s *GlobalLookupFactory) MakeRoutineFactory() (zdns.RoutineLookupFactory, error) {
	r := new(RoutineLookupFactory)
	r.Factory = s
	r.Initialize(s.GlobalConf.Timeout)
	return r, nil
}

// Global Registration ========================================================
//
func init() {
	s := new(GlobalLookupFactory)
	zdns.RegisterLookup("PTR", s)
}
<|endoftext|>


<commit_before>package main

import (
	"log"
	"time"

	"github.com/streadway/amqp"
)

// AmqpBase is the base class for amqp senders and recievers, containing the
// startup and shutdown logic.
type AmqpBase struct {
	connection *amqp.Connection
	channel    *amqp.Channel
}

// Close the connection to amqp gracefully. Subclasses should ensure they finish
// all in-flight processing.
func (a AmqpBase) Close() {
	a.channel.Close()
	a.connection.Close()
}

// Connect to AMQP, and open a communication channel.
func (a *AmqpBase) dial(amqpURL string) (err error) {
	a.connection, err = amqp.Dial(amqpURL)
	if err != nil {
		log.Println("Could not connect to AMQP: ", err)
		return
	}

	a.channel, err = a.connection.Channel()
	if err != nil {
		log.Println("Could not open AMQP channel: ", err)
		return
	}

	return
}

// AmqpReceiver receives delayd commands over amqp
type AmqpReceiver struct {
	AmqpBase
	C    <-chan EntryWrapper
	rawC <-chan amqp.Delivery
}

// NewAmqpReceiver creates a new AmqpReceiver based on the provided AmqpConfig,
// and starts it listening for commands.
func NewAmqpReceiver(ac AmqpConfig) (receiver *AmqpReceiver, err error) {
	receiver = new(AmqpReceiver)

	err = receiver.dial(ac.URL)
	if err != nil {
		return
	}

	err = receiver.channel.ExchangeDeclare(ac.Exchange.Name, ac.Exchange.Kind, ac.Exchange.Durable, ac.Exchange.AutoDelete, ac.Exchange.Internal, ac.Exchange.NoWait, nil)
	if err != nil {
		log.Println("Could not declare AMQP Exchange: ", err)
		return
	}

	queue, err := receiver.channel.QueueDeclare(ac.Queue.Name, ac.Queue.Durable, ac.Queue.AutoDelete, ac.Queue.Exclusive, ac.Queue.NoWait, nil)
	if err != nil {
		log.Println("Could not declare AMQP Queue: ", err)
		return
	}

	for _, exch := range ac.Queue.Bind {
		log.Printf("Binding queue %s to exchange %s", queue.Name, exch)
		err = receiver.channel.QueueBind(queue.Name, "delayd", exch, ac.Queue.NoWait, nil)
		if err != nil {
			log.Fatalf("Error binding queue %s to Exchange %s", queue.Name, exch)
		}
	}

	//XXX set Qos here to match incoming concurrency
	messages, err := receiver.channel.Consume(queue.Name, "delayd", ac.Queue.AutoAck, ac.Queue.Exclusive, ac.Queue.NoLocal, ac.Queue.NoWait, nil)
	if err != nil {
		log.Println("Could not set up queue consume: ", err)
		return
	}

	c := make(chan EntryWrapper)
	receiver.C = c

	go func() {
		for {
			msg, ok := <-messages
			entry := Entry{}

			eWrapper := EntryWrapper{Msg: msg}

			// channel was closed. exit
			if !ok {
				return
			}

			delay, ok := msg.Headers["delayd-delay"].(int64)
			if !ok {
				log.Println("Bad/missing delay. discarding message")
				eWrapper.Done(false)
				continue
			}
			entry.SendAt = time.Now().Add(time.Duration(delay) * time.Millisecond)

			entry.Target, ok = msg.Headers["delayd-target"].(string)
			if !ok {
				log.Println("Bad/missing target. discarding message")
				eWrapper.Done(false)
				continue
			}

			// optional key value for overwrite
			h, ok := msg.Headers["delayd-key"].(string)
			if ok {
				entry.Key = h
			}

			// optional headers that will be relayed
			h, ok = msg.Headers["content-type"].(string)
			if ok {
				entry.ContentType = h
			}

			h, ok = msg.Headers["content-encoding"].(string)
			if ok {
				entry.ContentEncoding = h
			}

			h, ok = msg.Headers["correlation-id"].(string)
			if ok {
				entry.CorrelationID = h
			}

			entry.Body = msg.Body
			eWrapper.Entry = entry

			c <- eWrapper
		}
	}()

	return
}

// AmqpSender sends delayd entries over amqp after their timeout
type AmqpSender struct {
	AmqpBase

	C chan<- EntryWrapper
}

// NewAmqpSender creates a new AmqpSender connected to the given AMQP URL.
func NewAmqpSender(amqpURL string) (sender *AmqpSender, err error) {
	sender = new(AmqpSender)

	err = sender.dial(amqpURL)
	if err != nil {
		return
	}

	return
}

// Send sends a delayd entry over AMQP, using the entry's Target as the publish
// exchange.
func (s AmqpSender) Send(e Entry) (err error) {
	msg := amqp.Publishing{
		DeliveryMode:    amqp.Persistent,
		Timestamp:       time.Now(),
		ContentType:     e.ContentType,
		ContentEncoding: e.ContentEncoding,
		CorrelationId:   e.CorrelationID,
		Body:            e.Body,
	}

	err = s.channel.Publish(e.Target, "", true, false, msg)
	return
}
<commit_msg>Flush incoming amqp messages out of amqp receiver channel before closing<commit_after>package main

import (
	"log"
	"time"

	"github.com/streadway/amqp"
)

// Shutdown is a base class that is inheritable by any other class that may want
// to send a shutdown signal over a channel
type Shutdown struct {
	shutdown chan bool
}

// AmqpBase is the base class for amqp senders and recievers, containing the
// startup and shutdown logic.
type AmqpBase struct {
	Shutdown

	connection *amqp.Connection
	channel    *amqp.Channel
}

// Close the connection to amqp gracefully. Subclasses should ensure they finish
// all in-flight processing.
func (a AmqpBase) Close() {
	a.channel.Close()
	a.connection.Close()
}

// Connect to AMQP, and open a communication channel.
func (a *AmqpBase) dial(amqpURL string) (err error) {
	a.connection, err = amqp.Dial(amqpURL)
	if err != nil {
		log.Println("Could not connect to AMQP: ", err)
		return
	}

	a.channel, err = a.connection.Channel()
	if err != nil {
		log.Println("Could not open AMQP channel: ", err)
		return
	}

	return
}

// AmqpReceiver receives delayd commands over amqp
type AmqpReceiver struct {
	AmqpBase
	C    <-chan EntryWrapper
	rawC <-chan amqp.Delivery
}

// Close overwrites the base class close because we need to do some additional
// work for the receiver (signalling the shutdown channel)
func (a AmqpReceiver) Close() {
	a.shutdown <- true
	a.AmqpBase.Close()
}

// NewAmqpReceiver creates a new AmqpReceiver based on the provided AmqpConfig,
// and starts it listening for commands.
func NewAmqpReceiver(ac AmqpConfig) (receiver *AmqpReceiver, err error) {
	receiver = new(AmqpReceiver)

	err = receiver.dial(ac.URL)
	if err != nil {
		return
	}

	err = receiver.channel.ExchangeDeclare(ac.Exchange.Name, ac.Exchange.Kind, ac.Exchange.Durable, ac.Exchange.AutoDelete, ac.Exchange.Internal, ac.Exchange.NoWait, nil)
	if err != nil {
		log.Println("Could not declare AMQP Exchange: ", err)
		return
	}

	queue, err := receiver.channel.QueueDeclare(ac.Queue.Name, ac.Queue.Durable, ac.Queue.AutoDelete, ac.Queue.Exclusive, ac.Queue.NoWait, nil)
	if err != nil {
		log.Println("Could not declare AMQP Queue: ", err)
		return
	}

	for _, exch := range ac.Queue.Bind {
		log.Printf("Binding queue %s to exchange %s", queue.Name, exch)
		err = receiver.channel.QueueBind(queue.Name, "delayd", exch, ac.Queue.NoWait, nil)
		if err != nil {
			log.Fatalf("Error binding queue %s to Exchange %s", queue.Name, exch)
		}
	}

	//XXX set Qos here to match incoming concurrency
	messages, err := receiver.channel.Consume(queue.Name, "delayd", ac.Queue.AutoAck, ac.Queue.Exclusive, ac.Queue.NoLocal, ac.Queue.NoWait, nil)
	if err != nil {
		log.Println("Could not set up queue consume: ", err)
		return
	}

	c := make(chan EntryWrapper)
	receiver.C = c
	receiver.shutdown = make(chan bool)

	go func() {
		for {
			select {
			case _ = <-receiver.shutdown:
				log.Println("received signal to quit reading amqp, exiting goroutine")
				return
			case msg, ok := <-messages:
				entry := Entry{}

				eWrapper := EntryWrapper{Msg: msg}

				// channel was closed. exit
				if !ok {
					return
				}

				delay, ok := msg.Headers["delayd-delay"].(int64)
				if !ok {
					log.Println("Bad/missing delay. discarding message")
					eWrapper.Done(false)
					continue
				}
				entry.SendAt = time.Now().Add(time.Duration(delay) * time.Millisecond)

				entry.Target, ok = msg.Headers["delayd-target"].(string)
				if !ok {
					log.Println("Bad/missing target. discarding message")
					eWrapper.Done(false)
					continue
				}

				// optional key value for overwrite
				h, ok := msg.Headers["delayd-key"].(string)
				if ok {
					entry.Key = h
				}

				// optional headers that will be relayed
				h, ok = msg.Headers["content-type"].(string)
				if ok {
					entry.ContentType = h
				}

				h, ok = msg.Headers["content-encoding"].(string)
				if ok {
					entry.ContentEncoding = h
				}

				h, ok = msg.Headers["correlation-id"].(string)
				if ok {
					entry.CorrelationID = h
				}

				entry.Body = msg.Body
				eWrapper.Entry = entry

				c <- eWrapper
			}
		}
	}()

	return
}

// AmqpSender sends delayd entries over amqp after their timeout
type AmqpSender struct {
	AmqpBase

	C chan<- EntryWrapper
}

// NewAmqpSender creates a new AmqpSender connected to the given AMQP URL.
func NewAmqpSender(amqpURL string) (sender *AmqpSender, err error) {
	sender = new(AmqpSender)

	err = sender.dial(amqpURL)
	if err != nil {
		return
	}

	return
}

// Send sends a delayd entry over AMQP, using the entry's Target as the publish
// exchange.
func (s AmqpSender) Send(e Entry) (err error) {
	msg := amqp.Publishing{
		DeliveryMode:    amqp.Persistent,
		Timestamp:       time.Now(),
		ContentType:     e.ContentType,
		ContentEncoding: e.ContentEncoding,
		CorrelationId:   e.CorrelationID,
		Body:            e.Body,
	}

	err = s.channel.Publish(e.Target, "", true, false, msg)
	return
}
<|endoftext|>


<commit_before>// Package amqputil provides some abstractions for AMQP for easy the testing.
// The best way to test
package amqputil

type (
	// Option is a map of AMQP configurations
	Option map[string]interface{}

	// Conn is a amqp connection interface
	Conn interface {
		Channel() (Channel, error)
		Dial(amqpuri string) error
		AutoRedial(errChan chan error, cbk func())
		Close() error
	}

	// Channel is a AMQP channel interface
	Channel interface {
		Ack(tag uint64, multiple bool) error
		Nack(tag uint64, multiple bool, requeue bool) error
		Reject(tag uint64, requeue bool) error

		Cancel(consumer string, noWait bool) error
		ExchangeDeclare(name, kind string, opt Option) error
		QueueDeclare(name string, args Option) (Queue, error)
		QueueBind(name, key, exchange string, opt Option) error
		Consume(queue, consumer string, opt Option) (<-chan Delivery, error)
		Publisher
	}

	// Queue is a AMQP queue interface
	Queue interface {
		Name() string
		Messages() int
		Consumers() int
	}

	// Publisher is an interface to something able to publish messages
	Publisher interface {
		Publish(exc, route string, msg []byte) error
	}

	// Delivery is an interface to delivered messages
	Delivery interface {
		Ack(multiple bool) error
		Nack(multiple, request bool) error
		Reject(requeue bool) error

		Body() []byte
		DeliveryTag() uint64
	}
)
<commit_msg>amqp.go: added comments<commit_after>// Package amqputil provides some abstractions for AMQP for easy the testing.
// The best way to test
package amqputil

type (
	// Option is a map of AMQP configurations
	Option map[string]interface{}

	Conn interface {
		Channel() (Channel, error)
		Dial(amqpuri string) error
		AutoRedial(errChan chan error, cbk func())
		Close() error
	}

	// Channel is a AMQP channel interface
	Channel interface {
		Ack(tag uint64, multiple bool) error
		Nack(tag uint64, multiple bool, requeue bool) error
		Reject(tag uint64, requeue bool) error

		Cancel(consumer string, noWait bool) error
		ExchangeDeclare(name, kind string, opt Option) error
		QueueDeclare(name string, args Option) (Queue, error)
		QueueBind(name, key, exchange string, opt Option) error
		Consume(queue, consumer string, opt Option) (<-chan Delivery, error)
		Publisher
	}

	// Queue is a AMQP queue interface
	Queue interface {
		Name() string
		Messages() int
		Consumers() int
	}

	// Publisher is an interface to something able to publish messages
	Publisher interface {
		Publish(exc, route string, msg []byte) error
	}

	// Delivery is an interface to delivered messages
	Delivery interface {
		Ack(multiple bool) error
		Nack(multiple, request bool) error
		Reject(requeue bool) error

		Body() []byte
		DeliveryTag() uint64
	}
)
<|endoftext|>


<commit_before>package datadog

import (
	"fmt"
	"testing"
	"strconv"

	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/terraform"
	"github.com/zorkian/go-datadog-api"
)

func TestAccDatadogGraph_Basic(t *testing.T) {
	var resp datadog.Graph

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckDatadogGraphDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccCheckDatadogGraphConfig_basic,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckDatadogGraphExists("datadog_graph.bar", &resp),
					// TODO: Test request attributes
					resource.TestCheckResourceAttr(
						"datadog_dashboard.foo", "title", "title for dashboard foo"),
					resource.TestCheckResourceAttr(
						"datadog_dashboard.foo", "description", "description for dashboard foo"),
					resource.TestCheckResourceAttr(
						"datadog_graph.bar", "title", "title for graph bar"),
					resource.TestCheckResourceAttr(
						"datadog_graph.bar", "description", "description for graph bar"),
					resource.TestCheckResourceAttr(
						"datadog_graph.bar", "viz", "timeseries"),
				),
			},
		},
	})
}

func testAccCheckDatadogGraphDestroy(s *terraform.State) error {

	for _, rs := range s.RootModule().Resources {
		if rs.Type != "datadog_graph" {
			continue
		}

		dashboard_id, err := getGraphDashboard(s, rs)

		if err != nil {
			return err
		}

		// See if the graph with our title is still in the dashboard
		_, err = getGraphFromDashboard(dashboard_id, rs.Primary.Attributes["title"])

		if err != nil {
			return err
		}

		return fmt.Errorf("Graph still exists")
	}

	return nil
}

func getGraphDashboard(s *terraform.State, rs *terraform.ResourceState) (string, error) {

	for _, d := range rs.Dependencies {

		rs, ok := s.RootModule().Resources[d]

		if !ok {
			return "", fmt.Errorf("Not found: %s", d)
		}

		if rs.Primary.ID == "" {
			return "", fmt.Errorf("No ID is set")
		}

		return rs.Primary.ID, nil
	}

	return "", fmt.Errorf("Failed to find dashboard in state.") // TODO: make this a little nicer?

}

func getGraphFromDashboard(id, title string) (datadog.Graph, error) {
	client := testAccProvider.Meta().(*datadog.Client)

	graph := datadog.Graph{}

	IdInt, int_err := strconv.Atoi(id)
	if int_err == nil {
		return graph, int_err
	}

	dashboard, err := client.GetDashboard(IdInt)

	if err != nil {
		return graph, fmt.Errorf("Error retrieving associated dashboard: %s", err)
	}

	for _, g := range dashboard.Graphs {
		if g.Title != title {
			continue
		}

		return g, nil
	}

	return graph, nil
}

func testAccCheckDatadogGraphExists(n string, GraphResp *datadog.Graph) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		rs, ok := s.RootModule().Resources[n]
		if !ok {
			return fmt.Errorf("Not found: %s", n)
		}

		if rs.Primary.ID == "" {
			return fmt.Errorf("No ID is set")
		}

		dashboard_id, err := getGraphDashboard(s, rs)

		if err != nil {
			return err
		}

		// See if out graph is in the dashboard
		_, err = getGraphFromDashboard(dashboard_id, rs.Primary.Attributes["title"])

		if err != nil {
			return err
		}

	return nil
	}
}

const testAccCheckDatadogGraphConfig_basic = `
resource "datadog_dashboard" "foo" {
	description = "description for dashboard foo"
	title = "title for dashboard foo"
}

resource "datadog_graph" "bar" {
	title = "title for graph bar"
    dashboard_id = "${datadog_dashboard.foo.id}"
    description = "description for graph bar"
    title = "bar"
    viz =  "timeseries"
    request {
        query =  "avg:system.cpu.system{*}"
        stacked = false
    }
    request {
        query =  "avg:system.cpu.user{*}"
        stacked = false
    }
    request {
        query =  "avg:system.mem.user{*}"
        stacked = false
    }

}
`
<commit_msg>Cosmetics.<commit_after>package datadog

import (
	"fmt"
	"testing"
	"strconv"

	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/terraform"
	"github.com/zorkian/go-datadog-api"
)

func TestAccDatadogGraph_Basic(t *testing.T) {
	var resp datadog.Graph

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckDatadogGraphDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccCheckDatadogGraphConfig_basic,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckDatadogGraphExists("datadog_graph.bar", &resp),
					// TODO: Test request attributes
					resource.TestCheckResourceAttr(
						"datadog_dashboard.foo", "title", "title for dashboard foo"),
					resource.TestCheckResourceAttr(
						"datadog_dashboard.foo", "description", "description for dashboard foo"),
					resource.TestCheckResourceAttr(
						"datadog_graph.bar", "title", "title for graph bar"),
					resource.TestCheckResourceAttr(
						"datadog_graph.bar", "description", "description for graph bar"),
					resource.TestCheckResourceAttr(
						"datadog_graph.bar", "viz", "timeseries"),
				),
			},
		},
	})
}

func testAccCheckDatadogGraphDestroy(s *terraform.State) error {

	for _, rs := range s.RootModule().Resources {
		if rs.Type != "datadog_graph" {
			continue
		}

		dashboard_id, err := getGraphDashboard(s, rs)

		if err != nil {
			return err
		}

		// See if the graph with our title is still in the dashboard
		_, err = getGraphFromDashboard(dashboard_id, rs.Primary.Attributes["title"])

		if err != nil {
			return err
		}

		return fmt.Errorf("Graph still exists")
	}

	return nil
}

func getGraphDashboard(s *terraform.State, rs *terraform.ResourceState) (string, error) {

	var id string

	for _, d := range rs.Dependencies {

		rs, ok := s.RootModule().Resources[d]

		if !ok {
			return id, fmt.Errorf("Not found: %s", d)
		}

		if rs.Primary.ID == "" {
			return id, fmt.Errorf("No ID is set")
		}

		return rs.Primary.ID, nil
	}

	return id, fmt.Errorf("Failed to find dashboard in state.")

}

func getGraphFromDashboard(id, title string) (datadog.Graph, error) {
	client := testAccProvider.Meta().(*datadog.Client)

	graph := datadog.Graph{}

	IdInt, int_err := strconv.Atoi(id)
	if int_err == nil {
		return graph, int_err
	}

	dashboard, err := client.GetDashboard(IdInt)

	if err != nil {
		return graph, fmt.Errorf("Error retrieving associated dashboard: %s", err)
	}

	for _, g := range dashboard.Graphs {
		if g.Title != title {
			continue
		}

		return g, nil
	}

	return graph, nil
}

func testAccCheckDatadogGraphExists(n string, GraphResp *datadog.Graph) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		rs, ok := s.RootModule().Resources[n]
		if !ok {
			return fmt.Errorf("Not found: %s", n)
		}

		if rs.Primary.ID == "" {
			return fmt.Errorf("No ID is set")
		}

		dashboard_id, err := getGraphDashboard(s, rs)

		if err != nil {
			return err
		}

		// See if out graph is in the dashboard
		_, err = getGraphFromDashboard(dashboard_id, rs.Primary.Attributes["title"])

		if err != nil {
			return err
		}

	return nil
	}
}

const testAccCheckDatadogGraphConfig_basic = `
resource "datadog_dashboard" "foo" {
	description = "description for dashboard foo"
	title = "title for dashboard foo"
}

resource "datadog_graph" "bar" {
	title = "title for graph bar"
    dashboard_id = "${datadog_dashboard.foo.id}"
    description = "description for graph bar"
    title = "bar"
    viz =  "timeseries"
    request {
        query =  "avg:system.cpu.system{*}"
        stacked = false
    }
    request {
        query =  "avg:system.cpu.user{*}"
        stacked = false
    }
    request {
        query =  "avg:system.mem.user{*}"
        stacked = false
    }

}
`
<|endoftext|>


<commit_before>package lightswarm

import (
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestFadeArgs(t *testing.T) {
	tt := []struct {
		name     string
		fade     Fade
		expected []byte
	}{
		{
			"fade to 255 at 1 step per 1 interval",
			Fade{255, 1, 1},
			[]byte{255, 1, 1},
		},
	}
	for _, tc := range tt {
		t.Run(tc.name, func(t *testing.T) {
			bs := tc.fade.Args()
			assert.Equal(t, tc.expected, bs)
		})
	}
}

func TestFrameAddress(t *testing.T) {
	tt := []struct {
		name    string
		address uint16
		b1      byte
		b2      byte
	}{
		{
			"lowest address (1)",
			1,
			0,
			1,
		},
		{
			"real address (690)",
			690,
			2,
			178,
		},
		{
			"maximum address (65535)",
			65535,
			255,
			255,
		},
	}
	for _, tc := range tt {
		t.Run(tc.name, func(t *testing.T) {
			f := Frame{Addr: tc.address}
			b1, b2 := f.address()
			assert.Equal(t, tc.b1, b1)
			assert.Equal(t, tc.b2, b2)
		})
	}
}

func TestFrameChecksum(t *testing.T) {
	tt := []struct {
		name     string
		bs       []byte
		expected byte
	}{
		{
			"simple bytes",
			[]byte{0, 1, 2, 3, 4},
			4,
		},
		{
			"real world bytes",
			[]byte{2, 178, ON},
			144,
		},
	}
	for _, tc := range tt {
		t.Run(tc.name, func(t *testing.T) {
			f := Frame{}
			checksum := f.checksum(tc.bs)
			assert.Equal(t, tc.expected, checksum)
		})
	}
}

func TestFrameWrap(t *testing.T) {
	tt := []struct {
		name     string
		bs       []byte
		expected []byte
	}{
		{
			"no bytes",
			[]byte{},
			[]byte{END, END},
		},
		{
			"end byte in bytes",
			[]byte{END},
			[]byte{END, ESC, 0xDC, END},
		},
		{
			"esc byte in bytes",
			[]byte{ESC},
			[]byte{END, ESC, 0xDD, END},
		},
		{
			"turn 690 on",
			[]byte{2, 178, ON, 144},
			[]byte{END, 2, 178, ON, 144, END},
		},
		{
			"turn 738 on",
			[]byte{2, 226, ON, 192},
			[]byte{END, 2, 226, ON, ESC, 0xDC, END},
		},
	}
	for _, tc := range tt {
		t.Run(tc.name, func(t *testing.T) {
			f := Frame{}
			frame := f.wrap(tc.bs)
			assert.Equal(t, tc.expected, frame)
		})
	}
}

func TestFrameBytes(t *testing.T) {
	tt := []struct {
		name     string
		frame    Frame
		expected []byte
	}{
		{
			"turn 690 on",
			Frame{690, ON, nil},
			[]byte{END, 2, 178, ON, 144, END},
		},
		{
			"fade 690 to 255 at 1 step per 1 interval",
			Frame{690, FADE_TO_LEVEL, []byte{255, 1, 1}},
			[]byte{END, 2, 178, FADE_TO_LEVEL, 255, 1, 1, 108, END},
		},
	}
	for _, tc := range tt {
		t.Run(tc.name, func(t *testing.T) {
			bs := tc.frame.Bytes()
			assert.Equal(t, tc.expected, bs)
		})
	}
}
<commit_msg>Test for LED on<commit_after>package lightswarm

import (
	"bytes"
	"io/ioutil"
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestFadeArgs(t *testing.T) {
	tt := []struct {
		name     string
		fade     Fade
		expected []byte
	}{
		{
			"fade to 255 at 1 step per 1 interval",
			Fade{255, 1, 1},
			[]byte{255, 1, 1},
		},
	}
	for _, tc := range tt {
		t.Run(tc.name, func(t *testing.T) {
			bs := tc.fade.Args()
			assert.Equal(t, tc.expected, bs)
		})
	}
}

func TestFrameAddress(t *testing.T) {
	tt := []struct {
		name    string
		address uint16
		b1      byte
		b2      byte
	}{
		{
			"lowest address (1)",
			1,
			0,
			1,
		},
		{
			"real address (690)",
			690,
			2,
			178,
		},
		{
			"maximum address (65535)",
			65535,
			255,
			255,
		},
	}
	for _, tc := range tt {
		t.Run(tc.name, func(t *testing.T) {
			f := Frame{Addr: tc.address}
			b1, b2 := f.address()
			assert.Equal(t, tc.b1, b1)
			assert.Equal(t, tc.b2, b2)
		})
	}
}

func TestFrameChecksum(t *testing.T) {
	tt := []struct {
		name     string
		bs       []byte
		expected byte
	}{
		{
			"simple bytes",
			[]byte{0, 1, 2, 3, 4},
			4,
		},
		{
			"real world bytes",
			[]byte{2, 178, ON},
			144,
		},
	}
	for _, tc := range tt {
		t.Run(tc.name, func(t *testing.T) {
			f := Frame{}
			checksum := f.checksum(tc.bs)
			assert.Equal(t, tc.expected, checksum)
		})
	}
}

func TestFrameWrap(t *testing.T) {
	tt := []struct {
		name     string
		bs       []byte
		expected []byte
	}{
		{
			"no bytes",
			[]byte{},
			[]byte{END, END},
		},
		{
			"end byte in bytes",
			[]byte{END},
			[]byte{END, ESC, 0xDC, END},
		},
		{
			"esc byte in bytes",
			[]byte{ESC},
			[]byte{END, ESC, 0xDD, END},
		},
		{
			"turn 690 on",
			[]byte{2, 178, ON, 144},
			[]byte{END, 2, 178, ON, 144, END},
		},
		{
			"turn 738 on",
			[]byte{2, 226, ON, 192},
			[]byte{END, 2, 226, ON, ESC, 0xDC, END},
		},
	}
	for _, tc := range tt {
		t.Run(tc.name, func(t *testing.T) {
			f := Frame{}
			frame := f.wrap(tc.bs)
			assert.Equal(t, tc.expected, frame)
		})
	}
}

func TestFrameBytes(t *testing.T) {
	tt := []struct {
		name     string
		frame    Frame
		expected []byte
	}{
		{
			"turn 690 on",
			Frame{690, ON, nil},
			[]byte{END, 2, 178, ON, 144, END},
		},
		{
			"fade 690 to 255 at 1 step per 1 interval",
			Frame{690, FADE_TO_LEVEL, []byte{255, 1, 1}},
			[]byte{END, 2, 178, FADE_TO_LEVEL, 255, 1, 1, 108, END},
		},
	}
	for _, tc := range tt {
		t.Run(tc.name, func(t *testing.T) {
			bs := tc.frame.Bytes()
			assert.Equal(t, tc.expected, bs)
		})
	}
}

func TestLEDOn(t *testing.T) {
	tt := []struct {
		name     string
		addr     uint16
		buff     *bytes.Buffer
		expected []byte
		n        int
		err      error
	}{
		{
			"turn 690 on",
			690,
			bytes.NewBuffer(nil),
			[]byte{END, 2, 178, ON, 144, END},
			6,
			nil,
		},
	}
	for _, tc := range tt {
		t.Run(tc.name, func(t *testing.T) {
			led := &LED{690, tc.buff}
			n, err := led.On()
			assert.Equal(t, tc.n, n)
			assert.Equal(t, tc.err, err)
			bs, err := ioutil.ReadAll(tc.buff)
			assert.Nil(t, err)
			assert.Equal(t, tc.expected, bs)
		})
	}
}
<|endoftext|>


<commit_before>// Copyright © 2017 Aaron Donovan <amdonov@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package sp

import (
	"bytes"
	"encoding/xml"
	"errors"
	"fmt"
	"io"
	"net/http"
	"os"
	"time"

	"github.com/amdonov/lite-idp/saml"
	log "github.com/sirupsen/logrus"
)

type ArtifactCallback func(w http.ResponseWriter, r *http.Request, state []byte, assertion *saml.Assertion)

func (sp *serviceProvider) ArtifactFunc(callback ArtifactCallback) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		err := r.ParseForm()
		if err != nil {
			log.Error(err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// retrieve the relayState from our cache
		stateID := r.Form.Get("RelayState")
		if stateID == "" {
			log.Info("received a request without RelayState")
			http.Error(w, "identity provider did not return RelayState", http.StatusUnauthorized)
			return
		}
		state, err := sp.stateCache.Get(stateID)
		if err != nil {
			log.Info("RelayState not found in cache")
			http.Error(w, "identity provider did not return RelayState", http.StatusUnauthorized)
			return
		}

		// call the IdP to get the SAML assertion
		artifact := r.Form.Get("SAMLart")

		assertion, err := sp.resolveArtifact(artifact)
		if err != nil {
			http.Error(w, err.Error(), http.StatusUnauthorized)
			return
		}

		// allow the application to write the response
		callback(w, r, state, assertion)
	}
}

func (sp *serviceProvider) resolveArtifact(artifact string) (*saml.Assertion, error) {
	request, err := sp.buildResolveRequest(artifact)
	if err != nil {
		return nil, err
	}
	post, err := http.NewRequest(http.MethodPost, sp.configuration.IDPArtifactEndpoint, request)
	if err != nil {
		return nil, err
	}
	post.Header.Add("Content-Type", "text/xml")
	post.Header.Add("SOAPAction", "http://www.oasis-open.org/committees/security")
	resp, err := sp.client.Do(post)
	if err != nil {
		return nil, err
	}
	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("unexpected status code from artifact resolve request %d", resp.StatusCode)
	}
	defer resp.Body.Close()
	decoder := xml.NewDecoder(resp.Body)
	response := &saml.ArtifactResponseEnvelope{}
	err = decoder.Decode(response)
	if err != nil {
		return nil, err
	}
	assertion := response.Body.ArtifactResponse.Response.Assertion
	if assertion == nil {
		// TODO check the rest of the response for an error
		// Write it out for now until we know what we're looking
		encoder := xml.NewEncoder(os.Stderr)
		encoder.Encode(response)
		return nil, errors.New("check logs assertion was nil")
	}
	return assertion, nil
}

func (sp *serviceProvider) buildResolveRequest(artifact string) (io.Reader, error) {
	resolve := saml.ArtifactResolveEnvelope{
		Body: saml.ArtifactResolveBody{
			ArtifactResolve: saml.ArtifactResolve{
				RequestAbstractType: saml.RequestAbstractType{
					ID:           saml.NewID(),
					IssueInstant: time.Now(),
					Issuer:       sp.configuration.EntityID,
					Version:      "2.0",
				},
				Artifact: artifact,
			},
		},
	}
	signature, err := sp.signer.CreateSignature(resolve.Body.ArtifactResolve)
	if err != nil {
		return nil, err
	}
	resolve.Body.ArtifactResolve.Signature = signature
	var b bytes.Buffer
	encoder := xml.NewEncoder(&b)
	err = encoder.Encode(resolve)
	if err != nil {
		return nil, err
	}
	return bytes.NewReader(b.Bytes()), nil
}
<commit_msg>Moved close above status check<commit_after>// Copyright © 2017 Aaron Donovan <amdonov@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package sp

import (
	"bytes"
	"encoding/xml"
	"errors"
	"fmt"
	"io"
	"net/http"
	"os"
	"time"

	"github.com/amdonov/lite-idp/saml"
	log "github.com/sirupsen/logrus"
)

type ArtifactCallback func(w http.ResponseWriter, r *http.Request, state []byte, assertion *saml.Assertion)

func (sp *serviceProvider) ArtifactFunc(callback ArtifactCallback) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		err := r.ParseForm()
		if err != nil {
			log.Error(err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// retrieve the relayState from our cache
		stateID := r.Form.Get("RelayState")
		if stateID == "" {
			log.Info("received a request without RelayState")
			http.Error(w, "identity provider did not return RelayState", http.StatusUnauthorized)
			return
		}
		state, err := sp.stateCache.Get(stateID)
		if err != nil {
			log.Info("RelayState not found in cache")
			http.Error(w, "identity provider did not return RelayState", http.StatusUnauthorized)
			return
		}

		// call the IdP to get the SAML assertion
		artifact := r.Form.Get("SAMLart")

		assertion, err := sp.resolveArtifact(artifact)
		if err != nil {
			http.Error(w, err.Error(), http.StatusUnauthorized)
			return
		}

		// allow the application to write the response
		callback(w, r, state, assertion)
	}
}

func (sp *serviceProvider) resolveArtifact(artifact string) (*saml.Assertion, error) {
	request, err := sp.buildResolveRequest(artifact)
	if err != nil {
		return nil, err
	}
	post, err := http.NewRequest(http.MethodPost, sp.configuration.IDPArtifactEndpoint, request)
	if err != nil {
		return nil, err
	}
	post.Header.Add("Content-Type", "text/xml")
	post.Header.Add("SOAPAction", "http://www.oasis-open.org/committees/security")
	resp, err := sp.client.Do(post)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("unexpected status code from artifact resolve request %d", resp.StatusCode)
	}
	decoder := xml.NewDecoder(resp.Body)
	response := &saml.ArtifactResponseEnvelope{}
	err = decoder.Decode(response)
	if err != nil {
		return nil, err
	}
	assertion := response.Body.ArtifactResponse.Response.Assertion
	if assertion == nil {
		// TODO check the rest of the response for an error
		// Write it out for now until we know what we're looking
		encoder := xml.NewEncoder(os.Stderr)
		encoder.Encode(response)
		return nil, errors.New("check logs assertion was nil")
	}
	return assertion, nil
}

func (sp *serviceProvider) buildResolveRequest(artifact string) (io.Reader, error) {
	resolve := saml.ArtifactResolveEnvelope{
		Body: saml.ArtifactResolveBody{
			ArtifactResolve: saml.ArtifactResolve{
				RequestAbstractType: saml.RequestAbstractType{
					ID:           saml.NewID(),
					IssueInstant: time.Now(),
					Issuer:       sp.configuration.EntityID,
					Version:      "2.0",
				},
				Artifact: artifact,
			},
		},
	}
	signature, err := sp.signer.CreateSignature(resolve.Body.ArtifactResolve)
	if err != nil {
		return nil, err
	}
	resolve.Body.ArtifactResolve.Signature = signature
	var b bytes.Buffer
	encoder := xml.NewEncoder(&b)
	err = encoder.Encode(resolve)
	if err != nil {
		return nil, err
	}
	return bytes.NewReader(b.Bytes()), nil
}
<|endoftext|>


<commit_before>package macross

import (
	"github.com/insionng/macross/libraries/com"
	"strconv"
)

type (
	Args struct {
		s string
	}
)

func (a *Args) MustInt() int {
	return com.StrTo(a.s).MustInt()
}

func (a *Args) MustInt64() int64 {
	return com.StrTo(a.s).MustInt64()
}

func (a *Args) MustUint8() uint8 {
	return com.StrTo(a.s).MustUint8()
}

func (a *Args) MustUint() uint {
	return uint(com.StrTo(a.s).MustInt64())
}

func (a *Args) Float32() (f float64, e error) {
	f, e = strconv.ParseFloat(a.s, 32)
	return
}

func (a *Args) Float64() (f float64, e error) {
	f, e = strconv.ParseFloat(a.s, 64)
	return
}

func (a *Args) Int() (int, error) {
	return com.StrTo(a.s).Int()
}

func (a *Args) Int64() (int64, error) {
	return com.StrTo(a.s).Int64()
}

func (a *Args) String() string {
	return com.StrTo(a.s).String()
}

func (a *Args) Exist() bool {
	return com.StrTo(a.s).Exist()
}

func (a *Args) ToStr(args ...int) (s string) {
	return com.ToStr(a.s, args...)
}

func (a *Args) ToSnakeCase(str ...string) string {
	var s string
	if len(str) > 0 {
		s = str[0]
	} else {
		if len(a.s) != 0 {
			s = a.s
		}
	}
	return com.ToSnakeCase(s)
}

// Param returns the named parameter value that is found in the URL path matching the current route.
// If the named parameter cannot be found, an empty string will be returned.
func (c *Context) Param(name string) *Args {
	var a = new(Args)
	for i, n := range c.pnames {
		if n == name {
			a.s = c.pvalues[i]
		}
	}
	return a
}

func (c *Context) Form(key ...string) *Args {
	var a = new(Args)
	var k string
	if len(key) > 0 {
		k = key[0]
		a.s = c.FormValue(k)
	}
	return a
}

//Args 先从URL获取参数，如若没有则再尝试从from获取参数
func (c *Context) Args(key ...string) *Args {
	var a = new(Args)
	var k string
	if len(key) > 0 {
		k = key[0]
		if a.s = c.QueryParam(k); len(a.s) == 0 {
			a.s = c.FormValue(k)
		}
	}
	return a
}

func (c *Context) Parameter(i int) (value string) {
	l := len(c.pnames)
	if i < l {
		value = c.pvalues[i]
	}
	return
}

// QueryParam implements `Context#QueryParam` function.
func (c *Context) QueryParam(name string) string {
	return string(c.QueryArgs().Peek(name))
}

// QueryParams implements `Context#QueryParams` function.
func (c *Context) QueryParams() (params map[string][]string) {
	params = make(map[string][]string)
	c.URI().QueryArgs().VisitAll(func(k, v []byte) {
		_, ok := params[string(k)]
		if !ok {
			params[string(k)] = make([]string, 0)
		}
		params[string(k)] = append(params[string(k)], string(v))
	})
	return
}

func (c *Context) QueryString() string {
	return string(c.URI().QueryString())
}
<commit_msg>fixed args<commit_after>package macross

import (
	"github.com/insionng/macross/libraries/com"
	"strconv"
)

type (
	Args struct {
		s string
	}
)

func (a *Args) MustInt() int {
	return com.StrTo(a.s).MustInt()
}

func (a *Args) MustInt64() int64 {
	return com.StrTo(a.s).MustInt64()
}

func (a *Args) MustUint8() uint8 {
	return com.StrTo(a.s).MustUint8()
}

func (a *Args) MustUint() uint {
	return uint(com.StrTo(a.s).MustInt64())
}

func (a *Args) Float32() (f float64, e error) {
	f, e = strconv.ParseFloat(a.s, 32)
	return
}

func (a *Args) Float64() (f float64, e error) {
	f, e = strconv.ParseFloat(a.s, 64)
	return
}

func (a *Args) Int() (int, error) {
	return com.StrTo(a.s).Int()
}

func (a *Args) Int64() (int64, error) {
	return com.StrTo(a.s).Int64()
}

func (a *Args) String() string {
	return com.StrTo(a.s).String()
}

func (a *Args) Exist() bool {
	return com.StrTo(a.s).Exist()
}

func (a *Args) ToStr(args ...int) (s string) {
	return com.ToStr(a.s, args...)
}

func (a *Args) ToSnakeCase(str ...string) string {
	var s string
	if len(str) > 0 {
		s = str[0]
	} else {
		if len(a.s) != 0 {
			s = a.s
		}
	}
	return com.ToSnakeCase(s)
}

// Param returns the named parameter value that is found in the URL path matching the current route.
// If the named parameter cannot be found, an empty string will be returned.
func (c *Context) Param(name string) *Args {
	var a = new(Args)
	for i, n := range c.pnames {
		if n == name {
			a.s = c.pvalues[i]
		}
	}
	return a
}

func (c *Context) Form(key ...string) *Args {
	var a = new(Args)
	var k string
	if len(key) > 0 {
		k = key[0]
		a.s = c.FormValue(k)
	}
	return a
}

//Args 先从URL获取参数，如若没有则再尝试从from获取参数
func (c *Context) Args(key ...string) *Args {
	var a = new(Args)
	var k string
	if len(key) > 0 {
		k = key[0]
		for i, n := range c.pnames {
			if n == k {
				a.s = c.pvalues[i]
			}
		}
		if len(a.s) == 0 {
			a.s = c.FormValue(k)
		}
	}
	return a
}

func (c *Context) Parameter(i int) (value string) {
	l := len(c.pnames)
	if i < l {
		value = c.pvalues[i]
	}
	return
}

// QueryParam implements `Context#QueryParam` function.
func (c *Context) QueryParam(name string) string {
	return string(c.QueryArgs().Peek(name))
}

// QueryParams implements `Context#QueryParams` function.
func (c *Context) QueryParams() (params map[string][]string) {
	params = make(map[string][]string)
	c.URI().QueryArgs().VisitAll(func(k, v []byte) {
		_, ok := params[string(k)]
		if !ok {
			params[string(k)] = make([]string, 0)
		}
		params[string(k)] = append(params[string(k)], string(v))
	})
	return
}

func (c *Context) QueryString() string {
	return string(c.URI().QueryString())
}
<|endoftext|>


<commit_before>// Copyright 2012 Google, Inc. All rights reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree.

package layers

import (
	"code.google.com/p/gopacket"
	"encoding/binary"
	"net"
	"strconv"
)

var (
	// We use two different endpoint types for IPv4 vs IPv6 addresses, so that
	// ordering with endpointA.LessThan(endpointB) sanely groups all IPv4
	// addresses and all IPv6 addresses, such that IPv6 > IPv4 for all addresses.
	EndpointIPv4 = gopacket.RegisterEndpointType(1, gopacket.EndpointTypeMetadata{"IPv4", func(b []byte) string {
		return net.IP(b).String()
	}})
	EndpointIPv6 = gopacket.RegisterEndpointType(2, gopacket.EndpointTypeMetadata{"IPv6", func(b []byte) string {
		return net.IP(b).String()
	}})

	EndpointMAC = gopacket.RegisterEndpointType(3, gopacket.EndpointTypeMetadata{"MAC", func(b []byte) string {
		return net.HardwareAddr(b).String()
	}})
	EndpointTCPPort = gopacket.RegisterEndpointType(4, gopacket.EndpointTypeMetadata{"TCP", func(b []byte) string {
		return strconv.Itoa(int(binary.BigEndian.Uint16(b)))
	}})
	EndpointUDPPort = gopacket.RegisterEndpointType(5, gopacket.EndpointTypeMetadata{"UDP", func(b []byte) string {
		return strconv.Itoa(int(binary.BigEndian.Uint16(b)))
	}})
	EndpointSCTPPort = gopacket.RegisterEndpointType(6, gopacket.EndpointTypeMetadata{"SCTP", func(b []byte) string {
		return strconv.Itoa(int(binary.BigEndian.Uint16(b)))
	}})
	EndpointRUDPPort = gopacket.RegisterEndpointType(7, gopacket.EndpointTypeMetadata{"RUDP", func(b []byte) string {
		return strconv.Itoa(int(b[0]))
	}})
	EndpointUDPLitePort = gopacket.RegisterEndpointType(8, gopacket.EndpointTypeMetadata{"UDPLite", func(b []byte) string {
		return strconv.Itoa(int(binary.BigEndian.Uint16(b)))
	}})
	EndpointPPP = gopacket.RegisterEndpointType(9, gopacket.EndpointTypeMetadata{"PPP", func([]byte) string {
		return "point"
	}})
)

// NewIPEndpoint creates a new IP (v4 or v6) endpoint from a net.IP address.
// It returns gopacket.InvalidEndpoint if the IP address is invalid.
func NewIPEndpoint(a net.IP) gopacket.Endpoint {
	switch len(a) {
	case 4:
		return gopacket.NewEndpoint(EndpointIPv4, []byte(a))
	case 16:
		return gopacket.NewEndpoint(EndpointIPv6, []byte(a))
	}
	return gopacket.InvalidEndpoint
}

// NewMACEndpoint returns a new MAC address endpoint.
func NewMACEndpoint(a net.HardwareAddr) gopacket.Endpoint {
	return gopacket.NewEndpoint(EndpointMAC, []byte(a))
}
func newPortEndpoint(t gopacket.EndpointType, p uint16) gopacket.Endpoint {
	return gopacket.NewEndpoint(t, []byte{byte(p >> 16), byte(p)})
}

// NewTCPPortEndpoint returns an endpoint based on a TCP port.
func NewTCPPortEndpoint(p TCPPort) gopacket.Endpoint {
	return newPortEndpoint(EndpointTCPPort, uint16(p))
}

// NewUDPPortEndpoint returns an endpoint based on a UDP port.
func NewUDPPortEndpoint(p UDPPort) gopacket.Endpoint {
	return newPortEndpoint(EndpointUDPPort, uint16(p))
}

// NewSCTPPortEndpoint returns an endpoint based on a SCTP port.
func NewSCTPPortEndpoint(p SCTPPort) gopacket.Endpoint {
	return newPortEndpoint(EndpointSCTPPort, uint16(p))
}

// NewRUDPPortEndpoint returns an endpoint based on a RUDP port.
func NewRUDPPortEndpoint(p RUDPPort) gopacket.Endpoint {
	return gopacket.NewEndpoint(EndpointRUDPPort, []byte{byte(p)})
}

// NewUDPLitePortEndpoint returns an endpoint based on a UDPLite port.
func NewUDPLitePortEndpoint(p UDPLitePort) gopacket.Endpoint {
	return newPortEndpoint(EndpointUDPLitePort, uint16(p))
}
<commit_msg>Fix port endpoint.<commit_after>// Copyright 2012 Google, Inc. All rights reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree.

package layers

import (
	"code.google.com/p/gopacket"
	"encoding/binary"
	"net"
	"strconv"
)

var (
	// We use two different endpoint types for IPv4 vs IPv6 addresses, so that
	// ordering with endpointA.LessThan(endpointB) sanely groups all IPv4
	// addresses and all IPv6 addresses, such that IPv6 > IPv4 for all addresses.
	EndpointIPv4 = gopacket.RegisterEndpointType(1, gopacket.EndpointTypeMetadata{"IPv4", func(b []byte) string {
		return net.IP(b).String()
	}})
	EndpointIPv6 = gopacket.RegisterEndpointType(2, gopacket.EndpointTypeMetadata{"IPv6", func(b []byte) string {
		return net.IP(b).String()
	}})

	EndpointMAC = gopacket.RegisterEndpointType(3, gopacket.EndpointTypeMetadata{"MAC", func(b []byte) string {
		return net.HardwareAddr(b).String()
	}})
	EndpointTCPPort = gopacket.RegisterEndpointType(4, gopacket.EndpointTypeMetadata{"TCP", func(b []byte) string {
		return strconv.Itoa(int(binary.BigEndian.Uint16(b)))
	}})
	EndpointUDPPort = gopacket.RegisterEndpointType(5, gopacket.EndpointTypeMetadata{"UDP", func(b []byte) string {
		return strconv.Itoa(int(binary.BigEndian.Uint16(b)))
	}})
	EndpointSCTPPort = gopacket.RegisterEndpointType(6, gopacket.EndpointTypeMetadata{"SCTP", func(b []byte) string {
		return strconv.Itoa(int(binary.BigEndian.Uint16(b)))
	}})
	EndpointRUDPPort = gopacket.RegisterEndpointType(7, gopacket.EndpointTypeMetadata{"RUDP", func(b []byte) string {
		return strconv.Itoa(int(b[0]))
	}})
	EndpointUDPLitePort = gopacket.RegisterEndpointType(8, gopacket.EndpointTypeMetadata{"UDPLite", func(b []byte) string {
		return strconv.Itoa(int(binary.BigEndian.Uint16(b)))
	}})
	EndpointPPP = gopacket.RegisterEndpointType(9, gopacket.EndpointTypeMetadata{"PPP", func([]byte) string {
		return "point"
	}})
)

// NewIPEndpoint creates a new IP (v4 or v6) endpoint from a net.IP address.
// It returns gopacket.InvalidEndpoint if the IP address is invalid.
func NewIPEndpoint(a net.IP) gopacket.Endpoint {
	switch len(a) {
	case 4:
		return gopacket.NewEndpoint(EndpointIPv4, []byte(a))
	case 16:
		return gopacket.NewEndpoint(EndpointIPv6, []byte(a))
	}
	return gopacket.InvalidEndpoint
}

// NewMACEndpoint returns a new MAC address endpoint.
func NewMACEndpoint(a net.HardwareAddr) gopacket.Endpoint {
	return gopacket.NewEndpoint(EndpointMAC, []byte(a))
}
func newPortEndpoint(t gopacket.EndpointType, p uint16) gopacket.Endpoint {
	return gopacket.NewEndpoint(t, []byte{byte(p >> 8), byte(p)})
}

// NewTCPPortEndpoint returns an endpoint based on a TCP port.
func NewTCPPortEndpoint(p TCPPort) gopacket.Endpoint {
	return newPortEndpoint(EndpointTCPPort, uint16(p))
}

// NewUDPPortEndpoint returns an endpoint based on a UDP port.
func NewUDPPortEndpoint(p UDPPort) gopacket.Endpoint {
	return newPortEndpoint(EndpointUDPPort, uint16(p))
}

// NewSCTPPortEndpoint returns an endpoint based on a SCTP port.
func NewSCTPPortEndpoint(p SCTPPort) gopacket.Endpoint {
	return newPortEndpoint(EndpointSCTPPort, uint16(p))
}

// NewRUDPPortEndpoint returns an endpoint based on a RUDP port.
func NewRUDPPortEndpoint(p RUDPPort) gopacket.Endpoint {
	return gopacket.NewEndpoint(EndpointRUDPPort, []byte{byte(p)})
}

// NewUDPLitePortEndpoint returns an endpoint based on a UDPLite port.
func NewUDPLitePortEndpoint(p UDPLitePort) gopacket.Endpoint {
	return newPortEndpoint(EndpointUDPLitePort, uint16(p))
}
<|endoftext|>


<commit_before>package main

import (
    "fmt"
	"encoding/json"
    "net/http"
	"io/ioutil"
)

var counter int64
var file []byte
var jsontype jsonobject

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "<form action=\"/Blame Brune\" method=\"POST\">"+
        "<input type=\"submit\" value=\"Blame Brune\">"+
        "</form>")
}

func bruneHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "<form action=\"/Blame Brune\" method=\"POST\">"+
        "<input type=\"submit\" value=\"Blame Brune\">"+
        "</form>")
	fmt.Print(jsontype)
	jsontype.Object.counter++
	data, err := json.Marshal(jsontype)
	err = ioutil.WriteFile("config.json", data, 755)
	if err != nil {
		fmt.Println("Can't write file.")
		return
	}
}

type jsonobject struct {
    Object ObjectType
}

type ObjectType struct {
	counter int64
}

func main() {
	file, e := ioutil.ReadFile("config.json")
    if e != nil {
        fmt.Printf("File error: %v\n", e)
		return
    }
    json.Unmarshal(file, &jsontype)
    fmt.Printf("Brunes counted: %v\n", jsontype)
    fmt.Printf("%s\n", string(file))
    http.HandleFunc("/", handler)
	http.HandleFunc("/Blame Brune", bruneHandler)
    http.ListenAndServe(":8080", nil)
}
<commit_msg>Improve program.<commit_after>package main

import (
    "fmt"
	"encoding/json"
    "net/http"
	"io/ioutil"
)

var file []byte
var jsontype jsonobject

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "%v<form action=\"/Blame Brune\" method=\"POST\">"+
        "<input type=\"submit\" value=\"Blame Brune\">"+
        "</form>", jsontype.Object.Counter)
}

func bruneHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "%v<form action=\"/Blame Brune\" method=\"POST\">"+
        "<input type=\"submit\" value=\"Blame Brune\">"+
        "</form>", jsontype.Object.Counter)
	fmt.Print(jsontype)
	jsontype.Object.Counter++
	data, err := json.Marshal(jsontype)
	err = ioutil.WriteFile("config.json", data, 755)
	if err != nil {
		fmt.Println("Can't write file.")
		return
	}
}

type jsonobject struct {
    Object ObjectType
}

type ObjectType struct {
	Counter int64
}

func main() {
	file, e := ioutil.ReadFile("config.json")
    if e != nil {
        fmt.Printf("File error: %v\n", e)
		return
    }
    json.Unmarshal(file, &jsontype)
    fmt.Printf("Brunes counted: %v", jsontype)
    fmt.Printf("%s\n", string(file))
    http.HandleFunc("/", handler)
	http.HandleFunc("/Blame Brune", bruneHandler)
    http.ListenAndServe(":8099", nil)
	fmt.Print(jsontype)
}
<|endoftext|>


<commit_before><commit_msg>Remove redundant _ in for loop<commit_after><|endoftext|>


<commit_before><commit_msg>Create example02.go<commit_after><|endoftext|>


<commit_before>package kv

import (
	"encoding/json"
	"fmt"
	"strings"

	"github.com/movio/kasper/util"
	"golang.org/x/net/context"
	elastic "gopkg.in/olivere/elastic.v5"
)

const indexSettings = `{
	"index.translog.durability": "async",
	"index.translog.sync_interval": "60s",
	"index.translog.flush_threshold_size: "512m"
}`

const indexMapping = `{
	"_all" : {
		"enabled" : false
	},
	"dynamic_templates": [{
		"no_index": {
			"mapping": {
				"index": "no"
			},
			"match": "*"
		}
	}]
}`

// ElasticsearchKeyValueStore is a key-value storage that uses ElasticSearch.
// In this key-value store, all keys must have the format "<index>/<type>/<_id>".
// For performance reasons, this implementation create indexes with async durability.
// You must call Flush() at appropriate times to ensure Elasticsearch syncs it's translog to disk.
// See: https://www.elastic.co/products/elasticsearch
type ElasticsearchKeyValueStore struct {
	witness         *util.StructPtrWitness
	client          *elastic.Client
	context         context.Context
	existingIndexes []string
}

// NewElasticsearchKeyValueStore creates new ElasticsearchKeyValueStore instance.
// Host must of the format hostname:port.
// StructPtr should be a pointer to struct type that is used
// for serialization and deserialization of store values.
func NewElasticsearchKeyValueStore(host string, structPtr interface{}) *ElasticsearchKeyValueStore {
	url := fmt.Sprintf("http://%s", host)
	client, err := elastic.NewClient(
		elastic.SetURL(url),
		elastic.SetSniff(false), // FIXME: workaround for issues with ES in docker
	)
	if err != nil {
		panic(fmt.Sprintf("Cannot create ElasticSearch Client to '%s': %s", url, err))
	}
	return &ElasticsearchKeyValueStore{
		witness: util.NewStructPtrWitness(structPtr),
		client:  client,
		context: context.Background(),
	}
}

func (s *ElasticsearchKeyValueStore) checkOrCreateIndex(indexName string, indexType string) {
	index := strings.Join([]string{indexName, indexType}, "/")
	for _, existingIndex := range s.existingIndexes {
		if existingIndex == index {
			return
		}
	}
	exists, err := s.client.IndexExists(indexName).Do(s.context)
	if err != nil {
		panic(fmt.Sprintf("Failed to check if index exists: %s", err))
	}
	if !exists {
		_, err = s.client.CreateIndex(indexName).BodyString(indexSettings).Do(s.context)
		if err != nil {
			panic(fmt.Sprintf("Failed to create index: %s", err))
		}
		s.putMapping(indexName, indexType)
	}

	s.existingIndexes = append(s.existingIndexes, index)
}

func (s *ElasticsearchKeyValueStore) putMapping(indexName string, indexType string) {
	resp, err := s.client.PutMapping().Index(indexName).Type(indexType).BodyString(indexMapping).Do(s.context)
	if err != nil {
		panic(fmt.Sprintf("Failed to put mapping for index: %s/%s: %s", indexName, indexType, err))
	}
	if resp == nil {
		panic(fmt.Sprintf("Expected put mapping response; got: %v", resp))
	}
	if !resp.Acknowledged {
		panic(fmt.Sprintf("Expected put mapping ack; got: %v", resp.Acknowledged))
	}
}

// Get gets value by key from store
func (s *ElasticsearchKeyValueStore) Get(key string) (interface{}, error) {
	keyParts := strings.Split(key, "/")
	if len(keyParts) != 3 {
		return nil, fmt.Errorf("invalid key: '%s'", key)
	}
	indexName := keyParts[0]
	indexType := keyParts[1]
	valueID := keyParts[2]

	s.checkOrCreateIndex(indexName, indexType)

	rawValue, err := s.client.Get().
		Index(indexName).
		Type(indexType).
		Id(valueID).
		Do(s.context)

	if fmt.Sprintf("%s", err) == "elastic: Error 404 (Not Found)" {
		return s.witness.Nil(), nil
	}

	if err != nil {
		return s.witness.Nil(), err
	}

	if !rawValue.Found {
		return s.witness.Nil(), nil
	}

	structPtr := s.witness.Allocate()
	err = json.Unmarshal(*rawValue.Source, structPtr)
	if err != nil {
		return s.witness.Nil(), err
	}
	return structPtr, nil
}

// Put updates key in store with serialized value
func (s *ElasticsearchKeyValueStore) Put(key string, structPtr interface{}) error {
	s.witness.Assert(structPtr)
	keyParts := strings.Split(key, "/")
	if len(keyParts) != 3 {
		return fmt.Errorf("invalid key: '%s'", key)
	}
	indexName := keyParts[0]
	indexType := keyParts[1]
	valueID := keyParts[2]

	s.checkOrCreateIndex(indexName, indexType)

	_, err := s.client.Index().
		Index(indexName).
		Type(indexType).
		Id(valueID).
		BodyJson(structPtr).
		Do(s.context)

	return err
}

// Delete removes key from store
func (s *ElasticsearchKeyValueStore) Delete(key string) error {
	keyParts := strings.Split(key, "/")
	if len(keyParts) != 3 {
		return fmt.Errorf("invalid key: '%s'", key)
	}
	indexName := keyParts[0]
	indexType := keyParts[1]
	valueID := keyParts[2]

	s.checkOrCreateIndex(indexName, indexType)

	_, err := s.client.Delete().
		Index(indexName).
		Type(indexType).
		Id(valueID).
		Do(s.context)

	return err
}

// Flush the Elasticsearch translog to disk
func (s* ElasticsearchKeyValueStore) Flush() error {
	_, err := s.client.Flush(s.existingIndexes...).
		WaitIfOngoing(true).
		Do(s.context)
	return err
}
<commit_msg>Fix another JSON error...<commit_after>package kv

import (
	"encoding/json"
	"fmt"
	"strings"

	"github.com/movio/kasper/util"
	"golang.org/x/net/context"
	elastic "gopkg.in/olivere/elastic.v5"
)

const indexSettings = `{
	"index.translog.durability": "async",
	"index.translog.sync_interval": "60s",
	"index.translog.flush_threshold_size": "512m"
}`

const indexMapping = `{
	"_all" : {
		"enabled" : false
	},
	"dynamic_templates": [{
		"no_index": {
			"mapping": {
				"index": "no"
			},
			"match": "*"
		}
	}]
}`

// ElasticsearchKeyValueStore is a key-value storage that uses ElasticSearch.
// In this key-value store, all keys must have the format "<index>/<type>/<_id>".
// For performance reasons, this implementation create indexes with async durability.
// You must call Flush() at appropriate times to ensure Elasticsearch syncs it's translog to disk.
// See: https://www.elastic.co/products/elasticsearch
type ElasticsearchKeyValueStore struct {
	witness         *util.StructPtrWitness
	client          *elastic.Client
	context         context.Context
	existingIndexes []string
}

// NewElasticsearchKeyValueStore creates new ElasticsearchKeyValueStore instance.
// Host must of the format hostname:port.
// StructPtr should be a pointer to struct type that is used
// for serialization and deserialization of store values.
func NewElasticsearchKeyValueStore(host string, structPtr interface{}) *ElasticsearchKeyValueStore {
	url := fmt.Sprintf("http://%s", host)
	client, err := elastic.NewClient(
		elastic.SetURL(url),
		elastic.SetSniff(false), // FIXME: workaround for issues with ES in docker
	)
	if err != nil {
		panic(fmt.Sprintf("Cannot create ElasticSearch Client to '%s': %s", url, err))
	}
	return &ElasticsearchKeyValueStore{
		witness: util.NewStructPtrWitness(structPtr),
		client:  client,
		context: context.Background(),
	}
}

func (s *ElasticsearchKeyValueStore) checkOrCreateIndex(indexName string, indexType string) {
	index := strings.Join([]string{indexName, indexType}, "/")
	for _, existingIndex := range s.existingIndexes {
		if existingIndex == index {
			return
		}
	}
	exists, err := s.client.IndexExists(indexName).Do(s.context)
	if err != nil {
		panic(fmt.Sprintf("Failed to check if index exists: %s", err))
	}
	if !exists {
		_, err = s.client.CreateIndex(indexName).BodyString(indexSettings).Do(s.context)
		if err != nil {
			panic(fmt.Sprintf("Failed to create index: %s", err))
		}
		s.putMapping(indexName, indexType)
	}

	s.existingIndexes = append(s.existingIndexes, index)
}

func (s *ElasticsearchKeyValueStore) putMapping(indexName string, indexType string) {
	resp, err := s.client.PutMapping().Index(indexName).Type(indexType).BodyString(indexMapping).Do(s.context)
	if err != nil {
		panic(fmt.Sprintf("Failed to put mapping for index: %s/%s: %s", indexName, indexType, err))
	}
	if resp == nil {
		panic(fmt.Sprintf("Expected put mapping response; got: %v", resp))
	}
	if !resp.Acknowledged {
		panic(fmt.Sprintf("Expected put mapping ack; got: %v", resp.Acknowledged))
	}
}

// Get gets value by key from store
func (s *ElasticsearchKeyValueStore) Get(key string) (interface{}, error) {
	keyParts := strings.Split(key, "/")
	if len(keyParts) != 3 {
		return nil, fmt.Errorf("invalid key: '%s'", key)
	}
	indexName := keyParts[0]
	indexType := keyParts[1]
	valueID := keyParts[2]

	s.checkOrCreateIndex(indexName, indexType)

	rawValue, err := s.client.Get().
		Index(indexName).
		Type(indexType).
		Id(valueID).
		Do(s.context)

	if fmt.Sprintf("%s", err) == "elastic: Error 404 (Not Found)" {
		return s.witness.Nil(), nil
	}

	if err != nil {
		return s.witness.Nil(), err
	}

	if !rawValue.Found {
		return s.witness.Nil(), nil
	}

	structPtr := s.witness.Allocate()
	err = json.Unmarshal(*rawValue.Source, structPtr)
	if err != nil {
		return s.witness.Nil(), err
	}
	return structPtr, nil
}

// Put updates key in store with serialized value
func (s *ElasticsearchKeyValueStore) Put(key string, structPtr interface{}) error {
	s.witness.Assert(structPtr)
	keyParts := strings.Split(key, "/")
	if len(keyParts) != 3 {
		return fmt.Errorf("invalid key: '%s'", key)
	}
	indexName := keyParts[0]
	indexType := keyParts[1]
	valueID := keyParts[2]

	s.checkOrCreateIndex(indexName, indexType)

	_, err := s.client.Index().
		Index(indexName).
		Type(indexType).
		Id(valueID).
		BodyJson(structPtr).
		Do(s.context)

	return err
}

// Delete removes key from store
func (s *ElasticsearchKeyValueStore) Delete(key string) error {
	keyParts := strings.Split(key, "/")
	if len(keyParts) != 3 {
		return fmt.Errorf("invalid key: '%s'", key)
	}
	indexName := keyParts[0]
	indexType := keyParts[1]
	valueID := keyParts[2]

	s.checkOrCreateIndex(indexName, indexType)

	_, err := s.client.Delete().
		Index(indexName).
		Type(indexType).
		Id(valueID).
		Do(s.context)

	return err
}

// Flush the Elasticsearch translog to disk
func (s* ElasticsearchKeyValueStore) Flush() error {
	_, err := s.client.Flush(s.existingIndexes...).
		WaitIfOngoing(true).
		Do(s.context)
	return err
}
<|endoftext|>


<commit_before>package glfw3

/*
// Choose OpenGL client on 386 and amd64.
#cgo 386 CFLAGS: -D_GLFW_USE_OPENGL
#cgo amd64 CFLAGS: -D_GLFW_USE_OPENGL

// Choose OpenGL ES V2 on arm.
#cgo arm CFLAGS: -D_GLFW_USE_GLESV2

// Windows Build Tags
// ----------------
// GLFW Options:
#cgo windows CFLAGS: -D_GLFW_WIN32 -D_GLFW_WGL

// Linker Options:
#cgo windows LDFLAGS: -lopengl32 -lgdi32

// Darwin Build Tags
// ----------------
// GLFW Options:
#cgo darwin CFLAGS: -D_GLFW_COCOA -D_GLFW_NSGL

// Linker Options:
#cgo darwin LDFLAGS: -framework Cocoa -framework OpenGL -framework IOKit -framework CoreVideo

// Linux Build Tags
// ----------------
// GLFW Options:
#cgo linux,!wayland CFLAGS: -D_GLFW_X11 -D_GLFW_GLX -D_GLFW_HAS_GLXGETPROCADDRESSARB -D_GLFW_HAS_DLOPEN
#cgo linux,wayland CFLAGS: -D_GLFW_WAYLAND -D_GLFW_EGL -D_GLFW_HAS_DLOPEN

// Linker Options:
#cgo linux,!wayland LDFLAGS: -lGL -lX11 -lXrandr -lXxf86vm -lXi -lXcursor -lm
#cgo linux,wayland LDFLAGS: -lGL -lX11 -lXrandr -lXxf86vm -lXi -lXcursor -lm

// FreeBSD Build Tags
// ----------------
// GLFW Options:
#cgo freebsd,!wayland CFLAGS: -D_GLFW_X11 -D_GLFW_GLX -D_GLFW_HAS_GLXGETPROCADDRESSARB -D_GLFW_HAS_DLOPEN
#cgo freebsd,wayland CFLAGS: -D_GLFW_WAYLAND -D_GLFW_EGL -D_GLFW_HAS_DLOPEN

// Linker Options:
#cgo freebsd,!wayland LDFLAGS: -lGL -lX11 -lXrandr -lXxf86vm -lXi -lXcursor -lm
#cgo freebsd,wayland LDFLAGS: -lGL -lX11 -lXrandr -lXxf86vm -lXi -lXcursor -lm
*/
import "C"
<commit_msg>Fix build on OS X Mavericks (10.9.1); Add -Wno-deprecated-declarations<commit_after>package glfw3

/*
// Choose OpenGL client on 386 and amd64.
#cgo 386 CFLAGS: -D_GLFW_USE_OPENGL
#cgo amd64 CFLAGS: -D_GLFW_USE_OPENGL

// Choose OpenGL ES V2 on arm.
#cgo arm CFLAGS: -D_GLFW_USE_GLESV2

// Windows Build Tags
// ----------------
// GLFW Options:
#cgo windows CFLAGS: -D_GLFW_WIN32 -D_GLFW_WGL

// Linker Options:
#cgo windows LDFLAGS: -lopengl32 -lgdi32

// Darwin Build Tags
// ----------------
// GLFW Options:
#cgo darwin CFLAGS: -D_GLFW_COCOA -D_GLFW_NSGL -Wno-deprecated-declarations

// Linker Options:
#cgo darwin LDFLAGS: -framework Cocoa -framework OpenGL -framework IOKit -framework CoreVideo

// Linux Build Tags
// ----------------
// GLFW Options:
#cgo linux,!wayland CFLAGS: -D_GLFW_X11 -D_GLFW_GLX -D_GLFW_HAS_GLXGETPROCADDRESSARB -D_GLFW_HAS_DLOPEN
#cgo linux,wayland CFLAGS: -D_GLFW_WAYLAND -D_GLFW_EGL -D_GLFW_HAS_DLOPEN

// Linker Options:
#cgo linux,!wayland LDFLAGS: -lGL -lX11 -lXrandr -lXxf86vm -lXi -lXcursor -lm
#cgo linux,wayland LDFLAGS: -lGL -lX11 -lXrandr -lXxf86vm -lXi -lXcursor -lm

// FreeBSD Build Tags
// ----------------
// GLFW Options:
#cgo freebsd,!wayland CFLAGS: -D_GLFW_X11 -D_GLFW_GLX -D_GLFW_HAS_GLXGETPROCADDRESSARB -D_GLFW_HAS_DLOPEN
#cgo freebsd,wayland CFLAGS: -D_GLFW_WAYLAND -D_GLFW_EGL -D_GLFW_HAS_DLOPEN

// Linker Options:
#cgo freebsd,!wayland LDFLAGS: -lGL -lX11 -lXrandr -lXxf86vm -lXi -lXcursor -lm
#cgo freebsd,wayland LDFLAGS: -lGL -lX11 -lXrandr -lXxf86vm -lXi -lXcursor -lm
*/
import "C"
<|endoftext|>