Ejemplo n.º 1
0
def sign(authenticator, message):
    """
    Sign the message using the specified validator.
    signed document:
      {
        message: <message>,
        signature: <signature>
      }
    :param authenticator: A message authenticator.
    :type authenticator: Authenticator
    :param message: A (signed) json encoded AMQP message.
    :rtype message: str
    """
    if not authenticator:
        return message
    try:
        h = sha256()
        h.update(message)
        digest = h.hexdigest()
        signature = authenticator.sign(digest)
        signed = Document(message=message, signature=encode(signature))
        message = signed.dump()
    except Exception, e:
        log.info(utf8(e))
        log.debug(message, exc_info=True)
Ejemplo n.º 2
0
def sign(authenticator, message):
    """
    Sign the message using the specified validator.
    signed document:
      {
        message: <message>,
        signature: <signature>
      }
    :param authenticator: A message authenticator.
    :type authenticator: Authenticator
    :param message: A (signed) json encoded AMQP message.
    :rtype message: str
    """
    if not authenticator:
        return message
    try:
        h = sha256()
        h.update(message)
        digest = h.hexdigest()
        signature = authenticator.sign(digest)
        signed = Document(message=message, signature=encode(signature))
        message = signed.dump()
    except Exception, e:
        log.info(utf8(e))
        log.debug(message, exc_info=True)
Ejemplo n.º 3
0
def validate(authenticator, message):
    """
    Validate the document using the specified validator.
    signed document:
      {
        message: <message>,
        signature: <signature>
      }
    :param authenticator: A message authenticator.
    :type authenticator: Authenticator
    :param message: A json encoded AMQP message.
    :rtype message: str
    :return: The authenticated document.
    :rtype: Document
    :raises ValidationFailed: when message is not valid.
    """
    document, original, signature = peal(message)
    try:
        if authenticator:
            h = sha256()
            h.update(original)
            digest = h.hexdigest()
            authenticator.validate(document, digest, decode(signature))
        return document
    except ValidationFailed, de:
        de.document = document
        log.info(utf8(de))
        raise de
Ejemplo n.º 4
0
 def domain_id(self):
     """
     Unique domain ID.
     :return: A unique domain ID.
     :rtype: str
     """
     return '::'.join((self.__class__.__name__, utf8(id(self))))
Ejemplo n.º 5
0
 def _fn(messenger, *args, **kwargs):
     repair = lambda: None
     while not Thread.aborted():
         try:
             repair()
             return fn(messenger, *args, **kwargs)
         except LinkDetached, le:
             if le.condition != NOT_FOUND:
                 log.error(utf8(le))
                 repair = messenger.repair
                 sleep(DELAY)
             else:
                 raise NotFound(*le.args)
         except ConnectionException, pe:
             log.error(utf8(pe))
             repair = messenger.repair
             sleep(DELAY)
Ejemplo n.º 6
0
 def _fn(messenger, *args, **kwargs):
     repair = lambda: None
     while not Thread.aborted():
         try:
             repair()
             return fn(messenger, *args, **kwargs)
         except ChannelError, le:
             if le.code != 404:
                 log.error(utf8(le))
                 repair = messenger.repair
                 sleep(DELAY)
             else:
                 raise NotFound(*le.args)
         except CONNECTION_EXCEPTIONS, pe:
             log.error(utf8(pe))
             repair = messenger.repair
             sleep(DELAY)
Ejemplo n.º 7
0
 def _fn(messenger, *args, **kwargs):
     repair = lambda: None
     while not Thread.aborted():
         try:
             repair()
             return fn(messenger, *args, **kwargs)
         except LinkDetached, le:
             if le.condition != NOT_FOUND:
                 log.error(utf8(le))
                 repair = messenger.repair
                 sleep(DELAY)
             else:
                 raise NotFound(*le.args)
         except ConnectionException, pe:
             log.error(utf8(pe))
             repair = messenger.repair
             sleep(DELAY)
Ejemplo n.º 8
0
 def _fn(*args, **keywords):
     try:
         return fn(*args, **keywords)
     except ModelError:
         raise
     except Exception, e:
         log.exception(utf8(e))
         raise ModelError(*e.args)
