-
Notifications
You must be signed in to change notification settings - Fork 9
/
config.go
672 lines (561 loc) · 18.3 KB
/
config.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
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
package install
import (
"context"
"errors"
"fmt"
"html/template"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"strconv"
"strings"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armsubscriptions"
"github.com/a8m/envsubst"
"github.com/eiannone/keyboard"
"github.com/golang-jwt/jwt/v5"
"github.com/ipinfo/go/v2/ipinfo"
"github.com/microsoft/tyger/cli/internal/dataplane"
"github.com/microsoft/tyger/cli/internal/install/cloudinstall"
"github.com/microsoft/tyger/cli/internal/install/dockerinstall"
"github.com/spf13/cobra"
"github.com/erikgeiser/promptkit"
"github.com/erikgeiser/promptkit/confirmation"
"github.com/erikgeiser/promptkit/selection"
"github.com/erikgeiser/promptkit/textinput"
)
func NewConfigCommand(parentCommand *cobra.Command) *cobra.Command {
installCmd := &cobra.Command{
Use: "config",
Short: "Manage the Tyger configuration file",
Long: "Manage the Tyger configuration file",
DisableFlagsInUseLine: true,
Args: cobra.NoArgs,
RunE: func(*cobra.Command, []string) error {
return errors.New("a command is required")
},
}
installCmd.AddCommand(newConfigCreateCommand())
return installCmd
}
func newConfigCreateCommand() *cobra.Command {
configPath := ""
cmd := &cobra.Command{
Use: "create -f FILE.yml",
Short: "Create a new config file",
Long: "Create a new config file",
DisableFlagsInUseLine: true,
RunE: func(cmd *cobra.Command, args []string) error {
if _, err := os.Stat(configPath); err == nil {
input := confirmation.New(fmt.Sprintf("A config file already exists at %s and will be overwritten. Continue?", configPath), confirmation.Yes)
input.WrapMode = promptkit.WordWrap
ready, err := input.RunPrompt()
if err != nil {
return err
}
if !ready {
os.Exit(1)
}
fmt.Println()
}
if err := os.MkdirAll(path.Dir(configPath), 0775); err != nil {
return fmt.Errorf("failed to create config directory: %w", err)
}
f, err := os.OpenFile(configPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return fmt.Errorf("failed to open config file for writing: %w", err)
}
defer f.Close()
options := []IdAndName{
{cloudinstall.EnvironmentKindCloud, "Azure cloud"},
{dockerinstall.EnvironmentKindDocker, "Docker"},
}
s := selection.New(
"Do you want to create a Tyger environment in the Azure cloud or on your local system using Docker?",
options)
s.Filter = nil
s.WrapMode = promptkit.WordWrap
res, err := s.RunPrompt()
if err != nil {
return err
}
fmt.Println()
switch res.id {
case cloudinstall.EnvironmentKindCloud:
if err := generateCloudConfig(cmd.Context(), f); err != nil {
return err
}
case dockerinstall.EnvironmentKindDocker:
if err := generateDockerConfig(f); err != nil {
return err
}
default:
panic(fmt.Sprintf("unexpected environment kind: %s", res.id))
}
fmt.Println("Config file written to", configPath)
return nil
},
}
cmd.Flags().StringVarP(&configPath, "file", "f", "", "The path to the config file to create")
cmd.MarkFlagRequired("file")
return cmd
}
func generateDockerConfig(configFile *os.File) error {
templateValues := dockerinstall.ConfigTemplateValues{}
c := confirmation.New("Tyger requires a cryptographic key pair to secure the data plane API. Do you want to generate a new key pair?", confirmation.Yes)
c.WrapMode = promptkit.WordWrap
shouldGenerateKey, err := c.RunPrompt()
if err != nil {
return err
}
fmt.Println()
privateKeyPath := "${HOME}/tyger-signing.pem"
var expandedPrivateKeyPath string
PromptPrivateKey:
privateKeyPath, err = prompt("Enter the path of the private key file. This must not be in a source code repository. Environment variables (${VAR}) will be expanded when reading the file.", privateKeyPath, "", nil)
if err != nil {
return err
}
expandedPrivateKeyPath, err = envsubst.String(privateKeyPath)
if err != nil {
return fmt.Errorf("failed to expand environment variables: %w", err)
}
if _, err := os.Stat(expandedPrivateKeyPath); err != nil {
if !shouldGenerateKey {
fmt.Printf("Failed to stat file at '%s'. Please enter a valid path.\n\n", expandedPrivateKeyPath)
goto PromptPrivateKey
}
} else {
if shouldGenerateKey {
c := confirmation.New("Do you want to overwrite the existing file?", confirmation.Yes)
c.WrapMode = promptkit.WordWrap
overwrite, err := c.RunPrompt()
if err != nil {
return err
}
fmt.Println()
if !overwrite {
goto PromptPrivateKey
}
}
}
baseName := strings.TrimSuffix(privateKeyPath, filepath.Ext(privateKeyPath))
publicKeyPath := fmt.Sprintf("%s-public%s", baseName, filepath.Ext(privateKeyPath))
var expandedPublicKeyPath string
PromptPublicKey:
publicKeyPath, err = prompt("Enter the path of the public key file. This must not be in a source code repository. Environment variables (${VAR}) will be expanded when reading the file.", publicKeyPath, "", nil)
if err != nil {
return err
}
expandedPublicKeyPath, err = envsubst.StringRestricted(publicKeyPath, true, false)
if err != nil {
return fmt.Errorf("failed to expand environment variables: %w", err)
}
if _, err := os.Stat(expandedPublicKeyPath); err != nil {
if !shouldGenerateKey {
fmt.Printf("Failed to stat file at '%s'. Please enter a valid path.\n\n", expandedPublicKeyPath)
goto PromptPublicKey
}
} else {
if shouldGenerateKey {
c := confirmation.New("Do you want to overwrite the existing file?", confirmation.Yes)
c.WrapMode = promptkit.WordWrap
overwrite, err := c.RunPrompt()
if err != nil {
return err
}
fmt.Println()
if !overwrite {
goto PromptPublicKey
}
}
}
templateValues.PrivateSigningKeyPath = privateKeyPath
templateValues.PublicSigningKeyPath = publicKeyPath
if shouldGenerateKey {
if err := dockerinstall.GenerateSigningKeyPair(expandedPublicKeyPath, expandedPrivateKeyPath); err != nil {
return fmt.Errorf("failed to generate key pair: %w", err)
}
}
portString := ""
port, err := dataplane.GetFreePort()
if err == nil {
portString = strconv.Itoa(port)
}
portString, err = prompt("Enter the port on which the data plane API will listen:", portString, "", regexp.MustCompile(`^\d+$`))
if err != nil {
return err
}
templateValues.DataPlanePort, err = strconv.Atoi(portString)
if err != nil {
return err
}
return dockerinstall.RenderConfig(templateValues, configFile)
}
func generateCloudConfig(ctx context.Context, configFile *os.File) error {
if _, err := exec.LookPath("az"); err != nil {
return errors.New("please install the Azure CLI (az) first")
}
ipInfoClient := ipinfo.NewClient(nil, nil, "")
ip, err := ipInfoClient.GetIPInfo(nil)
if err != nil {
return fmt.Errorf("failed to get current external IP address: %w", err)
}
templateValues := cloudinstall.ConfigTemplateValues{
KubernetesVersion: cloudinstall.DefaultKubernetesVersion,
PostgresMajorVersion: cloudinstall.DefaultPostgresMajorVersion,
CurrentIpAddress: ip.IP.String(),
}
fmt.Printf("\nLet's collect settings for the Azure subscription to use. This is where cloud resources will be deployed.\n\n")
var cred azcore.TokenCredential
for {
var principal ExtendedPrincipal
for {
cred, err = cloudinstall.NewMiAwareAzureCLICredential(nil)
if err == nil {
principal, err = getCurrentPrincipal(ctx, cred)
}
if err != nil {
if err == cloudinstall.ErrNotLoggedIn {
fmt.Printf("You are not logged in to Azure. Please run `az login` in another terminal window.\nPress any key to continue when ready...\n\n")
getSingleKey()
continue
}
return err
}
break
}
input := confirmation.New(fmt.Sprintf("You are logged in as %s. Is that the right account?", principal.String()), confirmation.Yes)
input.WrapMode = promptkit.WordWrap
ready, err := input.RunPrompt()
if err != nil {
return err
}
fmt.Println()
if ready {
break
}
fmt.Printf("Please run `az login` in another terminal window.\nPress any key to continue when ready...\n\n")
getSingleKey()
}
templateValues.TenantId, err = chooseTenant(cred, "Select the tenant associated with the subscription:", false)
if err != nil {
return err
}
tenantCred, err := cloudinstall.NewMiAwareAzureCLICredential(
&azidentity.AzureCLICredentialOptions{
TenantID: templateValues.TenantId,
})
if err != nil {
return err
}
principal, err := getCurrentPrincipal(ctx, tenantCred)
if err != nil {
return err
}
templateValues.Principal = principal.Principal
for {
templateValues.SubscriptionId, err = chooseSubscription(tenantCred)
if err != nil {
if strings.Contains(err.Error(), "AADSTS50076") {
fmt.Printf("Run 'az login --tenant %s' in another terminal window to explicitly login to this tenant.\nPress any key when ready...\n\n", templateValues.TenantId)
getSingleKey()
continue
}
return err
}
break
}
templateValues.EnvironmentName, err = prompt("Give this environment a name:", "", "", cloudinstall.ResourceNameRegex)
if err != nil {
return err
}
templateValues.ResourceGroup, err = prompt("Enter a name for a resource group:", templateValues.EnvironmentName, "", cloudinstall.ResourceNameRegex)
if err != nil {
return err
}
templateValues.DefaultLocation, err = chooseLocation(tenantCred, templateValues.SubscriptionId)
if err != nil {
return err
}
templateValues.DatabaseServerName, err = prompt("Give the database server a name:", fmt.Sprintf("%s-tyger", templateValues.EnvironmentName), "", cloudinstall.DatabaseServerNameRegex)
if err != nil {
return err
}
templateValues.BufferStorageAccountName, err = prompt("Give the buffer storage account a name:", fmt.Sprintf("%s%sbuf", templateValues.EnvironmentName, templateValues.DefaultLocation), "", cloudinstall.StorageAccountNameRegex)
if err != nil {
return err
}
templateValues.LogsStorageAccountName, err = prompt("Give the logs storage account a name:", fmt.Sprintf("%stygerlogs", templateValues.EnvironmentName), "", cloudinstall.StorageAccountNameRegex)
if err != nil {
return err
}
positiveIntegerRegex := regexp.MustCompile(`^\d+$`)
if numString, err := prompt("Enter the minimum node count for the CPU node pool:", "1", "", positiveIntegerRegex); err != nil {
return err
} else {
templateValues.CpuNodePoolMinCount, _ = strconv.Atoi(numString)
}
if numString, err := prompt("Enter the minimum node count for the GPU node pool:", "0", "", positiveIntegerRegex); err != nil {
return err
} else {
templateValues.GpuNodePoolMinCount, _ = strconv.Atoi(numString)
}
suggestedDomainName := fmt.Sprintf("%s-tyger", templateValues.EnvironmentName)
domainSuffix := cloudinstall.GetDomainNameSuffix(templateValues.DefaultLocation)
domainLabel, err := prompt("Choose a domain name for the Tyger service:", suggestedDomainName, domainSuffix, cloudinstall.SubdomainRegex)
if err != nil {
return err
}
templateValues.DomainName = fmt.Sprintf("%s%s", domainLabel, domainSuffix)
fmt.Printf("Now for the tenant associated with the Tyger service.\n\n")
input := confirmation.New("Do you want to use the same tenant for the Tyger service?", confirmation.Yes)
input.WrapMode = promptkit.WordWrap
sameTenant, err := input.RunPrompt()
if err != nil {
return err
}
if sameTenant {
templateValues.ApiTenantId = templateValues.TenantId
} else {
for {
res, err := chooseTenant(cred, "Choose a tenant for the Tyger service:", true)
if err != nil {
return err
}
if res == "other" {
fmt.Printf("Run 'az login' in another terminal window.\nPress any key when ready...\n\n")
getSingleKey()
continue
} else {
templateValues.ApiTenantId = res
break
}
}
}
err = cloudinstall.RenderConfig(templateValues, configFile)
if err != nil {
return fmt.Errorf("failed to write config file: %w", err)
}
return nil
}
func chooseLocation(cred azcore.TokenCredential, subscriptionId string) (string, error) {
c, err := armsubscriptions.NewClient(cred, nil)
if err != nil {
return "", fmt.Errorf("failed to create subscriptions client: %w", err)
}
locations := make([]IdAndName, 0)
pager := c.NewListLocationsPager(subscriptionId, nil)
for pager.More() {
page, err := pager.NextPage(context.Background())
if err != nil {
return "", fmt.Errorf("failed to enumerate locations: %w", err)
}
for _, l := range page.LocationListResult.Value {
if *l.Metadata.RegionType == armsubscriptions.RegionTypePhysical {
locations = append(locations, IdAndName{
id: *l.Name,
name: *l.DisplayName,
})
}
}
}
if len(locations) == 0 {
return "", errors.New("no Azure locations are available for this subscription")
}
sp := selection.New("Select a default Azure location:", locations)
sp.Filter = func(filterText string, choice *selection.Choice[IdAndName]) bool {
return choice.Value.MatchesFilter(filterText)
}
res, err := sp.RunPrompt()
if err != nil {
return "", err
}
fmt.Println()
return res.id, nil
}
func chooseSubscription(cred azcore.TokenCredential) (string, error) {
subscriptionsClient, _ := armsubscriptions.NewClient(cred, nil)
subscriptions := make([]IdAndName, 0)
pager := subscriptionsClient.NewListPager(nil)
for pager.More() {
page, err := pager.NextPage(context.Background())
if err != nil {
return "", fmt.Errorf("failed to enumerate subscriptions: %w", err)
}
for _, sub := range page.SubscriptionListResult.Value {
subscriptions = append(subscriptions, IdAndName{
id: *sub.SubscriptionID,
name: *sub.DisplayName,
})
}
}
if len(subscriptions) == 0 {
return "", errors.New("no subscriptions found")
}
sp := selection.New("Select the Azure subscription to use:", subscriptions)
sp.Filter = func(filterText string, choice *selection.Choice[IdAndName]) bool {
return choice.Value.MatchesFilter(filterText)
}
sub, err := sp.RunPrompt()
if err != nil {
return "", err
}
fmt.Println()
return sub.id, nil
}
func getCurrentPrincipal(ctx context.Context, cred azcore.TokenCredential) (principal ExtendedPrincipal, err error) {
tokenResponse, err := cred.GetToken(ctx, policy.TokenRequestOptions{Scopes: []string{cloud.AzurePublic.Services[cloud.ResourceManager].Audience}})
if err != nil {
return principal, cloudinstall.ErrNotLoggedIn
}
claims := jwt.MapClaims{}
_, _, err = jwt.NewParser().ParseUnverified(tokenResponse.Token, claims)
if err != nil {
return principal, fmt.Errorf("failed to parse token: %w", err)
}
principal.ObjectId = claims["oid"].(string)
principals, err := cloudinstall.ObjectsIdToPrincipals(ctx, cred, []string{principal.ObjectId})
if err != nil {
return principal, err
}
if len(principals) == 0 {
return principal, errors.New("principal not found")
}
principal.Kind = principals[0].Kind
switch principals[0].Kind {
case cloudinstall.PrincipalKindUser:
principal.UserPrincipalName, err = cloudinstall.GetUserPrincipalName(ctx, cred, principals[0].ObjectId)
if err != nil {
return principal, err
}
case cloudinstall.PrincipalKindServicePrincipal:
principal.Display, err = cloudinstall.GetServicePrincipalDisplayName(ctx, cred, principals[0].ObjectId)
if err != nil {
return principal, err
}
default:
panic(fmt.Sprintf("unexpected principal kind: %s", principals[0].Kind))
}
return principal, nil
}
func chooseTenant(cred azcore.TokenCredential, prompt string, presentOtherOption bool) (string, error) {
tenantsClient, err := armsubscriptions.NewTenantsClient(cred, nil)
if err != nil {
return "", err
}
tenants := make([]IdAndName, 0)
pager := tenantsClient.NewListPager(nil)
for pager.More() {
page, err := pager.NextPage(context.Background())
if err != nil {
return "", fmt.Errorf("failed to enumerate tenants: %w", err)
}
for _, ten := range page.TenantListResult.Value {
tenant := IdAndName{
id: *ten.TenantID,
}
if ten.DisplayName != nil {
tenant.name = *ten.DisplayName
} else {
tenant.name = tenant.id
}
tenants = append(tenants, tenant)
}
}
if len(tenants) == 0 {
panic("no tenants found")
}
if presentOtherOption {
tenants = append(tenants, IdAndName{
id: "other",
name: "***OTHER***",
})
}
if len(tenants) == 1 {
return tenants[0].id, nil
} else {
sp := selection.New(prompt, tenants)
sp.Filter = func(filterText string, choice *selection.Choice[IdAndName]) bool {
return choice.Value.MatchesFilter(filterText)
}
sp.PageSize = 0
t, err := sp.RunPrompt()
if err != nil {
return "", err
}
fmt.Println()
return t.id, nil
}
}
type IdAndName struct {
id string
name string
}
func (t IdAndName) String() string {
return t.name
}
func (t IdAndName) MatchesFilter(filterText string) bool {
return strings.Contains(strings.ReplaceAll(strings.ToLower(t.String()), " ", ""), strings.ToLower(filterText))
}
func prompt(question, initialValue string, suffix string, validationRegex *regexp.Regexp) (string, error) {
const tmpl = `
{{- Bold .Prompt }} {{ .Input -}} {{ Suffix }}
{{- if .ValidationError }} {{ Foreground "1" (Bold "✘") }}
{{ Faint (Bold .ValidationError.Error) }}
{{- else }} {{ Foreground "2" (Bold "✔") }}
{{- end -}}
`
const resultTmpl = `
{{- print .Prompt " " (Foreground "32" (Mask .FinalValue)) (Suffix) "\n" -}}
`
input := textinput.New(question)
input.WrapMode = promptkit.WordWrap
input.InitialValue = initialValue
if validationRegex != nil {
input.Validate = func(s string) error {
if validationRegex.MatchString(s) {
return nil
}
return fmt.Errorf("must match the regex %s", validationRegex.String())
}
}
input.ExtendedTemplateFuncs = template.FuncMap{
"Suffix": func() string {
return suffix
},
}
input.Template = tmpl
input.ResultTemplate = resultTmpl
defer fmt.Println()
return input.RunPrompt()
}
func getSingleKey() {
_, key, err := keyboard.GetSingleKey()
if err != nil {
panic(err)
}
if key == keyboard.KeyCtrlC {
os.Exit(1)
}
}
type ExtendedPrincipal struct {
cloudinstall.Principal
Display string
}
func (p ExtendedPrincipal) String() string {
if p.UserPrincipalName != "" {
return p.UserPrincipalName
}
if p.Display != "" {
return p.Display
}
return p.ObjectId
}