github.com/cilium/cilium@v1.16.2/pkg/safetime/safetime.go (about)

     1  // SPDX-License-Identifier: Apache-2.0
     2  // Copyright Authors of Cilium
     3  
     4  package safetime
     5  
     6  import (
     7  	"runtime"
     8  
     9  	"github.com/sirupsen/logrus"
    10  
    11  	"github.com/cilium/cilium/pkg/logging/logfields"
    12  	"github.com/cilium/cilium/pkg/time"
    13  )
    14  
    15  // TimeSinceSafe returns the duration since t. If the duration is negative,
    16  // returns false to indicate the fact.
    17  //
    18  // Used to workaround a malfunctioning monotonic clock.
    19  func TimeSinceSafe(t time.Time, logger *logrus.Entry) (time.Duration, bool) {
    20  	n := time.Now()
    21  	d := n.Sub(t)
    22  
    23  	if d < 0 {
    24  		logger = logger.WithFields(logrus.Fields{
    25  			logfields.StartTime: t,
    26  			logfields.EndTime:   n,
    27  			logfields.Duration:  d,
    28  		})
    29  		_, file, line, ok := runtime.Caller(1)
    30  		if ok {
    31  			logger = logger.WithFields(logrus.Fields{
    32  				logfields.Path: file,
    33  				logfields.Line: line,
    34  			})
    35  		}
    36  		logger.Warn("BUG: negative duration")
    37  
    38  		return time.Duration(0), false
    39  	}
    40  
    41  	return d, true
    42  }