fix: add agent key auth for ingest endpoints

This commit is contained in:
2026-02-06 19:13:30 -03:00
parent 615a8b5404
commit 6038e82b22
18 changed files with 1244 additions and 5 deletions

View File

@@ -0,0 +1,43 @@
# ═══════════════════════════════════════════════════════════
# 🐍 OPHION - Java Instrumented App Dockerfile
# Example showing how to add OpenTelemetry to any Java app
# ═══════════════════════════════════════════════════════════
# Build stage
FROM eclipse-temurin:21-jdk-alpine AS builder
WORKDIR /app
# Copy Maven/Gradle files (if using build tool)
COPY pom.xml* build.gradle* ./
# Copy source code
COPY src/ ./src/
# For simple example, compile directly
RUN mkdir -p target/classes && \
javac -d target/classes src/main/java/*.java
# Package as JAR
RUN cd target/classes && \
jar cfe ../app.jar Main .
# Runtime stage
FROM eclipse-temurin:21-jre-alpine
WORKDIR /app
# Download OpenTelemetry Java Agent
ARG OTEL_AGENT_VERSION=2.1.0
RUN wget -q https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases/download/v${OTEL_AGENT_VERSION}/opentelemetry-javaagent.jar \
-O /opt/opentelemetry-javaagent.jar
# Copy the built application
COPY --from=builder /app/target/app.jar .
# Expose port
EXPOSE 8080
# Start with OpenTelemetry Java Agent
# The JAVA_TOOL_OPTIONS env var in docker-compose.yml enables the agent
CMD ["java", "-jar", "app.jar"]

View File

@@ -0,0 +1,62 @@
# ═══════════════════════════════════════════════════════════
# 🐍 OPHION - Java Auto-Instrumentation Example
# Demonstrates automatic tracing for Java applications
# ═══════════════════════════════════════════════════════════
#
# Usage:
# docker-compose up -d
#
# This example shows how to instrument ANY Java app without
# code changes using the OpenTelemetry Java Agent
# ═══════════════════════════════════════════════════════════
version: '3.8'
services:
java-app:
build:
context: .
dockerfile: Dockerfile
ports:
- "8081:8080"
environment:
# ════════════════════════════════════════════════════
# OpenTelemetry Auto-Instrumentation Configuration
# ════════════════════════════════════════════════════
# Service identification
- OTEL_SERVICE_NAME=java-example-app
- OTEL_SERVICE_VERSION=1.0.0
# OTLP Exporter configuration (pointing to Ophion collector)
- OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
- OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
- OTEL_TRACES_EXPORTER=otlp
- OTEL_METRICS_EXPORTER=otlp
- OTEL_LOGS_EXPORTER=otlp
# Resource attributes
- OTEL_RESOURCE_ATTRIBUTES=deployment.environment=development,service.namespace=ophion-examples
# Sampling (1.0 = 100% of traces)
- OTEL_TRACES_SAMPLER=parentbased_traceidratio
- OTEL_TRACES_SAMPLER_ARG=1.0
# Propagation format
- OTEL_PROPAGATORS=tracecontext,baggage,b3multi
# Java Agent path (set in Dockerfile JAVA_TOOL_OPTIONS)
- JAVA_TOOL_OPTIONS=-javaagent:/opt/opentelemetry-javaagent.jar
networks:
- ophion
restart: unless-stopped
healthcheck:
test: ["CMD", "wget", "-q", "--spider", "http://localhost:8080/health"]
interval: 10s
timeout: 5s
retries: 3
networks:
ophion:
external: true

View File

@@ -0,0 +1,115 @@
/**
* ═══════════════════════════════════════════════════════════
* 🐍 OPHION - Example Java Application
* This app is automatically instrumented by OpenTelemetry Java Agent
* No code changes needed - just the agent JAR!
* ═══════════════════════════════════════════════════════════
*/
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpExchange;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import java.util.logging.Logger;
public class Main {
private static final Logger logger = Logger.getLogger(Main.class.getName());
private static final int PORT = 8080;
public static void main(String[] args) throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress(PORT), 0);
// Routes
server.createContext("/", new HomeHandler());
server.createContext("/health", new HealthHandler());
server.createContext("/api/users", new UsersHandler());
server.createContext("/api/slow", new SlowHandler());
server.setExecutor(Executors.newFixedThreadPool(10));
server.start();
logger.info("🚀 Java server running on port " + PORT);
logger.info("📊 OTEL Endpoint: " + System.getenv("OTEL_EXPORTER_OTLP_ENDPOINT"));
logger.info("🏷️ Service Name: " + System.getenv("OTEL_SERVICE_NAME"));
}
static class HomeHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
logger.info("Home endpoint called");
String response = """
{
"message": "Hello from Java!",
"instrumented": true,
"otelEndpoint": "%s"
}
""".formatted(System.getenv("OTEL_EXPORTER_OTLP_ENDPOINT"));
sendResponse(exchange, 200, response);
}
}
static class HealthHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
String response = """
{
"status": "healthy",
"service": "java-example"
}
""";
sendResponse(exchange, 200, response);
}
}
static class UsersHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
logger.info("Fetching users");
// Simulate some work
sleep(10 + (int)(Math.random() * 90));
String response = """
[
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"},
{"id": 3, "name": "Charlie"}
]
""";
sendResponse(exchange, 200, response);
}
}
static class SlowHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
logger.info("Starting slow operation");
sleep(500);
logger.info("Slow operation completed");
String response = """
{
"message": "Slow response",
"delay": "500ms"
}
""";
sendResponse(exchange, 200, response);
}
}
private static void sendResponse(HttpExchange exchange, int code, String response) throws IOException {
exchange.getResponseHeaders().set("Content-Type", "application/json");
exchange.sendResponseHeaders(code, response.getBytes().length);
try (OutputStream os = exchange.getResponseBody()) {
os.write(response.getBytes());
}
}
private static void sleep(int ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}

