<commit_before>package models_test

import (
	"encoding/json"
	"time"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	. "github.com/cloudfoundry-incubator/runtime-schema/models"
)

var _ = Describe("ExecutorAction", func() {
	Describe("With an invalid action", func() {
		It("should fail to marshal", func() {
			invalidAction := []string{"butts", "from", "mars"}
			payload, err := json.Marshal(&ExecutorAction{Action: invalidAction})
			Ω(payload).Should(BeZero())
			Ω(err.(*json.MarshalerError).Err).Should(Equal(InvalidActionConversion))
		})

		It("should fail to unmarshal", func() {
			var unmarshalledAction *ExecutorAction
			actionPayload := `{"action":"buttz","args":{"from":"space"}}`
			err := json.Unmarshal([]byte(actionPayload), &unmarshalledAction)
			Ω(err).Should(Equal(InvalidActionConversion))
		})
	})

	itSerializesAndDeserializes := func(actionPayload string, action interface{}) {
		Describe("Converting to JSON", func() {
			It("creates a json representation of the object", func() {
				marshalledAction := action

				json, err := json.Marshal(&marshalledAction)
				Ω(err).Should(BeNil())
				Ω(json).Should(MatchJSON(actionPayload))
			})
		})

		Describe("Converting from JSON", func() {
			It("constructs an object from the json string", func() {
				var unmarshalledAction *ExecutorAction
				err := json.Unmarshal([]byte(actionPayload), &unmarshalledAction)
				Ω(err).Should(BeNil())
				Ω(*unmarshalledAction).Should(Equal(action))
			})
		})
	}

	Describe("Download", func() {
		itSerializesAndDeserializes(
			`{
				"action": "download",
				"args": {
					"from": "web_location",
					"name": "ruby buildback",
					"to": "local_location",
					"extract": true
				}
			}`,
			ExecutorAction{
				Action: DownloadAction{
					Name:    "ruby buildback",
					From:    "web_location",
					To:      "local_location",
					Extract: true,
				},
			},
		)
	})

	Describe("Upload", func() {
		itSerializesAndDeserializes(
			`{
				"action": "upload",
				"args": {
					"name": "app bits",
					"from": "local_location",
					"to": "web_location",
					"compress": true
				}
			}`,
			ExecutorAction{
				Action: UploadAction{
					Name:     "app bits",
					From:     "local_location",
					To:       "web_location",
					Compress: true,
				},
			},
		)
	})

	Describe("Run", func() {
		itSerializesAndDeserializes(
			`{
				"action": "run",
				"args": {
					"name": "staging",
					"script": "rm -rf /",
					"timeout": 10000000,
					"env": [
						["FOO", "1"],
						["BAR", "2"]
					]
				}
			}`,
			ExecutorAction{
				Action: RunAction{
					Name:    "staging",
					Script:  "rm -rf /",
					Timeout: 10 * time.Millisecond,
					Env: [][]string{
						{"FOO", "1"},
						{"BAR", "2"},
					},
				},
			},
		)
	})

	Describe("FetchResult", func() {
		itSerializesAndDeserializes(
			`{
				"action": "fetch_result",
				"args": {
					"name": "fetching temp file",
					"file": "/tmp/foo"
				}
			}`,
			ExecutorAction{
				Action: FetchResultAction{
					Name: "fetching temp file",
					File: "/tmp/foo",
				},
			},
		)
	})

	Describe("Try", func() {
		itSerializesAndDeserializes(
			`{
				"action": "try",
				"args": {
					"action": {
						"action": "run",
						"args": {
							"script": "rm -rf /",
							"timeout": 10000000,
							"env": [
								["FOO", "1"],
								["BAR", "2"]
							]
						}
					}
				}
			}`,
			ExecutorAction{
				Action: TryAction{
					Action: ExecutorAction{
						Action: RunAction{
							Script:  "rm -rf /",
							Timeout: 10 * time.Millisecond,
							Env: [][]string{
								{"FOO", "1"},
								{"BAR", "2"},
							},
						},
					},
				},
			},
		)
	})
})
<commit_msg>fix jsonifying tests<commit_after>package models_test

import (
	"encoding/json"
	"time"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	. "github.com/cloudfoundry-incubator/runtime-schema/models"
)

var _ = Describe("ExecutorAction", func() {
	Describe("With an invalid action", func() {
		It("should fail to marshal", func() {
			invalidAction := []string{"butts", "from", "mars"}
			payload, err := json.Marshal(&ExecutorAction{Action: invalidAction})
			Ω(payload).Should(BeZero())
			Ω(err.(*json.MarshalerError).Err).Should(Equal(InvalidActionConversion))
		})

		It("should fail to unmarshal", func() {
			var unmarshalledAction *ExecutorAction
			actionPayload := `{"action":"buttz","args":{"from":"space"}}`
			err := json.Unmarshal([]byte(actionPayload), &unmarshalledAction)
			Ω(err).Should(Equal(InvalidActionConversion))
		})
	})

	itSerializesAndDeserializes := func(actionPayload string, action interface{}) {
		Describe("Converting to JSON", func() {
			It("creates a json representation of the object", func() {
				marshalledAction := action

				json, err := json.Marshal(&marshalledAction)
				Ω(err).Should(BeNil())
				Ω(json).Should(MatchJSON(actionPayload))
			})
		})

		Describe("Converting from JSON", func() {
			It("constructs an object from the json string", func() {
				var unmarshalledAction *ExecutorAction
				err := json.Unmarshal([]byte(actionPayload), &unmarshalledAction)
				Ω(err).Should(BeNil())
				Ω(*unmarshalledAction).Should(Equal(action))
			})
		})
	}

	Describe("Download", func() {
		itSerializesAndDeserializes(
			`{
				"action": "download",
				"args": {
					"from": "web_location",
					"name": "some asset",
					"to": "local_location",
					"extract": true
				}
			}`,
			ExecutorAction{
				Action: DownloadAction{
					Name:    "some asset",
					From:    "web_location",
					To:      "local_location",
					Extract: true,
				},
			},
		)
	})

	Describe("Upload", func() {
		itSerializesAndDeserializes(
			`{
				"action": "upload",
				"args": {
					"name": "some output",
					"from": "local_location",
					"to": "web_location",
					"compress": true
				}
			}`,
			ExecutorAction{
				Action: UploadAction{
					Name:     "some output",
					From:     "local_location",
					To:       "web_location",
					Compress: true,
				},
			},
		)
	})

	Describe("Run", func() {
		itSerializesAndDeserializes(
			`{
				"action": "run",
				"args": {
					"name": "nuke",
					"script": "rm -rf /",
					"timeout": 10000000,
					"env": [
						["FOO", "1"],
						["BAR", "2"]
					]
				}
			}`,
			ExecutorAction{
				Action: RunAction{
					Name:    "nuke",
					Script:  "rm -rf /",
					Timeout: 10 * time.Millisecond,
					Env: [][]string{
						{"FOO", "1"},
						{"BAR", "2"},
					},
				},
			},
		)
	})

	Describe("FetchResult", func() {
		itSerializesAndDeserializes(
			`{
				"action": "fetch_result",
				"args": {
					"name": "fetching temp file",
					"file": "/tmp/foo"
				}
			}`,
			ExecutorAction{
				Action: FetchResultAction{
					Name: "fetching temp file",
					File: "/tmp/foo",
				},
			},
		)
	})

	Describe("Try", func() {
		itSerializesAndDeserializes(
			`{
				"action": "try",
				"args": {
					"action": {
						"action": "run",
						"args": {
							"name": "nuke",
							"script": "rm -rf /",
							"timeout": 10000000,
							"env": [
								["FOO", "1"],
								["BAR", "2"]
							]
						}
					}
				}
			}`,
			ExecutorAction{
				Action: TryAction{
					Action: ExecutorAction{
						Action: RunAction{
							Name:    "nuke",
							Script:  "rm -rf /",
							Timeout: 10 * time.Millisecond,
							Env: [][]string{
								{"FOO", "1"},
								{"BAR", "2"},
							},
						},
					},
				},
			},
		)
	})
})
<|endoftext|>


<commit_before>package tailer

import (
	"errors"
	"os"
	"strings"
	"time"

	"github.com/apcera/nats"
	"github.com/golang/glog"
)

// NatsPublisher will Publish messages via nats
type NatsPublisher struct {
	URL   string
	topic string
	nc    *nats.Conn
}

var (
	ErrNatsConnectionClosed    = nats.ErrConnectionClosed
	ErrNatsExceedMaxReconnects = errors.New("pubnats: exceed max reconnects")
)

// NewNatsPublisher return a Publisher using nats
func NewNatsPublisher(url string) (Publisher, error) {
	opts := nats.DefaultOptions
	opts.Servers = strings.Split(url, ",")
	opts.MaxReconnect = 10
	opts.ReconnectWait = (1 * time.Second)

	nc, err := opts.Connect()
	if err != nil {
		glog.Errorf("error to connect to %s: %v", url, err)
		return nil, err
	}
	nc.Opts.DisconnectedCB = func(nc *nats.Conn) {
		glog.Warningf("Got disconnected! Reconnects: %d\n", nc.Reconnects)
	}
	nc.Opts.ReconnectedCB = func(nc *nats.Conn) {
		glog.Warningf("Got reconnected to %v!\n", nc.ConnectedUrl())
	}
	hostname := os.Getenv("HOSTNAME")
	if hostname == "" {
		hostname, _ = os.Hostname()
	}
	return &NatsPublisher{
		URL:   url,
		topic: strings.Replace(hostname, "-", ".", -1),
		nc:    nc,
	}, nil
}

// SetTopic sets the publish topic
func (n *NatsPublisher) SetTopic(topic string) {
	n.topic = topic
}

func (n *NatsPublisher) isExceedMaxReconnects() bool {
	if uint64(n.nc.Opts.MaxReconnect) < n.nc.Reconnects {
		return true
	}
	return false
}

// Publish publish the message to server
func (n *NatsPublisher) Publish(msg []byte) error {
	glog.V(2).Infof("publish %s with topic %s", msg, n.topic)
	err := n.nc.Publish(n.topic, msg)
	if err != nil {
		if n.isExceedMaxReconnects() {
			return ErrNatsExceedMaxReconnects
		}
		return err
	}
	return nil
}

// Close close the channel
func (n *NatsPublisher) Close() {
	n.nc.Close()
}
<commit_msg>add closedcb<commit_after>package tailer

import (
	"errors"
	"os"
	"strings"
	"time"

	"github.com/apcera/nats"
	"github.com/golang/glog"
)

// NatsPublisher will Publish messages via nats
type NatsPublisher struct {
	URL   string
	topic string
	nc    *nats.Conn
}

var (
	ErrNatsConnectionClosed    = nats.ErrConnectionClosed
	ErrNatsExceedMaxReconnects = errors.New("pubnats: exceed max reconnects")
)

// NewNatsPublisher return a Publisher using nats
func NewNatsPublisher(url string) (Publisher, error) {
	opts := nats.DefaultOptions
	opts.Servers = strings.Split(url, ",")
	opts.MaxReconnect = 10
	opts.ReconnectWait = (1 * time.Second)

	nc, err := opts.Connect()
	if err != nil {
		glog.Errorf("error to connect to %s: %v", url, err)
		return nil, err
	}
	nc.Opts.DisconnectedCB = func(nc *nats.Conn) {
		glog.Warningf("Got disconnected! Reconnects: %d", nc.Reconnects)
	}
	nc.Opts.ReconnectedCB = func(nc *nats.Conn) {
		glog.Warningf("Got reconnected to %v!", nc.ConnectedUrl())
	}
	nc.Opts.ClosedCB = func(_ *nats.Conn) {
		glog.Fatal("Got closed")
	}
	hostname := os.Getenv("HOSTNAME")
	if hostname == "" {
		hostname, _ = os.Hostname()
	}
	return &NatsPublisher{
		URL:   url,
		topic: strings.Replace(hostname, "-", ".", -1),
		nc:    nc,
	}, nil
}

// SetTopic sets the publish topic
func (n *NatsPublisher) SetTopic(topic string) {
	n.topic = topic
}

func (n *NatsPublisher) isExceedMaxReconnects() bool {
	if uint64(n.nc.Opts.MaxReconnect) < n.nc.Reconnects {
		return true
	}
	return false
}

// Publish publish the message to server
func (n *NatsPublisher) Publish(msg []byte) error {
	glog.V(2).Infof("publish %s with topic %s", msg, n.topic)
	err := n.nc.Publish(n.topic, msg)
	if err != nil {
		if n.isExceedMaxReconnects() {
			return ErrNatsExceedMaxReconnects
		}
		return err
	}
	return nil
}

// Close close the channel
func (n *NatsPublisher) Close() {
	n.nc.Close()
}
<|endoftext|>


