Skip to content

Commit

Permalink
Add opentracing shim example
Browse files Browse the repository at this point in the history
  • Loading branch information
c24t authored and ocelotl committed Dec 20, 2019
1 parent 8fa21e6 commit c3e965d
Show file tree
Hide file tree
Showing 7 changed files with 192 additions and 0 deletions.
82 changes: 82 additions & 0 deletions examples/opentracing/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
# Overview

This example shows how to use the [`opentelemetry-ext-opentracing-shim`
package](https://github.com/open-telemetry/opentelemetry-python/tree/master/ext/opentelemetry-ext-opentracing-shim)
to interact with libraries instrumented with
[`opentracing-python`](https://github.com/opentracing/opentracing-python).

The included `rediscache` library creates spans via the OpenTelemetry Redis
integration,
[`redis_opentracing`](https://github.com/opentracing-contrib/python-redis).
Spans are exported via the Jaeger exporter, which is attached to the
OpenTelemetry tracer.

## Installation

### Jaeger

Install and run
[Jaeger](https://www.jaegertracing.io/docs/latest/getting-started/#all-in-one).
See the [basic tracer
example](https://github.com/open-telemetry/opentelemetry-python/tree/master/examples/basic-tracer)
for more detail.

### Redis

Install Redis following the [instructions](https://redis.io/topics/quickstart).

### Python Dependencies

Install the Python dependencies in [`requirements.txt`](requirements.txt):

```sh
$ pip install -r requirements.txt
```

Alternatively, you can install the Python dependencies separately:

```sh
$ pip install \
opentelemetry-api \
opentelemetry-opentracing-shim \
redis \
redis_opentracing
```

## Run the Application

The example script calculates a few Fibonacci numbers and stores the results in
Redis. The script, the `rediscache` library, and the OpenTracing Redis
integration all contribute spans to the trace.

To run the script:

```sh
$ python main.py
```

After running, you can view the generated trace in the Jaeger UI.

#### Jaeger UI

Open the Jaeger UI in your browser at
[http://localhost:16686](http://localhost:16686) and view traces for the
"OpenTracing Shim Example" service.

Each `main.py` run should generate a trace, and each trace should include
multiple spans that represent calls to Redis.

<p align="center"><img src="images/jaeger-trace-full.png?raw=true"/></p>

Note that tags and logs (OpenTracing) and attributes and events (OpenTelemetry)
from both tracing systems appear in the exported trace.

<p align="center"><img src="./images/jaeger-span-expanded.png?raw=true"/></p>

## Useful links
- For more information on OpenTelemetry, visit: <https://opentelemetry.io/>
- For more information on tracing in Python, visit: <https://github.com/open-telemetry/opentelemetry-python>

## LICENSE

Apache License 2.0
Empty file.
Binary file added examples/opentracing/jaeger-span-expanded.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added examples/opentracing/jaeger-trace-full.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
47 changes: 47 additions & 0 deletions examples/opentracing/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
#!/usr/bin/env python

from opentelemetry import trace as trace_api
from opentelemetry.ext import opentracing_shim
from opentelemetry.ext.jaeger import JaegerSpanExporter
from opentelemetry.sdk.trace import Tracer
from opentelemetry.sdk.trace.export import BatchExportSpanProcessor
from rediscache import RedisCache

# Configure the tracer using the default implementation
trace_api.set_preferred_tracer_implementation(lambda T: Tracer())
tracer = trace_api.tracer()

# Configure the tracer to export traces to Jaeger
jaeger_exporter = JaegerSpanExporter(
service_name="OpenTracing Shim Example",
agent_host_name="localhost",
agent_port=6831,
)
span_processor = BatchExportSpanProcessor(jaeger_exporter)
tracer.add_span_processor(span_processor)

# Create an OpenTracing shim. This implements the OpenTracing tracer API, but
# forwards calls to the underlying OpenTelemetry tracer.
opentracing_tracer = opentracing_shim.create_tracer(tracer)

# Our example caching library expects an OpenTracing-compliant tracer.
redis_cache = RedisCache(opentracing_tracer)


@redis_cache
def fib(n):
"""Get the Nth Fibonacci number, cache intermediate results in Redis."""
if n < 0:
raise ValueError
if n == 0 or n == 1:
return 1
return fib(n - 1) + fib(n - 2)


with tracer.start_as_current_span("Fibonacci") as span:
span.set_attribute("is_example", "yes :)")
fib(4)


# Export the remaining span before exiting
span_processor.shutdown()
59 changes: 59 additions & 0 deletions examples/opentracing/rediscache.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
"""
This is an example of a library written to work with opentracing-python. It
provides a simple caching decorator backed by Redis, and uses the OpenTracing
Redis integartion to automatically generate spans for each call to Redis.
"""

import json
import pickle
from functools import wraps

import redis
import redis_opentracing


class RedisCache:
"""Redis-backed caching decorator, using OpenTracing!
Args:
tracer: an opentracing.tracer.Tracer
"""

def __init__(self, tracer):
redis_opentracing.init_tracing(tracer)
self.tracer = tracer
self.client = redis.StrictRedis()

def __call__(self, func):
@wraps(func)
def inner(*args, **kwargs):
with self.tracer.start_active_span("Caching decorator") as scope1:

# Pickle the call args to get a canonical key. Don't do this in
# prod!
key = pickle.dumps((func.__qualname__, args, kwargs))

pval = self.client.get(key)
if pval is not None:
val = pickle.loads(pval)
scope1.span.log_kv(
{"msg": "Found cached value", "val": val}
)
return val

scope1.span.log_kv({"msg": "Cache miss, calling function"})
with self.tracer.start_active_span(
'Call "{}"'.format(func.__name__)
) as scope2:
scope2.span.set_tag("func", func.__name__)
scope2.span.set_tag("args", str(args))
scope2.span.set_tag("kwargs", str(kwargs))

val = func(*args, **kwargs)
scope2.span.set_tag("val", str(val))

# Let keys expire after 10 seconds
self.client.setex(key, 10, pickle.dumps(val))
return val

return inner
4 changes: 4 additions & 0 deletions examples/opentracing/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
opentelemetry-api
opentelemetry-opentracing-shim
redis
redis_opentracing

0 comments on commit c3e965d

Please sign in to comment.