| 1 | // Copyright 2017 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 ip |
| 16 | |
| 17 | import ( |
| 18 | "fmt" |
| 19 | "syscall" |
| 20 | "time" |
| 21 | |
| 22 | "github.com/vishvananda/netlink" |
| 23 | |
| 24 | "github.com/containernetworking/plugins/pkg/netlinksafe" |
| 25 | ) |
| 26 | |
| 27 | const SETTLE_INTERVAL = 50 * time.Millisecond |
| 28 | |
| 29 | // SettleAddresses waits for all addresses on a link to leave tentative state. |
| 30 | // This is particularly useful for ipv6, where all addresses need to do DAD. |
| 31 | // There is no easy way to wait for this as an event, so just loop until the |
| 32 | // addresses are no longer tentative. |
| 33 | // If any addresses are still tentative after timeout seconds, then error. |
| 34 | func SettleAddresses(ifName string, timeout time.Duration) error { |
| 35 | link, err := netlinksafe.LinkByName(ifName) |
| 36 | if err != nil { |
| 37 | return fmt.Errorf("failed to retrieve link: %v", err) |
| 38 | } |
| 39 | |
| 40 | deadline := time.Now().Add(timeout) |
| 41 | for { |
| 42 | addrs, err := netlinksafe.AddrList(link, netlink.FAMILY_V6) |
| 43 | if err != nil { |
| 44 | return fmt.Errorf("could not list addresses: %v", err) |
| 45 | } |
| 46 | |
| 47 | if len(addrs) == 0 { |
| 48 | return nil |
| 49 | } |
| 50 | |
| 51 | ok := true |
| 52 | for _, addr := range addrs { |
| 53 | if addr.Flags&(syscall.IFA_F_DADFAILED) != 0 { |
| 54 | return fmt.Errorf("link %s has address %s in DADFAILED state", |
| 55 | ifName, |
| 56 | addr.IP.String()) |
| 57 | } |
| 58 | |
| 59 | if addr.Flags&(syscall.IFA_F_TENTATIVE) != 0 { |
| 60 | ok = false |
| 61 | break // Break out of the `range addrs`, not the `for` |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | if ok { |
| 66 | return nil |
| 67 | } |
| 68 | if time.Now().After(deadline) { |
| 69 | link, err := netlinksafe.LinkByName(ifName) |
| 70 | if err != nil { |
| 71 | return fmt.Errorf("failed to retrieve link: %v", err) |
| 72 | } |
| 73 | if link.Attrs().OperState == netlink.OperUp { |
| 74 | return fmt.Errorf("link %s still has tentative addresses after %d seconds", |
| 75 | ifName, |
| 76 | timeout) |
| 77 | } |
| 78 | return nil |
| 79 | } |
| 80 | |
| 81 | time.Sleep(SETTLE_INTERVAL) |
| 82 | } |
| 83 | } |