Ejemplo n.º 1
0
def test_create_attrs_for_span(random_64bit_mock, random_128bit_mock):
    random_64bit_mock.return_value = '0000000000000042'
    expected_attrs = ZipkinAttrs(
        trace_id='0000000000000042',
        span_id='0000000000000042',
        parent_span_id=None,
        flags='0',
        is_sampled=True,
    )
    assert expected_attrs == zipkin.create_attrs_for_span()

    # Test overrides
    expected_attrs = ZipkinAttrs(
        trace_id='0000000000000045',
        span_id='0000000000000046',
        parent_span_id=None,
        flags='0',
        is_sampled=False,
    )
    assert expected_attrs == zipkin.create_attrs_for_span(
        sample_rate=0.0,
        trace_id='0000000000000045',
        span_id='0000000000000046',
    )

    random_128bit_mock.return_value = '00000000000000420000000000000042'
    expected_attrs = ZipkinAttrs(
        trace_id='00000000000000420000000000000042',
        span_id='0000000000000042',
        parent_span_id=None,
        flags='0',
        is_sampled=True,
    )
    assert expected_attrs == zipkin.create_attrs_for_span(
        use_128bit_trace_id=True, )
Ejemplo n.º 2
0
    def test_get_current_context_non_root_existing(
            self,
            mock_create_attr,
    ):
        # Non root, zipkin_attrs in context stack.
        # Return existing zipkin_attrs with the current one as parent
        zipkin_attrs = ZipkinAttrs(
            trace_id=generate_random_64bit_string(),
            span_id=generate_random_64bit_string(),
            parent_span_id=generate_random_64bit_string(),
            flags=None,
            is_sampled=True,
        )
        tracer = MockTracer()
        context = tracer.zipkin_span(
            service_name='test_service',
            span_name='test_span',
        )
        tracer._context_stack.push(zipkin_attrs)

        _, current_attrs = context._get_current_context()

        assert mock_create_attr.call_count == 0
        assert current_attrs == ZipkinAttrs(
            trace_id=zipkin_attrs.trace_id,
            span_id=mock.ANY,
            parent_span_id=zipkin_attrs.span_id,
            flags=zipkin_attrs.flags,
            is_sampled=zipkin_attrs.is_sampled,
        )
Ejemplo n.º 3
0
def create_zipkin_attr_from_dict(data):
    """
    Create ZipkinAttrs object from a dict.
    """
    if not data or 'trace_id' not in data:
        return ZipkinAttrs('', '', '', '0', False)
    return ZipkinAttrs(
        trace_id=data['trace_id'],
        span_id=generate_random_64bit_string(),
        parent_span_id=data['span_id'],
        flags=data['flags'],
        is_sampled=True,
    )
Ejemplo n.º 4
0
def test_service_span_that_is_independently_sampled(mock_logger):
    mock_transport_handler, mock_logs = mock_logger
    zipkin_attrs = ZipkinAttrs(
        trace_id='0',
        span_id='1',
        parent_span_id='2',
        flags='0',
        is_sampled=False,
    )
    with zipkin.zipkin_span(
        service_name='test_service_name',
        span_name='service_span',
        zipkin_attrs=zipkin_attrs,
        transport_handler=mock_transport_handler,
        port=45,
        sample_rate=100.0,
        binary_annotations={'some_key': 'some_value'},
    ):
        pass

    span = _decode_binary_thrift_obj(mock_logs[0])
    assert span.name == 'service_span'
    assert span.annotations[0].host.service_name == 'test_service_name'
    assert span.parent_id is None
    assert span.binary_annotations[0].key == 'some_key'
    assert span.binary_annotations[0].value == 'some_value'
    assert set([ann.value for ann in span.annotations]) == set(['ss', 'sr'])
