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