Ejemplo n.º 9
0
 def _fn(messenger, *args, **kwargs):
     repair = lambda: None
     while not Thread.aborted():
         try:
             repair()
             return fn(messenger, *args, **kwargs)
         except ChannelError, le:
             if le.code != 404:
                 log.error(utf8(le))
                 repair = messenger.repair
                 sleep(DELAY)
             else:
                 raise NotFound(*le.args)
         except CONNECTION_EXCEPTIONS, pe:
             log.error(utf8(pe))
             repair = messenger.repair
             sleep(DELAY)
Ejemplo n.º 10
0
 def __call__(self, *args, **kwargs):
     try:
         result = self.call(*args, **kwargs)
     except Exception, e:
         reply = Document()
         reply.code = 1
         reply.result = utf8(e)
         result = reply
Ejemplo n.º 11
0
 def __call__(self, *args, **kwargs):
     try:
         result = self.call(*args, **kwargs)
     except Exception, e:
         reply = Document()
         reply.code = 1
         reply.result = utf8(e)
         result = reply
Ejemplo n.º 12
0
 def __init__(self, name=None, url=None):
     """
     :param name: The queue name.
     :type name: str
     :param url: The (optional) broker URL.
     :type url: str
     """
     BaseQueue.__init__(self, name or utf8(uuid4()))
     self.url = url
Ejemplo n.º 13
0
 def unloaded(self):
     """
     Plugin unloaded.
     """
     for fn in self.unload:
         try:
             fn()
         except Exception:
             log.exception(utf8(fn))
Ejemplo n.º 14
0
 def close(self):
     """
     Close the receiver.
     """
     try:
         channel = self.channel()
         channel.basic_cancel(self.tag)
     except Exception, e:
         log.debug(utf8(e))
Ejemplo n.º 15
0
 def unloaded(self):
     """
     Plugin unloaded.
     """
     for fn in self.unload:
         try:
             fn()
         except Exception:
             log.exception(utf8(fn))
Ejemplo n.º 16
0
 def setpid(self, pid=os.getpid()):
     """
     Write our procecss id and flush.
     :param pid: The process ID.
     :type pid: int
     """
     self.__fp.seek(0)
     self.__fp.write(utf8(pid))
     self.__fp.flush()
Ejemplo n.º 17
0
 def setpid(self, pid=os.getpid()):
     """
     Write our procecss id and flush.
     :param pid: The process ID.
     :type pid: int
     """
     self.__fp.seek(0)
     self.__fp.write(utf8(pid))
     self.__fp.flush()
Ejemplo n.º 18
0
 def close(self):
     """
     Close the receiver.
     """
     try:
         channel = self.channel()
         channel.basic_cancel(self.tag)
     except Exception, e:
         log.debug(utf8(e))
Ejemplo n.º 19
0
 def sender(self, address):
     """
     Get a message sender for the specified address.
     :param address: An AMQP address.
     :type address: str
     :return: A sender.
     :rtype: proton.utils.BlockingSender
     """
     name = utf8(uuid4())
     return self._impl.create_sender(address, name=name)
Ejemplo n.º 20
0
 def sender(self, address):
     """
     Get a message sender for the specified address.
     :param address: An AMQP address.
     :type address: str
     :return: A sender.
     :rtype: proton.utils.BlockingSender
     """
     name = utf8(uuid4())
     return self._impl.create_sender(address, name=name)
Ejemplo n.º 21
0
 def close(self):
     """
     Close the connection.
     """
     connection = self._impl
     self._impl = None
     try:
         connection.close()
         log.info('closed: %s', self.url)
     except Exception, pe:
         log.debug(utf8(pe))
Ejemplo n.º 22
0
 def close(self):
     """
     Close the connection.
     """
     connection = self._impl
     self._impl = None
     try:
         connection.close()
         log.info('closed: %s', self.url)
     except Exception, pe:
         log.exception(utf8(pe))
Ejemplo n.º 23
0
def validate(document):
    """
    Determine whether the specified document is valid.
    :param document: The document to evaluate.
    :type document: Document
    :raises InvalidDocument: when invalid.
    """
    if document.version != VERSION:
        failed = InvalidVersion(document.dump(), VERSION, document.version)
        log.warn(utf8(failed))
        raise failed
