rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
self._commandLineHandler.setLevel(logging.DEBUG)
if self._debugMode == True: self._commandLineHandler.setLevel(logging.DEBUG) else: self._commandLineHandler.setLevel(logging.INFO)
def __init__(self, debugMode): self._debugMode = debugMode
elif self._debugMode == False:
else:
def getLogger(self, name, level): logger = logging.getLogger(name) if level == "debug": if self._debugMode == True: logger.setLevel(logging.DEBUG) elif self._debugMode == False: logger.setLevel(logging.INFO) else: self._logger.error(str(self.debugMode)\ +" is an invalid debug mode.") raise ValueError(str(self.debugMode...
else: self._logger.error(str(self.debugMode)\ +" is an invalid debug mode.") raise ValueError(str(self.debugMode)\ +" is an invalid debug mode.")
def getLogger(self, name, level): logger = logging.getLogger(name) if level == "debug": if self._debugMode == True: logger.setLevel(logging.DEBUG) elif self._debugMode == False: logger.setLevel(logging.INFO) else: self._logger.error(str(self.debugMode)\ +" is an invalid debug mode.") raise ValueError(str(self.debugMode...
if value.trace != None: self._logger.critical("Uncaught exception:\n\nTraceback (most "\ +"recent call last):\n"+"".join([ line for line in traceback.format_list(value.trace)\ +traceback.format_exception_only(type, value)])) else:
try: if value.trace != None: self._logger.critical("Uncaught exception:\n\nTraceback (most "\ +"recent call last):\n"+"".join([ line for line in traceback.format_list(value.trace)\ +traceback.format_exception_only(type, value)])) else: self._logger.critical("Uncaught exception:\n\n"+"".join([ line for line in traceback...
def _exceptHook(self, type, value, traceBack): if value.trace != None: self._logger.critical("Uncaught exception:\n\nTraceback (most "\ +"recent call last):\n"+"".join([ line for line in traceback.format_list(value.trace)\ +traceback.format_exception_only(type, value)])) else: self._logger.critical("Uncaught exception:...
def initPlayerMenu(self): self.initRateMenu() self.playerMenu = wx.Menu() menuPlay = self.playerMenu.Append(-1, "&Play", " Play or restart the current track") menuPause = self.playerMenu.Append(-1, "P&ause", " Pause or resume the current track") menuNext = self.playerMenu.Append(-1, "&Next Track", " Play the next trac...
def initFileMenu(self): self.fileMenu = wx.Menu() menuAbout = self.fileMenu.Append( wx.ID_ABOUT, "&About NQr", " Information about NQr") self.fileMenu.AppendSeparator() menuAddFile = self.fileMenu.Append( self.ID_ADDFILE, "Add &File...", " Add a file to the library") menuAddDirectory = self.fileMenu.Append( self.ID_ADD...
self.initRateMenu() trackRightClickMenu = wx.Menu() menuTrackRightClickRateUp = trackRightClickMenu.Append( -1, "Rate &Up", " Increase the score of the current track by one") menuTrackRightClickRateDown = trackRightClickMenu.Append( -1, "Rate &Down", " Decrease the score of the current track by one") rateRightClickMenu...
self.PopupMenu(self.trackRightClickMenu, point)
def onTrackRightClick(self, e): point = e.GetPoint() self.initRateMenu() trackRightClickMenu = wx.Menu() menuTrackRightClickRateUp = trackRightClickMenu.Append( -1, "Rate &Up", " Increase the score of the current track by one") menuTrackRightClickRateDown = trackRightClickMenu.Append( -1, "Rate &Down", " Decrease the s...
self._logger.debug("Retrieving track from cache.")
def _getTrackFromCache(self, trackID): self._logger.debug("Retrieving track from cache.") if type(trackID) is not int: self._logger.error(str(trackID)+" is not a valid track ID") raise TypeError(str(trackID)+" is not a valid track ID") return self._trackCache.get(trackID, None)
self._logger.info("Creating tag.")
def _onTag(self, e): try: self._logger.info("Creating tag.") tagID = e.GetId() if self._tagMenu.IsChecked(tagID) == True: # since clicking checks self.setTag(self._track, tagID) else: self.unsetTag(self._track, tagID) self.refreshSelectedTrack() except AttributeError as err: if str(err) != "'MainWindow' object has no a...
self.addTrackAtPos(0)
self.addTrackAtPos(track, 0)
def addTrack(self, track): self.addTrackAtPos(0)
if self.db.isScored(track) == False:
isScored = self.db.isScored(track) if isScored == False: score = "("+str(self.db.getScoreValue(track))+")"
def addTrackAtPos(self, track, index):
if self.db.getLastPlayedLocalTime(track) == None:
lastPlayed = self.db.getLastPlayedLocalTime(track) if lastPlayed == None:
def addTrackAtPos(self, track, index):
else: lastPlayed = self.db.getLastPlayedLocalTime(track)
def addTrackAtPos(self, track, index):
self.trackList.SetStringItem(index, 3, str(self.db.getScore(track)))
self.trackList.SetStringItem(index, 3, score)
def addTrackAtPos(self, track, index):
if self.db.getLastPlayedLocalTime(track) == None:
lastPlayed = self.db.getLastPlayedLocalTime(track) if lastPlayed == None:
def populateDetails(self, track): if self.db.getLastPlayedLocalTime(track) == None: lastPlayed = "-" else: lastPlayed = self.db.getLastPlayedLocalTime(track) ## should be time from last play self.clearDetails() self.addDetail("Artist: "+self.db.getArtist(track)) self.addDetail("Title: "+self.db.getTitle(track)) sel...
else: lastPlayed = self.db.getLastPlayedLocalTime(track)
def populateDetails(self, track): if self.db.getLastPlayedLocalTime(track) == None: lastPlayed = "-" else: lastPlayed = self.db.getLastPlayedLocalTime(track) ## should be time from last play self.clearDetails() self.addDetail("Artist: "+self.db.getArtist(track)) self.addDetail("Title: "+self.db.getTitle(track)) sel...
self._configParser = ConfigParser.RawConfigParser()
self._configParser = MyConfigParser()
def __init__(self): wx.App.__init__(self, False) self._prefsFile = "settings"
(details, ) = c.fetchall() c.close() if details == None: return None return details
details = c.fetchall() c.close() if details == None: return None tags = [] for detail in details: tags.append(detail[0]) return tags
def getTagsFromID(self, trackID): self._logger.debug("Retrieving track tags.") c = self._conn.cursor() c.execute("select tag from tags where trackid = ?", (trackID, )) (details, ) = c.fetchall() c.close() if details == None: return None return details
self._ignoreNewTracks = bool(self._configParser.get( "GUI", "ignoreNewTracks"))
self._ignoreNewTracks = self._configParser.getboolean( "GUI", "ignoreNewTracks")
def loadSettings(self): try: self._configParser.add_section("GUI") except ConfigParser.DuplicateSectionError: pass try: self._playDelay = self._configParser.getint("GUI", "playDelay") except ConfigParser.NoOptionError: self._playDelay = self._defaultPlayDelay try: self._inactivityTime = self._configParser.getint("GUI",...
got = self._queue.get()[1]
got = self._queue.get()[2]
def run(self): conn = sqlite3.connect(self._databasePath) cursor = conn.cursor() while True: got = self._queue.get()[1] # appears not to get in order of put got(self, cursor)
if range[0] == '': range[0] = 0 else: range[0] = int(range[0])
def get_data(self,uri, range = None): """ return the content of an object """ path=self.uri2local(uri) if os.path.exists(path): if os.path.isfile(path): file_size = os.path.getsize(path) if range == None: fp=open(path,"r") log.info('Serving content of %s' % uri) return Resource(fp, file_size) else: if range[0] == '': r...
if isinstance(DATA, str):
if isinstance(DATA, str) or isinstance(DATA, unicode):
def send_body(self, DATA, code = None, msg = None, desc = None, ctype='application/octet-stream', headers={}): """ send a body in one part """ log.debug("Use send_body method")
def send_body_chunks(self, DATA, code, msg, desc, ctype='text/xml; encoding="utf-8"'):
def send_body_chunks(self, DATA, code, msg=None, desc=None, ctype='text/xml"', headers={}):
def send_body_chunks(self, DATA, code, msg, desc, ctype='text/xml; encoding="utf-8"'): """ send a body in chunks """
if isinstance(DATA, str):
if isinstance(DATA, str) or isinstance(DATA, unicode):
def send_body_chunks(self, DATA, code, msg, desc, ctype='text/xml; encoding="utf-8"'): """ send a body in chunks """
self.log_request(status_code)
def do_OPTIONS(self): """return the list of capabilities """
if isinstance(data, str):
if isinstance(data, str) or isinstance(data, unicode):
def _HEAD_GET(self, with_body=False): """ Returns headers and body for given resource """
def progfunc_avr32( comp[ 'target' ], source, env ):
def progfunc_avr32( target, source, env ):
def progfunc_avr32( comp[ 'target' ], source, env ): outname = output + ".elf" os.system( "%s %s" % ( toolset[ 'size' ], outname ) ) print "Generating binary image..." os.system( "%s -O ihex %s %s.hex" % ( toolset[ 'bin' ], outname, output ) )
elif part['recipe'] == 'plone.recipe.zope2zeoserver':
elif part['recipe'] in ('plone.recipe.zope2zeoserver', 'plone.recipe.zeoserver'):
def __init__(self, buildout, name, options): self.buildout, self.name, self.options = buildout, name, options active_parts = [p.strip() for p in self.buildout['buildout']['parts'].split()] # figure out which ZEO we're going to inject filestorage configuration into, if any zeo_address = None self.zeo_part = options.get...
raise UserError, '[collective.recipe.filestorage] "%s" part found multiple plone.recipe.zope2zeoserver parts; please specify which one to use with the "zeo" option.' % name
raise UserError, '[collective.recipe.filestorage] "%s" part found multiple zeoserver parts; please specify which one to use with the "zeo" option.' % name
def __init__(self, buildout, name, options): self.buildout, self.name, self.options = buildout, name, options active_parts = [p.strip() for p in self.buildout['buildout']['parts'].split()] # figure out which ZEO we're going to inject filestorage configuration into, if any zeo_address = None self.zeo_part = options.get...
version = '0.6dev'
version = '0.6'
def read(*rnames): return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
return dict((name, options.get(name) for name in keep))
return dict((name, options.get(name)) for name in keep)
def extract_msg_options(options, keep=MSG_OPTIONS): return dict((name, options.get(name) for name in keep))
print("SETTING LOGGER TO %s" % (logfile, ))
def setup_logging_subsystem(loglevel=conf.CELERYD_LOG_LEVEL, logfile=None, format=conf.CELERYD_LOG_FORMAT, colorize=conf.CELERYD_LOG_COLOR, **kwargs): global _setup if not _setup: print("SETTING LOGGER TO %s" % (logfile, )) ensure_process_aware_logger() logging.Logger.manager.loggerDict.clear() from multiprocessing imp...
_setup_logger(root, logfile, loglevel, format, colorize, **kwargs)
_setup_logger(root, logfile, format, colorize, **kwargs)
def setup_logging_subsystem(loglevel=conf.CELERYD_LOG_LEVEL, logfile=None, format=conf.CELERYD_LOG_FORMAT, colorize=conf.CELERYD_LOG_COLOR, **kwargs): global _setup if not _setup: print("SETTING LOGGER TO %s" % (logfile, )) ensure_process_aware_logger() logging.Logger.manager.loggerDict.clear() from multiprocessing imp...
if not handled: logger = log.get_default_logger(name="celery.beat") if self.redirect_stdouts: log.redirect_stdouts_to_logger(logger, loglevel=self.redirect_stdouts_level)
logger = log.get_default_logger(name="celery.beat") if self.redirect_stdouts and not handled: log.redirect_stdouts_to_logger(logger, loglevel=self.redirect_stdouts_level)
def setup_logging(self): from celery import log handled = log.setup_logging_subsystem(loglevel=self.loglevel, logfile=self.logfile) if not handled: logger = log.get_default_logger(name="celery.beat") if self.redirect_stdouts: log.redirect_stdouts_to_logger(logger, loglevel=self.redirect_stdouts_level) return logger
E.g. "how many seconds left for 30 seconds after ``start``?"
e.g. "how many seconds left for 30 seconds after start?"
def remaining(start, ends_in, now=None, relative=True): """Calculate the remaining time for a start date and a timedelta. E.g. "how many seconds left for 30 seconds after ``start``?" :param start: Start :class:`datetime.datetime`. :param ends_in: The end delta as a :class:`datetime.timedelta`. :keyword relative: If ...
:param start: Start :class:`datetime.datetime`. :param ends_in: The end delta as a :class:`datetime.timedelta`.
:param start: Start :class:`~datetime.datetime`. :param ends_in: The end delta as a :class:`~datetime.timedelta`.
def remaining(start, ends_in, now=None, relative=True): """Calculate the remaining time for a start date and a timedelta. E.g. "how many seconds left for 30 seconds after ``start``?" :param start: Start :class:`datetime.datetime`. :param ends_in: The end delta as a :class:`datetime.timedelta`. :keyword relative: If ...
serializer=self.serializer)
serializer=self.serializer, auto_delete=self.auto_delete)
def _create_publisher(self, task_id, connection): delivery_mode = self.persistent and 2 or 1
emergency_error(logfile,
emergency_error(self.logfile,
def start_scheduler(self): from celery.log import setup_logger logger = setup_logger(self.loglevel, self.logfile) beat = ClockService(logger, schedule_filename=self.schedule)
exchange_type=exchange_type,
type=exchange_type,
def delay_task(self, task_name, task_args=None, task_kwargs=None, countdown=None, eta=None, task_id=None, taskset_id=None, expires=None, exchange=None, exchange_type=None, **kwargs): """Delay task for execution by the celery nodes."""
celeryd-multi -n celeryd1.myhost -c 10 celeryd-multi -n celeryd2.myhost -c 10 celeryd-multi -n celeryd3.myhost -c 10 celeryd-multi -n celeryd4.myhost -c 3 celeryd-multi -n celeryd5.myhost -c 3
celeryd -n celeryd1.myhost -c 10 celeryd -n celeryd2.myhost -c 10 celeryd -n celeryd3.myhost -c 10 celeryd -n celeryd4.myhost -c 3 celeryd -n celeryd5.myhost -c 3
def help(argv, cmd=None): print("""Some examples: # Advanced example with 10 workers: # * Three of the workers processes the images and video queue # * Two of the workers processes the data queue with loglevel DEBUG # * the rest processes the default' queue. $ celeryd-multi start 10 -l INFO -Q:1-3 images,video -...
celeryd-multi -n foo.myhost -c 10 celeryd-multi -n bar.myhost -c 10 celeryd-multi -n baz.myhost -c 10 celeryd-multi -n xuzzy.myhost -c 3
celeryd -n foo.myhost -c 10 celeryd -n bar.myhost -c 10 celeryd -n baz.myhost -c 10 celeryd -n xuzzy.myhost -c 3
def help(argv, cmd=None): print("""Some examples: # Advanced example with 10 workers: # * Three of the workers processes the images and video queue # * Two of the workers processes the data queue with loglevel DEBUG # * the rest processes the default' queue. $ celeryd-multi start 10 -l INFO -Q:1-3 images,video -...
task = get()
ready, task = poll(1.0) if not ready: continue
def worker(inqueue, outqueue, initializer=None, initargs=(), maxtasks=None): assert maxtasks is None or (type(maxtasks) == int and maxtasks > 0) pid = os.getpid() put = outqueue.put get = inqueue.get if hasattr(inqueue, '_writer'): inqueue._writer.close() outqueue._reader.close() if initializer is not None: initialize...
if putlock is not None: try: putlock.release() except ValueError: pass
def on_state_change(task): state, args = task try: state_handlers[state](*args) except KeyError: debug("Unknown job state: %s (args=%s)" % (state, args))
return self.get_type().apply_async(args, kwargs, options)
return self.get_type().apply_async(args, kwargs, **options)
def apply_async(self, args, kwargs, **options): """Apply this task asynchronously.""" # For callbacks: extra args are prepended to the stored args. args = tuple(args) + tuple(self.args) kwargs = dict(self.kwargs, **kwargs) options = dict(self.options, **options) return self.get_type().apply_async(args, kwargs, options)
if not isinstance(self.destination, (list, tuple)):
if self.destination and \ not isinstance(self.destination, (list, tuple)):
def _prepare(self, reply): if not reply: return by_node = flatten_reply(reply) if not isinstance(self.destination, (list, tuple)): return by_node.get(self.destination) return by_node
self.assertIsInstance(worker.ready_queue, FastQueue)
self.assertTrue(hasattr(worker.ready_queue, "put"))
def test_with_rate_limits_disabled(self): conf.DISABLE_RATE_LIMITS = True try: worker = WorkController(concurrency=1, loglevel=0) self.assertIsInstance(worker.ready_queue, FastQueue) finally: conf.DISABLE_RATE_LIMITS = False
return self.__class__(*s, enabled=self.enabled, op=op)
return self.__class__(enabled=self.enabled, op=op, *s)
def node(self, s, op): return self.__class__(*s, enabled=self.enabled, op=op)
the call evaluates to ``True''.
the call evaluates to :const:`True`.
def cancel(self): """Set the state of the task to :const:`CANCELLED`.
Always returns ``False'' in case the `task_id` parameter refers to a regular (non-cancelable) :class:`Task`.
Always returns :const:`False` in case the `task_id` parameter refers to a regular (non-cancelable) :class:`Task`.
def is_cancelled(self, **kwargs): """Checks against the backend whether this :class:`CancelableAsyncResult` is :const:`CANCELLED`.
"kombu
"kombu",
def run(self, *args, **kwargs): Upgrade().run() install.run(self, *args, **kwargs)
if self.exchange not in _exchanges_declared:
if self.exchange.name not in _exchanges_declared:
def declare(self): if self.exchange not in _exchanges_declared: super(TaskPublisher, self).declare() _exchanges_declared.add(self.exchange)
_exchanges_declared.add(self.exchange)
_exchanges_declared.add(self.exchange.name)
def declare(self): if self.exchange not in _exchanges_declared: super(TaskPublisher, self).declare() _exchanges_declared.add(self.exchange)
win.hline(my - 6, x, curses.ACS_HLINE, self.screen_width)
win.hline(my - 6, x, curses.ACS_HLINE, self.screen_width - 4)
def draw(self): win = self.win self.handle_keypress() x = LEFT_BORDER_OFFSET y = blank_line = count(2).next my, mx = win.getmaxyx() win.erase() win.bkgd(" ", curses.color_pair(1)) win.border() win.addstr(1, x, self.greet, curses.A_DIM | curses.color_pair(5)) blank_line() win.addstr(y(), x, self.format_row("UUID", "TASK...
def multi_args(p, cmd="celeryd", append=None, prefix="", suffix=""):
def multi_args(p, cmd="celeryd", append="", prefix="", suffix=""):
def multi_args(p, cmd="celeryd", append=None, prefix="", suffix=""): names = p.values options = dict(p.options) ranges = len(names) == 1 if ranges: names = map(str, range(1, int(names[0]) + 1)) prefix = "celery" cmd = options.pop("--cmd", cmd) append = options.pop("--append", append) hostname = options.pop("--hostname"...
return emit_no_tyrant_msg("not installed") return emit_no_tyrant_msg("not configured")
emit_no_tyrant_msg("not installed") raise SkipTest("Tokyo Tyrant is not installed") emit_no_tyrant_msg("not configured") raise SkipTest("Tokyo Tyrant not configured")
def emit_no_tyrant_msg(reason): global _no_tyrant_msg_emitted if not _no_tyrant_msg_emitted: sys.stderr.write("\n" + _no_tyrant_msg % reason + "\n") _no_tyrant_msg_emitted = True
executed. Default is a 1 minute delay.
executed. Default is a 3 minute delay.
def __new__(cls, name, bases, attrs): super_new = super(TaskType, cls).__new__ task_module = attrs["__module__"]
print("NAME: %s WANTED: %s" % (name, wanted))
def get(self, argv, cmd): wanted = argv[0] p = NamespacedOptionParser(argv[1:]) for name, worker, _ in multi_args(p, cmd): print("NAME: %s WANTED: %s" % (name, wanted)) if name == wanted: print(" ".join(worker)) return
user=self.conf.EMAIL_USER, password=self.conf.EMAIL_PASSWORD)
user=self.conf.EMAIL_HOST_USER, password=self.conf.EMAIL_HOST_PASSWORD)
def mail_admins(self, subject, body, fail_silently=False): """Send an e-mail to the admins in conf.ADMINS.""" if not self.conf.ADMINS: return to = [admin_email for _, admin_email in self.conf.ADMINS] self.loader.mail_admins(subject, body, fail_silently, to=to, sender=self.conf.SERVER_EMAIL, host=self.conf.EMAIL_HOST, p...
response = self._dispatch()
response = self._dispatch_raw()
def dispatch(self): """Dispatch callback and return result.""" response = self._dispatch() if not response: raise InvalidResponseError("Empty response") try: payload = deserialize(response) except ValueError, exc: raise InvalidResponseError(str(exc))
return HttpDispatch(url, method, kwargs, logger).execute()
return HttpDispatch(url, method, kwargs, logger).dispatch()
def run(self, url=None, method="GET", **kwargs): url = url or self.url method = method or self.method logger = self.get_logger(**kwargs) return HttpDispatch(url, method, kwargs, logger).execute()
self.connection_errors = \ self.app.broker_connection().connection_errors
conninfo = self.app.broker_connection() self.connection_errors = conninfo.connection_errors self.channel_errors = conninfo.channel_errors
def __init__(self, ready_queue, eta_schedule, logger, init_callback=noop, send_events=False, hostname=None, initial_prefetch_count=2, pool=None, queues=None, app=None):
>>> remaining(datetime.now(), ends_in=timedelta(seconds=30)) '0:0:29.999948'
Examples::
def remaining(start, ends_in, now=None, relative=True): """Calculate the remaining time for a start date and a timedelta. E.g. "how many seconds left for 30 seconds after ``start``?" :param start: Start :class:`datetime.datetime`. :param ends_in: The end delta as a :class:`datetime.timedelta`. :keyword relative: If ...
>>> str(remaining(datetime.now() - timedelta(minutes=29), ends_in=timedelta(hours=2))) '1:30:59.999938'
>>> remaining(datetime.now(), ends_in=timedelta(seconds=30)) '0:0:29.999948'
def remaining(start, ends_in, now=None, relative=True): """Calculate the remaining time for a start date and a timedelta. E.g. "how many seconds left for 30 seconds after ``start``?" :param start: Start :class:`datetime.datetime`. :param ends_in: The end delta as a :class:`datetime.timedelta`. :keyword relative: If ...
>>> str(remaining(datetime.now() - timedelta(minutes=29), ends_in=timedelta(hours=2), relative=False)) '1:11:18.458437'
>>> str(remaining(datetime.now() - timedelta(minutes=29), ends_in=timedelta(hours=2))) '1:30:59.999938' >>> str(remaining(datetime.now() - timedelta(minutes=29), ends_in=timedelta(hours=2), relative=False)) '1:11:18.458437'
def remaining(start, ends_in, now=None, relative=True): """Calculate the remaining time for a start date and a timedelta. E.g. "how many seconds left for 30 seconds after ``start``?" :param start: Start :class:`datetime.datetime`. :param ends_in: The end delta as a :class:`datetime.timedelta`. :keyword relative: If ...
server.login(self.user, self.password)
client.login(self.user, self.password)
def send(self, message): client = smtplib.SMTP(self.host, self.port)
process, _index = _process_by_pid(job._accept_pid)
process, _index = _process_by_pid(job._worker_pid)
def _on_soft_timeout(job, i): debug('soft time limit exceeded for %i' % i) process, _index = _process_by_pid(job._accept_pid) if not process: return
os.kill(job._accept_pid, SIG_SOFT_TIMEOUT)
os.kill(job._worker_pid, SIG_SOFT_TIMEOUT)
def _on_soft_timeout(job, i): debug('soft time limit exceeded for %i' % i) process, _index = _process_by_pid(job._accept_pid) if not process: return
process = _pop_by_pid(job._accept_pid)
process = _pop_by_pid(job._worker_pid)
def _on_hard_timeout(job, i): debug('hard time limit exceeded for %i', i) # Remove from _pool process = _pop_by_pid(job._accept_pid) # Remove from cache and set return value to an exception job._set(i, (False, TimeLimitExceeded())) # Run timeout callback if job._timeout_callback is not None: job._timeout_callback(soft=...
return "<crontab: %s %s %s (m/d/h)>" % (self._orig_minute or "*",
return "<crontab: %s %s %s (m/h/d)>" % (self._orig_minute or "*",
def __repr__(self): return "<crontab: %s %s %s (m/d/h)>" % (self._orig_minute or "*", self._orig_hour or "*", self._orig_day_of_week or "*")
for node in P: nodename, _, pid = node self.note("\t> %s: %s -> %s" % (nodename, SIGMAP[sig][3:], pid)) if not self.signal_node(nodename, pid, sig): on_down(node)
for node in list(P): if node in P: nodename, _, pid = node self.note("\t> %s: %s -> %s" % (nodename, SIGMAP[sig][3:], pid)) if not self.signal_node(nodename, pid, sig): on_down(node)
def on_down(node): P.discard(node) if callback: callback(*node)
return memcache.Client(*args, **kwargs)
client = memcache.Client(*args, **kwargs) if is_pylibmc and behaviors is not None: client.behaviors = behaviors return client
def get_best_memcache(*args, **kwargs): try: import pylibmc as memcache except ImportError: try: import memcache except ImportError: raise ImproperlyConfigured("Memcached backend requires either " "the 'memcache' or 'pylibmc' library") return memcache.Client(*args, **kwargs)
def callback(message_data, message): results.append(message_data)
def callback(meta, message): if meta["status"] in states.READY_STATES: results.append(meta)
def callback(message_data, message): results.append(message_data)
kwargs=dict(kwargs, **extra) or {},
kwargs=dict(kwargs or {}, **extra),
def __init__(self, task=None, args=None, kwargs=None, options=None, **extra): init = super(subtask, self).__init__
The queue that holds tasks ready for processing immediately.
The queue that holds tasks ready for immediate processing.
def next(self): return int(self.value)
if not handled: logger = self.app.log.get_default_logger(name="celery.beat") if self.redirect_stdouts: self.app.log.redirect_stdouts_to_logger(logger, loglevel=self.redirect_stdouts_level)
logger = self.app.log.get_default_logger(name="celery.beat") if self.redirect_stdouts and not handled: self.app.log.redirect_stdouts_to_logger(logger, loglevel=self.redirect_stdouts_level)
def setup_logging(self): handled = self.app.log.setup_logging_subsystem(loglevel=self.loglevel, logfile=self.logfile) if not handled: logger = self.app.log.get_default_logger(name="celery.beat") if self.redirect_stdouts: self.app.log.redirect_stdouts_to_logger(logger, loglevel=self.redirect_stdouts_level) return logger
channel.release()
channel.close()
def consume(self, task_id, timeout=None): conn = self.pool.acquire(block=True) channel = conn.channel() try: binding = self._create_binding(task_id) consumer = self._create_consumer(binding, channel) consumer.consume() try: return self.drain_events(consumer, timeout=timeout).values()[0] finally: consumer.cancel() final...
self.chan = self.conn.create_backend().channel
self.chan = self.conn.channel()
def _reconnect(self): """Re-establish connection to the AMQP server.""" self.conn = self.connect(self.conn) self.chan = self.conn.create_backend().channel self.needs_reconnect = False
self.publisher = publisher or EventPublisher(self.connection)
def __init__(self, connection, hostname=None, enabled=True, publisher=None): self.connection = connection self.publisher = publisher or EventPublisher(self.connection) self.hostname = hostname or socket.gethostname() self.enabled = enabled self._lock = threading.Lock()
def sigdump(**kwargs): from celery.log import setup_logger logger = setup_logger() logger.error("Received signal: %s" % repr(kwargs)) task_postrun.connect(sigdump)
def sigdump(**kwargs): from celery.log import setup_logger logger = setup_logger() logger.error("Received signal: %s" % repr(kwargs))
get_default_backend_cls = curry(get_backend_cls, conf.CELERY_RESULT_BACKEND)
get_default_backend_cls = curry(get_backend_cls, conf.RESULT_BACKEND)
def get_backend_cls(backend): """Get backend class by name/alias""" if backend not in _backend_cache: _backend_cache[backend] = _get_backend_cls(backend) return _backend_cache[backend]
_loader = _detect_loader()()
_loader = detect_loader()()
def current_loader(): """Detect and return the current loader.""" global _loader if _loader is None: _loader = _detect_loader()() return _loader
pass
self.logger = log.get_default_logger()
def __init__(self, *args, **kwargs): pass
st = cd.set_process_status("Running")
st = worker.set_process_status("Running")
def test_set_process_status(self): prev1, sys.argv = sys.argv, ["Arg0"] try: st = cd.set_process_status("Running") self.assertIn("celeryd", st) self.assertIn("Running", st) prev2, sys.argv = sys.argv, ["Arg0", "Arg1"] try: st = cd.set_process_status("Running") self.assertIn("celeryd", st) self.assertIn("Running", st) s...
conf.QUEUES = dict((queue, options)
if self.queues: conf.QUEUES = dict((queue, options)
def init_queues(self): conf.QUEUES = dict((queue, options) for queue, options in conf.QUEUES.items() if queue in self.queues)
win.addstr(my - 2, x, self.help_title, curses.A_BOLD) win.addstr(my - 2, x + len(self.help_title), self.help, curses.A_DIM)
self.safe_add_str(my - 2, x, self.help_title, curses.A_BOLD) self.safe_add_str(my - 2, x + len(self.help_title), self.help, curses.A_DIM)
def draw(self): win = self.win self.handle_keypress() x = LEFT_BORDER_OFFSET y = blank_line = count(2).next my, mx = win.getmaxyx() win.erase() win.bkgd(" ", curses.color_pair(1)) win.border() win.addstr(1, x, self.greet, curses.A_DIM | curses.color_pair(5)) blank_line() win.addstr(y(), x, self.format_row("UUID", "TASK...
self.assertIsInstance(worker.ready_queue, FastQueue)
self.assertTrue(hasattr(worker.ready_queue, "put"))
def test_with_rate_limits_disabled(self): worker = WorkController(concurrency=1, loglevel=0, disable_rate_limits=True) self.assertIsInstance(worker.ready_queue, FastQueue)
``settings.SEND_CELERY_ERROR_EMAILS`` is on.)
``settings.CELERY_SEND_TASK_ERROR_EMAILS`` is on.)
def __new__(cls, name, bases, attrs): super_new = super(TaskType, cls).__new__ task_module = attrs["__module__"]
def worker(inqueue, outqueue, ackqueue, initializer=None, initargs=(), maxtasks=None):
def worker(inqueue, outqueue, initializer=None, initargs=(), maxtasks=None):
def worker(inqueue, outqueue, ackqueue, initializer=None, initargs=(), maxtasks=None): assert maxtasks is None or (type(maxtasks) == int and maxtasks > 0) pid = os.getpid() put = outqueue.put get = inqueue.get ack = ackqueue.put if hasattr(inqueue, '_writer'): inqueue._writer.close() outqueue._reader.close() if initia...
ack = ackqueue.put
def worker(inqueue, outqueue, ackqueue, initializer=None, initargs=(), maxtasks=None): assert maxtasks is None or (type(maxtasks) == int and maxtasks > 0) pid = os.getpid() put = outqueue.put get = inqueue.get ack = ackqueue.put if hasattr(inqueue, '_writer'): inqueue._writer.close() outqueue._reader.close() if initia...
ack((job, i, time.time(), pid))
put((ACK, (job, i, time.time(), pid)))
def worker(inqueue, outqueue, ackqueue, initializer=None, initargs=(), maxtasks=None): assert maxtasks is None or (type(maxtasks) == int and maxtasks > 0) pid = os.getpid() put = outqueue.put get = inqueue.get ack = ackqueue.put if hasattr(inqueue, '_writer'): inqueue._writer.close() outqueue._reader.close() if initia...
put((job, i, result))
put((READY, (job, i, result)))
def worker(inqueue, outqueue, ackqueue, initializer=None, initargs=(), maxtasks=None): assert maxtasks is None or (type(maxtasks) == int and maxtasks > 0) pid = os.getpid() put = outqueue.put get = inqueue.get ack = ackqueue.put if hasattr(inqueue, '_writer'): inqueue._writer.close() outqueue._reader.close() if initia...
put((job, i, (False, wrapped)))
put((READY, (job, i, (False, wrapped))))
def worker(inqueue, outqueue, ackqueue, initializer=None, initargs=(), maxtasks=None): assert maxtasks is None or (type(maxtasks) == int and maxtasks > 0) pid = os.getpid() put = outqueue.put get = inqueue.get ack = ackqueue.put if hasattr(inqueue, '_writer'): inqueue._writer.close() outqueue._reader.close() if initia...
class AckHandler(PoolThread): def __init__(self, ackqueue, get, cache): self.ackqueue = ackqueue self.get = get self.cache = cache super(AckHandler, self).__init__() def run(self): debug('ack handler starting') get = self.get cache = self.cache while 1: try: task = get() except (IOError, EOFError), exc: debug('ack ...
def run(self): taskqueue = self.taskqueue outqueue = self.outqueue put = self.put pool = self.pool
def __init__(self, outqueue, get, cache, putlock):
def __init__(self, outqueue, get, cache, poll, join_exited_workers, putlock):
def __init__(self, outqueue, get, cache, putlock): self.outqueue = outqueue self.get = get self.cache = cache self.putlock = putlock super(ResultHandler, self).__init__()
task = get()
ready, task = poll(0.2)
def run(self): get = self.get outqueue = self.outqueue cache = self.cache putlock = self.putlock
debug('result handler got %s -- exiting', exc.__class__.__name__)
debug('result handler got %r -- exiting' % (exc, ))
def run(self): get = self.get outqueue = self.outqueue cache = self.cache putlock = self.putlock
if putlock is not None: try: putlock.release() except ValueError: pass
def run(self): get = self.get outqueue = self.outqueue cache = self.cache putlock = self.putlock
if task is None: debug('result handler got sentinel') break job, i, obj = task try: cache[job]._set(i, obj) except KeyError: pass
if ready: if task is None: debug('result handler got sentinel') break if putlock is not None: try: putlock.release() except ValueError: pass on_state_change(task)
def run(self): get = self.get outqueue = self.outqueue cache = self.cache putlock = self.putlock
if task is None: debug('result handler ignoring extra sentinel') continue
if ready: if task is None: debug('result handler ignoring extra sentinel') continue on_state_change(task) join_exited_workers()
def run(self): get = self.get outqueue = self.outqueue cache = self.cache putlock = self.putlock
AckHandler = AckHandler
def run(self): get = self.get outqueue = self.outqueue cache = self.cache putlock = self.putlock
self._ack_handler = self.AckHandler(self._ackqueue, self._quick_get_ack, self._cache) self._ack_handler.start()
def __init__(self, processes=None, initializer=None, initargs=(), maxtasksperchild=None, timeout=None, soft_timeout=None): self._setup_queues() self._taskqueue = Queue.Queue() self._cache = {} self._state = RUN self.timeout = timeout self.soft_timeout = soft_timeout self._maxtasksperchild = maxtasksperchild self._initi...