github.com/anuvu/nomad@v0.8.7-atom1/client/fingerprint/cpu.go (about)

     1  package fingerprint
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  
     7  	cstructs "github.com/hashicorp/nomad/client/structs"
     8  	"github.com/hashicorp/nomad/helper/stats"
     9  	"github.com/hashicorp/nomad/nomad/structs"
    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(req *cstructs.FingerprintRequest, resp *cstructs.FingerprintResponse) error {
    25  	cfg := req.Config
    26  	setResourcesCPU := func(totalCompute int) {
    27  		resp.Resources = &structs.Resources{
    28  			CPU: totalCompute,
    29  		}
    30  	}
    31  
    32  	if err := stats.Init(); err != nil {
    33  		f.logger.Printf("[WARN] fingerprint.cpu: %v", err)
    34  	}
    35  
    36  	if cfg.CpuCompute != 0 {
    37  		setResourcesCPU(cfg.CpuCompute)
    38  		return nil
    39  	}
    40  
    41  	if modelName := stats.CPUModelName(); modelName != "" {
    42  		resp.AddAttribute("cpu.modelname", modelName)
    43  	}
    44  
    45  	if mhz := stats.CPUMHzPerCore(); mhz > 0 {
    46  		resp.AddAttribute("cpu.frequency", fmt.Sprintf("%.0f", mhz))
    47  		f.logger.Printf("[DEBUG] fingerprint.cpu: frequency: %.0f MHz", mhz)
    48  	}
    49  
    50  	if numCores := stats.CPUNumCores(); numCores > 0 {
    51  		resp.AddAttribute("cpu.numcores", fmt.Sprintf("%d", numCores))
    52  		f.logger.Printf("[DEBUG] fingerprint.cpu: core count: %d", numCores)
    53  	}
    54  
    55  	tt := int(stats.TotalTicksAvailable())
    56  	if cfg.CpuCompute > 0 {
    57  		f.logger.Printf("[DEBUG] fingerprint.cpu: Using specified cpu compute %d", cfg.CpuCompute)
    58  		tt = cfg.CpuCompute
    59  	}
    60  
    61  	// Return an error if no cpu was detected or explicitly set as this
    62  	// node would be unable to receive any allocations.
    63  	if tt == 0 {
    64  		return fmt.Errorf("cannot detect cpu total compute. "+
    65  			"CPU compute must be set manually using the client config option %q",
    66  			"cpu_total_compute")
    67  	}
    68  
    69  	resp.AddAttribute("cpu.totalcompute", fmt.Sprintf("%d", tt))
    70  	setResourcesCPU(tt)
    71  	resp.Detected = true
    72  
    73  	return nil
    74  }