├── .flake8 ├── .gitignore ├── .travis.yml ├── CHANGELOG.rst ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README.md ├── basictracer ├── __init__.py ├── binary_propagator.py ├── context.py ├── propagator.py ├── recorder.py ├── span.py ├── text_propagator.py ├── tracer.py ├── util.py └── wire_pb2.py ├── examples └── span_logging.py ├── requirements-test.txt ├── requirements.txt ├── setup.cfg ├── setup.py ├── tests ├── __init__.py ├── test_api.py ├── test_propagation.py ├── test_span.py └── utils.py └── tox.ini /.flake8: -------------------------------------------------------------------------------- 1 | [flake8] 2 | exclude = 3 | basictracer/wire_pb2.py 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.py[cod] 2 | *.orig 3 | 4 | # Ignore gen/ directory where we temporarily store thrift classes to help with development 5 | gen/ 6 | 7 | # No local dbs 8 | *.db 9 | 10 | # C extensions 11 | *.so 12 | 13 | # Packages 14 | *.egg 15 | *.egg-info 16 | 17 | .tests 18 | 19 | bin 20 | build 21 | develop-eggs 22 | dist 23 | eggs 24 | parts 25 | sdist 26 | var 27 | 28 | .installed.cfg 29 | lib64 30 | __pycache__ 31 | .cache/ 32 | 33 | # Installer logs 34 | pip-log.txt 35 | 36 | # Unit test / coverage reports 37 | .coverage 38 | .coverage* 39 | .tox 40 | .noseids 41 | 42 | # Translations 43 | *.mo 44 | 45 | # Ignore python virtual environments 46 | env* 47 | thrift_env 48 | 49 | # Ignore local logs 50 | *.log 51 | logs/* 52 | !logs/.gitkeep 53 | 54 | # Ignore local log 55 | npm-debug.log 56 | 57 | # Ignore docs 58 | docs/_build/* 59 | 60 | # ignore ipython profile stuff 61 | config/profile_default/ 62 | !config/profile_default/ipython_config.py 63 | config/README 64 | protobuf/*.py 65 | 66 | .phutil_module_cache 67 | 68 | # Ignore coverage output 69 | *.xml 70 | coverage/ 71 | 72 | # Ignore benchmarks output 73 | perf.log 74 | perf.svg 75 | 76 | # vim 77 | *.swp 78 | .idea/ 79 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | dist: xenial 2 | 3 | language: python 4 | python: 5 | - "2.7" 6 | - "3.6" 7 | - "3.7" 8 | - "3.8-dev" 9 | 10 | matrix: 11 | allow_failures: 12 | - python: "3.8-dev" 13 | 14 | install: 15 | - make bootstrap 16 | 17 | script: 18 | - make test lint 19 | -------------------------------------------------------------------------------- /CHANGELOG.rst: -------------------------------------------------------------------------------- 1 | .. :changelog: 2 | 3 | History 4 | ------- 5 | 6 | 3.2.1 (unreleased) 7 | ------------------ 8 | 9 | - Nothing changed yet. 10 | 11 | 12 | 3.2.0 (2021-04-12) 13 | ------------------ 14 | 15 | - setup.py: Remove test dependency doubles (#44) 16 | - Do not throw error when no tracing headers are sent (#43) 17 | - Stop testing with Python 3.5 18 | - Provide meaningful error messages when failed to extract headers from carrier (#42) 19 | - TextPropagator.extract raises SpanContextCorruptedException with 20 | more meaningful error messages. 21 | - Tracer.start_span validates type of ``references=`` preventing 22 | problems for users migrating code from opentracing==1.3.0. 23 | 24 | 25 | 3.1.0 (2019-05-12) 26 | ------------------ 27 | 28 | - Unpin OpenTracing dependency and change to a range (#40) 29 | - Add support for Python 3.5+ (#39) 30 | - Include 0,1 as acceptable sampled value (#37) 31 | 32 | 33 | 3.0.0 (2018-07-10) 34 | ------------------ 35 | 36 | - Update our OT dependency to 2.0.0. 37 | - Implement ScopeManager for in-process propagation. 38 | 39 | 40 | 2.2.1 (2018-02-20) 41 | ------------------ 42 | 43 | - Update OT dependency to >=1.2.1 and <2.0. 44 | 45 | 46 | 2.2.0 (2016-09-22) 47 | ------------------ 48 | 49 | - Bump the minor version :-/ 50 | 51 | 52 | 2.1.2 (2016-09-22) 53 | ------------------ 54 | 55 | - Adjust to OT logging changes 56 | 57 | 58 | 2.1.1 (2016-08-19) 59 | ------------------ 60 | 61 | - Make the RNG robust to fork() 62 | 63 | 64 | 2.1.0 (2016-08-07) 65 | ------------------ 66 | 67 | - Implement immutable SpanContext 68 | 69 | 70 | 2.0.1.dev1 (2016-08-04) 71 | ----------------------- 72 | 73 | - Allow BasicTracer users to opt in to propagators 74 | 75 | 76 | 2.0.0.dev3 (2016-07-26) 77 | ----------------------- 78 | 79 | - Positional arguments 80 | 81 | 82 | 2.0.0.dev2 (2016-07-26) 83 | ----------------------- 84 | 85 | - Adapt to SpanContext changes 86 | 87 | 88 | 2.0.0.dev1 (2016-07-12) 89 | ----------------------- 90 | 91 | - Rename ChildOf/FollowsFrom to child_of/follows_from 92 | 93 | 94 | 2.0.0.dev0 (2016-07-11) 95 | ----------------------- 96 | 97 | - Adapt to SpanContext changes 98 | 99 | 100 | 1.0rc2 (2016-07-06) 101 | ------------------- 102 | 103 | - Add InMemoryRecorder and respect sampling.priority tag 104 | 105 | 106 | 1.0rc1 (2015-05-11) 107 | ------------------- 108 | 109 | - Official release 110 | 111 | 112 | 0.1.0 (2016-5-4) 113 | ---------------- 114 | 115 | - Initial public API 116 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright The OpenTracing Authors 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | recursive-include basictracer * 2 | recursive-include tests *.py 3 | include * 4 | global-exclude *.pyc 5 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | project := basictracer 2 | 3 | pytest := PYTHONDONTWRITEBYTECODE=1 py.test --tb short -rxs \ 4 | --cov-config .coveragerc --cov $(project) tests 5 | 6 | html_report := --cov-report=html 7 | test_args := --cov-report xml --cov-report term-missing 8 | 9 | .PHONY: clean-pyc clean-build docs clean 10 | .DEFAULT_GOAL : help 11 | 12 | help: 13 | @echo "bootstrap - initialize local environement for development. Requires virtualenv." 14 | @echo "clean - remove all build, test, coverage and Python artifacts" 15 | @echo "clean-build - remove build artifacts" 16 | @echo "clean-pyc - remove Python file artifacts" 17 | @echo "clean-test - remove test and coverage artifacts" 18 | @echo "lint - check style with flake8" 19 | @echo "test - run tests quickly with the default Python" 20 | @echo "coverage - check code coverage quickly with the default Python" 21 | @echo "docs - generate Sphinx HTML documentation, including API docs" 22 | @echo "release - package and upload a release" 23 | @echo "dist - package" 24 | @echo "install - install the package to the active Python's site-packages" 25 | 26 | check-virtual-env: 27 | @echo virtual-env: $${VIRTUAL_ENV?"Please run in virtual-env"} 28 | 29 | bootstrap: check-virtual-env 30 | pip install -r requirements.txt 31 | pip install -r requirements-test.txt 32 | python setup.py develop 33 | 34 | clean: clean-build clean-pyc clean-test 35 | 36 | clean-build: 37 | rm -fr build/ 38 | rm -fr dist/ 39 | rm -fr .eggs/ 40 | find . -name '*.egg-info' -exec rm -fr {} + 41 | find . -name '*.egg' -exec rm -rf {} + 42 | 43 | clean-pyc: 44 | find . -name '*.pyc' -exec rm -f {} + 45 | find . -name '*.pyo' -exec rm -f {} + 46 | find . -name '*~' -exec rm -f {} + 47 | find . -name '__pycache__' -exec rm -fr {} + 48 | 49 | clean-test: 50 | rm -f .coverage 51 | rm -f coverage.xml 52 | rm -fr htmlcov/ 53 | 54 | lint: 55 | flake8 --config=.flake8 $(project) tests 56 | 57 | test: 58 | $(pytest) $(test_args) 59 | 60 | jenkins: 61 | pip install -r requirements.txt 62 | pip install -r requirements-test.txt 63 | python setup.py develop 64 | CLAY_CONFIG=config/test.yaml $(pytest) $(test_args) --junit-xml=jenkins.xml 65 | 66 | coverage: 67 | coverage run --source $(project) setup.py test 68 | coverage report -m 69 | coverage html 70 | open htmlcov/index.html 71 | 72 | docs: 73 | $(MAKE) -C docs clean 74 | $(MAKE) -C docs html 75 | 76 | release: clean 77 | @echo Please see README 78 | # python setup.py sdist upload 79 | # python setup.py bdist_wheel upload 80 | 81 | dist: clean 82 | @echo Please see README 83 | # python setup.py sdist 84 | # python setup.py bdist_wheel 85 | # ls -l dist 86 | 87 | install: 88 | pip install -r requirements.txt 89 | pip install -r requirements-test.txt 90 | echo skipping pip install -r requirements-doc.txt 91 | python setup.py install 92 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Gitter chat](http://img.shields.io/badge/gitter-join%20chat%20%E2%86%92-brightgreen.svg)](https://gitter.im/opentracing/public) [![Build Status](https://travis-ci.org/opentracing/basictracer-python.svg?branch=master)](https://travis-ci.org/opentracing/basictracer-python) [![PyPI version](https://badge.fury.io/py/basictracer.svg)](https://badge.fury.io/py/basictracer) 2 | 3 | # Basictracer Python 4 | 5 | A python version of the "BasicTracer" reference implementation for OpenTracing. 6 | 7 | The `examples/` directory contains a sample of how the BasicTracer 8 | implementation could be used to display spans in the console. 9 | 10 | ## Development 11 | 12 | ### Tests 13 | 14 | ```sh 15 | virtualenv env 16 | . ./env/bin/activate 17 | make bootstrap 18 | make test 19 | ``` 20 | 21 | You can use [tox](https://tox.readthedocs.io) to run tests as well. 22 | ```bash 23 | tox 24 | ``` 25 | 26 | ### Releases 27 | 28 | Before new release, add a summary of changes since last version to CHANGELOG.rst 29 | 30 | ```sh 31 | pip install zest.releaser[recommended] 32 | prerelease 33 | release 34 | git push origin master --follow-tags 35 | python setup.py sdist upload -r pypi 36 | postrelease 37 | git push 38 | ``` 39 | 40 | ## Licensing 41 | 42 | [Apache 2.0 License](./LICENSE). 43 | 44 | -------------------------------------------------------------------------------- /basictracer/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | from .tracer import BasicTracer # noqa 4 | from .recorder import SpanRecorder, Sampler, DefaultSampler # noqa 5 | -------------------------------------------------------------------------------- /basictracer/binary_propagator.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | import struct 4 | from .context import SpanContext 5 | from .propagator import Propagator 6 | # This can cause problems when old versions of protobuf are installed 7 | from .wire_pb2 import TracerState 8 | from opentracing import InvalidCarrierException 9 | 10 | _proto_size_bytes = 4 # bytes 11 | 12 | 13 | class BinaryPropagator(Propagator): 14 | """A BasicTracer Propagator for Format.BINARY.""" 15 | 16 | def inject(self, span_context, carrier): 17 | if type(carrier) is not bytearray: 18 | raise InvalidCarrierException() 19 | state = TracerState() 20 | state.trace_id = span_context.trace_id 21 | state.span_id = span_context.span_id 22 | state.sampled = span_context.sampled 23 | if span_context.baggage is not None: 24 | for key in span_context.baggage: 25 | state.baggage_items[key] = span_context.baggage[key] 26 | 27 | # The binary format is {uint32}{protobuf} using big-endian for the uint 28 | carrier.extend(struct.pack('>I', state.ByteSize())) 29 | carrier.extend(state.SerializeToString()) 30 | 31 | def extract(self, carrier): 32 | if type(carrier) is not bytearray: 33 | raise InvalidCarrierException() 34 | state = TracerState() 35 | state.ParseFromString(bytes(carrier[_proto_size_bytes:])) 36 | baggage = {} 37 | for k in state.baggage_items: 38 | baggage[k] = state.baggage_items[k] 39 | 40 | return SpanContext( 41 | span_id=state.span_id, 42 | trace_id=state.trace_id, 43 | baggage=baggage, 44 | sampled=state.sampled) 45 | -------------------------------------------------------------------------------- /basictracer/context.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | import opentracing 4 | 5 | 6 | class SpanContext(opentracing.SpanContext): 7 | """SpanContext satisfies the opentracing.SpanContext contract. 8 | 9 | trace_id and span_id are uint64's, so their range is [0, 2^64). 10 | """ 11 | 12 | def __init__( 13 | self, 14 | trace_id=None, 15 | span_id=None, 16 | baggage=None, 17 | sampled=True): 18 | self.trace_id = trace_id 19 | self.span_id = span_id 20 | self.sampled = sampled 21 | self._baggage = baggage or opentracing.SpanContext.EMPTY_BAGGAGE 22 | 23 | @property 24 | def baggage(self): 25 | return self._baggage 26 | 27 | def with_baggage_item(self, key, value): 28 | new_baggage = self._baggage.copy() 29 | new_baggage[key] = value 30 | return SpanContext( 31 | trace_id=self.trace_id, 32 | span_id=self.span_id, 33 | sampled=self.sampled, 34 | baggage=new_baggage) 35 | -------------------------------------------------------------------------------- /basictracer/propagator.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | from abc import ABCMeta, abstractmethod 4 | import six 5 | 6 | 7 | class Propagator(six.with_metaclass(ABCMeta, object)): 8 | 9 | @abstractmethod 10 | def inject(self, span_context, carrier): 11 | pass 12 | 13 | @abstractmethod 14 | def extract(self, carrier): 15 | pass 16 | -------------------------------------------------------------------------------- /basictracer/recorder.py: -------------------------------------------------------------------------------- 1 | import threading 2 | 3 | from abc import ABCMeta, abstractmethod 4 | import six 5 | 6 | 7 | class SpanRecorder(six.with_metaclass(ABCMeta, object)): 8 | """SpanRecorder is a simple abstract interface built around record_span. 9 | """ 10 | 11 | @abstractmethod 12 | def record_span(self, span): 13 | """After the call to finish(), each BasicSpan is passed as `span` to 14 | SpanRecorder.record_span. 15 | 16 | :param BasicSpan span: the finish()'d BasicSpan object. 17 | """ 18 | pass 19 | 20 | 21 | class InMemoryRecorder(SpanRecorder): 22 | """InMemoryRecorder stores all received spans in an internal list. 23 | 24 | This recorder is not suitable for production use, only for testing. 25 | """ 26 | def __init__(self): 27 | self.spans = [] 28 | self.mux = threading.Lock() 29 | 30 | def record_span(self, span): 31 | with self.mux: 32 | self.spans.append(span) 33 | 34 | def get_spans(self): 35 | with self.mux: 36 | return self.spans[:] 37 | 38 | 39 | class Sampler(six.with_metaclass(ABCMeta, object)): 40 | """Sampler determines the sampling status of a span given its trace_id. 41 | 42 | Sampler.sampled() is expected to return a boolean. 43 | """ 44 | 45 | @abstractmethod 46 | def sampled(self, trace_id): 47 | pass 48 | 49 | 50 | class DefaultSampler(Sampler): 51 | """DefaultSampler determines the sampling status via ID % rate == 0. 52 | """ 53 | def __init__(self, rate): 54 | self.rate = rate 55 | 56 | def sampled(self, trace_id): 57 | return trace_id % self.rate == 0 58 | -------------------------------------------------------------------------------- /basictracer/span.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | from threading import Lock 4 | import time 5 | 6 | from opentracing import Span 7 | from opentracing.ext import tags 8 | 9 | 10 | class BasicSpan(Span): 11 | """BasicSpan is a thread-safe implementation of opentracing.Span. 12 | """ 13 | 14 | def __init__( 15 | self, 16 | tracer, 17 | operation_name=None, 18 | context=None, 19 | parent_id=None, 20 | tags=None, 21 | start_time=None): 22 | super(BasicSpan, self).__init__(tracer, context) 23 | self._tracer = tracer 24 | self._lock = Lock() 25 | 26 | self.operation_name = operation_name 27 | self.start_time = start_time 28 | self.parent_id = parent_id 29 | self.tags = tags if tags is not None else {} 30 | self.duration = -1 31 | self.logs = [] 32 | 33 | def set_operation_name(self, operation_name): 34 | with self._lock: 35 | self.operation_name = operation_name 36 | return super(BasicSpan, self).set_operation_name(operation_name) 37 | 38 | def set_tag(self, key, value): 39 | with self._lock: 40 | if key == tags.SAMPLING_PRIORITY: 41 | self.context.sampled = value > 0 42 | if self.tags is None: 43 | self.tags = {} 44 | self.tags[key] = value 45 | return super(BasicSpan, self).set_tag(key, value) 46 | 47 | def log_kv(self, key_values, timestamp=None): 48 | with self._lock: 49 | self.logs.append(LogData(key_values, timestamp)) 50 | return super(BasicSpan, self).log_kv(key_values, timestamp) 51 | 52 | def finish(self, finish_time=None): 53 | with self._lock: 54 | finish = time.time() if finish_time is None else finish_time 55 | self.duration = finish - self.start_time 56 | self._tracer.record(self) 57 | 58 | def set_baggage_item(self, key, value): 59 | new_context = self._context.with_baggage_item(key, value) 60 | with self._lock: 61 | self._context = new_context 62 | return self 63 | 64 | def get_baggage_item(self, key): 65 | with self._lock: 66 | return self.context.baggage.get(key) 67 | 68 | 69 | class LogData(object): 70 | def __init__( 71 | self, 72 | key_values, 73 | timestamp=None): 74 | self.key_values = key_values 75 | self.timestamp = time.time() if timestamp is None else timestamp 76 | -------------------------------------------------------------------------------- /basictracer/text_propagator.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | from opentracing import SpanContextCorruptedException 4 | from .context import SpanContext 5 | from .propagator import Propagator 6 | 7 | prefix_tracer_state = 'ot-tracer-' 8 | prefix_baggage = 'ot-baggage-' 9 | field_name_trace_id = prefix_tracer_state + 'traceid' 10 | field_name_span_id = prefix_tracer_state + 'spanid' 11 | field_name_sampled = prefix_tracer_state + 'sampled' 12 | field_count = 3 13 | 14 | 15 | def parse_hex_for_field(field_name, value): 16 | """parses the hexadecimal value of a field into an integer. 17 | Raises SpanContextCorruptedException in case of failure 18 | """ 19 | try: 20 | return int(value, 16) 21 | except ValueError: 22 | msg = '{field_name} got an invalid hexadecimal value {value!r}' 23 | msg = msg.format(field_name=field_name, value=value) 24 | raise SpanContextCorruptedException(msg) 25 | 26 | 27 | def parse_boolean_for_field(field_name, value): 28 | """parses the string value of a field into a boolean. 29 | Raises SpanContextCorruptedException in case of failure 30 | """ 31 | if value in ('true', '1'): 32 | return True 33 | elif value in ('false', '0'): 34 | return False 35 | 36 | msg = ( 37 | '{field} got an invalid value {value!r}, ' 38 | "should be one of \'true\', \'false\', \'0\', \'1\'" 39 | ) 40 | raise SpanContextCorruptedException(msg.format( 41 | value=value, 42 | field=field_name_sampled 43 | )) 44 | 45 | 46 | class TextPropagator(Propagator): 47 | """A BasicTracer Propagator for Format.TEXT_MAP.""" 48 | 49 | def inject(self, span_context, carrier): 50 | carrier[field_name_trace_id] = '{0:x}'.format(span_context.trace_id) 51 | carrier[field_name_span_id] = '{0:x}'.format(span_context.span_id) 52 | carrier[field_name_sampled] = str(span_context.sampled).lower() 53 | if span_context.baggage is not None: 54 | for k in span_context.baggage: 55 | carrier[prefix_baggage+k] = span_context.baggage[k] 56 | 57 | def extract(self, carrier): # noqa 58 | count = 0 59 | span_id, trace_id, sampled = (0, 0, False) 60 | baggage = {} 61 | for k in carrier: 62 | v = carrier[k] 63 | k = k.lower() 64 | if k == field_name_span_id: 65 | span_id = parse_hex_for_field(field_name_span_id, v) 66 | count += 1 67 | elif k == field_name_trace_id: 68 | trace_id = parse_hex_for_field(field_name_trace_id, v) 69 | count += 1 70 | elif k == field_name_sampled: 71 | sampled = parse_boolean_for_field(field_name_sampled, v) 72 | count += 1 73 | elif k.startswith(prefix_baggage): 74 | baggage[k[len(prefix_baggage):]] = v 75 | 76 | if count == 0: 77 | if len(baggage) > 0: 78 | raise SpanContextCorruptedException( 79 | 'found baggage without required fields') 80 | 81 | return None 82 | 83 | if count != field_count: 84 | msg = ( 85 | 'expected to parse {field_count} fields' 86 | ', but parsed {count} instead' 87 | ) 88 | raise SpanContextCorruptedException(msg.format( 89 | field_count=field_count, 90 | count=count, 91 | )) 92 | 93 | return SpanContext( 94 | span_id=span_id, 95 | trace_id=trace_id, 96 | baggage=baggage, 97 | sampled=sampled) 98 | -------------------------------------------------------------------------------- /basictracer/tracer.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | import opentracing 4 | from opentracing import Format, Tracer 5 | from opentracing import UnsupportedFormatException 6 | from opentracing.scope_managers import ThreadLocalScopeManager 7 | from .context import SpanContext 8 | from .recorder import SpanRecorder, DefaultSampler 9 | from .span import BasicSpan 10 | from .util import generate_id 11 | 12 | 13 | class BasicTracer(Tracer): 14 | 15 | def __init__(self, recorder=None, sampler=None, scope_manager=None): 16 | """Initialize a BasicTracer instance. 17 | 18 | Note that the returned BasicTracer has *no* propagators registered. The 19 | user should either call register_propagator() for each needed 20 | inject/extract format and/or the user can simply call 21 | register_required_propagators(). 22 | 23 | The required formats are opt-in because of protobuf version conflicts 24 | with the binary carrier. 25 | """ 26 | 27 | scope_manager = ThreadLocalScopeManager() \ 28 | if scope_manager is None else scope_manager 29 | super(BasicTracer, self).__init__(scope_manager) 30 | 31 | self.recorder = NoopRecorder() if recorder is None else recorder 32 | self.sampler = DefaultSampler(1) if sampler is None else sampler 33 | self._propagators = {} 34 | 35 | def register_propagator(self, format, propagator): 36 | """Register a propagator with this BasicTracer. 37 | 38 | :param string format: a Format identifier like Format.TEXT_MAP 39 | :param Propagator propagator: a Propagator instance to handle 40 | inject/extract calls involving `format` 41 | """ 42 | self._propagators[format] = propagator 43 | 44 | def register_required_propagators(self): 45 | from .text_propagator import TextPropagator 46 | from .binary_propagator import BinaryPropagator 47 | self.register_propagator(Format.TEXT_MAP, TextPropagator()) 48 | self.register_propagator(Format.HTTP_HEADERS, TextPropagator()) 49 | self.register_propagator(Format.BINARY, BinaryPropagator()) 50 | 51 | def start_active_span(self, 52 | operation_name, 53 | child_of=None, 54 | references=None, 55 | tags=None, 56 | start_time=None, 57 | ignore_active_span=False, 58 | finish_on_close=True): 59 | 60 | # create a new Span 61 | span = self.start_span( 62 | operation_name=operation_name, 63 | child_of=child_of, 64 | references=references, 65 | tags=tags, 66 | start_time=start_time, 67 | ignore_active_span=ignore_active_span, 68 | ) 69 | 70 | return self.scope_manager.activate(span, finish_on_close) 71 | 72 | def start_span(self, 73 | operation_name=None, 74 | child_of=None, 75 | references=None, 76 | tags=None, 77 | start_time=None, 78 | ignore_active_span=False): 79 | 80 | if isinstance(references, opentracing.Reference): 81 | references = [references] 82 | 83 | start_time = time.time() if start_time is None else start_time 84 | 85 | # See if we have a parent_ctx in `references` 86 | parent_ctx = None 87 | if child_of is not None: 88 | parent_ctx = ( 89 | child_of if isinstance(child_of, opentracing.SpanContext) 90 | else child_of.context) 91 | elif references is not None and len(references) > 0: 92 | # TODO only the first reference is currently used 93 | first_ref = references[0] 94 | if not isinstance(first_ref, opentracing.Reference): 95 | msg = ( 96 | 'references[0] should be a opentracing.Reference ' 97 | 'objects, got %r instead' 98 | ) 99 | raise TypeError(msg % first_ref) 100 | parent_ctx = first_ref.referenced_context 101 | 102 | # retrieve the active SpanContext 103 | if not ignore_active_span and parent_ctx is None: 104 | scope = self.scope_manager.active 105 | if scope is not None: 106 | parent_ctx = scope.span.context 107 | 108 | # Assemble the child ctx 109 | ctx = SpanContext(span_id=generate_id()) 110 | if parent_ctx is not None: 111 | if parent_ctx._baggage is not None: 112 | ctx._baggage = parent_ctx._baggage.copy() 113 | ctx.trace_id = parent_ctx.trace_id 114 | ctx.sampled = parent_ctx.sampled 115 | else: 116 | ctx.trace_id = generate_id() 117 | ctx.sampled = self.sampler.sampled(ctx.trace_id) 118 | 119 | # Tie it all together 120 | return BasicSpan( 121 | self, 122 | operation_name=operation_name, 123 | context=ctx, 124 | parent_id=(None if parent_ctx is None else parent_ctx.span_id), 125 | tags=tags, 126 | start_time=start_time) 127 | 128 | def inject(self, span_context, format, carrier): 129 | if format in self._propagators: 130 | self._propagators[format].inject(span_context, carrier) 131 | else: 132 | raise UnsupportedFormatException() 133 | 134 | def extract(self, format, carrier): 135 | if format in self._propagators: 136 | return self._propagators[format].extract(carrier) 137 | else: 138 | raise UnsupportedFormatException() 139 | 140 | def record(self, span): 141 | self.recorder.record_span(span) 142 | 143 | 144 | class NoopRecorder(SpanRecorder): 145 | def record_span(self, span): 146 | pass 147 | -------------------------------------------------------------------------------- /basictracer/util.py: -------------------------------------------------------------------------------- 1 | import random 2 | import os 3 | import time 4 | 5 | # A basictracer-specific instance of guid_rng. See _fork_guard_pid. 6 | guid_rng = random.Random() 7 | 8 | # The current pid. If the process forks (which happens, for instance, in 9 | # uwsgi), we consult _fork_guard_pid and re-seed guid_rng accordingly. 10 | _fork_guard_pid = 0 11 | 12 | 13 | def generate_id(): 14 | global _fork_guard_pid 15 | 16 | # Microbenchmarks suggest that os.getpid() takes less than 0.1 microsecond. 17 | pid = os.getpid() 18 | if (_fork_guard_pid == 0) or (_fork_guard_pid != pid): 19 | _fork_guard_pid = pid 20 | guid_rng.seed(int(1000000 * time.time()) ^ pid) 21 | return guid_rng.getrandbits(64) - 1 22 | -------------------------------------------------------------------------------- /basictracer/wire_pb2.py: -------------------------------------------------------------------------------- 1 | # Generated by the protocol buffer compiler. DO NOT EDIT! 2 | # source: wire.proto 3 | 4 | import sys 5 | _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) 6 | from google.protobuf import descriptor as _descriptor 7 | from google.protobuf import message as _message 8 | from google.protobuf import reflection as _reflection 9 | from google.protobuf import symbol_database as _symbol_database 10 | from google.protobuf import descriptor_pb2 11 | # @@protoc_insertion_point(imports) 12 | 13 | _sym_db = _symbol_database.Default() 14 | 15 | 16 | 17 | 18 | DESCRIPTOR = _descriptor.FileDescriptor( 19 | name='wire.proto', 20 | package='basictracer_go.wire', 21 | syntax='proto3', 22 | serialized_pb=_b('\n\nwire.proto\x12\x13\x62\x61sictracer_go.wire\"\xc1\x01\n\x0bTracerState\x12\x10\n\x08trace_id\x18\x01 \x01(\x06\x12\x0f\n\x07span_id\x18\x02 \x01(\x06\x12\x0f\n\x07sampled\x18\x03 \x01(\x08\x12I\n\rbaggage_items\x18\x04 \x03(\x0b\x32\x32.basictracer_go.wire.TracerState.BaggageItemsEntry\x1a\x33\n\x11\x42\x61ggageItemsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x42\x06Z\x04wireb\x06proto3') 23 | ) 24 | _sym_db.RegisterFileDescriptor(DESCRIPTOR) 25 | 26 | 27 | 28 | 29 | _TRACERSTATE_BAGGAGEITEMSENTRY = _descriptor.Descriptor( 30 | name='BaggageItemsEntry', 31 | full_name='basictracer_go.wire.TracerState.BaggageItemsEntry', 32 | filename=None, 33 | file=DESCRIPTOR, 34 | containing_type=None, 35 | fields=[ 36 | _descriptor.FieldDescriptor( 37 | name='key', full_name='basictracer_go.wire.TracerState.BaggageItemsEntry.key', index=0, 38 | number=1, type=9, cpp_type=9, label=1, 39 | has_default_value=False, default_value=_b("").decode('utf-8'), 40 | message_type=None, enum_type=None, containing_type=None, 41 | is_extension=False, extension_scope=None, 42 | options=None), 43 | _descriptor.FieldDescriptor( 44 | name='value', full_name='basictracer_go.wire.TracerState.BaggageItemsEntry.value', index=1, 45 | number=2, type=9, cpp_type=9, label=1, 46 | has_default_value=False, default_value=_b("").decode('utf-8'), 47 | message_type=None, enum_type=None, containing_type=None, 48 | is_extension=False, extension_scope=None, 49 | options=None), 50 | ], 51 | extensions=[ 52 | ], 53 | nested_types=[], 54 | enum_types=[ 55 | ], 56 | options=_descriptor._ParseOptions(descriptor_pb2.MessageOptions(), _b('8\001')), 57 | is_extendable=False, 58 | syntax='proto3', 59 | extension_ranges=[], 60 | oneofs=[ 61 | ], 62 | serialized_start=178, 63 | serialized_end=229, 64 | ) 65 | 66 | _TRACERSTATE = _descriptor.Descriptor( 67 | name='TracerState', 68 | full_name='basictracer_go.wire.TracerState', 69 | filename=None, 70 | file=DESCRIPTOR, 71 | containing_type=None, 72 | fields=[ 73 | _descriptor.FieldDescriptor( 74 | name='trace_id', full_name='basictracer_go.wire.TracerState.trace_id', index=0, 75 | number=1, type=6, cpp_type=4, label=1, 76 | has_default_value=False, default_value=0, 77 | message_type=None, enum_type=None, containing_type=None, 78 | is_extension=False, extension_scope=None, 79 | options=None), 80 | _descriptor.FieldDescriptor( 81 | name='span_id', full_name='basictracer_go.wire.TracerState.span_id', index=1, 82 | number=2, type=6, cpp_type=4, label=1, 83 | has_default_value=False, default_value=0, 84 | message_type=None, enum_type=None, containing_type=None, 85 | is_extension=False, extension_scope=None, 86 | options=None), 87 | _descriptor.FieldDescriptor( 88 | name='sampled', full_name='basictracer_go.wire.TracerState.sampled', index=2, 89 | number=3, type=8, cpp_type=7, label=1, 90 | has_default_value=False, default_value=False, 91 | message_type=None, enum_type=None, containing_type=None, 92 | is_extension=False, extension_scope=None, 93 | options=None), 94 | _descriptor.FieldDescriptor( 95 | name='baggage_items', full_name='basictracer_go.wire.TracerState.baggage_items', index=3, 96 | number=4, type=11, cpp_type=10, label=3, 97 | has_default_value=False, default_value=[], 98 | message_type=None, enum_type=None, containing_type=None, 99 | is_extension=False, extension_scope=None, 100 | options=None), 101 | ], 102 | extensions=[ 103 | ], 104 | nested_types=[_TRACERSTATE_BAGGAGEITEMSENTRY, ], 105 | enum_types=[ 106 | ], 107 | options=None, 108 | is_extendable=False, 109 | syntax='proto3', 110 | extension_ranges=[], 111 | oneofs=[ 112 | ], 113 | serialized_start=36, 114 | serialized_end=229, 115 | ) 116 | 117 | _TRACERSTATE_BAGGAGEITEMSENTRY.containing_type = _TRACERSTATE 118 | _TRACERSTATE.fields_by_name['baggage_items'].message_type = _TRACERSTATE_BAGGAGEITEMSENTRY 119 | DESCRIPTOR.message_types_by_name['TracerState'] = _TRACERSTATE 120 | 121 | TracerState = _reflection.GeneratedProtocolMessageType('TracerState', (_message.Message,), dict( 122 | 123 | BaggageItemsEntry = _reflection.GeneratedProtocolMessageType('BaggageItemsEntry', (_message.Message,), dict( 124 | DESCRIPTOR = _TRACERSTATE_BAGGAGEITEMSENTRY, 125 | __module__ = 'wire_pb2' 126 | # @@protoc_insertion_point(class_scope:basictracer_go.wire.TracerState.BaggageItemsEntry) 127 | )) 128 | , 129 | DESCRIPTOR = _TRACERSTATE, 130 | __module__ = 'wire_pb2' 131 | # @@protoc_insertion_point(class_scope:basictracer_go.wire.TracerState) 132 | )) 133 | _sym_db.RegisterMessage(TracerState) 134 | _sym_db.RegisterMessage(TracerState.BaggageItemsEntry) 135 | 136 | 137 | DESCRIPTOR.has_options = True 138 | DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('Z\004wire')) 139 | _TRACERSTATE_BAGGAGEITEMSENTRY.has_options = True 140 | _TRACERSTATE_BAGGAGEITEMSENTRY._options = _descriptor._ParseOptions(descriptor_pb2.MessageOptions(), _b('8\001')) 141 | # @@protoc_insertion_point(module_scope) 142 | -------------------------------------------------------------------------------- /examples/span_logging.py: -------------------------------------------------------------------------------- 1 | """ Example usage of the BasicTracer implementation which log spans to the console. 2 | 3 | Ensure the following pip packages are installed: 4 | 5 | - opentracing 6 | - basictracer 7 | 8 | Run with the command: 9 | 10 | python3 examples/span_logging.py 11 | 12 | Example output: 13 | 14 | [DEBUG ] span_logging.loop.14644595994193200868[1.00 S parent=14464006555861026741 i=0]: message=Sleeping for 1 second 15 | [DEBUG ] span_logging.loop.1520449992154412943[1.01 S parent=14464006555861026741 i=1]: message=Sleeping for 1 second 16 | [DEBUG ] span_logging.loop.15868927260288211418[1.00 S parent=14464006555861026741 i=2]: message=Sleeping for 1 second 17 | [DEBUG ] span_logging.loop.13311248096002911557[1.00 S parent=14464006555861026741 i=3]: message=Sleeping for 1 second 18 | [DEBUG ] span_logging.loop.13408887418100893456[1.00 S parent=14464006555861026741 i=4]: message=Sleeping for 1 second 19 | [DEBUG ] span_logging.loop.2166932256275619626[1.00 S parent=14464006555861026741 i=5]: message=Sleeping for 1 second 20 | [DEBUG ] span_logging.loop.17208766771418783859[1.00 S parent=14464006555861026741 i=6]: message=Sleeping for 1 second 21 | [DEBUG ] span_logging.loop.175072314141445432[1.00 S parent=14464006555861026741 i=7]: message=Sleeping for 1 second 22 | [DEBUG ] span_logging.loop.6741939691448627555[1.00 S parent=14464006555861026741 i=8]: message=Sleeping for 1 second 23 | [DEBUG ] span_logging.loop.8035570631348486191[1.00 S parent=14464006555861026741 i=9]: message=Sleeping for 1 second 24 | [DEBUG ] span_logging.main.14464006555861026741[10.03 S]: finished 25 | """ 26 | 27 | import logging 28 | import sys 29 | import time 30 | 31 | from opentracing import Tracer 32 | from basictracer import BasicTracer 33 | from basictracer.recorder import SpanRecorder 34 | 35 | class LogSpanRecorder(SpanRecorder): 36 | """ Records spans by printing them to a log 37 | Fields: 38 | - logger (Logger): Logger used to display spans 39 | """ 40 | 41 | def __init__(self, logger: logging.Logger): 42 | self.logger = logger 43 | 44 | def record_span(self, span): 45 | bracket_items = [] # Information to put in log tag brackets 46 | 47 | # Time 48 | duration_str = "{0:.2f} S".format(span.duration) 49 | 50 | if span.duration < 0: 51 | duration_str = "{0:.2e} S".format(span.duration) 52 | 53 | bracket_items.append(duration_str) 54 | 55 | # Parent ID 56 | if span.parent_id is not None: 57 | bracket_items.append("parent={}".format(span.parent_id)) 58 | 59 | 60 | # Tags 61 | tags_strs = ["{}={}".format(tag, span.tags[tag]) for tag in span.tags] 62 | bracket_items.extend(tags_strs) 63 | 64 | # Create logger for span 65 | bracket_str = " ".join(bracket_items) 66 | 67 | span_logger = self.logger.getChild("{}.{}[{}]" 68 | .format(span.operation_name, span.context.span_id, 69 | bracket_str)) 70 | 71 | # Print span logs 72 | if len(span.logs) > 0: 73 | for log in span.logs: 74 | log_str = " ".join(["{}={}".format(log_key, log.key_values[log_key]) for log_key in log.key_values]) 75 | 76 | span_logger.debug(log_str) 77 | else: 78 | # If no span logs exist simply print span finished 79 | span_logger.debug("finished") 80 | 81 | def main(): 82 | # Setup BasicTracer to log to console 83 | logger = logging.getLogger('span_logging') 84 | 85 | logger.setLevel(logging.DEBUG) 86 | 87 | hndlr = logging.StreamHandler(sys.stdout) 88 | hndlr.setFormatter(logging.Formatter("[%(levelname)-8s] %(name)s: %(message)s")) 89 | 90 | logger.addHandler(hndlr) 91 | 92 | recorder = LogSpanRecorder(logger) 93 | 94 | tracer = BasicTracer(recorder=recorder) 95 | tracer.register_required_propagators() 96 | 97 | # Use tracer to create spans 98 | span = tracer.start_span(operation_name='main') 99 | 100 | for i in range(10): 101 | child_span = tracer.start_span(operation_name='loop', child_of=span) 102 | child_span.set_tag('i', i) 103 | 104 | child_span.log_kv({'message': "Sleeping for 1 second"}) 105 | 106 | time.sleep(1) 107 | 108 | child_span.finish() 109 | 110 | span.finish() 111 | 112 | if __name__ == '__main__': 113 | main() 114 | -------------------------------------------------------------------------------- /requirements-test.txt: -------------------------------------------------------------------------------- 1 | # add dependencies in setup.py 2 | 3 | -r requirements.txt 4 | 5 | -e .[tests] 6 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # add dependencies in setup.py 2 | 3 | -e . 4 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | description-file = README.md 3 | 4 | [flake8] 5 | max-line-length = 79 6 | max-complexity = 8 7 | exclude = ./docs/ 8 | 9 | [zest.releaser] 10 | release = no 11 | history_file = CHANGELOG.rst 12 | 13 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | setup( 4 | name='basictracer', 5 | version='3.2.1.dev0', 6 | author='The OpenTracing Authors', 7 | author_email='info@opentracing.io', 8 | license='MIT', 9 | url='https://github.com/opentracing/basictracer-python', 10 | keywords=['basictracer', 'opentracing'], 11 | classifiers=[ 12 | 'Development Status :: 3 - Alpha', 13 | 'Intended Audience :: Developers', 14 | 'License :: OSI Approved :: MIT License', 15 | 'Programming Language :: Python :: 2.7', 16 | 'Programming Language :: Python :: 3.5', 17 | 'Programming Language :: Python :: 3.6', 18 | 'Programming Language :: Python :: 3.7', 19 | 'Programming Language :: Python :: Implementation :: PyPy', 20 | 'Topic :: Software Development :: Libraries :: Python Modules', 21 | ], 22 | packages=['basictracer'], 23 | include_package_data=True, 24 | zip_safe=False, 25 | platforms='any', 26 | install_requires=[ 27 | 'protobuf>=3.0.0b2.post2', 28 | 'opentracing>=2.0,<3.0', 29 | 'six>=1.10.0,<2.0', 30 | ], 31 | extras_require={ 32 | 'tests': [ 33 | 'flake8', 34 | 'flake8-quotes', 35 | 'mock<1.1.0', 36 | 'pytest', 37 | 'pytest-cov', 38 | 'pytest-mock', 39 | 'Sphinx', 40 | 'sphinx_rtd_theme' 41 | ] 42 | }, 43 | ) 44 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/opentracing/basictracer-python/b55c192dcfc65d638e1d2c6ae2d5b27747e15ccc/tests/__init__.py -------------------------------------------------------------------------------- /tests/test_api.py: -------------------------------------------------------------------------------- 1 | # Copyright The OpenTracing Authors 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from __future__ import absolute_import 16 | import unittest 17 | from basictracer import BasicTracer 18 | from opentracing.harness.api_check import APICompatibilityCheckMixin 19 | 20 | 21 | class APICheckBasicTracer(unittest.TestCase, APICompatibilityCheckMixin): 22 | def tracer(self): 23 | t = BasicTracer() 24 | t.register_required_propagators() 25 | return t 26 | 27 | def check_baggage_values(self): 28 | return True 29 | 30 | def is_parent(self, parent, span): 31 | # use `Span` ids to check parenting 32 | if parent is None: 33 | return span.parent_id is None 34 | 35 | return parent.context.span_id == span.parent_id 36 | -------------------------------------------------------------------------------- /tests/test_propagation.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from opentracing import ( 3 | Format, 4 | UnsupportedFormatException, 5 | SpanContextCorruptedException, 6 | ) 7 | from basictracer import BasicTracer 8 | 9 | 10 | def test_propagation(): 11 | tracer = BasicTracer() 12 | tracer.register_required_propagators() 13 | sp = tracer.start_span(operation_name='test') 14 | sp.context.sampled = False 15 | sp.set_baggage_item('foo', 'bar') 16 | 17 | # Test invalid types 18 | with pytest.raises(UnsupportedFormatException): 19 | tracer.inject(sp.context, 'invalid', {}) 20 | with pytest.raises(UnsupportedFormatException): 21 | tracer.extract('invalid', {}) 22 | 23 | tests = [(Format.BINARY, bytearray()), 24 | (Format.TEXT_MAP, {})] 25 | for format, carrier in tests: 26 | tracer.inject(sp.context, format, carrier) 27 | extracted_ctx = tracer.extract(format, carrier) 28 | 29 | assert extracted_ctx.trace_id == sp.context.trace_id 30 | assert extracted_ctx.span_id == sp.context.span_id 31 | assert extracted_ctx.sampled == sp.context.sampled 32 | assert extracted_ctx.baggage == sp.context.baggage 33 | 34 | # Test string value of sampled field 35 | headers = {} 36 | tracer.inject(sp.context, Format.HTTP_HEADERS, headers) 37 | headers['ot-tracer-sampled'] = '0' 38 | span_ctx0 = tracer.extract(Format.HTTP_HEADERS, headers) 39 | assert not span_ctx0.sampled 40 | 41 | headers['ot-tracer-sampled'] = '1' 42 | span_ctx1 = tracer.extract(Format.HTTP_HEADERS, headers) 43 | assert span_ctx1.sampled 44 | 45 | 46 | def test_start_span(): 47 | """ Test in process child span creation.""" 48 | tracer = BasicTracer() 49 | tracer.register_required_propagators() 50 | sp = tracer.start_span(operation_name='test') 51 | sp.set_baggage_item('foo', 'bar') 52 | 53 | child = tracer.start_span( 54 | operation_name='child', child_of=sp.context) 55 | assert child.context.trace_id == sp.context.trace_id 56 | assert child.context.sampled == sp.context.sampled 57 | assert child.context.baggage == sp.context.baggage 58 | assert child.parent_id == sp.context.span_id 59 | 60 | 61 | def test_span_missing_all_fields(): 62 | tracer = BasicTracer() 63 | tracer.register_required_propagators() 64 | 65 | # Given an empty carrier 66 | headers = {} 67 | 68 | # When .extract is called 69 | ctx = tracer.extract(Format.TEXT_MAP, headers) 70 | 71 | # Then it should return None 72 | assert ctx is None 73 | 74 | 75 | def test_span_missing_all_headers(): 76 | tracer = BasicTracer() 77 | tracer.register_required_propagators() 78 | 79 | # Given an carrier with no ot-headers 80 | headers = { 81 | 'Content-Type': 'text/html', 82 | 'Authorization': 'Digest 123456', 83 | } 84 | 85 | # When .extract is called 86 | ctx = tracer.extract(Format.TEXT_MAP, headers) 87 | 88 | # Then it should return None 89 | assert ctx is None 90 | 91 | 92 | def test_span_missing_one_field(): 93 | tracer = BasicTracer() 94 | tracer.register_required_propagators() 95 | 96 | # Given a carrier missing ot-tracer-sampled: 97 | headers = { 98 | 'ot-tracer-spanid': 'deadbeaf', 99 | 'ot-tracer-traceid': '1c3b00da', 100 | } 101 | 102 | # When .extract is called 103 | with pytest.raises(SpanContextCorruptedException) as exc: 104 | tracer.extract(Format.TEXT_MAP, headers) 105 | 106 | # Then it should raise SpanContextCorruptedException 107 | assert str(exc.value) == 'expected to parse 3 fields, but parsed 2 instead' 108 | 109 | 110 | def test_span_missing_two_fields(): 111 | tracer = BasicTracer() 112 | tracer.register_required_propagators() 113 | 114 | # Given a carrier with only ot-tracer-traceid: 115 | headers = { 116 | 'ot-tracer-traceid': '1c3b00da', 117 | } 118 | 119 | # When .extract is called 120 | with pytest.raises(SpanContextCorruptedException) as exc: 121 | tracer.extract(Format.TEXT_MAP, headers) 122 | 123 | # Then it should raise SpanContextCorruptedException 124 | assert str(exc.value) == 'expected to parse 3 fields, but parsed 1 instead' 125 | 126 | 127 | def test_span_with_baggage_only(): 128 | tracer = BasicTracer() 129 | tracer.register_required_propagators() 130 | 131 | # Given a carrier with only baggage: 132 | headers = { 133 | 'ot-baggage-example': 'ok', 134 | } 135 | 136 | # When .extract is called 137 | with pytest.raises(SpanContextCorruptedException) as exc: 138 | tracer.extract(Format.TEXT_MAP, headers) 139 | 140 | # Then it should raise SpanContextCorruptedException 141 | assert str(exc.value) == 'found baggage without required fields' 142 | 143 | 144 | def test_span_corrupted_invalid_sampled_value(): 145 | tracer = BasicTracer() 146 | tracer.register_required_propagators() 147 | 148 | # Given a carrier with invalid "ot-tracer-sampled" value 149 | headers = { 150 | 'ot-tracer-spanid': 'deadbeef', 151 | 'ot-tracer-sampled': 'notbool', 152 | 'ot-tracer-traceid': '1c3b00da', 153 | } 154 | 155 | # When .extract is called 156 | with pytest.raises(SpanContextCorruptedException) as exc: 157 | tracer.extract(Format.TEXT_MAP, headers) 158 | 159 | # Then it should raise SpanContextCorruptedException 160 | assert str(exc.value) == ( 161 | "ot-tracer-sampled got an invalid value 'notbool', " 162 | "should be one of 'true', 'false', '0', '1'" 163 | ) 164 | 165 | 166 | def test_span_corrupted_invalid_spanid_value(): 167 | tracer = BasicTracer() 168 | tracer.register_required_propagators() 169 | 170 | # Given a carrier with invalid "ot-tracer-spanid" value 171 | headers = { 172 | 'ot-tracer-spanid': 'nothex', 173 | 'ot-tracer-sampled': 'false', 174 | 'ot-tracer-traceid': '1c3b00da', 175 | } 176 | 177 | # When .extract is called 178 | with pytest.raises(SpanContextCorruptedException) as exc: 179 | tracer.extract(Format.TEXT_MAP, headers) 180 | 181 | # Then it should raise SpanContextCorruptedException 182 | assert str(exc.value) == ( 183 | "ot-tracer-spanid got an invalid hexadecimal value 'nothex'" 184 | ) 185 | 186 | 187 | def test_span_corrupted_invalid_traceid_value(): 188 | tracer = BasicTracer() 189 | tracer.register_required_propagators() 190 | 191 | # Given a carrier with invalid 'ot-tracer-traceid' value 192 | headers = { 193 | 'ot-tracer-traceid': 'nothex', 194 | 'ot-tracer-sampled': 'false', 195 | 'ot-tracer-spanid': '1c3b00da', 196 | } 197 | 198 | # When .extract is called 199 | with pytest.raises(SpanContextCorruptedException) as exc: 200 | tracer.extract(Format.TEXT_MAP, headers) 201 | 202 | # Then it should raise SpanContextCorruptedException 203 | assert str(exc.value) == ( 204 | "ot-tracer-traceid got an invalid hexadecimal value 'nothex'" 205 | ) 206 | -------------------------------------------------------------------------------- /tests/test_span.py: -------------------------------------------------------------------------------- 1 | from basictracer import BasicTracer 2 | from basictracer.recorder import InMemoryRecorder 3 | from opentracing.ext import tags 4 | 5 | 6 | def test_span_sampling_priority(): 7 | recorder = InMemoryRecorder() 8 | tracer = BasicTracer(recorder=recorder) 9 | 10 | span = tracer.start_span('x') 11 | assert span.context.sampled is True 12 | 13 | span.set_tag(tags.SAMPLING_PRIORITY, 0) 14 | assert span.context.sampled is False 15 | 16 | span.finish() 17 | 18 | assert len(recorder.get_spans()) == 1 19 | 20 | def get_sampled_spans(): 21 | return [span for span in recorder.get_spans() if span.context.sampled] 22 | 23 | assert len(get_sampled_spans()) == 0 24 | 25 | 26 | def test_span_log_kv(): 27 | recorder = InMemoryRecorder() 28 | tracer = BasicTracer(recorder=recorder) 29 | 30 | span = tracer.start_span('x') 31 | span.log_kv({ 32 | 'foo': 'bar', 33 | 'baz': 42, 34 | }) 35 | span.finish() 36 | 37 | finished_spans = recorder.get_spans() 38 | assert len(finished_spans) == 1 39 | assert len(finished_spans[0].logs) == 1 40 | assert len(finished_spans[0].logs[0].key_values) == 2 41 | assert finished_spans[0].logs[0].key_values['foo'] == 'bar' 42 | assert finished_spans[0].logs[0].key_values['baz'] == 42 43 | -------------------------------------------------------------------------------- /tests/utils.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2017 The OpenTracing Authors. 2 | # 3 | # Permission is hereby granted, free of charge, to any person obtaining a copy 4 | # of this software and associated documentation files (the "Software"), to deal 5 | # in the Software without restriction, including without limitation the rights 6 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | # copies of the Software, and to permit persons to whom the Software is 8 | # furnished to do so, subject to the following conditions: 9 | # 10 | # The above copyright notice and this permission notice shall be included in 11 | # all copies or substantial portions of the Software. 12 | # 13 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | # THE SOFTWARE. 20 | 21 | from __future__ import absolute_import 22 | 23 | from unittest import TestCase 24 | 25 | from basictracer import BasicTracer 26 | from basictracer.recorder import InMemoryRecorder 27 | 28 | 29 | class TracerTestCase(TestCase): 30 | """Common TestCase to avoid duplication""" 31 | 32 | def setUp(self): 33 | # initialize an in-memory tracer 34 | self.recorder = InMemoryRecorder() 35 | self.tracer = BasicTracer(recorder=self.recorder) 36 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py27,py35,py36,py37 3 | 4 | [testenv] 5 | install_command = pip install {opts} {packages} {env:PWD}[tests] 6 | whitelist_externals = make 7 | commands = make test lint 8 | --------------------------------------------------------------------------------