forked from cilium/cilium
/
endpoint.go
2333 lines (1996 loc) · 72.8 KB
/
endpoint.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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2016-2019 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 endpoint
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"net"
"os"
"runtime"
"sort"
"strconv"
"strings"
"time"
"unsafe"
"github.com/cilium/cilium/api/v1/models"
"github.com/cilium/cilium/common/addressing"
"github.com/cilium/cilium/pkg/bpf"
"github.com/cilium/cilium/pkg/completion"
"github.com/cilium/cilium/pkg/controller"
"github.com/cilium/cilium/pkg/datapath/loader"
"github.com/cilium/cilium/pkg/endpoint/regeneration"
"github.com/cilium/cilium/pkg/eventqueue"
"github.com/cilium/cilium/pkg/fqdn"
identityPkg "github.com/cilium/cilium/pkg/identity"
"github.com/cilium/cilium/pkg/identity/cache"
"github.com/cilium/cilium/pkg/identity/identitymanager"
"github.com/cilium/cilium/pkg/k8s/apis/cilium.io"
"github.com/cilium/cilium/pkg/labels"
pkgLabels "github.com/cilium/cilium/pkg/labels"
"github.com/cilium/cilium/pkg/labels/model"
"github.com/cilium/cilium/pkg/lock"
"github.com/cilium/cilium/pkg/logging/logfields"
"github.com/cilium/cilium/pkg/mac"
bpfconfig "github.com/cilium/cilium/pkg/maps/configmap"
"github.com/cilium/cilium/pkg/maps/ctmap"
"github.com/cilium/cilium/pkg/maps/policymap"
"github.com/cilium/cilium/pkg/metrics"
"github.com/cilium/cilium/pkg/monitor/notifications"
"github.com/cilium/cilium/pkg/option"
"github.com/cilium/cilium/pkg/policy"
"github.com/cilium/cilium/pkg/policy/trafficdirection"
"github.com/cilium/cilium/pkg/proxy/accesslog"
"github.com/cilium/cilium/pkg/trigger"
"github.com/sirupsen/logrus"
"golang.org/x/sys/unix"
)
const (
maxLogs = 256
)
var (
EndpointMutableOptionLibrary = option.GetEndpointMutableOptionLibrary()
)
const (
// StateCreating is used to set the endpoint is being created.
StateCreating = string(models.EndpointStateCreating)
// StateWaitingForIdentity is used to set if the endpoint is waiting
// for an identity from the KVStore.
StateWaitingForIdentity = string(models.EndpointStateWaitingForIdentity)
// StateReady specifies if the endpoint is ready to be used.
StateReady = string(models.EndpointStateReady)
// StateWaitingToRegenerate specifies when the endpoint needs to be regenerated, but regeneration has not started yet.
StateWaitingToRegenerate = string(models.EndpointStateWaitingToRegenerate)
// StateRegenerating specifies when the endpoint is being regenerated.
StateRegenerating = string(models.EndpointStateRegenerating)
// StateDisconnecting indicates that the endpoint is being disconnected
StateDisconnecting = string(models.EndpointStateDisconnecting)
// StateDisconnected is used to set the endpoint is disconnected.
StateDisconnected = string(models.EndpointStateDisconnected)
// StateRestoring is used to set the endpoint is being restored.
StateRestoring = string(models.EndpointStateRestoring)
// IpvlanMapName specifies the tail call map for EP on egress used with ipvlan.
IpvlanMapName = "cilium_lxc_ipve_"
// HealthCEPPrefix is the prefix used to name the cilium health endpoints' CEP
HealthCEPPrefix = "cilium-health-"
)
// compile time interface check
var _ notifications.RegenNotificationInfo = &Endpoint{}
// Endpoint represents a container or similar which can be individually
// addresses on L3 with its own IP addresses. This structured is managed by the
// endpoint manager in pkg/endpointmanager.
//
//
// WARNING - STABLE API
// This structure is written as JSON to StateDir/{ID}/lxc_config.h to allow to
// restore endpoints when the agent is being restarted. The restore operation
// will read the file and re-create all endpoints with all fields which are not
// marked as private to JSON marshal. Do NOT modify this structure in ways which
// is not JSON forward compatible.
//
type Endpoint struct {
owner regeneration.Owner
// ID of the endpoint, unique in the scope of the node
ID uint16
// mutex protects write operations to this endpoint structure except
// for the logger field which has its own mutex
mutex lock.RWMutex
// ContainerName is the name given to the endpoint by the container runtime
ContainerName string
// ContainerID is the container ID that docker has assigned to the endpoint
// Note: The JSON tag was kept for backward compatibility.
ContainerID string `json:"dockerID,omitempty"`
// DockerNetworkID is the network ID of the libnetwork network if the
// endpoint is a docker managed container which uses libnetwork
DockerNetworkID string
// DockerEndpointID is the Docker network endpoint ID if managed by
// libnetwork
DockerEndpointID string
// Corresponding BPF map identifier for tail call map of ipvlan datapath
DatapathMapID int
// isDatapathMapPinned denotes whether the datapath map has been pinned.
isDatapathMapPinned bool
// IfName is the name of the host facing interface (veth pair) which
// connects into the endpoint
IfName string
// IfIndex is the interface index of the host face interface (veth pair)
IfIndex int
// OpLabels is the endpoint's label configuration
//
// FIXME: Rename this field to Labels
OpLabels pkgLabels.OpLabels
// identityRevision is incremented each time the identity label
// information of the endpoint has changed
identityRevision int
// LXCMAC is the MAC address of the endpoint
//
// FIXME: Rename this field to MAC
LXCMAC mac.MAC // Container MAC address.
// IPv6 is the IPv6 address of the endpoint
IPv6 addressing.CiliumIPv6
// IPv4 is the IPv4 address of the endpoint
IPv4 addressing.CiliumIPv4
// NodeMAC is the MAC of the node (agent). The MAC is different for every endpoint.
NodeMAC mac.MAC
// SecurityIdentity is the security identity of this endpoint. This is computed from
// the endpoint's labels.
SecurityIdentity *identityPkg.Identity `json:"SecLabel"`
// hasSidecarProxy indicates whether the endpoint has been injected by
// Istio with a Cilium-compatible sidecar proxy. If true, the sidecar proxy
// will be used to apply L7 policy rules. Otherwise, Cilium's node-wide
// proxy will be used.
// TODO: Currently this applies only to HTTP L7 rules. Kafka L7 rules are still enforced by Cilium's node-wide Kafka proxy.
hasSidecarProxy bool
// PolicyMap is the policy related state of the datapath including
// reference to all policy related BPF
PolicyMap *policymap.PolicyMap `json:"-"`
// Options determine the datapath configuration of the endpoint.
Options *option.IntOptions
// Status are the last n state transitions this endpoint went through
Status *EndpointStatus `json:"-"`
// DNSHistory is the collection of still-valid DNS responses intercepted for
// this endpoint.
DNSHistory *fqdn.DNSCache
// dnsHistoryTrigger is the trigger to write down the lxc_config.h to make
// sure that restores when DNS policy is in there are correct
dnsHistoryTrigger *trigger.Trigger
// state is the state the endpoint is in. See SetStateLocked()
state string
// bpfHeaderfileHash is the hash of the last BPF headerfile that has been
// compiled and installed.
bpfHeaderfileHash string
// K8sPodName is the Kubernetes pod name of the endpoint
K8sPodName string
// K8sNamespace is the Kubernetes namespace of the endpoint
K8sNamespace string
// policyRevision is the policy revision this endpoint is currently on
// to modify this field please use endpoint.setPolicyRevision instead
policyRevision uint64
// policyRevisionSignals contains a map of PolicyRevision signals that
// should be triggered once the policyRevision reaches the wanted wantedRev.
policyRevisionSignals map[*policySignal]bool
// proxyPolicyRevision is the policy revision that has been applied to
// the proxy.
proxyPolicyRevision uint64
// proxyStatisticsMutex is the mutex that must be held to read or write
// proxyStatistics.
proxyStatisticsMutex lock.RWMutex
// proxyStatistics contains statistics of proxy redirects.
// They keys in this map are policy.ProxyIDs.
// You must hold Endpoint.proxyStatisticsMutex to read or write it.
proxyStatistics map[string]*models.ProxyStatistics
// nextPolicyRevision is the policy revision that the endpoint has
// updated to and that will become effective with the next regenerate
nextPolicyRevision uint64
// forcePolicyCompute full endpoint policy recomputation
// Set when endpoint options have been changed. Cleared right before releasing the
// endpoint mutex after policy recalculation.
forcePolicyCompute bool
// BuildMutex synchronizes builds of individual endpoints and locks out
// deletion during builds
//
// FIXME: Mark private once endpoint deletion can be moved into
// `pkg/endpoint`
BuildMutex lock.Mutex `json:"-"`
// logger is a logrus object with fields set to report an endpoints information.
// You must hold Endpoint.Mutex to read or write it (but not to log with it).
logger unsafe.Pointer
// controllers is the list of async controllers syncing the endpoint to
// other resources
controllers *controller.Manager
// realizedRedirects maps the ID of each proxy redirect that has been
// successfully added into a proxy for this endpoint, to the redirect's
// proxy port number.
// You must hold Endpoint.Mutex to read or write it.
realizedRedirects map[string]uint16
// BPFConfigMap provides access to the endpoint's BPF configuration.
bpfConfigMap *bpfconfig.EndpointConfigMap
// desiredBPFConfig is the BPF Configuration computed from the endpoint.
desiredBPFConfig *bpfconfig.EndpointConfig
// realizedBPFConfig is the config currently active in the BPF datapath.
realizedBPFConfig *bpfconfig.EndpointConfig
// ctCleaned indicates whether the conntrack table has already been
// cleaned when this endpoint was first created
ctCleaned bool
hasBPFProgram chan struct{}
// selectorPolicy represents a reference to the shared SelectorPolicy
// for all endpoints that have the same Identity.
selectorPolicy policy.SelectorPolicy
desiredPolicy *policy.EndpointPolicy
realizedPolicy *policy.EndpointPolicy
EventQueue *eventqueue.EventQueue `json:"-"`
// DatapathConfiguration is the endpoint's datapath configuration as
// passed in via the plugin that created the endpoint, e.g. the CNI
// plugin which performed the plumbing will enable certain datapath
// features according to the mode selected.
DatapathConfiguration models.EndpointDatapathConfiguration
regenFailedChan chan struct{}
}
// UpdateController updates the controller with the specified name with the
// provided list of parameters in endpoint's list of controllers.
func (e *Endpoint) UpdateController(name string, params controller.ControllerParams) *controller.Controller {
return e.controllers.UpdateController(name, params)
}
// CloseBPFProgramChannel closes the channel that signals whether the endpoint
// has had its BPF program compiled. If the channel is already closed, this is
// a no-op.
func (e *Endpoint) CloseBPFProgramChannel() {
select {
case <-e.hasBPFProgram:
default:
close(e.hasBPFProgram)
}
}
// HasBPFProgram returns whether a BPF program has been generated for this
// endpoint.
func (e *Endpoint) HasBPFProgram() bool {
select {
case <-e.hasBPFProgram:
return true
default:
return false
}
}
// HasIpvlanDataPath returns whether the daemon is running in ipvlan mode.
func (e *Endpoint) HasIpvlanDataPath() bool {
if e.DatapathMapID > 0 {
return true
}
return false
}
// GetIngressPolicyEnabledLocked returns whether ingress policy enforcement is
// enabled for endpoint or not. The endpoint's mutex must be held.
func (e *Endpoint) GetIngressPolicyEnabledLocked() bool {
return e.desiredPolicy.IngressPolicyEnabled
}
// GetEgressPolicyEnabledLocked returns whether egress policy enforcement is
// enabled for endpoint or not. The endpoint's mutex must be held.
func (e *Endpoint) GetEgressPolicyEnabledLocked() bool {
return e.desiredPolicy.EgressPolicyEnabled
}
// SetDesiredIngressPolicyEnabled sets Endpoint's ingress policy enforcement
// configuration to the specified value. The endpoint's mutex must not be held.
func (e *Endpoint) SetDesiredIngressPolicyEnabled(ingress bool) {
e.UnconditionalLock()
e.desiredPolicy.IngressPolicyEnabled = ingress
e.Unlock()
}
// SetDesiredEgressPolicyEnabled sets Endpoint's egress policy enforcement
// configuration to the specified value. The endpoint's mutex must not be held.
func (e *Endpoint) SetDesiredEgressPolicyEnabled(egress bool) {
e.UnconditionalLock()
e.desiredPolicy.EgressPolicyEnabled = egress
e.Unlock()
}
// SetDesiredIngressPolicyEnabledLocked sets Endpoint's ingress policy enforcement
// configuration to the specified value. The endpoint's mutex must be held.
func (e *Endpoint) SetDesiredIngressPolicyEnabledLocked(ingress bool) {
e.desiredPolicy.IngressPolicyEnabled = ingress
}
// SetDesiredEgressPolicyEnabledLocked sets Endpoint's egress policy enforcement
// configuration to the specified value. The endpoint's mutex must be held.
func (e *Endpoint) SetDesiredEgressPolicyEnabledLocked(egress bool) {
e.desiredPolicy.EgressPolicyEnabled = egress
}
// WaitForProxyCompletions blocks until all proxy changes have been completed.
// Called with BuildMutex held.
func (e *Endpoint) WaitForProxyCompletions(proxyWaitGroup *completion.WaitGroup) error {
if proxyWaitGroup == nil {
return nil
}
err := proxyWaitGroup.Context().Err()
if err != nil {
return fmt.Errorf("context cancelled before waiting for proxy updates: %s", err)
}
start := time.Now()
e.getLogger().Debug("Waiting for proxy updates to complete...")
err = proxyWaitGroup.Wait()
if err != nil {
return fmt.Errorf("proxy state changes failed: %s", err)
}
e.getLogger().Debug("Wait time for proxy updates: ", time.Since(start))
return nil
}
// NewEndpointWithState creates a new endpoint useful for testing purposes
func NewEndpointWithState(owner regeneration.Owner, ID uint16, state string) *Endpoint {
ep := &Endpoint{
owner: owner,
ID: ID,
OpLabels: pkgLabels.NewOpLabels(),
Status: NewEndpointStatus(),
DNSHistory: fqdn.NewDNSCacheWithLimit(option.Config.ToFQDNsMinTTL, option.Config.ToFQDNsMaxIPsPerHost),
state: state,
hasBPFProgram: make(chan struct{}, 0),
controllers: controller.NewManager(),
EventQueue: eventqueue.NewEventQueueBuffered(fmt.Sprintf("endpoint-%d", ID), option.Config.EndpointQueueSize),
desiredPolicy: policy.NewEndpointPolicy(owner.GetPolicyRepository()),
regenFailedChan: make(chan struct{}, 1),
}
ep.realizedPolicy = ep.desiredPolicy
ep.SetDefaultOpts(option.Config.Opts)
ep.UpdateLogger(nil)
ep.EventQueue.Run()
return ep
}
// NewEndpointFromChangeModel creates a new endpoint from a request
func NewEndpointFromChangeModel(owner regeneration.Owner, base *models.EndpointChangeRequest) (*Endpoint, error) {
if base == nil {
return nil, nil
}
ep := &Endpoint{
owner: owner,
ID: uint16(base.ID),
ContainerName: base.ContainerName,
ContainerID: base.ContainerID,
DockerNetworkID: base.DockerNetworkID,
DockerEndpointID: base.DockerEndpointID,
IfName: base.InterfaceName,
K8sPodName: base.K8sPodName,
K8sNamespace: base.K8sNamespace,
DatapathMapID: int(base.DatapathMapID),
IfIndex: int(base.InterfaceIndex),
OpLabels: pkgLabels.NewOpLabels(),
DNSHistory: fqdn.NewDNSCacheWithLimit(option.Config.ToFQDNsMinTTL, option.Config.ToFQDNsMaxIPsPerHost),
state: "",
Status: NewEndpointStatus(),
hasBPFProgram: make(chan struct{}, 0),
desiredPolicy: policy.NewEndpointPolicy(owner.GetPolicyRepository()),
controllers: controller.NewManager(),
regenFailedChan: make(chan struct{}, 1),
}
ep.realizedPolicy = ep.desiredPolicy
if base.Mac != "" {
m, err := mac.ParseMAC(base.Mac)
if err != nil {
return nil, err
}
ep.LXCMAC = m
}
if base.HostMac != "" {
m, err := mac.ParseMAC(base.HostMac)
if err != nil {
return nil, err
}
ep.NodeMAC = m
}
if base.Addressing != nil {
if ip := base.Addressing.IPV6; ip != "" {
ip6, err := addressing.NewCiliumIPv6(ip)
if err != nil {
return nil, err
}
ep.IPv6 = ip6
}
if ip := base.Addressing.IPV4; ip != "" {
ip4, err := addressing.NewCiliumIPv4(ip)
if err != nil {
return nil, err
}
ep.IPv4 = ip4
}
}
if base.DatapathConfiguration != nil {
ep.DatapathConfiguration = *base.DatapathConfiguration
}
ep.SetDefaultOpts(option.Config.Opts)
ep.UpdateLogger(nil)
ep.SetStateLocked(string(base.State), "Endpoint creation")
return ep, nil
}
// GetModelRLocked returns the API model of endpoint e.
// e.mutex must be RLocked.
func (e *Endpoint) GetModelRLocked() *models.Endpoint {
if e == nil {
return nil
}
currentState := models.EndpointState(e.state)
if currentState == models.EndpointStateReady && e.Status.CurrentStatus() != OK {
currentState = models.EndpointStateNotReady
}
// This returns the most recent log entry for this endpoint. It is backwards
// compatible with the json from before we added `cilium endpoint log` but it
// only returns 1 entry.
statusLog := e.Status.GetModel()
if len(statusLog) > 0 {
statusLog = statusLog[:1]
}
lblMdl := model.NewModel(&e.OpLabels)
// Sort these slices since they come out in random orders. This allows
// reflect.DeepEqual to succeed.
sort.StringSlice(lblMdl.Realized.User).Sort()
sort.StringSlice(lblMdl.Disabled).Sort()
sort.StringSlice(lblMdl.SecurityRelevant).Sort()
sort.StringSlice(lblMdl.Derived).Sort()
controllerMdl := e.controllers.GetStatusModel()
sort.Slice(controllerMdl, func(i, j int) bool { return controllerMdl[i].Name < controllerMdl[j].Name })
spec := &models.EndpointConfigurationSpec{
LabelConfiguration: lblMdl.Realized,
}
if e.Options != nil {
spec.Options = *e.Options.GetMutableModel()
}
mdl := &models.Endpoint{
ID: int64(e.ID),
Spec: spec,
Status: &models.EndpointStatus{
// FIXME GH-3280 When we begin implementing revision numbers this will
// diverge from models.Endpoint.Spec to reflect the in-datapath config
Realized: spec,
Identity: e.SecurityIdentity.GetModel(),
Labels: lblMdl,
Networking: &models.EndpointNetworking{
Addressing: []*models.AddressPair{{
IPV4: e.IPv4.String(),
IPV6: e.IPv6.String(),
}},
InterfaceIndex: int64(e.IfIndex),
InterfaceName: e.IfName,
Mac: e.LXCMAC.String(),
HostMac: e.NodeMAC.String(),
},
ExternalIdentifiers: &models.EndpointIdentifiers{
ContainerID: e.ContainerID,
ContainerName: e.ContainerName,
DockerEndpointID: e.DockerEndpointID,
DockerNetworkID: e.DockerNetworkID,
PodName: e.GetK8sNamespaceAndPodNameLocked(),
},
// FIXME GH-3280 When we begin returning endpoint revisions this should
// change to return the configured and in-datapath policies.
Policy: e.GetPolicyModel(),
Log: statusLog,
Controllers: controllerMdl,
State: currentState, // TODO: Validate
Health: e.getHealthModel(),
},
}
return mdl
}
// GetHealthModel returns the endpoint's health object.
//
// Must be called with e.Mutex locked.
func (e *Endpoint) getHealthModel() *models.EndpointHealth {
// Duplicated from GetModelRLocked.
currentState := models.EndpointState(e.state)
if currentState == models.EndpointStateReady && e.Status.CurrentStatus() != OK {
currentState = models.EndpointStateNotReady
}
h := models.EndpointHealth{
Bpf: models.EndpointHealthStatusDisabled,
Policy: models.EndpointHealthStatusDisabled,
Connected: false,
OverallHealth: models.EndpointHealthStatusDisabled,
}
switch currentState {
case models.EndpointStateRegenerating, models.EndpointStateWaitingToRegenerate, models.EndpointStateDisconnecting:
h = models.EndpointHealth{
Bpf: models.EndpointHealthStatusPending,
Policy: models.EndpointHealthStatusPending,
Connected: true,
OverallHealth: models.EndpointHealthStatusPending,
}
case models.EndpointStateCreating:
h = models.EndpointHealth{
Bpf: models.EndpointHealthStatusBootstrap,
Policy: models.EndpointHealthStatusDisabled,
Connected: true,
OverallHealth: models.EndpointHealthStatusDisabled,
}
case models.EndpointStateWaitingForIdentity:
h = models.EndpointHealth{
Bpf: models.EndpointHealthStatusDisabled,
Policy: models.EndpointHealthStatusBootstrap,
Connected: true,
OverallHealth: models.EndpointHealthStatusDisabled,
}
case models.EndpointStateNotReady:
h = models.EndpointHealth{
Bpf: models.EndpointHealthStatusWarning,
Policy: models.EndpointHealthStatusWarning,
Connected: true,
OverallHealth: models.EndpointHealthStatusWarning,
}
case models.EndpointStateDisconnected:
h = models.EndpointHealth{
Bpf: models.EndpointHealthStatusDisabled,
Policy: models.EndpointHealthStatusDisabled,
Connected: false,
OverallHealth: models.EndpointHealthStatusDisabled,
}
case models.EndpointStateReady:
h = models.EndpointHealth{
Bpf: models.EndpointHealthStatusOK,
Policy: models.EndpointHealthStatusOK,
Connected: true,
OverallHealth: models.EndpointHealthStatusOK,
}
}
return &h
}
// GetHealthModel returns the endpoint's health object.
func (e *Endpoint) GetHealthModel() *models.EndpointHealth {
// NOTE: Using rlock on mutex directly because getHealthModel handles removed endpoint properly
e.mutex.RLock()
defer e.mutex.RUnlock()
return e.getHealthModel()
}
// GetModel returns the API model of endpoint e.
func (e *Endpoint) GetModel() *models.Endpoint {
if e == nil {
return nil
}
// NOTE: Using rlock on mutex directly because GetModelRLocked handles removed endpoint properly
e.mutex.RLock()
defer e.mutex.RUnlock()
return e.GetModelRLocked()
}
// GetPolicyModel returns the endpoint's policy as an API model.
//
// Must be called with e.Mutex locked.
func (e *Endpoint) GetPolicyModel() *models.EndpointPolicyStatus {
if e == nil {
return nil
}
if e.SecurityIdentity == nil {
return nil
}
realizedIngressIdentities := make([]int64, 0)
realizedEgressIdentities := make([]int64, 0)
for policyMapKey := range e.realizedPolicy.PolicyMapState {
if policyMapKey.DestPort != 0 {
// If the port is non-zero, then the Key no longer only applies
// at L3. AllowedIngressIdentities and AllowedEgressIdentities
// contain sets of which identities (i.e., label-based L3 only)
// are allowed, so anything which contains L4-related policy should
// not be added to these sets.
continue
}
switch trafficdirection.TrafficDirection(policyMapKey.TrafficDirection) {
case trafficdirection.Ingress:
realizedIngressIdentities = append(realizedIngressIdentities, int64(policyMapKey.Identity))
case trafficdirection.Egress:
realizedEgressIdentities = append(realizedEgressIdentities, int64(policyMapKey.Identity))
default:
log.WithField(logfields.TrafficDirection, trafficdirection.TrafficDirection(policyMapKey.TrafficDirection)).Error("Unexpected traffic direction present in realized PolicyMap state for endpoint")
}
}
desiredIngressIdentities := make([]int64, 0)
desiredEgressIdentities := make([]int64, 0)
for policyMapKey := range e.desiredPolicy.PolicyMapState {
if policyMapKey.DestPort != 0 {
// If the port is non-zero, then the Key no longer only applies
// at L3. AllowedIngressIdentities and AllowedEgressIdentities
// contain sets of which identities (i.e., label-based L3 only)
// are allowed, so anything which contains L4-related policy should
// not be added to these sets.
continue
}
switch trafficdirection.TrafficDirection(policyMapKey.TrafficDirection) {
case trafficdirection.Ingress:
desiredIngressIdentities = append(desiredIngressIdentities, int64(policyMapKey.Identity))
case trafficdirection.Egress:
desiredEgressIdentities = append(desiredEgressIdentities, int64(policyMapKey.Identity))
default:
log.WithField(logfields.TrafficDirection, trafficdirection.TrafficDirection(policyMapKey.TrafficDirection)).Error("Unexpected traffic direction present in desired PolicyMap state for endpoint")
}
}
policyEnabled := e.policyStatus()
e.proxyStatisticsMutex.RLock()
proxyStats := make([]*models.ProxyStatistics, 0, len(e.proxyStatistics))
for _, stats := range e.proxyStatistics {
proxyStats = append(proxyStats, stats.DeepCopy())
}
e.proxyStatisticsMutex.RUnlock()
sortProxyStats(proxyStats)
var (
realizedCIDRPolicy *policy.CIDRPolicy
realizedL4Policy *policy.L4Policy
)
if e.realizedPolicy != nil {
realizedL4Policy = e.realizedPolicy.L4Policy
realizedCIDRPolicy = e.realizedPolicy.CIDRPolicy
}
mdl := &models.EndpointPolicy{
ID: int64(e.SecurityIdentity.ID),
// This field should be removed.
Build: int64(e.policyRevision),
PolicyRevision: int64(e.policyRevision),
AllowedIngressIdentities: realizedIngressIdentities,
AllowedEgressIdentities: realizedEgressIdentities,
CidrPolicy: realizedCIDRPolicy.GetModel(),
L4: realizedL4Policy.GetModel(),
PolicyEnabled: policyEnabled,
}
var (
desiredCIDRPolicy *policy.CIDRPolicy
desiredL4Policy *policy.L4Policy
)
if e.desiredPolicy != nil {
desiredCIDRPolicy = e.desiredPolicy.CIDRPolicy
desiredL4Policy = e.desiredPolicy.L4Policy
}
desiredMdl := &models.EndpointPolicy{
ID: int64(e.SecurityIdentity.ID),
// This field should be removed.
Build: int64(e.nextPolicyRevision),
PolicyRevision: int64(e.nextPolicyRevision),
AllowedIngressIdentities: desiredIngressIdentities,
AllowedEgressIdentities: desiredEgressIdentities,
CidrPolicy: desiredCIDRPolicy.GetModel(),
L4: desiredL4Policy.GetModel(),
PolicyEnabled: policyEnabled,
}
// FIXME GH-3280 Once we start returning revisions Realized should be the
// policy implemented in the data path
return &models.EndpointPolicyStatus{
Spec: desiredMdl,
Realized: mdl,
ProxyPolicyRevision: int64(e.proxyPolicyRevision),
ProxyStatistics: proxyStats,
}
}
// policyStatus returns the endpoint's policy status
//
// Must be called with e.Mutex locked.
func (e *Endpoint) policyStatus() models.EndpointPolicyEnabled {
policyEnabled := models.EndpointPolicyEnabledNone
switch {
case e.realizedPolicy.IngressPolicyEnabled && e.realizedPolicy.EgressPolicyEnabled:
policyEnabled = models.EndpointPolicyEnabledBoth
case e.realizedPolicy.IngressPolicyEnabled:
policyEnabled = models.EndpointPolicyEnabledIngress
case e.realizedPolicy.EgressPolicyEnabled:
policyEnabled = models.EndpointPolicyEnabledEgress
}
return policyEnabled
}
// GetID returns the endpoint's ID as a 64-bit unsigned integer.
func (e *Endpoint) GetID() uint64 {
return uint64(e.ID)
}
// GetLabels returns the labels as slice
func (e *Endpoint) GetLabels() []string {
if e.SecurityIdentity == nil {
return []string{}
}
return e.SecurityIdentity.Labels.GetModel()
}
// GetSecurityIdentity returns the security identity of the endpoint. It assumes
// the endpoint's mutex is held.
func (e *Endpoint) GetSecurityIdentity() *identityPkg.Identity {
return e.SecurityIdentity
}
// GetID16 returns the endpoint's ID as a 16-bit unsigned integer.
func (e *Endpoint) GetID16() uint16 {
return e.ID
}
// GetK8sPodLabels returns all labels that exist in the endpoint and were
// derived from k8s pod.
func (e *Endpoint) GetK8sPodLabels() pkgLabels.Labels {
e.UnconditionalRLock()
defer e.RUnlock()
allLabels := e.OpLabels.AllLabels()
if allLabels == nil {
return nil
}
allLabelsFromK8s := allLabels.GetFromSource(pkgLabels.LabelSourceK8s)
k8sEPPodLabels := pkgLabels.Labels{}
for k, v := range allLabelsFromK8s {
if !strings.HasPrefix(v.Key, ciliumio.PodNamespaceMetaLabels) &&
!strings.HasPrefix(v.Key, ciliumio.PolicyLabelServiceAccount) &&
!strings.HasPrefix(v.Key, ciliumio.PodNamespaceLabel) {
k8sEPPodLabels[k] = v
}
}
return k8sEPPodLabels
}
// GetLabelsSHA returns the SHA of labels
func (e *Endpoint) GetLabelsSHA() string {
if e.SecurityIdentity == nil {
return ""
}
return e.SecurityIdentity.GetLabelsSHA256()
}
// GetOpLabels returns the labels as slice
func (e *Endpoint) GetOpLabels() []string {
e.UnconditionalRLock()
defer e.RUnlock()
return e.OpLabels.IdentityLabels().GetModel()
}
// GetOptions returns the datapath configuration options of the endpoint.
func (e *Endpoint) GetOptions() *option.IntOptions {
return e.Options
}
// GetIPv4Address returns the IPv4 address of the endpoint as a string
func (e *Endpoint) GetIPv4Address() string {
return e.IPv4.String()
}
// GetIPv6Address returns the IPv6 address of the endpoint as a string
func (e *Endpoint) GetIPv6Address() string {
return e.IPv6.String()
}
// IPv4Address returns the IPv4 address of the endpoint
func (e *Endpoint) IPv4Address() addressing.CiliumIPv4 {
return e.IPv4
}
// IPv6Address returns the IPv6 address of the endpoint
func (e *Endpoint) IPv6Address() addressing.CiliumIPv6 {
return e.IPv6
}
// GetNodeMAC returns the MAC address of the node from this endpoint's perspective.
func (e *Endpoint) GetNodeMAC() mac.MAC {
return e.NodeMAC
}
// SetNodeMACLocked updates the node MAC inside the endpoint.
func (e *Endpoint) SetNodeMACLocked(m mac.MAC) {
e.NodeMAC = m
}
func (e *Endpoint) HasSidecarProxy() bool {
return e.hasSidecarProxy
}
// ConntrackName returns the name suffix for the endpoint-specific bpf
// conntrack map, which is a 5-digit endpoint ID, or "global" when the
// global map should be used.
// Must be called with the endpoint locked.
func (e *Endpoint) ConntrackName() string {
if e.ConntrackLocalLocked() {
return fmt.Sprintf("%05d", int(e.ID))
}
return "global"
}
// StringID returns the endpoint's ID in a string.
func (e *Endpoint) StringID() string {
return strconv.Itoa(int(e.ID))
}
func (e *Endpoint) GetIdentity() identityPkg.NumericIdentity {
if e.SecurityIdentity != nil {
return e.SecurityIdentity.ID
}
return identityPkg.InvalidIdentity
}
// Allows is only used for unit testing
func (e *Endpoint) Allows(id identityPkg.NumericIdentity) bool {
e.UnconditionalRLock()
defer e.RUnlock()
keyToLookup := policy.Key{
Identity: uint32(id),
TrafficDirection: trafficdirection.Ingress.Uint8(),
}
_, ok := e.desiredPolicy.PolicyMapState[keyToLookup]
return ok
}
// String returns endpoint on a JSON format.
func (e *Endpoint) String() string {
e.UnconditionalRLock()
defer e.RUnlock()
b, err := json.MarshalIndent(e, "", " ")
if err != nil {
return err.Error()
}
return string(b)
}
// optionChanged is a callback used with pkg/option to apply the options to an
// endpoint. Not used for anything at the moment.
func optionChanged(key string, value option.OptionSetting, data interface{}) {
}
// applyOptsLocked applies the given options to the endpoint's options and
// returns true if there were any options changed.
func (e *Endpoint) applyOptsLocked(opts option.OptionMap) bool {
changed := e.Options.ApplyValidated(opts, optionChanged, e) > 0
_, exists := opts[option.Debug]
if exists && changed {
e.UpdateLogger(nil)
}
return changed
}
// ForcePolicyCompute marks the endpoint for forced bpf regeneration.
func (e *Endpoint) ForcePolicyCompute() {
e.forcePolicyCompute = true
}
// SetDefaultOpts initializes the endpoint Options and configures the specified
// options.
func (e *Endpoint) SetDefaultOpts(opts *option.IntOptions) {
if e.Options == nil {
e.Options = option.NewIntOptions(&EndpointMutableOptionLibrary)
}
if e.Options.Library == nil {
e.Options.Library = &EndpointMutableOptionLibrary
}
if e.Options.Opts == nil {
e.Options.Opts = option.OptionMap{}
}
if opts != nil {
epOptLib := option.GetEndpointMutableOptionLibrary()
for k := range epOptLib {
e.Options.SetValidated(k, opts.GetValue(k))
}
}