Ejemplo n.º 5
0
    def test_get_current_context_root_sample_rate_override_not_sampled(
        self,
        mock_create_attr,
    ):
        # Root span, with custom zipkin_attrs, not sampled and sample_rate
        zipkin_attrs = ZipkinAttrs(
            trace_id=generate_random_64bit_string(),
            span_id=generate_random_64bit_string(),
            parent_span_id=generate_random_64bit_string(),
            flags=None,
            is_sampled=False,
        )
        context = zipkin.zipkin_span(
            service_name='test_service',
            span_name='test_span',
            transport_handler=MockTransportHandler(),
            zipkin_attrs=zipkin_attrs,
            sample_rate=100.0,
        )

        report_root, _ = context._get_current_context()

        assert mock_create_attr.call_args == mock.call(
            sample_rate=100.0,
            trace_id=zipkin_attrs.trace_id,
        )
        # It wasn't sampled before and now it is, so this is the trace root
        assert report_root is True
Ejemplo n.º 6
0
def test_update_binary_annotations():
    zipkin_attrs = ZipkinAttrs(
        trace_id='0',
        span_id='1',
        parent_span_id=None,
        flags='0',
        is_sampled=True,
    )
    context = zipkin.zipkin_span(
        service_name='my_service',
        span_name='span_name',
        zipkin_attrs=zipkin_attrs,
        transport_handler=mock.Mock(),
        port=5,
    )

    with context:
        assert 'test' not in context.logging_context.binary_annotations_dict
        context.update_binary_annotations({'test': 'hi'})
        assert context.logging_context.binary_annotations_dict['test'] == 'hi'

        nested_context = zipkin.zipkin_span(
            service_name='my_service',
            span_name='nested_span',
            binary_annotations={'one': 'one'},
        )
        with nested_context:
            assert 'one' not in context.logging_context.binary_annotations_dict
            nested_context.update_binary_annotations({'two': 'two'})
            assert 'two' in nested_context.binary_annotations
            assert 'two' not in context.logging_context.binary_annotations_dict
Ejemplo n.º 7
0
def test_span_context_sampled_no_handlers(
    zipkin_logger_mock,
    generate_string_mock,
    thread_local_mock,
):
    zipkin_attrs = ZipkinAttrs(
        trace_id='1111111111111111',
        span_id='2222222222222222',
        parent_span_id='3333333333333333',
        flags='flags',
        is_sampled=True,
    )
    thread_local_mock.zipkin_attrs = [zipkin_attrs]

    zipkin_logger_mock.handlers = []
    generate_string_mock.return_value = '1'

    context = zipkin.zipkin_span(
        service_name='my_service',
        port=5,
        transport_handler=mock.Mock(),
        sample_rate=0.0,
    )
    with context:
        # Assert that the new ZipkinAttrs were saved
        new_zipkin_attrs = get_zipkin_attrs()
        assert new_zipkin_attrs.span_id == '1'

    # Outside of the context, things should be returned to normal
    assert get_zipkin_attrs() == zipkin_attrs
Ejemplo n.º 8
0
def test_zipkin_span_trace_with_0_sample_rate(
    logging_context_cls_mock,
    logger_handler_cls_mock,
    create_endpoint_mock,
    create_attrs_for_span_mock,
    push_zipkin_attrs_mock,
    pop_zipkin_attrs_mock,
):
    create_attrs_for_span_mock.return_value = ZipkinAttrs(
        trace_id=generate_random_64bit_string(),
        span_id=generate_random_64bit_string(),
        parent_span_id=None,
        flags='0',
        is_sampled=False,
    )
    with zipkin.zipkin_span(
        service_name='some_service_name',
        span_name='span_name',
        transport_handler=mock.Mock(),
        sample_rate=0.0,
    ) as zipkin_context:
        assert zipkin_context.port == 0
        pass
    create_attrs_for_span_mock.assert_called_once_with(
        sample_rate=0.0,
        use_128bit_trace_id=False,
    )
    push_zipkin_attrs_mock.assert_called_once_with(
        create_attrs_for_span_mock.return_value)
    assert create_endpoint_mock.call_count == 0
    assert logger_handler_cls_mock.call_count == 0
    assert logging_context_cls_mock.call_count == 0
    pop_zipkin_attrs_mock.assert_called_once_with()
