/
hubble.go
269 lines (221 loc) · 11 KB
/
hubble.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
// Copyright 2020 Authors of Cilium
//
// 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 k8sTest
import (
"context"
"fmt"
"net"
"strconv"
"strings"
"time"
"github.com/asaskevich/govalidator"
"github.com/cilium/cilium/pkg/annotation"
. "github.com/cilium/cilium/test/ginkgo-ext"
"github.com/cilium/cilium/test/helpers"
. "github.com/onsi/gomega"
)
var _ = Describe("K8sHubbleTest", func() {
var (
kubectl *helpers.Kubectl
ciliumFilename string
k8s1NodeName string
ciliumPodK8s1 string
hubbleRelayNamespace = helpers.CiliumNamespace
hubbleRelayService = "hubble-relay"
hubbleRelayAddress string
demoPath string
app1Service = "app1-service"
app1Labels = "id=app1,zgroup=testapp"
apps = []string{helpers.App1, helpers.App2, helpers.App3}
prometheusPort = "9091"
)
addVisibilityAnnotation := func(ns, podLabels, direction, port, l4proto, l7proto string) {
visibilityAnnotation := fmt.Sprintf("<%s/%s/%s/%s>", direction, port, l4proto, l7proto)
By("Adding visibility annotation %s on pod with labels %s", visibilityAnnotation, podLabels)
// Prints <node>=<ns>/<podname> for each pod the annotation was applied to
res := kubectl.Exec(fmt.Sprintf("%s annotate pod -n %s -l %s %s=%q"+
" -o 'jsonpath={.spec.nodeName}={.metadata.namespace}/{.metadata.name}{\"\\n\"}'",
helpers.KubectlCmd,
ns, app1Labels,
annotation.ProxyVisibility, visibilityAnnotation))
res.ExpectSuccess("adding proxy visibility annotation failed")
// For each pod, check that the Cilium proxy-statistics contain the new annotation
expectedProxyState := strings.ToLower(visibilityAnnotation)
for node, podName := range res.KVOutput() {
ciliumPod, err := kubectl.GetCiliumPodOnNode(helpers.CiliumNamespace, node)
Expect(err).To(BeNil())
// Extract annotation from endpoint model of pod. It does not have the l4proto, so we insert it manually.
cmd := fmt.Sprintf("cilium endpoint get pod-name:%s"+
" -o jsonpath='{range [*].status.policy.proxy-statistics[*]}<{.location}/{.port}/%s/{.protocol}>{\"\\n\"}{end}'",
podName, strings.ToLower(l4proto))
err = kubectl.CiliumExecUntilMatch(ciliumPod, cmd, expectedProxyState)
Expect(err).To(BeNil(), "timed out waiting for endpoint to regenerate for visibility annotation")
}
}
removeVisbilityAnnotation := func(ns, podLabels string) {
By("Removing visibility annotation on pod with labels %s", app1Labels)
res := kubectl.Exec(fmt.Sprintf("%s annotate pod -n %s -l %s %s-", helpers.KubectlCmd, ns, podLabels, annotation.ProxyVisibility))
res.ExpectSuccess("removing proxy visibility annotation failed")
}
hubbleObserveUntilMatch := func(hubbleNamespace, hubblePod, args, filter, expected string, timeout *helpers.TimeoutConfig) {
hubbleObserve := func() bool {
res := kubectl.HubbleObserve(hubbleNamespace, hubblePod, args)
res.ExpectSuccess("hubble observe invocation failed: %q", res.OutputPrettyPrint())
lines, err := res.FilterLines(filter)
Expect(err).Should(BeNil(), "hubble observe: invalid filter: %q", filter)
for _, line := range lines {
if line.String() == expected {
return true
}
}
return false
}
err := helpers.RepeatUntilTrue(hubbleObserve, timeout)
Expect(err).Should(BeNil(),
"hubble observe: filter %q never matched expected string %q", filter, expected)
}
BeforeAll(func() {
kubectl = helpers.CreateKubectl(helpers.K8s1VMName(), logger)
ciliumFilename = helpers.TimestampFilename("cilium.yaml")
k8s1NodeName, _ = kubectl.GetNodeInfo(helpers.K8s1)
demoPath = helpers.ManifestGet(kubectl.BasePath(), "demo.yaml")
DeployCiliumOptionsAndDNS(kubectl, ciliumFilename, map[string]string{
"global.hubble.metrics.enabled": `"{dns:query;ignoreAAAA,drop,tcp,flow,port-distribution,icmp,http}"`,
"global.hubble.relay.enabled": "true",
})
var err error
ciliumPodK8s1, err = kubectl.GetCiliumPodOnNodeWithLabel(helpers.CiliumNamespace, helpers.K8s1)
Expect(err).Should(BeNil(), "unable to find hubble-cli pod on %s", helpers.K8s1)
ExpectHubbleRelayReady(kubectl, hubbleRelayNamespace)
hubbleRelayIP, hubbleRelayPort, err := kubectl.GetServiceHostPort(hubbleRelayNamespace, hubbleRelayService)
Expect(err).Should(BeNil(), "Cannot get service %s", hubbleRelayService)
Expect(govalidator.IsIP(hubbleRelayIP)).Should(BeTrue(), "hubbleRelayIP is not an IP")
hubbleRelayAddress = net.JoinHostPort(hubbleRelayIP, strconv.Itoa(hubbleRelayPort))
})
AfterFailed(func() {
kubectl.CiliumReport(helpers.CiliumNamespace,
"cilium endpoint list")
})
JustAfterEach(func() {
kubectl.ValidateNoErrorsInLogs(CurrentGinkgoTestDescription().Duration)
})
AfterEach(func() {
ExpectAllPodsTerminated(kubectl)
})
AfterAll(func() {
kubectl.DeleteHubbleRelay(hubbleRelayNamespace)
kubectl.CloseSSHClient()
})
Context("Hubble Observe", func() {
var (
namespaceForTest string
appPods map[string]string
app1ClusterIP string
app1Port int
)
BeforeAll(func() {
namespaceForTest = helpers.GenerateNamespaceForTest("")
kubectl.NamespaceDelete(namespaceForTest)
res := kubectl.NamespaceCreate(namespaceForTest)
res.ExpectSuccess("could not create namespace")
res = kubectl.Apply(helpers.ApplyOptions{FilePath: demoPath, Namespace: namespaceForTest})
res.ExpectSuccess("could not create resource")
err := kubectl.WaitforPods(namespaceForTest, "-l zgroup=testapp", helpers.HelperTimeout)
Expect(err).Should(BeNil(), "test pods are not ready after timeout")
appPods = helpers.GetAppPods(apps, namespaceForTest, kubectl, "id")
app1ClusterIP, app1Port, err = kubectl.GetServiceHostPort(namespaceForTest, app1Service)
Expect(err).To(BeNil(), "unable to find service in %q namespace", namespaceForTest)
})
AfterAll(func() {
kubectl.Delete(demoPath)
kubectl.NamespaceDelete(namespaceForTest)
})
It("Test L3/L4 Flow", func() {
ctx, cancel := context.WithTimeout(context.Background(), helpers.MidCommandTimeout)
defer cancel()
follow := kubectl.HubbleObserveFollow(ctx, helpers.CiliumNamespace, ciliumPodK8s1, fmt.Sprintf(
"--last 1 --type trace --from-pod %s/%s --to-namespace %s --to-label %s --to-port %d",
namespaceForTest, appPods[helpers.App2], namespaceForTest, app1Labels, app1Port))
res := kubectl.ExecPodCmd(namespaceForTest, appPods[helpers.App2],
helpers.CurlFail(fmt.Sprintf("http://%s/public", app1ClusterIP)))
res.ExpectSuccess("%q cannot curl clusterIP %q", appPods[helpers.App2], app1ClusterIP)
err := follow.WaitUntilMatchFilterLineTimeout(`{$.Type}`, "L3_L4", helpers.ShortCommandTimeout)
Expect(err).To(BeNil(), fmt.Sprintf("hubble observe query timed out on %q", follow.OutputPrettyPrint()))
// Basic check for L4 Prometheus metrics.
_, nodeIP := kubectl.GetNodeInfo(helpers.K8s1)
metricsUrl := fmt.Sprintf("%s/metrics", net.JoinHostPort(nodeIP, prometheusPort))
res, err = kubectl.ExecInHostNetNS(ctx, k8s1NodeName, helpers.CurlFail(metricsUrl))
Expect(err).To(BeNil(), "failed to execute curl on node %q", k8s1NodeName)
res.ExpectSuccess("%s/%s cannot curl metrics %q", helpers.CiliumNamespace, ciliumPodK8s1, app1ClusterIP)
res.ExpectContains(`hubble_flows_processed_total{subtype="to-endpoint",type="Trace",verdict="FORWARDED"}`)
})
It("Test L3/L4 Flow with hubble-relay", func() {
res := kubectl.ExecPodCmd(namespaceForTest, appPods[helpers.App2],
helpers.CurlFail(fmt.Sprintf("http://%s/public", app1ClusterIP)))
res.ExpectSuccess("%q cannot curl clusterIP %q", appPods[helpers.App2], app1ClusterIP)
// In case a node was temporarily unavailable, hubble-relay will
// reconnect once it receives a new request. Therefore we retry
// in a 5 second interval.
hubbleObserveUntilMatch(helpers.CiliumNamespace, ciliumPodK8s1, fmt.Sprintf(
"--server %s --last 1 --type trace --from-pod %s/%s --to-namespace %s --to-label %s --to-port %d",
hubbleRelayAddress, namespaceForTest, appPods[helpers.App2], namespaceForTest, app1Labels, app1Port),
`{$.Type}`, "L3_L4",
&helpers.TimeoutConfig{
Ticker: 5 * time.Second,
Timeout: helpers.MidCommandTimeout,
},
)
})
It("Test L7 Flow", func() {
addVisibilityAnnotation(namespaceForTest, app1Labels, "Ingress", "80", "TCP", "HTTP")
defer removeVisbilityAnnotation(namespaceForTest, app1Labels)
ctx, cancel := context.WithTimeout(context.Background(), helpers.MidCommandTimeout)
defer cancel()
follow := kubectl.HubbleObserveFollow(ctx, helpers.CiliumNamespace, ciliumPodK8s1, fmt.Sprintf(
"--last 1 --type l7 --from-pod %s/%s --to-namespace %s --to-label %s --protocol http",
namespaceForTest, appPods[helpers.App2], namespaceForTest, app1Labels))
res := kubectl.ExecPodCmd(namespaceForTest, appPods[helpers.App2],
helpers.CurlFail(fmt.Sprintf("http://%s/public", app1ClusterIP)))
res.ExpectSuccess("%q cannot curl clusterIP %q", appPods[helpers.App2], app1ClusterIP)
err := follow.WaitUntilMatchFilterLineTimeout(`{$.Type}`, "L7", helpers.ShortCommandTimeout)
Expect(err).To(BeNil(), fmt.Sprintf("hubble observe query timed out on %q", follow.OutputPrettyPrint()))
// Basic check for L7 Prometheus metrics.
_, nodeIP := kubectl.GetNodeInfo(helpers.K8s1)
metricsUrl := fmt.Sprintf("%s/metrics", net.JoinHostPort(nodeIP, prometheusPort))
res, err = kubectl.ExecInHostNetNS(ctx, k8s1NodeName, helpers.CurlFail(metricsUrl))
Expect(err).To(BeNil(), "failed to execute curl on node %q", k8s1NodeName)
res.ExpectSuccess("%s/%s cannot curl metrics %q", helpers.CiliumNamespace, ciliumPodK8s1, app1ClusterIP)
res.ExpectContains(`hubble_flows_processed_total{subtype="HTTP",type="L7",verdict="FORWARDED"}`)
})
It("Test L7 Flow with hubble-relay", func() {
addVisibilityAnnotation(namespaceForTest, app1Labels, "Ingress", "80", "TCP", "HTTP")
defer removeVisbilityAnnotation(namespaceForTest, app1Labels)
res := kubectl.ExecPodCmd(namespaceForTest, appPods[helpers.App2],
helpers.CurlFail(fmt.Sprintf("http://%s/public", app1ClusterIP)))
res.ExpectSuccess("%q cannot curl clusterIP %q", appPods[helpers.App2], app1ClusterIP)
// In case a node was temporarily unavailable, hubble-relay will
// reconnect once it receives a new request. Therefore we retry
// in a 5 second interval.
hubbleObserveUntilMatch(helpers.CiliumNamespace, ciliumPodK8s1, fmt.Sprintf(
"--server %s --last 1 --type l7 --from-pod %s/%s --to-namespace %s --to-label %s --protocol http",
hubbleRelayAddress, namespaceForTest, appPods[helpers.App2], namespaceForTest, app1Labels),
`{$.Type}`, "L7",
&helpers.TimeoutConfig{
Ticker: 5 * time.Second,
Timeout: helpers.MidCommandTimeout,
},
)
})
})
})