repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
gmr/rejected | rejected/mcp.py | MasterControlProgram.on_sigchld | def on_sigchld(self, _signum, _unused_frame):
"""Invoked when a child sends up an SIGCHLD signal.
:param int _signum: The signal that was invoked
:param frame _unused_frame: The frame that was interrupted
"""
LOGGER.info('SIGCHLD received from child')
if not self.active_processes(False):
LOGGER.info('Stopping with no active processes and child error')
signal.setitimer(signal.ITIMER_REAL, 0, 0)
self.set_state(self.STATE_STOPPED) | python | def on_sigchld(self, _signum, _unused_frame):
"""Invoked when a child sends up an SIGCHLD signal.
:param int _signum: The signal that was invoked
:param frame _unused_frame: The frame that was interrupted
"""
LOGGER.info('SIGCHLD received from child')
if not self.active_processes(False):
LOGGER.info('Stopping with no active processes and child error')
signal.setitimer(signal.ITIMER_REAL, 0, 0)
self.set_state(self.STATE_STOPPED) | [
"def",
"on_sigchld",
"(",
"self",
",",
"_signum",
",",
"_unused_frame",
")",
":",
"LOGGER",
".",
"info",
"(",
"'SIGCHLD received from child'",
")",
"if",
"not",
"self",
".",
"active_processes",
"(",
"False",
")",
":",
"LOGGER",
".",
"info",
"(",
"'Stopping w... | Invoked when a child sends up an SIGCHLD signal.
:param int _signum: The signal that was invoked
:param frame _unused_frame: The frame that was interrupted | [
"Invoked",
"when",
"a",
"child",
"sends",
"up",
"an",
"SIGCHLD",
"signal",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/mcp.py#L398-L409 | train | 30,600 |
gmr/rejected | rejected/mcp.py | MasterControlProgram.on_timer | def on_timer(self, _signum, _unused_frame):
"""Invoked by the Poll timer signal.
:param int _signum: The signal that was invoked
:param frame _unused_frame: The frame that was interrupted
"""
if self.is_shutting_down:
LOGGER.debug('Polling timer fired while shutting down')
return
if not self.polled:
self.poll()
self.polled = True
self.set_timer(5) # Wait 5 seconds for results
else:
self.polled = False
self.poll_results_check()
self.set_timer(self.poll_interval) # Wait poll interval duration
# If stats logging is enabled, log the stats
if self.log_stats_enabled:
self.log_stats()
# Increment the unresponsive children
for proc_name in self.poll_data['processes']:
self.unresponsive[proc_name] += 1
# Remove counters for processes that came back to life
for proc_name in list(self.unresponsive.keys()):
if proc_name not in self.poll_data['processes']:
del self.unresponsive[proc_name] | python | def on_timer(self, _signum, _unused_frame):
"""Invoked by the Poll timer signal.
:param int _signum: The signal that was invoked
:param frame _unused_frame: The frame that was interrupted
"""
if self.is_shutting_down:
LOGGER.debug('Polling timer fired while shutting down')
return
if not self.polled:
self.poll()
self.polled = True
self.set_timer(5) # Wait 5 seconds for results
else:
self.polled = False
self.poll_results_check()
self.set_timer(self.poll_interval) # Wait poll interval duration
# If stats logging is enabled, log the stats
if self.log_stats_enabled:
self.log_stats()
# Increment the unresponsive children
for proc_name in self.poll_data['processes']:
self.unresponsive[proc_name] += 1
# Remove counters for processes that came back to life
for proc_name in list(self.unresponsive.keys()):
if proc_name not in self.poll_data['processes']:
del self.unresponsive[proc_name] | [
"def",
"on_timer",
"(",
"self",
",",
"_signum",
",",
"_unused_frame",
")",
":",
"if",
"self",
".",
"is_shutting_down",
":",
"LOGGER",
".",
"debug",
"(",
"'Polling timer fired while shutting down'",
")",
"return",
"if",
"not",
"self",
".",
"polled",
":",
"self"... | Invoked by the Poll timer signal.
:param int _signum: The signal that was invoked
:param frame _unused_frame: The frame that was interrupted | [
"Invoked",
"by",
"the",
"Poll",
"timer",
"signal",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/mcp.py#L411-L441 | train | 30,601 |
gmr/rejected | rejected/mcp.py | MasterControlProgram.poll | def poll(self):
"""Start the poll process by invoking the get_stats method of the
consumers. If we hit this after another interval without fully
processing, note it with a warning.
"""
self.set_state(self.STATE_ACTIVE)
# If we don't have any active consumers, spawn new ones
if not self.total_process_count:
LOGGER.debug('Did not find any active consumers in poll')
return self.check_process_counts()
# Start our data collection dict
self.poll_data = {'timestamp': time.time(), 'processes': list()}
# Iterate through all of the consumers
for proc in list(self.active_processes()):
if proc == multiprocessing.current_process():
continue
# Send the profile signal
os.kill(int(proc.pid), signal.SIGPROF)
self.poll_data['processes'].append(proc.name)
# Check if we need to start more processes
self.check_process_counts() | python | def poll(self):
"""Start the poll process by invoking the get_stats method of the
consumers. If we hit this after another interval without fully
processing, note it with a warning.
"""
self.set_state(self.STATE_ACTIVE)
# If we don't have any active consumers, spawn new ones
if not self.total_process_count:
LOGGER.debug('Did not find any active consumers in poll')
return self.check_process_counts()
# Start our data collection dict
self.poll_data = {'timestamp': time.time(), 'processes': list()}
# Iterate through all of the consumers
for proc in list(self.active_processes()):
if proc == multiprocessing.current_process():
continue
# Send the profile signal
os.kill(int(proc.pid), signal.SIGPROF)
self.poll_data['processes'].append(proc.name)
# Check if we need to start more processes
self.check_process_counts() | [
"def",
"poll",
"(",
"self",
")",
":",
"self",
".",
"set_state",
"(",
"self",
".",
"STATE_ACTIVE",
")",
"# If we don't have any active consumers, spawn new ones",
"if",
"not",
"self",
".",
"total_process_count",
":",
"LOGGER",
".",
"debug",
"(",
"'Did not find any ac... | Start the poll process by invoking the get_stats method of the
consumers. If we hit this after another interval without fully
processing, note it with a warning. | [
"Start",
"the",
"poll",
"process",
"by",
"invoking",
"the",
"get_stats",
"method",
"of",
"the",
"consumers",
".",
"If",
"we",
"hit",
"this",
"after",
"another",
"interval",
"without",
"fully",
"processing",
"note",
"it",
"with",
"a",
"warning",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/mcp.py#L443-L469 | train | 30,602 |
gmr/rejected | rejected/mcp.py | MasterControlProgram.poll_results_check | def poll_results_check(self):
"""Check the polling results by checking to see if the stats queue is
empty. If it is not, try and collect stats. If it is set a timer to
call ourselves in _POLL_RESULTS_INTERVAL.
"""
if not self.consumers:
LOGGER.debug('Skipping poll results check, no consumers')
return
LOGGER.debug('Checking for poll results')
while True:
try:
stats = self.stats_queue.get(False)
except queue.Empty:
break
try:
self.poll_data['processes'].remove(stats['name'])
except ValueError:
pass
self.collect_results(stats)
if self.poll_data['processes']:
LOGGER.warning('Did not receive results from %r',
self.poll_data['processes']) | python | def poll_results_check(self):
"""Check the polling results by checking to see if the stats queue is
empty. If it is not, try and collect stats. If it is set a timer to
call ourselves in _POLL_RESULTS_INTERVAL.
"""
if not self.consumers:
LOGGER.debug('Skipping poll results check, no consumers')
return
LOGGER.debug('Checking for poll results')
while True:
try:
stats = self.stats_queue.get(False)
except queue.Empty:
break
try:
self.poll_data['processes'].remove(stats['name'])
except ValueError:
pass
self.collect_results(stats)
if self.poll_data['processes']:
LOGGER.warning('Did not receive results from %r',
self.poll_data['processes']) | [
"def",
"poll_results_check",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"consumers",
":",
"LOGGER",
".",
"debug",
"(",
"'Skipping poll results check, no consumers'",
")",
"return",
"LOGGER",
".",
"debug",
"(",
"'Checking for poll results'",
")",
"while",
"Tr... | Check the polling results by checking to see if the stats queue is
empty. If it is not, try and collect stats. If it is set a timer to
call ourselves in _POLL_RESULTS_INTERVAL. | [
"Check",
"the",
"polling",
"results",
"by",
"checking",
"to",
"see",
"if",
"the",
"stats",
"queue",
"is",
"empty",
".",
"If",
"it",
"is",
"not",
"try",
"and",
"collect",
"stats",
".",
"If",
"it",
"is",
"set",
"a",
"timer",
"to",
"call",
"ourselves",
... | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/mcp.py#L480-L504 | train | 30,603 |
gmr/rejected | rejected/mcp.py | MasterControlProgram.process_spawn_qty | def process_spawn_qty(self, name):
"""Return the number of processes to spawn for the given consumer name.
:param str name: The consumer name
:rtype: int
"""
return self.consumers[name].qty - self.process_count(name) | python | def process_spawn_qty(self, name):
"""Return the number of processes to spawn for the given consumer name.
:param str name: The consumer name
:rtype: int
"""
return self.consumers[name].qty - self.process_count(name) | [
"def",
"process_spawn_qty",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"consumers",
"[",
"name",
"]",
".",
"qty",
"-",
"self",
".",
"process_count",
"(",
"name",
")"
] | Return the number of processes to spawn for the given consumer name.
:param str name: The consumer name
:rtype: int | [
"Return",
"the",
"number",
"of",
"processes",
"to",
"spawn",
"for",
"the",
"given",
"consumer",
"name",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/mcp.py#L526-L533 | train | 30,604 |
gmr/rejected | rejected/mcp.py | MasterControlProgram.remove_consumer_process | def remove_consumer_process(self, consumer, name):
"""Remove all details for the specified consumer and process name.
:param str consumer: The consumer name
:param str name: The process name
"""
my_pid = os.getpid()
if name in self.consumers[consumer].processes.keys():
child = self.consumers[consumer].processes[name]
try:
alive = child.is_alive()
except AssertionError:
LOGGER.debug('Tried to test non-child process (%r to %r)',
os.getpid(), child.pid)
else:
if child.pid == my_pid:
LOGGER.debug('Child has my pid? %r, %r', my_pid, child.pid)
elif alive:
try:
child.terminate()
except OSError:
pass
try:
del self.consumers[consumer].processes[name]
except KeyError:
pass | python | def remove_consumer_process(self, consumer, name):
"""Remove all details for the specified consumer and process name.
:param str consumer: The consumer name
:param str name: The process name
"""
my_pid = os.getpid()
if name in self.consumers[consumer].processes.keys():
child = self.consumers[consumer].processes[name]
try:
alive = child.is_alive()
except AssertionError:
LOGGER.debug('Tried to test non-child process (%r to %r)',
os.getpid(), child.pid)
else:
if child.pid == my_pid:
LOGGER.debug('Child has my pid? %r, %r', my_pid, child.pid)
elif alive:
try:
child.terminate()
except OSError:
pass
try:
del self.consumers[consumer].processes[name]
except KeyError:
pass | [
"def",
"remove_consumer_process",
"(",
"self",
",",
"consumer",
",",
"name",
")",
":",
"my_pid",
"=",
"os",
".",
"getpid",
"(",
")",
"if",
"name",
"in",
"self",
".",
"consumers",
"[",
"consumer",
"]",
".",
"processes",
".",
"keys",
"(",
")",
":",
"ch... | Remove all details for the specified consumer and process name.
:param str consumer: The consumer name
:param str name: The process name | [
"Remove",
"all",
"details",
"for",
"the",
"specified",
"consumer",
"and",
"process",
"name",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/mcp.py#L535-L561 | train | 30,605 |
gmr/rejected | rejected/mcp.py | MasterControlProgram.run | def run(self):
"""When the consumer is ready to start running, kick off all of our
consumer consumers and then loop while we process messages.
"""
self.set_state(self.STATE_ACTIVE)
self.setup_consumers()
# Set the SIGCHLD handler for child creation errors
signal.signal(signal.SIGCHLD, self.on_sigchld)
# Set the SIGALRM handler for poll interval
signal.signal(signal.SIGALRM, self.on_timer)
# Kick off the poll timer
signal.setitimer(signal.ITIMER_REAL, self.poll_interval, 0)
# Loop for the lifetime of the app, pausing for a signal to pop up
while self.is_running:
if not self.is_sleeping:
self.set_state(self.STATE_SLEEPING)
signal.pause()
# Note we're exiting run
LOGGER.info('Exiting Master Control Program') | python | def run(self):
"""When the consumer is ready to start running, kick off all of our
consumer consumers and then loop while we process messages.
"""
self.set_state(self.STATE_ACTIVE)
self.setup_consumers()
# Set the SIGCHLD handler for child creation errors
signal.signal(signal.SIGCHLD, self.on_sigchld)
# Set the SIGALRM handler for poll interval
signal.signal(signal.SIGALRM, self.on_timer)
# Kick off the poll timer
signal.setitimer(signal.ITIMER_REAL, self.poll_interval, 0)
# Loop for the lifetime of the app, pausing for a signal to pop up
while self.is_running:
if not self.is_sleeping:
self.set_state(self.STATE_SLEEPING)
signal.pause()
# Note we're exiting run
LOGGER.info('Exiting Master Control Program') | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"set_state",
"(",
"self",
".",
"STATE_ACTIVE",
")",
"self",
".",
"setup_consumers",
"(",
")",
"# Set the SIGCHLD handler for child creation errors",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGCHLD",
",",
... | When the consumer is ready to start running, kick off all of our
consumer consumers and then loop while we process messages. | [
"When",
"the",
"consumer",
"is",
"ready",
"to",
"start",
"running",
"kick",
"off",
"all",
"of",
"our",
"consumer",
"consumers",
"and",
"then",
"loop",
"while",
"we",
"process",
"messages",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/mcp.py#L563-L587 | train | 30,606 |
gmr/rejected | rejected/mcp.py | MasterControlProgram.set_process_name | def set_process_name():
"""Set the process name for the top level process so that it shows up
in logs in a more trackable fashion.
"""
proc = multiprocessing.current_process()
for offset in range(0, len(sys.argv)):
if sys.argv[offset] == '-c':
name = sys.argv[offset + 1].split('/')[-1]
proc.name = name.split('.')[0]
break | python | def set_process_name():
"""Set the process name for the top level process so that it shows up
in logs in a more trackable fashion.
"""
proc = multiprocessing.current_process()
for offset in range(0, len(sys.argv)):
if sys.argv[offset] == '-c':
name = sys.argv[offset + 1].split('/')[-1]
proc.name = name.split('.')[0]
break | [
"def",
"set_process_name",
"(",
")",
":",
"proc",
"=",
"multiprocessing",
".",
"current_process",
"(",
")",
"for",
"offset",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"sys",
".",
"argv",
")",
")",
":",
"if",
"sys",
".",
"argv",
"[",
"offset",
"]",
... | Set the process name for the top level process so that it shows up
in logs in a more trackable fashion. | [
"Set",
"the",
"process",
"name",
"for",
"the",
"top",
"level",
"process",
"so",
"that",
"it",
"shows",
"up",
"in",
"logs",
"in",
"a",
"more",
"trackable",
"fashion",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/mcp.py#L590-L600 | train | 30,607 |
gmr/rejected | rejected/mcp.py | MasterControlProgram.set_timer | def set_timer(self, duration):
"""Setup the next alarm to fire and then wait for it to fire.
:param int duration: How long to sleep
"""
# Make sure that the application is not shutting down before sleeping
if self.is_shutting_down:
LOGGER.debug('Not sleeping, application is trying to shutdown')
return
# Set the signal timer
signal.setitimer(signal.ITIMER_REAL, duration, 0) | python | def set_timer(self, duration):
"""Setup the next alarm to fire and then wait for it to fire.
:param int duration: How long to sleep
"""
# Make sure that the application is not shutting down before sleeping
if self.is_shutting_down:
LOGGER.debug('Not sleeping, application is trying to shutdown')
return
# Set the signal timer
signal.setitimer(signal.ITIMER_REAL, duration, 0) | [
"def",
"set_timer",
"(",
"self",
",",
"duration",
")",
":",
"# Make sure that the application is not shutting down before sleeping",
"if",
"self",
".",
"is_shutting_down",
":",
"LOGGER",
".",
"debug",
"(",
"'Not sleeping, application is trying to shutdown'",
")",
"return",
... | Setup the next alarm to fire and then wait for it to fire.
:param int duration: How long to sleep | [
"Setup",
"the",
"next",
"alarm",
"to",
"fire",
"and",
"then",
"wait",
"for",
"it",
"to",
"fire",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/mcp.py#L602-L614 | train | 30,608 |
gmr/rejected | rejected/mcp.py | MasterControlProgram.setup_consumers | def setup_consumers(self):
"""Iterate through each consumer in the configuration and kick off the
minimal amount of processes, setting up the runtime data as well.
"""
if not self.consumer_cfg:
LOGGER.warning('No consumers are configured')
for name in self.consumer_cfg.keys():
self.consumers[name] = self.new_consumer(
self.consumer_cfg[name], name)
self.start_processes(name, self.consumers[name].qty) | python | def setup_consumers(self):
"""Iterate through each consumer in the configuration and kick off the
minimal amount of processes, setting up the runtime data as well.
"""
if not self.consumer_cfg:
LOGGER.warning('No consumers are configured')
for name in self.consumer_cfg.keys():
self.consumers[name] = self.new_consumer(
self.consumer_cfg[name], name)
self.start_processes(name, self.consumers[name].qty) | [
"def",
"setup_consumers",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"consumer_cfg",
":",
"LOGGER",
".",
"warning",
"(",
"'No consumers are configured'",
")",
"for",
"name",
"in",
"self",
".",
"consumer_cfg",
".",
"keys",
"(",
")",
":",
"self",
".",
... | Iterate through each consumer in the configuration and kick off the
minimal amount of processes, setting up the runtime data as well. | [
"Iterate",
"through",
"each",
"consumer",
"in",
"the",
"configuration",
"and",
"kick",
"off",
"the",
"minimal",
"amount",
"of",
"processes",
"setting",
"up",
"the",
"runtime",
"data",
"as",
"well",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/mcp.py#L616-L626 | train | 30,609 |
gmr/rejected | rejected/mcp.py | MasterControlProgram.start_process | def start_process(self, name):
"""Start a new consumer process for the given consumer name
:param str name: The consumer name
"""
process_name, proc = self.new_process(name)
LOGGER.info('Spawning %s process for %s', process_name, name)
# Append the process to the consumer process list
self.consumers[name].processes[process_name] = proc
# Start the process
try:
proc.start()
except IOError as error:
LOGGER.critical('Failed to start %s for %s: %r',
process_name, name, error)
del self.consumers[name].process[process_name] | python | def start_process(self, name):
"""Start a new consumer process for the given consumer name
:param str name: The consumer name
"""
process_name, proc = self.new_process(name)
LOGGER.info('Spawning %s process for %s', process_name, name)
# Append the process to the consumer process list
self.consumers[name].processes[process_name] = proc
# Start the process
try:
proc.start()
except IOError as error:
LOGGER.critical('Failed to start %s for %s: %r',
process_name, name, error)
del self.consumers[name].process[process_name] | [
"def",
"start_process",
"(",
"self",
",",
"name",
")",
":",
"process_name",
",",
"proc",
"=",
"self",
".",
"new_process",
"(",
"name",
")",
"LOGGER",
".",
"info",
"(",
"'Spawning %s process for %s'",
",",
"process_name",
",",
"name",
")",
"# Append the process... | Start a new consumer process for the given consumer name
:param str name: The consumer name | [
"Start",
"a",
"new",
"consumer",
"process",
"for",
"the",
"given",
"consumer",
"name"
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/mcp.py#L628-L646 | train | 30,610 |
gmr/rejected | rejected/mcp.py | MasterControlProgram.start_processes | def start_processes(self, name, quantity):
"""Start the specified quantity of consumer processes for the given
consumer.
:param str name: The consumer name
:param int quantity: The quantity of processes to start
"""
[self.start_process(name) for i in range(0, quantity or 0)] | python | def start_processes(self, name, quantity):
"""Start the specified quantity of consumer processes for the given
consumer.
:param str name: The consumer name
:param int quantity: The quantity of processes to start
"""
[self.start_process(name) for i in range(0, quantity or 0)] | [
"def",
"start_processes",
"(",
"self",
",",
"name",
",",
"quantity",
")",
":",
"[",
"self",
".",
"start_process",
"(",
"name",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"quantity",
"or",
"0",
")",
"]"
] | Start the specified quantity of consumer processes for the given
consumer.
:param str name: The consumer name
:param int quantity: The quantity of processes to start | [
"Start",
"the",
"specified",
"quantity",
"of",
"consumer",
"processes",
"for",
"the",
"given",
"consumer",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/mcp.py#L648-L656 | train | 30,611 |
gmr/rejected | rejected/mcp.py | MasterControlProgram.stop_processes | def stop_processes(self):
"""Iterate through all of the consumer processes shutting them down."""
self.set_state(self.STATE_SHUTTING_DOWN)
LOGGER.info('Stopping consumer processes')
signal.signal(signal.SIGABRT, signal.SIG_IGN)
signal.signal(signal.SIGALRM, signal.SIG_IGN)
signal.signal(signal.SIGCHLD, signal.SIG_IGN)
signal.signal(signal.SIGPROF, signal.SIG_IGN)
signal.setitimer(signal.ITIMER_REAL, 0, 0)
# Send SIGABRT
LOGGER.info('Sending SIGABRT to active children')
for proc in multiprocessing.active_children():
if int(proc.pid) != os.getpid():
try:
os.kill(int(proc.pid), signal.SIGABRT)
except OSError:
pass
# Wait for them to finish up to MAX_SHUTDOWN_WAIT
for iteration in range(0, self.MAX_SHUTDOWN_WAIT):
processes = len(self.active_processes(False))
if not processes:
break
LOGGER.info('Waiting on %i active processes to shut down (%i/%i)',
processes, iteration, self.MAX_SHUTDOWN_WAIT)
try:
time.sleep(0.5)
except KeyboardInterrupt:
break
if len(self.active_processes(False)):
self.kill_processes()
LOGGER.debug('All consumer processes stopped')
self.set_state(self.STATE_STOPPED) | python | def stop_processes(self):
"""Iterate through all of the consumer processes shutting them down."""
self.set_state(self.STATE_SHUTTING_DOWN)
LOGGER.info('Stopping consumer processes')
signal.signal(signal.SIGABRT, signal.SIG_IGN)
signal.signal(signal.SIGALRM, signal.SIG_IGN)
signal.signal(signal.SIGCHLD, signal.SIG_IGN)
signal.signal(signal.SIGPROF, signal.SIG_IGN)
signal.setitimer(signal.ITIMER_REAL, 0, 0)
# Send SIGABRT
LOGGER.info('Sending SIGABRT to active children')
for proc in multiprocessing.active_children():
if int(proc.pid) != os.getpid():
try:
os.kill(int(proc.pid), signal.SIGABRT)
except OSError:
pass
# Wait for them to finish up to MAX_SHUTDOWN_WAIT
for iteration in range(0, self.MAX_SHUTDOWN_WAIT):
processes = len(self.active_processes(False))
if not processes:
break
LOGGER.info('Waiting on %i active processes to shut down (%i/%i)',
processes, iteration, self.MAX_SHUTDOWN_WAIT)
try:
time.sleep(0.5)
except KeyboardInterrupt:
break
if len(self.active_processes(False)):
self.kill_processes()
LOGGER.debug('All consumer processes stopped')
self.set_state(self.STATE_STOPPED) | [
"def",
"stop_processes",
"(",
"self",
")",
":",
"self",
".",
"set_state",
"(",
"self",
".",
"STATE_SHUTTING_DOWN",
")",
"LOGGER",
".",
"info",
"(",
"'Stopping consumer processes'",
")",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGABRT",
",",
"signal",
"... | Iterate through all of the consumer processes shutting them down. | [
"Iterate",
"through",
"all",
"of",
"the",
"consumer",
"processes",
"shutting",
"them",
"down",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/mcp.py#L658-L695 | train | 30,612 |
gmr/rejected | rejected/controller.py | add_parser_arguments | def add_parser_arguments():
"""Add options to the parser"""
argparser = parser.get()
argparser.add_argument('-P', '--profile',
action='store',
default=None,
dest='profile',
help='Profile the consumer modules, specifying '
'the output directory.')
argparser.add_argument('-o', '--only',
action='store',
default=None,
dest='consumer',
help='Only run the consumer specified')
argparser.add_argument('-p', '--prepend-path',
action='store',
default=None,
dest='prepend_path',
help='Prepend the python path with the value.')
argparser.add_argument('-q', '--qty',
action='store',
type=int,
default=None,
dest='quantity',
help='Run the specified quantity of consumer '
'processes when used in conjunction with -o')
argparser.add_argument('--version', action='version',
version='%(prog)s {}'.format(__version__)) | python | def add_parser_arguments():
"""Add options to the parser"""
argparser = parser.get()
argparser.add_argument('-P', '--profile',
action='store',
default=None,
dest='profile',
help='Profile the consumer modules, specifying '
'the output directory.')
argparser.add_argument('-o', '--only',
action='store',
default=None,
dest='consumer',
help='Only run the consumer specified')
argparser.add_argument('-p', '--prepend-path',
action='store',
default=None,
dest='prepend_path',
help='Prepend the python path with the value.')
argparser.add_argument('-q', '--qty',
action='store',
type=int,
default=None,
dest='quantity',
help='Run the specified quantity of consumer '
'processes when used in conjunction with -o')
argparser.add_argument('--version', action='version',
version='%(prog)s {}'.format(__version__)) | [
"def",
"add_parser_arguments",
"(",
")",
":",
"argparser",
"=",
"parser",
".",
"get",
"(",
")",
"argparser",
".",
"add_argument",
"(",
"'-P'",
",",
"'--profile'",
",",
"action",
"=",
"'store'",
",",
"default",
"=",
"None",
",",
"dest",
"=",
"'profile'",
... | Add options to the parser | [
"Add",
"options",
"to",
"the",
"parser"
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/controller.py#L116-L143 | train | 30,613 |
gmr/rejected | rejected/controller.py | Controller._master_control_program | def _master_control_program(self):
"""Return an instance of the MasterControlProgram.
:rtype: rejected.mcp.MasterControlProgram
"""
return mcp.MasterControlProgram(self.config,
consumer=self.args.consumer,
profile=self.args.profile,
quantity=self.args.quantity) | python | def _master_control_program(self):
"""Return an instance of the MasterControlProgram.
:rtype: rejected.mcp.MasterControlProgram
"""
return mcp.MasterControlProgram(self.config,
consumer=self.args.consumer,
profile=self.args.profile,
quantity=self.args.quantity) | [
"def",
"_master_control_program",
"(",
"self",
")",
":",
"return",
"mcp",
".",
"MasterControlProgram",
"(",
"self",
".",
"config",
",",
"consumer",
"=",
"self",
".",
"args",
".",
"consumer",
",",
"profile",
"=",
"self",
".",
"args",
".",
"profile",
",",
... | Return an instance of the MasterControlProgram.
:rtype: rejected.mcp.MasterControlProgram | [
"Return",
"an",
"instance",
"of",
"the",
"MasterControlProgram",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/controller.py#L42-L51 | train | 30,614 |
gmr/rejected | rejected/controller.py | Controller.setup | def setup(self):
"""Continue the run process blocking on MasterControlProgram.run"""
# If the app was invoked to specified to prepend the path, do so now
if self.args.prepend_path:
self._prepend_python_path(self.args.prepend_path) | python | def setup(self):
"""Continue the run process blocking on MasterControlProgram.run"""
# If the app was invoked to specified to prepend the path, do so now
if self.args.prepend_path:
self._prepend_python_path(self.args.prepend_path) | [
"def",
"setup",
"(",
"self",
")",
":",
"# If the app was invoked to specified to prepend the path, do so now",
"if",
"self",
".",
"args",
".",
"prepend_path",
":",
"self",
".",
"_prepend_python_path",
"(",
"self",
".",
"args",
".",
"prepend_path",
")"
] | Continue the run process blocking on MasterControlProgram.run | [
"Continue",
"the",
"run",
"process",
"blocking",
"on",
"MasterControlProgram",
".",
"run"
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/controller.py#L63-L67 | train | 30,615 |
gmr/rejected | rejected/controller.py | Controller.stop | def stop(self):
"""Shutdown the MCP and child processes cleanly"""
LOGGER.info('Shutting down controller')
self.set_state(self.STATE_STOP_REQUESTED)
# Clear out the timer
signal.setitimer(signal.ITIMER_PROF, 0, 0)
self._mcp.stop_processes()
if self._mcp.is_running:
LOGGER.info('Waiting up to 3 seconds for MCP to shut things down')
signal.setitimer(signal.ITIMER_REAL, 3, 0)
signal.pause()
LOGGER.info('Post pause')
# Force MCP to stop
if self._mcp.is_running:
LOGGER.warning('MCP is taking too long, requesting process kills')
self._mcp.stop_processes()
del self._mcp
else:
LOGGER.info('MCP exited cleanly')
# Change our state
self._stopped()
LOGGER.info('Shutdown complete') | python | def stop(self):
"""Shutdown the MCP and child processes cleanly"""
LOGGER.info('Shutting down controller')
self.set_state(self.STATE_STOP_REQUESTED)
# Clear out the timer
signal.setitimer(signal.ITIMER_PROF, 0, 0)
self._mcp.stop_processes()
if self._mcp.is_running:
LOGGER.info('Waiting up to 3 seconds for MCP to shut things down')
signal.setitimer(signal.ITIMER_REAL, 3, 0)
signal.pause()
LOGGER.info('Post pause')
# Force MCP to stop
if self._mcp.is_running:
LOGGER.warning('MCP is taking too long, requesting process kills')
self._mcp.stop_processes()
del self._mcp
else:
LOGGER.info('MCP exited cleanly')
# Change our state
self._stopped()
LOGGER.info('Shutdown complete') | [
"def",
"stop",
"(",
"self",
")",
":",
"LOGGER",
".",
"info",
"(",
"'Shutting down controller'",
")",
"self",
".",
"set_state",
"(",
"self",
".",
"STATE_STOP_REQUESTED",
")",
"# Clear out the timer",
"signal",
".",
"setitimer",
"(",
"signal",
".",
"ITIMER_PROF",
... | Shutdown the MCP and child processes cleanly | [
"Shutdown",
"the",
"MCP",
"and",
"child",
"processes",
"cleanly"
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/controller.py#L69-L95 | train | 30,616 |
gmr/rejected | rejected/controller.py | Controller.run | def run(self):
"""Run the rejected Application"""
self.setup()
self._mcp = self._master_control_program()
try:
self._mcp.run()
except KeyboardInterrupt:
LOGGER.info('Caught CTRL-C, shutting down')
except Exception:
exc_info = sys.exc_info()
kwargs = {'logger': 'rejected.controller'}
LOGGER.debug('Sending exception to sentry: %r', kwargs)
if self._sentry_client:
self._sentry_client.captureException(exc_info, **kwargs)
raise
if self.is_running:
self.stop() | python | def run(self):
"""Run the rejected Application"""
self.setup()
self._mcp = self._master_control_program()
try:
self._mcp.run()
except KeyboardInterrupt:
LOGGER.info('Caught CTRL-C, shutting down')
except Exception:
exc_info = sys.exc_info()
kwargs = {'logger': 'rejected.controller'}
LOGGER.debug('Sending exception to sentry: %r', kwargs)
if self._sentry_client:
self._sentry_client.captureException(exc_info, **kwargs)
raise
if self.is_running:
self.stop() | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"setup",
"(",
")",
"self",
".",
"_mcp",
"=",
"self",
".",
"_master_control_program",
"(",
")",
"try",
":",
"self",
".",
"_mcp",
".",
"run",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"LOGGER",
".",... | Run the rejected Application | [
"Run",
"the",
"rejected",
"Application"
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/controller.py#L97-L113 | train | 30,617 |
gmr/rejected | rejected/connection.py | Connection.connect | def connect(self):
"""Create the low-level AMQP connection to RabbitMQ.
:rtype: pika.adapters.tornado_connection.TornadoConnection
"""
self.set_state(self.STATE_CONNECTING)
self.handle = tornado_connection.TornadoConnection(
self._connection_parameters,
on_open_callback=self.on_open,
on_open_error_callback=self.on_open_error,
stop_ioloop_on_close=False,
custom_ioloop=self.io_loop) | python | def connect(self):
"""Create the low-level AMQP connection to RabbitMQ.
:rtype: pika.adapters.tornado_connection.TornadoConnection
"""
self.set_state(self.STATE_CONNECTING)
self.handle = tornado_connection.TornadoConnection(
self._connection_parameters,
on_open_callback=self.on_open,
on_open_error_callback=self.on_open_error,
stop_ioloop_on_close=False,
custom_ioloop=self.io_loop) | [
"def",
"connect",
"(",
"self",
")",
":",
"self",
".",
"set_state",
"(",
"self",
".",
"STATE_CONNECTING",
")",
"self",
".",
"handle",
"=",
"tornado_connection",
".",
"TornadoConnection",
"(",
"self",
".",
"_connection_parameters",
",",
"on_open_callback",
"=",
... | Create the low-level AMQP connection to RabbitMQ.
:rtype: pika.adapters.tornado_connection.TornadoConnection | [
"Create",
"the",
"low",
"-",
"level",
"AMQP",
"connection",
"to",
"RabbitMQ",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/connection.py#L109-L121 | train | 30,618 |
gmr/rejected | rejected/connection.py | Connection.shutdown | def shutdown(self):
"""Start the connection shutdown process, cancelling any active
consuming and closing the channel if the connection is not active.
"""
if self.is_shutting_down:
self.logger.debug('Already shutting down')
return
self.set_state(self.STATE_SHUTTING_DOWN)
self.logger.debug('Shutting down connection')
if not self.is_active:
return self.channel.close()
self.logger.debug('Sending a Basic.Cancel to RabbitMQ')
self.channel.basic_cancel(self.on_consumer_cancelled,
self.consumer_tag) | python | def shutdown(self):
"""Start the connection shutdown process, cancelling any active
consuming and closing the channel if the connection is not active.
"""
if self.is_shutting_down:
self.logger.debug('Already shutting down')
return
self.set_state(self.STATE_SHUTTING_DOWN)
self.logger.debug('Shutting down connection')
if not self.is_active:
return self.channel.close()
self.logger.debug('Sending a Basic.Cancel to RabbitMQ')
self.channel.basic_cancel(self.on_consumer_cancelled,
self.consumer_tag) | [
"def",
"shutdown",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_shutting_down",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Already shutting down'",
")",
"return",
"self",
".",
"set_state",
"(",
"self",
".",
"STATE_SHUTTING_DOWN",
")",
"self",
".",
"... | Start the connection shutdown process, cancelling any active
consuming and closing the channel if the connection is not active. | [
"Start",
"the",
"connection",
"shutdown",
"process",
"cancelling",
"any",
"active",
"consuming",
"and",
"closing",
"the",
"channel",
"if",
"the",
"connection",
"is",
"not",
"active",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/connection.py#L132-L147 | train | 30,619 |
gmr/rejected | rejected/connection.py | Connection.on_open | def on_open(self, _handle):
"""Invoked when the connection is opened
:type _handle: pika.adapters.tornado_connection.TornadoConnection
"""
self.logger.debug('Connection opened')
self.handle.add_on_connection_blocked_callback(self.on_blocked)
self.handle.add_on_connection_unblocked_callback(self.on_unblocked)
self.handle.add_on_close_callback(self.on_closed)
self.handle.channel(self.on_channel_open) | python | def on_open(self, _handle):
"""Invoked when the connection is opened
:type _handle: pika.adapters.tornado_connection.TornadoConnection
"""
self.logger.debug('Connection opened')
self.handle.add_on_connection_blocked_callback(self.on_blocked)
self.handle.add_on_connection_unblocked_callback(self.on_unblocked)
self.handle.add_on_close_callback(self.on_closed)
self.handle.channel(self.on_channel_open) | [
"def",
"on_open",
"(",
"self",
",",
"_handle",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Connection opened'",
")",
"self",
".",
"handle",
".",
"add_on_connection_blocked_callback",
"(",
"self",
".",
"on_blocked",
")",
"self",
".",
"handle",
".",
... | Invoked when the connection is opened
:type _handle: pika.adapters.tornado_connection.TornadoConnection | [
"Invoked",
"when",
"the",
"connection",
"is",
"opened"
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/connection.py#L149-L159 | train | 30,620 |
gmr/rejected | rejected/connection.py | Connection.on_channel_open | def on_channel_open(self, channel):
"""This method is invoked by pika when the channel has been opened. It
will change the state to CONNECTED, add the callbacks and setup the
channel to start consuming.
:param pika.channel.Channel channel: The channel object
"""
self.logger.debug('Channel opened')
self.set_state(self.STATE_CONNECTED)
self.channel = channel
self.channel.add_on_close_callback(self.on_channel_closed)
self.channel.add_on_cancel_callback(self.on_consumer_cancelled)
if self.publisher_confirmations:
self.delivery_tag = 0
self.channel.confirm_delivery(self.on_confirmation)
self.channel.add_on_return_callback(self.on_return)
self.callbacks.on_ready(self.name) | python | def on_channel_open(self, channel):
"""This method is invoked by pika when the channel has been opened. It
will change the state to CONNECTED, add the callbacks and setup the
channel to start consuming.
:param pika.channel.Channel channel: The channel object
"""
self.logger.debug('Channel opened')
self.set_state(self.STATE_CONNECTED)
self.channel = channel
self.channel.add_on_close_callback(self.on_channel_closed)
self.channel.add_on_cancel_callback(self.on_consumer_cancelled)
if self.publisher_confirmations:
self.delivery_tag = 0
self.channel.confirm_delivery(self.on_confirmation)
self.channel.add_on_return_callback(self.on_return)
self.callbacks.on_ready(self.name) | [
"def",
"on_channel_open",
"(",
"self",
",",
"channel",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Channel opened'",
")",
"self",
".",
"set_state",
"(",
"self",
".",
"STATE_CONNECTED",
")",
"self",
".",
"channel",
"=",
"channel",
"self",
".",
"... | This method is invoked by pika when the channel has been opened. It
will change the state to CONNECTED, add the callbacks and setup the
channel to start consuming.
:param pika.channel.Channel channel: The channel object | [
"This",
"method",
"is",
"invoked",
"by",
"pika",
"when",
"the",
"channel",
"has",
"been",
"opened",
".",
"It",
"will",
"change",
"the",
"state",
"to",
"CONNECTED",
"add",
"the",
"callbacks",
"and",
"setup",
"the",
"channel",
"to",
"start",
"consuming",
"."... | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/connection.py#L182-L199 | train | 30,621 |
gmr/rejected | rejected/connection.py | Connection.consume | def consume(self, queue_name, no_ack, prefetch_count):
"""Consume messages from RabbitMQ, changing the state, QoS and issuing
the RPC to RabbitMQ to start delivering messages.
:param str queue_name: The name of the queue to consume from
:param False no_ack: Enable no-ack mode
:param int prefetch_count: The number of messages to prefetch
"""
if self.state == self.STATE_ACTIVE:
self.logger.debug('%s already consuming', self.name)
return
self.set_state(self.STATE_ACTIVE)
self.channel.basic_qos(self.on_qos_set, 0, prefetch_count, False)
self.channel.basic_consume(
consumer_callback=self.on_delivery, queue=queue_name,
no_ack=no_ack, consumer_tag=self.consumer_tag) | python | def consume(self, queue_name, no_ack, prefetch_count):
"""Consume messages from RabbitMQ, changing the state, QoS and issuing
the RPC to RabbitMQ to start delivering messages.
:param str queue_name: The name of the queue to consume from
:param False no_ack: Enable no-ack mode
:param int prefetch_count: The number of messages to prefetch
"""
if self.state == self.STATE_ACTIVE:
self.logger.debug('%s already consuming', self.name)
return
self.set_state(self.STATE_ACTIVE)
self.channel.basic_qos(self.on_qos_set, 0, prefetch_count, False)
self.channel.basic_consume(
consumer_callback=self.on_delivery, queue=queue_name,
no_ack=no_ack, consumer_tag=self.consumer_tag) | [
"def",
"consume",
"(",
"self",
",",
"queue_name",
",",
"no_ack",
",",
"prefetch_count",
")",
":",
"if",
"self",
".",
"state",
"==",
"self",
".",
"STATE_ACTIVE",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'%s already consuming'",
",",
"self",
".",
"n... | Consume messages from RabbitMQ, changing the state, QoS and issuing
the RPC to RabbitMQ to start delivering messages.
:param str queue_name: The name of the queue to consume from
:param False no_ack: Enable no-ack mode
:param int prefetch_count: The number of messages to prefetch | [
"Consume",
"messages",
"from",
"RabbitMQ",
"changing",
"the",
"state",
"QoS",
"and",
"issuing",
"the",
"RPC",
"to",
"RabbitMQ",
"to",
"start",
"delivering",
"messages",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/connection.py#L233-L249 | train | 30,622 |
gmr/rejected | rejected/connection.py | Connection.on_consumer_cancelled | def on_consumer_cancelled(self, _frame):
"""Invoked by pika when a ``Basic.Cancel`` or ``Basic.CancelOk``
is received.
:param _frame: The Basic.Cancel or Basic.CancelOk frame
:type _frame: pika.frame.Frame
"""
self.logger.debug('Consumer has been cancelled')
if self.is_shutting_down:
self.channel.close()
else:
self.set_state(self.STATE_CONNECTED) | python | def on_consumer_cancelled(self, _frame):
"""Invoked by pika when a ``Basic.Cancel`` or ``Basic.CancelOk``
is received.
:param _frame: The Basic.Cancel or Basic.CancelOk frame
:type _frame: pika.frame.Frame
"""
self.logger.debug('Consumer has been cancelled')
if self.is_shutting_down:
self.channel.close()
else:
self.set_state(self.STATE_CONNECTED) | [
"def",
"on_consumer_cancelled",
"(",
"self",
",",
"_frame",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Consumer has been cancelled'",
")",
"if",
"self",
".",
"is_shutting_down",
":",
"self",
".",
"channel",
".",
"close",
"(",
")",
"else",
":",
"... | Invoked by pika when a ``Basic.Cancel`` or ``Basic.CancelOk``
is received.
:param _frame: The Basic.Cancel or Basic.CancelOk frame
:type _frame: pika.frame.Frame | [
"Invoked",
"by",
"pika",
"when",
"a",
"Basic",
".",
"Cancel",
"or",
"Basic",
".",
"CancelOk",
"is",
"received",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/connection.py#L259-L271 | train | 30,623 |
gmr/rejected | rejected/connection.py | Connection.on_confirmation | def on_confirmation(self, frame):
"""Invoked by pika when RabbitMQ responds to a Basic.Publish RPC
command, passing in either a Basic.Ack or Basic.Nack frame with
the delivery tag of the message that was published. The delivery tag
is an integer counter indicating the message number that was sent
on the channel via Basic.Publish.
:param pika.frame.Method frame: Basic.Ack or Basic.Nack frame
"""
delivered = frame.method.NAME.split('.')[1].lower() == 'ack'
self.logger.debug('Received publisher confirmation (Delivered: %s)',
delivered)
if frame.method.multiple:
for index in range(self.last_confirmation + 1,
frame.method.delivery_tag):
self.confirm_delivery(index, delivered)
self.confirm_delivery(frame.method.delivery_tag, delivered)
self.last_confirmation = frame.method.delivery_tag | python | def on_confirmation(self, frame):
"""Invoked by pika when RabbitMQ responds to a Basic.Publish RPC
command, passing in either a Basic.Ack or Basic.Nack frame with
the delivery tag of the message that was published. The delivery tag
is an integer counter indicating the message number that was sent
on the channel via Basic.Publish.
:param pika.frame.Method frame: Basic.Ack or Basic.Nack frame
"""
delivered = frame.method.NAME.split('.')[1].lower() == 'ack'
self.logger.debug('Received publisher confirmation (Delivered: %s)',
delivered)
if frame.method.multiple:
for index in range(self.last_confirmation + 1,
frame.method.delivery_tag):
self.confirm_delivery(index, delivered)
self.confirm_delivery(frame.method.delivery_tag, delivered)
self.last_confirmation = frame.method.delivery_tag | [
"def",
"on_confirmation",
"(",
"self",
",",
"frame",
")",
":",
"delivered",
"=",
"frame",
".",
"method",
".",
"NAME",
".",
"split",
"(",
"'.'",
")",
"[",
"1",
"]",
".",
"lower",
"(",
")",
"==",
"'ack'",
"self",
".",
"logger",
".",
"debug",
"(",
"... | Invoked by pika when RabbitMQ responds to a Basic.Publish RPC
command, passing in either a Basic.Ack or Basic.Nack frame with
the delivery tag of the message that was published. The delivery tag
is an integer counter indicating the message number that was sent
on the channel via Basic.Publish.
:param pika.frame.Method frame: Basic.Ack or Basic.Nack frame | [
"Invoked",
"by",
"pika",
"when",
"RabbitMQ",
"responds",
"to",
"a",
"Basic",
".",
"Publish",
"RPC",
"command",
"passing",
"in",
"either",
"a",
"Basic",
".",
"Ack",
"or",
"Basic",
".",
"Nack",
"frame",
"with",
"the",
"delivery",
"tag",
"of",
"the",
"messa... | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/connection.py#L273-L291 | train | 30,624 |
gmr/rejected | rejected/connection.py | Connection.confirm_delivery | def confirm_delivery(self, delivery_tag, delivered):
"""Invoked by RabbitMQ when it is confirming delivery via a Basic.Ack
:param
:param int delivery_tag: The message # being confirmed
:param bool delivered: Was the message delivered
"""
for offset, msg in self.pending_confirmations():
if delivery_tag == msg.delivery_tag:
self.published_messages[offset].future.set_result(delivered)
return
for msg in self.published_messages:
if msg.delivery_tag == delivery_tag and msg.future.done():
return
self.logger.warning('Attempted to confirm publish without future: %r',
delivery_tag) | python | def confirm_delivery(self, delivery_tag, delivered):
"""Invoked by RabbitMQ when it is confirming delivery via a Basic.Ack
:param
:param int delivery_tag: The message # being confirmed
:param bool delivered: Was the message delivered
"""
for offset, msg in self.pending_confirmations():
if delivery_tag == msg.delivery_tag:
self.published_messages[offset].future.set_result(delivered)
return
for msg in self.published_messages:
if msg.delivery_tag == delivery_tag and msg.future.done():
return
self.logger.warning('Attempted to confirm publish without future: %r',
delivery_tag) | [
"def",
"confirm_delivery",
"(",
"self",
",",
"delivery_tag",
",",
"delivered",
")",
":",
"for",
"offset",
",",
"msg",
"in",
"self",
".",
"pending_confirmations",
"(",
")",
":",
"if",
"delivery_tag",
"==",
"msg",
".",
"delivery_tag",
":",
"self",
".",
"publ... | Invoked by RabbitMQ when it is confirming delivery via a Basic.Ack
:param
:param int delivery_tag: The message # being confirmed
:param bool delivered: Was the message delivered | [
"Invoked",
"by",
"RabbitMQ",
"when",
"it",
"is",
"confirming",
"delivery",
"via",
"a",
"Basic",
".",
"Ack"
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/connection.py#L293-L309 | train | 30,625 |
gmr/rejected | rejected/connection.py | Connection.on_delivery | def on_delivery(self, channel, method, properties, body):
"""Invoked by pika when RabbitMQ delivers a message from a queue.
:param channel: The channel the message was delivered on
:type channel: pika.channel.Channel
:param method: The AMQP method frame
:type method: pika.frame.Frame
:param properties: The AMQP message properties
:type properties: pika.spec.Basic.Properties
:param bytes body: The message body
"""
self.callbacks.on_delivery(
self.name, channel, method, properties, body) | python | def on_delivery(self, channel, method, properties, body):
"""Invoked by pika when RabbitMQ delivers a message from a queue.
:param channel: The channel the message was delivered on
:type channel: pika.channel.Channel
:param method: The AMQP method frame
:type method: pika.frame.Frame
:param properties: The AMQP message properties
:type properties: pika.spec.Basic.Properties
:param bytes body: The message body
"""
self.callbacks.on_delivery(
self.name, channel, method, properties, body) | [
"def",
"on_delivery",
"(",
"self",
",",
"channel",
",",
"method",
",",
"properties",
",",
"body",
")",
":",
"self",
".",
"callbacks",
".",
"on_delivery",
"(",
"self",
".",
"name",
",",
"channel",
",",
"method",
",",
"properties",
",",
"body",
")"
] | Invoked by pika when RabbitMQ delivers a message from a queue.
:param channel: The channel the message was delivered on
:type channel: pika.channel.Channel
:param method: The AMQP method frame
:type method: pika.frame.Frame
:param properties: The AMQP message properties
:type properties: pika.spec.Basic.Properties
:param bytes body: The message body | [
"Invoked",
"by",
"pika",
"when",
"RabbitMQ",
"delivers",
"a",
"message",
"from",
"a",
"queue",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/connection.py#L311-L324 | train | 30,626 |
gmr/rejected | rejected/connection.py | Connection.on_return | def on_return(self, channel, method, properties, body):
"""Invoked by RabbitMQ when it returns a message that was published.
:param channel: The channel the message was delivered on
:type channel: pika.channel.Channel
:param method: The AMQP method frame
:type method: pika.frame.Frame
:param properties: The AMQP message properties
:type properties: pika.spec.Basic.Properties
:param bytes body: The message body
"""
pending = self.pending_confirmations()
if not pending: # Exit early if there are no pending messages
self.logger.warning('RabbitMQ returned message %s and no pending '
'messages are unconfirmed',
utils.message_info(method.exchange,
method.routing_key,
properties))
return
self.logger.warning('RabbitMQ returned message %s: (%s) %s',
utils.message_info(method.exchange,
method.routing_key, properties),
method.reply_code, method.reply_text)
# Try and match the exact message or first message published that
# matches the exchange and routing key
for offset, msg in pending:
if (msg.message_id == properties.message_id or
(msg.exchange == method.exchange and
msg.routing_key == method.routing_key)):
self.published_messages[offset].future.set_result(False)
return
# Handle the case where we only can go on message ordering
self.published_messages[0].future.set_result(False) | python | def on_return(self, channel, method, properties, body):
"""Invoked by RabbitMQ when it returns a message that was published.
:param channel: The channel the message was delivered on
:type channel: pika.channel.Channel
:param method: The AMQP method frame
:type method: pika.frame.Frame
:param properties: The AMQP message properties
:type properties: pika.spec.Basic.Properties
:param bytes body: The message body
"""
pending = self.pending_confirmations()
if not pending: # Exit early if there are no pending messages
self.logger.warning('RabbitMQ returned message %s and no pending '
'messages are unconfirmed',
utils.message_info(method.exchange,
method.routing_key,
properties))
return
self.logger.warning('RabbitMQ returned message %s: (%s) %s',
utils.message_info(method.exchange,
method.routing_key, properties),
method.reply_code, method.reply_text)
# Try and match the exact message or first message published that
# matches the exchange and routing key
for offset, msg in pending:
if (msg.message_id == properties.message_id or
(msg.exchange == method.exchange and
msg.routing_key == method.routing_key)):
self.published_messages[offset].future.set_result(False)
return
# Handle the case where we only can go on message ordering
self.published_messages[0].future.set_result(False) | [
"def",
"on_return",
"(",
"self",
",",
"channel",
",",
"method",
",",
"properties",
",",
"body",
")",
":",
"pending",
"=",
"self",
".",
"pending_confirmations",
"(",
")",
"if",
"not",
"pending",
":",
"# Exit early if there are no pending messages",
"self",
".",
... | Invoked by RabbitMQ when it returns a message that was published.
:param channel: The channel the message was delivered on
:type channel: pika.channel.Channel
:param method: The AMQP method frame
:type method: pika.frame.Frame
:param properties: The AMQP message properties
:type properties: pika.spec.Basic.Properties
:param bytes body: The message body | [
"Invoked",
"by",
"RabbitMQ",
"when",
"it",
"returns",
"a",
"message",
"that",
"was",
"published",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/connection.py#L326-L362 | train | 30,627 |
gmr/rejected | rejected/connection.py | Connection.pending_confirmations | def pending_confirmations(self):
"""Return all published messages that have yet to be acked, nacked, or
returned.
:return: [(int, Published)]
"""
return sorted([(idx, msg)
for idx, msg in enumerate(self.published_messages)
if not msg.future.done()],
key=lambda x: x[1].delivery_tag) | python | def pending_confirmations(self):
"""Return all published messages that have yet to be acked, nacked, or
returned.
:return: [(int, Published)]
"""
return sorted([(idx, msg)
for idx, msg in enumerate(self.published_messages)
if not msg.future.done()],
key=lambda x: x[1].delivery_tag) | [
"def",
"pending_confirmations",
"(",
"self",
")",
":",
"return",
"sorted",
"(",
"[",
"(",
"idx",
",",
"msg",
")",
"for",
"idx",
",",
"msg",
"in",
"enumerate",
"(",
"self",
".",
"published_messages",
")",
"if",
"not",
"msg",
".",
"future",
".",
"done",
... | Return all published messages that have yet to be acked, nacked, or
returned.
:return: [(int, Published)] | [
"Return",
"all",
"published",
"messages",
"that",
"have",
"yet",
"to",
"be",
"acked",
"nacked",
"or",
"returned",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/connection.py#L364-L374 | train | 30,628 |
gmr/rejected | rejected/connection.py | Connection._connection_parameters | def _connection_parameters(self):
"""Return connection parameters for a pika connection.
:rtype: pika.ConnectionParameters
"""
return pika.ConnectionParameters(
self.config.get('host', 'localhost'),
self.config.get('port', 5672),
self.config.get('vhost', '/'),
pika.PlainCredentials(
self.config.get('user', 'guest'),
self.config.get('password', self.config.get('pass', 'guest'))),
ssl=self.config.get('ssl', False),
frame_max=self.config.get('frame_max', spec.FRAME_MAX_SIZE),
socket_timeout=self.config.get('socket_timeout', 10),
heartbeat_interval=self.config.get(
'heartbeat_interval', self.HB_INTERVAL)) | python | def _connection_parameters(self):
"""Return connection parameters for a pika connection.
:rtype: pika.ConnectionParameters
"""
return pika.ConnectionParameters(
self.config.get('host', 'localhost'),
self.config.get('port', 5672),
self.config.get('vhost', '/'),
pika.PlainCredentials(
self.config.get('user', 'guest'),
self.config.get('password', self.config.get('pass', 'guest'))),
ssl=self.config.get('ssl', False),
frame_max=self.config.get('frame_max', spec.FRAME_MAX_SIZE),
socket_timeout=self.config.get('socket_timeout', 10),
heartbeat_interval=self.config.get(
'heartbeat_interval', self.HB_INTERVAL)) | [
"def",
"_connection_parameters",
"(",
"self",
")",
":",
"return",
"pika",
".",
"ConnectionParameters",
"(",
"self",
".",
"config",
".",
"get",
"(",
"'host'",
",",
"'localhost'",
")",
",",
"self",
".",
"config",
".",
"get",
"(",
"'port'",
",",
"5672",
")"... | Return connection parameters for a pika connection.
:rtype: pika.ConnectionParameters | [
"Return",
"connection",
"parameters",
"for",
"a",
"pika",
"connection",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/connection.py#L377-L394 | train | 30,629 |
gmr/rejected | rejected/smart_consumer.py | SmartConsumer.publish_message | def publish_message(self,
exchange,
routing_key,
properties,
body,
no_serialization=False,
no_encoding=False,
channel=None,
connection=None):
"""Publish a message to RabbitMQ on the same channel the original
message was received on.
By default, if you pass a non-string object to the body and the
properties have a supported ``content_type`` set, the body will be
auto-serialized in the specified ``content_type``.
If the properties do not have a timestamp set, it will be set to the
current time.
If you specify a ``content_encoding`` in the properties and the
encoding is supported, the body will be auto-encoded.
Both of these behaviors can be disabled by setting
``no_serialization`` or ``no_encoding`` to ``True``.
If you pass an unsupported content-type or content-encoding when using
the auto-serialization and auto-encoding features, a :exc:`ValueError`
will be raised.
.. versionchanged:: 4.0.0
The method returns a :py:class:`~tornado.concurrent.Future` if
`publisher confirmations <https://www.rabbitmq.com/confirms.html>`_
are enabled on for the connection. In addition, The ``channel``
parameter is deprecated and will be removed in a future release.
:param str exchange: The exchange to publish to
:param str routing_key: The routing key to publish with
:param dict properties: The message properties
:param mixed body: The message body to publish
:param bool no_serialization: Turn off auto-serialization of the body
:param bool no_encoding: Turn off auto-encoding of the body
:param str channel: **Deprecated in 4.0.0** Specify the connection
parameter instead.
:param str connection: The connection to use. If it is not
specified, the channel that the message was delivered on is used.
:rtype: tornado.concurrent.Future or None
:raises: ValueError
"""
# Auto-serialize the content if needed
is_string = (isinstance(body, str) or isinstance(body, bytes)
or isinstance(body, unicode))
if not no_serialization and not is_string and \
properties.get('content_type'):
body = self._serialize(
body, headers.parse_content_type(properties['content_type']))
# Auto-encode the message body if needed
if not no_encoding and \
properties.get('content_encoding') in self._CODEC_MAP.keys():
body = self._compress(
body, self._CODEC_MAP[properties['content_encoding']])
return super(SmartConsumer, self).publish_message(
exchange, routing_key, properties, body, channel or connection) | python | def publish_message(self,
exchange,
routing_key,
properties,
body,
no_serialization=False,
no_encoding=False,
channel=None,
connection=None):
"""Publish a message to RabbitMQ on the same channel the original
message was received on.
By default, if you pass a non-string object to the body and the
properties have a supported ``content_type`` set, the body will be
auto-serialized in the specified ``content_type``.
If the properties do not have a timestamp set, it will be set to the
current time.
If you specify a ``content_encoding`` in the properties and the
encoding is supported, the body will be auto-encoded.
Both of these behaviors can be disabled by setting
``no_serialization`` or ``no_encoding`` to ``True``.
If you pass an unsupported content-type or content-encoding when using
the auto-serialization and auto-encoding features, a :exc:`ValueError`
will be raised.
.. versionchanged:: 4.0.0
The method returns a :py:class:`~tornado.concurrent.Future` if
`publisher confirmations <https://www.rabbitmq.com/confirms.html>`_
are enabled on for the connection. In addition, The ``channel``
parameter is deprecated and will be removed in a future release.
:param str exchange: The exchange to publish to
:param str routing_key: The routing key to publish with
:param dict properties: The message properties
:param mixed body: The message body to publish
:param bool no_serialization: Turn off auto-serialization of the body
:param bool no_encoding: Turn off auto-encoding of the body
:param str channel: **Deprecated in 4.0.0** Specify the connection
parameter instead.
:param str connection: The connection to use. If it is not
specified, the channel that the message was delivered on is used.
:rtype: tornado.concurrent.Future or None
:raises: ValueError
"""
# Auto-serialize the content if needed
is_string = (isinstance(body, str) or isinstance(body, bytes)
or isinstance(body, unicode))
if not no_serialization and not is_string and \
properties.get('content_type'):
body = self._serialize(
body, headers.parse_content_type(properties['content_type']))
# Auto-encode the message body if needed
if not no_encoding and \
properties.get('content_encoding') in self._CODEC_MAP.keys():
body = self._compress(
body, self._CODEC_MAP[properties['content_encoding']])
return super(SmartConsumer, self).publish_message(
exchange, routing_key, properties, body, channel or connection) | [
"def",
"publish_message",
"(",
"self",
",",
"exchange",
",",
"routing_key",
",",
"properties",
",",
"body",
",",
"no_serialization",
"=",
"False",
",",
"no_encoding",
"=",
"False",
",",
"channel",
"=",
"None",
",",
"connection",
"=",
"None",
")",
":",
"# A... | Publish a message to RabbitMQ on the same channel the original
message was received on.
By default, if you pass a non-string object to the body and the
properties have a supported ``content_type`` set, the body will be
auto-serialized in the specified ``content_type``.
If the properties do not have a timestamp set, it will be set to the
current time.
If you specify a ``content_encoding`` in the properties and the
encoding is supported, the body will be auto-encoded.
Both of these behaviors can be disabled by setting
``no_serialization`` or ``no_encoding`` to ``True``.
If you pass an unsupported content-type or content-encoding when using
the auto-serialization and auto-encoding features, a :exc:`ValueError`
will be raised.
.. versionchanged:: 4.0.0
The method returns a :py:class:`~tornado.concurrent.Future` if
`publisher confirmations <https://www.rabbitmq.com/confirms.html>`_
are enabled on for the connection. In addition, The ``channel``
parameter is deprecated and will be removed in a future release.
:param str exchange: The exchange to publish to
:param str routing_key: The routing key to publish with
:param dict properties: The message properties
:param mixed body: The message body to publish
:param bool no_serialization: Turn off auto-serialization of the body
:param bool no_encoding: Turn off auto-encoding of the body
:param str channel: **Deprecated in 4.0.0** Specify the connection
parameter instead.
:param str connection: The connection to use. If it is not
specified, the channel that the message was delivered on is used.
:rtype: tornado.concurrent.Future or None
:raises: ValueError | [
"Publish",
"a",
"message",
"to",
"RabbitMQ",
"on",
"the",
"same",
"channel",
"the",
"original",
"message",
"was",
"received",
"on",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/smart_consumer.py#L254-L318 | train | 30,630 |
gmr/rejected | rejected/smart_consumer.py | SmartConsumer.body | def body(self):
"""Return the message body, unencoded if needed,
deserialized if possible.
:rtype: any
"""
if self._message_body: # If already set, return it
return self._message_body
self._message_body = self._maybe_decompress_body()
self._message_body = self._maybe_deserialize_body()
return self._message_body | python | def body(self):
"""Return the message body, unencoded if needed,
deserialized if possible.
:rtype: any
"""
if self._message_body: # If already set, return it
return self._message_body
self._message_body = self._maybe_decompress_body()
self._message_body = self._maybe_deserialize_body()
return self._message_body | [
"def",
"body",
"(",
"self",
")",
":",
"if",
"self",
".",
"_message_body",
":",
"# If already set, return it",
"return",
"self",
".",
"_message_body",
"self",
".",
"_message_body",
"=",
"self",
".",
"_maybe_decompress_body",
"(",
")",
"self",
".",
"_message_body"... | Return the message body, unencoded if needed,
deserialized if possible.
:rtype: any | [
"Return",
"the",
"message",
"body",
"unencoded",
"if",
"needed",
"deserialized",
"if",
"possible",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/smart_consumer.py#L321-L332 | train | 30,631 |
gmr/rejected | rejected/smart_consumer.py | SmartConsumer._compress | def _compress(self, value, module_name):
"""Compress the value passed in using the named compression module.
:param bytes value: The uncompressed value
:rtype: bytes
"""
self.logger.debug('Decompressing with %s', module_name)
if not isinstance(value, bytes):
value = value.encode('utf-8')
return self._maybe_import(module_name).compress(value) | python | def _compress(self, value, module_name):
"""Compress the value passed in using the named compression module.
:param bytes value: The uncompressed value
:rtype: bytes
"""
self.logger.debug('Decompressing with %s', module_name)
if not isinstance(value, bytes):
value = value.encode('utf-8')
return self._maybe_import(module_name).compress(value) | [
"def",
"_compress",
"(",
"self",
",",
"value",
",",
"module_name",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Decompressing with %s'",
",",
"module_name",
")",
"if",
"not",
"isinstance",
"(",
"value",
",",
"bytes",
")",
":",
"value",
"=",
"val... | Compress the value passed in using the named compression module.
:param bytes value: The uncompressed value
:rtype: bytes | [
"Compress",
"the",
"value",
"passed",
"in",
"using",
"the",
"named",
"compression",
"module",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/smart_consumer.py#L334-L344 | train | 30,632 |
gmr/rejected | rejected/smart_consumer.py | SmartConsumer._dump_csv | def _dump_csv(self, rows):
"""Take a list of dicts and return it as a CSV value. The
.. versionchanged:: 4.0.0
:param list rows: A list of lists to return as a CSV
:rtype: str
"""
self.logger.debug('Writing %r', rows)
csv = self._maybe_import('csv')
buff = io.StringIO() if _PYTHON3 else io.BytesIO()
writer = csv.DictWriter(
buff,
sorted(set([k for r in rows for k in r.keys()])),
dialect='excel')
writer.writeheader()
writer.writerows(rows)
value = buff.getvalue()
buff.close()
return value | python | def _dump_csv(self, rows):
"""Take a list of dicts and return it as a CSV value. The
.. versionchanged:: 4.0.0
:param list rows: A list of lists to return as a CSV
:rtype: str
"""
self.logger.debug('Writing %r', rows)
csv = self._maybe_import('csv')
buff = io.StringIO() if _PYTHON3 else io.BytesIO()
writer = csv.DictWriter(
buff,
sorted(set([k for r in rows for k in r.keys()])),
dialect='excel')
writer.writeheader()
writer.writerows(rows)
value = buff.getvalue()
buff.close()
return value | [
"def",
"_dump_csv",
"(",
"self",
",",
"rows",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Writing %r'",
",",
"rows",
")",
"csv",
"=",
"self",
".",
"_maybe_import",
"(",
"'csv'",
")",
"buff",
"=",
"io",
".",
"StringIO",
"(",
")",
"if",
"_P... | Take a list of dicts and return it as a CSV value. The
.. versionchanged:: 4.0.0
:param list rows: A list of lists to return as a CSV
:rtype: str | [
"Take",
"a",
"list",
"of",
"dicts",
"and",
"return",
"it",
"as",
"a",
"CSV",
"value",
".",
"The"
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/smart_consumer.py#L356-L376 | train | 30,633 |
gmr/rejected | rejected/smart_consumer.py | SmartConsumer._maybe_decode | def _maybe_decode(self, value, encoding='utf-8'):
"""If a bytes object is passed in, in the Python 3 environment,
decode it using the specified encoding to turn it to a str instance.
:param mixed value: The value to possibly decode
:param str encoding: The encoding to use
:rtype: str
"""
if _PYTHON3 and isinstance(value, bytes):
try:
return value.decode(encoding)
except Exception as err:
self.logger.exception('Error decoding value: %s', err)
raise MessageException(
str(err), 'decoding-{}'.format(encoding))
return value | python | def _maybe_decode(self, value, encoding='utf-8'):
"""If a bytes object is passed in, in the Python 3 environment,
decode it using the specified encoding to turn it to a str instance.
:param mixed value: The value to possibly decode
:param str encoding: The encoding to use
:rtype: str
"""
if _PYTHON3 and isinstance(value, bytes):
try:
return value.decode(encoding)
except Exception as err:
self.logger.exception('Error decoding value: %s', err)
raise MessageException(
str(err), 'decoding-{}'.format(encoding))
return value | [
"def",
"_maybe_decode",
"(",
"self",
",",
"value",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"if",
"_PYTHON3",
"and",
"isinstance",
"(",
"value",
",",
"bytes",
")",
":",
"try",
":",
"return",
"value",
".",
"decode",
"(",
"encoding",
")",
"except",
"Ex... | If a bytes object is passed in, in the Python 3 environment,
decode it using the specified encoding to turn it to a str instance.
:param mixed value: The value to possibly decode
:param str encoding: The encoding to use
:rtype: str | [
"If",
"a",
"bytes",
"object",
"is",
"passed",
"in",
"in",
"the",
"Python",
"3",
"environment",
"decode",
"it",
"using",
"the",
"specified",
"encoding",
"to",
"turn",
"it",
"to",
"a",
"str",
"instance",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/smart_consumer.py#L424-L440 | train | 30,634 |
gmr/rejected | rejected/smart_consumer.py | SmartConsumer._maybe_decompress_body | def _maybe_decompress_body(self):
"""Attempt to decompress the message body passed in using the named
compression module, if specified.
:rtype: bytes
"""
if self.content_encoding:
if self.content_encoding in self._CODEC_MAP.keys():
module_name = self._CODEC_MAP[self.content_encoding]
self.logger.debug('Decompressing with %s', module_name)
module = self._maybe_import(module_name)
return module.decompress(self._message.body)
self.logger.debug('Unsupported content-encoding: %s',
self.content_encoding)
return self._message.body | python | def _maybe_decompress_body(self):
"""Attempt to decompress the message body passed in using the named
compression module, if specified.
:rtype: bytes
"""
if self.content_encoding:
if self.content_encoding in self._CODEC_MAP.keys():
module_name = self._CODEC_MAP[self.content_encoding]
self.logger.debug('Decompressing with %s', module_name)
module = self._maybe_import(module_name)
return module.decompress(self._message.body)
self.logger.debug('Unsupported content-encoding: %s',
self.content_encoding)
return self._message.body | [
"def",
"_maybe_decompress_body",
"(",
"self",
")",
":",
"if",
"self",
".",
"content_encoding",
":",
"if",
"self",
".",
"content_encoding",
"in",
"self",
".",
"_CODEC_MAP",
".",
"keys",
"(",
")",
":",
"module_name",
"=",
"self",
".",
"_CODEC_MAP",
"[",
"sel... | Attempt to decompress the message body passed in using the named
compression module, if specified.
:rtype: bytes | [
"Attempt",
"to",
"decompress",
"the",
"message",
"body",
"passed",
"in",
"using",
"the",
"named",
"compression",
"module",
"if",
"specified",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/smart_consumer.py#L442-L457 | train | 30,635 |
gmr/rejected | rejected/smart_consumer.py | SmartConsumer._maybe_deserialize_body | def _maybe_deserialize_body(self):
"""Attempt to deserialize the message body based upon the content-type.
:rtype: mixed
"""
if not self.content_type:
return self._message_body
ct = headers.parse_content_type(self.content_type)
key = '{}/{}'.format(ct.content_type, ct.content_subtype)
if key not in self._SERIALIZATION_MAP:
if key not in self._IGNORE_TYPES:
self.logger.debug('Unsupported content-type: %s',
self.content_type)
return self._message_body
elif not self._SERIALIZATION_MAP[key].get('enabled', True):
self.logger.debug('%s is not enabled in the serialization map',
key)
return self._message_body
value = self._message_body
if not self._SERIALIZATION_MAP[key].get('binary'):
value = self._maybe_decode(
self._message_body, ct.parameters.get('charset', 'utf-8'))
return self._maybe_invoke_serialization(value, 'load', key) | python | def _maybe_deserialize_body(self):
"""Attempt to deserialize the message body based upon the content-type.
:rtype: mixed
"""
if not self.content_type:
return self._message_body
ct = headers.parse_content_type(self.content_type)
key = '{}/{}'.format(ct.content_type, ct.content_subtype)
if key not in self._SERIALIZATION_MAP:
if key not in self._IGNORE_TYPES:
self.logger.debug('Unsupported content-type: %s',
self.content_type)
return self._message_body
elif not self._SERIALIZATION_MAP[key].get('enabled', True):
self.logger.debug('%s is not enabled in the serialization map',
key)
return self._message_body
value = self._message_body
if not self._SERIALIZATION_MAP[key].get('binary'):
value = self._maybe_decode(
self._message_body, ct.parameters.get('charset', 'utf-8'))
return self._maybe_invoke_serialization(value, 'load', key) | [
"def",
"_maybe_deserialize_body",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"content_type",
":",
"return",
"self",
".",
"_message_body",
"ct",
"=",
"headers",
".",
"parse_content_type",
"(",
"self",
".",
"content_type",
")",
"key",
"=",
"'{}/{}'",
"."... | Attempt to deserialize the message body based upon the content-type.
:rtype: mixed | [
"Attempt",
"to",
"deserialize",
"the",
"message",
"body",
"based",
"upon",
"the",
"content",
"-",
"type",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/smart_consumer.py#L459-L482 | train | 30,636 |
gmr/rejected | rejected/smart_consumer.py | SmartConsumer._serialize | def _serialize(self, value, ct):
"""Auto-serialization of the value based upon the content-type value.
:param any value: The value to serialize
:param ietfparse.: The content type to serialize
:rtype: str
:raises: ValueError
"""
key = '{}/{}'.format(ct.content_type, ct.content_subtype)
if key not in self._SERIALIZATION_MAP:
raise ValueError('Unsupported content-type: {}'.format(key))
elif not self._SERIALIZATION_MAP[key].get('enabled', True):
self.logger.debug('%s is not enabled in the serialization map',
key)
raise ValueError('Disabled content-type: {}'.format(key))
return self._maybe_invoke_serialization(
self._maybe_decode(value, ct.parameters.get('charset', 'utf-8')),
'dump', key) | python | def _serialize(self, value, ct):
"""Auto-serialization of the value based upon the content-type value.
:param any value: The value to serialize
:param ietfparse.: The content type to serialize
:rtype: str
:raises: ValueError
"""
key = '{}/{}'.format(ct.content_type, ct.content_subtype)
if key not in self._SERIALIZATION_MAP:
raise ValueError('Unsupported content-type: {}'.format(key))
elif not self._SERIALIZATION_MAP[key].get('enabled', True):
self.logger.debug('%s is not enabled in the serialization map',
key)
raise ValueError('Disabled content-type: {}'.format(key))
return self._maybe_invoke_serialization(
self._maybe_decode(value, ct.parameters.get('charset', 'utf-8')),
'dump', key) | [
"def",
"_serialize",
"(",
"self",
",",
"value",
",",
"ct",
")",
":",
"key",
"=",
"'{}/{}'",
".",
"format",
"(",
"ct",
".",
"content_type",
",",
"ct",
".",
"content_subtype",
")",
"if",
"key",
"not",
"in",
"self",
".",
"_SERIALIZATION_MAP",
":",
"raise"... | Auto-serialization of the value based upon the content-type value.
:param any value: The value to serialize
:param ietfparse.: The content type to serialize
:rtype: str
:raises: ValueError | [
"Auto",
"-",
"serialization",
"of",
"the",
"value",
"based",
"upon",
"the",
"content",
"-",
"type",
"value",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/smart_consumer.py#L508-L526 | train | 30,637 |
gmr/rejected | rejected/mixins.py | GarbageCollector.collection_cycle | def collection_cycle(self, value):
"""Set the number of messages to process before invoking ``gc.collect``
:param int value: Cycle size
"""
if value is not None:
self._collection_cycle = value
self._cycles_left = min(self._cycles_left, self._collection_cycle) | python | def collection_cycle(self, value):
"""Set the number of messages to process before invoking ``gc.collect``
:param int value: Cycle size
"""
if value is not None:
self._collection_cycle = value
self._cycles_left = min(self._cycles_left, self._collection_cycle) | [
"def",
"collection_cycle",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"self",
".",
"_collection_cycle",
"=",
"value",
"self",
".",
"_cycles_left",
"=",
"min",
"(",
"self",
".",
"_cycles_left",
",",
"self",
".",
"_collec... | Set the number of messages to process before invoking ``gc.collect``
:param int value: Cycle size | [
"Set",
"the",
"number",
"of",
"messages",
"to",
"process",
"before",
"invoking",
"gc",
".",
"collect"
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/mixins.py#L32-L40 | train | 30,638 |
gmr/rejected | rejected/mixins.py | GarbageCollector.on_finish | def on_finish(self, exc=None):
"""Used to initiate the garbage collection"""
super(GarbageCollector, self).on_finish(exc)
self._cycles_left -= 1
if self._cycles_left <= 0:
num_collected = gc.collect()
self._cycles_left = self.collection_cycle
LOGGER.debug('garbage collection run, %d objects evicted',
num_collected) | python | def on_finish(self, exc=None):
"""Used to initiate the garbage collection"""
super(GarbageCollector, self).on_finish(exc)
self._cycles_left -= 1
if self._cycles_left <= 0:
num_collected = gc.collect()
self._cycles_left = self.collection_cycle
LOGGER.debug('garbage collection run, %d objects evicted',
num_collected) | [
"def",
"on_finish",
"(",
"self",
",",
"exc",
"=",
"None",
")",
":",
"super",
"(",
"GarbageCollector",
",",
"self",
")",
".",
"on_finish",
"(",
"exc",
")",
"self",
".",
"_cycles_left",
"-=",
"1",
"if",
"self",
".",
"_cycles_left",
"<=",
"0",
":",
"num... | Used to initiate the garbage collection | [
"Used",
"to",
"initiate",
"the",
"garbage",
"collection"
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/mixins.py#L42-L50 | train | 30,639 |
gmr/rejected | rejected/consumer.py | Consumer.rpc_reply | def rpc_reply(self,
body,
properties=None,
exchange=None,
reply_to=None,
connection=None):
"""Reply to the message that is currently being processed.
.. versionadded:: 4.0.0
If the exchange is not specified, the exchange of the message that is
currently being processed by the Consumer will be used.
If ``reply_to`` is not provided, it will attempt to use the
``reply_to`` property of the message that is currently being processed
by the consumer. If both are not set, a :exc:`ValueError` is raised.
If any of the following message properties are not provided, they will
automatically be assigned:
- ``app_id``
- ``correlation_id``
- ``message_id``
- ``timestamp``
The ``correlation_id`` will only be automatically assigned if the
original message provided a ``message_id``.
If the connection that the message is being published on has publisher
confirmations enabled, a :py:class:`~tornado.concurrent.Future` is
returned.
:param body: The message body
:type body: :class:`bytes` or :class:`str`
:param properties: The AMQP properties to use for the reply message
:type properties: :class:`dict` or :data:`None`
:param exchange: The exchange to publish to. Defaults to the exchange
of the message that is currently being processed by the Consumer.
:type exchange: :class:`str` or :data:`None`
:param reply_to: The routing key to send the reply to. Defaults to the
reply_to property of the message that is currently being processed
by the Consumer. If neither are set, a :exc:`ValueError` is
raised.
:type reply_to: class:`str` or :data:`None`
:param connection: The connection to use. If it is not
specified, the channel that the message was delivered on is used.
:type connection: :class:`str`
:rtype: :class:`tornado.concurrent.Future` or :data:`None`
:raises: :exc:`ValueError`
"""
if reply_to is None and self.reply_to is None:
raise ValueError('Missing reply_to routing key')
properties = properties or {}
if not properties.get('app_id'):
properties['app_id'] = self.name
if not properties.get('correlation_id') and self.message_id:
properties['correlation_id'] = self.message_id
if not properties.get('message_id'):
properties['message_id'] = str(uuid.uuid4())
if not properties.get('timestamp'):
properties['timestamp'] = int(time.time())
return self.publish_message(exchange or self.exchange, reply_to
or self.reply_to, properties, body,
connection) | python | def rpc_reply(self,
body,
properties=None,
exchange=None,
reply_to=None,
connection=None):
"""Reply to the message that is currently being processed.
.. versionadded:: 4.0.0
If the exchange is not specified, the exchange of the message that is
currently being processed by the Consumer will be used.
If ``reply_to`` is not provided, it will attempt to use the
``reply_to`` property of the message that is currently being processed
by the consumer. If both are not set, a :exc:`ValueError` is raised.
If any of the following message properties are not provided, they will
automatically be assigned:
- ``app_id``
- ``correlation_id``
- ``message_id``
- ``timestamp``
The ``correlation_id`` will only be automatically assigned if the
original message provided a ``message_id``.
If the connection that the message is being published on has publisher
confirmations enabled, a :py:class:`~tornado.concurrent.Future` is
returned.
:param body: The message body
:type body: :class:`bytes` or :class:`str`
:param properties: The AMQP properties to use for the reply message
:type properties: :class:`dict` or :data:`None`
:param exchange: The exchange to publish to. Defaults to the exchange
of the message that is currently being processed by the Consumer.
:type exchange: :class:`str` or :data:`None`
:param reply_to: The routing key to send the reply to. Defaults to the
reply_to property of the message that is currently being processed
by the Consumer. If neither are set, a :exc:`ValueError` is
raised.
:type reply_to: class:`str` or :data:`None`
:param connection: The connection to use. If it is not
specified, the channel that the message was delivered on is used.
:type connection: :class:`str`
:rtype: :class:`tornado.concurrent.Future` or :data:`None`
:raises: :exc:`ValueError`
"""
if reply_to is None and self.reply_to is None:
raise ValueError('Missing reply_to routing key')
properties = properties or {}
if not properties.get('app_id'):
properties['app_id'] = self.name
if not properties.get('correlation_id') and self.message_id:
properties['correlation_id'] = self.message_id
if not properties.get('message_id'):
properties['message_id'] = str(uuid.uuid4())
if not properties.get('timestamp'):
properties['timestamp'] = int(time.time())
return self.publish_message(exchange or self.exchange, reply_to
or self.reply_to, properties, body,
connection) | [
"def",
"rpc_reply",
"(",
"self",
",",
"body",
",",
"properties",
"=",
"None",
",",
"exchange",
"=",
"None",
",",
"reply_to",
"=",
"None",
",",
"connection",
"=",
"None",
")",
":",
"if",
"reply_to",
"is",
"None",
"and",
"self",
".",
"reply_to",
"is",
... | Reply to the message that is currently being processed.
.. versionadded:: 4.0.0
If the exchange is not specified, the exchange of the message that is
currently being processed by the Consumer will be used.
If ``reply_to`` is not provided, it will attempt to use the
``reply_to`` property of the message that is currently being processed
by the consumer. If both are not set, a :exc:`ValueError` is raised.
If any of the following message properties are not provided, they will
automatically be assigned:
- ``app_id``
- ``correlation_id``
- ``message_id``
- ``timestamp``
The ``correlation_id`` will only be automatically assigned if the
original message provided a ``message_id``.
If the connection that the message is being published on has publisher
confirmations enabled, a :py:class:`~tornado.concurrent.Future` is
returned.
:param body: The message body
:type body: :class:`bytes` or :class:`str`
:param properties: The AMQP properties to use for the reply message
:type properties: :class:`dict` or :data:`None`
:param exchange: The exchange to publish to. Defaults to the exchange
of the message that is currently being processed by the Consumer.
:type exchange: :class:`str` or :data:`None`
:param reply_to: The routing key to send the reply to. Defaults to the
reply_to property of the message that is currently being processed
by the Consumer. If neither are set, a :exc:`ValueError` is
raised.
:type reply_to: class:`str` or :data:`None`
:param connection: The connection to use. If it is not
specified, the channel that the message was delivered on is used.
:type connection: :class:`str`
:rtype: :class:`tornado.concurrent.Future` or :data:`None`
:raises: :exc:`ValueError` | [
"Reply",
"to",
"the",
"message",
"that",
"is",
"currently",
"being",
"processed",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/consumer.py#L612-L676 | train | 30,640 |
gmr/rejected | rejected/consumer.py | Consumer.set_sentry_context | def set_sentry_context(self, tag, value):
"""Set a context tag in Sentry for the given key and value.
:param tag: The context tag name
:type tag: :class:`str`
:param value: The context value
:type value: :class:`str`
"""
if self.sentry_client:
self.logger.debug('Setting sentry context for %s to %s', tag,
value)
self.sentry_client.tags_context({tag: value}) | python | def set_sentry_context(self, tag, value):
"""Set a context tag in Sentry for the given key and value.
:param tag: The context tag name
:type tag: :class:`str`
:param value: The context value
:type value: :class:`str`
"""
if self.sentry_client:
self.logger.debug('Setting sentry context for %s to %s', tag,
value)
self.sentry_client.tags_context({tag: value}) | [
"def",
"set_sentry_context",
"(",
"self",
",",
"tag",
",",
"value",
")",
":",
"if",
"self",
".",
"sentry_client",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Setting sentry context for %s to %s'",
",",
"tag",
",",
"value",
")",
"self",
".",
"sentry_clie... | Set a context tag in Sentry for the given key and value.
:param tag: The context tag name
:type tag: :class:`str`
:param value: The context value
:type value: :class:`str` | [
"Set",
"a",
"context",
"tag",
"in",
"Sentry",
"for",
"the",
"given",
"key",
"and",
"value",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/consumer.py#L688-L700 | train | 30,641 |
gmr/rejected | rejected/consumer.py | Consumer.stats_add_duration | def stats_add_duration(self, key, duration):
"""Add a duration to the per-message measurements
.. versionadded:: 3.19.0
.. note:: If this method is called when there is not a message being
processed, a message will be logged at the ``warning`` level to
indicate the value is being dropped. To suppress these warnings,
set the :attr:`~rejected.consumer.Consumer.IGNORE_OOB_STATS`
attribute to :data:`True`.
:param key: The key to add the timing to
:type key: :class:`str`
:param duration: The timing value in seconds
:type duration: :class:`int` or :class:`float`
"""
if not self._measurement:
if not self.IGNORE_OOB_STATS:
self.logger.warning(
'stats_add_timing invoked outside execution')
return
self._measurement.add_duration(key, duration) | python | def stats_add_duration(self, key, duration):
"""Add a duration to the per-message measurements
.. versionadded:: 3.19.0
.. note:: If this method is called when there is not a message being
processed, a message will be logged at the ``warning`` level to
indicate the value is being dropped. To suppress these warnings,
set the :attr:`~rejected.consumer.Consumer.IGNORE_OOB_STATS`
attribute to :data:`True`.
:param key: The key to add the timing to
:type key: :class:`str`
:param duration: The timing value in seconds
:type duration: :class:`int` or :class:`float`
"""
if not self._measurement:
if not self.IGNORE_OOB_STATS:
self.logger.warning(
'stats_add_timing invoked outside execution')
return
self._measurement.add_duration(key, duration) | [
"def",
"stats_add_duration",
"(",
"self",
",",
"key",
",",
"duration",
")",
":",
"if",
"not",
"self",
".",
"_measurement",
":",
"if",
"not",
"self",
".",
"IGNORE_OOB_STATS",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"'stats_add_timing invoked outside ex... | Add a duration to the per-message measurements
.. versionadded:: 3.19.0
.. note:: If this method is called when there is not a message being
processed, a message will be logged at the ``warning`` level to
indicate the value is being dropped. To suppress these warnings,
set the :attr:`~rejected.consumer.Consumer.IGNORE_OOB_STATS`
attribute to :data:`True`.
:param key: The key to add the timing to
:type key: :class:`str`
:param duration: The timing value in seconds
:type duration: :class:`int` or :class:`float` | [
"Add",
"a",
"duration",
"to",
"the",
"per",
"-",
"message",
"measurements"
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/consumer.py#L702-L724 | train | 30,642 |
gmr/rejected | rejected/consumer.py | Consumer.stats_incr | def stats_incr(self, key, value=1):
"""Increment the specified key in the per-message measurements
.. versionadded:: 3.13.0
.. note:: If this method is called when there is not a message being
processed, a message will be logged at the ``warning`` level to
indicate the value is being dropped. To suppress these warnings,
set the :attr:`rejected.consumer.Consumer.IGNORE_OOB_STATS`
attribute to :data:`True`.
:param key: The key to increment
:type key: :class:`str`
:param value: The value to increment the key by
:type value: :class:`int`
"""
if not self._measurement:
if not self.IGNORE_OOB_STATS:
self.logger.warning('stats_incr invoked outside execution')
return
self._measurement.incr(key, value) | python | def stats_incr(self, key, value=1):
"""Increment the specified key in the per-message measurements
.. versionadded:: 3.13.0
.. note:: If this method is called when there is not a message being
processed, a message will be logged at the ``warning`` level to
indicate the value is being dropped. To suppress these warnings,
set the :attr:`rejected.consumer.Consumer.IGNORE_OOB_STATS`
attribute to :data:`True`.
:param key: The key to increment
:type key: :class:`str`
:param value: The value to increment the key by
:type value: :class:`int`
"""
if not self._measurement:
if not self.IGNORE_OOB_STATS:
self.logger.warning('stats_incr invoked outside execution')
return
self._measurement.incr(key, value) | [
"def",
"stats_incr",
"(",
"self",
",",
"key",
",",
"value",
"=",
"1",
")",
":",
"if",
"not",
"self",
".",
"_measurement",
":",
"if",
"not",
"self",
".",
"IGNORE_OOB_STATS",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"'stats_incr invoked outside execu... | Increment the specified key in the per-message measurements
.. versionadded:: 3.13.0
.. note:: If this method is called when there is not a message being
processed, a message will be logged at the ``warning`` level to
indicate the value is being dropped. To suppress these warnings,
set the :attr:`rejected.consumer.Consumer.IGNORE_OOB_STATS`
attribute to :data:`True`.
:param key: The key to increment
:type key: :class:`str`
:param value: The value to increment the key by
:type value: :class:`int` | [
"Increment",
"the",
"specified",
"key",
"in",
"the",
"per",
"-",
"message",
"measurements"
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/consumer.py#L726-L747 | train | 30,643 |
gmr/rejected | rejected/consumer.py | Consumer.stats_track_duration | def stats_track_duration(self, key):
"""Time around a context and add to the the per-message measurements
.. versionadded:: 3.19.0
.. note:: If this method is called when there is not a message being
processed, a message will be logged at the ``warning`` level to
indicate the value is being dropped. To suppress these warnings,
set the :attr:`rejected.consumer.Consumer.IGNORE_OOB_STATS`
attribute to :data:`True`.
.. code-block:: python
:caption: Example Usage
class Test(consumer.Consumer):
@gen.coroutine
def process(self):
with self.stats_track_duration('track-time'):
yield self._time_consuming_function()
:param key: The key for the timing to track
:type key: :class:`str`
"""
start_time = time.time()
try:
yield
finally:
self.stats_add_duration(
key, max(start_time, time.time()) - start_time) | python | def stats_track_duration(self, key):
"""Time around a context and add to the the per-message measurements
.. versionadded:: 3.19.0
.. note:: If this method is called when there is not a message being
processed, a message will be logged at the ``warning`` level to
indicate the value is being dropped. To suppress these warnings,
set the :attr:`rejected.consumer.Consumer.IGNORE_OOB_STATS`
attribute to :data:`True`.
.. code-block:: python
:caption: Example Usage
class Test(consumer.Consumer):
@gen.coroutine
def process(self):
with self.stats_track_duration('track-time'):
yield self._time_consuming_function()
:param key: The key for the timing to track
:type key: :class:`str`
"""
start_time = time.time()
try:
yield
finally:
self.stats_add_duration(
key, max(start_time, time.time()) - start_time) | [
"def",
"stats_track_duration",
"(",
"self",
",",
"key",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"try",
":",
"yield",
"finally",
":",
"self",
".",
"stats_add_duration",
"(",
"key",
",",
"max",
"(",
"start_time",
",",
"time",
".",
"ti... | Time around a context and add to the the per-message measurements
.. versionadded:: 3.19.0
.. note:: If this method is called when there is not a message being
processed, a message will be logged at the ``warning`` level to
indicate the value is being dropped. To suppress these warnings,
set the :attr:`rejected.consumer.Consumer.IGNORE_OOB_STATS`
attribute to :data:`True`.
.. code-block:: python
:caption: Example Usage
class Test(consumer.Consumer):
@gen.coroutine
def process(self):
with self.stats_track_duration('track-time'):
yield self._time_consuming_function()
:param key: The key for the timing to track
:type key: :class:`str` | [
"Time",
"around",
"a",
"context",
"and",
"add",
"to",
"the",
"the",
"per",
"-",
"message",
"measurements"
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/consumer.py#L797-L828 | train | 30,644 |
gmr/rejected | rejected/consumer.py | Consumer.unset_sentry_context | def unset_sentry_context(self, tag):
"""Remove a context tag from sentry
:param tag: The context tag to remove
:type tag: :class:`str`
"""
if self.sentry_client:
self.sentry_client.tags.pop(tag, None) | python | def unset_sentry_context(self, tag):
"""Remove a context tag from sentry
:param tag: The context tag to remove
:type tag: :class:`str`
"""
if self.sentry_client:
self.sentry_client.tags.pop(tag, None) | [
"def",
"unset_sentry_context",
"(",
"self",
",",
"tag",
")",
":",
"if",
"self",
".",
"sentry_client",
":",
"self",
".",
"sentry_client",
".",
"tags",
".",
"pop",
"(",
"tag",
",",
"None",
")"
] | Remove a context tag from sentry
:param tag: The context tag to remove
:type tag: :class:`str` | [
"Remove",
"a",
"context",
"tag",
"from",
"sentry"
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/consumer.py#L830-L838 | train | 30,645 |
gmr/rejected | rejected/consumer.py | Consumer.yield_to_ioloop | def yield_to_ioloop(self):
"""Function that will allow Rejected to process IOLoop events while
in a tight-loop inside an asynchronous consumer.
.. code-block:: python
:caption: Example Usage
class Consumer(consumer.Consumer):
@gen.coroutine
def process(self):
for iteration in range(0, 1000000):
yield self.yield_to_ioloop()
"""
try:
yield self._yield_condition.wait(
self._message.channel.connection.ioloop.time() + 0.001)
except gen.TimeoutError:
pass | python | def yield_to_ioloop(self):
"""Function that will allow Rejected to process IOLoop events while
in a tight-loop inside an asynchronous consumer.
.. code-block:: python
:caption: Example Usage
class Consumer(consumer.Consumer):
@gen.coroutine
def process(self):
for iteration in range(0, 1000000):
yield self.yield_to_ioloop()
"""
try:
yield self._yield_condition.wait(
self._message.channel.connection.ioloop.time() + 0.001)
except gen.TimeoutError:
pass | [
"def",
"yield_to_ioloop",
"(",
"self",
")",
":",
"try",
":",
"yield",
"self",
".",
"_yield_condition",
".",
"wait",
"(",
"self",
".",
"_message",
".",
"channel",
".",
"connection",
".",
"ioloop",
".",
"time",
"(",
")",
"+",
"0.001",
")",
"except",
"gen... | Function that will allow Rejected to process IOLoop events while
in a tight-loop inside an asynchronous consumer.
.. code-block:: python
:caption: Example Usage
class Consumer(consumer.Consumer):
@gen.coroutine
def process(self):
for iteration in range(0, 1000000):
yield self.yield_to_ioloop() | [
"Function",
"that",
"will",
"allow",
"Rejected",
"to",
"process",
"IOLoop",
"events",
"while",
"in",
"a",
"tight",
"-",
"loop",
"inside",
"an",
"asynchronous",
"consumer",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/consumer.py#L841-L860 | train | 30,646 |
gmr/rejected | rejected/consumer.py | Consumer.execute | def execute(self, message_in, measurement):
"""Process the message from RabbitMQ. To implement logic for processing
a message, extend Consumer._process, not this method.
This for internal use and should not be extended or used directly.
:param message_in: The message to process
:type message_in: :class:`rejected.data.Message`
:param measurement: For collecting per-message instrumentation
:type measurement: :class:`rejected.data.Measurement`
"""
self.logger.debug('Received: %r', message_in)
try:
self._preprocess(message_in, measurement)
except DropMessage:
raise gen.Return(data.MESSAGE_DROP)
except MessageException as exc:
raise gen.Return(self._on_message_exception(exc))
try:
yield self._execute()
except ExecutionFinished as exc:
self.logger.debug('Execution finished early')
if not self._finished:
self.on_finish(exc)
except RabbitMQException as exc:
self._handle_exception(exc)
raise gen.Return(data.RABBITMQ_EXCEPTION)
except ConfigurationException as exc:
self._handle_exception(exc)
raise gen.Return(data.CONFIGURATION_EXCEPTION)
except ConsumerException as exc:
self._handle_exception(exc)
raise gen.Return(data.CONSUMER_EXCEPTION)
except MessageException as exc:
raise gen.Return(self._on_message_exception(exc))
except ProcessingException as exc:
self._handle_exception(exc)
self._republish_processing_error(
exc.metric or exc.__class__.__name__)
raise gen.Return(data.PROCESSING_EXCEPTION)
except (NotImplementedError, Exception) as exc:
self._handle_exception(exc)
raise gen.Return(data.UNHANDLED_EXCEPTION)
else:
self._finished = True
self._maybe_clear_confirmation_futures()
raise gen.Return(data.MESSAGE_ACK) | python | def execute(self, message_in, measurement):
"""Process the message from RabbitMQ. To implement logic for processing
a message, extend Consumer._process, not this method.
This for internal use and should not be extended or used directly.
:param message_in: The message to process
:type message_in: :class:`rejected.data.Message`
:param measurement: For collecting per-message instrumentation
:type measurement: :class:`rejected.data.Measurement`
"""
self.logger.debug('Received: %r', message_in)
try:
self._preprocess(message_in, measurement)
except DropMessage:
raise gen.Return(data.MESSAGE_DROP)
except MessageException as exc:
raise gen.Return(self._on_message_exception(exc))
try:
yield self._execute()
except ExecutionFinished as exc:
self.logger.debug('Execution finished early')
if not self._finished:
self.on_finish(exc)
except RabbitMQException as exc:
self._handle_exception(exc)
raise gen.Return(data.RABBITMQ_EXCEPTION)
except ConfigurationException as exc:
self._handle_exception(exc)
raise gen.Return(data.CONFIGURATION_EXCEPTION)
except ConsumerException as exc:
self._handle_exception(exc)
raise gen.Return(data.CONSUMER_EXCEPTION)
except MessageException as exc:
raise gen.Return(self._on_message_exception(exc))
except ProcessingException as exc:
self._handle_exception(exc)
self._republish_processing_error(
exc.metric or exc.__class__.__name__)
raise gen.Return(data.PROCESSING_EXCEPTION)
except (NotImplementedError, Exception) as exc:
self._handle_exception(exc)
raise gen.Return(data.UNHANDLED_EXCEPTION)
else:
self._finished = True
self._maybe_clear_confirmation_futures()
raise gen.Return(data.MESSAGE_ACK) | [
"def",
"execute",
"(",
"self",
",",
"message_in",
",",
"measurement",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Received: %r'",
",",
"message_in",
")",
"try",
":",
"self",
".",
"_preprocess",
"(",
"message_in",
",",
"measurement",
")",
"except"... | Process the message from RabbitMQ. To implement logic for processing
a message, extend Consumer._process, not this method.
This for internal use and should not be extended or used directly.
:param message_in: The message to process
:type message_in: :class:`rejected.data.Message`
:param measurement: For collecting per-message instrumentation
:type measurement: :class:`rejected.data.Measurement` | [
"Process",
"the",
"message",
"from",
"RabbitMQ",
".",
"To",
"implement",
"logic",
"for",
"processing",
"a",
"message",
"extend",
"Consumer",
".",
"_process",
"not",
"this",
"method",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/consumer.py#L865-L922 | train | 30,647 |
gmr/rejected | rejected/consumer.py | Consumer._clear | def _clear(self):
"""Resets all assigned data for the current message."""
self._finished = False
self._measurement = None
self._message = None
self._message_body = None | python | def _clear(self):
"""Resets all assigned data for the current message."""
self._finished = False
self._measurement = None
self._message = None
self._message_body = None | [
"def",
"_clear",
"(",
"self",
")",
":",
"self",
".",
"_finished",
"=",
"False",
"self",
".",
"_measurement",
"=",
"None",
"self",
".",
"_message",
"=",
"None",
"self",
".",
"_message_body",
"=",
"None"
] | Resets all assigned data for the current message. | [
"Resets",
"all",
"assigned",
"data",
"for",
"the",
"current",
"message",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/consumer.py#L956-L961 | train | 30,648 |
gmr/rejected | rejected/consumer.py | Consumer._handle_exception | def _handle_exception(self, exc):
"""Common exception handling behavior across all exceptions.
.. note:: This for internal use and should not be extended or used
directly.
"""
exc_info = sys.exc_info()
self.logger.exception(
'%s while processing message #%s',
exc.__class__.__name__, self._message.delivery_tag,
exc_info=exc_info)
self._measurement.set_tag('exception', exc.__class__.__name__)
if hasattr(exc, 'metric') and exc.metric:
self._measurement.set_tag('error', exc.metric)
self._process.send_exception_to_sentry(exc_info)
self._maybe_clear_confirmation_futures()
if not self._finished:
self.on_finish(exc)
self._finished = True | python | def _handle_exception(self, exc):
"""Common exception handling behavior across all exceptions.
.. note:: This for internal use and should not be extended or used
directly.
"""
exc_info = sys.exc_info()
self.logger.exception(
'%s while processing message #%s',
exc.__class__.__name__, self._message.delivery_tag,
exc_info=exc_info)
self._measurement.set_tag('exception', exc.__class__.__name__)
if hasattr(exc, 'metric') and exc.metric:
self._measurement.set_tag('error', exc.metric)
self._process.send_exception_to_sentry(exc_info)
self._maybe_clear_confirmation_futures()
if not self._finished:
self.on_finish(exc)
self._finished = True | [
"def",
"_handle_exception",
"(",
"self",
",",
"exc",
")",
":",
"exc_info",
"=",
"sys",
".",
"exc_info",
"(",
")",
"self",
".",
"logger",
".",
"exception",
"(",
"'%s while processing message #%s'",
",",
"exc",
".",
"__class__",
".",
"__name__",
",",
"self",
... | Common exception handling behavior across all exceptions.
.. note:: This for internal use and should not be extended or used
directly. | [
"Common",
"exception",
"handling",
"behavior",
"across",
"all",
"exceptions",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/consumer.py#L990-L1009 | train | 30,649 |
gmr/rejected | rejected/consumer.py | Consumer._maybe_clear_confirmation_futures | def _maybe_clear_confirmation_futures(self):
"""Invoked when the message has finished processing, ensuring there
are no confirmation futures pending.
"""
for name in self._connections.keys():
self._connections[name].clear_confirmation_futures() | python | def _maybe_clear_confirmation_futures(self):
"""Invoked when the message has finished processing, ensuring there
are no confirmation futures pending.
"""
for name in self._connections.keys():
self._connections[name].clear_confirmation_futures() | [
"def",
"_maybe_clear_confirmation_futures",
"(",
"self",
")",
":",
"for",
"name",
"in",
"self",
".",
"_connections",
".",
"keys",
"(",
")",
":",
"self",
".",
"_connections",
"[",
"name",
"]",
".",
"clear_confirmation_futures",
"(",
")"
] | Invoked when the message has finished processing, ensuring there
are no confirmation futures pending. | [
"Invoked",
"when",
"the",
"message",
"has",
"finished",
"processing",
"ensuring",
"there",
"are",
"no",
"confirmation",
"futures",
"pending",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/consumer.py#L1011-L1017 | train | 30,650 |
gmr/rejected | rejected/consumer.py | Consumer._maybe_set_message_age | def _maybe_set_message_age(self):
"""If timestamp is set and the relative age is > 0, record age of the
message coming in
"""
if self._message.properties.timestamp:
message_age = float(
max(self._message.properties.timestamp, time.time()) -
self._message.properties.timestamp)
if message_age > 0:
self.measurement.add_duration(
self.message_age_key(), message_age) | python | def _maybe_set_message_age(self):
"""If timestamp is set and the relative age is > 0, record age of the
message coming in
"""
if self._message.properties.timestamp:
message_age = float(
max(self._message.properties.timestamp, time.time()) -
self._message.properties.timestamp)
if message_age > 0:
self.measurement.add_duration(
self.message_age_key(), message_age) | [
"def",
"_maybe_set_message_age",
"(",
"self",
")",
":",
"if",
"self",
".",
"_message",
".",
"properties",
".",
"timestamp",
":",
"message_age",
"=",
"float",
"(",
"max",
"(",
"self",
".",
"_message",
".",
"properties",
".",
"timestamp",
",",
"time",
".",
... | If timestamp is set and the relative age is > 0, record age of the
message coming in | [
"If",
"timestamp",
"is",
"set",
"and",
"the",
"relative",
"age",
"is",
">",
"0",
"record",
"age",
"of",
"the",
"message",
"coming",
"in"
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/consumer.py#L1036-L1047 | train | 30,651 |
gmr/rejected | rejected/consumer.py | Consumer._preprocess | def _preprocess(self, message_in, measurement):
"""Invoked at the start of execution, setting internal state,
validating that the message should be processed and not dropped.
:param message_in: The message to process
:type message_in: :class:`rejected.data.Message`
:param measurement: For collecting per-message instrumentation
:type measurement: :class:`rejected.data.Measurement`
:raises: rejected.errors.MessageException
:raises: rejected.errors.DropMessage
"""
self._clear()
self._message = message_in
self._measurement = measurement
self._maybe_set_message_age()
# Ensure there is a correlation ID
self._correlation_id = (
self._message.properties.correlation_id or
self._message.properties.message_id or
str(uuid.uuid4()))
# Set the Correlation ID for the connection for logging
self._connections[self._message.connection].correlation_id = \
self._correlation_id
# Set the sentry context for the message type if set
if self.message_type:
self.set_sentry_context('type', self.message_type)
# Validate the message type if validation is turned on
if self._message_type:
self._validate_message_type()
# Check the number of ProcessingErrors and possibly drop the message
if self._error_max_retry and _PROCESSING_EXCEPTIONS in self.headers:
self._maybe_drop_message() | python | def _preprocess(self, message_in, measurement):
"""Invoked at the start of execution, setting internal state,
validating that the message should be processed and not dropped.
:param message_in: The message to process
:type message_in: :class:`rejected.data.Message`
:param measurement: For collecting per-message instrumentation
:type measurement: :class:`rejected.data.Measurement`
:raises: rejected.errors.MessageException
:raises: rejected.errors.DropMessage
"""
self._clear()
self._message = message_in
self._measurement = measurement
self._maybe_set_message_age()
# Ensure there is a correlation ID
self._correlation_id = (
self._message.properties.correlation_id or
self._message.properties.message_id or
str(uuid.uuid4()))
# Set the Correlation ID for the connection for logging
self._connections[self._message.connection].correlation_id = \
self._correlation_id
# Set the sentry context for the message type if set
if self.message_type:
self.set_sentry_context('type', self.message_type)
# Validate the message type if validation is turned on
if self._message_type:
self._validate_message_type()
# Check the number of ProcessingErrors and possibly drop the message
if self._error_max_retry and _PROCESSING_EXCEPTIONS in self.headers:
self._maybe_drop_message() | [
"def",
"_preprocess",
"(",
"self",
",",
"message_in",
",",
"measurement",
")",
":",
"self",
".",
"_clear",
"(",
")",
"self",
".",
"_message",
"=",
"message_in",
"self",
".",
"_measurement",
"=",
"measurement",
"self",
".",
"_maybe_set_message_age",
"(",
")",... | Invoked at the start of execution, setting internal state,
validating that the message should be processed and not dropped.
:param message_in: The message to process
:type message_in: :class:`rejected.data.Message`
:param measurement: For collecting per-message instrumentation
:type measurement: :class:`rejected.data.Measurement`
:raises: rejected.errors.MessageException
:raises: rejected.errors.DropMessage | [
"Invoked",
"at",
"the",
"start",
"of",
"execution",
"setting",
"internal",
"state",
"validating",
"that",
"the",
"message",
"should",
"be",
"processed",
"and",
"not",
"dropped",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/consumer.py#L1060-L1098 | train | 30,652 |
gmr/rejected | rejected/consumer.py | Consumer._publisher_confirmation_future | def _publisher_confirmation_future(self, name, exchange, routing_key,
properties):
"""Return a future a publisher confirmation result that enables
consumers to block on the confirmation of a published message.
Two internal dicts are used for keeping track of state.
Consumer._delivery_tags is a dict of connection names that keeps
the last delivery tag expectation and is used to correlate the future
with the delivery tag that is expected to be confirmed from RabbitMQ.
This for internal use and should not be extended or used directly.
:param str name: The connection name for the future
:param str exchange: The exchange the message was published to
:param str routing_key: The routing key that was used
:param properties: The AMQP message properties for the delivery
:type properties: pika.spec.Basic.Properties
:rtype: concurrent.Future.
"""
if self._connections[name].publisher_confirmations:
future = concurrent.Future()
self._connections[name].add_confirmation_future(
exchange, routing_key, properties, future)
return future | python | def _publisher_confirmation_future(self, name, exchange, routing_key,
properties):
"""Return a future a publisher confirmation result that enables
consumers to block on the confirmation of a published message.
Two internal dicts are used for keeping track of state.
Consumer._delivery_tags is a dict of connection names that keeps
the last delivery tag expectation and is used to correlate the future
with the delivery tag that is expected to be confirmed from RabbitMQ.
This for internal use and should not be extended or used directly.
:param str name: The connection name for the future
:param str exchange: The exchange the message was published to
:param str routing_key: The routing key that was used
:param properties: The AMQP message properties for the delivery
:type properties: pika.spec.Basic.Properties
:rtype: concurrent.Future.
"""
if self._connections[name].publisher_confirmations:
future = concurrent.Future()
self._connections[name].add_confirmation_future(
exchange, routing_key, properties, future)
return future | [
"def",
"_publisher_confirmation_future",
"(",
"self",
",",
"name",
",",
"exchange",
",",
"routing_key",
",",
"properties",
")",
":",
"if",
"self",
".",
"_connections",
"[",
"name",
"]",
".",
"publisher_confirmations",
":",
"future",
"=",
"concurrent",
".",
"Fu... | Return a future a publisher confirmation result that enables
consumers to block on the confirmation of a published message.
Two internal dicts are used for keeping track of state.
Consumer._delivery_tags is a dict of connection names that keeps
the last delivery tag expectation and is used to correlate the future
with the delivery tag that is expected to be confirmed from RabbitMQ.
This for internal use and should not be extended or used directly.
:param str name: The connection name for the future
:param str exchange: The exchange the message was published to
:param str routing_key: The routing key that was used
:param properties: The AMQP message properties for the delivery
:type properties: pika.spec.Basic.Properties
:rtype: concurrent.Future. | [
"Return",
"a",
"future",
"a",
"publisher",
"confirmation",
"result",
"that",
"enables",
"consumers",
"to",
"block",
"on",
"the",
"confirmation",
"of",
"a",
"published",
"message",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/consumer.py#L1100-L1124 | train | 30,653 |
gmr/rejected | rejected/consumer.py | Consumer._publish_connection | def _publish_connection(self, name=None):
"""Return the connection to publish. If the name is not specified,
the connection associated with the current message is returned.
:param str name:
:rtype: rejected.process.Connection
"""
try:
conn = self._connections[name or self._message.connection]
except KeyError:
raise ValueError('Channel {} not found'.format(name))
if not conn.is_connected or conn.channel.is_closed:
raise RabbitMQException(conn.name, 599, 'NOT_CONNECTED')
return conn | python | def _publish_connection(self, name=None):
"""Return the connection to publish. If the name is not specified,
the connection associated with the current message is returned.
:param str name:
:rtype: rejected.process.Connection
"""
try:
conn = self._connections[name or self._message.connection]
except KeyError:
raise ValueError('Channel {} not found'.format(name))
if not conn.is_connected or conn.channel.is_closed:
raise RabbitMQException(conn.name, 599, 'NOT_CONNECTED')
return conn | [
"def",
"_publish_connection",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"self",
".",
"_connections",
"[",
"name",
"or",
"self",
".",
"_message",
".",
"connection",
"]",
"except",
"KeyError",
":",
"raise",
"ValueError",
"("... | Return the connection to publish. If the name is not specified,
the connection associated with the current message is returned.
:param str name:
:rtype: rejected.process.Connection | [
"Return",
"the",
"connection",
"to",
"publish",
".",
"If",
"the",
"name",
"is",
"not",
"specified",
"the",
"connection",
"associated",
"with",
"the",
"current",
"message",
"is",
"returned",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/consumer.py#L1126-L1140 | train | 30,654 |
gmr/rejected | rejected/consumer.py | Consumer._republish_dropped_message | def _republish_dropped_message(self, reason):
"""Republish the original message that was received it is being dropped
by the consumer.
This for internal use and should not be extended or used directly.
:param str reason: The reason the message was dropped
"""
self.logger.debug('Republishing due to ProcessingException')
properties = dict(self._message.properties) or {}
if 'headers' not in properties or not properties['headers']:
properties['headers'] = {}
properties['headers']['X-Dropped-By'] = self.name
properties['headers']['X-Dropped-Reason'] = reason
properties['headers']['X-Dropped-Timestamp'] = \
datetime.datetime.utcnow().isoformat()
properties['headers']['X-Original-Exchange'] = self._message.exchange
self._message.channel.basic_publish(
self._drop_exchange, self._message.routing_key, self._message.body,
pika.BasicProperties(**properties)) | python | def _republish_dropped_message(self, reason):
"""Republish the original message that was received it is being dropped
by the consumer.
This for internal use and should not be extended or used directly.
:param str reason: The reason the message was dropped
"""
self.logger.debug('Republishing due to ProcessingException')
properties = dict(self._message.properties) or {}
if 'headers' not in properties or not properties['headers']:
properties['headers'] = {}
properties['headers']['X-Dropped-By'] = self.name
properties['headers']['X-Dropped-Reason'] = reason
properties['headers']['X-Dropped-Timestamp'] = \
datetime.datetime.utcnow().isoformat()
properties['headers']['X-Original-Exchange'] = self._message.exchange
self._message.channel.basic_publish(
self._drop_exchange, self._message.routing_key, self._message.body,
pika.BasicProperties(**properties)) | [
"def",
"_republish_dropped_message",
"(",
"self",
",",
"reason",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Republishing due to ProcessingException'",
")",
"properties",
"=",
"dict",
"(",
"self",
".",
"_message",
".",
"properties",
")",
"or",
"{",
"... | Republish the original message that was received it is being dropped
by the consumer.
This for internal use and should not be extended or used directly.
:param str reason: The reason the message was dropped | [
"Republish",
"the",
"original",
"message",
"that",
"was",
"received",
"it",
"is",
"being",
"dropped",
"by",
"the",
"consumer",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/consumer.py#L1142-L1163 | train | 30,655 |
gmr/rejected | rejected/statsd.py | Client._setting | def _setting(self, key, default):
"""Return the setting, checking config, then the appropriate
environment variable, falling back to the default, caching the
results.
:param str key: The key to get
:param any default: The default value if not set
:return: str
"""
if key not in self._settings:
value = self._settings_in.get(
key, os.environ.get('STATSD_{}'.format(key).upper(), default))
self._settings[key] = value
return self._settings[key] | python | def _setting(self, key, default):
"""Return the setting, checking config, then the appropriate
environment variable, falling back to the default, caching the
results.
:param str key: The key to get
:param any default: The default value if not set
:return: str
"""
if key not in self._settings:
value = self._settings_in.get(
key, os.environ.get('STATSD_{}'.format(key).upper(), default))
self._settings[key] = value
return self._settings[key] | [
"def",
"_setting",
"(",
"self",
",",
"key",
",",
"default",
")",
":",
"if",
"key",
"not",
"in",
"self",
".",
"_settings",
":",
"value",
"=",
"self",
".",
"_settings_in",
".",
"get",
"(",
"key",
",",
"os",
".",
"environ",
".",
"get",
"(",
"'STATSD_{... | Return the setting, checking config, then the appropriate
environment variable, falling back to the default, caching the
results.
:param str key: The key to get
:param any default: The default value if not set
:return: str | [
"Return",
"the",
"setting",
"checking",
"config",
"then",
"the",
"appropriate",
"environment",
"variable",
"falling",
"back",
"to",
"the",
"default",
"caching",
"the",
"results",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/statsd.py#L51-L65 | train | 30,656 |
gmr/rejected | rejected/state.py | State.set_state | def set_state(self, new_state):
"""Assign the specified state to this consumer object.
:param int new_state: The new state of the object
:raises: ValueError
"""
# Make sure it's a valid state
if new_state not in self.STATES:
raise ValueError('Invalid state value: %r' % new_state)
# Set the state
LOGGER.debug('State changing from %s to %s', self.STATES[self.state],
self.STATES[new_state])
self.state = new_state
self.state_start = time.time() | python | def set_state(self, new_state):
"""Assign the specified state to this consumer object.
:param int new_state: The new state of the object
:raises: ValueError
"""
# Make sure it's a valid state
if new_state not in self.STATES:
raise ValueError('Invalid state value: %r' % new_state)
# Set the state
LOGGER.debug('State changing from %s to %s', self.STATES[self.state],
self.STATES[new_state])
self.state = new_state
self.state_start = time.time() | [
"def",
"set_state",
"(",
"self",
",",
"new_state",
")",
":",
"# Make sure it's a valid state",
"if",
"new_state",
"not",
"in",
"self",
".",
"STATES",
":",
"raise",
"ValueError",
"(",
"'Invalid state value: %r'",
"%",
"new_state",
")",
"# Set the state",
"LOGGER",
... | Assign the specified state to this consumer object.
:param int new_state: The new state of the object
:raises: ValueError | [
"Assign",
"the",
"specified",
"state",
"to",
"this",
"consumer",
"object",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/state.py#L43-L58 | train | 30,657 |
gmr/rejected | rejected/state.py | State.is_running | def is_running(self):
"""Returns a bool determining if the process is in a running state or
not
:rtype: bool
"""
return self.state in [self.STATE_IDLE, self.STATE_ACTIVE,
self.STATE_SLEEPING] | python | def is_running(self):
"""Returns a bool determining if the process is in a running state or
not
:rtype: bool
"""
return self.state in [self.STATE_IDLE, self.STATE_ACTIVE,
self.STATE_SLEEPING] | [
"def",
"is_running",
"(",
"self",
")",
":",
"return",
"self",
".",
"state",
"in",
"[",
"self",
".",
"STATE_IDLE",
",",
"self",
".",
"STATE_ACTIVE",
",",
"self",
".",
"STATE_SLEEPING",
"]"
] | Returns a bool determining if the process is in a running state or
not
:rtype: bool | [
"Returns",
"a",
"bool",
"determining",
"if",
"the",
"process",
"is",
"in",
"a",
"running",
"state",
"or",
"not"
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/state.py#L88-L96 | train | 30,658 |
gmr/rejected | rejected/process.py | Process.ack_message | def ack_message(self, message):
"""Acknowledge the message on the broker and log the ack
:param message: The message to acknowledge
:type message: rejected.data.Message
"""
if message.channel.is_closed:
LOGGER.warning('Can not ack message, channel is closed')
self.counters[self.CLOSED_ON_COMPLETE] += 1
return
message.channel.basic_ack(delivery_tag=message.delivery_tag)
self.counters[self.ACKED] += 1
self.measurement.set_tag(self.ACKED, True) | python | def ack_message(self, message):
"""Acknowledge the message on the broker and log the ack
:param message: The message to acknowledge
:type message: rejected.data.Message
"""
if message.channel.is_closed:
LOGGER.warning('Can not ack message, channel is closed')
self.counters[self.CLOSED_ON_COMPLETE] += 1
return
message.channel.basic_ack(delivery_tag=message.delivery_tag)
self.counters[self.ACKED] += 1
self.measurement.set_tag(self.ACKED, True) | [
"def",
"ack_message",
"(",
"self",
",",
"message",
")",
":",
"if",
"message",
".",
"channel",
".",
"is_closed",
":",
"LOGGER",
".",
"warning",
"(",
"'Can not ack message, channel is closed'",
")",
"self",
".",
"counters",
"[",
"self",
".",
"CLOSED_ON_COMPLETE",
... | Acknowledge the message on the broker and log the ack
:param message: The message to acknowledge
:type message: rejected.data.Message | [
"Acknowledge",
"the",
"message",
"on",
"the",
"broker",
"and",
"log",
"the",
"ack"
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/process.py#L121-L134 | train | 30,659 |
gmr/rejected | rejected/process.py | Process.create_connections | def create_connections(self):
"""Create and start the RabbitMQ connections, assigning the connection
object to the connections dict.
"""
self.set_state(self.STATE_CONNECTING)
for conn in self.consumer_config.get('connections', []):
name, confirm, consume = conn, False, True
if isinstance(conn, dict):
name = conn['name']
confirm = conn.get('publisher_confirmation', False)
consume = conn.get('consume', True)
if name not in self.config['Connections']:
LOGGER.critical('Connection "%s" for %s not found',
name, self.consumer_name)
continue
self.connections[name] = connection.Connection(
name, self.config['Connections'][name], self.consumer_name,
consume, confirm, self.ioloop, self.callbacks) | python | def create_connections(self):
"""Create and start the RabbitMQ connections, assigning the connection
object to the connections dict.
"""
self.set_state(self.STATE_CONNECTING)
for conn in self.consumer_config.get('connections', []):
name, confirm, consume = conn, False, True
if isinstance(conn, dict):
name = conn['name']
confirm = conn.get('publisher_confirmation', False)
consume = conn.get('consume', True)
if name not in self.config['Connections']:
LOGGER.critical('Connection "%s" for %s not found',
name, self.consumer_name)
continue
self.connections[name] = connection.Connection(
name, self.config['Connections'][name], self.consumer_name,
consume, confirm, self.ioloop, self.callbacks) | [
"def",
"create_connections",
"(",
"self",
")",
":",
"self",
".",
"set_state",
"(",
"self",
".",
"STATE_CONNECTING",
")",
"for",
"conn",
"in",
"self",
".",
"consumer_config",
".",
"get",
"(",
"'connections'",
",",
"[",
"]",
")",
":",
"name",
",",
"confirm... | Create and start the RabbitMQ connections, assigning the connection
object to the connections dict. | [
"Create",
"and",
"start",
"the",
"RabbitMQ",
"connections",
"assigning",
"the",
"connection",
"object",
"to",
"the",
"connections",
"dict",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/process.py#L136-L156 | train | 30,660 |
gmr/rejected | rejected/process.py | Process.get_config | def get_config(cfg, number, name, connection_name):
"""Initialize a new consumer thread, setting defaults and config values
:param dict cfg: Consumer config section from YAML File
:param int number: The identification number for the consumer
:param str name: The name of the consumer
:param str connection_name: The name of the connection):
:rtype: dict
"""
return {
'connection': cfg['Connections'][connection_name],
'consumer_name': name,
'process_name': '%s_%i_tag_%i' % (name, os.getpid(), number)
} | python | def get_config(cfg, number, name, connection_name):
"""Initialize a new consumer thread, setting defaults and config values
:param dict cfg: Consumer config section from YAML File
:param int number: The identification number for the consumer
:param str name: The name of the consumer
:param str connection_name: The name of the connection):
:rtype: dict
"""
return {
'connection': cfg['Connections'][connection_name],
'consumer_name': name,
'process_name': '%s_%i_tag_%i' % (name, os.getpid(), number)
} | [
"def",
"get_config",
"(",
"cfg",
",",
"number",
",",
"name",
",",
"connection_name",
")",
":",
"return",
"{",
"'connection'",
":",
"cfg",
"[",
"'Connections'",
"]",
"[",
"connection_name",
"]",
",",
"'consumer_name'",
":",
"name",
",",
"'process_name'",
":",... | Initialize a new consumer thread, setting defaults and config values
:param dict cfg: Consumer config section from YAML File
:param int number: The identification number for the consumer
:param str name: The name of the consumer
:param str connection_name: The name of the connection):
:rtype: dict | [
"Initialize",
"a",
"new",
"consumer",
"thread",
"setting",
"defaults",
"and",
"config",
"values"
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/process.py#L159-L173 | train | 30,661 |
gmr/rejected | rejected/process.py | Process.get_consumer | def get_consumer(self, cfg):
"""Import and create a new instance of the configured message consumer.
:param dict cfg: The named consumer section of the configuration
:rtype: instance
:raises: ImportError
"""
try:
handle, version = utils.import_consumer(cfg['consumer'])
except ImportError as error:
LOGGER.exception('Error importing the consumer %s: %s',
cfg['consumer'], error)
return
if version:
LOGGER.info('Creating consumer %s v%s', cfg['consumer'], version)
self.consumer_version = version
else:
LOGGER.info('Creating consumer %s', cfg['consumer'])
settings = cfg.get('config', dict())
settings['_import_module'] = '.'.join(cfg['consumer'].split('.')[0:-1])
kwargs = {
'settings': settings,
'process': self,
'drop_exchange': cfg.get('drop_exchange'),
'drop_invalid_messages': cfg.get('drop_invalid_messages'),
'message_type': cfg.get('message_type'),
'error_exchange': cfg.get('error_exchange'),
'error_max_retry': cfg.get('error_max_retry')
}
try:
return handle(**kwargs)
except Exception as error:
LOGGER.exception('Error creating the consumer "%s": %s',
cfg['consumer'], error)
self.send_exception_to_sentry(sys.exc_info())
self.on_startup_error('Failed to create consumer {}: {}'.format(
self.consumer_name, error)) | python | def get_consumer(self, cfg):
"""Import and create a new instance of the configured message consumer.
:param dict cfg: The named consumer section of the configuration
:rtype: instance
:raises: ImportError
"""
try:
handle, version = utils.import_consumer(cfg['consumer'])
except ImportError as error:
LOGGER.exception('Error importing the consumer %s: %s',
cfg['consumer'], error)
return
if version:
LOGGER.info('Creating consumer %s v%s', cfg['consumer'], version)
self.consumer_version = version
else:
LOGGER.info('Creating consumer %s', cfg['consumer'])
settings = cfg.get('config', dict())
settings['_import_module'] = '.'.join(cfg['consumer'].split('.')[0:-1])
kwargs = {
'settings': settings,
'process': self,
'drop_exchange': cfg.get('drop_exchange'),
'drop_invalid_messages': cfg.get('drop_invalid_messages'),
'message_type': cfg.get('message_type'),
'error_exchange': cfg.get('error_exchange'),
'error_max_retry': cfg.get('error_max_retry')
}
try:
return handle(**kwargs)
except Exception as error:
LOGGER.exception('Error creating the consumer "%s": %s',
cfg['consumer'], error)
self.send_exception_to_sentry(sys.exc_info())
self.on_startup_error('Failed to create consumer {}: {}'.format(
self.consumer_name, error)) | [
"def",
"get_consumer",
"(",
"self",
",",
"cfg",
")",
":",
"try",
":",
"handle",
",",
"version",
"=",
"utils",
".",
"import_consumer",
"(",
"cfg",
"[",
"'consumer'",
"]",
")",
"except",
"ImportError",
"as",
"error",
":",
"LOGGER",
".",
"exception",
"(",
... | Import and create a new instance of the configured message consumer.
:param dict cfg: The named consumer section of the configuration
:rtype: instance
:raises: ImportError | [
"Import",
"and",
"create",
"a",
"new",
"instance",
"of",
"the",
"configured",
"message",
"consumer",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/process.py#L175-L216 | train | 30,662 |
gmr/rejected | rejected/process.py | Process.invoke_consumer | def invoke_consumer(self, message):
"""Wrap the actual processor processing bits
:param rejected.data.Message message: The message to process
"""
# Only allow for a single message to be processed at a time
with (yield self.consumer_lock.acquire()):
if self.is_idle:
if message.channel.is_closed:
LOGGER.warning('Channel %s is closed on '
'connection "%s", discarding '
'local copy of message %s',
message.channel.channel_number,
message.connection,
utils.message_info(message.exchange,
message.routing_key,
message.properties))
self.counters[self.CLOSED_ON_START] += 1
self.maybe_get_next_message()
return
self.set_state(self.STATE_PROCESSING)
self.delivery_time = start_time = time.time()
self.active_message = message
self.measurement = data.Measurement()
if message.method.redelivered:
self.counters[self.REDELIVERED] += 1
self.measurement.set_tag(self.REDELIVERED, True)
try:
result = yield self.consumer.execute(message,
self.measurement)
except Exception as error:
LOGGER.exception('Unhandled exception from consumer in '
'process. This should not happen. %s',
error)
result = data.MESSAGE_REQUEUE
LOGGER.debug('Finished processing message: %r', result)
self.on_processed(message, result, start_time)
elif self.is_waiting_to_shutdown:
LOGGER.info(
'Requeueing pending message due to pending shutdown')
self.reject(message, True)
self.shutdown_connections()
elif self.is_shutting_down:
LOGGER.info('Requeueing pending message due to shutdown')
self.reject(message, True)
self.on_ready_to_stop()
else:
LOGGER.warning('Exiting invoke_consumer without processing, '
'this should not happen. State: %s',
self.state_description)
self.maybe_get_next_message() | python | def invoke_consumer(self, message):
"""Wrap the actual processor processing bits
:param rejected.data.Message message: The message to process
"""
# Only allow for a single message to be processed at a time
with (yield self.consumer_lock.acquire()):
if self.is_idle:
if message.channel.is_closed:
LOGGER.warning('Channel %s is closed on '
'connection "%s", discarding '
'local copy of message %s',
message.channel.channel_number,
message.connection,
utils.message_info(message.exchange,
message.routing_key,
message.properties))
self.counters[self.CLOSED_ON_START] += 1
self.maybe_get_next_message()
return
self.set_state(self.STATE_PROCESSING)
self.delivery_time = start_time = time.time()
self.active_message = message
self.measurement = data.Measurement()
if message.method.redelivered:
self.counters[self.REDELIVERED] += 1
self.measurement.set_tag(self.REDELIVERED, True)
try:
result = yield self.consumer.execute(message,
self.measurement)
except Exception as error:
LOGGER.exception('Unhandled exception from consumer in '
'process. This should not happen. %s',
error)
result = data.MESSAGE_REQUEUE
LOGGER.debug('Finished processing message: %r', result)
self.on_processed(message, result, start_time)
elif self.is_waiting_to_shutdown:
LOGGER.info(
'Requeueing pending message due to pending shutdown')
self.reject(message, True)
self.shutdown_connections()
elif self.is_shutting_down:
LOGGER.info('Requeueing pending message due to shutdown')
self.reject(message, True)
self.on_ready_to_stop()
else:
LOGGER.warning('Exiting invoke_consumer without processing, '
'this should not happen. State: %s',
self.state_description)
self.maybe_get_next_message() | [
"def",
"invoke_consumer",
"(",
"self",
",",
"message",
")",
":",
"# Only allow for a single message to be processed at a time",
"with",
"(",
"yield",
"self",
".",
"consumer_lock",
".",
"acquire",
"(",
")",
")",
":",
"if",
"self",
".",
"is_idle",
":",
"if",
"mess... | Wrap the actual processor processing bits
:param rejected.data.Message message: The message to process | [
"Wrap",
"the",
"actual",
"processor",
"processing",
"bits"
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/process.py#L219-L275 | train | 30,663 |
gmr/rejected | rejected/process.py | Process.maybe_get_next_message | def maybe_get_next_message(self):
"""Pop the next message on the stack, adding a callback on the IOLoop
to invoke the consumer with the message. This is done so we let the
IOLoop perform any pending callbacks before trying to process the
next message.
"""
if self.pending:
self.ioloop.add_callback(
self.invoke_consumer, self.pending.popleft()) | python | def maybe_get_next_message(self):
"""Pop the next message on the stack, adding a callback on the IOLoop
to invoke the consumer with the message. This is done so we let the
IOLoop perform any pending callbacks before trying to process the
next message.
"""
if self.pending:
self.ioloop.add_callback(
self.invoke_consumer, self.pending.popleft()) | [
"def",
"maybe_get_next_message",
"(",
"self",
")",
":",
"if",
"self",
".",
"pending",
":",
"self",
".",
"ioloop",
".",
"add_callback",
"(",
"self",
".",
"invoke_consumer",
",",
"self",
".",
"pending",
".",
"popleft",
"(",
")",
")"
] | Pop the next message on the stack, adding a callback on the IOLoop
to invoke the consumer with the message. This is done so we let the
IOLoop perform any pending callbacks before trying to process the
next message. | [
"Pop",
"the",
"next",
"message",
"on",
"the",
"stack",
"adding",
"a",
"callback",
"on",
"the",
"IOLoop",
"to",
"invoke",
"the",
"consumer",
"with",
"the",
"message",
".",
"This",
"is",
"done",
"so",
"we",
"let",
"the",
"IOLoop",
"perform",
"any",
"pendin... | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/process.py#L286-L295 | train | 30,664 |
gmr/rejected | rejected/process.py | Process.maybe_submit_measurement | def maybe_submit_measurement(self):
"""Check for configured instrumentation backends and if found, submit
the message measurement info.
"""
if self.statsd:
self.submit_statsd_measurements()
if self.influxdb:
self.submit_influxdb_measurement() | python | def maybe_submit_measurement(self):
"""Check for configured instrumentation backends and if found, submit
the message measurement info.
"""
if self.statsd:
self.submit_statsd_measurements()
if self.influxdb:
self.submit_influxdb_measurement() | [
"def",
"maybe_submit_measurement",
"(",
"self",
")",
":",
"if",
"self",
".",
"statsd",
":",
"self",
".",
"submit_statsd_measurements",
"(",
")",
"if",
"self",
".",
"influxdb",
":",
"self",
".",
"submit_influxdb_measurement",
"(",
")"
] | Check for configured instrumentation backends and if found, submit
the message measurement info. | [
"Check",
"for",
"configured",
"instrumentation",
"backends",
"and",
"if",
"found",
"submit",
"the",
"message",
"measurement",
"info",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/process.py#L297-L305 | train | 30,665 |
gmr/rejected | rejected/process.py | Process.on_delivery | def on_delivery(self, name, channel, method, properties, body):
"""Process a message from Rabbit
:param str name: The connection name
:param pika.channel.Channel channel: The message's delivery channel
:param pika.frames.MethodFrame method: The method frame
:param pika.spec.BasicProperties properties: The message properties
:param str body: The message body
"""
message = data.Message(name, channel, method, properties, body)
if self.is_processing:
return self.pending.append(message)
self.invoke_consumer(message) | python | def on_delivery(self, name, channel, method, properties, body):
"""Process a message from Rabbit
:param str name: The connection name
:param pika.channel.Channel channel: The message's delivery channel
:param pika.frames.MethodFrame method: The method frame
:param pika.spec.BasicProperties properties: The message properties
:param str body: The message body
"""
message = data.Message(name, channel, method, properties, body)
if self.is_processing:
return self.pending.append(message)
self.invoke_consumer(message) | [
"def",
"on_delivery",
"(",
"self",
",",
"name",
",",
"channel",
",",
"method",
",",
"properties",
",",
"body",
")",
":",
"message",
"=",
"data",
".",
"Message",
"(",
"name",
",",
"channel",
",",
"method",
",",
"properties",
",",
"body",
")",
"if",
"s... | Process a message from Rabbit
:param str name: The connection name
:param pika.channel.Channel channel: The message's delivery channel
:param pika.frames.MethodFrame method: The method frame
:param pika.spec.BasicProperties properties: The message properties
:param str body: The message body | [
"Process",
"a",
"message",
"from",
"Rabbit"
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/process.py#L353-L366 | train | 30,666 |
gmr/rejected | rejected/process.py | Process.on_processed | def on_processed(self, message, result, start_time):
"""Invoked after a message is processed by the consumer and
implements the logic for how to deal with a message based upon
the result.
:param rejected.data.Message message: The message that was processed
:param int result: The result of the processing of the message
:param float start_time: When the message was received
"""
duration = max(start_time, time.time()) - start_time
self.counters[self.TIME_SPENT] += duration
self.measurement.add_duration(self.TIME_SPENT, duration)
if result == data.MESSAGE_DROP:
LOGGER.debug('Rejecting message due to drop return from consumer')
self.reject(message, False)
self.counters[self.DROPPED] += 1
elif result == data.MESSAGE_EXCEPTION:
LOGGER.debug('Rejecting message due to MessageException')
self.reject(message, False)
self.counters[self.MESSAGE_EXCEPTION] += 1
elif result == data.PROCESSING_EXCEPTION:
LOGGER.debug('Rejecting message due to ProcessingException')
self.reject(message, False)
self.counters[self.PROCESSING_EXCEPTION] += 1
elif result == data.CONFIGURATION_EXCEPTION:
LOGGER.debug('Rejecting message due to ConfigurationException '
'and shutting down')
self.reject(message, False)
self.counters[self.CONFIGURATION_EXCEPTION] += 1
self.stop_consumer()
self.shutdown_connections()
elif result == data.CONSUMER_EXCEPTION:
LOGGER.debug('Re-queueing message due to ConsumerException')
self.reject(message, True)
self.on_processing_error()
self.counters[self.CONSUMER_EXCEPTION] += 1
elif result == data.RABBITMQ_EXCEPTION:
LOGGER.debug('Processing interrupted due to RabbitMQException')
self.on_processing_error()
self.counters[self.RABBITMQ_EXCEPTION] += 1
elif result == data.UNHANDLED_EXCEPTION:
LOGGER.debug('Re-queueing message due to UnhandledException')
self.reject(message, True)
self.on_processing_error()
self.counters[self.UNHANDLED_EXCEPTION] += 1
elif result == data.MESSAGE_REQUEUE:
LOGGER.debug('Re-queueing message due Consumer request')
self.reject(message, True)
self.counters[self.REQUEUED] += 1
elif result == data.MESSAGE_ACK and not self.no_ack:
self.ack_message(message)
self.counters[self.PROCESSED] += 1
self.measurement.set_tag(self.PROCESSED, True)
self.maybe_submit_measurement()
self.reset_state() | python | def on_processed(self, message, result, start_time):
"""Invoked after a message is processed by the consumer and
implements the logic for how to deal with a message based upon
the result.
:param rejected.data.Message message: The message that was processed
:param int result: The result of the processing of the message
:param float start_time: When the message was received
"""
duration = max(start_time, time.time()) - start_time
self.counters[self.TIME_SPENT] += duration
self.measurement.add_duration(self.TIME_SPENT, duration)
if result == data.MESSAGE_DROP:
LOGGER.debug('Rejecting message due to drop return from consumer')
self.reject(message, False)
self.counters[self.DROPPED] += 1
elif result == data.MESSAGE_EXCEPTION:
LOGGER.debug('Rejecting message due to MessageException')
self.reject(message, False)
self.counters[self.MESSAGE_EXCEPTION] += 1
elif result == data.PROCESSING_EXCEPTION:
LOGGER.debug('Rejecting message due to ProcessingException')
self.reject(message, False)
self.counters[self.PROCESSING_EXCEPTION] += 1
elif result == data.CONFIGURATION_EXCEPTION:
LOGGER.debug('Rejecting message due to ConfigurationException '
'and shutting down')
self.reject(message, False)
self.counters[self.CONFIGURATION_EXCEPTION] += 1
self.stop_consumer()
self.shutdown_connections()
elif result == data.CONSUMER_EXCEPTION:
LOGGER.debug('Re-queueing message due to ConsumerException')
self.reject(message, True)
self.on_processing_error()
self.counters[self.CONSUMER_EXCEPTION] += 1
elif result == data.RABBITMQ_EXCEPTION:
LOGGER.debug('Processing interrupted due to RabbitMQException')
self.on_processing_error()
self.counters[self.RABBITMQ_EXCEPTION] += 1
elif result == data.UNHANDLED_EXCEPTION:
LOGGER.debug('Re-queueing message due to UnhandledException')
self.reject(message, True)
self.on_processing_error()
self.counters[self.UNHANDLED_EXCEPTION] += 1
elif result == data.MESSAGE_REQUEUE:
LOGGER.debug('Re-queueing message due Consumer request')
self.reject(message, True)
self.counters[self.REQUEUED] += 1
elif result == data.MESSAGE_ACK and not self.no_ack:
self.ack_message(message)
self.counters[self.PROCESSED] += 1
self.measurement.set_tag(self.PROCESSED, True)
self.maybe_submit_measurement()
self.reset_state() | [
"def",
"on_processed",
"(",
"self",
",",
"message",
",",
"result",
",",
"start_time",
")",
":",
"duration",
"=",
"max",
"(",
"start_time",
",",
"time",
".",
"time",
"(",
")",
")",
"-",
"start_time",
"self",
".",
"counters",
"[",
"self",
".",
"TIME_SPEN... | Invoked after a message is processed by the consumer and
implements the logic for how to deal with a message based upon
the result.
:param rejected.data.Message message: The message that was processed
:param int result: The result of the processing of the message
:param float start_time: When the message was received | [
"Invoked",
"after",
"a",
"message",
"is",
"processed",
"by",
"the",
"consumer",
"and",
"implements",
"the",
"logic",
"for",
"how",
"to",
"deal",
"with",
"a",
"message",
"based",
"upon",
"the",
"result",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/process.py#L368-L433 | train | 30,667 |
gmr/rejected | rejected/process.py | Process.on_processing_error | def on_processing_error(self):
"""Called when message processing failure happens due to a
ConsumerException or an unhandled exception.
"""
duration = time.time() - self.last_failure
if duration > self.MAX_ERROR_WINDOW:
LOGGER.info('Resetting failure window, %i seconds since last',
duration)
self.reset_error_counter()
self.counters[self.ERROR] += 1
self.last_failure = time.time()
if self.too_many_errors:
LOGGER.critical('Error threshold exceeded (%i), shutting down',
self.counters[self.ERROR])
self.shutdown_connections() | python | def on_processing_error(self):
"""Called when message processing failure happens due to a
ConsumerException or an unhandled exception.
"""
duration = time.time() - self.last_failure
if duration > self.MAX_ERROR_WINDOW:
LOGGER.info('Resetting failure window, %i seconds since last',
duration)
self.reset_error_counter()
self.counters[self.ERROR] += 1
self.last_failure = time.time()
if self.too_many_errors:
LOGGER.critical('Error threshold exceeded (%i), shutting down',
self.counters[self.ERROR])
self.shutdown_connections() | [
"def",
"on_processing_error",
"(",
"self",
")",
":",
"duration",
"=",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"last_failure",
"if",
"duration",
">",
"self",
".",
"MAX_ERROR_WINDOW",
":",
"LOGGER",
".",
"info",
"(",
"'Resetting failure window, %i secon... | Called when message processing failure happens due to a
ConsumerException or an unhandled exception. | [
"Called",
"when",
"message",
"processing",
"failure",
"happens",
"due",
"to",
"a",
"ConsumerException",
"or",
"an",
"unhandled",
"exception",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/process.py#L435-L450 | train | 30,668 |
gmr/rejected | rejected/process.py | Process.on_ready_to_stop | def on_ready_to_stop(self):
"""Invoked when the consumer is ready to stop."""
# Set the state to shutting down if it wasn't set as that during loop
self.set_state(self.STATE_SHUTTING_DOWN)
# Reset any signal handlers
signal.signal(signal.SIGABRT, signal.SIG_IGN)
signal.signal(signal.SIGINT, signal.SIG_IGN)
signal.signal(signal.SIGPROF, signal.SIG_IGN)
signal.signal(signal.SIGTERM, signal.SIG_IGN)
# Allow the consumer to gracefully stop and then stop the IOLoop
if self.consumer:
self.stop_consumer()
# Clear IOLoop constructs
self.consumer_lock = None
# Stop the IOLoop
if self.ioloop:
LOGGER.debug('Stopping IOLoop')
self.ioloop.stop()
# Note that shutdown is complete and set the state accordingly
self.set_state(self.STATE_STOPPED)
LOGGER.info('Shutdown complete') | python | def on_ready_to_stop(self):
"""Invoked when the consumer is ready to stop."""
# Set the state to shutting down if it wasn't set as that during loop
self.set_state(self.STATE_SHUTTING_DOWN)
# Reset any signal handlers
signal.signal(signal.SIGABRT, signal.SIG_IGN)
signal.signal(signal.SIGINT, signal.SIG_IGN)
signal.signal(signal.SIGPROF, signal.SIG_IGN)
signal.signal(signal.SIGTERM, signal.SIG_IGN)
# Allow the consumer to gracefully stop and then stop the IOLoop
if self.consumer:
self.stop_consumer()
# Clear IOLoop constructs
self.consumer_lock = None
# Stop the IOLoop
if self.ioloop:
LOGGER.debug('Stopping IOLoop')
self.ioloop.stop()
# Note that shutdown is complete and set the state accordingly
self.set_state(self.STATE_STOPPED)
LOGGER.info('Shutdown complete') | [
"def",
"on_ready_to_stop",
"(",
"self",
")",
":",
"# Set the state to shutting down if it wasn't set as that during loop",
"self",
".",
"set_state",
"(",
"self",
".",
"STATE_SHUTTING_DOWN",
")",
"# Reset any signal handlers",
"signal",
".",
"signal",
"(",
"signal",
".",
"... | Invoked when the consumer is ready to stop. | [
"Invoked",
"when",
"the",
"consumer",
"is",
"ready",
"to",
"stop",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/process.py#L452-L478 | train | 30,669 |
gmr/rejected | rejected/process.py | Process.on_sigprof | def on_sigprof(self, _unused_signum, _unused_frame):
"""Called when SIGPROF is sent to the process, will dump the stats, in
future versions, queue them for the master process to get data.
:param int _unused_signum: The signal number
:param frame _unused_frame: The python frame the signal was received at
"""
self.stats_queue.put(self.report_stats(), True)
self.last_stats_time = time.time()
signal.siginterrupt(signal.SIGPROF, False) | python | def on_sigprof(self, _unused_signum, _unused_frame):
"""Called when SIGPROF is sent to the process, will dump the stats, in
future versions, queue them for the master process to get data.
:param int _unused_signum: The signal number
:param frame _unused_frame: The python frame the signal was received at
"""
self.stats_queue.put(self.report_stats(), True)
self.last_stats_time = time.time()
signal.siginterrupt(signal.SIGPROF, False) | [
"def",
"on_sigprof",
"(",
"self",
",",
"_unused_signum",
",",
"_unused_frame",
")",
":",
"self",
".",
"stats_queue",
".",
"put",
"(",
"self",
".",
"report_stats",
"(",
")",
",",
"True",
")",
"self",
".",
"last_stats_time",
"=",
"time",
".",
"time",
"(",
... | Called when SIGPROF is sent to the process, will dump the stats, in
future versions, queue them for the master process to get data.
:param int _unused_signum: The signal number
:param frame _unused_frame: The python frame the signal was received at | [
"Called",
"when",
"SIGPROF",
"is",
"sent",
"to",
"the",
"process",
"will",
"dump",
"the",
"stats",
"in",
"future",
"versions",
"queue",
"them",
"for",
"the",
"master",
"process",
"to",
"get",
"data",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/process.py#L480-L490 | train | 30,670 |
gmr/rejected | rejected/process.py | Process.on_startup_error | def on_startup_error(self, error):
"""Invoked when a pre-condition for starting the consumer has failed.
Log the error and then exit the process.
"""
LOGGER.critical('Could not start %s: %s', self.consumer_name, error)
self.set_state(self.STATE_STOPPED) | python | def on_startup_error(self, error):
"""Invoked when a pre-condition for starting the consumer has failed.
Log the error and then exit the process.
"""
LOGGER.critical('Could not start %s: %s', self.consumer_name, error)
self.set_state(self.STATE_STOPPED) | [
"def",
"on_startup_error",
"(",
"self",
",",
"error",
")",
":",
"LOGGER",
".",
"critical",
"(",
"'Could not start %s: %s'",
",",
"self",
".",
"consumer_name",
",",
"error",
")",
"self",
".",
"set_state",
"(",
"self",
".",
"STATE_STOPPED",
")"
] | Invoked when a pre-condition for starting the consumer has failed.
Log the error and then exit the process. | [
"Invoked",
"when",
"a",
"pre",
"-",
"condition",
"for",
"starting",
"the",
"consumer",
"has",
"failed",
".",
"Log",
"the",
"error",
"and",
"then",
"exit",
"the",
"process",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/process.py#L492-L498 | train | 30,671 |
gmr/rejected | rejected/process.py | Process.reject | def reject(self, message, requeue=True):
"""Reject the message on the broker and log it.
:param message: The message to reject
:type message: rejected.Data.message
:param bool requeue: Specify if the message should be re-queued or not
"""
if self.no_ack:
raise RuntimeError('Can not rejected messages when ack is False')
if message.channel.is_closed:
LOGGER.warning('Can not nack message, disconnected from RabbitMQ')
self.counters[self.CLOSED_ON_COMPLETE] += 1
return
LOGGER.warning('Rejecting message %s %s requeue', message.delivery_tag,
'with' if requeue else 'without')
message.channel.basic_nack(
delivery_tag=message.delivery_tag, requeue=requeue)
self.measurement.set_tag(self.NACKED, True)
self.measurement.set_tag(self.REQUEUED, requeue) | python | def reject(self, message, requeue=True):
"""Reject the message on the broker and log it.
:param message: The message to reject
:type message: rejected.Data.message
:param bool requeue: Specify if the message should be re-queued or not
"""
if self.no_ack:
raise RuntimeError('Can not rejected messages when ack is False')
if message.channel.is_closed:
LOGGER.warning('Can not nack message, disconnected from RabbitMQ')
self.counters[self.CLOSED_ON_COMPLETE] += 1
return
LOGGER.warning('Rejecting message %s %s requeue', message.delivery_tag,
'with' if requeue else 'without')
message.channel.basic_nack(
delivery_tag=message.delivery_tag, requeue=requeue)
self.measurement.set_tag(self.NACKED, True)
self.measurement.set_tag(self.REQUEUED, requeue) | [
"def",
"reject",
"(",
"self",
",",
"message",
",",
"requeue",
"=",
"True",
")",
":",
"if",
"self",
".",
"no_ack",
":",
"raise",
"RuntimeError",
"(",
"'Can not rejected messages when ack is False'",
")",
"if",
"message",
".",
"channel",
".",
"is_closed",
":",
... | Reject the message on the broker and log it.
:param message: The message to reject
:type message: rejected.Data.message
:param bool requeue: Specify if the message should be re-queued or not | [
"Reject",
"the",
"message",
"on",
"the",
"broker",
"and",
"log",
"it",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/process.py#L500-L521 | train | 30,672 |
gmr/rejected | rejected/process.py | Process.report_stats | def report_stats(self):
"""Create the dict of stats data for the MCP stats queue"""
if not self.previous:
self.previous = dict()
for key in self.counters:
self.previous[key] = 0
values = {
'name': self.name,
'consumer_name': self.consumer_name,
'counts': dict(self.counters),
'previous': dict(self.previous)
}
self.previous = dict(self.counters)
return values | python | def report_stats(self):
"""Create the dict of stats data for the MCP stats queue"""
if not self.previous:
self.previous = dict()
for key in self.counters:
self.previous[key] = 0
values = {
'name': self.name,
'consumer_name': self.consumer_name,
'counts': dict(self.counters),
'previous': dict(self.previous)
}
self.previous = dict(self.counters)
return values | [
"def",
"report_stats",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"previous",
":",
"self",
".",
"previous",
"=",
"dict",
"(",
")",
"for",
"key",
"in",
"self",
".",
"counters",
":",
"self",
".",
"previous",
"[",
"key",
"]",
"=",
"0",
"values",... | Create the dict of stats data for the MCP stats queue | [
"Create",
"the",
"dict",
"of",
"stats",
"data",
"for",
"the",
"MCP",
"stats",
"queue"
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/process.py#L523-L536 | train | 30,673 |
gmr/rejected | rejected/process.py | Process.reset_state | def reset_state(self):
"""Reset the runtime state after processing a message to either idle
or shutting down based upon the current state.
"""
self.active_message = None
self.measurement = None
if self.is_waiting_to_shutdown:
self.shutdown_connections()
elif self.is_processing:
self.set_state(self.STATE_IDLE)
elif self.is_idle or self.is_connecting or self.is_shutting_down:
pass
else:
LOGGER.critical('Unexepected state: %s', self.state_description)
LOGGER.debug('State reset to %s (%s in pending)',
self.state_description, len(self.pending)) | python | def reset_state(self):
"""Reset the runtime state after processing a message to either idle
or shutting down based upon the current state.
"""
self.active_message = None
self.measurement = None
if self.is_waiting_to_shutdown:
self.shutdown_connections()
elif self.is_processing:
self.set_state(self.STATE_IDLE)
elif self.is_idle or self.is_connecting or self.is_shutting_down:
pass
else:
LOGGER.critical('Unexepected state: %s', self.state_description)
LOGGER.debug('State reset to %s (%s in pending)',
self.state_description, len(self.pending)) | [
"def",
"reset_state",
"(",
"self",
")",
":",
"self",
".",
"active_message",
"=",
"None",
"self",
".",
"measurement",
"=",
"None",
"if",
"self",
".",
"is_waiting_to_shutdown",
":",
"self",
".",
"shutdown_connections",
"(",
")",
"elif",
"self",
".",
"is_proces... | Reset the runtime state after processing a message to either idle
or shutting down based upon the current state. | [
"Reset",
"the",
"runtime",
"state",
"after",
"processing",
"a",
"message",
"to",
"either",
"idle",
"or",
"shutting",
"down",
"based",
"upon",
"the",
"current",
"state",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/process.py#L543-L559 | train | 30,674 |
gmr/rejected | rejected/process.py | Process.run | def run(self):
"""Start the consumer"""
if self.profile_file:
LOGGER.info('Profiling to %s', self.profile_file)
profile.runctx('self._run()', globals(), locals(),
self.profile_file)
else:
self._run()
LOGGER.debug('Exiting %s (%i, %i)', self.name, os.getpid(),
os.getppid()) | python | def run(self):
"""Start the consumer"""
if self.profile_file:
LOGGER.info('Profiling to %s', self.profile_file)
profile.runctx('self._run()', globals(), locals(),
self.profile_file)
else:
self._run()
LOGGER.debug('Exiting %s (%i, %i)', self.name, os.getpid(),
os.getppid()) | [
"def",
"run",
"(",
"self",
")",
":",
"if",
"self",
".",
"profile_file",
":",
"LOGGER",
".",
"info",
"(",
"'Profiling to %s'",
",",
"self",
".",
"profile_file",
")",
"profile",
".",
"runctx",
"(",
"'self._run()'",
",",
"globals",
"(",
")",
",",
"locals",
... | Start the consumer | [
"Start",
"the",
"consumer"
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/process.py#L561-L570 | train | 30,675 |
gmr/rejected | rejected/process.py | Process._run | def _run(self):
"""Run method that can be profiled"""
self.set_state(self.STATE_INITIALIZING)
self.ioloop = ioloop.IOLoop.current()
self.consumer_lock = locks.Lock()
self.sentry_client = self.setup_sentry(
self._kwargs['config'], self.consumer_name)
try:
self.setup()
except (AttributeError, ImportError):
return self.on_startup_error(
'Failed to import the Python module for {}'.format(
self.consumer_name))
if not self.is_stopped:
try:
self.ioloop.start()
except KeyboardInterrupt:
LOGGER.warning('CTRL-C while waiting for clean shutdown') | python | def _run(self):
"""Run method that can be profiled"""
self.set_state(self.STATE_INITIALIZING)
self.ioloop = ioloop.IOLoop.current()
self.consumer_lock = locks.Lock()
self.sentry_client = self.setup_sentry(
self._kwargs['config'], self.consumer_name)
try:
self.setup()
except (AttributeError, ImportError):
return self.on_startup_error(
'Failed to import the Python module for {}'.format(
self.consumer_name))
if not self.is_stopped:
try:
self.ioloop.start()
except KeyboardInterrupt:
LOGGER.warning('CTRL-C while waiting for clean shutdown') | [
"def",
"_run",
"(",
"self",
")",
":",
"self",
".",
"set_state",
"(",
"self",
".",
"STATE_INITIALIZING",
")",
"self",
".",
"ioloop",
"=",
"ioloop",
".",
"IOLoop",
".",
"current",
"(",
")",
"self",
".",
"consumer_lock",
"=",
"locks",
".",
"Lock",
"(",
... | Run method that can be profiled | [
"Run",
"method",
"that",
"can",
"be",
"profiled"
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/process.py#L572-L592 | train | 30,676 |
gmr/rejected | rejected/process.py | Process.send_exception_to_sentry | def send_exception_to_sentry(self, exc_info):
"""Send an exception to Sentry if enabled.
:param tuple exc_info: exception information as returned from
:func:`sys.exc_info`
"""
if not self.sentry_client:
LOGGER.debug('No sentry_client, aborting')
return
message = dict(self.active_message)
try:
duration = math.ceil(time.time() - self.delivery_time) * 1000
except TypeError:
duration = 0
kwargs = {'extra': {
'consumer_name': self.consumer_name,
'env': dict(os.environ),
'message': message},
'time_spent': duration}
LOGGER.debug('Sending exception to sentry: %r', kwargs)
self.sentry_client.captureException(exc_info, **kwargs) | python | def send_exception_to_sentry(self, exc_info):
"""Send an exception to Sentry if enabled.
:param tuple exc_info: exception information as returned from
:func:`sys.exc_info`
"""
if not self.sentry_client:
LOGGER.debug('No sentry_client, aborting')
return
message = dict(self.active_message)
try:
duration = math.ceil(time.time() - self.delivery_time) * 1000
except TypeError:
duration = 0
kwargs = {'extra': {
'consumer_name': self.consumer_name,
'env': dict(os.environ),
'message': message},
'time_spent': duration}
LOGGER.debug('Sending exception to sentry: %r', kwargs)
self.sentry_client.captureException(exc_info, **kwargs) | [
"def",
"send_exception_to_sentry",
"(",
"self",
",",
"exc_info",
")",
":",
"if",
"not",
"self",
".",
"sentry_client",
":",
"LOGGER",
".",
"debug",
"(",
"'No sentry_client, aborting'",
")",
"return",
"message",
"=",
"dict",
"(",
"self",
".",
"active_message",
"... | Send an exception to Sentry if enabled.
:param tuple exc_info: exception information as returned from
:func:`sys.exc_info` | [
"Send",
"an",
"exception",
"to",
"Sentry",
"if",
"enabled",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/process.py#L594-L616 | train | 30,677 |
gmr/rejected | rejected/process.py | Process.setup | def setup(self):
"""Initialize the consumer, setting up needed attributes and connecting
to RabbitMQ.
"""
LOGGER.info('Initializing for %s', self.name)
if 'consumer' not in self.consumer_config:
return self.on_startup_error(
'"consumer" not specified in configuration')
self.consumer = self.get_consumer(self.consumer_config)
if not self.consumer:
return self.on_startup_error(
'Could not import "{}"'.format(
self.consumer_config.get(
'consumer', 'unconfigured consumer')))
self.setup_instrumentation()
self.reset_error_counter()
self.setup_sighandlers()
self.create_connections() | python | def setup(self):
"""Initialize the consumer, setting up needed attributes and connecting
to RabbitMQ.
"""
LOGGER.info('Initializing for %s', self.name)
if 'consumer' not in self.consumer_config:
return self.on_startup_error(
'"consumer" not specified in configuration')
self.consumer = self.get_consumer(self.consumer_config)
if not self.consumer:
return self.on_startup_error(
'Could not import "{}"'.format(
self.consumer_config.get(
'consumer', 'unconfigured consumer')))
self.setup_instrumentation()
self.reset_error_counter()
self.setup_sighandlers()
self.create_connections() | [
"def",
"setup",
"(",
"self",
")",
":",
"LOGGER",
".",
"info",
"(",
"'Initializing for %s'",
",",
"self",
".",
"name",
")",
"if",
"'consumer'",
"not",
"in",
"self",
".",
"consumer_config",
":",
"return",
"self",
".",
"on_startup_error",
"(",
"'\"consumer\" no... | Initialize the consumer, setting up needed attributes and connecting
to RabbitMQ. | [
"Initialize",
"the",
"consumer",
"setting",
"up",
"needed",
"attributes",
"and",
"connecting",
"to",
"RabbitMQ",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/process.py#L618-L640 | train | 30,678 |
gmr/rejected | rejected/process.py | Process.setup_influxdb | def setup_influxdb(self, config):
"""Configure the InfluxDB module for measurement submission.
:param dict config: The InfluxDB configuration stanza
"""
base_tags = {
'version': self.consumer_version
}
measurement = self.config.get('influxdb_measurement',
os.environ.get('SERVICE'))
if measurement != self.consumer_name:
base_tags['consumer'] = self.consumer_name
for key in {'ENVIRONMENT', 'SERVICE'}:
if key in os.environ:
base_tags[key.lower()] = os.environ[key]
influxdb.install(
'{}://{}:{}/write'.format(
config.get('scheme',
os.environ.get('INFLUXDB_SCHEME', 'http')),
config.get('host',
os.environ.get('INFLUXDB_HOST', 'localhost')),
config.get('port', os.environ.get('INFLUXDB_PORT', '8086'))
),
config.get('user', os.environ.get('INFLUXDB_USER')),
config.get('password', os.environ.get('INFLUXDB_PASSWORD')),
base_tags=base_tags)
return config.get('database', 'rejected'), measurement | python | def setup_influxdb(self, config):
"""Configure the InfluxDB module for measurement submission.
:param dict config: The InfluxDB configuration stanza
"""
base_tags = {
'version': self.consumer_version
}
measurement = self.config.get('influxdb_measurement',
os.environ.get('SERVICE'))
if measurement != self.consumer_name:
base_tags['consumer'] = self.consumer_name
for key in {'ENVIRONMENT', 'SERVICE'}:
if key in os.environ:
base_tags[key.lower()] = os.environ[key]
influxdb.install(
'{}://{}:{}/write'.format(
config.get('scheme',
os.environ.get('INFLUXDB_SCHEME', 'http')),
config.get('host',
os.environ.get('INFLUXDB_HOST', 'localhost')),
config.get('port', os.environ.get('INFLUXDB_PORT', '8086'))
),
config.get('user', os.environ.get('INFLUXDB_USER')),
config.get('password', os.environ.get('INFLUXDB_PASSWORD')),
base_tags=base_tags)
return config.get('database', 'rejected'), measurement | [
"def",
"setup_influxdb",
"(",
"self",
",",
"config",
")",
":",
"base_tags",
"=",
"{",
"'version'",
":",
"self",
".",
"consumer_version",
"}",
"measurement",
"=",
"self",
".",
"config",
".",
"get",
"(",
"'influxdb_measurement'",
",",
"os",
".",
"environ",
"... | Configure the InfluxDB module for measurement submission.
:param dict config: The InfluxDB configuration stanza | [
"Configure",
"the",
"InfluxDB",
"module",
"for",
"measurement",
"submission",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/process.py#L642-L669 | train | 30,679 |
gmr/rejected | rejected/process.py | Process.setup_sighandlers | def setup_sighandlers(self):
"""Setup the stats and stop signal handlers."""
signal.signal(signal.SIGINT, signal.SIG_IGN)
signal.signal(signal.SIGTERM, signal.SIG_IGN)
signal.signal(signal.SIGPROF, self.on_sigprof)
signal.signal(signal.SIGABRT, self.stop)
signal.siginterrupt(signal.SIGPROF, False)
signal.siginterrupt(signal.SIGABRT, False)
LOGGER.debug('Signal handlers setup') | python | def setup_sighandlers(self):
"""Setup the stats and stop signal handlers."""
signal.signal(signal.SIGINT, signal.SIG_IGN)
signal.signal(signal.SIGTERM, signal.SIG_IGN)
signal.signal(signal.SIGPROF, self.on_sigprof)
signal.signal(signal.SIGABRT, self.stop)
signal.siginterrupt(signal.SIGPROF, False)
signal.siginterrupt(signal.SIGABRT, False)
LOGGER.debug('Signal handlers setup') | [
"def",
"setup_sighandlers",
"(",
"self",
")",
":",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"signal",
".",
"SIG_IGN",
")",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGTERM",
",",
"signal",
".",
"SIG_IGN",
")",
"signal",
".",
"si... | Setup the stats and stop signal handlers. | [
"Setup",
"the",
"stats",
"and",
"stop",
"signal",
"handlers",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/process.py#L732-L742 | train | 30,680 |
gmr/rejected | rejected/process.py | Process.shutdown_connections | def shutdown_connections(self):
"""This method closes the connections to RabbitMQ."""
if not self.is_shutting_down:
self.set_state(self.STATE_SHUTTING_DOWN)
for name in self.connections:
if self.connections[name].is_running:
self.connections[name].shutdown() | python | def shutdown_connections(self):
"""This method closes the connections to RabbitMQ."""
if not self.is_shutting_down:
self.set_state(self.STATE_SHUTTING_DOWN)
for name in self.connections:
if self.connections[name].is_running:
self.connections[name].shutdown() | [
"def",
"shutdown_connections",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_shutting_down",
":",
"self",
".",
"set_state",
"(",
"self",
".",
"STATE_SHUTTING_DOWN",
")",
"for",
"name",
"in",
"self",
".",
"connections",
":",
"if",
"self",
".",
"conne... | This method closes the connections to RabbitMQ. | [
"This",
"method",
"closes",
"the",
"connections",
"to",
"RabbitMQ",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/process.py#L744-L750 | train | 30,681 |
gmr/rejected | rejected/process.py | Process.stop | def stop(self, signum=None, _unused=None):
"""Stop the consumer from consuming by calling BasicCancel and setting
our state.
:param int signum: The signal received
:param frame _unused: The stack frame from when the signal was called
"""
LOGGER.debug('Stop called in state: %s', self.state_description)
if self.is_stopped:
LOGGER.warning('Stop requested but consumer is already stopped')
return
elif self.is_shutting_down:
LOGGER.warning('Stop requested, consumer is already shutting down')
return
elif self.is_waiting_to_shutdown:
LOGGER.warning('Stop requested but already waiting to shut down')
return
# Stop consuming and close AMQP connections
self.shutdown_connections()
# Wait until the consumer has finished processing to shutdown
if self.is_processing:
LOGGER.info('Waiting for consumer to finish processing')
self.set_state(self.STATE_STOP_REQUESTED)
if signum == signal.SIGTERM:
signal.siginterrupt(signal.SIGTERM, False)
return | python | def stop(self, signum=None, _unused=None):
"""Stop the consumer from consuming by calling BasicCancel and setting
our state.
:param int signum: The signal received
:param frame _unused: The stack frame from when the signal was called
"""
LOGGER.debug('Stop called in state: %s', self.state_description)
if self.is_stopped:
LOGGER.warning('Stop requested but consumer is already stopped')
return
elif self.is_shutting_down:
LOGGER.warning('Stop requested, consumer is already shutting down')
return
elif self.is_waiting_to_shutdown:
LOGGER.warning('Stop requested but already waiting to shut down')
return
# Stop consuming and close AMQP connections
self.shutdown_connections()
# Wait until the consumer has finished processing to shutdown
if self.is_processing:
LOGGER.info('Waiting for consumer to finish processing')
self.set_state(self.STATE_STOP_REQUESTED)
if signum == signal.SIGTERM:
signal.siginterrupt(signal.SIGTERM, False)
return | [
"def",
"stop",
"(",
"self",
",",
"signum",
"=",
"None",
",",
"_unused",
"=",
"None",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'Stop called in state: %s'",
",",
"self",
".",
"state_description",
")",
"if",
"self",
".",
"is_stopped",
":",
"LOGGER",
".",
"wa... | Stop the consumer from consuming by calling BasicCancel and setting
our state.
:param int signum: The signal received
:param frame _unused: The stack frame from when the signal was called | [
"Stop",
"the",
"consumer",
"from",
"consuming",
"by",
"calling",
"BasicCancel",
"and",
"setting",
"our",
"state",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/process.py#L752-L780 | train | 30,682 |
gmr/rejected | rejected/process.py | Process.stop_consumer | def stop_consumer(self):
"""Stop the consumer object and allow it to do a clean shutdown if it
has the ability to do so.
"""
try:
LOGGER.info('Shutting down the consumer')
self.consumer.shutdown()
except AttributeError:
LOGGER.debug('Consumer does not have a shutdown method') | python | def stop_consumer(self):
"""Stop the consumer object and allow it to do a clean shutdown if it
has the ability to do so.
"""
try:
LOGGER.info('Shutting down the consumer')
self.consumer.shutdown()
except AttributeError:
LOGGER.debug('Consumer does not have a shutdown method') | [
"def",
"stop_consumer",
"(",
"self",
")",
":",
"try",
":",
"LOGGER",
".",
"info",
"(",
"'Shutting down the consumer'",
")",
"self",
".",
"consumer",
".",
"shutdown",
"(",
")",
"except",
"AttributeError",
":",
"LOGGER",
".",
"debug",
"(",
"'Consumer does not ha... | Stop the consumer object and allow it to do a clean shutdown if it
has the ability to do so. | [
"Stop",
"the",
"consumer",
"object",
"and",
"allow",
"it",
"to",
"do",
"a",
"clean",
"shutdown",
"if",
"it",
"has",
"the",
"ability",
"to",
"do",
"so",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/process.py#L782-L791 | train | 30,683 |
gmr/rejected | rejected/process.py | Process.submit_influxdb_measurement | def submit_influxdb_measurement(self):
"""Submit a measurement for a message to InfluxDB"""
measurement = influxdb.Measurement(*self.influxdb)
measurement.set_timestamp(time.time())
for key, value in self.measurement.counters.items():
measurement.set_field(key, value)
for key, value in self.measurement.tags.items():
measurement.set_tag(key, value)
for key, value in self.measurement.values.items():
measurement.set_field(key, value)
for key, values in self.measurement.durations.items():
if len(values) == 1:
measurement.set_field(key, values[0])
elif len(values) > 1:
measurement.set_field('{}-average'.format(key),
sum(values) / len(values))
measurement.set_field('{}-max'.format(key), max(values))
measurement.set_field('{}-min'.format(key), min(values))
measurement.set_field('{}-median'.format(key),
utils.percentile(values, 50))
measurement.set_field('{}-95th'.format(key),
utils.percentile(values, 95))
influxdb.add_measurement(measurement)
LOGGER.debug('InfluxDB Measurement: %r', measurement.marshall()) | python | def submit_influxdb_measurement(self):
"""Submit a measurement for a message to InfluxDB"""
measurement = influxdb.Measurement(*self.influxdb)
measurement.set_timestamp(time.time())
for key, value in self.measurement.counters.items():
measurement.set_field(key, value)
for key, value in self.measurement.tags.items():
measurement.set_tag(key, value)
for key, value in self.measurement.values.items():
measurement.set_field(key, value)
for key, values in self.measurement.durations.items():
if len(values) == 1:
measurement.set_field(key, values[0])
elif len(values) > 1:
measurement.set_field('{}-average'.format(key),
sum(values) / len(values))
measurement.set_field('{}-max'.format(key), max(values))
measurement.set_field('{}-min'.format(key), min(values))
measurement.set_field('{}-median'.format(key),
utils.percentile(values, 50))
measurement.set_field('{}-95th'.format(key),
utils.percentile(values, 95))
influxdb.add_measurement(measurement)
LOGGER.debug('InfluxDB Measurement: %r', measurement.marshall()) | [
"def",
"submit_influxdb_measurement",
"(",
"self",
")",
":",
"measurement",
"=",
"influxdb",
".",
"Measurement",
"(",
"*",
"self",
".",
"influxdb",
")",
"measurement",
".",
"set_timestamp",
"(",
"time",
".",
"time",
"(",
")",
")",
"for",
"key",
",",
"value... | Submit a measurement for a message to InfluxDB | [
"Submit",
"a",
"measurement",
"for",
"a",
"message",
"to",
"InfluxDB"
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/process.py#L793-L818 | train | 30,684 |
gmr/rejected | rejected/process.py | Process.submit_statsd_measurements | def submit_statsd_measurements(self):
"""Submit a measurement for a message to statsd as individual items."""
for key, value in self.measurement.counters.items():
self.statsd.incr(key, value)
for key, values in self.measurement.durations.items():
for value in values:
self.statsd.add_timing(key, value)
for key, value in self.measurement.values.items():
self.statsd.set_gauge(key, value)
for key, value in self.measurement.tags.items():
if isinstance(value, bool):
if value:
self.statsd.incr(key)
elif isinstance(value, str):
if value:
self.statsd.incr('{}.{}'.format(key, value))
elif isinstance(value, int):
self.statsd.incr(key, value)
else:
LOGGER.warning('The %s value type of %s is unsupported',
key, type(value)) | python | def submit_statsd_measurements(self):
"""Submit a measurement for a message to statsd as individual items."""
for key, value in self.measurement.counters.items():
self.statsd.incr(key, value)
for key, values in self.measurement.durations.items():
for value in values:
self.statsd.add_timing(key, value)
for key, value in self.measurement.values.items():
self.statsd.set_gauge(key, value)
for key, value in self.measurement.tags.items():
if isinstance(value, bool):
if value:
self.statsd.incr(key)
elif isinstance(value, str):
if value:
self.statsd.incr('{}.{}'.format(key, value))
elif isinstance(value, int):
self.statsd.incr(key, value)
else:
LOGGER.warning('The %s value type of %s is unsupported',
key, type(value)) | [
"def",
"submit_statsd_measurements",
"(",
"self",
")",
":",
"for",
"key",
",",
"value",
"in",
"self",
".",
"measurement",
".",
"counters",
".",
"items",
"(",
")",
":",
"self",
".",
"statsd",
".",
"incr",
"(",
"key",
",",
"value",
")",
"for",
"key",
"... | Submit a measurement for a message to statsd as individual items. | [
"Submit",
"a",
"measurement",
"for",
"a",
"message",
"to",
"statsd",
"as",
"individual",
"items",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/process.py#L820-L840 | train | 30,685 |
gmr/rejected | rejected/process.py | Process.profile_file | def profile_file(self):
"""Return the full path to write the cProfile data
:return: str
"""
if 'profile' in self._kwargs and self._kwargs['profile']:
profile_path = path.normpath(self._kwargs['profile'])
if os.path.exists(profile_path) and os.path.isdir(profile_path):
return path.join(
profile_path, '{}-{}.prof'.format(
os.getpid(), self._kwargs['consumer_name'])) | python | def profile_file(self):
"""Return the full path to write the cProfile data
:return: str
"""
if 'profile' in self._kwargs and self._kwargs['profile']:
profile_path = path.normpath(self._kwargs['profile'])
if os.path.exists(profile_path) and os.path.isdir(profile_path):
return path.join(
profile_path, '{}-{}.prof'.format(
os.getpid(), self._kwargs['consumer_name'])) | [
"def",
"profile_file",
"(",
"self",
")",
":",
"if",
"'profile'",
"in",
"self",
".",
"_kwargs",
"and",
"self",
".",
"_kwargs",
"[",
"'profile'",
"]",
":",
"profile_path",
"=",
"path",
".",
"normpath",
"(",
"self",
".",
"_kwargs",
"[",
"'profile'",
"]",
... | Return the full path to write the cProfile data
:return: str | [
"Return",
"the",
"full",
"path",
"to",
"write",
"the",
"cProfile",
"data"
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/process.py#L877-L888 | train | 30,686 |
gmr/rejected | rejected/utils.py | get_package_version | def get_package_version(module_obj, value):
"""Get the version of a package or a module's package.
:param object module_obj: The module that was imported for the consumer
:param str value: The namespaced module path or package name
:rtype: str or None
"""
for key in ['version', '__version__']:
if hasattr(module_obj, key):
return getattr(module_obj, key)
parts = value.split('.')
for index, part in enumerate(parts):
try:
return pkg_resources.get_distribution(
'.'.join(parts[0:index + 1])).version
except (pkg_resources.DistributionNotFound,
pkg_resources.RequirementParseError):
continue | python | def get_package_version(module_obj, value):
"""Get the version of a package or a module's package.
:param object module_obj: The module that was imported for the consumer
:param str value: The namespaced module path or package name
:rtype: str or None
"""
for key in ['version', '__version__']:
if hasattr(module_obj, key):
return getattr(module_obj, key)
parts = value.split('.')
for index, part in enumerate(parts):
try:
return pkg_resources.get_distribution(
'.'.join(parts[0:index + 1])).version
except (pkg_resources.DistributionNotFound,
pkg_resources.RequirementParseError):
continue | [
"def",
"get_package_version",
"(",
"module_obj",
",",
"value",
")",
":",
"for",
"key",
"in",
"[",
"'version'",
",",
"'__version__'",
"]",
":",
"if",
"hasattr",
"(",
"module_obj",
",",
"key",
")",
":",
"return",
"getattr",
"(",
"module_obj",
",",
"key",
"... | Get the version of a package or a module's package.
:param object module_obj: The module that was imported for the consumer
:param str value: The namespaced module path or package name
:rtype: str or None | [
"Get",
"the",
"version",
"of",
"a",
"package",
"or",
"a",
"module",
"s",
"package",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/utils.py#L6-L24 | train | 30,687 |
gmr/rejected | rejected/utils.py | import_consumer | def import_consumer(value):
"""Pass in a string in the format of foo.Bar, foo.bar.Baz, foo.bar.baz.Qux
and it will return a handle to the class, and the version.
:param str value: The consumer class in module.Consumer format
:return: tuple(Class, str)
"""
parts = value.split('.')
module_obj = importlib.import_module('.'.join(parts[0:-1]))
return (getattr(module_obj, parts[-1]),
get_package_version(module_obj, value)) | python | def import_consumer(value):
"""Pass in a string in the format of foo.Bar, foo.bar.Baz, foo.bar.baz.Qux
and it will return a handle to the class, and the version.
:param str value: The consumer class in module.Consumer format
:return: tuple(Class, str)
"""
parts = value.split('.')
module_obj = importlib.import_module('.'.join(parts[0:-1]))
return (getattr(module_obj, parts[-1]),
get_package_version(module_obj, value)) | [
"def",
"import_consumer",
"(",
"value",
")",
":",
"parts",
"=",
"value",
".",
"split",
"(",
"'.'",
")",
"module_obj",
"=",
"importlib",
".",
"import_module",
"(",
"'.'",
".",
"join",
"(",
"parts",
"[",
"0",
":",
"-",
"1",
"]",
")",
")",
"return",
"... | Pass in a string in the format of foo.Bar, foo.bar.Baz, foo.bar.baz.Qux
and it will return a handle to the class, and the version.
:param str value: The consumer class in module.Consumer format
:return: tuple(Class, str) | [
"Pass",
"in",
"a",
"string",
"in",
"the",
"format",
"of",
"foo",
".",
"Bar",
"foo",
".",
"bar",
".",
"Baz",
"foo",
".",
"bar",
".",
"baz",
".",
"Qux",
"and",
"it",
"will",
"return",
"a",
"handle",
"to",
"the",
"class",
"and",
"the",
"version",
".... | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/utils.py#L27-L38 | train | 30,688 |
gmr/rejected | rejected/utils.py | message_info | def message_info(exchange, routing_key, properties):
"""Return info about a message using the same conditional constructs
:param str exchange: The exchange the message was published to
:param str routing_key: The routing key used
:param properties: The AMQP message properties
:type properties: pika.spec.Basic.Properties
:rtype: str
"""
output = []
if properties.message_id:
output.append(properties.message_id)
if properties.correlation_id:
output.append('[correlation_id="{}"]'.format(
properties.correlation_id))
if exchange:
output.append('published to "{}"'.format(exchange))
if routing_key:
output.append('using "{}"'.format(routing_key))
return ' '.join(output) | python | def message_info(exchange, routing_key, properties):
"""Return info about a message using the same conditional constructs
:param str exchange: The exchange the message was published to
:param str routing_key: The routing key used
:param properties: The AMQP message properties
:type properties: pika.spec.Basic.Properties
:rtype: str
"""
output = []
if properties.message_id:
output.append(properties.message_id)
if properties.correlation_id:
output.append('[correlation_id="{}"]'.format(
properties.correlation_id))
if exchange:
output.append('published to "{}"'.format(exchange))
if routing_key:
output.append('using "{}"'.format(routing_key))
return ' '.join(output) | [
"def",
"message_info",
"(",
"exchange",
",",
"routing_key",
",",
"properties",
")",
":",
"output",
"=",
"[",
"]",
"if",
"properties",
".",
"message_id",
":",
"output",
".",
"append",
"(",
"properties",
".",
"message_id",
")",
"if",
"properties",
".",
"corr... | Return info about a message using the same conditional constructs
:param str exchange: The exchange the message was published to
:param str routing_key: The routing key used
:param properties: The AMQP message properties
:type properties: pika.spec.Basic.Properties
:rtype: str | [
"Return",
"info",
"about",
"a",
"message",
"using",
"the",
"same",
"conditional",
"constructs"
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/utils.py#L41-L61 | train | 30,689 |
gmr/rejected | rejected/data.py | Measurement.add_duration | def add_duration(self, key, value):
"""Add a duration for the specified key
:param str key: The value name
:param float value: The value
.. versionadded:: 3.19.0
"""
if key not in self.durations:
self.durations[key] = []
self.durations[key].append(value) | python | def add_duration(self, key, value):
"""Add a duration for the specified key
:param str key: The value name
:param float value: The value
.. versionadded:: 3.19.0
"""
if key not in self.durations:
self.durations[key] = []
self.durations[key].append(value) | [
"def",
"add_duration",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"key",
"not",
"in",
"self",
".",
"durations",
":",
"self",
".",
"durations",
"[",
"key",
"]",
"=",
"[",
"]",
"self",
".",
"durations",
"[",
"key",
"]",
".",
"append",
"... | Add a duration for the specified key
:param str key: The value name
:param float value: The value
.. versionadded:: 3.19.0 | [
"Add",
"a",
"duration",
"for",
"the",
"specified",
"key"
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/data.py#L223-L234 | train | 30,690 |
gmr/rejected | rejected/data.py | Measurement.track_duration | def track_duration(self, key):
"""Context manager that sets a value with the duration of time that it
takes to execute whatever it is wrapping.
:param str key: The timing name
"""
if key not in self.durations:
self.durations[key] = []
start_time = time.time()
try:
yield
finally:
self.durations[key].append(
max(start_time, time.time()) - start_time) | python | def track_duration(self, key):
"""Context manager that sets a value with the duration of time that it
takes to execute whatever it is wrapping.
:param str key: The timing name
"""
if key not in self.durations:
self.durations[key] = []
start_time = time.time()
try:
yield
finally:
self.durations[key].append(
max(start_time, time.time()) - start_time) | [
"def",
"track_duration",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"not",
"in",
"self",
".",
"durations",
":",
"self",
".",
"durations",
"[",
"key",
"]",
"=",
"[",
"]",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"try",
":",
"yield",
... | Context manager that sets a value with the duration of time that it
takes to execute whatever it is wrapping.
:param str key: The timing name | [
"Context",
"manager",
"that",
"sets",
"a",
"value",
"with",
"the",
"duration",
"of",
"time",
"that",
"it",
"takes",
"to",
"execute",
"whatever",
"it",
"is",
"wrapping",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/data.py#L257-L271 | train | 30,691 |
gmr/rejected | rejected/log.py | CorrelationFilter.filter | def filter(self, record):
"""Is the specified record to be logged? Returns zero for no,
nonzero for yes. If deemed appropriate, the record may be modified
in-place by this method.
:param logging.LogRecord record: The log record to process
:rtype: int
"""
if self._exists:
return int(getattr(record, 'correlation_id', None) is not None)
return int(getattr(record, 'correlation_id', None) is None) | python | def filter(self, record):
"""Is the specified record to be logged? Returns zero for no,
nonzero for yes. If deemed appropriate, the record may be modified
in-place by this method.
:param logging.LogRecord record: The log record to process
:rtype: int
"""
if self._exists:
return int(getattr(record, 'correlation_id', None) is not None)
return int(getattr(record, 'correlation_id', None) is None) | [
"def",
"filter",
"(",
"self",
",",
"record",
")",
":",
"if",
"self",
".",
"_exists",
":",
"return",
"int",
"(",
"getattr",
"(",
"record",
",",
"'correlation_id'",
",",
"None",
")",
"is",
"not",
"None",
")",
"return",
"int",
"(",
"getattr",
"(",
"reco... | Is the specified record to be logged? Returns zero for no,
nonzero for yes. If deemed appropriate, the record may be modified
in-place by this method.
:param logging.LogRecord record: The log record to process
:rtype: int | [
"Is",
"the",
"specified",
"record",
"to",
"be",
"logged?",
"Returns",
"zero",
"for",
"no",
"nonzero",
"for",
"yes",
".",
"If",
"deemed",
"appropriate",
"the",
"record",
"may",
"be",
"modified",
"in",
"-",
"place",
"by",
"this",
"method",
"."
] | 610a3e1401122ecb98d891b6795cca0255e5b044 | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/log.py#L36-L47 | train | 30,692 |
genialis/django-rest-framework-reactive | src/rest_framework_reactive/request.py | Request.observe_id | def observe_id(self):
"""Unique identifier that identifies the observer."""
if self._observe_id is None:
hasher = hashlib.sha256()
hasher.update(self.viewset_class.__module__.encode('utf8'))
hasher.update(self.viewset_class.__name__.encode('utf8'))
hasher.update(self.viewset_method.encode('utf8'))
# Arguments do not need to be taken into account as they are
# derived from the request path, which is already accounted for.
for key in sorted(self.GET.keys()):
hasher.update(key.encode('utf8'))
hasher.update(self.GET[key].encode('utf8'))
hasher.update(self.path.encode('utf8'))
hasher.update(self.path_info.encode('utf8'))
if self._force_auth_user is not None:
hasher.update(
(str(self._force_auth_user.id) or 'anonymous').encode('utf8')
)
else:
hasher.update(b'anonymous')
self._observe_id = hasher.hexdigest()
return self._observe_id | python | def observe_id(self):
"""Unique identifier that identifies the observer."""
if self._observe_id is None:
hasher = hashlib.sha256()
hasher.update(self.viewset_class.__module__.encode('utf8'))
hasher.update(self.viewset_class.__name__.encode('utf8'))
hasher.update(self.viewset_method.encode('utf8'))
# Arguments do not need to be taken into account as they are
# derived from the request path, which is already accounted for.
for key in sorted(self.GET.keys()):
hasher.update(key.encode('utf8'))
hasher.update(self.GET[key].encode('utf8'))
hasher.update(self.path.encode('utf8'))
hasher.update(self.path_info.encode('utf8'))
if self._force_auth_user is not None:
hasher.update(
(str(self._force_auth_user.id) or 'anonymous').encode('utf8')
)
else:
hasher.update(b'anonymous')
self._observe_id = hasher.hexdigest()
return self._observe_id | [
"def",
"observe_id",
"(",
"self",
")",
":",
"if",
"self",
".",
"_observe_id",
"is",
"None",
":",
"hasher",
"=",
"hashlib",
".",
"sha256",
"(",
")",
"hasher",
".",
"update",
"(",
"self",
".",
"viewset_class",
".",
"__module__",
".",
"encode",
"(",
"'utf... | Unique identifier that identifies the observer. | [
"Unique",
"identifier",
"that",
"identifies",
"the",
"observer",
"."
] | ddf3d899685a54b6bd0ae4b3789649a89340c59f | https://github.com/genialis/django-rest-framework-reactive/blob/ddf3d899685a54b6bd0ae4b3789649a89340c59f/src/rest_framework_reactive/request.py#L43-L65 | train | 30,693 |
genialis/django-rest-framework-reactive | src/rest_framework_reactive/views.py | QueryObserverUnsubscribeView.post | def post(self, request):
"""Handle a query observer unsubscription request."""
try:
observer_id = request.query_params['observer']
session_id = request.query_params['subscriber']
except KeyError:
return response.Response(status=400)
observer.remove_subscriber(session_id, observer_id)
return response.Response() | python | def post(self, request):
"""Handle a query observer unsubscription request."""
try:
observer_id = request.query_params['observer']
session_id = request.query_params['subscriber']
except KeyError:
return response.Response(status=400)
observer.remove_subscriber(session_id, observer_id)
return response.Response() | [
"def",
"post",
"(",
"self",
",",
"request",
")",
":",
"try",
":",
"observer_id",
"=",
"request",
".",
"query_params",
"[",
"'observer'",
"]",
"session_id",
"=",
"request",
".",
"query_params",
"[",
"'subscriber'",
"]",
"except",
"KeyError",
":",
"return",
... | Handle a query observer unsubscription request. | [
"Handle",
"a",
"query",
"observer",
"unsubscription",
"request",
"."
] | ddf3d899685a54b6bd0ae4b3789649a89340c59f | https://github.com/genialis/django-rest-framework-reactive/blob/ddf3d899685a54b6bd0ae4b3789649a89340c59f/src/rest_framework_reactive/views.py#L7-L16 | train | 30,694 |
genialis/django-rest-framework-reactive | src/rest_framework_reactive/signals.py | notify_observers | def notify_observers(table, kind, primary_key=None):
"""Transmit ORM table change notification.
:param table: Name of the table that has changed
:param kind: Change type
:param primary_key: Primary key of the affected instance
"""
if IN_MIGRATIONS:
return
# Don't propagate events when there are no observers to receive them.
if not Observer.objects.filter(dependencies__table=table).exists():
return
def handler():
"""Send a notification to the given channel."""
try:
async_to_sync(get_channel_layer().send)(
CHANNEL_MAIN,
{
'type': TYPE_ORM_NOTIFY,
'table': table,
'kind': kind,
'primary_key': str(primary_key),
},
)
except ChannelFull:
logger.exception("Unable to notify workers.")
batcher = PrioritizedBatcher.global_instance()
if batcher.is_started:
# If a batch is open, queue the send via the batcher.
batcher.add(
'rest_framework_reactive', handler, group_by=(table, kind, primary_key)
)
else:
# If no batch is open, invoke immediately.
handler() | python | def notify_observers(table, kind, primary_key=None):
"""Transmit ORM table change notification.
:param table: Name of the table that has changed
:param kind: Change type
:param primary_key: Primary key of the affected instance
"""
if IN_MIGRATIONS:
return
# Don't propagate events when there are no observers to receive them.
if not Observer.objects.filter(dependencies__table=table).exists():
return
def handler():
"""Send a notification to the given channel."""
try:
async_to_sync(get_channel_layer().send)(
CHANNEL_MAIN,
{
'type': TYPE_ORM_NOTIFY,
'table': table,
'kind': kind,
'primary_key': str(primary_key),
},
)
except ChannelFull:
logger.exception("Unable to notify workers.")
batcher = PrioritizedBatcher.global_instance()
if batcher.is_started:
# If a batch is open, queue the send via the batcher.
batcher.add(
'rest_framework_reactive', handler, group_by=(table, kind, primary_key)
)
else:
# If no batch is open, invoke immediately.
handler() | [
"def",
"notify_observers",
"(",
"table",
",",
"kind",
",",
"primary_key",
"=",
"None",
")",
":",
"if",
"IN_MIGRATIONS",
":",
"return",
"# Don't propagate events when there are no observers to receive them.",
"if",
"not",
"Observer",
".",
"objects",
".",
"filter",
"(",... | Transmit ORM table change notification.
:param table: Name of the table that has changed
:param kind: Change type
:param primary_key: Primary key of the affected instance | [
"Transmit",
"ORM",
"table",
"change",
"notification",
"."
] | ddf3d899685a54b6bd0ae4b3789649a89340c59f | https://github.com/genialis/django-rest-framework-reactive/blob/ddf3d899685a54b6bd0ae4b3789649a89340c59f/src/rest_framework_reactive/signals.py#L35-L73 | train | 30,695 |
genialis/django-rest-framework-reactive | src/rest_framework_reactive/signals.py | model_post_save | def model_post_save(sender, instance, created=False, **kwargs):
"""Signal emitted after any model is saved via Django ORM.
:param sender: Model class that was saved
:param instance: The actual instance that was saved
:param created: True if a new row was created
"""
if sender._meta.app_label == 'rest_framework_reactive':
# Ignore own events.
return
def notify():
table = sender._meta.db_table
if created:
notify_observers(table, ORM_NOTIFY_KIND_CREATE, instance.pk)
else:
notify_observers(table, ORM_NOTIFY_KIND_UPDATE, instance.pk)
transaction.on_commit(notify) | python | def model_post_save(sender, instance, created=False, **kwargs):
"""Signal emitted after any model is saved via Django ORM.
:param sender: Model class that was saved
:param instance: The actual instance that was saved
:param created: True if a new row was created
"""
if sender._meta.app_label == 'rest_framework_reactive':
# Ignore own events.
return
def notify():
table = sender._meta.db_table
if created:
notify_observers(table, ORM_NOTIFY_KIND_CREATE, instance.pk)
else:
notify_observers(table, ORM_NOTIFY_KIND_UPDATE, instance.pk)
transaction.on_commit(notify) | [
"def",
"model_post_save",
"(",
"sender",
",",
"instance",
",",
"created",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"sender",
".",
"_meta",
".",
"app_label",
"==",
"'rest_framework_reactive'",
":",
"# Ignore own events.",
"return",
"def",
"notify"... | Signal emitted after any model is saved via Django ORM.
:param sender: Model class that was saved
:param instance: The actual instance that was saved
:param created: True if a new row was created | [
"Signal",
"emitted",
"after",
"any",
"model",
"is",
"saved",
"via",
"Django",
"ORM",
"."
] | ddf3d899685a54b6bd0ae4b3789649a89340c59f | https://github.com/genialis/django-rest-framework-reactive/blob/ddf3d899685a54b6bd0ae4b3789649a89340c59f/src/rest_framework_reactive/signals.py#L77-L96 | train | 30,696 |
genialis/django-rest-framework-reactive | src/rest_framework_reactive/signals.py | model_post_delete | def model_post_delete(sender, instance, **kwargs):
"""Signal emitted after any model is deleted via Django ORM.
:param sender: Model class that was deleted
:param instance: The actual instance that was removed
"""
if sender._meta.app_label == 'rest_framework_reactive':
# Ignore own events.
return
def notify():
table = sender._meta.db_table
notify_observers(table, ORM_NOTIFY_KIND_DELETE, instance.pk)
transaction.on_commit(notify) | python | def model_post_delete(sender, instance, **kwargs):
"""Signal emitted after any model is deleted via Django ORM.
:param sender: Model class that was deleted
:param instance: The actual instance that was removed
"""
if sender._meta.app_label == 'rest_framework_reactive':
# Ignore own events.
return
def notify():
table = sender._meta.db_table
notify_observers(table, ORM_NOTIFY_KIND_DELETE, instance.pk)
transaction.on_commit(notify) | [
"def",
"model_post_delete",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"sender",
".",
"_meta",
".",
"app_label",
"==",
"'rest_framework_reactive'",
":",
"# Ignore own events.",
"return",
"def",
"notify",
"(",
")",
":",
"table",
... | Signal emitted after any model is deleted via Django ORM.
:param sender: Model class that was deleted
:param instance: The actual instance that was removed | [
"Signal",
"emitted",
"after",
"any",
"model",
"is",
"deleted",
"via",
"Django",
"ORM",
"."
] | ddf3d899685a54b6bd0ae4b3789649a89340c59f | https://github.com/genialis/django-rest-framework-reactive/blob/ddf3d899685a54b6bd0ae4b3789649a89340c59f/src/rest_framework_reactive/signals.py#L100-L115 | train | 30,697 |
genialis/django-rest-framework-reactive | src/rest_framework_reactive/signals.py | model_m2m_changed | def model_m2m_changed(sender, instance, action, **kwargs):
"""
Signal emitted after any M2M relation changes via Django ORM.
:param sender: M2M intermediate model
:param instance: The actual instance that was saved
:param action: M2M action
"""
if sender._meta.app_label == 'rest_framework_reactive':
# Ignore own events.
return
def notify():
table = sender._meta.db_table
if action == 'post_add':
notify_observers(table, ORM_NOTIFY_KIND_CREATE)
elif action in ('post_remove', 'post_clear'):
notify_observers(table, ORM_NOTIFY_KIND_DELETE)
transaction.on_commit(notify) | python | def model_m2m_changed(sender, instance, action, **kwargs):
"""
Signal emitted after any M2M relation changes via Django ORM.
:param sender: M2M intermediate model
:param instance: The actual instance that was saved
:param action: M2M action
"""
if sender._meta.app_label == 'rest_framework_reactive':
# Ignore own events.
return
def notify():
table = sender._meta.db_table
if action == 'post_add':
notify_observers(table, ORM_NOTIFY_KIND_CREATE)
elif action in ('post_remove', 'post_clear'):
notify_observers(table, ORM_NOTIFY_KIND_DELETE)
transaction.on_commit(notify) | [
"def",
"model_m2m_changed",
"(",
"sender",
",",
"instance",
",",
"action",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"sender",
".",
"_meta",
".",
"app_label",
"==",
"'rest_framework_reactive'",
":",
"# Ignore own events.",
"return",
"def",
"notify",
"(",
")",
... | Signal emitted after any M2M relation changes via Django ORM.
:param sender: M2M intermediate model
:param instance: The actual instance that was saved
:param action: M2M action | [
"Signal",
"emitted",
"after",
"any",
"M2M",
"relation",
"changes",
"via",
"Django",
"ORM",
"."
] | ddf3d899685a54b6bd0ae4b3789649a89340c59f | https://github.com/genialis/django-rest-framework-reactive/blob/ddf3d899685a54b6bd0ae4b3789649a89340c59f/src/rest_framework_reactive/signals.py#L119-L139 | train | 30,698 |
genialis/django-rest-framework-reactive | src/rest_framework_reactive/consumers.py | MainConsumer.observer_orm_notify | async def observer_orm_notify(self, message):
"""Process notification from ORM."""
@database_sync_to_async
def get_observers(table):
# Find all observers with dependencies on the given table.
return list(
Observer.objects.filter(
dependencies__table=table, subscribers__isnull=False
)
.distinct('pk')
.values_list('pk', flat=True)
)
observers_ids = await get_observers(message['table'])
for observer_id in observers_ids:
await self.channel_layer.send(
CHANNEL_WORKER, {'type': TYPE_EVALUATE, 'observer': observer_id}
) | python | async def observer_orm_notify(self, message):
"""Process notification from ORM."""
@database_sync_to_async
def get_observers(table):
# Find all observers with dependencies on the given table.
return list(
Observer.objects.filter(
dependencies__table=table, subscribers__isnull=False
)
.distinct('pk')
.values_list('pk', flat=True)
)
observers_ids = await get_observers(message['table'])
for observer_id in observers_ids:
await self.channel_layer.send(
CHANNEL_WORKER, {'type': TYPE_EVALUATE, 'observer': observer_id}
) | [
"async",
"def",
"observer_orm_notify",
"(",
"self",
",",
"message",
")",
":",
"@",
"database_sync_to_async",
"def",
"get_observers",
"(",
"table",
")",
":",
"# Find all observers with dependencies on the given table.",
"return",
"list",
"(",
"Observer",
".",
"objects",
... | Process notification from ORM. | [
"Process",
"notification",
"from",
"ORM",
"."
] | ddf3d899685a54b6bd0ae4b3789649a89340c59f | https://github.com/genialis/django-rest-framework-reactive/blob/ddf3d899685a54b6bd0ae4b3789649a89340c59f/src/rest_framework_reactive/consumers.py#L28-L47 | train | 30,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.