<commit_before>package decorators

import (
	"fmt"
	"os/exec"
	"strings"

	"github.com/antham/chyle/chyle/convh"
)

type shellConfig map[string]struct {
	COMMAND string
	ORIGKEY string
	DESTKEY string
}

// shell pipes a shell command on field content and dump the
// result into a new field
type shell struct {
	COMMAND string
	ORIGKEY string
	DESTKEY string
}

// Decorate executes shell command on field content
func (s shell) Decorate(commitMap *map[string]interface{}) (*map[string]interface{}, error) {
	var tmp interface{}
	var value string
	var result []byte
	var ok bool
	var err error

	(*commitMap)[s.DESTKEY] = nil

	if tmp, ok = (*commitMap)[s.ORIGKEY]; !ok {
		return commitMap, nil
	}

	if value, err = convh.ConvertToString(tmp); err != nil {
		return commitMap, nil
	}

	command := fmt.Sprintf(`echo "%s"|%s`, strings.Replace(value, `"`, `\"`, -1), s.COMMAND)

	/* #nosec */
	if result, err = exec.Command("sh", "-c", command).Output(); err != nil {
		return commitMap, fmt.Errorf("%s : command failed", command)
	}

	(*commitMap)[s.DESTKEY] = string(result[:len(result)-1])

	return commitMap, nil
}

// buildShell create a new shell decorator
func buildShell(configs shellConfig) []Decorater {
	results := []Decorater{}

	for _, config := range configs {
		results = append(results, shell{config.COMMAND, config.ORIGKEY, config.DESTKEY})
	}

	return results
}
<commit_msg>fix(chyle/decorators) : fix warning<commit_after>package decorators

import (
	"fmt"
	"os/exec"
	"strings"

	"github.com/antham/chyle/chyle/convh"
)

type shellConfig map[string]struct {
	COMMAND string
	ORIGKEY string
	DESTKEY string
}

// shell pipes a shell command on field content and dump the
// result into a new field
type shell struct {
	COMMAND string
	ORIGKEY string
	DESTKEY string
}

// Decorate executes shell command on field content
func (s shell) Decorate(commitMap *map[string]interface{}) (*map[string]interface{}, error) {
	var tmp interface{}
	var value string
	var result []byte
	var ok bool
	var err error

	(*commitMap)[s.DESTKEY] = nil

	if tmp, ok = (*commitMap)[s.ORIGKEY]; !ok {
		return commitMap, nil
	}

	if value, err = convh.ConvertToString(tmp); err != nil {
		return commitMap, nil
	}

	command := fmt.Sprintf(`echo "%s"|%s`, strings.Replace(value, `"`, `\"`, -1), s.COMMAND)

	/* #nosec */
	if result, err = exec.Command("sh", "-c", command).Output(); err != nil {
		return commitMap, fmt.Errorf("%s : command failed", command)
	}

	(*commitMap)[s.DESTKEY] = string(result[:len(result)-1])

	return commitMap, nil
}

// buildShell create a new shell decorator
func buildShell(configs shellConfig) []Decorater {
	results := []Decorater{}

	for _, config := range configs {
		results = append(results, shell(config))
	}

	return results
}
<|endoftext|>


<commit_before>package main

import (
	"math/rand"

	"github.com/btittelbach/go-bbhw"

	"bytes"
	"container/ring"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"math"
	"sort"
	"strings"
	"time"
)

// PWM library functions:
// SetPolarity(p bool)
// SetPWMFreqDuty(freq_hz, fraction float64)
// GetPWMFreqDuty() (freq_hz, fraction float64)
// SetDuty(fraction float64)
// SetPWM(period, duty time.Duration)
// GetPWM() (period, duty time.Duration)
// DisablePWM()

const (
	slotsPath = "/sys/devices/bone_capemgr.9/slots"
	pwmPath   = "/sys/devices/ocp.3/pwm_test_P9_14.16/"
	ainPath   = "/sys/devices/ocp.3/44e0d000.tscadc/tiadc/iio:device0/in_voltage4_raw"
	// Using sysfs for PWM control
	pwmDTO        = "am33xx_pwm"
	pwmP9_14      = "bone_pwm_P9_14"
	pwmP9_16      = "bone_pwm_P9_16"
	pwmP9_21      = "bone_pwm_P9_21"
	pwmP9_22      = "bone_pwm_P9_22"
	pwmPeriod     = 500000 * time.Nanosecond
	pwmResolution = 10 // smallest detectable unit
	// Though analog input starts at zero, lowest value to trigger lights is 30.
	// Values below 30 are dead zone on potentiometers, so we pad the bottom values.
	ainLevels       = 4096 // 0 - 4095
	ainMinPad       = 25
	clockDividerMin = 1
	clockDividerMax = 65534
	sampleAvgMin    = 1
	// Limit overall maximum current draw to 1.5 amps.
	// 500K ns * 1.5 amps / 0.7 amps =
	maxLEDCurrent   = 700  // enforced by resistors on light fixture
	maxTotalCurrent = 1400 // previously determined to not overheat fixture
	maxTotalDuty    = pwmPeriod * maxTotalCurrent / maxLEDCurrent
	// auto mode
	// autoLoop controls when the aout offset is changed
	autoLoopMax    = 400 // we add min pad to get minpad to max+minpad
	autoLoopMinPad = 100
	autoLoopAdjust = 5 // frequency of change to auto loop max
	// autoOffset controls by how much aout is adjusted
	autoOffsetDelta = 2
	autoOffsetMax   = 400 // outer bounds +/-
)

var (
	// auto mode
	autoMode bool // auto mode continuously varies light intensity
)

// translate command line options to ADC constants
var sampleAvgMap = map[int]byte{
	1:  ADC_AVG_1,
	2:  ADC_AVG_2,
	4:  ADC_AVG_4,
	8:  ADC_AVG_8,
	16: ADC_AVG_16,
}

// flags
var (
	debug      = flag.Bool("debug", false, "log debug messages")
	sleep      = flag.String("sleep", "0ms", "duration (string) between updates (default 0ms)")
	windowSize = flag.Int("window", 100, "size of averaging window (default 100)")
	// program clock divider to actual value - 1, i.e., default register value 0
	clockDivider = flag.Int("divider", clockDividerMin, "ADC clock divider (default 1; max 65534)")
	sampleAvg    = flag.Int("average", sampleAvgMin, "ADC sample averaging (default 1; possible values 1, 2, 4, 8, 16)")
)

// calcMedian add aout to existing values to calculate median
func calcMedian(window *ring.Ring, aout int) float64 {
	var counts = make([]float64, 0, *windowSize)
	count := func(v interface{}) {
		counts = append(counts, v.(float64))
	}
	window.Value = float64(aout)
	window.Do(count)
	sort.Float64s(counts)
	return counts[*windowSize/2]
}

func calcDuty(aout float64) time.Duration {
	// theoretical max is 500000 but avoid hitting
	// type Duration int64 as number of nanoseconds
	return time.Duration(math.Min(.03*math.Pow(aout, 2)+ainMinPad, 499990))
}

func normalize(duties *[]time.Duration, duty time.Duration) time.Duration {
	var sum time.Duration
	for _, d := range *duties {
		sum += d
	}
	// only normalize if needed
	if sum > maxTotalDuty {
		return maxTotalDuty * duty / sum
	}
	return duty
}

// set duty based on median calculation
func setDuty(pwm *bbhw.PWMLine, window *ring.Ring, aout int, step byte, duties *[]time.Duration, msgs *[]string) *ring.Ring {
	newAout := calcMedian(window, aout)
	newDuty := calcDuty(newAout)
	normalDuty := normalize(duties, newDuty)
	// we save raw values for normalization calcs but set pwm to normalized duty cycle
	if newDuty != (*duties)[step] {
		(*duties)[step] = newDuty
		pwm.SetPWM(pwmPeriod, normalDuty)
	}
	if *debug {
		(*msgs)[step] = fmt.Sprintf("%s   aout %4d  duty %9s", (*msgs)[step], int(newAout), normalDuty)
	}
	return window.Next()
}

func initWindow() *ring.Ring {
	w := ring.New(*windowSize)
	for i := 0; i < *windowSize; i++ {
		w.Value = float64(0)
		w = w.Next()
	}
	return w
}

func addDTOIfNotExists(dto string) {
	log.Println("looking for slots file")
	slotsFileName, err := bbhw.FindSlotsFile()
	if err != nil {
		log.Fatalln(err)
	}
	log.Println("found slots file", slotsFileName)
	time.Sleep(100 * time.Millisecond)
	log.Println("reading slots file")
	slots, err := ioutil.ReadFile(slotsFileName)
	if err != nil {
		log.Fatalln(err)
	}
	if bytes.Contains(slots, []byte(dto)) {
		log.Println("slots file already contains overlay", dto)
		return
	}
	log.Println("adding DTO", dto)
	if err := bbhw.AddDeviceTreeOverlay(dto); err != nil {
		log.Fatalln(err)
	}
	time.Sleep(100 * time.Millisecond)
}

func newPWM(pwmPin string) *bbhw.PWMLine {
	addDTOIfNotExists("bone_pwm_" + pwmPin)
	pwm, err := bbhw.NewBBBPWM(pwmPin)
	if err != nil {
		log.Fatalln(err)
	}
	pwm.SetPolarity(true)
	return pwm
}

type LED struct {
	pwm *bbhw.PWMLine
	win *ring.Ring
	// auto mode
	autoLoop        int // current loop number
	autoLoopMax     int // number of loops between changes to aout offset
	autoOffset      int // offset to aout in auto mode
	autoOffsetDelta int // direction to change aout offset
}

// Incoming aout always reflects the current pot setting. What varies
// over time is the autoOffset, which starts out at zero and always
// remains within +/-autoOffsetMax.
func (led *LED) autoAdjust() {
	// increment/decrement the offset
	led.autoLoop++
	if led.autoLoop > led.autoLoopMax {
		led.autoOffset += led.autoOffsetDelta
		led.autoLoop = 0
		// switch offset direction if led hit a boundary
		if led.autoOffset >= autoOffsetMax || led.autoOffset <= -autoOffsetMax {
			led.autoOffsetDelta = -led.autoOffsetDelta
		}
		// every so often change size of auto loop to change the change
		if rand.Intn(autoLoopAdjust) == 0 {
			led.autoLoopMax = randomAutoLoopMax()
		}
	}
}

func initPWMs() map[byte]*LED {
	// do not remove pwm; will crash BBB
	addDTOIfNotExists(pwmDTO)
	pwm14 := newPWM("P9_14") // green
	pwm16 := newPWM("P9_21") // red
	pwm21 := newPWM("P9_16") // white
	pwm22 := newPWM("P9_22") // blue

	// map ADC step channels to PWM pins
	// adjusted LEDs to mirror RGBW on my potentiometer test board
	LEDMap := map[byte]*LED{
		0: &LED{
			pwm:             pwm21,
			win:             initWindow(),
			autoLoopMax:     randomAutoLoopMax(),
			autoOffsetDelta: randomAutoOffsetDelta(),
		},
		1: &LED{
			pwm:             pwm14,
			win:             initWindow(),
			autoLoopMax:     randomAutoLoopMax(),
			autoOffsetDelta: randomAutoOffsetDelta(),
		},
		2: &LED{
			pwm:             pwm22,
			win:             initWindow(),
			autoLoopMax:     randomAutoLoopMax(),
			autoOffsetDelta: randomAutoOffsetDelta(),
		},
		3: &LED{
			pwm:             pwm16,
			win:             initWindow(),
			autoLoopMax:     randomAutoLoopMax(),
			autoOffsetDelta: randomAutoOffsetDelta(),
		},
	}
	return LEDMap
}

func randomAutoLoopMax() int {
	return rand.Intn(autoLoopMax) + autoLoopMinPad
}

func randomAutoOffsetDelta() int {
	if rand.Intn(2) == 0 {
		return autoOffsetDelta
	}
	return -autoOffsetDelta
}

