ganeti.workerpool_unittest.py 18.7 KB
Newer Older
1
2
3
#!/usr/bin/python
#

4
# Copyright (C) 2008, 2009, 2010 Google Inc.
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.


"""Script for unittesting the workerpool module"""

import unittest
import threading
import time
import sys
import zlib
29
import random
30
31

from ganeti import workerpool
32
from ganeti import errors
33
from ganeti import utils
34

35
36
import testutils

37

38
class CountingContext(object):
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
  def __init__(self):
    self._lock = threading.Condition(threading.Lock())
    self.done = 0

  def DoneTask(self):
    self._lock.acquire()
    try:
      self.done += 1
    finally:
      self._lock.release()

  def GetDoneTasks(self):
    self._lock.acquire()
    try:
      return self.done
    finally:
      self._lock.release()

  @staticmethod
  def UpdateChecksum(current, value):
    return zlib.adler32(str(value), current)
60

61
62
63
64

class CountingBaseWorker(workerpool.BaseWorker):
  def RunTask(self, ctx, text):
    ctx.DoneTask()
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80


class ChecksumContext:
  CHECKSUM_START = zlib.adler32("")

  def __init__(self):
    self.lock = threading.Condition(threading.Lock())
    self.checksum = self.CHECKSUM_START

  @staticmethod
  def UpdateChecksum(current, value):
    return zlib.adler32(str(value), current)


class ChecksumBaseWorker(workerpool.BaseWorker):
  def RunTask(self, ctx, number):
81
82
83
84
85
86
87
    name = "number%s" % number
    self.SetTaskName(name)

    # This assertion needs to be checked before updating the checksum. A
    # failing assertion will then cause the result to be wrong.
    assert self.getName() == ("%s/%s" % (self._worker_id, name))

88
89
90
91
92
93
94
    ctx.lock.acquire()
    try:
      ctx.checksum = ctx.UpdateChecksum(ctx.checksum, number)
    finally:
      ctx.lock.release()


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
class ListBuilderContext:
  def __init__(self):
    self.lock = threading.Lock()
    self.result = []
    self.prioresult = {}


class ListBuilderWorker(workerpool.BaseWorker):
  def RunTask(self, ctx, data):
    ctx.lock.acquire()
    try:
      ctx.result.append((self.GetCurrentPriority(), data))
      ctx.prioresult.setdefault(self.GetCurrentPriority(), []).append(data)
    finally:
      ctx.lock.release()


class DeferringTaskContext:
  def __init__(self):
    self.lock = threading.Lock()
    self.prioresult = {}
    self.samepriodefer = {}


class DeferringWorker(workerpool.BaseWorker):
  def RunTask(self, ctx, num, targetprio):
    ctx.lock.acquire()
    try:
      if num in ctx.samepriodefer:
        del ctx.samepriodefer[num]
        raise workerpool.DeferTask()

      if self.GetCurrentPriority() > targetprio:
        raise workerpool.DeferTask(priority=self.GetCurrentPriority() - 1)

      ctx.prioresult.setdefault(self.GetCurrentPriority(), set()).add(num)
    finally:
      ctx.lock.release()


135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
class PriorityContext:
  def __init__(self):
    self.lock = threading.Lock()
    self.result = []


class PriorityWorker(workerpool.BaseWorker):
  def RunTask(self, ctx, data):
    ctx.lock.acquire()
    try:
      ctx.result.append((self.GetCurrentPriority(), data))
    finally:
      ctx.lock.release()


class NotImplementedWorker(workerpool.BaseWorker):
  def RunTask(self):
    raise NotImplementedError


155
156
157
class TestWorkerpool(unittest.TestCase):
  """Workerpool tests"""

158
159
160
  def testCounting(self):
    ctx = CountingContext()
    wp = workerpool.WorkerPool("Test", 3, CountingBaseWorker)
161
162
163
    try:
      self._CheckWorkerCount(wp, 3)

164
      for i in range(10):
165
        wp.AddTask((ctx, "Hello world %s" % i))
166
167
168
169
170
171

      wp.Quiesce()
    finally:
      wp.TerminateWorkers()
      self._CheckWorkerCount(wp, 0)

172
173
    self.assertEquals(ctx.GetDoneTasks(), 10)

174
  def testNoTasks(self):
175
    wp = workerpool.WorkerPool("Test", 3, CountingBaseWorker)
176
177
178
179
180
181
182
183
    try:
      self._CheckWorkerCount(wp, 3)
      self._CheckNoTasks(wp)
    finally:
      wp.TerminateWorkers()
      self._CheckWorkerCount(wp, 0)

  def testNoTasksQuiesce(self):
184
    wp = workerpool.WorkerPool("Test", 3, CountingBaseWorker)
185
186
187
188
189
190
191
192
193
    try:
      self._CheckWorkerCount(wp, 3)
      self._CheckNoTasks(wp)
      wp.Quiesce()
      self._CheckNoTasks(wp)
    finally:
      wp.TerminateWorkers()
      self._CheckWorkerCount(wp, 0)

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
  def testActive(self):
    ctx = CountingContext()
    wp = workerpool.WorkerPool("TestActive", 5, CountingBaseWorker)
    try:
      self._CheckWorkerCount(wp, 5)
      self.assertTrue(wp._active)

      # Process some tasks
      for _ in range(10):
        wp.AddTask((ctx, None))

      wp.Quiesce()
      self._CheckNoTasks(wp)
      self.assertEquals(ctx.GetDoneTasks(), 10)

      # Repeat a few times
      for count in range(10):
        # Deactivate pool
        wp.SetActive(False)
        self._CheckNoTasks(wp)

        # Queue some more tasks
        for _ in range(10):
          wp.AddTask((ctx, None))

        for _ in range(5):
          # Short delays to give other threads a chance to cause breakage
          time.sleep(.01)
          wp.AddTask((ctx, "Hello world %s" % 999))
          self.assertFalse(wp._active)

        self.assertEquals(ctx.GetDoneTasks(), 10 + (count * 15))

        # Start processing again
        wp.SetActive(True)
        self.assertTrue(wp._active)

        # Wait for tasks to finish
        wp.Quiesce()
        self._CheckNoTasks(wp)
        self.assertEquals(ctx.GetDoneTasks(), 10 + (count * 15) + 15)

        self._CheckWorkerCount(wp, 5)
    finally:
      wp.TerminateWorkers()
      self._CheckWorkerCount(wp, 0)

241
242
243
  def testChecksum(self):
    # Tests whether all tasks are run and, since we're only using a single
    # thread, whether everything is started in order.
244
    wp = workerpool.WorkerPool("Test", 1, ChecksumBaseWorker)
245
246
247
248
249
    try:
      self._CheckWorkerCount(wp, 1)

      ctx = ChecksumContext()
      checksum = ChecksumContext.CHECKSUM_START
250
      for i in range(1, 100):
251
        checksum = ChecksumContext.UpdateChecksum(checksum, i)
252
        wp.AddTask((ctx, i))
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267

      wp.Quiesce()

      self._CheckNoTasks(wp)

      # Check sum
      ctx.lock.acquire()
      try:
        self.assertEqual(checksum, ctx.checksum)
      finally:
        ctx.lock.release()
    finally:
      wp.TerminateWorkers()
      self._CheckWorkerCount(wp, 0)

Guido Trotter's avatar
Guido Trotter committed
268
  def testAddManyTasks(self):
269
270
    ctx = CountingContext()
    wp = workerpool.WorkerPool("Test", 3, CountingBaseWorker)
Guido Trotter's avatar
Guido Trotter committed
271
272
273
    try:
      self._CheckWorkerCount(wp, 3)

274
      wp.AddManyTasks([(ctx, "Hello world %s" % i, ) for i in range(10)])
275
276
      wp.AddTask((ctx, "A separate hello"))
      wp.AddTask((ctx, "Once more, hi!"))
277
      wp.AddManyTasks([(ctx, "Hello world %s" % i, ) for i in range(10)])
Guido Trotter's avatar
Guido Trotter committed
278
279
280
281
282
283
284
285

      wp.Quiesce()

      self._CheckNoTasks(wp)
    finally:
      wp.TerminateWorkers()
      self._CheckWorkerCount(wp, 0)

286
287
    self.assertEquals(ctx.GetDoneTasks(), 22)

288
289
290
291
292
293
294
295
296
  def testManyTasksSequence(self):
    ctx = CountingContext()
    wp = workerpool.WorkerPool("Test", 3, CountingBaseWorker)
    try:
      self._CheckWorkerCount(wp, 3)
      self.assertRaises(AssertionError, wp.AddManyTasks,
                        ["Hello world %s" % i for i in range(10)])
      self.assertRaises(AssertionError, wp.AddManyTasks,
                        [i for i in range(10)])
297
      self.assertRaises(AssertionError, wp.AddManyTasks, [], task_id=0)
298
299

      wp.AddManyTasks([(ctx, "Hello world %s" % i, ) for i in range(10)])
300
      wp.AddTask((ctx, "A separate hello"))
301
302
303
304
305
306
307
308
309
310

      wp.Quiesce()

      self._CheckNoTasks(wp)
    finally:
      wp.TerminateWorkers()
      self._CheckWorkerCount(wp, 0)

    self.assertEquals(ctx.GetDoneTasks(), 11)

311
312
313
314
  def _CheckNoTasks(self, wp):
    wp._lock.acquire()
    try:
      # The task queue must be empty now
315
316
      self.assertFalse(wp._tasks)
      self.assertFalse(wp._taskdata)
317
318
319
320
321
322
323
324
325
326
    finally:
      wp._lock.release()

  def _CheckWorkerCount(self, wp, num_workers):
    wp._lock.acquire()
    try:
      self.assertEqual(len(wp._workers), num_workers)
    finally:
      wp._lock.release()

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
  def testPriorityChecksum(self):
    # Tests whether all tasks are run and, since we're only using a single
    # thread, whether everything is started in order and respects the priority
    wp = workerpool.WorkerPool("Test", 1, ChecksumBaseWorker)
    try:
      self._CheckWorkerCount(wp, 1)

      ctx = ChecksumContext()

      data = {}
      tasks = []
      priorities = []
      for i in range(1, 333):
        prio = i % 7
        tasks.append((ctx, i))
        priorities.append(prio)
        data.setdefault(prio, []).append(i)

      wp.AddManyTasks(tasks, priority=priorities)

      wp.Quiesce()

      self._CheckNoTasks(wp)

      # Check sum
      ctx.lock.acquire()
      try:
        checksum = ChecksumContext.CHECKSUM_START
        for priority in sorted(data.keys()):
          for i in data[priority]:
            checksum = ChecksumContext.UpdateChecksum(checksum, i)

        self.assertEqual(checksum, ctx.checksum)
      finally:
        ctx.lock.release()

      self._CheckWorkerCount(wp, 1)
    finally:
      wp.TerminateWorkers()
      self._CheckWorkerCount(wp, 0)

  def testPriorityListManyTasks(self):
    # Tests whether all tasks are run and, since we're only using a single
    # thread, whether everything is started in order and respects the priority
    wp = workerpool.WorkerPool("Test", 1, ListBuilderWorker)
    try:
      self._CheckWorkerCount(wp, 1)

      ctx = ListBuilderContext()

      # Use static seed for this test
      rnd = random.Random(0)

      data = {}
      tasks = []
      priorities = []
      for i in range(1, 333):
        prio = int(rnd.random() * 10)
        tasks.append((ctx, i))
        priorities.append(prio)
        data.setdefault(prio, []).append((prio, i))

      wp.AddManyTasks(tasks, priority=priorities)

      self.assertRaises(errors.ProgrammerError, wp.AddManyTasks,
                        [("x", ), ("y", )], priority=[1] * 5)
