cubefs
1// Copyright 2018 The CubeFS Authors.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12// implied. See the License for the specific language governing
13// permissions and limitations under the License.
14
15package util16
17import (18"bufio"19"fmt"20"os"21"strconv"22"strings"23)
24
25const (26MEMINFO = "/proc/meminfo"27PRO_MEM = "/proc/%d/status"28)
29
30// GetMemInfo returns the memory information.
31func GetMemInfo() (total, used uint64, err error) {32fp, err := os.Open(MEMINFO)33if err != nil {34return35}36// TODO Unhandled errors37defer fp.Close()38var (39val uint6440free uint6441buffer uint6442cached uint6443)44scan := bufio.NewScanner(fp)45for scan.Scan() {46line := scan.Text()47fields := strings.Split(line, ":")48if len(fields) != 2 {49continue50}51key := fields[0]52value := strings.TrimSpace(fields[1])53value = strings.Replace(value, " kB", "", -1)54val, err = strconv.ParseUint(value, 10, 64)55if err != nil {56return57}58switch key {59case "MemTotal":60total = val * KB61case "MemFree":62free = val * KB63case "Buffers":64buffer = val * KB65case "Cached":66cached = val * KB67default:68// do nothing69}70}71used = total - free - buffer - cached72return73}
74
75func GetProcessMemory(pid int) (used uint64, err error) {76proFileName := fmt.Sprintf(PRO_MEM, pid)77fp, err := os.Open(proFileName)78if err != nil {79return80}81defer fp.Close()82scan := bufio.NewScanner(fp)83for scan.Scan() {84line := scan.Text()85fields := strings.Split(line, ":")86key := fields[0]87if key != "VmRSS" {88continue89}90value := strings.TrimSpace(fields[1])91value = strings.Replace(value, " kB", "", -1)92used, err = strconv.ParseUint(value, 10, 64)93if err != nil {94return95}96used = used * KB97break98}99return100}
101