Ejemplo n.º 24
0
def validate(document):
    """
    Determine whether the specified document is valid.
    :param document: The document to evaluate.
    :type document: Document
    :raises DocumentError: when invalid.
    """
    if document.version != VERSION:
        error = VersionError(document, VERSION, document.version)
        log.warn(utf8(error))
        raise error
Ejemplo n.º 25
0
def validate(document):
    """
    Determine whether the specified document is valid.
    :param document: The document to evaluate.
    :type document: Document
    :raises DocumentError: when invalid.
    """
    if document.version != VERSION:
        error = VersionError(document, VERSION, document.version)
        log.warn(utf8(error))
        raise error
Ejemplo n.º 26
0
 def __init__(self, policy, request):
     """
     :param policy: The policy object.
     :type policy: Policy
     :param request: A request to send.
     :type request: object
     """
     self._sn = utf8(uuid4())
     self._policy = policy
     self._request = request
     self._pending = True
Ejemplo n.º 27
0
 def __init__(self, policy, request):
     """
     :param policy: The policy object.
     :type policy: Policy
     :param request: A request to send.
     :type request: object
     """
     self._sn = utf8(uuid4())
     self._policy = policy
     self._request = request
     self._pending = True
Ejemplo n.º 28
0
 def _fn(thing, *args, **kwargs):
     repair = lambda: None
     while not Thread.aborted():
         try:
             repair()
             return fn(thing, *args, **kwargs)
         except _NotFound, e:
             raise NotFound(*e.args)
         except LinkError, le:
             log.error(utf8(le))
             repair = thing.repair
             sleep(DELAY)
Ejemplo n.º 29
0
 def _fn(thing, *args, **kwargs):
     repair = lambda: None
     while not Thread.aborted():
         try:
             repair()
             return fn(thing, *args, **kwargs)
         except _NotFound, e:
             raise NotFound(*e.args)
         except LinkError, le:
             log.error(utf8(le))
             repair = thing.repair
             sleep(DELAY)
Ejemplo n.º 30
0
 def __call__(self):
     """
     Invoke the method.
     :return: The invocation result.
     :rtype: Return
     """
     try:
         self.permitted()
         retval = self.method(*self.args, **self.kwargs)
         return Return.succeed(retval)
     except Exception:
         log.exception(utf8(self.method))
         return Return.exception()
Ejemplo n.º 31
0
 def __call__(self):
     """
     Invoke the method.
     :return: The invocation result.
     :rtype: Return
     """
     try:
         self.permitted()
         retval = self.method(*self.args, **self.kwargs)
         return Return.succeed(retval)
     except Exception:
         log.exception(utf8(self.method))
         return Return.exception()
Ejemplo n.º 32
0
def setup_logging():
    """
    Set logging levels based on configuration.
    """
    cfg = AgentConfig()
    for name, level in cfg.logging:
        if not level:
            continue
        try:
            logger = logging.getLogger(name)
            level = getattr(logging, level.upper())
            logger.setLevel(level)
        except Exception, e:
            log.error(utf8(e))
Ejemplo n.º 33
0
def setup_logging():
    """
    Set logging levels based on configuration.
    """
    cfg = AgentConfig()
    for name, level in cfg.logging:
        if not level:
            continue
        try:
            logger = logging.getLogger(name)
            level = getattr(logging, level.upper())
            logger.setLevel(level)
        except Exception, e:
            log.error(utf8(e))
Ejemplo n.º 34
0
 def dispatch(self, call):
     """
     Dispatch the call to the handler.
     :param call: A *call* document.
     :type call: Document
     """
     reply = Document()
     try:
         method = getattr(self.handler, call.name)
         result = method(*call.args, **call.kwargs)
         reply.code = 0
         reply.result = result
     except Exception, e:
         reply.code = 1
         reply.result = utf8(e)
Ejemplo n.º 35
0
 def __call__(self):
     """
     Invoke the method.
     :return: The invocation result.
     :rtype: Return
     """
     try:
         self.permitted()
         fninfo = RMI.fninfo(self.method)
         model = ALL[fninfo.call.model](self.method, *self.args, **self.kwargs)
         retval = model()
         return Return.succeed(retval)
     except Exception:
         log.exception(utf8(self.method))
         return Return.exception()