Ejemplo n.º 9
0
def test_zipkin_span_trace_with_no_sampling(
    logging_context_cls_mock,
    create_endpoint_mock,
    create_attrs_for_span_mock,
    mock_context_stack,
):
    zipkin_attrs = ZipkinAttrs(
        trace_id='0',
        span_id='1',
        parent_span_id=None,
        flags='0',
        is_sampled=False,
    )

    with zipkin.zipkin_span(
            service_name='my_service',
            span_name='span_name',
            zipkin_attrs=zipkin_attrs,
            transport_handler=MockTransportHandler(),
            port=5,
            context_stack=mock_context_stack,
            span_storage=SpanStorage(),
    ):
        pass

    assert create_attrs_for_span_mock.call_count == 0
    mock_context_stack.push.assert_called_once_with(zipkin_attrs, )
    assert create_endpoint_mock.call_count == 0
    assert logging_context_cls_mock.call_count == 0
    mock_context_stack.pop.assert_called_once_with()
Ejemplo n.º 10
0
def trace(span_name, tracer, span_id=None, service_name=None):
    span_id = span_id or generate_random_64bit_string()
    service_name = service_name or settings.ZIPKIN_SERVICE_NAME
    if len(span_id) > 16:
        logger.warning('Span id %s for %s should be max 16 chars.' %
                       (span_id, span_name))
    trace_id = (tracer.get('trace_id') or generate_random_64bit_string())
    parent_span_id = (tracer.get('span_id') or generate_random_64bit_string())
    flags = tracer.get('flags') or ''
    is_sampled = (True if tracer.get('is_tracing') else False)
    transport_handler = import_string(
        getattr(settings, 'ZIPKIN_TRANSPORT_HANDLER',
                'django_py_zipkin.transport.zipkin_transport'))

    span = zipkin_span(service_name=service_name,
                       span_name=span_name,
                       transport_handler=transport_handler,
                       zipkin_attrs=ZipkinAttrs(trace_id=trace_id,
                                                span_id=span_id,
                                                parent_span_id=parent_span_id,
                                                flags=flags,
                                                is_sampled=is_sampled))
    with span as zipkin_context:
        dict_context = {}
        yield dict_context
        zipkin_context.update_binary_annotations(dict_context)
Ejemplo n.º 11
0
def test_batch_sender_add_span_not_sampled_with_firehose(
        add_span_mock, flush_mock, time_mock):
    attr = ZipkinAttrs(
        trace_id='0000000000000001',
        span_id='0000000000000002',
        parent_span_id=None,
        flags=None,
        is_sampled=False,
    )
    span_storage = SpanStorage()
    transport_handler = mock.Mock()
    firehose_handler = mock.Mock()

    context = logging_helper.ZipkinLoggingContext(
        zipkin_attrs=attr,
        endpoint=create_endpoint(80, 'test_server', '127.0.0.1'),
        span_name='span_name',
        transport_handler=transport_handler,
        report_root_timestamp=False,
        span_storage=span_storage,
        firehose_handler=firehose_handler,
        service_name='test_server',
        encoding=Encoding.V1_JSON,
    )
    context.start_timestamp = 24
    context.response_status_code = 200

    context.binary_annotations_dict = {'k': 'v'}
    time_mock.return_value = 42

    context.emit_spans()
    assert add_span_mock.call_count == 1
    assert flush_mock.call_count == 1
Ejemplo n.º 12
0
def test_batch_sender_add_span_not_called_if_not_sampled(
        add_span_mock, flush_mock):
    attr = ZipkinAttrs(
        trace_id='0000000000000001',
        span_id='0000000000000002',
        parent_span_id=None,
        flags=None,
        is_sampled=False,
    )
    span_storage = SpanStorage()
    transport_handler = mock.Mock()

    context = logging_helper.ZipkinLoggingContext(
        zipkin_attrs=attr,
        endpoint=create_endpoint(80, 'test_server', '127.0.0.1'),
        span_name='span_name',
        transport_handler=transport_handler,
        report_root_timestamp=False,
        span_storage=span_storage,
        service_name='test_server',
        encoding=Encoding.V1_JSON,
    )
    context.emit_spans()
    assert add_span_mock.call_count == 0
    assert flush_mock.call_count == 0
