<commit_before>package gardenrunner

import (
	"fmt"
	"net"
	"os"
	"os/exec"
	"path/filepath"
	"strconv"
	"strings"
	"syscall"
	"time"

	"code.cloudfoundry.org/lager"
	"code.cloudfoundry.org/lager/lagertest"
	"github.com/cloudfoundry-incubator/garden/client"
	"github.com/cloudfoundry-incubator/garden/client/connection"
	"github.com/onsi/ginkgo"
	"github.com/tedsuo/ifrit"
	"github.com/tedsuo/ifrit/ginkgomon"
)

type Runner struct {
	Command *exec.Cmd

	network string
	addr    string

	bin  string
	argv []string

	binPath    string
	rootFSPath string

	tmpdir    string
	graphRoot string
	graphPath string
}

func UseGardenRunc() bool {
	return os.Getenv("USE_GARDEN_RUNC") != ""
}

func GardenServerPackageName() string {
	if UseGardenRunc() {
		return "code.cloudfoundry.org/guardian/cmd/guardian"
	}
	return "code.cloudfoundry.org/garden-linux"
}

func New(network, addr string, bin, binPath, rootFSPath, graphRoot string, argv ...string) *Runner {
	tmpDir := filepath.Join(
		os.TempDir(),
		fmt.Sprintf("test-garden-%d", ginkgo.GinkgoParallelNode()),
	)

	if graphRoot == "" {
		graphRoot = filepath.Join(tmpDir, "graph")
	}

	graphPath := filepath.Join(graphRoot, fmt.Sprintf("node-%d", ginkgo.GinkgoParallelNode()))

	return &Runner{
		network: network,
		addr:    addr,

		bin:  bin,
		argv: argv,

		binPath:    binPath,
		rootFSPath: rootFSPath,
		graphRoot:  graphRoot,
		graphPath:  graphPath,
		tmpdir:     tmpDir,
	}
}

func (r *Runner) Run(signals <-chan os.Signal, ready chan<- struct{}) error {
	logger := lagertest.NewTestLogger("garden-runner")

	if err := os.MkdirAll(r.tmpdir, 0755); err != nil {
		return err
	}

	depotPath := filepath.Join(r.tmpdir, "containers")
	snapshotsPath := filepath.Join(r.tmpdir, "snapshots")
	stateDirPath := filepath.Join(r.tmpdir, "state")

	if err := os.MkdirAll(depotPath, 0755); err != nil {
		return err
	}

	if err := os.MkdirAll(snapshotsPath, 0755); err != nil {
		return err
	}

	if err := os.MkdirAll(r.graphPath, 0755); err != nil {
		return err
	}

	var appendDefaultFlag = func(ar []string, key, value string) []string {
		for _, a := range r.argv {
			if a == key {
				return ar
			}
		}

		if value != "" {
			return append(ar, key, value)
		} else {
			return append(ar, key)
		}
	}

	gardenArgs := make([]string, len(r.argv))
	copy(gardenArgs, r.argv)

	gardenArgs = appendDefaultFlag(gardenArgs, "--depot", depotPath)
	gardenArgs = appendDefaultFlag(gardenArgs, "--graph", r.graphPath)
	gardenArgs = appendDefaultFlag(gardenArgs, "--tag", strconv.Itoa(ginkgo.GinkgoParallelNode()))

	if !UseGardenRunc() { // garden-linux
		gardenArgs = appendDefaultFlag(gardenArgs, "--bin", r.binPath)
		gardenArgs = appendDefaultFlag(gardenArgs, "--listenNetwork", r.network)
		gardenArgs = appendDefaultFlag(gardenArgs, "--listenAddr", r.addr)
		if r.rootFSPath != "" { //rootfs is an optional parameter
			gardenArgs = appendDefaultFlag(gardenArgs, "--rootfs", r.rootFSPath)
		}
		gardenArgs = appendDefaultFlag(gardenArgs, "--snapshots", snapshotsPath)
		gardenArgs = appendDefaultFlag(gardenArgs, "--logLevel", "debug")
		gardenArgs = appendDefaultFlag(gardenArgs, "--networkPool", fmt.Sprintf("10.250.%d.0/24", ginkgo.GinkgoParallelNode()))
		gardenArgs = appendDefaultFlag(gardenArgs, "--portPoolStart", strconv.Itoa(51000+(1000*ginkgo.GinkgoParallelNode())))
		gardenArgs = appendDefaultFlag(gardenArgs, "--portPoolSize", "1000")

		gardenArgs = appendDefaultFlag(gardenArgs, "--debugAddr", fmt.Sprintf(":808%d", ginkgo.GinkgoParallelNode()))
		gardenArgs = appendDefaultFlag(gardenArgs, "--stateDir", stateDirPath)

		gardenArgs = appendDefaultFlag(gardenArgs, "--allowHostAccess", "")
		gardenArgs = appendDefaultFlag(gardenArgs, "--denyNetworks", "0.0.0.0/0")
	} else { // garden-runc
		gardenArgs = appendDefaultFlag(gardenArgs, "--init-bin", r.binPath+"/init")
		gardenArgs = appendDefaultFlag(gardenArgs, "--dadoo-bin", r.binPath+"/dadoo")
		gardenArgs = appendDefaultFlag(gardenArgs, "--nstar-bin", r.binPath+"/nstar")
		gardenArgs = appendDefaultFlag(gardenArgs, "--tar-bin", r.binPath+"/tar")
		gardenArgs = appendDefaultFlag(gardenArgs, "--runc-bin", r.binPath+"/runc")
		gardenArgs = appendDefaultFlag(gardenArgs, "--port-pool-start", strconv.Itoa(51000+(1000*ginkgo.GinkgoParallelNode())))
		gardenArgs = appendDefaultFlag(gardenArgs, "--port-pool-size", "1000")

		switch r.network {
		case "tcp":
			gardenArgs = appendDefaultFlag(gardenArgs, "--bind-ip", strings.Split(r.addr, ":")[0])
			gardenArgs = appendDefaultFlag(gardenArgs, "--bind-port", strings.Split(r.addr, ":")[1])
		case "unix":
			gardenArgs = appendDefaultFlag(gardenArgs, "--bind-socket", r.addr)
		}

		gardenArgs = appendDefaultFlag(gardenArgs, "--network-pool", fmt.Sprintf("10.250.%d.0/24", ginkgo.GinkgoParallelNode()))

		if r.rootFSPath != "" { //default-rootfs is an optional parameter
			gardenArgs = appendDefaultFlag(gardenArgs, "--default-rootfs", r.rootFSPath)
		}

		gardenArgs = appendDefaultFlag(gardenArgs, "--allow-host-access", "")
		gardenArgs = appendDefaultFlag(gardenArgs, "--deny-network", "0.0.0.0/0")
	}

	var signal os.Signal

	r.Command = exec.Command(r.bin, gardenArgs...)

	startLogLine := "garden-linux.started"
	if UseGardenRunc() {
		startLogLine = "guardian.started"
	}

	process := ifrit.Invoke(&ginkgomon.Runner{
		Name:              "garden",
		Command:           r.Command,
		AnsiColorCode:     "31m",
		StartCheck:        startLogLine,
		StartCheckTimeout: 30 * time.Second,
		Cleanup: func() {
			if signal == syscall.SIGQUIT {
				logger.Info("cleanup-subvolumes")

				// remove contents of subvolumes before deleting the subvolume
				if err := os.RemoveAll(r.graphPath); err != nil {
					logger.Error("remove graph", err)
				}

				logger.Info("cleanup-tempdirs")
				if err := os.RemoveAll(r.tmpdir); err != nil {
					logger.Error("cleanup-tempdirs-failed", err, lager.Data{"tmpdir": r.tmpdir})
				} else {
					logger.Info("tempdirs-removed")
				}
			}
		},
	})

	close(ready)

	for {
		select {
		case signal = <-signals:
			// SIGQUIT means clean up the containers, the garden process (SIGTERM) and the temporary directories
			// SIGKILL, SIGTERM and SIGINT are passed through to the garden process
			if signal == syscall.SIGQUIT {
				logger.Info("received-signal SIGQUIT")
				if err := r.destroyContainers(); err != nil {
					logger.Error("destroy-containers-failed", err)
					return err
				}
				logger.Info("destroyed-containers")
				process.Signal(syscall.SIGTERM)
			} else {
				logger.Info("received-signal", lager.Data{"signal": signal})
				process.Signal(signal)
			}

		case waitErr := <-process.Wait():
			logger.Info("process-exited")
			return waitErr
		}
	}
}

func (r *Runner) TryDial() error {
	conn, dialErr := net.DialTimeout(r.network, r.addr, 100*time.Millisecond)

	if dialErr == nil {
		conn.Close()
		return nil
	}

	return dialErr
}

func (r *Runner) NewClient() client.Client {
	return client.New(connection.New(r.network, r.addr))
}

func (r *Runner) destroyContainers() error {
	client := r.NewClient()

	containers, err := client.Containers(nil)
	if err != nil {
		return err
	}

	for _, container := range containers {
		err := client.Destroy(container.Handle())
		if err != nil {
			return err
		}
	}

	return nil
}
<commit_msg>add some logic to inigo to distinguish old from newer guardian<commit_after>package gardenrunner

import (
	"fmt"
	"net"
	"os"
	"os/exec"
	"path/filepath"
	"strconv"
	"strings"
	"syscall"
	"time"

	"code.cloudfoundry.org/lager"
	"code.cloudfoundry.org/lager/lagertest"
	"github.com/cloudfoundry-incubator/garden/client"
	"github.com/cloudfoundry-incubator/garden/client/connection"
	"github.com/onsi/ginkgo"
	"github.com/tedsuo/ifrit"
	"github.com/tedsuo/ifrit/ginkgomon"
)

type Runner struct {
	Command *exec.Cmd

	network string
	addr    string

	bin  string
	argv []string

	binPath    string
	rootFSPath string

	tmpdir    string
	graphRoot string
	graphPath string
}

func UseOldGardenRunc() bool {
	// return true if we are using old garden-runc (i.e. version <= 0.4)
	// we use the package name to distinguish them
	oldGardenRuncPath := os.Getenv("GOPATH") + "/src/github.com/cloudfoundry-incubator/guardian"
	if _, err := os.Stat(oldGardenRuncPath); os.IsNotExist(err) {
		return false
	}
	return true
}

func UseGardenRunc() bool {
	return os.Getenv("USE_GARDEN_RUNC") != ""
}

func GardenServerPackageName() string {
	if UseGardenRunc() {
		if UseOldGardenRunc() {
			return "github.com/cloudfoundry-incubator/guardian/cmd/guardian"
		}
		return "code.cloudfoundry.org/guardian/cmd/guardian"
	}
	return "code.cloudfoundry.org/garden-linux"
}

func New(network, addr string, bin, binPath, rootFSPath, graphRoot string, argv ...string) *Runner {
	tmpDir := filepath.Join(
		os.TempDir(),
		fmt.Sprintf("test-garden-%d", ginkgo.GinkgoParallelNode()),
	)

	if graphRoot == "" {
		graphRoot = filepath.Join(tmpDir, "graph")
	}

	graphPath := filepath.Join(graphRoot, fmt.Sprintf("node-%d", ginkgo.GinkgoParallelNode()))

	return &Runner{
		network: network,
		addr:    addr,

		bin:  bin,
		argv: argv,

		binPath:    binPath,
		rootFSPath: rootFSPath,
		graphRoot:  graphRoot,
		graphPath:  graphPath,
		tmpdir:     tmpDir,
	}
}

