2018-02-05 16:05:59 -05:00
|
|
|
package system // import "github.com/docker/docker/pkg/system"
|
2014-10-13 23:41:22 -04:00
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"io"
|
|
|
|
"os"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2015-03-31 04:03:31 -04:00
|
|
|
// ReadMemInfo retrieves memory statistics of the host system and returns a
|
2016-03-11 10:02:17 -05:00
|
|
|
// MemInfo type.
|
2014-10-13 23:41:22 -04:00
|
|
|
func ReadMemInfo() (*MemInfo, error) {
|
|
|
|
file, err := os.Open("/proc/meminfo")
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer file.Close()
|
|
|
|
return parseMemInfo(file)
|
|
|
|
}
|
|
|
|
|
2015-03-31 04:03:31 -04:00
|
|
|
// parseMemInfo parses the /proc/meminfo file into
|
2016-03-11 10:02:17 -05:00
|
|
|
// a MemInfo object given an io.Reader to the file.
|
2015-03-31 04:03:31 -04:00
|
|
|
// Throws error if there are problems reading from the file
|
2014-10-13 23:41:22 -04:00
|
|
|
func parseMemInfo(reader io.Reader) (*MemInfo, error) {
|
|
|
|
meminfo := &MemInfo{}
|
|
|
|
scanner := bufio.NewScanner(reader)
|
2019-07-10 04:43:03 -04:00
|
|
|
memAvailable := int64(-1)
|
2014-10-13 23:41:22 -04:00
|
|
|
for scanner.Scan() {
|
|
|
|
// Expected format: ["MemTotal:", "1234", "kB"]
|
|
|
|
parts := strings.Fields(scanner.Text())
|
|
|
|
|
|
|
|
// Sanity checks: Skip malformed entries.
|
|
|
|
if len(parts) < 3 || parts[2] != "kB" {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// Convert to bytes.
|
|
|
|
size, err := strconv.Atoi(parts[1])
|
|
|
|
if err != nil {
|
|
|
|
continue
|
|
|
|
}
|
2022-03-02 16:44:29 -05:00
|
|
|
// Convert to KiB
|
|
|
|
bytes := int64(size) * 1024
|
2014-10-13 23:41:22 -04:00
|
|
|
|
|
|
|
switch parts[0] {
|
|
|
|
case "MemTotal:":
|
|
|
|
meminfo.MemTotal = bytes
|
|
|
|
case "MemFree:":
|
|
|
|
meminfo.MemFree = bytes
|
2019-07-10 04:43:03 -04:00
|
|
|
case "MemAvailable:":
|
|
|
|
memAvailable = bytes
|
2014-10-13 23:41:22 -04:00
|
|
|
case "SwapTotal:":
|
|
|
|
meminfo.SwapTotal = bytes
|
|
|
|
case "SwapFree:":
|
|
|
|
meminfo.SwapFree = bytes
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
2019-07-10 04:43:03 -04:00
|
|
|
if memAvailable != -1 {
|
|
|
|
meminfo.MemFree = memAvailable
|
|
|
|
}
|
2014-10-13 23:41:22 -04:00
|
|
|
|
|
|
|
// Handle errors that may have occurred during the reading of the file.
|
|
|
|
if err := scanner.Err(); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return meminfo, nil
|
|
|
|
}
|