Repository navigation
Expand file tree
/
Copy pathcontainer_helper.go
More file actions
1557 lines (1357 loc) · 48.9 KB
/
Copy pathcontainer_helper.go
File metadata and controls
1557 lines (1357 loc) · 48.9 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
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package project
import (
"context"
"errors"
"fmt"
"io"
"log"
"net"
"net/url"
"os"
"path"
"path/filepath"
"strings"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry"
"github.com/azure/azure-dev/cli/azd/internal"
"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/apphost"
"github.com/azure/azure-dev/cli/azd/pkg/async"
"github.com/azure/azure-dev/cli/azd/pkg/azapi"
"github.com/azure/azure-dev/cli/azd/pkg/cloud"
"github.com/azure/azure-dev/cli/azd/pkg/containerregistry"
"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/output/ux"
"github.com/azure/azure-dev/cli/azd/pkg/tools"
"github.com/azure/azure-dev/cli/azd/pkg/tools/docker"
"github.com/azure/azure-dev/cli/azd/pkg/tools/dotnet"
"github.com/azure/azure-dev/cli/azd/pkg/tools/pack"
"github.com/benbjohnson/clock"
"github.com/distribution/reference"
"github.com/sethvargo/go-retry"
"go.opentelemetry.io/otel/trace"
)
// PublishOptions holds options for container operations such as publish and deploy.
type PublishOptions struct {
// Image specifies the target image in the form '[registry/]repository[:tag]'
Image string
}
type ContainerHelper struct {
remoteBuildManager *containerregistry.RemoteBuildManager
containerRegistryService azapi.ContainerRegistryService
commandRunner exec.CommandRunner
docker *docker.Cli
dotNetCli *dotnet.Cli
clock clock.Clock
console input.Console
cloud *cloud.Cloud
}
func NewContainerHelper(
clock clock.Clock,
containerRegistryService azapi.ContainerRegistryService,
remoteBuildManager *containerregistry.RemoteBuildManager,
commandRunner exec.CommandRunner,
docker *docker.Cli,
dotNetCli *dotnet.Cli,
console input.Console,
cloud *cloud.Cloud,
) *ContainerHelper {
return &ContainerHelper{
remoteBuildManager: remoteBuildManager,
containerRegistryService: containerRegistryService,
commandRunner: commandRunner,
docker: docker,
dotNetCli: dotNetCli,
clock: clock,
console: console,
cloud: cloud,
}
}
// ContainerEngine returns the detected container engine name ("docker" or "podman").
func (ch *ContainerHelper) ContainerEngine() tools.ContainerEngine {
return ch.docker.ContainerEngine()
}
// DockerfileBuilder returns a new DockerfileBuilder instance for building Dockerfiles programmatically.
func (ch *ContainerHelper) DockerfileBuilder() *DockerfileBuilder {
return NewDockerfileBuilder()
}
// DefaultImageName returns a default image name generated from the service name and environment name.
func (ch *ContainerHelper) DefaultImageName(
ctx context.Context,
serviceConfig *ServiceConfig,
env *environment.Environment,
) (string, error) {
return fmt.Sprintf("%s/%s-%s",
strings.ToLower(serviceConfig.Project.Name),
strings.ToLower(serviceConfig.Name),
strings.ToLower(env.Name())), nil
}
// DefaultImageTag returns a default image tag generated from the current time.
func (ch *ContainerHelper) DefaultImageTag() string {
return fmt.Sprintf("azd-deploy-%d", ch.clock.Now().Unix())
}
// RegistryName returns the name of the destination container registry to use for the current environment from the following:
// 1. AZURE_CONTAINER_REGISTRY_ENDPOINT environment variable
// 2. docker.registry from the service configuration
func (ch *ContainerHelper) RegistryName(
ctx context.Context,
serviceConfig *ServiceConfig,
env *environment.Environment,
) (string, error) {
registryName, found := env.LookupEnv(environment.ContainerRegistryEndpointEnvVarName)
if !found {
log.Printf(
"Container registry not found in '%s' environment variable\n",
environment.ContainerRegistryEndpointEnvVarName,
)
}
if registryName == "" {
yamlRegistryName, err := serviceConfig.Docker.Registry.Envsubst(env.Getenv)
if err != nil {
log.Println("Failed expanding 'docker.registry'")
}
registryName = yamlRegistryName
}
// If the service provides its own code artifacts then the expectation is that an images needs to be built and
// pushed to a container registry.
// If the service does not provide its own code artifacts then the expectation is a registry is optional and
// an image can be referenced independently.
if serviceConfig.RelativePath != "" && registryName == "" {
return "", fmt.Errorf(
//nolint:lll
"could not determine container registry endpoint, ensure 'registry' has been set in the docker options or '%s' environment variable has been set",
environment.ContainerRegistryEndpointEnvVarName,
)
}
return registryName, nil
}
// GeneratedImage returns the configured image from the service configuration
// or a default image name generated from the service name and environment name.
func (ch *ContainerHelper) GeneratedImage(
ctx context.Context,
serviceConfig *ServiceConfig,
env *environment.Environment,
) (*docker.ContainerImage, error) {
// Parse the image from azure.yaml configuration when available
configuredImage, err := serviceConfig.Docker.Image.Envsubst(env.Getenv)
if err != nil {
return nil, fmt.Errorf("failed parsing 'image' from docker configuration, %w", err)
}
// Set default image name if not configured
if configuredImage == "" {
configuredImage, err = ch.DefaultImageName(ctx, serviceConfig, env)
if err != nil {
return nil, err
}
}
parsedImage, err := docker.ParseContainerImage(configuredImage)
if err != nil {
return nil, fmt.Errorf("failed parsing configured image, %w", err)
}
if parsedImage.Tag == "" {
configuredTag, err := serviceConfig.Docker.Tag.Envsubst(env.Getenv)
if err != nil {
return nil, fmt.Errorf("failed parsing 'tag' from docker configuration, %w", err)
}
// Set default tag if not configured
if configuredTag == "" {
configuredTag = ch.DefaultImageTag()
}
parsedImage.Tag = configuredTag
}
// Set default registry if not configured
if parsedImage.Registry == "" {
// This can fail if called before provisioning the registry
configuredRegistry, err := ch.RegistryName(ctx, serviceConfig, env)
if err == nil {
parsedImage.Registry = configuredRegistry
}
}
return parsedImage, nil
}
// RemoteImageTag returns the remote image tag for the service configuration.
func (ch *ContainerHelper) RemoteImageTag(
ctx context.Context,
serviceConfig *ServiceConfig,
localImageTag string,
imageOverride *imageOverride,
env *environment.Environment,
) (string, error) {
registryName, err := ch.RegistryName(ctx, serviceConfig, env)
if err != nil {
return "", err
}
containerImage, err := docker.ParseContainerImage(localImageTag)
if err != nil {
return "", err
}
if registryName != "" {
containerImage.Registry = registryName
}
// Apply overrides
if imageOverride != nil {
if imageOverride.Registry != "" {
containerImage.Registry = imageOverride.Registry
}
if imageOverride.Repository != "" {
containerImage.Repository = imageOverride.Repository
}
if imageOverride.Tag != "" {
containerImage.Tag = imageOverride.Tag
}
}
return containerImage.Remote(), nil
}
// LocalImageTag returns the local image tag for the service configuration.
func (ch *ContainerHelper) LocalImageTag(
ctx context.Context,
serviceConfig *ServiceConfig,
env *environment.Environment,
) (string, error) {
configuredImage, err := ch.GeneratedImage(ctx, serviceConfig, env)
if err != nil {
return "", err
}
return configuredImage.Local(), nil
}
func resolveImagePassthrough(
serviceConfig *ServiceConfig,
env *environment.Environment,
) (string, error) {
if !serviceConfig.Docker.ImagePassthrough {
return "", nil
}
if serviceConfig.Docker.RemoteBuild {
return "", fmt.Errorf("docker.imagePassthrough cannot be combined with docker.remoteBuild")
}
image, err := serviceConfig.Image.Envsubst(env.Getenv)
if err != nil {
return "", fmt.Errorf("substituting environment variables in passthrough image: %w", err)
}
if strings.TrimSpace(image) == "" {
return "", fmt.Errorf("docker.imagePassthrough requires the service image property")
}
if err := validateFullyQualifiedRemoteContainerImage(image); err != nil {
return "", fmt.Errorf("passthrough image must be a fully qualified remote container image: %w", err)
}
// Passthrough preserves the expanded reference exactly, including tag and digest combinations.
return image, nil
}
func imagePassthroughArtifact(image string) *Artifact {
return &Artifact{
Kind: ArtifactKindContainer,
Location: image,
LocationKind: LocationKindRemote,
Metadata: map[string]string{
MetadataKeyImagePassthrough: "true",
"remoteImage": image,
"sourceImage": image,
},
}
}
func (ch *ContainerHelper) RequiredExternalTools(ctx context.Context, serviceConfig *ServiceConfig) []tools.ExternalTool {
if serviceConfig.Docker.ImagePassthrough || serviceConfig.Docker.RemoteBuild {
return []tools.ExternalTool{}
}
if useDotnetPublishForDockerBuild(serviceConfig) {
return []tools.ExternalTool{ch.dotNetCli}
}
return []tools.ExternalTool{ch.docker}
}
// Login logs into the container registry specified by AZURE_CONTAINER_REGISTRY_ENDPOINT in the environment. On success,
// it returns the name of the container registry that was logged into.
func (ch *ContainerHelper) Login(
ctx context.Context,
serviceConfig *ServiceConfig,
env *environment.Environment,
) (string, error) {
registryName, err := ch.RegistryName(ctx, serviceConfig, env)
if err != nil {
return "", err
}
// Only perform automatic login for ACR
// Other registries require manual login via external 'docker login' command
hostParts := strings.Split(registryName, ".")
if len(hostParts) == 1 || strings.HasSuffix(registryName, ch.cloud.ContainerRegistryEndpointSuffix) {
return registryName, ch.containerRegistryService.Login(ctx, env.GetSubscriptionId(), registryName)
}
return registryName, nil
}
var defaultCredentialsRetryInitialDelay = 2 * time.Second
func (ch *ContainerHelper) Credentials(
ctx context.Context,
serviceConfig *ServiceConfig,
targetResource *environment.TargetResource,
env *environment.Environment,
) (_ *azapi.DockerCredentials, err error) {
ctx, span := tracing.Start(ctx, events.ContainerCredentialsEvent)
defer func() { span.EndWithStatus(err) }()
loginServer, err := ch.RegistryName(ctx, serviceConfig, env)
if err != nil {
return nil, err
}
var credential *azapi.DockerCredentials
credentialsError := retry.Do(
ctx,
// Use exponential backoff (2s → 4s → 8s → 16s → 32s = 62s worst case) instead of
// constant 20s delay. ACR credentials are typically available within seconds after
// resource creation, so aggressive early retries resolve most 404s quickly while
// preserving roughly the same total retry window for slow DNS propagation.
retry.WithMaxRetries(5, retry.NewExponential(defaultCredentialsRetryInitialDelay)),
func(ctx context.Context) error {
cred, err := ch.containerRegistryService.Credentials(ctx, targetResource.SubscriptionId(), loginServer)
if err != nil {
if httpErr, ok := errors.AsType[*azcore.ResponseError](err); ok {
// Only retry 404 — the ACR resource may not have propagated yet.
// Do NOT retry 429 or 5xx here: the Azure SDK's built-in retry
// policy already handles those, so retrying at this layer would
// cause retry amplification (outer × inner).
if httpErr.StatusCode == 404 {
return retry.RetryableError(err)
}
}
// Retry transient network/DNS errors (e.g. "no such host"
// during DNS propagation after ACR creation). Only retry
// genuinely transient errors, not permanent URL/TLS failures.
if _, ok := errors.AsType[*url.Error](err); ok {
if netErr, ok := errors.AsType[net.Error](err); ok && netErr.Timeout() {
return retry.RetryableError(err)
}
msg := err.Error()
if strings.Contains(msg, "no such host") ||
strings.Contains(msg, "connection refused") {
return retry.RetryableError(err)
}
}
return err
}
credential = cred
return nil
})
return credential, credentialsError
}
func (ch *ContainerHelper) Build(
ctx context.Context,
serviceConfig *ServiceConfig,
serviceContext *ServiceContext,
env *environment.Environment,
progress *async.Progress[ServiceProgress],
) (*ServiceBuildResult, error) {
if serviceConfig.Docker.ImagePassthrough {
if _, err := resolveImagePassthrough(serviceConfig, env); err != nil {
return nil, err
}
return &ServiceBuildResult{}, nil
}
if serviceConfig.Docker.RemoteBuild || useDotnetPublishForDockerBuild(serviceConfig) {
return &ServiceBuildResult{}, nil
}
return ch.buildLocalImage(ctx, serviceConfig, env, progress)
}
func (ch *ContainerHelper) buildLocalImage(
ctx context.Context,
serviceConfig *ServiceConfig,
env *environment.Environment,
progress *async.Progress[ServiceProgress],
) (*ServiceBuildResult, error) {
dockerOptions := getDockerOptionsWithDefaults(serviceConfig.Docker)
resolveDockerPaths(serviceConfig, &dockerOptions)
resolvedBuildArgs, err := resolveDockerBuildArgs(dockerOptions.BuildArgs, env)
if err != nil {
return nil, err
}
// resolve parameters for build env
resolvedBuildEnv, err := resolveDockerParameters(dockerOptions.BuildEnv, env)
if err != nil {
return nil, err
}
dockerOptions.BuildEnv = resolvedBuildEnv
// For services that do not specify a project path and have not specified a language then
// there is nothing to build and we can return an empty build result
// Ex) A container app project that uses an external image path
if serviceConfig.RelativePath == "" &&
(serviceConfig.Language == ServiceLanguageNone || serviceConfig.Language == ServiceLanguageDocker) {
return &ServiceBuildResult{}, nil
}
buildArgs := []string{}
for _, arg := range resolvedBuildArgs {
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),
)
// dockerOptions.Path is already resolved to absolute by resolveDockerPaths
dockerfilePath := dockerOptions.Path
_, err = os.Stat(dockerfilePath)
if errors.Is(err, os.ErrNotExist) && serviceConfig.Docker.Path == "" {
// Build the container from source when:
// 1. No Dockerfile path is specified, and
// 2. <service directory>/Dockerfile doesn't exist
progress.SetProgress(NewServiceProgress("Building Docker image from source"))
res, err := ch.packBuild(ctx, serviceConfig, dockerOptions, imageName)
if err != nil {
return nil, err
}
return res, nil
}
// Include full environment variables for the docker build including:
// 1. Environment variables from the host
// 2. Environment variables from the service configuration
// 3. Environment variables from the docker configuration
dockerEnv := []string{}
dockerEnv = append(dockerEnv, os.Environ()...)
dockerEnv = append(dockerEnv, env.Environ()...)
dockerEnv = append(dockerEnv, dockerOptions.BuildEnv...)
// Build the container
progress.SetProgress(NewServiceProgress("Building Docker image"))
previewerWriter := ch.console.ShowPreviewer(ctx,
&input.ShowPreviewerOptions{
Prefix: " ",
MaxLineCount: 8,
Title: "Docker Output",
})
dockerFilePath := dockerOptions.Path
if dockerOptions.InMemDockerfile != nil {
// when using an in-memory dockerfile, we write it to a temp file and use that path for the build
tempDir, err := os.MkdirTemp("", "dockerfile-for-"+serviceConfig.Name)
if err != nil {
return nil, fmt.Errorf("creating temp dir for dockerfile for service %s: %w", serviceConfig.Name, err)
}
// use the name of the original dockerfile path
dockerfilePath = filepath.Join(tempDir, filepath.Base(dockerFilePath))
err = os.WriteFile(dockerfilePath, dockerOptions.InMemDockerfile, osutil.PermissionFileOwnerOnly)
if err != nil {
return nil, fmt.Errorf("writing dockerfile for service %s: %w", serviceConfig.Name, err)
}
dockerFilePath = dockerfilePath
if serviceConfig.Docker.Context == "" || serviceConfig.Docker.Context == "." {
dockerOptions.Context = tempDir
}
log.Println("using in-memory dockerfile for build", dockerfilePath)
// ensure we clean up the temp dockerfile after the build
defer func() {
if err := os.RemoveAll(tempDir); err != nil {
log.Printf("removing temp dockerfile dir %s: %v", tempDir, err)
}
}()
}
imageId, err := ch.docker.Build(
ctx,
serviceConfig.Path(),
dockerFilePath,
dockerOptions.Platform,
dockerOptions.Target,
dockerOptions.Context,
imageName,
resolvedBuildArgs,
dockerOptions.BuildSecrets,
dockerEnv,
dockerOptions.Network,
previewerWriter,
)
if previewerWriter != io.Discard {
ch.console.StopPreviewer(ctx, false)
}
if err != nil {
return nil, fmt.Errorf("building container: %s at %s: %w", serviceConfig.Name, dockerOptions.Context, err)
}
log.Printf("built image %s for %s", imageId, serviceConfig.Name)
// Create container image artifact for build output
return &ServiceBuildResult{
Artifacts: ArtifactCollection{{
Kind: ArtifactKindContainer,
Location: imageId,
LocationKind: LocationKindLocal,
Metadata: map[string]string{
"imageId": imageId,
"imageName": imageName,
"framework": "docker",
},
}},
}, nil
}
func resolveDockerBuildArgs(buildArgs []osutil.ExpandableString, env *environment.Environment) ([]string, error) {
dockerBuildArgs := make([]string, 0, len(buildArgs))
for _, arg := range buildArgs {
buildArgValue, err := arg.Envsubst(env.Getenv)
if err != nil {
return nil, fmt.Errorf("substituting environment variables in build args: %w", err)
}
dockerBuildArgs = append(dockerBuildArgs, buildArgValue)
}
return resolveDockerParameters(dockerBuildArgs, env)
}
func resolveDockerParameters(source []string, env *environment.Environment) ([]string, error) {
result := make([]string, len(source))
for i, arg := range source {
evaluatedString, err := apphost.EvalString(arg, func(match string) (string, error) {
path := match
value, has := env.Config.GetString(path)
if !has {
return "", fmt.Errorf("parameter %s not found", path)
}
return value, nil
})
if err != nil {
return nil, err
}
result[i] = evaluatedString
}
return result, nil
}
func (ch *ContainerHelper) Package(
ctx context.Context,
serviceConfig *ServiceConfig,
serviceContext *ServiceContext,
env *environment.Environment,
progress *async.Progress[ServiceProgress],
) (*ServicePackageResult, error) {
if serviceConfig.Docker.ImagePassthrough {
image, err := resolveImagePassthrough(serviceConfig, env)
if err != nil {
return nil, err
}
return &ServicePackageResult{
Artifacts: ArtifactCollection{imagePassthroughArtifact(image)},
}, nil
}
if serviceConfig.Docker.RemoteBuild || useDotnetPublishForDockerBuild(serviceConfig) {
return &ServicePackageResult{}, nil
}
return ch.packageLocalImage(ctx, serviceConfig, serviceContext, env, progress)
}
func (ch *ContainerHelper) packageLocalImage(
ctx context.Context,
serviceConfig *ServiceConfig,
serviceContext *ServiceContext,
env *environment.Environment,
progress *async.Progress[ServiceProgress],
) (*ServicePackageResult, error) {
var imageId string
var sourceImage string
var imageHash string
// Find the container image artifact from build results
if artifact, found := serviceContext.Build.FindFirst(WithKind(ArtifactKindContainer)); found && artifact.Location != "" {
imageId = artifact.Location
imageHash = imageId // For built images, the location is the image hash
}
// If we don't have an image ID from a docker build then an external source image is being used
if imageId == "" {
sourceImageValue, err := serviceConfig.Image.Envsubst(env.Getenv)
if err != nil {
return nil, fmt.Errorf("substituting environment variables in image: %w", err)
}
sourceImageContainer, err := docker.ParseContainerImage(sourceImageValue)
if err != nil {
return nil, fmt.Errorf("parsing source container image: %w", err)
}
remoteImageUrl := sourceImageContainer.Remote()
progress.SetProgress(NewServiceProgress("Pulling container source image"))
if err := ch.docker.Pull(ctx, remoteImageUrl); err != nil {
return nil, fmt.Errorf("pulling source container image: %w", err)
}
imageId = remoteImageUrl // For tagging purposes
sourceImage = remoteImageUrl
imageHash = "" // External images don't have a known image hash
}
// Generate a local tag from the 'docker' configuration section of the service
imageWithTag, err := ch.LocalImageTag(ctx, serviceConfig, env)
if err != nil {
return nil, fmt.Errorf("generating local image tag: %w", err)
}
// Tag image.
log.Printf("tagging image %s as %s", imageId, imageWithTag)
progress.SetProgress(NewServiceProgress("Tagging container image"))
if err := ch.docker.Tag(ctx, serviceConfig.Path(), imageId, imageWithTag); err != nil {
return nil, fmt.Errorf("tagging image: %w", err)
}
targetImage := imageWithTag
// Create container image artifact
packageArtifact := &Artifact{
Kind: ArtifactKindContainer,
Location: imageWithTag,
LocationKind: LocationKindLocal, // Local during package phase
Metadata: map[string]string{
"imageHash": imageHash,
"sourceImage": sourceImage,
"targetImage": targetImage,
},
}
return &ServicePackageResult{
Artifacts: ArtifactCollection{packageArtifact},
}, nil
}
func validatePublishOptions(serviceConfig *ServiceConfig, options *PublishOptions) error {
if serviceConfig.Docker.ImagePassthrough && options != nil && options.Image != "" {
return fmt.Errorf("docker.imagePassthrough cannot be combined with a publish image override")
}
return nil
}
func validateFullyQualifiedRemoteContainerImage(image string) error {
parsed, err := reference.Parse(image)
if err != nil {
return err
}
named, ok := parsed.(reference.Named)
if !ok {
return fmt.Errorf("image reference does not include a repository name")
}
registry := reference.Domain(named)
if registry == "" ||
(!strings.Contains(registry, ".") && !strings.Contains(registry, ":") && registry != "localhost") {
return fmt.Errorf("image reference does not include an explicit registry")
}
return nil
}
func imagePassthroughPackageOverride(
serviceConfig *ServiceConfig,
serviceContext *ServiceContext,
) (string, bool, error) {
if !serviceConfig.Docker.ImagePassthrough || serviceContext == nil || len(serviceContext.Package) == 0 {
return "", false, nil
}
var packageImage string
containerArtifacts := []*Artifact{}
for _, artifact := range serviceContext.Package {
if artifact == nil {
return "", false, fmt.Errorf("docker.imagePassthrough does not support a nil package artifact")
}
switch artifact.Kind {
case ArtifactKindContainer:
if err := validateFullyQualifiedRemoteContainerImage(artifact.Location); err != nil {
return "", false, fmt.Errorf(
"docker.imagePassthrough requires package container artifacts to use "+
"a fully qualified remote container image: %w",
err,
)
}
if packageImage != "" && artifact.Location != packageImage {
return "", false, fmt.Errorf(
"docker.imagePassthrough package contains multiple distinct remote container images",
)
}
packageImage = artifact.Location
containerArtifacts = append(containerArtifacts, artifact)
case ArtifactKindConfig:
// Targets may add supplementary configuration alongside the container image.
case ArtifactKindArchive, ArtifactKindDirectory:
return "", false, fmt.Errorf(
"docker.imagePassthrough does not support %s package artifacts; "+
"use a fully qualified remote container image",
artifact.Kind,
)
default:
return "", false, fmt.Errorf(
"docker.imagePassthrough does not support %s package artifacts",
artifact.Kind,
)
}
}
if packageImage == "" {
return "", false, fmt.Errorf("docker.imagePassthrough package does not contain a container image")
}
for _, artifact := range containerArtifacts {
artifact.LocationKind = LocationKindRemote
if artifact.Metadata == nil {
artifact.Metadata = map[string]string{}
}
artifact.Metadata[MetadataKeyImagePassthrough] = "true"
artifact.Metadata["remoteImage"] = packageImage
artifact.Metadata["sourceImage"] = packageImage
}
// The package artifact is the per-run input selected by --from-package. Its location wins over
// the service image while imagePassthrough continues to control how the selected image is handled.
return packageImage, true, nil
}
// Publish pushes an image to a remote server and returns the fully qualified remote image name.
func (ch *ContainerHelper) Publish(
ctx context.Context,
serviceConfig *ServiceConfig,
serviceContext *ServiceContext,
targetResource *environment.TargetResource,
env *environment.Environment,
progress *async.Progress[ServiceProgress],
options *PublishOptions,
) (_ *ServicePublishResult, err error) {
ctx, span := tracing.Start(ctx, events.ContainerPublishEvent)
defer func() { span.EndWithStatus(err) }()
// Record the user-configured remote-build preference (serviceConfig.Docker.RemoteBuild),
// which already carries the requested true/false value.
span.SetAttributes(
fields.ContainerRemoteBuildKey.Bool(serviceConfig.Docker.RemoteBuild),
)
if err := ctx.Err(); err != nil {
return nil, err
}
var remoteImage string
if err := validatePublishOptions(serviceConfig, options); err != nil {
return nil, err
}
passthroughOverride, hasPassthroughOverride, err := imagePassthroughPackageOverride(
serviceConfig,
serviceContext,
)
if err != nil {
return nil, err
}
// Parse PublishOptions into ImageOverride
imageOverride, err := parseImageOverride(options)
if err != nil {
return nil, err
}
if serviceConfig.Docker.ImagePassthrough {
if hasPassthroughOverride {
remoteImage = passthroughOverride
} else {
remoteImage, err = resolveImagePassthrough(serviceConfig, env)
}
} else if serviceConfig.Docker.RemoteBuild {
remoteImage, err = ch.runRemoteBuild(ctx, serviceConfig, targetResource, env, progress, imageOverride)
if err != nil {
remoteErr := err
if _, ok := errors.AsType[*containerregistry.RemoteBuildUnavailableError](remoteErr); !ok {
return nil, remoteErr
}
remoteImage, err = ch.publishLocalFallback(
ctx, serviceConfig, serviceContext, env, progress, imageOverride)
if err != nil {
fallbackErr := fmt.Errorf("remote build failed: %w\n\nLocal fallback failed: %w", remoteErr, err)
if suggestion, ok := errors.AsType[*internal.ErrorWithSuggestion](fallbackErr); ok {
// Rich CLI output renders suggestion.Err rather than its outer wrappers.
combined := *suggestion
combined.Err = fallbackErr
return nil, &combined
}
return nil, fallbackErr
}
}
} else if useDotnetPublishForDockerBuild(serviceConfig) {
remoteImage, err = ch.runDotnetPublish(ctx, serviceConfig, targetResource, env, progress)
} else {
remoteImage, err = ch.publishLocalImage(ctx, serviceConfig, serviceContext, env, progress, imageOverride)
}
if err != nil {
return nil, err
}
// Create publish artifact with remote image reference
metadata := map[string]string{"remoteImage": remoteImage}
if serviceConfig.Docker.ImagePassthrough {
metadata[MetadataKeyImagePassthrough] = "true"
}
publishArtifact := &Artifact{
Kind: ArtifactKindContainer,
Location: remoteImage,
LocationKind: LocationKindRemote, // Remote after publish
Metadata: metadata,
}
return &ServicePublishResult{
Artifacts: ArtifactCollection{publishArtifact},
}, nil
}
// publishLocalFallback builds and packages locally if no container package was supplied,
// then publishes the image after ACR has refused to schedule a remote build.
func (ch *ContainerHelper) publishLocalFallback(
ctx context.Context,
serviceConfig *ServiceConfig,
serviceContext *ServiceContext,
env *environment.Environment,
progress *async.Progress[ServiceProgress],
imageOverride *imageOverride,
) (string, error) {
// Shell commands may start despite cancellation; keep these stage guards until Azure/azure-dev#10035 is fixed.
if err := ctx.Err(); err != nil {
return "", err
}
if err := ch.docker.CheckInstalled(ctx); err != nil {
if _, ok := errors.AsType[*docker.ContainerEngineUnavailableError](err); ok {
engineName := ch.docker.Name()
return "", &internal.ErrorWithSuggestion{
Err: err,
Message: fmt.Sprintf(
"Azure Container Registry refused the remote build, and local fallback could not start "+
"because %s is unavailable.",
engineName,
),
Suggestion: fmt.Sprintf(
"Check that %s is running and accessible, then run the command again.", engineName),
}
}
return "", fmt.Errorf("local container runtime unavailable: %w", err)
}
// Do not announce or prepare a fallback if cancellation arrived during the readiness check.
if err := ctx.Err(); err != nil {
return "", err
}
var hasPackage bool
if serviceContext != nil {
artifact, found := serviceContext.Package.FindFirst(WithKind(ArtifactKindContainer))
hasPackage = found
if found && artifact.LocationKind == LocationKindRemote {
return "", errors.New("local fallback requires a local container package")
}
}
action := fmt.Sprintf("Building locally with %s.", ch.docker.Name())
if hasPackage {
action = fmt.Sprintf("Publishing the existing local image with %s.", ch.docker.Name())
}
ch.console.MessageUxItem(ctx, &ux.WarningMessage{
Description: fmt.Sprintf("ACR refused the build request with TasksOperationsNotAllowed. %s", action),
})
if !hasPackage {
// Remote mode skips local build/package. Keep fallback artifacts separate from completed lifecycle state.
serviceContext = NewServiceContext()
buildResult, err := ch.buildLocalImage(ctx, serviceConfig, env, progress)
if err != nil {
return "", fmt.Errorf("building local image: %w", err)
}
if err := serviceContext.Build.Add(buildResult.Artifacts...); err != nil {
return "", fmt.Errorf("adding local build artifacts: %w", err)
}
if err := ctx.Err(); err != nil {
return "", err
}
packageResult, err := ch.packageLocalImage(ctx, serviceConfig, serviceContext, env, progress)
if err != nil {
return "", fmt.Errorf("packaging local image: %w", err)
}
if err := serviceContext.Package.Add(packageResult.Artifacts...); err != nil {
return "", fmt.Errorf("adding local package artifacts: %w", err)
}
}
if err := ctx.Err(); err != nil {
return "", err
}
return ch.publishLocalImage(ctx, serviceConfig, serviceContext, env, progress, imageOverride)
}
// publishLocalImage publishes a prepared container package and returns the full remote image name.
func (ch *ContainerHelper) publishLocalImage(
ctx context.Context,
serviceConfig *ServiceConfig,
serviceContext *ServiceContext,
env *environment.Environment,
progress *async.Progress[ServiceProgress],
imageOverride *imageOverride,
) (string, error) {
// Get ACR Login Server
registryName, err := ch.RegistryName(ctx, serviceConfig, env)
if err != nil {
return "", err
}
var sourceImage string
var targetImage string
// Find the container image artifact from package results
if artifact, found := serviceContext.Package.FindFirst(WithKind(ArtifactKindContainer)); found {
targetImage = artifact.Location
if sourceImageValue := artifact.Metadata["sourceImage"]; sourceImageValue != "" {
sourceImage = sourceImageValue
}
// Fall back to metadata targetImage if Location is empty
if targetImage == "" {
if targetImageValue := artifact.Metadata["targetImage"]; targetImageValue != "" {
targetImage = targetImageValue
}
}
}
// Default to the local image tag
remoteImage := targetImage
// If we don't have a registry specified and the service does not reference a project path
// then we are referencing a public/pre-existing image and don't have anything to tag or push
if registryName == "" && serviceConfig.RelativePath == "" && sourceImage != "" {
remoteImage = sourceImage
} else {
if targetImage == "" {