github.com/bigcommerce/nomad@v0.9.3-bc/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 = 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 int
    29  	cfg := req.Config
    30  	if cfg.MemoryMB != 0 {
    31  		totalMemory = 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 = int(memInfo.Total)
    40  		}
    41  	}
    42  
    43  	if totalMemory > 0 {
    44  		resp.AddAttribute("memory.totalbytes", fmt.Sprintf("%d", totalMemory))
    45  
    46  		// COMPAT(0.10): Remove in 0.10
    47  		resp.Resources = &structs.Resources{
    48  			MemoryMB: totalMemory / bytesInMB,
    49  		}
    50  
    51  		resp.NodeResources = &structs.NodeResources{
    52  			Memory: structs.NodeMemoryResources{
    53  				MemoryMB: int64(totalMemory / bytesInMB),
    54  			},
    55  		}
    56  	}
    57  
    58  	return nil
    59  }