This commit is contained in:
loveuer
2026-01-28 10:28:13 +08:00
parent 507a67e455
commit 3ee0c9c098
29 changed files with 2852 additions and 0 deletions

View File

@@ -0,0 +1,105 @@
apiVersion: v1
kind: Pod
metadata:
name: k8s-discovery-test
namespace: redis-demo
spec:
containers:
- name: test
image: alpine:latest
command: ["sh", "-c"]
args:
- |
echo "=== Installing Go ==="
apk add --no-cache go
echo "=== Building discovery tool ==="
mkdir -p /app/discovery
cat > /app/discovery/main.go << 'EOF'
package main
import (
"fmt"
"net"
"strings"
)
func main() {
fmt.Println("=== Kubernetes Service Discovery Test ===")
headlessAddr := "redis-headless.redis-demo.svc.cluster.local"
fmt.Printf("🔍 Discovering service: %s\n", headlessAddr)
serviceInfo, err := parseHeadlessServiceAddr(headlessAddr)
if err != nil {
fmt.Printf("❌ Failed to discover service: %v\n", err)
return
}
fmt.Println("\n📋 Service Information:")
fmt.Printf(" Name: %s\n", serviceInfo.Name)
fmt.Printf(" Namespace: %s\n", serviceInfo.Namespace)
if len(serviceInfo.All) > 0 {
fmt.Printf("\n🌐 All Pod IPs (%d):\n", len(serviceInfo.All))
for idx, ip := range serviceInfo.All {
podName := fmt.Sprintf("%s-%d", serviceInfo.Name, idx)
if idx == 0 {
fmt.Printf(" 📌 Master: %s -> %s\n", podName, ip)
} else {
fmt.Printf(" 📊 Replica: %s -> %s\n", podName, ip)
}
}
}
fmt.Println("\n🎉 Service discovery completed successfully!")
}
type ServiceInfo struct {
Name string
All []string
}
func parseHeadlessServiceAddr(headlessAddr string) (*ServiceInfo, error) {
resolver := &net.Resolver{PreferGo: true}
addrs, err := resolver.LookupIPAddr(headlessAddr)
if err != nil {
return nil, fmt.Errorf("DNS query failed: %v", err)
}
if len(addrs) == 0 {
return nil, fmt.Errorf("no records found")
}
var podIPs []string
for _, addr := range addrs {
podIPs = append(podIPs, addr.String())
}
parts := strings.Split(headlessAddr, ".")
if len(parts) < 4 {
return nil, fmt.Errorf("invalid format")
}
serviceName := parts[0]
namespace := parts[1]
return &ServiceInfo{
Name: serviceName,
All: podIPs,
}, nil
}
EOF
echo "=== Running discovery tool ==="
cd /app/discovery && go run main.go
echo "=== Sleeping for 30s ==="
sleep 30
volumeMounts:
- name: app-volume
mountPath: /app
volumes:
- name: app-volume
emptyDir: {}
restartPolicy: Never