File size: 6,742 Bytes
68888be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
#include "io/os_info.h"

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cwctype>
#include <filesystem>
#include <string>

#include "common/base.h"

#if defined(_WIN32)
#ifndef NOMINMAX
#define NOMINMAX
#endif
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
// GetProcessMemoryInfo from kernel32 itself, so that no psapi library is linked
#ifndef PSAPI_VERSION
#define PSAPI_VERSION 2
#endif
#include <psapi.h>
#elif defined(__APPLE__)
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/sysctl.h>
#include <sys/types.h>
#else
#include <sys/resource.h>
#include <sys/stat.h>
#include <unistd.h>
#endif

namespace hk {

#if defined(__linux__)
// cgroup v2 (memory.max) or v1 (memory.limit_in_bytes); "max" or a huge number means no limit
static int64_t cgroup_limit() {
    const char* files[] = {"/sys/fs/cgroup/memory.max", "/sys/fs/cgroup/memory/memory.limit_in_bytes"};
    for (const char* f : files) {
        FILE* fp = fopen(f, "r");
        if (!fp) continue;
        char buf[64] = {0};
        size_t n = fread(buf, 1, sizeof(buf) - 1, fp);
        fclose(fp);
        if (n == 0 || buf[0] == 'm') continue;
        long long v = atoll(buf);
        if (v > 0 && v < ((long long)1 << 60)) return (int64_t)v;
    }
    return -1;
}
#endif

int64_t system_ram_bytes() {
#if defined(_WIN32)
    MEMORYSTATUSEX st;
    st.dwLength = sizeof(st);
    if (!GlobalMemoryStatusEx(&st)) return -1;
    return (int64_t)st.ullTotalPhys;
#elif defined(__APPLE__)
    int64_t mem = 0;
    size_t len = sizeof(mem);
    if (sysctlbyname("hw.memsize", &mem, &len, nullptr, 0) != 0) return -1;
    return mem;
#else
    int64_t phys = (int64_t)sysconf(_SC_PHYS_PAGES) * (int64_t)sysconf(_SC_PAGE_SIZE);
#if defined(__linux__)
    int64_t lim = cgroup_limit();
    if (lim > 0 && lim < phys) return lim;
#endif
    return phys;
#endif
}

#if defined(__linux__)
// a number from a one-line file, or -1
static int64_t file_number(const char* path) {
    FILE* fp = fopen(path, "r");
    if (!fp) return -1;
    char buf[64] = {0};
    size_t n = fread(buf, 1, sizeof(buf) - 1, fp);
    fclose(fp);
    if (n == 0 || buf[0] < '0' || buf[0] > '9') return -1;
    long long v = atoll(buf);
    return v >= 0 && v < ((long long)1 << 60) ? (int64_t)v : -1;
}
#endif

int64_t system_ram_free_bytes() {
#if defined(_WIN32)
    MEMORYSTATUSEX st;
    st.dwLength = sizeof(st);
    if (!GlobalMemoryStatusEx(&st)) return -1;
    return (int64_t)st.ullAvailPhys;
#elif defined(__linux__)
    int64_t avail = -1;
    if (FILE* fp = fopen("/proc/meminfo", "r")) {
        char line[256];
        while (fgets(line, sizeof(line), fp)) {
            long long kb = 0;
            if (sscanf(line, "MemAvailable: %lld kB", &kb) == 1) {
                avail = (int64_t)kb * 1024;
                break;
            }
        }
        fclose(fp);
    }
    // In a container the limit counts, not the host's memory. File cache counts as used
    // there, but the kernel gives it up when memory is asked for.
    const int64_t lim = cgroup_limit();
    if (lim > 0) {
        int64_t used = file_number("/sys/fs/cgroup/memory.current");
        const char* stat = "/sys/fs/cgroup/memory.stat";
        if (used < 0) {
            used = file_number("/sys/fs/cgroup/memory/memory.usage_in_bytes");
            stat = "/sys/fs/cgroup/memory/memory.stat";
        }
        if (used >= 0) {
            long long cached = 0, total_cached = -1;
            if (FILE* fp = fopen(stat, "r")) {
                char name[64];
                long long v = 0;
                while (fscanf(fp, "%63s %lld", name, &v) == 2) {
                    const std::string s = name;
                    if (s == "inactive_file" || s == "active_file") cached += v;
                    if (s == "total_inactive_file" || s == "total_active_file") total_cached = (total_cached < 0 ? 0 : total_cached) + v;
                }
                fclose(fp);
            }
            if (total_cached >= 0) cached = total_cached;   // cgroup v1 with child groups
            used = used > cached ? used - cached : 0;
            const int64_t left = lim > used ? lim - used : 0;
            if (avail < 0 || left < avail) avail = left;
        }
    }
    return avail;
#else
    return -1;
#endif
}

int64_t process_ram_peak_bytes() {
#if defined(_WIN32)
    PROCESS_MEMORY_COUNTERS pmc;
    memset(&pmc, 0, sizeof(pmc));
    pmc.cb = sizeof(pmc);
    if (!GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc))) return -1;
    return (int64_t)pmc.PeakWorkingSetSize;
#else
    struct rusage ru;
    if (getrusage(RUSAGE_SELF, &ru) != 0) return -1;
#if defined(__APPLE__)
    return (int64_t)ru.ru_maxrss;          // bytes there
#else
    return (int64_t)ru.ru_maxrss * 1024;   // kilobytes here
#endif
#endif
}

int64_t disk_free_bytes(const std::string& path) {
    std::error_code ec;
    auto info = std::filesystem::space(std::filesystem::u8path(path), ec);
    if (ec) return -1;
    return (int64_t)info.available;
}

bool same_volume(const std::string& a, const std::string& b) {
#if defined(_WIN32)
    // the volume of a path: the longest mount point that starts it
    auto volume = [](const std::string& path) {
        std::error_code ec;
        std::wstring full = std::filesystem::absolute(std::filesystem::u8path(path), ec).wstring();
        wchar_t root[MAX_PATH + 1] = {0};
        if (ec || !GetVolumePathNameW(full.c_str(), root, MAX_PATH)) return std::wstring();
        std::wstring v(root);
        for (wchar_t& ch : v) ch = (wchar_t)towlower(ch);
        return v;
    };
    std::wstring va = volume(a), vb = volume(b);
    return !va.empty() && va == vb;
#else
    struct stat sa, sb;
    if (stat(a.c_str(), &sa) != 0 || stat(b.c_str(), &sb) != 0) return false;
    return sa.st_dev == sb.st_dev;
#endif
}

bool file_is_open_here(const std::string& path) {
#if defined(__linux__)
    // One entry per open descriptor. Compared by device and inode, so a file reached
    // under another name still counts.
    struct stat want;
    if (stat(path.c_str(), &want) != 0) return false;
    std::error_code ec;
    for (std::filesystem::directory_iterator it("/proc/self/fd", ec), end; !ec && it != end; it.increment(ec)) {
        struct stat st;
        int fd = atoi(it->path().filename().string().c_str());
        if (fstat(fd, &st) == 0 && st.st_dev == want.st_dev && st.st_ino == want.st_ino) return true;
    }
    return false;
#else
    (void)path;
    return false;
#endif
}

std::string os_name() {
#if defined(_WIN32)
    return "windows";
#elif defined(__APPLE__)
    return "macos";
#elif defined(__linux__)
    return "linux";
#else
    return "posix";
#endif
}

}  // namespace hk