// backend/vxlan/vxlan.go
func (be *VXLANBackend) RegisterNetwork(ctx context.Context, network string, config *subnet.Config) (backend.Network, error)
- 创建cfg变量,它的结构体中包含VIN int, Port int, GBP bool三个字段,其中VNI设置为默认的defaultVNI = 1,并且调用json.Unmarshal(config.Backend, &cfg)解析
- 创建变量devAttrs := vxlanDeviceAttrs{
vni: uint32(cfg.VNI),
name: fmt.Sprintf("flannel.%v", cfg.VNI),
vtepIndex: be.extIface.Iface.Index,
vtepAddr: be.extIface.IfaceAddr,
vtepPort: cfg.Port,
gbp: cfg.GBP,
}
- 调用dev, err := newVXLANDevice(&devAttrs) ---> 调用netlink库添加vlan设备,并且可以处理设备已经存在的情况
- 调用subnetAttrs, err := newSubnetAttrs(be.extIface.ExtAddr, dev.MACAddr())
- 调用lease, err := be.subnetMgr.AcquireLease(ctx, network, subnetAttrs)
- 创建vxlanNet := ip.IP4Net{
IP: lease.Subnet.IP,
PrefixLen: config.Network.PrefixLen,
}
- 调用err = dev.Configure(vxlanNet)
- 最后return newNetwork(network, be.subnetMgr, be.extIface, dev, vxlanNet, lease)
// backend/vxlan/vxlan.go
func newSubnetAttrs(publicIP net.IP, mac net.HardwareAddr)
- 首先调用data, err := json.Marshal(&vxlanLeaseAttrs{hardwarAddr(mac)})
- 接着调用return &subnet.LeaseAttrs{
PublicIP: ip.FromIP(publicIP),
BackendType: "vxlan",
BackendData: json.RawMessage(data),
}
// backend/vxlan/device.go
func (dev *vxlanDevice) Configure(ipn ip.IP4Net) error
- 调用setAddr4(dev.link, ipn.ToIPNet())
- 调用netlink.LinkSetUp(dev.link)启动VTEP
- 最后添加一条路由 route := netlink.Route{
LinkIndex: dev.link.Attrs().Index,
Scope: netlink.SCOPE_UNIVERSE,
Dst: ipn.Network().ToIPNet(),
},再调用netlink.RouteAdd(&route)
// backend/vxlan/network.go
func newNetwork(name string, subnetMgr subnet.Manager, extIface *backend.ExternalInterface, dev *vxlanDevice, _ ip.IP4Net, lease *subnet.Lease) (*network, error)
该函数仅仅用参数填充network数据结构:
nw := &network {
SimpleNetwork: backend.SimpleNetwork{
SubnetLease: lease,
ExtIface: extIface,
},
name: name,
subnetMgr: subnetMgr,
dev: dev,
}
network数据结构如下所示:
type network struct {
backend.SimpleNetwork
name string
extIface *backend.ExternalInterface
dev *vxlanDevice
routes routes
subnetMgr subnet.Manager
}
// backend/vxlan/network.go
func (nw *network) Run(ctx context.Context)
- 创建misses := make(chan *netlink.Neigh, 100)并调用go nw.dev.MonitorMisses(misses)
- 创建events := make(chan []subnet.Event)并调用go subnet.WatchLeases(ctx, nw.subnetMgr, nw.name, nw.SubnetLease, events)
- 调用select,如果事件类型为initialEventsBatch,调用nw.handleInitialSubnetEvents(initialEventsBatch)直到成功为止
- 一个无限的for循环,当misses有事件发生时,调用nw.handleMiss(miss),events有事件发生时,调用nw.handleSubnetEvents(evtBatch)