asynpool.py 47 KB

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