Skip to content

Instantly share code, notes, and snippets.

@Skarlso
Last active July 29, 2022 13:54
Show Gist options
  • Save Skarlso/e2ec5c805e23b44089fa4e502eef2548 to your computer and use it in GitHub Desktop.
Save Skarlso/e2ec5c805e23b44089fa4e502eef2548 to your computer and use it in GitHub Desktop.
Create Pod and get logs of the running container
go run main.go
creating pod, then creating a container...
pod created... waiting for it to be running
Pod status: Pending
Pod status: Pending
Pod status: Running
watcher stopped
Got container logs: /docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
2022/07/29 13:47:18 [notice] 1#1: using the "epoll" event method
2022/07/29 13:47:18 [notice] 1#1: nginx/1.23.1
2022/07/29 13:47:18 [notice] 1#1: built by gcc 10.2.1 20210110 (Debian 10.2.1-6)
2022/07/29 13:47:18 [notice] 1#1: OS: Linux 5.10.104-linuxkit
2022/07/29 13:47:18 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2022/07/29 13:47:18 [notice] 1#1: start worker processes
2022/07/29 13:47:18 [notice] 1#1: start worker process 31
2022/07/29 13:47:18 [notice] 1#1: start worker process 32
2022/07/29 13:47:18 [notice] 1#1: start worker process 33
2022/07/29 13:47:18 [notice] 1#1: start worker process 34
package main
import (
"bytes"
"context"
"fmt"
"os"
"time"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)
func main() {
args := os.Args
if len(args) < 2 {
fmt.Println("Usage: go run main.go <path to kube-config>")
os.Exit(1)
}
fmt.Println("using config: ", args[1])
fmt.Println("creating pod, then creating a container...")
config, err := clientcmd.BuildConfigFromFlags("", args[1])
//config, err := rest.InClusterConfig()
if err != nil {
fmt.Println("failed to get cluster config: %w", err)
os.Exit(1)
}
client, err := kubernetes.NewForConfig(config)
if err != nil {
fmt.Println("failed to get config: %w", err)
os.Exit(1)
}
var (
namespace = "default"
podName = "test-pod"
)
pod, err := createPod(client, namespace, podName, "test-container-1")
if err != nil {
fmt.Println("failed to create pod: %w", err)
os.Exit(1)
}
logs, err := getContainerLogs(client, namespace, pod.Name, "test-container-1")
if err != nil {
fmt.Println("failed to get pod logs: ", err)
os.Exit(1)
}
fmt.Println("Got container logs: ", logs)
}
func createPod(client *kubernetes.Clientset, namespace string, podName string, containerName string) (*corev1.Pod, error) {
pod := corev1.Pod{
TypeMeta: metav1.TypeMeta{
Kind: "Pod",
APIVersion: "v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: podName,
},
Spec: corev1.PodSpec{
Containers: []corev1.Container{
{
Name: containerName,
Image: "nginx",
},
},
},
}
createdPod, err := client.CoreV1().Pods(namespace).Create(context.Background(), &pod, metav1.CreateOptions{})
if err != nil {
return nil, fmt.Errorf("failed to create pod: %w", err)
}
fmt.Println("pod created... waiting for it to be running")
w, err := client.CoreV1().Pods(namespace).Watch(context.Background(), metav1.ListOptions{
Watch: true,
ResourceVersion: createdPod.GetResourceVersion(),
FieldSelector: fields.OneTermEqualSelector("metadata.name", podName).String(),
})
if err != nil {
return nil, fmt.Errorf("failed to initialize watcher: %w", err)
}
loop:
for {
select {
case events, ok := <-w.ResultChan():
if !ok {
fmt.Println("watcher stopped")
break loop
}
resp, _ := events.Object.(*corev1.Pod)
createdPod = resp
fmt.Println("Pod status:", resp.Status.Phase)
if resp.Status.Phase != corev1.PodPending {
w.Stop()
}
case <-time.After(30 * time.Second):
fmt.Println("timeout to wait for pod active")
w.Stop()
}
}
return createdPod, nil
}
func getContainerLogs(client kubernetes.Interface, namespace, podName, containerName string) (string, error) {
req := client.CoreV1().Pods(namespace).GetLogs(podName, &corev1.PodLogOptions{
Container: containerName,
})
podLogs, err := req.Stream(context.Background())
if err != nil {
return "", fmt.Errorf("failed to get log Stream: %w", err)
}
defer podLogs.Close()
buf := new(bytes.Buffer)
buf.ReadFrom(podLogs)
return buf.String(), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment