Fixed some race conditions
This commit is contained in:
@@ -2,6 +2,7 @@ package osimage
|
||||
|
||||
import (
|
||||
"k8s.io/klog/v2"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -92,8 +93,10 @@ func (l *ProgressLogger) Log(p Progress) {
|
||||
}
|
||||
|
||||
type TimeBasedUpdater struct {
|
||||
mu sync.Mutex
|
||||
interval time.Duration
|
||||
lastRun time.Time
|
||||
inFlight bool
|
||||
}
|
||||
|
||||
func NewTimeBasedUpdater(seconds int) *TimeBasedUpdater {
|
||||
@@ -106,16 +109,28 @@ func NewTimeBasedUpdater(seconds int) *TimeBasedUpdater {
|
||||
}
|
||||
|
||||
func (u *TimeBasedUpdater) Run(fn func() error) error {
|
||||
u.mu.Lock()
|
||||
now := time.Now()
|
||||
|
||||
if !u.lastRun.IsZero() && now.Sub(u.lastRun) < u.interval {
|
||||
if u.inFlight {
|
||||
u.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := fn(); err != nil {
|
||||
return err
|
||||
if !u.lastRun.IsZero() && now.Sub(u.lastRun) < u.interval {
|
||||
u.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
u.lastRun = now
|
||||
return nil
|
||||
u.inFlight = true
|
||||
u.mu.Unlock()
|
||||
|
||||
defer func() {
|
||||
u.mu.Lock()
|
||||
u.inFlight = false
|
||||
u.mu.Unlock()
|
||||
}()
|
||||
|
||||
return fn()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user