vlan.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package netconf
  2. import (
  3. "fmt"
  4. "strconv"
  5. "strings"
  6. "github.com/vishvananda/netlink"
  7. )
  8. type VlanDefinition struct {
  9. Id int
  10. Name string
  11. }
  12. type Vlan struct {
  13. name string
  14. link netlink.Link
  15. id int
  16. }
  17. func NewVlan(link netlink.Link, name string, id int) (*Vlan, error) {
  18. if name == "" {
  19. name = fmt.Sprintf("%s.%d", link.Attrs().Name, id)
  20. }
  21. v := &Vlan{
  22. name: name,
  23. link: link,
  24. id: id,
  25. }
  26. return v, v.init()
  27. }
  28. func (v *Vlan) init() error {
  29. link, err := netlink.LinkByName(v.name)
  30. if err == nil {
  31. if _, ok := link.(*netlink.Vlan); !ok {
  32. return fmt.Errorf("%s is not a VLAN device", v.name)
  33. }
  34. return nil
  35. }
  36. vlan := netlink.Vlan{}
  37. vlan.ParentIndex = v.link.Attrs().Index
  38. vlan.Name = v.name
  39. vlan.VlanId = v.id
  40. return netlink.LinkAdd(&vlan)
  41. }
  42. func ParseVlanDefinitions(vlans string) ([]VlanDefinition, error) {
  43. vlans = strings.TrimSpace(vlans)
  44. if vlans == "" {
  45. return nil, nil
  46. }
  47. result := []VlanDefinition{}
  48. for _, vlan := range strings.Split(vlans, ",") {
  49. idName := strings.SplitN(strings.TrimSpace(vlan), ":", 2)
  50. id, err := strconv.Atoi(idName[0])
  51. if err != nil {
  52. return nil, fmt.Errorf("Invalid format in %s: %v", vlans, err)
  53. }
  54. def := VlanDefinition{
  55. Id: id,
  56. }
  57. if len(idName) > 1 {
  58. def.Name = idName[1]
  59. }
  60. result = append(result, def)
  61. }
  62. return result, nil
  63. }