feat: Wrap all Kubernetes API operations with circuit breaker protection and improve error handling

- Add strings import to kubernetes.go
- Wrap ListDeployments with circuitBreaker.Execute and move result building inside closure
- Wrap GetDeployment with circuitBreaker.Execute and move result assignment inside closure
- Wrap ScaleDeployment with circuitBreaker.Execute and simplify error messages
- Wrap RestartDeployment with circuitBreaker.Execute
- Wrap PodLogs with circuitBreaker.Execute and add streaming
This commit is contained in:
nutcas3
2026-04-25 06:12:40 +03:00
parent 12513943cc
commit 653f23ff24
+103 -57
View File
@@ -5,6 +5,7 @@ import (
"fmt" "fmt"
"os" "os"
"path/filepath" "path/filepath"
"strings"
"time" "time"
corev1 "k8s.io/api/core/v1" corev1 "k8s.io/api/core/v1"
@@ -111,12 +112,13 @@ type Deployment struct {
// ListDeployments returns all deployments in the configured namespace // ListDeployments returns all deployments in the configured namespace
func (k *KubernetesService) ListDeployments(ctx context.Context) ([]Deployment, error) { func (k *KubernetesService) ListDeployments(ctx context.Context) ([]Deployment, error) {
var result []Deployment
err := k.circuitBreaker.Execute(func() error {
deployments, err := k.clientset.AppsV1().Deployments(k.namespace).List(ctx, metav1.ListOptions{}) deployments, err := k.clientset.AppsV1().Deployments(k.namespace).List(ctx, metav1.ListOptions{})
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to list deployments: %w", err) return fmt.Errorf("failed to list deployments: %w", err)
} }
var result []Deployment
for _, d := range deployments.Items { for _, d := range deployments.Items {
result = append(result, Deployment{ result = append(result, Deployment{
Name: d.Name, Name: d.Name,
@@ -130,18 +132,25 @@ func (k *KubernetesService) ListDeployments(ctx context.Context) ([]Deployment,
UnavailableReplicas: d.Status.UnavailableReplicas, UnavailableReplicas: d.Status.UnavailableReplicas,
}) })
} }
return nil
})
if err != nil {
return nil, err
}
return result, nil return result, nil
} }
// GetDeployment returns a specific deployment by name // GetDeployment returns a specific deployment by name
func (k *KubernetesService) GetDeployment(ctx context.Context, name string) (*Deployment, error) { func (k *KubernetesService) GetDeployment(ctx context.Context, name string) (*Deployment, error) {
var result *Deployment
err := k.circuitBreaker.Execute(func() error {
deployment, err := k.clientset.AppsV1().Deployments(k.namespace).Get(ctx, name, metav1.GetOptions{}) deployment, err := k.clientset.AppsV1().Deployments(k.namespace).Get(ctx, name, metav1.GetOptions{})
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to get deployment %s: %w", name, err) return fmt.Errorf("failed to get deployment %s: %w", name, err)
} }
return &Deployment{ result = &Deployment{
Name: deployment.Name, Name: deployment.Name,
Namespace: deployment.Namespace, Namespace: deployment.Namespace,
CreationTimestamp: deployment.CreationTimestamp.Time, CreationTimestamp: deployment.CreationTimestamp.Time,
@@ -151,7 +160,14 @@ func (k *KubernetesService) GetDeployment(ctx context.Context, name string) (*De
AvailableReplicas: deployment.Status.AvailableReplicas, AvailableReplicas: deployment.Status.AvailableReplicas,
UpdatedReplicas: deployment.Status.UpdatedReplicas, UpdatedReplicas: deployment.Status.UpdatedReplicas,
UnavailableReplicas: deployment.Status.UnavailableReplicas, UnavailableReplicas: deployment.Status.UnavailableReplicas,
}, nil }
return nil
})
if err != nil {
return nil, err
}
return result, nil
} }
// ScaleDeployment updates the replica count for a deployment // ScaleDeployment updates the replica count for a deployment
@@ -160,24 +176,26 @@ func (k *KubernetesService) ScaleDeployment(ctx context.Context, name string, re
return fmt.Errorf("replica count %d is out of valid range [0, 100]", replicas) return fmt.Errorf("replica count %d is out of valid range [0, 100]", replicas)
} }
return k.circuitBreaker.Execute(func() error {
// Get current deployment // Get current deployment
deployment, err := k.clientset.AppsV1().Deployments(k.namespace).Get(ctx, name, metav1.GetOptions{}) deployment, err := k.clientset.AppsV1().Deployments(k.namespace).Get(ctx, name, metav1.GetOptions{})
if err != nil { if err != nil {
return fmt.Errorf("failed to get deployment %s for scaling: %w", name, err) return fmt.Errorf("failed to get deployment %s: %w", name, err)
} }
// Update replica count // Update replicas
deployment.Spec.Replicas = &replicas deployment.Spec.Replicas = &replicas
_, err = k.clientset.AppsV1().Deployments(k.namespace).Update(ctx, deployment, metav1.UpdateOptions{}) _, err = k.clientset.AppsV1().Deployments(k.namespace).Update(ctx, deployment, metav1.UpdateOptions{})
if err != nil { if err != nil {
return fmt.Errorf("failed to scale deployment %s to %d replicas: %w", name, replicas, err) return fmt.Errorf("failed to scale deployment %s: %w", name, err)
} }
return nil return nil
})
} }
// RestartDeployment triggers a rolling restart by updating the pod template annotation // RestartDeployment restarts a deployment by rolling its pods
func (k *KubernetesService) RestartDeployment(ctx context.Context, name string) error { func (k *KubernetesService) RestartDeployment(ctx context.Context, name string) error {
return k.circuitBreaker.Execute(func() error {
deployment, err := k.clientset.AppsV1().Deployments(k.namespace).Get(ctx, name, metav1.GetOptions{}) deployment, err := k.clientset.AppsV1().Deployments(k.namespace).Get(ctx, name, metav1.GetOptions{})
if err != nil { if err != nil {
return fmt.Errorf("failed to get deployment %s for restart: %w", name, err) return fmt.Errorf("failed to get deployment %s for restart: %w", name, err)
@@ -195,14 +213,17 @@ func (k *KubernetesService) RestartDeployment(ctx context.Context, name string)
} }
return nil return nil
})
} }
// PodLogs fetches recent logs from pods matching the deployment's label selector // PodLogs fetches recent logs from pods matching the deployment's label selector
func (k *KubernetesService) PodLogs(ctx context.Context, name string, tailLines int) (string, error) { func (k *KubernetesService) PodLogs(ctx context.Context, name string, tailLines int) (string, error) {
var result string
err := k.circuitBreaker.Execute(func() error {
// Get deployment to find label selector // Get deployment to find label selector
deployment, err := k.clientset.AppsV1().Deployments(k.namespace).Get(ctx, name, metav1.GetOptions{}) deployment, err := k.clientset.AppsV1().Deployments(k.namespace).Get(ctx, name, metav1.GetOptions{})
if err != nil { if err != nil {
return "", fmt.Errorf("failed to get deployment %s for logs: %w", name, err) return fmt.Errorf("failed to get deployment %s for logs: %w", name, err)
} }
// Find pods using deployment's label selector // Find pods using deployment's label selector
@@ -211,11 +232,11 @@ func (k *KubernetesService) PodLogs(ctx context.Context, name string, tailLines
LabelSelector: labelSelector.String(), LabelSelector: labelSelector.String(),
}) })
if err != nil { if err != nil {
return "", fmt.Errorf("failed to list pods for deployment %s: %w", name, err) return fmt.Errorf("failed to list pods for deployment %s: %w", name, err)
} }
if len(pods.Items) == 0 { if len(pods.Items) == 0 {
return "", fmt.Errorf("no pods found for deployment %s", name) return fmt.Errorf("no pods found for deployment %s", name)
} }
// Get logs from the first running pod // Get logs from the first running pod
@@ -226,41 +247,47 @@ func (k *KubernetesService) PodLogs(ctx context.Context, name string, tailLines
break break
} }
} }
if pod == nil { if pod == nil {
// If no running pod, use the first one return fmt.Errorf("no running pods found for deployment %s", name)
pod = &pods.Items[0]
} }
if tailLines <= 0 {
tailLines = 100
}
tailLines64 := int64(tailLines)
req := k.clientset.CoreV1().Pods(k.namespace).GetLogs(pod.Name, &corev1.PodLogOptions{ req := k.clientset.CoreV1().Pods(k.namespace).GetLogs(pod.Name, &corev1.PodLogOptions{
TailLines: &tailLines64, TailLines: func(i int64) *int64 { return &i }(int64(tailLines)),
Follow: false,
}) })
logs, err := req.Stream(ctx) logData, err := req.Stream(ctx)
if err != nil { if err != nil {
return "", fmt.Errorf("failed to get logs for pod %s: %w", pod.Name, err) return fmt.Errorf("failed to stream logs from pod %s: %w", pod.Name, err)
} }
defer logs.Close() defer logData.Close()
data := make([]byte, 1024*1024) // 1MB limit buf := make([]byte, 1024)
n, err := logs.Read(data) var logs strings.Builder
if err != nil && err.Error() != "EOF" { for {
return "", fmt.Errorf("failed to read logs: %w", err) n, err := logData.Read(buf)
if err != nil {
break
} }
logs.WriteString(string(buf[:n]))
}
result = logs.String()
return nil
})
return string(data[:n]), nil if err != nil {
return "", err
}
return result, nil
} }
// GetPodStatus returns detailed pod status for a deployment // GetPodStatus returns detailed pod status for a deployment
func (k *KubernetesService) GetPodStatus(ctx context.Context, name string) (map[string]any, error) { func (k *KubernetesService) GetPodStatus(ctx context.Context, name string) (map[string]any, error) {
var result map[string]any
err := k.circuitBreaker.Execute(func() error {
deployment, err := k.clientset.AppsV1().Deployments(k.namespace).Get(ctx, name, metav1.GetOptions{}) deployment, err := k.clientset.AppsV1().Deployments(k.namespace).Get(ctx, name, metav1.GetOptions{})
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to get deployment %s: %w", name, err) return fmt.Errorf("failed to get deployment %s: %w", name, err)
} }
labelSelector := labels.Set(deployment.Spec.Selector.MatchLabels).AsSelector() labelSelector := labels.Set(deployment.Spec.Selector.MatchLabels).AsSelector()
@@ -268,54 +295,68 @@ func (k *KubernetesService) GetPodStatus(ctx context.Context, name string) (map[
LabelSelector: labelSelector.String(), LabelSelector: labelSelector.String(),
}) })
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to list pods for deployment %s: %w", name, err) return fmt.Errorf("failed to list pods for deployment %s: %w", name, err)
} }
status := map[string]any{ // Build response with deployment replica info and pod details
podList := make([]map[string]any, 0, len(pods.Items))
for _, pod := range pods.Items {
conditions := make([]map[string]string, 0, len(pod.Status.Conditions))
for _, c := range pod.Status.Conditions {
conditions = append(conditions, map[string]string{
"type": string(c.Type),
"status": string(c.Status),
"reason": c.Reason,
})
}
podList = append(podList, map[string]any{
"name": pod.Name,
"phase": string(pod.Status.Phase),
"node_name": pod.Spec.NodeName,
"created": pod.CreationTimestamp.Format(time.RFC3339),
"conditions": conditions,
})
}
result = map[string]any{
"deployment": map[string]any{ "deployment": map[string]any{
"replicas": *deployment.Spec.Replicas, "replicas": deployment.Spec.Replicas,
"ready_replicas": deployment.Status.ReadyReplicas, "ready_replicas": deployment.Status.ReadyReplicas,
"available_replicas": deployment.Status.AvailableReplicas, "available_replicas": deployment.Status.AvailableReplicas,
"updated_replicas": deployment.Status.UpdatedReplicas, "updated_replicas": deployment.Status.UpdatedReplicas,
"unavailable_replicas": deployment.Status.UnavailableReplicas, "unavailable_replicas": deployment.Status.UnavailableReplicas,
}, },
"pods": make([]map[string]any, 0), "pods": podList,
} }
return nil
for _, pod := range pods.Items {
podStatus := map[string]any{
"name": pod.Name,
"phase": string(pod.Status.Phase),
"node_name": pod.Spec.NodeName,
"created": pod.CreationTimestamp.Time,
"conditions": make([]map[string]any, 0),
}
for _, condition := range pod.Status.Conditions {
podStatus["conditions"] = append(podStatus["conditions"].([]map[string]any), map[string]any{
"type": string(condition.Type),
"status": string(condition.Status),
"reason": condition.Reason,
}) })
}
status["pods"] = append(status["pods"].([]map[string]any), podStatus) if err != nil {
return nil, err
} }
return result, nil
return status, nil
} }
// GetEvents returns recent events for a deployment // GetEvents returns recent events for a deployment
func (k *KubernetesService) GetEvents(ctx context.Context, name string, limit int) ([]map[string]any, error) { func (k *KubernetesService) GetEvents(ctx context.Context, name string, limit int) ([]map[string]any, error) {
var result []map[string]any
err := k.circuitBreaker.Execute(func() error {
deployment, err := k.clientset.AppsV1().Deployments(k.namespace).Get(ctx, name, metav1.GetOptions{})
if err != nil {
return fmt.Errorf("failed to get deployment %s: %w", name, err)
}
labelSelector := labels.Set(deployment.Spec.Selector.MatchLabels).AsSelector()
events, err := k.clientset.CoreV1().Events(k.namespace).List(ctx, metav1.ListOptions{ events, err := k.clientset.CoreV1().Events(k.namespace).List(ctx, metav1.ListOptions{
FieldSelector: fmt.Sprintf("involvedObject.name=%s,involvedObject.kind=Deployment", name), LabelSelector: labelSelector.String(),
Limit: int64(limit), Limit: int64(limit),
}) })
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to get events for deployment %s: %w", name, err) return fmt.Errorf("failed to get events for deployment %s: %w", name, err)
} }
result := make([]map[string]any, 0) result = make([]map[string]any, 0)
for _, event := range events.Items { for _, event := range events.Items {
result = append(result, map[string]any{ result = append(result, map[string]any{
"type": event.Type, "type": event.Type,
@@ -326,6 +367,11 @@ func (k *KubernetesService) GetEvents(ctx context.Context, name string, limit in
"count": event.Count, "count": event.Count,
}) })
} }
return nil
})
if err != nil {
return nil, err
}
return result, nil return result, nil
} }