<commit_before>package azure

import (
	"context"

	"github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2018-10-01/containerinstance"
	"github.com/Azure/go-autorest/autorest/azure/auth"
	"github.com/compose-spec/compose-go/types"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"

	"github.com/docker/api/azure/convert"
	"github.com/docker/api/backend"
	"github.com/docker/api/compose"
	"github.com/docker/api/containers"
	apicontext "github.com/docker/api/context"
	"github.com/docker/api/context/store"
)

type containerService struct {
	containerGroupsClient containerinstance.ContainerGroupsClient
	ctx                   store.AciContext
}

func init() {
	backend.Register("aci", "aci", func(ctx context.Context) (interface{}, error) {
		return New(ctx)
	})
}

func getter() interface{} {
	return &store.AciContext{}
}

func New(ctx context.Context) (containers.ContainerService, error) {
	currentContext := apicontext.CurrentContext(ctx)
	contextStore, err := store.New()
	if err != nil {
		return nil, err
	}
	metadata, err := contextStore.Get(currentContext, getter)
	if err != nil {
		return nil, errors.Wrap(err, "wrong context type")
	}
	aciContext, _ := metadata.Metadata.Data.(store.AciContext)

	auth, _ := auth.NewAuthorizerFromCLI()
	containerGroupsClient := containerinstance.NewContainerGroupsClient(aciContext.SubscriptionID)
	containerGroupsClient.Authorizer = auth

	return &containerService{
		containerGroupsClient: containerGroupsClient,
		ctx:                   aciContext,
	}, nil
}

func (cs *containerService) List(ctx context.Context) ([]containers.Container, error) {
	var containerGroups []containerinstance.ContainerGroup
	result, err := cs.containerGroupsClient.ListByResourceGroup(ctx, cs.ctx.ResourceGroup)
	if err != nil {
		return []containers.Container{}, err
	}

	for result.NotDone() {
		containerGroups = append(containerGroups, result.Values()...)
		if err := result.NextWithContext(ctx); err != nil {
			return []containers.Container{}, err
		}
	}

	res := []containers.Container{}
	for _, containerGroup := range containerGroups {
		group, err := cs.containerGroupsClient.Get(ctx, cs.ctx.ResourceGroup, *containerGroup.Name)
		if err != nil {
			return []containers.Container{}, err
		}

		for _, container := range *group.Containers {
			status := "Unknown"
			if container.InstanceView != nil && container.InstanceView.CurrentState != nil {
				status = *container.InstanceView.CurrentState.State
			}
			res = append(res, containers.Container{
				ID:     *container.Name,
				Image:  *container.Image,
				Status: status,
			})
		}
	}

	return res, nil
}

func (cs *containerService) Run(ctx context.Context, r containers.ContainerConfig) error {
	var project compose.Project
	project.Name = r.ID
	var ports []types.ServicePortConfig
	for _, p := range r.Ports {
		ports = append(ports, types.ServicePortConfig{
			Target:    p.Destination,
			Published: p.Source,
		})
	}
	project.Services = []types.ServiceConfig{
		{
			Name:  r.ID,
			Image: r.Image,
			Ports: ports,
		},
	}

	logrus.Debugf("Running container %q with name %q\n", r.Image, r.ID)
	groupDefinition, err := convert.ToContainerGroup(cs.ctx, project)
	if err != nil {
		return err
	}

	_, err = createACIContainers(ctx, cs.ctx, groupDefinition)
	return err
}
<commit_msg>Init all the fields of a compose project at once<commit_after>package azure

import (
	"context"

	"github.com/Azure/azure-sdk-for-go/services/containerinstance/mgmt/2018-10-01/containerinstance"
	"github.com/Azure/go-autorest/autorest/azure/auth"
	"github.com/compose-spec/compose-go/types"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"

	"github.com/docker/api/azure/convert"
	"github.com/docker/api/backend"
	"github.com/docker/api/compose"
	"github.com/docker/api/containers"
	apicontext "github.com/docker/api/context"
	"github.com/docker/api/context/store"
)

type containerService struct {
	containerGroupsClient containerinstance.ContainerGroupsClient
	ctx                   store.AciContext
}

func init() {
	backend.Register("aci", "aci", func(ctx context.Context) (interface{}, error) {
		return New(ctx)
	})
}

func getter() interface{} {
	return &store.AciContext{}
}

func New(ctx context.Context) (containers.ContainerService, error) {
	currentContext := apicontext.CurrentContext(ctx)
	contextStore, err := store.New()
	if err != nil {
		return nil, err
	}
	metadata, err := contextStore.Get(currentContext, getter)
	if err != nil {
		return nil, errors.Wrap(err, "wrong context type")
	}
	aciContext, _ := metadata.Metadata.Data.(store.AciContext)

	auth, _ := auth.NewAuthorizerFromCLI()
	containerGroupsClient := containerinstance.NewContainerGroupsClient(aciContext.SubscriptionID)
	containerGroupsClient.Authorizer = auth

	return &containerService{
		containerGroupsClient: containerGroupsClient,
		ctx:                   aciContext,
	}, nil
}

func (cs *containerService) List(ctx context.Context) ([]containers.Container, error) {
	var containerGroups []containerinstance.ContainerGroup
	result, err := cs.containerGroupsClient.ListByResourceGroup(ctx, cs.ctx.ResourceGroup)
	if err != nil {
		return []containers.Container{}, err
	}

	for result.NotDone() {
		containerGroups = append(containerGroups, result.Values()...)
		if err := result.NextWithContext(ctx); err != nil {
			return []containers.Container{}, err
		}
	}

	res := []containers.Container{}
	for _, containerGroup := range containerGroups {
		group, err := cs.containerGroupsClient.Get(ctx, cs.ctx.ResourceGroup, *containerGroup.Name)
		if err != nil {
			return []containers.Container{}, err
		}

		for _, container := range *group.Containers {
			status := "Unknown"
			if container.InstanceView != nil && container.InstanceView.CurrentState != nil {
				status = *container.InstanceView.CurrentState.State
			}
			res = append(res, containers.Container{
				ID:     *container.Name,
				Image:  *container.Image,
				Status: status,
			})
		}
	}

	return res, nil
}

func (cs *containerService) Run(ctx context.Context, r containers.ContainerConfig) error {
	var ports []types.ServicePortConfig
	for _, p := range r.Ports {
		ports = append(ports, types.ServicePortConfig{
			Target:    p.Destination,
			Published: p.Source,
		})
	}
	project := compose.Project{
		Name: r.ID,
		Config: types.Config{
			Services: []types.ServiceConfig{
				{
					Name:  r.ID,
					Image: r.Image,
					Ports: ports,
				},
			},
		},
	}

	logrus.Debugf("Running container %q with name %q\n", r.Image, r.ID)
	groupDefinition, err := convert.ToContainerGroup(cs.ctx, project)
	if err != nil {
		return err
	}

	_, err = createACIContainers(ctx, cs.ctx, groupDefinition)
	return err
}
<|endoftext|>


<commit_before>package util

import (
	"crypto/tls"
	"fmt"
	"net"
	"net/http"
	"net/url"
	"time"

	"github.com/getlantern/golog"
	"github.com/getlantern/keyman"
	"github.com/getlantern/waitforserver"
)

var (
	log = golog.LoggerFor("flashlight.util")
)

// PersistentHTTPClient creates an http.Client that persists across requests.
// If rootCA is specified, the client will validate the server's certificate
// on TLS connections against that RootCA. If proxyAddr is specified, the client
// will proxy through the given http proxy.
func PersistentHTTPClient(rootCA string, proxyAddr string) (*http.Client, error) {
	return httpClient(rootCA, proxyAddr, true)
}

// HTTPClient creates an http.Client. If rootCA is specified, the client will
// validate the server's certificate on TLS connections against that RootCA. If
// proxyAddr is specified, the client will proxy through the given http proxy.
func HTTPClient(rootCA string, proxyAddr string) (*http.Client, error) {
	return httpClient(rootCA, proxyAddr, false)
}

// httpClient creates an http.Client. If rootCA is specified, the client will
// validate the server's certificate on TLS connections against that RootCA. If
// proxyAddr is specified, the client will proxy through the given http proxy.
func httpClient(rootCA string, proxyAddr string, persistent bool) (*http.Client, error) {

	log.Debugf("Creating new HTTPClient with proxy: %v", proxyAddr)

	tr := &http.Transport{
		Dial: (&net.Dialer{
			Timeout:   60 * time.Second,
			KeepAlive: 30 * time.Second,
		}).Dial,
		TLSHandshakeTimeout: 10 * time.Second,

		// This method is typically used for creating a one-off HTTP client
		// that we don't want to keep around for future calls, making
		// persistent connections a potential source of file descriptor
		// leaks. Note the name of this variable is misleading -- it would
		// be clearer to call it DisablePersistentConnections -- i.e. it has
		// nothing to do with TCP keep alives along the lines of the KeepAlive
		// variable in net.Dialer.
		DisableKeepAlives: !persistent,
	}

	if rootCA != "" {
		caCert, err := keyman.LoadCertificateFromPEMBytes([]byte(rootCA))
		if err != nil {
			return nil, fmt.Errorf("Unable to decode rootCA: %s", err)
		}
		tr.TLSClientConfig = &tls.Config{
			RootCAs: caCert.PoolContainingCert(),
		}
	}

	if proxyAddr != "" {

		host, _, err := net.SplitHostPort(proxyAddr)
		if err != nil {
			return nil, fmt.Errorf("Unable to split host and port for %v: %v", proxyAddr, err)
		}

		noHostSpecified := host == ""
		if noHostSpecified {
			// For addresses of the form ":8080", prepend the loopback IP
			host = "127.0.0.1"
			proxyAddr = host + proxyAddr
		}

		var ip net.IP
		if ip = net.ParseIP(host); ip != nil {
			if ip.IsLoopback() {
				log.Debugf("Waiting for loopback proxy server to came online...")
				// Waiting for proxy server to came online.
				err := waitforserver.WaitForServer("tcp", proxyAddr, 60*time.Second)
				if err != nil {
					// Instead of finishing here we just log the error and continue, the client
					// we are going to create will surely fail when used and return errors,
					// those errors should be handled by the code that depends on such client.
					log.Errorf("Proxy never came online at %v: %q", proxyAddr, err)
				}
			}
		}

		tr.Proxy = func(req *http.Request) (*url.URL, error) {
			return url.Parse("http://" + proxyAddr)
		}
	}
	return &http.Client{Transport: tr}, nil
}
<commit_msg>Fixed loopback check to consider localhost to be a loopback address closes #2817<commit_after>package util

import (
	"crypto/tls"
	"fmt"
	"net"
	"net/http"
	"net/url"
	"time"

	"github.com/getlantern/golog"
	"github.com/getlantern/keyman"
	"github.com/getlantern/waitforserver"
)

var (
	log = golog.LoggerFor("flashlight.util")
)

// PersistentHTTPClient creates an http.Client that persists across requests.
// If rootCA is specified, the client will validate the server's certificate
// on TLS connections against that RootCA. If proxyAddr is specified, the client
// will proxy through the given http proxy.
func PersistentHTTPClient(rootCA string, proxyAddr string) (*http.Client, error) {
	return httpClient(rootCA, proxyAddr, true)
}

// HTTPClient creates an http.Client. If rootCA is specified, the client will
// validate the server's certificate on TLS connections against that RootCA. If
// proxyAddr is specified, the client will proxy through the given http proxy.
func HTTPClient(rootCA string, proxyAddr string) (*http.Client, error) {
	return httpClient(rootCA, proxyAddr, false)
}

// httpClient creates an http.Client. If rootCA is specified, the client will
// validate the server's certificate on TLS connections against that RootCA. If
// proxyAddr is specified, the client will proxy through the given http proxy.
func httpClient(rootCA string, proxyAddr string, persistent bool) (*http.Client, error) {

	log.Debugf("Creating new HTTPClient with proxy: %v", proxyAddr)

	tr := &http.Transport{
		Dial: (&net.Dialer{
			Timeout:   60 * time.Second,
			KeepAlive: 30 * time.Second,
		}).Dial,
		TLSHandshakeTimeout: 10 * time.Second,

		// This method is typically used for creating a one-off HTTP client
		// that we don't want to keep around for future calls, making
		// persistent connections a potential source of file descriptor
		// leaks. Note the name of this variable is misleading -- it would
		// be clearer to call it DisablePersistentConnections -- i.e. it has
		// nothing to do with TCP keep alives along the lines of the KeepAlive
		// variable in net.Dialer.
		DisableKeepAlives: !persistent,
	}

	if rootCA != "" {
		caCert, err := keyman.LoadCertificateFromPEMBytes([]byte(rootCA))
		if err != nil {
			return nil, fmt.Errorf("Unable to decode rootCA: %s", err)
		}
		tr.TLSClientConfig = &tls.Config{
			RootCAs: caCert.PoolContainingCert(),
		}
	}

	if proxyAddr != "" {

		host, _, err := net.SplitHostPort(proxyAddr)
		if err != nil {
			return nil, fmt.Errorf("Unable to split host and port for %v: %v", proxyAddr, err)
		}

		noHostSpecified := host == ""
		if noHostSpecified {
			// For addresses of the form ":8080", prepend the loopback IP
			host = "127.0.0.1"
			proxyAddr = host + proxyAddr
		}

		if isLoopback(host) {
			log.Debugf("Waiting for loopback proxy server to came online...")
			// Waiting for proxy server to came online.
			err := waitforserver.WaitForServer("tcp", proxyAddr, 60*time.Second)
			if err != nil {
				// Instead of finishing here we just log the error and continue, the client
				// we are going to create will surely fail when used and return errors,
				// those errors should be handled by the code that depends on such client.
				log.Errorf("Proxy never came online at %v: %q", proxyAddr, err)
			}
			log.Debugf("Connected to proxy on localhost")
		} else {
			log.Errorf("Attempting to proxy through server other than loopback %v", host)
		}

		tr.Proxy = func(req *http.Request) (*url.URL, error) {
			return url.Parse("http://" + proxyAddr)
		}
	} else {
		log.Errorf("Using direct http client with no proxyAddr")
	}
	return &http.Client{Transport: tr}, nil
}

