当前位置: 首页>>代码示例>>Golang>>正文


Golang Context.Duration方法代码示例

本文整理汇总了Golang中github.com/urfave/cli.Context.Duration方法的典型用法代码示例。如果您正苦于以下问题:Golang Context.Duration方法的具体用法?Golang Context.Duration怎么用?Golang Context.Duration使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在github.com/urfave/cli.Context的用法示例。


在下文中一共展示了Context.Duration方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: Validate

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)
	}
}
开发者ID:aelsabbahy,项目名称:goss,代码行数:28,代码来源:validate.go

示例2: AutoAddResources

// Simple wrapper to add multiple resources
func AutoAddResources(fileName string, keys []string, c *cli.Context) error {
	setStoreFormatFromFileName(fileName)
	config := util.Config{
		IgnoreList: c.GlobalStringSlice("exclude-attr"),
		Timeout:    int(c.Duration("timeout") / time.Millisecond),
	}

	var gossConfig GossConfig
	if _, err := os.Stat(fileName); err == nil {
		gossConfig = ReadJSON(fileName)
	} else {
		gossConfig = *NewGossConfig()
	}

	sys := system.New(c)

	for _, key := range keys {
		if err := AutoAddResource(fileName, gossConfig, key, c, config, sys); err != nil {
			return err
		}
	}
	WriteJSON(fileName, gossConfig)

	return nil
}
开发者ID:aelsabbahy,项目名称:goss,代码行数:26,代码来源:add.go

示例3: cmdServe

func cmdServe(c *cli.Context) error {
	testSvc := ble.NewService(lib.TestSvcUUID)
	testSvc.AddCharacteristic(lib.NewCountChar())
	testSvc.AddCharacteristic(lib.NewEchoChar())

	if err := ble.AddService(testSvc); err != nil {
		return errors.Wrap(err, "can't add service")
	}

	fmt.Printf("Serving GATT Server for %s...\n", c.Duration("tmo"))
	ctx := ble.WithSigHandler(context.WithTimeout(context.Background(), c.Duration("tmo")))
	return chkErr(ble.AdvertiseNameAndServices(ctx, "Gopher", testSvc.UUID))
}
开发者ID:currantlabs,项目名称:ble,代码行数:13,代码来源:main.go

示例4: pollOAuthConfirmation

func pollOAuthConfirmation(context *cli.Context, deviceCode string, interval int) (*http.Client, string) {
	config := oauth2.Config{
		ClientID:     context.String("gcp-oauth-client-id"),
		ClientSecret: context.String("gcp-oauth-client-secret"),
		Endpoint: oauth2.Endpoint{
			AuthURL:  lib.DefaultConfig.GCPOAuthAuthURL,
			TokenURL: lib.DefaultConfig.GCPOAuthTokenURL,
		},
		RedirectURL: gcp.RedirectURL,
		Scopes:      []string{gcp.ScopeCloudPrint},
	}

	for {
		time.Sleep(time.Duration(interval) * time.Second)

		form := url.Values{
			"client_id":     {context.String("gcp-oauth-client-id")},
			"client_secret": {context.String("gcp-oauth-client-secret")},
			"code":          {deviceCode},
			"grant_type":    {gcpOAuthGrantTypeDevice},
		}
		response, err := postWithRetry(gcpOAuthTokenPollURL, form)
		if err != nil {
			log.Fatalln(err)
		}

		var r struct {
			Error        string `json:"error"`
			AccessToken  string `json:"access_token"`
			ExpiresIn    int    `json:"expires_in"`
			RefreshToken string `json:"refresh_token"`
		}
		json.NewDecoder(response.Body).Decode(&r)

		switch r.Error {
		case "":
			token := &oauth2.Token{RefreshToken: r.RefreshToken}
			client := config.Client(oauth2.NoContext, token)
			client.Timeout = context.Duration("gcp-api-timeout")
			return client, r.RefreshToken
		case "authorization_pending":
		case "slow_down":
			interval *= 2
		default:
			log.Fatalln(err)
		}
	}

	panic("unreachable")
}
开发者ID:jacobmarble,项目名称:cloud-print-connector,代码行数:50,代码来源:init.go

