-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathbuilder.go
More file actions
720 lines (590 loc) · 17.8 KB
/
builder.go
File metadata and controls
720 lines (590 loc) · 17.8 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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
package commands
import (
"context"
"fmt"
"strings"
"time"
"github.com/kagent-dev/tools/internal/cache"
"github.com/kagent-dev/tools/internal/cmd"
"github.com/kagent-dev/tools/internal/errors"
"github.com/kagent-dev/tools/internal/logger"
"github.com/kagent-dev/tools/internal/security"
"github.com/kagent-dev/tools/internal/telemetry"
"go.opentelemetry.io/otel/attribute"
)
const (
// DefaultTimeout is the default timeout for command execution
DefaultTimeout = 2 * time.Minute
// DefaultCacheTTL is the default cache TTL
DefaultCacheTTL = 1 * time.Minute
)
// CommandBuilder provides a fluent interface for building CLI commands
type CommandBuilder struct {
command string
args []string
namespace string
context string
kubeconfig string
token string
output string
labels map[string]string
annotations map[string]string
timeout time.Duration
useTimeout bool
dryRun bool
force bool
wait bool
validate bool
cached bool
cacheTTL time.Duration
cacheKey string
}
// NewCommandBuilder creates a new command builder
func NewCommandBuilder(command string) *CommandBuilder {
return &CommandBuilder{
command: command,
args: make([]string, 0),
labels: make(map[string]string),
annotations: make(map[string]string),
timeout: DefaultTimeout,
useTimeout: false, // Only enable timeout when explicitly requested
validate: true,
cacheTTL: DefaultCacheTTL,
}
}
// KubectlBuilder creates a kubectl command builder
func KubectlBuilder() *CommandBuilder {
return NewCommandBuilder("kubectl")
}
// HelmBuilder creates a helm command builder
func HelmBuilder() *CommandBuilder {
return NewCommandBuilder("helm")
}
// IstioCtlBuilder creates an istioctl command builder
func IstioCtlBuilder() *CommandBuilder {
return NewCommandBuilder("istioctl")
}
// CiliumBuilder creates a cilium command builder
func CiliumBuilder() *CommandBuilder {
return NewCommandBuilder("cilium")
}
// ArgoRolloutsBuilder creates an argo rollouts command builder
func ArgoRolloutsBuilder() *CommandBuilder {
return NewCommandBuilder("kubectl").WithArgs("argo", "rollouts")
}
// WithArgs adds arguments to the command
func (cb *CommandBuilder) WithArgs(args ...string) *CommandBuilder {
cb.args = append(cb.args, args...)
return cb
}
// WithNamespace sets the namespace
func (cb *CommandBuilder) WithNamespace(namespace string) *CommandBuilder {
if err := security.ValidateNamespace(namespace); err != nil {
logger.Get().Error("Invalid namespace", "namespace", namespace, "error", err)
return cb
}
cb.namespace = namespace
return cb
}
// WithContext sets the Kubernetes context
func (cb *CommandBuilder) WithContext(context string) *CommandBuilder {
if err := security.ValidateCommandInput(context); err != nil {
logger.Get().Error("Invalid context", "context", context, "error", err)
return cb
}
cb.context = context
return cb
}
// WithKubeconfig sets the kubeconfig file
func (cb *CommandBuilder) WithKubeconfig(kubeconfig string) *CommandBuilder {
if kubeconfig != "" {
if err := security.ValidateFilePath(kubeconfig); err != nil {
logger.Get().Error("Invalid kubeconfig path", "kubeconfig", kubeconfig, "error", err)
return cb
}
cb.kubeconfig = kubeconfig
}
return cb
}
// WithToken sets the authentication token for kubectl commands
func (cb *CommandBuilder) WithToken(token string) *CommandBuilder {
if token != "" {
cb.token = token
}
return cb
}
// WithOutput sets the output format
func (cb *CommandBuilder) WithOutput(output string) *CommandBuilder {
validOutputs := []string{"json", "yaml", "wide", "name", "custom-columns", "custom-columns-file", "go-template", "go-template-file", "jsonpath", "jsonpath-file"}
valid := false
for _, validOutput := range validOutputs {
if output == validOutput {
valid = true
break
}
}
if !valid {
logger.Get().Error("Invalid output format", "output", output)
return cb
}
cb.output = output
return cb
}
// WithLabel adds a label selector
func (cb *CommandBuilder) WithLabel(key, value string) *CommandBuilder {
if err := security.ValidateK8sLabel(key, value); err != nil {
logger.Get().Error("Invalid label", "key", key, "value", value, "error", err)
return cb
}
cb.labels[key] = value
return cb
}
// WithLabels adds multiple label selectors
func (cb *CommandBuilder) WithLabels(labels map[string]string) *CommandBuilder {
for key, value := range labels {
cb.WithLabel(key, value)
}
return cb
}
// WithAnnotation adds an annotation
func (cb *CommandBuilder) WithAnnotation(key, value string) *CommandBuilder {
if err := security.ValidateK8sLabel(key, value); err != nil {
logger.Get().Error("Invalid annotation", "key", key, "value", value, "error", err)
return cb
}
cb.annotations[key] = value
return cb
}
// WithTimeout sets the command timeout
func (cb *CommandBuilder) WithTimeout(timeout time.Duration) *CommandBuilder {
cb.useTimeout = true
cb.timeout = timeout
return cb
}
// WithDryRun enables dry run mode
func (cb *CommandBuilder) WithDryRun(dryRun bool) *CommandBuilder {
cb.dryRun = dryRun
return cb
}
// WithForce enables force mode
func (cb *CommandBuilder) WithForce(force bool) *CommandBuilder {
cb.force = force
return cb
}
// WithWait enables wait mode
func (cb *CommandBuilder) WithWait(wait bool) *CommandBuilder {
cb.wait = wait
return cb
}
// WithValidation enables/disables validation
func (cb *CommandBuilder) WithValidation(validate bool) *CommandBuilder {
cb.validate = validate
return cb
}
// WithCache enables caching of the command result
func (cb *CommandBuilder) WithCache(cached bool) *CommandBuilder {
cb.cached = cached
return cb
}
// WithCacheTTL sets the cache TTL
func (cb *CommandBuilder) WithCacheTTL(ttl time.Duration) *CommandBuilder {
cb.cacheTTL = ttl
return cb
}
// WithCacheKey sets a custom cache key
func (cb *CommandBuilder) WithCacheKey(key string) *CommandBuilder {
cb.cacheKey = key
return cb
}
// Build constructs the final command arguments
func (cb *CommandBuilder) Build() (string, []string, error) {
args := make([]string, 0, len(cb.args)+20)
// Add main arguments
args = append(args, cb.args...)
// Add namespace if specified
if cb.namespace != "" {
args = append(args, "--namespace", cb.namespace)
}
// Add context if specified
if cb.context != "" {
args = append(args, "--context", cb.context)
}
// Add kubeconfig if specified
if cb.kubeconfig != "" {
args = append(args, "--kubeconfig", cb.kubeconfig)
}
// Add token if specified
if cb.token != "" {
args = append(args, "--token", cb.token)
}
// Add output format
if cb.output != "" {
args = append(args, "--output", cb.output)
}
// Add label selectors
if len(cb.labels) > 0 {
var labelSelectors []string
for key, value := range cb.labels {
if value != "" {
labelSelectors = append(labelSelectors, fmt.Sprintf("%s=%s", key, value))
} else {
labelSelectors = append(labelSelectors, key)
}
}
if len(labelSelectors) > 0 {
args = append(args, "--selector", strings.Join(labelSelectors, ","))
}
}
// Add timeout when explicitly requested
if cb.timeout > 0 && cb.useTimeout {
args = append(args, "--timeout", cb.timeout.String())
}
// Add dry run
if cb.dryRun {
args = append(args, "--dry-run=client")
}
// Add force
if cb.force {
args = append(args, "--force")
}
// Add wait
if cb.wait {
args = append(args, "--wait")
}
// Add validation
if !cb.validate {
args = append(args, "--validate=false")
}
return cb.command, args, nil
}
// Execute runs the command
func (cb *CommandBuilder) Execute(ctx context.Context) (string, error) {
log := logger.WithContext(ctx)
_, span := telemetry.StartSpan(ctx, "commands.execute",
attribute.String("command", cb.command),
attribute.StringSlice("args", cb.args),
attribute.Bool("cached", cb.cached),
)
defer span.End()
command, args, err := cb.Build()
if err != nil {
telemetry.RecordError(span, err, "Command build failed")
log.Error("failed to build command",
"command", cb.command,
"error", err,
)
return "", err
}
span.SetAttributes(
attribute.String("built_command", command),
attribute.StringSlice("built_args", args),
)
log.Debug("executing command",
"command", command,
"args", args,
"cached", cb.cached,
)
// Generate cache key if caching is enabled
if cb.cached {
telemetry.AddEvent(span, "execution.cached")
return cb.executeWithCache(ctx, command, args)
}
// Execute the command
telemetry.AddEvent(span, "execution.direct")
result, err := cb.executeCommand(ctx, command, args)
if err != nil {
telemetry.RecordError(span, err, "Command execution failed")
return "", err
}
telemetry.RecordSuccess(span, "Command executed successfully")
span.SetAttributes(
attribute.Int("result_length", len(result)),
)
return result, nil
}
func (cb *CommandBuilder) executeWithCache(ctx context.Context, command string, args []string) (string, error) {
log := logger.WithContext(ctx)
_, span := telemetry.StartSpan(ctx, "commands.executeWithCache",
attribute.String("command", command),
attribute.StringSlice("args", args),
attribute.Bool("cached", true),
)
defer span.End()
cacheKey := cb.cacheKey
if cacheKey == "" {
cacheKey = cache.CacheKey(append([]string{command}, args...)...)
}
log.Info("executing cached command",
"command", command,
"args", args,
"cache_key", cacheKey,
"cache_ttl", cb.cacheTTL.String(),
)
// Try to get from cache first
cacheInstance := cache.GetCacheByCommand(command)
telemetry.AddEvent(span, "cache.lookup",
attribute.String("cache_key", cacheKey),
attribute.String("cache_ttl", cb.cacheTTL.String()),
)
result, err := cache.CacheResult(cacheInstance, cacheKey, cb.cacheTTL, func() (string, error) {
telemetry.AddEvent(span, "cache.miss.executing_command")
log.Debug("cache miss, executing command",
"command", command,
"args", args,
)
return cb.executeCommand(ctx, command, args)
})
if err != nil {
telemetry.RecordError(span, err, "Cached command execution failed")
log.Error("cached command execution failed",
"command", command,
"args", args,
"cache_key", cacheKey,
"error", err,
)
return "", err
}
telemetry.RecordSuccess(span, "Cached command executed successfully")
log.Info("cached command execution successful",
"command", command,
"args", args,
"cache_key", cacheKey,
"result_length", len(result),
)
span.SetAttributes(
attribute.String("cache_key", cacheKey),
attribute.Int("result_length", len(result)),
)
return result, nil
}
// executeCommand executes the actual command
func (cb *CommandBuilder) executeCommand(ctx context.Context, command string, args []string) (string, error) {
executor := cmd.GetShellExecutor(ctx)
output, err := executor.Exec(ctx, command, args...)
if err != nil {
// Create appropriate error based on command type
var toolError *errors.ToolError
switch command {
case "kubectl":
toolError = errors.NewKubernetesError(strings.Join(args, " "), err)
case "helm":
toolError = errors.NewHelmError(strings.Join(args, " "), err)
case "istioctl":
toolError = errors.NewIstioError(strings.Join(args, " "), err)
case "cilium":
toolError = errors.NewCiliumError(strings.Join(args, " "), err)
default:
toolError = errors.NewCommandError(command, err)
}
return string(output), toolError
}
return string(output), nil
}
// Common command patterns as helper functions
// GetPods creates a command to get pods
func GetPods(namespace string, labels map[string]string) *CommandBuilder {
builder := KubectlBuilder().WithArgs("get", "pods")
if namespace != "" {
builder = builder.WithNamespace(namespace)
}
if len(labels) > 0 {
builder = builder.WithLabels(labels)
}
return builder.WithCache(true)
}
// GetServices creates a command to get services
func GetServices(namespace string, labels map[string]string) *CommandBuilder {
builder := KubectlBuilder().WithArgs("get", "services")
if namespace != "" {
builder = builder.WithNamespace(namespace)
}
if len(labels) > 0 {
builder = builder.WithLabels(labels)
}
return builder.WithCache(true)
}
// GetDeployments creates a command to get deployments
func GetDeployments(namespace string, labels map[string]string) *CommandBuilder {
builder := KubectlBuilder().WithArgs("get", "deployments")
if namespace != "" {
builder = builder.WithNamespace(namespace)
}
if len(labels) > 0 {
builder = builder.WithLabels(labels)
}
return builder.WithCache(true)
}
// DescribeResource creates a command to describe a resource
func DescribeResource(resourceType, resourceName, namespace string) *CommandBuilder {
builder := KubectlBuilder().WithArgs("describe", resourceType, resourceName)
if namespace != "" {
builder = builder.WithNamespace(namespace)
}
return builder.WithCache(true).WithCacheTTL(2 * time.Minute)
}
// GetLogs creates a command to get logs
func GetLogs(podName, namespace string, options LogOptions) *CommandBuilder {
builder := KubectlBuilder().WithArgs("logs", podName)
if namespace != "" {
builder = builder.WithNamespace(namespace)
}
if options.Container != "" {
builder = builder.WithArgs("--container", options.Container)
}
if options.Follow {
builder = builder.WithArgs("--follow")
}
if options.Previous {
builder = builder.WithArgs("--previous")
}
if options.Timestamps {
builder = builder.WithArgs("--timestamps")
}
if options.TailLines > 0 {
builder = builder.WithArgs("--tail", fmt.Sprintf("%d", options.TailLines))
}
if options.SinceTime != "" {
builder = builder.WithArgs("--since-time", options.SinceTime)
}
if options.SinceDuration != "" {
builder = builder.WithArgs("--since", options.SinceDuration)
}
// Don't cache logs by default as they change frequently
return builder.WithCache(false)
}
// LogOptions represents options for log commands
type LogOptions struct {
Container string
Follow bool
Previous bool
Timestamps bool
TailLines int
SinceTime string
SinceDuration string
}
// ApplyResource creates a command to apply a resource
func ApplyResource(filename string, namespace string, options ApplyOptions) *CommandBuilder {
builder := KubectlBuilder().WithArgs("apply", "-f", filename)
if namespace != "" {
builder = builder.WithNamespace(namespace)
}
if options.DryRun {
builder = builder.WithDryRun(true)
}
if options.Force {
builder = builder.WithForce(true)
}
if options.Wait {
builder = builder.WithWait(true)
}
if !options.Validate {
builder = builder.WithValidation(false)
}
return builder.WithCache(false) // Don't cache apply operations
}
// ApplyOptions represents options for apply commands
type ApplyOptions struct {
DryRun bool
Force bool
Wait bool
Validate bool
}
// DeleteResource creates a command to delete a resource
func DeleteResource(resourceType, resourceName, namespace string, options DeleteOptions) *CommandBuilder {
builder := KubectlBuilder().WithArgs("delete", resourceType, resourceName)
if namespace != "" {
builder = builder.WithNamespace(namespace)
}
if options.Force {
builder = builder.WithForce(true)
}
if options.GracePeriod >= 0 {
builder = builder.WithArgs("--grace-period", fmt.Sprintf("%d", options.GracePeriod))
}
if options.Wait {
builder = builder.WithWait(true)
}
return builder.WithCache(false) // Don't cache delete operations
}
// DeleteOptions represents options for delete commands
type DeleteOptions struct {
Force bool
GracePeriod int
Wait bool
}
// HelmInstall creates a command to install a Helm chart
func HelmInstall(releaseName, chart, namespace string, options HelmInstallOptions) *CommandBuilder {
builder := HelmBuilder().WithArgs("install", releaseName, chart)
if namespace != "" {
builder = builder.WithNamespace(namespace)
}
if options.CreateNamespace {
builder = builder.WithArgs("--create-namespace")
}
if options.DryRun {
builder = builder.WithDryRun(true)
}
if options.Wait {
builder = builder.WithWait(true)
}
if options.ValuesFile != "" {
builder = builder.WithArgs("--values", options.ValuesFile)
}
for key, value := range options.SetValues {
builder = builder.WithArgs("--set", fmt.Sprintf("%s=%s", key, value))
}
return builder.WithCache(false) // Don't cache install operations
}
// HelmInstallOptions represents options for Helm install commands
type HelmInstallOptions struct {
CreateNamespace bool
DryRun bool
Wait bool
ValuesFile string
SetValues map[string]string
}
// HelmList creates a command to list Helm releases
func HelmList(namespace string, options HelmListOptions) *CommandBuilder {
builder := HelmBuilder().WithArgs("list")
if namespace != "" {
builder = builder.WithNamespace(namespace)
}
if options.AllNamespaces {
builder = builder.WithArgs("--all-namespaces")
}
if options.Output != "" {
builder = builder.WithOutput(options.Output)
}
return builder.WithCache(true).WithCacheTTL(2 * time.Minute)
}
// HelmListOptions represents options for Helm list commands
type HelmListOptions struct {
AllNamespaces bool
Output string
}
// IstioProxyStatus creates a command to get Istio proxy status
func IstioProxyStatus(podName, namespace string) *CommandBuilder {
builder := IstioCtlBuilder().WithArgs("proxy-status")
if namespace != "" {
builder = builder.WithNamespace(namespace)
}
if podName != "" {
builder = builder.WithArgs(podName)
}
return builder.WithCache(true).WithCacheTTL(30 * time.Second)
}
// CiliumStatus creates a command to get Cilium status
func CiliumStatus() *CommandBuilder {
return CiliumBuilder().WithArgs("status").WithCache(true).WithCacheTTL(30 * time.Second)
}
// ArgoRolloutsGet creates a command to get Argo rollouts
func ArgoRolloutsGet(rolloutName, namespace string) *CommandBuilder {
builder := ArgoRolloutsBuilder().WithArgs("get", "rollout")
if rolloutName != "" {
builder = builder.WithArgs(rolloutName)
}
if namespace != "" {
builder = builder.WithNamespace(namespace)
}
return builder.WithCache(true).WithCacheTTL(1 * time.Minute)
}