workerpool.py 13.3 KB
Newer Older
1
2
3
#
#

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
#
# 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.


"""Base classes for worker pools.

"""

import logging
import threading
28
import heapq
29

30
from ganeti import compat
31
from ganeti import errors
32

33

34
_TERMINATE = object()
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
_DEFAULT_PRIORITY = 0


class DeferTask(Exception):
  """Special exception class to defer a task.

  This class can be raised by L{BaseWorker.RunTask} to defer the execution of a
  task. Optionally, the priority of the task can be changed.

  """
  def __init__(self, priority=None):
    """Initializes this class.

    @type priority: number
    @param priority: New task priority (None means no change)

    """
    Exception.__init__(self)
    self.priority = priority
54
55


56
57
58
59
60
61
class BaseWorker(threading.Thread, object):
  """Base worker class for worker pools.

  Users of a worker pool must override RunTask in a subclass.

  """
62
  # pylint: disable=W0212
63
64
65
  def __init__(self, pool, worker_id):
    """Constructor for BaseWorker thread.

66
67
    @param pool: the parent worker pool
    @param worker_id: identifier for this worker
68
69

    """
70
    super(BaseWorker, self).__init__(name=worker_id)
71
    self.pool = pool
72
    self._worker_id = worker_id
73
74
    self._current_task = None

75
76
    assert self.getName() == worker_id

77
  def ShouldTerminate(self):
78
79
80
    """Returns whether this worker should terminate.

    Should only be called from within L{RunTask}.
81
82

    """
83
84
85
86
87
88
    self.pool._lock.acquire()
    try:
      assert self._HasRunningTaskUnlocked()
      return self.pool._ShouldWorkerTerminateUnlocked(self)
    finally:
      self.pool._lock.release()
89

90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
  def GetCurrentPriority(self):
    """Returns the priority of the current task.

    Should only be called from within L{RunTask}.

    """
    self.pool._lock.acquire()
    try:
      assert self._HasRunningTaskUnlocked()

      (priority, _, _) = self._current_task

      return priority
    finally:
      self.pool._lock.release()

106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
  def SetTaskName(self, taskname):
    """Sets the name of the current task.

    Should only be called from within L{RunTask}.

    @type taskname: string
    @param taskname: Task's name

    """
    if taskname:
      name = "%s/%s" % (self._worker_id, taskname)
    else:
      name = self._worker_id

    # Set thread name
    self.setName(name)

123
124
125
126
127
128
  def _HasRunningTaskUnlocked(self):
    """Returns whether this worker is currently running a task.

    """
    return (self._current_task is not None)

129
130
131
132
133
134
135
136
137
  def run(self):
    """Main thread function.

    Waits for new tasks to show up in the queue.

    """
    pool = self.pool

    while True:
138
      assert self._current_task is None
139
140

      defer = None
141
      try:
142
        # Wait on lock to be told either to terminate or to do a task
143
144
        pool._lock.acquire()
        try:
145
          task = pool._WaitForTaskUnlocked(self)
146

147
148
149
          if task is _TERMINATE:
            # Told to terminate
            break
150

151
152
153
          if task is None:
            # Spurious notification, ignore
            continue
154

155
          self._current_task = task
156

157
158
159
          # No longer needed, dispose of reference
          del task

160
          assert self._HasRunningTaskUnlocked()
161

162
163
164
        finally:
          pool._lock.release()

165
        (priority, _, args) = self._current_task
166
        try:
167
168
169
          # Run the actual task
          assert defer is None
          logging.debug("Starting task %r, priority %s", args, priority)
170
171
          assert self.getName() == self._worker_id
          try:
172
            self.RunTask(*args) # pylint: disable=W0142
173
174
          finally:
            self.SetTaskName(None)
175
176
177
178
179
180
181
182
          logging.debug("Done with task %r, priority %s", args, priority)
        except DeferTask, err:
          defer = err

          if defer.priority is None:
            # Use same priority
            defer.priority = priority

Michael Hanselmann's avatar
Michael Hanselmann committed
183
184
          logging.debug("Deferring task %r, new priority %s",
                        args, defer.priority)
185
186

          assert self._HasRunningTaskUnlocked()
187
        except: # pylint: disable=W0702
188
          logging.exception("Caught unhandled exception")
189
190

        assert self._HasRunningTaskUnlocked()
191
192
193
194
      finally:
        # Notify pool
        pool._lock.acquire()
        try:
195
196
197
198
199
200
          if defer:
            assert self._current_task
            # Schedule again for later run
            (_, _, args) = self._current_task
            pool._AddTaskUnlocked(args, defer.priority)

201
202
          if self._current_task:
            self._current_task = None
203
            pool._worker_to_pool.notifyAll()
