github.com/jaypipes/ghw@v0.21.1/pkg/accelerator/accelerator.go (about) 1 // 2 // Use and distribution licensed under the Apache license version 2. 3 // 4 // See the COPYING file in the root project directory for full text. 5 // 6 7 package accelerator 8 9 import ( 10 "fmt" 11 12 "github.com/jaypipes/ghw/pkg/context" 13 "github.com/jaypipes/ghw/pkg/marshal" 14 "github.com/jaypipes/ghw/pkg/option" 15 "github.com/jaypipes/ghw/pkg/pci" 16 ) 17 18 type AcceleratorDevice struct { 19 // the PCI address where the accelerator device can be found 20 Address string `json:"address"` 21 // pointer to a PCIDevice struct that describes the vendor and product 22 // model, etc 23 PCIDevice *pci.Device `json:"pci_device"` 24 } 25 26 func (dev *AcceleratorDevice) String() string { 27 deviceStr := dev.Address 28 if dev.PCIDevice != nil { 29 deviceStr = dev.PCIDevice.String() 30 } 31 nodeStr := "" 32 return fmt.Sprintf( 33 "device %s@%s", 34 nodeStr, 35 deviceStr, 36 ) 37 } 38 39 type Info struct { 40 ctx *context.Context 41 Devices []*AcceleratorDevice `json:"devices"` 42 } 43 44 // New returns a pointer to an Info struct that contains information about the 45 // accelerator devices on the host system 46 func New(opts ...*option.Option) (*Info, error) { 47 ctx := context.New(opts...) 48 info := &Info{ctx: ctx} 49 50 if err := ctx.Do(info.load); err != nil { 51 return nil, err 52 } 53 return info, nil 54 } 55 56 func (i *Info) String() string { 57 numDevsStr := "devices" 58 if len(i.Devices) == 1 { 59 numDevsStr = "device" 60 } 61 return fmt.Sprintf( 62 "processing accelerators (%d %s)", 63 len(i.Devices), 64 numDevsStr, 65 ) 66 } 67 68 // simple private struct used to encapsulate processing accelerators information in a top-level 69 // "accelerator" YAML/JSON map/object key 70 type acceleratorPrinter struct { 71 Info *Info `json:"accelerator"` 72 } 73 74 // YAMLString returns a string with the processing accelerators information formatted as YAML 75 // under a top-level "accelerator:" key 76 func (i *Info) YAMLString() string { 77 return marshal.SafeYAML(i.ctx, acceleratorPrinter{i}) 78 } 79 80 // JSONString returns a string with the processing accelerators information formatted as JSON 81 // under a top-level "accelerator:" key 82 func (i *Info) JSONString(indent bool) string { 83 return marshal.SafeJSON(i.ctx, acceleratorPrinter{i}, indent) 84 }