mirror of
https://github.com/andwati/telecom-platform.git
synced 2026-11-26 13:58:49 +00:00
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:
@@ -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,47 +112,62 @@ 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) {
|
||||||
deployments, err := k.clientset.AppsV1().Deployments(k.namespace).List(ctx, metav1.ListOptions{})
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to list deployments: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var result []Deployment
|
var result []Deployment
|
||||||
for _, d := range deployments.Items {
|
err := k.circuitBreaker.Execute(func() error {
|
||||||
result = append(result, Deployment{
|
deployments, err := k.clientset.AppsV1().Deployments(k.namespace).List(ctx, metav1.ListOptions{})
|
||||||
Name: d.Name,
|
if err != nil {
|
||||||
Namespace: d.Namespace,
|
return fmt.Errorf("failed to list deployments: %w", err)
|
||||||
CreationTimestamp: d.CreationTimestamp.Time,
|
}
|
||||||
Labels: d.Labels,
|
|
||||||
Replicas: *d.Spec.Replicas,
|
|
||||||
ReadyReplicas: d.Status.ReadyReplicas,
|
|
||||||
AvailableReplicas: d.Status.AvailableReplicas,
|
|
||||||
UpdatedReplicas: d.Status.UpdatedReplicas,
|
|
||||||
UnavailableReplicas: d.Status.UnavailableReplicas,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
|
for _, d := range deployments.Items {
|
||||||
|
result = append(result, Deployment{
|
||||||
|
Name: d.Name,
|
||||||
|
Namespace: d.Namespace,
|
||||||
|
CreationTimestamp: d.CreationTimestamp.Time,
|
||||||
|
Labels: d.Labels,
|
||||||
|
Replicas: *d.Spec.Replicas,
|
||||||
|
ReadyReplicas: d.Status.ReadyReplicas,
|
||||||
|
AvailableReplicas: d.Status.AvailableReplicas,
|
||||||
|
UpdatedReplicas: d.Status.UpdatedReplicas,
|
||||||
|
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) {
|
||||||
deployment, err := k.clientset.AppsV1().Deployments(k.namespace).Get(ctx, name, metav1.GetOptions{})
|
var result *Deployment
|
||||||
if err != nil {
|
err := k.circuitBreaker.Execute(func() error {
|
||||||
return nil, fmt.Errorf("failed to get deployment %s: %w", name, err)
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
return &Deployment{
|
result = &Deployment{
|
||||||
Name: deployment.Name,
|
Name: deployment.Name,
|
||||||
Namespace: deployment.Namespace,
|
Namespace: deployment.Namespace,
|
||||||
CreationTimestamp: deployment.CreationTimestamp.Time,
|
CreationTimestamp: deployment.CreationTimestamp.Time,
|
||||||
Labels: deployment.Labels,
|
Labels: deployment.Labels,
|
||||||
Replicas: *deployment.Spec.Replicas,
|
Replicas: *deployment.Spec.Replicas,
|
||||||
ReadyReplicas: deployment.Status.ReadyReplicas,
|
ReadyReplicas: deployment.Status.ReadyReplicas,
|
||||||
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,172 +176,202 @@ 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)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get current deployment
|
return k.circuitBreaker.Execute(func() error {
|
||||||
deployment, err := k.clientset.AppsV1().Deployments(k.namespace).Get(ctx, name, metav1.GetOptions{})
|
// Get current deployment
|
||||||
if err != nil {
|
deployment, err := k.clientset.AppsV1().Deployments(k.namespace).Get(ctx, name, metav1.GetOptions{})
|
||||||
return fmt.Errorf("failed to get deployment %s for scaling: %w", name, err)
|
if err != nil {
|
||||||
}
|
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 {
|
||||||
deployment, err := k.clientset.AppsV1().Deployments(k.namespace).Get(ctx, name, metav1.GetOptions{})
|
return k.circuitBreaker.Execute(func() error {
|
||||||
if err != nil {
|
deployment, err := k.clientset.AppsV1().Deployments(k.namespace).Get(ctx, name, metav1.GetOptions{})
|
||||||
return fmt.Errorf("failed to get deployment %s for restart: %w", name, err)
|
if err != nil {
|
||||||
}
|
return fmt.Errorf("failed to get deployment %s for restart: %w", name, err)
|
||||||
|
}
|
||||||
|
|
||||||
// Add restart annotation to trigger rolling restart
|
// Add restart annotation to trigger rolling restart
|
||||||
if deployment.Spec.Template.Annotations == nil {
|
if deployment.Spec.Template.Annotations == nil {
|
||||||
deployment.Spec.Template.Annotations = make(map[string]string)
|
deployment.Spec.Template.Annotations = make(map[string]string)
|
||||||
}
|
}
|
||||||
deployment.Spec.Template.Annotations["kubectl.kubernetes.io/restartedAt"] = time.Now().UTC().Format(time.RFC3339)
|
deployment.Spec.Template.Annotations["kubectl.kubernetes.io/restartedAt"] = time.Now().UTC().Format(time.RFC3339)
|
||||||
|
|
||||||
_, 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 restart deployment %s: %w", name, err)
|
return fmt.Errorf("failed to restart deployment %s: %w", name, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
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) {
|
||||||
// Get deployment to find label selector
|
var result string
|
||||||
deployment, err := k.clientset.AppsV1().Deployments(k.namespace).Get(ctx, name, metav1.GetOptions{})
|
err := k.circuitBreaker.Execute(func() error {
|
||||||
if err != nil {
|
// Get deployment to find label selector
|
||||||
return "", fmt.Errorf("failed to get deployment %s for logs: %w", name, err)
|
deployment, err := k.clientset.AppsV1().Deployments(k.namespace).Get(ctx, name, metav1.GetOptions{})
|
||||||
}
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to get deployment %s for logs: %w", name, err)
|
||||||
// Find pods using deployment's label selector
|
|
||||||
labelSelector := labels.Set(deployment.Spec.Selector.MatchLabels).AsSelector()
|
|
||||||
pods, err := k.clientset.CoreV1().Pods(k.namespace).List(ctx, metav1.ListOptions{
|
|
||||||
LabelSelector: labelSelector.String(),
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return "", fmt.Errorf("failed to list pods for deployment %s: %w", name, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(pods.Items) == 0 {
|
|
||||||
return "", fmt.Errorf("no pods found for deployment %s", name)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get logs from the first running pod
|
|
||||||
var pod *corev1.Pod
|
|
||||||
for _, p := range pods.Items {
|
|
||||||
if p.Status.Phase == corev1.PodRunning {
|
|
||||||
pod = &p
|
|
||||||
break
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
if pod == nil {
|
|
||||||
// If no running pod, use the first one
|
|
||||||
pod = &pods.Items[0]
|
|
||||||
}
|
|
||||||
|
|
||||||
if tailLines <= 0 {
|
// Find pods using deployment's label selector
|
||||||
tailLines = 100
|
labelSelector := labels.Set(deployment.Spec.Selector.MatchLabels).AsSelector()
|
||||||
}
|
pods, err := k.clientset.CoreV1().Pods(k.namespace).List(ctx, metav1.ListOptions{
|
||||||
|
LabelSelector: labelSelector.String(),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to list pods for deployment %s: %w", name, err)
|
||||||
|
}
|
||||||
|
|
||||||
tailLines64 := int64(tailLines)
|
if len(pods.Items) == 0 {
|
||||||
req := k.clientset.CoreV1().Pods(k.namespace).GetLogs(pod.Name, &corev1.PodLogOptions{
|
return fmt.Errorf("no pods found for deployment %s", name)
|
||||||
TailLines: &tailLines64,
|
}
|
||||||
Follow: false,
|
|
||||||
|
// Get logs from the first running pod
|
||||||
|
var pod *corev1.Pod
|
||||||
|
for _, p := range pods.Items {
|
||||||
|
if p.Status.Phase == corev1.PodRunning {
|
||||||
|
pod = &p
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if pod == nil {
|
||||||
|
return fmt.Errorf("no running pods found for deployment %s", name)
|
||||||
|
}
|
||||||
|
|
||||||
|
req := k.clientset.CoreV1().Pods(k.namespace).GetLogs(pod.Name, &corev1.PodLogOptions{
|
||||||
|
TailLines: func(i int64) *int64 { return &i }(int64(tailLines)),
|
||||||
|
})
|
||||||
|
|
||||||
|
logData, err := req.Stream(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to stream logs from pod %s: %w", pod.Name, err)
|
||||||
|
}
|
||||||
|
defer logData.Close()
|
||||||
|
|
||||||
|
buf := make([]byte, 1024)
|
||||||
|
var logs strings.Builder
|
||||||
|
for {
|
||||||
|
n, err := logData.Read(buf)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
logs.WriteString(string(buf[:n]))
|
||||||
|
}
|
||||||
|
result = logs.String()
|
||||||
|
return nil
|
||||||
})
|
})
|
||||||
|
|
||||||
logs, 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 "", err
|
||||||
}
|
}
|
||||||
defer logs.Close()
|
return result, nil
|
||||||
|
|
||||||
data := make([]byte, 1024*1024) // 1MB limit
|
|
||||||
n, err := logs.Read(data)
|
|
||||||
if err != nil && err.Error() != "EOF" {
|
|
||||||
return "", fmt.Errorf("failed to read logs: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return string(data[:n]), 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) {
|
||||||
deployment, err := k.clientset.AppsV1().Deployments(k.namespace).Get(ctx, name, metav1.GetOptions{})
|
var result map[string]any
|
||||||
if err != nil {
|
err := k.circuitBreaker.Execute(func() error {
|
||||||
return nil, fmt.Errorf("failed to get deployment %s: %w", name, err)
|
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()
|
|
||||||
pods, err := k.clientset.CoreV1().Pods(k.namespace).List(ctx, metav1.ListOptions{
|
|
||||||
LabelSelector: labelSelector.String(),
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to list pods for deployment %s: %w", name, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
status := map[string]any{
|
|
||||||
"deployment": map[string]any{
|
|
||||||
"replicas": *deployment.Spec.Replicas,
|
|
||||||
"ready_replicas": deployment.Status.ReadyReplicas,
|
|
||||||
"available_replicas": deployment.Status.AvailableReplicas,
|
|
||||||
"updated_replicas": deployment.Status.UpdatedReplicas,
|
|
||||||
"unavailable_replicas": deployment.Status.UnavailableReplicas,
|
|
||||||
},
|
|
||||||
"pods": make([]map[string]any, 0),
|
|
||||||
}
|
|
||||||
|
|
||||||
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 {
|
labelSelector := labels.Set(deployment.Spec.Selector.MatchLabels).AsSelector()
|
||||||
podStatus["conditions"] = append(podStatus["conditions"].([]map[string]any), map[string]any{
|
pods, err := k.clientset.CoreV1().Pods(k.namespace).List(ctx, metav1.ListOptions{
|
||||||
"type": string(condition.Type),
|
LabelSelector: labelSelector.String(),
|
||||||
"status": string(condition.Status),
|
})
|
||||||
"reason": condition.Reason,
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to list pods for deployment %s: %w", name, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
status["pods"] = append(status["pods"].([]map[string]any), podStatus)
|
result = map[string]any{
|
||||||
}
|
"deployment": map[string]any{
|
||||||
|
"replicas": deployment.Spec.Replicas,
|
||||||
|
"ready_replicas": deployment.Status.ReadyReplicas,
|
||||||
|
"available_replicas": deployment.Status.AvailableReplicas,
|
||||||
|
"updated_replicas": deployment.Status.UpdatedReplicas,
|
||||||
|
"unavailable_replicas": deployment.Status.UnavailableReplicas,
|
||||||
|
},
|
||||||
|
"pods": podList,
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
return status, nil
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return result, 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) {
|
||||||
events, err := k.clientset.CoreV1().Events(k.namespace).List(ctx, metav1.ListOptions{
|
var result []map[string]any
|
||||||
FieldSelector: fmt.Sprintf("involvedObject.name=%s,involvedObject.kind=Deployment", name),
|
err := k.circuitBreaker.Execute(func() error {
|
||||||
Limit: int64(limit),
|
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: %w", name, err)
|
||||||
return nil, fmt.Errorf("failed to get events for deployment %s: %w", name, err)
|
}
|
||||||
}
|
|
||||||
|
|
||||||
result := make([]map[string]any, 0)
|
labelSelector := labels.Set(deployment.Spec.Selector.MatchLabels).AsSelector()
|
||||||
for _, event := range events.Items {
|
events, err := k.clientset.CoreV1().Events(k.namespace).List(ctx, metav1.ListOptions{
|
||||||
result = append(result, map[string]any{
|
LabelSelector: labelSelector.String(),
|
||||||
"type": event.Type,
|
Limit: int64(limit),
|
||||||
"reason": event.Reason,
|
|
||||||
"message": event.Message,
|
|
||||||
"first_timestamp": event.FirstTimestamp.Time,
|
|
||||||
"last_timestamp": event.LastTimestamp.Time,
|
|
||||||
"count": event.Count,
|
|
||||||
})
|
})
|
||||||
}
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to get events for deployment %s: %w", name, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
result = make([]map[string]any, 0)
|
||||||
|
for _, event := range events.Items {
|
||||||
|
result = append(result, map[string]any{
|
||||||
|
"type": event.Type,
|
||||||
|
"reason": event.Reason,
|
||||||
|
"message": event.Message,
|
||||||
|
"first_timestamp": event.FirstTimestamp.Time,
|
||||||
|
"last_timestamp": event.LastTimestamp.Time,
|
||||||
|
"count": event.Count,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user