asynpool.py 46 KB

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