-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
hubble.go
433 lines (391 loc) · 14.3 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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
// SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium
package cmd
import (
"context"
"fmt"
"net/netip"
"strings"
"github.com/go-openapi/strfmt"
grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
"github.com/sirupsen/logrus"
k8scache "k8s.io/client-go/tools/cache"
flowpb "github.com/cilium/cilium/api/v1/flow"
"github.com/cilium/cilium/api/v1/models"
observerpb "github.com/cilium/cilium/api/v1/observer"
cgroupManager "github.com/cilium/cilium/pkg/cgroups/manager"
cmtypes "github.com/cilium/cilium/pkg/clustermesh/types"
"github.com/cilium/cilium/pkg/crypto/certloader"
"github.com/cilium/cilium/pkg/datapath/link"
v1 "github.com/cilium/cilium/pkg/hubble/api/v1"
"github.com/cilium/cilium/pkg/hubble/container"
"github.com/cilium/cilium/pkg/hubble/exporter"
"github.com/cilium/cilium/pkg/hubble/exporter/exporteroption"
"github.com/cilium/cilium/pkg/hubble/metrics"
"github.com/cilium/cilium/pkg/hubble/monitor"
"github.com/cilium/cilium/pkg/hubble/observer"
"github.com/cilium/cilium/pkg/hubble/observer/observeroption"
"github.com/cilium/cilium/pkg/hubble/parser"
parserOptions "github.com/cilium/cilium/pkg/hubble/parser/options"
"github.com/cilium/cilium/pkg/hubble/peer"
"github.com/cilium/cilium/pkg/hubble/peer/serviceoption"
"github.com/cilium/cilium/pkg/hubble/recorder"
"github.com/cilium/cilium/pkg/hubble/recorder/recorderoption"
"github.com/cilium/cilium/pkg/hubble/recorder/sink"
"github.com/cilium/cilium/pkg/hubble/server"
"github.com/cilium/cilium/pkg/hubble/server/serveroption"
"github.com/cilium/cilium/pkg/identity"
"github.com/cilium/cilium/pkg/loadbalancer"
"github.com/cilium/cilium/pkg/logging"
"github.com/cilium/cilium/pkg/logging/logfields"
"github.com/cilium/cilium/pkg/option"
"github.com/cilium/cilium/pkg/policy"
"github.com/cilium/cilium/pkg/time"
)
func (d *Daemon) getHubbleStatus(ctx context.Context) *models.HubbleStatus {
if !option.Config.EnableHubble {
return &models.HubbleStatus{State: models.HubbleStatusStateDisabled}
}
obs := d.hubbleObserver.Load()
if obs == nil {
return &models.HubbleStatus{
State: models.HubbleStatusStateWarning,
Msg: "Server not initialized",
}
}
req := &observerpb.ServerStatusRequest{}
status, err := obs.ServerStatus(ctx, req)
if err != nil {
return &models.HubbleStatus{State: models.HubbleStatusStateFailure, Msg: err.Error()}
}
metricsState := models.HubbleStatusMetricsStateDisabled
if option.Config.HubbleMetricsServer != "" {
// TODO: The metrics package should be refactored to be able report its actual state
metricsState = models.HubbleStatusMetricsStateOk
}
hubbleStatus := &models.HubbleStatus{
State: models.StatusStateOk,
Observer: &models.HubbleStatusObserver{
CurrentFlows: int64(status.NumFlows),
MaxFlows: int64(status.MaxFlows),
SeenFlows: int64(status.SeenFlows),
Uptime: strfmt.Duration(time.Duration(status.UptimeNs)),
},
Metrics: &models.HubbleStatusMetrics{
State: metricsState,
},
}
return hubbleStatus
}
func (d *Daemon) launchHubble() {
logger := logging.DefaultLogger.WithField(logfields.LogSubsys, "hubble")
if !option.Config.EnableHubble {
logger.Info("Hubble server is disabled")
return
}
var (
observerOpts []observeroption.Option
localSrvOpts []serveroption.Option
parserOpts []parserOptions.Option
)
if len(option.Config.HubbleMonitorEvents) > 0 {
monitorFilter, err := monitor.NewMonitorFilter(logger, option.Config.HubbleMonitorEvents)
if err != nil {
logger.WithError(err).Warn("Failed to initialize Hubble monitor event filter")
} else {
observerOpts = append(observerOpts, observeroption.WithOnMonitorEvent(monitorFilter))
}
}
if option.Config.HubbleMetricsServer != "" {
logger.WithFields(logrus.Fields{
"address": option.Config.HubbleMetricsServer,
"metrics": option.Config.HubbleMetrics,
}).Info("Starting Hubble Metrics server")
grpcMetrics := grpc_prometheus.NewServerMetrics()
if err := metrics.EnableMetrics(log, option.Config.HubbleMetricsServer, option.Config.HubbleMetrics, grpcMetrics, option.Config.EnableHubbleOpenMetrics); err != nil {
logger.WithError(err).Warn("Failed to initialize Hubble metrics server")
return
}
observerOpts = append(observerOpts,
observeroption.WithOnDecodedFlowFunc(func(ctx context.Context, flow *flowpb.Flow) (bool, error) {
err := metrics.ProcessFlow(ctx, flow)
if err != nil {
logger.WithError(err).Error("Failed to ProcessFlow in metrics handler")
}
return false, nil
}),
)
localSrvOpts = append(localSrvOpts,
serveroption.WithGRPCMetrics(grpcMetrics),
serveroption.WithGRPCStreamInterceptor(grpcMetrics.StreamServerInterceptor()),
serveroption.WithGRPCUnaryInterceptor(grpcMetrics.UnaryServerInterceptor()),
)
}
if option.Config.HubbleRedactEnabled {
parserOpts = append(
parserOpts,
parserOptions.Redact(
logger,
option.Config.HubbleRedactHttpURLQuery,
option.Config.HubbleRedactHttpUserInfo,
option.Config.HubbleRedactKafkaApiKey,
option.Config.HubbleRedactHttpHeadersAllow,
option.Config.HubbleRedactHttpHeadersDeny,
),
)
}
d.linkCache = link.NewLinkCache()
payloadParser, err := parser.New(logger, d, d, d, d.ipcache, d, d.linkCache, d.cgroupManager, parserOpts...)
if err != nil {
logger.WithError(err).Error("Failed to initialize Hubble")
return
}
maxFlows, err := getHubbleEventBufferCapacity(logger)
if err != nil {
logger.WithError(err).Error("Specified capacity for Hubble events buffer is invalid")
return
}
observerOpts = append(observerOpts,
observeroption.WithMaxFlows(maxFlows),
observeroption.WithMonitorBuffer(option.Config.HubbleEventQueueSize),
observeroption.WithCiliumDaemon(d),
)
if option.Config.HubbleExportFilePath != "" {
exporterOpts := []exporteroption.Option{
exporteroption.WithPath(option.Config.HubbleExportFilePath),
exporteroption.WithMaxSizeMB(option.Config.HubbleExportFileMaxSizeMB),
exporteroption.WithMaxBackups(option.Config.HubbleExportFileMaxBackups),
exporteroption.WithAllowList(option.Config.HubbleExportAllowlist),
exporteroption.WithDenyList(option.Config.HubbleExportDenylist),
exporteroption.WithFieldMask(option.Config.HubbleExportFieldmask),
}
if option.Config.HubbleExportFileCompress {
exporterOpts = append(exporterOpts, exporteroption.WithCompress())
}
hubbleExporter, err := exporter.NewExporter(d.ctx, logger, exporterOpts...)
if err != nil {
logger.WithError(err).Error("Failed to configure Hubble export")
} else {
opt := observeroption.WithOnDecodedEvent(hubbleExporter)
observerOpts = append(observerOpts, opt)
}
}
if option.Config.HubbleFlowlogsConfigFilePath != "" {
dynamicHubbleExporter := exporter.NewDynamicExporter(logger, option.Config.HubbleFlowlogsConfigFilePath, option.Config.HubbleExportFileMaxSizeMB, option.Config.HubbleExportFileMaxBackups)
opt := observeroption.WithOnDecodedEvent(dynamicHubbleExporter)
observerOpts = append(observerOpts, opt)
}
namespaceManager := observer.NewNamespaceManager()
go namespaceManager.Run(d.ctx)
hubbleObserver, err := observer.NewLocalServer(
payloadParser,
namespaceManager,
logger,
observerOpts...,
)
if err != nil {
logger.WithError(err).Error("Failed to initialize Hubble")
return
}
go hubbleObserver.Start()
d.monitorAgent.RegisterNewConsumer(monitor.NewConsumer(hubbleObserver))
// configure a local hubble instance that serves more gRPC services
sockPath := "unix://" + option.Config.HubbleSocketPath
var peerServiceOptions []serviceoption.Option
if option.Config.HubbleTLSDisabled {
peerServiceOptions = append(peerServiceOptions, serviceoption.WithoutTLSInfo())
}
if option.Config.HubblePreferIpv6 {
peerServiceOptions = append(peerServiceOptions, serviceoption.WithAddressFamilyPreference(serviceoption.AddressPreferIPv6))
}
peerSvc := peer.NewService(d.nodeDiscovery.Manager, peerServiceOptions...)
localSrvOpts = append(localSrvOpts,
serveroption.WithUnixSocketListener(sockPath),
serveroption.WithHealthService(),
serveroption.WithObserverService(hubbleObserver),
serveroption.WithPeerService(peerSvc),
serveroption.WithInsecure(),
)
if option.Config.EnableRecorder && option.Config.EnableHubbleRecorderAPI {
dispatch, err := sink.NewDispatch(option.Config.HubbleRecorderSinkQueueSize)
if err != nil {
logger.WithError(err).Error("Failed to initialize Hubble recorder sink dispatch")
return
}
d.monitorAgent.RegisterNewConsumer(dispatch)
svc, err := recorder.NewService(d.rec, dispatch,
recorderoption.WithStoragePath(option.Config.HubbleRecorderStoragePath))
if err != nil {
logger.WithError(err).Error("Failed to initialize Hubble recorder service")
return
}
localSrvOpts = append(localSrvOpts, serveroption.WithRecorderService(svc))
}
localSrv, err := server.NewServer(logger, localSrvOpts...)
if err != nil {
logger.WithError(err).Error("Failed to initialize local Hubble server")
return
}
logger.WithField("address", sockPath).Info("Starting local Hubble server")
go func() {
if err := localSrv.Serve(); err != nil {
logger.WithError(err).WithField("address", sockPath).Error("Error while serving from local Hubble server")
}
}()
go func() {
<-d.ctx.Done()
localSrv.Stop()
peerSvc.Close()
}()
// configure another hubble instance that serve fewer gRPC services
address := option.Config.HubbleListenAddress
if address != "" {
if option.Config.HubbleTLSDisabled {
logger.WithField("address", address).Warn("Hubble server will be exposing its API insecurely on this address")
}
options := []serveroption.Option{
serveroption.WithTCPListener(address),
serveroption.WithHealthService(),
serveroption.WithPeerService(peerSvc),
serveroption.WithObserverService(hubbleObserver),
}
// Hubble TLS/mTLS setup.
var tlsServerConfig *certloader.WatchedServerConfig
if option.Config.HubbleTLSDisabled {
options = append(options, serveroption.WithInsecure())
} else {
tlsServerConfigChan, err := certloader.FutureWatchedServerConfig(
logger.WithField("config", "tls-server"),
option.Config.HubbleTLSClientCAFiles,
option.Config.HubbleTLSCertFile,
option.Config.HubbleTLSKeyFile,
)
if err != nil {
logger.WithError(err).Error("Failed to initialize Hubble server TLS configuration")
return
}
waitingMsgTimeout := time.After(30 * time.Second)
for tlsServerConfig == nil {
select {
case tlsServerConfig = <-tlsServerConfigChan:
case <-waitingMsgTimeout:
logger.Info("Waiting for Hubble server TLS certificate and key files to be created")
case <-d.ctx.Done():
return
}
}
options = append(options, serveroption.WithServerTLS(tlsServerConfig))
}
srv, err := server.NewServer(logger, options...)
if err != nil {
logger.WithError(err).Error("Failed to initialize Hubble server")
if tlsServerConfig != nil {
tlsServerConfig.Stop()
}
return
}
logger.WithField("address", address).Info("Starting Hubble server")
go func() {
if err := srv.Serve(); err != nil {
logger.WithError(err).WithField("address", address).Error("Error while serving from Hubble server")
if tlsServerConfig != nil {
tlsServerConfig.Stop()
}
}
}()
go func() {
<-d.ctx.Done()
srv.Stop()
if tlsServerConfig != nil {
tlsServerConfig.Stop()
}
}()
}
d.hubbleObserver.Store(hubbleObserver)
}
// GetIdentity looks up identity by ID from Cilium's identity cache. Hubble uses the identity info
// to populate source and destination labels of flows.
func (d *Daemon) GetIdentity(securityIdentity uint32) (*identity.Identity, error) {
ident := d.identityAllocator.LookupIdentityByID(context.Background(), identity.NumericIdentity(securityIdentity))
if ident == nil {
return nil, fmt.Errorf("identity %d not found", securityIdentity)
}
return ident, nil
}
// GetEndpointInfo returns endpoint info for a given IP address. Hubble uses this function to populate
// fields like namespace and pod name for local endpoints.
func (d *Daemon) GetEndpointInfo(ip netip.Addr) (endpoint v1.EndpointInfo, ok bool) {
if !ip.IsValid() {
return nil, false
}
ep := d.endpointManager.LookupIP(ip)
if ep == nil {
return nil, false
}
return ep, true
}
// GetEndpointInfoByID returns endpoint info for a given Cilium endpoint id. Used by Hubble.
func (d *Daemon) GetEndpointInfoByID(id uint16) (endpoint v1.EndpointInfo, ok bool) {
ep := d.endpointManager.LookupCiliumID(id)
if ep == nil {
return nil, false
}
return ep, true
}
func (d *Daemon) GetEndpoints() map[policy.Endpoint]struct{} {
return d.endpointManager.GetPolicyEndpoints()
}
// GetNamesOf implements DNSGetter.GetNamesOf. It looks up DNS names of a given IP from the
// FQDN cache of an endpoint specified by sourceEpID.
func (d *Daemon) GetNamesOf(sourceEpID uint32, ip netip.Addr) []string {
ep := d.endpointManager.LookupCiliumID(uint16(sourceEpID))
if ep == nil {
return nil
}
if !ip.IsValid() {
return nil
}
names := ep.DNSHistory.LookupIP(ip)
for i := range names {
names[i] = strings.TrimSuffix(names[i], ".")
}
return names
}
// GetServiceByAddr looks up service by IP/port. Hubble uses this function to annotate flows
// with service information.
func (d *Daemon) GetServiceByAddr(ip netip.Addr, port uint16) *flowpb.Service {
if !ip.IsValid() {
return nil
}
addrCluster := cmtypes.AddrClusterFrom(ip, 0)
addr := loadbalancer.L3n4Addr{
AddrCluster: addrCluster,
L4Addr: loadbalancer.L4Addr{
Port: port,
},
}
namespace, name, ok := d.svc.GetServiceNameByAddr(addr)
if !ok {
return nil
}
return &flowpb.Service{
Namespace: namespace,
Name: name,
}
}
// GetK8sStore returns the k8s watcher cache store for the given resource name.
// It implements hubble parser's StoreGetter.GetK8sStore
// WARNING: the objects returned by these stores can't be used to create
// update objects into k8s as well as the objects returned by these stores
// should only be used for reading.
func (d *Daemon) GetK8sStore(name string) k8scache.Store {
return d.k8sWatcher.GetStore(name)
}
// getHubbleEventBufferCapacity returns the user configured capacity for
// Hubble's events buffer.
func getHubbleEventBufferCapacity(logger logrus.FieldLogger) (container.Capacity, error) {
return container.NewCapacity(option.Config.HubbleEventBufferCapacity)
}
func (d *Daemon) GetParentPodMetadata(cgroupId uint64) *cgroupManager.PodMetadata {
return d.cgroupManager.GetPodMetadataForContainer(cgroupId)
}