Skip to content

Commit 547924e

Browse files
committed
Issue #4: Fix - validate namespaces input by user via cmdline
* New function allNamespacesExist() checks for the existence of all the input namespaces in the k8s cluster * Any namespace that is not found is logged to the user and the data collection aborted
1 parent e0e8122 commit 547924e

File tree

1 file changed

+38
-13
lines changed

1 file changed

+38
-13
lines changed

cmd/nic-supportpkg.go

Lines changed: 38 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
package cmd
22

33
import (
4+
"context"
45
"fmt"
56
"github.com/nginxinc/nginx-k8s-supportpkg/pkg/data_collector"
67
"github.com/nginxinc/nginx-k8s-supportpkg/pkg/jobs"
78
"github.com/spf13/cobra"
9+
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
810
"os"
911
)
1012

@@ -24,32 +26,55 @@ func Execute() {
2426
os.Exit(1)
2527
}
2628

27-
for _, job := range jobs.JobList() {
28-
fmt.Printf("Running job %s...", job.Name)
29-
err = job.Collect(collector)
29+
if allNamespacesExist(collector) == true {
30+
31+
for _, job := range jobs.JobList() {
32+
fmt.Printf("Running job %s...", job.Name)
33+
err = job.Collect(collector)
34+
if err != nil {
35+
fmt.Printf(" Error: %s\n", err)
36+
} else {
37+
fmt.Print(" OK\n")
38+
}
39+
}
40+
41+
tarFile, err := collector.WrapUp()
3042
if err != nil {
31-
fmt.Printf(" Error: %s\n", err)
43+
fmt.Println(fmt.Errorf("error when wrapping up: %s", err))
44+
os.Exit(1)
3245
} else {
33-
fmt.Print(" OK\n")
46+
fmt.Printf("Supportpkg successfully generated: %s\n", tarFile)
3447
}
35-
}
36-
37-
tarFile, err := collector.WrapUp()
38-
if err != nil {
39-
fmt.Println(fmt.Errorf("error when wrapping up: %s", err))
40-
os.Exit(1)
4148
} else {
42-
fmt.Printf("Supportpkg successfully generated: %s\n", tarFile)
49+
fmt.Println(" Error: all namespaces do not exist")
4350
}
4451
},
4552
}
4653

4754
rootCmd.Flags().StringSliceVarP(&namespaces, "namespace", "n", []string{}, "list of namespaces to collect information from")
48-
rootCmd.MarkFlagRequired("namespace")
55+
if err := rootCmd.MarkFlagRequired("namespace"); err != nil {
56+
fmt.Println(err)
57+
os.Exit(1)
58+
}
4959
rootCmd.SetUsageTemplate("Usage: \n nic supportpkg [-n|--namespace] ns1 [-n|--namespace] ns2 ...\n nic supportpkg [-n|--namespace] ns1,ns2 ...\n")
5060

5161
if err := rootCmd.Execute(); err != nil {
5262
fmt.Println(err)
5363
os.Exit(1)
5464
}
5565
}
66+
67+
func allNamespacesExist(dc *data_collector.DataCollector) bool {
68+
69+
var allExist bool = true
70+
for _, namespace := range dc.Namespaces {
71+
_, err := dc.K8sCoreClientSet.CoreV1().Namespaces().Get(context.TODO(), namespace, metav1.GetOptions{})
72+
if err != nil {
73+
dc.Logger.Printf("\t%s: %v\n", namespace, err)
74+
fmt.Printf("\t%s: %v\n", namespace, err)
75+
allExist = false
76+
}
77+
}
78+
79+
return allExist
80+
}

0 commit comments

Comments
 (0)