|
| 1 | +/* |
| 2 | +Copyright (c) Microsoft Corporation. |
| 3 | +Licensed under the MIT license. |
| 4 | +*/ |
| 5 | + |
| 6 | +package podmetrics |
| 7 | + |
| 8 | +import ( |
| 9 | + "context" |
| 10 | + "fmt" |
| 11 | + "slices" |
| 12 | + "strings" |
| 13 | + "sync" |
| 14 | + "time" |
| 15 | + |
| 16 | + "github.com/go-logr/logr" |
| 17 | + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 18 | + "k8s.io/client-go/rest" |
| 19 | + metricsv1beta1 "k8s.io/metrics/pkg/apis/metrics/v1beta1" |
| 20 | + metricsclient "k8s.io/metrics/pkg/client/clientset/versioned" |
| 21 | +) |
| 22 | + |
| 23 | +const ( |
| 24 | + // DefaultNamespace is the namespace where ASO controller pods run. |
| 25 | + DefaultNamespace = "azureserviceoperator-system" |
| 26 | + |
| 27 | + // DefaultPodPrefix is the prefix of the ASO controller pod name. |
| 28 | + DefaultPodPrefix = "azureserviceoperator-controller-manager" |
| 29 | + |
| 30 | + // DefaultInterval is how frequently to poll for pod metrics. |
| 31 | + DefaultInterval = 5 * time.Second |
| 32 | +) |
| 33 | + |
| 34 | +// CollectorConfig holds configuration for a MetricsCollector. |
| 35 | +type CollectorConfig struct { |
| 36 | + // Namespace is the Kubernetes namespace to monitor. |
| 37 | + Namespace string |
| 38 | + |
| 39 | + // PodPrefix filters pods whose names start with this prefix. |
| 40 | + PodPrefix string |
| 41 | + |
| 42 | + // Interval is how often to poll the metrics API. |
| 43 | + Interval time.Duration |
| 44 | +} |
| 45 | + |
| 46 | +// MetricsCollector polls the Kubernetes metrics API at a regular interval and stores samples. |
| 47 | +type MetricsCollector struct { |
| 48 | + client metricsclient.Interface |
| 49 | + namespace string |
| 50 | + podPrefix string |
| 51 | + interval time.Duration |
| 52 | + |
| 53 | + mu sync.Mutex |
| 54 | + samples []Sample |
| 55 | + start time.Time |
| 56 | + |
| 57 | + cancel context.CancelFunc |
| 58 | + done chan struct{} |
| 59 | +} |
| 60 | + |
| 61 | +// NewMetricsCollector creates a MetricsCollector that polls pod metrics from the given cluster. |
| 62 | +// It targets pods in the specified namespace whose names start with podPrefix. |
| 63 | +func NewMetricsCollector(cfg *rest.Config, collectorCfg CollectorConfig) (*MetricsCollector, error) { |
| 64 | + mc, err := metricsclient.NewForConfig(cfg) |
| 65 | + if err != nil { |
| 66 | + return nil, fmt.Errorf("creating metrics client: %w", err) |
| 67 | + } |
| 68 | + |
| 69 | + namespace := collectorCfg.Namespace |
| 70 | + if namespace == "" { |
| 71 | + namespace = DefaultNamespace |
| 72 | + } |
| 73 | + |
| 74 | + podPrefix := collectorCfg.PodPrefix |
| 75 | + if podPrefix == "" { |
| 76 | + podPrefix = DefaultPodPrefix |
| 77 | + } |
| 78 | + |
| 79 | + interval := collectorCfg.Interval |
| 80 | + if interval <= 0 { |
| 81 | + interval = DefaultInterval |
| 82 | + } |
| 83 | + |
| 84 | + return &MetricsCollector{ |
| 85 | + client: mc, |
| 86 | + namespace: namespace, |
| 87 | + podPrefix: podPrefix, |
| 88 | + interval: interval, |
| 89 | + }, nil |
| 90 | +} |
| 91 | + |
| 92 | +// CheckAvailable probes the metrics API to verify that metrics-server is reachable. |
| 93 | +// Returns an error if the metrics API is not available. |
| 94 | +func (mc *MetricsCollector) CheckAvailable(ctx context.Context) error { |
| 95 | + _, err := mc.client.MetricsV1beta1().PodMetricses(mc.namespace).List(ctx, metav1.ListOptions{Limit: 1}) |
| 96 | + if err != nil { |
| 97 | + return fmt.Errorf("metrics-server not available in namespace %q: %w", mc.namespace, err) |
| 98 | + } |
| 99 | + return nil |
| 100 | +} |
| 101 | + |
| 102 | +// Start begins collecting metrics in a background goroutine. |
| 103 | +// Call Stop to end collection. |
| 104 | +func (mc *MetricsCollector) Start(log logr.Logger) { |
| 105 | + mc.mu.Lock() |
| 106 | + mc.start = time.Now() |
| 107 | + mc.samples = nil |
| 108 | + mc.mu.Unlock() |
| 109 | + |
| 110 | + ctx, cancel := context.WithCancel(context.Background()) |
| 111 | + mc.cancel = cancel |
| 112 | + mc.done = make(chan struct{}) |
| 113 | + |
| 114 | + go func() { |
| 115 | + defer close(mc.done) |
| 116 | + ticker := time.NewTicker(mc.interval) |
| 117 | + defer ticker.Stop() |
| 118 | + |
| 119 | + for { |
| 120 | + select { |
| 121 | + case <-ctx.Done(): |
| 122 | + return |
| 123 | + case <-ticker.C: |
| 124 | + if err := mc.collect(ctx); err != nil { |
| 125 | + log.Error(err, "metrics collection error") |
| 126 | + } |
| 127 | + } |
| 128 | + } |
| 129 | + }() |
| 130 | + |
| 131 | + log.Info("Metrics collector started", |
| 132 | + "namespace", mc.namespace, |
| 133 | + "podPrefix", mc.podPrefix, |
| 134 | + "interval", mc.interval) |
| 135 | +} |
| 136 | + |
| 137 | +// Stop ends metrics collection and waits for the collector goroutine to exit. |
| 138 | +func (mc *MetricsCollector) Stop() { |
| 139 | + if mc.cancel != nil { |
| 140 | + mc.cancel() |
| 141 | + <-mc.done |
| 142 | + } |
| 143 | +} |
| 144 | + |
| 145 | +// Samples returns a copy of all collected samples. |
| 146 | +func (mc *MetricsCollector) Samples() []Sample { |
| 147 | + mc.mu.Lock() |
| 148 | + defer mc.mu.Unlock() |
| 149 | + result := slices.Clone(mc.samples) |
| 150 | + return result |
| 151 | +} |
| 152 | + |
| 153 | +// collect performs a single metrics API poll and stores the results. |
| 154 | +func (mc *MetricsCollector) collect(ctx context.Context) error { |
| 155 | + podMetricsList, err := mc.client.MetricsV1beta1().PodMetricses(mc.namespace).List(ctx, metav1.ListOptions{}) |
| 156 | + if err != nil { |
| 157 | + return fmt.Errorf("listing pod metrics: %w", err) |
| 158 | + } |
| 159 | + |
| 160 | + now := time.Now() |
| 161 | + mc.mu.Lock() |
| 162 | + defer mc.mu.Unlock() |
| 163 | + |
| 164 | + for i := range podMetricsList.Items { |
| 165 | + pod := &podMetricsList.Items[i] |
| 166 | + if !strings.HasPrefix(pod.Name, mc.podPrefix) { |
| 167 | + continue |
| 168 | + } |
| 169 | + |
| 170 | + mc.collectPodContainers(pod, now) |
| 171 | + } |
| 172 | + |
| 173 | + return nil |
| 174 | +} |
| 175 | + |
| 176 | +// collectPodContainers extracts metrics from each container in a pod. |
| 177 | +func (mc *MetricsCollector) collectPodContainers(pod *metricsv1beta1.PodMetrics, now time.Time) { |
| 178 | + for i := range pod.Containers { |
| 179 | + container := &pod.Containers[i] |
| 180 | + |
| 181 | + cpuMillis := container.Usage.Cpu().MilliValue() |
| 182 | + memBytes := container.Usage.Memory().Value() |
| 183 | + |
| 184 | + sample := Sample{ |
| 185 | + Timestamp: now, |
| 186 | + Elapsed: now.Sub(mc.start), |
| 187 | + PodName: pod.Name, |
| 188 | + ContainerName: container.Name, |
| 189 | + CPUMillicores: float64(cpuMillis), |
| 190 | + MemoryBytes: memBytes, |
| 191 | + } |
| 192 | + mc.samples = append(mc.samples, sample) |
| 193 | + } |
| 194 | +} |
0 commit comments