func NewFromDevice()

in pkg/localvolume/localvolume.go [50:87]


func NewFromDevice(devicePath, mountPath string) (LocalVolume, error) {
	actualDevice, err := filepath.EvalSymlinks(devicePath)
	if err != nil {
		return nil, fmt.Errorf("Cannot resolve %s: %w", devicePath, err)
	}
	mounts, err := os.ReadFile(procMounts)
	if err != nil {
		return nil, fmt.Errorf("Cannot read %s: %w", procMounts, err)
	}
	for _, line := range strings.Split(string(mounts), "\n") {
		if strings.Contains(line, mountPath) {
			if !strings.Contains(line, actualDevice) {
				return nil, fmt.Errorf("Already mounted, but not to expected device %s: %s", actualDevice, line)
			}
			klog.Infof("Found %s already mounted at %s", devicePath, mountPath)
			return &deviceVolume{
				devicePath,
				mountPath,
			}, nil
		}
	}

	if err := os.MkdirAll(mountPath, 0750); err != nil {
		return nil, fmt.Errorf("Couldn't create mount point: %w", err)
	}

	mounter := &mount.SafeFormatAndMount{
		Interface: mount.New(""),
		Exec:      exec.New(),
	}
	if err := mounter.FormatAndMount(devicePath, mountPath, fsType, nil); err != nil {
		return nil, fmt.Errorf("cannot format %s to %s: %w", devicePath, mountPath, err)
	}
	return &deviceVolume{
		devicePath,
		mountPath,
	}, nil
}