<commit_before>package main

import (
	"os"
	"os/signal"
	"path/filepath"
	"time"

	"context"

	netContext "golang.org/x/net/context"
	kingpin "gopkg.in/alecthomas/kingpin.v2"

	"github.com/keel-hq/keel/approvals"
	"github.com/keel-hq/keel/bot"
	"github.com/keel-hq/keel/cache/memory"

	"github.com/keel-hq/keel/constants"
	"github.com/keel-hq/keel/extension/credentialshelper"
	"github.com/keel-hq/keel/extension/notification"
	"github.com/keel-hq/keel/internal/k8s"
	"github.com/keel-hq/keel/internal/workgroup"
	"github.com/keel-hq/keel/provider"
	"github.com/keel-hq/keel/provider/helm"
	"github.com/keel-hq/keel/provider/kubernetes"
	"github.com/keel-hq/keel/registry"
	"github.com/keel-hq/keel/secrets"
	"github.com/keel-hq/keel/trigger/http"
	"github.com/keel-hq/keel/trigger/poll"
	"github.com/keel-hq/keel/trigger/pubsub"
	"github.com/keel-hq/keel/types"
	"github.com/keel-hq/keel/version"

	// notification extensions
	_ "github.com/keel-hq/keel/extension/notification/hipchat"
	_ "github.com/keel-hq/keel/extension/notification/mattermost"
	_ "github.com/keel-hq/keel/extension/notification/slack"
	_ "github.com/keel-hq/keel/extension/notification/webhook"

	// credentials helpers
	_ "github.com/keel-hq/keel/extension/credentialshelper/aws"
	secretsCredentialsHelper "github.com/keel-hq/keel/extension/credentialshelper/secrets"

	// bots
	_ "github.com/keel-hq/keel/bot/hipchat"
	_ "github.com/keel-hq/keel/bot/slack"

	log "github.com/sirupsen/logrus"
)

// gcloud pubsub related config
const (
	EnvTriggerPubSub = "PUBSUB" // set to 1 or something to enable pub/sub trigger
	EnvTriggerPoll   = "POLL"   // set to 1 or something to enable poll trigger
	EnvProjectID     = "PROJECT_ID"
	EnvClusterName   = "CLUSTER_NAME"

	EnvNamespace = "NAMESPACE" // Keel's namespace

	EnvHelmProvider      = "HELM_PROVIDER"  // helm provider
	EnvHelmTillerAddress = "TILLER_ADDRESS" // helm provider

	// EnvDefaultDockerRegistryCfg - default registry configuration that can be passed into
	// keel for polling trigger
	EnvDefaultDockerRegistryCfg = "DOCKER_REGISTRY_CFG"
)

// kubernetes config, if empty - will default to InCluster
const (
	EnvKubernetesConfig = "KUBERNETES_CONFIG"
)

// EnvDebug - set to 1 or anything else to enable debug logging
const EnvDebug = "DEBUG"

func main() {
	ver := version.GetKeelVersion()

	inCluster := kingpin.Flag("incluster", "use in cluster configuration (defaults to 'true'), use '--no-incluster' if running outside of the cluster").Default("true").Bool()
	kubeconfig := kingpin.Flag("kubeconfig", "path to kubeconfig (if not in running inside a cluster)").Default(filepath.Join(os.Getenv("HOME"), ".kube", "config")).String()

	kingpin.UsageTemplate(kingpin.CompactUsageTemplate).Version(ver.Version)
	kingpin.CommandLine.Help = "Automated Kubernetes deployment updates. Learn more on https://keel.sh."
	kingpin.Parse()

	log.WithFields(log.Fields{
		"os":         ver.OS,
		"build_date": ver.BuildDate,
		"revision":   ver.Revision,
		"version":    ver.Version,
		"go_version": ver.GoVersion,
		"arch":       ver.Arch,
	}).Info("keel starting...")

	if os.Getenv(EnvDebug) != "" {
		log.SetLevel(log.DebugLevel)
	}

	// setting up triggers
	ctx, cancel := netContext.WithCancel(context.Background())
	defer cancel()

	notificationLevel := types.LevelInfo
	if os.Getenv(constants.EnvNotificationLevel) != "" {
		parsedLevel, err := types.ParseLevel(os.Getenv(constants.EnvNotificationLevel))
		if err != nil {
			log.WithFields(log.Fields{
				"error": err,
			}).Errorf("main: got error while parsing notification level, defaulting to: %s", notificationLevel)
		} else {
			notificationLevel = parsedLevel
		}
	}

	notifCfg := &notification.Config{
		Attempts: 10,
		Level:    notificationLevel,
	}
	sender := notification.New(ctx)

	_, err := sender.Configure(notifCfg)
	if err != nil {
		log.WithFields(log.Fields{
			"error": err,
		}).Fatal("main: failed to configure notification sender manager")
	}

	// getting k8s provider
	k8sCfg := &kubernetes.Opts{
		ConfigPath: *kubeconfig,
	}

	if os.Getenv(EnvKubernetesConfig) != "" {
		k8sCfg.ConfigPath = os.Getenv(EnvKubernetesConfig)
	}

	k8sCfg.InCluster = *inCluster

	implementer, err := kubernetes.NewKubernetesImplementer(k8sCfg)
	if err != nil {
		log.WithFields(log.Fields{
			"error":  err,
			"config": k8sCfg,
		}).Fatal("main: failed to create kubernetes implementer")
	}

	var g workgroup.Group

	t := &k8s.Translator{
		FieldLogger: log.WithField("context", "translator"),
	}

	buf := k8s.NewBuffer(&g, t, log.StandardLogger(), 128)
	wl := log.WithField("context", "watch")
	k8s.WatchDeployments(&g, implementer.Client(), wl, buf)
	k8s.WatchStatefulSets(&g, implementer.Client(), wl, buf)
	k8s.WatchDaemonSets(&g, implementer.Client(), wl, buf)
	k8s.WatchCronJobs(&g, implementer.Client(), wl, buf)

	approvalsCache := memory.NewMemoryCache()
	approvalsManager := approvals.New(approvalsCache)

	go approvalsManager.StartExpiryService(ctx)

	// setting up providers
	providers := setupProviders(implementer, sender, approvalsManager, &t.GenericResourceCache)

	// registering secrets based credentials helper
	dockerConfig := make(secrets.DockerCfg)
	if os.Getenv(EnvDefaultDockerRegistryCfg) != "" {
		dockerConfigStr := os.Getenv(EnvDefaultDockerRegistryCfg)
		dockerConfig, err = secrets.DecodeDockerCfgJson([]byte(dockerConfigStr))
		if err != nil {
			log.WithFields(log.Fields{
				"error": err,
			}).Fatalf("failed to decode secret provided in %s env variable", EnvDefaultDockerRegistryCfg)
		}
	}
	secretsGetter := secrets.NewGetter(implementer, dockerConfig)

	ch := secretsCredentialsHelper.New(secretsGetter)
	credentialshelper.RegisterCredentialsHelper("secrets", ch)

	// trigger setup
	teardownTriggers := setupTriggers(ctx, providers, approvalsManager)

	bot.Run(implementer, approvalsManager)

	signalChan := make(chan os.Signal, 1)
	cleanupDone := make(chan bool)
	signal.Notify(signalChan, os.Interrupt)
	g.Add(func(stop <-chan struct{}) {
		go func() {
			for range signalChan {
				log.Info("received an interrupt, shutting down...")
				go func() {
					select {
					case <-time.After(10 * time.Second):
						log.Info("connection shutdown took too long, exiting... ")
						close(cleanupDone)
						return
					case <-cleanupDone:
						return
					}
				}()
				providers.Stop()
				teardownTriggers()
				bot.Stop()

				cleanupDone <- true
			}
		}()
		<-cleanupDone
	})
	g.Run()
}

// setupProviders - setting up available providers. New providers should be initialised here and added to
// provider map
func setupProviders(k8sImplementer kubernetes.Implementer, sender notification.Sender, approvalsManager approvals.Manager, grc *k8s.GenericResourceCache) (providers provider.Providers) {
	var enabledProviders []provider.Provider

	k8sProvider, err := kubernetes.NewProvider(k8sImplementer, sender, approvalsManager, grc)
	if err != nil {
		log.WithFields(log.Fields{
			"error": err,
		}).Fatal("main.setupProviders: failed to create kubernetes provider")
	}
	go func() {
		err := k8sProvider.Start()
		if err != nil {
			log.WithFields(log.Fields{
				"error": err,
			}).Fatal("kubernetes provider stopped with an error")
		}
	}()

	enabledProviders = append(enabledProviders, k8sProvider)

	if os.Getenv(EnvHelmProvider) == "1" {
		tillerAddr := os.Getenv(EnvHelmTillerAddress)
		helmImplementer := helm.NewHelmImplementer(tillerAddr)
		helmProvider := helm.NewProvider(helmImplementer, sender, approvalsManager)

		go func() {
			err := helmProvider.Start()
			if err != nil {
				log.WithFields(log.Fields{
					"error": err,
				}).Fatal("helm provider stopped with an error")
			}
		}()

		enabledProviders = append(enabledProviders, helmProvider)
	}

	providers = provider.New(enabledProviders, approvalsManager)

	return providers
}

// setupTriggers - setting up triggers. New triggers should be added to this function. Each trigger
// should go through all providers (or not if there is a reason) and submit events)
func setupTriggers(ctx context.Context, providers provider.Providers, approvalsManager approvals.Manager) (teardown func()) {

	// setting up generic http webhook server
	whs := http.NewTriggerServer(&http.Opts{
		Port:            types.KeelDefaultPort,
		Providers:       providers,
		ApprovalManager: approvalsManager,
	})

	go func() {
		err := whs.Start()
		if err != nil {
			log.WithFields(log.Fields{
				"error": err,
				"port":  types.KeelDefaultPort,
			}).Fatal("trigger server stopped")
		}
	}()

	// checking whether pubsub (GCR) trigger is enabled
	if os.Getenv(EnvTriggerPubSub) != "" {
		projectID := os.Getenv(EnvProjectID)
		if projectID == "" {
			log.Fatalf("main.setupTriggers: project ID env variable not set")
			return
		}

		ps, err := pubsub.NewPubsubSubscriber(&pubsub.Opts{
			ProjectID: projectID,
			Providers: providers,
		})
		if err != nil {
			log.WithFields(log.Fields{
				"error": err,
			}).Fatal("main.setupTriggers: failed to create gcloud pubsub subscriber")
			return
		}

		subManager := pubsub.NewDefaultManager(os.Getenv(EnvClusterName), projectID, providers, ps)
		go subManager.Start(ctx)
	}

	if os.Getenv(EnvTriggerPoll) != "0" {

		registryClient := registry.New()
		watcher := poll.NewRepositoryWatcher(providers, registryClient)
		pollManager := poll.NewPollManager(providers, watcher)

		// start poll manager, will finish with ctx
		go watcher.Start(ctx)
		go pollManager.Start(ctx)
	}

	teardown = func() {
		whs.Stop()
	}

	return teardown
}
<commit_msg>initializing basic auth<commit_after>package main

import (
	"os"
	"os/signal"
	"path/filepath"
	"time"

	"context"

	netContext "golang.org/x/net/context"
	kingpin "gopkg.in/alecthomas/kingpin.v2"

	"github.com/keel-hq/keel/approvals"
	"github.com/keel-hq/keel/bot"
	"github.com/keel-hq/keel/cache/memory"

	"github.com/keel-hq/keel/constants"
	"github.com/keel-hq/keel/extension/credentialshelper"
	"github.com/keel-hq/keel/extension/notification"
	"github.com/keel-hq/keel/internal/k8s"
	"github.com/keel-hq/keel/internal/workgroup"
	"github.com/keel-hq/keel/provider"
	"github.com/keel-hq/keel/provider/helm"
	"github.com/keel-hq/keel/provider/kubernetes"
	"github.com/keel-hq/keel/registry"
	"github.com/keel-hq/keel/secrets"
	"github.com/keel-hq/keel/trigger/http"
	"github.com/keel-hq/keel/trigger/poll"
	"github.com/keel-hq/keel/trigger/pubsub"
	"github.com/keel-hq/keel/types"
	"github.com/keel-hq/keel/version"

	// notification extensions
	_ "github.com/keel-hq/keel/extension/notification/hipchat"
	_ "github.com/keel-hq/keel/extension/notification/mattermost"
	_ "github.com/keel-hq/keel/extension/notification/slack"
	_ "github.com/keel-hq/keel/extension/notification/webhook"

	// credentials helpers
	_ "github.com/keel-hq/keel/extension/credentialshelper/aws"
	secretsCredentialsHelper "github.com/keel-hq/keel/extension/credentialshelper/secrets"

	// bots
	_ "github.com/keel-hq/keel/bot/hipchat"
	_ "github.com/keel-hq/keel/bot/slack"

	log "github.com/sirupsen/logrus"
)

// gcloud pubsub related config
const (
	EnvTriggerPubSub = "PUBSUB" // set to 1 or something to enable pub/sub trigger
	EnvTriggerPoll   = "POLL"   // set to 1 or something to enable poll trigger
	EnvProjectID     = "PROJECT_ID"
	EnvClusterName   = "CLUSTER_NAME"

	EnvNamespace = "NAMESPACE" // Keel's namespace

	EnvHelmProvider      = "HELM_PROVIDER"  // helm provider
	EnvHelmTillerAddress = "TILLER_ADDRESS" // helm provider

	// EnvDefaultDockerRegistryCfg - default registry configuration that can be passed into
	// keel for polling trigger
	EnvDefaultDockerRegistryCfg = "DOCKER_REGISTRY_CFG"
)

// kubernetes config, if empty - will default to InCluster
const (
	EnvKubernetesConfig = "KUBERNETES_CONFIG"
)

// EnvDebug - set to 1 or anything else to enable debug logging
const EnvDebug = "DEBUG"