func isLoopback(host string) bool {
	if host == "localhost" {
		return true
	}
	var ip net.IP
	if ip = net.ParseIP(host); ip != nil {
		return ip.IsLoopback()
	}
	return false
}
<|endoftext|>


<commit_before>package ofx

import (
	"os"
	"testing"
)

func TestParseV102(t *testing.T) {
	f, err := os.Open("testdata/v102.ofx")
	if err != nil {
		t.Fatal(err)
	}

	_ofx, err := Parse(f)
	if err != nil {
		t.Error(err)
	}

	if _ofx == nil {
		t.Errorf("Nil ofx %s\n", _ofx)
	}
}

func TestParseV103(t *testing.T) {
	f, err := os.Open("testdata/v103.ofx")
	if err != nil {
		t.Fatal(err)
	}

	_ofx, err := Parse(f)
	if err != nil {
		t.Error(err)
	}

	if _ofx == nil {
		t.Errorf("Nil ofx %s\n", _ofx)
	}
}
<commit_msg>Verify parsed OFX contents.<commit_after>package ofx

import (
	"os"
	"testing"
)

func verifyOfx(t *testing.T, _ofx *Ofx, acctNum string, routingID string) {

	if _ofx == nil {
		t.Errorf("Nil ofx\n")
	}

	if _ofx.AccountNumber != acctNum {
		t.Errorf("Wrong account number. Expected: %s Actual: %s\n", acctNum, _ofx.AccountNumber)
	}

	if _ofx.RoutingCode != routingID {
		t.Errorf("Wrong routing number. Expected: %s Actual: %s\n", routingID, _ofx.RoutingCode)
	}
}

func TestParseV102(t *testing.T) {
	f, err := os.Open("testdata/v102.ofx")
	if err != nil {
		t.Fatal(err)
	}

	_ofx, err := Parse(f)
	if err != nil {
		t.Error(err)
	}

	verifyOfx(t, _ofx, "098-121", "987654321")
}

func TestParseV103(t *testing.T) {
	f, err := os.Open("testdata/v103.ofx")
	if err != nil {
		t.Fatal(err)
	}

	_ofx, err := Parse(f)
	if err != nil {
		t.Error(err)
	}

	if _ofx == nil {
		t.Errorf("Nil ofx\n")
	}

	verifyOfx(t, _ofx, "098-121", "987654321")
}
<|endoftext|>


<commit_before>package backup

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

	"github.com/pivotal-cf/cf-redis-broker/backup/s3bucket"
	"github.com/pivotal-cf/cf-redis-broker/brokerconfig"
	"github.com/pivotal-cf/cf-redis-broker/redis"
	"github.com/pivotal-cf/cf-redis-broker/redis/client"
	"github.com/pivotal-cf/cf-redis-broker/redisconf"
	"github.com/pivotal-golang/lager"
)

type Backup struct {
	Config *brokerconfig.Config
	Logger lager.Logger
}

func (backup Backup) Create(instanceID string) error {
	s3Client := s3bucket.NewClient(
		backup.Config.RedisConfiguration.BackupConfiguration.EndpointUrl,
		backup.Config.RedisConfiguration.BackupConfiguration.S3Region,
		backup.Config.RedisConfiguration.BackupConfiguration.AccessKeyId,
		backup.Config.RedisConfiguration.BackupConfiguration.SecretAccessKey,
	)

	bucket, err := s3Client.GetOrCreate(backup.Config.RedisConfiguration.BackupConfiguration.BucketName)
	if err != nil {
		return err
	}

	err = backup.createSnapshot(instanceID)
	if err != nil {
		return err
	}

	pathToRdbFile := filepath.Join(backup.Config.RedisConfiguration.InstanceDataDirectory, instanceID, "db", "dump.rdb")

	if !backup.validateBackupFileCreatedFor(pathToRdbFile) {
		return nil
	}

	return backup.uploadToS3(instanceID, pathToRdbFile, bucket)
}

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

func (backup Backup) createSnapshot(instanceID string) error {
	client, err := backup.buildRedisClient(instanceID)
	if err != nil {
		return err
	}

	return client.CreateSnapshot(backup.Config.RedisConfiguration.BackupConfiguration.BGSaveTimeoutSeconds)
}

func (backup Backup) buildRedisClient(instanceID string) (*client.Client, error) {
	localRepo := redis.LocalRepository{RedisConf: backup.Config.RedisConfiguration}
	instance, err := localRepo.FindByID(instanceID)
	if err != nil {
		return nil, err
	}

	instanceConf, err := redisconf.Load(localRepo.InstanceConfigPath(instanceID))
	if err != nil {
		return nil, err
	}

	return client.Connect(instance.Host, uint(instance.Port), instance.Password, instanceConf)
}

func (backup Backup) validateBackupFileCreatedFor(pathToRdbFile string) bool {
	if !fileExists(pathToRdbFile) {
		backup.Logger.Info("dump.rb not found, skipping instance backup", lager.Data{
			"Local file": pathToRdbFile,
		})
		return false
	}
	return true
}

func (backup Backup) uploadToS3(instanceID, pathToRdbFile string, bucket s3bucket.Bucket) error {
	rdbBytes, err := ioutil.ReadFile(pathToRdbFile)
	if err != nil {
		return err
	}

	remotePath := fmt.Sprintf("%s/%s", backup.Config.RedisConfiguration.BackupConfiguration.Path, instanceID)

	backup.Logger.Info("Backing up instance", lager.Data{
		"Local file":  pathToRdbFile,
		"Remote file": remotePath,
	})

	return bucket.Upload(rdbBytes, remotePath)
}
<commit_msg>improve fileExists function in backup<commit_after>package backup

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

	"github.com/pivotal-cf/cf-redis-broker/backup/s3bucket"
	"github.com/pivotal-cf/cf-redis-broker/brokerconfig"
	"github.com/pivotal-cf/cf-redis-broker/redis"
	"github.com/pivotal-cf/cf-redis-broker/redis/client"
	"github.com/pivotal-cf/cf-redis-broker/redisconf"
	"github.com/pivotal-golang/lager"
)

type Backup struct {
	Config *brokerconfig.Config
	Logger lager.Logger
}

func (backup Backup) Create(instanceID string) error {
	s3Client := s3bucket.NewClient(
		backup.Config.RedisConfiguration.BackupConfiguration.EndpointUrl,
		backup.Config.RedisConfiguration.BackupConfiguration.S3Region,
		backup.Config.RedisConfiguration.BackupConfiguration.AccessKeyId,
		backup.Config.RedisConfiguration.BackupConfiguration.SecretAccessKey,
	)

	bucket, err := s3Client.GetOrCreate(backup.Config.RedisConfiguration.BackupConfiguration.BucketName)
	if err != nil {
		return err
	}

	err = backup.createSnapshot(instanceID)
	if err != nil {
		return err
	}

	pathToRdbFile := filepath.Join(backup.Config.RedisConfiguration.InstanceDataDirectory, instanceID, "db", "dump.rdb")

	if !backup.validateBackupFileCreatedFor(pathToRdbFile) {
		return nil
	}

	return backup.uploadToS3(instanceID, pathToRdbFile, bucket)
}

func (backup Backup) createSnapshot(instanceID string) error {
	client, err := backup.buildRedisClient(instanceID)
	if err != nil {
		return err
	}

	return client.CreateSnapshot(backup.Config.RedisConfiguration.BackupConfiguration.BGSaveTimeoutSeconds)
}

func (backup Backup) buildRedisClient(instanceID string) (*client.Client, error) {
	localRepo := redis.LocalRepository{RedisConf: backup.Config.RedisConfiguration}
	instance, err := localRepo.FindByID(instanceID)
	if err != nil {
		return nil, err
	}

	instanceConf, err := redisconf.Load(localRepo.InstanceConfigPath(instanceID))
	if err != nil {
		return nil, err
	}

	return client.Connect(instance.Host, uint(instance.Port), instance.Password, instanceConf)
}

func (backup Backup) validateBackupFileCreatedFor(pathToRdbFile string) bool {
	if !fileExists(pathToRdbFile) {
		backup.Logger.Info("dump.rb not found, skipping instance backup", lager.Data{
			"Local file": pathToRdbFile,
		})
		return false
	}
	return true
}

func (backup Backup) uploadToS3(instanceID, pathToRdbFile string, bucket s3bucket.Bucket) error {
	rdbBytes, err := ioutil.ReadFile(pathToRdbFile)
	if err != nil {
		return err
	}

	remotePath := fmt.Sprintf("%s/%s", backup.Config.RedisConfiguration.BackupConfiguration.Path, instanceID)

	backup.Logger.Info("Backing up instance", lager.Data{
		"Local file":  pathToRdbFile,
		"Remote file": remotePath,
	})

	return bucket.Upload(rdbBytes, remotePath)
}

func fileExists(path string) bool {
	_, err := os.Stat(path)
	return err == nil || os.IsExist(err)
}
<|endoftext|>


<commit_before>// Copyright 2016 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.

package api

import (
	"errors"
	"time"

	"github.com/juju/testing"
	gc "gopkg.in/check.v1"

	jjtesting "github.com/juju/juju/testing"
)

var _ = gc.Suite(&MonitorSuite{})

type MonitorSuite struct {
	testing.IsolationSuite
	clock   *testing.Clock
	closed  chan (struct{})
	broken  chan (struct{})
	monitor *monitor
}

func (s *MonitorSuite) SetUpTest(c *gc.C) {
	s.IsolationSuite.SetUpTest(c)
	s.clock = testing.NewClock(time.Time{})
	s.closed = make(chan struct{})
	s.broken = make(chan struct{})
	s.monitor = &monitor{
		clock:  s.clock,
		ping:   func() error { return nil },
		closed: s.closed,
		broken: s.broken,
	}
}

func (s *MonitorSuite) TestInitialPingFails(c *gc.C) {
	s.monitor.ping = func() error { return errors.New("boom") }
	go s.monitor.run()

	select {
	case <-s.broken:
	case <-time.After(jjtesting.LongWait):
		c.Fatal("timed out waiting for broken to close")
	}
}

func (s *MonitorSuite) TestLaterPingFails(c *gc.C) {
	pings := 0
	s.monitor.ping = func() error {
		if pings > 0 {
			return errors.New("boom")
		}
		pings++
		return nil
	}
	go s.monitor.run()

	// Wait for the time.After in the main loop.
	for i := 0; i < 2; i++ {
		select {
		case <-s.clock.Alarms():
		case <-time.After(jjtesting.LongWait):
			c.Fatal("timed out waiting for monitor to wait")
		}
	}

	s.clock.Advance(PingPeriod)

	select {
	case <-s.broken:
	case <-time.After(jjtesting.LongWait):
		c.Fatal("timed out waiting for broken to close")
	}
}

func (s *MonitorSuite) TestPingsTimesOut(c *gc.C) {
	s.monitor.ping = func() error {
		s.clock.WaitAdvance(PingTimeout, jjtesting.LongWait, 1)
		return nil
	}
	go s.monitor.run()

	select {
	case <-s.broken:
	case <-time.After(jjtesting.LongWait):
		c.Fatal("timed out waiting for broken to close")
	}
}

func (s *MonitorSuite) TestClose(c *gc.C) {
	go s.monitor.run()

	select {
	case <-s.clock.Alarms():
	case <-time.After(jjtesting.LongWait):
		c.Fatal("timed out waiting for monitor to start")
	}

	close(s.closed)

	select {
	case <-s.broken:
	case <-time.After(jjtesting.LongWait):
		c.Fatal("timed out waiting for broken to close")
	}
}
<commit_msg>api: Use test helper for channel events<commit_after>// Copyright 2016 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.

package api

import (
	"errors"
	"time"

	"github.com/juju/testing"
	gc "gopkg.in/check.v1"

	jjtesting "github.com/juju/juju/testing"
)

var _ = gc.Suite(&MonitorSuite{})

type MonitorSuite struct {
	testing.IsolationSuite
	clock   *testing.Clock
	closed  chan (struct{})
	broken  chan (struct{})
	monitor *monitor
}

func (s *MonitorSuite) SetUpTest(c *gc.C) {
	s.IsolationSuite.SetUpTest(c)
	s.clock = testing.NewClock(time.Time{})
	s.closed = make(chan struct{})
	s.broken = make(chan struct{})
	s.monitor = &monitor{
		clock:  s.clock,
		ping:   func() error { return nil },
		closed: s.closed,
		broken: s.broken,
	}
}

func (s *MonitorSuite) TestInitialPingFails(c *gc.C) {
	s.monitor.ping = func() error { return errors.New("boom") }
	go s.monitor.run()

	assertEvent(c, s.broken)
}