func main() {
	rand.Seed(time.Now().UnixNano())
	var sleepDuration time.Duration
	var err error
	flag.Parse()
	if sleepDuration, err = time.ParseDuration(*sleep); err != nil {
		log.Fatal("could not interpret sleep duration '%v'", *sleep)
	}
	if (*clockDivider < clockDividerMin) || (*clockDivider > clockDividerMax) {
		log.Fatalf("illegal ADC clock divider: must be %v to %v", clockDividerMin, clockDividerMax)
	}

	LEDMap := initPWMs()

	ADCInit(byte(*clockDivider-1), sampleAvgMap[*sampleAvg])
	defer ADCDisable()

	// setup a data structure to map steps to pins and pwms
	// windows to average the analog input values
	var led *LED
	// for efficiency, though it seems to make no difference to cpu%
	duties := make([]time.Duration, 4)
	// for debug logging
	msgs := make([]string, 4) // 4 LED colors max

	autoMode = true
	for {
		if sleepDuration > 0 {
			time.Sleep(sleepDuration)
		}

		for step, aout := range ReadAnalog(P9_37, P9_38, P9_39, P9_40) {
			if *debug {
				msgs[step] = fmt.Sprintf("Step %d:  aout %4d", step, aout)
			}
			led = LEDMap[step]
			if autoMode && aout > ainMinPad {
				led.autoAdjust()
				aout += led.autoOffset
				if aout < 0 {
					aout = 0
				}
			}
			led.win = setDuty(led.pwm, led.win, aout, step, &duties, &msgs)
		}
		if *debug {
			fmt.Println(strings.Join(msgs, "   "))
		}
	}
}
<commit_msg>Add automode activation via pots<commit_after>package main

import (
	"math/rand"

	"github.com/btittelbach/go-bbhw"

	"bytes"
	"container/ring"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"math"
	"sort"
	"strings"
	"time"
)

// PWM library functions:
// SetPolarity(p bool)
// SetPWMFreqDuty(freq_hz, fraction float64)
// GetPWMFreqDuty() (freq_hz, fraction float64)
// SetDuty(fraction float64)
// SetPWM(period, duty time.Duration)
// GetPWM() (period, duty time.Duration)
// DisablePWM()

const (
	slotsPath = "/sys/devices/bone_capemgr.9/slots"
	pwmPath   = "/sys/devices/ocp.3/pwm_test_P9_14.16/"
	ainPath   = "/sys/devices/ocp.3/44e0d000.tscadc/tiadc/iio:device0/in_voltage4_raw"
	// Using sysfs for PWM control
	pwmDTO        = "am33xx_pwm"
	pwmP9_14      = "bone_pwm_P9_14"
	pwmP9_16      = "bone_pwm_P9_16"
	pwmP9_21      = "bone_pwm_P9_21"
	pwmP9_22      = "bone_pwm_P9_22"
	pwmPeriod     = 500000 * time.Nanosecond
	pwmResolution = 10 // smallest detectable unit
	// Though analog input starts at zero, lowest value to trigger lights is 30.
	// Values below 30 are dead zone on potentiometers, so we pad the bottom values.
	ainLevels       = 4096 // 0 - 4095
	ainMinPad       = 25
	clockDividerMin = 1
	clockDividerMax = 65534
	sampleAvgMin    = 1
	// Limit overall maximum current draw to 1.5 amps.
	// 500K ns * 1.5 amps / 0.7 amps =
	maxLEDCurrent   = 700  // enforced by resistors on light fixture
	maxTotalCurrent = 1400 // previously determined to not overheat fixture
	maxTotalDuty    = pwmPeriod * maxTotalCurrent / maxLEDCurrent
	// auto mode
	// thresholds for OFF and ON
	aoutOff = 10
	aoutOn  = 4000
	// autoLoop controls when the aout offset is changed
	autoLoopMax    = 400 // we add min pad to get minpad to max+minpad
	autoLoopMinPad = 100
	autoLoopAdjust = 5 // frequency of change to auto loop max
	// autoOffset controls by how much aout is adjusted
	autoOffsetDelta = 2
	autoOffsetMax   = 400 // outer bounds +/-
)

// translate command line options to ADC constants
var sampleAvgMap = map[int]byte{
	1:  ADC_AVG_1,
	2:  ADC_AVG_2,
	4:  ADC_AVG_4,
	8:  ADC_AVG_8,
	16: ADC_AVG_16,
}

// flags
var (
	debug      = flag.Bool("debug", false, "log debug messages")
	sleep      = flag.String("sleep", "0ms", "duration (string) between updates (default 0ms)")
	windowSize = flag.Int("window", 100, "size of averaging window (default 100)")
	// program clock divider to actual value - 1, i.e., default register value 0
	clockDivider = flag.Int("divider", clockDividerMin, "ADC clock divider (default 1; max 65534)")
	sampleAvg    = flag.Int("average", sampleAvgMin, "ADC sample averaging (default 1; possible values 1, 2, 4, 8, 16)")
)

// calcMedian add aout to existing values to calculate median
func calcMedian(window *ring.Ring, aout int) float64 {
	var counts = make([]float64, 0, *windowSize)
	count := func(v interface{}) {
		counts = append(counts, v.(float64))
	}
	window.Value = float64(aout)
	window.Do(count)
	sort.Float64s(counts)
	return counts[*windowSize/2]
}

func calcDuty(aout float64) time.Duration {
	// theoretical max is 500000 but avoid hitting
	// type Duration int64 as number of nanoseconds
	return time.Duration(math.Min(.03*math.Pow(aout, 2)+ainMinPad, 499990))
}

func normalize(duties *[]time.Duration, duty time.Duration) time.Duration {
	var sum time.Duration
	for _, d := range *duties {
		sum += d
	}
	// only normalize if needed
	if sum > maxTotalDuty {
		return maxTotalDuty * duty / sum
	}
	return duty
}

// set duty based on median calculation
func setDuty(pwm *bbhw.PWMLine, aout float64, step byte, duties *[]time.Duration, msgs *[]string) {
	newDuty := calcDuty(aout)
	normalDuty := normalize(duties, newDuty)
	// we save raw values for normalization calcs but set pwm to normalized duty cycle
	if newDuty != (*duties)[step] {
		(*duties)[step] = newDuty
		pwm.SetPWM(pwmPeriod, normalDuty)
	}
	if *debug {
		(*msgs)[step] = fmt.Sprintf("%s   duty %9s", (*msgs)[step], normalDuty)
	}
}

func initWindow() *ring.Ring {
	w := ring.New(*windowSize)
	for i := 0; i < *windowSize; i++ {
		w.Value = float64(0)
		w = w.Next()
	}
	return w
}

func addDTOIfNotExists(dto string) {
	log.Println("looking for slots file")
	slotsFileName, err := bbhw.FindSlotsFile()
	if err != nil {
		log.Fatalln(err)
	}
	log.Println("found slots file", slotsFileName)
	time.Sleep(100 * time.Millisecond)
	log.Println("reading slots file")
	slots, err := ioutil.ReadFile(slotsFileName)
	if err != nil {
		log.Fatalln(err)
	}
	if bytes.Contains(slots, []byte(dto)) {
		log.Println("slots file already contains overlay", dto)
		return
	}
	log.Println("adding DTO", dto)
	if err := bbhw.AddDeviceTreeOverlay(dto); err != nil {
		log.Fatalln(err)
	}
	time.Sleep(100 * time.Millisecond)
}

func newPWM(pwmPin string) *bbhw.PWMLine {
	addDTOIfNotExists("bone_pwm_" + pwmPin)
	pwm, err := bbhw.NewBBBPWM(pwmPin)
	if err != nil {
		log.Fatalln(err)
	}
	pwm.SetPolarity(true)
	return pwm
}

type LED struct {
	pwm *bbhw.PWMLine
	win *ring.Ring
	// auto mode
	autoLoop        int // current loop number
	autoLoopMax     int // number of loops between changes to aout offset
	autoOffset      int // offset to aout in auto mode
	autoOffsetDelta int // direction to change aout offset
}

// Incoming aout always reflects the current pot setting. What varies
// over time is the autoOffset, which starts out at zero and always
// remains within +/-autoOffsetMax.
func (led *LED) autoAdjust() {
	// increment/decrement the offset
	led.autoLoop++
	if led.autoLoop > led.autoLoopMax {
		led.autoOffset += led.autoOffsetDelta
		led.autoLoop = 0
		// switch offset direction if led hit a boundary
		if led.autoOffset >= autoOffsetMax || led.autoOffset <= -autoOffsetMax {
			led.autoOffsetDelta = -led.autoOffsetDelta
		}
		// every so often change size of auto loop to change the change
		if rand.Intn(autoLoopAdjust) == 0 {
			led.autoLoopMax = randomAutoLoopMax()
		}
	}
}

func initPWMs() map[byte]*LED {
	// do not remove pwm; will crash BBB
	addDTOIfNotExists(pwmDTO)
	pwm14 := newPWM("P9_14") // green
	pwm16 := newPWM("P9_21") // red
	pwm21 := newPWM("P9_16") // white
	pwm22 := newPWM("P9_22") // blue

	// map ADC step channels to PWM pins
	// adjusted LEDs to mirror RGBW on my potentiometer test board
	LEDMap := map[byte]*LED{
		0: &LED{
			pwm:             pwm21,
			win:             initWindow(),
			autoLoopMax:     randomAutoLoopMax(),
			autoOffsetDelta: randomAutoOffsetDelta(),
		},
		1: &LED{
			pwm:             pwm14,
			win:             initWindow(),
			autoLoopMax:     randomAutoLoopMax(),
			autoOffsetDelta: randomAutoOffsetDelta(),
		},
		2: &LED{
			pwm:             pwm22,
			win:             initWindow(),
			autoLoopMax:     randomAutoLoopMax(),
			autoOffsetDelta: randomAutoOffsetDelta(),
		},
		3: &LED{
			pwm:             pwm16,
			win:             initWindow(),
			autoLoopMax:     randomAutoLoopMax(),
			autoOffsetDelta: randomAutoOffsetDelta(),
		},
	}
	return LEDMap
}

func randomAutoLoopMax() int {
	return rand.Intn(autoLoopMax) + autoLoopMinPad
}

func randomAutoOffsetDelta() int {
	if rand.Intn(2) == 0 {
		return autoOffsetDelta
	}
	return -autoOffsetDelta
}

// calcAutoMode returns true if one pot is off and three are on,
// false if all pots are off, and the input value otherwise.
func calcAutoMode(autoMode bool, aoutMap map[byte]int) bool {
	var offCt, onCt uint8
	for _, aout := range aoutMap {
		switch {
		case aout < aoutOff:
			offCt += 1
		case aout > aoutOn:
			onCt += 1
		}
	}
	if offCt == 4 {
		return false // set auto mode off
	}
	if offCt == 1 && onCt == 3 {
		return true // set auto mode on
	}
	return autoMode // leaves as is
}

func main() {
	rand.Seed(time.Now().UnixNano())
	var sleepDuration time.Duration
	var err error
	flag.Parse()
	if sleepDuration, err = time.ParseDuration(*sleep); err != nil {
		log.Fatal("could not interpret sleep duration '%v'", *sleep)
	}
	if (*clockDivider < clockDividerMin) || (*clockDivider > clockDividerMax) {
		log.Fatalf("illegal ADC clock divider: must be %v to %v", clockDividerMin, clockDividerMax)
	}

	LEDMap := initPWMs()

	ADCInit(byte(*clockDivider-1), sampleAvgMap[*sampleAvg])
	defer ADCDisable()

	// setup a data structure to map steps to pins and pwms
	// windows to average the analog input values
	var led *LED
	// for efficiency, though it seems to make no difference to cpu%
	duties := make([]time.Duration, 4)
	// for debug logging
	msgs := make([]string, 4) // 4 LED colors max

	var aoutMap map[byte]int
	var medAout float64 // median value of aout
	var autoMode bool   // auto mode continuously varies light intensity
	for {
		if sleepDuration > 0 {
			time.Sleep(sleepDuration)
		}

		aoutMap = ReadAnalog(P9_37, P9_38, P9_39, P9_40)
		autoMode = calcAutoMode(autoMode, aoutMap)
		for step, aout := range aoutMap {
			led = LEDMap[step]
			medAout = calcMedian(led.win, aout)
			led.win = led.win.Next()

			if autoMode && medAout > aoutOff {
				led.autoAdjust()
				medAout += float64(led.autoOffset)
				if medAout < 0 {
					medAout = 0
				}
			}
			if *debug {
				msgs[step] = fmt.Sprintf("STEP %d:   aout %4d   aout %6.1f", step, aout, medAout)
			}
			setDuty(led.pwm, medAout, step, &duties, &msgs)
		}
		if *debug {
			fmt.Println(strings.Join(msgs, "     "))
		}
	}
}
<|endoftext|>


<commit_before>package main

import (
	"eaciit/gdrj/model"
	"eaciit/gdrj/modules"
	"os"

	"flag"
	"github.com/eaciit/dbox"
	"github.com/eaciit/orm/v1"
	"github.com/eaciit/toolkit"
	"time"
)

var conn dbox.IConnection
var count int

// var mwg sync.WaitGroup

var (
	t0                                time.Time
	custgroup, prodgroup, plcode, ref string
	value, fiscalyear                 int
	globalval                         float64
	mapkeysvalue                      map[string]float64
	masters                           toolkit.M
)

