-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeployment.go
More file actions
436 lines (378 loc) · 12.6 KB
/
deployment.go
File metadata and controls
436 lines (378 loc) · 12.6 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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
package sdk
import (
"fmt"
"path/filepath"
"strings"
"time"
"github.com/google/uuid"
)
// DeploymentHelper assists with ConfigHub-based deployments
type DeploymentHelper struct {
Cub *ConfigHubClient
ProjectName string
AppName string
}
// NewDeploymentHelper creates a deployment helper for a DevOps app
func NewDeploymentHelper(cub *ConfigHubClient, appName string) (*DeploymentHelper, error) {
// Use ConfigHub's new-prefix to generate unique names (like "chubby-paws")
// This would call: cub space new-prefix
prefix, err := cub.GetNewSpacePrefix()
if err != nil {
// Fallback to timestamp if API call fails
prefix = fmt.Sprintf("prefix-%d", time.Now().Unix())
}
// Project name format: prefix-appname (e.g., "chubby-paws-drift-detector")
projectName := fmt.Sprintf("%s-%s", prefix, appName)
return &DeploymentHelper{
Cub: cub,
ProjectName: projectName,
AppName: appName,
}, nil
}
// SetupBaseSpace creates the base ConfigHub structure
func (d *DeploymentHelper) SetupBaseSpace() error {
// Create main space
_, err := d.Cub.CreateSpace(CreateSpaceRequest{
Slug: d.ProjectName,
DisplayName: fmt.Sprintf("%s DevOps App", d.AppName),
Labels: map[string]string{
"app": d.AppName,
"type": "devops-app",
"project": d.ProjectName,
},
})
if err != nil && !strings.Contains(err.Error(), "already exists") {
return fmt.Errorf("create main space: %w", err)
}
// Create base space for base configurations
_, err = d.Cub.CreateSpace(CreateSpaceRequest{
Slug: fmt.Sprintf("%s-base", d.ProjectName),
DisplayName: fmt.Sprintf("%s Base Configurations", d.AppName),
Labels: map[string]string{
"base": "true",
"project": d.ProjectName,
},
})
if err != nil && !strings.Contains(err.Error(), "already exists") {
return fmt.Errorf("create base space: %w", err)
}
// Create filters space
_, err = d.Cub.CreateSpace(CreateSpaceRequest{
Slug: fmt.Sprintf("%s-filters", d.ProjectName),
DisplayName: fmt.Sprintf("%s Filters", d.AppName),
Labels: map[string]string{
"type": "filters",
"project": d.ProjectName,
},
})
if err != nil && !strings.Contains(err.Error(), "already exists") {
return fmt.Errorf("create filters space: %w", err)
}
return nil
}
// CreateStandardFilters creates common filters for DevOps apps
func (d *DeploymentHelper) CreateStandardFilters() error {
filtersSpaceID, err := d.getSpaceIDOrCreate(
fmt.Sprintf("%s-filters", d.ProjectName),
fmt.Sprintf("%s Filters", d.AppName),
map[string]string{"type": "filters", "project": d.ProjectName},
)
if err != nil {
return fmt.Errorf("get filters space: %w", err)
}
// All project units filter
_, err = d.Cub.CreateFilter(filtersSpaceID, CreateFilterRequest{
Slug: "all",
DisplayName: "All Project Units",
From: "Unit",
Where: fmt.Sprintf("Space.Labels.project = '%s'", d.ProjectName),
})
if err != nil && !strings.Contains(err.Error(), "already exists") {
return fmt.Errorf("create all filter: %w", err)
}
// App-specific filter
_, err = d.Cub.CreateFilter(filtersSpaceID, CreateFilterRequest{
Slug: d.AppName,
DisplayName: fmt.Sprintf("%s Units", d.AppName),
From: "Unit",
Where: fmt.Sprintf("Labels.app = '%s'", d.AppName),
})
if err != nil && !strings.Contains(err.Error(), "already exists") {
return fmt.Errorf("create app filter: %w", err)
}
// Critical services filter
_, err = d.Cub.CreateFilter(filtersSpaceID, CreateFilterRequest{
Slug: "critical",
DisplayName: "Critical Services",
From: "Unit",
Where: "Labels.tier = 'critical'",
})
if err != nil && !strings.Contains(err.Error(), "already exists") {
return fmt.Errorf("create critical filter: %w", err)
}
return nil
}
// LoadBaseConfigurations loads K8s manifests as ConfigHub units
func (d *DeploymentHelper) LoadBaseConfigurations(configPath string) error {
baseSpaceID, err := d.getSpaceID(fmt.Sprintf("%s-base", d.ProjectName))
if err != nil {
return fmt.Errorf("get base space: %w", err)
}
// Standard files to load
configs := []struct {
name string
file string
unitType string
tier string
}{
{"namespace", "namespace.yaml", "infrastructure", "critical"},
{fmt.Sprintf("%s-rbac", d.AppName), fmt.Sprintf("%s-rbac.yaml", d.AppName), "devops-app", "critical"},
{fmt.Sprintf("%s-deployment", d.AppName), fmt.Sprintf("%s-deployment.yaml", d.AppName), "devops-app", "critical"},
{fmt.Sprintf("%s-service", d.AppName), fmt.Sprintf("%s-service.yaml", d.AppName), "devops-app", "critical"},
}
for _, cfg := range configs {
filePath := filepath.Join(configPath, cfg.file)
// In real implementation, would read file content
_, err = d.Cub.CreateUnit(baseSpaceID, CreateUnitRequest{
Slug: cfg.name,
DisplayName: fmt.Sprintf("%s Configuration", cfg.name),
Data: fmt.Sprintf("# Content from %s", filePath),
Labels: map[string]string{
"type": cfg.unitType,
"app": d.AppName,
"tier": cfg.tier,
},
})
if err != nil && !strings.Contains(err.Error(), "already exists") {
return fmt.Errorf("create unit %s: %w", cfg.name, err)
}
}
return nil
}
// CreateEnvironmentHierarchy sets up dev → staging → prod
func (d *DeploymentHelper) CreateEnvironmentHierarchy() error {
baseSpaceID, err := d.getSpaceID(fmt.Sprintf("%s-base", d.ProjectName))
if err != nil {
return fmt.Errorf("get base space: %w", err)
}
// Create dev environment
devSpaceID, err := d.createEnvironment("dev", &baseSpaceID)
if err != nil {
return fmt.Errorf("create dev environment: %w", err)
}
// Create staging environment (downstream from dev)
stagingSpaceID, err := d.createEnvironment("staging", &devSpaceID)
if err != nil {
return fmt.Errorf("create staging environment: %w", err)
}
// Create prod environment (downstream from staging)
_, err = d.createEnvironment("prod", &stagingSpaceID)
if err != nil {
return fmt.Errorf("create prod environment: %w", err)
}
return nil
}
// CreateVariant creates a variant by editing an existing unit directly
// This avoids unnecessary cloning - just edit the unit where you need the variant
func (d *DeploymentHelper) CreateVariant(unitName, spaceName string, changes map[string]interface{}, description string) error {
spaceID, err := d.getSpaceID(spaceName)
if err != nil {
return fmt.Errorf("get space: %w", err)
}
// Edit the unit directly with the variant changes
// ConfigHub will create a new revision automatically
err = d.Cub.BulkPatchUnits(BulkPatchParams{
SpaceID: spaceID,
Where: fmt.Sprintf("Slug = '%s'", unitName),
Patch: changes,
Upgrade: false, // Don't push to downstream, this is a local variant
})
if err != nil {
return fmt.Errorf("create variant for unit %s: %w", unitName, err)
}
return nil
}
// ApplyToEnvironment applies all units to a specific environment
func (d *DeploymentHelper) ApplyToEnvironment(environment string) error {
spaceID, err := d.getSpaceID(fmt.Sprintf("%s-%s", d.ProjectName, environment))
if err != nil {
return fmt.Errorf("get environment space: %w", err)
}
// Apply units in correct order
units := []string{
"namespace",
fmt.Sprintf("%s-rbac", d.AppName),
fmt.Sprintf("%s-service", d.AppName),
fmt.Sprintf("%s-deployment", d.AppName),
}
for _, unit := range units {
// Get unit ID by slug
unitList, err := d.Cub.ListUnits(ListUnitsParams{
SpaceID: spaceID,
Where: fmt.Sprintf("Slug = '%s'", unit),
})
if err != nil {
return fmt.Errorf("list units for %s: %w", unit, err)
}
if len(unitList) > 0 {
err = d.Cub.ApplyUnit(spaceID, unitList[0].UnitID)
if err != nil {
return fmt.Errorf("apply unit %s: %w", unit, err)
}
}
}
// Alternative: Use bulk apply
err = d.Cub.BulkApplyUnits(BulkApplyParams{
SpaceID: spaceID,
Where: fmt.Sprintf("Labels.app = '%s'", d.AppName),
DryRun: false,
})
if err != nil {
return fmt.Errorf("bulk apply: %w", err)
}
return nil
}
// PromoteEnvironment promotes changes from one environment to another
func (d *DeploymentHelper) PromoteEnvironment(from, to string) error {
fromSpaceID, err := d.getSpaceID(fmt.Sprintf("%s-%s", d.ProjectName, from))
if err != nil {
return fmt.Errorf("get from space: %w", err)
}
toSpaceID, err := d.getSpaceID(fmt.Sprintf("%s-%s", d.ProjectName, to))
if err != nil {
return fmt.Errorf("get to space: %w", err)
}
// Use push-upgrade pattern
err = d.Cub.BulkPatchUnits(BulkPatchParams{
SpaceID: toSpaceID,
Where: fmt.Sprintf("UpstreamSpaceID = '%s'", fromSpaceID),
Patch: map[string]interface{}{},
Upgrade: true, // Push-upgrade
})
if err != nil {
return fmt.Errorf("promote from %s to %s: %w", from, to, err)
}
return nil
}
// Helper functions
func (d *DeploymentHelper) createEnvironment(env string, upstreamSpaceID *uuid.UUID) (uuid.UUID, error) {
spaceName := fmt.Sprintf("%s-%s", d.ProjectName, env)
space, err := d.Cub.CreateSpace(CreateSpaceRequest{
Slug: spaceName,
DisplayName: fmt.Sprintf("%s %s Environment", d.AppName, strings.Title(env)),
Labels: map[string]string{
"project": d.ProjectName,
"environment": env,
},
})
if err != nil && !strings.Contains(err.Error(), "already exists") {
return uuid.UUID{}, fmt.Errorf("create space: %w", err)
}
// Clone units from upstream
if upstreamSpaceID != nil {
err = d.cloneUnitsFromUpstream(*upstreamSpaceID, space.SpaceID, env)
if err != nil {
return uuid.UUID{}, fmt.Errorf("clone units: %w", err)
}
}
return space.SpaceID, nil
}
func (d *DeploymentHelper) cloneUnitsFromUpstream(fromSpaceID, toSpaceID uuid.UUID, env string) error {
// List units in upstream space
units, err := d.Cub.ListUnits(ListUnitsParams{
SpaceID: fromSpaceID,
})
if err != nil {
return fmt.Errorf("list upstream units: %w", err)
}
// Clone each unit with upstream relationship
for _, unit := range units {
_, err = d.Cub.CreateUnit(toSpaceID, CreateUnitRequest{
Slug: unit.Slug,
DisplayName: unit.DisplayName,
Data: unit.Data,
Labels: mergeLabels(unit.Labels, map[string]string{"environment": env}),
UpstreamUnitID: &unit.UnitID,
})
if err != nil && !strings.Contains(err.Error(), "already exists") {
return fmt.Errorf("clone unit %s: %w", unit.Slug, err)
}
}
return nil
}
// getSpaceID resolves space name to UUID by querying ConfigHub
func (d *DeploymentHelper) getSpaceID(spaceName string) (uuid.UUID, error) {
spaces, err := d.Cub.ListSpaces()
if err != nil {
return uuid.UUID{}, fmt.Errorf("list spaces: %w", err)
}
// Filter by slug
for _, space := range spaces {
if space.Slug == spaceName {
return space.SpaceID, nil
}
}
return uuid.UUID{}, fmt.Errorf("space not found: %s", spaceName)
}
// getSpaceIDOrCreate resolves space name to UUID, creating it if it doesn't exist
func (d *DeploymentHelper) getSpaceIDOrCreate(spaceName, displayName string, labels map[string]string) (uuid.UUID, error) {
// Try to get existing space first
spaceID, err := d.getSpaceID(spaceName)
if err == nil {
return spaceID, nil
}
// Space doesn't exist, create it
space, err := d.Cub.CreateSpace(CreateSpaceRequest{
Slug: spaceName,
DisplayName: displayName,
Labels: labels,
})
if err != nil {
return uuid.UUID{}, fmt.Errorf("create space %s: %w", spaceName, err)
}
return space.SpaceID, nil
}
func mergeLabels(base, additional map[string]string) map[string]string {
result := make(map[string]string)
for k, v := range base {
result[k] = v
}
for k, v := range additional {
result[k] = v
}
return result
}
// QuickDeploy performs a complete deployment setup
// Example usage:
//
// helper, err := NewDeploymentHelper(cub, "drift-detector")
// if err != nil { ... }
// err = helper.QuickDeploy("confighub/base")
//
// // Create variants by editing directly (no cloning needed)
// helper.CreateVariant("drift-detector-deployment", "prefix-drift-detector-prod",
// map[string]interface{}{"spec": map[string]interface{}{"replicas": 3}},
// "Production scaling")
func (d *DeploymentHelper) QuickDeploy(configPath string) error {
// 1. Setup base spaces
if err := d.SetupBaseSpace(); err != nil {
return fmt.Errorf("setup base space: %w", err)
}
// 2. Create standard filters
if err := d.CreateStandardFilters(); err != nil {
return fmt.Errorf("create filters: %w", err)
}
// 3. Load base configurations
if err := d.LoadBaseConfigurations(configPath); err != nil {
return fmt.Errorf("load configs: %w", err)
}
// 4. Create environment hierarchy
if err := d.CreateEnvironmentHierarchy(); err != nil {
return fmt.Errorf("create environments: %w", err)
}
// 5. Apply to dev environment
if err := d.ApplyToEnvironment("dev"); err != nil {
return fmt.Errorf("apply to dev: %w", err)
}
return nil
}