204
205
206
        finally:
          pool._lock.release()

207
208
      assert not self._HasRunningTaskUnlocked()

209
    logging.debug("Terminates")
210

211
212
213
  def RunTask(self, *args):
    """Function called to start a task.

214
215
    This needs to be implemented by child classes.

216
217
218
219
220
221
222
223
224
    """
    raise NotImplementedError()


class WorkerPool(object):
  """Worker pool with a queue.

  This class is thread-safe.

225
226
227
  Tasks are guaranteed to be started in the order in which they're
  added to the pool. Due to the nature of threading, they're not
  guaranteed to finish in the same order.
228
229

  """
230
  def __init__(self, name, num_workers, worker_class):
231
232
    """Constructor for worker pool.

233
234
235
236
    @param num_workers: number of workers to be started
        (dynamic resizing is not yet implemented)
    @param worker_class: the class to be instantiated for workers;
        should derive from L{BaseWorker}
237
238
239

    """
    # Some of these variables are accessed by BaseWorker
240
241
242
243
    self._lock = threading.Lock()
    self._pool_to_pool = threading.Condition(self._lock)
    self._pool_to_worker = threading.Condition(self._lock)
    self._worker_to_pool = threading.Condition(self._lock)
244
    self._worker_class = worker_class
245
    self._name = name
246
247
248
249
250
251
252
253
    self._last_worker_id = 0
    self._workers = []
    self._quiescing = False

    # Terminating workers
    self._termworkers = []

    # Queued tasks
254
255
    self._counter = 0
    self._tasks = []
256
257
258
259
260
261

    # Start workers
    self.Resize(num_workers)

  # TODO: Implement dynamic resizing?

Guido Trotter's avatar
Guido Trotter committed
262
263
264
265
266
267
268
  def _WaitWhileQuiescingUnlocked(self):
    """Wait until the worker pool has finished quiescing.

    """
    while self._quiescing:
      self._pool_to_pool.wait()

269
270
271
272
273
274
275
276
277
  def _AddTaskUnlocked(self, args, priority):
    """Adds a task to the internal queue.

    @type args: sequence
    @param args: Arguments passed to L{BaseWorker.RunTask}
    @type priority: number
    @param priority: Task priority

    """
278
    assert isinstance(args, (tuple, list)), "Arguments must be a sequence"
279
    assert isinstance(priority, (int, long)), "Priority must be numeric"
280

281
282
283
284
285
286
    # This counter is used to ensure elements are processed in their
    # incoming order. For processing they're sorted by priority and then
    # counter.
    self._counter += 1

    heapq.heappush(self._tasks, (priority, self._counter, args))
287
288
289
290

    # Notify a waiting worker
    self._pool_to_worker.notify()

291
  def AddTask(self, args, priority=_DEFAULT_PRIORITY):
292
293
    """Adds a task to the queue.

294
    @type args: sequence
295
    @param args: arguments passed to L{BaseWorker.RunTask}
296
297
    @type priority: number
    @param priority: Task priority
298
299
300
301

    """
    self._lock.acquire()
    try:
Guido Trotter's avatar
Guido Trotter committed
302
      self._WaitWhileQuiescingUnlocked()
303
      self._AddTaskUnlocked(args, priority)
304
305
306
    finally:
      self._lock.release()

307
  def AddManyTasks(self, tasks, priority=_DEFAULT_PRIORITY):
Guido Trotter's avatar
Guido Trotter committed
308
309
310
311
    """Add a list of tasks to the queue.

    @type tasks: list of tuples
    @param tasks: list of args passed to L{BaseWorker.RunTask}
312
313
314
    @type priority: number or list of numbers
    @param priority: Priority for all added tasks or a list with the priority
                     for each task
Guido Trotter's avatar
Guido Trotter committed
315
316

    """
317
318
319
    assert compat.all(isinstance(task, (tuple, list)) for task in tasks), \
      "Each task must be a sequence"

320
321
322
323
324
325
326
327
328
329
330
    assert (isinstance(priority, (int, long)) or
            compat.all(isinstance(prio, (int, long)) for prio in priority)), \
           "Priority must be numeric or be a list of numeric values"

    if isinstance(priority, (int, long)):
      priority = [priority] * len(tasks)
    elif len(priority) != len(tasks):
      raise errors.ProgrammerError("Number of priorities (%s) doesn't match"
                                   " number of tasks (%s)" %
                                   (len(priority), len(tasks)))

Guido Trotter's avatar
Guido Trotter committed
331
332
333
334
    self._lock.acquire()
    try:
      self._WaitWhileQuiescingUnlocked()

335
336
337
338
339
      assert compat.all(isinstance(prio, (int, long)) for prio in priority)
      assert len(tasks) == len(priority)

      for args, priority in zip(tasks, priority):
        self._AddTaskUnlocked(args, priority)