func setinitialconnection() {
	var err error
	conn, err = modules.GetDboxIConnection("db_godrej")

	if err != nil {
		toolkit.Println("Initial connection found : ", err)
		os.Exit(1)
	}

	err = gdrj.SetDb(conn)
	if err != nil {
		toolkit.Println("Initial connection found : ", err)
		os.Exit(1)
	}
}

func buildmap(holder interface{},
	fnModel func() orm.IModel,
	filter *dbox.Filter,
	fnIter func(holder interface{}, obj interface{})) interface{} {
	crx, _ := gdrj.Find(fnModel(), filter, nil)
	defer crx.Close()
	for {
		s := fnModel()
		e := crx.Fetch(s, 1, false)
		if e != nil {
			break
		}
		fnIter(holder, s)
	}
	return holder
}

func prepmaster() {
	masters = toolkit.M{}
	masters.Set("plmodel", buildmap(map[string]*gdrj.PLModel{},
		func() orm.IModel {
			return new(gdrj.PLModel)
		},
		nil,
		func(holder, obj interface{}) {
			h := holder.(map[string]*gdrj.PLModel)
			o := obj.(*gdrj.PLModel)
			h[o.ID] = o
		}).(map[string]*gdrj.PLModel))
}

func main() {
	t0 = time.Now()
	mapkeysvalue = make(map[string]float64)

	flag.IntVar(&value, "value", 0, "representation of value need to be allocation. Default is 0")
	flag.IntVar(&fiscalyear, "year", 2015, "YYYY representation of godrej fiscal year. Default is 2015")
	flag.StringVar(&ref, "ref", "", "Reference from document or other. Default is blank")
	flag.Parse()

	if value == 0 {
		toolkit.Println("Value are mandatory to fill")
		os.Exit(1)
	}

	setinitialconnection()
	defer gdrj.CloseDb()

	toolkit.Println("Get Data Master...")
	prepmaster()

	toolkit.Println("Start Data Process...")

	toolkit.Printfn("Preparing the data")

	amount := toolkit.ToFloat64(value/12, 6, toolkit.RoundingAuto)
	for i := 1; i <= 12; i++ {
		Date := time.Date(fiscalyear, time.Month(i), 1, 0, 0, 0, 0, time.UTC).AddDate(-1, 3, 0)

		tcustomer := new(gdrj.Customer)
		tproduct := gdrj.ProductGetBySKUID("40011932")
		tpc := gdrj.ProfitCenterGetByID(toolkit.Sprintf("CD02%v", tproduct.BrandCategoryID))
		tcc := new(gdrj.CostCenter)

		tcustomer.Name = "CUSTOMER VIRTUAL"
		tcustomer.BranchID = "CD02"
		tcustomer.ChannelID = "I3"
		tcustomer.ChannelName = "MT"
		tcustomer.CustomerGroup = "MD"
		tcustomer.CustomerGroupName = "Modern Market"

		spl := new(gdrj.SalesPL)
		spl.Date = gdrj.SetDate(Date)

		spl.Customer = tcustomer
		spl.Product = tproduct
		spl.Source = "ADJUST"
		spl.Ref = "SALES"
		spl.PC = tpc
		spl.CC = tcc

		spl.GrossAmount = amount
		spl.NetAmount = amount

		plmodels := masters.Get("plmodel").(map[string]*gdrj.PLModel)
		spl.AddData("PL1", amount, plmodels)
		spl.CalcSum(masters)

		gdrj.Save(spl)

		toolkit.Printfn("Saving %d of %d in %s", i, 12,
			time.Since(t0).String())
	}

	toolkit.Printfn("Processing done in %s",
		time.Since(t0).String())
}
<commit_msg>update sales add<commit_after>package main

import (
	"eaciit/gdrj/model"
	"eaciit/gdrj/modules"
	"os"

	"flag"
	"github.com/eaciit/dbox"
	"github.com/eaciit/orm/v1"
	"github.com/eaciit/toolkit"
	"time"
)

var conn dbox.IConnection
var count int

// var mwg sync.WaitGroup

var (
	t0                                time.Time
	custgroup, prodgroup, plcode, ref string
	value, fiscalyear                 int
	globalval                         float64
	mapkeysvalue                      map[string]float64
	masters                           toolkit.M
)

func setinitialconnection() {
	var err error
	conn, err = modules.GetDboxIConnection("db_godrej")

	if err != nil {
		toolkit.Println("Initial connection found : ", err)
		os.Exit(1)
	}

	err = gdrj.SetDb(conn)
	if err != nil {
		toolkit.Println("Initial connection found : ", err)
		os.Exit(1)
	}
}

func buildmap(holder interface{},
	fnModel func() orm.IModel,
	filter *dbox.Filter,
	fnIter func(holder interface{}, obj interface{})) interface{} {
	crx, _ := gdrj.Find(fnModel(), filter, nil)
	defer crx.Close()
	for {
		s := fnModel()
		e := crx.Fetch(s, 1, false)
		if e != nil {
			break
		}
		fnIter(holder, s)
	}
	return holder
}

func getCursor(obj orm.IModel) dbox.ICursor {
	c, e := gdrj.Find(obj,
		nil, nil)
	//toolkit.M{}.Set("take", 10))
	if e != nil {
		return nil
	}
	return c
}

func prepmaster() {
	masters = toolkit.M{}
	masters.Set("plmodel", buildmap(map[string]*gdrj.PLModel{},
		func() orm.IModel {
			return new(gdrj.PLModel)
		},
		nil,
		func(holder, obj interface{}) {
			h := holder.(map[string]*gdrj.PLModel)
			o := obj.(*gdrj.PLModel)
			h[o.ID] = o
		}).(map[string]*gdrj.PLModel))
	toolkit.Println("--> Sub Channel")

	subchannels := toolkit.M{}
	csr, _ := conn.NewQuery().From("subchannels").Cursor(nil)
	defer csr.Close()
	for {
		m := toolkit.M{}
		e := csr.Fetch(&m, 1, false)
		if e != nil {
			break
		}
		subchannels.Set(m.GetString("_id"), m.GetString("title"))
	}
	masters.Set("subchannels", subchannels)

	customers := toolkit.M{}
	toolkit.Println("--> Customer")
	ccb := getCursor(new(gdrj.Customer))
	defer ccb.Close()
	for {
		cust := new(gdrj.Customer)
		e := ccb.Fetch(cust, 1, false)
		if e != nil {
			break
		}

		customers.Set(cust.ID, cust)
	}
	masters.Set("customers", customers)

	branchs := toolkit.M{}
	cmb := getCursor(new(gdrj.MasterBranch))
	defer cmb.Close()
	for {
		stx := toolkit.M{}
		e := cmb.Fetch(&stx, 1, false)
		if e != nil {
			break
		}

		branchs.Set(stx.Get("_id", "").(string), stx)
	}
	masters.Set("branchs", branchs)
}

func main() {
	t0 = time.Now()
	mapkeysvalue = make(map[string]float64)

	flag.IntVar(&value, "value", 0, "representation of value need to be allocation. Default is 0")
	flag.IntVar(&fiscalyear, "year", 2015, "YYYY representation of godrej fiscal year. Default is 2015")
	flag.StringVar(&ref, "ref", "", "Reference from document or other. Default is blank")
	flag.Parse()

	if value == 0 {
		toolkit.Println("Value are mandatory to fill")
		os.Exit(1)
	}

	setinitialconnection()
	defer gdrj.CloseDb()

	toolkit.Println("Get Data Master...")
	prepmaster()

	toolkit.Println("Start Data Process...")

	toolkit.Printfn("Preparing the data")

	amount := toolkit.ToFloat64(value/12, 6, toolkit.RoundingAuto)
	for i := 1; i <= 12; i++ {
		Date := time.Date(fiscalyear, time.Month(i), 1, 0, 0, 0, 0, time.UTC).AddDate(-1, 3, 0)

		tcustomer := new(gdrj.Customer)
		tproduct := gdrj.ProductGetBySKUID("40011932")
		tpc := gdrj.ProfitCenterGetByID(toolkit.Sprintf("CD02%v", tproduct.BrandCategoryID))
		tcc := new(gdrj.CostCenter)

		tcustomer.Name = "CUSTOMER VIRTUAL"
		tcustomer.BranchID = "CD02"
		tcustomer.ChannelID = "I3"
		tcustomer.ChannelName = "MT"
		tcustomer.CustomerGroup = "MD"
		tcustomer.CustomerGroupName = "Modern Market"

		spl := new(gdrj.SalesPL)
		spl.Date = gdrj.SetDate(Date)

		spl.Customer = tcustomer
		spl.Product = tproduct
		spl.Source = "ADJUST"
		spl.Ref = "SALES"
		spl.PC = tpc
		spl.CC = tcc

		spl.GrossAmount = amount
		spl.NetAmount = amount

		// plmodels := masters.Get("plmodel").(map[string]*gdrj.PLModel)
		spl.CleanAndClasify(masters)
		spl.CalcSales(masters)
		spl.CalcSum(masters)

		gdrj.Save(spl)

		toolkit.Printfn("Saving %d of %d in %s", i, 12,
			time.Since(t0).String())
	}

	toolkit.Printfn("Processing done in %s",
		time.Since(t0).String())
}
<|endoftext|>


<commit_before>//go:generate genspy
package example

// Doer does things, sometimes repeatedly
type Doer interface {
	DoIt(task string, repeat bool) (int, error)
	DoItAgain(task, prefix string) (count int, err error)
}

type Delegater struct {
	Delegate Doer
}

func (d *Delegater) DoSomething(task string) (int, error) {
	return d.Delegate.DoIt(task, false)
}

// RealDoer get stuff done for real
type RealDoer struct {
}

// DoIt does all the hard work
func (r *RealDoer) DoIt(task string, repeat bool) (int, error) {
	return 0, nil
}

const someConst = 1
<commit_msg>Remove irrelevant code from doer<commit_after>//go:generate genspy
package example

// Doer does things, sometimes repeatedly
type Doer interface {
	DoIt(task string, repeat bool) (int, error)
	DoItAgain(task, prefix string) (count int, err error)
}

type Delegater struct {
	Delegate Doer
}

func (d *Delegater) DoSomething(task string) (int, error) {
	return d.Delegate.DoIt(task, false)
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"fmt"
	"proksi"
	"time"
	"path/filepath"
	"os"
)

func main() {

    dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }

	proxychan := make(chan proksi.Proxy)
	lines := 0
	amountOf := 0
	alive := 0
	te := time.Now()
	var timeout = time.Second * 5
	var buffer bytes.Buffer

	proxies, err := proksi.ReadFile(dir+"/proxies.txt")
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	for _, proxy := range proxies {
		lines++
		amountOf++
		go proksi.Resolve(proxychan, proxy, timeout)
	}

	for proxy := range proxychan {

		lines--

		if proxy.Alive {
			alive++
			buffer.WriteString(proxy.Address + "\n")
		}

		if lines == 0 {
			err := proksi.WriteFile(time.Now().String()+".txt", buffer)
			if err != nil {
				fmt.Println(err)
				os.Exit(1)
			}
			fmt.Println("Checked", amountOf, "proxies in", time.Now().Sub(te), "and of which", alive, "responded.")
			os.Exit(0)
		}
	}
}
<commit_msg>example: decrease timeout, make Windows compatible, use ResolveAndWrite<commit_after>package main

import (
	"bytes"
	"fmt"
	"proksi"
	"time"
	"path/filepath"
	"os"
)

func main() {

    dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }

	proxychan := make(chan proksi.Proxy)
	lines := 0
	amountOf := 0
	alive := 0
	te := time.Now()
	var timeout = time.Second * 3
	var buffer bytes.Buffer

	proxies, err := proksi.ReadFile(dir+"/proxies.txt")
	if err != nil {
		fmt.Println(err)
	}

	for _, proxy := range proxies {
		lines++
		amountOf++
		go proksi.ResolveAndWrite(proxychan, proxy, timeout, "http://google.com/")
	}

	for proxy := range proxychan {

		lines--

		if proxy.Alive {
			alive++
			buffer.WriteString(proxy.Address + "\n")
		}

		if lines == 0 {
			err := proksi.WriteFile("checked-proxies.txt", buffer)
			if err != nil {
				fmt.Println(err)
			}
			fmt.Println("Checked", amountOf, "proxies in", time.Now().Sub(te), "and of which", alive, "responded.")
		}
	}
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"runtime"
	"time"

	"github.com/smartystreets/go-disruptor"
)

const (
	BufferSize = 1024 * 64
	BufferMask = BufferSize - 1
	Iterations = 1000000 * 100
)

var ringBuffer = [BufferSize]int64{}

