<commit_before>package kube

import (
	"fmt"

	"k8s.io/client-go/rest"
	"k8s.io/client-go/tools/clientcmd"
)

// Config will return a rest.Config for communicating with the Kubernetes API server.
// If apiServerHost is specified, a config without authentication that is configured
// to talk to the apiServerHost URL will be returned. Else, the in-cluster config will be loaded,
// and failing this, the config will be loaded from the users local kubeconfig directory
func Config(apiServerHost string) (*rest.Config, error) {
	var err error
	var cfg *rest.Config

	if len(apiServerHost) > 0 {
		cfg = new(rest.Config)
		cfg.Host = apiServerHost
	} else if cfg, err = rest.InClusterConfig(); err != nil {
		apiCfg, err := clientcmd.NewDefaultClientConfigLoadingRules().Load()

		if err != nil {
			return nil, fmt.Errorf("error loading cluster config: %s", err.Error())
		}

		cfg, err = clientcmd.NewDefaultClientConfig(*apiCfg, &clientcmd.ConfigOverrides{}).ClientConfig()

		if err != nil {
			return nil, fmt.Errorf("error loading cluster client config: %s", err.Error())
		}
	}

	return cfg, nil
}
<commit_msg>Remove unused kube package<commit_after><|endoftext|>


<commit_before>package util

import (
	"bufio"
	"bytes"
	"encoding/base64"
	"fmt"
	"io"
	"io/ioutil"
	"math/rand"
	"os"
	"os/exec"
	"path/filepath"
	"strconv"
	"strings"
	"syscall"
	"time"

	"github.com/pkg/errors"
	v1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/resource"
	"k8s.io/klog"
	"kubevirt.io/containerized-data-importer/pkg/common"
)

// CountingReader is a reader that keeps track of how much has been read
type CountingReader struct {
	Reader  io.ReadCloser
	Current uint64
	Done    bool
}

// RandAlphaNum provides an implementation to generate a random alpha numeric string of the specified length
func RandAlphaNum(n int) string {
	rand.Seed(time.Now().UnixNano())
	var letter = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
	b := make([]rune, n)
	for i := range b {
		b[i] = letter[rand.Intn(len(letter))]
	}
	return string(b)
}

// GetNamespace returns the namespace the pod is executing in
func GetNamespace() string {
	return getNamespace("/var/run/secrets/kubernetes.io/serviceaccount/namespace")
}

func getNamespace(path string) string {
	if data, err := ioutil.ReadFile(path); err == nil {
		if ns := strings.TrimSpace(string(data)); len(ns) > 0 {
			return ns
		}
	}
	return "cdi"
}

// ParseEnvVar provides a wrapper to attempt to fetch the specified env var
func ParseEnvVar(envVarName string, decode bool) (string, error) {
	value := os.Getenv(envVarName)
	if decode {
		v, err := base64.StdEncoding.DecodeString(value)
		if err != nil {
			return "", errors.Errorf("error decoding environment variable %q", envVarName)
		}
		value = fmt.Sprintf("%s", v)
	}
	return value, nil
}

// Read reads bytes from the stream and updates the prometheus clone_progress metric according to the progress.
func (r *CountingReader) Read(p []byte) (n int, err error) {
	n, err = r.Reader.Read(p)
	r.Current += uint64(n)
	r.Done = err == io.EOF
	return n, err
}

// Close closes the stream
func (r *CountingReader) Close() error {
	return r.Reader.Close()
}

// GetAvailableSpaceByVolumeMode calls another method based on the volumeMode parameter to get the amount of
// available space at the path specified.
func GetAvailableSpaceByVolumeMode(volumeMode v1.PersistentVolumeMode) int64 {
	if volumeMode == v1.PersistentVolumeBlock {
		return GetAvailableSpaceBlock(common.WriteBlockPath)
	}
	return GetAvailableSpace(common.ImporterVolumePath)
}

// GetAvailableSpace gets the amount of available space at the path specified.
func GetAvailableSpace(path string) int64 {
	var stat syscall.Statfs_t
	err := syscall.Statfs(path, &stat)
	if err != nil {
		return int64(-1)
	}
	return int64(stat.Bavail) * int64(stat.Bsize)
}

// GetAvailableSpaceBlock gets the amount of available space at the block device path specified.
func GetAvailableSpaceBlock(deviceName string) int64 {
	cmd := exec.Command("/usr/bin/lsblk", "-n", "-b", "-o", "SIZE", deviceName)
	var out bytes.Buffer
	var stderr bytes.Buffer
	cmd.Stdout = &out
	cmd.Stderr = &stderr
	err := cmd.Run()
	if err != nil {
		return int64(-1)
	}
	i, err := strconv.ParseInt(strings.TrimSpace(string(out.Bytes())), 10, 64)
	if err != nil {
		return int64(-1)
	}
	return i
}

// RetryBackoffSize Calls the passed in function to size/resize and if it fails lowers the size and tries again up to 10 times.
func RetryBackoffSize(dest string, size resource.Quantity, sizeFunc func(string, resource.Quantity) error) error {
	var stat syscall.Statfs_t
	klog.V(3).Infof("Checking block size on path: %s\n", filepath.Dir(dest))
	err := syscall.Statfs(filepath.Dir(dest), &stat)
	if err != nil {
		// Unable to stat, won't be able to size.
		return err
	}
	blockSize := int64(stat.Bsize)
	klog.V(3).Infof("Block size: %d\n", blockSize)

	err = sizeFunc(dest, size)
	retryCount := 0
	reduceSize := *size.Copy()
	for err != nil && retryCount < 10 {
		retryCount++
		// Reduce by 25 blocks, and try again. How did we end up with 25 blocks? Well we need to leave some blocks for the fs on the pvc.
		// Then we need to leave some extra blocks so it can mount inside the container.
		reduceSize.Sub(*resource.NewScaledQuantity(blockSize*int64(25), 0))
		klog.V(3).Infof("Trying new size: %s\n", reduceSize.String())
		err = sizeFunc(dest, reduceSize)
	}
	return err
}

// MinQuantity calculates the minimum of two quantities.
func MinQuantity(availableSpace, imageSize *resource.Quantity) resource.Quantity {
	if imageSize.Cmp(*availableSpace) == 1 {
		return *availableSpace
	}
	return *imageSize
}

// StreamDataToFile provides a function to stream the specified io.Reader to the specified local file
func StreamDataToFile(r io.Reader, fileName string) error {
	var outFile *os.File
	var err error
	if GetAvailableSpaceBlock(fileName) < 0 {
		// Attempt to create the file with name filePath.  If it exists, fail.
		outFile, err = os.OpenFile(fileName, os.O_CREATE|os.O_EXCL|os.O_WRONLY, os.ModePerm)
	} else {
		outFile, err = os.OpenFile(fileName, os.O_EXCL|os.O_WRONLY, os.ModePerm)
	}
	if err != nil {
		return errors.Wrapf(err, "could not open file %q", fileName)
	}
	defer outFile.Close()
	klog.V(1).Infof("Writing data...\n")
	if _, err = io.Copy(outFile, r); err != nil {
		klog.Errorf("Unable to write file from dataReader: %v\n", err)
		os.Remove(outFile.Name())
		return errors.Wrapf(err, "unable to write to file")
	}
	err = outFile.Sync()
	return err
}

// UnArchiveTar unarchives a tar file and streams its files
// using the specified io.Reader to the specified destination.
func UnArchiveTar(reader io.Reader, destDir string, arg ...string) error {
	klog.V(1).Infof("begin untar to %s...\n", destDir)

	var tarOptions string
	var args = arg
	if len(arg) > 0 {
		tarOptions = arg[0]
		args = arg[1:]
	}
	options := fmt.Sprintf("-%s%s", tarOptions, "xvC")
	untar := exec.Command("/usr/bin/tar", options, destDir, strings.Join(args, ""))
	untar.Stdin = reader
	var errBuf bytes.Buffer
	untar.Stderr = &errBuf
	err := untar.Start()
	if err != nil {
		return err
	}
	err = untar.Wait()
	if err != nil {
		klog.V(3).Infof("%s\n", string(errBuf.Bytes()))
		klog.Errorf("%s\n", err.Error())
		return err
	}
	return nil
}

// UnArchiveLocalTar unarchives a local tar file to the specified destination.
func UnArchiveLocalTar(filePath, destDir string, arg ...string) error {
	file, err := os.Open(filePath)
	if err != nil {
		return errors.Wrap(err, "could not open tar file")
	}
	fileReader := bufio.NewReader(file)
	return UnArchiveTar(fileReader, destDir, arg...)
}

// CopyFile copies a file from one location to another.
func CopyFile(src, dst string) error {
	in, err := os.Open(src)
	if err != nil {
		return err
	}
	defer in.Close()

	out, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer out.Close()

	_, err = io.Copy(out, in)
	if err != nil {
		return err
	}
	return out.Close()
}

// WriteTerminationMessage writes the passed in message to the default termination message file
func WriteTerminationMessage(message string) error {
	return WriteTerminationMessageToFile(common.PodTerminationMessageFile, message)
}

// WriteTerminationMessageToFile writes the passed in message to the passed in message file
func WriteTerminationMessageToFile(file, message string) error {
	// Only write the first line of the message.
	scanner := bufio.NewScanner(strings.NewReader(message))
	if scanner.Scan() {
		err := ioutil.WriteFile(file, []byte(scanner.Text()), os.ModeAppend)
		if err != nil {
			return errors.Wrap(err, "could not create termination message file")
		}
	}
	return nil
}

