Skip to content

Commit

Permalink
feat: check if current env is Kubernetes cluster
Browse files Browse the repository at this point in the history
  • Loading branch information
Esonhugh committed Jul 2, 2024
1 parent 6a4dc79 commit 21a7a41
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
10 changes: 10 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ var Opts = struct {

MultiThreadingMode bool
ThreadingNum int

SkipKubeDNSCheck bool
}{}

func init() {
Expand All @@ -32,6 +34,8 @@ func init() {
RootCmd.PersistentFlags().StringVarP(&Opts.Verbose, "verbose", "v", "info", "log level (debug,info,trace,warn,error,fatal,panic)")
RootCmd.PersistentFlags().BoolVarP(&Opts.MultiThreadingMode, "thread", "t", false, "multi threading mode, work pair with -n")
RootCmd.PersistentFlags().IntVarP(&Opts.ThreadingNum, "thread-num", "n", 16, "threading num, default 16")

RootCmd.PersistentFlags().BoolVarP(&Opts.SkipKubeDNSCheck, "skip-kube-dns-check", "k", false, "skip kube-dns check, force check if current environment is matched kube-dns schema")
}

var RootCmd = &cobra.Command{
Expand All @@ -40,6 +44,12 @@ var RootCmd = &cobra.Command{
Long: "k8spider is a tool to discover k8s services",
PersistentPreRun: func(cmd *cobra.Command, args []string) {
SetLogLevel(Opts.Verbose)
if !Opts.SkipKubeDNSCheck { // Not Skip
if pkg.CheckKubernetes() {
log.Warn("current environment is not a kubernetes cluster")
os.Exit(1)
}
}
if Opts.DnsServer != "" {
pkg.NetResolver = &net.Resolver{
PreferGo: true,
Expand Down
20 changes: 20 additions & 0 deletions pkg/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,3 +83,23 @@ func TestPodVerified() bool {
}
return true
}

func TXTRecord(domain string) (txts []string, err error) {
txts, err = net.LookupTXT(domain)
return
}

// https://github.com/kubernetes/dns/blob/master/docs/specification.md
// CheckKubernetes checks if the current environment is a kubernetes cluster
func CheckKubernetes() bool {
_, err := ARecord("kubernetes.default.svc." + Zone)
if err != nil {
return false
}
t, err := TXTRecord("dns-version." + Zone)
if err != nil {
return false
}
log.Infof("dns-version: %v", strings.Join(t, ","))
return true
}

0 comments on commit 21a7a41

Please sign in to comment.