-
Notifications
You must be signed in to change notification settings - Fork 67
/
docker.go
507 lines (411 loc) · 12.8 KB
/
docker.go
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
package airflow
import (
"bytes"
"context"
"crypto/md5"
"fmt"
"html/template"
"os"
"strconv"
"strings"
"text/tabwriter"
"github.com/docker/libcompose/cli/logger"
dockercompose "github.com/docker/libcompose/docker"
"github.com/docker/libcompose/docker/ctx"
"github.com/docker/libcompose/project"
"github.com/docker/libcompose/project/options"
"github.com/pkg/errors"
"github.com/astronomer/astro-cli/airflow/include"
"github.com/astronomer/astro-cli/config"
"github.com/astronomer/astro-cli/docker"
"github.com/astronomer/astro-cli/houston"
"github.com/astronomer/astro-cli/messages"
"github.com/astronomer/astro-cli/pkg/fileutil"
"github.com/astronomer/astro-cli/pkg/input"
"github.com/astronomer/astro-cli/pkg/printutil"
"github.com/astronomer/astro-cli/settings"
)
const (
componentName = "airflow"
deployTagPrefix = "cli-"
dockerStateUp = "Up"
dockerStateExited = "Exited"
)
var (
tab = printutil.Table{
Padding: []int{5, 30, 30, 50},
DynamicPadding: true,
Header: []string{"#", "LABEL", "DEPLOYMENT NAME", "WORKSPACE", "DEPLOYMENT ID"},
}
)
// ComposeConfig is input data to docker compose yaml template
type ComposeConfig struct {
PostgresUser string
PostgresPassword string
PostgresHost string
PostgresPort string
AirflowEnvFile string
AirflowImage string
AirflowHome string
AirflowUser string
AirflowWebserverPort string
}
// projectNameUnique creates a reasonably unique project name based on the hashed
// path of the project. This prevents collisions of projects with identical dir names
// in different paths. ie (~/dev/project1 vs ~/prod/project1)
func projectNameUnique() (string, error) {
projectName := config.CFG.ProjectName.GetString()
pwd, err := fileutil.GetWorkingDir()
if err != nil {
return "", errors.Wrap(err, "error retrieving working directory")
}
b := md5.Sum([]byte(pwd))
s := fmt.Sprintf("%x", b[:])
return projectName + "_" + s[0:6], nil
}
// repositoryName creates an airflow repository name
func repositoryName(name string) string {
return fmt.Sprintf("%s/%s", name, componentName)
}
// imageName creates an airflow image name
func imageName(name, tag string) string {
return fmt.Sprintf("%s:%s", repositoryName(name), tag)
}
// imageBuild builds the airflow project
func imageBuild(path, imageName string) error {
// Change to location of Dockerfile
os.Chdir(path)
// Build image
err := docker.Exec("build", "-t", imageName, ".")
if err != nil {
return errors.Wrapf(err, "command 'docker build -t %s failed", imageName)
}
return nil
}
// generateConfig generates the docker-compose config
func generateConfig(projectName, airflowHome string, envFile string) (string, error) {
tmpl, err := template.New("yml").Parse(include.Composeyml)
if err != nil {
return "", errors.Wrap(err, "failed to generate config")
}
envExists, err := fileutil.Exists(envFile)
if err != nil {
return "", errors.Wrap(err, fmt.Sprintf(messages.ENV_PATH, envFile))
}
if envFile != "" {
if !envExists {
fmt.Printf(messages.ENV_NOT_FOUND, envFile)
envFile = ""
} else {
fmt.Printf(messages.ENV_FOUND, envFile)
envFile = fmt.Sprintf("env_file: %s", envFile)
}
}
config := ComposeConfig{
PostgresUser: config.CFG.PostgresUser.GetString(),
PostgresPassword: config.CFG.PostgresPassword.GetString(),
PostgresHost: config.CFG.PostgresHost.GetString(),
PostgresPort: config.CFG.PostgresPort.GetString(),
AirflowImage: imageName(projectName, "latest"),
AirflowHome: airflowHome,
AirflowUser: "astro",
AirflowWebserverPort: config.CFG.WebserverPort.GetString(),
AirflowEnvFile: envFile,
}
buff := new(bytes.Buffer)
err = tmpl.Execute(buff, config)
if err != nil {
return "", errors.Wrap(err, "failed to generate config")
}
return buff.String(), nil
}
func checkServiceState(serviceState, expectedState string) bool {
scrubbedState := strings.Split(serviceState, " ")[0]
if scrubbedState == expectedState {
return true
}
return false
}
// createProject creates project with yaml config as context
func createProject(projectName, airflowHome string, envFile string) (project.APIProject, error) {
// Generate the docker-compose yaml
yaml, err := generateConfig(projectName, airflowHome, envFile)
if err != nil {
return nil, errors.Wrap(err, "failed to create project")
}
// Create the project
project, err := dockercompose.NewProject(&ctx.Context{
Context: project.Context{
ComposeBytes: [][]byte{[]byte(yaml)},
ProjectName: projectName,
LoggerFactory: logger.NewColorLoggerFactory(),
},
}, nil)
return project, err
}
// Start starts a local airflow development cluster
func Start(airflowHome string, envFile string) error {
// Get project name from config
projectName, err := projectNameUnique()
replacer := strings.NewReplacer("_", "", "-", "")
strippedProjectName := replacer.Replace(projectName)
if err != nil {
return errors.Wrap(err, "error retrieving working directory")
}
// Create a libcompose project
project, err := createProject(projectName, airflowHome, envFile)
if err != nil {
return errors.Wrap(err, messages.COMPOSE_CREATE_ERROR)
}
// Get project containers
psInfo, err := project.Ps(context.Background())
if err != nil {
return errors.Wrap(err, messages.COMPOSE_STATUS_CHECK_ERROR)
}
if len(psInfo) > 0 {
// Ensure project is not already running
for _, info := range psInfo {
if checkServiceState(info["State"], dockerStateUp) {
return errors.New("cannot start, project already running")
}
}
err = imageBuild(airflowHome, imageName(projectName, "latest"))
if err != nil {
return err
}
err = project.Up(context.Background(), options.Up{})
if err != nil {
return errors.Wrap(err, messages.COMPOSE_RECREATE_ERROR)
}
} else {
// Build this project image
err = imageBuild(airflowHome, imageName(projectName, "latest"))
if err != nil {
return err
}
// Start up our project
err = project.Up(context.Background(), options.Up{})
if err != nil {
return errors.Wrap(err, messages.COMPOSE_RECREATE_ERROR)
}
}
psInfo, err = project.Ps(context.Background())
if err != nil {
return errors.Wrap(err, messages.COMPOSE_STATUS_CHECK_ERROR)
}
fileState, err := fileutil.Exists("airflow_settings.yaml")
if err != nil {
return errors.Wrap(err, messages.SETTINGS_PATH)
}
if fileState {
for _, info := range psInfo {
if strings.Contains(info["Name"], strippedProjectName) &&
strings.Contains(info["Name"], "webserver") {
settings.ConfigSettings(info["Id"])
}
}
}
parts := strings.Split(config.CFG.WebserverPort.GetString(), ":")
fmt.Printf(messages.COMPOSE_LINK_WEBSERVER+"\n", parts[len(parts)-1])
fmt.Printf(messages.COMPOSE_LINK_POSTGRES+"\n", config.CFG.PostgresPort.GetString())
return nil
}
// Kill stops a local airflow development cluster
func Kill(airflowHome string) error {
// Get project name from config
projectName, err := projectNameUnique()
if err != nil {
return errors.Wrap(err, "error retrieving working directory")
}
// Create a libcompose project
project, err := createProject(projectName, airflowHome, "")
if err != nil {
return errors.Wrap(err, messages.COMPOSE_CREATE_ERROR)
}
// Shut down our project
err = project.Down(context.Background(), options.Down{RemoveVolume: true, RemoveOrphans: true})
if err != nil {
return errors.Wrap(err, messages.COMPOSE_STOP_ERROR)
}
return nil
}
// Logs out airflow webserver or scheduler logs
func Logs(airflowHome string, webserver, scheduler, follow bool) error {
s := make([]string, 0)
// Get project name from config
projectName := config.CFG.ProjectName.GetString()
// Create libcompose project
project, err := createProject(projectName, airflowHome, "")
if err != nil {
return errors.Wrap(err, messages.COMPOSE_CREATE_ERROR)
}
psInfo, err := project.Ps(context.Background())
if err != nil {
return errors.Wrap(err, messages.COMPOSE_STATUS_CHECK_ERROR)
}
if len(psInfo) == 0 {
return errors.Wrap(err, "cannot view logs, project not running")
}
if scheduler {
s = append(s, "scheduler")
}
if webserver {
s = append(s, "webserver")
}
err = project.Log(context.Background(), follow, s...)
if err != nil {
return err
}
return nil
}
// Stop a running docker project
func Stop(airflowHome string) error {
// Get project name from config
projectName, err := projectNameUnique()
if err != nil {
return errors.Wrap(err, "error retrieving working directory")
}
// Create a libcompose project
project, err := createProject(projectName, airflowHome, "")
if err != nil {
return errors.Wrap(err, messages.COMPOSE_CREATE_ERROR)
}
// Pause our project
err = project.Stop(context.Background(), 5)
if err != nil {
return errors.Wrap(err, messages.COMPOSE_PAUSE_ERROR)
}
return nil
}
// PS prints the running airflow containers
func PS(airflowHome string) error {
// Get project name from config
projectName, err := projectNameUnique()
if err != nil {
return errors.Wrap(err, "error retrieving working directory")
}
// Create a libcompose project
project, err := createProject(projectName, airflowHome, "")
if err != nil {
return errors.Wrap(err, messages.COMPOSE_CREATE_ERROR)
}
// List project containers
psInfo, err := project.Ps(context.Background())
if err != nil {
return errors.Wrap(err, messages.COMPOSE_STATUS_CHECK_ERROR)
}
// Columns for table
infoColumns := []string{"Name", "State", "Ports"}
// Create a new tabwriter
tw := new(tabwriter.Writer)
tw.Init(os.Stdout, 0, 8, 2, '\t', tabwriter.AlignRight)
// Append data to table
fmt.Fprintln(tw, strings.Join(infoColumns, "\t"))
for _, info := range psInfo {
data := []string{}
for _, lbl := range infoColumns {
data = append(data, info[lbl])
}
fmt.Fprintln(tw, strings.Join(data, "\t"))
}
// Flush to stdout
return tw.Flush()
}
// Deploy pushes a new docker image
func Deploy(path, name, wsId string, prompt bool) error {
if len(wsId) == 0 {
return errors.New("no workspace id provided")
}
// Validate workspace
wsReq := houston.Request{
Query: houston.WorkspacesGetRequest,
Variables: map[string]interface{}{"workspaceId": wsId},
}
wsResp, err := wsReq.Do()
if err != nil {
return err
}
if len(wsResp.Data.GetWorkspaces) == 0 {
return fmt.Errorf("no workspaces with id (%s) found", wsId)
}
w := wsResp.Data.GetWorkspaces[0]
// Get Deployments from workspace ID
deReq := houston.Request{
Query: houston.DeploymentsGetRequest,
Variables: map[string]interface{}{"workspaceId": w.Id},
}
deResp, err := deReq.Do()
if err != nil {
return err
}
deployments := deResp.Data.GetDeployments
c, err := config.GetCurrentContext()
if err != nil {
return err
}
cloudDomain := c.Domain
if len(cloudDomain) == 0 {
return errors.New("No domain set, re-authenticate.")
}
// Use config deployment if provided
if len(name) == 0 {
name = config.CFG.ProjectDeployment.GetProjectString()
}
// Prompt user for deployment if no deployment passed in
if len(name) == 0 || prompt {
if len(deployments) == 0 {
return errors.New(messages.HOUSTON_NO_DEPLOYMENTS_ERROR)
}
fmt.Printf(messages.HOUSTON_DEPLOYMENT_HEADER, cloudDomain)
fmt.Println(messages.HOUSTON_SELECT_DEPLOYMENT_PROMPT)
deployMap := map[string]houston.Deployment{}
for i, d := range deployments {
index := i + 1
tab.AddRow([]string{strconv.Itoa(index), d.Label, d.ReleaseName, w.Label, d.Id}, false)
deployMap[strconv.Itoa(index)] = d
}
tab.Print()
choice := input.InputText("\n> ")
selected, ok := deployMap[choice]
if !ok {
return errors.New(messages.HOUSTON_INVALID_DEPLOYMENT_KEY)
}
name = selected.ReleaseName
}
nextTag := ""
for _, deployment := range deployments {
if deployment.ReleaseName == name {
nextTag = deployment.DeploymentInfo.Next
}
}
fmt.Printf(messages.HOUSTON_DEPLOYING_PROMPT, name)
fmt.Println(repositoryName(name))
// Build the image to deploy
// We use latest and keep this tag around after deployments to keep subsequent deploys quick
deployImage := imageName(name, "latest")
// Build our image
fmt.Println(messages.COMPOSE_IMAGE_BUILDING_PROMT)
err = imageBuild(path, deployImage)
if err != nil {
return err
}
registry := "registry." + cloudDomain
remoteImage := fmt.Sprintf("%s/%s",
registry, imageName(name, nextTag))
err = docker.Exec("tag", deployImage, remoteImage)
if err != nil {
return errors.Wrapf(err, "command 'docker tag %s %s' failed", deployImage, remoteImage)
}
// Push image to registry
fmt.Println(messages.COMPOSE_PUSHING_IMAGE_PROMPT)
err = docker.Exec("push", remoteImage)
if err != nil {
return errors.Wrapf(err, "command 'docker push %s' failed", remoteImage)
}
// Delete the image tags we just generated
err = docker.Exec("rmi", remoteImage)
if err != nil {
return errors.Wrapf(err, "command 'docker rmi %s' failed", remoteImage)
}
return nil
}