kvm_stat 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888
  1. #!/usr/bin/env python3
  2. # SPDX-License-Identifier: GPL-2.0-only
  3. #
  4. # top-like utility for displaying kvm statistics
  5. #
  6. # Copyright 2006-2008 Qumranet Technologies
  7. # Copyright 2008-2011 Red Hat, Inc.
  8. #
  9. # Authors:
  10. # Avi Kivity <[email protected]>
  11. #
  12. """The kvm_stat module outputs statistics about running KVM VMs
  13. Three different ways of output formatting are available:
  14. - as a top-like text ui
  15. - in a key -> value format
  16. - in an all keys, all values format
  17. The data is sampled from the KVM's debugfs entries and its perf events.
  18. """
  19. from __future__ import print_function
  20. import curses
  21. import sys
  22. import locale
  23. import os
  24. import time
  25. import argparse
  26. import ctypes
  27. import fcntl
  28. import resource
  29. import struct
  30. import re
  31. import subprocess
  32. import signal
  33. from collections import defaultdict, namedtuple
  34. from functools import reduce
  35. from datetime import datetime
  36. VMX_EXIT_REASONS = {
  37. 'EXCEPTION_NMI': 0,
  38. 'EXTERNAL_INTERRUPT': 1,
  39. 'TRIPLE_FAULT': 2,
  40. 'INIT_SIGNAL': 3,
  41. 'SIPI_SIGNAL': 4,
  42. 'INTERRUPT_WINDOW': 7,
  43. 'NMI_WINDOW': 8,
  44. 'TASK_SWITCH': 9,
  45. 'CPUID': 10,
  46. 'HLT': 12,
  47. 'INVD': 13,
  48. 'INVLPG': 14,
  49. 'RDPMC': 15,
  50. 'RDTSC': 16,
  51. 'VMCALL': 18,
  52. 'VMCLEAR': 19,
  53. 'VMLAUNCH': 20,
  54. 'VMPTRLD': 21,
  55. 'VMPTRST': 22,
  56. 'VMREAD': 23,
  57. 'VMRESUME': 24,
  58. 'VMWRITE': 25,
  59. 'VMOFF': 26,
  60. 'VMON': 27,
  61. 'CR_ACCESS': 28,
  62. 'DR_ACCESS': 29,
  63. 'IO_INSTRUCTION': 30,
  64. 'MSR_READ': 31,
  65. 'MSR_WRITE': 32,
  66. 'INVALID_STATE': 33,
  67. 'MSR_LOAD_FAIL': 34,
  68. 'MWAIT_INSTRUCTION': 36,
  69. 'MONITOR_TRAP_FLAG': 37,
  70. 'MONITOR_INSTRUCTION': 39,
  71. 'PAUSE_INSTRUCTION': 40,
  72. 'MCE_DURING_VMENTRY': 41,
  73. 'TPR_BELOW_THRESHOLD': 43,
  74. 'APIC_ACCESS': 44,
  75. 'EOI_INDUCED': 45,
  76. 'GDTR_IDTR': 46,
  77. 'LDTR_TR': 47,
  78. 'EPT_VIOLATION': 48,
  79. 'EPT_MISCONFIG': 49,
  80. 'INVEPT': 50,
  81. 'RDTSCP': 51,
  82. 'PREEMPTION_TIMER': 52,
  83. 'INVVPID': 53,
  84. 'WBINVD': 54,
  85. 'XSETBV': 55,
  86. 'APIC_WRITE': 56,
  87. 'RDRAND': 57,
  88. 'INVPCID': 58,
  89. 'VMFUNC': 59,
  90. 'ENCLS': 60,
  91. 'RDSEED': 61,
  92. 'PML_FULL': 62,
  93. 'XSAVES': 63,
  94. 'XRSTORS': 64,
  95. 'UMWAIT': 67,
  96. 'TPAUSE': 68,
  97. 'BUS_LOCK': 74,
  98. 'NOTIFY': 75,
  99. }
  100. SVM_EXIT_REASONS = {
  101. 'READ_CR0': 0x000,
  102. 'READ_CR2': 0x002,
  103. 'READ_CR3': 0x003,
  104. 'READ_CR4': 0x004,
  105. 'READ_CR8': 0x008,
  106. 'WRITE_CR0': 0x010,
  107. 'WRITE_CR2': 0x012,
  108. 'WRITE_CR3': 0x013,
  109. 'WRITE_CR4': 0x014,
  110. 'WRITE_CR8': 0x018,
  111. 'READ_DR0': 0x020,
  112. 'READ_DR1': 0x021,
  113. 'READ_DR2': 0x022,
  114. 'READ_DR3': 0x023,
  115. 'READ_DR4': 0x024,
  116. 'READ_DR5': 0x025,
  117. 'READ_DR6': 0x026,
  118. 'READ_DR7': 0x027,
  119. 'WRITE_DR0': 0x030,
  120. 'WRITE_DR1': 0x031,
  121. 'WRITE_DR2': 0x032,
  122. 'WRITE_DR3': 0x033,
  123. 'WRITE_DR4': 0x034,
  124. 'WRITE_DR5': 0x035,
  125. 'WRITE_DR6': 0x036,
  126. 'WRITE_DR7': 0x037,
  127. 'EXCP_BASE': 0x040,
  128. 'LAST_EXCP': 0x05f,
  129. 'INTR': 0x060,
  130. 'NMI': 0x061,
  131. 'SMI': 0x062,
  132. 'INIT': 0x063,
  133. 'VINTR': 0x064,
  134. 'CR0_SEL_WRITE': 0x065,
  135. 'IDTR_READ': 0x066,
  136. 'GDTR_READ': 0x067,
  137. 'LDTR_READ': 0x068,
  138. 'TR_READ': 0x069,
  139. 'IDTR_WRITE': 0x06a,
  140. 'GDTR_WRITE': 0x06b,
  141. 'LDTR_WRITE': 0x06c,
  142. 'TR_WRITE': 0x06d,
  143. 'RDTSC': 0x06e,
  144. 'RDPMC': 0x06f,
  145. 'PUSHF': 0x070,
  146. 'POPF': 0x071,
  147. 'CPUID': 0x072,
  148. 'RSM': 0x073,
  149. 'IRET': 0x074,
  150. 'SWINT': 0x075,
  151. 'INVD': 0x076,
  152. 'PAUSE': 0x077,
  153. 'HLT': 0x078,
  154. 'INVLPG': 0x079,
  155. 'INVLPGA': 0x07a,
  156. 'IOIO': 0x07b,
  157. 'MSR': 0x07c,
  158. 'TASK_SWITCH': 0x07d,
  159. 'FERR_FREEZE': 0x07e,
  160. 'SHUTDOWN': 0x07f,
  161. 'VMRUN': 0x080,
  162. 'VMMCALL': 0x081,
  163. 'VMLOAD': 0x082,
  164. 'VMSAVE': 0x083,
  165. 'STGI': 0x084,
  166. 'CLGI': 0x085,
  167. 'SKINIT': 0x086,
  168. 'RDTSCP': 0x087,
  169. 'ICEBP': 0x088,
  170. 'WBINVD': 0x089,
  171. 'MONITOR': 0x08a,
  172. 'MWAIT': 0x08b,
  173. 'MWAIT_COND': 0x08c,
  174. 'XSETBV': 0x08d,
  175. 'RDPRU': 0x08e,
  176. 'EFER_WRITE_TRAP': 0x08f,
  177. 'CR0_WRITE_TRAP': 0x090,
  178. 'CR1_WRITE_TRAP': 0x091,
  179. 'CR2_WRITE_TRAP': 0x092,
  180. 'CR3_WRITE_TRAP': 0x093,
  181. 'CR4_WRITE_TRAP': 0x094,
  182. 'CR5_WRITE_TRAP': 0x095,
  183. 'CR6_WRITE_TRAP': 0x096,
  184. 'CR7_WRITE_TRAP': 0x097,
  185. 'CR8_WRITE_TRAP': 0x098,
  186. 'CR9_WRITE_TRAP': 0x099,
  187. 'CR10_WRITE_TRAP': 0x09a,
  188. 'CR11_WRITE_TRAP': 0x09b,
  189. 'CR12_WRITE_TRAP': 0x09c,
  190. 'CR13_WRITE_TRAP': 0x09d,
  191. 'CR14_WRITE_TRAP': 0x09e,
  192. 'CR15_WRITE_TRAP': 0x09f,
  193. 'INVPCID': 0x0a2,
  194. 'NPF': 0x400,
  195. 'AVIC_INCOMPLETE_IPI': 0x401,
  196. 'AVIC_UNACCELERATED_ACCESS': 0x402,
  197. 'VMGEXIT': 0x403,
  198. }
  199. # EC definition of HSR (from arch/arm64/include/asm/esr.h)
  200. AARCH64_EXIT_REASONS = {
  201. 'UNKNOWN': 0x00,
  202. 'WFx': 0x01,
  203. 'CP15_32': 0x03,
  204. 'CP15_64': 0x04,
  205. 'CP14_MR': 0x05,
  206. 'CP14_LS': 0x06,
  207. 'FP_ASIMD': 0x07,
  208. 'CP10_ID': 0x08,
  209. 'PAC': 0x09,
  210. 'CP14_64': 0x0C,
  211. 'BTI': 0x0D,
  212. 'ILL': 0x0E,
  213. 'SVC32': 0x11,
  214. 'HVC32': 0x12,
  215. 'SMC32': 0x13,
  216. 'SVC64': 0x15,
  217. 'HVC64': 0x16,
  218. 'SMC64': 0x17,
  219. 'SYS64': 0x18,
  220. 'SVE': 0x19,
  221. 'ERET': 0x1A,
  222. 'FPAC': 0x1C,
  223. 'SME': 0x1D,
  224. 'IMP_DEF': 0x1F,
  225. 'IABT_LOW': 0x20,
  226. 'IABT_CUR': 0x21,
  227. 'PC_ALIGN': 0x22,
  228. 'DABT_LOW': 0x24,
  229. 'DABT_CUR': 0x25,
  230. 'SP_ALIGN': 0x26,
  231. 'FP_EXC32': 0x28,
  232. 'FP_EXC64': 0x2C,
  233. 'SERROR': 0x2F,
  234. 'BREAKPT_LOW': 0x30,
  235. 'BREAKPT_CUR': 0x31,
  236. 'SOFTSTP_LOW': 0x32,
  237. 'SOFTSTP_CUR': 0x33,
  238. 'WATCHPT_LOW': 0x34,
  239. 'WATCHPT_CUR': 0x35,
  240. 'BKPT32': 0x38,
  241. 'VECTOR32': 0x3A,
  242. 'BRK64': 0x3C,
  243. }
  244. # From include/uapi/linux/kvm.h, KVM_EXIT_xxx
  245. USERSPACE_EXIT_REASONS = {
  246. 'UNKNOWN': 0,
  247. 'EXCEPTION': 1,
  248. 'IO': 2,
  249. 'HYPERCALL': 3,
  250. 'DEBUG': 4,
  251. 'HLT': 5,
  252. 'MMIO': 6,
  253. 'IRQ_WINDOW_OPEN': 7,
  254. 'SHUTDOWN': 8,
  255. 'FAIL_ENTRY': 9,
  256. 'INTR': 10,
  257. 'SET_TPR': 11,
  258. 'TPR_ACCESS': 12,
  259. 'S390_SIEIC': 13,
  260. 'S390_RESET': 14,
  261. 'DCR': 15,
  262. 'NMI': 16,
  263. 'INTERNAL_ERROR': 17,
  264. 'OSI': 18,
  265. 'PAPR_HCALL': 19,
  266. 'S390_UCONTROL': 20,
  267. 'WATCHDOG': 21,
  268. 'S390_TSCH': 22,
  269. 'EPR': 23,
  270. 'SYSTEM_EVENT': 24,
  271. 'S390_STSI': 25,
  272. 'IOAPIC_EOI': 26,
  273. 'HYPERV': 27,
  274. 'ARM_NISV': 28,
  275. 'X86_RDMSR': 29,
  276. 'X86_WRMSR': 30,
  277. 'DIRTY_RING_FULL': 31,
  278. 'AP_RESET_HOLD': 32,
  279. 'X86_BUS_LOCK': 33,
  280. 'XEN': 34,
  281. 'RISCV_SBI': 35,
  282. 'RISCV_CSR': 36,
  283. 'NOTIFY': 37,
  284. }
  285. IOCTL_NUMBERS = {
  286. 'SET_FILTER': 0x40082406,
  287. 'ENABLE': 0x00002400,
  288. 'DISABLE': 0x00002401,
  289. 'RESET': 0x00002403,
  290. }
  291. signal_received = False
  292. ENCODING = locale.getpreferredencoding(False)
  293. TRACE_FILTER = re.compile(r'^[^\(]*$')
  294. class Arch(object):
  295. """Encapsulates global architecture specific data.
  296. Contains the performance event open syscall and ioctl numbers, as
  297. well as the VM exit reasons for the architecture it runs on.
  298. """
  299. @staticmethod
  300. def get_arch():
  301. machine = os.uname()[4]
  302. if machine.startswith('ppc'):
  303. return ArchPPC()
  304. elif machine.startswith('aarch64'):
  305. return ArchA64()
  306. elif machine.startswith('s390'):
  307. return ArchS390()
  308. else:
  309. # X86_64
  310. for line in open('/proc/cpuinfo'):
  311. if not line.startswith('flags'):
  312. continue
  313. flags = line.split()
  314. if 'vmx' in flags:
  315. return ArchX86(VMX_EXIT_REASONS)
  316. if 'svm' in flags:
  317. return ArchX86(SVM_EXIT_REASONS)
  318. return
  319. def tracepoint_is_child(self, field):
  320. if (TRACE_FILTER.match(field)):
  321. return None
  322. return field.split('(', 1)[0]
  323. class ArchX86(Arch):
  324. def __init__(self, exit_reasons):
  325. self.sc_perf_evt_open = 298
  326. self.ioctl_numbers = IOCTL_NUMBERS
  327. self.exit_reason_field = 'exit_reason'
  328. self.exit_reasons = exit_reasons
  329. def debugfs_is_child(self, field):
  330. """ Returns name of parent if 'field' is a child, None otherwise """
  331. return None
  332. class ArchPPC(Arch):
  333. def __init__(self):
  334. self.sc_perf_evt_open = 319
  335. self.ioctl_numbers = IOCTL_NUMBERS
  336. self.ioctl_numbers['ENABLE'] = 0x20002400
  337. self.ioctl_numbers['DISABLE'] = 0x20002401
  338. self.ioctl_numbers['RESET'] = 0x20002403
  339. # PPC comes in 32 and 64 bit and some generated ioctl
  340. # numbers depend on the wordsize.
  341. char_ptr_size = ctypes.sizeof(ctypes.c_char_p)
  342. self.ioctl_numbers['SET_FILTER'] = 0x80002406 | char_ptr_size << 16
  343. self.exit_reason_field = 'exit_nr'
  344. self.exit_reasons = {}
  345. def debugfs_is_child(self, field):
  346. """ Returns name of parent if 'field' is a child, None otherwise """
  347. return None
  348. class ArchA64(Arch):
  349. def __init__(self):
  350. self.sc_perf_evt_open = 241
  351. self.ioctl_numbers = IOCTL_NUMBERS
  352. self.exit_reason_field = 'esr_ec'
  353. self.exit_reasons = AARCH64_EXIT_REASONS
  354. def debugfs_is_child(self, field):
  355. """ Returns name of parent if 'field' is a child, None otherwise """
  356. return None
  357. class ArchS390(Arch):
  358. def __init__(self):
  359. self.sc_perf_evt_open = 331
  360. self.ioctl_numbers = IOCTL_NUMBERS
  361. self.exit_reason_field = None
  362. self.exit_reasons = None
  363. def debugfs_is_child(self, field):
  364. """ Returns name of parent if 'field' is a child, None otherwise """
  365. if field.startswith('instruction_'):
  366. return 'exit_instruction'
  367. ARCH = Arch.get_arch()
  368. class perf_event_attr(ctypes.Structure):
  369. """Struct that holds the necessary data to set up a trace event.
  370. For an extensive explanation see perf_event_open(2) and
  371. include/uapi/linux/perf_event.h, struct perf_event_attr
  372. All fields that are not initialized in the constructor are 0.
  373. """
  374. _fields_ = [('type', ctypes.c_uint32),
  375. ('size', ctypes.c_uint32),
  376. ('config', ctypes.c_uint64),
  377. ('sample_freq', ctypes.c_uint64),
  378. ('sample_type', ctypes.c_uint64),
  379. ('read_format', ctypes.c_uint64),
  380. ('flags', ctypes.c_uint64),
  381. ('wakeup_events', ctypes.c_uint32),
  382. ('bp_type', ctypes.c_uint32),
  383. ('bp_addr', ctypes.c_uint64),
  384. ('bp_len', ctypes.c_uint64),
  385. ]
  386. def __init__(self):
  387. super(self.__class__, self).__init__()
  388. self.type = PERF_TYPE_TRACEPOINT
  389. self.size = ctypes.sizeof(self)
  390. self.read_format = PERF_FORMAT_GROUP
  391. PERF_TYPE_TRACEPOINT = 2
  392. PERF_FORMAT_GROUP = 1 << 3
  393. class Group(object):
  394. """Represents a perf event group."""
  395. def __init__(self):
  396. self.events = []
  397. def add_event(self, event):
  398. self.events.append(event)
  399. def read(self):
  400. """Returns a dict with 'event name: value' for all events in the
  401. group.
  402. Values are read by reading from the file descriptor of the
  403. event that is the group leader. See perf_event_open(2) for
  404. details.
  405. Read format for the used event configuration is:
  406. struct read_format {
  407. u64 nr; /* The number of events */
  408. struct {
  409. u64 value; /* The value of the event */
  410. } values[nr];
  411. };
  412. """
  413. length = 8 * (1 + len(self.events))
  414. read_format = 'xxxxxxxx' + 'Q' * len(self.events)
  415. return dict(zip([event.name for event in self.events],
  416. struct.unpack(read_format,
  417. os.read(self.events[0].fd, length))))
  418. class Event(object):
  419. """Represents a performance event and manages its life cycle."""
  420. def __init__(self, name, group, trace_cpu, trace_pid, trace_point,
  421. trace_filter, trace_set='kvm'):
  422. self.libc = ctypes.CDLL('libc.so.6', use_errno=True)
  423. self.syscall = self.libc.syscall
  424. self.name = name
  425. self.fd = None
  426. self._setup_event(group, trace_cpu, trace_pid, trace_point,
  427. trace_filter, trace_set)
  428. def __del__(self):
  429. """Closes the event's file descriptor.
  430. As no python file object was created for the file descriptor,
  431. python will not reference count the descriptor and will not
  432. close it itself automatically, so we do it.
  433. """
  434. if self.fd:
  435. os.close(self.fd)
  436. def _perf_event_open(self, attr, pid, cpu, group_fd, flags):
  437. """Wrapper for the sys_perf_evt_open() syscall.
  438. Used to set up performance events, returns a file descriptor or -1
  439. on error.
  440. Attributes are:
  441. - syscall number
  442. - struct perf_event_attr *
  443. - pid or -1 to monitor all pids
  444. - cpu number or -1 to monitor all cpus
  445. - The file descriptor of the group leader or -1 to create a group.
  446. - flags
  447. """
  448. return self.syscall(ARCH.sc_perf_evt_open, ctypes.pointer(attr),
  449. ctypes.c_int(pid), ctypes.c_int(cpu),
  450. ctypes.c_int(group_fd), ctypes.c_long(flags))
  451. def _setup_event_attribute(self, trace_set, trace_point):
  452. """Returns an initialized ctype perf_event_attr struct."""
  453. id_path = os.path.join(PATH_DEBUGFS_TRACING, 'events', trace_set,
  454. trace_point, 'id')
  455. event_attr = perf_event_attr()
  456. event_attr.config = int(open(id_path).read())
  457. return event_attr
  458. def _setup_event(self, group, trace_cpu, trace_pid, trace_point,
  459. trace_filter, trace_set):
  460. """Sets up the perf event in Linux.
  461. Issues the syscall to register the event in the kernel and
  462. then sets the optional filter.
  463. """
  464. event_attr = self._setup_event_attribute(trace_set, trace_point)
  465. # First event will be group leader.
  466. group_leader = -1
  467. # All others have to pass the leader's descriptor instead.
  468. if group.events:
  469. group_leader = group.events[0].fd
  470. fd = self._perf_event_open(event_attr, trace_pid,
  471. trace_cpu, group_leader, 0)
  472. if fd == -1:
  473. err = ctypes.get_errno()
  474. raise OSError(err, os.strerror(err),
  475. 'while calling sys_perf_event_open().')
  476. if trace_filter:
  477. fcntl.ioctl(fd, ARCH.ioctl_numbers['SET_FILTER'],
  478. trace_filter)
  479. self.fd = fd
  480. def enable(self):
  481. """Enables the trace event in the kernel.
  482. Enabling the group leader makes reading counters from it and the
  483. events under it possible.
  484. """
  485. fcntl.ioctl(self.fd, ARCH.ioctl_numbers['ENABLE'], 0)
  486. def disable(self):
  487. """Disables the trace event in the kernel.
  488. Disabling the group leader makes reading all counters under it
  489. impossible.
  490. """
  491. fcntl.ioctl(self.fd, ARCH.ioctl_numbers['DISABLE'], 0)
  492. def reset(self):
  493. """Resets the count of the trace event in the kernel."""
  494. fcntl.ioctl(self.fd, ARCH.ioctl_numbers['RESET'], 0)
  495. class Provider(object):
  496. """Encapsulates functionalities used by all providers."""
  497. def __init__(self, pid):
  498. self.child_events = False
  499. self.pid = pid
  500. @staticmethod
  501. def is_field_wanted(fields_filter, field):
  502. """Indicate whether field is valid according to fields_filter."""
  503. if not fields_filter:
  504. return True
  505. return re.match(fields_filter, field) is not None
  506. @staticmethod
  507. def walkdir(path):
  508. """Returns os.walk() data for specified directory.
  509. As it is only a wrapper it returns the same 3-tuple of (dirpath,
  510. dirnames, filenames).
  511. """
  512. return next(os.walk(path))
  513. class TracepointProvider(Provider):
  514. """Data provider for the stats class.
  515. Manages the events/groups from which it acquires its data.
  516. """
  517. def __init__(self, pid, fields_filter):
  518. self.group_leaders = []
  519. self.filters = self._get_filters()
  520. self.update_fields(fields_filter)
  521. super(TracepointProvider, self).__init__(pid)
  522. @staticmethod
  523. def _get_filters():
  524. """Returns a dict of trace events, their filter ids and
  525. the values that can be filtered.
  526. Trace events can be filtered for special values by setting a
  527. filter string via an ioctl. The string normally has the format
  528. identifier==value. For each filter a new event will be created, to
  529. be able to distinguish the events.
  530. """
  531. filters = {}
  532. filters['kvm_userspace_exit'] = ('reason', USERSPACE_EXIT_REASONS)
  533. if ARCH.exit_reason_field and ARCH.exit_reasons:
  534. filters['kvm_exit'] = (ARCH.exit_reason_field, ARCH.exit_reasons)
  535. return filters
  536. def _get_available_fields(self):
  537. """Returns a list of available events of format 'event name(filter
  538. name)'.
  539. All available events have directories under
  540. /sys/kernel/debug/tracing/events/ which export information
  541. about the specific event. Therefore, listing the dirs gives us
  542. a list of all available events.
  543. Some events like the vm exit reasons can be filtered for
  544. specific values. To take account for that, the routine below
  545. creates special fields with the following format:
  546. event name(filter name)
  547. """
  548. path = os.path.join(PATH_DEBUGFS_TRACING, 'events', 'kvm')
  549. fields = self.walkdir(path)[1]
  550. extra = []
  551. for field in fields:
  552. if field in self.filters:
  553. filter_name_, filter_dicts = self.filters[field]
  554. for name in filter_dicts:
  555. extra.append(field + '(' + name + ')')
  556. fields += extra
  557. return fields
  558. def update_fields(self, fields_filter):
  559. """Refresh fields, applying fields_filter"""
  560. self.fields = [field for field in self._get_available_fields()
  561. if self.is_field_wanted(fields_filter, field)]
  562. # add parents for child fields - otherwise we won't see any output!
  563. for field in self._fields:
  564. parent = ARCH.tracepoint_is_child(field)
  565. if (parent and parent not in self._fields):
  566. self.fields.append(parent)
  567. @staticmethod
  568. def _get_online_cpus():
  569. """Returns a list of cpu id integers."""
  570. def parse_int_list(list_string):
  571. """Returns an int list from a string of comma separated integers and
  572. integer ranges."""
  573. integers = []
  574. members = list_string.split(',')
  575. for member in members:
  576. if '-' not in member:
  577. integers.append(int(member))
  578. else:
  579. int_range = member.split('-')
  580. integers.extend(range(int(int_range[0]),
  581. int(int_range[1]) + 1))
  582. return integers
  583. with open('/sys/devices/system/cpu/online') as cpu_list:
  584. cpu_string = cpu_list.readline()
  585. return parse_int_list(cpu_string)
  586. def _setup_traces(self):
  587. """Creates all event and group objects needed to be able to retrieve
  588. data."""
  589. fields = self._get_available_fields()
  590. if self._pid > 0:
  591. # Fetch list of all threads of the monitored pid, as qemu
  592. # starts a thread for each vcpu.
  593. path = os.path.join('/proc', str(self._pid), 'task')
  594. groupids = self.walkdir(path)[1]
  595. else:
  596. groupids = self._get_online_cpus()
  597. # The constant is needed as a buffer for python libs, std
  598. # streams and other files that the script opens.
  599. newlim = len(groupids) * len(fields) + 50
  600. try:
  601. softlim_, hardlim = resource.getrlimit(resource.RLIMIT_NOFILE)
  602. if hardlim < newlim:
  603. # Now we need CAP_SYS_RESOURCE, to increase the hard limit.
  604. resource.setrlimit(resource.RLIMIT_NOFILE, (newlim, newlim))
  605. else:
  606. # Raising the soft limit is sufficient.
  607. resource.setrlimit(resource.RLIMIT_NOFILE, (newlim, hardlim))
  608. except ValueError:
  609. sys.exit("NOFILE rlimit could not be raised to {0}".format(newlim))
  610. for groupid in groupids:
  611. group = Group()
  612. for name in fields:
  613. tracepoint = name
  614. tracefilter = None
  615. match = re.match(r'(.*)\((.*)\)', name)
  616. if match:
  617. tracepoint, sub = match.groups()
  618. tracefilter = ('%s==%d\0' %
  619. (self.filters[tracepoint][0],
  620. self.filters[tracepoint][1][sub]))
  621. # From perf_event_open(2):
  622. # pid > 0 and cpu == -1
  623. # This measures the specified process/thread on any CPU.
  624. #
  625. # pid == -1 and cpu >= 0
  626. # This measures all processes/threads on the specified CPU.
  627. trace_cpu = groupid if self._pid == 0 else -1
  628. trace_pid = int(groupid) if self._pid != 0 else -1
  629. group.add_event(Event(name=name,
  630. group=group,
  631. trace_cpu=trace_cpu,
  632. trace_pid=trace_pid,
  633. trace_point=tracepoint,
  634. trace_filter=tracefilter))
  635. self.group_leaders.append(group)
  636. @property
  637. def fields(self):
  638. return self._fields
  639. @fields.setter
  640. def fields(self, fields):
  641. """Enables/disables the (un)wanted events"""
  642. self._fields = fields
  643. for group in self.group_leaders:
  644. for index, event in enumerate(group.events):
  645. if event.name in fields:
  646. event.reset()
  647. event.enable()
  648. else:
  649. # Do not disable the group leader.
  650. # It would disable all of its events.
  651. if index != 0:
  652. event.disable()
  653. @property
  654. def pid(self):
  655. return self._pid
  656. @pid.setter
  657. def pid(self, pid):
  658. """Changes the monitored pid by setting new traces."""
  659. self._pid = pid
  660. # The garbage collector will get rid of all Event/Group
  661. # objects and open files after removing the references.
  662. self.group_leaders = []
  663. self._setup_traces()
  664. self.fields = self._fields
  665. def read(self, by_guest=0):
  666. """Returns 'event name: current value' for all enabled events."""
  667. ret = defaultdict(int)
  668. for group in self.group_leaders:
  669. for name, val in group.read().items():
  670. if name not in self._fields:
  671. continue
  672. parent = ARCH.tracepoint_is_child(name)
  673. if parent:
  674. name += ' ' + parent
  675. ret[name] += val
  676. return ret
  677. def reset(self):
  678. """Reset all field counters"""
  679. for group in self.group_leaders:
  680. for event in group.events:
  681. event.reset()
  682. class DebugfsProvider(Provider):
  683. """Provides data from the files that KVM creates in the kvm debugfs
  684. folder."""
  685. def __init__(self, pid, fields_filter, include_past):
  686. self.update_fields(fields_filter)
  687. self._baseline = {}
  688. self.do_read = True
  689. self.paths = []
  690. super(DebugfsProvider, self).__init__(pid)
  691. if include_past:
  692. self._restore()
  693. def _get_available_fields(self):
  694. """"Returns a list of available fields.
  695. The fields are all available KVM debugfs files
  696. """
  697. exempt_list = ['halt_poll_fail_ns', 'halt_poll_success_ns', 'halt_wait_ns']
  698. fields = [field for field in self.walkdir(PATH_DEBUGFS_KVM)[2]
  699. if field not in exempt_list]
  700. return fields
  701. def update_fields(self, fields_filter):
  702. """Refresh fields, applying fields_filter"""
  703. self._fields = [field for field in self._get_available_fields()
  704. if self.is_field_wanted(fields_filter, field)]
  705. # add parents for child fields - otherwise we won't see any output!
  706. for field in self._fields:
  707. parent = ARCH.debugfs_is_child(field)
  708. if (parent and parent not in self._fields):
  709. self.fields.append(parent)
  710. @property
  711. def fields(self):
  712. return self._fields
  713. @fields.setter
  714. def fields(self, fields):
  715. self._fields = fields
  716. self.reset()
  717. @property
  718. def pid(self):
  719. return self._pid
  720. @pid.setter
  721. def pid(self, pid):
  722. self._pid = pid
  723. if pid != 0:
  724. vms = self.walkdir(PATH_DEBUGFS_KVM)[1]
  725. if len(vms) == 0:
  726. self.do_read = False
  727. self.paths = list(filter(lambda x: "{}-".format(pid) in x, vms))
  728. else:
  729. self.paths = []
  730. self.do_read = True
  731. def _verify_paths(self):
  732. """Remove invalid paths"""
  733. for path in self.paths:
  734. if not os.path.exists(os.path.join(PATH_DEBUGFS_KVM, path)):
  735. self.paths.remove(path)
  736. continue
  737. def read(self, reset=0, by_guest=0):
  738. """Returns a dict with format:'file name / field -> current value'.
  739. Parameter 'reset':
  740. 0 plain read
  741. 1 reset field counts to 0
  742. 2 restore the original field counts
  743. """
  744. results = {}
  745. # If no debugfs filtering support is available, then don't read.
  746. if not self.do_read:
  747. return results
  748. self._verify_paths()
  749. paths = self.paths
  750. if self._pid == 0:
  751. paths = []
  752. for entry in os.walk(PATH_DEBUGFS_KVM):
  753. for dir in entry[1]:
  754. paths.append(dir)
  755. for path in paths:
  756. for field in self._fields:
  757. value = self._read_field(field, path)
  758. key = path + field
  759. if reset == 1:
  760. self._baseline[key] = value
  761. if reset == 2:
  762. self._baseline[key] = 0
  763. if self._baseline.get(key, -1) == -1:
  764. self._baseline[key] = value
  765. parent = ARCH.debugfs_is_child(field)
  766. if parent:
  767. field = field + ' ' + parent
  768. else:
  769. if by_guest:
  770. field = key.split('-')[0] # set 'field' to 'pid'
  771. increment = value - self._baseline.get(key, 0)
  772. if field in results:
  773. results[field] += increment
  774. else:
  775. results[field] = increment
  776. return results
  777. def _read_field(self, field, path):
  778. """Returns the value of a single field from a specific VM."""
  779. try:
  780. return int(open(os.path.join(PATH_DEBUGFS_KVM,
  781. path,
  782. field))
  783. .read())
  784. except IOError:
  785. return 0
  786. def reset(self):
  787. """Reset field counters"""
  788. self._baseline = {}
  789. self.read(1)
  790. def _restore(self):
  791. """Reset field counters"""
  792. self._baseline = {}
  793. self.read(2)
  794. EventStat = namedtuple('EventStat', ['value', 'delta'])
  795. class Stats(object):
  796. """Manages the data providers and the data they provide.
  797. It is used to set filters on the provider's data and collect all
  798. provider data.
  799. """
  800. def __init__(self, options):
  801. self.providers = self._get_providers(options)
  802. self._pid_filter = options.pid
  803. self._fields_filter = options.fields
  804. self.values = {}
  805. self._child_events = False
  806. def _get_providers(self, options):
  807. """Returns a list of data providers depending on the passed options."""
  808. providers = []
  809. if options.debugfs:
  810. providers.append(DebugfsProvider(options.pid, options.fields,
  811. options.debugfs_include_past))
  812. if options.tracepoints or not providers:
  813. providers.append(TracepointProvider(options.pid, options.fields))
  814. return providers
  815. def _update_provider_filters(self):
  816. """Propagates fields filters to providers."""
  817. # As we reset the counters when updating the fields we can
  818. # also clear the cache of old values.
  819. self.values = {}
  820. for provider in self.providers:
  821. provider.update_fields(self._fields_filter)
  822. def reset(self):
  823. self.values = {}
  824. for provider in self.providers:
  825. provider.reset()
  826. @property
  827. def fields_filter(self):
  828. return self._fields_filter
  829. @fields_filter.setter
  830. def fields_filter(self, fields_filter):
  831. if fields_filter != self._fields_filter:
  832. self._fields_filter = fields_filter
  833. self._update_provider_filters()
  834. @property
  835. def pid_filter(self):
  836. return self._pid_filter
  837. @pid_filter.setter
  838. def pid_filter(self, pid):
  839. if pid != self._pid_filter:
  840. self._pid_filter = pid
  841. self.values = {}
  842. for provider in self.providers:
  843. provider.pid = self._pid_filter
  844. @property
  845. def child_events(self):
  846. return self._child_events
  847. @child_events.setter
  848. def child_events(self, val):
  849. self._child_events = val
  850. for provider in self.providers:
  851. provider.child_events = val
  852. def get(self, by_guest=0):
  853. """Returns a dict with field -> (value, delta to last value) of all
  854. provider data.
  855. Key formats:
  856. * plain: 'key' is event name
  857. * child-parent: 'key' is in format '<child> <parent>'
  858. * pid: 'key' is the pid of the guest, and the record contains the
  859. aggregated event data
  860. These formats are generated by the providers, and handled in class TUI.
  861. """
  862. for provider in self.providers:
  863. new = provider.read(by_guest=by_guest)
  864. for key in new:
  865. oldval = self.values.get(key, EventStat(0, 0)).value
  866. newval = new.get(key, 0)
  867. newdelta = newval - oldval
  868. self.values[key] = EventStat(newval, newdelta)
  869. return self.values
  870. def toggle_display_guests(self, to_pid):
  871. """Toggle between collection of stats by individual event and by
  872. guest pid
  873. Events reported by DebugfsProvider change when switching to/from
  874. reading by guest values. Hence we have to remove the excess event
  875. names from self.values.
  876. """
  877. if any(isinstance(ins, TracepointProvider) for ins in self.providers):
  878. return 1
  879. if to_pid:
  880. for provider in self.providers:
  881. if isinstance(provider, DebugfsProvider):
  882. for key in provider.fields:
  883. if key in self.values.keys():
  884. del self.values[key]
  885. else:
  886. oldvals = self.values.copy()
  887. for key in oldvals:
  888. if key.isdigit():
  889. del self.values[key]
  890. # Update oldval (see get())
  891. self.get(to_pid)
  892. return 0
  893. DELAY_DEFAULT = 3.0
  894. MAX_GUEST_NAME_LEN = 48
  895. MAX_REGEX_LEN = 44
  896. SORT_DEFAULT = 0
  897. MIN_DELAY = 0.1
  898. MAX_DELAY = 25.5
  899. class Tui(object):
  900. """Instruments curses to draw a nice text ui."""
  901. def __init__(self, stats, opts):
  902. self.stats = stats
  903. self.screen = None
  904. self._delay_initial = 0.25
  905. self._delay_regular = opts.set_delay
  906. self._sorting = SORT_DEFAULT
  907. self._display_guests = 0
  908. def __enter__(self):
  909. """Initialises curses for later use. Based on curses.wrapper
  910. implementation from the Python standard library."""
  911. self.screen = curses.initscr()
  912. curses.noecho()
  913. curses.cbreak()
  914. # The try/catch works around a minor bit of
  915. # over-conscientiousness in the curses module, the error
  916. # return from C start_color() is ignorable.
  917. try:
  918. curses.start_color()
  919. except curses.error:
  920. pass
  921. # Hide cursor in extra statement as some monochrome terminals
  922. # might support hiding but not colors.
  923. try:
  924. curses.curs_set(0)
  925. except curses.error:
  926. pass
  927. curses.use_default_colors()
  928. return self
  929. def __exit__(self, *exception):
  930. """Resets the terminal to its normal state. Based on curses.wrapper
  931. implementation from the Python standard library."""
  932. if self.screen:
  933. self.screen.keypad(0)
  934. curses.echo()
  935. curses.nocbreak()
  936. curses.endwin()
  937. @staticmethod
  938. def get_all_gnames():
  939. """Returns a list of (pid, gname) tuples of all running guests"""
  940. res = []
  941. try:
  942. child = subprocess.Popen(['ps', '-A', '--format', 'pid,args'],
  943. stdout=subprocess.PIPE)
  944. except:
  945. raise Exception
  946. for line in child.stdout:
  947. line = line.decode(ENCODING).lstrip().split(' ', 1)
  948. # perform a sanity check before calling the more expensive
  949. # function to possibly extract the guest name
  950. if ' -name ' in line[1]:
  951. res.append((line[0], Tui.get_gname_from_pid(line[0])))
  952. child.stdout.close()
  953. return res
  954. def _print_all_gnames(self, row):
  955. """Print a list of all running guests along with their pids."""
  956. self.screen.addstr(row, 2, '%8s %-60s' %
  957. ('Pid', 'Guest Name (fuzzy list, might be '
  958. 'inaccurate!)'),
  959. curses.A_UNDERLINE)
  960. row += 1
  961. try:
  962. for line in self.get_all_gnames():
  963. self.screen.addstr(row, 2, '%8s %-60s' % (line[0], line[1]))
  964. row += 1
  965. if row >= self.screen.getmaxyx()[0]:
  966. break
  967. except Exception:
  968. self.screen.addstr(row + 1, 2, 'Not available')
  969. @staticmethod
  970. def get_pid_from_gname(gname):
  971. """Fuzzy function to convert guest name to QEMU process pid.
  972. Returns a list of potential pids, can be empty if no match found.
  973. Throws an exception on processing errors.
  974. """
  975. pids = []
  976. for line in Tui.get_all_gnames():
  977. if gname == line[1]:
  978. pids.append(int(line[0]))
  979. return pids
  980. @staticmethod
  981. def get_gname_from_pid(pid):
  982. """Returns the guest name for a QEMU process pid.
  983. Extracts the guest name from the QEMU comma line by processing the
  984. '-name' option. Will also handle names specified out of sequence.
  985. """
  986. name = ''
  987. try:
  988. line = open('/proc/{}/cmdline'
  989. .format(pid), 'r').read().split('\0')
  990. parms = line[line.index('-name') + 1].split(',')
  991. while '' in parms:
  992. # commas are escaped (i.e. ',,'), hence e.g. 'foo,bar' results
  993. # in # ['foo', '', 'bar'], which we revert here
  994. idx = parms.index('')
  995. parms[idx - 1] += ',' + parms[idx + 1]
  996. del parms[idx:idx+2]
  997. # the '-name' switch allows for two ways to specify the guest name,
  998. # where the plain name overrides the name specified via 'guest='
  999. for arg in parms:
  1000. if '=' not in arg:
  1001. name = arg
  1002. break
  1003. if arg[:6] == 'guest=':
  1004. name = arg[6:]
  1005. except (ValueError, IOError, IndexError):
  1006. pass
  1007. return name
  1008. def _update_pid(self, pid):
  1009. """Propagates pid selection to stats object."""
  1010. self.screen.addstr(4, 1, 'Updating pid filter...')
  1011. self.screen.refresh()
  1012. self.stats.pid_filter = pid
  1013. def _refresh_header(self, pid=None):
  1014. """Refreshes the header."""
  1015. if pid is None:
  1016. pid = self.stats.pid_filter
  1017. self.screen.erase()
  1018. gname = self.get_gname_from_pid(pid)
  1019. self._gname = gname
  1020. if gname:
  1021. gname = ('({})'.format(gname[:MAX_GUEST_NAME_LEN] + '...'
  1022. if len(gname) > MAX_GUEST_NAME_LEN
  1023. else gname))
  1024. if pid > 0:
  1025. self._headline = 'kvm statistics - pid {0} {1}'.format(pid, gname)
  1026. else:
  1027. self._headline = 'kvm statistics - summary'
  1028. self.screen.addstr(0, 0, self._headline, curses.A_BOLD)
  1029. if self.stats.fields_filter:
  1030. regex = self.stats.fields_filter
  1031. if len(regex) > MAX_REGEX_LEN:
  1032. regex = regex[:MAX_REGEX_LEN] + '...'
  1033. self.screen.addstr(1, 17, 'regex filter: {0}'.format(regex))
  1034. if self._display_guests:
  1035. col_name = 'Guest Name'
  1036. else:
  1037. col_name = 'Event'
  1038. self.screen.addstr(2, 1, '%-40s %10s%7s %8s' %
  1039. (col_name, 'Total', '%Total', 'CurAvg/s'),
  1040. curses.A_STANDOUT)
  1041. self.screen.addstr(4, 1, 'Collecting data...')
  1042. self.screen.refresh()
  1043. def _refresh_body(self, sleeptime):
  1044. def insert_child(sorted_items, child, values, parent):
  1045. num = len(sorted_items)
  1046. for i in range(0, num):
  1047. # only add child if parent is present
  1048. if parent.startswith(sorted_items[i][0]):
  1049. sorted_items.insert(i + 1, (' ' + child, values))
  1050. def get_sorted_events(self, stats):
  1051. """ separate parent and child events """
  1052. if self._sorting == SORT_DEFAULT:
  1053. def sortkey(pair):
  1054. # sort by (delta value, overall value)
  1055. v = pair[1]
  1056. return (v.delta, v.value)
  1057. else:
  1058. def sortkey(pair):
  1059. # sort by overall value
  1060. v = pair[1]
  1061. return v.value
  1062. childs = []
  1063. sorted_items = []
  1064. # we can't rule out child events to appear prior to parents even
  1065. # when sorted - separate out all children first, and add in later
  1066. for key, values in sorted(stats.items(), key=sortkey,
  1067. reverse=True):
  1068. if values == (0, 0):
  1069. continue
  1070. if key.find(' ') != -1:
  1071. if not self.stats.child_events:
  1072. continue
  1073. childs.insert(0, (key, values))
  1074. else:
  1075. sorted_items.append((key, values))
  1076. if self.stats.child_events:
  1077. for key, values in childs:
  1078. (child, parent) = key.split(' ')
  1079. insert_child(sorted_items, child, values, parent)
  1080. return sorted_items
  1081. if not self._is_running_guest(self.stats.pid_filter):
  1082. if self._gname:
  1083. try: # ...to identify the guest by name in case it's back
  1084. pids = self.get_pid_from_gname(self._gname)
  1085. if len(pids) == 1:
  1086. self._refresh_header(pids[0])
  1087. self._update_pid(pids[0])
  1088. return
  1089. except:
  1090. pass
  1091. self._display_guest_dead()
  1092. # leave final data on screen
  1093. return
  1094. row = 3
  1095. self.screen.move(row, 0)
  1096. self.screen.clrtobot()
  1097. stats = self.stats.get(self._display_guests)
  1098. total = 0.
  1099. ctotal = 0.
  1100. for key, values in stats.items():
  1101. if self._display_guests:
  1102. if self.get_gname_from_pid(key):
  1103. total += values.value
  1104. continue
  1105. if not key.find(' ') != -1:
  1106. total += values.value
  1107. else:
  1108. ctotal += values.value
  1109. if total == 0.:
  1110. # we don't have any fields, or all non-child events are filtered
  1111. total = ctotal
  1112. # print events
  1113. tavg = 0
  1114. tcur = 0
  1115. guest_removed = False
  1116. for key, values in get_sorted_events(self, stats):
  1117. if row >= self.screen.getmaxyx()[0] - 1 or values == (0, 0):
  1118. break
  1119. if self._display_guests:
  1120. key = self.get_gname_from_pid(key)
  1121. if not key:
  1122. continue
  1123. cur = int(round(values.delta / sleeptime)) if values.delta else 0
  1124. if cur < 0:
  1125. guest_removed = True
  1126. continue
  1127. if key[0] != ' ':
  1128. if values.delta:
  1129. tcur += values.delta
  1130. ptotal = values.value
  1131. ltotal = total
  1132. else:
  1133. ltotal = ptotal
  1134. self.screen.addstr(row, 1, '%-40s %10d%7.1f %8s' % (key,
  1135. values.value,
  1136. values.value * 100 / float(ltotal), cur))
  1137. row += 1
  1138. if row == 3:
  1139. if guest_removed:
  1140. self.screen.addstr(4, 1, 'Guest removed, updating...')
  1141. else:
  1142. self.screen.addstr(4, 1, 'No matching events reported yet')
  1143. if row > 4:
  1144. tavg = int(round(tcur / sleeptime)) if tcur > 0 else ''
  1145. self.screen.addstr(row, 1, '%-40s %10d %8s' %
  1146. ('Total', total, tavg), curses.A_BOLD)
  1147. self.screen.refresh()
  1148. def _display_guest_dead(self):
  1149. marker = ' Guest is DEAD '
  1150. y = min(len(self._headline), 80 - len(marker))
  1151. self.screen.addstr(0, y, marker, curses.A_BLINK | curses.A_STANDOUT)
  1152. def _show_msg(self, text):
  1153. """Display message centered text and exit on key press"""
  1154. hint = 'Press any key to continue'
  1155. curses.cbreak()
  1156. self.screen.erase()
  1157. (x, term_width) = self.screen.getmaxyx()
  1158. row = 2
  1159. for line in text:
  1160. start = (term_width - len(line)) // 2
  1161. self.screen.addstr(row, start, line)
  1162. row += 1
  1163. self.screen.addstr(row + 1, (term_width - len(hint)) // 2, hint,
  1164. curses.A_STANDOUT)
  1165. self.screen.getkey()
  1166. def _show_help_interactive(self):
  1167. """Display help with list of interactive commands"""
  1168. msg = (' b toggle events by guests (debugfs only, honors'
  1169. ' filters)',
  1170. ' c clear filter',
  1171. ' f filter by regular expression',
  1172. ' g filter by guest name/PID',
  1173. ' h display interactive commands reference',
  1174. ' o toggle sorting order (Total vs CurAvg/s)',
  1175. ' p filter by guest name/PID',
  1176. ' q quit',
  1177. ' r reset stats',
  1178. ' s set delay between refreshs (value range: '
  1179. '%s-%s secs)' % (MIN_DELAY, MAX_DELAY),
  1180. ' x toggle reporting of stats for individual child trace'
  1181. ' events',
  1182. 'Any other key refreshes statistics immediately')
  1183. curses.cbreak()
  1184. self.screen.erase()
  1185. self.screen.addstr(0, 0, "Interactive commands reference",
  1186. curses.A_BOLD)
  1187. self.screen.addstr(2, 0, "Press any key to exit", curses.A_STANDOUT)
  1188. row = 4
  1189. for line in msg:
  1190. self.screen.addstr(row, 0, line)
  1191. row += 1
  1192. self.screen.getkey()
  1193. self._refresh_header()
  1194. def _show_filter_selection(self):
  1195. """Draws filter selection mask.
  1196. Asks for a valid regex and sets the fields filter accordingly.
  1197. """
  1198. msg = ''
  1199. while True:
  1200. self.screen.erase()
  1201. self.screen.addstr(0, 0,
  1202. "Show statistics for events matching a regex.",
  1203. curses.A_BOLD)
  1204. self.screen.addstr(2, 0,
  1205. "Current regex: {0}"
  1206. .format(self.stats.fields_filter))
  1207. self.screen.addstr(5, 0, msg)
  1208. self.screen.addstr(3, 0, "New regex: ")
  1209. curses.echo()
  1210. regex = self.screen.getstr().decode(ENCODING)
  1211. curses.noecho()
  1212. if len(regex) == 0:
  1213. self.stats.fields_filter = ''
  1214. self._refresh_header()
  1215. return
  1216. try:
  1217. re.compile(regex)
  1218. self.stats.fields_filter = regex
  1219. self._refresh_header()
  1220. return
  1221. except re.error:
  1222. msg = '"' + regex + '": Not a valid regular expression'
  1223. continue
  1224. def _show_set_update_interval(self):
  1225. """Draws update interval selection mask."""
  1226. msg = ''
  1227. while True:
  1228. self.screen.erase()
  1229. self.screen.addstr(0, 0, 'Set update interval (defaults to %.1fs).'
  1230. % DELAY_DEFAULT, curses.A_BOLD)
  1231. self.screen.addstr(4, 0, msg)
  1232. self.screen.addstr(2, 0, 'Change delay from %.1fs to ' %
  1233. self._delay_regular)
  1234. curses.echo()
  1235. val = self.screen.getstr().decode(ENCODING)
  1236. curses.noecho()
  1237. try:
  1238. if len(val) > 0:
  1239. delay = float(val)
  1240. err = is_delay_valid(delay)
  1241. if err is not None:
  1242. msg = err
  1243. continue
  1244. else:
  1245. delay = DELAY_DEFAULT
  1246. self._delay_regular = delay
  1247. break
  1248. except ValueError:
  1249. msg = '"' + str(val) + '": Invalid value'
  1250. self._refresh_header()
  1251. def _is_running_guest(self, pid):
  1252. """Check if pid is still a running process."""
  1253. if not pid:
  1254. return True
  1255. return os.path.isdir(os.path.join('/proc/', str(pid)))
  1256. def _show_vm_selection_by_guest(self):
  1257. """Draws guest selection mask.
  1258. Asks for a guest name or pid until a valid guest name or '' is entered.
  1259. """
  1260. msg = ''
  1261. while True:
  1262. self.screen.erase()
  1263. self.screen.addstr(0, 0,
  1264. 'Show statistics for specific guest or pid.',
  1265. curses.A_BOLD)
  1266. self.screen.addstr(1, 0,
  1267. 'This might limit the shown data to the trace '
  1268. 'statistics.')
  1269. self.screen.addstr(5, 0, msg)
  1270. self._print_all_gnames(7)
  1271. curses.echo()
  1272. curses.curs_set(1)
  1273. self.screen.addstr(3, 0, "Guest or pid [ENTER exits]: ")
  1274. guest = self.screen.getstr().decode(ENCODING)
  1275. curses.noecho()
  1276. pid = 0
  1277. if not guest or guest == '0':
  1278. break
  1279. if guest.isdigit():
  1280. if not self._is_running_guest(guest):
  1281. msg = '"' + guest + '": Not a running process'
  1282. continue
  1283. pid = int(guest)
  1284. break
  1285. pids = []
  1286. try:
  1287. pids = self.get_pid_from_gname(guest)
  1288. except:
  1289. msg = '"' + guest + '": Internal error while searching, ' \
  1290. 'use pid filter instead'
  1291. continue
  1292. if len(pids) == 0:
  1293. msg = '"' + guest + '": Not an active guest'
  1294. continue
  1295. if len(pids) > 1:
  1296. msg = '"' + guest + '": Multiple matches found, use pid ' \
  1297. 'filter instead'
  1298. continue
  1299. pid = pids[0]
  1300. break
  1301. curses.curs_set(0)
  1302. self._refresh_header(pid)
  1303. self._update_pid(pid)
  1304. def show_stats(self):
  1305. """Refreshes the screen and processes user input."""
  1306. sleeptime = self._delay_initial
  1307. self._refresh_header()
  1308. start = 0.0 # result based on init value never appears on screen
  1309. while True:
  1310. self._refresh_body(time.time() - start)
  1311. curses.halfdelay(int(sleeptime * 10))
  1312. start = time.time()
  1313. sleeptime = self._delay_regular
  1314. try:
  1315. char = self.screen.getkey()
  1316. if char == 'b':
  1317. self._display_guests = not self._display_guests
  1318. if self.stats.toggle_display_guests(self._display_guests):
  1319. self._show_msg(['Command not available with '
  1320. 'tracepoints enabled', 'Restart with '
  1321. 'debugfs only (see option \'-d\') and '
  1322. 'try again!'])
  1323. self._display_guests = not self._display_guests
  1324. self._refresh_header()
  1325. if char == 'c':
  1326. self.stats.fields_filter = ''
  1327. self._refresh_header(0)
  1328. self._update_pid(0)
  1329. if char == 'f':
  1330. curses.curs_set(1)
  1331. self._show_filter_selection()
  1332. curses.curs_set(0)
  1333. sleeptime = self._delay_initial
  1334. if char == 'g' or char == 'p':
  1335. self._show_vm_selection_by_guest()
  1336. sleeptime = self._delay_initial
  1337. if char == 'h':
  1338. self._show_help_interactive()
  1339. if char == 'o':
  1340. self._sorting = not self._sorting
  1341. if char == 'q':
  1342. break
  1343. if char == 'r':
  1344. self.stats.reset()
  1345. if char == 's':
  1346. curses.curs_set(1)
  1347. self._show_set_update_interval()
  1348. curses.curs_set(0)
  1349. sleeptime = self._delay_initial
  1350. if char == 'x':
  1351. self.stats.child_events = not self.stats.child_events
  1352. except KeyboardInterrupt:
  1353. break
  1354. except curses.error:
  1355. continue
  1356. def batch(stats):
  1357. """Prints statistics in a key, value format."""
  1358. try:
  1359. s = stats.get()
  1360. time.sleep(1)
  1361. s = stats.get()
  1362. for key, values in sorted(s.items()):
  1363. print('%-42s%10d%10d' % (key.split(' ')[0], values.value,
  1364. values.delta))
  1365. except KeyboardInterrupt:
  1366. pass
  1367. class StdFormat(object):
  1368. def __init__(self, keys):
  1369. self._banner = ''
  1370. for key in keys:
  1371. self._banner += key.split(' ')[0] + ' '
  1372. def get_banner(self):
  1373. return self._banner
  1374. def get_statline(self, keys, s):
  1375. res = ''
  1376. for key in keys:
  1377. res += ' %9d' % s[key].delta
  1378. return res
  1379. class CSVFormat(object):
  1380. def __init__(self, keys):
  1381. self._banner = 'timestamp'
  1382. self._banner += reduce(lambda res, key: "{},{!s}".format(res,
  1383. key.split(' ')[0]), keys, '')
  1384. def get_banner(self):
  1385. return self._banner
  1386. def get_statline(self, keys, s):
  1387. return reduce(lambda res, key: "{},{!s}".format(res, s[key].delta),
  1388. keys, '')
  1389. def log(stats, opts, frmt, keys):
  1390. """Prints statistics as reiterating key block, multiple value blocks."""
  1391. global signal_received
  1392. line = 0
  1393. banner_repeat = 20
  1394. f = None
  1395. def do_banner(opts):
  1396. nonlocal f
  1397. if opts.log_to_file:
  1398. if not f:
  1399. try:
  1400. f = open(opts.log_to_file, 'a')
  1401. except (IOError, OSError):
  1402. sys.exit("Error: Could not open file: %s" %
  1403. opts.log_to_file)
  1404. if isinstance(frmt, CSVFormat) and f.tell() != 0:
  1405. return
  1406. print(frmt.get_banner(), file=f or sys.stdout)
  1407. def do_statline(opts, values):
  1408. statline = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + \
  1409. frmt.get_statline(keys, values)
  1410. print(statline, file=f or sys.stdout)
  1411. do_banner(opts)
  1412. banner_printed = True
  1413. while True:
  1414. try:
  1415. time.sleep(opts.set_delay)
  1416. if signal_received:
  1417. banner_printed = True
  1418. line = 0
  1419. f.close()
  1420. do_banner(opts)
  1421. signal_received = False
  1422. if (line % banner_repeat == 0 and not banner_printed and
  1423. not (opts.log_to_file and isinstance(frmt, CSVFormat))):
  1424. do_banner(opts)
  1425. banner_printed = True
  1426. values = stats.get()
  1427. if (not opts.skip_zero_records or
  1428. any(values[k].delta != 0 for k in keys)):
  1429. do_statline(opts, values)
  1430. line += 1
  1431. banner_printed = False
  1432. except KeyboardInterrupt:
  1433. break
  1434. if opts.log_to_file:
  1435. f.close()
  1436. def handle_signal(sig, frame):
  1437. global signal_received
  1438. signal_received = True
  1439. return
  1440. def is_delay_valid(delay):
  1441. """Verify delay is in valid value range."""
  1442. msg = None
  1443. if delay < MIN_DELAY:
  1444. msg = '"' + str(delay) + '": Delay must be >=%s' % MIN_DELAY
  1445. if delay > MAX_DELAY:
  1446. msg = '"' + str(delay) + '": Delay must be <=%s' % MAX_DELAY
  1447. return msg
  1448. def get_options():
  1449. """Returns processed program arguments."""
  1450. description_text = """
  1451. This script displays various statistics about VMs running under KVM.
  1452. The statistics are gathered from the KVM debugfs entries and / or the
  1453. currently available perf traces.
  1454. The monitoring takes additional cpu cycles and might affect the VM's
  1455. performance.
  1456. Requirements:
  1457. - Access to:
  1458. %s
  1459. %s/events/*
  1460. /proc/pid/task
  1461. - /proc/sys/kernel/perf_event_paranoid < 1 if user has no
  1462. CAP_SYS_ADMIN and perf events are used.
  1463. - CAP_SYS_RESOURCE if the hard limit is not high enough to allow
  1464. the large number of files that are possibly opened.
  1465. Interactive Commands:
  1466. b toggle events by guests (debugfs only, honors filters)
  1467. c clear filter
  1468. f filter by regular expression
  1469. g filter by guest name
  1470. h display interactive commands reference
  1471. o toggle sorting order (Total vs CurAvg/s)
  1472. p filter by PID
  1473. q quit
  1474. r reset stats
  1475. s set update interval (value range: 0.1-25.5 secs)
  1476. x toggle reporting of stats for individual child trace events
  1477. Press any other key to refresh statistics immediately.
  1478. """ % (PATH_DEBUGFS_KVM, PATH_DEBUGFS_TRACING)
  1479. class Guest_to_pid(argparse.Action):
  1480. def __call__(self, parser, namespace, values, option_string=None):
  1481. try:
  1482. pids = Tui.get_pid_from_gname(values)
  1483. except:
  1484. sys.exit('Error while searching for guest "{}". Use "-p" to '
  1485. 'specify a pid instead?'.format(values))
  1486. if len(pids) == 0:
  1487. sys.exit('Error: No guest by the name "{}" found'
  1488. .format(values))
  1489. if len(pids) > 1:
  1490. sys.exit('Error: Multiple processes found (pids: {}). Use "-p"'
  1491. ' to specify the desired pid'
  1492. .format(" ".join(map(str, pids))))
  1493. namespace.pid = pids[0]
  1494. argparser = argparse.ArgumentParser(description=description_text,
  1495. formatter_class=argparse
  1496. .RawTextHelpFormatter)
  1497. argparser.add_argument('-1', '--once', '--batch',
  1498. action='store_true',
  1499. default=False,
  1500. help='run in batch mode for one second',
  1501. )
  1502. argparser.add_argument('-c', '--csv',
  1503. action='store_true',
  1504. default=False,
  1505. help='log in csv format - requires option -l/-L',
  1506. )
  1507. argparser.add_argument('-d', '--debugfs',
  1508. action='store_true',
  1509. default=False,
  1510. help='retrieve statistics from debugfs',
  1511. )
  1512. argparser.add_argument('-f', '--fields',
  1513. default='',
  1514. help='''fields to display (regex)
  1515. "-f help" for a list of available events''',
  1516. )
  1517. argparser.add_argument('-g', '--guest',
  1518. type=str,
  1519. help='restrict statistics to guest by name',
  1520. action=Guest_to_pid,
  1521. )
  1522. argparser.add_argument('-i', '--debugfs-include-past',
  1523. action='store_true',
  1524. default=False,
  1525. help='include all available data on past events for'
  1526. ' debugfs',
  1527. )
  1528. argparser.add_argument('-l', '--log',
  1529. action='store_true',
  1530. default=False,
  1531. help='run in logging mode (like vmstat)',
  1532. )
  1533. argparser.add_argument('-L', '--log-to-file',
  1534. type=str,
  1535. metavar='FILE',
  1536. help="like '--log', but logging to a file"
  1537. )
  1538. argparser.add_argument('-p', '--pid',
  1539. type=int,
  1540. default=0,
  1541. help='restrict statistics to pid',
  1542. )
  1543. argparser.add_argument('-s', '--set-delay',
  1544. type=float,
  1545. default=DELAY_DEFAULT,
  1546. metavar='DELAY',
  1547. help='set delay between refreshs (value range: '
  1548. '%s-%s secs)' % (MIN_DELAY, MAX_DELAY),
  1549. )
  1550. argparser.add_argument('-t', '--tracepoints',
  1551. action='store_true',
  1552. default=False,
  1553. help='retrieve statistics from tracepoints',
  1554. )
  1555. argparser.add_argument('-z', '--skip-zero-records',
  1556. action='store_true',
  1557. default=False,
  1558. help='omit records with all zeros in logging mode',
  1559. )
  1560. options = argparser.parse_args()
  1561. if options.csv and not (options.log or options.log_to_file):
  1562. sys.exit('Error: Option -c/--csv requires -l/--log')
  1563. if options.skip_zero_records and not (options.log or options.log_to_file):
  1564. sys.exit('Error: Option -z/--skip-zero-records requires -l/-L')
  1565. try:
  1566. # verify that we were passed a valid regex up front
  1567. re.compile(options.fields)
  1568. except re.error:
  1569. sys.exit('Error: "' + options.fields + '" is not a valid regular '
  1570. 'expression')
  1571. return options
  1572. def check_access(options):
  1573. """Exits if the current user can't access all needed directories."""
  1574. if not os.path.exists(PATH_DEBUGFS_TRACING) and (options.tracepoints or
  1575. not options.debugfs):
  1576. sys.stderr.write("Please enable CONFIG_TRACING in your kernel "
  1577. "when using the option -t (default).\n"
  1578. "If it is enabled, make {0} readable by the "
  1579. "current user.\n"
  1580. .format(PATH_DEBUGFS_TRACING))
  1581. if options.tracepoints:
  1582. sys.exit(1)
  1583. sys.stderr.write("Falling back to debugfs statistics!\n")
  1584. options.debugfs = True
  1585. time.sleep(5)
  1586. return options
  1587. def assign_globals():
  1588. global PATH_DEBUGFS_KVM
  1589. global PATH_DEBUGFS_TRACING
  1590. debugfs = ''
  1591. for line in open('/proc/mounts'):
  1592. if line.split(' ')[2] == 'debugfs':
  1593. debugfs = line.split(' ')[1]
  1594. break
  1595. if debugfs == '':
  1596. sys.stderr.write("Please make sure that CONFIG_DEBUG_FS is enabled in "
  1597. "your kernel, mounted and\nreadable by the current "
  1598. "user:\n"
  1599. "('mount -t debugfs debugfs /sys/kernel/debug')\n")
  1600. sys.exit(1)
  1601. PATH_DEBUGFS_KVM = os.path.join(debugfs, 'kvm')
  1602. PATH_DEBUGFS_TRACING = os.path.join(debugfs, 'tracing')
  1603. if not os.path.exists(PATH_DEBUGFS_KVM):
  1604. sys.stderr.write("Please make sure that CONFIG_KVM is enabled in "
  1605. "your kernel and that the modules are loaded.\n")
  1606. sys.exit(1)
  1607. def main():
  1608. assign_globals()
  1609. options = get_options()
  1610. options = check_access(options)
  1611. if (options.pid > 0 and
  1612. not os.path.isdir(os.path.join('/proc/',
  1613. str(options.pid)))):
  1614. sys.stderr.write('Did you use a (unsupported) tid instead of a pid?\n')
  1615. sys.exit('Specified pid does not exist.')
  1616. err = is_delay_valid(options.set_delay)
  1617. if err is not None:
  1618. sys.exit('Error: ' + err)
  1619. stats = Stats(options)
  1620. if options.fields == 'help':
  1621. stats.fields_filter = None
  1622. event_list = []
  1623. for key in stats.get().keys():
  1624. event_list.append(key.split('(', 1)[0])
  1625. sys.stdout.write(' ' + '\n '.join(sorted(set(event_list))) + '\n')
  1626. sys.exit(0)
  1627. if options.log or options.log_to_file:
  1628. if options.log_to_file:
  1629. signal.signal(signal.SIGHUP, handle_signal)
  1630. keys = sorted(stats.get().keys())
  1631. if options.csv:
  1632. frmt = CSVFormat(keys)
  1633. else:
  1634. frmt = StdFormat(keys)
  1635. log(stats, options, frmt, keys)
  1636. elif not options.once:
  1637. with Tui(stats, options) as tui:
  1638. tui.show_stats()
  1639. else:
  1640. batch(stats)
  1641. if __name__ == "__main__":
  1642. main()