k8s

package
v1.68.3 Latest Latest
Warning

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

Go to latest
Published: Mar 8, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Overview

* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT

* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT

* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT

* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT

* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT

* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT

* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT

* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GlobMatch added in v1.57.0

func GlobMatch(pattern, s string) bool

GlobMatch matches a simple glob pattern with * wildcards.

func MatchesAnyFilter added in v1.57.0

func MatchesAnyFilter(name string, filters []string) bool

MatchesAnyFilter returns true if name matches at least one glob pattern.

func ParseMetricLine added in v1.57.0

func ParseMetricLine(line string) (name string, value float64, ok bool)

ParseMetricLine parses a single Prometheus metric line. Format: metric_name{labels} value [timestamp] or: metric_name value [timestamp]

func ParsePrometheusText added in v1.57.0

func ParsePrometheusText(reader io.Reader, filters []string) map[string]float64

ParsePrometheusText parses the Prometheus text exposition format. It extracts metric lines matching the filter patterns (empty filters = accept all).

Types

type Alert

type Alert struct {
	Timestamp time.Time
	Severity  AlertSeverity
	Type      AlertType
	Message   string
	Object    string // affected resource
}

Alert represents an anomaly detected by the watcher.

type AlertSeverity

type AlertSeverity string

AlertSeverity indicates the severity level of an alert.

const (
	SeverityInfo     AlertSeverity = "INFO"
	SeverityWarning  AlertSeverity = "WARNING"
	SeverityCritical AlertSeverity = "CRITICAL"
)

type AlertType

type AlertType string

AlertType categorizes the type of anomaly detected.

const (
	AlertPodCrashLoop  AlertType = "CrashLoopBackOff"
	AlertPodOOMKilled  AlertType = "OOMKilled"
	AlertHighRestarts  AlertType = "HighRestartCount"
	AlertPodNotReady   AlertType = "PodNotReady"
	AlertScaleEvent    AlertType = "ScaleEvent"
	AlertDeployFailing AlertType = "DeploymentFailing"
)

type AppMetrics added in v1.57.0

type AppMetrics struct {
	Timestamp time.Time
	Metrics   map[string]float64 // metric_name -> value
}

AppMetrics holds application-level metrics scraped from Prometheus endpoints.

type DeploymentCollector

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

DeploymentCollector collects deployment status and pod information.

func NewDeploymentCollector

func NewDeploymentCollector(clientset kubernetes.Interface, namespace, deployment string, logger *zap.Logger) *DeploymentCollector

NewDeploymentCollector creates a collector for deployment and pod status.

func (*DeploymentCollector) Collect

Collect gathers deployment status and pod information.

type DeploymentStatus

type DeploymentStatus struct {
	Name              string
	Namespace         string
	Replicas          int32
	ReadyReplicas     int32
	UpdatedReplicas   int32
	AvailableReplicas int32
	Conditions        []string // human-readable condition summaries
	Strategy          string
}

DeploymentStatus holds deployment-level information.

type EventCollector

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

EventCollector collects Kubernetes events related to the deployment.

func NewEventCollector

func NewEventCollector(clientset kubernetes.Interface, namespace, deployment string, logger *zap.Logger) *EventCollector

NewEventCollector creates an event collector.

func (*EventCollector) Collect

func (c *EventCollector) Collect(ctx context.Context) ([]K8sEvent, error)

Collect gathers recent events for the deployment and its pods.

type HPACollector

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

HPACollector collects HorizontalPodAutoscaler status.

func NewHPACollector

func NewHPACollector(clientset kubernetes.Interface, namespace, deployment string, logger *zap.Logger) *HPACollector

NewHPACollector creates an HPA collector.

func (*HPACollector) Collect

func (c *HPACollector) Collect(ctx context.Context) (*HPAStatus, error)

Collect gathers HPA status if one exists for the deployment.

type HPAStatus

type HPAStatus struct {
	Name            string
	MinReplicas     int32
	MaxReplicas     int32
	CurrentReplicas int32
	DesiredReplicas int32
	CurrentMetrics  []string // human-readable metric summaries
}

