func setVolumeOwnershipTopLevel()

in pkg/csi_driver/node.go [484:535]


func setVolumeOwnershipTopLevel(volumeID, dir, fsGroup string, readOnly bool) error {
	// Skip volume ownership change if the volume is read-only.
	if readOnly {
		klog.V(3).InfoS("Skipping setVolumeOwnershipTopLevel as volume is readOnly", "volume", volumeID, "path", dir)

		return nil
	}

	if fsGroup == "" {
		klog.V(3).InfoS("Skipping setVolumeOwnershipTopLevel as no fsGroup is provided", "volume", volumeID, "path", dir)

		return nil
	}

	klog.InfoS("NodePublishVolume starting setVolumeOwnershipTopLevel", "volume", volumeID, "path", dir, "fsGroup", fsGroup, "readOnly", readOnly)
	// Convert fsGroup string to integer.
	gid, err := strconv.Atoi(fsGroup)
	if err != nil {
		return fmt.Errorf("invalid fsGroup %s, must a numeric string: %w", fsGroup, err)
	}

	// Retrieve directory info.
	info, err := os.Lstat(dir)
	if err != nil {
		klog.ErrorS(err, "Failed to retrieve directory info", "path", dir, "volume", volumeID)

		return err
	}

	// Change ownership of the top-level directory.
	if err := os.Lchown(dir, -1, gid); err != nil {
		klog.ErrorS(err, "Failed to chown of directory", "path", dir, "volume", volumeID, "gid", gid)

		return err
	}

	// Apply permissions to the directory.
	mask := rwMask
	if readOnly {
		mask = roMask
	}
	mask |= os.ModeSetgid | execMask

	if err := os.Chmod(dir, info.Mode()|mask); err != nil {
		klog.ErrorS(err, "Failed to chmod of directory", "path", dir, "volume", volumeID, "mode", mask)

		return err
	}
	klog.InfoS("NodePublishVolume successfully changed ownership and permissions of top-level directory", "volume", volumeID, "path", dir, "fsGroup", fsGroup)

	return nil
}