func main() {
	ver := version.GetKeelVersion()

	inCluster := kingpin.Flag("incluster", "use in cluster configuration (defaults to 'true'), use '--no-incluster' if running outside of the cluster").Default("true").Bool()
	kubeconfig := kingpin.Flag("kubeconfig", "path to kubeconfig (if not in running inside a cluster)").Default(filepath.Join(os.Getenv("HOME"), ".kube", "config")).String()

	kingpin.UsageTemplate(kingpin.CompactUsageTemplate).Version(ver.Version)
	kingpin.CommandLine.Help = "Automated Kubernetes deployment updates. Learn more on https://keel.sh."
	kingpin.Parse()

	log.WithFields(log.Fields{
		"os":         ver.OS,
		"build_date": ver.BuildDate,
		"revision":   ver.Revision,
		"version":    ver.Version,
		"go_version": ver.GoVersion,
		"arch":       ver.Arch,
	}).Info("keel starting...")

	if os.Getenv(EnvDebug) != "" {
		log.SetLevel(log.DebugLevel)
	}

	// setting up triggers
	ctx, cancel := netContext.WithCancel(context.Background())
	defer cancel()

	notificationLevel := types.LevelInfo
	if os.Getenv(constants.EnvNotificationLevel) != "" {
		parsedLevel, err := types.ParseLevel(os.Getenv(constants.EnvNotificationLevel))
		if err != nil {
			log.WithFields(log.Fields{
				"error": err,
			}).Errorf("main: got error while parsing notification level, defaulting to: %s", notificationLevel)
		} else {
			notificationLevel = parsedLevel
		}
	}

	notifCfg := &notification.Config{
		Attempts: 10,
		Level:    notificationLevel,
	}
	sender := notification.New(ctx)

	_, err := sender.Configure(notifCfg)
	if err != nil {
		log.WithFields(log.Fields{
			"error": err,
		}).Fatal("main: failed to configure notification sender manager")
	}

	// getting k8s provider
	k8sCfg := &kubernetes.Opts{
		ConfigPath: *kubeconfig,
	}

	if os.Getenv(EnvKubernetesConfig) != "" {
		k8sCfg.ConfigPath = os.Getenv(EnvKubernetesConfig)
	}

	k8sCfg.InCluster = *inCluster

	implementer, err := kubernetes.NewKubernetesImplementer(k8sCfg)
	if err != nil {
		log.WithFields(log.Fields{
			"error":  err,
			"config": k8sCfg,
		}).Fatal("main: failed to create kubernetes implementer")
	}

	var g workgroup.Group

	t := &k8s.Translator{
		FieldLogger: log.WithField("context", "translator"),
	}

	buf := k8s.NewBuffer(&g, t, log.StandardLogger(), 128)
	wl := log.WithField("context", "watch")
	k8s.WatchDeployments(&g, implementer.Client(), wl, buf)
	k8s.WatchStatefulSets(&g, implementer.Client(), wl, buf)
	k8s.WatchDaemonSets(&g, implementer.Client(), wl, buf)
	k8s.WatchCronJobs(&g, implementer.Client(), wl, buf)

	approvalsCache := memory.NewMemoryCache()
	approvalsManager := approvals.New(approvalsCache)

	go approvalsManager.StartExpiryService(ctx)

	// setting up providers
	providers := setupProviders(implementer, sender, approvalsManager, &t.GenericResourceCache)

	// registering secrets based credentials helper
	dockerConfig := make(secrets.DockerCfg)
	if os.Getenv(EnvDefaultDockerRegistryCfg) != "" {
		dockerConfigStr := os.Getenv(EnvDefaultDockerRegistryCfg)
		dockerConfig, err = secrets.DecodeDockerCfgJson([]byte(dockerConfigStr))
		if err != nil {
			log.WithFields(log.Fields{
				"error": err,
			}).Fatalf("failed to decode secret provided in %s env variable", EnvDefaultDockerRegistryCfg)
		}
	}
	secretsGetter := secrets.NewGetter(implementer, dockerConfig)

	ch := secretsCredentialsHelper.New(secretsGetter)
	credentialshelper.RegisterCredentialsHelper("secrets", ch)

	// trigger setup
	teardownTriggers := setupTriggers(ctx, providers, approvalsManager)

	bot.Run(implementer, approvalsManager)

	signalChan := make(chan os.Signal, 1)
	cleanupDone := make(chan bool)
	signal.Notify(signalChan, os.Interrupt)
	g.Add(func(stop <-chan struct{}) {
		go func() {
			for range signalChan {
				log.Info("received an interrupt, shutting down...")
				go func() {
					select {
					case <-time.After(10 * time.Second):
						log.Info("connection shutdown took too long, exiting... ")
						close(cleanupDone)
						return
					case <-cleanupDone:
						return
					}
				}()
				providers.Stop()
				teardownTriggers()
				bot.Stop()

				cleanupDone <- true
			}
		}()
		<-cleanupDone
	})
	g.Run()
}

// setupProviders - setting up available providers. New providers should be initialised here and added to
// provider map
func setupProviders(k8sImplementer kubernetes.Implementer, sender notification.Sender, approvalsManager approvals.Manager, grc *k8s.GenericResourceCache) (providers provider.Providers) {
	var enabledProviders []provider.Provider

	k8sProvider, err := kubernetes.NewProvider(k8sImplementer, sender, approvalsManager, grc)
	if err != nil {
		log.WithFields(log.Fields{
			"error": err,
		}).Fatal("main.setupProviders: failed to create kubernetes provider")
	}
	go func() {
		err := k8sProvider.Start()
		if err != nil {
			log.WithFields(log.Fields{
				"error": err,
			}).Fatal("kubernetes provider stopped with an error")
		}
	}()

	enabledProviders = append(enabledProviders, k8sProvider)

	if os.Getenv(EnvHelmProvider) == "1" {
		tillerAddr := os.Getenv(EnvHelmTillerAddress)
		helmImplementer := helm.NewHelmImplementer(tillerAddr)
		helmProvider := helm.NewProvider(helmImplementer, sender, approvalsManager)

		go func() {
			err := helmProvider.Start()
			if err != nil {
				log.WithFields(log.Fields{
					"error": err,
				}).Fatal("helm provider stopped with an error")
			}
		}()

		enabledProviders = append(enabledProviders, helmProvider)
	}

	providers = provider.New(enabledProviders, approvalsManager)

	return providers
}

// setupTriggers - setting up triggers. New triggers should be added to this function. Each trigger
// should go through all providers (or not if there is a reason) and submit events)
func setupTriggers(ctx context.Context, providers provider.Providers, approvalsManager approvals.Manager) (teardown func()) {

	// setting up generic http webhook server
	whs := http.NewTriggerServer(&http.Opts{
		Port:            types.KeelDefaultPort,
		Providers:       providers,
		ApprovalManager: approvalsManager,
		Username:        os.Getenv(constants.EnvBasicAuthUser),
		Password:        os.Getenv(constants.EnvBasicAuthPassword),
	})

	go func() {
		err := whs.Start()
		if err != nil {
			log.WithFields(log.Fields{
				"error": err,
				"port":  types.KeelDefaultPort,
			}).Fatal("trigger server stopped")
		}
	}()

	// checking whether pubsub (GCR) trigger is enabled
	if os.Getenv(EnvTriggerPubSub) != "" {
		projectID := os.Getenv(EnvProjectID)
		if projectID == "" {
			log.Fatalf("main.setupTriggers: project ID env variable not set")
			return
		}

		ps, err := pubsub.NewPubsubSubscriber(&pubsub.Opts{
			ProjectID: projectID,
			Providers: providers,
		})
		if err != nil {
			log.WithFields(log.Fields{
				"error": err,
			}).Fatal("main.setupTriggers: failed to create gcloud pubsub subscriber")
			return
		}

		subManager := pubsub.NewDefaultManager(os.Getenv(EnvClusterName), projectID, providers, ps)
		go subManager.Start(ctx)
	}

	if os.Getenv(EnvTriggerPoll) != "0" {

		registryClient := registry.New()
		watcher := poll.NewRepositoryWatcher(providers, registryClient)
		pollManager := poll.NewPollManager(providers, watcher)

		// start poll manager, will finish with ctx
		go watcher.Start(ctx)
		go pollManager.Start(ctx)
	}

	teardown = func() {
		whs.Stop()
	}

	return teardown
}
<|endoftext|>


<commit_before>// Package main provides main service.
package main

import (
	"github.com/powerman/narada-go/narada/bootstrap"

	"net/http"

	"github.com/powerman/narada-go/narada"

	_ "../../api/eventsvc"
	_ "../../api/rpcsvc"
	_ "../../api/websvc"
	"../../cfg"
)

var log = narada.NewLog("")

func main() {
	if err := bootstrap.Unlock(); err != nil {
		log.Fatal(err)
	}
	log.NOTICE("Listening on %s", cfg.HTTP.Listen+cfg.HTTP.BasePath)
	log.Fatal(http.ListenAndServe(cfg.HTTP.Listen, nil))
}
<commit_msg>Add metrics URL<commit_after>// Package main provides main service.
package main

import (
	"github.com/powerman/narada-go/narada/bootstrap"

	"net/http"

	"github.com/powerman/narada-go/narada"
	"github.com/prometheus/client_golang/prometheus"

	_ "../../api/eventsvc"
	_ "../../api/rpcsvc"
	_ "../../api/websvc"
	"../../cfg"
)

var log = narada.NewLog("")

func main() {
	if err := bootstrap.Unlock(); err != nil {
		log.Fatal(err)
	}
	http.Handle(cfg.HTTP.BasePath+"/metrics", prometheus.Handler())
	log.NOTICE("Listening on %s", cfg.HTTP.Listen+cfg.HTTP.BasePath)
	log.Fatal(http.ListenAndServe(cfg.HTTP.Listen, nil))
}
<|endoftext|>


<commit_before>package cmd

import (
	"fmt"
	"io/ioutil"

	"github.com/mobingi/mobingi-cli/pkg/cli"
	"github.com/mobingi/mobingi-cli/pkg/cli/confmap"
	"github.com/mobingilabs/mobingi-sdk-go/mobingi/alm"
	"github.com/mobingilabs/mobingi-sdk-go/pkg/cmdline"
	d "github.com/mobingilabs/mobingi-sdk-go/pkg/debug"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

func StackGetPemCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "pem",
		Short: "print stack pem file",
		Long: `Print your stack's pem file, if available.

Example:

  $ ` + cmdline.Args0() + ` stack pem --id foo`,
		Run: getpem,
	}

	cmd.Flags().StringP("id", "i", "", "stack id")
	cmd.Flags().String("flag", "", "flag")
	return cmd
}

func getpem(cmd *cobra.Command, args []string) {
	verbose := viper.GetBool(confmap.ConfigKey("verbose"))
	sess, err := clisession()
	d.ErrorExit(err, 1)

	svc := alm.New(sess)
	in := &alm.GetPemInput{
		StackId: cli.GetCliStringFlag(cmd, "id"),
		Flag:    cli.GetCliStringFlag(cmd, "flag"),
	}

	resp, body, pem, err := svc.GetPem(in)
	exitOn401(resp)
	if err != nil {
		d.Error(err)
		if verbose {
			d.Error("req payload:")
			fmt.Println(string(body))
			d.Error("pem payload:")
			fmt.Println(string(pem))
		}

		return
	}

	if verbose {
		d.Info("req payload:")
		fmt.Println(string(body))
	}

	d.Info("payload:")
	fmt.Println(string(pem))

	// write to file if requested
	out := cli.GetCliStringFlag(cmd, "out")
	if out != "" {
		err = ioutil.WriteFile(out, pem, 0644)
		d.ErrorExit(err, 1)
	}
}
<commit_msg>[ci skip] Unsorted help.<commit_after>package cmd

import (
	"fmt"
	"io/ioutil"

	"github.com/mobingi/mobingi-cli/pkg/cli"
	"github.com/mobingi/mobingi-cli/pkg/cli/confmap"
	"github.com/mobingilabs/mobingi-sdk-go/mobingi/alm"
	"github.com/mobingilabs/mobingi-sdk-go/pkg/cmdline"
	d "github.com/mobingilabs/mobingi-sdk-go/pkg/debug"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

func StackGetPemCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "pem",
		Short: "print stack pem file",
		Long: `Print your stack's pem file, if available.

Example:

  $ ` + cmdline.Args0() + ` stack pem --id foo`,
		Run: getpem,
	}

	cmd.Flags().SortFlags = false
	cmd.Flags().String("id", "", "stack id")
	cmd.Flags().String("flag", "", "flag")
	return cmd
}

func getpem(cmd *cobra.Command, args []string) {
	verbose := viper.GetBool(confmap.ConfigKey("verbose"))
	sess, err := clisession()
	d.ErrorExit(err, 1)

	svc := alm.New(sess)
	in := &alm.GetPemInput{
		StackId: cli.GetCliStringFlag(cmd, "id"),
		Flag:    cli.GetCliStringFlag(cmd, "flag"),
	}

	resp, body, pem, err := svc.GetPem(in)
	exitOn401(resp)
	if err != nil {
		d.Error(err)
		if verbose {
			d.Error("req payload:")
			fmt.Println(string(body))
			d.Error("pem payload:")
			fmt.Println(string(pem))
		}

		return
	}

	if verbose {
		d.Info("req payload:")
		fmt.Println(string(body))
	}

	d.Info("payload:")
	fmt.Println(string(pem))

	// write to file if requested
	out := cli.GetCliStringFlag(cmd, "out")
	if out != "" {
		err = ioutil.WriteFile(out, pem, 0644)
		d.ErrorExit(err, 1)
	}
}
<|endoftext|>


<commit_before>/*
	This file is part of go-ethereum

	go-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	go-ethereum is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with go-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @authors
 * 	Jeffrey Wilcke <i@jev.io>
 * 	Viktor Tron <viktor@ethdev.com>
 */
package utils

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"os/signal"
	"regexp"
	"strings"

	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/core"
	"github.com/ethereum/go-ethereum/core/types"
	"github.com/ethereum/go-ethereum/eth"
	"github.com/ethereum/go-ethereum/logger"
	"github.com/ethereum/go-ethereum/logger/glog"
	"github.com/ethereum/go-ethereum/rlp"
	"github.com/peterh/liner"
)

var interruptCallbacks = []func(os.Signal){}

// Register interrupt handlers callbacks
func RegisterInterrupt(cb func(os.Signal)) {
	interruptCallbacks = append(interruptCallbacks, cb)
}

// go routine that call interrupt handlers in order of registering
func HandleInterrupt() {
	c := make(chan os.Signal, 1)
	go func() {
		signal.Notify(c, os.Interrupt)
		for sig := range c {
			glog.V(logger.Error).Infof("Shutting down (%v) ... \n", sig)
			RunInterruptCallbacks(sig)
		}
	}()
}

func RunInterruptCallbacks(sig os.Signal) {
	for _, cb := range interruptCallbacks {
		cb(sig)
	}
}

func openLogFile(Datadir string, filename string) *os.File {
	path := common.AbsolutePath(Datadir, filename)
	file, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		panic(fmt.Sprintf("error opening log file '%s': %v", filename, err))
	}
	return file
}

func confirm(message string) bool {
	fmt.Println(message, "Are you sure? (y/n)")
	var r string
	fmt.Scanln(&r)
	for ; ; fmt.Scanln(&r) {
		if r == "n" || r == "y" {
			break
		} else {
			fmt.Printf("Yes or no? (%s)", r)
		}
	}
	return r == "y"
}

func PromptConfirm(prompt string) (bool, error) {
	var (
		input string
		err   error
	)
	prompt = prompt + " [y/N] "

	if liner.TerminalSupported() {
		lr := liner.NewLiner()
		defer lr.Close()
		input, err = lr.Prompt(prompt)
	} else {
		fmt.Print(prompt)
		input, err = bufio.NewReader(os.Stdin).ReadString('\n')
		fmt.Println()
	}

	if len(input) > 0 && strings.ToUpper(input[:1]) == "Y" {
		return true, nil
	} else {
		return false, nil
	}

	return false, err
}

func PromptPassword(prompt string, warnTerm bool) (string, error) {
	if liner.TerminalSupported() {
		lr := liner.NewLiner()
		defer lr.Close()
		return lr.PasswordPrompt(prompt)
	}
	if warnTerm {
		fmt.Println("!! Unsupported terminal, password will be echoed.")
	}
	fmt.Print(prompt)
	input, err := bufio.NewReader(os.Stdin).ReadString('\n')
	fmt.Println()
	return input, err
}

func initDataDir(Datadir string) {
	_, err := os.Stat(Datadir)
	if err != nil {
		if os.IsNotExist(err) {
			fmt.Printf("Data directory '%s' doesn't exist, creating it\n", Datadir)
			os.Mkdir(Datadir, 0777)
		}
	}
}

// Fatalf formats a message to standard output and exits the program.
func Fatalf(format string, args ...interface{}) {
	fmt.Fprintf(os.Stderr, "Fatal: "+format+"\n", args...)
	fmt.Fprintf(os.Stdout, "Fatal: "+format+"\n", args...)
	logger.Flush()
	os.Exit(1)
}

func StartEthereum(ethereum *eth.Ethereum) {
	glog.V(logger.Info).Infoln("Starting", ethereum.Name())
	if err := ethereum.Start(); err != nil {
		Fatalf("Error starting Ethereum: %v", err)
	}
	RegisterInterrupt(func(sig os.Signal) {
		ethereum.Stop()
		logger.Flush()
	})
}

func StartEthereumForTest(ethereum *eth.Ethereum) {
	glog.V(logger.Info).Infoln("Starting ", ethereum.Name())
	ethereum.StartForTest()
	RegisterInterrupt(func(sig os.Signal) {
		ethereum.Stop()
		logger.Flush()
	})
}

func FormatTransactionData(data string) []byte {
	d := common.StringToByteFunc(data, func(s string) (ret []byte) {
		slice := regexp.MustCompile("\\n|\\s").Split(s, 1000000000)
		for _, dataItem := range slice {
			d := common.FormatData(dataItem)
			ret = append(ret, d...)
		}
		return
	})

	return d
}

func ImportChain(chainmgr *core.ChainManager, fn string) error {
	fmt.Printf("importing blockchain '%s'\n", fn)
	fh, err := os.OpenFile(fn, os.O_RDONLY, os.ModePerm)
	if err != nil {
		return err
	}
	defer fh.Close()

	chainmgr.Reset()
	stream := rlp.NewStream(fh, 0)
	var i, n int

	batchSize := 2500
	blocks := make(types.Blocks, batchSize)

	for ; ; i++ {
		var b types.Block
		if err := stream.Decode(&b); err == io.EOF {
			break
		} else if err != nil {
			return fmt.Errorf("at block %d: %v", i, err)
		}

		blocks[n] = &b
		n++

		if n == batchSize {
			if _, err := chainmgr.InsertChain(blocks); err != nil {
				return fmt.Errorf("invalid block %v", err)
			}
			n = 0
			blocks = make(types.Blocks, batchSize)
		}
	}

	if n > 0 {
		if _, err := chainmgr.InsertChain(blocks[:n]); err != nil {
			return fmt.Errorf("invalid block %v", err)
		}
	}

	fmt.Printf("imported %d blocks\n", i)
	return nil
}

func ExportChain(chainmgr *core.ChainManager, fn string) error {
	fmt.Printf("exporting blockchain '%s'\n", fn)
	fh, err := os.OpenFile(fn, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm)
	if err != nil {
		return err
	}
	defer fh.Close()
	if err := chainmgr.Export(fh); err != nil {
		return err
	}
	fmt.Printf("exported blockchain\n")
	return nil
}
<commit_msg>Remove unused confirm() method<commit_after>/*
	This file is part of go-ethereum

	go-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	go-ethereum is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with go-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @authors
 * 	Jeffrey Wilcke <i@jev.io>
 * 	Viktor Tron <viktor@ethdev.com>
 */
package utils

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"os/signal"
	"regexp"
	"strings"

	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/core"
	"github.com/ethereum/go-ethereum/core/types"
	"github.com/ethereum/go-ethereum/eth"
	"github.com/ethereum/go-ethereum/logger"
	"github.com/ethereum/go-ethereum/logger/glog"
	"github.com/ethereum/go-ethereum/rlp"
	"github.com/peterh/liner"
)

var interruptCallbacks = []func(os.Signal){}

// Register interrupt handlers callbacks
func RegisterInterrupt(cb func(os.Signal)) {
	interruptCallbacks = append(interruptCallbacks, cb)
}

// go routine that call interrupt handlers in order of registering
func HandleInterrupt() {
	c := make(chan os.Signal, 1)
	go func() {
		signal.Notify(c, os.Interrupt)
		for sig := range c {
			glog.V(logger.Error).Infof("Shutting down (%v) ... \n", sig)
			RunInterruptCallbacks(sig)
		}
	}()
}

func RunInterruptCallbacks(sig os.Signal) {
	for _, cb := range interruptCallbacks {
		cb(sig)
	}
}

func openLogFile(Datadir string, filename string) *os.File {
	path := common.AbsolutePath(Datadir, filename)
	file, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		panic(fmt.Sprintf("error opening log file '%s': %v", filename, err))
	}
	return file
}

func PromptConfirm(prompt string) (bool, error) {
	var (
		input string
		err   error
	)
	prompt = prompt + " [y/N] "

	if liner.TerminalSupported() {
		lr := liner.NewLiner()
		defer lr.Close()
		input, err = lr.Prompt(prompt)
	} else {
		fmt.Print(prompt)
		input, err = bufio.NewReader(os.Stdin).ReadString('\n')
		fmt.Println()
	}

	if len(input) > 0 && strings.ToUpper(input[:1]) == "Y" {
		return true, nil
	} else {
		return false, nil
	}

	return false, err
}

func PromptPassword(prompt string, warnTerm bool) (string, error) {
	if liner.TerminalSupported() {
		lr := liner.NewLiner()
		defer lr.Close()
		return lr.PasswordPrompt(prompt)
	}
	if warnTerm {
		fmt.Println("!! Unsupported terminal, password will be echoed.")
	}
	fmt.Print(prompt)
	input, err := bufio.NewReader(os.Stdin).ReadString('\n')
	fmt.Println()
	return input, err
}

func initDataDir(Datadir string) {
	_, err := os.Stat(Datadir)
	if err != nil {
		if os.IsNotExist(err) {
			fmt.Printf("Data directory '%s' doesn't exist, creating it\n", Datadir)
			os.Mkdir(Datadir, 0777)
		}
	}
}

// Fatalf formats a message to standard output and exits the program.
func Fatalf(format string, args ...interface{}) {
	fmt.Fprintf(os.Stderr, "Fatal: "+format+"\n", args...)
	fmt.Fprintf(os.Stdout, "Fatal: "+format+"\n", args...)
	logger.Flush()
	os.Exit(1)
}

func StartEthereum(ethereum *eth.Ethereum) {
	glog.V(logger.Info).Infoln("Starting", ethereum.Name())
	if err := ethereum.Start(); err != nil {
		Fatalf("Error starting Ethereum: %v", err)
	}
	RegisterInterrupt(func(sig os.Signal) {
		ethereum.Stop()
		logger.Flush()
	})
}

func StartEthereumForTest(ethereum *eth.Ethereum) {
	glog.V(logger.Info).Infoln("Starting ", ethereum.Name())
	ethereum.StartForTest()
	RegisterInterrupt(func(sig os.Signal) {
		ethereum.Stop()
		logger.Flush()
	})
}

func FormatTransactionData(data string) []byte {
	d := common.StringToByteFunc(data, func(s string) (ret []byte) {
		slice := regexp.MustCompile("\\n|\\s").Split(s, 1000000000)
		for _, dataItem := range slice {
			d := common.FormatData(dataItem)
			ret = append(ret, d...)
		}
		return
	})

	return d
}

func ImportChain(chainmgr *core.ChainManager, fn string) error {
	fmt.Printf("importing blockchain '%s'\n", fn)
	fh, err := os.OpenFile(fn, os.O_RDONLY, os.ModePerm)
	if err != nil {
		return err
	}
	defer fh.Close()

	chainmgr.Reset()
	stream := rlp.NewStream(fh, 0)
	var i, n int

	batchSize := 2500
	blocks := make(types.Blocks, batchSize)

	for ; ; i++ {
		var b types.Block
		if err := stream.Decode(&b); err == io.EOF {
			break
		} else if err != nil {
			return fmt.Errorf("at block %d: %v", i, err)
		}

		blocks[n] = &b
		n++

		if n == batchSize {
			if _, err := chainmgr.InsertChain(blocks); err != nil {
				return fmt.Errorf("invalid block %v", err)
			}
			n = 0
			blocks = make(types.Blocks, batchSize)
		}
	}

	if n > 0 {
		if _, err := chainmgr.InsertChain(blocks[:n]); err != nil {
			return fmt.Errorf("invalid block %v", err)
		}
	}

	fmt.Printf("imported %d blocks\n", i)
	return nil
}

func ExportChain(chainmgr *core.ChainManager, fn string) error {
	fmt.Printf("exporting blockchain '%s'\n", fn)
	fh, err := os.OpenFile(fn, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm)
	if err != nil {
		return err
	}
	defer fh.Close()
	if err := chainmgr.Export(fh); err != nil {
		return err
	}
	fmt.Printf("exported blockchain\n")
	return nil
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strings"
	"text/template"
	"time"

	"github.com/gonuts/commander"
	"github.com/gonuts/flag"
)

func hwaf_make_cmd_waf_bdist_deb() *commander.Command {
	cmd := &commander.Command{
		Run:       hwaf_run_cmd_waf_bdist_deb,
		UsageLine: "bdist-deb [deb-name]",
		Short:     "create a DEB from the local project/packages",
		Long: `
bdist-deb creates a DEB from the local project/packages.

ex:
 $ hwaf bdist-deb
 $ hwaf bdist-deb -name=mana
 $ hwaf bdist-deb -name=mana -version=20130101
`,
		Flag: *flag.NewFlagSet("hwaf-bdist-deb", flag.ExitOnError),
	}
	cmd.Flag.Bool("q", true, "only print error and warning messages, all other output will be suppressed")
	cmd.Flag.String("name", "", "name of the binary distribution (default: project name)")
	cmd.Flag.String("version", "", "version of the binary distribution (default: project version)")
	cmd.Flag.String("release", "1", "release version of the binary distribution (default: 1)")
	cmd.Flag.String("cmtcfg", "", "CMTCFG quadruplet for the binary distribution (default: project CMTCFG)")
	cmd.Flag.String("spec", "", "DEB control file for the binary distribution")
	cmd.Flag.String("url", "", "URL for the DEB binary distribution")
	return cmd
}

func hwaf_run_cmd_waf_bdist_deb(cmd *commander.Command, args []string) {
	var err error
	n := "hwaf-" + cmd.Name()

	switch len(args) {
	case 0:
	default:
		err = fmt.Errorf("%s: too many arguments (%s)", n, len(args))
		handle_err(err)
	}

	quiet := cmd.Flag.Lookup("q").Value.Get().(bool)

	bdist_name := cmd.Flag.Lookup("name").Value.Get().(string)
	bdist_vers := cmd.Flag.Lookup("version").Value.Get().(string)
	bdist_release := cmd.Flag.Lookup("release").Value.Get().(string)
	bdist_cmtcfg := cmd.Flag.Lookup("cmtcfg").Value.Get().(string)
	bdist_spec := cmd.Flag.Lookup("spec").Value.Get().(string)

	bdist_url := cmd.Flag.Lookup("url").Value.Get().(string)
	if bdist_url == "" {
		bdist_url = "http://cern.ch/mana-fwk"
	}

	type DebInfo struct {
		Name      string // DEB package name
		Vers      string // DEB package version
		Release   string // DEB package release
		CmtCfg    string // DEB CMTCFG quadruplet
		BuildRoot string // DEB build directory
		Url       string // URL home page
		Arch      string // DEB architecture (32b/64b)
	}

	workdir, err := get_workarea_root()
	if err != nil {
		// not a git repo... assume we are at the root, then...
		workdir, err = os.Getwd()
	}
	handle_err(err)

	if bdist_name == "" {
		bdist_name = workdir
		bdist_name = filepath.Base(bdist_name)
	}
	if bdist_vers == "" {
		bdist_vers = time.Now().Format("20060102")
	}
	if bdist_cmtcfg == "" {
		// FIXME: get actual value from waf, somehow
		pinfo_name := filepath.Join(workdir, "__build__", "c4che", "_cache.py")
		if !path_exists(pinfo_name) {
			err = fmt.Errorf(
				"no such file [%s]. did you run \"hwaf configure\" ?",
				pinfo_name,
			)
			handle_err(err)
		}
		pinfo, err := NewProjectInfo(pinfo_name)
		handle_err(err)
		bdist_cmtcfg, err = pinfo.Get("CMTCFG")
		handle_err(err)
	}
	fname := bdist_name + "-" + bdist_vers + "-" + bdist_cmtcfg
	debbldroot, err := ioutil.TempDir("", "hwaf-deb-buildroot-")
	handle_err(err)
	defer os.RemoveAll(debbldroot)
	for _, dir := range []string{
		"DEBIAN",
	} {
		err = os.MkdirAll(filepath.Join(debbldroot, dir), 0700)
		handle_err(err)
	}

	specfile, err := os.Create(filepath.Join(debbldroot, "DEBIAN", "control"))
	handle_err(err)

	debarch := ""
	switch runtime.GOARCH {
	case "amd64":
		debarch = "amd64"
	case "386":
		debarch = "i386"
	default:
		err = fmt.Errorf("unhandled GOARCH [%s]", runtime.GOARCH)
		handle_err(err)
	}

	debinfos := DebInfo{
		Name:      bdist_name,
		Vers:      bdist_vers,
		Release:   bdist_release,
		CmtCfg:    bdist_cmtcfg,
		BuildRoot: debbldroot,
		Url:       bdist_url,
		Arch:      debarch,
	}

	// get tarball from 'hwaf bdist'...
	bdist_fname := strings.Replace(fname, ".deb", "", 1) + ".tar.gz"
	if !path_exists(bdist_fname) {
		err = fmt.Errorf("no such file [%s]. did you run \"hwaf bdist\" ?", bdist_fname)
		handle_err(err)
	}
	bdist_fname, err = filepath.Abs(bdist_fname)
	handle_err(err)
	{
		untar := exec.Command("tar", "-zxf", bdist_fname)
		untar.Dir = debbldroot
		untar.Stdin = os.Stdin
		untar.Stdout = os.Stdout
		untar.Stderr = os.Stderr
	}

	if bdist_spec != "" {
		bdist_spec = os.ExpandEnv(bdist_spec)
		bdist_spec, err = filepath.Abs(bdist_spec)
		handle_err(err)

		if !path_exists(bdist_spec) {
			err = fmt.Errorf("no such file [%s]", bdist_spec)
			handle_err(err)
		}
		user_spec, err := os.Open(bdist_spec)
		handle_err(err)
		defer user_spec.Close()

		_, err = io.Copy(specfile, user_spec)
		handle_err(err)
	} else {
		bdist_spec = specfile.Name()

		var spec_tmpl *template.Template
		spec_tmpl, err = template.New("SPEC").Parse(`
Package: {{.Name}}
Version: {{.Version}}-{{.Release}}
Section: devel
Priority: optional
Architecture: {{.Arch}}
Depends: coreutils
Maintainer: hwaf
Description: hwaf generated DEB for {{.Name}}
`) // */ for emacs...
		handle_err(err)

		err = spec_tmpl.Execute(specfile, debinfos)
		handle_err(err)
	}

	err = specfile.Sync()
	handle_err(err)
	err = specfile.Close()
	handle_err(err)

	if !strings.HasSuffix(fname, ".deb") {
		fname = fname + ".deb"
	}

	if !quiet {
		fmt.Printf("%s: building DEB [%s]...\n", n, fname)
	}

	debbld, err := exec.LookPath("dpkg-deb")
	handle_err(err)
	//dpkg-deb --build debian
	deb := exec.Command(debbld,
		"--build",
		".",
	)
	deb.Dir = debbldroot
	if !quiet {
		deb.Stdin = os.Stdin
		deb.Stdout = os.Stdout
		deb.Stderr = os.Stderr
	}
	err = deb.Run()
	handle_err(err)

	dst, err := os.Create(fname)
	handle_err(err)
	defer dst.Close()

	src, err := os.Open(filepath.Join(debbldroot, "..deb"))
	handle_err(err)
	defer src.Close()

	_, err = io.Copy(dst, src)
	handle_err(err)
	err = dst.Sync()
	handle_err(err)

	if !quiet {
		fmt.Printf("%s: building DEB [%s]...[ok]\n", n, fname)
	}
}

