<commit_before>package werf

import (
	"fmt"
	"os"
	"path/filepath"
	"runtime"
)

var (
	Version = "dev"
)

var (
	tmpDir, homeDir  string
	sharedContextDir string
	localCacheDir    string
	serviceDir       string
)

func GetSharedContextDir() string {
	if sharedContextDir == "" {
		panic("bug: init required!")
	}

	return sharedContextDir
}

func GetLocalCacheDir() string {
	if localCacheDir == "" {
		panic("bug: init required!")
	}

	return localCacheDir
}

func GetServiceDir() string {
	if serviceDir == "" {
		panic("bug: init required!")
	}

	return serviceDir
}

func GetHomeDir() string {
	if homeDir == "" {
		panic("bug: init required!")
	}

	return homeDir
}

func GetTmpDir() string {
	if tmpDir == "" {
		panic("bug: init required!")
	}

	return tmpDir
}

func Init(tmpDirOption, homeDirOption string) error {
	if val, ok := os.LookupEnv("WERF_TMP_DIR"); ok {
		tmpDir = val
	} else if tmpDirOption != "" {
		tmpDir = tmpDirOption
	} else {
		tmpDir = os.TempDir()
	}

	if runtime.GOOS == "darwin" {
		dir, err := filepath.EvalSymlinks(tmpDir)
		if err != nil {
			return fmt.Errorf("eval symlinks of path %s failed: %s", tmpDir, err)
		}

		tmpDir = dir
	}

	if val, ok := os.LookupEnv("WERF_HOME"); ok {
		homeDir = val
	} else if homeDirOption != "" {
		homeDir = homeDirOption
	} else {
		homeDir = filepath.Join(os.Getenv("HOME"), ".werf")
	}

	// TODO: options + update purgeHomeWerfFiles

	sharedContextDir = filepath.Join(homeDir, "shared_context")
	localCacheDir = filepath.Join(homeDir, "local_cache")
	serviceDir = filepath.Join(homeDir, "service")

	return nil
}
<commit_msg>[windows] Fix default werf home dir<commit_after>package werf

import (
	"fmt"
	"os"
	"path/filepath"
	"runtime"
)

var (
	Version = "dev"
)

var (
	tmpDir, homeDir  string
	sharedContextDir string
	localCacheDir    string
	serviceDir       string
)

func GetSharedContextDir() string {
	if sharedContextDir == "" {
		panic("bug: init required!")
	}

	return sharedContextDir
}

func GetLocalCacheDir() string {
	if localCacheDir == "" {
		panic("bug: init required!")
	}

	return localCacheDir
}

func GetServiceDir() string {
	if serviceDir == "" {
		panic("bug: init required!")
	}

	return serviceDir
}

func GetHomeDir() string {
	if homeDir == "" {
		panic("bug: init required!")
	}

	return homeDir
}

func GetTmpDir() string {
	if tmpDir == "" {
		panic("bug: init required!")
	}

	return tmpDir
}

func Init(tmpDirOption, homeDirOption string) error {
	if val, ok := os.LookupEnv("WERF_TMP_DIR"); ok {
		tmpDir = val
	} else if tmpDirOption != "" {
		tmpDir = tmpDirOption
	} else {
		tmpDir = os.TempDir()
	}

	if runtime.GOOS == "darwin" {
		dir, err := filepath.EvalSymlinks(tmpDir)
		if err != nil {
			return fmt.Errorf("eval symlinks of path %s failed: %s", tmpDir, err)
		}

		tmpDir = dir
	}

	if val, ok := os.LookupEnv("WERF_HOME"); ok {
		homeDir = val
	} else if homeDirOption != "" {
		homeDir = homeDirOption
	} else {
		userHomeDir, err := os.UserHomeDir()
		if err != nil {
			return fmt.Errorf("get user home dir failed: %s", err)
		}

		homeDir = filepath.Join(userHomeDir, ".werf")
	}

	// TODO: options + update purgeHomeWerfFiles

	sharedContextDir = filepath.Join(homeDir, "shared_context")
	localCacheDir = filepath.Join(homeDir, "local_cache")
	serviceDir = filepath.Join(homeDir, "service")

	return nil
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"fmt"
	"github.com/couchbaselabs/go-couchbase"
	"log"
	"math/rand"
	"os"
	"text/tabwriter"
	"time"
)

var poolName = flag.String("pool", "default", "Pool to connect to")
var bucketName = flag.String("bucket", "default", "Bucket to connect to")

const myfmt = "2006-02-01-15:04:05.000000000"

var names = []string{
	"Jan Lehnardt",
	"John Christopher Anderson",
	"Noah Slater",
	"Filipe David Borba Manana",
	"Adam Kocoloski",
	"Paul Joseph Davis",
	"Christopher Lenz",
	"Damien F. Katz",
	"Robert Newson",
	"Benoit Chesneau",
	"Jason David Davies",
	"Mark Hammond",
	"Randall Leeds",
	"Bin Cui",
	"Benjamin Young",
	"Dustin Sallings",
	"Steve Yen",
	"Joe Schaefer",
}

var actions = []string{
	"submitted", "aborted", "approved", "declined",
}

var projects = []string{
	"ep-engine", "couchdb", "ns_server", "moxi", "libcouchbase",
}

type Record struct {
	Author   string `json:"author"`
	Reviewer string `json:"reviewer"`
	Action   string `json:"action"`
	Project  string `json:"project"`
	Score    int    `json:"score"`
}

func report(b couchbase.Bucket) {
	fmt.Printf("-----------------------------------------------------\n")
	tr := tabwriter.NewWriter(os.Stdout, 8, 8, 1, ' ', 0)
	defer tr.Flush()
	params := map[string]interface{}{
		"group_level": 1,
	}
	vres, err := b.View("test", "test", params)
	if err != nil {
		log.Fatalf("Error executing view:  %v", err)
	}

	for _, r := range vres.Rows {
		fmt.Fprintf(tr, "%v:\t%v\n", r.Key, r.Value)
	}
}

func harass(b couchbase.Bucket) {
	fmt.Printf("Doing stuff\n")

	go func() {
		for {
			time.Sleep(5 * time.Second)
			report(b)
		}
	}()

	for {
		r := Record{
			Author:   names[rand.Intn(len(names))],
			Reviewer: names[rand.Intn(len(names))],
			Action:   actions[rand.Intn(len(actions))],
			Project:  projects[rand.Intn(len(projects))],
			Score:    rand.Intn(4) - 2,
		}

		k := time.Now().Format(myfmt)

		// mfmt.Printf("%s:  %#v\n", k, r)
		if err := b.Set(k, r); err != nil {
			log.Fatalf("Oops, failed a store of %s:  %v", k, err)
		}
	}
}

func main() {
	flag.Parse()
	c, err := couchbase.Connect(flag.Arg(0))
	if err != nil {
		log.Fatalf("Error connecting:  %v", err)
	}

	pool, err := c.GetPool(*poolName)
	if err != nil {
		log.Fatalf("Error getting pool:  %v", err)
	}

	bucket, err := pool.GetBucket(*bucketName)
	if err != nil {
		log.Fatalf("Error getting bucket:  %v", err)
	}

	harass(bucket)
}
<commit_msg>Killed a commented-out line.<commit_after>package main

import (
	"flag"
	"fmt"
	"github.com/couchbaselabs/go-couchbase"
	"log"
	"math/rand"
	"os"
	"text/tabwriter"
	"time"
)

var poolName = flag.String("pool", "default", "Pool to connect to")
var bucketName = flag.String("bucket", "default", "Bucket to connect to")

const myfmt = "2006-02-01-15:04:05.000000000"

var names = []string{
	"Jan Lehnardt",
	"John Christopher Anderson",
	"Noah Slater",
	"Filipe David Borba Manana",
	"Adam Kocoloski",
	"Paul Joseph Davis",
	"Christopher Lenz",
	"Damien F. Katz",
	"Robert Newson",
	"Benoit Chesneau",
	"Jason David Davies",
	"Mark Hammond",
	"Randall Leeds",
	"Bin Cui",
	"Benjamin Young",
	"Dustin Sallings",
	"Steve Yen",
	"Joe Schaefer",
}

var actions = []string{
	"submitted", "aborted", "approved", "declined",
}

var projects = []string{
	"ep-engine", "couchdb", "ns_server", "moxi", "libcouchbase",
}

type Record struct {
	Author   string `json:"author"`
	Reviewer string `json:"reviewer"`
	Action   string `json:"action"`
	Project  string `json:"project"`
	Score    int    `json:"score"`
}

func report(b couchbase.Bucket) {
	fmt.Printf("-----------------------------------------------------\n")
	tr := tabwriter.NewWriter(os.Stdout, 8, 8, 1, ' ', 0)
	defer tr.Flush()
	params := map[string]interface{}{
		"group_level": 1,
	}
	vres, err := b.View("test", "test", params)
	if err != nil {
		log.Fatalf("Error executing view:  %v", err)
	}

	for _, r := range vres.Rows {
		fmt.Fprintf(tr, "%v:\t%v\n", r.Key, r.Value)
	}
}

func harass(b couchbase.Bucket) {
	fmt.Printf("Doing stuff\n")

	go func() {
		for {
			time.Sleep(5 * time.Second)
			report(b)
		}
	}()

	for {
		r := Record{
			Author:   names[rand.Intn(len(names))],
			Reviewer: names[rand.Intn(len(names))],
			Action:   actions[rand.Intn(len(actions))],
			Project:  projects[rand.Intn(len(projects))],
			Score:    rand.Intn(4) - 2,
		}

		k := time.Now().Format(myfmt)

		if err := b.Set(k, r); err != nil {
			log.Fatalf("Oops, failed a store of %s:  %v", k, err)
		}
	}
}

func main() {
	flag.Parse()
	c, err := couchbase.Connect(flag.Arg(0))
	if err != nil {
		log.Fatalf("Error connecting:  %v", err)
	}

	pool, err := c.GetPool(*poolName)
	if err != nil {
		log.Fatalf("Error getting pool:  %v", err)
	}

	bucket, err := pool.GetBucket(*bucketName)
	if err != nil {
		log.Fatalf("Error getting bucket:  %v", err)
	}

	harass(bucket)
}
<|endoftext|>


<commit_before>package Lint

import "time"

const (
	// AuthenticationURL - API address to Authenticate Pocket Consumer Key
	AuthenticationURL string = "https://getpocket.com/v3/oauth/request"

	// AuthorisationURL - API address to Authorise and recience a Request Key
	AuthorisationURL string = "https://getpocket.com/v3/oauth/authorize"

	//UserAuthorisationURL - Address that a user must enter into their browser to Authorise Lint to access Pocket
	UserAuthorisationURL string = "https://getpocket.com/auth/authorize?"

	//RedirectURI - Link back location after Authorisation has been granted
	RedirectURI string = "https://github.com/daveym/lint/blob/master/AUTHCOMPLETE.md"
)

// Initial Authentication response from Pocket
type authenticationResponse struct {
	Code  string
	State string
}

// Initial Authorisation response from Pocket
type authorisationResponse struct {
	AccessToken string
	Username    string
}

type getListRequest struct {
	State       string
	Favorite    int
	Tag         string
	ContentType string
	Sort        string
	DetailType  string
	Search      string
	Domain      string
	Since       time.Time
	Count       int
	Offset      int
}
<commit_msg>More types added for response<commit_after>package Lint

import "time"

const (
	// AuthenticationURL - API address to Authenticate Pocket Consumer Key
	AuthenticationURL string = "https://getpocket.com/v3/oauth/request"

	// AuthorisationURL - API address to Authorise and recience a Request Key
	AuthorisationURL string = "https://getpocket.com/v3/oauth/authorize"

	//UserAuthorisationURL - Address that a user must enter into their browser to Authorise Lint to access Pocket
	UserAuthorisationURL string = "https://getpocket.com/auth/authorize?"

	//RedirectURI - Link back location after Authorisation has been granted
	RedirectURI string = "https://github.com/daveym/lint/blob/master/AUTHCOMPLETE.md"
)

type Time time.Time

// Initial Authentication response from Pocket
type authenticationResponse struct {
	Code  string
	State string
}

// Initial Authorisation response from Pocket
type authorisationResponse struct {
	AccessToken string
	Username    string
}

type getListRequest struct {
	State       string
	Favorite    int
	Tag         string
	ContentType string
	Sort        string
	DetailType  string
	Search      string
	Domain      string
	Since       Time
	Count       int
	Offset      int
}

type ItemStatus int
type ItemMediaAttachment int

const (
	ItemStatusUnread   ItemStatus = 0
	ItemStatusArchived            = 1
	ItemStatusDeleted             = 2
)

const (
	ItemMediaAttachmentNoMedia  ItemMediaAttachment = 0
	ItemMediaAttachmentHasMedia                     = 1
	ItemMediaAttachmentIsMedia                      = 2
)

type listItem struct {
	ItemID        int        `json:"item_id,string"`
	ResolvedId    int        `json:"resolved_id,string"`
	GivenURL      string     `json:"given_url"`
	ResolvedURL   string     `json:"resolved_url"`
	GivenTitle    string     `json:"given_title"`
	ResolvedTitle string     `json:"resolved_title"`
	Favorite      int        `json:",string"`
	Status        ItemStatus `json:",string"`
	Excerpt       string
	IsArticle     int                 `json:"is_article,string"`
	HasImage      ItemMediaAttachment `json:"has_image,string"`
	HasVideo      ItemMediaAttachment `json:"has_video,string"`
	WordCount     int                 `json:"word_count,string"`
	Tags          map[string]map[string]interface{}
	Authors       map[string]map[string]interface{}
	Images        map[string]map[string]interface{}
	Videos        map[string]map[string]interface{}
	SortId        int  `json:"sort_id"`
	TimeAdded     Time `json:"time_added"`
	TimeUpdated   Time `json:"time_updated"`
	TimeRead      Time `json:"time_read"`
	TimeFavorited Time `json:"time_favorited"`
}
<|endoftext|>


<commit_before>// Copyright 2016 Stefan Nyman.
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.

package hellosign

import "fmt"

// EmbeddedAPI used for embedded signature manipulations.
type EmbeddedAPI struct {
	*hellosign
}

// NewEmbeddedAPI creates a new api client for embedded operations.
func NewEmbeddedAPI(apiKey string) *EmbeddedAPI {
	return &EmbeddedAPI{newHellosign(apiKey)}
}

// EmbeddedURL is an URL with an expiration time.
type EmbeddedURL struct {
	SignURL   string `json:"sign_url"`
	ExpiresAt uint64 `json:"expires_at"`
}

// GetSignURL retrieves an embedded object containing a signature url that can be opened in an iFrame.
func (c *EmbeddedAPI) GetSignURL(signatureID string) (*EmbeddedURL, error) {
	url := &EmbeddedURL{}
	if err := c.getAndParse(fmt.Sprintf("embedded/sign_url/%s", signatureID), nil, url); err != nil {
		return nil, err
	}
	return url, nil
}

// GetTemplateEditURL retrieves an embedded object containing a template url that can be opened in an iFrame.
// Note that only templates created via the embedded template process are available to be edited with this endpoint.
func (c *EmbeddedAPI) GetTemplateEditURL(templateID string) (*EmbeddedURL, error) {
	url := &EmbeddedURL{}
	if err := c.getAndParse(fmt.Sprintf("embedded/edit_url/%s", templateID), nil, url); err != nil {
		return nil, err
	}
	return url, nil
}
<commit_msg>embedded: parse raw response and return actual data<commit_after>// Copyright 2016 Stefan Nyman.
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.

package hellosign

import "fmt"

// EmbeddedAPI used for embedded signature manipulations.
type EmbeddedAPI struct {
	*hellosign
}

// NewEmbeddedAPI creates a new api client for embedded operations.
func NewEmbeddedAPI(apiKey string) *EmbeddedAPI {
	return &EmbeddedAPI{newHellosign(apiKey)}
}

// EmbeddedURL is an URL with an expiration time.
type EmbeddedURL struct {
	SignURL   string `json:"sign_url"`
	ExpiresAt uint64 `json:"expires_at"`
}

type embeddedURLRaw struct {
	Embedded EmbeddedURL `json:"embedded"`
}

// GetSignURL retrieves an embedded object containing a signature url that can be opened in an iFrame.
func (c *EmbeddedAPI) GetSignURL(signatureID string) (*EmbeddedURL, error) {
	url := &embeddedURLRaw{}
	if err := c.getAndParse(fmt.Sprintf("embedded/sign_url/%s", signatureID), nil, url); err != nil {
		return nil, err
	}
	return &url.Embedded, nil
}

// GetTemplateEditURL retrieves an embedded object containing a template url that can be opened in an iFrame.
// Note that only templates created via the embedded template process are available to be edited with this endpoint.
func (c *EmbeddedAPI) GetTemplateEditURL(templateID string) (*EmbeddedURL, error) {
	url := &embeddedURLRaw{}
	if err := c.getAndParse(fmt.Sprintf("embedded/edit_url/%s", templateID), nil, url); err != nil {
		return nil, err
	}
	return &url.Embedded, nil
}
<|endoftext|>


<commit_before>package kubernetes

import (
	"bytes"
	"fmt"
	"io"
	"os/exec"
	"strings"
	"time"

	"github.com/go-kit/kit/log"
	"github.com/pkg/errors"
	"github.com/weaveworks/flux/cluster"
	rest "k8s.io/client-go/rest"
)

type Kubectl struct {
	exe    string
	config *rest.Config
}

func NewKubectl(exe string, config *rest.Config) *Kubectl {
	return &Kubectl{
		exe:    exe,
		config: config,
	}
}

func (c *Kubectl) connectArgs() []string {
	var args []string
	if c.config.Host != "" {
		args = append(args, fmt.Sprintf("--server=%s", c.config.Host))
	}
	if c.config.Username != "" {
		args = append(args, fmt.Sprintf("--username=%s", c.config.Username))
	}
	if c.config.Password != "" {
		args = append(args, fmt.Sprintf("--password=%s", c.config.Password))
	}
	if c.config.TLSClientConfig.CertFile != "" {
		args = append(args, fmt.Sprintf("--client-certificate=%s", c.config.TLSClientConfig.CertFile))
	}
	if c.config.TLSClientConfig.CAFile != "" {
		args = append(args, fmt.Sprintf("--certificate-authority=%s", c.config.TLSClientConfig.CAFile))
	}
	if c.config.TLSClientConfig.KeyFile != "" {
		args = append(args, fmt.Sprintf("--client-key=%s", c.config.TLSClientConfig.KeyFile))
	}
	if c.config.BearerToken != "" {
		args = append(args, fmt.Sprintf("--token=%s", c.config.BearerToken))
	}
	return args
}

func (c *Kubectl) apply(logger log.Logger, cs changeSet, errs cluster.SyncError) {
	f := func(m map[string][]obj, cmd string, args ...string) {
		objs := m[cmd]
		if len(objs) == 0 {
			return
		}
		args = append(args, cmd)
		if err := c.doCommand(logger, makeMultidoc(objs), args...); err != nil {
			for _, obj := range objs {
				r := bytes.NewReader(obj.bytes)
				if err := c.doCommand(logger, r, args...); err != nil {
					errs[obj.id] = err
				}
			}
		}
	}

	// When deleting resources we must ensure any resource in a non-default
	// namespace is deleted before the namespace that it is in. Since namespace
	// resources don't specify a namespace, this ordering guarantees that.
	f(cs.nsObjs, "delete")
	f(cs.noNsObjs, "delete", "--namespace", "default")
	// Likewise, when applying resources we must ensure the namespace is applied
	// first, so we run the commands the other way round.
	f(cs.noNsObjs, "apply", "--namespace", "default")
	f(cs.nsObjs, "apply")

}

func (c *Kubectl) doCommand(logger log.Logger, r io.Reader, args ...string) error {
	args = append(args, "-f", "-")
	cmd := c.kubectlCommand(args...)
	cmd.Stdin = r
	stderr := &bytes.Buffer{}
	cmd.Stderr = stderr
	stdout := &bytes.Buffer{}
	cmd.Stdout = stdout

	begin := time.Now()
	err := cmd.Run()
	if err != nil {
		err = errors.Wrap(errors.New(strings.TrimSpace(stderr.String())), "running kubectl")
	}

	logger.Log("cmd", "kubectl "+strings.Join(args, " "), "took", time.Since(begin), "err", err, "output", strings.TrimSpace(stdout.String()))
	return err
}

func makeMultidoc(objs []obj) *bytes.Buffer {
	buf := &bytes.Buffer{}
	for _, obj := range objs {
		buf.WriteString("---\n" + string(obj.bytes))
	}
	return buf
}

func (c *Kubectl) kubectlCommand(args ...string) *exec.Cmd {
	return exec.Command(c.exe, append(c.connectArgs(), args...)...)
}
<commit_msg>Make sure multi-yamels are delimited<commit_after>package kubernetes

import (
	"bytes"
	"fmt"
	"io"
	"os/exec"
	"strings"
	"time"

	"github.com/go-kit/kit/log"
	"github.com/pkg/errors"
	"github.com/weaveworks/flux/cluster"
	rest "k8s.io/client-go/rest"
)

type Kubectl struct {
	exe    string
	config *rest.Config
}

func NewKubectl(exe string, config *rest.Config) *Kubectl {
	return &Kubectl{
		exe:    exe,
		config: config,
	}
}

func (c *Kubectl) connectArgs() []string {
	var args []string
	if c.config.Host != "" {
		args = append(args, fmt.Sprintf("--server=%s", c.config.Host))
	}
	if c.config.Username != "" {
		args = append(args, fmt.Sprintf("--username=%s", c.config.Username))
	}
	if c.config.Password != "" {
		args = append(args, fmt.Sprintf("--password=%s", c.config.Password))
	}
	if c.config.TLSClientConfig.CertFile != "" {
		args = append(args, fmt.Sprintf("--client-certificate=%s", c.config.TLSClientConfig.CertFile))
	}
	if c.config.TLSClientConfig.CAFile != "" {
		args = append(args, fmt.Sprintf("--certificate-authority=%s", c.config.TLSClientConfig.CAFile))
	}
	if c.config.TLSClientConfig.KeyFile != "" {
		args = append(args, fmt.Sprintf("--client-key=%s", c.config.TLSClientConfig.KeyFile))
	}
	if c.config.BearerToken != "" {
		args = append(args, fmt.Sprintf("--token=%s", c.config.BearerToken))
	}
	return args
}

func (c *Kubectl) apply(logger log.Logger, cs changeSet, errs cluster.SyncError) {
	f := func(m map[string][]obj, cmd string, args ...string) {
		objs := m[cmd]
		if len(objs) == 0 {
			return
		}
		logger.Log("cmd", cmd, "args", strings.Join(args, " "), "count", len(objs))
		args = append(args, cmd)
		if err := c.doCommand(logger, makeMultidoc(objs), args...); err != nil {
			for _, obj := range objs {
				r := bytes.NewReader(obj.bytes)
				if err := c.doCommand(logger, r, args...); err != nil {
					errs[obj.id] = err
				}
			}
		}
	}

	// When deleting resources we must ensure any resource in a non-default
	// namespace is deleted before the namespace that it is in. Since namespace
	// resources don't specify a namespace, this ordering guarantees that.
	f(cs.nsObjs, "delete")
	f(cs.noNsObjs, "delete", "--namespace", "default")
	// Likewise, when applying resources we must ensure the namespace is applied
	// first, so we run the commands the other way round.
	f(cs.noNsObjs, "apply", "--namespace", "default")
	f(cs.nsObjs, "apply")

}

func (c *Kubectl) doCommand(logger log.Logger, r io.Reader, args ...string) error {
	args = append(args, "-f", "-")
	cmd := c.kubectlCommand(args...)
	cmd.Stdin = r
	stderr := &bytes.Buffer{}
	cmd.Stderr = stderr
	stdout := &bytes.Buffer{}
	cmd.Stdout = stdout

	begin := time.Now()
	err := cmd.Run()
	if err != nil {
		err = errors.Wrap(errors.New(strings.TrimSpace(stderr.String())), "running kubectl")
	}

	logger.Log("cmd", "kubectl "+strings.Join(args, " "), "took", time.Since(begin), "err", err, "output", strings.TrimSpace(stdout.String()))
	return err
}

func makeMultidoc(objs []obj) *bytes.Buffer {
	buf := &bytes.Buffer{}
	for _, obj := range objs {
		buf.WriteString("\n---\n" + string(obj.bytes))
	}
	return buf
}

func (c *Kubectl) kubectlCommand(args ...string) *exec.Cmd {
	return exec.Command(c.exe, append(c.connectArgs(), args...)...)
}
<|endoftext|>


<commit_before>// Copyright 2012 Apcera Inc. All rights reserved.

package nats

import (
	"bytes"
	"testing"
	"time"
)

func NewEConn(t *testing.T) *EncodedConn {
	ec, err := NewEncodedConn(newConnection(t), "default")
	if err != nil {
		t.Fatalf("Failed to create an encoded connection: %v\n", err)
	}
	return ec
}

func TestMarshalString(t *testing.T) {
	ec := NewEConn(t)
	defer ec.Close()
	ch := make(chan bool)

	testString := "Hello World!"

	ec.Subscribe("enc_string", func(s string) {
		if s != testString {
			t.Fatalf("Received test string of '%s', wanted '%s'\n", s, testString)
		}
		ch <- true
	})
	ec.Publish("enc_string", testString)
	if e := wait(ch); e != nil {
		if ec.LastError() != nil {
			e = ec.LastError()
		}
		t.Fatalf("Did not receive the message: %s", e)
	}
}

func TestMarshalBytes(t *testing.T) {
	ec := NewEConn(t)
	defer ec.Close()
	ch := make(chan bool)

	testBytes := []byte("Hello World!")

	ec.Subscribe("enc_bytes", func(b []byte) {
		if !bytes.Equal(b, testBytes) {
			t.Fatalf("Received test bytes of '%s', wanted '%s'\n", b, testBytes)
		}
		ch <- true
	})
	ec.Publish("enc_bytes", testBytes)
	if e := wait(ch); e != nil {
		if ec.LastError() != nil {
			e = ec.LastError()
		}
		t.Fatalf("Did not receive the message: %s", e)
	}
}

func TestMarshalInt(t *testing.T) {
	ec := NewEConn(t)
	defer ec.Close()
	ch := make(chan bool)

	testN := 22

	ec.Subscribe("enc_int", func(n int) {
		if n != testN {
			t.Fatalf("Received test number of %d, wanted %d\n", n, testN)
		}
		ch <- true
	})
	ec.Publish("enc_int", testN)
	if e := wait(ch); e != nil {
		if ec.LastError() != nil {
			e = ec.LastError()
		}
		t.Fatalf("Did not receive the message: %s", e)
	}
}

func TestMarshalInt32(t *testing.T) {
	ec := NewEConn(t)
	defer ec.Close()
	ch := make(chan bool)

	testN := 22

	ec.Subscribe("enc_int", func(n int32) {
		if n != int32(testN) {
			t.Fatalf("Received test number of %d, wanted %d\n", n, testN)
		}
		ch <- true
	})
	ec.Publish("enc_int", testN)
	if e := wait(ch); e != nil {
		if ec.LastError() != nil {
			e = ec.LastError()
		}
		t.Fatalf("Did not receive the message: %s", e)
	}
}

func TestMarshalInt64(t *testing.T) {
	ec := NewEConn(t)
	defer ec.Close()
	ch := make(chan bool)

	testN := 22

	ec.Subscribe("enc_int", func(n int64) {
		if n != int64(testN) {
			t.Fatalf("Received test number of %d, wanted %d\n", n, testN)
		}
		ch <- true
	})
	ec.Publish("enc_int", testN)
	if e := wait(ch); e != nil {
		if ec.LastError() != nil {
			e = ec.LastError()
		}
		t.Fatalf("Did not receive the message: %s", e)
	}
}

func TestMarshalFloat32(t *testing.T) {
	ec := NewEConn(t)
	defer ec.Close()
	ch := make(chan bool)

	testN := float32(22)

	ec.Subscribe("enc_float", func(n float32) {
		if n != testN {
			t.Fatalf("Received test number of %f, wanted %f\n", n, testN)
		}
		ch <- true
	})
	ec.Publish("enc_float", testN)
	if e := wait(ch); e != nil {
		if ec.LastError() != nil {
			e = ec.LastError()
		}
		t.Fatalf("Did not receive the message: %s", e)
	}
}