示例5: getUserClientFromToken

// getUserClientFromToken creates a user client with just a refresh token.
func getUserClientFromToken(context *cli.Context) *http.Client {
	config := &oauth2.Config{
		ClientID:     context.String("gcp-oauth-client-id"),
		ClientSecret: context.String("gcp-oauth-client-secret"),
		Endpoint: oauth2.Endpoint{
			AuthURL:  lib.DefaultConfig.GCPOAuthAuthURL,
			TokenURL: lib.DefaultConfig.GCPOAuthTokenURL,
		},
		RedirectURL: gcp.RedirectURL,
		Scopes:      []string{gcp.ScopeCloudPrint},
	}

	token := &oauth2.Token{RefreshToken: context.String("gcp-user-refresh-token")}
	client := config.Client(oauth2.NoContext, token)
	client.Timeout = context.Duration("gcp-api-timeout")

	return client
}
开发者ID:jacobmarble,项目名称:cloud-print-connector,代码行数:19,代码来源:init.go

示例6: run

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()
}
开发者ID:drone-plugins,项目名称:drone-ssh,代码行数:19,代码来源:main.go

示例7: runAgent

func runAgent(c *cli.Context) error {
	a := agent.Agent{
		DockerAddress: c.String("docker"),
		FusisAddress:  c.String("fusis-addr"),
		LabelFilter:   c.String("label-filter"),
		Interval:      c.Duration("interval"),
	}
	if a.FusisAddress == "" {
		return cli.NewExitError("Parameter --fusis-addr is mandatory", 1)
	}
	err := a.Init()
	if err != nil {
		return cli.NewExitError(err.Error(), 1)
	}
	handleSignals(&a)
	log.Print("Running agent...")
	a.Start()
	a.Wait()
	return nil
}
开发者ID:cezarsa,项目名称:fusis-agent,代码行数:20,代码来源:main.go

示例8: ProxyAction

func ProxyAction(c *cli.Context) error {
	http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
		err := HealthCheck("tcp://127.0.0.1:2379", 5*time.Second)

		if err == nil {
			fmt.Fprintf(w, "OK")
			if c.Bool("debug") {
				log.Println("OK")
			}
		} else {
			http.Error(w, err.Error(), http.StatusServiceUnavailable)
			if c.Bool("debug") {
				log.Println(err.Error())
			}
		}
	})

	time.Sleep(c.Duration("wait"))
	// TODO (llparse): determine when raft index has caught up with other nodes in metadata
	return http.ListenAndServe(c.String("port"), nil)
}
开发者ID:rancher,项目名称:catalog-dockerfiles,代码行数:21,代码来源:hcproxy.go

示例9: monitorConnector

func monitorConnector(context *cli.Context) {
	config, filename, err := lib.GetConfig(context)
	if err != nil {
		log.Fatalf("Failed to read config file: %s\n", err)
	}
	if filename == "" {
		fmt.Println("No config file was found, so using defaults")
	}

	if _, err := os.Stat(config.MonitorSocketFilename); err != nil {
		if !os.IsNotExist(err) {
			log.Fatalln(err)
		}
		log.Fatalf(
			"No connector is running, or the monitoring socket %s is mis-configured\n",
			config.MonitorSocketFilename)
	}

	timer := time.AfterFunc(context.Duration("monitor-timeout"), func() {
		log.Fatalf("Timeout after %s\n", context.Duration("monitor-timeout").String())
	})

	conn, err := net.DialTimeout("unix", config.MonitorSocketFilename, time.Second)
	if err != nil {
		log.Fatalf(
			"No connector is running, or it is not listening to socket %s\n",
			config.MonitorSocketFilename)
	}
	defer conn.Close()

	buf, err := ioutil.ReadAll(conn)
	if err != nil {
		log.Fatalln(err)
	}

	timer.Stop()

	fmt.Printf(string(buf))
}
开发者ID:jacobmarble,项目名称:cloud-print-connector,代码行数:39,代码来源:monitor.go

示例10: Serve

