bridge.go 872 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package netconf
  2. import (
  3. "fmt"
  4. "github.com/vishvananda/netlink"
  5. )
  6. type Bridge struct {
  7. name string
  8. }
  9. func NewBridge(name string) (*Bridge, error) {
  10. b := &Bridge{name: name}
  11. return b, b.init()
  12. }
  13. func (b *Bridge) init() error {
  14. link, err := netlink.LinkByName(b.name)
  15. if err == nil {
  16. if _, ok := link.(*netlink.Bridge); !ok {
  17. return fmt.Errorf("%s is not a bridge device", b.name)
  18. }
  19. return nil
  20. }
  21. bridge := netlink.Bridge{}
  22. bridge.LinkAttrs.Name = b.name
  23. return netlink.LinkAdd(&bridge)
  24. }
  25. func (b *Bridge) AddLink(link netlink.Link) error {
  26. existing, err := netlink.LinkByName(b.name)
  27. if err != nil {
  28. return err
  29. }
  30. if bridge, ok := existing.(*netlink.Bridge); ok {
  31. if link.Attrs().MasterIndex != bridge.Index {
  32. return netlink.LinkSetMaster(link, bridge)
  33. }
  34. } else {
  35. return fmt.Errorf("%s is not a bridge", b.name)
  36. }
  37. return nil
  38. }