Пример #1
0
func Validate(c *cli.Context, startTime time.Time) {
	gossConfig := getGossConfig(c)
	sys := system.New(c)
	outputer := getOutputer(c)

	sleep := c.Duration("sleep")
	retryTimeout := c.Duration("retry-timeout")
	i := 1
	for {
		iStartTime := time.Now()
		out := validate(sys, gossConfig, c.Int("max-concurrent"))
		exitCode := outputer.Output(os.Stdout, out, iStartTime)
		if retryTimeout == 0 || exitCode == 0 {
			os.Exit(exitCode)
		}
		elapsed := time.Since(startTime)
		if elapsed+sleep > retryTimeout {
			color.Red("\nERROR: Timeout of %s reached before tests entered a passing state", retryTimeout)
			os.Exit(3)
		}
		color.Red("Retrying in %s (elapsed/timeout time: %.3fs/%s)\n\n\n", sleep, elapsed.Seconds(), retryTimeout)
		// Reset cache
		sys = system.New(c)
		time.Sleep(sleep)
		i++
		fmt.Printf("Attempt #%d:\n", i)
	}
}
Пример #2
0
func cmdTripDelete(c *cli.Context) error {
	// Get loggers
	printUserMsg, printError := getLoggers()

	// Check obligatory flags
	if c.String("file") == NotSetStringValue {
		printError.Fatalln(errMissingFileFlag)
	}
	id := c.Int("id")
	if id == NotSetIntValue {
		printError.Fatalln(errMissingIdFlag)
	}

	// Open data file
	f := gsqlitehandler.New(c.String("file"), dataFileProperties)
	if err := f.Open(); err != nil {
		printError.Fatalln(err)
	}
	defer f.Close()

	// Delete bicycle type
	sqlDeleteTrip := fmt.Sprintf("DELETE FROM trips WHERE id=%d;", id)
	r, err := f.Handler.Exec(sqlDeleteTrip)
	if err != nil {
		printError.Fatalln(errWritingToFile)
	}
	if i, _ := r.RowsAffected(); i == 0 {
		printError.Fatalln(errNoTripWithID)
	}

	// Show summary
	printUserMsg.Printf("deleted tirp with id = %d\n", id)

	return nil
}
Пример #3
0
// ProjectStop stops all services.
func ProjectStop(p project.APIProject, c *cli.Context) error {
	err := p.Stop(context.Background(), c.Int("timeout"), c.Args()...)
	if err != nil {
		return cli.NewExitError(err.Error(), 1)
	}
	return nil
}
func (exp *exporter) main(c *cli.Context) {
	setupLogging(c)

	registry := newRegistry()

	collector, err := exp.Init(c, registry)
	if err != nil {
		log.Fatal(err)
	}

	if exp.Tick {
		collector.Collect(registry)
		interval := c.Int("interval")
		go func() {
			for _ = range time.Tick(time.Duration(interval) * time.Second) {
				if exp.ResetOnTick {
					registry.Reset()
				}
				collector.Collect(registry)
			}
		}()
	}

	http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		w.Header().Add("Location", exp.MetricsPath)
		w.WriteHeader(http.StatusFound)
	})
	http.Handle(exp.MetricsPath, prometheus.Handler())
	if err := http.ListenAndServe(fmt.Sprintf(":%d", c.Int("port")), nil); err != nil {
		log.Fatal(err)
	}
}
// createCloudConfig creates a config object that supports cloud and (optionally) local mode.
func createCloudConfig(context *cli.Context, xmppJID, robotRefreshToken, userRefreshToken, shareScope, proxyName string, localEnable bool) *lib.Config {
	return &lib.Config{
		LocalPrintingEnable: localEnable,
		CloudPrintingEnable: true,

		XMPPJID:                   xmppJID,
		RobotRefreshToken:         robotRefreshToken,
		UserRefreshToken:          userRefreshToken,
		ShareScope:                shareScope,
		ProxyName:                 proxyName,
		XMPPServer:                lib.DefaultConfig.XMPPServer,
		XMPPPort:                  uint16(context.Int("xmpp-port")),
		XMPPPingTimeout:           context.String("xmpp-ping-timeout"),
		XMPPPingInterval:          context.String("xmpp-ping-interval"),
		GCPBaseURL:                lib.DefaultConfig.GCPBaseURL,
		GCPOAuthClientID:          context.String("gcp-oauth-client-id"),
		GCPOAuthClientSecret:      context.String("gcp-oauth-client-secret"),
		GCPOAuthAuthURL:           lib.DefaultConfig.GCPOAuthAuthURL,
		GCPOAuthTokenURL:          lib.DefaultConfig.GCPOAuthTokenURL,
		GCPMaxConcurrentDownloads: uint(context.Int("gcp-max-concurrent-downloads")),

		NativeJobQueueSize:        uint(context.Int("native-job-queue-size")),
		NativePrinterPollInterval: context.String("native-printer-poll-interval"),
		CUPSJobFullUsername:       lib.PointerToBool(context.Bool("cups-job-full-username")),
		PrefixJobIDToJobTitle:     lib.PointerToBool(context.Bool("prefix-job-id-to-job-title")),
		DisplayNamePrefix:         context.String("display-name-prefix"),
		PrinterBlacklist:          lib.DefaultConfig.PrinterBlacklist,
		PrinterWhitelist:          lib.DefaultConfig.PrinterWhitelist,
		LogLevel:                  context.String("log-level"),

		LocalPortLow:  uint16(context.Int("local-port-low")),
		LocalPortHigh: uint16(context.Int("local-port-high")),
	}
}
Пример #6
0
// mkCommandFunc executes the "mk" command.
func mkCommandFunc(c *cli.Context, ki client.KeysAPI) {
	if len(c.Args()) == 0 {
		handleError(c, ExitBadArgs, errors.New("key required"))
	}
	key := c.Args()[0]
	value, err := argOrStdin(c.Args(), os.Stdin, 1)
	if err != nil {
		handleError(c, ExitBadArgs, errors.New("value required"))
	}

	ttl := c.Int("ttl")
	inorder := c.Bool("in-order")

	var resp *client.Response
	ctx, cancel := contextWithTotalTimeout(c)
	if !inorder {
		// Since PrevNoExist means that the Node must not exist previously,
		// this Set method always creates a new key. Therefore, mk command
		// succeeds only if the key did not previously exist, and the command
		// prevents one from overwriting values accidentally.
		resp, err = ki.Set(ctx, key, value, &client.SetOptions{TTL: time.Duration(ttl) * time.Second, PrevExist: client.PrevNoExist})
	} else {
		// If in-order flag is specified then create an inorder key under
		// the directory identified by the key argument.
		resp, err = ki.CreateInOrder(ctx, key, value, &client.CreateInOrderOptions{TTL: time.Duration(ttl) * time.Second})
	}
	cancel()
	if err != nil {
		handleError(c, ExitServerError, err)
	}

	printResponseKey(resp, c.GlobalString("output"))
}
Пример #7
0
func addInvoice(ctx *cli.Context) error {
	client := getClient(ctx)

	preimage, err := hex.DecodeString(ctx.String("preimage"))
	if err != nil {
		return fmt.Errorf("unable to parse preimage: %v", err)
	}

	receipt, err := hex.DecodeString(ctx.String("receipt"))
	if err != nil {
		return fmt.Errorf("unable to parse receipt: %v", err)
	}

	invoice := &lnrpc.Invoice{
		Memo:      ctx.String("memo"),
		Receipt:   receipt,
		RPreimage: preimage,
		Value:     int64(ctx.Int("value")),
	}

	resp, err := client.AddInvoice(context.Background(), invoice)
	if err != nil {
		return err
	}

	printRespJson(struct {
		RHash string `json:"r_hash"`
	}{
		RHash: hex.EncodeToString(resp.RHash),
	})

	return nil
}
// updateGCPPrinter updates settings for a GCP printer.
func updateGCPPrinter(context *cli.Context) {
	config := getConfig(context)
	gcpConn := getGCP(config)

	var diff lib.PrinterDiff
	diff.Printer = lib.Printer{GCPID: context.String("printer-id")}

	if context.Bool("enable-quota") {
		diff.Printer.QuotaEnabled = true
		diff.QuotaEnabledChanged = true
	} else if context.Bool("disable-quota") {
		diff.Printer.QuotaEnabled = false
		diff.QuotaEnabledChanged = true
	}
	if context.Int("daily-quota") > 0 {
		diff.Printer.DailyQuota = context.Int("daily-quota")
		diff.DailyQuotaChanged = true
	}
	err := gcpConn.Update(&diff)
	if err != nil {
		fmt.Printf("Failed to update GCP printer %s: %s", context.String("printer-id"), err)
	} else {
		fmt.Printf("Updated GCP printer %s", context.String("printer-id"))
	}
}
Пример #9
0
func run(c *cli.Context) error {
	if c.String("env-file") != "" {
		_ = godotenv.Load(c.String("env-file"))
	}

	plugin := Plugin{
		Repo: Repo{
			Owner: c.String("repo.owner"),
			Name:  c.String("repo.name"),
		},
		Commit: Commit{
			Sha:    c.String("commit.sha"),
			Ref:    c.String("commit.ref"),
			Branch: c.String("commit.branch"),
			Author: c.String("commit.author"),
			Link:   c.String("commit.link"),
		},
		Build: Build{
			Number: c.Int("build.number"),
			Event:  c.String("build.event"),
			Status: c.String("build.status"),
			Deploy: c.String("build.deploy"),
			Link:   c.String("build.link"),
		},
		Config: Config{
			Webhook: c.StringSlice("webhook"),
		},
	}

	return plugin.Exec()
}
Пример #10
0
func (req *TnDestroy) FromContext(c *cli.Context) error {
	fmt.Println("In TnDestroy")
	Id := c.Int("id")
	if Id < 0 {
		return fmt.Errorf("invalid id")
	} else {
		req.Id = uint32(Id)
	}
	return nil
}
Пример #11
0
func closeChannel(ctx *cli.Context) error {
	ctxb := context.Background()
	client := getClient(ctx)

	txid, err := wire.NewShaHashFromStr(ctx.String("funding_txid"))
	if err != nil {
		return err
	}

	// TODO(roasbeef): implement time deadline within server
	req := &lnrpc.CloseChannelRequest{
		ChannelPoint: &lnrpc.ChannelPoint{
			FundingTxid: txid[:],
			OutputIndex: uint32(ctx.Int("output_index")),
		},
		Force: ctx.Bool("force"),
	}

	stream, err := client.CloseChannel(ctxb, req)
	if err != nil {
		return err
	}

	if !ctx.Bool("block") {
		return nil
	}

	for {
		resp, err := stream.Recv()
		if err == io.EOF {
			return nil
		} else if err != nil {
			return err
		}

		switch update := resp.Update.(type) {
		case *lnrpc.CloseStatusUpdate_ChanClose:
			closingHash := update.ChanClose.ClosingTxid
			txid, err := wire.NewShaHash(closingHash)
			if err != nil {
				return err
			}

			printRespJson(struct {
				ClosingTXID string `json:"closing_txid"`
			}{
				ClosingTXID: txid.String(),
			})
		}

	}

	return nil
}
Пример #12
0
func run(c *cli.Context) error {
	if c.String("env-file") != "" {
		_ = godotenv.Load(c.String("env-file"))
	}

	plugin := Plugin{
		Repo: Repo{
			FullName: c.String("repo.fullname"),
			Owner:    c.String("repo.owner"),
			Name:     c.String("repo.name"),
			Link:     c.String("repo.link"),
		},
		Build: Build{
			Commit:    c.String("commit.sha"),
			Branch:    c.String("commit.branch"),
			Ref:       c.String("commit.ref"),
			Link:      c.String("commit.link"),
			Message:   c.String("commit.message"),
			Author:    c.String("commit.author.name"),
			Email:     c.String("commit.author.email"),
			Number:    c.Int("build.number"),
			Status:    c.String("build.status"),
			Event:     c.String("build.event"),
			Deploy:    c.String("build.deploy"),
			BuildLink: c.String("build.link"),
		},
		BuildLast: Build{
			Number: c.Int("prev.build.number"),
			Status: c.String("prev.build.status"),
			Commit: c.String("prev.commit.sha"),
		},
		Config: Config{
			Token:   c.String("token"),
			Channel: c.String("channel"),
			Mapping: c.String("mapping"),
			Success: MessageOptions{
				Username:         c.String("success_username"),
				Icon:             c.String("success_icon"),
				Template:         c.String("success_template"),
				ImageAttachments: c.StringSlice("success_image_attachments"),
			},
			Failure: MessageOptions{
				Username:         c.String("failure_username"),
				Icon:             c.String("failure_icon"),
				Template:         c.String("failure_template"),
				ImageAttachments: c.StringSlice("failure_image_attachments"),
			},
		},
	}

	return plugin.Exec()
}
Пример #13
0
func logsCmd(c *CLI, ctx *cli.Context) {
	var err error
	var instance *gondor.Instance
	var service *gondor.Service

	api := c.GetAPIClient(ctx)
	instance = c.GetInstance(ctx, nil)

	if len(ctx.Args()) == 1 {
		service, err = api.Services.Get(*instance.URL, ctx.Args()[0])
		if err != nil {
			fatal(err.Error())
		}
	}

	var records []*gondor.LogRecord

	if instance != nil && service == nil {
		records, err = api.Logs.ListByInstance(*instance.URL, ctx.Int("lines"))
		if err != nil {
			fatal(err.Error())
		}
	} else if service != nil {
		records, err = api.Logs.ListByService(*service.URL, ctx.Int("lines"))
		if err != nil {
			fatal(err.Error())
		}
	}

	var color func(string) string

	for i := range records {
		record := records[i]
		switch *record.Stream {
		case "stdout":
			color = blue
			break
		case "stderr":
			color = red
			break
		}
		fmt.Printf(
			"%s %s\n",
			color(fmt.Sprintf(
				"[%s; %s]",
				*record.Timestamp,
				*record.Tag,
			)),
			strings.TrimSpace(*record.Message),
		)
	}
}
Пример #14
0
// updatedirCommandFunc executes the "updatedir" command.
func updatedirCommandFunc(c *cli.Context, ki client.KeysAPI) {
	if len(c.Args()) == 0 {
		handleError(ExitBadArgs, errors.New("key required"))
	}
	key := c.Args()[0]
	ttl := c.Int("ttl")
	ctx, cancel := contextWithTotalTimeout(c)
	_, err := ki.Set(ctx, key, "", &client.SetOptions{TTL: time.Duration(ttl) * time.Second, Dir: true, PrevExist: client.PrevExist})
	cancel()
	if err != nil {
		handleError(ExitServerError, err)
	}
}
Пример #15
0
func (req *TnTeleportEntity) FromContext(c *cli.Context) error {
	fmt.Println("In TnTeleportEntity")
	Id := c.Int("id")
	if Id < 0 {
		return fmt.Errorf("invalid id")
	} else {
		req.Id = uint32(Id)
	}

	if err := req.Dest.Set(c.String("pos")); err != nil {
		return fmt.Errorf("invalid position vector: %s", c.String("pos"))
	}
	return nil
}
Пример #16
0
func IonblogServerAction(c *cli.Context) error {

	if c.String("secret") == "" {
		log.Print("A secret value is required!")
		return errors.New("A secret value is required!")
	}

	PublishBlog()
	go ServeHook(c.Int("port"), c.String("secret"))
	go ServeSite(c.Int("webport"))

	Listen()
	return nil
}
Пример #17
0
func sendPaymentCommand(ctx *cli.Context) error {
	client := getClient(ctx)

	destNode, err := hex.DecodeString(ctx.String("dest"))
	if err != nil {
		return err
	}
	if len(destNode) != 33 {
		return fmt.Errorf("dest node pubkey must be exactly 33 bytes, is "+
			"instead: %v", len(destNode))
	}

	req := &lnrpc.SendRequest{
		Dest:     destNode,
		Amt:      int64(ctx.Int("amt")),
		FastSend: ctx.Bool("fast"),
	}

	if !ctx.Bool("debug_send") {
		rHash, err := hex.DecodeString(ctx.String("payment_hash"))
		if err != nil {
			return err
		}
		if len(rHash) != 32 {
			return fmt.Errorf("payment hash must be exactly 32 "+
				"bytes, is instead %v", len(rHash))
		}
		req.PaymentHash = rHash
	}

	paymentStream, err := client.SendPayment(context.Background())
	if err != nil {
		return err
	}

	if err := paymentStream.Send(req); err != nil {
		return err
	}

	resp, err := paymentStream.Recv()
	if err != nil {
		return err
	}

	paymentStream.CloseSend()

	printRespJson(resp)

	return nil
}
Пример #18
0
// Executes the "serve" command
func execServeCommand(c *cli.Context) error {
	name, err := os.Hostname()
	if err != nil {
		return cli.NewExitError(err.Error(), 1)
	}

	concurrency := c.Int("concurrency")
	if concurrency < 0 {
		concurrency = runtime.NumCPU()
	}

	if c.String("siterepo") == "" {
		return cli.NewExitError(errNoSiteRepo.Error(), 64)
	}

	nameFlag := c.String("name")
	if nameFlag != "" {
		name = nameFlag
	}

	etcdCfg := etcdConfigFromFlags(c)
	minionCfg := &minion.EtcdMinionConfig{
		Concurrency: concurrency,
		Name:        name,
		SiteRepo:    c.String("siterepo"),
		EtcdConfig:  etcdCfg,
	}

	m, err := minion.NewEtcdMinion(minionCfg)
	if err != nil {
		return cli.NewExitError(err.Error(), 1)
	}

	// Channel on which the shutdown signal is sent
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)

	// Start minion
	err = m.Serve()
	if err != nil {
		return cli.NewExitError(err.Error(), 1)
	}

	// Block until a shutdown signal is received
	<-quit
	m.Stop()

	return nil
}
Пример #19
0
// main function
func doMain(c *cli.Context) error {

	var apache2 Apache2Plugin

	apache2.Host = c.String("http_host")
	apache2.Port = uint16(c.Int("http_port"))
	apache2.Path = c.String("status_page")
	apache2.Header = c.StringSlice("header")

	helper := mp.NewMackerelPlugin(apache2)
	helper.Tempfile = c.String("tempfile")

	helper.Run()
	return nil
}
Пример #20
0
func hash(c *cli.Context) error {
	fmt.Println("Enter password: "******"factor")

	hash, err := bcrypt.GenerateFromPassword(password, factor)
	if err == nil {
		fmt.Println(string(hash))
	} else {
		fmt.Printf("Error: %s\n", err)
	}

	return err
}
Пример #21
0
func sendCoins(ctx *cli.Context) error {
	ctxb := context.Background()
	client := getClient(ctx)

	req := &lnrpc.SendCoinsRequest{
		Addr:   ctx.String("addr"),
		Amount: int64(ctx.Int("amt")),
	}
	txid, err := client.SendCoins(ctxb, req)
	if err != nil {
		return err
	}

	printRespJson(txid)
	return nil
}
Пример #22
0
// newOption returns ClientOptions via parsing command line options.
func newOption(c *cli.Context) (*MQTT.ClientOptions, error) {
	opts := MQTT.NewClientOptions()

	host := c.String("host")
	port := c.Int("p")

	opts.SetClientID(getRandomClientId())

	scheme := "tcp"
	brokerUri := fmt.Sprintf("%s://%s:%d", scheme, host, port)
	log.Infof("Broker URI: %s", brokerUri)
	opts.AddBroker(brokerUri)

	opts.SetAutoReconnect(true)
	return opts, nil
}
Пример #23
0
func runWeb(c *cli.Context) error {
	startServerService()

	m := macaron.New()

	//Set Macaron Web Middleware And Routers
	web.SetDockyardMacaron(m)

	switch setting.ListenMode {
	case "http":
		listenaddr := fmt.Sprintf("%s:%d", c.String("address"), c.Int("port"))
		if err := http.ListenAndServe(listenaddr, m); err != nil {
			fmt.Printf("Start Dockyard http service error: %v\n", err.Error())
			return err
		}
		break
	case "https":
		listenaddr := fmt.Sprintf("%s:443", c.String("address"))
		server := &http.Server{Addr: listenaddr, TLSConfig: &tls.Config{MinVersion: tls.VersionTLS10}, Handler: m}
		if err := server.ListenAndServeTLS(setting.HTTPSCertFile, setting.HTTPSKeyFile); err != nil {
			fmt.Printf("Start Dockyard https service error: %v\n", err.Error())
			return err
		}
		break
	case "unix":
		listenaddr := fmt.Sprintf("%s", c.String("address"))
		if utils.IsFileExist(listenaddr) {
			os.Remove(listenaddr)
		}

		if listener, err := net.Listen("unix", listenaddr); err != nil {
			fmt.Printf("Start Dockyard unix socket error: %v\n", err.Error())
			return err
		} else {
			server := &http.Server{Handler: m}
			if err := server.Serve(listener); err != nil {
				fmt.Printf("Start Dockyard unix socket error: %v\n", err.Error())
				return err
			}
		}
		break
	default:
		break
	}

	return nil
}
Пример #24
0
func (req *TnRepair) FromContext(c *cli.Context) error {
	fmt.Println("In TnRepair")
	Id := c.Int("id")
	if Id < 0 {
		return fmt.Errorf("invalid id")
	} else {
		req.Id = uint32(Id)
	}

	BId := c.Int("bid")
	if BId < 0 {
		return fmt.Errorf("invalid building id")
	} else {
		req.BuildingId = uint32(BId)
	}
	return nil
}
func doMain(c *cli.Context) error {
	var phpopcache PhpOpcachePlugin

	phpopcache.Host = c.String("http_host")
	phpopcache.Port = uint16(c.Int("http_port"))
	phpopcache.Path = c.String("status_page")

	helper := mp.NewMackerelPlugin(phpopcache)
	helper.Tempfile = c.String("tempfile")

	if os.Getenv("MACKEREL_AGENT_PLUGIN_META") != "" {
		helper.OutputDefinitions()
	} else {
		helper.OutputValues()
	}
	return nil
}
Пример #26
0
// ProjectPort prints the public port for a port binding.
func ProjectPort(p project.APIProject, c *cli.Context) error {
	if len(c.Args()) != 2 {
		return cli.NewExitError("Please pass arguments in the form: SERVICE PORT", 1)
	}

	index := c.Int("index")
	protocol := c.String("protocol")
	serviceName := c.Args()[0]
	privatePort := c.Args()[1]

	port, err := p.Port(context.Background(), index, protocol, serviceName, privatePort)
	if err != nil {
		return cli.NewExitError(err.Error(), 1)
	}
	fmt.Println(port)
	return nil
}
Пример #27
0
func (p *ProjectFactory) Create(c *cli.Context) (project.APIProject, error) {
	rancherComposeFile, err := rancher.ResolveRancherCompose(c.GlobalString("file"),
		c.GlobalString("rancher-file"))
	if err != nil {
		return nil, err
	}

	qLookup, err := rLookup.NewQuestionLookup(rancherComposeFile, &lookup.OsEnvLookup{})
	if err != nil {
		return nil, err
	}

	envLookup, err := rLookup.NewFileEnvLookup(c.GlobalString("env-file"), qLookup)
	if err != nil {
		return nil, err
	}

	context := &rancher.Context{
		Context: project.Context{
			ResourceLookup:    &rLookup.FileResourceLookup{},
			EnvironmentLookup: envLookup,
			LoggerFactory:     logger.NewColorLoggerFactory(),
		},
		RancherComposeFile: c.GlobalString("rancher-file"),
		Url:                c.GlobalString("url"),
		AccessKey:          c.GlobalString("access-key"),
		SecretKey:          c.GlobalString("secret-key"),
		PullCached:         c.Bool("cached"),
		Uploader:           &rancher.S3Uploader{},
		Args:               c.Args(),
		BindingsFile:       c.GlobalString("bindings-file"),
	}
	qLookup.Context = context

	command.Populate(&context.Context, c)

	context.Upgrade = c.Bool("upgrade") || c.Bool("force-upgrade")
	context.ForceUpgrade = c.Bool("force-upgrade")
	context.Rollback = c.Bool("rollback")
	context.BatchSize = int64(c.Int("batch-size"))
	context.Interval = int64(c.Int("interval"))
	context.ConfirmUpgrade = c.Bool("confirm-upgrade")
	context.Pull = c.Bool("pull")

	return rancher.NewProject(context)
}
Пример #28
0
// mkdirCommandFunc executes the "mkdir" command.
func mkdirCommandFunc(c *cli.Context, ki client.KeysAPI, prevExist client.PrevExistType) {
	if len(c.Args()) == 0 {
		handleError(ExitBadArgs, errors.New("key required"))
	}

	key := c.Args()[0]
	ttl := c.Int("ttl")

	ctx, cancel := contextWithTotalTimeout(c)
	resp, err := ki.Set(ctx, key, "", &client.SetOptions{TTL: time.Duration(ttl) * time.Second, Dir: true, PrevExist: prevExist})
	cancel()
	if err != nil {
		handleError(ExitServerError, err)
	}
	if c.GlobalString("output") != "simple" {
		printResponseKey(resp, c.GlobalString("output"))
	}
}
Пример #29
0
func run(c *cli.Context) error {
	if c.String("env-file") != "" {
		_ = godotenv.Load(c.String("env-file"))
	}

	plugin := Plugin{
		Config: Config{
			Key:     c.String("ssh-key"),
			User:    c.String("user"),
			Host:    c.StringSlice("host"),
			Port:    c.Int("port"),
			Sleep:   c.Int("sleep"),
			Timeout: c.Duration("timeout"),
			Script:  c.StringSlice("script"),
		},
	}

	return plugin.Exec()
}
Пример #30
0
func parseOthersFlagsForRunContext(ctx *cli.Context, ctxRun *action.Context) error {
	if ctx.IsSet("format") {
		format := ctx.String("format")
		subformat := ""
		//TODO: refactor it!
		if strings.Contains(format, "raw:") {
			subformat = format[len("raw:"):]
			format = "raw"
		}
		if strings.Contains(format, "table:") {
			subformat = format[len("table:"):]
			format = "table"
		}
		if strings.Contains(format, "json:") {
			subformat = format[len("json:"):]
			format = "json"
		}
		if strings.Contains(format, "xml:") {
			subformat = format[len("xml:"):]
			format = "xml"
		}

		switch format {
		case "table", "raw", "json", "xml":
			ctxRun.Set("format", format)
			ctxRun.Set("subformat", subformat)
			break
		default:
			return fmt.Errorf("Unknown format:%s", format)
		}
	} else {
		ctxRun.Set("format", "raw")
	}

	if ctx.IsSet("timeout") {
		ctxRun.Set("timeout", ctx.Int("timeout"))
	}
	if ctx.IsSet("commit") {
		ctxRun.Set("commit", ctx.Bool("commit"))
	}
	return nil
}