cubefs

Форк
0
/
mem.go 
100 строк · 2.1 Кб
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

15
package util
16

17
import (
18
	"bufio"
19
	"fmt"
20
	"os"
21
	"strconv"
22
	"strings"
23
)
24

25
const (
26
	MEMINFO = "/proc/meminfo"
27
	PRO_MEM = "/proc/%d/status"
28
)
29

30
// GetMemInfo returns the memory information.
31
func GetMemInfo() (total, used uint64, err error) {
32
	fp, err := os.Open(MEMINFO)
33
	if err != nil {
34
		return
35
	}
36
	// TODO Unhandled errors
37
	defer fp.Close()
38
	var (
39
		val    uint64
40
		free   uint64
41
		buffer uint64
42
		cached uint64
43
	)
44
	scan := bufio.NewScanner(fp)
45
	for scan.Scan() {
46
		line := scan.Text()
47
		fields := strings.Split(line, ":")
48
		if len(fields) != 2 {
49
			continue
50
		}
51
		key := fields[0]
52
		value := strings.TrimSpace(fields[1])
53
		value = strings.Replace(value, " kB", "", -1)
54
		val, err = strconv.ParseUint(value, 10, 64)
55
		if err != nil {
56
			return
57
		}
58
		switch key {
59
		case "MemTotal":
60
			total = val * KB
61
		case "MemFree":
62
			free = val * KB
63
		case "Buffers":
64
			buffer = val * KB
65
		case "Cached":
66
			cached = val * KB
67
		default:
68
			// do nothing
69
		}
70
	}
71
	used = total - free - buffer - cached
72
	return
73
}
74

75
func GetProcessMemory(pid int) (used uint64, err error) {
76
	proFileName := fmt.Sprintf(PRO_MEM, pid)
77
	fp, err := os.Open(proFileName)
78
	if err != nil {
79
		return
80
	}
81
	defer fp.Close()
82
	scan := bufio.NewScanner(fp)
83
	for scan.Scan() {
84
		line := scan.Text()
85
		fields := strings.Split(line, ":")
86
		key := fields[0]
87
		if key != "VmRSS" {
88
			continue
89
		}
90
		value := strings.TrimSpace(fields[1])
91
		value = strings.Replace(value, " kB", "", -1)
92
		used, err = strconv.ParseUint(value, 10, 64)
93
		if err != nil {
94
			return
95
		}
96
		used = used * KB
97
		break
98
	}
99
	return
100
}
101

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.