def test_service_exits_on_erroneous_span(log_mock):
    """Tests that for invalid zipkin_attrs exceptions are not thrown
       Services may not be handling them. Instead log an error
    """
    mock_transport_handler, mock_logs = mock_logger()
    tracer = MockTracer()
    try:
        zipkin_attrs = ZipkinAttrs(
            trace_id='0',
            span_id='1, 1',  # invalid span id
            parent_span_id='2',
            flags='0',
            is_sampled=True,
        )
        with tracer.zipkin_span(
                service_name='test_service_name',
                span_name='service_span',
                zipkin_attrs=zipkin_attrs,
                transport_handler=mock_transport_handler,
                encoding=Encoding.V1_THRIFT,
        ):
            pass

    except Exception:
        pytest.fail('Exception not expected to be thrown!')

    finally:
        assert log_mock.call_count == 1
        assert len(mock_logs) == 0
        assert len(tracer.get_spans()) == 0
Ejemplo n.º 14
0
def test_batch_sender_add_span_not_sampled_with_firehose(
        add_span_mock, flush_mock, time_mock):
    attr = ZipkinAttrs(
        trace_id='0000000000000001',
        span_id='0000000000000002',
        parent_span_id=None,
        flags=None,
        is_sampled=False,
    )
    log_handler = logging_helper.ZipkinLoggerHandler(attr)
    transport_handler = mock.Mock()
    firehose_handler = mock.Mock()
    context = logging_helper.ZipkinLoggingContext(
        zipkin_attrs=attr,
        thrift_endpoint='thrift_endpoint',
        log_handler=log_handler,
        span_name='span_name',
        transport_handler=transport_handler,
        report_root_timestamp=False,
        firehose_handler=firehose_handler,
    )
    context.start_timestamp = 24
    context.response_status_code = 200

    context.binary_annotations_dict = {'k': 'v'}
    time_mock.return_value = 42

    context.log_spans()
    assert add_span_mock.call_count == 1
    assert flush_mock.call_count == 1
Ejemplo n.º 15
0
def test_service_span(mock_logger):
    mock_transport_handler, mock_logs = mock_logger
    zipkin_attrs = ZipkinAttrs(
        trace_id='0',
        span_id='1',
        parent_span_id='2',
        flags='0',
        is_sampled=True,
    )
    with zipkin.zipkin_span(
        service_name='test_service_name',
        span_name='service_span',
        zipkin_attrs=zipkin_attrs,
        transport_handler=mock_transport_handler,
        binary_annotations={'some_key': 'some_value'},
    ):
        pass

    span = _decode_binary_thrift_obj(mock_logs[0])
    assert span.name == 'service_span'
    assert span.trace_id == 0
    assert span.id == 1
    assert span.annotations[0].host.service_name == 'test_service_name'
    assert span.annotations[0].host.port == 0
    assert span.parent_id == 2
    assert span.binary_annotations[0].key == 'some_key'
    assert span.binary_annotations[0].value == 'some_value'
    assert set([ann.value for ann in span.annotations]) == set(['ss', 'sr'])
def test_service_span_report_timestamp_override(
    mock_logger,
    default_annotations,
):
    mock_transport_handler, mock_logs = mock_logger
    zipkin_attrs = ZipkinAttrs(
        trace_id='0',
        span_id='1',
        parent_span_id='2',
        flags='0',
        is_sampled=True,
    )
    with zipkin.zipkin_span(
        service_name='test_service_name',
        span_name='service_span',
        zipkin_attrs=zipkin_attrs,
        transport_handler=mock_transport_handler,
        binary_annotations={'some_key': 'some_value'},
        add_logging_annotation=True,
        report_root_timestamp=True,
    ):
        pass

    span = _decode_binary_thrift_obj(mock_logs[0])
    _verify_service_span(span, default_annotations)
    assert span.timestamp is not None
    assert span.duration is not None