func (s *MonitorSuite) TestLaterPingFails(c *gc.C) {
	pings := 0
	s.monitor.ping = func() error {
		if pings > 0 {
			return errors.New("boom")
		}
		pings++
		return nil
	}
	go s.monitor.run()

	// Wait for the time.After in the main loop.
	for i := 0; i < 2; i++ {
		assertEvent(c, s.clock.Alarms())
	}

	s.clock.Advance(PingPeriod)
	assertEvent(c, s.broken)
}

func (s *MonitorSuite) TestPingsTimesOut(c *gc.C) {
	s.monitor.ping = func() error {
		s.clock.WaitAdvance(PingTimeout, jjtesting.LongWait, 1)
		return nil
	}
	go s.monitor.run()

	assertEvent(c, s.broken)
}

func (s *MonitorSuite) TestClose(c *gc.C) {
	go s.monitor.run()
	assertEvent(c, s.clock.Alarms())
	close(s.closed)
	assertEvent(c, s.broken)
}

func assertEvent(c *gc.C, ch <-chan struct{}) {
	select {
	case <-ch:
	case <-time.After(jjtesting.LongWait):
		c.Fatal("timed out waiting for channel event")
	}
}
<|endoftext|>


<commit_before>// BaruwaAPI Golang bindings for Baruwa REST API
// Copyright (C) 2019 Andrew Colin Kissa <andrew@topdog.za.net>

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.

package api

import (
	"fmt"
	"net/url"

	"github.com/google/go-querystring/query"
)

// OrgSmartHost holds domain smarthosts
type OrgSmartHost struct {
	ID          int    `json:"id,omitempty"`
	Address     string `json:"address"`
	Username    string `json:"username"`
	Password    string `json:"password,omitempty"`
	Port        int    `json:"port"`
	RequireTLS  bool   `json:"require_tls"`
	Enabled     bool   `json:"enabled"`
	Description string `json:"description"`
}

// GetOrgSmartHost returns a domain smarthost
// https://www.baruwa.com/docs/api/#retrieve-a-organization-smarthost
func (c *Client) GetOrgSmartHost(organizationID, serverID int) (server *OrgSmartHost, err error) {
	if organizationID <= 0 {
		err = fmt.Errorf("The organizationID param should be > 0")
		return
	}

	if serverID <= 0 {
		err = fmt.Errorf("The serverID param should be > 0")
		return
	}

	err = c.get(fmt.Sprintf("organizations/smarthosts/%d/%d", organizationID, serverID), nil, server)

	return
}

// CreateOrgSmartHost creates a domain smarthost
// https://www.baruwa.com/docs/api/#create-an-organization-smarthost
func (c *Client) CreateOrgSmartHost(organizationID int, server *OrgSmartHost) (err error) {
	var v url.Values

	if organizationID <= 0 {
		err = fmt.Errorf("The organizationID param should be > 0")
		return
	}

	if server == nil {
		err = fmt.Errorf("The server param cannot be nil")
		return
	}

	if v, err = query.Values(server); err != nil {
		return
	}

	err = c.post(fmt.Sprintf("organizations/smarthosts/%d", organizationID), v, server)

	return
}

// UpdateOrgSmartHost updates a domain smarthost
// https://www.baruwa.com/docs/api/#update-a-organization-smarthost
func (c *Client) UpdateOrgSmartHost(organizationID int, server *OrgSmartHost) (err error) {
	var v url.Values

	if organizationID <= 0 {
		err = fmt.Errorf("The organizationID param should be > 0")
		return
	}

	if server == nil {
		err = fmt.Errorf("The server param cannot be nil")
		return
	}

	if server.ID <= 0 {
		err = fmt.Errorf("The server.ID param should be > 0")
		return
	}

	if v, err = query.Values(server); err != nil {
		return
	}

	err = c.put(fmt.Sprintf("organizations/smarthosts/%d/%d", organizationID, server.ID), v, server)

	return
}

// DeleteOrgSmartHost deletes a domain smarthost
// https://www.baruwa.com/docs/api/#retrieve-system-status
func (c *Client) DeleteOrgSmartHost(organizationID int, server *OrgSmartHost) (err error) {
	var v url.Values

	if organizationID <= 0 {
		err = fmt.Errorf("The organizationID param should be > 0")
		return
	}

	if server == nil {
		err = fmt.Errorf("The server param cannot be nil")
		return
	}

	if server.ID <= 0 {
		err = fmt.Errorf("The server.ID param should be > 0")
		return
	}

	if v, err = query.Values(server); err != nil {
		return
	}

	err = c.delete(fmt.Sprintf("organizations/smarthosts/%d/%d", organizationID, server.ID), v)

	return
}
<commit_msg>FET: Organization Smarthosts Implementation<commit_after>// BaruwaAPI Golang bindings for Baruwa REST API
// Copyright (C) 2019 Andrew Colin Kissa <andrew@topdog.za.net>

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.

package api

import (
	"fmt"
	"net/url"

	"github.com/google/go-querystring/query"
)

// OrgSmartHost holds domain smarthosts
type OrgSmartHost struct {
	ID          int    `json:"id,omitempty"`
	Address     string `json:"address"`
	Username    string `json:"username"`
	Password    string `json:"password,omitempty"`
	Port        int    `json:"port"`
	RequireTLS  bool   `json:"require_tls"`
	Enabled     bool   `json:"enabled"`
	Description string `json:"description"`
}

// OrgSmartHostList holds domain smarthosts
type OrgSmartHostList struct {
	Items []OrgSmartHost `json:"items"`
	Links Links          `json:"links"`
	Meta  Meta           `json:"meta"`
}

// GetOrgSmartHosts returns a OrgSmartHostList object
// This contains a paginated list of Organization smarthosts and links
// to the neigbouring pages.
// https://www.baruwa.com/docs/api/#listing-organization-smarthosts
func (c *Client) GetOrgSmartHosts(organizationID int, opts *ListOptions) (l *OrgSmartHostList, err error) {
	if organizationID <= 0 {
		err = fmt.Errorf(organizationIDError)
		return
	}

	l = &OrgSmartHostList{}

	err = c.get(fmt.Sprintf("organizations/smarthosts/%d", organizationID), opts, l)

	return
}

// GetOrgSmartHost returns a domain smarthost
// https://www.baruwa.com/docs/api/#retrieve-a-organization-smarthost
func (c *Client) GetOrgSmartHost(organizationID, serverID int) (server *OrgSmartHost, err error) {
	if organizationID <= 0 {
		err = fmt.Errorf(organizationIDError)
		return
	}

	if serverID <= 0 {
		err = fmt.Errorf(serverIDError)
		return
	}

	server = &OrgSmartHost{}

	err = c.get(fmt.Sprintf("organizations/smarthosts/%d/%d", organizationID, serverID), nil, server)

	return
}

// CreateOrgSmartHost creates a domain smarthost
// https://www.baruwa.com/docs/api/#create-an-organization-smarthost
func (c *Client) CreateOrgSmartHost(organizationID int, server *OrgSmartHost) (err error) {
	var v url.Values

	if organizationID <= 0 {
		err = fmt.Errorf(organizationIDError)
		return
	}

	if server == nil {
		err = fmt.Errorf(serverParamError)
		return
	}

	if v, err = query.Values(server); err != nil {
		return
	}

	err = c.post(fmt.Sprintf("organizations/smarthosts/%d", organizationID), v, server)

	return
}

// UpdateOrgSmartHost updates a domain smarthost
// https://www.baruwa.com/docs/api/#update-a-organization-smarthost
func (c *Client) UpdateOrgSmartHost(organizationID int, server *OrgSmartHost) (err error) {
	var v url.Values

	if organizationID <= 0 {
		err = fmt.Errorf(organizationIDError)
		return
	}

	if server == nil {
		err = fmt.Errorf(serverParamError)
		return
	}

	if server.ID <= 0 {
		err = fmt.Errorf(serverSIDError)
		return
	}

	if v, err = query.Values(server); err != nil {
		return
	}

	err = c.put(fmt.Sprintf("organizations/smarthosts/%d/%d", organizationID, server.ID), v, server)

	return
}

// DeleteOrgSmartHost deletes a domain smarthost
// https://www.baruwa.com/docs/api/#retrieve-system-status
func (c *Client) DeleteOrgSmartHost(organizationID int, server *OrgSmartHost) (err error) {
	var v url.Values

	if organizationID <= 0 {
		err = fmt.Errorf(organizationIDError)
		return
	}

	if server == nil {
		err = fmt.Errorf(serverParamError)
		return
	}

	if server.ID <= 0 {
		err = fmt.Errorf(serverSIDError)
		return
	}

	if v, err = query.Values(server); err != nil {
		return
	}

	err = c.delete(fmt.Sprintf("organizations/smarthosts/%d/%d", organizationID, server.ID), v)

	return
}
<|endoftext|>


<commit_before>package main

import (
	"archive/zip"
	"bytes"
	"flag"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path"
	"path/filepath"
	"strings"
	"time"
)

var (
	flagSrc  = flag.String("src", ".", "The path of the source directory.")
	flagDest = flag.String("dest", ".", "The destination path of the generated package.")
)

func main() {
	flag.Parse()
	file, err := createSourceFile(*flagSrc)
	if err != nil {
		exitWithError(err)
	}

	destDir := *flagDest + "/statik"
	err = os.MkdirAll(destDir, 0755)
	if err != nil {
		exitWithError(err)
	}

	err = os.Rename(file.Name(), path.Join(destDir, "data.go"))
	if err != nil {
		exitWithError(err)
	}
}

func createSourceFile(srcPath string) (file *os.File, err error) {
	var (
		buffer  bytes.Buffer
		zipdest io.Writer
	)
	zipdest = &buffer
	f, err := ioutil.TempFile("", "statik-archive")
	if err != nil {
		return
	}

	zipdest = io.MultiWriter(zipdest, f)
	defer f.Close()
	var modTime time.Time

	w := zip.NewWriter(zipdest)
	if err = filepath.Walk(srcPath, func(path string, fi os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		// Ignore empty directories and hidden files.
		if fi.IsDir() || strings.HasPrefix(fi.Name(), ".") {
			return nil
		}
		suffix, err := filepath.Rel(srcPath, path)
		if err != nil {
			return err
		}
		if mt := fi.ModTime(); mt.After(modTime) {
			modTime = mt
		}
		b, err := ioutil.ReadFile(path)
		if err != nil {
			return err
		}
		f, err := w.Create(filepath.ToSlash(suffix))
		if err != nil {
			return err
		}
		_, err = f.Write(b)
		return err
	}); err != nil {
		return
	}
	if err = w.Close(); err != nil {
		return
	}

	// then embed it as a quoted string
	var qb bytes.Buffer
	fmt.Fprint(&qb, "package statik\n\n")
	// imports
	fmt.Fprint(&qb, "import (\n")
	fmt.Fprint(&qb, "\t\"time\"\n\n")
	fmt.Fprint(&qb, "\t\"github.com/rakyll/statik/fs\"\n")
	fmt.Fprint(&qb, ")\n\n")
	// func init
	fmt.Fprint(&qb, "func init() {\n")
	fmt.Fprintf(&qb, "\tmodTime := time.Unix(%d, 0)\n", modTime.Unix())
	fmt.Fprint(&qb, "\tdata := ")
	quote(&qb, buffer.Bytes())
	fmt.Fprint(&qb, "\n\tfs.Register(modTime, data)")
	fmt.Fprint(&qb, "\n}\n")

	// Create a temp file to output the generated code
	sourceFile, err := ioutil.TempFile("", "statik-gencode")
	if err != nil {
		return
	}
	if err = ioutil.WriteFile(sourceFile.Name(), qb.Bytes(), 0644); err != nil {
		return
	}
	return sourceFile, nil
}

func quote(dest *bytes.Buffer, bs []byte) {
	dest.WriteByte('"')
	for _, b := range bs {
		if b == '\n' {
			dest.WriteString(`\n`)
			continue
		}
		if b == '\\' {
			dest.WriteString(`\\`)
			continue
		}
		if b == '"' {
			dest.WriteString(`\"`)
			continue
		}
		if (b >= 32 && b <= 126) || b == '\t' {
			dest.WriteByte(b)
			continue
		}
		fmt.Fprintf(dest, "\\x%02x", b)
	}
	dest.WriteByte('"')
}

func exitWithError(err error) {
	fmt.Println(err)
	os.Exit(1)
}
<commit_msg>Rename zipdest.<commit_after>package main

import (
	"archive/zip"
	"bytes"
	"flag"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path"
	"path/filepath"
	"strings"
	"time"
)

var (
	flagSrc  = flag.String("src", ".", "The path of the source directory.")
	flagDest = flag.String("dest", ".", "The destination path of the generated package.")
)

func main() {
	flag.Parse()
	file, err := createSourceFile(*flagSrc)
	if err != nil {
		exitWithError(err)
	}

	destDir := *flagDest + "/statik"
	err = os.MkdirAll(destDir, 0755)
	if err != nil {
		exitWithError(err)
	}

	err = os.Rename(file.Name(), path.Join(destDir, "data.go"))
	if err != nil {
		exitWithError(err)
	}
}