func main() {
	runtime.GOMAXPROCS(2)

	written, read := disruptor.NewCursor(), disruptor.NewCursor()
	reader := disruptor.NewReader(read, written, written, SampleConsumer{})

	started := time.Now()
	reader.Start()
	publish(written, read)
	reader.Stop()
	finished := time.Now()
	fmt.Println(Iterations, finished.Sub(started))
}

const Reservations = 1

func publish(written *disruptor.Cursor, upstream disruptor.Barrier) {
	sequence := disruptor.InitialSequenceValue
	writer := disruptor.NewWriter(written, upstream, BufferSize)
	for sequence <= Iterations {
		sequence += Reservations
		writer.Await(sequence)
		ringBuffer[sequence&BufferMask] = sequence
		writer.Commit(sequence, sequence)
	}
}

// func publish(written *disruptor.Cursor, upstream disruptor.Barrier) {
// 	sequence := disruptor.InitialSequenceValue
// 	writer := disruptor.NewWriter(written, upstream, BufferSize)
// 	for sequence <= Iterations {
// 		sequence = writer.Reserve(Reservations)
// 		ringBuffer[sequence&BufferMask] = sequence
// 		writer.Commit(sequence, sequence)
// 	}
// }

// func publish(written *disruptor.Cursor, upstream disruptor.Barrier) {
// 	previous := disruptor.InitialSequenceValue
// 	gate := disruptor.InitialSequenceValue

// 	for previous <= Iterations {
// 		next := previous + 1

// 		for next-BufferSize > gate {
// 			gate = upstream.Read(next)
// 		}

// 		ringBuffer[next&BufferMask] = next
// 		written.Store(next)
// 		previous = next
// 	}
// }

type SampleConsumer struct{}

func (this SampleConsumer) Consume(lower, upper int64) {
	for lower <= upper {
		message := ringBuffer[lower&BufferMask]
		if message != lower {
			fmt.Println("Race condition", message, lower)
			panic("Race condition")
		}
		lower++
	}
}
<commit_msg>Using simplified wireup.<commit_after>package main

import (
	"fmt"
	"runtime"
	"time"

	"github.com/smartystreets/go-disruptor"
)

const (
	BufferSize   = 1024 * 64
	BufferMask   = BufferSize - 1
	Iterations   = 1000000 * 100
	Reservations = 1
)

var ring = [BufferSize]int64{}

func main() {
	runtime.GOMAXPROCS(2)

	controller := disruptor.Configure(BufferSize, SampleConsumer{}).Build()
	controller.Start()

	started := time.Now()
	publish(controller.Writer())
	finished := time.Now()

	controller.Stop()
	fmt.Println(Iterations, finished.Sub(started))
}

func publish(writer *disruptor.Writer) {
	sequence := disruptor.InitialSequenceValue
	for sequence <= Iterations {
		sequence = writer.Reserve(Reservations)
		ring[sequence&BufferMask] = sequence
		writer.Commit(sequence, sequence)
	}
}

// func publish(writer *disruptor.Writer) {
// 	sequence := disruptor.InitialSequenceValue
// 	for sequence <= Iterations {
// 		sequence += Reservations
// 		writer.Await(sequence)
// 		ring[sequence&BufferMask] = sequence
// 		writer.Commit(sequence, sequence)
// 	}
// }

type SampleConsumer struct{}

func (this SampleConsumer) Consume(lower, upper int64) {
	for lower <= upper {
		message := ring[lower&BufferMask]
		if message != lower {
			fmt.Println("Race condition", message, lower)
			panic("Race condition")
		}
		lower++
	}
}
<|endoftext|>


<commit_before>package main

import (
	"bitbucket.org/danderson/gofer"
	"flag"
	"fmt"
	"log"
	"net/http"
	"time"
)

var (
	listenHttps   = flag.String("listen-https", ":1443", "Address to listen on for HTTPS")
	listenHttp    = flag.String("listen-http", ":1080", "Address to listen on for HTTP")
	certDir       = flag.String("certdir", "", "Directory containing certs and keys")
	socketTimeout = flag.Duration("socket-timeout", 10*time.Second, "Timeout on HTTP server socket operations")
	hstsDuration  = flag.Duration("hsts-duration", 365*24*time.Hour, "HSTS enforcement time to return to clients")
)

func main() {
	flag.Parse()

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(200)
		fmt.Fprintf(w, "Hello world! Your request:\n\n%#v", r)
	})

	s := &gofer.Server{
		ReadTimeout:  *socketTimeout,
		WriteTimeout: *socketTimeout,
		HSTSDuration: *hstsDuration,
	}
	if err := s.LoadCertsFromDir(*certDir); err != nil {
		log.Fatalln(err)
	}

	log.Fatalln(s.ListenAndServe(*listenHttp, *listenHttps))
}
<commit_msg>Delete the example, static_content is a better example.<commit_after><|endoftext|>


<commit_before>package main

import (
	"net/http"

	"github.com/quan-xie/tuba"
)
git
func main() {
	r := tuba.NewRouter()
	r.Get("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("welcome"))
	})
	http.ListenAndServe(":3000", r)
}
<commit_msg>modify example main<commit_after>package main

import (
	"net/http"

	"github.com/quan-xie/tuba"
)

func main() {
	r := tuba.NewRouter()
	r.Get("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("welcome"))
	})
	http.ListenAndServe(":3000", r)
}
<|endoftext|>


<commit_before>package worker

import (
        //"os"
        "sync"
        "errors"
)

// Result represents a delivery of a job done.
type Result interface {}

// Job represents a piece of job to be done.
type Job interface {
        Action() Result
}

// Continual job
type Continue Job

// Sentry is used to ensure a sequence of jobs are done at a point.
type Sentry struct {
        worker *Worker
        mutex *sync.Mutex
        results []Result
        waiter *sync.WaitGroup
}

type guard struct {
        sentry *Sentry
        job Job
}
func (m *guard) Action() Result {
        return &unguard{ m.sentry, m.job.Action() }
}

type unguard struct {
        sentry *Sentry
        result Result
}
func (m *unguard) Action() Result {
        result := chainJob(m.result)
        m.sentry.mutex.Lock()
        m.sentry.results = append(m.sentry.results, result)
        m.sentry.mutex.Unlock()
        m.sentry.waiter.Done()
        return result
}

type stop struct {
        waiter *sync.WaitGroup
}
func (m *stop) Action() Result { return nil }

// Worker represents a worker to dispatch jobs being done.
type Worker struct {
        routines int
        i chan Job
        o chan Result
}

// New creates a new worker valid to do user-defined jobs.
func New() *Worker {
        return &Worker{}
}

// New creates a new worker and spawn N threads to do user-defined jobs.
func SpawnN(num int) *Worker {
        w := New()
        w.SpawnN(num)
        return w
}

func chainJob(result Result) Result {
        for ; result != nil; {
                if j, ok := result.(Continue); ok && j != nil {
                        result = j.Action()
                } else {
                        break
                }
        }
        return result
}

func (w *Worker) routine(num int) {
        for msg := range w.i {
                if msg != nil {
                        var sw *sync.WaitGroup
                        if stop, ok := msg.(*stop); ok && stop != nil {
                                sw = stop.waiter
                        }
                        w.o <- msg.Action(); go w.advance(sw)
                        if sw != nil { return }
                }
        }
}

func (w *Worker) advance(wg *sync.WaitGroup) {
        if chainJob(<-w.o); wg != nil {
                wg.Done()
        }
}

// Worker.SpawnN starts a number of `num` threads for jobs.
func (w *Worker) SpawnN(num int) error {
        if w.i != nil {
                return errors.New("worker is busy on jobs")
        }
        if w.o != nil {
                return errors.New("worker is busy on job results")
        }
        w.i, w.o, w.routines = make(chan Job, 1), make(chan Result, 1), num
        for i := 0; i < num; i++ {
                go w.routine(i)
        }
        return nil
}

// Worker.Kill stops all threads.
func (w *Worker) Kill() error {
        if w.i == nil {
                return errors.New("worker free")
        }
        if w.o == nil {
                return errors.New("worker don't have job results")
        }

        c := &stop{ new(sync.WaitGroup) }
        c.waiter.Add(w.routines)
        for i := 0; i < w.routines; i++ {
                w.i <- c
        }
        c.waiter.Wait()
        close(w.i)
        close(w.o)
        w.i, w.o = nil, nil
        return nil
}

// Worker.Do perform a job.
func (w *Worker) Do(m Job) {
        if w.i != nil {
                w.i <- m
        }
}

// Set a new sentry for the worker.
func (w *Worker) Sentry() *Sentry {
        if w.i == nil || w.o == nil {
                return nil
        }
        sentry := &Sentry{
                worker: w,
                mutex: new(sync.Mutex),
                waiter: new(sync.WaitGroup),
        }
        return sentry
}

// Perform a guarded job by the sentry.
func (s *Sentry) Guard(m Job) {
        s.waiter.Add(1)
        s.worker.Do(&guard{ s, m })
}

// Wait for finish of all guarded jobs.
func (s *Sentry) Wait() (results []Result) {
        s.waiter.Wait()
        return s.results
}
<commit_msg>add Wait method<commit_after>package worker

import (
        //"os"
        "sync"
        "errors"
)

// Result represents a delivery of a job done.
type Result interface {}

// Job represents a piece of job to be done.
type Job interface {
        Action() Result
}

// Continual job
type Continue Job

// Sentry is used to ensure a sequence of jobs are done at a point.
type Sentry struct {
        worker *Worker
        mutex *sync.Mutex
        results []Result
        waiter *sync.WaitGroup
}

type guard struct {
        sentry *Sentry
        job Job
}
func (m *guard) Action() Result {
        return &unguard{ m.sentry, m.job.Action() }
}

type unguard struct {
        sentry *Sentry
        result Result
}
func (m *unguard) Action() Result {
        result := chainJob(m.result)
        m.sentry.mutex.Lock()
        m.sentry.results = append(m.sentry.results, result)
        m.sentry.mutex.Unlock()
        m.sentry.waiter.Done()
        return result
}

type stop struct {
        waiter *sync.WaitGroup
}
func (m *stop) Action() Result { return nil }

// Worker represents a worker to dispatch jobs being done.
type Worker struct {
        routines int
        i chan Job
        o chan Result
}

// New creates a new worker valid to do user-defined jobs.
func New() *Worker {
        return &Worker{}
}

// New creates a new worker and spawn N threads to do user-defined jobs.
func SpawnN(num int) *Worker {
        w := New()
        w.SpawnN(num)
        return w
}

func chainJob(result Result) Result {
        for ; result != nil; {
                if j, ok := result.(Continue); ok && j != nil {
                        result = j.Action()
                } else {
                        break
                }
        }
        return result
}

func (w *Worker) routine(num int) {
        for msg := range w.i {
                if msg != nil {
                        var sw *sync.WaitGroup
                        if stop, ok := msg.(*stop); ok && stop != nil {
                                sw = stop.waiter
                        }
                        w.o <- msg.Action(); go w.advance(sw)
                        if sw != nil { return }
                }
        }
}

func (w *Worker) advance(wg *sync.WaitGroup) {
        if chainJob(<-w.o); wg != nil {
                wg.Done()
        }
}

// Worker.SpawnN starts a number of `num` threads for jobs.
func (w *Worker) SpawnN(num int) error {
        if w.i != nil {
                return errors.New("worker is busy on jobs")
        }
        if w.o != nil {
                return errors.New("worker is busy on job results")
        }
        w.i, w.o, w.routines = make(chan Job, 1), make(chan Result, 1), num
        for i := 0; i < num; i++ {
                go w.routine(i)
        }
        return nil
}

// Worker.Kill stops all threads.
func (w *Worker) Kill() error {
        // TODO: stops all threads immediately
        return w.Wait()
}

func (w *Worker) Wait() error {
        if w.i == nil {
                return errors.New("worker free")
        }
        if w.o == nil {
                return errors.New("worker don't have job results")
        }

        c := &stop{ new(sync.WaitGroup) }
        c.waiter.Add(w.routines)
        for i := 0; i < w.routines; i++ {
                w.i <- c
        }
        c.waiter.Wait()
        close(w.i)
        close(w.o)
        w.i, w.o = nil, nil
        return nil
}

// Worker.Do perform a job.
func (w *Worker) Do(m Job) {
        if w.i != nil {
                w.i <- m
        }
}

// Set a new sentry for the worker.
func (w *Worker) Sentry() *Sentry {
        if w.i == nil || w.o == nil {
                return nil
        }
        sentry := &Sentry{
                worker: w,
                mutex: new(sync.Mutex),
                waiter: new(sync.WaitGroup),
        }
        return sentry
}

// Perform a guarded job by the sentry.
func (s *Sentry) Guard(m Job) {
        s.waiter.Add(1)
        s.worker.Do(&guard{ s, m })
}

