github.com/vmware/govmomi@v0.51.0/cli/device/pci/ls.go (about)

     1  // © Broadcom. All Rights Reserved.
     2  // The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
     3  // SPDX-License-Identifier: Apache-2.0
     4  
     5  package pci
     6  
     7  import (
     8  	"context"
     9  	"flag"
    10  	"fmt"
    11  	"io"
    12  	"os"
    13  	"text/tabwriter"
    14  
    15  	"github.com/vmware/govmomi/cli"
    16  	"github.com/vmware/govmomi/cli/flags"
    17  	"github.com/vmware/govmomi/object"
    18  	"github.com/vmware/govmomi/vim25/types"
    19  )
    20  
    21  type ls struct {
    22  	*flags.VirtualMachineFlag
    23  	*flags.OutputFlag
    24  }
    25  
    26  func init() {
    27  	cli.Register("device.pci.ls", &ls{})
    28  }
    29  
    30  func (cmd *ls) Register(ctx context.Context, f *flag.FlagSet) {
    31  	cmd.VirtualMachineFlag, ctx = flags.NewVirtualMachineFlag(ctx)
    32  	cmd.VirtualMachineFlag.Register(ctx, f)
    33  	cmd.OutputFlag, ctx = flags.NewOutputFlag(ctx)
    34  	cmd.OutputFlag.Register(ctx, f)
    35  }
    36  
    37  func (cmd *ls) Description() string {
    38  	return `List allowed PCI passthrough devices that could be attach to VM.
    39  
    40  Examples:
    41    govc device.pci.ls -vm VM`
    42  }
    43  
    44  func (cmd *ls) Process(ctx context.Context) error {
    45  	if err := cmd.VirtualMachineFlag.Process(ctx); err != nil {
    46  		return err
    47  	}
    48  	if err := cmd.OutputFlag.Process(ctx); err != nil {
    49  		return err
    50  	}
    51  	return nil
    52  }
    53  
    54  func (cmd *ls) Run(ctx context.Context, f *flag.FlagSet) error {
    55  	vm, err := cmd.VirtualMachine()
    56  	if err != nil {
    57  		return err
    58  	}
    59  	if vm == nil {
    60  		return flag.ErrHelp
    61  	}
    62  
    63  	vmConfigOptions, err := queryConfigTarget(ctx, vm)
    64  	if err != nil {
    65  		return err
    66  	}
    67  
    68  	return cmd.WriteResult(&infoResult{PciDevices: vmConfigOptions.PciPassthrough})
    69  }
    70  
    71  type infoResult struct {
    72  	PciDevices []types.BaseVirtualMachinePciPassthroughInfo `json:"pciDevices"`
    73  }
    74  
    75  func (r *infoResult) Write(w io.Writer) error {
    76  	tw := tabwriter.NewWriter(os.Stdout, 2, 0, 2, ' ', 0)
    77  	fmt.Fprintf(tw, "System ID\tAddress\tDevice Name\n")
    78  	for _, d := range r.PciDevices {
    79  		info := d.GetVirtualMachinePciPassthroughInfo()
    80  		pd := info.PciDevice
    81  		fmt.Fprintf(tw, "%s\t%s\t%s\t%s\n", info.SystemId, pd.Id, pd.VendorName, pd.DeviceName)
    82  	}
    83  	return tw.Flush()
    84  }
    85  
    86  func queryConfigTarget(ctx context.Context, m *object.VirtualMachine) (*types.ConfigTarget, error) {
    87  	b, err := m.EnvironmentBrowser(ctx)
    88  	if err != nil {
    89  		return nil, err
    90  	}
    91  	return b.QueryConfigTarget(ctx, nil)
    92  }