HPAStatus holds HorizontalPodAutoscaler information.

type K8sEvent

type K8sEvent struct {
	Timestamp time.Time
	Type      string // Normal, Warning
	Reason    string
	Message   string
	Object    string // e.g., "Pod/myapp-xyz"
	Count     int32
}

K8sEvent represents a Kubernetes event related to the monitored resources.

type LogCollector

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

LogCollector collects recent logs from pods.

func NewLogCollector

func NewLogCollector(clientset kubernetes.Interface, namespace, deployment string, maxLines int, logger *zap.Logger) *LogCollector

NewLogCollector creates a log collector.

func (*LogCollector) Collect

func (c *LogCollector) Collect(ctx context.Context) ([]LogEntry, error)

Collect gathers recent logs from all pods of the deployment.

type LogEntry

type LogEntry struct {
	Timestamp time.Time
	PodName   string
	Container string
	Line      string
	IsError   bool
}

LogEntry holds a log line from a pod.

type MetricsCollector

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

MetricsCollector collects resource usage metrics from metrics-server.

func NewMetricsCollector

func NewMetricsCollector(clientset kubernetes.Interface, metricsClient metricsv.Interface, namespace, deployment string, logger *zap.Logger) *MetricsCollector

NewMetricsCollector creates a metrics collector.

func (*MetricsCollector) Collect

func (c *MetricsCollector) Collect(ctx context.Context, pods []PodStatus) []PodStatus

Collect gathers CPU/memory usage for deployment pods.

type MultiSummarizer added in v1.57.0

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

MultiSummarizer generates budget-constrained context from multiple watch targets.

func NewMultiSummarizer added in v1.57.0

func NewMultiSummarizer(stores map[string]*ObservabilityStore, maxChars int) *MultiSummarizer

NewMultiSummarizer creates a summarizer for multi-deployment watching.

func (*MultiSummarizer) GenerateContext added in v1.57.0

func (ms *MultiSummarizer) GenerateContext() string

GenerateContext produces a budget-constrained context block for all targets. Unhealthy targets get detailed context, healthy targets get compact one-liners. If total exceeds maxChars, progressively compresses from the healthiest targets.

func (*MultiSummarizer) GenerateStatusSummary added in v1.57.0

func (ms *MultiSummarizer) GenerateStatusSummary() string

GenerateStatusSummary produces a multi-target compact status line.

type MultiWatchConfig added in v1.57.0

type MultiWatchConfig struct {
	Targets         []WatchTarget `yaml:"targets" json:"targets"`
	Interval        time.Duration `yaml:"interval" json:"interval"`
	Window          time.Duration `yaml:"window" json:"window"`
	MaxLogLines     int           `yaml:"maxLogLines" json:"maxLogLines"`
	Kubeconfig      string        `yaml:"kubeconfig,omitempty" json:"kubeconfig,omitempty"`
	MaxContextChars int           `yaml:"maxContextChars,omitempty" json:"maxContextChars,omitempty"`
}

MultiWatchConfig holds configuration for multi-deployment watching.

func LoadMultiWatchConfig added in v1.57.0

func LoadMultiWatchConfig(path string) (*MultiWatchConfig, error)

LoadMultiWatchConfig loads a MultiWatchConfig from a YAML file.

func SingleTargetToMulti added in v1.57.0

func SingleTargetToMulti(cfg WatchConfig) MultiWatchConfig

SingleTargetToMulti converts a legacy single-target WatchConfig to a MultiWatchConfig.

type MultiWatcher added in v1.57.0

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

MultiWatcher manages multiple ResourceWatchers sharing a single K8s clientset.

func NewMultiWatcher added in v1.57.0

func NewMultiWatcher(cfg MultiWatchConfig, logger *zap.Logger) (*MultiWatcher, error)

NewMultiWatcher creates watchers for all targets in the config.

func (*MultiWatcher) GetStores added in v1.57.0

