k8s.io/kubernetes@v1.29.3/pkg/kubelet/util/queue/work_queue.go (about) 1 /* 2 Copyright 2015 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package queue 18 19 import ( 20 "sync" 21 "time" 22 23 "k8s.io/apimachinery/pkg/types" 24 "k8s.io/utils/clock" 25 ) 26 27 // WorkQueue allows queuing items with a timestamp. An item is 28 // considered ready to process if the timestamp has expired. 29 type WorkQueue interface { 30 // GetWork dequeues and returns all ready items. 31 GetWork() []types.UID 32 // Enqueue inserts a new item or overwrites an existing item. 33 Enqueue(item types.UID, delay time.Duration) 34 } 35 36 type basicWorkQueue struct { 37 clock clock.Clock 38 lock sync.Mutex 39 queue map[types.UID]time.Time 40 } 41 42 var _ WorkQueue = &basicWorkQueue{} 43 44 // NewBasicWorkQueue returns a new basic WorkQueue with the provided clock 45 func NewBasicWorkQueue(clock clock.Clock) WorkQueue { 46 queue := make(map[types.UID]time.Time) 47 return &basicWorkQueue{queue: queue, clock: clock} 48 } 49 50 func (q *basicWorkQueue) GetWork() []types.UID { 51 q.lock.Lock() 52 defer q.lock.Unlock() 53 now := q.clock.Now() 54 var items []types.UID 55 for k, v := range q.queue { 56 if v.Before(now) { 57 items = append(items, k) 58 delete(q.queue, k) 59 } 60 } 61 return items 62 } 63 64 func (q *basicWorkQueue) Enqueue(item types.UID, delay time.Duration) { 65 q.lock.Lock() 66 defer q.lock.Unlock() 67 q.queue[item] = q.clock.Now().Add(delay) 68 }