本文整理汇总了Golang中github.com/codegangsta/cli.Context.Duration方法的典型用法代码示例。如果您正苦于以下问题:Golang Context.Duration方法的具体用法?Golang Context.Duration怎么用?Golang Context.Duration使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类github.com/codegangsta/cli.Context
的用法示例。
在下文中一共展示了Context.Duration方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: PopulateFlags
// Add the flags accepted by run to the supplied flag set, returning the
// variables into which the flags will parse.
func PopulateFlags(c *cli.Context) (flags *FlagStorage) {
flags = &FlagStorage{
// File system
MountOptions: make(map[string]string),
DirMode: os.FileMode(c.Int("dir-mode")),
FileMode: os.FileMode(c.Int("file-mode")),
Uid: uint32(c.Int("uid")),
Gid: uint32(c.Int("gid")),
// Tuning,
StatCacheTTL: c.Duration("stat-cache-ttl"),
TypeCacheTTL: c.Duration("type-cache-ttl"),
// OSS
Endpoint: c.String("endpoint"),
UsePathRequest: c.Bool("use-path-request"),
Internal: c.Bool("internal"),
// Debugging,
DebugFuse: c.Bool("debug_fuse"),
DebugOSS: c.Bool("debug_oss"),
}
// Handle the repeated "-o" flag.
for _, o := range c.StringSlice("o") {
parseOptions(flags.MountOptions, o)
}
// Get the region/AccessKeyId/AccessKeySecret
flags.AccessKeyId = os.Getenv("ACCESS_KEY_ID")
flags.AccessKeySecret = os.Getenv("ACCESS_KEY_SECRET")
flags.Region = oss.Region(os.Getenv("OSS_REGION"))
return
}
示例2: PopulateFlags
// Add the flags accepted by run to the supplied flag set, returning the
// variables into which the flags will parse.
func PopulateFlags(c *cli.Context) (flags *FlagStorage) {
flags = &FlagStorage{
// File system
MountOptions: make(map[string]string),
DirMode: os.FileMode(c.Int("dir-mode")),
FileMode: os.FileMode(c.Int("file-mode")),
Uid: uint32(c.Int("uid")),
Gid: uint32(c.Int("gid")),
// Tuning,
StatCacheTTL: c.Duration("stat-cache-ttl"),
TypeCacheTTL: c.Duration("type-cache-ttl"),
// S3
Endpoint: c.String("endpoint"),
StorageClass: c.String("storage-class"),
UsePathRequest: c.Bool("use-path-request"),
// Debugging,
DebugFuse: c.Bool("debug_fuse"),
DebugS3: c.Bool("debug_s3"),
Foreground: c.Bool("f"),
}
// Handle the repeated "-o" flag.
for _, o := range c.StringSlice("o") {
parseOptions(flags.MountOptions, o)
}
return
}
示例3: newDockerStressor
func newDockerStressor(context *cli.Context) (ds *dockerStressor, err error) {
ds = &dockerStressor{}
client, err := dcli.NewDockerClientTimeout(
"unix:///var/run/docker.sock", nil, time.Second*5)
if err != nil {
return
}
ds.dockerClient = client
scfg, err := loadStressCfg(context.String("config"))
if err != nil {
return
}
ds.stressConfig = scfg
if context.Int("count") <= 0 {
return nil, errors.New("flag count must > 0")
}
ds.containerNum = context.Int("count")
if context.Int("concurrent") <= 0 {
return nil, errors.New("flag concurrent must > 0")
}
ds.containerConCurrent = context.Int("concurrent")
ds.containerRunTime = context.Duration("runtime")
return
}
示例4: populateFlags
// Add the flags accepted by run to the supplied flag set, returning the
// variables into which the flags will parse.
func populateFlags(c *cli.Context) (flags *flagStorage) {
flags = &flagStorage{
// File system
MountOptions: make(map[string]string),
DirMode: os.FileMode(c.Int("dir-mode")),
FileMode: os.FileMode(c.Int("file-mode")),
Uid: int64(c.Int("uid")),
Gid: int64(c.Int("gid")),
// GCS,
KeyFile: c.String("key-file"),
EgressBandwidthLimitBytesPerSecond: c.Float64("limit-bytes-per-sec"),
OpRateLimitHz: c.Float64("limit-ops-per-sec"),
// Tuning,
StatCacheTTL: c.Duration("stat-cache-ttl"),
TypeCacheTTL: c.Duration("type-cache-ttl"),
TempDir: c.String("temp-dir"),
ImplicitDirs: c.Bool("implicit-dirs"),
// Debugging,
DebugFuse: c.Bool("debug_fuse"),
DebugGCS: c.Bool("debug_gcs"),
DebugHTTP: c.Bool("debug_http"),
DebugInvariants: c.Bool("debug_invariants"),
}
// Handle the repeated "-o" flag.
for _, o := range c.StringSlice("o") {
mountpkg.ParseOptions(flags.MountOptions, o)
}
return
}
示例5: FromCLIContext
// FromCLIContext creates a Config using a cli.Context by pulling configuration
// from the flags in the context.
func FromCLIContext(c *cli.Context) *Config {
cfg := &Config{}
cfgVal := reflect.ValueOf(cfg).Elem()
for _, def := range defs {
if !def.HasField {
continue
}
field := cfgVal.FieldByName(def.FieldName)
if _, ok := def.Flag.(*cli.BoolFlag); ok {
field.SetBool(c.Bool(def.Name))
} else if _, ok := def.Flag.(*cli.DurationFlag); ok {
field.Set(reflect.ValueOf(c.Duration(def.Name)))
} else if _, ok := def.Flag.(*cli.IntFlag); ok {
field.SetInt(int64(c.Int(def.Name)))
} else if _, ok := def.Flag.(*cli.StringFlag); ok {
field.SetString(c.String(def.Name))
}
}
cfg.ProviderConfig = ProviderConfigFromEnviron(cfg.ProviderName)
return cfg
}
示例6: upsertHostAction
func (cmd *Command) upsertHostAction(c *cli.Context) {
host, err := engine.NewHost(c.String("name"), engine.HostSettings{})
if err != nil {
cmd.printError(err)
return
}
if c.String("cert") != "" || c.String("privateKey") != "" {
keyPair, err := readKeyPair(c.String("cert"), c.String("privateKey"))
if err != nil {
cmd.printError(fmt.Errorf("failed to read key pair: %s", err))
return
}
host.Settings.KeyPair = keyPair
}
host.Settings.OCSP = engine.OCSPSettings{
Enabled: c.Bool("ocsp"),
SkipSignatureCheck: c.Bool("ocspSkipCheck"),
Period: c.Duration("ocspPeriod").String(),
Responders: c.StringSlice("ocspResponder"),
}
if err := cmd.client.UpsertHost(*host); err != nil {
cmd.printError(err)
return
}
cmd.printOk("host added")
}
示例7: buildAction
func buildAction(context *cli.Context) {
signals := make(chan os.Signal, 128)
signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
config := nsq.NewConfig()
config.MsgTimeout = context.Duration("timeout")
config.MaxInFlight = context.Int("c")
consumer, err := nsq.NewConsumer(context.String("topic"), context.String("channel"), config)
if err != nil {
log.Fatal(err)
}
producer, err := nsq.NewProducer(context.String("nsqd"), config)
if err != nil {
log.Fatal(err)
}
consumer.AddConcurrentHandlers(&handler{
producer: producer,
topic: context.String("error-topic"),
channel: context.String("channel"),
}, context.Int("c"))
if err := consumer.ConnectToNSQD(context.String("nsqd")); err != nil {
log.Fatal(err)
}
for {
select {
case <-consumer.StopChan:
return
case <-signals:
consumer.Stop()
}
}
}
示例8: appStatus
func (factory *AppExaminerCommandFactory) appStatus(context *cli.Context) {
summaryFlag := context.Bool("summary")
rateFlag := context.Duration("rate")
if len(context.Args()) < 1 {
factory.ui.SayIncorrectUsage("App Name required")
factory.exitHandler.Exit(exit_codes.InvalidSyntax)
return
}
appName := context.Args()[0]
appInfo, err := factory.appExaminer.AppStatus(appName)
if err != nil {
factory.ui.SayLine(err.Error())
factory.exitHandler.Exit(exit_codes.CommandFailed)
return
}
factory.printAppInfo(appInfo)
if summaryFlag || rateFlag != 0 {
factory.printInstanceSummary(appInfo.ActualInstances)
} else {
factory.printInstanceInfo(appInfo.ActualInstances)
}
if rateFlag == 0 {
return
}
linesWritten := appStatusLinesWritten(appInfo)
closeChan := make(chan struct{})
defer factory.ui.Say(cursor.Show())
factory.ui.Say(cursor.Hide())
factory.exitHandler.OnExit(func() {
closeChan <- struct{}{}
factory.ui.Say(cursor.Show())
})
for {
select {
case <-closeChan:
return
case <-factory.clock.NewTimer(rateFlag).C():
appInfo, err = factory.appExaminer.AppStatus(appName)
if err != nil {
factory.ui.SayLine("Error getting status: " + err.Error())
return
}
factory.ui.Say(cursor.Up(linesWritten))
factory.printAppInfo(appInfo)
factory.printInstanceSummary(appInfo.ActualInstances)
linesWritten = appStatusLinesWritten(appInfo)
}
}
}
示例9: appBefore
func appBefore(c *cli.Context) error {
desc := "cli.app.Before"
switch {
case c.Bool("debug"):
log.Level = logrus.DebugLevel
case c.Bool("quiet"):
log.Level = logrus.ErrorLevel
default:
log.Level = logrus.InfoLevel
}
getConfig()
cfg.Mission = airstrike.NewMission(log)
client = sleepwalker.GetClient(&sleepwalker.Config{
Credentials: &sleepwalker.Credentials{
APIKey: c.String("key"),
APISecret: c.String("secret"),
Username: c.String("username"),
Password: c.String("password"),
},
OAuthEndpoint: espsdk.OAuthEndpoint,
APIRoot: espsdk.SandboxAPI,
Logger: log,
})
cfg.Mission.Enabled = true
cliInterval := float64(c.Duration("attack-interval") / time.Duration(time.Millisecond))
if cliInterval > 0 {
cfg.Mission.Interval = cliInterval
}
if c.Duration("warning-threshold") == 0 {
warningThreshold = time.Duration(cfg.Mission.Interval) * time.Millisecond
}
// set up the reporter for logging and console output
cfg.Mission.Reporter.URLInvariant = espsdk.APIInvariant
cfg.Mission.Reporter.WarningThreshold = warningThreshold
token = sleepwalker.Token(c.String("token"))
if viper.GetString("format") == "json" {
log.Formatter = &logrus.JSONFormatter{}
}
config = loadConfig(c.String("config"))
cfgJSON, err := json.Marshal(config)
if err != nil {
log.WithFields(logrus.Fields{
"error": "unable to marshal config",
}).Error(desc)
}
log.WithFields(logrus.Fields{"config": string(cfgJSON)}).Debug(desc)
return nil
}
示例10: collectAPIImages
func collectAPIImages(images []docker.APIImages, client *docker.Client, ctx *cli.Context, excludes []string) {
var imageSync sync.WaitGroup
grace := ctx.Duration("grace")
quiet := ctx.Bool("quiet")
options := docker.RemoveImageOptions{
Force: ctx.Bool("force"),
NoPrune: ctx.Bool("no-prune"),
}
for _, image := range images {
imageSync.Add(1)
go func(image docker.APIImages) {
defer imageSync.Done()
// Check if the image id or tag is on excludes list
for _, excludeName := range excludes {
if image.ID == excludeName {
return
}
for _, tag := range image.RepoTags {
if tag == excludeName {
return
}
}
}
// End if the image is still in the grace period
log.Printf("Inspecting image: %s\n", image.ID)
imageDetail, err := client.InspectImage(image.ID)
if err != nil {
log.Printf("Error. Failed to inspect image: %s\n", image.ID)
return
}
now := time.Now()
if now.Sub(imageDetail.Created) < grace {
return
}
// Delete image
log.Printf("Deleting image: %s\n", imageDetail.ID)
if err := client.RemoveImageExtended(imageDetail.ID, options); err == nil {
log.Printf("Deleted image: %s\n", imageDetail.ID)
if !quiet {
fmt.Printf("Deleted image: %s\n", imageDetail.ID)
}
} else {
log.Printf("Error. Failed to delete image: %s\n", imageDetail.ID)
return
}
}(image)
}
imageSync.Wait()
}
示例11: upsertServerAction
func (cmd *Command) upsertServerAction(c *cli.Context) error {
s, err := engine.NewServer(c.String("id"), c.String("url"))
if err != nil {
return err
}
if err := cmd.client.UpsertServer(engine.BackendKey{Id: c.String("backend")}, *s, c.Duration("ttl")); err != nil {
return err
}
cmd.printOk("server upserted")
return nil
}
示例12: doSplay
func doSplay(c *cli.Context) {
splay := c.Duration(`splay`)
if splay > 0 {
rand.Seed(time.Now().UnixNano())
rsplayf := splay.Seconds() * rand.Float64()
rsplay, err := time.ParseDuration(fmt.Sprintf("%fs", rsplayf))
if err == nil {
time.Sleep(rsplay)
}
}
}
示例13: getDuration
// getDuration calculates interval value since interval can be set with
// --hour and --day boolean flags
func getDuration(c *cli.Context) (duration time.Duration, err error) {
if err = validateDuration(c); err != nil {
return
}
if c.Bool("hour") {
return IntervalHour, nil
}
if c.Bool("day") {
return IntervalDay, nil
}
return c.Duration("duration") * -1, nil
}
示例14: validateDuration
func validateDuration(c *cli.Context) error {
hour := c.Bool("hour")
day := c.Bool("day")
duration := c.Duration("duration")
if hour && day {
return ErrMutuallyExclusiveFlags
}
if duration != intervalFlagDuration.Value && (hour || day) {
return ErrMutuallyExclusiveFlags
}
return nil
}
示例15: consulConfFromFlags
func consulConfFromFlags(c *cli.Context) func(*dagger.ConsulConfig) {
return func(conf *dagger.ConsulConfig) {
if c.IsSet("consul") {
conf.Address = c.String("consul")
}
if c.IsSet("consul-ttl") {
conf.TTL = c.String("consul-ttl")
}
if c.IsSet("consul-lockdelay") {
conf.LockDelay = c.Duration("consul-lockdelay")
}
}
}