Skip to content

Instantly share code, notes, and snippets.

@yifan-gu
Created May 15, 2017 21:18
Show Gist options
  • Save yifan-gu/9e9cf3866ac5b283fdd12692e1576946 to your computer and use it in GitHub Desktop.
Save yifan-gu/9e9cf3866ac5b283fdd12692e1576946 to your computer and use it in GitHub Desktop.
nginx pod checker
package main
import (
"fmt"
"os"
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/pkg/api"
"k8s.io/client-go/pkg/api/v1"
"k8s.io/client-go/tools/clientcmd"
)
var nginxPod = []byte(`apiVersion: v1
kind: Pod
metadata:
name: nginx
labels:
name: nginx
spec:
containers:
- name: nginx
image: nginx
ports:
- containerPort: 80
`)
var curlPod = &v1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "curl-pod",
Namespace: "default",
},
Spec: v1.PodSpec{
Containers: []v1.Container{
{
Name: "curl-container",
Image: "byrnedo/alpine-curl", // TODO(yifan): Host this image under quay.io/coreos/
},
},
RestartPolicy: v1.RestartPolicyNever,
},
}
func main() {
kubeconfig := os.Getenv("KUBECONFIG")
if kubeconfig == "" {
panic("no kubeconfig")
}
config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
panic(err)
}
client, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err)
}
obj, _, err := api.Codecs.UniversalDecoder().Decode(nginxPod, nil, &v1.Pod{})
if err != nil {
panic(err)
}
pod, ok := obj.(*v1.Pod)
if !ok {
panic("not a pod")
}
// 1. Run the nginx pod.
_, err = client.CoreV1().Pods("default").Create(pod)
if err != nil {
panic(err)
}
time.Sleep(time.Second * 5)
// 2. Get the nginx pod IP.
running := false
var p *v1.Pod
for i := 0; i < 10; i++ {
p, err = client.CoreV1().Pods("default").Get("nginx", metav1.GetOptions{})
if err == nil && p.Status.Phase == v1.PodRunning {
running = true
break
}
time.Sleep(time.Second)
}
if !running {
panic("time out waiting nginx running")
}
fmt.Println("pod ip", p.Status.PodIP)
// 3. Create a curl pod that curls the nginx pod IP.
curlPod.Spec.Containers[0].Command = []string{"curl", "--fail", p.Status.PodIP}
_, err = client.CoreV1().Pods("default").Create(curlPod)
if err != nil {
panic(err)
}
time.Sleep(time.Second * 5)
succeeded := false
for i := 0; i < 10; i++ {
p, err = client.CoreV1().Pods("default").Get("curl-pod", metav1.GetOptions{})
if err == nil && p.Status.Phase == v1.PodSucceeded {
succeeded = true
break
}
time.Sleep(time.Second)
}
if !succeeded {
panic("not succeeded")
}
fmt.Println("PASS")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment