Skip to content

Commit

Permalink
chore(examples/docs): Updating Otel Examples/Recipes (#3967)
Browse files Browse the repository at this point in the history
* chore(examples/docs): Updating Otel Examples/Recipes

* chore(examples/docs): Updating Otel Examples/Recipes

* updating nodejs manual instrumentation

* updating python example

* updating recipes
  • Loading branch information
xoscar authored Aug 15, 2024
1 parent 2e10f27 commit b8ae439
Show file tree
Hide file tree
Showing 38 changed files with 377 additions and 1,438 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,6 @@ keywords:
image: https://res.cloudinary.com/djwdcmwdz/image/upload/v1698686403/docs/Blog_Thumbnail_14_rsvkmo.jpg
---

import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
import CodeBlock from '@theme/CodeBlock';

:::note
[Check out the source code on GitHub here.](https://github.com/kubeshop/tracetest/tree/main/examples/quick-start-python)
:::
Expand All @@ -31,19 +27,12 @@ import CodeBlock from '@theme/CodeBlock';

This is a simple quick start on how to configure a Python app to use OpenTelemetry instrumentation with traces, and Tracetest for enhancing your e2e and integration tests with trace-based testing.

```mdx-code-block
<Tabs groupId="running-tracetest-without-a-trace-data-store">
<TabItem value="Tracetest" label="Cloud-based Managed Tracetest" default>
```

## Prerequisites

**Tracetest Account**:

- Sign up to [`app.tracetest.io`](https://app.tracetest.io) or follow the [get started](/getting-started/installation) docs.
- Create an [environment](/concepts/environments).
- Create an [environment token](/concepts/environment-tokens).
- Have access to the environment's [agent API key](/configuration/agent).
- Have access to the environment's [agent API key](https://app.tracetest.io/retrieve-token).

**Docker**: Have [Docker](https://docs.docker.com/get-docker/) and [Docker Compose](https://docs.docker.com/compose/install/) installed on your machine.

Expand All @@ -61,11 +50,9 @@ cd tracetest/examples/quick-start-python
Follow these instructions to run the quick start:

1. Copy the `.env.template` file to `.env`.
2. Log into the [Tracetest app](https://app.tracetest.io/).
3. This example is configured to use the OpenTelemetry Tracing Backend. Ensure the environment you will be utilizing to run this example is also configured to use the OpenTelemetry Tracing Backend by clicking on Settings, Tracing Backend, OpenTelemetry, Save.
4. Fill out the [token](https://docs.tracetest.io/concepts/environment-tokens) and [API key](https://docs.tracetest.io/concepts/agent) details by editing your `.env` file. You can find these values in the Settings area for your environment.
5. Run `docker compose up -d`.
6. Run tests from the Tracetest Web UI by accessing the app with the URL `http://app:8080/`.
2. Fill out the [TRACETEST_TOKEN and ENVIRONMENT_ID](https://app.tracetest.io/retrieve-token) details by editing your `.env` file.
3. Run `docker compose run tracetest-run`.
4. Follow the links in the output to view the test results.

Follow along with the sections below for a detailed breakdown of what the example you just ran did and how it works.

Expand All @@ -82,8 +69,15 @@ The Python app is a simple Flask app, contained in the `app.py` file.
Configure the `.env` like shown below.

```bash
# Get the required information here: https://app.tracetest.io/retrieve-token

TRACETEST_TOKEN="<YOUR_TRACETEST_TOKEN>"
TRACETEST_ENVIRONMENT_ID="<YOUR_ENV_ID>"

# GRPC
OTEL_EXPORTER_OTLP_TRACES_ENDPOINT="http://tracetest-agent:4317/"
TRACETEST_API_KEY="<YOUR_TRACETEST_API_KEY>"
# or, use HTTP
# OTEL_EXPORTER_OTLP_TRACES_ENDPOINT="http://tracetest-agent:4318/v1/traces"
```

The OpenTelemetry tracing is contained both as automatic and manual instrumentation. Traces will be sent to the Tracetest Agent. Here's the `requirements.txt` with OpenTelemetry libraries.
Expand All @@ -107,7 +101,6 @@ EXPOSE 8080

The `docker-compose.yaml` contains just one service for the Python app. The service is started with the `command` parameter.


```yaml title="docker-compose.yaml"
command: opentelemetry-instrument --traces_exporter otlp --service_name app --exporter_otlp_endpoint ${OTEL_EXPORTER_OTLP_TRACES_ENDPOINT} --exporter_otlp_insecure true flask run --host=0.0.0.0 --port=8080
```
Expand Down Expand Up @@ -139,16 +132,16 @@ To start the full setup, run the following command:
docker compose up -d
```

There are 3 endpoints in the Flask app. To see manual instrumentation, trigger the `"/manual"` endpoint. To see the automatic instrumentation, trigger the `"/automatic"` endpoint respectively.
There are 3 endpoints in the Flask app. To see manual instrumentation, trigger the `"/manual"` endpoint. To see the automatic instrumentation, trigger the `"/automatic"` endpoint respectively.

```python
app = Flask(__name__)
@app.route("/manual")
def manual():
with tracer.start_as_current_span(
"manual",
attributes={ "endpoint": "/manual", "foo": "bar" }
"manual",
attributes={ "endpoint": "/manual", "foo": "bar" }
):
return "App works with a manual instrumentation."
Expand All @@ -163,277 +156,32 @@ def home():

## Run Tracetest Tests

1. Open [Tracetest](https://app.tracetest.io/)
2. Start creating tests! Make sure to use the `http://app:8080/automatic` or `http://app:8080/manual` URLs in your test creation.
3. To trigger tests in the CLI, first [install the CLI](/cli/cli-installation-reference), [configure it](/cli/configuring-your-cli), and [run a test](/cli/running-tests). From the root of the quick start directory, run:
To execute the tests, run this command:

```bash
tracetest configure -t <YOUR_API_TOKEN>
tracetest run test -f ./test-api.yaml
docker compose run tracetest-run
```

This will:
1. Start the Node.js app, the OpenTelemetry Collector, and send the traces to the Tracetest Agent.
2. Start the Tracetest Agent.
3. Configure the tracing backend and create tests in your environment.
4. Run the tests.

Here's a sample of a failed test run, which happens if you use this selector and assertion pair.

Selector:

```
span[tracetest.span.type="http" name="/automatic" http.target="/automatic" http.method="GET"]
```

Assertion:

```
attr:http.status_code = 200
```

![assertion](https://res.cloudinary.com/djwdcmwdz/image/upload/v1715620289/docs/app.tracetest.io_organizations_ttorg_e66318ba6544b856_environments_ttenv_8fca16a31b8b6e24_tests_ayy2cq.png)

```mdx-code-block
</TabItem>
<TabItem value="Tracetest Core" label="Hobby Open-Source Tracetest Core">
```

## Prerequisites

You will need [Docker](https://docs.docker.com/get-docker/) and [Docker Compose](https://docs.docker.com/compose/install/) installed on your machine to run this quick start app!

## Project structure

The project is built with Docker Compose. It contains two distinct `docker-compose.yaml` files.

### 1. Python app

The `docker-compose.yaml` file and `Dockerfile` in the root directory are for the Python app.

### 2. Tracetest

The `docker-compose.yaml` file, `collector.config.yaml`, `tracetest-provision.yaml`, and `tracetest-config.yaml` in the `tracetest` directory are for setting up Tracetest and the OpenTelemetry Collector.

The `tracetest` directory is self-contained and will run all the prerequisites for enabling OpenTelemetry traces and trace-based testing with Tracetest.

### Docker Compose Network

All `services` in the `docker-compose.yaml` are on the same network and will be reachable by hostname from within other services. E.g. `tracetest:4317` in the `collector.config.yaml` will map to the `tracetest` service, where the port `4317` is the port where Tracetest accepts traces.

## Python app

The Python app is a simple Flask app, contained in the `app.py` file.

The code below imports all the Flask, and OpenTelemetry libraries and configures both manual and automatic OpenTelemetry instrumentation.

```python
from flask import Flask, request
import json
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.sdk.trace.export import ConsoleSpanExporter
provider = TracerProvider()
processor = BatchSpanProcessor(ConsoleSpanExporter())
provider.add_span_processor(processor)
trace.set_tracer_provider(provider)
tracer = trace.get_tracer(__name__)
```

There are 3 endpoints in the Flask app. For seeing manual instrumentation trigger the `"/manual"` endpoint. For seeing the automatic instrumentation trigger the `"/automatic"` endpoint respectively.

```python
app = Flask(__name__)
@app.route("/manual")
def manual():
with tracer.start_as_current_span(
"manual",
attributes={ "endpoint": "/manual", "foo": "bar" }
):
return "App works with a manual instrumentation."
@app.route('/automatic')
def automatic():
return "App works with automatic instrumentation."
@app.route("/")
def home():
return "App works."
```

The `Dockerfile` includes bootstrapping the needed OpenTelemetry packages. As you can see it does not have the `CMD` command. Instead, it's configured in the `docker-compose.yaml` below.

```Dockerfile
FROM python:3.10.1-slim
WORKDIR /opt/app
COPY . .
RUN pip install --no-cache-dir -r requirements.txt
RUN opentelemetry-bootstrap -a install
EXPOSE 8080
```

The `docker-compose.yaml` contains just one service for the Python app. The service is stared with the `command` parameter.

```yaml
version: '3'
services:
app:
image: quick-start-python
platform: linux/amd64
extra_hosts:
- "host.docker.internal:host-gateway"
build: .
ports:
- "8080:8080"
# using the command here instead of the Dockerfile
command: opentelemetry-instrument --traces_exporter otlp --service_name app --exporter_otlp_endpoint otel-collector:4317 --exporter_otlp_insecure true flask run --host=0.0.0.0 --port=8080
depends_on:
tracetest:
condition: service_started
```

To start it, run this command:

```bash
docker compose build # optional if you haven't already built the image
docker compose up
```

This will start the Python app. But, you're not sending the traces anywhere.

Let's fix this by configuring Tracetest and OpenTelemetry Collector.

## Tracetest

The `docker-compose.yaml` in the `tracetest` directory is configured with three services.

- **Postgres** - Postgres is a prerequisite for Tracetest to work. It stores trace data when running the trace-based tests.
- [**OpenTelemetry Collector**](https://opentelemetry.io/docs/collector/) - A vendor-agnostic implementation of how to receive, process and export telemetry data.
- [**Tracetest**](https://tracetest.io/) - Trace-based testing that generates end-to-end tests automatically from traces.

```yaml
version: "3"
services:
tracetest:
image: kubeshop/tracetest:latest
platform: linux/amd64
volumes:
- type: bind
source: ./tracetest/tracetest-config.yaml
target: /app/tracetest.yaml
- type: bind
source: ./tracetest/tracetest-provision.yaml
target: /app/provisioning.yaml
ports:
- 11633:11633
command: --provisioning-file /app/provisioning.yaml
depends_on:
postgres:
condition: service_healthy
otel-collector:
condition: service_started
healthcheck:
test: ["CMD", "wget", "--spider", "localhost:11633"]
interval: 1s
timeout: 3s
retries: 60
environment:
TRACETEST_DEV: ${TRACETEST_DEV}
postgres:
image: postgres:14
environment:
POSTGRES_PASSWORD: postgres
POSTGRES_USER: postgres
healthcheck:
test: pg_isready -U "$$POSTGRES_USER" -d "$$POSTGRES_DB"
interval: 1s
timeout: 5s
retries: 60
otel-collector:
image: otel/opentelemetry-collector-contrib:0.59.0
command:
- "--config"
- "/otel-local-config.yaml"
volumes:
- ./tracetest/collector.config.yaml:/otel-local-config.yaml
```

Tracetest depends on both Postgres and the OpenTelemetry Collector. Both Tracetest and the OpenTelemetry Collector require config files to be loaded via a volume. The volumes are mapped from the root directory into the `tracetest` directory and the respective config files.

The `tracetest-config.yaml` file contains the basic setup of connecting Tracetest to the Postgres instance.

```yaml
postgres:
host: postgres
user: postgres
password: postgres
port: 5432
dbname: postgres
params: sslmode=disable
```

The `tracetest-provision.yaml` file provisions the trace data store and polling to store in the Postgres database. The data store is set to OTLP meaning the traces will be stored in Tracetest itself.

```yaml
---
type: DataStore
spec:
name: OpenTelemetry Collector
type: otlp
isdefault: true
```

But how are traces sent to Tracetest?

The `collector.config.yaml` explains that. It receives traces via either `grpc` or `http`. Then, exports them to Tracetest's otlp endpoint `tracetest:4317`.

```yaml
receivers:
otlp:
protocols:
grpc:
http:
processors:
batch:
timeout: 100ms
exporters:
logging:
loglevel: debug
otlp/1:
endpoint: tracetest:4317
# Send traces to Tracetest.
# Read more in docs here: https://docs.tracetest.io/configuration/connecting-to-data-stores/opentelemetry-collector
tls:
insecure: true
service:
pipelines:
traces/1:
receivers: [otlp]
processors: [batch]
exporters: [otlp/1]
```

## Run both the Python app and Tracetest

To start both the Python app and Tracetest we will run this command:

```bash
docker-compose -f docker-compose.yaml -f tracetest/docker-compose.yaml up # add --build if the images are not built already
```

This will start your Tracetest instance on `http://localhost:11633/`. Go ahead and open it up.

Start creating tests! Make sure to use the `http://app:8080/` url in your test creation, because your Python app and Tracetest are in the same network.

```mdx-code-block
</TabItem>
</Tabs>
```

## Learn more

Feel free to check out our [examples in GitHub](https://github.com/kubeshop/tracetest/tree/main/examples), and join our [Slack Community](https://dub.sh/tracetest-community) for more info!
Loading

0 comments on commit b8ae439

Please sign in to comment.