-
Notifications
You must be signed in to change notification settings - Fork 744
/
data_store.go
1536 lines (1352 loc) · 50.1 KB
/
data_store.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 Amazon.com Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may
// not use this file except in compliance with the License. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file 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 datastore
import (
"fmt"
"net"
"os"
"strings"
"sync"
"time"
"github.com/aws/amazon-vpc-cni-k8s/pkg/netlinkwrapper"
"github.com/aws/amazon-vpc-cni-k8s/pkg/networkutils"
"github.com/vishvananda/netlink"
"golang.org/x/sys/unix"
"github.com/aws/amazon-vpc-cni-k8s/pkg/utils/logger"
"github.com/aws/amazon-vpc-cni-k8s/utils"
"github.com/aws/amazon-vpc-cni-k8s/utils/prometheusmetrics"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
)
const (
// minENILifeTime is the shortest time before we consider deleting a newly created ENI
minENILifeTime = 1 * time.Minute
// envIPCooldownPeriod (default 30 seconds) specifies the time after pod deletion before an IP can be assigned to a new pod
envIPCooldownPeriod = "IP_COOLDOWN_PERIOD"
// DuplicatedENIError is an error when caller tries to add an duplicate ENI to data store
DuplicatedENIError = "data store: duplicate ENI"
// IPAlreadyInStoreError is an error when caller tries to add an duplicate IP address to data store
IPAlreadyInStoreError = "datastore: IP already in data store"
// UnknownIPError is an error when caller tries to delete an IP which is unknown to data store
UnknownIPError = "datastore: unknown IP"
// IPInUseError is an error when caller tries to delete an IP where IP is still assigned to a Pod
IPInUseError = "datastore: IP is used and can not be deleted"
// ENIInUseError is an error when caller tries to delete an ENI where there are IP still assigned to a pod
ENIInUseError = "datastore: ENI is used and can not be deleted"
// UnknownENIError is an error when caller tries to access an ENI which is unknown to datastore
UnknownENIError = "datastore: unknown ENI"
)
// On IPAMD/datastore restarts, we need to determine which pod IPs are already allocated. In VPC CNI <= 1.6,
// this was done by querying kubelet's CRI. This required scary access to the CRI socket, which could result
// in race conditions with the CRI's internal logic. Therefore, we transitioned to storing IP allocations
// ourselves in a persistent file (similar to host-ipam CNI plugin).
//
// The migration process took place over a series of phases:
// Phase 0 (<= CNI 1.6): Read/write from CRI only
// Phase 1 (CNI 1.7): Read from CRI. Write to CRI+file
// Phase 2 (CNI 1.8): Read from file. Write to CRI+file
// Phase 3 (CNI 1.12+): Read/write from file only
//
// Now that phase 3 has completed, IPAMD has no CRI dependency.
// Placeholders used for unknown values
const backfillNetworkName = "_migrated-from-cri"
const backfillNetworkIface = "unknown"
// ErrUnknownPod is an error when there is no pod in data store matching pod name, namespace, sandbox id
var ErrUnknownPod = errors.New("datastore: unknown pod")
// IPAMKey is the IPAM primary key. Quoting CNI spec:
//
// Plugins that store state should do so using a primary key of
// (network name, CNI_CONTAINERID, CNI_IFNAME).
type IPAMKey struct {
NetworkName string `json:"networkName"`
ContainerID string `json:"containerID"`
IfName string `json:"ifName"`
}
// IsZero returns true if object is equal to the golang zero/null value.
func (k IPAMKey) IsZero() bool {
return k == IPAMKey{}
}
// String() implements the fmt.Stringer interface.
func (k IPAMKey) String() string {
return fmt.Sprintf("%s/%s/%s", k.NetworkName, k.ContainerID, k.IfName)
}
// IPAMMetadata is the metadata associated with IP allocations.
type IPAMMetadata struct {
K8SPodNamespace string `json:"k8sPodNamespace,omitempty"`
K8SPodName string `json:"k8sPodName,omitempty"`
}
// ENI represents a single ENI. Exported fields will be marshaled for introspection.
type ENI struct {
// AWS ENI ID
ID string
createTime time.Time
// IsPrimary indicates whether ENI is a primary ENI
IsPrimary bool
// IsTrunk indicates whether this ENI is used to provide pods with dedicated ENIs
IsTrunk bool
// IsEFA indicates whether this ENI is tagged as an EFA
IsEFA bool
// DeviceNumber is the device number of ENI (0 means the primary ENI)
DeviceNumber int
// IPv4Addresses shows whether each address is assigned, the key is IP address, which must
// be in dot-decimal notation with no leading zeros and no whitespace(eg: "10.1.0.253")
// Key is the IP address - PD: "IP/28" and SIP: "IP/32"
AvailableIPv4Cidrs map[string]*CidrInfo
//IPv6CIDRs contains information tied to IPv6 Prefixes attached to the ENI
IPv6Cidrs map[string]*CidrInfo
}
// AddressInfo contains information about an IP, Exported fields will be marshaled for introspection.
type AddressInfo struct {
Address string
IPAMKey IPAMKey
IPAMMetadata IPAMMetadata
AssignedTime time.Time
UnassignedTime time.Time
}
// CidrInfo
type CidrInfo struct {
// Either v4/v6 Host or LPM Prefix
Cidr net.IPNet
// Key is individual IP addresses from the Prefix - /32 (v4) or /128 (v6)
IPAddresses map[string]*AddressInfo
// true if Cidr here is an LPM prefix
IsPrefix bool
// IP Address Family of the Cidr
AddressFamily string
}
func (cidr *CidrInfo) Size() int {
ones, bits := cidr.Cidr.Mask.Size()
return (1 << (bits - ones))
}
func (e *ENI) findAddressForSandbox(ipamKey IPAMKey) (*CidrInfo, *AddressInfo) {
// Either v4 or v6 for now.
// Check in V4 prefixes
for _, availableCidr := range e.AvailableIPv4Cidrs {
for _, addr := range availableCidr.IPAddresses {
if addr.IPAMKey == ipamKey {
return availableCidr, addr
}
}
}
// Check in V6 prefixes
for _, availableCidr := range e.IPv6Cidrs {
for _, addr := range availableCidr.IPAddresses {
if addr.IPAMKey == ipamKey {
return availableCidr, addr
}
}
}
return nil, nil
}
// AssignedIPv4Addresses is the number of IP addresses already assigned
func (e *ENI) AssignedIPv4Addresses() int {
count := 0
for _, availableCidr := range e.AvailableIPv4Cidrs {
count += availableCidr.AssignedIPAddressesInCidr()
}
return count
}
// AssignedIPAddressesInCidr is the number of IP addresses already assigned in the IPv4 CIDR
func (cidr *CidrInfo) AssignedIPAddressesInCidr() int {
count := 0
//SIP : This will run just once and count will be 0 if addr is not assigned or addr is not allocated yet(unused IP)
//PD : This will return count of number /32 assigned in /28 CIDR.
for _, addr := range cidr.IPAddresses {
if addr.Assigned() {
count++
}
}
return count
}
type CidrStats struct {
AssignedIPs int
CooldownIPs int
}
// Gets number of assigned IPs and the IPs in cooldown from a given CIDR
func (cidr *CidrInfo) GetIPStatsFromCidr(ipCooldownPeriod time.Duration) CidrStats {
stats := CidrStats{}
for _, addr := range cidr.IPAddresses {
if addr.Assigned() {
stats.AssignedIPs++
} else if addr.inCoolingPeriod(ipCooldownPeriod) {
stats.CooldownIPs++
}
}
return stats
}
// Assigned returns true iff the address is allocated to a pod/sandbox.
func (addr AddressInfo) Assigned() bool {
return !addr.IPAMKey.IsZero()
}
// getCooldownPeriod returns the time duration in seconds configured by the IP_COOLDOWN_PERIOD env variable
func getCooldownPeriod() time.Duration {
cooldownVal, err, _ := utils.GetIntFromStringEnvVar(envIPCooldownPeriod, 30)
if err != nil {
return 30 * time.Second
}
return time.Duration(cooldownVal) * time.Second
}
// InCoolingPeriod checks whether an addr is in ipCooldownPeriod
func (addr AddressInfo) inCoolingPeriod(ipCooldownPeriod time.Duration) bool {
return time.Since(addr.UnassignedTime) <= ipCooldownPeriod
}
// ENIPool is a collection of ENI, keyed by ENI ID
type ENIPool map[string]*ENI
// AssignedIPv4Addresses is the number of IP addresses already assigned
func (p *ENIPool) AssignedIPv4Addresses() int {
count := 0
for _, eni := range *p {
count += eni.AssignedIPv4Addresses()
}
return count
}
// FindAddressForSandbox returns ENI and AddressInfo or (nil, nil) if not found
func (p *ENIPool) FindAddressForSandbox(ipamKey IPAMKey) (*ENI, *CidrInfo, *AddressInfo) {
for _, eni := range *p {
if availableCidr, addr := eni.findAddressForSandbox(ipamKey); addr != nil && availableCidr != nil {
return eni, availableCidr, addr
}
}
return nil, nil, nil
}
// PodIPInfo contains pod's IP and the device number of the ENI
type PodIPInfo struct {
IPAMKey IPAMKey
// IP is the IPv4 address of pod
IP string
// DeviceNumber is the device number of the ENI
DeviceNumber int
}
// DataStore contains node level ENI/IP
type DataStore struct {
total int
assigned int
allocatedPrefix int
eniPool ENIPool
lock sync.Mutex
log logger.Logger
backingStore Checkpointer
netLink netlinkwrapper.NetLink
isPDEnabled bool
ipCooldownPeriod time.Duration
}
// ENIInfos contains ENI IP information
type ENIInfos struct {
// TotalIPs is the total number of IP addresses
TotalIPs int
// assigned is the number of IP addresses that has been assigned
AssignedIPs int
// ENIs contains ENI IP pool information
ENIs map[string]ENI
}
// NewDataStore returns DataStore structure
func NewDataStore(log logger.Logger, backingStore Checkpointer, isPDEnabled bool) *DataStore {
return &DataStore{
eniPool: make(ENIPool),
log: log,
backingStore: backingStore,
netLink: netlinkwrapper.NewNetLink(),
isPDEnabled: isPDEnabled,
ipCooldownPeriod: getCooldownPeriod(),
}
}
// CheckpointFormatVersion is the version stamp used on stored checkpoints.
const CheckpointFormatVersion = "vpc-cni-ipam/1"
// CheckpointData is the format of stored checkpoints. Note this is
// deliberately a "dumb" format since efficiency is less important
// than version stability here.
type CheckpointData struct {
Version string `json:"version"`
Allocations []CheckpointEntry `json:"allocations"`
}
// CheckpointEntry is a "row" in the conceptual IPAM datastore, as stored
// in checkpoints.
type CheckpointEntry struct {
IPAMKey
IPv4 string `json:"ipv4,omitempty"`
IPv6 string `json:"ipv6,omitempty"`
AllocationTimestamp int64 `json:"allocationTimestamp"`
Metadata IPAMMetadata `json:"metadata"`
}
// ReadBackingStore initializes the IP allocation state from the
// configured backing store. Should be called before using data store.
func (ds *DataStore) ReadBackingStore(isv6Enabled bool) error {
var data CheckpointData
// Read from checkpoint file
ds.log.Infof("Begin ipam state recovery from backing store")
if err := ds.backingStore.Restore(&data); err != nil {
// Assume that no file == no containers are currently in use, e.g. a fresh reboot just cleared everything out.
// This is ok, and no-op.
if os.IsNotExist(err) {
ds.log.Debugf("backing store doesn't exists, assuming bootstrap on a new node")
return nil
}
return errors.Wrap(err, "failed ipam state recovery from backing store")
}
if data.Version != CheckpointFormatVersion {
return errors.Errorf("failed ipam state recovery due to unexpected checkpointVersion: %v/%v", data.Version, CheckpointFormatVersion)
}
if normalizedData, err := ds.normalizeCheckpointDataByPodVethExistence(data); err != nil {
return errors.Wrap(err, "failed normalize checkpoint data with veth check")
} else {
data = normalizedData
}
ds.lock.Lock()
defer ds.lock.Unlock()
for _, allocation := range data.Allocations {
ipv4Addr := net.ParseIP(allocation.IPv4)
ipv6Addr := net.ParseIP(allocation.IPv6)
var ipAddr net.IP
found := false
eniloop:
for _, eni := range ds.eniPool {
eniCidrs := eni.AvailableIPv4Cidrs
ipAddr = ipv4Addr
if isv6Enabled {
ds.log.Debugf("v6 is enabled")
eniCidrs = eni.IPv6Cidrs
ipAddr = ipv6Addr
}
for _, cidr := range eniCidrs {
ds.log.Debugf("Checking if IP: %v belongs to CIDR: %v", ipAddr, cidr.Cidr)
if cidr.Cidr.Contains(ipAddr) {
// Found!
found = true
if _, ok := cidr.IPAddresses[ipAddr.String()]; ok {
return errors.New(IPAlreadyInStoreError)
}
addr := &AddressInfo{Address: ipAddr.String()}
cidr.IPAddresses[ipAddr.String()] = addr
ds.assignPodIPAddressUnsafe(addr, allocation.IPAMKey, allocation.Metadata, time.Unix(0, allocation.AllocationTimestamp))
ds.log.Debugf("Recovered %s => %s/%s", allocation.IPAMKey, eni.ID, addr.Address)
// Increment ENI IP usage upon finding assigned ips
prometheusmetrics.EniIPsInUse.WithLabelValues(eni.ID).Inc()
// Update prometheus for ips per cidr
// Secondary IP mode will have /32:1 and Prefix mode will have /28:<number of /32s>
prometheusmetrics.IpsPerCidr.With(prometheus.Labels{"cidr": cidr.Cidr.String()}).Inc()
break eniloop
}
}
}
if !found {
ds.log.Infof("datastore: Sandbox %s uses unknown IP Address %s - presuming stale/dead",
allocation.IPAMKey, ipAddr.String())
}
}
// Some entries may have been purged during recovery, so write to backing store
if err := ds.writeBackingStoreUnsafe(); err != nil {
ds.log.Warnf("Unable to update backing store after restoration: %v", err)
}
ds.log.Debugf("Completed ipam state recovery")
return nil
}
func (ds *DataStore) writeBackingStoreUnsafe() error {
allocations := make([]CheckpointEntry, 0, ds.assigned)
for _, eni := range ds.eniPool {
// Loop through ENI's v4 prefixes
for _, assignedAddr := range eni.AvailableIPv4Cidrs {
for _, addr := range assignedAddr.IPAddresses {
if addr.Assigned() {
entry := CheckpointEntry{
IPAMKey: addr.IPAMKey,
IPv4: addr.Address,
AllocationTimestamp: addr.AssignedTime.UnixNano(),
Metadata: addr.IPAMMetadata,
}
allocations = append(allocations, entry)
}
}
}
// Loop through ENI's v6 prefixes
for _, assignedAddr := range eni.IPv6Cidrs {
for _, addr := range assignedAddr.IPAddresses {
if addr.Assigned() {
entry := CheckpointEntry{
IPAMKey: addr.IPAMKey,
IPv6: addr.Address,
AllocationTimestamp: addr.AssignedTime.UnixNano(),
Metadata: addr.IPAMMetadata,
}
allocations = append(allocations, entry)
}
}
}
}
data := CheckpointData{
Version: CheckpointFormatVersion,
Allocations: allocations,
}
return ds.backingStore.Checkpoint(&data)
}
// AddENI add ENI to data store
func (ds *DataStore) AddENI(eniID string, deviceNumber int, isPrimary, isTrunk, isEFA bool) error {
ds.lock.Lock()
defer ds.lock.Unlock()
ds.log.Debugf("DataStore add an ENI %s", eniID)
_, ok := ds.eniPool[eniID]
if ok {
return errors.New(DuplicatedENIError)
}
ds.eniPool[eniID] = &ENI{
createTime: time.Now(),
IsPrimary: isPrimary,
IsTrunk: isTrunk,
IsEFA: isEFA,
ID: eniID,
DeviceNumber: deviceNumber,
AvailableIPv4Cidrs: make(map[string]*CidrInfo)}
prometheusmetrics.Enis.Set(float64(len(ds.eniPool)))
// Initialize ENI IPs In Use to 0 when an ENI is created
prometheusmetrics.EniIPsInUse.WithLabelValues(eniID).Set(0)
return nil
}
// AddIPv4AddressToStore adds IPv4 CIDR of an ENI to data store
func (ds *DataStore) AddIPv4CidrToStore(eniID string, ipv4Cidr net.IPNet, isPrefix bool) error {
ds.lock.Lock()
defer ds.lock.Unlock()
strIPv4Cidr := ipv4Cidr.String()
ds.log.Infof("Adding %s to DS for %s", strIPv4Cidr, eniID)
curENI, ok := ds.eniPool[eniID]
if !ok {
ds.log.Infof("unknown ENI")
return errors.New("add ENI's IP to datastore: unknown ENI")
}
// Already there
_, ok = curENI.AvailableIPv4Cidrs[strIPv4Cidr]
if ok {
ds.log.Infof("IP already in DS")
return errors.New(IPAlreadyInStoreError)
}
newCidrInfo := &CidrInfo{
Cidr: ipv4Cidr,
IPAddresses: make(map[string]*AddressInfo),
IsPrefix: isPrefix,
AddressFamily: "4",
}
curENI.AvailableIPv4Cidrs[strIPv4Cidr] = newCidrInfo
ds.total += newCidrInfo.Size()
if isPrefix {
ds.allocatedPrefix++
prometheusmetrics.TotalPrefixes.Set(float64(ds.allocatedPrefix))
}
prometheusmetrics.TotalIPs.Set(float64(ds.total))
ds.log.Infof("Added ENI(%s)'s IP/Prefix %s to datastore", eniID, strIPv4Cidr)
return nil
}
func (ds *DataStore) DelIPv4CidrFromStore(eniID string, cidr net.IPNet, force bool) error {
ds.lock.Lock()
defer ds.lock.Unlock()
curENI, ok := ds.eniPool[eniID]
if !ok {
ds.log.Debugf("Unknown ENI %s while deleting the CIDR", eniID)
return errors.New(UnknownENIError)
}
strIPv4Cidr := cidr.String()
var deletableCidr *CidrInfo
deletableCidr, ok = curENI.AvailableIPv4Cidrs[strIPv4Cidr]
if !ok {
ds.log.Debugf("Unknown %s CIDR", strIPv4Cidr)
return errors.New(UnknownIPError)
}
// SIP case : This runs just once
// PD case : if (force is false) then if there are any unassigned IPs, those will get freed but the first assigned IP will
// break the loop, should be fine since freed IPs will be reused for new pods.
updateBackingStore := false
for _, addr := range deletableCidr.IPAddresses {
if addr.Assigned() {
if !force {
return errors.New(IPInUseError)
}
prometheusmetrics.ForceRemovedIPs.Inc()
ds.unassignPodIPAddressUnsafe(addr)
updateBackingStore = true
}
}
if updateBackingStore {
if err := ds.writeBackingStoreUnsafe(); err != nil {
ds.log.Warnf("Unable to update backing store: %v", err)
// Continuing because 'force'
}
}
ds.total -= deletableCidr.Size()
if deletableCidr.IsPrefix {
ds.allocatedPrefix--
prometheusmetrics.TotalPrefixes.Set(float64(ds.allocatedPrefix))
}
prometheusmetrics.TotalIPs.Set(float64(ds.total))
delete(curENI.AvailableIPv4Cidrs, strIPv4Cidr)
ds.log.Infof("Deleted ENI(%s)'s IP/Prefix %s from datastore", eniID, strIPv4Cidr)
return nil
}
// AddIPv6AddressToStore adds IPv6 CIDR of an ENI to data store
func (ds *DataStore) AddIPv6CidrToStore(eniID string, ipv6Cidr net.IPNet, isPrefix bool) error {
ds.lock.Lock()
defer ds.lock.Unlock()
strIPv6Cidr := ipv6Cidr.String()
ds.log.Debugf("Adding %s to DS for %s", strIPv6Cidr, eniID)
curENI, ok := ds.eniPool[eniID]
ds.log.Debugf("ENI in pool %s", ok)
if !ok {
ds.log.Debugf("unkown ENI")
return errors.New("add ENI's IP to datastore: unknown ENI")
}
// Check if already present in datastore.
_, ok = curENI.IPv6Cidrs[strIPv6Cidr]
ds.log.Debugf("IP not in DS")
if ok {
ds.log.Debugf("IPv6 prefix %s already in DS", strIPv6Cidr)
return errors.New(IPAlreadyInStoreError)
}
ds.log.Debugf("Assigning IPv6CIDRs")
if curENI.IPv6Cidrs == nil {
curENI.IPv6Cidrs = make(map[string]*CidrInfo)
}
curENI.IPv6Cidrs[strIPv6Cidr] = &CidrInfo{
Cidr: ipv6Cidr,
IPAddresses: make(map[string]*AddressInfo),
IsPrefix: isPrefix,
AddressFamily: "6",
}
ds.total += curENI.IPv6Cidrs[strIPv6Cidr].Size()
if isPrefix {
ds.allocatedPrefix++
}
prometheusmetrics.TotalIPs.Set(float64(ds.total))
ds.log.Debugf("Added ENI(%s)'s IP/Prefix %s to datastore", eniID, strIPv6Cidr)
return nil
}
func (ds *DataStore) AssignPodIPAddress(ipamKey IPAMKey, ipamMetadata IPAMMetadata, isIPv4Enabled bool, isIPv6Enabled bool) (ipv4Address string,
ipv6Address string, deviceNumber int, err error) {
//Currently it's either v4 or v6. Dual Stack mode isn't supported.
if isIPv4Enabled {
ipv4Address, deviceNumber, err = ds.AssignPodIPv4Address(ipamKey, ipamMetadata)
} else if isIPv6Enabled {
ipv6Address, deviceNumber, err = ds.AssignPodIPv6Address(ipamKey, ipamMetadata)
}
return ipv4Address, ipv6Address, deviceNumber, err
}
// AssignPodIPv6Address assigns an IPv6 address to pod. Returns the assigned IPv6 address along with device number
func (ds *DataStore) AssignPodIPv6Address(ipamKey IPAMKey, ipamMetadata IPAMMetadata) (ipv6Address string, deviceNumber int, err error) {
ds.lock.Lock()
defer ds.lock.Unlock()
if !ds.isPDEnabled {
return "", -1, fmt.Errorf("PD is not enabled. V6 is only supported in PD mode")
}
ds.log.Debugf("AssignPodIPv6Address: IPv6 address pool stats: assigned %d", ds.assigned)
if eni, _, addr := ds.eniPool.FindAddressForSandbox(ipamKey); addr != nil {
ds.log.Infof("AssignPodIPv6Address: duplicate pod assign for sandbox %s", ipamKey)
return addr.Address, eni.DeviceNumber, nil
}
// In IPv6 Prefix Delegation mode, eniPool will only have Primary ENI.
for _, eni := range ds.eniPool {
if len(eni.IPv6Cidrs) == 0 {
continue
}
for _, V6Cidr := range eni.IPv6Cidrs {
if !V6Cidr.IsPrefix {
continue
}
ipv6Address, err = ds.getFreeIPv6AddrFromCidr(V6Cidr)
if err != nil {
ds.log.Debugf("Unable to get IP address from prefix: %v", err)
//In v6 mode, we (should) only have one CIDR/Prefix. So, we can bail out but we will let the loop
//exit instead.
continue
}
ds.log.Debugf("New v6 IP from PD pool- %s", ipv6Address)
addr := &AddressInfo{Address: ipv6Address}
V6Cidr.IPAddresses[ipv6Address] = addr
ds.assignPodIPAddressUnsafe(addr, ipamKey, ipamMetadata, time.Now())
if err := ds.writeBackingStoreUnsafe(); err != nil {
ds.log.Warnf("Failed to update backing store: %v", err)
// Important! Unwind assignment
ds.unassignPodIPAddressUnsafe(addr)
//Remove the IP from eni DB
delete(V6Cidr.IPAddresses, addr.Address)
return "", -1, err
}
// Increment ENI IP usage on pod IPv6 allocation
prometheusmetrics.EniIPsInUse.WithLabelValues(eni.ID).Inc()
return addr.Address, eni.DeviceNumber, nil
}
}
prometheusmetrics.NoAvailableIPAddrs.Inc()
return "", -1, errors.New("AssignPodIPv6Address: no available IP addresses")
}
// AssignPodIPv4Address assigns an IPv4 address to pod
// It returns the assigned IPv4 address, device number, error
func (ds *DataStore) AssignPodIPv4Address(ipamKey IPAMKey, ipamMetadata IPAMMetadata) (ipv4address string, deviceNumber int, err error) {
ds.lock.Lock()
defer ds.lock.Unlock()
ds.log.Debugf("AssignPodIPv4Address: IP address pool stats: total %d, assigned %d", ds.total, ds.assigned)
if eni, _, addr := ds.eniPool.FindAddressForSandbox(ipamKey); addr != nil {
ds.log.Infof("AssignPodIPv4Address: duplicate pod assign for sandbox %s", ipamKey)
return addr.Address, eni.DeviceNumber, nil
}
for _, eni := range ds.eniPool {
for _, availableCidr := range eni.AvailableIPv4Cidrs {
var addr *AddressInfo
var strPrivateIPv4 string
var err error
if (ds.isPDEnabled && availableCidr.IsPrefix) || (!ds.isPDEnabled && !availableCidr.IsPrefix) {
strPrivateIPv4, err = ds.getFreeIPv4AddrfromCidr(availableCidr)
if err != nil {
ds.log.Debugf("Unable to get IP address from CIDR: %v", err)
// Check in next CIDR
continue
}
ds.log.Debugf("New IP from CIDR pool- %s", strPrivateIPv4)
if availableCidr.IPAddresses == nil {
availableCidr.IPAddresses = make(map[string]*AddressInfo)
}
// Update prometheus for ips per cidr
// Secondary IP mode will have /32:1 and Prefix mode will have /28:<number of /32s>
prometheusmetrics.IpsPerCidr.With(prometheus.Labels{"cidr": availableCidr.Cidr.String()}).Inc()
} else {
// This can happen during upgrade or PD enable/disable knob toggle
// ENI can have prefixes attached and no space for SIPs or vice versa
continue
}
addr = availableCidr.IPAddresses[strPrivateIPv4]
if addr == nil {
// addr is nil when we are using a new IP from prefix or SIP pool
// if addr is out of cooldown or not assigned, we can reuse addr
addr = &AddressInfo{Address: strPrivateIPv4}
}
availableCidr.IPAddresses[strPrivateIPv4] = addr
ds.assignPodIPAddressUnsafe(addr, ipamKey, ipamMetadata, time.Now())
if err := ds.writeBackingStoreUnsafe(); err != nil {
ds.log.Warnf("Failed to update backing store: %v", err)
// Important! Unwind assignment
ds.unassignPodIPAddressUnsafe(addr)
// Remove the IP from eni DB
delete(availableCidr.IPAddresses, addr.Address)
// Update prometheus for ips per cidr
prometheusmetrics.IpsPerCidr.With(prometheus.Labels{"cidr": availableCidr.Cidr.String()}).Dec()
return "", -1, err
}
// Increment ENI IP usage on pod IPv4 allocation
prometheusmetrics.EniIPsInUse.WithLabelValues(eni.ID).Inc()
return addr.Address, eni.DeviceNumber, nil
}
ds.log.Debugf("AssignPodIPv4Address: ENI %s does not have available addresses", eni.ID)
}
prometheusmetrics.NoAvailableIPAddrs.Inc()
ds.log.Errorf("DataStore has no available IP/Prefix addresses")
return "", -1, errors.New("AssignPodIPv4Address: no available IP/Prefix addresses")
}
// assignPodIPAddressUnsafe mark Address as assigned.
func (ds *DataStore) assignPodIPAddressUnsafe(addr *AddressInfo, ipamKey IPAMKey, ipamMetadata IPAMMetadata, assignedTime time.Time) {
ds.log.Infof("assignPodIPAddressUnsafe: Assign IP %v to sandbox %s",
addr.Address, ipamKey)
if addr.Assigned() {
panic("addr already assigned")
}
addr.IPAMKey = ipamKey // This marks the addr as assigned
addr.IPAMMetadata = ipamMetadata
addr.AssignedTime = assignedTime
ds.assigned++
// Prometheus gauge
prometheusmetrics.AssignedIPs.Set(float64(ds.assigned))
}
// unassignPodIPAddressUnsafe mark Address as unassigned.
func (ds *DataStore) unassignPodIPAddressUnsafe(addr *AddressInfo) {
if !addr.Assigned() {
// Already unassigned
return
}
ds.log.Infof("unassignPodIPAddressUnsafe: Unassign IP %v from sandbox %s",
addr.Address, addr.IPAMKey)
addr.IPAMKey = IPAMKey{} // unassign the addr
addr.IPAMMetadata = IPAMMetadata{}
ds.assigned--
// Prometheus gauge
prometheusmetrics.AssignedIPs.Set(float64(ds.assigned))
}
type DataStoreStats struct {
// Total number of addresses allocated
TotalIPs int
// Total number of prefixes allocated
TotalPrefixes int
// Number of assigned addresses
AssignedIPs int
// Number of addresses in cooldown
CooldownIPs int
}
func (stats *DataStoreStats) String() string {
return fmt.Sprintf("Total IPs/Prefixes = %d/%d, AssignedIPs/CooldownIPs: %d/%d",
stats.TotalIPs, stats.TotalPrefixes, stats.AssignedIPs, stats.CooldownIPs)
}
func (stats *DataStoreStats) AvailableAddresses() int {
return stats.TotalIPs - stats.AssignedIPs
}
// GetIPStats returns DataStoreStats for addressFamily
func (ds *DataStore) GetIPStats(addressFamily string) *DataStoreStats {
ds.lock.Lock()
defer ds.lock.Unlock()
stats := &DataStoreStats{
TotalPrefixes: ds.allocatedPrefix,
}
for _, eni := range ds.eniPool {
AssignedCIDRs := eni.AvailableIPv4Cidrs
if addressFamily == "6" {
AssignedCIDRs = eni.IPv6Cidrs
}
for _, cidr := range AssignedCIDRs {
if addressFamily == "4" && ((ds.isPDEnabled && cidr.IsPrefix) || (!ds.isPDEnabled && !cidr.IsPrefix)) {
cidrStats := cidr.GetIPStatsFromCidr(ds.ipCooldownPeriod)
stats.AssignedIPs += cidrStats.AssignedIPs
stats.CooldownIPs += cidrStats.CooldownIPs
stats.TotalIPs += cidr.Size()
} else if addressFamily == "6" {
stats.AssignedIPs += cidr.AssignedIPAddressesInCidr()
stats.TotalIPs += cidr.Size()
}
}
}
return stats
}
// GetTrunkENI returns the trunk ENI ID or an empty string
func (ds *DataStore) GetTrunkENI() string {
ds.lock.Lock()
defer ds.lock.Unlock()
for _, eni := range ds.eniPool {
if eni.IsTrunk {
return eni.ID
}
}
return ""
}
// GetEFAENIs returns the a map containing all attached EFA ENIs
func (ds *DataStore) GetEFAENIs() map[string]bool {
ds.lock.Lock()
defer ds.lock.Unlock()
ret := make(map[string]bool)
for _, eni := range ds.eniPool {
if eni.IsEFA {
ret[eni.ID] = true
}
}
return ret
}
// IsRequiredForWarmIPTarget determines if this ENI has warm IPs that are required to fulfill whatever WARM_IP_TARGET is set to.
func (ds *DataStore) isRequiredForWarmIPTarget(warmIPTarget int, eni *ENI) bool {
otherWarmIPs := 0
for _, other := range ds.eniPool {
if other.ID != eni.ID {
for _, otherPrefixes := range other.AvailableIPv4Cidrs {
if (ds.isPDEnabled && otherPrefixes.IsPrefix) || (!ds.isPDEnabled && !otherPrefixes.IsPrefix) {
otherWarmIPs += otherPrefixes.Size() - otherPrefixes.AssignedIPAddressesInCidr()
}
}
}
}
if ds.isPDEnabled {
_, numIPsPerPrefix, _ := GetPrefixDelegationDefaults()
numPrefixNeeded := DivCeil(warmIPTarget, numIPsPerPrefix)
warmIPTarget = numPrefixNeeded * numIPsPerPrefix
}
return otherWarmIPs < warmIPTarget
}
// IsRequiredForMinimumIPTarget determines if this ENI is necessary to fulfill whatever MINIMUM_IP_TARGET is set to.
func (ds *DataStore) isRequiredForMinimumIPTarget(minimumIPTarget int, eni *ENI) bool {
otherIPs := 0
for _, other := range ds.eniPool {
if other.ID != eni.ID {
for _, otherPrefixes := range other.AvailableIPv4Cidrs {
if (ds.isPDEnabled && otherPrefixes.IsPrefix) || (!ds.isPDEnabled && !otherPrefixes.IsPrefix) {
otherIPs += otherPrefixes.Size()
}
}
}
}
if ds.isPDEnabled {
_, numIPsPerPrefix, _ := GetPrefixDelegationDefaults()
numPrefixNeeded := DivCeil(minimumIPTarget, numIPsPerPrefix)
minimumIPTarget = numPrefixNeeded * numIPsPerPrefix
}
return otherIPs < minimumIPTarget
}
// IsRequiredForWarmPrefixTarget determines if this ENI is necessary to fulfill whatever WARM_PREFIX_TARGET is set to.
func (ds *DataStore) isRequiredForWarmPrefixTarget(warmPrefixTarget int, eni *ENI) bool {
freePrefixes := 0
for _, other := range ds.eniPool {
if other.ID != eni.ID {
for _, otherPrefixes := range other.AvailableIPv4Cidrs {
if otherPrefixes.AssignedIPAddressesInCidr() == 0 {
freePrefixes++
}
}
}
}
return freePrefixes < warmPrefixTarget
}
func (ds *DataStore) getDeletableENI(warmIPTarget, minimumIPTarget, warmPrefixTarget int) *ENI {
for _, eni := range ds.eniPool {
if eni.IsPrimary {
ds.log.Debugf("ENI %s cannot be deleted because it is primary", eni.ID)
continue
}
if eni.isTooYoung() {
ds.log.Debugf("ENI %s cannot be deleted because it is too young", eni.ID)
continue
}
if eni.hasIPInCooling(ds.ipCooldownPeriod) {
ds.log.Debugf("ENI %s cannot be deleted because has IPs in cooling", eni.ID)
continue
}
if eni.hasPods() {
ds.log.Debugf("ENI %s cannot be deleted because it has pods assigned", eni.ID)
continue
}
if warmIPTarget != 0 && ds.isRequiredForWarmIPTarget(warmIPTarget, eni) {
ds.log.Debugf("ENI %s cannot be deleted because it is required for WARM_IP_TARGET: %d", eni.ID, warmIPTarget)
continue
}
if minimumIPTarget != 0 && ds.isRequiredForMinimumIPTarget(minimumIPTarget, eni) {
ds.log.Debugf("ENI %s cannot be deleted because it is required for MINIMUM_IP_TARGET: %d", eni.ID, minimumIPTarget)
continue
}
if ds.isPDEnabled && warmPrefixTarget != 0 && ds.isRequiredForWarmPrefixTarget(warmPrefixTarget, eni) {
ds.log.Debugf("ENI %s cannot be deleted because it is required for WARM_PREFIX_TARGET: %d", eni.ID, warmPrefixTarget)
continue
}
if eni.IsTrunk {
ds.log.Debugf("ENI %s cannot be deleted because it is a trunk ENI", eni.ID)
continue
}
if eni.IsEFA {
ds.log.Debugf("ENI %s cannot be deleted because it is an EFA ENI", eni.ID)
continue
}
ds.log.Debugf("getDeletableENI: found a deletable ENI %s", eni.ID)
return eni
}
return nil
}
// IsTooYoung returns true if the ENI hasn't been around long enough to be deleted.
func (e *ENI) isTooYoung() bool {
return time.Since(e.createTime) < minENILifeTime
}
// HasIPInCooling returns true if an IP address was unassigned recently.
func (e *ENI) hasIPInCooling(ipCooldownPeriod time.Duration) bool {
for _, assignedaddr := range e.AvailableIPv4Cidrs {
for _, addr := range assignedaddr.IPAddresses {
if addr.inCoolingPeriod(ipCooldownPeriod) {
return true
}
}
}
return false
}
// HasPods returns true if the ENI has pods assigned to it.
func (e *ENI) hasPods() bool {
return e.AssignedIPv4Addresses() != 0
}
// GetAllocatableENIs finds ENIs in the datastore that needs more IP addresses allocated
func (ds *DataStore) GetAllocatableENIs(maxIPperENI int, skipPrimary bool) []*ENI {
var enis []*ENI
ds.lock.Lock()
defer ds.lock.Unlock()
for _, eni := range ds.eniPool {
if (skipPrimary && eni.IsPrimary) || eni.IsTrunk {
ds.log.Debugf("Skip needs IP check for trunk ENI of primary ENI when Custom Networking is enabled")
continue
}
if len(eni.AvailableIPv4Cidrs) < maxIPperENI {
ds.log.Debugf("Found ENI %s that has less than the maximum number of IP/Prefixes addresses allocated: cur=%d, max=%d",
eni.ID, len(eni.AvailableIPv4Cidrs), maxIPperENI)
enis = append(enis, eni)
}
}
return enis
}
// RemoveUnusedENIFromStore removes a deletable ENI from the data store.
// It returns the name of the ENI which has been removed from the data store and needs to be deleted,
// or empty string if no ENI could be removed.
func (ds *DataStore) RemoveUnusedENIFromStore(warmIPTarget, minimumIPTarget, warmPrefixTarget int) string {
ds.lock.Lock()
defer ds.lock.Unlock()