Пример #1
0
func processGlobalFlags(c *cli.Context) time.Duration {
	var network string
	if c.GlobalBool("tcp") {
		network = "tcp"
	} else {
		network = "udp"
	}
	client, err := raidman.Dial(network, fmt.Sprintf("%s:%d", c.GlobalString("host"), c.GlobalInt("port")))
	if c.GlobalString("event-host") == "nil" {
		log.Panic("Failed to automatically get the hostname. Please specify it with --host")
	}
	if err != nil {
		log.Panicf("Failed to connect to the riemann host because %s", err)
	}
	attribute, err := processAttributes(c.GlobalStringSlice("attribute"))
	if err != nil {
		log.Panic(err)
	}
	eventTemplate := raidman.Event{
		Ttl:        float32(c.GlobalDuration("ttl").Seconds()),
		Tags:       c.GlobalStringSlice("tags"),
		Host:       c.GlobalString("event-host"),
		Attributes: attribute,
	}
	riemannSend = func(url, method string, duration float64) {
		event := eventTemplate
		event.Service = fmt.Sprintf("%s %s", url, method)
		event.Time = time.Now().Unix()
		event.Metric = duration
		client.Send(&event)
	}

	return c.GlobalDuration("interval")
}
Пример #2
0
// Populate updates the specified project context based on command line arguments and subcommands.
func Populate(context *project.Context, c *cli.Context) {
	context.ComposeFiles = c.GlobalStringSlice("file")

	if len(context.ComposeFiles) == 0 {
		context.ComposeFiles = []string{"docker-compose.yml"}
		if _, err := os.Stat("docker-compose.override.yml"); err == nil {
			context.ComposeFiles = append(context.ComposeFiles, "docker-compose.override.yml")
		}
	}

	context.ProjectName = c.GlobalString("project-name")

	if c.Command.Name == "logs" {
		context.Log = true
		context.FollowLog = c.Bool("follow")
	} else if c.Command.Name == "up" || c.Command.Name == "create" {
		context.Log = !c.Bool("d")
		context.NoRecreate = c.Bool("no-recreate")
		context.ForceRecreate = c.Bool("force-recreate")
		context.NoBuild = c.Bool("no-build")
	} else if c.Command.Name == "stop" || c.Command.Name == "restart" || c.Command.Name == "scale" {
		context.Timeout = uint(c.Int("timeout"))
	} else if c.Command.Name == "kill" {
		context.Signal = c.String("signal")
	} else if c.Command.Name == "rm" {
		context.Volume = c.Bool("v")
	} else if c.Command.Name == "build" {
		context.NoCache = c.Bool("no-cache")
	}
}
Пример #3
0
func cmdReorderTemplateScripts(c *cli.Context) {
	utils.FlagsRequired(c, []string{"template_id", "type", "script_ids"})
	webservice, err := webservice.NewWebService()
	utils.CheckError(err)

	v := make(map[string]interface{})
	v["type"] = c.String("type")
	v["script_ids"] = c.GlobalStringSlice("script_ids")

	jsonBytes, err := json.Marshal(v)
	utils.CheckError(err)
	err, res, code := webservice.Put(fmt.Sprintf("/v1/blueprint/templates/%s/scripts/reorder", c.String("template_id")), jsonBytes)
	utils.CheckError(err)
	utils.CheckReturnCode(code, res)

	var templateScripts []TemplateScript
	err = json.Unmarshal(res, &templateScripts)
	utils.CheckError(err)

	w := tabwriter.NewWriter(os.Stdout, 15, 1, 3, ' ', 0)
	fmt.Fprintln(w, "ID\tTYPE\tEXECUTION ORDER\tTEMPLATE ID\tSCRIPT ID\tPARAMETER VALUES\r")
	for _, templateScript := range templateScripts {
		fmt.Fprintf(w, "%s\t%s\t%d\t%s\t%s\t%s\n", templateScript.Id, templateScript.Type, templateScript.Execution_Order, templateScript.Template_Id, templateScript.Script_Id, templateScript.Parameter_Values)
	}
	w.Flush()
}
Пример #4
0
func revoke(c *cli.Context) error {

	conf, _, client := setup(c)

	err := checkFolder(conf.CertPath())
	if err != nil {
		logger().Fatalf("Could not check/create path: %s", err.Error())
	}

	for _, domain := range c.GlobalStringSlice("domains") {
		logger().Printf("Trying to revoke certificate for domain %s", domain)

		certPath := path.Join(conf.CertPath(), domain+".crt")
		certBytes, err := ioutil.ReadFile(certPath)

		err = client.RevokeCertificate(certBytes)
		if err != nil {
			logger().Fatalf("Error while revoking the certificate for domain %s\n\t%s", domain, err.Error())
		} else {
			logger().Print("Certificate was revoked.")
		}
	}

	return nil
}
Пример #5
0
func renew(c *cli.Context) {
	conf, _, client := setup(c)

	if len(c.GlobalStringSlice("domains")) <= 0 {
		logger().Fatal("Please specify at least one domain.")
	}

	domain := c.GlobalStringSlice("domains")[0]

	// load the cert resource from files.
	// We store the certificate, private key and metadata in different files
	// as web servers would not be able to work with a combined file.
	certPath := path.Join(conf.CertPath(), domain+".crt")
	privPath := path.Join(conf.CertPath(), domain+".key")
	metaPath := path.Join(conf.CertPath(), domain+".json")

	certBytes, err := ioutil.ReadFile(certPath)
	if err != nil {
		logger().Fatalf("Error while loading the certificate for domain %s\n\t%s", domain, err.Error())
	}

	if c.IsSet("days") {
		expTime, err := acme.GetPEMCertExpiration(certBytes)
		if err != nil {
			logger().Printf("Could not get Certification expiration for domain %s", domain)
		}

		if int(expTime.Sub(time.Now()).Hours()/24.0) > c.Int("days") {
			return
		}
	}

	metaBytes, err := ioutil.ReadFile(metaPath)
	if err != nil {
		logger().Fatalf("Error while loading the meta data for domain %s\n\t%s", domain, err.Error())
	}

	var certRes acme.CertificateResource
	err = json.Unmarshal(metaBytes, &certRes)
	if err != nil {
		logger().Fatalf("Error while marshalling the meta data for domain %s\n\t%s", domain, err.Error())
	}

	if c.Bool("reuse-key") {
		keyBytes, err := ioutil.ReadFile(privPath)
		if err != nil {
			logger().Fatalf("Error while loading the private key for domain %s\n\t%s", domain, err.Error())
		}
		certRes.PrivateKey = keyBytes
	}

	certRes.Certificate = certBytes

	newCert, err := client.RenewCertificate(certRes, true)
	if err != nil {
		logger().Fatalf("%s", err.Error())
	}

	saveCertRes(newCert, conf)
}
Пример #6
0
func revoke(c *cli.Context) {
	err := checkFolder(c.GlobalString("path"))
	if err != nil {
		logger().Fatalf("Cound not check/create path: %v", err)
	}

	conf := NewConfiguration(c)
	if !c.GlobalIsSet("email") {
		logger().Fatal("You have to pass an account (email address) to the program using --email or -m")
	}

	acc := NewAccount(c.GlobalString("email"), conf)
	client := acme.NewClient(c.GlobalString("server"), acc, conf.RsaBits(), conf.OptPort())

	err = checkFolder(conf.CertPath())
	if err != nil {
		logger().Fatalf("Cound not check/create path: %v", err)
	}

	for _, domain := range c.GlobalStringSlice("domains") {
		logger().Printf("Trying to revoke certificate for domain %s", domain)

		certPath := path.Join(conf.CertPath(), domain+".crt")
		certBytes, err := ioutil.ReadFile(certPath)

		err = client.RevokeCertificate(certBytes)
		if err != nil {
			logger().Printf("Error while revoking the certificate for domain %s\n\t%v", domain, err)
		} else {
			logger().Print("Certificate was revoked.")
		}
	}
}
Пример #7
0
func setup(c *cli.Context) (*Configuration, *Account, *acme.Client) {
	err := checkFolder(c.GlobalString("path"))
	if err != nil {
		logger().Fatalf("Cound not check/create path: %s", err.Error())
	}

	conf := NewConfiguration(c)
	if len(c.GlobalString("email")) == 0 {
		logger().Fatal("You have to pass an account (email address) to the program using --email or -m")
	}

	//TODO: move to account struct? Currently MUST pass email.
	acc := NewAccount(c.GlobalString("email"), conf)

	client, err := acme.NewClient(c.GlobalString("server"), acc, conf.RsaBits())
	if err != nil {
		logger().Fatalf("Could not create client: %s", err.Error())
	}

	if len(c.GlobalStringSlice("exclude")) > 0 {
		client.ExcludeChallenges(conf.ExcludedSolvers())
	}

	if c.GlobalIsSet("http") {
		client.SetHTTPAddress(c.GlobalString("http"))
	}

	if c.GlobalIsSet("tls") {
		client.SetTLSAddress(c.GlobalString("tls"))
	}

	return conf, acc, client
}
Пример #8
0
func setIsvcsEnv(ctx *cli.Context) error {
	for _, val := range ctx.GlobalStringSlice("isvcs-env") {
		if err := isvcs.AddEnv(val); err != nil {
			return err
		}
	}
	return nil
}
Пример #9
0
// serviced service shell [--saveas SAVEAS]  [--interactive, -i] SERVICEID [COMMAND]
func (c *ServicedCli) cmdServiceShell(ctx *cli.Context) error {
	args := ctx.Args()
	if len(args) < 1 {
		if !ctx.Bool("help") {
			fmt.Fprintf(os.Stderr, "Incorrect Usage.\n\n")
		}
		cli.ShowSubcommandHelp(ctx)
		return c.exit(1)
	}

	var (
		command string
		argv    []string
		isTTY   bool
	)

	svc, err := c.searchForService(args[0])
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		return c.exit(1)
	}

	if len(args) < 2 {
		command = "/bin/bash"
		isTTY = true
	} else {
		command = args[1]
		isTTY = ctx.GlobalBool("interactive")
	}

	if len(args) > 2 {
		argv = args[2:]
	}

	config := api.ShellConfig{
		ServiceID:        svc.ID,
		Command:          command,
		Args:             argv,
		SaveAs:           ctx.GlobalString("saveas"),
		IsTTY:            isTTY,
		Mounts:           ctx.GlobalStringSlice("mount"),
		ServicedEndpoint: fmt.Sprintf("localhost:%s", api.GetOptionsRPCPort()),
	}

	if err := c.driver.StartShell(config); err != nil {
		fmt.Fprintln(os.Stderr, err)
		if exitErr, ok := err.(*exec.ExitError); ok {
			if exitErr != nil && exitErr.ProcessState != nil && exitErr.ProcessState.Sys() != nil {
				if status, ok := exitErr.ProcessState.Sys().(syscall.WaitStatus); ok {
					return c.exit(status.ExitStatus())
				}
			}
		}
		return c.exit(1)
	} else {
		return c.exit(0)
	}
}
Пример #10
0
// serviced service run SERVICEID [COMMAND [ARGS ...]]
func (c *ServicedCli) cmdServiceRun(ctx *cli.Context) error {
	args := ctx.Args()
	if len(args) < 1 {
		if !ctx.Bool("help") {
			fmt.Fprintf(os.Stderr, "Incorrect Usage.\n\n")
		}
		cli.ShowSubcommandHelp(ctx)
		return c.exit(1)
	}

	if len(args) < 2 {
		for _, s := range c.serviceRuns(args[0]) {
			fmt.Println(s)
		}
		fmt.Fprintf(os.Stderr, "serviced service run")
		return c.exit(1)
	}

	var (
		command string
		argv    []string
	)

	svc, err := c.searchForService(args[0])
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		return c.exit(1)
	}

	command = args[1]
	if len(args) > 2 {
		argv = args[2:]
	}

	config := api.ShellConfig{
		ServiceID:        svc.ID,
		Command:          command,
		Username:         ctx.GlobalString("user"),
		Args:             argv,
		SaveAs:           dfs.NewLabel(svc.ID),
		IsTTY:            ctx.GlobalBool("interactive"),
		Mounts:           ctx.GlobalStringSlice("mount"),
		ServicedEndpoint: fmt.Sprintf("localhost:%s", api.GetOptionsRPCPort()),
		LogToStderr:      ctx.GlobalBool("logtostderr"),
	}

	config.LogStash.Enable = ctx.GlobalBool("logstash")
	config.LogStash.SettleTime = ctx.GlobalString("logstash-settle-time")
	config.LogStash.IdleFlushTime = ctx.GlobalString("logstash-idle-flush-time")

	if err := c.driver.RunShell(config); err != nil {
		fmt.Fprintln(os.Stderr, err)
		return c.exit(1)
	}

	return c.exit(0)
}
Пример #11
0
func parseEnvironment(context *cli.Context) (map[string]string, error) {
	env := make(map[string]string)
	for _, v := range context.GlobalStringSlice("env") {
		parts := strings.SplitN(v, "=", 2)
		if len(parts) != 2 {
			return nil, fmt.Errorf("invalid env format %s", v)
		}
		env[parts[0]] = parts[1]
	}
	return env, nil
}
Пример #12
0
func AppendResource(fileName, resourceName, key string, c *cli.Context) error {
	ignoreList := c.GlobalStringSlice("exclude-attr")

	var configJSON ConfigJSON
	if _, err := os.Stat(fileName); err == nil {
		configJSON = ReadJSON(fileName)
	} else {
		configJSON = *NewConfigJSON()
	}

	sys := system.New(c)

	// Need to figure out a good way to refactor this
	switch resourceName {
	case "Addr":
		res, _ := configJSON.Addrs.AppendSysResource(key, sys, ignoreList)
		resourcePrint(fileName, res)
	case "Command":
		res, _ := configJSON.Commands.AppendSysResource(key, sys, ignoreList)
		resourcePrint(fileName, res)
	case "DNS":
		res, _ := configJSON.DNS.AppendSysResource(key, sys, ignoreList)
		resourcePrint(fileName, res)
	case "File":
		res, _ := configJSON.Files.AppendSysResource(key, sys, ignoreList)
		resourcePrint(fileName, res)
	case "Group":
		res, _ := configJSON.Groups.AppendSysResource(key, sys, ignoreList)
		resourcePrint(fileName, res)
	case "Package":
		res, _ := configJSON.Packages.AppendSysResource(key, sys, ignoreList)
		resourcePrint(fileName, res)
	case "Port":
		res, _ := configJSON.Ports.AppendSysResource(key, sys, ignoreList)
		resourcePrint(fileName, res)
	case "Process":
		res, _ := configJSON.Processes.AppendSysResource(key, sys, ignoreList)
		resourcePrint(fileName, res)
	case "Service":
		res, _ := configJSON.Services.AppendSysResource(key, sys, ignoreList)
		resourcePrint(fileName, res)
	case "User":
		res, _ := configJSON.Users.AppendSysResource(key, sys, ignoreList)
		resourcePrint(fileName, res)
	case "Gossfile":
		res, _ := configJSON.Gossfiles.AppendSysResource(key, sys, ignoreList)
		resourcePrint(fileName, res)
	}

	WriteJSON(fileName, configJSON)

	return nil
}
Пример #13
0
func showVersions(ctx *cli.Context) (bool, error) {
	if len(ctx.Args()) != 0 {
		return true, errorInvalidArgCount(len(ctx.Args()), 0, ctx.Args())
	}

	e := etcd2.New(ctx.GlobalString("prefix"), ctx.GlobalStringSlice("etcd"))

	fmt.Printf("Current local schema version: %d\n", e.CurrentSchemaVersion())
	fmt.Printf("Newest available schema version: %d\n", latestMigrationVersion)

	return false, nil
}
Пример #14
0
func run(c *cli.Context) error {
	conf, acc, client := setup(c)
	if acc.Registration == nil {
		reg, err := client.Register()
		if err != nil {
			logger().Fatalf("Could not complete registration\n\t%s", err.Error())
		}

		acc.Registration = reg
		acc.Save()

		logger().Print("!!!! HEADS UP !!!!")
		logger().Printf(`
		Your account credentials have been saved in your Let's Encrypt
		configuration directory at "%s".
		You should make a secure backup	of this folder now. This
		configuration directory will also contain certificates and
		private keys obtained from Let's Encrypt so making regular
		backups of this folder is ideal.`, conf.AccountPath(c.GlobalString("email")))

	}

	// If the agreement URL is empty, the account still needs to accept the LE TOS.
	if acc.Registration.Body.Agreement == "" {
		handleTOS(c, client, acc)
	}

	if len(c.GlobalStringSlice("domains")) == 0 {
		logger().Fatal("Please specify --domains or -d")
	}

	cert, failures := client.ObtainCertificate(c.GlobalStringSlice("domains"), !c.Bool("no-bundle"), nil)
	if len(failures) > 0 {
		for k, v := range failures {
			logger().Printf("[%s] Could not obtain certificates\n\t%s", k, v.Error())
		}

		// Make sure to return a non-zero exit code if ObtainSANCertificate
		// returned at least one error. Due to us not returning partial
		// certificate we can just exit here instead of at the end.
		os.Exit(1)
	}

	err := checkFolder(conf.CertPath())
	if err != nil {
		logger().Fatalf("Could not check/create path: %s", err.Error())
	}

	saveCertRes(cert, conf)

	return nil
}
Пример #15
0
func config(context *cli.Context) factory.Config {
	configPath := context.GlobalString("config")
	var config factory.Config
	var err error
	if configPath == "" {
		config, err = factory.Parse([]byte("{}"))
	} else {
		config, err = factory.LoadFromFile(configPath)
	}
	if err != nil {
		cli.ShowAppHelp(context)
		panic(err)
	}

	schemeType := context.GlobalString("scheme")
	if schemeType != "" {
		config.SchemeType = schemeType
	}
	writerType := context.GlobalString("writer")
	if writerType != "" {
		config.WriterType = writerType
	}
	readerType := context.GlobalString("reader")
	if readerType != "" {
		config.ReaderType = readerType
	}

	for _, assignment := range context.GlobalStringSlice("config-string") {
		keyValue, err := parseAssignment(assignment)
		if err != nil {
			panic(err)
		}

		config.Additional.SetString(keyValue[0], keyValue[1])
	}
	for _, assignment := range context.GlobalStringSlice("config-int") {
		keyValue, err := parseAssignment(assignment)
		if err != nil {
			panic(err)
		}

		value, err := strconv.Atoi(keyValue[1])
		if err != nil {
			panic(err)
		}

		config.Additional.SetInt(keyValue[0], value)
	}

	return config
}
Пример #16
0
func processClientTarget(c *cli.Context) (isUnix bool, target string, err error) {
	for _, v := range c.GlobalStringSlice(`host`) {
		if strings.HasPrefix(v, "tcp://") {
			isUnix = false
			target = strings.TrimPrefix(v, "tcp://")
			err = nil
		}
		if strings.HasPrefix(v, "unix://") {
			isUnix = true
			target = strings.TrimPrefix(v, "unix://")
			err = nil
		}
	}
	return
}
Пример #17
0
func getStoreOpts(c *cli.Context) map[string]interface{} {
	opts := c.GlobalStringSlice("store-opt")
	data := map[string]interface{}{}

	for _, o := range opts {
		parts := strings.Split(o, "=")
		if len(parts) > 1 {
			data[parts[0]] = parts[1]
		} else {
			data[parts[0]] = ""
		}
	}

	return data
}
Пример #18
0
func renew(c *cli.Context) {
	conf, _, client := setup(c)

	for _, domain := range c.GlobalStringSlice("domains") {
		// load the cert resource from files.
		// We store the certificate, private key and metadata in different files
		// as web servers would not be able to work with a combined file.
		certPath := path.Join(conf.CertPath(), domain+".crt")
		privPath := path.Join(conf.CertPath(), domain+".key")
		metaPath := path.Join(conf.CertPath(), domain+".json")

		certBytes, err := ioutil.ReadFile(certPath)
		if err != nil {
			logger().Printf("Error while loading the certificate for domain %s\n\t%v", domain, err)
			return
		}

		keyBytes, err := ioutil.ReadFile(privPath)
		if err != nil {
			logger().Printf("Error while loading the private key for domain %s\n\t%v", domain, err)
			return
		}

		metaBytes, err := ioutil.ReadFile(metaPath)
		if err != nil {
			logger().Printf("Error while loading the meta data for domain %s\n\t%v", domain, err)
			return
		}

		var certRes acme.CertificateResource
		err = json.Unmarshal(metaBytes, &certRes)
		if err != nil {
			logger().Printf("Error while marshalling the meta data for domain %s\n\t%v", domain, err)
			return
		}

		certRes.PrivateKey = keyBytes
		certRes.Certificate = certBytes

		newCert, err := client.RenewCertificate(certRes, true, true)
		if err != nil {
			logger().Printf("%v", err)
			return
		}

		saveCertRes(newCert, conf)
	}
}
Пример #19
0
func initializeKVStore(c *cli.Context) {
	var kvt store.Backend
	switch c.GlobalString("kvtype") {
	case "consul":
		kvt = store.CONSUL
	case "etcd":
		kvt = store.ETCD
	case "zk":
		kvt = store.ZK
	}
	k, err := libkv.NewStore(kvt, c.GlobalStringSlice("kvurl"), &store.Config{})
	if err != nil {
		logger.Fatal(err)
	}
	kvStore = k
}
Пример #20
0
func initDriver(c *cli.Context) graphdriver.Driver {
	graphdriver.DefaultDriver = c.GlobalString("driver")
	if graphdriver.DefaultDriver == "" {
		fmt.Printf("No graphdriver specified.\n")
		os.Exit(1)
	}
	homedir := c.GlobalString("home")
	drv, err := graphdriver.New(homedir, c.GlobalStringSlice("storage-opt"), nil, nil)
	if err != nil {
		fmt.Printf("Failed to instantiate graphdriver: %s\n", err)
		os.Exit(1)
	}
	if c.GlobalBool("debug") {
		fmt.Fprintf(os.Stderr, "[DEBUG] Using driver %s.\n[DEBUG] %g\n[DEBUG] Home directory: %s\n", drv.String(), drv.Status(), homedir)
	}
	return drv
}
Пример #21
0
Файл: main.go Проект: Vektah/gin
func MainAction(c *cli.Context) {
	port := c.GlobalInt("port")
	appPort := strconv.Itoa(c.GlobalInt("appPort"))
	immediate = c.GlobalBool("immediate")

	// Bootstrap the environment
	envy.Bootstrap()

	// Set the PORT env
	os.Setenv("PORT", appPort)

	wd, err := os.Getwd()
	if err != nil {
		logger.Fatal(err)
	}

	builder := gin.NewBuilder(c.GlobalString("path"), c.GlobalString("bin"), c.GlobalBool("godep"))
	runner := gin.NewRunner(filepath.Join(wd, builder.Binary()), c.Args()...)
	runner.SetWriter(os.Stdout)
	proxy := gin.NewProxy(builder, runner)

	config := &gin.Config{
		Port:    port,
		ProxyTo: "http://localhost:" + appPort,
	}

	err = proxy.Run(config)
	if err != nil {
		logger.Fatal(err)
	}

	logger.Printf("listening on port %d\n", port)

	shutdown(runner)

	// build right now
	build(builder, runner, logger)

	// scan for changes
	scanChanges(c.GlobalString("path"), c.GlobalStringSlice("excludeDir"), func(path string) {
		logger.Printf("Change detected, build starting...")
		runner.Kill()
		build(builder, runner, logger)
	})
}
Пример #22
0
// Create implements ProjectFactory.Create using docker client.
func (p *ProjectFactory) Create(c *cli.Context) (project.APIProject, error) {
	context := &docker.Context{}
	context.LoggerFactory = logger.NewColorLoggerFactory()
	Populate(context, c)

	context.ComposeFiles = c.GlobalStringSlice("file")

	if len(context.ComposeFiles) == 0 {
		context.ComposeFiles = []string{"docker-compose.yml"}
		if _, err := os.Stat("docker-compose.override.yml"); err == nil {
			context.ComposeFiles = append(context.ComposeFiles, "docker-compose.override.yml")
		}
	}

	context.ProjectName = c.GlobalString("project-name")

	return docker.NewProject(context, nil)
}
Пример #23
0
func initDaemon(c *cli.Context) (*daemon.Daemon, *graph.TagStore, *graph.Graph, graphdriver.Driver) {
	t, tc, g, d := initTagStoreAndConfig(c)
	config := &daemon.Config{}
	config.DisableBridge = true
	config.GraphDriver = c.GlobalString("driver")
	config.GraphOptions = c.GlobalStringSlice("storage-opt")
	home := c.GlobalString("home")
	config.Root = home
	config.TrustKeyPath = filepath.Join(c.GlobalString("configdir"), "key.json")
	flags := mflag.NewFlagSet("graphc", mflag.ExitOnError)
	config.InstallFlags(flags, func(string) string { return "" })
	daemon, err := daemon.NewDaemon(config, tc.Registry)
	if err != nil {
		fmt.Printf("Failed to instantiate daemon: %s\n", err)
		os.Exit(1)
	}
	return daemon, t, g, d
}
Пример #24
0
// hostHosts returns a list of host addresses that are specified on the
// command line and also in a hosts file separated by new lines.
func loadHosts(context *cli.Context) ([]string, error) {
	hosts := []string(context.GlobalStringSlice("host"))
	if hostsFile := context.GlobalString("hosts"); hostsFile != "" {
		f, err := os.Open(hostsFile)
		if err != nil {
			return nil, err
		}
		defer f.Close()
		s := bufio.NewScanner(f)
		for s.Scan() {
			if err := s.Err(); err != nil {
				return nil, err
			}
			hosts = append(hosts, s.Text())
		}
	}
	return hosts, nil
}
Пример #25
0
func cmdStart(c *cli.Context) {
	username := c.GlobalString("username")
	apiKey := c.GlobalString("api-key")
	clusterName := c.GlobalString("clustername")
	endpoint := c.GlobalString("endpoint")

	if clusterName == "" {
		log.Fatalf("cluster name must not be empty")
	}

	config := &interlock.Config{}

	client, err := libcarina.NewClusterClient(endpoint, username, apiKey)

	if err != nil {
		log.Fatalf("error getting access to the cluster: %s", err)
	}

	swarmURL, tlsConfig, err := client.GetDockerConfig(clusterName)
	if err != nil {
		log.Fatalf("error retrieving tls config and swarm URL: %s", err)
	}

	config.SwarmUrl = swarmURL
	config.EnabledPlugins = c.GlobalStringSlice("plugin")

	m := NewManager(config, tlsConfig)

	log.Infof("interlock running version=%s", version.FullVersion())
	if err := m.Run(); err != nil {
		log.Fatal(err)
	}

	waitForInterrupt()

	log.Infof("shutting down")
	if err := m.Stop(); err != nil {
		log.Fatal(err)
	}
}
Пример #26
0
func runMigrations(ctx *cli.Context) (bool, error) {
	e := etcd2.New(ctx.GlobalString("prefix"), ctx.GlobalStringSlice("etcd"))

	if len(ctx.Args()) > 0 {
		i, err := strconv.Atoi(ctx.Args()[0])
		if err != nil {
			return true, errored.Errorf("Invalid migration version: %v", ctx.Args()[0])
		}

		targetVersion := int64(i)

		if targetVersion < 1 || targetVersion > latestMigrationVersion {
			return false, errored.Errorf("%d is outside valid migration range - min: 1, max %d", targetVersion, latestMigrationVersion)
		}

		promptBeforeRunning(ctx, fmt.Sprintf("You have requested to run all pending migrations up to and including #%d.", targetVersion))
		return runMigrationsUpTo(e, targetVersion)
	}

	promptBeforeRunning(ctx, "You have requested to run all pending migrations.")
	return runAllMigrations(e)
}
Пример #27
0
func cmdStart(c *cli.Context) {
	swarmURL := c.GlobalString("swarm-url")
	swarmTLSCaCert := c.GlobalString("swarm-tls-ca-cert")
	swarmTLSCert := c.GlobalString("swarm-tls-cert")
	swarmTLSKey := c.GlobalString("swarm-tls-key")
	allowInsecureTLS := c.GlobalBool("swarm-allow-insecure")

	// only load env vars if no args
	// check environment for docker client config
	envDockerHost := os.Getenv("DOCKER_HOST")
	if swarmURL == "" && envDockerHost != "" {
		swarmURL = envDockerHost
	}

	// only load env vars if no args
	envDockerCertPath := os.Getenv("DOCKER_CERT_PATH")
	envDockerTLSVerify := os.Getenv("DOCKER_TLS_VERIFY")
	if swarmTLSCaCert == "" && envDockerCertPath != "" && envDockerTLSVerify != "" {
		swarmTLSCaCert = filepath.Join(envDockerCertPath, "ca.pem")
		swarmTLSCert = filepath.Join(envDockerCertPath, "cert.pem")
		swarmTLSKey = filepath.Join(envDockerCertPath, "key.pem")
	}

	config := &interlock.Config{}
	config.SwarmUrl = swarmURL
	config.EnabledPlugins = c.GlobalStringSlice("plugin")

	// load tlsconfig
	var tlsConfig *tls.Config
	if swarmTLSCaCert != "" && swarmTLSCert != "" && swarmTLSKey != "" {
		log.Infof("using tls for communication with swarm")
		caCert, err := ioutil.ReadFile(swarmTLSCaCert)
		if err != nil {
			log.Fatalf("error loading tls ca cert: %s", err)
		}

		cert, err := ioutil.ReadFile(swarmTLSCert)
		if err != nil {
			log.Fatalf("error loading tls cert: %s", err)
		}

		key, err := ioutil.ReadFile(swarmTLSKey)
		if err != nil {
			log.Fatalf("error loading tls key: %s", err)
		}

		cfg, err := getTLSConfig(caCert, cert, key, allowInsecureTLS)
		if err != nil {
			log.Fatalf("error configuring tls: %s", err)
		}
		tlsConfig = cfg
	}

	m := manager.NewManager(config, tlsConfig)

	log.Infof("interlock running version=%s", version.FullVersion())
	if err := m.Run(); err != nil {
		log.Fatal(err)
	}

	waitForInterrupt()

	log.Infof("shutting down")
	if err := m.Stop(); err != nil {
		log.Fatal(err)
	}
}
Пример #28
0
func defaultAction(c *cli.Context) {
	thisCfg := new(AppCfg)
	thisCfg.Lines = c.Int("lines")
	thisCfg.Fail = c.Bool("fail")
	thisCfg.Color = c.BoolT("color")

	// If no flag, get current username
	u := c.String("user")
	if len(u) == 0 {
		usr, err := user.Current()
		if err == nil {
			u = usr.Username
		}
	}

	// Load SSH keys
	auths, err := getKeyAuths(c.GlobalStringSlice("key")...)
	if err != nil {
		log.Error("Error loading key", err)
	}

	if len(auths) == 0 {
		log.Error("No keys defined, cannot continue!", nil)
		cli.ShowAppHelp(c)
		os.Exit(2)
	}

	for _, target := range c.StringSlice("server") {
		thisHost := &HostConfig{
			User:  u,
			Auths: auths,
			Addr:  portAddrCheck(target),
		}
		thisCfg.Hosts = append(thisCfg.Hosts, thisHost)
	}

	// host(s) is required
	if len(thisCfg.Hosts) == 0 {
		log.Error("At least one host is required", nil)
		cli.ShowAppHelp(c)
		os.Exit(2)
	}

	// At least one command is required
	if len(c.Args().First()) == 0 {
		log.Error("At least one command is required", nil)
		cli.ShowAppHelp(c)
		os.Exit(2)
	}
	// append list of commands to argList
	thisCfg.Cmds = append([]string{c.Args().First()}, c.Args().Tail()...)
	done := make(chan bool, len(thisCfg.Hosts))

	for _, h := range thisCfg.Hosts {
		go handleHost(h, thisCfg.Cmds, thisCfg.Color, thisCfg.Lines, thisCfg.Fail, done)
	}

	// Drain chan before exiting
	for i := 0; i < len(thisCfg.Hosts); i++ {
		<-done
	}
}
Пример #29
0
func run(c *cli.Context) {
	err := checkFolder(c.GlobalString("path"))
	if err != nil {
		logger().Fatalf("Cound not check/create path: %v", err)
	}

	conf := NewConfiguration(c)

	//TODO: move to account struct? Currently MUST pass email.
	if !c.GlobalIsSet("email") {
		logger().Fatal("You have to pass an account (email address) to the program using --email or -m")
	}

	acc := NewAccount(c.GlobalString("email"), conf)
	client := acme.NewClient(c.GlobalString("server"), acc, conf.RsaBits(), conf.OptPort())
	if acc.Registration == nil {
		reg, err := client.Register()
		if err != nil {
			logger().Fatalf("Could not complete registration -> %v", err)
		}

		acc.Registration = reg
		acc.Save()

		logger().Print("!!!! HEADS UP !!!!")
		logger().Printf(`
			Your account credentials have been saved in your Let's Encrypt
			configuration directory at "%s".
			You should make a secure backup	of this folder now. This
			configuration directory will also contain certificates and
			private keys obtained from Let's Encrypt so making regular
			backups of this folder is ideal.

			If you lose your account credentials, you can recover
			them using the token
			"%s".
			You must write that down and put it in a safe place.`, c.GlobalString("config-dir"), reg.Body.Recoverytoken)

	}

	if acc.Registration.Body.Agreement == "" {
		if !c.GlobalBool("agree-tos") {
			reader := bufio.NewReader(os.Stdin)
			logger().Printf("Please review the TOS at %s", acc.Registration.TosURL)

			for {
				logger().Println("Do you accept the TOS? Y/n")
				text, err := reader.ReadString('\n')
				if err != nil {
					logger().Fatalf("Could not read from console -> %v", err)
				}

				text = strings.Trim(text, "\r\n")

				if text == "n" {
					logger().Fatal("You did not accept the TOS. Unable to proceed.")
				}

				if text == "Y" || text == "y" || text == "" {
					err = client.AgreeToTos()
					if err != nil {
						logger().Fatalf("Could not agree to tos -> %v", err)
					}
					acc.Save()
					break
				}

				logger().Println("Your input was invalid. Please answer with one of Y/y, n or by pressing enter.")
			}
		}
	}

	if !c.GlobalIsSet("domains") {
		logger().Fatal("Please specify --domains")
	}

	certs, err := client.ObtainCertificates(c.GlobalStringSlice("domains"))
	if err != nil {
		logger().Fatalf("Could not obtain certificates -> %v", err)
	}

	err = checkFolder(conf.CertPath())
	if err != nil {
		logger().Fatalf("Cound not check/create path: %v", err)
	}

	for _, certRes := range certs {
		certOut := path.Join(conf.CertPath(), certRes.Domain+".crt")
		privOut := path.Join(conf.CertPath(), certRes.Domain+".key")

		err = ioutil.WriteFile(certOut, certRes.Certificate, 0700)
		if err != nil {
			logger().Printf("Unable to save Certificate for domain %s -> %v", certRes.Domain, err)
		}

		err = ioutil.WriteFile(privOut, certRes.PrivateKey, 0700)
		if err != nil {
			logger().Printf("Unable to save PrivateKey for domain %s -> %v", certRes.Domain, err)
		}

	}
}
Пример #30
0
func runWithArgs(c *cli.Context) {
	timeout := c.Duration("error-timeout")
	if timeout == 0 {
		log.Println("timeout not specified(or specied as 0); using default 30s")
		timeout = 30 * time.Second
	}

	startCmd := c.GlobalString("leader-start-command")
	if startCmd == "" {
		log.Fatal("leader-start-command is required.")
	}

	endCmd := c.GlobalString("leader-end-command")
	if endCmd == "" {
		log.Fatal("leader-end-command is required.")
	}

	backendName := c.GlobalString("backend")
	var backend elector.ElectionBackend

	switch backendName {
	case "etcd-lock":
		keyspace := c.GlobalString("etcd-keyspace")
		if keyspace == "" {
			log.Fatal("keyspace is required.")
		}

		members := c.GlobalStringSlice("etcd-members")
		if len(members) < 1 {
			log.Fatal("at least one etcd-members is required.")
		}

		instanceID := c.GlobalString("instance-id")

		caFile := c.GlobalString("ca-file")
		certFile := c.GlobalString("cert-file")
		keyFile := c.GlobalString("key-file")

		backend = &backends.EtcdLock{
			Members:    &members,
			Keyspace:   &keyspace,
			InstanceID: &instanceID,

			CAFile:   &caFile,
			CertFile: &certFile,
			KeyFile:  &keyFile,
		}
	case "console":
		backend = &backends.Console{}
	default:
		log.Fatal("must specify a valid backend.")
	}

	elector := &elector.Elector{
		BeginLeaderHandler: handlers.CommandHandler(&startCmd),
		EndLeaderHandler:   handlers.CommandHandler(&endCmd),
		ErrorHandler:       handlers.TimeoutHandler(&timeout),

		ElectionBackend: backend,
	}

	err := elector.Run()
	if err != nil {
		log.Fatal(err)
	}
}