-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathPlatform.actor.cpp
4458 lines (3892 loc) · 141 KB
/
Platform.actor.cpp
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Platform.actor.cpp
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2013-2024 Apple Inc. and the FoundationDB project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifdef _WIN32
// This has to come as the first include on Win32 for rand_s() to be found
#define _CRT_RAND_S
#endif // _WIN32
#include "flow/Platform.h"
#include <algorithm>
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstring>
#include <string>
#include <string_view>
#include <vector>
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#include <boost/format.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/asio.hpp>
#include "fmt/format.h"
#include "flow/Arena.h"
#include "flow/Error.h"
#include "flow/FaultInjection.h"
#include "flow/Knobs.h"
#include "flow/Platform.actor.h"
#include "flow/ScopeExit.h"
#include "flow/StreamCipher.h"
#include "flow/Trace.h"
#include "flow/Trace.h"
#include "flow/UnitTest.h"
#include "flow/Util.h"
// boost uses either std::array or boost::asio::detail::array to store the IPv6 Addresses.
// Enforce the format of IPAddressStore, which is declared in IPAddress.h, is using the same type
// to boost.
static_assert(std::is_same<boost::asio::ip::address_v6::bytes_type, std::array<uint8_t, 16>>::value,
"IPAddressStore must be std::array<uint8_t, 16>");
#ifdef _WIN32
#include <conio.h>
#include <direct.h>
#include <io.h>
#include <math.h> // For _set_FMA3_enable workaround in platformInit
#include <pdh.h>
#include <pdhmsg.h>
#include <processenv.h>
#include <psapi.h>
#include <stdlib.h>
#include <windows.h>
#include <winioctl.h>
#pragma comment(lib, "pdh.lib")
// for SHGetFolderPath
#include <ShlObj.h>
#pragma comment(lib, "Shell32.lib")
#define CANONICAL_PATH_SEPARATOR '\\'
#define PATH_MAX MAX_PATH
#endif
#ifdef __unixish__
#define CANONICAL_PATH_SEPARATOR '/'
#include <dirent.h>
#include <ftw.h>
#include <pwd.h>
#include <sched.h>
#include <sys/mman.h>
#include <sys/time.h>
#include <unistd.h>
#include <sys/statvfs.h> /* Needed for disk capacity */
#if !defined(__aarch64__) && !defined(__powerpc64__)
#include <cpuid.h>
#endif
/* getifaddrs */
#include <sys/socket.h>
#include <ifaddrs.h>
#include <arpa/inet.h>
#include "stacktrace/stacktrace.h"
#ifdef __linux__
/* Needed for memory allocation */
#include <linux/mman.h>
/* Needed for processor affinity */
#include <sched.h>
/* Needed for getProcessorTime* and setpriority */
#include <sys/syscall.h>
/* Needed for setpriority */
#include <sys/resource.h>
/* Needed for crash handler */
#include <signal.h>
/* Needed for gnu_dev_{major,minor} */
#include <sys/sysmacros.h>
#endif // __linux__
#ifdef __FreeBSD__
/* Needed for processor affinity */
#include <sys/sched.h>
/* Needed for getProcessorTime and setpriority */
#include <sys/syscall.h>
/* Needed for setpriority */
#include <sys/resource.h>
/* Needed for crash handler */
#include <sys/signal.h>
/* Needed for proc info */
#include <sys/user.h>
/* Needed for vm info */
#include <sys/param.h>
#include <sys/sysctl.h>
#include <sys/vmmeter.h>
#include <sys/cpuset.h>
#include <sys/resource.h>
/* Needed for sysctl info */
#include <sys/sysctl.h>
#include <sys/fcntl.h>
/* Needed for network info */
#include <net/if.h>
#include <net/if_mib.h>
#include <net/if_var.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netinet/tcp_var.h>
/* Needed for device info */
#include <devstat.h>
#include <kvm.h>
#include <libutil.h>
#endif // __FreeBSD__
#ifdef __APPLE__
/* Needed for cross-platform 'environ' */
#include <crt_externs.h>
#include <mach-o/dyld.h>
#include <mach/mach.h>
#include <net/if_dl.h>
#include <net/if.h>
#include <net/route.h>
#include <netinet/in.h>
#include <sys/mount.h>
#include <sys/param.h>
#include <sys/sysctl.h>
#include <sys/syslimits.h>
#include <sys/uio.h>
#include <CoreFoundation/CoreFoundation.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/storage/IOBlockStorageDriver.h>
#include <IOKit/storage/IOMedia.h>
#include <IOKit/IOBSD.h>
#endif // __APPLE_
#endif // __unixish__
#include "flow/actorcompiler.h" // This must be the last #include.
std::string removeWhitespace(const std::string& t) {
static const std::string ws(" \t\r");
std::string str = t;
size_t found = str.find_last_not_of(ws);
if (found != std::string::npos)
str.erase(found + 1);
else
str.clear(); // str is all whitespace
found = str.find_first_not_of(ws);
if (found != std::string::npos)
str.erase(0, found);
else
str.clear(); // str is all whitespace
return str;
}
#ifdef _WIN32
#define ALLOC_FAIL nullptr
#elif defined(__unixish__)
#define ALLOC_FAIL MAP_FAILED
#else
#error What platform is this?
#endif
#if defined(_WIN32)
__int64 FiletimeAsInt64(FILETIME& t) {
return *(__int64*)&t;
}
#endif
#ifdef _WIN32
bool handlePdhStatus(const PDH_STATUS& status, std::string message) {
if (status != ERROR_SUCCESS) {
TraceEvent(SevWarnAlways, message.c_str()).GetLastError().detail("Status", status);
return false;
}
return true;
}
bool setPdhString(int id, std::string& out) {
char buf[512];
DWORD sz = 512;
if (!handlePdhStatus(PdhLookupPerfNameByIndex(nullptr, id, buf, &sz), "PdhLookupPerfByNameIndex"))
return false;
out = buf;
return true;
}
#endif
#ifdef __unixish__
static double getProcessorTimeGeneric(int who) {
struct rusage r_usage;
if (getrusage(who, &r_usage)) {
TraceEvent(SevError, "GetCPUTime").detail("Who", who).GetLastError();
throw platform_error();
}
return (r_usage.ru_utime.tv_sec + (r_usage.ru_utime.tv_usec / double(1e6)) + r_usage.ru_stime.tv_sec +
(r_usage.ru_stime.tv_usec / double(1e6)));
}
#endif
double getProcessorTimeThread() {
INJECT_FAULT(platform_error, "getProcessorTimeThread"); // Get Thread CPU Time failed
#if defined(_WIN32)
FILETIME ftCreate, ftExit, ftKernel, ftUser;
if (!GetThreadTimes(GetCurrentThread(), &ftCreate, &ftExit, &ftKernel, &ftUser)) {
TraceEvent(SevError, "GetThreadCPUTime").GetLastError();
throw platform_error();
}
return FiletimeAsInt64(ftKernel) / double(1e7) + FiletimeAsInt64(ftUser) / double(1e7);
#elif defined(__linux__) || defined(__FreeBSD__)
return getProcessorTimeGeneric(RUSAGE_THREAD);
#elif defined(__APPLE__)
/* No RUSAGE_THREAD so we use the lower level interface */
struct thread_basic_info info;
mach_msg_type_number_t info_count = THREAD_BASIC_INFO_COUNT;
if (KERN_SUCCESS != thread_info(mach_thread_self(), THREAD_BASIC_INFO, (thread_info_t)&info, &info_count)) {
TraceEvent(SevError, "GetThreadCPUTime").GetLastError();
throw platform_error();
}
return (info.user_time.seconds + (info.user_time.microseconds / double(1e6)) + info.system_time.seconds +
(info.system_time.microseconds / double(1e6)));
#else
#warning getProcessorTimeThread unimplemented on this platform
return 0.0;
#endif
}
double getProcessorTimeProcess() {
INJECT_FAULT(platform_error, "getProcessorTimeProcess"); // Get CPU Process Time failed
#if defined(_WIN32)
FILETIME ftCreate, ftExit, ftKernel, ftUser;
if (!GetProcessTimes(GetCurrentProcess(), &ftCreate, &ftExit, &ftKernel, &ftUser)) {
TraceEvent(SevError, "GetProcessCPUTime").GetLastError();
throw platform_error();
}
return FiletimeAsInt64(ftKernel) / double(1e7) + FiletimeAsInt64(ftUser) / double(1e7);
#elif defined(__unixish__)
return getProcessorTimeGeneric(RUSAGE_SELF);
#else
#warning getProcessorTimeProcess unimplemented on this platform
return 0.0;
#endif
}
uint64_t getResidentMemoryUsage() {
#if defined(__linux__)
uint64_t rssize = 0;
std::ifstream stat_stream("/proc/self/statm", std::ifstream::in);
std::string ignore;
if (!stat_stream.good()) {
TraceEvent(SevError, "GetResidentMemoryUsage").GetLastError();
throw platform_error();
}
stat_stream >> ignore;
stat_stream >> rssize;
rssize *= sysconf(_SC_PAGESIZE);
return rssize;
#elif defined(__FreeBSD__)
uint64_t rssize = 0;
int status;
pid_t ppid = getpid();
int pidinfo[4];
pidinfo[0] = CTL_KERN;
pidinfo[1] = KERN_PROC;
pidinfo[2] = KERN_PROC_PID;
pidinfo[3] = (int)ppid;
struct kinfo_proc procstk;
size_t len = sizeof(procstk);
status = sysctl(pidinfo, nitems(pidinfo), &procstk, &len, nullptr, 0);
if (status < 0) {
TraceEvent(SevError, "GetResidentMemoryUsage").GetLastError();
throw platform_error();
}
rssize = (uint64_t)procstk.ki_rssize;
return rssize;
#elif defined(_WIN32)
PROCESS_MEMORY_COUNTERS_EX pmc;
if (!GetProcessMemoryInfo(GetCurrentProcess(), (PPROCESS_MEMORY_COUNTERS)&pmc, sizeof(pmc))) {
TraceEvent(SevError, "GetResidentMemoryUsage").GetLastError();
throw platform_error();
}
return pmc.WorkingSetSize;
#elif defined(__APPLE__)
struct task_basic_info info;
mach_msg_type_number_t info_count = TASK_BASIC_INFO_COUNT;
if (KERN_SUCCESS != task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)&info, &info_count)) {
TraceEvent(SevError, "GetResidentMemoryUsage").GetLastError();
throw platform_error();
}
return info.resident_size;
#else
#warning getMemoryUsage unimplemented on this platform
return 0;
#endif
}
uint64_t getMemoryUsage() {
#if defined(__linux__)
uint64_t vmsize = 0;
std::ifstream stat_stream("/proc/self/statm", std::ifstream::in);
if (!stat_stream.good()) {
TraceEvent(SevError, "GetMemoryUsage").GetLastError();
throw platform_error();
}
stat_stream >> vmsize;
vmsize *= sysconf(_SC_PAGESIZE);
return vmsize;
#elif defined(__FreeBSD__)
uint64_t vmsize = 0;
int status;
pid_t ppid = getpid();
int pidinfo[4];
pidinfo[0] = CTL_KERN;
pidinfo[1] = KERN_PROC;
pidinfo[2] = KERN_PROC_PID;
pidinfo[3] = (int)ppid;
struct kinfo_proc procstk;
size_t len = sizeof(procstk);
status = sysctl(pidinfo, nitems(pidinfo), &procstk, &len, nullptr, 0);
if (status < 0) {
TraceEvent(SevError, "GetMemoryUsage").GetLastError();
throw platform_error();
}
vmsize = (uint64_t)procstk.ki_size >> PAGE_SHIFT;
return vmsize;
#elif defined(_WIN32)
PROCESS_MEMORY_COUNTERS_EX pmc;
if (!GetProcessMemoryInfo(GetCurrentProcess(), (PPROCESS_MEMORY_COUNTERS)&pmc, sizeof(pmc))) {
TraceEvent(SevError, "GetMemoryUsage").GetLastError();
throw platform_error();
}
return pmc.PagefileUsage;
#elif defined(__APPLE__)
struct task_basic_info info;
mach_msg_type_number_t info_count = TASK_BASIC_INFO_COUNT;
if (KERN_SUCCESS != task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)&info, &info_count)) {
TraceEvent(SevError, "GetMemoryUsage").GetLastError();
throw platform_error();
}
return info.virtual_size;
#else
#warning getMemoryUsage unimplemented on this platform
return 0;
#endif
}
#ifdef __linux__
namespace linux_os {
namespace {
void getMemoryInfo(std::map<StringRef, int64_t>& request, std::stringstream& memInfoStream) {
size_t count = request.size();
if (count == 0)
return;
keyValueReader<std::string, int64_t>(memInfoStream, [&](const std::string& key, const int64_t& value) -> bool {
auto item = request.find(StringRef(key));
if (item != std::end(request)) {
item->second = value;
--count;
}
return count != 0;
});
}
int64_t getLowWatermark(std::stringstream& zoneInfoStream) {
int64_t lowWatermark = 0;
while (!zoneInfoStream.eof()) {
std::string key;
zoneInfoStream >> key;
if (key == "low") {
int64_t value;
zoneInfoStream >> value;
lowWatermark += value;
}
zoneInfoStream.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
return lowWatermark;
}
void getMachineRAMInfoImpl(MachineRAMInfo& memInfo) {
std::ifstream zoneInfoFileStream("/proc/zoneinfo", std::ifstream::in);
int64_t lowWatermark = 0;
if (!zoneInfoFileStream.good()) {
TraceEvent(SevWarnAlways, "GetMachineZoneInfo").GetLastError();
} else {
std::stringstream zoneInfoStream;
zoneInfoStream << zoneInfoFileStream.rdbuf();
lowWatermark = getLowWatermark(zoneInfoStream) * 4; // Convert from 4K pages to KB
}
std::ifstream fileStream("/proc/meminfo", std::ifstream::in);
if (!fileStream.good()) {
TraceEvent(SevError, "GetMachineMemInfo").GetLastError();
throw platform_error();
}
std::map<StringRef, int64_t> request = {
{ "MemTotal:"_sr, 0 }, { "MemFree:"_sr, 0 }, { "MemAvailable:"_sr, -1 }, { "Active(file):"_sr, 0 },
{ "Inactive(file):"_sr, 0 }, { "SwapTotal:"_sr, 0 }, { "SwapFree:"_sr, 0 }, { "SReclaimable:"_sr, 0 },
};
std::stringstream memInfoStream;
memInfoStream << fileStream.rdbuf();
getMemoryInfo(request, memInfoStream);
int64_t memFree = request["MemFree:"_sr];
int64_t pageCache = request["Active(file):"_sr] + request["Inactive(file):"_sr];
int64_t slabReclaimable = request["SReclaimable:"_sr];
int64_t usedSwap = request["SwapTotal:"_sr] - request["SwapFree:"_sr];
memInfo.total = 1024 * request["MemTotal:"_sr];
if (request["MemAvailable:"_sr] != -1) {
memInfo.available = 1024 * (request["MemAvailable:"_sr] - usedSwap);
} else {
memInfo.available =
1024 * (std::max<int64_t>(0,
(memFree - lowWatermark) + std::max(pageCache - lowWatermark, pageCache / 2) +
std::max(slabReclaimable - lowWatermark, slabReclaimable / 2)) -
usedSwap);
}
memInfo.committed = memInfo.total - memInfo.available;
}
} // anonymous namespace
std::map<std::string, int64_t> reportCGroupCpuStat() {
// Default path to the cpu,cpuacct
// See manpages for cgroup
static const std::string PATH_TO_CPU_CPUACCT = "/sys/fs/cgroup/cpu,cpuacct/cpu.stat";
std::map<std::string, int64_t> result;
std::ifstream ifs(PATH_TO_CPU_CPUACCT);
if (!ifs.is_open()) {
return result;
}
keyValueReader<std::string, int64_t>(ifs, [&](const std::string& key, const int64_t& value) -> bool {
result[key] = value;
return true;
});
return result;
}
} // namespace linux_os
#endif // #ifdef __linux__
void getMachineRAMInfo(MachineRAMInfo& memInfo) {
#if defined(__linux__)
linux_os::getMachineRAMInfoImpl(memInfo);
#elif defined(__FreeBSD__)
int status;
u_int page_size;
u_int free_count;
u_int active_count;
u_int inactive_count;
u_int wire_count;
size_t uint_size;
uint_size = sizeof(page_size);
status = sysctlbyname("vm.stats.vm.v_page_size", &page_size, &uint_size, nullptr, 0);
if (status < 0) {
TraceEvent(SevError, "GetMachineMemInfo").GetLastError();
throw platform_error();
}
status = sysctlbyname("vm.stats.vm.v_free_count", &free_count, &uint_size, nullptr, 0);
if (status < 0) {
TraceEvent(SevError, "GetMachineMemInfo").GetLastError();
throw platform_error();
}
status = sysctlbyname("vm.stats.vm.v_active_count", &active_count, &uint_size, nullptr, 0);
if (status < 0) {
TraceEvent(SevError, "GetMachineMemInfo").GetLastError();
throw platform_error();
}
status = sysctlbyname("vm.stats.vm.v_inactive_count", &inactive_count, &uint_size, nullptr, 0);
if (status < 0) {
TraceEvent(SevError, "GetMachineMemInfo").GetLastError();
throw platform_error();
}
status = sysctlbyname("vm.stats.vm.v_wire_count", &wire_count, &uint_size, nullptr, 0);
if (status < 0) {
TraceEvent(SevError, "GetMachineMemInfo").GetLastError();
throw platform_error();
}
memInfo.total = (int64_t)((free_count + active_count + inactive_count + wire_count) * (u_int64_t)(page_size));
memInfo.available = (int64_t)(free_count * (u_int64_t)(page_size));
memInfo.committed = memInfo.total - memInfo.available;
#elif defined(_WIN32)
MEMORYSTATUSEX mem_status;
mem_status.dwLength = sizeof(mem_status);
if (!GlobalMemoryStatusEx(&mem_status)) {
TraceEvent(SevError, "WindowsGetMemStatus").GetLastError();
throw platform_error();
}
PERFORMACE_INFORMATION perf;
if (!GetPerformanceInfo(&perf, sizeof(perf))) {
TraceEvent(SevError, "WindowsGetMemPerformanceInfo").GetLastError();
throw platform_error();
}
memInfo.total = mem_status.ullTotalPhys;
memInfo.committed = perf.PageSize * perf.CommitTotal;
memInfo.available = memInfo.total - memInfo.committed;
#elif defined(__APPLE__)
vm_statistics_data_t vm_stat;
vm_size_t pagesize;
mach_msg_type_number_t host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t);
if (KERN_SUCCESS != host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&vm_stat, &host_size)) {
TraceEvent(SevError, "GetMachineMemInfo").GetLastError();
throw platform_error();
}
host_page_size(mach_host_self(), &pagesize);
memInfo.total =
pagesize * (vm_stat.free_count + vm_stat.active_count + vm_stat.inactive_count + vm_stat.wire_count);
memInfo.available = pagesize * vm_stat.free_count;
memInfo.committed = memInfo.total - memInfo.available;
#else
#warning getMachineRAMInfo unimplemented on this platform
#endif
}
Error systemErrorCodeToError() {
#if defined(_WIN32)
if (GetLastError() == ERROR_IO_DEVICE) {
return io_error();
}
#elif defined(__unixish__)
if (errno == EIO || errno == EROFS) {
return io_error();
}
#else
#error Port me!
#endif
return platform_error();
}
void getDiskBytes(std::string const& directory, int64_t& free, int64_t& total) {
INJECT_FAULT(platform_error, "getDiskBytes"); // Get disk bytes failed
#if defined(__unixish__)
#if defined(__linux__) || defined(__FreeBSD__)
struct statvfs buf;
if (statvfs(directory.c_str(), &buf)) {
Error e = systemErrorCodeToError();
TraceEvent(SevError, "GetDiskBytesStatvfsError").error(e).detail("Directory", directory).GetLastError();
throw e;
}
uint64_t blockSize = buf.f_frsize;
#elif defined(__APPLE__)
struct statfs buf;
if (statfs(directory.c_str(), &buf)) {
Error e = systemErrorCodeToError();
TraceEvent(SevError, "GetDiskBytesStatfsError").error(e).detail("Directory", directory).GetLastError();
throw e;
}
uint64_t blockSize = buf.f_bsize;
#else
#error Unknown unix
#endif
free = std::min((uint64_t)std::numeric_limits<int64_t>::max(), buf.f_bavail * blockSize);
// f_blocks is the total fs space but (f_bfree - f_bavail) is space only available to privileged users
// so that amount will be subtracted from the reported total since FDB can't use it.
total = std::min((uint64_t)std::numeric_limits<int64_t>::max(),
(buf.f_blocks - (buf.f_bfree - buf.f_bavail)) * blockSize);
#elif defined(_WIN32)
std::string fullPath = abspath(directory);
//TraceEvent("FullDiskPath").detail("Path", fullPath).detail("Disk", (char)toupper(fullPath[0]));
ULARGE_INTEGER freeSpace;
ULARGE_INTEGER totalSpace;
ULARGE_INTEGER totalFreeSpace;
if (!GetDiskFreeSpaceEx(fullPath.c_str(), &freeSpace, &totalSpace, &totalFreeSpace)) {
Error e = systemErrorCodeToError();
TraceEvent(SevError, "DiskFreeError").error(e).detail("Path", fullPath).GetLastError();
throw e;
}
total = std::min((uint64_t)std::numeric_limits<int64_t>::max(), totalSpace.QuadPart);
free = std::min((uint64_t)std::numeric_limits<int64_t>::max(), freeSpace.QuadPart);
#else
#warning getDiskBytes unimplemented on this platform
free = 1LL << 50;
total = 1LL << 50;
#endif
}
#ifdef __unixish__
const char* getInterfaceName(const IPAddress& _ip) {
INJECT_FAULT(platform_error, "getInterfaceName"); // Get interface name failed
static char iname[20];
struct ifaddrs* interfaces = nullptr;
const char* ifa_name = nullptr;
if (getifaddrs(&interfaces)) {
TraceEvent(SevWarnAlways, "GetInterfaceAddrs").GetLastError();
throw platform_error();
}
for (struct ifaddrs* iter = interfaces; iter; iter = iter->ifa_next) {
if (!iter->ifa_addr)
continue;
if (iter->ifa_addr->sa_family == AF_INET && _ip.isV4()) {
uint32_t ip = ntohl((reinterpret_cast<struct sockaddr_in*>(iter->ifa_addr))->sin_addr.s_addr);
if (ip == _ip.toV4()) {
ifa_name = iter->ifa_name;
break;
}
} else if (iter->ifa_addr->sa_family == AF_INET6 && _ip.isV6()) {
struct sockaddr_in6* ifa_addr = reinterpret_cast<struct sockaddr_in6*>(iter->ifa_addr);
if (memcmp(_ip.toV6().data(), &ifa_addr->sin6_addr, 16) == 0) {
ifa_name = iter->ifa_name;
break;
}
}
}
if (ifa_name) {
strncpy(iname, ifa_name, 19);
iname[19] = 0;
}
freeifaddrs(interfaces);
if (ifa_name)
return iname;
else
return nullptr;
}
#endif
#if defined(__linux__)
void getNetworkTraffic(const IPAddress& ip,
uint64_t& bytesSent,
uint64_t& bytesReceived,
uint64_t& outSegs,
uint64_t& retransSegs) {
INJECT_FAULT(
platform_error,
"getNetworkTraffic"); // getNetworkTraffic: Even though this function doesn't throw errors, the equivalents for
// other platforms do, and since all of our simulation testing is on Linux...
const char* ifa_name = nullptr;
try {
ifa_name = getInterfaceName(ip);
} catch (Error& e) {
if (e.code() != error_code_platform_error) {
throw;
}
}
if (!ifa_name)
return;
std::ifstream dev_stream("/proc/net/dev", std::ifstream::in);
dev_stream.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
dev_stream.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::string iface;
std::string ignore;
uint64_t bytesSentSum = 0;
uint64_t bytesReceivedSum = 0;
while (dev_stream.good()) {
dev_stream >> iface;
if (dev_stream.eof())
break;
if (!strncmp(iface.c_str(), ifa_name, strlen(ifa_name))) {
uint64_t sent = 0, received = 0;
dev_stream >> received;
for (int i = 0; i < 7; i++)
dev_stream >> ignore;
dev_stream >> sent;
bytesSentSum += sent;
bytesReceivedSum += received;
dev_stream.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
if (bytesSentSum > 0) {
bytesSent = bytesSentSum;
}
if (bytesReceivedSum > 0) {
bytesReceived = bytesReceivedSum;
}
std::ifstream snmp_stream("/proc/net/snmp", std::ifstream::in);
std::string label;
while (snmp_stream.good()) {
snmp_stream >> label;
snmp_stream.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
if (label == "Tcp:")
break;
}
/* Ignore the first 11 columns of the Tcp line */
for (int i = 0; i < 11; i++)
snmp_stream >> ignore;
snmp_stream >> outSegs;
snmp_stream >> retransSegs;
}
void getMachineLoad(uint64_t& idleTime, uint64_t& totalTime, bool logDetails) {
INJECT_FAULT(platform_error,
"getMachineLoad"); // getMachineLoad: Even though this function doesn't throw errors, the equivalents
// for other platforms do, and since all of our simulation testing is on Linux...
std::ifstream stat_stream("/proc/stat", std::ifstream::in);
std::string ignore;
stat_stream >> ignore;
uint64_t t_user, t_nice, t_system, t_idle, t_iowait, t_irq, t_softirq, t_steal, t_guest;
stat_stream >> t_user >> t_nice >> t_system >> t_idle >> t_iowait >> t_irq >> t_softirq >> t_steal >> t_guest;
totalTime = t_user + t_nice + t_system + t_idle + t_iowait + t_irq + t_softirq + t_steal + t_guest;
idleTime = t_idle + t_iowait;
if (!DEBUG_DETERMINISM && logDetails && !g_network->isSimulated())
TraceEvent("MachineLoadDetail")
.detail("User", t_user)
.detail("Nice", t_nice)
.detail("System", t_system)
.detail("Idle", t_idle)
.detail("IOWait", t_iowait)
.detail("IRQ", t_irq)
.detail("SoftIRQ", t_softirq)
.detail("Steal", t_steal)
.detail("Guest", t_guest);
}
void getDiskStatistics(std::string const& directory,
uint64_t& currentIOs,
uint64_t& readMilliSecs,
uint64_t& writeMilliSecs,
uint64_t& IOMilliSecs,
uint64_t& reads,
uint64_t& writes,
uint64_t& writeSectors,
uint64_t& readSectors) {
INJECT_FAULT(platform_error, "getDiskStatistics"); // Getting disks statistics failed
currentIOs = 0;
struct stat buf;
if (stat(directory.c_str(), &buf)) {
TraceEvent(SevError, "GetDiskStatisticsStatError").detail("Directory", directory).GetLastError();
throw platform_error();
}
std::ifstream proc_stream("/proc/diskstats", std::ifstream::in);
while (proc_stream.good()) {
std::string line;
getline(proc_stream, line);
std::istringstream disk_stream(line, std::istringstream::in);
unsigned int majorId;
unsigned int minorId;
disk_stream >> majorId;
disk_stream >> minorId;
if (majorId == (unsigned int)gnu_dev_major(buf.st_dev) && minorId == (unsigned int)gnu_dev_minor(buf.st_dev)) {
std::string ignore;
uint64_t rd_ios; /* # of reads completed */
// This is the total number of reads completed successfully.
uint64_t rd_merges; /* # of reads merged */
// Reads and writes which are adjacent to each other may be merged for
// efficiency. Thus two 4K reads may become one 8K read before it is
// ultimately handed to the disk, and so it will be counted (and queued)
// as only one I/O. This field lets you know how often this was done.
uint64_t rd_sectors; /*# of sectors read */
// This is the total number of sectors read successfully.
uint64_t rd_ticks; /* # of milliseconds spent reading */
// This is the total number of milliseconds spent by all reads (as
// measured from __make_request() to end_that_request_last()).
uint64_t wr_ios; /* # of writes completed */
// This is the total number of writes completed successfully.
uint64_t wr_merges; /* # of writes merged */
// Reads and writes which are adjacent to each other may be merged for
// efficiency. Thus two 4K reads may become one 8K read before it is
// ultimately handed to the disk, and so it will be counted (and queued)
// as only one I/O. This field lets you know how often this was done.
uint64_t wr_sectors; /* # of sectors written */
// This is the total number of sectors written successfully.
uint64_t wr_ticks; /* # of milliseconds spent writing */
// This is the total number of milliseconds spent by all writes (as
// measured from __make_request() to end_that_request_last()).
uint64_t cur_ios; /* # of I/Os currently in progress */
// The only field that should go to zero. Incremented as requests are
// given to appropriate struct request_queue and decremented as they finish.
uint64_t ticks; /* # of milliseconds spent doing I/Os */
// This field increases so long as field 9 is nonzero.
uint64_t aveq; /* weighted # of milliseconds spent doing I/Os */
// This field is incremented at each I/O start, I/O completion, I/O
// merge, or read of these stats by the number of I/Os in progress
// (field 9) times the number of milliseconds spent doing I/O since the
// last update of this field. This can provide an easy measure of both
// I/O completion time and the backlog that may be accumulating.
disk_stream >> ignore;
disk_stream >> rd_ios;
disk_stream >> rd_merges;
disk_stream >> rd_sectors;
disk_stream >> rd_ticks;
disk_stream >> wr_ios;
disk_stream >> wr_merges;
disk_stream >> wr_sectors;
disk_stream >> wr_ticks;
disk_stream >> cur_ios;
disk_stream >> ticks;
disk_stream >> aveq;
currentIOs = cur_ios;
readMilliSecs = rd_ticks;
writeMilliSecs = wr_ticks;
IOMilliSecs = ticks;
reads = rd_ios;
writes = wr_ios;
writeSectors = wr_sectors;
readSectors = rd_sectors;
//TraceEvent("DiskMetricsRaw").detail("Input", line).detail("Ignore", ignore).detail("RdIos", rd_ios)
// .detail("RdMerges", rd_merges).detail("RdSectors", rd_sectors).detail("RdTicks",
// rd_ticks).detail("WrIos", wr_ios).detail("WrMerges", wr_merges) .detail("WrSectors",
// wr_sectors).detail("WrTicks", wr_ticks).detail("CurIos", cur_ios).detail("Ticks", ticks).detail("Aveq",
// aveq) .detail("CurrentIOs", currentIOs).detail("BusyTicks", busyTicks).detail("Reads",
// reads).detail("Writes", writes).detail("WriteSectors", writeSectors)
// .detail("ReadSectors", readSectors);
return;
} else
disk_stream.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
if (!g_network->isSimulated())
TraceEvent(SevWarn, "GetDiskStatisticsDeviceNotFound").detail("Directory", directory);
}
dev_t getDeviceId(std::string path) {
struct stat statInfo;
while (true) {
int returnValue = stat(path.c_str(), &statInfo);
if (!returnValue)
break;
if (errno == ENOENT) {
path = parentDirectory(path);
} else {
TraceEvent(SevError, "GetDeviceIdError").detail("Path", path).GetLastError();
throw platform_error();
}
}
return statInfo.st_dev;
}
#endif
#if defined(__FreeBSD__)
void getNetworkTraffic(const IPAddress ip,
uint64_t& bytesSent,
uint64_t& bytesReceived,
uint64_t& outSegs,
uint64_t& retransSegs) {
INJECT_FAULT(platform_error, "getNetworkTraffic"); // Get Network traffic failed
const char* ifa_name = nullptr;
try {
ifa_name = getInterfaceName(ip);
} catch (Error& e) {
if (e.code() != error_code_platform_error) {
throw;
}
}
if (!ifa_name)
return;
struct ifaddrs* interfaces = nullptr;
if (getifaddrs(&interfaces)) {
TraceEvent(SevError, "GetNetworkTrafficError").GetLastError();
throw platform_error();
}
int if_count, i;
int mib[6];
size_t ifmiblen;
struct ifmibdata ifmd;
mib[0] = CTL_NET;
mib[1] = PF_LINK;
mib[2] = NETLINK_GENERIC;