// CopyDir copies a dir from one location to another.
func CopyDir(source string, dest string) (err error) {
	// get properties of source dir
	sourceinfo, err := os.Stat(source)
	if err != nil {
		return err
	}

	// create dest dir
	err = os.MkdirAll(dest, sourceinfo.Mode())
	if err != nil {
		return err
	}

	directory, _ := os.Open(source)
	objects, err := directory.Readdir(-1)

	for _, obj := range objects {
		src := filepath.Join(source, obj.Name())
		dst := filepath.Join(dest, obj.Name())

		if obj.IsDir() {
			// create sub-directories - recursively
			err = CopyDir(src, dst)
			if err != nil {
				fmt.Println(err)
			}
		} else {
			// perform copy
			err = CopyFile(src, dst)
			if err != nil {
				fmt.Println(err)
			}
		}
	}
	return
}
<commit_msg>Fix `GetAvailableSpaceBlock` always return -1 in LXC (#1065)<commit_after>package util

import (
	"bufio"
	"bytes"
	"encoding/base64"
	"fmt"
	"io"
	"io/ioutil"
	"math/rand"
	"os"
	"os/exec"
	"path/filepath"
	"strconv"
	"strings"
	"syscall"
	"time"

	"github.com/pkg/errors"
	v1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/resource"
	"k8s.io/klog"
	"kubevirt.io/containerized-data-importer/pkg/common"
)

// CountingReader is a reader that keeps track of how much has been read
type CountingReader struct {
	Reader  io.ReadCloser
	Current uint64
	Done    bool
}

// RandAlphaNum provides an implementation to generate a random alpha numeric string of the specified length
func RandAlphaNum(n int) string {
	rand.Seed(time.Now().UnixNano())
	var letter = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
	b := make([]rune, n)
	for i := range b {
		b[i] = letter[rand.Intn(len(letter))]
	}
	return string(b)
}

// GetNamespace returns the namespace the pod is executing in
func GetNamespace() string {
	return getNamespace("/var/run/secrets/kubernetes.io/serviceaccount/namespace")
}

func getNamespace(path string) string {
	if data, err := ioutil.ReadFile(path); err == nil {
		if ns := strings.TrimSpace(string(data)); len(ns) > 0 {
			return ns
		}
	}
	return "cdi"
}

// ParseEnvVar provides a wrapper to attempt to fetch the specified env var
func ParseEnvVar(envVarName string, decode bool) (string, error) {
	value := os.Getenv(envVarName)
	if decode {
		v, err := base64.StdEncoding.DecodeString(value)
		if err != nil {
			return "", errors.Errorf("error decoding environment variable %q", envVarName)
		}
		value = fmt.Sprintf("%s", v)
	}
	return value, nil
}

// Read reads bytes from the stream and updates the prometheus clone_progress metric according to the progress.
func (r *CountingReader) Read(p []byte) (n int, err error) {
	n, err = r.Reader.Read(p)
	r.Current += uint64(n)
	r.Done = err == io.EOF
	return n, err
}

// Close closes the stream
func (r *CountingReader) Close() error {
	return r.Reader.Close()
}

// GetAvailableSpaceByVolumeMode calls another method based on the volumeMode parameter to get the amount of
// available space at the path specified.
func GetAvailableSpaceByVolumeMode(volumeMode v1.PersistentVolumeMode) int64 {
	if volumeMode == v1.PersistentVolumeBlock {
		return GetAvailableSpaceBlock(common.WriteBlockPath)
	}
	return GetAvailableSpace(common.ImporterVolumePath)
}

// GetAvailableSpace gets the amount of available space at the path specified.
func GetAvailableSpace(path string) int64 {
	var stat syscall.Statfs_t
	err := syscall.Statfs(path, &stat)
	if err != nil {
		return int64(-1)
	}
	return int64(stat.Bavail) * int64(stat.Bsize)
}

// GetAvailableSpaceBlock gets the amount of available space at the block device path specified.
func GetAvailableSpaceBlock(deviceName string) int64 {
	cmd := exec.Command("/usr/sbin/blockdev", "--getsize64", deviceName)
	var out bytes.Buffer
	var stderr bytes.Buffer
	cmd.Stdout = &out
	cmd.Stderr = &stderr
	err := cmd.Run()
	if err != nil {
		return int64(-1)
	}
	i, err := strconv.ParseInt(strings.TrimSpace(string(out.Bytes())), 10, 64)
	if err != nil {
		return int64(-1)
	}
	return i
}

// RetryBackoffSize Calls the passed in function to size/resize and if it fails lowers the size and tries again up to 10 times.
func RetryBackoffSize(dest string, size resource.Quantity, sizeFunc func(string, resource.Quantity) error) error {
	var stat syscall.Statfs_t
	klog.V(3).Infof("Checking block size on path: %s\n", filepath.Dir(dest))
	err := syscall.Statfs(filepath.Dir(dest), &stat)
	if err != nil {
		// Unable to stat, won't be able to size.
		return err
	}
	blockSize := int64(stat.Bsize)
	klog.V(3).Infof("Block size: %d\n", blockSize)

	err = sizeFunc(dest, size)
	retryCount := 0
	reduceSize := *size.Copy()
	for err != nil && retryCount < 10 {
		retryCount++
		// Reduce by 25 blocks, and try again. How did we end up with 25 blocks? Well we need to leave some blocks for the fs on the pvc.
		// Then we need to leave some extra blocks so it can mount inside the container.
		reduceSize.Sub(*resource.NewScaledQuantity(blockSize*int64(25), 0))
		klog.V(3).Infof("Trying new size: %s\n", reduceSize.String())
		err = sizeFunc(dest, reduceSize)
	}
	return err
}

// MinQuantity calculates the minimum of two quantities.
func MinQuantity(availableSpace, imageSize *resource.Quantity) resource.Quantity {
	if imageSize.Cmp(*availableSpace) == 1 {
		return *availableSpace
	}
	return *imageSize
}

// StreamDataToFile provides a function to stream the specified io.Reader to the specified local file
func StreamDataToFile(r io.Reader, fileName string) error {
	var outFile *os.File
	var err error
	if GetAvailableSpaceBlock(fileName) < 0 {
		// Attempt to create the file with name filePath.  If it exists, fail.
		outFile, err = os.OpenFile(fileName, os.O_CREATE|os.O_EXCL|os.O_WRONLY, os.ModePerm)
	} else {
		outFile, err = os.OpenFile(fileName, os.O_EXCL|os.O_WRONLY, os.ModePerm)
	}
	if err != nil {
		return errors.Wrapf(err, "could not open file %q", fileName)
	}
	defer outFile.Close()
	klog.V(1).Infof("Writing data...\n")
	if _, err = io.Copy(outFile, r); err != nil {
		klog.Errorf("Unable to write file from dataReader: %v\n", err)
		os.Remove(outFile.Name())
		return errors.Wrapf(err, "unable to write to file")
	}
	err = outFile.Sync()
	return err
}

// UnArchiveTar unarchives a tar file and streams its files
// using the specified io.Reader to the specified destination.
func UnArchiveTar(reader io.Reader, destDir string, arg ...string) error {
	klog.V(1).Infof("begin untar to %s...\n", destDir)

	var tarOptions string
	var args = arg
	if len(arg) > 0 {
		tarOptions = arg[0]
		args = arg[1:]
	}
	options := fmt.Sprintf("-%s%s", tarOptions, "xvC")
	untar := exec.Command("/usr/bin/tar", options, destDir, strings.Join(args, ""))
	untar.Stdin = reader
	var errBuf bytes.Buffer
	untar.Stderr = &errBuf
	err := untar.Start()
	if err != nil {
		return err
	}
	err = untar.Wait()
	if err != nil {
		klog.V(3).Infof("%s\n", string(errBuf.Bytes()))
		klog.Errorf("%s\n", err.Error())
		return err
	}
	return nil
}

// UnArchiveLocalTar unarchives a local tar file to the specified destination.
func UnArchiveLocalTar(filePath, destDir string, arg ...string) error {
	file, err := os.Open(filePath)
	if err != nil {
		return errors.Wrap(err, "could not open tar file")
	}
	fileReader := bufio.NewReader(file)
	return UnArchiveTar(fileReader, destDir, arg...)
}

// CopyFile copies a file from one location to another.
func CopyFile(src, dst string) error {
	in, err := os.Open(src)
	if err != nil {
		return err
	}
	defer in.Close()

	out, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer out.Close()

	_, err = io.Copy(out, in)
	if err != nil {
		return err
	}
	return out.Close()
}

// WriteTerminationMessage writes the passed in message to the default termination message file
func WriteTerminationMessage(message string) error {
	return WriteTerminationMessageToFile(common.PodTerminationMessageFile, message)
}

// WriteTerminationMessageToFile writes the passed in message to the passed in message file
func WriteTerminationMessageToFile(file, message string) error {
	// Only write the first line of the message.
	scanner := bufio.NewScanner(strings.NewReader(message))
	if scanner.Scan() {
		err := ioutil.WriteFile(file, []byte(scanner.Text()), os.ModeAppend)
		if err != nil {
			return errors.Wrap(err, "could not create termination message file")
		}
	}
	return nil
}

// CopyDir copies a dir from one location to another.
func CopyDir(source string, dest string) (err error) {
	// get properties of source dir
	sourceinfo, err := os.Stat(source)
	if err != nil {
		return err
	}

	// create dest dir
	err = os.MkdirAll(dest, sourceinfo.Mode())
	if err != nil {
		return err
	}

	directory, _ := os.Open(source)
	objects, err := directory.Readdir(-1)

	for _, obj := range objects {
		src := filepath.Join(source, obj.Name())
		dst := filepath.Join(dest, obj.Name())

		if obj.IsDir() {
			// create sub-directories - recursively
			err = CopyDir(src, dst)
			if err != nil {
				fmt.Println(err)
			}
		} else {
			// perform copy
			err = CopyFile(src, dst)
			if err != nil {
				fmt.Println(err)
			}
		}
	}
	return
}
<|endoftext|>


<commit_before>package main

import (
	"crypto/sha256"
	"flag"
	"fmt"
	"os"

	"golang.org/x/net/context"
	"golang.org/x/net/proxy"

	"github.com/andres-erbsen/torch"
	"github.com/andres-erbsen/torch/directory"
	"github.com/andres-erbsen/torch/nd"
)

var identifiable = flag.Bool("i", false, "skip TOR anonymization")

type hex32byte [32]byte

func (h *hex32byte) String() string     { return fmt.Sprintf("%x", *h) }
func (h *hex32byte) Set(s string) error { _, err := fmt.Sscanf("%x", s, h[:]); return err }

func main() {
	var id [32]byte
	flag.Var((*hex32byte)(&id), "rend", "hex ID of the OR through which the connection is created. If zero, computed from seed.")
	flag.Parse()

	if flag.NArg() != 1 || len(flag.Arg(0)) == 0 {
		os.Stderr.Write([]byte("USAGE: please specify a shared seed as the first argument\n"))
		flag.Usage()
		os.Exit(3)
	}
	seed := flag.Arg(0)

	if id == [32]byte{} {
		id = sha256.Sum256(append([]byte("TF_EXPAND_SEED_R"), []byte(seed)...))
	}
	ctx := context.Background()
	run(ctx, &id, []byte(seed), *identifiable)
}

func run(ctx context.Context, rendID *[32]byte, seed []byte, identifiable bool) error {
	tr, err := torch.New(ctx, proxy.FromEnvironment())
	if err != nil {
		return err
	}
	defer tr.Stop()

	rendNode := tr.WithDirectory(func(dir *directory.Directory) interface{} {
		shortInfos := make([]*directory.ShortNodeInfo, len(dir.Routers))
		for i, r := range dir.Routers {
			shortInfos[i] = r.ShortNodeInfo
		}
		rendShort := nd.Pick(shortInfos, rendID)
		for _, r := range dir.Routers {
			if r.ShortNodeInfo == rendShort {
				return r
			}
		}
		panic("unreachable")
	}).(*directory.NodeInfo)

	// when we talk to a website over TOR, the website knows what the third hop
	// is. Therefore our converstion partner may as well.
	n := 3
	if identifiable {
		n = 1
	}

	tc1, c1, err := tr.UnguardedCircuitTo(ctx, n, rendNode)
	if err != nil {
		return err
	}
	defer tc1.Close()

	//TODO: use the same path as the first circuit to enable reduction arguments about anonymity.
	tc2, c2, err := tr.UnguardedCircuitTo(ctx, n, rendNode)
	if err != nil {
		return err
	}
	defer tc2.Close()

	ndc, err := nd.Handshake(ctx, c1, c2, seed)

	fmt.Printf("%#v\n", ndc.Bit)

	return nil
}
<commit_msg>update tor thingy for new APIs<commit_after>package main

import (
	"crypto/sha256"
	"flag"
	"fmt"
	"os"

	"golang.org/x/net/context"
	"golang.org/x/net/proxy"

	"github.com/andres-erbsen/rrtcp/fnet"
	"github.com/andres-erbsen/torch"
	"github.com/andres-erbsen/torch/directory"
	"github.com/andres-erbsen/torch/nd"
)

var identifiable = flag.Bool("i", false, "skip TOR anonymization")

type hex32byte [32]byte

func (h *hex32byte) String() string     { return fmt.Sprintf("%x", *h) }
func (h *hex32byte) Set(s string) error { _, err := fmt.Sscanf("%x", s, h[:]); return err }

func main() {
	var id [32]byte
	flag.Var((*hex32byte)(&id), "rend", "hex ID of the OR through which the connection is created. If zero, computed from seed.")
	flag.Parse()

	if flag.NArg() != 1 || len(flag.Arg(0)) == 0 {
		os.Stderr.Write([]byte("USAGE: please specify a shared seed as the first argument\n"))
		flag.Usage()
		os.Exit(3)
	}
	seed := flag.Arg(0)

	if id == [32]byte{} {
		id = sha256.Sum256(append([]byte("TF_EXPAND_SEED_R"), []byte(seed)...))
	}
	ctx := context.Background()
	run(ctx, &id, []byte(seed), *identifiable)
}

func run(ctx context.Context, rendID *[32]byte, seed []byte, identifiable bool) error {
	tr, err := torch.New(ctx, proxy.FromEnvironment())
	if err != nil {
		return err
	}
	defer tr.Stop()

	rendNode := tr.WithDirectory(func(dir *directory.Directory) interface{} {
		shortInfos := make([]*directory.ShortNodeInfo, len(dir.Routers))
		for i, r := range dir.Routers {
			shortInfos[i] = r.ShortNodeInfo
		}
		rendShort := nd.Pick(shortInfos, rendID)
		for _, r := range dir.Routers {
			if r.ShortNodeInfo == rendShort {
				return r
			}
		}
		panic("unreachable")
	}).(*directory.NodeInfo)

	// when we talk to a website over TOR, the website knows what the third hop
	// is. Therefore our converstion partner may as well.
	nodes := make([]*directory.NodeInfo, 0, 3)
	if !identifiable {
		nodes = append(nodes, tr.Pick(weighRelayWith))
		nodes = append(nodes, tr.Pick(weighRelayWith))
	}
	nodes = append(nodes, rendNode)

	tc1, c1, err := torch.BuildCircuit(ctx, proxy.FromEnvironment(), nodes)
	if err != nil {
		return err
	}
	defer tc1.Close()
	tc2, c2, err := torch.BuildCircuit(ctx, proxy.FromEnvironment(), nodes)
	if err != nil {
		return err
	}
	defer tc2.Close()

	ndc, err := nd.Handshake(ctx, c1, c2, seed)
	var _ fnet.FrameConn = (ndc)

	fmt.Printf("%#v\n", ndc.Bit)

	return nil
}

func weighRelayWith(w *directory.BandwidthWeights, n *directory.NodeInfo) int64 {
	return w.ForRelay.Weigh(n)
}
<|endoftext|>


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

// +build !appengine

package main

import (
	"flag"
	"fmt"
	"go/build"
	"io"
	"log"
	"net"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strings"
	"time"

	"code.google.com/p/go.talks/pkg/socket"

	// Imports so that go build/install automatically installs them.
	_ "code.google.com/p/go-tour/pic"
	_ "code.google.com/p/go-tour/tree"
	_ "code.google.com/p/go-tour/wc"
)

const (
	basePkg    = "code.google.com/p/go-tour/"
	socketPath = "/socket"
)

var (
	httpListen  = flag.String("http", "127.0.0.1:3999", "host:port to listen on")
	htmlOutput  = flag.Bool("html", false, "render program output as HTML")
	openBrowser = flag.Bool("openbrowser", true, "open browser automatically")
)

var (
	// GOPATH containing the tour packages
	gopath = os.Getenv("GOPATH")

	httpAddr string
)

func isRoot(path string) bool {
	_, err := os.Stat(filepath.Join(path, "tour.article"))
	return err == nil
}

func findRoot() (string, error) {
	ctx := build.Default
	p, err := ctx.Import(basePkg, "", build.FindOnly)
	if err == nil && isRoot(p.Dir) {
		return p.Dir, nil
	}
	tourRoot := filepath.Join(runtime.GOROOT(), "misc", "tour")
	ctx.GOPATH = tourRoot
	p, err = ctx.Import(basePkg, "", build.FindOnly)
	if err == nil && isRoot(tourRoot) {
		gopath = tourRoot
		return tourRoot, nil
	}
	return "", fmt.Errorf("could not find go-tour content; check $GOROOT and $GOPATH")
}

func main() {
	flag.Parse()

	// find and serve the go tour files
	root, err := findRoot()
	if err != nil {
		log.Fatalf("Couldn't find tour files: %v", err)
	}

	log.Println("Serving content from", root)

	host, port, err := net.SplitHostPort(*httpListen)
	if err != nil {
		log.Fatal(err)
	}
	if host == "" {
		host = "localhost"
	}
	if host != "127.0.0.1" && host != "localhost" {
		log.Print(localhostWarning)
	}
	httpAddr = host + ":" + port

	if err := initTour(root); err != nil {
		log.Fatal(err)
	}

	fs := http.FileServer(http.Dir(root))
	http.Handle("/favicon.ico", fs)
	http.Handle("/static/", fs)
	http.Handle("/talks/", fs)

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path == "/" {
			if err := renderTour(w); err != nil {
				log.Println(err)
			}
			return
		}
		http.Error(w, "not found", 404)
	})

	http.Handle(socketPath, socket.Handler)

	err = serveScripts(filepath.Join(root, "js"), "SocketTransport")
	if err != nil {
		log.Fatal(err)
	}

	go func() {
		url := "http://" + httpAddr
		if waitServer(url) && *openBrowser && startBrowser(url) {
			log.Printf("A browser window should open. If not, please visit %s", url)
		} else {
			log.Printf("Please open your web browser and visit %s", url)
		}
	}()
	log.Fatal(http.ListenAndServe(httpAddr, nil))
}

