generated from diginfra/template-repository
-
Notifications
You must be signed in to change notification settings - Fork 0
/
root.go
235 lines (209 loc) · 7.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
// SPDX-License-Identifier: Apache-2.0
/*
Copyright (C) 2023 The Diginfra Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd
import (
"errors"
"fmt"
"io"
"os"
"sort"
"strings"
"github.com/diginfra/driverkit/pkg/driverbuilder/builder"
"github.com/diginfra/driverkit/pkg/kernelrelease"
"github.com/diginfra/driverkit/pkg/version"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
)
func persistentValidateFunc(rootCommand *RootCmd, configOpts *ConfigOptions, rootOpts *RootOptions) func(c *cobra.Command, args []string) error {
return func(c *cobra.Command, args []string) error {
var validationError = errors.New("exiting for validation errors")
configErr := configOpts.Init()
// Early exit if detect some error into config flags
if configErr {
return validationError
}
// Merge environment variables or config file values into the RootOptions instance
skip := map[string]bool{ // do not merge these
"config": true,
"timeout": true,
"loglevel": true,
"dryrun": true,
"proxy": true,
}
nested := map[string]string{ // handle nested options in config file
"output-module": "output.module",
"output-probe": "output.probe",
}
rootCommand.c.Flags().VisitAll(func(f *pflag.Flag) {
if name := f.Name; !skip[name] {
if name == "kernelurls" {
// Slice types need special treatment when used as flags. If we call 'Set(name, value)',
// rather than replace, it appends. Since viper will already have the cli options set
// if supplied, we only need this step if rootCommand doesn't already have them e.g.
// not set on CLI so read from config.
if cliURLs, err := rootCommand.c.Flags().GetStringSlice(name); err == nil && len(cliURLs) != 0 {
return
}
value := viper.GetStringSlice(name)
if len(value) != 0 {
strValue := strings.Join(value, ",")
_ = rootCommand.c.Flags().Set(name, strValue)
}
} else {
value := viper.GetString(name)
if value == "" {
// fallback to nested options in config file, if any
if nestedName, ok := nested[name]; ok {
value = viper.GetString(nestedName)
}
}
// set the value, if any, otherwise let the default
if value != "" {
_ = rootCommand.c.Flags().Set(name, value)
}
}
}
})
// Avoid sensitive info into default values help line
rootCommand.StripSensitive()
// Do not block root or help command to exec disregarding the root flags validity
if c.Root() != c && c.Name() != "help" && c.Name() != "__complete" && c.Name() != "__completeNoDesc" && c.Name() != "completion" {
if errs := rootOpts.Validate(); errs != nil {
for _, err := range errs {
configOpts.Printer.Logger.Error("error validating build options",
configOpts.Printer.Logger.Args("err", err.Error()))
}
return validationError
}
rootOpts.Log(configOpts.Printer)
}
return nil
}
}
// RootCmd wraps the main cobra.Command.
type RootCmd struct {
c *cobra.Command
}
// NewRootCmd instantiates the root command.
func NewRootCmd(configOpts *ConfigOptions, rootOpts *RootOptions) *RootCmd {
rootCmd := &cobra.Command{
Use: "driverkit",
Short: "A command line tool to build Diginfra kernel modules and eBPF probes.",
ValidArgs: validProcessors,
ArgAliases: aliasProcessors,
Args: cobra.OnlyValidArgs,
DisableFlagsInUseLine: true,
DisableAutoGenTag: true,
SilenceErrors: true,
SilenceUsage: true,
Version: version.String(),
RunE: func(c *cobra.Command, args []string) error {
if len(args) == 0 {
configOpts.Printer.Logger.Info("specify a valid processor", configOpts.Printer.Logger.Args("processors", validProcessors))
}
// Fallback to help
return c.Help()
},
}
ret := &RootCmd{
c: rootCmd,
}
rootCmd.PersistentPreRunE = persistentValidateFunc(ret, configOpts, rootOpts)
flags := rootCmd.Flags()
targets := builder.Targets()
sort.Strings(targets)
configOpts.AddFlags(flags)
rootOpts.AddFlags(flags, targets)
if err := viper.BindPFlags(flags); err != nil {
panic(err)
}
// Flag annotations and custom completions
_ = rootCmd.MarkFlagFilename("config", viper.SupportedExts...)
_ = rootCmd.RegisterFlagCompletionFunc("target", func(c *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return targets, cobra.ShellCompDirectiveDefault
})
_ = rootCmd.RegisterFlagCompletionFunc("architecture", func(c *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return kernelrelease.SupportedArchs.Strings(), cobra.ShellCompDirectiveDefault
})
// Subcommands
rootCmd.AddCommand(NewKubernetesCmd(configOpts, rootOpts, flags))
rootCmd.AddCommand(NewKubernetesInClusterCmd(configOpts, rootOpts, flags))
rootCmd.AddCommand(NewDockerCmd(configOpts, rootOpts, flags))
rootCmd.AddCommand(NewLocalCmd(configOpts, rootOpts, flags))
rootCmd.AddCommand(NewImagesCmd(configOpts, rootOpts, flags))
rootCmd.AddCommand(NewCompletionCmd(configOpts, rootOpts, flags))
ret.StripSensitive()
return ret
}
// Sensitive is a list of sensitive environment variable to replace into the help outputs.
var Sensitive = []string{
"HOME",
}
// StripSensitive removes sensistive info from default values printed into the help messages.
func (r *RootCmd) StripSensitive() {
for _, s := range Sensitive {
homeDir := os.Getenv(s)
for _, childCommand := range r.c.Commands() {
childCommand.Flags().VisitAll(func(f *pflag.Flag) {
f.DefValue = strings.ReplaceAll(f.DefValue, homeDir, fmt.Sprintf("$%s", s))
})
}
}
}
// Command returns the underlying cobra.Command.
func (r *RootCmd) Command() *cobra.Command {
return r.c
}
// SetArgs proxies the arguments to the underlying cobra.Command.
func (r *RootCmd) SetArgs(args []string) {
r.c.SetArgs(args)
}
// SetOutput sets the main command output writer.
func (r *RootCmd) SetOutput(w io.Writer) {
r.c.SetOut(w)
r.c.SetErr(w)
}
// Execute proxies the cobra.Command execution.
func (r *RootCmd) Execute() error {
return r.c.Execute()
}
// Start creates the root command and runs it.
func Start() {
configOpts, err := NewConfigOptions()
if err != nil {
// configOpts will never be nil here
if configOpts != nil {
configOpts.Printer.Logger.Fatal("error setting driverkit config options defaults",
configOpts.Printer.Logger.Args("err", err.Error()))
} else {
os.Exit(1)
}
}
rootOpts, err := NewRootOptions()
if err != nil {
configOpts.Printer.Logger.Fatal("error setting driverkit root options defaults",
configOpts.Printer.Logger.Args("err", err.Error()))
}
// Cleanup spinner upon leaving if any
defer func() {
if configOpts.Printer.Spinner != nil {
_ = configOpts.Printer.Spinner.Stop()
}
}()
root := NewRootCmd(configOpts, rootOpts)
if err = root.Execute(); err != nil {
configOpts.Printer.Logger.Fatal("error executing driverkit", configOpts.Printer.Logger.Args("err", err.Error()))
}
}