Ejemplo n.º 36
0
 def dispatch(self, call):
     """
     Dispatch the call to the handler.
     :param call: A *call* document.
     :type call: Document
     """
     reply = Document()
     try:
         method = getattr(self.handler, call.name)
         result = method(*call.args, **call.kwargs)
         reply.code = 0
         reply.result = result
     except Exception, e:
         reply.code = 1
         reply.result = utf8(e)
Ejemplo n.º 37
0
 def run(self):
     """
     Main run loop; processes input queue.
     """
     while not Thread.aborted():
         call = self.queue.get()
         if call == 1:
             # # busy
             continue
         if not call:
             # termination requested
             return
         try:
             call()
         except Exception:
             log.exception(utf8(call))
Ejemplo n.º 38
0
 def accepted(self, client):
     """
     Process the request on the accepted socket.
     :param client: A client socket.
     :type client: socket.socket
     """
     try:
         client.setsockopt(IPPROTO_TCP, TCP_NODELAY, 1)
         client.setsockopt(SOL_SOCKET, SO_LINGER, struct.pack('ii', 1, 1))
         message = client.recv(4096)
         call = Document()
         call.load(message)
         reply = self.dispatch(call)
         client.send(reply)
     except Exception, e:
         log.error(utf8(e))
Ejemplo n.º 39
0
 def run(self):
     """
     Main run loop; processes input queue.
     """
     while not Thread.aborted():
         call = self.queue.get()
         if call == 1:
             # # busy
             continue
         if not call:
             # termination requested
             return
         try:
             call()
         except Exception:
             log.exception(utf8(call))
Ejemplo n.º 40
0
 def accepted(self, client):
     """
     Process the request on the accepted socket.
     :param client: A client socket.
     :type client: socket.socket
     """
     try:
         client.setsockopt(IPPROTO_TCP, TCP_NODELAY, 1)
         client.setsockopt(SOL_SOCKET, SO_LINGER, struct.pack('ii', 1, 1))
         message = client.recv(4096)
         call = Document()
         call.load(message)
         reply = self.dispatch(call)
         client.send(reply)
     except Exception, e:
         log.error(utf8(e))
Ejemplo n.º 41
0
def indent(string, indent, *args):
    """
    Indent the specified string and replace arguments.
    :param string: A string.
    :param string: basestring
    :param indent: The number of spaces to indent.
    :type indent: int
    :param args: List of arguments.
    :type args: list
    :return: The indented string.
    :rtype: str
    """
    s = []
    for n in range(0, indent):
        s.append(' ')
    s.append(utf8(string) % args)
    return ''.join(s)
Ejemplo n.º 42
0
 def receiver(self, address=None, dynamic=False):
     """
     Get a message receiver for the specified address.
     :param address: An AMQP address.
     :type address: str
     :param dynamic: Indicates link address is dynamically assigned.
     :type dynamic: bool
     :return: A receiver.
     :rtype: proton.utils.BlockingReceiver
     """
     options = None
     name = utf8(uuid4())
     if dynamic:
         # needed by dispatch router
         options = DynamicNodeProperties({'x-opt-qd.address': unicode(address)})
         address = None
     return self._impl.create_receiver(address, name=name, dynamic=dynamic, options=options)
Ejemplo n.º 43
0
def indent(value, indent, *args):
    """
    Generate an indent.
    :param value: The value to indent.
    :type value: object
    :param indent: Number of spaces to indent.
    :type indent: int
    :param args: Replacement arguments.
    :type args: list
    :return: The indented value.
    :rtype: str
    """
    s = []
    for n in range(0, indent):
        s.append(' ')
    s.append(utf8(value) % args)
    return ''.join(s)
Ejemplo n.º 44
0
def indent(value, indent, *args):
    """
    Generate an indent.
    :param value: The value to indent.
    :type value: object
    :param indent: Number of spaces to indent.
    :type indent: int
    :param args: Replacement arguments.
    :type args: list
    :return: The indented value.
    :rtype: str
    """
    s = []
    for n in range(0, indent):
        s.append(' ')
    s.append(utf8(value) % args)
    return ''.join(s)
