forked from neuvector/neuvector
/
engine.go
2043 lines (1793 loc) · 59.3 KB
/
engine.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
package main
// #include "../defs.h"
import "C"
import (
"bytes"
"errors"
"fmt"
"net"
"os"
"reflect"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
log "github.com/sirupsen/logrus"
"github.com/neuvector/neuvector/agent/dp"
"github.com/neuvector/neuvector/agent/pipe"
"github.com/neuvector/neuvector/agent/probe"
"github.com/neuvector/neuvector/share"
"github.com/neuvector/neuvector/share/container"
"github.com/neuvector/neuvector/share/fsmon"
"github.com/neuvector/neuvector/share/global"
"github.com/neuvector/neuvector/share/osutil"
"github.com/neuvector/neuvector/share/utils"
)
const containerWaitParentPeriod time.Duration = (time.Second * 1)
const containerReexamIntfMax time.Duration = (time.Second * 180)
const containerReexamIntfIPv4Min time.Duration = (time.Second * 4)
const containerTaskChanSizeMin = 256
var errHostModeUnsupported = errors.New("Host mode not supported")
var errChildUnsupported = errors.New("Child container not supported")
var containerGracePeriod time.Duration = (time.Second * 1)
var ContainerTaskChan chan *ContainerTask
// inline: If a workload is configured to be inline (not including quarantin case)
// capIntcp: Indicate if a workload can be put inline.
// Platform and host mode containers cannot be intercepted.
// If not interceptable, the container cannot be quarantined
// hasDatapath: parent and non-platform-containers, could be host mode
type containerData struct {
id string
name string
pid int
info *container.ContainerMetaExtra
inline bool
blocking bool
quar bool
capIntcp bool
capBlock bool
hostMode bool
hasDatapath bool
nfq bool
policyMode string
stats share.ContainerStats
intcpPairs []*pipe.InterceptPair
ownListenPorts utils.Set // set of share.CLUSProtoPort. Not merged from children.
appMap map[share.CLUSProtoPort]*share.CLUSApp // Including merged app from children
portMap map[share.CLUSProtoPort]*share.CLUSMappedPort
parentNS string
pods utils.Set
service string
domain string
role string
svcSubnet *net.IPNet
cgroupMemory string
cgroupCPUAcct string
rootFs string
upperDir string
propertyFilled bool
benchReported bool
pushPHistory bool
scanCache []byte
}
// All information inside localSystemInfo is protected by mutex,
// and is only modified by docker task thread. Sending info to DP
// needs to grab dpMsg lock, so be careful to avoid lock embedding
type localSystemInfo struct {
mutex sync.RWMutex
hostScanCache []byte
activeContainers map[string]*containerData
neuContainers map[string]*containerData // separate them from normal containers
activePid2ID map[int]string
allContainers utils.Set
macContainerMap map[string]string
macPortPairMap map[string]*pipe.InterceptPair
// network info read from docker daemon
networks map[string]*container.Network
networkLBs map[string]*container.NetworkEndpoint
// all subnets that local containers connect to, including overlay
// and local bridge subnets
localSubnetMap map[string]share.CLUSSubnet
// all subnets that all containers in the cluster connect to, including
// local subnets and subnets populated from controller
internalSubnets map[string]share.CLUSSubnet
containerConfig map[string]*share.CLUSWorkloadConfig
policyMode string
agentConfig share.CLUSAgentConfig
agentStats share.ContainerStats
hostIPs utils.Set
tapProxymesh bool
jumboFrameMTU bool
xffEnabled bool
}
var defaultPolicyMode string = share.PolicyModeLearn
var defaultTapProxymesh bool = true
var defaultXffEnabled bool = true
var specialSubnets map[string]share.CLUSSpecSubnet = make(map[string]share.CLUSSpecSubnet)
var rtStorageDriver string
var gInfo localSystemInfo = localSystemInfo{
networks: make(map[string]*container.Network),
networkLBs: make(map[string]*container.NetworkEndpoint),
activeContainers: make(map[string]*containerData),
neuContainers: make(map[string]*containerData),
activePid2ID: make(map[int]string),
allContainers: utils.NewSet(),
macContainerMap: make(map[string]string),
macPortPairMap: make(map[string]*pipe.InterceptPair),
localSubnetMap: make(map[string]share.CLUSSubnet),
internalSubnets: make(map[string]share.CLUSSubnet),
containerConfig: make(map[string]*share.CLUSWorkloadConfig),
policyMode: defaultPolicyMode,
agentConfig: share.CLUSAgentConfig{Debug: make([]string, 0)},
hostIPs: utils.NewSet(),
tapProxymesh: defaultTapProxymesh,
jumboFrameMTU: false,
xffEnabled: defaultXffEnabled,
}
func gInfoLock() {
//log.WithFields(log.Fields{"goroutine": utils.GetGID()}).Debug("PROC: ")
gInfo.mutex.Lock()
}
func gInfoUnlock() {
//log.WithFields(log.Fields{"goroutine": utils.GetGID()}).Debug("PROC: ")
gInfo.mutex.Unlock()
}
func gInfoRLock() {
//log.WithFields(log.Fields{"goroutine": utils.GetGID()}).Debug("PROC: ")
gInfo.mutex.RLock()
}
func gInfoRUnlock() {
//log.WithFields(log.Fields{"goroutine": utils.GetGID()}).Debug("PROC: ")
gInfo.mutex.RUnlock()
}
func getContainerByMAC(mac net.HardwareAddr) *containerData {
gInfoRLock()
defer gInfoRUnlock()
if id, ok := gInfo.macContainerMap[mac.String()]; ok {
if c, ok := gInfo.activeContainers[id]; ok {
return c
}
}
return nil
}
func isLocalHostIP(ip net.IP) bool {
gInfoRLock()
defer gInfoRUnlock()
return gInfo.hostIPs.Contains(ip.String())
}
func isIPInternal(ip net.IP) bool {
if ip.IsLoopback() {
return true
}
for _, subnet := range gInfo.internalSubnets {
if subnet.Subnet.Contains(ip) {
return true
}
}
return false
}
func isContainerNetHostMode(info *container.ContainerMetaExtra, parent *containerData) bool {
if info.NetMode == "host" || (parent != nil && parent.info.NetMode == "host") {
return true
}
return false
}
// TODO: add more verifications to exclude hacker containers
func nvPod2Role(pod string) string {
// Assume the pod name must be of pattern, neuvector-controller-pod-xxxx or dss-controller-pod-xxxx (OEM)
if !strings.HasPrefix(pod, "neuvector-") && !strings.HasPrefix(pod, "dss-") {
return ""
}
role := pod
if index := strings.LastIndex(role, "-pod"); index != -1 {
role = role[:index]
if index = strings.Index(role, "-"); index != -1 {
role = role[index+1:]
return role
} else {
return ""
}
} else {
return ""
}
}
func isNeuvectorFunctionRole(role string, rootPid int) bool {
// log.WithFields(log.Fields{"role": role, "pid": rootPid}).Debug("PROC:")
// 1st screening
entryPtSig := ""
// assumptions: user does not modify the production yaml
switch role { // role or simplified podname
case "controller+enforcer", "enforcer", "controller", "scanner":
entryPtSig = "/usr/local/bin/monitor"
case "manager":
entryPtSig = "/usr/local/bin/admin-assembly-" // partial library name
case "controller+enforcer+manager", "allinone":
entryPtSig = "/usr/bin/supervisord" // a python app
case "updater":
entryPtSig = "/usr/local/bin/upgrader"
case "fetcher":
entryPtSig = "/usr/local/bin/fetcher"
default:
// log.WithFields(log.Fields{"invalid role": role}).Debug("PROC:")
return false // exclude others
}
// passed the 1st screening
// 2nd screening: handle the exited child container at the last part
if rootPid == 0 {
log.Debug("invalid root pid")
return true // skipped the test
}
if cmds, err := global.SYS.ReadCmdLine(rootPid); err == nil && len(cmds) > 0 {
// log.WithFields(log.Fields{"role": role, "cmds": cmds}).Debug("PROC:")
for _, cmd := range cmds {
if strings.HasPrefix(cmd, entryPtSig) { // matched at least two criteria
return true
}
}
}
return false
}
func isNeuVectorContainer(info *container.ContainerMetaExtra) (string, bool) {
labels := info.Labels
if Agent.Domain != "" && Agent.Domain != global.ORCH.GetDomain(labels) { // orchestra
return "", false
}
// only for docker runtime engine
// not present for controller, updater releases
// if vendor, ok := labels["vendor"]; !ok || vendor != "NeuVector Inc." {
// log.WithFields(log.Fields{"labels": labels}).Debug("PROC")
// return "", false
// }
// only for docker runtime engine (inc docker native)
if role, ok := labels[share.NeuVectorLabelRole]; ok {
// log.WithFields(log.Fields{"labels": labels}).Debug("PROC")
if isNeuvectorFunctionRole(role, info.Pid) {
return role, true
}
}
// orchestra platforms
if podname, ok := labels[container.KubeKeyPodName]; ok {
role := nvPod2Role(podname)
if role == "" {
return "", false
}
if isNeuvectorFunctionRole(role, info.Pid) {
return role, true
}
// POD for neuvector
if isChild, _ := getSharedContainer(info); !isChild {
// log.WithFields(log.Fields{"labels": labels, "podname": podname}).Debug("PROC: POD")
return role, true
} else { // a child
if !info.Running {
// and exited neuvector containers
return role, true
}
}
}
return "", false
}
func isSidecarContainer(labels map[string]string) bool {
//check if container is a sidecar that is linkerd-proxy or istio-proxy
sc_containername, _ := labels[container.KubeKeyContainerName]
if strings.Contains(sc_containername, container.KubeLinkerdProxyName) ||
strings.Contains(sc_containername, container.KubeIstioProxyName) ||
strings.Contains(sc_containername, container.KubeAwsProxyName) {
return true
}
return false
}
func runtimeEventCallback(ev container.Event, id string, pid int) {
switch ev {
case container.EventContainerStart:
task := ContainerTask{task: TASK_ADD_CONTAINER, id: id}
ContainerTaskChan <- &task
case container.EventContainerStop:
// containerd runtime report TaskExit for both process stop and container stop.
// Here is to make sure the pid is container's pid and avoid writing event log
if pid != 0 {
gInfoRLock()
_, ok := gInfo.activePid2ID[pid]
gInfoRUnlock()
if !ok {
return
}
}
task := ContainerTask{task: TASK_STOP_CONTAINER, id: id, pid: pid}
ContainerTaskChan <- &task
case container.EventContainerDelete:
task := ContainerTask{task: TASK_DEL_CONTAINER, id: id}
ContainerTaskChan <- &task
case container.EventContainerCopyIn:
gInfoRLock()
defer gInfoRUnlock()
if c, ok := gInfo.activeContainers[id]; ok {
prober.ReportDockerCp(id, c.name, true)
} else if isAgentContainer(id) {
prober.ReportDockerCp(id, Agent.Name, true)
}
case container.EventContainerCopyOut:
gInfoRLock()
defer gInfoRUnlock()
if c, ok := gInfo.activeContainers[id]; ok {
prober.ReportDockerCp(id, c.name, false)
} else if isAgentContainer(id) {
prober.ReportDockerCp(id, Agent.Name, false)
}
case container.EventNetworkCreate:
// ignore network creatation for now, the special lb-net endpoint is detected when new container starts
case container.EventNetworkDelete:
handleNetworkDelete(id)
case container.EventSocketError:
monitorExitChan <- nil
}
}
// with gInfoLock held
func refreshLocalSubnets() bool {
subnetMap := make(map[string]share.CLUSSubnet)
addHostSubnets(Host.Ifaces, subnetMap)
for _, c := range gInfo.activeContainers {
addContainerSubnets(c, subnetMap)
}
if reflect.DeepEqual(gInfo.localSubnetMap, subnetMap) {
return false
} else {
gInfo.localSubnetMap = subnetMap
return mergeLocalSubnets(gInfo.internalSubnets)
}
}
// with gInfoLock held
func addContainerSubnets(c *containerData, subnetMap map[string]share.CLUSSubnet) bool {
var new bool
// Add subnets used by containers
for _, pair := range c.intcpPairs {
for _, addr := range pair.Addrs {
subnet := utils.IPNet2SubnetLoose(&addr.IPNet, addr.Scope)
if _, ok := subnetMap[subnet.String()]; !ok {
subnetMap[subnet.String()] = share.CLUSSubnet{Subnet: *subnet, Scope: addr.Scope}
new = true
}
}
}
// Add all local bridge subnets. Even the subnet is not used by any containers,
// the gateway IP (172.17.0.1) can be used to reach other containers on different
// subnets (172.18.0.0)
for _, network := range gInfo.networks {
if network.Scope == container.DockerNetworkLocal {
for _, subnet := range network.Subnets {
if _, ok := subnetMap[subnet.String()]; !ok {
subnetMap[subnet.String()] = share.CLUSSubnet{
Subnet: *subnet, Scope: share.CLUSIPAddrScopeLocalhost,
}
new = true
}
}
}
}
// Service IPs are in a different subnet in Kubernetes, if we don't learn it at the
// enforcer, connections are marked as 'external' before internal subnets are pushed
// from the controllers.
if c.svcSubnet != nil {
subnet := utils.IPNet2SubnetLoose(c.svcSubnet, share.CLUSIPAddrScopeGlobal)
if _, ok := subnetMap[subnet.String()]; !ok {
subnetMap[subnet.String()] = share.CLUSSubnet{
Subnet: *subnet, Scope: share.CLUSIPAddrScopeGlobal,
}
new = true
}
}
return new
}
func addHostSubnets(ifaces map[string][]share.CLUSIPAddr, subnetMap map[string]share.CLUSSubnet) {
for _, addrs := range ifaces {
for _, addr := range addrs {
subnet := utils.IPNet2SubnetLoose(&addr.IPNet, share.CLUSIPAddrScopeNAT)
if _, ok := subnetMap[subnet.String()]; !ok {
subnetMap[subnet.String()] = share.CLUSSubnet{Subnet: *subnet, Scope: addr.Scope}
}
}
}
}
func notifyDPContainerApps(c *containerData) {
if c.hostMode || !c.hasDatapath {
return
}
macs := make([]string, len(c.intcpPairs))
for i, pair := range c.intcpPairs {
macs[i] = pair.MAC.String()
}
if gInfo.tapProxymesh && c.info.ProxyMesh {
lomac_str := fmt.Sprintf(container.KubeProxyMeshLoMacStr, (c.pid>>8)&0xff, c.pid&0xff)
macs = append(macs, lomac_str)
}
if len(macs) == 0 {
log.WithFields(log.Fields{"container": c.id}).Error("No interface!!")
return
}
dp.DPCtrlConfigMAC(macs, nil, c.appMap)
}
func updatePods(c *containerData, quarReason *string) {
if c.pods.Cardinality() > 0 {
for pod := range c.pods.Iter() {
if pc, ok := gInfo.activeContainers[pod.(string)]; ok {
pc.inline = c.inline
pc.quar = c.quar
ClusterEventChan <- &ClusterEvent{
event: EV_UPDATE_CONTAINER, id: pc.id, inline: &pc.inline, quar: &pc.quar,
quarReason: quarReason,
}
}
}
}
}
func changeContainerWire(c *containerData, inline bool, quar bool, quarReason *string) {
// If inline and it doesn't change, and only quarantine state is chagned => only need change bridge rules
if c.inline && inline {
c.inline = inline
c.quar = quar
programBridge(c)
} else {
c.inline = inline
c.quar = quar
_, _, _, _, err := programUpdatePairs(c, true)
if err == nil {
programBridge(c)
programDP(c, false, nil)
if gInfo.tapProxymesh {
programProxyMeshDP(c, false, true)
updateProxyMeshMac(c, false)
}
}
}
ClusterEventChan <- &ClusterEvent{
event: EV_UPDATE_CONTAINER, id: c.id, inline: &c.inline,
quar: &c.quar, quarReason: quarReason,
}
updatePods(c, quarReason)
}
func updateProxyMeshMac(c *containerData, withlock bool) {
if c.info.ProxyMesh == false {
return
}
//POD with proxy injection
lomac_str := fmt.Sprintf(container.KubeProxyMeshLoMacStr, (c.pid>>8)&0xff, c.pid&0xff)
log.WithFields(log.Fields{"lomac_str": lomac_str, "pid": c.pid}).Debug("tap proxymesh's loopback intf")
if !withlock {
gInfoLock()
}
gInfo.macContainerMap[lomac_str] = c.id
if !withlock {
gInfoUnlock()
}
}
func delProxyMeshMac(c *containerData, withlock bool) {
if c.info.ProxyMesh == false {
return
}
lomac_str := fmt.Sprintf(container.KubeProxyMeshLoMacStr, (c.pid>>8)&0xff, c.pid&0xff)
log.WithFields(log.Fields{"lomac_str": lomac_str, "pid": c.pid}).Debug("Delete tap proxymesh's loopback intf")
if !withlock {
gInfoLock()
}
delete(gInfo.macContainerMap, lomac_str)
if !withlock {
gInfoUnlock()
}
}
func getProxyMeshAppMap(c *containerData) map[share.CLUSProtoPort]*share.CLUSApp {
proxyMeshApp := make(map[share.CLUSProtoPort]*share.CLUSApp)
for port, app := range c.appMap {
proxyMeshApp[port] = app
}
for podID := range c.pods.Iter() { //c is parent
if pod, ok := gInfo.activeContainers[podID.(string)]; ok && !pod.info.Sidecar {
for port, app := range pod.appMap {
_, ok := proxyMeshApp[port]
if !ok {
proxyMeshApp[port] = app
}
}
}
}
return proxyMeshApp
}
func programProxyMeshDP(c *containerData, cfgApp, restore bool) {
if c.info.ProxyMesh == false { //parent only
return
}
log.WithFields(log.Fields{"container": c.id}).Debug("proxymesh")
netns := global.SYS.GetNetNamespacePath(c.pid)
macs := make([]string, 1)
tap := false
//tap lo interface for POD that inject proxy
// 6c:6b:73:74 - lkst
var lomac_str string
var lo_oldmac, lo_mac, lo_umac, lo_bmac net.HardwareAddr
lomac_str = fmt.Sprintf(container.KubeProxyMeshLoMacStr, (c.pid>>8)&0xff, c.pid&0xff)
lo_mac, _ = net.ParseMAC(lomac_str)
//pass parent containers IP to service mesh ep so that
//when src/dst IP are both 127.0.0.x, we can replace dst
//IP with parent containers IP to do XFF related policy match
pAddrs := make([]net.IP, 0)
for _, pair := range c.intcpPairs {
for _, addr := range pair.Addrs {
pAddrs = append(pAddrs, addr.IPNet.IP)
}
}
if c.quar || c.inline {
dp.DPCtrlDelTapPort(netns, "lo")
for _, pair := range c.intcpPairs {
//for proxymesh endpoint, we need pair.MAC for policy matching in DP,
//all pair.MAC point to same policy handle in DP, use only one
dp.DPCtrlAddMAC("lo", lo_mac, lo_umac, lo_bmac, lo_oldmac, pair.MAC, pAddrs)
break
}
//traffic between sidecar proxy and app container cannot be enforced
//as regular veth pair, we need to set up iptable rules with NFQUEUE
//in container's namespace, and dp need to create nfq handle(nfq_open)
proxyMeshApp := getProxyMeshAppMap(c)
if c.nfq == false {
err := pipe.CreateNfqRules(c.pid, true, proxyMeshApp)
if err != nil {
log.WithFields(log.Fields{"container": c.id, "error": err}).Error("Failed to create nfq iptable rules")
} else {
c.nfq = true
jumboFrame := gInfo.jumboFrameMTU
//create dp nfq handle
dp.DPCtrlAddNfqPort(netns, "lo", lo_mac, &jumboFrame)
}
} else {
pipe.CreateNfqRules(c.pid, false, proxyMeshApp)
jumboFrame := gInfo.jumboFrameMTU
//create dp nfq handle
dp.DPCtrlAddNfqPort(netns, "lo", lo_mac, &jumboFrame)
}
} else {
if restore {
//delete dp nfq handle first before reset iptable rules
dp.DPCtrlDelNfqPort(netns, "lo")
}
dp.DPCtrlAddTapPort(netns, "lo", lo_mac)
for _, pair := range c.intcpPairs {
//for proxymesh endpoint, we need pair.MAC for policy matching in DP,
//all pair.MAC point to same policy handle in DP, use only one
dp.DPCtrlAddMAC("lo", lo_mac, lo_umac, lo_bmac, lo_oldmac, pair.MAC, pAddrs)
break
}
tap = true
}
macs[len(macs)-1] = lo_mac.String()
if cfgApp {
dp.DPCtrlConfigMAC(macs, &tap, c.appMap)
} else {
dp.DPCtrlConfigMAC(macs, &tap, nil)
}
}
func programDelProxyMeshDP(c *containerData, ns string) {
if c.info.ProxyMesh == false {
return
}
var netns string
netns = ns
if ns == "" {
netns = global.SYS.GetNetNamespacePath(c.pid)
}
//POD with proxy injection
// 6c:6b:73:74 - lkst
var lomac_str string
var lo_mac net.HardwareAddr
lomac_str = fmt.Sprintf(container.KubeProxyMeshLoMacStr, (c.pid>>8)&0xff, c.pid&0xff)
lo_mac, _ = net.ParseMAC(lomac_str)
if c.quar || c.inline {
//delete dp nfq handle if any then reset iptable rules
dp.DPCtrlDelNfqPort(netns, "lo")
pipe.DeleteNfqRules(c.pid)
c.nfq = false
dp.DPCtrlDelMAC("lo", lo_mac)
} else {
pipe.DeleteNfqRules(c.pid)
c.nfq = false
dp.DPCtrlDelTapPort(netns, "lo")
dp.DPCtrlDelMAC("lo", lo_mac)
}
}
func enableTapProxymesh(c *containerData) {
updateProxyMeshMac(c, false)
programProxyMeshDP(c, false, false)
}
func disableTapProxymesh(c *containerData) {
programDelProxyMeshDP(c, "")
delProxyMeshMac(c, false)
}
func getContainerIDByName(name string) string {
for id, c := range gInfo.activeContainers {
if c.name == name {
return id
}
}
return ""
}
// Get IP scope by workload MAC and ip address
func getIPAddrScope(mac net.HardwareAddr, ip net.IP) (string, string) {
if pair, ok := gInfo.macPortPairMap[mac.String()]; ok {
for _, addr := range pair.Addrs {
if ip.String() == addr.IPNet.IP.String() {
return addr.Scope, addr.NetworkName
}
}
}
return share.CLUSIPAddrScopeLocalhost, ""
}
// Return if container is child and its parent container.
func getSharedContainer(info *container.ContainerMetaExtra) (bool, *containerData) {
if isChild, parent_cid := global.RT.GetParent(info, gInfo.activePid2ID); parent_cid != "" {
var ok bool
var parent *containerData
if parent, ok = gInfo.activeContainers[parent_cid]; !ok {
if real_parent_cid := getContainerIDByName(parent_cid); real_parent_cid != "" {
parent_cid = real_parent_cid
}
if parent, ok = gInfo.activeContainers[parent_cid]; !ok {
log.WithFields(log.Fields{"net_mode": info.NetMode}).Debug("Skip")
return true, nil
}
}
log.WithFields(log.Fields{"with": parent_cid}).Debug("Share network namespace")
return true, parent
} else {
return isChild, nil
}
}
func intcpPairs2Ifaces(intcpPairs []*pipe.InterceptPair) map[string][]share.CLUSIPAddr {
if intcpPairs != nil {
ifaces := make(map[string][]share.CLUSIPAddr)
for _, pair := range intcpPairs {
ifaces[pair.Port] = pair.Addrs
}
return ifaces
}
return nil
}
const (
changeInit = iota
changeIntf
changeApp
)
var changeName = []string{
changeInit: "init",
changeIntf: "intf",
changeApp: "app",
}
func notifyContainerChanges(c *containerData, parent *containerData, change int) {
log.WithFields(log.Fields{"id": c.id, "change": changeName[change]}).Debug("")
var ev ClusterEvent
if change == changeInit {
capSniff := !c.hostMode
ev = ClusterEvent{
event: EV_ADD_CONTAINER, id: c.id, info: c.info,
service: &c.service, domain: &c.domain, role: &c.role,
inline: &c.inline, quar: &c.quar, shareNetNS: &c.parentNS,
capIntcp: &c.capIntcp, capSniff: &capSniff,
}
} else {
ev = ClusterEvent{
event: EV_UPDATE_CONTAINER, id: c.id,
}
}
var ifaces map[string][]share.CLUSIPAddr
if change == changeInit || change == changeIntf {
if c.hostMode {
ifaces = make(map[string][]share.CLUSIPAddr)
for name, addrs := range Host.Ifaces {
ifaces[name] = addrs
}
} else {
ifaces = intcpPairs2Ifaces(c.intcpPairs)
}
ev.ifaces = ifaces
}
if change == changeInit || change == changeApp {
ev.apps = translateAppMap(c.appMap)
ev.ports = translateMappedPort(c.portMap)
}
ClusterEventChan <- &ev
// When event is changeInit, app/port may already be available,
// need to inform dp because the changeApp event may never come
if change == changeApp || change == changeInit {
if parent == nil {
notifyDPContainerApps(c)
} else {
notifyDPContainerApps(parent)
}
}
if parent == nil {
if change == changeInit || change == changeIntf {
// Notify the children for interface change
for podID := range c.pods.Iter() {
podEv := ClusterEvent{
event: EV_UPDATE_CONTAINER, id: podID.(string), ifaces: ifaces,
}
ClusterEventChan <- &podEv
}
}
} else {
if change == changeInit || change == changeApp {
// App map already populated to parent, send update to cluster channel.
parentEv := ClusterEvent{
event: EV_UPDATE_CONTAINER,
id: parent.id,
info: parent.info,
apps: translateAppMap(parent.appMap),
ports: translateMappedPort(parent.portMap),
}
ClusterEventChan <- &parentEv
}
}
}
// Calling with gInfoLock held
func setIPAddrScope(c *containerData) {
ports := make(map[string][]share.CLUSIPAddr, len(c.intcpPairs))
for _, pair := range c.intcpPairs {
ports[pair.Port] = pair.Addrs
}
global.ORCH.SetIPAddrScope(ports, &c.info.ContainerMeta, gInfo.networks)
}
type containerTimerReq struct {
id string
info *container.ContainerMetaExtra
req int
}
func (p *containerTimerReq) Expire() {
log.WithFields(log.Fields{"id": p.id, "req": ContainerTaskName[p.req]}).Debug("")
task := ContainerTask{task: p.req, id: p.id, info: p.info}
ContainerTaskChan <- &task
}
// This function should only be called on non-host mode parent container
func programUpdatePairs(c *containerData, restore bool) (bool, bool, bool, map[string]*pipe.InterceptPair, error) {
// Program ports and compare change should always be done together, so we won't miss port changes.
intcpPairs, err := programPorts(c, restore)
if err != nil {
return false, false, false, nil, err
}
var intfAdded, addrChanged, subnetChanged bool
macChangePairs := make(map[string]*pipe.InterceptPair)
gInfoLock()
defer gInfoUnlock()
for _, pairOld := range c.intcpPairs {
for _, pairNew := range intcpPairs {
if pairOld.Port == pairNew.Port {
if len(pairOld.Addrs) != len(pairNew.Addrs) {
addrChanged = true
}
if bytes.Compare(pairOld.MAC, pairNew.MAC) != 0 {
delete(gInfo.macContainerMap, pairOld.MAC.String())
delete(gInfo.macPortPairMap, pairOld.MAC.String())
gInfo.macContainerMap[pairNew.MAC.String()] = c.id
gInfo.macPortPairMap[pairNew.MAC.String()] = pairNew
macChangePairs[pairOld.Port] = pairOld
}
break
}
}
}
if len(c.intcpPairs) != len(intcpPairs) {
for _, pair := range intcpPairs {
gInfo.macContainerMap[pair.MAC.String()] = c.id
gInfo.macPortPairMap[pair.MAC.String()] = pair
}
intfAdded = true
}
// When changing between tap and inline, UC/BCMAC, in/exPort all changed. =>
// Always take the new copy and set the scope again
c.intcpPairs = intcpPairs
setIPAddrScope(c)
if intfAdded || addrChanged {
updateContainerNetworks(c, c.info)
if addContainerSubnets(c, gInfo.localSubnetMap) {
subnetChanged = mergeLocalSubnets(gInfo.internalSubnets)
}
}
if intfAdded || addrChanged || len(macChangePairs) > 0 {
for podID := range c.pods.Iter() {
if pod, ok := gInfo.activeContainers[podID.(string)]; ok {
pod.intcpPairs = c.intcpPairs
}
}
}
return intfAdded, addrChanged, subnetChanged, macChangePairs, nil
}
func taskReexamIntfContainer(id string, info *container.ContainerMetaExtra, restartMonitor bool) {
if c, ok := gInfo.neuContainers[id]; ok {
if info != nil && c.pid != info.Pid {
return
}
examNeuVectorInterface(c, changeIntf)
return
}
// Check if the container is the same running instance when event is scheduled.
c, ok := gInfo.activeContainers[id]
if !ok || (info != nil && c.pid != info.Pid) || !c.propertyFilled {
return
}
info = c.info
intfAdded, addrChanged, subnetChanged, macChangePairs, err := programUpdatePairs(c, false)
log.WithFields(log.Fields{
"id": id, "intf": intfAdded, "addr": addrChanged, "subnet": subnetChanged, "mac": len(macChangePairs) > 0,
}).Debug("Container changes")
if err == nil {
if len(macChangePairs) > 0 {
// Reprogram pipe rules (rules are always reset and re-added)
programBridge(c)
// AddTapPort need to be called besides AddMAC in order to update MAC in pkt ring.
programDP(c, false, macChangePairs)
if gInfo.tapProxymesh {
programProxyMeshDP(c, false, false)
updateProxyMeshMac(c, false)
}
} else if intfAdded {
programBridge(c)
programDP(c, false, nil)
if gInfo.tapProxymesh {
programProxyMeshDP(c, false, false)
updateProxyMeshMac(c, false)
}
}
if subnetChanged {
dp.DPCtrlConfigInternalSubnet(gInfo.internalSubnets, true)
}
if intfAdded || addrChanged {
notifyContainerChanges(c, nil, changeIntf)
}
}
}
func updateAppPorts(c *containerData, parent *containerData) bool {
var appChanged bool = false
listenPorts, appMap := prober.GetContainerAppPorts(c.id)
gInfoLock()
// remove closed port, only those opened by myself, not those merged from children.
for port, _ := range c.appMap {
if _, ok := appMap[port]; !ok && c.ownListenPorts.Contains(port) {
delete(c.appMap, port)
/* In service mesh's case parent POD use encrypted connection,
* while app/child container sees clear text traffic, update parent
* with child's appMap can confuse user especially in mid-stream session
* case, thus add additional check
*/
if parent != nil && !parent.info.ProxyMesh {
delete(parent.appMap, port)
}
log.WithFields(log.Fields{"port": port}).Debug("remove port")
appChanged = true
}
}
// add new port, populate to parent as well
for port, app := range appMap {
capp, ok := c.appMap[port]
if !ok || capp.Server != app.Server || capp.Application != app.Application {
c.appMap[port] = app
/* In service mesh's case parent POD use encrypted connection,
* while app/child container sees clear text traffic, update parent
* with child's appMap can confuse user especially in mid-stream session
* case, thus add additional check
*/
if parent != nil && !parent.info.ProxyMesh {
parent.appMap[port] = app
}
log.WithFields(log.Fields{"port": port}).Debug("add port")
appChanged = true
}
}
if appChanged {
c.ownListenPorts = listenPorts
// Update portMap only for host mode container
// For non-host mode container, the portmap is read from meta data
// which is configured at init
if c.hostMode {
c.portMap = app2MappedPort(c.appMap)
if parent != nil {
parent.portMap = app2MappedPort(parent.appMap)
}
}
}
gInfoUnlock()
return appChanged
}