1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
| package main
import (
"bytes"
"context"
"flag"
"fmt"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/tools/remotecommand"
"strings"
)
func main() {
kubeconfig := flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
flag.Parse()
config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
if err != nil {
panic(err.Error())
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
pods, err := clientset.CoreV1().Pods("").List(context.TODO(), metav1.ListOptions{
FieldSelector: "status.phase=Running",
})
if err != nil {
panic(err.Error())
}
fmt.Printf("There are %d running pods in the cluster\n", len(pods.Items))
for _, item := range pods.Items {
stdout, stderr, err := execInPod(config, item.Namespace, item.Name, item.Spec.Containers[0].Name)
if err != nil {
continue
}
fmt.Printf("--> %v/%v/%v\n", item.Namespace, item.Name, item.Spec.Containers[0].Name)
fmt.Println(stderr)
fmt.Println(stdout)
}
}
func execInPod(config *rest.Config, namespace, podName, containerName string) (string, string, error) {
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
req := clientset.CoreV1().RESTClient().Post().
Resource("pods").Name(podName).Namespace(namespace).
SubResource("exec").
Param("container", containerName)
req.VersionedParams(
&corev1.PodExecOptions{
Command: []string{"java", "-version"},
Stdin: false,
Stdout: true,
Stderr: true,
TTY: false,
},
scheme.ParameterCodec,
)
var stdout, stderr bytes.Buffer
exec, err := remotecommand.NewSPDYExecutor(config, "POST", req.URL())
if err != nil {
return "", "", err
}
err = exec.Stream(remotecommand.StreamOptions{
Stdin: nil,
Stdout: &stdout,
Stderr: &stderr,
})
if err != nil {
return "", "", err
}
return strings.TrimSpace(stdout.String()), strings.TrimSpace(stderr.String()), err
}
|