示例#1
1
// Add adds new node and returns it, it replaces existing without notification.
func (s *nodeStore) Add(n *api.Node, expireFunc func()) *registeredNode {
	s.mu.Lock()
	defer s.mu.Unlock()
	var attempts int
	var registered time.Time
	if existRn, ok := s.nodes[n.ID]; ok {
		attempts = existRn.Attempts
		registered = existRn.Registered
		existRn.Heartbeat.Stop()
		delete(s.nodes, n.ID)
	}
	if registered.IsZero() {
		registered = time.Now()
	}
	rn := &registeredNode{
		SessionID:  identity.NewID(), // session ID is local to the dispatcher.
		Node:       n,
		Registered: registered,
		Attempts:   attempts,
		Disconnect: make(chan struct{}),
	}
	s.nodes[n.ID] = rn
	rn.Heartbeat = heartbeat.New(s.periodChooser.Choose()*s.gracePeriodMultiplierNormal, expireFunc)
	return rn
}
func (df *datanodeFailover) next() string {
	if df.numRemaining() == 0 {
		return ""
	}

	var picked = -1
	var oldestFailure time.Time

	for i, address := range df.datanodes {
		datanodeFailuresLock.Lock()
		failedAt, hasFailed := datanodeFailures[address]
		datanodeFailuresLock.Unlock()

		if !hasFailed {
			picked = i
			break
		} else if oldestFailure.IsZero() || failedAt.Before(oldestFailure) {
			picked = i
			oldestFailure = failedAt
		}
	}

	address := df.datanodes[picked]
	df.datanodes = append(df.datanodes[:picked], df.datanodes[picked+1:]...)

	df.currentDatanode = address
	return address
}
示例#3
0
文件: message.go 项目: jrossi/gollum
// Enqueue is a convenience function to push a message to a channel while
// waiting for a timeout instead of just blocking.
// Passing a timeout of -1 will discard the message.
// Passing a timout of 0 will always block.
// Messages that time out will be passed to the dropped queue if a Dropped
// consumer exists.
// The source parameter is used when a message is dropped, i.e. it is passed
// to the Drop function.
func (msg Message) Enqueue(channel chan<- Message, timeout time.Duration) MessageState {
	if timeout == 0 {
		channel <- msg
		return MessageStateOk // ### return, done ###
	}

	start := time.Time{}
	spin := shared.Spinner{}
	for {
		select {
		case channel <- msg:
			return MessageStateOk // ### return, done ###

		default:
			switch {
			// Start timeout based retries
			case start.IsZero():
				if timeout < 0 {
					return MessageStateDiscard // ### return, discard and ignore ###
				}
				start = time.Now()
				spin = shared.NewSpinner(shared.SpinPriorityHigh)

			// Discard message after timeout
			case time.Since(start) > timeout:
				return MessageStateTimeout // ### return, drop and retry ###

			// Yield and try again
			default:
				spin.Yield()
			}
		}
	}
}
示例#4
0
func showSince(writer io.Writer, now time.Time, since time.Time) {
	if now.IsZero() || since.IsZero() {
		fmt.Fprintln(writer, "    <td></td>")
	} else {
		showDuration(writer, now.Sub(since), false)
	}
}
示例#5
0
文件: helpers.go 项目: gmelika/rack
func humanizeTime(t time.Time) string {
	if t.IsZero() {
		return ""
	} else {
		return humanize.Time(t)
	}
}
示例#6
0
文件: crypto.go 项目: kennwhite/lego
func generateDerCert(privKey *rsa.PrivateKey, expiration time.Time, domain string) ([]byte, error) {
	serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
	serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
	if err != nil {
		return nil, err
	}

	if expiration.IsZero() {
		expiration = time.Now().Add(365)
	}

	template := x509.Certificate{
		SerialNumber: serialNumber,
		Subject: pkix.Name{
			CommonName: "ACME Challenge TEMP",
		},
		NotBefore: time.Now(),
		NotAfter:  expiration,

		KeyUsage:              x509.KeyUsageKeyEncipherment,
		BasicConstraintsValid: true,
		DNSNames:              []string{domain},
	}

	return x509.CreateCertificate(rand.Reader, &template, &template, &privKey.PublicKey, privKey)
}
示例#7
0
func (p *InMemoryDataStore) retrieveChangeSets(dsocialId string, after time.Time) ([]*dm.ChangeSet, bc.NextToken, error) {
	l := list.New()
	var afterString string
	if !after.IsZero() {
		afterString = after.Format(dm.UTC_DATETIME_FORMAT)
	}
	for _, v := range p.retrieveChangesetCollection().Data {
		if cs, ok := v.(*dm.ChangeSet); ok {
			if cs.RecordId == dsocialId {
				if after.IsZero() || cs.CreatedAt > afterString {
					cs2 := new(dm.ChangeSet)
					*cs2 = *cs
					l.PushBack(cs2)
				}
			}
		}
	}
	rc := make([]*dm.ChangeSet, l.Len())
	for i, iter := 0, l.Front(); iter != nil; i, iter = i+1, iter.Next() {
		if iter.Value != nil {
			rc[i] = iter.Value.(*dm.ChangeSet)
		}
	}
	return rc, nil, nil
}
示例#8
0
// dialChannel is the simple pure-Go implementation of dial, still
// used on operating systems where the deadline hasn't been pushed
// down into the pollserver. (Plan 9 and some old versions of Windows)
func dialChannel(net string, ra Addr, dialer func(time.Time) (Conn, error), deadline time.Time) (Conn, error) {
	var timeout time.Duration
	if !deadline.IsZero() {
		timeout = deadline.Sub(time.Now())
	}
	if timeout <= 0 {
		return dialer(noDeadline)
	}
	t := time.NewTimer(timeout)
	defer t.Stop()
	type racer struct {
		Conn
		error
	}
	ch := make(chan racer, 1)
	go func() {
		if testingIssue5349 {
			time.Sleep(time.Millisecond)
		}
		c, err := dialer(noDeadline)
		ch <- racer{c, err}
	}()
	select {
	case <-t.C:
		return nil, &OpError{Op: "dial", Net: net, Addr: ra, Err: errTimeout}
	case racer := <-ch:
		return racer.Conn, racer.error
	}
}
示例#9
0
func timeAsString(gotime time.Time, unit units.Unit) string {
	var dur duration.Duration
	if !gotime.IsZero() {
		dur = duration.SinceEpoch(gotime)
	}
	return dur.StringUsingUnits(unit)
}
示例#10
0
// SetExpires - Sets expiration time for the new policy.
func (p *PostPolicy) SetExpires(t time.Time) error {
	if t.IsZero() {
		return ErrInvalidArgument("No expiry time set.")
	}
	p.expiration = t
	return nil
}
示例#11
0
func tailFile(f io.ReadSeeker, logWatcher *logger.LogWatcher, tail int, since time.Time) {
	var rdr io.Reader = f
	if tail > 0 {
		ls, err := tailfile.TailFile(f, tail)
		if err != nil {
			logWatcher.Err <- err
			return
		}
		rdr = bytes.NewBuffer(bytes.Join(ls, []byte("\n")))
	}
	dec := json.NewDecoder(rdr)
	l := &jsonlog.JSONLog{}
	for {
		msg, err := decodeLogLine(dec, l)
		if err != nil {
			if err != io.EOF {
				logWatcher.Err <- err
			}
			return
		}
		if !since.IsZero() && msg.Timestamp.Before(since) {
			continue
		}
		logWatcher.Msg <- msg
	}
}
示例#12
0
// lookupIPDeadline looks up a hostname with a deadline.
func lookupIPDeadline(host string, deadline time.Time) (addrs []IPAddr, err error) {
	if deadline.IsZero() {
		return lookupIPMerge(host)
	}

	// We could push the deadline down into the name resolution
	// functions.  However, the most commonly used implementation
	// calls getaddrinfo, which has no timeout.

	timeout := deadline.Sub(time.Now())
	if timeout <= 0 {
		return nil, errTimeout
	}
	t := time.NewTimer(timeout)
	defer t.Stop()

	ch := lookupGroup.DoChan(host, func() (interface{}, error) {
		return testHookLookupIP(lookupIP, host)
	})

	select {
	case <-t.C:
		// The DNS lookup timed out for some reason.  Force
		// future requests to start the DNS lookup again
		// rather than waiting for the current lookup to
		// complete.  See issue 8602.
		lookupGroup.Forget(host)

		return nil, errTimeout

	case r := <-ch:
		return lookupIPReturn(r.Val, r.Err, r.Shared)
	}
}
示例#13
0
func (t *Time) UnmarshalJSON(data []byte) error {
	var err error
	var parsedTime time.Time

	if string(data) == "null" {
		*t = Time(time.Time{})
		return nil
	}

	layouts := []string{
		"2006-01-02 15:04:05 UTC",
		"2006-01-02 15:04:05+00",
		"2006-01-02T15:04:05.999999Z",

		"2006-01-02 15:04:05.999999",
		"2006-01-02T15:04:05Z",
		"2006-01-02 15:04:05.999999+00"}
	for _, layout := range layouts {
		parsedTime, err = time.Parse(layout,
			strings.Replace(string(data), "\"", "", -1))
		if err != nil {
			continue
		}
		break
	}
	if parsedTime.IsZero() {
		return err
	}

	*t = Time(parsedTime)

	return nil
}
示例#14
0
// Make sure to call with the mutex locked
func (db *BlockDB) addToCache(h *btc.Uint256, bl []byte, str *btc.Block) (crec *BlckCachRec) {
	if db.cache == nil {
		return
	}
	crec = db.cache[h.BIdx()]
	if crec != nil {
		crec.Data = bl
		if str != nil {
			crec.Block = str
		}
		crec.LastUsed = time.Now()
		return
	}
	if len(db.cache) >= db.max_cached_blocks {
		var oldest_t time.Time
		var oldest_k [btc.Uint256IdxLen]byte
		for k, v := range db.cache {
			if oldest_t.IsZero() || v.LastUsed.Before(oldest_t) {
				oldest_t = v.LastUsed
				oldest_k = k
			}
		}
		delete(db.cache, oldest_k)
	}
	crec = &BlckCachRec{LastUsed: time.Now(), Data: bl, Block: str}
	db.cache[h.BIdx()] = crec
	return
}
// Crée un nouvel objet de type AnneesMoisJours pour la date spécifiée
func TimeToAnneesMoisJour(t time.Time) (AnneesMoisJours, error) {
	if t.IsZero() {
		return AnneesMoisJours{}, ErrDateFormatInvalide
	}

	return AnneesMoisJours{t.Year(), int(t.Month()), t.Day()}, nil
}
示例#16
0
// Events returns an event channel that external consumers can use to receive updates
// on container events
func (s *Supervisor) Events(from time.Time, storedOnly bool, id string) chan Event {
	c := make(chan Event, defaultBufferSize)
	if storedOnly {
		defer s.Unsubscribe(c)
	}
	s.subscriberLock.Lock()
	defer s.subscriberLock.Unlock()
	if !from.IsZero() {
		// replay old event
		s.eventLock.Lock()
		past := s.eventLog[:]
		s.eventLock.Unlock()
		for _, e := range past {
			if e.Timestamp.After(from) {
				if id == "" || e.ID == id {
					c <- e
				}
			}
		}
	}
	if storedOnly {
		close(c)
	} else {
		EventSubscriberCounter.Inc(1)
		s.subscribers[c] = struct{}{}
	}
	return c
}
示例#17
0
文件: keys.go 项目: usercenter/crypto
// encryptionKey returns the best candidate Key for encrypting a message to the
// given Entity.
func (e *Entity) encryptionKey(now time.Time) (Key, bool) {
	candidateSubkey := -1

	// Iterate the keys to find the newest key
	var maxTime time.Time
	for i, subkey := range e.Subkeys {
		if subkey.Sig.FlagsValid &&
			subkey.Sig.FlagEncryptCommunications &&
			subkey.PublicKey.PubKeyAlgo.CanEncrypt() &&
			!subkey.Sig.KeyExpired(now) &&
			(maxTime.IsZero() || subkey.Sig.CreationTime.After(maxTime)) {
			candidateSubkey = i
			maxTime = subkey.Sig.CreationTime
		}
	}

	if candidateSubkey != -1 {
		subkey := e.Subkeys[candidateSubkey]
		return Key{e, subkey.PublicKey, subkey.PrivateKey, subkey.Sig}, true
	}

	// If we don't have any candidate subkeys for encryption and
	// the primary key doesn't have any usage metadata then we
	// assume that the primary key is ok. Or, if the primary key is
	// marked as ok to encrypt to, then we can obviously use it.
	i := e.primaryIdentity()
	if !i.SelfSignature.FlagsValid || i.SelfSignature.FlagEncryptCommunications &&
		e.PrimaryKey.PubKeyAlgo.CanEncrypt() &&
		!i.SelfSignature.KeyExpired(now) {
		return Key{e, e.PrimaryKey, e.PrivateKey, i.SelfSignature}, true
	}

	// This Entity appears to be signing only.
	return Key{}, false
}
示例#18
0
// Check the DS set to see if the expiration date of the DNSKEYs signatures are near. The
// alert period is defined by the parameter daysBefore, that is the number of days before
// the expiration date that we will consider near
func (d Domain) isNearDNSSECExpirationDate(daysBefore int) bool {
	// Lets look for the oldest expiration date of the DS set, the it's probably the most
	// problematic one
	var expiresAt time.Time

	for i := 0; i < len(d.DSSet); i++ {
		// If is the first iteration we don't compare to expiresAt, because we do compare it
		// will be always less than any other date. And we also check if the expiration date
		// of the DS record was initialized to avoid replacing a real date for a not
		// initialized date
		if expiresAt.IsZero() || (!d.DSSet[i].ExpiresAt.IsZero() &&
			d.DSSet[i].ExpiresAt.Before(expiresAt)) {

			expiresAt = d.DSSet[i].ExpiresAt
		}
	}

	// When there's no DS, we don't have an expiration date and shouldn't care about it
	if expiresAt.IsZero() {
		return false
	}

	// Now we can check if this expiration date is already in the alert period. The alert
	// period is defined by the function parameter in days
	return time.Now().Add(time.Duration(daysBefore*24) * time.Hour).After(expiresAt)
}
示例#19
0
// Times returns the start and stop time for
// the closest Day translation to now.
func (d *Day) Times(now time.Time) (closestStart time.Time, closestStop time.Time) {
	if now.IsZero() {
		Log.Error("Cannot find times without reference")
		return
	}

	if loc, err := d.GetLocation(); loc != nil && err == nil {
		now = now.In(loc)
	}

	// find nearest start time of this slot
	if now.Weekday() == d.Day && todayAt(now, d.Start).Before(now) {
		// if the schedule is for today
		// and we are after that scheduled time,
		// then we have found the closest start
		closestStart = todayAt(now, d.Start)
	} else {
		// Step back a day at a time until we find
		// the most recent day that matches the day
		// of the week of our Day.
		for i := 1; i < 8; i++ {
			sTime := now.Add(-time.Duration(i) * 24 * time.Hour)
			if sTime.Weekday() == d.Day {
				closestStart = todayAt(sTime, d.Start)
				break
			}
		}
	}

	// closestStop is just the closests start plus
	// the duration
	closestStop = closestStart.Add(d.Duration)

	return
}
示例#20
0
func getDateString(d time.Time) string {
	if d.IsZero() {
		return "Date TBC"
	}

	year, month, day := d.Date()
	suffix := "th"
	switch day % 10 {
	case 1:
		if day%100 != 11 {
			suffix = "st"
		}
	case 2:
		if day%100 != 12 {
			suffix = "nd"
		}
	case 3:
		if day%100 != 13 {
			suffix = "rd"
		}
	}
	return d.Weekday().String() + " " + strconv.Itoa(day) + suffix + " " +
		month.String() + " " + strconv.Itoa(year)

}
示例#21
0
// SetExpires expiration time
func (p *PostPolicy) SetExpires(t time.Time) error {
	if t.IsZero() {
		return errors.New("time input invalid")
	}
	p.expiration = t
	return nil
}
示例#22
0
文件: main.go 项目: koron/upvim
func download(url, outpath string, pivot time.Time) error {
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return err
	}
	if !pivot.IsZero() {
		t := pivot.UTC().Format(http.TimeFormat)
		req.Header.Set("If-Modified-Since", t)
	}
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	switch resp.StatusCode {
	case http.StatusOK:
		f, err := os.Create(outpath)
		if err != nil {
			return err
		}
		defer f.Close()
		if _, err := io.Copy(f, resp.Body); err != nil {
			return err
		}

	case http.StatusNotModified:
		return errorNotModified

	default:
		return fmt.Errorf("unexpected response: %s", resp.Status)
	}
	return nil
}
示例#23
0
func (d *deadline) setTime(t time.Time) {
	if t.IsZero() {
		d.set(0)
	} else {
		d.set(t.UnixNano())
	}
}
示例#24
0
func (c *Conn) processEventsWithDeadline(deadline time.Time) {
	localAddr, ok := c.sock.LocalAddr().(*net.UDPAddr)
	if !ok {
		panic("Cannot convert localAddr")
	}

	var timeoutCh <-chan time.Time
	if !deadline.IsZero() {
		timeoutCh = time.After(-time.Since(deadline))
	} else {
		timeoutCh = make(chan time.Time, 1)
	}

	select {
	case result, ok := <-c.readChan:
		if len(result.Buf) == 0 {
			break
		}
		if !ok || c.closed {
			break
		}
		c.quicClient.ProcessPacket(localAddr, result.Addr, result.Buf)
	case <-c.quicClient.taskRunner.WaitTimer():
		if c.closed {
			panic("debug")
			break
		}
		c.quicClient.taskRunner.DoTasks()
	case <-timeoutCh:
		// Break when past deadline
	}
	c.quicClient.taskRunner.DoTasks()
}
示例#25
0
文件: sched.go 项目: bridgewell/bosun
func marshalTime(t time.Time) string {
	if t.IsZero() {
		return ""
	}
	b, _ := t.MarshalText()
	return string(b)
}
示例#26
0
func (x *Index) PathLookup(signer, base blob.Ref, suffix string, at time.Time) (*camtypes.Path, error) {
	paths, err := x.PathsLookup(signer, base, suffix)
	if err != nil {
		return nil, err
	}
	var (
		newest    = int64(0)
		atSeconds = int64(0)
		best      *camtypes.Path
	)

	if !at.IsZero() {
		atSeconds = at.Unix()
	}

	for _, path := range paths {
		t := path.ClaimDate
		secs := t.Unix()
		if atSeconds != 0 && secs > atSeconds {
			// Too new
			continue
		}
		if newest > secs {
			// Too old
			continue
		}
		// Just right
		newest, best = secs, path
	}
	if best == nil {
		return nil, os.ErrNotExist
	}
	return best, nil
}
示例#27
0
文件: getdefault.go 项目: peak6/utils
func Time(v, d time.Time) time.Time {
	if v.IsZero() {
		return d
	}

	return v
}
示例#28
0
func (self *SelectDeleteCommonQuery) GetQueryStringForContinuousQuery(start, end time.Time) string {
	queryString := self.GetQueryString()
	queryString = strings.TrimSuffix(queryString, ";")

	intoRegex, _ := regexp.Compile("(?i)\\s+into\\s+")
	components := intoRegex.Split(queryString, 2)

	queryString = components[0]

	startTime := common.TimeToMicroseconds(start)
	startTimeStr := strconv.FormatInt(startTime-1, 10)
	endTime := common.TimeToMicroseconds(end)
	endTimeStr := strconv.FormatInt(endTime, 10)

	if self.GetWhereCondition() == nil {
		queryString = queryString + " where "
	} else {
		queryString = queryString + " and "
	}

	if start.IsZero() {
		return queryString + "time < " + endTimeStr + "u"
	} else {
		return queryString + "time > " + startTimeStr + "u and time < " + endTimeStr + "u"
	}
}
示例#29
0
// flock acquires an advisory lock on a file descriptor.
func flock(f *os.File, exclusive bool, timeout time.Duration) error {
	var t time.Time
	for {
		// If we're beyond our timeout then return an error.
		// This can only occur after we've attempted a flock once.
		if t.IsZero() {
			t = time.Now()
		} else if timeout > 0 && time.Since(t) > timeout {
			return ErrTimeout
		}
		var lock syscall.Flock_t
		lock.Start = 0
		lock.Len = 0
		lock.Pid = 0
		lock.Whence = 0
		lock.Pid = 0
		if exclusive {
			lock.Type = syscall.F_WRLCK
		} else {
			lock.Type = syscall.F_RDLCK
		}
		err := syscall.FcntlFlock(f.Fd(), syscall.F_SETLK, &lock)
		if err == nil {
			return nil
		} else if err != syscall.EAGAIN {
			return err
		}

		// Wait for a bit and try again.
		time.Sleep(50 * time.Millisecond)
	}
}
示例#30
0
func writeTimestamp(w io.Writer, t time.Time) (err error) {
	nanoSeconds := t.Round(time.Microsecond).UnixNano()
	if t.IsZero() {
		return writeLong(w, math.MinInt64)
	}
	return writeLong(w, nanoSeconds/int64(time.Microsecond))
}