View File

@@ -0,0 +1,29 @@
# ═══════════════════════════════════════════════════════════
# 🐍 OPHION - Node.js Instrumented App Dockerfile
# Example showing how to add OpenTelemetry to any Node.js app
# ═══════════════════════════════════════════════════════════
FROM node:20-alpine
WORKDIR /app
# Copy package files
COPY package*.json ./
# Install dependencies + OpenTelemetry auto-instrumentation
RUN npm install && \
npm install @opentelemetry/auto-instrumentations-node \
@opentelemetry/api \
@opentelemetry/sdk-node \
@opentelemetry/exporter-trace-otlp-http \
@opentelemetry/exporter-metrics-otlp-http
# Copy application code
COPY . .
# Expose port
EXPOSE 3000
# Start with auto-instrumentation
# The NODE_OPTIONS env var in docker-compose.yml handles instrumentation
CMD ["node", "server.js"]

View File

@@ -0,0 +1,62 @@
# ═══════════════════════════════════════════════════════════
# 🐍 OPHION - Node.js Auto-Instrumentation Example
# Demonstrates automatic tracing for Node.js applications
# ═══════════════════════════════════════════════════════════
#
# Usage:
# docker-compose up -d
#
# This example shows how to instrument ANY Node.js app without
# code changes using @opentelemetry/auto-instrumentations-node
# ═══════════════════════════════════════════════════════════
version: '3.8'
services:
nodejs-app:
build:
context: .
dockerfile: Dockerfile
ports:
- "3001:3000"
environment:
# ════════════════════════════════════════════════════
# OpenTelemetry Auto-Instrumentation Configuration
# ════════════════════════════════════════════════════
# Service identification
- OTEL_SERVICE_NAME=nodejs-example-app
- OTEL_SERVICE_VERSION=1.0.0
# OTLP Exporter configuration (pointing to Ophion collector)
- OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
- OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
- OTEL_TRACES_EXPORTER=otlp
- OTEL_METRICS_EXPORTER=otlp
- OTEL_LOGS_EXPORTER=otlp
# Resource attributes
- OTEL_RESOURCE_ATTRIBUTES=deployment.environment=development,service.namespace=ophion-examples
# Sampling (1.0 = 100% of traces)
- OTEL_TRACES_SAMPLER=parentbased_traceidratio
- OTEL_TRACES_SAMPLER_ARG=1.0
# Propagation format
- OTEL_PROPAGATORS=tracecontext,baggage,b3multi
# Enable auto-instrumentation via Node.js loader
- NODE_OPTIONS=--require @opentelemetry/auto-instrumentations-node/register
networks:
- ophion
restart: unless-stopped
healthcheck:
test: ["CMD", "wget", "-q", "--spider", "http://localhost:3000/health"]
interval: 10s
timeout: 5s
retries: 3
networks:
ophion:
external: true

