monitoring

package
v0.0.0-...-fe4519f Latest Latest
Warning

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

Go to latest
Published: Apr 7, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Example

Example example of using the monitoring system

// Create monitoring components
metrics := NewMetricsCollector()

logConfig := &LogConfig{
	Level:  LevelError, // Only errors to not clutter output
	Format: FormatJSON,
	Output: "/dev/null", // Send to /dev/null
}
logger, _ := NewLogger(logConfig)
defer logger.Close()

monitor := NewPerformanceMonitor(metrics, logger, 30*time.Second)
alertManager := NewAlertManager(logger, monitor, 30*time.Second)

// Subscribe to alerts
consoleSubscriber := NewConsoleAlertSubscriber(logger)
alertManager.Subscribe(consoleSubscriber)

// Start monitoring
monitor.Start()
alertManager.Start()

// Start metrics server
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()

// Start metrics server in background
go func() {
	_ = metrics.StartMetricsServer(ctx, ":0") // Random port - ignore error in test
}()

// Emulate activity
monitor.OnConnectionStart("user1", "udp")
monitor.OnTrafficReceived("user1", "udp", 1024, 1)

// Stop monitoring
monitor.Stop()
alertManager.Stop()

fmt.Println("Monitoring example completed")
Output:
Monitoring example completed

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Alert

type Alert struct {
	ID          string                 `json:"id"`
	Level       AlertLevel             `json:"level"`
	Title       string                 `json:"title"`
	Description string                 `json:"description"`
	Component   string                 `json:"component"`
	Metadata    map[string]interface{} `json:"metadata"`
	Timestamp   time.Time              `json:"timestamp"`
	Resolved    bool                   `json:"resolved"`
	ResolvedAt  *time.Time             `json:"resolved_at,omitempty"`
}

Alert alert structure

type AlertLevel

type AlertLevel string

AlertLevel alert priority level

const (
	AlertInfo     AlertLevel = "info"
	AlertWarning  AlertLevel = "warning"
	AlertCritical AlertLevel = "critical"
)

type AlertManager

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

AlertManager manages alerts and notifications

func NewAlertManager

func NewAlertManager(logger *Logger, monitor *PerformanceMonitor, checkInterval time.Duration) *AlertManager

NewAlertManager creates a new alerts manager

func (*AlertManager) AddRule

func (am *AlertManager) AddRule(rule *AlertRule)

AddRule adds an alert rule

func (*AlertManager) GetActiveAlerts

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

GetActiveAlerts returns active alerts

func (*AlertManager) RemoveRule

func (am *AlertManager) RemoveRule(name string)

RemoveRule removes an alert rule

func (*AlertManager) ResolveAlert

func (am *AlertManager) ResolveAlert(alertID string) error

ResolveAlert marks an alert as resolved

func (*AlertManager) Start

func (am *AlertManager) Start()

Start starts alerts monitoring

func (*AlertManager) Stop

func (am *AlertManager) Stop()

Stop stops alerts monitoring

func (*AlertManager) Subscribe

func (am *AlertManager) Subscribe(subscriber AlertSubscriber)

Subscribe adds a subscriber to alerts

type AlertRule

type AlertRule struct {
	Name        string                                      `json:"name"`
	Description string                                      `json:"description"`
	Level       AlertLevel                                  `json:"level"`
	Condition   func(metrics map[string]interface{}) bool   `json:"-"`
	Message     func(metrics map[string]interface{}) string `json:"-"`
	Cooldown    time.Duration                               `json:"cooldown"`
	// contains filtered or unexported fields
}

AlertRule rule for creating alerts

type AlertSubscriber

type AlertSubscriber interface {
	OnAlert(alert *Alert) error
}

AlertSubscriber interface for alert subscribers

type ConsoleAlertSubscriber

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

ConsoleAlertSubscriber outputs alerts to console

func NewConsoleAlertSubscriber

func NewConsoleAlertSubscriber(logger *Logger) *ConsoleAlertSubscriber

func (*ConsoleAlertSubscriber) OnAlert

func (c *ConsoleAlertSubscriber) OnAlert(alert *Alert) error

type EnhancedMetrics

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

EnhancedMetrics provides comprehensive monitoring capabilities

func NewEnhancedMetrics

func NewEnhancedMetrics(config *MetricsConfig) *EnhancedMetrics

NewEnhancedMetrics creates a new enhanced metrics instance

func (*EnhancedMetrics) GetMetricsSummary