func (r *Runner) Run(signals <-chan os.Signal, ready chan<- struct{}) error {
	logger := lagertest.NewTestLogger("garden-runner")

	if err := os.MkdirAll(r.tmpdir, 0755); err != nil {
		return err
	}

	depotPath := filepath.Join(r.tmpdir, "containers")
	snapshotsPath := filepath.Join(r.tmpdir, "snapshots")
	stateDirPath := filepath.Join(r.tmpdir, "state")

	if err := os.MkdirAll(depotPath, 0755); err != nil {
		return err
	}

	if err := os.MkdirAll(snapshotsPath, 0755); err != nil {
		return err
	}

	if err := os.MkdirAll(r.graphPath, 0755); err != nil {
		return err
	}

	var appendDefaultFlag = func(ar []string, key, value string) []string {
		for _, a := range r.argv {
			if a == key {
				return ar
			}
		}

		if value != "" {
			return append(ar, key, value)
		} else {
			return append(ar, key)
		}
	}

	gardenArgs := make([]string, len(r.argv))
	copy(gardenArgs, r.argv)

	gardenArgs = appendDefaultFlag(gardenArgs, "--depot", depotPath)
	gardenArgs = appendDefaultFlag(gardenArgs, "--graph", r.graphPath)
	gardenArgs = appendDefaultFlag(gardenArgs, "--tag", strconv.Itoa(ginkgo.GinkgoParallelNode()))

	if !UseGardenRunc() { // garden-linux
		gardenArgs = appendDefaultFlag(gardenArgs, "--bin", r.binPath)
		gardenArgs = appendDefaultFlag(gardenArgs, "--listenNetwork", r.network)
		gardenArgs = appendDefaultFlag(gardenArgs, "--listenAddr", r.addr)
		if r.rootFSPath != "" { //rootfs is an optional parameter
			gardenArgs = appendDefaultFlag(gardenArgs, "--rootfs", r.rootFSPath)
		}
		gardenArgs = appendDefaultFlag(gardenArgs, "--snapshots", snapshotsPath)
		gardenArgs = appendDefaultFlag(gardenArgs, "--logLevel", "debug")
		gardenArgs = appendDefaultFlag(gardenArgs, "--networkPool", fmt.Sprintf("10.250.%d.0/24", ginkgo.GinkgoParallelNode()))
		gardenArgs = appendDefaultFlag(gardenArgs, "--portPoolStart", strconv.Itoa(51000+(1000*ginkgo.GinkgoParallelNode())))
		gardenArgs = appendDefaultFlag(gardenArgs, "--portPoolSize", "1000")

		gardenArgs = appendDefaultFlag(gardenArgs, "--debugAddr", fmt.Sprintf(":808%d", ginkgo.GinkgoParallelNode()))
		gardenArgs = appendDefaultFlag(gardenArgs, "--stateDir", stateDirPath)

		gardenArgs = appendDefaultFlag(gardenArgs, "--allowHostAccess", "")
		gardenArgs = appendDefaultFlag(gardenArgs, "--denyNetworks", "0.0.0.0/0")
	} else { // garden-runc
		if UseOldGardenRunc() {
			gardenArgs = appendDefaultFlag(gardenArgs, "--iodaemon-bin", r.binPath+"/iodaemon")
			gardenArgs = appendDefaultFlag(gardenArgs, "--kawasaki-bin", r.binPath+"/kawasaki")
		}

		gardenArgs = appendDefaultFlag(gardenArgs, "--init-bin", r.binPath+"/init")
		gardenArgs = appendDefaultFlag(gardenArgs, "--dadoo-bin", r.binPath+"/dadoo")
		gardenArgs = appendDefaultFlag(gardenArgs, "--nstar-bin", r.binPath+"/nstar")
		gardenArgs = appendDefaultFlag(gardenArgs, "--tar-bin", r.binPath+"/tar")
		gardenArgs = appendDefaultFlag(gardenArgs, "--runc-bin", r.binPath+"/runc")
		gardenArgs = appendDefaultFlag(gardenArgs, "--port-pool-start", strconv.Itoa(51000+(1000*ginkgo.GinkgoParallelNode())))
		gardenArgs = appendDefaultFlag(gardenArgs, "--port-pool-size", "1000")

		switch r.network {
		case "tcp":
			gardenArgs = appendDefaultFlag(gardenArgs, "--bind-ip", strings.Split(r.addr, ":")[0])
			gardenArgs = appendDefaultFlag(gardenArgs, "--bind-port", strings.Split(r.addr, ":")[1])
		case "unix":
			gardenArgs = appendDefaultFlag(gardenArgs, "--bind-socket", r.addr)
		}

		gardenArgs = appendDefaultFlag(gardenArgs, "--network-pool", fmt.Sprintf("10.250.%d.0/24", ginkgo.GinkgoParallelNode()))

		if r.rootFSPath != "" { //default-rootfs is an optional parameter
			gardenArgs = appendDefaultFlag(gardenArgs, "--default-rootfs", r.rootFSPath)
		}

		gardenArgs = appendDefaultFlag(gardenArgs, "--allow-host-access", "")
		gardenArgs = appendDefaultFlag(gardenArgs, "--deny-network", "0.0.0.0/0")
	}

	var signal os.Signal

	r.Command = exec.Command(r.bin, gardenArgs...)

	startLogLine := "garden-linux.started"
	if UseGardenRunc() {
		startLogLine = "guardian.started"
	}

	process := ifrit.Invoke(&ginkgomon.Runner{
		Name:              "garden",
		Command:           r.Command,
		AnsiColorCode:     "31m",
		StartCheck:        startLogLine,
		StartCheckTimeout: 30 * time.Second,
		Cleanup: func() {
			if signal == syscall.SIGQUIT {
				logger.Info("cleanup-subvolumes")

				// remove contents of subvolumes before deleting the subvolume
				if err := os.RemoveAll(r.graphPath); err != nil {
					logger.Error("remove graph", err)
				}

				logger.Info("cleanup-tempdirs")
				if err := os.RemoveAll(r.tmpdir); err != nil {
					logger.Error("cleanup-tempdirs-failed", err, lager.Data{"tmpdir": r.tmpdir})
				} else {
					logger.Info("tempdirs-removed")
				}
			}
		},
	})

	close(ready)

	for {
		select {
		case signal = <-signals:
			// SIGQUIT means clean up the containers, the garden process (SIGTERM) and the temporary directories
			// SIGKILL, SIGTERM and SIGINT are passed through to the garden process
			if signal == syscall.SIGQUIT {
				logger.Info("received-signal SIGQUIT")
				if err := r.destroyContainers(); err != nil {
					logger.Error("destroy-containers-failed", err)
					return err
				}
				logger.Info("destroyed-containers")
				process.Signal(syscall.SIGTERM)
			} else {
				logger.Info("received-signal", lager.Data{"signal": signal})
				process.Signal(signal)
			}

		case waitErr := <-process.Wait():
			logger.Info("process-exited")
			return waitErr
		}
	}
}

func (r *Runner) TryDial() error {
	conn, dialErr := net.DialTimeout(r.network, r.addr, 100*time.Millisecond)

	if dialErr == nil {
		conn.Close()
		return nil
	}

	return dialErr
}

func (r *Runner) NewClient() client.Client {
	return client.New(connection.New(r.network, r.addr))
}

func (r *Runner) destroyContainers() error {
	client := r.NewClient()

	containers, err := client.Containers(nil)
	if err != nil {
		return err
	}

	for _, container := range containers {
		err := client.Destroy(container.Handle())
		if err != nil {
			return err
		}
	}

	return nil
}
<|endoftext|>


<commit_before>package client

import (
	"bufio"
	"crypto/sha256"
	"encoding/hex"
	"io"
	"os"
	"path"
)

func exists(path string) bool {
	_, err := os.Stat(path)
	if err == nil {
		return true
	}
	if os.IsNotExist(err) {
		return false
	}
	return false
}

func write_file(content []byte, filename string) {
	// open output file
	fo, err := os.Create(filename)
	// fo, err := os.Create(filename)
	if err != nil {
		panic(err)
	}
	// close fo on exit and check for its returned error
	defer func() {
		if err := fo.Close(); err != nil {
			panic(err)
		}
	}()
	// make a write buffer
	w := bufio.NewWriter(fo)
	if _, err := w.Write(content); err != nil {
		panic(err)
	}
	if err = w.Flush(); err != nil {
		panic(err)
	}
}

func open_file(filename string) io.Reader {
	// open input file
	fi, err := os.Open(filename)
	if err != nil {
		panic(err)
	}
	// close fi on exit and check for its returned error
	defer func() {
		if err := fi.Close(); err != nil {
			panic(err)
		}
	}()
	return fi

}
func Split(file io.Reader, block_size int, filedir string) []string {
	// make a buffer to keep chunks that are read
	files := make([]string, 0)
	buf := make([]byte, block_size)
	file = bufio.NewReader(file)
	for {
		// read a chunk
		n, err := file.Read(buf)
		if err != nil && err != io.EOF {
			break
		}
		if n == 0 {
			break
		}
		h := sha256.New()
		s := string(buf[:n])
		io.WriteString(h, s)
		filename := hex.EncodeToString(h.Sum(nil))
		filename = path.Join(filedir, filename)
		write_file(buf[:n], filename)
		files = append(files, filename)
	}
	return files
}

func Join(files []string, block_size int, final string) io.Reader {
	result := make([]byte, 0)
	for _, file := range files {
		fi, err := os.Open(file)
		if err != nil {
			panic(err)
		}
		// close fi on exit and check for its returned error
		defer func() {
			if err := fi.Close(); err != nil {
				panic(err)
			}
		}()
		r := bufio.NewReader(fi)
		buf := make([]byte, block_size)
		n, err := r.Read(buf)
		for _, bite := range buf[:n] {
			result = append(result, bite)
		}
	}
	write_file(result, final)
	return open_file(final)
}
<commit_msg>Returing io.Reader instead<commit_after>package client

import (
	"bufio"
	"crypto/sha256"
	"encoding/hex"
	"io"
	"os"
	"path"
	"strings"
)

func exists(path string) bool {
	_, err := os.Stat(path)
	if err == nil {
		return true
	}
	if os.IsNotExist(err) {
		return false
	}
	return false
}

func write_file(content []byte, filename string) {
	// open output file
	fo, err := os.Create(filename)
	// fo, err := os.Create(filename)
	if err != nil {
		panic(err)
	}
	// close fo on exit and check for its returned error
	defer func() {
		if err := fo.Close(); err != nil {
			panic(err)
		}
	}()
	// make a write buffer
	w := bufio.NewWriter(fo)
	if _, err := w.Write(content); err != nil {
		panic(err)
	}
	if err = w.Flush(); err != nil {
		panic(err)
	}
}

func open_file(filename string) io.Reader {
	// open input file
	fi, err := os.Open(filename)
	if err != nil {
		panic(err)
	}
	// close fi on exit and check for its returned error
	defer func() {
		if err := fi.Close(); err != nil {
			panic(err)
		}
	}()
	return fi

}
func Split(file io.Reader, block_size int, filedir string) []string {
	// make a buffer to keep chunks that are read
	files := make([]string, 0)
	buf := make([]byte, block_size)
	file = bufio.NewReader(file)
	for {
		// read a chunk
		n, err := file.Read(buf)
		if err != nil && err != io.EOF {
			break
		}
		if n == 0 {
			break
		}
		h := sha256.New()
		s := string(buf[:n])
		io.WriteString(h, s)
		filename := hex.EncodeToString(h.Sum(nil))
		filename = path.Join(filedir, filename)
		write_file(buf[:n], filename)
		files = append(files, filename)
	}
	return files
}

func Join(files []string, block_size int) io.Reader {
	result := make([]byte, 0)
	for _, file := range files {
		fi, err := os.Open(file)
		if err != nil {
			panic(err)
		}
		// close fi on exit and check for its returned error
		defer func() {
			if err := fi.Close(); err != nil {
				panic(err)
			}
		}()

		r := bufio.NewReader(fi)
		buf := make([]byte, block_size)
		n, err := r.Read(buf)
		for _, bite := range buf[:n] {
			result = append(result, bite)
		}
	}

	sresult := string(result)
	return strings.NewReader(sresult)
}
<|endoftext|>


<commit_before>package doozer

import (
	"doozer/ack"
	"doozer/client"
	"doozer/gc"
	"doozer/lock"
	"doozer/member"
	"doozer/consensus"
	"doozer/server"
	"doozer/session"
	"doozer/store"
	"doozer/util"
	"doozer/web"
	"net"
	"os"
)

const (
	alpha           = 50
	pulseInterval   = 1e9
	timeout         = 60e9 // 60s
)

const slot = "/doozer/slot"

var slots = store.MustCompileGlob("/doozer/slot/*")

type proposer struct {
	seqns chan int64
	props chan *consensus.Prop
	st    *store.Store
}

func (p *proposer) Propose(v []byte) (e store.Event) {
	for e.Mut != string(v) {
		n := <-p.seqns
		w := p.st.Wait(n)
		p.props <- &consensus.Prop{n, v}
		e = <-w
	}
	return
}

func Main(clusterName, attachAddr string, udpConn net.PacketConn, listener, webListener net.Listener) {
	logger := util.NewLogger("main")

	var err os.Error

	listenAddr := listener.Addr().String()

	var activateSeqn int64
	cal := make(chan bool, 1)
	useSelf := make(chan bool, 1)

	var cl *client.Client
	self := util.RandId()
	st := store.New()
	if attachAddr == "" { // we are the only node in a new cluster
		set(st, "/doozer/info/"+self+"/addr", listenAddr, store.Missing)
		set(st, "/doozer/info/"+self+"/public-addr", listenAddr, store.Missing)
		set(st, "/doozer/info/"+self+"/hostname", os.Getenv("HOSTNAME"), store.Missing)
		set(st, "/doozer/info/"+self+"/version", Version, store.Missing)
		set(st, "/doozer/members/"+self, listenAddr, store.Missing)
		set(st, "/doozer/slot/"+"1", self, store.Missing)
		set(st, "/ping", "pong", store.Missing)

		cal <- true
		useSelf <- true

		cl = client.New("local", listenAddr) // TODO use real cluster name
	} else {
		cl = client.New("local", attachAddr) // TODO use real cluster name

		path := "/doozer/info/" + self + "/addr"
		_, err = cl.Set(path, store.Clobber, []byte(listenAddr))
		if err != nil {
			panic(err)
		}

		path = "/doozer/info/" + self + "/public-addr"
		_, err = cl.Set(path, store.Clobber, []byte(listenAddr))
		if err != nil {
			panic(err)
		}

		path = "/doozer/info/" + self + "/hostname"
		_, err = cl.Set(path, store.Clobber, []byte(os.Getenv("HOSTNAME")))
		if err != nil {
			panic(err)
		}

		path = "/doozer/info/" + self + "/version"
		_, err = cl.Set(path, store.Clobber, []byte(Version))
		if err != nil {
			panic(err)
		}

		joinSeqn, snap, err := cl.Join(self, listenAddr)
		if err != nil {
			panic(err)
		}

		done := make(chan int)
		st.Ops <- store.Op{1, snap}

		go advanceUntil(cl, done)

		go func() {
			st.Sync(joinSeqn + alpha)
			close(done)

			activateSeqn = activate(st, self, cl)
			cal <- true

			done = make(chan int)
			go advanceUntil(cl, done)
			st.Sync(activateSeqn + alpha)
			close(done)
			useSelf <- true
		}()

		// TODO sink needs a way to pick up missing values if there are any
		// gaps in its sequence
	}

	acker := ack.Ackify(udpConn)

	pr := &proposer{
		seqns: make(chan int64, alpha),
		props: make(chan *consensus.Prop),
		st:    st,
	}

	cmw := st.Watch(store.Any)
	in := make(chan consensus.Packet)
	out := make(chan consensus.Packet)

	consensus.NewManager(self, alpha, in, out, st.Ops, pr.seqns, pr.props, cmw)

	if attachAddr == "" {
		// Skip ahead alpha steps so that the registrar can provide a
		// meaningful cluster.
		n := <-st.Seqns
		for i := n + 1; i < n+alpha; i++ {
			st.Ops <- store.Op{i, store.Nop}
		}
	}

	live := make(chan string, 64)
	shun := make(chan string, 3) // sufficient for a cluster of 7

	go member.Clean(shun, st, pr)
	go member.Timeout(live, shun, listenAddr, timeout)

	go func() {
		<-cal
		go lock.Clean(st, pr)
		go session.Clean(st, pr)
		go gc.Pulse(self, st.Seqns, pr, pulseInterval)
		go gc.Clean(st)
	}()

	sv := &server.Server{listenAddr, st, pr, self, alpha}

	go sv.Serve(listener, useSelf)

	if webListener != nil {
		web.Store = st
		web.ClusterName = clusterName
		go web.Serve(webListener)
	}

	go func() {
		for p := range out {
			acker.WriteTo(p.Data, p.Addr)
		}
	}()

	for {
		data, addr, err := acker.ReadFrom()
		if err == os.EINVAL {
			break
		}
		if err != nil {
			logger.Println(err)
			continue
		}

		// Update liveness time stamp for this addr
		live <- addr

		in <- consensus.Packet{addr, data}
	}
}