View File

@@ -0,0 +1,17 @@
{
"name": "nodejs-instrumented-example",
"version": "1.0.0",
"description": "Example Node.js app with OpenTelemetry auto-instrumentation for Ophion",
"main": "server.js",
"scripts": {
"start": "node server.js",
"start:instrumented": "node --require @opentelemetry/auto-instrumentations-node/register server.js"
},
"dependencies": {
"express": "^4.18.2"
},
"devDependencies": {},
"keywords": ["ophion", "opentelemetry", "tracing", "observability"],
"author": "Ophion Team",
"license": "MIT"
}

View File

@@ -0,0 +1,67 @@
/**
* ═══════════════════════════════════════════════════════════
* 🐍 OPHION - Example Node.js Application
* This app is automatically instrumented by OpenTelemetry
* No code changes needed - just env vars!
* ═══════════════════════════════════════════════════════════
*/
const http = require('http');
const PORT = process.env.PORT || 3000;
// Simple HTTP server
const server = http.createServer((req, res) => {
const { url, method } = req;
console.log(`[${new Date().toISOString()}] ${method} ${url}`);
// Route handling
if (url === '/health') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ status: 'healthy', service: 'nodejs-example' }));
return;
}
if (url === '/') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
message: 'Hello from Node.js!',
instrumented: true,
otelEndpoint: process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'not set'
}));
return;
}
if (url === '/api/users') {
// Simulate some work
setTimeout(() => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify([
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }
]));
}, Math.random() * 100);
return;
}
if (url === '/api/slow') {
// Simulate slow operation (good for testing traces)
setTimeout(() => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'Slow response', delay: '500ms' }));
}, 500);
return;
}
// 404
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Not Found' }));
});
server.listen(PORT, () => {
console.log(`🚀 Node.js server running on port ${PORT}`);
console.log(`📊 OTEL Endpoint: ${process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'not configured'}`);
console.log(`🏷️ Service Name: ${process.env.OTEL_SERVICE_NAME || 'unknown'}`);
});

View File

@@ -0,0 +1,31 @@
# ═══════════════════════════════════════════════════════════
# 🐍 OPHION - Python Instrumented App Dockerfile
# Example showing how to add OpenTelemetry to any Python app
# ═══════════════════════════════════════════════════════════
FROM python:3.12-slim
WORKDIR /app
# Install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Install OpenTelemetry auto-instrumentation
RUN pip install --no-cache-dir \
opentelemetry-distro \
opentelemetry-exporter-otlp \
opentelemetry-instrumentation
# Auto-install all available instrumentations
RUN opentelemetry-bootstrap -a install
# Copy application code
COPY . .
# Expose port
EXPOSE 5000
# Start with auto-instrumentation wrapper
# opentelemetry-instrument auto-configures tracing based on env vars
CMD ["opentelemetry-instrument", "python", "app.py"]

View File

