github.com/taylorchu/nomad@v0.5.3-rc1.0.20170407200202-db11e7dd7b55/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  		err := fmt.Errorf("Unable to obtain CPU information: %v", err)
    35  
    36  		if cfg.CpuCompute != 0 {
    37  			f.logger.Printf("[DEBUG] fingerprint.cpu: %v. Using specified cpu compute %d", err, cfg.CpuCompute)
    38  			setResources(cfg.CpuCompute)
    39  			return true, nil
    40  		}
    41  
    42  		f.logger.Printf("[ERR] fingerprint.cpu: %v", err)
    43  		f.logger.Printf("[INFO] fingerprint.cpu: cpu compute may be set manually"+
    44  			" using the client config option %q on machines where cpu information"+
    45  			" can not be automatically detected.", "cpu_total_compute")
    46  
    47  		return false, err
    48  	}
    49  
    50  	modelName := stats.CPUModelName()
    51  	if modelName != "" {
    52  		node.Attributes["cpu.modelname"] = modelName
    53  	}
    54  
    55  	mhz := stats.CPUMHzPerCore()
    56  	node.Attributes["cpu.frequency"] = fmt.Sprintf("%.0f", mhz)
    57  	f.logger.Printf("[DEBUG] fingerprint.cpu: frequency: %.0f MHz", mhz)
    58  
    59  	numCores := stats.CPUNumCores()
    60  	node.Attributes["cpu.numcores"] = fmt.Sprintf("%d", numCores)
    61  	f.logger.Printf("[DEBUG] fingerprint.cpu: core count: %d", numCores)
    62  
    63  	tt := stats.TotalTicksAvailable()
    64  
    65  	node.Attributes["cpu.totalcompute"] = fmt.Sprintf("%.0f", tt)
    66  
    67  	setResources(int(tt))
    68  	return true, nil
    69  }