_pslinux.py 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096
  1. # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. """Linux platform implementation."""
  5. from __future__ import division
  6. import base64
  7. import collections
  8. import errno
  9. import functools
  10. import glob
  11. import os
  12. import re
  13. import socket
  14. import struct
  15. import sys
  16. import traceback
  17. import warnings
  18. from collections import defaultdict
  19. from collections import namedtuple
  20. from . import _common
  21. from . import _psposix
  22. from . import _psutil_linux as cext
  23. from . import _psutil_posix as cext_posix
  24. from ._common import AccessDenied
  25. from ._common import debug
  26. from ._common import decode
  27. from ._common import get_procfs_path
  28. from ._common import isfile_strict
  29. from ._common import memoize
  30. from ._common import memoize_when_activated
  31. from ._common import NIC_DUPLEX_FULL
  32. from ._common import NIC_DUPLEX_HALF
  33. from ._common import NIC_DUPLEX_UNKNOWN
  34. from ._common import NoSuchProcess
  35. from ._common import open_binary
  36. from ._common import open_text
  37. from ._common import parse_environ_block
  38. from ._common import path_exists_strict
  39. from ._common import supports_ipv6
  40. from ._common import usage_percent
  41. from ._common import ZombieProcess
  42. from ._compat import b
  43. from ._compat import basestring
  44. from ._compat import FileNotFoundError
  45. from ._compat import PermissionError
  46. from ._compat import ProcessLookupError
  47. from ._compat import PY3
  48. if sys.version_info >= (3, 4):
  49. import enum
  50. else:
  51. enum = None
  52. __extra__all__ = [
  53. #
  54. 'PROCFS_PATH',
  55. # io prio constants
  56. "IOPRIO_CLASS_NONE", "IOPRIO_CLASS_RT", "IOPRIO_CLASS_BE",
  57. "IOPRIO_CLASS_IDLE",
  58. # connection status constants
  59. "CONN_ESTABLISHED", "CONN_SYN_SENT", "CONN_SYN_RECV", "CONN_FIN_WAIT1",
  60. "CONN_FIN_WAIT2", "CONN_TIME_WAIT", "CONN_CLOSE", "CONN_CLOSE_WAIT",
  61. "CONN_LAST_ACK", "CONN_LISTEN", "CONN_CLOSING", ]
  62. # =====================================================================
  63. # --- globals
  64. # =====================================================================
  65. POWER_SUPPLY_PATH = "/sys/class/power_supply"
  66. HAS_SMAPS = os.path.exists('/proc/%s/smaps' % os.getpid())
  67. HAS_PRLIMIT = hasattr(cext, "linux_prlimit")
  68. HAS_PROC_IO_PRIORITY = hasattr(cext, "proc_ioprio_get")
  69. HAS_CPU_AFFINITY = hasattr(cext, "proc_cpu_affinity_get")
  70. _DEFAULT = object()
  71. # Number of clock ticks per second
  72. CLOCK_TICKS = os.sysconf("SC_CLK_TCK")
  73. PAGESIZE = os.sysconf("SC_PAGE_SIZE")
  74. BOOT_TIME = None # set later
  75. # Used when reading "big" files, namely /proc/{pid}/smaps and /proc/net/*.
  76. # On Python 2, using a buffer with open() for such files may result in a
  77. # speedup, see: https://github.com/giampaolo/psutil/issues/708
  78. BIGFILE_BUFFERING = -1 if PY3 else 8192
  79. LITTLE_ENDIAN = sys.byteorder == 'little'
  80. # "man iostat" states that sectors are equivalent with blocks and have
  81. # a size of 512 bytes. Despite this value can be queried at runtime
  82. # via /sys/block/{DISK}/queue/hw_sector_size and results may vary
  83. # between 1k, 2k, or 4k... 512 appears to be a magic constant used
  84. # throughout Linux source code:
  85. # * https://stackoverflow.com/a/38136179/376587
  86. # * https://lists.gt.net/linux/kernel/2241060
  87. # * https://github.com/giampaolo/psutil/issues/1305
  88. # * https://github.com/torvalds/linux/blob/
  89. # 4f671fe2f9523a1ea206f63fe60a7c7b3a56d5c7/include/linux/bio.h#L99
  90. # * https://lkml.org/lkml/2015/8/17/234
  91. DISK_SECTOR_SIZE = 512
  92. if enum is None:
  93. AF_LINK = socket.AF_PACKET
  94. else:
  95. AddressFamily = enum.IntEnum('AddressFamily',
  96. {'AF_LINK': int(socket.AF_PACKET)})
  97. AF_LINK = AddressFamily.AF_LINK
  98. # ioprio_* constants http://linux.die.net/man/2/ioprio_get
  99. if enum is None:
  100. IOPRIO_CLASS_NONE = 0
  101. IOPRIO_CLASS_RT = 1
  102. IOPRIO_CLASS_BE = 2
  103. IOPRIO_CLASS_IDLE = 3
  104. else:
  105. class IOPriority(enum.IntEnum):
  106. IOPRIO_CLASS_NONE = 0
  107. IOPRIO_CLASS_RT = 1
  108. IOPRIO_CLASS_BE = 2
  109. IOPRIO_CLASS_IDLE = 3
  110. globals().update(IOPriority.__members__)
  111. # See:
  112. # https://github.com/torvalds/linux/blame/master/fs/proc/array.c
  113. # ...and (TASK_* constants):
  114. # https://github.com/torvalds/linux/blob/master/include/linux/sched.h
  115. PROC_STATUSES = {
  116. "R": _common.STATUS_RUNNING,
  117. "S": _common.STATUS_SLEEPING,
  118. "D": _common.STATUS_DISK_SLEEP,
  119. "T": _common.STATUS_STOPPED,
  120. "t": _common.STATUS_TRACING_STOP,
  121. "Z": _common.STATUS_ZOMBIE,
  122. "X": _common.STATUS_DEAD,
  123. "x": _common.STATUS_DEAD,
  124. "K": _common.STATUS_WAKE_KILL,
  125. "W": _common.STATUS_WAKING,
  126. "I": _common.STATUS_IDLE,
  127. "P": _common.STATUS_PARKED,
  128. }
  129. # https://github.com/torvalds/linux/blob/master/include/net/tcp_states.h
  130. TCP_STATUSES = {
  131. "01": _common.CONN_ESTABLISHED,
  132. "02": _common.CONN_SYN_SENT,
  133. "03": _common.CONN_SYN_RECV,
  134. "04": _common.CONN_FIN_WAIT1,
  135. "05": _common.CONN_FIN_WAIT2,
  136. "06": _common.CONN_TIME_WAIT,
  137. "07": _common.CONN_CLOSE,
  138. "08": _common.CONN_CLOSE_WAIT,
  139. "09": _common.CONN_LAST_ACK,
  140. "0A": _common.CONN_LISTEN,
  141. "0B": _common.CONN_CLOSING
  142. }
  143. # =====================================================================
  144. # --- named tuples
  145. # =====================================================================
  146. # psutil.virtual_memory()
  147. svmem = namedtuple(
  148. 'svmem', ['total', 'available', 'percent', 'used', 'free',
  149. 'active', 'inactive', 'buffers', 'cached', 'shared', 'slab'])
  150. # psutil.disk_io_counters()
  151. sdiskio = namedtuple(
  152. 'sdiskio', ['read_count', 'write_count',
  153. 'read_bytes', 'write_bytes',
  154. 'read_time', 'write_time',
  155. 'read_merged_count', 'write_merged_count',
  156. 'busy_time'])
  157. # psutil.Process().open_files()
  158. popenfile = namedtuple(
  159. 'popenfile', ['path', 'fd', 'position', 'mode', 'flags'])
  160. # psutil.Process().memory_info()
  161. pmem = namedtuple('pmem', 'rss vms shared text lib data dirty')
  162. # psutil.Process().memory_full_info()
  163. pfullmem = namedtuple('pfullmem', pmem._fields + ('uss', 'pss', 'swap'))
  164. # psutil.Process().memory_maps(grouped=True)
  165. pmmap_grouped = namedtuple(
  166. 'pmmap_grouped',
  167. ['path', 'rss', 'size', 'pss', 'shared_clean', 'shared_dirty',
  168. 'private_clean', 'private_dirty', 'referenced', 'anonymous', 'swap'])
  169. # psutil.Process().memory_maps(grouped=False)
  170. pmmap_ext = namedtuple(
  171. 'pmmap_ext', 'addr perms ' + ' '.join(pmmap_grouped._fields))
  172. # psutil.Process.io_counters()
  173. pio = namedtuple('pio', ['read_count', 'write_count',
  174. 'read_bytes', 'write_bytes',
  175. 'read_chars', 'write_chars'])
  176. # psutil.Process.cpu_times()
  177. pcputimes = namedtuple('pcputimes',
  178. ['user', 'system', 'children_user', 'children_system',
  179. 'iowait'])
  180. # =====================================================================
  181. # --- utils
  182. # =====================================================================
  183. def readlink(path):
  184. """Wrapper around os.readlink()."""
  185. assert isinstance(path, basestring), path
  186. path = os.readlink(path)
  187. # readlink() might return paths containing null bytes ('\x00')
  188. # resulting in "TypeError: must be encoded string without NULL
  189. # bytes, not str" errors when the string is passed to other
  190. # fs-related functions (os.*, open(), ...).
  191. # Apparently everything after '\x00' is garbage (we can have
  192. # ' (deleted)', 'new' and possibly others), see:
  193. # https://github.com/giampaolo/psutil/issues/717
  194. path = path.split('\x00')[0]
  195. # Certain paths have ' (deleted)' appended. Usually this is
  196. # bogus as the file actually exists. Even if it doesn't we
  197. # don't care.
  198. if path.endswith(' (deleted)') and not path_exists_strict(path):
  199. path = path[:-10]
  200. return path
  201. def file_flags_to_mode(flags):
  202. """Convert file's open() flags into a readable string.
  203. Used by Process.open_files().
  204. """
  205. modes_map = {os.O_RDONLY: 'r', os.O_WRONLY: 'w', os.O_RDWR: 'w+'}
  206. mode = modes_map[flags & (os.O_RDONLY | os.O_WRONLY | os.O_RDWR)]
  207. if flags & os.O_APPEND:
  208. mode = mode.replace('w', 'a', 1)
  209. mode = mode.replace('w+', 'r+')
  210. # possible values: r, w, a, r+, a+
  211. return mode
  212. def is_storage_device(name):
  213. """Return True if the given name refers to a root device (e.g.
  214. "sda", "nvme0n1") as opposed to a logical partition (e.g. "sda1",
  215. "nvme0n1p1"). If name is a virtual device (e.g. "loop1", "ram")
  216. return True.
  217. """
  218. # Readapted from iostat source code, see:
  219. # https://github.com/sysstat/sysstat/blob/
  220. # 97912938cd476645b267280069e83b1c8dc0e1c7/common.c#L208
  221. # Some devices may have a slash in their name (e.g. cciss/c0d0...).
  222. name = name.replace('/', '!')
  223. including_virtual = True
  224. if including_virtual:
  225. path = "/sys/block/%s" % name
  226. else:
  227. path = "/sys/block/%s/device" % name
  228. return os.access(path, os.F_OK)
  229. @memoize
  230. def set_scputimes_ntuple(procfs_path):
  231. """Set a namedtuple of variable fields depending on the CPU times
  232. available on this Linux kernel version which may be:
  233. (user, nice, system, idle, iowait, irq, softirq, [steal, [guest,
  234. [guest_nice]]])
  235. Used by cpu_times() function.
  236. """
  237. global scputimes
  238. with open_binary('%s/stat' % procfs_path) as f:
  239. values = f.readline().split()[1:]
  240. fields = ['user', 'nice', 'system', 'idle', 'iowait', 'irq', 'softirq']
  241. vlen = len(values)
  242. if vlen >= 8:
  243. # Linux >= 2.6.11
  244. fields.append('steal')
  245. if vlen >= 9:
  246. # Linux >= 2.6.24
  247. fields.append('guest')
  248. if vlen >= 10:
  249. # Linux >= 3.2.0
  250. fields.append('guest_nice')
  251. scputimes = namedtuple('scputimes', fields)
  252. def cat(fname, fallback=_DEFAULT, binary=True):
  253. """Return file content.
  254. fallback: the value returned in case the file does not exist or
  255. cannot be read
  256. binary: whether to open the file in binary or text mode.
  257. """
  258. try:
  259. with open_binary(fname) if binary else open_text(fname) as f:
  260. return f.read().strip()
  261. except (IOError, OSError):
  262. if fallback is not _DEFAULT:
  263. return fallback
  264. else:
  265. raise
  266. try:
  267. set_scputimes_ntuple("/proc")
  268. except Exception: # pragma: no cover
  269. # Don't want to crash at import time.
  270. traceback.print_exc()
  271. scputimes = namedtuple('scputimes', 'user system idle')(0.0, 0.0, 0.0)
  272. # =====================================================================
  273. # --- system memory
  274. # =====================================================================
  275. def calculate_avail_vmem(mems):
  276. """Fallback for kernels < 3.14 where /proc/meminfo does not provide
  277. "MemAvailable:" column, see:
  278. https://blog.famzah.net/2014/09/24/
  279. This code reimplements the algorithm outlined here:
  280. https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/
  281. commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773
  282. XXX: on recent kernels this calculation differs by ~1.5% than
  283. "MemAvailable:" as it's calculated slightly differently, see:
  284. https://gitlab.com/procps-ng/procps/issues/42
  285. https://github.com/famzah/linux-memavailable-procfs/issues/2
  286. It is still way more realistic than doing (free + cached) though.
  287. """
  288. # Fallback for very old distros. According to
  289. # https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/
  290. # commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773
  291. # ...long ago "avail" was calculated as (free + cached).
  292. # We might fallback in such cases:
  293. # "Active(file)" not available: 2.6.28 / Dec 2008
  294. # "Inactive(file)" not available: 2.6.28 / Dec 2008
  295. # "SReclaimable:" not available: 2.6.19 / Nov 2006
  296. # /proc/zoneinfo not available: 2.6.13 / Aug 2005
  297. free = mems[b'MemFree:']
  298. fallback = free + mems.get(b"Cached:", 0)
  299. try:
  300. lru_active_file = mems[b'Active(file):']
  301. lru_inactive_file = mems[b'Inactive(file):']
  302. slab_reclaimable = mems[b'SReclaimable:']
  303. except KeyError:
  304. return fallback
  305. try:
  306. f = open_binary('%s/zoneinfo' % get_procfs_path())
  307. except IOError:
  308. return fallback # kernel 2.6.13
  309. watermark_low = 0
  310. with f:
  311. for line in f:
  312. line = line.strip()
  313. if line.startswith(b'low'):
  314. watermark_low += int(line.split()[1])
  315. watermark_low *= PAGESIZE
  316. avail = free - watermark_low
  317. pagecache = lru_active_file + lru_inactive_file
  318. pagecache -= min(pagecache / 2, watermark_low)
  319. avail += pagecache
  320. avail += slab_reclaimable - min(slab_reclaimable / 2.0, watermark_low)
  321. return int(avail)
  322. def virtual_memory():
  323. """Report virtual memory stats.
  324. This implementation matches "free" and "vmstat -s" cmdline
  325. utility values and procps-ng-3.3.12 source was used as a reference
  326. (2016-09-18):
  327. https://gitlab.com/procps-ng/procps/blob/
  328. 24fd2605c51fccc375ab0287cec33aa767f06718/proc/sysinfo.c
  329. For reference, procps-ng-3.3.10 is the version available on Ubuntu
  330. 16.04.
  331. Note about "available" memory: up until psutil 4.3 it was
  332. calculated as "avail = (free + buffers + cached)". Now
  333. "MemAvailable:" column (kernel 3.14) from /proc/meminfo is used as
  334. it's more accurate.
  335. That matches "available" column in newer versions of "free".
  336. """
  337. missing_fields = []
  338. mems = {}
  339. with open_binary('%s/meminfo' % get_procfs_path()) as f:
  340. for line in f:
  341. fields = line.split()
  342. mems[fields[0]] = int(fields[1]) * 1024
  343. # /proc doc states that the available fields in /proc/meminfo vary
  344. # by architecture and compile options, but these 3 values are also
  345. # returned by sysinfo(2); as such we assume they are always there.
  346. total = mems[b'MemTotal:']
  347. free = mems[b'MemFree:']
  348. try:
  349. buffers = mems[b'Buffers:']
  350. except KeyError:
  351. # https://github.com/giampaolo/psutil/issues/1010
  352. buffers = 0
  353. missing_fields.append('buffers')
  354. try:
  355. cached = mems[b"Cached:"]
  356. except KeyError:
  357. cached = 0
  358. missing_fields.append('cached')
  359. else:
  360. # "free" cmdline utility sums reclaimable to cached.
  361. # Older versions of procps used to add slab memory instead.
  362. # This got changed in:
  363. # https://gitlab.com/procps-ng/procps/commit/
  364. # 05d751c4f076a2f0118b914c5e51cfbb4762ad8e
  365. cached += mems.get(b"SReclaimable:", 0) # since kernel 2.6.19
  366. try:
  367. shared = mems[b'Shmem:'] # since kernel 2.6.32
  368. except KeyError:
  369. try:
  370. shared = mems[b'MemShared:'] # kernels 2.4
  371. except KeyError:
  372. shared = 0
  373. missing_fields.append('shared')
  374. try:
  375. active = mems[b"Active:"]
  376. except KeyError:
  377. active = 0
  378. missing_fields.append('active')
  379. try:
  380. inactive = mems[b"Inactive:"]
  381. except KeyError:
  382. try:
  383. inactive = \
  384. mems[b"Inact_dirty:"] + \
  385. mems[b"Inact_clean:"] + \
  386. mems[b"Inact_laundry:"]
  387. except KeyError:
  388. inactive = 0
  389. missing_fields.append('inactive')
  390. try:
  391. slab = mems[b"Slab:"]
  392. except KeyError:
  393. slab = 0
  394. used = total - free - cached - buffers
  395. if used < 0:
  396. # May be symptomatic of running within a LCX container where such
  397. # values will be dramatically distorted over those of the host.
  398. used = total - free
  399. # - starting from 4.4.0 we match free's "available" column.
  400. # Before 4.4.0 we calculated it as (free + buffers + cached)
  401. # which matched htop.
  402. # - free and htop available memory differs as per:
  403. # http://askubuntu.com/a/369589
  404. # http://unix.stackexchange.com/a/65852/168884
  405. # - MemAvailable has been introduced in kernel 3.14
  406. try:
  407. avail = mems[b'MemAvailable:']
  408. except KeyError:
  409. avail = calculate_avail_vmem(mems)
  410. if avail < 0:
  411. avail = 0
  412. missing_fields.append('available')
  413. # If avail is greater than total or our calculation overflows,
  414. # that's symptomatic of running within a LCX container where such
  415. # values will be dramatically distorted over those of the host.
  416. # https://gitlab.com/procps-ng/procps/blob/
  417. # 24fd2605c51fccc375ab0287cec33aa767f06718/proc/sysinfo.c#L764
  418. if avail > total:
  419. avail = free
  420. percent = usage_percent((total - avail), total, round_=1)
  421. # Warn about missing metrics which are set to 0.
  422. if missing_fields:
  423. msg = "%s memory stats couldn't be determined and %s set to 0" % (
  424. ", ".join(missing_fields),
  425. "was" if len(missing_fields) == 1 else "were")
  426. warnings.warn(msg, RuntimeWarning)
  427. return svmem(total, avail, percent, used, free,
  428. active, inactive, buffers, cached, shared, slab)
  429. def swap_memory():
  430. """Return swap memory metrics."""
  431. mems = {}
  432. with open_binary('%s/meminfo' % get_procfs_path()) as f:
  433. for line in f:
  434. fields = line.split()
  435. mems[fields[0]] = int(fields[1]) * 1024
  436. # We prefer /proc/meminfo over sysinfo() syscall so that
  437. # psutil.PROCFS_PATH can be used in order to allow retrieval
  438. # for linux containers, see:
  439. # https://github.com/giampaolo/psutil/issues/1015
  440. try:
  441. total = mems[b'SwapTotal:']
  442. free = mems[b'SwapFree:']
  443. except KeyError:
  444. _, _, _, _, total, free, unit_multiplier = cext.linux_sysinfo()
  445. total *= unit_multiplier
  446. free *= unit_multiplier
  447. used = total - free
  448. percent = usage_percent(used, total, round_=1)
  449. # get pgin/pgouts
  450. try:
  451. f = open_binary("%s/vmstat" % get_procfs_path())
  452. except IOError as err:
  453. # see https://github.com/giampaolo/psutil/issues/722
  454. msg = "'sin' and 'sout' swap memory stats couldn't " \
  455. "be determined and were set to 0 (%s)" % str(err)
  456. warnings.warn(msg, RuntimeWarning)
  457. sin = sout = 0
  458. else:
  459. with f:
  460. sin = sout = None
  461. for line in f:
  462. # values are expressed in 4 kilo bytes, we want
  463. # bytes instead
  464. if line.startswith(b'pswpin'):
  465. sin = int(line.split(b' ')[1]) * 4 * 1024
  466. elif line.startswith(b'pswpout'):
  467. sout = int(line.split(b' ')[1]) * 4 * 1024
  468. if sin is not None and sout is not None:
  469. break
  470. else:
  471. # we might get here when dealing with exotic Linux
  472. # flavors, see:
  473. # https://github.com/giampaolo/psutil/issues/313
  474. msg = "'sin' and 'sout' swap memory stats couldn't " \
  475. "be determined and were set to 0"
  476. warnings.warn(msg, RuntimeWarning)
  477. sin = sout = 0
  478. return _common.sswap(total, used, free, percent, sin, sout)
  479. # =====================================================================
  480. # --- CPU
  481. # =====================================================================
  482. def cpu_times():
  483. """Return a named tuple representing the following system-wide
  484. CPU times:
  485. (user, nice, system, idle, iowait, irq, softirq [steal, [guest,
  486. [guest_nice]]])
  487. Last 3 fields may not be available on all Linux kernel versions.
  488. """
  489. procfs_path = get_procfs_path()
  490. set_scputimes_ntuple(procfs_path)
  491. with open_binary('%s/stat' % procfs_path) as f:
  492. values = f.readline().split()
  493. fields = values[1:len(scputimes._fields) + 1]
  494. fields = [float(x) / CLOCK_TICKS for x in fields]
  495. return scputimes(*fields)
  496. def per_cpu_times():
  497. """Return a list of namedtuple representing the CPU times
  498. for every CPU available on the system.
  499. """
  500. procfs_path = get_procfs_path()
  501. set_scputimes_ntuple(procfs_path)
  502. cpus = []
  503. with open_binary('%s/stat' % procfs_path) as f:
  504. # get rid of the first line which refers to system wide CPU stats
  505. f.readline()
  506. for line in f:
  507. if line.startswith(b'cpu'):
  508. values = line.split()
  509. fields = values[1:len(scputimes._fields) + 1]
  510. fields = [float(x) / CLOCK_TICKS for x in fields]
  511. entry = scputimes(*fields)
  512. cpus.append(entry)
  513. return cpus
  514. def cpu_count_logical():
  515. """Return the number of logical CPUs in the system."""
  516. try:
  517. return os.sysconf("SC_NPROCESSORS_ONLN")
  518. except ValueError:
  519. # as a second fallback we try to parse /proc/cpuinfo
  520. num = 0
  521. with open_binary('%s/cpuinfo' % get_procfs_path()) as f:
  522. for line in f:
  523. if line.lower().startswith(b'processor'):
  524. num += 1
  525. # unknown format (e.g. amrel/sparc architectures), see:
  526. # https://github.com/giampaolo/psutil/issues/200
  527. # try to parse /proc/stat as a last resort
  528. if num == 0:
  529. search = re.compile(r'cpu\d')
  530. with open_text('%s/stat' % get_procfs_path()) as f:
  531. for line in f:
  532. line = line.split(' ')[0]
  533. if search.match(line):
  534. num += 1
  535. if num == 0:
  536. # mimic os.cpu_count()
  537. return None
  538. return num
  539. def cpu_count_physical():
  540. """Return the number of physical cores in the system."""
  541. # Method #1
  542. ls = set()
  543. # These 2 files are the same but */core_cpus_list is newer while
  544. # */thread_siblings_list is deprecated and may disappear in the future.
  545. # https://www.kernel.org/doc/Documentation/admin-guide/cputopology.rst
  546. # https://github.com/giampaolo/psutil/pull/1727#issuecomment-707624964
  547. # https://lkml.org/lkml/2019/2/26/41
  548. p1 = "/sys/devices/system/cpu/cpu[0-9]*/topology/core_cpus_list"
  549. p2 = "/sys/devices/system/cpu/cpu[0-9]*/topology/thread_siblings_list"
  550. for path in glob.glob(p1) or glob.glob(p2):
  551. with open_binary(path) as f:
  552. ls.add(f.read().strip())
  553. result = len(ls)
  554. if result != 0:
  555. return result
  556. # Method #2
  557. mapping = {}
  558. current_info = {}
  559. with open_binary('%s/cpuinfo' % get_procfs_path()) as f:
  560. for line in f:
  561. line = line.strip().lower()
  562. if not line:
  563. # new section
  564. try:
  565. mapping[current_info[b'physical id']] = \
  566. current_info[b'cpu cores']
  567. except KeyError:
  568. pass
  569. current_info = {}
  570. else:
  571. # ongoing section
  572. if line.startswith((b'physical id', b'cpu cores')):
  573. key, value = line.split(b'\t:', 1)
  574. current_info[key] = int(value)
  575. result = sum(mapping.values())
  576. return result or None # mimic os.cpu_count()
  577. def cpu_stats():
  578. """Return various CPU stats as a named tuple."""
  579. with open_binary('%s/stat' % get_procfs_path()) as f:
  580. ctx_switches = None
  581. interrupts = None
  582. soft_interrupts = None
  583. for line in f:
  584. if line.startswith(b'ctxt'):
  585. ctx_switches = int(line.split()[1])
  586. elif line.startswith(b'intr'):
  587. interrupts = int(line.split()[1])
  588. elif line.startswith(b'softirq'):
  589. soft_interrupts = int(line.split()[1])
  590. if ctx_switches is not None and soft_interrupts is not None \
  591. and interrupts is not None:
  592. break
  593. syscalls = 0
  594. return _common.scpustats(
  595. ctx_switches, interrupts, soft_interrupts, syscalls)
  596. if os.path.exists("/sys/devices/system/cpu/cpufreq/policy0") or \
  597. os.path.exists("/sys/devices/system/cpu/cpu0/cpufreq"):
  598. def cpu_freq():
  599. """Return frequency metrics for all CPUs.
  600. Contrarily to other OSes, Linux updates these values in
  601. real-time.
  602. """
  603. def get_path(num):
  604. for p in ("/sys/devices/system/cpu/cpufreq/policy%s" % num,
  605. "/sys/devices/system/cpu/cpu%s/cpufreq" % num):
  606. if os.path.exists(p):
  607. return p
  608. ret = []
  609. for n in range(cpu_count_logical()):
  610. path = get_path(n)
  611. if not path:
  612. continue
  613. pjoin = os.path.join
  614. curr = cat(pjoin(path, "scaling_cur_freq"), fallback=None)
  615. if curr is None:
  616. # Likely an old RedHat, see:
  617. # https://github.com/giampaolo/psutil/issues/1071
  618. curr = cat(pjoin(path, "cpuinfo_cur_freq"), fallback=None)
  619. if curr is None:
  620. raise NotImplementedError(
  621. "can't find current frequency file")
  622. curr = int(curr) / 1000
  623. max_ = int(cat(pjoin(path, "scaling_max_freq"))) / 1000
  624. min_ = int(cat(pjoin(path, "scaling_min_freq"))) / 1000
  625. ret.append(_common.scpufreq(curr, min_, max_))
  626. return ret
  627. elif os.path.exists("/proc/cpuinfo"):
  628. def cpu_freq():
  629. """Alternate implementation using /proc/cpuinfo.
  630. min and max frequencies are not available and are set to None.
  631. """
  632. ret = []
  633. with open_binary('%s/cpuinfo' % get_procfs_path()) as f:
  634. for line in f:
  635. if line.lower().startswith(b'cpu mhz'):
  636. key, value = line.split(b':', 1)
  637. ret.append(_common.scpufreq(float(value), 0., 0.))
  638. return ret
  639. else:
  640. def cpu_freq():
  641. """Dummy implementation when none of the above files are present.
  642. """
  643. return []
  644. # =====================================================================
  645. # --- network
  646. # =====================================================================
  647. net_if_addrs = cext_posix.net_if_addrs
  648. class _Ipv6UnsupportedError(Exception):
  649. pass
  650. class Connections:
  651. """A wrapper on top of /proc/net/* files, retrieving per-process
  652. and system-wide open connections (TCP, UDP, UNIX) similarly to
  653. "netstat -an".
  654. Note: in case of UNIX sockets we're only able to determine the
  655. local endpoint/path, not the one it's connected to.
  656. According to [1] it would be possible but not easily.
  657. [1] http://serverfault.com/a/417946
  658. """
  659. def __init__(self):
  660. # The string represents the basename of the corresponding
  661. # /proc/net/{proto_name} file.
  662. tcp4 = ("tcp", socket.AF_INET, socket.SOCK_STREAM)
  663. tcp6 = ("tcp6", socket.AF_INET6, socket.SOCK_STREAM)
  664. udp4 = ("udp", socket.AF_INET, socket.SOCK_DGRAM)
  665. udp6 = ("udp6", socket.AF_INET6, socket.SOCK_DGRAM)
  666. unix = ("unix", socket.AF_UNIX, None)
  667. self.tmap = {
  668. "all": (tcp4, tcp6, udp4, udp6, unix),
  669. "tcp": (tcp4, tcp6),
  670. "tcp4": (tcp4,),
  671. "tcp6": (tcp6,),
  672. "udp": (udp4, udp6),
  673. "udp4": (udp4,),
  674. "udp6": (udp6,),
  675. "unix": (unix,),
  676. "inet": (tcp4, tcp6, udp4, udp6),
  677. "inet4": (tcp4, udp4),
  678. "inet6": (tcp6, udp6),
  679. }
  680. self._procfs_path = None
  681. def get_proc_inodes(self, pid):
  682. inodes = defaultdict(list)
  683. for fd in os.listdir("%s/%s/fd" % (self._procfs_path, pid)):
  684. try:
  685. inode = readlink("%s/%s/fd/%s" % (self._procfs_path, pid, fd))
  686. except (FileNotFoundError, ProcessLookupError):
  687. # ENOENT == file which is gone in the meantime;
  688. # os.stat('/proc/%s' % self.pid) will be done later
  689. # to force NSP (if it's the case)
  690. continue
  691. except OSError as err:
  692. if err.errno == errno.EINVAL:
  693. # not a link
  694. continue
  695. raise
  696. else:
  697. if inode.startswith('socket:['):
  698. # the process is using a socket
  699. inode = inode[8:][:-1]
  700. inodes[inode].append((pid, int(fd)))
  701. return inodes
  702. def get_all_inodes(self):
  703. inodes = {}
  704. for pid in pids():
  705. try:
  706. inodes.update(self.get_proc_inodes(pid))
  707. except (FileNotFoundError, ProcessLookupError, PermissionError):
  708. # os.listdir() is gonna raise a lot of access denied
  709. # exceptions in case of unprivileged user; that's fine
  710. # as we'll just end up returning a connection with PID
  711. # and fd set to None anyway.
  712. # Both netstat -an and lsof does the same so it's
  713. # unlikely we can do any better.
  714. # ENOENT just means a PID disappeared on us.
  715. continue
  716. return inodes
  717. @staticmethod
  718. def decode_address(addr, family):
  719. """Accept an "ip:port" address as displayed in /proc/net/*
  720. and convert it into a human readable form, like:
  721. "0500000A:0016" -> ("10.0.0.5", 22)
  722. "0000000000000000FFFF00000100007F:9E49" -> ("::ffff:127.0.0.1", 40521)
  723. The IP address portion is a little or big endian four-byte
  724. hexadecimal number; that is, the least significant byte is listed
  725. first, so we need to reverse the order of the bytes to convert it
  726. to an IP address.
  727. The port is represented as a two-byte hexadecimal number.
  728. Reference:
  729. http://linuxdevcenter.com/pub/a/linux/2000/11/16/LinuxAdmin.html
  730. """
  731. ip, port = addr.split(':')
  732. port = int(port, 16)
  733. # this usually refers to a local socket in listen mode with
  734. # no end-points connected
  735. if not port:
  736. return ()
  737. if PY3:
  738. ip = ip.encode('ascii')
  739. if family == socket.AF_INET:
  740. # see: https://github.com/giampaolo/psutil/issues/201
  741. if LITTLE_ENDIAN:
  742. ip = socket.inet_ntop(family, base64.b16decode(ip)[::-1])
  743. else:
  744. ip = socket.inet_ntop(family, base64.b16decode(ip))
  745. else: # IPv6
  746. ip = base64.b16decode(ip)
  747. try:
  748. # see: https://github.com/giampaolo/psutil/issues/201
  749. if LITTLE_ENDIAN:
  750. ip = socket.inet_ntop(
  751. socket.AF_INET6,
  752. struct.pack('>4I', *struct.unpack('<4I', ip)))
  753. else:
  754. ip = socket.inet_ntop(
  755. socket.AF_INET6,
  756. struct.pack('<4I', *struct.unpack('<4I', ip)))
  757. except ValueError:
  758. # see: https://github.com/giampaolo/psutil/issues/623
  759. if not supports_ipv6():
  760. raise _Ipv6UnsupportedError
  761. else:
  762. raise
  763. return _common.addr(ip, port)
  764. @staticmethod
  765. def process_inet(file, family, type_, inodes, filter_pid=None):
  766. """Parse /proc/net/tcp* and /proc/net/udp* files."""
  767. if file.endswith('6') and not os.path.exists(file):
  768. # IPv6 not supported
  769. return
  770. with open_text(file, buffering=BIGFILE_BUFFERING) as f:
  771. f.readline() # skip the first line
  772. for lineno, line in enumerate(f, 1):
  773. try:
  774. _, laddr, raddr, status, _, _, _, _, _, inode = \
  775. line.split()[:10]
  776. except ValueError:
  777. raise RuntimeError(
  778. "error while parsing %s; malformed line %s %r" % (
  779. file, lineno, line))
  780. if inode in inodes:
  781. # # We assume inet sockets are unique, so we error
  782. # # out if there are multiple references to the
  783. # # same inode. We won't do this for UNIX sockets.
  784. # if len(inodes[inode]) > 1 and family != socket.AF_UNIX:
  785. # raise ValueError("ambiguos inode with multiple "
  786. # "PIDs references")
  787. pid, fd = inodes[inode][0]
  788. else:
  789. pid, fd = None, -1
  790. if filter_pid is not None and filter_pid != pid:
  791. continue
  792. else:
  793. if type_ == socket.SOCK_STREAM:
  794. status = TCP_STATUSES[status]
  795. else:
  796. status = _common.CONN_NONE
  797. try:
  798. laddr = Connections.decode_address(laddr, family)
  799. raddr = Connections.decode_address(raddr, family)
  800. except _Ipv6UnsupportedError:
  801. continue
  802. yield (fd, family, type_, laddr, raddr, status, pid)
  803. @staticmethod
  804. def process_unix(file, family, inodes, filter_pid=None):
  805. """Parse /proc/net/unix files."""
  806. with open_text(file, buffering=BIGFILE_BUFFERING) as f:
  807. f.readline() # skip the first line
  808. for line in f:
  809. tokens = line.split()
  810. try:
  811. _, _, _, _, type_, _, inode = tokens[0:7]
  812. except ValueError:
  813. if ' ' not in line:
  814. # see: https://github.com/giampaolo/psutil/issues/766
  815. continue
  816. raise RuntimeError(
  817. "error while parsing %s; malformed line %r" % (
  818. file, line))
  819. if inode in inodes:
  820. # With UNIX sockets we can have a single inode
  821. # referencing many file descriptors.
  822. pairs = inodes[inode]
  823. else:
  824. pairs = [(None, -1)]
  825. for pid, fd in pairs:
  826. if filter_pid is not None and filter_pid != pid:
  827. continue
  828. else:
  829. if len(tokens) == 8:
  830. path = tokens[-1]
  831. else:
  832. path = ""
  833. type_ = _common.socktype_to_enum(int(type_))
  834. # XXX: determining the remote endpoint of a
  835. # UNIX socket on Linux is not possible, see:
  836. # https://serverfault.com/questions/252723/
  837. raddr = ""
  838. status = _common.CONN_NONE
  839. yield (fd, family, type_, path, raddr, status, pid)
  840. def retrieve(self, kind, pid=None):
  841. if kind not in self.tmap:
  842. raise ValueError("invalid %r kind argument; choose between %s"
  843. % (kind, ', '.join([repr(x) for x in self.tmap])))
  844. self._procfs_path = get_procfs_path()
  845. if pid is not None:
  846. inodes = self.get_proc_inodes(pid)
  847. if not inodes:
  848. # no connections for this process
  849. return []
  850. else:
  851. inodes = self.get_all_inodes()
  852. ret = set()
  853. for proto_name, family, type_ in self.tmap[kind]:
  854. path = "%s/net/%s" % (self._procfs_path, proto_name)
  855. if family in (socket.AF_INET, socket.AF_INET6):
  856. ls = self.process_inet(
  857. path, family, type_, inodes, filter_pid=pid)
  858. else:
  859. ls = self.process_unix(
  860. path, family, inodes, filter_pid=pid)
  861. for fd, family, type_, laddr, raddr, status, bound_pid in ls:
  862. if pid:
  863. conn = _common.pconn(fd, family, type_, laddr, raddr,
  864. status)
  865. else:
  866. conn = _common.sconn(fd, family, type_, laddr, raddr,
  867. status, bound_pid)
  868. ret.add(conn)
  869. return list(ret)
  870. _connections = Connections()
  871. def net_connections(kind='inet'):
  872. """Return system-wide open connections."""
  873. return _connections.retrieve(kind)
  874. def net_io_counters():
  875. """Return network I/O statistics for every network interface
  876. installed on the system as a dict of raw tuples.
  877. """
  878. with open_text("%s/net/dev" % get_procfs_path()) as f:
  879. lines = f.readlines()
  880. retdict = {}
  881. for line in lines[2:]:
  882. colon = line.rfind(':')
  883. assert colon > 0, repr(line)
  884. name = line[:colon].strip()
  885. fields = line[colon + 1:].strip().split()
  886. # in
  887. (bytes_recv,
  888. packets_recv,
  889. errin,
  890. dropin,
  891. fifoin, # unused
  892. framein, # unused
  893. compressedin, # unused
  894. multicastin, # unused
  895. # out
  896. bytes_sent,
  897. packets_sent,
  898. errout,
  899. dropout,
  900. fifoout, # unused
  901. collisionsout, # unused
  902. carrierout, # unused
  903. compressedout) = map(int, fields)
  904. retdict[name] = (bytes_sent, bytes_recv, packets_sent, packets_recv,
  905. errin, errout, dropin, dropout)
  906. return retdict
  907. def net_if_stats():
  908. """Get NIC stats (isup, duplex, speed, mtu)."""
  909. duplex_map = {cext.DUPLEX_FULL: NIC_DUPLEX_FULL,
  910. cext.DUPLEX_HALF: NIC_DUPLEX_HALF,
  911. cext.DUPLEX_UNKNOWN: NIC_DUPLEX_UNKNOWN}
  912. names = net_io_counters().keys()
  913. ret = {}
  914. for name in names:
  915. try:
  916. mtu = cext_posix.net_if_mtu(name)
  917. isup = cext_posix.net_if_is_running(name)
  918. duplex, speed = cext.net_if_duplex_speed(name)
  919. except OSError as err:
  920. # https://github.com/giampaolo/psutil/issues/1279
  921. if err.errno != errno.ENODEV:
  922. raise
  923. else:
  924. ret[name] = _common.snicstats(isup, duplex_map[duplex], speed, mtu)
  925. return ret
  926. # =====================================================================
  927. # --- disks
  928. # =====================================================================
  929. disk_usage = _psposix.disk_usage
  930. def disk_io_counters(perdisk=False):
  931. """Return disk I/O statistics for every disk installed on the
  932. system as a dict of raw tuples.
  933. """
  934. def read_procfs():
  935. # OK, this is a bit confusing. The format of /proc/diskstats can
  936. # have 3 variations.
  937. # On Linux 2.4 each line has always 15 fields, e.g.:
  938. # "3 0 8 hda 8 8 8 8 8 8 8 8 8 8 8"
  939. # On Linux 2.6+ each line *usually* has 14 fields, and the disk
  940. # name is in another position, like this:
  941. # "3 0 hda 8 8 8 8 8 8 8 8 8 8 8"
  942. # ...unless (Linux 2.6) the line refers to a partition instead
  943. # of a disk, in which case the line has less fields (7):
  944. # "3 1 hda1 8 8 8 8"
  945. # 4.18+ has 4 fields added:
  946. # "3 0 hda 8 8 8 8 8 8 8 8 8 8 8 0 0 0 0"
  947. # 5.5 has 2 more fields.
  948. # See:
  949. # https://www.kernel.org/doc/Documentation/iostats.txt
  950. # https://www.kernel.org/doc/Documentation/ABI/testing/procfs-diskstats
  951. with open_text("%s/diskstats" % get_procfs_path()) as f:
  952. lines = f.readlines()
  953. for line in lines:
  954. fields = line.split()
  955. flen = len(fields)
  956. if flen == 15:
  957. # Linux 2.4
  958. name = fields[3]
  959. reads = int(fields[2])
  960. (reads_merged, rbytes, rtime, writes, writes_merged,
  961. wbytes, wtime, _, busy_time, _) = map(int, fields[4:14])
  962. elif flen == 14 or flen >= 18:
  963. # Linux 2.6+, line referring to a disk
  964. name = fields[2]
  965. (reads, reads_merged, rbytes, rtime, writes, writes_merged,
  966. wbytes, wtime, _, busy_time, _) = map(int, fields[3:14])
  967. elif flen == 7:
  968. # Linux 2.6+, line referring to a partition
  969. name = fields[2]
  970. reads, rbytes, writes, wbytes = map(int, fields[3:])
  971. rtime = wtime = reads_merged = writes_merged = busy_time = 0
  972. else:
  973. raise ValueError("not sure how to interpret line %r" % line)
  974. yield (name, reads, writes, rbytes, wbytes, rtime, wtime,
  975. reads_merged, writes_merged, busy_time)
  976. def read_sysfs():
  977. for block in os.listdir('/sys/block'):
  978. for root, _, files in os.walk(os.path.join('/sys/block', block)):
  979. if 'stat' not in files:
  980. continue
  981. with open_text(os.path.join(root, 'stat')) as f:
  982. fields = f.read().strip().split()
  983. name = os.path.basename(root)
  984. (reads, reads_merged, rbytes, rtime, writes, writes_merged,
  985. wbytes, wtime, _, busy_time) = map(int, fields[:10])
  986. yield (name, reads, writes, rbytes, wbytes, rtime,
  987. wtime, reads_merged, writes_merged, busy_time)
  988. if os.path.exists('%s/diskstats' % get_procfs_path()):
  989. gen = read_procfs()
  990. elif os.path.exists('/sys/block'):
  991. gen = read_sysfs()
  992. else:
  993. raise NotImplementedError(
  994. "%s/diskstats nor /sys/block filesystem are available on this "
  995. "system" % get_procfs_path())
  996. retdict = {}
  997. for entry in gen:
  998. (name, reads, writes, rbytes, wbytes, rtime, wtime, reads_merged,
  999. writes_merged, busy_time) = entry
  1000. if not perdisk and not is_storage_device(name):
  1001. # perdisk=False means we want to calculate totals so we skip
  1002. # partitions (e.g. 'sda1', 'nvme0n1p1') and only include
  1003. # base disk devices (e.g. 'sda', 'nvme0n1'). Base disks
  1004. # include a total of all their partitions + some extra size
  1005. # of their own:
  1006. # $ cat /proc/diskstats
  1007. # 259 0 sda 10485760 ...
  1008. # 259 1 sda1 5186039 ...
  1009. # 259 1 sda2 5082039 ...
  1010. # See:
  1011. # https://github.com/giampaolo/psutil/pull/1313
  1012. continue
  1013. rbytes *= DISK_SECTOR_SIZE
  1014. wbytes *= DISK_SECTOR_SIZE
  1015. retdict[name] = (reads, writes, rbytes, wbytes, rtime, wtime,
  1016. reads_merged, writes_merged, busy_time)
  1017. return retdict
  1018. def disk_partitions(all=False):
  1019. """Return mounted disk partitions as a list of namedtuples."""
  1020. fstypes = set()
  1021. procfs_path = get_procfs_path()
  1022. with open_text("%s/filesystems" % procfs_path) as f:
  1023. for line in f:
  1024. line = line.strip()
  1025. if not line.startswith("nodev"):
  1026. fstypes.add(line.strip())
  1027. else:
  1028. # ignore all lines starting with "nodev" except "nodev zfs"
  1029. fstype = line.split("\t")[1]
  1030. if fstype == "zfs":
  1031. fstypes.add("zfs")
  1032. # See: https://github.com/giampaolo/psutil/issues/1307
  1033. if procfs_path == "/proc" and os.path.isfile('/etc/mtab'):
  1034. mounts_path = os.path.realpath("/etc/mtab")
  1035. else:
  1036. mounts_path = os.path.realpath("%s/self/mounts" % procfs_path)
  1037. retlist = []
  1038. partitions = cext.disk_partitions(mounts_path)
  1039. for partition in partitions:
  1040. device, mountpoint, fstype, opts = partition
  1041. if device == 'none':
  1042. device = ''
  1043. if not all:
  1044. if device == '' or fstype not in fstypes:
  1045. continue
  1046. ntuple = _common.sdiskpart(device, mountpoint, fstype, opts)
  1047. retlist.append(ntuple)
  1048. return retlist
  1049. # =====================================================================
  1050. # --- sensors
  1051. # =====================================================================
  1052. def sensors_temperatures():
  1053. """Return hardware (CPU and others) temperatures as a dict
  1054. including hardware name, label, current, max and critical
  1055. temperatures.
  1056. Implementation notes:
  1057. - /sys/class/hwmon looks like the most recent interface to
  1058. retrieve this info, and this implementation relies on it
  1059. only (old distros will probably use something else)
  1060. - lm-sensors on Ubuntu 16.04 relies on /sys/class/hwmon
  1061. - /sys/class/thermal/thermal_zone* is another one but it's more
  1062. difficult to parse
  1063. """
  1064. ret = collections.defaultdict(list)
  1065. basenames = glob.glob('/sys/class/hwmon/hwmon*/temp*_*')
  1066. # CentOS has an intermediate /device directory:
  1067. # https://github.com/giampaolo/psutil/issues/971
  1068. # https://github.com/nicolargo/glances/issues/1060
  1069. basenames.extend(glob.glob('/sys/class/hwmon/hwmon*/device/temp*_*'))
  1070. basenames.extend(glob.glob(
  1071. '/sys/devices/platform/coretemp.*/hwmon/hwmon*/temp*_*'))
  1072. basenames = sorted(set([x.split('_')[0] for x in basenames]))
  1073. for base in basenames:
  1074. try:
  1075. path = base + '_input'
  1076. current = float(cat(path)) / 1000.0
  1077. path = os.path.join(os.path.dirname(base), 'name')
  1078. unit_name = cat(path, binary=False)
  1079. except (IOError, OSError, ValueError):
  1080. # A lot of things can go wrong here, so let's just skip the
  1081. # whole entry. Sure thing is Linux's /sys/class/hwmon really
  1082. # is a stinky broken mess.
  1083. # https://github.com/giampaolo/psutil/issues/1009
  1084. # https://github.com/giampaolo/psutil/issues/1101
  1085. # https://github.com/giampaolo/psutil/issues/1129
  1086. # https://github.com/giampaolo/psutil/issues/1245
  1087. # https://github.com/giampaolo/psutil/issues/1323
  1088. continue
  1089. high = cat(base + '_max', fallback=None)
  1090. critical = cat(base + '_crit', fallback=None)
  1091. label = cat(base + '_label', fallback='', binary=False)
  1092. if high is not None:
  1093. try:
  1094. high = float(high) / 1000.0
  1095. except ValueError:
  1096. high = None
  1097. if critical is not None:
  1098. try:
  1099. critical = float(critical) / 1000.0
  1100. except ValueError:
  1101. critical = None
  1102. ret[unit_name].append((label, current, high, critical))
  1103. # Indication that no sensors were detected in /sys/class/hwmon/
  1104. if not basenames:
  1105. basenames = glob.glob('/sys/class/thermal/thermal_zone*')
  1106. basenames = sorted(set(basenames))
  1107. for base in basenames:
  1108. try:
  1109. path = os.path.join(base, 'temp')
  1110. current = float(cat(path)) / 1000.0
  1111. path = os.path.join(base, 'type')
  1112. unit_name = cat(path, binary=False)
  1113. except (IOError, OSError, ValueError) as err:
  1114. debug("ignoring %r for file %r" % (err, path))
  1115. continue
  1116. trip_paths = glob.glob(base + '/trip_point*')
  1117. trip_points = set(['_'.join(
  1118. os.path.basename(p).split('_')[0:3]) for p in trip_paths])
  1119. critical = None
  1120. high = None
  1121. for trip_point in trip_points:
  1122. path = os.path.join(base, trip_point + "_type")
  1123. trip_type = cat(path, fallback='', binary=False)
  1124. if trip_type == 'critical':
  1125. critical = cat(os.path.join(base, trip_point + "_temp"),
  1126. fallback=None)
  1127. elif trip_type == 'high':
  1128. high = cat(os.path.join(base, trip_point + "_temp"),
  1129. fallback=None)
  1130. if high is not None:
  1131. try:
  1132. high = float(high) / 1000.0
  1133. except ValueError:
  1134. high = None
  1135. if critical is not None:
  1136. try:
  1137. critical = float(critical) / 1000.0
  1138. except ValueError:
  1139. critical = None
  1140. ret[unit_name].append(('', current, high, critical))
  1141. return dict(ret)
  1142. def sensors_fans():
  1143. """Return hardware fans info (for CPU and other peripherals) as a
  1144. dict including hardware label and current speed.
  1145. Implementation notes:
  1146. - /sys/class/hwmon looks like the most recent interface to
  1147. retrieve this info, and this implementation relies on it
  1148. only (old distros will probably use something else)
  1149. - lm-sensors on Ubuntu 16.04 relies on /sys/class/hwmon
  1150. """
  1151. ret = collections.defaultdict(list)
  1152. basenames = glob.glob('/sys/class/hwmon/hwmon*/fan*_*')
  1153. if not basenames:
  1154. # CentOS has an intermediate /device directory:
  1155. # https://github.com/giampaolo/psutil/issues/971
  1156. basenames = glob.glob('/sys/class/hwmon/hwmon*/device/fan*_*')
  1157. basenames = sorted(set([x.split('_')[0] for x in basenames]))
  1158. for base in basenames:
  1159. try:
  1160. current = int(cat(base + '_input'))
  1161. except (IOError, OSError) as err:
  1162. warnings.warn("ignoring %r" % err, RuntimeWarning)
  1163. continue
  1164. unit_name = cat(os.path.join(os.path.dirname(base), 'name'),
  1165. binary=False)
  1166. label = cat(base + '_label', fallback='', binary=False)
  1167. ret[unit_name].append(_common.sfan(label, current))
  1168. return dict(ret)
  1169. def sensors_battery():
  1170. """Return battery information.
  1171. Implementation note: it appears /sys/class/power_supply/BAT0/
  1172. directory structure may vary and provide files with the same
  1173. meaning but under different names, see:
  1174. https://github.com/giampaolo/psutil/issues/966
  1175. """
  1176. null = object()
  1177. def multi_cat(*paths):
  1178. """Attempt to read the content of multiple files which may
  1179. not exist. If none of them exist return None.
  1180. """
  1181. for path in paths:
  1182. ret = cat(path, fallback=null)
  1183. if ret != null:
  1184. return int(ret) if ret.isdigit() else ret
  1185. return None
  1186. bats = [x for x in os.listdir(POWER_SUPPLY_PATH) if x.startswith('BAT') or
  1187. 'battery' in x.lower()]
  1188. if not bats:
  1189. return None
  1190. # Get the first available battery. Usually this is "BAT0", except
  1191. # some rare exceptions:
  1192. # https://github.com/giampaolo/psutil/issues/1238
  1193. root = os.path.join(POWER_SUPPLY_PATH, sorted(bats)[0])
  1194. # Base metrics.
  1195. energy_now = multi_cat(
  1196. root + "/energy_now",
  1197. root + "/charge_now")
  1198. power_now = multi_cat(
  1199. root + "/power_now",
  1200. root + "/current_now")
  1201. energy_full = multi_cat(
  1202. root + "/energy_full",
  1203. root + "/charge_full")
  1204. time_to_empty = multi_cat(root + "/time_to_empty_now")
  1205. # Percent. If we have energy_full the percentage will be more
  1206. # accurate compared to reading /capacity file (float vs. int).
  1207. if energy_full is not None and energy_now is not None:
  1208. try:
  1209. percent = 100.0 * energy_now / energy_full
  1210. except ZeroDivisionError:
  1211. percent = 0.0
  1212. else:
  1213. percent = int(cat(root + "/capacity", fallback=-1))
  1214. if percent == -1:
  1215. return None
  1216. # Is AC power cable plugged in?
  1217. # Note: AC0 is not always available and sometimes (e.g. CentOS7)
  1218. # it's called "AC".
  1219. power_plugged = None
  1220. online = multi_cat(
  1221. os.path.join(POWER_SUPPLY_PATH, "AC0/online"),
  1222. os.path.join(POWER_SUPPLY_PATH, "AC/online"))
  1223. if online is not None:
  1224. power_plugged = online == 1
  1225. else:
  1226. status = cat(root + "/status", fallback="", binary=False).lower()
  1227. if status == "discharging":
  1228. power_plugged = False
  1229. elif status in ("charging", "full"):
  1230. power_plugged = True
  1231. # Seconds left.
  1232. # Note to self: we may also calculate the charging ETA as per:
  1233. # https://github.com/thialfihar/dotfiles/blob/
  1234. # 013937745fd9050c30146290e8f963d65c0179e6/bin/battery.py#L55
  1235. if power_plugged:
  1236. secsleft = _common.POWER_TIME_UNLIMITED
  1237. elif energy_now is not None and power_now is not None:
  1238. try:
  1239. secsleft = int(energy_now / power_now * 3600)
  1240. except ZeroDivisionError:
  1241. secsleft = _common.POWER_TIME_UNKNOWN
  1242. elif time_to_empty is not None:
  1243. secsleft = int(time_to_empty * 60)
  1244. if secsleft < 0:
  1245. secsleft = _common.POWER_TIME_UNKNOWN
  1246. else:
  1247. secsleft = _common.POWER_TIME_UNKNOWN
  1248. return _common.sbattery(percent, secsleft, power_plugged)
  1249. # =====================================================================
  1250. # --- other system functions
  1251. # =====================================================================
  1252. def users():
  1253. """Return currently connected users as a list of namedtuples."""
  1254. retlist = []
  1255. rawlist = cext.users()
  1256. for item in rawlist:
  1257. user, tty, hostname, tstamp, user_process, pid = item
  1258. # note: the underlying C function includes entries about
  1259. # system boot, run level and others. We might want
  1260. # to use them in the future.
  1261. if not user_process:
  1262. continue
  1263. if hostname in (':0.0', ':0'):
  1264. hostname = 'localhost'
  1265. nt = _common.suser(user, tty or None, hostname, tstamp, pid)
  1266. retlist.append(nt)
  1267. return retlist
  1268. def boot_time():
  1269. """Return the system boot time expressed in seconds since the epoch."""
  1270. global BOOT_TIME
  1271. path = '%s/stat' % get_procfs_path()
  1272. with open_binary(path) as f:
  1273. for line in f:
  1274. if line.startswith(b'btime'):
  1275. ret = float(line.strip().split()[1])
  1276. BOOT_TIME = ret
  1277. return ret
  1278. raise RuntimeError(
  1279. "line 'btime' not found in %s" % path)
  1280. # =====================================================================
  1281. # --- processes
  1282. # =====================================================================
  1283. def pids():
  1284. """Returns a list of PIDs currently running on the system."""
  1285. return [int(x) for x in os.listdir(b(get_procfs_path())) if x.isdigit()]
  1286. def pid_exists(pid):
  1287. """Check for the existence of a unix PID. Linux TIDs are not
  1288. supported (always return False).
  1289. """
  1290. if not _psposix.pid_exists(pid):
  1291. return False
  1292. else:
  1293. # Linux's apparently does not distinguish between PIDs and TIDs
  1294. # (thread IDs).
  1295. # listdir("/proc") won't show any TID (only PIDs) but
  1296. # os.stat("/proc/{tid}") will succeed if {tid} exists.
  1297. # os.kill() can also be passed a TID. This is quite confusing.
  1298. # In here we want to enforce this distinction and support PIDs
  1299. # only, see:
  1300. # https://github.com/giampaolo/psutil/issues/687
  1301. try:
  1302. # Note: already checked that this is faster than using a
  1303. # regular expr. Also (a lot) faster than doing
  1304. # 'return pid in pids()'
  1305. path = "%s/%s/status" % (get_procfs_path(), pid)
  1306. with open_binary(path) as f:
  1307. for line in f:
  1308. if line.startswith(b"Tgid:"):
  1309. tgid = int(line.split()[1])
  1310. # If tgid and pid are the same then we're
  1311. # dealing with a process PID.
  1312. return tgid == pid
  1313. raise ValueError("'Tgid' line not found in %s" % path)
  1314. except (EnvironmentError, ValueError):
  1315. return pid in pids()
  1316. def ppid_map():
  1317. """Obtain a {pid: ppid, ...} dict for all running processes in
  1318. one shot. Used to speed up Process.children().
  1319. """
  1320. ret = {}
  1321. procfs_path = get_procfs_path()
  1322. for pid in pids():
  1323. try:
  1324. with open_binary("%s/%s/stat" % (procfs_path, pid)) as f:
  1325. data = f.read()
  1326. except (FileNotFoundError, ProcessLookupError):
  1327. # Note: we should be able to access /stat for all processes
  1328. # aka it's unlikely we'll bump into EPERM, which is good.
  1329. pass
  1330. else:
  1331. rpar = data.rfind(b')')
  1332. dset = data[rpar + 2:].split()
  1333. ppid = int(dset[1])
  1334. ret[pid] = ppid
  1335. return ret
  1336. def wrap_exceptions(fun):
  1337. """Decorator which translates bare OSError and IOError exceptions
  1338. into NoSuchProcess and AccessDenied.
  1339. """
  1340. @functools.wraps(fun)
  1341. def wrapper(self, *args, **kwargs):
  1342. try:
  1343. return fun(self, *args, **kwargs)
  1344. except PermissionError:
  1345. raise AccessDenied(self.pid, self._name)
  1346. except ProcessLookupError:
  1347. raise NoSuchProcess(self.pid, self._name)
  1348. except FileNotFoundError:
  1349. if not os.path.exists("%s/%s" % (self._procfs_path, self.pid)):
  1350. raise NoSuchProcess(self.pid, self._name)
  1351. # Note: zombies will keep existing under /proc until they're
  1352. # gone so there's no way to distinguish them in here.
  1353. raise
  1354. return wrapper
  1355. class Process(object):
  1356. """Linux process implementation."""
  1357. __slots__ = ["pid", "_name", "_ppid", "_procfs_path", "_cache"]
  1358. def __init__(self, pid):
  1359. self.pid = pid
  1360. self._name = None
  1361. self._ppid = None
  1362. self._procfs_path = get_procfs_path()
  1363. def _assert_alive(self):
  1364. """Raise NSP if the process disappeared on us."""
  1365. # For those C function who do not raise NSP, possibly returning
  1366. # incorrect or incomplete result.
  1367. os.stat('%s/%s' % (self._procfs_path, self.pid))
  1368. @wrap_exceptions
  1369. @memoize_when_activated
  1370. def _parse_stat_file(self):
  1371. """Parse /proc/{pid}/stat file and return a dict with various
  1372. process info.
  1373. Using "man proc" as a reference: where "man proc" refers to
  1374. position N always substract 3 (e.g ppid position 4 in
  1375. 'man proc' == position 1 in here).
  1376. The return value is cached in case oneshot() ctx manager is
  1377. in use.
  1378. """
  1379. with open_binary("%s/%s/stat" % (self._procfs_path, self.pid)) as f:
  1380. data = f.read()
  1381. # Process name is between parentheses. It can contain spaces and
  1382. # other parentheses. This is taken into account by looking for
  1383. # the first occurrence of "(" and the last occurence of ")".
  1384. rpar = data.rfind(b')')
  1385. name = data[data.find(b'(') + 1:rpar]
  1386. fields = data[rpar + 2:].split()
  1387. ret = {}
  1388. ret['name'] = name
  1389. ret['status'] = fields[0]
  1390. ret['ppid'] = fields[1]
  1391. ret['ttynr'] = fields[4]
  1392. ret['utime'] = fields[11]
  1393. ret['stime'] = fields[12]
  1394. ret['children_utime'] = fields[13]
  1395. ret['children_stime'] = fields[14]
  1396. ret['create_time'] = fields[19]
  1397. ret['cpu_num'] = fields[36]
  1398. ret['blkio_ticks'] = fields[39] # aka 'delayacct_blkio_ticks'
  1399. return ret
  1400. @wrap_exceptions
  1401. @memoize_when_activated
  1402. def _read_status_file(self):
  1403. """Read /proc/{pid}/stat file and return its content.
  1404. The return value is cached in case oneshot() ctx manager is
  1405. in use.
  1406. """
  1407. with open_binary("%s/%s/status" % (self._procfs_path, self.pid)) as f:
  1408. return f.read()
  1409. @wrap_exceptions
  1410. @memoize_when_activated
  1411. def _read_smaps_file(self):
  1412. with open_binary("%s/%s/smaps" % (self._procfs_path, self.pid),
  1413. buffering=BIGFILE_BUFFERING) as f:
  1414. return f.read().strip()
  1415. def oneshot_enter(self):
  1416. self._parse_stat_file.cache_activate(self)
  1417. self._read_status_file.cache_activate(self)
  1418. self._read_smaps_file.cache_activate(self)
  1419. def oneshot_exit(self):
  1420. self._parse_stat_file.cache_deactivate(self)
  1421. self._read_status_file.cache_deactivate(self)
  1422. self._read_smaps_file.cache_deactivate(self)
  1423. @wrap_exceptions
  1424. def name(self):
  1425. name = self._parse_stat_file()['name']
  1426. if PY3:
  1427. name = decode(name)
  1428. # XXX - gets changed later and probably needs refactoring
  1429. return name
  1430. def exe(self):
  1431. try:
  1432. return readlink("%s/%s/exe" % (self._procfs_path, self.pid))
  1433. except (FileNotFoundError, ProcessLookupError):
  1434. # no such file error; might be raised also if the
  1435. # path actually exists for system processes with
  1436. # low pids (about 0-20)
  1437. if os.path.lexists("%s/%s" % (self._procfs_path, self.pid)):
  1438. return ""
  1439. else:
  1440. if not pid_exists(self.pid):
  1441. raise NoSuchProcess(self.pid, self._name)
  1442. else:
  1443. raise ZombieProcess(self.pid, self._name, self._ppid)
  1444. except PermissionError:
  1445. raise AccessDenied(self.pid, self._name)
  1446. @wrap_exceptions
  1447. def cmdline(self):
  1448. with open_text("%s/%s/cmdline" % (self._procfs_path, self.pid)) as f:
  1449. data = f.read()
  1450. if not data:
  1451. # may happen in case of zombie process
  1452. return []
  1453. # 'man proc' states that args are separated by null bytes '\0'
  1454. # and last char is supposed to be a null byte. Nevertheless
  1455. # some processes may change their cmdline after being started
  1456. # (via setproctitle() or similar), they are usually not
  1457. # compliant with this rule and use spaces instead. Google
  1458. # Chrome process is an example. See:
  1459. # https://github.com/giampaolo/psutil/issues/1179
  1460. sep = '\x00' if data.endswith('\x00') else ' '
  1461. if data.endswith(sep):
  1462. data = data[:-1]
  1463. cmdline = data.split(sep)
  1464. # Sometimes last char is a null byte '\0' but the args are
  1465. # separated by spaces, see: https://github.com/giampaolo/psutil/
  1466. # issues/1179#issuecomment-552984549
  1467. if sep == '\x00' and len(cmdline) == 1 and ' ' in data:
  1468. cmdline = data.split(' ')
  1469. return cmdline
  1470. @wrap_exceptions
  1471. def environ(self):
  1472. with open_text("%s/%s/environ" % (self._procfs_path, self.pid)) as f:
  1473. data = f.read()
  1474. return parse_environ_block(data)
  1475. @wrap_exceptions
  1476. def terminal(self):
  1477. tty_nr = int(self._parse_stat_file()['ttynr'])
  1478. tmap = _psposix.get_terminal_map()
  1479. try:
  1480. return tmap[tty_nr]
  1481. except KeyError:
  1482. return None
  1483. # May not be available on old kernels.
  1484. if os.path.exists('/proc/%s/io' % os.getpid()):
  1485. @wrap_exceptions
  1486. def io_counters(self):
  1487. fname = "%s/%s/io" % (self._procfs_path, self.pid)
  1488. fields = {}
  1489. with open_binary(fname) as f:
  1490. for line in f:
  1491. # https://github.com/giampaolo/psutil/issues/1004
  1492. line = line.strip()
  1493. if line:
  1494. try:
  1495. name, value = line.split(b': ')
  1496. except ValueError:
  1497. # https://github.com/giampaolo/psutil/issues/1004
  1498. continue
  1499. else:
  1500. fields[name] = int(value)
  1501. if not fields:
  1502. raise RuntimeError("%s file was empty" % fname)
  1503. try:
  1504. return pio(
  1505. fields[b'syscr'], # read syscalls
  1506. fields[b'syscw'], # write syscalls
  1507. fields[b'read_bytes'], # read bytes
  1508. fields[b'write_bytes'], # write bytes
  1509. fields[b'rchar'], # read chars
  1510. fields[b'wchar'], # write chars
  1511. )
  1512. except KeyError as err:
  1513. raise ValueError("%r field was not found in %s; found fields "
  1514. "are %r" % (err[0], fname, fields))
  1515. @wrap_exceptions
  1516. def cpu_times(self):
  1517. values = self._parse_stat_file()
  1518. utime = float(values['utime']) / CLOCK_TICKS
  1519. stime = float(values['stime']) / CLOCK_TICKS
  1520. children_utime = float(values['children_utime']) / CLOCK_TICKS
  1521. children_stime = float(values['children_stime']) / CLOCK_TICKS
  1522. iowait = float(values['blkio_ticks']) / CLOCK_TICKS
  1523. return pcputimes(utime, stime, children_utime, children_stime, iowait)
  1524. @wrap_exceptions
  1525. def cpu_num(self):
  1526. """What CPU the process is on."""
  1527. return int(self._parse_stat_file()['cpu_num'])
  1528. @wrap_exceptions
  1529. def wait(self, timeout=None):
  1530. return _psposix.wait_pid(self.pid, timeout, self._name)
  1531. @wrap_exceptions
  1532. def create_time(self):
  1533. ctime = float(self._parse_stat_file()['create_time'])
  1534. # According to documentation, starttime is in field 21 and the
  1535. # unit is jiffies (clock ticks).
  1536. # We first divide it for clock ticks and then add uptime returning
  1537. # seconds since the epoch, in UTC.
  1538. # Also use cached value if available.
  1539. bt = BOOT_TIME or boot_time()
  1540. return (ctime / CLOCK_TICKS) + bt
  1541. @wrap_exceptions
  1542. def memory_info(self):
  1543. # ============================================================
  1544. # | FIELD | DESCRIPTION | AKA | TOP |
  1545. # ============================================================
  1546. # | rss | resident set size | | RES |
  1547. # | vms | total program size | size | VIRT |
  1548. # | shared | shared pages (from shared mappings) | | SHR |
  1549. # | text | text ('code') | trs | CODE |
  1550. # | lib | library (unused in Linux 2.6) | lrs | |
  1551. # | data | data + stack | drs | DATA |
  1552. # | dirty | dirty pages (unused in Linux 2.6) | dt | |
  1553. # ============================================================
  1554. with open_binary("%s/%s/statm" % (self._procfs_path, self.pid)) as f:
  1555. vms, rss, shared, text, lib, data, dirty = \
  1556. [int(x) * PAGESIZE for x in f.readline().split()[:7]]
  1557. return pmem(rss, vms, shared, text, lib, data, dirty)
  1558. # /proc/pid/smaps does not exist on kernels < 2.6.14 or if
  1559. # CONFIG_MMU kernel configuration option is not enabled.
  1560. if HAS_SMAPS:
  1561. @wrap_exceptions
  1562. def memory_full_info(
  1563. self,
  1564. # Gets Private_Clean, Private_Dirty, Private_Hugetlb.
  1565. _private_re=re.compile(br"\nPrivate.*:\s+(\d+)"),
  1566. _pss_re=re.compile(br"\nPss\:\s+(\d+)"),
  1567. _swap_re=re.compile(br"\nSwap\:\s+(\d+)")):
  1568. basic_mem = self.memory_info()
  1569. # Note: using 3 regexes is faster than reading the file
  1570. # line by line.
  1571. # XXX: on Python 3 the 2 regexes are 30% slower than on
  1572. # Python 2 though. Figure out why.
  1573. #
  1574. # You might be tempted to calculate USS by subtracting
  1575. # the "shared" value from the "resident" value in
  1576. # /proc/<pid>/statm. But at least on Linux, statm's "shared"
  1577. # value actually counts pages backed by files, which has
  1578. # little to do with whether the pages are actually shared.
  1579. # /proc/self/smaps on the other hand appears to give us the
  1580. # correct information.
  1581. smaps_data = self._read_smaps_file()
  1582. # Note: smaps file can be empty for certain processes.
  1583. # The code below will not crash though and will result to 0.
  1584. uss = sum(map(int, _private_re.findall(smaps_data))) * 1024
  1585. pss = sum(map(int, _pss_re.findall(smaps_data))) * 1024
  1586. swap = sum(map(int, _swap_re.findall(smaps_data))) * 1024
  1587. return pfullmem(*basic_mem + (uss, pss, swap))
  1588. else:
  1589. memory_full_info = memory_info
  1590. if HAS_SMAPS:
  1591. @wrap_exceptions
  1592. def memory_maps(self):
  1593. """Return process's mapped memory regions as a list of named
  1594. tuples. Fields are explained in 'man proc'; here is an updated
  1595. (Apr 2012) version: http://goo.gl/fmebo
  1596. /proc/{PID}/smaps does not exist on kernels < 2.6.14 or if
  1597. CONFIG_MMU kernel configuration option is not enabled.
  1598. """
  1599. def get_blocks(lines, current_block):
  1600. data = {}
  1601. for line in lines:
  1602. fields = line.split(None, 5)
  1603. if not fields[0].endswith(b':'):
  1604. # new block section
  1605. yield (current_block.pop(), data)
  1606. current_block.append(line)
  1607. else:
  1608. try:
  1609. data[fields[0]] = int(fields[1]) * 1024
  1610. except ValueError:
  1611. if fields[0].startswith(b'VmFlags:'):
  1612. # see issue #369
  1613. continue
  1614. else:
  1615. raise ValueError("don't know how to inte"
  1616. "rpret line %r" % line)
  1617. yield (current_block.pop(), data)
  1618. data = self._read_smaps_file()
  1619. # Note: smaps file can be empty for certain processes.
  1620. if not data:
  1621. return []
  1622. lines = data.split(b'\n')
  1623. ls = []
  1624. first_line = lines.pop(0)
  1625. current_block = [first_line]
  1626. for header, data in get_blocks(lines, current_block):
  1627. hfields = header.split(None, 5)
  1628. try:
  1629. addr, perms, offset, dev, inode, path = hfields
  1630. except ValueError:
  1631. addr, perms, offset, dev, inode, path = \
  1632. hfields + ['']
  1633. if not path:
  1634. path = '[anon]'
  1635. else:
  1636. if PY3:
  1637. path = decode(path)
  1638. path = path.strip()
  1639. if (path.endswith(' (deleted)') and not
  1640. path_exists_strict(path)):
  1641. path = path[:-10]
  1642. ls.append((
  1643. decode(addr), decode(perms), path,
  1644. data.get(b'Rss:', 0),
  1645. data.get(b'Size:', 0),
  1646. data.get(b'Pss:', 0),
  1647. data.get(b'Shared_Clean:', 0),
  1648. data.get(b'Shared_Dirty:', 0),
  1649. data.get(b'Private_Clean:', 0),
  1650. data.get(b'Private_Dirty:', 0),
  1651. data.get(b'Referenced:', 0),
  1652. data.get(b'Anonymous:', 0),
  1653. data.get(b'Swap:', 0)
  1654. ))
  1655. return ls
  1656. @wrap_exceptions
  1657. def cwd(self):
  1658. try:
  1659. return readlink("%s/%s/cwd" % (self._procfs_path, self.pid))
  1660. except (FileNotFoundError, ProcessLookupError):
  1661. # https://github.com/giampaolo/psutil/issues/986
  1662. if not pid_exists(self.pid):
  1663. raise NoSuchProcess(self.pid, self._name)
  1664. else:
  1665. raise ZombieProcess(self.pid, self._name, self._ppid)
  1666. @wrap_exceptions
  1667. def num_ctx_switches(self,
  1668. _ctxsw_re=re.compile(br'ctxt_switches:\t(\d+)')):
  1669. data = self._read_status_file()
  1670. ctxsw = _ctxsw_re.findall(data)
  1671. if not ctxsw:
  1672. raise NotImplementedError(
  1673. "'voluntary_ctxt_switches' and 'nonvoluntary_ctxt_switches'"
  1674. "lines were not found in %s/%s/status; the kernel is "
  1675. "probably older than 2.6.23" % (
  1676. self._procfs_path, self.pid))
  1677. else:
  1678. return _common.pctxsw(int(ctxsw[0]), int(ctxsw[1]))
  1679. @wrap_exceptions
  1680. def num_threads(self, _num_threads_re=re.compile(br'Threads:\t(\d+)')):
  1681. # Note: on Python 3 using a re is faster than iterating over file
  1682. # line by line. On Python 2 is the exact opposite, and iterating
  1683. # over a file on Python 3 is slower than on Python 2.
  1684. data = self._read_status_file()
  1685. return int(_num_threads_re.findall(data)[0])
  1686. @wrap_exceptions
  1687. def threads(self):
  1688. thread_ids = os.listdir("%s/%s/task" % (self._procfs_path, self.pid))
  1689. thread_ids.sort()
  1690. retlist = []
  1691. hit_enoent = False
  1692. for thread_id in thread_ids:
  1693. fname = "%s/%s/task/%s/stat" % (
  1694. self._procfs_path, self.pid, thread_id)
  1695. try:
  1696. with open_binary(fname) as f:
  1697. st = f.read().strip()
  1698. except FileNotFoundError:
  1699. # no such file or directory; it means thread
  1700. # disappeared on us
  1701. hit_enoent = True
  1702. continue
  1703. # ignore the first two values ("pid (exe)")
  1704. st = st[st.find(b')') + 2:]
  1705. values = st.split(b' ')
  1706. utime = float(values[11]) / CLOCK_TICKS
  1707. stime = float(values[12]) / CLOCK_TICKS
  1708. ntuple = _common.pthread(int(thread_id), utime, stime)
  1709. retlist.append(ntuple)
  1710. if hit_enoent:
  1711. self._assert_alive()
  1712. return retlist
  1713. @wrap_exceptions
  1714. def nice_get(self):
  1715. # with open_text('%s/%s/stat' % (self._procfs_path, self.pid)) as f:
  1716. # data = f.read()
  1717. # return int(data.split()[18])
  1718. # Use C implementation
  1719. return cext_posix.getpriority(self.pid)
  1720. @wrap_exceptions
  1721. def nice_set(self, value):
  1722. return cext_posix.setpriority(self.pid, value)
  1723. # starting from CentOS 6.
  1724. if HAS_CPU_AFFINITY:
  1725. @wrap_exceptions
  1726. def cpu_affinity_get(self):
  1727. return cext.proc_cpu_affinity_get(self.pid)
  1728. def _get_eligible_cpus(
  1729. self, _re=re.compile(br"Cpus_allowed_list:\t(\d+)-(\d+)")):
  1730. # See: https://github.com/giampaolo/psutil/issues/956
  1731. data = self._read_status_file()
  1732. match = _re.findall(data)
  1733. if match:
  1734. return list(range(int(match[0][0]), int(match[0][1]) + 1))
  1735. else:
  1736. return list(range(len(per_cpu_times())))
  1737. @wrap_exceptions
  1738. def cpu_affinity_set(self, cpus):
  1739. try:
  1740. cext.proc_cpu_affinity_set(self.pid, cpus)
  1741. except (OSError, ValueError) as err:
  1742. if isinstance(err, ValueError) or err.errno == errno.EINVAL:
  1743. eligible_cpus = self._get_eligible_cpus()
  1744. all_cpus = tuple(range(len(per_cpu_times())))
  1745. for cpu in cpus:
  1746. if cpu not in all_cpus:
  1747. raise ValueError(
  1748. "invalid CPU number %r; choose between %s" % (
  1749. cpu, eligible_cpus))
  1750. if cpu not in eligible_cpus:
  1751. raise ValueError(
  1752. "CPU number %r is not eligible; choose "
  1753. "between %s" % (cpu, eligible_cpus))
  1754. raise
  1755. # only starting from kernel 2.6.13
  1756. if HAS_PROC_IO_PRIORITY:
  1757. @wrap_exceptions
  1758. def ionice_get(self):
  1759. ioclass, value = cext.proc_ioprio_get(self.pid)
  1760. if enum is not None:
  1761. ioclass = IOPriority(ioclass)
  1762. return _common.pionice(ioclass, value)
  1763. @wrap_exceptions
  1764. def ionice_set(self, ioclass, value):
  1765. if value is None:
  1766. value = 0
  1767. if value and ioclass in (IOPRIO_CLASS_IDLE, IOPRIO_CLASS_NONE):
  1768. raise ValueError("%r ioclass accepts no value" % ioclass)
  1769. if value < 0 or value > 7:
  1770. raise ValueError("value not in 0-7 range")
  1771. return cext.proc_ioprio_set(self.pid, ioclass, value)
  1772. if HAS_PRLIMIT:
  1773. @wrap_exceptions
  1774. def rlimit(self, resource, limits=None):
  1775. # If pid is 0 prlimit() applies to the calling process and
  1776. # we don't want that. We should never get here though as
  1777. # PID 0 is not supported on Linux.
  1778. if self.pid == 0:
  1779. raise ValueError("can't use prlimit() against PID 0 process")
  1780. try:
  1781. if limits is None:
  1782. # get
  1783. return cext.linux_prlimit(self.pid, resource)
  1784. else:
  1785. # set
  1786. if len(limits) != 2:
  1787. raise ValueError(
  1788. "second argument must be a (soft, hard) tuple, "
  1789. "got %s" % repr(limits))
  1790. soft, hard = limits
  1791. cext.linux_prlimit(self.pid, resource, soft, hard)
  1792. except OSError as err:
  1793. if err.errno == errno.ENOSYS and pid_exists(self.pid):
  1794. # I saw this happening on Travis:
  1795. # https://travis-ci.org/giampaolo/psutil/jobs/51368273
  1796. raise ZombieProcess(self.pid, self._name, self._ppid)
  1797. else:
  1798. raise
  1799. @wrap_exceptions
  1800. def status(self):
  1801. letter = self._parse_stat_file()['status']
  1802. if PY3:
  1803. letter = letter.decode()
  1804. # XXX is '?' legit? (we're not supposed to return it anyway)
  1805. return PROC_STATUSES.get(letter, '?')
  1806. @wrap_exceptions
  1807. def open_files(self):
  1808. retlist = []
  1809. files = os.listdir("%s/%s/fd" % (self._procfs_path, self.pid))
  1810. hit_enoent = False
  1811. for fd in files:
  1812. file = "%s/%s/fd/%s" % (self._procfs_path, self.pid, fd)
  1813. try:
  1814. path = readlink(file)
  1815. except (FileNotFoundError, ProcessLookupError):
  1816. # ENOENT == file which is gone in the meantime
  1817. hit_enoent = True
  1818. continue
  1819. except OSError as err:
  1820. if err.errno == errno.EINVAL:
  1821. # not a link
  1822. continue
  1823. raise
  1824. else:
  1825. # If path is not an absolute there's no way to tell
  1826. # whether it's a regular file or not, so we skip it.
  1827. # A regular file is always supposed to be have an
  1828. # absolute path though.
  1829. if path.startswith('/') and isfile_strict(path):
  1830. # Get file position and flags.
  1831. file = "%s/%s/fdinfo/%s" % (
  1832. self._procfs_path, self.pid, fd)
  1833. try:
  1834. with open_binary(file) as f:
  1835. pos = int(f.readline().split()[1])
  1836. flags = int(f.readline().split()[1], 8)
  1837. except FileNotFoundError:
  1838. # fd gone in the meantime; process may
  1839. # still be alive
  1840. hit_enoent = True
  1841. else:
  1842. mode = file_flags_to_mode(flags)
  1843. ntuple = popenfile(
  1844. path, int(fd), int(pos), mode, flags)
  1845. retlist.append(ntuple)
  1846. if hit_enoent:
  1847. self._assert_alive()
  1848. return retlist
  1849. @wrap_exceptions
  1850. def connections(self, kind='inet'):
  1851. ret = _connections.retrieve(kind, self.pid)
  1852. self._assert_alive()
  1853. return ret
  1854. @wrap_exceptions
  1855. def num_fds(self):
  1856. return len(os.listdir("%s/%s/fd" % (self._procfs_path, self.pid)))
  1857. @wrap_exceptions
  1858. def ppid(self):
  1859. return int(self._parse_stat_file()['ppid'])
  1860. @wrap_exceptions
  1861. def uids(self, _uids_re=re.compile(br'Uid:\t(\d+)\t(\d+)\t(\d+)')):
  1862. data = self._read_status_file()
  1863. real, effective, saved = _uids_re.findall(data)[0]
  1864. return _common.puids(int(real), int(effective), int(saved))
  1865. @wrap_exceptions
  1866. def gids(self, _gids_re=re.compile(br'Gid:\t(\d+)\t(\d+)\t(\d+)')):
  1867. data = self._read_status_file()
  1868. real, effective, saved = _gids_re.findall(data)[0]
  1869. return _common.pgids(int(real), int(effective), int(saved))