Skip to content

Commit

Permalink
Add a "run" consumer callback
Browse files Browse the repository at this point in the history
Runs a configurable command when a message is received.

Fixes fedora-infra#155

Signed-off-by: Jeremy Cline <[email protected]>
  • Loading branch information
jeremycline committed Apr 17, 2019
1 parent fce0ed3 commit 723217c
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
9 changes: 9 additions & 0 deletions docs/consuming.rst
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,15 @@ called when a message arrives::
api.consume(PrintMessage)


Common Consumers
================

Several generally useful consumers are shipped with fedora-messaging.

.. autofunction:: fedora_messaging.callbacks.printer
.. autofunction:: fedora_messaging.callbacks.run


.. _AMQP overview: https://www.rabbitmq.com/tutorials/amqp-concepts.html
.. _RabbitMQ tutorials: https://www.rabbitmq.com/getstarted.html
.. _pika: https://pika.readthedocs.io/
Expand Down
44 changes: 44 additions & 0 deletions fedora_messaging/callbacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,15 @@
"""This module contains a set of callbacks that are generally useful."""
from __future__ import print_function

import logging
import subprocess

import six

from . import config, exceptions

_log = logging.getLogger(__name__)


def printer(message):
"""
Expand All @@ -30,3 +37,40 @@ def printer(message):
message (fedora_messaging.api.Message): The message that was received.
"""
print(six.text_type(message))


def run(message):
"""
Run a command in a subprocess.
**Configuration Options**
This consumer uses the following configuration keys in the :ref:`conf-consumer-config`
section of the configuration file:
* ``command`` (string or list of strings): The arguments to launch the process
as a string or list of strings.
* ``shell`` (boolean): Whether or not to execute the command in a shell. Refer to the
`security considerations
<https://docs.python.org/3/library/subprocess.html#security-considerations>`_
before setting this to true. Defaults to false.
* ``timeout`` (integer): The length of time, in seconds, to wait on the command
before halting the command and returning the message to the queue for later
processing. Defaults to no timeout.
"""
try:
subprocess.check_call(
config.conf["consumer_config"]["command"],
shell=config.conf["consumer_config"].get("shell", False),
timeout=config.conf["consumer_config"].get("timeout"),
)
except subprocess.CalledProcessError:
raise exceptions.Drop()
except subprocess.TimeoutExpired as e:
_log.error(
"{} failed to return after {} seconds; returning {} to the queue",
e.cmd,
e.timeout,
str(message.id),
)
raise exceptions.Nack()

0 comments on commit 723217c

Please sign in to comment.