-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
599 lines (530 loc) · 16.9 KB
/
main.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
package main
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"sync"
"time"
"github.com/containerd/console"
"github.com/gorilla/websocket"
"github.com/jmespath/go-jmespath"
"github.com/spf13/cobra"
"github.com/spf13/viper"
trie "github.com/v-pap/trie"
"gitlab.ops.mist.io/mistio/openapi-cli-generator/apikey"
"gitlab.ops.mist.io/mistio/openapi-cli-generator/cli"
terminal "golang.org/x/term"
)
var logger = log.New(os.Stdout, "", 0)
// completionCmd represents the completion command
var completionCmd = &cobra.Command{
Use: "completion [bash|zsh|fish|powershell]",
Short: "Generate completion script",
Long: `To load completions:
Bash:
$ source <(mist completion bash)
# To load completions for each session, execute once:
Linux:
$ mist completion bash > /etc/bash_completion.d/mist
MacOS:
$ mist completion bash > /usr/local/etc/bash_completion.d/mist
Zsh:
# If shell completion is not already enabled in your environment you will need
# to enable it. You can execute the following once:
$ echo "autoload -U compinit; compinit" >> ~/.zshrc
# To load completions for each session, execute once:
$ mist completion zsh > "${fpath[1]}/_mist"
# You will need to start a new shell for this setup to take effect.
Fish:
$ mist completion fish | source
# To load completions for each session, execute once:
$ mist completion fish > ~/.config/fish/completions/mist.fish
`,
DisableFlagsInUseLine: true,
ValidArgs: []string{"bash", "zsh", "fish", "powershell"},
Args: cobra.ExactValidArgs(1),
Run: func(cmd *cobra.Command, args []string) {
switch args[0] {
case "bash":
cmd.Root().GenBashCompletion(os.Stdout)
case "zsh":
cmd.Root().GenZshCompletion(os.Stdout)
case "fish":
cmd.Root().GenFishCompletion(os.Stdout, true)
case "powershell":
cmd.Root().GenPowerShellCompletion(os.Stdout)
}
},
}
var customUsageTpl = `Usage:{{if .Runnable}}
{{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}
{{.CommandPath}} [command]{{end}}{{if .HasExample}}
Examples:
{{.Example}}{{end}}{{if .HasAvailableSubCommands}}
Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}
Flags:
{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}
Global Flags:
{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}
Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}
{{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}
`
var customUsageSubCommandTpl = `Usage:{{if .Runnable}}
{{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}
{{.CommandPath}} [command]{{end}}{{if .HasExample}}
Examples:
{{.Example}}{{end}}
API Docs:
$API_DOCS{{if .HasAvailableSubCommands}}
Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}
Flags:
{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}
Global Flags:
{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}
Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}
{{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}
`
func customUsageFunc(c *cobra.Command) error {
err := setContext()
if err != nil {
return err
}
server, err := getServer()
if err != nil {
return err
}
apiDocs := server + c.UsageTemplate()
c.SetUsageTemplate(strings.ReplaceAll(customUsageSubCommandTpl, "$API_DOCS", apiDocs))
c.SetUsageFunc(nil)
c.Usage()
return nil
}
func versionCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "version",
Short: "Get CLI & API version",
Args: cobra.ExactValidArgs(0),
Run: func(cmd *cobra.Command, args []string) {
type version struct {
Sha string `json:"sha"`
Name string `json:"name"`
Repo string `json:"repo"`
Modified bool `json:"modified"`
}
type versionResp struct {
Version version `json:"version"`
}
err := setContext()
if err != nil {
fmt.Println(err)
return
}
server, err := getServer()
if err != nil {
fmt.Println(err)
return
}
url := server + "/version"
req := cli.Client.Get().URL(url)
resp, err := req.Do()
if err != nil {
fmt.Println(err)
return
}
var ver versionResp
err = resp.JSON(&ver)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("CLI version: $CLI_VERSION")
fmt.Printf("Server version: %s - %s#%s", ver.Version.Name, ver.Version.Repo, ver.Version.Sha)
if ver.Version.Modified {
fmt.Printf(" modified")
}
fmt.Println("")
},
}
return cmd
}
func sshCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "ssh",
Short: "Open a shell to a machine",
Args: cobra.ExactValidArgs(1),
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) == 0 {
params := viper.New()
params.Set("only", "name")
params.Set("search", "key_associations:true AND state:running")
var decoded interface{}
_, decoded, _, err := MistApiV2ListMachines(params)
if err != nil {
logger.Fatalf("Error calling operation: %s", err.Error())
}
data, _ := jmespath.Search("data[].name", decoded)
j, _ := json.Marshal(data)
str := strings.Replace(strings.Replace(strings.Replace(string(j[:]), "[", "", -1), "]", "", -1), " ", "\\ ", -1)
return strings.Split(str, ","), cobra.ShellCompDirectiveNoFileComp
}
return nil, cobra.ShellCompDirectiveNoFileComp
},
Run: func(cmd *cobra.Command, args []string) {
machine := args[0]
// Time allowed to write a message to the peer.
writeWait := 2 * time.Second
// Time allowed to read the next pong message from the peer.
pongWait := 10 * time.Second
// Send pings to peer with this period. Must be less than pongWait.
pingPeriod := (pongWait * 9) / 10
err := setContext()
if err != nil {
logger.Fatalf("Could not set context %s", err)
}
server, err := getServer()
if err != nil {
logger.Fatal(err)
}
if !strings.HasSuffix(server, "/") {
server = server + "/"
}
if !strings.HasPrefix(server, "http") {
server = "http://" + server
}
path := server + "api/v2/machines/" + machine + "/actions/ssh"
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}}
req, err := http.NewRequest("POST", path, nil)
if err != nil {
logger.Fatal(err)
}
token, err := getToken()
if err != nil {
logger.Fatal(err)
}
req.Header.Add("Authorization", token)
if err != nil {
logger.Fatal(err)
}
resp, err := client.Do(req)
if err != nil {
logger.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode/100 != 3 {
logger.Fatalf("Could not SSH into machine: %s", resp.Status)
}
_, err = ioutil.ReadAll(resp.Body)
if err != nil {
logger.Fatal(err)
}
location := resp.Header.Get("location")
c, resp, err := websocket.DefaultDialer.Dial(location, http.Header{"Authorization": []string{token}})
if err != nil {
logger.Fatal(err)
}
// Handle the case of redirections
if resp != nil && resp.StatusCode == 302 {
u, _ := resp.Location()
c, resp, err = websocket.DefaultDialer.Dial(u.String(), http.Header{"Authorization": []string{token}})
if err != nil || resp.StatusCode/100 != 2 {
logger.Fatal(err)
}
}
defer c.Close()
current := console.Current()
if err := current.SetRaw(); err != nil {
logger.Fatal(err)
}
terminal.NewTerminal(current, "")
defer current.Reset()
done := make(chan bool)
var writeMutex sync.Mutex
err = updateTerminalSize(c, &writeMutex, writeWait)
if err != nil {
logger.Fatal(err)
}
go handleTerminalResize(c, &done, &writeMutex, writeWait)
go readFromRemoteStdout(c, &done, pongWait)
go writeToRemoteStdin(c, &done, &writeMutex, writeWait)
go sendPingMessages(c, &done, writeWait, pingPeriod)
<-done
},
}
cmd.SetErr(os.Stderr)
return cmd
}
func streamingCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "stream JOB_ID",
Short: "Stream logs of a running script",
Args: cobra.ExactValidArgs(1),
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return nil, cobra.ShellCompDirectiveNoFileComp
},
Run: func(cmd *cobra.Command, args []string) {
job_id := args[0]
// Time allowed to write a message to the peer.
writeWait := 10 * 3600 * time.Second
// Time allowed to read the next pong message from the peer.
pongWait := 20 * time.Second
// Send pings to peer with this period. Must be less than pongWait.
pingPeriod := (10 * time.Second * 9) / 10
server, err := getServer()
if err != nil {
logger.Println(err)
return
}
if !strings.HasSuffix(server, "/") {
server = server + "/"
}
if !strings.HasPrefix(server, "http") {
server = "http://" + server
}
path := server + "api/v2/jobs/" + job_id
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}}
req, err := http.NewRequest("GET", path, nil)
if err != nil {
logger.Println(err)
return
}
token, err := getToken()
if err != nil {
logger.Println(err)
return
}
req.Header.Add("Authorization", token)
if err != nil {
logger.Println(err)
return
}
resp, err := client.Do(req)
if err != nil {
logger.Println(err)
return
}
var r any
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(&r)
if err != nil {
logger.Println(err)
return
}
data, data_exists := r.(map[string]any)["data"]
var location string
if data_exists {
_, ok := data.(map[string]any)["stream_uri"].(string)
if !ok {
logger.Fatal(errors.New("stream_uri not found in api response for given JOB_ID"))
return
}
location = data.(map[string]any)["stream_uri"].(string)
} else {
logger.Fatal(errors.New("api response for given JOB_ID does not contain any data"))
}
defer resp.Body.Close()
c, resp, err := websocket.DefaultDialer.Dial(location, http.Header{"Authorization": []string{token}})
if err != nil {
logger.Println(err)
return
}
if resp != nil && resp.StatusCode == 302 {
u, _ := resp.Location()
c, resp, err = websocket.DefaultDialer.Dial(u.String(), http.Header{"Authorization": []string{token}})
}
defer c.Close()
if err != nil {
logger.Println(err)
return
}
current := console.Current()
if err := current.SetRaw(); err != nil {
panic(err)
}
terminal.NewTerminal(current, "")
defer current.Reset()
done := make(chan bool)
var writeMutex sync.Mutex
err = updateTerminalSize(c, &writeMutex, writeWait)
if err != nil {
logger.Println(err)
return
}
go func() {
cmd.InOrStdin()
_, _, err := bufio.NewReader(cmd.InOrStdin()).ReadRune()
if err != nil {
logger.Println(err)
return
}
done <- true
os.Exit(0)
}()
go readFromRemoteStdout(c, &done, pongWait)
go sendPingMessages(c, &done, writeWait, pingPeriod)
<-done
},
}
cmd.SetErr(os.Stderr)
return cmd
}
func getResourceMeterCmdRun(params *viper.Viper, resource string, detailedName bool) {
dtStart := params.GetString("start")
if dtStart == "" {
dtStart = fmt.Sprintf("%d", (time.Now()).Unix()-60*60)
}
dtEnd := params.GetString("end")
if dtEnd == "" {
dtEnd = fmt.Sprintf("%d", (time.Now()).Unix())
}
_, resourceMetricsStart, _ := getMeteringData(dtStart, dtEnd, params.GetString("search"), fmt.Sprintf("first_over_time({metering=\"true\",%s_id=~\".+\"}", resource)+"[%ds])")
metricsSet, resourceMetricsEnd, resourceNames := getMeteringData(dtStart, dtEnd, params.GetString("search"), fmt.Sprintf("last_over_time({metering=\"true\",%s_id=~\".+\"}", resource)+"[%ds])")
if detailedName {
for resourceID, name := range resourceNames {
resourceNames[resourceID] = resource + "/" + name
}
}
machineMetricsGauges := calculateDiffs(resourceMetricsStart, resourceMetricsEnd, metricsSet)
formatMeteringData(metricsSet, machineMetricsGauges, resourceNames)
}
func getResourceMeterCmd(resource string, aliasesMap map[string][]string, detailedName bool) *cobra.Command {
params := viper.New()
cmd := &cobra.Command{
Use: resource,
Aliases: aliasesMap[resource],
Short: fmt.Sprintf("Get metering data for %s resource", resource),
Args: cobra.ExactValidArgs(0),
Run: func(cmd *cobra.Command, args []string) {
getResourceMeterCmdRun(params, resource, false)
},
}
cmd.Flags().String("start", "", "start <rfc3339 | unix_timestamp>")
cmd.Flags().String("end", "", "end <rfc3339 | unix_timestamp>")
cmd.Flags().String("search", "", "Only return results matching search filter")
cli.SetCustomFlags(cmd)
if cmd.Flags().HasFlags() {
params.BindPFlags(cmd.Flags())
}
return cmd
}
func getAllResourcesMeterCmd(resources []string, aliasesMap map[string][]string) *cobra.Command {
params := viper.New()
cmd := &cobra.Command{
Use: "all",
Aliases: aliasesMap["all"],
Short: "Get metering data for all resources",
Args: cobra.ExactValidArgs(0),
Run: func(cmd *cobra.Command, args []string) {
for i, resource := range resources {
getResourceMeterCmdRun(params, resource, true)
if i != len(resources)-1 {
fmt.Println("")
}
}
},
}
cmd.Flags().String("start", "", "start <rfc3339 | unix_timestamp>")
cmd.Flags().String("end", "", "end <rfc3339 | unix_timestamp>")
cmd.Flags().String("search", "", "Only return results matching search filter")
cli.SetCustomFlags(cmd)
if cmd.Flags().HasFlags() {
params.BindPFlags(cmd.Flags())
}
return cmd
}
func calculateAliases(command, suffix string) []string {
if len(command) == 0 {
return []string{}
}
prefix := strings.TrimSuffix(command, suffix)
subString := ""
aliases := []string{}
for i := len(prefix); i < len(command)-1; i++ {
subString += string(command[i])
aliases = append(aliases, prefix+subString)
}
if len(aliases) > 0 && string(command[len(command)-1]) != "s" {
aliases = append(aliases, command+"s")
}
return aliases
}
func meterCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "meter",
Short: "Get metering data",
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return nil, cobra.ShellCompDirectiveNoFileComp
},
}
resources := []string{"machine", "volume"}
resourcesTrie := trie.New()
aliasesMap := make(map[string][]string)
for _, resource := range append(resources, []string{"all"}...) {
resourcesTrie.Insert(resource)
}
for _, resource := range append(resources, []string{"all"}...) {
suffix, ok := resourcesTrie.FindLongestUniqueSuffix(resource)
if !ok {
continue
}
aliasesMap[resource] = calculateAliases(resource, suffix)
}
for _, resource := range resources {
cmd.AddCommand(getResourceMeterCmd(resource, aliasesMap, false))
}
cmd.AddCommand(getAllResourcesMeterCmd(resources, aliasesMap))
cmd.SetErr(os.Stderr)
return cmd
}
func main() {
cli.Init(&cli.Config{
AppName: "mist",
EnvPrefix: "MIST",
Version: "",
})
log.SetFlags(log.LstdFlags | log.Lshortfile)
// Initialize the API key authentication.
apikey.Init("Authorization", apikey.LocationHeader)
// Add command groups
/*cli.Root.AddGroup(&cobra.Group{Group: "clouds", Title: " # CLOUDS"})
cli.Root.AddGroup(&cobra.Group{Group: "machines", Title: " # MACHINES"})
cli.Root.AddGroup(&cobra.Group{Group: "volumes", Title: " # VOLUMES"})
cli.Root.AddGroup(&cobra.Group{Group: "networks", Title: " # NETWORKS"})
cli.Root.AddGroup(&cobra.Group{Group: "zones", Title: " # ZONES"})
cli.Root.AddGroup(&cobra.Group{Group: "keys", Title: " # KEYS"})
cli.Root.AddGroup(&cobra.Group{Group: "images", Title: " # IMAGES"})
cli.Root.AddGroup(&cobra.Group{Group: "scripts", Title: " # SCRIPTS"})
cli.Root.AddGroup(&cobra.Group{Group: "templates", Title: " # TEMPLATES"})
cli.Root.AddGroup(&cobra.Group{Group: "rules", Title: " # RULES"})
cli.Root.AddGroup(&cobra.Group{Group: "teams", Title: " # TEAMS"})*/
// Add completion command
cli.Root.AddCommand(completionCmd)
// Register auto-generated commands
mistApiV2Register(false)
// Add version command
cli.Root.AddCommand(versionCmd())
// Add ssh command
cli.Root.AddCommand(sshCmd())
cli.Root.AddCommand(streamingCmd())
// Add metering command
cli.Root.AddCommand(meterCmd())
cli.Root.AddCommand(tagCmd())
cli.Root.AddCommand(untagCmd())
cli.Root.AddCommand(kubeconfigCmd())
cli.Root.Execute()
}