caddymonitor

package module
v0.1.1-0...-3a73667 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 16, 2025 License: Apache-2.0 Imports: 39 Imported by: 0

README

Caddy Monitor

Go Report Card License GoDoc

Enterprise-grade observability and monitoring plugin for Caddy web server with distributed tracing, multi-tenancy, and SLO management.

🎯 Overview

Caddy Monitor extends Caddy v2 with comprehensive monitoring capabilities designed for production environments. It provides real-time metrics, intelligent alerting, distributed tracing, and multi-tenant isolation out of the box.

Key Features
  • 📊 Enhanced Metrics Collection

    • Prometheus-compatible metrics export
    • Per-host, per-route, per-tenant tracking
    • TLS handshake and certificate monitoring
    • Proxy backend health checks
    • Configurable cardinality limits
  • 🔔 Intelligent Alerting

    • Webhook notifications with HMAC signatures
    • Multi-burn-rate SLO alerting
    • Exponential backoff retry logic
    • Error budget tracking
    • Severity-based routing (P0-P4)
  • 🔍 Distributed Tracing

    • OpenTelemetry-compatible tracing
    • OTLP, Jaeger, and Zipkin exporters
    • Configurable sampling strategies
    • W3C Trace Context propagation
  • 👥 Multi-Tenancy & RBAC

    • Label-based access control (LBAC)
    • Tenant isolation and quotas
    • Auto-detection from headers/subdomain
    • Role-based permissions
  • 💾 Flexible Storage

    • Prometheus remote write
    • VictoriaMetrics support
    • InfluxDB integration
    • Configurable retention policies
  • 🔌 REST API

    • Health check endpoints
    • Metrics query (PromQL-compatible)
    • Active alerts monitoring
    • Label introspection

🚀 Quick Start

Prerequisites
  • Go 1.21 or later
  • Caddy v2.7.6 or later
Installation
Using xcaddy
xcaddy build --with github.com/Frontier-Algorithmics/caddy-monitor
Using Docker
git clone https://github.com/Frontier-Algorithmics/caddy-monitor.git
cd caddy-monitor
docker-compose -f examples/docker-compose.yml up -d
From Source
go get github.com/Frontier-Algorithmics/caddy-monitor
Basic Configuration

Add to your Caddyfile:

{
    order monitor before respond
    
    monitor {
        metrics {
            enabled true
            per_host true
            per_route true
            cardinality_limit 10000
        }
        
        alerting {
            enabled true
            webhook {
                url "https://hooks.slack.com/your-webhook"
                secret "your-hmac-secret"
            }
            rules {
                high_latency {
                    metric "http_request_duration_seconds"
                    threshold 1.0
                    window "5m"
                    severity "p1"
                }
            }
        }
    }
}

api.example.com {
    monitor tenant_id "customer-123"
    reverse_proxy backend:8080
}

:9090 {
    respond /health 200
    metrics /metrics
}
JSON Configuration
{
  "apps": {
    "caddy_monitor": {
      "metrics": {
        "enabled": true,
        "per_host": true,
        "per_route": true,
        "cardinality_limit": 10000
      },
      "tracing": {
        "enabled": true,
        "sampler": {
          "type": "probability",
          "rate": 0.1
        },
        "exporter": {
          "type": "otlp",
          "endpoint": "localhost:4317"
        }
      },
      "storage": {
        "backend": "prometheus",
        "url": "http://prometheus:9090",
        "retention": "90d"
      },
      "tenants": {
        "enabled": true,
        "auto_detect_from": "header",
        "header_name": "X-Tenant-ID"
      }
    }
  }
}

📖 Documentation

Architecture

Caddy Monitor is built as a Caddy v2 App module with the following components:

CaddyMonitor (Main Module)
├── MetricsCollector    # Prometheus metrics
├── AlertManager        # Intelligent alerting
├── DistributedTracer   # OpenTelemetry tracing
├── DataStore           # Storage backends
├── MultiTenancy        # Tenant isolation
├── SLOManager          # SLO/SLA tracking
└── AdminAPI            # REST endpoints
API Endpoints
Endpoint Method Description
/health GET Health check
/api/v1/metrics/query GET Query metrics (PromQL)
/api/v1/metrics/labels GET Available metric labels
/api/v1/alerts/active GET Active alerts
Metrics
Metric Type Labels Description
caddy_http_requests_total Counter method, status, host Total HTTP requests
caddy_http_request_duration_seconds Histogram method, status, host Request latency
caddy_tls_handshakes_total Counter host, version TLS handshakes
caddy_tls_handshake_duration_seconds Histogram host TLS handshake duration
caddy_proxy_backend_health Gauge backend, host Backend health (1=healthy, 0=unhealthy)
Environment Variables
Variable Description Default
CADDY_MONITOR_LOG_LEVEL Log level (debug, info, warn, error) info
CADDY_MONITOR_METRICS_PORT Metrics export port 9090

🛠️ Development

Building
# Build binary
make build

# Run tests
make test

# Run linter
make lint

# Format code
make format
Running Locally
# Start with example config
make run

# Start Docker stack
make docker-up

# View logs
docker-compose -f examples/docker-compose.yml logs -f
Testing
# Unit tests
go test -v ./...

# With coverage
go test -v -cover ./...

# Benchmark
go test -bench=. ./...

🔐 Security

HMAC Webhook Signatures

All webhook notifications include HMAC-SHA256 signatures in the X-Webhook-Signature header. Verify signatures to ensure authenticity:

h := hmac.New(sha256.New, []byte(secret))
h.Write(payload)
expectedSignature := hex.EncodeToString(h.Sum(nil))
Best Practices
  • Always use HTTPS for webhook endpoints
  • Rotate HMAC secrets regularly
  • Enable tenant isolation for multi-user deployments
  • Configure resource quotas per tenant
  • Use least-privilege RBAC roles
  • Enable audit logging for compliance

📊 Performance

Benchmarks
  • Metrics Collection: <1ms overhead per request
  • Alert Evaluation: <10ms per rule
  • Memory Footprint: ~200MB typical workload
  • CPU Usage: <5% at 10K req/s
Scalability
  • Supports 100K+ requests/second
  • Configurable cardinality limits prevent memory explosion
  • Automatic metric aggregation
  • Hot/cold storage tiering

🤝 Contributing

We welcome contributions! Please see our contributing guidelines:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request
Code Style
  • Follow Go conventions and idioms
  • Run gofmt before committing
  • Ensure all tests pass
  • Add tests for new features
  • Update documentation

📜 License

Apache License 2.0 - see LICENSE for details.

👥 Team

Built with ❤️ by Frontier Algorithmics:

  • Zaid Marzguioui (@theemperor66) - Project Lead
  • T. Zehetbauer (@4th1omost) - Core Architecture
  • Cem (@cemGr) - Metrics & Performance
  • TobiasPoisel - API & Integration
  • David (@LUCKsBane0) - Security & Compliance
  • tastendaemon - DevOps & Deployment

🙏 Acknowledgments

📞 Support


Status: Production Ready | Version: 0.1.0 | Last Updated: October 2025

Documentation

Overview

Package caddymonitor provides enterprise-grade observability for Caddy deployments.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotProvisioned      = errors.New("component not provisioned")
	ErrInvalidConfig       = errors.New("invalid configuration")
	ErrMetricsDisabled     = errors.New("metrics collection is disabled")
	ErrAlertingDisabled    = errors.New("alerting is disabled")
	ErrExceededCardinality = errors.New("exceeded cardinality limit")
)

Common errors

Functions

This section is empty.

Types

type APIKey

type APIKey struct {
	ID          string       `json:"id"`
	Key         string       `json:"key,omitempty"` // Only shown once on creation
	Hash        string       `json:"-"`
	Name        string       `json:"name"`
	TenantID    string       `json:"tenant_id"`
	Role        Role         `json:"role"`
	Permissions []Permission `json:"permissions"`
	ExpiresAt   *time.Time   `json:"expires_at,omitempty"`
	CreatedAt   time.Time    `json:"created_at"`
	LastUsedAt  *time.Time   `json:"last_used_at,omitempty"`
	Active      bool         `json:"active"`
}