func createSourceFile(srcPath string) (file *os.File, err error) {
	var (
		buffer    bytes.Buffer
		zipWriter io.Writer
	)
	zipWriter = &buffer
	f, err := ioutil.TempFile("", "statik-archive")
	if err != nil {
		return
	}

	zipWriter = io.MultiWriter(zipWriter, f)
	defer f.Close()
	var modTime time.Time

	w := zip.NewWriter(zipWriter)
	if err = filepath.Walk(srcPath, func(path string, fi os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		// Ignore empty directories and hidden files.
		if fi.IsDir() || strings.HasPrefix(fi.Name(), ".") {
			return nil
		}
		suffix, err := filepath.Rel(srcPath, path)
		if err != nil {
			return err
		}
		if mt := fi.ModTime(); mt.After(modTime) {
			modTime = mt
		}
		b, err := ioutil.ReadFile(path)
		if err != nil {
			return err
		}
		f, err := w.Create(filepath.ToSlash(suffix))
		if err != nil {
			return err
		}
		_, err = f.Write(b)
		return err
	}); err != nil {
		return
	}
	if err = w.Close(); err != nil {
		return
	}

	// then embed it as a quoted string
	var qb bytes.Buffer
	fmt.Fprint(&qb, "package statik\n\n")
	// imports
	fmt.Fprint(&qb, "import (\n")
	fmt.Fprint(&qb, "\t\"time\"\n\n")
	fmt.Fprint(&qb, "\t\"github.com/rakyll/statik/fs\"\n")
	fmt.Fprint(&qb, ")\n\n")
	// func init
	fmt.Fprint(&qb, "func init() {\n")
	fmt.Fprintf(&qb, "\tmodTime := time.Unix(%d, 0)\n", modTime.Unix())
	fmt.Fprint(&qb, "\tdata := ")
	quote(&qb, buffer.Bytes())
	fmt.Fprint(&qb, "\n\tfs.Register(modTime, data)")
	fmt.Fprint(&qb, "\n}\n")

	// Create a temp file to output the generated code
	sourceFile, err := ioutil.TempFile("", "statik-gencode")
	if err != nil {
		return
	}
	if err = ioutil.WriteFile(sourceFile.Name(), qb.Bytes(), 0644); err != nil {
		return
	}
	return sourceFile, nil
}

func quote(dest *bytes.Buffer, bs []byte) {
	dest.WriteByte('"')
	for _, b := range bs {
		if b == '\n' {
			dest.WriteString(`\n`)
			continue
		}
		if b == '\\' {
			dest.WriteString(`\\`)
			continue
		}
		if b == '"' {
			dest.WriteString(`\"`)
			continue
		}
		if (b >= 32 && b <= 126) || b == '\t' {
			dest.WriteByte(b)
			continue
		}
		fmt.Fprintf(dest, "\\x%02x", b)
	}
	dest.WriteByte('"')
}

func exitWithError(err error) {
	fmt.Println(err)
	os.Exit(1)
}
<|endoftext|>


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

package prometheusexporter // import "github.com/open-telemetry/opentelemetry-collector-contrib/exporter/prometheusexporter"

import (
	"context"
	"errors"
	"net/http"
	"strings"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"go.opentelemetry.io/collector/component"
	"go.opentelemetry.io/collector/pdata/pmetric"
)

type prometheusExporter struct {
	config       Config
	name         string
	endpoint     string
	shutdownFunc func() error
	handler      http.Handler
	collector    *collector
	registry     *prometheus.Registry
	settings     component.TelemetrySettings
}

var errBlankPrometheusAddress = errors.New("expecting a non-blank address to run the Prometheus metrics handler")

func newPrometheusExporter(config *Config, set component.ExporterCreateSettings) (*prometheusExporter, error) {
	addr := strings.TrimSpace(config.Endpoint)
	if strings.TrimSpace(config.Endpoint) == "" {
		return nil, errBlankPrometheusAddress
	}

	collector := newCollector(config, set.Logger)
	registry := prometheus.NewRegistry()
	_ = registry.Register(collector)
	return &prometheusExporter{
		config:       *config,
		name:         config.ID().String(),
		endpoint:     addr,
		collector:    collector,
		registry:     registry,
		shutdownFunc: func() error { return nil },
		handler: promhttp.HandlerFor(
			registry,
			promhttp.HandlerOpts{
				ErrorHandling:     promhttp.ContinueOnError,
				ErrorLog:          newPromLogger(set.Logger),
				EnableOpenMetrics: config.EnableOpenMetrics,
			},
		),
	}, nil
}

func (pe *prometheusExporter) Start(_ context.Context, host component.Host) error {
	ln, err := pe.config.ToListener()
	if err != nil {
		return err
	}

	pe.shutdownFunc = ln.Close

	mux := http.NewServeMux()
	mux.Handle("/metrics", pe.handler)
	srv, err := pe.config.ToServer(host, pe.settings, mux)
	if err != nil {
		return err
	}
	go func() {
		_ = srv.Serve(ln)
	}()

	return nil
}

func (pe *prometheusExporter) ConsumeMetrics(_ context.Context, md pmetric.Metrics) error {
	n := 0
	rmetrics := md.ResourceMetrics()
	for i := 0; i < rmetrics.Len(); i++ {
		n += pe.collector.processMetrics(rmetrics.At(i))
	}

	return nil
}

func (pe *prometheusExporter) Shutdown(context.Context) error {
	return pe.shutdownFunc()
}
<commit_msg>[exporter/prometheus] settings were not set in prometheus exporter (#16068)<commit_after>// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package prometheusexporter // import "github.com/open-telemetry/opentelemetry-collector-contrib/exporter/prometheusexporter"

import (
	"context"
	"errors"
	"net/http"
	"strings"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"go.opentelemetry.io/collector/component"
	"go.opentelemetry.io/collector/pdata/pmetric"
)

type prometheusExporter struct {
	config       Config
	name         string
	endpoint     string
	shutdownFunc func() error
	handler      http.Handler
	collector    *collector
	registry     *prometheus.Registry
	settings     component.TelemetrySettings
}

var errBlankPrometheusAddress = errors.New("expecting a non-blank address to run the Prometheus metrics handler")

func newPrometheusExporter(config *Config, set component.ExporterCreateSettings) (*prometheusExporter, error) {
	addr := strings.TrimSpace(config.Endpoint)
	if strings.TrimSpace(config.Endpoint) == "" {
		return nil, errBlankPrometheusAddress
	}

	collector := newCollector(config, set.Logger)
	registry := prometheus.NewRegistry()
	_ = registry.Register(collector)
	return &prometheusExporter{
		config:       *config,
		name:         config.ID().String(),
		endpoint:     addr,
		collector:    collector,
		registry:     registry,
		shutdownFunc: func() error { return nil },
		handler: promhttp.HandlerFor(
			registry,
			promhttp.HandlerOpts{
				ErrorHandling:     promhttp.ContinueOnError,
				ErrorLog:          newPromLogger(set.Logger),
				EnableOpenMetrics: config.EnableOpenMetrics,
			},
		),
		settings: set.TelemetrySettings,
	}, nil
}

func (pe *prometheusExporter) Start(_ context.Context, host component.Host) error {
	ln, err := pe.config.ToListener()
	if err != nil {
		return err
	}

	pe.shutdownFunc = ln.Close

	mux := http.NewServeMux()
	mux.Handle("/metrics", pe.handler)
	srv, err := pe.config.ToServer(host, pe.settings, mux)
	if err != nil {
		return err
	}
	go func() {
		_ = srv.Serve(ln)
	}()

	return nil
}

func (pe *prometheusExporter) ConsumeMetrics(_ context.Context, md pmetric.Metrics) error {
	n := 0
	rmetrics := md.ResourceMetrics()
	for i := 0; i < rmetrics.Len(); i++ {
		n += pe.collector.processMetrics(rmetrics.At(i))
	}

	return nil
}

func (pe *prometheusExporter) Shutdown(context.Context) error {
	return pe.shutdownFunc()
}
<|endoftext|>


<commit_before>// GoAdventure!

package main

import (
	"bufio"
	"fmt"
	"os"
	//"time"
	//"math/rand"
)

func main() {

	// Game intro and reader is declared
	fmt.Println("-=GopherVenture!=-\nAn adventure game made in Go by Joaquin Padilla!\n")
	reader := bufio.NewReader(os.Stdin)

	// Game asks for name.
	fmt.Println("What is your name?")
	byteName, _, _ := reader.ReadLine()
	name := string(byteName)

	// Checks to see if you typed your name and tells name.
	// Otherwise, use fallback name "player."
	if name == "" {
		name = "player"
	}
	fmt.Printf("Alrighty, %s\n", name)

	//declare variable used to track objective
	obj := 0

	// Starting scenario is given along with the available commands
	fmt.Println("You are a gopher inside a room with the door locked. You see a key on the floor. What do you want to do?\nOptions: [open door] [pick up key]")

	// First objective is to pick up the key
	for obj == 0 {
		byteOption, _, _ := reader.ReadLine()
		option := string(byteOption)
		if option == "pick up key" {
			obj++
			fmt.Println("\nYou pick up the key from the floor with your paw.")
		} else if option == "open door" {
			fmt.Println("\nYour try to twist the knob with your paw, but it won't budge. The door is locked.")
		} else {
			fmt.Println("\nYou wonder what that means, but you can't seem to understand.")
		}
	}

	// Second objective is to open the door
	for obj == 1 {
		byteOption, _, _ := reader.ReadLine()
		option := string(byteOption)
		if option == "pick up key" {
			fmt.Println("\nYou already have the key on your paw.")
		} else if option == "open door\r\n" {
			obj++
			fmt.Println("\nYou unlock the door and twist the knob. The door opens and you exit the room.")
		} else {
			fmt.Println("\nYou wonder what that means, but you can't seem to understand.")
		}
	}

	// Third objective is to pick up the sword
	fmt.Println("You hear something approach you. You notice a sword as you look down.\nOptions: [pick up sword]")
	for obj == 2 {
		byteOption, _, _ := reader.ReadLine()
		option := string(byteOption)
		if option == "pick up sword" {
			obj++
			fmt.Println("\nYou pick up the sword with your paw. The sword feels solid.")
		} else {
			fmt.Println("\nYou wonder what that means, but you can't seem to understand.")
		}
	}

	fmt.Println("A bug approaches you! You must fight using the sword!")
	// TODO: RNG mechanic fight with monster
	//t := time.Now()
	//fmt.Println(rand.Intn(t.Nanosecond()))
	//fmt.Println(rand.Intn(t.Nanosecond()))
	//fmt.Println(rand.Intn(t.Nanosecond()))

	// Temporary ending message for end of game
	fmt.Println("You vision somehow fades and your adventure temporarily halts...\nPress Enter/Return to exit.")
	reader.ReadString('\n')

}<commit_msg>slight goofs taken care of<commit_after>// GoAdventure!

package main

import (
	"bufio"
	"fmt"
	"os"
	//"time"
	//"math/rand"
)

func main() {

	// Game intro and reader is declared
	fmt.Println("-=GopherVenture!=-\nAn adventure game made in Go by Joaquin Padilla!\n")
	reader := bufio.NewReader(os.Stdin)

	// Game asks for name.
	fmt.Println("What is your name?")
	byteName, _, _ := reader.ReadLine()
	name := string(byteName)

	// Checks to see if you typed your name and tells name.
	// Otherwise, use fallback name "player."
	if name == "" {
		name = "player"
	}
	fmt.Printf("\nAlrighty, %s.\n", name)

	//declare variable used to track objective
	obj := 0

	// Starting scenario is given along with the available commands
	fmt.Println("You are a gopher inside a room with the door locked. You see a key on the floor. What do you want to do?\nOptions: [open door] [pick up key]")

	// First objective is to pick up the key
	for obj == 0 {
		byteOption, _, _ := reader.ReadLine()
		option := string(byteOption)
		if option == "pick up key" {
			obj++
			fmt.Println("\nYou pick up the key from the floor with your paw.")
		} else if option == "open door" {
			fmt.Println("\nYour try to twist the knob with your paw, but it won't budge. The door is locked.")
		} else {
			fmt.Println("\nYou wonder what that means, but you can't seem to understand.")
		}
	}

	// Second objective is to open the door
	for obj == 1 {
		byteOption, _, _ := reader.ReadLine()
		option := string(byteOption)
		if option == "pick up key" {
			fmt.Println("\nYou already have the key on your paw.")
		} else if option == "open door" {
			obj++
			fmt.Println("\nYou unlock the door and twist the knob. The door opens and you exit the room.")
		} else {
			fmt.Println("\nYou wonder what that means, but you can't seem to understand.")
		}
	}

	// Third objective is to pick up the sword
	fmt.Println("You hear something approach you. You notice a sword as you look down.\nOptions: [pick up sword]")
	for obj == 2 {
		byteOption, _, _ := reader.ReadLine()
		option := string(byteOption)
		if option == "pick up sword" {
			obj++
			fmt.Println("\nYou pick up the sword with your paw. The sword feels solid.")
		} else {
			fmt.Println("\nYou wonder what that means, but you can't seem to understand.")
		}
	}

	fmt.Println("A bug approaches you! You must fight using the sword!")
	// TODO: RNG mechanic fight with monster
	//t := time.Now()
	//fmt.Println(rand.Intn(t.Nanosecond()))
	//fmt.Println(rand.Intn(t.Nanosecond()))
	//fmt.Println(rand.Intn(t.Nanosecond()))

	// Temporary ending message for end of game
	fmt.Println("You vision somehow fades and your adventure temporarily halts...\nPress Enter/Return to exit.")
	reader.ReadString('\n')

}<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"log"
	"os"
	"strconv"
	"time"

	"github.com/centrifugal/centrifugo/libcentrifugo/auth"
	"golang.org/x/net/websocket"
)

func subscriber(numChannels int, chSub chan struct{}, url, origin, connectMessage string) {
	var err error
	var ws *websocket.Conn
	for {
		ws, err = websocket.Dial(url, "", origin)
		if err != nil {
			time.Sleep(10 * time.Millisecond)
			continue
		}
		break
	}
	if _, err := ws.Write([]byte(connectMessage)); err != nil {
		fmt.Println("subscriber connect write error")
		log.Fatal(err)
	}
	var msg = make([]byte, 512)

	if _, err = ws.Read(msg); err != nil {
		fmt.Println("subscriber connect read error")
		log.Fatal(err)
	}

	for i := 1; i <= numChannels; i++ {
		channel := fmt.Sprintf("channel%d", i)
		subscribeMessage := "{\"params\": {\"channel\": \"" + channel + "\"}, \"method\": \"subscribe\"}"
		if _, err := ws.Write([]byte(subscribeMessage)); err != nil {
			fmt.Println("subscriber subscribe write error")
			log.Fatal(err)
		}
		if _, err = ws.Read(msg); err != nil {
			fmt.Println("subscriber subscribe read error")
			log.Fatal(err)
		}
	}

	close(chSub)

	for {
		if _, err = ws.Read(msg); err != nil {
			fmt.Println("subscriber msg read error")
			log.Fatal(err)
		}
	}
}

func main() {

	origin := "http://localhost:8000/"
	url := os.Args[1]
	secret := os.Args[2]
	clients, _ := strconv.Atoi(os.Args[3])
	var numChannels = 1
	if len(os.Args) > 4 {
		numChannels, _ = strconv.Atoi(os.Args[4])
	}

	fmt.Printf("clients: %d\nchannels: %d\n", clients, numChannels)

	timestamp := strconv.FormatInt(time.Now().Unix(), 10)
	token := auth.GenerateClientToken(secret, "test", timestamp, "")
	connectMessage := fmt.Sprintf("{\"params\": {\"timestamp\": \"%s\", \"token\": \"%s\", \"user\": \"test\"}, \"method\": \"connect\"}", timestamp, token)
	done := make(chan struct{})

	for i := 0; i < clients; i += 1 {
		chSub := make(chan struct{})
		go subscriber(numChannels, chSub, url, origin, connectMessage)
		<-chSub
		fmt.Printf("\r%d", i+1)
	}

	// Just run until interrupted keeping connections open.
	<-done
}
<commit_msg>connect faster<commit_after>package main

import (
	"fmt"
	"log"
	"os"
	"strconv"
	"sync"
	"time"

	"github.com/centrifugal/centrifugo/libcentrifugo/auth"
	"golang.org/x/net/websocket"
)

func subscriber(numChannels int, chSub chan struct{}, url, origin, connectMessage string) {
	var err error
	var ws *websocket.Conn
	for {
		ws, err = websocket.Dial(url, "", origin)
		if err != nil {
			time.Sleep(10 * time.Millisecond)
			continue
		}
		break
	}
	if _, err := ws.Write([]byte(connectMessage)); err != nil {
		fmt.Println("subscriber connect write error")
		log.Fatal(err)
	}
	var msg = make([]byte, 512)

	if _, err = ws.Read(msg); err != nil {
		fmt.Println("subscriber connect read error")
		log.Fatal(err)
	}

	for i := 1; i <= numChannels; i++ {
		channel := fmt.Sprintf("channel%d", i)
		subscribeMessage := "{\"params\": {\"channel\": \"" + channel + "\"}, \"method\": \"subscribe\"}"
		if _, err := ws.Write([]byte(subscribeMessage)); err != nil {
			fmt.Println("subscriber subscribe write error")
			log.Fatal(err)
		}
		if _, err = ws.Read(msg); err != nil {
			fmt.Println("subscriber subscribe read error")
			log.Fatal(err)
		}
	}

	close(chSub)

	for {
		if _, err = ws.Read(msg); err != nil {
			fmt.Println("subscriber msg read error")
			log.Fatal(err)
		}
	}
}

func main() {

	origin := "http://localhost:8000/"
	url := os.Args[1]
	secret := os.Args[2]
	clients, _ := strconv.Atoi(os.Args[3])
	var numChannels = 1
	if len(os.Args) > 4 {
		numChannels, _ = strconv.Atoi(os.Args[4])
	}

	fmt.Printf("clients: %d\nchannels: %d\n", clients, numChannels)

	timestamp := strconv.FormatInt(time.Now().Unix(), 10)
	token := auth.GenerateClientToken(secret, "test", timestamp, "")
	connectMessage := fmt.Sprintf("{\"params\": {\"timestamp\": \"%s\", \"token\": \"%s\", \"user\": \"test\"}, \"method\": \"connect\"}", timestamp, token)

	var mu sync.Mutex
	var wg sync.WaitGroup
	sem := make(chan struct{}, 10)
	connected := 0

	for i := 0; i < clients; i += 1 {
		wg.Add(1)
		go func() {
			defer wg.Done()
			sem <- struct{}{}
			defer func() { <-sem }()
			chSub := make(chan struct{})
			go subscriber(numChannels, chSub, url, origin, connectMessage)
			<-chSub
			mu.Lock()
			connected += 1
			fmt.Printf("\r%d", connected)
			mu.Unlock()
		}()

	}

	wg.Wait()

	// Just run until interrupted keeping connections open.
	select {}
}
<|endoftext|>


<commit_before>package ali

import (
	"crypto"
	"crypto/rsa"
	"crypto/x509"
	"encoding/base64"
	"encoding/json"
	"encoding/pem"
	"fmt"
	"net/url"
	"sort"
	"strings"
	"time"
)

func urlValues(c *Client, param PayParam) url.Values {
	values := url.Values{}
	values.Add("app_id", c.config.AppID)
	values.Add("method", param.URI())
	values.Add("format", "JSON")
	values.Add("charset", "utf-8")
	values.Add("sign_type", c.config.SignType)
	values.Add("timestamp", generateTimestampStr())
	values.Add("version", "1.0")
	values.Add("biz_content", param.BizContent())

	for k, v := range param.ExtraParams() {
		values.Add(k, v)
	}

	var keys []string
	for k := range values {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	values.Add("sign", signature(keys, values, c.config.AppPrivateKey, c.config.SignType))
	return values
}

func signature(keys []string, values url.Values, privateKey []byte, signType string) string {
	if values == nil {
		values = url.Values{}
	}

	var valueList []string
	for _, k := range keys {
		v := strings.TrimSpace(values.Get(k))
		if v != "" {
			valueList = append(valueList, fmt.Sprintf("%s=%s", k, v))
		}
	}

	concat := strings.Join(valueList, "&")

	var sign string
	if signType == "RSA" {
		sign = signPKCS1v15([]byte(concat), privateKey, crypto.SHA1)
	} else if signType == "RSA2" {
		sign = signPKCS1v15([]byte(concat), privateKey, crypto.SHA256)
	}
	return sign
}

func signPKCS1v15(source, privateKey []byte, hash crypto.Hash) string {
	block, _ := pem.Decode(privateKey)
	if block == nil {
		return ""
	}

	rsaPrivateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return ""
	}

	h := hash.New()
	h.Write(source)
	hashed := h.Sum(nil)

	s, err := rsa.SignPKCS1v15(nil, rsaPrivateKey, hash, hashed)
	if err != nil {
		return ""
	}
	return base64.StdEncoding.EncodeToString(s)
}

func verify(values url.Values, publicKey []byte, signType string) bool {
	decoded, err := base64.StdEncoding.DecodeString(values.Get("sign"))
	if err != nil {
		return false
	}

	var excluded []string
	for k, v := range values {
		if k == "sign" || k == "sign_type" {
			continue
		}
		if len(v) > 0 {
			excluded = append(excluded, k)
		}
	}

	sort.Strings(excluded)

	var valueList []string
	for _, k := range excluded {
		v := strings.TrimSpace(values.Get(k))
		if v != "" {
			valueList = append(valueList, fmt.Sprintf("%s=%s", k, v))
		}
	}
	concat := strings.Join(valueList, "&")

	var ok bool
	if signType == "RSA" {
		ok = verifyPKCS1v15([]byte(concat), decoded, publicKey, crypto.SHA1)
	} else if signType == "RSA2" {
		ok = verifyPKCS1v15([]byte(concat), decoded, publicKey, crypto.SHA256)
	}
	return ok
}

func verifyPKCS1v15(source, sign, publicKey []byte, hash crypto.Hash) bool {
	h := hash.New()
	h.Write(source)
	hashed := h.Sum(nil)

	block, _ := pem.Decode(publicKey)
	if block == nil {
		return false
	}

	pub, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return false
	}

	rsaPublicKey := pub.(*rsa.PublicKey)
	err = rsa.VerifyPKCS1v15(rsaPublicKey, hash, hashed, sign)
	if err != nil {
		return false
	}
	return true
}

func generateTimestampStr() string {
	now := time.Now()
	year, month, day := now.Date()
	hour, min, sec := now.Clock()
	return fmt.Sprintf("%d-%02d-%02d %02d:%02d:%02d", year, month, day, hour, min, sec)
}

func marshalJSON(val interface{}) string {
	data, err := json.Marshal(val)
	if err != nil {
		return ""
	}
	return string(data)
}
<commit_msg>add log to debug<commit_after>package ali

import (
	"crypto"
	"crypto/rsa"
	"crypto/x509"
	"encoding/base64"
	"encoding/json"
	"encoding/pem"
	"fmt"
	"net/url"
	"sort"
	"strings"
	"time"
)

func urlValues(c *Client, param PayParam) url.Values {
	values := url.Values{}
	values.Add("app_id", c.config.AppID)
	values.Add("method", param.URI())
	values.Add("format", "JSON")
	values.Add("charset", "utf-8")
	values.Add("sign_type", c.config.SignType)
	values.Add("timestamp", generateTimestampStr())
	values.Add("version", "1.0")
	values.Add("biz_content", param.BizContent())

	for k, v := range param.ExtraParams() {
		values.Add(k, v)
	}

	var keys []string
	for k := range values {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	values.Add("sign", signature(keys, values, c.config.AppPrivateKey, c.config.SignType))
	fmt.Printf("SIGN %#v\n", values)
	return values
}

func signature(keys []string, values url.Values, privateKey []byte, signType string) string {
	if values == nil {
		values = url.Values{}
	}

	var valueList []string
	for _, k := range keys {
		v := strings.TrimSpace(values.Get(k))
		if v != "" {
			valueList = append(valueList, fmt.Sprintf("%s=%s", k, v))
		}
	}

	concat := strings.Join(valueList, "&")

	var sign string
	if signType == "RSA" {
		sign = signPKCS1v15([]byte(concat), privateKey, crypto.SHA1)
	} else if signType == "RSA2" {
		sign = signPKCS1v15([]byte(concat), privateKey, crypto.SHA256)
	}
	return sign
}

func signPKCS1v15(source, privateKey []byte, hash crypto.Hash) string {
	block, _ := pem.Decode(privateKey)
	if block == nil {
		return ""
	}

	rsaPrivateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return ""
	}

	h := hash.New()
	h.Write(source)
	hashed := h.Sum(nil)

	s, err := rsa.SignPKCS1v15(nil, rsaPrivateKey, hash, hashed)
	if err != nil {
		return ""
	}
	return base64.StdEncoding.EncodeToString(s)
}

func verify(values url.Values, publicKey []byte, signType string) bool {
	decoded, err := base64.StdEncoding.DecodeString(values.Get("sign"))
	if err != nil {
		return false
	}

	var excluded []string
	for k, v := range values {
		if k == "sign" || k == "sign_type" {
			continue
		}
		if len(v) > 0 {
			excluded = append(excluded, k)
		}
	}

	sort.Strings(excluded)

	var valueList []string
	for _, k := range excluded {
		v := strings.TrimSpace(values.Get(k))
		if v != "" {
			valueList = append(valueList, fmt.Sprintf("%s=%s", k, v))
		}
	}
	concat := strings.Join(valueList, "&")

	var ok bool
	if signType == "RSA" {
		ok = verifyPKCS1v15([]byte(concat), decoded, publicKey, crypto.SHA1)
	} else if signType == "RSA2" {
		ok = verifyPKCS1v15([]byte(concat), decoded, publicKey, crypto.SHA256)
	}
	return ok
}

func verifyPKCS1v15(source, sign, publicKey []byte, hash crypto.Hash) bool {
	h := hash.New()
	h.Write(source)
	hashed := h.Sum(nil)

	block, _ := pem.Decode(publicKey)
	if block == nil {
		return false
	}

	pub, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return false
	}

	rsaPublicKey := pub.(*rsa.PublicKey)
	err = rsa.VerifyPKCS1v15(rsaPublicKey, hash, hashed, sign)
	if err != nil {
		return false
	}
	return true
}

func generateTimestampStr() string {
	now := time.Now()
	year, month, day := now.Date()
	hour, min, sec := now.Clock()
	return fmt.Sprintf("%d-%02d-%02d %02d:%02d:%02d", year, month, day, hour, min, sec)
}

func marshalJSON(val interface{}) string {
	data, err := json.Marshal(val)
	if err != nil {
		return ""
	}
	return string(data)
}
<|endoftext|>


<commit_before>package main

