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