def test_service_span_that_is_independently_sampled(
    mock_logger,
    default_annotations,
):
    mock_transport_handler, mock_logs = mock_logger
    zipkin_attrs = ZipkinAttrs(
        trace_id='0',
        span_id='1',
        parent_span_id='2',
        flags='0',
        is_sampled=False,
    )
    with zipkin.zipkin_span(
        service_name='test_service_name',
        span_name='service_span',
        zipkin_attrs=zipkin_attrs,
        transport_handler=mock_transport_handler,
        port=45,
        sample_rate=100.0,
        binary_annotations={'some_key': 'some_value'},
        add_logging_annotation=True,
    ):
        pass

    span = _decode_binary_thrift_obj(mock_logs[0])
    assert span.name == 'service_span'
    assert span.annotations[0].host.service_name == 'test_service_name'
    assert span.parent_id is None
    assert span.binary_annotations[0].key == 'some_key'
    assert span.binary_annotations[0].value == 'some_value'
    # Spans that are part of an unsampled trace which start their own sampling
    # should report timestamp/duration, as they're acting as root spans.
    assert span.timestamp is not None
    assert span.duration is not None
    assert set([ann.value for ann in span.annotations]) == default_annotations
Ejemplo n.º 18
0
def test_adding_error_annotation_on_exception(
    mock_update_binary_annotations,
    exception_message,
    expected_error_string,
):
    zipkin_attrs = ZipkinAttrs(
        trace_id='0',
        span_id='1',
        parent_span_id=None,
        flags='0',
        is_sampled=True,
    )
    context = zipkin.zipkin_span(
        service_name='my_service',
        span_name='span_name',
        zipkin_attrs=zipkin_attrs,
        transport_handler=MockTransportHandler(),
        port=5,
    )
    with pytest.raises(ValueError):
        with context:
            raise ValueError(exception_message)
    assert mock_update_binary_annotations.call_count == 1
    call_args, _ = mock_update_binary_annotations.call_args
    assert 'error' in call_args[1]
    assert expected_error_string == call_args[1]['error']
Ejemplo n.º 19
0
  def bulk_record_workunits(self, engine_workunits):
    """A collection of workunits from v2 engine part"""
    for workunit in engine_workunits:
      start_timestamp = from_secs_and_nanos_to_float(
        workunit['start_secs'],
        workunit['start_nanos']
      )
      duration = from_secs_and_nanos_to_float(
        workunit['duration_secs'],
        workunit['duration_nanos']
      )

      local_tracer = get_default_tracer()

      span = local_tracer.zipkin_span(
        service_name=self.service_name_prefix.format("rule"),
        span_name=workunit['name'],
        duration=duration,
      )
      span.start()
      span.zipkin_attrs = ZipkinAttrs(
        trace_id=self.trace_id,
        span_id=workunit['span_id'],
        # TODO change it when we properly pass parent_id to the v2 engine Nodes
        # TODO Pass parent_id with ExecutionRequest when v2 engine is called by a workunit
        # TODO pass parent_id when v2 engine Node is called by another v2 engine Node
        parent_span_id=workunit.get("parent_id", self.parent_id),
        flags='0', # flags: stores flags header. Currently unused
        is_sampled=True,
      )
      span.start_timestamp = start_timestamp
      span.stop()