393
394
      self.assertRaises(errors.ProgrammerError, wp.AddManyTasks,
                        [("x", ), ("y", )], task_id=[1] * 5)
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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502

      wp.Quiesce()

      self._CheckNoTasks(wp)

      # Check result
      ctx.lock.acquire()
      try:
        expresult = []
        for priority in sorted(data.keys()):
          expresult.extend(data[priority])

        self.assertEqual(expresult, ctx.result)
      finally:
        ctx.lock.release()

      self._CheckWorkerCount(wp, 1)
    finally:
      wp.TerminateWorkers()
      self._CheckWorkerCount(wp, 0)

  def testPriorityListSingleTasks(self):
    # Tests whether all tasks are run and, since we're only using a single
    # thread, whether everything is started in order and respects the priority
    wp = workerpool.WorkerPool("Test", 1, ListBuilderWorker)
    try:
      self._CheckWorkerCount(wp, 1)

      ctx = ListBuilderContext()

      # Use static seed for this test
      rnd = random.Random(26279)

      data = {}
      for i in range(1, 333):
        prio = int(rnd.random() * 30)
        wp.AddTask((ctx, i), priority=prio)
        data.setdefault(prio, []).append(i)

        # Cause some distortion
        if i % 11 == 0:
          time.sleep(.001)
        if i % 41 == 0:
          wp.Quiesce()

      wp.Quiesce()

      self._CheckNoTasks(wp)

      # Check result
      ctx.lock.acquire()
      try:
        self.assertEqual(data, ctx.prioresult)
      finally:
        ctx.lock.release()

      self._CheckWorkerCount(wp, 1)
    finally:
      wp.TerminateWorkers()
      self._CheckWorkerCount(wp, 0)

  def testDeferTask(self):
    # Tests whether all tasks are run and, since we're only using a single
    # thread, whether everything is started in order and respects the priority
    wp = workerpool.WorkerPool("Test", 1, DeferringWorker)
    try:
      self._CheckWorkerCount(wp, 1)

      ctx = DeferringTaskContext()

      # Use static seed for this test
      rnd = random.Random(14921)

      data = {}
      for i in range(1, 333):
        ctx.lock.acquire()
        try:
          if i % 5 == 0:
            ctx.samepriodefer[i] = True
        finally:
          ctx.lock.release()

        prio = int(rnd.random() * 30)
        wp.AddTask((ctx, i, prio), priority=50)
        data.setdefault(prio, set()).add(i)

        # Cause some distortion
        if i % 24 == 0:
          time.sleep(.001)
        if i % 31 == 0:
          wp.Quiesce()

      wp.Quiesce()

      self._CheckNoTasks(wp)

      # Check result
      ctx.lock.acquire()
      try:
        self.assertEqual(data, ctx.prioresult)
      finally:
        ctx.lock.release()

      self._CheckWorkerCount(wp, 1)
    finally:
      wp.TerminateWorkers()
      self._CheckWorkerCount(wp, 0)

