PageRenderTime 27ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/venv/lib/python2.7/site-packages/celery/concurrency/asynpool.py

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