// EOF
<commit_msg>bdist-deb: typo<commit_after>package main

import (
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strings"
	"text/template"
	"time"

	"github.com/gonuts/commander"
	"github.com/gonuts/flag"
)

func hwaf_make_cmd_waf_bdist_deb() *commander.Command {
	cmd := &commander.Command{
		Run:       hwaf_run_cmd_waf_bdist_deb,
		UsageLine: "bdist-deb [deb-name]",
		Short:     "create a DEB from the local project/packages",
		Long: `
bdist-deb creates a DEB from the local project/packages.

ex:
 $ hwaf bdist-deb
 $ hwaf bdist-deb -name=mana
 $ hwaf bdist-deb -name=mana -version=20130101
`,
		Flag: *flag.NewFlagSet("hwaf-bdist-deb", flag.ExitOnError),
	}
	cmd.Flag.Bool("q", true, "only print error and warning messages, all other output will be suppressed")
	cmd.Flag.String("name", "", "name of the binary distribution (default: project name)")
	cmd.Flag.String("version", "", "version of the binary distribution (default: project version)")
	cmd.Flag.String("release", "1", "release version of the binary distribution (default: 1)")
	cmd.Flag.String("cmtcfg", "", "CMTCFG quadruplet for the binary distribution (default: project CMTCFG)")
	cmd.Flag.String("spec", "", "DEB control file for the binary distribution")
	cmd.Flag.String("url", "", "URL for the DEB binary distribution")
	return cmd
}

func hwaf_run_cmd_waf_bdist_deb(cmd *commander.Command, args []string) {
	var err error
	n := "hwaf-" + cmd.Name()

	switch len(args) {
	case 0:
	default:
		err = fmt.Errorf("%s: too many arguments (%s)", n, len(args))
		handle_err(err)
	}

	quiet := cmd.Flag.Lookup("q").Value.Get().(bool)

	bdist_name := cmd.Flag.Lookup("name").Value.Get().(string)
	bdist_vers := cmd.Flag.Lookup("version").Value.Get().(string)
	bdist_release := cmd.Flag.Lookup("release").Value.Get().(string)
	bdist_cmtcfg := cmd.Flag.Lookup("cmtcfg").Value.Get().(string)
	bdist_spec := cmd.Flag.Lookup("spec").Value.Get().(string)

	bdist_url := cmd.Flag.Lookup("url").Value.Get().(string)
	if bdist_url == "" {
		bdist_url = "http://cern.ch/mana-fwk"
	}

	type DebInfo struct {
		Name      string // DEB package name
		Vers      string // DEB package version
		Release   string // DEB package release
		CmtCfg    string // DEB CMTCFG quadruplet
		BuildRoot string // DEB build directory
		Url       string // URL home page
		Arch      string // DEB architecture (32b/64b)
	}

	workdir, err := get_workarea_root()
	if err != nil {
		// not a git repo... assume we are at the root, then...
		workdir, err = os.Getwd()
	}
	handle_err(err)

	if bdist_name == "" {
		bdist_name = workdir
		bdist_name = filepath.Base(bdist_name)
	}
	if bdist_vers == "" {
		bdist_vers = time.Now().Format("20060102")
	}
	if bdist_cmtcfg == "" {
		// FIXME: get actual value from waf, somehow
		pinfo_name := filepath.Join(workdir, "__build__", "c4che", "_cache.py")
		if !path_exists(pinfo_name) {
			err = fmt.Errorf(
				"no such file [%s]. did you run \"hwaf configure\" ?",
				pinfo_name,
			)
			handle_err(err)
		}
		pinfo, err := NewProjectInfo(pinfo_name)
		handle_err(err)
		bdist_cmtcfg, err = pinfo.Get("CMTCFG")
		handle_err(err)
	}
	fname := bdist_name + "-" + bdist_vers + "-" + bdist_cmtcfg
	debbldroot, err := ioutil.TempDir("", "hwaf-deb-buildroot-")
	handle_err(err)
	defer os.RemoveAll(debbldroot)
	for _, dir := range []string{
		"DEBIAN",
	} {
		err = os.MkdirAll(filepath.Join(debbldroot, dir), 0700)
		handle_err(err)
	}

	specfile, err := os.Create(filepath.Join(debbldroot, "DEBIAN", "control"))
	handle_err(err)

	debarch := ""
	switch runtime.GOARCH {
	case "amd64":
		debarch = "amd64"
	case "386":
		debarch = "i386"
	default:
		err = fmt.Errorf("unhandled GOARCH [%s]", runtime.GOARCH)
		handle_err(err)
	}

	debinfos := DebInfo{
		Name:      bdist_name,
		Vers:      bdist_vers,
		Release:   bdist_release,
		CmtCfg:    bdist_cmtcfg,
		BuildRoot: debbldroot,
		Url:       bdist_url,
		Arch:      debarch,
	}

	// get tarball from 'hwaf bdist'...
	bdist_fname := strings.Replace(fname, ".deb", "", 1) + ".tar.gz"
	if !path_exists(bdist_fname) {
		err = fmt.Errorf("no such file [%s]. did you run \"hwaf bdist\" ?", bdist_fname)
		handle_err(err)
	}
	bdist_fname, err = filepath.Abs(bdist_fname)
	handle_err(err)
	{
		untar := exec.Command("tar", "-zxf", bdist_fname)
		untar.Dir = debbldroot
		untar.Stdin = os.Stdin
		untar.Stdout = os.Stdout
		untar.Stderr = os.Stderr
	}

	if bdist_spec != "" {
		bdist_spec = os.ExpandEnv(bdist_spec)
		bdist_spec, err = filepath.Abs(bdist_spec)
		handle_err(err)

		if !path_exists(bdist_spec) {
			err = fmt.Errorf("no such file [%s]", bdist_spec)
			handle_err(err)
		}
		user_spec, err := os.Open(bdist_spec)
		handle_err(err)
		defer user_spec.Close()

		_, err = io.Copy(specfile, user_spec)
		handle_err(err)
	} else {
		bdist_spec = specfile.Name()

		var spec_tmpl *template.Template
		spec_tmpl, err = template.New("SPEC").Parse(`
Package: {{.Name}}
Version: {{.Vers}}-{{.Release}}
Section: devel
Priority: optional
Architecture: {{.Arch}}
Depends: coreutils
Maintainer: hwaf
Description: hwaf generated DEB for {{.Name}}
`) // */ for emacs...
		handle_err(err)

		err = spec_tmpl.Execute(specfile, debinfos)
		handle_err(err)
	}

	err = specfile.Sync()
	handle_err(err)
	err = specfile.Close()
	handle_err(err)

	if !strings.HasSuffix(fname, ".deb") {
		fname = fname + ".deb"
	}

	if !quiet {
		fmt.Printf("%s: building DEB [%s]...\n", n, fname)
	}

	debbld, err := exec.LookPath("dpkg-deb")
	handle_err(err)
	//dpkg-deb --build debian
	deb := exec.Command(debbld,
		"--build",
		".",
	)
	deb.Dir = debbldroot
	if !quiet {
		deb.Stdin = os.Stdin
		deb.Stdout = os.Stdout
		deb.Stderr = os.Stderr
	}
	err = deb.Run()
	handle_err(err)

	dst, err := os.Create(fname)
	handle_err(err)
	defer dst.Close()

	src, err := os.Open(filepath.Join(debbldroot, "..deb"))
	handle_err(err)
	defer src.Close()

	_, err = io.Copy(dst, src)
	handle_err(err)
	err = dst.Sync()
	handle_err(err)

	if !quiet {
		fmt.Printf("%s: building DEB [%s]...[ok]\n", n, fname)
	}
}

// EOF
<|endoftext|>


<commit_before>package metrics

import (
	"sync"
)

type Registry struct {
	scope   string
	metrics map[string]interface{}
	mutex   sync.RWMutex
}

type Collection interface {
	Metrics() map[string]interface{}
}

type Doer func(name string, metric interface{}) error

func NewRegistry() *Registry {
	return &Registry{
		metrics: make(map[string]interface{}),
	}
}

func (r *Registry) scopedName(name string) string {
	if r.scope != "" {
		return r.scope + "/" + name
	}
	return name
}

func (r *Registry) Scope(scope string) *Registry {
	return &Registry{
		scope:   r.scopedName(scope),
		metrics: r.metrics,
	}
}

func (r *Registry) Add(name string, metric interface{}) {
	r.mutex.Lock()
	r.metrics[r.scopedName(name)] = metric
	r.mutex.Unlock()
}

func (r *Registry) Remove(name string) {
	r.mutex.Lock()
	delete(r.metrics, r.scopedName(name))
	r.mutex.Unlock()
}

func (r *Registry) Do(f Doer) error {
	r.mutex.RLock()
	defer r.mutex.RUnlock()
	return do(r.metrics, f)
}

func do(metrics map[string]interface{}, f Doer) error {
	for name, metric := range metrics {
		if collection, ok := metric.(Collection); ok {
			met := collection.Metrics()
			if met != nil {
				if err := do(met, f); err != nil {
					return err
				}
			}
		} else if err := f(name, metric); err != nil {
			return err
		}
	}
	return nil
}
<commit_msg>Make sure to scope Collection s<commit_after>package metrics

import (
	"sync"
)

type Registry struct {
	scope   string
	metrics map[string]interface{}
	mutex   sync.RWMutex
}

type Collection interface {
	Metrics() map[string]interface{}
}

type Doer func(name string, metric interface{}) error

func NewRegistry() *Registry {
	return &Registry{
		metrics: make(map[string]interface{}),
	}
}

func (r *Registry) scopedName(name string) string {
	if r.scope != "" {
		return r.scope + "/" + name
	}
	return name
}

func (r *Registry) Scope(scope string) *Registry {
	return &Registry{
		scope:   r.scopedName(scope),
		metrics: r.metrics,
	}
}

func (r *Registry) Add(name string, metric interface{}) {
	r.mutex.Lock()
	r.metrics[r.scopedName(name)] = metric
	r.mutex.Unlock()
}

func (r *Registry) Remove(name string) {
	r.mutex.Lock()
	delete(r.metrics, r.scopedName(name))
	r.mutex.Unlock()
}

func (r *Registry) Do(f Doer) error {
	r.mutex.RLock()
	defer r.mutex.RUnlock()
	return do("", r.metrics, f)
}

func do(scope string, metrics map[string]interface{}, f Doer) error {
	for name, metric := range metrics {
		if scope != "" {
			name = scope + "/" + name
		}
		if collection, ok := metric.(Collection); ok {
			met := collection.Metrics()
			if met != nil {
				if err := do(name, met, f); err != nil {
					return err
				}
			}
		} else if err := f(name, metric); err != nil {
			return err
		}
	}
	return nil
}
<|endoftext|>


<commit_before>package main

/**
 * Barista Server
 *
 * @author: Anant Bhardwaj
 * @date: 03/23/2014
 */

import "fmt"
import "barista"
import "git.apache.org/thrift.git/lib/go/thrift"

const ADDR = "localhost:9000"

func main() {
  protocolFactory := thrift.NewTBinaryProtocolFactoryDefault()
  transportFactory := thrift.NewTTransportFactory()
  transport, err := thrift.NewTServerSocket(ADDR)

  if err != nil {
    fmt.Println("Error: ", err)
    return
  }

  handler := NewBaristaHandler([]string {ADDR}, 0)
  processor := barista.NewBaristaProcessor(handler)
  server := thrift.NewTSimpleServer4(processor, transport, transportFactory, protocolFactory)

  fmt.Println("Starting the Barista server on ", ADDR)
  server.Serve()
}<commit_msg>find address<commit_after>package main

/**
 * Barista Server
 *
 * @author: Anant Bhardwaj
 * @date: 03/23/2014
 */

import "fmt"
import "barista"
import "git.apache.org/thrift.git/lib/go/thrift"
import "os"

const PORT = ":9000"

func main() {
  protocolFactory := thrift.NewTBinaryProtocolFactoryDefault()
  transportFactory := thrift.NewTTransportFactory()

  addr := os.Hostname() + PORT
  fmt.Println("addr: ", addr)
  transport, err := thrift.NewTServerSocket(addr)

  if err != nil {
    fmt.Println("Error: ", err)
    return
  }

  handler := NewBaristaHandler([]string {addr}, 0)
  processor := barista.NewBaristaProcessor(handler)
  server := thrift.NewTSimpleServer4(processor, transport, transportFactory, protocolFactory)

  fmt.Println("Starting the Barista server on ", addr)
  server.Serve()
}<|endoftext|>


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

// +build windows

