resources

package
v0.0.8 Latest Latest
Warning

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

Go to latest
Published: Jul 7, 2025 License: MIT Imports: 11 Imported by: 0

README

Resources Package

The resources package provides comprehensive resource monitoring, tracking, and alerting for plugin resource usage including CPU, memory, goroutines, file handles, and network connections.

Overview

This package implements real-time resource monitoring with trend analysis, violation detection, and automated alerting to ensure plugins operate within defined resource boundaries and maintain system stability.

Components

Core Files
  • monitor.go - Central resource monitoring system
  • collectors.go - Resource data collectors for different metrics
  • metrics.go - Resource metrics aggregation and analysis
  • alerts.go - Resource violation alerting system
  • trends.go - Resource usage trend analysis
  • integration_test.go - Comprehensive monitoring tests

Key Features

Real-time Resource Monitoring
monitor := resources.NewResourceMonitor(&resources.MonitorConfig{
    CollectionInterval: 30 * time.Second,
    AlertThresholds: map[resources.ResourceType]float64{
        resources.ResourceTypeMemory:     80.0,  // 80% of limit
        resources.ResourceTypeCPU:        70.0,  // 70% of limit
        resources.ResourceTypeGoroutines: 90.0,  // 90% of limit
    },
    RetentionPeriod: 24 * time.Hour,
    EnabledCollectors: []resources.ResourceType{
        resources.ResourceTypeMemory,
        resources.ResourceTypeCPU,
        resources.ResourceTypeGoroutines,
        resources.ResourceTypeFileHandles,
        resources.ResourceTypeConnections,
    },
})

err := monitor.Start(context.Background())
Plugin Resource Tracking
limits := &resources.ResourceLimits{
    MaxMemoryMB:      512,
    MaxCPUPercent:    25.0,
    MaxGoroutines:    100,
    MaxFileHandles:   50,
    MaxConnections:   20,
}

err := monitor.TrackPlugin("my-plugin", limits)
Resource Metrics Collection
usage, err := monitor.GetPluginUsage("my-plugin")
systemSummary := monitor.GetSystemSummary()
trends := monitor.GetResourceTrends("my-plugin", time.Hour)

Resource Types

Monitored Resources
  • Memory - RAM usage in MB with RSS and virtual memory
  • CPU - CPU utilization percentage and time
  • Goroutines - Active goroutine count per plugin
  • File Handles - Open file descriptor count
  • Network Connections - Active network connection count
  • Disk I/O - Read/write operations and bandwidth
  • Custom Metrics - Plugin-specific resource metrics
Resource Usage Structure
type ResourceUsage struct {
    PluginName   string
    ResourceType ResourceType
    Current      float64
    Peak         float64
    Average      float64
    Minimum      float64
    Unit         string
    Timestamp    time.Time
    Trend        TrendDirection
    Metadata     map[string]interface{}
}

Configuration

Monitor Configuration
type MonitorConfig struct {
    CollectionInterval    time.Duration
    AlertThresholds       map[ResourceType]float64
    RetentionPeriod      time.Duration
    EnabledCollectors    []ResourceType
    AlertingEnabled      bool
    TrendAnalysisEnabled bool
    MetricsExportEnabled bool
    ExportInterval       time.Duration
    AlertCooldownPeriod  time.Duration
    BatchSize           int
    MaxConcurrentCollections int
}
Resource Limits
type ResourceLimits struct {
    MaxMemoryMB      int64
    MaxCPUPercent    float64
    MaxGoroutines    int64
    MaxFileHandles   int64
    MaxConnections   int64
    MaxDiskReadMB    int64
    MaxDiskWriteMB   int64
    CustomLimits     map[string]float64
}

Resource Collectors

Memory Collector

Tracks memory usage patterns:

  • Resident Set Size (RSS)
  • Virtual Memory Size (VMS)
  • Heap allocation statistics
  • Garbage collection metrics
CPU Collector

Monitors CPU utilization:

  • User CPU time
  • System CPU time
  • CPU percentage utilization
  • Context switches
Goroutine Collector

Tracks goroutine lifecycle:

  • Active goroutine count
  • Goroutine creation rate
  • Blocked goroutine detection
  • Stack size monitoring