const localhostWarning = `
WARNING!  WARNING!  WARNING!

I appear to be listening on an address that is not localhost.
Anyone with access to this address and port will have access
to this machine as the user running gotour.

If you don't understand this message, hit Control-C to terminate this process.

WARNING!  WARNING!  WARNING!
`

type response struct {
	Output string `json:"output"`
	Errors string `json:"compile_errors"`
}

func init() {
	socket.Environ = environ
}

// environ returns the original execution environment with GOPATH
// replaced (or added) with the value of the global var gopath.
func environ() (env []string) {
	for _, v := range os.Environ() {
		if !strings.HasPrefix(v, "GOPATH=") {
			env = append(env, v)
		}
	}
	env = append(env, "GOPATH="+gopath)
	return
}

// waitServer waits some time for the http Server to start
// serving url and returns whether it starts
func waitServer(url string) bool {
	tries := 20
	for tries > 0 {
		resp, err := http.Get(url)
		if err == nil {
			resp.Body.Close()
			return true
		}
		time.Sleep(100 * time.Millisecond)
		tries--
	}
	return false
}

// startBrowser tries to open the URL in a browser, and returns
// whether it succeed.
func startBrowser(url string) bool {
	// try to start the browser
	var args []string
	switch runtime.GOOS {
	case "darwin":
		args = []string{"open"}
	case "windows":
		args = []string{"cmd", "/c", "start"}
	default:
		args = []string{"xdg-open"}
	}
	cmd := exec.Command(args[0], append(args[1:], url)...)
	return cmd.Start() == nil
}

// prepContent for the local tour simply returns the content as-is.
func prepContent(r io.Reader) io.Reader { return r }

// socketAddr returns the WebSocket handler address.
func socketAddr() string { return "ws://" + httpAddr + socketPath }
<commit_msg>[x/tour] go-tour: remove unused flag<commit_after>// Copyright 2011 The Go Authors.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build !appengine

package main

import (
	"flag"
	"fmt"
	"go/build"
	"io"
	"log"
	"net"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strings"
	"time"

	"code.google.com/p/go.talks/pkg/socket"

	// Imports so that go build/install automatically installs them.
	_ "code.google.com/p/go-tour/pic"
	_ "code.google.com/p/go-tour/tree"
	_ "code.google.com/p/go-tour/wc"
)

const (
	basePkg    = "code.google.com/p/go-tour/"
	socketPath = "/socket"
)

var (
	httpListen  = flag.String("http", "127.0.0.1:3999", "host:port to listen on")
	openBrowser = flag.Bool("openbrowser", true, "open browser automatically")
)

var (
	// GOPATH containing the tour packages
	gopath = os.Getenv("GOPATH")

	httpAddr string
)

func isRoot(path string) bool {
	_, err := os.Stat(filepath.Join(path, "tour.article"))
	return err == nil
}

func findRoot() (string, error) {
	ctx := build.Default
	p, err := ctx.Import(basePkg, "", build.FindOnly)
	if err == nil && isRoot(p.Dir) {
		return p.Dir, nil
	}
	tourRoot := filepath.Join(runtime.GOROOT(), "misc", "tour")
	ctx.GOPATH = tourRoot
	p, err = ctx.Import(basePkg, "", build.FindOnly)
	if err == nil && isRoot(tourRoot) {
		gopath = tourRoot
		return tourRoot, nil
	}
	return "", fmt.Errorf("could not find go-tour content; check $GOROOT and $GOPATH")
}

func main() {
	flag.Parse()

	// find and serve the go tour files
	root, err := findRoot()
	if err != nil {
		log.Fatalf("Couldn't find tour files: %v", err)
	}

	log.Println("Serving content from", root)

	host, port, err := net.SplitHostPort(*httpListen)
	if err != nil {
		log.Fatal(err)
	}
	if host == "" {
		host = "localhost"
	}
	if host != "127.0.0.1" && host != "localhost" {
		log.Print(localhostWarning)
	}
	httpAddr = host + ":" + port

	if err := initTour(root); err != nil {
		log.Fatal(err)
	}

	fs := http.FileServer(http.Dir(root))
	http.Handle("/favicon.ico", fs)
	http.Handle("/static/", fs)
	http.Handle("/talks/", fs)

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path == "/" {
			if err := renderTour(w); err != nil {
				log.Println(err)
			}
			return
		}
		http.Error(w, "not found", 404)
	})

	http.Handle(socketPath, socket.Handler)

	err = serveScripts(filepath.Join(root, "js"), "SocketTransport")
	if err != nil {
		log.Fatal(err)
	}

	go func() {
		url := "http://" + httpAddr
		if waitServer(url) && *openBrowser && startBrowser(url) {
			log.Printf("A browser window should open. If not, please visit %s", url)
		} else {
			log.Printf("Please open your web browser and visit %s", url)
		}
	}()
	log.Fatal(http.ListenAndServe(httpAddr, nil))
}

const localhostWarning = `
WARNING!  WARNING!  WARNING!

I appear to be listening on an address that is not localhost.
Anyone with access to this address and port will have access
to this machine as the user running gotour.

If you don't understand this message, hit Control-C to terminate this process.

WARNING!  WARNING!  WARNING!
`

type response struct {
	Output string `json:"output"`
	Errors string `json:"compile_errors"`
}

func init() {
	socket.Environ = environ
}

// environ returns the original execution environment with GOPATH
// replaced (or added) with the value of the global var gopath.
func environ() (env []string) {
	for _, v := range os.Environ() {
		if !strings.HasPrefix(v, "GOPATH=") {
			env = append(env, v)
		}
	}
	env = append(env, "GOPATH="+gopath)
	return
}

// waitServer waits some time for the http Server to start
// serving url and returns whether it starts
func waitServer(url string) bool {
	tries := 20
	for tries > 0 {
		resp, err := http.Get(url)
		if err == nil {
			resp.Body.Close()
			return true
		}
		time.Sleep(100 * time.Millisecond)
		tries--
	}
	return false
}

// startBrowser tries to open the URL in a browser, and returns
// whether it succeed.
func startBrowser(url string) bool {
	// try to start the browser
	var args []string
	switch runtime.GOOS {
	case "darwin":
		args = []string{"open"}
	case "windows":
		args = []string{"cmd", "/c", "start"}
	default:
		args = []string{"xdg-open"}
	}
	cmd := exec.Command(args[0], append(args[1:], url)...)
	return cmd.Start() == nil
}