func Serve(c *cli.Context) {
	endpoint := c.String("endpoint")
	color.NoColor = true
	cache := cache.New(c.Duration("cache"), 30*time.Second)

	health := healthHandler{
		c:             c,
		gossConfig:    getGossConfig(c),
		sys:           system.New(c),
		outputer:      getOutputer(c),
		cache:         cache,
		gossMu:        &sync.Mutex{},
		maxConcurrent: c.Int("max-concurrent"),
	}
	if c.String("format") == "json" {
		health.contentType = "application/json"
	}
	http.Handle(endpoint, health)
	listenAddr := c.String("listen-addr")
	log.Printf("Starting to listen on: %s", listenAddr)
	log.Fatal(http.ListenAndServe(c.String("listen-addr"), nil))
}
开发者ID:aelsabbahy,项目名称:goss,代码行数:22,代码来源:serve.go

示例11: ProxyAction

func ProxyAction(c *cli.Context) error {
	SetLoggingLevel(c.Bool("debug"))

	http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
		err := HealthCheck("tcp://127.0.0.1:2379", 5*time.Second)

		if err == nil {
			fmt.Fprintf(w, "OK")
			log.Debug("HealthCheck succeeded")

		} else {
			http.Error(w, err.Error(), http.StatusServiceUnavailable)
			log.WithFields(log.Fields{
				"error": err.Error(),
			}).Debug("HealthCheck failed")
		}
	})

	time.Sleep(c.Duration("wait"))
	// TODO (llparse): determine when raft index has caught up with other nodes in metadata
	return http.ListenAndServe(c.String("port"), nil)
}
开发者ID:rancher,项目名称:catalog-dockerfiles,代码行数:22,代码来源:wrapper.go

示例12: RollingBackupAction

func RollingBackupAction(c *cli.Context) error {
	SetLoggingLevel(c.Bool("debug"))

	backupPeriod := c.Duration("period")
	retentionPeriod := c.Duration("retention")
	index := c.Int("index")

	log.WithFields(log.Fields{
		"period":    backupPeriod,
		"retention": retentionPeriod,
	}).Info("Initializing Rolling Backups")

	backupTicker := time.NewTicker(backupPeriod)
	for {
		select {
		case backupTime := <-backupTicker.C:
			CreateBackup(backupTime, index)
			DeleteBackups(backupTime, retentionPeriod)
		}
	}
	return nil
}
开发者ID:rancher,项目名称:catalog-dockerfiles,代码行数:22,代码来源:wrapper.go

示例13: cmdConnect

func cmdConnect(c *cli.Context) error {
	curr.client = nil

	var cln ble.Client
	var err error

	ctx := ble.WithSigHandler(context.WithTimeout(context.Background(), c.Duration("tmo")))
	if c.String("addr") != "" {
		curr.addr = ble.NewAddr(c.String("addr"))
		fmt.Printf("Dialing to specified address: %s\n", curr.addr)
		cln, err = ble.Dial(ctx, curr.addr)
	} else if filter(c) != nil {
		fmt.Printf("Scanning with filter...\n")
		if cln, err = ble.Connect(ctx, filter(c)); err == nil {
			curr.addr = cln.Address()
			fmt.Printf("Connected to %s\n", curr.addr)

		}
	} else if curr.addr != nil {
		fmt.Printf("Dialing to implicit address: %s\n", curr.addr)
		cln, err = ble.Dial(ctx, curr.addr)
	} else {
		return fmt.Errorf("no filter specified, and cached peripheral address")
	}
	if err == nil {
		curr.client = cln
		curr.clients[cln.Address().String()] = cln
	}
	go func() {
		<-cln.Disconnected()
		delete(curr.clients, cln.Address().String())
		curr.client = nil
		fmt.Printf("\n%s disconnected\n", cln.Address().String())
	}()
	return err
}
开发者ID:currantlabs,项目名称:ble,代码行数:36,代码来源:main.go

示例14: manage

