github.com/jaypipes/ghw@v0.21.1/pkg/gpu/gpu.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 gpu 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 "github.com/jaypipes/ghw/pkg/topology" 17 ) 18 19 type GraphicsCard struct { 20 // the PCI address where the graphics card can be found 21 Address string `json:"address"` 22 // The "index" of the card on the bus (generally not useful information, 23 // but might as well include it) 24 Index int `json:"index"` 25 // pointer to a PCIDevice struct that describes the vendor and product 26 // model, etc 27 // TODO(jaypipes): Rename this field to PCI, instead of DeviceInfo 28 DeviceInfo *pci.Device `json:"pci"` 29 // Topology node that the graphics card is affined to. Will be nil if the 30 // architecture is not NUMA. 31 Node *topology.Node `json:"node,omitempty"` 32 } 33 34 func (card *GraphicsCard) String() string { 35 deviceStr := card.Address 36 if card.DeviceInfo != nil { 37 deviceStr = card.DeviceInfo.String() 38 } 39 nodeStr := "" 40 if card.Node != nil { 41 nodeStr = fmt.Sprintf(" [affined to NUMA node %d]", card.Node.ID) 42 } 43 return fmt.Sprintf( 44 "card #%d %s@%s", 45 card.Index, 46 nodeStr, 47 deviceStr, 48 ) 49 } 50 51 type Info struct { 52 ctx *context.Context 53 GraphicsCards []*GraphicsCard `json:"cards"` 54 } 55 56 // New returns a pointer to an Info struct that contains information about the 57 // graphics cards on the host system 58 func New(opts ...*option.Option) (*Info, error) { 59 ctx := context.New(opts...) 60 info := &Info{ctx: ctx} 61 if err := ctx.Do(info.load); err != nil { 62 return nil, err 63 } 64 return info, nil 65 } 66 67 func (i *Info) String() string { 68 numCardsStr := "cards" 69 if len(i.GraphicsCards) == 1 { 70 numCardsStr = "card" 71 } 72 return fmt.Sprintf( 73 "gpu (%d graphics %s)", 74 len(i.GraphicsCards), 75 numCardsStr, 76 ) 77 } 78 79 // simple private struct used to encapsulate gpu information in a top-level 80 // "gpu" YAML/JSON map/object key 81 type gpuPrinter struct { 82 Info *Info `json:"gpu"` 83 } 84 85 // YAMLString returns a string with the gpu information formatted as YAML 86 // under a top-level "gpu:" key 87 func (i *Info) YAMLString() string { 88 return marshal.SafeYAML(i.ctx, gpuPrinter{i}) 89 } 90 91 // JSONString returns a string with the gpu information formatted as JSON 92 // under a top-level "gpu:" key 93 func (i *Info) JSONString(indent bool) string { 94 return marshal.SafeJSON(i.ctx, gpuPrinter{i}, indent) 95 }