-
-
Notifications
You must be signed in to change notification settings - Fork 466
/
root.go
446 lines (380 loc) · 12.4 KB
/
root.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
/*
Copyright © 2020-2022 The k3d Author(s)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package cmd
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"regexp"
"sort"
"strings"
"github.com/spf13/cobra"
"gopkg.in/yaml.v2"
"github.com/rancher/k3d/v5/cmd/cluster"
cfg "github.com/rancher/k3d/v5/cmd/config"
"github.com/rancher/k3d/v5/cmd/debug"
"github.com/rancher/k3d/v5/cmd/image"
"github.com/rancher/k3d/v5/cmd/kubeconfig"
"github.com/rancher/k3d/v5/cmd/node"
"github.com/rancher/k3d/v5/cmd/registry"
cliutil "github.com/rancher/k3d/v5/cmd/util"
l "github.com/rancher/k3d/v5/pkg/logger"
"github.com/rancher/k3d/v5/pkg/runtimes"
"github.com/rancher/k3d/v5/version"
"github.com/sirupsen/logrus"
"github.com/sirupsen/logrus/hooks/writer"
)
// RootFlags describes a struct that holds flags that can be set on root level of the command
type RootFlags struct {
debugLogging bool
traceLogging bool
timestampedLogging bool
version bool
}
var flags = RootFlags{}
func NewCmdK3d() *cobra.Command {
// rootCmd represents the base command when called without any subcommands
rootCmd := &cobra.Command{
Use: "k3d",
Short: "https://k3d.io/ -> Run k3s in Docker!",
Long: `https://k3d.io/
k3d is a wrapper CLI that helps you to easily create k3s clusters inside docker.
Nodes of a k3d cluster are docker containers running a k3s image.
All Nodes of a k3d cluster are part of the same docker network.`,
Run: func(cmd *cobra.Command, args []string) {
if flags.version {
printVersion()
} else {
if err := cmd.Usage(); err != nil {
l.Log().Fatalln(err)
}
}
},
}
rootCmd.PersistentFlags().BoolVar(&flags.debugLogging, "verbose", false, "Enable verbose output (debug logging)")
rootCmd.PersistentFlags().BoolVar(&flags.traceLogging, "trace", false, "Enable super verbose output (trace logging)")
rootCmd.PersistentFlags().BoolVar(&flags.timestampedLogging, "timestamps", false, "Enable Log timestamps")
// add local flags
rootCmd.Flags().BoolVar(&flags.version, "version", false, "Show k3d and default k3s version")
// add subcommands
rootCmd.AddCommand(
NewCmdVersion(),
NewCmdCompletion(rootCmd),
cluster.NewCmdCluster(),
kubeconfig.NewCmdKubeconfig(),
node.NewCmdNode(),
image.NewCmdImage(),
cfg.NewCmdConfig(),
registry.NewCmdRegistry(),
debug.NewCmdDebug(),
&cobra.Command{
Use: "runtime-info",
Short: "Show runtime information",
Long: "Show some information about the runtime environment (e.g. docker info)",
Run: func(cmd *cobra.Command, args []string) {
info, err := runtimes.SelectedRuntime.Info()
if err != nil {
l.Log().Fatalln(err)
}
err = yaml.NewEncoder(os.Stdout).Encode(info)
if err != nil {
l.Log().Fatalln(err)
}
},
Hidden: true,
},
)
// Init
cobra.OnInitialize(initLogging, initRuntime)
return rootCmd
}
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
cmd := NewCmdK3d()
if len(os.Args) > 1 {
parts := os.Args[1:]
// Check if it's a built-in command, else try to execute it as a plugin
if _, _, err := cmd.Find(parts); err != nil {
pluginFound, err := cliutil.HandlePlugin(context.Background(), parts)
if err != nil {
l.Log().Errorf("Failed to execute plugin '%+v'", parts)
l.Log().Fatalln(err)
} else if pluginFound {
os.Exit(0)
}
}
}
if err := cmd.Execute(); err != nil {
l.Log().Fatalln(err)
}
}
// initLogging initializes the logger
func initLogging() {
if flags.traceLogging {
l.Log().SetLevel(logrus.TraceLevel)
} else if flags.debugLogging {
l.Log().SetLevel(logrus.DebugLevel)
} else {
switch logLevel := strings.ToUpper(os.Getenv("LOG_LEVEL")); logLevel {
case "TRACE":
l.Log().SetLevel(logrus.TraceLevel)
case "DEBUG":
l.Log().SetLevel(logrus.DebugLevel)
case "WARN":
l.Log().SetLevel(logrus.WarnLevel)
case "ERROR":
l.Log().SetLevel(logrus.ErrorLevel)
default:
l.Log().SetLevel(logrus.InfoLevel)
}
}
l.Log().SetOutput(io.Discard)
l.Log().AddHook(&writer.Hook{
Writer: os.Stderr,
LogLevels: []logrus.Level{
logrus.PanicLevel,
logrus.FatalLevel,
logrus.ErrorLevel,
logrus.WarnLevel,
},
})
l.Log().AddHook(&writer.Hook{
Writer: os.Stdout,
LogLevels: []logrus.Level{
logrus.InfoLevel,
logrus.DebugLevel,
logrus.TraceLevel,
},
})
formatter := &logrus.TextFormatter{
ForceColors: true,
}
if flags.timestampedLogging || os.Getenv("LOG_TIMESTAMPS") != "" {
formatter.FullTimestamp = true
}
l.Log().SetFormatter(formatter)
}
func initRuntime() {
runtime, err := runtimes.GetRuntime("docker")
if err != nil {
l.Log().Fatalln(err)
}
runtimes.SelectedRuntime = runtime
if rtinfo, err := runtime.Info(); err == nil {
l.Log().Debugf("Runtime Info:\n%+v", rtinfo)
}
}
func NewCmdVersion() *cobra.Command {
cmd := &cobra.Command{
Use: "version",
Short: "Show k3d and default k3s version",
Long: "Show k3d and default k3s version",
Run: func(cmd *cobra.Command, args []string) {
printVersion()
},
Args: cobra.NoArgs,
}
cmd.AddCommand(NewCmdVersionLs())
return cmd
}
func printVersion() {
fmt.Printf("k3d version %s\n", version.GetVersion())
fmt.Printf("k3s version %s (default)\n", version.K3sVersion)
}
func NewCmdVersionLs() *cobra.Command {
type VersionLsOutputFormat string
type VersionLsSortMode string
const (
VersionLsOutputFormatRaw VersionLsOutputFormat = "raw"
VersionLsOutputFormatRepo VersionLsOutputFormat = "repo"
VersionLsSortDesc VersionLsSortMode = "desc"
VersionLsSortAsc VersionLsSortMode = "asc"
VersionLsSortOff VersionLsSortMode = "off"
)
var VersionLsOutputFormats = map[string]VersionLsOutputFormat{
string(VersionLsOutputFormatRaw): VersionLsOutputFormatRaw,
string(VersionLsOutputFormatRepo): VersionLsOutputFormatRepo,
}
var VersionLsSortModes = map[string]VersionLsSortMode{
string(VersionLsSortDesc): VersionLsSortDesc,
string(VersionLsSortAsc): VersionLsSortAsc,
string(VersionLsSortOff): VersionLsSortOff,
}
type Flags struct {
includeRegexp string
excludeRegexp string
format string
sortMode string
limit int
}
flags := Flags{}
cmd := &cobra.Command{
Use: "list",
Aliases: []string{"ls"},
Short: "List k3d/K3s versions",
ValidArgs: []string{"k3d", "k3s", "k3d-proxy", "k3d-tools"},
Args: cobra.ExactValidArgs(1),
Run: func(cmd *cobra.Command, args []string) {
var format VersionLsOutputFormat
if f, ok := VersionLsOutputFormats[flags.format]; !ok {
l.Log().Fatalf("Unknown output format '%s'", flags.format)
} else {
format = f
}
var sortMode VersionLsSortMode
if m, ok := VersionLsSortModes[flags.sortMode]; !ok {
l.Log().Fatalf("Unknown sort mode '%s'", flags.sortMode)
} else {
sortMode = m
}
urlTpl := "https://registry.hub.docker.com/v1/repositories/%s/tags"
org := "rancher"
repo := fmt.Sprintf("%s/%s", org, args[0])
resp, err := http.Get(fmt.Sprintf(urlTpl, repo))
if err != nil {
l.Log().Fatalln(err)
}
defer resp.Body.Close()
type Layers struct {
Layer string
Name string
}
body, err := io.ReadAll(resp.Body)
if err != nil {
l.Log().Fatalln(err)
}
respJSON := &[]Layers{}
if err := json.Unmarshal(body, respJSON); err != nil {
l.Log().Fatalln(err)
}
includeRegexp, err := regexp.Compile(flags.includeRegexp)
if err != nil {
l.Log().Fatalln(err)
}
excludeRegexp, err := regexp.Compile(flags.excludeRegexp)
if err != nil {
l.Log().Fatalln(err)
}
tags := []string{}
for _, tag := range *respJSON {
if includeRegexp.Match([]byte(tag.Name)) {
if flags.excludeRegexp == "" || !excludeRegexp.Match([]byte(tag.Name)) {
switch format {
case VersionLsOutputFormatRaw:
tags = append(tags, tag.Name)
case VersionLsOutputFormatRepo:
tags = append(tags, fmt.Sprintf("%s:%s\n", repo, tag.Name))
default:
l.Log().Fatalf("Unknown output format '%+v'", format)
}
} else {
l.Log().Tracef("Tag %s excluded (regexp: `%s`)", tag.Name, flags.excludeRegexp)
}
} else {
l.Log().Tracef("Tag %s not included (regexp: `%s`)", tag.Name, flags.includeRegexp)
}
}
// Sort
if sortMode != VersionLsSortOff {
sort.Slice(tags, func(i, j int) bool {
if sortMode == VersionLsSortAsc {
return tags[i] < tags[j]
}
return tags[i] > tags[j]
})
}
if flags.limit > 0 {
tags = tags[0:flags.limit]
}
fmt.Println(strings.Join(tags, "\n"))
},
}
cmd.Flags().StringVarP(&flags.includeRegexp, "include", "i", ".*", "Include Regexp (default includes everything")
cmd.Flags().StringVarP(&flags.excludeRegexp, "exclude", "e", ".+(rc|engine|alpha|beta|dev|test|arm|arm64|amd64).*", "Exclude Regexp (default excludes pre-releases and arch-specific tags)")
cmd.Flags().StringVarP(&flags.format, "format", "f", string(VersionLsOutputFormatRaw), "Output Format")
cmd.Flags().StringVarP(&flags.sortMode, "sort", "s", string(VersionLsSortDesc), "Sort Mode (asc | desc | off)")
cmd.Flags().IntVarP(&flags.limit, "limit", "l", 0, "Limit number of tags in output (0 = unlimited)")
return cmd
}
// NewCmdCompletion creates a new completion command
func NewCmdCompletion(rootCmd *cobra.Command) *cobra.Command {
completionFunctions := map[string]func(io.Writer) error{
"bash": rootCmd.GenBashCompletion,
"zsh": func(writer io.Writer) error {
if err := rootCmd.GenZshCompletion(writer); err != nil {
return err
}
fmt.Fprintf(writer, "\n# source completion file\ncompdef _k3d k3d\n")
return nil
},
"psh": rootCmd.GenPowerShellCompletion,
"powershell": rootCmd.GenPowerShellCompletionWithDesc,
"fish": func(writer io.Writer) error {
return rootCmd.GenFishCompletion(writer, true)
},
}
// create new cobra command
cmd := &cobra.Command{
Use: "completion SHELL",
Short: "Generate completion scripts for [bash, zsh, fish, powershell | psh]",
Long: `To load completions:
Bash:
$ source <(k3d completion bash)
# To load completions for each session, execute once:
# Linux:
$ k3d completion bash > /etc/bash_completion.d/k3d
# macOS:
$ k3d completion bash > /usr/local/etc/bash_completion.d/k3d
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:
$ k3d completion zsh > "${fpath[1]}/k3d"
# You will need to start a new shell for this setup to take effect.
fish:
$ k3d completion fish | source
# To load completions for each session, execute once:
$ k3d completion fish > ~/.config/fish/completions/k3d.fish
PowerShell:
PS> k3d completion powershell | Out-String | Invoke-Expression
# To load completions for every new session, run:
PS> k3d completion powershell > k3d.ps1
# and source this file from your PowerShell profile.
`,
ValidArgs: []string{"bash", "zsh", "fish", "powershell"},
ArgAliases: []string{"psh"},
DisableFlagsInUseLine: true,
Args: cobra.ExactValidArgs(1),
Run: func(cmd *cobra.Command, args []string) {
if completionFunc, ok := completionFunctions[args[0]]; ok {
if err := completionFunc(os.Stdout); err != nil {
l.Log().Fatalf("Failed to generate completion script for shell '%s'", args[0])
}
return
}
l.Log().Fatalf("Shell '%s' not supported for completion", args[0])
},
}
return cmd
}