-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathranhelper.go
84 lines (62 loc) · 2.37 KB
/
ranhelper.go
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
package ranhelper
import (
"context"
"fmt"
"os/exec"
"time"
"github.com/golang/glog"
"github.com/openshift-kni/eco-goinfra/pkg/clients"
"github.com/openshift-kni/eco-goinfra/pkg/pod"
"github.com/openshift-kni/eco-gotests/tests/cnf/ran/internal/ranparam"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
)
// DoesContainerExistInPod checks if a given container exists in a given pod.
func DoesContainerExistInPod(pod *pod.Builder, containerName string) bool {
containers := pod.Object.Status.ContainerStatuses
for _, container := range containers {
if container.Name == containerName {
glog.V(ranparam.LogLevel).Infof("found %s container", containerName)
return true
}
}
return false
}
// UnmarshalRaw converts raw bytes for a K8s CR into the actual type.
func UnmarshalRaw[T any](raw []byte) (*T, error) {
untyped := &unstructured.Unstructured{}
err := untyped.UnmarshalJSON(raw)
if err != nil {
return nil, err
}
var typed T
err = runtime.DefaultUnstructuredConverter.FromUnstructured(untyped.UnstructuredContent(), &typed)
if err != nil {
return nil, err
}
return &typed, nil
}
// ExecLocalCommand runs the provided command with the provided args locally, cancelling execution if it exceeds
// timeout.
func ExecLocalCommand(timeout time.Duration, command string, args ...string) (string, error) {
glog.V(90).Infof("Locally executing command '%s' with args '%v'", command, args)
ctx, cancel := context.WithTimeout(context.TODO(), timeout)
defer cancel()
output, err := exec.CommandContext(ctx, command, args...).Output()
return string(output), err
}
// GetPodNameWithLabel returns a pod name matching pod label selector in a given namespace.
func GetPodNameWithLabel(client *clients.Settings, podNamespace, podLabelSelector string) (string, error) {
podList, err := pod.List(client, podNamespace, metav1.ListOptions{LabelSelector: podLabelSelector})
if err != nil {
return "", err
}
glog.V(ranparam.LogLevel).Infof("Length of podList matching podLabelSelector is '%v'", len(podList))
if len(podList) < 1 {
return "", fmt.Errorf("no pod found with label %s under namespace %s", podLabelSelector, podNamespace)
}
glog.V(ranparam.LogLevel).Infof("podList[0] matching podLabelSelector is '%v'",
podList[0].Definition.Name)
return podList[0].Definition.Name, nil
}