-
Notifications
You must be signed in to change notification settings - Fork 352
/
Copy pathroot.go
291 lines (247 loc) · 9.32 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
/*
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You 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 (
"context"
"errors"
"fmt"
"os"
"strings"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"golang.org/x/term"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
"github.com/apache/camel-k/v2/pkg/client"
v1 "github.com/apache/camel-k/v2/pkg/client/camel/clientset/versioned/typed/camel/v1"
"github.com/apache/camel-k/v2/pkg/util/defaults"
)
const kamelCommandLongDescription = `Apache Camel K is a lightweight integration platform, born on Kubernetes, with serverless
superpowers.
`
// RootCmdOptions --.
//
//nolint:containedctx
type RootCmdOptions struct {
RootContext context.Context `mapstructure:"-"`
Context context.Context `mapstructure:"-"`
ContextCancel context.CancelFunc `mapstructure:"-"`
_client client.Client `mapstructure:"-"`
Flags *viper.Viper `mapstructure:"-"`
KubeConfig string `mapstructure:"kube-config"`
Namespace string `mapstructure:"namespace"`
Verbose bool `mapstructure:"verbose" yaml:",omitempty"`
}
// NewKamelCommand --.
func NewKamelCommand(ctx context.Context) (*cobra.Command, error) {
childCtx, childCancel := context.WithCancel(ctx)
options := RootCmdOptions{
RootContext: ctx,
Context: childCtx,
ContextCancel: childCancel,
Flags: viper.New(),
}
cmd := kamelPreAddCommandInit(&options)
addKamelSubcommands(cmd, &options)
if err := addHelpSubCommands(cmd); err != nil {
return cmd, err
}
err := kamelPostAddCommandInit(cmd, options.Flags)
return cmd, err
}
func kamelPreAddCommandInit(options *RootCmdOptions) *cobra.Command {
cmd := cobra.Command{
BashCompletionFunction: bashCompletionFunction,
PersistentPreRunE: options.preRun,
Use: "kamel",
Short: "Kamel is a awesome client tool for running Apache Camel integrations natively on Kubernetes",
Long: kamelCommandLongDescription,
SilenceUsage: true,
}
cmd.PersistentFlags().StringVar(&options.KubeConfig, "kube-config", os.Getenv("KUBECONFIG"), "Path to the kube config file to use for CLI requests")
cmd.PersistentFlags().StringVarP(&options.Namespace, "namespace", "n", "", "Namespace to use for all operations")
cmd.PersistentFlags().BoolVarP(&options.Verbose, "verbose", "V", false, "Verbose logging")
cobra.AddTemplateFunc("wrappedFlagUsages", wrappedFlagUsages)
cmd.SetUsageTemplate(usageTemplate)
return &cmd
}
func kamelPostAddCommandInit(cmd *cobra.Command, v *viper.Viper) error {
if err := bindPFlagsHierarchy(cmd, v); err != nil {
return err
}
configName := os.Getenv("KAMEL_CONFIG_NAME")
if configName == "" {
configName = DefaultConfigName
}
v.SetConfigName(configName)
configPath := os.Getenv("KAMEL_CONFIG_PATH")
if configPath != "" {
// if a specific config path is set, don't add
// default locations
v.AddConfigPath(configPath)
} else {
v.AddConfigPath(".")
v.AddConfigPath(".kamel")
v.AddConfigPath("$HOME/.kamel")
}
v.AutomaticEnv()
v.SetEnvKeyReplacer(strings.NewReplacer(
".", "_",
"-", "_",
))
if err := v.ReadInConfig(); err != nil {
if !errors.As(err, &viper.ConfigFileNotFoundError{}) {
return err
}
}
return nil
}
func addKamelSubcommands(cmd *cobra.Command, options *RootCmdOptions) {
cmd.AddCommand(newCmdCompletion(cmd))
cmd.AddCommand(cmdOnly(newCmdVersion(options)))
cmd.AddCommand(cmdOnly(newCmdRun(options)))
cmd.AddCommand(cmdOnly(newCmdGet(options)))
cmd.AddCommand(cmdOnly(newCmdDelete(options)))
cmd.AddCommand(cmdOnly(newCmdInstall(options)))
cmd.AddCommand(cmdOnly(newCmdUninstall(options)))
cmd.AddCommand(cmdOnly(newCmdLog(options)))
cmd.AddCommand(newCmdKit(options))
cmd.AddCommand(cmdOnly(newCmdReset(options)))
cmd.AddCommand(newCmdDescribe(options))
cmd.AddCommand(cmdOnly(newCmdRebuild(options)))
cmd.AddCommand(cmdOnly(newCmdOperator(options)))
cmd.AddCommand(cmdOnly(newCmdBuilder(options)))
cmd.AddCommand(cmdOnly(newCmdDebug(options)))
cmd.AddCommand(cmdOnly(newCmdDump(options)))
cmd.AddCommand(cmdOnly(newCmdBind(options)))
cmd.AddCommand(cmdOnly(newCmdPromote(options)))
cmd.AddCommand(newCmdKamelet(options))
cmd.AddCommand(cmdOnly(newCmdConfig(options)))
}
func addHelpSubCommands(cmd *cobra.Command) error {
cmd.InitDefaultHelpCmd()
var helpCmd *cobra.Command
for _, c := range cmd.Commands() {
if c.Name() == "help" {
helpCmd = c
break
}
}
if helpCmd == nil {
return errors.New("could not find any configured help command")
}
helpCmd.Annotations = map[string]string{offlineCommandLabel: "true"}
return nil
}
func (command *RootCmdOptions) preRun(cmd *cobra.Command, _ []string) error {
if !isOfflineCommand(cmd) {
c, err := command.GetCmdClient()
if err != nil {
return fmt.Errorf("cannot get command client: %w", err)
}
if command.Namespace == "" {
current := command.Flags.GetString("kamel.config.default-namespace")
if current == "" {
defaultNS, err := c.GetCurrentNamespace(command.KubeConfig)
if err != nil {
return fmt.Errorf("cannot get current namespace: %w", err)
}
current = defaultNS
}
err = cmd.Flag("namespace").Value.Set(current)
if err != nil {
return err
}
}
// Check that the Kamel CLI matches that of the operator.
// The check relies on the version reported in the IntegrationPlatform status,
// which requires the operator is running and the IntegrationPlatform resource
// reconciled. Hence the compatibility check is skipped for the install and the operator command.
// Furthermore, there can be any incompatibilities, as the install command deploys
// the operator version it's compatible with.
if cmd.Use != builderCommand && cmd.Use != installCommand && cmd.Use != operatorCommand {
checkAndShowCompatibilityWarning(command.Context, cmd, c, command.Namespace)
}
}
return nil
}
func checkAndShowCompatibilityWarning(ctx context.Context, cmd *cobra.Command, c client.Client, namespace string) {
operatorVersion, err := operatorVersion(ctx, c, namespace)
if err != nil {
if k8serrors.IsNotFound(err) {
fmt.Fprintf(cmd.ErrOrStderr(), "No IntegrationPlatform resource in %s namespace\n", namespace)
} else {
fmt.Fprintf(cmd.ErrOrStderr(), "Unable to retrieve the operator version: %s\n", err.Error())
}
} else {
if operatorVersion != "" && !compatibleVersions(operatorVersion, defaults.Version, cmd) {
fmt.Fprintf(cmd.ErrOrStderr(), "You're using Camel K %s client with a %s cluster operator, it's recommended to use the same version to improve compatibility.\n\n", defaults.Version, operatorVersion)
}
}
}
// GetCmdClient returns the client that can be used from command line tools.
func (command *RootCmdOptions) GetCmdClient() (client.Client, error) {
// Get the pre-computed client
if command._client != nil {
return command._client, nil
}
var err error
command._client, err = command.NewCmdClient()
return command._client, err
}
// GetCamelCmdClient returns a client to access the Camel resources.
func (command *RootCmdOptions) GetCamelCmdClient() (*v1.CamelV1Client, error) {
c, err := command.GetCmdClient()
if err != nil {
return nil, err
}
return v1.NewForConfig(c.GetConfig())
}
// NewCmdClient returns a new client that can be used from command line tools.
func (command *RootCmdOptions) NewCmdClient() (client.Client, error) {
return client.NewOutOfClusterClient(command.KubeConfig)
}
func (command *RootCmdOptions) PrintVerboseOut(cmd *cobra.Command, a ...interface{}) {
if command.Verbose {
fmt.Fprintln(cmd.OutOrStdout(), a...)
}
}
func (command *RootCmdOptions) PrintfVerboseOutf(cmd *cobra.Command, format string, a ...interface{}) {
if command.Verbose {
fmt.Fprintf(cmd.OutOrStdout(), format, a...)
}
}
func (command *RootCmdOptions) PrintfVerboseErrf(cmd *cobra.Command, format string, a ...interface{}) {
if command.Verbose {
fmt.Fprintf(cmd.ErrOrStderr(), format, a...)
}
}
func wrappedFlagUsages(cmd *cobra.Command) string {
width := 80
if w, _, err := term.GetSize(0); err == nil {
width = w
}
return cmd.Flags().FlagUsagesWrapped(width - 1)
}
var usageTemplate = `Usage:{{if .Runnable}}
{{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}
{{.CommandPath}} [command]{{end}}{{if .HasAvailableSubCommands}}
Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}
Flags:
{{ wrappedFlagUsages . | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}
Global Flags:
{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableSubCommands}}
Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}
`