func()

in cmd/core_plugin/network/dhclient/dhclient_linux.go [143:215]


func (ds *dhclientService) setupVlanInterfaces(ctx context.Context, nic *nic.Configuration) error {
	galog.Debug("Setting up vlan interfaces.")

	sysInterfaces, err := ethernet.Interfaces()
	if err != nil {
		return fmt.Errorf("failed to list systems interfaces: %w", err)
	}

	interfaceMap := make(map[string]*ethernet.Interface)

	for _, iface := range sysInterfaces {
		interfaceMap[iface.Name()] = iface
	}

	var keepMe []*ethernet.VlanInterface

	for _, vlan := range nic.VlanInterfaces {
		// For dhclient/native implementation we use a "gcp." prefix to the interface name
		// so we can determine it is a guest agent managed vlan interface.
		existingIface, found := interfaceMap[vlan.InterfaceName()]

		// If the interface already exists and has the same configuration just keep it.
		if found && existingIface.HardwareAddr().String() == vlan.MacAddr && existingIface.MTU() == vlan.MTU {
			keepMe = append(keepMe, vlan)
			continue
		}

		// If the vlan interface exists but the configuration has changed we recreate it.
		if found {
			if err := vlanDeleteLinkCmd.WithContext(ctx, vlan); err != nil {
				return fmt.Errorf("failed to remove pre existing vlan interface: %w", err)
			}
		}

		// Setup common elements of the vlan interface.
		if err := vlanIfaceCommonSet.WithContext(ctx, vlan); err != nil {
			return err
		}

		var batch []vlanIPConfig
		addBatch := func(ipVersion ipVersion, address *address.IPAddr, set run.CommandSet) {
			batch = append(batch, vlanIPConfig{vlan, ipVersion, address, set})
		}

		// ipv4 specific configurations.
		if vlan.IPAddress != nil {
			addBatch(ipv4, vlan.IPAddress, ipAddressSet)
			addBatch(ipv4, vlan.IPAddress, commonRouteSet)
			addBatch(ipv4, vlan.IPAddress, ipv4RouteCommand)
		}

		// ipv6 specific configurations.
		for _, address := range vlan.IPv6Addresses {
			addBatch(ipv6, address, ipAddressSet)
			addBatch(ipv6, address, commonRouteSet)
		}

		// Run the command batch.
		for _, ipConfig := range batch {
			if err := ipConfig.Command.WithContext(ctx, ipConfig); err != nil {
				return fmt.Errorf("failed to setup vlan interface commands: %w", err)
			}
		}

		keepMe = append(keepMe, vlan)
	}

	if err := ds.removeVlanInterfaces(ctx, nic, keepMe); err != nil {
		return fmt.Errorf("failed to remove uninstalled vlan interfaces: %w", err)
	}

	return nil
}