-
Notifications
You must be signed in to change notification settings - Fork 55
/
cmd.go
968 lines (809 loc) · 23.8 KB
/
cmd.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
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
package cmd
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"os"
"os/exec"
"path/filepath"
"sort"
"strconv"
"strings"
"syscall"
"text/tabwriter"
"time"
survey "github.com/AlecAivazis/survey/v2"
"github.com/AlecAivazis/survey/v2/terminal"
"github.com/cli/browser"
"github.com/docker/go-units"
"github.com/goware/urlx"
"github.com/infrahq/infra/internal/engine"
"github.com/infrahq/infra/internal/generate"
"github.com/infrahq/infra/internal/registry"
v1 "github.com/infrahq/infra/internal/v1"
"github.com/infrahq/infra/internal/version"
"github.com/mitchellh/go-homedir"
"github.com/muesli/termenv"
"github.com/olekukonko/tablewriter"
"github.com/spf13/cobra"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/grpclog"
grpcMetadata "google.golang.org/grpc/metadata"
"google.golang.org/protobuf/types/known/emptypb"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
clientauthenticationv1alpha1 "k8s.io/client-go/pkg/apis/clientauthentication/v1alpha1"
"k8s.io/client-go/tools/clientcmd"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
)
type Config struct {
Host string `json:"host"`
Token string `json:"token"`
SkipTLSVerify bool `json:"skip-tls-verify"`
}
type ErrUnauthenticated struct{}
func (e *ErrUnauthenticated) Error() string {
return "could not read local credentials. Are you logged in? To login, use \"infra login\""
}
func readConfig() (config *Config, err error) {
config = &Config{}
homeDir, err := os.UserHomeDir()
if err != nil {
return
}
contents, err := ioutil.ReadFile(filepath.Join(homeDir, ".infra", "config"))
if os.IsNotExist(err) {
return nil, &ErrUnauthenticated{}
}
if err != nil {
return
}
if err = json.Unmarshal(contents, &config); err != nil {
return
}
return
}
func writeConfig(config *Config) error {
homeDir, err := os.UserHomeDir()
if err != nil {
return err
}
if err = os.MkdirAll(filepath.Join(homeDir, ".infra"), os.ModePerm); err != nil {
return err
}
contents, err := json.Marshal(config)
if err != nil {
return err
}
if err = ioutil.WriteFile(filepath.Join(homeDir, ".infra", "config"), []byte(contents), 0644); err != nil {
return err
}
return nil
}
func removeConfig() error {
homeDir, err := os.UserHomeDir()
if err != nil {
return err
}
err = os.Remove(filepath.Join(homeDir, ".infra", "config"))
if err != nil {
return err
}
return nil
}
func printTable(header []string, data [][]string) {
table := tablewriter.NewWriter(os.Stdout)
if len(header) > 0 {
table.SetHeader(header)
table.SetAutoFormatHeaders(true)
table.SetHeaderAlignment(tablewriter.ALIGN_LEFT)
}
table.SetAutoWrapText(false)
table.SetAlignment(tablewriter.ALIGN_LEFT)
table.SetCenterSeparator("")
table.SetColumnSeparator("")
table.SetRowSeparator("")
table.SetHeaderLine(false)
table.SetBorder(false)
table.SetTablePadding("\t")
table.SetNoWhiteSpace(true)
table.AppendBulk(data)
table.Render()
}
func blue(s string) string {
return termenv.String(s).Bold().Foreground(termenv.ColorProfile().Color("#0057FF")).String()
}
func withClientAuthUnaryInterceptor(token string) grpc.DialOption {
return grpc.WithUnaryInterceptor(func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
return invoker(grpcMetadata.AppendToOutgoingContext(context.Background(), "authorization", "Bearer "+token), method, req, reply, cc, opts...)
})
}
func NewClient(host string, token string, skipTlsVerify bool) (v1.V1Client, context.CancelFunc, error) {
if host == "" {
return nil, nil, errors.New("host must not be empty")
}
u, err := urlx.Parse(host)
if err != nil {
return nil, nil, err
}
normalizedHost := u.Host
if u.Port() == "" {
normalizedHost += ":443"
}
ctx, cancel := context.WithCancel(context.Background())
creds := credentials.NewTLS(&tls.Config{InsecureSkipVerify: skipTlsVerify})
dialOptions := []grpc.DialOption{grpc.WithTransportCredentials(creds)}
if token != "" {
dialOptions = append(dialOptions, withClientAuthUnaryInterceptor(token))
}
conn, err := grpc.Dial(normalizedHost, dialOptions...)
if err != nil {
return nil, cancel, err
}
go func() {
<-ctx.Done()
if cerr := conn.Close(); cerr != nil {
grpclog.Infof("Failed to close conn to %s: %v", host, cerr)
}
}()
return v1.NewV1Client(conn), cancel, nil
}
func clientFromConfig() (v1.V1Client, context.CancelFunc, error) {
config, err := readConfig()
if err != nil {
return nil, nil, err
}
return NewClient(config.Host, config.Token, config.SkipTLSVerify)
}
func updateKubeconfig(destinations []*v1.Destination) (bool, error) {
home, err := homedir.Dir()
if err != nil {
return false, err
}
if destinations == nil {
destinations = make([]*v1.Destination, 0)
}
destinationsJSON, err := json.Marshal(destinations)
if err != nil {
return false, err
}
// Write destinatinons to json file
err = os.WriteFile(filepath.Join(home, ".infra", "destinations"), destinationsJSON, 0644)
if err != nil {
return false, err
}
// Load default config and merge new config in
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
defaultConfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, &clientcmd.ConfigOverrides{})
kubeConfig, err := defaultConfig.RawConfig()
if err != nil {
return false, err
}
for _, d := range destinations {
kubeConfig.Clusters[d.Name] = &clientcmdapi.Cluster{
Server: "https://localhost:32710/client/" + d.Name,
CertificateAuthority: filepath.Join(home, ".infra", "client", "cert.pem"),
}
executable, err := os.Executable()
if err != nil {
return false, err
}
kubeConfig.AuthInfos[d.Name] = &clientcmdapi.AuthInfo{
Exec: &clientcmdapi.ExecConfig{
Command: executable,
Args: []string{"creds"},
APIVersion: "client.authentication.k8s.io/v1alpha1",
},
}
kubeConfig.Contexts[d.Name] = &clientcmdapi.Context{
Cluster: d.Name,
AuthInfo: d.Name,
}
}
for name, c := range kubeConfig.Clusters {
if !strings.HasPrefix(c.Server, "https://localhost:32710/client/") {
continue
}
var exists bool
for _, d := range destinations {
if name == d.Name {
exists = true
}
}
if !exists {
delete(kubeConfig.Clusters, name)
delete(kubeConfig.Contexts, name)
delete(kubeConfig.AuthInfos, name)
}
}
if err = clientcmd.WriteToFile(kubeConfig, defaultConfig.ConfigAccess().GetDefaultFilename()); err != nil {
return false, err
}
return len(destinations) > 0, nil
}
var rootCmd = &cobra.Command{
Use: "infra",
Short: "Infrastructure Identity & Access Management (IAM)",
PersistentPreRun: func(cmd *cobra.Command, args []string) {
cmd.SilenceUsage = true
},
}
func promptShouldSkipTLSVerify(host string) (skipTlsVerify bool, proceed bool, err error) {
httpClient := &http.Client{}
httpClient.Transport = &http.Transport{
TLSClientConfig: &tls.Config{},
}
url, err := urlx.Parse(host)
if err != nil {
return false, false, err
}
url.Scheme = "https"
urlString := url.String()
_, err = httpClient.Get(urlString)
if err != nil {
if !errors.As(err, &x509.UnknownAuthorityError{}) && !errors.As(err, &x509.HostnameError{}) {
return false, false, err
}
proceed := false
fmt.Println()
fmt.Print("Could not verify certificate for host ")
fmt.Print(termenv.String(host).Bold())
fmt.Println()
prompt := &survey.Confirm{
Message: "Are you sure you want to continue?",
}
err := survey.AskOne(prompt, &proceed, survey.WithIcons(func(icons *survey.IconSet) {
icons.Question.Text = blue("?")
}))
if err != nil {
fmt.Println(err.Error())
return false, false, err
}
if !proceed {
return false, false, nil
}
return true, true, nil
}
return false, true, nil
}
var loginCmd = &cobra.Command{
Use: "login REGISTRY",
Short: "Login to an Infra Registry",
Args: cobra.ExactArgs(1),
Example: "$ infra login infra.example.com",
RunE: func(cmd *cobra.Command, args []string) error {
skipTLSVerify, proceed, err := promptShouldSkipTLSVerify(args[0])
if err != nil {
return err
}
if !proceed {
return nil
}
client, close, err := NewClient(args[0], "", skipTLSVerify)
if err != nil {
return err
}
defer close()
res, err := client.Status(context.Background(), &emptypb.Empty{})
if err != nil {
return err
}
var loginRes *v1.LoginResponse
if !res.Admin {
fmt.Println()
fmt.Println(blue("Welcome to Infra. Get started by creating your admin user:"))
email := ""
emailPrompt := &survey.Input{
Message: "Email",
}
err = survey.AskOne(emailPrompt, &email, survey.WithShowCursor(true), survey.WithValidator(survey.Required), survey.WithIcons(func(icons *survey.IconSet) {
icons.Question.Text = blue("?")
}))
if err == terminal.InterruptErr {
return nil
}
password := ""
passwordPrompt := &survey.Password{
Message: "Password",
}
err = survey.AskOne(passwordPrompt, &password, survey.WithShowCursor(true), survey.WithValidator(survey.Required), survey.WithIcons(func(icons *survey.IconSet) {
icons.Question.Text = blue("?")
}))
if err == terminal.InterruptErr {
return nil
}
fmt.Println(blue("✓") + " Creating admin user...")
loginRes, err = client.Signup(context.Background(), &v1.SignupRequest{Email: email, Password: password})
if err != nil {
return err
}
} else {
sourcesRes, err := client.ListSources(context.Background(), &emptypb.Empty{})
if err != nil {
return err
}
sort.Slice(sourcesRes.Sources, func(i, j int) bool {
return sourcesRes.Sources[i].Created > sourcesRes.Sources[j].Created
})
options := []string{}
for _, srs := range sourcesRes.Sources {
switch srs.Type {
case v1.SourceType_OKTA:
options = append(options, fmt.Sprintf("Okta [%s]", srs.Okta.Domain))
case v1.SourceType_INFRA:
options = append(options, "Username & password")
}
}
var option int
if len(options) > 1 {
prompt := &survey.Select{
Message: "Choose a login method:",
Options: options,
}
err = survey.AskOne(prompt, &option, survey.WithIcons(func(icons *survey.IconSet) {
icons.Question.Text = blue("?")
}))
if err == terminal.InterruptErr {
return nil
}
}
source := sourcesRes.Sources[option]
var loginReq v1.LoginRequest
switch source.Type {
case v1.SourceType_OKTA:
// Start OIDC flow
// Get auth code from Okta
// Send auth code to Infra to login as a user
state := generate.RandString(12)
authorizeUrl := "https://" + source.Okta.Domain + "/oauth2/v1/authorize?redirect_uri=" + "http://localhost:8301&client_id=" + source.Okta.ClientId + "&response_type=code&scope=openid+email&nonce=" + generate.RandString(10) + "&state=" + state
fmt.Println(blue("✓") + " Logging in with Okta...")
ls, err := newLocalServer()
if err != nil {
return err
}
err = browser.OpenURL(authorizeUrl)
if err != nil {
return err
}
code, recvstate, err := ls.wait()
if err != nil {
return err
}
if state != recvstate {
return errors.New("received state is not the same as sent state")
}
loginReq.Type = v1.SourceType_OKTA
loginReq.Okta = &v1.LoginRequest_Okta{
Domain: source.Okta.Domain,
Code: code,
}
case v1.SourceType_INFRA:
email := ""
emailPrompt := &survey.Input{
Message: "Email",
}
err = survey.AskOne(emailPrompt, &email, survey.WithShowCursor(true), survey.WithValidator(survey.Required), survey.WithIcons(func(icons *survey.IconSet) {
icons.Question.Text = blue("?")
}))
if err == terminal.InterruptErr {
return nil
}
password := ""
passwordPrompt := &survey.Password{
Message: "Password",
}
err = survey.AskOne(passwordPrompt, &password, survey.WithShowCursor(true), survey.WithValidator(survey.Required), survey.WithIcons(func(icons *survey.IconSet) {
icons.Question.Text = blue("?")
}))
if err == terminal.InterruptErr {
return nil
}
fmt.Println(blue("✓") + " Logging in with username & password...")
loginReq.Type = v1.SourceType_INFRA
loginReq.Infra = &v1.LoginRequest_Infra{
Email: email,
Password: password,
}
}
loginRes, err = client.Login(context.Background(), &loginReq)
if err != nil {
return err
}
}
config := &Config{
Host: args[0],
Token: loginRes.Token,
SkipTLSVerify: skipTLSVerify,
}
err = writeConfig(config)
if err != nil {
return err
}
fmt.Println(blue("✓") + " Logged in")
// Generate client certs
home, err := homedir.Dir()
if err != nil {
return err
}
if err = os.MkdirAll(filepath.Join(home, ".infra", "client"), os.ModePerm); err != nil {
return err
}
if _, err := os.Stat(filepath.Join(home, ".infra", "client", "cert.pem")); os.IsNotExist(err) {
certBytes, keyBytes, err := generate.SelfSignedCert([]string{"localhost", "localhost:32710"})
if err != nil {
return err
}
if err = ioutil.WriteFile(filepath.Join(home, ".infra", "client", "cert.pem"), certBytes, 0644); err != nil {
return err
}
if err = ioutil.WriteFile(filepath.Join(home, ".infra", "client", "key.pem"), keyBytes, 0644); err != nil {
return err
}
// Kill client
contents, err := ioutil.ReadFile(filepath.Join(home, ".infra", "client", "pid"))
if err != nil && !os.IsNotExist(err) {
return err
}
var pid int
if !os.IsNotExist(err) {
pid, err = strconv.Atoi(string(contents))
if err != nil {
return err
}
process, _ := os.FindProcess(int(pid))
process.Kill()
}
os.Remove(filepath.Join(home, ".infra", "client", "pid"))
}
loggedInClient, close, err := NewClient(args[0], loginRes.Token, skipTLSVerify)
if err != nil {
return err
}
defer close()
destRes, err := loggedInClient.ListDestinations(context.Background(), &emptypb.Empty{})
if err != nil {
return err
}
updated, err := updateKubeconfig(destRes.Destinations)
if err != nil {
return err
}
if updated {
fmt.Println(blue("✓") + " Kubeconfig updated")
}
return nil
},
}
var logoutCmd = &cobra.Command{
Use: "logout",
Short: "Logout of an Infra Registry",
RunE: func(cmd *cobra.Command, args []string) error {
config, err := readConfig()
if err != nil {
return err
}
if config.Token == "" {
return nil
}
client, close, err := NewClient(config.Host, config.Token, config.SkipTLSVerify)
if err != nil {
return err
}
defer close()
client.Logout(context.Background(), &emptypb.Empty{})
err = removeConfig()
if err != nil {
return err
}
home, err := homedir.Dir()
if err != nil {
return err
}
contents, err := ioutil.ReadFile(filepath.Join(home, ".infra", "client", "pid"))
if err != nil && !os.IsNotExist(err) {
return err
}
var pid int
if !os.IsNotExist(err) {
pid, err = strconv.Atoi(string(contents))
if err != nil {
return err
}
process, _ := os.FindProcess(int(pid))
process.Kill()
}
os.Remove(filepath.Join(home, ".infra", "client", "pid"))
os.Remove(filepath.Join(home, ".infra", "destinations"))
// Load default config and merge new config in
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
defaultConfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, &clientcmd.ConfigOverrides{})
kubeConfig, err := defaultConfig.RawConfig()
if err != nil {
return err
}
for name, c := range kubeConfig.Clusters {
if strings.HasPrefix(c.Server, "https://localhost:32710/client/") {
delete(kubeConfig.Clusters, name)
delete(kubeConfig.Contexts, name)
delete(kubeConfig.AuthInfos, name)
}
}
if len(kubeConfig.Contexts) == 0 {
os.Remove(defaultConfig.ConfigAccess().GetDefaultFilename())
} else {
_, ok := kubeConfig.Contexts[kubeConfig.CurrentContext]
if !ok {
var firstName string
for name := range kubeConfig.Contexts {
firstName = name
break
}
kubeConfig.CurrentContext = firstName
}
}
if err = clientcmd.WriteToFile(kubeConfig, defaultConfig.ConfigAccess().GetDefaultFilename()); err != nil {
return err
}
return nil
},
}
var listCmd = &cobra.Command{
Use: "list",
Aliases: []string{"ls"},
Short: "List clusters",
RunE: func(cmd *cobra.Command, args []string) error {
client, close, err := clientFromConfig()
if err != nil {
return err
}
defer close()
res, err := client.ListDestinations(context.Background(), &emptypb.Empty{})
if err != nil {
return err
}
sort.Slice(res.Destinations, func(i, j int) bool {
return res.Destinations[i].Created > res.Destinations[j].Created
})
kubeConfig, _ := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(clientcmd.NewDefaultClientConfigLoadingRules(), nil).RawConfig()
rows := [][]string{}
for _, dest := range res.Destinations {
switch dest.Type {
case v1.DestinationType_KUBERNETES:
star := ""
if dest.Name == kubeConfig.CurrentContext {
star = "*"
}
rows = append(rows, []string{dest.Name + star, dest.Kubernetes.Endpoint})
}
}
printTable([]string{"NAME", "ENDPOINT"}, rows)
fmt.Println()
fmt.Println("To connect, run \"kubectl config use-context <name>\"")
fmt.Println()
_, err = updateKubeconfig(res.Destinations)
if err != nil {
return err
}
return nil
},
}
var usersCmd = &cobra.Command{
Use: "users",
Short: "List users",
RunE: func(cmd *cobra.Command, args []string) error {
client, close, err := clientFromConfig()
if err != nil {
return err
}
defer close()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
res, err := client.ListUsers(ctx, &v1.ListUsersRequest{})
if err != nil {
return err
}
sort.Slice(res.Users, func(i, j int) bool {
return res.Users[i].Created > res.Users[j].Created
})
rows := [][]string{}
for _, user := range res.Users {
admin := ""
if user.Admin {
admin = "x"
}
rows = append(rows, []string{user.Email, units.HumanDuration(time.Now().UTC().Sub(time.Unix(user.Created, 0))) + " ago", admin})
}
printTable([]string{"EMAIL", "CREATED", "ADMIN"}, rows)
return nil
},
}
func newRegistryCmd() (*cobra.Command, error) {
var options registry.Options
cmd := &cobra.Command{
Use: "registry",
Short: "Start Infra Registry",
RunE: func(cmd *cobra.Command, args []string) error {
return registry.Run(options)
},
}
home, err := homedir.Dir()
if err != nil {
return nil, err
}
cmd.Flags().StringVarP(&options.ConfigPath, "config", "c", "", "config file")
cmd.Flags().StringVar(&options.DefaultApiKey, "initial-apikey", os.Getenv("INFRA_REGISTRY_DEFAULT_API_KEY"), "initial api key for adding destinations")
cmd.Flags().StringVar(&options.DBPath, "db", filepath.Join(home, ".infra", "infra.db"), "path to database file")
cmd.Flags().StringVar(&options.TLSCache, "tls-cache", filepath.Join(home, ".infra", "cache"), "path to directory to cache tls self-signed and Let's Encrypt certificates")
cmd.Flags().StringVar(&options.UIProxy, "ui-proxy", "", "proxy ui requests to this host")
return cmd, nil
}
func newEngineCmd() *cobra.Command {
var options engine.Options
cmd := &cobra.Command{
Use: "engine",
Short: "Start Infra Engine",
RunE: func(cmd *cobra.Command, args []string) error {
if options.Registry == "" {
return errors.New("registry not specified (--registry or INFRA_ENGINE_REGISTRY)")
}
if options.Registry != "infra" && options.APIKey == "" {
return errors.New("api-key not specified (--api-key or INFRA_ENGINE_API_KEY)")
}
return engine.Run(options)
},
}
cmd.PersistentFlags().BoolVar(&options.ForceTLSVerify, "force-tls-verify", false, "force TLS verification")
cmd.Flags().StringVarP(&options.Registry, "registry", "r", os.Getenv("INFRA_ENGINE_REGISTRY"), "registry hostname")
cmd.Flags().StringVarP(&options.Name, "name", "n", os.Getenv("INFRA_ENGINE_NAME"), "cluster name")
cmd.Flags().StringVarP(&options.Endpoint, "endpoint", "e", os.Getenv("INFRA_ENGINE_ENDPOINT"), "cluster endpoint")
cmd.Flags().StringVar(&options.APIKey, "api-key", os.Getenv("INFRA_ENGINE_API_KEY"), "api key")
return cmd
}
var versionCmd = &cobra.Command{
Use: "version",
Aliases: []string{"v"},
Short: "Display the Infra build version",
RunE: func(cmd *cobra.Command, args []string) error {
w := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', tabwriter.AlignRight)
defer w.Flush()
fmt.Fprintln(w)
fmt.Fprintln(w, "Client:\t", version.Version)
client, close, err := clientFromConfig()
if err != nil {
switch err.(type) {
case *ErrUnauthenticated:
fmt.Fprintln(w, "Registry:\t", "not connected")
return nil
default:
return err
}
}
defer close()
// Note that we use the client to get this version, but it is in fact the server version
res, err := client.Version(context.Background(), &emptypb.Empty{})
if err != nil {
fmt.Fprintln(w, blue("✕")+" Could not retrieve registry version")
return err
}
fmt.Fprintln(w, "Registry:\t", res.Version)
fmt.Fprintln(w)
return nil
},
}
var credsCmd = &cobra.Command{
Use: "creds",
Short: "Generate credentials",
Hidden: true,
RunE: func(cmd *cobra.Command, args []string) error {
// TODO (https://github.com/infrahq/infra/issues/59): First try to read cached token
client, close, err := clientFromConfig()
if err != nil {
return err
}
defer close()
res, err := client.CreateCred(context.Background(), &emptypb.Empty{})
if err != nil {
return err
}
expiry := time.Unix(res.Expires, 0)
execCredential := &clientauthenticationv1alpha1.ExecCredential{
TypeMeta: metav1.TypeMeta{
Kind: "ExecCredential",
APIVersion: clientauthenticationv1alpha1.SchemeGroupVersion.String(),
},
Spec: clientauthenticationv1alpha1.ExecCredentialSpec{},
Status: &clientauthenticationv1alpha1.ExecCredentialStatus{
Token: res.Token,
ExpirationTimestamp: &metav1.Time{Time: expiry},
},
}
bts, err := json.Marshal(execCredential)
if err != nil {
return err
}
home, err := os.UserHomeDir()
if err != nil {
return err
}
if err = os.MkdirAll(filepath.Join(home, ".infra", "cache"), os.ModePerm); err != nil {
return err
}
contents, err := ioutil.ReadFile(filepath.Join(home, ".infra", "client", "pid"))
if err != nil && !os.IsNotExist(err) {
return err
}
var pid int
// see if proxy process is already running
if !os.IsNotExist(err) {
pid, err = strconv.Atoi(string(contents))
if err != nil {
return err
}
// verify process is still running
process, err := os.FindProcess(int(pid))
if process == nil || err != nil {
pid = 0
}
err = process.Signal(syscall.Signal(0))
if err != nil {
pid = 0
}
}
if pid == 0 {
os.Remove(filepath.Join(home, ".infra", "client", "pid"))
cmd := exec.Command(os.Args[0], "client")
err = cmd.Start()
if err != nil {
return err
}
for {
if _, err := os.Stat(filepath.Join(home, ".infra", "client", "pid")); os.IsNotExist(err) {
time.Sleep(25 * time.Millisecond)
} else {
break
}
}
}
fmt.Println(string(bts))
return nil
},
}
var clientCmd = &cobra.Command{
Use: "client",
Short: "Run local client to relay requests",
Hidden: true,
RunE: func(cmd *cobra.Command, args []string) error {
fmt.Println("Starting client")
return RunLocalClient()
},
}
func NewRootCmd() (*cobra.Command, error) {
cobra.EnableCommandSorting = false
rootCmd.AddCommand(listCmd)
rootCmd.AddCommand(usersCmd)
rootCmd.AddCommand(loginCmd)
rootCmd.AddCommand(logoutCmd)
registryCmd, err := newRegistryCmd()
if err != nil {
return nil, err
}
rootCmd.AddCommand(registryCmd)
rootCmd.AddCommand(newEngineCmd())
rootCmd.AddCommand(versionCmd)
// Hidden commands
rootCmd.AddCommand(credsCmd)
rootCmd.AddCommand(clientCmd)
return rootCmd, nil
}
func Run() error {
cmd, err := NewRootCmd()
if err != nil {
return err
}
return cmd.Execute()
}