func TestMarshalFloat64(t *testing.T) {
	ec := NewEConn(t)
	defer ec.Close()
	ch := make(chan bool)

	testN := float64(22.22)

	ec.Subscribe("enc_float", func(n float64) {
		if n != testN {
			t.Fatalf("Received test number of %f, wanted %f\n", n, testN)
		}
		ch <- true
	})
	ec.Publish("enc_float", testN)
	if e := wait(ch); e != nil {
		if ec.LastError() != nil {
			e = ec.LastError()
		}
		t.Fatalf("Did not receive the message: %s", e)
	}
}

func TestMarshalBool(t *testing.T) {
	ec := NewEConn(t)
	defer ec.Close()
	ch := make(chan bool)

	ec.Subscribe("enc_bool", func(b bool) {
		if b != false {
			t.Fatal("Boolean values did not match")
		}
		ch <- true
	})
	ec.Publish("enc_bool", false)
	if e := wait(ch); e != nil {
		if ec.LastError() != nil {
			e = ec.LastError()
		}
		t.Fatalf("Did not receive the message: %s", e)
	}
}

func TestExtendedSubscribeCB(t *testing.T) {
	ec := NewEConn(t)
	defer ec.Close()

	ch := make(chan bool)

	testString := "Hello World!"
	subject := "cb_args"

	ec.Subscribe(subject, func(subj, s string) {
		if s != testString {
			t.Fatalf("Received test string of '%s', wanted '%s'\n", s, testString)
		}
		if subj != subject {
			t.Fatalf("Received subject of '%s', wanted '%s'\n", subj, subject)
		}
		ch <- true
	})
	ec.Publish(subject, testString)
	if e := wait(ch); e != nil {
		if ec.LastError() != nil {
			e = ec.LastError()
		}
		t.Fatalf("Did not receive the message: %s", e)
	}
}

func TestExtendedSubscribeCB2(t *testing.T) {
	ec := NewEConn(t)
	defer ec.Close()

	ch := make(chan bool)

	testString := "Hello World!"
	oSubj := "cb_args"
	oReply := "foobar"

	ec.Subscribe(oSubj, func(subj, reply, s string) {
		if s != testString {
			t.Fatalf("Received test string of '%s', wanted '%s'\n", s, testString)
		}
		if subj != oSubj {
			t.Fatalf("Received subject of '%s', wanted '%s'\n", subj, oSubj)
		}
		if reply != oReply {
			t.Fatalf("Received reply of '%s', wanted '%s'\n", reply, oReply)
		}
		ch <- true
	})
	ec.PublishRequest(oSubj, oReply, testString)
	if e := wait(ch); e != nil {
		if ec.LastError() != nil {
			e = ec.LastError()
		}
		t.Fatalf("Did not receive the message: %s", e)
	}
}

func TestEncRequest(t *testing.T) {
	ec := NewEConn(t)
	defer ec.Close()

	ec.Subscribe("help", func(subj, reply, req string) {
		ec.Publish(reply, "I can help!")
	})

	var resp string

	err := ec.Request("help", "help me", &resp, 500*time.Millisecond)
	if err != nil {
		t.Fatalf("Failed at receiving proper response: %v\n", err)
	}
}

func TestEncRequestReceivesMsg(t *testing.T) {
	ec := NewEConn(t)
	defer ec.Close()

	ec.Subscribe("help", func(subj, reply, req string) {
		ec.Publish(reply, "I can help!")
	})

	var resp Msg

	err := ec.Request("help", "help me", &resp, 500*time.Millisecond)
	if err != nil {
		t.Fatalf("Failed at receiving proper response: %v\n", err)
	}
}

func TestAsyncMarshalErr(t *testing.T) {
	ec := NewEConn(t)
	defer ec.Close()

	ch := make(chan bool)

	testString := "Hello World!"
	subject := "err_marshall"

	ec.Subscribe(subject, func(subj, num int) {
		// This will never get called.
	})

	ec.Conn.Opts.AsyncErrorCB = func(c *Conn, s *Subscription, err error) {
		ch <- true
	}

	ec.Publish(subject, testString)
	if e := wait(ch); e != nil {
		t.Fatalf("Did not receive the message: %s", e)
	}
}
<commit_msg>Increased test coverage<commit_after>// Copyright 2012 Apcera Inc. All rights reserved.

package nats

import (
	"bytes"
	"testing"
	"time"
)

func NewEConn(t *testing.T) *EncodedConn {
	ec, err := NewEncodedConn(newConnection(t), "default")
	if err != nil {
		t.Fatalf("Failed to create an encoded connection: %v\n", err)
	}
	return ec
}

func TestMarshalString(t *testing.T) {
	ec := NewEConn(t)
	defer ec.Close()
	ch := make(chan bool)

	testString := "Hello World!"

	ec.Subscribe("enc_string", func(s string) {
		if s != testString {
			t.Fatalf("Received test string of '%s', wanted '%s'\n", s, testString)
		}
		ch <- true
	})
	ec.Publish("enc_string", testString)
	if e := wait(ch); e != nil {
		if ec.LastError() != nil {
			e = ec.LastError()
		}
		t.Fatalf("Did not receive the message: %s", e)
	}
}

func TestMarshalBytes(t *testing.T) {
	ec := NewEConn(t)
	defer ec.Close()
	ch := make(chan bool)

	testBytes := []byte("Hello World!")

	ec.Subscribe("enc_bytes", func(b []byte) {
		if !bytes.Equal(b, testBytes) {
			t.Fatalf("Received test bytes of '%s', wanted '%s'\n", b, testBytes)
		}
		ch <- true
	})
	ec.Publish("enc_bytes", testBytes)
	if e := wait(ch); e != nil {
		if ec.LastError() != nil {
			e = ec.LastError()
		}
		t.Fatalf("Did not receive the message: %s", e)
	}
}

func TestMarshalInt(t *testing.T) {
	ec := NewEConn(t)
	defer ec.Close()
	ch := make(chan bool)

	testN := 22

	ec.Subscribe("enc_int", func(n int) {
		if n != testN {
			t.Fatalf("Received test number of %d, wanted %d\n", n, testN)
		}
		ch <- true
	})
	ec.Publish("enc_int", testN)
	if e := wait(ch); e != nil {
		if ec.LastError() != nil {
			e = ec.LastError()
		}
		t.Fatalf("Did not receive the message: %s", e)
	}
}

func TestMarshalInt32(t *testing.T) {
	ec := NewEConn(t)
	defer ec.Close()
	ch := make(chan bool)

	testN := 22

	ec.Subscribe("enc_int", func(n int32) {
		if n != int32(testN) {
			t.Fatalf("Received test number of %d, wanted %d\n", n, testN)
		}
		ch <- true
	})
	ec.Publish("enc_int", testN)
	if e := wait(ch); e != nil {
		if ec.LastError() != nil {
			e = ec.LastError()
		}
		t.Fatalf("Did not receive the message: %s", e)
	}
}

func TestMarshalInt64(t *testing.T) {
	ec := NewEConn(t)
	defer ec.Close()
	ch := make(chan bool)

	testN := 22

	ec.Subscribe("enc_int", func(n int64) {
		if n != int64(testN) {
			t.Fatalf("Received test number of %d, wanted %d\n", n, testN)
		}
		ch <- true
	})
	ec.Publish("enc_int", testN)
	if e := wait(ch); e != nil {
		if ec.LastError() != nil {
			e = ec.LastError()
		}
		t.Fatalf("Did not receive the message: %s", e)
	}
}

func TestMarshalFloat32(t *testing.T) {
	ec := NewEConn(t)
	defer ec.Close()
	ch := make(chan bool)

	testN := float32(22)

	ec.Subscribe("enc_float", func(n float32) {
		if n != testN {
			t.Fatalf("Received test number of %f, wanted %f\n", n, testN)
		}
		ch <- true
	})
	ec.Publish("enc_float", testN)
	if e := wait(ch); e != nil {
		if ec.LastError() != nil {
			e = ec.LastError()
		}
		t.Fatalf("Did not receive the message: %s", e)
	}
}

func TestMarshalFloat64(t *testing.T) {
	ec := NewEConn(t)
	defer ec.Close()
	ch := make(chan bool)

	testN := float64(22.22)

	ec.Subscribe("enc_float", func(n float64) {
		if n != testN {
			t.Fatalf("Received test number of %f, wanted %f\n", n, testN)
		}
		ch <- true
	})
	ec.Publish("enc_float", testN)
	if e := wait(ch); e != nil {
		if ec.LastError() != nil {
			e = ec.LastError()
		}
		t.Fatalf("Did not receive the message: %s", e)
	}
}

func TestMarshalBool(t *testing.T) {
	ec := NewEConn(t)
	defer ec.Close()
	ch := make(chan bool)

	ec.Subscribe("enc_bool", func(b bool) {
		if b != false {
			t.Fatal("Boolean values did not match")
		}
		ch <- true
	})
	ec.Publish("enc_bool", false)
	if e := wait(ch); e != nil {
		if ec.LastError() != nil {
			e = ec.LastError()
		}
		t.Fatalf("Did not receive the message: %s", e)
	}
}

func TestExtendedSubscribeCB(t *testing.T) {
	ec := NewEConn(t)
	defer ec.Close()

	ch := make(chan bool)

	testString := "Hello World!"
	subject := "cb_args"

	ec.Subscribe(subject, func(subj, s string) {
		if s != testString {
			t.Fatalf("Received test string of '%s', wanted '%s'\n", s, testString)
		}
		if subj != subject {
			t.Fatalf("Received subject of '%s', wanted '%s'\n", subj, subject)
		}
		ch <- true
	})
	ec.Publish(subject, testString)
	if e := wait(ch); e != nil {
		if ec.LastError() != nil {
			e = ec.LastError()
		}
		t.Fatalf("Did not receive the message: %s", e)
	}
}

func TestExtendedSubscribeCB2(t *testing.T) {
	ec := NewEConn(t)
	defer ec.Close()

	ch := make(chan bool)

	testString := "Hello World!"
	oSubj := "cb_args"
	oReply := "foobar"

	ec.Subscribe(oSubj, func(subj, reply, s string) {
		if s != testString {
			t.Fatalf("Received test string of '%s', wanted '%s'\n", s, testString)
		}
		if subj != oSubj {
			t.Fatalf("Received subject of '%s', wanted '%s'\n", subj, oSubj)
		}
		if reply != oReply {
			t.Fatalf("Received reply of '%s', wanted '%s'\n", reply, oReply)
		}
		ch <- true
	})
	ec.PublishRequest(oSubj, oReply, testString)
	if e := wait(ch); e != nil {
		if ec.LastError() != nil {
			e = ec.LastError()
		}
		t.Fatalf("Did not receive the message: %s", e)
	}
}

func TestEncRequest(t *testing.T) {
	ec := NewEConn(t)
	defer ec.Close()

	ec.Subscribe("help", func(subj, reply, req string) {
		ec.Publish(reply, "I can help!")
	})

	var resp string

	err := ec.Request("help", "help me", &resp, 500*time.Millisecond)
	if err != nil {
		t.Fatalf("Failed at receiving proper response: %v\n", err)
	}
}

func TestEncRequestReceivesMsg(t *testing.T) {
	ec := NewEConn(t)
	defer ec.Close()

	ec.Subscribe("help", func(subj, reply, req string) {
		ec.Publish(reply, "I can help!")
	})

	var resp Msg

	err := ec.Request("help", "help me", &resp, 500*time.Millisecond)
	if err != nil {
		t.Fatalf("Failed at receiving proper response: %v\n", err)
	}
}

func TestAsyncMarshalErr(t *testing.T) {
	ec := NewEConn(t)
	defer ec.Close()

	ch := make(chan bool)

	testString := "Hello World!"
	subject := "err_marshall"

	ec.Subscribe(subject, func(subj, num int) {
		// This will never get called.
	})

	ec.Conn.Opts.AsyncErrorCB = func(c *Conn, s *Subscription, err error) {
		ch <- true
	}

	ec.Publish(subject, testString)
	if e := wait(ch); e != nil {
		t.Fatalf("Did not receive the message: %s", e)
	}
}

func TestEncodeNil(t *testing.T) {
	de := &DefaultEncoder{}
	_, err := de.Encode("foo", nil)
	if err != nil {
		t.Fatalf("Expected no error encoding nil", err)
	}
}

func TestDecodeDefault(t *testing.T) {
	de := &DefaultEncoder{}
	b, err := de.Encode("foo", 22)
	if err != nil {
		t.Fatalf("Expected no error encoding number", err)
	}
	var c chan bool
	err = de.Decode("foo", b, &c)
	if err == nil {
		t.Fatalf("Expected an error decoding")
	}
}
<|endoftext|>


<commit_before>package goenc

import (
	"bytes"
	"crypto/rand"
	"io/ioutil"
	"os"
	"testing"

	"fmt"

	"github.com/alistanis/goenc/encerrors"
	"github.com/alistanis/goenc/generate"
	"github.com/kisom/testio"
	. "github.com/smartystreets/goconvey/convey"
	"golang.org/x/crypto/nacl/box"
)

var (
	testMessage = []byte("do not go gentle into that good night")
	testSecured []byte

	aliceSession, bobSession *Session
	ciphers                  []*Cipher
)

func init() {
	cbc, err := NewCipher(CBC, testComplexity)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(-1)
	}

	cfb, err := NewCipher(CFB, testComplexity)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(-1)
	}
	ctr, err := NewCipher(CTR, testComplexity)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(-1)
	}

	gcm, err := NewCipher(GCM, testComplexity)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(-1)
	}

	nacl, err := NewCipher(NaCL, testComplexity, []byte("this is a pad to use for our key mwahahaha 123456789"))
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(-1)
	}
	ciphers = []*Cipher{cbc, cfb, ctr, gcm, nacl}
}

func TestFileIO(t *testing.T) {

	Convey("We can successfully perform file writing and reading using the block cipher interface functions", t, func() {
		bc, err := NewCipher(Mock, testComplexity)
		So(err, ShouldBeNil)
		d, err := ioutil.TempDir("/tmp", "")
		So(err, ShouldBeNil)
		defer os.RemoveAll(d)
		tf, err := ioutil.TempFile(d, "")
		So(err, ShouldBeNil)

		data := []byte("test data we'd like to 'encrypt' and save to file")
		key := []byte("test key which is meaningless")

		err = EncryptAndSave(bc, key, data, tf.Name())
		So(err, ShouldBeNil)

		err = tf.Close()
		So(err, ShouldBeNil)

		nd, err := ReadEncryptedFile(bc, key, tf.Name())
		So(err, ShouldBeNil)
		So(bytes.Equal(data, nd), ShouldBeTrue)
	})

}