// Package win32 implements a partial shiny screen driver using the Win32 API.
// It provides window, lifecycle, key, and mouse management, but no drawing.
// That is left to windriver (using GDI) or gldriver (using DirectX via ANGLE).
package win32 // import "golang.org/x/exp/shiny/driver/internal/win32"

import (
	"fmt"
	"runtime"
	"syscall"
	"unsafe"

	"golang.org/x/exp/shiny/screen"
	"golang.org/x/mobile/event/key"
	"golang.org/x/mobile/event/lifecycle"
	"golang.org/x/mobile/event/mouse"
	"golang.org/x/mobile/event/paint"
	"golang.org/x/mobile/event/size"
	"golang.org/x/mobile/geom"
)

// screenHWND is the handle to the "Screen window".
// The Screen window encapsulates all screen.Screen operations
// in an actual Windows window so they all run on the main thread.
// Since any messages sent to a window will be executed on the
// main thread, we can safely use the messages below.
var screenHWND HWND

const (
	msgCreateWindow = _WM_USER + iota
	msgMainCallback
	msgShow
	msgQuit
	msgLast
)

var nextWM uint32 = msgLast

func newWindow(opts *screen.NewWindowOptions) (HWND, error) {
	// TODO(brainman): convert windowClass to *uint16 once (in initWindowClass)
	wcname, err := syscall.UTF16PtrFromString(windowClass)
	if err != nil {
		return 0, err
	}
	title, err := syscall.UTF16PtrFromString("Shiny Window")
	if err != nil {
		return 0, err
	}
	hwnd, err := _CreateWindowEx(0,
		wcname, title,
		_WS_OVERLAPPEDWINDOW,
		_CW_USEDEFAULT, _CW_USEDEFAULT,
		_CW_USEDEFAULT, _CW_USEDEFAULT,
		0, 0, hThisInstance, 0)
	if err != nil {
		return 0, err
	}
	// TODO(andlabs): use proper nCmdShow
	// TODO(andlabs): call UpdateWindow()

	return hwnd, nil
}

// Show shows a newly created window.
// It sends the appropriate lifecycle events, makes the window appear
// on the screen, and sends an initial size event.
//
// This is a separate step from NewWindow to give the driver a chance
// to setup its internal state for a window before events start being
// delivered.
func Show(hwnd HWND) {
	SendMessage(hwnd, msgShow, 0, 0)
}

func Release(hwnd HWND) {
	// TODO(andlabs): check for errors from this?
	// TODO(andlabs): remove unsafe
	_DestroyWindow(hwnd)
	// TODO(andlabs): what happens if we're still painting?
}

func sendFocus(hwnd HWND, uMsg uint32, wParam, lParam uintptr) (lResult uintptr) {
	switch uMsg {
	case _WM_SETFOCUS:
		LifecycleEvent(hwnd, lifecycle.StageFocused)
	case _WM_KILLFOCUS:
		LifecycleEvent(hwnd, lifecycle.StageVisible)
	default:
		panic(fmt.Sprintf("unexpected focus message: %d", uMsg))
	}
	return _DefWindowProc(hwnd, uMsg, wParam, lParam)
}

func sendShow(hwnd HWND, uMsg uint32, wParam, lParam uintptr) (lResult uintptr) {
	LifecycleEvent(hwnd, lifecycle.StageVisible)
	_ShowWindow(hwnd, _SW_SHOWDEFAULT)
	sendSize(hwnd)
	return 0
}

func sendSizeEvent(hwnd HWND, uMsg uint32, wParam, lParam uintptr) (lResult uintptr) {
	wp := (*_WINDOWPOS)(unsafe.Pointer(lParam))
	if wp.Flags&_SWP_NOSIZE != 0 {
		return 0
	}
	sendSize(hwnd)
	return 0
}

func sendSize(hwnd HWND) {
	var r _RECT
	if err := _GetClientRect(hwnd, &r); err != nil {
		panic(err) // TODO(andlabs)
	}

	width := int(r.Right - r.Left)
	height := int(r.Bottom - r.Top)

	// TODO(andlabs): don't assume that PixelsPerPt == 1
	SizeEvent(hwnd, size.Event{
		WidthPx:     width,
		HeightPx:    height,
		WidthPt:     geom.Pt(width),
		HeightPt:    geom.Pt(height),
		PixelsPerPt: 1,
	})
}

func sendMouseEvent(hwnd HWND, uMsg uint32, wParam, lParam uintptr) (lResult uintptr) {
	e := mouse.Event{
		X:         float32(_GET_X_LPARAM(lParam)),
		Y:         float32(_GET_Y_LPARAM(lParam)),
		Modifiers: keyModifiers(),
	}

	switch uMsg {
	case _WM_MOUSEMOVE, _WM_MOUSEWHEEL:
		e.Direction = mouse.DirNone
	case _WM_LBUTTONDOWN, _WM_MBUTTONDOWN, _WM_RBUTTONDOWN:
		e.Direction = mouse.DirPress
	case _WM_LBUTTONUP, _WM_MBUTTONUP, _WM_RBUTTONUP:
		e.Direction = mouse.DirRelease
	default:
		panic("sendMouseEvent() called on non-mouse message")
	}

	switch uMsg {
	case _WM_MOUSEMOVE:
		switch {
		case wParam&_MK_LBUTTON == _MK_LBUTTON:
			e.Button = mouse.ButtonLeft
		case wParam&_MK_MBUTTON == _MK_MBUTTON:
			e.Button = mouse.ButtonMiddle
		case wParam&_MK_RBUTTON == _MK_RBUTTON:
			e.Button = mouse.ButtonRight
		default:
			// TODO: send move events when no buttons are held down?
			return 0
		}
	case _WM_LBUTTONDOWN, _WM_LBUTTONUP:
		e.Button = mouse.ButtonLeft
	case _WM_MBUTTONDOWN, _WM_MBUTTONUP:
		e.Button = mouse.ButtonMiddle
	case _WM_RBUTTONDOWN, _WM_RBUTTONUP:
		e.Button = mouse.ButtonRight
	case _WM_MOUSEWHEEL:
		delta := _GET_WHEEL_DELTA_WPARAM(wParam) / _WHEEL_DELTA
		switch {
		case delta > 0:
			e.Button = mouse.ButtonWheelUp
		case delta < 0:
			e.Button = mouse.ButtonWheelDown
			delta = -delta
		default:
			return
		}
		for delta > 0 {
			MouseEvent(hwnd, e)
			delta--
		}
		return
	}

	MouseEvent(hwnd, e)

	return 0
}

// Precondition: this is called in immediate response to the message that triggered the event (so not after w.Send).
func keyModifiers() (m key.Modifiers) {
	down := func(x int32) bool {
		// GetKeyState gets the key state at the time of the message, so this is what we want.
		return _GetKeyState(x)&0x80 != 0
	}

	if down(_VK_CONTROL) {
		m |= key.ModControl
	}
	if down(_VK_MENU) {
		m |= key.ModAlt
	}
	if down(_VK_SHIFT) {
		m |= key.ModShift
	}
	if down(_VK_LWIN) || down(_VK_RWIN) {
		m |= key.ModMeta
	}
	return m
}

var (
	MouseEvent     func(hwnd HWND, e mouse.Event)
	PaintEvent     func(hwnd HWND, e paint.Event)
	SizeEvent      func(hwnd HWND, e size.Event)
	KeyEvent       func(hwnd HWND, e key.Event)
	LifecycleEvent func(hwnd HWND, e lifecycle.Stage)
)

func sendPaint(hwnd HWND, uMsg uint32, wParam, lParam uintptr) (lResult uintptr) {
	PaintEvent(hwnd, paint.Event{})
	return _DefWindowProc(hwnd, uMsg, wParam, lParam)
}

func screenWindowWndProc(hwnd HWND, uMsg uint32, wParam uintptr, lParam uintptr) (lResult uintptr) {
	switch uMsg {
	case msgCreateWindow:
		p := (*newWindowParams)(unsafe.Pointer(lParam))
		p.w, p.err = newWindow(p.opts)
	case msgMainCallback:
		go func() {
			mainCallback()
			SendMessage(screenHWND, msgQuit, 0, 0)
		}()
	case msgQuit:
		_PostQuitMessage(0)
	default:
		return _DefWindowProc(hwnd, uMsg, wParam, lParam)
	}
	return 0
}

var windowMsgs = map[uint32]func(hwnd HWND, uMsg uint32, wParam, lParam uintptr) (lResult uintptr){
	_WM_SETFOCUS:         sendFocus,
	_WM_KILLFOCUS:        sendFocus,
	_WM_PAINT:            sendPaint,
	msgShow:              sendShow,
	_WM_WINDOWPOSCHANGED: sendSizeEvent,

	_WM_LBUTTONDOWN: sendMouseEvent,
	_WM_LBUTTONUP:   sendMouseEvent,
	_WM_MBUTTONDOWN: sendMouseEvent,
	_WM_MBUTTONUP:   sendMouseEvent,
	_WM_RBUTTONDOWN: sendMouseEvent,
	_WM_RBUTTONUP:   sendMouseEvent,
	_WM_MOUSEMOVE:   sendMouseEvent,
	_WM_MOUSEWHEEL:  sendMouseEvent,

	_WM_KEYDOWN: sendKeyEvent,
	_WM_KEYUP:   sendKeyEvent,
	// TODO case _WM_SYSKEYDOWN, _WM_SYSKEYUP:
}

func AddWindowMsg(fn func(hwnd HWND, uMsg uint32, wParam, lParam uintptr)) uint32 {
	uMsg := nextWM
	nextWM++
	windowMsgs[uMsg] = func(hwnd HWND, uMsg uint32, wParam, lParam uintptr) uintptr {
		fn(hwnd, uMsg, wParam, lParam)
		return 0
	}
	return uMsg
}

func windowWndProc(hwnd HWND, uMsg uint32, wParam uintptr, lParam uintptr) (lResult uintptr) {
	fn := windowMsgs[uMsg]
	if fn != nil {
		return fn(hwnd, uMsg, wParam, lParam)
	}
	return _DefWindowProc(hwnd, uMsg, wParam, lParam)
}

type newWindowParams struct {
	opts *screen.NewWindowOptions
	w    HWND
	err  error
}

func NewWindow(opts *screen.NewWindowOptions) (HWND, error) {
	var p newWindowParams
	p.opts = opts
	SendMessage(screenHWND, msgCreateWindow, 0, uintptr(unsafe.Pointer(&p)))
	return p.w, p.err
}

const windowClass = "shiny_Window"

func initWindowClass() (err error) {
	wcname, err := syscall.UTF16PtrFromString(windowClass)
	if err != nil {
		return err
	}
	_, err = _RegisterClass(&_WNDCLASS{
		LpszClassName: wcname,
		LpfnWndProc:   syscall.NewCallback(windowWndProc),
		HIcon:         hDefaultIcon,
		HCursor:       hDefaultCursor,
		HInstance:     hThisInstance,
		// TODO(andlabs): change this to something else? NULL? the hollow brush?
		HbrBackground: syscall.Handle(_COLOR_BTNFACE + 1),
	})
	return err
}

func initScreenWindow() (err error) {
	const screenWindowClass = "shiny_ScreenWindow"
	swc, err := syscall.UTF16PtrFromString(screenWindowClass)
	if err != nil {
		return err
	}
	emptyString, err := syscall.UTF16PtrFromString("")
	if err != nil {
		return err
	}
	wc := _WNDCLASS{
		LpszClassName: swc,
		LpfnWndProc:   syscall.NewCallback(screenWindowWndProc),
		HIcon:         hDefaultIcon,
		HCursor:       hDefaultCursor,
		HInstance:     hThisInstance,
		HbrBackground: syscall.Handle(_COLOR_BTNFACE + 1),
	}
	_, err = _RegisterClass(&wc)
	if err != nil {
		return err
	}
	screenHWND, err = _CreateWindowEx(0,
		swc, emptyString,
		_WS_OVERLAPPEDWINDOW,
		_CW_USEDEFAULT, _CW_USEDEFAULT,
		_CW_USEDEFAULT, _CW_USEDEFAULT,
		_HWND_MESSAGE, 0, hThisInstance, 0)
	if err != nil {
		return err
	}
	return nil
}

var (
	hDefaultIcon   syscall.Handle
	hDefaultCursor syscall.Handle
	hThisInstance  syscall.Handle
)

func initCommon() (err error) {
	hDefaultIcon, err = _LoadIcon(0, _IDI_APPLICATION)
	if err != nil {
		return err
	}
	hDefaultCursor, err = _LoadCursor(0, _IDC_ARROW)
	if err != nil {
		return err
	}
	// TODO(andlabs) hThisInstance
	return nil
}

var mainCallback func()

func Main(f func()) (retErr error) {
	// It does not matter which OS thread we are on.
	// All that matters is that we confine all UI operations
	// to the thread that created the respective window.
	runtime.LockOSThread()

	if err := initCommon(); err != nil {
		return err
	}

	if err := initScreenWindow(); err != nil {
		return err
	}
	defer func() {
		// TODO(andlabs): log an error if this fails?
		_DestroyWindow(screenHWND)
		// TODO(andlabs): unregister window class
	}()

	if err := initWindowClass(); err != nil {
		return err
	}

	// Prime the pump.
	mainCallback = f
	_PostMessage(screenHWND, msgMainCallback, 0, 0)

	// Main message pump.
	var m _MSG
	for {
		done, err := _GetMessage(&m, 0, 0, 0)
		if err != nil {
			return fmt.Errorf("win32 GetMessage failed: %v", err)
		}
		if done == 0 { // WM_QUIT
			break
		}
		_TranslateMessage(&m)
		_DispatchMessage(&m)
	}

	return nil
}
<commit_msg>x/exp/shiny/driver/internal/win32: Use screen.NewWindowOptions<commit_after>// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build windows

// Package win32 implements a partial shiny screen driver using the Win32 API.
// It provides window, lifecycle, key, and mouse management, but no drawing.
// That is left to windriver (using GDI) or gldriver (using DirectX via ANGLE).
package win32 // import "golang.org/x/exp/shiny/driver/internal/win32"

import (
	"fmt"
	"runtime"
	"syscall"
	"unsafe"

	"golang.org/x/exp/shiny/screen"
	"golang.org/x/mobile/event/key"
	"golang.org/x/mobile/event/lifecycle"
	"golang.org/x/mobile/event/mouse"
	"golang.org/x/mobile/event/paint"
	"golang.org/x/mobile/event/size"
	"golang.org/x/mobile/geom"
)

// screenHWND is the handle to the "Screen window".
// The Screen window encapsulates all screen.Screen operations
// in an actual Windows window so they all run on the main thread.
// Since any messages sent to a window will be executed on the
// main thread, we can safely use the messages below.
var screenHWND HWND

const (
	msgCreateWindow = _WM_USER + iota
	msgMainCallback
	msgShow
	msgQuit
	msgLast
)

var nextWM uint32 = msgLast

