Пример #1
0
def test_channel():
    channel = Channel(uri=URI, exchange=EXCHANGE)
    subscription = Subscription(channel)
    subscription.subscribe("MyTopic.Sub.Sub")

    struct = Struct()
    struct.fields["value"].number_value = 666.0

    sent = Message(struct)
    sent.reply_to = subscription
    sent.created_at = int(1000 * now()) / 1000.0
    sent.timeout = 1.0
    sent.topic = "MyTopic.Sub.Sub"

    channel.publish(message=sent)
    received = channel.consume(timeout=1.0)

    assert sent.reply_to == received.reply_to
    assert sent.subscription_id == received.subscription_id
    assert sent.content_type == received.content_type
    assert sent.body == received.body
    assert sent.status == received.status
    assert sent.topic == received.topic
    assert sent.correlation_id == received.correlation_id
    assert sent.timeout == received.timeout
    assert sent.metadata == received.metadata
    assert sent.created_at == received.created_at
    assert str(sent) == str(received)

    struct2 = received.unpack(Struct)
    assert str(struct) == str(struct2)
    assert struct == struct2

    channel.close()
    def request(self, content, topic, timeout_ms, metadata=None):

        if not self.can_request():
            raise Exception(
                "Can't request more than {}. Use 'RequestManager.can_request' "
                "method to check if you can do requests.")

        tracer = Tracer(
            exporter=self._zipkin_exporter) if self._do_tracing else None
        span = tracer.start_span(name='request') if self._do_tracing else None

        msg = Message(content=content)
        msg.topic = topic
        msg.reply_to = self._subscription
        msg.timeout = timeout_ms / 1000.0

        self._log.debug("[Sending] metadata={}, cid={}", metadata,
                        msg.correlation_id)

        if self._do_tracing:
            for key, value in (metadata or {}).items():
                span.add_attribute(key, value)
            tracer.end_span()
            msg.inject_tracing(span)

        self._publish(msg, metadata)

        if len(self._requests) >= self._max_requests:
            self._can_request = False
Пример #3
0
def test_create_reply():
    request = Message()
    request.topic = "topic"
    request.reply_to = "reply_to"
    request.content_type = ContentType.JSON

    reply = request.create_reply()

    assert reply.topic == request.reply_to
    assert reply.correlation_id == request.correlation_id
    assert reply.content_type == request.content_type
Пример #4
0
    def request_serve_consume(number):
        struct = Struct()
        struct.fields["value"].number_value = number
        message = Message(struct)
        message.reply_to = subscription
        message.pack(struct)
        channel.publish(topic="MyService", message=message)

        request = channel.consume(timeout=1.0)
        assert request.body == message.body
        service.serve(request)
        assert request.unpack(Struct) == struct

        return channel.consume(timeout=1.0)
Пример #5
0
def test_body(size):
    channel = Channel(uri=URI, exchange=EXCHANGE)

    subscription = Subscription(channel)
    subscription.subscribe("MyTopic.Sub.Sub")

    sent = Message()
    sent.reply_to = subscription
    sent.topic = "MyTopic.Sub.Sub"
    sent.body = bytes(bytearray(range(256)) * int(size))

    channel.publish(message=sent)
    received = channel.consume(timeout=1.0)

    assert repr(sent.body) == repr(received.body)
    assert sent.body == received.body

    channel.close()
