Exemplo n.º 1
0
func ValidateNodeAuthConfig(config api.NodeAuthConfig) fielderrors.ValidationErrorList {
	allErrs := fielderrors.ValidationErrorList{}

	if len(config.AuthenticationCacheTTL) == 0 {
		allErrs = append(allErrs, fielderrors.NewFieldRequired("authenticationCacheTTL"))
	} else if ttl, err := time.ParseDuration(config.AuthenticationCacheTTL); err != nil {
		allErrs = append(allErrs, fielderrors.NewFieldInvalid("authenticationCacheTTL", config.AuthenticationCacheTTL, fmt.Sprintf("%v", err)))
	} else if ttl < 0 {
		allErrs = append(allErrs, fielderrors.NewFieldInvalid("authenticationCacheTTL", config.AuthenticationCacheTTL, fmt.Sprintf("cannot be less than zero")))
	}

	if config.AuthenticationCacheSize <= 0 {
		allErrs = append(allErrs, fielderrors.NewFieldInvalid("authenticationCacheSize", config.AuthenticationCacheSize, fmt.Sprintf("must be greater than zero")))
	}

	if len(config.AuthorizationCacheTTL) == 0 {
		allErrs = append(allErrs, fielderrors.NewFieldRequired("authorizationCacheTTL"))
	} else if ttl, err := time.ParseDuration(config.AuthorizationCacheTTL); err != nil {
		allErrs = append(allErrs, fielderrors.NewFieldInvalid("authorizationCacheTTL", config.AuthorizationCacheTTL, fmt.Sprintf("%v", err)))
	} else if ttl < 0 {
		allErrs = append(allErrs, fielderrors.NewFieldInvalid("authorizationCacheTTL", config.AuthorizationCacheTTL, fmt.Sprintf("cannot be less than zero")))
	}

	if config.AuthorizationCacheSize <= 0 {
		allErrs = append(allErrs, fielderrors.NewFieldInvalid("authorizationCacheSize", config.AuthorizationCacheSize, fmt.Sprintf("must be greater than zero")))
	}

	return allErrs
}
Exemplo n.º 2
0
func ParseWait(s string) (*Wait, error) {
	if len(strings.TrimSpace(s)) < 1 {
		return &Wait{0, 0}, nil
	}

	parts := strings.Split(s, ":")

	var (
		min time.Duration
		max time.Duration
		err error
	)
	min, err = time.ParseDuration(strings.TrimSpace(parts[0]))
	if err != nil {
		return nil, err
	}
	if len(parts) > 1 {
		max, err = time.ParseDuration(strings.TrimSpace(parts[1]))
		if err != nil {
			return nil, err
		}
		if max < min {
			return nil, errors.New("Invalid wait interval: max must be larger than min")
		}
	} else {
		max = 4 * min
	}

	return &Wait{min, max}, nil
}
Exemplo n.º 3
0
// extract a Message from bytes
func (m *Message) extract(b []byte) {
	slices := bytes.Split(b, []byte{'|'})
	i := bytes.Index(b, []byte{'|'})
	m.Type = "default"
	if i != -1 {
		// well I know how I'd do it in python
		// this seems a little awkward
		m.dirtyfields = make(map[int]bool)
		if res, err := get(0, slices); err == nil {
			m.setField(0, string(res))
		}
	}
	if res, err := get(1, slices); err == nil {
		if string(res) != "" {
			m.setField(1, string(res))
		}
	}
	if res, err := get(2, slices); err == nil {
		m.setField(2, string(res))
	}
	if res, err := get(3, slices); err == nil {
		if t, err2 := strconv.Atoi(string(res)); err2 == nil {
			Timeout, _ := time.ParseDuration(fmt.Sprintf("%ds", t))
			m.setField(3, Timeout)
		} else {
			if d, err3 := time.ParseDuration(string(res)); err3 == nil {
				m.setField(3, d)
			}
		}
	}
}
Exemplo n.º 4
0
func (b *backend) pathConfigLeaseWrite(
	req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
	ttlRaw := d.Get("ttl").(string)
	ttlMaxRaw := d.Get("max_ttl").(string)
	if len(ttlMaxRaw) == 0 {
		ttlMaxRaw = d.Get("ttl_max").(string)
	}

	ttl, err := time.ParseDuration(ttlRaw)
	if err != nil {
		return logical.ErrorResponse(fmt.Sprintf(
			"Invalid ttl: %s", err)), nil
	}
	ttlMax, err := time.ParseDuration(ttlMaxRaw)
	if err != nil {
		return logical.ErrorResponse(fmt.Sprintf(
			"Invalid max_ttl: %s", err)), nil
	}

	// Store it
	entry, err := logical.StorageEntryJSON("config/lease", &configLease{
		TTL:    ttl,
		TTLMax: ttlMax,
	})
	if err != nil {
		return nil, err
	}
	if err := req.Storage.Put(entry); err != nil {
		return nil, err
	}

	return nil, nil
}
Exemplo n.º 5
0
func ValidateNodeAuthConfig(config api.NodeAuthConfig, fldPath *field.Path) field.ErrorList {
	allErrs := field.ErrorList{}

	authenticationCacheTTLPath := fldPath.Child("authenticationCacheTTL")
	if len(config.AuthenticationCacheTTL) == 0 {
		allErrs = append(allErrs, field.Required(authenticationCacheTTLPath, ""))
	} else if ttl, err := time.ParseDuration(config.AuthenticationCacheTTL); err != nil {
		allErrs = append(allErrs, field.Invalid(authenticationCacheTTLPath, config.AuthenticationCacheTTL, fmt.Sprintf("%v", err)))
	} else if ttl < 0 {
		allErrs = append(allErrs, field.Invalid(authenticationCacheTTLPath, config.AuthenticationCacheTTL, fmt.Sprintf("cannot be less than zero")))
	}

	if config.AuthenticationCacheSize <= 0 {
		allErrs = append(allErrs, field.Invalid(fldPath.Child("authenticationCacheSize"), config.AuthenticationCacheSize, fmt.Sprintf("must be greater than zero")))
	}

	authorizationCacheTTLPath := fldPath.Child("authorizationCacheTTL")
	if len(config.AuthorizationCacheTTL) == 0 {
		allErrs = append(allErrs, field.Required(authorizationCacheTTLPath, ""))
	} else if ttl, err := time.ParseDuration(config.AuthorizationCacheTTL); err != nil {
		allErrs = append(allErrs, field.Invalid(authorizationCacheTTLPath, config.AuthorizationCacheTTL, fmt.Sprintf("%v", err)))
	} else if ttl < 0 {
		allErrs = append(allErrs, field.Invalid(authorizationCacheTTLPath, config.AuthorizationCacheTTL, fmt.Sprintf("cannot be less than zero")))
	}

	if config.AuthorizationCacheSize <= 0 {
		allErrs = append(allErrs, field.Invalid(fldPath.Child("authorizationCacheSize"), config.AuthorizationCacheSize, fmt.Sprintf("must be greater than zero")))
	}

	return allErrs
}
Exemplo n.º 6
0
func (server *server) statistics() serverStats {
	stats := *server.stats
	stats.Uptime = time.Since(server.startedAt).Seconds()
	stats.CurrentTubes = len(server.tubes)
	stats.TotalJobs = len(server.jobs)

	for _, tube := range server.tubes {
		stats.CurrentJobsBuried += tube.buried.Len()
		stats.CurrentJobsDelayed += tube.delayed.Len()
		stats.CurrentJobsReady += tube.ready.Len()
		stats.CurrentJobsReserved += tube.reserved.Len()
	}

	var duration time.Duration
	usage := new(syscall.Rusage)
	err := syscall.Getrusage(syscall.RUSAGE_SELF, usage)
	if err == nil {
		s, ns := usage.Utime.Unix()
		duration, err = time.ParseDuration(fmt.Sprintf("%d.%ds", s, ns))
		stats.RusageStime = duration.Seconds()

		s, ns = usage.Stime.Unix()
		duration, err = time.ParseDuration(fmt.Sprintf("%d.%ds", s, ns))
		stats.RusageUtime = duration.Seconds()
	} else {
		pf("failed to get rusage : %v", err)
	}

	return stats
}
Exemplo n.º 7
0
func New(cookieName string, expires int, sessionDir string, timerDuration string) *SessionManager {
	if cookieName == "" {
		cookieName = "GoLangerSession"
	}

	if expires <= 0 {
		expires = 3600 * 24
	}

	if sessionDir == "" {
		sessionDir = "./tmp/" + "golangersession/"
	}

	os.MkdirAll(sessionDir, 0777)

	var dTimerDuration time.Duration

	if td, terr := time.ParseDuration(timerDuration); terr == nil {
		dTimerDuration = td
	} else {
		dTimerDuration, _ = time.ParseDuration("24h")
	}

	s := &SessionManager{
		CookieName:    cookieName,
		expires:       expires,
		sessionDir:    sessionDir,
		timerDuration: dTimerDuration,
	}

	time.AfterFunc(s.timerDuration, func() { s.GC() })

	return s
}
Exemplo n.º 8
0
func init() {
	Environment = getEnv("_DEPLOY_ENV")
	SignalfxAPIKey = getEnv("SIGNALFX_API_KEY")
	data := getEnv("POLLING_CONFIG")

	err := yaml.Unmarshal([]byte(data), &PollingConfigs)
	if err != nil {
		log.Fatalf("error: %v", err)
	}

	for i := range PollingConfigs {
		fmt.Printf("%+v", PollingConfigs[i])
		pollInterval, err := time.ParseDuration(PollingConfigs[i].PollIntervalRaw)
		if err != nil {
			log.Fatalf("Could not parse duration from poll_interval: %s", err)
		}
		PollingConfigs[i].PollInterval = pollInterval
		// default to http for backwards compatibility
		if PollingConfigs[i].RabbitMQProto == "" {
			PollingConfigs[i].RabbitMQProto = "http"
		}

		var timeout time.Duration
		if PollingConfigs[i].TimeoutRaw != "" {
			timeout, err = time.ParseDuration(PollingConfigs[i].TimeoutRaw)
			if err != nil {
				log.Fatalf("Could not parse duration from timeout: %s", err)
			}
		} else {
			// default to 60 seconds
			timeout = time.Duration(60 * time.Second)
		}
		PollingConfigs[i].Timeout = timeout
	}
}
Exemplo n.º 9
0
func decodeConfig(configBytes []byte) (*ProxyConfig, error) {
	var config ProxyConfig
	if err := json.Unmarshal(configBytes, &config); err != nil {
		return nil, err
	}
	if config.StatsDelay != nil {
		duration, err := time.ParseDuration(*config.StatsDelay)
		config.StatsDelayDuration = &duration
		if err != nil {
			return nil, err
		}
	}
	for _, f := range config.ForwardTo {
		if f.Timeout != nil {
			duration, err := time.ParseDuration(*f.Timeout)
			f.TimeoutDuration = &duration
			if err != nil {
				return nil, err
			}
		}
	}
	for _, f := range config.ListenFrom {
		if f.Timeout != nil {
			duration, err := time.ParseDuration(*f.Timeout)
			f.TimeoutDuration = &duration
			if err != nil {
				return nil, err
			}
		}
	}
	return &config, nil
}
Exemplo n.º 10
0
func (c ControllerOptions) toContainerControllerOptions() (options container.ControllerOptions, err error) {
	options.ServicedEndpoint = c.ServicedEndpoint
	options.Service.Autorestart = c.Autorestart
	options.Service.InstanceID = c.InstanceID
	options.Service.ID = c.ServiceID
	options.Service.Command = c.Command
	options.Mux.Port = c.MuxPort
	options.Mux.Enabled = c.Mux
	options.Mux.TLS = c.TLS
	options.Mux.KeyPEMFile = c.KeyPEMFile
	options.Mux.CertPEMFile = c.CertPEMFile
	options.Logforwarder.Enabled = c.Logstash
	options.Logforwarder.Path = c.LogstashBinary
	options.Logforwarder.ConfigFile = c.LogstashConfig
	options.Metric.Address = c.MetricForwarderPort
	options.MetricForwarding = c.MetricForwardingEnabled
	options.Metric.RemoteEndoint = "http://localhost:8444/api/metrics/store"
	options.VirtualAddressSubnet = c.VirtualAddressSubnet
	options.Logforwarder.SettleTime, err = time.ParseDuration(c.LogstashSettleTime)
	if err != nil {
		return options, err
	}
	options.Logforwarder.IdleFlushTime, err = time.ParseDuration(c.LogstashIdleFlushTime)
	if err != nil {
		return options, err
	}

	return options, nil
}
Exemplo n.º 11
0
func GetAccessToken() (string, error) {
	if cacheServer != nil {
		tokenS, found := cacheServer.Get(key_access_token)
		if found {
			switch tokenS.(type) {
			case string:
				return tokenS.(string), nil
			default:
				return "", fmt.Errorf("access_token from cache is not type string.\n")
			}
		}
		token, err := wapi.GetAcessToken()
		if err != nil {
			return "", fmt.Errorf("wapi GetAcessToken error. %s\n", err.Error())
		}
		expires_in, err := time.ParseDuration(strconv.Itoa(token.Expires_in) + "s")
		if err != nil {
			log.Panicf("format expires [%s] err:%s\n", token.Expires_in, err.Error())
			log.Printf("use default expires_in %s", default_expires_in)
			expires_in, err = time.ParseDuration(default_expires_in + "s")
			if err != nil {
				return "", fmt.Errorf("format default expires [%s] err:%s\n", token.Expires_in, err.Error())
			}
		}
		cacheServer.Add(key_access_token, token.Access_token, expires_in)
		return token.Access_token, nil
	}
	return "", fmt.Errorf("cacheServer is nil.\n")
}
Exemplo n.º 12
0
func parseDuration(s string) (time.Duration, error) {
	var interval time.Duration
	if s[len(s)-1] == 'd' {
		days, err := strconv.ParseInt(s[0:len(s)-1], 10, 64)
		if err != nil {
			return time.Nanosecond, err
		}
		interval, err = time.ParseDuration(strconv.FormatInt(days*24, 10) + "h")
		if err != nil {
			return time.Nanosecond, err
		}
	} else if s[len(s)-1] == 'h' ||
		s[len(s)-1] == 'm' ||
		s[len(s)-1] == 's' {
		return time.ParseDuration(s)
	} else {
		seconds, err := strconv.ParseInt(s, 10, 64)
		if err != nil {
			return time.Nanosecond, err
		}
		interval, err = time.ParseDuration(strconv.FormatInt(seconds, 10) + "s")
		if err != nil {
			return time.Nanosecond, err
		}
	}
	return interval, nil
}
Exemplo n.º 13
0
Arquivo: game.go Projeto: robsix/rps
func (g *game) Kick() bool {
	if g.State == _WAITING_FOR_OPPONENT || g.State == _DEACTIVATED {
		return false
	}

	ret := false
	if g.State == _GAME_IN_PROGRESS {
		dur, _ := time.ParseDuration(strconv.Itoa(turnLength) + _TIME_UNIT)
		if now().After(g.TurnStart.Add(dur)) {
			g.State = _WAITING_FOR_REMATCH
			ret = true
			for i := 0; i < 2; i++ {
				if g.CurrentChoices[i] == `` {
					g.CurrentChoices[i] = options[rand.Intn(len(options))]
				}
			}
			g.PastChoices = append(g.PastChoices, g.CurrentChoices[0], g.CurrentChoices[1])
			if len(g.PastChoices) >= _DOUBLE_MAX_TURNS {
				g.State = _DEACTIVATED
			} else {
				g.State = _WAITING_FOR_REMATCH
			}
		}
	}

	if g.State == _WAITING_FOR_REMATCH {
		dur, _ := time.ParseDuration(strconv.Itoa(turnLength+_REMATCH_TIME_LIMIT) + _TIME_UNIT)
		if now().After(g.TurnStart.Add(dur)) {
			g.State = _DEACTIVATED
			ret = true
		}
	}

	return ret
}
Exemplo n.º 14
0
func FixupCheckType(raw interface{}) error {
	// Handle decoding of time durations
	rawMap, ok := raw.(map[string]interface{})
	if !ok {
		return nil
	}
	if ttl, ok := rawMap["ttl"]; ok {
		ttlS, ok := ttl.(string)
		if ok {
			if dur, err := time.ParseDuration(ttlS); err != nil {
				return err
			} else {
				rawMap["ttl"] = dur
			}
		}
	}
	if interval, ok := rawMap["interval"]; ok {
		intervalS, ok := interval.(string)
		if ok {
			if dur, err := time.ParseDuration(intervalS); err != nil {
				return err
			} else {
				rawMap["interval"] = dur
			}
		}
	}
	return nil
}
Exemplo n.º 15
0
func New(cookieName string, expires int, timerDuration string) *SessionManager {
	if cookieName == "" {
		cookieName = "GoLangerSession"
	}

	if expires <= 0 {
		expires = 3600 * 24
	}

	var dTimerDuration time.Duration

	if td, terr := time.ParseDuration(timerDuration); terr == nil {
		dTimerDuration = td
	} else {
		dTimerDuration, _ = time.ParseDuration("24h")
	}

	s := &SessionManager{
		CookieName:    cookieName,
		sessions:      map[string][2]map[string]interface{}{},
		expires:       expires,
		timerDuration: dTimerDuration,
	}

	time.AfterFunc(s.timerDuration, func() { s.GC() })

	return s
}
Exemplo n.º 16
0
func TestAddJob(t *testing.T) {
	c := New("127.0.0.1:7711")
	defer TearDownAddJob(c)

	_, err := c.AddJob("test:addjob", DummyJob, AddJobOptions{})
	if err != nil {
		t.Error(err)
	}

	replicate, _ := time.ParseDuration("1s")
	delay, _ := time.ParseDuration("1s")
	retry, _ := time.ParseDuration("1s")
	ttl, _ := time.ParseDuration("5s")
	_, err = c.AddJob(
		"test:addjob",
		DummyJob,
		AddJobOptions{
			Replicate: replicate,
			Delay:     delay,
			Retry:     retry,
			TTL:       ttl,
			MaxLen:    10,
			Async:     true,
		},
	)
	if err != nil {
		t.Error(err)
	}
}
Exemplo n.º 17
0
Arquivo: caste.go Projeto: chyeh/cast
// ToDurationE casts an empty interface to time.Duration.
func ToDurationE(i interface{}) (d time.Duration, err error) {
	i = indirect(i)
	jww.DEBUG.Println("ToDurationE called on type:", reflect.TypeOf(i))

	switch s := i.(type) {
	case time.Duration:
		return s, nil
	case int64, int32, int16, int8, int:
		d = time.Duration(ToInt64(s))
		return
	case float32, float64:
		d = time.Duration(ToFloat64(s))
		return
	case string:
		if strings.ContainsAny(s, "nsuµmh") {
			d, err = time.ParseDuration(s)
		} else {
			d, err = time.ParseDuration(s + "ns")
		}
		return
	default:
		err = fmt.Errorf("Unable to Cast %#v to Duration\n", i)
		return
	}
}
Exemplo n.º 18
0
func (c *Config) ConstructPoolConfig(pool Pool) backend.PoolConfig {
	name, config := pool.Name, pool.Config

	healthzEvery, err := time.ParseDuration(config.HealthzEvery)
	if err != nil {
		logger.Errorf("[config %s] %s is not valid duration", name, config.HealthzEvery)
		healthzEvery = defaultHealthzEvery
	}

	healthzTimeout, err := time.ParseDuration(config.HealthzTimeout)
	if err != nil {
		logger.Errorf("[config %s] %s is not valid duration", name, config.HealthzTimeout)
		healthzTimeout = defaultHealthzTimeout
	}

	requestTimeout, err := time.ParseDuration(config.RequestTimeout)
	if err != nil {
		logger.Errorf("[config %s] %s is not valid duration", name, config.RequestTimeout)
		requestTimeout = defaultRequestTimeout
	}

	status := config.Status
	if !backend.IsValidStatus(status) {
		logger.Errorf("[config %s] %s is not valid status", name, config.Status)
		status = "OK"
	}

	return backend.PoolConfig{
		HealthzEvery:   healthzEvery,
		HealthzTimeout: healthzTimeout,
		RequestTimeout: requestTimeout,
		Status:         status,
	}
}
Exemplo n.º 19
0
func (b *backend) pathLeaseWrite(
	req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
	leaseRaw := d.Get("lease").(string)
	leaseMaxRaw := d.Get("lease_max").(string)

	lease, err := time.ParseDuration(leaseRaw)
	if err != nil {
		return logical.ErrorResponse(fmt.Sprintf(
			"Invalid lease: %s", err)), nil
	}
	leaseMax, err := time.ParseDuration(leaseMaxRaw)
	if err != nil {
		return logical.ErrorResponse(fmt.Sprintf(
			"Invalid lease: %s", err)), nil
	}

	// Store it
	entry, err := logical.StorageEntryJSON("config/lease", &configLease{
		Lease:    lease,
		LeaseMax: leaseMax,
	})
	if err != nil {
		return nil, err
	}
	if err := req.Storage.Put(entry); err != nil {
		return nil, err
	}

	return nil, nil
}
Exemplo n.º 20
0
func NewStratum(cfg *pool.Config, port pool.Port) *StratumServer {
	b := make([]byte, 4)
	_, err := rand.Read(b)
	if err != nil {
		log.Fatalf("Can't seed with random bytes: %v", err)
	}

	stratum := &StratumServer{config: cfg, port: port, instanceId: b}
	stratum.rpc = rpc.NewRPCClient(cfg)
	stratum.miners = NewMinersMap()

	timeout, _ := time.ParseDuration(cfg.Stratum.Timeout)
	stratum.timeout = timeout

	// Init block template
	stratum.blockTemplate.Store(&BlockTemplate{})
	stratum.refreshBlockTemplate(false)

	refreshIntv, _ := time.ParseDuration(cfg.Stratum.BlockRefreshInterval)
	refreshTimer := time.NewTimer(refreshIntv)
	log.Printf("Set block refresh every %v", refreshIntv)

	go func() {
		for {
			select {
			case <-refreshTimer.C:
				stratum.refreshBlockTemplate(true)
				refreshTimer.Reset(refreshIntv)
			}
		}
	}()
	return stratum
}
Exemplo n.º 21
0
// RenewPeriodic is used to periodically invoke Session.Renew on a
// session until a doneCh is closed. This is meant to be used in a long running
// goroutine to ensure a session stays valid.
func (s *Session) RenewPeriodic(initialTTL string, id string, q *WriteOptions, doneCh chan struct{}) error {
	ttl, err := time.ParseDuration(initialTTL)
	if err != nil {
		return err
	}
	for {
		select {
		case <-time.After(ttl / 2):
			entry, _, err := s.Renew(id, q)
			if err != nil {
				return err
			}
			if entry == nil {
				return nil
			}

			// Handle the server updating the TTL
			ttl, _ = time.ParseDuration(entry.TTL)

		case <-doneCh:
			// Attempt a session destroy
			s.Destroy(id, q)
			return nil
		}
	}
}
Exemplo n.º 22
0
func durationWithArguments(arguments []map[string]interface{}, key string, defaultValue time.Duration) time.Duration {
	for _, arg := range arguments {
		v, ok := arg[key]
		if !ok {
			continue
		}

		switch value := v.(type) {
		case time.Duration:
			return value
		case string:
			i, e := time.ParseDuration(value)
			if nil == e {
				return i
			}
		default:
			s := fmt.Sprint(value)
			i, e := time.ParseDuration(s)
			if nil == e {
				return i
			}
		}
	}
	return defaultValue
}
Exemplo n.º 23
0
// This method takes in the TTL and MaxTTL values provided by the user, compares
// those with the SystemView values. If they are empty default values are set.
// If they are set, their boundaries are validated.
func (b *Backend) SanitizeTTL(ttlStr, maxTTLStr string) (ttl, maxTTL time.Duration, err error) {
	sysMaxTTL := b.System().MaxLeaseTTL()
	if len(ttlStr) == 0 {
		ttl = b.System().DefaultLeaseTTL()
	} else {
		ttl, err = time.ParseDuration(ttlStr)
		if err != nil {
			return 0, 0, fmt.Errorf("Invalid ttl: %s", err)
		}
		if ttl > sysMaxTTL {
			return 0, 0, fmt.Errorf("\"ttl\" value must be less than allowed max lease TTL value '%s'", sysMaxTTL.String())
		}
	}
	if len(maxTTLStr) == 0 {
		maxTTL = sysMaxTTL
	} else {
		maxTTL, err = time.ParseDuration(maxTTLStr)
		if err != nil {
			return 0, 0, fmt.Errorf("Invalid max_ttl: %s", err)
		}
		if maxTTL > sysMaxTTL {
			return 0, 0, fmt.Errorf("\"max_ttl\" value must be less than allowed max lease TTL value '%s'", sysMaxTTL.String())
		}
	}
	if ttl > maxTTL {
		ttl = maxTTL
	}
	return
}
Exemplo n.º 24
0
func reifyDuration(
	opts fieldOptions,
	val value,
	_ reflect.Type,
) (reflect.Value, Error) {
	var d time.Duration
	var err error

	switch v := val.(type) {
	case *cfgInt:
		d = time.Duration(v.i) * time.Second
	case *cfgUint:
		d = time.Duration(v.u) * time.Second
	case *cfgFloat:
		d = time.Duration(v.f * float64(time.Second))
	case *cfgString:
		d, err = time.ParseDuration(v.s)
	default:
		var s string
		s, err = val.toString(opts.opts)
		if err != nil {
			return reflect.Value{}, raiseInvalidDuration(val, err)
		}

		d, err = time.ParseDuration(s)
	}

	if err != nil {
		return reflect.Value{}, raiseInvalidDuration(val, err)
	}
	return reflect.ValueOf(d), nil
}
Exemplo n.º 25
0
func (n *IpfsNode) setupIpnsRepublisher() error {
	cfg, err := n.Repo.Config()
	if err != nil {
		return err
	}

	n.IpnsRepub = ipnsrp.NewRepublisher(n.Routing, n.Repo.Datastore(), n.Peerstore)
	n.IpnsRepub.AddName(n.Identity)

	if cfg.Ipns.RepublishPeriod != "" {
		d, err := time.ParseDuration(cfg.Ipns.RepublishPeriod)
		if err != nil {
			return fmt.Errorf("failure to parse config setting IPNS.RepublishPeriod: %s", err)
		}

		if !u.Debug && (d < time.Minute || d > (time.Hour*24)) {
			return fmt.Errorf("config setting IPNS.RepublishPeriod is not between 1min and 1day: %s", d)
		}

		n.IpnsRepub.Interval = d
	}

	if cfg.Ipns.RecordLifetime != "" {
		d, err := time.ParseDuration(cfg.Ipns.RepublishPeriod)
		if err != nil {
			return fmt.Errorf("failure to parse config setting IPNS.RecordLifetime: %s", err)
		}

		n.IpnsRepub.RecordLifetime = d
	}

	n.Process().Go(n.IpnsRepub.Run)

	return nil
}
Exemplo n.º 26
0
func (cf *Config) Apply() (err error) {
	// runtime
	if cf.MaxProcs <= 0 {
		cf.MaxProcs = runtime.NumCPU()
	}
	runtime.GOMAXPROCS(cf.MaxProcs)

	// logging
	if err := lg.SetLevelString(strings.ToLower(cf.LogLevel)); err != nil {
		return err
	}

	// limits
	if cf.Limits.RequestTimeoutStr != "" {
		to, err := time.ParseDuration(cf.Limits.RequestTimeoutStr)
		if err != nil {
			return err
		}
		cf.Limits.RequestTimeout = to
	}
	if cf.Limits.BacklogTimeoutStr != "" {
		to, err := time.ParseDuration(cf.Limits.BacklogTimeoutStr)
		if err != nil {
			return err
		}
		cf.Limits.BacklogTimeout = to
	}

	return nil
}
Exemplo n.º 27
0
func join(c *cli.Context) {
	dflag := getDiscovery(c)
	if dflag == "" {
		log.Fatalf("discovery required to join a cluster. See '%s join --help'.", c.App.Name)
	}

	addr := c.String("advertise")
	if addr == "" {
		log.Fatal("missing mandatory --advertise flag")
	}
	if !checkAddrFormat(addr) {
		log.Fatal("--advertise should be of the form ip:port or hostname:port")
	}

	joinDelay, err := time.ParseDuration(c.String("delay"))
	if err != nil {
		log.Fatalf("invalid --delay: %v", err)
	}
	if joinDelay < time.Duration(0)*time.Second {
		log.Fatalf("--delay should not be a negative number")
	}

	hb, err := time.ParseDuration(c.String("heartbeat"))
	if err != nil {
		log.Fatalf("invalid --heartbeat: %v", err)
	}
	if hb < 1*time.Second {
		log.Fatal("--heartbeat should be at least one second")
	}
	ttl, err := time.ParseDuration(c.String("ttl"))
	if err != nil {
		log.Fatalf("invalid --ttl: %v", err)
	}
	if ttl <= hb {
		log.Fatal("--ttl must be strictly superior to the heartbeat value")
	}

	d, err := discovery.New(dflag, hb, ttl, getDiscoveryOpt(c))
	if err != nil {
		log.Fatal(err)
	}

	// if joinDelay is 0, no delay will be executed
	// if joinDelay is larger than 0,
	// add a random delay between 0s and joinDelay at start to avoid synchronized registration
	if joinDelay > 0 {
		r := rand.New(rand.NewSource(time.Now().UTC().UnixNano()))
		delay := time.Duration(r.Int63n(int64(joinDelay)))
		log.Infof("Add a random delay %s to avoid synchronized registration", delay)
		time.Sleep(delay)
	}

	for {
		log.WithFields(log.Fields{"addr": addr, "discovery": dflag}).Infof("Registering on the discovery service every %s...", hb)
		if err := d.Register(addr); err != nil {
			log.Error(err)
		}
		time.Sleep(hb)
	}
}
Exemplo n.º 28
0
// NewRouter returns a new empty router instance. You will still need to call
// ReloadRoutes() to do the initial route load.
func NewRouter(mongoURL, mongoDbName, backendConnectTimeout, backendHeaderTimeout, logFileName string) (rt *Router, err error) {
	beConnTimeout, err := time.ParseDuration(backendConnectTimeout)
	if err != nil {
		return nil, err
	}
	beHeaderTimeout, err := time.ParseDuration(backendHeaderTimeout)
	if err != nil {
		return nil, err
	}
	logInfo("router: using backend connect timeout:", beConnTimeout)
	logInfo("router: using backend header timeout:", beHeaderTimeout)

	l, err := logger.New(logFileName)
	if err != nil {
		return nil, err
	}
	logInfo("router: logging errors as JSON to", logFileName)

	rt = &Router{
		mux:                   triemux.NewMux(),
		mongoURL:              mongoURL,
		mongoDbName:           mongoDbName,
		backendConnectTimeout: beConnTimeout,
		backendHeaderTimeout:  beHeaderTimeout,
		logger:                l,
	}
	return rt, nil
}
Exemplo n.º 29
0
func memStats() error {
	memstats := serverCmd.Flags().Lookup("memstats").Value.String()
	if memstats != "" {
		interval, err := time.ParseDuration(serverCmd.Flags().Lookup("meminterval").Value.String())
		if err != nil {
			interval, _ = time.ParseDuration("100ms")
		}

		fileMemStats, err := os.Create(memstats)
		if err != nil {
			return err
		}

		fileMemStats.WriteString("# Time\tHeapSys\tHeapAlloc\tHeapIdle\tHeapReleased\n")

		go func() {
			var stats runtime.MemStats

			start := time.Now().UnixNano()

			for {
				runtime.ReadMemStats(&stats)
				if fileMemStats != nil {
					fileMemStats.WriteString(fmt.Sprintf("%d\t%d\t%d\t%d\t%d\n",
						(time.Now().UnixNano()-start)/1000000, stats.HeapSys, stats.HeapAlloc, stats.HeapIdle, stats.HeapReleased))
					time.Sleep(interval)
				} else {
					break
				}
			}
		}()
	}
	return nil
}
Exemplo n.º 30
0
func TestString(t *testing.T) {
	t.Parallel()

	// test empty
	d := Duration{}
	assert.Equal(t, d.String(), "P")

	// test only larger-than-day
	p, _ := time.ParseDuration("10272h")
	d = Duration{p}
	assert.Equal(t, d.String(), "P1Y63D")

	// test only smaller-than-day
	p, _ = time.ParseDuration("1h2m3s")
	d = Duration{p}
	assert.Equal(t, d.String(), "PT1H2M3S")

	// test full format
	p, _ = time.ParseDuration("10276h5m6s")
	d = Duration{p}
	assert.Equal(t, d.String(), "P1Y63DT4H5M6S")

	// test week format
	p, _ = time.ParseDuration("168h")
	d = Duration{p}
	assert.Equal(t, d.String(), "P1W")
}