func (mw *MultiWatcher) GetStores() map[string]*ObservabilityStore

GetStores returns all stores keyed by target.

func (*MultiWatcher) SetMetrics added in v1.57.1

func (mw *MultiWatcher) SetMetrics(recorder WatcherMetricsRecorder)

SetMetrics sets the metrics recorder on all managed watchers.

func (*MultiWatcher) Start added in v1.57.0

func (mw *MultiWatcher) Start(ctx context.Context) error

Start launches all watchers in parallel goroutines. Blocks until ctx is cancelled.

func (*MultiWatcher) TargetCount added in v1.57.0

func (mw *MultiWatcher) TargetCount() int

TargetCount returns the number of watch targets.

type ObservabilityStore

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

ObservabilityStore stores collected observability data with a fixed-size ring buffer.

func NewObservabilityStore

func NewObservabilityStore(maxSnapshots, maxLogs int, window time.Duration) *ObservabilityStore

NewObservabilityStore creates a new store with the given capacity.

func (*ObservabilityStore) AddAlert

func (s *ObservabilityStore) AddAlert(alert Alert)

AddAlert adds an alert to the store. Duplicates (same Type+Object) are skipped to prevent alert accumulation from repeated poll cycles detecting the same condition.

func (*ObservabilityStore) AddLogs

func (s *ObservabilityStore) AddLogs(entries []LogEntry)

AddLogs adds log entries to the store.

func (*ObservabilityStore) AddSnapshot

func (s *ObservabilityStore) AddSnapshot(snap ResourceSnapshot)

AddSnapshot adds a resource snapshot to the store.

func (*ObservabilityStore) GetAlerts

func (s *ObservabilityStore) GetAlerts() []Alert

GetAlerts returns all active alerts within the observation window.

func (*ObservabilityStore) GetErrorLogs

func (s *ObservabilityStore) GetErrorLogs(maxLines int) []LogEntry

GetErrorLogs returns only error log entries within the window.

func (*ObservabilityStore) GetRecentLogs

func (s *ObservabilityStore) GetRecentLogs(maxLines int) []LogEntry

GetRecentLogs returns the most recent log entries (up to maxLines).

func (*ObservabilityStore) GetRestartTrend

func (s *ObservabilityStore) GetRestartTrend() (totalRestarts int32, restartsInWindow int32)

GetRestartTrend returns the total restart count over time from snapshots.

func (*ObservabilityStore) GetSnapshots

func (s *ObservabilityStore) GetSnapshots() []ResourceSnapshot

GetSnapshots returns all snapshots within the observation window.

func (*ObservabilityStore) LatestSnapshot

func (s *ObservabilityStore) LatestSnapshot() (ResourceSnapshot, bool)

LatestSnapshot returns the most recent snapshot, if any.

func (*ObservabilityStore) Stats

func (s *ObservabilityStore) Stats() StoreStats

Stats returns summary statistics for display.

type PodStatus

type PodStatus struct {
	Name           string
	Phase          string // Running, Pending, Failed, etc.
	Ready          bool
	RestartCount   int32
	ContainerCount int
	ReadyCount     int
	StartTime      *time.Time
	Conditions     []string
	CPUUsage       string // e.g., "45m" (millicores)
	MemoryUsage    string // e.g., "120Mi"
	LastTerminated *TerminationInfo
}

PodStatus holds pod-level information.

type PrometheusCollector added in v1.57.0

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

PrometheusCollector scrapes /metrics endpoints from pods of a deployment.

func NewPrometheusCollector added in v1.57.0

func NewPrometheusCollector(
	clientset kubernetes.Interface,
	namespace, deployment string,
	port int, path string,
	filters []string,
	logger *zap.Logger,
) *PrometheusCollector

NewPrometheusCollector creates a collector for application-level Prometheus metrics.

func (*PrometheusCollector) Collect added in v1.57.0

func (c *PrometheusCollector) Collect(ctx context.Context) *AppMetrics

Collect scrapes metrics from the first Ready pod and returns AppMetrics.

type ResourceSnapshot

type ResourceSnapshot struct {
	Timestamp  time.Time
	Deployment DeploymentStatus
	Pods       []PodStatus
	Events     []K8sEvent
	HPA        *HPAStatus
	AppMetrics *AppMetrics // application-level Prometheus metrics (nil if not configured)
}

ResourceSnapshot captures the state of monitored resources at a point in time.

type ResourceWatcher

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

ResourceWatcher monitors Kubernetes resources and collects observability data.

func NewResourceWatcher

func NewResourceWatcher(cfg WatchConfig, logger *zap.Logger) (*ResourceWatcher, error)

NewResourceWatcher creates a new watcher for the given deployment.

func (*ResourceWatcher) GetStore

func (w *ResourceWatcher) GetStore() *ObservabilityStore

GetStore returns the observability store for reading data.

func (*ResourceWatcher) Start

func (w *ResourceWatcher) Start(ctx context.Context) error

Start begins the watch loop, collecting data at the configured interval. It blocks until the context is cancelled.

type StoreStats

type StoreStats struct {
	SnapshotCount int
	LogCount      int
	AlertCount    int
}

StoreStats holds store statistics.

type Summarizer

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

Summarizer generates text summaries of the observability data for LLM context injection.

func NewSummarizer

func NewSummarizer(store *ObservabilityStore) *Summarizer

NewSummarizer creates a new summarizer.

func (*Summarizer) GenerateContext

func (s *Summarizer) GenerateContext() string

GenerateContext creates a text block to prepend to LLM prompts. This gives the AI full context about the monitored Kubernetes resources.

func (*Summarizer) GenerateStatusSummary

func (s *Summarizer) GenerateStatusSummary() string

GenerateStatusSummary creates a compact status line for display.

type TargetHealthScore added in v1.57.0

type TargetHealthScore struct {
	Key        string
	Score      int // 0 = healthy, 1 = warning, 2 = critical
	AlertCount int
}

TargetHealthScore represents the health status of a watch target for budget allocation.

type TerminationInfo

type TerminationInfo struct {
	Reason    string
	ExitCode  int32
	StartedAt time.Time
	EndedAt   time.Time
}

TerminationInfo holds info about the last container termination.

type WatchConfig

type WatchConfig struct {
	Deployment  string
	Namespace   string
	Interval    time.Duration
	Window      time.Duration
	MaxLogLines int
	Kubeconfig  string // path to kubeconfig (empty = in-cluster)
}

WatchConfig holds configuration for the Kubernetes watcher.

type WatchTarget added in v1.57.0

type WatchTarget struct {
	Deployment    string   `yaml:"deployment" json:"deployment"`
	Namespace     string   `yaml:"namespace" json:"namespace"`
	MetricsPort   int      `yaml:"metricsPort,omitempty" json:"metricsPort,omitempty"`
	MetricsPath   string   `yaml:"metricsPath,omitempty" json:"metricsPath,omitempty"`
	MetricsFilter []string `yaml:"metricsFilter,omitempty" json:"metricsFilter,omitempty"`
}

WatchTarget defines a single deployment to watch with optional Prometheus scraping.

func (WatchTarget) Key added in v1.57.0

func (t WatchTarget) Key() string

Key returns a unique identifier for this target: "namespace/deployment".

type WatcherMetricsRecorder added in v1.57.1

type WatcherMetricsRecorder interface {
	ObserveCollectionDuration(target string, seconds float64)
	IncrementCollectionErrors(target string)
	IncrementAlert(target, severity, alertType string)
	SetPodsReady(namespace, deployment string, count float64)
	SetPodsDesired(namespace, deployment string, count float64)
	SetSnapshotsStored(target string, count float64)
	SetPodRestarts(target string, count float64)
}

WatcherMetricsRecorder is the interface for recording watcher metrics. Implemented by metrics.WatcherMetrics to avoid circular imports.

Jump to

Keyboard shortcuts

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