func newWindow(opts *screen.NewWindowOptions) (HWND, error) {
	// TODO(brainman): convert windowClass to *uint16 once (in initWindowClass)
	wcname, err := syscall.UTF16PtrFromString(windowClass)
	if err != nil {
		return 0, err
	}
	title, err := syscall.UTF16PtrFromString("Shiny Window")
	if err != nil {
		return 0, err
	}
	w, h := _CW_USEDEFAULT, _CW_USEDEFAULT
	if opts != nil {
		if opts.Width > 0 {
			w = opts.Width
		}
		if opts.Height > 0 {
			w = opts.Height
		}
	}
	hwnd, err := _CreateWindowEx(0,
		wcname, title,
		_WS_OVERLAPPEDWINDOW,
		_CW_USEDEFAULT, _CW_USEDEFAULT,
		int32(w), int32(h),
		0, 0, hThisInstance, 0)
	if err != nil {
		return 0, err
	}
	// TODO(andlabs): use proper nCmdShow
	// TODO(andlabs): call UpdateWindow()

	return hwnd, nil
}

// Show shows a newly created window.
// It sends the appropriate lifecycle events, makes the window appear
// on the screen, and sends an initial size event.
//
// This is a separate step from NewWindow to give the driver a chance
// to setup its internal state for a window before events start being
// delivered.
func Show(hwnd HWND) {
	SendMessage(hwnd, msgShow, 0, 0)
}

func Release(hwnd HWND) {
	// TODO(andlabs): check for errors from this?
	// TODO(andlabs): remove unsafe
	_DestroyWindow(hwnd)
	// TODO(andlabs): what happens if we're still painting?
}

func sendFocus(hwnd HWND, uMsg uint32, wParam, lParam uintptr) (lResult uintptr) {
	switch uMsg {
	case _WM_SETFOCUS:
		LifecycleEvent(hwnd, lifecycle.StageFocused)
	case _WM_KILLFOCUS:
		LifecycleEvent(hwnd, lifecycle.StageVisible)
	default:
		panic(fmt.Sprintf("unexpected focus message: %d", uMsg))
	}
	return _DefWindowProc(hwnd, uMsg, wParam, lParam)
}

func sendShow(hwnd HWND, uMsg uint32, wParam, lParam uintptr) (lResult uintptr) {
	LifecycleEvent(hwnd, lifecycle.StageVisible)
	_ShowWindow(hwnd, _SW_SHOWDEFAULT)
	sendSize(hwnd)
	return 0
}

func sendSizeEvent(hwnd HWND, uMsg uint32, wParam, lParam uintptr) (lResult uintptr) {
	wp := (*_WINDOWPOS)(unsafe.Pointer(lParam))
	if wp.Flags&_SWP_NOSIZE != 0 {
		return 0
	}
	sendSize(hwnd)
	return 0
}

func sendSize(hwnd HWND) {
	var r _RECT
	if err := _GetClientRect(hwnd, &r); err != nil {
		panic(err) // TODO(andlabs)
	}

	width := int(r.Right - r.Left)
	height := int(r.Bottom - r.Top)

	// TODO(andlabs): don't assume that PixelsPerPt == 1
	SizeEvent(hwnd, size.Event{
		WidthPx:     width,
		HeightPx:    height,
		WidthPt:     geom.Pt(width),
		HeightPt:    geom.Pt(height),
		PixelsPerPt: 1,
	})
}

func sendMouseEvent(hwnd HWND, uMsg uint32, wParam, lParam uintptr) (lResult uintptr) {
	e := mouse.Event{
		X:         float32(_GET_X_LPARAM(lParam)),
		Y:         float32(_GET_Y_LPARAM(lParam)),
		Modifiers: keyModifiers(),
	}

	switch uMsg {
	case _WM_MOUSEMOVE, _WM_MOUSEWHEEL:
		e.Direction = mouse.DirNone
	case _WM_LBUTTONDOWN, _WM_MBUTTONDOWN, _WM_RBUTTONDOWN:
		e.Direction = mouse.DirPress
	case _WM_LBUTTONUP, _WM_MBUTTONUP, _WM_RBUTTONUP:
		e.Direction = mouse.DirRelease
	default:
		panic("sendMouseEvent() called on non-mouse message")
	}

	switch uMsg {
	case _WM_MOUSEMOVE:
		switch {
		case wParam&_MK_LBUTTON == _MK_LBUTTON:
			e.Button = mouse.ButtonLeft
		case wParam&_MK_MBUTTON == _MK_MBUTTON:
			e.Button = mouse.ButtonMiddle
		case wParam&_MK_RBUTTON == _MK_RBUTTON:
			e.Button = mouse.ButtonRight
		default:
			// TODO: send move events when no buttons are held down?
			return 0
		}
	case _WM_LBUTTONDOWN, _WM_LBUTTONUP:
		e.Button = mouse.ButtonLeft
	case _WM_MBUTTONDOWN, _WM_MBUTTONUP:
		e.Button = mouse.ButtonMiddle
	case _WM_RBUTTONDOWN, _WM_RBUTTONUP:
		e.Button = mouse.ButtonRight
	case _WM_MOUSEWHEEL:
		delta := _GET_WHEEL_DELTA_WPARAM(wParam) / _WHEEL_DELTA
		switch {
		case delta > 0:
			e.Button = mouse.ButtonWheelUp
		case delta < 0:
			e.Button = mouse.ButtonWheelDown
			delta = -delta
		default:
			return
		}
		for delta > 0 {
			MouseEvent(hwnd, e)
			delta--
		}
		return
	}

	MouseEvent(hwnd, e)

	return 0
}

// Precondition: this is called in immediate response to the message that triggered the event (so not after w.Send).
func keyModifiers() (m key.Modifiers) {
	down := func(x int32) bool {
		// GetKeyState gets the key state at the time of the message, so this is what we want.
		return _GetKeyState(x)&0x80 != 0
	}

	if down(_VK_CONTROL) {
		m |= key.ModControl
	}
	if down(_VK_MENU) {
		m |= key.ModAlt
	}
	if down(_VK_SHIFT) {
		m |= key.ModShift
	}
	if down(_VK_LWIN) || down(_VK_RWIN) {
		m |= key.ModMeta
	}
	return m
}

var (
	MouseEvent     func(hwnd HWND, e mouse.Event)
	PaintEvent     func(hwnd HWND, e paint.Event)
	SizeEvent      func(hwnd HWND, e size.Event)
	KeyEvent       func(hwnd HWND, e key.Event)
	LifecycleEvent func(hwnd HWND, e lifecycle.Stage)
)

func sendPaint(hwnd HWND, uMsg uint32, wParam, lParam uintptr) (lResult uintptr) {
	PaintEvent(hwnd, paint.Event{})
	return _DefWindowProc(hwnd, uMsg, wParam, lParam)
}

func screenWindowWndProc(hwnd HWND, uMsg uint32, wParam uintptr, lParam uintptr) (lResult uintptr) {
	switch uMsg {
	case msgCreateWindow:
		p := (*newWindowParams)(unsafe.Pointer(lParam))
		p.w, p.err = newWindow(p.opts)
	case msgMainCallback:
		go func() {
			mainCallback()
			SendMessage(screenHWND, msgQuit, 0, 0)
		}()
	case msgQuit:
		_PostQuitMessage(0)
	default:
		return _DefWindowProc(hwnd, uMsg, wParam, lParam)
	}
	return 0
}

var windowMsgs = map[uint32]func(hwnd HWND, uMsg uint32, wParam, lParam uintptr) (lResult uintptr){
	_WM_SETFOCUS:         sendFocus,
	_WM_KILLFOCUS:        sendFocus,
	_WM_PAINT:            sendPaint,
	msgShow:              sendShow,
	_WM_WINDOWPOSCHANGED: sendSizeEvent,

	_WM_LBUTTONDOWN: sendMouseEvent,
	_WM_LBUTTONUP:   sendMouseEvent,
	_WM_MBUTTONDOWN: sendMouseEvent,
	_WM_MBUTTONUP:   sendMouseEvent,
	_WM_RBUTTONDOWN: sendMouseEvent,
	_WM_RBUTTONUP:   sendMouseEvent,
	_WM_MOUSEMOVE:   sendMouseEvent,
	_WM_MOUSEWHEEL:  sendMouseEvent,

	_WM_KEYDOWN: sendKeyEvent,
	_WM_KEYUP:   sendKeyEvent,
	// TODO case _WM_SYSKEYDOWN, _WM_SYSKEYUP:
}

func AddWindowMsg(fn func(hwnd HWND, uMsg uint32, wParam, lParam uintptr)) uint32 {
	uMsg := nextWM
	nextWM++
	windowMsgs[uMsg] = func(hwnd HWND, uMsg uint32, wParam, lParam uintptr) uintptr {
		fn(hwnd, uMsg, wParam, lParam)
		return 0
	}
	return uMsg
}

func windowWndProc(hwnd HWND, uMsg uint32, wParam uintptr, lParam uintptr) (lResult uintptr) {
	fn := windowMsgs[uMsg]
	if fn != nil {
		return fn(hwnd, uMsg, wParam, lParam)
	}
	return _DefWindowProc(hwnd, uMsg, wParam, lParam)
}

type newWindowParams struct {
	opts *screen.NewWindowOptions
	w    HWND
	err  error
}

func NewWindow(opts *screen.NewWindowOptions) (HWND, error) {
	var p newWindowParams
	p.opts = opts
	SendMessage(screenHWND, msgCreateWindow, 0, uintptr(unsafe.Pointer(&p)))
	return p.w, p.err
}

const windowClass = "shiny_Window"

func initWindowClass() (err error) {
	wcname, err := syscall.UTF16PtrFromString(windowClass)
	if err != nil {
		return err
	}
	_, err = _RegisterClass(&_WNDCLASS{
		LpszClassName: wcname,
		LpfnWndProc:   syscall.NewCallback(windowWndProc),
		HIcon:         hDefaultIcon,
		HCursor:       hDefaultCursor,
		HInstance:     hThisInstance,
		// TODO(andlabs): change this to something else? NULL? the hollow brush?
		HbrBackground: syscall.Handle(_COLOR_BTNFACE + 1),
	})
	return err
}

func initScreenWindow() (err error) {
	const screenWindowClass = "shiny_ScreenWindow"
	swc, err := syscall.UTF16PtrFromString(screenWindowClass)
	if err != nil {
		return err
	}
	emptyString, err := syscall.UTF16PtrFromString("")
	if err != nil {
		return err
	}
	wc := _WNDCLASS{
		LpszClassName: swc,
		LpfnWndProc:   syscall.NewCallback(screenWindowWndProc),
		HIcon:         hDefaultIcon,
		HCursor:       hDefaultCursor,
		HInstance:     hThisInstance,
		HbrBackground: syscall.Handle(_COLOR_BTNFACE + 1),
	}
	_, err = _RegisterClass(&wc)
	if err != nil {
		return err
	}
	screenHWND, err = _CreateWindowEx(0,
		swc, emptyString,
		_WS_OVERLAPPEDWINDOW,
		_CW_USEDEFAULT, _CW_USEDEFAULT,
		_CW_USEDEFAULT, _CW_USEDEFAULT,
		_HWND_MESSAGE, 0, hThisInstance, 0)
	if err != nil {
		return err
	}
	return nil
}

var (
	hDefaultIcon   syscall.Handle
	hDefaultCursor syscall.Handle
	hThisInstance  syscall.Handle
)

func initCommon() (err error) {
	hDefaultIcon, err = _LoadIcon(0, _IDI_APPLICATION)
	if err != nil {
		return err
	}
	hDefaultCursor, err = _LoadCursor(0, _IDC_ARROW)
	if err != nil {
		return err
	}
	// TODO(andlabs) hThisInstance
	return nil
}

var mainCallback func()

func Main(f func()) (retErr error) {
	// It does not matter which OS thread we are on.
	// All that matters is that we confine all UI operations
	// to the thread that created the respective window.
	runtime.LockOSThread()

	if err := initCommon(); err != nil {
		return err
	}

	if err := initScreenWindow(); err != nil {
		return err
	}
	defer func() {
		// TODO(andlabs): log an error if this fails?
		_DestroyWindow(screenHWND)
		// TODO(andlabs): unregister window class
	}()

	if err := initWindowClass(); err != nil {
		return err
	}

	// Prime the pump.
	mainCallback = f
	_PostMessage(screenHWND, msgMainCallback, 0, 0)

	// Main message pump.
	var m _MSG
	for {
		done, err := _GetMessage(&m, 0, 0, 0)
		if err != nil {
			return fmt.Errorf("win32 GetMessage failed: %v", err)
		}
		if done == 0 { // WM_QUIT
			break
		}
		_TranslateMessage(&m)
		_DispatchMessage(&m)
	}

	return nil
}
<|endoftext|>


<commit_before>package collect

import (
	"bytes"
	"compress/gzip"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"os"
	"sync/atomic"
	"time"

	"bosun.org/metadata"
	"bosun.org/opentsdb"
	"bosun.org/slog"
	"github.com/GROpenSourceDev/go-ntlm-auth/ntlm"
)

func queuer() {
	for dp := range tchan {
		if err := dp.Clean(); err != nil {
			atomic.AddInt64(&dropped, 1)
			continue // if anything gets this far that can't be made valid, just drop it silently.
		}
		qlock.Lock()
		for {
			if len(queue) > MaxQueueLen {
				atomic.AddInt64(&dropped, 1)
				break
			}
			queue = append(queue, dp)
			select {
			case dp = <-tchan:
				continue
			default:
			}
			break
		}
		qlock.Unlock()
	}
}

// Locks the queue and sends all datapoints. Intended to be used as scollector exits.
func Flush() {
	flushData()
	metadata.FlushMetadata()
	qlock.Lock()
	for len(queue) > 0 {
		i := len(queue)
		if i > BatchSize {
			i = BatchSize
		}
		sending := queue[:i]
		queue = queue[i:]
		if Debug {
			slog.Infof("sending: %d, remaining: %d", i, len(queue))
		}
		sendBatch(sending)
	}
	qlock.Unlock()
}

func send() {
	for {
		qlock.Lock()
		if i := len(queue); i > 0 {
			if i > BatchSize {
				i = BatchSize
			}
			sending := queue[:i]
			queue = queue[i:]
			if Debug {
				slog.Infof("sending: %d, remaining: %d", i, len(queue))
			}
			qlock.Unlock()
			Sample("collect.post.batchsize", Tags, float64(len(sending)))
			sendBatch(sending)
		} else {
			qlock.Unlock()
			time.Sleep(time.Second)
		}
	}
}