// Wait for finish of all guarded jobs.
func (s *Sentry) Wait() (results []Result) {
        s.waiter.Wait()
        return s.results
}
<|endoftext|>


<commit_before>package que

import (
	"fmt"
	"log"
	"sync"
	"time"
)

type WorkFunc func(j *Job) error

type WorkMap map[string]WorkFunc

type Worker struct {
	Interval time.Duration
	Queue    string

	c *Client
	m WorkMap

	mu   sync.Mutex
	done bool
	ch   chan struct{}
}

func NewWorker(c *Client, m WorkMap) *Worker {
	return &Worker{
		Interval: 5 * time.Second,
		c:        c,
		m:        m,
		ch:       make(chan struct{}),
	}
}

func (w *Worker) Work() {
	for {
		select {
		case <-w.ch:
			log.Println("worker done")
			return
		case <-time.After(w.Interval):
			for {
				if didWork := w.workOne(); !didWork {
					break // didn't do any work, go back to sleep
				}
			}
		}
	}
}

func (w *Worker) workOne() (didWork bool) {
	j, err := w.c.LockJob(w.Queue)
	if err != nil {
		log.Printf("attempting to lock job: %v", err)
		return
	}
	if j == nil {
		return // no job was available
	}
	defer j.Done()

	didWork = true

	wf, ok := w.m[j.Type]
	if !ok {
		if err = j.Error(fmt.Sprintf("unknown job type: %q", j.Type)); err != nil {
			log.Printf("attempting to save error on job %d: %v", j.ID, err)
		}
		return
	}

	if err = wf(j); err != nil {
		j.Error(err.Error())
		return
	}

	if err = j.Delete(); err != nil {
		log.Printf("attempting to delete job %d: %v", j.ID, err)
	}
	log.Printf("event=job_worked job_id=%d job_type=%s", j.ID, j.Type)
	return
}

func (w *Worker) Shutdown() {
	w.mu.Lock()
	defer w.mu.Unlock()

	if w.done {
		return
	}

	log.Println("worker shutting down gracefully...")
	w.ch <- struct{}{}
	w.done = true
	close(w.ch)
}

type WorkerPool struct {
	workers []*Worker

	mu   sync.Mutex
	done bool
}

func NewWorkerPool(c *Client, wm WorkMap, interval time.Duration, count int) (w *WorkerPool) {
	w.workers = make([]*Worker, count)

	for i := 0; i < count; i++ {
		w.workers[i] = NewWorker(c, wm)
		w.workers[i].Interval = interval
	}
	return
}

func (w *WorkerPool) Start() {
	for i := range w.workers {
		go w.workers[i].Work()
	}
}

func (w *WorkerPool) Shutdown() {
	w.mu.Lock()
	defer w.mu.Unlock()

	if w.done {
		return
	}
	var wg sync.WaitGroup
	wg.Add(len(w.workers))

	for _, worker := range w.workers {
		go func(worker *Worker) {
			worker.Shutdown()
			wg.Done()
		}(worker)
	}
	w.done = true
}
<commit_msg>make WorkerPool wait for Workers to Shutdown<commit_after>package que

import (
	"fmt"
	"log"
	"sync"
	"time"
)

type WorkFunc func(j *Job) error

type WorkMap map[string]WorkFunc

type Worker struct {
	Interval time.Duration
	Queue    string

	c *Client
	m WorkMap

	mu   sync.Mutex
	done bool
	ch   chan struct{}
}

func NewWorker(c *Client, m WorkMap) *Worker {
	return &Worker{
		Interval: 5 * time.Second,
		c:        c,
		m:        m,
		ch:       make(chan struct{}),
	}
}

func (w *Worker) Work() {
	for {
		select {
		case <-w.ch:
			log.Println("worker done")
			return
		case <-time.After(w.Interval):
			for {
				if didWork := w.workOne(); !didWork {
					break // didn't do any work, go back to sleep
				}
			}
		}
	}
}

func (w *Worker) workOne() (didWork bool) {
	j, err := w.c.LockJob(w.Queue)
	if err != nil {
		log.Printf("attempting to lock job: %v", err)
		return
	}
	if j == nil {
		return // no job was available
	}
	defer j.Done()

	didWork = true

	wf, ok := w.m[j.Type]
	if !ok {
		if err = j.Error(fmt.Sprintf("unknown job type: %q", j.Type)); err != nil {
			log.Printf("attempting to save error on job %d: %v", j.ID, err)
		}
		return
	}

	if err = wf(j); err != nil {
		j.Error(err.Error())
		return
	}

	if err = j.Delete(); err != nil {
		log.Printf("attempting to delete job %d: %v", j.ID, err)
	}
	log.Printf("event=job_worked job_id=%d job_type=%s", j.ID, j.Type)
	return
}

func (w *Worker) Shutdown() {
	w.mu.Lock()
	defer w.mu.Unlock()

	if w.done {
		return
	}

	log.Println("worker shutting down gracefully...")
	w.ch <- struct{}{}
	w.done = true
	close(w.ch)
}

type WorkerPool struct {
	workers []*Worker

	mu   sync.Mutex
	done bool
}

func NewWorkerPool(c *Client, wm WorkMap, interval time.Duration, count int) (w *WorkerPool) {
	w.workers = make([]*Worker, count)

	for i := 0; i < count; i++ {
		w.workers[i] = NewWorker(c, wm)
		w.workers[i].Interval = interval
	}
	return
}

func (w *WorkerPool) Start() {
	for i := range w.workers {
		go w.workers[i].Work()
	}
}

func (w *WorkerPool) Shutdown() {
	w.mu.Lock()
	defer w.mu.Unlock()

	if w.done {
		return
	}
	var wg sync.WaitGroup
	wg.Add(len(w.workers))

	for _, worker := range w.workers {
		go func(worker *Worker) {
			worker.Shutdown()
			wg.Done()
		}(worker)
	}
	wg.Wait()
	w.done = true
}
<|endoftext|>


<commit_before>package containerd

import (
	"sync"
	"time"

	"github.com/docker/containerd/runtime"
)

type Worker interface {
	Start()
}

type StartTask struct {
	Container  runtime.Container
	Checkpoint string
	Err        chan error
}

func NewWorker(s *Supervisor, wg *sync.WaitGroup) Worker {
	return &worker{
		s:  s,
		wg: wg,
	}
}

type worker struct {
	wg *sync.WaitGroup
	s  *Supervisor
}

func (w *worker) Start() {
	defer w.wg.Done()
	for t := range w.s.tasks {
		started := time.Now()
		if t.Checkpoint != "" {
			if err := t.Container.Restore(t.Checkpoint); err != nil {
				evt := NewEvent(DeleteEventType)
				evt.ID = t.Container.ID()
				w.s.SendEvent(evt)
				t.Err <- err
				continue
			}
		} else {
			if err := t.Container.Start(); err != nil {
				evt := NewEvent(DeleteEventType)
				evt.ID = t.Container.ID()
				w.s.SendEvent(evt)
				t.Err <- err
				continue
			}
		}
		ContainerStartTimer.UpdateSince(started)
		t.Err <- nil
	}
}
<commit_msg>Log start tasks<commit_after>package containerd

import (
	"sync"
	"time"

	"github.com/Sirupsen/logrus"
	"github.com/docker/containerd/runtime"
)

type Worker interface {
	Start()
}

type StartTask struct {
	Container  runtime.Container
	Checkpoint string
	Err        chan error
}

func NewWorker(s *Supervisor, wg *sync.WaitGroup) Worker {
	return &worker{
		s:  s,
		wg: wg,
	}
}

type worker struct {
	wg *sync.WaitGroup
	s  *Supervisor
}

func (w *worker) Start() {
	defer w.wg.Done()
	for t := range w.s.tasks {
		started := time.Now()
		logrus.WithFields(logrus.Fields{
			"containerID": t.Container.ID(),
			"checkpoint":  t.Checkpoint,
			"started":     started,
		}).Debug("worker received task")
		if t.Checkpoint != "" {
			if err := t.Container.Restore(t.Checkpoint); err != nil {
				evt := NewEvent(DeleteEventType)
				evt.ID = t.Container.ID()
				w.s.SendEvent(evt)
				t.Err <- err
				continue
			}
		} else {
			if err := t.Container.Start(); err != nil {
				evt := NewEvent(DeleteEventType)
				evt.ID = t.Container.ID()
				w.s.SendEvent(evt)
				t.Err <- err
				continue
			}
		}
		ContainerStartTimer.UpdateSince(started)
		t.Err <- nil
	}
}
<|endoftext|>


<commit_before>package lights

import (
	"errors"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"strings"
)

// WorkerFunc handles incoming string messages returning an error if the
// message could not be handled.
type WorkerFunc func(message string) error

// Worker takes care of the common nsq worker tasks that all message
// driven agents must carry out. The worker takes care of bootstrapping
// the system, and automatically configures nsq according to the current
// environment.
type Worker struct {
	agent string
}

// NewWorker creates a new worker ready for configuration. Call Start() on
// the worker to begin processing messages. Returns an error if there was a
// problem creating the worker. If an ID is provided the worker will use it,
// otherwise an ID will automatically be generated using lights.NewID().
func NewWorker(agent string) (*Worker, error) {
	w := &Worker{agent: agent}
	port := w.agentPort(agent)
	if len(port) == 0 {
		return nil, errors.New("Agent " + agent + " not supported")
	}
	return w, nil
}

// Start begins processing commands blocking the thread.
func (w *Worker) Start() error {
	host := ":" + w.agentPort(w.agent)
	log.Println("Listening for HTTP API", host)
	return http.ListenAndServe(host, nil)
}

// Consumer creates a new API command Consumer for the worker.
func (w *Worker) Consumer(handler WorkerFunc) error {
	http.HandleFunc("/command", func(resp http.ResponseWriter, r *http.Request) {
		body, err := ioutil.ReadAll(r.Body)
		log.Println("<-", string(body))
		if w.errorFree(err, resp) {
			err = handler(string(body))
			if w.errorFree(err, resp) {
				io.WriteString(resp, "OK")
			}
		}
	})
	return nil
}

// Send transmits a message to an agent.
func (w *Worker) Send(agent, message string) {
	url := "http://127.0.0.1:" + w.agentPort(agent) + "/command"
	log.Println("->", agent, message)
	resp, err := http.Post(url, "text/plain", strings.NewReader(message))
	if err != nil {
		log.Println("Error sending message", agent, message, err)
	} else {
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			log.Println("Error reading response body", err)
		} else {
			log.Println("  ", string(body))
		}
		resp.Body.Close()
	}
}

// errorFree will respond correctly to clients when an error occurs.
// Returns true if there was an error for easy handling.
func (w *Worker) errorFree(err error, resp http.ResponseWriter) bool {
	if err == nil {
		return true
	}
	resp.WriteHeader(http.StatusInternalServerError)
	io.WriteString(resp, err.Error())
	return false
}

// agentPort looks up the correct port for an agent by name.
func (w *Worker) agentPort(agent string) string {
	switch agent {
	case "gateway":
		return "8000"
	case "controller":
		return "8002"
	case "gatekeeper":
		return "8003"
	case "scheduler":
		return "8004"
	case "updater":
		return "8005"
	default:
		// Default is the gateway agent
		return ""
	}
}
<commit_msg>Add API arbitrary route handlers<commit_after>package lights

import (
	"errors"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"strings"
)

// WorkerFunc handles incoming string messages returning an error if the
// message could not be handled.
type WorkerFunc func(message string) error

// Worker takes care of the common nsq worker tasks that all message
// driven agents must carry out. The worker takes care of bootstrapping
// the system, and automatically configures nsq according to the current
// environment.
type Worker struct {
	agent string
}

// NewWorker creates a new worker ready for configuration. Call Start() on
// the worker to begin processing messages. Returns an error if there was a
// problem creating the worker. If an ID is provided the worker will use it,
// otherwise an ID will automatically be generated using lights.NewID().
func NewWorker(agent string) (*Worker, error) {
	w := &Worker{agent: agent}
	port := w.agentPort(agent)
	if len(port) == 0 {
		return nil, errors.New("Agent " + agent + " not supported")
	}
	return w, nil
}

// Start begins processing commands blocking the thread.
func (w *Worker) Start() error {
	host := ":" + w.agentPort(w.agent)
	log.Println("Listening for HTTP API", host)
	return http.ListenAndServe(host, nil)
}

// Consumer creates a new API /command Consumer for the worker.
func (w *Worker) Consumer(handler WorkerFunc) error {
	return w.Handler("/command", handler)
}

// Handler registers a new API route handler for the worker.
func (w *Worker) Handler(route string, handler WorkerFunc) error {
	http.HandleFunc(route, func(resp http.ResponseWriter, r *http.Request) {
		body, err := ioutil.ReadAll(r.Body)
		log.Println("<-", string(body))
		if w.errorFree(err, resp) {
			err = handler(string(body))
			if w.errorFree(err, resp) {
				io.WriteString(resp, "OK")
			}
		}
	})
	return nil
}

