Debian Codegraph @

plugins/ipam/dhcp/lease.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 main
16
17 import (
18 "context"
19 "errors"
20 "fmt"
21 "log"
22 "math/rand"
23 "net"
24 "strings"
25 "sync"
26 "sync/atomic"
27 "time"
28
29 dhcp4 "github.com/insomniacslk/dhcp/dhcpv4"
30 "github.com/insomniacslk/dhcp/dhcpv4/nclient4"
31 "github.com/vishvananda/netlink"
32
33 "github.com/containernetworking/cni/pkg/types"
34 "github.com/containernetworking/plugins/pkg/netlinksafe"
35 "github.com/containernetworking/plugins/pkg/ns"
36 )
37
38 // RFC 2131 suggests using exponential backoff, starting with 4sec
39 // and randomized to +/- 1sec
40 const (
41 resendDelay0 = 4 * time.Second
42 resendDelayMax = 62 * time.Second
43 defaultLeaseTime = 60 * time.Minute
44 defaultResendTimeout = 208 * time.Second // fast resend + backoff resend
45 )
46
47 // To speed up the retry for first few failures, we retry without
48 // backoff for a few times
49 const (
50 resendFastDelay = 2 * time.Second
51 resendFastMax = 4
52 )
53
54 const (
55 leaseStateBound = iota
56 leaseStateRenewing
57 leaseStateRebinding
58 )
59
60 // Timing for retrying link existence check
61 const (
62 linkCheckDelay0 = 1 * time.Second
63 linkCheckRetryMax = 10 * time.Second
64 linkCheckTotalTimeout = 30 * time.Second
65 )
66
67 // This implementation uses 1 OS thread per lease. This is because
68 // all the network operations have to be done in network namespace
69 // of the interface. This can be improved by switching to the proper
70 // namespace for network ops and using fewer threads. However, this
71 // needs to be done carefully as dhcp4client ops are blocking.
72
73 type DHCPLease struct {
74 clientID string
75 latestLease *nclient4.Lease
76 link netlink.Link
77 linkName string
78 renewalTime time.Time
79 rebindingTime time.Time
80 expireTime time.Time
81 timeout time.Duration
82 resendMax time.Duration
83 resendTimeout time.Duration
84 broadcast bool
85 stopping uint32
86 stop chan struct{}
87 check chan struct{}
88 wg sync.WaitGroup
89 cancelFunc context.CancelFunc
90 ctx context.Context
91 // list of requesting and providing options and if they are necessary / their value
92 opts []dhcp4.Option
93 }
94
95 var requestOptionsDefault = []dhcp4.OptionCode{
96 dhcp4.OptionRouter,
97 dhcp4.OptionSubnetMask,
98 }
99
100 func prepareOptions(cniArgs string, provideOptions []ProvideOption, requestOptions []RequestOption) (
101 []dhcp4.Option, error,
102 ) {
103 var opts []dhcp4.Option
104
105 var err error
106 // parse CNI args
107 cniArgsParsed := map[string]string{}
108 for _, argPair := range strings.Split(cniArgs, ";") {
109 args := strings.SplitN(argPair, "=", 2)
110 if len(args) > 1 {
111 cniArgsParsed[args[0]] = args[1]
112 }
113 }
114
115 // parse providing options map
116 var optParsed dhcp4.OptionCode
117 for _, opt := range provideOptions {
118 optParsed, err = parseOptionName(string(opt.Option))
119 if err != nil {
120 return nil, fmt.Errorf("Can not parse option %q: %w", opt.Option, err)
121 }
122 if len(opt.Value) > 0 {
123 if len(opt.Value) > 255 {
124 return nil, fmt.Errorf("value too long for option %q: %q", opt.Option, opt.Value)
125 }
126 opts = append(opts, dhcp4.Option{Code: optParsed, Value: dhcp4.String(opt.Value)})
127 }
128 if value, ok := cniArgsParsed[opt.ValueFromCNIArg]; ok {
129 if len(value) > 255 {
130 return nil, fmt.Errorf("value too long for option %q from CNI_ARGS %q: %q", opt.Option, opt.ValueFromCNIArg, opt.Value)
131 }
132 opts = append(opts, dhcp4.Option{Code: optParsed, Value: dhcp4.String(value)})
133 }
134 }
135
136 // parse necessary options map
137 var optsRequesting dhcp4.OptionCodeList
138 skipRequireDefault := false
139 for _, opt := range requestOptions {
140 if opt.SkipDefault {
141 skipRequireDefault = true
142 }
143 if opt.Option == "" {
144 continue
145 }
146 optParsed, err = parseOptionName(string(opt.Option))
147 if err != nil {
148 return nil, fmt.Errorf("Can not parse option %q: %w", opt.Option, err)
149 }
150 optsRequesting.Add(optParsed)
151 }
152 if !skipRequireDefault {
153 for _, opt := range requestOptionsDefault {
154 optsRequesting.Add(opt)
155 }
156 }
157 if len(optsRequesting) > 0 {
158 opts = append(opts, dhcp4.Option{Code: dhcp4.OptionParameterRequestList, Value: optsRequesting})
159 }
160
161 return opts, err
162 }
163
164 // AcquireLease gets an DHCP lease and then maintains it in the background
165 // by periodically renewing it. The acquired lease can be released by
166 // calling DHCPLease.Stop()
167 func AcquireLease(
168 clientID, netns, ifName string,
169 opts []dhcp4.Option,
170 timeout, resendMax time.Duration, resendTimeout time.Duration, broadcast bool,
171 ) (*DHCPLease, error) {
172 errCh := make(chan error, 1)
173
174 ctx := context.Background()
175 ctx, cancel := context.WithCancel(ctx)
176
177 l := &DHCPLease{
178 clientID: clientID,
179 stop: make(chan struct{}),
180 check: make(chan struct{}),
181 timeout: timeout,
182 resendMax: resendMax,
183 resendTimeout: resendTimeout,
184 broadcast: broadcast,
185 opts: opts,
186 cancelFunc: cancel,
187 ctx: ctx,
188 }
189
190 log.Printf("%v: acquiring lease", clientID)
191
192 l.wg.Add(1)
193 go func() {
194 errCh <- ns.WithNetNSPath(netns, func(_ ns.NetNS) error {
195 defer l.wg.Done()
196
197 link, err := netlinksafe.LinkByName(ifName)
198 if err != nil {
199 return fmt.Errorf("error looking up %q: %v", ifName, err)
200 }
201
202 l.link = link
203 l.linkName = link.Attrs().Name
204
205 if err = l.acquire(); err != nil {
206 return err
207 }
208
209 log.Printf("%v: lease acquired, expiration is %v", l.clientID, l.expireTime)
210
211 errCh <- nil
212
213 l.maintain()
214 return nil
215 })
216 }()
217
218 if err := <-errCh; err != nil {
219 return nil, err
220 }
221
222 return l, nil
223 }
224
225 // Stop terminates the background task that maintains the lease
226 // and issues a DHCP Release
227 func (l *DHCPLease) Stop() {
228 if atomic.CompareAndSwapUint32(&l.stopping, 0, 1) {
229 close(l.stop)
230 l.cancelFunc()
231 }
232 l.wg.Wait()
233 }
234
235 func (l *DHCPLease) Check() {
236 l.check <- struct{}{}
237 }
238
239 func withClientID(clientID string) dhcp4.Modifier {
240 return func(d *dhcp4.DHCPv4) {
241 optClientID := []byte{0}
242 optClientID = append(optClientID, []byte(clientID)...)
243 d.Options.Update(dhcp4.OptClientIdentifier(optClientID))
244 }
245 }
246
247 func withAllOptions(l *DHCPLease) dhcp4.Modifier {
248 return func(d *dhcp4.DHCPv4) {
249 for _, opt := range l.opts {
250 d.Options.Update(opt)
251 }
252 }
253 }
254
255 func (l *DHCPLease) acquire() error {
256 if (l.link.Attrs().Flags & net.FlagUp) != net.FlagUp {
257 log.Printf("Link %q down. Attempting to set up", l.linkName)
258 if err := netlink.LinkSetUp(l.link); err != nil {
259 return err
260 }
261 }
262
263 c, err := newDHCPClient(l.link, l.timeout)
264 if err != nil {
265 return err
266 }
267 defer c.Close()
268
269 timeoutCtx, cancel := context.WithTimeoutCause(l.ctx, l.resendTimeout, errNoMoreTries)
270 defer cancel()
271 pkt, err := backoffRetry(timeoutCtx, l.resendMax, func() (*nclient4.Lease, error) {
272 return c.Request(
273 timeoutCtx,
274 withClientID(l.clientID),
275 withAllOptions(l),
276 )
277 })
278 if err != nil {
279 return err
280 }
281
282 l.commit(pkt)
283 return nil
284 }
285
286 func (l *DHCPLease) commit(lease *nclient4.Lease) {
287 l.latestLease = lease
288 ack := lease.ACK
289
290 leaseTime := ack.IPAddressLeaseTime(defaultLeaseTime)
291 rebindingTime := ack.IPAddressRebindingTime(leaseTime * 85 / 100)
292 renewalTime := ack.IPAddressRenewalTime(leaseTime / 2)
293
294 now := time.Now()
295 l.expireTime = now.Add(leaseTime)
296 l.renewalTime = now.Add(renewalTime)
297 l.rebindingTime = now.Add(rebindingTime)
298 }
299
300 func (l *DHCPLease) maintain() {
301 state := leaseStateBound
302
303 for {
304 var sleepDur time.Duration
305
306 linkCheckCtx, cancel := context.WithTimeoutCause(l.ctx, l.resendTimeout, errNoMoreTries)
307 defer cancel()
308 linkExists, _ := checkLinkExistsWithBackoff(linkCheckCtx, l.linkName)
309 if !linkExists {
310 log.Printf("%v: interface %s no longer exists or link check failed, terminating lease maintenance", l.clientID, l.linkName)
311 return
312 }
313
314 switch state {
315 case leaseStateBound:
316 sleepDur = time.Until(l.renewalTime)
317 if sleepDur <= 0 {
318 log.Printf("%v: renewing lease", l.clientID)
319 state = leaseStateRenewing
320 continue
321 }
322
323 case leaseStateRenewing:
324 if err := l.renew(); err != nil {
325 log.Printf("%v: %v", l.clientID, err)
326
327 if time.Now().After(l.rebindingTime) {
328 log.Printf("%v: renewal time expired, rebinding", l.clientID)
329 state = leaseStateRebinding
330 }
331 } else {
332 log.Printf("%v: lease renewed, expiration is %v", l.clientID, l.expireTime)
333 state = leaseStateBound
334 }
335
336 case leaseStateRebinding:
337 if err := l.acquire(); err != nil {
338 log.Printf("%v: %v", l.clientID, err)
339
340 if time.Now().After(l.expireTime) {
341 log.Printf("%v: lease expired, bringing interface DOWN", l.clientID)
342 l.downIface()
343 return
344 }
345 } else {
346 log.Printf("%v: lease rebound, expiration is %v", l.clientID, l.expireTime)
347 state = leaseStateBound
348 }
349 }
350
351 select {
352 case <-time.After(sleepDur):
353
354 case <-l.check:
355 log.Printf("%v: Checking lease", l.clientID)
356
357 case <-l.stop:
358 if err := l.release(); err != nil {
359 log.Printf("%v: failed to release DHCP lease: %v", l.clientID, err)
360 }
361 return
362 }
363 }
364 }
365
366 func checkLinkExistsWithBackoff(ctx context.Context, linkName string) (bool, error) {
367 baseDelay := linkCheckDelay0
368 for {
369 exists, err := checkLinkByName(linkName)
370 if err == nil {
371 return exists, nil
372 }
373
374 select {
375 case <-ctx.Done():
376 return false, ctx.Err() // Context's done, return with its error
377 case <-time.After(baseDelay):
378 if baseDelay < linkCheckRetryMax {
379 baseDelay *= 2
380 }
381 }
382 }
383 }
384
385 func checkLinkByName(linkName string) (bool, error) {
386 _, err := netlinksafe.LinkByName(linkName)
387 if err != nil {
388 linkNotFoundErr := &netlink.LinkNotFoundError{}
389 if errors.As(err, linkNotFoundErr) {
390 return false, nil
391 }
392 return false, err
393 }
394 return true, nil
395 }
396
397 func (l *DHCPLease) downIface() {
398 if err := netlink.LinkSetDown(l.link); err != nil {
399 log.Printf("%v: failed to bring %v interface DOWN: %v", l.clientID, l.linkName, err)
400 }
401 }
402
403 func (l *DHCPLease) renew() error {
404 c, err := newDHCPClient(l.link, l.timeout)
405 if err != nil {
406 return err
407 }
408 defer c.Close()
409
410 timeoutCtx, cancel := context.WithTimeoutCause(l.ctx, l.resendTimeout, errNoMoreTries)
411 defer cancel()
412 lease, err := backoffRetry(timeoutCtx, l.resendMax, func() (*nclient4.Lease, error) {
413 return c.Renew(
414 timeoutCtx,
415 l.latestLease,
416 withClientID(l.clientID),
417 withAllOptions(l),
418 )
419 })
420 if err != nil {
421 return err
422 }
423
424 l.commit(lease)
425 return nil
426 }
427
428 func (l *DHCPLease) release() error {
429 log.Printf("%v: releasing lease", l.clientID)
430
431 c, err := newDHCPClient(l.link, l.timeout)
432 if err != nil {
433 return err
434 }
435 defer c.Close()
436
437 if err = c.Release(l.latestLease, withClientID(l.clientID)); err != nil {
438 return fmt.Errorf("failed to send DHCPRELEASE")
439 }
440
441 return nil
442 }
443
444 func (l *DHCPLease) IPNet() (*net.IPNet, error) {
445 ack := l.latestLease.ACK
446
447 mask := ack.SubnetMask()
448 if mask == nil {
449 return nil, fmt.Errorf("DHCP option Subnet Mask not found in DHCPACK")
450 }
451
452 return &net.IPNet{
453 IP: ack.YourIPAddr,
454 Mask: mask,
455 }, nil
456 }
457
458 func (l *DHCPLease) Gateway() net.IP {
459 ack := l.latestLease.ACK
460 gws := ack.Router()
461 if len(gws) > 0 {
462 return gws[0]
463 }
464 return nil
465 }
466
467 func (l *DHCPLease) Routes() []*types.Route {
468 routes := []*types.Route{}
469
470 ack := l.latestLease.ACK
471
472 // RFC 3442 states that if Classless Static Routes (option 121)
473 // exist, we ignore Static Routes (option 33) and the Router/Gateway.
474 opt121Routes := ack.ClasslessStaticRoute()
475 if len(opt121Routes) > 0 {
476 for _, r := range opt121Routes {
477 route := &types.Route{Dst: *r.Dest, GW: r.Router}
478 // if router is not specified, add SCOPE_LINK so routes are installed
479 if r.Router.IsUnspecified() {
480 scopeLinkValue := int(netlink.SCOPE_LINK)
481 route.Scope = &scopeLinkValue
482 }
483 routes = append(routes, route)
484 }
485 return routes
486 }
487
488 // Append Static Routes
489 if ack.Options.Has(dhcp4.OptionStaticRoutingTable) {
490 routes = append(routes, parseRoutes(ack.Options.Get(dhcp4.OptionStaticRoutingTable))...)
491 }
492
493 // The CNI spec says even if there is a gateway specified, we must
494 // add a default route in the routes section.
495 if gw := l.Gateway(); gw != nil {
496 _, defaultRoute, _ := net.ParseCIDR("0.0.0.0/0")
497 routes = append(routes, &types.Route{Dst: *defaultRoute, GW: gw})
498 }
499
500 return routes
501 }
502
503 // jitter returns a random value within [-span, span) range
504 func jitter(span time.Duration) time.Duration {
505 return time.Duration(float64(span) * (2.0*rand.Float64() - 1.0))
506 }
507
508 func backoffRetry(ctx context.Context, resendMax time.Duration, f func() (*nclient4.Lease, error)) (*nclient4.Lease, error) {
509 baseDelay := resendDelay0
510 var sleepTime time.Duration
511 fastRetryLimit := resendFastMax
512 for {
513 pkt, err := f()
514 if err == nil {
515 return pkt, nil
516 }
517
518 log.Print(err)
519
520 if fastRetryLimit == 0 {
521 sleepTime = baseDelay + jitter(time.Second)
522 } else {
523 sleepTime = resendFastDelay + jitter(time.Second)
524 fastRetryLimit--
525 }
526
527 log.Printf("retrying in %f seconds", sleepTime.Seconds())
528
529 select {
530 case <-ctx.Done():
531 return nil, context.Cause(ctx)
532 case <-time.After(sleepTime):
533 // only adjust delay time if we are in normal backoff stage
534 if baseDelay < resendMax && fastRetryLimit == 0 {
535 baseDelay *= 2
536 }
537 }
538 }
539 }
540
541 func newDHCPClient(
542 link netlink.Link,
543 timeout time.Duration,
544 clientOpts ...nclient4.ClientOpt,
545 ) (*nclient4.Client, error) {
546 clientOpts = append(clientOpts, nclient4.WithTimeout(timeout))
547 return nclient4.New(link.Attrs().Name, clientOpts...)
548 }