Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding pymongo integration #232

Merged
merged 27 commits into from
Nov 7, 2019
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
b837c9f
Span add override parameters
hectorhdzg Sep 26, 2019
a12fe5d
Make lint happy
hectorhdzg Sep 26, 2019
276ecb4
Addressing comments
hectorhdzg Sep 27, 2019
2b90351
Addressing comments
hectorhdzg Sep 27, 2019
eccef1a
Allowing 0 as start and end time
hectorhdzg Sep 28, 2019
a187fec
Fix lint issues
hectorhdzg Sep 28, 2019
a43c980
Merge remote-tracking branch 'upstream/master'
hectorhdzg Oct 2, 2019
8dfb44e
Merge remote-tracking branch 'upstream/master'
hectorhdzg Oct 8, 2019
77d3649
Add code coverage
hectorhdzg Oct 8, 2019
f3af20f
Revert latest commit
hectorhdzg Oct 9, 2019
cf3a605
Merge branch 'master' of https://github.com/open-telemetry/openteleme…
hectorhdzg Oct 17, 2019
0670790
Initial commit
hectorhdzg Oct 17, 2019
dbe5c6a
Initial version
hectorhdzg Oct 21, 2019
fbeb356
Merging with latest upstream
hectorhdzg Oct 21, 2019
4db5db6
Lint fix
hectorhdzg Oct 22, 2019
5783c16
Remove with to avoid span to be closed
hectorhdzg Oct 22, 2019
bf6ec3b
Addressing comments
hectorhdzg Oct 22, 2019
17dcda7
Reformat using black
hectorhdzg Oct 22, 2019
40f2abd
Fixing lint issues
hectorhdzg Oct 22, 2019
3595748
Adding try/except and removing peer.address
hectorhdzg Oct 23, 2019
77425b7
Merge branch 'master' of https://github.com/hectorhdzg/opentelemetry-…
hectorhdzg Oct 25, 2019
3f602d9
Adding reference for current span to
hectorhdzg Oct 25, 2019
a858564
Merge branch 'master' into master
hectorhdzg Oct 25, 2019
ee8adf2
Addressing comments
hectorhdzg Oct 30, 2019
2b23370
Addressing comments
hectorhdzg Oct 31, 2019
2af10a1
Merge branch 'master' into master
hectorhdzg Nov 7, 2019
f2c344e
s/0.1.dev0/0.3.dev0/
c24t Nov 7, 2019
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions ext/opentelemetry-ext-pymongo/README.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
OpenTelemetry pymongo integration
=================================

The integration with MongoDB supports the `pymongo`_ library and is specified
to ``trace_integration`` using ``'pymongo'``.

.. _pymongo: https://pypi.org/project/pymongo

Usage
-----

.. code:: python

from pymongo import MongoClient
from opentelemetry.trace import tracer
from opentelemetry.trace.ext.pymongo import trace_integration

trace_integration(tracer())
client = MongoClient()
db = client["MongoDB_Database"]
collection = db["MongoDB_Collection"]
collection.find_one()

References
----------

* `OpenTelemetry Project <https://opentelemetry.io/>`_
46 changes: 46 additions & 0 deletions ext/opentelemetry-ext-pymongo/setup.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Copyright 2019, OpenTelemetry Authors
#
# 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.
#
[metadata]
name = opentelemetry-ext-pymongo
description = OpenTelemetry pymongo integration
long_description = file: README.rst
long_description_content_type = text/x-rst
author = OpenTelemetry Authors
author_email = cncf-opentelemetry-contributors@lists.cncf.io
url = https://github.com/open-telemetry/opentelemetry-python/ext/opentelemetry-ext-pymongo
platforms = any
license = Apache-2.0
classifiers =
Development Status :: 3 - Alpha
Intended Audience :: Developers
License :: OSI Approved :: Apache Software License
Programming Language :: Python
Programming Language :: Python :: 3
Programming Language :: Python :: 3.4
Programming Language :: Python :: 3.5
Programming Language :: Python :: 3.6
Programming Language :: Python :: 3.7

[options]
python_requires = >=3.4
package_dir=
=src
packages=find_namespace:
install_requires =
opentelemetry-api >= 0.1.dev0
c24t marked this conversation as resolved.
Show resolved Hide resolved
pymongo ~= 3.1

[options.packages.find]
where = src
26 changes: 26 additions & 0 deletions ext/opentelemetry-ext-pymongo/setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Copyright 2019, OpenTelemetry Authors
#
# 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.
import os

import setuptools

BASE_DIR = os.path.dirname(__file__)
VERSION_FILENAME = os.path.join(
BASE_DIR, "src", "opentelemetry", "ext", "pymongo", "version.py"
)
PACKAGE_INFO = {}
with open(VERSION_FILENAME) as f:
exec(f.read(), PACKAGE_INFO)

setuptools.setup(version=PACKAGE_INFO["__version__"])
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
# Copyright 2019, OpenTelemetry Authors
#
# 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.

