Browse Source

Merge branch 'using_execv'

Conflicts:
	celery/bin/celeryd.py
Ask Solem 13 years ago
parent
commit
7ceef761d5

+ 1 - 0
celery/app/defaults.py

@@ -156,6 +156,7 @@ NAMESPACES = {
         "CONCURRENCY": Option(0, type="int"),
         "ETA_SCHEDULER": Option(None, type="string"),
         "ETA_SCHEDULER_PRECISION": Option(1.0, type="float"),
+        "FORCE_EXECV": Option(False, type="bool"),
         "HIJACK_ROOT_LOGGER": Option(True, type="bool"),
         "CONSUMER": Option("celery.worker.consumer.Consumer"),
         "LOG_FORMAT": Option(DEFAULT_PROCESS_LOG_FMT),

+ 3 - 7
celery/apps/worker.py

@@ -166,13 +166,9 @@ class Worker(configurated):
             self.loader.import_from_cwd(module)
 
     def redirect_stdouts_to_logger(self):
-        handled = self.app.log.setup_logging_subsystem(loglevel=self.loglevel,
-                                                       logfile=self.logfile)
-        if not handled:
-            logger = self.app.log.get_default_logger()
-            if self.redirect_stdouts:
-                self.app.log.redirect_stdouts_to_logger(logger,
-                                loglevel=self.redirect_stdouts_level)
+        self.app.log.setup(self.loglevel, self.logfile,
+                           self.redirect_stdouts,
+                           self.redirect_stdouts_level)
 
     def purge_messages(self):
         count = self.app.control.discard_all()

+ 2 - 1
celery/bin/celeryd.py

@@ -76,10 +76,11 @@ from __future__ import absolute_import
 if __name__ == "__main__" and __package__ is None:
     __package__ = "celery.bin.celeryd"
 
+import os
 import sys
 
 try:
-    from multiprocessing import freeze_support
+    from celery.concurrency.processes.forking import freeze_support
 except ImportError:  # pragma: no cover
     freeze_support = lambda: True  # noqa
 

+ 5 - 0
celery/concurrency/processes/__init__.py

@@ -1,6 +1,7 @@
 # -*- coding: utf-8 -*-
 from __future__ import absolute_import
 
+import os
 import platform
 import signal as _signal
 
@@ -40,6 +41,10 @@ def process_initializer(app, hostname):
     # This is for Windows and other platforms not supporting
     # fork(). Note that init_worker makes sure it's only
     # run once per process.
+    app.log.setup(int(os.environ.get("CELERY_LOG_LEVEL", 0)),
+                  os.environ.get("CELERY_LOG_FILE") or None,
+                  bool(os.environ.get("CELERY_LOG_REDIRECT", False)),
+                  str(os.environ.get("CELERY_LOG_REDIRECT_LEVEL")))
     app.loader.init_worker()
     app.loader.init_worker_process()
     signals.worker_process_init.send(sender=None)

+ 187 - 0
celery/concurrency/processes/forking.py

@@ -0,0 +1,187 @@
+#
+# Module for starting a process object using os.fork() or CreateProcess()
+#
+# multiprocessing/forking.py
+#
+# Copyright (c) 2006-2008, R Oudkerk
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+#    notice, this list of conditions and the following disclaimer.
+# 2. Redistributions in binary form must reproduce the above copyright
+#    notice, this list of conditions and the following disclaimer in the
+#    documentation and/or other materials provided with the distribution.
+# 3. Neither the name of author nor the names of any contributors may be
+#    used to endorse or promote products derived from this software
+#    without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+#
+
+from __future__ import absolute_import
+
+import os
+import sys
+
+from multiprocessing import current_process
+from multiprocessing import forking as _forking
+from multiprocessing import process
+from pickle import load, dump as _dump, HIGHEST_PROTOCOL
+
+Popen = _forking.Popen
+
+
+def dump(obj, file, protocol=None):
+    _forking.ForkingPickler(file, protocol).dump(obj)
+
+
+if sys.platform != "win32":
+    import threading
+
+    class Popen(_forking.Popen):  # noqa
+        _tls = threading.local()
+        returncode = None
+
+        def __init__(self, process_obj):
+            self.force_execv = process_obj.force_execv
+
+            if self.force_execv:
+                sys.stdout.flush()
+                sys.stderr.flush()
+                r, w = os.pipe()
+                self.sentinel = r
+
+                from_parent_fd, to_child_fd = os.pipe()
+                cmd = get_command_line() + [str(from_parent_fd)]
+
+                self.pid = os.fork()
+                if self.pid == 0:
+                    os.close(r)
+                    os.close(to_child_fd)
+                    os.execv(sys.executable, cmd)
+
+                # send information to child
+                prep_data = get_preparation_data(process_obj._name)
+                os.close(from_parent_fd)
+                to_child = os.fdopen(to_child_fd, 'wb')
+                Popen._tls.process_handle = self.pid
+                try:
+                    dump(prep_data, to_child, HIGHEST_PROTOCOL)
+                    dump(process_obj, to_child, HIGHEST_PROTOCOL)
+                finally:
+                    del(Popen._tls.process_handle)
+                    to_child.close()
+            else:
+                super(Popen, self).__init__(process_obj)
+
+        @staticmethod
+        def thread_is_spawning():
+            return getattr(Popen._tls, "process_handle", None) is not None
+
+        @staticmethod
+        def duplicate_for_child(handle):
+            return handle
+
+    def is_forking(argv):
+        if len(argv) >= 2 and argv[1] == '--multiprocessing-fork':
+            assert len(argv) == 3
+            return True
+        return False
+
+    def freeze_support():
+        if is_forking(sys.argv):
+            main()
+            sys.exit()
+
+    def get_command_line():
+        if current_process()._identity == () and is_forking(sys.argv):
+            raise RuntimeError(
+                "Can't start new process while bootstrapping another")
+        if getattr(sys, "frozen", False):
+            return [sys.executable, '--multiprocessing-fork']
+        else:
+            prog = """\
+from celery.concurrency.processes.forking import main; main()"""
+            return [sys.executable, '-c', prog, '--multiprocessing-fork']
+
+    def main():
+        assert is_forking(sys.argv)
+        fd = int(sys.argv[-1])
+        from_parent = os.fdopen(fd, 'rb')
+        current_process()._inheriting = True
+        preparation_data = load(from_parent)
+        _forking.prepare(preparation_data)
+
+        # Huge hack to make logging before Process.run work.
+        loglevel = os.environ.get("_MP_FORK_LOGLEVEL_")
+        logfile = os.environ.get("_MP_FORK_LOGFILE_") or None
+        format = os.environ.get("_MP_FORK_LOGFORMAT_")
+        if loglevel:
+            from multiprocessing import util
+            import logging
+            logger = util.get_logger()
+            logger.setLevel(int(loglevel))
+            if not logger.handlers:
+                logger._rudimentary_setup = True
+                logfile = logfile or sys.__stderr__
+                if hasattr(logfile, "write"):
+                    handler = logging.StreamHandler(logfile)
+                else:
+                    handler = logging.FileHandler(logfile)
+                formatter = logging.Formatter(
+                        format or util.DEFAULT_LOGGING_FORMAT)
+                handler.setFormatter(formatter)
+                logger.addHandler(handler)
+
+        self = load(from_parent)
+        current_process()._inheriting = False
+
+        exitcode = self._bootstrap()
+        exit(exitcode)
+
+    def get_preparation_data(name):
+        from multiprocessing.util import _logger, _log_to_stderr
+        d = dict(name=name,
+                 sys_path=sys.path,
+                 sys_argv=sys.argv,
+                 log_to_stderr=_log_to_stderr,
+                 orig_dir=process.ORIGINAL_DIR,
+                 authkey=process.current_process().authkey)
+        if _logger is not None:
+            d["log_level"] = _logger.getEffectiveLevel()
+        main_path = getattr(sys.modules['__main__'], '__file__', None)
+        if not main_path and sys.argv[0] not in ('', '-c'):
+            main_path = sys.argv[0]
+        if main_path is not None:
+            if not os.path.isabs(main_path) \
+                    and process.ORIGINAL_DIR is not None:
+                main_path = os.path.join(process.ORIGINAL_DIR, main_path)
+            d["main_path"] = os.path.normpath(main_path)
+        return d
+
+    from _multiprocessing import Connection
+
+    def reduce_connection(conn):
+        if not Popen.thread_is_spawning():
+            raise RuntimeError("blabla")
+        return type(conn), (Popen.duplicate_for_child(conn.fileno()),
+                            conn.readable, conn.writable)
+    _forking.ForkingPickler.register(Connection, reduce_connection)
+
+    _forking.Popen = Popen
+else:
+    from multiprocessing.forking import freeze_support

+ 7 - 2
celery/concurrency/processes/pool.py

@@ -24,7 +24,7 @@ import time
 import Queue
 import warnings
 
-from multiprocessing import Process, cpu_count, TimeoutError, Event
+from multiprocessing import cpu_count, TimeoutError, Event
 from multiprocessing import util
 from multiprocessing.util import Finalize, debug
 
@@ -32,6 +32,8 @@ from celery.datastructures import ExceptionInfo
 from celery.exceptions import SoftTimeLimitExceeded, TimeLimitExceeded
 from celery.exceptions import WorkerLostError
 
+from .process import Process
+
 _Semaphore = threading._Semaphore
 
 #
@@ -530,7 +532,8 @@ class Pool(object):
     SoftTimeLimitExceeded = SoftTimeLimitExceeded
 
     def __init__(self, processes=None, initializer=None, initargs=(),
-            maxtasksperchild=None, timeout=None, soft_timeout=None):
+            maxtasksperchild=None, timeout=None, soft_timeout=None,
+            force_execv=False):
         self._setup_queues()
         self._taskqueue = Queue.Queue()
         self._cache = {}