503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
  def testChangeTaskPriority(self):
    wp = workerpool.WorkerPool("Test", 1, PriorityWorker)
    try:
      self._CheckWorkerCount(wp, 1)

      ctx = PriorityContext()

      # Use static seed for this test
      rnd = random.Random(4727)

      # Disable processing of tasks
      wp.SetActive(False)

      # No task ID
      self.assertRaises(workerpool.NoSuchTask, wp.ChangeTaskPriority,
                        None, 0)

      # Pre-generate task IDs and priorities
      count = 100
      task_ids = range(0, count)
      priorities = range(200, 200 + count) * 2

      rnd.shuffle(task_ids)
      rnd.shuffle(priorities)

      # Make sure there are some duplicate priorities, but not all
      priorities[count * 2 - 10:count * 2 - 1] = \
        priorities[count - 10: count - 1]

      assert len(priorities) == 2 * count
      assert priorities[0:(count - 1)] != priorities[count:(2 * count - 1)]

      # Add some tasks; this loop consumes the first half of all previously
      # generated priorities
      for (idx, task_id) in enumerate(task_ids):
        wp.AddTask((ctx, idx),
                   priority=priorities.pop(),
                   task_id=task_id)

      self.assertEqual(len(wp._tasks), len(task_ids))
      self.assertEqual(len(wp._taskdata), len(task_ids))

      # Tasks have been added, so half of the priorities should have been
      # consumed
      assert len(priorities) == len(task_ids)

      # Change task priority
      expected = []
      for ((idx, task_id), prio) in zip(enumerate(task_ids), priorities):
        wp.ChangeTaskPriority(task_id, prio)
        expected.append((prio, idx))

      self.assertEqual(len(wp._taskdata), len(task_ids))

      # Half the entries are now abandoned tasks
      self.assertEqual(len(wp._tasks), len(task_ids) * 2)

      assert len(priorities) == count
      assert len(task_ids) == count

      # Start processing
      wp.SetActive(True)

      # Wait for tasks to finish
      wp.Quiesce()

      self._CheckNoTasks(wp)

      for task_id in task_ids:
        # All tasks are done
        self.assertRaises(workerpool.NoSuchTask, wp.ChangeTaskPriority,
                          task_id, 0)

      # Check result
      ctx.lock.acquire()
      try:
        self.assertEqual(ctx.result, sorted(expected))
      finally:
        ctx.lock.release()

      self._CheckWorkerCount(wp, 1)
    finally:
      wp.TerminateWorkers()
      self._CheckWorkerCount(wp, 0)

  def testChangeTaskPriorityInteralStructures(self):
    wp = workerpool.WorkerPool("Test", 1, NotImplementedWorker)
    try:
      self._CheckWorkerCount(wp, 1)

      # Use static seed for this test
      rnd = random.Random(643)

      (num1, num2) = rnd.sample(range(1000), 2)

      # Disable processing of tasks
      wp.SetActive(False)

      self.assertFalse(wp._tasks)
      self.assertFalse(wp._taskdata)

      # No priority or task ID
      wp.AddTask(())
      self.assertEqual(wp._tasks, [
        [workerpool._DEFAULT_PRIORITY, 0, None, ()],
        ])
      self.assertFalse(wp._taskdata)

      # No task ID
      wp.AddTask((), priority=7413)
      self.assertEqual(wp._tasks, [
        [workerpool._DEFAULT_PRIORITY, 0, None, ()],
        [7413, 1, None, ()],
        ])
      self.assertFalse(wp._taskdata)

      # Start adding real tasks
      wp.AddTask((), priority=10267659, task_id=num1)
      self.assertEqual(wp._tasks, [
        [workerpool._DEFAULT_PRIORITY, 0, None, ()],
        [7413, 1, None, ()],
        [10267659, 2, num1, ()],
        ])
      self.assertEqual(wp._taskdata, {
        num1: [10267659, 2, num1, ()],
        })

      wp.AddTask((), priority=123, task_id=num2)
      self.assertEqual(sorted(wp._tasks), [
        [workerpool._DEFAULT_PRIORITY, 0, None, ()],
        [123, 3, num2, ()],
        [7413, 1, None, ()],
        [10267659, 2, num1, ()],
        ])
      self.assertEqual(wp._taskdata, {
        num1: [10267659, 2, num1, ()],
        num2: [123, 3, num2, ()],
        })

      wp.ChangeTaskPriority(num1, 100)
      self.assertEqual(sorted(wp._tasks), [
        [workerpool._DEFAULT_PRIORITY, 0, None, ()],
        [100, 2, num1, ()],
        [123, 3, num2, ()],
        [7413, 1, None, ()],
        [10267659, 2, num1, None],
        ])
      self.assertEqual(wp._taskdata, {
        num1: [100, 2, num1, ()],
        num2: [123, 3, num2, ()],
        })

      wp.ChangeTaskPriority(num2, 91337)
      self.assertEqual(sorted(wp._tasks), [
        [workerpool._DEFAULT_PRIORITY, 0, None, ()],
        [100, 2, num1, ()],
        [123, 3, num2, None],
        [7413, 1, None, ()],
        [91337, 3, num2, ()],
        [10267659, 2, num1, None],
        ])
      self.assertEqual(wp._taskdata, {
        num1: [100, 2, num1, ()],
        num2: [91337, 3, num2, ()],
        })

      wp.ChangeTaskPriority(num1, 10139)
      self.assertEqual(sorted(wp._tasks), [
        [workerpool._DEFAULT_PRIORITY, 0, None, ()],
        [100, 2, num1, None],
        [123, 3, num2, None],
        [7413, 1, None, ()],
        [10139, 2, num1, ()],
        [91337, 3, num2, ()],
        [10267659, 2, num1, None],
        ])
      self.assertEqual(wp._taskdata, {
        num1: [10139, 2, num1, ()],
        num2: [91337, 3, num2, ()],
        })

      # Change to the same priority once again
      wp.ChangeTaskPriority(num1, 10139)
      self.assertEqual(sorted(wp._tasks), [
        [workerpool._DEFAULT_PRIORITY, 0, None, ()],
        [100, 2, num1, None],
        [123, 3, num2, None],
        [7413, 1, None, ()],
        [10139, 2, num1, None],
        [10139, 2, num1, ()],
        [91337, 3, num2, ()],
        [10267659, 2, num1, None],
        ])
      self.assertEqual(wp._taskdata, {
        num1: [10139, 2, num1, ()],
        num2: [91337, 3, num2, ()],
        })

      self._CheckWorkerCount(wp, 1)
    finally:
      wp.TerminateWorkers()
      self._CheckWorkerCount(wp, 0)

706

707
if __name__ == "__main__":
708
  testutils.GanetiTestProgram()