func TestFileIOErrors(t *testing.T) {
	Convey("We can get errors on file io when we should", t, func() {
		c, err := NewCipher(GCM, testComplexity)
		So(err, ShouldBeNil)

		err = EncryptAndSave(c, []byte{}, []byte{}, "")
		So(err, ShouldNotBeNil)

		_, err = ReadEncryptedFile(c, []byte{}, "")
		So(err, ShouldNotBeNil)
	})
}

var (
	alicePub, alicePriv *[32]byte
	bobPub, bobPriv     *[32]byte
)

func TestGenerateKeys(t *testing.T) {
	var err error

	alicePub, alicePriv, err = box.GenerateKey(rand.Reader)
	if err != nil {
		t.Fatalf("%v", err)
	}

	bobPub, bobPriv, err = box.GenerateKey(rand.Reader)
	if err != nil {
		t.Fatalf("%v", err)
	}
}

func TestSessionSetup(t *testing.T) {

	Convey("We can test all ciphers with a session", t, func() {
		for _, c := range ciphers {

			pub, priv, err := GenerateKeyPair()
			So(err, ShouldBeNil)

			conn := testio.NewBufferConn()
			conn.WritePeer(pub[:])

			aliceSession, err = Dial(conn, c)
			So(err, ShouldBeNil)

			var peer [64]byte
			_, err = conn.ReadClient(peer[:])
			So(err, ShouldBeNil)

			bobSession = &Session{
				recvKey: new([32]byte),
				sendKey: new([32]byte),
				Channel: testio.NewBufCloser(nil),
				Cipher:  c,
			}

			bobSession.KeyExchange(priv, &peer, false)
			aliceSession.Channel = bobSession.Channel
			err = aliceSession.Send(testMessage)
			So(err, ShouldBeNil)

			out, err := bobSession.Receive()
			So(err, ShouldBeNil)

			if !bytes.Equal(out, testMessage) {
				t.Fatal("recovered message doesn't match original")
			}

			if err = aliceSession.Send(nil); err == nil {
				t.Fatal("empty message should trigger an error")
			}

			aliceSession.Close()
			bobSession.Close()
		}
	})

}

var oldMessage []byte

func TestSessionListen(t *testing.T) {

	Convey("We can test session listening with all ciphers", t, func() {

		for _, c := range ciphers {
			pub, priv, err := GenerateKeyPair()
			So(err, ShouldBeNil)

			conn := testio.NewBufferConn()
			conn.WritePeer(pub[:])

			aliceSession, err = Listen(conn, c)
			So(err, ShouldBeNil)

			var peer [64]byte
			_, err = conn.ReadClient(peer[:])
			So(err, ShouldBeNil)

			bobSession = &Session{
				recvKey: new([32]byte),
				sendKey: new([32]byte),
				Channel: testio.NewBufCloser(nil),
				Cipher:  c,
			}

			bobSession.KeyExchange(priv, &peer, true)

			aliceSession.Channel = bobSession.Channel
			err = aliceSession.Send(testMessage)
			So(err, ShouldBeNil)

			out, err := bobSession.Receive()
			So(err, ShouldBeNil)

			So(bobSession.LastRecv(), ShouldBeGreaterThan, 0)
			So(aliceSession.LastSent(), ShouldBeGreaterThan, 0)
			// The NBA is always listening, on and off the court.
			oldMessage = out

			if !bytes.Equal(out, testMessage) {
				t.Fatal("recovered message doesn't match original")
			}

			for i := 0; i < 4; i++ {
				randMessage, err := generate.RandBytes(128)
				So(err, ShouldBeNil)

				err = aliceSession.Send(randMessage)
				So(err, ShouldBeNil)

				out, err = bobSession.Receive()
				So(err, ShouldBeNil)

				if !bytes.Equal(out, randMessage) {
					t.Fatal("recovered message doesn't match original")
				}
			}

			// NBA injects an old message into the channel. Damn those hoops!
			bobSession.Channel.Write(oldMessage)
			_, err = bobSession.Receive()
			So(err, ShouldNotBeNil)
		}
	})

}

func TestErrors(t *testing.T) {
	Convey("We can get appropriate errors", t, func() {
		_, err := NewCipher(NaCL, testComplexity)
		So(err, ShouldEqual, encerrors.ErrNoPadProvided)

		_, err = NewCipher(50, testComplexity)
		So(err, ShouldEqual, encerrors.ErrInvalidCipherKind)

		_, err = UnmarshalMessage([]byte{})
		So(err, ShouldEqual, encerrors.ErrInvalidMessageLength)

		c, err := NewCipher(GCM, testComplexity)
		So(err, ShouldBeNil)
		s := NewSession(testio.NewBufCloser(nil), c)

		_, err = s.Decrypt([]byte{})
		So(err, ShouldNotBeNil)

		msg := []byte("this is a message")
		k, err := generate.Key()
		So(err, ShouldBeNil)
		s.sendKey = k
		s.recvKey = k
		data, err := s.Encrypt(msg)
		So(err, ShouldBeNil)
		s.lastRecv = 40
		_, err = s.Decrypt(data)
		So(err, ShouldNotBeNil)

		_, err = DeriveKey([]byte{}, []byte{}, 0, 1)
		So(err, ShouldNotBeNil)
	})
}
<commit_msg>adds missing test case<commit_after>package goenc

import (
	"bytes"
	"crypto/rand"
	"io/ioutil"
	"os"
	"testing"

	"fmt"

	"github.com/alistanis/goenc/encerrors"
	"github.com/alistanis/goenc/generate"
	"github.com/kisom/testio"
	. "github.com/smartystreets/goconvey/convey"
	"golang.org/x/crypto/nacl/box"
)

var (
	testMessage = []byte("do not go gentle into that good night")
	testSecured []byte

	aliceSession, bobSession *Session
	ciphers                  []*Cipher
)

func init() {
	cbc, err := NewCipher(CBC, testComplexity)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(-1)
	}

	cfb, err := NewCipher(CFB, testComplexity)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(-1)
	}
	ctr, err := NewCipher(CTR, testComplexity)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(-1)
	}

	gcm, err := NewCipher(GCM, testComplexity)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(-1)
	}

	nacl, err := NewCipher(NaCL, testComplexity, []byte("this is a pad to use for our key mwahahaha 123456789"))
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(-1)
	}
	ciphers = []*Cipher{cbc, cfb, ctr, gcm, nacl}
}

func TestFileIO(t *testing.T) {

	Convey("We can successfully perform file writing and reading using the block cipher interface functions", t, func() {
		bc, err := NewCipher(Mock, testComplexity)
		So(err, ShouldBeNil)
		d, err := ioutil.TempDir("/tmp", "")
		So(err, ShouldBeNil)
		defer os.RemoveAll(d)
		tf, err := ioutil.TempFile(d, "")
		So(err, ShouldBeNil)

		data := []byte("test data we'd like to 'encrypt' and save to file")
		key := []byte("test key which is meaningless")

		err = EncryptAndSave(bc, key, data, tf.Name())
		So(err, ShouldBeNil)

		err = tf.Close()
		So(err, ShouldBeNil)

		nd, err := ReadEncryptedFile(bc, key, tf.Name())
		So(err, ShouldBeNil)
		So(bytes.Equal(data, nd), ShouldBeTrue)
	})

}

func TestFileIOErrors(t *testing.T) {
	Convey("We can get errors on file io when we should", t, func() {
		c, err := NewCipher(GCM, testComplexity)
		So(err, ShouldBeNil)

		err = EncryptAndSave(c, []byte{}, []byte{}, "")
		So(err, ShouldNotBeNil)

		_, err = ReadEncryptedFile(c, []byte{}, "")
		So(err, ShouldNotBeNil)

		err = EncryptAndSaveWithPerms(c, []byte{}, []byte{}, "", 0644)
		So(err, ShouldNotBeNil)
	})
}

var (
	alicePub, alicePriv *[32]byte
	bobPub, bobPriv     *[32]byte
)

func TestGenerateKeys(t *testing.T) {
	var err error

	alicePub, alicePriv, err = box.GenerateKey(rand.Reader)
	if err != nil {
		t.Fatalf("%v", err)
	}

	bobPub, bobPriv, err = box.GenerateKey(rand.Reader)
	if err != nil {
		t.Fatalf("%v", err)
	}
}

func TestSessionSetup(t *testing.T) {

	Convey("We can test all ciphers with a session", t, func() {
		for _, c := range ciphers {

			pub, priv, err := GenerateKeyPair()
			So(err, ShouldBeNil)

			conn := testio.NewBufferConn()
			conn.WritePeer(pub[:])

			aliceSession, err = Dial(conn, c)
			So(err, ShouldBeNil)

			var peer [64]byte
			_, err = conn.ReadClient(peer[:])
			So(err, ShouldBeNil)

			bobSession = &Session{
				recvKey: new([32]byte),
				sendKey: new([32]byte),
				Channel: testio.NewBufCloser(nil),
				Cipher:  c,
			}

			bobSession.KeyExchange(priv, &peer, false)
			aliceSession.Channel = bobSession.Channel
			err = aliceSession.Send(testMessage)
			So(err, ShouldBeNil)

			out, err := bobSession.Receive()
			So(err, ShouldBeNil)

			if !bytes.Equal(out, testMessage) {
				t.Fatal("recovered message doesn't match original")
			}

			if err = aliceSession.Send(nil); err == nil {
				t.Fatal("empty message should trigger an error")
			}

			aliceSession.Close()
			bobSession.Close()
		}
	})

}

var oldMessage []byte

func TestSessionListen(t *testing.T) {

	Convey("We can test session listening with all ciphers", t, func() {

		for _, c := range ciphers {
			pub, priv, err := GenerateKeyPair()
			So(err, ShouldBeNil)

			conn := testio.NewBufferConn()
			conn.WritePeer(pub[:])

			aliceSession, err = Listen(conn, c)
			So(err, ShouldBeNil)

			var peer [64]byte
			_, err = conn.ReadClient(peer[:])
			So(err, ShouldBeNil)

			bobSession = &Session{
				recvKey: new([32]byte),
				sendKey: new([32]byte),
				Channel: testio.NewBufCloser(nil),
				Cipher:  c,
			}

			bobSession.KeyExchange(priv, &peer, true)

			aliceSession.Channel = bobSession.Channel
			err = aliceSession.Send(testMessage)
			So(err, ShouldBeNil)

			out, err := bobSession.Receive()
			So(err, ShouldBeNil)

			So(bobSession.LastRecv(), ShouldBeGreaterThan, 0)
			So(aliceSession.LastSent(), ShouldBeGreaterThan, 0)
			// The NBA is always listening, on and off the court.
			oldMessage = out

			if !bytes.Equal(out, testMessage) {
				t.Fatal("recovered message doesn't match original")
			}

			for i := 0; i < 4; i++ {
				randMessage, err := generate.RandBytes(128)
				So(err, ShouldBeNil)

				err = aliceSession.Send(randMessage)
				So(err, ShouldBeNil)

				out, err = bobSession.Receive()
				So(err, ShouldBeNil)

				if !bytes.Equal(out, randMessage) {
					t.Fatal("recovered message doesn't match original")
				}
			}

			// NBA injects an old message into the channel. Damn those hoops!
			bobSession.Channel.Write(oldMessage)
			_, err = bobSession.Receive()
			So(err, ShouldNotBeNil)
		}
	})

}

func TestErrors(t *testing.T) {
	Convey("We can get appropriate errors", t, func() {
		_, err := NewCipher(NaCL, testComplexity)
		So(err, ShouldEqual, encerrors.ErrNoPadProvided)

		_, err = NewCipher(50, testComplexity)
		So(err, ShouldEqual, encerrors.ErrInvalidCipherKind)

		_, err = UnmarshalMessage([]byte{})
		So(err, ShouldEqual, encerrors.ErrInvalidMessageLength)

		c, err := NewCipher(GCM, testComplexity)
		So(err, ShouldBeNil)
		s := NewSession(testio.NewBufCloser(nil), c)

		_, err = s.Decrypt([]byte{})
		So(err, ShouldNotBeNil)

		msg := []byte("this is a message")
		k, err := generate.Key()
		So(err, ShouldBeNil)
		s.sendKey = k
		s.recvKey = k
		data, err := s.Encrypt(msg)
		So(err, ShouldBeNil)
		s.lastRecv = 40
		_, err = s.Decrypt(data)
		So(err, ShouldNotBeNil)

		_, err = DeriveKey([]byte{}, []byte{}, 0, 1)
		So(err, ShouldNotBeNil)
	})
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"github.com/blackbass1988/access_logs_stats/core"
	"log"
	"os"

	"io"
	"runtime"
	"runtime/pprof"
	"time"
)

const progName = "AccessLogsStats"

var (
	//version it is a version of application will be overridden on build
	version = "0.7.1"
	//buildTime it is a build time of application will be overridden on build
	buildTime = "unknown"
)

func printHello() {
	log.Printf("%s ver.%s@%s", progName, version, buildTime)
}

func main() {
	var (
		fileconfig       string
		profile          bool
		exitAfterOneTick bool
	)

	printHello()

	flag.StringVar(&fileconfig, "c", "", "config path")
	flag.BoolVar(&profile, "p", false, "enable profiling")
	flag.BoolVar(&exitAfterOneTick, "one", false, "make one tick end exit")
	flag.Parse()

	if fileconfig == "" {
		log.Print("ERROR config not set")
		flag.PrintDefaults()
		os.Exit(2)
	}

	config, err := core.NewConfig(fileconfig)
	if err != nil {
		log.Fatal(err)
	}
	config.ExitAfterOneTick = exitAfterOneTick

	app, err := core.NewApp(config)
	if err != nil {
		log.Fatal(err)
	}

	if profile {
		go codeProfile()
	}

	app.Start()
}

func codeProfile() {
	m := &runtime.MemStats{}
	tick1m := time.Tick(1 * time.Minute)
	tick5s := time.Tick(5 * time.Second)

	fCPUProfiling, err := os.Create("profile.prof")
	if err != nil {
		panic(err)
	}
	pprof.StartCPUProfile(fCPUProfiling)
	defer func() {
		pprof.StopCPUProfile()
	}()

	for {
		select {
		case <-tick5s:
			runtime.ReadMemStats(m)
			log.Println("")
			log.Println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
			log.Printf("~ Goroutines count %d\n", runtime.NumGoroutine())
			log.Printf("~ Alloc %dKB\n", m.Alloc/1024)
			log.Printf("~ TotalAlloc %dKB\n", m.TotalAlloc/1024)
			log.Printf("~ Sys (sum of XxxSys below) %dKB\n", m.Sys/1024)
			log.Printf("~ Lookups (number of pointer lookups) %d\n", m.Lookups)
			log.Printf("~ Mallocs %d\n", m.Mallocs)
			log.Printf("~ Frees %d\n", m.Frees)

			log.Println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")

			log.Printf("~ HeapAlloc %dKB\n", m.HeapAlloc/1024)
			log.Printf("~ HeapSys %dKB\n", m.HeapSys/1024)
			log.Printf("~ HeapIdle %dKB\n", m.HeapIdle/1024)
			log.Printf("~ HeapInuse %dKB\n", m.HeapInuse/1024)
			log.Printf("~ HeapReleased %dKB\n", m.HeapReleased/1024)
			log.Printf("~ HeapObjects %d\n", m.HeapObjects)

			log.Println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")

			log.Printf("~ NextGC %d\n", m.NextGC)
			log.Printf("~ LastGC %v\n", time.Unix(0, int64(m.LastGC)))
			log.Printf("~ PauseTotalNs %d\n", m.PauseTotalNs)
			log.Printf("~ NumGC %d\n", m.PauseTotalNs)
			log.Printf("~ GCCPUFraction %f\n", m.GCCPUFraction)
			log.Printf("~ EnableGC %v\n", m.EnableGC)
			log.Printf("~ DebugGC %v\n", m.DebugGC)
			log.Println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
			log.Println("")

		case <-tick1m:
			var fHeapProfiling io.Writer
			fHeapProfiling, _ = os.Create("profile_heap.prof")
			pprof.WriteHeapProfile(fHeapProfiling)
			log.Println("~ head saved")
		}
	}
}
<commit_msg>bump version<commit_after>package main

import (
	"flag"
	"github.com/blackbass1988/access_logs_stats/core"
	"log"
	"os"

	"io"
	"runtime"
	"runtime/pprof"
	"time"
)

var (
	version = "0.8"
	buildTime = "unknown"
)

func printHello() {
	log.Printf("AccessLogsStats ver.%s@%s", version, buildTime)
}

func main() {
	var (
		fileconfig       string
		profile          bool
		exitAfterOneTick bool
	)

	printHello()

	flag.StringVar(&fileconfig, "c", "", "config path")
	flag.BoolVar(&profile, "p", false, "enable profiling")
	flag.BoolVar(&exitAfterOneTick, "one", false, "make one tick end exit")
	flag.Parse()

	if fileconfig == "" {
		log.Print("ERROR config not set")
		flag.PrintDefaults()
		os.Exit(2)
	}

	config, err := core.NewConfig(fileconfig)
	if err != nil {
		log.Fatal(err)
	}
	config.ExitAfterOneTick = exitAfterOneTick

	app, err := core.NewApp(config)
	if err != nil {
		log.Fatal(err)
	}

	if profile {
		go codeProfile()
	}

	app.Start()
}

func codeProfile() {
	m := &runtime.MemStats{}
	tick1m := time.Tick(1 * time.Minute)
	tick5s := time.Tick(5 * time.Second)

	fCPUProfiling, err := os.Create("profile.prof")
	if err != nil {
		panic(err)
	}
	pprof.StartCPUProfile(fCPUProfiling)
	defer func() {
		pprof.StopCPUProfile()
	}()

	for {
		select {
		case <-tick5s:
			runtime.ReadMemStats(m)
			log.Println("")
			log.Println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
			log.Printf("~ Goroutines count %d\n", runtime.NumGoroutine())
			log.Printf("~ Alloc %dKB\n", m.Alloc/1024)
			log.Printf("~ TotalAlloc %dKB\n", m.TotalAlloc/1024)
			log.Printf("~ Sys (sum of XxxSys below) %dKB\n", m.Sys/1024)
			log.Printf("~ Lookups (number of pointer lookups) %d\n", m.Lookups)
			log.Printf("~ Mallocs %d\n", m.Mallocs)
			log.Printf("~ Frees %d\n", m.Frees)

			log.Println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")

			log.Printf("~ HeapAlloc %dKB\n", m.HeapAlloc/1024)
			log.Printf("~ HeapSys %dKB\n", m.HeapSys/1024)
			log.Printf("~ HeapIdle %dKB\n", m.HeapIdle/1024)
			log.Printf("~ HeapInuse %dKB\n", m.HeapInuse/1024)
			log.Printf("~ HeapReleased %dKB\n", m.HeapReleased/1024)
			log.Printf("~ HeapObjects %d\n", m.HeapObjects)

			log.Println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")

			log.Printf("~ NextGC %d\n", m.NextGC)
			log.Printf("~ LastGC %v\n", time.Unix(0, int64(m.LastGC)))
			log.Printf("~ PauseTotalNs %d\n", m.PauseTotalNs)
			log.Printf("~ NumGC %d\n", m.PauseTotalNs)
			log.Printf("~ GCCPUFraction %f\n", m.GCCPUFraction)
			log.Printf("~ EnableGC %v\n", m.EnableGC)
			log.Printf("~ DebugGC %v\n", m.DebugGC)
			log.Println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
			log.Println("")

		case <-tick1m:
			var fHeapProfiling io.Writer
			fHeapProfiling, _ = os.Create("profile_heap.prof")
			pprof.WriteHeapProfile(fHeapProfiling)
			log.Println("~ head saved")
		}
	}
}
<|endoftext|>


<commit_before>package commands

import (
	"github.com/BytemarkHosting/bytemark-client/cmd/bytemark/commands/show"
	"github.com/urfave/cli"
)

func init() {
	Commands = append(Commands, cli.Command{
		Name:      "show",
		Usage:     "displays information about your account and of your assets at Bytemark",
		UsageText: "show accounts, discs, groups, etc - see `bytemark help show <kind of thing> `",
		Description: `scripting-friendly lists of your assets at Bytemark

This command will list the kind of object you request, one per line. Perfect for piping into a bash while loop!`,
		Action:      cli.ShowSubcommandHelp,
		Subcommands: show.Commands,
	})
}
<commit_msg>update description<commit_after>package commands

import (
	"github.com/BytemarkHosting/bytemark-client/cmd/bytemark/commands/show"
	"github.com/urfave/cli"
)

func init() {
	Commands = append(Commands, cli.Command{
		Name:      "show",
		Usage:     "displays information about your account and of your assets at Bytemark",
		UsageText: "show accounts, discs, groups, etc - see `bytemark help show <kind of thing> `",
		Description: `displays information about the given server, group, or account.

Plurals are scripting-friendly lists of your assets at Bytemark, showing the kind of object you request, one per line.

Perfect for piping into a bash while loop!`,
		Action:      cli.ShowSubcommandHelp,
		Subcommands: show.Commands,
	})
}
<|endoftext|>


<commit_before>package command

import (
	"database/sql"
	"errors"
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"strings"
	"time"

	_ "net/http/pprof"

	_ "github.com/lib/pq"

	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/sqs"
	"github.com/kelseyhightower/envconfig"
	"github.com/nabeken/aws-go-sqs/queue"
	"github.com/nabeken/delayd2"
)

type ServerConfig struct {
	WorkerID  string `envconfig:"worker_id"`
	DSN       string `envconfig:"dsn"`
	QueueName string `envconfig:"queue_name"`

	ShutdownDuration  int `envconfig:"shutdown_duration"`
	NumConsumerFactor int `envconfig:"num_consumer_factor"`
	NumRelayFactor    int `envconfig:"num_relay_factor"`

	EnablePProf bool

	LeaveMessagesOrphanedAtShutdown bool
}

type ServerCommand struct {
	Meta

	ShutdownCh <-chan struct{}
}

func (c *ServerCommand) Run(args []string) int {
	var config ServerConfig

	if err := envconfig.Process("delayd2", &config); err != nil {
		c.Ui.Error(fmt.Sprintf("Unable to get configuration from envvars: %s", err))
		return 1
	}

	cmdFlags := flag.NewFlagSet("server", flag.ContinueOnError)
	cmdFlags.BoolVar(&config.EnablePProf, "pprof", false, "enable pprof server on 127.0.0.1:6060")
	cmdFlags.BoolVar(&config.LeaveMessagesOrphanedAtShutdown, "leave-messages-orphaned-at-shutdown", true, "leave messages orphaned at shutdown")

	if err := cmdFlags.Parse(args); err != nil {
		c.Ui.Error(c.Help())
		return 1
	}

	if config.EnablePProf {
		log.Println("server: launching pprof http server on 127.0.0.1:6060")
		go func() {
			log.Println(http.ListenAndServe("127.0.0.1:6060", nil))
		}()
	}

	// initialize configuration
	if config.NumConsumerFactor == 0 {
		config.NumConsumerFactor = 1
	}

	if config.NumRelayFactor == 0 {
		config.NumRelayFactor = 1
	}

	if config.ShutdownDuration == 0 {
		config.ShutdownDuration = 60
	}

	if config.WorkerID == "" {
		hostname, err := os.Hostname()
		if err != nil {
			c.Ui.Error(fmt.Sprintf("Unable to get hostname: %s", err))
			return 1
		}
		log.Printf("No worker-id specified so use hostname (%s) instead", hostname)
		config.WorkerID = hostname
	}

	db, err := sql.Open("postgres-delayd2", config.DSN)
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Unable to open database connection: %s", err))
		return 1
	}
	if err := db.Ping(); err != nil {
		c.Ui.Error(fmt.Sprintf("Unable to open database connection: %s", err))
		return 1
	}
	defer db.Close()

	drv := delayd2.NewDriver(config.WorkerID, db)
	sqsSvc := sqs.New(session.New())

	q, err := queue.New(sqsSvc, config.QueueName)
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Unable to initialize SQS connection: %s", err))
		return 1
	}

	consumer := delayd2.NewConsumer(config.WorkerID, drv, q)
	relay := delayd2.NewRelay(sqsSvc)

	workerConfig := &delayd2.WorkerConfig{
		ID: config.WorkerID,

		NumConsumerFactor: config.NumConsumerFactor,
		NumRelayFactor:    config.NumRelayFactor,

		LeaveMessagesOrphanedAtShutdown: config.LeaveMessagesOrphanedAtShutdown,
	}

	w := delayd2.NewWorker(workerConfig, drv, consumer, relay)

	errCh := make(chan error)
	go func() {
		errCh <- w.Run()
	}()

	go func() {
		select {
		case <-c.ShutdownCh:
			// we should wait until s.Stop returns for 10 seconds.
			time.AfterFunc(time.Duration(config.ShutdownDuration)*time.Second, func() {
				errCh <- errors.New("delayd2: Worker#Stop() does not return for 1 minute. existing...")
			})
			w.Stop()
		}
	}()

	select {
	case err := <-errCh:
		if err != nil {
			c.Ui.Error(err.Error())
			return 1
		}
	}
	return 0
}

func (c *ServerCommand) Synopsis() string {
	return ""
}

func (c *ServerCommand) Help() string {
	helpText := `

`
	return strings.TrimSpace(helpText)
}
<commit_msg>Launch HTTP server for pprof and stats by default on loopback<commit_after>package command

import (
	"database/sql"
	"errors"
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"strings"
	"time"

	_ "net/http/pprof"

	_ "github.com/lib/pq"

	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/sqs"
	"github.com/fukata/golang-stats-api-handler"
	"github.com/kelseyhightower/envconfig"
	"github.com/nabeken/aws-go-sqs/queue"
	"github.com/nabeken/delayd2"
)

type ServerConfig struct {
	WorkerID  string `envconfig:"worker_id"`
	DSN       string `envconfig:"dsn"`
	QueueName string `envconfig:"queue_name"`

	ShutdownDuration  int `envconfig:"shutdown_duration"`
	NumConsumerFactor int `envconfig:"num_consumer_factor"`
	NumRelayFactor    int `envconfig:"num_relay_factor"`

	HTTPServer string

	LeaveMessagesOrphanedAtShutdown bool
}

type ServerCommand struct {
	Meta

	ShutdownCh <-chan struct{}
}

func (c *ServerCommand) Run(args []string) int {
	var config ServerConfig

	if err := envconfig.Process("delayd2", &config); err != nil {
		c.Ui.Error(fmt.Sprintf("Unable to get configuration from envvars: %s", err))
		return 1
	}

	cmdFlags := flag.NewFlagSet("server", flag.ContinueOnError)
	cmdFlags.StringVar(&config.HTTPServer, "http-server", "127.0.0.1:6060", "Listen HTTP request for pprof and stats on 127.0.0.1:6060")
	cmdFlags.BoolVar(&config.LeaveMessagesOrphanedAtShutdown, "leave-messages-orphaned-at-shutdown", true, "leave messages orphaned at shutdown")

	if err := cmdFlags.Parse(args); err != nil {
		c.Ui.Error(c.Help())
		return 1
	}

	if config.HTTPServer != "" {
		http.HandleFunc("/_stats", stats_api.Handler)
		log.Println("server: launching http server on ", config.HTTPServer)
		go func() {
			log.Println(http.ListenAndServe(config.HTTPServer, nil))
		}()
	}

	// initialize configuration
	if config.NumConsumerFactor == 0 {
		config.NumConsumerFactor = 1
	}

	if config.NumRelayFactor == 0 {
		config.NumRelayFactor = 1
	}

	if config.ShutdownDuration == 0 {
		config.ShutdownDuration = 60
	}

	if config.WorkerID == "" {
		hostname, err := os.Hostname()
		if err != nil {
			c.Ui.Error(fmt.Sprintf("Unable to get hostname: %s", err))
			return 1
		}
		log.Printf("No worker-id specified so use hostname (%s) instead", hostname)
		config.WorkerID = hostname
	}

	db, err := sql.Open("postgres-delayd2", config.DSN)
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Unable to open database connection: %s", err))
		return 1
	}
	if err := db.Ping(); err != nil {
		c.Ui.Error(fmt.Sprintf("Unable to open database connection: %s", err))
		return 1
	}
	defer db.Close()

	drv := delayd2.NewDriver(config.WorkerID, db)
	sqsSvc := sqs.New(session.New())

	q, err := queue.New(sqsSvc, config.QueueName)
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Unable to initialize SQS connection: %s", err))
		return 1
	}

	consumer := delayd2.NewConsumer(config.WorkerID, drv, q)
	relay := delayd2.NewRelay(sqsSvc)

	workerConfig := &delayd2.WorkerConfig{
		ID: config.WorkerID,

		NumConsumerFactor: config.NumConsumerFactor,
		NumRelayFactor:    config.NumRelayFactor,

		LeaveMessagesOrphanedAtShutdown: config.LeaveMessagesOrphanedAtShutdown,
	}

	w := delayd2.NewWorker(workerConfig, drv, consumer, relay)

	errCh := make(chan error)
	go func() {
		errCh <- w.Run()
	}()

	go func() {
		select {
		case <-c.ShutdownCh:
			// we should wait until s.Stop returns for 10 seconds.
			time.AfterFunc(time.Duration(config.ShutdownDuration)*time.Second, func() {
				errCh <- errors.New("delayd2: Worker#Stop() does not return for 1 minute. existing...")
			})
			w.Stop()
		}
	}()

	select {
	case err := <-errCh:
		if err != nil {
			c.Ui.Error(err.Error())
			return 1
		}
	}
	return 0
}

