harvester / pcidevices

Manage PCI Devices and PCI Device Claims for PCI Passthrough in Harvester

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

file is not closed in some cases

w13915984028 opened this issue · comments

The file is not closed in all cases.

And there are some similar functions have such issue, e.g. unbindPCIDeviceFromDriver, unbindPCIDeviceFromVfioPCIDriver, please check and update.

func addNewIdToVfioPCIDriver(vendorId string, deviceId string) error {
	var id string = fmt.Sprintf("%s %s", vendorId, deviceId)

	file, err := os.OpenFile("/sys/bus/pci/drivers/vfio-pci/new_id", os.O_WRONLY, 0400)
	if err != nil {
		return err
	}
	_, err = file.WriteString(id)
	if err != nil {
		return err   // the file is not closed in this return
	}
	file.Close()
	return nil
}

Found when reviewing: #14

Fixed in

func bindDeviceToVFIOPCIDriver(pd *v1beta1.PCIDevice) error {
vendorId := pd.Status.VendorId
deviceId := pd.Status.VendorId
var id string = fmt.Sprintf("%s %s", vendorId, deviceId)
file, err := os.OpenFile("/sys/bus/pci/drivers/vfio-pci/new_id", os.O_WRONLY, 0400)
if err != nil {
return err
}
_, err = file.WriteString(id)
if err != nil {
file.Close()
return err
}
file.Close()
return nil
}

Please double check unbindDeviceFromDriver

func unbindDeviceFromDriver(addr string, driver string) error {
	path := fmt.Sprintf("/sys/bus/pci/drivers/%s/unbind", driver)
	file, err := os.OpenFile(path, os.O_WRONLY, 0400)
..
	_, err = file.WriteString(addr)
	if err != nil {
                // file should be closed 
		return err   ////
	}
..
}

General practice in go is:

func unbindDeviceFromDriver(addr string, driver string) error {
...
	file, err := os.OpenFile(path, os.O_WRONLY, 0400)
..
       // after successfully OpenFile
       defer file.Close()   /// it will make sure, in any return path, file is closed

	_, err = file.WriteString(addr)

        // do NOT need any file.Close
...
..
}

Fixed in f10b170