type Alert

type Alert struct {
	ID       string    `json:"id"`
	RuleName string    `json:"rule_name"`
	Severity string    `json:"severity"`
	StartsAt time.Time `json:"starts_at"`
	Value    float64   `json:"value"`
}

Alert represents an active alert.

type AlertCorrelator

type AlertCorrelator struct {
	// contains filtered or unexported fields
}

func NewAlertCorrelator

func NewAlertCorrelator() *AlertCorrelator

func (*AlertCorrelator) AddCorrelation

func (ac *AlertCorrelator) AddCorrelation(parent string, children []string)

func (*AlertCorrelator) ShouldSuppress

func (ac *AlertCorrelator) ShouldSuppress(alertName string, activeAlerts map[string]*Alert) bool

type AlertDeduplicator

type AlertDeduplicator struct {
	// contains filtered or unexported fields
}

func NewAlertDeduplicator

func NewAlertDeduplicator(window time.Duration) *AlertDeduplicator

func (*AlertDeduplicator) Cleanup

func (ad *AlertDeduplicator) Cleanup()

func (*AlertDeduplicator) IsDuplicate

func (ad *AlertDeduplicator) IsDuplicate(alertKey string) bool

type AlertEscalation

type AlertEscalation struct {
	Level        int    `json:"level"`
	AfterMinutes int    `json:"after_minutes"`
	NotifyURL    string `json:"notify_url"`
}

type AlertManager

type AlertManager struct {
	Enabled      bool           `json:"enabled,omitempty"`
	Rules        []*AlertRule   `json:"rules,omitempty"`
	Webhook      *WebhookConfig `json:"webhook,omitempty"`
	EvalInterval string         `json:"eval_interval,omitempty"`
	// contains filtered or unexported fields
}

AlertManager handles intelligent alerting.

func (*AlertManager) DeduplicateAlert

func (am *AlertManager) DeduplicateAlert(alert *Alert) bool

func (*AlertManager) EvaluateWithAnomalyDetection

func (am *AlertManager) EvaluateWithAnomalyDetection(rule *AlertRule, value float64, detector *AnomalyDetector) (bool, error)

func (*AlertManager) FireAlert

func (am *AlertManager) FireAlert(alert *Alert) error

FireAlert fires an alert with retry logic.

func (*AlertManager) GetActiveAlerts

func (am *AlertManager) GetActiveAlerts() []*Alert

func (*AlertManager) Provision

func (am *AlertManager) Provision(ctx caddy.Context, logger *zap.Logger) error

Provision sets up the alert manager.

func (*AlertManager) Run

func (am *AlertManager) Run(ctx context.Context, provider MetricProvider, slo *SLOManager) error

func (*AlertManager) SilenceAlert

func (am *AlertManager) SilenceAlert(ruleName string, duration time.Duration) error

type AlertRule

type AlertRule struct {
	Name      string      `json:"name"`
	Metric    string      `json:"metric"`
	Threshold float64     `json:"threshold"`
	Window    string      `json:"window"`
	Severity  string      `json:"severity"`
	BurnRates []*BurnRate `json:"burn_rates,omitempty"`
}

AlertRule defines an alerting rule.

type AlertSilence

type AlertSilence struct {
	RuleName  string
	ExpiresAt time.Time
}

type AnomalyDetector

type AnomalyDetector struct {
	Enabled    bool    `json:"enabled,omitempty"`
	Threshold  float64 `json:"threshold,omitempty"` // z-score threshold
	WindowSize int     `json:"window_size,omitempty"`
	// contains filtered or unexported fields
}

func (*AnomalyDetector) IsAnomaly

func (ad *AnomalyDetector) IsAnomaly(value float64) bool

func (*AnomalyDetector) Provision

func (ad *AnomalyDetector) Provision(logger *zap.Logger) error

func (*AnomalyDetector) RecordValue

func (ad *AnomalyDetector) RecordValue(value float64)

type AuditEntry

type AuditEntry struct {
	ID        string                 `json:"id"`
	Timestamp time.Time              `json:"timestamp"`
	TenantID  string                 `json:"tenant_id"`
	UserID    string                 `json:"user_id,omitempty"`
	APIKeyID  string                 `json:"api_key_id,omitempty"`
	Action    string                 `json:"action"`
	Resource  string                 `json:"resource"`
	Result    string                 `json:"result"` // success, failure
	Details   map[string]interface{} `json:"details,omitempty"`
	IPAddress string                 `json:"ip_address,omitempty"`
}

type AuditLog

type AuditLog struct {
	Enabled       bool `json:"enabled,omitempty"`
	RetentionDays int  `json:"retention_days,omitempty"`
	// contains filtered or unexported fields
}

func (*AuditLog) Cleanup

func (al *AuditLog) Cleanup()

func (*AuditLog) Log

func (al *AuditLog) Log(entry AuditEntry)

func (*AuditLog) Provision

func (al *AuditLog) Provision(logger *zap.Logger) error

func (*AuditLog) Query

func (al *AuditLog) Query(tenantID, action string, since time.Time) []AuditEntry

type BurnRate

type BurnRate struct {
	Threshold float64 `json:"threshold"` // e.g., 0.02 for 2% error rate
	Window    string  `json:"window"`    // e.g., "1h", "6h"
	Severity  string  `json:"severity"`  // critical, warning
}

BurnRate defines multi-burn-rate alerting thresholds.

func (*BurnRate) ValidateBurnRate

func (br *BurnRate) ValidateBurnRate(errorRate float64) bool

ValidateBurnRate checks if a burn rate threshold is exceeded.

type CaddyMonitor

type CaddyMonitor struct {
	MetricsConfig    *MetricsCollector  `json:"metrics,omitempty"`
	AlertingConfig   *AlertManager      `json:"alerting,omitempty"`
	TenantsConfig    *MultiTenancy      `json:"tenants,omitempty"`
	SLOConfig        *SLOManager        `json:"slos,omitempty"`
	TracingConfig    *DistributedTracer `json:"tracing,omitempty"`
	StorageConfig    *DataStore         `json:"storage,omitempty"`
	RBACConfig       *RBACManager       `json:"rbac,omitempty"`
	AuditConfig      *AuditLog          `json:"audit,omitempty"`
	ComplianceConfig *ComplianceManager `json:"compliance,omitempty"`
	// contains filtered or unexported fields
}

CaddyMonitor is the main plugin module for enterprise monitoring.

func (*CaddyMonitor) CaddyModule

func (*CaddyMonitor) CaddyModule() caddy.ModuleInfo

CaddyModule returns the Caddy module information.

func (*CaddyMonitor) Provision

func (m *CaddyMonitor) Provision(ctx caddy.Context) error

Provision sets up the module.

func (*CaddyMonitor) Start

func (m *CaddyMonitor) Start() error

Start starts the monitoring services.

func (*CaddyMonitor) Stop

func (m *CaddyMonitor) Stop() error

Stop gracefully shuts down.

func (*CaddyMonitor) UnmarshalCaddyfile

func (m *CaddyMonitor) UnmarshalCaddyfile(d *caddyfile.Dispenser) error

UnmarshalCaddyfile implements caddyfile.Unmarshaler.

type ComplianceManager

type ComplianceManager struct {
	Enabled    bool              `json:"enabled,omitempty"`
	Encryption *EncryptionConfig `json:"encryption,omitempty"`
	PIIMasking *PIIMaskingConfig `json:"pii_masking,omitempty"`
	Retention  *RetentionConfig  `json:"retention,omitempty"`
	Reporting  *ReportingConfig  `json:"reporting,omitempty"`
	// contains filtered or unexported fields
}

func (*ComplianceManager) DecryptData

func (cm *ComplianceManager) DecryptData(data []byte) ([]byte, error)

func (*ComplianceManager) EncryptData

func (cm *ComplianceManager) EncryptData(data []byte) ([]byte, error)

func (*ComplianceManager) GenerateComplianceReport