Пример #6
0
def test_amqp_conversion():
    sent = Message()
    sent.created_at = int(now() * 1000) / 1000.0
    sent.reply_to = "reply_to"
    sent.subscription_id = "subscription_id"
    sent.content_type = ContentType.JSON
    sent.body = '{"field":"value"}'.encode('latin1')
    sent.topic = "MyTopic"
    sent.status = Status(
        code=StatusCode.FAILED_PRECONDITION,
        why="Bad Args...",
    )
    sent.metadata = {
        'x-b3-sampled': '1',
        'x-b3-traceid': 'f047c6f208eb36ab',
        'x-b3-flags': '0',
        'x-b3-spanid': 'ef81a2f9c261473d',
        'x-b3-parentspanid': '0000000000000000'
    }

    body = sent.body

    amqp_message = amqp.Message(channel=None,
                                body=body,
                                **WireV1.to_amqp_properties(sent))

    amqp_message.delivery_info = {
        "routing_key": sent.topic,
        "consumer_tag": sent.subscription_id,
    }

    received = WireV1.from_amqp_message(amqp_message)
    print(sent.__str__(), received.__str__())
    assert str(sent) == str(received)
    assert sent.created_at == received.created_at
    assert sent.reply_to == received.reply_to
    assert sent.subscription_id == received.subscription_id
    assert sent.content_type == received.content_type
    assert sent.body == received.body
    assert sent.status == received.status
    assert sent.topic == received.topic
    assert sent.correlation_id == received.correlation_id
    assert sent.timeout == received.timeout
    assert sent.metadata == received.metadata
    def consume_ready(self, timeout=1.0):
        received_msgs = []

        # wait for new message
        try:
            stated_at = now()
            while True:
                _timeout = max(0.0, stated_at + timeout - now())
                msg = self._channel.consume(timeout=_timeout)

                if msg.status.ok() and msg.has_correlation_id():
                    cid = msg.correlation_id
                    if cid in self._requests:
                        received_msgs.append(
                            (msg, self._requests[cid]["metadata"]))
                        del self._requests[cid]

        except socket.timeout:
            pass

        # check for timeouted requests
        for cid in self._requests.keys():
            timeouted_msg = self._requests[cid]["msg"]

            if timeouted_msg.deadline_exceeded():
                msg = Message()
                msg.body = timeouted_msg.body
                msg.topic = timeouted_msg.topic
                msg.reply_to = self._subscription
                msg.timeout = timeouted_msg.timeout

                metadata = self._requests[cid]["metadata"]

                del self._requests[cid]

                self._log.debug("[Retring] metadata={}, cid={}", metadata,
                                msg.correlation_id)
                self._publish(msg, metadata)

        if not self._can_request and len(self._requests) <= self._min_requests:
            self._can_request = True

        return received_msgs
    Loading CameraConfig protobuf from a json file
"""
with open('camera_config.json', 'r') as f:
    try:
        set_config = Parse(f.read(), CameraConfig())
        log.info('CameraConfig:\n{}', set_config)
    except Exception as ex:
        log.critical('Unable to camera settings. \n{}', ex)
"""
    Another way to create a CameraConfig message
"""
set_config = CameraConfig(
    sampling=SamplingSettings(frequency=FloatValue(value=5.0)),
    image=ImageSettings(
        resolution=Resolution(width=720, height=540),
        color_space=ColorSpace(value=ColorSpaces.Value('GRAY'))))

msg = Message()
msg.reply_to = subscription
msg.topic = 'CameraGateway.{}.SetConfig'.format(camera_id)
msg.pack(set_config)
channel.publish(msg)

while True:
    msg = channel.consume()
    if msg.status.code == StatusCode.OK:
        log.info('Configuration applied on camera \'{}\'.', camera_id)
    else:
        log.warn('Can\'t apply configuration:\n{}', msg.status)
    sys.exit(0)
from is_wire.core import Channel, Subscription, Message, Logger
from utils import load_options

log = Logger(name='ConfigureCameras')

options = load_options()
c = Channel(options.broker_uri)
sb = Subscription(c)

cids = {}
for camera in options.cameras:
    log.info("Camera: {}\nConfiguration: {}", camera.id, camera.config)
    msg = Message()
    msg.pack(camera.config)
    msg.reply_to = sb
    msg.topic = 'CameraGateway.{}.SetConfig'.format(camera.id)
    c.publish(msg)
    cids[msg.correlation_id] = {'camera': camera.id, 'ok': False}

while True:
    msg = c.consume()
    if msg.correlation_id in cids:
        camera = cids[msg.correlation_id]['camera']
        cids[msg.correlation_id]['ok'] = True
        log.info('Camera: {} Reply: {}', camera, msg.status)
    if all(map(lambda x: x[1]['ok'], cids.items())):
        break