forked from inspektor-gadget/inspektor-gadget
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelpers.go
282 lines (243 loc) · 9.67 KB
/
helpers.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
// Copyright 2022 The Inspektor Gadget authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package integration
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"os/exec"
"strings"
"testing"
"github.com/docker/go-connections/nat"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/stretchr/testify/require"
containercollection "github.com/inspektor-gadget/inspektor-gadget/pkg/container-collection"
"github.com/inspektor-gadget/inspektor-gadget/pkg/container-utils/testutils"
"github.com/inspektor-gadget/inspektor-gadget/pkg/testing/match"
eventtypes "github.com/inspektor-gadget/inspektor-gadget/pkg/types"
)
var cmpIgnoreUnexported = cmpopts.IgnoreUnexported(
containercollection.Container{},
containercollection.K8sMetadata{},
)
func parseJSONArrayOutput[T any](t *testing.T, output string, normalize func(*T)) []*T {
entries := []*T{}
err := json.Unmarshal([]byte(output), &entries)
require.NoError(t, err, "unmarshaling output array")
for _, entry := range entries {
// To be able to use reflect.DeepEqual and cmp.Diff, we need to
// "normalize" the output so that it only includes non-default values
// for the fields we are able to verify.
if normalize != nil {
normalize(entry)
}
}
return entries
}
func parseMultipleJSONArrayOutput[T any](t *testing.T, output string, normalize func(*T)) []*T {
allEntries := make([]*T, 0)
sc := bufio.NewScanner(strings.NewReader(output))
// On ARO we saw arrays with charcounts of > 100,000. Lets just set 1 MB as the limit
sc.Buffer(make([]byte, 1024), 1024*1024)
for sc.Scan() {
entries := parseJSONArrayOutput(t, sc.Text(), normalize)
allEntries = append(allEntries, entries...)
}
require.NoError(t, sc.Err(), "parsing multiple JSON arrays")
return allEntries
}
func expectAllToMatch[T any](t *testing.T, entries []*T, expectedEntry *T) {
require.NotEmpty(t, entries, "no output entries to match")
for _, entry := range entries {
require.Equal(t, expectedEntry, entry, "unexpected output entry")
}
}
// ExpectAllToMatch verifies that the expectedEntry is matched by all the
// entries in the output (Lines of independent JSON objects).
func ExpectAllToMatch[T any](t *testing.T, output string, normalize func(*T), expectedEntry *T) {
entries := match.ParseMultiJSONOutput(t, output, normalize)
expectAllToMatch(t, entries, expectedEntry)
}
// ExpectAllInArrayToMatch verifies that the expectedEntry is matched by all the
// entries in the output (JSON array of JSON objects).
func ExpectAllInArrayToMatch[T any](t *testing.T, output string, normalize func(*T), expectedEntry *T) {
entries := parseJSONArrayOutput(t, output, normalize)
expectAllToMatch(t, entries, expectedEntry)
}
// ExpectAllInMultipleArrayToMatch verifies that the expectedEntry is matched by all the
// entries in the output (multiple JSON array of JSON objects separated by newlines).
func ExpectAllInMultipleArrayToMatch[T any](t *testing.T, output string, normalize func(*T), expectedEntry *T) {
entries := parseMultipleJSONArrayOutput(t, output, normalize)
expectAllToMatch(t, entries, expectedEntry)
}
// ExpectEntriesInArrayToMatch verifies that all the entries in expectedEntries are
// matched by at least one entry in the output (JSON array of JSON objects).
func ExpectEntriesInArrayToMatch[T any](t *testing.T, output string, normalize func(*T), expectedEntries ...*T) {
entries := parseJSONArrayOutput(t, output, normalize)
match.ExpectNormalizedEntriesToMatch(t, entries, expectedEntries...)
}
// ExpectEntriesInMultipleArrayToMatch verifies that all the entries in expectedEntries are
// matched by at least one entry in the output (multiple JSON array of JSON objects separated by newlines).
func ExpectEntriesInMultipleArrayToMatch[T any](t *testing.T, output string, normalize func(*T), expectedEntries ...*T) {
entries := parseMultipleJSONArrayOutput(t, output, normalize)
match.ExpectNormalizedEntriesToMatch(t, entries, expectedEntries...)
}
type CommonDataOption func(commonData *eventtypes.CommonData)
// WithRuntimeMetadata sets the runtime and container name in the common data.
// Notice the container name is taken from the Kubernetes metadata.
func WithRuntimeMetadata(runtime string) CommonDataOption {
return func(commonData *eventtypes.CommonData) {
commonData.Runtime.RuntimeName = eventtypes.String2RuntimeName(runtime)
commonData.Runtime.ContainerName = commonData.K8s.ContainerName
}
}
// WithContainerImageName sets the ContainerImageName to facilitate the tests
func WithContainerImageName(imageName string, isDockerRuntime bool) CommonDataOption {
return func(commonData *eventtypes.CommonData) {
if !isDockerRuntime {
commonData.Runtime.ContainerImageName = imageName
}
}
}
// WithPodLabels sets the PodLabels to facilitate the tests
func WithPodLabels(podName string, namespace string, enable bool) CommonDataOption {
return func(commonData *eventtypes.CommonData) {
if enable {
commonData.K8s.PodLabels = map[string]string{
"run": podName,
}
}
}
}
func BuildCommonData(namespace string, options ...CommonDataOption) eventtypes.CommonData {
e := eventtypes.CommonData{
K8s: eventtypes.K8sMetadata{
BasicK8sMetadata: eventtypes.BasicK8sMetadata{
Namespace: namespace,
// Pod and Container name are defined by BusyboxPodCommand.
PodName: "test-pod",
ContainerName: "test-pod",
},
},
// TODO: Include the Node
}
for _, option := range options {
option(&e)
}
return e
}
func BuildCommonDataK8s(namespace string, options ...CommonDataOption) eventtypes.CommonData {
e := BuildCommonData(namespace, options...)
WithPodLabels("test-pod", namespace, true)(&e)
return e
}
func BuildBaseEvent(namespace string, options ...CommonDataOption) eventtypes.Event {
e := eventtypes.Event{
Type: eventtypes.NORMAL,
CommonData: BuildCommonData(namespace),
}
for _, option := range options {
option(&e.CommonData)
}
return e
}
func BuildBaseEventK8s(namespace string, options ...CommonDataOption) eventtypes.Event {
e := BuildBaseEvent(namespace, options...)
WithPodLabels("test-pod", namespace, true)(&e.CommonData)
return e
}
func GetTestPodIP(t *testing.T, ns string, podname string) string {
cmd := exec.Command("kubectl", "-n", ns, "get", "pod", podname, "-o", "jsonpath={.status.podIP}")
var stderr bytes.Buffer
cmd.Stderr = &stderr
r, err := cmd.Output()
require.NoError(t, err, "getting pod ip: %s", stderr.String())
return string(r)
}
func GetPodIPsFromLabel(t *testing.T, ns string, label string) []string {
cmd := exec.Command("kubectl", "-n", ns, "get", "pod", "-l", label, "-o", "jsonpath={.items[*].status.podIP}")
var stderr bytes.Buffer
cmd.Stderr = &stderr
r, err := cmd.Output()
require.NoError(t, err, "getting pods ips from label: %s", stderr.String())
return strings.Split(string(r), " ")
}
func GetPodNode(t *testing.T, ns string, podname string) string {
cmd := exec.Command("kubectl", "-n", ns, "get", "pod", podname, "-o", "jsonpath={.spec.nodeName}")
var stderr bytes.Buffer
cmd.Stderr = &stderr
r, err := cmd.Output()
require.NoError(t, err, "getting pod node: %s", stderr.String())
return string(r)
}
func GetPodUID(t *testing.T, ns, podname string) string {
cmd := exec.Command("kubectl", "-n", ns, "get", "pod", podname, "-o", "jsonpath={.metadata.uid}")
r, err := cmd.Output()
require.NoError(t, err, "getting UID of %s/%s: %s", ns, podname, r)
return string(r)
}
func CheckNamespace(ns string) bool {
cmd := exec.Command("kubectl", "get", "ns", ns)
return cmd.Run() == nil
}
// IsDockerRuntime checks whether the container runtime of the first node in the Kubernetes cluster is Docker or not.
func IsDockerRuntime(t *testing.T) bool {
cmd := exec.Command("kubectl", "get", "node", "-o", "jsonpath={.items[0].status.nodeInfo.containerRuntimeVersion}")
var stderr bytes.Buffer
cmd.Stderr = &stderr
r, err := cmd.Output()
require.NoError(t, err, "getting container runtime: %s", stderr.String())
ret := string(r)
return strings.Contains(ret, "docker")
}
// GetContainerRuntime returns the container runtime the cluster is using.
func GetContainerRuntime() (string, error) {
cmd := exec.Command("kubectl", "get", "node", "-o", "jsonpath={.items[0].status.nodeInfo.containerRuntimeVersion}")
var stderr bytes.Buffer
cmd.Stderr = &stderr
r, err := cmd.Output()
if err != nil {
return "", fmt.Errorf("getting container runtime: %w, %s", err, stderr.String())
}
ret := string(r)
parts := strings.Split(ret, ":")
if len(parts) < 1 {
return "", fmt.Errorf("unexpected container runtime version: %s", ret)
}
return parts[0], nil
}
// GetIPVersion returns the version of the IP, 4 or 6. It makes the test fail in case of error.
// Based on https://stackoverflow.com/a/48519490
func GetIPVersion(t *testing.T, address string) uint8 {
if strings.Count(address, ":") < 2 {
return 4
} else if strings.Count(address, ":") >= 2 {
return 6
}
t.Fatalf("Failed to determine IP version for address %s", address)
return 0
}
func StartRegistry(t *testing.T, name string) testutils.Container {
t.Helper()
c := testutils.NewDockerContainer(name, "registry serve /etc/docker/registry/config.yml",
testutils.WithImage("registry:2"),
testutils.WithoutWait(),
testutils.WithPortBindings(nat.PortMap{
"5000/tcp": []nat.PortBinding{{HostIP: "127.0.0.1"}},
}),
)
c.Start(t)
return c
}