"""
The opentelemetry-ext-pymongo package allows tracing commands made by the
pymongo library.
"""

from pymongo import monitoring

from opentelemetry.trace import SpanKind
from opentelemetry.trace.status import Status, StatusCanonicalCode

DATABASE_TYPE = "mongodb"
COMMAND_ATTRIBUTES = ["filter", "sort", "skip", "limit", "pipeline"]


def trace_integration(tracer=None):
"""Integrate with pymongo to trace it using event listener.
https://api.mongodb.com/python/current/api/pymongo/monitoring.html
"""

monitoring.register(CommandTracer(tracer))
Oberon00 marked this conversation as resolved.
Show resolved Hide resolved


class CommandTracer(monitoring.CommandListener):
def __init__(self, tracer):
self._tracer = tracer
hectorhdzg marked this conversation as resolved.
Show resolved Hide resolved

def started(self, event: monitoring.CommandStartedEvent):
command = event.command.get(event.command_name)
hectorhdzg marked this conversation as resolved.
Show resolved Hide resolved
if command is None:
command = ""
name = DATABASE_TYPE + "." + event.command_name + "." + command
hectorhdzg marked this conversation as resolved.
Show resolved Hide resolved
try:
span = self._tracer.start_span(name, kind=SpanKind.CLIENT)
span.set_attribute("component", DATABASE_TYPE)
span.set_attribute("db.type", DATABASE_TYPE)
span.set_attribute("db.instance", event.database_name)
span.set_attribute(
"db.statement", event.command_name + " " + command
hectorhdzg marked this conversation as resolved.
Show resolved Hide resolved
)
if event.connection_id is not None:
span.set_attribute("peer.hostname", event.connection_id[0])
span.set_attribute("peer.port", event.connection_id[1])

# pymongo specific, not specified by spec
span.set_attribute("db.mongo.operation_id", event.operation_id)
span.set_attribute("db.mongo.request_id", event.request_id)

for attr in COMMAND_ATTRIBUTES:
_attr = event.command.get(attr)
if _attr is not None:
span.set_attribute("db.mongo." + attr, str(_attr))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On using str: Shouldn't e.g. limit be an integer?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

string casting is more important for other fields, dictionaries and lists are also part of COMMAND_ATTRIBUTES, I can add specific checks for limit and skip(both int) if the type is important here

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think at this point, it would be simpler to take "limit" out of COMMAND_ATTRIBUTES and query it separately.

except Exception as ex: # noqa pylint: disable=broad-except
if span is not None:
span.set_status(Status(StatusCanonicalCode.INTERNAL, ex))
hectorhdzg marked this conversation as resolved.
Show resolved Hide resolved
span.end()

def succeeded(self, event: monitoring.CommandSucceededEvent):
span = self._tracer.get_current_span()
hectorhdzg marked this conversation as resolved.
Show resolved Hide resolved
span.set_attribute("db.mongo.duration_micros", event.duration_micros)
span.set_status(Status(StatusCanonicalCode.OK, event.reply))
span.end()
hectorhdzg marked this conversation as resolved.
Show resolved Hide resolved

def failed(self, event: monitoring.CommandFailedEvent):
span = self._tracer.get_current_span()
span.set_attribute("db.mongo.duration_micros", event.duration_micros)
span.set_status(Status(StatusCanonicalCode.UNKNOWN, event.failure))
span.end()
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Copyright 2019, OpenTelemetry Authors
#
# 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.

__version__ = "0.1.dev0"
c24t marked this conversation as resolved.
Show resolved Hide resolved
Empty file.
147 changes: 147 additions & 0 deletions ext/opentelemetry-ext-pymongo/tests/test_pymongo_integration.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
# Copyright 2019, OpenTelemetry Authors
#
# 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.

import unittest
from unittest import mock

from opentelemetry import trace as trace_api
from opentelemetry.ext.pymongo import CommandTracer, trace_integration
from opentelemetry.util import time_ns


class TestPymongoIntegration(unittest.TestCase):
def test_trace_integration(self):
mock_register = mock.Mock()
patch = mock.patch(
"pymongo.monitoring.register", side_effect=mock_register
)
with patch:
trace_integration()

self.assertTrue(mock_register.called)

def test_started(self):
command_attrs = {
"filter": "filter",
"sort": "sort",
"limit": "limit",
"pipeline": "pipeline",
"command_name": "find",
}
mock_tracer = MockTracer()
CommandTracer(mock_tracer).started(
event=MockEvent(command_attrs, ("test.com", "1234"))
)
span = mock_tracer.get_current_span()
self.assertIs(span.kind, trace_api.SpanKind.CLIENT)
self.assertEqual(span.name, "mongodb.command_name.find")
self.assertEqual(span.attributes["component"], "mongodb")
self.assertEqual(span.attributes["db.type"], "mongodb")
self.assertEqual(span.attributes["db.instance"], "database_name")
self.assertEqual(span.attributes["db.statement"], "command_name find")
self.assertEqual(span.attributes["peer.hostname"], "test.com")
self.assertEqual(span.attributes["peer.port"], "1234")
self.assertEqual(
span.attributes["db.mongo.operation_id"], "operation_id"
)
self.assertEqual(span.attributes["db.mongo.request_id"], "request_id")

