/
bpf.go
1536 lines (1330 loc) · 52.1 KB
/
bpf.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
// SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium
package endpoint
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"net/netip"
"os"
"path/filepath"
"sync"
"github.com/google/renameio/v2"
"github.com/sirupsen/logrus"
"github.com/vishvananda/netlink"
"golang.org/x/sys/unix"
"github.com/cilium/cilium/api/v1/models"
"github.com/cilium/cilium/pkg/bpf"
"github.com/cilium/cilium/pkg/common"
"github.com/cilium/cilium/pkg/completion"
"github.com/cilium/cilium/pkg/controller"
"github.com/cilium/cilium/pkg/endpoint/regeneration"
"github.com/cilium/cilium/pkg/fqdn/restore"
"github.com/cilium/cilium/pkg/loadinfo"
"github.com/cilium/cilium/pkg/logging"
"github.com/cilium/cilium/pkg/logging/logfields"
"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/option"
"github.com/cilium/cilium/pkg/policy"
"github.com/cilium/cilium/pkg/revert"
"github.com/cilium/cilium/pkg/time"
"github.com/cilium/cilium/pkg/version"
)
const (
// EndpointGenerationTimeout specifies timeout for proxy completion context
EndpointGenerationTimeout = 330 * time.Second
// ciliumCHeaderPrefix is the prefix using when printing/writing an endpoint in a
// base64 form.
ciliumCHeaderPrefix = "CILIUM_BASE64_"
)
var (
handleNoHostInterfaceOnce sync.Once
syncPolicymapControllerGroup = controller.NewGroup("sync-policymap")
)
// policyMapPath returns the path to the policy map of endpoint.
func (e *Endpoint) policyMapPath() string {
return bpf.LocalMapPath(policymap.MapName, e.ID)
}
// callsMapPath returns the path to cilium tail calls map of an endpoint.
func (e *Endpoint) callsMapPath() string {
return e.owner.Datapath().Loader().CallsMapPath(e.ID)
}
// callsCustomMapPath returns the path to cilium custom tail calls map of an
// endpoint.
func (e *Endpoint) customCallsMapPath() string {
return e.owner.Datapath().Loader().CustomCallsMapPath(e.ID)
}
// writeInformationalComments writes annotations to the specified writer,
// including a base64 encoding of the endpoint object, and human-readable
// strings describing the configuration of the datapath.
//
// For configuration of actual datapath behavior, see WriteEndpointConfig().
//
// e.mutex must be RLock()ed
func (e *Endpoint) writeInformationalComments(w io.Writer) error {
fw := bufio.NewWriter(w)
fmt.Fprint(fw, "/*\n")
epStr64, err := e.base64()
if err == nil {
var verBase64 string
verBase64, err = version.Base64()
if err == nil {
fmt.Fprintf(fw, " * %s%s:%s\n * \n", ciliumCHeaderPrefix,
verBase64, epStr64)
}
}
if err != nil {
e.logStatusLocked(BPF, Warning, fmt.Sprintf("Unable to create a base64: %s", err))
}
if cid := e.GetContainerID(); cid == "" {
fmt.Fprintf(fw, " * Docker Network ID: %s\n", e.dockerNetworkID)
fmt.Fprintf(fw, " * Docker Endpoint ID: %s\n", e.dockerEndpointID)
} else {
fmt.Fprintf(fw, " * Container ID: %s\n", cid)
fmt.Fprintf(fw, " * Container Interface: %s\n", e.containerIfName)
}
if option.Config.EnableIPv6 {
fmt.Fprintf(fw, " * IPv6 address: %s\n", e.IPv6.String())
}
fmt.Fprintf(fw, ""+
" * IPv4 address: %s\n"+
" * Identity: %d\n"+
" * PolicyMap: %s\n"+
" * NodeMAC: %s\n"+
" */\n\n",
e.IPv4.String(),
e.getIdentity(), bpf.LocalMapName(policymap.MapName, e.ID),
e.nodeMAC)
fw.WriteString("/*\n")
fw.WriteString(" * Labels:\n")
if e.SecurityIdentity != nil {
if len(e.SecurityIdentity.Labels) == 0 {
fmt.Fprintf(fw, " * - %s\n", "(no labels)")
} else {
for _, v := range e.SecurityIdentity.Labels {
fmt.Fprintf(fw, " * - %s\n", v)
}
}
}
fw.WriteString(" */\n\n")
return fw.Flush()
}
// writeHeaderfile writes the lxc_config.h header file of an endpoint.
//
// e.mutex must be write-locked.
func (e *Endpoint) writeHeaderfile(prefix string) error {
headerPath := filepath.Join(prefix, common.CHeaderFileName)
e.getLogger().WithFields(logrus.Fields{
logfields.Path: headerPath,
}).Debug("writing header file")
// Write new contents to a temporary file which will be atomically renamed to the
// real file at the end of this function. This will make sure we never end up with
// corrupted header files on the filesystem.
f, err := renameio.TempFile(prefix, headerPath)
if err != nil {
return fmt.Errorf("failed to open temporary file: %s", err)
}
defer f.Cleanup()
if e.DNSRulesV2 != nil {
// Note: e.DNSRulesV2 is updated by syncEndpointHeaderFile and regenerateBPF
// before they call into writeHeaderfile, because GetDNSRules must not be
// called with endpoint.mutex held.
e.getLogger().WithFields(logrus.Fields{
logfields.Path: headerPath,
"DNSRulesV2": e.DNSRulesV2,
}).Debug("writing header file with DNSRules")
}
if err = e.writeInformationalComments(f); err != nil {
return err
}
if err = e.owner.Datapath().WriteEndpointConfig(f, e); err != nil {
return err
}
return f.CloseAtomicallyReplace()
}
// proxyPolicy implements policy.ProxyPolicy interface, and passes most of the calls
// to policy.L4Filter, but re-implements GetPort() to return the resolved named port,
// instead of returning a 0 port number.
type proxyPolicy struct {
*policy.L4Filter
port uint16
protocol uint8
}
// newProxyPolicy returns a new instance of proxyPolicy by value
func (e *Endpoint) newProxyPolicy(l4 *policy.L4Filter, port uint16, proto uint8) proxyPolicy {
return proxyPolicy{L4Filter: l4, port: port, protocol: proto}
}
// GetPort returns the destination port number on which the proxy policy applies
// This version properly returns the port resolved from a named port, if any.
func (p *proxyPolicy) GetPort() uint16 {
return p.port
}
// GetProtocol returns the destination protocol number on which the proxy policy applies
func (p *proxyPolicy) GetProtocol() uint8 {
return p.protocol
}
// addNewRedirectsFromDesiredPolicy must be called while holding the endpoint lock for
// writing. On success, returns nil; otherwise, returns an error indicating the
// problem that occurred while adding an l7 redirect for the specified policy.
// Must be called with endpoint.mutex Lock()ed.
func (e *Endpoint) addNewRedirectsFromDesiredPolicy(ingress bool, desiredRedirects map[string]bool, proxyWaitGroup *completion.WaitGroup) (error, revert.FinalizeFunc, revert.RevertFunc) {
if option.Config.DryMode || e.IsProxyDisabled() {
return nil, nil, nil
}
var (
finalizeList revert.FinalizeList
revertStack revert.RevertStack
updatedStats []*models.ProxyStatistics
)
changes := policy.ChangeState{
Adds: make(policy.Keys),
Old: make(map[policy.Key]policy.MapStateEntry),
}
e.desiredPolicy.UpdateRedirects(ingress,
func(l4 *policy.L4Filter) (uint16, bool) {
var redirectPort uint16
// Only create a redirect if the proxy is NOT running in a sidecar container
// or the parser is not HTTP. If running in a sidecar container and the parser
// is HTTP, just allow traffic to the port at L4 by setting the proxy port
// to 0.
if !e.hasSidecarProxy || l4.L7Parser != policy.ParserTypeHTTP {
var finalizeFunc revert.FinalizeFunc
var revertFunc revert.RevertFunc
// proxyID() returns also the destination port for the policy,
// which may be resolved from a named port
proxyID, dstPort, dstProto := e.proxyID(l4)
if proxyID == "" {
// Skip redirects for which a proxyID cannot be created.
// This may happen due to the named port mapping not
// existing or multiple PODs defining the same port name
// with different port values. The redirect will be created
// when the mapping is available or when the port name
// conflicts have been resolved in POD specs.
return 0, false
}
pp := e.newProxyPolicy(l4, dstPort, dstProto)
var err error
redirectPort, err, finalizeFunc, revertFunc = e.proxy.CreateOrUpdateRedirect(e.aliveCtx, &pp, proxyID, e, proxyWaitGroup)
if err != nil {
// Skip redirects that can not be created or updated. This
// can happen when a listener is missing, for example when
// restarting and k8s delivers the CNP before the related
// CEC.
// Policy is regenerated when listeners are added or removed
// to fix this condition when the listener is available.
e.getLogger().WithField(logfields.Listener, l4.GetListener()).WithError(err).Debug("Redirect rule with missing listener skipped, will be applied once the listener is available")
return 0, false
}
finalizeList.Append(finalizeFunc)
revertStack.Push(revertFunc)
if e.realizedRedirects == nil {
e.realizedRedirects = make(map[string]uint16)
}
if _, found := e.realizedRedirects[proxyID]; !found {
revertStack.Push(func() error {
delete(e.realizedRedirects, proxyID)
return nil
})
}
e.realizedRedirects[proxyID] = redirectPort
desiredRedirects[proxyID] = true
// Update the endpoint API model to report that Cilium manages a
// redirect for that port.
e.proxyStatisticsMutex.Lock()
proxyStats := e.getProxyStatisticsLocked(proxyID, string(l4.L7Parser), dstPort, l4.Ingress)
proxyStats.AllocatedProxyPort = int64(redirectPort)
e.proxyStatisticsMutex.Unlock()
updatedStats = append(updatedStats, proxyStats)
}
if e.desiredPolicy == e.realizedPolicy {
// Any map updates when a new policy has not been calculated are taken care by incremental map updates.
return 0, false
}
return redirectPort, true
}, changes)
revertStack.Push(func() error {
// Restore the proxy stats.
e.proxyStatisticsMutex.Lock()
for _, stats := range updatedStats {
stats.AllocatedProxyPort = 0
}
e.proxyStatisticsMutex.Unlock()
e.desiredPolicy.GetPolicyMap().RevertChanges(changes)
return nil
})
return nil, finalizeList.Finalize, revertStack.Revert
}
func (e *Endpoint) addVisibilityRedirects(ingress bool, desiredRedirects map[string]bool, proxyWaitGroup *completion.WaitGroup) (error, revert.FinalizeFunc, revert.RevertFunc) {
var (
visPolicy policy.DirectionalVisibilityPolicy
finalizeList revert.FinalizeList
revertStack revert.RevertStack
changes = policy.ChangeState{
Adds: make(policy.Keys),
Old: make(map[policy.Key]policy.MapStateEntry),
}
)
if e.visibilityPolicy == nil || e.IsProxyDisabled() {
return nil, finalizeList.Finalize, revertStack.Revert
}
if ingress {
visPolicy = e.visibilityPolicy.Ingress
} else {
visPolicy = e.visibilityPolicy.Egress
}
updatedStats := make([]*models.ProxyStatistics, 0, len(visPolicy))
for _, visMeta := range visPolicy {
// Create a redirect for every entry in the visibility policy.
// Sidecar already sees all HTTP traffic
if e.hasSidecarProxy && visMeta.Parser == policy.ParserTypeHTTP {
continue
}
var (
redirectPort uint16
err error
finalizeFunc revert.FinalizeFunc
revertFunc revert.RevertFunc
)
proxyID := policy.ProxyID(e.ID, visMeta.Ingress, visMeta.Proto.String(), visMeta.Port)
// Skip adding a visibility redirect if a redirect for the given proto and port already
// exists. The existing redirect will do policy enforcement and also provides visibility
if desiredRedirects[proxyID] {
continue
}
redirectPort, err, finalizeFunc, revertFunc = e.proxy.CreateOrUpdateRedirect(e.aliveCtx, visMeta, proxyID, e, proxyWaitGroup)
if err != nil {
revertStack.Revert() // Ignore errors while reverting. This is best-effort.
return err, nil, nil
}
finalizeList.Append(finalizeFunc)
revertStack.Push(revertFunc)
if e.realizedRedirects == nil {
e.realizedRedirects = make(map[string]uint16)
}
if _, found := e.realizedRedirects[proxyID]; !found {
revertStack.Push(func() error {
delete(e.realizedRedirects, proxyID)
return nil
})
}
e.realizedRedirects[proxyID] = redirectPort
desiredRedirects[proxyID] = true
// Update the endpoint API model to report that Cilium manages a
// redirect for that port.
e.proxyStatisticsMutex.Lock()
proxyStats := e.getProxyStatisticsLocked(proxyID, string(visMeta.Parser), visMeta.Port, visMeta.Ingress)
proxyStats.AllocatedProxyPort = int64(redirectPort)
e.proxyStatisticsMutex.Unlock()
updatedStats = append(updatedStats, proxyStats)
e.desiredPolicy.GetPolicyMap().AddVisibilityKeys(e, redirectPort, visMeta, changes)
}
revertStack.Push(func() error {
// Restore the proxy stats.
e.proxyStatisticsMutex.Lock()
for _, stats := range updatedStats {
stats.AllocatedProxyPort = 0
}
e.proxyStatisticsMutex.Unlock()
// Restore the desired policy map state.
e.desiredPolicy.GetPolicyMap().RevertChanges(changes)
return nil
})
return nil, finalizeList.Finalize, revertStack.Revert
}
// addNewRedirects must be called while holding the endpoint lock for writing.
// On success, returns nil; otherwise, returns an error indicating the problem
// that occurred while adding an l7 redirect for the specified policy.
// The returned map contains the exact set of IDs of proxy redirects that is
// required to implement the given L4 policy.
// Must be called with endpoint.mutex Lock()ed.
func (e *Endpoint) addNewRedirects(proxyWaitGroup *completion.WaitGroup) (desiredRedirects map[string]bool, err error, finalizeFunc revert.FinalizeFunc, revertFunc revert.RevertFunc) {
var (
finalizeList revert.FinalizeList
revertStack revert.RevertStack
ff revert.FinalizeFunc
rf revert.RevertFunc
)
defer func() {
// In case updates partially succeeded, and subsequently failed,
// revert.
if err != nil {
revertStack.Revert()
}
}()
desiredRedirects = make(map[string]bool)
for dirLogStr, ingress := range map[string]bool{"ingress": true, "egress": false} {
err, ff, rf = e.addNewRedirectsFromDesiredPolicy(ingress, desiredRedirects, proxyWaitGroup)
if err != nil {
return desiredRedirects, fmt.Errorf("unable to allocate %s redirects: %s", dirLogStr, err), nil, nil
}
finalizeList.Append(ff)
revertStack.Push(rf)
err, ff, rf = e.addVisibilityRedirects(ingress, desiredRedirects, proxyWaitGroup)
if err != nil {
return desiredRedirects, fmt.Errorf("unable to allocate %s visibility redirects: %s", dirLogStr, err), nil, nil
}
finalizeList.Append(ff)
revertStack.Push(rf)
}
return desiredRedirects, nil, finalizeList.Finalize, func() error {
e.getLogger().Debug("Reverting proxy redirect additions")
err := revertStack.Revert()
e.getLogger().Debug("Finished reverting proxy redirect additions")
return err
}
}
// Must be called with endpoint.mutex Lock()ed.
func (e *Endpoint) removeOldRedirects(desiredRedirects map[string]bool, proxyWaitGroup *completion.WaitGroup) (revert.FinalizeFunc, revert.RevertFunc) {
if option.Config.DryMode {
return nil, nil
}
var finalizeList revert.FinalizeList
var revertStack revert.RevertStack
removedRedirects := make(map[string]uint16, len(e.realizedRedirects))
updatedStats := make(map[uint16]*models.ProxyStatistics, len(e.realizedRedirects))
for id, redirectPort := range e.realizedRedirects {
// Remove only the redirects that are not required.
if desiredRedirects[id] {
continue
}
err, finalizeFunc, revertFunc := e.proxy.RemoveRedirect(id, proxyWaitGroup)
if err != nil {
e.getLogger().WithError(err).WithField(logfields.L4PolicyID, id).Warn("Error while removing proxy redirect")
continue
}
finalizeList.Append(finalizeFunc)
revertStack.Push(revertFunc)
delete(e.realizedRedirects, id)
removedRedirects[id] = redirectPort
// Update the endpoint API model to report that no redirect is
// active or known for that port anymore. We never delete stats
// until an endpoint is deleted, so we only set the redirect port
// to 0.
e.proxyStatisticsMutex.Lock()
if proxyStats, ok := e.proxyStatistics[id]; ok {
updatedStats[redirectPort] = proxyStats
proxyStats.AllocatedProxyPort = 0
} else {
e.getLogger().WithField(logfields.L4PolicyID, id).Warn("Proxy stats not found")
}
e.proxyStatisticsMutex.Unlock()
}
return finalizeList.Finalize,
func() error {
e.getLogger().Debug("Reverting proxy redirect removals")
// Restore the proxy stats.
e.proxyStatisticsMutex.Lock()
for redirectPort, stats := range updatedStats {
stats.AllocatedProxyPort = int64(redirectPort)
}
e.proxyStatisticsMutex.Unlock()
for id, redirectPort := range removedRedirects {
e.realizedRedirects[id] = redirectPort
}
err := revertStack.Revert()
e.getLogger().Debug("Finished reverting proxy redirect removals")
return err
}
}
// regenerateBPF rewrites all headers and updates all BPF maps to reflect the
// specified endpoint.
// ReloadDatapath forces the datapath programs to be reloaded. It does
// not guarantee recompilation of the programs.
// Must be called with endpoint.mutex not held and endpoint.buildMutex held.
//
// Returns the policy revision number when the regeneration has called,
// Whether the new state dir is populated with all new BPF state files,
// and an error if something failed.
func (e *Endpoint) regenerateBPF(regenContext *regenerationContext) (revnum uint64, stateDirComplete bool, reterr error) {
var (
err error
compilationExecuted bool
headerfileChanged bool
)
stats := ®enContext.Stats
stats.waitingForLock.Start()
datapathRegenCtxt := regenContext.datapathRegenerationContext
// Make sure that owner is not compiling base programs while we are
// regenerating an endpoint.
e.owner.GetCompilationLock().RLock()
stats.waitingForLock.End(true)
defer e.owner.GetCompilationLock().RUnlock()
datapathRegenCtxt.prepareForProxyUpdates(regenContext.parentContext)
defer datapathRegenCtxt.completionCancel()
// The following DNS rules code was previously inside the critical section
// below (runPreCompilationSteps()), but this caused a deadlock with the
// IPCache. Therefore, we obtain the DNSRules outside the critical section.
rules := e.owner.GetDNSRules(e.ID)
headerfileChanged, err = e.runPreCompilationSteps(regenContext, rules)
// Keep track of the side-effects of the regeneration that need to be
// reverted in case of failure.
// Also keep track of the regeneration finalization code that can't be
// reverted, and execute it in case of regeneration success.
defer func() {
// Ignore finalizing of proxy state in dry mode.
if !option.Config.DryMode {
e.finalizeProxyState(regenContext, reterr)
}
}()
if err != nil {
return 0, false, err
}
// No need to compile BPF in dry mode.
if option.Config.DryMode {
return e.nextPolicyRevision, false, nil
}
// Skip BPF if the endpoint has no policy map
if !e.HasBPFPolicyMap() {
// Allow another builder to start while we wait for the proxy
if regenContext.DoneFunc != nil {
regenContext.DoneFunc()
}
stats.proxyWaitForAck.Start()
err = e.waitForProxyCompletions(datapathRegenCtxt.proxyWaitGroup)
stats.proxyWaitForAck.End(err == nil)
if err != nil {
return 0, false, fmt.Errorf("Error while updating network policy: %s", err)
}
return e.nextPolicyRevision, false, nil
}
// Wait for connection tracking cleaning to complete
stats.waitingForCTClean.Start()
<-datapathRegenCtxt.ctCleaned
stats.waitingForCTClean.End(true)
compilationExecuted, err = e.realizeBPFState(regenContext)
if err != nil {
return datapathRegenCtxt.epInfoCache.revision, compilationExecuted, err
}
if !datapathRegenCtxt.epInfoCache.IsHost() || option.Config.EnableHostFirewall {
// Hook the endpoint into the endpoint and endpoint to policy tables then expose it
stats.mapSync.Start()
err = lxcmap.WriteEndpoint(datapathRegenCtxt.epInfoCache)
stats.mapSync.End(err == nil)
if err != nil {
return 0, compilationExecuted, fmt.Errorf("Exposing new BPF failed: %s", err)
}
}
// Signal that BPF program has been generated.
// The endpoint has at least L3/L4 connectivity at this point.
e.closeBPFProgramChannel()
// Allow another builder to start while we wait for the proxy
if regenContext.DoneFunc != nil {
regenContext.DoneFunc()
}
stats.proxyWaitForAck.Start()
err = e.waitForProxyCompletions(datapathRegenCtxt.proxyWaitGroup)
stats.proxyWaitForAck.End(err == nil)
if err != nil {
return 0, compilationExecuted, fmt.Errorf("Error while configuring proxy redirects: %s", err)
}
stats.waitingForLock.Start()
err = e.lockAlive()
stats.waitingForLock.End(err == nil)
if err != nil {
return 0, compilationExecuted, err
}
defer e.unlock()
e.ctCleaned = true
// Synchronously try to update PolicyMap for this endpoint. If any
// part of updating the PolicyMap fails, bail out.
// Unfortunately, this means that the map will be in an inconsistent
// state with the current program (if it exists) for this endpoint.
// GH-3897 would fix this by creating a new map to do an atomic swap
// with the old one.
//
// This must be done after allocating the new redirects, to update the
// policy map with the new proxy ports.
stats.mapSync.Start()
err = e.syncPolicyMap()
stats.mapSync.End(err == nil)
if err != nil {
return 0, compilationExecuted, fmt.Errorf("unable to regenerate policy because PolicyMap synchronization failed: %s", err)
}
stateDirComplete = headerfileChanged && compilationExecuted
return datapathRegenCtxt.epInfoCache.revision, stateDirComplete, err
}
func (e *Endpoint) realizeBPFState(regenContext *regenerationContext) (compilationExecuted bool, err error) {
stats := ®enContext.Stats
datapathRegenCtxt := regenContext.datapathRegenerationContext
debugEnabled := logging.CanLogAt(e.getLogger().Logger, logrus.DebugLevel)
if debugEnabled {
e.getLogger().WithFields(logrus.Fields{fieldRegenLevel: datapathRegenCtxt.regenerationLevel}).Debug("Preparing to compile BPF")
}
if datapathRegenCtxt.regenerationLevel > regeneration.RegenerateWithoutDatapath {
if debugEnabled {
debugFunc := log.WithFields(logrus.Fields{logfields.EndpointID: e.StringID()}).Debugf
ctx, cancel := context.WithCancel(regenContext.parentContext)
defer cancel()
loadinfo.LogPeriodicSystemLoad(ctx, debugFunc, time.Second)
}
// Compile and install BPF programs for this endpoint
if datapathRegenCtxt.regenerationLevel == regeneration.RegenerateWithDatapathRebuild {
err = e.owner.Datapath().Loader().CompileAndLoad(datapathRegenCtxt.completionCtx, datapathRegenCtxt.epInfoCache, &stats.datapathRealization)
e.getLogger().WithError(err).Info("Regenerated endpoint BPF program")
compilationExecuted = true
} else if datapathRegenCtxt.regenerationLevel == regeneration.RegenerateWithDatapathRewrite {
err = e.owner.Datapath().Loader().CompileOrLoad(datapathRegenCtxt.completionCtx, datapathRegenCtxt.epInfoCache, &stats.datapathRealization)
if err == nil {
e.getLogger().Info("Rewrote endpoint BPF program")
} else if !errors.Is(err, context.Canceled) {
e.getLogger().WithError(err).Error("Error while rewriting endpoint BPF program")
}
compilationExecuted = true
} else { // RegenerateWithDatapathLoad
err = e.owner.Datapath().Loader().ReloadDatapath(datapathRegenCtxt.completionCtx, datapathRegenCtxt.epInfoCache, &stats.datapathRealization)
if err == nil {
e.getLogger().Info("Reloaded endpoint BPF program")
} else {
e.getLogger().WithError(err).Error("Error while reloading endpoint BPF program")
}
}
if err != nil {
return compilationExecuted, err
}
e.bpfHeaderfileHash = datapathRegenCtxt.bpfHeaderfilesHash
} else if debugEnabled {
e.getLogger().WithField(logfields.BPFHeaderfileHash, datapathRegenCtxt.bpfHeaderfilesHash).
Debug("BPF header file unchanged, skipping BPF compilation and installation")
}
return compilationExecuted, nil
}
// runPreCompilationSteps runs all of the regeneration steps that are necessary
// right before compiling the BPF for the given endpoint.
// The endpoint mutex must not be held.
//
// Returns whether the headerfile changed and/or an error.
func (e *Endpoint) runPreCompilationSteps(regenContext *regenerationContext, rules restore.DNSRules) (headerfileChanged bool, preCompilationError error) {
stats := ®enContext.Stats
datapathRegenCtxt := regenContext.datapathRegenerationContext
// regenerate policy without holding the lock.
// This is because policy generation needs the ipcache to make progress, and the ipcache needs to call
// endpoint.ApplyPolicyMapChanges()
stats.policyCalculation.Start()
policyResult, err := e.regeneratePolicy()
stats.policyCalculation.End(err == nil)
if err != nil {
return false, fmt.Errorf("unable to regenerate policy for '%s': %w", e.StringID(), err)
}
stats.waitingForLock.Start()
err = e.lockAlive()
stats.waitingForLock.End(err == nil)
if err != nil {
return false, err
}
defer e.unlock()
currentDir := datapathRegenCtxt.currentDir
nextDir := datapathRegenCtxt.nextDir
// In the first ever regeneration of the endpoint, the conntrack table
// is cleaned from the new endpoint IPs as it is guaranteed that any
// pre-existing connections using that IP are now invalid.
if !e.ctCleaned {
go func() {
if !option.Config.DryMode {
ipv4 := option.Config.EnableIPv4
ipv6 := option.Config.EnableIPv6
exists := ctmap.Exists(nil, ipv4, ipv6)
if e.ConntrackLocal() {
exists = ctmap.Exists(e, ipv4, ipv6)
}
if exists {
e.scrubIPsInConntrackTable()
}
}
close(datapathRegenCtxt.ctCleaned)
}()
} else {
close(datapathRegenCtxt.ctCleaned)
}
// Set the computed policy as the "incoming" policy. This can fail if
// the endpoint's security identity changed during or after policy calculation.
if err := e.setDesiredPolicy(policyResult); err != nil {
return false, err
}
// We cannot obtain the rules while e.mutex is held, because obtaining
// fresh DNSRules requires the IPCache lock (which must not be taken while
// holding e.mutex to avoid deadlocks). Therefore, rules are obtained
// before the call to runPreCompilationSteps.
e.OnDNSPolicyUpdateLocked(rules)
// If dry mode is enabled, no further changes to BPF maps are performed
if option.Config.DryMode {
_ = e.updateAndOverrideEndpointOptions(nil)
// Dry mode needs Network Policy Updates, but the proxy wait group must
// not be initialized, as there is no proxy ACKing the changes.
if err, _ = e.updateNetworkPolicy(nil); err != nil {
return false, err
}
if err = e.writeHeaderfile(nextDir); err != nil {
return false, fmt.Errorf("Unable to write header file: %s", err)
}
if logging.CanLogAt(log.Logger, logrus.DebugLevel) {
log.WithField(logfields.EndpointID, e.ID).Debug("Skipping bpf updates due to dry mode")
}
return false, nil
}
// Endpoints without policy maps only need Network Policy Updates
if !e.HasBPFPolicyMap() {
if logging.CanLogAt(log.Logger, logrus.DebugLevel) {
log.WithField(logfields.EndpointID, e.ID).Debug("Ingress Endpoint skipping bpf regeneration")
}
if e.SecurityIdentity != nil {
_ = e.updateAndOverrideEndpointOptions(nil)
if logging.CanLogAt(log.Logger, logrus.DebugLevel) {
log.WithField(logfields.EndpointID, e.ID).Debug("Ingress Endpoint updating Network policy")
}
stats.proxyPolicyCalculation.Start()
err, networkPolicyRevertFunc := e.updateNetworkPolicy(datapathRegenCtxt.proxyWaitGroup)
stats.proxyPolicyCalculation.End(err == nil)
if err != nil {
return false, err
}
datapathRegenCtxt.revertStack.Push(networkPolicyRevertFunc)
}
return false, nil
}
if e.policyMap == nil {
e.policyMap, err = policymap.OpenOrCreate(e.policyMapPath())
if err != nil {
return false, err
}
// Synchronize the in-memory realized state with BPF map entries,
// so that any potential discrepancy between desired and realized
// state would be dealt with by the following e.syncPolicyMap.
pm, err := e.dumpPolicyMapToMapState()
if err != nil {
return false, err
}
e.realizedPolicy.SetPolicyMap(pm)
e.updatePolicyMapPressureMetric()
}
// Only generate & populate policy map if a security identity is set up for
// this endpoint.
if e.SecurityIdentity != nil {
_ = e.updateAndOverrideEndpointOptions(nil)
// Walk the L4Policy to add new redirects and update the desired policy for existing redirects.
// Do this before updating the bpf policy maps, so that the proxies are ready when new traffic
// is redirected to them.
var (
desiredRedirects map[string]bool
finalizeFunc revert.FinalizeFunc
revertFunc revert.RevertFunc
)
if e.desiredPolicy != nil {
stats.proxyConfiguration.Start()
// Deny policies do not support redirects
desiredRedirects, err, finalizeFunc, revertFunc = e.addNewRedirects(datapathRegenCtxt.proxyWaitGroup)
stats.proxyConfiguration.End(err == nil)
if err != nil {
return false, err
}
datapathRegenCtxt.finalizeList.Append(finalizeFunc)
datapathRegenCtxt.revertStack.Push(revertFunc)
}
// Configure the new network policy with the proxies.
//
// This must be done after adding new redirects above, as waiting for policy update ACKs is
// disabled when there are no listeners, which is the case before the first redirect is added.
//
// Do this before updating the bpf policy maps below, so that the proxy listeners have a chance to be
// ready when new traffic is redirected to them.
// note: unlike regeneratePolicy, updateNetworkPolicy requires the endpoint read lock
stats.proxyPolicyCalculation.Start()
err, networkPolicyRevertFunc := e.updateNetworkPolicy(datapathRegenCtxt.proxyWaitGroup)
stats.proxyPolicyCalculation.End(err == nil)
if err != nil {
return false, err
}
datapathRegenCtxt.revertStack.Push(networkPolicyRevertFunc)
// Synchronously try to update PolicyMap for this endpoint. If any
// part of updating the PolicyMap fails, bail out and do not generate
// BPF. Unfortunately, this means that the map will be in an inconsistent
// state with the current program (if it exists) for this endpoint.
// GH-3897 would fix this by creating a new map to do an atomic swap
// with the old one.
stats.mapSync.Start()
err = e.syncPolicyMap()
stats.mapSync.End(err == nil)
if err != nil {
return false, fmt.Errorf("unable to regenerate policy because PolicyMap synchronization failed: %s", err)
}
// At this point, traffic is no longer redirected to the proxy for
// now-obsolete redirects, since we synced the updated policy map above.
// It's now safe to remove the redirects from the proxy's configuration.
stats.proxyConfiguration.Start()
finalizeFunc, revertFunc = e.removeOldRedirects(desiredRedirects, datapathRegenCtxt.proxyWaitGroup)
datapathRegenCtxt.finalizeList.Append(finalizeFunc)
datapathRegenCtxt.revertStack.Push(revertFunc)
stats.proxyConfiguration.End(true)
}
stats.prepareBuild.Start()
defer func() {
stats.prepareBuild.End(preCompilationError == nil)
}()
// Avoid BPF program compilation and installation if the headerfile for the endpoint
// or the node have not changed.
datapathRegenCtxt.bpfHeaderfilesHash, err = e.owner.Datapath().Loader().EndpointHash(e)
if err != nil {
e.getLogger().WithError(err).Warn("Unable to hash header file")
datapathRegenCtxt.bpfHeaderfilesHash = ""
headerfileChanged = true
} else {
headerfileChanged = (datapathRegenCtxt.bpfHeaderfilesHash != e.bpfHeaderfileHash)
if logger := e.getLogger(); logging.CanLogAt(logger.Logger, logrus.DebugLevel) {
logger.WithField(logfields.BPFHeaderfileHash, datapathRegenCtxt.bpfHeaderfilesHash).
Debugf("BPF header file hashed (was: %q)", e.bpfHeaderfileHash)
}
}
if headerfileChanged {
datapathRegenCtxt.regenerationLevel = regeneration.RegenerateWithDatapathRewrite
}
if datapathRegenCtxt.regenerationLevel >= regeneration.RegenerateWithDatapathRewrite {
if err := e.writeHeaderfile(nextDir); err != nil {
return false, fmt.Errorf("unable to write header file: %s", err)
}
}
// Cache endpoint information so that we can release the endpoint lock.
if datapathRegenCtxt.regenerationLevel >= regeneration.RegenerateWithDatapathRewrite {
datapathRegenCtxt.epInfoCache = e.createEpInfoCache(nextDir)
} else {
datapathRegenCtxt.epInfoCache = e.createEpInfoCache(currentDir)
}
if datapathRegenCtxt.epInfoCache == nil {
return headerfileChanged, fmt.Errorf("Unable to cache endpoint information")
}
return headerfileChanged, nil
}
func (e *Endpoint) finalizeProxyState(regenContext *regenerationContext, err error) {
datapathRegenCtx := regenContext.datapathRegenerationContext
if err == nil {
// Always execute the finalization code, even if the endpoint is
// terminating, in order to properly release resources.
e.unconditionalLock()
defer e.unlock() // In case Finalize() panics
e.getLogger().Debug("Finalizing successful endpoint regeneration")
datapathRegenCtx.finalizeList.Finalize()
} else {
if err := e.lockAlive(); err != nil {
e.getLogger().WithError(err).Debug("Skipping unnecessary reverting of endpoint regeneration changes")
return
}
defer e.unlock() // In case Revert() panics
e.getLogger().Debug("Reverting endpoint changes after BPF regeneration failed")
if err := datapathRegenCtx.revertStack.Revert(); err != nil {
e.getLogger().WithError(err).Error("Reverting endpoint regeneration changes failed")
}
e.getLogger().Debug("Finished reverting endpoint changes after BPF regeneration failed")
}
}
// InitMap creates the policy map in the kernel.
func (e *Endpoint) InitMap() error {
return policymap.Create(e.policyMapPath())
}
// deleteMaps releases references to all BPF maps associated with this
// endpoint.
//
// For each error that occurs while releasing these references, an error is
// added to the resulting error slice which is returned.
//
// Returns nil on success.
func (e *Endpoint) deleteMaps() []error {
var errors []error
maps := map[string]string{
"policy": e.policyMapPath(),
"calls": e.callsMapPath(),
}
if !e.isHost {
maps["custom"] = e.customCallsMapPath()
}
for name, path := range maps {
if err := os.RemoveAll(path); err != nil {
errors = append(errors, fmt.Errorf("unable to remove %s map file %s: %s", name, path, err))
}
}
if e.ConntrackLocalLocked() {
// Remove local connection tracking maps
for _, m := range ctmap.LocalMaps(e, option.Config.EnableIPv4, option.Config.EnableIPv6) {
ctPath, err := m.Path()
if err == nil {
err = os.RemoveAll(ctPath)
}
if err != nil {
errors = append(errors, fmt.Errorf("unable to remove CT map %s: %s", ctPath, err))
}
}
}
// Remove handle_policy() tail call entry for EP
if err := policymap.RemoveGlobalMapping(uint32(e.ID), option.Config.EnableEnvoyConfig); err != nil {