Skip to content

Instantly share code, notes, and snippets.

@imjasonh
Created June 7, 2018 19:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save imjasonh/d36d138dbc461c8e96a320aba7b78cf9 to your computer and use it in GitHub Desktop.
Save imjasonh/d36d138dbc461c8e96a320aba7b78cf9 to your computer and use it in GitHub Desktop.
Demonstrate connecting to GKE cluster from outside, starting pod, grabbing logs
$ go run main.go -tok=$(gcloud auth print-access-token) -project=$(gcloud config get-value core/project)
There are 41 pods in the cluster
...
There are 3 nodes in the cluster
-> gke-cluster-1-default-pool-968a07e0-bw9p
-> gke-cluster-1-default-pool-968a07e0-gxzx
-> gke-cluster-1-default-pool-968a07e0-xrdh
Created pod foo-k4twr
container "noop" in pod "foo-k4twr" is waiting to start: ContainerCreating
container "noop" in pod "foo-k4twr" is waiting to start: ContainerCreating
container "noop" in pod "foo-k4twr" is waiting to start: ContainerCreating
container "noop" in pod "foo-k4twr" is waiting to start: ContainerCreating
container "noop" in pod "foo-k4twr" is waiting to start: ContainerCreating
container "noop" in pod "foo-k4twr" is waiting to start: ContainerCreating
container "noop" in pod "foo-k4twr" is waiting to start: ContainerCreating
container "noop" in pod "foo-k4twr" is waiting to start: ContainerCreating
container "noop" in pod "foo-k4twr" is waiting to start: ContainerCreating
container "noop" in pod "foo-k4twr" is waiting to start: ContainerCreating
container "noop" in pod "foo-k4twr" is waiting to start: ContainerCreating
container "noop" in pod "foo-k4twr" is waiting to start: ContainerCreating
container "noop" in pod "foo-k4twr" is waiting to start: ContainerCreating
hello
rpc error: code = Unknown desc = Error: No such container: fb338e4172d6827b4f61feab1982fa236f3faf053ddc17607c271a15d733b807
took 6.152402206s
package main
import (
"context"
"encoding/base64"
"flag"
"fmt"
"io/ioutil"
"log"
"strings"
"time"
"golang.org/x/oauth2"
gke "google.golang.org/api/container/v1beta1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
var (
projectID = flag.String("project", "", "GCP project")
zone = flag.String("zone", "us-east1-b", "GCP zone")
clusterName = flag.String("cluster", "cluster-1", "GKE cluster name")
tok = flag.String("tok", "", "OAuth2 token")
)
func main() {
flag.Parse()
ctx := context.Background()
svc, err := gke.New(oauth2.NewClient(ctx, oauth2.StaticTokenSource(&oauth2.Token{AccessToken: *tok})))
if err != nil {
log.Fatalf("New service: %v", err)
}
cluster, err := svc.Projects.Zones.Clusters.Get(*projectID, *zone, *clusterName).Do()
if err != nil {
log.Fatalf("Get cluster: %v", err)
}
caBytes, err := base64.StdEncoding.DecodeString(cluster.MasterAuth.ClusterCaCertificate)
if err != nil {
log.Fatal(err)
}
config := &rest.Config{
Host: "https://" + cluster.Endpoint,
Username: cluster.MasterAuth.Username,
Password: cluster.MasterAuth.Password,
TLSClientConfig: rest.TLSClientConfig{CAData: caBytes},
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
// Get pods
pods, err := clientset.CoreV1().Pods("").List(metav1.ListOptions{})
if err != nil {
log.Fatal(err)
}
fmt.Printf("There are %d pods in the cluster\n", len(pods.Items))
for _, p := range pods.Items {
fmt.Println("->", p.Namespace, p.Name)
}
// Get nodes
nodes, err := clientset.CoreV1().Nodes().List(metav1.ListOptions{})
if err != nil {
log.Fatal(err)
}
fmt.Printf("There are %d nodes in the cluster\n", len(nodes.Items))
for _, n := range nodes.Items {
fmt.Println("->", n.Name)
}
// Start a pod
pod, err := clientset.CoreV1().Pods("default").Create(&corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
GenerateName: "foo-",
},
Spec: corev1.PodSpec{
Containers: []corev1.Container{{
Name: "noop",
Image: "busybox",
Command: []string{"/bin/echo"},
Args: []string{"hello"},
}},
},
})
if err != nil {
fmt.Println("error creating pod: %v", err)
}
fmt.Println("Created pod", pod.Name)
podStart := time.Now()
// Read pod logs
req := clientset.CoreV1().RESTClient().Get().Namespace("default").Name(pod.Name).Resource("pods").SubResource("log").Param("follow", "true")
for {
rc, err := req.Stream()
if err != nil {
fmt.Println(err)
continue
}
b, err := ioutil.ReadAll(rc)
rc.Close()
if err != nil {
log.Fatal(err)
}
fmt.Println(string(b))
if strings.Contains(string(b), "hello") {
fmt.Println("took", time.Since(podStart))
break
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment