Debian Codegraph @

futurist/_futures.py

raw
1 # Copyright (C) 2014 Yahoo! Inc. All Rights Reserved.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License"); you may
4 # not use this file except in compliance with the License. You may obtain
5 # a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 # License for the specific language governing permissions and limitations
13 # under the License.
14
15 import functools
16 import logging
17 import queue
18 import threading
19 import time
20
21 from concurrent import futures as _futures
22 from concurrent.futures import process as _process
23
24 from debtcollector import removals
25
26 from futurist import _green
27 from futurist import _thread
28 from futurist import _utils
29
30 TimeoutError = _futures.TimeoutError
31 CancelledError = _futures.CancelledError
32
33
34 LOG = logging.getLogger(__name__)
35
36
37 class RejectedSubmission(Exception):
38 """Exception raised when a submitted call is rejected (for some reason)."""
39
40
41 # NOTE(harlowja): Allows for simpler access to this type...
42 Future = _futures.Future
43
44
45 class _Gatherer:
46 def __init__(self, submit_func, lock_factory, start_before_submit=False):
47 self._submit_func = submit_func
48 self._stats_lock = lock_factory()
49 self._stats = ExecutorStatistics()
50 self._start_before_submit = start_before_submit
51
52 @property
53 def statistics(self):
54 return self._stats
55
56 def clear(self):
57 with self._stats_lock:
58 self._stats = ExecutorStatistics()
59
60 def _capture_stats(self, started_at, fut):
61 """Capture statistics
62
63 :param started_at: when the activity the future has performed
64 was started at
65 :param fut: future object
66 """
67 # If time somehow goes backwards, make sure we cap it at 0.0 instead
68 # of having negative elapsed time...
69 elapsed = max(0.0, _utils.now() - started_at)
70 with self._stats_lock:
71 # Use a new collection and lock so that all mutations are seen as
72 # atomic and not overlapping and corrupting with other
73 # mutations (the clone ensures that others reading the current
74 # values will not see a mutated/corrupted one). Since futures may
75 # be completed by different threads we need to be extra careful to
76 # gather this data in a way that is thread-safe...
77 (failures, executed, runtime, cancelled) = (self._stats.failures,
78 self._stats.executed,
79 self._stats.runtime,
80 self._stats.cancelled)
81 if fut.cancelled():
82 cancelled += 1
83 else:
84 executed += 1
85 if fut.exception() is not None:
86 failures += 1
87 runtime += elapsed
88 self._stats = ExecutorStatistics(failures=failures,
89 executed=executed,
90 runtime=runtime,
91 cancelled=cancelled)
92
93 def submit(self, fn, *args, **kwargs):
94 """Submit work to be executed and capture statistics."""
95 if self._start_before_submit:
96 started_at = _utils.now()
97 fut = self._submit_func(fn, *args, **kwargs)
98 if not self._start_before_submit:
99 started_at = _utils.now()
100 fut.add_done_callback(functools.partial(self._capture_stats,
101 started_at))
102 return fut
103
104
105 class ThreadPoolExecutor(_futures.Executor):
106 """Executor that uses a thread pool to execute calls asynchronously.
107
108 It gathers statistics about the submissions executed for post-analysis...
109
110 Note that this executor never shrinks its thread pool, which will cause
111 the pool to eventually reach its maximum capacity defined by max_workers.
112 Check :py:class:`DynamicThreadPoolExecutor` for an alternative.
113
114 See: https://docs.python.org/dev/library/concurrent.futures.html
115 """
116
117 threading = _thread.Threading()
118
119 def __init__(self, max_workers=None, check_and_reject=None):
120 """Initializes a thread pool executor.
121
122 :param max_workers: maximum number of workers that can be
123 simultaneously active at the same time, further
124 submitted work will be queued up when this limit
125 is reached.
126 :type max_workers: int
127 :param check_and_reject: a callback function that will be provided
128 two position arguments, the first argument
129 will be this executor instance, and the second
130 will be the number of currently queued work
131 items in this executors backlog; the callback
132 should raise a :py:class:`.RejectedSubmission`
133 exception if it wants to have this submission
134 rejected.
135 :type check_and_reject: callback
136 """
137 if max_workers is None:
138 max_workers = _utils.get_optimal_thread_count()
139 if max_workers <= 0:
140 raise ValueError("max_workers must be greater than zero")
141 self._max_workers = max_workers
142 self._work_queue = queue.Queue()
143 self._shutdown_lock = threading.RLock()
144 self._shutdown = False
145 self._workers = []
146 self._check_and_reject = check_and_reject or (lambda e, waiting: None)
147 self._gatherer = _Gatherer(self._submit, self.threading.lock_object)
148
149 @property
150 def statistics(self):
151 """:class:`.ExecutorStatistics` about the executors executions."""
152 return self._gatherer.statistics
153
154 @property
155 def alive(self):
156 """Accessor to determine if the executor is alive/active."""
157 return not self._shutdown
158
159 @property
160 def queue_size(self):
161 """The current size of the queue.
162
163 This value represents the number of tasks that are waiting for a free
164 worker thread.
165 """
166 return self._work_queue.qsize()
167
168 @property
169 def num_workers(self):
170 """The current number of worker threads."""
171 return len(self._workers)
172
173 def get_num_idle_workers(self):
174 """Get the number of currently idle threads.
175
176 A thread is idle if it's waiting for new tasks from the queue.
177
178 This method is required to obtain the shutdown lock it provides
179 an accurate count.
180 """
181 with self._shutdown_lock:
182 return sum(1 for w in self._workers if w.idle)
183
184 def _add_thread(self):
185 w = _thread.ThreadWorker.create_and_register(
186 self, self._work_queue)
187 # Always save it before we start (so that even if we fail
188 # starting it we can correctly join on it).
189 self._workers.append(w)
190 w.start()
191
192 def _maybe_spin_up(self):
193 """Spin up a worker if needed."""
194 if (not self._workers or
195 len(self._workers) < self._max_workers):
196 self._add_thread()
197
198 def shutdown(self, wait=True):
199 with self._shutdown_lock:
200 if not self._shutdown:
201 self._shutdown = True
202 if wait:
203 # Wait for all queued work to complete using queue.join()
204 # This will block until all work items have been processed
205 # and task_done() has been called for each
206 self._work_queue.join()
207 for w in self._workers:
208 w.stop()
209 if wait:
210 for w in self._workers:
211 w.join()
212
213 def _submit(self, fn, *args, **kwargs):
214 f = Future()
215 self._maybe_spin_up()
216 self._work_queue.put(_utils.WorkItem(f, fn, args, kwargs))
217 return f
218
219 def submit(self, fn, *args, **kwargs):
220 """Submit some work to be executed (and gather statistics)."""
221 # NOTE(dtantsur): DynamicThreadPoolExecutor relies on this lock for
222 # its complex logic around thread management. If you ever decide to
223 # remove it, please add a lock there instead.
224 with self._shutdown_lock:
225 if self._shutdown:
226 raise RuntimeError('Can not schedule new futures'
227 ' after being shutdown')
228 self._check_and_reject(self, self._work_queue.qsize())
229 return self._gatherer.submit(fn, *args, **kwargs)
230
231
232 class DynamicThreadPoolExecutor(ThreadPoolExecutor):
233 """Executor that creates or removes threads on demand.
234
235 As new work is scheduled on the executor, it will try to keep the
236 proportion of busy threads within the provided range (between 40% and 80%
237 by default). A busy thread is a thread that is not waiting on the
238 task queue.
239
240 Each time a task is submitted, the executor makes a decision whether to
241 grow or shrink the pool. It takes the proportion of the number of busy
242 threads to the total number of threads and compares it to shrink_threshold
243 and grow_threshold.
244
245 Initially, the pool is empty, so submitting a task always result in one
246 new thread. Since min_workers must be greater than zero, at least one
247 thread will always be available after this point.
248
249 Once the proportion of busy threads reaches grow_threshold (e.g. 4 out of 5
250 with the default grow_threshold of 0.8), a new thread is created when a
251 task is submitted. If on submitting a task a proportion of busy threads is
252 below shrink_threshold (e.g. only 2 out of 5), one idle thread is stopped.
253
254 The values of grow_threshold and shrink_threshold are different to prevent
255 the number of threads from oscilating on reaching grow_threshold.
256
257 If threads are not created often in your application, the number of idle
258 threads may stay high for a long time. To avoid it, you can call
259 :py:meth:`.maintain` periodically to keep the number of threads within
260 the thresholds.
261
262 """
263
264 def __init__(self, max_workers=None, check_and_reject=None,
265 min_workers=1, grow_threshold=0.8,
266 shrink_threshold=0.4):
267 """Initializes a thread pool executor.
268
269 :param max_workers: maximum number of workers that can be
270 simultaneously active at the same time, further
271 submitted work will be queued up when this limit
272 is reached.
273 :type max_workers: int
274 :param check_and_reject: a callback function that will be provided
275 two position arguments, the first argument
276 will be this executor instance, and the second
277 will be the number of currently queued work
278 items in this executors backlog; the callback
279 should raise a :py:class:`.RejectedSubmission`
280 exception if it wants to have this submission
281 rejected.
282 :type check_and_reject: callback
283 :param min_workers: the minimum number of workers that can be reached
284 when shrinking the pool. Note that the pool always
285 starts at zero workers and will be smaller than
286 min_workers until enough workers are created.
287 At least one thread is required.
288 :type max_workers: int
289 :param grow_threshold: minimum proportion of busy threads to total
290 threads for the pool to grow.
291 :type grow_threshold: float
292 :param shrink_threshold: maximum proportion of busy threads to total
293 threads for the pool to shrink.
294 :type shrink_threshold: float
295 """
296 super().__init__(max_workers=max_workers,
297 check_and_reject=check_and_reject)
298 if min_workers <= 0:
299 raise ValueError('min_workers must be greater than zero')
300 if max_workers and min_workers >= max_workers:
301 raise ValueError('min_workers must be less than max_workers')
302 self._min_workers = min_workers
303
304 if grow_threshold <= 0 or grow_threshold > 1.0:
305 raise ValueError('grow_threshold must be within (0, 1]')
306 if shrink_threshold < 0 or shrink_threshold >= 1.0:
307 raise ValueError('shrink_threshold must be within [0, 1)')
308 if shrink_threshold >= grow_threshold:
309 raise ValueError(
310 'shrink_threshold must be less than grow_threshold')
311 self._grow_threshold = grow_threshold
312 self._shrink_threshold = shrink_threshold
313
314 self._dead_workers = []
315
316 def _drop_thread(self):
317 new_workers = []
318 idle_worker = None
319 for i, w in enumerate(self._workers):
320 if w.idle:
321 new_workers = self._workers[i + 1:]
322 idle_worker = w
323 break
324 new_workers.append(w)
325
326 if idle_worker is None:
327 # Should not actually happen but races are possible; do nothing
328 LOG.warning(
329 'No idle worker thread to delete when shrinking pool %r', self)
330 return False
331
332 w.stop()
333 self._workers = new_workers
334 self._dead_workers.append(w)
335 return True
336
337 def _maybe_spin_up(self):
338 nthreads = self.num_workers
339 if nthreads < self._min_workers:
340 self._add_thread()
341 return True
342
343 # NOTE(dtantsur): here we count the number of threads that are
344 # doing something (i.e. are not waiting on the queue) plus the
345 # number of tasks in the queue. In theory, if there are idle
346 # workers, the queue should be empty. But race conditions are
347 # possible when workers do not pick up tasks quickly enough,
348 # especially in the presence of CPU-bound tasks.
349 idle = self.get_num_idle_workers()
350 busy = (nthreads - idle + self.queue_size) / nthreads
351 if busy >= self._grow_threshold and nthreads < self._max_workers:
352 LOG.debug('Creating a new worker thread for pool %r '
353 '(%d thread(s) idle, queue size %d, total %d thread(s))',
354 self, idle, self.queue_size, nthreads)
355 self._add_thread()
356 return True
357 elif busy <= self._shrink_threshold and nthreads > self._min_workers:
358 LOG.debug('Deleting a worker thread from pool %r '
359 '(%d thread(s) idle, queue size %d, total %d thread(s))',
360 self, idle, self.queue_size, nthreads)
361 return self._drop_thread()
362
363 return False
364
365 def maintain(self):
366 """Keep the number of threads within the expected range.
367
368 If too many idle threads are running, they are deleted.
369 Additionally, deleted workers are joined to free up resources.
370 """
371 # NOTE(dtantsur): this call can potentially run for some time, so
372 # avoid taking shutdown_lock once and holding it for the entire
373 # duration (blocking any new tasks from being added).
374 keep_going = True
375 while keep_going:
376 if self._shutdown:
377 return
378
379 with self._shutdown_lock:
380 keep_going = self._maybe_spin_up()
381
382 time.sleep(0)
383
384 # NOTE(dtantsur): copy the value of _dead_workers to prevent races with
385 # other invocations for maintain or shutdown.
386 with self._shutdown_lock:
387 dead_workers = self._dead_workers
388 self._dead_workers = []
389
390 for w in dead_workers:
391 w.join()
392
393 def shutdown(self, wait=True):
394 super().shutdown(wait=wait)
395 if wait:
396 for w in self._dead_workers:
397 w.join()
398
399
400 class ProcessPoolExecutor(_process.ProcessPoolExecutor):
401 """Executor that uses a process pool to execute calls asynchronously.
402
403 It gathers statistics about the submissions executed for post-analysis...
404
405 See: https://docs.python.org/dev/library/concurrent.futures.html
406 """
407
408 threading = _thread.Threading()
409
410 def __init__(self, max_workers=None):
411 if max_workers is None:
412 max_workers = _utils.get_optimal_process_count()
413 super().__init__(max_workers=max_workers)
414 if self._max_workers <= 0:
415 raise ValueError("Max workers must be greater than zero")
416 self._gatherer = _Gatherer(
417 # Since our submit will use this gatherer we have to reference
418 # the parent submit, bound to this instance (which is what we
419 # really want to use anyway).
420 super().submit,
421 self.threading.lock_object)
422
423 @property
424 def alive(self):
425 """Accessor to determine if the executor is alive/active."""
426 return not self._shutdown_thread
427
428 @property
429 def statistics(self):
430 """:class:`.ExecutorStatistics` about the executors executions."""
431 return self._gatherer.statistics
432
433 def submit(self, fn, *args, **kwargs):
434 """Submit some work to be executed (and gather statistics)."""
435 return self._gatherer.submit(fn, *args, **kwargs)
436
437
438 class SynchronousExecutor(_futures.Executor):
439 """Executor that uses the caller to execute calls synchronously.
440
441 This provides an interface to a caller that looks like an executor but
442 will execute the calls inside the caller thread instead of executing it
443 in a external process/thread for when this type of functionality is
444 useful to provide...
445
446 It gathers statistics about the submissions executed for post-analysis...
447 """
448
449 threading = _thread.Threading()
450
451 @removals.removed_kwarg('green',
452 message="Eventlet support is deprecated. "
453 "Please migrate your code and stop enforcing "
454 "its usage.")
455 def __init__(self, green=False, run_work_func=lambda work: work.run()):
456 """Synchronous executor constructor.
457
458 :param green: when enabled this forces the usage of greened lock
459 classes and green futures (so that the internals of this
460 object operate correctly under eventlet)
461 :type green: bool
462 :param run_work_func: callable that takes a single work item and
463 runs it (typically in a blocking manner)
464 :param run_work_func: callable
465 """
466 if green and not _utils.EVENTLET_AVAILABLE:
467 raise RuntimeError('Eventlet is needed to use a green'
468 ' synchronous executor')
469 if not callable(run_work_func):
470 raise ValueError("Run work parameter expected to be callable")
471 self._run_work_func = run_work_func
472 self._shutoff = False
473 if green:
474 self.threading = _green.threading
475 self._future_cls = GreenFuture
476 else:
477 self._future_cls = Future
478 self._run_work_func = run_work_func
479 self._gatherer = _Gatherer(self._submit,
480 self.threading.lock_object,
481 start_before_submit=True)
482
483 @property
484 def alive(self):
485 """Accessor to determine if the executor is alive/active."""
486 return not self._shutoff
487
488 def shutdown(self, wait=True):
489 self._shutoff = True
490
491 def restart(self):
492 """Restarts this executor (*iff* previously shutoff/shutdown).
493
494 NOTE(harlowja): clears any previously gathered statistics.
495 """
496 if self._shutoff:
497 self._shutoff = False
498 self._gatherer.clear()
499
500 @property
501 def statistics(self):
502 """:class:`.ExecutorStatistics` about the executors executions."""
503 return self._gatherer.statistics
504
505 def submit(self, fn, *args, **kwargs):
506 """Submit some work to be executed (and gather statistics)."""
507 if self._shutoff:
508 raise RuntimeError('Can not schedule new futures'
509 ' after being shutdown')
510 return self._gatherer.submit(fn, *args, **kwargs)
511
512 def _submit(self, fn, *args, **kwargs):
513 fut = self._future_cls()
514 self._run_work_func(_utils.WorkItem(fut, fn, args, kwargs))
515 return fut
516
517
518 @removals.removed_class("GreenFuture",
519 message="Eventlet support is deprecated. "
520 "Please migrate your code and stop using Green "
521 "future.")
522 class GreenFuture(Future):
523 __doc__ = Future.__doc__
524
525 def __init__(self):
526 super().__init__()
527 if not _utils.EVENTLET_AVAILABLE:
528 raise RuntimeError('Eventlet is needed to use a green future')
529 # NOTE(harlowja): replace the built-in condition with a greenthread
530 # compatible one so that when getting the result of this future the
531 # functions will correctly yield to eventlet. If this is not done then
532 # waiting on the future never actually causes the greenthreads to run
533 # and thus you wait for infinity.
534 if not _green.is_monkey_patched('thread'):
535 self._condition = _green.threading.condition_object()
536
537
538 @removals.removed_class("GreenThreadPoolExecutor",
539 message="Eventlet support is deprecated. "
540 "Please migrate your code and stop using Green "
541 "executor.")
542 class GreenThreadPoolExecutor(_futures.Executor):
543 """Executor that uses a green thread pool to execute calls asynchronously.
544
545 See: https://docs.python.org/dev/library/concurrent.futures.html
546 and http://eventlet.net/doc/modules/greenpool.html for information on
547 how this works.
548
549 It gathers statistics about the submissions executed for post-analysis...
550 """
551
552 threading = _green.threading
553
554 def __init__(self, max_workers=1000, check_and_reject=None):
555 """Initializes a green thread pool executor.
556
557 :param max_workers: maximum number of workers that can be
558 simulatenously active at the same time, further
559 submitted work will be queued up when this limit
560 is reached.
561 :type max_workers: int
562 :param check_and_reject: a callback function that will be provided
563 two position arguments, the first argument
564 will be this executor instance, and the second
565 will be the number of currently queued work
566 items in this executors backlog; the callback
567 should raise a :py:class:`.RejectedSubmission`
568 exception if it wants to have this submission
569 rejected.
570 :type check_and_reject: callback
571 """
572 if not _utils.EVENTLET_AVAILABLE:
573 raise RuntimeError('Eventlet is needed to use a green executor')
574 if max_workers <= 0:
575 raise ValueError("Max workers must be greater than zero")
576 self._max_workers = max_workers
577 self._pool = _green.Pool(self._max_workers)
578 self._delayed_work = _green.Queue()
579 self._check_and_reject = check_and_reject or (lambda e, waiting: None)
580 self._shutdown_lock = self.threading.lock_object()
581 self._shutdown = False
582 self._gatherer = _Gatherer(self._submit,
583 self.threading.lock_object)
584
585 @property
586 def alive(self):
587 """Accessor to determine if the executor is alive/active."""
588 return not self._shutdown
589
590 @property
591 def statistics(self):
592 """:class:`.ExecutorStatistics` about the executors executions."""
593 return self._gatherer.statistics
594
595 def submit(self, fn, *args, **kwargs):
596 """Submit some work to be executed (and gather statistics).
597
598 :param args: non-keyworded arguments
599 :type args: list
600 :param kwargs: key-value arguments
601 :type kwargs: dictionary
602 """
603 with self._shutdown_lock:
604 if self._shutdown:
605 raise RuntimeError('Can not schedule new futures'
606 ' after being shutdown')
607 self._check_and_reject(self, self._delayed_work.qsize())
608 return self._gatherer.submit(fn, *args, **kwargs)
609
610 def _submit(self, fn, *args, **kwargs):
611 f = GreenFuture()
612 work = _utils.WorkItem(f, fn, args, kwargs)
613 if not self._spin_up(work):
614 self._delayed_work.put(work)
615 return f
616
617 def _spin_up(self, work):
618 """Spin up a greenworker if less than max_workers.
619
620 :param work: work to be given to the greenworker
621 :returns: whether a green worker was spun up or not
622 :rtype: boolean
623 """
624 alive = self._pool.running() + self._pool.waiting()
625 if alive < self._max_workers:
626 self._pool.spawn_n(_green.GreenWorker(work, self._delayed_work))
627 return True
628 return False
629
630 def shutdown(self, wait=True):
631 with self._shutdown_lock:
632 if not self._shutdown:
633 self._shutdown = True
634 shutoff = True
635 else:
636 shutoff = False
637 if wait and shutoff:
638 self._delayed_work.join()
639 self._pool.waitall()
640
641
642 class ExecutorStatistics:
643 """Holds *immutable* information about a executors executions."""
644
645 __slots__ = ['_failures', '_executed', '_runtime', '_cancelled']
646
647 _REPR_MSG_TPL = ("<ExecutorStatistics object at 0x%(ident)x"
648 " (failures=%(failures)s,"
649 " executed=%(executed)s, runtime=%(runtime)0.2f,"
650 " cancelled=%(cancelled)s)>")
651
652 def __init__(self, failures=0, executed=0, runtime=0.0, cancelled=0):
653 self._failures = failures
654 self._executed = executed
655 self._runtime = runtime
656 self._cancelled = cancelled
657
658 @property
659 def failures(self):
660 """How many submissions ended up raising exceptions.
661
662 :returns: how many submissions ended up raising exceptions
663 :rtype: number
664 """
665 return self._failures
666
667 @property
668 def executed(self):
669 """How many submissions were executed (failed or not).
670
671 :returns: how many submissions were executed
672 :rtype: number
673 """
674 return self._executed
675
676 @property
677 def runtime(self):
678 """Total runtime of all submissions executed (failed or not).
679
680 :returns: total runtime of all submissions executed
681 :rtype: number
682 """
683 return self._runtime
684
685 @property
686 def cancelled(self):
687 """How many submissions were cancelled before executing.
688
689 :returns: how many submissions were cancelled before executing
690 :rtype: number
691 """
692 return self._cancelled
693
694 @property
695 def average_runtime(self):
696 """The average runtime of all submissions executed.
697
698 :returns: average runtime of all submissions executed
699 :rtype: number
700 :raises: ZeroDivisionError when no executions have occurred.
701 """
702 return self._runtime / self._executed
703
704 def __repr__(self):
705 return self._REPR_MSG_TPL % ({
706 'ident': id(self),
707 'failures': self._failures,
708 'executed': self._executed,
709 'runtime': self._runtime,
710 'cancelled': self._cancelled,
711 })