...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package collector
17
18 import (
19 "context"
20
21 "github.com/pkg/errors"
22 corev1 "k8s.io/api/core/v1"
23 apierrors "k8s.io/apimachinery/pkg/api/errors"
24 "k8s.io/apimachinery/pkg/types"
25 "sigs.k8s.io/controller-runtime/pkg/client"
26 )
27
28 const ExitCode string = "exitCode"
29
30 type ExitCodeCollector struct {
31 kubeClient client.Client
32 namespace string
33 podName string
34 containerName string
35 }
36
37 func NewExitCodeCollector(kubeClient client.Client, namespace string, podName string, containerName string) *ExitCodeCollector {
38 return &ExitCodeCollector{kubeClient: kubeClient, namespace: namespace, podName: podName, containerName: containerName}
39 }
40
41 func (it *ExitCodeCollector) CollectContext(ctx context.Context) (env map[string]interface{}, err error) {
42 var pod corev1.Pod
43 err = it.kubeClient.Get(ctx, types.NamespacedName{
44 Namespace: it.namespace,
45 Name: it.podName,
46 }, &pod)
47
48 if apierrors.IsNotFound(err) {
49 return nil, nil
50 }
51
52 if err != nil {
53 return nil, err
54 }
55
56 var targetContainerStatus corev1.ContainerStatus
57 found := false
58 for _, containerStatus := range pod.Status.ContainerStatuses {
59 if containerStatus.Name == it.containerName {
60 targetContainerStatus = containerStatus
61 found = true
62 break
63 }
64 }
65
66 if !found {
67 return nil, errors.Errorf("no such contaienr called %s in pod %s/%s", it.containerName, pod.Namespace, pod.Name)
68 }
69
70 if targetContainerStatus.State.Terminated == nil {
71 return nil, errors.Errorf("container %s in pod %s/%s is waiting or running, not in ternimated", it.containerName, pod.Namespace, pod.Name)
72 }
73
74 return map[string]interface{}{
75 ExitCode: targetContainerStatus.State.Terminated.ExitCode,
76 }, nil
77 }
78