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
def main():
    service_name = 'SkeletonsDetector.Detection'
    re_topic = re.compile(r'CameraGateway.(\w+).Frame')

    op = load_options()
    sd = SkeletonsDetector(op)

    log = Logger(name=service_name)
    channel = StreamChannel(op.broker_uri)
    log.info('Connected to broker {}', op.broker_uri)

    max_batch_size = max(100, op.zipkin_batch_size)
    exporter = ZipkinExporter(
        service_name=service_name,
        host_name=op.zipkin_host,
        port=op.zipkin_port,
        transport=BackgroundThreadTransport(max_batch_size=max_batch_size),
    )

    subscription = Subscription(channel=channel, name=service_name)
    subscription.subscribe('CameraGateway.*.Frame')

    while True:
        msg, dropped = channel.consume(return_dropped=True)

        tracer = Tracer(exporter, span_context=msg.extract_tracing())
        span = tracer.start_span(name='detection_and_render')
        detection_span = None

        with tracer.span(name='unpack'):
            im = msg.unpack(Image)
            im_np = get_np_image(im)
        with tracer.span(name='detection') as _span:
            skeletons = sd.detect(im_np)
            detection_span = _span
        with tracer.span(name='pack_and_publish_detections'):
            sks_msg = Message()
            sks_msg.topic = re_topic.sub(r'SkeletonsDetector.\1.Detection',
                                         msg.topic)
            sks_msg.inject_tracing(span)
            sks_msg.pack(skeletons)
            channel.publish(sks_msg)
        with tracer.span(name='render_pack_publish'):
            im_rendered = draw_skeletons(im_np, skeletons)
            rendered_msg = Message()
            rendered_msg.topic = re_topic.sub(r'SkeletonsDetector.\1.Rendered',
                                              msg.topic)
            rendered_msg.pack(get_pb_image(im_rendered))
            channel.publish(rendered_msg)

        span.add_attribute('Detections', len(skeletons.objects))
        tracer.end_span()
        log.info('detections = {:2d}, dropped_messages = {:2d}',
                 len(skeletons.objects), dropped)
        log.info('took_ms = {{ detection: {:5.2f}, service: {:5.2f}}}',
                 span_duration_ms(detection_span), span_duration_ms(span))
示例#3
0
def main():
    service_name = "FaceDetector.Detection"
    log = Logger(name=service_name)
    op = load_options()
    face_detector = FaceDetector(op.model)

    channel = StreamChannel(op.broker_uri)
    log.info('Connected to broker {}', op.broker_uri)

    exporter = create_exporter(service_name=service_name, uri=op.zipkin_uri)

    subscription = Subscription(channel=channel, name=service_name)
    subscription.subscribe(topic='CameraGateway.*.Frame')

    while True:
        msg, dropped = channel.consume_last(return_dropped=True)

        tracer = Tracer(exporter, span_context=msg.extract_tracing())
        span = tracer.start_span(name='detection_and_render')
        detection_span = None

        with tracer.span(name='unpack'):
            im = msg.unpack(Image)
            im_np = to_np(im)

        with tracer.span(name='detection') as _span:
            camera_id = get_topic_id(msg.topic)
            faces = face_detector.detect(im_np)
            detection_span = _span

        with tracer.span(name='pack_and_publish_detections'):
            faces_msg = Message()
            faces_msg.topic = 'FaceDetector.{}.Detection'.format(camera_id)
            faces_msg.inject_tracing(span)
            faces_msg.pack(faces)
            channel.publish(faces_msg)

        with tracer.span(name='render_pack_publish'):
            img_rendered = draw_detection(im_np, faces)
            rendered_msg = Message()
            rendered_msg.topic = 'FaceDetector.{}.Rendered'.format(camera_id)
            rendered_msg.pack(to_image(img_rendered))
            channel.publish(rendered_msg)

        span.add_attribute('Detections', len(faces.objects))
        tracer.end_span()

        info = {
            'detections': len(faces.objects),
            'dropped_messages': dropped,
            'took_ms': {
                'detection': round(span_duration_ms(detection_span), 2),
                'service': round(span_duration_ms(span), 2)
            }
        }
        log.info('{}', str(info).replace("'", '"'))