func sendBatch(batch []*opentsdb.DataPoint) {
	if Print {
		for _, d := range batch {
			j, err := d.MarshalJSON()
			if err != nil {
				slog.Error(err)
			}
			slog.Info(string(j))
		}
		recordSent(len(batch))
		return
	}
	now := time.Now()
	resp, err := SendDataPoints(batch, tsdbURL)
	if err == nil {
		defer resp.Body.Close()
	}
	d := time.Since(now).Nanoseconds() / 1e6
	Sample("collect.post.duration", Tags, float64(d))
	Add("collect.post.total_duration", Tags, d)
	Add("collect.post.count", Tags, 1)
	// Some problem with connecting to the server; retry later.
	if err != nil || resp.StatusCode != http.StatusNoContent {
		if err != nil {
			Add("collect.post.error", Tags, 1)
			slog.Error(err)
		} else if resp.StatusCode != http.StatusNoContent {
			Add("collect.post.bad_status", Tags, 1)
			slog.Errorln(resp.Status)
			body, err := ioutil.ReadAll(resp.Body)
			if err != nil {
				slog.Error(err)
			}
			if len(body) > 0 {
				slog.Error(string(body))
			}
		}
		restored := 0
		for _, msg := range batch {
			restored++
			tchan <- msg
		}
		d := time.Second * 5
		Add("collect.post.restore", Tags, int64(restored))
		slog.Infof("restored %d, sleeping %s", restored, d)
		time.Sleep(d)
		return
	}
	recordSent(len(batch))
}

func recordSent(num int) {
	if Debug {
		slog.Infoln("sent", num)
	}
	slock.Lock()
	sent += int64(num)
	slock.Unlock()
}

func SendDataPoints(dps []*opentsdb.DataPoint, tsdb string) (*http.Response, error) {
	var buf bytes.Buffer
	g := gzip.NewWriter(&buf)
	if err := json.NewEncoder(g).Encode(dps); err != nil {
		return nil, err
	}
	if err := g.Close(); err != nil {
		return nil, err
	}
	req, err := http.NewRequest("POST", tsdb, &buf)
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Content-Encoding", "gzip")
	Add("collect.post.total_bytes", Tags, int64(buf.Len()))

	if UseNtlm {
		resp, err := ntlm.DoNTLMRequest(client, req)

		if resp.StatusCode == 401 {
			slog.Errorf("Scollector unauthorized to post data points to tsdb. Terminating.")
			os.Exit(1)
		}

		return resp, err
	}

	resp, err := client.Do(req)
	return resp, err
}
<commit_msg>collect: creating buffer pool for sending datapoints (#1838)<commit_after>package collect

import (
	"bytes"
	"compress/gzip"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"os"
	"sync"
	"sync/atomic"
	"time"

	"bosun.org/metadata"
	"bosun.org/opentsdb"
	"bosun.org/slog"
	"github.com/GROpenSourceDev/go-ntlm-auth/ntlm"
)

func queuer() {
	for dp := range tchan {
		if err := dp.Clean(); err != nil {
			atomic.AddInt64(&dropped, 1)
			continue // if anything gets this far that can't be made valid, just drop it silently.
		}
		qlock.Lock()
		for {
			if len(queue) > MaxQueueLen {
				atomic.AddInt64(&dropped, 1)
				break
			}
			queue = append(queue, dp)
			select {
			case dp = <-tchan:
				continue
			default:
			}
			break
		}
		qlock.Unlock()
	}
}

// Locks the queue and sends all datapoints. Intended to be used as scollector exits.
func Flush() {
	flushData()
	metadata.FlushMetadata()
	qlock.Lock()
	for len(queue) > 0 {
		i := len(queue)
		if i > BatchSize {
			i = BatchSize
		}
		sending := queue[:i]
		queue = queue[i:]
		if Debug {
			slog.Infof("sending: %d, remaining: %d", i, len(queue))
		}
		sendBatch(sending)
	}
	qlock.Unlock()
}

func send() {
	for {
		qlock.Lock()
		if i := len(queue); i > 0 {
			if i > BatchSize {
				i = BatchSize
			}
			sending := queue[:i]
			queue = queue[i:]
			if Debug {
				slog.Infof("sending: %d, remaining: %d", i, len(queue))
			}
			qlock.Unlock()
			Sample("collect.post.batchsize", Tags, float64(len(sending)))
			sendBatch(sending)
		} else {
			qlock.Unlock()
			time.Sleep(time.Second)
		}
	}
}

func sendBatch(batch []*opentsdb.DataPoint) {
	if Print {
		for _, d := range batch {
			j, err := d.MarshalJSON()
			if err != nil {
				slog.Error(err)
			}
			slog.Info(string(j))
		}
		recordSent(len(batch))
		return
	}
	now := time.Now()
	resp, err := SendDataPoints(batch, tsdbURL)
	if err == nil {
		defer resp.Body.Close()
	}
	d := time.Since(now).Nanoseconds() / 1e6
	Sample("collect.post.duration", Tags, float64(d))
	Add("collect.post.total_duration", Tags, d)
	Add("collect.post.count", Tags, 1)
	// Some problem with connecting to the server; retry later.
	if err != nil || resp.StatusCode != http.StatusNoContent {
		if err != nil {
			Add("collect.post.error", Tags, 1)
			slog.Error(err)
		} else if resp.StatusCode != http.StatusNoContent {
			Add("collect.post.bad_status", Tags, 1)
			slog.Errorln(resp.Status)
			body, err := ioutil.ReadAll(resp.Body)
			if err != nil {
				slog.Error(err)
			}
			if len(body) > 0 {
				slog.Error(string(body))
			}
		}
		restored := 0
		for _, msg := range batch {
			restored++
			tchan <- msg
		}
		d := time.Second * 5
		Add("collect.post.restore", Tags, int64(restored))
		slog.Infof("restored %d, sleeping %s", restored, d)
		time.Sleep(d)
		return
	}
	recordSent(len(batch))
}

func recordSent(num int) {
	if Debug {
		slog.Infoln("sent", num)
	}
	slock.Lock()
	sent += int64(num)
	slock.Unlock()
}

var bufferPool = sync.Pool{
	New: func() interface{} { return &bytes.Buffer{} },
}

func SendDataPoints(dps []*opentsdb.DataPoint, tsdb string) (*http.Response, error) {
	buf := bufferPool.Get().(*bytes.Buffer)
	defer bufferPool.Put(buf)
	buf.Reset()
	g := gzip.NewWriter(buf)
	if err := json.NewEncoder(g).Encode(dps); err != nil {
		return nil, err
	}
	if err := g.Close(); err != nil {
		return nil, err
	}
	req, err := http.NewRequest("POST", tsdb, buf)
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Content-Encoding", "gzip")
	Add("collect.post.total_bytes", Tags, int64(buf.Len()))

	if UseNtlm {
		resp, err := ntlm.DoNTLMRequest(client, req)

		if resp.StatusCode == 401 {
			slog.Errorf("Scollector unauthorized to post data points to tsdb. Terminating.")
			os.Exit(1)
		}

		return resp, err
	}

	resp, err := client.Do(req)
	return resp, err
}
<|endoftext|>


<commit_before>package commands

import (
	"os"
	"strings"
	"github.com/jingweno/gh/git"
	"github.com/jingweno/gh/utils"
)

var cmdPush = &Command{
	Run: push,
	Usage: "push REMOTE-1,REMOTE-2,...,REMOTE-N [REF]",
	Short: "Update remote refs along with associated objects",
	Long: `Push REF to each of REMOTE-1 through REMOTE-N by executing  mul-
tiple git push commands.`,
}

/**
 $ git push origin,staging,qa bert_timeout
 > git push origin bert_timeout
 > git push staging bert_timeout
 > git push qa bert_timeout
**/

func push (command *Command, args *Args) {
	if !args.IsParamsEmpty() {
		transformPushArgs(args)
	}
}

func transformPushArgs (args *Args) {
	remotes, ref := getRemotesRef(args)
	for _, i := range remotes {
		err := git.Spawn("push", i, ref)
		utils.Check(err)
	}

	os.Exit(0)
}

func getRemotesRef(args *Args) (remotes []string, ref string) {
	remotes = strings.Split(args.GetParam(0), ",")
	if args.ParamsSize() == 2 {
		ref = args.GetParam(1)
	} else {
		ref = ""
	}

	return
}
<commit_msg>Changed function name, since it doesn't transform the arguments<commit_after>package commands

import (
	"os"
	"strings"
	"github.com/jingweno/gh/git"
	"github.com/jingweno/gh/utils"
)

var cmdPush = &Command{
	Run: push,
	Usage: "push REMOTE-1,REMOTE-2,...,REMOTE-N [REF]",
	Short: "Update remote refs along with associated objects",
	Long: `Push REF to each of REMOTE-1 through REMOTE-N by executing  mul-
tiple git push commands.`,
}

/**
 $ git push origin,staging,qa bert_timeout
 > git push origin bert_timeout
 > git push staging bert_timeout
 > git push qa bert_timeout
**/

func push (command *Command, args *Args) {
	if !args.IsParamsEmpty() {
		pushToEveryRemote(args)
	}
}

func pushToEveryRemote (args *Args) {
	remotes, ref := getRemotesRef(args)
	for _, i := range remotes {
		err := git.Spawn("push", i, ref)
		utils.Check(err)
	}

	os.Exit(0)
}

func getRemotesRef(args *Args) (remotes []string, ref string) {
	remotes = strings.Split(args.GetParam(0), ",")
	if args.ParamsSize() == 2 {
		ref = args.GetParam(1)
	} else {
		ref = ""
	}

	return
}
<|endoftext|>


<commit_before>package commands

import (
	"fmt"
	"github.com/spf13/cobra"
	"os"
)

var version string

var rootCmd = &cobra.Command{
	Use:   "srasearch",
	Short: "A SRA Search Utility",
	Long:  `A utility to manage and view local SRA submissions data`,
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Printf("%s -- see '%s help'\n",
			"Please specify a subcommand", os.Args[0])
	},
}

func Execute(semanticVersion string) {
	version = semanticVersion
	AddCommands()
	rootCmd.Execute()
}

func AddCommands() {
	rootCmd.AddCommand(cmdSraDump)
	rootCmd.AddCommand(cmdVersion)
	rootCmd.AddCommand(cmdMakeIndex)
	rootCmd.AddCommand(cmdMerge)
}
<commit_msg>+ update root command with new command name changes<commit_after>package commands

import (
	"fmt"
	"github.com/spf13/cobra"
	"os"
)

var version string

var rootCmd = &cobra.Command{
	Use:   "srasearch",
	Short: "A SRA Search Utility",
	Long:  `A utility to manage and view local SRA submissions data`,
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Printf("%s -- see '%s help'\n",
			"Please specify a subcommand", os.Args[0])
	},
}

func Execute(semanticVersion string) {
	version = semanticVersion
	AddCommands()
	rootCmd.Execute()
}

func AddCommands() {
	rootCmd.AddCommand(cmdInitDump)
	rootCmd.AddCommand(cmdVersion)
	rootCmd.AddCommand(cmdMakeIndex)
	rootCmd.AddCommand(cmdIncrementDump)
}
<|endoftext|>


<commit_before>package live

import (
	"fmt"
	"io/ioutil"
	"os"
	"time"

	"github.com/hashicorp/consul/test/porter"
)

type ClusterConfig struct {
	Executable string
	NicePorts  bool
	Servers    int
	ServerArgs []string
	Clients    int
	ClientArgs []string
}

type Cluster struct {
	DataDir string
	Agents  []*Consul
}

func NewCluster(cfg *ClusterConfig) (*Cluster, error) {
	n := cfg.Servers + cfg.Clients
	if n < 1 {
		return nil, fmt.Errorf("at least one client or server required")
	}

	ports, err := porter.RandomPorts(5 * n)
	if err != nil {
		return nil, err
	}

	dir, err := ioutil.TempDir("", "cluster")
	if err != nil {
		return nil, err
	}
	var disarm bool
	defer func() {
		if !disarm {
			os.RemoveAll(dir)
		}
	}()

	var joinPort int
	baseArgs := func(node string, idx int) []string {
		dnsPort := ports[5*idx+0]
		httpPort := ports[5*idx+1]
		lanPort := ports[5*idx+2]
		wanPort := ports[5*idx+3]
		serverPort := ports[5*idx+4]

		// Set the default ports on the first agent for convenience.
		if idx == 0 {
			if cfg.NicePorts {
				dnsPort = 8600
				httpPort = 8500
				lanPort = 8301
				wanPort = 8302
				serverPort = 8300
			}
			joinPort = lanPort
		}

		args := []string{
			"agent",
			"-node", node,
			"-data-dir", fmt.Sprintf("%s/%s", dir, node),
			"-retry-join", fmt.Sprintf("127.0.0.1:%d", joinPort),
			"-hcl", fmt.Sprintf("ports={dns=%d http=%d serf_lan=%d serf_wan=%d server=%d}",
				dnsPort, httpPort, lanPort, wanPort, serverPort),
		}
		return args
	}

	var agents []*Consul
	for i := 0; i < cfg.Servers; i++ {
		node := fmt.Sprintf("server-%d", i)
		args := append(baseArgs(node, i), []string{
			"-server",
			fmt.Sprintf("-bootstrap-expect=%d", cfg.Servers),
			"-hcl", "performance={raft_multiplier=1}",
		}...)
		args = append(args, cfg.ServerArgs...)
		consul, err := NewConsul(cfg.Executable, args)
		if err != nil {
			return nil, err
		}
		agents = append(agents, consul)
	}
	for i := 0; i < cfg.Clients; i++ {
		node := fmt.Sprintf("client-%d", i)
		args := append(baseArgs(node, cfg.Servers+i), cfg.ClientArgs...)
		consul, err := NewConsul(cfg.Executable, args)
		if err != nil {
			return nil, err
		}
		agents = append(agents, consul)
	}

	disarm = true
	return &Cluster{
		DataDir: dir,
		Agents:  agents,
	}, nil
}

func (c *Cluster) Start() error {
	for i, consul := range c.Agents {
		if err := consul.Start(); err != nil {
			return err
		}

		// Sleep a bit so the later agents will have something to join
		// to without a backoff.
		if i == 0 {
			time.Sleep(3 * time.Second)
		}
	}
	return nil
}

func (c *Cluster) Shutdown() error {
	for _, consul := range c.Agents {
		if err := consul.Shutdown(); err != nil {
			return err
		}
	}

	if err := os.RemoveAll(c.DataDir); err != nil {
		return err
	}
	return nil
}
<commit_msg>Always use loopback address vs. any.<commit_after>package live

import (
	"fmt"
	"io/ioutil"
	"os"
	"time"

	"github.com/hashicorp/consul/test/porter"
)

type ClusterConfig struct {
	Executable string
	NicePorts  bool
	Servers    int
	ServerArgs []string
	Clients    int
	ClientArgs []string
}

type Cluster struct {
	DataDir string
	Agents  []*Consul
}

