-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathdeploy_azure.go
More file actions
449 lines (406 loc) · 15.3 KB
/
deploy_azure.go
File metadata and controls
449 lines (406 loc) · 15.3 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
437
438
439
440
441
442
443
444
445
446
447
448
449
package cmd
import (
"encoding/json"
"fmt"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/DevExpGBB/gh-devlake/internal/azure"
dockerpkg "github.com/DevExpGBB/gh-devlake/internal/docker"
"github.com/DevExpGBB/gh-devlake/internal/gitclone"
"github.com/DevExpGBB/gh-devlake/internal/prompt"
"github.com/DevExpGBB/gh-devlake/internal/secrets"
"github.com/spf13/cobra"
)
var (
azureRG string
azureLocation string
azureBaseName string
azureSkipImageBuild bool
azureRepoURL string
azureOfficial bool
deployAzureDir string
deployAzureQuiet bool // suppress "Next Steps" when called from init wizard
)
func newDeployAzureCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "azure",
Short: "Deploy DevLake to Azure Container Apps",
Long: `Provisions DevLake on Azure using Container Instances, Azure Database for MySQL,
and (optionally) Azure Container Registry.
Example:
gh devlake deploy azure --resource-group devlake-rg --location eastus
gh devlake deploy azure --resource-group devlake-rg --location eastus --official`,
RunE: runDeployAzure,
}
cmd.Flags().StringVar(&azureRG, "resource-group", "", "Azure Resource Group name")
cmd.Flags().StringVar(&azureLocation, "location", "", "Azure region")
cmd.Flags().StringVar(&azureBaseName, "base-name", "devlake", "Base name for Azure resources")
cmd.Flags().BoolVar(&azureSkipImageBuild, "skip-image-build", false, "Skip Docker image building")
cmd.Flags().StringVar(&azureRepoURL, "repo-url", "", "Clone a remote DevLake repository for building")
cmd.Flags().BoolVar(&azureOfficial, "official", false, "Use official Apache images from Docker Hub (no ACR)")
cmd.Flags().StringVar(&deployAzureDir, "dir", ".", "Directory to save deployment state (.devlake-azure.json)")
return cmd
}
// Common Azure regions for interactive selection.
var azureRegions = []string{
"eastus", "eastus2", "westus2", "westus3",
"centralus", "northeurope", "westeurope",
"southeastasia", "australiaeast", "uksouth",
}
func runDeployAzure(cmd *cobra.Command, args []string) error {
// Suggest a dedicated directory unless already in the right place or called from init
if !deployAzureQuiet {
if suggestDedicatedDir("azure", "gh devlake deploy azure") {
return nil
}
}
if deployAzureDir == "" {
deployAzureDir = "."
}
if err := os.MkdirAll(deployAzureDir, 0755); err != nil {
return fmt.Errorf("failed to create directory %s: %w", deployAzureDir, err)
}
// ── Interactive image-source prompt (when no explicit flag set) ──
if !cmd.Flags().Changed("official") && !cmd.Flags().Changed("repo-url") {
imageChoices := []string{
"official - Apache DevLake images from Docker Hub (recommended)",
"fork - Clone a DevLake repo and build from source",
"custom - Use a local repo or pre-built images",
}
fmt.Println()
imgChoice := prompt.Select("Which DevLake images to use?", imageChoices)
if imgChoice == "" {
return fmt.Errorf("image choice is required")
}
switch {
case strings.HasPrefix(imgChoice, "official"):
azureOfficial = true
case strings.HasPrefix(imgChoice, "fork"):
azureOfficial = false
if azureRepoURL == "" {
azureRepoURL = prompt.ReadLine(fmt.Sprintf("Repository URL [%s]", gitclone.DefaultForkURL))
if azureRepoURL == "" {
azureRepoURL = gitclone.DefaultForkURL
}
}
default: // custom
azureOfficial = false
if azureRepoURL == "" {
azureRepoURL = prompt.ReadLine("Path or URL to DevLake repo (leave blank to auto-detect)")
}
}
}
// ── Interactive prompts for missing required flags ──
if azureLocation == "" {
azureLocation = prompt.SelectWithOther("Select Azure region", azureRegions, true)
if azureLocation == "" {
return fmt.Errorf("--location is required")
}
}
if azureRG == "" {
azureRG = prompt.ReadLine("Resource group name (e.g. devlake-rg)")
if azureRG == "" {
return fmt.Errorf("--resource-group is required")
}
}
suffix := azure.Suffix(azureRG)
acrName := "devlakeacr" + suffix
fmt.Println()
if azureOfficial {
printBanner("DevLake Azure Deployment (Official)")
fmt.Println("\nUsing official Apache DevLake images from Docker Hub")
azureSkipImageBuild = true
} else {
printBanner("DevLake Azure Deployment")
}
fmt.Printf("\n📋 Configuration:\n")
fmt.Printf(" Resource Group: %s\n", azureRG)
fmt.Printf(" Location: %s\n", azureLocation)
fmt.Printf(" Base Name: %s\n", azureBaseName)
if !azureOfficial {
fmt.Printf(" ACR Name: %s\n", acrName)
} else {
fmt.Println(" Images: Official (Docker Hub)")
}
// ── Check Azure login ──
fmt.Println("\n🔑 Checking Azure CLI login...")
acct, err := azure.CheckLogin()
if err != nil {
// Bounded recovery: Auto-login (single attempt)
fmt.Println(" ❌ Not logged in")
fmt.Println("\n🔧 Recovery: Running az login...")
if loginErr := azure.Login(); loginErr != nil {
return fmt.Errorf("az login failed: %w", loginErr)
}
acct, err = azure.CheckLogin()
if err != nil {
return fmt.Errorf("still not logged in after az login: %w", err)
}
fmt.Println(" ✅ Recovery successful")
}
fmt.Printf(" Logged in as: %s\n", acct.User.Name)
// ── Create Resource Group ──
fmt.Println("\n📦 Creating Resource Group...")
if err := azure.CreateResourceGroup(azureRG, azureLocation); err != nil {
return err
}
fmt.Println(" ✅ Resource Group created")
// ── Write early checkpoint — ensures cleanup works even if deployment fails ──
savePartialAzureState(azureRG, azureLocation)
// ── Generate secrets ──
fmt.Println("\n🔐 Generating secrets...")
mysqlPwd, err := secrets.MySQLPassword()
if err != nil {
return err
}
encSecret, err := secrets.EncryptionSecret(32)
if err != nil {
return err
}
fmt.Println(" ✅ Secrets generated")
// ── Build and push images (if needed) ──
if !azureSkipImageBuild {
repoRoot, err := findRepoRoot()
if err != nil {
return err
}
if azureRepoURL != "" {
defer os.RemoveAll(repoRoot)
if err := applyPoetryPinWorkaround(repoRoot); err != nil {
fmt.Printf(" ⚠️ Could not apply temporary Poetry pin workaround: %v\n", err)
} else {
fmt.Printf(" ⚠️ Applied temporary Poetry pin workaround (poetry==%s) for fork builds\n", poetryWorkaroundVersion)
}
}
fmt.Printf("\n🏗️ Building Docker images from %s...\n", repoRoot)
// Create ACR (idempotent — safe for re-runs)
fmt.Println(" Creating Container Registry...")
if err := azure.CreateACR(acrName, azureRG, azureLocation); err != nil {
return fmt.Errorf("failed to create ACR: %w", err)
}
fmt.Println(" ✅ Container Registry ready")
acrServer := acrName + ".azurecr.io"
fmt.Println("\n Logging into ACR...")
if err := azure.ACRLogin(acrName); err != nil {
return err
}
images := []struct {
name string
dockerfile string
context string
}{
{"devlake-backend", "backend/Dockerfile", filepath.Join(repoRoot, "backend")},
{"devlake-config-ui", "config-ui/Dockerfile", filepath.Join(repoRoot, "config-ui")},
{"devlake-grafana", "grafana/Dockerfile", filepath.Join(repoRoot, "grafana")},
}
for _, img := range images {
fmt.Printf("\n Building %s...\n", img.name)
localTag := img.name + ":latest"
if err := dockerpkg.Build(localTag, filepath.Join(repoRoot, img.dockerfile), img.context); err != nil {
fmt.Fprintf(os.Stderr, "\n ❌ Docker build failed for %s.\n", img.name)
fmt.Fprintf(os.Stderr, " Tip: re-run with --official to skip building and use\n")
fmt.Fprintf(os.Stderr, " official Apache DevLake images from Docker Hub instead.\n")
return fmt.Errorf("docker build failed for %s: %w", img.name, err)
}
remoteTag := acrServer + "/" + localTag
fmt.Printf(" Pushing %s...\n", img.name)
if err := dockerpkg.TagAndPush(localTag, remoteTag); err != nil {
return err
}
}
fmt.Println("\n ✅ All images pushed")
}
// ── Check MySQL state ──
mysqlName := fmt.Sprintf("%smysql%s", azureBaseName, suffix)
fmt.Println("\n🗄️ Checking MySQL state...")
state, err := azure.MySQLState(mysqlName, azureRG)
if err == nil && state == "Stopped" {
// Bounded recovery: Start stopped MySQL (single attempt)
fmt.Println(" ❌ MySQL is stopped")
fmt.Println("\n🔧 Recovery: Starting MySQL...")
if err := azure.MySQLStart(mysqlName, azureRG); err != nil {
fmt.Printf(" ⚠️ Could not start MySQL: %v\n", err)
fmt.Println(" Continuing deployment — MySQL may start later")
} else {
fmt.Println(" Waiting 30s for MySQL...")
time.Sleep(30 * time.Second)
fmt.Println(" ✅ MySQL started")
}
} else if state != "" {
fmt.Printf(" MySQL state: %s\n", state)
} else {
fmt.Println(" MySQL not yet created (will be created by Bicep)")
}
// ── Check for soft-deleted Key Vault ──
kvName := fmt.Sprintf("%skv%s", azureBaseName, suffix)
found, _ := azure.CheckSoftDeletedKeyVault(kvName)
if found {
// Bounded recovery: Purge soft-deleted Key Vault (single attempt)
fmt.Printf("\n🔑 Key Vault conflict detected\n")
fmt.Printf(" Key Vault %q is in soft-deleted state\n", kvName)
fmt.Println("\n🔧 Recovery: Purging soft-deleted Key Vault...")
if err := azure.PurgeKeyVault(kvName, azureLocation); err != nil {
return fmt.Errorf("failed to purge soft-deleted Key Vault %q: %w\nManual fix: az keyvault purge --name %s --location %s", kvName, err, kvName, azureLocation)
}
fmt.Println(" ✅ Key Vault purged — deployment can proceed")
}
// ── Deploy infrastructure ──
fmt.Println("\n🚀 Deploying infrastructure with Bicep...")
templateName := "main.bicep"
if azureOfficial {
templateName = "main-official.bicep"
}
templatePath, cleanup, err := azure.WriteTemplate(templateName)
if err != nil {
return err
}
defer cleanup()
params := map[string]string{
"baseName": azureBaseName,
"uniqueSuffix": suffix,
"mysqlAdminPassword": mysqlPwd,
"encryptionSecret": encSecret,
}
if !azureOfficial {
params["acrName"] = acrName
}
deployment, err := azure.DeployBicep(azureRG, templatePath, params)
if err != nil {
return fmt.Errorf("Bicep deployment failed: %w", err)
}
printBanner("✅ Deployment Complete!")
fmt.Printf("\nEndpoints:\n")
fmt.Printf(" Backend API: %s\n", deployment.BackendEndpoint)
fmt.Printf(" Config UI: %s\n", deployment.ConfigUIEndpoint)
fmt.Printf(" Grafana: %s\n", deployment.GrafanaEndpoint)
// ── Wait for backend and trigger migration ──
fmt.Println("\n⏳ Waiting for backend to start...")
backendReady := waitForReady(deployment.BackendEndpoint, 30, 10*time.Second) == nil
if backendReady {
fmt.Println(" ✅ Backend is responding!")
fmt.Println("\n🔄 Triggering database migration...")
httpClient := &http.Client{Timeout: 5 * time.Second}
resp, err := httpClient.Get(deployment.BackendEndpoint + "/proceed-db-migration")
if err == nil {
resp.Body.Close()
fmt.Println(" ✅ Migration triggered")
} else {
fmt.Printf(" ⚠️ Migration may need manual trigger: %v\n", err)
}
} else {
fmt.Println(" Backend not ready after 30 attempts.")
fmt.Printf(" Trigger migration manually: GET %s/proceed-db-migration\n", deployment.BackendEndpoint)
}
// ── Save state file ──
stateFile := filepath.Join(deployAzureDir, ".devlake-azure.json")
containers := []string{
fmt.Sprintf("%s-backend-%s", azureBaseName, suffix),
fmt.Sprintf("%s-grafana-%s", azureBaseName, suffix),
fmt.Sprintf("%s-ui-%s", azureBaseName, suffix),
}
kvName = deployment.KeyVaultName
if kvName == "" {
kvName = fmt.Sprintf("%skv%s", azureBaseName, suffix)
}
// Write a combined state file: Azure-specific metadata + DevLake discovery fields
combinedState := map[string]any{
"deployedAt": time.Now().Format(time.RFC3339),
"method": methodName(),
"subscription": acct.Name,
"subscriptionId": acct.ID,
"resourceGroup": azureRG,
"region": azureLocation,
"suffix": suffix,
"useOfficialImages": azureOfficial,
"resources": map[string]any{
"acr": conditionalACR(),
"keyVault": kvName,
"mysql": mysqlName,
"database": "lake",
"containers": containers,
},
"endpoints": map[string]string{
"backend": deployment.BackendEndpoint,
"grafana": deployment.GrafanaEndpoint,
"configUi": deployment.ConfigUIEndpoint,
},
}
data, _ := json.MarshalIndent(combinedState, "", " ")
if err := os.WriteFile(stateFile, data, 0644); err != nil {
fmt.Fprintf(os.Stderr, "⚠️ Could not save state file: %v\n", err)
} else {
fmt.Printf("\n💾 State saved to %s\n", stateFile)
if deployAzureDir != "." {
fmt.Println(" Next commands should be run from this directory:")
fmt.Println(" PowerShell:")
fmt.Printf(" Set-Location \"%s\"\n", deployAzureDir)
fmt.Println(" Bash/Zsh:")
fmt.Printf(" cd \"%s\"\n", deployAzureDir)
}
}
if !deployAzureQuiet {
fmt.Println("\nNext steps:")
fmt.Println(" 1. Wait 2-3 minutes for containers to start")
fmt.Printf(" 2. Open Config UI: %s\n", deployment.ConfigUIEndpoint)
fmt.Println(" 3. Configure your data sources")
fmt.Printf("\nTo cleanup: gh devlake cleanup --azure\n")
}
return nil
}
func findRepoRoot() (string, error) {
if azureRepoURL != "" {
tmpDir, err := os.MkdirTemp("", "devlake-clone-*")
if err != nil {
return "", err
}
fmt.Printf(" Cloning %s...\n", azureRepoURL)
if err := gitclone.Clone(azureRepoURL, tmpDir); err != nil {
return "", err
}
return tmpDir, nil
}
// Walk up looking for backend/Dockerfile
dir, _ := os.Getwd()
for dir != "" && dir != filepath.Dir(dir) {
if _, err := os.Stat(filepath.Join(dir, "backend", "Dockerfile")); err == nil {
return dir, nil
}
dir = filepath.Dir(dir)
}
return "", fmt.Errorf("could not find DevLake repo root.\n" +
"Options:\n" +
" --repo-url <url> Clone a fork with the custom Dockerfile\n" +
" --official Use official Apache images (no build needed)")
}
func methodName() string {
if azureOfficial {
return "bicep-official"
}
return "bicep"
}
func conditionalACR() any {
if azureOfficial {
return nil
}
return "devlakeacr" + azure.Suffix(azureRG)
}
// savePartialAzureState writes a minimal state file immediately after the
// Resource Group is created so that cleanup --azure always has a breadcrumb,
// even when the deployment fails mid-flight (e.g. Docker build errors).
// The full state write at the end of a successful deployment overwrites this.
func savePartialAzureState(rg, region string) {
stateFile := ".devlake-azure.json"
partial := map[string]any{
"deployedAt": time.Now().Format(time.RFC3339),
"resourceGroup": rg,
"region": region,
"partial": true,
}
data, _ := json.MarshalIndent(partial, "", " ")
if err := os.WriteFile(stateFile, data, 0644); err != nil {
fmt.Fprintf(os.Stderr, "⚠️ Could not save early state checkpoint: %v\n", err)
}
}