func activate(st *store.Store, self string, c *client.Client) (seqn int64) {
	logger := util.NewLogger("activate")
	w := store.NewWatch(st, slots)
	var err os.Error

	for _, base := range store.Getdir(st, slot) {
		p := slot + "/" + base
		v, cas := st.Get(p)
		if cas != store.Dir && v[0] == "" {
			seqn, err = c.Set(p, cas, []byte(self))
			if err != nil {
				logger.Println(err)
				continue
			}

			w.Stop()
			close(w.C)
			break
		}
	}

	for ev := range w.C {
		// TODO ev.IsEmpty()
		if ev.IsSet() && ev.Body == "" {
			seqn, err = c.Set(ev.Path, ev.Cas, []byte(self))
			if err != nil {
				logger.Println(err)
				continue
			}
			w.Stop()
			close(w.C)
		}
	}

	return seqn
}

func advanceUntil(cl *client.Client, done chan int) {
	for {
		select {
		case <-done:
			return
		default:
		}

		cl.Noop()
	}
}

func set(st *store.Store, path, body string, cas int64) {
	mut := store.MustEncodeSet(path, body, cas)
	st.Ops <- store.Op{1 + <-st.Seqns, mut}
}
<commit_msg>doozer: fix arithmetic applying boot nops<commit_after>package doozer

import (
	"doozer/ack"
	"doozer/client"
	"doozer/gc"
	"doozer/lock"
	"doozer/member"
	"doozer/consensus"
	"doozer/server"
	"doozer/session"
	"doozer/store"
	"doozer/util"
	"doozer/web"
	"net"
	"os"
)

const (
	alpha           = 50
	pulseInterval   = 1e9
	timeout         = 60e9 // 60s
)

const slot = "/doozer/slot"

var slots = store.MustCompileGlob("/doozer/slot/*")

type proposer struct {
	seqns chan int64
	props chan *consensus.Prop
	st    *store.Store
}

func (p *proposer) Propose(v []byte) (e store.Event) {
	for e.Mut != string(v) {
		n := <-p.seqns
		w := p.st.Wait(n)
		p.props <- &consensus.Prop{n, v}
		e = <-w
	}
	return
}

func Main(clusterName, attachAddr string, udpConn net.PacketConn, listener, webListener net.Listener) {
	logger := util.NewLogger("main")

	var err os.Error

	listenAddr := listener.Addr().String()

	var activateSeqn int64
	cal := make(chan bool, 1)
	useSelf := make(chan bool, 1)

	var cl *client.Client
	self := util.RandId()
	st := store.New()
	if attachAddr == "" { // we are the only node in a new cluster
		set(st, "/doozer/info/"+self+"/addr", listenAddr, store.Missing)
		set(st, "/doozer/info/"+self+"/public-addr", listenAddr, store.Missing)
		set(st, "/doozer/info/"+self+"/hostname", os.Getenv("HOSTNAME"), store.Missing)
		set(st, "/doozer/info/"+self+"/version", Version, store.Missing)
		set(st, "/doozer/members/"+self, listenAddr, store.Missing)
		set(st, "/doozer/slot/"+"1", self, store.Missing)
		set(st, "/ping", "pong", store.Missing)

		cal <- true
		useSelf <- true

		cl = client.New("local", listenAddr) // TODO use real cluster name
	} else {
		cl = client.New("local", attachAddr) // TODO use real cluster name

		path := "/doozer/info/" + self + "/addr"
		_, err = cl.Set(path, store.Clobber, []byte(listenAddr))
		if err != nil {
			panic(err)
		}

		path = "/doozer/info/" + self + "/public-addr"
		_, err = cl.Set(path, store.Clobber, []byte(listenAddr))
		if err != nil {
			panic(err)
		}

		path = "/doozer/info/" + self + "/hostname"
		_, err = cl.Set(path, store.Clobber, []byte(os.Getenv("HOSTNAME")))
		if err != nil {
			panic(err)
		}

		path = "/doozer/info/" + self + "/version"
		_, err = cl.Set(path, store.Clobber, []byte(Version))
		if err != nil {
			panic(err)
		}

		joinSeqn, snap, err := cl.Join(self, listenAddr)
		if err != nil {
			panic(err)
		}

		done := make(chan int)
		st.Ops <- store.Op{1, snap}

		go advanceUntil(cl, done)

		go func() {
			st.Sync(joinSeqn + alpha)
			close(done)

			activateSeqn = activate(st, self, cl)
			cal <- true

			done = make(chan int)
			go advanceUntil(cl, done)
			st.Sync(activateSeqn + alpha)
			close(done)
			useSelf <- true
		}()

		// TODO sink needs a way to pick up missing values if there are any
		// gaps in its sequence
	}

	acker := ack.Ackify(udpConn)

	pr := &proposer{
		seqns: make(chan int64, alpha),
		props: make(chan *consensus.Prop),
		st:    st,
	}

	start := <-st.Seqns
	<-st.Wait(start)
	cmw := st.Watch(store.Any)
	in := make(chan consensus.Packet)
	out := make(chan consensus.Packet)

	consensus.NewManager(self, alpha, in, out, st.Ops, pr.seqns, pr.props, cmw)

	if attachAddr == "" {
		// Skip ahead alpha steps so that the registrar can provide a
		// meaningful cluster.
		for i := start+1; i < start+alpha+1; i++ {
			st.Ops <- store.Op{i, store.Nop}
		}
	}

	live := make(chan string, 64)
	shun := make(chan string, 3) // sufficient for a cluster of 7

	go member.Clean(shun, st, pr)
	go member.Timeout(live, shun, listenAddr, timeout)

	go func() {
		<-cal
		go lock.Clean(st, pr)
		go session.Clean(st, pr)
		go gc.Pulse(self, st.Seqns, pr, pulseInterval)
		go gc.Clean(st)
	}()

	sv := &server.Server{listenAddr, st, pr, self, alpha}

	go sv.Serve(listener, useSelf)

	if webListener != nil {
		web.Store = st
		web.ClusterName = clusterName
		go web.Serve(webListener)
	}

	go func() {
		for p := range out {
			acker.WriteTo(p.Data, p.Addr)
		}
	}()

	for {
		data, addr, err := acker.ReadFrom()
		if err == os.EINVAL {
			break
		}
		if err != nil {
			logger.Println(err)
			continue
		}

		// Update liveness time stamp for this addr
		live <- addr

		in <- consensus.Packet{addr, data}
	}
}

func activate(st *store.Store, self string, c *client.Client) (seqn int64) {
	logger := util.NewLogger("activate")
	w := store.NewWatch(st, slots)
	var err os.Error

	for _, base := range store.Getdir(st, slot) {
		p := slot + "/" + base
		v, cas := st.Get(p)
		if cas != store.Dir && v[0] == "" {
			seqn, err = c.Set(p, cas, []byte(self))
			if err != nil {
				logger.Println(err)
				continue
			}

			w.Stop()
			close(w.C)
			break
		}
	}

	for ev := range w.C {
		// TODO ev.IsEmpty()
		if ev.IsSet() && ev.Body == "" {
			seqn, err = c.Set(ev.Path, ev.Cas, []byte(self))
			if err != nil {
				logger.Println(err)
				continue
			}
			w.Stop()
			close(w.C)
		}
	}

	return seqn
}

func advanceUntil(cl *client.Client, done chan int) {
	for {
		select {
		case <-done:
			return
		default:
		}

		cl.Noop()
	}
}

func set(st *store.Store, path, body string, cas int64) {
	mut := store.MustEncodeSet(path, body, cas)
	st.Ops <- store.Op{1 + <-st.Seqns, mut}
}
<|endoftext|>


<commit_before>package cmd

import (
	"fmt"
	"testing"

	"github.com/evandroflores/claimr/model"
	"github.com/shomali11/slacker"
	"github.com/stretchr/testify/assert"
)

func TestTryToAddDirect(t *testing.T) {
	mockResponse, patchReply := createMockReply(t, "this look like a direct message. Containers are related to a channels")
	patchGetEvent := createMockEvent(t, "team", "DIRECT", "user")

	add(new(slacker.Request), mockResponse)

	defer patchReply.Unpatch()
	defer patchGetEvent.Unpatch()
}

func TestTryToAddNoName(t *testing.T) {
	mockResponse, patchReply := createMockReply(t, "can not continue without a container name 🙄")
	patchGetEvent := createMockEvent(t, "team", "channel", "user")
	mockRequest, patchParam := createMockRequest(t, map[string]string{"container-name": ""})

	add(mockRequest, mockResponse)

	defer patchReply.Unpatch()
	defer patchGetEvent.Unpatch()
	defer patchParam.Unpatch()
}

func TestTryToAddExistentContainer(t *testing.T) {
	containerName := "my-container-exists"
	teamName := "TestTeam"
	channelName := "TestChannel"
	userName := "user"

	container := model.Container{TeamID: teamName, ChannelID: channelName, Name: containerName}
	err := container.Add()
	defer container.Delete()

	assert.NoError(t, err)

	mockResponse, patchReply := createMockReply(t, "There is a container with the same name on this channel. Try a different one.")
	patchGetEvent := createMockEvent(t, teamName, channelName, userName)
	mockRequest, patchParam := createMockRequest(t, map[string]string{"container-name": containerName})

	add(mockRequest, mockResponse)

	defer patchReply.Unpatch()
	defer patchGetEvent.Unpatch()
	defer patchParam.Unpatch()
}

func TestAddContainer(t *testing.T) {
	containerName := "my-container-ok"
	teamName := "TestTeam"
	channelName := "TestChannel"
	userName := "user"

	msg := fmt.Sprintf("Container `%s` added to channel <#%s>.", containerName, channelName)
	mockResponse, patchReply := createMockReply(t, msg)
	patchGetEvent := createMockEvent(t, teamName, channelName, userName)
	mockRequest, patchParam := createMockRequest(t, map[string]string{"container-name": containerName})

	defer func() {
		container, _ := model.GetContainer(teamName, channelName, containerName)
		container.Delete()
	}()

	add(mockRequest, mockResponse)

	defer patchReply.Unpatch()
	defer patchGetEvent.Unpatch()
	defer patchParam.Unpatch()
}
<commit_msg>erge branch 'master' of github.com:evandroflores/claimr<commit_after>package cmd

import (
	"fmt"
	"reflect"
	"testing"

	"github.com/bouk/monkey"
	"github.com/evandroflores/claimr/model"
	"github.com/shomali11/slacker"
	"github.com/stretchr/testify/assert"
)

func TestTryToAddDirect(t *testing.T) {
	mockResponse, patchReply := createMockReply(t, "this look like a direct message. Containers are related to a channels")
	patchGetEvent := createMockEvent(t, "team", "DIRECT", "user")

	add(new(slacker.Request), mockResponse)

	defer patchReply.Unpatch()
	defer patchGetEvent.Unpatch()
}

func TestTryToAddNoName(t *testing.T) {
	mockResponse, patchReply := createMockReply(t, "can not continue without a container name 🙄")
	patchGetEvent := createMockEvent(t, "team", "channel", "user")
	mockRequest, patchParam := createMockRequest(t, map[string]string{"container-name": ""})

	add(mockRequest, mockResponse)

	defer patchReply.Unpatch()
	defer patchGetEvent.Unpatch()
	defer patchParam.Unpatch()
}

func TestTryToAddExistentContainer(t *testing.T) {
	containerName := "my-container-exists"
	teamName := "TestTeam"
	channelName := "TestChannel"
	userName := "user"

	container := model.Container{TeamID: teamName, ChannelID: channelName, Name: containerName}
	err := container.Add()
	defer container.Delete()

	assert.NoError(t, err)

	mockResponse, patchReply := createMockReply(t, "There is a container with the same name on this channel. Try a different one.")
	patchGetEvent := createMockEvent(t, teamName, channelName, userName)
	mockRequest, patchParam := createMockRequest(t, map[string]string{"container-name": containerName})

	add(mockRequest, mockResponse)

	defer patchReply.Unpatch()
	defer patchGetEvent.Unpatch()
	defer patchParam.Unpatch()
}

