Fix some bugs when testing opensds ansible
[stor4nfv.git] / src / ceph / src / common / MemoryModel.cc
1 #include "MemoryModel.h"
2 #include "include/compat.h"
3 #include "debug.h"
4 #if defined(__linux__)
5 #include <malloc.h>
6 #endif
7
8 #include <fstream>
9
10 #define dout_subsys ceph_subsys_
11
12 MemoryModel::MemoryModel(CephContext *cct_)
13   : cct(cct_)
14 {
15 }
16
17 void MemoryModel::_sample(snap *psnap)
18 {
19   ifstream f;
20
21   f.open(PROCPREFIX "/proc/self/status");
22   if (!f.is_open()) {
23     ldout(cct, 0) << "check_memory_usage unable to open " PROCPREFIX "/proc/self/status" << dendl;
24     return;
25   }
26   while (!f.eof()) {
27     string line;
28     getline(f, line);
29     
30     if (strncmp(line.c_str(), "VmSize:", 7) == 0)
31       psnap->size = atol(line.c_str() + 7);
32     else if (strncmp(line.c_str(), "VmRSS:", 6) == 0)
33       psnap->rss = atol(line.c_str() + 7);
34     else if (strncmp(line.c_str(), "VmHWM:", 6) == 0)
35       psnap->hwm = atol(line.c_str() + 7);
36     else if (strncmp(line.c_str(), "VmLib:", 6) == 0)
37       psnap->lib = atol(line.c_str() + 7);
38     else if (strncmp(line.c_str(), "VmPeak:", 7) == 0)
39       psnap->peak = atol(line.c_str() + 7);
40     else if (strncmp(line.c_str(), "VmData:", 7) == 0)
41       psnap->data = atol(line.c_str() + 7);
42   }
43   f.close();
44
45   f.open(PROCPREFIX "/proc/self/maps");
46   if (!f.is_open()) {
47     ldout(cct, 0) << "check_memory_usage unable to open " PROCPREFIX "/proc/self/maps" << dendl;
48     return;
49   }
50
51   long heap = 0;
52   while (f.is_open() && !f.eof()) {
53     string line;
54     getline(f, line);
55     //ldout(cct, 0) << "line is " << line << dendl;
56
57     const char *start = line.c_str();
58     const char *dash = start;
59     while (*dash && *dash != '-') dash++;
60     if (!*dash)
61       continue;
62     const char *end = dash + 1;
63     while (*end && *end != ' ') end++;
64     if (!*end)
65       continue;
66     unsigned long long as = strtoll(start, 0, 16);
67     unsigned long long ae = strtoll(dash+1, 0, 16);
68
69     //ldout(cct, 0) << std::hex << as << " to " << ae << std::dec << dendl;
70
71     end++;
72     const char *mode = end;
73
74     int skip = 4;
75     while (skip--) {
76       end++;
77       while (*end && *end != ' ') end++;
78     }
79     if (*end)
80       end++;
81
82     long size = ae - as;
83     //ldout(cct, 0) << "size " << size << " mode is '" << mode << "' end is '" << end << "'" << dendl;
84
85     /*
86      * anything 'rw' and anon is assumed to be heap.
87      */
88     if (mode[0] == 'r' && mode[1] == 'w' && !*end)
89       heap += size;
90   }
91
92   psnap->heap = heap >> 10;
93
94 }