/
endpoint.go
2206 lines (1876 loc) · 68.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-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 endpoint
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"net"
"os"
"runtime"
"strconv"
"strings"
"time"
"unsafe"
"github.com/cilium/cilium/api/v1/models"
"github.com/cilium/cilium/common/addressing"
"github.com/cilium/cilium/pkg/annotation"
"github.com/cilium/cilium/pkg/bpf"
"github.com/cilium/cilium/pkg/completion"
"github.com/cilium/cilium/pkg/controller"
"github.com/cilium/cilium/pkg/endpoint/regeneration"
"github.com/cilium/cilium/pkg/eventqueue"
"github.com/cilium/cilium/pkg/fqdn"
"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/lock"
"github.com/cilium/cilium/pkg/logging/logfields"
"github.com/cilium/cilium/pkg/mac"
"github.com/cilium/cilium/pkg/maps/ctmap"
"github.com/cilium/cilium/pkg/maps/lxcmap"
"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 (
// 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_"
)
// 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.
//
// The representation of the Endpoint which is serialized to disk for restore
// purposes is the serializableEndpoint type in this package.
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
containerID string
// 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
// mac is the MAC address of the endpoint
//
mac 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 *identity.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
// Options determine the datapath configuration of the endpoint.
Options *option.IntOptions
// status contains the last n state transitions this endpoint went through
status *EndpointStatus
// DNSHistory is the collection of still-valid DNS responses intercepted for
// this endpoint.
DNSHistory *fqdn.DNSCache
// DNSZombies is the collection of DNS IPs that have expired in or been
// evicted from DNSHistory. They are held back from deletion until we can
// confirm that no existing connection is using them.
DNSZombies *fqdn.DNSZombieMappings
// 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 setState()
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
proxy EndpointProxy
// 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
buildMutex lock.Mutex
// 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
// 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
visibilityPolicy *policy.VisibilityPolicy
eventQueue *eventqueue.EventQueue
// skippedRegenerationLevel is the DatapathRegenerationLevel of the regeneration event that
// was skipped due to another regeneration event already being queued, as indicated by
// state. A lower-level current regeneration is bumped to this level to cover for the
// skipped regeneration levels.
skippedRegenerationLevel regeneration.DatapathRegenerationLevel
// 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
aliveCtx context.Context
aliveCancel context.CancelFunc
regenFailedChan chan struct{}
// exposed is a channel that is closed when the endpoint is exposed in the
// endpoint manager.
exposed chan struct{}
allocator cache.IdentityAllocator
}
// SetAllocator sets the identity allocator for this endpoint.
func (e *Endpoint) SetAllocator(allocator cache.IdentityAllocator) {
e.unconditionalLock()
defer e.unlock()
e.allocator = allocator
}
// 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) {
params.Context = e.aliveCtx
e.controllers.UpdateController(name, params)
}
// GetIfIndex returns the ifIndex for this endpoint.
func (e *Endpoint) GetIfIndex() int {
return e.ifIndex
}
// LXCMac returns the LXCMac for this endpoint.
func (e *Endpoint) LXCMac() mac.MAC {
return e.mac
}
// 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)
}
}
// bpfProgramInstalled returns whether a BPF program has been generated for this
// endpoint.
func (e *Endpoint) bpfProgramInstalled() 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
}
// 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, proxy EndpointProxy, allocator cache.IdentityAllocator, ID uint16, state string) *Endpoint {
ep := &Endpoint{
owner: owner,
proxy: proxy,
ID: ID,
OpLabels: pkgLabels.NewOpLabels(),
status: NewEndpointStatus(),
DNSHistory: fqdn.NewDNSCacheWithLimit(option.Config.ToFQDNsMinTTL, option.Config.ToFQDNsMaxIPsPerHost),
DNSZombies: fqdn.NewDNSZombieMappings(option.Config.ToFQDNsMaxDeferredConnectionDeletes),
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),
allocator: allocator,
exposed: make(chan struct{}),
}
ctx, cancel := context.WithCancel(context.Background())
ep.aliveCancel = cancel
ep.aliveCtx = ctx
ep.realizedPolicy = ep.desiredPolicy
ep.SetDefaultOpts(option.Config.Opts)
ep.UpdateLogger(nil)
ep.eventQueue.Run()
return ep
}
// 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() (*identity.Identity, error) {
if err := e.rlockAlive(); err != nil {
return nil, err
}
defer e.runlock()
return e.SecurityIdentity, nil
}
// 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
}
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.
func (e *Endpoint) ConntrackName() string {
e.unconditionalRLock()
defer e.runlock()
return e.conntrackName()
}
// ConntrackNameLocked 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) ConntrackNameLocked() string {
return e.conntrackName()
}
// 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() identity.NumericIdentity {
if e.SecurityIdentity != nil {
return e.SecurityIdentity.ID
}
return identity.InvalidIdentity
}
// Allows is only used for unit testing
func (e *Endpoint) Allows(id identity.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
}
// forcePolicyComputation ensures that upon the next policy calculation for this
// Endpoint, that no short-circuiting of said operation occurs.
func (e *Endpoint) forcePolicyComputation() {
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))
}
}
e.UpdateLogger(nil)
}
// ConntrackLocal determines whether this endpoint is currently using a local
// table to handle connection tracking (true), or the global table (false).
func (e *Endpoint) ConntrackLocal() bool {
e.unconditionalRLock()
defer e.runlock()
return e.ConntrackLocalLocked()
}
// ConntrackLocalLocked is the same as ConntrackLocal, but assumes that the
// endpoint is already locked for reading.
func (e *Endpoint) ConntrackLocalLocked() bool {
if e.SecurityIdentity == nil || e.Options == nil ||
!e.Options.IsEnabled(option.ConntrackLocal) {
return false
}
return true
}
// base64 returns the endpoint in a base64 format.
func (e *Endpoint) base64() (string, error) {
var (
jsonBytes []byte
err error
)
jsonBytes, err = json.Marshal(e)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(jsonBytes), nil
}
// parseBase64ToEndpoint parses the endpoint stored in the given base64 string.
func parseBase64ToEndpoint(str string, ep *Endpoint) error {
jsonBytes, err := base64.StdEncoding.DecodeString(str)
if err != nil {
return err
}
if err := json.Unmarshal(jsonBytes, ep); err != nil {
return fmt.Errorf("error unmarshaling serializableEndpoint from base64 representation: %s", err)
}
return nil
}
// FilterEPDir returns a list of directories' names that possible belong to an endpoint.
func FilterEPDir(dirFiles []os.FileInfo) []string {
eptsID := []string{}
for _, file := range dirFiles {
if file.IsDir() {
_, err := strconv.ParseUint(file.Name(), 10, 16)
if err == nil || strings.HasSuffix(file.Name(), nextDirectorySuffix) || strings.HasSuffix(file.Name(), nextFailedDirectorySuffix) {
eptsID = append(eptsID, file.Name())
}
}
}
return eptsID
}
// parseEndpoint parses the given strEp which is in the form of:
// common.CiliumCHeaderPrefix + common.Version + ":" + endpointBase64
// Note that the parse'd endpoint's identity is only partially restored. The
// caller must call `SetIdentity()` to make the returned endpoint's identity useful.
func parseEndpoint(ctx context.Context, owner regeneration.Owner, strEp string) (*Endpoint, error) {
// TODO: Provide a better mechanism to update from old version once we bump
// TODO: cilium version.
strEpSlice := strings.Split(strEp, ":")
if len(strEpSlice) != 2 {
return nil, fmt.Errorf("invalid format %q. Should contain a single ':'", strEp)
}
ep := Endpoint{
owner: owner,
}
if err := parseBase64ToEndpoint(strEpSlice[1], &ep); err != nil {
return nil, fmt.Errorf("failed to parse restored endpoint: %s", err)
}
// Validate the options that were parsed
ep.SetDefaultOpts(ep.Options)
// Initialize fields to values which are non-nil that are not serialized.
ep.hasBPFProgram = make(chan struct{}, 0)
ep.desiredPolicy = policy.NewEndpointPolicy(owner.GetPolicyRepository())
ep.realizedPolicy = ep.desiredPolicy
ep.controllers = controller.NewManager()
ep.regenFailedChan = make(chan struct{}, 1)
ep.exposed = make(chan struct{})
ctx, cancel := context.WithCancel(ctx)
ep.aliveCancel = cancel
ep.aliveCtx = ctx
// We need to check for nil in Status, CurrentStatuses and Log, since in
// some use cases, status will be not nil and Cilium will eventually
// error/panic if CurrentStatus or Log are not initialized correctly.
// Reference issue GH-2477
if ep.status == nil || ep.status.CurrentStatuses == nil || ep.status.Log == nil {
ep.status = NewEndpointStatus()
}
// Make sure the endpoint has an identity, using the 'init' identity if none.
if ep.SecurityIdentity == nil {
ep.SecurityIdentity = identity.LookupReservedIdentity(identity.ReservedIdentityInit)
}
ep.SecurityIdentity.Sanitize()
ep.UpdateLogger(nil)
ep.setState(StateRestoring, "Endpoint restoring")
return &ep, nil
}
func (e *Endpoint) LogStatus(typ StatusType, code StatusCode, msg string) {
e.unconditionalLock()
defer e.unlock()
// FIXME GH2323 instead of a mutex we could use a channel to send the status
// log message to a single writer?
e.logStatusLocked(typ, code, msg)
}
func (e *Endpoint) LogStatusOK(typ StatusType, msg string) {
e.LogStatus(typ, OK, msg)
}
// LogStatusOKLocked will log an OK message of the given status type with the
// given msg string.
// must be called with endpoint.Mutex held
func (e *Endpoint) LogStatusOKLocked(typ StatusType, msg string) {
e.logStatusLocked(typ, OK, msg)
}
// logStatusLocked logs a status message
// must be called with endpoint.Mutex held
func (e *Endpoint) logStatusLocked(typ StatusType, code StatusCode, msg string) {
e.status.indexMU.Lock()
defer e.status.indexMU.Unlock()
sts := &statusLogMsg{
Status: Status{
Code: code,
Msg: msg,
Type: typ,
State: e.state,
},
Timestamp: time.Now().UTC(),
}
e.status.addStatusLog(sts)
e.getLogger().WithFields(logrus.Fields{
"code": sts.Status.Code,
"type": sts.Status.Type,
logfields.EndpointState: sts.Status.State,
logfields.PolicyRevision: e.policyRevision,
}).Debug(msg)
}
type UpdateValidationError struct {
msg string
}
func (e UpdateValidationError) Error() string { return e.msg }
type UpdateCompilationError struct {
msg string
}
func (e UpdateCompilationError) Error() string { return e.msg }
// UpdateStateChangeError is an error that indicates that updating the state
// of an endpoint was unsuccessful.
// Implements error interface.
type UpdateStateChangeError struct {
msg string
}
func (e UpdateStateChangeError) Error() string { return e.msg }
// Update modifies the endpoint options and *always* tries to regenerate the
// endpoint's program. Returns an error if the provided options are not valid,
// if there was an issue triggering policy updates for the given endpoint,
// or if endpoint regeneration was unable to be triggered. Note that the
// LabelConfiguration in the EndpointConfigurationSpec is *not* consumed here.
func (e *Endpoint) Update(cfg *models.EndpointConfigurationSpec) error {
om, err := EndpointMutableOptionLibrary.ValidateConfigurationMap(cfg.Options)
if err != nil {
return UpdateValidationError{err.Error()}
}
if err := e.lockAlive(); err != nil {
return err
}
e.getLogger().WithField("configuration-options", cfg).Debug("updating endpoint configuration options")
// CurrentStatus will be not OK when we have an uncleared error in BPF,
// policy or Other. We should keep trying to regenerate in the hopes of
// succeeding.
// Note: This "retry" behaviour is better suited to a controller, and can be
// moved there once we have an endpoint regeneration controller.
regenCtx := ®eneration.ExternalRegenerationMetadata{
Reason: "endpoint was updated via API",
RegenerationLevel: regeneration.RegenerateWithoutDatapath,
}
// If configuration options are provided, we only regenerate if necessary.
// Otherwise always regenerate.
if cfg.Options == nil {
regenCtx.RegenerationLevel = regeneration.RegenerateWithDatapathRebuild
regenCtx.Reason = "endpoint was manually regenerated via API"
} else if e.updateAndOverrideEndpointOptions(om) || e.status.CurrentStatus() != OK {
regenCtx.RegenerationLevel = regeneration.RegenerateWithDatapathRewrite
}
if regenCtx.RegenerationLevel > regeneration.RegenerateWithoutDatapath {
e.getLogger().Debug("need to regenerate endpoint; checking state before" +
" attempting to regenerate")
// TODO / FIXME: GH-3281: need ways to queue up regenerations per-endpoint.
// Default timeout for PATCH /endpoint/{id}/config is 60 seconds, so put
// timeout in this function a bit below that timeout. If the timeout
// for clients in API is below this value, they will get a message containing
// "context deadline exceeded".
timeout := time.After(EndpointGenerationTimeout)
// Check for endpoint state every second.
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
e.unlock()
for {
select {
case <-ticker.C:
regen, err := e.SetRegenerateStateIfAlive(regenCtx)
if err != nil {
return err
}
if regen {
e.Regenerate(regenCtx)
return nil
}
case <-timeout:
e.getLogger().Warning("timed out waiting for endpoint state to change")
return UpdateStateChangeError{fmt.Sprintf("unable to regenerate endpoint program because state transition to %s was unsuccessful; check `cilium endpoint log %d` for more information", StateWaitingToRegenerate, e.ID)}
}
}
}
e.unlock()
return nil
}
// HasLabels returns whether endpoint e contains all labels l. Will return 'false'
// if any label in l is not in the endpoint's labels.
func (e *Endpoint) HasLabels(l pkgLabels.Labels) bool {
e.unconditionalRLock()
defer e.runlock()
return e.hasLabelsRLocked(l)
}
// hasLabelsRLocked returns whether endpoint e contains all labels l. Will
// return 'false' if any label in l is not in the endpoint's labels.
// e.Mutex must be RLocked
func (e *Endpoint) hasLabelsRLocked(l pkgLabels.Labels) bool {
allEpLabels := e.OpLabels.AllLabels()
for _, v := range l {
found := false
for _, j := range allEpLabels {
if j.Equals(&v) {
found = true
break
}
}
if !found {
return false
}
}
return true
}
// replaceInformationLabels replaces the information labels of the endpoint.
// Passing a nil set of labels will not perform any action.
// Must be called with e.Mutex.Lock().
func (e *Endpoint) replaceInformationLabels(l pkgLabels.Labels) {
if l == nil {
return
}
e.OpLabels.ReplaceInformationLabels(l, e.getLogger())
}
// replaceIdentityLabels replaces the identity labels of the endpoint. If a net
// changed occurred, the identityRevision is bumped and returned, otherwise 0 is
// returned.
// Passing a nil set of labels will not perform any action and will return the
// current endpoint's identityRevision.
// Must be called with e.Mutex.Lock().
func (e *Endpoint) replaceIdentityLabels(l pkgLabels.Labels) int {
if l == nil {
return e.identityRevision
}
changed := e.OpLabels.ReplaceIdentityLabels(l, e.getLogger())
rev := 0
if changed {
e.identityRevision++
rev = e.identityRevision
}
return rev
}
// DeleteConfig is the endpoint deletion configuration
type DeleteConfig struct {
NoIPRelease bool
NoIdentityRelease bool
}
// leaveLocked removes the endpoint's directory from the system. Must be called
// with Endpoint's mutex AND buildMutex locked.
//
// Note: leaveLocked() is called indirectly from endpoint restore logic for
// endpoints which failed to be restored. Any cleanup routine of leaveLocked()
// which depends on kvstore connectivity must be protected by a flag in
// DeleteConfig and the restore logic must opt-out of it.
func (e *Endpoint) leaveLocked(proxyWaitGroup *completion.WaitGroup, conf DeleteConfig) []error {
errors := []error{}
if !option.Config.DryMode {
e.owner.Datapath().Loader().Unload(e.createEpInfoCache(""))
}
if e.SecurityIdentity != nil && len(e.realizedRedirects) > 0 {
// Passing a new map of nil will purge all redirects
finalize, _ := e.removeOldRedirects(nil, proxyWaitGroup)
if finalize != nil {
finalize()
}
}
if e.policyMap != nil {
if err := e.policyMap.Close(); err != nil {
errors = append(errors, fmt.Errorf("unable to close policymap %s: %s", e.policyMap.String(), err))
}
}
if !conf.NoIdentityRelease && e.SecurityIdentity != nil {
identitymanager.Remove(e.SecurityIdentity)
releaseCtx, cancel := context.WithTimeout(context.Background(), option.Config.KVstoreConnectivityTimeout)
defer cancel()
_, err := e.allocator.Release(releaseCtx, e.SecurityIdentity)
if err != nil {
errors = append(errors, fmt.Errorf("unable to release identity: %s", err))
}