-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoverage.html
More file actions
4444 lines (3804 loc) · 209 KB
/
coverage.html
File metadata and controls
4444 lines (3804 loc) · 209 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
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>cmd: Go Coverage Report</title>
<style>
body {
background: black;
color: rgb(80, 80, 80);
}
body, pre, #legend span {
font-family: Menlo, monospace;
font-weight: bold;
}
#topbar {
background: black;
position: fixed;
top: 0; left: 0; right: 0;
height: 42px;
border-bottom: 1px solid rgb(80, 80, 80);
}
#content {
margin-top: 50px;
}
#nav, #legend {
float: left;
margin-left: 10px;
}
#legend {
margin-top: 12px;
}
#nav {
margin-top: 10px;
}
#legend span {
margin: 0 5px;
}
.cov0 { color: rgb(192, 0, 0) }
.cov1 { color: rgb(128, 128, 128) }
.cov2 { color: rgb(116, 140, 131) }
.cov3 { color: rgb(104, 152, 134) }
.cov4 { color: rgb(92, 164, 137) }
.cov5 { color: rgb(80, 176, 140) }
.cov6 { color: rgb(68, 188, 143) }
.cov7 { color: rgb(56, 200, 146) }
.cov8 { color: rgb(44, 212, 149) }
.cov9 { color: rgb(32, 224, 152) }
.cov10 { color: rgb(20, 236, 155) }
</style>
</head>
<body>
<div id="topbar">
<div id="nav">
<select id="files">
<option value="file0">kdebug/cmd/cluster.go (0.0%)</option>
<option value="file1">kdebug/cmd/ingress.go (0.0%)</option>
<option value="file2">kdebug/cmd/pod.go (0.0%)</option>
<option value="file3">kdebug/cmd/root.go (0.0%)</option>
<option value="file4">kdebug/cmd/service.go (0.0%)</option>
<option value="file5">kdebug/internal/client/client.go (37.7%)</option>
<option value="file6">kdebug/internal/output/output.go (88.5%)</option>
<option value="file7">kdebug/main.go (0.0%)</option>
<option value="file8">kdebug/pkg/cluster/cluster.go (17.1%)</option>
<option value="file9">kdebug/pkg/ingress/ingress.go (10.2%)</option>
<option value="file10">kdebug/pkg/pod/checks.go (34.9%)</option>
<option value="file11">kdebug/pkg/pod/pod.go (15.9%)</option>
<option value="file12">kdebug/pkg/service/service.go (50.0%)</option>
</select>
</div>
<div id="legend">
<span>not tracked</span>
<span class="cov0">not covered</span>
<span class="cov8">covered</span>
</div>
</div>
<div id="content">
<pre class="file" id="file0" style="display: none">package cmd
import (
"context"
"fmt"
"time"
"github.com/spf13/cobra"
"kdebug/internal/client"
"kdebug/internal/output"
"kdebug/pkg/cluster"
)
// clusterCmd represents the cluster command
var clusterCmd = &cobra.Command{
Use: "cluster",
Short: "Run comprehensive cluster health checks",
Long: `Analyze the overall health of your Kubernetes cluster by checking:
• API Server connectivity and response time
• Node health and conditions (ready, memory pressure, disk pressure)
• Control plane components (etcd, scheduler, controller manager)
• DNS functionality and CoreDNS health
• Basic cluster configuration
This command provides a quick overview of cluster-wide issues that might
affect workload deployment and operation.`,
Example: ` # Run all cluster health checks
kdebug cluster
# Check only node health
kdebug cluster --nodes-only
# Output results as JSON
kdebug cluster --output json
# Verbose output with detailed information
kdebug cluster --verbose
# Set custom timeout for checks
kdebug cluster --timeout 30s`,
RunE: runClusterDiagnostics,
}
func init() <span class="cov0" title="0">{
// Add cluster command to root
rootCmd.AddCommand(clusterCmd)
// Cluster-specific flags
clusterCmd.Flags().Bool("nodes-only", false, "check only node health (skip control plane and DNS checks)")
clusterCmd.Flags().Duration("timeout", 30*time.Second, "timeout for cluster checks")
}</span>
// runClusterDiagnostics executes the cluster diagnostic checks
func runClusterDiagnostics(cmd *cobra.Command, args []string) error <span class="cov0" title="0">{
// Get flag values
nodesOnly, _ := cmd.Flags().GetBool("nodes-only")
timeout, _ := cmd.Flags().GetDuration("timeout")
// Create context with timeout
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
// Initialize output manager
outputMgr := output.NewOutputManager(outputFormat, verbose)
// Print initial info
if verbose </span><span class="cov0" title="0">{
outputMgr.PrintInfo("Starting cluster diagnostics...")
outputMgr.PrintInfo(fmt.Sprintf("Timeout: %v", timeout))
if kubeconfig != "" </span><span class="cov0" title="0">{
outputMgr.PrintInfo(fmt.Sprintf("Using kubeconfig: %s", kubeconfig))
}</span>
<span class="cov0" title="0">fmt.Println()</span>
}
// Initialize Kubernetes client
<span class="cov0" title="0">k8sClient, err := client.NewKubernetesClient(kubeconfig)
if err != nil </span><span class="cov0" title="0">{
outputMgr.PrintError("Failed to initialize Kubernetes client", err)
return err
}</span>
// Test basic connectivity first
<span class="cov0" title="0">if err := k8sClient.TestConnection(ctx); err != nil </span><span class="cov0" title="0">{
outputMgr.PrintError("Failed to connect to Kubernetes cluster", err)
outputMgr.PrintInfo("Please check your kubeconfig and cluster connectivity")
return err
}</span>
// Initialize cluster diagnostic
<span class="cov0" title="0">clusterDiag := cluster.NewClusterDiagnostic(k8sClient, outputMgr)
// Run diagnostics
report, err := clusterDiag.RunDiagnostics(ctx)
if err != nil </span><span class="cov0" title="0">{
outputMgr.PrintError("Failed to run cluster diagnostics", err)
return err
}</span>
// Filter results if nodes-only flag is set
<span class="cov0" title="0">if nodesOnly </span><span class="cov0" title="0">{
report = filterNodeChecksOnly(report)
}</span>
// Print results
<span class="cov0" title="0">if err := outputMgr.PrintReport(report); err != nil </span><span class="cov0" title="0">{
outputMgr.PrintError("Failed to print diagnostic report", err)
return err
}</span>
// Print additional information based on results
<span class="cov0" title="0">if report.Summary.Failed > 0 </span><span class="cov0" title="0">{
fmt.Println()
outputMgr.PrintWarning("Some critical issues were found that may affect cluster functionality")
outputMgr.PrintInfo("Review the failed checks above and follow the suggested actions")
// Exit with non-zero code if there are critical failures
return fmt.Errorf("cluster health check failed: %d critical issues found", report.Summary.Failed)
}</span>
<span class="cov0" title="0">if report.Summary.Warnings > 0 </span><span class="cov0" title="0">{
fmt.Println()
outputMgr.PrintWarning("Some warnings were found that should be addressed")
outputMgr.PrintInfo("These issues may not immediately affect functionality but should be monitored")
}</span>
<span class="cov0" title="0">if report.Summary.Failed == 0 && report.Summary.Warnings == 0 </span><span class="cov0" title="0">{
fmt.Println()
outputMgr.PrintSuccess("Cluster appears to be healthy!")
}</span>
<span class="cov0" title="0">return nil</span>
}
// filterNodeChecksOnly filters the report to include only node-related checks
func filterNodeChecksOnly(report *output.DiagnosticReport) *output.DiagnosticReport <span class="cov0" title="0">{
var filteredChecks []output.CheckResult
for _, check := range report.Checks </span><span class="cov0" title="0">{
// Include connectivity check and node-related checks
if check.Name == "API Server Connectivity" ||
containsAny(check.Name, []string{"Node", "node"}) </span><span class="cov0" title="0">{
filteredChecks = append(filteredChecks, check)
}</span>
}
// Update the report
<span class="cov0" title="0">newReport := *report
newReport.Checks = filteredChecks
newReport.Target = "cluster (nodes only)"
// Recalculate summary
newSummary := output.Summary{}
for _, check := range filteredChecks </span><span class="cov0" title="0">{
newSummary.Total++
switch check.Status </span>{
case output.StatusPassed:<span class="cov0" title="0">
newSummary.Passed++</span>
case output.StatusFailed:<span class="cov0" title="0">
newSummary.Failed++</span>
case output.StatusWarning:<span class="cov0" title="0">
newSummary.Warnings++</span>
case output.StatusSkipped:<span class="cov0" title="0">
newSummary.Skipped++</span>
}
}
<span class="cov0" title="0">newReport.Summary = newSummary
return &newReport</span>
}
// containsAny checks if the string contains any of the given substrings
func containsAny(s string, substrings []string) bool <span class="cov0" title="0">{
for _, substr := range substrings </span><span class="cov0" title="0">{
if len(s) >= len(substr) </span><span class="cov0" title="0">{
for i := 0; i <= len(s)-len(substr); i++ </span><span class="cov0" title="0">{
if s[i:i+len(substr)] == substr </span><span class="cov0" title="0">{
return true
}</span>
}
}
}
<span class="cov0" title="0">return false</span>
}
</pre>
<pre class="file" id="file1" style="display: none">package cmd
import (
"context"
"fmt"
"strings"
"time"
"github.com/spf13/cobra"
"kdebug/internal/client"
"kdebug/internal/output"
"kdebug/pkg/ingress"
)
var ingressCmd = &cobra.Command{
Use: "ingress [INGRESS_NAME]",
Short: "Diagnose Kubernetes ingress resources",
Long: `Diagnose Kubernetes ingress resources for common issues and misconfigurations.
This command analyzes ingress resources and their dependencies including:
- Ingress existence and configuration
- Backend service availability and configuration
- Service endpoint health
- SSL/TLS certificate validation
- Controller discovery and status
Examples:
# Diagnose a specific ingress
kdebug ingress my-ingress
# Diagnose all ingress resources in current namespace
kdebug ingress --all
# Diagnose all ingress resources across all namespaces
kdebug ingress --all --all-namespaces
# Run specific checks only
kdebug ingress my-ingress --checks config,backends,ssl
# Output in JSON format
kdebug ingress my-ingress --output json`,
Args: cobra.MaximumNArgs(1),
RunE: runIngressDiagnosis,
}
var (
ingressAll bool
ingressAllNamespaces bool
ingressChecks []string
ingressOutputFormat string
ingressVerbose bool
ingressTimeout time.Duration
)
func init() <span class="cov0" title="0">{
rootCmd.AddCommand(ingressCmd)
// Flags
ingressCmd.Flags().BoolVar(&ingressAll, "all", false, "Diagnose all ingress resources in namespace(s)")
ingressCmd.Flags().BoolVar(&ingressAllNamespaces, "all-namespaces", false, "Analyze ingress resources across all namespaces")
ingressCmd.Flags().StringSliceVar(&ingressChecks, "checks", []string{}, "Comma-separated list of checks to run (existence,config,backends,endpoints,ssl)")
ingressCmd.Flags().StringVarP(&ingressOutputFormat, "output", "o", "table", "Output format (table, json, yaml)")
ingressCmd.Flags().BoolVarP(&ingressVerbose, "verbose", "v", false, "Enable verbose output")
ingressCmd.Flags().DurationVar(&ingressTimeout, "timeout", 30*time.Second, "Timeout for diagnosis operations")
// Add aliases for convenience
ingressCmd.Aliases = []string{"ing", "ingresses"}
}</span>
func runIngressDiagnosis(cmd *cobra.Command, args []string) error <span class="cov0" title="0">{
// Get global flags
kubeconfig, _ := cmd.Flags().GetString("kubeconfig")
namespace, _ := cmd.Flags().GetString("namespace")
// Set defaults
if namespace == "" </span><span class="cov0" title="0">{
namespace = "default"
}</span>
// Create context with timeout
<span class="cov0" title="0">ctx, cancel := context.WithTimeout(context.Background(), ingressTimeout)
defer cancel()
// Initialize Kubernetes client
kubeClient, err := client.NewKubernetesClient(kubeconfig)
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to create Kubernetes client: %w", err)
}</span>
// Initialize output manager
<span class="cov0" title="0">outputMgr := output.NewOutputManager(ingressOutputFormat, ingressVerbose)
// Initialize ingress diagnostic
ingressDiag := ingress.NewIngressDiagnostic(kubeClient, outputMgr)
// Prepare diagnostic configuration
config := ingress.DiagnosticConfig{
Namespace: namespace,
AllNamespaces: ingressAllNamespaces,
All: ingressAll,
Checks: ingressChecks,
Timeout: ingressTimeout,
}
// Handle specific ingress vs. all ingresses
if len(args) == 1 </span><span class="cov0" title="0">{
// Diagnose specific ingress
ingressName := args[0]
config.IngressName = ingressName
report, err := ingressDiag.DiagnoseIngress(ctx, ingressName, config)
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to diagnose ingress %s: %w", ingressName, err)
}</span>
// Print the report
<span class="cov0" title="0">if err := outputMgr.PrintReport(report); err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to print report: %w", err)
}</span>
} else<span class="cov0" title="0"> if ingressAll </span><span class="cov0" title="0">{
// Diagnose all ingresses
reports, err := ingressDiag.DiagnoseAllIngresses(ctx, config)
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to diagnose ingresses: %w", err)
}</span>
// Print each report
<span class="cov0" title="0">for _, report := range reports </span><span class="cov0" title="0">{
if err := outputMgr.PrintReport(report); err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to print report: %w", err)
}</span>
// Add separator between reports for table format
<span class="cov0" title="0">if ingressOutputFormat == "table" && len(reports) > 1 </span><span class="cov0" title="0">{
fmt.Println(output.ColorDim + strings.Repeat("─", 80) + output.ColorReset)
}</span>
}
// Print summary if multiple ingresses were analyzed
<span class="cov0" title="0">if len(reports) > 1 </span><span class="cov0" title="0">{
printIngressSummary(reports)
}</span>
} else<span class="cov0" title="0"> {
return fmt.Errorf("please specify an ingress name or use --all flag")
}</span>
<span class="cov0" title="0">return nil</span>
}
// printIngressSummary prints a summary of multiple ingress diagnoses
func printIngressSummary(reports []*output.DiagnosticReport) <span class="cov0" title="0">{
total := len(reports)
var totalChecks, passed, failed, warnings, skipped int
for _, report := range reports </span><span class="cov0" title="0">{
totalChecks += report.Summary.Total
passed += report.Summary.Passed
failed += report.Summary.Failed
warnings += report.Summary.Warnings
skipped += report.Summary.Skipped
}</span>
<span class="cov0" title="0">fmt.Printf("\n📊 Ingress Diagnostics Summary:\n")
fmt.Printf(" Total Ingresses: %d\n", total)
fmt.Printf(" Total Checks: %d\n", totalChecks)
fmt.Printf(" ✅ Passed: %d\n", passed)
fmt.Printf(" ❌ Failed: %d\n", failed)
fmt.Printf(" ⚠️ Warnings: %d\n", warnings)
fmt.Printf(" ⏭️ Skipped: %d\n", skipped)
// Calculate health percentage
if totalChecks > 0 </span><span class="cov0" title="0">{
healthPercent := float64(passed) / float64(totalChecks) * 100
fmt.Printf(" Health Score: %.1f%%\n", healthPercent)
}</span>
}
</pre>
<pre class="file" id="file2" style="display: none">package cmd
import (
"context"
"fmt"
"time"
"github.com/spf13/cobra"
"kdebug/internal/client"
"kdebug/internal/output"
"kdebug/pkg/pod"
)
var podCmd = &cobra.Command{
Use: "pod [pod-name] [flags]",
Short: "Diagnose pod-level issues and provide remediation suggestions",
Long: `Diagnose common pod-level issues in Kubernetes clusters including:
• Pending pods (scheduling constraints, resource limits, node taints)
• Image pull errors and registry connectivity problems
• CrashLoopBackOff detection with log analysis and hints
• RBAC permission validation for pods and service accounts
• Init container failures and misconfigurations
• Resource constraints and quality of service issues
This command analyzes pod status, events, logs, and related resources to identify
root causes and provide actionable remediation suggestions.`,
Example: ` # Diagnose a specific pod
kdebug pod myapp-deployment-7d4b8c6f9-x8k2l
# Diagnose pod in specific namespace
kdebug pod myapp-pod --namespace production
# Diagnose all pods in a namespace
kdebug pod --all --namespace default
# Export detailed analysis to JSON
kdebug pod myapp-pod --output json --verbose
# Focus on specific diagnostic areas
kdebug pod myapp-pod --checks=scheduling,images,rbac
# Include detailed log analysis for crashed pods
kdebug pod myapp-pod --include-logs --log-lines 50`,
RunE: runPodDiagnostics,
}
func init() <span class="cov0" title="0">{
rootCmd.AddCommand(podCmd)
// Pod-specific flags
podCmd.Flags().BoolP("all", "a", false, "Diagnose all pods in the specified namespace")
podCmd.Flags().StringSlice("checks", []string{}, "Comma-separated list of checks to run (scheduling,images,rbac,logs,init-containers)")
podCmd.Flags().Bool("include-logs", false, "Include container log analysis for failed pods")
podCmd.Flags().Int("log-lines", 20, "Number of recent log lines to analyze (when --include-logs is enabled)")
podCmd.Flags().Duration("timeout", 30*time.Second, "Timeout for pod diagnostics")
podCmd.Flags().Bool("watch", false, "Watch pod status and re-run diagnostics on changes")
podCmd.Flags().StringSlice("containers", []string{}, "Specific containers to analyze (default: all containers)")
}</span>
func runPodDiagnostics(cmd *cobra.Command, args []string) error <span class="cov0" title="0">{
// Parse flags
allPods, _ := cmd.Flags().GetBool("all")
checks, _ := cmd.Flags().GetStringSlice("checks")
includeLogs, _ := cmd.Flags().GetBool("include-logs")
logLines, _ := cmd.Flags().GetInt("log-lines")
timeout, _ := cmd.Flags().GetDuration("timeout")
watch, _ := cmd.Flags().GetBool("watch")
containers, _ := cmd.Flags().GetStringSlice("containers")
// Get global flags
outputFormat, _ := cmd.Flags().GetString("outputFormat")
verbose, _ := cmd.Flags().GetBool("verbose")
kubeconfig, _ := cmd.Flags().GetString("kubeconfig")
namespace, _ := cmd.Flags().GetString("namespace")
// Validate arguments
if !allPods && len(args) == 0 </span><span class="cov0" title="0">{
return fmt.Errorf("pod name is required when --all is not specified")
}</span>
<span class="cov0" title="0">if allPods && len(args) > 0 </span><span class="cov0" title="0">{
return fmt.Errorf("cannot specify pod name when using --all flag")
}</span>
// Initialize dependencies
<span class="cov0" title="0">outputManager := output.NewOutputManager(outputFormat, verbose)
k8sClient, err := client.NewKubernetesClient(kubeconfig)
if err != nil </span><span class="cov0" title="0">{
outputManager.PrintError("Failed to initialize Kubernetes client", err)
return fmt.Errorf("failed to create Kubernetes client: %w", err)
}</span>
// Test connectivity
<span class="cov0" title="0">ctx := context.Background()
if err := k8sClient.TestConnection(ctx); err != nil </span><span class="cov0" title="0">{
outputManager.PrintError("Kubernetes connectivity check failed", err)
return err
}</span>
<span class="cov0" title="0">outputManager.PrintInfo("Initializing pod diagnostics...")
// Create diagnostic configuration
config := pod.DiagnosticConfig{
Namespace: namespace,
Checks: checks,
IncludeLogs: includeLogs,
LogLines: logLines,
Timeout: timeout,
Containers: containers,
}
// Initialize pod diagnostic
diagnostic := pod.NewPodDiagnostic(k8sClient, outputManager)
var report *output.DiagnosticReport
var podName string
if allPods </span><span class="cov0" title="0">{
outputManager.PrintInfo(fmt.Sprintf("Analyzing all pods in namespace '%s'...", namespace))
report, err = diagnostic.DiagnoseAllPods(config)
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to diagnose pods: %w", err)
}</span>
} else<span class="cov0" title="0"> {
podName = args[0]
outputManager.PrintInfo(fmt.Sprintf("Analyzing pod '%s' in namespace '%s'...", podName, namespace))
if watch </span><span class="cov0" title="0">{
return diagnostic.WatchPod(podName, config)
}</span>
<span class="cov0" title="0">report, err = diagnostic.DiagnosePod(podName, config)
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to diagnose pod '%s': %w", podName, err)
}</span>
}
// Output results
<span class="cov0" title="0">if err := outputManager.PrintReport(report); err != nil </span><span class="cov0" title="0">{
outputManager.PrintWarning(fmt.Sprintf("Failed to print report: %v", err))
}</span>
// Don't return error for diagnostic findings - just print summary
// This allows the command to exit cleanly while still reporting issues
<span class="cov0" title="0">return nil</span>
}
</pre>
<pre class="file" id="file3" style="display: none">/*
Copyright © 2025 NAME HERE <EMAIL ADDRESS>
*/
package cmd
import (
"os"
"github.com/spf13/cobra"
)
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "kdebug",
Short: "A CLI tool that automatically diagnoses common Kubernetes issues",
Long: `kdebug is a diagnostic tool for Kubernetes clusters that automatically
identifies common issues and provides actionable suggestions.
Think of it as a "doctor" for Kubernetes clusters (like 'brew doctor', but for K8s).
Instead of manually digging through kubectl describe outputs and events, kdebug
runs a series of checks and gives clear guidance on what's wrong and how to fix it.
Examples:
kdebug cluster # Run cluster-wide health checks
kdebug pod myapp-123 -n production # Debug a specific pod
kdebug service myservice # Check service and endpoints
kdebug ingress my-ingress # Diagnose ingress routing issues
kdebug dns # Test DNS resolution`,
Version: "1.0.1",
}
// 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() <span class="cov0" title="0">{
err := rootCmd.Execute()
if err != nil </span><span class="cov0" title="0">{
os.Exit(1)
}</span>
}
var (
// Global flags
kubeconfig string
namespace string
outputFormat string
verbose bool
)
func init() <span class="cov0" title="0">{
// Global persistent flags that apply to all commands
rootCmd.PersistentFlags().StringVar(&kubeconfig, "kubeconfig", "", "path to kubeconfig file (defaults to $HOME/.kube/config)")
rootCmd.PersistentFlags().StringVarP(&namespace, "namespace", "n", "default", "Kubernetes namespace")
rootCmd.PersistentFlags().StringVarP(&outputFormat, "output", "o", "table", "output format: table, json, yaml")
rootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "verbose output for debugging")
}</span>
</pre>
<pre class="file" id="file4" style="display: none">package cmd
import (
"context"
"fmt"
"time"
"github.com/spf13/cobra"
"kdebug/internal/client"
"kdebug/internal/output"
"kdebug/pkg/service"
)
var serviceCmd = &cobra.Command{
Use: "service [service-name] [flags]",
Short: "Diagnose service-level issues and validate connectivity",
Long: `Diagnose common service-level issues in Kubernetes clusters including:
• Service configuration validation (ports, selectors, service types)
• Endpoint health and backend pod availability
• Service selector matching with available pods
• DNS resolution for service names within the cluster
• Load balancing and traffic distribution issues
• Connectivity validation between services and pods
This command analyzes service configuration, endpoints, DNS resolution, and related
resources to identify root causes and provide actionable remediation suggestions.`,
Example: ` # Diagnose a specific service
kdebug service frontend --namespace production
# Check all services in namespace
kdebug service --all --namespace default
# Include DNS resolution testing
kdebug service api-gateway --test-dns
# Check services across all namespaces
kdebug service --all-namespaces`,
RunE: runServiceDiagnostics,
}
func init() <span class="cov0" title="0">{
rootCmd.AddCommand(serviceCmd)
// Service-specific flags
serviceCmd.Flags().BoolP("all", "a", false, "Diagnose all services in the specified namespace")
serviceCmd.Flags().StringSlice("checks", []string{}, "Comma-separated list of checks to run (config,selector,endpoints,ports)")
serviceCmd.Flags().Bool("test-dns", false, "Include DNS resolution testing for the service")
serviceCmd.Flags().Bool("all-namespaces", false, "Check services across all namespaces")
serviceCmd.Flags().Duration("timeout", 30*time.Second, "Timeout for service diagnostics")
}</span>
func runServiceDiagnostics(cmd *cobra.Command, args []string) error <span class="cov0" title="0">{
// Parse flags
allServices, _ := cmd.Flags().GetBool("all")
checks, _ := cmd.Flags().GetStringSlice("checks")
testDNS, _ := cmd.Flags().GetBool("test-dns")
allNamespaces, _ := cmd.Flags().GetBool("all-namespaces")
timeout, _ := cmd.Flags().GetDuration("timeout")
// Get global flags
outputFormat, _ := cmd.Flags().GetString("outputFormat")
verbose, _ := cmd.Flags().GetBool("verbose")
kubeconfig, _ := cmd.Flags().GetString("kubeconfig")
namespace, _ := cmd.Flags().GetString("namespace")
// Validate arguments
if !allServices && !allNamespaces && len(args) == 0 </span><span class="cov0" title="0">{
return fmt.Errorf("service name is required when --all and --all-namespaces are not specified")
}</span>
<span class="cov0" title="0">if len(args) > 1 </span><span class="cov0" title="0">{
return fmt.Errorf("only one service name is supported")
}</span>
// Create context with timeout
<span class="cov0" title="0">ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
// Initialize Kubernetes client
kubeClient, err := client.NewKubernetesClient(kubeconfig)
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to create Kubernetes client: %w", err)
}</span>
// Initialize output manager
<span class="cov0" title="0">outputMgr := output.NewOutputManager(outputFormat, verbose)
// Initialize service diagnostic
serviceDiag := service.NewServiceDiagnostic(kubeClient, outputMgr)
// Create diagnostic configuration
config := service.DiagnosticConfig{
Namespace: namespace,
Checks: checks,
TestDNS: testDNS,
AllNamespaces: allNamespaces,
Timeout: timeout,
Verbose: verbose,
}
// Run diagnostics
if allServices || allNamespaces </span><span class="cov0" title="0">{
// Diagnose all services
reports, err := serviceDiag.DiagnoseAllServices(ctx, config)
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to diagnose services: %w", err)
}</span>
// Print results
<span class="cov0" title="0">for _, report := range reports </span><span class="cov0" title="0">{
if err := outputMgr.PrintReport(report); err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to print report: %w", err)
}</span>
<span class="cov0" title="0">fmt.Println()</span> // Add spacing between reports
}
// Print summary
<span class="cov0" title="0">if len(reports) > 0 </span><span class="cov0" title="0">{
printServicesSummary(outputMgr, reports)
}</span>
} else<span class="cov0" title="0"> {
// Diagnose specific service
serviceName := args[0]
report, err := serviceDiag.DiagnoseService(ctx, serviceName, config)
if err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to diagnose service %s: %w", serviceName, err)
}</span>
// Print results
<span class="cov0" title="0">if err := outputMgr.PrintReport(report); err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("failed to print report: %w", err)
}</span>
}
<span class="cov0" title="0">return nil</span>
}
// printServicesSummary prints a summary of all service diagnostic results.
func printServicesSummary(outputMgr *output.OutputManager, reports []*output.DiagnosticReport) <span class="cov0" title="0">{
if outputMgr.Format != output.FormatTable </span><span class="cov0" title="0">{
return // Only print summary for table format
}</span>
<span class="cov0" title="0">totalServices := len(reports)
healthyServices := 0
unhealthyServices := 0
warningServices := 0
for _, report := range reports </span><span class="cov0" title="0">{
if report.Summary.Failed > 0 </span><span class="cov0" title="0">{
unhealthyServices++
}</span> else<span class="cov0" title="0"> if report.Summary.Warnings > 0 </span><span class="cov0" title="0">{
warningServices++
}</span> else<span class="cov0" title="0"> {
healthyServices++
}</span>
}
<span class="cov0" title="0">fmt.Printf("\n📊 Service Health Summary:\n")
fmt.Printf(" Total Services: %d\n", totalServices)
fmt.Printf(" ✅ Healthy: %d\n", healthyServices)
fmt.Printf(" ⚠️ Warnings: %d\n", warningServices)
fmt.Printf(" ❌ Unhealthy: %d\n", unhealthyServices)
if unhealthyServices > 0 </span><span class="cov0" title="0">{
fmt.Printf("\n🎯 Priority Actions:\n")
fmt.Printf(" 1. Investigate services with failed checks\n")
fmt.Printf(" 2. Verify pod health and readiness for services with endpoint issues\n")
fmt.Printf(" 3. Check service selectors match pod labels\n")
}</span>
}
</pre>
<pre class="file" id="file5" style="display: none">package client
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/util/homedir"
)
// KubernetesClient wraps the Kubernetes clientset with additional metadata
type KubernetesClient struct {
Clientset *kubernetes.Clientset
Config *rest.Config
Context string
}
// NewKubernetesClient creates a new Kubernetes client
func NewKubernetesClient(kubeconfig string) (*KubernetesClient, error) <span class="cov8" title="1">{
var config *rest.Config
var err error
if kubeconfig == "" </span><span class="cov8" title="1">{
// Try in-cluster config first
config, err = rest.InClusterConfig()
if err != nil </span><span class="cov8" title="1">{
// Fall back to kubeconfig file using proper loading rules
// This handles KUBECONFIG env var and default paths correctly
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
configOverrides := &clientcmd.ConfigOverrides{}
clientConfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, configOverrides)
config, err = clientConfig.ClientConfig()
if err != nil </span><span class="cov8" title="1">{
return nil, fmt.Errorf("failed to load kubeconfig: %w", err)
}</span>
}
} else<span class="cov8" title="1"> {
// Load config from specific kubeconfig file
config, err = clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil </span><span class="cov8" title="1">{
return nil, fmt.Errorf("failed to load kubeconfig: %w", err)
}</span>
}
// Create clientset
<span class="cov0" title="0">clientset, err := kubernetes.NewForConfig(config)
if err != nil </span><span class="cov0" title="0">{
return nil, fmt.Errorf("failed to create Kubernetes client: %w", err)
}</span>
// Get current context
<span class="cov0" title="0">context := getCurrentContextFromConfig(config, kubeconfig)
return &KubernetesClient{
Clientset: clientset,
Config: config,
Context: context,
}, nil</span>
}
// TestConnection tests the connection to the Kubernetes cluster
func (k *KubernetesClient) TestConnection(ctx context.Context) error <span class="cov0" title="0">{
_, err := k.Clientset.Discovery().ServerVersion()
if err != nil </span><span class="cov0" title="0">{
// Provide more helpful error messages for common issues
errMsg := err.Error()
if strings.Contains(errMsg, "the server has asked for the client to provide credentials") </span><span class="cov0" title="0">{
return fmt.Errorf("authentication failed - please check your credentials:\n"+
" • For EKS: run 'aws eks update-kubeconfig --region <region> --name <cluster-name>'\n"+
" • Ensure AWS credentials are valid: 'aws sts get-caller-identity'\n"+
" • Check kubeconfig: 'kubectl cluster-info'\n"+
"Original error: %w", err)
}</span>
<span class="cov0" title="0">if strings.Contains(errMsg, "no such host") || strings.Contains(errMsg, "connection refused") </span><span class="cov0" title="0">{
return fmt.Errorf("cluster unreachable - please check network connectivity:\n"+
" • Verify cluster is running\n"+
" • Check kubeconfig server URL\n"+
" • Ensure network access to cluster\n"+
"Original error: %w", err)
}</span>
<span class="cov0" title="0">return fmt.Errorf("failed to connect to Kubernetes cluster: %w", err)</span>
}
<span class="cov0" title="0">return nil</span>
}
// GetClusterInfo returns basic cluster information
func (k *KubernetesClient) GetClusterInfo(ctx context.Context) (map[string]string, error) <span class="cov0" title="0">{
version, err := k.Clientset.Discovery().ServerVersion()
if err != nil </span><span class="cov0" title="0">{
return nil, fmt.Errorf("failed to get server version: %w", err)
}</span>
<span class="cov0" title="0">info := map[string]string{
"context": k.Context,
"server": k.Config.Host,
"version": version.String(),
"gitVersion": version.GitVersion,
"platform": version.Platform,
}
return info, nil</span>
}
// getDefaultKubeconfigPath returns the default kubeconfig path
func getDefaultKubeconfigPath() string <span class="cov8" title="1">{
if home := homedir.HomeDir(); home != "" </span><span class="cov8" title="1">{
return filepath.Join(home, ".kube", "config")
}</span>
<span class="cov0" title="0">return ""</span>
}
// getCurrentContextFromConfig returns the current context from the loaded config
func getCurrentContextFromConfig(_ *rest.Config, kubeconfig string) string <span class="cov0" title="0">{
// If we have a specific kubeconfig file, try to get context from it
if kubeconfig != "" </span><span class="cov0" title="0">{
if rawConfig, err := clientcmd.LoadFromFile(kubeconfig); err == nil </span><span class="cov0" title="0">{
return rawConfig.CurrentContext
}</span>
}
// Fall back to getting context using default loading rules
<span class="cov0" title="0">loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
configOverrides := &clientcmd.ConfigOverrides{}
clientConfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, configOverrides)
if rawConfig, err := clientConfig.RawConfig(); err == nil </span><span class="cov0" title="0">{
return rawConfig.CurrentContext
}</span>
<span class="cov0" title="0">return "unknown"</span>
}
// getCurrentContext returns the current context from kubeconfig
func getCurrentContext(kubeconfig string) (string, error) <span class="cov8" title="1">{
if kubeconfig == "" </span><span class="cov8" title="1">{
kubeconfig = getDefaultKubeconfigPath()
}</span>
<span class="cov8" title="1">if _, err := os.Stat(kubeconfig); os.IsNotExist(err) </span><span class="cov8" title="1">{