// Send transmits a message to an agent.
func (w *Worker) Send(agent, message string) {
	url := "http://127.0.0.1:" + w.agentPort(agent) + "/command"
	log.Println("->", agent, message)
	resp, err := http.Post(url, "text/plain", strings.NewReader(message))
	if err != nil {
		log.Println("Error sending message", agent, message, err)
	} else {
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			log.Println("Error reading response body", err)
		} else {
			log.Println("  ", string(body))
		}
		resp.Body.Close()
	}
}

// errorFree will respond correctly to clients when an error occurs.
// Returns true if there was an error for easy handling.
func (w *Worker) errorFree(err error, resp http.ResponseWriter) bool {
	if err == nil {
		return true
	}
	resp.WriteHeader(http.StatusInternalServerError)
	io.WriteString(resp, err.Error())
	return false
}

// agentPort looks up the correct port for an agent by name.
func (w *Worker) agentPort(agent string) string {
	switch agent {
	case "gateway":
		return "8000"
	case "controller":
		return "8002"
	case "gatekeeper":
		return "8003"
	case "scheduler":
		return "8004"
	case "updater":
		return "8005"
	default:
		// Default is the gateway agent
		return ""
	}
}
<|endoftext|>


<commit_before>package roger

import (
	"bytes"
	"image/png"
	"testing"

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

func getResultObject(command string) (interface{}, error) {
	client, _ := NewRClient("localhost", 6311)
	return client.Eval(command)
}

func TestBoolParsing(t *testing.T) {
	obj, _ := getResultObject("TRUE")
	boolean, ok := obj.(bool)
	assert.Equal(t, ok, true, "Return obj should be a boolean")
	assert.Equal(t, boolean, true)
}

func TestBoolArrayParsing(t *testing.T) {
	obj, _ := getResultObject("c(TRUE, FALSE, TRUE)")
	boolArr, ok := obj.([]bool)
	assert.Equal(t, ok, true, "Return obj should be a boolean array")
	assert.Equal(t, boolArr, []bool{true, false, true}, "Return obj should contain the correct booleans")
}

func TestStringParsing(t *testing.T) {
	obj, _ := getResultObject("'testing string'")
	str, ok := obj.(string)
	assert.Equal(t, ok, true, "Return obj should be a string")
	assert.Equal(t, str, "testing string")
}

func TestStringArrayParsing(t *testing.T) {
	obj, _ := getResultObject("c('test', 'string 2', '°')")
	strArr, ok := obj.([]string)
	assert.Equal(t, ok, true, "Return obj should be a string array")
	assert.Equal(t, strArr, []string{"test", "string 2", "°"})
}

func TestIntParsing(t *testing.T) {
	obj, _ := getResultObject("as.integer(2147483647)")
	in, ok := obj.(int32)
	assert.Equal(t, ok, true, "Return obj should be an int32")
	assert.Equal(t, in, int32(2147483647))
}

func TestIntArrayParsing(t *testing.T) {
	obj, _ := getResultObject("c(as.integer(2), as.integer(30000), as.integer(-20000))")
	strArr, ok := obj.([]int32)
	assert.Equal(t, ok, true, "Return obj should be an int32 array")
	assert.Equal(t, strArr, []int32{2, 30000, -20000})
}

func TestDoubleParsing(t *testing.T) {
	obj, _ := getResultObject("2147483647")
	double, ok := obj.(float64)
	assert.Equal(t, ok, true, "Return obj should be a float64")
	assert.Equal(t, double, float64(2147483647))
}

func TestDoubleArrayParsing(t *testing.T) {
	obj, _ := getResultObject("c(2, 2.3213413213213, 3e09, -420318392.2222)")
	doubleArr, ok := obj.([]float64)
	assert.Equal(t, ok, true, "Return obj should be a float64 array")
	assert.Equal(t, doubleArr, []float64{2, 2.3213413213213, 3000000000, -420318392.2222})
}

func TestListParsing(t *testing.T) {
	obj, _ := getResultObject("l <- list(); l$int <- as.integer(2); l$float <- 3.2342e04; l$char <- 'test'; l")
	list, ok := obj.(map[string]interface{})
	assert.Equal(t, ok, true, "Return obj should be a map")
	assert.Equal(t, list["int"], int32(2))
	assert.Equal(t, list["float"], float64(32342))
	assert.Equal(t, list["char"], "test")
}

func TestSingleItemListParsing(t *testing.T) {
	obj, err := getResultObject("list(echo=TRUE)")
	assert.Nil(t, err)
	list, ok := obj.(map[string]interface{})
	assert.Equal(t, ok, true, "Return obj should be a map")
	assert.Equal(t, list["echo"], true, "Expecting a 'echo' to equal TRUE")
}

func TestNestedListParsing(t *testing.T) {
	obj, _ := getResultObject("l <- list(); l$top <- 2; l$nested <- list(); l$nested$inner <- 3; l$nested$internal <- c(4,2,1); l")
	list, ok := obj.(map[string]interface{})
	assert.Equal(t, ok, true, "Return obj should be a map")
	assert.Equal(t, list["top"], float64(2))
	nestedList, ok := list["nested"].(map[string]interface{})
	assert.Equal(t, ok, true, "Nested list should be available")
	assert.Equal(t, nestedList["inner"], float64(3))
	assert.Equal(t, nestedList["internal"], []float64{4, 2, 1})
}

func TestRawParsing(t *testing.T) {
	obj, _ := getResultObject("xx <- raw(2); xx[1] <- as.raw(40); xx[2] <- charToRaw(\"A\"); xx")
	assert.Equal(t, obj, []byte{0x28, 0x41})
}

func TestImageParsing(t *testing.T) {
	obj, _ := getResultObject("filename <- tempfile(\"plot\", fileext = \".png\"); png(filename, width = 480, height = 480); plot(1:10); dev.off(); image <- readBin(filename, \"raw\", 29999); image")
	imageBytes, ok := obj.([]byte)
	assert.Equal(t, ok, true, "Image should be returned as a raw byte array")
	reader := bytes.NewReader(imageBytes)
	image, err := png.Decode(reader)
	assert.Equal(t, err, nil, "Returned byte array should be a png")
	assert.Equal(t, image.Bounds().Max.X, 480, "Image should be 480x480")
	assert.Equal(t, image.Bounds().Max.Y, 480, "Image should be 480x480")
}

func TestComplexParsing(t *testing.T) {
	obj, _ := getResultObject("complex(real = 1, imaginary = 2.22)")
	c, ok := obj.(complex128)
	assert.Equal(t, ok, true, "Return obj should be a complex128")
	assert.Equal(t, real(c), float64(1))
	assert.Equal(t, imag(c), float64(2.22))
}

func TestComplexArrayParsing(t *testing.T) {
	obj, _ := getResultObject("c(complex(real = 1, imaginary = 2.22), complex(real = 100, imaginary = -222))")
	cArr, ok := obj.([]complex128)
	assert.Equal(t, ok, true, "Return obj should be an complex128 array")
	assert.Equal(t, cArr, []complex128{complex(1, 2.22), complex(100, -222)})
}

func TestLargeResponse(t *testing.T) {
	obj, err := getResultObject("paste(rep(\"a\", 20000000), sep=\"\", collapse = \"\")")
	assert.Nil(t, err)
	str, ok := obj.(string)
	assert.Equal(t, ok, true, "Return obj should be a string")
	assert.Equal(t, len(str), 20000000, "String length expected to be 20000000 characters")
}

func TestLargeStringArrayResponse(t *testing.T) {
	obj, err := getResultObject("item <- paste(rep(\"a\", 10000000), sep=\"\", collapse = \"\"); c(item, item, item)")
	assert.Nil(t, err)
	strArr, ok := obj.([]string)
	assert.Equal(t, ok, true, "Return obj should be a string array")
	assert.Equal(t, len(strArr), 3)
	assert.Equal(t, len(strArr[0]), 10000000, "String length expected to be 10000000 characters")
}

func TestLangTag(t *testing.T) {
	_, err := getResultObject("expression(2^x)")
	assert.Nil(t, err)
}
<commit_msg>added a test for testing the return of a class - specifically this class has a slot that starts with *n* and this was causing the vector symbol parsing bug to occur because it was conflicting and overwriting the names key and causing Vector names not parsed correctly error<commit_after>package roger

import (
	"bytes"
	"image/png"
	"testing"

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

func getResultObject(command string) (interface{}, error) {
	client, _ := NewRClient("localhost", 6311)
	return client.Eval(command)
}

func TestBoolParsing(t *testing.T) {
	obj, _ := getResultObject("TRUE")
	boolean, ok := obj.(bool)
	assert.Equal(t, ok, true, "Return obj should be a boolean")
	assert.Equal(t, boolean, true)
}

func TestBoolArrayParsing(t *testing.T) {
	obj, _ := getResultObject("c(TRUE, FALSE, TRUE)")
	boolArr, ok := obj.([]bool)
	assert.Equal(t, ok, true, "Return obj should be a boolean array")
	assert.Equal(t, boolArr, []bool{true, false, true}, "Return obj should contain the correct booleans")
}

func TestStringParsing(t *testing.T) {
	obj, _ := getResultObject("'testing string'")
	str, ok := obj.(string)
	assert.Equal(t, ok, true, "Return obj should be a string")
	assert.Equal(t, str, "testing string")
}

func TestStringArrayParsing(t *testing.T) {
	obj, _ := getResultObject("c('test', 'string 2', '°')")
	strArr, ok := obj.([]string)
	assert.Equal(t, ok, true, "Return obj should be a string array")
	assert.Equal(t, strArr, []string{"test", "string 2", "°"})
}

func TestIntParsing(t *testing.T) {
	obj, _ := getResultObject("as.integer(2147483647)")
	in, ok := obj.(int32)
	assert.Equal(t, ok, true, "Return obj should be an int32")
	assert.Equal(t, in, int32(2147483647))
}

func TestIntArrayParsing(t *testing.T) {
	obj, _ := getResultObject("c(as.integer(2), as.integer(30000), as.integer(-20000))")
	strArr, ok := obj.([]int32)
	assert.Equal(t, ok, true, "Return obj should be an int32 array")
	assert.Equal(t, strArr, []int32{2, 30000, -20000})
}

func TestDoubleParsing(t *testing.T) {
	obj, _ := getResultObject("2147483647")
	double, ok := obj.(float64)
	assert.Equal(t, ok, true, "Return obj should be a float64")
	assert.Equal(t, double, float64(2147483647))
}

func TestDoubleArrayParsing(t *testing.T) {
	obj, _ := getResultObject("c(2, 2.3213413213213, 3e09, -420318392.2222)")
	doubleArr, ok := obj.([]float64)
	assert.Equal(t, ok, true, "Return obj should be a float64 array")
	assert.Equal(t, doubleArr, []float64{2, 2.3213413213213, 3000000000, -420318392.2222})
}

func TestListParsing(t *testing.T) {
	obj, _ := getResultObject("l <- list(); l$int <- as.integer(2); l$float <- 3.2342e04; l$char <- 'test'; l")
	list, ok := obj.(map[string]interface{})
	assert.Equal(t, ok, true, "Return obj should be a map")
	assert.Equal(t, list["int"], int32(2))
	assert.Equal(t, list["float"], float64(32342))
	assert.Equal(t, list["char"], "test")
}

func TestSingleItemListParsing(t *testing.T) {
	obj, err := getResultObject("list(echo=TRUE)")
	assert.Nil(t, err)
	list, ok := obj.(map[string]interface{})
	assert.Equal(t, ok, true, "Return obj should be a map")
	assert.Equal(t, list["echo"], true, "Expecting a 'echo' to equal TRUE")
}

func TestNestedListParsing(t *testing.T) {
	obj, _ := getResultObject("l <- list(); l$top <- 2; l$nested <- list(); l$nested$inner <- 3; l$nested$internal <- c(4,2,1); l")
	list, ok := obj.(map[string]interface{})
	assert.Equal(t, ok, true, "Return obj should be a map")
	assert.Equal(t, list["top"], float64(2))
	nestedList, ok := list["nested"].(map[string]interface{})
	assert.Equal(t, ok, true, "Nested list should be available")
	assert.Equal(t, nestedList["inner"], float64(3))
	assert.Equal(t, nestedList["internal"], []float64{4, 2, 1})
}

func TestRawParsing(t *testing.T) {
	obj, _ := getResultObject("xx <- raw(2); xx[1] <- as.raw(40); xx[2] <- charToRaw(\"A\"); xx")
	assert.Equal(t, obj, []byte{0x28, 0x41})
}

func TestImageParsing(t *testing.T) {
	obj, _ := getResultObject("filename <- tempfile(\"plot\", fileext = \".png\"); png(filename, width = 480, height = 480); plot(1:10); dev.off(); image <- readBin(filename, \"raw\", 29999); image")
	imageBytes, ok := obj.([]byte)
	assert.Equal(t, ok, true, "Image should be returned as a raw byte array")
	reader := bytes.NewReader(imageBytes)
	image, err := png.Decode(reader)
	assert.Equal(t, err, nil, "Returned byte array should be a png")
	assert.Equal(t, image.Bounds().Max.X, 480, "Image should be 480x480")
	assert.Equal(t, image.Bounds().Max.Y, 480, "Image should be 480x480")
}

func TestComplexParsing(t *testing.T) {
	obj, _ := getResultObject("complex(real = 1, imaginary = 2.22)")
	c, ok := obj.(complex128)
	assert.Equal(t, ok, true, "Return obj should be a complex128")
	assert.Equal(t, real(c), float64(1))
	assert.Equal(t, imag(c), float64(2.22))
}

func TestComplexArrayParsing(t *testing.T) {
	obj, _ := getResultObject("c(complex(real = 1, imaginary = 2.22), complex(real = 100, imaginary = -222))")
	cArr, ok := obj.([]complex128)
	assert.Equal(t, ok, true, "Return obj should be an complex128 array")
	assert.Equal(t, cArr, []complex128{complex(1, 2.22), complex(100, -222)})
}

func TestLargeResponse(t *testing.T) {
	obj, err := getResultObject("paste(rep(\"a\", 20000000), sep=\"\", collapse = \"\")")
	assert.Nil(t, err)
	str, ok := obj.(string)
	assert.Equal(t, ok, true, "Return obj should be a string")
	assert.Equal(t, len(str), 20000000, "String length expected to be 20000000 characters")
}

func TestLargeStringArrayResponse(t *testing.T) {
	obj, err := getResultObject("item <- paste(rep(\"a\", 10000000), sep=\"\", collapse = \"\"); c(item, item, item)")
	assert.Nil(t, err)
	strArr, ok := obj.([]string)
	assert.Equal(t, ok, true, "Return obj should be a string array")
	assert.Equal(t, len(strArr), 3)
	assert.Equal(t, len(strArr[0]), 10000000, "String length expected to be 10000000 characters")
}

func TestLangTag(t *testing.T) {
	_, err := getResultObject("expression(2^x)")
	assert.Nil(t, err)
}

func TestClass(t *testing.T) {
	_, err := getResultObject("setClass('test_class', slots=c(listslot='list', aslot='apNull', numslot='numeric', chrslot='character'), contains='data.frame'); j <- new('test_class'); d <- j")
	assert.Nil(t, err)
}
<|endoftext|>


<commit_before>/*
Copyright IBM Corp. 2016 All Rights Reserved.

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 client

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"testing"
	"time"

	"github.com/cloudflare/cfssl/cli"
	"github.com/hyperledger/fabric-cop/cli/server"
)

var serverStarted bool
var serverExitCode = 0
var dir string

const (
	ClientTLSConfig string = "cop_client.json"
)

// TestNewClient tests constructing a client
func TestNewClient(t *testing.T) {
	_, err := NewClient("https://127.0.0.1:8888")
	if err != nil {
		t.Errorf("Failed to create a client: %s", err)
	}
}

func TestEnrollCLI(t *testing.T) {
	startServer()

	clientConfig := filepath.Join(dir, ClientTLSConfig)
	os.Link("../../testdata/cop_client2.json", clientConfig)

	c := new(cli.Config)

	args := []string{"admin", "adminpw", "https://localhost:8888"}

	err := enrollMain(args, *c)
	if err != nil {
		t.Error("Failed to register, err: ", err)
	}

}

func TestReenrollCLI(t *testing.T) {
	c := new(cli.Config)

	args := []string{"https://localhost:8888"}

	err := reenrollMain(args, *c)
	if err != nil {
		t.Error("Failed to reenroll, err: ", err)
	}

}

func TestRegister(t *testing.T) {

	c := new(cli.Config)

	args := []string{"../../testdata/registerrequest.json", "https://localhost:8888"}

	err := registerMain(args, *c)
	if err != nil {
		t.Error("Failed to register, err: ", err)
	}

}

func TestRegisterNotEnoughArgs(t *testing.T) {
	c := new(cli.Config)

	args := []string{"../../testdata/registerrequest.json"}

	err := registerMain(args, *c)
	if err == nil {
		t.Error("Should have failed, not enough arguments provided")
	}

}

func TestRegisterNoJSON(t *testing.T) {
	c := new(cli.Config)

	args := []string{"", "admin", "https://localhost:8888"}

	err := registerMain(args, *c)
	if err == nil {
		t.Error("Should result in failure if registration json file not specificied, error: ", err)
	}

}

func TestRegisterMissingRegistrar(t *testing.T) {
	c := new(cli.Config)

	// os.Setenv("COP_HOME", "/tmp")
	args := []string{"", "", "https://localhost:8888"}

	err := registerMain(args, *c)
	if err == nil {
		t.Error("Should result in failure if no registrar identity exists")
	}

}

func TestRevoke(t *testing.T) {

	c := new(cli.Config)

	args := []string{"https://localhost:8888", "admin"}

	err := revokeMain(args, *c)
	if err != nil {
		t.Errorf("TestRevoke failed: %s", err)
	}

}

func TestEnrollCLINotEnoughArgs(t *testing.T) {

	c := new(cli.Config)

	args := []string{"testUser"}

	err := enrollMain(args, *c)
	if err == nil {
		t.Error("Should have failed, not enough argument provided")
	}

}

func TestEnrollCLIWithCSR(t *testing.T) {

	c := new(cli.Config)

	args := []string{"notadmin", "pass", "https://localhost:8888", "../../testdata/csr.json"}

	err := enrollMain(args, *c)
	if err != nil {
		t.Error("Failed to enroll, err: ", err)
	}

}

func TestReenrollCLIWithCSR(t *testing.T) {

	c := new(cli.Config)

	args := []string{"https://localhost:8888", "../../testdata/csr.json"}

	err := reenrollMain(args, *c)
	if err != nil {
		t.Error("Failed to reenroll, err: ", err)
	}
}

func TestRevokeNoArg(t *testing.T) {

	c := new(cli.Config)

	args := []string{"https://localhost:8888"}

	err := revokeMain(args, *c)
	if err == nil {
		t.Error("TestRevokeNoArg succeeded but should have failed")
	}
}

func TestRevokeNotAdmin(t *testing.T) {

	c := new(cli.Config)

	args := []string{"https://localhost:8888", "admin"}

	err := revokeMain(args, *c)
	if err == nil {
		t.Error("TestRevokeNotAdmin should have failed but didn't")
	}

	// os.RemoveAll(clientPath)
}

func TestBogusCommand(t *testing.T) {
	err := Command()
	if err == nil {
		t.Error("TestBogusCommand passed but should have failed")
	}
}

func TestLast(t *testing.T) {
	// Cleanup
	os.RemoveAll(dir)
}

func runServer() {
	os.Setenv("COP_DEBUG", "true")
	server.Start("../../testdata", "testconfig.json")
}

func startServer() {
	var err error
	dir, err = ioutil.TempDir("", "client")
	if err != nil {
		fmt.Printf("Failed to create temp directory [error: %s]", err)
		return
	}

	if !serverStarted {
		serverStarted = true
		fmt.Println("starting COP server ...")
		os.Setenv("COP_HOME", dir)
		go runServer()
		time.Sleep(10 * time.Second)
		fmt.Println("COP server started")
	} else {
		fmt.Println("COP server already started")
	}
}
<commit_msg>Delete cop.db after running COP unit tests<commit_after>/*
Copyright IBM Corp. 2016 All Rights Reserved.

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 client

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"testing"
	"time"

	"github.com/cloudflare/cfssl/cli"
	"github.com/hyperledger/fabric-cop/cli/server"
)

var serverStarted bool
var serverExitCode = 0
var dir string

const (
	ClientTLSConfig string = "cop_client.json"
)

// TestNewClient tests constructing a client
func TestNewClient(t *testing.T) {
	_, err := NewClient("https://127.0.0.1:8888")
	if err != nil {
		t.Errorf("Failed to create a client: %s", err)
	}
}

func TestEnrollCLI(t *testing.T) {
	startServer()

	clientConfig := filepath.Join(dir, ClientTLSConfig)
	os.Link("../../testdata/cop_client2.json", clientConfig)

	c := new(cli.Config)

	args := []string{"admin", "adminpw", "https://localhost:8888"}

	err := enrollMain(args, *c)
	if err != nil {
		t.Error("Failed to register, err: ", err)
	}

}

func TestReenrollCLI(t *testing.T) {
	c := new(cli.Config)

	args := []string{"https://localhost:8888"}

	err := reenrollMain(args, *c)
	if err != nil {
		t.Error("Failed to reenroll, err: ", err)
	}

}

func TestRegister(t *testing.T) {

	c := new(cli.Config)

	args := []string{"../../testdata/registerrequest.json", "https://localhost:8888"}

	err := registerMain(args, *c)
	if err != nil {
		t.Error("Failed to register, err: ", err)
	}

}

func TestRegisterNotEnoughArgs(t *testing.T) {
	c := new(cli.Config)

	args := []string{"../../testdata/registerrequest.json"}

	err := registerMain(args, *c)
	if err == nil {
		t.Error("Should have failed, not enough arguments provided")
	}

}

func TestRegisterNoJSON(t *testing.T) {
	c := new(cli.Config)

	args := []string{"", "admin", "https://localhost:8888"}

	err := registerMain(args, *c)
	if err == nil {
		t.Error("Should result in failure if registration json file not specificied, error: ", err)
	}

}

func TestRegisterMissingRegistrar(t *testing.T) {
	c := new(cli.Config)

	// os.Setenv("COP_HOME", "/tmp")
	args := []string{"", "", "https://localhost:8888"}

	err := registerMain(args, *c)
	if err == nil {
		t.Error("Should result in failure if no registrar identity exists")
	}

}

func TestRevoke(t *testing.T) {

	c := new(cli.Config)

	args := []string{"https://localhost:8888", "admin"}

	err := revokeMain(args, *c)
	if err != nil {
		t.Errorf("TestRevoke failed: %s", err)
	}

}

func TestEnrollCLINotEnoughArgs(t *testing.T) {

	c := new(cli.Config)

	args := []string{"testUser"}

	err := enrollMain(args, *c)
	if err == nil {
		t.Error("Should have failed, not enough argument provided")
	}

}

func TestEnrollCLIWithCSR(t *testing.T) {

	c := new(cli.Config)

	args := []string{"notadmin", "pass", "https://localhost:8888", "../../testdata/csr.json"}

	err := enrollMain(args, *c)
	if err != nil {
		t.Error("Failed to enroll, err: ", err)
	}

}

func TestReenrollCLIWithCSR(t *testing.T) {

	c := new(cli.Config)

	args := []string{"https://localhost:8888", "../../testdata/csr.json"}

	err := reenrollMain(args, *c)
	if err != nil {
		t.Error("Failed to reenroll, err: ", err)
	}
}

func TestRevokeNoArg(t *testing.T) {

	c := new(cli.Config)

	args := []string{"https://localhost:8888"}

	err := revokeMain(args, *c)
	if err == nil {
		t.Error("TestRevokeNoArg succeeded but should have failed")
	}
}

func TestRevokeNotAdmin(t *testing.T) {

	c := new(cli.Config)

	args := []string{"https://localhost:8888", "admin"}

	err := revokeMain(args, *c)
	if err == nil {
		t.Error("TestRevokeNotAdmin should have failed but didn't")
	}

	// os.RemoveAll(clientPath)
}

func TestBogusCommand(t *testing.T) {
	err := Command()
	if err == nil {
		t.Error("TestBogusCommand passed but should have failed")
	}
}

func TestLast(t *testing.T) {
	// Cleanup
	os.RemoveAll(dir)
	os.Remove("../../testdata/cop.db")
}

func runServer() {
	os.Setenv("COP_DEBUG", "true")
	server.Start("../../testdata", "testconfig.json")
}

func startServer() {
	var err error
	dir, err = ioutil.TempDir("", "client")
	if err != nil {
		fmt.Printf("Failed to create temp directory [error: %s]", err)
		return
	}

	if !serverStarted {
		serverStarted = true
		fmt.Println("starting COP server ...")
		os.Setenv("COP_HOME", dir)
		go runServer()
		time.Sleep(10 * time.Second)
		fmt.Println("COP server started")
	} else {
		fmt.Println("COP server already started")
	}
}
<|endoftext|>