@@ -0,0 +1,105 @@
"""
═══════════════════════════════════════════════════════════
🐍 OPHION - Example Python Application
This app is automatically instrumented by OpenTelemetry
No code changes needed - just env vars!
═══════════════════════════════════════════════════════════
"""
import os
import time
import random
import logging
from flask import Flask, jsonify
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = Flask(__name__)
@app.route('/')
def home():
"""Home endpoint"""
logger.info("Home endpoint called")
return jsonify({
'message': 'Hello from Python!',
'instrumented': True,
'otel_endpoint': os.getenv('OTEL_EXPORTER_OTLP_ENDPOINT', 'not set')
})
@app.route('/health')
def health():
"""Health check endpoint"""
return jsonify({
'status': 'healthy',
'service': 'python-example'
})
@app.route('/api/users')
def get_users():
"""Get users - simulates DB call"""
logger.info("Fetching users")
# Simulate some work
time.sleep(random.uniform(0.01, 0.1))
return jsonify([
{'id': 1, 'name': 'Alice'},
{'id': 2, 'name': 'Bob'},
{'id': 3, 'name': 'Charlie'}
])
@app.route('/api/slow')
def slow_endpoint():
"""Slow endpoint - good for testing trace visualization"""
logger.info("Starting slow operation")
# Simulate slow operation
time.sleep(0.5)
logger.info("Slow operation completed")
return jsonify({
'message': 'Slow response',
'delay': '500ms'
})
@app.route('/api/chain')
def chain_endpoint():
"""Simulates a chain of operations"""
logger.info("Starting chain operation")
# Step 1: Validate
time.sleep(random.uniform(0.01, 0.05))
logger.info("Validation complete")
# Step 2: Process
time.sleep(random.uniform(0.05, 0.1))
logger.info("Processing complete")
# Step 3: Save
time.sleep(random.uniform(0.02, 0.08))
logger.info("Save complete")
return jsonify({
'message': 'Chain completed',
'steps': ['validate', 'process', 'save']
})
@app.route('/api/error')
def error_endpoint():
"""Endpoint that raises an error - good for testing error traces"""
logger.error("About to raise an error")
raise ValueError("Intentional error for testing traces")
@app.errorhandler(Exception)
def handle_error(error):
"""Global error handler"""
logger.exception(f"Unhandled error: {error}")
return jsonify({
'error': str(error),
'type': type(error).__name__
}), 500
if __name__ == '__main__':
port = int(os.getenv('PORT', 5000))
logger.info(f"🚀 Python server starting on port {port}")
logger.info(f"📊 OTEL Endpoint: {os.getenv('OTEL_EXPORTER_OTLP_ENDPOINT', 'not configured')}")
logger.info(f"🏷️ Service Name: {os.getenv('OTEL_SERVICE_NAME', 'unknown')}")
app.run(host='0.0.0.0', port=port)

View File

@@ -0,0 +1,62 @@
# ═══════════════════════════════════════════════════════════
# 🐍 OPHION - Python Auto-Instrumentation Example
# Demonstrates automatic tracing for Python applications
# ═══════════════════════════════════════════════════════════
#
# Usage:
# docker-compose up -d
#
# This example shows how to instrument ANY Python app without
# code changes using opentelemetry-instrument command
# ═══════════════════════════════════════════════════════════
version: '3.8'
services:
python-app:
build:
context: .
dockerfile: Dockerfile
ports:
- "5001:5000"
environment:
# ════════════════════════════════════════════════════
# OpenTelemetry Auto-Instrumentation Configuration
# ════════════════════════════════════════════════════
# Service identification
- OTEL_SERVICE_NAME=python-example-app
- OTEL_SERVICE_VERSION=1.0.0
# OTLP Exporter configuration (pointing to Ophion collector)
- OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
- OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
- OTEL_TRACES_EXPORTER=otlp
- OTEL_METRICS_EXPORTER=otlp
- OTEL_LOGS_EXPORTER=otlp
# Resource attributes
- OTEL_RESOURCE_ATTRIBUTES=deployment.environment=development,service.namespace=ophion-examples
# Sampling (1.0 = 100% of traces)
- OTEL_TRACES_SAMPLER=parentbased_traceidratio
- OTEL_TRACES_SAMPLER_ARG=1.0
# Propagation format
- OTEL_PROPAGATORS=tracecontext,baggage,b3multi
# Python-specific: auto-detect instrumentations
- OTEL_PYTHON_LOGGING_AUTO_INSTRUMENTATION_ENABLED=true
networks:
- ophion
restart: unless-stopped
healthcheck:
test: ["CMD", "wget", "-q", "--spider", "http://localhost:5000/health"]
interval: 10s
timeout: 5s
retries: 3
networks:
ophion:
external: true

View File

@@ -0,0 +1,4 @@
# Python dependencies for instrumented example
flask>=3.0.0
gunicorn>=21.2.0
requests>=2.31.0