func (c *ServerCommand) Synopsis() string {
	return ""
}

func (c *ServerCommand) Help() string {
	helpText := `

`
	return strings.TrimSpace(helpText)
}
<|endoftext|>


<commit_before>package main

import (
	"errors"
	"fmt"
	"io/ioutil"
	"os"
	"regexp"
	"strconv"
	"strings"
	"unicode"

	"github.com/sbinet/go-clang"
	// "github.com/termie/go-shutil"
)

func main() {
	rawLLVMVersion, _, err := execToBuffer("llvm-config", "--version")
	if err != nil {
		exitWithFatal("Cannot determine LLVM version", err)
	}

	matchLLVMVersion := regexp.MustCompile(`^(\d+)\.(\d+)\.(\d+)`).FindSubmatch(rawLLVMVersion)
	if matchLLVMVersion == nil {
		exitWithFatal("Cannot parse LLVM version", nil)
	}

	var llvmVersion struct {
		Major int
		Minor int
		Patch int // TODO rename to Subminor
	}

	llvmVersion.Major, _ = strconv.Atoi(string(matchLLVMVersion[1]))
	llvmVersion.Minor, _ = strconv.Atoi(string(matchLLVMVersion[2]))
	llvmVersion.Patch, _ = strconv.Atoi(string(matchLLVMVersion[3]))

	fmt.Println("Found LLVM version", string(matchLLVMVersion[0]))

	rawLLVMIncludeDir, _, err := execToBuffer("llvm-config", "--includedir")
	if err != nil {
		exitWithFatal("Cannot determine LLVM include directory", err)
	}

	clangCIncludeDir := strings.TrimSpace(string(rawLLVMIncludeDir)) + "/clang-c/"
	if err := dirExists(clangCIncludeDir); err != nil {
		exitWithFatal(fmt.Sprintf("Cannot find Clang-C include directory %q", clangCIncludeDir), err)
	}

	fmt.Println("Clang-C include directory", clangCIncludeDir)

	fmt.Printf("Will generate go-clang for LLVM version %d.%d in current directory\n", llvmVersion.Major, llvmVersion.Minor)

	/*// Copy the Clang-C include directory into the current directory
	_ = os.RemoveAll("./clang-c/")
	if err := shutil.CopyTree(clangCIncludeDir, "./clang-c/", nil); err != nil {
		exitWithFatal(fmt.Sprintf("Cannot copy Clang-C include directory %q into current directory", clangCIncludeDir), err)
	}*/

	// Remove all generated .go files
	if files, err := ioutil.ReadDir("./"); err != nil {
		exitWithFatal("Cannot read current directory", err)
	} else {
		for _, f := range files {
			fn := f.Name()

			if !f.IsDir() && strings.HasSuffix(fn, "_gen.go") {
				if err := os.Remove(fn); err != nil {
					exitWithFatal(fmt.Sprintf("Cannot remove generated file %q", fn), err)
				}
			}
		}
	}

	// Parse clang-c's Index.h to analyse everything we need to know
	idx := clang.NewIndex(0, 1)
	defer idx.Dispose()

	clangIndexHeaderFilepath := "./clang-c/Index.h"
	tu := idx.Parse(clangIndexHeaderFilepath, []string{
		"-I", ".", // Include current folder
		"-I", "/usr/local/lib/clang/3.4.2/include/", // Include clang headers TODO make this generic
	}, nil, 0)
	defer tu.Dispose()

	if !tu.IsValid() {
		exitWithFatal("Cannot parse Index.h", nil)
	}

	for _, diag := range tu.Diagnostics() {
		switch diag.Severity() {
		case clang.Diagnostic_Error:
			exitWithFatal("Diagnostic error in Index.h", errors.New(diag.Spelling()))
		case clang.Diagnostic_Fatal:
			exitWithFatal("Diagnostic fatal in Index.h", errors.New(diag.Spelling()))
		}
	}

	var enums []*Enum
	var functions []*Function
	var structs []*Struct

	lookupEnum := map[string]*Enum{}
	lookupNonTypedefs := map[string]string{}
	lookupStruct := map[string]*Struct{}

	isEnumOrStruct := func(name string) bool {
		if _, ok := lookupEnum[name]; ok {
			return true
		} else if _, ok := lookupStruct[name]; ok {
			return true
		}

		return false
	}

	cursor := tu.ToCursor()
	cursor.Visit(func(cursor, parent clang.Cursor) clang.ChildVisitResult {
		// Only handle code of the current file
		sourceFile, _, _, _ := cursor.Location().GetFileLocation()
		if sourceFile.Name() != clangIndexHeaderFilepath {
			return clang.CVR_Continue
		}

		cname := cursor.Spelling()
		cnameIsTypeDef := false

		if parentCName := parent.Spelling(); parent.Kind() == clang.CK_TypedefDecl && parentCName != "" {
			cname = parentCName
			cnameIsTypeDef = true
		}

		switch cursor.Kind() {
		case clang.CK_EnumDecl:
			if cname == "" {
				break
			}

			e := handleEnumCursor(cursor, cname, cnameIsTypeDef)

			lookupEnum[e.Name] = e
			lookupNonTypedefs["enum "+e.CName] = e.Name
			lookupEnum[e.CName] = e

			enums = append(enums, e)
		case clang.CK_FunctionDecl:
			f := handleFunctionCursor(cursor)
			if f != nil {
				functions = append(functions, f)
			}
		case clang.CK_StructDecl:
			if cname == "" {
				break
			}

			s := handleStructCursor(cursor, cname, cnameIsTypeDef)

			lookupStruct[s.Name] = s
			lookupNonTypedefs["struct "+s.CName] = s.Name
			lookupStruct[s.CName] = s

			structs = append(structs, s)
		case clang.CK_TypedefDecl:
			underlyingType := cursor.TypedefDeclUnderlyingType().TypeSpelling()
			underlyingStructType := strings.TrimSuffix(strings.TrimPrefix(underlyingType, "struct "), " *")

			if s, ok := lookupStruct[underlyingStructType]; ok && !s.CNameIsTypeDef && strings.HasPrefix(underlyingType, "struct "+s.CName) {
				// Sometimes the typedef is not a parent of the struct but a sibling TODO find out if this is a bug?

				sn := handleVoidStructCursor(cursor, cname, true)

				lookupStruct[sn.Name] = sn
				lookupNonTypedefs["struct "+sn.CName] = sn.Name
				lookupStruct[sn.CName] = sn

				// Update the lookups for the old struct
				lookupStruct[s.Name] = sn
				lookupStruct[s.CName] = sn

				for i, si := range structs {
					if si == s {
						structs[i] = sn

						break
					}
				}
			} else if underlyingType == "void *" {
				s := handleVoidStructCursor(cursor, cname, true)

				lookupStruct[s.Name] = s
				lookupNonTypedefs["struct "+s.CName] = s.Name
				lookupStruct[s.CName] = s

				structs = append(structs, s)
			}
		}

		return clang.CVR_Recurse
	})

	trimCommonFName := func(fname string, rt Receiver) string {
		fname = strings.TrimPrefix(fname, "get")

		if fn := strings.TrimPrefix(fname, rt.Name+"_"); len(fn) != len(fname) {
			fname = fn
		} else if fn := strings.TrimPrefix(fname, rt.Name); len(fn) != len(fname) {
			fname = fn
		} else if fn := strings.TrimSuffix(fname, rt.CName); len(fn) != len(fname) {
			fname = fn
		}

		fname = strings.TrimPrefix(fname, "get")

		return fname
	}

	addMethod := func(f *Function, fname string, rt Receiver, method func(f *Function) string) bool {
		fname = upperFirstCharacter(fname)

		if e, ok := lookupEnum[rt.Name]; ok {
			f.Name = fname
			f.Receiver = e.Receiver
			f.Receiver.Type = rt.Name

			e.Methods = append(e.Methods, method(f))

			return true
		} else if s, ok := lookupStruct[rt.Name]; ok {
			f.Name = fname
			f.Receiver = s.Receiver
			f.Receiver.Type = rt.Name

			s.Methods = append(s.Methods, method(f))

			return true
		}

		return false
	}

	addBasicMethods := func(f *Function, fname string, rt Receiver) bool {
		if len(f.Parameters) == 1 && f.ReturnType == "String" {
			fname = trimCommonFName(fname, rt)

			return addMethod(f, fname, rt, generateFunctionStringGetter)
		} else if len(f.Parameters) == 1 && isEnumOrStruct(f.ReturnType) && isEnumOrStruct(f.Parameters[0].Type) {
			fname = trimCommonFName(fname, rt)

			return addMethod(f, fname, rt, generateFunctionGetter)
		} else if len(f.Parameters) == 1 &&
			((fname[0] == 'i' && fname[1] == 's' && unicode.IsUpper(rune(fname[2]))) || (fname[0] == 'h' && fname[1] == 'a' && fname[2] == 's' && unicode.IsUpper(rune(fname[3])))) &&
			(f.ReturnType == "unsigned int" || f.ReturnType == "int") {
			return addMethod(f, fname, rt, generateFunctionIs)
		} else if len(f.Parameters) == 1 && strings.HasPrefix(fname, "dispose") && f.ReturnType == "void" {
			fname = "Dispose"

			return addMethod(f, fname, rt, generateFunctionVoidMethod)
		} else if len(f.Parameters) == 2 && strings.HasPrefix(fname, "equal") && f.ReturnType == "unsigned int" && f.Parameters[0].Type == f.Parameters[1].Type {
			return addMethod(f, fname, rt, generateFunctionEqual)
		}

		return false
	}

	for _, f := range functions {
		fname := f.Name
		var rt Receiver
		if len(f.Parameters) > 0 {
			rt.CName = f.Parameters[0].Type
			rt.Name = trimClangPrefix(rt.CName)
			if n, ok := lookupNonTypedefs[rt.Name]; ok {
				rt.Name = n
			}
		}

		if n, ok := lookupNonTypedefs[f.ReturnType]; ok {
			f.ReturnType = n
		}
		if e, ok := lookupEnum[f.ReturnType]; ok {
			f.ReturnPrimitiveType = e.Receiver.PrimitiveType
		} else if _, ok := lookupStruct[f.ReturnType]; ok {
		}

		added := addBasicMethods(f, fname, rt)

		if !added {
			if s := strings.SplitN(f.Name, "_", 2); len(s) == 2 {
				if s[0] == rt.Name {
					rtc := rt
					rtc.Name = s[0]

					added = addBasicMethods(f, s[1], rtc)
				}
			}
		}

		if !added {
			fmt.Println("Unused:", f.Name)
		}
	}

	for _, e := range enums {
		if err := generateEnum(e); err != nil {
			exitWithFatal("Cannot generate enum", err)
		}
	}

	for _, s := range structs {
		if err := generateStruct(s); err != nil {
			exitWithFatal("Cannot generate struct", err)
		}
	}

	if _, _, err = execToBuffer("gofmt", "-w", "./"); err != nil { // TODO do this before saving the files using go/fmt
		exitWithFatal("Gofmt failed", err)
	}
}
<commit_msg>Allow a prefix during function adding<commit_after>package main

import (
	"errors"
	"fmt"
	"io/ioutil"
	"os"
	"regexp"
	"strconv"
	"strings"
	"unicode"

	"github.com/sbinet/go-clang"
	// "github.com/termie/go-shutil"
)

func main() {
	rawLLVMVersion, _, err := execToBuffer("llvm-config", "--version")
	if err != nil {
		exitWithFatal("Cannot determine LLVM version", err)
	}

	matchLLVMVersion := regexp.MustCompile(`^(\d+)\.(\d+)\.(\d+)`).FindSubmatch(rawLLVMVersion)
	if matchLLVMVersion == nil {
		exitWithFatal("Cannot parse LLVM version", nil)
	}

	var llvmVersion struct {
		Major int
		Minor int
		Patch int // TODO rename to Subminor
	}

	llvmVersion.Major, _ = strconv.Atoi(string(matchLLVMVersion[1]))
	llvmVersion.Minor, _ = strconv.Atoi(string(matchLLVMVersion[2]))
	llvmVersion.Patch, _ = strconv.Atoi(string(matchLLVMVersion[3]))

	fmt.Println("Found LLVM version", string(matchLLVMVersion[0]))

	rawLLVMIncludeDir, _, err := execToBuffer("llvm-config", "--includedir")
	if err != nil {
		exitWithFatal("Cannot determine LLVM include directory", err)
	}

	clangCIncludeDir := strings.TrimSpace(string(rawLLVMIncludeDir)) + "/clang-c/"
	if err := dirExists(clangCIncludeDir); err != nil {
		exitWithFatal(fmt.Sprintf("Cannot find Clang-C include directory %q", clangCIncludeDir), err)
	}

	fmt.Println("Clang-C include directory", clangCIncludeDir)

	fmt.Printf("Will generate go-clang for LLVM version %d.%d in current directory\n", llvmVersion.Major, llvmVersion.Minor)

	/*// Copy the Clang-C include directory into the current directory
	_ = os.RemoveAll("./clang-c/")
	if err := shutil.CopyTree(clangCIncludeDir, "./clang-c/", nil); err != nil {
		exitWithFatal(fmt.Sprintf("Cannot copy Clang-C include directory %q into current directory", clangCIncludeDir), err)
	}*/

	// Remove all generated .go files
	if files, err := ioutil.ReadDir("./"); err != nil {
		exitWithFatal("Cannot read current directory", err)
	} else {
		for _, f := range files {
			fn := f.Name()

			if !f.IsDir() && strings.HasSuffix(fn, "_gen.go") {
				if err := os.Remove(fn); err != nil {
					exitWithFatal(fmt.Sprintf("Cannot remove generated file %q", fn), err)
				}
			}
		}
	}

	// Parse clang-c's Index.h to analyse everything we need to know
	idx := clang.NewIndex(0, 1)
	defer idx.Dispose()

	clangIndexHeaderFilepath := "./clang-c/Index.h"
	tu := idx.Parse(clangIndexHeaderFilepath, []string{
		"-I", ".", // Include current folder
		"-I", "/usr/local/lib/clang/3.4.2/include/", // Include clang headers TODO make this generic
	}, nil, 0)
	defer tu.Dispose()

	if !tu.IsValid() {
		exitWithFatal("Cannot parse Index.h", nil)
	}

	for _, diag := range tu.Diagnostics() {
		switch diag.Severity() {
		case clang.Diagnostic_Error:
			exitWithFatal("Diagnostic error in Index.h", errors.New(diag.Spelling()))
		case clang.Diagnostic_Fatal:
			exitWithFatal("Diagnostic fatal in Index.h", errors.New(diag.Spelling()))
		}
	}

	var enums []*Enum
	var functions []*Function
	var structs []*Struct

	lookupEnum := map[string]*Enum{}
	lookupNonTypedefs := map[string]string{}
	lookupStruct := map[string]*Struct{}

	isEnumOrStruct := func(name string) bool {
		if _, ok := lookupEnum[name]; ok {
			return true
		} else if _, ok := lookupStruct[name]; ok {
			return true
		}

		return false
	}

	cursor := tu.ToCursor()
	cursor.Visit(func(cursor, parent clang.Cursor) clang.ChildVisitResult {
		// Only handle code of the current file
		sourceFile, _, _, _ := cursor.Location().GetFileLocation()
		if sourceFile.Name() != clangIndexHeaderFilepath {
			return clang.CVR_Continue
		}

		cname := cursor.Spelling()
		cnameIsTypeDef := false

		if parentCName := parent.Spelling(); parent.Kind() == clang.CK_TypedefDecl && parentCName != "" {
			cname = parentCName
			cnameIsTypeDef = true
		}

		switch cursor.Kind() {
		case clang.CK_EnumDecl:
			if cname == "" {
				break
			}

			e := handleEnumCursor(cursor, cname, cnameIsTypeDef)

			lookupEnum[e.Name] = e
			lookupNonTypedefs["enum "+e.CName] = e.Name
			lookupEnum[e.CName] = e

			enums = append(enums, e)
		case clang.CK_FunctionDecl:
			f := handleFunctionCursor(cursor)
			if f != nil {
				functions = append(functions, f)
			}
		case clang.CK_StructDecl:
			if cname == "" {
				break
			}

			s := handleStructCursor(cursor, cname, cnameIsTypeDef)

			lookupStruct[s.Name] = s
			lookupNonTypedefs["struct "+s.CName] = s.Name
			lookupStruct[s.CName] = s

			structs = append(structs, s)
		case clang.CK_TypedefDecl:
			underlyingType := cursor.TypedefDeclUnderlyingType().TypeSpelling()
			underlyingStructType := strings.TrimSuffix(strings.TrimPrefix(underlyingType, "struct "), " *")

			if s, ok := lookupStruct[underlyingStructType]; ok && !s.CNameIsTypeDef && strings.HasPrefix(underlyingType, "struct "+s.CName) {
				// Sometimes the typedef is not a parent of the struct but a sibling TODO find out if this is a bug?

				sn := handleVoidStructCursor(cursor, cname, true)

				lookupStruct[sn.Name] = sn
				lookupNonTypedefs["struct "+sn.CName] = sn.Name
				lookupStruct[sn.CName] = sn

				// Update the lookups for the old struct
				lookupStruct[s.Name] = sn
				lookupStruct[s.CName] = sn

				for i, si := range structs {
					if si == s {
						structs[i] = sn

						break
					}
				}
			} else if underlyingType == "void *" {
				s := handleVoidStructCursor(cursor, cname, true)

				lookupStruct[s.Name] = s
				lookupNonTypedefs["struct "+s.CName] = s.Name
				lookupStruct[s.CName] = s

				structs = append(structs, s)
			}
		}

		return clang.CVR_Recurse
	})

	trimCommonFName := func(fname string, rt Receiver) string {
		fname = strings.TrimPrefix(fname, "get")

		if fn := strings.TrimPrefix(fname, rt.Name+"_"); len(fn) != len(fname) {
			fname = fn
		} else if fn := strings.TrimPrefix(fname, rt.Name); len(fn) != len(fname) {
			fname = fn
		} else if fn := strings.TrimSuffix(fname, rt.CName); len(fn) != len(fname) {
			fname = fn
		}

		fname = strings.TrimPrefix(fname, "get")

		return fname
	}

	addMethod := func(f *Function, fname string, fnamePrefix string, rt Receiver, method func(f *Function) string) bool {
		fname = upperFirstCharacter(fname)

		if e, ok := lookupEnum[rt.Name]; ok {
			f.Name = fnamePrefix + fname
			f.Receiver = e.Receiver
			f.Receiver.Type = rt.Name

			e.Methods = append(e.Methods, method(f))

			return true
		} else if s, ok := lookupStruct[rt.Name]; ok {
			f.Name = fnamePrefix + fname
			f.Receiver = s.Receiver
			f.Receiver.Type = rt.Name

			s.Methods = append(s.Methods, method(f))

			return true
		}

		return false
	}

	addBasicMethods := func(f *Function, fname string, fnamePrefix string, rt Receiver) bool {
		if len(f.Parameters) == 1 && f.ReturnType == "String" {
			fname = trimCommonFName(fname, rt)

			return addMethod(f, fname, fnamePrefix, rt, generateFunctionStringGetter)
		} else if len(f.Parameters) == 1 && isEnumOrStruct(f.ReturnType) && isEnumOrStruct(f.Parameters[0].Type) {
			fname = trimCommonFName(fname, rt)

			return addMethod(f, fname, fnamePrefix, rt, generateFunctionGetter)
		} else if len(f.Parameters) == 1 &&
			((fname[0] == 'i' && fname[1] == 's' && unicode.IsUpper(rune(fname[2]))) || (fname[0] == 'h' && fname[1] == 'a' && fname[2] == 's' && unicode.IsUpper(rune(fname[3])))) &&
			(f.ReturnType == "unsigned int" || f.ReturnType == "int") {
			return addMethod(f, fname, fnamePrefix, rt, generateFunctionIs)
		} else if len(f.Parameters) == 1 && strings.HasPrefix(fname, "dispose") && f.ReturnType == "void" {
			fname = "Dispose"

			return addMethod(f, fname, fnamePrefix, rt, generateFunctionVoidMethod)
		} else if len(f.Parameters) == 2 && strings.HasPrefix(fname, "equal") && f.ReturnType == "unsigned int" && f.Parameters[0].Type == f.Parameters[1].Type {
			return addMethod(f, fname, fnamePrefix, rt, generateFunctionEqual)
		}

		return false
	}

	for _, f := range functions {
		fname := f.Name
		var rt Receiver
		if len(f.Parameters) > 0 {
			rt.CName = f.Parameters[0].Type
			rt.Name = trimClangPrefix(rt.CName)
			if n, ok := lookupNonTypedefs[rt.Name]; ok {
				rt.Name = n
			}
		}

		if n, ok := lookupNonTypedefs[f.ReturnType]; ok {
			f.ReturnType = n
		}
		if e, ok := lookupEnum[f.ReturnType]; ok {
			f.ReturnPrimitiveType = e.Receiver.PrimitiveType
		} else if _, ok := lookupStruct[f.ReturnType]; ok {
		}

		added := addBasicMethods(f, fname, "", rt)

		if !added {
			if s := strings.SplitN(f.Name, "_", 2); len(s) == 2 {
				if s[0] == rt.Name {
					rtc := rt
					rtc.Name = s[0]

					added = addBasicMethods(f, s[1], "", rtc)
				}
			}
		}

		if !added {
			fmt.Println("Unused:", f.Name)
		}
	}

	for _, e := range enums {
		if err := generateEnum(e); err != nil {
			exitWithFatal("Cannot generate enum", err)
		}
	}

	for _, s := range structs {
		if err := generateStruct(s); err != nil {
			exitWithFatal("Cannot generate struct", err)
		}
	}

	if _, _, err = execToBuffer("gofmt", "-w", "./"); err != nil { // TODO do this before saving the files using go/fmt
		exitWithFatal("Gofmt failed", err)
	}
}
<|endoftext|>


<commit_before>/*
Copyright 2016 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package main

import (
	"io"
	"path/filepath"

	"github.com/spf13/cobra"
	"k8s.io/helm/pkg/downloader"
	"k8s.io/helm/pkg/getter"
	"k8s.io/helm/pkg/helm/helmpath"
)

const dependencyUpDesc = `
Update the on-disk dependencies to mirror the requirements.yaml file.

This command verifies that the required charts, as expressed in 'requirements.yaml',
are present in 'charts/' and are at an acceptable version. It will pull down
the latest charts that satisfy the dependencies, and clean up old dependencies.

On successful update, this will generate a lock file that can be used to
rebuild the requirements to an exact version.

Dependencies are not required to be represented in 'requirements.yaml'. For that
reason, an update command will not remove charts unless they are (a) present
in the requirements.yaml file, but (b) at the wrong version.
`

// dependencyUpdateCmd describes a 'helm dependency update'
type dependencyUpdateCmd struct {
	out         io.Writer
	chartpath   string
	helmhome    helmpath.Home
	verify      bool
	keyring     string
	skipRefresh bool
}

// newDependencyUpdateCmd creates a new dependency update command.
func newDependencyUpdateCmd(out io.Writer) *cobra.Command {
	duc := &dependencyUpdateCmd{out: out}

	cmd := &cobra.Command{
		Use:     "update [flags] CHART",
		Aliases: []string{"up"},
		Short:   "update charts/ based on the contents of requirements.yaml",
		Long:    dependencyUpDesc,
		RunE: func(cmd *cobra.Command, args []string) error {
			cp := "."
			if len(args) > 0 {
				cp = args[0]
			}

			var err error
			duc.chartpath, err = filepath.Abs(cp)
			if err != nil {
				return err
			}

			duc.helmhome = settings.Home

			return duc.run()
		},
	}

	f := cmd.Flags()
	f.BoolVar(&duc.verify, "verify", false, "verify the packages against signatures")
	f.StringVar(&duc.keyring, "keyring", defaultKeyring(), "keyring containing public keys")
	f.BoolVar(&duc.skipRefresh, "skip-refresh", false, "do not refresh the local repository cache")

	return cmd
}

// run runs the full dependency update process.
func (d *dependencyUpdateCmd) run() error {
	man := &downloader.Manager{
		Out:        d.out,
		ChartPath:  d.chartpath,
		HelmHome:   d.helmhome,
		Keyring:    d.keyring,
		SkipUpdate: d.skipRefresh,
		Getters:    getter.All(settings),
	}
	if d.verify {
		man.Verify = downloader.VerifyIfPossible
	}
	if settings.Debug {
		man.Debug = true
	}
	return man.Update()
}
<commit_msg>fix(helm): Fix the bug in helm dependency update -verify<commit_after>/*
Copyright 2016 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package main

import (
	"io"
	"path/filepath"

	"github.com/spf13/cobra"
	"k8s.io/helm/pkg/downloader"
	"k8s.io/helm/pkg/getter"
	"k8s.io/helm/pkg/helm/helmpath"
)

const dependencyUpDesc = `
Update the on-disk dependencies to mirror the requirements.yaml file.

This command verifies that the required charts, as expressed in 'requirements.yaml',
are present in 'charts/' and are at an acceptable version. It will pull down
the latest charts that satisfy the dependencies, and clean up old dependencies.

On successful update, this will generate a lock file that can be used to
rebuild the requirements to an exact version.

Dependencies are not required to be represented in 'requirements.yaml'. For that
reason, an update command will not remove charts unless they are (a) present
in the requirements.yaml file, but (b) at the wrong version.
`

// dependencyUpdateCmd describes a 'helm dependency update'
type dependencyUpdateCmd struct {
	out         io.Writer
	chartpath   string
	helmhome    helmpath.Home
	verify      bool
	keyring     string
	skipRefresh bool
}

// newDependencyUpdateCmd creates a new dependency update command.
func newDependencyUpdateCmd(out io.Writer) *cobra.Command {
	duc := &dependencyUpdateCmd{out: out}

	cmd := &cobra.Command{
		Use:     "update [flags] CHART",
		Aliases: []string{"up"},
		Short:   "update charts/ based on the contents of requirements.yaml",
		Long:    dependencyUpDesc,
		RunE: func(cmd *cobra.Command, args []string) error {
			cp := "."
			if len(args) > 0 {
				cp = args[0]
			}

			var err error
			duc.chartpath, err = filepath.Abs(cp)
			if err != nil {
				return err
			}

			duc.helmhome = settings.Home

			return duc.run()
		},
	}

	f := cmd.Flags()
	f.BoolVar(&duc.verify, "verify", false, "verify the packages against signatures")
	f.StringVar(&duc.keyring, "keyring", defaultKeyring(), "keyring containing public keys")
	f.BoolVar(&duc.skipRefresh, "skip-refresh", false, "do not refresh the local repository cache")

	return cmd
}

// run runs the full dependency update process.
func (d *dependencyUpdateCmd) run() error {
	man := &downloader.Manager{
		Out:        d.out,
		ChartPath:  d.chartpath,
		HelmHome:   d.helmhome,
		Keyring:    d.keyring,
		SkipUpdate: d.skipRefresh,
		Getters:    getter.All(settings),
	}
	if d.verify {
		man.Verify = downloader.VerifyAlways
	}
	if settings.Debug {
		man.Debug = true
	}
	return man.Update()
}
<|endoftext|>


<commit_before>package cmd

import (
	"fmt"
	"os"

	"github.com/cayleygraph/cayley"
	"github.com/pkg/errors"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"

	_ "github.com/cayleygraph/cayley/graph/kv/bolt" // required for cayley

	"nimona.io/internal/api"
	"nimona.io/internal/store/graph"
	"nimona.io/pkg/discovery"
	"nimona.io/pkg/discovery/hyperspace"
	"nimona.io/pkg/middleware/handshake"
	"nimona.io/pkg/net"
	"nimona.io/pkg/object/aggregate"
	"nimona.io/pkg/object/dag"
	"nimona.io/pkg/object/exchange"
)

var (
	daemonPeerKey     string
	daemonIdentityKey string

	daemonPort             int
	daemonAPIPort          int
	daemonAnnounceHostname string
	daemonEnableMetrics    bool
	daemonToken            string

	daemonRelayAddresses []string

	daemonBootstrapAddresses = []string{
		// "tcps:andromeda.nimona.io:21013",
		// "tcps:borealis.nimona.io:21013",
		"tcps:cassiopeia.nimona.io:21013",
		// "tcps:draco.nimona.io:21013",
		// "tcps:eridanus.nimona.io:21013",
		// "tcps:fornax.nimona.io:21013",
		// "tcps:gemini.nimona.io:21013",
		// "tcps:hydra.nimona.io:21013",
		// "tcps:indus.nimona.io:21013",
		// "tcps:lacerta.nimona.io:21013",
		// "tcps:mensa.nimona.io:21013",
		// "tcps:norma.nimona.io:21013",
		// "tcps:orion.nimona.io:21013",
		// "tcps:pyxis.nimona.io:21013",
		// "tcps:stats.nimona.io:21013",
	}
)

// daemonStartCmd represents the daemon command
var daemonStartCmd = &cobra.Command{
	Use:   "start",
	Short: "Start a peer as a daemon",
	Long:  "",
	RunE: func(cmd *cobra.Command, args []string) error {
		bootstrapAddresses := viper.GetStringSlice("daemon.bootstraps")
		relayAddresses := viper.GetStringSlice("daemon.relays")

		if config.Daemon.PeerKey == nil {
			return errors.New("daemon not configured, please run 'daemon init'")
		}

		if err := os.MkdirAll(config.Daemon.ObjectPath, 0777); err != nil {
			return errors.Wrap(err, "could not create objects dir")
		}

		if len(bootstrapAddresses) > 0 {
			cmd.Println("Adding bootstrap nodes")
			for _, v := range bootstrapAddresses {
				cmd.Println("  *", v)
			}
		} else {
			cmd.Println("No bootstrap nodes provided")
		}

		dis := discovery.NewDiscoverer()

		k := config.Daemon.PeerKey

		li, err := net.NewLocalInfo(
			viper.GetString("daemon.announce_hostname"), k)
		if err != nil {
			return err
		}

		n, err := net.New(dis, li)
		if err != nil {
			return err
		}

		tcp := net.NewTCPTransport(li, relayAddresses)
		hsm := handshake.New(li, dis)

		n.AddMiddleware(hsm.Handle())
		n.AddTransport("tcps", tcp)

		ik := config.Daemon.IdentityKey
		if ik != nil {
			// TODO(NOW) sign pub peer key, add signature to pub peer key
		}

		gs, err := cayley.NewGraph("bolt", config.Daemon.ObjectPath, nil)
		if err != nil {
			return errors.Wrap(err, "could not init graph store")
		}

		dpr := graph.NewCayley(gs)

		bind := fmt.Sprintf("0.0.0.0:%d", viper.GetInt("daemon.port"))
		x, err := exchange.New(k, n, dpr, dis, li, bind)
		if err != nil {
			return err
		}

		dag, err := dag.New(dpr, x, nil, li)
		if err != nil {
			return err
		}

		agg, err := aggregate.New(dpr, x, dag)
		if err != nil {
			return err
		}

		hsr, err := hyperspace.NewDiscoverer(n, x, li, bootstrapAddresses)
		if err != nil {
			return err
		}

		// _ = telemetry.NewTelemetry(x, k, "tcps:stats.nimona.io:21013")

		if err := dis.AddProvider(hsr); err != nil {
			return err
		}

		cmd.Println("Started daemon")
		cmd.Println("* Peer fingerprint:\n  *", k.PublicKey.Fingerprint())
		if ik != nil {
			cmd.Println("* Identity fingerprint:\n  *", ik.PublicKey.Fingerprint())
		}
		peerAddresses := li.GetPeerInfo().Addresses
		cmd.Println("* Peer addresses:")
		if len(peerAddresses) > 0 {
			for _, addr := range peerAddresses {
				cmd.Println("  *", addr)
			}
		} else {
			cmd.Println("  * No addresses available")
		}

		apiServer := api.New(
			k,
			n,
			dis,
			x,
			li,
			dpr,
			dag,
			agg,
			Version,
			Commit,
			Date,
			viper.GetString("daemon.token"),
		)

		apiPort := viper.GetInt("daemon.api_port")
		cmd.Printf("* HTTP API address:\n  * http://localhost:%d\n", apiPort)
		return apiServer.Serve(fmt.Sprintf("0.0.0.0:%d", apiPort))
	},
}

func init() {
	daemonCmd.AddCommand(daemonStartCmd)

	daemonStartCmd.PersistentFlags().IntVarP(
		&daemonPort,
		"port",
		"p",
		0,
		"peer port",
	)
	_ = viper.BindPFlag(
		"daemon.port",
		daemonStartCmd.PersistentFlags().Lookup("port"),
	)

	daemonStartCmd.PersistentFlags().StringVarP(
		&daemonToken,
		"token",
		"t",
		daemonToken,
		"daemon token",
	)
	_ = viper.BindPFlag(
		"daemon.token",
		daemonStartCmd.PersistentFlags().Lookup("token"),
	)

	daemonStartCmd.PersistentFlags().StringVar(
		&daemonAnnounceHostname,
		"announce-hostname",
		"",
		"set and announce local dns address",
	)
	_ = viper.BindPFlag(
		"daemon.announce_hostname",
		daemonStartCmd.PersistentFlags().Lookup("announce-hostname"),
	)

	daemonStartCmd.PersistentFlags().IntVar(
		&daemonAPIPort,
		"api-port",
		8030,
		"api port",
	)
	_ = viper.BindPFlag(
		"daemon.api_port",
		daemonStartCmd.PersistentFlags().Lookup("api-port"),
	)

	daemonStartCmd.PersistentFlags().BoolVarP(
		&daemonEnableMetrics,
		"metrics",
		"m",
		false,
		"enable sending anonymous metrics",
	)
	_ = viper.BindPFlag(
		"daemon.metrics",
		daemonStartCmd.PersistentFlags().Lookup("metrics"),
	)

	daemonStartCmd.PersistentFlags().StringSliceVar(
		&daemonBootstrapAddresses,
		"bootstraps",
		daemonBootstrapAddresses,
		"bootstrap addresses",
	)
	_ = viper.BindPFlag(
		"daemon.bootstraps",
		daemonStartCmd.PersistentFlags().Lookup("bootstraps"),
	)

	daemonStartCmd.PersistentFlags().StringSliceVar(
		&daemonRelayAddresses,
		"relays",
		daemonRelayAddresses,
		"relay addresses",
	)
	_ = viper.BindPFlag(
		"daemon.relays",
		daemonStartCmd.PersistentFlags().Lookup("relays"),
	)
}
<commit_msg>chore(cmd/nimona): remove signed key todo check<commit_after>package cmd

import (
	"fmt"
	"os"

	"github.com/cayleygraph/cayley"
	"github.com/pkg/errors"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"

	_ "github.com/cayleygraph/cayley/graph/kv/bolt" // required for cayley

	"nimona.io/internal/api"
	"nimona.io/internal/store/graph"
	"nimona.io/pkg/discovery"
	"nimona.io/pkg/discovery/hyperspace"
	"nimona.io/pkg/middleware/handshake"
	"nimona.io/pkg/net"
	"nimona.io/pkg/object/aggregate"
	"nimona.io/pkg/object/dag"
	"nimona.io/pkg/object/exchange"
)

var (
	daemonPeerKey     string
	daemonIdentityKey string

	daemonPort             int
	daemonAPIPort          int
	daemonAnnounceHostname string
	daemonEnableMetrics    bool
	daemonToken            string

	daemonRelayAddresses []string

	daemonBootstrapAddresses = []string{
		// "tcps:andromeda.nimona.io:21013",
		// "tcps:borealis.nimona.io:21013",
		"tcps:cassiopeia.nimona.io:21013",
		// "tcps:draco.nimona.io:21013",
		// "tcps:eridanus.nimona.io:21013",
		// "tcps:fornax.nimona.io:21013",
		// "tcps:gemini.nimona.io:21013",
		// "tcps:hydra.nimona.io:21013",
		// "tcps:indus.nimona.io:21013",
		// "tcps:lacerta.nimona.io:21013",
		// "tcps:mensa.nimona.io:21013",
		// "tcps:norma.nimona.io:21013",
		// "tcps:orion.nimona.io:21013",
		// "tcps:pyxis.nimona.io:21013",
		// "tcps:stats.nimona.io:21013",
	}
)

// daemonStartCmd represents the daemon command
var daemonStartCmd = &cobra.Command{
	Use:   "start",
	Short: "Start a peer as a daemon",
	Long:  "",
	RunE: func(cmd *cobra.Command, args []string) error {
		bootstrapAddresses := viper.GetStringSlice("daemon.bootstraps")
		relayAddresses := viper.GetStringSlice("daemon.relays")

		if config.Daemon.PeerKey == nil {
			return errors.New("daemon not configured, please run 'daemon init'")
		}

		if err := os.MkdirAll(config.Daemon.ObjectPath, 0777); err != nil {
			return errors.Wrap(err, "could not create objects dir")
		}

		if len(bootstrapAddresses) > 0 {
			cmd.Println("Adding bootstrap nodes")
			for _, v := range bootstrapAddresses {
				cmd.Println("  *", v)
			}
		} else {
			cmd.Println("No bootstrap nodes provided")
		}

		dis := discovery.NewDiscoverer()

		k := config.Daemon.PeerKey

		li, err := net.NewLocalInfo(
			viper.GetString("daemon.announce_hostname"), k)
		if err != nil {
			return err
		}

		n, err := net.New(dis, li)
		if err != nil {
			return err
		}

		tcp := net.NewTCPTransport(li, relayAddresses)
		hsm := handshake.New(li, dis)

		n.AddMiddleware(hsm.Handle())
		n.AddTransport("tcps", tcp)

		gs, err := cayley.NewGraph("bolt", config.Daemon.ObjectPath, nil)
		if err != nil {
			return errors.Wrap(err, "could not init graph store")
		}

		dpr := graph.NewCayley(gs)

		bind := fmt.Sprintf("0.0.0.0:%d", viper.GetInt("daemon.port"))
		x, err := exchange.New(k, n, dpr, dis, li, bind)
		if err != nil {
			return err
		}

		dag, err := dag.New(dpr, x, nil, li)
		if err != nil {
			return err
		}

		agg, err := aggregate.New(dpr, x, dag)
		if err != nil {
			return err
		}

		hsr, err := hyperspace.NewDiscoverer(n, x, li, bootstrapAddresses)
		if err != nil {
			return err
		}

		// _ = telemetry.NewTelemetry(x, k, "tcps:stats.nimona.io:21013")

		if err := dis.AddProvider(hsr); err != nil {
			return err
		}

		cmd.Println("Started daemon")
		cmd.Println("* Peer fingerprint:\n  *", k.PublicKey.Fingerprint())
		ik := config.Daemon.IdentityKey
		if ik != nil {
			cmd.Println("* Identity fingerprint:\n  *", ik.PublicKey.Fingerprint())
		}
		peerAddresses := li.GetPeerInfo().Addresses
		cmd.Println("* Peer addresses:")
		if len(peerAddresses) > 0 {
			for _, addr := range peerAddresses {
				cmd.Println("  *", addr)
			}
		} else {
			cmd.Println("  * No addresses available")
		}

		apiServer := api.New(
			k,
			n,
			dis,
			x,
			li,
			dpr,
			dag,
			agg,
			Version,
			Commit,
			Date,
			viper.GetString("daemon.token"),
		)

		apiPort := viper.GetInt("daemon.api_port")
		cmd.Printf("* HTTP API address:\n  * http://localhost:%d\n", apiPort)
		return apiServer.Serve(fmt.Sprintf("0.0.0.0:%d", apiPort))
	},
}

func init() {
	daemonCmd.AddCommand(daemonStartCmd)

	daemonStartCmd.PersistentFlags().IntVarP(
		&daemonPort,
		"port",
		"p",
		0,
		"peer port",
	)
	_ = viper.BindPFlag(
		"daemon.port",
		daemonStartCmd.PersistentFlags().Lookup("port"),
	)

	daemonStartCmd.PersistentFlags().StringVarP(
		&daemonToken,
		"token",
		"t",
		daemonToken,
		"daemon token",
	)
	_ = viper.BindPFlag(
		"daemon.token",
		daemonStartCmd.PersistentFlags().Lookup("token"),
	)

	daemonStartCmd.PersistentFlags().StringVar(
		&daemonAnnounceHostname,
		"announce-hostname",
		"",
		"set and announce local dns address",
	)
	_ = viper.BindPFlag(
		"daemon.announce_hostname",
		daemonStartCmd.PersistentFlags().Lookup("announce-hostname"),
	)

	daemonStartCmd.PersistentFlags().IntVar(
		&daemonAPIPort,
		"api-port",
		8030,
		"api port",
	)
	_ = viper.BindPFlag(
		"daemon.api_port",
		daemonStartCmd.PersistentFlags().Lookup("api-port"),
	)

	daemonStartCmd.PersistentFlags().BoolVarP(
		&daemonEnableMetrics,
		"metrics",
		"m",
		false,
		"enable sending anonymous metrics",
	)
	_ = viper.BindPFlag(
		"daemon.metrics",
		daemonStartCmd.PersistentFlags().Lookup("metrics"),
	)

	daemonStartCmd.PersistentFlags().StringSliceVar(
		&daemonBootstrapAddresses,
		"bootstraps",
		daemonBootstrapAddresses,
		"bootstrap addresses",
	)
	_ = viper.BindPFlag(
		"daemon.bootstraps",
		daemonStartCmd.PersistentFlags().Lookup("bootstraps"),
	)

	daemonStartCmd.PersistentFlags().StringSliceVar(
		&daemonRelayAddresses,
		"relays",
		daemonRelayAddresses,
		"relay addresses",
	)
	_ = viper.BindPFlag(
		"daemon.relays",
		daemonStartCmd.PersistentFlags().Lookup("relays"),
	)
}
<|endoftext|>