/
app.go
468 lines (405 loc) · 10.6 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
// Package cli provides easy-to-use commands to manage, monitor, and utilize AIS clusters.
/*
* Copyright (c) 2018-2024, NVIDIA CORPORATION. All rights reserved.
*/
package cli
import (
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"time"
"github.com/NVIDIA/aistore/cmd/cli/config"
"github.com/NVIDIA/aistore/cmd/cli/teb"
"github.com/NVIDIA/aistore/cmn"
"github.com/NVIDIA/aistore/cmn/debug"
"github.com/NVIDIA/aistore/memsys"
"github.com/fatih/color"
"github.com/urfave/cli"
)
const (
cliName = "ais"
ua = "ais/cli"
metadata = "md"
)
const (
cliDescr = `If <TAB-TAB> completion doesn't work:
* download ` + cmn.GitHubHome + `/tree/main/cmd/cli/autocomplete
* run 'cmd/cli/autocomplete/install.sh'
To install CLI directly from GitHub: ` + cmn.GitHubHome + `/blob/main/scripts/install_from_binaries.sh`
// custom cli.AppHelpTemplate
// "You can render custom help text by setting this variable." (from github.com/urfave/cli)
appHelpTemplate = `NAME:
{{.Name}}{{if .Usage}} - {{.Usage}}{{end}}
USAGE:
{{if .UsageText}}{{.UsageText}}{{else}}{{.HelpName}} {{if .VisibleFlags}}[global options]{{end}}{{if .Commands}} command [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}{{end}}{{if .Version}}{{if not .HideVersion}}
VERSION:
{{.Version}}{{end}}{{end}}{{if .Description}}
TAB completions (Bash and Zsh):
{{.Description}}{{end}}{{if len .Authors}}
AUTHOR{{with $length := len .Authors}}{{if ne 1 $length}}S{{end}}{{end}}:
{{range $index, $author := .Authors}}{{if $index}}
{{end}}{{$author}}{{end}}{{end}}{{if .VisibleCommands}}
COMMANDS:{{range .VisibleCategories}}{{if .Name}}
{{.Name}}:{{range .VisibleCommands}}
{{join .Names ", "}}{{"\t"}}{{.Usage}}{{end}}{{else}}{{range .VisibleCommands}}
{{join .Names ", "}}{{"\t"}}{{.Usage}}{{end}}{{end}}{{end}}{{end}}{{if .VisibleFlags}}
GLOBAL OPTIONS:
{{range $index, $option := .VisibleFlags}}{{if $index}}
{{end}}{{$option}}{{end}}{{end}}{{if .Copyright}}
COPYRIGHT:
{{.Copyright}}{{end}}
`
)
const (
// currently _required_ - e.g., `ais://mmm` cannot be reduced to `mmm`
// in the future, we may fully support cfg.DefaultProvider but not yet
// * see also: cmd/cli/config/config.go
providerRequired = true
)
type (
acli struct {
app *cli.App
outWriter io.Writer
errWriter io.Writer
longRun *longRun
}
longRun struct {
count int
lfooter int
refreshRate time.Duration
offset int64
mapBegin, mapEnd teb.StstMap
outFile *os.File
}
)
var (
cfg *config.Config
buildTime string
k8sDetected bool
)
// color
var (
fred, fcyan, fblue, fgreen func(a ...any) string
)
// `ais help [COMMAND]`
var helpCommand = cli.Command{
Name: "help",
Usage: "show a list of commands; show help for a given command",
ArgsUsage: "[COMMAND]",
Action: helpCmdHandler,
BashComplete: func(c *cli.Context) {
for _, cmd := range c.App.Commands {
fmt.Println(cmd.Name)
}
},
}
func paginate(_ io.Writer, templ string, data interface{}) {
gmm, err := memsys.NewMMSA("cli-out-buffer", true)
if err != nil {
exitln("memsys:", err)
}
sgl := gmm.NewSGL(0)
r, w, err := os.Pipe()
if err != nil {
exitln("os.pipe:", err)
}
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
if _, err := io.Copy(sgl, r); err != nil {
exitln("write sgl:", err)
}
r.Close()
}()
cli.HelpPrinterCustom(w, templ, data, nil)
w.Close()
wg.Wait()
cmd := exec.Command("more")
cmd.Stdin = sgl
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
exitln("cmd more:", err)
}
}
func cliConfVerbose() bool { return cfg.Verbose } // more warnings, errors with backtraces and details
func helpCmdHandler(c *cli.Context) error {
args := c.Args()
if args.Present() {
return cli.ShowCommandHelp(c, args.First())
}
return cli.ShowAppHelp(c)
}
// main method
func Run(version, buildtime string, args []string) error {
a := acli{app: cli.NewApp(), outWriter: os.Stdout, errWriter: os.Stderr, longRun: &longRun{}}
buildTime = buildtime
// empty command line or 'ais help'
debug.Assert(filepath.Base(args[0]) == cliName, "expecting basename(arg0) '"+cliName+"'")
emptyCmdline := len(args) == 1 ||
strings.Contains(args[1], "help") ||
strings.Contains(args[1], "usage") ||
args[1] == "-h" ||
strings.Contains(args[1], fl1n(cli.HelpFlag.GetName()))
a.init(version, emptyCmdline)
teb.Init(os.Stdout, cfg.NoColor)
// run
if err := a.runOnce(args); err != nil {
return err
}
if !a.longRun.isSet() {
if emptyCmdline {
fmt.Println("\nALIASES:")
fmt.Println(indent1 + cfg.Aliases.Str(indent1))
}
return nil
}
if a.longRun.outFile != nil {
defer a.longRun.outFile.Close()
}
if a.longRun.isForever() {
return a.runForever(args)
}
return a.runN(args)
}
func (a *acli) runOnce(args []string) error {
err := a.app.Run(args)
if err == nil {
return nil
}
if isStartingUp(err) {
fmt.Fprintln(a.app.Writer, "(waiting for cluster to start ...)")
briefPause(1)
for range 8 { // retry
if err = a.app.Run(args); err == nil || !isStartingUp(err) {
break
}
briefPause(1)
}
}
return formatErr(err)
}
func (a *acli) runForever(args []string) error {
rate := a.longRun.refreshRate
for {
time.Sleep(rate)
printLongRunFooter(a.outWriter, a.longRun.lfooter)
if err := a.runOnce(args); err != nil {
return err
}
a.longRun.mapBegin = a.longRun.mapEnd
a.longRun.mapEnd = nil
}
}
func printLongRunFooter(w io.Writer, repeat int) {
if repeat > 0 {
fmt.Fprintln(w, fcyan(strings.Repeat("-", repeat)))
}
}
func (a *acli) runN(args []string) error {
delim := fcyan(strings.Repeat("-", 16))
fmt.Fprintln(a.outWriter, delim)
for i := 2; i <= a.longRun.count; i++ {
time.Sleep(a.longRun.refreshRate)
if err := a.runOnce(args); err != nil {
return err
}
if i < a.longRun.count {
fmt.Fprintln(a.outWriter, delim)
}
}
return nil
}
func (a *acli) init(version string, emptyCmdline bool) {
app := a.app
if cfg.NoColor {
fcyan = fmt.Sprint
fred = fmt.Sprint
fblue = fmt.Sprint
fgreen = fmt.Sprint
} else {
fcyan = color.New(color.FgHiCyan).SprintFunc()
fred = color.New(color.FgHiRed).SprintFunc()
fblue = color.New(color.FgHiBlue).SprintFunc()
fgreen = color.New(color.FgHiGreen).SprintFunc()
}
app.Name = cliName
app.Usage = "AIS CLI: command-line management utility for AIStore"
app.Version = version
app.EnableBashCompletion = true
app.HideHelp = true
app.Flags = []cli.Flag{cli.HelpFlag}
app.CommandNotFound = commandNotFoundHandler
app.OnUsageError = onUsageErrorHandler
app.Metadata = map[string]any{metadata: a.longRun}
app.Writer = a.outWriter
app.ErrWriter = a.errWriter
app.Description = cliDescr
if !cfg.NoMore {
cli.HelpPrinter = paginate
}
cli.AppHelpTemplate = appHelpTemplate
a.setupCommands(emptyCmdline)
}
func (a *acli) setupCommands(emptyCmdline bool) {
app := a.app
// Note: order of commands below is the order shown in "ais help"
appendJobSub(&jobCmd)
app.Commands = []cli.Command{
bucketCmd,
objectCmd,
clusterCmd,
configCmd,
etlCmd,
jobCmd,
authCmd,
showCmd,
helpCommand,
advancedCmd,
storageCmd,
archCmd,
logCmd,
perfCmd,
remClusterCmd,
a.getAliasCmd(),
}
if k8sDetected {
app.Commands = append(app.Commands, k8sCmd)
}
// not adding aliases - showing them as part of `ais [--help]`
if emptyCmdline {
return
}
app.Commands = append(app.Commands, a.initAliases()...)
setupCommandHelp(app.Commands)
a.enableSearch()
}
func (a *acli) enableSearch() {
initSearch(a.app)
a.app.Commands = append(a.app.Commands, searchCommands...)
}
func setupCommandHelp(commands []cli.Command) {
helpName := fl1n(cli.HelpFlag.GetName())
for i := range commands {
command := &commands[i]
// Get rid of 'h'/'help' subcommands
// and add the help flag manually
command.HideHelp = true
// (but only if there isn't one already)
if !hasHelpFlag(command.Flags, helpName) {
command.Flags = append(command.Flags, cli.HelpFlag)
}
command.OnUsageError = onUsageErrorHandler
// recursively
setupCommandHelp(command.Subcommands)
}
}
func hasHelpFlag(commandFlags []cli.Flag, helpName string) bool {
for _, flag := range commandFlags {
lst := splitCsv(flag.GetName())
for _, name := range lst {
if name == helpName {
return true
}
}
}
return false
}
//
// cli.App error callbacks
//
func commandNotFoundHandler(c *cli.Context, cmd string) {
if cmd == "version" {
fmt.Fprintf(c.App.Writer, "version %s (build %s)\n", c.App.Version, buildTime)
return
}
err := commandNotFoundError(c, cmd)
fmt.Fprint(c.App.ErrWriter, err)
os.Exit(1)
}
func onUsageErrorHandler(c *cli.Context, err error, _ bool) error {
if c == nil {
return err
}
return cannotExecuteError(c, err, "")
}
/////////////
// longRun //
/////////////
func (p *longRun) isForever() bool {
return p.count == countUnlimited
}
func (p *longRun) isSet() bool {
return p.refreshRate != 0
}
func (p *longRun) init(c *cli.Context, runOnce bool) {
if flagIsSet(c, refreshFlag) {
p.refreshRate = parseDurationFlag(c, refreshFlag)
p.count = countUnlimited // unless counted (below)
} else if runOnce {
p.count = 1 // unless --count spec-ed (below)
}
if flagIsSet(c, countFlag) {
p.count = parseIntFlag(c, countFlag)
if p.count <= 0 {
n := flprn(countFlag)
warn := fmt.Sprintf("option '%s=%d' is invalid (must be >= 1). Proceeding with '%s=%d' (default).",
n, p.count, n, countDefault)
actionWarn(c, warn)
briefPause(2)
p.count = countDefault
}
}
}
func isLongRun(c *cli.Context) bool {
params := c.App.Metadata[metadata].(*longRun)
return params.isSet()
}
func setLongRunParams(c *cli.Context, footer ...int) bool {
params := c.App.Metadata[metadata].(*longRun)
if params.isSet() {
return false
}
params.lfooter = 8
if len(footer) > 0 {
params.lfooter = footer[0]
}
params.init(c, false)
return true
}
func getLongRunParams(c *cli.Context) *longRun {
params := c.App.Metadata[metadata].(*longRun)
if !params.isSet() {
return nil
}
return params
}
func addLongRunOffset(c *cli.Context, off int64) {
params := c.App.Metadata[metadata].(*longRun)
if params.isSet() {
params.offset += off
}
}
func getLongRunOffset(c *cli.Context) int64 {
params := c.App.Metadata[metadata].(*longRun)
return params.offset
}
func setLongRunOutfile(c *cli.Context, file *os.File) {
params := c.App.Metadata[metadata].(*longRun)
if params.isSet() {
params.outFile = file
}
}
func getLongRunOutfile(c *cli.Context) *os.File {
params := c.App.Metadata[metadata].(*longRun)
return params.outFile
}
func exitln(prompt string, err error) {
fmt.Fprintln(os.Stderr, prompt, err)
os.Exit(1)
}