func TestAddError(t *testing.T) {

	guard := monkey.PatchInstanceMethod(reflect.TypeOf(model.Container{}), "Add",
		func(container model.Container) error {
			return fmt.Errorf("simulated error")
		})
	defer guard.Unpatch()

	containerName := "my-container-ok"
	teamName := "TestTeam"
	channelName := "TestChannel"
	userName := "user"

	mockResponse, patchReply := createMockReply(t, "simulated error")
	patchGetEvent := createMockEvent(t, teamName, channelName, userName)
	mockRequest, patchParam := createMockRequest(t, map[string]string{"container-name": containerName})

	add(mockRequest, mockResponse)

	defer patchReply.Unpatch()
	defer patchGetEvent.Unpatch()
	defer patchParam.Unpatch()
}

func TestAddContainer(t *testing.T) {
	containerName := "my-container-ok"
	teamName := "TestTeam"
	channelName := "TestChannel"
	userName := "user"

	msg := fmt.Sprintf("Container `%s` added to channel <#%s>.", containerName, channelName)
	mockResponse, patchReply := createMockReply(t, msg)
	patchGetEvent := createMockEvent(t, teamName, channelName, userName)
	mockRequest, patchParam := createMockRequest(t, map[string]string{"container-name": containerName})

	defer func() {
		container, _ := model.GetContainer(teamName, channelName, containerName)
		container.Delete()
	}()

	add(mockRequest, mockResponse)

	defer patchReply.Unpatch()
	defer patchGetEvent.Unpatch()
	defer patchParam.Unpatch()
}
<|endoftext|>


<commit_before>package cmd

import (
	"encoding/json"
	"fmt"
	"log"
	"os"

	term "github.com/buger/goterm"
	"github.com/mobingilabs/mocli/pkg/cli"
	"github.com/mobingilabs/mocli/pkg/stack"
	"github.com/mobingilabs/mocli/pkg/util"
	"github.com/spf13/cobra"
)

var describeCmd = &cobra.Command{
	Use:   "describe",
	Short: "display stack details",
	Long:  `Display stack details.`,
	Run:   describe,
}

func init() {
	rootCmd.AddCommand(describeCmd)
	describeCmd.Flags().String("id", "", "stack id")
}

func describe(cmd *cobra.Command, args []string) {
	token, err := util.GetToken()
	if err != nil {
		util.PrintErrorAndExit("Cannot read token. See `login` for information on how to login.", 1)
	}

	id := util.GetCliStringFlag(cmd, "id")
	if id == "" {
		util.PrintErrorAndExit("Stack id cannot be empty.", 1)
	}

	c := cli.New(util.GetCliStringFlag(cmd, "api-version"))
	ep := c.RootUrl + "/alm/stack/" + fmt.Sprintf("%s", id)
	resp, body, errs := c.GetSafe(ep, fmt.Sprintf("%s", token))
	if errs != nil {
		log.Println("Error(s):", errs)
		os.Exit(1)
	}

	var stacks []stack.DescribeStack
	err = json.Unmarshal(body, &stacks)
	if err != nil {
		log.Println(err)
		var m map[string]interface{}
		err = json.Unmarshal(body, &m)
		if err != nil {
			util.PrintErrorAndExit("Internal error.", 1)
		}

		serr := util.BuildRequestError(resp, m)
		if serr != "" {
			util.PrintErrorAndExit(serr, 1)
		}
	}

	stbl := term.NewTable(0, 10, 5, ' ', 0)
	fmt.Fprintf(stbl, "INSTANCE ID\tINSTANCE TYPE\tPUBLIC IP\tPRIVATE IP\n")
	for _, s := range stacks {
		for _, i := range s.Instances {
			fmt.Fprintf(stbl, "%s\t%s\t%s\t%s\n", i.InstanceId, i.InstanceType, i.PublicIpAddress, i.PrivateIpAddress)
		}
	}

	term.Print(stbl)
	term.Flush()
}
<commit_msg>Describe cmd implementation.<commit_after>package cmd

import (
	"encoding/json"
	"fmt"
	"log"
	"os"
	"time"

	term "github.com/buger/goterm"
	"github.com/mobingilabs/mocli/pkg/cli"
	"github.com/mobingilabs/mocli/pkg/stack"
	"github.com/mobingilabs/mocli/pkg/util"
	"github.com/spf13/cobra"
)

var describeCmd = &cobra.Command{
	Use:   "describe",
	Short: "display stack details",
	Long:  `Display stack details.`,
	Run:   describe,
}

func init() {
	rootCmd.AddCommand(describeCmd)
	describeCmd.Flags().String("id", "", "stack id")
}

func describe(cmd *cobra.Command, args []string) {
	token, err := util.GetToken()
	if err != nil {
		util.PrintErrorAndExit("Cannot read token. See `login` for information on how to login.", 1)
	}

	id := util.GetCliStringFlag(cmd, "id")
	if id == "" {
		util.PrintErrorAndExit("Stack id cannot be empty.", 1)
	}

	c := cli.New(util.GetCliStringFlag(cmd, "api-version"))
	ep := c.RootUrl + "/alm/stack/" + fmt.Sprintf("%s", id)
	resp, body, errs := c.GetSafe(ep, fmt.Sprintf("%s", token))
	if errs != nil {
		log.Println("Error(s):", errs)
		os.Exit(1)
	}

	var stacks []stack.DescribeStack
	err = json.Unmarshal(body, &stacks)
	if err != nil {
		log.Println(err)
		var m map[string]interface{}
		err = json.Unmarshal(body, &m)
		if err != nil {
			util.PrintErrorAndExit("Internal error.", 1)
		}

		serr := util.BuildRequestError(resp, m)
		if serr != "" {
			util.PrintErrorAndExit(serr, 1)
		}
	}

	for _, s := range stacks {
		l1 := term.NewTable(0, 10, 1, ' ', 0)
		fmt.Fprintf(l1, "Stack ID:\t%s\n", s.StackId)
		fmt.Fprintf(l1, "Stack name:\t%s\n", s.Nickname)
		fmt.Fprintf(l1, "Stack type:\t%s\n", s.Configuration.Type)
		fmt.Fprintf(l1, "Region:\t%s\n", s.Configuration.Region)
		fmt.Fprintf(l1, "Architecture:\t%s\n", s.Configuration.Architecture)
		fmt.Fprintf(l1, "Code:\t%s\n", s.Configuration.Code)
		fmt.Fprintf(l1, "Image:\t%s\n", s.Configuration.Image)
		fmt.Fprintf(l1, "Instances count:\t%d\n", len(s.Instances))
		for i, v := range s.Instances {
			fmt.Fprintf(l1, "  Index:\t[%d]\n", i)
			fmt.Fprintf(l1, "  Instance ID:\t%s\n", v.InstanceId)
			fmt.Fprintf(l1, "  Instance type:\t%s\n", v.InstanceType)
			fmt.Fprintf(l1, "  Virtualization type:\t%s\n", v.VirtualizationType)
			fmt.Fprintf(l1, "  Public IP:\t%s\n", v.PublicIpAddress)
			fmt.Fprintf(l1, "  Public DNS name:\t%s\n", v.PublicDnsName)
			fmt.Fprintf(l1, "  Private IP:\t%s\n", v.PrivateIpAddress)
			fmt.Fprintf(l1, "  Private DNS name:\t%s\n", v.PrivateDnsName)
			fmt.Fprintf(l1, "  Architecture:\t%s\n", v.Architecture)
			fmt.Fprintf(l1, "  Hypervisor:\t%s\n", v.Hypervisor)
			fmt.Fprintf(l1, "  Image ID:\t%s\n", v.ImageId)
			fmt.Fprintf(l1, "  Monitoring state:\t%s\n", v.Monitoring.State)
			fmt.Fprintf(l1, "  State:\t[%s], %s\n", v.State.Code, v.State.Name)
			fmt.Fprintf(l1, "  Availability zone:\t%s\n", v.Placement.AvailabilityZone)
			fmt.Fprintf(l1, "  Root device name:\t%s\n", v.RootDeviceName)
			fmt.Fprintf(l1, "  Root device type:\t%s\n", v.RootDeviceType)
			fmt.Fprintf(l1, "  VPC ID:\t%s\n", v.VpcId)
			fmt.Fprintf(l1, "\t\n")
		}

		fmt.Fprintf(l1, "Status:\t%s\n", s.StackStatus)
		timestr := s.CreateTime
		t, err := time.Parse(time.RFC3339, s.CreateTime)
		if err == nil {
			timestr = t.Format(time.RFC1123)
		}

		fmt.Fprintf(l1, "Time created:\t%s\n", timestr)
		term.Print(l1)
		term.Flush()
	}
}
<|endoftext|>


<commit_before>package cmd

import (
	"bytes"
	"errors"
	"fmt"
	"github.com/LastCallMedia/vagabond/config"
	"github.com/LastCallMedia/vagabond/util"
	"github.com/codegangsta/cli"
	"net"
	"os/exec"
	"runtime"
)

// Tests whether setup is completed properly
var CmdDiagnose = cli.Command{
	Name:   "diagnose",
	Usage:  "Run diagnostic tests on the environment",
	Action: runDiagnose,
}

func runDiagnose(ctx *cli.Context) {
	fmt.Println("Running diagnostics...")

	env := config.NewEnvironment()
	if err := env.Check(); err != nil {
		util.Fatal(err)
	}
	if err := checkInstall(env); err != nil {
		util.Fatal(err)
	}
	if err := checkConnection(env); err != nil {
		util.Fatal(err)
	}
	if err := checkContainers(env); err != nil {
		util.Fatal(err)
	}
	if err := checkDns(env); err != nil {
		util.Fatal(err)
	}

	util.Success("OK - No issues found")
}

func checkInstall(env *config.Environment) (err error) {
	err = exec.Command("which", "docker").Run()
	if err != nil {
		return errors.New("docker is not installed. " + helpMissingDocker())
	}
	err = exec.Command("which", "docker-compose").Run()
	if err != nil {
		return errors.New("docker-compose is not installed. " + helpMissingDockerCompose())
	}
	if runtime.GOOS == "darwin" {
		err = exec.Command("which", "docker-machine").Run()
		if err != nil {
			return errors.New("docker-machine is not installed. " + helpMissingDocker())
		}
	}
	return
}

func checkConnection(env *config.Environment) error {
	err := exec.Command("docker", "info").Run()
	if err != nil {
		if runtime.GOOS == "darwin" {
			machine := env.GetMachine()
			if !machine.IsCreated() {
				return errors.New("Docker machine is not created. Run setup to create the machine.")
			}
			if !machine.IsBooted() {
				return errors.New("Docker machine is created but not booted. Run setup to boot the machine.")
			}
		}
		return errors.New("Unable to connect to docker daemon. " + helpConnectingToDaemon(env))
	}
	return err
}

func checkContainers(env *config.Environment) error {
	running := []byte("running")
	out, err := exec.Command("docker", "inspect", "-f", "{{.State.Status}}", "vagabond_dnsmasq").Output()
	if err != nil {
		return errors.New("Problem inspecting DNSMasq container. Run setup to restart it.")
	}
	if !bytes.Contains(out, running) {
		return errors.New("dnsmasq container is not running.  Run setup to restart it.")
	}
	out, err = exec.Command("docker", "inspect", "-f", "{{.State.Status}}", "vagabond_proxy").Output()
	if err != nil {
		return errors.New("Unable to find proxy container. Run setup to start it.")
	}
	if !bytes.Contains(out, running) {
		return errors.New("Proxy container is not running. Run setup to restart it.")
	}
	return err
}

func checkDns(env *config.Environment) error {
	addrs, err := net.LookupIP("somehost.docker")
	if err != nil {
		return errors.New("Unable to resolve somehost.docker. Run setup to fix DNS settings.")
	}

	if !ipSliceContains(addrs, env.MachineIp) {
		return errors.New("somehost.docker resolves to the wrong host. Run setup to fix DNS settings.")
	}
	return err
}

func ipSliceContains(ips []net.IP, ip net.IP) bool {
	for _, v := range ips {
		if v.String() == ip.String() {
			return true
		}
	}
	return false
}

func helpConnectingToDaemon(env *config.Environment) string {
	if runtime.GOOS == "darwin" {
		return fmt.Sprintf(`Try running "eval $(docker-machine env %s)"`, env.MachineName)
	}
	return "Make sure the docker service is running and that you are running this command as a user that can access it (usually root)"
}

func helpMissingDocker() string {
	if runtime.GOOS == "darwin" {
		return "Download and install the docker toolbox from https://www.docker.com/products/docker-toolbox"
	}
	return "Install docker using your package manager (https://docs.docker.com/engine/installation/)"
}

func helpMissingDockerCompose() string {
	if runtime.GOOS == "darwin" {
		return "Download and install the docker toolbox from https://www.docker.com/products/docker-toolbox"
	}
	return "Install docker using your package manager (https://docs.docker.com/engine/installation/)"
}
<commit_msg>Fix compose instructions<commit_after>package cmd

import (
	"bytes"
	"errors"
	"fmt"
	"github.com/LastCallMedia/vagabond/config"
	"github.com/LastCallMedia/vagabond/util"
	"github.com/codegangsta/cli"
	"net"
	"os/exec"
	"runtime"
)

// Tests whether setup is completed properly
var CmdDiagnose = cli.Command{
	Name:   "diagnose",
	Usage:  "Run diagnostic tests on the environment",
	Action: runDiagnose,
}

func runDiagnose(ctx *cli.Context) {
	fmt.Println("Running diagnostics...")

	env := config.NewEnvironment()
	if err := env.Check(); err != nil {
		util.Fatal(err)
	}
	if err := checkInstall(env); err != nil {
		util.Fatal(err)
	}
	if err := checkConnection(env); err != nil {
		util.Fatal(err)
	}
	if err := checkContainers(env); err != nil {
		util.Fatal(err)
	}
	if err := checkDns(env); err != nil {
		util.Fatal(err)
	}

	util.Success("OK - No issues found")
}

func checkInstall(env *config.Environment) (err error) {
	err = exec.Command("which", "docker").Run()
	if err != nil {
		return errors.New("docker is not installed. " + helpMissingDocker())
	}
	err = exec.Command("which", "docker-compose").Run()
	if err != nil {
		return errors.New("docker-compose is not installed. " + helpMissingDockerCompose())
	}
	if runtime.GOOS == "darwin" {
		err = exec.Command("which", "docker-machine").Run()
		if err != nil {
			return errors.New("docker-machine is not installed. " + helpMissingDocker())
		}
	}
	return
}

func checkConnection(env *config.Environment) error {
	err := exec.Command("docker", "info").Run()
	if err != nil {
		if runtime.GOOS == "darwin" {
			machine := env.GetMachine()
			if !machine.IsCreated() {
				return errors.New("Docker machine is not created. Run setup to create the machine.")
			}
			if !machine.IsBooted() {
				return errors.New("Docker machine is created but not booted. Run setup to boot the machine.")
			}
		}
		return errors.New("Unable to connect to docker daemon. " + helpConnectingToDaemon(env))
	}
	return err
}

func checkContainers(env *config.Environment) error {
	running := []byte("running")
	out, err := exec.Command("docker", "inspect", "-f", "{{.State.Status}}", "vagabond_dnsmasq").Output()
	if err != nil {
		return errors.New("Problem inspecting DNSMasq container. Run setup to restart it.")
	}
	if !bytes.Contains(out, running) {
		return errors.New("dnsmasq container is not running.  Run setup to restart it.")
	}
	out, err = exec.Command("docker", "inspect", "-f", "{{.State.Status}}", "vagabond_proxy").Output()
	if err != nil {
		return errors.New("Unable to find proxy container. Run setup to start it.")
	}
	if !bytes.Contains(out, running) {
		return errors.New("Proxy container is not running. Run setup to restart it.")
	}
	return err
}

func checkDns(env *config.Environment) error {
	addrs, err := net.LookupIP("somehost.docker")
	if err != nil {
		return errors.New("Unable to resolve somehost.docker. Run setup to fix DNS settings.")
	}

	if !ipSliceContains(addrs, env.MachineIp) {
		return errors.New("somehost.docker resolves to the wrong host. Run setup to fix DNS settings.")
	}
	return err
}

func ipSliceContains(ips []net.IP, ip net.IP) bool {
	for _, v := range ips {
		if v.String() == ip.String() {
			return true
		}
	}
	return false
}

func helpConnectingToDaemon(env *config.Environment) string {
	if runtime.GOOS == "darwin" {
		return fmt.Sprintf(`Try running "eval $(docker-machine env %s)"`, env.MachineName)
	}
	return "Make sure the docker service is running and that you are running this command as a user that can access it (usually root)"
}

func helpMissingDocker() string {
	if runtime.GOOS == "darwin" {
		return "Download and install the docker toolbox from https://www.docker.com/products/docker-toolbox"
	}
	return "Install docker using your package manager (https://docs.docker.com/engine/installation/)"
}

func helpMissingDockerCompose() string {
	if runtime.GOOS == "darwin" {
		return "Download and install the docker toolbox from https://www.docker.com/products/docker-toolbox"
	}
	return "Download docker-compose from https://github.com/docker/compose/releases"
}
<|endoftext|>


<commit_before>// Copyright © 2017 sleepinggenius2 <sleepinggenius2@users.noreply.github.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package cmd

import (
	"bytes"
	"fmt"
	"go/format"
	"io"
	"log"
	"os"
	"path"
	"strings"

	"github.com/pkg/errors"
	"github.com/sleepinggenius2/gosmi"
	"github.com/sleepinggenius2/gosmi/models"
	"github.com/sleepinggenius2/gosmi/types"
	"github.com/spf13/cobra"
)

const fileHeader = `// Code generated by mib2go. DO NOT EDIT.
package %s

import (
	"github.com/sleepinggenius2/gosmi/models"
	"github.com/sleepinggenius2/gosmi/types"
)

`
const allowedNodeKinds = types.NodeScalar | types.NodeTable | types.NodeRow | types.NodeColumn | types.NodeNotification

var (
	outDir      string
	outFilename string
	packageName string
	paths       []string
)

