Skip to content

Commit

Permalink
Initial commit of middleware capable of sending data to tracer
Browse files Browse the repository at this point in the history
  • Loading branch information
acidjunk committed Apr 3, 2020
1 parent 4a4884d commit a9fe5f6
Show file tree
Hide file tree
Showing 16 changed files with 352 additions and 27 deletions.
134 changes: 134 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
# Created by .ignore support plugin (hsz.mobi)
### Python template
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
.python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

#IDE's
.idea/
24 changes: 24 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
dist: xenial
language: python
python:
- '3.6'
- '3.7'
- '3.8'
- 'pypy'
- 'pypy3.5'

stages:
- lint
- test

matrix:
include:
- stage: lint
name: flake8
python: '3.7'

install:
- pip install tox-travis

script:
- tox
25 changes: 1 addition & 24 deletions LICENSE
Original file line number Diff line number Diff line change
Expand Up @@ -175,27 +175,4 @@

END OF TERMS AND CONDITIONS

APPENDIX: How to apply the Apache License to your work.

To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.

Copyright [yyyy] [name of copyright owner]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

21 changes: 18 additions & 3 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,14 @@
Starlette-OpenTracing
#####################

OpenTracing support for Starlette and FastApi. Looseley inspired on: `python flask`_
OpenTracing support for Starlette and FastApi. Inspired by: `python flask`_

WORK IN PROGRESS. Not ready for production!

OpenTracing implementations exist for major distributed tracing systems and can be bound or swapped with a one-line configuration change.

.. _The OpenTracing Project: http://opentracing.io/
.. _python flask code: https://github.com/opentracing-contrib/python-flask
.. _breaking changes: #breaking-changes-from-0-x
.. _python flask: https://github.com/opentracing-contrib/python-flask

Installation
============
Expand All @@ -24,3 +23,19 @@ Run the following command:
Usage
=====
Todo



Copyright 2020 R. Dohmen <acidjunk@gmail.com>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
1 change: 1 addition & 0 deletions VERSION
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
0.0.1
5 changes: 5 additions & 0 deletions requirements-test.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# add dependencies in setup.py

-r requirements.txt

-e .[tests]
3 changes: 3 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# add dependencies in setup.py

-e .
Empty file added requirements/base.txt
Empty file.
16 changes: 16 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
[aliases]
test=pytest

[metadata]
description-file = README.rst

[tool:pytest]
addopts =
--tb short
-rxs
--cov-report term-missing:skip-covered
--cov flask_opentracing
tests

[coverage:run]
branch = True
53 changes: 53 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
from setuptools import setup

'''
Starlette-OpenTracing
---------------------
This extension provides simple integration of OpenTracing in Starlette applications.
'''
version = open('VERSION').read().strip()
setup(
name='Starlette-OpenTracing',
version=version,
url='http://github.com/acidjunk/starlette-opentracing',
download_url='https://github.com/acidjunk/starlette-opentracing/tarball/'+version,
license='Apache 2.0',
author='René Dohmen',
author_email='acidjunk@gmail.com',
description='OpenTracing support for Starlette and FastApi applications',
long_description=open('README.rst').read(),
long_description_content_type='text/x-rst',
packages=['starlette_opentracing', 'tests'],
zip_safe=False,
include_package_data=True,
platforms='any',
install_requires=[
'starlette',
'opentracing>=2.0,<3',
],
extras_require={
'tests': [
'flake8',
'flake8-quotes',
'mock',
'pytest',
'pytest-cov',
'requests',
],
},
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
3 changes: 3 additions & 0 deletions starlette_opentracing/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from starlette_opentracing.middleware import StarletteTracingMiddleWare

__all__ = ["StarletteTracingMiddleWare"]
32 changes: 32 additions & 0 deletions starlette_opentracing/middleware.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from urllib.parse import urlunparse

import opentracing
from opentracing.ext import tags

#Todo: check iw we can inherit from BaseHTTPMiddleware and/or opentracing.Tracer
# For now we use ASGI interface
class StarletteTracingMiddleWare:
def __init__(self, app):
self.tracer = opentracing.global_tracer()
self.app = app

async def __call__(self, scope, receive, send):
with self.tracer.start_active_span("request") as tracing_scope:
span = tracing_scope.span
span.set_tag(tags.COMPONENT, "asgi")
span.set_tag(tags.SPAN_KIND, tags.SPAN_KIND_RPC_SERVER)
if scope["type"] in {"http", "websocket"}:
span.set_tag(tags.HTTP_METHOD, scope["method"])
host, port = scope["server"]
url = urlunparse(
(
scope["scheme"],
f"{host}:{port}",
scope["path"],
"",
scope["query_string"],
"",
)
)
span.set_tag(tags.HTTP_URL, url)
await self.app(scope, receive, send)
Empty file added tests/__init__.py
Empty file.
33 changes: 33 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import pytest

from starlette.applications import Starlette
from starlette.responses import PlainTextResponse
from starlette.testclient import TestClient

from starlette_opentracing import StarletteTracingMiddleWare


# Todo: scope might be bigger
@pytest.fixture()
def app():
app_ = Starlette()
app_.add_middleware(StarletteTracingMiddleWare)

@app_.route("/foo/")
def foo(request):
return PlainTextResponse("Foo")

@app_.route("/bar/")
def bar(request):
raise ValueError("bar")

@app_.route("/foo/{bar}/")
def foobar(request):
return PlainTextResponse(f"Foo: {request.path_params['bar']}")

return app_


@pytest.fixture
def client(app):
return TestClient(app)
5 changes: 5 additions & 0 deletions tests/test_starlette_tracing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@

def test_view_ok(client):
# Do a request
response = client.get("/foo/")

Loading

0 comments on commit a9fe5f6

Please sign in to comment.