| 1 |
//go:build windows |
| 2 |
|
| 3 |
/* |
| 4 |
Copyright 2017 The Kubernetes Authors. |
| 5 |
|
| 6 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 |
you may not use this file except in compliance with the License. |
| 8 |
You may obtain a copy of the License at |
| 9 |
|
| 10 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 11 |
|
| 12 |
Unless required by applicable law or agreed to in writing, software |
| 13 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 14 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 |
See the License for the specific language governing permissions and |
| 16 |
limitations under the License. |
| 17 |
*/ |
| 18 |
|
| 19 |
package mount |
| 20 |
|
| 21 |
import ( |
| 22 |
"fmt" |
| 23 |
"os" |
| 24 |
"os/exec" |
| 25 |
"path/filepath" |
| 26 |
"strings" |
| 27 |
|
| 28 |
"k8s.io/klog/v2" |
| 29 |
"k8s.io/utils/keymutex" |
| 30 |
) |
| 31 |
|
| 32 |
const ( |
| 33 |
accessDenied string = "access is denied" |
| 34 |
) |
| 35 |
|
| 36 |
// Mounter provides the default implementation of mount.Interface |
| 37 |
// for the windows platform. This implementation assumes that the |
| 38 |
// kubelet is running in the host's root mount namespace. |
| 39 |
type Mounter struct { |
| 40 |
mounterPath string |
| 41 |
} |
| 42 |
|
| 43 |
// New returns a mount.Interface for the current system. |
| 44 |
// It provides options to override the default mounter behavior. |
| 45 |
// mounterPath allows using an alternative to `/bin/mount` for mounting. |
| 46 |
func New(mounterPath string) Interface { |
| 47 |
return &Mounter{ |
| 48 |
mounterPath: mounterPath, |
| 49 |
} |
| 50 |
} |
| 51 |
|
| 52 |
// acquire lock for smb mount |
| 53 |
var getSMBMountMutex = keymutex.NewHashed(0) |
| 54 |
|
| 55 |
// Mount : mounts source to target with given options. |
| 56 |
// currently only supports cifs(smb), bind mount(for disk) |
| 57 |
func (mounter *Mounter) Mount(source string, target string, fstype string, options []string) error { |
| 58 |
return mounter.MountSensitive(source, target, fstype, options, nil /* sensitiveOptions */) |
| 59 |
} |
| 60 |
|
| 61 |
// MountSensitiveWithoutSystemd is the same as MountSensitive() but disable using ssytemd mount. |
| 62 |
// Windows not supported systemd mount, this function degrades to MountSensitive(). |
| 63 |
func (mounter *Mounter) MountSensitiveWithoutSystemd(source string, target string, fstype string, options []string, sensitiveOptions []string) error { |
| 64 |
return mounter.MountSensitive(source, target, fstype, options, sensitiveOptions /* sensitiveOptions */) |
| 65 |
} |
| 66 |
|
| 67 |
// MountSensitiveWithoutSystemdWithMountFlags is the same as MountSensitiveWithoutSystemd with additional mount flags |
| 68 |
// Windows not supported systemd mount, this function degrades to MountSensitive(). |
| 69 |
func (mounter *Mounter) MountSensitiveWithoutSystemdWithMountFlags(source string, target string, fstype string, options []string, sensitiveOptions []string, mountFlags []string) error { |
| 70 |
return mounter.MountSensitive(source, target, fstype, options, sensitiveOptions /* sensitiveOptions */) |
| 71 |
} |
| 72 |
|
| 73 |
// MountSensitive is the same as Mount() but this method allows |
| 74 |
// sensitiveOptions to be passed in a separate parameter from the normal |
| 75 |
// mount options and ensures the sensitiveOptions are never logged. This |
| 76 |
// method should be used by callers that pass sensitive material (like |
| 77 |
// passwords) as mount options. |
| 78 |
func (mounter *Mounter) MountSensitive(source string, target string, fstype string, options []string, sensitiveOptions []string) error { |
| 79 |
target = NormalizeWindowsPath(target) |
| 80 |
sanitizedOptionsForLogging := sanitizedOptionsForLogging(options, sensitiveOptions) |
| 81 |
|
| 82 |
if source == "tmpfs" { |
| 83 |
klog.V(3).Infof("mounting source (%q), target (%q), with options (%q)", source, target, sanitizedOptionsForLogging) |
| 84 |
return os.MkdirAll(target, 0o755) |
| 85 |
} |
| 86 |
|
| 87 |
parentDir := filepath.Dir(target) |
| 88 |
if err := os.MkdirAll(parentDir, 0o755); err != nil { |
| 89 |
return err |
| 90 |
} |
| 91 |
|
| 92 |
klog.V(4).Infof("mount options(%q) source:%q, target:%q, fstype:%q, begin to mount", |
| 93 |
sanitizedOptionsForLogging, source, target, fstype) |
| 94 |
bindSource := source |
| 95 |
|
| 96 |
if bind, _, _, _ := MakeBindOptsSensitive(options, sensitiveOptions); bind { |
| 97 |
bindSource = NormalizeWindowsPath(source) |
| 98 |
} else { |
| 99 |
allOptions := []string{} |
| 100 |
allOptions = append(allOptions, options...) |
| 101 |
allOptions = append(allOptions, sensitiveOptions...) |
| 102 |
if len(allOptions) < 2 { |
| 103 |
return fmt.Errorf("mount options(%q) should have at least 2 options, current number:%d, source:%q, target:%q", |
| 104 |
sanitizedOptionsForLogging, len(allOptions), source, target) |
| 105 |
} |
| 106 |
|
| 107 |
// currently only cifs mount is supported |
| 108 |
if strings.ToLower(fstype) != "cifs" { |
| 109 |
return fmt.Errorf("only cifs mount is supported now, fstype: %q, mounting source (%q), target (%q), with options (%q)", fstype, source, target, sanitizedOptionsForLogging) |
| 110 |
} |
| 111 |
|
| 112 |
// lock smb mount for the same source |
| 113 |
getSMBMountMutex.LockKey(source) |
| 114 |
defer getSMBMountMutex.UnlockKey(source) |
| 115 |
|
| 116 |
username := allOptions[0] |
| 117 |
password := allOptions[1] |
| 118 |
if output, err := newSMBMapping(username, password, source); err != nil { |
| 119 |
klog.Warningf("SMB Mapping(%s) returned with error(%v), output(%s)", source, err, string(output)) |
| 120 |
if isSMBMappingExist(source) { |
| 121 |
valid, err := isValidPath(source) |
| 122 |
if !valid { |
| 123 |
if err == nil || isAccessDeniedError(err) { |
| 124 |
klog.V(2).Infof("SMB Mapping(%s) already exists while it's not valid, return error: %v, now begin to remove and remount", source, err) |
| 125 |
if output, err = removeSMBMapping(source); err != nil { |
| 126 |
return fmt.Errorf("Remove-SmbGlobalMapping failed: %v, output: %q", err, output) |
| 127 |
} |
| 128 |
if output, err := newSMBMapping(username, password, source); err != nil { |
| 129 |
return fmt.Errorf("New-SmbGlobalMapping(%s) failed: %v, output: %q", source, err, output) |
| 130 |
} |
| 131 |
} |
| 132 |
} else { |
| 133 |
klog.V(2).Infof("SMB Mapping(%s) already exists and is still valid, skip error(%v)", source, err) |
| 134 |
} |
| 135 |
} else { |
| 136 |
return fmt.Errorf("New-SmbGlobalMapping(%s) failed: %v, output: %q", source, err, output) |
| 137 |
} |
| 138 |
} |
| 139 |
} |
| 140 |
|
| 141 |
// There is an issue in golang where EvalSymlinks fails on Windows when passed a |
| 142 |
// UNC share root path without a trailing backslash. |
| 143 |
// Ex: \\SERVER\share will fail to resolve but \\SERVER\share\ will resolve |
| 144 |
// containerD on Windows calls EvalSymlinks so we'll add the backslash when making the symlink if it is missing. |
| 145 |
// https://github.com/golang/go/pull/42096 fixes this issue in golang but a fix will not be available until |
| 146 |
// golang v1.16 |
| 147 |
mklinkSource := bindSource |
| 148 |
if !strings.HasSuffix(mklinkSource, "\\") { |
| 149 |
mklinkSource = mklinkSource + "\\" |
| 150 |
} |
| 151 |
|
| 152 |
err := os.Symlink(mklinkSource, target) |
| 153 |
if err != nil { |
| 154 |
klog.Errorf("symlink failed: %v, source(%q) target(%q)", err, mklinkSource, target) |
| 155 |
return err |
| 156 |
} |
| 157 |
klog.V(2).Infof("symlink source(%q) on target(%q) successfully", mklinkSource, target) |
| 158 |
|
| 159 |
return nil |
| 160 |
} |
| 161 |
|
| 162 |
// do the SMB mount with username, password, remotepath |
| 163 |
// return (output, error) |
| 164 |
func newSMBMapping(username, password, remotepath string) (string, error) { |
| 165 |
if username == "" || password == "" || remotepath == "" { |
| 166 |
return "", fmt.Errorf("invalid parameter(username: %s, password: %s, remotepath: %s)", username, sensitiveOptionsRemoved, remotepath) |
| 167 |
} |
| 168 |
|
| 169 |
// use PowerShell Environment Variables to store user input string to prevent command line injection |
| 170 |
// https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_environment_variables?view=powershell-5.1 |
| 171 |
cmdLine := `$PWord = ConvertTo-SecureString -String $Env:smbpassword -AsPlainText -Force` + |
| 172 |
`;$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Env:smbuser, $PWord` + |
| 173 |
`;New-SmbGlobalMapping -RemotePath $Env:smbremotepath -Credential $Credential -RequirePrivacy $true` |
| 174 |
cmd := exec.Command("powershell", "/c", cmdLine) |
| 175 |
cmd.Env = append(os.Environ(), |
| 176 |
fmt.Sprintf("smbuser=%s", username), |
| 177 |
fmt.Sprintf("smbpassword=%s", password), |
| 178 |
fmt.Sprintf("smbremotepath=%s", remotepath)) |
| 179 |
|
| 180 |
output, err := cmd.CombinedOutput() |
| 181 |
return string(output), err |
| 182 |
} |
| 183 |
|
| 184 |
// check whether remotepath is already mounted |
| 185 |
func isSMBMappingExist(remotepath string) bool { |
| 186 |
cmd := exec.Command("powershell", "/c", `Get-SmbGlobalMapping -RemotePath $Env:smbremotepath`) |
| 187 |
cmd.Env = append(os.Environ(), fmt.Sprintf("smbremotepath=%s", remotepath)) |
| 188 |
_, err := cmd.CombinedOutput() |
| 189 |
return err == nil |
| 190 |
} |
| 191 |
|
| 192 |
// check whether remotepath is valid |
| 193 |
// return (true, nil) if remotepath is valid |
| 194 |
func isValidPath(remotepath string) (bool, error) { |
| 195 |
cmd := exec.Command("powershell", "/c", `Test-Path $Env:remotepath`) |
| 196 |
cmd.Env = append(os.Environ(), fmt.Sprintf("remotepath=%s", remotepath)) |
| 197 |
output, err := cmd.CombinedOutput() |
| 198 |
if err != nil { |
| 199 |
return false, fmt.Errorf("returned output: %s, error: %v", string(output), err) |
| 200 |
} |
| 201 |
|
| 202 |
return strings.HasPrefix(strings.ToLower(string(output)), "true"), nil |
| 203 |
} |
| 204 |
|
| 205 |
func isAccessDeniedError(err error) bool { |
| 206 |
return err != nil && strings.Contains(strings.ToLower(err.Error()), accessDenied) |
| 207 |
} |
| 208 |
|
| 209 |
// remove SMB mapping |
| 210 |
func removeSMBMapping(remotepath string) (string, error) { |
| 211 |
cmd := exec.Command("powershell", "/c", `Remove-SmbGlobalMapping -RemotePath $Env:smbremotepath -Force`) |
| 212 |
cmd.Env = append(os.Environ(), fmt.Sprintf("smbremotepath=%s", remotepath)) |
| 213 |
output, err := cmd.CombinedOutput() |
| 214 |
return string(output), err |
| 215 |
} |
| 216 |
|
| 217 |
// Unmount unmounts the target. |
| 218 |
func (mounter *Mounter) Unmount(target string) error { |
| 219 |
klog.V(4).Infof("Unmount target (%q)", target) |
| 220 |
target = NormalizeWindowsPath(target) |
| 221 |
|
| 222 |
if err := os.Remove(target); err != nil { |
| 223 |
klog.Errorf("removing directory %s failed: %v", target, err) |
| 224 |
return err |
| 225 |
} |
| 226 |
return nil |
| 227 |
} |
| 228 |
|
| 229 |
// List returns a list of all mounted filesystems. todo |
| 230 |
func (mounter *Mounter) List() ([]MountPoint, error) { |
| 231 |
return []MountPoint{}, nil |
| 232 |
} |
| 233 |
|
| 234 |
// IsLikelyNotMountPoint determines if a directory is not a mountpoint. |
| 235 |
func (mounter *Mounter) IsLikelyNotMountPoint(file string) (bool, error) { |
| 236 |
stat, err := os.Lstat(file) |
| 237 |
if err != nil { |
| 238 |
return true, err |
| 239 |
} |
| 240 |
|
| 241 |
if stat.Mode()&os.ModeSymlink != 0 { |
| 242 |
return false, err |
| 243 |
} |
| 244 |
// go1.23 behavior change: https://github.com/golang/go/issues/63703#issuecomment-2535941458 |
| 245 |
if stat.Mode()&os.ModeIrregular != 0 { |
| 246 |
return false, err |
| 247 |
} |
| 248 |
return true, nil |
| 249 |
} |
| 250 |
|
| 251 |
// CanSafelySkipMountPointCheck always returns false on Windows |
| 252 |
func (mounter *Mounter) CanSafelySkipMountPointCheck() bool { |
| 253 |
return false |
| 254 |
} |
| 255 |
|
| 256 |
// IsMountPoint: determines if a directory is a mountpoint. |
| 257 |
func (mounter *Mounter) IsMountPoint(file string) (bool, error) { |
| 258 |
isNotMnt, err := mounter.IsLikelyNotMountPoint(file) |
| 259 |
if err != nil { |
| 260 |
return false, err |
| 261 |
} |
| 262 |
return !isNotMnt, nil |
| 263 |
} |
| 264 |
|
| 265 |
// GetMountRefs : empty implementation here since there is no place to query all mount points on Windows |
| 266 |
func (mounter *Mounter) GetMountRefs(pathname string) ([]string, error) { |
| 267 |
windowsPath := NormalizeWindowsPath(pathname) |
| 268 |
pathExists, pathErr := PathExists(windowsPath) |
| 269 |
if !pathExists { |
| 270 |
return []string{}, nil |
| 271 |
} else if IsCorruptedMnt(pathErr) { |
| 272 |
klog.Warningf("GetMountRefs found corrupted mount at %s, treating as unmounted path", windowsPath) |
| 273 |
return []string{}, nil |
| 274 |
} else if pathErr != nil { |
| 275 |
return nil, fmt.Errorf("error checking path %s: %v", windowsPath, pathErr) |
| 276 |
} |
| 277 |
return []string{pathname}, nil |
| 278 |
} |
| 279 |
|
| 280 |
func (mounter *SafeFormatAndMount) formatAndMountSensitive(source string, target string, fstype string, options []string, sensitiveOptions []string, formatOptions []string) error { |
| 281 |
// Try to mount the disk |
| 282 |
klog.V(4).Infof("Attempting to formatAndMount disk: %s %s %s", fstype, source, target) |
| 283 |
|
| 284 |
if err := ValidateDiskNumber(source); err != nil { |
| 285 |
klog.Errorf("diskMount: formatAndMount failed, err: %v", err) |
| 286 |
return err |
| 287 |
} |
| 288 |
|
| 289 |
if len(fstype) == 0 { |
| 290 |
// Use 'NTFS' as the default |
| 291 |
fstype = "NTFS" |
| 292 |
} |
| 293 |
|
| 294 |
if len(formatOptions) > 0 { |
| 295 |
return fmt.Errorf("diskMount: formatOptions are not supported on Windows") |
| 296 |
} |
| 297 |
|
| 298 |
cmdString := "Get-Disk -Number $env:source | Where partitionstyle -eq 'raw' | Initialize-Disk -PartitionStyle GPT -PassThru" + |
| 299 |
" | New-Partition -UseMaximumSize | Format-Volume -FileSystem $env:fstype -Confirm:$false" |
| 300 |
cmd := mounter.Exec.Command("powershell", "/c", cmdString) |
| 301 |
env := append(os.Environ(), |
| 302 |
fmt.Sprintf("source=%s", source), |
| 303 |
fmt.Sprintf("fstype=%s", fstype), |
| 304 |
) |
| 305 |
cmd.SetEnv(env) |
| 306 |
klog.V(8).Infof("Executing command: %q", cmdString) |
| 307 |
if output, err := cmd.CombinedOutput(); err != nil { |
| 308 |
return fmt.Errorf("diskMount: format disk failed, error: %v, output: %q", err, string(output)) |
| 309 |
} |
| 310 |
klog.V(4).Infof("diskMount: Disk successfully formatted, disk: %q, fstype: %q", source, fstype) |
| 311 |
|
| 312 |
volumeIds, err := ListVolumesOnDisk(source) |
| 313 |
if err != nil { |
| 314 |
return err |
| 315 |
} |
| 316 |
driverPath := volumeIds[0] |
| 317 |
return mounter.MountSensitive(driverPath, target, fstype, options, sensitiveOptions) |
| 318 |
} |
| 319 |
|
| 320 |
// ListVolumesOnDisk - returns back list of volumes(volumeIDs) in the disk (requested in diskID). |
| 321 |
func ListVolumesOnDisk(diskID string) (volumeIDs []string, err error) { |
| 322 |
// If a Disk has multiple volumes, Get-Volume may not return items in the same order. |
| 323 |
cmd := exec.Command("powershell", "/c", "(Get-Disk -DeviceId $env:diskID | Get-Partition | Get-Volume | Sort-Object -Property UniqueId).UniqueId") |
| 324 |
cmd.Env = append(os.Environ(), fmt.Sprintf("diskID=%s", diskID)) |
| 325 |
klog.V(8).Infof("Executing command: %q", cmd.String()) |
| 326 |
output, err := cmd.CombinedOutput() |
| 327 |
klog.V(4).Infof("ListVolumesOnDisk id from %s: %s", diskID, string(output)) |
| 328 |
if err != nil { |
| 329 |
return []string{}, fmt.Errorf("error list volumes on disk. cmd: %s, output: %s, error: %v", cmd, string(output), err) |
| 330 |
} |
| 331 |
|
| 332 |
volumeIds := strings.Split(strings.TrimSpace(string(output)), "\r\n") |
| 333 |
return volumeIds, nil |
| 334 |
} |