github.com/ranjib/nomad@v0.1.1-0.20160225204057-97751b02f70b/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  	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  	cpuInfo, err := cpu.CPUInfo()
    26  	if err != nil {
    27  		f.logger.Println("[WARN] Error reading CPU information:", err)
    28  		return false, err
    29  	}
    30  
    31  	var numCores int32
    32  	var mhz float64
    33  	var modelName string
    34  
    35  	// Assume all CPUs found have same Model. Log if not.
    36  	// If CPUInfo() returns nil above, this loop is still safe
    37  	for _, c := range cpuInfo {
    38  		if c.Cores == 0 {
    39  			numCores += 1
    40  		} else {
    41  			numCores += c.Cores
    42  		}
    43  		mhz += c.Mhz
    44  
    45  		if modelName != "" && modelName != c.ModelName {
    46  			f.logger.Println("[WARN] Found different model names in the same CPU information. Recording last found")
    47  		}
    48  		modelName = c.ModelName
    49  	}
    50  	// Get average CPU frequency
    51  	mhz /= float64(len(cpuInfo))
    52  
    53  	if mhz > 0 {
    54  		node.Attributes["cpu.frequency"] = fmt.Sprintf("%.6f", mhz)
    55  	}
    56  
    57  	if numCores > 0 {
    58  		node.Attributes["cpu.numcores"] = fmt.Sprintf("%d", numCores)
    59  	}
    60  
    61  	if mhz > 0 && numCores > 0 {
    62  		tc := float64(numCores) * mhz
    63  		node.Attributes["cpu.totalcompute"] = fmt.Sprintf("%.6f", tc)
    64  
    65  		if node.Resources == nil {
    66  			node.Resources = &structs.Resources{}
    67  		}
    68  
    69  		node.Resources.CPU = int(tc)
    70  	}
    71  
    72  	if modelName != "" {
    73  		node.Attributes["cpu.modelname"] = modelName
    74  	}
    75  
    76  	return true, nil
    77  }