-
Notifications
You must be signed in to change notification settings - Fork 173
/
service_target_dotnet_containerapp.go
451 lines (388 loc) · 15.1 KB
/
service_target_dotnet_containerapp.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package project
import (
"context"
"fmt"
"log"
"net/url"
"os"
"path/filepath"
"strings"
"text/template"
"time"
"github.com/azure/azure-dev/cli/azd/internal/scaffold"
"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/azure"
"github.com/azure/azure-dev/cli/azd/pkg/containerapps"
"github.com/azure/azure-dev/cli/azd/pkg/cosmosdb"
"github.com/azure/azure-dev/cli/azd/pkg/environment"
"github.com/azure/azure-dev/cli/azd/pkg/infra"
"github.com/azure/azure-dev/cli/azd/pkg/password"
"github.com/azure/azure-dev/cli/azd/pkg/tools"
"github.com/azure/azure-dev/cli/azd/pkg/tools/dotnet"
)
type dotnetContainerAppTarget struct {
env *environment.Environment
containerHelper *ContainerHelper
containerAppService containerapps.ContainerAppService
resourceManager ResourceManager
dotNetCli dotnet.DotNetCli
cosmosDbService cosmosdb.CosmosDbService
}
// NewDotNetContainerAppTarget creates the Service Target for a Container App that is written in .NET. Unlike
// [ContainerAppTarget], this target does not require a Dockerfile to be present in the project. Instead, it uses the built
// in support in .NET 8 for publishing containers using `dotnet publish`. In addition, it uses a different deployment
// strategy built on a yaml manifest file, using the same format `az containerapp create --yaml`, with additional support
// for using text/template to do replacements, similar to tools like Helm.
//
// Note that unlike [ContainerAppTarget] this target does not add SERVICE_<XYZ>_IMAGE_NAME values to the environment,
// instead, the image name is present on the context object used when rendering the template.
func NewDotNetContainerAppTarget(
env *environment.Environment,
containerHelper *ContainerHelper,
containerAppService containerapps.ContainerAppService,
resourceManager ResourceManager,
dotNetCli dotnet.DotNetCli,
cosmosDbService cosmosdb.CosmosDbService,
) ServiceTarget {
return &dotnetContainerAppTarget{
env: env,
containerHelper: containerHelper,
containerAppService: containerAppService,
resourceManager: resourceManager,
dotNetCli: dotNetCli,
cosmosDbService: cosmosDbService,
}
}
// Gets the required external tools
func (at *dotnetContainerAppTarget) RequiredExternalTools(ctx context.Context) []tools.ExternalTool {
return []tools.ExternalTool{at.dotNetCli}
}
// Initializes the Container App target
func (at *dotnetContainerAppTarget) Initialize(ctx context.Context, serviceConfig *ServiceConfig) error {
return nil
}
// Prepares and tags the container image from the build output based on the specified service configuration
func (at *dotnetContainerAppTarget) Package(
ctx context.Context,
serviceConfig *ServiceConfig,
packageOutput *ServicePackageResult,
) *async.TaskWithProgress[*ServicePackageResult, ServiceProgress] {
return async.RunTaskWithProgress(
func(task *async.TaskContextWithProgress[*ServicePackageResult, ServiceProgress]) {
task.SetResult(packageOutput)
},
)
}
// Deploys service container images to ACR and provisions the container app service.
func (at *dotnetContainerAppTarget) Deploy(
ctx context.Context,
serviceConfig *ServiceConfig,
packageOutput *ServicePackageResult,
targetResource *environment.TargetResource,
) *async.TaskWithProgress[*ServiceDeployResult, ServiceProgress] {
return async.RunTaskWithProgress(
func(task *async.TaskContextWithProgress[*ServiceDeployResult, ServiceProgress]) {
if err := at.validateTargetResource(ctx, serviceConfig, targetResource); err != nil {
task.SetError(fmt.Errorf("validating target resource: %w", err))
return
}
task.SetProgress(NewServiceProgress("Logging in to registry"))
// Login, tag & push container image to ACR
dockerCreds, err := at.containerHelper.Credentials(ctx, serviceConfig, targetResource)
if err != nil {
task.SetError(fmt.Errorf("logging in to registry: %w", err))
return
}
task.SetProgress(NewServiceProgress("Pushing container image"))
var remoteImageName string
if serviceConfig.Language == ServiceLanguageDocker {
containerDeployTask := at.containerHelper.Deploy(ctx, serviceConfig, packageOutput, targetResource, false)
syncProgress(task, containerDeployTask.Progress())
res, err := containerDeployTask.Await()
if err != nil {
task.SetError(err)
return
}
remoteImageName = res.Details.(*dockerDeployResult).RemoteImageTag
} else {
imageName := fmt.Sprintf("azd-deploy-%s-%d", serviceConfig.Name, time.Now().Unix())
err = at.dotNetCli.PublishContainer(
ctx,
serviceConfig.Path(),
"Debug",
imageName,
dockerCreds.LoginServer,
dockerCreds.Username,
dockerCreds.Password)
if err != nil {
task.SetError(fmt.Errorf("publishing container: %w", err))
return
}
remoteImageName = fmt.Sprintf("%s/%s", dockerCreds.LoginServer, imageName)
}
task.SetProgress(NewServiceProgress("Updating container app"))
var manifest string
projectRoot := serviceConfig.Path()
if f, err := os.Stat(projectRoot); err == nil && !f.IsDir() {
projectRoot = filepath.Dir(projectRoot)
}
manifestPath := filepath.Join(projectRoot, "manifests", "containerApp.tmpl.yaml")
if _, err := os.Stat(manifestPath); err == nil {
log.Printf("using container app manifest from %s", manifestPath)
contents, err := os.ReadFile(filepath.Join(projectRoot, "manifests", "containerApp.tmpl.yaml"))
if err != nil {
task.SetError(fmt.Errorf("reading container app manifest: %w", err))
return
}
manifest = string(contents)
} else {
log.Printf(
"generating container app manifest from %s for project %s",
serviceConfig.DotNetContainerApp.ProjectPath,
serviceConfig.DotNetContainerApp.ProjectName)
generatedManifest, err := apphost.ContainerAppManifestTemplateForProject(
serviceConfig.DotNetContainerApp.Manifest,
serviceConfig.DotNetContainerApp.ProjectName,
)
if err != nil {
task.SetError(fmt.Errorf("generating container app manifest: %w", err))
return
}
manifest = generatedManifest
}
fns := &containerAppTemplateManifestFuncs{
ctx: ctx,
manifest: serviceConfig.DotNetContainerApp.Manifest,
targetResource: targetResource,
containerAppService: at.containerAppService,
cosmosDbService: at.cosmosDbService,
env: at.env,
}
tmpl, err := template.New("containerApp.tmpl.yaml").
Option("missingkey=error").
Funcs(template.FuncMap{
"urlHost": fns.UrlHost,
"connectionString": fns.ConnectionString,
}).
Parse(manifest)
if err != nil {
task.SetError(fmt.Errorf("failing parsing containerApp.tmpl.yaml: %w", err))
return
}
requiredInputs, err := apphost.Inputs(serviceConfig.DotNetContainerApp.Manifest)
if err != nil {
task.SetError(fmt.Errorf("failed to get required inputs: %w", err))
}
wroteNewInput := false
for inputName, inputInfo := range requiredInputs {
inputConfigKey := fmt.Sprintf("inputs.%s", inputName)
if _, has := at.env.Config.GetString(inputConfigKey); !has {
// No value found, so we need to generate one, and store it in the config bag.
//
// TODO(ellismg): Today this dereference is safe because when loading a manifest we validate that every
// input has a generate block with a min length property. We would like to relax this in Preview 3 to
// to support cases where this is not the case (and we'd prompt for the value). When we do that, we'll
// need to audit these dereferences to check for nil.
val, err := password.FromAlphabet(password.LettersAndDigits, *inputInfo.Default.Generate.MinLength)
if err != nil {
task.SetError(fmt.Errorf("generating value for input %s: %w", inputName, err))
return
}
if err := at.env.Config.Set(inputConfigKey, val); err != nil {
task.SetError(fmt.Errorf("saving value for input %s: %w", inputName, err))
return
}
wroteNewInput = true
}
}
if wroteNewInput {
if err := at.containerHelper.envManager.Save(ctx, at.env); err != nil {
task.SetError(fmt.Errorf("saving environment: %w", err))
return
}
}
var inputs map[string]any
if has, err := at.env.Config.GetSection("inputs", &inputs); err != nil {
task.SetError(fmt.Errorf("failed to get inputs section: %w", err))
return
} else if !has {
inputs = make(map[string]any)
}
builder := strings.Builder{}
err = tmpl.Execute(&builder, struct {
Env map[string]string
Image string
Inputs map[string]any
}{
Env: at.env.Dotenv(),
Image: remoteImageName,
Inputs: inputs,
})
if err != nil {
task.SetError(fmt.Errorf("failed executing template file: %w", err))
return
}
err = at.containerAppService.DeployYaml(
ctx,
targetResource.SubscriptionId(),
targetResource.ResourceGroupName(),
serviceConfig.Name,
[]byte(builder.String()),
)
if err != nil {
task.SetError(fmt.Errorf("updating container app service: %w", err))
return
}
task.SetProgress(NewServiceProgress("Fetching endpoints for container app service"))
containerAppTarget := environment.NewTargetResource(
targetResource.SubscriptionId(),
targetResource.ResourceGroupName(),
serviceConfig.Name,
string(infra.AzureResourceTypeContainerApp))
endpoints, err := at.Endpoints(ctx, serviceConfig, containerAppTarget)
if err != nil {
task.SetError(err)
return
}
task.SetResult(&ServiceDeployResult{
Package: packageOutput,
TargetResourceId: azure.ContainerAppRID(
targetResource.SubscriptionId(),
targetResource.ResourceGroupName(),
serviceConfig.Name,
),
Kind: ContainerAppTarget,
Endpoints: endpoints,
})
},
)
}
// Gets endpoint for the container app service
func (at *dotnetContainerAppTarget) Endpoints(
ctx context.Context,
serviceConfig *ServiceConfig,
targetResource *environment.TargetResource,
) ([]string, error) {
if ingressConfig, err := at.containerAppService.GetIngressConfiguration(
ctx,
targetResource.SubscriptionId(),
targetResource.ResourceGroupName(),
targetResource.ResourceName(),
); err != nil {
return nil, fmt.Errorf("fetching service properties: %w", err)
} else {
endpoints := make([]string, len(ingressConfig.HostNames))
for idx, hostName := range ingressConfig.HostNames {
endpoints[idx] = fmt.Sprintf("https://%s/", hostName)
}
return endpoints, nil
}
}
func (at *dotnetContainerAppTarget) validateTargetResource(
ctx context.Context,
serviceConfig *ServiceConfig,
targetResource *environment.TargetResource,
) error {
if targetResource.ResourceGroupName() == "" {
return fmt.Errorf("missing resource group name: %s", targetResource.ResourceGroupName())
}
if targetResource.ResourceType() != "" {
if err := checkResourceType(targetResource, infra.AzureResourceTypeContainerAppEnvironment); err != nil {
return err
}
}
return nil
}
// containerAppTemplateManifestFuncs contains all the functions that are callable while evaluating the manifest template.
type containerAppTemplateManifestFuncs struct {
ctx context.Context
manifest *apphost.Manifest
targetResource *environment.TargetResource
containerAppService containerapps.ContainerAppService
cosmosDbService cosmosdb.CosmosDbService
env *environment.Environment
}
// UrlHost returns the Hostname (without the port) of the given string, or an error if the string is not a valid URL.
//
// It is callable from a template under the name `urlHost`
func (_ *containerAppTemplateManifestFuncs) UrlHost(s string) (string, error) {
u, err := url.Parse(s)
if err != nil {
return "", err
}
return u.Hostname(), nil
}
// ConnectionString returns the connection string for the given resource name. Presently, we only support resources of
// type `redis.v0`, `postgres.v0` and `cosmosdb.database.v0`.
//
// It is callable from a template under the name `connectionString`.
func (fns *containerAppTemplateManifestFuncs) ConnectionString(name string) (string, error) {
resource, has := fns.manifest.Resources[name]
if !has {
return "", fmt.Errorf("resource %s not found in manifest", name)
}
switch resource.Type {
case "redis.v0":
targetContainerName := scaffold.ContainerAppName(name)
cfg, err := fns.secretValue(targetContainerName, "redis-config")
if err != nil {
return "", fmt.Errorf("could not determine redis password: %w", err)
}
for _, line := range strings.Split(cfg, "\n") {
if strings.HasPrefix(line, "requirepass ") {
password := strings.TrimPrefix(line, "requirepass ")
return fmt.Sprintf("%s:6379,password=%s", targetContainerName, password), nil
}
}
return "", fmt.Errorf("could not determine redis password: no requirepass line found in redis-config")
case "postgres.database.v0":
targetContainerName := scaffold.ContainerAppName(name)
password, err := fns.secretValue(targetContainerName, "pg-password")
if err != nil {
return "", fmt.Errorf("could not determine postgres password: %w", err)
}
return fmt.Sprintf("Host=%s;Database=postgres;Username=postgres;Password=%s", targetContainerName, password), nil
case "azure.cosmosdb.account.v0":
return fns.cosmosConnectionString(name)
case "azure.cosmosdb.database.v0":
// get the parent resource name, which is the cosmos account name
return fns.cosmosConnectionString(*resource.Parent)
default:
return "", fmt.Errorf("connectionString: unsupported resource type '%s'", resource.Type)
}
}
func (fns *containerAppTemplateManifestFuncs) cosmosConnectionString(accountName string) (string, error) {
// cosmos account name can be defined with a resourceToken during provisioning
// the final name is expected to be output as SERVICE_BINDING_{accountName}_NAME
accountNameKey := fmt.Sprintf("SERVICE_BINDING_%s_NAME", scaffold.AlphaSnakeUpper(accountName))
resourceName := fns.env.Getenv(accountNameKey)
if resourceName == "" {
return "", fmt.Errorf("The value for SERVICE_BINDING_%s_NAME was not found or is empty.", accountName)
}
return fns.cosmosDbService.ConnectionString(
fns.ctx,
fns.targetResource.SubscriptionId(),
fns.targetResource.ResourceGroupName(),
resourceName)
}
// secretValue returns the value of the secret with the given name, or an error if the secret is not found. A nil value
// is returned as "", without an error.
func (fns *containerAppTemplateManifestFuncs) secretValue(containerAppName string, secretName string) (string, error) {
secrets, err := fns.containerAppService.ListSecrets(
fns.ctx, fns.targetResource.SubscriptionId(), fns.targetResource.ResourceGroupName(), containerAppName)
if err != nil {
return "", fmt.Errorf("fetching %s secrets: %w", containerAppName, err)
}
for _, secret := range secrets {
if secret.Name != nil && *secret.Name == secretName {
if secret.Value == nil {
return "", nil
}
return *secret.Value, nil
}
}
return "", fmt.Errorf("secret %s not found", secretName)
}