asynpool.py 44 KB

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