github.com/fafucoder/cilium@v1.6.11/pkg/ipam/hostscope.go (about) 1 // Copyright 2017-2019 Authors of Cilium 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package ipam 16 17 import ( 18 "fmt" 19 "math/big" 20 "net" 21 22 "github.com/cilium/cilium/pkg/ip" 23 24 k8sAPI "k8s.io/kubernetes/pkg/apis/core" 25 "k8s.io/kubernetes/pkg/registry/core/service/ipallocator" 26 ) 27 28 type hostScopeAllocator struct { 29 allocCIDR *net.IPNet 30 allocator *ipallocator.Range 31 } 32 33 func newHostScopeAllocator(n *net.IPNet) Allocator { 34 cidrRange, err := ipallocator.NewCIDRRange(n) 35 if err != nil { 36 panic(err) 37 } 38 a := &hostScopeAllocator{ 39 allocCIDR: n, 40 allocator: cidrRange, 41 } 42 43 return a 44 } 45 46 func (h *hostScopeAllocator) Allocate(ip net.IP, owner string) (*AllocationResult, error) { 47 if err := h.allocator.Allocate(ip); err != nil { 48 return nil, err 49 } 50 51 return &AllocationResult{IP: ip}, nil 52 } 53 54 func (h *hostScopeAllocator) Release(ip net.IP) error { 55 return h.allocator.Release(ip) 56 } 57 58 func (h *hostScopeAllocator) AllocateNext(owner string) (*AllocationResult, error) { 59 ip, err := h.allocator.AllocateNext() 60 if err != nil { 61 return nil, err 62 } 63 64 return &AllocationResult{IP: ip}, nil 65 } 66 67 func (h *hostScopeAllocator) Dump() (map[string]string, string) { 68 var origIP *big.Int 69 alloc := map[string]string{} 70 ral := k8sAPI.RangeAllocation{} 71 h.allocator.Snapshot(&ral) 72 if h.allocCIDR.IP.To4() != nil { 73 origIP = big.NewInt(0).SetBytes(h.allocCIDR.IP.To4()) 74 } else { 75 origIP = big.NewInt(0).SetBytes(h.allocCIDR.IP.To16()) 76 } 77 bits := big.NewInt(0).SetBytes(ral.Data) 78 for i := 0; i < bits.BitLen(); i++ { 79 if bits.Bit(i) != 0 { 80 ip := net.IP(big.NewInt(0).Add(origIP, big.NewInt(int64(uint(i+1)))).Bytes()).String() 81 alloc[ip] = "" 82 } 83 } 84 85 maxIPs := ip.CountIPsInCIDR(h.allocCIDR) 86 status := fmt.Sprintf("%d/%d allocated from %s", len(alloc), maxIPs, h.allocCIDR.String()) 87 88 return alloc, status 89 }