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