Exemplo n.º 1
0
def test_create_headers_for_new_span(mock_create_http_headers):
    tracer = MockTracer()
    context_stack = Stack()
    zipkin.create_http_headers_for_new_span(context_stack, tracer)

    assert mock_create_http_headers.call_count == 1
    assert mock_create_http_headers.call_args == mock.call(context_stack, tracer, True,)
Exemplo n.º 2
0
def invoke_service(request):
  headers = {}
  headers.update(create_http_headers_for_new_span())
  nextend_response = requests.get(
      'http://localhost:9002/apib',
      headers=headers,
  )
  headers = {}
  headers.update(create_http_headers_for_new_span())
  nextend_response = requests.get(
      'http://localhost:9003/api',
      headers=headers,
  )
  return Response(nextend_response.text)
Exemplo n.º 3
0
def invoke_service(request):
    headers = {}
    headers.update(create_http_headers_for_new_span())
    nextend_response = requests.get(
        'http://localhost:9002/apib',
        headers=headers,
    )
    headers = {}
    headers.update(create_http_headers_for_new_span())
    nextend_response = requests.get(
        'http://localhost:9003/api',
        headers=headers,
    )
    return Response(nextend_response.text)
Exemplo n.º 4
0
def do_stuff():
    # time.sleep(2)
    headers = create_http_headers_for_new_span()
    r = requests.get('http://www.baidu.com', headers=headers)
    log.info(r)
    log.info(r.content)
    return 'OK'
Exemplo n.º 5
0
def get_playlist_songs_info(id):
    """ Retrieves all playlist songs' information"""
    logging.debug("{aggregator_controller} BEGIN function get_playlist_songs_info()")

    if id is '':
        return RESP.response_400(message='A given parameter is empty')

    base_url = PLAYLISTS_MS + '/playlists/songs'
    url = '/'.join((base_url, str(id)))

    # Checks if song exists by sending a request into the Songs Microservice

    headers = {'Content-Type': 'application/json',
               'Authorization': request.headers['Authorization']}
    headers.update(create_http_headers_for_new_span())

    with zipkin_span(service_name='aggregator_ms', span_name='get_playlists_songs') as zipkin_context:
        r = requests.get(url, headers=headers)
        zipkin_context.update_binary_annotations({'http.method': 'GET', 'http.url': url,
                                                  'http.status_code': r.status_code})

    if r.status_code == 400:
        return RESP.response_400()
    if r.status_code == 404:
        return RESP.response_404(message='Playlist not found!')
    if r.status_code == 500:
        return RESP.response_500(message='Playlists_MS is down!')

    response_data = json.loads(r.text)

    song_ids = []
    for dictionary in response_data:
        song_ids.append(dictionary['song_id'])

    return RESP.response_200(message="Playlist Songs Info Retrieved Successfully")
Exemplo n.º 6
0
    def with_headers(self, call_name, *args, **kwargs):
        kwargs.setdefault('_request_options', {})
        headers = kwargs['_request_options'].setdefault('headers', {})

        headers.update(
            create_http_headers_for_new_span(
                context_stack=self._context_stack))
        return getattr(self.resource, call_name)(*args, **kwargs)
Exemplo n.º 7
0
def do_stuff2():
    time.sleep(2)
    headers = create_http_headers_for_new_span()
    print('do_stuff')
    print(headers)
    requests.get('http://localhost:7003/service1/', headers=headers)
    # print(res.text)
    return 'OK'
Exemplo n.º 8
0
def call_backend(request):
    headers = {}
    headers.update(create_http_headers_for_new_span())
    backend_response = requests.get(
        url='http://localhost:9000/api',
        headers=headers,
    )
    return Response(backend_response.text)
Exemplo n.º 9
0
def do_stuff():
    logger.debug("")
    time.sleep(5)
    logger.debug("")
    headers = create_http_headers_for_new_span()
    logger.debug("")
    requests.get('http://localhost:6000/service1/', headers=headers)
    logger.debug("")
    return 'OK'
def add_2_numbers_and_square_it(num1, num2):
    output = {"sum_of_numbers": 0}
    sum_of_2_numbers = num1 + num2
    headers_new = create_http_headers_for_new_span()
    response_square = requests.post(
        SQUARE_URL, json={"num": sum_of_2_numbers}, headers=headers_new)
    if response_square.ok:
        resp_sq_json = response_square.json()
        output["sum_of_numbers"] = resp_sq_json['square_of_number']
    return output
Exemplo n.º 11
0
 def _call_traced(self: MethodProxy, *args, **kwargs):
     span = zipkin.zipkin_client_span(self.service_name,
                                      self.method_name,
                                      transport_handler=transport_handler)
     start_span(span)
     self.worker_ctx.data.update(zipkin.create_http_headers_for_new_span())
     try:
         reply = _call(self, *args, **kwargs)
     except:
         stop_span(span)
         raise
     return TracedRpcReply(reply.reply_event, span)
Exemplo n.º 12
0
def do_stuff():
    time.sleep(2)
    headers = create_http_headers_for_new_span()
    print('do_stuff')
    print(headers)
    res = requests.get('http://192.168.10.104:5000/api/fortunes',
                       headers=headers)
    # res = requests.get('http://192.168.10.104:17401/values/1', headers=headers)
    # requests.post('http://localhost:9000/', headers=headers)
    # requests.get('http://localhost:6000/service1/', headers=headers)
    # print(res.text)
    return 'OK'
Exemplo n.º 13
0
def test_create_headers_for_new_span_returns_header_if_active_request(
        gen_mock, get_mock):
    get_mock.return_value = mock.Mock(
        trace_id='27133d482ba4f605', span_id='37133d482ba4f605', is_sampled=True)
    gen_mock.return_value = '17133d482ba4f605'
    expected = {
        'X-B3-TraceId': '27133d482ba4f605',
        'X-B3-SpanId': '17133d482ba4f605',
        'X-B3-ParentSpanId': '37133d482ba4f605',
        'X-B3-Flags': '0',
        'X-B3-Sampled': '1',
    }
    assert expected == zipkin.create_http_headers_for_new_span()
Exemplo n.º 14
0
def hello():
    with zipkin_span(
            service_name='hello_world_service',
            span_name='hello',
            transport_handler=http_transport,
            port=6000,
            sample_rate=100,  # Value between 0.0 and 100.0
    ):
        zipkin_headers = create_http_headers_for_new_span()
        print zipkin_headers
        time.sleep(0.2)
        requests.get('http://localhost:6001', headers=zipkin_headers)
        time.sleep(0.3)
        return "Hello World!\n", 200
Exemplo n.º 15
0
def test_create_headers_for_new_span_custom_tracer(gen_mock):
    tracer = MockTracer()
    tracer.push_zipkin_attrs(
        mock.Mock(
            trace_id='27133d482ba4f605',
            span_id='37133d482ba4f605',
            is_sampled=True,
        ))
    gen_mock.return_value = '17133d482ba4f605'
    expected = {
        'X-B3-TraceId': '27133d482ba4f605',
        'X-B3-SpanId': '17133d482ba4f605',
        'X-B3-ParentSpanId': '37133d482ba4f605',
        'X-B3-Flags': '0',
        'X-B3-Sampled': '1',
    }
    assert expected == zipkin.create_http_headers_for_new_span(tracer=tracer, )
Exemplo n.º 16
0
def get_song(id):
    """ Retrives a song given an id"""
    headers = {'Content-Type': 'application/json',
               'Authorization': request.headers['Authorization']}
    headers.update(create_http_headers_for_new_span())
    param = {'id': id}

    with zipkin_span(service_name='aggregator_ms', span_name='get_song') as zipkin_context:
        r = requests.get(SONGS_MS + '/songs', params=param, headers=headers)
        zipkin_context.update_binary_annotations({'http.method': 'GET', 'http.url': SONGS_MS + '/songs',
                                                  'http.status_code': r.status_code})

    if r.status_code == 404:
        return RESP.response_404(message='Song not found!')
    if r.status_code == 500:
        return RESP.response_500(message='Songs_MS is down!')

    return json.loads(r.text)
Exemplo n.º 17
0
    def urlopen(self, method, url, *args, **kw):
        if parsed_host and self.host == parsed_host.hostname:
            # Don't trace zipkin calls
            return func(self, method, url, **kw)

        attrs = {
            zipkin_core.HTTP_HOST: self.host,
            zipkin_core.HTTP_METHOD: method,
            zipkin_core.HTTP_PATH: url,
        }

        with zipkin_span(service_name=self.host,
                         span_name=self._absolute_url(url),
                         binary_annotations=attrs) as span:
            headers = kw['headers'] or {}
            headers.update(create_http_headers_for_new_span())

            if 'headers' in kw:
                del kw['headers']

            try:
                out = func(self, method, url, *args, headers=headers, **kw)

                if hasattr(out.connection,
                           'sock') and out.connection.sock and hasattr(
                               out.connection.sock, 'getpeername'):
                    peer = out.connection.sock.getpeername()
                    span.add_sa_binary_annotation(peer[1], self.host, peer[0])
                else:
                    span.add_sa_binary_annotation(self.port, self.host)
            except:
                # always add sa_binary even in case of error
                # but if we do it before firing urlopen, then we ended up with two annotations
                span.add_sa_binary_annotation(self.port, self.host)
                raise

            span.update_binary_annotations({
                zipkin_core.HTTP_STATUS_CODE: out.status,
                'http.retries': out.retries,
            })

        return out
Exemplo n.º 18
0
async def call_service_d(tracer, span):

    # to call next service, generate a span context using create_http_headers_for_new_span()
    span_headers = create_http_headers_for_new_span(tracer=tracer)

    # trace_id, span_id, parent_id et.al all the same
    zipkin_attrs = ZipkinAttrs(
        trace_id=span_headers.get('X-B3-TraceId'),
        span_id=span_headers.get('X-B3-SpanId'),
        parent_span_id=span_headers.get('X-B3-ParentSpanId'),
        flags=span_headers.get('X-B3-Flags'),
        is_sampled=span_headers.get('X-B3-Sampled'))

    # generate CLIENT span
    with tracer.zipkin_span(
            service_name=SERVICE_NAME,
            span_name='/services/d',
            kind=Kind.CLIENT,
            transport_handler=HttpTransport(),
            zipkin_attrs=zipkin_attrs,
    ) as client_span_d:

        res_body = None
        res_code = '500'

        req = tornado.httpclient.HTTPRequest(
            url='http://localhost:9001/services/d',
            method='GET',
            headers=span_headers)

        try:
            res = await AsyncHTTPClient().fetch(req)
            res_code = res.code
            res_body = res.body.decode().strip()
        except Exception as e:
            return "Error: %s" % e
        else:
            pass
        finally:
            client_span_d.update_binary_annotations({"result": str(res_code)})
            span.update_binary_annotations({"result": str(res_code)})
            return res_body
Exemplo n.º 19
0
def create_token(body):
    logging.debug("{authentication_controller} BEGIN function create_token()")

    if body['email'] is '' or body['password'] is '':
        return RESP.response_400(message='A given parameter is empty!')

    payload = {'email': body['email'], 'password': body['password']}

    logging.debug("{authentication_controller} %s", USERS_MS)

    with zipkin_span(service_name='authentication_ms',
                     span_name='create_token') as zipkin_context:
        headers = {}
        headers.update(create_http_headers_for_new_span())
        r = requests.post(USERS_MS + '/login', json=payload, headers=headers)
        zipkin_context.update_binary_annotations({
            'http.method':
            'POST',
            'http.url':
            USERS_MS + '/login',
            'http.status_code':
            r.status_code
        })

    if r.status_code == requests.codes.ok:
        token_info = {
            'id': json.loads(r.content).get('id'),
            'name': json.loads(r.content).get('name'),
            'email': json.loads(r.content).get('email')
        }

        token = jwt.encode(token_info, TOKEN_SECRET, algorithm=ALGORITHM)
        return RESP.response_200(message={'token': token.decode('utf-8')})
    if r.status_code == 500:
        return RESP.response_500(message='Users_MS is down!')

    return RESP.response_400(message='Credentials are incorrect!')
Exemplo n.º 20
0
def sample_child_span(dummy_request):
    return create_http_headers_for_new_span()
Exemplo n.º 21
0
 def create_http_headers_for_new_span(self):
     if self._disable:
         return dict()
     return zipkin.create_http_headers_for_new_span()
Exemplo n.º 22
0
def sample_child_span(dummy_request):
    return create_http_headers_for_new_span()
Exemplo n.º 23
0
def cart_service_do_stuff():
    time.sleep(5)
    headers = create_http_headers_for_new_span()
    requests.get('http://www.kubernetes/cart', headers=headers)
    return 'OK'
Exemplo n.º 24
0
def test_create_headers_for_new_span_empty_if_no_active_request():
    with mock.patch.object(get_default_tracer(), 'get_zipkin_attrs') as mock_ctx:
        mock_ctx.return_value = None
        assert {} == zipkin.create_http_headers_for_new_span()
Exemplo n.º 25
0
def test_create_headers_for_new_span_empty_if_no_active_request(
    mock_context_stack, ):
    mock_context_stack.get.return_value = None
    assert {} == zipkin.create_http_headers_for_new_span()
Exemplo n.º 26
0
    def with_headers(self, call_name, *args, **kwargs):
        kwargs.setdefault("_request_options", {})
        headers = kwargs["_request_options"].setdefault("headers", {})

        headers.update(create_http_headers_for_new_span())
        return getattr(self.resource, call_name)(*args, **kwargs)
Exemplo n.º 27
0
def test_create_headers_for_new_span_empty_if_no_active_request(get_mock):
    get_mock.return_value = None
    assert {} == zipkin.create_http_headers_for_new_span()
Exemplo n.º 28
0
 def create_http_headers_for_new_span(self):
     return zipkin.create_http_headers_for_new_span()