File Handle Collector

Monitors file descriptor usage:

  • Open file count
  • File type distribution
  • Socket connections
  • Pipe and device files
Network Collector

Tracks network resource usage:

  • TCP connection count
  • UDP socket count
  • Network I/O statistics
  • Connection state distribution

Metrics and Analysis

Resource Metrics
type ResourceMetrics struct {
    PluginName          string
    TotalResourceTypes  int
    HealthScore         float64
    ResourceUsage       map[ResourceType]*ResourceUsage
    ViolationCount      int64
    LastViolation       time.Time
    TrendAnalysis       map[ResourceType]*TrendAnalysis
    PredictedUsage      map[ResourceType]*UsagePrediction
}
Trend Analysis
type TrendAnalysis struct {
    Direction     TrendDirection
    Confidence    float64
    Slope         float64
    RSquared     float64
    PredictedPeak time.Time
    TimeToLimit   time.Duration
    Seasonality   []SeasonalPattern
}

Alerting System

Violation Detection
type ResourceViolation struct {
    PluginName   string
    ResourceType ResourceType
    Limit        float64
    Actual       float64
    Threshold    float64
    Timestamp    time.Time
    Severity     Severity
    Action       string
    Context      map[string]interface{}
}
Alert Manager
alertManager := resources.NewAlertManager()
alertManager.RegisterHandler(resources.SeverityCritical, criticalHandler)
alertManager.RegisterHandler(resources.SeverityWarning, warningHandler)

Integration Examples

Basic Plugin Monitoring
// Initialize monitor
monitor := resources.NewResourceMonitor(nil) // Use defaults
ctx := context.Background()
monitor.Start(ctx)
defer monitor.Stop()

// Track plugin with limits
limits := &resources.ResourceLimits{
    MaxMemoryMB:   256,
    MaxCPUPercent: 50.0,
    MaxGoroutines: 50,
}
monitor.TrackPlugin("my-plugin", limits)

// Check usage periodically
ticker := time.NewTicker(time.Minute)
for range ticker.C {
    usage, _ := monitor.GetPluginUsage("my-plugin")
    for resourceType, resource := range usage {
        if resource.Current > limits.GetLimit(resourceType) * 0.8 {
            log.Printf("Plugin %s approaching %s limit: %.2f%%",
                "my-plugin", resourceType, resource.Current)
        }
    }
}
Custom Resource Collector
type CustomCollector struct {
    pluginName string
}

func (c *CustomCollector) Collect() (*resources.ResourceUsage, error) {
    // Collect custom metrics
    customValue := getCustomMetric(c.pluginName)
    
    return &resources.ResourceUsage{
        PluginName:   c.pluginName,
        ResourceType: "custom_metric",
        Current:      customValue,
        Unit:         "units",
        Timestamp:    time.Now(),
    }, nil
}

// Register custom collector
monitor.RegisterCollector("my-plugin", "custom_metric", &CustomCollector{
    pluginName: "my-plugin",
})

Performance Considerations

  • Collection Frequency - Balance monitoring accuracy with overhead
  • Data Retention - Configure appropriate retention periods
  • Batch Processing - Use batching for high-frequency metrics
  • Memory Management - Monitor the monitor's own resource usage
  • Concurrent Collections - Limit concurrent collection operations

Testing

go test ./pkg/resources -v

Test coverage includes:

  • Resource collection accuracy
  • Trend analysis algorithms
  • Alert triggering and handling
  • Performance under load
  • Memory leak detection

Dependencies

  • runtime - Go runtime metrics
  • os - Process and system information
  • syscall - System call interfaces
  • time - Time-based operations
  • sync - Concurrency primitives

Monitoring Dashboard Integration

The package supports exporting metrics to popular monitoring systems:

  • Prometheus - Native metrics export
  • Grafana - Dashboard templates
  • DataDog - Custom metric integration
  • New Relic - APM integration
  • CloudWatch - AWS metrics export

Future Enhancements

  • Machine learning-based anomaly detection
  • Predictive resource scaling recommendations
  • Integration with container orchestration platforms
  • Real-time resource optimization suggestions
  • Advanced correlation analysis between resources

Documentation

Overview

Package resources provides resource monitoring and limiting for plugins

Index

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"`
	Type        AlertType              `json:"type"`
	Severity    Severity               `json:"severity"`
	Title       string                 `json:"title"`
	Description string                 `json:"description"`
	PluginName  string                 `json:"plugin_name"`
	Resource    ResourceType           `json:"resource"`
	Violation   *ResourceViolation     `json:"violation"`
	Timestamp   time.Time              `json:"timestamp"`
	Metadata    map[string]interface{} `json:"metadata"`
}

Alert represents a resource violation alert

type AlertConfig

type AlertConfig struct {
	EnabledAlerters    []AlerterType               `json:"enabled_alerters"`
	RateLimitWindow    time.Duration               `json:"rate_limit_window"`
	MaxAlertsPerWindow int                         `json:"max_alerts_per_window"`
	SeverityThresholds map[Severity]bool           `json:"severity_thresholds"`
	Cooldowns          map[AlertType]time.Duration `json:"cooldowns"`
}

AlertConfig contains alerting configuration

func DefaultAlertConfig

func DefaultAlertConfig() *AlertConfig

DefaultAlertConfig returns a default alert configuration

type AlertManager

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

AlertManager handles resource violation alerts

func NewAlertManager

func NewAlertManager() *AlertManager

NewAlertManager creates a new alert manager

func (*AlertManager) RegisterAlerter

func (am *AlertManager) RegisterAlerter(alerter Alerter)

RegisterAlerter registers a new alerter

func (*AlertManager) SendAlert

func (am *AlertManager) SendAlert(violation *ResourceViolation)

SendAlert sends an alert through all registered alerters

type AlertType

type AlertType string

AlertType represents different types of alerts

const (
	AlertTypeResourceViolation AlertType = "resource_violation"
	AlertTypePluginFailure     AlertType = "plugin_failure"
	AlertTypeSecurityEvent     AlertType = "security_event"
	AlertTypeSystemHealth      AlertType = "system_health"
)

type Alerter

type Alerter interface {
	SendAlert(alert *Alert) error
	GetAlerterType() AlerterType
}

Alerter defines interface for sending alerts

type AlerterType

type AlerterType string

AlerterType represents different types of alerters

const (
	AlerterTypeLog     AlerterType = "log"
	AlerterTypeEmail   AlerterType = "email"
	AlerterTypeSlack   AlerterType = "slack"
	AlerterTypeWebhook AlerterType = "webhook"
)

type CPUCollector

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

CPUCollector collects CPU usage statistics

func NewCPUCollector

func NewCPUCollector() *CPUCollector

NewCPUCollector creates a new CPU collector

func (*CPUCollector) Collect

func (cc *CPUCollector) Collect(pluginName string) (*ResourceUsage, error)

Collect collects CPU usage for a plugin

func (*CPUCollector) GetResourceType

func (cc *CPUCollector) GetResourceType() ResourceType

GetResourceType returns the resource type

type ConnectionCollector

type ConnectionCollector struct{}

ConnectionCollector collects network connection statistics

func NewConnectionCollector

func NewConnectionCollector() *ConnectionCollector

NewConnectionCollector creates a new connection collector

func (*ConnectionCollector) Collect

func (cc *ConnectionCollector) Collect(pluginName string) (*ResourceUsage, error)

Collect collects connection count for a plugin

func (*ConnectionCollector) GetResourceType

func (cc *ConnectionCollector) GetResourceType() ResourceType

GetResourceType returns the resource type

type FileHandleCollector

type FileHandleCollector struct{}

FileHandleCollector collects file handle usage statistics

func NewFileHandleCollector

func NewFileHandleCollector() *FileHandleCollector

NewFileHandleCollector creates a new file handle collector

func (*FileHandleCollector) Collect

func (fhc *FileHandleCollector) Collect(pluginName string) (*ResourceUsage, error)

Collect collects file handle count for a plugin

func (*FileHandleCollector) GetResourceType

func (fhc *FileHandleCollector) GetResourceType() ResourceType