import (
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

// ClientRequest TODO
type ClientRequest struct {
	Timestamp    time.Time `orm:"pk;column(timestamp);type(datetime)"`
	IP           string    `orm:"pk;column(ip)"`
	URL          string    `orm:"column(url)"`
	UserAgent    string    `orm:"column(user-agent)"`
	Referer      string
	HTTPCode     int           `orm:"column(httpcode)"`
	ResponseTime time.Duration `orm:"column(reponse-time)"`
}

/*
// TableUnique returns columns that should be unique
func (c *ClientRequest) TableUnique() [][]string {
	return [][]string{
		[]string{"ip"},
	}
}
*/

// Analytics TODO
func Analytics(c *gin.Context) {
	// Get the current time
	then := time.Now()

	// Let the rest of the request happen
	c.Next()

	clientip := c.Request.Header.Get("X-Forwarded-For")
	if clientip == "" {
		clientip = c.Request.RemoteAddr
	}
	clientipparts := strings.Split(clientip, ":")
	clientip = clientipparts[0]

	// Build our client request record
	cr := ClientRequest{
		Timestamp:    time.Now(),
		UserAgent:    c.Request.UserAgent(),
		IP:           clientip,
		URL:          c.Request.RequestURI,
		Referer:      c.Request.Referer(),
		HTTPCode:     c.Writer.Status(),
		ResponseTime: time.Since(then),
	}
	// log this to the database
	orm.Insert(cr)
}
<commit_msg>ORM interaction must be in this format now<commit_after>package main

import (
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

// ClientRequest TODO
type ClientRequest struct {
	Timestamp    time.Time `orm:"pk;column(timestamp);type(datetime)"`
	IP           string    `orm:"pk;column(ip)"`
	URL          string    `orm:"column(url)"`
	UserAgent    string    `orm:"column(user-agent)"`
	Referer      string
	HTTPCode     int           `orm:"column(httpcode)"`
	ResponseTime time.Duration `orm:"column(reponse-time)"`
}

/*
// TableUnique returns columns that should be unique
func (c *ClientRequest) TableUnique() [][]string {
	return [][]string{
		[]string{"ip"},
	}
}
*/

// Analytics TODO
func Analytics(c *gin.Context) {
	// Get the current time
	then := time.Now()

	// Let the rest of the request happen
	c.Next()

	clientip := c.Request.Header.Get("X-Forwarded-For")
	if clientip == "" {
		clientip = c.Request.RemoteAddr
	}
	clientipparts := strings.Split(clientip, ":")
	clientip = clientipparts[0]

	// Build our client request record
	cr := new(ClientRequest)
	cr.Timestamp = time.Now()
	cr.UserAgent = c.Request.UserAgent()
	cr.IP = clientip
	cr.URL = c.Request.RequestURI
	cr.Referer = c.Request.Referer()
	cr.HTTPCode = c.Writer.Status()
	cr.ResponseTime = time.Since(then)
	// log this to the database
	orm.Insert(cr)
}
<|endoftext|>


<commit_before>package impl

import (
	"v2ray.com/core/app"
	"v2ray.com/core/app/dispatcher"
	"v2ray.com/core/app/proxyman"
	"v2ray.com/core/app/router"
	"v2ray.com/core/common/buf"
	"v2ray.com/core/common/errors"
	"v2ray.com/core/common/log"
	v2net "v2ray.com/core/common/net"
	"v2ray.com/core/common/serial"
	"v2ray.com/core/proxy"
	"v2ray.com/core/transport/ray"
)

type DefaultDispatcher struct {
	ohm    proxyman.OutboundHandlerManager
	router *router.Router
}

func NewDefaultDispatcher(space app.Space) *DefaultDispatcher {
	d := &DefaultDispatcher{}
	space.InitializeApplication(func() error {
		return d.Initialize(space)
	})
	return d
}

// Private: Used by app.Space only.
func (v *DefaultDispatcher) Initialize(space app.Space) error {
	if !space.HasApp(proxyman.APP_ID_OUTBOUND_MANAGER) {
		return errors.New("DefaultDispatcher: OutboundHandlerManager is not found in the space.")
	}
	v.ohm = space.GetApp(proxyman.APP_ID_OUTBOUND_MANAGER).(proxyman.OutboundHandlerManager)

	if space.HasApp(router.APP_ID) {
		v.router = space.GetApp(router.APP_ID).(*router.Router)
	}

	return nil
}

func (v *DefaultDispatcher) Release() {

}

func (v *DefaultDispatcher) DispatchToOutbound(session *proxy.SessionInfo) ray.InboundRay {
	direct := ray.NewRay()
	dispatcher := v.ohm.GetDefaultHandler()
	destination := session.Destination

	if v.router != nil {
		if tag, err := v.router.TakeDetour(session); err == nil {
			if handler := v.ohm.GetHandler(tag); handler != nil {
				log.Info("DefaultDispatcher: Taking detour [", tag, "] for [", destination, "].")
				dispatcher = handler
			} else {
				log.Warning("DefaultDispatcher: Nonexisting tag: ", tag)
			}
		} else {
			log.Info("DefaultDispatcher: Default route for ", destination)
		}
	}

	if session.Inbound != nil && session.Inbound.AllowPassiveConnection {
		go dispatcher.Dispatch(destination, buf.NewLocal(32), direct)
	} else {
		go v.FilterPacketAndDispatch(destination, direct, dispatcher)
	}

	return direct
}

// Private: Visible for testing.
func (v *DefaultDispatcher) FilterPacketAndDispatch(destination v2net.Destination, link ray.OutboundRay, dispatcher proxy.OutboundHandler) {
	payload, err := link.OutboundInput().Read()
	if err != nil {
		log.Info("DefaultDispatcher: No payload towards ", destination, ", stopping now.")
		link.OutboundInput().Release()
		link.OutboundOutput().Release()
		return
	}
	dispatcher.Dispatch(destination, payload, link)
}

type DefaultDispatcherFactory struct{}

func (v DefaultDispatcherFactory) Create(space app.Space, config interface{}) (app.Application, error) {
	return NewDefaultDispatcher(space), nil
}

func (v DefaultDispatcherFactory) AppId() app.ID {
	return dispatcher.APP_ID
}

func init() {
	app.RegisterApplicationFactory(serial.GetMessageType(new(dispatcher.Config)), DefaultDispatcherFactory{})
}
<commit_msg>comments<commit_after>package impl

import (
	"v2ray.com/core/app"
	"v2ray.com/core/app/dispatcher"
	"v2ray.com/core/app/proxyman"
	"v2ray.com/core/app/router"
	"v2ray.com/core/common/buf"
	"v2ray.com/core/common/errors"
	"v2ray.com/core/common/log"
	v2net "v2ray.com/core/common/net"
	"v2ray.com/core/common/serial"
	"v2ray.com/core/proxy"
	"v2ray.com/core/transport/ray"
)

type DefaultDispatcher struct {
	ohm    proxyman.OutboundHandlerManager
	router *router.Router
}

func NewDefaultDispatcher(space app.Space) *DefaultDispatcher {
	d := &DefaultDispatcher{}
	space.InitializeApplication(func() error {
		return d.Initialize(space)
	})
	return d
}

// Private: Used by app.Space only.
func (v *DefaultDispatcher) Initialize(space app.Space) error {
	if !space.HasApp(proxyman.APP_ID_OUTBOUND_MANAGER) {
		return errors.New("DefaultDispatcher: OutboundHandlerManager is not found in the space.")
	}
	v.ohm = space.GetApp(proxyman.APP_ID_OUTBOUND_MANAGER).(proxyman.OutboundHandlerManager)

	if space.HasApp(router.APP_ID) {
		v.router = space.GetApp(router.APP_ID).(*router.Router)
	}

	return nil
}

func (v *DefaultDispatcher) Release() {

}

func (v *DefaultDispatcher) DispatchToOutbound(session *proxy.SessionInfo) ray.InboundRay {
	direct := ray.NewRay()
	dispatcher := v.ohm.GetDefaultHandler()
	destination := session.Destination

	if v.router != nil {
		if tag, err := v.router.TakeDetour(session); err == nil {
			if handler := v.ohm.GetHandler(tag); handler != nil {
				log.Info("DefaultDispatcher: Taking detour [", tag, "] for [", destination, "].")
				dispatcher = handler
			} else {
				log.Warning("DefaultDispatcher: Nonexisting tag: ", tag)
			}
		} else {
			log.Info("DefaultDispatcher: Default route for ", destination)
		}
	}

	if session.Inbound != nil && session.Inbound.AllowPassiveConnection {
		go dispatcher.Dispatch(destination, buf.NewLocal(32), direct)
	} else {
		go v.FilterPacketAndDispatch(destination, direct, dispatcher)
	}

	return direct
}

// FilterPacketAndDispatch waits for a payload from source and starts dispatching.
// Private: Visible for testing.
func (v *DefaultDispatcher) FilterPacketAndDispatch(destination v2net.Destination, link ray.OutboundRay, dispatcher proxy.OutboundHandler) {
	payload, err := link.OutboundInput().Read()
	if err != nil {
		log.Info("DefaultDispatcher: No payload towards ", destination, ", stopping now.")
		link.OutboundInput().Release()
		link.OutboundOutput().Release()
		return
	}
	dispatcher.Dispatch(destination, payload, link)
}

type DefaultDispatcherFactory struct{}

func (v DefaultDispatcherFactory) Create(space app.Space, config interface{}) (app.Application, error) {
	return NewDefaultDispatcher(space), nil
}

func (v DefaultDispatcherFactory) AppId() app.ID {
	return dispatcher.APP_ID
}

func init() {
	app.RegisterApplicationFactory(serial.GetMessageType(new(dispatcher.Config)), DefaultDispatcherFactory{})
}
<|endoftext|>


<commit_before>package bh1750

import (
	"github.com/explicite/i2c/driver"
	"time"
)

const (
	// ADDR ≦ 0.3VCC
	AddrL = 0x23

	// ADDR ≧ 0.7VCC
	AddrH = 0x5c

	// No active state.
	PowerDown = 0x00

	// Waiting for measurement command.
	PowerOn = 0x01

	// Reset Data register value. Reset command is not acceptable in Power Down mode.
	Reset = 0x07

	// Start measurement at 1lx resolution. Measurement Time is typically 120ms.
	ConHRes1lx = 0x10

	// Start measurement at 0.5lx resolution. Measurement Time is typically 120ms.
	ConHRes05lx = 0x11

	// Start measurement at 4lx resolution. Measurement Time is typically 16ms.
	ConLRes4lx = 0x13

	// Start measurement at 1lx resolution. Measurement Time is typically 120ms.
	// It is automatically set to Power Down mode after measurement.
	OtHRes1lx = 0x20

	// Start measurement at 0.5lx resolution. Measurement Time is typically 120ms.
	// It is automatically set to Power Down mode after measurement.
	OtHRes05lx = 0x21

	// Start measurement at 4lx resolution. Measurement Time is typically 16ms.
	// It is automatically set to Power Down mode after measurement.
	OtLRes4lx = 0x23

	// 20ms for safety time margine in measurement.
	Stm = 20 * time.Millisecond
)

// Map of timeouts for measurement type.
var timeout = map[byte]time.Duration{
	ConHRes1lx:  120*time.Millisecond + Stm,
	ConHRes05lx: 120*time.Millisecond + Stm,
	ConLRes4lx:  16*time.Millisecond + Stm,
	OtHRes1lx:   120*time.Millisecond + Stm,
	OtHRes05lx:  120*time.Millisecond + Stm,
	OtLRes4lx:   16*time.Millisecond + Stm,
}

type BH1750 struct{ driver.Driver }

func (b *BH1750) Init(addr byte, bus byte) error {
	return b.Load(addr, bus)
}

func (b *BH1750) Lux(mode byte) (float32, error) {
	b.Write(mode, 0x00)
	time.Sleep(timeout[mode])
	buf := make([]byte, 0x02)
	var err error
	buf, err = b.Read(mode, 0x02)

	if err != nil {
		return 0, err
	}

	return float32((int(buf[1]) + (int(buf[0]) >> 8))) / 1.2, nil
}

func (b *BH1750) Active() error {
	return b.On()
}

func (b *BH1750) Deactive() error {
	return b.Off()
}
<commit_msg>bh1750 influx db api<commit_after>package bh1750

import (
	"github.com/explicite/i2c/driver"
	"time"
)

const (
	// ADDR ≦ 0.3VCC
	AddrL = 0x23

	// ADDR ≧ 0.7VCC
	AddrH = 0x5c

	// No active state.
	PowerDown = 0x00

	// Waiting for measurement command.
	PowerOn = 0x01

	// Reset Data register value. Reset command is not acceptable in Power Down mode.
	Reset = 0x07

	// Start measurement at 1lx resolution. Measurement Time is typically 120ms.
	ConHRes1lx = 0x10

	// Start measurement at 0.5lx resolution. Measurement Time is typically 120ms.
	ConHRes05lx = 0x11

	// Start measurement at 4lx resolution. Measurement Time is typically 16ms.
	ConLRes4lx = 0x13

	// Start measurement at 1lx resolution. Measurement Time is typically 120ms.
	// It is automatically set to Power Down mode after measurement.
	OtHRes1lx = 0x20

	// Start measurement at 0.5lx resolution. Measurement Time is typically 120ms.
	// It is automatically set to Power Down mode after measurement.
	OtHRes05lx = 0x21

	// Start measurement at 4lx resolution. Measurement Time is typically 16ms.
	// It is automatically set to Power Down mode after measurement.
	OtLRes4lx = 0x23

	// 20ms for safety time margine in measurement.
	Stm = 20 * time.Millisecond
)

// Map of timeouts for measurement type.
var timeout = map[byte]time.Duration{
	ConHRes1lx:  120*time.Millisecond + Stm,
	ConHRes05lx: 120*time.Millisecond + Stm,
	ConLRes4lx:  16*time.Millisecond + Stm,
	OtHRes1lx:   120*time.Millisecond + Stm,
	OtHRes05lx:  120*time.Millisecond + Stm,
	OtLRes4lx:   16*time.Millisecond + Stm,
}

type BH1750 struct{ driver.Driver }

func (b *BH1750) Init(addr byte, bus byte) error {
	return b.Load(addr, bus)
}

func (b *BH1750) Illuminance(mode byte) (float32, error) {
	b.Write(mode, 0x00)
	time.Sleep(timeout[mode])
	buf := make([]byte, 0x02)
	var err error
	buf, err = b.Read(mode, 0x02)

	if err != nil {
		return 0, err
	}

	return float32((int(buf[1]) + (int(buf[0]) >> 8))) / 1.2, nil
}

func (b *BH1750) Active() error {
	return b.On()
}

func (b *BH1750) Deactive() error {
	return b.Off()
}
<|endoftext|>


<commit_before>// Copyright 2017 King Qiu.  All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
// https://github.com/qjw/kelly

package binding

import (
	"gopkg.in/go-playground/validator.v9"
	"reflect"
	"sync"
)

type defaultValidator struct {
	once     sync.Once
	validate *validator.Validate
}

var _ StructValidator = &defaultValidator{}

func (v *defaultValidator) ValidateStruct(obj interface{}) error {
	if kindOfData(obj) == reflect.Struct {
		v.lazyinit()
		if err := v.validate.Struct(obj); err != nil {
			return error(err)
		}
	}
	return nil
}

/*
func isAlpha(ctx context.Context, fl validator.FieldLevel) bool {
	alphaRegex := regexp.MustCompile("^[0-9]{4}-[0-9]{2}-[0-9]{2}$")
	return alphaRegex.MatchString(fl.Field().String())
}
*/

func (v *defaultValidator) lazyinit() {
	v.once.Do(func() {
		// config := &validator.Config{TagName: "binding"}
		// v.validate = validator.New(config)
		v.validate = validator.New()
		v.validate.SetTagName("binding")
		// v.validate.RegisterValidationCtx("date", isAlpha)
	})
}

func kindOfData(data interface{}) reflect.Kind {
	value := reflect.ValueOf(data)
	valueType := value.Kind()
	if valueType == reflect.Ptr {
		valueType = value.Elem().Kind()
	}
	return valueType
}
<commit_msg>扩展校验(date/datetime)<commit_after>// Copyright 2017 King Qiu.  All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
// https://github.com/qjw/kelly

package binding

import (
	"context"
	"reflect"
	"regexp"
	"sync"

	"gopkg.in/go-playground/validator.v9"
)

type defaultValidator struct {
	once     sync.Once
	validate *validator.Validate
}

var _ StructValidator = &defaultValidator{}

func (v *defaultValidator) ValidateStruct(obj interface{}) error {
	if kindOfData(obj) == reflect.Struct {
		v.lazyinit()
		if err := v.validate.Struct(obj); err != nil {
			return error(err)
		}
	}
	return nil
}

func isDate(ctx context.Context, fl validator.FieldLevel) bool {
	alphaRegex := regexp.MustCompile("^[0-9]{4}-[0-9]{2}-[0-9]{2}$")
	return alphaRegex.MatchString(fl.Field().String())
}

func isDatetime(ctx context.Context, fl validator.FieldLevel) bool {
	alphaRegex := regexp.MustCompile("^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$")
	return alphaRegex.MatchString(fl.Field().String())
}

func (v *defaultValidator) lazyinit() {
	v.once.Do(func() {
		// config := &validator.Config{TagName: "binding"}
		// v.validate = validator.New(config)
		v.validate = validator.New()
		v.validate.SetTagName("binding")
		v.validate.RegisterValidationCtx("date", isDate)
		v.validate.RegisterValidationCtx("datetime", isDatetime)
	})
}

func kindOfData(data interface{}) reflect.Kind {
	value := reflect.ValueOf(data)
	valueType := value.Kind()
	if valueType == reflect.Ptr {
		valueType = value.Elem().Kind()
	}
	return valueType
}
<|endoftext|>


<commit_before>package httptests

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"net/url"
	"reflect"
	"strconv"
	"testing"

	"strings"

	"github.com/Nivl/go-rest-tools/router"
	"github.com/gorilla/mux"
)

// DefaultRouter represents the router to be used if none are specified
var DefaultRouter *mux.Router

// RequestAuth represents the auth data for a request
type RequestAuth struct {
	SessionID string
	UserID    string
}

// ToBasicAuth returns the data using the basic auth format
func (ra *RequestAuth) ToBasicAuth() string {
	authValue := fmt.Sprintf("%s:%s", ra.UserID, ra.SessionID)

	encoded := base64.StdEncoding.EncodeToString([]byte(authValue))
	return "basic " + encoded
}

// NewRequestAuth creates a new
func NewRequestAuth(sessionID string, userID string) *RequestAuth {
	return &RequestAuth{
		SessionID: sessionID,
		UserID:    userID,
	}
}

// RequestInfo represents the params accepted by NewRequest
type RequestInfo struct {
	Endpoint *router.Endpoint

	Params interface{}  // Optional
	Auth   *RequestAuth // Optional
	// Router is used to parse Mux Variables. Default on the api router
	Router *mux.Router

	urlParams   map[string]string
	bodyParams  map[string]string
	queryParams map[string]string
}

// ParseParams parses the params and copy them in the right list:
// urlParams, bodyParams, and queryParams
func (ri *RequestInfo) ParseParams() {
	ri.urlParams = map[string]string{}
	ri.bodyParams = map[string]string{}
	ri.queryParams = map[string]string{}

	if ri.Params == nil {
		return
	}

	params := reflect.ValueOf(ri.Params)
	if params.Kind() == reflect.Ptr {
		params = params.Elem()
	}
	ri.parseParamsRecursive(params)
}

func (ri *RequestInfo) parseParamsRecursive(params reflect.Value) {
	nbParams := params.NumField()
	for i := 0; i < nbParams; i++ {
		param := params.Field(i)
		paramInfo := params.Type().Field(i)
		tags := paramInfo.Tag

		if param.Kind() == reflect.Ptr {
			param = param.Elem()
		}

		// Handle embeded struct
		if param.Kind() == reflect.Struct && paramInfo.Anonymous {
			ri.parseParamsRecursive(param)
			continue
		}

		// We get the Value
		value := ""
		switch param.Kind() {
		case reflect.Bool:
			value = strconv.FormatBool(param.Bool())
		case reflect.String:
			value = param.String()
		case reflect.Int:
			value = strconv.Itoa(int(param.Int()))
		case reflect.Ptr:
			if !param.IsNil() {
				val := param.Elem()
				switch val.Kind() {
				case reflect.Bool:
					value = strconv.FormatBool(val.Bool())
				case reflect.String:
					value = param.String()
				case reflect.Int:
					value = strconv.Itoa(int(val.Int()))
				}
			}
		}

		// We get the name from the json tag
		fieldName := ""
		jsonOpts := strings.Split(tags.Get("json"), ",")
		if len(jsonOpts) > 0 {
			if jsonOpts[0] == "-" {
				continue
			}
			fieldName = jsonOpts[0]
		}

		switch strings.ToLower(tags.Get("from")) {
		case "url":
			ri.urlParams[fieldName] = value
		case "form":
			ri.bodyParams[fieldName] = value
		case "query":
			ri.queryParams[fieldName] = value
		}
	}
}

// URL returns the full URL
func (ri *RequestInfo) URL() string {
	url := ri.Endpoint.Path
	for param, value := range ri.urlParams {
		url = strings.Replace(url, "{"+param+"}", value, -1)
	}

	return url
}

// PopulateQuery populate the query string of a request
func (ri *RequestInfo) PopulateQuery(qs *url.Values) {
	for key, value := range ri.queryParams {
		qs.Add(key, value)
	}
}

// Body returns the full Body of the request
func (ri *RequestInfo) Body() (*bytes.Buffer, error) {
	body := bytes.NewBufferString("")

	// Parse the body as a JSON object
	if len(ri.bodyParams) > 0 {
		jsonDump, err := json.Marshal(ri.bodyParams)
		if err != nil {
			return nil, err
		}

		body = bytes.NewBuffer(jsonDump)
	}

	return body, nil
}

// NewRequest simulates a new http request executed against the api
func NewRequest(t *testing.T, info *RequestInfo) *httptest.ResponseRecorder {
	info.ParseParams()

	// Parse the body as a JSON object
	body, err := info.Body()
	if err != nil {
		t.Fatalf("could not create request: %s", err)
	}

	req, err := http.NewRequest(info.Endpoint.Verb, info.URL(), body)
	if err != nil {
		t.Fatalf("could not execute request %s", err)
	}

	// Attach the query string
	qs := req.URL.Query()
	info.PopulateQuery(&qs)
	req.URL.RawQuery = qs.Encode()

	if info.Auth != nil {
		req.Header.Add("Authorization", info.Auth.ToBasicAuth())
	}

	req.Header.Add("Content-Type", "application/json; charset=utf-8")

	// If no router is provided we assume that we want to execute a regular endpoint
	if info.Router == nil {
		if DefaultRouter == nil {
			t.Fatalf("no router provided and DefaultRouter not set")
		}
		info.Router = DefaultRouter
	}

	rec := httptest.NewRecorder()
	info.Router.ServeHTTP(rec, req)
	return rec
}
<commit_msg>Buid a NewRequestAuth from a session<commit_after>package httptests

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"net/url"
	"reflect"
	"strconv"
	"testing"

	"strings"

	"github.com/Nivl/go-rest-tools/router"
	"github.com/Nivl/go-rest-tools/security/auth"
	"github.com/gorilla/mux"
)

