-
Notifications
You must be signed in to change notification settings - Fork 79
/
app.go
1038 lines (875 loc) · 28 KB
/
app.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
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
package cmd
import (
"fmt"
"io"
"os"
"strings"
"time"
"github.com/fatih/color"
"github.com/luizalabs/teresa/pkg/client"
"github.com/luizalabs/teresa/pkg/client/connection"
appb "github.com/luizalabs/teresa/pkg/protobuf/app"
"github.com/olekukonko/tablewriter"
"github.com/spf13/cobra"
"golang.org/x/net/context"
)
const (
//Service name component must be a valid RFC 1035 name
appNameLimit = 63
flagNotDefined = -1
)
var appCmd = &cobra.Command{
Use: "app",
Short: "Everything about apps",
}
var appCreateCmd = &cobra.Command{
Use: "create <name>",
Short: "Creates a new app",
Long: `Creates a new application.
You should provide the unique name for the App and the team name in order to create a new App.
Remember, all team members can view and modify this newly created app.
The app name must follow this rules:
- must contain only letters and the special character "-"
- must start and finish with a letter
- something like: foo or foo-bar`,
Example: ` $ teresa app create foo --team bar
With specific process type:
$ teresa app create foo-worker --team bar --process-type worker
With scale rules... min 2, max 10 pods, scalling with a cpu target of 70%
$ teresa app create foo --team bar --scale-min 2 --scale-max 10 --scale-cpu 70
With specific cpu and memory size...
$ teresa create foo --team bar --cpu 200m --max-cpu 500m --memory 512Mi --max-memory 1Gi
With virtual host
$ teresa create foo --team bar --vhost foo.teresa.io
An internal app (without external endpoint)
$ teresa create foo --team bar --internal
An app that uses the grpc protocol:
$ teresa create foo --team bar --protocol grpc
With all flags...
$ teresa app create foo --team bar --cpu 200m --max-cpu 500m --memory 512Mi --max-memory 1Gi \
--scale-min 2 --scale-max 10 --scale-cpu 70 --process-type web --protocol http`,
Run: createApp,
}
func createApp(cmd *cobra.Command, args []string) {
if len(args) != 1 {
cmd.Usage()
return
}
name := args[0]
if len(name) > appNameLimit {
client.PrintErrorAndExit("Invalid app name (max %d characters)", appNameLimit)
}
team, err := cmd.Flags().GetString("team")
if err != nil || team == "" {
client.PrintErrorAndExit("Invalid team parameter")
}
targetCPU, err := cmd.Flags().GetInt32("scale-cpu")
if err != nil {
client.PrintErrorAndExit("Invalid scale-cpu parameter")
}
scaleMax, err := cmd.Flags().GetInt32("scale-max")
if err != nil {
client.PrintErrorAndExit("Invalid scale-max parameter")
}
scaleMin, err := cmd.Flags().GetInt32("scale-min")
if err != nil {
client.PrintErrorAndExit("Invalid scale-min parameter")
}
cpu, err := cmd.Flags().GetString("cpu")
if err != nil {
client.PrintErrorAndExit("Invalid cpu parameter")
}
memory, err := cmd.Flags().GetString("memory")
if err != nil {
client.PrintErrorAndExit("Invalid memory parameter")
}
maxCPU, err := cmd.Flags().GetString("max-cpu")
if err != nil {
client.PrintErrorAndExit("Invalid max-cpu parameter")
}
maxMemory, err := cmd.Flags().GetString("max-memory")
if err != nil {
client.PrintErrorAndExit("Invalid max-memory parameter")
}
processType, err := cmd.Flags().GetString("process-type")
if err != nil {
client.PrintErrorAndExit("Invalid process-type parameter")
}
vHost, err := cmd.Flags().GetString("vhost")
if err != nil {
client.PrintErrorAndExit("Invalid vhost parameter")
}
internal, err := cmd.Flags().GetBool("internal")
if err != nil {
client.PrintErrorAndExit("Invalid internal parameter")
}
protocol, err := cmd.Flags().GetString("protocol")
if err != nil {
client.PrintErrorAndExit("Invalid protocol parameter")
}
conn, err := connection.New(cfgFile, cfgCluster)
if err != nil {
client.PrintErrorAndExit("Error connecting to server: %v", err)
}
defer conn.Close()
lim := &appb.CreateRequest_Limits{
Default: []*appb.CreateRequest_Limits_LimitRangeQuantity{
{
Resource: "cpu",
Quantity: maxCPU,
},
{
Resource: "memory",
Quantity: maxMemory,
},
},
DefaultRequest: []*appb.CreateRequest_Limits_LimitRangeQuantity{
{
Resource: "cpu",
Quantity: cpu,
},
{
Resource: "memory",
Quantity: memory,
},
},
}
as := &appb.CreateRequest_Autoscale{
CpuTargetUtilization: targetCPU,
Min: scaleMin,
Max: scaleMax,
}
cli := appb.NewAppClient(conn)
_, err = cli.Create(
context.Background(),
&appb.CreateRequest{
Name: name,
Team: team,
ProcessType: processType,
VirtualHost: vHost,
Limits: lim,
Autoscale: as,
Internal: internal,
Protocol: protocol,
},
)
if err != nil {
client.PrintErrorAndExit(client.GetErrorMsg(err))
}
fmt.Println("App created")
}
var appListCmd = &cobra.Command{
Use: "list",
Short: "List all apps",
Long: "Return all apps with address and team.",
Example: " $ teresa app list",
Run: appList,
}
func appList(cmd *cobra.Command, args []string) {
conn, err := connection.New(cfgFile, cfgCluster)
if err != nil {
client.PrintErrorAndExit("Error connecting to server: %v", err)
}
defer conn.Close()
cli := appb.NewAppClient(conn)
resp, err := cli.List(context.Background(), &appb.Empty{})
if err != nil {
client.PrintErrorAndExit(client.GetErrorMsg(err))
}
if len(resp.Apps) == 0 {
fmt.Println("You don't have any app")
return
}
// rendering app list in a table view
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"TEAM", "APP", "ADDRESS"})
table.SetRowLine(true)
table.SetAlignment(tablewriter.ALIGN_LEFT)
table.SetRowSeparator("-")
table.SetAutoWrapText(false)
for _, a := range resp.Apps {
urls := strings.Join(a.Urls, ",")
if urls == "" {
urls = "n/a"
}
r := []string{a.Team, a.Name, urls}
table.Append(r)
}
table.Render()
}
var appDelCmd = &cobra.Command{
Use: "delete <name>",
Short: "Delete app",
Long: "Delete app.",
Example: " $ teresa app delete foo",
Run: appDel,
}
func appDel(cmd *cobra.Command, args []string) {
if len(args) != 1 {
cmd.Usage()
return
}
name := args[0]
conn, err := connection.New(cfgFile, cfgCluster)
if err != nil {
client.PrintErrorAndExit("Error connecting to server: %v", err)
}
defer conn.Close()
cli := appb.NewAppClient(conn)
if err != nil {
client.PrintErrorAndExit(client.GetErrorMsg(err))
}
fmt.Print()
s, _ := client.GetInput("Are you sure? (yes/NO)? ")
if s != "yes" {
fmt.Println("Delete process aborted!")
return
}
resp, _ := client.GetInput("Please re type the app name: ")
if resp != name {
fmt.Println("Delete process aborted!")
return
}
_, err = cli.Delete(context.Background(), &appb.DeleteRequest{Name: name})
if err != nil {
client.PrintErrorAndExit(client.GetErrorMsg(err))
return
}
fmt.Printf("App %s deleted!\n", name)
}
var appInfoCmd = &cobra.Command{
Use: "info <name>",
Short: "All infos about the app",
Long: "Return all infos about an specific app, like addresses, scale, auto scale, etc...",
Example: " $ teresa app info foo",
Run: appInfo,
}
func appInfo(cmd *cobra.Command, args []string) {
if len(args) != 1 {
cmd.Usage()
return
}
name := args[0]
conn, err := connection.New(cfgFile, cfgCluster)
if err != nil {
client.PrintErrorAndExit("Error connecting to server: %v", err)
}
defer conn.Close()
cli := appb.NewAppClient(conn)
info, err := cli.Info(context.Background(), &appb.InfoRequest{Name: name})
if err != nil {
client.PrintErrorAndExit(client.GetErrorMsg(err))
}
color.New(color.FgCyan, color.Bold).Printf("[%s]\n", name)
bold := color.New(color.Bold).SprintFunc()
fmt.Println(bold("team:"), info.Team)
if len(info.Addresses) > 0 {
fmt.Println(bold("addresses:"))
for _, addr := range info.Addresses {
fmt.Printf(" %s\n", addr.Hostname)
}
}
if info.Protocol != "" {
fmt.Println(bold("protocol:"), info.Protocol)
}
if len(info.EnvVars) > 0 {
client.SortEnvsByKey(info.EnvVars)
fmt.Println(bold("env vars:"))
for _, ev := range info.EnvVars {
fmt.Printf(" %s=%s\n", ev.Key, ev.Value)
}
}
if info.Status != nil {
pods := make([]*appb.InfoResponse_Status_Pod, 0)
for _, pod := range info.Status.Pods {
// Don't print pods in OutOfCpu or Evicted status
if pod.State != "" {
pods = append(pods, pod)
}
}
fmt.Println(bold("status:"))
if info.Status.Cpu >= 0 {
fmt.Printf(" %s %d%%\n", bold("cpu:"), info.Status.Cpu)
}
fmt.Printf(" %s %d\n", bold("pods:"), len(pods))
for _, pod := range pods {
age := shortHumanDuration(time.Duration(pod.Age))
fmt.Printf(" Name: %s State: %s Age: %s Restarts: %d Ready: %v\n", pod.Name, pod.State, age, pod.Restarts, pod.Ready)
}
}
if info.Autoscale != nil {
fmt.Println(bold("autoscale:"))
fmt.Printf(" %s %d%%\n", bold("cpu:"), info.Autoscale.CpuTargetUtilization)
fmt.Printf(" %s %d\n", bold("max:"), info.Autoscale.Max)
fmt.Printf(" %s %d\n", bold("min:"), info.Autoscale.Min)
}
fmt.Println(bold("limits:"))
if len(info.Limits.Default) > 0 {
fmt.Println(bold(" defaults"))
for _, item := range info.Limits.Default {
fmt.Printf(" %s %s\n", bold(item.Resource), item.Quantity)
}
}
if len(info.Limits.DefaultRequest) > 0 {
fmt.Println(bold(" request"))
for _, item := range info.Limits.DefaultRequest {
fmt.Printf(" %s %s\n", bold(item.Resource), item.Quantity)
}
}
}
func prepareEnvAndSecretSet(label, currentClusterName string, cmd *cobra.Command, args []string) (*appb.SetEnvRequest, error) {
if len(args) == 0 {
cmd.Usage()
return nil, nil
}
appName, err := cmd.Flags().GetString("app")
if err != nil || appName == "" {
return nil, fmt.Errorf("Invalid app parameter")
}
evs := make([]*appb.SetEnvRequest_EnvVar, len(args))
for i, item := range args {
tmp := strings.SplitN(item, "=", 2)
if len(tmp) != 2 {
return nil, fmt.Errorf("%s must be in the format FOO=bar", label)
}
evs[i] = &appb.SetEnvRequest_EnvVar{Key: tmp[0], Value: tmp[1]}
}
fmt.Printf("Setting %s and %s %s on %s...\n", label, color.YellowString("restarting"), color.CyanString(`"%s"`, appName), color.YellowString(`"%s"`, currentClusterName))
for _, ev := range evs {
fmt.Printf(" %s: %s\n", ev.Key, ev.Value)
}
noinput, err := cmd.Flags().GetBool("no-input")
if err != nil {
return nil, fmt.Errorf("Invalid no-input parameter")
}
if !noinput {
s, _ := client.GetInput("Are you sure? (yes/NO)? ")
if s != "yes" {
return nil, nil
}
}
return &appb.SetEnvRequest{Name: appName, EnvVars: evs}, nil
}
var appEnvSetCmd = &cobra.Command{
Use: "env-set [KEY=value, ...]",
Short: "Set env vars for the app",
Long: `Create or update an environment variable for the app.
You can add a new environment variable for the app, or update if it already exists.
WARNING:
If you need to set more than one env var to the application, provide all at once.
Every time this command is called, the application needs to be restared.`,
Example: ` To add an new env var called "FOO":
$ teresa app env-set FOO=bar --app myapp
You can also provide more than one env var at a time:
$ teresa app env-set FOO=bar BAR=foo --app myapp`,
Run: appEnvSet,
}
func appEnvSet(cmd *cobra.Command, args []string) {
currentClusterName := cfgCluster
if currentClusterName == "" {
var err error
currentClusterName, err = getCurrentClusterName()
if err != nil {
client.PrintErrorAndExit("error reading config file: %v", err)
}
}
req, err := prepareEnvAndSecretSet("Env vars", currentClusterName, cmd, args)
if err != nil {
client.PrintErrorAndExit("%s", err)
} else if req == nil {
return
}
conn, err := connection.New(cfgFile, currentClusterName)
if err != nil {
client.PrintErrorAndExit("Error connecting to server: %s", err)
}
defer conn.Close()
cli := appb.NewAppClient(conn)
if _, err := cli.SetEnv(context.Background(), req); err != nil {
client.PrintErrorAndExit(client.GetErrorMsg(err))
}
fmt.Println("Env vars updated with success")
}
func prepareEnvAndSecretUnSet(label, currentClusterName string, cmd *cobra.Command, args []string) (*appb.UnsetEnvRequest, error) {
if len(args) == 0 {
cmd.Usage()
return nil, nil
}
appName, err := cmd.Flags().GetString("app")
if err != nil || appName == "" {
return nil, fmt.Errorf("Invalid app parameter")
}
fmt.Printf("Unsetting %s and %s %s on %s...\n", label, color.YellowString("restarting"), color.CyanString(`"%s"`, appName), color.YellowString(`"%s"`, currentClusterName))
for _, ev := range args {
fmt.Printf(" %s\n", ev)
}
noinput, err := cmd.Flags().GetBool("no-input")
if err != nil {
return nil, fmt.Errorf("Invalid no-input parameter")
}
if !noinput {
s, _ := client.GetInput("Are you sure? (yes/NO)? ")
if s != "yes" {
return nil, nil
}
}
return &appb.UnsetEnvRequest{Name: appName, EnvVars: args}, nil
}
var appEnvUnSetCmd = &cobra.Command{
Use: "env-unset [KEY, ...]",
Short: "Unset env vars for the app",
Long: `Unset an environment variable for the app.
You can remove one or more environment variables from the application.
WARNING:
If you need to unset more than one env var from the application, provide all at once.
Every time this command is called, the application needs to be restarted.`,
Example: ` To unset an env var called "FOO":
$ teresa app env-unset FOO --app myapp
You can also provide more than one env var at a time:
$ teresa app env-unset FOO BAR --app myapp`,
Run: appEnvUnset,
}
func appEnvUnset(cmd *cobra.Command, args []string) {
currentClusterName := cfgCluster
if currentClusterName == "" {
var err error
currentClusterName, err = getCurrentClusterName()
if err != nil {
client.PrintErrorAndExit("error reading config file: %v", err)
}
}
req, err := prepareEnvAndSecretUnSet("Env vars", currentClusterName, cmd, args)
if err != nil {
client.PrintErrorAndExit("%s", err)
} else if req == nil {
return
}
conn, err := connection.New(cfgFile, currentClusterName)
if err != nil {
client.PrintErrorAndExit("Error connecting to server: %s", err)
}
defer conn.Close()
cli := appb.NewAppClient(conn)
if _, err := cli.UnsetEnv(context.Background(), req); err != nil {
client.PrintErrorAndExit(client.GetErrorMsg(err))
}
fmt.Println("Env vars updated with success")
}
var appSecretSetCmd = &cobra.Command{
Use: "secret-set [KEY=value, ...]",
Short: "Set secert (as env vars) for the app",
Long: `Create or update a secret for the app.
You can add a new secret for the app, or update if it already exists.
WARNING:
If you need to set more than one secret to the application, provide all at once.
Every time this command is called, the application needs to be restared.`,
Example: ` To add an new secret called "FOO":
$ teresa app secret-set FOO=bar --app myapp
You can also provide more than one env var at a time:
$ teresa app secret-set FOO=bar BAR=foo --app myapp`,
Run: appSecretSet,
}
func appSecretSet(cmd *cobra.Command, args []string) {
currentClusterName := cfgCluster
if currentClusterName == "" {
var err error
currentClusterName, err = getCurrentClusterName()
if err != nil {
client.PrintErrorAndExit("error reading config file: %v", err)
}
}
req, err := prepareEnvAndSecretSet("Secrets", currentClusterName, cmd, args)
if err != nil {
client.PrintErrorAndExit("%s", err)
} else if req == nil {
return
}
conn, err := connection.New(cfgFile, currentClusterName)
if err != nil {
client.PrintErrorAndExit("Error connecting to server: %s", err)
}
defer conn.Close()
cli := appb.NewAppClient(conn)
if _, err := cli.SetSecret(context.Background(), req); err != nil {
client.PrintErrorAndExit(client.GetErrorMsg(err))
}
fmt.Println("Secrets updated with success")
}
var appSecretUnSetCmd = &cobra.Command{
Use: "secret-unset [KEY, ...]",
Short: "Unset secrets for the app",
Long: `Unset a secrets for the app.
You can remove one or more secrets from the application.
WARNING:
If you need to unset more than one secrets from the application, provide all at once.
Every time this command is called, the application needs to be restarted.`,
Example: ` To unset a secret called "FOO":
$ teresa app secret-unset FOO --app myapp
You can also provide more than one env var at a time:
$ teresa app secret-unset FOO BAR --app myapp`,
Run: appSecretUnset,
}
func appSecretUnset(cmd *cobra.Command, args []string) {
currentClusterName := cfgCluster
if currentClusterName == "" {
var err error
currentClusterName, err = getCurrentClusterName()
if err != nil {
client.PrintErrorAndExit("error reading config file: %v", err)
}
}
req, err := prepareEnvAndSecretUnSet("Secrets", currentClusterName, cmd, args)
if err != nil {
client.PrintErrorAndExit("%s", err)
} else if req == nil {
return
}
conn, err := connection.New(cfgFile, currentClusterName)
if err != nil {
client.PrintErrorAndExit("Error connecting to server: %s", err)
}
defer conn.Close()
cli := appb.NewAppClient(conn)
if _, err := cli.UnsetSecret(context.Background(), req); err != nil {
client.PrintErrorAndExit(client.GetErrorMsg(err))
}
fmt.Println("Secrets updated with success")
}
var appLogsCmd = &cobra.Command{
Use: "logs <name>",
Short: "Show app logs",
Long: `Show application logs.
WARNING:
Lines are collected from all pods.`,
Example: ` $ teresa app logs foo
To change the number of lines:
$ teresa app logs foo --lines=20
To filter logs by pod name:
$ teresa app logs foo --pod mypod-1234
To filter by container name:
$ teresa app logs foo --container nginx
You can also simulate tail -f:
$ teresa app logs foo --lines=20 --follow`,
Run: appLogs,
Aliases: []string{"log"},
}
var appAutoscaleSetCmd = &cobra.Command{
Use: "autoscale <name> [flags]",
Short: "Set autoscale parameters for the app",
Long: `Set application's autoscaling.
You can set the lower and upper limit for the number of pods of the application, as well as the
target CPU utilization to trigger the autoscaler.
Example: To set the number minimum of replicas to 2:
$ teresa app autoscale myapp --min 2`,
Run: appAutoscaleSet,
}
func appAutoscaleSet(cmd *cobra.Command, args []string) {
if len(args) != 1 {
cmd.Usage()
return
}
name := args[0]
min, err := cmd.Flags().GetInt32("min")
if err != nil {
client.PrintErrorAndExit("invalid min parameter")
}
max, err := cmd.Flags().GetInt32("max")
if err != nil {
client.PrintErrorAndExit("invalid max parameter")
}
cpu, err := cmd.Flags().GetInt32("cpu-percent")
if err != nil {
client.PrintErrorAndExit("invalid cpu-percent parameter")
}
if msg, isValid := validateFlags(min, max); !isValid {
client.PrintErrorAndExit(msg)
}
conn, err := connection.New(cfgFile, cfgCluster)
if err != nil {
client.PrintErrorAndExit("Error connecting to server: %s", err)
}
defer conn.Close()
as := &appb.SetAutoscaleRequest_Autoscale{
Min: min,
Max: max,
CpuTargetUtilization: cpu,
}
req := &appb.SetAutoscaleRequest{
Name: name,
Autoscale: as,
}
cli := appb.NewAppClient(conn)
if _, err := cli.SetAutoscale(context.Background(), req); err != nil {
client.PrintErrorAndExit(client.GetErrorMsg(err))
}
fmt.Println("Autoscale updated with success")
}
func validateFlags(min, max int32) (string, bool) {
if max == flagNotDefined || min == flagNotDefined {
return "--min and --max are required", false
}
if max < 1 {
return fmt.Sprintf("--max=MAXPODS must be at least 1, max: %d", max), false
}
if max < min {
return fmt.Sprintf("--max=MAXPODS must be larger or equal to --min=MINPODS, max: %d, min: %d", max, min), false
}
if min < 1 {
return fmt.Sprintf("--min=MINPODS must be at least 1, min: %d", min), false
}
return "", true
}
var appStartCmd = &cobra.Command{
Use: "start <name> [flags]",
Short: "Set replicas count for the app",
Long: `Set application's replicas count.
Example: To set the number of replicas to 2:
$ teresa app start myapp --replicas 2`,
Run: appStart,
}
func appStart(cmd *cobra.Command, args []string) {
if len(args) != 1 {
cmd.Usage()
return
}
name := args[0]
replicas, err := cmd.Flags().GetInt32("replicas")
if err != nil || replicas < 1 {
client.PrintErrorAndExit("invalid replicas parameter")
}
conn, err := connection.New(cfgFile, cfgCluster)
if err != nil {
client.PrintErrorAndExit("Error connecting to server: %s", err)
}
defer conn.Close()
req := &appb.SetReplicasRequest{
Name: name,
Replicas: replicas,
}
cli := appb.NewAppClient(conn)
if _, err := cli.SetReplicas(context.Background(), req); err != nil {
client.PrintErrorAndExit(client.GetErrorMsg(err))
}
fmt.Println("App started with success")
}
var appStopCmd = &cobra.Command{
Use: "stop <name> [flags]",
Short: "Set replicas count for the app to 0",
Long: `Set application's replicas count to 0.
Example:
$ teresa app stop myapp`,
Run: appStop,
}
func appStop(cmd *cobra.Command, args []string) {
if len(args) != 1 {
cmd.Usage()
return
}
name := args[0]
conn, err := connection.New(cfgFile, cfgCluster)
if err != nil {
client.PrintErrorAndExit("Error connecting to server: %s", err)
}
defer conn.Close()
req := &appb.SetReplicasRequest{
Name: name,
Replicas: 0,
}
cli := appb.NewAppClient(conn)
if _, err := cli.SetReplicas(context.Background(), req); err != nil {
client.PrintErrorAndExit(client.GetErrorMsg(err))
}
fmt.Println("App stopped with success")
}
func init() {
// add AppCmd
RootCmd.AddCommand(appCmd)
// App commands
appCmd.AddCommand(appCreateCmd)
appCmd.AddCommand(appListCmd)
appCmd.AddCommand(appDelCmd)
appCmd.AddCommand(appInfoCmd)
appCmd.AddCommand(appEnvSetCmd)
appCmd.AddCommand(appEnvUnSetCmd)
appCmd.AddCommand(appSecretSetCmd)
appCmd.AddCommand(appSecretUnSetCmd)
appCmd.AddCommand(appLogsCmd)
appCmd.AddCommand(appAutoscaleSetCmd)
appCmd.AddCommand(appStartCmd)
appCmd.AddCommand(appStopCmd)
appCmd.AddCommand(appDeletePodsCmd)
appCmd.AddCommand(appChangeTeamCmd)
appCreateCmd.Flags().String("team", "", "team owner of the app")
appCreateCmd.Flags().Int32("scale-min", 1, "minimum number of replicas")
appCreateCmd.Flags().Int32("scale-max", 2, "maximum number of replicas")
appCreateCmd.Flags().Int32("scale-cpu", 70, "auto scale target cpu percentage to scale")
appCreateCmd.Flags().String("cpu", "200m", "allocated pod cpu")
appCreateCmd.Flags().String("memory", "512Mi", "allocated pod memory")
appCreateCmd.Flags().String("max-cpu", "400m", "when set, allows the pod to burst cpu usage up to 'max-cpu'")
appCreateCmd.Flags().String("max-memory", "512Mi", "when set, allows the pod to burst memory usage up to 'max-memory'")
appCreateCmd.Flags().String("process-type", "", "app process type")
appCreateCmd.Flags().String("vhost", "", "virtual host of the app")
appCreateCmd.Flags().Bool("internal", false, "create an internal app (without external endpoint)")
appCreateCmd.Flags().String("protocol", "", "app protocol: http, http2, grpc, etc.")
appEnvSetCmd.Flags().String("app", "", "app name")
appEnvSetCmd.Flags().Bool("no-input", false, "set env vars without warning")
appEnvUnSetCmd.Flags().String("app", "", "app name")
appEnvUnSetCmd.Flags().Bool("no-input", false, "unset env vars without warning")
appSecretSetCmd.Flags().String("app", "", "app name")
appSecretSetCmd.Flags().Bool("no-input", false, "set env vars without warning")
appSecretUnSetCmd.Flags().String("app", "", "app name")
appSecretUnSetCmd.Flags().Bool("no-input", false, "unset env vars without warning")
// App logs
appLogsCmd.Flags().Int64P("lines", "n", 10, "number of lines")
appLogsCmd.Flags().BoolP("follow", "f", false, "follow logs")
appLogsCmd.Flags().String("pod", "", "filter logs by pod name")
appLogsCmd.Flags().BoolP("previous", "p", false, "print the logs for the previous instance")
appLogsCmd.Flags().String("container", "", "filter logs by container name")
// App autoscale
appAutoscaleSetCmd.Flags().Int32("min", flagNotDefined, "Minimum number of replicas")
appAutoscaleSetCmd.Flags().Int32("max", flagNotDefined, "Maximum number of replicas")
appAutoscaleSetCmd.Flags().Int32("cpu-percent", flagNotDefined, "The target average CPU utilization (represented as a percent of requested CPU) over all the pods. If it's not specified or negative, the current autoscaling policy will be used.")
// App Start
appStartCmd.Flags().Int32("replicas", 1, "Number of replicas")
// App delete-pods
appDeletePodsCmd.Flags().String("app", "", "app name")
}
func appLogs(cmd *cobra.Command, args []string) {
if len(args) != 1 {
cmd.Usage()
return
}
appName := args[0]
lines, err := cmd.Flags().GetInt64("lines")
if err != nil {
client.PrintErrorAndExit("Invalid lines parameter")
}
follow, err := cmd.Flags().GetBool("follow")
if err != nil {
client.PrintErrorAndExit("Invalid follow parameter")
}
pod, err := cmd.Flags().GetString("pod")
if err != nil {
client.PrintErrorAndExit("Invalid pod parameter")
}
previous, err := cmd.Flags().GetBool("previous")
if err != nil {
client.PrintErrorAndExit("Invalid previous parameter")
}
container, err := cmd.Flags().GetString("container")
if err != nil {
client.PrintErrorAndExit("Invalid container parameter")
}
conn, err := connection.New(cfgFile, cfgCluster)
if err != nil {
client.PrintErrorAndExit("Error connecting to server: %v", err)
}
defer conn.Close()
cli := appb.NewAppClient(conn)
req := &appb.LogsRequest{
Name: appName,
Lines: lines,
Follow: follow,
PodName: pod,
Previous: previous,
Container: container,
}
stream, err := cli.Logs(context.Background(), req)
if err != nil {
client.PrintErrorAndExit(client.GetErrorMsg(err))
}
for {
msg, err := stream.Recv()
if err != nil {
if err == io.EOF {
return
}
client.PrintErrorAndExit(client.GetErrorMsg(err))
}
fmt.Println(msg.Text)
}
}
var appDeletePodsCmd = &cobra.Command{
Use: "delete-pods [pods, ...]",
Short: "Delete app's pods by name",
Long: "Delete app's pods by name",
Example: ` To delete pods myapp-1234 and myapp-5678 from app myapp:
$ teresa app delete-pods myapp-1234 myapp-5678 --app myapp`,
Run: appDeletePods,
}
func appDeletePods(cmd *cobra.Command, args []string) {
if len(args) == 0 {
cmd.Usage()
return
}
appName, err := cmd.Flags().GetString("app")
if err != nil || appName == "" {
client.PrintErrorAndExit("Invalid app parameter")
}
conn, err := connection.New(cfgFile, cfgCluster)
if err != nil {
client.PrintErrorAndExit("Error connecting to server: %v", err)
}
defer conn.Close()
cli := appb.NewAppClient(conn)
if err != nil {
client.PrintErrorAndExit(client.GetErrorMsg(err))
}
req := &appb.DeletePodsRequest{Name: appName, PodsNames: args}
_, err = cli.DeletePods(context.Background(), req)
if err != nil {
client.PrintErrorAndExit(client.GetErrorMsg(err))
return
}
fmt.Println("Pods will be deleted in a few seconds")
}
var appChangeTeamCmd = &cobra.Command{
Use: "change-team <app-name> <team-name>",
Short: "Change app team",
Long: "Change app team",
Example: ` To change myapp team to myteam:
$ teresa app change-team myapp myteam`,
Run: appChangeTeam,
}
func appChangeTeam(cmd *cobra.Command, args []string) {
if len(args) != 2 {
cmd.Usage()
return
}
appName := args[0]
teamName := args[1]