func()

in google_guest_agent/network/manager/systemd_networkd_linux.go [359:444]


func (n *systemdNetworkd) removeVlanInterfaces(ctx context.Context, keepMe []string) (bool, error) {
	files, err := os.ReadDir(n.configDir)
	if err != nil {
		return false, fmt.Errorf("failed to read content from %s: %+v", n.configDir, err)
	}

	configExp := `(?P<priority>[0-9]+)-(?P<interface>.*\.[0-9]+)-(?P<suffix>.*)\.(?P<extension>network|netdev)`
	configRegex := regexp.MustCompile(configExp)
	requiresRestart := false

	var ifacesDeleteMe []string
	var filesDeleteMe []string

	for _, file := range files {
		var (
			currIface, extension string
			found                bool
		)

		if file.IsDir() {
			continue
		}

		groups := utils.RegexGroupsMap(configRegex, file.Name())

		// If we don't have a matching interface skip it.
		if currIface, found = groups["interface"]; !found {
			continue
		}

		// If we don't have a matching extension skip it.
		if extension, found = groups["extension"]; !found {
			continue
		}

		// If this is an interface still present skip it.
		if slices.Contains(keepMe, currIface) {
			continue
		}

		ptrMap := map[string]guestAgentManaged{
			"network": new(systemdConfig),
			"netdev":  new(systemdNetdevConfig),
		}

		ptr, foundPtr := ptrMap[extension]
		if !foundPtr {
			return requiresRestart, fmt.Errorf("regex matching failed, invalid extension: %s", extension)
		}

		filePath := filepath.Join(n.configDir, file.Name())
		if err := readIniFile(filePath, ptr); err != nil {
			return requiresRestart, fmt.Errorf("failed to read .network file before removal: %+v", err)
		}

		// Although the file name is following the same pattern we are assuming this is not
		// managed by us - skip it.
		if !ptr.isGuestAgentManaged() {
			continue
		}

		if extension == "network" {
			network := ptr.(*systemdConfig)
			ifacesDeleteMe = append(ifacesDeleteMe, network.Match.Name)
		}

		filesDeleteMe = append(filesDeleteMe, filePath)
		requiresRestart = true
	}

	if len(ifacesDeleteMe) > 0 {
		args := []string{"delete"}
		args = append(args, ifacesDeleteMe...)
		if err := run.Quiet(ctx, "networkctl", args...); err != nil {
			return false, fmt.Errorf("networkctl %v failed with error: %w", args, err)
		}
	}

	for _, filePath := range filesDeleteMe {
		if err := os.Remove(filePath); err != nil {
			return requiresRestart, fmt.Errorf("failed to remove vlan interface config(%s): %+v", filePath, err)
		}
	}

	return requiresRestart, nil
}