/
rules.go
2584 lines (2278 loc) · 64.3 KB
/
rules.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 (c) 2022 NetLOX Inc
*
* 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 loxinet
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net"
"reflect"
"sort"
"strconv"
"strings"
"sync"
"time"
tk "github.com/loxilb-io/loxilib"
probing "github.com/prometheus-community/pro-bing"
"github.com/loxilb-io/loxilb/api/loxinlp"
cmn "github.com/loxilb-io/loxilb/common"
)
// error codes
const (
RuleErrBase = iota - 7000
RuleUnknownServiceErr
RuleUnknownEpErr
RuleExistsErr
RuleAllocErr
RuleNotExistsErr
RuleEpCountErr
RuleTupleErr
RuleArgsErr
RuleEpNotExistErr
)
type ruleTMatch uint
// rm tuples
const (
RmPort ruleTMatch = 1 << iota
RmL2Src
RmL2Dst
RmVlanID
RmL3Src
RmL3Dst
RmL4Src
RmL4Dst
RmL4Prot
RmInL2Src
RmInL2Dst
RmInL3Src
RmInL3Dst
RmInL4Src
RmInL4Dst
RmInL4Port
RmMax
)
// constants
const (
MaxNatEndPoints = 16
DflLbaInactiveTries = 2 // Default number of inactive tries before LB arm is turned off
MaxDflLbaInactiveTries = 100 // Max number of inactive tries before LB arm is turned off
DflLbaCheckTimeout = 10 // Default timeout for checking LB arms
DflHostProbeTimeout = 60 // Default probe timeout for end-point host
InitHostProbeTimeout = 15 // Initial probe timeout for end-point host
MaxHostProbeTime = 24 * 3600 // Max possible host health check duration
LbDefaultInactiveTimeout = 4 * 60 // Default inactive timeout for established sessions
LbMaxInactiveTimeout = 24 * 3600 // Maximum inactive timeout for established sessions
MaxEndPointCheckers = 4 // Maximum helpers to check endpoint health
EndPointCheckerDuration = 2 // Duration at which ep-helpers will run
MaxEndPointSweeps = 20 // Maximum end-point sweeps per round
)
type ruleTType uint
// rt types
const (
RtEm ruleTType = iota + 1
RtMf
)
type rule8Tuple struct {
val uint8
valid uint8
}
type rule16Tuple struct {
val uint16
valid uint16
}
type rule32Tuple struct {
val uint32
valid uint32
}
type rule64Tuple struct {
val uint64
valid uint64
}
type ruleIPTuple struct {
addr net.IPNet
}
type ruleMacTuple struct {
addr [6]uint8
valid [6]uint8
}
type ruleStringTuple struct {
val string
}
type ruleTuples struct {
port ruleStringTuple
l2Src ruleMacTuple
l2Dst ruleMacTuple
vlanID rule16Tuple
l3Src ruleIPTuple
l3Dst ruleIPTuple
l4Prot rule8Tuple
l4Src rule16Tuple
l4Dst rule16Tuple
tunID rule32Tuple
inL2Src ruleMacTuple
inL2Dst ruleMacTuple
inL3Src ruleIPTuple
inL3Dst ruleIPTuple
inL4Prot rule8Tuple
inL4Src rule16Tuple
inL4Dst rule16Tuple
pref uint16
}
type ruleTActType uint
// possible actions for a rt-entry
const (
RtActDrop ruleTActType = iota + 1
RtActFwd
RtActTrap
RtActRedirect
RtActDnat
RtActSnat
RtActFullNat
)
// possible types of end-point probe
const (
HostProbePing = "ping"
HostProbeConnectTCP = "tcp"
HostProbeConnectUDP = "udp"
HostProbeConnectSCTP = "sctp"
HostProbeHTTP = "http"
HostProbeHTTPS = "https"
HostProbeNone = "none"
)
type epHostOpts struct {
inActTryThr int
probeType string
probeReq string
probeResp string
probeDuration uint32
currProbeDuration uint32
probePort uint16
probeActivated bool
}
type epHost struct {
epKey string
hostName string
ruleCount int
inactive bool
initProberOn bool
sT time.Time
avgDelay time.Duration
minDelay time.Duration
maxDelay time.Duration
hID uint8
inActTries int
opts epHostOpts
}
type ruleNatEp struct {
xIP net.IP
rIP net.IP
xPort uint16
weight uint8
inActTries int
inActive bool
noService bool
chkVal bool
stat ruleStat
foldEndPoints []ruleNatEp
foldRuleKey string
}
type ruleNatSIP struct {
sIP net.IP
}
type ruleNatActs struct {
mode cmn.LBMode
sel cmn.EpSelect
endPoints []ruleNatEp
}
type ruleFwOpt struct {
rdrMirr string
rdrPort string
fwMark uint32
record bool
}
type ruleFwOpts struct {
op ruleTActType
opt ruleFwOpt
}
type ruleTAct interface{}
type ruleAct struct {
actType ruleTActType
action ruleTAct
}
type ruleStat struct {
bytes uint64
packets uint64
}
type ruleProbe struct {
actChk bool
prbType string
prbPort uint16
prbReq string
prbResp string
}
type ruleEnt struct {
zone *Zone
ruleNum uint64
sync DpStatusT
tuples ruleTuples
ci string
hChk ruleProbe
managed bool
bgp bool
addrRslv bool
sT time.Time
iTo uint32
act ruleAct
secIP []ruleNatSIP
stat ruleStat
name string
}
type ruleTable struct {
tableType ruleTType
tableMatch ruleTMatch
eMap map[string]*ruleEnt
rArr [RtMaximumLbs]*ruleEnt
pMap []*ruleEnt
Mark *tk.Counter
}
type ruleTableType uint
// rt types
const (
RtFw ruleTableType = iota + 1
RtLB
RtMax
)
// rule specific loxilb constants
const (
RtMaximumFw4s = (8 * 1024)
RtMaximumLbs = (2 * 1024)
)
// RuleCfg - tunable parameters related to inactive rules
type RuleCfg struct {
RuleInactTries int
RuleInactChkTime int
}
type epChecker struct {
hChk *time.Ticker
tD chan bool
}
// RuleH - context container
type RuleH struct {
zone *Zone
cfg RuleCfg
tables [RtMax]ruleTable
epMap map[string]*epHost
vipMap map[string]int
epCs [MaxEndPointCheckers]epChecker
wg sync.WaitGroup
lepHID uint8
epMx sync.RWMutex
rootCAPool *x509.CertPool
tlsCert tls.Certificate
}
// RulesInit - initialize the Rules subsystem
func RulesInit(zone *Zone) *RuleH {
var nRh = new(RuleH)
nRh.zone = zone
nRh.cfg.RuleInactChkTime = DflLbaCheckTimeout
nRh.cfg.RuleInactTries = DflLbaInactiveTries
nRh.vipMap = make(map[string]int)
nRh.epMap = make(map[string]*epHost)
nRh.tables[RtFw].tableMatch = RmMax - 1
nRh.tables[RtFw].tableType = RtMf
nRh.tables[RtFw].eMap = make(map[string]*ruleEnt)
nRh.tables[RtFw].Mark = tk.NewCounter(1, RtMaximumFw4s)
nRh.tables[RtLB].tableMatch = RmL3Dst | RmL4Dst | RmL4Prot
nRh.tables[RtLB].tableType = RtEm
nRh.tables[RtLB].eMap = make(map[string]*ruleEnt)
nRh.tables[RtLB].Mark = tk.NewCounter(1, RtMaximumLbs)
for i := 0; i < MaxEndPointCheckers; i++ {
nRh.epCs[i].tD = make(chan bool)
nRh.epCs[i].hChk = time.NewTicker(EndPointCheckerDuration * time.Second)
go epTicker(nRh, i)
}
nRh.rootCAPool = x509.NewCertPool()
rootCACertile := cmn.CertPath + cmn.CACertFileName
// Check if there exist a common CA certificate
if exists := FileExists(rootCACertile); exists {
rootCA, err := ioutil.ReadFile(rootCACertile)
if err != nil {
tk.LogIt(tk.LogError, "RootCA cert load failed : %v\n", err)
} else {
nRh.rootCAPool.AppendCertsFromPEM(rootCA)
tk.LogIt(tk.LogDebug, "RootCA cert loaded\n")
}
}
certFile := cmn.CertPath + cmn.PrivateCertName
keyFile := cmn.CertPath + cmn.PrivateKeyName
certExists := FileExists(certFile)
keyExists := FileExists(keyFile)
if certExists == true && keyExists == true {
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
tk.LogIt(tk.LogError, "Error loading loxilb certificate %s and key file %s",
certFile, keyFile)
}
nRh.tlsCert = cert
}
nRh.wg.Add(MaxEndPointCheckers)
return nRh
}
func (r *ruleTuples) ruleMkKeyCompliance(match ruleTMatch) {
if match&RmPort != RmPort {
r.port.val = ""
}
if match&RmL2Src != RmL2Src {
for i := 0; i < 6; i++ {
r.l2Src.addr[i] = 0
r.l2Src.valid[i] = 0
}
}
if match&RmL2Dst != RmL2Dst {
for i := 0; i < 6; i++ {
r.l2Dst.addr[i] = 0
r.l2Dst.valid[i] = 0
}
}
if match&RmVlanID != RmVlanID {
r.vlanID.val = 0
r.vlanID.valid = 0
}
if match&RmL3Src != RmL3Src {
_, dst, _ := net.ParseCIDR("0.0.0.0/0")
r.l3Src.addr = *dst
}
if match&RmL3Dst != RmL3Dst {
_, dst, _ := net.ParseCIDR("0.0.0.0/0")
r.l3Dst.addr = *dst
}
if match&RmL4Prot != RmL4Prot {
r.l4Prot.val = 0
r.l4Prot.valid = 0
}
if match&RmL4Src != RmL4Src {
r.l4Src.val = 0
r.l4Src.valid = 0
}
if match&RmL4Dst != RmL4Dst {
r.l4Dst.val = 0
r.l4Dst.valid = 0
}
if match&RmInL2Src != RmInL2Src {
for i := 0; i < 6; i++ {
r.inL2Src.addr[i] = 0
r.inL2Src.valid[i] = 0
}
}
if match&RmInL2Dst != RmInL2Dst {
for i := 0; i < 6; i++ {
r.inL2Dst.addr[i] = 0
r.inL2Dst.valid[i] = 0
}
}
if match&RmInL3Src != RmInL3Src {
_, dst, _ := net.ParseCIDR("0.0.0.0/0")
r.inL3Src.addr = *dst
}
if match&RmInL3Dst != RmInL3Dst {
_, dst, _ := net.ParseCIDR("0.0.0.0/0")
r.inL3Dst.addr = *dst
}
if match&RmInL4Port != RmInL4Port {
r.inL4Prot.val = 0
r.inL4Prot.valid = 0
}
if match&RmInL4Src != RmInL4Src {
r.inL4Src.val = 0
r.inL4Src.valid = 0
}
if match&RmInL4Dst != RmInL4Dst {
r.inL4Dst.val = 0
r.inL4Dst.valid = 0
}
}
func (r *ruleTuples) ruleKey() string {
var ks string
ks = fmt.Sprintf("%s", r.port.val)
ks += fmt.Sprintf("%02x:%02x:%02x:%02x:%02x:%02x",
r.l2Dst.addr[0]&r.l2Dst.valid[0],
r.l2Dst.addr[1]&r.l2Dst.valid[1],
r.l2Dst.addr[2]&r.l2Dst.valid[2],
r.l2Dst.addr[3]&r.l2Dst.valid[3],
r.l2Dst.addr[4]&r.l2Dst.valid[4],
r.l2Dst.addr[5]&r.l2Dst.valid[5])
ks += fmt.Sprintf("%02x:%02x:%02x:%02x:%02x:%02x",
r.l2Src.addr[0]&r.l2Src.valid[0],
r.l2Src.addr[1]&r.l2Src.valid[1],
r.l2Src.addr[2]&r.l2Src.valid[2],
r.l2Src.addr[3]&r.l2Src.valid[3],
r.l2Src.addr[4]&r.l2Src.valid[4],
r.l2Src.addr[5]&r.l2Src.valid[5])
ks += fmt.Sprintf("%d", r.vlanID.val&r.vlanID.valid)
ks += fmt.Sprintf("%s", r.l3Dst.addr.String())
ks += fmt.Sprintf("%s", r.l3Src.addr.String())
ks += fmt.Sprintf("%d", r.l4Prot.val&r.l4Prot.valid)
if r.l4Src.valid == 0xffff {
ks += fmt.Sprintf("%d", r.l4Src.val&r.l4Src.valid)
} else {
ks += fmt.Sprintf("%d%d", r.l4Src.val, r.l4Src.valid)
}
if r.l4Dst.valid == 0xffff {
ks += fmt.Sprintf("%d", r.l4Dst.val&r.l4Dst.valid)
} else {
ks += fmt.Sprintf("%d%d", r.l4Dst.val, r.l4Dst.valid)
}
ks += fmt.Sprintf("%02x:%02x:%02x:%02x:%02x:%02x",
r.inL2Dst.addr[0]&r.inL2Dst.valid[0],
r.inL2Dst.addr[1]&r.inL2Dst.valid[1],
r.inL2Dst.addr[2]&r.inL2Dst.valid[2],
r.inL2Dst.addr[3]&r.inL2Dst.valid[3],
r.inL2Dst.addr[4]&r.inL2Dst.valid[4],
r.inL2Dst.addr[5]&r.inL2Dst.valid[5])
ks += fmt.Sprintf("%02x:%02x:%02x:%02x:%02x:%02x",
r.inL2Src.addr[0]&r.inL2Src.valid[0],
r.inL2Src.addr[1]&r.inL2Src.valid[1],
r.inL2Src.addr[2]&r.inL2Src.valid[2],
r.inL2Src.addr[3]&r.inL2Src.valid[3],
r.inL2Src.addr[4]&r.inL2Src.valid[4],
r.inL2Src.addr[5]&r.inL2Src.valid[5])
ks += fmt.Sprintf("%s", r.inL3Dst.addr.String())
ks += fmt.Sprintf("%s", r.inL3Src.addr.String())
ks += fmt.Sprintf("%d", r.inL4Prot.val&r.inL4Prot.valid)
ks += fmt.Sprintf("%d", r.inL4Src.val&r.inL4Src.valid)
ks += fmt.Sprintf("%d", r.inL4Dst.val&r.inL4Dst.valid)
ks += fmt.Sprintf("%d", r.pref)
return ks
}
func checkValidMACTuple(mt ruleMacTuple) bool {
if mt.valid[0] != 0 ||
mt.valid[1] != 0 ||
mt.valid[2] != 0 ||
mt.valid[3] != 0 ||
mt.valid[4] != 0 ||
mt.valid[5] != 0 {
return true
}
return false
}
func (r *ruleTuples) String() string {
var ks string
if r.port.val != "" {
ks = fmt.Sprintf("inp-%s,", r.port.val)
}
if checkValidMACTuple(r.l2Dst) {
ks += fmt.Sprintf("dmac-%02x:%02x:%02x:%02x:%02x:%02x,",
r.l2Dst.addr[0]&r.l2Dst.valid[0],
r.l2Dst.addr[1]&r.l2Dst.valid[1],
r.l2Dst.addr[2]&r.l2Dst.valid[2],
r.l2Dst.addr[3]&r.l2Dst.valid[3],
r.l2Dst.addr[4]&r.l2Dst.valid[4],
r.l2Dst.addr[5]&r.l2Dst.valid[5])
}
if checkValidMACTuple(r.l2Src) {
ks += fmt.Sprintf("smac-%02x:%02x:%02x:%02x:%02x:%02x",
r.l2Src.addr[0]&r.l2Src.valid[0],
r.l2Src.addr[1]&r.l2Src.valid[1],
r.l2Src.addr[2]&r.l2Src.valid[2],
r.l2Src.addr[3]&r.l2Src.valid[3],
r.l2Src.addr[4]&r.l2Src.valid[4],
r.l2Src.addr[5]&r.l2Src.valid[5])
}
if r.vlanID.valid != 0 {
ks += fmt.Sprintf("vid-%d,", r.vlanID.val&r.vlanID.valid)
}
if r.l3Dst.addr.String() != "<nil>" {
ks += fmt.Sprintf("dst-%s,", r.l3Dst.addr.String())
}
if r.l3Src.addr.String() != "<nil>" {
ks += fmt.Sprintf("src-%s,", r.l3Src.addr.String())
}
if r.l4Prot.valid != 0 {
ks += fmt.Sprintf("proto-%d,", r.l4Prot.val&r.l4Prot.valid)
}
if r.l4Dst.valid != 0 {
ks += fmt.Sprintf("dport-%d,", r.l4Dst.val&r.l4Dst.valid)
}
if r.l4Src.valid != 0 {
ks += fmt.Sprintf("sport-%d,", r.l4Src.val&r.l4Src.valid)
}
if checkValidMACTuple(r.inL2Dst) {
ks += fmt.Sprintf("idmac-%02x:%02x:%02x:%02x:%02x:%02x,",
r.inL2Dst.addr[0]&r.inL2Dst.valid[0],
r.inL2Dst.addr[1]&r.inL2Dst.valid[1],
r.inL2Dst.addr[2]&r.inL2Dst.valid[2],
r.inL2Dst.addr[3]&r.inL2Dst.valid[3],
r.inL2Dst.addr[4]&r.inL2Dst.valid[4],
r.inL2Dst.addr[5]&r.inL2Dst.valid[5])
}
if checkValidMACTuple(r.inL2Src) {
ks += fmt.Sprintf("ismac-%02x:%02x:%02x:%02x:%02x:%02x,",
r.inL2Src.addr[0]&r.inL2Src.valid[0],
r.inL2Src.addr[1]&r.inL2Src.valid[1],
r.inL2Src.addr[2]&r.inL2Src.valid[2],
r.inL2Src.addr[3]&r.inL2Src.valid[3],
r.inL2Src.addr[4]&r.inL2Src.valid[4],
r.inL2Src.addr[5]&r.inL2Src.valid[5])
}
if r.inL3Dst.addr.String() != "<nil>" {
ks += fmt.Sprintf("idst-%s,", r.inL3Dst.addr.String())
}
if r.inL3Src.addr.String() != "<nil>" {
ks += fmt.Sprintf("isrc-%s,", r.inL3Src.addr.String())
}
if r.inL4Prot.valid != 0 {
ks += fmt.Sprintf("iproto-%d,", r.inL4Prot.val&r.inL4Prot.valid)
}
if r.inL4Dst.valid != 0 {
ks += fmt.Sprintf("idport-%d,", r.inL4Dst.val&r.inL4Dst.valid)
}
if r.inL4Src.valid != 0 {
ks += fmt.Sprintf("isport-%d,", r.inL4Src.val&r.inL4Src.valid)
}
return ks
}
func (a *ruleAct) String() string {
var ks string
if a.actType == RtActDrop {
ks += fmt.Sprintf("%s", "drop")
} else if a.actType == RtActFwd {
ks += fmt.Sprintf("%s", "allow")
} else if a.actType == RtActTrap {
ks += fmt.Sprintf("%s", "trap")
} else if a.actType == RtActDnat ||
a.actType == RtActSnat ||
a.actType == RtActFullNat {
if a.actType == RtActSnat {
ks += fmt.Sprintf("%s", "do-snat:")
} else if a.actType == RtActDnat {
ks += fmt.Sprintf("%s", "do-dnat:")
} else {
ks += fmt.Sprintf("%s", "do-fullnat:")
}
switch na := a.action.(type) {
case *ruleNatActs:
if na.mode == cmn.LBModeOneArm {
ks += fmt.Sprintf("%s", "onearm:")
}
for _, n := range na.endPoints {
if len(n.foldEndPoints) > 0 {
for _, nf := range n.foldEndPoints {
ks += fmt.Sprintf("feip-%s,fep-%d,fw-%d,",
nf.xIP.String(), nf.xPort, nf.weight)
if nf.inActive || nf.noService {
ks += fmt.Sprintf("dead|")
} else {
ks += fmt.Sprintf("alive|")
}
}
} else {
ks += fmt.Sprintf("eip-%s,ep-%d,w-%d,",
n.xIP.String(), n.xPort, n.weight)
if n.inActive || n.noService {
ks += fmt.Sprintf("dead|")
} else {
ks += fmt.Sprintf("alive|")
}
}
}
}
}
return ks
}
// Rules2Json - output all rules into json and write to the byte array
func (R *RuleH) Rules2Json() ([]byte, error) {
var t cmn.LbServiceArg
var eps []cmn.LbEndPointArg
var ret cmn.LbRuleMod
var bret []byte
for _, data := range R.tables[RtLB].eMap {
// Make Service Arguments
t.ServIP = data.tuples.l3Dst.addr.IP.String()
if data.tuples.l4Prot.val == 6 {
t.Proto = "tcp"
} else if data.tuples.l4Prot.val == 17 {
t.Proto = "udp"
} else if data.tuples.l4Prot.val == 1 {
t.Proto = "icmp"
} else if data.tuples.l4Prot.val == 132 {
t.Proto = "sctp"
} else {
return nil, errors.New("malformed service proto")
}
t.ServPort = data.tuples.l4Dst.val
t.Sel = data.act.action.(*ruleNatActs).sel
t.Mode = data.act.action.(*ruleNatActs).mode
// Make Endpoints
tmpEp := data.act.action.(*ruleNatActs).endPoints
for _, ep := range tmpEp {
eps = append(eps, cmn.LbEndPointArg{
EpIP: ep.xIP.String(),
EpPort: ep.xPort,
Weight: ep.weight,
})
}
// Make LB rule
ret.Serv = t
ret.Eps = eps
js, err := json.Marshal(ret)
if err != nil {
return nil, err
}
bret = append(bret, js...)
fmt.Printf("js: %v\n", js)
fmt.Println(string(js))
}
return bret, nil
}
// GetNatLbRule - get all rules and pack them into a cmn.LbRuleMod slice
func (R *RuleH) GetNatLbRule() ([]cmn.LbRuleMod, error) {
var res []cmn.LbRuleMod
for _, data := range R.tables[RtLB].eMap {
var ret cmn.LbRuleMod
// Make Service Arguments
ret.Serv.ServIP = data.tuples.l3Dst.addr.IP.String()
if data.tuples.l4Prot.val == 6 {
ret.Serv.Proto = "tcp"
} else if data.tuples.l4Prot.val == 17 {
ret.Serv.Proto = "udp"
} else if data.tuples.l4Prot.val == 1 {
ret.Serv.Proto = "icmp"
} else if data.tuples.l4Prot.val == 132 {
ret.Serv.Proto = "sctp"
} else {
return []cmn.LbRuleMod{}, errors.New("malformed service proto")
}
ret.Serv.ServPort = data.tuples.l4Dst.val
ret.Serv.Sel = data.act.action.(*ruleNatActs).sel
ret.Serv.Mode = data.act.action.(*ruleNatActs).mode
ret.Serv.Monitor = data.hChk.actChk
ret.Serv.InactiveTimeout = data.iTo
ret.Serv.Bgp = data.bgp
ret.Serv.BlockNum = data.tuples.pref
ret.Serv.Managed = data.managed
ret.Serv.ProbeType = data.hChk.prbType
ret.Serv.ProbePort = data.hChk.prbPort
ret.Serv.ProbeReq = data.hChk.prbReq
ret.Serv.ProbeResp = data.hChk.prbResp
ret.Serv.Name = data.name
for _, sip := range data.secIP {
ret.SecIPs = append(ret.SecIPs, cmn.LbSecIPArg{SecIP: sip.sIP.String()})
}
data.DP(DpStatsGetImm)
// Make Endpoints
tmpEp := data.act.action.(*ruleNatActs).endPoints
for _, ep := range tmpEp {
state := "active"
if ep.noService {
state = "inactive"
}
if ep.inActive {
continue
}
counterStr := fmt.Sprintf("%v:%v", ep.stat.packets, ep.stat.bytes)
ret.Eps = append(ret.Eps, cmn.LbEndPointArg{
EpIP: ep.xIP.String(),
EpPort: ep.xPort,
Weight: ep.weight,
State: state,
Counters: counterStr,
})
}
// Make LB rule
res = append(res, ret)
}
return res, nil
}
// validateXlateEPWeights - validate and adjust weights if necessary
func validateXlateEPWeights(servEndPoints []cmn.LbEndPointArg) (int, error) {
sum := 0
for _, se := range servEndPoints {
sum += int(se.Weight)
}
if sum > 100 {
return -1, errors.New("malformed-weight error")
} else if sum < 100 {
rem := (100 - sum) / len(servEndPoints)
for idx := range servEndPoints {
pSe := &servEndPoints[idx]
pSe.Weight += uint8(rem)
}
}
return 0, nil
}
func (R *RuleH) modNatEpHost(r *ruleEnt, endpoints []ruleNatEp, doAddOp bool, liveCheckEn bool) {
var hopts epHostOpts
pType := ""
pPort := uint16(0)
hopts.inActTryThr = DflLbaInactiveTries
hopts.probeDuration = DflHostProbeTimeout
for _, nep := range endpoints {
if r.tuples.l4Prot.val == 6 {
pType = HostProbeConnectTCP
pPort = nep.xPort
} else if r.tuples.l4Prot.val == 17 {
pType = HostProbeConnectUDP
pPort = nep.xPort
} else if r.tuples.l4Prot.val == 1 {
pType = HostProbePing
} else if r.tuples.l4Prot.val == 132 {
pType = HostProbeConnectSCTP
pPort = nep.xPort
} else {
pType = HostProbePing
}
if r.hChk.prbType != "" {
// If probetype is specified as a part of rule,
// override per end-point liveness settings
hopts.probeType = r.hChk.prbType
hopts.probePort = r.hChk.prbPort
hopts.probeReq = r.hChk.prbReq
hopts.probeResp = r.hChk.prbResp
} else {
hopts.probeType = pType
hopts.probePort = pPort
}
if mh.pProbe == true || liveCheckEn {
hopts.probeActivated = true
}
epKey := makeEPKey(nep.xIP.String(), pType, pPort)
if doAddOp {
if nep.inActive != true {
R.AddEPHost(false, nep.xIP.String(), epKey, hopts)
}
} else {
R.DeleteEPHost(false, epKey, nep.xIP.String(), hopts.probeType, hopts.probePort)
}
}
}
// GetNatLbRuleByID - Get a NAT rule by its identifier
func (R *RuleH) GetNatLbRuleByID(ruleID uint32) *ruleEnt {
if ruleID < RtMaximumLbs {
return R.tables[RtLB].rArr[ruleID]
}
return nil
}
// GetNatLbRuleByServArgs - Get a NAT rule by its service args
func (R *RuleH) GetNatLbRuleByServArgs(serv cmn.LbServiceArg) *ruleEnt {
var ipProto uint8
service := ""
if tk.IsNetIPv4(serv.ServIP) {
service = serv.ServIP + "/32"
} else {
service = serv.ServIP + "/128"
}
_, sNetAddr, err := net.ParseCIDR(service)
if err != nil {
return nil
}
if serv.Proto == "tcp" {
ipProto = 6
} else if serv.Proto == "udp" {
ipProto = 17
} else if serv.Proto == "icmp" {
ipProto = 1
} else if serv.Proto == "sctp" {
ipProto = 132
} else {
return nil
}
l4prot := rule8Tuple{ipProto, 0xff}
l3dst := ruleIPTuple{*sNetAddr}
l4dst := rule16Tuple{serv.ServPort, 0xffff}
rt := ruleTuples{l3Dst: l3dst, l4Prot: l4prot, l4Dst: l4dst, pref: serv.BlockNum}
return R.tables[RtLB].eMap[rt.ruleKey()]
}
// GetNatLbRuleSecIPs - Get secondary IPs for SCTP NAT rule by its service args
func (R *RuleH) GetNatLbRuleSecIPs(serv cmn.LbServiceArg) []string {
var ipProto uint8
var ips []string
service := ""
if tk.IsNetIPv4(serv.ServIP) {
service = serv.ServIP + "/32"
} else {
service = serv.ServIP + "/128"
}
_, sNetAddr, err := net.ParseCIDR(service)
if err != nil {
return nil
}
if serv.Proto == "sctp" {
ipProto = 132
} else {
return nil
}
l4prot := rule8Tuple{ipProto, 0xff}
l3dst := ruleIPTuple{*sNetAddr}
l4dst := rule16Tuple{serv.ServPort, 0xffff}
rt := ruleTuples{l3Dst: l3dst, l4Prot: l4prot, l4Dst: l4dst, pref: serv.BlockNum}
if R.tables[RtLB].eMap[rt.ruleKey()] != nil {
for _, ip := range R.tables[RtLB].eMap[rt.ruleKey()].secIP {
ips = append(ips, ip.sIP.String())
}
}
return ips
}
func (R *RuleH) electEPSrc(r *ruleEnt) bool {
var sip net.IP
var e int
chg := false
mode := "default"
addrRslv := false
switch na := r.act.action.(type) {
case *ruleNatActs:
{
for idx := range na.endPoints {
np := &na.endPoints[idx]
if np.foldRuleKey != "" {
fr := R.tables[RtLB].eMap[np.foldRuleKey]
if fr == nil || fr.addrRslv {
addrRslv = true
continue
}
}
sip = np.rIP
if na.mode == cmn.LBModeOneArm {
mode = "onearm"
e, sip, _ = R.zone.L3.IfaSelectAny(np.xIP, false)
if e != 0 {
tk.LogIt(tk.LogDebug, "Failed to find suitable source for %s\n", np.xIP.String())
addrRslv = true
}
if np.xIP.Equal(sip) {
sip = net.IPv4(0, 0, 0, 0)
}
} else if na.mode == cmn.LBModeFullNAT {
mode = "fullnat"
if !mh.has.IsCIKAMode() {
sip = r.tuples.l3Dst.addr.IP.Mask(r.tuples.l3Dst.addr.Mask)
if np.xIP.Equal(sip) {
sip = net.IPv4(0, 0, 0, 0)
} else if IsIPHostAddr(np.xIP.String()) {
sip = net.IPv4(0, 0, 0, 0)
}
} else {
vip, err := mh.has.CIVipGet(r.ci)
if err == nil {
tk.LogIt(tk.LogDebug, "vip for %s: %s\n", r.ci, vip.String())
sip = vip
} else {
tk.LogIt(tk.LogError, "vip for %s not found \n", r.ci)
addrRslv = true
}
}
} else {
serviceIP := r.tuples.l3Dst.addr.IP.Mask(r.tuples.l3Dst.addr.Mask)
if tk.IsNetIPv6(serviceIP.String()) && tk.IsNetIPv4(np.xIP.String()) {
e, sip, _ = r.zone.L3.IfaSelectAny(np.xIP, false)
if e != 0 {
addrRslv = true
}