self.assertEqual(span.attributes["db.mongo.filter"], "filter")
self.assertEqual(span.attributes["db.mongo.sort"], "sort")
self.assertEqual(span.attributes["db.mongo.limit"], "limit")
self.assertEqual(span.attributes["db.mongo.pipeline"], "pipeline")

def test_succeeded(self):
mock_tracer = MockTracer()
CommandTracer(mock_tracer).succeeded(event=MockEvent(None))
span = mock_tracer.get_current_span()
self.assertEqual(
span.attributes["db.mongo.duration_micros"], "duration_micros"
)
self.assertIs(
span.status.canonical_code, trace_api.status.StatusCanonicalCode.OK
)
self.assertEqual(span.status.description, "reply")
self.assertIsNotNone(span.end_time)

def test_failed(self):
mock_tracer = MockTracer()
CommandTracer(mock_tracer).failed(event=MockEvent(None))
span = mock_tracer.get_current_span()
self.assertEqual(
span.attributes["db.mongo.duration_micros"], "duration_micros"
)
self.assertIs(
span.status.canonical_code,
trace_api.status.StatusCanonicalCode.UNKNOWN,
)
self.assertEqual(span.status.description, "failure")
self.assertIsNotNone(span.end_time)


class MockCommand:
def __init__(self, command_attrs):
self.command_attrs = command_attrs

def get(self, key):
return self.command_attrs.get(key)


class MockEvent:
def __init__(self, command_attrs, connection_id=""):
self.command = MockCommand(command_attrs)
self.connection_id = connection_id

def __getattr__(self, item):
return item


class MockSpan:
def __enter__(self):
return self

def __exit__(self, exc_type, exc_val, exc_tb):
return False

def __init__(self):
self.status = None
self.name = ""
self.kind = trace_api.SpanKind.INTERNAL
self.attributes = None
self.end_time = None

def set_attribute(self, key, value):
self.attributes[key] = value

def set_status(self, status):
self.status = status

def end(self, end_time=None):
self.end_time = end_time if end_time is not None else time_ns()


class MockTracer:
def __init__(self):
self.span = MockSpan()
self.end_span = mock.Mock()
self.span.attributes = {}
self.span.status = None

def start_span(self, name, kind):
self.span.name = name
self.span.kind = kind
return self.span

def get_current_span(self):
return self.span
5 changes: 5 additions & 0 deletions tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ changedir =
test-sdk: opentelemetry-sdk/tests
test-ext-http-requests: ext/opentelemetry-ext-http-requests/tests
test-ext-jaeger: ext/opentelemetry-ext-jaeger/tests
test-ext-pymongo: ext/opentelemetry-ext-pymongo/tests
hectorhdzg marked this conversation as resolved.
Show resolved Hide resolved
test-ext-wsgi: ext/opentelemetry-ext-wsgi/tests
test-example-app: examples/opentelemetry-example-app/tests

Expand All @@ -38,6 +39,7 @@ commands_pre =
example-app: pip install {toxinidir}/examples/opentelemetry-example-app
ext: pip install {toxinidir}/opentelemetry-api
wsgi: pip install {toxinidir}/ext/opentelemetry-ext-wsgi
pymongo: pip install {toxinidir}/ext/opentelemetry-ext-pymongo
http-requests: pip install {toxinidir}/ext/opentelemetry-ext-http-requests
jaeger: pip install {toxinidir}/opentelemetry-sdk
jaeger: pip install {toxinidir}/ext/opentelemetry-ext-jaeger
Expand Down Expand Up @@ -72,6 +74,7 @@ commands_pre =
pip install -e {toxinidir}/ext/opentelemetry-ext-azure-monitor
pip install -e {toxinidir}/ext/opentelemetry-ext-http-requests
pip install -e {toxinidir}/ext/opentelemetry-ext-jaeger
pip install -e {toxinidir}/ext/opentelemetry-ext-pymongo
pip install -e {toxinidir}/ext/opentelemetry-ext-wsgi
pip install -e {toxinidir}/examples/opentelemetry-example-app

Expand All @@ -90,6 +93,8 @@ commands =
ext/opentelemetry-ext-http-requests/tests/ \
ext/opentelemetry-ext-jaeger/src/opentelemetry \
ext/opentelemetry-ext-jaeger/tests/ \
ext/opentelemetry-ext-pymongo/src/opentelemetry \
ext/opentelemetry-ext-pymongo/tests/ \
ext/opentelemetry-ext-wsgi/tests/ \
examples/opentelemetry-example-app/src/opentelemetry_example_app/ \
examples/opentelemetry-example-app/tests/
Expand Down