Skip to content

Add instrumentation for aioredis #569

New issue

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

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

Already on GitHub? # to your account

Draft
wants to merge 16 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -608,6 +608,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- `opentelemetry-instrumentation-httpx` Add `httpx` instrumentation
([#461](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/461))
- `opentelemetry-instrumentation-aioredis` Add `aioredis` instrumentation
([#569](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/569))

## Version 1.3.0/0.22b0 (2021-06-01)

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
graft src
graft tests
global-exclude *.pyc
global-exclude *.pyo
global-exclude __pycache__/*
include CHANGELOG.md
include MANIFEST.in
include README.rst
include LICENSE
24 changes: 24 additions & 0 deletions instrumentation/opentelemetry-instrumentation-aioredis/README.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
OpenTelemetry AioRedis Instrumentation
======================================

|pypi|

.. |pypi| image:: https://badge.fury.io/py/opentelemetry-instrumentation-aioredis.svg
:target: https://pypi.org/project/opentelemetry-instrumentation-aioredis/

This library allows tracing requests made by the aioredis library.

Installation
------------

::

pip install opentelemetry-instrumentation-aioredis


References
----------

* `OpenTelemetry aioredis Instrumentation <https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/opentelemetry-instrumentation-aioredis/opentelemetry-instrumentation-aioredis.html>`_
* `OpenTelemetry Project <https://opentelemetry.io/>`_
* `OpenTelemetry Python Examples <https://github.com/open-telemetry/opentelemetry-python/tree/main/docs/examples>`_
56 changes: 56 additions & 0 deletions instrumentation/opentelemetry-instrumentation-aioredis/setup.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# Copyright The 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-instrumentation-aioredis
description = OpenTelemetry aioredis instrumentation
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-contrib/tree/main/instrumentation/opentelemetry-instrumentation-aioredis
platforms = any
license = Apache-2.0
classifiers =
Development Status :: 4 - Beta
Intended Audience :: Developers
License :: OSI Approved :: Apache Software License
Programming Language :: Python
Programming Language :: Python :: 3
Programming Language :: Python :: 3.6
Programming Language :: Python :: 3.7
Programming Language :: Python :: 3.8

[options]
python_requires = >=3.6
package_dir=
=src
packages=find_namespace:
install_requires =
opentelemetry-api == 1.4.0.dev0
opentelemetry-semantic-conventions == 0.23.dev0
opentelemetry-instrumentation == 0.23.dev0
wrapt >= 1.12.1

[options.extras_require]
test =
opentelemetry-test == 0.23.dev0
opentelemetry-sdk == 1.4.0.dev0

[options.packages.find]
where = src

[options.entry_points]
opentelemetry_instrumentor =
aioredis = opentelemetry.instrumentation.aioredis:AioRedisInstrumentor
99 changes: 99 additions & 0 deletions instrumentation/opentelemetry-instrumentation-aioredis/setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
# Copyright The 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.


# DO NOT EDIT. THIS FILE WAS AUTOGENERATED FROM templates/instrumentation_setup.py.txt.
# RUN `python scripts/generate_setup.py` TO REGENERATE.


import distutils.cmd
import json
import os
from configparser import ConfigParser

import setuptools

config = ConfigParser()
config.read("setup.cfg")

# We provide extras_require parameter to setuptools.setup later which
# overwrites the extra_require section from setup.cfg. To support extra_require
# secion in setup.cfg, we load it here and merge it with the extra_require param.
Copy link

Choose a reason for hiding this comment

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

Suggested change
# secion in setup.cfg, we load it here and merge it with the extra_require param.
# section in setup.cfg, we load it here and merge it with the extra_require param.

extras_require = {}
if "options.extras_require" in config:
for key, value in config["options.extras_require"].items():
extras_require[key] = [v for v in value.split("\n") if v.strip()]

BASE_DIR = os.path.dirname(__file__)
PACKAGE_INFO = {}

VERSION_FILENAME = os.path.join(
BASE_DIR,
"src",
"opentelemetry",
"instrumentation",
"aioredis",
"version.py",
)
with open(VERSION_FILENAME) as f:
exec(f.read(), PACKAGE_INFO)

PACKAGE_FILENAME = os.path.join(
BASE_DIR,
"src",
"opentelemetry",
"instrumentation",
"aioredis",
"package.py",
)
with open(PACKAGE_FILENAME) as f:
exec(f.read(), PACKAGE_INFO)

# Mark any instruments/runtime dependencies as test dependencies as well.
extras_require["instruments"] = PACKAGE_INFO["_instruments"]
test_deps = extras_require.get("test", [])
for dep in extras_require["instruments"]:
test_deps.append(dep)

extras_require["test"] = test_deps


class JSONMetadataCommand(distutils.cmd.Command):

description = (
"print out package metadata as JSON. This is used by OpenTelemetry dev scripts to ",
"auto-generate code in other places",
)
user_options = []

def initialize_options(self):
pass

def finalize_options(self):
pass

def run(self):
metadata = {
"name": config["metadata"]["name"],
"version": PACKAGE_INFO["__version__"],
"instruments": PACKAGE_INFO["_instruments"],
}
print(json.dumps(metadata))


setuptools.setup(
cmdclass={"meta": JSONMetadataCommand},
version=PACKAGE_INFO["__version__"],
extras_require=extras_require,
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
# Copyright The 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.
#
"""
Instrument `aioredis`_ to report Redis queries.

There are two options for instrumenting code. The first option is to use the
``opentelemetry-instrumentation`` executable which will automatically
instrument your Redis client. The second is to programmatically enable
instrumentation via the following code:

.. _aioredis: https://pypi.org/project/aioredis/

Usage
-----

.. code:: python

from opentelemetry.instrumentation.aioredis import AioRedisInstrumentor
import aioredis


# Instrument redis
AioRedisInstrumentor().instrument()

# This will report a span with the default settings
client = redis.StrictRedis(host="localhost", port=6379)
client.get("my-key")

API
---
"""

from typing import Collection

import aioredis
from wrapt import wrap_function_wrapper

from opentelemetry import trace
from opentelemetry.instrumentation.aioredis.package import _instruments
from opentelemetry.instrumentation.aioredis.util import _format_command_args
from opentelemetry.instrumentation.aioredis.version import __version__
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from opentelemetry.instrumentation.utils import unwrap
from opentelemetry.semconv.trace import (
DbSystemValues,
NetTransportValues,
SpanAttributes,
)

_DEFAULT_SERVICE = "redis"


async def traced_execute(func, instance: aioredis.Redis, args, kwargs):
tracer = getattr(aioredis, "_opentelemetry_tracer")
query = _format_command_args(args)
name: str = ""
if len(args) > 0 and args[0]:
name = args[0].decode("utf-8")
else:
name = str(instance.db)
with tracer.start_as_current_span(
name, kind=trace.SpanKind.CLIENT
) as span:
if span.is_recording():
span.set_attributes(
{
SpanAttributes.DB_SYSTEM: DbSystemValues.REDIS.value,
SpanAttributes.DB_STATEMENT: query,
SpanAttributes.DB_NAME: instance.db,
SpanAttributes.DB_REDIS_DATABASE_INDEX: instance.db,
}
)
span.set_attribute("db.redis.args_length", len(args))
if instance.address:
span.set_attributes(
{
SpanAttributes.NET_PEER_NAME: instance.address[0],
SpanAttributes.NET_PEER_PORT: instance.address[1],
SpanAttributes.NET_TRANSPORT: NetTransportValues.IP_TCP.value,
}
)
return await func(*args, **kwargs)


class AioRedisInstrumentor(BaseInstrumentor):
"""An instrumentor for aioredis
See `BaseInstrumentor`
"""

def instrumentation_dependencies(self) -> Collection[str]:
return _instruments

def _instrument(self, **kwargs):
tracer_provider = kwargs.get("tracer_provider")
setattr(
aioredis,
"_opentelemetry_tracer",
trace.get_tracer(
__name__, __version__, tracer_provider=tracer_provider,
),
)
wrap_function_wrapper(aioredis, "Redis.execute", traced_execute)

def _uninstrument(self, **kwargs):
unwrap(aioredis.Redis, "execute")
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Copyright The 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.


_instruments = ("aioredis >= 1.3, < 2.0",)
Loading