vishvananda / netlink

Simple netlink library for go.
Apache License 2.0
2.85k stars 744 forks source link

Support for mapping between tunnel id and vlan #907

Open cwmos opened 1 year ago

cwmos commented 1 year ago

If a VxLAN device is attached to a VLAN aware bridge, it is possible to specify which VLAN IDs should map to which VNIs.

Using the bridge command, this is done using the tunnel_info and tunnelshow keywords, see https://man7.org/linux/man-pages/man8/bridge.8.html. See also https://developers.redhat.com/articles/2022/04/06/introduction-linux-bridging-commands-and-features in the section "VLAN tunnel mapping".

It would nice if the netlink library supported this.

paalgyula commented 2 weeks ago

Hey, I think it's already feasible:

package main

import (
    "fmt"
    "github.com/vishvananda/netlink"
)

// Example VLAN to VNI mapping
var vlanToVniMap = map[int]int{
    10: 1000,
    20: 2000,
    30: 3000,
}

func main() {
    // 1. Get the bridge link
    bridgeLink, err := netlink.LinkByName("br0") // Replace "br0" with your bridge name
    if err != nil {
        fmt.Println("Error getting bridge link:", err)
        return
    }

    // 2. Create a new VxLAN interface
    vxlan := &netlink.Vxlan{
        LinkAttrs: netlink.LinkAttrs{
            Name: "vxlan0", // Choose a name for your VxLAN interface
        },
        VxlanId: 100, // Set the desired VNI
    }
    err = netlink.LinkAdd(vxlan)
    if err != nil {
        fmt.Println("Error adding VxLAN interface:", err)
        return
    }

    // 3. Set up the VLAN mapping
    for vlanID, vni := range vlanToVniMap {
        err = netlink.BridgeVlanAdd(bridgeLink, vlanID, true, true, false, false)
        if err != nil {
            fmt.Println("Error adding VLAN to bridge:", err)
            return
        }

        // You'll need to find the index of the VxLAN interface
        vxlanLink, err := netlink.LinkByName("vxlan0")
        if err != nil {
            fmt.Println("Error getting VxLAN link:", err)
            return
        }

        err = netlink.BridgeFdbAdd(bridgeLink, vxlanLink.Attrs().HardwareAddr, vlanID, 0, vxlanLink.Attrs().Index)
        if err != nil {
            fmt.Println("Error adding FDB entry:", err)
            return
        }
    }

    fmt.Println("VxLAN interface with VLAN mapping created successfully!")
}
cwmos commented 2 weeks ago

Thanks for the example. I cannot find the function BridgeFdbAdd, perhaps I am missing something?