asynpool.py 45 KB

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