-
Notifications
You must be signed in to change notification settings - Fork 19
/
vmtop.py
executable file
·1666 lines (1494 loc) · 58.5 KB
/
vmtop.py
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
#!/usr/bin/python3
# TODO:
# - system-wide metrics
# - /sys/devices/system/node/nodeX/numastat
# - can we get guest throttling data (for live migration) ?
# - user-controlled list metrics to show, the list is getting large
# - vmexit rate + reasons
# - arbitrary groups of processes metrics (kernel threads,
# middleware, etc)
# - parallel scrape
# - filter by name, not just PID
import subprocess
import operator
import threading
import time
import signal
import ctypes
import os
import sys
import argparse
import shutil
import socket
from datetime import datetime
# optional dependencies
# bcc for vmexit
import_failed_bcc = False
try:
from bcc import BPF
except ImportError:
import_failed_bcc = True
# prometheus
import_failed_prometheus = False
try:
from prometheus_client import Gauge
from prometheus_client import start_http_server
except ImportError:
import_failed_prometheus = True
# daemon mode
import_failed_daemon = False
try:
import daemon
except ImportError:
import_failed_daemon = True
stop = False
def read_str(filename):
with open(filename, "r") as fd:
return fd.read().strip()
def read_int(filename):
return int(read_str(filename))
def mixrange(s):
r = []
if not s:
return r
if s == "\n":
return r
for i in s.split(","):
if "-" not in i:
r.append(int(i))
else:
l, h = map(int, i.split("-"))
r += range(l, h + 1)
return r
class QemuThread:
def __init__(self, vm_pid, cgroup, thread_pid, machine, vhost=False):
self.vm_pid = vm_pid
self.machine = machine
self.thread_pid = thread_pid
self.last_stealtime = None
self.last_cputime = None
self.last_scrape_ts = None
self.nodes = None
self.vhost = vhost
self.cgroup = cgroup
self.pc_steal = 0.0
self.pc_util = 0.0
self.diff_steal = 0
self.diff_util = 0
self.diff_ts = 0
self.warned = False
self.get_thread_name()
self.get_thread_cpuset()
self.get_schedstats()
def get_thread_name(self):
if self.vhost is True:
fpath = "/proc/%s/comm" % (self.thread_pid)
else:
fpath = "/proc/%s/task/%s/comm" % (self.vm_pid, self.thread_pid)
self.thread_name = read_str(fpath)
def get_prctl_cpus(self):
status = read_str(
"/proc/%s/task/%s/status" % (self.vm_pid, self.thread_pid)
).split("\n")
for l in status:
k = l.split(":")[0]
v = l.split(":")[1]
if k == "Cpus_allowed_list":
cpus = mixrange(v.strip())
self.nodes = self.machine.get_prctl_nodes(cpus)
def get_thread_cpuset(self):
try:
if self.vhost is not True:
fpath = "/proc/%s/task/%s/cpuset" % (self.vm_pid, self.thread_pid)
with open(fpath, "r") as f:
line = f.read().strip()
# if no cpuset, try to read the Cpus_allowed_list
if line == "/":
return self.get_prctl_cpus()
# Cgroup1
if self.cgroup != 2:
self.cpuset = line
else:
# Cgroup2
# If cpuset controller is not enabled, then it may just
# return "/machine.slice" for the /proc/<pid>/cpuset
if line != "/machine.slice":
self.cpuset = line
else:
print("Please check if cpuset controller is enabled")
sys.exit(1)
except:
# Teardown
self.nodes = []
return
self.nodes = self.machine.get_nodes(self.cpuset)
if len(self.nodes) != 1:
# kvm-pit is not pinned, but also mostly idle, no need to
# warn here
if "kvm-pit" in self.thread_name:
return
if self.warned is True:
return
print(
"Warning: thread %d from VM %d belongs to multiple nodes, "
"node accounting may be inaccurate" % (self.thread_pid, self.vm_pid)
)
self.warned = True
def get_schedstats(self):
self.last_scrape_ts = time.time() * 1000000000
if self.vhost is True:
fpath = "/proc/%s/schedstat" % (self.thread_pid)
else:
fpath = "/proc/%s/task/%s/schedstat" % (self.vm_pid, self.thread_pid)
try:
stats = read_str(fpath).split(" ")
except FileNotFoundError:
# On VM teardown return 0
self.last_cputime = 0
self.last_stealtime = 0
return -1
self.last_cputime = int(stats[0])
self.last_stealtime = int(stats[1])
return 0
def __repr__(self):
return "%s (%s), util: %0.02f %%, steal: %0.02f %%" % (
self.thread_name,
self.thread_pid,
self.pc_util,
self.pc_steal,
)
def refresh_stats(self):
prev_steal_time = self.last_stealtime
prev_cpu_time = self.last_cputime
prev_scrape_ts = self.last_scrape_ts
ret = self.get_schedstats()
# if a thread vanished, make it 0 and we will remove it
# in the VM refresh_stat function
if ret == -1:
return ret
else:
self.diff_ts = self.last_scrape_ts - prev_scrape_ts
self.diff_steal = self.last_stealtime - prev_steal_time
self.diff_util = self.last_cputime - prev_cpu_time
if self.diff_ts < 0 or self.diff_steal < 0 or self.diff_util < 0:
print(
f"Error: negative difference in thread {self.thread_pid}, "
f"VM {self.vm_pid}\n"
f"self.diff_ts: {self.diff_ts}\n"
f"self.last_scrape_ts: {self.last_scrape_ts}\n"
f"prev_scrape_ts: {prev_scrape_ts}\n"
f"self.diff_steal: {self.diff_steal}\n"
f"self.last_scrape_steal: {self.last_stealtime}\n"
f"prev_scrape_steal: {prev_steal_time}\n"
f"self.diff_util: {self.diff_util}\n"
f"self.last_scrape_util: {self.last_cputime}\n"
f"prev_scrape_util: {prev_cpu_time}"
)
self.pc_util = self.diff_util / self.diff_ts * 100
self.pc_steal = self.diff_steal / self.diff_ts * 100
return ret
class NIC:
def __init__(self, vm, name):
self.vm = vm
self.name = name
self.last_scrape_ts = None
self.last_rx = None
self.last_tx = None
self.last_rx_drop = None
self.last_tx_drop = None
self.tx_rate = None
self.rx_rate = None
self.tx_rate_dropped = None
self.rx_rate_dropped = None
self.get_stats()
def get_stats(self):
self.last_scrape_ts = time.time()
# Flipped rx/tx to reflect the VM point of view
try:
self.last_rx = read_int(
f"/sys/devices/virtual/net/{self.name}/statistics/tx_bytes"
)
self.last_tx = read_int(
f"/sys/devices/virtual/net/{self.name}/statistics/rx_bytes"
)
self.last_rx_dropped = read_int(
f"/sys/devices/virtual/net/{self.name}/statistics/tx_dropped"
)
self.last_tx_dropped = read_int(
f"/sys/devices/virtual/net/{self.name}/statistics/rx_dropped"
)
except:
# VM Teardown
self.last_rx = 0
self.last_tx = 0
self.last_rx_dropped = 0
self.last_tx_dropped = 0
return
def refresh_stats(self):
prev_scrape_ts = self.last_scrape_ts
prev_rx = self.last_rx
prev_tx = self.last_tx
prev_rx_dropped = self.last_rx_dropped
prev_tx_dropped = self.last_tx_dropped
self.get_stats()
diff_sec = self.last_scrape_ts - prev_scrape_ts
mb = 1024.0 * 1024.0
self.rx_rate = ((self.last_rx - prev_rx) * 8) / diff_sec / mb
self.tx_rate = ((self.last_tx - prev_tx) * 8) / diff_sec / mb
self.rx_rate_dropped = (self.last_rx_dropped - prev_rx_dropped) / diff_sec
self.tx_rate_dropped = (self.last_tx_dropped - prev_tx_dropped) / diff_sec
class VM:
def __init__(self, args, vm_pid, machine):
self.args = args
self.vm_pid = vm_pid
self.machine = machine
self.name = None
self.csv = None
# If the memory is on a different primary node than the vcpus
self.warned_vcpu_mem_split = False
# If the vcpus of that VM are running on different nodes
self.warned_vcpu_split = False
self.mem_allocated = 0
self.clear_stats()
# We assume all the allocated memory was allocated to fit on
# only one node, we still track the real usage on each node.
# changes protected by machine.nodes_lock.
self.mem_primary_node = None
# If a VM changed node, store it here and update with
# machine.nodes_lock is held by the vm allocation thread
self.new_mem_primary_node = None
# Same thing with vcpus, we try to find the node where most
# vcpus use and set it as default. If the VM is unpinned or
# pinned to multiple nodes, we use mem_primary_node as an
# assumption (and warn).
# VMs are accounted for in vcpu_primary_node because this tool
# first metric is CPU usage.
self.vcpu_primary_node = None
self.new_vcpu_primary_node = None
self.mem_used_per_node = {}
self.total_vcpu_count = 0
self.total_vcpu_count_per_node = {}
self.vcpu_threads = {}
self.emulator_threads = {}
self.vhost_threads = {}
self.nics = {}
self.last_io_scrape_ts = None
self.last_io_read_bytes = None
self.last_io_write_bytes = None
self.last_vmexit_count = 0
self.last_vmexit_diff = 0
self.get_vm_info()
if self.args.csv is not None and self.args.vm is True:
self.open_vm_csv()
self.get_threads()
self.get_node_memory()
self.refresh_vcpu_primary_node()
self.check_vcpu_mem_split()
if self.args.no_nic is not True:
self.get_nic_info()
self.refresh_io_stats()
@property
def nr_vcpus(self):
return len(self.vcpu_threads.keys())
def set_vcpu_primary_node(self, new_node):
if new_node is None:
return
if self.vcpu_primary_node == new_node:
return
if self.vcpu_primary_node is not None:
# We cannot update the primary node directly, because of
# concurrency between the 2 threads, so if the node needs
# to be updated, set the new_ value and wait for the
# alloc thread to update with the lock held.
self.new_vcpu_primary_node = new_node
else:
self.vcpu_primary_node = new_node
def refresh_vcpu_primary_node(self):
tmp_primary = None
for vcpu in self.vcpu_threads.values():
# if any vcpu is floating to more than one node or we didn't
# manage to find the node, assign it to the primary memory node
# we already warned about this.
if len(vcpu.nodes) != 1:
self.set_vcpu_primary_node(self.mem_primary_node)
break
if tmp_primary is None:
tmp_primary = vcpu.nodes[0]
elif vcpu.nodes[0] != tmp_primary:
self.set_vcpu_primary_node(self.mem_primary_node)
if self.warned_vcpu_split is False:
print(
f"Warning: VM {self.name} has vcpus pinned to "
f"different nodes, accounting will not be accurate"
)
self.warned_vcpu_split = True
break
self.set_vcpu_primary_node(tmp_primary)
if self.vcpu_primary_node is None:
print(f"Failed to set the vcpu primary node for VM {self.name}")
def refresh_vcpu_node(self):
for vcpu in self.vcpu_threads.values():
vcpu.get_thread_cpuset()
self.refresh_vcpu_primary_node()
def check_vcpu_mem_split(self):
if self.warned_vcpu_mem_split is True:
return
for vcpu in self.vcpu_threads.values():
if len(vcpu.nodes) == 1 and vcpu.nodes[0] != self.mem_primary_node:
print(
f"Warning: VCPU thread {vcpu.thread_pid} from VM "
f"{self.name} is not pinned on the same node as its "
f"memory"
)
self.warned_vcpu_mem_split = True
def get_exit_count(self):
if self.args.vmexit is False:
return
try:
c = self.machine.bpf["exitcount"][ctypes.c_uint(self.vm_pid)].value
self.last_vmexit_diff = c - self.last_vmexit_count
self.last_vmexit_count = c
except:
pass
def __str__(self):
if self.args.vcpu:
vm = (
" - %s (%s), vcpu util: %0.02f%%, vcpu steal: %0.02f%%, "
"vhost util: %0.02f%%, vhost steal: %0.02f%%"
"emulators util: %0.02f%%, emulators steal: %0.02f%%"
% (
self.name,
self.vm_pid,
self.vcpu_sum_pc_util,
self.vcpu_sum_pc_steal,
self.vhost_sum_pc_util,
self.vhost_sum_pc_steal,
self.emulators_sum_pc_util,
self.emulators_sum_pc_steal,
)
)
vcpu_util = ""
for v in self.vcpu_threads.values():
vcpu_util = "%s\n - %s" % (vcpu_util, v)
emulators_util = ""
if self.args.emulators:
for v in self.emulator_threads.values():
emulators_util = "%s\n - %s" % (emulators_util, v)
return "%s%s%s" % (vm, vcpu_util, emulators_util)
else:
metrics = [self.name, str(self.vm_pid)]
for i in self.args.display_metrics:
if i == "vcpu_sum_pc_util":
metrics.append("%0.02f" % self.vcpu_sum_pc_util)
elif i == "vcpu_sum_pc_steal":
metrics.append("%0.02f" % self.vcpu_sum_pc_steal)
elif i == "emulators_sum_pc_util":
metrics.append("%0.02f" % self.emulators_sum_pc_util)
elif i == "emulators_sum_pc_steal":
metrics.append("%0.02f" % self.emulators_sum_pc_steal)
elif i == "vhost_sum_pc_util":
metrics.append("%0.02f" % self.vhost_sum_pc_util)
elif i == "vhost_sum_pc_steal":
metrics.append("%0.02f" % self.vhost_sum_pc_steal)
elif i == "mb_read":
metrics.append("%0.02f" % self.mb_read)
elif i == "mb_write":
metrics.append("%0.02f" % self.mb_write)
elif i == "rx_rate":
metrics.append("%0.02f" % self.rx_rate)
elif i == "tx_rate":
metrics.append("%0.02f" % self.tx_rate)
elif i == "rx_rate_dropped":
metrics.append("%0.02f" % self.rx_rate_dropped)
elif i == "tx_rate_dropped":
metrics.append("%0.02f" % self.tx_rate_dropped)
elif i == "last_vmexit_diff":
metrics.append("%d" % self.last_vmexit_diff)
return self.args.vm_format.format(*metrics)
def open_vm_csv(self):
fname = os.path.join(self.args.csv, "%s.csv" % self.name)
self.csv = open(fname, "w")
self.csv.write(
"timestamp,pid,name,nr_vcpus,mem_node,vcpu_node,vcpu_util,vcpu_steal,emulators_util,"
"emulators_steal,vhost_util,vhost_steal,disk_read,disk_write,rx,tx,"
"rx_dropped,tx_dropped,vmexit_count\n"
)
def output_vm_csv(self, timestamp):
# Output the CSV file
# we use abs() because Python manages to write -0.00 once in a
# while...
self.csv.write(
f"{datetime.fromtimestamp(timestamp)},"
f"{self.vm_pid},{self.name},"
f"{self.nr_vcpus},"
f"{self.mem_primary_node.id},"
f"{self.vcpu_primary_node.id},"
f"{'%0.02f' % (abs(self.vcpu_sum_pc_util))},"
f"{'%0.02f' % (abs(self.vcpu_sum_pc_steal))},"
f"{'%0.02f' % (abs(self.emulators_sum_pc_util))},"
f"{'%0.02f' % (abs(self.emulators_sum_pc_steal))},"
f"{'%0.02f' % (abs(self.vhost_sum_pc_util))},"
f"{'%0.02f' % (abs(self.vhost_sum_pc_steal))},"
f"{'%0.02f' % (abs(self.mb_read))},"
f"{'%0.02f' % (abs(self.mb_write))},"
f"{'%0.02f' % (abs(self.rx_rate))},"
f"{'%0.02f' % (abs(self.tx_rate))},"
f"{'%0.02f' % (abs(self.rx_rate_dropped))},"
f"{'%0.02f' % (abs(self.tx_rate_dropped))},"
f"{'%d' % (self.last_vmexit_diff)}\n"
)
self.csv.flush()
def get_nic_info(self):
for fd in os.listdir(f"/proc/{self.vm_pid}/fd/"):
lname = f"/proc/{self.vm_pid}/fd/{fd}"
try:
link = os.readlink(lname)
except OSError:
continue
if link == "/dev/net/tun":
try:
with open(f"/proc/{self.vm_pid}/fdinfo/{fd}", "r") as _f:
fdinfo = _f.read().split("\n")
except FileNotFoundError:
# Ignore fd that vanished
continue
for l in fdinfo:
l = l.split()
if len(l) == 2 and l[0] == "iff:":
self.nics[l[1]] = NIC(self, l[1])
def is_vcpu(self, thread, comm):
if "CPU" in comm:
return True
def get_threads(self):
for tid in os.listdir("/proc/%s/task/" % self.vm_pid):
fname = "/proc/%s/task/%s/comm" % (self.vm_pid, tid)
try:
with open(fname, "r") as _f:
comm = _f.read()
tid = int(tid)
thread = QemuThread(self.vm_pid, self.machine.cgroup, tid, self.machine)
except FileNotFoundError:
# Ignore threads that disappear for now (temporary workers)
continue
if self.is_vcpu(thread, comm):
self.vcpu_threads[tid] = thread
else:
self.emulator_threads[tid] = thread
# Find vhost threads
cmd = ["pgrep", str(self.vm_pid)]
pids = (
subprocess.check_output(cmd, shell=False)
.strip()
.decode("utf-8")
.split("\n")
)
for p in pids:
tid = int(p)
thread = QemuThread(
self.vm_pid, self.machine.cgroup, tid, self.machine, vhost=True
)
self.vhost_threads[tid] = thread
def get_vm_info(self):
with open("/proc/%s/cmdline" % self.vm_pid, mode="r") as fh:
cmdline = fh.read().split("\0")
for i in range(len(cmdline)):
if cmdline[i].startswith("guest="):
self.name = cmdline[i].split("=")[1].split(",")[0]
elif cmdline[i].startswith("-name"):
self.name = cmdline[i + 1]
elif cmdline[i] == "-m":
self.mem_allocated = int(cmdline[i + 1])
elif cmdline[i] == "-smp":
self.total_vcpu_count = int(cmdline[i + 1].split(",")[0])
if self.name is None:
print("Failed to parse guest name")
self.name = "unknown"
def refresh_io_stats(self):
self.last_io_scrape_ts = time.time()
try:
with open("/proc/%s/io" % self.vm_pid, "r") as f:
stats = f.read().split("\n")
except FileNotFoundError:
# On VM teardown return 0
self.last_io_read_bytes = 0
self.last_io_write_bytes = 0
return
for l in stats:
l = l.split(" ")
if l[0] == "read_bytes:":
self.last_io_read_bytes = int(l[1])
if l[0] == "write_bytes:":
self.last_io_write_bytes = int(l[1])
def get_node_memory(self):
path = shutil.which("numastat")
if path is None:
print("no executable found for numastat")
return
cmd = ["numastat", "-p", str(self.vm_pid)]
try:
usage = (
subprocess.check_output(cmd, shell=False)
.decode("utf-8")
.split("\n")[-2]
.split()[1:-1]
)
except subprocess.CalledProcessError:
# ctrl-c
return
maxnode = None
maxmem = 0
for node_id in range(len(usage)):
try:
mem = float(usage[node_id])
except ValueError:
# Teardown
return
self.mem_used_per_node[node_id] = mem
if maxnode is None or mem > maxmem:
maxnode = node_id
maxmem = mem
if self.mem_primary_node is None:
self.mem_primary_node = self.machine.nodes[maxnode]
elif self.mem_primary_node != self.machine.nodes[maxnode]:
self.new_mem_primary_node = self.machine.nodes[maxnode]
def clear_stats(self):
self.vcpu_sum_pc_util = 0
self.vcpu_sum_pc_steal = 0
self.vhost_sum_pc_util = 0
self.vhost_sum_pc_steal = 0
self.emulators_sum_pc_util = 0
self.emulators_sum_pc_steal = 0
def refresh_stats(self):
self.clear_stats()
# sum of all vcpu stats
for vcpu in self.vcpu_threads.values():
vcpu.refresh_stats()
self.vcpu_sum_pc_util += vcpu.pc_util
self.vcpu_sum_pc_steal += vcpu.pc_steal
# vhost
for vhost in self.vhost_threads.values():
vhost.refresh_stats()
self.vhost_sum_pc_util += vhost.pc_util
self.vhost_sum_pc_steal += vhost.pc_steal
# emulators
to_remove = []
for tid, emulator in self.emulator_threads.items():
ret = emulator.refresh_stats()
if ret == -1:
to_remove.append(tid)
continue
self.emulators_sum_pc_util += emulator.pc_util
self.emulators_sum_pc_steal += emulator.pc_steal
# workers are added/removed on demand, so we can't keep track of all
for tid in to_remove:
del self.emulator_threads[tid]
# disk
prev_io_scrape_ts = self.last_io_scrape_ts
prev_io_read_bytes = self.last_io_read_bytes
prev_io_write_bytes = self.last_io_write_bytes
self.refresh_io_stats()
diff_sec = self.last_io_scrape_ts - prev_io_scrape_ts
mb = 1024.0 * 1024.0
self.mb_read = (self.last_io_read_bytes - prev_io_read_bytes) / diff_sec / mb
self.mb_write = (self.last_io_write_bytes - prev_io_write_bytes) / diff_sec / mb
self.tx_rate = 0
self.rx_rate = 0
self.tx_rate_dropped = 0
self.rx_rate_dropped = 0
if not self.args.no_nic:
for n in self.nics.values():
n.refresh_stats()
self.tx_rate += n.tx_rate
self.rx_rate += n.rx_rate
self.tx_rate_dropped += n.tx_rate_dropped
self.rx_rate_dropped += n.rx_rate_dropped
# copy to node stats
self.vcpu_primary_node.node_vcpu_sum_pc_util += self.vcpu_sum_pc_util
self.vcpu_primary_node.node_vcpu_sum_pc_steal += self.vcpu_sum_pc_steal
self.vcpu_primary_node.node_vhost_sum_pc_util += self.vhost_sum_pc_util
self.vcpu_primary_node.node_vhost_sum_pc_steal += self.vhost_sum_pc_steal
self.vcpu_primary_node.node_emulators_sum_pc_util += self.emulators_sum_pc_util
self.vcpu_primary_node.node_emulators_sum_pc_steal += (
self.emulators_sum_pc_steal
)
self.get_exit_count()
class Node:
def __init__(self, _id, args):
self.id = _id
self.args = args
self.hwthread_list = Node.node_hwthreads(_id)
# Approximation, VMs could be split between nodes, we use the node
# where most of the memory is allocated to decide here
self.node_vms = {}
# After the initial scan, the resource accounting is owned by the
# refresh_vm_allocation thread
# Approximation, assumes all the allocated memory is not split
self.vm_mem_allocated = 0
self.vm_mem_used = 0
self.node_vcpu_threads = 0
self.clear_stats()
def clear_stats(self):
# Owned by the main loop
self.node_vcpu_sum_pc_util = 0
self.node_vcpu_sum_pc_steal = 0
self.node_vhost_sum_pc_util = 0
self.node_vhost_sum_pc_steal = 0
self.node_emulators_sum_pc_util = 0
self.node_emulators_sum_pc_steal = 0
def refresh_vm_allocation(self):
tmp_vm_mem_allocated = 0
for vm in self.node_vms.values():
vm.get_node_memory()
vm.refresh_vcpu_node()
tmp_vm_mem_allocated += vm.mem_allocated
self.vm_mem_allocated = tmp_vm_mem_allocated
def print_node_initial_count(self):
if self.args.csv is not None:
return
return "%s VMs (%s vcpus, %0.02f GB mem allocated, " "%0.02f GB mem used)" % (
self.nr_vms,
self.node_vcpu_threads,
self.vm_mem_allocated / 1024,
self.vm_mem_used / 1024,
)
def open_csv_file(self):
fname = os.path.join(self.args.csv, "node%d.csv" % self.id)
print("Writing node %s data in %s" % (self.id, fname))
self.node_csv = open(fname, "w")
self.node_csv.write(
"timestamp,id,nr_vms,nr_vcpus,vm_mem_allocated,"
"vm_mem_used,vcpu_util,vcpu_steal,emulators_util,"
"emulators_steal,vhost_util,vhost_steal\n"
)
def output_node_csv(self, timestamp):
self.node_csv.write(
f"{datetime.fromtimestamp(timestamp)},"
f"{self.id},"
f"{self.nr_vms},"
f"{self.node_vcpu_threads},"
f"{self.vm_mem_allocated/1024},"
f"{self.vm_mem_used/1024},"
f"{'%0.02f' % (self.node_vcpu_sum_pc_util)},"
f"{'%0.02f' % (self.node_vcpu_sum_pc_steal)},"
f"{'%0.02f' % (self.node_emulators_sum_pc_util)},"
f"{'%0.02f' % (self.node_emulators_sum_pc_steal)},"
f"{'%0.02f' % (self.node_vhost_sum_pc_util)},"
f"{'%0.02f' % (self.node_vhost_sum_pc_steal)}\n"
)
self.node_csv.flush()
def output_allocation(self):
print(" Node %d: %s" % (self.id, self.print_node_initial_count()))
# -1 when no numa nodes
def node_list():
if os.path.exists("/sys/devices/system/node/online"):
return mixrange(read_str("/sys/devices/system/node/online"))
else:
return [-1]
def node_hwthreads(node_n):
if node_n == -1:
return mixrange(read_str("/sys/devices/system/cpu/online"))
else:
return mixrange(read_str(f"/sys/devices/system/node/node{node_n}/cpulist"))
@property
def nr_vms(self):
return len(self.node_vms)
@property
def nr_hwthreads(self):
return len(self.hwthread_list)
class Machine:
def __init__(self, args):
self.args = args
# to read/update node_vms in each node, prevents concurrent
# accesses by the main loop and the vm_allocation thread
self.nodes_lock = threading.Lock()
# Protect concurrent reads and writes to the all_vms dict
self.all_vms_lock = threading.Lock()
self.nodes = {}
self.all_vms = {}
self.cgroup = self.check_cgroup()
self.get_cpuset_mount_point()
self.cancel = False
self.get_machine_stat()
for n in Node.node_list():
self.nodes[n] = Node(n, self.args)
def refresh_machine_stats(self):
nr_hwthreads = self.nr_hwthreads
prev_user = self.last_cpu_user
prev_nice = self.last_cpu_nice
prev_system = self.last_cpu_system
prev_idle = self.last_cpu_idle
prev_iowait = self.last_cpu_iowait
prev_irq = self.last_cpu_irq
prev_softirq = self.last_cpu_softirq
prev_guest = self.last_cpu_guest
prev_ts = self.last_scrape_ts
self.get_machine_stat()
diff = (self.last_scrape_ts - prev_ts) * nr_hwthreads
self.pc_user = (self.last_cpu_user - prev_user) / diff
self.pc_nice = (self.last_cpu_nice - prev_nice) / diff
self.pc_system = (self.last_cpu_system - prev_system) / diff
self.pc_idle = (self.last_cpu_idle - prev_idle) / diff
self.pc_iowait = (self.last_cpu_iowait - prev_iowait) / diff
self.pc_irq = (self.last_cpu_irq - prev_irq) / diff
self.pc_softirq = (self.last_cpu_softirq - prev_softirq) / diff
self.pc_guest = (self.last_cpu_guest - prev_guest) / diff
def __repr__(self):
return (
f"Host CPU: user: {'%0.02f%%' % self.pc_user}, "
f"nice: {'%0.02f%%' % self.pc_nice}, "
f"system: {'%0.02f%%' % self.pc_system}, "
f"idle: {'%0.02f%%' % self.pc_idle}, "
f"iowait: {'%0.02f%%' % self.pc_iowait}, "
f"irq: {'%0.02f%%' % self.pc_irq}, "
f"guest: {'%0.02f%%' % self.pc_guest}"
)
def open_csv_file(self):
fname = os.path.join(self.args.csv, "host.csv")
print("Writing host data in %s" % (fname))
self.machine_csv = open(fname, "w")
self.machine_csv.write(
"timestamp,cpu_user,cpu_nice,cpu_system,"
"cpu_idle,cpu_iowait,cpu_irq,cpu_guest\n"
)
self.machine_csv.flush()
def output_machine_csv(self, timestamp):
self.machine_csv.write(
f"{datetime.fromtimestamp(timestamp)},"
f"{'%0.02f' % self.pc_user},"
f"{'%0.02f' % self.pc_nice},"
f"{'%0.02f' % self.pc_system},"
f"{'%0.02f' % self.pc_idle},"
f"{'%0.02f' % self.pc_iowait},"
f"{'%0.02f' % self.pc_irq},"
f"{'%0.02f' % self.pc_guest}\n"
)
def get_machine_stat(self):
self.last_scrape_ts = time.time()
with open("/proc/stat", "r") as f:
cpu = f.readline().split()
self.last_cpu_user = int(cpu[1])
self.last_cpu_nice = int(cpu[2])
self.last_cpu_system = int(cpu[3])
self.last_cpu_idle = int(cpu[4])
self.last_cpu_iowait = int(cpu[5])
self.last_cpu_irq = int(cpu[6])
self.last_cpu_softirq = int(cpu[7])
self.last_cpu_guest = int(cpu[9])
def check_cgroup(self):
# Check if cgroup2 is configured
cgroup2_path = "/sys/fs/cgroup/cgroup.controllers"
isfile = os.path.exists(cgroup2_path)
if isfile:
return 2
else:
return 1
def get_cpuset_mount_point(self):
with open("/proc/mounts", "r") as f:
mounts = f.read().split("\n")
for m in mounts:
m = m.split()
# Avoid scenrio where m is empty
if m:
if m[0] == "cgroup" or m[0] == "cgroup2":
if "unified" in m[1]:
continue
if "cpuset" in m[3]:
self.cpuset_mount_point = m[1]
return
elif "cgroup2" in m[2]:
self.cpuset_mount_point = m[1]
return
if self.cpuset_mount_point is None:
print("Cgroup cpuset path not found")
def refresh_stats(self):
for node in self.nodes.values():
node.clear_stats()
try:
self.all_vms_lock.acquire()
for vm in self.all_vms.values():
vm.refresh_stats()
finally:
self.all_vms_lock.release()
# Normalize by CPU count
for node in self.nodes.values():
node.node_vcpu_sum_pc_util /= node.nr_hwthreads
node.node_vcpu_sum_pc_steal /= node.nr_hwthreads
node.node_vhost_sum_pc_util /= node.nr_hwthreads
node.node_vhost_sum_pc_steal /= node.nr_hwthreads
node.node_emulators_sum_pc_util /= node.nr_hwthreads
node.node_emulators_sum_pc_steal /= node.nr_hwthreads
self.refresh_machine_stats()
def account_vcpus(self):
tmp = {}
for node_id in self.nodes.keys():
tmp[node_id] = 0
for vm in self.all_vms.values():
tmp[vm.vcpu_primary_node.id] += len(vm.vcpu_threads.keys())
for node_id in self.nodes.keys():
self.nodes[node_id].node_vcpu_threads = tmp[node_id]
def refresh_vm_allocation(self):
while True:
# Sleep 1s between scans
for i in range(10):
if stop is True:
return
time.sleep(0.1)
self.list_vms()
self.refresh_mem_allocation()
for vm in self.all_vms.values():
# If a VM switched memory node
if vm.new_mem_primary_node is not None:
try:
self.nodes_lock.acquire()
vm.mem_primary_node.vm_mem_allocated -= vm.mem_allocated
vm.new_mem_primary_node.vm_mem_allocated += vm.mem_allocated
vm.mem_primary_node = vm.new_mem_primary_node
vm.new_mem_primary_node = None
finally:
self.nodes_lock.release()
# If a VM switched vcpu node
if vm.new_vcpu_primary_node is not None:
try:
self.nodes_lock.acquire()
del vm.vcpu_primary_node.node_vms[vm.vm_pid]
vm.vcpu_primary_node.node_vcpu_threads -= vm.nr_vcpus
vm.new_vcpu_primary_node.node_vms[vm.vm_pid] = vm
vm.new_vcpu_primary_node.node_vcpu_threads += vm.nr_vcpus
vm.vcpu_primary_node = vm.new_vcpu_primary_node
vm.new_vcpu_primary_node = None
finally:
self.nodes_lock.release()
self.account_vcpus()
def print_initial_count(self):
for node in self.nodes.values():
self.print_node_count(node.id)
def print_node_count(self, node_id):
node = self.nodes[node_id]
node.output_allocation()
def get_prctl_nodes(self, cpus):
nodes = []
for c in cpus:
for n in self.nodes.values():
if c in n.hwthread_list:
if n not in nodes:
nodes.append(n)
break
return nodes
def get_nodes(self, cpuset):
nodes = []
fullpath = "%s/%s/cpuset.cpus" % (self.cpuset_mount_point, cpuset)
if os.path.exists(fullpath):
with open(fullpath, "r") as f:
cpus = mixrange(f.read())
for c in cpus:
for n in self.nodes.values():
if c in n.hwthread_list:
if n not in nodes:
nodes.append(n)
break
return nodes
@property
def nr_nodes(self):
return len(self.nodes)
@property
def nr_hwthreads(self):