1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
|
/*
Copyright 2015 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package workqueue_test
import (
"fmt"
"runtime"
"sync"
"sync/atomic"
"testing"
"time"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/util/workqueue"
)
// traceQueue traces whether items are touched
type traceQueue struct {
workqueue.Queue[any]
touched map[interface{}]struct{}
}
func (t *traceQueue) Touch(item interface{}) {
t.Queue.Touch(item)
if t.touched == nil {
t.touched = make(map[interface{}]struct{})
}
t.touched[item] = struct{}{}
}
var _ workqueue.Queue[any] = &traceQueue{}
func TestBasic(t *testing.T) {
tests := []struct {
queue *workqueue.Type
queueShutDown func(workqueue.Interface)
}{
{
queue: workqueue.New(),
queueShutDown: workqueue.Interface.ShutDown,
},
{
queue: workqueue.New(),
queueShutDown: workqueue.Interface.ShutDownWithDrain,
},
}
for _, test := range tests {
// If something is seriously wrong this test will never complete.
// Start producers
const producers = 50
producerWG := sync.WaitGroup{}
producerWG.Add(producers)
for i := 0; i < producers; i++ {
go func(i int) {
defer producerWG.Done()
for j := 0; j < 50; j++ {
test.queue.Add(i)
time.Sleep(time.Millisecond)
}
}(i)
}
// Start consumers
const consumers = 10
consumerWG := sync.WaitGroup{}
consumerWG.Add(consumers)
for i := 0; i < consumers; i++ {
go func(i int) {
defer consumerWG.Done()
for {
item, quit := test.queue.Get()
if item == "added after shutdown!" {
t.Errorf("Got an item added after shutdown.")
}
if quit {
return
}
t.Logf("Worker %v: begin processing %v", i, item)
time.Sleep(3 * time.Millisecond)
t.Logf("Worker %v: done processing %v", i, item)
test.queue.Done(item)
}
}(i)
}
producerWG.Wait()
test.queueShutDown(test.queue)
test.queue.Add("added after shutdown!")
consumerWG.Wait()
if test.queue.Len() != 0 {
t.Errorf("Expected the queue to be empty, had: %v items", test.queue.Len())
}
}
}
func TestAddWhileProcessing(t *testing.T) {
tests := []struct {
queue *workqueue.Type
queueShutDown func(workqueue.Interface)
}{
{
queue: workqueue.New(),
queueShutDown: workqueue.Interface.ShutDown,
},
{
queue: workqueue.New(),
queueShutDown: workqueue.Interface.ShutDownWithDrain,
},
}
for _, test := range tests {
// Start producers
const producers = 50
producerWG := sync.WaitGroup{}
producerWG.Add(producers)
for i := 0; i < producers; i++ {
go func(i int) {
defer producerWG.Done()
test.queue.Add(i)
}(i)
}
// Start consumers
const consumers = 10
consumerWG := sync.WaitGroup{}
consumerWG.Add(consumers)
for i := 0; i < consumers; i++ {
go func(i int) {
defer consumerWG.Done()
// Every worker will re-add every item up to two times.
// This tests the dirty-while-processing case.
counters := map[interface{}]int{}
for {
item, quit := test.queue.Get()
if quit {
return
}
counters[item]++
if counters[item] < 2 {
test.queue.Add(item)
}
test.queue.Done(item)
}
}(i)
}
producerWG.Wait()
test.queueShutDown(test.queue)
consumerWG.Wait()
if test.queue.Len() != 0 {
t.Errorf("Expected the queue to be empty, had: %v items", test.queue.Len())
}
}
}
func TestLen(t *testing.T) {
q := workqueue.New()
q.Add("foo")
if e, a := 1, q.Len(); e != a {
t.Errorf("Expected %v, got %v", e, a)
}
q.Add("bar")
if e, a := 2, q.Len(); e != a {
t.Errorf("Expected %v, got %v", e, a)
}
q.Add("foo") // should not increase the queue length.
if e, a := 2, q.Len(); e != a {
t.Errorf("Expected %v, got %v", e, a)
}
}
func TestReinsert(t *testing.T) {
q := workqueue.New()
q.Add("foo")
// Start processing
i, _ := q.Get()
if i != "foo" {
t.Errorf("Expected %v, got %v", "foo", i)
}
// Add it back while processing
q.Add(i)
// Finish it up
q.Done(i)
// It should be back on the queue
i, _ = q.Get()
if i != "foo" {
t.Errorf("Expected %v, got %v", "foo", i)
}
// Finish that one up
q.Done(i)
if a := q.Len(); a != 0 {
t.Errorf("Expected queue to be empty. Has %v items", a)
}
}
func TestCollapse(t *testing.T) {
tq := &traceQueue{Queue: workqueue.DefaultQueue[any]()}
q := workqueue.NewWithConfig(workqueue.QueueConfig{
Name: "",
Queue: tq,
})
// Add a new one twice
q.Add("bar")
q.Add("bar")
// It should get the new one
i, _ := q.Get()
if i != "bar" {
t.Errorf("Expected %v, got %v", "bar", i)
}
// Finish that one up
q.Done(i)
// There should be no more objects in the queue
if a := q.Len(); a != 0 {
t.Errorf("Expected queue to be empty. Has %v items", a)
}
if _, ok := tq.touched["bar"]; !ok {
t.Errorf("Expected bar to be Touched")
}
}
func TestCollapseWhileProcessing(t *testing.T) {
tq := &traceQueue{Queue: workqueue.DefaultQueue[any]()}
q := workqueue.NewWithConfig(workqueue.QueueConfig{
Name: "",
Queue: tq,
})
q.Add("foo")
// Start processing
i, _ := q.Get()
if i != "foo" {
t.Errorf("Expected %v, got %v", "foo", i)
}
// Add the same one twice
q.Add("foo")
q.Add("foo")
waitCh := make(chan struct{})
// simulate another worker consuming the queue
go func() {
defer close(waitCh)
i, _ := q.Get()
if i != "foo" {
t.Errorf("Expected %v, got %v", "foo", i)
}
// Finish that one up
q.Done(i)
}()
// give the worker some head start to avoid races
// on the select statement that cause flakiness
time.Sleep(100 * time.Millisecond)
// Finish the first one to unblock the other worker
select {
case <-waitCh:
t.Errorf("worker should be blocked until we are done")
default:
q.Done("foo")
}
// wait for the worker to consume the new object
// There should be no more objects in the queue
<-waitCh
if a := q.Len(); a != 0 {
t.Errorf("Expected queue to be empty. Has %v items", a)
}
if _, ok := tq.touched["foo"]; ok {
t.Errorf("Unexpected Touch")
}
}
func TestQueueDrainageUsingShutDownWithDrain(t *testing.T) {
q := workqueue.New()
q.Add("foo")
q.Add("bar")
firstItem, _ := q.Get()
secondItem, _ := q.Get()
finishedWG := sync.WaitGroup{}
finishedWG.Add(1)
go func() {
defer finishedWG.Done()
q.ShutDownWithDrain()
}()
// This is done as to simulate a sequence of events where ShutDownWithDrain
// is called before we start marking all items as done - thus simulating a
// drain where we wait for all items to finish processing.
shuttingDown := false
for !shuttingDown {
_, shuttingDown = q.Get()
}
// Mark the first two items as done, as to finish up
q.Done(firstItem)
q.Done(secondItem)
finishedWG.Wait()
}
func TestNoQueueDrainageUsingShutDown(t *testing.T) {
q := workqueue.New()
q.Add("foo")
q.Add("bar")
q.Get()
q.Get()
finishedWG := sync.WaitGroup{}
finishedWG.Add(1)
go func() {
defer finishedWG.Done()
// Invoke ShutDown: suspending the execution immediately.
q.ShutDown()
}()
// We can now do this and not have the test timeout because we didn't call
// Done on the first two items before arriving here.
finishedWG.Wait()
}
func TestForceQueueShutdownUsingShutDown(t *testing.T) {
q := workqueue.New()
q.Add("foo")
q.Add("bar")
q.Get()
q.Get()
finishedWG := sync.WaitGroup{}
finishedWG.Add(1)
go func() {
defer finishedWG.Done()
q.ShutDownWithDrain()
}()
// This is done as to simulate a sequence of events where ShutDownWithDrain
// is called before ShutDown
shuttingDown := false
for !shuttingDown {
_, shuttingDown = q.Get()
}
// Use ShutDown to force the queue to shut down (simulating a caller
// which can invoke this function on a second SIGTERM/SIGINT)
q.ShutDown()
// We can now do this and not have the test timeout because we didn't call
// done on any of the items before arriving here.
finishedWG.Wait()
}
func TestQueueDrainageUsingShutDownWithDrainWithDirtyItem(t *testing.T) {
q := workqueue.New()
q.Add("foo")
gotten, _ := q.Get()
q.Add("foo")
finishedWG := sync.WaitGroup{}
finishedWG.Add(1)
go func() {
defer finishedWG.Done()
q.ShutDownWithDrain()
}()
// Ensure that ShutDownWithDrain has started and is blocked.
shuttingDown := false
for !shuttingDown {
_, shuttingDown = q.Get()
}
// Finish "working".
q.Done(gotten)
// `shuttingDown` becomes false because Done caused an item to go back into
// the queue.
again, shuttingDown := q.Get()
if shuttingDown {
t.Fatalf("should not have been done")
}
q.Done(again)
// Now we are really done.
_, shuttingDown = q.Get()
if !shuttingDown {
t.Fatalf("should have been done")
}
finishedWG.Wait()
}
// TestGarbageCollection ensures that objects that are added then removed from the queue are
// able to be garbage collected.
func TestGarbageCollection(t *testing.T) {
type bigObject struct {
data []byte
}
leakQueue := workqueue.New()
t.Cleanup(func() {
// Make sure leakQueue doesn't go out of scope too early
runtime.KeepAlive(leakQueue)
})
c := &bigObject{data: []byte("hello")}
mustGarbageCollect(t, c)
leakQueue.Add(c)
o, _ := leakQueue.Get()
leakQueue.Done(o)
}
// mustGarbageCollect asserts than an object was garbage collected by the end of the test.
// The input must be a pointer to an object.
func mustGarbageCollect(t *testing.T, i interface{}) {
t.Helper()
var collected int32 = 0
runtime.SetFinalizer(i, func(x interface{}) {
atomic.StoreInt32(&collected, 1)
})
t.Cleanup(func() {
if err := wait.PollImmediate(time.Millisecond*100, wait.ForeverTestTimeout, func() (done bool, err error) {
// Trigger GC explicitly, otherwise we may need to wait a long time for it to run
runtime.GC()
return atomic.LoadInt32(&collected) == 1, nil
}); err != nil {
t.Errorf("object was not garbage collected")
}
})
}
func BenchmarkQueue(b *testing.B) {
keys := make([]string, 100)
for idx := range keys {
keys[idx] = fmt.Sprintf("key-%d", idx)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
b.StopTimer()
q := workqueue.NewTypedWithConfig(workqueue.TypedQueueConfig[string]{})
b.StartTimer()
for j := 0; j < 100; j++ {
q.Add(keys[j])
key, _ := q.Get()
q.Done(key)
}
}
}
|