|
| 1 | +package k8s |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "encoding/json" |
| 7 | + "fmt" |
| 8 | + "io" |
| 9 | + "strings" |
| 10 | + "time" |
| 11 | + |
| 12 | + "k8s.io/apimachinery/pkg/api/errors" |
| 13 | + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 14 | + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" |
| 15 | + "k8s.io/apimachinery/pkg/runtime/schema" |
| 16 | + "k8s.io/apimachinery/pkg/types" |
| 17 | + "k8s.io/apimachinery/pkg/util/yaml" |
| 18 | + "k8s.io/client-go/discovery/cached/memory" |
| 19 | + "k8s.io/client-go/restmapper" |
| 20 | + "github.com/aamod/llm-infra-assistant/internal/store" |
| 21 | +) |
| 22 | + |
| 23 | +type ApplyResult struct { |
| 24 | + ID string |
| 25 | + Resources []string |
| 26 | + AppliedAt time.Time |
| 27 | + CanUndo bool |
| 28 | +} |
| 29 | + |
| 30 | +type ClusterManager struct { |
| 31 | + client *Client |
| 32 | + store *store.Store |
| 33 | +} |
| 34 | + |
| 35 | +func NewClusterManager(client *Client, dbStore *store.Store) *ClusterManager { |
| 36 | + return &ClusterManager{ |
| 37 | + client: client, |
| 38 | + store: dbStore, |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +func (cm *ClusterManager) Apply(ctx context.Context, yamlData string) (ApplyResult, error) { |
| 43 | + decoder := yaml.NewYAMLOrJSONDecoder(bytes.NewReader([]byte(yamlData)), 4096) |
| 44 | + mapper := restmapper.NewDeferredDiscoveryRESTMapper(memory.NewMemCacheClient(cm.client.DiscoveryClient)) |
| 45 | + |
| 46 | + var appliedResources []string |
| 47 | + applyID := fmt.Sprintf("apply-%d", time.Now().UnixNano()) |
| 48 | + |
| 49 | + for { |
| 50 | + var obj unstructured.Unstructured |
| 51 | + if err := decoder.Decode(&obj); err != nil { |
| 52 | + if err == io.EOF { |
| 53 | + break |
| 54 | + } |
| 55 | + return ApplyResult{}, err |
| 56 | + } |
| 57 | + if len(obj.Object) == 0 { |
| 58 | + continue |
| 59 | + } |
| 60 | + |
| 61 | + gvk := obj.GroupVersionKind() |
| 62 | + mapping, err := mapper.RESTMapping(gvk.GroupKind(), gvk.Version) |
| 63 | + if err != nil { |
| 64 | + return ApplyResult{}, fmt.Errorf("failed to map %s: %v", gvk, err) |
| 65 | + } |
| 66 | + |
| 67 | + ns := obj.GetNamespace() |
| 68 | + if ns == "" && mapping.Scope.Name() == "namespace" { |
| 69 | + ns = "default" |
| 70 | + } |
| 71 | + |
| 72 | + dr := cm.client.DynamicClient.Resource(mapping.Resource).Namespace(ns) |
| 73 | + name := obj.GetName() |
| 74 | + |
| 75 | + // Snapshot previous state |
| 76 | + var prevJSON []byte |
| 77 | + existing, err := dr.Get(ctx, name, metav1.GetOptions{}) |
| 78 | + if err == nil { |
| 79 | + prevJSON, _ = existing.MarshalJSON() |
| 80 | + } else if !errors.IsNotFound(err) { |
| 81 | + return ApplyResult{}, fmt.Errorf("failed to get existing %s: %v", name, err) |
| 82 | + } |
| 83 | + |
| 84 | + // Apply |
| 85 | + data, _ := json.Marshal(obj.Object) |
| 86 | + _, err = dr.Patch(ctx, name, types.ApplyPatchType, data, metav1.PatchOptions{FieldManager: "llm-infra"}) |
| 87 | + if err != nil { |
| 88 | + return ApplyResult{}, fmt.Errorf("failed to apply %s: %v", name, err) |
| 89 | + } |
| 90 | + |
| 91 | + resKey := fmt.Sprintf("%s/%s/%s", ns, gvk.Kind, name) |
| 92 | + appliedResources = append(appliedResources, resKey) |
| 93 | + |
| 94 | + // Build a GVR key: "group/version/resource" so rollback can map back |
| 95 | + gvrKey := fmt.Sprintf("%s/%s/%s", mapping.Resource.Group, mapping.Resource.Version, mapping.Resource.Resource) |
| 96 | + |
| 97 | + // Record snapshot (pass gvrKey for rollback) |
| 98 | + if err := cm.store.SaveSnapshot(ctx, applyID, resKey, gvrKey, string(prevJSON)); err != nil { |
| 99 | + return ApplyResult{}, fmt.Errorf("failed to save snapshot: %v", err) |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + return ApplyResult{ |
| 104 | + ID: applyID, |
| 105 | + Resources: appliedResources, |
| 106 | + AppliedAt: time.Now(), |
| 107 | + CanUndo: true, |
| 108 | + }, nil |
| 109 | +} |
| 110 | + |
| 111 | +func (cm *ClusterManager) CheckRollbackTTL(ctx context.Context, applyID string) error { |
| 112 | + return cm.store.CheckRollbackTTL(ctx, applyID) |
| 113 | +} |
| 114 | + |
| 115 | +func (cm *ClusterManager) Rollback(ctx context.Context, applyID string) error { |
| 116 | + snapshots, err := cm.store.GetSnapshots(ctx, applyID) |
| 117 | + if err != nil { |
| 118 | + return err |
| 119 | + } |
| 120 | + if len(snapshots) == 0 { |
| 121 | + return fmt.Errorf("no snapshots found for %s or TTL expired", applyID) |
| 122 | + } |
| 123 | + |
| 124 | + for _, snap := range snapshots { |
| 125 | + // Parse resource key "namespace/Kind/name" |
| 126 | + parts := strings.SplitN(snap.ResourceKey, "/", 3) |
| 127 | + if len(parts) != 3 { |
| 128 | + return fmt.Errorf("invalid resource key format: %s", snap.ResourceKey) |
| 129 | + } |
| 130 | + ns, _, name := parts[0], parts[1], parts[2] |
| 131 | + |
| 132 | + // Parse GVR key "group/version/resource" |
| 133 | + gvrParts := strings.SplitN(snap.GVRKey, "/", 3) |
| 134 | + if len(gvrParts) != 3 { |
| 135 | + return fmt.Errorf("invalid gvr key format: %s", snap.GVRKey) |
| 136 | + } |
| 137 | + gvr := schema.GroupVersionResource{ |
| 138 | + Group: gvrParts[0], |
| 139 | + Version: gvrParts[1], |
| 140 | + Resource: gvrParts[2], |
| 141 | + } |
| 142 | + |
| 143 | + dr := cm.client.DynamicClient.Resource(gvr).Namespace(ns) |
| 144 | + |
| 145 | + if snap.StateJSON == "" { |
| 146 | + // Resource didn't exist before apply — delete it to roll back |
| 147 | + err := dr.Delete(ctx, name, metav1.DeleteOptions{}) |
| 148 | + if err != nil && !errors.IsNotFound(err) { |
| 149 | + return fmt.Errorf("rollback delete failed for %s: %v", snap.ResourceKey, err) |
| 150 | + } |
| 151 | + } else { |
| 152 | + // Resource existed before — patch it back to its original state |
| 153 | + var obj unstructured.Unstructured |
| 154 | + if jsonErr := json.Unmarshal([]byte(snap.StateJSON), &obj); jsonErr != nil { |
| 155 | + return fmt.Errorf("rollback unmarshal failed for %s: %v", snap.ResourceKey, jsonErr) |
| 156 | + } |
| 157 | + // Clear resource version to avoid conflicts with the current state |
| 158 | + obj.SetResourceVersion("") |
| 159 | + patchData, _ := json.Marshal(obj.Object) |
| 160 | + _, err := dr.Patch(ctx, name, types.MergePatchType, patchData, metav1.PatchOptions{}) |
| 161 | + if err != nil { |
| 162 | + // If it no longer exists, recreate it |
| 163 | + if errors.IsNotFound(err) { |
| 164 | + _, createErr := dr.Create(ctx, &obj, metav1.CreateOptions{FieldManager: "llm-infra"}) |
| 165 | + if createErr != nil { |
| 166 | + return fmt.Errorf("rollback recreate failed for %s: %v", snap.ResourceKey, createErr) |
| 167 | + } |
| 168 | + } else { |
| 169 | + return fmt.Errorf("rollback patch failed for %s: %v", snap.ResourceKey, err) |
| 170 | + } |
| 171 | + } |
| 172 | + } |
| 173 | + } |
| 174 | + |
| 175 | + return nil |
| 176 | +} |
0 commit comments