func (em *EnhancedMetrics) GetMetricsSummary() map[string]interface{}

GetMetricsSummary returns a summary of all metrics

func (*EnhancedMetrics) RecordAuditEvent

func (em *EnhancedMetrics) RecordAuditEvent(eventType, user string)

RecordAuditEvent records an audit event

func (*EnhancedMetrics) RecordAuthAttempt

func (em *EnhancedMetrics) RecordAuthAttempt(method, result string)

RecordAuthAttempt records an authentication attempt

func (*EnhancedMetrics) RecordAuthDuration

func (em *EnhancedMetrics) RecordAuthDuration(method string, duration time.Duration)

RecordAuthDuration records authentication duration

func (*EnhancedMetrics) RecordBufferPoolGet

func (em *EnhancedMetrics) RecordBufferPoolGet()

RecordBufferPoolGet records a buffer pool get operation

func (*EnhancedMetrics) RecordBufferPoolHit

func (em *EnhancedMetrics) RecordBufferPoolHit()

RecordBufferPoolHit records a buffer pool cache hit

func (*EnhancedMetrics) RecordBufferPoolMiss

func (em *EnhancedMetrics) RecordBufferPoolMiss()

RecordBufferPoolMiss records a buffer pool cache miss

func (*EnhancedMetrics) RecordBufferPoolPut

func (em *EnhancedMetrics) RecordBufferPoolPut()

RecordBufferPoolPut records a buffer pool put operation

func (*EnhancedMetrics) RecordCircuitBreakerOp

func (em *EnhancedMetrics) RecordCircuitBreakerOp(service, state, result string)

RecordCircuitBreakerOp records a circuit breaker operation

func (*EnhancedMetrics) RecordComplianceCheck

func (em *EnhancedMetrics) RecordComplianceCheck(checkType, result string)

RecordComplianceCheck records a compliance check

func (*EnhancedMetrics) RecordConnectionError

func (em *EnhancedMetrics) RecordConnectionError(errorType string)

RecordConnectionError records a connection error

func (*EnhancedMetrics) RecordDataTransferred

func (em *EnhancedMetrics) RecordDataTransferred(direction string, bytes float64)

RecordDataTransferred records data transfer

func (*EnhancedMetrics) RecordFailedLogin

func (em *EnhancedMetrics) RecordFailedLogin(source, reason string)

RecordFailedLogin records a failed login attempt

func (*EnhancedMetrics) RecordGCDuration

func (em *EnhancedMetrics) RecordGCDuration(duration time.Duration)

RecordGCDuration records garbage collection duration

func (*EnhancedMetrics) RecordMFAAttempt

func (em *EnhancedMetrics) RecordMFAAttempt(result string)

RecordMFAAttempt records an MFA attempt

func (*EnhancedMetrics) RecordRateLimitHit

func (em *EnhancedMetrics) RecordRateLimitHit()

RecordRateLimitHit records a rate limit hit

func (*EnhancedMetrics) RecordRequest

func (em *EnhancedMetrics) RecordRequest(service, result string)

RecordRequest records a request

func (*EnhancedMetrics) RecordRequestDuration

func (em *EnhancedMetrics) RecordRequestDuration(service string, duration time.Duration)

RecordRequestDuration records request duration

func (*EnhancedMetrics) RecordSecurityEvent

func (em *EnhancedMetrics) RecordSecurityEvent(eventType, severity string)

RecordSecurityEvent records a security event

func (*EnhancedMetrics) RecordSuspiciousActivity

func (em *EnhancedMetrics) RecordSuspiciousActivity()

RecordSuspiciousActivity records suspicious activity

func (*EnhancedMetrics) RecordTunnelLatency

func (em *EnhancedMetrics) RecordTunnelLatency(tunnelType string, latency time.Duration)

RecordTunnelLatency records tunnel latency

func (*EnhancedMetrics) SetActiveBuffers

func (em *EnhancedMetrics) SetActiveBuffers(count float64)

SetActiveBuffers sets the number of active buffers

func (*EnhancedMetrics) SetActiveConnections

func (em *EnhancedMetrics) SetActiveConnections(count float64)

SetActiveConnections sets the number of active connections

func (*EnhancedMetrics) SetCPUUsage

func (em *EnhancedMetrics) SetCPUUsage(percent float64)

SetCPUUsage sets CPU usage percentage

func (*EnhancedMetrics) SetCacheHitRate

func (em *EnhancedMetrics) SetCacheHitRate(cacheType string, rate float64)

