2023-04-10 15:36:59 +00:00
|
|
|
// Copyright (c) HashiCorp, Inc.
|
|
|
|
// SPDX-License-Identifier: MPL-2.0
|
|
|
|
|
2015-08-27 19:58:37 +00:00
|
|
|
package fingerprint
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
|
2018-09-16 00:48:59 +00:00
|
|
|
log "github.com/hashicorp/go-hclog"
|
2018-01-30 17:57:37 +00:00
|
|
|
"github.com/hashicorp/nomad/nomad/structs"
|
2021-03-30 18:47:33 +00:00
|
|
|
"github.com/shirou/gopsutil/v3/mem"
|
2015-08-27 19:58:37 +00:00
|
|
|
)
|
|
|
|
|
2019-08-31 14:36:47 +00:00
|
|
|
const bytesInMB int64 = 1024 * 1024
|
2018-03-28 15:07:15 +00:00
|
|
|
|
2015-08-27 19:58:37 +00:00
|
|
|
// MemoryFingerprint is used to fingerprint the available memory on the node
|
|
|
|
type MemoryFingerprint struct {
|
2015-11-05 21:46:02 +00:00
|
|
|
StaticFingerprinter
|
2018-09-16 00:48:59 +00:00
|
|
|
logger log.Logger
|
2015-08-27 19:58:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewMemoryFingerprint is used to create a Memory fingerprint
|
2018-09-16 00:48:59 +00:00
|
|
|
func NewMemoryFingerprint(logger log.Logger) Fingerprint {
|
2015-08-27 19:58:37 +00:00
|
|
|
f := &MemoryFingerprint{
|
2018-09-16 00:48:59 +00:00
|
|
|
logger: logger.Named("memory"),
|
2015-08-27 19:58:37 +00:00
|
|
|
}
|
|
|
|
return f
|
|
|
|
}
|
|
|
|
|
2018-12-01 16:10:39 +00:00
|
|
|
func (f *MemoryFingerprint) Fingerprint(req *FingerprintRequest, resp *FingerprintResponse) error {
|
2019-08-31 14:36:47 +00:00
|
|
|
var totalMemory int64
|
2018-01-22 20:28:29 +00:00
|
|
|
cfg := req.Config
|
|
|
|
if cfg.MemoryMB != 0 {
|
2019-08-31 14:36:47 +00:00
|
|
|
totalMemory = int64(cfg.MemoryMB) * bytesInMB
|
2018-01-22 20:28:29 +00:00
|
|
|
} else {
|
|
|
|
memInfo, err := mem.VirtualMemory()
|
|
|
|
if err != nil {
|
2018-09-16 00:48:59 +00:00
|
|
|
f.logger.Warn("error reading memory information", "error", err)
|
2018-01-22 20:28:29 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
if memInfo.Total > 0 {
|
2019-08-31 14:36:47 +00:00
|
|
|
totalMemory = int64(memInfo.Total)
|
2018-01-22 20:28:29 +00:00
|
|
|
}
|
2015-08-27 19:58:37 +00:00
|
|
|
}
|
|
|
|
|
2018-01-22 20:28:29 +00:00
|
|
|
if totalMemory > 0 {
|
|
|
|
resp.AddAttribute("memory.totalbytes", fmt.Sprintf("%d", totalMemory))
|
2018-09-30 00:23:41 +00:00
|
|
|
|
2019-09-04 15:09:30 +00:00
|
|
|
memoryMB := totalMemory / bytesInMB
|
|
|
|
|
2019-09-04 15:38:35 +00:00
|
|
|
// COMPAT(0.10): Unused since 0.9.
|
2019-09-04 15:09:30 +00:00
|
|
|
resp.Resources = &structs.Resources{
|
|
|
|
MemoryMB: int(memoryMB),
|
|
|
|
}
|
|
|
|
|
2018-09-30 00:23:41 +00:00
|
|
|
resp.NodeResources = &structs.NodeResources{
|
|
|
|
Memory: structs.NodeMemoryResources{
|
2019-09-04 15:09:30 +00:00
|
|
|
MemoryMB: memoryMB,
|
2018-09-30 00:23:41 +00:00
|
|
|
},
|
|
|
|
}
|
2015-08-27 19:58:37 +00:00
|
|
|
}
|
|
|
|
|
2018-01-24 14:09:53 +00:00
|
|
|
return nil
|
2015-08-27 19:58:37 +00:00
|
|
|
}
|