Guido Trotter's avatar
Guido Trotter committed
340
341
342
    finally:
      self._lock.release()

343
344
345
346
347
348
349
350
351
352
353
354
355
356
  def _WaitForTaskUnlocked(self, worker):
    """Waits for a task for a worker.

    @type worker: L{BaseWorker}
    @param worker: Worker thread

    """
    if self._ShouldWorkerTerminateUnlocked(worker):
      return _TERMINATE

    # We only wait if there's no task for us.
    if not self._tasks:
      logging.debug("Waiting for tasks")

357
358
359
      while True:
        # wait() releases the lock and sleeps until notified
        self._pool_to_worker.wait()
360

361
        logging.debug("Notified while waiting")
362

363
364
365
        # Were we woken up in order to terminate?
        if self._ShouldWorkerTerminateUnlocked(worker):
          return _TERMINATE
366

367
368
        if self._tasks:
          break
369
370
371

    # Get task from queue and tell pool about it
    try:
372
      return heapq.heappop(self._tasks)
373
374
375
    finally:
      self._worker_to_pool.notifyAll()

376
377
378
379
380
381
382
383
384
385
386
  def _ShouldWorkerTerminateUnlocked(self, worker):
    """Returns whether a worker should terminate.

    """
    return (worker in self._termworkers)

  def _HasRunningTasksUnlocked(self):
    """Checks whether there's a task running in a worker.

    """
    for worker in self._workers + self._termworkers:
387
      if worker._HasRunningTaskUnlocked(): # pylint: disable=W0212
388
389
390
391
392
393
394
395
396
397
398
399
400
        return True
    return False

  def Quiesce(self):
    """Waits until the task queue is empty.

    """
    self._lock.acquire()
    try:
      self._quiescing = True

      # Wait while there are tasks pending or running
      while self._tasks or self._HasRunningTasksUnlocked():
401
        self._worker_to_pool.wait()
402
403
404
405
406

    finally:
      self._quiescing = False

      # Make sure AddTasks continues in case it was waiting
407
      self._pool_to_pool.notifyAll()
408
409
410
411

      self._lock.release()

  def _NewWorkerIdUnlocked(self):
412
413
414
    """Return an identifier for a new worker.

    """
415
    self._last_worker_id += 1
416
417

    return "%s%d" % (self._name, self._last_worker_id)
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

  def _ResizeUnlocked(self, num_workers):
    """Changes the number of workers.

    """
    assert num_workers >= 0, "num_workers must be >= 0"

    logging.debug("Resizing to %s workers", num_workers)

    current_count = len(self._workers)

    if current_count == num_workers:
      # Nothing to do
      pass

    elif current_count > num_workers:
      if num_workers == 0:
        # Create copy of list to iterate over while lock isn't held.
        termworkers = self._workers[:]
        del self._workers[:]
      else:
        # TODO: Implement partial downsizing
        raise NotImplementedError()
        #termworkers = ...

      self._termworkers += termworkers

      # Notify workers that something has changed
446
      self._pool_to_worker.notifyAll()
447
448
449
450
451

      # Join all terminating workers
      self._lock.release()
      try:
        for worker in termworkers:
452
          logging.debug("Waiting for thread %s", worker.getName())
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
          worker.join()
      finally:
        self._lock.acquire()

      # Remove terminated threads. This could be done in a more efficient way
      # (del self._termworkers[:]), but checking worker.isAlive() makes sure we
      # don't leave zombie threads around.
      for worker in termworkers:
        assert worker in self._termworkers, ("Worker not in list of"
                                             " terminating workers")
        if not worker.isAlive():
          self._termworkers.remove(worker)

      assert not self._termworkers, "Zombie worker detected"

    elif current_count < num_workers:
      # Create (num_workers - current_count) new workers
470
      for _ in range(num_workers - current_count):
471
472
473
474
475
476
477
        worker = self._worker_class(self, self._NewWorkerIdUnlocked())
        self._workers.append(worker)
        worker.start()

  def Resize(self, num_workers):
    """Changes the number of workers in the pool.

478
    @param num_workers: the new number of workers
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504

    """
    self._lock.acquire()
    try:
      return self._ResizeUnlocked(num_workers)
    finally:
      self._lock.release()

  def TerminateWorkers(self):
    """Terminate all worker threads.

    Unstarted tasks will be ignored.

    """
    logging.debug("Terminating all workers")

    self._lock.acquire()
    try:
      self._ResizeUnlocked(0)

      if self._tasks:
        logging.debug("There are %s tasks left", len(self._tasks))
    finally:
      self._lock.release()

    logging.debug("All workers terminated")