func NewCluster(cfg *ClusterConfig) (*Cluster, error) {
	n := cfg.Servers + cfg.Clients
	if n < 1 {
		return nil, fmt.Errorf("at least one client or server required")
	}

	ports, err := porter.RandomPorts(5 * n)
	if err != nil {
		return nil, err
	}

	dir, err := ioutil.TempDir("", "cluster")
	if err != nil {
		return nil, err
	}
	var disarm bool
	defer func() {
		if !disarm {
			os.RemoveAll(dir)
		}
	}()

	var joinPort int
	baseArgs := func(node string, idx int) []string {
		dnsPort := ports[5*idx+0]
		httpPort := ports[5*idx+1]
		lanPort := ports[5*idx+2]
		wanPort := ports[5*idx+3]
		serverPort := ports[5*idx+4]

		// Set the default ports on the first agent for convenience.
		if idx == 0 {
			if cfg.NicePorts {
				dnsPort = 8600
				httpPort = 8500
				lanPort = 8301
				wanPort = 8302
				serverPort = 8300
			}
			joinPort = lanPort
		}

		args := []string{
			"agent",
			"-node", node,
			"-data-dir", fmt.Sprintf("%s/%s", dir, node),
			"-retry-join", fmt.Sprintf("127.0.0.1:%d", joinPort),
			"-bind", "127.0.0.1",
			"-client", "127.0.0.1",
			"-hcl", fmt.Sprintf("ports={dns=%d http=%d serf_lan=%d serf_wan=%d server=%d}",
				dnsPort, httpPort, lanPort, wanPort, serverPort),
		}
		return args
	}

	var agents []*Consul
	for i := 0; i < cfg.Servers; i++ {
		node := fmt.Sprintf("server-%d", i)
		args := append(baseArgs(node, i), []string{
			"-server",
			fmt.Sprintf("-bootstrap-expect=%d", cfg.Servers),
			"-hcl", "performance={raft_multiplier=1}",
		}...)
		args = append(args, cfg.ServerArgs...)
		consul, err := NewConsul(cfg.Executable, args)
		if err != nil {
			return nil, err
		}
		agents = append(agents, consul)
	}
	for i := 0; i < cfg.Clients; i++ {
		node := fmt.Sprintf("client-%d", i)
		args := append(baseArgs(node, cfg.Servers+i), cfg.ClientArgs...)
		consul, err := NewConsul(cfg.Executable, args)
		if err != nil {
			return nil, err
		}
		agents = append(agents, consul)
	}

	disarm = true
	return &Cluster{
		DataDir: dir,
		Agents:  agents,
	}, nil
}

func (c *Cluster) Start() error {
	for i, consul := range c.Agents {
		if err := consul.Start(); err != nil {
			return err
		}

		// Sleep a bit so the later agents will have something to join
		// to without a backoff.
		if i == 0 {
			time.Sleep(3 * time.Second)
		}
	}
	return nil
}

func (c *Cluster) Shutdown() error {
	for _, consul := range c.Agents {
		if err := consul.Shutdown(); err != nil {
			return err
		}
	}

	if err := os.RemoveAll(c.DataDir); err != nil {
		return err
	}
	return nil
}
<|endoftext|>


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

package models

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path"
	"path/filepath"
	"strings"
	"sync"
	"time"

	"github.com/Unknwon/com"
	qlog "github.com/qiniu/log"

	"github.com/gogits/gogs/modules/base"
	"github.com/gogits/gogs/modules/log"
)

const (
	// "### autogenerated by gitgos, DO NOT EDIT\n"
	_TPL_PUBLICK_KEY = `command="%s serv key-%d",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty %s` + "\n"
)

var (
	ErrKeyAlreadyExist = errors.New("Public key already exist")
	ErrKeyNotExist     = errors.New("Public key does not exist")
)

var sshOpLocker = sync.Mutex{}

var (
	sshPath string // SSH directory.
	appPath string // Execution(binary) path.
)

// homeDir returns the home directory of current user.
func homeDir() string {
	home, err := com.HomeDir()
	if err != nil {
		qlog.Fatalln(err)
	}
	return home
}

func init() {
	var err error

	if appPath, err = base.ExecDir(); err != nil {
		qlog.Fatalf("publickey.init(fail to get app path): %v\n", err)
	}

	// Determine and create .ssh path.
	sshPath = filepath.Join(homeDir(), ".ssh")
	if err = os.MkdirAll(sshPath, os.ModePerm); err != nil {
		qlog.Fatalf("publickey.init(fail to create sshPath(%s)): %v\n", sshPath, err)
	}
}

// PublicKey represents a SSH key.
type PublicKey struct {
	Id          int64
	OwnerId     int64  `xorm:"UNIQUE(s) INDEX NOT NULL"`
	Name        string `xorm:"UNIQUE(s) NOT NULL"`
	Fingerprint string
	Content     string    `xorm:"TEXT NOT NULL"`
	Created     time.Time `xorm:"CREATED"`
	Updated     time.Time `xorm:"UPDATED"`
}

// GetAuthorizedString generates and returns formatted public key string for authorized_keys file.
func (key *PublicKey) GetAuthorizedString() string {
	return fmt.Sprintf(_TPL_PUBLICK_KEY, appPath, key.Id, key.Content)
}

// saveAuthorizedKeyFile writes SSH key content to authorized_keys file.
func saveAuthorizedKeyFile(key *PublicKey) error {
	sshOpLocker.Lock()
	defer sshOpLocker.Unlock()

	fpath := filepath.Join(sshPath, "authorized_keys")
	f, err := os.OpenFile(fpath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
	if err != nil {
		return err
	}
	defer f.Close()

	_, err = f.WriteString(key.GetAuthorizedString())
	return err
}

// AddPublicKey adds new public key to database and authorized_keys file.
func AddPublicKey(key *PublicKey) (err error) {
	has, err := orm.Get(key)
	if err != nil {
		return err
	} else if has {
		return ErrKeyAlreadyExist
	}

	// Calculate fingerprint.
	tmpPath := strings.Replace(path.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()),
		"id_rsa.pub"), "\\", "/", -1)
	os.MkdirAll(path.Dir(tmpPath), os.ModePerm)
	if err = ioutil.WriteFile(tmpPath, []byte(key.Content), os.ModePerm); err != nil {
		return err
	}
	stdout, stderr, err := com.ExecCmd("ssh-keygen", "-l", "-f", tmpPath)
	if err != nil {
		return errors.New("ssh-keygen -l -f: " + stderr)
	} else if len(stdout) < 2 {
		return errors.New("Not enough output for calculating fingerprint")
	}
	key.Fingerprint = strings.Split(stdout, " ")[1]

	// Save SSH key.
	if _, err = orm.Insert(key); err != nil {
		return err
	} else if err = saveAuthorizedKeyFile(key); err != nil {
		// Roll back.
		if _, err2 := orm.Delete(key); err2 != nil {
			return err2
		}
		return err
	}

	return nil
}

// ListPublicKey returns a list of all public keys that user has.
func ListPublicKey(uid int64) ([]PublicKey, error) {
	keys := make([]PublicKey, 0, 5)
	err := orm.Find(&keys, &PublicKey{OwnerId: uid})
	return keys, err
}

// rewriteAuthorizedKeys finds and deletes corresponding line in authorized_keys file.
func rewriteAuthorizedKeys(key *PublicKey, p, tmpP string) error {
	sshOpLocker.Lock()
	defer sshOpLocker.Unlock()

	fr, err := os.Open(p)
	if err != nil {
		return err
	}
	defer fr.Close()

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

	isFound := false
	keyword := fmt.Sprintf("key-%d", key.Id)
	buf := bufio.NewReader(fr)
	for {
		line, errRead := buf.ReadString('\n')
		line = strings.TrimSpace(line)

		if errRead != nil {
			if errRead != io.EOF {
				return errRead
			}

			// Reached end of file, if nothing to read then break,
			// otherwise handle the last line.
			if len(line) == 0 {
				break
			}
		}

		// Found the line and copy rest of file.
		if !isFound && strings.Contains(line, keyword) && strings.Contains(line, key.Content) {
			isFound = true
			continue
		}
		// Still finding the line, copy the line that currently read.
		if _, err = fw.WriteString(line + "\n"); err != nil {
			return err
		}

		if errRead == io.EOF {
			break
		}
	}
	return nil
}

// DeletePublicKey deletes SSH key information both in database and authorized_keys file.
func DeletePublicKey(key *PublicKey) error {
	has, err := orm.Get(key)
	if err != nil {
		return err
	} else if !has {
		return ErrKeyNotExist
	}

	if _, err = orm.Delete(key); err != nil {
		return err
	}

	fpath := filepath.Join(sshPath, "authorized_keys")
	tmpPath := filepath.Join(sshPath, "authorized_keys.tmp")
	log.Trace("publickey.DeletePublicKey(authorized_keys): %s", fpath)

	if err = rewriteAuthorizedKeys(key, fpath, tmpPath); err != nil {
		return err
	} else if err = os.Remove(fpath); err != nil {
		return err
	}
	return os.Rename(tmpPath, fpath)
}
<commit_msg>Bug fix<commit_after>// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package models

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"os/exec"
	"path"
	"path/filepath"
	"strings"
	"sync"
	"time"

	"github.com/Unknwon/com"
	qlog "github.com/qiniu/log"

	"github.com/gogits/gogs/modules/log"
)

const (
	// "### autogenerated by gitgos, DO NOT EDIT\n"
	_TPL_PUBLICK_KEY = `command="%s serv key-%d",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty %s` + "\n"
)

var (
	ErrKeyAlreadyExist = errors.New("Public key already exist")
	ErrKeyNotExist     = errors.New("Public key does not exist")
)

var sshOpLocker = sync.Mutex{}

var (
	sshPath string // SSH directory.
	appPath string // Execution(binary) path.
)

// exePath returns the executable path.
func exePath() (string, error) {
	file, err := exec.LookPath(os.Args[0])
	if err != nil {
		return "", err
	}
	return filepath.Abs(file)
}

// homeDir returns the home directory of current user.
func homeDir() string {
	home, err := com.HomeDir()
	if err != nil {
		qlog.Fatalln(err)
	}
	return home
}

func init() {
	var err error

	if appPath, err = exePath(); err != nil {
		qlog.Fatalf("publickey.init(fail to get app path): %v\n", err)
	}

	// Determine and create .ssh path.
	sshPath = filepath.Join(homeDir(), ".ssh")
	if err = os.MkdirAll(sshPath, os.ModePerm); err != nil {
		qlog.Fatalf("publickey.init(fail to create sshPath(%s)): %v\n", sshPath, err)
	}
}

// PublicKey represents a SSH key.
type PublicKey struct {
	Id          int64
	OwnerId     int64  `xorm:"UNIQUE(s) INDEX NOT NULL"`
	Name        string `xorm:"UNIQUE(s) NOT NULL"`
	Fingerprint string
	Content     string    `xorm:"TEXT NOT NULL"`
	Created     time.Time `xorm:"CREATED"`
	Updated     time.Time `xorm:"UPDATED"`
}

// GetAuthorizedString generates and returns formatted public key string for authorized_keys file.
func (key *PublicKey) GetAuthorizedString() string {
	return fmt.Sprintf(_TPL_PUBLICK_KEY, appPath, key.Id, key.Content)
}

// saveAuthorizedKeyFile writes SSH key content to authorized_keys file.
func saveAuthorizedKeyFile(key *PublicKey) error {
	sshOpLocker.Lock()
	defer sshOpLocker.Unlock()

	fpath := filepath.Join(sshPath, "authorized_keys")
	f, err := os.OpenFile(fpath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
	if err != nil {
		return err
	}
	defer f.Close()

	_, err = f.WriteString(key.GetAuthorizedString())
	return err
}

// AddPublicKey adds new public key to database and authorized_keys file.
func AddPublicKey(key *PublicKey) (err error) {
	has, err := orm.Get(key)
	if err != nil {
		return err
	} else if has {
		return ErrKeyAlreadyExist
	}

	// Calculate fingerprint.
	tmpPath := strings.Replace(path.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()),
		"id_rsa.pub"), "\\", "/", -1)
	os.MkdirAll(path.Dir(tmpPath), os.ModePerm)
	if err = ioutil.WriteFile(tmpPath, []byte(key.Content), os.ModePerm); err != nil {
		return err
	}
	stdout, stderr, err := com.ExecCmd("ssh-keygen", "-l", "-f", tmpPath)
	if err != nil {
		return errors.New("ssh-keygen -l -f: " + stderr)
	} else if len(stdout) < 2 {
		return errors.New("Not enough output for calculating fingerprint")
	}
	key.Fingerprint = strings.Split(stdout, " ")[1]

	// Save SSH key.
	if _, err = orm.Insert(key); err != nil {
		return err
	} else if err = saveAuthorizedKeyFile(key); err != nil {
		// Roll back.
		if _, err2 := orm.Delete(key); err2 != nil {
			return err2
		}
		return err
	}

	return nil
}

// ListPublicKey returns a list of all public keys that user has.
func ListPublicKey(uid int64) ([]PublicKey, error) {
	keys := make([]PublicKey, 0, 5)
	err := orm.Find(&keys, &PublicKey{OwnerId: uid})
	return keys, err
}

// rewriteAuthorizedKeys finds and deletes corresponding line in authorized_keys file.
func rewriteAuthorizedKeys(key *PublicKey, p, tmpP string) error {
	sshOpLocker.Lock()
	defer sshOpLocker.Unlock()

	fr, err := os.Open(p)
	if err != nil {
		return err
	}
	defer fr.Close()

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

	isFound := false
	keyword := fmt.Sprintf("key-%d", key.Id)
	buf := bufio.NewReader(fr)
	for {
		line, errRead := buf.ReadString('\n')
		line = strings.TrimSpace(line)

		if errRead != nil {
			if errRead != io.EOF {
				return errRead
			}

			// Reached end of file, if nothing to read then break,
			// otherwise handle the last line.
			if len(line) == 0 {
				break
			}
		}

		// Found the line and copy rest of file.
		if !isFound && strings.Contains(line, keyword) && strings.Contains(line, key.Content) {
			isFound = true
			continue
		}
		// Still finding the line, copy the line that currently read.
		if _, err = fw.WriteString(line + "\n"); err != nil {
			return err
		}

		if errRead == io.EOF {
			break
		}
	}
	return nil
}

// DeletePublicKey deletes SSH key information both in database and authorized_keys file.
func DeletePublicKey(key *PublicKey) error {
	has, err := orm.Get(key)
	if err != nil {
		return err
	} else if !has {
		return ErrKeyNotExist
	}

	if _, err = orm.Delete(key); err != nil {
		return err
	}

	fpath := filepath.Join(sshPath, "authorized_keys")
	tmpPath := filepath.Join(sshPath, "authorized_keys.tmp")
	log.Trace("publickey.DeletePublicKey(authorized_keys): %s", fpath)

	if err = rewriteAuthorizedKeys(key, fpath, tmpPath); err != nil {
		return err
	} else if err = os.Remove(fpath); err != nil {
		return err
	}
	return os.Rename(tmpPath, fpath)
}
<|endoftext|>