GetResourceType returns the resource type

type GoroutineCollector

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

GoroutineCollector collects goroutine count statistics

func NewGoroutineCollector

func NewGoroutineCollector() *GoroutineCollector

NewGoroutineCollector creates a new goroutine collector

func (*GoroutineCollector) Collect

func (gc *GoroutineCollector) Collect(pluginName string) (*ResourceUsage, error)

Collect collects goroutine count for a plugin

func (*GoroutineCollector) GetResourceType

func (gc *GoroutineCollector) GetResourceType() ResourceType

GetResourceType returns the resource type

type LogAlerter

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

LogAlerter sends alerts to the log

func NewLogAlerter

func NewLogAlerter() *LogAlerter

NewLogAlerter creates a new log alerter

func (*LogAlerter) GetAlerterType

func (la *LogAlerter) GetAlerterType() AlerterType

GetAlerterType returns the alerter type

func (*LogAlerter) SendAlert

func (la *LogAlerter) SendAlert(alert *Alert) error

SendAlert sends an alert to the log

type MemoryCollector

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

MemoryCollector collects memory usage statistics

func NewMemoryCollector

func NewMemoryCollector() *MemoryCollector

NewMemoryCollector creates a new memory collector

func (*MemoryCollector) Collect

func (mc *MemoryCollector) Collect(pluginName string) (*ResourceUsage, error)

Collect collects memory usage for a plugin

func (*MemoryCollector) GetResourceType

func (mc *MemoryCollector) GetResourceType() ResourceType

GetResourceType returns the resource type

type MonitorConfig

type MonitorConfig struct {
	CollectionInterval time.Duration            `json:"collection_interval"`
	AlertThresholds    map[ResourceType]float64 `json:"alert_thresholds"`
	RetentionPeriod    time.Duration            `json:"retention_period"`
	EnabledCollectors  []ResourceType           `json:"enabled_collectors"`
	AlertingEnabled    bool                     `json:"alerting_enabled"`
}

MonitorConfig contains monitoring configuration

func DefaultMonitorConfig

func DefaultMonitorConfig() *MonitorConfig

DefaultMonitorConfig returns a default monitoring configuration

type PluginMetrics

type PluginMetrics struct {
	PluginName      string                         `json:"plugin_name"`
	ResourceUsage   map[ResourceType]*UsageMetrics `json:"resource_usage"`
	ViolationCount  map[ResourceType]int           `json:"violation_count"`
	LastViolation   map[ResourceType]time.Time     `json:"last_violation"`
	TotalUptime     time.Duration                  `json:"total_uptime"`
	LastCollection  time.Time                      `json:"last_collection"`
	CollectionCount int64                          `json:"collection_count"`
	HealthScore     float64                        `json:"health_score"`
}

PluginMetrics contains metrics for a specific plugin

type PluginResourceTracker

type PluginResourceTracker struct {
	PluginName     string
	Limits         *ResourceLimits
	CurrentUsage   map[ResourceType]*ResourceUsage
	History        []*ResourceSnapshot
	Violations     []*ResourceViolation
	LastCollection time.Time
	// contains filtered or unexported fields
}

PluginResourceTracker tracks resources for a specific plugin

type RateLimit

type RateLimit struct {
	Window      time.Duration
	MaxAlerts   int
	AlertCount  int
	WindowStart time.Time
	// contains filtered or unexported fields
}

RateLimit tracks alert rate limiting

type ResourceCollector

type ResourceCollector interface {
	Collect(pluginName string) (*ResourceUsage, error)
	GetResourceType() ResourceType
}

ResourceCollector defines interface for collecting resource metrics

type ResourceLimitManager

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

ResourceLimitManager manages resource limits for plugins

func NewResourceLimitManager

func NewResourceLimitManager() *ResourceLimitManager

NewResourceLimitManager creates a new resource limit manager

func (*ResourceLimitManager) GetAllLimits

func (rlm *ResourceLimitManager) GetAllLimits() map[string]*ResourceLimits

GetAllLimits returns all configured limits

func (*ResourceLimitManager) GetLimits

func (rlm *ResourceLimitManager) GetLimits(pluginName string) (*ResourceLimits, bool)

GetLimits gets resource limits for a plugin

func (*ResourceLimitManager) RemoveLimits

func (rlm *ResourceLimitManager) RemoveLimits(pluginName string)

RemoveLimits removes resource limits for a plugin

func (*ResourceLimitManager) SetLimits

func (rlm *ResourceLimitManager) SetLimits(pluginName string, limits *ResourceLimits)

SetLimits sets resource limits for a plugin

type ResourceLimits

type ResourceLimits struct {
	MaxMemoryMB     int64   `json:"max_memory_mb"`
	MaxCPUPercent   float64 `json:"max_cpu_percent"`
	MaxGoroutines   int32   `json:"max_goroutines"`
	MaxFileHandles  int32   `json:"max_file_handles"`
	MaxConnections  int32   `json:"max_connections"`
	MaxDiskIOBPS    int64   `json:"max_disk_io_bps"`
	MaxNetworkIOBPS int64   `json:"max_network_io_bps"`
}

ResourceLimits defines resource limits for a plugin

func DefaultResourceLimits

func DefaultResourceLimits() *ResourceLimits

DefaultResourceLimits returns default resource limits

type ResourceMetrics

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

ResourceMetrics tracks and aggregates resource metrics

func NewResourceMetrics

func NewResourceMetrics() *ResourceMetrics

NewResourceMetrics creates a new resource metrics instance

func (*ResourceMetrics) GetAllPluginMetrics

func (rm *ResourceMetrics) GetAllPluginMetrics() map[string]*PluginMetrics

GetAllPluginMetrics returns metrics for all plugins

func (*ResourceMetrics) GetPluginMetrics

func (rm *ResourceMetrics) GetPluginMetrics(pluginName string) (*PluginMetrics, bool)

GetPluginMetrics returns metrics for a specific plugin

func (*ResourceMetrics) GetResourceSummary

func (rm *ResourceMetrics) GetResourceSummary() map[ResourceType]map[string]interface{}

GetResourceSummary returns a summary of resource usage across all plugins

func (*ResourceMetrics) GetSystemMetrics

func (rm *ResourceMetrics) GetSystemMetrics() *SystemMetrics

GetSystemMetrics returns system-wide metrics

func (*ResourceMetrics) RecordViolation

func (rm *ResourceMetrics) RecordViolation(pluginName string, resourceType ResourceType)

RecordViolation records a resource violation

func (*ResourceMetrics) UpdatePluginMetrics

func (rm *ResourceMetrics) UpdatePluginMetrics(pluginName string, usage map[ResourceType]*ResourceUsage)

UpdatePluginMetrics updates metrics for a plugin

type ResourceMonitor

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

ResourceMonitor tracks and limits plugin resource usage

func NewResourceMonitor

func NewResourceMonitor(config *MonitorConfig) *ResourceMonitor

NewResourceMonitor creates a new resource monitor

func (*ResourceMonitor) GetPluginUsage

func (rm *ResourceMonitor) GetPluginUsage(pluginName string) (map[ResourceType]*ResourceUsage, error)

GetPluginUsage returns current resource usage for a plugin

func (*ResourceMonitor) GetPluginViolations

func (rm *ResourceMonitor) GetPluginViolations(pluginName string) ([]*ResourceViolation, error)

GetPluginViolations returns resource violations for a plugin

func (*ResourceMonitor) GetSystemSummary

func (rm *ResourceMonitor) GetSystemSummary() map[string]interface{}

GetSystemSummary returns overall system resource summary

func (*ResourceMonitor) Start

func (rm *ResourceMonitor) Start(ctx context.Context) error

Start begins resource monitoring

func (*ResourceMonitor) Stop

func (rm *ResourceMonitor) Stop() error

Stop stops resource monitoring

func (*ResourceMonitor) TrackPlugin

func (rm *ResourceMonitor) TrackPlugin(pluginName string, limits *ResourceLimits) error

TrackPlugin starts tracking resources for a plugin

func (*ResourceMonitor) UntrackPlugin

func (rm *ResourceMonitor) UntrackPlugin(pluginName string) error

UntrackPlugin stops tracking a plugin

func (*ResourceMonitor) UpdatePluginLimits

func (rm *ResourceMonitor) UpdatePluginLimits(pluginName string, limits *ResourceLimits) error

UpdatePluginLimits updates resource limits for a plugin

type ResourceSnapshot

type ResourceSnapshot struct {
	Timestamp time.Time                       `json:"timestamp"`
	Usage     map[ResourceType]*ResourceUsage `json:"usage"`
}

ResourceSnapshot captures resource state at a point in time

type ResourceType

type ResourceType string

ResourceType represents different types of resources

const (
	ResourceTypeCPU         ResourceType = "cpu"
	ResourceTypeMemory      ResourceType = "memory"
	ResourceTypeGoroutines  ResourceType = "goroutines"
	ResourceTypeFileHandles ResourceType = "file_handles"
	ResourceTypeConnections ResourceType = "connections"
	ResourceTypeDiskIO      ResourceType = "disk_io"
	ResourceTypeNetworkIO   ResourceType = "network_io"
)

type ResourceUsage

type ResourceUsage struct {
	PluginName   string                 `json:"plugin_name"`
	ResourceType ResourceType           `json:"resource_type"`
	Current      float64                `json:"current"`
	Peak         float64                `json:"peak"`
	Average      float64                `json:"average"`
	Unit         string                 `json:"unit"`
	Timestamp    time.Time              `json:"timestamp"`
	Metadata     map[string]interface{} `json:"metadata"`
}

ResourceUsage represents current resource usage

type ResourceViolation

type ResourceViolation struct {
	PluginName   string       `json:"plugin_name"`
	ResourceType ResourceType `json:"resource_type"`
	Limit        float64      `json:"limit"`
	Actual       float64      `json:"actual"`
	Timestamp    time.Time    `json:"timestamp"`
	Severity     Severity     `json:"severity"`
	Action       string       `json:"action"`
}

ResourceViolation represents a resource limit violation

type Severity

type Severity string

Severity levels for violations

const (
	SeverityInfo     Severity = "info"
	SeverityWarning  Severity = "warning"
	SeverityError    Severity = "error"
	SeverityCritical Severity = "critical"
)

type SystemMetrics

type SystemMetrics struct {
	TotalPlugins    int                            `json:"total_plugins"`
	ActivePlugins   int                            `json:"active_plugins"`
	TotalViolations int                            `json:"total_violations"`
	SystemResources map[ResourceType]*UsageMetrics `json:"system_resources"`
	AlertsGenerated int64                          `json:"alerts_generated"`
	LastUpdate      time.Time                      `json:"last_update"`
	UptimeSeconds   float64                        `json:"uptime_seconds"`
}

SystemMetrics contains system-wide resource metrics

type TrendDirection

type TrendDirection string

TrendDirection indicates the trend of resource usage

const (
	TrendIncreasing TrendDirection = "increasing"
	TrendDecreasing TrendDirection = "decreasing"
	TrendStable     TrendDirection = "stable"
	TrendVolatile   TrendDirection = "volatile"
)

type UsageMetrics

type UsageMetrics struct {
	Current    float64        `json:"current"`
	Peak       float64        `json:"peak"`
	Average    float64        `json:"average"`
	Minimum    float64        `json:"minimum"`
	Samples    int64          `json:"samples"`
	LastUpdate time.Time      `json:"last_update"`
	Trend      TrendDirection `json:"trend"`
	History    []float64      `json:"history,omitempty"`
}

UsageMetrics contains detailed usage statistics

type WebhookAlerter

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

WebhookAlerter sends alerts to a webhook endpoint

func NewWebhookAlerter

func NewWebhookAlerter(url string, timeout time.Duration) *WebhookAlerter

NewWebhookAlerter creates a new webhook alerter

func (*WebhookAlerter) GetAlerterType

func (wa *WebhookAlerter) GetAlerterType() AlerterType

GetAlerterType returns the alerter type

func (*WebhookAlerter) SendAlert

func (wa *WebhookAlerter) SendAlert(alert *Alert) error

SendAlert sends an alert to a webhook

Jump to

Keyboard shortcuts

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