-
Notifications
You must be signed in to change notification settings - Fork 173
/
framework_service_docker.go
463 lines (404 loc) · 13.6 KB
/
framework_service_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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package project
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"os"
"path"
"path/filepath"
"strings"
"github.com/azure/azure-dev/cli/azd/internal/appdetect"
"github.com/azure/azure-dev/cli/azd/internal/tracing"
"github.com/azure/azure-dev/cli/azd/internal/tracing/events"
"github.com/azure/azure-dev/cli/azd/internal/tracing/fields"
"github.com/azure/azure-dev/cli/azd/pkg/alpha"
"github.com/azure/azure-dev/cli/azd/pkg/async"
"github.com/azure/azure-dev/cli/azd/pkg/environment"
"github.com/azure/azure-dev/cli/azd/pkg/exec"
"github.com/azure/azure-dev/cli/azd/pkg/input"
"github.com/azure/azure-dev/cli/azd/pkg/osutil"
"github.com/azure/azure-dev/cli/azd/pkg/output"
"github.com/azure/azure-dev/cli/azd/pkg/tools"
"github.com/azure/azure-dev/cli/azd/pkg/tools/azcli"
"github.com/azure/azure-dev/cli/azd/pkg/tools/docker"
"github.com/azure/azure-dev/cli/azd/pkg/tools/pack"
"go.opentelemetry.io/otel/trace"
)
type DockerProjectOptions struct {
Registry string `yaml:"registry,omitempty" json:"registry,omitempty"`
Path string `yaml:"path,omitempty" json:"path,omitempty"`
Context string `yaml:"context,omitempty" json:"context,omitempty"`
Platform string `yaml:"platform,omitempty" json:"platform,omitempty"`
Target string `yaml:"target,omitempty" json:"target,omitempty"`
Tag osutil.ExpandableString `yaml:"tag,omitempty" json:"tag,omitempty"`
BuildArgs []string `yaml:"buildArgs,omitempty" json:"buildArgs,omitempty"`
}
type dockerBuildResult struct {
ImageId string `json:"imageId"`
ImageName string `json:"imageName"`
}
func (dbr *dockerBuildResult) ToString(currentIndentation string) string {
lines := []string{
fmt.Sprintf("%s- Image ID: %s", currentIndentation, output.WithLinkFormat(dbr.ImageId)),
fmt.Sprintf("%s- Image Name: %s", currentIndentation, output.WithLinkFormat(dbr.ImageName)),
}
return strings.Join(lines, "\n")
}
func (dbr *dockerBuildResult) MarshalJSON() ([]byte, error) {
return json.Marshal(*dbr)
}
type dockerPackageResult struct {
ImageHash string `json:"imageHash"`
ImageTag string `json:"imageTag"`
}
func (dpr *dockerPackageResult) ToString(currentIndentation string) string {
lines := []string{
fmt.Sprintf("%s- Image Hash: %s", currentIndentation, output.WithLinkFormat(dpr.ImageHash)),
fmt.Sprintf("%s- Image Tag: %s", currentIndentation, output.WithLinkFormat(dpr.ImageTag)),
}
return strings.Join(lines, "\n")
}
func (dpr *dockerPackageResult) MarshalJSON() ([]byte, error) {
return json.Marshal(*dpr)
}
type dockerProject struct {
env *environment.Environment
docker docker.Docker
framework FrameworkService
containerHelper *ContainerHelper
console input.Console
alphaFeatureManager *alpha.FeatureManager
commandRunner exec.CommandRunner
}
// NewDockerProject creates a new instance of a Azd project that
// leverages docker for building
func NewDockerProject(
env *environment.Environment,
docker docker.Docker,
containerHelper *ContainerHelper,
console input.Console,
alphaFeatureManager *alpha.FeatureManager,
commandRunner exec.CommandRunner,
) CompositeFrameworkService {
return &dockerProject{
env: env,
docker: docker,
containerHelper: containerHelper,
console: console,
alphaFeatureManager: alphaFeatureManager,
commandRunner: commandRunner,
framework: NewNoOpProject(env),
}
}
// NewDockerProjectAsFrameworkService is the same as NewDockerProject().(FrameworkService) and exists to support our
// use of DI and ServiceLocators, where we sometimes need to resolve this type as a FrameworkService instance instead
// of a CompositeFrameworkService as [NewDockerProject] does.
func NewDockerProjectAsFrameworkService(
env *environment.Environment,
docker docker.Docker,
containerHelper *ContainerHelper,
console input.Console,
alphaFeatureManager *alpha.FeatureManager,
commandRunner exec.CommandRunner,
) FrameworkService {
return NewDockerProject(env, docker, containerHelper, console, alphaFeatureManager, commandRunner)
}
func (p *dockerProject) Requirements() FrameworkRequirements {
return FrameworkRequirements{
Package: FrameworkPackageRequirements{
RequireRestore: false,
// Docker project needs to build a container image
RequireBuild: true,
},
}
}
// Gets the required external tools for the project
func (p *dockerProject) RequiredExternalTools(context.Context) []tools.ExternalTool {
return []tools.ExternalTool{p.docker}
}
// Initializes the docker project
func (p *dockerProject) Initialize(ctx context.Context, serviceConfig *ServiceConfig) error {
return p.framework.Initialize(ctx, serviceConfig)
}
// Sets the inner framework service used for restore and build command
func (p *dockerProject) SetSource(inner FrameworkService) {
p.framework = inner
}
// Restores the dependencies for the docker project
func (p *dockerProject) Restore(
ctx context.Context,
serviceConfig *ServiceConfig,
) *async.TaskWithProgress[*ServiceRestoreResult, ServiceProgress] {
// When the program runs the restore actions for the underlying project (containerapp),
// the dependencies are installed locally
return p.framework.Restore(ctx, serviceConfig)
}
// Builds the docker project based on the docker options specified within the Service configuration
func (p *dockerProject) Build(
ctx context.Context,
serviceConfig *ServiceConfig,
restoreOutput *ServiceRestoreResult,
) *async.TaskWithProgress[*ServiceBuildResult, ServiceProgress] {
return async.RunTaskWithProgress(
func(task *async.TaskContextWithProgress[*ServiceBuildResult, ServiceProgress]) {
dockerOptions := getDockerOptionsWithDefaults(serviceConfig.Docker)
buildArgs := []string{}
for _, arg := range dockerOptions.BuildArgs {
buildArgs = append(buildArgs, exec.RedactSensitiveData(arg))
}
log.Printf(
"building image for service %s, cwd: %s, path: %s, context: %s, buildArgs: %s)",
serviceConfig.Name,
serviceConfig.Path(),
dockerOptions.Path,
dockerOptions.Context,
buildArgs,
)
imageName := fmt.Sprintf(
"%s-%s",
strings.ToLower(serviceConfig.Project.Name),
strings.ToLower(serviceConfig.Name),
)
path := dockerOptions.Path
if !filepath.IsAbs(path) {
path = filepath.Join(serviceConfig.Path(), path)
}
_, err := os.Stat(path)
if err != nil && !errors.Is(err, os.ErrNotExist) {
task.SetError(fmt.Errorf("reading dockerfile: %w", err))
return
}
if errors.Is(err, os.ErrNotExist) {
// Build the container from source
task.SetProgress(NewServiceProgress("Building Docker image from source"))
res, err := p.packBuild(ctx, serviceConfig, dockerOptions, imageName)
if err != nil {
task.SetError(err)
return
}
res.Restore = restoreOutput
task.SetResult(res)
return
}
// Build the container
task.SetProgress(NewServiceProgress("Building Docker image"))
previewerWriter := p.console.ShowPreviewer(ctx,
&input.ShowPreviewerOptions{
Prefix: " ",
MaxLineCount: 8,
Title: "Docker Output",
})
imageId, err := p.docker.Build(
ctx,
serviceConfig.Path(),
dockerOptions.Path,
dockerOptions.Platform,
dockerOptions.Target,
dockerOptions.Context,
imageName,
dockerOptions.BuildArgs,
previewerWriter,
)
p.console.StopPreviewer(ctx, false)
if err != nil {
task.SetError(fmt.Errorf("building container: %s at %s: %w", serviceConfig.Name, dockerOptions.Context, err))
return
}
log.Printf("built image %s for %s", imageId, serviceConfig.Name)
task.SetResult(&ServiceBuildResult{
Restore: restoreOutput,
BuildOutputPath: imageId,
Details: &dockerBuildResult{
ImageId: imageId,
ImageName: imageName,
},
})
},
)
}
func (p *dockerProject) Package(
ctx context.Context,
serviceConfig *ServiceConfig,
buildOutput *ServiceBuildResult,
) *async.TaskWithProgress[*ServicePackageResult, ServiceProgress] {
return async.RunTaskWithProgress(
func(task *async.TaskContextWithProgress[*ServicePackageResult, ServiceProgress]) {
imageId := buildOutput.BuildOutputPath
if imageId == "" {
task.SetError(errors.New("missing container image id from build output"))
return
}
localTag, err := p.containerHelper.LocalImageTag(ctx, serviceConfig)
if err != nil {
task.SetError(fmt.Errorf("generating local image tag: %w", err))
return
}
// Tag image.
log.Printf("tagging image %s as %s", imageId, localTag)
task.SetProgress(NewServiceProgress("Tagging Docker image"))
if err := p.docker.Tag(ctx, serviceConfig.Path(), imageId, localTag); err != nil {
task.SetError(fmt.Errorf("tagging image: %w", err))
return
}
task.SetResult(&ServicePackageResult{
Build: buildOutput,
PackagePath: localTag,
Details: &dockerPackageResult{
ImageHash: imageId,
ImageTag: localTag,
},
})
},
)
}
// Default builder image to produce container images from source
const DefaultBuilderImage = "mcr.microsoft.com/oryx/builder:debian-bullseye-20231107.2"
func (p *dockerProject) packBuild(
ctx context.Context,
svc *ServiceConfig,
dockerOptions DockerProjectOptions,
imageName string) (*ServiceBuildResult, error) {
packCli, err := pack.NewPackCli(ctx, p.console, p.commandRunner)
if err != nil {
return nil, err
}
builder := DefaultBuilderImage
environ := []string{}
userDefinedImage := false
if os.Getenv("AZD_BUILDER_IMAGE") != "" {
builder = os.Getenv("AZD_BUILDER_IMAGE")
userDefinedImage = true
}
if !userDefinedImage {
// Always default to port 80 for consistency across languages
environ = append(environ, "ORYX_RUNTIME_PORT=80")
if svc.OutputPath != "" && (svc.Language == ServiceLanguageTypeScript || svc.Language == ServiceLanguageJavaScript) {
inDockerOutputPath := path.Join("/workspace", svc.OutputPath)
// A dist folder has been set.
// We assume that the service is a front-end service, configuring a nginx web server to serve the static content
// produced.
environ = append(environ,
"ORYX_RUNTIME_IMAGE=nginx:1.25.2-bookworm",
fmt.Sprintf(
//nolint:lll
"ORYX_RUNTIME_SCRIPT=[ -d \"%s\" ] || { echo \"error: directory '%s' does not exist. ensure the 'dist' path in azure.yaml is specified correctly.\"; exit 1; } && "+
"rm -rf /usr/share/nginx/html && ln -sT %s /usr/share/nginx/html && "+
"nginx -g 'daemon off;'",
inDockerOutputPath,
svc.OutputPath,
inDockerOutputPath,
))
}
if svc.Language == ServiceLanguagePython {
pyEnviron, err := getEnvironForPython(ctx, svc)
if err != nil {
return nil, err
}
if len(pyEnviron) > 0 {
environ = append(environ, pyEnviron...)
}
}
}
previewer := p.console.ShowPreviewer(ctx,
&input.ShowPreviewerOptions{
Prefix: " ",
MaxLineCount: 8,
Title: "Docker (pack) Output",
})
ctx, span := tracing.Start(
ctx,
events.PackBuildEvent,
trace.WithAttributes(fields.ProjectServiceLanguageKey.String(string(svc.Language))))
img, tag := docker.SplitDockerImage(builder)
if userDefinedImage {
span.SetAttributes(
fields.StringHashed(fields.PackBuilderImage, img),
fields.StringHashed(fields.PackBuilderTag, tag),
)
} else {
span.SetAttributes(
fields.PackBuilderImage.String(img),
fields.PackBuilderTag.String(tag),
)
}
err = packCli.Build(
ctx,
svc.Path(),
builder,
imageName,
environ,
previewer)
p.console.StopPreviewer(ctx, false)
if err != nil {
span.EndWithStatus(err)
var statusCodeErr *pack.StatusCodeError
if errors.As(err, &statusCodeErr) && statusCodeErr.Code == pack.StatusCodeUndetectedNoError {
return nil, &azcli.ErrorWithSuggestion{
Err: err,
Suggestion: "No Dockerfile was found, and image could not be automatically built from source. " +
fmt.Sprintf(
"\nSuggested action: Author a Dockerfile and save it as %s",
filepath.Join(svc.Path(), dockerOptions.Path)),
}
}
return nil, err
}
span.End()
imageId, err := p.docker.Inspect(ctx, imageName, "{{.Id}}")
if err != nil {
return nil, err
}
imageId = strings.TrimSpace(imageId)
return &ServiceBuildResult{
BuildOutputPath: imageId,
Details: &dockerBuildResult{
ImageId: imageId,
ImageName: imageName,
},
}, nil
}
func getEnvironForPython(ctx context.Context, svc *ServiceConfig) ([]string, error) {
prj, err := appdetect.DetectDirectory(ctx, svc.Path())
if err != nil {
return nil, err
}
if prj == nil { // Undetected project, resume build from the Oryx builder
return nil, nil
}
// Support for FastAPI apps since the Oryx builder does not support it yet
for _, dep := range prj.Dependencies {
if dep == appdetect.PyFastApi {
launch, err := appdetect.PyFastApiLaunch(prj.Path)
if err != nil {
return nil, err
}
// If launch isn't detected, fallback to default Oryx runtime logic, which may recover for scenarios
// such as a simple main entrypoint launch.
if launch == "" {
return nil, nil
}
return []string{
"POST_BUILD_COMMAND=pip install uvicorn",
//nolint:lll
"ORYX_RUNTIME_SCRIPT=oryx create-script -appPath ./oryx-output -bindPort 80 -userStartupCommand " +
"'uvicorn " + launch + " --port $PORT --host $HOST' && ./run.sh"}, nil
}
}
return nil, nil
}
func getDockerOptionsWithDefaults(options DockerProjectOptions) DockerProjectOptions {
if options.Path == "" {
options.Path = "./Dockerfile"
}
if options.Platform == "" {
options.Platform = docker.DefaultPlatform
}
if options.Context == "" {
options.Context = "."
}
return options
}