-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeployment_dev.go
More file actions
354 lines (298 loc) · 10.1 KB
/
deployment_dev.go
File metadata and controls
354 lines (298 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
package sdk
import (
"context"
"fmt"
"time"
"github.com/google/uuid"
"gopkg.in/yaml.v3"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/dynamic"
)
// DevModeDeployer implements direct ConfigHub → Kubernetes deployment for development
// This bypasses Git/GitOps for fast feedback loops during development
type DevModeDeployer struct {
app *DevOpsApp
dynamicClient dynamic.Interface
spaceID uuid.UUID
}
// NewDevModeDeployer creates a new development mode deployer
func NewDevModeDeployer(app *DevOpsApp, spaceID uuid.UUID) *DevModeDeployer {
return &DevModeDeployer{
app: app,
dynamicClient: app.K8s.DynamicClient,
spaceID: spaceID,
}
}
// DeployUnit deploys a single ConfigHub unit directly to Kubernetes
func (d *DevModeDeployer) DeployUnit(unitID uuid.UUID) error {
d.app.Logger.Printf("🚀 [Dev Mode] Deploying unit %s directly to Kubernetes", unitID)
// Get unit from ConfigHub
unit, err := d.app.Cub.GetUnit(d.spaceID, unitID)
if err != nil {
return fmt.Errorf("get unit: %w", err)
}
// Parse manifest from Data field
var manifest map[string]interface{}
if err := yaml.Unmarshal([]byte(unit.Data), &manifest); err != nil {
return fmt.Errorf("parse manifest: %w", err)
}
return d.applyManifest(manifest, unit.Slug)
}
// DeploySpace deploys all units in a ConfigHub space directly to Kubernetes
func (d *DevModeDeployer) DeploySpace() error {
d.app.Logger.Printf("🚀 [Dev Mode] Deploying all units from space %s", d.spaceID)
start := time.Now()
// List all units in space
units, err := d.app.Cub.ListUnits(ListUnitsParams{
SpaceID: d.spaceID,
})
if err != nil {
return fmt.Errorf("list units: %w", err)
}
deployed := 0
failed := 0
for _, unit := range units {
if err := d.DeployUnit(unit.UnitID); err != nil {
d.app.Logger.Printf("⚠️ Failed to deploy %s: %v", unit.Slug, err)
failed++
} else {
deployed++
}
}
d.app.Logger.Printf("✅ [Dev Mode] Deployment complete: %d succeeded, %d failed in %v",
deployed, failed, time.Since(start))
return nil
}
// DeployWithFilter deploys units matching a filter directly to Kubernetes
func (d *DevModeDeployer) DeployWithFilter(filterID uuid.UUID) error {
d.app.Logger.Printf("🚀 [Dev Mode] Deploying units matching filter %s", filterID)
// Get filter and apply it
filter, err := d.app.Cub.GetFilter(d.spaceID, filterID)
if err != nil {
return fmt.Errorf("get filter: %w", err)
}
// List units using filter's WHERE clause
units, err := d.app.Cub.ListUnits(ListUnitsParams{
SpaceID: d.spaceID,
Where: filter.Where,
})
if err != nil {
return fmt.Errorf("list filtered units: %w", err)
}
deployed := 0
for _, unit := range units {
if err := d.DeployUnit(unit.UnitID); err != nil {
d.app.Logger.Printf("⚠️ Failed to deploy %s: %v", unit.Slug, err)
} else {
deployed++
}
}
d.app.Logger.Printf("✅ [Dev Mode] Deployed %d/%d units matching filter", deployed, len(units))
return nil
}
// WatchAndSync continuously syncs ConfigHub changes to Kubernetes
func (d *DevModeDeployer) WatchAndSync(ctx context.Context, interval time.Duration) error {
d.app.Logger.Printf("👁️ [Dev Mode] Watching ConfigHub space %s for changes", d.spaceID)
ticker := time.NewTicker(interval)
defer ticker.Stop()
// Track last revision for change detection
lastRevisions := make(map[uuid.UUID]int64)
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-ticker.C:
if err := d.syncChanges(lastRevisions); err != nil {
d.app.Logger.Printf("⚠️ Sync error: %v", err)
}
}
}
}
// syncChanges syncs any changed units to Kubernetes
func (d *DevModeDeployer) syncChanges(lastRevisions map[uuid.UUID]int64) error {
units, err := d.app.Cub.ListUnits(ListUnitsParams{
SpaceID: d.spaceID,
})
if err != nil {
return fmt.Errorf("list units: %w", err)
}
changes := 0
for _, unit := range units {
// Check if unit has changed
lastRev, exists := lastRevisions[unit.UnitID]
currentRev := unit.Version // Use Version field for revision tracking
if !exists || currentRev > lastRev {
d.app.Logger.Printf("🔄 [Dev Mode] Detected change in %s (version %d -> %d)",
unit.Slug, lastRev, currentRev)
if err := d.DeployUnit(unit.UnitID); err != nil {
d.app.Logger.Printf("⚠️ Failed to sync %s: %v", unit.Slug, err)
} else {
changes++
lastRevisions[unit.UnitID] = currentRev
}
}
}
if changes > 0 {
d.app.Logger.Printf("✅ [Dev Mode] Synced %d changed units", changes)
}
return nil
}
// applyManifest applies a Kubernetes manifest directly
func (d *DevModeDeployer) applyManifest(manifest map[string]interface{}, name string) error {
// Extract resource information
apiVersion, _ := manifest["apiVersion"].(string)
kind, _ := manifest["kind"].(string)
if apiVersion == "" || kind == "" {
return fmt.Errorf("missing apiVersion or kind in manifest")
}
// Parse GVR from manifest
gvr, namespace, err := d.parseGVR(apiVersion, kind, manifest)
if err != nil {
return fmt.Errorf("parse GVR: %w", err)
}
// Create unstructured object
obj := &unstructured.Unstructured{
Object: manifest,
}
// Apply to Kubernetes
ctx := context.Background()
var result *unstructured.Unstructured
if namespace == "" {
// Cluster-scoped resource
result, err = d.dynamicClient.Resource(gvr).Create(ctx, obj, metav1.CreateOptions{})
if err != nil {
// Try update if create fails
result, err = d.dynamicClient.Resource(gvr).Update(ctx, obj, metav1.UpdateOptions{})
}
} else {
// Namespaced resource
result, err = d.dynamicClient.Resource(gvr).Namespace(namespace).Create(ctx, obj, metav1.CreateOptions{})
if err != nil {
// Try update if create fails
result, err = d.dynamicClient.Resource(gvr).Namespace(namespace).Update(ctx, obj, metav1.UpdateOptions{})
}
}
if err != nil {
return fmt.Errorf("apply manifest: %w", err)
}
d.app.Logger.Printf("✅ [Dev Mode] Applied %s/%s: %s", kind, apiVersion, result.GetName())
return nil
}
// parseGVR parses Group, Version, Resource from manifest
func (d *DevModeDeployer) parseGVR(apiVersion, kind string, manifest map[string]interface{}) (schema.GroupVersionResource, string, error) {
// Common resource mappings
resourceMap := map[string]string{
"Deployment": "deployments",
"Service": "services",
"ConfigMap": "configmaps",
"Secret": "secrets",
"StatefulSet": "statefulsets",
"DaemonSet": "daemonsets",
"Pod": "pods",
"Ingress": "ingresses",
"ServiceAccount": "serviceaccounts",
"Role": "roles",
"RoleBinding": "rolebindings",
"ClusterRole": "clusterroles",
"ClusterRoleBinding": "clusterrolebindings",
"PersistentVolumeClaim": "persistentvolumeclaims",
"HorizontalPodAutoscaler": "horizontalpodautoscalers",
}
resource, ok := resourceMap[kind]
if !ok {
// Try to pluralize by adding 's'
resource = kind + "s"
}
// Parse group and version from apiVersion
group := ""
version := apiVersion
if idx := len(apiVersion) - 1; idx > 0 {
for i := len(apiVersion) - 1; i >= 0; i-- {
if apiVersion[i] == '/' {
group = apiVersion[:i]
version = apiVersion[i+1:]
break
}
}
}
// Extract namespace from metadata
namespace := ""
if metadata, ok := manifest["metadata"].(map[string]interface{}); ok {
namespace, _ = metadata["namespace"].(string)
}
return schema.GroupVersionResource{
Group: group,
Version: version,
Resource: resource,
}, namespace, nil
}
// Rollback rolls back a deployment to a previous ConfigHub revision
func (d *DevModeDeployer) Rollback(unitID uuid.UUID, targetRevision int) error {
d.app.Logger.Printf("⏮️ [Dev Mode] Rolling back unit %s to revision %d", unitID, targetRevision)
// In Dev Mode, rollback is instant - just get the old revision and apply it
// This would require ConfigHub to support revision history API
// For now, just re-deploy current version
return d.DeployUnit(unitID)
}
// ValidateDeployment validates that Kubernetes matches ConfigHub configuration
func (d *DevModeDeployer) ValidateDeployment() (bool, []string) {
d.app.Logger.Println("🔍 [Dev Mode] Validating Kubernetes matches ConfigHub...")
units, err := d.app.Cub.ListUnits(ListUnitsParams{
SpaceID: d.spaceID,
})
if err != nil {
return false, []string{fmt.Sprintf("Failed to list units: %v", err)}
}
var issues []string
for _, unit := range units {
// Parse manifest from Data field
var manifest map[string]interface{}
if err := yaml.Unmarshal([]byte(unit.Data), &manifest); err != nil {
issues = append(issues, fmt.Sprintf("%s: failed to parse manifest: %v", unit.Slug, err))
continue
}
// Check if resource exists in Kubernetes
exists, err := d.resourceExists(manifest)
if err != nil {
issues = append(issues, fmt.Sprintf("%s: %v", unit.Slug, err))
} else if !exists {
issues = append(issues, fmt.Sprintf("%s: not found in Kubernetes", unit.Slug))
}
}
valid := len(issues) == 0
if valid {
d.app.Logger.Println("✅ [Dev Mode] All ConfigHub units are deployed to Kubernetes")
} else {
d.app.Logger.Printf("⚠️ [Dev Mode] Found %d validation issues", len(issues))
}
return valid, issues
}
// resourceExists checks if a resource exists in Kubernetes
func (d *DevModeDeployer) resourceExists(manifest map[string]interface{}) (bool, error) {
apiVersion, _ := manifest["apiVersion"].(string)
kind, _ := manifest["kind"].(string)
metadata, ok := manifest["metadata"].(map[string]interface{})
if !ok {
return false, fmt.Errorf("missing metadata")
}
name, _ := metadata["name"].(string)
if name == "" {
return false, fmt.Errorf("missing name in metadata")
}
gvr, namespace, err := d.parseGVR(apiVersion, kind, manifest)
if err != nil {
return false, err
}
ctx := context.Background()
if namespace == "" {
_, err = d.dynamicClient.Resource(gvr).Get(ctx, name, metav1.GetOptions{})
} else {
_, err = d.dynamicClient.Resource(gvr).Namespace(namespace).Get(ctx, name, metav1.GetOptions{})
}
if err != nil {
return false, nil // Resource doesn't exist
}
return true, nil
}