addr_linux.go 2.2 KB

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