// DefaultRouter represents the router to be used if none are specified
var DefaultRouter *mux.Router

// RequestAuth represents the auth data for a request
type RequestAuth struct {
	SessionID string
	UserID    string
}

// ToBasicAuth returns the data using the basic auth format
func (ra *RequestAuth) ToBasicAuth() string {
	authValue := fmt.Sprintf("%s:%s", ra.UserID, ra.SessionID)

	encoded := base64.StdEncoding.EncodeToString([]byte(authValue))
	return "basic " + encoded
}

// NewRequestAuth creates a new request auth
func NewRequestAuth(s *auth.Session) *RequestAuth {
	return &RequestAuth{
		SessionID: s.ID,
		UserID:    s.UserID,
	}
}

// RequestInfo represents the params accepted by NewRequest
type RequestInfo struct {
	Endpoint *router.Endpoint

	Params interface{}  // Optional
	Auth   *RequestAuth // Optional
	// Router is used to parse Mux Variables. Default on the api router
	Router *mux.Router

	urlParams   map[string]string
	bodyParams  map[string]string
	queryParams map[string]string
}

// ParseParams parses the params and copy them in the right list:
// urlParams, bodyParams, and queryParams
func (ri *RequestInfo) ParseParams() {
	ri.urlParams = map[string]string{}
	ri.bodyParams = map[string]string{}
	ri.queryParams = map[string]string{}

	if ri.Params == nil {
		return
	}

	params := reflect.ValueOf(ri.Params)
	if params.Kind() == reflect.Ptr {
		params = params.Elem()
	}
	ri.parseParamsRecursive(params)
}

func (ri *RequestInfo) parseParamsRecursive(params reflect.Value) {
	nbParams := params.NumField()
	for i := 0; i < nbParams; i++ {
		param := params.Field(i)
		paramInfo := params.Type().Field(i)
		tags := paramInfo.Tag

		if param.Kind() == reflect.Ptr {
			param = param.Elem()
		}

		// Handle embeded struct
		if param.Kind() == reflect.Struct && paramInfo.Anonymous {
			ri.parseParamsRecursive(param)
			continue
		}

		// We get the Value
		value := ""
		switch param.Kind() {
		case reflect.Bool:
			value = strconv.FormatBool(param.Bool())
		case reflect.String:
			value = param.String()
		case reflect.Int:
			value = strconv.Itoa(int(param.Int()))
		case reflect.Ptr:
			if !param.IsNil() {
				val := param.Elem()
				switch val.Kind() {
				case reflect.Bool:
					value = strconv.FormatBool(val.Bool())
				case reflect.String:
					value = param.String()
				case reflect.Int:
					value = strconv.Itoa(int(val.Int()))
				}
			}
		}

		// We get the name from the json tag
		fieldName := ""
		jsonOpts := strings.Split(tags.Get("json"), ",")
		if len(jsonOpts) > 0 {
			if jsonOpts[0] == "-" {
				continue
			}
			fieldName = jsonOpts[0]
		}

		switch strings.ToLower(tags.Get("from")) {
		case "url":
			ri.urlParams[fieldName] = value
		case "form":
			ri.bodyParams[fieldName] = value
		case "query":
			ri.queryParams[fieldName] = value
		}
	}
}

// URL returns the full URL
func (ri *RequestInfo) URL() string {
	url := ri.Endpoint.Path
	for param, value := range ri.urlParams {
		url = strings.Replace(url, "{"+param+"}", value, -1)
	}

	return url
}

// PopulateQuery populate the query string of a request
func (ri *RequestInfo) PopulateQuery(qs *url.Values) {
	for key, value := range ri.queryParams {
		qs.Add(key, value)
	}
}

// Body returns the full Body of the request
func (ri *RequestInfo) Body() (*bytes.Buffer, error) {
	body := bytes.NewBufferString("")

	// Parse the body as a JSON object
	if len(ri.bodyParams) > 0 {
		jsonDump, err := json.Marshal(ri.bodyParams)
		if err != nil {
			return nil, err
		}

		body = bytes.NewBuffer(jsonDump)
	}

	return body, nil
}

// NewRequest simulates a new http request executed against the api
func NewRequest(t *testing.T, info *RequestInfo) *httptest.ResponseRecorder {
	info.ParseParams()

	// Parse the body as a JSON object
	body, err := info.Body()
	if err != nil {
		t.Fatalf("could not create request: %s", err)
	}

	req, err := http.NewRequest(info.Endpoint.Verb, info.URL(), body)
	if err != nil {
		t.Fatalf("could not execute request %s", err)
	}

	// Attach the query string
	qs := req.URL.Query()
	info.PopulateQuery(&qs)
	req.URL.RawQuery = qs.Encode()

	if info.Auth != nil {
		req.Header.Add("Authorization", info.Auth.ToBasicAuth())
	}

	req.Header.Add("Content-Type", "application/json; charset=utf-8")

	// If no router is provided we assume that we want to execute a regular endpoint
	if info.Router == nil {
		if DefaultRouter == nil {
			t.Fatalf("no router provided and DefaultRouter not set")
		}
		info.Router = DefaultRouter
	}

	rec := httptest.NewRecorder()
	info.Router.ServeHTTP(rec, req)
	return rec
}
<|endoftext|>


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

package trace_test

import (
	"context"
	"testing"

	"go.opentelemetry.io/otel/api/core"
	"go.opentelemetry.io/otel/api/key"
	apitrace "go.opentelemetry.io/otel/api/trace"
	sdktrace "go.opentelemetry.io/otel/sdk/trace"
)

func BenchmarkStartEndSpan(b *testing.B) {
	t := getTracer(b, "Benchmark StartEndSpan")

	traceBenchmark(b, func(b *testing.B) {
		ctx := context.Background()
		b.ResetTimer()
		for i := 0; i < b.N; i++ {
			_, span := t.Start(ctx, "/foo")
			span.End()
		}
	})
}

func BenchmarkSpanWithAttributes_4(b *testing.B) {
	t := getTracer(b, "Benchmark Start With 4 Attributes")

	traceBenchmark(b, func(b *testing.B) {
		ctx := context.Background()
		b.ResetTimer()

		for i := 0; i < b.N; i++ {
			_, span := t.Start(ctx, "/foo")
			span.SetAttributes(
				key.New("key1").Bool(false),
				key.New("key2").String("hello"),
				key.New("key3").Uint64(123),
				key.New("key4").Float64(123.456),
			)
			span.End()
		}
	})
}

func BenchmarkSpanWithAttributes_8(b *testing.B) {
	t := getTracer(b, "Benchmark Start With 8 Attributes")

	traceBenchmark(b, func(b *testing.B) {
		ctx := context.Background()
		b.ResetTimer()

		for i := 0; i < b.N; i++ {
			_, span := t.Start(ctx, "/foo")
			span.SetAttributes(
				key.New("key1").Bool(false),
				key.New("key2").String("hello"),
				key.New("key3").Uint64(123),
				key.New("key4").Float64(123.456),
				key.New("key21").Bool(false),
				key.New("key22").String("hello"),
				key.New("key23").Uint64(123),
				key.New("key24").Float64(123.456),
			)
			span.End()
		}
	})
}

func BenchmarkSpanWithAttributes_all(b *testing.B) {
	t := getTracer(b, "Benchmark Start With all Attribute types")

	traceBenchmark(b, func(b *testing.B) {
		ctx := context.Background()
		b.ResetTimer()

		for i := 0; i < b.N; i++ {
			_, span := t.Start(ctx, "/foo")
			span.SetAttributes(
				key.New("key1").Bool(false),
				key.New("key2").String("hello"),
				key.New("key3").Int64(123),
				key.New("key4").Uint64(123),
				key.New("key5").Int32(123),
				key.New("key6").Uint32(123),
				key.New("key7").Float64(123.456),
				key.New("key8").Float32(123.456),
				key.New("key9").Int(123),
				key.New("key10").Uint(123),
			)
			span.End()
		}
	})
}

func BenchmarkSpanWithAttributes_all_2x(b *testing.B) {
	t := getTracer(b, "Benchmark Start With all Attributes types twice")
	traceBenchmark(b, func(b *testing.B) {
		ctx := context.Background()
		b.ResetTimer()

		for i := 0; i < b.N; i++ {
			_, span := t.Start(ctx, "/foo")
			span.SetAttributes(
				key.New("key1").Bool(false),
				key.New("key2").String("hello"),
				key.New("key3").Int64(123),
				key.New("key4").Uint64(123),
				key.New("key5").Int32(123),
				key.New("key6").Uint32(123),
				key.New("key7").Float64(123.456),
				key.New("key8").Float32(123.456),
				key.New("key10").Int(123),
				key.New("key11").Uint(123),
				key.New("key21").Bool(false),
				key.New("key22").String("hello"),
				key.New("key23").Int64(123),
				key.New("key24").Uint64(123),
				key.New("key25").Int32(123),
				key.New("key26").Uint32(123),
				key.New("key27").Float64(123.456),
				key.New("key28").Float32(123.456),
				key.New("key210").Int(123),
				key.New("key211").Uint(123),
			)
			span.End()
		}
	})
}

func BenchmarkTraceID_DotString(b *testing.B) {
	traceBenchmark(b, func(b *testing.B) {
		t, _ := core.TraceIDFromHex("0000000000000001000000000000002a")
		sc := core.SpanContext{TraceID: t}

		want := "0000000000000001000000000000002a"
		for i := 0; i < b.N; i++ {
			if got := sc.TraceIDString(); got != want {
				b.Fatalf("got = %q want = %q", got, want)
			}
		}
	})
}

func BenchmarkSpanID_DotString(b *testing.B) {
	traceBenchmark(b, func(b *testing.B) {
		sc := core.SpanContext{SpanID: core.SpanID{1}}
		want := "1000000000000000"
		for i := 0; i < b.N; i++ {
			if got := sc.SpanIDString(); got != want {
				b.Fatalf("got = %q want = %q", got, want)
			}
		}
	})
}

func traceBenchmark(b *testing.B, fn func(*testing.B)) {
	b.Run("AlwaysSample", func(b *testing.B) {
		b.ReportAllocs()
		fn(b)
	})
	b.Run("NeverSample", func(b *testing.B) {
		b.ReportAllocs()
		fn(b)
	})
}

func getTracer(b *testing.B, name string) apitrace.Tracer {
	tp, err := sdktrace.NewProvider(sdktrace.WithConfig(testConfig))
	if err != nil {
		b.Fatalf("Failed to create trace provider for test %s\n", name)
	}
	return tp.GetTracer(name)
}
<commit_msg>fix benchmark error, with always/never sample and add benchmark setAttribute vs setAttributes (#325)<commit_after>// Copyright 2019, OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package trace_test

import (
	"context"
	"testing"

	"go.opentelemetry.io/otel/api/core"
	"go.opentelemetry.io/otel/api/key"
	apitrace "go.opentelemetry.io/otel/api/trace"
	sdktrace "go.opentelemetry.io/otel/sdk/trace"
)

func BenchmarkStartEndSpan(b *testing.B) {
	traceBenchmark(b, "Benchmark StartEndSpan", func(b *testing.B, t apitrace.Tracer) {
		ctx := context.Background()
		b.ResetTimer()
		for i := 0; i < b.N; i++ {
			_, span := t.Start(ctx, "/foo")
			span.End()
		}
	})
}

func BenchmarkSpanWithAttributes_4(b *testing.B) {
	traceBenchmark(b, "Benchmark Start With 4 Attributes", func(b *testing.B, t apitrace.Tracer) {
		ctx := context.Background()
		b.ResetTimer()

		for i := 0; i < b.N; i++ {
			_, span := t.Start(ctx, "/foo")
			span.SetAttributes(
				key.New("key1").Bool(false),
				key.New("key2").String("hello"),
				key.New("key3").Uint64(123),
				key.New("key4").Float64(123.456),
			)
			span.End()
		}
	})
}

func BenchmarkSpan_SetAttributes(b *testing.B) {
	b.Run("SetAttribute", func(b *testing.B) {
		traceBenchmark(b, "Benchmark Start With 4 Attributes", func(b *testing.B, t apitrace.Tracer) {
			ctx := context.Background()
			b.ResetTimer()

			for i := 0; i < b.N; i++ {
				_, span := t.Start(ctx, "/foo")
				span.SetAttribute(key.New("key1").Bool(false))
				span.SetAttribute(key.New("key2").String("hello"))
				span.SetAttribute(key.New("key3").Uint64(123))
				span.SetAttribute(key.New("key4").Float64(123.456))
				span.End()
			}
		})
	})

	b.Run("SetAttributes", func(b *testing.B) {
		traceBenchmark(b, "Benchmark Start With 4 Attributes", func(b *testing.B, t apitrace.Tracer) {
			ctx := context.Background()
			b.ResetTimer()
			for i := 0; i < b.N; i++ {
				_, span := t.Start(ctx, "/foo")
				span.SetAttributes(key.New("key1").Bool(false))
				span.SetAttributes(key.New("key2").String("hello"))
				span.SetAttributes(key.New("key3").Uint64(123))
				span.SetAttributes(key.New("key4").Float64(123.456))
				span.End()
			}
		})
	})
}

func BenchmarkSpanWithAttributes_8(b *testing.B) {
	traceBenchmark(b, "Benchmark Start With 8 Attributes", func(b *testing.B, t apitrace.Tracer) {
		ctx := context.Background()
		b.ResetTimer()

		for i := 0; i < b.N; i++ {
			_, span := t.Start(ctx, "/foo")
			span.SetAttributes(
				key.New("key1").Bool(false),
				key.New("key2").String("hello"),
				key.New("key3").Uint64(123),
				key.New("key4").Float64(123.456),
				key.New("key21").Bool(false),
				key.New("key22").String("hello"),
				key.New("key23").Uint64(123),
				key.New("key24").Float64(123.456),
			)
			span.End()
		}
	})
}

func BenchmarkSpanWithAttributes_all(b *testing.B) {
	traceBenchmark(b, "Benchmark Start With all Attribute types", func(b *testing.B, t apitrace.Tracer) {
		ctx := context.Background()
		b.ResetTimer()

		for i := 0; i < b.N; i++ {
			_, span := t.Start(ctx, "/foo")
			span.SetAttributes(
				key.New("key1").Bool(false),
				key.New("key2").String("hello"),
				key.New("key3").Int64(123),
				key.New("key4").Uint64(123),
				key.New("key5").Int32(123),
				key.New("key6").Uint32(123),
				key.New("key7").Float64(123.456),
				key.New("key8").Float32(123.456),
				key.New("key9").Int(123),
				key.New("key10").Uint(123),
			)
			span.End()
		}
	})
}

func BenchmarkSpanWithAttributes_all_2x(b *testing.B) {
	traceBenchmark(b, "Benchmark Start With all Attributes types twice", func(b *testing.B, t apitrace.Tracer) {
		ctx := context.Background()
		b.ResetTimer()

		for i := 0; i < b.N; i++ {
			_, span := t.Start(ctx, "/foo")
			span.SetAttributes(
				key.New("key1").Bool(false),
				key.New("key2").String("hello"),
				key.New("key3").Int64(123),
				key.New("key4").Uint64(123),
				key.New("key5").Int32(123),
				key.New("key6").Uint32(123),
				key.New("key7").Float64(123.456),
				key.New("key8").Float32(123.456),
				key.New("key10").Int(123),
				key.New("key11").Uint(123),
				key.New("key21").Bool(false),
				key.New("key22").String("hello"),
				key.New("key23").Int64(123),
				key.New("key24").Uint64(123),
				key.New("key25").Int32(123),
				key.New("key26").Uint32(123),
				key.New("key27").Float64(123.456),
				key.New("key28").Float32(123.456),
				key.New("key210").Int(123),
				key.New("key211").Uint(123),
			)
			span.End()
		}
	})
}

func BenchmarkTraceID_DotString(b *testing.B) {
	t, _ := core.TraceIDFromHex("0000000000000001000000000000002a")
	sc := core.SpanContext{TraceID: t}

	want := "0000000000000001000000000000002a"
	for i := 0; i < b.N; i++ {
		if got := sc.TraceIDString(); got != want {
			b.Fatalf("got = %q want = %q", got, want)
		}
	}
}

func BenchmarkSpanID_DotString(b *testing.B) {
	sc := core.SpanContext{SpanID: core.SpanID{1}}
	want := "0100000000000000"
	for i := 0; i < b.N; i++ {
		if got := sc.SpanIDString(); got != want {
			b.Fatalf("got = %q want = %q", got, want)
		}
	}
}

func traceBenchmark(b *testing.B, name string, fn func(*testing.B, apitrace.Tracer)) {
	b.Run("AlwaysSample", func(b *testing.B) {
		b.ReportAllocs()
		fn(b, getTracer(b, name, sdktrace.AlwaysSample()))
	})
	b.Run("NeverSample", func(b *testing.B) {
		b.ReportAllocs()
		fn(b, getTracer(b, name, sdktrace.NeverSample()))
	})
}

func getTracer(b *testing.B, name string, sampler sdktrace.Sampler) apitrace.Tracer {
	tp, err := sdktrace.NewProvider(sdktrace.WithConfig(sdktrace.Config{DefaultSampler: sampler}))
	if err != nil {
		b.Fatalf("Failed to create trace provider for test %s\n", name)
	}
	return tp.GetTracer(name)
}
<|endoftext|>