@@ -540,6 +543,7 @@ class Pool(object):
         self._maxtasksperchild = maxtasksperchild
         self._initializer = initializer
         self._initargs = initargs
+        self._force_execv = force_execv
 
         if soft_timeout and SIG_SOFT_TIMEOUT is None:
             warnings.warn(UserWarning("Soft timeouts are not supported: "
@@ -597,6 +601,7 @@ class Pool(object):
     def _create_worker_process(self):
         sentinel = Event()
         w = self.Process(
+            force_execv=self._force_execv,
             target=worker,
             args=(self._inqueue, self._outqueue,
                     self._initializer, self._initargs,

+ 11 - 0
celery/concurrency/processes/process.py

@@ -0,0 +1,11 @@
+from multiprocessing.process import Process as _Process
+
+from .forking import Popen
+
+
+class Process(_Process):
+    _Popen = Popen
+
+    def __init__(self, *args, **kwargs):
+        self.force_execv = kwargs.pop("force_execv", False)
+        super(Process, self).__init__(*args, **kwargs)

+ 27 - 2
celery/log.py

@@ -3,6 +3,7 @@ from __future__ import absolute_import
 
 import logging
 import threading
+import os
 import sys
 import traceback
 
@@ -130,10 +131,31 @@ class Logging(object):
                 signals.after_setup_logger.send(sender=None, logger=logger,
                                         loglevel=loglevel, logfile=logfile,
                                         format=format, colorize=colorize)
+
+        # This is a hack for multiprocessing's fork+exec, so that
+        # logging before Process.run works.
+        os.environ.update(_MP_FORK_LOGLEVEL_=str(loglevel),
+                          _MP_FORK_LOGFILE_=logfile or "",
+                          _MP_FORK_LOGFORMAT_=format)
         Logging._setup = True
 
         return receivers
 
+    def setup(self, loglevel=None, logfile=None, redirect_stdouts=False,
+            redirect_level="WARNING"):
+        handled = self.setup_logging_subsystem(loglevel=loglevel,
+                                               logfile=logfile)
+        if not handled:
+            logger = self.get_default_logger()
+            if redirect_stdouts:
+                self.redirect_stdouts_to_logger(logger,
+                                loglevel=redirect_level)
+        os.environ.update(
+            CELERY_LOG_LEVEL=str(loglevel) if loglevel else "",
+            CELERY_LOG_FILE=str(logfile) if logfile else "",
+            CELERY_LOG_REDIRECT="1" if redirect_stdouts else "",
+            CELERY_LOG_REDIRECT_LEVEL=str(redirect_level))
+
     def _detect_handler(self, logfile=None):
         """Create log handler with either a filename, an open stream
         or :const:`None` (stderr)."""
@@ -216,10 +238,13 @@ class Logging(object):
             sys.stderr = proxy
         return proxy
 
+    def _is_configured(self, logger):
+        return logger.handlers and not getattr(
+                logger, "_rudimentary_setup", False)
+
     def _setup_logger(self, logger, logfile, format, colorize,
             formatter=ColorFormatter, **kwargs):
-
-        if logger.handlers:  # Logger already configured
+        if self._is_configured(logger):
             return logger
 
         handler = self._detect_handler(logfile)

+ 3 - 1
celery/worker/__init__.py

@@ -90,7 +90,8 @@ class Pool(abstract.StartStopComponent):
                                 maxtasksperchild=w.max_tasks_per_child,
                                 timeout=w.task_time_limit,
                                 soft_timeout=w.task_soft_time_limit,
-                                putlocks=w.pool_putlocks)
+                                putlocks=w.pool_putlocks,
+                                force_execv=w.force_execv)
         return pool
 
 
@@ -186,6 +187,7 @@ class WorkController(configurated):
     task_soft_time_limit = from_config()
     max_tasks_per_child = from_config()
     pool_putlocks = from_config()
+    force_execv = from_config()
     prefetch_multiplier = from_config()
     state_db = from_config()
     disable_rate_limits = from_config()

+ 18 - 0
docs/configuration.rst

@@ -966,6 +966,24 @@ A sequence of modules to import when the celery daemon starts.
 This is used to specify the task modules to import, but also
 to import signal handlers and additional remote control commands, etc.
 
+.. setting:: CELERYD_FORCE_EXECV
+
+CELERYD_FORCE_EXECV
+~~~~~~~~~~~~~~~~~~~
+
+On Unix the processes pool will fork, so that child processes
+start with the same memory as the parent process.
+
+This can cause problems as there is a known deadlock condition
+with pthread locking primitives when `fork()` is combined with threads.
+
+You should enable this setting if you are experiencing hangs (deadlocks),
+especially in combination with time limits or having a max tasks per child limit.
+
+This option will be enabled by default in a later version.
+
+This is not a problem on Windows, as it does not have `fork()`.
+
 .. setting:: CELERYD_MAX_TASKS_PER_CHILD
 
 CELERYD_MAX_TASKS_PER_CHILD