-
-
Notifications
You must be signed in to change notification settings - Fork 452
/
root.go
257 lines (227 loc) · 7.27 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
/*
Copyright © 2020-2021 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"
"fmt"
"io"
"io/ioutil"
"os"
"strings"
"github.com/spf13/cobra"
"gopkg.in/yaml.v2"
"github.com/rancher/k3d/v4/cmd/cluster"
cfg "github.com/rancher/k3d/v4/cmd/config"
"github.com/rancher/k3d/v4/cmd/image"
"github.com/rancher/k3d/v4/cmd/kubeconfig"
"github.com/rancher/k3d/v4/cmd/node"
"github.com/rancher/k3d/v4/cmd/registry"
cliutil "github.com/rancher/k3d/v4/cmd/util"
"github.com/rancher/k3d/v4/pkg/runtimes"
"github.com/rancher/k3d/v4/version"
log "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{}
// rootCmd represents the base command when called without any subcommands
var 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 {
log.Fatalln(err)
}
}
},
}
// 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() {
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 := rootCmd.Find(parts); err != nil {
pluginFound, err := cliutil.HandlePlugin(context.Background(), parts)
if err != nil {
log.Errorf("Failed to execute plugin '%+v'", parts)
log.Fatalln(err)
} else if pluginFound {
os.Exit(0)
}
}
}
if err := rootCmd.Execute(); err != nil {
log.Fatalln(err)
}
}
func GetRootCmd() *cobra.Command {
return rootCmd
}
func init() {
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(NewCmdCompletion())
rootCmd.AddCommand(cluster.NewCmdCluster())
rootCmd.AddCommand(kubeconfig.NewCmdKubeconfig())
rootCmd.AddCommand(node.NewCmdNode())
rootCmd.AddCommand(image.NewCmdImage())
rootCmd.AddCommand(cfg.NewCmdConfig())
rootCmd.AddCommand(registry.NewCmdRegistry())
rootCmd.AddCommand(&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()
},
})
rootCmd.AddCommand(&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 {
log.Fatalln(err)
}
err = yaml.NewEncoder(os.Stdout).Encode(info)
if err != nil {
log.Fatalln(err)
}
},
Hidden: true,
})
// Init
cobra.OnInitialize(initLogging, initRuntime)
}
// initLogging initializes the logger
func initLogging() {
if flags.traceLogging {
log.SetLevel(log.TraceLevel)
} else if flags.debugLogging {
log.SetLevel(log.DebugLevel)
} else {
switch logLevel := strings.ToUpper(os.Getenv("LOG_LEVEL")); logLevel {
case "TRACE":
log.SetLevel(log.TraceLevel)
case "DEBUG":
log.SetLevel(log.DebugLevel)
case "WARN":
log.SetLevel(log.WarnLevel)
case "ERROR":
log.SetLevel(log.ErrorLevel)
default:
log.SetLevel(log.InfoLevel)
}
}
log.SetOutput(ioutil.Discard)
log.AddHook(&writer.Hook{
Writer: os.Stderr,
LogLevels: []log.Level{
log.PanicLevel,
log.FatalLevel,
log.ErrorLevel,
log.WarnLevel,
},
})
log.AddHook(&writer.Hook{
Writer: os.Stdout,
LogLevels: []log.Level{
log.InfoLevel,
log.DebugLevel,
log.TraceLevel,
},
})
formatter := &log.TextFormatter{
ForceColors: true,
}
if flags.timestampedLogging || os.Getenv("LOG_TIMESTAMPS") != "" {
formatter.FullTimestamp = true
}
log.SetFormatter(formatter)
}
func initRuntime() {
runtime, err := runtimes.GetRuntime("docker")
if err != nil {
log.Fatalln(err)
}
runtimes.SelectedRuntime = runtime
if rtinfo, err := runtime.Info(); err == nil {
log.Debugf("Runtime Info:\n%+v", rtinfo)
}
}
func printVersion() {
fmt.Printf("k3d version %s\n", version.GetVersion())
fmt.Printf("k3s version %s (default)\n", version.K3sVersion)
}
func generateFishCompletion(writer io.Writer) error {
return rootCmd.GenFishCompletion(writer, true)
}
// Completion
var 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.GenPowerShellCompletion,
"fish": generateFishCompletion,
}
// NewCmdCompletion creates a new completion command
func NewCmdCompletion() *cobra.Command {
// create new cobra command
cmd := &cobra.Command{
Use: "completion SHELL",
Short: "Generate completion scripts for [bash, zsh, fish, powershell | psh]",
Long: `Generate completion scripts for [bash, zsh, fish, powershell | psh]`,
Args: cobra.ExactArgs(1), // TODO: NewCmdCompletion: add support for 0 args = auto detection
Run: func(cmd *cobra.Command, args []string) {
if completionFunc, ok := completionFunctions[args[0]]; ok {
if err := completionFunc(os.Stdout); err != nil {
log.Fatalf("Failed to generate completion script for shell '%s'", args[0])
}
return
}
log.Fatalf("Shell '%s' not supported for completion", args[0])
},
}
return cmd
}