Ejemplo n.º 20
0
def test_service_span(encoding):
    """Tests that zipkin_attrs can be passed in"""
    mock_transport_handler, mock_logs = mock_logger()
    zipkin_attrs = ZipkinAttrs(
        trace_id='0',
        span_id='1',
        parent_span_id='2',
        flags='0',
        is_sampled=True,
    )
    with zipkin.zipkin_span(
            service_name='test_service_name',
            span_name='service_span',
            zipkin_attrs=zipkin_attrs,
            transport_handler=mock_transport_handler,
            encoding=encoding,
    ):
        pass

    span = json.loads(mock_logs[0])[0]
    assert span['name'] == 'service_span'
    assert span['traceId'] == '0'
    assert span['id'] == '1'
    assert span['parentId'] == '2'

    if encoding == Encoding.V1_JSON:
        # Spans continued on the server don't log timestamp/duration, as it's
        # assumed the client part of the pair will log them.
        assert 'timestamp' not in span
        assert 'duration' not in span
    elif encoding == Encoding.V2_JSON:
        assert span['shared'] is True
Ejemplo n.º 21
0
def test_zipkin_span_trace_with_no_sampling(
    logging_context_cls_mock,
    logger_handler_cls_mock,
    create_endpoint_mock,
    create_attrs_for_span_mock,
    push_zipkin_attrs_mock,
    pop_zipkin_attrs_mock,
):
    zipkin_attrs = ZipkinAttrs(
        trace_id='0',
        span_id='1',
        parent_span_id=None,
        flags='0',
        is_sampled=False,
    )
    with zipkin.zipkin_span(
        service_name='my_service',
        span_name='span_name',
        zipkin_attrs=zipkin_attrs,
        transport_handler=mock.Mock(),
        port=5,
    ):
        pass
    assert create_attrs_for_span_mock.call_count == 0
    push_zipkin_attrs_mock.assert_called_once_with(zipkin_attrs)
    assert create_endpoint_mock.call_count == 0
    assert logger_handler_cls_mock.call_count == 0
    assert logging_context_cls_mock.call_count == 0
    pop_zipkin_attrs_mock.assert_called_once_with()
Ejemplo n.º 22
0
def test_service_span_report_timestamp_override():
    """Tests that timestamp and duration are set if report_root_timestamp=True"""
    mock_transport_handler, mock_logs = mock_logger()
    # We need to pass in zipkin_attrs so that py_zipkin doesn't think this is the
    # root span (ts and duration are always set for the root span)
    zipkin_attrs = ZipkinAttrs(
        trace_id='0',
        span_id='1',
        parent_span_id='2',
        flags='0',
        is_sampled=True,
    )
    with zipkin.zipkin_span(
            service_name='test_service_name',
            span_name='service_span',
            zipkin_attrs=zipkin_attrs,
            transport_handler=mock_transport_handler,
            report_root_timestamp=True,
            encoding=Encoding.V1_JSON,
    ):
        pass

    span = json.loads(mock_logs[0])[0]
    assert 'timestamp' in span
    assert 'duration' in span
Ejemplo n.º 23
0
def test_span_context(
    zipkin_logger_mock,
    generate_string_128bit_mock,
    generate_string_mock,
    thread_local_mock,
    span_func,
    expected_annotations,
):
    zipkin_attrs = ZipkinAttrs(
        trace_id='1111111111111111',
        span_id='2222222222222222',
        parent_span_id='3333333333333333',
        flags='flags',
        is_sampled=True,
    )
    thread_local_mock.zipkin_attrs = [zipkin_attrs]
    logging_handler = ZipkinLoggerHandler(zipkin_attrs)
    assert logging_handler.parent_span_id is None
    assert logging_handler.client_spans == []

    zipkin_logger_mock.handlers = [logging_handler]
    generate_string_mock.return_value = '1'

    context = span_func(
        service_name='svc',
        span_name='span',
        annotations={'something': 1},
        binary_annotations={'foo': 'bar'},
    )
    with context:
        # Assert that the new ZipkinAttrs were saved
        new_zipkin_attrs = get_zipkin_attrs()
        assert new_zipkin_attrs.span_id == '1'
        # And that the logging handler has a parent_span_id
        assert logging_handler.parent_span_id == '1'

    # Outside of the context, things should be returned to normal,
    # except a new client span is saved in the handler
    assert logging_handler.parent_span_id is None
    assert get_zipkin_attrs() == zipkin_attrs

    client_span = logging_handler.client_spans.pop()
    assert logging_handler.client_spans == []
    # These reserved annotations are based on timestamps so pop em.
    # This also acts as a check that they exist.
    for annotation in expected_annotations:
        client_span['annotations'].pop(annotation)

    expected_client_span = {
        'span_name': 'span',
        'service_name': 'svc',
        'parent_span_id': None,
        'span_id': '1',
        'annotations': {'something': 1},
        'binary_annotations': {'foo': 'bar'},
        'sa_binary_annotations': [],
    }
    assert client_span == expected_client_span

    assert generate_string_128bit_mock.call_count == 0
