Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Docker tool for debugging in cluster issues #6060

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions build/diagnostics/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# syntax=docker/dockerfile:1
ARG BUSYBOX_IMAGE="busybox:1.36.1"
FROM ${BUSYBOX_IMAGE}
COPY testkube-diagnostics /
USER 1001
ENTRYPOINT ["/testkube-diagnostics"]
137 changes: 137 additions & 0 deletions cmd/diagnostics/commands/dns.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
package commands

import (
"context"
"fmt"
"net"
"strings"
"time"

"github.com/kubeshop/testkube/pkg/ui"
"github.com/spf13/cobra"
)

func NewDnsCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "dns",
Short: "Check DNS entry",
Run: func(cmd *cobra.Command, args []string) {
if len(args) == 0 {
ui.Failf("Please pass domain name")
}
domain := args[0]
analyzer := NewDNSAnalyzer(domain)
results := analyzer.LookupAll(context.Background())
analyzer.PrintResults(results)
},
}

return cmd
}

type DNSResult struct {
RecordType string
Records []string
Duration time.Duration
Error error
}

type DNSAnalyzer struct {
domain string
resolver *net.Resolver
}

func NewDNSAnalyzer(domain string) *DNSAnalyzer {
return &DNSAnalyzer{
domain: domain,
resolver: net.DefaultResolver,
}
}

func (da *DNSAnalyzer) LookupAll(ctx context.Context) map[string]DNSResult {
results := make(map[string]DNSResult)

// Perform A record lookup
results["A"] = da.lookupA(ctx)

// Perform NS record lookup
results["NS"] = da.lookupNS(ctx)

// Perform CNAME record lookup
results["CNAME"] = da.lookupCNAME(ctx)

return results
}

func (da *DNSAnalyzer) lookupA(ctx context.Context) DNSResult {
start := time.Now()
ips, err := da.resolver.LookupIP(ctx, da.domain, "ip4")
duration := time.Since(start)

var records []string
for _, ip := range ips {
records = append(records, ip.String())
}

return DNSResult{
RecordType: "A",
Records: records,
Duration: duration,
Error: err,
}
}

func (da *DNSAnalyzer) lookupNS(ctx context.Context) DNSResult {
start := time.Now()
nss, err := da.resolver.LookupNS(ctx, da.domain)
duration := time.Since(start)

var records []string
for _, ns := range nss {
records = append(records, ns.Host)
}

return DNSResult{
RecordType: "NS",
Records: records,
Duration: duration,
Error: err,
}
}

func (da *DNSAnalyzer) lookupCNAME(ctx context.Context) DNSResult {
start := time.Now()
cname, err := da.resolver.LookupCNAME(ctx, da.domain)
duration := time.Since(start)

var records []string
if cname != "" {
records = append(records, cname)
}

return DNSResult{
RecordType: "CNAME",
Records: records,
Duration: duration,
Error: err,
}
}

func (da *DNSAnalyzer) PrintResults(results map[string]DNSResult) {
fmt.Printf("DNS Analysis Results for %s\n", da.domain)
fmt.Println(strings.Repeat("-", 50))

for recordType, result := range results {
fmt.Printf("\n%s Records:\n", recordType)
if result.Error != nil {
fmt.Printf(" Error: %v\n", result.Error)
} else if len(result.Records) == 0 {
fmt.Println(" No records found")
} else {
for _, record := range result.Records {
fmt.Printf(" %s\n", record)
}
}
fmt.Printf(" Lookup Duration: %v\n", result.Duration)
}
}
61 changes: 61 additions & 0 deletions cmd/diagnostics/commands/root.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package commands

import (
"context"
"fmt"
"os"
"os/signal"
"syscall"

"github.com/pkg/errors"
"github.com/spf13/cobra"

"golang.org/x/sync/errgroup"

"github.com/kubeshop/testkube/pkg/ui"
)

func init() {
// New commands
RootCmd.AddCommand(NewDnsCmd())
RootCmd.AddCommand(NewTLSCmd())
}

var RootCmd = &cobra.Command{
Use: "diagnostics",
Short: "Testkube entrypoint for kubectl plugin",

Run: func(cmd *cobra.Command, args []string) {
ui.Logo()
err := cmd.Usage()
ui.PrintOnError("Displaying usage", err)
cmd.DisableAutoGenTag = true
},
}

func Execute() {
// Run services within an errgroup to propagate errors between services.
g, ctx := errgroup.WithContext(context.Background())

// Cancel the errgroup context on SIGINT and SIGTERM,
// which shuts everything down gracefully.
stopSignal := make(chan os.Signal, 1)
signal.Notify(stopSignal, syscall.SIGINT, syscall.SIGTERM)
g.Go(func() error {
select {
case <-ctx.Done():
return nil
case sig := <-stopSignal:
go func() {
<-stopSignal
os.Exit(137)
}()
return errors.Errorf("received signal: %v", sig)
}
})

if err := RootCmd.ExecuteContext(ctx); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
125 changes: 125 additions & 0 deletions cmd/diagnostics/commands/tls.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
package commands

import (
"crypto/tls"
"fmt"
"time"

"github.com/kubeshop/testkube/pkg/ui"
"github.com/spf13/cobra"
)

func NewTLSCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "dns",
Short: "Check DNS entry",
Run: func(cmd *cobra.Command, args []string) {
if len(args) == 0 {
ui.Failf("Please pass domain name")
}
host := args[0]
checkTLS(host)
},
}

return cmd
}

func checkTLS(host string) {
// Test connection with modern configuration
conf := &tls.Config{
InsecureSkipVerify: false,
MinVersion: tls.VersionTLS12,
}

fmt.Printf("TLS Diagnostic Results for %s\n", host)
fmt.Println("=====================================")

// Connect and get certificate info
conn, err := tls.Dial("tcp", host, conf)
if err != nil {
fmt.Printf("Error connecting: %v\n", err)
return
}
defer conn.Close()

// Get certificate details
certs := conn.ConnectionState().PeerCertificates
if len(certs) > 0 {
cert := certs[0]
fmt.Println("\nCertificate Details:")
fmt.Printf("Subject: %s\n", cert.Subject)
fmt.Printf("Issuer: %s\n", cert.Issuer)
fmt.Printf("Valid from: %s\n", cert.NotBefore)
fmt.Printf("Valid until: %s\n", cert.NotAfter)
fmt.Printf("Expiring in: %d days\n", int(cert.NotAfter.Sub(time.Now()).Hours()/24))
fmt.Printf("Serial number: %x\n", cert.SerialNumber)
fmt.Printf("Version: %d\n", cert.Version)

// Check for domain names
fmt.Println("\nSAN (Subject Alternative Names):")
for _, dns := range cert.DNSNames {
fmt.Printf("- %s\n", dns)
}
}

// Test supported TLS versions
fmt.Println("\nTLS Version Support:")
versions := map[uint16]string{
tls.VersionTLS10: "TLS 1.0",
tls.VersionTLS11: "TLS 1.1",
tls.VersionTLS12: "TLS 1.2",
tls.VersionTLS13: "TLS 1.3",
}

for version, name := range versions {
testConfig := &tls.Config{
InsecureSkipVerify: true,

Check failure

Code scanning / CodeQL

Disabled TLS certificate check High

InsecureSkipVerify should not be used in production code.

Copilot Autofix AI about 1 month ago

Copilot could not generate an autofix suggestion

Copilot could not generate an autofix suggestion for this alert. Try pushing a new commit or if the problem persists contact support.

MinVersion: version,
MaxVersion: version,
}

testConn, err := tls.Dial("tcp", host, testConfig)
if err != nil {
fmt.Printf("✗ %s: Not supported\n", name)
continue
}
testConn.Close()
fmt.Printf("✓ %s: Supported\n", name)
}

// Test cipher suites
fmt.Println("\nSupported Cipher Suites:")
state := conn.ConnectionState()
fmt.Printf("Negotiated Cipher Suite: %s\n", tls.CipherSuiteName(state.CipherSuite))

// Connection info
fmt.Println("\nConnection Information:")
fmt.Printf("Protocol: %s\n", versionToString(state.Version))
fmt.Printf("Server Name: %s\n", state.ServerName)
fmt.Printf("Handshake Complete: %v\n", state.HandshakeComplete)
fmt.Printf("Mutual TLS: %v\n", state.NegotiatedProtocolIsMutual)

Check failure on line 101 in cmd/diagnostics/commands/tls.go

View workflow job for this annotation

GitHub Actions / Lint Go

SA1019: state.NegotiatedProtocolIsMutual has been deprecated since Go 1.16 because it shouldn't be used: this value is always true. (staticcheck)

// Basic security checks
fmt.Println("\nSecurity Assessment:")
if state.Version < tls.VersionTLS12 {
fmt.Println("⚠️ Warning: Using TLS version below 1.2")
} else {
fmt.Println("✓ TLS version >= 1.2")
}
}

func versionToString(version uint16) string {
switch version {
case tls.VersionTLS10:
return "TLS 1.0"
case tls.VersionTLS11:
return "TLS 1.1"
case tls.VersionTLS12:
return "TLS 1.2"
case tls.VersionTLS13:
return "TLS 1.3"
default:
return "Unknown"
}
}
25 changes: 25 additions & 0 deletions cmd/diagnostics/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package main

import (
"github.com/kubeshop/testkube/cmd/diagnostics/commands"
"github.com/kubeshop/testkube/cmd/kubectl-testkube/commands/common"
)

var (
commit string
version string = "999.0.0-dev"
builtBy string
date string
)

func init() {
// pass data from goreleaser to commands package
common.Version = version
common.BuiltBy = builtBy
common.Commit = commit
common.Date = date
}

func main() {
commands.Execute()
}
Loading
Loading