func (cm *ComplianceManager) GenerateComplianceReport(reportType string) (*ComplianceReport, error)

func (*ComplianceManager) MaskPII

func (cm *ComplianceManager) MaskPII(text string) string

func (*ComplianceManager) Provision

func (cm *ComplianceManager) Provision(logger *zap.Logger) error

type ComplianceReport

type ComplianceReport struct {
	GeneratedAt     time.Time              `json:"generated_at"`
	ReportType      string                 `json:"report_type"`
	ComplianceMode  string                 `json:"compliance_mode"`
	Summary         map[string]interface{} `json:"summary"`
	Violations      []string               `json:"violations,omitempty"`
	Recommendations []string               `json:"recommendations,omitempty"`
}

type DataRetentionManager

type DataRetentionManager struct {
	// contains filtered or unexported fields
}

func NewDataRetentionManager

func NewDataRetentionManager(config *RetentionConfig, logger *zap.Logger) *DataRetentionManager

func (*DataRetentionManager) CleanupExpiredData

func (drm *DataRetentionManager) CleanupExpiredData() error

func (*DataRetentionManager) GetRetentionPolicy

func (drm *DataRetentionManager) GetRetentionPolicy() map[string]interface{}

type DataStore

type DataStore struct {
	Backend   string `json:"backend"` // prometheus, victoriametrics, influxdb
	URL       string `json:"url"`
	Username  string `json:"username,omitempty"`
	Password  string `json:"password,omitempty"`
	Database  string `json:"database,omitempty"`
	Retention string `json:"retention,omitempty"`
	// contains filtered or unexported fields
}

func (*DataStore) Provision

func (ds *DataStore) Provision(ctx caddy.Context, logger *zap.Logger) error

func (*DataStore) Query

func (ds *DataStore) Query(ctx context.Context, query string) (interface{}, error)

func (*DataStore) WriteMetrics

func (ds *DataStore) WriteMetrics(ctx context.Context, registry *prometheus.Registry) error

type DistributedTracer

type DistributedTracer struct {
	Enabled  bool            `json:"enabled,omitempty"`
	Sampler  *SamplerConfig  `json:"sampler,omitempty"`
	Exporter *ExporterConfig `json:"exporter,omitempty"`
	// contains filtered or unexported fields
}

func (*DistributedTracer) ExtractHTTPHeaders

func (dt *DistributedTracer) ExtractHTTPHeaders(r *http.Request) context.Context

func (*DistributedTracer) InjectHTTPHeaders

func (dt *DistributedTracer) InjectHTTPHeaders(ctx context.Context, r *http.Request)

func (*DistributedTracer) Provision

func (dt *DistributedTracer) Provision(ctx caddy.Context, logger *zap.Logger) error

func (*DistributedTracer) RecordHTTPRequest

func (dt *DistributedTracer) RecordHTTPRequest(ctx context.Context, r *http.Request, statusCode int)

func (*DistributedTracer) Shutdown

func (dt *DistributedTracer) Shutdown(ctx context.Context) error

func (*DistributedTracer) StartSpan

func (dt *DistributedTracer) StartSpan(ctx context.Context, name string, opts ...trace.SpanStartOption) (context.Context, trace.Span)

type EncryptionConfig

type EncryptionConfig struct {
	Enabled    bool   `json:"enabled,omitempty"`
	Algorithm  string `json:"algorithm,omitempty"` // aes-256-gcm
	KeyPath    string `json:"key_path,omitempty"`
	RotateDays int    `json:"rotate_days,omitempty"`
}

type Encryptor

type Encryptor struct {
	// contains filtered or unexported fields
}

func NewEncryptor

func NewEncryptor(keyPath string) (*Encryptor, error)

func (*Encryptor) Decrypt

func (e *Encryptor) Decrypt(ciphertext []byte) ([]byte, error)

func (*Encryptor) Encrypt

func (e *Encryptor) Encrypt(plaintext []byte) ([]byte, error)

type ErrorBudget

type ErrorBudget struct {
	Total     float64   `json:"total"`     // Total error budget for window
	Consumed  float64   `json:"consumed"`  // Amount consumed so far
	Remaining float64   `json:"remaining"` // Remaining budget
	UpdatedAt time.Time `json:"updated_at"`
}

ErrorBudget tracks remaining error budget.

type EscalationPolicy

type EscalationPolicy struct {
	RuleName    string             `json:"rule_name"`
	Escalations []*AlertEscalation `json:"escalations"`
	// contains filtered or unexported fields
}

func (*EscalationPolicy) CheckEscalation

func (ep *EscalationPolicy) CheckEscalation(alert *Alert) *AlertEscalation

func (*EscalationPolicy) Reset

func (ep *EscalationPolicy) Reset()

type ExporterConfig

type ExporterConfig struct {
	Type     string `json:"type"` // otlp, jaeger, zipkin
	Endpoint string `json:"endpoint"`
	Insecure bool   `json:"insecure,omitempty"`
}

type InfluxDBBackend

type InfluxDBBackend struct {
	// contains filtered or unexported fields
}

func (*InfluxDBBackend) Close

func (ib *InfluxDBBackend) Close() error

func (*InfluxDBBackend) Query

func (ib *InfluxDBBackend) Query(ctx context.Context, query string) (interface{}, error)

func (*InfluxDBBackend) Write

func (ib *InfluxDBBackend) Write(ctx context.Context, metrics []byte) error

type MetricProvider

type MetricProvider interface {
	MetricValue(metric string) (float64, error)
}

type MetricsCollector

type MetricsCollector struct {
	Enabled          bool   `json:"enabled,omitempty"`
	PerHost          bool   `json:"per_host,omitempty"`
	PerRoute         bool   `json:"per_route,omitempty"`
	Retention        string `json:"retention,omitempty"`
	CardinalityLimit int    `json:"cardinality_limit,omitempty"`
	// contains filtered or unexported fields
}

MetricsCollector handles metrics collection.

func (*MetricsCollector) MetricValue

func (mc *MetricsCollector) MetricValue(name string) (float64, error)

func (*MetricsCollector) Provision

func (mc *MetricsCollector) Provision(ctx caddy.Context, logger *zap.Logger) error

Provision sets up the metrics collector.

func (*MetricsCollector) RecordHTTPRequest

func (mc *MetricsCollector) RecordHTTPRequest(r *http.Request, statusCode int, duration time.Duration, tenantID string) error

func (*MetricsCollector) RecordRequest

func (mc *MetricsCollector) RecordRequest(labels prometheus.Labels, duration time.Duration) error

RecordRequest records an HTTP request metric.

type MonitorAPI

type MonitorAPI struct {
	BasePath string `json:"base_path,omitempty"`
	// contains filtered or unexported fields
}

func (MonitorAPI) CaddyModule

func (MonitorAPI) CaddyModule() caddy.ModuleInfo

func (*MonitorAPI) Provision

func (api *MonitorAPI) Provision(ctx caddy.Context) error

func (*MonitorAPI) ServeHTTP

func (api *MonitorAPI) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error

type MonitorMiddleware

type MonitorMiddleware struct {
	TenantID string `json:"tenant_id,omitempty"`
	// contains filtered or unexported fields
}

func (MonitorMiddleware) CaddyModule

func (MonitorMiddleware) CaddyModule() caddy.ModuleInfo

func (*MonitorMiddleware) Provision

func (m *MonitorMiddleware) Provision(ctx caddy.Context) error

func (*MonitorMiddleware) ServeHTTP

type MultiTenancy

type MultiTenancy struct {
	Enabled        bool     `json:"enabled,omitempty"`
	AutoDetectFrom string   `json:"auto_detect_from,omitempty"` // header, subdomain, path
	HeaderName     string   `json:"header_name,omitempty"`      // e.g., X-Tenant-ID
	Tenants        []Tenant `json:"tenants,omitempty"`
	// contains filtered or unexported fields
}

MultiTenancy handles tenant isolation and RBAC.

func (*MultiTenancy) AuthorizeTenant

func (mt *MultiTenancy) AuthorizeTenant(tenantID string) error

