asynpool.py 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294
  1. # -*- coding: utf-8 -*-
  2. """Version of multiprocessing.Pool using Async I/O.
  3. .. note::
  4. This module will be moved soon, so don't use it directly.
  5. This is a non-blocking version of :class:`multiprocessing.Pool`.
  6. This code deals with three major challenges:
  7. #. Starting up child processes and keeping them running.
  8. #. Sending jobs to the processes and receiving results back.
  9. #. Safely shutting down this system.
  10. """
  11. from __future__ import absolute_import, unicode_literals
  12. import errno
  13. import gc
  14. import os
  15. import select
  16. import socket
  17. import struct
  18. import sys
  19. import time
  20. from collections import deque, namedtuple
  21. from io import BytesIO
  22. from numbers import Integral
  23. from pickle import HIGHEST_PROTOCOL
  24. from time import sleep
  25. from weakref import WeakValueDictionary, ref
  26. from billiard import pool as _pool
  27. from billiard.compat import buf_t, isblocking, setblocking
  28. from billiard.pool import ACK, NACK, RUN, TERMINATE, WorkersJoined
  29. from billiard.queues import _SimpleQueue
  30. from kombu.async import ERR, WRITE
  31. from kombu.serialization import pickle as _pickle
  32. from kombu.utils.eventio import SELECT_BAD_FD
  33. from kombu.utils.functional import fxrange
  34. from vine import promise
  35. from celery.five import Counter, items, values
  36. from celery.utils.functional import noop
  37. from celery.utils.log import get_logger
  38. from celery.worker import state as worker_state
  39. # pylint: disable=redefined-outer-name
  40. # We cache globals and attribute lookups, so disable this warning.
  41. try:
  42. from _billiard import read as __read__
  43. from struct import unpack_from as _unpack_from
  44. memoryview = memoryview
  45. readcanbuf = True
  46. if sys.version_info[0] == 2 and sys.version_info < (2, 7, 6):
  47. def unpack_from(fmt, view, _unpack_from=_unpack_from): # noqa
  48. return _unpack_from(fmt, view.tobytes()) # <- memoryview
  49. else:
  50. # unpack_from supports memoryview in 2.7.6 and 3.3+
  51. unpack_from = _unpack_from # noqa
  52. except (ImportError, NameError): # pragma: no cover
  53. def __read__(fd, buf, size, read=os.read): # noqa
  54. chunk = read(fd, size)
  55. n = len(chunk)
  56. if n != 0:
  57. buf.write(chunk)
  58. return n
  59. readcanbuf = False # noqa
  60. def unpack_from(fmt, iobuf, unpack=struct.unpack): # noqa
  61. return unpack(fmt, iobuf.getvalue()) # <-- BytesIO
  62. __all__ = ('AsynPool',)
  63. logger = get_logger(__name__)
  64. error, debug = logger.error, logger.debug
  65. UNAVAIL = frozenset({errno.EAGAIN, errno.EINTR})
  66. #: Constant sent by child process when started (ready to accept work)
  67. WORKER_UP = 15
  68. #: A process must've started before this timeout (in secs.) expires.
  69. PROC_ALIVE_TIMEOUT = 4.0
  70. SCHED_STRATEGY_FCFS = 1
  71. SCHED_STRATEGY_FAIR = 4
  72. SCHED_STRATEGIES = {
  73. None: SCHED_STRATEGY_FAIR,
  74. 'fast': SCHED_STRATEGY_FCFS,
  75. 'fcfs': SCHED_STRATEGY_FCFS,
  76. 'fair': SCHED_STRATEGY_FAIR,
  77. }
  78. SCHED_STRATEGY_TO_NAME = {v: k for k, v in SCHED_STRATEGIES.items()}
  79. Ack = namedtuple('Ack', ('id', 'fd', 'payload'))
  80. def gen_not_started(gen):
  81. """Return true if generator is not started."""
  82. # gi_frame is None when generator stopped.
  83. return gen.gi_frame and gen.gi_frame.f_lasti == -1
  84. def _get_job_writer(job):
  85. try:
  86. writer = job._writer
  87. except AttributeError:
  88. pass
  89. else:
  90. return writer() # is a weakref
  91. if hasattr(select, 'poll'):
  92. def _select_imp(readers=None, writers=None, err=None, timeout=0,
  93. poll=select.poll, POLLIN=select.POLLIN,
  94. POLLOUT=select.POLLOUT, POLLERR=select.POLLERR):
  95. poller = poll()
  96. register = poller.register
  97. if readers:
  98. [register(fd, POLLIN) for fd in readers]
  99. if writers:
  100. [register(fd, POLLOUT) for fd in writers]
  101. if err:
  102. [register(fd, POLLERR) for fd in err]
  103. R, W = set(), set()
  104. timeout = 0 if timeout and timeout < 0 else round(timeout * 1e3)
  105. events = poller.poll(timeout)
  106. for fd, event in events:
  107. if not isinstance(fd, Integral):
  108. fd = fd.fileno()
  109. if event & POLLIN:
  110. R.add(fd)
  111. if event & POLLOUT:
  112. W.add(fd)
  113. if event & POLLERR:
  114. R.add(fd)
  115. return R, W, 0
  116. else:
  117. def _select_imp(readers=None, writers=None, err=None, timeout=0):
  118. r, w, e = select.select(readers, writers, err, timeout)
  119. if e:
  120. r = list(set(r) | set(e))
  121. return r, w, 0
  122. def _select(readers=None, writers=None, err=None, timeout=0,
  123. poll=_select_imp):
  124. """Simple wrapper to :class:`~select.select`, using :`~select.poll`.
  125. Arguments:
  126. readers (Set[Fd]): Set of reader fds to test if readable.
  127. writers (Set[Fd]): Set of writer fds to test if writable.
  128. err (Set[Fd]): Set of fds to test for error condition.
  129. All fd sets passed must be mutable as this function
  130. will remove non-working fds from them, this also means
  131. the caller must make sure there are still fds in the sets
  132. before calling us again.
  133. Returns:
  134. Tuple[Set, Set, Set]: of ``(readable, writable, again)``, where
  135. ``readable`` is a set of fds that have data available for read,
  136. ``writable`` is a set of fds that's ready to be written to
  137. and ``again`` is a flag that if set means the caller must
  138. throw away the result and call us again.
  139. """
  140. readers = set() if readers is None else readers
  141. writers = set() if writers is None else writers
  142. err = set() if err is None else err
  143. try:
  144. return poll(readers, writers, err, timeout)
  145. except (select.error, socket.error) as exc:
  146. if exc.errno == errno.EINTR:
  147. return set(), set(), 1
  148. elif exc.errno in SELECT_BAD_FD:
  149. for fd in readers | writers | err:
  150. try:
  151. select.select([fd], [], [], 0)
  152. except (select.error, socket.error) as exc:
  153. if getattr(exc, 'errno', None) not in SELECT_BAD_FD:
  154. raise
  155. readers.discard(fd)
  156. writers.discard(fd)
  157. err.discard(fd)
  158. return set(), set(), 1
  159. else:
  160. raise
  161. class Worker(_pool.Worker):
  162. """Pool worker process."""
  163. def on_loop_start(self, pid):
  164. # our version sends a WORKER_UP message when the process is ready
  165. # to accept work, this will tell the parent that the inqueue fd
  166. # is writable.
  167. self.outq.put((WORKER_UP, (pid,)))
  168. class ResultHandler(_pool.ResultHandler):
  169. """Handles messages from the pool processes."""
  170. def __init__(self, *args, **kwargs):
  171. self.fileno_to_outq = kwargs.pop('fileno_to_outq')
  172. self.on_process_alive = kwargs.pop('on_process_alive')
  173. super(ResultHandler, self).__init__(*args, **kwargs)
  174. # add our custom message handler
  175. self.state_handlers[WORKER_UP] = self.on_process_alive
  176. def _recv_message(self, add_reader, fd, callback,
  177. __read__=__read__, readcanbuf=readcanbuf,
  178. BytesIO=BytesIO, unpack_from=unpack_from,
  179. load=_pickle.load):
  180. Hr = Br = 0
  181. if readcanbuf:
  182. buf = bytearray(4)
  183. bufv = memoryview(buf)
  184. else:
  185. buf = bufv = BytesIO()
  186. # header
  187. while Hr < 4:
  188. try:
  189. n = __read__(
  190. fd, bufv[Hr:] if readcanbuf else bufv, 4 - Hr,
  191. )
  192. except OSError as exc:
  193. if exc.errno not in UNAVAIL:
  194. raise
  195. yield
  196. else:
  197. if n == 0:
  198. raise (OSError('End of file during message') if Hr
  199. else EOFError())
  200. Hr += n
  201. body_size, = unpack_from(b'>i', bufv)
  202. if readcanbuf:
  203. buf = bytearray(body_size)
  204. bufv = memoryview(buf)
  205. else:
  206. buf = bufv = BytesIO()
  207. while Br < body_size:
  208. try:
  209. n = __read__(
  210. fd, bufv[Br:] if readcanbuf else bufv, body_size - Br,
  211. )
  212. except OSError as exc:
  213. if exc.errno not in UNAVAIL:
  214. raise
  215. yield
  216. else:
  217. if n == 0:
  218. raise (OSError('End of file during message') if Br
  219. else EOFError())
  220. Br += n
  221. add_reader(fd, self.handle_event, fd)
  222. if readcanbuf:
  223. message = load(BytesIO(bufv))
  224. else:
  225. bufv.seek(0)
  226. message = load(bufv)
  227. if message:
  228. callback(message)
  229. def _make_process_result(self, hub):
  230. """Coroutine reading messages from the pool processes."""
  231. fileno_to_outq = self.fileno_to_outq
  232. on_state_change = self.on_state_change
  233. add_reader = hub.add_reader
  234. remove_reader = hub.remove_reader
  235. recv_message = self._recv_message
  236. def on_result_readable(fileno):
  237. try:
  238. fileno_to_outq[fileno]
  239. except KeyError: # process gone
  240. return remove_reader(fileno)
  241. it = recv_message(add_reader, fileno, on_state_change)
  242. try:
  243. next(it)
  244. except StopIteration:
  245. pass
  246. except (IOError, OSError, EOFError):
  247. remove_reader(fileno)
  248. else:
  249. add_reader(fileno, it)
  250. return on_result_readable
  251. def register_with_event_loop(self, hub):
  252. self.handle_event = self._make_process_result(hub)
  253. def handle_event(self, *args):
  254. # pylint: disable=method-hidden
  255. # register_with_event_loop overrides this
  256. raise RuntimeError('Not registered with event loop')
  257. def on_stop_not_started(self):
  258. # This is always used, since we do not start any threads.
  259. cache = self.cache
  260. check_timeouts = self.check_timeouts
  261. fileno_to_outq = self.fileno_to_outq
  262. on_state_change = self.on_state_change
  263. join_exited_workers = self.join_exited_workers
  264. # flush the processes outqueues until they've all terminated.
  265. outqueues = set(fileno_to_outq)
  266. while cache and outqueues and self._state != TERMINATE:
  267. if check_timeouts is not None:
  268. # make sure tasks with a time limit will time out.
  269. check_timeouts()
  270. # cannot iterate and remove at the same time
  271. pending_remove_fd = set()
  272. for fd in outqueues:
  273. self._flush_outqueue(
  274. fd, pending_remove_fd.add, fileno_to_outq,
  275. on_state_change,
  276. )
  277. try:
  278. join_exited_workers(shutdown=True)
  279. except WorkersJoined:
  280. return debug('result handler: all workers terminated')
  281. outqueues.difference_update(pending_remove_fd)
  282. def _flush_outqueue(self, fd, remove, process_index, on_state_change):
  283. try:
  284. proc = process_index[fd]
  285. except KeyError:
  286. # process already found terminated
  287. # this means its outqueue has already been processed
  288. # by the worker lost handler.
  289. return remove(fd)
  290. reader = proc.outq._reader
  291. try:
  292. setblocking(reader, 1)
  293. except (OSError, IOError):
  294. return remove(fd)
  295. try:
  296. if reader.poll(0):
  297. task = reader.recv()
  298. else:
  299. task = None
  300. sleep(0.5)
  301. except (IOError, EOFError):
  302. return remove(fd)
  303. else:
  304. if task:
  305. on_state_change(task)
  306. finally:
  307. try:
  308. setblocking(reader, 0)
  309. except (OSError, IOError):
  310. return remove(fd)
  311. class AsynPool(_pool.Pool):
  312. """AsyncIO Pool (no threads)."""
  313. ResultHandler = ResultHandler
  314. Worker = Worker
  315. def WorkerProcess(self, worker):
  316. worker = super(AsynPool, self).WorkerProcess(worker)
  317. worker.dead = False
  318. return worker
  319. def __init__(self, processes=None, synack=False,
  320. sched_strategy=None, *args, **kwargs):
  321. self.sched_strategy = SCHED_STRATEGIES.get(sched_strategy,
  322. sched_strategy)
  323. processes = self.cpu_count() if processes is None else processes
  324. self.synack = synack
  325. # create queue-pairs for all our processes in advance.
  326. self._queues = {
  327. self.create_process_queues(): None for _ in range(processes)
  328. }
  329. # inqueue fileno -> process mapping
  330. self._fileno_to_inq = {}
  331. # outqueue fileno -> process mapping
  332. self._fileno_to_outq = {}
  333. # synqueue fileno -> process mapping
  334. self._fileno_to_synq = {}
  335. # We keep track of processes that haven't yet
  336. # sent a WORKER_UP message. If a process fails to send
  337. # this message within proc_up_timeout we terminate it
  338. # and hope the next process will recover.
  339. self._proc_alive_timeout = PROC_ALIVE_TIMEOUT
  340. self._waiting_to_start = set()
  341. # denormalized set of all inqueues.
  342. self._all_inqueues = set()
  343. # Set of fds being written to (busy)
  344. self._active_writes = set()
  345. # Set of active co-routines currently writing jobs.
  346. self._active_writers = set()
  347. # Set of fds that are busy (executing task)
  348. self._busy_workers = set()
  349. self._mark_worker_as_available = self._busy_workers.discard
  350. # Holds jobs waiting to be written to child processes.
  351. self.outbound_buffer = deque()
  352. self.write_stats = Counter()
  353. super(AsynPool, self).__init__(processes, *args, **kwargs)
  354. for proc in self._pool:
  355. # create initial mappings, these will be updated
  356. # as processes are recycled, or found lost elsewhere.
  357. self._fileno_to_outq[proc.outqR_fd] = proc
  358. self._fileno_to_synq[proc.synqW_fd] = proc
  359. self.on_soft_timeout = getattr(
  360. self._timeout_handler, 'on_soft_timeout', noop,
  361. )
  362. self.on_hard_timeout = getattr(
  363. self._timeout_handler, 'on_hard_timeout', noop,
  364. )
  365. def _create_worker_process(self, i):
  366. gc.collect() # Issue #2927
  367. return super(AsynPool, self)._create_worker_process(i)
  368. def _event_process_exit(self, hub, proc):
  369. # This method is called whenever the process sentinel is readable.
  370. self._untrack_child_process(proc, hub)
  371. self.maintain_pool()
  372. def _track_child_process(self, proc, hub):
  373. try:
  374. fd = proc._sentinel_poll
  375. except AttributeError:
  376. # we need to duplicate the fd here to carefully
  377. # control when the fd is removed from the process table,
  378. # as once the original fd is closed we cannot unregister
  379. # the fd from epoll(7) anymore, causing a 100% CPU poll loop.
  380. fd = proc._sentinel_poll = os.dup(proc._popen.sentinel)
  381. hub.add_reader(fd, self._event_process_exit, hub, proc)
  382. def _untrack_child_process(self, proc, hub):
  383. if proc._sentinel_poll is not None:
  384. fd, proc._sentinel_poll = proc._sentinel_poll, None
  385. hub.remove(fd)
  386. os.close(fd)
  387. def register_with_event_loop(self, hub):
  388. """Register the async pool with the current event loop."""
  389. self._result_handler.register_with_event_loop(hub)
  390. self.handle_result_event = self._result_handler.handle_event
  391. self._create_timelimit_handlers(hub)
  392. self._create_process_handlers(hub)
  393. self._create_write_handlers(hub)
  394. # Add handler for when a process exits (calls maintain_pool)
  395. [self._track_child_process(w, hub) for w in self._pool]
  396. # Handle_result_event is called whenever one of the
  397. # result queues are readable.
  398. [hub.add_reader(fd, self.handle_result_event, fd)
  399. for fd in self._fileno_to_outq]
  400. # Timers include calling maintain_pool at a regular interval
  401. # to be certain processes are restarted.
  402. for handler, interval in items(self.timers):
  403. hub.call_repeatedly(interval, handler)
  404. hub.on_tick.add(self.on_poll_start)
  405. def _create_timelimit_handlers(self, hub):
  406. """Create handlers used to implement time limits."""
  407. call_later = hub.call_later
  408. trefs = self._tref_for_id = WeakValueDictionary()
  409. def on_timeout_set(R, soft, hard):
  410. if soft:
  411. trefs[R._job] = call_later(
  412. soft, self._on_soft_timeout, R._job, soft, hard, hub,
  413. )
  414. elif hard:
  415. trefs[R._job] = call_later(
  416. hard, self._on_hard_timeout, R._job,
  417. )
  418. self.on_timeout_set = on_timeout_set
  419. def _discard_tref(job):
  420. try:
  421. tref = trefs.pop(job)
  422. tref.cancel()
  423. del tref
  424. except (KeyError, AttributeError):
  425. pass # out of scope
  426. self._discard_tref = _discard_tref
  427. def on_timeout_cancel(R):
  428. _discard_tref(R._job)
  429. self.on_timeout_cancel = on_timeout_cancel
  430. def _on_soft_timeout(self, job, soft, hard, hub):
  431. # only used by async pool.
  432. if hard:
  433. self._tref_for_id[job] = hub.call_later(
  434. hard - soft, self._on_hard_timeout, job,
  435. )
  436. try:
  437. result = self._cache[job]
  438. except KeyError:
  439. pass # job ready
  440. else:
  441. self.on_soft_timeout(result)
  442. finally:
  443. if not hard:
  444. # remove tref
  445. self._discard_tref(job)
  446. def _on_hard_timeout(self, job):
  447. # only used by async pool.
  448. try:
  449. result = self._cache[job]
  450. except KeyError:
  451. pass # job ready
  452. else:
  453. self.on_hard_timeout(result)
  454. finally:
  455. # remove tref
  456. self._discard_tref(job)
  457. def on_job_ready(self, job, i, obj, inqW_fd):
  458. self._mark_worker_as_available(inqW_fd)
  459. def _create_process_handlers(self, hub):
  460. """Create handlers called on process up/down, etc."""
  461. add_reader, remove_reader, remove_writer = (
  462. hub.add_reader, hub.remove_reader, hub.remove_writer,
  463. )
  464. cache = self._cache
  465. all_inqueues = self._all_inqueues
  466. fileno_to_inq = self._fileno_to_inq
  467. fileno_to_outq = self._fileno_to_outq
  468. fileno_to_synq = self._fileno_to_synq
  469. busy_workers = self._busy_workers
  470. handle_result_event = self.handle_result_event
  471. process_flush_queues = self.process_flush_queues
  472. waiting_to_start = self._waiting_to_start
  473. def verify_process_alive(proc):
  474. proc = proc() # is a weakref
  475. if (proc is not None and proc._is_alive() and
  476. proc in waiting_to_start):
  477. assert proc.outqR_fd in fileno_to_outq
  478. assert fileno_to_outq[proc.outqR_fd] is proc
  479. assert proc.outqR_fd in hub.readers
  480. error('Timed out waiting for UP message from %r', proc)
  481. os.kill(proc.pid, 9)
  482. def on_process_up(proc):
  483. """Called when a process has started."""
  484. # If we got the same fd as a previous process then we'll also
  485. # receive jobs in the old buffer, so we need to reset the
  486. # job._write_to and job._scheduled_for attributes used to recover
  487. # message boundaries when processes exit.
  488. infd = proc.inqW_fd
  489. for job in values(cache):
  490. if job._write_to and job._write_to.inqW_fd == infd:
  491. job._write_to = proc
  492. if job._scheduled_for and job._scheduled_for.inqW_fd == infd:
  493. job._scheduled_for = proc
  494. fileno_to_outq[proc.outqR_fd] = proc
  495. # maintain_pool is called whenever a process exits.
  496. self._track_child_process(proc, hub)
  497. assert not isblocking(proc.outq._reader)
  498. # handle_result_event is called when the processes outqueue is
  499. # readable.
  500. add_reader(proc.outqR_fd, handle_result_event, proc.outqR_fd)
  501. waiting_to_start.add(proc)
  502. hub.call_later(
  503. self._proc_alive_timeout, verify_process_alive, ref(proc),
  504. )
  505. self.on_process_up = on_process_up
  506. def _remove_from_index(obj, proc, index, remove_fun, callback=None):
  507. # this remove the file descriptors for a process from
  508. # the indices. we have to make sure we don't overwrite
  509. # another processes fds, as the fds may be reused.
  510. try:
  511. fd = obj.fileno()
  512. except (IOError, OSError):
  513. return
  514. try:
  515. if index[fd] is proc:
  516. # fd hasn't been reused so we can remove it from index.
  517. index.pop(fd, None)
  518. except KeyError:
  519. pass
  520. else:
  521. remove_fun(fd)
  522. if callback is not None:
  523. callback(fd)
  524. return fd
  525. def on_process_down(proc):
  526. """Called when a worker process exits."""
  527. if getattr(proc, 'dead', None):
  528. return
  529. process_flush_queues(proc)
  530. _remove_from_index(
  531. proc.outq._reader, proc, fileno_to_outq, remove_reader,
  532. )
  533. if proc.synq:
  534. _remove_from_index(
  535. proc.synq._writer, proc, fileno_to_synq, remove_writer,
  536. )
  537. inq = _remove_from_index(
  538. proc.inq._writer, proc, fileno_to_inq, remove_writer,
  539. callback=all_inqueues.discard,
  540. )
  541. if inq:
  542. busy_workers.discard(inq)
  543. self._untrack_child_process(proc, hub)
  544. waiting_to_start.discard(proc)
  545. self._active_writes.discard(proc.inqW_fd)
  546. remove_writer(proc.inq._writer)
  547. remove_reader(proc.outq._reader)
  548. if proc.synqR_fd:
  549. remove_reader(proc.synq._reader)
  550. if proc.synqW_fd:
  551. self._active_writes.discard(proc.synqW_fd)
  552. remove_reader(proc.synq._writer)
  553. self.on_process_down = on_process_down
  554. def _create_write_handlers(self, hub,
  555. pack=struct.pack, dumps=_pickle.dumps,
  556. protocol=HIGHEST_PROTOCOL):
  557. """Create handlers used to write data to child processes."""
  558. fileno_to_inq = self._fileno_to_inq
  559. fileno_to_synq = self._fileno_to_synq
  560. outbound = self.outbound_buffer
  561. pop_message = outbound.popleft
  562. put_message = outbound.append
  563. all_inqueues = self._all_inqueues
  564. active_writes = self._active_writes
  565. active_writers = self._active_writers
  566. busy_workers = self._busy_workers
  567. diff = all_inqueues.difference
  568. add_writer = hub.add_writer
  569. hub_add, hub_remove = hub.add, hub.remove
  570. mark_write_fd_as_active = active_writes.add
  571. mark_write_gen_as_active = active_writers.add
  572. mark_worker_as_busy = busy_workers.add
  573. write_generator_done = active_writers.discard
  574. get_job = self._cache.__getitem__
  575. write_stats = self.write_stats
  576. is_fair_strategy = self.sched_strategy == SCHED_STRATEGY_FAIR
  577. revoked_tasks = worker_state.revoked
  578. getpid = os.getpid
  579. precalc = {ACK: self._create_payload(ACK, (0,)),
  580. NACK: self._create_payload(NACK, (0,))}
  581. def _put_back(job, _time=time.time):
  582. # puts back at the end of the queue
  583. if job._terminated is not None or \
  584. job.correlation_id in revoked_tasks:
  585. if not job._accepted:
  586. job._ack(None, _time(), getpid(), None)
  587. job._set_terminated(job._terminated)
  588. else:
  589. # XXX linear lookup, should find a better way,
  590. # but this happens rarely and is here to protect against races.
  591. if job not in outbound:
  592. outbound.appendleft(job)
  593. self._put_back = _put_back
  594. # called for every event loop iteration, and if there
  595. # are messages pending this will schedule writing one message
  596. # by registering the 'schedule_writes' function for all currently
  597. # inactive inqueues (not already being written to)
  598. # consolidate means the event loop will merge them
  599. # and call the callback once with the list writable fds as
  600. # argument. Using this means we minimize the risk of having
  601. # the same fd receive every task if the pipe read buffer is not
  602. # full.
  603. if is_fair_strategy:
  604. def on_poll_start():
  605. if outbound and len(busy_workers) < len(all_inqueues):
  606. # print('ALL: %r ACTIVE: %r' % (len(all_inqueues),
  607. # len(active_writes)))
  608. inactive = diff(active_writes)
  609. [hub_add(fd, None, WRITE | ERR, consolidate=True)
  610. for fd in inactive]
  611. else:
  612. [hub_remove(fd) for fd in diff(active_writes)]
  613. else:
  614. def on_poll_start(): # noqa
  615. if outbound:
  616. [hub_add(fd, None, WRITE | ERR, consolidate=True)
  617. for fd in diff(active_writes)]
  618. else:
  619. [hub_remove(fd) for fd in diff(active_writes)]
  620. self.on_poll_start = on_poll_start
  621. def on_inqueue_close(fd, proc):
  622. # Makes sure the fd is removed from tracking when
  623. # the connection is closed, this is essential as fds may be reused.
  624. busy_workers.discard(fd)
  625. try:
  626. if fileno_to_inq[fd] is proc:
  627. fileno_to_inq.pop(fd, None)
  628. active_writes.discard(fd)
  629. all_inqueues.discard(fd)
  630. hub_remove(fd)
  631. except KeyError:
  632. pass
  633. self.on_inqueue_close = on_inqueue_close
  634. def schedule_writes(ready_fds, total_write_count=[0]):
  635. # Schedule write operation to ready file descriptor.
  636. # The file descriptor is writable, but that does not
  637. # mean the process is currently reading from the socket.
  638. # The socket is buffered so writable simply means that
  639. # the buffer can accept at least 1 byte of data.
  640. # This means we have to cycle between the ready fds.
  641. # the first version used shuffle, but this version
  642. # using `total_writes % ready_fds` is about 30% faster
  643. # with many processes, and also leans more towards fairness
  644. # in write stats when used with many processes
  645. # [XXX On macOS, this may vary depending
  646. # on event loop implementation (i.e, select/poll vs epoll), so
  647. # have to test further]
  648. num_ready = len(ready_fds)
  649. for _ in range(num_ready):
  650. ready_fd = ready_fds[total_write_count[0] % num_ready]
  651. total_write_count[0] += 1
  652. if ready_fd in active_writes:
  653. # already writing to this fd
  654. continue
  655. if is_fair_strategy and ready_fd in busy_workers:
  656. # worker is already busy with another task
  657. continue
  658. if ready_fd not in all_inqueues:
  659. hub_remove(ready_fd)
  660. continue
  661. try:
  662. job = pop_message()
  663. except IndexError:
  664. # no more messages, remove all inactive fds from the hub.
  665. # this is important since the fds are always writable
  666. # as long as there's 1 byte left in the buffer, and so
  667. # this may create a spinloop where the event loop
  668. # always wakes up.
  669. for inqfd in diff(active_writes):
  670. hub_remove(inqfd)
  671. break
  672. else:
  673. if not job._accepted: # job not accepted by another worker
  674. try:
  675. # keep track of what process the write operation
  676. # was scheduled for.
  677. proc = job._scheduled_for = fileno_to_inq[ready_fd]
  678. except KeyError:
  679. # write was scheduled for this fd but the process
  680. # has since exited and the message must be sent to
  681. # another process.
  682. put_message(job)
  683. continue
  684. cor = _write_job(proc, ready_fd, job)
  685. job._writer = ref(cor)
  686. mark_write_gen_as_active(cor)
  687. mark_write_fd_as_active(ready_fd)
  688. mark_worker_as_busy(ready_fd)
  689. # Try to write immediately, in case there's an error.
  690. try:
  691. next(cor)
  692. except StopIteration:
  693. pass
  694. except OSError as exc:
  695. if exc.errno != errno.EBADF:
  696. raise
  697. else:
  698. add_writer(ready_fd, cor)
  699. hub.consolidate_callback = schedule_writes
  700. def send_job(tup):
  701. # Schedule writing job request for when one of the process
  702. # inqueues are writable.
  703. body = dumps(tup, protocol=protocol)
  704. body_size = len(body)
  705. header = pack(b'>I', body_size)
  706. # index 1,0 is the job ID.
  707. job = get_job(tup[1][0])
  708. job._payload = buf_t(header), buf_t(body), body_size
  709. put_message(job)
  710. self._quick_put = send_job
  711. def on_not_recovering(proc, fd, job, exc):
  712. logger.exception(
  713. 'Process inqueue damaged: %r %r: %r', proc, proc.exitcode, exc)
  714. if proc._is_alive():
  715. proc.terminate()
  716. hub.remove(fd)
  717. self._put_back(job)
  718. def _write_job(proc, fd, job):
  719. # writes job to the worker process.
  720. # Operation must complete if more than one byte of data
  721. # was written. If the broker connection is lost
  722. # and no data was written the operation shall be canceled.
  723. header, body, body_size = job._payload
  724. errors = 0
  725. try:
  726. # job result keeps track of what process the job is sent to.
  727. job._write_to = proc
  728. send = proc.send_job_offset
  729. Hw = Bw = 0
  730. # write header
  731. while Hw < 4:
  732. try:
  733. Hw += send(header, Hw)
  734. except Exception as exc: # pylint: disable=broad-except
  735. if getattr(exc, 'errno', None) not in UNAVAIL:
  736. raise
  737. # suspend until more data
  738. errors += 1
  739. if errors > 100:
  740. on_not_recovering(proc, fd, job, exc)
  741. raise StopIteration()
  742. yield
  743. else:
  744. errors = 0
  745. # write body
  746. while Bw < body_size:
  747. try:
  748. Bw += send(body, Bw)
  749. except Exception as exc: # pylint: disable=broad-except
  750. if getattr(exc, 'errno', None) not in UNAVAIL:
  751. raise
  752. # suspend until more data
  753. errors += 1
  754. if errors > 100:
  755. on_not_recovering(proc, fd, job, exc)
  756. raise StopIteration()
  757. yield
  758. else:
  759. errors = 0
  760. finally:
  761. hub_remove(fd)
  762. write_stats[proc.index] += 1
  763. # message written, so this fd is now available
  764. active_writes.discard(fd)
  765. write_generator_done(job._writer()) # is a weakref
  766. def send_ack(response, pid, job, fd):
  767. # Only used when synack is enabled.
  768. # Schedule writing ack response for when the fd is writable.
  769. msg = Ack(job, fd, precalc[response])
  770. callback = promise(write_generator_done)
  771. cor = _write_ack(fd, msg, callback=callback)
  772. mark_write_gen_as_active(cor)
  773. mark_write_fd_as_active(fd)
  774. callback.args = (cor,)
  775. add_writer(fd, cor)
  776. self.send_ack = send_ack
  777. def _write_ack(fd, ack, callback=None):
  778. # writes ack back to the worker if synack enabled.
  779. # this operation *MUST* complete, otherwise
  780. # the worker process will hang waiting for the ack.
  781. header, body, body_size = ack[2]
  782. try:
  783. try:
  784. proc = fileno_to_synq[fd]
  785. except KeyError:
  786. # process died, we can safely discard the ack at this
  787. # point.
  788. raise StopIteration()
  789. send = proc.send_syn_offset
  790. Hw = Bw = 0
  791. # write header
  792. while Hw < 4:
  793. try:
  794. Hw += send(header, Hw)
  795. except Exception as exc: # pylint: disable=broad-except
  796. if getattr(exc, 'errno', None) not in UNAVAIL:
  797. raise
  798. yield
  799. # write body
  800. while Bw < body_size:
  801. try:
  802. Bw += send(body, Bw)
  803. except Exception as exc: # pylint: disable=broad-except
  804. if getattr(exc, 'errno', None) not in UNAVAIL:
  805. raise
  806. # suspend until more data
  807. yield
  808. finally:
  809. if callback:
  810. callback()
  811. # message written, so this fd is now available
  812. active_writes.discard(fd)
  813. def flush(self):
  814. if self._state == TERMINATE:
  815. return
  816. # cancel all tasks that haven't been accepted so that NACK is sent.
  817. for job in values(self._cache):
  818. if not job._accepted:
  819. job._cancel()
  820. # clear the outgoing buffer as the tasks will be redelivered by
  821. # the broker anyway.
  822. if self.outbound_buffer:
  823. self.outbound_buffer.clear()
  824. self.maintain_pool()
  825. try:
  826. # ...but we must continue writing the payloads we already started
  827. # to keep message boundaries.
  828. # The messages may be NACK'ed later if synack is enabled.
  829. if self._state == RUN:
  830. # flush outgoing buffers
  831. intervals = fxrange(0.01, 0.1, 0.01, repeatlast=True)
  832. owned_by = {}
  833. for job in values(self._cache):
  834. writer = _get_job_writer(job)
  835. if writer is not None:
  836. owned_by[writer] = job
  837. while self._active_writers:
  838. writers = list(self._active_writers)
  839. for gen in writers:
  840. if (gen.__name__ == '_write_job' and
  841. gen_not_started(gen)):
  842. # hasn't started writing the job so can
  843. # discard the task, but we must also remove
  844. # it from the Pool._cache.
  845. try:
  846. job = owned_by[gen]
  847. except KeyError:
  848. pass
  849. else:
  850. # removes from Pool._cache
  851. job.discard()
  852. self._active_writers.discard(gen)
  853. else:
  854. try:
  855. job = owned_by[gen]
  856. except KeyError:
  857. pass
  858. else:
  859. job_proc = job._write_to
  860. if job_proc._is_alive():
  861. self._flush_writer(job_proc, gen)
  862. # workers may have exited in the meantime.
  863. self.maintain_pool()
  864. sleep(next(intervals)) # don't busyloop
  865. finally:
  866. self.outbound_buffer.clear()
  867. self._active_writers.clear()
  868. self._active_writes.clear()
  869. self._busy_workers.clear()
  870. def _flush_writer(self, proc, writer):
  871. fds = {proc.inq._writer}
  872. try:
  873. while fds:
  874. if not proc._is_alive():
  875. break # process exited
  876. readable, writable, again = _select(
  877. writers=fds, err=fds, timeout=0.5,
  878. )
  879. if not again and (writable or readable):
  880. try:
  881. next(writer)
  882. except (StopIteration, OSError, IOError, EOFError):
  883. break
  884. finally:
  885. self._active_writers.discard(writer)
  886. def get_process_queues(self):
  887. """Get queues for a new process.
  888. Here we'll find an unused slot, as there should always
  889. be one available when we start a new process.
  890. """
  891. return next(q for q, owner in items(self._queues)
  892. if owner is None)
  893. def on_grow(self, n):
  894. """Grow the pool by ``n`` proceses."""
  895. diff = max(self._processes - len(self._queues), 0)
  896. if diff:
  897. self._queues.update({
  898. self.create_process_queues(): None for _ in range(diff)
  899. })
  900. def on_shrink(self, n):
  901. """Shrink the pool by ``n`` processes."""
  902. pass
  903. def create_process_queues(self):
  904. """Create new in, out, etc. queues, returned as a tuple."""
  905. # NOTE: Pipes must be set O_NONBLOCK at creation time (the original
  906. # fd), otherwise it won't be possible to change the flags until
  907. # there's an actual reader/writer on the other side.
  908. inq = _SimpleQueue(wnonblock=True)
  909. outq = _SimpleQueue(rnonblock=True)
  910. synq = None
  911. assert isblocking(inq._reader)
  912. assert not isblocking(inq._writer)
  913. assert not isblocking(outq._reader)
  914. assert isblocking(outq._writer)
  915. if self.synack:
  916. synq = _SimpleQueue(wnonblock=True)
  917. assert isblocking(synq._reader)
  918. assert not isblocking(synq._writer)
  919. return inq, outq, synq
  920. def on_process_alive(self, pid):
  921. """Called when reciving the :const:`WORKER_UP` message.
  922. Marks the process as ready to receive work.
  923. """
  924. try:
  925. proc = next(w for w in self._pool if w.pid == pid)
  926. except StopIteration:
  927. return logger.warning('process with pid=%s already exited', pid)
  928. assert proc.inqW_fd not in self._fileno_to_inq
  929. assert proc.inqW_fd not in self._all_inqueues
  930. self._waiting_to_start.discard(proc)
  931. self._fileno_to_inq[proc.inqW_fd] = proc
  932. self._fileno_to_synq[proc.synqW_fd] = proc
  933. self._all_inqueues.add(proc.inqW_fd)
  934. def on_job_process_down(self, job, pid_gone):
  935. """Called for each job when the process assigned to it exits."""
  936. if job._write_to and not job._write_to._is_alive():
  937. # job was partially written
  938. self.on_partial_read(job, job._write_to)
  939. elif job._scheduled_for and not job._scheduled_for._is_alive():
  940. # job was only scheduled to be written to this process,
  941. # but no data was sent so put it back on the outbound_buffer.
  942. self._put_back(job)
  943. def on_job_process_lost(self, job, pid, exitcode):
  944. """Called when the process executing job' exits.
  945. This happens when the process job'
  946. was assigned to exited by mysterious means (error exitcodes and
  947. signals).
  948. """
  949. self.mark_as_worker_lost(job, exitcode)
  950. def human_write_stats(self):
  951. if self.write_stats is None:
  952. return 'N/A'
  953. vals = list(values(self.write_stats))
  954. total = sum(vals)
  955. def per(v, total):
  956. return '{0:.2%}'.format((float(v) / total) if v else 0)
  957. return {
  958. 'total': total,
  959. 'avg': per(total / len(self.write_stats) if total else 0, total),
  960. 'all': ', '.join(per(v, total) for v in vals),
  961. 'raw': ', '.join(map(str, vals)),
  962. 'strategy': SCHED_STRATEGY_TO_NAME.get(
  963. self.sched_strategy, self.sched_strategy,
  964. ),
  965. 'inqueues': {
  966. 'total': len(self._all_inqueues),
  967. 'active': len(self._active_writes),
  968. }
  969. }
  970. def _process_cleanup_queues(self, proc):
  971. """Called to clean up queues after process exit."""
  972. if not proc.dead:
  973. try:
  974. self._queues[self._find_worker_queues(proc)] = None
  975. except (KeyError, ValueError):
  976. pass
  977. @staticmethod
  978. def _stop_task_handler(task_handler):
  979. """Called at shutdown to tell processes that we're shutting down."""
  980. for proc in task_handler.pool:
  981. try:
  982. setblocking(proc.inq._writer, 1)
  983. except (OSError, IOError):
  984. pass
  985. else:
  986. try:
  987. proc.inq.put(None)
  988. except OSError as exc:
  989. if exc.errno != errno.EBADF:
  990. raise
  991. def create_result_handler(self):
  992. return super(AsynPool, self).create_result_handler(
  993. fileno_to_outq=self._fileno_to_outq,
  994. on_process_alive=self.on_process_alive,
  995. )
  996. def _process_register_queues(self, proc, queues):
  997. """Mark new ownership for ``queues`` to update fileno indices."""
  998. assert queues in self._queues
  999. b = len(self._queues)
  1000. self._queues[queues] = proc
  1001. assert b == len(self._queues)
  1002. def _find_worker_queues(self, proc):
  1003. """Find the queues owned by ``proc``."""
  1004. try:
  1005. return next(q for q, owner in items(self._queues)
  1006. if owner == proc)
  1007. except StopIteration:
  1008. raise ValueError(proc)
  1009. def _setup_queues(self):
  1010. # this is only used by the original pool that used a shared
  1011. # queue for all processes.
  1012. self._quick_put = None
  1013. # these attributes are unused by this class, but we'll still
  1014. # have to initialize them for compatibility.
  1015. self._inqueue = self._outqueue = \
  1016. self._quick_get = self._poll_result = None
  1017. def process_flush_queues(self, proc):
  1018. """Flush all queues.
  1019. Including the outbound buffer, so that
  1020. all tasks that haven't been started will be discarded.
  1021. In Celery this is called whenever the transport connection is lost
  1022. (consumer restart), and when a process is terminated.
  1023. """
  1024. resq = proc.outq._reader
  1025. on_state_change = self._result_handler.on_state_change
  1026. fds = {resq}
  1027. while fds and not resq.closed and self._state != TERMINATE:
  1028. readable, _, _ = _select(fds, None, fds, timeout=0.01)
  1029. if readable:
  1030. try:
  1031. task = resq.recv()
  1032. except (OSError, IOError, EOFError) as exc:
  1033. _errno = getattr(exc, 'errno', None)
  1034. if _errno == errno.EINTR:
  1035. continue
  1036. elif _errno == errno.EAGAIN:
  1037. break
  1038. elif _errno not in UNAVAIL:
  1039. debug('got %r while flushing process %r',
  1040. exc, proc, exc_info=1)
  1041. break
  1042. else:
  1043. if task is None:
  1044. debug('got sentinel while flushing process %r', proc)
  1045. break
  1046. else:
  1047. on_state_change(task)
  1048. else:
  1049. break
  1050. def on_partial_read(self, job, proc):
  1051. """Called when a job was partially written to exited child."""
  1052. # worker terminated by signal:
  1053. # we cannot reuse the sockets again, because we don't know if
  1054. # the process wrote/read anything frmo them, and if so we cannot
  1055. # restore the message boundaries.
  1056. if not job._accepted:
  1057. # job was not acked, so find another worker to send it to.
  1058. self._put_back(job)
  1059. writer = _get_job_writer(job)
  1060. if writer:
  1061. self._active_writers.discard(writer)
  1062. del writer
  1063. if not proc.dead:
  1064. proc.dead = True
  1065. # Replace queues to avoid reuse
  1066. before = len(self._queues)
  1067. try:
  1068. queues = self._find_worker_queues(proc)
  1069. if self.destroy_queues(queues, proc):
  1070. self._queues[self.create_process_queues()] = None
  1071. except ValueError:
  1072. pass
  1073. assert len(self._queues) == before
  1074. def destroy_queues(self, queues, proc):
  1075. """Destroy queues that can no longer be used.
  1076. This way they can be replaced by new usable sockets.
  1077. """
  1078. assert not proc._is_alive()
  1079. self._waiting_to_start.discard(proc)
  1080. removed = 1
  1081. try:
  1082. self._queues.pop(queues)
  1083. except KeyError:
  1084. removed = 0
  1085. try:
  1086. self.on_inqueue_close(queues[0]._writer.fileno(), proc)
  1087. except IOError:
  1088. pass
  1089. for queue in queues:
  1090. if queue:
  1091. for sock in (queue._reader, queue._writer):
  1092. if not sock.closed:
  1093. try:
  1094. sock.close()
  1095. except (IOError, OSError):
  1096. pass
  1097. return removed
  1098. def _create_payload(self, type_, args,
  1099. dumps=_pickle.dumps, pack=struct.pack,
  1100. protocol=HIGHEST_PROTOCOL):
  1101. body = dumps((type_, args), protocol=protocol)
  1102. size = len(body)
  1103. header = pack(b'>I', size)
  1104. return header, body, size
  1105. @classmethod
  1106. def _set_result_sentinel(cls, _outqueue, _pool):
  1107. # unused
  1108. pass
  1109. def _help_stuff_finish_args(self):
  1110. # Pool._help_stuff_finished is a classmethod so we have to use this
  1111. # trick to modify the arguments passed to it.
  1112. return (self._pool,)
  1113. @classmethod
  1114. def _help_stuff_finish(cls, pool):
  1115. # pylint: disable=arguments-differ
  1116. debug(
  1117. 'removing tasks from inqueue until task handler finished',
  1118. )
  1119. fileno_to_proc = {}
  1120. inqR = set()
  1121. for w in pool:
  1122. try:
  1123. fd = w.inq._reader.fileno()
  1124. inqR.add(fd)
  1125. fileno_to_proc[fd] = w
  1126. except IOError:
  1127. pass
  1128. while inqR:
  1129. readable, _, again = _select(inqR, timeout=0.5)
  1130. if again:
  1131. continue
  1132. if not readable:
  1133. break
  1134. for fd in readable:
  1135. fileno_to_proc[fd].inq._reader.recv()
  1136. sleep(0)
  1137. @property
  1138. def timers(self):
  1139. return {self.maintain_pool: 5.0}