Ejemplo n.º 24
0
    def zipkin_span_params(self, span):
        span_params = self.log_span_params(span)

        timing = {'ss': span.start_time, 'sr': span.start_time + span.duration}
        annotations = annotation_list_builder(timing, self.endpoint)
        zipkin_attrs = ZipkinAttrs(
            trace_id=span_params['trace_id'],
            span_id=span_params['span_id'],
            parent_span_id=span_params['parent_span_id'],
            flags=span_params['flags'],
            is_sampled=span_params['is_sampled'])

        return {
            **span_params,
            'zipkin_attrs':
            zipkin_attrs,
            'annotations':
            annotations,
            'binary_annotations':
            binary_annotation_list_builder(
                {
                    **span.context.baggage,
                    **span.tags
                }, self.endpoint),
        }
Ejemplo n.º 25
0
    def test_init(self, mock_generate_kind):
        # Test that all arguments are correctly saved
        zipkin_attrs = ZipkinAttrs(None, None, None, None, None)
        transport = MockTransportHandler()
        firehose = MockTransportHandler()
        stack = Stack([])
        span_storage = SpanStorage()
        tracer = MockTracer()

        context = tracer.zipkin_span(
            service_name="test_service",
            span_name="test_span",
            zipkin_attrs=zipkin_attrs,
            transport_handler=transport,
            max_span_batch_size=10,
            annotations={"test_annotation": 1},
            binary_annotations={"status": "200"},
            port=80,
            sample_rate=100.0,
            include=("cs", "cr"),
            add_logging_annotation=True,
            report_root_timestamp=True,
            use_128bit_trace_id=True,
            host="127.0.0.255",
            context_stack=stack,
            span_storage=span_storage,
            firehose_handler=firehose,
            kind=Kind.CLIENT,
            timestamp=1234,
            duration=10,
            encoding=Encoding.V2_JSON,
        )

        assert context.service_name == "test_service"
        assert context.span_name == "test_span"
        assert context.zipkin_attrs_override == zipkin_attrs
        assert context.transport_handler == transport
        assert context.max_span_batch_size == 10
        assert context.annotations == {"test_annotation": 1}
        assert context.binary_annotations == {"status": "200"}
        assert context.port == 80
        assert context.sample_rate == 100.0
        assert context.add_logging_annotation is True
        assert context.report_root_timestamp_override is True
        assert context.use_128bit_trace_id is True
        assert context.host == "127.0.0.255"
        assert context._context_stack == stack
        assert context._span_storage == span_storage
        assert context.firehose_handler == firehose
        assert mock_generate_kind.call_count == 1
        assert mock_generate_kind.call_args == mock.call(
            context, Kind.CLIENT, ("cs", "cr"),
        )
        assert context.timestamp == 1234
        assert context.duration == 10
        assert context.encoding == Encoding.V2_JSON
        assert context._tracer == tracer
        # Check for backward compatibility
        assert tracer.get_spans() == span_storage
        assert tracer.get_context() == stack