SetCacheHitRate sets cache hit rate

func (*EnhancedMetrics) SetDataRetention

func (em *EnhancedMetrics) SetDataRetention(dataType string, days float64)

SetDataRetention sets data retention period

func (*EnhancedMetrics) SetErrorRate

func (em *EnhancedMetrics) SetErrorRate(service string, rate float64)

SetErrorRate sets error rate for a service

func (*EnhancedMetrics) SetGoroutineCount

func (em *EnhancedMetrics) SetGoroutineCount(count float64)

SetGoroutineCount sets the number of goroutines

func (*EnhancedMetrics) SetMemoryUsage

func (em *EnhancedMetrics) SetMemoryUsage(memType string, bytes float64)

SetMemoryUsage sets memory usage

func (*EnhancedMetrics) SetSessionCount

func (em *EnhancedMetrics) SetSessionCount(count float64)

SetSessionCount sets the number of active sessions

func (*EnhancedMetrics) SetTotalBufferBytes

func (em *EnhancedMetrics) SetTotalBufferBytes(bytes float64)

SetTotalBufferBytes sets the total bytes in active buffers

func (*EnhancedMetrics) UpdateFromBufferPool

func (em *EnhancedMetrics) UpdateFromBufferPool(stats map[string]interface{})

UpdateFromBufferPool updates metrics from buffer pool stats

func (*EnhancedMetrics) UpdateFromReliabilityManager

func (em *EnhancedMetrics) UpdateFromReliabilityManager(stats map[string]interface{})

UpdateFromReliabilityManager updates metrics from reliability manager

type LogConfig

type LogConfig struct {
	Level      LogLevel  `json:"level" yaml:"level"`
	Format     LogFormat `json:"format" yaml:"format"`
	Output     string    `json:"output" yaml:"output"`           // "stdout", "stderr", or file path
	MaxSize    int       `json:"max_size" yaml:"max_size"`       // maximum file size in MB
	MaxBackups int       `json:"max_backups" yaml:"max_backups"` // number of backup files
	MaxAge     int       `json:"max_age" yaml:"max_age"`         // maximum file age in days
	Compress   bool      `json:"compress" yaml:"compress"`       // compress backup files

	// Additional fields for OpenVPN compatibility
	EnableOpenVPNCompat bool   `json:"enable_openvpn_compat" yaml:"enable_openvpn_compat"`
	Facility            string `json:"facility" yaml:"facility"` // for syslog
	EnableSyslog        bool   `json:"enable_syslog" yaml:"enable_syslog"`
}

LogConfig logging configuration

func DefaultLogConfig

func DefaultLogConfig() *LogConfig

DefaultLogConfig returns default logging configuration

type LogFormat

type LogFormat string

LogFormat logging format

const (
	FormatJSON    LogFormat = "json"
	FormatText    LogFormat = "text"
	FormatOpenVPN LogFormat = "openvpn" // OpenVPN-compatible format
)

type LogLevel

type LogLevel string

LogLevel logging levels

const (
	LevelDebug LogLevel = "debug"
	LevelInfo  LogLevel = "info"
	LevelWarn  LogLevel = "warn"
	LevelError LogLevel = "error"
)

type Logger

type Logger struct {
	*slog.Logger
	// contains filtered or unexported fields
}

Logger structured logger for GoVPN

func NewLogger

func NewLogger(config *LogConfig) (*Logger, error)

NewLogger creates a new structured logger

func (*Logger) Close

func (l *Logger) Close() error

Close closes the logger and releases resources

func (*Logger) LogAuthEvent

func (l *Logger) LogAuthEvent(event, userID, method, result, reason string)

Authentication logging methods

func (*Logger) LogAuthFailure

func (l *Logger) LogAuthFailure(userID, method, reason string)

func (*Logger) LogAuthSuccess

func (l *Logger) LogAuthSuccess(userID, method string)

func (*Logger) LogCertificateEvent

func (l *Logger) LogCertificateEvent(event, certType, commonName string, attrs ...interface{})

func (*Logger) LogConnection

func (l *Logger) LogConnection(event string, userID, clientIP, virtualIP string, attrs ...interface{})

Connection logging methods

func (*Logger) LogConnectionEnd

func (l *Logger) LogConnectionEnd(userID, clientIP, reason string, duration time.Duration, bytesRx, bytesTx int64)

func (*Logger) LogConnectionStart

func (l *Logger) LogConnectionStart(userID, clientIP, virtualIP, protocol string)

func (*Logger) LogDPIDetection

func (l *Logger) LogDPIDetection(method, region string, confidence float64)

func (*Logger) LogError

func (l *Logger) LogError(component, operation string, err error, attrs ...interface{})

func (*Logger) LogObfuscation

func (l *Logger) LogObfuscation(event, method, region string, attrs ...interface{})

Obfuscation logging methods

func (*Logger) LogObfuscationSwitch

func (l *Logger) LogObfuscationSwitch(oldMethod, newMethod, reason, region string)

func (*Logger) LogOpenVPNEvent

func (l *Logger) LogOpenVPNEvent(level, message string)

OpenVPN-compatible logging methods

func (*Logger) LogPerformanceMetric

func (l *Logger) LogPerformanceMetric(metric string, value float64, unit string, attrs ...interface{})

Performance logging methods

func (*Logger) LogSecurityEvent

func (l *Logger) LogSecurityEvent(event, severity, description string, attrs ...interface{})

Security logging methods

func (*Logger) LogSystemEvent

func (l *Logger) LogSystemEvent(event, component, message string, attrs ...interface{})

System logging methods

func (*Logger) WithFields

func (l *Logger) WithFields(fields map[string]interface{}) *Logger

WithFields adds fields to the logger

type MetricsCollector

type MetricsCollector struct {
	// Connection metrics
	ActiveConnections    prometheus.Gauge
	TotalConnections     prometheus.Counter
	ConnectionDuration   prometheus.Histogram
	DisconnectionReasons prometheus.CounterVec

	// Traffic metrics
	BytesReceived   prometheus.CounterVec
	BytesSent       prometheus.CounterVec
	PacketsReceived prometheus.CounterVec
	PacketsSent     prometheus.CounterVec
	PacketsDropped  prometheus.CounterVec

	// Authentication metrics
	AuthAttempts    prometheus.CounterVec
	AuthSuccessful  prometheus.Counter
	AuthFailed      prometheus.CounterVec
	SessionDuration prometheus.Histogram
	ActiveSessions  prometheus.Gauge

	// Obfuscation metrics
	ObfuscationMethods prometheus.CounterVec
	ObfuscationSwitch  prometheus.Counter
	DPIDetections      prometheus.Counter
	ObfuscationLatency prometheus.Histogram

	// Server performance metrics
	CPUUsage            prometheus.Gauge
	MemoryUsage         prometheus.Gauge
	GoroutineCount      prometheus.Gauge
	OpenFileDescriptors prometheus.Gauge
	NetworkErrors       prometheus.CounterVec

	// Certificate metrics
	CertificatesTotal      prometheus.GaugeVec
	CertificatesExpiring   prometheus.Gauge
	CertificateRevocations prometheus.Counter

	// Protocol metrics
	ProtocolVersions prometheus.CounterVec
	ClientVersions   prometheus.CounterVec
	ProtocolErrors   prometheus.CounterVec
	// contains filtered or unexported fields
}

MetricsCollector collects metrics for GoVPN server

func NewMetricsCollector

func NewMetricsCollector() *MetricsCollector

NewMetricsCollector creates a new metrics collector

func (*MetricsCollector) Handler

func (m *MetricsCollector) Handler() http.Handler

Handler returns HTTP handler for metrics export

func (*MetricsCollector) OnAuthAttempt

func (m *MetricsCollector) OnAuthAttempt(method, result string)

Authentication tracking methods

func (*MetricsCollector) OnCertificateRevocation

func (m *MetricsCollector) OnCertificateRevocation()

func (*MetricsCollector) OnClientConnection

func (m *MetricsCollector) OnClientConnection(version, platform string)

Client information tracking

func (*MetricsCollector) OnConnectionEnd

func (m *MetricsCollector) OnConnectionEnd(userID, reason string, duration time.Duration)

func (*MetricsCollector) OnConnectionStart

func (m *MetricsCollector) OnConnectionStart(userID, protocol string)

Connection tracking methods

func (*MetricsCollector) OnDPIDetection

func (m *MetricsCollector) OnDPIDetection()

func (*MetricsCollector) OnNetworkError

func (m *MetricsCollector) OnNetworkError(errorType, interfaceName string)

Network error tracking

func (*MetricsCollector) OnObfuscationMethodUsed

func (m *MetricsCollector) OnObfuscationMethodUsed(method, region string)

Obfuscation tracking methods

func (*MetricsCollector) OnObfuscationProcessed

func (m *MetricsCollector) OnObfuscationProcessed(latency time.Duration)

func (*MetricsCollector) OnObfuscationSwitch

func (m *MetricsCollector) OnObfuscationSwitch()

func (*MetricsCollector) OnPacketsDropped

func (m *MetricsCollector) OnPacketsDropped(reason string, count int64)

func (*MetricsCollector) OnProtocolError

func (m *MetricsCollector) OnProtocolError(errorType, protocol string)

func (*MetricsCollector) OnSessionEnd

func (m *MetricsCollector) OnSessionEnd(duration time.Duration)

func (*MetricsCollector) OnTrafficReceived

func (m *MetricsCollector) OnTrafficReceived(userID, protocol string, bytes, packets int64)

Traffic tracking methods

func (*MetricsCollector) OnTrafficSent

func (m *MetricsCollector) OnTrafficSent(userID, protocol string, bytes, packets int64)

func (*MetricsCollector) StartMetricsServer

func (m *MetricsCollector) StartMetricsServer(ctx context.Context, addr string) error

StartMetricsServer starts HTTP server for metrics export

func (*MetricsCollector) UpdateCertificateCount

func (m *MetricsCollector) UpdateCertificateCount(certType, status string, count float64)

Certificate tracking methods

func (*MetricsCollector) UpdateExpiringCertificates

func (m *MetricsCollector) UpdateExpiringCertificates(count float64)

type MetricsConfig

type MetricsConfig struct {
	Namespace    string
	Subsystem    string
	EnableAll    bool
	CustomLabels map[string]string
}

MetricsConfig configures the enhanced metrics system

func DefaultMetricsConfig

func DefaultMetricsConfig() *MetricsConfig

DefaultMetricsConfig returns default metrics configuration

type OpenVPNHandler

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

OpenVPNHandler special handler for OpenVPN compatibility

func NewOpenVPNHandler

func NewOpenVPNHandler(w io.Writer, opts *slog.HandlerOptions) *OpenVPNHandler

func (*OpenVPNHandler) Enabled

func (h *OpenVPNHandler) Enabled(ctx context.Context, level slog.Level) bool

func (*OpenVPNHandler) Handle

func (h *OpenVPNHandler) Handle(ctx context.Context, r slog.Record) error

func (*OpenVPNHandler) WithAttrs

func (h *OpenVPNHandler) WithAttrs(attrs []slog.Attr) slog.Handler

func (*OpenVPNHandler) WithGroup

func (h *OpenVPNHandler) WithGroup(name string) slog.Handler

type PerformanceMonitor

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

PerformanceMonitor monitors system performance

func NewPerformanceMonitor

func NewPerformanceMonitor(metrics *MetricsCollector, logger *Logger, interval time.Duration) *PerformanceMonitor

NewPerformanceMonitor creates a new performance monitor

func (*PerformanceMonitor) GetMetricsSummary

func (pm *PerformanceMonitor) GetMetricsSummary() map[string]interface{}

GetMetricsSummary returns a summary of metrics

func (*PerformanceMonitor) OnAuthAttempt

func (pm *PerformanceMonitor) OnAuthAttempt(method, result string)

Authentication tracking

func (*PerformanceMonitor) OnConnectionEnd

func (pm *PerformanceMonitor) OnConnectionEnd(userID, reason string, duration time.Duration)

func (*PerformanceMonitor) OnConnectionStart

func (pm *PerformanceMonitor) OnConnectionStart(userID, protocol string)

Connection tracking

func (*PerformanceMonitor) OnDPIDetection

func (pm *PerformanceMonitor) OnDPIDetection()

func (*PerformanceMonitor) OnObfuscationSwitch

func (pm *PerformanceMonitor) OnObfuscationSwitch()

Obfuscation tracking

func (*PerformanceMonitor) OnTrafficReceived

func (pm *PerformanceMonitor) OnTrafficReceived(userID, protocol string, bytes, packets int64)

Traffic tracking

func (*PerformanceMonitor) OnTrafficSent

func (pm *PerformanceMonitor) OnTrafficSent(userID, protocol string, bytes, packets int64)

func (*PerformanceMonitor) Start

func (pm *PerformanceMonitor) Start()

Start starts the performance monitoring

func (*PerformanceMonitor) Stop

func (pm *PerformanceMonitor) Stop()

Stop stops the performance monitoring

Jump to

Keyboard shortcuts

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