// generateCmd represents the generate command
var generateCmd = &cobra.Command{
	Use:   "generate",
	Short: "Generates Go files from MIBs",
	Long:  `Generates Go files from MIBs.`,
	Args:  cobra.MinimumNArgs(1),
	RunE: func(cmd *cobra.Command, args []string) (err error) {
		gosmi.Init()
		defer gosmi.Exit()

		for _, path := range paths {
			gosmi.AppendPath(path)
		}

		var out *os.File
		if outFilename == "-" {
			out = os.Stdout
		} else if outFilename != "" {
			var err error
			out, err = os.OpenFile(outFilename, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
			if err != nil {
				return errors.Wrapf(err, "Opening file %s", outFilename)
			}
			defer out.Close()
			log.Printf("Outputting to %s\n", outFilename)
		}

		typesMap := make(map[string]*models.Type)

		for i, arg := range args {
			moduleName, err := gosmi.LoadModule(arg)
			if err != nil {
				return errors.Wrapf(err, "Loading module %s", arg)
			}

			module, err := gosmi.GetModule(moduleName)
			if err != nil {
				return errors.Wrapf(err, "Getting module %s", moduleName)
			}

			fileBuf := &bytes.Buffer{}
			if out == nil || i == 0 {
				fmt.Fprintf(fileBuf, fileHeader, packageName)
			}

			generateMibFile(module, fileBuf, typesMap)

			outFile := out
			if outFile == nil {
				filename := path.Join(outDir, strings.ToLower(module.Name)+".go")
				outFile, err = os.OpenFile(filename, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
				if err != nil {
					return errors.Wrapf(err, "Opening file %s", filename)
				}
				defer outFile.Close()
				log.Printf("Outputting to %s\n", filename)
			}

			err = writeGoFile(outFile, fileBuf.Bytes())
			if err != nil {
				return errors.Wrap(err, "Writing module Go file")
			}
		}

		typesBuf := &bytes.Buffer{}
		if out == nil {
			fmt.Fprintf(typesBuf, fileHeader, packageName)
		}

		for _, nodeType := range typesMap {
			generateTypeBlock(typesBuf, nodeType, true)
		}

		outFile := out
		if outFile == nil {
			filename := "types.go"
			outFile, err = os.OpenFile(filename, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
			if err != nil {
				return errors.Wrapf(err, "Opening file %s", filename)
			}
			defer outFile.Close()
			log.Printf("Outputting to %s\n", filename)
		}

		err = writeGoFile(outFile, typesBuf.Bytes())
		if err != nil {
			return errors.Wrap(err, "Writing types Go file")
		}

		return nil
	},
}

func formatModuleName(moduleName string) (formattedName string) {
	parts := strings.Split(moduleName, "-")
	for _, part := range parts {
		formattedName += strings.ToUpper(part[:1]) + strings.ToLower(part[1:])
	}
	return
}

func formatNodeName(nodeName string) (formattedName string) {
	return strings.ToUpper(nodeName[:1]) + nodeName[1:]
}

func formatNodeVarName(nodeName string) (formattedName string) {
	return strings.ToLower(nodeName[:1]) + nodeName[1:] + "Node"
}

func generateMibFile(module gosmi.SmiModule, buf io.Writer, typesMap map[string]*models.Type) {
	formattedModuleName := formatModuleName(module.Name)
	nodes := module.GetNodes()

	fmt.Fprintf(buf, "type %sModule struct {\n", formattedModuleName)
	for _, node := range nodes {
		if node.Kind&allowedNodeKinds > 0 {
			fmt.Fprintf(buf, "\t%s\tmodels.%sNode\n", formatNodeName(node.Name), node.Kind)
		}
	}
	fmt.Fprintf(buf, "}\n\n")

	fmt.Fprintf(buf, "var %s = %sModule {\n", formattedModuleName, formattedModuleName)
	for _, node := range nodes {
		if node.Kind&allowedNodeKinds > 0 {
			fmt.Fprintf(buf, "\t%s:\t%s,\n", formatNodeName(node.Name), formatNodeVarName(node.Name))
		}
	}
	fmt.Fprintf(buf, "}\n\n")

	for _, node := range nodes {
		if node.Kind&allowedNodeKinds > 0 {
			fmt.Fprintf(buf, "var %s = models.%sNode{\n", formatNodeVarName(node.Name), node.Kind)
			fmt.Fprintf(buf, "\tBaseNode: models.BaseNode{\n")
			fmt.Fprintf(buf, "\t\tName: %q,\n", node.Name)
			oid := node.Oid
			oidFormatted := node.RenderNumeric()
			oidLen := node.OidLen
			if node.Kind == types.NodeScalar {
				oid = append(oid, 0)
				oidFormatted += ".0"
				oidLen++
			}
			fmt.Fprintf(buf, "\t\tOid: %#v,\n", oid)
			fmt.Fprintf(buf, "\t\tOidFormatted: %q,\n", oidFormatted)
			fmt.Fprintf(buf, "\t\tOidLen: %d,\n", oidLen)
			fmt.Fprintf(buf, "\t},\n")

			if node.Kind&(types.NodeColumn|types.NodeScalar) > 0 {
				switch node.Type.Name {
				case "Integer32", "OctetString", "ObjectIdentifier", "Unsigned32", "Integer64", "Unsigned64", "Enumeration", "Bits":
					generateTypeBlock(buf, node.Type, false)
				default:
					if _, ok := typesMap[node.Type.Name]; !ok {
						typesMap[node.Type.Name] = node.Type
					}
					fmt.Fprintf(buf, "\tType: %sType,\n", formatNodeName(node.Type.Name))
				}
			} else if node.Kind == types.NodeTable {
				fmt.Fprintf(buf, "\tRow: %s,\n", formatNodeVarName(node.GetRow().Name))
			} else if node.Kind == types.NodeRow {
				fmt.Fprintf(buf, "\tColumns: []models.ColumnNode{\n")
				_, columnOrder := node.GetColumns()
				for _, column := range columnOrder {
					fmt.Fprintf(buf, "\t\t%s,\n", formatNodeVarName(column))
				}
				fmt.Fprintf(buf, "\t},\n")
				fmt.Fprintf(buf, "\tIndex: []models.ColumnNode{\n")
				indices := node.GetIndex()
				for _, index := range indices {
					fmt.Fprintf(buf, "\t\t%s,\n", formatNodeVarName(index.Name))
				}
				fmt.Fprintf(buf, "\t},\n")
			} else if node.Kind == types.NodeNotification {
				objects := node.GetNotificationObjects()
				fmt.Fprintf(buf, "\tObjects: []models.ScalarNode{\n")
				for _, object := range objects {
					if object.Kind == types.NodeScalar {
						fmt.Fprintf(buf, "\t\t%s,\n", formatNodeVarName(object.Name))
					} else {
						fmt.Fprintf(buf, "\t\tmodels.ScalarNode(%s),\n", formatNodeVarName(object.Name))
					}
				}
				fmt.Fprintf(buf, "\t},\n")
			}

			fmt.Fprintf(buf, "}\n")
		}
	}
}

func generateTypeBlock(buf io.Writer, t *models.Type, asVar bool) {
	if asVar {
		fmt.Fprintf(buf, "var %sType = models.Type{\n", formatNodeName(t.Name))
	} else {
		fmt.Fprintf(buf, "Type: models.Type{\n")
	}
	fmt.Fprintf(buf, "\tBaseType: types.BaseType%s,\n", t.BaseType)
	if t.Enum != nil {
		fmt.Fprintf(buf, "\tEnum: &models.Enum{\n")
		fmt.Fprintf(buf, "\t\tBaseType: types.BaseType%s,\n", t.Enum.BaseType)
		fmt.Fprintf(buf, "\t\tValues: []models.NamedNumber{\n")
		for _, value := range t.Enum.Values {
			fmt.Fprintf(buf, "\t\t\t%#v,\n", value)
		}
		fmt.Fprintf(buf, "\t\t},\n")
		fmt.Fprintf(buf, "\t},\n")
	}
	if t.Format != "" {
		fmt.Fprintf(buf, "\tFormat: %q,\n", t.Format)
	}
	fmt.Fprintf(buf, "\tName: %q,\n", t.Name)
	if len(t.Ranges) > 0 {
		fmt.Fprintf(buf, "\tRanges: []models.Range{\n")
		for _, typeRange := range t.Ranges {
			fmt.Fprintf(buf, "\t\tmodels.Range{BaseType: types.BaseType%s, MinValue: %#v, MaxValue: %#v},\n",
				typeRange.BaseType,
				typeRange.MinValue,
				typeRange.MaxValue,
			)
		}
		fmt.Fprintf(buf, "\t},\n")
	}
	if t.Units != "" {
		fmt.Fprintf(buf, "\tUnits: %q,\n", t.Units)
	}
	if asVar {
		fmt.Fprintf(buf, "}\n\n")
	} else {
		fmt.Fprintf(buf, "},\n")
	}
}

func writeGoFile(out io.Writer, b []byte) error {
	formattedSource, err := format.Source(b)
	if err != nil {
		return errors.Wrap(err, "Generating formatted source")
	}

	_, err = out.Write(formattedSource)
	if err != nil {
		return errors.Wrap(err, "Writing file")
	}

	return nil
}

func init() {
	RootCmd.AddCommand(generateCmd)

	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// generateCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	generateCmd.Flags().StringVarP(&outDir, "dir", "d", ".", "Output directory")
	generateCmd.Flags().StringVarP(&outFilename, "output", "o", "", "Output filename, use - for stdout")
	generateCmd.Flags().StringVarP(&packageName, "package", "p", "mibs", "The package for the generated file")
	generateCmd.Flags().StringSliceVarP(&paths, "path", "M", []string{}, "Path(s) to add to MIB search path")
}
<commit_msg>Fixes types.go file path and module variable name<commit_after>// Copyright © 2017 sleepinggenius2 <sleepinggenius2@users.noreply.github.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package cmd

import (
	"bytes"
	"fmt"
	"go/format"
	"io"
	"log"
	"os"
	"path"
	"strings"

	"github.com/pkg/errors"
	"github.com/sleepinggenius2/gosmi"
	"github.com/sleepinggenius2/gosmi/models"
	"github.com/sleepinggenius2/gosmi/types"
	"github.com/spf13/cobra"
)

const fileHeader = `// Code generated by mib2go. DO NOT EDIT.
package %s

import (
	"github.com/sleepinggenius2/gosmi/models"
	"github.com/sleepinggenius2/gosmi/types"
)

`
const allowedNodeKinds = types.NodeScalar | types.NodeTable | types.NodeRow | types.NodeColumn | types.NodeNotification

var (
	outDir      string
	outFilename string
	packageName string
	paths       []string
)

// generateCmd represents the generate command
var generateCmd = &cobra.Command{
	Use:   "generate",
	Short: "Generates Go files from MIBs",
	Long:  `Generates Go files from MIBs.`,
	Args:  cobra.MinimumNArgs(1),
	RunE: func(cmd *cobra.Command, args []string) (err error) {
		gosmi.Init()
		defer gosmi.Exit()

		for _, path := range paths {
			gosmi.AppendPath(path)
		}

		var out *os.File
		if outFilename == "-" {
			out = os.Stdout
		} else if outFilename != "" {
			var err error
			out, err = os.OpenFile(outFilename, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
			if err != nil {
				return errors.Wrapf(err, "Opening file %s", outFilename)
			}
			defer out.Close()
			log.Printf("Outputting to %s\n", outFilename)
		}

		typesMap := make(map[string]*models.Type)

		for i, arg := range args {
			moduleName, err := gosmi.LoadModule(arg)
			if err != nil {
				return errors.Wrapf(err, "Loading module %s", arg)
			}

			module, err := gosmi.GetModule(moduleName)
			if err != nil {
				return errors.Wrapf(err, "Getting module %s", moduleName)
			}

			fileBuf := &bytes.Buffer{}
			if out == nil || i == 0 {
				fmt.Fprintf(fileBuf, fileHeader, packageName)
			}

			generateMibFile(module, fileBuf, typesMap)

			outFile := out
			if outFile == nil {
				filename := path.Join(outDir, strings.ToLower(module.Name)+".go")
				outFile, err = os.OpenFile(filename, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
				if err != nil {
					return errors.Wrapf(err, "Opening file %s", filename)
				}
				defer outFile.Close()
				log.Printf("Outputting to %s\n", filename)
			}

			err = writeGoFile(outFile, fileBuf.Bytes())
			if err != nil {
				return errors.Wrap(err, "Writing module Go file")
			}
		}

		typesBuf := &bytes.Buffer{}
		if out == nil {
			fmt.Fprintf(typesBuf, fileHeader, packageName)
		}

		for _, nodeType := range typesMap {
			generateTypeBlock(typesBuf, nodeType, true)
		}

		outFile := out
		if outFile == nil {
			filename := path.Join(outDir, "types.go")
			outFile, err = os.OpenFile(filename, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
			if err != nil {
				return errors.Wrapf(err, "Opening file %s", filename)
			}
			defer outFile.Close()
			log.Printf("Outputting to %s\n", filename)
		}

		err = writeGoFile(outFile, typesBuf.Bytes())
		if err != nil {
			return errors.Wrap(err, "Writing types Go file")
		}

		return nil
	},
}

func formatModuleName(moduleName string) (formattedName string) {
	parts := strings.Split(moduleName, "-")
	for _, part := range parts {
		formattedName += strings.ToUpper(part[:1]) + strings.ToLower(part[1:])
	}
	return
}

func formatModuleVarName(moduleName string) (formattedName string) {
	formattedModuleName := formatModuleName(moduleName)
	return strings.ToLower(formattedModuleName[:1]) + formattedModuleName[1:] + "Module"
}

func formatNodeName(nodeName string) (formattedName string) {
	return strings.ToUpper(nodeName[:1]) + nodeName[1:]
}

func formatNodeVarName(nodeName string) (formattedName string) {
	return strings.ToLower(nodeName[:1]) + nodeName[1:] + "Node"
}

func generateMibFile(module gosmi.SmiModule, buf io.Writer, typesMap map[string]*models.Type) {
	formattedModuleName := formatModuleName(module.Name)
	formattedModuleVarName := formatModuleVarName(module.Name)
	nodes := module.GetNodes()

	fmt.Fprintf(buf, "type %s struct {\n", formattedModuleVarName)
	for _, node := range nodes {
		if node.Kind&allowedNodeKinds > 0 {
			fmt.Fprintf(buf, "\t%s\tmodels.%sNode\n", formatNodeName(node.Name), node.Kind)
		}
	}
	fmt.Fprintf(buf, "}\n\n")

	fmt.Fprintf(buf, "var %s = %s {\n", formattedModuleName, formattedModuleVarName)
	for _, node := range nodes {
		if node.Kind&allowedNodeKinds > 0 {
			fmt.Fprintf(buf, "\t%s:\t%s,\n", formatNodeName(node.Name), formatNodeVarName(node.Name))
		}
	}
	fmt.Fprintf(buf, "}\n\n")

	for _, node := range nodes {
		if node.Kind&allowedNodeKinds > 0 {
			fmt.Fprintf(buf, "var %s = models.%sNode{\n", formatNodeVarName(node.Name), node.Kind)
			fmt.Fprintf(buf, "\tBaseNode: models.BaseNode{\n")
			fmt.Fprintf(buf, "\t\tName: %q,\n", node.Name)
			oid := node.Oid
			oidFormatted := node.RenderNumeric()
			oidLen := node.OidLen
			if node.Kind == types.NodeScalar {
				oid = append(oid, 0)
				oidFormatted += ".0"
				oidLen++
			}
			fmt.Fprintf(buf, "\t\tOid: %#v,\n", oid)
			fmt.Fprintf(buf, "\t\tOidFormatted: %q,\n", oidFormatted)
			fmt.Fprintf(buf, "\t\tOidLen: %d,\n", oidLen)
			fmt.Fprintf(buf, "\t},\n")

			switch node.Kind {
			case types.NodeColumn, types.NodeScalar:
				switch node.Type.Name {
				case "Integer32", "OctetString", "ObjectIdentifier", "Unsigned32", "Integer64", "Unsigned64", "Enumeration", "Bits":
					generateTypeBlock(buf, node.Type, false)
				default:
					if _, ok := typesMap[node.Type.Name]; !ok {
						typesMap[node.Type.Name] = node.Type
					}
					fmt.Fprintf(buf, "\tType: %sType,\n", formatNodeName(node.Type.Name))
				}
			case types.NodeTable:
				fmt.Fprintf(buf, "\tRow: %s,\n", formatNodeVarName(node.GetRow().Name))
			case types.NodeRow:
				fmt.Fprintf(buf, "\tColumns: []models.ColumnNode{\n")
				_, columnOrder := node.GetColumns()
				for _, column := range columnOrder {
					fmt.Fprintf(buf, "\t\t%s,\n", formatNodeVarName(column))
				}
				fmt.Fprintf(buf, "\t},\n")
				fmt.Fprintf(buf, "\tIndex: []models.ColumnNode{\n")
				indices := node.GetIndex()
				for _, index := range indices {
					fmt.Fprintf(buf, "\t\t%s,\n", formatNodeVarName(index.Name))
				}
				fmt.Fprintf(buf, "\t},\n")
			case types.NodeNotification:
				objects := node.GetNotificationObjects()
				fmt.Fprintf(buf, "\tObjects: []models.ScalarNode{\n")
				for _, object := range objects {
					if object.Kind == types.NodeScalar {
						fmt.Fprintf(buf, "\t\t%s,\n", formatNodeVarName(object.Name))
					} else {
						fmt.Fprintf(buf, "\t\tmodels.ScalarNode(%s),\n", formatNodeVarName(object.Name))
					}
				}
				fmt.Fprintf(buf, "\t},\n")
			}

			fmt.Fprintf(buf, "}\n")
		}
	}
}

func generateTypeBlock(buf io.Writer, t *models.Type, asVar bool) {
	if asVar {
		fmt.Fprintf(buf, "var %sType = models.Type{\n", formatNodeName(t.Name))
	} else {
		fmt.Fprintf(buf, "Type: models.Type{\n")
	}
	fmt.Fprintf(buf, "\tBaseType: types.BaseType%s,\n", t.BaseType)
	if t.Enum != nil {
		fmt.Fprintf(buf, "\tEnum: &models.Enum{\n")
		fmt.Fprintf(buf, "\t\tBaseType: types.BaseType%s,\n", t.Enum.BaseType)
		fmt.Fprintf(buf, "\t\tValues: []models.NamedNumber{\n")
		for _, value := range t.Enum.Values {
			fmt.Fprintf(buf, "\t\t\t%#v,\n", value)
		}
		fmt.Fprintf(buf, "\t\t},\n")
		fmt.Fprintf(buf, "\t},\n")
	}
	if t.Format != "" {
		fmt.Fprintf(buf, "\tFormat: %q,\n", t.Format)
	}
	fmt.Fprintf(buf, "\tName: %q,\n", t.Name)
	if len(t.Ranges) > 0 {
		fmt.Fprintf(buf, "\tRanges: []models.Range{\n")
		for _, typeRange := range t.Ranges {
			fmt.Fprintf(buf, "\t\tmodels.Range{BaseType: types.BaseType%s, MinValue: %#v, MaxValue: %#v},\n",
				typeRange.BaseType,
				typeRange.MinValue,
				typeRange.MaxValue,
			)
		}
		fmt.Fprintf(buf, "\t},\n")
	}
	if t.Units != "" {
		fmt.Fprintf(buf, "\tUnits: %q,\n", t.Units)
	}
	if asVar {
		fmt.Fprintf(buf, "}\n\n")
	} else {
		fmt.Fprintf(buf, "},\n")
	}
}

func writeGoFile(out io.Writer, b []byte) error {
	formattedSource, err := format.Source(b)
	if err != nil {
		return errors.Wrap(err, "Generating formatted source")
	}

	_, err = out.Write(formattedSource)
	if err != nil {
		return errors.Wrap(err, "Writing file")
	}

	return nil
}

func init() {
	RootCmd.AddCommand(generateCmd)

	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// generateCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	generateCmd.Flags().StringVarP(&outDir, "dir", "d", ".", "Output directory")
	generateCmd.Flags().StringVarP(&outFilename, "output", "o", "", "Output filename, use - for stdout")
	generateCmd.Flags().StringVarP(&packageName, "package", "p", "mibs", "The package for the generated file")
	generateCmd.Flags().StringSliceVarP(&paths, "path", "M", []string{}, "Path(s) to add to MIB search path")
}
<|endoftext|>


<commit_before>// Copyright 2014 Volker Dobler.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"fmt"
	"log"
	"time"

	"github.com/vdobler/ht"
	"github.com/vdobler/ht/hist"
)

var cmdBench = &Command{
	Run:   runBench,
	Usage: "bench [-warmup n] [-count n] [-pause d] [-concurrent n] <suite.ht>...",
	Help: `
Benchmark the tests by running count many requests seperated by pause
after doing warmup many requests which are not measured.
`,
}

func init() {
	cmdBench.Flag.IntVar(&bcountFlag, "count", 17,
		"number of requests to measure")
	cmdBench.Flag.IntVar(&concurrentFlag, "concurrent", 1,
		"concurrency level")
	cmdBench.Flag.IntVar(&warmupFlag, "warmup", 3,
		"number of request to do before actual mesurement")
	cmdBench.Flag.DurationVar(&pauseFlag, "pause", 10*time.Millisecond,
		"duration to pause between requests")
}

var (
	bcountFlag     int
	warmupFlag     int
	pauseFlag      time.Duration
	concurrentFlag int
)

func runBench(cmd *Command, suites []*ht.Suite) {
	println(warmupFlag, bcountFlag, concurrentFlag)
	for s, suite := range suites {
		result := suite.ExecuteSetup()
		if result.Status != ht.Pass {
			log.Printf("Suite %d %q: Setup failure %q", s, suite.Name,
				result.Error.Error())
			continue
		}
		for _, test := range suite.Tests {
			if test.Poll.Max < 0 {
				continue
			}
			results := test.Benchmark(suite.Variables,
				warmupFlag, bcountFlag, pauseFlag, concurrentFlag)
			fmt.Printf("Suite: %s; Test: %s\n", suite.Name, test.Name)
			printBenchmarkSummary(results)
		}
		suite.ExecuteTeardown()
	}
}

func printBenchmarkSummary(results []ht.TestResult) {
	max := 0
	for _, r := range results {
		if d := int(r.Duration / 1e6); d > max {
			max = d
		}
	}
	h := hist.NewLogHist(7, max)
	for _, r := range results {
		h.Add(int(r.Duration / 1e6))
	}

	ps := []float64{0, 0.25, 0.50, 0.75, 0.80, 0.85, 0.90, 0.95, 0.97, 0.98, 0.99, 1}
	cps := make([]int, len(ps))
	for i, p := range ps {
		cps[i] = int(100*p + 0.2)
	}

	fmt.Printf("Percentil %4d \n", cps)
	fmt.Printf("Resp.Time %4d  [ms]\n", h.Percentils(ps))
}
<commit_msg>Make cmd/ht work with refactored code<commit_after>// Copyright 2014 Volker Dobler.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"fmt"
	"log"
	"time"

	"github.com/vdobler/ht"
	"github.com/vdobler/ht/hist"
)

var cmdBench = &Command{
	Run:   runBench,
	Usage: "bench [-warmup n] [-count n] [-pause d] [-concurrent n] <suite.ht>...",
	Help: `
Benchmark the tests by running count many requests seperated by pause
after doing warmup many requests which are not measured.
`,
}

func init() {
	cmdBench.Flag.IntVar(&bcountFlag, "count", 17,
		"number of requests to measure")
	cmdBench.Flag.IntVar(&concurrentFlag, "concurrent", 1,
		"concurrency level")
	cmdBench.Flag.IntVar(&warmupFlag, "warmup", 3,
		"number of request to do before actual mesurement")
	cmdBench.Flag.DurationVar(&pauseFlag, "pause", 10*time.Millisecond,
		"duration to pause between requests")
}

var (
	bcountFlag     int
	warmupFlag     int
	pauseFlag      time.Duration
	concurrentFlag int
)

func runBench(cmd *Command, suites []*ht.Suite) {
	println(warmupFlag, bcountFlag, concurrentFlag)
	for s, suite := range suites {
		result := suite.ExecuteSetup()
		if result.Status != ht.Pass {
			log.Printf("Suite %d %q: Setup failure %q", s, suite.Name,
				result.Error.Error())
			continue
		}
		for _, test := range suite.Tests {
			if test.Poll.Max < 0 {
				continue
			}
			results := test.Benchmark(suite.Variables,
				warmupFlag, bcountFlag, pauseFlag, concurrentFlag)
			fmt.Printf("Suite: %s; Test: %s\n", suite.Name, test.Name)
			printBenchmarkSummary(results)
		}
		suite.ExecuteTeardown()
	}
}

func printBenchmarkSummary(results []ht.Test) {
	max := 0
	for _, r := range results {
		if d := int(r.Duration / 1e6); d > max {
			max = d
		}
	}
	h := hist.NewLogHist(7, max)
	for _, r := range results {
		h.Add(int(r.Duration / 1e6))
	}

	ps := []float64{0, 0.25, 0.50, 0.75, 0.80, 0.85, 0.90, 0.95, 0.97, 0.98, 0.99, 1}
	cps := make([]int, len(ps))
	for i, p := range ps {
		cps[i] = int(100*p + 0.2)
	}

	fmt.Printf("Percentil %4d \n", cps)
	fmt.Printf("Resp.Time %4d  [ms]\n", h.Percentils(ps))
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"path/filepath"

	"github.com/hoffie/larasync/repository"
)

// addAction adds the current state of the given file or directory to the repository.
func (d *Dispatcher) addAction() int {
	numArgs := len(d.flags.Args())
	if numArgs < 1 {
		fmt.Fprint(d.stderr, "No items specified\n")
		return 1
	}
	absPath, err := filepath.Abs(d.flags.Arg(0))
	if err != nil {
		fmt.Fprint(d.stderr, "Unable to resolve path\n")
		return 1
	}
	root, err := repository.GetRoot(absPath)
	if err != nil {
		fmt.Fprint(d.stderr, "Unable to find the repository root\n")
		return 1
	}
	r := repository.New(root)
	err = r.AddItem(absPath)
	if err != nil {
		fmt.Fprint(d.stderr, "Unable to add the given item to the repository\n")
		return 1
	}
	return 0
}
<commit_msg>cmd/lara add: more verbose error message<commit_after>package main

import (
	"fmt"
	"path/filepath"

	"github.com/hoffie/larasync/repository"
)

// addAction adds the current state of the given file or directory to the repository.
func (d *Dispatcher) addAction() int {
	numArgs := len(d.flags.Args())
	if numArgs < 1 {
		fmt.Fprint(d.stderr, "No items specified\n")
		return 1
	}
	absPath, err := filepath.Abs(d.flags.Arg(0))
	if err != nil {
		fmt.Fprint(d.stderr, "Unable to resolve path\n")
		return 1
	}
	root, err := repository.GetRoot(absPath)
	if err != nil {
		fmt.Fprint(d.stderr, "Unable to find the repository root\n")
		return 1
	}
	r := repository.New(root)
	err = r.AddItem(absPath)
	if err != nil {
		fmt.Fprintf(d.stderr, "Unable to add the given item to the repository (%s)\n", err)
		return 1
	}
	return 0
}
<|endoftext|>


<commit_before>// Copyright © 2017 uxbh
// This file is part of gitlab.com/uxbh/ztdns.

package cmd

import (
	"os"

	log "github.com/Sirupsen/logrus"
	"github.com/spf13/cobra"
)

// mkconfigCmd represents the mkconfig command
var mkconfigCmd = &cobra.Command{
	Use:   "mkconfig",
	Short: "Make a new config file",
	Long: `mkconfig (ztdns mkconfig) creates a new configuation file.
If you do not specify a filename the default is ./.ztdns.toml

Example: ztdns mkconfig .filenames.toml`,
	Run: func(cmd *cobra.Command, args []string) {
		filename := "./.ztdns.toml"
		if len(args) > 0 {
			filename = args[0]
		}
		if _, err := os.Stat(filename); os.IsNotExist(err) {
			log.Printf("Creating new config file in %s", filename)
			file, err := os.Create(filename)
			if err != nil {
				log.Fatalf("Could not create file: %s", err.Error())
			}
			defer file.Close()
			file.WriteString(`# Configuration file for ztDNS

suffix = "zt"
port = 53
interface = "zt0"

# This section contains information related to your ZeroTier config
[ZT]
# API is used to contact the ZeroTier controller API service.
API = ""
# Network is your ZeroTier network ID.
Network = ""
# URL is the url of the ZeroTier controller API
URL = "https://my.zerotier.com/api"
`)
		}
	},
}

func init() {
	RootCmd.AddCommand(mkconfigCmd)
}
<commit_msg>fix example text<commit_after>// Copyright © 2017 uxbh
// This file is part of gitlab.com/uxbh/ztdns.

package cmd

import (
	"os"

	log "github.com/Sirupsen/logrus"
	"github.com/spf13/cobra"
)

// mkconfigCmd represents the mkconfig command
var mkconfigCmd = &cobra.Command{
	Use:   "mkconfig",
	Short: "Make a new config file",
	Long: `mkconfig (ztdns mkconfig) creates a new configuation file.
If you do not specify a filename the default is ./.ztdns.toml

Example: ztdns mkconfig [.filename.toml]`,
	Run: func(cmd *cobra.Command, args []string) {
		filename := "./.ztdns.toml"
		if len(args) > 0 {
			filename = args[0]
		}
		if _, err := os.Stat(filename); os.IsNotExist(err) {
			log.Printf("Creating new config file in %s", filename)
			file, err := os.Create(filename)
			if err != nil {
				log.Fatalf("Could not create file: %s", err.Error())
			}
			defer file.Close()
			file.WriteString(`# Configuration file for ztDNS

suffix = "zt"
port = 53
interface = "zt0"

# This section contains information related to your ZeroTier config
[ZT]
# API is used to contact the ZeroTier controller API service.
API = ""
# Network is your ZeroTier network ID.
Network = ""
# URL is the url of the ZeroTier controller API
URL = "https://my.zerotier.com/api"
`)
		}
	},
}

func init() {
	RootCmd.AddCommand(mkconfigCmd)
}
<|endoftext|>


<commit_before>package main

import (
	"log"
	"os"

	"github.com/pressly/stackup"
)

// usage prints help for an arg and exits.
func usage(conf *stackup.Supfile, arg int) {
	log.Println("Usage: sup <network> <target/command>\n")
	switch arg {
	case 1:
		// <network> missing, print available hosts.
		log.Println("Available host groups (from ./Supfile):")
		for name, network := range conf.Networks {
			log.Printf("- %v\n", name)
			for _, host := range network.Hosts {
				log.Printf("   - %v\n", host)
			}
		}
	case 2:
		// <target/command> not found or missing,
		// print available targets/commands.
		log.Println("Available targets (from Supfile):")
		for name, commands := range conf.Targets {
			log.Printf("- %v", name)
			for _, cmd := range commands {
				log.Printf("\t%v\n", cmd)
			}
		}
		log.Println()
		log.Println("Available commands (from Supfile):")
		for name, cmd := range conf.Commands {
			log.Printf("- %v\t%v", name, cmd.Desc)
		}
	}
	os.Exit(1)
}

// parseArgs parses os.Args and returns network and commands to be run.
// On error, it prints usage and exits.
func parseArgsOrDie(conf *stackup.Supfile) (*stackup.Network, []*stackup.Command) {
	var commands []*stackup.Command

	// Check for the first argument first
	if len(os.Args) < 2 {
		usage(conf, len(os.Args))
	}
	// Does the <network> exist?
	network, ok := conf.Networks[os.Args[1]]
	if !ok {
		log.Printf("Unknown network \"%v\"\n\n", os.Args[1])
		usage(conf, 1)
	}

	// Does <network> have any hosts?
	if len(network.Hosts) == 0 {
		log.Printf("No hosts specified for network \"%v\"", os.Args[1])
		usage(conf, 1)
	}

	// Check for the second argument
	if len(os.Args) < 3 {
		usage(conf, len(os.Args))
	}
	// Does the <target/command> exist?
	target, isTarget := conf.Targets[os.Args[2]]
	if isTarget {
		// It's the target. Loop over its commands.
		for _, cmd := range target {
			// Does the target's command exist?
			command, isCommand := conf.Commands[cmd]
			if !isCommand {
				log.Printf("Unknown command \"%v\" (from target \"%v\": %v)\n\n", cmd, os.Args[2], target)
				usage(conf, 2)
			}
			command.Name = cmd
			commands = append(commands, &command)
		}
	} else {
		// It's probably a command. Does it exist?
		command, isCommand := conf.Commands[os.Args[2]]
		if !isCommand {
			// Not a target, nor command.
			log.Printf("Unknown target/command \"%v\"\n\n", os.Args[2])
			usage(conf, 2)
		}
		command.Name = os.Args[2]
		commands = append(commands, &command)
	}

	// Check for extra arguments
	if len(os.Args) != 3 {
		usage(conf, len(os.Args))
	}

	return &network, commands
}

func main() {
	// Parse configuration file in current directory.
	// TODO: -f flag to pass custom file.
	conf, err := stackup.NewSupfile("./Supfile")
	if err != nil {
		log.Fatal(err)
	}

	// Parse network and commands to be run from os.Args.
	network, commands := parseArgsOrDie(conf)

	// Create new Stackup app.
	app, err := stackup.New(conf)
	if err != nil {
		log.Fatal(err)
	}

	// Run all the commands in the given network.
	err = app.Run(network, commands...)
	if err != nil {
		log.Fatal(err)
	}
}
<commit_msg>Fix typo<commit_after>package main

import (
	"log"
	"os"

	"github.com/pressly/stackup"
)

// usage prints help for an arg and exits.
func usage(conf *stackup.Supfile, arg int) {
	log.Println("Usage: sup <network> <target/command>\n")
	switch arg {
	case 1:
		// <network> missing, print available hosts.
		log.Println("Available networks (from ./Supfile):")
		for name, network := range conf.Networks {
			log.Printf("- %v\n", name)
			for _, host := range network.Hosts {
				log.Printf("   - %v\n", host)
			}
		}
	case 2:
		// <target/command> not found or missing,
		// print available targets/commands.
		log.Println("Available targets (from Supfile):")
		for name, commands := range conf.Targets {
			log.Printf("- %v", name)
			for _, cmd := range commands {
				log.Printf("\t%v\n", cmd)
			}
		}
		log.Println()
		log.Println("Available commands (from Supfile):")
		for name, cmd := range conf.Commands {
			log.Printf("- %v\t%v", name, cmd.Desc)
		}
	}
	os.Exit(1)
}

// parseArgs parses os.Args and returns network and commands to be run.
// On error, it prints usage and exits.
func parseArgsOrDie(conf *stackup.Supfile) (*stackup.Network, []*stackup.Command) {
	var commands []*stackup.Command

	// Check for the first argument first
	if len(os.Args) < 2 {
		usage(conf, len(os.Args))
	}
	// Does the <network> exist?
	network, ok := conf.Networks[os.Args[1]]
	if !ok {
		log.Printf("Unknown network \"%v\"\n\n", os.Args[1])
		usage(conf, 1)
	}

	// Does <network> have any hosts?
	if len(network.Hosts) == 0 {
		log.Printf("No hosts specified for network \"%v\"", os.Args[1])
		usage(conf, 1)
	}

	// Check for the second argument
	if len(os.Args) < 3 {
		usage(conf, len(os.Args))
	}
	// Does the <target/command> exist?
	target, isTarget := conf.Targets[os.Args[2]]
	if isTarget {
		// It's the target. Loop over its commands.
		for _, cmd := range target {
			// Does the target's command exist?
			command, isCommand := conf.Commands[cmd]
			if !isCommand {
				log.Printf("Unknown command \"%v\" (from target \"%v\": %v)\n\n", cmd, os.Args[2], target)
				usage(conf, 2)
			}
			command.Name = cmd
			commands = append(commands, &command)
		}
	} else {
		// It's probably a command. Does it exist?
		command, isCommand := conf.Commands[os.Args[2]]
		if !isCommand {
			// Not a target, nor command.
			log.Printf("Unknown target/command \"%v\"\n\n", os.Args[2])
			usage(conf, 2)
		}
		command.Name = os.Args[2]
		commands = append(commands, &command)
	}

	// Check for extra arguments
	if len(os.Args) != 3 {
		usage(conf, len(os.Args))
	}

	return &network, commands
}

func main() {
	// Parse configuration file in current directory.
	// TODO: -f flag to pass custom file.
	conf, err := stackup.NewSupfile("./Supfile")
	if err != nil {
		log.Fatal(err)
	}

	// Parse network and commands to be run from os.Args.
	network, commands := parseArgsOrDie(conf)

	// Create new Stackup app.
	app, err := stackup.New(conf)
	if err != nil {
		log.Fatal(err)
	}

	// Run all the commands in the given network.
	err = app.Run(network, commands...)
	if err != nil {
		log.Fatal(err)
	}
}
<|endoftext|>


<commit_before>// Copyright 2018 the u-root Authors. All rights reserved
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import "github.com/u-root/u-root/pkg/sos"

func main() {
	sos.StartServer(sos.NewSosService())
}
<commit_msg>sos: brings up locahost before starting the server<commit_after>// Copyright 2018 the u-root Authors. All rights reserved
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"log"
	"os/exec"

	"github.com/u-root/u-root/pkg/sos"
)

func main() {
	if o, err := exec.Command("ip", "link", "set", "dev", "lo", "up").CombinedOutput(); err != nil {
		log.Fatalf("ip link set dev lo: %v (%v)", string(o), err)
	}
	sos.StartServer(sos.NewSosService())
}
<|endoftext|>


<commit_before>// Copyright (c) 2018 Intel Corporation
//
// 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 checkpoint

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

	"github.com/intel/multus-cni/logging"
	"github.com/intel/multus-cni/types"
	v1 "k8s.io/api/core/v1"
)

const (
	checkPointfile = "/var/lib/kubelet/device-plugins/kubelet_internal_checkpoint"
)

// PodDevicesEntry maps PodUID, resource name and allocated device id
type PodDevicesEntry struct {
	PodUID        string
	ContainerName string
	ResourceName  string
	DeviceIDs     []string
	AllocResp     []byte
}

type checkpointData struct {
	PodDeviceEntries  []PodDevicesEntry
	RegisteredDevices map[string][]string
}

type checkpointFileData struct {
	Data     checkpointData
	Checksum uint64
}

type checkpoint struct {
	fileName   string
	podEntires []PodDevicesEntry
}

// GetCheckpoint returns an instance of Checkpoint
func GetCheckpoint() (types.ResourceClient, error) {
	logging.Debugf("GetCheckpoint(): invoked")
	return getCheckpoint(checkPointfile)
}

func getCheckpoint(filePath string) (types.ResourceClient, error) {
	cp := &checkpoint{fileName: filePath}
	err := cp.getPodEntries()
	if err != nil {
		return nil, err
	}
	logging.Debugf("getCheckpoint(): created checkpoint instance with file: %s", filePath)
	return cp, nil
}

// getPodEntries gets all Pod device allocation entries from checkpoint file
func (cp *checkpoint) getPodEntries() error {

	cpd := &checkpointFileData{}
	rawBytes, err := ioutil.ReadFile(cp.fileName)
	if err != nil {
		return logging.Errorf("getPodEntries(): error reading file %s\n%v\n", checkPointfile, err)
	}

	if err = json.Unmarshal(rawBytes, cpd); err != nil {
		return logging.Errorf("getPodEntries(): error unmarshalling raw bytes %v", err)
	}

	cp.podEntires = cpd.Data.PodDeviceEntries
	logging.Debugf("getPodEntries(): podEntires %+v", cp.podEntires)
	return nil
}

// GetComputeDeviceMap returns an instance of a map of ResourceInfo
func (cp *checkpoint) GetPodResourceMap(pod *v1.Pod) (map[string]*types.ResourceInfo, error) {
	podID := string(pod.UID)
	resourceMap := make(map[string]*types.ResourceInfo)

	if podID == "" {
		return nil, logging.Errorf("GetPodResourceMap(): invalid Pod cannot be empty")
	}

	for _, pod := range cp.podEntires {
		if pod.PodUID == podID {
			entry, ok := resourceMap[pod.ResourceName]
			if ok {
				// already exists; append to it
				entry.DeviceIDs = append(entry.DeviceIDs, pod.DeviceIDs...)
			} else {
				// new entry
				resourceMap[pod.ResourceName] = &types.ResourceInfo{DeviceIDs: pod.DeviceIDs}
			}
		}
	}
	return resourceMap, nil
}
<commit_msg>Added up to 96% coverage for checkpoint.go<commit_after>// Copyright (c) 2018 Intel Corporation
//
// 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 checkpoint

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

	"github.com/intel/multus-cni/logging"
	"github.com/intel/multus-cni/types"
	v1 "k8s.io/api/core/v1"
)

const (
	checkPointfile = "/var/lib/kubelet/device-plugins/kubelet_internal_checkpoint"
)

// PodDevicesEntry maps PodUID, resource name and allocated device id
type PodDevicesEntry struct {
	PodUID        string
	ContainerName string
	ResourceName  string
	DeviceIDs     []string
	AllocResp     []byte
}

type checkpointData struct {
	PodDeviceEntries  []PodDevicesEntry
	RegisteredDevices map[string][]string
}

type checkpointFileData struct {
	Data     checkpointData
	Checksum uint64
}

type checkpoint struct {
	fileName   string
	podEntires []PodDevicesEntry
}

// GetCheckpoint returns an instance of Checkpoint
func GetCheckpoint() (types.ResourceClient, error) {
	logging.Debugf("GetCheckpoint(): invoked")
	return getCheckpoint(checkPointfile)
}

func getCheckpoint(filePath string) (types.ResourceClient, error) {
	cp := &checkpoint{fileName: filePath}
	err := cp.getPodEntries()
	if err != nil {
		return nil, err
	}
	logging.Debugf("getCheckpoint(): created checkpoint instance with file: %s", filePath)
	return cp, nil
}

// getPodEntries gets all Pod device allocation entries from checkpoint file
func (cp *checkpoint) getPodEntries() error {

	cpd := &checkpointFileData{}
	rawBytes, err := ioutil.ReadFile(cp.fileName)
	if err != nil {
		return logging.Errorf("getPodEntries(): error reading file %s\n%v\n", checkPointfile, err)
	}

	if err = json.Unmarshal(rawBytes, cpd); err != nil {
		return logging.Errorf("getPodEntries(): error unmarshalling raw bytes %v", err)
	}

	cp.podEntires = cpd.Data.PodDeviceEntries
	logging.Debugf("getPodEntries(): podEntires %+v", cp.podEntires)
	return nil
}

// GetComputeDeviceMap returns an instance of a map of ResourceInfo
func (cp *checkpoint) GetPodResourceMap(pod *v1.Pod) (map[string]*types.ResourceInfo, error) {
	podID := string(pod.UID)
	resourceMap := make(map[string]*types.ResourceInfo)

	if podID == "" {
		return nil, logging.Errorf("GetPodResourceMap(): invalid Pod cannot be empty")
	}
	for _, pod := range cp.podEntires {
		if pod.PodUID == podID {
			entry, ok := resourceMap[pod.ResourceName]
			if ok {
				// already exists; append to it
				entry.DeviceIDs = append(entry.DeviceIDs, pod.DeviceIDs...)
			} else {
				// new entry
				resourceMap[pod.ResourceName] = &types.ResourceInfo{DeviceIDs: pod.DeviceIDs}
			}
		}
	}
	return resourceMap, nil
}
<|endoftext|>


<commit_before>package server

var season2R7Rep = []HallOfFameEntry{
	{
		Rank:        1,
		Racer:       "mgln",
		ProfileName: "mgln",
		Time:        2716,
		Date:        "2022-05-22",
		Proof:       "https://www.twitch.tv/videos/1490540193",
		Site:        "Twitch",
	},

	{
		Rank:        2,
		Racer:       "Finalkids",
		ProfileName: "Finalkids",
		Time:        2738,
		Date:        "2022-03-17",
		Proof:       "https://www.youtube.com/watch?v=_FMJjWuz9a0",
		Site:        "Youtube",
	},

	{
		Rank:        3,
		Racer:       "tayu",
		ProfileName: "tayu",
		Time:        2888,
		Date:        "2021-08-07",
		Proof:       "https://www.youtube.com/watch?v=Y9-05jneA24",
		Site:        "YouTube",
	},

	{
		Rank:        4,
		Racer:       "KiraKeepKool",
		ProfileName: "KiraKeepKool",
		Time:        2892,
		Date:        "2022-05-13",
		Proof:       "https://www.twitch.tv/videos/1482375296",
		Site:        "Twitch",
	},

	{
		Rank:        5,
		Racer:       "leo_ze_tron",
		ProfileName: "leo_ze_tron",
		Time:        2926,
		Date:        "2022-04-14",
		Proof:       "https://www.twitch.tv/videos/1455280672",
		Site:        "Twitch",
	},

	{
		Rank:        6,
		Racer:       "sisuka",
		ProfileName: "sisuka",
		Time:        2946,
		Date:        "2022-05-17",
		Proof:       "https://www.twitch.tv/videos/1486409779",
		Site:        "Twitch",
	},

	{
		Rank:        7,
		Racer:       "Cyber_1",
		ProfileName: "Cyber_1",
		Time:        2958,
		Date:        "2022-08-23",
		Proof:       "https://www.twitch.tv/videos/1570091193",
		Site:        "Twitch",
	},

	{
		Rank:        8,
		Racer:       "YuCaesar",
		ProfileName: "YuCaesar",
		Time:        2965,
		Date:        "2022-04-26",
		Proof:       "https://www.twitch.tv/videos/1467714564",
		Site:        "Twitch",
	},

	{
		Rank:        9,
		Racer:       "Adrayon",
		ProfileName: "Adrayon",
		Time:        2992,
		Date:        "2022-06-12",
		Proof:       "https://www.twitch.tv/videos/1501950411",
		Site:        "Twitch",
	},

	{
		Rank:        10,
		Racer:       "thereisnofuture",
		ProfileName: "thereisnofuture",
		Time:        3011,
		Date:        "2022-03-21",
		Proof:       "https://www.twitch.tv/videos/1432566879",
		Site:        "Twitch",
	},
}
<commit_msg>Update season2Rep.go (#80)<commit_after>package server

var season2R7Rep = []HallOfFameEntry{
	{
		Rank:        1,
		Racer:       "mgln",
		ProfileName: "mgln",
		Time:        2716,
		Date:        "2022-05-22",
		Proof:       "https://www.twitch.tv/videos/1490540193",
		Site:        "Twitch",
	},

	{
		Rank:        2,
		Racer:       "Finalkids",
		ProfileName: "Finalkids",
		Time:        2738,
		Date:        "2022-03-17",
		Proof:       "https://www.youtube.com/watch?v=_FMJjWuz9a0",
		Site:        "YouTube",
	},

	{
		Rank:        3,
		Racer:       "tayu",
		ProfileName: "tayu",
		Time:        2888,
		Date:        "2021-08-07",
		Proof:       "https://www.youtube.com/watch?v=Y9-05jneA24",
		Site:        "YouTube",
	},

	{
		Rank:        4,
		Racer:       "KiraKeepKool",
		ProfileName: "KiraKeepKool",
		Time:        2892,
		Date:        "2022-05-13",
		Proof:       "https://www.twitch.tv/videos/1482375296",
		Site:        "Twitch",
	},

	{
		Rank:        5,
		Racer:       "leo_ze_tron",
		ProfileName: "leo_ze_tron",
		Time:        2926,
		Date:        "2022-04-14",
		Proof:       "https://www.twitch.tv/videos/1455280672",
		Site:        "Twitch",
	},

	{
		Rank:        6,
		Racer:       "sisuka",
		ProfileName: "sisuka",
		Time:        2946,
		Date:        "2022-05-17",
		Proof:       "https://www.twitch.tv/videos/1486409779",
		Site:        "Twitch",
	},

	{
		Rank:        7,
		Racer:       "Cyber_1",
		ProfileName: "Cyber_1",
		Time:        2958,
		Date:        "2022-08-23",
		Proof:       "https://www.twitch.tv/videos/1570091193",
		Site:        "Twitch",
	},

	{
		Rank:        8,
		Racer:       "YuCaesar",
		ProfileName: "YuCaesar",
		Time:        2965,
		Date:        "2022-04-26",
		Proof:       "https://www.twitch.tv/videos/1467714564",
		Site:        "Twitch",
	},

	{
		Rank:        9,
		Racer:       "Adrayon",
		ProfileName: "Adrayon",
		Time:        2992,
		Date:        "2022-06-12",
		Proof:       "https://www.twitch.tv/videos/1501950411",
		Site:        "Twitch",
	},

	{
		Rank:        10,
		Racer:       "thereisnofuture",
		ProfileName: "thereisnofuture",
		Time:        3011,
		Date:        "2022-03-21",
		Proof:       "https://www.twitch.tv/videos/1432566879",
		Site:        "Twitch",
	},
}
<|endoftext|>