Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.
TypeScript agent-harnessagent-harness-engineeringai-engineeringai-observabilityamd-gpuclaude-codeclickhousecodexcoding-agentcoding-agentscursorgenaigpu-monitoringllm-observabilityllmopsnvidia-smiobservabilityopen-sourceopenaiopentelemetry
Feat: add Fleet Hub for centralized OpenTelemetry collector management with OpAMP (#923)
Aman Agarwal3c9d7837e6bf
diff --git a/.gitignore b/.gitignoreindex 2beadaac..3d69b3e1 100644--- a/.gitignore+++ b/.gitignore@@ -9,6 +9,11 @@ path/__pycache__/**bun.lockblogs/-.env+**.env.vscode/-.idea/\ No newline at end of file+.idea/+.cursor-rules/+.cursorrules+**.pem+**certs/index.txt+**.csr\ No newline at end of filediff --git a/OPAMP_DEPLOYMENT.md b/OPAMP_DEPLOYMENT.mdnew file mode 100644index 00000000..e531fb5d--- /dev/null+++ b/OPAMP_DEPLOYMENT.md@@ -0,0 +1,406 @@+# OpenLIT OpAMP Server Deployment Guide++This guide explains how to deploy OpenLIT with the integrated OpAMP server for Fleet Hub management using Docker Compose.++## Overview++The OpenLIT OpAMP server provides secure communication between the OpenLIT platform and OpAMP supervisors managing OpenTelemetry Collectors. This deployment includes:++- **Automatic certificate generation** for secure TLS communication+- **Environment-aware configuration** (development vs production)+- **Dynamic supervisor configuration** based on environment settings+- **Controlled network configuration** with user-configurable security settings++## Quick Start++### 1. Clone and Setup++```bash+git clone https://github.com/openlit/openlit.git+cd openlit+```++### 2. Configure Environment (Optional)++Copy the example environment file and customize:++```bash+cp env.example .env+# Edit .env with your preferred settings+```++### 3. Deploy with Docker Compose++**For Development:**+```bash+docker-compose up -d+```++**For Production:**+```bash+# Production mode is now the default with secure TLS settings+# Set any custom overrides if needed+export OPAMP_ENVIRONMENT=production # Default+export OPAMP_TLS_INSECURE_SKIP_VERIFY=false # Default+export OPAMP_TLS_REQUIRE_CLIENT_CERT=true # Default++docker-compose up -d+```++### 4. Access Services++- **OpenLIT UI**: http://localhost:3000+- **Fleet Hub**: http://localhost:3000/fleet-hub+- **OpAMP Server**: wss://localhost:4320/v1/opamp+- **OpAMP API**: http://localhost:8080++## Environment Configuration++### Available Environment Variables++| Variable | Default | Description |+|----------|---------|-------------|+| `OPAMP_ENVIRONMENT` | `development` | Environment mode (`development`, `production`, `testing`) |+| `OPAMP_TLS_INSECURE_SKIP_VERIFY` | `true` | Skip certificate verification (dev only) |+| `OPAMP_TLS_REQUIRE_CLIENT_CERT` | `false` | Require client certificates |+| `OPAMP_TLS_MIN_VERSION` | `1.2` | Minimum TLS version |+| `OPAMP_TLS_MAX_VERSION` | `1.3` | Maximum TLS version |+| `OPAMP_LOG_LEVEL` | `info` | Logging level |++### Environment Modes++#### Development Mode (Default)+- Certificate verification is skipped (`insecure_skip_verify: true`)+- Client certificates are not required+- Suitable for local development and testing+- **⚠️ Not secure for production use**++#### Production Mode+- Full certificate verification enabled+- Client certificates required by default+- Strict TLS configuration+- Certificate expiry monitoring+- **✅ Production-ready security**++#### Testing Mode+- Similar to development mode+- Optimized for automated testing+- Flexible certificate validation++## Deployment Scenarios++### Scenario 1: Local Development++```bash+# Use default development settings+docker-compose up -d+```++The OpAMP supervisor will automatically connect using `insecure_skip_verify: true`.++### Scenario 2: Production Deployment++```bash+# Set production environment variables+export OPAMP_ENVIRONMENT=production+export OPAMP_TLS_INSECURE_SKIP_VERIFY=false+export OPAMP_TLS_REQUIRE_CLIENT_CERT=true++# Deploy with production settings+docker-compose up -d+```++### Scenario 3: Custom Configuration++Create a `.env` file:++```env+# Custom production configuration+OPAMP_ENVIRONMENT=production+OPAMP_TLS_INSECURE_SKIP_VERIFY=false+OPAMP_TLS_REQUIRE_CLIENT_CERT=true+OPAMP_TLS_MIN_VERSION=1.3+OPAMP_LOG_LEVEL=warn++# Database settings+OPENLIT_DB_PASSWORD=your-secure-password+```++Then deploy:++```bash+docker-compose up -d+```++## Certificate Management++### Automatic Certificate Generation++The deployment automatically generates:+- **CA Certificate**: Self-signed root certificate+- **Server Certificate**: For OpAMP server TLS+- **Client Certificate**: For mutual TLS authentication (required in production)++### Certificate Properties++- **Key Size**: 4096-bit RSA keys+- **Validity**: 10 years (CA), 1 year (server/client)+- **Subject Alternative Names**: Includes localhost, Docker IPs, and container hostnames+- **Extensions**: Proper key usage and extended key usage++### Custom Certificates++For production with custom certificates:++1. **Replace generated certificates** in the container:+ ```bash+ docker cp your-ca.cert.pem openlit:/app/opamp/certs/cert/ca.cert.pem+ docker cp your-server.cert.pem openlit:/app/opamp/certs/server/server.cert.pem+ docker cp your-server.key.pem openlit:/app/opamp/certs/server/server.key.pem+ ```++2. **Restart the container**:+ ```bash+ docker-compose restart openlit+ ```++## Connecting External Supervisors++### Development Connection++For external OpAMP supervisors in development:++```yaml+# supervisor.yaml+server:+ endpoint: wss://your-openlit-host:4320/v1/opamp+ tls:+ insecure_skip_verify: true++agent:+ executable: /path/to/otelcol-contrib+ config_files:+ - /etc/otel/config.yaml++capabilities:+ accepts_remote_config: true+ reports_effective_config: true+ reports_own_logs: true+ reports_health: true+```++### Production Connection++For production deployments with mutual TLS:++1. **Extract certificates**:+ ```bash+ # Extract CA certificate+ docker cp openlit:/app/opamp/certs/cert/ca.cert.pem ./ca.cert.pem++ # Extract client certificates for mutual TLS+ docker cp openlit:/app/opamp/certs/client/client.cert.pem ./client.cert.pem+ docker cp openlit:/app/opamp/certs/client/client.key.pem ./client.key.pem+ ```++2. **Configure supervisor with mutual TLS**:+ ```yaml+ # supervisor.yaml+ server:+ endpoint: wss://your-openlit-host:4320/v1/opamp+ tls:+ insecure_skip_verify: false+ ca_file: /path/to/ca.cert.pem+ cert_file: /path/to/client.cert.pem+ key_file: /path/to/client.key.pem+ ```++3. **Deploy supervisor**:+ ```bash+ ./opampsupervisor --config supervisor.yaml+ ```++### Using the Setup Script++Use the included setup script for automated configuration:++```bash+# Extract setup script from container+docker cp openlit:/app/opamp/setup-supervisor.sh ./++# Generate development configuration+./setup-supervisor.sh --development++# Generate production configuration+./setup-supervisor.sh --production --server-url wss://your-server:4320/v1/opamp+```++## Monitoring and Troubleshooting++### Container Logs++```bash+# View all logs+docker-compose logs -f++# View OpAMP specific logs+docker-compose logs -f openlit | grep -E "(OpAMP|OPAMP)"++# View certificate generation logs+docker exec openlit cat /var/log/certs.log+```++### Health Checks++```bash+# Check OpAMP server status+curl -k https://localhost:8080/health++# Test TLS connection+openssl s_client -connect localhost:4320++# View certificate information+docker exec openlit openssl x509 -in /app/opamp/certs/cert/ca.cert.pem -noout -text+```++### Common Issues++#### "certificate signed by unknown authority"++**Cause**: Supervisor doesn't trust the self-signed CA certificate.++**Solutions**:+1. **Development**: Set `insecure_skip_verify: true` in supervisor config+2. **Production**: Provide CA certificate path in supervisor config++#### "connection refused"++**Cause**: OpAMP server not running or network issues.++**Solutions**:+1. Check container status: `docker-compose ps`+2. Verify port mapping: `docker-compose port openlit 4320`+3. Check firewall rules for port 4320++#### "certificate has expired"++**Cause**: Generated certificates have expired.++**Solutions**:+1. Regenerate certificates: `docker-compose restart openlit`+2. Check certificate expiry: `docker exec openlit openssl x509 -in /app/opamp/certs/server/server.cert.pem -noout -dates`++## Security Considerations++### Development Security++- Uses `insecure_skip_verify: true` by default+- Suitable for local development only+- **Never use in production**++### Production Security++- Full certificate verification enabled+- Mutual TLS support available+- Secure cipher suites and TLS versions+- Certificate expiry monitoring++### Best Practices++1. **Use production mode** for production deployments+2. **Rotate certificates** regularly+3. **Secure CA private key** with proper file permissions+4. **Monitor certificate expiry** and set up alerts+5. **Use strong passwords** for database and other services++## Advanced Configuration++### Mutual TLS Configuration++Mutual TLS is enabled by default in production mode. To disable it:++```bash+export OPAMP_TLS_REQUIRE_CLIENT_CERT=false+docker-compose up -d+```++Supervisor configuration with client certificates (required in production):++```yaml+server:+ tls:+ insecure_skip_verify: false+ ca_file: /path/to/ca.cert.pem+ cert_file: /path/to/client.cert.pem+ key_file: /path/to/client.key.pem+```++### Custom Certificate Validity++Modify certificate validity periods by setting environment variables before deployment:++```bash+export CERT_VALIDITY_DAYS=7300 # 20 years for CA+export SERVER_CERT_DAYS=730 # 2 years for server cert+docker-compose up -d+```++## Migration from Previous Versions++If upgrading from a previous version without OpAMP support:++1. **Backup existing data**:+ ```bash+ docker-compose down+ docker volume create openlit-backup+ docker run --rm -v openlit-data:/source -v openlit-backup:/backup alpine cp -r /source/. /backup/+ ```++2. **Update configuration**:+ ```bash+ # Pull latest changes+ git pull origin main++ # Update Docker Compose+ docker-compose pull+ ```++3. **Deploy with new configuration**:+ ```bash+ docker-compose up -d+ ```++## Support and Documentation++- **Fleet Hub Documentation**: [docs/latest/openlit/observability/fleet-hub.mdx](docs/latest/openlit/observability/fleet-hub.mdx)+- **Certificate Management**: [src/opamp-server/CERTIFICATES.md](src/opamp-server/CERTIFICATES.md)+- **OpAMP Specification**: [OpenTelemetry OpAMP](https://github.com/open-telemetry/opamp-spec)++## Environment Variables Reference++### User-Configurable Variables++```bash+# Environment and Security+OPAMP_ENVIRONMENT=development|production|testing+OPAMP_TLS_INSECURE_SKIP_VERIFY=true|false+OPAMP_TLS_REQUIRE_CLIENT_CERT=true|false+OPAMP_TLS_MIN_VERSION=1.0|1.1|1.2|1.3+OPAMP_TLS_MAX_VERSION=1.0|1.1|1.2|1.3+OPAMP_LOG_LEVEL=debug|info|warn|error++# Database Configuration+OPENLIT_DB_NAME=openlit+OPENLIT_DB_USER=default+OPENLIT_DB_PASSWORD=OPENLIT++# Application Configuration+PORT=3000+DOCKER_PORT=3000++# OAuth (Optional)+GOOGLE_CLIENT_ID=your-client-id+GOOGLE_CLIENT_SECRET=your-client-secret+GITHUB_CLIENT_ID=your-client-id+GITHUB_CLIENT_SECRET=your-client-secret+```diff --git a/assets/otel-collector-config.yaml b/assets/otel-collector-config.yamlindex b7e89afd..4cea7519 100644--- a/assets/otel-collector-config.yaml+++ b/assets/otel-collector-config.yaml@@ -5,6 +5,7 @@ receivers:endpoint: 0.0.0.0:4317http:endpoint: 0.0.0.0:4318+processors:batch:memory_limiter:@@ -13,11 +14,10 @@ processors:# 25% of limit up to 2Gspike_limit_mib: 512check_interval: 5s-extensions:- zpages: {}+exporters:clickhouse:- endpoint: tcp://${env:INIT_DB_HOST}:${env:INIT_DB_PORT}?dial_timeout=10s+ endpoint: tcp://${env:INIT_DB_HOST}:9000?dial_timeout=10sdatabase: ${env:INIT_DB_DATABASE}username: ${env:INIT_DB_USERNAME}password: ${env:INIT_DB_PASSWORD}@@ -31,17 +31,21 @@ exporters:initial_interval: 5smax_interval: 30smax_elapsed_time: 300s+service:pipelines:logs:- receivers: [ otlp ]- processors: [ batch ]- exporters: [ clickhouse ]+ receivers: [otlp]+ processors: [batch]+ exporters: [clickhouse]traces:- receivers: [ otlp ]+ receivers: [otlp]processors: [memory_limiter, batch]- exporters: [ clickhouse ]+ exporters: [clickhouse]metrics:- receivers: [ otlp ]+ receivers: [otlp]processors: [memory_limiter, batch]- exporters: [ clickhouse ]\ No newline at end of file+ exporters: [clickhouse]+ # telemetry:+ # metrics:+ # address: localhost:8888\ No newline at end of filediff --git a/assets/supervisor-dynamic.yaml b/assets/supervisor-dynamic.yamlnew file mode 100644index 00000000..88288fac--- /dev/null+++ b/assets/supervisor-dynamic.yaml@@ -0,0 +1,2 @@+server:+ endpoint: wss://localhost:4320/v1/opampdiff --git a/assets/supervisor-production.yaml b/assets/supervisor-production.yamlnew file mode 100644index 00000000..a8cc5181--- /dev/null+++ b/assets/supervisor-production.yaml@@ -0,0 +1,34 @@+server:+ # The endpoint of the OpAMP server+ endpoint: wss://your-openlit-server:4320/v1/opamp+ tls:+ # Production configuration with proper certificate verification+ insecure_skip_verify: false++ # Path to the CA certificate that signed the server certificate+ ca_file: /app/opamp/certs/cert/ca.cert.pem++ # Optional: Client certificate for mutual TLS authentication+ # Uncomment these lines if the server requires client certificates+ # cert_file: /app/opamp/certs/client/client.cert.pem+ # key_file: /app/opamp/certs/client/client.key.pem++agent:+ # The path to the OpenTelemetry Collector binary managed by this supervisor+ executable: /app/opamp/otelcontribcol++ # Reference to external configuration file+ config_files:+ - /etc/otel/otel-collector-config.yaml++capabilities:+ accepts_remote_config: true+ reports_effective_config: true+ reports_own_metrics: false+ reports_own_logs: true+ reports_own_traces: false+ reports_health: true+ reports_remote_config: true++storage:+ directory: ./storagediff --git a/assets/supervisor.yaml b/assets/supervisor.yamlnew file mode 100644index 00000000..485996ca--- /dev/null+++ b/assets/supervisor.yaml@@ -0,0 +1,35 @@+server:+ # The endpoint of the OpAMP server+ endpoint: wss://0.0.0.0:4320/v1/opamp+ tls:+ # For development: set to true to skip certificate verification+ # For production: set to false and provide ca_file+ insecure_skip_verify: true++ # For production with custom CA certificate:+ # insecure_skip_verify: false+ # ca_file: /app/opamp/certs/cert/ca.cert.pem++ # Optional: Client certificate for mutual TLS+ # cert_file: /app/opamp/certs/client/client.cert.pem+ # key_file: /app/opamp/certs/client/client.key.pem++agent:+ # The path to the OpenTelemetry Collector binary managed by this supervisor+ executable: /app/opamp/otelcontribcol++ # Reference to external configuration file+ config_files:+ - /etc/otel/otel-collector-config.yaml++capabilities:+ accepts_remote_config: true+ reports_effective_config: true+ reports_own_metrics: false+ reports_own_logs: true+ reports_own_traces: false+ reports_health: true+ reports_remote_config: true++storage:+ directory: ./storage\ No newline at end of filediff --git a/docker-compose.yml b/docker-compose.ymlindex 9418e519..ad7fdec4 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -26,41 +26,35 @@ services:SQLITE_DATABASE_URL: file:/app/client/data/data.dbPORT: ${PORT:-3000}DOCKER_PORT: ${PORT:-3000}+# OAuth Environment VariablesGOOGLE_CLIENT_ID: ${GOOGLE_CLIENT_ID:-}GOOGLE_CLIENT_SECRET: ${GOOGLE_CLIENT_SECRET:-}GITHUB_CLIENT_ID: ${GITHUB_CLIENT_ID:-}GITHUB_CLIENT_SECRET: ${GITHUB_CLIENT_SECRET:-}++ # TLS Configuration (user-configurable)+ OPAMP_ENVIRONMENT: ${OPAMP_ENVIRONMENT:-production}+ OPAMP_CERTS_DIR: "/app/opamp/certs"+ OPAMP_TLS_INSECURE_SKIP_VERIFY: ${OPAMP_TLS_INSECURE_SKIP_VERIFY:-false}+ OPAMP_TLS_REQUIRE_CLIENT_CERT: ${OPAMP_TLS_REQUIRE_CLIENT_CERT:-true}+ OPAMP_TLS_MIN_VERSION: ${OPAMP_TLS_MIN_VERSION:-1.2}+ OPAMP_TLS_MAX_VERSION: ${OPAMP_TLS_MAX_VERSION:-1.3}+ OPAMP_LOG_LEVEL: ${OPAMP_LOG_LEVEL:-info}env_file:- path: .envrequired: falseports:- "${PORT:-3000}:${DOCKER_PORT:-3000}"+ - "4317:4317" # OTLP gRPC receiver+ - "4318:4318" # OTLP HTTP receiverdepends_on:- clickhousevolumes:- openlit-data:/app/client/data- restart: always-- otel-collector:- image: otel/opentelemetry-collector-contrib:0.94.0- container_name: otel-collector- environment:- INIT_DB_HOST: clickhouse- INIT_DB_PORT: 9000- INIT_DB_DATABASE: ${OPENLIT_DB_NAME:-openlit}- INIT_DB_USERNAME: ${OPENLIT_DB_USER:-default}- INIT_DB_PASSWORD: ${OPENLIT_DB_PASSWORD:-OPENLIT}- ports:- - "4317:4317"- - "4318:4318"- - "8888:8888"- - "55679:55679"- depends_on:- - clickhouse- volumes:- - ./assets/otel-collector-config.yaml:/etc/otelcol-contrib/config.yaml+ - ./assets/otel-collector-config.yaml:/etc/otel/otel-collector-config.yaml+ - ./assets/supervisor-dynamic.yaml:/etc/otel/supervisor-dynamic.yamlrestart: alwaysvolumes:diff --git a/docs/docs.json b/docs/docs.jsonindex 632622de..c51639cf 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -63,7 +63,8 @@"pages": ["latest/openlit/observability/tracing","latest/openlit/observability/metrics",- "latest/openlit/observability/error"+ "latest/openlit/observability/error",+ "latest/openlit/observability/fleet-hub"]},{diff --git a/docs/images/fleet-hub.mp4 b/docs/images/fleet-hub.mp4new file mode 100644index 00000000..659e6aebBinary files /dev/null and b/docs/images/fleet-hub.mp4 differdiff --git a/docs/latest/openlit/observability/fleet-hub.mdx b/docs/latest/openlit/observability/fleet-hub.mdxnew file mode 100644index 00000000..11c52ad1--- /dev/null+++ b/docs/latest/openlit/observability/fleet-hub.mdx@@ -0,0 +1,310 @@+---+title: "Fleet Hub"+description: "Centralized management and monitoring of OpenTelemetry collectors using OpAMP (Open Agent Management Protocol)"+---++<video+ autoPlay+ muted+ loop+ controls+ className="w-full rounded-xl"+ src="/images/fleet-hub.mp4"+>+</video>++## Upgrade Information++<Warning>+**Important Upgrade Notice**: When upgrading from OpenLIT versions prior to 1.15.0 (which introduced Fleet Hub), special attention is required for Docker Compose deployments.+</Warning>++### Docker Compose Upgrade++If you're running OpenLIT using Docker Compose, you **must** use the `--remove-orphans` flag when upgrading:++```bash+# Upgrade with orphan removal+docker-compose up -d --remove-orphans+```++**Why this is necessary:**+- The OpenTelemetry Collector has been integrated directly into the OpenLIT container+- The standalone `otel-collector` container is no longer needed+- Without `--remove-orphans`, the old collector container will conflict with the new integrated collector+- Both containers attempt to bind to the same ports (4317, 4318), causing startup failures++### Migration Steps++1. **Stop Current Deployment**+ ```bash+ docker-compose down+ ```++2. **Pull Latest Images**+ ```bash+ docker-compose pull+ ```++3. **Start with Orphan Removal**+ ```bash+ docker-compose up -d --remove-orphans+ ```++4. **Verify Fleet Hub Access**+ - Navigate to Fleet Hub in the OpenLIT UI+ - Confirm the integrated collector is running+ - Update any existing collector configurations to connect to the new OpAMP endpoint++### What Changed in Version 1.15.0++- **Integrated Collector**: OpenTelemetry Collector now runs inside the OpenLIT container+- **OpAMP Server**: New OpAMP server for Fleet Hub functionality+- **Port Consolidation**: OTLP ports (4317, 4318) now served by the main OpenLIT container+- **Configuration Management**: Centralized configuration through Fleet Hub UI++<Note>+After upgrading, existing OpenTelemetry Collectors in your infrastructure can be connected to Fleet Hub by configuring them with OpAMP supervisors pointing to your OpenLIT instance.+</Note>++## Overview++Fleet Hub is OpenLIT's centralized management system for OpenTelemetry collectors across your infrastructure. Built on the **OpAMP (Open Agent Management Protocol)** standard, Fleet Hub provides real-time monitoring, configuration management, and health tracking for all your collectors from a unified dashboard.++<Note>+Fleet Hub uses the industry-standard OpAMP protocol, ensuring compatibility with OpenTelemetry ecosystem tools and future-proofing your observability infrastructure.+</Note>++## Key Features++### 🔍 **Real-time Monitoring**+- Live health status of all connected collectors+- Component-level health monitoring+- Performance metrics and resource usage+- Connection status and uptime tracking++### ⚙️ **Configuration Management**+- Centralized configuration updates+- Real-time configuration deployment+- Configuration validation and rollback+- Custom instance-specific configurations++### 📊 **Comprehensive Dashboard**+- Unified view of all collectors+- Detailed collector information (OS, architecture, version)+- Health status indicators with error details+- Searchable and filterable collector list++### 🔧 **OpAMP Integration**+- Standards-compliant OpAMP implementation+- Secure WebSocket connections with TLS support+- Automatic agent discovery and registration+- Bi-directional communication for configuration and status++## How It Works++Fleet Hub operates through three main components:++1. **OpAMP Server**: Built into OpenLIT, handles agent connections and configuration distribution+2. **OpAMP Supervisor**: Manages the OpenTelemetry Collector lifecycle on each host+3. **Fleet Hub UI**: Web interface for monitoring and managing collectors++```mermaid+graph TB+ A[Fleet Hub UI] --> B[OpAMP Server]+ B --> C[OpAMP Supervisor 1]+ B --> D[OpAMP Supervisor 2]+ B --> E[OpAMP Supervisor N]+ C --> F[OTel Collector 1]+ D --> G[OTel Collector 2]+ E --> H[OTel Collector N]++ F --> I[Your Applications]+ G --> J[Your Applications]+ H --> K[Your Applications]+```++## Getting Started++### Prerequisites++- OpenLIT platform deployed and running+- OpenTelemetry Collector with OpAMP supervisor support+- Network connectivity between collectors and OpenLIT++### Step 1: Access Fleet Hub++Navigate to Fleet Hub in your OpenLIT dashboard:++1. Open your OpenLIT instance+2. Go to **Fleet Hub** from the main navigation+3. You'll see the Fleet Hub dashboard with any connected collectors++### Step 2: Configure OpAMP Supervisor++On each host where you want to monitor collectors, set up the OpAMP supervisor:++<CodeGroup>++```yaml supervisor.yaml+server:+ # Replace with your OpenLIT instance URL+ endpoint: wss://your-openlit-instance:4320/v1/opamp+ tls:+ insecure_skip_verify: false # Set to true for development++agent:+ # Path to your OpenTelemetry Collector binary+ executable: /usr/local/bin/otelcol-contrib++ # Configuration files for the collector+ config_files:+ - /etc/otel/otel-collector-config.yaml++capabilities:+ accepts_remote_config: true+ reports_effective_config: true+ reports_own_metrics: false+ reports_own_logs: true+ reports_own_traces: false+ reports_health: true+ reports_remote_config: true++storage:+ directory: ./storage+```++```bash Start Supervisor+# Download OpAMP supervisor+curl -LO https://github.com/open-telemetry/opentelemetry-collector-releases/releases/latest/download/opampsupervisor_linux_amd64++# Make executable+chmod +x opampsupervisor_linux_amd64++# Start with configuration+./opampsupervisor_linux_amd64 --config supervisor.yaml+```++</CodeGroup>++### Step 3: Monitor Your Fleet++Once connected, you can:++- **View all collectors** in the Fleet Hub dashboard+- **Monitor health status** with real-time updates+- **Inspect configurations** both custom and effective+- **Update configurations** remotely through the UI+- **Track performance** and connection metrics++## Using Fleet Hub++### Dashboard Overview++The Fleet Hub dashboard displays:++- **Collector List**: All connected collectors with key information+- **Health Status**: Visual indicators for healthy/unhealthy collectors+- **System Information**: OS type, architecture, version details+- **Connection Details**: Start time, uptime, and connection status++### Managing Collectors++#### Viewing Collector Details++Click on any collector to view:+- Detailed system information+- Component health status+- Current configuration (read-only)+- Custom configuration editor+- Connection and performance metrics++#### Updating Configurations++1. Select a collector from the list+2. Navigate to the **Configuration** section+3. Edit the custom configuration in the YAML editor+4. Click **Save** to deploy changes+5. Monitor the **Effective Configuration** for applied changes++<Warning>+Configuration changes are applied immediately. Always validate your YAML syntax before saving to avoid collector disruption.+</Warning>++#### Health Monitoring++Fleet Hub provides multi-level health monitoring:++- **Overall Health**: Collector-wide health status+- **Component Health**: Individual component status (receivers, processors, exporters)+- **Error Details**: Specific error messages for troubleshooting++## Architecture Details++### OpAMP Protocol++Fleet Hub implements the OpenTelemetry Agent Management Protocol (OpAMP) which provides:++- **Standardized Communication**: Industry-standard protocol for agent management+- **Secure Connections**: WebSocket with TLS encryption+- **Bi-directional Messaging**: Real-time status reporting and configuration updates+- **Capability Negotiation**: Flexible feature support based on agent capabilities++### Security Features++- **TLS Encryption**: All communications encrypted in transit+- **Certificate Management**: Automatic certificate handling+- **Authentication**: Secure agent identification and verification+- **Access Control**: Role-based access to configuration management++### Scalability++Fleet Hub is designed to handle:+- **Multiple Collectors**: Hundreds of collectors per instance+- **Real-time Updates**: Low-latency status and configuration synchronization+- **High Availability**: Resilient to network interruptions and reconnections++## Troubleshooting++### Common Issues++#### Collector Not Appearing in Fleet Hub++1. **Check Network Connectivity**+ ```bash+ # Test connection to OpAMP endpoint+ telnet your-openlit-instance 4320+ ```++2. **Verify Supervisor Configuration**+ ```bash+ # Check supervisor logs+ ./opampsupervisor --config supervisor.yaml --verbose+ ```++3. **Validate TLS Settings**+ - Ensure TLS configuration matches between supervisor and server+ - Check certificate validity and trust chains++#### Configuration Updates Not Applied++1. **Check Supervisor Logs**: Look for configuration parsing errors+2. **Validate YAML Syntax**: Ensure configuration is valid YAML+3. **Verify Permissions**: Ensure supervisor has write access to config files+4. **Monitor Effective Config**: Check if changes appear in effective configuration++#### Health Status Issues++1. **Component Failures**: Check individual component health in the dashboard+2. **Resource Constraints**: Monitor system resources (CPU, memory, disk)+3. **Network Issues**: Verify connectivity to downstream services+4. **Configuration Errors**: Review collector logs for configuration issues++### Getting Help++If you encounter issues with Fleet Hub:++1. **Check Logs**: Review both OpenLIT and supervisor logs+2. **Community Support**: Join our [Slack community](https://join.slack.com/t/openlit/shared_invite/zt-2etnfttwg-TjP_7BZXfYg84oAukY8QRQ)+3. **GitHub Issues**: Report bugs on our [GitHub repository](https://github.com/openlit/openlit)+4. **Documentation**: Check the [OpAMP specification](https://github.com/open-telemetry/opamp-spec) for protocol detailsdiff --git a/docs/latest/overview.mdx b/docs/latest/overview.mdxindex 9bcd268d..b1ad04fd 100644--- a/docs/latest/overview.mdx+++ b/docs/latest/overview.mdx@@ -118,6 +118,21 @@ The project proudly follows OpenTelemetry Semantic Conventions for AI observabil</Tab></Tabs>+## Upgrade Information++<Warning>+**Important Upgrade Notice**: When upgrading from OpenLIT versions prior to 1.15.0 (which introduced Fleet Hub), special attention is required for Docker Compose deployments.++If you're running OpenLIT using Docker Compose, you **must** use the `--remove-orphans` flag when upgrading:++```bash+# Upgrade with orphan removal+docker-compose up -d --remove-orphans+```++This is necessary because the OpenTelemetry Collector has been integrated directly into the OpenLIT container, and the standalone `otel-collector` container is no longer needed. Without `--remove-orphans`, the old collector container will conflict with the new integrated collector on ports 4317 and 4318.+</Warning>+## Getting StartedChoose your path to start building better AI applications with OpenLIT:diff --git a/docs/snippets/destinations/otelcol/conclusion.mdx b/docs/snippets/destinations/otelcol/conclusion.mdxindex b462b433..6f36b5eb 100644--- a/docs/snippets/destinations/otelcol/conclusion.mdx+++ b/docs/snippets/destinations/otelcol/conclusion.mdx@@ -10,7 +10,7 @@ exporters:jaeger:endpoint: http://jaeger-collector:14250tls:- insecure: true+ insecure: falseservice:pipelines:diff --git a/env.example b/env.examplenew file mode 100644index 00000000..7466b84d--- /dev/null+++ b/env.example@@ -0,0 +1,86 @@+# OpenLIT Environment Configuration+# Copy this file to .env and customize the values for your deployment++# =============================================================================+# Database Configuration+# =============================================================================+OPENLIT_DB_NAME=openlit+OPENLIT_DB_USER=default+OPENLIT_DB_PASSWORD=OPENLIT++# =============================================================================+# Application Configuration+# =============================================================================+PORT=3000+DOCKER_PORT=3000++# =============================================================================+# OAuth Configuration (Optional)+# =============================================================================+# Google OAuth+GOOGLE_CLIENT_ID=+GOOGLE_CLIENT_SECRET=++# GitHub OAuth+GITHUB_CLIENT_ID=+GITHUB_CLIENT_SECRET=++# =============================================================================+# OpAMP Server Configuration+# =============================================================================++# Environment Mode+# Options: development, production, testing+# - development: Relaxed security, insecure_skip_verify=true by default+# - production: Strict security, full certificate verification, mutual TLS+# - testing: Similar to development, optimized for automated testing+# Default: production (secure by default)+OPAMP_ENVIRONMENT=production++# TLS Configuration+# Skip certificate verification (development only)+# Set to false for production with proper CA certificates+# Default: false (secure by default)+OPAMP_TLS_INSECURE_SKIP_VERIFY=false++# Require client certificates for mutual TLS+# Enabled by default for enhanced security+# Default: true (secure by default)+OPAMP_TLS_REQUIRE_CLIENT_CERT=true++# TLS Version Configuration+# Minimum and maximum TLS versions (1.0, 1.1, 1.2, 1.3)+OPAMP_TLS_MIN_VERSION=1.2+OPAMP_TLS_MAX_VERSION=1.3++# Logging Configuration+# Options: debug, info, warn, error+OPAMP_LOG_LEVEL=info++# =============================================================================+# Certificate Configuration (Advanced)+# =============================================================================+# Certificate directory path (usually managed by Docker)+# OPAMP_CERTS_DIR=/app/opamp/certs++# =============================================================================+# Production Deployment Example (Default)+# =============================================================================+# Production settings are now the default for enhanced security:+#+# OPAMP_ENVIRONMENT=production # Default+# OPAMP_TLS_INSECURE_SKIP_VERIFY=false # Default+# OPAMP_TLS_REQUIRE_CLIENT_CERT=true # Default+# OPAMP_TLS_MIN_VERSION=1.2 # Default+# OPAMP_TLS_MAX_VERSION=1.3 # Default+# OPAMP_LOG_LEVEL=info # Default++# =============================================================================+# Development Deployment Example+# =============================================================================+# For development, override these settings for relaxed security:+#+# OPAMP_ENVIRONMENT=development+# OPAMP_TLS_INSECURE_SKIP_VERIFY=true+# OPAMP_TLS_REQUIRE_CLIENT_CERT=false+# OPAMP_LOG_LEVEL=debugdiff --git a/src/Dockerfile b/src/Dockerfilenew file mode 100644index 00000000..ef29abbf--- /dev/null+++ b/src/Dockerfile@@ -0,0 +1,118 @@+# Use an alpine as a base image+FROM alpine AS builder++# Build arguments for configurable versions+ARG OTEL_VERSION=v0.132.0+ARG OPAMP_SUPERVISOR_VERSION=v0.132.0+ARG TARGETARCH=arm64++# Installing node and npm+RUN apk add --update nodejs npm+++# Installing extra packages+RUN apk add --no-cache python3 py3-pip pipx rust cargo build-base+++# Create a virtual environment+RUN python3 -m venv /app/client/venv++# Install litellm inside the virtual environment+RUN /app/client/venv/bin/pip install --no-cache-dir litellm++RUN find /app/client/venv -name '*.pyc' -delete && \+ find /app/client/venv -name '__pycache__' -type d -exec rm -r {} ++++# Set the working directory in the container+WORKDIR /app/client++# Copy package.json and package-lock.json to the working directory & the rest of the application code+COPY ./client/ .++# Install dependencies & Build the Next.js application+RUN npm install && npm run build+++# Opamp server build from source+FROM golang:1.25-alpine AS go-builder++# Set working directory for opamp-server+WORKDIR /app/opamp-server++# Copy the rest of the opamp-server source code+COPY ./opamp-server/ ./++# Build the opamp-server binary+RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o opamp-server .++# OpenTelemetry Collector Contrib download+FROM alpine AS otel-downloader++# Accept build arguments+ARG OTEL_VERSION=v0.132.4+ARG OPAMP_SUPERVISOR_VERSION=v0.126.0+ARG TARGETARCH=arm64++# Install curl for downloading binaries+RUN apk add --no-cache curl++# Set working directory+WORKDIR /tmp++# Download OpenTelemetry Collector Contrib+RUN curl -LO "https://github.com/open-telemetry/opentelemetry-collector-releases/releases/download/${OTEL_VERSION}/otelcol-contrib_${OTEL_VERSION#v}_linux_${TARGETARCH}.tar.gz" && \+ tar -xzf "otelcol-contrib_${OTEL_VERSION#v}_linux_${TARGETARCH}.tar.gz" && \+ chmod +x otelcol-contrib++# Download OpAMP Supervisor+RUN curl --proto '=https' --tlsv1.2 -fL -o opampsupervisor \+ "https://github.com/open-telemetry/opentelemetry-collector-releases/releases/download/cmd%2Fopampsupervisor%2F${OPAMP_SUPERVISOR_VERSION}/opampsupervisor_${OPAMP_SUPERVISOR_VERSION#v}_linux_${TARGETARCH}" && \+ chmod +x opampsupervisor+++# Use a smaller image for production+FROM alpine++# Installing extra packages+RUN apk add nodejs bash openssl python3+++# Set the working directory in the container+WORKDIR /app/client++# Copy only necessary files from the builder stage++# Copying python virtual environment+COPY --from=builder /app/client/venv ./venv+# Copying the standalone next.js build+COPY --from=builder /app/client/.next/standalone ./+# Standalone build doesn't copy public, static, prisma, scripts+COPY --from=builder /app/client/public ./public+COPY --from=builder /app/client/.next/static ./.next/static+COPY --from=builder /app/client/prisma ./prisma+COPY --from=builder /app/client/scripts ./scripts+# Copying prisma client, prisma and prisma cli (.bin) from builder stage+COPY --from=builder /app/client/node_modules/@prisma ./node_modules/@prisma+COPY --from=builder /app/client/node_modules/.bin ./node_modules/.bin+COPY --from=builder /app/client/node_modules/prisma ./node_modules/prisma++# Copy the built opamp-server binary from go-builder stage+COPY --from=go-builder /app/opamp-server/opamp-server /app/opamp/opamp-server+COPY --from=go-builder /app/opamp-server/certs /app/opamp/certs+COPY --from=go-builder /app/opamp-server/setup-supervisor.sh /app/opamp/setup-supervisor.sh++# Copy OpenTelemetry Collector and OpAMP Supervisor binaries+# Place otelcol-contrib at the path expected by supervisor configuration file+COPY --from=otel-downloader /tmp/otelcol-contrib /app/opamp/otelcontribcol+COPY --from=otel-downloader /tmp/opampsupervisor /app/opamp/opampsupervisor++# Execute entrypoint script to generate NextAuth.js secret and run commands+RUN chmod +x ./scripts/entrypoint.sh /app/opamp/otelcontribcol /app/opamp/opampsupervisor /app/opamp/opamp-server /app/opamp/setup-supervisor.sh+RUN chmod -R u=rwX,go= /app/opamp/certs++# Expose the port that Next.js will run on+EXPOSE ${DOCKER_PORT:-3000}++# Run the entrypoint script+CMD ["/app/client/scripts/entrypoint.sh"]\ No newline at end of filediff --git a/src/client/.env.example b/src/client/.env.exampleindex 69aa0028..29396a71 100644--- a/src/client/.env.example+++ b/src/client/.env.example@@ -5,7 +5,7 @@ GITHUB_CLIENT_ID=GITHUB_CLIENT_SECRET=-# Generate NEXTAUTH_SECRET by running command : `openssl rand -base64 32` on your terminal+# Generate NEXTAUTH_SECRET by running command : `node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"` on your terminalNEXTAUTH_SECRET=NEXTAUTH_URL=http://localhost:3000/diff --git a/src/client/Dockerfile b/src/client/Dockerfiledeleted file mode 100644index d882baa9..00000000--- a/src/client/Dockerfile+++ /dev/null@@ -1,68 +0,0 @@-# Use an alpine as a base image-FROM alpine AS builder--# Installing node and npm-RUN apk add --update nodejs npm---# Installing extra packages-RUN apk add --no-cache python3 py3-pip pipx rust cargo build-base---# Create a virtual environment-RUN python3 -m venv /app/client/venv--# Install litellm inside the virtual environment-RUN /app/client/venv/bin/pip install --no-cache-dir litellm--RUN find /app/client/venv -name '*.pyc' -delete && \- find /app/client/venv -name '__pycache__' -type d -exec rm -r {} +---# Set the working directory in the container-WORKDIR /app/client--# Copy package.json and package-lock.json to the working directory & the rest of the application code-COPY . .--# Install dependencies & Build the Next.js application-RUN npm install && npm run build---# Use a smaller image for production-FROM alpine--# Installing extra packages-RUN apk add nodejs bash openssl python3---# Set the working directory in the container-WORKDIR /app/client--# Copy only necessary files from the builder stage--# Copying python virtual environment-COPY --from=builder /app/client/venv ./venv-# Copying the standalone next.js build-COPY --from=builder /app/client/.next/standalone ./-# Standalone build doesn't copy public, static, prisma, scripts-COPY --from=builder /app/client/public ./public-COPY --from=builder /app/client/.next/static ./.next/static-COPY --from=builder /app/client/prisma ./prisma-COPY --from=builder /app/client/scripts ./scripts-# Copying prisma client, prisma and prisma cli (.bin) from builder stage-COPY --from=builder /app/client/node_modules/@prisma ./node_modules/@prisma-COPY --from=builder /app/client/node_modules/.bin ./node_modules/.bin-COPY --from=builder /app/client/node_modules/prisma ./node_modules/prisma--# Execute entrypoint script to generate NextAuth.js secret and run commands-RUN chmod +x ./scripts/entrypoint.sh--# Install Prisma globally-# RUN npm install -g [email protected]--# Expose the port that Next.js will run on-EXPOSE ${DOCKER_PORT:-3000}--# Run the entrypoint script-CMD ["/app/client/scripts/entrypoint.sh"]diff --git a/src/client/package-lock.json b/src/client/package-lock.jsonindex b2809745..c9d31b3f 100644--- a/src/client/package-lock.json+++ b/src/client/package-lock.json@@ -1,12 +1,12 @@{"name": "openlit",- "version": "1.14.7",+ "version": "1.15.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "openlit",- "version": "1.14.7",+ "version": "1.15.0","dependencies": {"@anthropic-ai/sdk": "^0.21.1","@clickhouse/client": "^1.1.0",@@ -55,15 +55,16 @@"next-themes": "^0.3.0","openai": "^4.50.0","posthog-js": "^1.261.7",- "posthog-node": "^5.8.2","react": "^18.3.1","react-beautiful-dnd": "^13.1.1","react-day-picker": "^8.10.1","react-dom": "^18.3.1","react-grid-layout": "^1.5.1","react-markdown": "^10.1.0",+ "react-resizable-panels": "^3.0.5","react-syntax-highlighter": "^15.5.0","recharts": "^2.12.7",+ "sharp": "^0.34.5","sonner": "^1.5.0","sqlstring": "^2.3.3","tailwind-merge": "^2.2.2",@@ -1206,6 +1207,15 @@"zustand": "^4.0.0"}},+ "node_modules/@emnapi/runtime": {+ "version": "1.7.0",+ "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.7.0.tgz",+ "integrity": "sha512-oAYoQnCYaQZKVS53Fq23ceWMRxq5EhQsE0x0RdQ55jT7wagMu5k+fS39v1fiSLrtrLQlXwVINenqhLMtTrV/1Q==",+ "optional": true,+ "dependencies": {+ "tslib": "^2.4.0"+ }+ },"node_modules/@emotion/babel-plugin": {"version": "11.11.0","resolved": "https://registry.npmjs.org/@emotion/babel-plugin/-/babel-plugin-11.11.0.tgz",@@ -1492,6 +1502,446 @@"deprecated": "Use @eslint/object-schema instead","dev": true},+ "node_modules/@img/colour": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.0.0.tgz",+ "integrity": "sha512-A5P/LfWGFSl6nsckYtjw9da+19jB8hkJ6ACTGcDfEJ0aE+l2n2El7dsVM7UVHZQ9s2lmYMWlrS21YLy2IR1LUw==",+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@img/sharp-darwin-arm64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.34.5.tgz",+ "integrity": "sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w==",+ "cpu": [+ "arm64"+ ],+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-darwin-arm64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-darwin-x64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.34.5.tgz",+ "integrity": "sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw==",+ "cpu": [+ "x64"+ ],+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-darwin-x64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-libvips-darwin-arm64": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.2.4.tgz",+ "integrity": "sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g==",+ "cpu": [+ "arm64"+ ],+ "optional": true,+ "os": [+ "darwin"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-darwin-x64": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.2.4.tgz",+ "integrity": "sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg==",+ "cpu": [+ "x64"+ ],+ "optional": true,+ "os": [+ "darwin"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-arm": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.2.4.tgz",+ "integrity": "sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==",+ "cpu": [+ "arm"+ ],+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-arm64": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.2.4.tgz",+ "integrity": "sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==",+ "cpu": [+ "arm64"+ ],+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-ppc64": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.2.4.tgz",+ "integrity": "sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==",+ "cpu": [+ "ppc64"+ ],+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-riscv64": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.2.4.tgz",+ "integrity": "sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==",+ "cpu": [+ "riscv64"+ ],+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-s390x": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.2.4.tgz",+ "integrity": "sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==",+ "cpu": [+ "s390x"+ ],+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-x64": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.2.4.tgz",+ "integrity": "sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==",+ "cpu": [+ "x64"+ ],+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linuxmusl-arm64": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.2.4.tgz",+ "integrity": "sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==",+ "cpu": [+ "arm64"+ ],+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linuxmusl-x64": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.2.4.tgz",+ "integrity": "sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==",+ "cpu": [+ "x64"+ ],+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-linux-arm": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.34.5.tgz",+ "integrity": "sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==",+ "cpu": [+ "arm"+ ],+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-arm": "1.2.4"+ }+ },+ "node_modules/@img/sharp-linux-arm64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.34.5.tgz",+ "integrity": "sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==",+ "cpu": [+ "arm64"+ ],+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-arm64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-linux-ppc64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.34.5.tgz",+ "integrity": "sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==",+ "cpu": [+ "ppc64"+ ],+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-ppc64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-linux-riscv64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.34.5.tgz",+ "integrity": "sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==",+ "cpu": [+ "riscv64"+ ],+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-riscv64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-linux-s390x": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.34.5.tgz",+ "integrity": "sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==",+ "cpu": [+ "s390x"+ ],+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-s390x": "1.2.4"+ }+ },+ "node_modules/@img/sharp-linux-x64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.34.5.tgz",+ "integrity": "sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==",+ "cpu": [+ "x64"+ ],+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-x64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-linuxmusl-arm64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.34.5.tgz",+ "integrity": "sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==",+ "cpu": [+ "arm64"+ ],+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linuxmusl-arm64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-linuxmusl-x64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.34.5.tgz",+ "integrity": "sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==",+ "cpu": [+ "x64"+ ],+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linuxmusl-x64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-wasm32": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.34.5.tgz",+ "integrity": "sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==",+ "cpu": [+ "wasm32"+ ],+ "optional": true,+ "dependencies": {+ "@emnapi/runtime": "^1.7.0"+ },+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-win32-arm64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.34.5.tgz",+ "integrity": "sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g==",+ "cpu": [+ "arm64"+ ],+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-win32-ia32": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.34.5.tgz",+ "integrity": "sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg==",+ "cpu": [+ "ia32"+ ],+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-win32-x64": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.34.5.tgz",+ "integrity": "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw==",+ "cpu": [+ "x64"+ ],+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },"node_modules/@isaacs/cliui": {"version": "8.0.2","resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz",@@ -6054,9 +6504,9 @@"integrity": "sha512-C1HsxuPCY/5opR55G5/WNzyEGDWFVG+6GLrA+fW/sCTcP6A6NTjUP2AK7B8n2PyFs90kDG2qzwm8LMheADku6A=="},"node_modules/cross-spawn": {- "version": "7.0.3",- "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz",- "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==",+ "version": "7.0.6",+ "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",+ "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==","dependencies": {"path-key": "^3.1.0","shebang-command": "^2.0.0",@@ -6363,6 +6813,14 @@"node": ">=6"}},+ "node_modules/detect-libc": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",+ "engines": {+ "node": ">=8"+ }+ },"node_modules/detect-node-es": {"version": "1.1.0","resolved": "https://registry.npmjs.org/detect-node-es/-/detect-node-es-1.1.0.tgz",@@ -10316,17 +10774,6 @@}}},- "node_modules/posthog-node": {- "version": "5.8.2",- "resolved": "https://registry.npmjs.org/posthog-node/-/posthog-node-5.8.2.tgz",- "integrity": "sha512-z3XRvYwnc3T/1999FKzv16YTpxERQqLunULl2vkOPfgbCXUGNyJWLgcbTcED2ZIDE11jjZhrSph4De6OSMLphw==",- "dependencies": {- "@posthog/core": "1.0.2"- },- "engines": {- "node": ">=20"- }- },"node_modules/preact": {"version": "10.22.0","resolved": "https://registry.npmjs.org/preact/-/preact-10.22.0.tgz",@@ -10691,6 +11138,16 @@"react": ">= 16.3"}},+ "node_modules/react-resizable-panels": {+ "version": "3.0.5",+ "resolved": "https://registry.npmjs.org/react-resizable-panels/-/react-resizable-panels-3.0.5.tgz",+ "integrity": "sha512-3z1yN25DMTXLg2wfyFrW32r5k4WEcUa3F7cJ2EgtNK07lnOs4mpM8yWLGunCpkhcQRwJX4fqoLcIh/pHPxzlmQ==",+ "license": "MIT",+ "peerDependencies": {+ "react": "^16.14.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc",+ "react-dom": "^16.14.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc"+ }+ },"node_modules/react-smooth": {"version": "4.0.1","resolved": "https://registry.npmjs.org/react-smooth/-/react-smooth-4.0.1.tgz",@@ -11108,10 +11565,9 @@}},"node_modules/semver": {- "version": "7.6.2",- "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.2.tgz",- "integrity": "sha512-FNAIBWCx9qcRhoHcgcJ0gvU7SN1lYU2ZXuSfl04bSC5OpvDHFyJCjdNHomPXxjQlCBU67YW64PzY7/VIEH7F2w==",- "dev": true,+ "version": "7.7.3",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz",+ "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==","bin": {"semver": "bin/semver.js"},@@ -11150,6 +11606,49 @@"node": ">= 0.4"}},+ "node_modules/sharp": {+ "version": "0.34.5",+ "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.34.5.tgz",+ "integrity": "sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg==",+ "hasInstallScript": true,+ "dependencies": {+ "@img/colour": "^1.0.0",+ "detect-libc": "^2.1.2",+ "semver": "^7.7.3"+ },+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-darwin-arm64": "0.34.5",+ "@img/sharp-darwin-x64": "0.34.5",+ "@img/sharp-libvips-darwin-arm64": "1.2.4",+ "@img/sharp-libvips-darwin-x64": "1.2.4",+ "@img/sharp-libvips-linux-arm": "1.2.4",+ "@img/sharp-libvips-linux-arm64": "1.2.4",+ "@img/sharp-libvips-linux-ppc64": "1.2.4",+ "@img/sharp-libvips-linux-riscv64": "1.2.4",+ "@img/sharp-libvips-linux-s390x": "1.2.4",+ "@img/sharp-libvips-linux-x64": "1.2.4",+ "@img/sharp-libvips-linuxmusl-arm64": "1.2.4",+ "@img/sharp-libvips-linuxmusl-x64": "1.2.4",+ "@img/sharp-linux-arm": "0.34.5",+ "@img/sharp-linux-arm64": "0.34.5",+ "@img/sharp-linux-ppc64": "0.34.5",+ "@img/sharp-linux-riscv64": "0.34.5",+ "@img/sharp-linux-s390x": "0.34.5",+ "@img/sharp-linux-x64": "0.34.5",+ "@img/sharp-linuxmusl-arm64": "0.34.5",+ "@img/sharp-linuxmusl-x64": "0.34.5",+ "@img/sharp-wasm32": "0.34.5",+ "@img/sharp-win32-arm64": "0.34.5",+ "@img/sharp-win32-ia32": "0.34.5",+ "@img/sharp-win32-x64": "0.34.5"+ }+ },"node_modules/shebang-command": {"version": "2.0.0","resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",diff --git a/src/client/package.json b/src/client/package.jsonindex 3009c23d..b86adf02 100644--- a/src/client/package.json+++ b/src/client/package.json@@ -1,6 +1,6 @@{"name": "openlit",- "version": "1.14.7",+ "version": "1.15.0","private": true,"scripts": {"dev": "next dev",@@ -57,15 +57,16 @@"next-themes": "^0.3.0","openai": "^4.50.0","posthog-js": "^1.261.7",- "posthog-node": "^5.8.2","react": "^18.3.1","react-beautiful-dnd": "^13.1.1","react-day-picker": "^8.10.1","react-dom": "^18.3.1","react-grid-layout": "^1.5.1","react-markdown": "^10.1.0",+ "react-resizable-panels": "^3.0.5","react-syntax-highlighter": "^15.5.0","recharts": "^2.12.7",+ "sharp": "^0.34.5","sonner": "^1.5.0","sqlstring": "^2.3.3","tailwind-merge": "^2.2.2",diff --git a/src/client/scripts/entrypoint.sh b/src/client/scripts/entrypoint.shold mode 100755new mode 100644index 8fe35051..eff33688--- a/src/client/scripts/entrypoint.sh+++ b/src/client/scripts/entrypoint.sh@@ -30,6 +30,93 @@ prisma db seed# Run crond in the backgroundcrond &+# Set OpAMP environment variables for entrypoint+export OPAMP_ENVIRONMENT=${OPAMP_ENVIRONMENT:-production}+export OPAMP_CERTS_DIR=${OPAMP_CERTS_DIR:-/app/opamp/certs}+export OPAMP_TLS_INSECURE_SKIP_VERIFY=${OPAMP_TLS_INSECURE_SKIP_VERIFY:-false}++echo "OpAMP Configuration:"+echo " Environment: $OPAMP_ENVIRONMENT"+echo " Certificates Directory: $OPAMP_CERTS_DIR"+echo " TLS Insecure Skip Verify: $OPAMP_TLS_INSECURE_SKIP_VERIFY"++# Generate certificates using enhanced script+echo "Generating OpAMP certificates..."+chmod +x /app/opamp/certs/clear.sh+chmod +x /app/opamp/certs/generate.sh+cd /app/opamp/certs++# Generate certificates with proper logging+if ./generate.sh > /var/log/certs.log 2>&1; then+ echo "✅ Certificates generated successfully"+else+ echo "❌ Certificate generation failed, check /var/log/certs.log"+ cat /var/log/certs.log+fi++# Generate supervisor configuration based on environment+echo "Configuring OpAMP supervisor for $OPAMP_ENVIRONMENT environment..."+cd /app/opamp++# Create supervisor configuration dynamically+cat > /etc/otel/supervisor-dynamic.yaml << EOF+server:+ endpoint: wss://localhost:4320/v1/opamp+ tls:+EOF++if [[ "$OPAMP_ENVIRONMENT" == "production" ]]; then+ cat >> /etc/otel/supervisor-dynamic.yaml << EOF+ insecure_skip_verify: false+ ca_file: /app/opamp/certs/cert/ca.cert.pem+ cert_file: /app/opamp/certs/client/client.cert.pem+ key_file: /app/opamp/certs/client/client.key.pem+EOF+ echo " Production mode: Using CA certificate verification with client certificates"+else+ cat >> /etc/otel/supervisor-dynamic.yaml << EOF+ insecure_skip_verify: true+EOF+ echo " Development mode: Skipping certificate verification"+fi++cat >> /etc/otel/supervisor-dynamic.yaml << EOF++agent:+ executable: /app/opamp/otelcontribcol+ config_files:+ - /etc/otel/otel-collector-config.yaml++capabilities:+ accepts_remote_config: true+ reports_effective_config: true+ reports_own_metrics: false+ reports_own_logs: true+ reports_own_traces: false+ reports_health: true+ reports_remote_config: true++storage:+ directory: ./storage+EOF++echo "✅ Supervisor configuration generated"++# Starting OpAMP Server+echo "Starting OpAMP Server..."+/app/opamp/opamp-server &+OPAMP_SERVER_PID=$!++# Wait a moment for the server to start+sleep 2++# Starting Supervisor for the OTEL Collector+echo "Starting OpAMP Supervisor..."+/app/opamp/opampsupervisor --config=/etc/otel/supervisor-dynamic.yaml &+SUPERVISOR_PID=$!+++# Starting the OpenLIT UI Serverexport PORT=${DOCKER_PORT:-3000}# Start the Next.js application-exec node --max_old_space_size=512 server.js+exec node --max_old_space_size=512 /app/client/server.js\ No newline at end of filediff --git a/src/client/src/app/(playground)/fleet-hub/[id]/agent.tsx b/src/client/src/app/(playground)/fleet-hub/[id]/agent.tsxnew file mode 100644index 00000000..b2c8888c--- /dev/null+++ b/src/client/src/app/(playground)/fleet-hub/[id]/agent.tsx@@ -0,0 +1,169 @@+"use client"++import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"+import { Badge } from "@/components/ui/badge"+import { Clock, HeartPulse, Package, Server } from "lucide-react"+import { Agent } from "@/types/fleet-hub"+import { formatDate } from "@/utils/date"+import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "@/components/ui/accordion"+import { cn } from "@/lib/utils"+import { CodeEditor } from "@/components/(playground)/manage-dashboard/board-creator"+import { useCallback, useEffect, useState } from "react"+import { Button } from "@/components/ui/button"+import useFetchWrapper from "@/utils/hooks/useFetchWrapper"+import { jsonStringify } from "@/utils/json"+import { consoleLog } from "@/utils/log"+import { getAttributeValue } from "@/helpers/client/fleet-hub"+import { usePageHeader } from "@/selectors/page"+import { usePostHog } from "posthog-js/react"+import { CLIENT_EVENTS } from "@/constants/events"++interface AgentDetailProps {+ agent: Agent,+ fetchAgentInfo: () => void+}++const InfoItem = ({ label, value, mono = false }: { label: string; value: string; mono?: boolean }) => (+ <div className="space-y-1">+ <p className="text-xs text-muted-foreground">{label}</p>+ <p className={cn("text-sm font-medium", mono && "font-mono")}>{value}</p>+ </div>+);++export default function AgentDetail({ agent, fetchAgentInfo }: AgentDetailProps) {+ const isUnhealthy = !agent.Status.health.healthy;+ const { setHeader } = usePageHeader();++ useEffect(() => {+ setHeader({+ title: getAttributeValue(agent, "Status.agent_description.identifying_attributes", "service.name"),+ breadcrumbs: [+ {+ title: "Fleet Hub",+ href: "/fleet-hub"+ }+ ]+ })+ }, [agent]);++ return (+ <div className="space-y-6 overflow-auto w-full flex flex-col grow">+ <Card>+ <CardHeader className="flex flex-row items-center gap-8 space-y-0 p-4">+ <CardTitle>{getAttributeValue(agent, "Status.agent_description.identifying_attributes", "service.name")}</CardTitle>+ </CardHeader>+ <CardContent className="p-4 pt-0">+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">+ <div className="flex items-center gap-3 p-3 rounded-lg bg-stone-200/50 dark:bg-stone-700/50">+ <Package className="h-4 w-4 text-primary" />+ <div>+ <p className="text-xs text-muted-foreground">Version</p>+ <p className="font-mono text-sm font-medium">{getAttributeValue(agent, "Status.agent_description.identifying_attributes", "service.version")}</p>+ </div>+ </div>+ <div className="flex items-center gap-3 p-3 rounded-lg bg-stone-200/50 dark:bg-stone-700/50">+ <Clock className="h-4 w-4 text-primary" />+ <div>+ <p className="text-xs text-muted-foreground">Started At</p>+ <p className="font-mono text-sm font-medium">{formatDate(agent.StartedAt, { time: true })}</p>+ </div>+ </div>+ <div className="flex items-center gap-3 p-3 rounded-lg bg-stone-200/50 dark:bg-stone-700/50">+ <Server className="h-4 w-4 text-primary" />+ <div>+ <p className="text-xs text-muted-foreground">Host Name</p>+ <p className="font-mono text-sm font-medium">{getAttributeValue(agent, "Status.agent_description.non_identifying_attributes", "host.name")}</p>+ </div>+ </div>+ <div className="flex items-center gap-3 p-3 rounded-lg bg-stone-200/50 dark:bg-stone-700/50">+ <HeartPulse className="h-4 w-4 text-primary" />+ <div>+ <p className="text-xs text-muted-foreground">Health Status</p>+ <p className={`font-mono text-xs font-medium px-2 text-center ${agent.Status.health.healthy ? "bg-green-500 text-white dark:bg-green-500 dark:text-white" : "bg-red-500 text-white dark:bg-red-500 dark:text-white"}`}>{agent.Status.health.status || "Error"}</p>+ </div>+ </div>+ {+ isUnhealthy && agent.Status.health.last_error ? (+ <div className="bg-red-500 text-white text-center text-xs p-2 col-span-4">{agent.Status.health.last_error} </div>+ ) : null+ }+ </div>+ </CardContent>+ <CardFooter className="p-0">+ <Accordion type="single" collapsible className="w-full">+ <AccordionItem value="item-1" className="flex flex-col-reverse w-full border-0">+ <AccordionTrigger className="p-0 flex w-full items-center gap-2 justify-center py-1 bg-stone-200/60 dark:bg-stone-800 text-xs text-stone-500 dark:text-stone-500">Show more</AccordionTrigger>+ <AccordionContent className="p-4 pt-0">+ <div className="pt-4 border-t border-stone-200 dark:border-stone-700 space-y-4">+ <h4 className="font-semibold text-sm">Detailed Information</h4>+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">+ {agent.Status.agent_description.identifying_attributes.map((attr, index) => (+ <InfoItem key={index} label={attr.key} value={attr.value.Value.StringValue} />+ ))}+ {agent.Status.agent_description.non_identifying_attributes.map((attr, index) => (+ <InfoItem key={index} label={attr.key} value={attr.value.Value.StringValue} />+ ))}+ </div>++ <h4 className="font-semibold text-sm">Component Health Status</h4>+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">+ {Object.entries(agent.Status.health.component_health_map || {}).map(([component, health]) => (+ <div key={component} className={`p-4 rounded-lg border ${health.healthy ? "bg-green-500/10 border-green-500/20" : "bg-red-500/10 border-red-500/20"}`}>+ <p className="text-xs text-muted-foreground mb-1">{component}</p>+ <Badge variant={health.healthy ? "default" : "destructive"}>{health.status}</Badge>+ </div>+ ))}+ </div>+ </div>+ </AccordionContent>+ </AccordionItem>+ </Accordion>+ </CardFooter>+ </Card>+ <ConfigDetails agent={agent} fetchAgentInfo={fetchAgentInfo} />+ </div>+ )+}++function ConfigDetails({ agent, fetchAgentInfo }: { agent: Agent, fetchAgentInfo: () => void }) {+ const [yamlInput, setYamlInput] = useState<string>(agent.CustomInstanceConfig || "");+ const { fireRequest } = useFetchWrapper();+ const posthog = usePostHog();++ const handleYamlChange = (value: string | undefined) => {+ setYamlInput(value || "");+ };++ const onSave = useCallback(() => {+ fireRequest({+ requestType: "POST",+ url: `/api/fleet-hub/${agent.InstanceIdStr}/config`,+ body: jsonStringify({+ config: yamlInput,+ }),+ successCb: (resp) => {+ fetchAgentInfo();+ posthog?.capture(CLIENT_EVENTS.FLEET_HUB_AGENT_CONFIG_SAVED, {+ agentId: agent.InstanceIdStr,+ });+ },+ failureCb: (resp) => {+ consoleLog(resp);+ }+ })+ }, [yamlInput, agent.InstanceIdStr]);++ return (+ <div className="grid grid-cols-2 gap-3 grow text-stone-700 dark:text-stone-300">+ <div className="flex flex-col gap-3">+ <h4 className="font-semibold text-sm">Custom Configuration</h4>+ <CodeEditor value={yamlInput} onChange={handleYamlChange} language="yaml" />+ <Button variant="default" size={"sm"} className="rounded-none py-1 h-auto bg-primary/80 hover:bg-primary disabled:bg-stone-400 disabled:dark:text-stone-700 shrink-0" disabled={agent.CustomInstanceConfig === yamlInput} onClick={onSave}>Save</Button>+ </div>+ <div className="flex flex-col gap-3">+ <h4 className="font-semibold text-sm">Effective Configuration (readonly)</h4>+ <CodeEditor value={agent.EffectiveConfig} onChange={() => { }} language="yaml" readOnly />+ </div>+ </div>+ )+}\ No newline at end of filediff --git a/src/client/src/app/(playground)/fleet-hub/[id]/page.tsx b/src/client/src/app/(playground)/fleet-hub/[id]/page.tsxnew file mode 100644index 00000000..f80ad60c--- /dev/null+++ b/src/client/src/app/(playground)/fleet-hub/[id]/page.tsx@@ -0,0 +1,47 @@+"use client";+import { Agent } from "@/types/fleet-hub";+import AgentDetail from "./agent";+import useFetchWrapper from "@/utils/hooks/useFetchWrapper";+import { useCallback, useEffect } from "react";+import { useParams } from "next/navigation";+import Loader from "@/components/common/loader";+import { usePostHog } from "posthog-js/react";+import { CLIENT_EVENTS } from "@/constants/events";++export default function AgentPage() {+ const { fireRequest, data, isLoading } = useFetchWrapper<Agent>();+ const params = useParams();+ const posthog = usePostHog();+++ const fetchAgentInfo = useCallback(async () => {+ fireRequest({+ requestType: "GET",+ url: `/api/fleet-hub/${params.id}`,+ responseDataKey: "data",+ successCb: (response) => {+ if (response?.data) {+ posthog?.capture(CLIENT_EVENTS.FLEET_HUB_AGENT_VIEWED, {+ agentId: params.id,+ });+ }+ },+ });+ }, [params.id]);++ useEffect(() => {+ fetchAgentInfo();+ }, [fetchAgentInfo]);++ if (isLoading && !data) return (+ <div className="flex items-center justify-center w-full h-full">+ <Loader />+ </div>+ );++ if (!isLoading && !data) {+ return null;+ }++ return <AgentDetail agent={data!} fetchAgentInfo={fetchAgentInfo} />;+}\ No newline at end of filediff --git a/src/client/src/app/(playground)/fleet-hub/list.tsx b/src/client/src/app/(playground)/fleet-hub/list.tsxnew file mode 100644index 00000000..74a874c5--- /dev/null+++ b/src/client/src/app/(playground)/fleet-hub/list.tsx@@ -0,0 +1,153 @@+"use client";+import DataTable from "@/components/data-table/table";+import { Agent } from "@/types/fleet-hub";++import { Badge } from "@/components/ui/badge";+import { Columns } from "@/components/data-table/columns";+import { useRouter } from "next/navigation";+import { useRootStore } from "@/store";+import { getVisibilityColumnsOfPage } from "@/selectors/page";+import VisibilityColumns from "@/components/(playground)/filter/visibility-columns";+import { getAttributeValue } from "@/helpers/client/fleet-hub";+import LinuxSvg from "@/components/svg/linux";+import WindowsSvg from "@/components/svg/windows";+import { formatDate } from "@/utils/date";+import MacSvg from "@/components/svg/mac";++const osTypeMap = {+ linux: <LinuxSvg />,+ windows: <WindowsSvg />,+ mac: <MacSvg />,+} as const;++const columns: Columns<string, Agent> = {+ id: {+ header: () => "ID",+ cell: ({ row }) => {+ return (<div+ className="block items-center overflow-hidden text-ellipsis whitespace-nowrap"+ title={row.InstanceIdStr}+ >+ {row.InstanceIdStr}+ </div>)+ },+ },+ name: {+ header: () => "Name",+ cell: ({ row }) => {+ const serviceName = getAttributeValue(row, "Status.agent_description.identifying_attributes", "service.name")+ return (<div+ className="block items-center overflow-hidden text-ellipsis whitespace-nowrap"+ title={serviceName}+ >+ {serviceName}+ </div>)+ },+ enableHiding: false,+ },+ version: {+ header: () => "Version",+ cell: ({ row }) => {+ const serviceVersion = getAttributeValue(+ row,+ "Status.agent_description.identifying_attributes",+ "service.version",+ )+ return (+ <div className="flex space-x-2 items-center" title={serviceVersion}>+ <span className="truncate font-medium">{serviceVersion}</span>+ </div>+ );+ },+ enableHiding: true,+ },+ os: {+ header: () => "Operating System",+ cell: ({ row }) => {+ const osType = getAttributeValue(+ row,+ "Status.agent_description.non_identifying_attributes",+ "os.type",+ )+ return (+ <div className="flex space-x-2 items-center" title={osType}>+ <span className="truncate font-medium">{osType in osTypeMap ? osTypeMap[osType as keyof typeof osTypeMap] : osType}</span>+ </div>+ );+ },+ enableHiding: true,+ },+ startedAt: {+ header: () => "Started At",+ cell: ({ row }) => {+ return (+ <div+ className="block items-center overflow-hidden text-ellipsis whitespace-nowrap"+ title={row.StartedAt}+ >+ {formatDate(row.StartedAt, { time: true })}+ </div>+ );+ },+ enableHiding: true,+ },+ status: {+ header: () => "Status",+ cell: ({ row }) => {+ return (+ <Badge variant={row.Status.health.healthy ? "default" : "destructive"} className={`${row.Status.health.healthy ? "bg-green-500 text-white" : "bg-red-500 text-white"}`}>+ {row.Status.health.status || "StatusError"}+ </Badge>+ );+ },+ enableHiding: false,+ },+ hostArchitecture: {+ header: () => "Host Architecture",+ cell: ({ row }) => {+ const hostArchitecture = getAttributeValue(+ row,+ "Status.agent_description.non_identifying_attributes",+ "host.arch",+ )+ return (+ <div className="flex space-x-2 items-center" title={hostArchitecture}>+ <span className="truncate font-medium">{hostArchitecture}</span>+ </div>+ );+ },+ enableHiding: true,+ }+};+++export default function List({ agents, isLoading, isFetched }: {+ agents: Agent[];+ isLoading: boolean;+ isFetched: boolean;+}) {+ const visibilityColumns = useRootStore((state) =>+ getVisibilityColumnsOfPage(state, "fleethub")+ );+ const router = useRouter()++ const handleClick = (row: Agent) => {+ router.push(`/fleet-hub/${row.InstanceIdStr}`)+ }++ return (+ <div className="flex flex-col w-full h-full gap-3">+ <div className="flex items-end justify-end w-full">+ <VisibilityColumns columns={columns} pageName={"fleethub"} />+ </div>+ <DataTable+ columns={columns}+ data={agents}+ isFetched={isFetched}+ isLoading={isLoading}+ visibilityColumns={visibilityColumns}+ onClick={handleClick}+ />+ </div>+ );+}diff --git a/src/client/src/app/(playground)/fleet-hub/page.tsx b/src/client/src/app/(playground)/fleet-hub/page.tsxnew file mode 100644index 00000000..2cc7c025--- /dev/null+++ b/src/client/src/app/(playground)/fleet-hub/page.tsx@@ -0,0 +1,55 @@+"use client";+import { useEffect } from "react";+import useFetchWrapper from "@/utils/hooks/useFetchWrapper";+import { Agent } from "@/types/fleet-hub";+import List from "./list";+import OpenTelemetrySvg from "@/components/svg/opentelemetry";+import { usePostHog } from "posthog-js/react";+import { CLIENT_EVENTS } from "@/constants/events";++export default function Opamp() {+ const { fireRequest, data, isLoading, isFetched } = useFetchWrapper<Agent[]>();+ const posthog = usePostHog();++ useEffect(() => {+ fireRequest({+ requestType: "GET",+ url: `/api/fleet-hub`,+ responseDataKey: "data",+ successCb: (response) => {+ if (response?.data) {+ posthog?.capture(CLIENT_EVENTS.FLEET_HUB_VIEWED, {+ count: response?.data?.length || 0,+ });+ }+ },+ });+ }, []);++ return (+ <div className="flex flex-col w-full gap-3">+ {/* Feature Description Section */}+ <div className="border dark:border-stone-800 rounded-lg p-6">+ <div className="flex items-start space-x-4">+ <div className="flex-shrink-0">+ <div className="w-10 h-10 bg-stone-200 dark:bg-stone-700 rounded-full p-1.5 flex items-center justify-center">+ <OpenTelemetrySvg className="fill-stone-600 dark:fill-stone-300" />+ </div>+ </div>+ <div className="flex-1">+ <h2 className="text-xl font-semibold text-stone-600 dark:text-stone-300 mb-2">+ Fleet Hub+ </h2>+ <p className="text-stone-600 dark:text-stone-300 mb-4">+ Fleet hub is a feature that uses OpAMP (Open Agent Management Protocol) to provide centralized management and monitor OpenTelemetry collectors across your infrastructure.+ Monitor collector health, view detailed configurations, and manage collector settings from a unified dashboard.+ </p>+ </div>+ </div>+ </div>++ {/* Collector List */}+ <List agents={data || []} isLoading={!data || isLoading} isFetched={isFetched} />+ </div>+ );+}\ No newline at end of filediff --git a/src/client/src/app/api/fleet-hub/[id]/config/route.ts b/src/client/src/app/api/fleet-hub/[id]/config/route.tsnew file mode 100644index 00000000..18d0bede--- /dev/null+++ b/src/client/src/app/api/fleet-hub/[id]/config/route.ts@@ -0,0 +1,8 @@+import { updateAgentConfig } from "@/lib/platform/fleet-hub";++export async function POST(request: Request, context: any) {+ const { id } = context.params;+ const { config } = await request.json();+ const res = await updateAgentConfig(id, config);+ return Response.json(res);+}\ No newline at end of filediff --git a/src/client/src/app/api/fleet-hub/[id]/route.ts b/src/client/src/app/api/fleet-hub/[id]/route.tsnew file mode 100644index 00000000..12f7a716--- /dev/null+++ b/src/client/src/app/api/fleet-hub/[id]/route.ts@@ -0,0 +1,7 @@+import { getAgentByInstanceId } from "@/lib/platform/fleet-hub";++export async function GET(_: Request, context: any) {+ const { id } = context.params;+ const res = await getAgentByInstanceId(id);+ return Response.json(res);+}diff --git a/src/client/src/app/api/fleet-hub/[id]/tls-connection/route.ts b/src/client/src/app/api/fleet-hub/[id]/tls-connection/route.tsnew file mode 100644index 00000000..96543011--- /dev/null+++ b/src/client/src/app/api/fleet-hub/[id]/tls-connection/route.ts@@ -0,0 +1,8 @@+import { updateTlsConnection } from "@/lib/platform/fleet-hub";++export async function POST(request: Request, context: any) {+ const { id } = context.params;+ const { tlsMin } = await request.json();+ const res = await updateTlsConnection(id, tlsMin);+ return Response.json(res);+}\ No newline at end of filediff --git a/src/client/src/app/api/fleet-hub/route.ts b/src/client/src/app/api/fleet-hub/route.tsnew file mode 100644index 00000000..1b3731fb--- /dev/null+++ b/src/client/src/app/api/fleet-hub/route.ts@@ -0,0 +1,6 @@+import { getAllAgents } from "@/lib/platform/fleet-hub";++export async function GET() {+ const res: any = await getAllAgents();+ return Response.json(res);+}\ No newline at end of filediff --git a/src/client/src/components/(playground)/filter/visibility-columns.tsx b/src/client/src/components/(playground)/filter/visibility-columns.tsxindex 9910dfce..477de5ed 100644--- a/src/client/src/components/(playground)/filter/visibility-columns.tsx+++ b/src/client/src/components/(playground)/filter/visibility-columns.tsx@@ -7,14 +7,16 @@ import {DropdownMenuItem,DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";-import { TraceMapping } from "@/constants/traces";import { getVisibilityColumnsOfPage, setPageData } from "@/selectors/page";import { useRootStore } from "@/store";-import { PAGE, REQUEST_VISIBILITY_COLUMNS } from "@/types/store/page";-import { TraceMappingKeyType } from "@/types/trace";+import { PAGE } from "@/types/store/page";import { objectEntries } from "@/utils/object";import { EyeIcon } from "lucide-react";+const convertKeyToLabel = (key: string) => {+ return key.replace(/(?<=[a-z])(?=[A-Z])/g, " ").replace(/\b\w/g, (char) => char.toUpperCase());+}+export default function VisibilityColumns({columns,pageName,@@ -26,7 +28,7 @@ export default function VisibilityColumns({const visibilityColumns = useRootStore((state) =>getVisibilityColumnsOfPage(state, pageName));- const onVisibilityChange = (key: TraceMappingKeyType, value: boolean) => {+ const onVisibilityChange = (key: string, value: boolean) => {updateFilter(pageName, `visibilityColumns.${key}`, value);};@@ -46,8 +48,8 @@ export default function VisibilityColumns({key={key}onClick={() =>onVisibilityChange(- key as TraceMappingKeyType,- !visibilityColumns[key as keyof REQUEST_VISIBILITY_COLUMNS]+ key,+ !visibilityColumns[key])}disabled={!value?.enableHiding}@@ -55,10 +57,10 @@ export default function VisibilityColumns({><Checkboxchecked={- visibilityColumns[key as keyof REQUEST_VISIBILITY_COLUMNS]+ visibilityColumns[key]}/>- {TraceMapping[key as TraceMappingKeyType].label}+ {convertKeyToLabel(key)}</DropdownMenuItem>))}</DropdownMenuContent>diff --git a/src/client/src/components/(playground)/manage-dashboard/board-creator/components/code-editor.tsx b/src/client/src/components/(playground)/manage-dashboard/board-creator/components/code-editor.tsxindex fa04d021..4cbcd94e 100644--- a/src/client/src/components/(playground)/manage-dashboard/board-creator/components/code-editor.tsx+++ b/src/client/src/components/(playground)/manage-dashboard/board-creator/components/code-editor.tsx@@ -12,6 +12,7 @@ const CodeEditor: React.FC<EditorProps> = ({language = "sql",height = "100%",fullScreen = false,+ readOnly,}) => {const editorRef = useRef<any>(null);const completionProviderRef = useRef<any>(null);@@ -60,6 +61,7 @@ const CodeEditor: React.FC<EditorProps> = ({fontSize: 14,wordWrap: "on",automaticLayout: true,+ readOnly: !!readOnly}}beforeMount={(monaco) => {// Register ClickHouse SQL languagediff --git a/src/client/src/components/(playground)/manage-dashboard/board-creator/types.ts b/src/client/src/components/(playground)/manage-dashboard/board-creator/types.tsindex 200f944e..c3a4ffcf 100644--- a/src/client/src/components/(playground)/manage-dashboard/board-creator/types.ts+++ b/src/client/src/components/(playground)/manage-dashboard/board-creator/types.ts@@ -165,4 +165,5 @@ export interface EditorProps {language?: string;height?: string;fullScreen?: boolean;+ readOnly?: boolean;}diff --git a/src/client/src/components/(playground)/posthog.tsx b/src/client/src/components/(playground)/posthog.tsxindex 08101837..8197225c 100644--- a/src/client/src/components/(playground)/posthog.tsx+++ b/src/client/src/components/(playground)/posthog.tsx@@ -1,14 +1,14 @@"use client";import {- NEXT_PUBLIC_POSTHOG_API_HOST,- NEXT_PUBLIC_POSTHOG_API_KEY,+ POSTHOG_API_HOST,+ POSTHOG_API_KEY,} from "@/constants/posthog";import { PostHogConfig } from "posthog-js";import { PostHogProvider } from "posthog-js/react";import { ReactNode } from "react";const POSTHOG_OPTIONS: Partial<PostHogConfig> = {- api_host: NEXT_PUBLIC_POSTHOG_API_HOST,+ api_host: POSTHOG_API_HOST,autocapture: false,};@@ -22,7 +22,7 @@ export default function CustomPostHogProvider({if (telemetryEnabled) {return (<PostHogProvider- apiKey={NEXT_PUBLIC_POSTHOG_API_KEY}+ apiKey={POSTHOG_API_KEY}options={POSTHOG_OPTIONS}>{children}diff --git a/src/client/src/components/(playground)/sidebar/index.tsx b/src/client/src/components/(playground)/sidebar/index.tsxindex 2e762429..d0df20da 100644--- a/src/client/src/components/(playground)/sidebar/index.tsx+++ b/src/client/src/components/(playground)/sidebar/index.tsx@@ -19,8 +19,8 @@ import { PRIMARY_BACKGROUND } from "@/constants/common-classes";const getIfSidebarItemClasses = (pathname: string, item: SidebarItemProps) => {const commonClasses = "flex gap-2 group-data-[state=open]:w-auto group-data-[state=open]:justify-start p-2.5 font-normal ";- const activeClasses = "text-white bg-primary dark:bg-primary dark:text-white [&]:hover:bg-primary [&]:dark:hover:bg-primary hover:text-white ";- const inactiveClasses = "text-stone-500 dark:text-stone-300 hover:bg-stone-700 dark:hover:bg-stone-600 hover:text-white ";+ const activeClasses = "text-white bg-primary dark:bg-primary dark:text-white [&]:hover:bg-primary [&]:dark:hover:bg-primary hover:text-white [&>.external-icon-svg]:fill-white [&>.external-icon-svg]:dark:fill-white ";+ const inactiveClasses = "text-stone-500 dark:text-stone-300 hover:bg-stone-700 dark:hover:bg-stone-600 hover:text-white [&>.external-icon-svg]:fill-stone-500 [&>.external-icon-svg]:dark:fill-stone-300 [&>.external-icon-svg]:hover:fill-white ";if (item.type === "section")return `${inactiveClasses}${commonClasses}`;diff --git a/src/client/src/components/svg/linux.tsx b/src/client/src/components/svg/linux.tsxnew file mode 100644index 00000000..17f60afb--- /dev/null+++ b/src/client/src/components/svg/linux.tsx@@ -0,0 +1,7 @@+export default function LinuxSvg({ className = "" }: { className?: string }) {+ return (+ <svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" height="24" width="24" className={`${className} external-icon-svg`}>+ <path d="M12.504 0c-0.155 0 -0.315 0.008 -0.48 0.021 -4.226 0.333 -3.105 4.807 -3.17 6.298 -0.076 1.092 -0.3 1.953 -1.05 3.02 -0.885 1.051 -2.127 2.75 -2.716 4.521 -0.278 0.832 -0.41 1.684 -0.287 2.489a0.424 0.424 0 0 0 -0.11 0.135c-0.26 0.268 -0.45 0.6 -0.663 0.839 -0.199 0.199 -0.485 0.267 -0.797 0.4 -0.313 0.136 -0.658 0.269 -0.864 0.68 -0.09 0.189 -0.136 0.394 -0.132 0.602 0 0.199 0.027 0.4 0.055 0.536 0.058 0.399 0.116 0.728 0.04 0.97 -0.249 0.68 -0.28 1.145 -0.106 1.484 0.174 0.334 0.535 0.47 0.94 0.601 0.81 0.2 1.91 0.135 2.774 0.6 0.926 0.466 1.866 0.67 2.616 0.47 0.526 -0.116 0.97 -0.464 1.208 -0.946 0.587 -0.003 1.23 -0.269 2.26 -0.334 0.699 -0.058 1.574 0.267 2.577 0.2 0.025 0.134 0.063 0.198 0.114 0.333l0.003 0.003c0.391 0.778 1.113 1.132 1.884 1.071 0.771 -0.06 1.592 -0.536 2.257 -1.306 0.631 -0.765 1.683 -1.084 2.378 -1.503 0.348 -0.199 0.629 -0.469 0.649 -0.853 0.023 -0.4 -0.2 -0.811 -0.714 -1.376v-0.097l-0.003 -0.003c-0.17 -0.2 -0.25 -0.535 -0.338 -0.926 -0.085 -0.401 -0.182 -0.786 -0.492 -1.046h-0.003c-0.059 -0.054 -0.123 -0.067 -0.188 -0.135a0.357 0.357 0 0 0 -0.19 -0.064c0.431 -1.278 0.264 -2.55 -0.173 -3.694 -0.533 -1.41 -1.465 -2.638 -2.175 -3.483 -0.796 -1.005 -1.576 -1.957 -1.56 -3.368 0.026 -2.152 0.236 -6.133 -3.544 -6.139zm0.529 3.405h0.013c0.213 0 0.396 0.062 0.584 0.198 0.19 0.135 0.33 0.332 0.438 0.533 0.105 0.259 0.158 0.459 0.166 0.724 0 -0.02 0.006 -0.04 0.006 -0.06v0.105a0.086 0.086 0 0 1 -0.004 -0.021l-0.004 -0.024a1.807 1.807 0 0 1 -0.15 0.706 0.953 0.953 0 0 1 -0.213 0.335 0.71 0.71 0 0 0 -0.088 -0.042c-0.104 -0.045 -0.198 -0.064 -0.284 -0.133a1.312 1.312 0 0 0 -0.22 -0.066c0.05 -0.06 0.146 -0.133 0.183 -0.198 0.053 -0.128 0.082 -0.264 0.088 -0.402v-0.02a1.21 1.21 0 0 0 -0.061 -0.4c-0.045 -0.134 -0.101 -0.2 -0.183 -0.333 -0.084 -0.066 -0.167 -0.132 -0.267 -0.132h-0.016c-0.093 0 -0.176 0.03 -0.262 0.132a0.8 0.8 0 0 0 -0.205 0.334 1.18 1.18 0 0 0 -0.09 0.4v0.019c0.002 0.089 0.008 0.179 0.02 0.267 -0.193 -0.067 -0.438 -0.135 -0.607 -0.202a1.635 1.635 0 0 1 -0.018 -0.2v-0.02a1.772 1.772 0 0 1 0.15 -0.768c0.082 -0.22 0.232 -0.406 0.43 -0.533a0.985 0.985 0 0 1 0.594 -0.2zm-2.962 0.059h0.036c0.142 0 0.27 0.048 0.399 0.135 0.146 0.129 0.264 0.288 0.344 0.465 0.09 0.199 0.14 0.4 0.153 0.667v0.004c0.007 0.134 0.006 0.2 -0.002 0.266v0.08c-0.03 0.007 -0.056 0.018 -0.083 0.024 -0.152 0.055 -0.274 0.135 -0.393 0.2 0.012 -0.09 0.013 -0.18 0.003 -0.267v-0.015c-0.012 -0.133 -0.04 -0.2 -0.082 -0.333a0.613 0.613 0 0 0 -0.166 -0.267 0.248 0.248 0 0 0 -0.183 -0.064h-0.021c-0.071 0.006 -0.13 0.04 -0.186 0.132a0.552 0.552 0 0 0 -0.12 0.27 0.944 0.944 0 0 0 -0.023 0.33v0.015c0.012 0.135 0.037 0.2 0.08 0.334 0.046 0.134 0.098 0.2 0.166 0.268 0.01 0.009 0.02 0.018 0.034 0.024 -0.07 0.057 -0.117 0.07 -0.176 0.136a0.304 0.304 0 0 1 -0.131 0.068 2.62 2.62 0 0 1 -0.275 -0.402 1.772 1.772 0 0 1 -0.155 -0.667 1.759 1.759 0 0 1 0.08 -0.668 1.43 1.43 0 0 1 0.283 -0.535c0.128 -0.133 0.26 -0.2 0.418 -0.2zm1.37 1.706c0.332 0 0.733 0.065 1.216 0.399 0.293 0.2 0.523 0.269 1.052 0.468h0.003c0.255 0.136 0.405 0.266 0.478 0.399v-0.131a0.571 0.571 0 0 1 0.016 0.47c-0.123 0.31 -0.516 0.643 -1.063 0.842v0.002c-0.268 0.135 -0.501 0.333 -0.775 0.465 -0.276 0.135 -0.588 0.292 -1.012 0.267a1.139 1.139 0 0 1 -0.448 -0.067 3.566 3.566 0 0 1 -0.322 -0.198c-0.195 -0.135 -0.363 -0.332 -0.612 -0.465v-0.005h-0.005c-0.4 -0.246 -0.616 -0.512 -0.686 -0.71 -0.07 -0.268 -0.005 -0.47 0.193 -0.6 0.224 -0.135 0.38 -0.271 0.483 -0.336 0.104 -0.074 0.143 -0.102 0.176 -0.131h0.002v-0.003c0.169 -0.202 0.436 -0.47 0.839 -0.601 0.139 -0.036 0.294 -0.065 0.466 -0.065zm2.8 2.142c0.358 1.417 1.196 3.475 1.735 4.473 0.286 0.534 0.855 1.659 1.102 3.024 0.156 -0.005 0.33 0.018 0.513 0.064 0.646 -1.671 -0.546 -3.467 -1.089 -3.966 -0.22 -0.2 -0.232 -0.335 -0.123 -0.335 0.59 0.534 1.365 1.572 1.646 2.757 0.13 0.535 0.16 1.104 0.021 1.67 0.067 0.028 0.135 0.06 0.205 0.067 1.032 0.534 1.413 0.938 1.23 1.537v-0.043c-0.06 -0.003 -0.12 0 -0.18 0h-0.016c0.151 -0.467 -0.182 -0.825 -1.065 -1.224 -0.915 -0.4 -1.646 -0.336 -1.77 0.465 -0.008 0.043 -0.013 0.066 -0.018 0.135 -0.068 0.023 -0.139 0.053 -0.209 0.064 -0.43 0.268 -0.662 0.669 -0.793 1.187 -0.13 0.533 -0.17 1.156 -0.205 1.869v0.003c-0.02 0.334 -0.17 0.838 -0.319 1.35 -1.5 1.072 -3.58 1.538 -5.348 0.334a2.645 2.645 0 0 0 -0.402 -0.533 1.45 1.45 0 0 0 -0.275 -0.333c0.182 0 0.338 -0.03 0.465 -0.067a0.615 0.615 0 0 0 0.314 -0.334c0.108 -0.267 0 -0.697 -0.345 -1.163 -0.345 -0.467 -0.931 -0.995 -1.788 -1.521 -0.63 -0.4 -0.986 -0.87 -1.15 -1.396 -0.165 -0.534 -0.143 -1.085 -0.015 -1.645 0.245 -1.07 0.873 -2.11 1.274 -2.763 0.107 -0.065 0.037 0.135 -0.408 0.974 -0.396 0.751 -1.14 2.497 -0.122 3.854a8.123 8.123 0 0 1 0.647 -2.876c0.564 -1.278 1.743 -3.504 1.836 -5.268 0.048 0.036 0.217 0.135 0.289 0.202 0.218 0.133 0.38 0.333 0.59 0.465 0.21 0.201 0.477 0.335 0.876 0.335 0.039 0.003 0.075 0.006 0.11 0.006 0.412 0 0.73 -0.134 0.997 -0.268 0.29 -0.134 0.52 -0.334 0.74 -0.4h0.005c0.467 -0.135 0.835 -0.402 1.044 -0.7zm2.185 8.958c0.037 0.6 0.343 1.245 0.882 1.377 0.588 0.134 1.434 -0.333 1.791 -0.765l0.211 -0.01c0.315 -0.007 0.577 0.01 0.847 0.268l0.003 0.003c0.208 0.199 0.305 0.53 0.391 0.876 0.085 0.4 0.154 0.78 0.409 1.066 0.486 0.527 0.645 0.906 0.636 1.14l0.003 -0.007v0.018l-0.003 -0.012c-0.015 0.262 -0.185 0.396 -0.498 0.595 -0.63 0.401 -1.746 0.712 -2.457 1.57 -0.618 0.737 -1.37 1.14 -2.036 1.191 -0.664 0.053 -1.237 -0.2 -1.574 -0.898l-0.005 -0.003c-0.21 -0.4 -0.12 -1.025 0.056 -1.69 0.176 -0.668 0.428 -1.344 0.463 -1.897 0.037 -0.714 0.076 -1.335 0.195 -1.814 0.12 -0.465 0.308 -0.797 0.641 -0.984l0.045 -0.022zm-10.814 0.049h0.01c0.053 0 0.105 0.005 0.157 0.014 0.376 0.055 0.706 0.333 1.023 0.752l0.91 1.664 0.003 0.003c0.243 0.533 0.754 1.064 1.189 1.637 0.434 0.598 0.77 1.131 0.729 1.57v0.006c-0.057 0.744 -0.48 1.148 -1.125 1.294 -0.645 0.135 -1.52 0.002 -2.395 -0.464 -0.968 -0.536 -2.118 -0.469 -2.857 -0.602 -0.369 -0.066 -0.61 -0.2 -0.723 -0.4 -0.11 -0.2 -0.113 -0.602 0.123 -1.23v-0.004l0.002 -0.003c0.117 -0.334 0.03 -0.752 -0.027 -1.118 -0.055 -0.401 -0.083 -0.71 0.043 -0.94 0.16 -0.334 0.396 -0.4 0.69 -0.533 0.294 -0.135 0.64 -0.202 0.915 -0.47h0.002v-0.002c0.256 -0.268 0.445 -0.601 0.668 -0.838 0.19 -0.201 0.38 -0.336 0.663 -0.336zm7.159 -9.074c-0.435 0.201 -0.945 0.535 -1.488 0.535 -0.542 0 -0.97 -0.267 -1.28 -0.466 -0.154 -0.134 -0.28 -0.268 -0.373 -0.335 -0.164 -0.134 -0.144 -0.333 -0.074 -0.333 0.109 0.016 0.129 0.134 0.199 0.2 0.096 0.066 0.215 0.2 0.36 0.333 0.292 0.2 0.68 0.467 1.167 0.467 0.485 0 1.053 -0.267 1.398 -0.466 0.195 -0.135 0.445 -0.334 0.648 -0.467 0.156 -0.136 0.149 -0.267 0.279 -0.267 0.128 0.016 0.034 0.134 -0.147 0.332a8.097 8.097 0 0 1 -0.69 0.468zm-1.082 -1.583V5.64c-0.006 -0.02 0.013 -0.042 0.029 -0.05 0.074 -0.043 0.18 -0.027 0.26 0.004 0.063 0 0.16 0.067 0.15 0.135 -0.006 0.049 -0.085 0.066 -0.135 0.066 -0.055 0 -0.092 -0.043 -0.141 -0.068 -0.052 -0.018 -0.146 -0.008 -0.163 -0.065zm-0.551 0c-0.02 0.058 -0.113 0.049 -0.166 0.066 -0.047 0.025 -0.086 0.068 -0.14 0.068 -0.05 0 -0.13 -0.02 -0.136 -0.068 -0.01 -0.066 0.088 -0.133 0.15 -0.133 0.08 -0.031 0.184 -0.047 0.259 -0.005 0.019 0.009 0.036 0.03 0.03 0.05v0.02h0.003z" fill="currentColor" stroke-width="1"></path>+ </svg>+ );+}\ No newline at end of filediff --git a/src/client/src/components/svg/mac.tsx b/src/client/src/components/svg/mac.tsxnew file mode 100644index 00000000..e13ef1f6--- /dev/null+++ b/src/client/src/components/svg/mac.tsx@@ -0,0 +1,7 @@+export default function MacSvg({ className = "" }: { className?: string }) {+ return (+ <svg role="img" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg" height="16" width="16" className={`${className} external-icon-svg`}>+ <path d="M10.306266666666666 2.6608c0.2964 -0.34159999999999996 0.5223333333333333 -0.7383333333333333 0.6649333333333333 -1.1675333333333333 0.1426 -0.42913333333333337 0.19906666666666664 -0.8822666666666665 0.16606666666666664 -1.3332666666666666 -0.9098666666666666 0.07346666666666667 -1.7544666666666666 0.5014 -2.3518666666666665 1.1916 -0.28606666666666664 0.3308 -0.5027999999999999 0.7156666666666666 -0.6375333333333333 1.1317333333333333 -0.13466666666666666 0.41606666666666664 -0.18446666666666667 0.855 -0.14639999999999997 1.2906666666666666 0.4438 0.003666666666666666 0.8825333333333334 -0.0948 1.2822 -0.28779999999999994 0.39966666666666667 -0.19306666666666666 0.7495333333333334 -0.4754666666666666 1.0226 -0.8253999999999999Zm1.9755333333333331 5.832533333333332c0.005266666666666667 -0.6007333333333333 0.16346666666666665 -1.1901333333333333 0.4598 -1.7127333333333334 0.2962666666666667 -0.5226 0.7207333333333332 -0.9610666666666666 1.2335333333333334 -1.2740666666666667 -0.3236 -0.46626666666666666 -0.7514 -0.8507333333333333 -1.2494666666666667 -1.1228666666666665 -0.498 -0.27213333333333334 -1.0526 -0.4245333333333333 -1.6198 -0.4450666666666666 -1.2229333333333332 -0.12539999999999998 -2.3518 0.7134 -3.002533333333333 0.7134 -0.6506666666666666 0 -1.5678666666666665 -0.6976666666666667 -2.5869999999999997 -0.6819999999999999 -0.6662666666666666 0.021933333333333332 -1.3154666666666666 0.21619999999999998 -1.8842666666666665 0.5638 -0.5688 0.34759999999999996 -1.0377999999999998 0.8366666666666666 -1.3612666666666666 1.4196 -1.3797333333333333 2.3988666666666667 -0.3528 5.9658 1.0269333333333333 7.902200000000001 0.6272 0.9485333333333333 1.4111333333333331 2.022533333333333 2.445933333333333 1.9833333333333334 1.0348 -0.0392 1.3719333333333332 -0.6427999999999999 2.5713333333333335 -0.6427999999999999 1.1994666666666665 0 1.5679333333333334 0.6427999999999999 2.5870666666666664 0.6193333333333333 1.0191333333333332 -0.02353333333333333 1.7403333333333333 -0.9721333333333333 2.3988666666666667 -1.9207333333333332 0.46646666666666664 -0.6886666666666665 0.8309333333333333 -1.4411999999999998 1.0818666666666665 -2.2342 -0.6212666666666666 -0.265 -1.1514 -0.7061333333333333 -1.5248 -1.269 -0.37333333333333335 -0.5628666666666666 -0.5736666666666667 -1.2227333333333332 -0.5761999999999999 -1.8982Z" fill="currentColor" stroke-width="0.6667"></path>+ </svg>+ );+}\ No newline at end of filediff --git a/src/client/src/components/svg/opentelemetry.tsx b/src/client/src/components/svg/opentelemetry.tsxnew file mode 100644index 00000000..d91480ac--- /dev/null+++ b/src/client/src/components/svg/opentelemetry.tsx@@ -0,0 +1,8 @@+export default function OpenTelemetrySvg({ className = "" }: { className?: string }) {+ return (+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" className={`${className} external-icon-svg`}>+ <path d="M67.648 69.797c-5.246 5.25-5.246 13.758 0 19.008 5.25 5.246 13.758 5.246 19.004 0 5.25-5.25 5.25-13.758 0-19.008-5.246-5.246-13.754-5.246-19.004 0Zm14.207 14.219a6.649 6.649 0 0 1-9.41 0 6.65 6.65 0 0 1 0-9.407 6.649 6.649 0 0 1 9.41 0c2.598 2.586 2.598 6.809 0 9.407ZM86.43 3.672l-8.235 8.234a4.17 4.17 0 0 0 0 5.875l32.149 32.149a4.17 4.17 0 0 0 5.875 0l8.234-8.235c1.61-1.61 1.61-4.261 0-5.87L92.29 3.671a4.159 4.159 0 0 0-5.86 0ZM28.738 108.895a3.763 3.763 0 0 0 0-5.31l-4.183-4.187a3.768 3.768 0 0 0-5.313 0l-8.644 8.649-.016.012-2.371-2.375c-1.313-1.313-3.45-1.313-4.75 0-1.313 1.312-1.313 3.449 0 4.75l14.246 14.242a3.353 3.353 0 0 0 4.746 0c1.3-1.313 1.313-3.45 0-4.746l-2.375-2.375.016-.012Zm0 0" />+ <path d="M72.297 27.313 54.004 45.605c-1.625 1.625-1.625 4.301 0 5.926L65.3 62.824c7.984-5.746 19.18-5.035 26.363 2.153l9.148-9.149c1.622-1.625 1.622-4.297 0-5.922L78.22 27.313a4.185 4.185 0 0 0-5.922 0ZM60.55 67.585l-6.672-6.672c-1.563-1.562-4.125-1.562-5.684 0l-23.53 23.54a4.036 4.036 0 0 0 0 5.687l13.331 13.332a4.036 4.036 0 0 0 5.688 0l15.132-15.157c-3.199-6.609-2.625-14.593 1.735-20.73Zm0 0" />+ </svg>+ );+}\ No newline at end of filediff --git a/src/client/src/components/svg/windows.tsx b/src/client/src/components/svg/windows.tsxnew file mode 100644index 00000000..eca32134--- /dev/null+++ b/src/client/src/components/svg/windows.tsx@@ -0,0 +1,7 @@+export default function WindowsSvg({ className = "" }: { className?: string }) {+ return (+ <svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" height="24" width="24" className={`${className} external-icon-svg`}>+ <path d="M3 3h8.5v8.5H3V3zm9.5 0H21v8.5h-8.5V3zM3 12.5h8.5V21H3v-8.5zm9.5 0H21V21h-8.5v-8.5z" fill="currentColor" />+ </svg>+ );+}\ No newline at end of filediff --git a/src/client/src/components/ui/resizable.tsx b/src/client/src/components/ui/resizable.tsxnew file mode 100644index 00000000..b5081e8c--- /dev/null+++ b/src/client/src/components/ui/resizable.tsx@@ -0,0 +1,45 @@+"use client"++import { GripVertical } from "lucide-react"+import * as ResizablePrimitive from "react-resizable-panels"++import { cn } from "@/lib/utils"++const ResizablePanelGroup = ({+ className,+ ...props+}: React.ComponentProps<typeof ResizablePrimitive.PanelGroup>) => (+ <ResizablePrimitive.PanelGroup+ className={cn(+ "flex h-full w-full data-[panel-group-direction=vertical]:flex-col",+ className+ )}+ {...props}+ />+)++const ResizablePanel = ResizablePrimitive.Panel++const ResizableHandle = ({+ withHandle,+ className,+ ...props+}: React.ComponentProps<typeof ResizablePrimitive.PanelResizeHandle> & {+ withHandle?: boolean+}) => (+ <ResizablePrimitive.PanelResizeHandle+ className={cn(+ "relative flex w-px items-center justify-center bg-stone-200 after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-stone-950 focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90 dark:bg-stone-800 dark:focus-visible:ring-stone-300",+ className+ )}+ {...props}+ >+ {withHandle && (+ <div className="z-10 flex h-4 w-3 items-center justify-center rounded-sm border border-stone-200 bg-stone-200 dark:border-stone-800 dark:bg-stone-800">+ <GripVertical className="h-2.5 w-2.5" />+ </div>+ )}+ </ResizablePrimitive.PanelResizeHandle>+)++export { ResizablePanelGroup, ResizablePanel, ResizableHandle }diff --git a/src/client/src/constants/documentation-links.ts b/src/client/src/constants/documentation-links.tsindex 066bf5eb..f152d1e8 100644--- a/src/client/src/constants/documentation-links.ts+++ b/src/client/src/constants/documentation-links.ts@@ -1,4 +1,4 @@-export default {+const DOCUMENTATION_LINKS = {promptHub: "https://docs.openlit.io/latest/openlit/prompts-experiments/prompt-hub",openground: "https://docs.openlit.io/latest/openlit/prompts-experiments/openground",vault: "https://docs.openlit.io/latest/openlit/developer-resources/vault",@@ -7,4 +7,6 @@ export default {apiReference: "https://docs.openlit.io/latest/openlit/developer-resources/api-reference",promptHubApiReference: "https://docs.openlit.io/latest/openlit/developer-resources/api-reference/endpoint/prompt-hub",vaultApiReference: "https://docs.openlit.io/latest/openlit/developer-resources/api-reference/endpoint/vault",-}\ No newline at end of file+};++export default DOCUMENTATION_LINKS;\ No newline at end of filediff --git a/src/client/src/constants/events.ts b/src/client/src/constants/events.tsindex 8e0ec3f8..450383cf 100644--- a/src/client/src/constants/events.ts+++ b/src/client/src/constants/events.ts@@ -72,6 +72,11 @@ export const CLIENT_EVENTS = {LIST_DASHBOARDS_PAGE_VISITED: "LIST_DASHBOARDS_PAGE_VISITED",EXPLORE_DASHBOARDS_PAGE_VISITED: "EXPLORE_DASHBOARDS_PAGE_VISITED",LIST_WIDGETS_PAGE_VISITED: "LIST_WIDGETS_PAGE_VISITED",++ // Fleet Hub+ FLEET_HUB_VIEWED: "FLEET_HUB_VIEWED",+ FLEET_HUB_AGENT_VIEWED: "FLEET_HUB_AGENT_VIEWED",+ FLEET_HUB_AGENT_CONFIG_SAVED: "FLEET_HUB_AGENT_CONFIG_SAVED",};export const SERVER_EVENTS = {diff --git a/src/client/src/constants/posthog.ts b/src/client/src/constants/posthog.tsindex f7f52f53..5f46a5ef 100644--- a/src/client/src/constants/posthog.ts+++ b/src/client/src/constants/posthog.ts@@ -1,3 +1,3 @@-export const NEXT_PUBLIC_POSTHOG_API_KEY =+export const POSTHOG_API_KEY ="phc_JiR0FxzxAYeV3gDoMUltOxjLa3r7RnogMHPVrjDzTR9";-export const NEXT_PUBLIC_POSTHOG_API_HOST = "https://us.i.posthog.com";+export const POSTHOG_API_HOST = "https://us.i.posthog.com";diff --git a/src/client/src/constants/sidebar.tsx b/src/client/src/constants/sidebar.tsxindex d3724343..d770cc74 100644--- a/src/client/src/constants/sidebar.tsx+++ b/src/client/src/constants/sidebar.tsx@@ -12,6 +12,7 @@ import {TextQuote} from "lucide-react";import DatabaseConfigSwitch from "@/components/(playground)/sidebar/database-config-switch";+import OpenTelemetrySvg from "@/components/svg/opentelemetry";export const ICON_CLASSES = "flex-shrink-0 size-5";@@ -42,7 +43,14 @@ export const SIDEBAR_ITEMS: SidebarItemProps[] = [text: "Exceptions",link: "/exceptions",type: "action",- },]+ },+ {+ icon: <OpenTelemetrySvg className={ICON_CLASSES} />,+ text: "Fleet Hub",+ link: "/fleet-hub",+ type: "action",+ },+ ]},{title: "Resources",@@ -88,12 +96,12 @@ export const SIDEBAR_ITEMS: SidebarItemProps[] = [type: "section",collapsible: true,children: [- {- icon: <Key className={ICON_CLASSES} />,- text: "Api Keys",- link: "/settings/api-keys",- type: "action",- },+ {+ icon: <Key className={ICON_CLASSES} />,+ text: "Api Keys",+ link: "/settings/api-keys",+ type: "action",+ },]},{diff --git a/src/client/src/helpers/client/fleet-hub.ts b/src/client/src/helpers/client/fleet-hub.tsnew file mode 100644index 00000000..bc164c81--- /dev/null+++ b/src/client/src/helpers/client/fleet-hub.ts@@ -0,0 +1,7 @@+import { Agent, AgentAttribute } from "@/types/fleet-hub"+import { get } from "lodash"++export const getAttributeValue = (agent: Agent, path:string, key: string, defaultValue: string = "N/A") => {+ const attributes: AgentAttribute[] = get(agent, path);+ return get(attributes.find((attr) => attr.key === key), "value.Value.StringValue", defaultValue)+}\ No newline at end of filediff --git a/src/client/src/lib/platform/fleet-hub/index.ts b/src/client/src/lib/platform/fleet-hub/index.tsnew file mode 100644index 00000000..4d206534--- /dev/null+++ b/src/client/src/lib/platform/fleet-hub/index.ts@@ -0,0 +1,96 @@+import asaw from "@/utils/asaw";+import { jsonStringify } from "@/utils/json";+import { consoleLog } from "@/utils/log";++const baseUrl = "http://127.0.0.1:8080";++export async function getAllAgents() {+ const [err, res]: any = await asaw(fetch(`${baseUrl}/api/agents`, {+ headers: {+ "Content-type": "application/json"+ },+ cache: 'no-store'+ }));++ if (err) {+ return {+ err+ };+ }++ const data = await res.json();++ return {+ data+ };+}++export async function getAgentByInstanceId(id: string) {+ const [err, res]: any = await asaw(fetch(`${baseUrl}/api/agent?id=${id}`, {+ headers: {+ "Content-type": "application/json"+ },+ cache: "no-store"+ }));++ if (err) {+ return {+ err+ };+ }++ const data = await res.json();++ return {+ data+ };+}++export async function updateAgentConfig(id: string, config: string) {+ const [err, res]: any = await asaw(fetch(`${baseUrl}/api/agent/config`, {+ method: "POST",+ headers: {+ "Content-type": "application/json"+ },+ body: jsonStringify({+ id,+ config,+ }),+ }));++ if (err) {+ consoleLog(err);+ return {+ err+ };+ }++ await new Promise(resolve => setTimeout(resolve, 2000));++ return {+ data: res+ };+}++export async function updateTlsConnection(id: string, tls_min: string) {+ const [err, res]: any = await asaw(fetch(`${baseUrl}/api/agent/connection`, {+ method: "POST",+ headers: {+ "Content-type": "application/json"+ },+ body: jsonStringify({+ id,+ tls_min,+ }),+ }));++ if (err) {+ return {+ err+ };+ }++ return {+ data: res+ };+}\ No newline at end of filediff --git a/src/client/src/lib/posthog.ts b/src/client/src/lib/posthog.tsindex e8028219..d7c94a05 100644--- a/src/client/src/lib/posthog.ts+++ b/src/client/src/lib/posthog.ts@@ -1,58 +1,62 @@import {- NEXT_PUBLIC_POSTHOG_API_HOST,- NEXT_PUBLIC_POSTHOG_API_KEY,+ POSTHOG_API_HOST,+ POSTHOG_API_KEY,} from "@/constants/posthog";+import { jsonStringify } from "@/utils/json";import { consoleLog } from "@/utils/log";import { randomUUID } from "crypto";-import { PostHog } from "posthog-node";+/* This is to force the node to use IPv4 for posthog events. Although this sets this config globally but right now it's only used for posthog events. If any problem occurs in future, we can remove this or use a undici for the fetch wrapper */+import { setDefaultAutoSelectFamily } from 'node:net';+setDefaultAutoSelectFamily(false);export default class PostHogServer {- static client: PostHog;- static distinctId: string;- static createClient() {- this.client = new PostHog(NEXT_PUBLIC_POSTHOG_API_KEY, {- host: NEXT_PUBLIC_POSTHOG_API_HOST,- flushAt: 1,- flushInterval: 0,- });- this.distinctId = randomUUID();- }+ static distinctId: string = randomUUID();- static capture(options: Parameters<PostHog["capture"]>[0]) {+ static async capture(options: {+ event: string,+ timestamp?: Date,+ properties?: Record<string, unknown>,+ }) {const telemetryEnabled = process.env.TELEMETRY_ENABLED !== "false";try {if (telemetryEnabled) {- if (!this.client) {- this.createClient();- }-- this.client.capture({- ...options,- properties: {- ...(options.properties || {}),- isServer: true,+ await fetch(+ `${POSTHOG_API_HOST}/capture/`,+ {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: jsonStringify({+ api_key: POSTHOG_API_KEY,+ ...options,+ distinctId: this.distinctId,+ properties: {+ ...(options.properties || {}),+ isServer: true,+ },+ }),},- });- this.client.shutdown();+ );}} catch (error) {consoleLog("Error capturing telemetry events:", error);}}- static fireEvent({+ static async fireEvent({event,properties = {},startTimestamp,}: {event: string;- properties?: Record<string, any>;+ properties?: Record<string, unknown>;startTimestamp: number;}) {- PostHogServer.capture({+ await PostHogServer.capture({event,- distinctId: this.distinctId,+ timestamp: new Date(startTimestamp),properties: {...properties,responseTime: Date.now() - startTimestamp,diff --git a/src/client/src/selectors/filter.ts b/src/client/src/selectors/filter.tsindex 06d09a95..7453e384 100644--- a/src/client/src/selectors/filter.ts+++ b/src/client/src/selectors/filter.ts@@ -1,7 +1,5 @@import { useRootStore } from "@/store";import { RootStore } from "@/types/store/root";-import { useMemo } from "react";-import { getFilterParamsForDashboard } from "@/helpers/client/filter";export const getFilterDetails = (state: RootStore) => state.filter.details;diff --git a/src/client/src/selectors/page.ts b/src/client/src/selectors/page.tsindex becec4c3..fb0fc090 100644--- a/src/client/src/selectors/page.ts+++ b/src/client/src/selectors/page.ts@@ -1,5 +1,5 @@import { RootStore } from "@/types/store/root";-import { PAGE, REQUEST_VISIBILITY_COLUMNS } from "@/types/store/page";+import { PAGE } from "@/types/store/page";import { useRootStore } from "@/store";export const getDashboardType = (state: RootStore) => state.page.dashboard.type;@@ -7,7 +7,7 @@ export const getDashboardType = (state: RootStore) => state.page.dashboard.type;export const getVisibilityColumnsOfPage = (state: RootStore, pageName: PAGE) =>(state.page[pageName] as {- visibilityColumns: Partial<REQUEST_VISIBILITY_COLUMNS>;+ visibilityColumns: Record<string, boolean>;}).visibilityColumns;diff --git a/src/client/src/store/page.ts b/src/client/src/store/page.tsindex 36afebd0..6455fc61 100644--- a/src/client/src/store/page.ts+++ b/src/client/src/store/page.ts@@ -25,6 +25,16 @@ export const pageStoreSlice: PageStore = lens((setStore, getStore) => ({exceptionType: true,},},+ fleethub: {+ visibilityColumns: {+ id: true,+ name: true,+ os: true,+ version: true,+ startedAt: true,+ status: true,+ }+ },header: {title: "",breadcrumbs: [],@@ -35,7 +45,7 @@ export const pageStoreSlice: PageStore = lens((setStore, getStore) => ({header: {...getStore().header,title: header.title,- breadcrumbs: header.breadcrumbs.length > 0 ? header.breadcrumbs : getStore().header.breadcrumbs,+ breadcrumbs: header.breadcrumbs,description: header.description,}});diff --git a/src/client/src/types/fleet-hub.ts b/src/client/src/types/fleet-hub.tsnew file mode 100644index 00000000..6887a56b--- /dev/null+++ b/src/client/src/types/fleet-hub.ts@@ -0,0 +1,33 @@+export interface AgentAttribute {+ key: string+ value: { Value: { StringValue: string } }+}++export interface Agent {+ InstanceIdStr: string;+ Status: {+ health: {+ healthy: boolean+ status: string+ component_health_map: Record<string, { healthy: boolean; status: string }>+ last_error?: string+ }+ agent_description: {+ identifying_attributes: AgentAttribute[]+ non_identifying_attributes: AgentAttribute[]+ }+ };+ StartedAt: string;+ EffectiveConfig: string;+ CustomInstanceConfig: string;+}++export enum OpampFilterType {+ "ALL" = "ALL",+ "HEALTHY" = "HEALTHY",+ "UNHEALTHY" = "UNHEALTHY",+}++export type OpampFilters = {+ type: OpampFilterType;+}\ No newline at end of filediff --git a/src/client/src/types/store/page.ts b/src/client/src/types/store/page.tsindex 7ec2e629..a3b3310e 100644--- a/src/client/src/types/store/page.ts+++ b/src/client/src/types/store/page.ts@@ -13,7 +13,7 @@ export type REQUEST_VISIBILITY_COLUMNS = Record<boolean>;-export type PAGE = "dashboard" | "request" | "exception";+export type PAGE = "dashboard" | "request" | "exception" | "fleethub";export type PageHeader = {title: string;@@ -29,10 +29,13 @@ export type PageStore = {type: DASHBOARD_TYPE;};request: {- visibilityColumns: Partial<REQUEST_VISIBILITY_COLUMNS>;+ visibilityColumns: Record<string, boolean>;};exception: {- visibilityColumns: Partial<REQUEST_VISIBILITY_COLUMNS>;+ visibilityColumns: Record<string, boolean>;+ };+ fleethub: {+ visibilityColumns: Record<string, boolean>;};setData: (p: PAGE, keyPath: string, value: unknown) => void;header: PageHeader,diff --git a/src/client/src/utils/breadcrumbs.ts b/src/client/src/utils/breadcrumbs.tsindex 75470b35..d1bf6381 100644--- a/src/client/src/utils/breadcrumbs.ts+++ b/src/client/src/utils/breadcrumbs.ts@@ -204,11 +204,13 @@ export const ROUTE_CONFIGS: RouteConfig[] = [],},- // Getting started+ // Fleet Hub{- regex: /^\/getting-started$/,- getTitle: () => "Getting Started",- getBreadcrumbs: () => [],+ regex: /^\/fleet-hub\/[^/]+$/,+ getTitle: () => "Fleet Hub",+ getBreadcrumbs: () => [+ { title: "Fleet Hub", href: "/fleet-hub" }+ ],},];diff --git a/src/client/src/utils/date.ts b/src/client/src/utils/date.tsnew file mode 100644index 00000000..30c5c59d--- /dev/null+++ b/src/client/src/utils/date.ts@@ -0,0 +1,13 @@+export function formatDate(dateString: string, options?: { time?: boolean }) {+ const date = new Date(dateString);+ return date.toLocaleDateString(undefined, {+ year: "numeric",+ month: "short",+ day: "numeric",+ ...(options?.time && {+ hour: "2-digit",+ minute: "2-digit",+ second: "2-digit",+ }),+ });+}\ No newline at end of filediff --git a/src/dev-docker-compose.yml b/src/dev-docker-compose.ymlindex 90856b54..28d4cf59 100644--- a/src/dev-docker-compose.yml+++ b/src/dev-docker-compose.yml@@ -16,8 +16,12 @@ services:openlit:image: openlitbuild:- context: ./client- dockerfile: Dockerfile+ context: .+ dockerfile: ./Dockerfile+ args:+ OTEL_VERSION: ${OTEL_VERSION:-v0.132.4}+ OPAMP_SUPERVISOR_VERSION: ${OPAMP_SUPERVISOR_VERSION:-v0.132.4}+ TARGETARCH: ${TARGETARCH:-arm64}container_name: openlitenvironment:TELEMETRY_ENABLED: "true"@@ -29,41 +33,35 @@ services:SQLITE_DATABASE_URL: file:/app/client/data/data.dbPORT: ${PORT:-3000}DOCKER_PORT: ${DOCKER_PORT:-3000}+# OAuth Environment VariablesGOOGLE_CLIENT_ID: ${GOOGLE_CLIENT_ID:-}GOOGLE_CLIENT_SECRET: ${GOOGLE_CLIENT_SECRET:-}GITHUB_CLIENT_ID: ${GITHUB_CLIENT_ID:-}GITHUB_CLIENT_SECRET: ${GITHUB_CLIENT_SECRET:-}++ # TLS Configuration (user-configurable)+ OPAMP_ENVIRONMENT: ${OPAMP_ENVIRONMENT:-production}+ OPAMP_CERTS_DIR: "/app/opamp/certs"+ OPAMP_TLS_INSECURE_SKIP_VERIFY: ${OPAMP_TLS_INSECURE_SKIP_VERIFY:-false}+ OPAMP_TLS_REQUIRE_CLIENT_CERT: ${OPAMP_TLS_REQUIRE_CLIENT_CERT:-true}+ OPAMP_TLS_MIN_VERSION: ${OPAMP_TLS_MIN_VERSION:-1.2}+ OPAMP_TLS_MAX_VERSION: ${OPAMP_TLS_MAX_VERSION:-1.3}+ OPAMP_LOG_LEVEL: ${OPAMP_LOG_LEVEL:-info}env_file:- path: .envrequired: falseports:- "${PORT:-3000}:${DOCKER_PORT:-3000}"+ - "4317:4317" # OTLP gRPC receiver+ - "4318:4318" # OTLP HTTP receiverdepends_on:- clickhousevolumes:- openlit-data:/app/client/data- restart: always-- otel-collector:- image: otel/opentelemetry-collector-contrib:0.94.0- container_name: otel-collector- environment:- INIT_DB_HOST: clickhouse- INIT_DB_PORT: 9000- INIT_DB_DATABASE: ${OPENLIT_DB_NAME:-openlit}- INIT_DB_USERNAME: ${OPENLIT_DB_USER:-default}- INIT_DB_PASSWORD: ${OPENLIT_DB_PASSWORD:-OPENLIT}- ports:- - "4317:4317"- - "4318:4318"- - "8888:8888"- - "55679:55679"- depends_on:- - clickhouse- volumes:- - ../assets/otel-collector-config.yaml:/etc/otelcol-contrib/config.yaml+ - ../assets/supervisor-dynamic.yaml:/etc/otel/supervisor-dynamic.yaml+ - ../assets/otel-collector-config.yaml:/etc/otel/otel-collector-config.yamlrestart: alwaysvolumes:diff --git a/src/opamp-server/CERTIFICATES.md b/src/opamp-server/CERTIFICATES.mdnew file mode 100644index 00000000..04952771--- /dev/null+++ b/src/opamp-server/CERTIFICATES.md@@ -0,0 +1,387 @@+# OpenLIT OpAMP Server - TLS Certificate Management++This document explains how to set up and manage TLS certificates for secure OpAMP communication between the OpenLIT server and OpAMP supervisors.++## Overview++The OpenLIT OpAMP server uses TLS certificates to secure communication with OpAMP supervisors. This implementation provides:++- **Self-signed CA** for development and testing+- **Production-ready certificate management** with proper validation+- **Environment-aware configuration** (development vs production)+- **Mutual TLS support** for enhanced security+- **Certificate validation and monitoring** utilities++## Quick Start++### 1. Generate Certificates++```bash+cd src/opamp-server/certs+./generate.sh+```++### 2. Configure Environment++**For Development:**+```bash+export OPAMP_ENVIRONMENT=development+export OPAMP_CERTS_DIR=/path/to/certs+```++**For Production:**+```bash+export OPAMP_ENVIRONMENT=production+export OPAMP_CERTS_DIR=/path/to/certs+export OPAMP_TLS_INSECURE_SKIP_VERIFY=false+```++### 3. Start the Server++```bash+cd src/opamp-server+./opamp-server+```++### 4. Configure Supervisors++**For Development:**+```bash+./setup-supervisor.sh --development+```++**For Production:**+```bash+./setup-supervisor.sh --production --server-url wss://your-server:4320/v1/opamp+```++## Certificate Structure++```+certs/+├── cert/+│ └── ca.cert.pem # CA certificate (public)+├── private/+│ └── ca.key.pem # CA private key (keep secure!)+├── server/+│ ├── server.cert.pem # Server certificate+│ ├── server.key.pem # Server private key+│ └── server.csr # Server certificate signing request+├── client/+│ ├── client.cert.pem # Client certificate (optional)+│ ├── client.key.pem # Client private key (optional)+│ └── client.csr # Client certificate signing request+└── generate.sh # Certificate generation script+```++## Environment Configuration++### Environment Variables++| Variable | Default | Description |+|----------|---------|-------------|+| `OPAMP_ENVIRONMENT` | `production` | Environment mode (`development`, `production`, `testing`) |+| `OPAMP_CERTS_DIR` | `/app/opamp/certs` | Certificate directory path |+| `OPAMP_TLS_INSECURE_SKIP_VERIFY` | `false` | Skip certificate verification (dev only) |+| `OPAMP_TLS_REQUIRE_CLIENT_CERT` | `true` | Require client certificates for mutual TLS |+| `OPAMP_TLS_MIN_VERSION` | `1.2` | Minimum TLS version |+| `OPAMP_TLS_MAX_VERSION` | `1.3` | Maximum TLS version |++### Environment Modes++#### Development Mode+- `insecure_skip_verify: true` by default+- Client certificates not required+- Relaxed certificate validation+- Suitable for local development and testing++#### Production Mode (Default)+- `insecure_skip_verify: false` (strict verification)+- Client certificates required for mutual TLS authentication+- Full certificate chain validation+- Certificate expiry monitoring+- Secure cipher suites only++#### Testing Mode+- Similar to development mode+- Optimized for automated testing+- Flexible certificate validation++## Certificate Generation++### Basic Generation++```bash+cd certs/+./generate.sh+```++### Advanced Options++```bash+# Clean existing certificates and regenerate+./generate.sh --clean++# Set custom certificate validity periods+CERT_VALIDITY_DAYS=7300 SERVER_CERT_DAYS=730 ./generate.sh++# Generate with custom configuration+CERT_VALIDITY_DAYS=3650 ./generate.sh+```++### Certificate Properties++- **Key Size**: 4096-bit RSA keys for enhanced security+- **Hash Algorithm**: SHA-256+- **CA Validity**: 10 years (configurable)+- **Server/Client Validity**: 1 year (configurable)+- **Extensions**: Proper key usage and extended key usage+- **Subject Alternative Names**: Comprehensive SAN list for flexibility++### Subject Alternative Names (SANs)++The server certificate includes SANs for various deployment scenarios:++- `localhost` - Local development+- `127.0.0.1`, `0.0.0.0` - Local IP addresses+- `172.17.0.1` - Docker default bridge+- `host.docker.internal` - Docker host access++For production, customize the SANs in `server_ext.conf`:++```conf+[alt_names]+DNS.1 = your-domain.com+DNS.2 = opamp.your-domain.com+IP.1 = 192.168.1.100+```++## Supervisor Configuration++### Development Setup++```yaml+server:+ endpoint: wss://localhost:4320/v1/opamp+ tls:+ insecure_skip_verify: true+```++### Production Setup++```yaml+server:+ endpoint: wss://your-server:4320/v1/opamp+ tls:+ insecure_skip_verify: false+ ca_file: /app/opamp/certs/cert/ca.cert.pem+ # Required for mutual TLS (default in production):+ cert_file: /app/opamp/certs/client/client.cert.pem+ key_file: /app/opamp/certs/client/client.key.pem+```++### Automated Setup++Use the provided setup script:++```bash+# Development configuration+./setup-supervisor.sh --development++# Production configuration+./setup-supervisor.sh --production \+ --server-url wss://my-server:4320/v1/opamp \+ --output-dir /etc/opamp+```++## Security Best Practices++### Certificate Management++1. **Secure Storage**: Store private keys with restricted permissions (600)+2. **Regular Rotation**: Rotate certificates before expiration+3. **CA Protection**: Keep CA private key highly secure+4. **Distribution**: Securely distribute CA certificates to clients++### Production Deployment++1. **Use Real Domains**: Configure proper DNS names in certificates+2. **Enable Mutual TLS**: Use client certificates for authentication+3. **Monitor Expiry**: Set up alerts for certificate expiration+4. **Secure Transport**: Always use TLS in production++### File Permissions++```bash+# Set proper permissions after certificate generation+chmod 600 private/*.pem client/*.key.pem server/*.key.pem+chmod 644 cert/*.pem client/*.cert.pem server/*.cert.pem+chmod 700 private/+```++## Troubleshooting++### Common Issues++#### "certificate signed by unknown authority"++**Cause**: Client doesn't trust the self-signed CA certificate.++**Solutions**:+1. **Development**: Set `insecure_skip_verify: true` in supervisor config+2. **Production**: Provide CA certificate path in supervisor config+3. **Verify**: Ensure CA certificate is accessible and readable++#### "tls: certificate required" / "client didn't provide a certificate"++**Cause**: Server requires client certificates for mutual TLS, but client configuration is missing certificate files.++**Solutions**:+1. **Check client certificate files exist**:+ ```bash+ ls -la /app/opamp/certs/client/client.cert.pem+ ls -la /app/opamp/certs/client/client.key.pem+ ```+2. **Regenerate certificates if missing**:+ ```bash+ cd /app/opamp/certs && ./generate.sh --clean+ ```+3. **Update supervisor configuration**:+ ```yaml+ server:+ tls:+ cert_file: /app/opamp/certs/client/client.cert.pem+ key_file: /app/opamp/certs/client/client.key.pem+ ```+4. **Disable mutual TLS for development**:+ ```bash+ export OPAMP_TLS_REQUIRE_CLIENT_CERT=false+ ```++#### "certificate has expired"++**Cause**: Certificate validity period has passed.++**Solutions**:+1. Regenerate certificates: `cd certs && ./generate.sh --clean`+2. Check expiry: `openssl x509 -in cert/ca.cert.pem -noout -dates`+3. Set longer validity: `CERT_VALIDITY_DAYS=7300 ./generate.sh`++#### "certificate is valid for localhost, not your-server"++**Cause**: Certificate doesn't include the server's hostname/IP in SANs.++**Solutions**:+1. Update `server_ext.conf` with correct DNS names/IPs+2. Regenerate server certificate+3. Use IP address or localhost for development++#### Connection refused or timeout++**Cause**: Network connectivity or server configuration issues.++**Solutions**:+1. Verify server is running: `netstat -tlnp | grep 4320`+2. Check firewall rules for port 4320+3. Verify WebSocket support in network infrastructure++#### "Can't load /root/.rnd into RNG"++**Cause**: OpenSSL trying to access a random number generator file that doesn't exist.++**Solutions**:+1. **Fixed automatically**: This issue has been resolved in the current version+2. **Manual fix**: Remove or comment out `RANDFILE` in `openssl.conf`+3. **Verify fix**: Run `./generate.sh` and check for the error++### Validation Tools++#### Certificate Information++```bash+# View certificate details+openssl x509 -in cert/ca.cert.pem -noout -text++# Check certificate expiry+openssl x509 -in server/server.cert.pem -noout -dates++# Verify certificate chain+openssl verify -CAfile cert/ca.cert.pem server/server.cert.pem+```++#### Test TLS Connection++```bash+# Test TLS handshake+openssl s_client -connect localhost:4320 -CAfile cert/ca.cert.pem++# Test with client certificate+openssl s_client -connect localhost:4320 \+ -CAfile cert/ca.cert.pem \+ -cert client/client.cert.pem \+ -key client/client.key.pem+```++#### Built-in Validation++```bash+# Run certificate validation (requires Go build)+cd src/opamp-server+OPAMP_CERTS_DIR=/path/to/certs go run -tags validation ./cmd/validate-certs+```++## Advanced Configuration++### Custom Certificate Authority++For production environments, you may want to use certificates from a trusted CA:++1. **Obtain certificates** from your CA (Let's Encrypt, internal CA, etc.)+2. **Update paths** in configuration to point to your certificates+3. **Ensure compatibility** with OpAMP server certificate requirements++### Mutual TLS (mTLS)++Enable mutual TLS for enhanced security:++1. **Server configuration**:+ ```bash+ export OPAMP_TLS_REQUIRE_CLIENT_CERT=true+ ```++2. **Supervisor configuration**:+ ```yaml+ server:+ tls:+ cert_file: /path/to/client.cert.pem+ key_file: /path/to/client.key.pem+ ```++### Certificate Rotation++Implement automated certificate rotation:++1. **Monitor expiry** using the built-in validation tools+2. **Generate new certificates** before expiration+3. **Update configurations** and restart services+4. **Validate connectivity** after rotation++## Support++For issues related to certificate management:++1. Check the troubleshooting section above+2. Review server and supervisor logs+3. Validate certificate properties and expiry+4. Test network connectivity and TLS handshake++## Files Reference++- `generate.sh` - Certificate generation script+- `setup-supervisor.sh` - Supervisor configuration helper+- `openssl.conf` - OpenSSL CA configuration+- `server.conf` - Server certificate configuration+- `server_ext.conf` - Server certificate extensions+- `client.conf` - Client certificate configuration+- `supervisor.yaml` - Development supervisor configuration+- `supervisor-production.yaml` - Production supervisor templatediff --git a/src/opamp-server/README.md b/src/opamp-server/README.mdnew file mode 100644index 00000000..f7ae46f3--- /dev/null+++ b/src/opamp-server/README.md@@ -0,0 +1,55 @@+# Standalone OpAMP Server++This is a simplified version of the OpenTelemetry OpAMP server that can be used independently. It provides the core functionality of the OpAMP protocol without the UI server component.++## Features++- OpAMP protocol support+- Agent management+- Connection handling+- Status updates+- Configuration management++## Getting Started++1. Make sure you have Go installed (1.16 or later)++2. Create a new directory for your project and copy these files into it++3. Initialize the Go module:+ ```bash+ go mod init opamp-server+ ```++4. Install dependencies:+ ```bash+ go mod tidy+ ```++5. Run the server:+ ```bash+ go run .+ ```++The server will start and listen on `0.0.0.0:4320` by default.++## Configuration++The server is configured to run without TLS for simplicity. In a production environment, you should enable TLS by modifying the `Start()` function in `server/server.go`.++## API Endpoints++- `/v1/opamp` - The main OpAMP endpoint that agents connect to++## Integration with Other Services++You can integrate this server with your own services by:++1. Implementing custom configuration management+2. Adding authentication+3. Implementing custom agent status handling+4. Adding metrics collection++## License++This project uses the same license as the original OpenTelemetry OpAMP Go implementation.diff --git a/src/opamp-server/certman/certman.go b/src/opamp-server/certman/certman.gonew file mode 100644index 00000000..14500ac1--- /dev/null+++ b/src/opamp-server/certman/certman.go@@ -0,0 +1,380 @@+package certman++import (+ "bytes"+ "crypto/rand"+ "crypto/rsa"+ "crypto/tls"+ "crypto/x509"+ "crypto/x509/pkix"+ "encoding/pem"+ "errors"+ "fmt"+ "io/ioutil"+ "log"+ "math/big"+ "net"+ "os"+ "sync"+ "time"++ "opamp-server/constants"++ "github.com/open-telemetry/opamp-go/protobufs"+)++var logger = log.New(log.Default().Writer(), "[CertMan] ", log.Default().Flags()|log.Lmsgprefix|log.Lmicroseconds)++var (+ caCert *x509.Certificate+ caPrivKey *rsa.PrivateKey+ caCertBytes []byte+)++var loadCACertOnce sync.Once++func loadCACert() {++ // Load CA certificate.+ var err error+ caCertBytes, err = ioutil.ReadFile(constants.CaCertPath)+ if err != nil {+ logger.Fatalf("Cannot read CA cert: %v", err)+ }++ caKeyBytes, err := ioutil.ReadFile(constants.PrivateKeyPath)+ if err != nil {+ logger.Fatalf("Cannot read CA key: %v", err)+ }++ // Convert from DER to PEM format.+ caCertPB, _ := pem.Decode(caCertBytes)+ caKeyPB, _ := pem.Decode(caKeyBytes)++ caCert, err = x509.ParseCertificate(caCertPB.Bytes)+ if err != nil {+ logger.Fatalf("Cannot parse CA certificate: %v", err)+ }++ caPrivKey, err = x509.ParsePKCS1PrivateKey(caKeyPB.Bytes)+ if err != nil {+ logger.Fatalf("Cannot parse CA key: %v", err)+ }+}++func createClientTLSCertTemplate() *x509.Certificate {+ return &x509.Certificate{+ SerialNumber: big.NewInt(1),+ IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1)},+ NotBefore: time.Now(),+ NotAfter: time.Now().Add(time.Hour * 1000),+ ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},+ KeyUsage: x509.KeyUsageDigitalSignature,+ }+}++func CreateClientTLSCertFromCSR(csr *x509.CertificateRequest) (*protobufs.TLSCertificate, error) {+ loadCACertOnce.Do(loadCACert)++ template := createClientTLSCertTemplate()++ // Use the Subject from CSR.+ template.Subject = csr.Subject++ // Create the client cert and sign it using CA cert.+ certBytes, err := x509.CreateCertificate(rand.Reader, template, caCert, csr.PublicKey, caPrivKey)+ if err != nil {+ err := fmt.Errorf("cannot create certificate: %v", err)+ return nil, err+ }++ // Convert from DER to PEM format.+ certPEM := new(bytes.Buffer)+ pem.Encode(+ certPEM, &pem.Block{+ Type: "CERTIFICATE",+ Bytes: certBytes,+ },+ )++ // We have a client certificate with a public and private key.+ certificate := &protobufs.TLSCertificate{+ Cert: certPEM.Bytes(),+ CaCert: caCertBytes,+ }++ return certificate, nil+}++func CreateClientTLSCert() (*protobufs.TLSCertificate, error) {+ loadCACertOnce.Do(loadCACert)++ // Generate a keypair for new client cert.+ clientCertKeyPair, err := rsa.GenerateKey(rand.Reader, 4096)+ if err != nil {+ err := fmt.Errorf("cannot generate keypair: %v", err)+ return nil, err+ }++ // Prepare certificate template.+ template := createClientTLSCertTemplate()+ template.Subject = pkix.Name{+ CommonName: "OpAMP Example Client",+ Organization: []string{"OpenTelemetry OpAMP Workgroup"},+ Locality: []string{"Server-initiated"},+ }++ // Create the client cert. Sign it using CA cert.+ certDER, err := x509.CreateCertificate(rand.Reader, template, caCert, &clientCertKeyPair.PublicKey, caPrivKey)+ if err != nil {+ err := fmt.Errorf("cannot create certificate: %v", err)+ return nil, err+ }++ certPEM := new(bytes.Buffer)+ pem.Encode(+ certPEM, &pem.Block{+ Type: "CERTIFICATE",+ Bytes: certDER,+ },+ )++ privateKeyPEM := new(bytes.Buffer)+ pem.Encode(+ privateKeyPEM, &pem.Block{+ Type: "RSA PRIVATE KEY",+ Bytes: x509.MarshalPKCS1PrivateKey(clientCertKeyPair),+ },+ )++ // We have a client certificate with a public and private key.+ certificate := &protobufs.TLSCertificate{+ Cert: certPEM.Bytes(),+ PrivateKey: privateKeyPEM.Bytes(),+ CaCert: caCertBytes,+ }++ return certificate, nil+}++// TLSConfigOptions holds options for TLS configuration+type TLSConfigOptions struct {+ InsecureSkipVerify bool+ RequireClientCert bool+ MinTLSVersion uint16+ MaxTLSVersion uint16+}++// CreateServerTLSConfig creates a TLS configuration for the server with enhanced security options+func CreateServerTLSConfig(caCertPath, serverCertPath, serverKeyPath string) (*tls.Config, error) {+ return CreateServerTLSConfigWithOptions(caCertPath, serverCertPath, serverKeyPath, TLSConfigOptions{+ InsecureSkipVerify: false,+ RequireClientCert: false,+ MinTLSVersion: tls.VersionTLS12,+ MaxTLSVersion: tls.VersionTLS13,+ })+}++// CreateServerTLSConfigWithOptions creates a TLS configuration with custom options+func CreateServerTLSConfigWithOptions(caCertPath, serverCertPath, serverKeyPath string, options TLSConfigOptions) (*tls.Config, error) {+ // Validate certificate files first+ validator := NewCertificateValidator()++ // Check if certificate files exist+ if _, err := os.Stat(caCertPath); os.IsNotExist(err) {+ return nil, fmt.Errorf("CA certificate file not found: %s", caCertPath)+ }+ if _, err := os.Stat(serverCertPath); os.IsNotExist(err) {+ return nil, fmt.Errorf("server certificate file not found: %s", serverCertPath)+ }+ if _, err := os.Stat(serverKeyPath); os.IsNotExist(err) {+ return nil, fmt.Errorf("server private key file not found: %s", serverKeyPath)+ }++ // Validate certificate chain+ if err := validator.VerifyCertificateChain(serverCertPath, caCertPath); err != nil {+ logger.Printf("WARNING: Server certificate chain validation failed: %v", err)+ }++ // Check certificate expiry+ if err := validator.CheckCertificateExpiry(serverCertPath, 30); err != nil {+ logger.Printf("WARNING: %v", err)+ }++ // Read the CA's public key+ caCertBytes, err := os.ReadFile(caCertPath)+ if err != nil {+ return nil, fmt.Errorf("failed to read CA certificate: %v", err)+ }++ // Create a certificate pool and make our CA trusted+ caCertPool := x509.NewCertPool()+ if ok := caCertPool.AppendCertsFromPEM(caCertBytes); !ok {+ return nil, errors.New("failed to append CA certificate to pool")+ }++ // Load server's certificate+ cert, err := tls.LoadX509KeyPair(serverCertPath, serverKeyPath)+ if err != nil {+ return nil, fmt.Errorf("failed to load server certificate/key pair: %v", err)+ }++ // Determine client authentication mode+ clientAuth := tls.NoClientCert+ if options.RequireClientCert {+ clientAuth = tls.RequireAndVerifyClientCert+ } else {+ clientAuth = tls.VerifyClientCertIfGiven+ }++ tlsConfig := &tls.Config{+ Certificates: []tls.Certificate{cert},+ ClientAuth: clientAuth,+ ClientCAs: caCertPool,+ MinVersion: options.MinTLSVersion,+ MaxVersion: options.MaxTLSVersion,++ // Security settings+ InsecureSkipVerify: options.InsecureSkipVerify,++ // Prefer server cipher suites for better security+ PreferServerCipherSuites: true,++ // Use only secure cipher suites+ CipherSuites: []uint16{+ tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,+ tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,+ tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,+ tls.TLS_RSA_WITH_AES_256_GCM_SHA384,+ tls.TLS_RSA_WITH_AES_128_GCM_SHA256,+ },++ // Curve preferences+ CurvePreferences: []tls.CurveID{+ tls.X25519,+ tls.CurveP256,+ tls.CurveP384,+ },+ }++ logger.Printf("TLS configuration created successfully")+ logger.Printf(" Min TLS Version: %s", getTLSVersionString(options.MinTLSVersion))+ logger.Printf(" Max TLS Version: %s", getTLSVersionString(options.MaxTLSVersion))+ logger.Printf(" Client Auth: %s", getClientAuthString(clientAuth))+ logger.Printf(" Insecure Skip Verify: %t", options.InsecureSkipVerify)++ return tlsConfig, nil+}++// Helper function to get TLS version string+func getTLSVersionString(version uint16) string {+ switch version {+ case tls.VersionTLS10:+ return "TLS 1.0"+ case tls.VersionTLS11:+ return "TLS 1.1"+ case tls.VersionTLS12:+ return "TLS 1.2"+ case tls.VersionTLS13:+ return "TLS 1.3"+ default:+ return fmt.Sprintf("Unknown (%d)", version)+ }+}++// Helper function to get client auth string+func getClientAuthString(auth tls.ClientAuthType) string {+ switch auth {+ case tls.NoClientCert:+ return "No Client Certificate"+ case tls.RequestClientCert:+ return "Request Client Certificate"+ case tls.RequireAnyClientCert:+ return "Require Any Client Certificate"+ case tls.VerifyClientCertIfGiven:+ return "Verify Client Certificate If Given"+ case tls.RequireAndVerifyClientCert:+ return "Require and Verify Client Certificate"+ default:+ return fmt.Sprintf("Unknown (%d)", auth)+ }+}++func CreateTLSCert(caCertPath, caKeyPath string) (*protobufs.TLSCertificate, error) {+ // Load CA Cert.+ caCertBytes, err := os.ReadFile(caCertPath)+ if err != nil {+ return nil, fmt.Errorf("cannot read CA cert: %v", err)+ }++ caKeyBytes, err := os.ReadFile(caKeyPath)+ if err != nil {+ return nil, fmt.Errorf("cannot read CA key: %v", err)+ }++ caCertPB, _ := pem.Decode(caCertBytes)+ caKeyPB, _ := pem.Decode(caKeyBytes)+ caCert, err := x509.ParseCertificate(caCertPB.Bytes)+ if err != nil {+ return nil, fmt.Errorf("cannot parse CA cert: %v", err)+ }++ caPrivKey, err := x509.ParsePKCS1PrivateKey(caKeyPB.Bytes)+ if err != nil {+ return nil, fmt.Errorf("cannot parse CA key: %v", err)+ }++ // Generate a private key for new client cert.+ certPrivKey, err := rsa.GenerateKey(rand.Reader, 4096)+ if err != nil {+ err := fmt.Errorf("cannot generate private key: %v", err)+ return nil, err+ }++ // Prepare certificate template.+ template := &x509.Certificate{+ SerialNumber: big.NewInt(1),+ Subject: pkix.Name{+ CommonName: "OpAMP Example Client",+ Organization: []string{"OpAMP Example"},+ Country: []string{"CA"},+ Province: []string{"ON"},+ Locality: []string{"City"},+ StreetAddress: []string{""},+ PostalCode: []string{""},+ },+ IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1)},+ NotBefore: time.Now(),+ NotAfter: time.Now().Add(time.Hour * 1000),+ ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},+ KeyUsage: x509.KeyUsageDigitalSignature,+ }++ // Create the client cert. Sign it using CA cert.+ certBytes, err := x509.CreateCertificate(rand.Reader, template, caCert, &certPrivKey.PublicKey, caPrivKey)+ if err != nil {+ err := fmt.Errorf("cannot create certificate: %v", err)+ return nil, err+ }++ publicKeyPEM := new(bytes.Buffer)+ pem.Encode(publicKeyPEM, &pem.Block{+ Type: "CERTIFICATE",+ Bytes: certBytes,+ })++ privateKeyPEM := new(bytes.Buffer)+ pem.Encode(privateKeyPEM, &pem.Block{+ Type: "RSA PRIVATE KEY",+ Bytes: x509.MarshalPKCS1PrivateKey(certPrivKey),+ })++ // We have a client certificate with a public and private key.+ certificate := &protobufs.TLSCertificate{+ Cert: publicKeyPEM.Bytes(),+ PrivateKey: privateKeyPEM.Bytes(),+ CaCert: caCertBytes,+ }++ return certificate, nil+}diff --git a/src/opamp-server/certman/validator.go b/src/opamp-server/certman/validator.gonew file mode 100644index 00000000..3655acf8--- /dev/null+++ b/src/opamp-server/certman/validator.go@@ -0,0 +1,240 @@+package certman++import (+ "crypto/x509"+ "encoding/pem"+ "fmt"+ "log"+ "os"+ "time"+)++// CertificateInfo holds information about a certificate+type CertificateInfo struct {+ Subject string+ Issuer string+ SerialNumber string+ NotBefore time.Time+ NotAfter time.Time+ DNSNames []string+ IPAddresses []string+ IsCA bool+ KeyUsage x509.KeyUsage+ ExtKeyUsage []x509.ExtKeyUsage+}++// CertificateValidator provides certificate validation functionality+type CertificateValidator struct {+ logger *log.Logger+}++// NewCertificateValidator creates a new certificate validator+func NewCertificateValidator() *CertificateValidator {+ return &CertificateValidator{+ logger: logger,+ }+}++// ValidateCertificateFile validates a certificate file+func (cv *CertificateValidator) ValidateCertificateFile(certPath string) (*CertificateInfo, error) {+ // Read certificate file+ certBytes, err := os.ReadFile(certPath)+ if err != nil {+ return nil, fmt.Errorf("failed to read certificate file %s: %v", certPath, err)+ }++ return cv.ValidateCertificateBytes(certBytes)+}++// ValidateCertificateBytes validates certificate bytes+func (cv *CertificateValidator) ValidateCertificateBytes(certBytes []byte) (*CertificateInfo, error) {+ // Decode PEM block+ block, _ := pem.Decode(certBytes)+ if block == nil {+ return nil, fmt.Errorf("failed to decode PEM block")+ }++ // Parse certificate+ cert, err := x509.ParseCertificate(block.Bytes)+ if err != nil {+ return nil, fmt.Errorf("failed to parse certificate: %v", err)+ }++ // Extract certificate information+ info := &CertificateInfo{+ Subject: cert.Subject.String(),+ Issuer: cert.Issuer.String(),+ SerialNumber: cert.SerialNumber.String(),+ NotBefore: cert.NotBefore,+ NotAfter: cert.NotAfter,+ DNSNames: cert.DNSNames,+ IsCA: cert.IsCA,+ KeyUsage: cert.KeyUsage,+ ExtKeyUsage: cert.ExtKeyUsage,+ }++ // Convert IP addresses to strings+ for _, ip := range cert.IPAddresses {+ info.IPAddresses = append(info.IPAddresses, ip.String())+ }++ return info, nil+}++// CheckCertificateExpiry checks if a certificate is expired or expiring soon+func (cv *CertificateValidator) CheckCertificateExpiry(certPath string, warningDays int) error {+ info, err := cv.ValidateCertificateFile(certPath)+ if err != nil {+ return err+ }++ now := time.Now()++ // Check if certificate is expired+ if now.After(info.NotAfter) {+ return fmt.Errorf("certificate %s is expired (expired on %s)", certPath, info.NotAfter.Format(time.RFC3339))+ }++ // Check if certificate is expiring soon+ warningTime := now.Add(time.Duration(warningDays) * 24 * time.Hour)+ if warningTime.After(info.NotAfter) {+ cv.logger.Printf("WARNING: Certificate %s will expire in %d days (expires on %s)",+ certPath, int(info.NotAfter.Sub(now).Hours()/24), info.NotAfter.Format(time.RFC3339))+ }++ return nil+}++// VerifyCertificateChain verifies that a certificate is signed by the CA+func (cv *CertificateValidator) VerifyCertificateChain(certPath, caCertPath string) error {+ // Read CA certificate+ caCertBytes, err := os.ReadFile(caCertPath)+ if err != nil {+ return fmt.Errorf("failed to read CA certificate: %v", err)+ }++ caBlock, _ := pem.Decode(caCertBytes)+ if caBlock == nil {+ return fmt.Errorf("failed to decode CA certificate PEM")+ }++ caCert, err := x509.ParseCertificate(caBlock.Bytes)+ if err != nil {+ return fmt.Errorf("failed to parse CA certificate: %v", err)+ }++ // Read certificate to verify+ certBytes, err := os.ReadFile(certPath)+ if err != nil {+ return fmt.Errorf("failed to read certificate: %v", err)+ }++ certBlock, _ := pem.Decode(certBytes)+ if certBlock == nil {+ return fmt.Errorf("failed to decode certificate PEM")+ }++ cert, err := x509.ParseCertificate(certBlock.Bytes)+ if err != nil {+ return fmt.Errorf("failed to parse certificate: %v", err)+ }++ // Create certificate pool with CA+ caPool := x509.NewCertPool()+ caPool.AddCert(caCert)++ // Verify certificate+ opts := x509.VerifyOptions{+ Roots: caPool,+ }++ _, err = cert.Verify(opts)+ if err != nil {+ return fmt.Errorf("certificate verification failed: %v", err)+ }++ cv.logger.Printf("Certificate %s successfully verified against CA %s", certPath, caCertPath)+ return nil+}++// ValidateKeyPair validates that a certificate and private key match+func (cv *CertificateValidator) ValidateKeyPair(certPath, keyPath string) error {+ // This is a basic validation - in production you might want more thorough checks+ certInfo, err := os.Stat(certPath)+ if err != nil {+ return fmt.Errorf("certificate file not found: %v", err)+ }++ keyInfo, err := os.Stat(keyPath)+ if err != nil {+ return fmt.Errorf("private key file not found: %v", err)+ }++ // Check file permissions+ if certInfo.Mode().Perm() != 0644 {+ cv.logger.Printf("WARNING: Certificate file %s has permissions %o, should be 644", certPath, certInfo.Mode().Perm())+ }++ if keyInfo.Mode().Perm() != 0600 {+ cv.logger.Printf("WARNING: Private key file %s has permissions %o, should be 600", keyPath, keyInfo.Mode().Perm())+ }++ return nil+}++// GetCertificateInfo returns detailed information about a certificate+func (cv *CertificateValidator) GetCertificateInfo(certPath string) (*CertificateInfo, error) {+ return cv.ValidateCertificateFile(certPath)+}++// CheckAllCertificates performs comprehensive validation of all certificates+func (cv *CertificateValidator) CheckAllCertificates(caCertPath, serverCertPath, serverKeyPath, clientCertPath, clientKeyPath string) error {+ cv.logger.Printf("Starting comprehensive certificate validation...")++ // Check CA certificate+ cv.logger.Printf("Validating CA certificate...")+ caInfo, err := cv.ValidateCertificateFile(caCertPath)+ if err != nil {+ return fmt.Errorf("CA certificate validation failed: %v", err)+ }++ if !caInfo.IsCA {+ return fmt.Errorf("CA certificate is not marked as CA")+ }++ // Check CA certificate expiry+ if err := cv.CheckCertificateExpiry(caCertPath, 30); err != nil {+ return fmt.Errorf("CA certificate expiry check failed: %v", err)+ }++ // Check server certificate+ cv.logger.Printf("Validating server certificate...")+ if err := cv.ValidateKeyPair(serverCertPath, serverKeyPath); err != nil {+ return fmt.Errorf("server certificate/key validation failed: %v", err)+ }++ if err := cv.VerifyCertificateChain(serverCertPath, caCertPath); err != nil {+ return fmt.Errorf("server certificate chain validation failed: %v", err)+ }++ if err := cv.CheckCertificateExpiry(serverCertPath, 30); err != nil {+ return fmt.Errorf("server certificate expiry check failed: %v", err)+ }++ // Check client certificate+ cv.logger.Printf("Validating client certificate...")+ if err := cv.ValidateKeyPair(clientCertPath, clientKeyPath); err != nil {+ return fmt.Errorf("client certificate/key validation failed: %v", err)+ }++ if err := cv.VerifyCertificateChain(clientCertPath, caCertPath); err != nil {+ return fmt.Errorf("client certificate chain validation failed: %v", err)+ }++ if err := cv.CheckCertificateExpiry(clientCertPath, 30); err != nil {+ return fmt.Errorf("client certificate expiry check failed: %v", err)+ }++ cv.logger.Printf("All certificate validations passed successfully!")+ return nil+}diff --git a/src/opamp-server/certs/cert/.gitkeep b/src/opamp-server/certs/cert/.gitkeepnew file mode 100644index 00000000..e69de29bdiff --git a/src/opamp-server/certs/clear.sh b/src/opamp-server/certs/clear.shnew file mode 100755index 00000000..79cbdfc3--- /dev/null+++ b/src/opamp-server/certs/clear.sh@@ -0,0 +1,8 @@+rm cert/*+rm server/*+rm private/*+rm client/*+rm index.*+rm serial.*+echo 01 > serial+touch index.txtdiff --git a/src/opamp-server/certs/client.conf b/src/opamp-server/certs/client.confnew file mode 100644index 00000000..9d6e09d3--- /dev/null+++ b/src/opamp-server/certs/client.conf@@ -0,0 +1,34 @@+[req]+default_bits = 4096+distinguished_name = req_distinguished_name+req_extensions = req_ext+x509_extensions = v3_req+prompt = no++[req_distinguished_name]+C = IN+ST = Delhi+L = Delhi+O = OpenLIT+OU = OpAMP Client+CN = OpAMP Example Client++[req_ext]+subjectAltName = @alt_names+keyUsage = keyEncipherment, dataEncipherment+extendedKeyUsage = clientAuth++[v3_req]+subjectAltName = @alt_names+keyUsage = keyEncipherment, dataEncipherment+extendedKeyUsage = clientAuth++[alt_names]+# Local development+IP.1 = 127.0.0.1+IP.2 = 0.0.0.0+DNS.1 = localhost++# Docker/Container environments+IP.3 = 172.17.0.1+DNS.2 = host.docker.internal\ No newline at end of filediff --git a/src/opamp-server/certs/client/.gitkeep b/src/opamp-server/certs/client/.gitkeepnew file mode 100644index 00000000..e69de29bdiff --git a/src/opamp-server/certs/generate.sh b/src/opamp-server/certs/generate.shnew file mode 100755index 00000000..7585d762--- /dev/null+++ b/src/opamp-server/certs/generate.sh@@ -0,0 +1,193 @@+#!/bin/bash++# OpenLIT OpAMP Server Certificate Generation Script+# This script creates a complete PKI infrastructure for secure OpAMP communication+# including CA, server, and client certificates with proper production settings.++set -e # Exit on any error++# Configuration+CERT_VALIDITY_DAYS=${CERT_VALIDITY_DAYS:-3650} # 10 years for CA+SERVER_CERT_DAYS=${SERVER_CERT_DAYS:-365} # 1 year for server cert+CLIENT_CERT_DAYS=${CLIENT_CERT_DAYS:-365} # 1 year for client cert++# Colors for output+RED='\033[0;31m'+GREEN='\033[0;32m'+YELLOW='\033[1;33m'+NC='\033[0m' # No Color++# Logging functions+log_info() {+ echo -e "${GREEN}[INFO]${NC} $1"+}++log_warn() {+ echo -e "${YELLOW}[WARN]${NC} $1"+}++log_error() {+ echo -e "${RED}[ERROR]${NC} $1"+}++# Check if OpenSSL is available+if ! command -v openssl &> /dev/null; then+ log_error "OpenSSL is not installed or not in PATH"+ exit 1+fi++log_info "Starting certificate generation for OpenLIT OpAMP Server..."++# Create necessary directories+log_info "Creating certificate directories..."+mkdir -p cert server client private+chmod 755 cert server client+chmod 700 private++# Clean up existing certificates if requested+if [[ "${1:-}" == "--clean" ]] || [[ ! -f "index.txt" ]]; then+ log_info "Cleaning up existing certificates..."+ ./clear.sh+fi++# Initialize CA database if it doesn't exist+if [[ ! -f "index.txt" ]]; then+ touch index.txt+ echo 01 > serial+fi++# Generate CA private key+log_info "Generating CA private key..."+if [[ ! -f "private/ca.key.pem" ]]; then+ openssl genrsa -out private/ca.key.pem 4096+ chmod 600 private/ca.key.pem+ log_info "CA private key generated successfully"+else+ log_warn "CA private key already exists, skipping generation"+fi++# Generate CA certificate+log_info "Generating CA certificate..."+if [[ ! -f "cert/ca.cert.pem" ]]; then+ openssl req -new -x509 -days $CERT_VALIDITY_DAYS -key private/ca.key.pem -out cert/ca.cert.pem -config openssl.conf+ chmod 644 cert/ca.cert.pem+ log_info "CA certificate generated successfully"++ # Display CA certificate info+ log_info "CA Certificate Information:"+ openssl x509 -in cert/ca.cert.pem -noout -subject -dates+else+ log_warn "CA certificate already exists, skipping generation"+fi++# Generate client private key+log_info "Generating client private key..."+if [[ ! -f "client/client.key.pem" ]]; then+ openssl genrsa -out client/client.key.pem 4096+ chmod 600 client/client.key.pem+ log_info "Client private key generated successfully"+else+ log_warn "Client private key already exists, skipping generation"+fi++# Generate client certificate signing request+log_info "Generating client certificate signing request..."+if [[ ! -f "client/client.csr" ]]; then+ openssl req -new -key client/client.key.pem -out client/client.csr -config client.conf+ chmod 600 client/client.csr+ log_info "Client CSR generated successfully"+else+ log_warn "Client CSR already exists, skipping generation"+fi++# Generate client certificate+log_info "Generating client certificate..."+if [[ ! -f "client/client.cert.pem" ]]; then+ openssl ca -config openssl.conf -days $CLIENT_CERT_DAYS -notext -batch -in client/client.csr -out client/client.cert.pem+ chmod 644 client/client.cert.pem+ log_info "Client certificate generated successfully"++ # Display client certificate info+ log_info "Client Certificate Information:"+ openssl x509 -in client/client.cert.pem -noout -subject -dates+else+ log_warn "Client certificate already exists, skipping generation"+fi++# Generate server private key+log_info "Generating server private key..."+if [[ ! -f "server/server.key.pem" ]]; then+ openssl genrsa -out server/server.key.pem 4096+ chmod 600 server/server.key.pem+ log_info "Server private key generated successfully"+else+ log_warn "Server private key already exists, skipping generation"+fi++# Generate server certificate signing request+log_info "Generating server certificate signing request..."+if [[ ! -f "server/server.csr" ]]; then+ openssl req -new -key server/server.key.pem -out server/server.csr -config server.conf+ chmod 600 server/server.csr+ log_info "Server CSR generated successfully"+else+ log_warn "Server CSR already exists, skipping generation"+fi++# Generate server certificate+log_info "Generating server certificate..."+if [[ ! -f "server/server.cert.pem" ]]; then+ openssl ca -config openssl.conf -extfile server_ext.conf -days $SERVER_CERT_DAYS -notext -batch -in server/server.csr -out server/server.cert.pem+ chmod 644 server/server.cert.pem+ log_info "Server certificate generated successfully"++ # Display server certificate info+ log_info "Server Certificate Information:"+ openssl x509 -in server/server.cert.pem -noout -subject -dates+ log_info "Server Certificate Subject Alternative Names:"+ openssl x509 -in server/server.cert.pem -noout -text | grep -A 1 "Subject Alternative Name" || echo "No SAN found"+else+ log_warn "Server certificate already exists, skipping generation"+fi++# Verify certificate chain+log_info "Verifying certificate chain..."+if openssl verify -CAfile cert/ca.cert.pem server/server.cert.pem > /dev/null 2>&1; then+ log_info "Server certificate verification: PASSED"+else+ log_error "Server certificate verification: FAILED"+ exit 1+fi++if openssl verify -CAfile cert/ca.cert.pem client/client.cert.pem > /dev/null 2>&1; then+ log_info "Client certificate verification: PASSED"+else+ log_error "Client certificate verification: FAILED"+ exit 1+fi++# Set proper file permissions+log_info "Setting proper file permissions..."+find . -name "*.key.pem" -exec chmod 600 {} \;+find . -name "*.cert.pem" -exec chmod 644 {} \;+find . -name "*.csr" -exec chmod 600 {} \;+chmod 700 private+chmod 755 cert server client++log_info "Certificate generation completed successfully!"+log_info "Generated files:"+log_info " CA Certificate: cert/ca.cert.pem"+log_info " CA Private Key: private/ca.key.pem"+log_info " Server Certificate: server/server.cert.pem"+log_info " Server Private Key: server/server.key.pem"+log_info " Client Certificate: client/client.cert.pem"+log_info " Client Private Key: client/client.key.pem"++# Check certificate expiration+log_info "Certificate expiration dates:"+echo "CA Certificate:"+openssl x509 -in cert/ca.cert.pem -noout -dates | grep "notAfter"+echo "Server Certificate:"+openssl x509 -in server/server.cert.pem -noout -dates | grep "notAfter"+echo "Client Certificate:"+openssl x509 -in client/client.cert.pem -noout -dates | grep "notAfter"diff --git a/src/opamp-server/certs/index.txt.attr b/src/opamp-server/certs/index.txt.attrnew file mode 100644index 00000000..8f7e63a3--- /dev/null+++ b/src/opamp-server/certs/index.txt.attr@@ -0,0 +1 @@+unique_subject = yesdiff --git a/src/opamp-server/certs/index.txt.attr.old b/src/opamp-server/certs/index.txt.attr.oldnew file mode 100644index 00000000..8f7e63a3--- /dev/null+++ b/src/opamp-server/certs/index.txt.attr.old@@ -0,0 +1 @@+unique_subject = yesdiff --git a/src/opamp-server/certs/index.txt.old b/src/opamp-server/certs/index.txt.oldnew file mode 100644index 00000000..55cec1c3--- /dev/null+++ b/src/opamp-server/certs/index.txt.old@@ -0,0 +1 @@+V 261107191059Z 01 unknown /C=IN/ST=Delhi/O=OpenLIT/OU=OpAMP Client/CN=OpAMP Example Clientdiff --git a/src/opamp-server/certs/openssl.conf b/src/opamp-server/certs/openssl.confnew file mode 100644index 00000000..f05fc533--- /dev/null+++ b/src/opamp-server/certs/openssl.conf@@ -0,0 +1,88 @@+# OpenSSL configuration file+HOME = .+# RANDFILE removed - not needed for modern OpenSSL versions++oid_section = new_oids++[ new_oids ]+tsa_policy1 = 1.2.3.4.1+tsa_policy2 = 1.2.3.4.5.6+tsa_policy3 = 1.2.3.4.5.7++####################################################################+[ ca ]+default_ca = CA_default++[ CA_default ]+dir = .+certs = $dir/cert+database = $dir/index.txt+new_certs_dir = $dir/cert+certificate = $dir/cert/ca.cert.pem+serial = $dir/serial+crlnumber = $dir/crlnumber+private_key = $dir/private/ca.key.pem++name_opt = ca_default+cert_opt = ca_default++default_days = 365+default_crl_days= 30+default_md = sha256+preserve = no+policy = policy_match++[ policy_match ]+countryName = match+stateOrProvinceName = match+organizationName = match+organizationalUnitName = optional+commonName = supplied+emailAddress = optional++[ policy_anything ]+countryName = optional+stateOrProvinceName = optional+localityName = optional+organizationName = optional+organizationalUnitName = optional+commonName = supplied+emailAddress = optional++####################################################################+[ req ]+default_bits = 4096+default_md = sha256+default_keyfile = privkey.pem+distinguished_name = req_distinguished_name+attributes = req_attributes+prompt = no+x509_extensions = v3_ca++# CA Distinguished Name+[ req_distinguished_name ]+C = IN+ST = Delhi+L = Delhi+O = OpenLIT+OU = Certificate Authority+CN = OpenLIT Root CA++[ req_attributes ]+# Leave empty for non-interactive mode++[ v3_req ]+basicConstraints = CA:FALSE+keyUsage = critical, nonRepudiation, digitalSignature, keyEncipherment+extendedKeyUsage = serverAuth, clientAuth++[ v3_ca ]+# CA certificate extensions+subjectKeyIdentifier = hash+authorityKeyIdentifier = keyid:always,issuer+basicConstraints = critical, CA:true, pathlen:0+keyUsage = critical, keyCertSign, cRLSign+nsCertType = sslCA, emailCA++[ crl_ext ]+authorityKeyIdentifier=keyid:always\ No newline at end of filediff --git a/src/opamp-server/certs/private/.gitkeep b/src/opamp-server/certs/private/.gitkeepnew file mode 100644index 00000000..e69de29bdiff --git a/src/opamp-server/certs/serial b/src/opamp-server/certs/serialnew file mode 100644index 00000000..75016ea3--- /dev/null+++ b/src/opamp-server/certs/serial@@ -0,0 +1 @@+03diff --git a/src/opamp-server/certs/serial.old b/src/opamp-server/certs/serial.oldnew file mode 100644index 00000000..9e22bcb8--- /dev/null+++ b/src/opamp-server/certs/serial.old@@ -0,0 +1 @@+02diff --git a/src/opamp-server/certs/server.conf b/src/opamp-server/certs/server.confnew file mode 100644index 00000000..bf589d55--- /dev/null+++ b/src/opamp-server/certs/server.conf@@ -0,0 +1,42 @@+[req]+default_bits = 4096+distinguished_name = req_distinguished_name+req_extensions = req_ext+x509_extensions = v3_req+prompt = no++[req_distinguished_name]+C = IN+ST = Delhi+L = Delhi+O = OpenLIT+OU = OpAMP Server+CN = OpenLIT OpAMP Server++[req_ext]+subjectAltName = @alt_names+keyUsage = keyEncipherment, dataEncipherment+extendedKeyUsage = serverAuth, clientAuth++[v3_req]+subjectAltName = @alt_names+keyUsage = keyEncipherment, dataEncipherment+extendedKeyUsage = serverAuth, clientAuth++[alt_names]+# Local development+IP.1 = 127.0.0.1+IP.2 = 0.0.0.0+DNS.1 = localhost++# Docker/Container environments+IP.3 = 172.17.0.1+DNS.2 = host.docker.internal++# Production domains (customize as needed)+# DNS.3 = opamp.yourdomain.com+# DNS.4 = *.yourdomain.com++# Kubernetes service names (customize as needed)+# DNS.5 = openlit-opamp-server+# DNS.6 = openlit-opamp-server.default.svc.cluster.local\ No newline at end of filediff --git a/src/opamp-server/certs/server/.gitkeep b/src/opamp-server/certs/server/.gitkeepnew file mode 100644index 00000000..e69de29bdiff --git a/src/opamp-server/certs/server_ext.conf b/src/opamp-server/certs/server_ext.confnew file mode 100644index 00000000..fa29502a--- /dev/null+++ b/src/opamp-server/certs/server_ext.conf@@ -0,0 +1,26 @@+basicConstraints = CA:FALSE+nsCertType = server+nsComment = "OpenLIT OpAMP Server Certificate"+subjectKeyIdentifier = hash+authorityKeyIdentifier = keyid,issuer:always+keyUsage = critical, digitalSignature, keyEncipherment+extendedKeyUsage = serverAuth, clientAuth+subjectAltName = @alt_names++[alt_names]+# Local development+IP.1 = 127.0.0.1+IP.2 = 0.0.0.0+DNS.1 = localhost++# Docker/Container environments+IP.3 = 172.17.0.1+DNS.2 = host.docker.internal++# Production domains (customize as needed)+# DNS.3 = opamp.yourdomain.com+# DNS.4 = *.yourdomain.com++# Kubernetes service names (customize as needed)+# DNS.5 = openlit-opamp-server+# DNS.6 = openlit-opamp-server.default.svc.cluster.local\ No newline at end of filediff --git a/src/opamp-server/config/config.go b/src/opamp-server/config/config.gonew file mode 100644index 00000000..129d8b80--- /dev/null+++ b/src/opamp-server/config/config.go@@ -0,0 +1,164 @@+package config++import (+ "os"+ "strconv"+ "strings"+)++// TLSConfig holds TLS-related configuration+type TLSConfig struct {+ // Certificate paths+ CertificatesDirectory string+ CaCertPath string+ ServerCertPath string+ ServerCertKeyPath string+ ClientCertPath string+ ClientKeyPath string+ PrivateKeyPath string++ // TLS behavior+ InsecureSkipVerify bool+ RequireClientCert bool+ MinTLSVersion string+ MaxTLSVersion string++ // Environment+ Environment string+}++// ServerConfig holds server configuration+type ServerConfig struct {+ // Server settings+ ListenAddress string+ ListenPort string+ APIPort string++ // TLS configuration+ TLS TLSConfig++ // Logging+ LogLevel string+}++// NewConfig creates a new configuration with environment-aware defaults+func NewConfig() *ServerConfig {+ config := &ServerConfig{+ ListenAddress: "0.0.0.0",+ ListenPort: "4320",+ APIPort: "8080",+ LogLevel: getEnvOrDefault("OPAMP_LOG_LEVEL", "info"),+ }++ // Initialize TLS configuration+ config.TLS = TLSConfig{+ Environment: getEnvOrDefault("OPAMP_ENVIRONMENT", "development"),+ CertificatesDirectory: getEnvOrDefault("OPAMP_CERTS_DIR", "/app/opamp/certs"),+ MinTLSVersion: getEnvOrDefault("OPAMP_TLS_MIN_VERSION", "1.2"),+ MaxTLSVersion: getEnvOrDefault("OPAMP_TLS_MAX_VERSION", "1.3"),+ InsecureSkipVerify: getEnvBool("OPAMP_TLS_INSECURE_SKIP_VERIFY", false),+ RequireClientCert: getEnvBool("OPAMP_TLS_REQUIRE_CLIENT_CERT", true),+ }++ // Set certificate paths based on certificates directory+ config.TLS.CaCertPath = config.TLS.CertificatesDirectory + "/cert/ca.cert.pem"+ config.TLS.ServerCertPath = config.TLS.CertificatesDirectory + "/server/server.cert.pem"+ config.TLS.ServerCertKeyPath = config.TLS.CertificatesDirectory + "/server/server.key.pem"+ config.TLS.ClientCertPath = config.TLS.CertificatesDirectory + "/client/client.cert.pem"+ config.TLS.ClientKeyPath = config.TLS.CertificatesDirectory + "/client/client.key.pem"+ config.TLS.PrivateKeyPath = config.TLS.CertificatesDirectory + "/private/ca.key.pem"++ // Environment-specific overrides+ switch strings.ToLower(config.TLS.Environment) {+ case "development", "dev":+ config.TLS.InsecureSkipVerify = getEnvBool("OPAMP_TLS_INSECURE_SKIP_VERIFY", true)+ config.TLS.RequireClientCert = getEnvBool("OPAMP_TLS_REQUIRE_CLIENT_CERT", false)+ case "production", "prod":+ config.TLS.InsecureSkipVerify = getEnvBool("OPAMP_TLS_INSECURE_SKIP_VERIFY", false)+ config.TLS.RequireClientCert = getEnvBool("OPAMP_TLS_REQUIRE_CLIENT_CERT", true)+ case "testing", "test":+ config.TLS.InsecureSkipVerify = getEnvBool("OPAMP_TLS_INSECURE_SKIP_VERIFY", true)+ config.TLS.RequireClientCert = getEnvBool("OPAMP_TLS_REQUIRE_CLIENT_CERT", false)+ }++ return config+}++// IsProduction returns true if running in production environment+func (c *ServerConfig) IsProduction() bool {+ env := strings.ToLower(c.TLS.Environment)+ return env == "production" || env == "prod"+}++// IsDevelopment returns true if running in development environment+func (c *ServerConfig) IsDevelopment() bool {+ env := strings.ToLower(c.TLS.Environment)+ return env == "development" || env == "dev"+}++// GetListenEndpoint returns the formatted listen endpoint+func (c *ServerConfig) GetListenEndpoint() string {+ return c.ListenAddress + ":" + c.ListenPort+}++// GetAPIEndpoint returns the formatted API endpoint+func (c *ServerConfig) GetAPIEndpoint() string {+ return c.ListenAddress + ":" + c.APIPort+}++// Validate checks if the configuration is valid+func (c *ServerConfig) Validate() error {+ // Check if certificate files exist in production+ if c.IsProduction() && !c.TLS.InsecureSkipVerify {+ if err := c.validateCertificateFiles(); err != nil {+ return err+ }+ }+ return nil+}++// validateCertificateFiles checks if required certificate files exist+func (c *ServerConfig) validateCertificateFiles() error {+ requiredFiles := []string{+ c.TLS.CaCertPath,+ c.TLS.ServerCertPath,+ c.TLS.ServerCertKeyPath,+ }++ for _, file := range requiredFiles {+ if _, err := os.Stat(file); os.IsNotExist(err) {+ return &CertificateError{+ Message: "Required certificate file not found: " + file,+ Path: file,+ }+ }+ }+ return nil+}++// Helper functions+func getEnvOrDefault(key, defaultValue string) string {+ if value := os.Getenv(key); value != "" {+ return value+ }+ return defaultValue+}++func getEnvBool(key string, defaultValue bool) bool {+ if value := os.Getenv(key); value != "" {+ if parsed, err := strconv.ParseBool(value); err == nil {+ return parsed+ }+ }+ return defaultValue+}++// CertificateError represents a certificate-related error+type CertificateError struct {+ Message string+ Path string+}++func (e *CertificateError) Error() string {+ return e.Message+}diff --git a/src/opamp-server/constants/certificatespath.go b/src/opamp-server/constants/certificatespath.gonew file mode 100644index 00000000..4bac5a81--- /dev/null+++ b/src/opamp-server/constants/certificatespath.go@@ -0,0 +1,47 @@+package constants++import (+ "os"+ "path/filepath"+)++// Default certificate paths - can be overridden by environment variables+var (+ // Base directory for certificates+ CertificatesDirectory = getEnvOrDefault("OPAMP_CERTS_DIR", "/app/opamp/certs")++ // Certificate Authority files+ CaCertPath = filepath.Join(CertificatesDirectory, "cert", "ca.cert.pem")+ PrivateKeyPath = filepath.Join(CertificatesDirectory, "private", "ca.key.pem")++ // Server certificate files+ ServerCertPath = filepath.Join(CertificatesDirectory, "server", "server.cert.pem")+ ServerCertKeyPath = filepath.Join(CertificatesDirectory, "server", "server.key.pem")+ ServerCSRPath = filepath.Join(CertificatesDirectory, "server", "server.csr")++ // Client certificate files+ ClientCertPath = filepath.Join(CertificatesDirectory, "client", "client.cert.pem")+ ClientKeyPath = filepath.Join(CertificatesDirectory, "client", "client.key.pem")+ ClientCSRPath = filepath.Join(CertificatesDirectory, "client", "client.csr")+)++// getEnvOrDefault returns environment variable value or default if not set+func getEnvOrDefault(key, defaultValue string) string {+ if value := os.Getenv(key); value != "" {+ return value+ }+ return defaultValue+}++// UpdateCertificatePaths updates all certificate paths based on a new base directory+func UpdateCertificatePaths(baseDir string) {+ CertificatesDirectory = baseDir+ CaCertPath = filepath.Join(baseDir, "cert", "ca.cert.pem")+ PrivateKeyPath = filepath.Join(baseDir, "private", "ca.key.pem")+ ServerCertPath = filepath.Join(baseDir, "server", "server.cert.pem")+ ServerCertKeyPath = filepath.Join(baseDir, "server", "server.key.pem")+ ServerCSRPath = filepath.Join(baseDir, "server", "server.csr")+ ClientCertPath = filepath.Join(baseDir, "client", "client.cert.pem")+ ClientKeyPath = filepath.Join(baseDir, "client", "client.key.pem")+ ClientCSRPath = filepath.Join(baseDir, "client", "client.csr")+}diff --git a/src/opamp-server/data/agent.go b/src/opamp-server/data/agent.gonew file mode 100644index 00000000..7e3956b6--- /dev/null+++ b/src/opamp-server/data/agent.go@@ -0,0 +1,518 @@+package data++import (+ "bytes"+ "context"+ "crypto/sha256"+ "crypto/tls"+ "crypto/x509"+ "encoding/pem"+ "fmt"+ "sync"+ "time"++ "opamp-server/certman"++ "github.com/google/uuid"+ "google.golang.org/protobuf/proto"++ "github.com/open-telemetry/opamp-go/protobufs"+ "github.com/open-telemetry/opamp-go/server/types"+)++// Agent represents a connected Agent.+type Agent struct {+ // Some fields in this struct are exported so that we can render them in the UI.++ // Agent's instance id. This is an immutable field.+ InstanceId InstanceId+ InstanceIdStr string++ // Connection to the Agent.+ conn types.Connection++ // mutex for the fields that follow it.+ mux sync.RWMutex++ // Agent's current status.+ Status *protobufs.AgentToServer++ // The time when the agent has started. Valid only if Status.Health.Up==true+ StartedAt time.Time++ // Effective config reported by the Agent.+ EffectiveConfig string++ // Optional special remote config for this particular instance defined by+ // the user in the UI.+ CustomInstanceConfig string++ // Client certificate+ ClientCert *x509.Certificate+ ClientCertSha256Fingerprint string+ ClientCertOfferError string++ // Remote config that we will give to this Agent.+ remoteConfig *protobufs.AgentRemoteConfig++ // Channels to notify when this Agent's status is updated next time.+ statusUpdateWatchers []chan<- struct{}+}++func NewAgent(+ instanceId InstanceId,+ conn types.Connection,+) *Agent {+ agent := &Agent{InstanceId: instanceId, InstanceIdStr: uuid.UUID(instanceId).String(), conn: conn}+ tslConn, ok := conn.Connection().(*tls.Conn)+ if ok {+ // Client is using TLS connection.+ connState := tslConn.ConnectionState()+ if len(connState.PeerCertificates) > 0 {+ // Client uses client-side certificate. Get certificate details to display in the UI.+ leafClientCert := connState.PeerCertificates[0]+ fingerprint := sha256.Sum256(leafClientCert.Raw)+ agent.ClientCert = leafClientCert+ agent.ClientCertSha256Fingerprint = fmt.Sprintf("%X", fingerprint)+ }+ }++ return agent+}++// CloneReadonly returns a copy of the Agent that is safe to read.+// Functions that modify the Agent should not be called on the cloned copy.+func (agent *Agent) CloneReadonly() *Agent {+ agent.mux.RLock()+ defer agent.mux.RUnlock()++ var clonedStatus *protobufs.AgentToServer+ if agent.Status != nil {+ clonedStatus = proto.Clone(agent.Status).(*protobufs.AgentToServer)+ }++ var clonedRemoteConfig *protobufs.AgentRemoteConfig+ if agent.remoteConfig != nil {+ clonedRemoteConfig = proto.Clone(agent.remoteConfig).(*protobufs.AgentRemoteConfig)+ }++ return &Agent{+ InstanceId: agent.InstanceId,+ InstanceIdStr: uuid.UUID(agent.InstanceId).String(),+ Status: clonedStatus,+ EffectiveConfig: agent.EffectiveConfig,+ CustomInstanceConfig: agent.CustomInstanceConfig,+ remoteConfig: clonedRemoteConfig,+ StartedAt: agent.StartedAt,+ ClientCert: agent.ClientCert,+ ClientCertOfferError: agent.ClientCertOfferError,+ ClientCertSha256Fingerprint: agent.ClientCertSha256Fingerprint,+ }+}++// UpdateStatus updates the status of the Agent struct based on the newly received+// status report and sets appropriate fields in the response message to be sent+// to the Agent.+func (agent *Agent) UpdateStatus(+ statusMsg *protobufs.AgentToServer,+ response *protobufs.ServerToAgent,+) {+ agent.mux.Lock()++ agent.processStatusUpdate(statusMsg, response)++ if statusMsg.ConnectionSettingsRequest != nil {+ agent.processConnectionSettingsRequest(statusMsg.ConnectionSettingsRequest.Opamp, response)+ }++ statusUpdateWatchers := agent.statusUpdateWatchers+ agent.statusUpdateWatchers = nil++ agent.mux.Unlock()++ // Notify watcher outside mutex to avoid blocking the mutex for too long.+ notifyStatusWatchers(statusUpdateWatchers)+}++func notifyStatusWatchers(statusUpdateWatchers []chan<- struct{}) {+ // Notify everyone who is waiting on this Agent's status updates.+ for _, ch := range statusUpdateWatchers {+ select {+ case ch <- struct{}{}:+ default:+ }+ }+}++func (agent *Agent) updateAgentDescription(newStatus *protobufs.AgentToServer) (agentDescrChanged bool) {+ prevStatus := agent.Status++ if agent.Status == nil {+ // First time this Agent reports a status, remember it.+ agent.Status = newStatus+ agentDescrChanged = true+ } else {+ // Not a new Agent. Update the Status.+ agent.Status.SequenceNum = newStatus.SequenceNum++ // Check what's changed in the AgentDescription.+ if newStatus.AgentDescription != nil {+ // If the AgentDescription field is set it means the Agent tells us+ // something is changed in the field since the last status report+ // (or this is the first report).+ // Make full comparison of previous and new descriptions to see if it+ // really is different.+ if prevStatus != nil && proto.Equal(prevStatus.AgentDescription, newStatus.AgentDescription) {+ // Agent description didn't change.+ agentDescrChanged = false+ } else {+ // Yes, the description is different, update it.+ agent.Status.AgentDescription = newStatus.AgentDescription+ agentDescrChanged = true+ }+ } else {+ // AgentDescription field is not set, which means description didn't change.+ agentDescrChanged = false+ }++ // Update remote config status if it is included and is different from what we have.+ if newStatus.RemoteConfigStatus != nil &&+ !proto.Equal(agent.Status.RemoteConfigStatus, newStatus.RemoteConfigStatus) {+ agent.Status.RemoteConfigStatus = newStatus.RemoteConfigStatus+ }+ }+ return agentDescrChanged+}++func (agent *Agent) updateHealth(newStatus *protobufs.AgentToServer) {+ if newStatus.Health == nil {+ return+ }++ agent.Status.Health = newStatus.Health++ if agent.Status != nil && agent.Status.Health != nil && agent.Status.Health.Healthy {+ agent.StartedAt = time.Unix(0, int64(agent.Status.Health.StartTimeUnixNano)).UTC()+ }+}++func (agent *Agent) updateRemoteConfigStatus(newStatus *protobufs.AgentToServer) {+ // Update remote config status if it is included and is different from what we have.+ if newStatus.RemoteConfigStatus != nil {+ agent.Status.RemoteConfigStatus = newStatus.RemoteConfigStatus+ }+}++func (agent *Agent) updateStatusField(newStatus *protobufs.AgentToServer) (agentDescrChanged bool) {+ if agent.Status == nil {+ // First time this Agent reports a status, remember it.+ agent.Status = newStatus+ agentDescrChanged = true+ }++ agentDescrChanged = agent.updateAgentDescription(newStatus) || agentDescrChanged+ agent.updateRemoteConfigStatus(newStatus)+ agent.updateHealth(newStatus)++ return agentDescrChanged+}++func (agent *Agent) updateEffectiveConfig(+ newStatus *protobufs.AgentToServer,+ response *protobufs.ServerToAgent,+) {+ // Update effective config if provided.+ if newStatus.EffectiveConfig != nil {+ if newStatus.EffectiveConfig.ConfigMap != nil {+ agent.Status.EffectiveConfig = newStatus.EffectiveConfig++ // Convert to string for displaying purposes.+ agent.EffectiveConfig = ""+ for _, cfg := range newStatus.EffectiveConfig.ConfigMap.ConfigMap {+ // TODO: we just concatenate parts of effective config as a single+ // blob to show in the UI. A proper approach is to keep the effective+ // config as a set and show the set in the UI.+ agent.EffectiveConfig = agent.EffectiveConfig + string(cfg.Body)+ }+ }+ }+}++func (agent *Agent) hasCapability(capability protobufs.AgentCapabilities) bool {+ return agent.Status.Capabilities&uint64(capability) != 0+}++func (agent *Agent) processStatusUpdate(+ newStatus *protobufs.AgentToServer,+ response *protobufs.ServerToAgent,+) {+ // We don't have any status for this Agent, or we lost the previous status update from the Agent, so our+ // current status is not up-to-date.+ lostPreviousUpdate := (agent.Status == nil) || (agent.Status != nil && agent.Status.SequenceNum+1 != newStatus.SequenceNum)++ agentDescrChanged := agent.updateStatusField(newStatus)++ // Check if any fields were omitted in the status report.+ effectiveConfigOmitted := newStatus.EffectiveConfig == nil &&+ agent.hasCapability(protobufs.AgentCapabilities_AgentCapabilities_ReportsEffectiveConfig)++ packageStatusesOmitted := newStatus.PackageStatuses == nil &&+ agent.hasCapability(protobufs.AgentCapabilities_AgentCapabilities_ReportsPackageStatuses)++ remoteConfigStatusOmitted := newStatus.RemoteConfigStatus == nil &&+ agent.hasCapability(protobufs.AgentCapabilities_AgentCapabilities_ReportsRemoteConfig)++ healthOmitted := newStatus.Health == nil &&+ agent.hasCapability(protobufs.AgentCapabilities_AgentCapabilities_ReportsHealth)++ // True if the status was not fully reported.+ statusIsCompressed := effectiveConfigOmitted || packageStatusesOmitted || remoteConfigStatusOmitted || healthOmitted++ if statusIsCompressed && lostPreviousUpdate {+ // The status message is not fully set in the message that we received, but we lost the previous+ // status update. Request full status update from the agent.+ response.Flags |= uint64(protobufs.ServerToAgentFlags_ServerToAgentFlags_ReportFullState)+ }++ configChanged := false+ if agentDescrChanged {+ // Agent description is changed.++ // We need to recalculate the config.+ configChanged = agent.calcRemoteConfig()++ // And set connection settings that are appropriate for the Agent description.+ agent.calcConnectionSettings(response)+ }++ // If remote config is changed and different from what the Agent has then+ // send the new remote config to the Agent.+ if configChanged ||+ (agent.Status.RemoteConfigStatus != nil &&+ bytes.Compare(agent.Status.RemoteConfigStatus.LastRemoteConfigHash, agent.remoteConfig.ConfigHash) != 0) {+ // The new status resulted in a change in the config of the Agent or the Agent+ // does not have this config (hash is different). Send the new config the Agent.+ response.RemoteConfig = agent.remoteConfig+ }++ agent.updateEffectiveConfig(newStatus, response)+}++// SetCustomConfig sets a custom config for this Agent.+// notifyWhenConfigIsApplied channel is notified after the remote config is applied+// to the Agent and after the Agent reports back the effective config.+// If the provided config is equal to the current remoteConfig of the Agent+// then we will not send any config to the Agent and notifyWhenConfigIsApplied channel+// will be notified immediately. This requires that notifyWhenConfigIsApplied channel+// has a buffer size of at least 1.+func (agent *Agent) SetCustomConfig(+ config *protobufs.AgentConfigMap,+ notifyWhenConfigIsApplied chan<- struct{},+) {+ agent.mux.Lock()++ agent.CustomInstanceConfig = string(config.ConfigMap[""].Body)++ configChanged := agent.calcRemoteConfig()+ if configChanged {+ if notifyWhenConfigIsApplied != nil {+ // The caller wants to be notified when the Agent reports a status+ // update next time. This is typically used in the UI to wait until+ // the configuration changes are propagated successfully to the Agent.+ agent.statusUpdateWatchers = append(+ agent.statusUpdateWatchers,+ notifyWhenConfigIsApplied,+ )+ }+ msg := &protobufs.ServerToAgent{+ RemoteConfig: agent.remoteConfig,+ }+ agent.mux.Unlock()++ agent.SendToAgent(msg)+ } else {+ agent.mux.Unlock()++ if notifyWhenConfigIsApplied != nil {+ // No config change. We are not going to send config to the Agent and+ // as a result we do not expect status update from the Agent, so we will+ // just notify the waiter that the config change is done.+ notifyWhenConfigIsApplied <- struct{}{}+ }+ }+}++// calcRemoteConfig calculates the remote config for this Agent. It returns true if+// the calculated new config is different from the existing config stored in+// Agent.remoteConfig.+func (agent *Agent) calcRemoteConfig() bool {+ hash := sha256.New()++ cfg := protobufs.AgentRemoteConfig{+ Config: &protobufs.AgentConfigMap{+ ConfigMap: map[string]*protobufs.AgentConfigFile{},+ },+ }++ // Add the custom config for this particular Agent instance. Use empty+ // string as the config file name.+ cfg.Config.ConfigMap[""] = &protobufs.AgentConfigFile{+ Body: []byte(agent.CustomInstanceConfig),+ }++ // Calculate the hash.+ for k, v := range cfg.Config.ConfigMap {+ hash.Write([]byte(k))+ hash.Write(v.Body)+ hash.Write([]byte(v.ContentType))+ }++ cfg.ConfigHash = hash.Sum(nil)++ configChanged := !isEqualRemoteConfig(agent.remoteConfig, &cfg)++ agent.remoteConfig = &cfg++ return configChanged+}++func isEqualRemoteConfig(c1, c2 *protobufs.AgentRemoteConfig) bool {+ if c1 == c2 {+ return true+ }+ if c1 == nil || c2 == nil {+ return false+ }+ return isEqualConfigSet(c1.Config, c2.Config)+}++func isEqualConfigSet(c1, c2 *protobufs.AgentConfigMap) bool {+ if c1 == c2 {+ return true+ }+ if c1 == nil || c2 == nil {+ return false+ }+ if len(c1.ConfigMap) != len(c2.ConfigMap) {+ return false+ }+ for k, v1 := range c1.ConfigMap {+ v2, ok := c2.ConfigMap[k]+ if !ok {+ return false+ }+ if !isEqualConfigFile(v1, v2) {+ return false+ }+ }+ return true+}++func isEqualConfigFile(f1, f2 *protobufs.AgentConfigFile) bool {+ if f1 == f2 {+ return true+ }+ if f1 == nil || f2 == nil {+ return false+ }+ return bytes.Compare(f1.Body, f2.Body) == 0 && f1.ContentType == f2.ContentType+}++func (agent *Agent) calcConnectionSettings(response *protobufs.ServerToAgent) {+ // Here we can use Agent's description to send the appropriate connection+ // settings to the Agent.+ // In this simple example the connection settings do not depend on the+ // Agent description, so we jst set them directly.++ response.ConnectionSettings = &protobufs.ConnectionSettingsOffers{+ Hash: nil, // TODO: calc has from settings.+ Opamp: nil,+ OwnMetrics: &protobufs.TelemetryConnectionSettings{+ // We just hard-code this to a port on a localhost on which we can+ // run an Otel Collector for demo purposes. With real production+ // servers this should likely point to an OTLP backend.+ DestinationEndpoint: "http://localhost:4318/v1/metrics",+ },+ OwnTraces: nil,+ OwnLogs: nil,+ OtherConnections: nil,+ }+ response.ConnectionSettings.Hash = toHash(response.ConnectionSettings)+}++func (agent *Agent) SendToAgent(msg *protobufs.ServerToAgent) {+ agent.conn.Send(context.Background(), msg)+}++func (agent *Agent) OfferConnectionSettings(offers *protobufs.ConnectionSettingsOffers) {+ agent.SendToAgent(+ &protobufs.ServerToAgent{+ ConnectionSettings: offers,+ },+ )+}++func (agent *Agent) addErrorResponse(errMsg string, response *protobufs.ServerToAgent) {+ logger.Println(errMsg)+ if response.ErrorResponse == nil {+ response.ErrorResponse = &protobufs.ServerErrorResponse{+ Type: protobufs.ServerErrorResponseType_ServerErrorResponseType_BadRequest,+ ErrorMessage: errMsg,+ Details: nil,+ }+ } else if response.ErrorResponse.Type == protobufs.ServerErrorResponseType_ServerErrorResponseType_BadRequest {+ // Append this error message to the existing error message.+ response.ErrorResponse.ErrorMessage += errMsg+ } else {+ // Can't report it since it is a different error type.+ // TODO: consider adding support for reporting multiple errors of different type in the response.+ }+}++func (agent *Agent) processConnectionSettingsRequest(+ request *protobufs.OpAMPConnectionSettingsRequest, response *protobufs.ServerToAgent,+) {+ if request == nil || request.CertificateRequest == nil {+ return+ }++ csrDer, _ := pem.Decode(request.CertificateRequest.Csr)+ if csrDer == nil {+ agent.addErrorResponse("Failed to decode PEM certificate request", response)+ return+ }++ csr, err := x509.ParseCertificateRequest(csrDer.Bytes)+ if err != nil {+ agent.addErrorResponse("Failed to parse received certificate request: "+err.Error(), response)+ return+ }++ if csr.CheckSignature() != err {+ agent.addErrorResponse("Certificate request signature check failed: "+err.Error(), response)+ return+ }++ // Verify the CSR's details and decide if we want to honor the request.+ // For example verify the CommonName.+ if csr.Subject.CommonName != "OpAMP Example Client" {+ agent.addErrorResponse("Invalid CommonName in certificate request", response)+ return+ }++ // Create a new certificate for the agent.+ certificate, err := certman.CreateClientTLSCertFromCSR(csr)+ if err != nil {+ agent.addErrorResponse("Failed to create client certificate from CSR: "+err.Error(), response)+ return+ }++ // Create an offer for the agent.+ if response.ConnectionSettings == nil {+ response.ConnectionSettings = &protobufs.ConnectionSettingsOffers{}+ }+ response.ConnectionSettings.Opamp = &protobufs.OpAMPConnectionSettings{+ Certificate: certificate,+ }+ response.ConnectionSettings.Hash = toHash(response.ConnectionSettings)+}diff --git a/src/opamp-server/data/agents.go b/src/opamp-server/data/agents.gonew file mode 100644index 00000000..8ee9139b--- /dev/null+++ b/src/opamp-server/data/agents.go@@ -0,0 +1,213 @@+package data++import (+ "crypto/sha256"+ "io"+ "log"+ "sync"++ "github.com/open-telemetry/opamp-go/protobufs"+ "github.com/open-telemetry/opamp-go/protobufshelpers"+ "github.com/open-telemetry/opamp-go/server/types"+)++type Agents struct {+ mux sync.RWMutex+ agentsById map[InstanceId]*Agent+ connections map[types.Connection]map[InstanceId]bool+}++var logger = log.New(log.Default().Writer(), "[AGENTS] ", log.Default().Flags()|log.Lmsgprefix|log.Lmicroseconds)++// RemoveConnection removes the connection all Agent instances associated with the+// connection.+func (agents *Agents) RemoveConnection(conn types.Connection) {+ agents.mux.Lock()+ defer agents.mux.Unlock()++ for instanceId := range agents.connections[conn] {+ delete(agents.agentsById, instanceId)+ }+ delete(agents.connections, conn)+}++func (agents *Agents) SetCustomConfigForAgent(+ agentId InstanceId,+ config *protobufs.AgentConfigMap,+ notifyNextStatusUpdate chan<- struct{},+) {+ agent := agents.FindAgent(agentId)+ if agent != nil {+ agent.SetCustomConfig(config, notifyNextStatusUpdate)+ }+}++func isEqualAgentDescr(d1, d2 *protobufs.AgentDescription) bool {+ if d1 == d2 {+ return true+ }+ if d1 == nil || d2 == nil {+ return false+ }+ return isEqualAttrs(d1.IdentifyingAttributes, d2.IdentifyingAttributes) &&+ isEqualAttrs(d1.NonIdentifyingAttributes, d2.NonIdentifyingAttributes)+}++func isEqualAttrs(attrs1, attrs2 []*protobufs.KeyValue) bool {+ if len(attrs1) != len(attrs2) {+ return false+ }+ for i, a1 := range attrs1 {+ a2 := attrs2[i]+ if !protobufshelpers.IsEqualKeyValue(a1, a2) {+ return false+ }+ }+ return true+}++func (agents *Agents) FindAgent(agentId InstanceId) *Agent {+ agents.mux.RLock()+ defer agents.mux.RUnlock()+ return agents.agentsById[agentId]+}++func (agents *Agents) FindOrCreateAgent(agentId InstanceId, conn types.Connection) *Agent {+ agents.mux.Lock()+ defer agents.mux.Unlock()++ // Ensure the Agent is in the agentsById map.+ agent := agents.agentsById[agentId]+ if agent == nil {+ agent = NewAgent(agentId, conn)+ agents.agentsById[agentId] = agent++ // Ensure the Agent's instance id is associated with the connection.+ if agents.connections[conn] == nil {+ agents.connections[conn] = map[InstanceId]bool{}+ }+ agents.connections[conn][agentId] = true+ }++ return agent+}++func (agents *Agents) GetAgentReadonlyClone(agentId InstanceId) *Agent {+ agent := agents.FindAgent(agentId)+ if agent == nil {+ return nil+ }++ // Return a clone to allow safe access after returning.+ return agent.CloneReadonly()+}++func (agents *Agents) GetAllAgentsReadonlyClone() map[InstanceId]*Agent {+ agents.mux.RLock()++ // Clone the map first+ m := map[InstanceId]*Agent{}+ for id, agent := range agents.agentsById {+ m[id] = agent+ }+ agents.mux.RUnlock()++ // Clone agents in the map+ for id, agent := range m {+ // Return a clone to allow safe access after returning.+ m[id] = agent.CloneReadonly()+ }+ return m+}++func (a *Agents) OfferAgentConnectionSettings(+ id InstanceId,+ offers *protobufs.ConnectionSettingsOffers,+) {+ if len(offers.Hash) == 0 {+ offers.Hash = toHash(offers)+ }++ a.mux.Lock()+ defer a.mux.Unlock()++ agent, ok := a.agentsById[id]+ if ok {+ agent.OfferConnectionSettings(offers)+ logger.Printf("Client connection settings offers sent to %s (hash=%x)\n", id, offers.Hash)+ } else {+ logger.Printf("Agent %s not found\n", id)+ }+}++var AllAgents = Agents{+ agentsById: map[InstanceId]*Agent{},+ connections: map[types.Connection]map[InstanceId]bool{},+}++// toHash computes a sha256 hash from fields within ConnectionSettingsOffers+func toHash(c *protobufs.ConnectionSettingsOffers) []byte {+ hasher := sha256.New()+ if c.Opamp != nil {+ hashEndpoint(hasher, c.Opamp)+ }+ if c.OwnMetrics != nil {+ hashEndpoint(hasher, c.OwnMetrics)+ }+ if c.OwnTraces != nil {+ hashEndpoint(hasher, c.OwnTraces)+ }+ if c.OwnLogs != nil {+ hashEndpoint(hasher, c.OwnLogs)+ }+ for name, endpoint := range c.OtherConnections {+ hasher.Write([]byte(name))+ hashEndpoint(hasher, endpoint)+ }++ return hasher.Sum(nil)+}++// endpoint is an incomplete interface to assist with turning an offered connection into a hash.+type endpoint interface {+ GetDestinationEndpoint() string+ GetHeaders() *protobufs.Headers+ GetCertificate() *protobufs.TLSCertificate+ GetTls() *protobufs.TLSConnectionSettings+}++// hashEndpoint writes some shared attributes of the passed enpoint to the passed writer.+func hashEndpoint(w io.Writer, e endpoint) {+ _, err := w.Write([]byte(e.GetDestinationEndpoint()))+ if err != nil {+ panic(err)+ }+ if headers := e.GetHeaders(); headers != nil {+ for _, header := range headers.Headers {+ _, err := w.Write([]byte(header.Key + header.Value))+ if err != nil {+ panic(err)+ }+ }+ }+ if cert := e.GetCertificate(); cert != nil {+ _, err := w.Write(cert.Cert)+ if err != nil {+ panic(err)+ }+ _, err = w.Write(cert.PrivateKey)+ if err != nil {+ panic(err)+ }+ _, err = w.Write(cert.CaCert)+ if err != nil {+ panic(err)+ }+ }+ if tlsSettings := e.GetTls(); tlsSettings != nil {+ _, err := w.Write([]byte(tlsSettings.CaPemContents))+ if err != nil {+ panic(err)+ }+ }+}diff --git a/src/opamp-server/data/instanceid.go b/src/opamp-server/data/instanceid.gonew file mode 100644index 00000000..b40ae23a--- /dev/null+++ b/src/opamp-server/data/instanceid.go@@ -0,0 +1,5 @@+package data++import "github.com/google/uuid"++type InstanceId uuid.UUIDdiff --git a/src/opamp-server/go.mod b/src/opamp-server/go.modnew file mode 100644index 00000000..b0983fb3--- /dev/null+++ b/src/opamp-server/go.mod@@ -0,0 +1,22 @@+module opamp-server++go 1.25.0++require (+ github.com/google/uuid v1.6.0+ github.com/oklog/ulid/v2 v2.1.1+ github.com/open-telemetry/opamp-go v0.21.0+ go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.62.0+ google.golang.org/protobuf v1.36.7+)++require (+ github.com/felixge/httpsnoop v1.0.4 // indirect+ github.com/go-logr/logr v1.4.3 // indirect+ github.com/go-logr/stdr v1.2.2 // indirect+ github.com/gorilla/websocket v1.5.3 // indirect+ go.opentelemetry.io/auto/sdk v1.1.0 // indirect+ go.opentelemetry.io/otel v1.37.0 // indirect+ go.opentelemetry.io/otel/metric v1.37.0 // indirect+ go.opentelemetry.io/otel/trace v1.37.0 // indirect+)diff --git a/src/opamp-server/go.sum b/src/opamp-server/go.sumnew file mode 100644index 00000000..f8cbcb85--- /dev/null+++ b/src/opamp-server/go.sum@@ -0,0 +1,44 @@+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=+github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=+github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=+github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=+github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=+github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=+github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=+github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=+github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=+github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=+github.com/oklog/ulid/v2 v2.1.1 h1:suPZ4ARWLOJLegGFiZZ1dFAkqzhMjL3J1TzI+5wHz8s=+github.com/oklog/ulid/v2 v2.1.1/go.mod h1:rcEKHmBBKfef9DhnvX7y1HZBYxjXb0cP5ExxNsTT1QQ=+github.com/open-telemetry/opamp-go v0.21.0 h1:G2e0G4bi2Il3Z4hHqbXUA05m5jajdhQLxq2dBARvT5U=+github.com/open-telemetry/opamp-go v0.21.0/go.mod h1:d8/1ubFfy2QkTodIC9rd+9A3OCC/6788jSJ6uil1uLk=+github.com/pborman/getopt v0.0.0-20170112200414-7148bc3a4c30/go.mod h1:85jBQOZwpVEaDAr341tbn15RS4fCAsIst0qp7i8ex1o=+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=+github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=+github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=+go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=+go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=+go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.62.0 h1:Hf9xI/XLML9ElpiHVDNwvqI0hIFlzV8dgIr35kV1kRU=+go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.62.0/go.mod h1:NfchwuyNoMcZ5MLHwPrODwUF1HWCXWrL31s8gSAdIKY=+go.opentelemetry.io/otel v1.37.0 h1:9zhNfelUvx0KBfu/gb+ZgeAfAgtWrfHJZcAqFC228wQ=+go.opentelemetry.io/otel v1.37.0/go.mod h1:ehE/umFRLnuLa/vSccNq9oS1ErUlkkK71gMcN34UG8I=+go.opentelemetry.io/otel/metric v1.37.0 h1:mvwbQS5m0tbmqML4NqK+e3aDiO02vsf/WgbsdpcPoZE=+go.opentelemetry.io/otel/metric v1.37.0/go.mod h1:04wGrZurHYKOc+RKeye86GwKiTb9FKm1WHtO+4EVr2E=+go.opentelemetry.io/otel/sdk v1.37.0 h1:ItB0QUqnjesGRvNcmAcU0LyvkVyGJ2xftD29bWdDvKI=+go.opentelemetry.io/otel/sdk v1.37.0/go.mod h1:VredYzxUvuo2q3WRcDnKDjbdvmO0sCzOvVAiY+yUkAg=+go.opentelemetry.io/otel/sdk/metric v1.37.0 h1:90lI228XrB9jCMuSdA0673aubgRobVZFhbjxHHspCPc=+go.opentelemetry.io/otel/sdk/metric v1.37.0/go.mod h1:cNen4ZWfiD37l5NhS+Keb5RXVWZWpRE+9WyVCpbo5ps=+go.opentelemetry.io/otel/trace v1.37.0 h1:HLdcFNbRQBE2imdSEgm/kwqmQj1Or1l/7bW6mxVK7z4=+go.opentelemetry.io/otel/trace v1.37.0/go.mod h1:TlgrlQ+PtQO5XFerSPUYG0JSgGyryXewPGyayAWSBS0=+golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=+golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=+google.golang.org/protobuf v1.36.7 h1:IgrO7UwFQGJdRNXH/sQux4R1Dj1WAKcLElzeeRaXV2A=+google.golang.org/protobuf v1.36.7/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY=+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=diff --git a/src/opamp-server/main.go b/src/opamp-server/main.gonew file mode 100644index 00000000..05beccb4--- /dev/null+++ b/src/opamp-server/main.go@@ -0,0 +1,30 @@+package main++import (+ "log"+ "os"+ "os/signal"++ "opamp-server/data"+ "opamp-server/server"+)++var logger = log.New(log.Default().Writer(), "[MAIN] ", log.Default().Flags()|log.Lmsgprefix|log.Lmicroseconds)++func main() {+ logger.Println("OpAMP Server starting...")++ // Create and start the OpAMP server+ opampSrv := server.NewServer(&data.AllAgents)+ opampSrv.Start()++ logger.Println("OpAMP Server running...")++ // Wait for interrupt signal+ interrupt := make(chan os.Signal, 1)+ signal.Notify(interrupt, os.Interrupt)+ <-interrupt++ logger.Println("OpAMP Server shutting down...")+ opampSrv.Stop()+}diff --git a/src/opamp-server/opamp-server b/src/opamp-server/opamp-servernew file mode 100755index 00000000..48e84ebdBinary files /dev/null and b/src/opamp-server/opamp-server differdiff --git a/src/opamp-server/server/logger.go b/src/opamp-server/server/logger.gonew file mode 100644index 00000000..8c112548--- /dev/null+++ b/src/opamp-server/server/logger.go@@ -0,0 +1,83 @@+package server++import (+ "context"+ "log"+)++// OpAMPLogger wraps a standard logger to implement the OpAMP Logger interface+type OpAMPLogger struct {+ logger *log.Logger+}++func NewOpAMPLogger(logger *log.Logger) *OpAMPLogger {+ return &OpAMPLogger{logger: logger}+}++func (l *OpAMPLogger) Debugf(_ context.Context, format string, v ...interface{}) {+ l.logger.Printf("[DEBUG] "+format, v...)+}++func (l *OpAMPLogger) Errorf(_ context.Context, format string, v ...interface{}) {+ l.logger.Printf("[ERROR] "+format, v...)+}++func (l *OpAMPLogger) Warnf(_ context.Context, format string, v ...interface{}) {+ l.logger.Printf("[WARN] "+format, v...)+}++func (l *OpAMPLogger) Infof(_ context.Context, format string, v ...interface{}) {+ l.logger.Printf("[INFO] "+format, v...)+}++func (l *OpAMPLogger) Debug(_ context.Context, msg string) {+ l.logger.Printf("[DEBUG] %s", msg)+}++func (l *OpAMPLogger) Error(_ context.Context, msg string) {+ l.logger.Printf("[ERROR] %s", msg)+}++func (l *OpAMPLogger) Warn(_ context.Context, msg string) {+ l.logger.Printf("[WARN] %s", msg)+}++func (l *OpAMPLogger) Info(_ context.Context, msg string) {+ l.logger.Printf("[INFO] %s", msg)+}++func (l *OpAMPLogger) Printf(format string, v ...interface{}) {+ l.logger.Printf(format, v...)+}++func (l *OpAMPLogger) Print(v ...interface{}) {+ l.logger.Print(v...)+}++func (l *OpAMPLogger) Println(v ...interface{}) {+ l.logger.Println(v...)+}++func (l *OpAMPLogger) Fatal(v ...interface{}) {+ l.logger.Fatal(v...)+}++func (l *OpAMPLogger) Fatalf(format string, v ...interface{}) {+ l.logger.Fatalf(format, v...)+}++func (l *OpAMPLogger) Fatalln(v ...interface{}) {+ l.logger.Fatalln(v...)+}++func (l *OpAMPLogger) Panic(v ...interface{}) {+ l.logger.Panic(v...)+}++func (l *OpAMPLogger) Panicf(format string, v ...interface{}) {+ l.logger.Panicf(format, v...)+}++func (l *OpAMPLogger) Panicln(v ...interface{}) {+ l.logger.Panicln(v...)+}diff --git a/src/opamp-server/server/server.go b/src/opamp-server/server/server.gonew file mode 100644index 00000000..ddacf767--- /dev/null+++ b/src/opamp-server/server/server.go@@ -0,0 +1,208 @@+package server++import (+ "context"+ "crypto/tls"+ "fmt"+ "log"+ "net/http"+ "os"+ "strings"++ "github.com/oklog/ulid/v2"+ "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"++ "opamp-server/certman"+ "opamp-server/config"+ "opamp-server/constants"+ "opamp-server/data"++ "github.com/open-telemetry/opamp-go/protobufs"+ "github.com/open-telemetry/opamp-go/server"+ "github.com/open-telemetry/opamp-go/server/types"+)++type Server struct {+ opampSrv server.OpAMPServer+ httpSrv *http.Server+ agents *data.Agents+ logger *OpAMPLogger+ config *config.ServerConfig+}++func NewServer(agents *data.Agents) *Server {+ // Load configuration+ cfg := config.NewConfig()++ logger := &OpAMPLogger{+ log.New(+ log.Default().Writer(),+ "[OPAMP] ",+ log.Default().Flags()|log.Lmsgprefix|log.Lmicroseconds,+ ),+ }++ // Update certificate paths if custom directory is specified+ if cfg.TLS.CertificatesDirectory != constants.CertificatesDirectory {+ constants.UpdateCertificatePaths(cfg.TLS.CertificatesDirectory)+ }++ srv := &Server{+ agents: agents,+ logger: logger,+ config: cfg,+ }++ srv.opampSrv = server.New(logger)++ mux := http.NewServeMux()+ srv.setupRoutes(mux)+ srv.httpSrv = &http.Server{+ Addr: cfg.GetAPIEndpoint(),+ Handler: mux,+ }++ logger.Printf("Starting API server on %s", cfg.GetAPIEndpoint())+ go srv.httpSrv.ListenAndServe()++ return srv+}++func (srv *Server) Start() {+ srv.logger.Printf("Starting OpAMP server in %s environment", srv.config.TLS.Environment)++ // Validate configuration+ if err := srv.config.Validate(); err != nil {+ if srv.config.IsProduction() {+ srv.logger.Errorf(context.Background(), "Configuration validation failed in production: %v", err)+ os.Exit(1)+ } else {+ srv.logger.Printf("WARNING: Configuration validation failed (continuing in %s mode): %v", srv.config.TLS.Environment, err)+ }+ }++ settings := server.StartSettings{+ Settings: server.Settings{+ Callbacks: types.Callbacks{+ OnConnecting: func(request *http.Request) types.ConnectionResponse {+ return types.ConnectionResponse{+ Accept: true,+ ConnectionCallbacks: types.ConnectionCallbacks{+ OnMessage: srv.onMessage,+ OnConnectionClose: srv.onDisconnect,+ },+ }+ },+ },+ },+ ListenEndpoint: srv.config.GetListenEndpoint(),+ HTTPMiddleware: otelhttp.NewMiddleware("/v1/opamp"),+ }++ // Create TLS configuration with environment-aware settings+ tlsConfig, err := srv.createTLSConfig()+ if err != nil {+ if srv.config.IsProduction() {+ srv.logger.Errorf(context.Background(), "Failed to create TLS config in production: %v", err)+ os.Exit(1)+ } else {+ srv.logger.Printf("WARNING: Could not load TLS config, working without TLS in %s mode: %v", srv.config.TLS.Environment, err)+ }+ } else {+ srv.logger.Printf("TLS configuration loaded successfully")+ }++ settings.TLSConfig = tlsConfig++ srv.logger.Printf("Starting OpAMP server on %s", srv.config.GetListenEndpoint())+ if err := srv.opampSrv.Start(settings); err != nil {+ srv.logger.Errorf(context.Background(), "OpAMP server start failed: %v", err.Error())+ os.Exit(1)+ }+}++// createTLSConfig creates TLS configuration based on environment settings+func (srv *Server) createTLSConfig() (*tls.Config, error) {+ // Convert string TLS versions to constants+ minVersion, err := srv.parseTLSVersion(srv.config.TLS.MinTLSVersion)+ if err != nil {+ return nil, fmt.Errorf("invalid min TLS version: %v", err)+ }++ maxVersion, err := srv.parseTLSVersion(srv.config.TLS.MaxTLSVersion)+ if err != nil {+ return nil, fmt.Errorf("invalid max TLS version: %v", err)+ }++ options := certman.TLSConfigOptions{+ InsecureSkipVerify: srv.config.TLS.InsecureSkipVerify,+ RequireClientCert: srv.config.TLS.RequireClientCert,+ MinTLSVersion: minVersion,+ MaxTLSVersion: maxVersion,+ }++ return certman.CreateServerTLSConfigWithOptions(+ constants.CaCertPath,+ constants.ServerCertPath,+ constants.ServerCertKeyPath,+ options,+ )+}++// parseTLSVersion converts string TLS version to tls constant+func (srv *Server) parseTLSVersion(version string) (uint16, error) {+ switch strings.ToLower(version) {+ case "1.0":+ return tls.VersionTLS10, nil+ case "1.1":+ return tls.VersionTLS11, nil+ case "1.2":+ return tls.VersionTLS12, nil+ case "1.3":+ return tls.VersionTLS13, nil+ default:+ return 0, fmt.Errorf("unsupported TLS version: %s", version)+ }+}++func (srv *Server) Stop() {+ srv.opampSrv.Stop(context.Background())+}++func (srv *Server) onDisconnect(conn types.Connection) {+ srv.agents.RemoveConnection(conn)+}++func (srv *Server) onMessage(ctx context.Context, conn types.Connection, msg *protobufs.AgentToServer) *protobufs.ServerToAgent {+ // Start building the response.+ response := &protobufs.ServerToAgent{}++ var instanceId data.InstanceId+ if len(msg.InstanceUid) == 26 {+ // This is an old-style ULID.+ u, err := ulid.Parse(string(msg.InstanceUid))+ if err != nil {+ srv.logger.Errorf(ctx, "Cannot parse ULID %s: %v", string(msg.InstanceUid), err)+ return response+ }+ instanceId = data.InstanceId(u.Bytes())+ } else if len(msg.InstanceUid) == 16 {+ // This is a 16 byte, new style UID.+ instanceId = data.InstanceId(msg.InstanceUid)+ } else {+ srv.logger.Errorf(ctx, "Invalid length of msg.InstanceUid")+ return response+ }++ agent := srv.agents.FindOrCreateAgent(instanceId, conn)++ // Process the status report and continue building the response.+ agent.UpdateStatus(msg, response)++ if msg.ConnectionSettingsStatus != nil {+ srv.logger.Debugf(ctx, "Connection settings for instance %x %s (err=%s) hash=%x", instanceId, msg.ConnectionSettingsStatus.Status.String(), msg.ConnectionSettingsStatus.ErrorMessage, msg.ConnectionSettingsStatus.LastConnectionSettingsHash)+ }++ // Send the response back to the Agent.+ return response+}diff --git a/src/opamp-server/server/ui.go b/src/opamp-server/server/ui.gonew file mode 100644index 00000000..240db64f--- /dev/null+++ b/src/opamp-server/server/ui.go@@ -0,0 +1,275 @@+package server++import (+ "context"+ "encoding/json"+ "net/http"+ "os"+ "sync"+ "time"++ "opamp-server/certman"+ "opamp-server/constants"+ "opamp-server/data"++ "github.com/google/uuid"++ "github.com/open-telemetry/opamp-go/protobufs"+)++var (+ srv *http.Server+ opampCA = sync.OnceValue(func() string {+ p, err := os.ReadFile(constants.CaCertPath)+ if err != nil {+ panic(err)+ }+ return string(p)+ })+)++func (srv *Server) setupRoutes(mux *http.ServeMux) {+ mux.HandleFunc("/api/agents", srv.handleGetAgents)+ mux.HandleFunc("/api/agent", srv.handleGetAgent)+ mux.HandleFunc("/api/agent/config", srv.handleSaveConfig)+ mux.HandleFunc("/api/agent/connection", srv.handleConnectionSettings)+ mux.HandleFunc("/api/agent/certificate", srv.handleRotateCertificate)+ // mux.HandleFunc("/api/capabilities", srv.handleCapabilities)+}++func Shutdown() {+ srv.Shutdown(context.Background())+}++func (srv *Server) handleGetAgents(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }++ agents := srv.agents.GetAllAgentsReadonlyClone()+ response := make([]data.Agent, 0, len(agents))++ for _, agent := range agents {+ response = append(response, *agent)+ }++ w.Header().Set("Content-Type", "application/json")+ json.NewEncoder(w).Encode(response)+}++func (srv *Server) handleGetAgent(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }++ instanceID := r.URL.Query().Get("id")+ if instanceID == "" {+ http.Error(w, "Missing instance ID", http.StatusBadRequest)+ return+ }++ uid, err := uuid.Parse(instanceID)+ if err != nil {+ http.Error(w, "Invalid instance ID", http.StatusBadRequest)+ return+ }++ agent := srv.agents.GetAgentReadonlyClone(data.InstanceId(uid))+ if agent == nil {+ http.Error(w, "Agent not found", http.StatusNotFound)+ return+ }++ w.Header().Set("Content-Type", "application/json")+ json.NewEncoder(w).Encode(agent)+}++func (srv *Server) handleSaveConfig(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPost {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }++ var request struct {+ InstanceID string `json:"id"`+ Config string `json:"config"`+ }++ if err := json.NewDecoder(r.Body).Decode(&request); err != nil {+ http.Error(w, "Invalid request body", http.StatusBadRequest)+ return+ }++ uid, err := uuid.Parse(request.InstanceID)+ if err != nil {+ http.Error(w, "Invalid instance ID", http.StatusBadRequest)+ return+ }++ instanceId := data.InstanceId(uid)+ agent := srv.agents.GetAgentReadonlyClone(instanceId)+ if agent == nil {+ http.Error(w, "Agent not found", http.StatusNotFound)+ return+ }++ configStr := request.Config+ config := &protobufs.AgentConfigMap{+ ConfigMap: map[string]*protobufs.AgentConfigFile{+ "": {Body: []byte(configStr)},+ },+ }++ notifyNextStatusUpdate := make(chan struct{}, 1)+ data.AllAgents.SetCustomConfigForAgent(instanceId, config, notifyNextStatusUpdate)++ // Wait for up to 5 seconds for a Status update, which is expected+ // to be reported by the Agent after we set the remote config.+ timer := time.NewTicker(time.Second * 5)+ defer timer.Stop()++ select {+ case <-notifyNextStatusUpdate:+ w.WriteHeader(http.StatusOK)+ case <-timer.C:+ w.WriteHeader(http.StatusRequestTimeout)+ }+}++func (srv *Server) handleRotateCertificate(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPost {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }++ var request struct {+ InstanceID string `json:"id"`+ }++ if err := json.NewDecoder(r.Body).Decode(&request); err != nil {+ http.Error(w, "Invalid request body", http.StatusBadRequest)+ return+ }++ uid, err := uuid.Parse(request.InstanceID)+ if err != nil {+ http.Error(w, "Invalid instance ID", http.StatusBadRequest)+ return+ }++ instanceId := data.InstanceId(uid)+ agent := data.AllAgents.GetAgentReadonlyClone(instanceId)+ if agent == nil {+ http.Error(w, "Agent not found", http.StatusNotFound)+ return+ }++ // Create a new certificate for the agent.+ certificate, err := certman.CreateTLSCert(constants.CaCertPath, constants.PrivateKeyPath)+ if err != nil {+ http.Error(w, "Internal server error", http.StatusInternalServerError)+ srv.logger.Println(err)+ return+ }++ // Create an offer for the agent.+ offers := &protobufs.ConnectionSettingsOffers{+ Opamp: &protobufs.OpAMPConnectionSettings{+ Certificate: certificate,+ },+ }++ // Send the offer to the agent.+ data.AllAgents.OfferAgentConnectionSettings(instanceId, offers)++ srv.logger.Printf("Waiting for agent %s to reconnect\n", instanceId)++ // Wait for up to 5 seconds for a Status update, which is expected+ // to be reported by the agent after we set the remote config.+ timer := time.NewTicker(time.Second * 5)+ defer timer.Stop()++ // TODO: wait for agent to reconnect instead of waiting full 5 seconds.++ select {+ case <-timer.C:+ srv.logger.Printf("Time out waiting for agent %s to reconnect\n", instanceId)+ }++ w.WriteHeader(http.StatusOK)+}++func (srv *Server) handleConnectionSettings(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPost {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ return+ }++ var request struct {+ InstanceID string `json:"id"`+ TLSMin string `json:"tls_min"`+ }++ if err := json.NewDecoder(r.Body).Decode(&request); err != nil {+ http.Error(w, "Invalid request body", http.StatusBadRequest)+ return+ }++ uid, err := uuid.Parse(request.InstanceID)+ if err != nil {+ http.Error(w, "Invalid instance ID", http.StatusBadRequest)+ return+ }++ instanceId := data.InstanceId(uid)+ agent := srv.agents.GetAgentReadonlyClone(instanceId)+ if agent == nil {+ http.Error(w, "Agent not found", http.StatusNotFound)+ return+ }++ var tlsMin string+ switch request.TLSMin {+ case "TLSv1.0":+ tlsMin = "1.0"+ case "TLSv1.1":+ tlsMin = "1.1"+ case "TLSv1.2":+ tlsMin = "1.2"+ case "TLSv1.3":+ tlsMin = "1.3"+ default:+ http.Error(w, "Invalid TLS version", http.StatusBadRequest)+ return+ }++ offers := &protobufs.ConnectionSettingsOffers{+ Opamp: &protobufs.OpAMPConnectionSettings{+ Tls: &protobufs.TLSConnectionSettings{+ CaPemContents: opampCA(),+ MinVersion: tlsMin,+ MaxVersion: "1.3",+ },+ },+ }++ data.AllAgents.OfferAgentConnectionSettings(instanceId, offers)++ srv.logger.Printf("Waiting for agent %s to reconnect\n", instanceId)++ // Wait for up to 5 seconds for a Status update, which is expected+ // to be reported by the agent after we set the remote config.+ timer := time.NewTicker(time.Second * 5)+ defer timer.Stop()++ // TODO: wait for agent to reconnect instead of waiting full 5 seconds.++ select {+ case <-timer.C:+ srv.logger.Printf("Time out waiting for agent %s to reconnect\n", instanceId)+ }++ w.WriteHeader(http.StatusOK)+}diff --git a/src/opamp-server/setup-supervisor.sh b/src/opamp-server/setup-supervisor.shnew file mode 100755index 00000000..3e910950--- /dev/null+++ b/src/opamp-server/setup-supervisor.sh@@ -0,0 +1,343 @@+#!/bin/bash++# OpenLIT OpAMP Supervisor Setup Script+# This script helps configure the OpAMP supervisor for secure communication with the OpenLIT server++set -e++# Configuration+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+CERTS_DIR="${SCRIPT_DIR}/certs"+ASSETS_DIR="${SCRIPT_DIR}/../../assets"++# Colors for output+RED='\033[0;31m'+GREEN='\033[0;32m'+YELLOW='\033[1;33m'+BLUE='\033[0;34m'+NC='\033[0m' # No Color++# Logging functions+log_info() {+ echo -e "${GREEN}[INFO]${NC} $1"+}++log_warn() {+ echo -e "${YELLOW}[WARN]${NC} $1"+}++log_error() {+ echo -e "${RED}[ERROR]${NC} $1"+}++log_step() {+ echo -e "${BLUE}[STEP]${NC} $1"+}++print_banner() {+ echo -e "${BLUE}"+ echo "╔══════════════════════════════════════════════════════════════════════════════════════╗"+ echo "║ OpenLIT OpAMP Supervisor Setup ║"+ echo "║ ║"+ echo "║ This script configures the OpAMP supervisor for secure communication with ║"+ echo "║ your OpenLIT OpAMP server using proper TLS certificates. ║"+ echo "╚══════════════════════════════════════════════════════════════════════════════════════╝"+ echo -e "${NC}"+}++show_usage() {+ echo "Usage: $0 [OPTIONS]"+ echo ""+ echo "Options:"+ echo " --development Configure for development (insecure_skip_verify=true)"+ echo " --production Configure for production (with CA certificate)"+ echo " --server-url URL Set the OpAMP server URL (default: wss://localhost:4320/v1/opamp)"+ echo " --output-dir DIR Output directory for supervisor config (default: ./supervisor-config)"+ echo " --help Show this help message"+ echo ""+ echo "Examples:"+ echo " $0 --development"+ echo " $0 --production --server-url wss://my-openlit-server:4320/v1/opamp"+}++# Default values+ENVIRONMENT="development"+SERVER_URL="wss://localhost:4320/v1/opamp"+OUTPUT_DIR="./supervisor-config"++# Parse command line arguments+while [[ $# -gt 0 ]]; do+ case $1 in+ --development)+ ENVIRONMENT="development"+ shift+ ;;+ --production)+ ENVIRONMENT="production"+ shift+ ;;+ --server-url)+ SERVER_URL="$2"+ shift 2+ ;;+ --output-dir)+ OUTPUT_DIR="$2"+ shift 2+ ;;+ --help)+ show_usage+ exit 0+ ;;+ *)+ log_error "Unknown option: $1"+ show_usage+ exit 1+ ;;+ esac+done++print_banner++log_step "Configuring OpAMP supervisor for ${ENVIRONMENT} environment"++# Create output directory+mkdir -p "${OUTPUT_DIR}"++# Check if certificates exist+if [[ "${ENVIRONMENT}" == "production" ]]; then+ if [[ ! -f "${CERTS_DIR}/cert/ca.cert.pem" ]]; then+ log_error "CA certificate not found at ${CERTS_DIR}/cert/ca.cert.pem"+ log_info "Please run the certificate generation script first:"+ log_info " cd ${CERTS_DIR} && ./generate.sh"+ exit 1+ fi++ if [[ ! -f "${CERTS_DIR}/client/client.cert.pem" ]]; then+ log_warn "Client certificate not found at ${CERTS_DIR}/client/client.cert.pem"+ log_info "Client certificates are optional but recommended for mutual TLS"+ fi+fi++# Generate supervisor configuration+SUPERVISOR_CONFIG="${OUTPUT_DIR}/supervisor.yaml"++log_info "Generating supervisor configuration..."++cat > "${SUPERVISOR_CONFIG}" << EOF+server:+ # The endpoint of the OpAMP server+ endpoint: ${SERVER_URL}+ tls:+EOF++if [[ "${ENVIRONMENT}" == "development" ]]; then+ cat >> "${SUPERVISOR_CONFIG}" << EOF+ # Development configuration - skips certificate verification+ # WARNING: This is insecure and should only be used for development!+ insecure_skip_verify: true+EOF+else+ cat >> "${SUPERVISOR_CONFIG}" << EOF+ # Production configuration with proper certificate verification+ insecure_skip_verify: false++ # Path to the CA certificate that signed the server certificate+ ca_file: /app/opamp/certs/cert/ca.cert.pem++ # Optional: Client certificate for mutual TLS authentication+ # Uncomment these lines if the server requires client certificates+ # cert_file: /app/opamp/certs/client/client.cert.pem+ # key_file: /app/opamp/certs/client/client.key.pem+EOF+fi++cat >> "${SUPERVISOR_CONFIG}" << EOF++agent:+ # The path to the OpenTelemetry Collector binary managed by this supervisor+ executable: /app/opamp/otelcontribcol++ # Reference to external configuration file+ config_files:+ - /etc/otel/otel-collector-config.yaml++capabilities:+ accepts_remote_config: true+ reports_effective_config: true+ reports_own_metrics: false+ reports_own_logs: true+ reports_own_traces: false+ reports_health: true+ reports_remote_config: true++storage:+ directory: ./storage+EOF++log_info "Supervisor configuration generated: ${SUPERVISOR_CONFIG}"++# Copy certificates if in production mode+if [[ "${ENVIRONMENT}" == "production" ]]; then+ log_info "Copying certificates to output directory..."++ mkdir -p "${OUTPUT_DIR}/certs/cert"+ mkdir -p "${OUTPUT_DIR}/certs/client"++ cp "${CERTS_DIR}/cert/ca.cert.pem" "${OUTPUT_DIR}/certs/cert/"++ if [[ -f "${CERTS_DIR}/client/client.cert.pem" ]]; then+ cp "${CERTS_DIR}/client/client.cert.pem" "${OUTPUT_DIR}/certs/client/"+ cp "${CERTS_DIR}/client/client.key.pem" "${OUTPUT_DIR}/certs/client/"+ log_info "Client certificates copied for mutual TLS"+ fi++ log_info "Certificates copied to ${OUTPUT_DIR}/certs/"+fi++# Generate deployment instructions+INSTRUCTIONS_FILE="${OUTPUT_DIR}/DEPLOYMENT.md"++log_info "Generating deployment instructions..."++cat > "${INSTRUCTIONS_FILE}" << EOF+# OpAMP Supervisor Deployment Instructions++## Configuration Generated+- **Environment**: ${ENVIRONMENT}+- **Server URL**: ${SERVER_URL}+- **Configuration File**: supervisor.yaml++## Deployment Steps++### 1. Download OpAMP Supervisor++\`\`\`bash+# Download the latest OpAMP supervisor binary+curl -LO https://github.com/open-telemetry/opentelemetry-collector-releases/releases/latest/download/opampsupervisor_linux_amd64++# Make it executable+chmod +x opampsupervisor_linux_amd64+\`\`\`++### 2. Deploy Configuration++\`\`\`bash+# Copy the supervisor configuration+cp supervisor.yaml /etc/opamp/supervisor.yaml+EOF++if [[ "${ENVIRONMENT}" == "production" ]]; then+ cat >> "${INSTRUCTIONS_FILE}" << EOF++# Copy certificates (production only)+sudo mkdir -p /app/opamp/certs+sudo cp -r certs/* /app/opamp/certs/+sudo chown -R root:root /app/opamp/certs+sudo chmod 644 /app/opamp/certs/cert/ca.cert.pem+sudo chmod 600 /app/opamp/certs/client/client.key.pem 2>/dev/null || true+EOF+fi++cat >> "${INSTRUCTIONS_FILE}" << EOF+\`\`\`++### 3. Start the Supervisor++\`\`\`bash+# Start the OpAMP supervisor+./opampsupervisor_linux_amd64 --config /etc/opamp/supervisor.yaml+\`\`\`++### 4. Verify Connection++Check the supervisor logs for successful connection:+- Look for "Connected to OpAMP server" messages+- Verify no TLS certificate errors++## Troubleshooting++### Certificate Issues+EOF++if [[ "${ENVIRONMENT}" == "production" ]]; then+ cat >> "${INSTRUCTIONS_FILE}" << EOF+- Ensure CA certificate is accessible at the configured path+- Verify certificate file permissions (644 for certs, 600 for keys)+- Check that the server certificate includes the correct hostname/IP in SAN+EOF+else+ cat >> "${INSTRUCTIONS_FILE}" << EOF+- Development mode uses insecure_skip_verify=true+- For production, use --production flag to generate secure configuration+EOF+fi++cat >> "${INSTRUCTIONS_FILE}" << EOF++### Network Issues+- Verify the server URL is correct and accessible+- Check firewall rules for port 4320+- Ensure WebSocket connections are allowed++### Server Issues+- Verify the OpAMP server is running and listening on the correct port+- Check server logs for connection attempts and errors++## Security Notes+EOF++if [[ "${ENVIRONMENT}" == "production" ]]; then+ cat >> "${INSTRUCTIONS_FILE}" << EOF+- This configuration uses proper TLS certificate verification+- CA certificate must be distributed securely to all supervisor instances+- Consider using client certificates for mutual TLS authentication+- Regularly rotate certificates before expiration+EOF+else+ cat >> "${INSTRUCTIONS_FILE}" << EOF+- **WARNING**: Development configuration skips certificate verification+- This is insecure and should NEVER be used in production+- Use --production flag for secure production configuration+EOF+fi++cat >> "${INSTRUCTIONS_FILE}" << EOF++## Environment Variables++You can override configuration using environment variables:+- \`OPAMP_SERVER_URL\`: Override the server endpoint+- \`OPAMP_CA_FILE\`: Override the CA certificate path+- \`OPAMP_CLIENT_CERT\`: Override the client certificate path+- \`OPAMP_CLIENT_KEY\`: Override the client key path+EOF++log_info "Deployment instructions generated: ${INSTRUCTIONS_FILE}"++# Summary+echo ""+log_step "Setup Complete!"+echo ""+log_info "Generated files:"+log_info " 📄 Configuration: ${SUPERVISOR_CONFIG}"+log_info " 📋 Instructions: ${INSTRUCTIONS_FILE}"++if [[ "${ENVIRONMENT}" == "production" ]]; then+ log_info " 🔐 Certificates: ${OUTPUT_DIR}/certs/"+fi++echo ""+log_info "Next steps:"+log_info " 1. Review the generated configuration"+log_info " 2. Follow the deployment instructions in ${INSTRUCTIONS_FILE}"+log_info " 3. Start the OpAMP supervisor with the new configuration"++if [[ "${ENVIRONMENT}" == "development" ]]; then+ echo ""+ log_warn "Development mode is configured with insecure_skip_verify=true"+ log_warn "This is NOT secure and should only be used for development!"+ log_info "For production, run: $0 --production --server-url wss://your-server:4320/v1/opamp"+fi++echo ""+log_info "🎉 OpAMP supervisor setup completed successfully!"