github.com/wlan0/docker@v1.5.0/pkg/system/meminfo_linux.go (about) 1 package system 2 3 import ( 4 "bufio" 5 "errors" 6 "io" 7 "os" 8 "strconv" 9 "strings" 10 11 "github.com/docker/docker/pkg/units" 12 ) 13 14 var ( 15 ErrMalformed = errors.New("malformed file") 16 ) 17 18 // Retrieve memory statistics of the host system and parse them into a MemInfo 19 // type. 20 func ReadMemInfo() (*MemInfo, error) { 21 file, err := os.Open("/proc/meminfo") 22 if err != nil { 23 return nil, err 24 } 25 defer file.Close() 26 return parseMemInfo(file) 27 } 28 29 func parseMemInfo(reader io.Reader) (*MemInfo, error) { 30 meminfo := &MemInfo{} 31 scanner := bufio.NewScanner(reader) 32 for scanner.Scan() { 33 // Expected format: ["MemTotal:", "1234", "kB"] 34 parts := strings.Fields(scanner.Text()) 35 36 // Sanity checks: Skip malformed entries. 37 if len(parts) < 3 || parts[2] != "kB" { 38 continue 39 } 40 41 // Convert to bytes. 42 size, err := strconv.Atoi(parts[1]) 43 if err != nil { 44 continue 45 } 46 bytes := int64(size) * units.KiB 47 48 switch parts[0] { 49 case "MemTotal:": 50 meminfo.MemTotal = bytes 51 case "MemFree:": 52 meminfo.MemFree = bytes 53 case "SwapTotal:": 54 meminfo.SwapTotal = bytes 55 case "SwapFree:": 56 meminfo.SwapFree = bytes 57 } 58 59 } 60 61 // Handle errors that may have occurred during the reading of the file. 62 if err := scanner.Err(); err != nil { 63 return nil, err 64 } 65 66 return meminfo, nil 67 }