Ejemplo n.º 45
0
def indent(string, indent, *args):
    """
    Indent the specified string and replace arguments.
    :param string: A string.
    :param string: basestring
    :param indent: The number of spaces to indent.
    :type indent: int
    :param args: List of arguments.
    :type args: list
    :return: The indented string.
    :rtype: str
    """
    s = []
    for n in range(0, indent):
        s.append(' ')
    s.append(utf8(string) % args)
    return ''.join(s)
Ejemplo n.º 46
0
 def __call__(self):
     """
     Invoke the method.
     :raise: Error on failure.
     """
     self.open()
     try:
         request = Message(content=self.content,
                           reply_to=self.reply_to,
                           properties=self.properties,
                           correlation_id=utf8(uuid4()),
                           subject=SUBJECT)
         self.sender.send(request)
         reply = self.receiver.fetch()
         self.session.acknowledge()
         self.on_reply(reply)
     finally:
         self.close()
Ejemplo n.º 47
0
 def __call__(self):
     """
     Invoke the method.
     :raise: Error on failure.
     """
     self.open()
     try:
         reply_to = self.receiver.remote_source.address
         request = Message(body=self.body,
                           reply_to=reply_to,
                           properties=self.properties,
                           correlation_id=utf8(uuid4()),
                           subject=SUBJECT)
         self.send(request)
         reply = self.receiver.receive()
         self.on_reply(reply)
     finally:
         self.close()
Ejemplo n.º 48
0
 def __call__(self):
     """
     Invoke the method.
     :raise: Error on failure.
     """
     self.open()
     try:
         reply_to = self.receiver.remote_source.address
         request = Message(
             body=self.body,
             reply_to=reply_to,
             properties=self.properties,
             correlation_id=utf8(uuid4()),
             subject=SUBJECT)
         self.send(request)
         reply = self.receiver.receive()
         self.on_reply(reply)
     finally:
         self.close()
Ejemplo n.º 49
0
 def dispatch(self, document):
     """
     Dispatch the requested RMI.
     :param document: A request document.
     :type document: Document
     :return: The result.
     :rtype: any
     """
     try:
         self.log(document)
         auth = self.auth(document)
         request = Request(document.request)
         log.debug('request: %s', request)
         method = RMI(request, auth, self.catalog)
         log.debug('method: %s', method)
         return method()
     except Exception:
         log.exception(utf8(document))
         return Return.exception()
Ejemplo n.º 50
0
 def __call__(self):
     """
     Invoke the method.
     :raise: Error on failure.
     """
     self.open()
     try:
         request = Message(
             content=self.content,
             reply_to=self.reply_to,
             properties=self.properties,
             correlation_id=utf8(uuid4()),
             subject=SUBJECT)
         self.sender.send(request)
         reply = self.receiver.fetch()
         self.session.acknowledge()
         self.on_reply(reply)
     finally:
         self.close()
Ejemplo n.º 51
0
 def send(self, address, ttl=None, **body):
     """
     Send a message.
     :param address: An AMQP address.
     :type address: str
     :param ttl: Time to Live (seconds)
     :type ttl: float
     :keyword body: document body.
     :return: The message serial number.
     :rtype: str
     :raise: ModelError
     """
     sn = utf8(uuid4())
     routing = (None, address)
     document = Document(sn=sn, version=VERSION, routing=routing)
     document += body
     unsigned = document.dump()
     signed = auth.sign(self.authenticator, unsigned)
     self._impl.send(address, signed, ttl)
     return sn
Ejemplo n.º 52
0
 def open(self):
     """
     Open a connection to the broker.
     """
     if self.is_open():
         # already open
         return
     connector = Connector.find(self.url)
     host = ':'.join((connector.host, utf8(connector.port)))
     virtual_host = connector.virtual_host or VIRTUAL_HOST
     domain = self.ssl_domain(connector)
     userid = connector.userid or USERID
     password = connector.password or PASSWORD
     log.info('open: %s', connector)
     self._impl = RealConnection(host=host,
                                 virtual_host=virtual_host,
                                 ssl=domain,
                                 userid=userid,
                                 password=password,
                                 confirm_publish=True)
     log.info('opened: %s', self.url)