Debian Codegraph @

plugins/ipam/host-local/backend/allocator/allocator.go

raw symbols SCIP
1 // Copyright 2015 CNI authors
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 allocator
16
17 import (
18 "fmt"
19 "log"
20 "net"
21 "os"
22 "strconv"
23
24 current "github.com/containernetworking/cni/pkg/types/100"
25 "github.com/containernetworking/plugins/pkg/ip"
26 "github.com/containernetworking/plugins/plugins/ipam/host-local/backend"
27 )
28
29 type IPAllocator struct {
30 rangeset *RangeSet
31 store backend.Store
32 rangeID string // Used for tracking last reserved ip
33 }
34
35 func NewIPAllocator(s *RangeSet, store backend.Store, id int) *IPAllocator {
36 return &IPAllocator{
37 rangeset: s,
38 store: store,
39 rangeID: strconv.Itoa(id),
40 }
41 }
42
43 // Get allocates an IP
44 func (a *IPAllocator) Get(id string, ifname string, requestedIP net.IP) (*current.IPConfig, error) {
45 a.store.Lock()
46 defer a.store.Unlock()
47
48 var reservedIP *net.IPNet
49 var gw net.IP
50
51 if requestedIP != nil {
52 if err := canonicalizeIP(&requestedIP); err != nil {
53 return nil, err
54 }
55
56 r, err := a.rangeset.RangeFor(requestedIP)
57 if err != nil {
58 return nil, err
59 }
60
61 if requestedIP.Equal(r.Gateway) {
62 return nil, fmt.Errorf("requested ip %s is subnet's gateway", requestedIP.String())
63 }
64
65 reserved, err := a.store.Reserve(id, ifname, requestedIP, a.rangeID)
66 if err != nil {
67 return nil, err
68 }
69 if !reserved {
70 return nil, fmt.Errorf("requested IP address %s is not available in range set %s", requestedIP, a.rangeset.String())
71 }
72 reservedIP = &net.IPNet{IP: requestedIP, Mask: r.Subnet.Mask}
73 gw = r.Gateway
74
75 } else {
76 // try to get allocated IPs for this given id, if exists, just return error
77 // because duplicate allocation is not allowed in SPEC
78 // https://github.com/containernetworking/cni/blob/master/SPEC.md
79 allocatedIPs := a.store.GetByID(id, ifname)
80 for _, allocatedIP := range allocatedIPs {
81 // check whether the existing IP belong to this range set
82 if _, err := a.rangeset.RangeFor(allocatedIP); err == nil {
83 return nil, fmt.Errorf("%s has been allocated to %s, duplicate allocation is not allowed", allocatedIP.String(), id)
84 }
85 }
86
87 iter, err := a.GetIter()
88 if err != nil {
89 return nil, err
90 }
91 for {
92 reservedIP, gw = iter.Next()
93 if reservedIP == nil {
94 break
95 }
96
97 reserved, err := a.store.Reserve(id, ifname, reservedIP.IP, a.rangeID)
98 if err != nil {
99 return nil, err
100 }
101
102 if reserved {
103 break
104 }
105 }
106 }
107
108 if reservedIP == nil {
109 return nil, fmt.Errorf("no IP addresses available in range set: %s", a.rangeset.String())
110 }
111
112 return &current.IPConfig{
113 Address: *reservedIP,
114 Gateway: gw,
115 }, nil
116 }
117
118 // Release clears all IPs allocated for the container with given ID
119 func (a *IPAllocator) Release(id string, ifname string) error {
120 a.store.Lock()
121 defer a.store.Unlock()
122
123 return a.store.ReleaseByID(id, ifname)
124 }
125
126 type RangeIter struct {
127 rangeset *RangeSet
128
129 // The current range id
130 rangeIdx int
131
132 // Our current position
133 cur net.IP
134
135 // The IP where we started iterating; if we hit this again, we're done.
136 startIP net.IP
137 }
138
139 // GetIter encapsulates the strategy for this allocator.
140 // We use a round-robin strategy, attempting to evenly use the whole set.
141 // More specifically, a crash-looping container will not see the same IP until
142 // the entire range has been run through.
143 // We may wish to consider avoiding recently-released IPs in the future.
144 func (a *IPAllocator) GetIter() (*RangeIter, error) {
145 iter := RangeIter{
146 rangeset: a.rangeset,
147 }
148
149 // Round-robin by trying to allocate from the last reserved IP + 1
150 startFromLastReservedIP := false
151
152 // We might get a last reserved IP that is wrong if the range indexes changed.
153 // This is not critical, we just lose round-robin this one time.
154 lastReservedIP, err := a.store.LastReservedIP(a.rangeID)
155 if err != nil && !os.IsNotExist(err) {
156 log.Printf("Error retrieving last reserved ip: %v", err)
157 } else if lastReservedIP != nil {
158 startFromLastReservedIP = a.rangeset.Contains(lastReservedIP)
159 }
160
161 // Find the range in the set with this IP
162 if startFromLastReservedIP {
163 for i, r := range *a.rangeset {
164 if r.Contains(lastReservedIP) {
165 iter.rangeIdx = i
166
167 // We advance the cursor on every Next(), so the first call
168 // to next() will return lastReservedIP + 1
169 iter.cur = lastReservedIP
170 break
171 }
172 }
173 } else {
174 iter.rangeIdx = 0
175 iter.startIP = (*a.rangeset)[0].RangeStart
176 }
177 return &iter, nil
178 }
179
180 // Next returns the next IP, its mask, and its gateway. Returns nil
181 // if the iterator has been exhausted
182 func (i *RangeIter) Next() (*net.IPNet, net.IP) {
183 r := (*i.rangeset)[i.rangeIdx]
184
185 // If this is the first time iterating and we're not starting in the middle
186 // of the range, then start at rangeStart, which is inclusive
187 if i.cur == nil {
188 i.cur = r.RangeStart
189 i.startIP = i.cur
190 if i.cur.Equal(r.Gateway) {
191 return i.Next()
192 }
193 return &net.IPNet{IP: i.cur, Mask: r.Subnet.Mask}, r.Gateway
194 }
195
196 // If we've reached the end of this range, we need to advance the range
197 // RangeEnd is inclusive as well
198 if i.cur.Equal(r.RangeEnd) {
199 i.rangeIdx++
200 i.rangeIdx %= len(*i.rangeset)
201 r = (*i.rangeset)[i.rangeIdx]
202
203 i.cur = r.RangeStart
204 } else {
205 i.cur = ip.NextIP(i.cur)
206 }
207
208 if i.startIP == nil {
209 i.startIP = i.cur
210 } else if i.cur.Equal(i.startIP) {
211 // IF we've looped back to where we started, give up
212 return nil, nil
213 }
214
215 if i.cur.Equal(r.Gateway) {
216 return i.Next()
217 }
218
219 return &net.IPNet{IP: i.cur, Mask: r.Subnet.Mask}, r.Gateway
220 }