github.com/dkerwin/nomad@v0.3.3-0.20160525181927-74554135514b/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  		numCores += c.Cores
    39  		mhz += c.Mhz
    40  
    41  		if modelName != "" && modelName != c.ModelName {
    42  			f.logger.Println("[WARN] Found different model names in the same CPU information. Recording last found")
    43  		}
    44  		modelName = c.ModelName
    45  	}
    46  	// Get average CPU frequency
    47  	mhz /= float64(len(cpuInfo))
    48  
    49  	if mhz > 0 {
    50  		node.Attributes["cpu.frequency"] = fmt.Sprintf("%.6f", mhz)
    51  		f.logger.Printf("[DEBUG] fingerprint.cpu: frequency: %02.1fMHz", mhz)
    52  	}
    53  
    54  	if numCores <= 0 {
    55  		const defaultCPUCoreCount = 1
    56  		f.logger.Printf("[DEBUG] fingerprint.cpu: unable to find core count, defaulting to %d", defaultCPUCoreCount)
    57  		numCores = defaultCPUCoreCount
    58  	}
    59  
    60  	if numCores > 0 {
    61  		node.Attributes["cpu.numcores"] = fmt.Sprintf("%d", numCores)
    62  		f.logger.Printf("[DEBUG] fingerprint.cpu: core count: %d", numCores)
    63  	}
    64  
    65  	if mhz > 0 && numCores > 0 {
    66  		tc := float64(numCores) * mhz
    67  		node.Attributes["cpu.totalcompute"] = fmt.Sprintf("%.6f", tc)
    68  
    69  		if node.Resources == nil {
    70  			node.Resources = &structs.Resources{}
    71  		}
    72  
    73  		node.Resources.CPU = int(tc)
    74  	}
    75  
    76  	if modelName != "" {
    77  		node.Attributes["cpu.modelname"] = modelName
    78  	}
    79  
    80  	return true, nil
    81  }