github.com/Ilhicas/nomad@v1.0.4-0.20210304152020-e86851182bc3/client/fingerprint/cpu.go (about) 1 package fingerprint 2 3 import ( 4 "fmt" 5 6 log "github.com/hashicorp/go-hclog" 7 "github.com/hashicorp/nomad/helper/stats" 8 "github.com/hashicorp/nomad/nomad/structs" 9 ) 10 11 const ( 12 // defaultCPUTicks is the default amount of CPU resources assumed to be 13 // available if the CPU performance data is unable to be detected. This is 14 // common on EC2 instances, where the env_aws fingerprinter will follow up, 15 // setting an accurate value. 16 defaultCPUTicks = 1000 // 1 core * 1 GHz 17 ) 18 19 // CPUFingerprint is used to fingerprint the CPU 20 type CPUFingerprint struct { 21 StaticFingerprinter 22 logger log.Logger 23 } 24 25 // NewCPUFingerprint is used to create a CPU fingerprint 26 func NewCPUFingerprint(logger log.Logger) Fingerprint { 27 f := &CPUFingerprint{logger: logger.Named("cpu")} 28 return f 29 } 30 31 func (f *CPUFingerprint) Fingerprint(req *FingerprintRequest, resp *FingerprintResponse) error { 32 cfg := req.Config 33 setResourcesCPU := func(totalCompute int) { 34 // COMPAT(0.10): Remove in 0.10 35 resp.Resources = &structs.Resources{ 36 CPU: totalCompute, 37 } 38 39 resp.NodeResources = &structs.NodeResources{ 40 Cpu: structs.NodeCpuResources{ 41 CpuShares: int64(totalCompute), 42 }, 43 } 44 } 45 46 if err := stats.Init(); err != nil { 47 f.logger.Warn("failed initializing stats collector", "error", err) 48 } 49 50 if modelName := stats.CPUModelName(); modelName != "" { 51 resp.AddAttribute("cpu.modelname", modelName) 52 } 53 54 if mhz := stats.CPUMHzPerCore(); mhz > 0 { 55 resp.AddAttribute("cpu.frequency", fmt.Sprintf("%.0f", mhz)) 56 f.logger.Debug("detected cpu frequency", "MHz", log.Fmt("%.0f", mhz)) 57 } 58 59 if numCores := stats.CPUNumCores(); numCores > 0 { 60 resp.AddAttribute("cpu.numcores", fmt.Sprintf("%d", numCores)) 61 f.logger.Debug("detected core count", "cores", numCores) 62 } 63 64 tt := int(stats.TotalTicksAvailable()) 65 if cfg.CpuCompute > 0 { 66 f.logger.Debug("using user specified cpu compute", "cpu_compute", cfg.CpuCompute) 67 tt = cfg.CpuCompute 68 } 69 70 // If we cannot detect the cpu total compute, fallback to a very low default 71 // value and log a message about configuring cpu_total_compute. This happens 72 // on Graviton instances where CPU information is unavailable. In that case, 73 // the env_aws fingerprinter updates the value with correct information. 74 if tt == 0 { 75 f.logger.Info("fallback to default cpu total compute, set client config option cpu_total_compute to override") 76 tt = defaultCPUTicks 77 } 78 79 resp.AddAttribute("cpu.totalcompute", fmt.Sprintf("%d", tt)) 80 setResourcesCPU(tt) 81 resp.Detected = true 82 83 return nil 84 }