forked from migtools/oadp-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroot.go
More file actions
516 lines (448 loc) · 17.7 KB
/
Copy pathroot.go
File metadata and controls
516 lines (448 loc) · 17.7 KB
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
/*
Copyright 2025 The OADP CLI Contributors.
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 (
"context"
"flag"
"fmt"
"io"
"net"
"os"
"regexp"
"strings"
"sync"
"time"
"github.com/fatih/color"
"github.com/migtools/oadp-cli/cmd/completion"
mustgather "github.com/migtools/oadp-cli/cmd/must-gather"
"github.com/migtools/oadp-cli/cmd/nabsl-request"
nonadmin "github.com/migtools/oadp-cli/cmd/non-admin"
"github.com/migtools/oadp-cli/cmd/setup"
"github.com/spf13/cobra"
velerov1 "github.com/vmware-tanzu/velero/pkg/apis/velero/v1"
clientcmd "github.com/vmware-tanzu/velero/pkg/client"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/discovery"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
kbclient "sigs.k8s.io/controller-runtime/pkg/client"
"github.com/vmware-tanzu/velero/pkg/cmd/cli/backup"
"github.com/vmware-tanzu/velero/pkg/cmd/cli/backuplocation"
cliclient "github.com/vmware-tanzu/velero/pkg/cmd/cli/client"
"github.com/vmware-tanzu/velero/pkg/cmd/cli/create"
"github.com/vmware-tanzu/velero/pkg/cmd/cli/debug"
veldelete "github.com/vmware-tanzu/velero/pkg/cmd/cli/delete"
"github.com/vmware-tanzu/velero/pkg/cmd/cli/describe"
"github.com/vmware-tanzu/velero/pkg/cmd/cli/get"
"github.com/vmware-tanzu/velero/pkg/cmd/cli/restore"
"github.com/vmware-tanzu/velero/pkg/cmd/cli/schedule"
"github.com/vmware-tanzu/velero/pkg/cmd/cli/snapshotlocation"
"github.com/vmware-tanzu/velero/pkg/cmd/cli/version"
veleroflag "github.com/vmware-tanzu/velero/pkg/cmd/util/flag"
"github.com/vmware-tanzu/velero/pkg/features"
"k8s.io/klog/v2"
)
// globalRequestTimeout holds the request timeout value set by --request-timeout flag.
// This is used by the timeoutFactory wrapper to apply dial timeout to all clients.
var (
globalRequestTimeout time.Duration
globalTimeoutMu sync.RWMutex
)
// setGlobalRequestTimeout sets the global request timeout value.
func setGlobalRequestTimeout(timeout time.Duration) {
globalTimeoutMu.Lock()
defer globalTimeoutMu.Unlock()
globalRequestTimeout = timeout
}
// getGlobalRequestTimeout gets the global request timeout value.
func getGlobalRequestTimeout() time.Duration {
globalTimeoutMu.RLock()
defer globalTimeoutMu.RUnlock()
return globalRequestTimeout
}
// timeoutFactory wraps a Velero client.Factory to apply dial timeout to REST configs.
type timeoutFactory struct {
clientcmd.Factory
}
// applyTimeoutToConfig applies the global request timeout to a REST config.
func applyTimeoutToConfig(config *rest.Config) {
timeout := getGlobalRequestTimeout()
if timeout > 0 {
config.Timeout = timeout
// Set custom dial function with timeout for TCP connections
dialer := &net.Dialer{
Timeout: timeout,
}
config.Dial = func(ctx context.Context, network, address string) (net.Conn, error) {
return dialer.DialContext(ctx, network, address)
}
}
}
// ClientConfig returns a REST config with dial timeout applied.
func (f *timeoutFactory) ClientConfig() (*rest.Config, error) {
config, err := f.Factory.ClientConfig()
if err != nil {
return nil, err
}
applyTimeoutToConfig(config)
return config, nil
}
// KubeClient returns a Kubernetes client with dial timeout applied.
func (f *timeoutFactory) KubeClient() (kubernetes.Interface, error) {
config, err := f.ClientConfig()
if err != nil {
return nil, err
}
return kubernetes.NewForConfig(config)
}
// DynamicClient returns a Kubernetes dynamic client with dial timeout applied.
func (f *timeoutFactory) DynamicClient() (dynamic.Interface, error) {
config, err := f.ClientConfig()
if err != nil {
return nil, err
}
return dynamic.NewForConfig(config)
}
// DiscoveryClient returns a Kubernetes discovery client with dial timeout applied.
func (f *timeoutFactory) DiscoveryClient() (discovery.AggregatedDiscoveryInterface, error) {
config, err := f.ClientConfig()
if err != nil {
return nil, err
}
return discovery.NewDiscoveryClientForConfig(config)
}
// KubebuilderClient returns a controller-runtime client with dial timeout applied.
func (f *timeoutFactory) KubebuilderClient() (kbclient.Client, error) {
config, err := f.ClientConfig()
if err != nil {
return nil, err
}
scheme := runtime.NewScheme()
if err := velerov1.AddToScheme(scheme); err != nil {
return nil, err
}
return kbclient.New(config, kbclient.Options{Scheme: scheme})
}
// KubebuilderWatchClient returns a controller-runtime client with watch capability and dial timeout applied.
func (f *timeoutFactory) KubebuilderWatchClient() (kbclient.WithWatch, error) {
config, err := f.ClientConfig()
if err != nil {
return nil, err
}
scheme := runtime.NewScheme()
if err := velerov1.AddToScheme(scheme); err != nil {
return nil, err
}
return kbclient.NewWithWatch(config, kbclient.Options{Scheme: scheme})
}
// veleroCommandPattern matches "velero" when used as a CLI command.
// It matches "velero" followed by common command patterns, including two-word commands
// like "backup create", "restore get", etc.
var veleroCommandPattern = regexp.MustCompile(`(?m)(?:^|[\s\x60])velero\s+(?:` +
// Two-word commands: "backup create", "restore get", etc.
`(?:backup|restore|schedule)\s+(?:create|get|delete|describe|logs|download|patch)` +
`|` +
// Single-word commands
`(?:version|install|uninstall|plugin|snapshot-location|backup-location|restic|repo|client|completion|bug|debug|datamover)` +
`)`)
// veleroCreateVerbFirstPattern matches upstream Velero's "velero create <resource>" example
// text (verb-first), which some commands hardcode instead of the actual resource-first
// invocation. For example, velero's schedule create command is invoked as
// "velero schedule create NAME", but its upstream Example text says "velero create schedule
// NAME". veleroCommandPattern above doesn't catch this ordering, so it's normalized to
// resource-first form here before the general replacement runs.
var veleroCreateVerbFirstPattern = regexp.MustCompile(`(^|[\s\x60\n])velero\s+create\s+(backup|restore|schedule)\b`)
// replaceVeleroCommandWithOADP performs context-aware replacement of "velero" with "oadp".
// It only replaces "velero" when it's being used as a CLI command, not when referring to
// the Velero project, server, or components.
// It also prepends "oc" or "kubectl" based on how the CLI was invoked.
func replaceVeleroCommandWithOADP(text string) string {
// Use "oc" as the CLI prefix since OADP is primarily used on OpenShift
cliPrefix := "oc"
// Normalize verb-first "velero create <resource>" examples to resource-first
// "oc oadp <resource> create" before the general pattern runs, since the actual
// command is always invoked resource-first.
text = veleroCreateVerbFirstPattern.ReplaceAllString(text, "${1}"+cliPrefix+" oadp ${2} create")
// Replace "velero <command>" patterns with "oc/kubectl oadp <command>"
result := veleroCommandPattern.ReplaceAllStringFunc(text, func(match string) string {
// Preserve leading whitespace or backtick
if strings.HasPrefix(match, " ") || strings.HasPrefix(match, "\t") || strings.HasPrefix(match, "`") || strings.HasPrefix(match, "\n") {
prefix := match[0:1]
return prefix + cliPrefix + " " + strings.Replace(match[1:], "velero", "oadp", 1)
}
// Start of line - prepend cli prefix
return cliPrefix + " " + strings.Replace(match, "velero", "oadp", 1)
})
return result
}
// replaceVeleroWithOADP recursively replaces all mentions of "velero" with "oadp" in the
// Example field of the given command and all its children. It also wraps the Run and RunE
// functions to replace "velero" with "oadp" in runtime output.
func replaceVeleroWithOADP(cmd *cobra.Command) *cobra.Command {
// Replace in multiple command fields using context-aware replacement
cmd.Example = replaceVeleroCommandWithOADP(cmd.Example)
// Skip wrapping commands that stream output or make long-running requests
// to allow real-time display without buffering. Check both the command itself
// and its parent to handle both "backup describe" and "describe backup" patterns.
isLogsCommand := cmd.Use == "logs" || strings.HasPrefix(cmd.Use, "logs ")
isDescribeCommand := cmd.Use == "describe" || strings.HasPrefix(cmd.Use, "describe ")
isDeleteCommand := cmd.Use == "delete" || strings.HasPrefix(cmd.Use, "delete ")
// Also check if parent command is one we should skip
if cmd.Parent() != nil {
parentUse := cmd.Parent().Use
isLogsCommand = isLogsCommand || parentUse == "logs" || strings.HasPrefix(parentUse, "logs ")
isDescribeCommand = isDescribeCommand || parentUse == "describe" || strings.HasPrefix(parentUse, "describe ")
isDeleteCommand = isDeleteCommand || parentUse == "delete" || strings.HasPrefix(parentUse, "delete ")
}
shouldSkipWrapper := isLogsCommand || isDescribeCommand || isDeleteCommand
// Wrap the Run function to replace velero in output
if cmd.Run != nil && !shouldSkipWrapper {
originalRun := cmd.Run
cmd.Run = func(c *cobra.Command, args []string) {
// Capture stdout temporarily
oldStdout := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
// Run the original command
originalRun(c, args)
// Restore stdout
_ = w.Close()
os.Stdout = oldStdout
// Read captured output and replace velero with oadp (context-aware)
var buf strings.Builder
_, err := io.Copy(&buf, r)
if err != nil {
fmt.Fprintf(os.Stderr, "WARNING: Error copying output: %v\n", err)
}
output := replaceVeleroCommandWithOADP(buf.String())
fmt.Print(output)
}
}
// Wrap the RunE function to replace velero in output
if cmd.RunE != nil && !shouldSkipWrapper {
originalRunE := cmd.RunE
cmd.RunE = func(c *cobra.Command, args []string) error {
// Capture stdout temporarily
oldStdout := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
// Run the original command
err := originalRunE(c, args)
// Restore stdout
_ = w.Close()
os.Stdout = oldStdout
// Read captured output and replace velero with oadp (context-aware)
var buf strings.Builder
_, copyErr := io.Copy(&buf, r)
if copyErr != nil {
fmt.Fprintf(os.Stderr, "WARNING: Error copying output: %v\n", copyErr)
}
output := replaceVeleroCommandWithOADP(buf.String())
fmt.Print(output)
return err
}
}
// Recursively process all child commands
for _, child := range cmd.Commands() {
replaceVeleroWithOADP(child)
}
return cmd
}
// renameTimeoutFlag renames --timeout flag to --request-timeout for kubectl consistency.
// This applies to all commands recursively to ensure a consistent CLI experience.
func renameTimeoutFlag(cmd *cobra.Command) {
// Check if this command has a --timeout flag
timeoutFlag := cmd.Flags().Lookup("timeout")
if timeoutFlag != nil {
// Get the current value and usage
usage := timeoutFlag.Usage
defValue := timeoutFlag.DefValue
// Parse the default value as duration
var defaultDuration time.Duration
if defValue != "" && defValue != "0s" {
if parsed, err := time.ParseDuration(defValue); err == nil {
defaultDuration = parsed
}
}
// Create a variable to hold the value
var requestTimeout time.Duration
// If there's a shorthand, we need to handle it
shorthand := timeoutFlag.Shorthand
// Hide the old flag instead of removing it (to avoid breaking existing scripts)
timeoutFlag.Hidden = true
// Add the new --request-timeout flag
if shorthand != "" {
cmd.Flags().DurationVarP(&requestTimeout, "request-timeout", shorthand, defaultDuration, usage)
} else {
cmd.Flags().DurationVar(&requestTimeout, "request-timeout", defaultDuration, usage)
}
// Link the flags so setting one affects the other and set global timeout
cmd.PreRunE = wrapPreRunE(cmd.PreRunE, func(c *cobra.Command, args []string) error {
// If request-timeout was set, copy its value to the timeout flag and set global
if c.Flags().Changed("request-timeout") {
rtFlag := c.Flags().Lookup("request-timeout")
if rtFlag != nil {
// Set the global timeout for the timeoutFactory wrapper
if parsed, err := time.ParseDuration(rtFlag.Value.String()); err == nil {
setGlobalRequestTimeout(parsed)
}
return c.Flags().Set("timeout", rtFlag.Value.String())
}
}
return nil
})
}
// Recursively process all child commands
for _, child := range cmd.Commands() {
renameTimeoutFlag(child)
}
}
// wrapPreRunE wraps an existing PreRunE function with additional logic
func wrapPreRunE(existing func(*cobra.Command, []string) error, additional func(*cobra.Command, []string) error) func(*cobra.Command, []string) error {
return func(cmd *cobra.Command, args []string) error {
if err := additional(cmd, args); err != nil {
return err
}
if existing != nil {
return existing(cmd, args)
}
return nil
}
}
// isNonadminEnabled checks if nonadmin mode is enabled in the VeleroConfig.
// Handles both boolean and string representations since
// `oc oadp client config set nonadmin=true` stores the value as a string.
func isNonadminEnabled(config clientcmd.VeleroConfig) bool {
val, ok := config["nonadmin"]
if !ok {
return false
}
switch v := val.(type) {
case bool:
return v
case string:
return strings.EqualFold(v, "true")
default:
return false
}
}
// NewVeleroRootCommand returns a root command with all Velero CLI subcommands attached.
func NewVeleroRootCommand(baseName string) *cobra.Command {
config, err := clientcmd.LoadConfig()
if err != nil {
fmt.Fprintf(os.Stderr, "WARNING: Error reading config file: %v\n", err)
}
if config == nil {
config = clientcmd.VeleroConfig{}
}
// When nonadmin mode is enabled, remove the namespace override so the
// factory uses the current kubeconfig context namespace instead of an
// admin namespace like openshift-adp.
if isNonadminEnabled(config) {
delete(config, clientcmd.ConfigKeyNamespace)
} else if config.Namespace() == "" {
config[clientcmd.ConfigKeyNamespace] = "openshift-adp"
}
// Declare cmdFeatures and cmdColorzied here so we can access them in the PreRun hooks
// without doing a chain of calls into the command's FlagSet
var cmdFeatures veleroflag.StringArray
var cmdColorzied veleroflag.OptionalBool
c := &cobra.Command{
Use: baseName,
Short: "OADP CLI commands",
Run: func(cmd *cobra.Command, args []string) {
// Default action when no subcommand is provided
fmt.Println("Welcome to the OADP CLI! Use --help to see available commands.")
},
PersistentPreRun: func(cmd *cobra.Command, args []string) {
features.Enable(config.Features()...)
features.Enable(cmdFeatures...)
switch {
case cmdColorzied.Value != nil:
color.NoColor = !*cmdColorzied.Value
default:
color.NoColor = !config.Colorized()
}
},
}
// Create Velero client factory for regular Velero commands
// This factory is used to create clients for interacting with Velero resources.
// We wrap it with timeoutFactory to apply dial timeout from --request-timeout flag.
baseFactory := clientcmd.NewFactory(baseName, config)
f := &timeoutFactory{Factory: baseFactory}
// Bind factory flags to enable -n/--namespace flag for admin commands.
// This allows admin Velero and NABSL-request commands to accept namespace via CLI flag.
// Nonadmin commands continue using GetCurrentNamespace() for security isolation.
f.BindFlags(c.PersistentFlags())
c.AddCommand(
backup.NewCommand(f),
schedule.NewCommand(f),
restore.NewCommand(f),
version.NewCommand(f),
get.NewCommand(f),
describe.NewCommand(f),
create.NewCommand(f),
veldelete.NewCommand(f),
cliclient.NewCommand(),
completion.NewCommand(),
backuplocation.NewCommand(f),
snapshotlocation.NewCommand(f),
debug.NewCommand(f),
)
// Admin NABSL request commands - use Velero factory (admin namespace)
c.AddCommand(nabsl.NewNABSLRequestCommand(f))
// Custom subcommands - use NonAdmin factory
c.AddCommand(nonadmin.NewNonAdminCommand(f))
// Must-gather command - diagnostic tool
c.AddCommand(mustgather.NewMustGatherCommand(f))
// Setup command - auto-detect and configure admin vs non-admin mode
c.AddCommand(setup.NewSetupCommand(f))
// Apply velero->oadp replacement to all commands recursively
// Skip nonadmin commands since we have full control over their output
for _, cmd := range c.Commands() {
// Don't wrap nonadmin commands - we control them and they already use correct terminology
// Don't wrap completion - it needs direct stdout access for shell completion generation
if cmd.Use == "nonadmin" || cmd.Use == "nabsl-request" || cmd.Use == "must-gather" || cmd.Use == "setup" || strings.HasPrefix(cmd.Use, "completion") {
continue
}
replaceVeleroWithOADP(cmd)
}
// Rename --timeout flags to --request-timeout for kubectl consistency
for _, cmd := range c.Commands() {
renameTimeoutFlag(cmd)
}
// When nonadmin mode is enabled, remove all admin commands so only
// nonadmin, client (for toggling the config), and help are available.
if isNonadminEnabled(config) {
allowedCmds := map[string]bool{
"nonadmin": true,
"client": true,
"completion": true,
"setup": true,
}
for _, cmd := range c.Commands() {
if !allowedCmds[cmd.Use] {
c.RemoveCommand(cmd)
}
}
}
// Set custom usage template to show "oc oadp" instead of just "oadp"
usageTemplate := c.UsageTemplate()
usageTemplate = strings.ReplaceAll(usageTemplate, "{{.CommandPath}}", "oc {{.CommandPath}}")
usageTemplate = strings.ReplaceAll(usageTemplate, "{{.UseLine}}", "oc {{.UseLine}}")
c.SetUsageTemplate(usageTemplate)
klog.InitFlags(flag.CommandLine)
c.PersistentFlags().AddGoFlagSet(flag.CommandLine)
return c
}