github.com/fafucoder/cilium@v1.6.11/pkg/safetime/safetime.go (about) 1 // Copyright 2018 Authors of Cilium 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package safetime 16 17 import ( 18 "runtime" 19 "time" 20 21 "github.com/cilium/cilium/pkg/logging/logfields" 22 23 log "github.com/sirupsen/logrus" 24 ) 25 26 // TimeSinceSafe returns the duration since t. If the duration is negative, 27 // returns false to indicate the fact. 28 // 29 // Used to workaround a malfunctioning monotonic clock. 30 func TimeSinceSafe(t time.Time, logger *log.Entry) (time.Duration, bool) { 31 n := time.Now() 32 d := n.Sub(t) 33 34 if d < 0 { 35 logger = logger.WithFields(log.Fields{ 36 logfields.StartTime: t, 37 logfields.EndTime: n, 38 logfields.Duration: d, 39 }) 40 _, file, line, ok := runtime.Caller(1) 41 if ok { 42 logger = logger.WithFields(log.Fields{ 43 logfields.Path: file, 44 logfields.Line: line, 45 }) 46 } 47 logger.Warn("BUG: negative duration") 48 49 return time.Duration(0), false 50 } 51 52 return d, true 53 }