k8s.io/kubernetes@v1.29.3/pkg/volume/vsphere_volume/vsphere_volume_util_windows.go (about)

     1  //go:build !providerless && windows
     2  // +build !providerless,windows
     3  
     4  /*
     5  Copyright 2019 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 vsphere_volume
    21  
    22  import (
    23  	"encoding/json"
    24  	"fmt"
    25  	"os/exec"
    26  	"strings"
    27  
    28  	"k8s.io/klog/v2"
    29  )
    30  
    31  type diskInfoResult struct {
    32  	Number       json.Number
    33  	SerialNumber string
    34  }
    35  
    36  func verifyDevicePath(path string) (string, error) {
    37  	if !strings.Contains(path, diskByIDPath) {
    38  		// If this volume has already been mounted then
    39  		// its devicePath will have already been converted to a disk number
    40  		klog.V(4).Infof("Found vSphere disk attached with disk number %v", path)
    41  		return path, nil
    42  	}
    43  	// NOTE: If a powershell command that would return an array (e.g.: Get-Disk) would return an array of
    44  	// one element, powershell will in fact return that object directly, and **not an array containing
    45  	// that elemenent, which means piping it to ConvertTo-Json would not result in array as expected below.
    46  	// The following syntax forces it to always be an array.
    47  	cmd := exec.Command("powershell", "/c", "Get-Disk | Select Number, SerialNumber | ConvertTo-JSON")
    48  	output, err := cmd.Output()
    49  	if err != nil {
    50  		klog.Errorf("Get-Disk failed, error: %v, output: %q", err, string(output))
    51  		return "", err
    52  	}
    53  
    54  	var results []diskInfoResult
    55  	if err = json.Unmarshal(output, &results); err != nil {
    56  		klog.Errorf("Failed to unmarshal Get-Disk json, output: %q", string(output))
    57  		return "", err
    58  	}
    59  	serialNumber := strings.TrimPrefix(path, diskByIDPath+diskSCSIPrefix)
    60  	for _, v := range results {
    61  		if v.SerialNumber == serialNumber {
    62  			klog.V(4).Infof("Found vSphere disk attached with serial %v", serialNumber)
    63  			return v.Number.String(), nil
    64  		}
    65  	}
    66  
    67  	return "", fmt.Errorf("unable to find vSphere disk with serial %v", serialNumber)
    68  }