// prepContent for the local tour simply returns the content as-is.
func prepContent(r io.Reader) io.Reader { return r }

// socketAddr returns the WebSocket handler address.
func socketAddr() string { return "ws://" + httpAddr + socketPath }
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os"

	"github.com/apex/log"
	"github.com/apex/log/handlers/cli"

	_ "github.com/apex/apex/runtime/golang"
	_ "github.com/apex/apex/runtime/nodejs"
	_ "github.com/apex/apex/runtime/python"
)

var version = "0.4.1"

func main() {
	log.SetHandler(cli.Default)

	if err := rootCmd.Execute(); err != nil {
		fmt.Errorf("%s\n", err.Error())
		os.Exit(1)
	}
}
<commit_msg>Changed cmd main error output<commit_after>package main

import (
	"fmt"
	"os"

	"github.com/apex/log"
	"github.com/apex/log/handlers/cli"

	_ "github.com/apex/apex/runtime/golang"
	_ "github.com/apex/apex/runtime/nodejs"
	_ "github.com/apex/apex/runtime/python"
)

var version = "0.4.1"

func main() {
	log.SetHandler(cli.Default)

	if err := rootCmd.Execute(); err != nil {
		fmt.Fprintf(os.Stderr, "error: %s\n", err)
		os.Exit(1)
	}
}
<|endoftext|>


<commit_before>package cmd