func manage(c *cli.Context) {
	var (
		tlsConfig *tls.Config
		err       error
	)

	// If either --tls or --tlsverify are specified, load the certificates.
	if c.Bool("tls") || c.Bool("tlsverify") {
		if !c.IsSet("tlscert") || !c.IsSet("tlskey") {
			log.Fatal("--tlscert and --tlskey must be provided when using --tls")
		}
		if c.Bool("tlsverify") && !c.IsSet("tlscacert") {
			log.Fatal("--tlscacert must be provided when using --tlsverify")
		}
		tlsConfig, err = loadTLSConfig(
			c.String("tlscacert"),
			c.String("tlscert"),
			c.String("tlskey"),
			c.Bool("tlsverify"))
		if err != nil {
			log.Fatal(err)
		}
	} else {
		// Otherwise, if neither --tls nor --tlsverify are specified, abort if
		// the other flags are passed as they will be ignored.
		if c.IsSet("tlscert") || c.IsSet("tlskey") || c.IsSet("tlscacert") {
			log.Fatal("--tlscert, --tlskey and --tlscacert require the use of either --tls or --tlsverify")
		}
	}

	refreshMinInterval := c.Duration("engine-refresh-min-interval")
	refreshMaxInterval := c.Duration("engine-refresh-max-interval")
	if refreshMinInterval <= time.Duration(0)*time.Second {
		log.Fatal("min refresh interval should be a positive number")
	}
	if refreshMaxInterval < refreshMinInterval {
		log.Fatal("max refresh interval cannot be less than min refresh interval")
	}
	// engine-refresh-retry is deprecated
	refreshRetry := c.Int("engine-refresh-retry")
	if refreshRetry != 3 {
		log.Fatal("--engine-refresh-retry is deprecated. Use --engine-failure-retry")
	}
	failureRetry := c.Int("engine-failure-retry")
	if failureRetry <= 0 {
		log.Fatal("invalid failure retry count")
	}
	engineOpts := &cluster.EngineOpts{
		RefreshMinInterval: refreshMinInterval,
		RefreshMaxInterval: refreshMaxInterval,
		FailureRetry:       failureRetry,
	}

	uri := getDiscovery(c)
	if uri == "" {
		log.Fatalf("discovery required to manage a cluster. See '%s manage --help'.", c.App.Name)
	}
	discovery := createDiscovery(uri, c)
	s, err := strategy.New(c.String("strategy"))
	if err != nil {
		log.Fatal(err)
	}

	// see https://github.com/urfave/cli/issues/160
	names := c.StringSlice("filter")
	if c.IsSet("filter") || c.IsSet("f") {
		names = names[DefaultFilterNumber:]
	}
	fs, err := filter.New(names)
	if err != nil {
		log.Fatal(err)
	}

	sched := scheduler.New(s, fs)
	var cl cluster.Cluster
	switch c.String("cluster-driver") {
	case "mesos-experimental":
		log.Warn("WARNING: the mesos driver is currently experimental, use at your own risks")
		cl, err = mesos.NewCluster(sched, tlsConfig, uri, c.StringSlice("cluster-opt"), engineOpts)
	case "swarm":
		cl, err = swarm.NewCluster(sched, tlsConfig, discovery, c.StringSlice("cluster-opt"), engineOpts)
	default:
		log.Fatalf("unsupported cluster %q", c.String("cluster-driver"))
	}
	if err != nil {
		log.Fatal(err)
	}

	// see https://github.com/urfave/cli/issues/160
	hosts := c.StringSlice("host")
	if c.IsSet("host") || c.IsSet("H") {
		hosts = hosts[1:]
	}

	server := api.NewServer(hosts, tlsConfig)
	if c.Bool("replication") {
		addr := c.String("advertise")
		if addr == "" {
			log.Fatal("--advertise address must be provided when using --leader-election")
		}
//.........这里部分代码省略.........
开发者ID:yehohanan7,项目名称:swarm,代码行数:101,代码来源:manage.go

示例15: cmdScan

func cmdScan(c *cli.Context) error {
	fmt.Printf("Scanning for %s...\n", c.Duration("tmo"))
	ctx := ble.WithSigHandler(context.WithTimeout(context.Background(), c.Duration("tmo")))
	return chkErr(ble.Scan(ctx, c.Bool("dup"), advHandler, filter(c)))
}
开发者ID:currantlabs,项目名称:ble,代码行数:5,代码来源:main.go


注:本文中的github.com/urfave/cli.Context.Duration方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。