示例#4
0
def test_injection():
    tracer = Tracer()
    with tracer.span(name="span_name") as span:
        message = Message()
        message.inject_tracing(span)

        assert message.metadata['x-b3-sampled'] == '1'
        assert message.metadata['x-b3-traceid'] == str(
            tracer.tracer.span_context.trace_id)
        assert message.metadata['x-b3-flags'] == '0'
        assert message.metadata['x-b3-spanid'] == str(span.span_id)
        assert message.metadata['x-b3-parentspanid'] == '0000000000000000'
示例#5
0
def test_propagation():
    topic = "span_test"
    channel = Channel(uri=URI, exchange=EXCHANGE)
    subscription = Subscription(channel)
    subscription.subscribe(topic)

    tracer = Tracer()
    with tracer.span(name="span_name") as span:
        span_id = span.span_id
        message = Message()
        message.body = "body".encode('latin1')
        message.inject_tracing(span)
        channel.publish(topic=topic, message=message)

    message2 = channel.consume(timeout=1.0)
    span_context = message2.extract_tracing()

    assert span_context.span_id == span_id
    assert span_context.trace_id == tracer.tracer.span_context.trace_id
    port=ops.zipkin_port,
    transport=BackgroundThreadTransport(max_batch_size=20),
)

subscription.subscribe('Skeletons.Localization')

sks_hm = SkeletonsHeatmap(ops)

period = ops.period_ms / 1000.0
deadline = now()
while True:
    deadline += period
    msgs = []
    while True:
        try:
            msgs.append(channel.consume_until(deadline=deadline))
        except:
            break
    
    span_context = msgs[-1].extract_tracing() if len(msgs) > 0 else None
    tracer = Tracer(exporter=exporter, span_context=span_context)
    with tracer.span(name='Render') as span:
        sks_list = list(map(lambda x: x.unpack(ObjectAnnotations), msgs))
        sks_hm.update_heatmap(sks_list)
        im_pb = sks_hm.get_pb_image()
        msg = Message()
        msg.topic = service_name
        msg.pack(im_pb)
        msg.inject_tracing(span)
        channel.publish(msg)
示例#7
0
def main():

    service_name = "CameraGateway"
    log = Logger(service_name)
    options = load_options()
    camera = CameraGateway(fps=options["fps"])

    publish_channel = Channel(options['broker_uri'])
    rpc_channel = Channel(options['broker_uri'])
    server = ServiceProvider(rpc_channel)
    logging = LogInterceptor()
    server.add_interceptor(logging)

    server.delegate(topic=service_name + ".*.GetConfig",
                    request_type=FieldSelector,
                    reply_type=CameraConfig,
                    function=camera.get_config)

    server.delegate(topic=service_name + ".*.SetConfig",
                    request_type=CameraConfig,
                    reply_type=Empty,
                    function=camera.set_config)

    exporter = create_exporter(service_name=service_name,
                               uri=options["zipkin_uri"])

    while True:

        # iterate through videos listed
        for video in options['videos']:

            # id of the first sequence of videos
            person_id = video['person_id']
            gesture_id = video['gesture_id']

            # getting the path of the 4 videos
            video_files = {
                cam_id: os.path.join(
                    options['folder'],
                    'p{:03d}g{:02d}c{:02d}.mp4'.format(person_id, gesture_id,
                                                       cam_id))
                for cam_id in options["cameras_id"]
            }

            for iteration in range(video['iterations']):

                info = {
                    "person": person_id,
                    "gesture": gesture_id,
                    "iteration": iteration
                }
                log.info('{}', str(info).replace("'", '"'))

                # object that let get images from multiples videos files
                video_loader = FramesLoader(video_files)

                # iterate through all samples on video
                while True:

                    time_initial = time.time()

                    # listen server for messages about change
                    try:
                        message = rpc_channel.consume(timeout=0)
                        if server.should_serve(message):
                            server.serve(message)
                    except socket.timeout:
                        pass

                    frame_id, frames = video_loader.read()

                    for cam in sorted(frames.keys()):
                        tracer = Tracer(exporter)
                        span = tracer.start_span(name='frame')
                        pb_image = to_pb_image(frames[cam])
                        msg = Message(content=pb_image)
                        msg.inject_tracing(span)
                        topic = 'CameraGateway.{}.Frame'.format(cam)
                        publish_channel.publish(msg, topic=topic)
                        tracer.end_span()

                    took_ms = (time.time() - time_initial) * 1000

                    dt = (1 / camera.fps) - (took_ms / 1000)
                    if dt > 0:
                        time.sleep(dt)
                        info = {
                            "sample": frame_id,
                            "took_ms": took_ms,
                            "wait_ms": dt * 1000
                        }
                        log.info('{}', str(info).replace("'", '"'))

                    if frame_id >= (video_loader.num_samples - 1):
                        video_loader.release()
                        del video_loader
                        gc.collect()
                        break

        if options['loop'] is False:
            break
