github.com/iqoqo/nomad@v0.11.3-0.20200911112621-d7021c74d101/client/fingerprint/memory.go (about)

     1  package fingerprint
     2  
     3  import (
     4  	"fmt"
     5  
     6  	log "github.com/hashicorp/go-hclog"
     7  	"github.com/hashicorp/nomad/nomad/structs"
     8  	"github.com/shirou/gopsutil/mem"
     9  )
    10  
    11  const bytesInMB int64 = 1024 * 1024
    12  
    13  // MemoryFingerprint is used to fingerprint the available memory on the node
    14  type MemoryFingerprint struct {
    15  	StaticFingerprinter
    16  	logger log.Logger
    17  }
    18  
    19  // NewMemoryFingerprint is used to create a Memory fingerprint
    20  func NewMemoryFingerprint(logger log.Logger) Fingerprint {
    21  	f := &MemoryFingerprint{
    22  		logger: logger.Named("memory"),
    23  	}
    24  	return f
    25  }
    26  
    27  func (f *MemoryFingerprint) Fingerprint(req *FingerprintRequest, resp *FingerprintResponse) error {
    28  	var totalMemory int64
    29  	cfg := req.Config
    30  	if cfg.MemoryMB != 0 {
    31  		totalMemory = int64(cfg.MemoryMB) * bytesInMB
    32  	} else {
    33  		memInfo, err := mem.VirtualMemory()
    34  		if err != nil {
    35  			f.logger.Warn("error reading memory information", "error", err)
    36  			return err
    37  		}
    38  		if memInfo.Total > 0 {
    39  			totalMemory = int64(memInfo.Total)
    40  		}
    41  	}
    42  
    43  	if totalMemory > 0 {
    44  		resp.AddAttribute("memory.totalbytes", fmt.Sprintf("%d", totalMemory))
    45  
    46  		memoryMB := totalMemory / bytesInMB
    47  
    48  		// COMPAT(0.10): Unused since 0.9.
    49  		resp.Resources = &structs.Resources{
    50  			MemoryMB: int(memoryMB),
    51  		}
    52  
    53  		resp.NodeResources = &structs.NodeResources{
    54  			Memory: structs.NodeMemoryResources{
    55  				MemoryMB: memoryMB,
    56  			},
    57  		}
    58  	}
    59  
    60  	return nil
    61  }