import (
	"context"
	"fmt"
	"os"
	"strings"
	"testing"

	"reflect"

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

func createMockReply(t *testing.T, expectedMsg string) (*slacker.Response, *monkey.PatchGuard) {
	var mockResponse *slacker.Response

	patchReply := monkey.PatchInstanceMethod(reflect.TypeOf(mockResponse), "Reply",
		func(response *slacker.Response, msg string) {
			assert.Equal(t, expectedMsg, msg)
		})

	_ = monkey.PatchInstanceMethod(reflect.TypeOf(mockResponse), "Typing",
		func(response *slacker.Response) {})

	return mockResponse, patchReply
}

func createMockRequest(t *testing.T, params map[string]string) (*slacker.Request, *monkey.PatchGuard) {
	var mockRequest *slacker.Request

	patchParam := monkey.PatchInstanceMethod(reflect.TypeOf(mockRequest), "Param",
		func(r *slacker.Request, key string) string {
			if params == nil {
				return ""
			}
			return params[key]
		})
	return mockRequest, patchParam
}

func createMockEvent(t *testing.T, team string, channel string, user string) *monkey.PatchGuard {
	patchGetEvent := monkey.Patch(getEvent,
		func(request *slacker.Request) ClaimrEvent {
			return ClaimrEvent{team, channel, user}
		})
	return patchGetEvent
}

func TestCmdCommandList(t *testing.T) {
	usageExpected := []string{
		"add <container-name>",
		"claim <container-name> <reason>",
		"free <container-name>",
		"list",
		"refresh-admins",
		"remove <container-name>",
		"show <container-name>",
		"log-level <level>",
		"purge",
	}
	commandList := CommandList()

	assert.Len(t, commandList, len(usageExpected))

	usageActual := []string{}

	for _, command := range commandList {
		usageActual = append(usageActual, command.Usage)
	}

	assert.Subset(t, usageExpected, usageActual)
}

func TestCmdNotDirect(t *testing.T) {
	isDirect, err := isDirect("CHANNEL")
	assert.False(t, isDirect)
	assert.NoError(t, err)
}

func TestCmdDirect(t *testing.T) {
	direct, err := isDirect("DIRECT")
	assert.True(t, direct)
	assert.Error(t, err, messages.Get("direct-not-allowed"))
}

func TestMessageContainsUser(t *testing.T) {
	hasUser, err := hasUserOnText("lorem ipsum <@USER>")
	assert.True(t, hasUser)
	assert.Error(t, err, messages.Get("shouldnt-mention-user"))
}

func TestMessageDoesNotContainsUser(t *testing.T) {
	hasUser, err := hasUserOnText("lorem ipsum")
	assert.False(t, hasUser)
	assert.NoError(t, err)
}

func TestMessageContainsChannel(t *testing.T) {
	hasChannel, err := hasChannelOnText("lorem ipsum <#CHANNEL>")
	assert.True(t, hasChannel)
	assert.Error(t, err, messages.Get("shouldnt-mention-channel"))
}

func TestMessageDoesNotContainsChannel(t *testing.T) {
	hasChannel, err := hasChannelOnText("lorem ipsum")
	assert.False(t, hasChannel)
	assert.NoError(t, err)
}

func TestAllCommandsCheckingDirect(t *testing.T) {
	mockResponse, patchReply := createMockReply(t, messages.Get("direct-not-allowed"))
	mockRequest, patchParam := createMockRequest(t, map[string]string{"container-name": ""})
	patchGetEvent := createMockEvent(t, "team", "DIRECT", "user")

	for _, command := range commands {
		if !strings.Contains(command.Description, "admin-only") {
			command.Handler(mockRequest, mockResponse)
		}
	}

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

func TestAllCommandsCheckingNoName(t *testing.T) {
	mockResponse, patchReply := createMockReply(t, fmt.Sprintf(messages.Get("field-required"), "container name"))
	patchGetEvent := createMockEvent(t, "team", "channel", "user")
	mockRequest, patchParam := createMockRequest(t, map[string]string{"container-name": ""})

	for _, command := range CommandList() {
		if strings.Contains(command.Usage, "<container-name>") {
			command.Handler(mockRequest, mockResponse)
		}
	}

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

func TestAllCommandsErrorWhenGettingFromDB(t *testing.T) {

	guard := monkey.Patch(model.GetContainer,
		func(Team string, Channel string, Name string) (model.Container, error) {
			return model.Container{}, fmt.Errorf("simulated error")
		})

	teamName := "TestTeamList"
	channelName := "TestChannel"
	userName := "user"

	mockResponse, patchReply := createMockReply(t, "simulated error")
	patchGetEvent := createMockEvent(t, teamName, channelName, userName)
	mockRequest, patchParam := createMockRequest(t, nil)

	for _, command := range commands {
		if strings.Contains(command.Usage, "<container-name>") {
			command.Handler(mockRequest, mockResponse)
		}
	}

	patchReply.Unpatch()
	patchGetEvent.Unpatch()
	patchParam.Unpatch()
	guard.Unpatch()

}

func TestNilGetEvent(t *testing.T) {
	event := getEvent(nil)
	assert.ObjectsAreEqual(ClaimrEvent{}, event)
}

func TestGetEventFromNSLopesEvent(t *testing.T) {
	var message slack.MessageEvent
	message.Team = "Team"
	message.Channel = "Channel"
	message.User = "User"
	request := slacker.NewRequest(context.Background(), &message, &proper.Properties{})
	event := getEvent(request)
	assert.ObjectsAreEqual(ClaimrEvent{}, event)
}

func TestGetEventText(t *testing.T) {
	text := "Text"
	var message slack.MessageEvent
	message.Team = "Team"
	message.Channel = "Channel"
	message.User = "User"
	message.Text = text
	request := slacker.NewRequest(context.Background(), &message, &proper.Properties{})

	assert.Equal(t, text, GetEventText(request))
}

func TestNonAdminTryAccessAdminOnlyCommands(t *testing.T) {
	teamName := "TestPurge"
	channelName := "TestChannel"
	userName := "NotAAdmin"

	mockResponse, patchReply := createMockReply(t, messages.Get("admin-only"))
	patchGetEvent := createMockEvent(t, teamName, channelName, userName)
	mockRequest, _ := createMockRequest(t, nil)

	for _, command := range commands {
		if strings.Contains(command.Description, "admin-only") {
			command.Handler(mockRequest, mockResponse)
		}
	}

	patchReply.Unpatch()
	patchGetEvent.Unpatch()
}

func TestNonAdminTryAccessAdminOnlyCommandsWhenEnvIsNotSet(t *testing.T) {
	teamName := "TestPurge"
	channelName := "TestChannel"
	userName := "NotAAdmin"

	currentEnv := os.Getenv("CLAIMR_SUPERUSER")
	os.Unsetenv("CLAIMR_SUPERUSER")
	defer func() { os.Setenv("CLAIMR_SUPERUSER", currentEnv) }()

	mockResponse, patchReply := createMockReply(t, messages.Get("admin-only"))
	patchGetEvent := createMockEvent(t, teamName, channelName, userName)
	mockRequest, _ := createMockRequest(t, nil)

	for _, command := range commands {
		if strings.Contains(command.Description, "admin-only") {
			command.Handler(mockRequest, mockResponse)
		}
	}

	patchReply.Unpatch()
	patchGetEvent.Unpatch()
}

func TestIsSuperUserAdmin(t *testing.T) {
	assert.True(t, isAdmin(os.Getenv("CLAIMR_SUPERUSER")))
}

func TestIsSuperUserAdminCaseInsensitive(t *testing.T) {
	assert.True(t, isAdmin(strings.ToLower(os.Getenv("CLAIMR_SUPERUSER"))))
}

func TestIsNotAdmin(t *testing.T) {
	assert.False(t, isAdmin("ANOTHER-USER"))
}

func TestIsSlackAdmin(t *testing.T) {
	currentAdmins := model.Admins
	model.Admins = []model.Admin{}
	defer func() {
		model.Admins = currentAdmins
	}()
	model.Admins = []model.Admin{{ID: "SlackAdmin", RealName: "Fake Slack Admin"}}

	assert.True(t, isAdmin("SlackAdmin"))
}
<commit_msg>Fixing base_test<commit_after>package cmd

import (
	"context"
	"fmt"
	"os"
	"strings"
	"testing"

	"reflect"

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

func createMockReply(t *testing.T, expectedMsg string) (*slacker.Response, *monkey.PatchGuard) {
	var mockResponse *slacker.Response

	patchReply := monkey.PatchInstanceMethod(reflect.TypeOf(mockResponse), "Reply",
		func(response *slacker.Response, msg string) {
			assert.Equal(t, expectedMsg, msg)
		})

	_ = monkey.PatchInstanceMethod(reflect.TypeOf(mockResponse), "Typing",
		func(response *slacker.Response) {})

	return mockResponse, patchReply
}

func createMockRequest(t *testing.T, params map[string]string) (*slacker.Request, *monkey.PatchGuard) {
	var mockRequest *slacker.Request

	patchParam := monkey.PatchInstanceMethod(reflect.TypeOf(mockRequest), "Param",
		func(r *slacker.Request, key string) string {
			if params == nil {
				return ""
			}
			return params[key]
		})
	return mockRequest, patchParam
}

func createMockEvent(t *testing.T, team string, channel string, user string) *monkey.PatchGuard {
	patchGetEvent := monkey.Patch(getEvent,
		func(request *slacker.Request) ClaimrEvent {
			return ClaimrEvent{team, channel, user}
		})
	return patchGetEvent
}

func TestCmdCommandList(t *testing.T) {
	usageExpected := []string{
		"add <container-name>",
		"claim <container-name> <reason>",
		"free <container-name>",
		"list",
		"refresh-admins",
		"remove <container-name>",
		"show <container-name>",
		"log-level <level>",
		"purge",
	}
	commandList := CommandList()

	assert.Len(t, commandList, len(usageExpected))

	usageActual := []string{}

	for _, command := range commandList {
		usageActual = append(usageActual, command.Usage)
	}

	assert.Subset(t, usageExpected, usageActual)
}

func TestCmdNotDirect(t *testing.T) {
	isDirect, err := isDirect("CHANNEL")
	assert.False(t, isDirect)
	assert.NoError(t, err)
}

func TestCmdDirect(t *testing.T) {
	direct, err := isDirect("DIRECT")
	assert.True(t, direct)
	assert.Error(t, err, messages.Get("direct-not-allowed"))
}

func TestMessageContainsUser(t *testing.T) {
	hasUser, err := hasUserOnText("lorem ipsum <@USER>")
	assert.True(t, hasUser)
	assert.Error(t, err, messages.Get("shouldnt-mention-user"))
}

func TestMessageDoesNotContainsUser(t *testing.T) {
	hasUser, err := hasUserOnText("lorem ipsum")
	assert.False(t, hasUser)
	assert.NoError(t, err)
}

func TestMessageContainsChannel(t *testing.T) {
	hasChannel, err := hasChannelOnText("lorem ipsum <#CHANNEL>")
	assert.True(t, hasChannel)
	assert.Error(t, err, messages.Get("shouldnt-mention-channel"))
}

func TestMessageDoesNotContainsChannel(t *testing.T) {
	hasChannel, err := hasChannelOnText("lorem ipsum")
	assert.False(t, hasChannel)
	assert.NoError(t, err)
}

func TestAllCommandsCheckingDirect(t *testing.T) {
	mockResponse, patchReply := createMockReply(t, messages.Get("direct-not-allowed"))
	mockRequest, patchParam := createMockRequest(t, map[string]string{"container-name": ""})
	patchGetEvent := createMockEvent(t, "team", "DIRECT", "user")

	for _, command := range commands {
		if !strings.Contains(command.Description, "admin-only") {
			command.Handler(mockRequest, mockResponse)
		}
	}

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

func TestAllCommandsCheckingNoName(t *testing.T) {
	mockResponse, patchReply := createMockReply(t, fmt.Sprintf(messages.Get("field-required"), "container name"))
	patchGetEvent := createMockEvent(t, "team", "channel", "user")
	mockRequest, patchParam := createMockRequest(t, map[string]string{"container-name": ""})

	for _, command := range CommandList() {
		if strings.Contains(command.Usage, "<container-name>") {
			command.Handler(mockRequest, mockResponse)
		}
	}

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

func TestAllCommandsErrorWhenGettingFromDB(t *testing.T) {

	guard := monkey.Patch(model.GetContainer,
		func(Team string, Channel string, Name string) (model.Container, error) {
			return model.Container{}, fmt.Errorf("simulated error")
		})

	teamName := "TestTeamList"
	channelName := "TestChannel"
	userName := "user"

	mockResponse, patchReply := createMockReply(t, "simulated error")
	patchGetEvent := createMockEvent(t, teamName, channelName, userName)
	mockRequest, patchParam := createMockRequest(t, nil)

	for _, command := range commands {
		if strings.Contains(command.Usage, "<container-name>") {
			command.Handler(mockRequest, mockResponse)
		}
	}

	patchReply.Unpatch()
	patchGetEvent.Unpatch()
	patchParam.Unpatch()
	guard.Unpatch()

}

func TestNilGetEvent(t *testing.T) {
	event := getEvent(nil)
	assert.ObjectsAreEqual(ClaimrEvent{}, event)
}

func TestGetEventFromNSLopesEvent(t *testing.T) {
	var message slack.MessageEvent
	message.Team = "Team"
	message.Channel = "Channel"
	message.User = "User"
	request := slacker.NewRequest(context.Background(), &message, &proper.Properties{})
	event := getEvent(request)
	assert.ObjectsAreEqual(ClaimrEvent{}, event)
}

func TestGetEventText(t *testing.T) {
	text := "Text"
	var message slack.MessageEvent
	message.Team = "Team"
	message.Channel = "Channel"
	message.User = "User"
	message.Text = text
	request := slacker.NewRequest(context.Background(), &message, &proper.Properties{})

	assert.Equal(t, text, GetEventText(request))
}

func TestNonAdminTryAccessAdminOnlyCommands(t *testing.T) {
	teamName := "TestPurge"
	channelName := "TestChannel"
	userName := "NotAAdmin"

	mockResponse, patchReply := createMockReply(t, messages.Get("admin-only"))
	patchGetEvent := createMockEvent(t, teamName, channelName, userName)
	mockRequest, _ := createMockRequest(t, nil)

	for _, command := range commands {
		if strings.Contains(command.Description, "admin-only") {
			command.Handler(mockRequest, mockResponse)
		}
	}

	patchReply.Unpatch()
	patchGetEvent.Unpatch()
}

func TestNonAdminTryAccessAdminOnlyCommandsWhenEnvIsNotSet(t *testing.T) {
	teamName := "TestPurge"
	channelName := "TestChannel"
	userName := "NotAAdmin"

	currentEnv := os.Getenv("CLAIMR_SUPERUSER")
	os.Unsetenv("CLAIMR_SUPERUSER")
	defer func() { os.Setenv("CLAIMR_SUPERUSER", currentEnv) }()

	mockResponse, patchReply := createMockReply(t, messages.Get("admin-only"))
	patchGetEvent := createMockEvent(t, teamName, channelName, userName)
	mockRequest, _ := createMockRequest(t, nil)

	for _, command := range commands {
		if strings.Contains(command.Description, "admin-only") {
			command.Handler(mockRequest, mockResponse)
		}
	}

	patchReply.Unpatch()
	patchGetEvent.Unpatch()
}

func TestIsSuperUserAdmin(t *testing.T) {
	assert.True(t, model.IsAdmin(os.Getenv("CLAIMR_SUPERUSER")))
}

func TestIsSuperUserAdminCaseInsensitive(t *testing.T) {
	assert.True(t, model.IsAdmin(strings.ToLower(os.Getenv("CLAIMR_SUPERUSER"))))
}

func TestIsNotAdmin(t *testing.T) {
	assert.False(t, model.IsAdmin("ANOTHER-USER"))
}

func TestIsSlackAdmin(t *testing.T) {
	currentAdmins := model.Admins
	model.Admins = []model.Admin{}
	defer func() {
		model.Admins = currentAdmins
	}()
	model.Admins = []model.Admin{{ID: "SlackAdmin", RealName: "Fake Slack Admin"}}

	assert.True(t, model.IsAdmin("SlackAdmin"))
}
<|endoftext|>


<commit_before>package main

import (
	//"flag"
	"fmt"
	"log"
	"os"

	"github.com/namsral/flag"
	gogitlab "github.com/plouc/go-gitlab-client"
)

func projectList(args []string) {

	fmt.Printf("args: %v\n", args)
	fs := flag.NewFlagSetWithEnvPrefix(os.Args[0], "GLAB", flag.PanicOnError)

	host := fs.String("host", "", "name of the gitlab host")
	apiPath := fs.String("apipath", "", "api path on the gitlab host")
	token := fs.String("token", "", "token for gitlab")

	if err := fs.Parse(args[1:]); err != nil {
		fmt.Errorf("error: %s\n", err)
	}

	gitlab := gogitlab.NewGitlab(*host, *apiPath, *token)
	fmt.Printf("gitlab: %+v \n", *gitlab)

}

func main() {

	mode := ""
	if len(os.Args) > 1 {
		mode = os.Args[1]
	} else {
		fmt.Println("Used needs to include a subcommand.")
		return
	}

	args := append(os.Args[:1], os.Args[2:]...)
	// args := os.Args[2:]

	switch mode {
	case "projects":
		projectList(args)
	// case "replay":
	default:
		log.Fatal("Available commands: projects")
	}

}
<commit_msg>Remove stdout<commit_after>package main

import (
	"fmt"
	"log"
	"os"

	"github.com/namsral/flag"
	gogitlab "github.com/plouc/go-gitlab-client"
)

func projectList(args []string) {
	fs := flag.NewFlagSetWithEnvPrefix(args[0], "GLAB", flag.PanicOnError)

	host := fs.String("host", "", "name of the gitlab host")
	apiPath := fs.String("apipath", "", "api path on the gitlab host")
	token := fs.String("token", "", "token for gitlab")

	if err := fs.Parse(args[1:]); err != nil {
		fmt.Errorf("error: %s\n", err)
	}

	gitlab := gogitlab.NewGitlab(*host, *apiPath, *token)
	fmt.Printf("gitlab: %+v \n", *gitlab)

}

func main() {

	mode := ""
	if len(os.Args) > 1 {
		mode = os.Args[1]
	} else {
		fmt.Println("Used needs to include a subcommand.")
		return
	}

	args := append(os.Args[:1], os.Args[2:]...)

	switch mode {
	case "projects":
		projectList(args)
	// case "replay":
	default:
		log.Fatal("Available commands: projects")
	}

}
<|endoftext|>


<commit_before>package psi

type Descriptor []byte

func (d Descriptor) Tag() DescriptorTag {
	return DescriptorTag(d[0])
}

func (d Descriptor) Data() []byte {
	return d[2 : 2+d[1]]
}

type DescriptorList []byte

// Pop returns first descriptor in d and remaining descriptors in rdl.
// If there is no more descriptors len(rdl) == 0. If an error occurs
// d == nil.
func (dl DescriptorList) Pop() (d Descriptor, rdl DescriptorList) {
	if len(dl) < 2 {
		return
	}
	l := int(dl[1]) + 2
	if len(dl) < l {
		return
	}
	d = Descriptor(dl[:l])
	rdl = dl[l:]
	return
}

// Append adds d to the end of the dl. It works like Go append function so need
// to be used in this way:
//     dl = dl.Append(d)
func (dl DescriptorList) Append(d Descriptor) DescriptorList {
	return append(dl, d...)
}

type DescriptorTag byte

const (
	CATag         DescriptorTag = 0x09
	ISO639LangTag DescriptorTag = 0x0a

	NetworkNameTag               DescriptorTag = 0x40
	ServiceListTag               DescriptorTag = 0x41
	StuffingTag                  DescriptorTag = 0x42
	SatelliteDeliverySystemTag   DescriptorTag = 0x43
	CableDeliverySystemTag       DescriptorTag = 0x44
	BouquetNameTag               DescriptorTag = 0x47
	ServiceTag                   DescriptorTag = 0x48
	CountryAvailabilityTag       DescriptorTag = 0x49
	LinkageTag                   DescriptorTag = 0x4A
	NVODReferenceTag             DescriptorTag = 0x4B
	TimeShiftedServiceTag        DescriptorTag = 0x4C
	ShortEventTag                DescriptorTag = 0x4D
	ExtendedEventTag             DescriptorTag = 0x4E
	TimeShiftedEventTag          DescriptorTag = 0x4F
	ComponentTag                 DescriptorTag = 0x50
	MosaicTag                    DescriptorTag = 0x51
	StreamIdentifierTag          DescriptorTag = 0x52
	CAIdentifierTag              DescriptorTag = 0x53
	ContentTag                   DescriptorTag = 0x54
	ParentalRatingTag            DescriptorTag = 0x55
	TeletextTag                  DescriptorTag = 0x56
	TelephoneTag                 DescriptorTag = 0x57
	LocalTimeOffsetTag           DescriptorTag = 0x58
	SubtitlingTag                DescriptorTag = 0x59
	TerrestrialDeliverySystemTag DescriptorTag = 0x5A
	MultilingualNetworkName      DescriptorTag = 0x5B
	MultilingualBouquetName      DescriptorTag = 0x5C
	MultilingualServiceName      DescriptorTag = 0x5D
	MultilingualComponent        DescriptorTag = 0x5E
	PrivateDataSpecifier         DescriptorTag = 0x5F
	ServiceMove                  DescriptorTag = 0x60
	ShortSmoothingBuffer         DescriptorTag = 0x61
	FrequencyList                DescriptorTag = 0x62
	PartialTransportStreamTag    DescriptorTag = 0x63
	DataBroadcastTag             DescriptorTag = 0x64
	CASystemTag                  DescriptorTag = 0x65
	DataBroadcastIdTag           DescriptorTag = 0x66
	TransportStreamTag           DescriptorTag = 0x67
	DSNGTag                      DescriptorTag = 0x68
	PDCTag                       DescriptorTag = 0x69
	AC3Tag                       DescriptorTag = 0x6a
	AncillaryDataTag             DescriptorTag = 0x6b
	CellListTag                  DescriptorTag = 0x6c
	CellFrequencyLinkTag         DescriptorTag = 0x6d
	AnnouncementSupportTag       DescriptorTag = 0x6e
	ApplicationSignalling        DescriptorTag = 0x6f

	EnhancedAC3Tag DescriptorTag = 0x7a
	DTSTag         DescriptorTag = 0x7b
	AACTag         DescriptorTag = 0x7c
)
<commit_msg>psi: More descriptor tags<commit_after>package psi

type Descriptor []byte

func (d Descriptor) Tag() DescriptorTag {
	return DescriptorTag(d[0])
}

func (d Descriptor) Data() []byte {
	return d[2 : 2+d[1]]
}

type DescriptorList []byte

// Pop returns first descriptor in d and remaining descriptors in rdl.
// If there is no more descriptors len(rdl) == 0. If an error occurs
// d == nil.
func (dl DescriptorList) Pop() (d Descriptor, rdl DescriptorList) {
	if len(dl) < 2 {
		return
	}
	l := int(dl[1]) + 2
	if len(dl) < l {
		return
	}
	d = Descriptor(dl[:l])
	rdl = dl[l:]
	return
}

// Append adds d to the end of the dl. It works like Go append function so need
// to be used in this way:
//     dl = dl.Append(d)
func (dl DescriptorList) Append(d Descriptor) DescriptorList {
	return append(dl, d...)
}

type DescriptorTag byte

const (
	VideoStreamTag                DescriptorTag = 0x02
	AudioStreamTag                DescriptorTag = 0x03 //PMT
	HierarchyTag                  DescriptorTag = 0x04
	RegistrationTag               DescriptorTag = 0x05 //PMT
	DataStreamAlignmentTag        DescriptorTag = 0x06
	TargetBackgroundGridTag       DescriptorTag = 0x07
	VideoWindowTag                DescriptorTag = 0x08
	CATag                         DescriptorTag = 0x09
	ISO639LangTag                 DescriptorTag = 0x0A //PMT
	SystemClockTag                DescriptorTag = 0x0B
	MultiplexBufferUtilizationTag DescriptorTag = 0x0C
	CopyrightTag                  DescriptorTag = 0x0D
	MaximumBitrateTag             DescriptorTag = 0x0E //PMT
	PrivateDataIndicatorTag       DescriptorTag = 0x0F
	SmoothingBufferTag            DescriptorTag = 0x10
	STDTag                        DescriptorTag = 0x11
	IBPTag                        DescriptorTag = 0x12

	MPEG4VideoTag      DescriptorTag = 0x1b
	MPEG4AudioTag      DescriptorTag = 0x1c
	IODTag             DescriptorTag = 0x1d
	SLTag              DescriptorTag = 0x1f
	FMCTag             DescriptorTag = 0x20
	ExternalESIDTag    DescriptorTag = 0x21
	MuxCodeTag         DescriptorTag = 0x22
	FmxBufferSizeTag   DescriptorTag = 0x23
	MultiplexBufferTag DescriptorTag = 0x24

	NetworkNameTag               DescriptorTag = 0x40 //NIT
	ServiceListTag               DescriptorTag = 0x41 //NIT
	StuffingTag                  DescriptorTag = 0x42
	SatelliteDeliverySystemTag   DescriptorTag = 0x43
	CableDeliverySystemTag       DescriptorTag = 0x44
	BouquetNameTag               DescriptorTag = 0x47
	ServiceTag                   DescriptorTag = 0x48
	CountryAvailabilityTag       DescriptorTag = 0x49
	LinkageTag                   DescriptorTag = 0x4A
	NVODReferenceTag             DescriptorTag = 0x4B
	TimeShiftedServiceTag        DescriptorTag = 0x4C
	ShortEventTag                DescriptorTag = 0x4D
	ExtendedEventTag             DescriptorTag = 0x4E
	TimeShiftedEventTag          DescriptorTag = 0x4F
	ComponentTag                 DescriptorTag = 0x50
	MosaicTag                    DescriptorTag = 0x51
	StreamIdentifierTag          DescriptorTag = 0x52 //PMT
	CAIdentifierTag              DescriptorTag = 0x53
	ContentTag                   DescriptorTag = 0x54
	ParentalRatingTag            DescriptorTag = 0x55
	TeletextTag                  DescriptorTag = 0x56
	TelephoneTag                 DescriptorTag = 0x57
	LocalTimeOffsetTag           DescriptorTag = 0x58
	SubtitlingTag                DescriptorTag = 0x59 //PMT
	TerrestrialDeliverySystemTag DescriptorTag = 0x5A //NIT
	MultilingualNetworkName      DescriptorTag = 0x5B
	MultilingualBouquetName      DescriptorTag = 0x5C
	MultilingualServiceName      DescriptorTag = 0x5D
	MultilingualComponent        DescriptorTag = 0x5E
	PrivateDataSpecifier         DescriptorTag = 0x5F //NIT
	ServiceMove                  DescriptorTag = 0x60
	ShortSmoothingBuffer         DescriptorTag = 0x61
	FrequencyList                DescriptorTag = 0x62 //NIT
	PartialTransportStreamTag    DescriptorTag = 0x63
	DataBroadcastTag             DescriptorTag = 0x64
	CASystemTag                  DescriptorTag = 0x65
	DataBroadcastIdTag           DescriptorTag = 0x66
	TransportStreamTag           DescriptorTag = 0x67
	DSNGTag                      DescriptorTag = 0x68
	PDCTag                       DescriptorTag = 0x69
	AC3Tag                       DescriptorTag = 0x6a //PMT
	AncillaryDataTag             DescriptorTag = 0x6b
	CellListTag                  DescriptorTag = 0x6c
	CellFrequencyLinkTag         DescriptorTag = 0x6d
	AnnouncementSupportTag       DescriptorTag = 0x6e
	ApplicationSignalling        DescriptorTag = 0x6f //PMT

	EnhancedAC3Tag DescriptorTag = 0x7a //PMT
	DTSTag         DescriptorTag = 0x7b
	AACTag         DescriptorTag = 0x7c

	LogicalCannelTag DescriptorTag = 0x83 //NIT
)
<|endoftext|>


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

package main

import (
	"fmt"
	"os"
	"sort"
	"text/tabwriter"

	"github.com/coreos/mantle/cli"
	"github.com/coreos/mantle/kola"
	"github.com/coreos/mantle/kola/register"
	"github.com/coreos/pkg/capnslog"
	"github.com/spf13/cobra"

	_ "github.com/coreos-inc/pluton/tests/bootkube"
)

var (
	plog = capnslog.NewPackageLogger("github.com/coreos-inc/pluton", "kola")

	root = &cobra.Command{
		Use:   "kola [command]",
		Short: "The CoreOS Superdeep Borehole",
		// http://en.wikipedia.org/wiki/Kola_Superdeep_Borehole
	}

	cmdRun = &cobra.Command{
		Use:    "run [glob pattern]",
		Short:  "Run run kola tests by category",
		Long:   "run all kola tests (default) or related groups",
		Run:    runRun,
		PreRun: preRun,
	}

	cmdList = &cobra.Command{
		Use:   "list",
		Short: "List kola test names",
		Run:   runList,
	}

	bootkubeRepo       string
	bootkubeTag        string
	hostKubeletTag     string
	conformanceRepo    string
	conformanceVersion string
)

func init() {

	cmdRun.Flags().StringVar(&bootkubeRepo, "bootkubeRepo", "quay.io/coreos/bootkube", "")
	cmdRun.Flags().StringVar(&bootkubeTag, "bootkubeTag", "v0.3.7", "")
	cmdRun.Flags().StringVar(&hostKubeletTag, "hostKubeletTag", "v1.5.2_coreos.2", "")
	cmdRun.Flags().StringVar(&conformanceRepo, "conformanceRepo", "github.com/coreos/kubernetes", "")
	cmdRun.Flags().StringVar(&conformanceVersion, "conformanceVersion", "v1.5.2+coreos.2", "")
	root.AddCommand(cmdRun)
	root.AddCommand(cmdList)
}

func main() {
	cli.Execute(root)
}

func preRun(cmd *cobra.Command, args []string) {
	err := syncOptions()
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error: %v\n", err)
		os.Exit(3)
	}
}

func runRun(cmd *cobra.Command, args []string) {
	if len(args) > 1 {
		fmt.Fprintf(os.Stderr, "Extra arguements specified. Usage: 'kola run [glob pattern]'\n")
		os.Exit(2)
	}
	var pattern string
	if len(args) == 1 {
		pattern = args[0]
	} else {
		pattern = "*" // run all tests by default
	}

	kola.RegisterTestOption("BootkubeRepo", bootkubeRepo)
	kola.RegisterTestOption("BootkubeTag", bootkubeTag)
	kola.RegisterTestOption("HostKubeletTag", hostKubeletTag)
	kola.RegisterTestOption("ConformanceRepo", conformanceRepo)
	kola.RegisterTestOption("ConformanceVersion", conformanceVersion)

	err := kola.RunTests(pattern, kolaPlatform, outputDir)
	if err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
		os.Exit(1)
	}
}

func runList(cmd *cobra.Command, args []string) {
	var w = tabwriter.NewWriter(os.Stdout, 0, 8, 0, '\t', 0)
	var testlist list

	for name, test := range register.Tests {
		testlist = append(testlist, item{name, test.Platforms})
	}

	sort.Sort(testlist)

	fmt.Fprintln(w, "Test Name\tPlatforms Available")
	fmt.Fprintln(w, "\t")
	for _, item := range testlist {
		fmt.Fprintf(w, "%v\n", item)
	}
	w.Flush()
}

type item struct {
	Name      string
	Platforms []string
}

func (i item) String() string {
	if len(i.Platforms) == 0 {
		i.Platforms = []string{"all"}
	}
	return fmt.Sprintf("%v\t%v", i.Name, i.Platforms)
}

type list []item

func (s list) Len() int           { return len(s) }
func (s list) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s list) Less(i, j int) bool { return s[i].Name < s[j].Name }
<commit_msg>cmd/kola: bump default kubelet to 1.5.3<commit_after>// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
	"fmt"
	"os"
	"sort"
	"text/tabwriter"

	"github.com/coreos/mantle/cli"
	"github.com/coreos/mantle/kola"
	"github.com/coreos/mantle/kola/register"
	"github.com/coreos/pkg/capnslog"
	"github.com/spf13/cobra"

	_ "github.com/coreos-inc/pluton/tests/bootkube"
)

var (
	plog = capnslog.NewPackageLogger("github.com/coreos-inc/pluton", "kola")

	root = &cobra.Command{
		Use:   "kola [command]",
		Short: "The CoreOS Superdeep Borehole",
		// http://en.wikipedia.org/wiki/Kola_Superdeep_Borehole
	}

	cmdRun = &cobra.Command{
		Use:    "run [glob pattern]",
		Short:  "Run run kola tests by category",
		Long:   "run all kola tests (default) or related groups",
		Run:    runRun,
		PreRun: preRun,
	}

	cmdList = &cobra.Command{
		Use:   "list",
		Short: "List kola test names",
		Run:   runList,
	}

	bootkubeRepo       string
	bootkubeTag        string
	hostKubeletTag     string
	conformanceRepo    string
	conformanceVersion string
)

func init() {

	cmdRun.Flags().StringVar(&bootkubeRepo, "bootkubeRepo", "quay.io/coreos/bootkube", "")
	cmdRun.Flags().StringVar(&bootkubeTag, "bootkubeTag", "v0.3.7", "")
	cmdRun.Flags().StringVar(&hostKubeletTag, "hostKubeletTag", "v1.5.3_coreos.0", "")
	cmdRun.Flags().StringVar(&conformanceRepo, "conformanceRepo", "github.com/coreos/kubernetes", "")
	cmdRun.Flags().StringVar(&conformanceVersion, "conformanceVersion", "v1.5.3+coreos.0", "")
	root.AddCommand(cmdRun)
	root.AddCommand(cmdList)
}

func main() {
	cli.Execute(root)
}

func preRun(cmd *cobra.Command, args []string) {
	err := syncOptions()
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error: %v\n", err)
		os.Exit(3)
	}
}

func runRun(cmd *cobra.Command, args []string) {
	if len(args) > 1 {
		fmt.Fprintf(os.Stderr, "Extra arguements specified. Usage: 'kola run [glob pattern]'\n")
		os.Exit(2)
	}
	var pattern string
	if len(args) == 1 {
		pattern = args[0]
	} else {
		pattern = "*" // run all tests by default
	}

	kola.RegisterTestOption("BootkubeRepo", bootkubeRepo)
	kola.RegisterTestOption("BootkubeTag", bootkubeTag)
	kola.RegisterTestOption("HostKubeletTag", hostKubeletTag)
	kola.RegisterTestOption("ConformanceRepo", conformanceRepo)
	kola.RegisterTestOption("ConformanceVersion", conformanceVersion)

	err := kola.RunTests(pattern, kolaPlatform, outputDir)
	if err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
		os.Exit(1)
	}
}