示例#8
0
sks_hm = SkeletonsHeatmap(ops)

period = ops.period_ms / 1000.0
deadline = now()
while True:
    deadline += period
    msgs = []
    while True:
        try:
            msgs.append(channel.consume_until(deadline=deadline))
        except:
            break

    span_context = msgs[-1].extract_tracing() if len(msgs) > 0 else None
    tracer = Tracer(exporter=exporter, span_context=span_context)
    update_span, service_span = None, None
    with tracer.span(name='Render') as span_0:
        sks_list = list(map(lambda x: x.unpack(ObjectAnnotations), msgs))
        with tracer.span(name='Update_Heatmap') as span_1:
            sks_hm.update_heatmap(sks_list)
            update_span = span_1
        im_pb = sks_hm.get_pb_image()
        msg = Message(content=im_pb)
        msg.inject_tracing(span_0)
        channel.publish(message=msg, topic='{}.Rendered'.format(service_name))
        service_span = span_0

    log.info('event=Render messages={}', len(msgs))
    log.info('took_ms= {{ update_heatmap={:4.2f}, service={:4.2f} }}',
             span_duration_ms(update_span), span_duration_ms(service_span))
示例#9
0
while True:
    msg, dropped = channel.consume(return_dropped=True)

    tracer = Tracer(exporter, span_context=msg.extract_tracing())
    span = tracer.start_span(name='detection_and_render')

    with tracer.span(name='unpack'):
        im = msg.unpack(Image)
        im_np = get_np_image(im)
    with tracer.span(name='detect'):
        skeletons = sd.detect(im_np)
    with tracer.span(name='pack_and_publish_detections'):
        sks_msg = Message()
        sks_msg.topic = re_topic.sub(r'Skeletons.\1.Detection', msg.topic)
        sks_msg.inject_tracing(span)
        sks_msg.pack(skeletons)
        channel.publish(sks_msg)
    with tracer.span(name='render_pack_publish'):
        im_rendered = draw_skeletons(im_np, skeletons)
        rendered_msg = Message()
        rendered_msg.topic = re_topic.sub(r'Skeletons.\1.Rendered', msg.topic)
        rendered_msg.pack(get_pb_image(im_rendered))
        channel.publish(rendered_msg)

    span.add_attribute('Detections', len(skeletons.objects))
    tracer.end_span()
    log.info('[Detections: {:2d}][{:5.2f}ms][Dropped {}]',
        len(skeletons.objects),
        span_duration_ms(span),
        dropped