func (*MultiTenancy) GetTenant

func (mt *MultiTenancy) GetTenant(tenantID string) (*Tenant, error)

GetTenant retrieves a tenant by ID.

func (*MultiTenancy) GetTenantStats

func (mt *MultiTenancy) GetTenantStats(tenantID string) (map[string]int64, error)

func (*MultiTenancy) ListTenants

func (mt *MultiTenancy) ListTenants() []*Tenant

ListTenants returns all registered tenants.

func (*MultiTenancy) Provision

func (mt *MultiTenancy) Provision(ctx caddy.Context, logger *zap.Logger) error

Provision sets up multi-tenancy.

func (*MultiTenancy) RecordRequest

func (mt *MultiTenancy) RecordRequest(tenantID string, statusCode int)

func (*MultiTenancy) RegisterTenant

func (mt *MultiTenancy) RegisterTenant(tenant *Tenant) error

RegisterTenant adds a new tenant.

func (*MultiTenancy) ResolveTenantID

func (mt *MultiTenancy) ResolveTenantID(r *http.Request) string

type PIIMasker

type PIIMasker struct {
	// contains filtered or unexported fields
}

func NewPIIMasker

func NewPIIMasker(config *PIIMaskingConfig) *PIIMasker

func (*PIIMasker) Mask

func (pm *PIIMasker) Mask(text string) string

type PIIMaskingConfig

type PIIMaskingConfig struct {
	Enabled        bool     `json:"enabled,omitempty"`
	MaskFields     []string `json:"mask_fields,omitempty"`
	MaskEmail      bool     `json:"mask_email,omitempty"`
	MaskPhone      bool     `json:"mask_phone,omitempty"`
	MaskIP         bool     `json:"mask_ip,omitempty"`
	MaskCreditCard bool     `json:"mask_credit_card,omitempty"`
}

type Permission

type Permission string
const (
	PermissionMetricsRead  Permission = "metrics:read"
	PermissionMetricsWrite Permission = "metrics:write"
	PermissionAlertsRead   Permission = "alerts:read"
	PermissionAlertsWrite  Permission = "alerts:write"
	PermissionTenantsRead  Permission = "tenants:read"
	PermissionTenantsWrite Permission = "tenants:write"
	PermissionSLORead      Permission = "slo:read"
	PermissionSLOWrite     Permission = "slo:write"
	PermissionAuditRead    Permission = "audit:read"
)

type PrometheusBackend

type PrometheusBackend struct {
	// contains filtered or unexported fields
}

func (*PrometheusBackend) Close

func (pb *PrometheusBackend) Close() error

func (*PrometheusBackend) Query

func (pb *PrometheusBackend) Query(ctx context.Context, query string) (interface{}, error)

func (*PrometheusBackend) Write

func (pb *PrometheusBackend) Write(ctx context.Context, metrics []byte) error

type RBACManager

type RBACManager struct {
	Enabled bool `json:"enabled,omitempty"`
	// contains filtered or unexported fields
}

func (*RBACManager) CreateAPIKey

func (rbac *RBACManager) CreateAPIKey(name, tenantID string, role Role, expiresIn *time.Duration) (*APIKey, error)

func (*RBACManager) HasPermission

func (rbac *RBACManager) HasPermission(apiKey *APIKey, permission Permission) bool

func (*RBACManager) ListAPIKeys

func (rbac *RBACManager) ListAPIKeys(tenantID string) []*APIKey

func (*RBACManager) Provision

func (rbac *RBACManager) Provision(logger *zap.Logger) error

func (*RBACManager) RevokeAPIKey

func (rbac *RBACManager) RevokeAPIKey(keyID string) error

func (*RBACManager) ValidateAPIKey

func (rbac *RBACManager) ValidateAPIKey(key string) (*APIKey, error)

type ReportingConfig

type ReportingConfig struct {
	Enabled      bool     `json:"enabled,omitempty"`
	Formats      []string `json:"formats,omitempty"` // json, csv, pdf
	Schedule     string   `json:"schedule,omitempty"`
	Recipients   []string `json:"recipients,omitempty"`
	IncludeAudit bool     `json:"include_audit,omitempty"`
}

type RetentionConfig

type RetentionConfig struct {
	MetricsRetentionDays int    `json:"metrics_retention_days,omitempty"`
	TracesRetentionDays  int    `json:"traces_retention_days,omitempty"`
	LogsRetentionDays    int    `json:"logs_retention_days,omitempty"`
	AuditRetentionDays   int    `json:"audit_retention_days,omitempty"`
	AutoCleanup          bool   `json:"auto_cleanup,omitempty"`
	ComplianceMode       string `json:"compliance_mode,omitempty"` // sox, gdpr, hipaa, iso27001
}

type Role

type Role string
const (
	RoleAdmin   Role = "admin"
	RoleEditor  Role = "editor"
	RoleViewer  Role = "viewer"
	RoleAuditor Role = "auditor"
)

type SLO

type SLO struct {
	Name        string       `json:"name"`
	Target      float64      `json:"target"` // e.g., 99.9 for 99.9%
	Window      string       `json:"window"` // e.g., "30d"
	BurnRates   []*BurnRate  `json:"burn_rates,omitempty"`
	ErrorBudget *ErrorBudget `json:"error_budget,omitempty"`
}

SLO defines a Service Level Objective.

func (*SLO) CalculateErrorBudget

func (s *SLO) CalculateErrorBudget(totalRequests, failedRequests int64) *ErrorBudget

CalculateErrorBudget calculates error budget for an SLO.

func (*SLO) Validate

func (s *SLO) Validate() error

Validate validates SLO configuration.

type SLOManager

type SLOManager struct {
	SLOs []*SLO `json:"slos,omitempty"`
	// contains filtered or unexported fields
}

SLOManager handles Service Level Objective monitoring.

func (*SLOManager) CheckBurnRate

func (sm *SLOManager) CheckBurnRate(br *BurnRate) bool

CheckBurnRate checks if a burn rate threshold is exceeded.

func (*SLOManager) Provision

func (sm *SLOManager) Provision(logger *zap.Logger) error

Provision sets up the SLO manager.

func (*SLOManager) RecordResult

func (sm *SLOManager) RecordResult(statusCode int, duration time.Duration)

RecordResult records the result of a request.

type SamplerConfig

type SamplerConfig struct {
	Type string  `json:"type"` // always, never, probability, parent_based
	Rate float64 `json:"rate,omitempty"`
}

type StorageBackend

type StorageBackend interface {
	Write(ctx context.Context, metrics []byte) error
	Query(ctx context.Context, query string) (interface{}, error)
	Close() error
}

type Tenant

type Tenant struct {
	ID     string            `json:"id"`
	Name   string            `json:"name"`
	Quota  *TenantQuota      `json:"quota,omitempty"`
	Roles  []string          `json:"roles,omitempty"`
	Labels map[string]string `json:"labels,omitempty"`
	// contains filtered or unexported fields
}

Tenant represents a single tenant configuration.

type TenantQuota

type TenantQuota struct {
	MaxRequests  int64 `json:"max_requests,omitempty"`
	MaxMetrics   int64 `json:"max_metrics,omitempty"`
	MaxAlerts    int   `json:"max_alerts,omitempty"`
	RateLimitRPS int   `json:"rate_limit_rps,omitempty"`
}

TenantQuota defines resource limits for a tenant.

type VictoriaMetricsBackend

type VictoriaMetricsBackend struct {
	// contains filtered or unexported fields
}

func (*VictoriaMetricsBackend) Close

func (vm *VictoriaMetricsBackend) Close() error

func (*VictoriaMetricsBackend) Query

func (vm *VictoriaMetricsBackend) Query(ctx context.Context, query string) (interface{}, error)

func (*VictoriaMetricsBackend) Write

func (vm *VictoriaMetricsBackend) Write(ctx context.Context, metrics []byte) error

type WebhookConfig

type WebhookConfig struct {
	URL    string `json:"url"`
	Secret string `json:"secret,omitempty"`
}

WebhookConfig configures webhook notifications.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL