github.com/ryanslade/nomad@v0.2.4-0.20160128061903-fc95782f2089/client/fingerprint/cpu.go (about) 1 package fingerprint 2 3 import ( 4 "fmt" 5 "log" 6 7 "github.com/hashicorp/nomad/client/config" 8 "github.com/hashicorp/nomad/nomad/structs" 9 "github.com/shirou/gopsutil/cpu" 10 ) 11 12 // CPUFingerprint is used to fingerprint the CPU 13 type CPUFingerprint struct { 14 StaticFingerprinter 15 logger *log.Logger 16 } 17 18 // NewCPUFingerprint is used to create a CPU fingerprint 19 func NewCPUFingerprint(logger *log.Logger) Fingerprint { 20 f := &CPUFingerprint{logger: logger} 21 return f 22 } 23 24 func (f *CPUFingerprint) Fingerprint(cfg *config.Config, node *structs.Node) (bool, error) { 25 cpuInfo, err := cpu.CPUInfo() 26 if err != nil { 27 f.logger.Println("[WARN] Error reading CPU information:", err) 28 return false, err 29 } 30 31 var numCores int32 32 var mhz float64 33 var modelName string 34 35 // Assume all CPUs found have same Model. Log if not. 36 // If CPUInfo() returns nil above, this loop is still safe 37 for _, c := range cpuInfo { 38 numCores += c.Cores 39 mhz += c.Mhz 40 41 if modelName != "" && modelName != c.ModelName { 42 f.logger.Println("[WARN] Found different model names in the same CPU information. Recording last found") 43 } 44 modelName = c.ModelName 45 } 46 // Get average CPU frequency 47 mhz /= float64(len(cpuInfo)) 48 49 if mhz > 0 { 50 node.Attributes["cpu.frequency"] = fmt.Sprintf("%.6f", mhz) 51 } 52 53 if numCores > 0 { 54 node.Attributes["cpu.numcores"] = fmt.Sprintf("%d", numCores) 55 } 56 57 if mhz > 0 && numCores > 0 { 58 tc := float64(numCores) * mhz 59 node.Attributes["cpu.totalcompute"] = fmt.Sprintf("%.6f", tc) 60 61 if node.Resources == nil { 62 node.Resources = &structs.Resources{} 63 } 64 65 node.Resources.CPU = int(tc) 66 } 67 68 if modelName != "" { 69 node.Attributes["cpu.modelname"] = modelName 70 } 71 72 return true, nil 73 }