Ejemplo n.º 26
0
def test_batch_sender_add_span_not_sampled_with_firehose(
    add_span_mock, flush_mock, time_mock
):
    attr = ZipkinAttrs(
        trace_id="0000000000000001",
        span_id="0000000000000002",
        parent_span_id=None,
        flags=None,
        is_sampled=False,
    )
    tracer = MockTracer()
    transport_handler = mock.Mock()
    firehose_handler = mock.Mock()

    context = logging_helper.ZipkinLoggingContext(
        zipkin_attrs=attr,
        endpoint=create_endpoint(80, "test_server", "127.0.0.1"),
        span_name="span_name",
        transport_handler=transport_handler,
        report_root_timestamp=False,
        get_tracer=lambda: tracer,
        firehose_handler=firehose_handler,
        service_name="test_server",
        encoding=Encoding.V1_JSON,
    )
    context.start_timestamp = 24
    context.response_status_code = 200

    context.tags = {"k": "v"}
    time_mock.return_value = 42

    context.emit_spans()
    assert add_span_mock.call_count == 1
    assert flush_mock.call_count == 1
Ejemplo n.º 27
0
    def test_get_current_context_root_sample_rate_override_sampled(
            self,
            mock_create_attr,
    ):
        # Root span, with custom zipkin_attrs, sampled
        # Just return the custom zipkin_attrs.
        zipkin_attrs = ZipkinAttrs(
            trace_id=generate_random_64bit_string(),
            span_id=generate_random_64bit_string(),
            parent_span_id=generate_random_64bit_string(),
            flags=None,
            is_sampled=True,
        )
        context = zipkin.zipkin_span(
            service_name='test_service',
            span_name='test_span',
            transport_handler=MockTransportHandler(),
            zipkin_attrs=zipkin_attrs,
            sample_rate=100.0,
        )

        report_root, current_attrs = context._get_current_context()

        assert mock_create_attr.call_count == 0
        assert current_attrs == zipkin_attrs
        # The override was set and was already sampled, so this is probably
        # not the trace root.
        assert report_root is False
Ejemplo n.º 28
0
def construct_zipkin_attrs(data):
    parsed = json.loads(data)
    return ZipkinAttrs(trace_id=parsed.get('trace_id'),
                       parent_span_id=parsed.get('parent_span_id'),
                       span_id=generate_random_64bit_string(),
                       is_sampled=parsed.get('is_sampled'),
                       flags='0')
Ejemplo n.º 29
0
def dealsbyhotel():
    with zipkin_span(service_name='hotels.com:dealsquery',
                     zipkin_attrs=ZipkinAttrs(
                         trace_id=request.headers['X-B3-TraceID'],
                         span_id=request.headers['X-B3-SpanID'],
                         parent_span_id=request.headers['X-B3-ParentSpanID'],
                         flags='1',
                         is_sampled=request.headers['X-B3-Sampled']),
                     span_name='dealquery:dealsbyhotel',
                     transport_handler=http_transport,
                     port=PORT,
                     sample_rate=ZIPKINSAMPLERATE):
        sessionid = request.args.get('sessionid')
        debugmessage('BEGIN DEALS SEARCH: SESSIONID', sessionid)

        status = setupsearchindex(sessionid)
        if (status == False):
            return jsonify({})

        deals = getdeals(sessionid)
        hoteldict = defaultdict(defaultdict)

        for deal in deals:
            hoteldict[deal['hotelid']] = []

        for deal in deals:
            hoteldict[deal['hotelid']].append(deal)

        debugmessage('END DEALS SEARCH: SESSIONID', sessionid)
        return jsonify(hoteldict)
def test_service_span(mock_logger, default_annotations):
    mock_transport_handler, mock_logs = mock_logger
    zipkin_attrs = ZipkinAttrs(
        trace_id='0',
        span_id='1',
        parent_span_id='2',
        flags='0',
        is_sampled=True,
    )
    with zipkin.zipkin_span(
        service_name='test_service_name',
        span_name='service_span',
        zipkin_attrs=zipkin_attrs,
        transport_handler=mock_transport_handler,
        binary_annotations={'some_key': 'some_value'},
        add_logging_annotation=True,
    ):
        pass

    span = _decode_binary_thrift_obj(mock_logs[0])
    _verify_service_span(span, default_annotations)
    # Spans continued on the server don't log timestamp/duration, as it's
    # assumed the client part of the pair will log them.
    assert span.timestamp is None
    assert span.duration is None