def test_span(): tracer = Tracer() parent = tracer.start_span('parent') child = tracer.start_span('test', references=child_of(parent.context)) assert parent == child child.log_kv({'event': 'cache_hit', 'size.bytes': 42}) child.log_kv({'event': 'cache_miss'}, time.time()) child.log_event('cache_hit', ['arg1', 'arg2']) with mock.patch.object(parent, 'finish') as finish: with mock.patch.object(parent, 'log_event') as log_event: with mock.patch.object(parent, 'log_kv') as log_kv: try: with parent: raise ValueError() except ValueError: pass assert finish.call_count == 1 assert log_event.call_count == 0 assert log_kv.call_count == 1 with mock.patch.object(parent, 'finish') as finish: with mock.patch.object(parent, 'log_event') as log_kv: with parent: pass assert finish.call_count == 1 assert log_kv.call_count == 0 parent.set_tag('x', 'y').set_tag('z', 1) # test chaining parent.set_tag(tags.PEER_SERVICE, 'test-service') parent.set_tag(tags.PEER_HOST_IPV4, 127 << 24 + 1) parent.set_tag(tags.PEER_HOST_IPV6, '::') parent.set_tag(tags.PEER_HOSTNAME, 'uber.com') parent.set_tag(tags.PEER_PORT, 123) parent.finish()
def test_tracer(): tracer = Tracer() span = tracer.start_span(operation_name='root') child = tracer.start_span(operation_name='child', parent=span) assert span == child fut = tracer.flush() assert type(fut) is Future fut.result(timeout=1)
def test_join_trace(): tracer = Tracer() span_ctx = tracer.extract(format=Format.TEXT_MAP, carrier={}) span = tracer.start_span(operation_name='test', references=opentracing.child_of(span_ctx)) span.set_tag('x', 'y') span.set_baggage_item('a', 'b') span.log_event('z') child = tracer.start_span(operation_name='child', references=opentracing.child_of(span.context)) child.log_event('w') child.finish() span.finish()
def test_span_error_report(): tracer = Tracer() span = tracer.start_span('foo') error_message = 'unexpected_situation' with mock.patch.object(span, 'log_kv') as log_kv: with mock.patch.object(span, 'set_tag') as set_tag: try: with span: raise ValueError(error_message) except ValueError: pass assert set_tag.call_count == 1 assert set_tag.call_args[0] == (tags.ERROR, True) assert log_kv.call_count == 1 log_kv_args = log_kv.call_args[0][0] assert log_kv_args.get(logs.EVENT, None) is tags.ERROR assert log_kv_args.get(logs.MESSAGE, None) is error_message assert log_kv_args.get(logs.ERROR_KIND, None) is ValueError assert isinstance(log_kv_args.get(logs.ERROR_OBJECT, None), ValueError) assert isinstance(log_kv_args.get(logs.STACK, None), types.TracebackType)
def test_new_trace(): tracer = Tracer() span = tracer.start_span(operation_name='test') span.set_baggage_item('Fry', 'Leela') span.set_tag('x', 'y') span.log_event('z') child = tracer.start_span(operation_name='child', parent=span) child.log_event('w') assert child.get_baggage_item('Fry') is None carrier = {} tracer.inject(span=child, format=Format.TEXT_MAP, carrier=carrier) assert carrier == dict() child.finish() span.finish()
def test_new_trace(): tracer = Tracer() span = tracer.start_span(operation_name='test') span.set_baggage_item('Fry', 'Leela') span.set_tag('x', 'y') span.log_event('z') child = tracer.start_span(operation_name='child', references=opentracing.child_of(span.context)) child.log_event('w') assert child.get_baggage_item('Fry') is None carrier = {} tracer.inject(span_context=child.context, format=Format.TEXT_MAP, carrier=carrier) assert carrier == dict() child.finish() span.finish()
def test_join_trace(): tracer = Tracer() span = tracer.join(operation_name='test', format=Format.TEXT_MAP, carrier={}) span.set_tag('x', 'y') span.log_event('z') child = tracer.start_span('child', parent=span) child.log_event('w') child.finish() span.finish()
def test_inject(): tracer = Tracer() span = tracer.start_span() bin_carrier = bytearray() tracer.inject(span_context=span.context, format=Format.BINARY, carrier=bin_carrier) assert bin_carrier == bytearray() text_carrier = {} tracer.inject(span_context=span.context, format=Format.TEXT_MAP, carrier=text_carrier) assert text_carrier == {}
def test_inject(): tracer = Tracer() span = tracer.start_span() bin_carrier = bytearray() tracer.inject( span_context=span.context, format=Format.BINARY, carrier=bin_carrier) assert bin_carrier == bytearray() text_carrier = {} tracer.inject( span_context=span.context, format=Format.TEXT_MAP, carrier=text_carrier) assert text_carrier == {}
def outgoing_trace(operation: str, request: Request, tracer: Tracer, parent: Span) \ -> Generator[Tuple[Span, Dict[str, Any]], None, None]: with tracer.start_span(operation, child_of=parent) as span: span.set_tag('http.url', request.url) remote_ip = request.client.host if remote_ip: span.set_tag(tags.PEER_HOST_IPV4, remote_ip) remote_port = request.client.port if remote_port: span.set_tag(tags.PEER_PORT, remote_port) http_header_carrier = {} tracer.inject(span_context=span, format=Format.HTTP_HEADERS, carrier=http_header_carrier) yield span, http_header_carrier
def incoming_trace(operation: str, request: Request, tracer: Tracer) -> Generator[Span, None, None]: span_context = tracer.extract(format=Format.HTTP_HEADERS, carrier=dict(request.headers)) params = {} if span_context: params["child_of"] = span_context with tracer.start_span(operation, **params) as span: span.set_tag('http.url', request.url) remote_ip = request.client.host if remote_ip: span.set_tag(tags.PEER_HOST_IPV4, remote_ip) remote_port = request.client.port if remote_port: span.set_tag(tags.PEER_PORT, remote_port) yield span
def test_tracer(): tracer = Tracer() span = tracer.start_span(operation_name="root") child = tracer.start_span(operation_name="child", references=child_of(span)) assert span == child
def test_tracer(): tracer = Tracer() span = tracer.start_span(operation_name='root') child = tracer.start_span(operation_name='child', references=child_of(span)) assert span == child
class HomeHandler(tornado.web.RequestHandler): def initialize(self): SERVICE = "Home Handler" tracer.init(o.Options(service=SERVICE, log_level=logging.DEBUG)) print("Calling initialize " + str(self) + str(SERVICE)) today = datetime.datetime.now() print(today) self.tracer = Tracer() self.span = self.tracer.start_span(operation_name='root') self.requestmethod = "" self.clazzName = self.__class__.__name__ self.span.set_tag('RequestHandler', self.clazzName) def instana_span_decorator(orig_func): @wraps(orig_func) def wrapper(*args, **kwargs): requestObject = None print("Before Call >> ") requestObject = args[0] if requestObject is not None: spanName = requestObject.clazzName print("Request Object is NOT None") print(requestObject) decorator_http_method = requestObject.request.method decorator_http_host = requestObject.request.host decorator_http_path = requestObject.request.path decorator_http_url = requestObject.request.path decorator_http_requesttime = requestObject.request.request_time( ) print("Request Object") print(decorator_http_method) parent_span = opentracing.tracer.start_span( operation_name=spanName) parent_span.set_tag(ext.COMPONENT, "Tornado Request Handler") parent_span.set_tag(ext.SPAN_KIND, ext.SPAN_KIND_RPC_SERVER) parent_span.set_tag(ext.PEER_HOSTNAME, decorator_http_host) parent_span.set_tag(ext.HTTP_URL, decorator_http_path) parent_span.set_tag(ext.HTTP_METHOD, decorator_http_method) parent_span.set_tag(ext.HTTP_STATUS_CODE, 200) parent_span.set_tag("RequestTime", decorator_http_requesttime) result = orig_func(*args, **kwargs) parent_span.finish() else: print("help") parent_span = opentracing.tracer.start_span( operation_name="DemoSpan") parent_span.set_tag(ext.COMPONENT, "Tornado") parent_span.set_tag(ext.SPAN_KIND, ext.SPAN_KIND_RPC_SERVER) parent_span.set_tag(ext.PEER_HOSTNAME, "localhost") parent_span.set_tag(ext.HTTP_URL, "/") parent_span.set_tag(ext.HTTP_METHOD, "GET") parent_span.set_tag(ext.HTTP_STATUS_CODE, 404) result = orig_func(*args, **kwargs) parent_span.finish() print(" << After Call") return result return wrapper @instana_span_decorator def get(self): self.write("Get Try") @instana_span_decorator def post(self): self.write("Post Try")
class MainHandler(tornado.web.RequestHandler): def initialize(self): SERVICE = "🦄 Stan ❤️s Python 🦄" tracer.init(o.Options(service=SERVICE, log_level=logging.DEBUG)) print("Calling initialize " + str(self) + str(SERVICE)) today = datetime.datetime.now() print(today) self.tracer = Tracer() self.span = self.tracer.start_span(operation_name='root') self.requestmethod = "" self.clazzName = self.__class__.__name__ self.span.set_tag('RequestHandler', self.clazzName) def instana_span_decorator(orig_func): @wraps(orig_func) def wrapper(*args, **kwargs): requestObject = None print("Before Call >> ") requestObject = args[0] if requestObject is not None: spanName = requestObject.clazzName print("Request Object is NOT None") print(requestObject) decorator_http_method = requestObject.request.method decorator_http_host = requestObject.request.host decorator_http_path = requestObject.request.path decorator_http_url = requestObject.request.path decorator_http_requesttime = requestObject.request.request_time( ) print("Request Object") print(decorator_http_method) parent_span = opentracing.tracer.start_span( operation_name=spanName) parent_span.set_tag(ext.COMPONENT, "Tornado Request Handler") parent_span.set_tag(ext.SPAN_KIND, ext.SPAN_KIND_RPC_SERVER) parent_span.set_tag(ext.PEER_HOSTNAME, decorator_http_host) parent_span.set_tag(ext.HTTP_URL, decorator_http_path) parent_span.set_tag(ext.HTTP_METHOD, decorator_http_method) parent_span.set_tag(ext.HTTP_STATUS_CODE, 200) parent_span.set_tag("RequestTime", decorator_http_requesttime) result = orig_func(*args, **kwargs) parent_span.finish() else: print("help") parent_span = opentracing.tracer.start_span( operation_name="DemoSpan") parent_span.set_tag(ext.COMPONENT, "Tornado") parent_span.set_tag(ext.SPAN_KIND, ext.SPAN_KIND_RPC_SERVER) parent_span.set_tag(ext.PEER_HOSTNAME, "localhost") parent_span.set_tag(ext.HTTP_URL, "/") parent_span.set_tag(ext.HTTP_METHOD, "GET") parent_span.set_tag(ext.HTTP_STATUS_CODE, 404) result = orig_func(*args, **kwargs) parent_span.finish() print(" << After Call") return result return wrapper @instana_span_decorator def get(self): self.requestmethod = "GET" print("GET CALLED") self.write( "<html><head><title>Python Tracing Demo</title></head><body>") self.write("<h1>Welcome to the Python Tracing</h1>") self.write("<hr></hr>") welcomeMessage = """Welcome to the Instana Python Sensor and Tracing Example. The instana package provides Python metrics and traces (request, queue & cross-host) for Instana. Build Status OpenTracing Badge Note This package supports Python 2.7 or greater. Any and all feedback is welcome. Happy Python visibility. See the <a href="https://github.com/instana/python-sensor">Python Sensor</a> Installation : pip install instana into the virtual-env or container (hosted on pypi) """ localheaders = self.request.headers myHost = localheaders["Host"] userAgent = localheaders["User-Agent"] connection = localheaders["Connection"] cacheControl = localheaders["Cache-Control"] referrer = localheaders["Referer"] self.write(welcomeMessage) self.write("<ul>") self.write("<li>") self.write(myHost) self.write("<li>") self.write(userAgent) self.write("<li>") self.write(connection) self.write("<li>") self.write(referrer) self.write("<li>") self.write(self.request.uri) self.write("<li>") self.write(self.request.path) self.write("<li>") self.write(self.request.query) self.write("<li>") self.write(self.request.version) self.write("<li>") self.write(self.request.protocol) self.write("<li>") self.write(self.request.host) self.write("</ul>") self.write(str(self.request.headers)) self.write("</body></html>") print("GET ENDED") @instana_span_decorator def head(self): self.requestmethod = "HEAD" print("HEAD CALLED") def post(self): self.requestmethod = "POST" print("POST CALLED") self.write("<h1>THIS is a POST</h1>") def prepare(self): print("Called Prepare") def on_finish(self): print("Called Finish")
class MainHandler(tornado.web.RequestHandler): def initialize(self): SERVICE = "🦄 Stan ❤️s Python 🦄" tracer.init(o.Options(service=SERVICE, log_level=logging.DEBUG)) print("Calling initialize " + str(self) + str(SERVICE)) today = datetime.datetime.now() print(today) self.tracer = Tracer() self.span = self.tracer.start_span(operation_name='root') self.span.set_tag('RequestHandler', 'MainHandler') self.requestmethod = "" self.clazzName = self.__class__.__name__ def instana_span_decorator(orig_func): @wraps(orig_func) def wrapper(*args, **kwargs): print("Before Call >> ") thisInstance = args[0] parent_span = opentracing.tracer.start_span( operation_name="DemoSpan") parent_span.set_tag(ext.COMPONENT, "Tornado") parent_span.set_tag(ext.SPAN_KIND, ext.SPAN_KIND_RPC_SERVER) parent_span.set_tag(ext.PEER_HOSTNAME, "localhost") parent_span.set_tag(ext.HTTP_URL, "/") parent_span.set_tag(ext.HTTP_METHOD, thisInstance.requestmethod) parent_span.set_tag(ext.HTTP_STATUS_CODE, 200) result = orig_func(*args, **kwargs) parent_span.finish() print(" << After Call") return result return wrapper @instana_span_decorator def get(self): self.requestmethod = "GET" print("GET CALLED") self.write("<h1>Welcome to the Python Tracing</h1>") self.write("<hr></hr>") welcomeMessage = """Welcome to the Instana Python Sensor and Tracing Example. The instana package provides Python metrics and traces (request, queue & cross-host) for Instana. Build Status OpenTracing Badge Note This package supports Python 2.7 or greater. Any and all feedback is welcome. Happy Python visibility. See the <a href="https://github.com/instana/python-sensor">Python Sensor</a> Installation : pip install instana into the virtual-env or container (hosted on pypi) """ self.write(welcomeMessage) @instana_span_decorator def head(self): self.requestmethod = "HEAD" print("HEAD CALLED") def post(self): self.requestmethod = "POST" print("POST CALLED") self.write("<h1>THIS is a POST</h1>") def prepare(self): print("Called Prepare") def on_finish(self): print("Called Finish")