func runList(cmd *cobra.Command, args []string) {
	var w = tabwriter.NewWriter(os.Stdout, 0, 8, 0, '\t', 0)
	var testlist list

	for name, test := range register.Tests {
		testlist = append(testlist, item{name, test.Platforms})
	}

	sort.Sort(testlist)

	fmt.Fprintln(w, "Test Name\tPlatforms Available")
	fmt.Fprintln(w, "\t")
	for _, item := range testlist {
		fmt.Fprintf(w, "%v\n", item)
	}
	w.Flush()
}

type item struct {
	Name      string
	Platforms []string
}

func (i item) String() string {
	if len(i.Platforms) == 0 {
		i.Platforms = []string{"all"}
	}
	return fmt.Sprintf("%v\t%v", i.Name, i.Platforms)
}

type list []item

func (s list) Len() int           { return len(s) }
func (s list) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s list) Less(i, j int) bool { return s[i].Name < s[j].Name }
<|endoftext|>


<commit_before>/*
Copyright 2019 The Kubernetes Authors.

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 main

import (
	"bytes"
	goflag "flag"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"strings"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"k8s.io/apimachinery/pkg/util/validation/field"
	"k8s.io/client-go/tools/clientcmd"
	"k8s.io/client-go/util/homedir"
	"k8s.io/klog"
	"k8s.io/kops/cmd/kops/util"
	kopsapi "k8s.io/kops/pkg/apis/kops"
	"k8s.io/kops/pkg/client/simple"
	"k8s.io/kubectl/pkg/util/i18n"
	"k8s.io/kubectl/pkg/util/templates"
)

const (
	validResources = `

	* cluster
	* instancegroup
	* secret

	`
)

var (
	rootLong = templates.LongDesc(i18n.T(`
	kops is Kubernetes ops.

	kops is the easiest way to get a production grade Kubernetes cluster up and running.
	We like to think of it as kubectl for clusters.

	kops helps you create, destroy, upgrade and maintain production-grade, highly available,
	Kubernetes clusters from the command line. AWS (Amazon Web Services) is currently
	officially supported, with GCE and VMware vSphere in alpha support.
	`))

	rootShort = i18n.T(`kops is Kubernetes ops.`)
)

type Factory interface {
	Clientset() (simple.Clientset, error)
}

type RootCmd struct {
	util.FactoryOptions

	factory *util.Factory

	configFile string

	clusterName string

	cobraCommand *cobra.Command
}

var _ Factory = &RootCmd{}

var rootCommand = RootCmd{
	cobraCommand: &cobra.Command{
		Use:   "kops",
		Short: rootShort,
		Long:  rootLong,
	},
}

func Execute() {
	goflag.Set("logtostderr", "true")
	goflag.CommandLine.Parse([]string{})
	if err := rootCommand.cobraCommand.Execute(); err != nil {
		exitWithError(err)
	}
}

func init() {
	cobra.OnInitialize(initConfig)

	klog.InitFlags(nil)

	factory := util.NewFactory(&rootCommand.FactoryOptions)
	rootCommand.factory = factory

	NewCmdRoot(factory, os.Stdout)
}

func NewCmdRoot(f *util.Factory, out io.Writer) *cobra.Command {

	cmd := rootCommand.cobraCommand

	//cmd.PersistentFlags().AddGoFlagSet(goflag.CommandLine)
	goflag.CommandLine.VisitAll(func(goflag *goflag.Flag) {
		switch goflag.Name {
		case "cloud-provider-gce-lb-src-cidrs":
			// Skip; this is dragged in by the google cloudprovider dependency

		default:
			cmd.PersistentFlags().AddGoFlag(goflag)
		}
	})

	cmd.PersistentFlags().StringVar(&rootCommand.configFile, "config", "", "yaml config file (default is $HOME/.kops.yaml)")
	viper.BindPFlag("config", cmd.PersistentFlags().Lookup("config"))
	viper.SetDefault("config", "$HOME/.kops.yaml")

	cmd.PersistentFlags().StringVar(&rootCommand.RegistryPath, "state", "", "Location of state storage (kops 'config' file). Overrides KOPS_STATE_STORE environment variable")
	viper.BindPFlag("KOPS_STATE_STORE", cmd.PersistentFlags().Lookup("state"))
	viper.BindEnv("KOPS_STATE_STORE")

	defaultClusterName := os.Getenv("KOPS_CLUSTER_NAME")
	cmd.PersistentFlags().StringVarP(&rootCommand.clusterName, "name", "", defaultClusterName, "Name of cluster. Overrides KOPS_CLUSTER_NAME environment variable")

	// create subcommands
	cmd.AddCommand(NewCmdCompletion(f, out))
	cmd.AddCommand(NewCmdCreate(f, out))
	cmd.AddCommand(NewCmdDelete(f, out))
	cmd.AddCommand(NewCmdEdit(f, out))
	cmd.AddCommand(NewCmdExport(f, out))
	cmd.AddCommand(NewCmdGet(f, out))
	cmd.AddCommand(NewCmdUpdate(f, out))
	cmd.AddCommand(NewCmdReplace(f, out))
	cmd.AddCommand(NewCmdRollingUpdate(f, out))
	cmd.AddCommand(NewCmdSet(f, out))
	cmd.AddCommand(NewCmdToolbox(f, out))
	cmd.AddCommand(NewCmdValidate(f, out))
	cmd.AddCommand(NewCmdVersion(f, out))

	return cmd
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
	// Config file precedence: --config flag, ${HOME}/.kops.yaml ${HOME}/.kops/config
	configFile := rootCommand.configFile
	if configFile == "" {
		home := homedir.HomeDir()
		configPaths := []string{
			filepath.Join(home, ".kops.yaml"),
			filepath.Join(home, ".kops", "config"),
		}
		for _, p := range configPaths {
			_, err := os.Stat(p)
			if err == nil {
				configFile = p
				break
			} else if !os.IsNotExist(err) {
				klog.V(2).Infof("error checking for file %s: %v", p, err)
			}
		}
	}

	if configFile != "" {
		viper.SetConfigFile(configFile)
		viper.SetConfigType("yaml")

		if err := viper.ReadInConfig(); err != nil {
			klog.Warningf("error reading config: %v", err)
		}
	}

	rootCommand.RegistryPath = viper.GetString("KOPS_STATE_STORE")

	// Tolerate multiple slashes at end
	rootCommand.RegistryPath = strings.TrimSuffix(rootCommand.RegistryPath, "/")
}

func (c *RootCmd) AddCommand(cmd *cobra.Command) {
	c.cobraCommand.AddCommand(cmd)
}

// ProcessArgs will parse the positional args.  It assumes one of these formats:
//  * <no arguments at all>
//  * <clustername> (and --name not specified)
// Everything else is an error.
func (c *RootCmd) ProcessArgs(args []string) error {
	if len(args) == 0 {
		return nil
	}

	if len(args) == 1 {
		// Assume <clustername>
		if c.clusterName == "" {
			c.clusterName = args[0]
			return nil
		}
	}

	fmt.Printf("\nFound multiple arguments which look like a cluster name\n")
	if c.clusterName != "" {
		fmt.Printf("\t%q (via flag)\n", c.clusterName)
	}
	for _, arg := range args {
		fmt.Printf("\t%q (as argument)\n", arg)
	}
	fmt.Printf("\n")
	fmt.Printf("This often happens if you specify an argument to a boolean flag without using =\n")
	fmt.Printf("For example: use `--bastion=true` or `--bastion`, not `--bastion true`\n\n")

	if len(args) == 1 {
		return fmt.Errorf("cannot specify cluster via --name and positional argument")
	}
	return fmt.Errorf("expected a single <clustername> to be passed as an argument")
}

func (c *RootCmd) ClusterName() string {
	if c.clusterName != "" {
		return c.clusterName
	}

	c.clusterName = ClusterNameFromKubecfg()

	return c.clusterName
}

func ClusterNameFromKubecfg() string {
	// Read from kubeconfig
	pathOptions := clientcmd.NewDefaultPathOptions()

	clusterName := ""

	config, err := pathOptions.GetStartingConfig()
	if err != nil {
		klog.Warningf("error reading kubecfg: %v", err)
	} else if config.CurrentContext == "" {
		klog.Warningf("no context set in kubecfg")
	} else {
		context := config.Contexts[config.CurrentContext]
		if context == nil {
			klog.Warningf("context %q in kubecfg not found", config.CurrentContext)
		} else if context.Cluster == "" {
			klog.Warningf("context %q in kubecfg did not have a cluster", config.CurrentContext)
		} else {
			fmt.Fprintf(os.Stderr, "Using cluster from kubectl context: %s\n\n", context.Cluster)
			clusterName = context.Cluster
		}
	}

	//config, err := readKubectlClusterConfig()
	//if err != nil {
	//	klog.Warningf("error reading kubecfg: %v", err)
	//} else if config != nil && config.Name != "" {
	//	fmt.Fprintf(os.Stderr, "Using cluster from kubectl context: %s\n\n", config.Name)
	//	c.clusterName = config.Name
	//}

	return clusterName
}

func (c *RootCmd) Clientset() (simple.Clientset, error) {
	return c.factory.Clientset()
}

func (c *RootCmd) Cluster() (*kopsapi.Cluster, error) {
	clusterName := c.ClusterName()
	if clusterName == "" {
		return nil, fmt.Errorf("--name is required")
	}

	return GetCluster(c.factory, clusterName)
}

func GetCluster(factory Factory, clusterName string) (*kopsapi.Cluster, error) {
	if clusterName == "" {
		return nil, field.Required(field.NewPath("clusterName"), "Cluster name is required")
	}

	clientset, err := factory.Clientset()
	if err != nil {
		return nil, err
	}

	cluster, err := clientset.GetCluster(clusterName)
	if err != nil {
		return nil, fmt.Errorf("error reading cluster configuration: %v", err)
	}
	if cluster == nil {
		return nil, fmt.Errorf("cluster %q not found", clusterName)
	}

	if clusterName != cluster.ObjectMeta.Name {
		return nil, fmt.Errorf("cluster name did not match expected name: %v vs %v", clusterName, cluster.ObjectMeta.Name)
	}
	return cluster, nil
}

// ConsumeStdin reads all the bytes available from stdin
func ConsumeStdin() ([]byte, error) {
	file := os.Stdin
	buf := new(bytes.Buffer)
	_, err := buf.ReadFrom(file)
	if err != nil {
		return nil, fmt.Errorf("error reading stdin: %v", err)
	}
	return buf.Bytes(), nil
}
<commit_msg>Skip GCE cloudprovider flag cloud-provider-gce-l7lb-src-cidrs<commit_after>/*
Copyright 2019 The Kubernetes Authors.

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 main

import (
	"bytes"
	goflag "flag"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"strings"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"k8s.io/apimachinery/pkg/util/validation/field"
	"k8s.io/client-go/tools/clientcmd"
	"k8s.io/client-go/util/homedir"
	"k8s.io/klog"
	"k8s.io/kops/cmd/kops/util"
	kopsapi "k8s.io/kops/pkg/apis/kops"
	"k8s.io/kops/pkg/client/simple"
	"k8s.io/kubectl/pkg/util/i18n"
	"k8s.io/kubectl/pkg/util/templates"
)

const (
	validResources = `

	* cluster
	* instancegroup
	* secret

	`
)

var (
	rootLong = templates.LongDesc(i18n.T(`
	kops is Kubernetes ops.

	kops is the easiest way to get a production grade Kubernetes cluster up and running.
	We like to think of it as kubectl for clusters.

	kops helps you create, destroy, upgrade and maintain production-grade, highly available,
	Kubernetes clusters from the command line. AWS (Amazon Web Services) is currently
	officially supported, with GCE and VMware vSphere in alpha support.
	`))

	rootShort = i18n.T(`kops is Kubernetes ops.`)
)

type Factory interface {
	Clientset() (simple.Clientset, error)
}

type RootCmd struct {
	util.FactoryOptions

	factory *util.Factory

	configFile string

	clusterName string

	cobraCommand *cobra.Command
}

var _ Factory = &RootCmd{}

var rootCommand = RootCmd{
	cobraCommand: &cobra.Command{
		Use:   "kops",
		Short: rootShort,
		Long:  rootLong,
	},
}

func Execute() {
	goflag.Set("logtostderr", "true")
	goflag.CommandLine.Parse([]string{})
	if err := rootCommand.cobraCommand.Execute(); err != nil {
		exitWithError(err)
	}
}

func init() {
	cobra.OnInitialize(initConfig)

	klog.InitFlags(nil)

	factory := util.NewFactory(&rootCommand.FactoryOptions)
	rootCommand.factory = factory

	NewCmdRoot(factory, os.Stdout)
}

func NewCmdRoot(f *util.Factory, out io.Writer) *cobra.Command {

	cmd := rootCommand.cobraCommand

	//cmd.PersistentFlags().AddGoFlagSet(goflag.CommandLine)
	goflag.CommandLine.VisitAll(func(goflag *goflag.Flag) {
		switch goflag.Name {
		case "cloud-provider-gce-lb-src-cidrs":
		case "cloud-provider-gce-l7lb-src-cidrs":
			// Skip; these is dragged in by the google cloudprovider dependency

		default:
			cmd.PersistentFlags().AddGoFlag(goflag)
		}
	})

	cmd.PersistentFlags().StringVar(&rootCommand.configFile, "config", "", "yaml config file (default is $HOME/.kops.yaml)")
	viper.BindPFlag("config", cmd.PersistentFlags().Lookup("config"))
	viper.SetDefault("config", "$HOME/.kops.yaml")

	cmd.PersistentFlags().StringVar(&rootCommand.RegistryPath, "state", "", "Location of state storage (kops 'config' file). Overrides KOPS_STATE_STORE environment variable")
	viper.BindPFlag("KOPS_STATE_STORE", cmd.PersistentFlags().Lookup("state"))
	viper.BindEnv("KOPS_STATE_STORE")

	defaultClusterName := os.Getenv("KOPS_CLUSTER_NAME")
	cmd.PersistentFlags().StringVarP(&rootCommand.clusterName, "name", "", defaultClusterName, "Name of cluster. Overrides KOPS_CLUSTER_NAME environment variable")

	// create subcommands
	cmd.AddCommand(NewCmdCompletion(f, out))
	cmd.AddCommand(NewCmdCreate(f, out))
	cmd.AddCommand(NewCmdDelete(f, out))
	cmd.AddCommand(NewCmdEdit(f, out))
	cmd.AddCommand(NewCmdExport(f, out))
	cmd.AddCommand(NewCmdGet(f, out))
	cmd.AddCommand(NewCmdUpdate(f, out))
	cmd.AddCommand(NewCmdReplace(f, out))
	cmd.AddCommand(NewCmdRollingUpdate(f, out))
	cmd.AddCommand(NewCmdSet(f, out))
	cmd.AddCommand(NewCmdToolbox(f, out))
	cmd.AddCommand(NewCmdValidate(f, out))
	cmd.AddCommand(NewCmdVersion(f, out))

	return cmd
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
	// Config file precedence: --config flag, ${HOME}/.kops.yaml ${HOME}/.kops/config
	configFile := rootCommand.configFile
	if configFile == "" {
		home := homedir.HomeDir()
		configPaths := []string{
			filepath.Join(home, ".kops.yaml"),
			filepath.Join(home, ".kops", "config"),
		}
		for _, p := range configPaths {
			_, err := os.Stat(p)
			if err == nil {
				configFile = p
				break
			} else if !os.IsNotExist(err) {
				klog.V(2).Infof("error checking for file %s: %v", p, err)
			}
		}
	}

	if configFile != "" {
		viper.SetConfigFile(configFile)
		viper.SetConfigType("yaml")

		if err := viper.ReadInConfig(); err != nil {
			klog.Warningf("error reading config: %v", err)
		}
	}

	rootCommand.RegistryPath = viper.GetString("KOPS_STATE_STORE")

	// Tolerate multiple slashes at end
	rootCommand.RegistryPath = strings.TrimSuffix(rootCommand.RegistryPath, "/")
}

func (c *RootCmd) AddCommand(cmd *cobra.Command) {
	c.cobraCommand.AddCommand(cmd)
}

// ProcessArgs will parse the positional args.  It assumes one of these formats:
//  * <no arguments at all>
//  * <clustername> (and --name not specified)
// Everything else is an error.
func (c *RootCmd) ProcessArgs(args []string) error {
	if len(args) == 0 {
		return nil
	}

	if len(args) == 1 {
		// Assume <clustername>
		if c.clusterName == "" {
			c.clusterName = args[0]
			return nil
		}
	}

	fmt.Printf("\nFound multiple arguments which look like a cluster name\n")
	if c.clusterName != "" {
		fmt.Printf("\t%q (via flag)\n", c.clusterName)
	}
	for _, arg := range args {
		fmt.Printf("\t%q (as argument)\n", arg)
	}
	fmt.Printf("\n")
	fmt.Printf("This often happens if you specify an argument to a boolean flag without using =\n")
	fmt.Printf("For example: use `--bastion=true` or `--bastion`, not `--bastion true`\n\n")

	if len(args) == 1 {
		return fmt.Errorf("cannot specify cluster via --name and positional argument")
	}
	return fmt.Errorf("expected a single <clustername> to be passed as an argument")
}

func (c *RootCmd) ClusterName() string {
	if c.clusterName != "" {
		return c.clusterName
	}

	c.clusterName = ClusterNameFromKubecfg()

	return c.clusterName
}

func ClusterNameFromKubecfg() string {
	// Read from kubeconfig
	pathOptions := clientcmd.NewDefaultPathOptions()

	clusterName := ""

	config, err := pathOptions.GetStartingConfig()
	if err != nil {
		klog.Warningf("error reading kubecfg: %v", err)
	} else if config.CurrentContext == "" {
		klog.Warningf("no context set in kubecfg")
	} else {
		context := config.Contexts[config.CurrentContext]
		if context == nil {
			klog.Warningf("context %q in kubecfg not found", config.CurrentContext)
		} else if context.Cluster == "" {
			klog.Warningf("context %q in kubecfg did not have a cluster", config.CurrentContext)
		} else {
			fmt.Fprintf(os.Stderr, "Using cluster from kubectl context: %s\n\n", context.Cluster)
			clusterName = context.Cluster
		}
	}

	//config, err := readKubectlClusterConfig()
	//if err != nil {
	//	klog.Warningf("error reading kubecfg: %v", err)
	//} else if config != nil && config.Name != "" {
	//	fmt.Fprintf(os.Stderr, "Using cluster from kubectl context: %s\n\n", config.Name)
	//	c.clusterName = config.Name
	//}

	return clusterName
}

func (c *RootCmd) Clientset() (simple.Clientset, error) {
	return c.factory.Clientset()
}

func (c *RootCmd) Cluster() (*kopsapi.Cluster, error) {
	clusterName := c.ClusterName()
	if clusterName == "" {
		return nil, fmt.Errorf("--name is required")
	}

	return GetCluster(c.factory, clusterName)
}

func GetCluster(factory Factory, clusterName string) (*kopsapi.Cluster, error) {
	if clusterName == "" {
		return nil, field.Required(field.NewPath("clusterName"), "Cluster name is required")
	}

	clientset, err := factory.Clientset()
	if err != nil {
		return nil, err
	}

	cluster, err := clientset.GetCluster(clusterName)
	if err != nil {
		return nil, fmt.Errorf("error reading cluster configuration: %v", err)
	}
	if cluster == nil {
		return nil, fmt.Errorf("cluster %q not found", clusterName)
	}

	if clusterName != cluster.ObjectMeta.Name {
		return nil, fmt.Errorf("cluster name did not match expected name: %v vs %v", clusterName, cluster.ObjectMeta.Name)
	}
	return cluster, nil
}

// ConsumeStdin reads all the bytes available from stdin
func ConsumeStdin() ([]byte, error) {
	file := os.Stdin
	buf := new(bytes.Buffer)
	_, err := buf.ReadFrom(file)
	if err != nil {
		return nil, fmt.Errorf("error reading stdin: %v", err)
	}
	return buf.Bytes(), nil
}
<|endoftext|>


<commit_before>package main

import (
	"os"

	"golang.org/x/net/context"

	"github.com/bmatsuo/lark/cmd"
)

// MainCmd is the root lark command that will call subcommands as necessary.
var MainCmd = &cmd.Cmd{
	Name: os.Args[0],
	Run:  RunLark,
}

// RunLark performs logic for the default invocation `lark`.
func RunLark(c context.Context, prefix string, args []string) error {
	return nil
}
<commit_msg>remove unwanted file<commit_after><|endoftext|>