-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopenshift-analyzer.go
More file actions
1479 lines (1269 loc) · 37.6 KB
/
Copy pathopenshift-analyzer.go
File metadata and controls
1479 lines (1269 loc) · 37.6 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
package main
import (
"encoding/json"
"flag"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"text/tabwriter"
)
const (
colorRed = "\033[0;31m"
colorGreen = "\033[0;32m"
colorYellow = "\033[0;33m"
colorBlue = "\033[0;34m"
colorCyan = "\033[0;36m"
colorReset = "\033[0m"
bold = "\033[1m"
regular = "\033[0m"
statusOK = "[OK]"
statusError = "[ERROR]"
statusWarn = "[WARNING]"
statusInfo = "[INFO]"
)
type Config struct {
mustGatherPath string
mode string
verbose bool
noColor bool
}
type ETCDEndpointHealth struct {
Endpoint string `json:"endpoint"`
Health bool `json:"health"`
Took string `json:"took"`
}
type ETCDEndpointStatus struct {
Endpoint string `json:"Endpoint"`
Status struct {
Header struct {
MemberID int64 `json:"member_id"`
RaftTerm int64 `json:"raft_term"`
} `json:"header"`
Leader int64 `json:"leader"`
Version string `json:"version"`
DBSize int64 `json:"dbSize"`
RaftIndex int64 `json:"raftIndex"`
RaftAppliedIndex int64 `json:"raftAppliedIndex"`
} `json:"Status"`
}
type ETCDMember struct {
Name string `json:"name"`
PeerURLs []string `json:"peerURLs"`
ClientURLs []string `json:"clientURLs"`
}
type ETCDMemberList struct {
Members []ETCDMember `json:"members"`
}
type AnalysisResult struct {
Section string
Status string
Message string
Issues []string
Warnings []string
}
var (
cfg Config
results []AnalysisResult
)
func main() {
if err := run(); err != nil {
printError("Fatal error: %v", err)
os.Exit(1)
}
}
func run() error {
parseFlags()
if err := validate(); err != nil {
return err
}
printBanner()
switch cfg.mode {
case "health":
runHealthAnalysis()
case "issues":
runIssueAnalysis()
case "full":
runFullAnalysis()
default:
runFullAnalysis()
}
printSummary()
return nil
}
func parseFlags() {
flag.StringVar(&cfg.mode, "mode", "full", "Analysis mode: health, issues, or full")
flag.BoolVar(&cfg.verbose, "verbose", false, "Enable verbose output")
flag.BoolVar(&cfg.noColor, "no-color", false, "Disable colored output")
flag.Parse()
if flag.NArg() < 1 {
printUsage()
os.Exit(1)
}
cfg.mustGatherPath = flag.Arg(0)
}
func printUsage() {
fmt.Println()
fmt.Println("OpenShift Must-Gather Analyzer")
fmt.Println()
fmt.Println("USAGE:")
fmt.Printf(" %s [OPTIONS] <must-gather-directory>\n\n", os.Args[0])
fmt.Println("OPTIONS:")
fmt.Println(" -mode string")
fmt.Println(" Analysis mode: health, issues, or full (default: full)")
fmt.Println(" - health: General cluster health and configuration")
fmt.Println(" - issues: Focus on identifying problems and degraded components")
fmt.Println(" - full: Complete analysis (both health + issues)")
fmt.Println(" -verbose")
fmt.Println(" Enable verbose output with detailed troubleshooting")
fmt.Println(" -no-color")
fmt.Println(" Disable colored output")
fmt.Println()
fmt.Println("EXAMPLES:")
fmt.Printf(" %s /path/to/must-gather\n", os.Args[0])
fmt.Printf(" %s -mode issues /path/to/must-gather\n", os.Args[0])
fmt.Printf(" %s -mode health -verbose /path/to/must-gather\n", os.Args[0])
fmt.Println()
}
func validate() error {
printInfo("Validating prerequisites...")
if flag.NArg() == 0 {
return fmt.Errorf("no must-gather directory supplied\nUSAGE: %s [OPTIONS] <must-gather-directory>", os.Args[0])
}
if flag.NArg() > 1 {
return fmt.Errorf("only one must-gather directory should be provided\nUSAGE: %s [OPTIONS] <must-gather-directory>", os.Args[0])
}
if !commandExists("omg") {
return fmt.Errorf("%s omg command not found\n\nTroubleshooting:\n"+
" 1. Install o-must-gather: pip install o-must-gather\n"+
" 2. Verify installation: omg --version\n"+
" 3. Visit: https://pypi.org/project/o-must-gather\n"+
" 4. For Python issues: ensure pip is installed (python3 -m pip --version)",
statusError)
}
printSuccess("omg command found")
if !commandExists("jq") {
return fmt.Errorf("%s jq command not found\n\nTroubleshooting:\n"+
" Red Hat/Fedora: sudo dnf install jq\n"+
" Debian/Ubuntu: sudo apt install jq\n"+
" MacOS: brew install jq\n"+
" Manual install: https://stedolan.github.io/jq/download",
statusError)
}
printSuccess("jq command found")
if !commandExists("column") {
return fmt.Errorf("%s column command not found\n\nTroubleshooting:\n"+
" Red Hat/Fedora: sudo dnf install util-linux\n"+
" Debian/Ubuntu: sudo apt install bsdmainutils\n"+
" Note: Usually pre-installed on most Linux distributions",
statusError)
}
printSuccess("column command found")
if _, err := os.Stat(cfg.mustGatherPath); os.IsNotExist(err) {
return fmt.Errorf("%s must-gather directory does not exist: %s\n\nTroubleshooting:\n"+
" 1. Verify the path is correct\n"+
" 2. Ensure you have read permissions\n"+
" 3. Check if the must-gather was extracted properly",
statusError, cfg.mustGatherPath)
}
printSuccess(fmt.Sprintf("must-gather directory found: %s", cfg.mustGatherPath))
configFile := filepath.Join(os.Getenv("HOME"), ".omgconfig")
os.Remove(configFile)
cmd := exec.Command("omg", "use", cfg.mustGatherPath)
if output, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("%s failed to set omg context: %v\n\nOutput: %s\n\nTroubleshooting:\n"+
" 1. Verify must-gather structure is intact\n"+
" 2. Check if must-gather was collected properly\n"+
" 3. Try: omg use %s manually\n"+
" 4. Ensure must-gather is uncompressed",
statusError, err, string(output), cfg.mustGatherPath)
}
printSuccess("omg context initialized")
fmt.Println()
return nil
}
func commandExists(cmd string) bool {
_, err := exec.LookPath(cmd)
return err == nil
}
func printBanner() {
fmt.Println()
fmt.Println("================================================================")
fmt.Println("OpenShift Must-Gather Comprehensive Analyzer v2.0")
fmt.Println("Cluster Health & Issue Detection Tool")
fmt.Println("================================================================")
fmt.Printf("\nAnalysis Mode: %s\n", cfg.mode)
fmt.Printf("Verbose Output: %v\n", cfg.verbose)
fmt.Printf("Must-Gather Path: %s\n\n", cfg.mustGatherPath)
}
func runFullAnalysis() {
printHeader("COMPREHENSIVE ANALYSIS: HEALTH + ISSUES")
runHealthAnalysis()
fmt.Println("\n" + strings.Repeat("=", 80) + "\n")
runIssueAnalysis()
}
func runHealthAnalysis() {
printHeader("CLUSTER HEALTH ANALYSIS")
sections := []struct {
title string
fn func()
}{
{"Cluster Infrastructure Details", func() { infrastructure() }},
{"ETCD Endpoint Health", func() { etcdEndpointHealth() }},
{"ETCD Endpoint Status", func() { etcdEndpointStatus() }},
{"ETCD Member List", func() { etcdMemberList() }},
{"ClusterVersion Details", func() { clusterversion() }},
{"Install-Config Configuration", func() { installConfigYAML() }},
{"Cluster-Wide Proxy Configuration", func() { clusterWideProxy() }},
{"Cluster Operators Status", func() { clusterOperator() }},
{"Nodes Status", func() { nodes() }},
{"Node Machine Configuration", func() { machineconfiguration() }},
{"Machine Config Pool Status", func() { mcp() }},
{"Machines Status", func() { machine() }},
{"MachineSets Status", func() { machineset() }},
{"Failing Pods", func() { pods() }},
{"Pods with High Restart Count (>10)", func() { podRestart() }},
{"Kube-APIServer Logs", func() { kubeApiserver() }},
{"ETCD Pod Logs", func() { etcdPodLogs() }},
{"Kube-Controller-Manager Logs", func() { kubeControllerManager() }},
}
for _, section := range sections {
printSection(section.title)
section.fn()
}
}
func runIssueAnalysis() {
printHeader("ISSUE IDENTIFICATION & TROUBLESHOOTING")
sections := []struct {
title string
fn func()
}{
{"ClusterVersion Status", func() { clusterversionIssues() }},
{"Degraded Cluster Operators", func() { degradedOperators() }},
{"Degraded Operators Detailed Analysis", func() { degradedOperatorsDescription() }},
{"Degraded Machine Config Pools", func() { degradedMCP() }},
{"Degraded MCPs Detailed Analysis", func() { degradedMCPDescription() }},
{"Machines Not in Running State", func() { machinePhase() }},
{"Degraded Machines Detailed Analysis", func() { degradedMachinesDescription() }},
{"Degraded Nodes", func() { degradedNodes() }},
{"Degraded Nodes Detailed Analysis", func() { degradedNodesDescription() }},
{"Pods Not in Running/Succeeded State", func() { podsNotRunning() }},
{"Machine-Config-Daemon Logs (Degraded Nodes)", func() { mcdPodLogs() }},
}
for _, section := range sections {
printSection(section.title)
section.fn()
}
}
// ============================================================================
// HEALTH ANALYSIS FUNCTIONS
// ============================================================================
func infrastructure() {
pattern := filepath.Join(cfg.mustGatherPath, "*/cluster-scoped-resources/config.openshift.io/infrastructures.yaml")
files, _ := filepath.Glob(pattern)
if len(files) == 0 {
printWarning("infrastructures.yaml not found")
printTroubleshoot([]string{
"Must-gather may be incomplete or corrupted",
"Re-collect must-gather: oc adm must-gather",
"Verify cluster-scoped-resources directory exists",
})
return
}
content, err := os.ReadFile(files[0])
if err != nil {
printError("Error reading file: %v", err)
return
}
lines := strings.Split(string(content), "\n")
inRange := false
for _, line := range lines {
if strings.Contains(line, "uid:") {
inRange = true
continue
}
if strings.Contains(line, "kind:") {
break
}
if inRange {
fmt.Println(line)
}
}
if cfg.verbose {
printInfo("\nInfrastructure information shows platform type, API endpoints, and cluster topology")
}
}
func etcdEndpointHealth() {
pattern := filepath.Join(cfg.mustGatherPath, "*/etcd_info/endpoint_health.json")
files, _ := filepath.Glob(pattern)
if len(files) == 0 {
printWarning("endpoint_health.json not found")
printTroubleshoot([]string{
"ETCD diagnostics may not have been collected",
"This is critical for cluster health assessment",
"Ensure must-gather includes ETCD information",
})
return
}
content, err := os.ReadFile(files[0])
if err != nil {
printError("Error reading file: %v", err)
return
}
var health []ETCDEndpointHealth
if err := json.Unmarshal(content, &health); err != nil {
printError("Error parsing JSON: %v", err)
return
}
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
fmt.Fprintln(w, "ENDPOINT\tHEALTH\tRESPONSE TIME")
fmt.Fprintln(w, strings.Repeat("-", 60))
allHealthy := true
for _, h := range health {
status := "healthy"
if !h.Health {
status = "unhealthy"
allHealthy = false
}
fmt.Fprintf(w, "%s\t%s\t%s\n", h.Endpoint, status, h.Took)
}
w.Flush()
if !allHealthy {
printWarning("Some ETCD endpoints are unhealthy")
printTroubleshoot([]string{
"Check ETCD pod logs for errors",
"Verify network connectivity between ETCD members",
"Check master node resources (CPU, memory, disk)",
"Review ETCD certificates and authentication",
"Consult: https://docs.openshift.com/container-platform/latest/backup_and_restore/control_plane_backup_and_restore/disaster_recovery/about-disaster-recovery.html",
})
} else if cfg.verbose {
printSuccess("All ETCD endpoints are healthy")
}
}
func etcdEndpointStatus() {
pattern := filepath.Join(cfg.mustGatherPath, "*/etcd_info/endpoint_status.json")
files, _ := filepath.Glob(pattern)
if len(files) == 0 {
printWarning("endpoint_status.json not found")
return
}
content, err := os.ReadFile(files[0])
if err != nil {
printError("Error reading file: %v", err)
return
}
var statuses []ETCDEndpointStatus
if err := json.Unmarshal(content, &statuses); err != nil {
printError("Error parsing JSON: %v", err)
return
}
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
fmt.Fprintln(w, "ENDPOINT\tMEMBER-ID\tLEADER-ID\tVERSION\tDB-SIZE(MB)\tRAFT-TERM\tRAFT-INDEX\tRAFT-APPLIED")
fmt.Fprintln(w, strings.Repeat("-", 120))
var leaderID int64
dbSizes := make(map[int64]int64)
for _, s := range statuses {
dbSizeMB := float64(s.Status.DBSize) / 1024 / 1024
leaderID = s.Status.Leader
dbSizes[s.Status.Header.MemberID] = s.Status.DBSize
fmt.Fprintf(w, "%s\t%d\t%d\t%s\t%.2f\t%d\t%d\t%d\n",
s.Endpoint,
s.Status.Header.MemberID,
s.Status.Leader,
s.Status.Version,
dbSizeMB,
s.Status.Header.RaftTerm,
s.Status.RaftIndex,
s.Status.RaftAppliedIndex,
)
}
w.Flush()
if cfg.verbose {
printInfo("ETCD Status Analysis")
fmt.Printf(" Leader ID: %d\n", leaderID)
fmt.Printf(" Total members: %d\n", len(statuses))
maxDBSize := int64(0)
for _, size := range dbSizes {
if size > maxDBSize {
maxDBSize = size
}
}
maxDBSizeMB := float64(maxDBSize) / 1024 / 1024
if maxDBSizeMB > 8000 {
printWarning(fmt.Sprintf("Large ETCD database detected (%.2f MB)", maxDBSizeMB))
printTroubleshoot([]string{
"Consider ETCD defragmentation if DB size > 8GB",
"Review object counts and resource quotas",
"Check for excessive events or log entries",
})
}
}
}
func etcdMemberList() {
pattern := filepath.Join(cfg.mustGatherPath, "*/etcd_info/member_list.json")
files, _ := filepath.Glob(pattern)
if len(files) == 0 {
printWarning("member_list.json not found")
return
}
content, err := os.ReadFile(files[0])
if err != nil {
printError("Error reading file: %v", err)
return
}
var memberList ETCDMemberList
if err := json.Unmarshal(content, &memberList); err != nil {
printError("Error parsing JSON: %v", err)
return
}
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
fmt.Fprintln(w, "NAME\tPEER-ADDRS\tCLIENT-ADDRS")
fmt.Fprintln(w, strings.Repeat("-", 100))
for _, m := range memberList.Members {
peerAddrs := strings.Join(m.PeerURLs, ", ")
clientAddrs := strings.Join(m.ClientURLs, ", ")
fmt.Fprintf(w, "%s\t%s\t%s\n", m.Name, peerAddrs, clientAddrs)
}
w.Flush()
if cfg.verbose && len(memberList.Members) != 3 {
printWarning(fmt.Sprintf("Non-standard ETCD member count: %d", len(memberList.Members)))
printInfo("Recommended: 3 or 5 members for HA clusters")
}
}
func clusterversion() {
runOMGCommand("get", "clusterversion")
pattern := filepath.Join(cfg.mustGatherPath, "*/cluster-scoped-resources/config.openshift.io/clusterversions.yaml")
files, _ := filepath.Glob(pattern)
if len(files) == 0 {
printWarning("clusterversions.yaml not found")
return
}
content, err := os.ReadFile(files[0])
if err != nil {
printError("Error reading file: %v", err)
return
}
lines := strings.Split(string(content), "\n")
printSubSection("ClusterVersion Spec")
printSectionBetween(lines, "uid:", "version:", false, true)
printSubSection("ClusterVersion Conditions")
printSectionBetween(lines, "lastTransitionTime:", "desired:", false, false)
printSubSection("ClusterVersion History")
printSectionBetween(lines, "completionTime:", "observedGeneration:", false, false)
}
func installConfigYAML() {
pattern := filepath.Join(cfg.mustGatherPath, "*/namespaces/kube-system/core/configmaps.yaml")
files, _ := filepath.Glob(pattern)
if len(files) == 0 {
printWarning("install-config.yaml not found")
printTroubleshoot([]string{
"Install config may have been removed post-installation",
"This is normal for some clusters",
"Check cluster documentation for deployment details",
})
return
}
content, err := os.ReadFile(files[0])
if err != nil {
printError("Error reading file: %v", err)
return
}
lines := strings.Split(string(content), "\n")
inSection := false
foundConfig := false
for _, line := range lines {
if strings.Contains(line, "install-config") {
inSection = true
foundConfig = true
}
if inSection {
if strings.Contains(line, "kind:") && !strings.Contains(line, "install-config") {
break
}
fmt.Println(line)
}
}
if !foundConfig && cfg.verbose {
printInfo("Install configuration shows deployment topology, networking, and platform details")
}
}
func clusterWideProxy() {
pattern := filepath.Join(cfg.mustGatherPath, "*/cluster-scoped-resources/config.openshift.io/proxies/cluster.yaml")
files, _ := filepath.Glob(pattern)
if len(files) == 0 {
printWarning("cluster-wide proxy details not found")
if cfg.verbose {
printInfo("No proxy configuration - cluster may not require proxy")
}
return
}
content, err := os.ReadFile(files[0])
if err != nil {
printError("Error reading file: %v", err)
return
}
lines := strings.Split(string(content), "\n")
inRange := false
hasProxy := false
for _, line := range lines {
if strings.Contains(line, "uid:") {
inRange = true
continue
}
if strings.Contains(line, "kind:") {
break
}
if inRange {
fmt.Println(line)
if strings.Contains(line, "httpProxy:") || strings.Contains(line, "httpsProxy:") {
hasProxy = true
}
}
}
if hasProxy && cfg.verbose {
printInfo("Proxy configuration detected - ensure no-proxy settings include cluster networks")
}
}
func clusterOperator() {
runOMGCommand("get", "co")
}
func nodes() {
runOMGCommand("get", "nodes", "-o", "wide")
}
func machineconfiguration() {
pattern := filepath.Join(cfg.mustGatherPath, "*/cluster-scoped-resources/core/nodes/*.yaml")
files, _ := filepath.Glob(pattern)
if len(files) == 0 {
printWarning("No node configurations found")
return
}
mismatchFound := false
for _, file := range files {
content, err := os.ReadFile(file)
if err != nil {
continue
}
lines := strings.Split(string(content), "\n")
var hostname, current, desired string
for _, line := range lines {
if strings.Contains(line, "kubernetes.io/hostname") {
parts := strings.Split(line, ":")
if len(parts) >= 2 {
hostname = strings.TrimSpace(parts[1])
}
}
if strings.Contains(line, "machineconfiguration.openshift.io/currentConfig") {
parts := strings.Split(line, ":")
if len(parts) >= 2 {
current = strings.TrimSpace(parts[1])
}
}
if strings.Contains(line, "machineconfiguration.openshift.io/desiredConfig") {
parts := strings.Split(line, ":")
if len(parts) >= 2 {
desired = strings.TrimSpace(parts[1])
}
}
}
if hostname != "" {
status := "synchronized"
if current != desired {
status = "drift detected"
mismatchFound = true
}
fmt.Printf("Node: %s - Status: %s\n", hostname, status)
fmt.Printf(" Current Config: %s\n", current)
fmt.Printf(" Desired Config: %s\n\n", desired)
}
}
if mismatchFound {
printWarning("Configuration drift detected")
printTroubleshoot([]string{
"Some nodes have current config not matching desired config",
"Check MachineConfigPool status",
"Review machine-config-daemon logs",
"Node may be updating or stuck in update",
})
}
}
func mcp() {
runOMGCommand("get", "mcp")
}
func machine() {
runOMGCommand("get", "machine", "-n", "openshift-machine-api")
}
func machineset() {
runOMGCommand("get", "machineset", "-n", "openshift-machine-api")
}
func pods() {
cmd := exec.Command("omg", "get", "pod", "-o", "wide", "-A")
output, err := cmd.Output()
if err != nil {
printError("Error running omg command: %v", err)
return
}
lines := strings.Split(string(output), "\n")
failingCount := 0
for _, line := range lines {
if !strings.Contains(line, "Running") && !strings.Contains(line, "Succeeded") && line != "" {
fmt.Println(line)
failingCount++
}
}
if failingCount > 1 && cfg.verbose {
printWarning(fmt.Sprintf("Found %d failing pods", failingCount-1))
printInfo("Review pod logs and events for root cause analysis")
}
}
func podRestart() {
cmd := exec.Command("omg", "get", "pod", "-A")
output, err := cmd.Output()
if err != nil {
printError("Error running omg command: %v", err)
return
}
lines := strings.Split(string(output), "\n")
highRestartCount := 0
for i, line := range lines {
if i == 0 {
fmt.Println(line)
continue
}
fields := strings.Fields(line)
if len(fields) >= 5 {
restarts, err := strconv.Atoi(fields[4])
if err == nil && restarts > 10 {
fmt.Println(line)
highRestartCount++
}
}
}
if highRestartCount > 0 {
printWarning(fmt.Sprintf("%d pods with excessive restarts detected", highRestartCount))
printTroubleshoot([]string{
"High restart count indicates instability",
"Check pod logs for crash reasons",
"Review resource limits and requests",
"Check for liveness/readiness probe failures",
"Investigate OOMKilled events",
})
}
}
func kubeApiserver() {
masterNodes := getMasterNodes("kube-apiserver-")
if len(masterNodes) == 0 {
printWarning("No master nodes found for kube-apiserver")
return
}
for _, node := range masterNodes {
logPath := filepath.Join(cfg.mustGatherPath, "*/namespaces/openshift-kube-apiserver/pods", node, "kube-apiserver/kube-apiserver/logs/current.log")
files, _ := filepath.Glob(logPath)
if len(files) == 0 {
printWarning(fmt.Sprintf("%s pod logs not found", node))
continue
}
printSubSection(node)
printTailLines(files[0], 10)
}
}
func etcdPodLogs() {
masterNodes := getMasterNodes("etcd-")
if len(masterNodes) == 0 {
printWarning("No master nodes found for ETCD")
return
}
for _, node := range masterNodes {
logPath := filepath.Join(cfg.mustGatherPath, "*/namespaces/openshift-etcd/pods", node, "etcd/etcd/logs/current.log")
files, _ := filepath.Glob(logPath)
if len(files) == 0 {
printWarning(fmt.Sprintf("%s pod logs not found", node))
continue
}
printSubSection(node)
printTailLines(files[0], 10)
}
}
func kubeControllerManager() {
masterNodes := getMasterNodes("kube-controller-manager-")
if len(masterNodes) == 0 {
printWarning("No master nodes found for kube-controller-manager")
return
}
for _, node := range masterNodes {
logPath := filepath.Join(cfg.mustGatherPath, "*/namespaces/openshift-kube-controller-manager/pods", node, "kube-controller-manager/kube-controller-manager/logs/current.log")
files, _ := filepath.Glob(logPath)
if len(files) == 0 {
printWarning(fmt.Sprintf("%s pod logs not found", node))
continue
}
printSubSection(node)
printTailLines(files[0], 10)
}
}
// ============================================================================
// ISSUE ANALYSIS FUNCTIONS
// ============================================================================
func clusterversionIssues() {
runOMGCommand("get", "clusterversion")
}
func degradedOperators() {
cmd := exec.Command("omg", "get", "co")
output, err := cmd.Output()
if err != nil {
printError("Error running omg command: %v", err)
return
}
lines := strings.Split(string(output), "\n")
degradedCount := 0
healthyOperators := true
for i, line := range lines {
if i == 0 {
fmt.Println(line)
continue
}
fields := strings.Fields(line)
if len(fields) >= 5 {
available := fields[2]
progressing := fields[3]
degraded := fields[4]
if available != "True" || progressing != "False" || degraded != "False" {
fmt.Println(line)
degradedCount++
healthyOperators = false
}
}
}
if healthyOperators {
printSuccess("All cluster operators are working fine")
} else {
printError(fmt.Sprintf("%d degraded operators found", degradedCount))
printTroubleshoot([]string{
"Check operator logs: oc logs -n <namespace> <pod>",
"Review operator conditions in detailed section below",
"Verify all prerequisites are met (network, storage, etc.)",
"Check for resource constraints",
"Review recent cluster changes or updates",
})
}
}
func degradedOperatorsDescription() {
cmd := exec.Command("omg", "get", "co")
output, err := cmd.Output()
if err != nil {
printError("Error running omg command: %v", err)
return
}
lines := strings.Split(string(output), "\n")
var degradedOps []string
for i, line := range lines {
if i == 0 {
continue
}
fields := strings.Fields(line)
if len(fields) >= 5 {
available := fields[2]
progressing := fields[3]
degraded := fields[4]
if available != "True" || progressing != "False" || degraded != "False" {
degradedOps = append(degradedOps, fields[0])
}
}
}
if len(degradedOps) == 0 {
printSuccess("Not required - all operators are available")
return
}
for _, op := range degradedOps {
printSubSection(fmt.Sprintf("%s operator description", op))
runOMGCommand("get", "co", op, "-o", "yaml")
fmt.Println()
}
}
func degradedMCP() {
cmd := exec.Command("omg", "get", "mcp")
output, err := cmd.Output()
if err != nil {
printError("Error running omg command: %v", err)
return
}
lines := strings.Split(string(output), "\n")
degradedCount := 0
healthyMCPs := true
for i, line := range lines {
if i == 0 {
fmt.Println(line)
continue
}
fields := strings.Fields(line)
if len(fields) >= 5 {
updated := fields[2]
updating := fields[3]
degraded := fields[4]
if updated != "True" || updating != "False" || degraded != "False" {
fmt.Println(line)
degradedCount++
healthyMCPs = false
}
}
}
if healthyMCPs {
printSuccess("No machine-config-pool degraded")
} else {
printError(fmt.Sprintf("%d degraded machine-config-pools found", degradedCount))
printTroubleshoot([]string{
"Check MCP conditions for specific errors",
"Review machine-config-daemon logs on affected nodes",
"Verify disk space on nodes",
"Check for file system corruption",
"Review recent MachineConfig changes",
})
}
}
func degradedMCPDescription() {
cmd := exec.Command("omg", "get", "mcp")
output, err := cmd.Output()
if err != nil {
printError("Error running omg command: %v", err)
return
}
lines := strings.Split(string(output), "\n")
var degradedMCPs []string
for i, line := range lines {
if i == 0 {
continue
}
fields := strings.Fields(line)
if len(fields) >= 5 {
updated := fields[2]
updating := fields[3]
degraded := fields[4]
if updated != "True" || updating != "False" || degraded != "False" {
degradedMCPs = append(degradedMCPs, fields[0])
}
}
}
if len(degradedMCPs) == 0 {
printSuccess("Not required - all machine-config-pools are available")
return
}
for _, mcp := range degradedMCPs {
printSubSection(fmt.Sprintf("%s machine-config-pool description", mcp))
runOMGCommand("get", "mcp", mcp, "-o", "yaml")
fmt.Println()
}