-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy path_pslinux.py
2265 lines (2018 loc) · 84.9 KB
/
_pslinux.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Linux platform implementation."""
from __future__ import division
import base64
import collections
import errno
import functools
import glob
import os
import re
import socket
import struct
import sys
import traceback
import warnings
from collections import defaultdict
from collections import namedtuple
from . import _common
from . import _psposix
from . import _psutil_linux as cext
from . import _psutil_posix as cext_posix
from ._common import NIC_DUPLEX_FULL
from ._common import NIC_DUPLEX_HALF
from ._common import NIC_DUPLEX_UNKNOWN
from ._common import AccessDenied
from ._common import NoSuchProcess
from ._common import ZombieProcess
from ._common import bcat
from ._common import cat
from ._common import debug
from ._common import decode
from ._common import get_procfs_path
from ._common import isfile_strict
from ._common import memoize
from ._common import memoize_when_activated
from ._common import open_binary
from ._common import open_text
from ._common import parse_environ_block
from ._common import path_exists_strict
from ._common import supports_ipv6
from ._common import usage_percent
from ._compat import PY3
from ._compat import FileNotFoundError
from ._compat import PermissionError
from ._compat import ProcessLookupError
from ._compat import b
from ._compat import basestring
if sys.version_info >= (3, 4):
import enum
else:
enum = None
__extra__all__ = [
#
'PROCFS_PATH',
# io prio constants
"IOPRIO_CLASS_NONE", "IOPRIO_CLASS_RT", "IOPRIO_CLASS_BE",
"IOPRIO_CLASS_IDLE",
# connection status constants
"CONN_ESTABLISHED", "CONN_SYN_SENT", "CONN_SYN_RECV", "CONN_FIN_WAIT1",
"CONN_FIN_WAIT2", "CONN_TIME_WAIT", "CONN_CLOSE", "CONN_CLOSE_WAIT",
"CONN_LAST_ACK", "CONN_LISTEN", "CONN_CLOSING", ]
# =====================================================================
# --- globals
# =====================================================================
POWER_SUPPLY_PATH = "/sys/class/power_supply"
HAS_PROC_SMAPS = os.path.exists('/proc/%s/smaps' % os.getpid())
HAS_PROC_SMAPS_ROLLUP = os.path.exists('/proc/%s/smaps_rollup' % os.getpid())
HAS_PROC_IO_PRIORITY = hasattr(cext, "proc_ioprio_get")
HAS_CPU_AFFINITY = hasattr(cext, "proc_cpu_affinity_get")
# Number of clock ticks per second
CLOCK_TICKS = os.sysconf("SC_CLK_TCK")
PAGESIZE = cext_posix.getpagesize()
BOOT_TIME = None # set later
LITTLE_ENDIAN = sys.byteorder == 'little'
# "man iostat" states that sectors are equivalent with blocks and have
# a size of 512 bytes. Despite this value can be queried at runtime
# via /sys/block/{DISK}/queue/hw_sector_size and results may vary
# between 1k, 2k, or 4k... 512 appears to be a magic constant used
# throughout Linux source code:
# * https://stackoverflow.com/a/38136179/376587
# * https://lists.gt.net/linux/kernel/2241060
# * https://github.com/giampaolo/psutil/issues/1305
# * https://github.com/torvalds/linux/blob/
# 4f671fe2f9523a1ea206f63fe60a7c7b3a56d5c7/include/linux/bio.h#L99
# * https://lkml.org/lkml/2015/8/17/234
DISK_SECTOR_SIZE = 512
if enum is None:
AF_LINK = socket.AF_PACKET
else:
AddressFamily = enum.IntEnum('AddressFamily',
{'AF_LINK': int(socket.AF_PACKET)})
AF_LINK = AddressFamily.AF_LINK
# ioprio_* constants http://linux.die.net/man/2/ioprio_get
if enum is None:
IOPRIO_CLASS_NONE = 0
IOPRIO_CLASS_RT = 1
IOPRIO_CLASS_BE = 2
IOPRIO_CLASS_IDLE = 3
else:
class IOPriority(enum.IntEnum):
IOPRIO_CLASS_NONE = 0
IOPRIO_CLASS_RT = 1
IOPRIO_CLASS_BE = 2
IOPRIO_CLASS_IDLE = 3
globals().update(IOPriority.__members__)
# See:
# https://github.com/torvalds/linux/blame/master/fs/proc/array.c
# ...and (TASK_* constants):
# https://github.com/torvalds/linux/blob/master/include/linux/sched.h
PROC_STATUSES = {
"R": _common.STATUS_RUNNING,
"S": _common.STATUS_SLEEPING,
"D": _common.STATUS_DISK_SLEEP,
"T": _common.STATUS_STOPPED,
"t": _common.STATUS_TRACING_STOP,
"Z": _common.STATUS_ZOMBIE,
"X": _common.STATUS_DEAD,
"x": _common.STATUS_DEAD,
"K": _common.STATUS_WAKE_KILL,
"W": _common.STATUS_WAKING,
"I": _common.STATUS_IDLE,
"P": _common.STATUS_PARKED,
}
# https://github.com/torvalds/linux/blob/master/include/net/tcp_states.h
TCP_STATUSES = {
"01": _common.CONN_ESTABLISHED,
"02": _common.CONN_SYN_SENT,
"03": _common.CONN_SYN_RECV,
"04": _common.CONN_FIN_WAIT1,
"05": _common.CONN_FIN_WAIT2,
"06": _common.CONN_TIME_WAIT,
"07": _common.CONN_CLOSE,
"08": _common.CONN_CLOSE_WAIT,
"09": _common.CONN_LAST_ACK,
"0A": _common.CONN_LISTEN,
"0B": _common.CONN_CLOSING
}
# =====================================================================
# --- named tuples
# =====================================================================
# psutil.virtual_memory()
svmem = namedtuple(
'svmem', ['total', 'available', 'percent', 'used', 'free',
'active', 'inactive', 'buffers', 'cached', 'shared', 'slab'])
# psutil.disk_io_counters()
sdiskio = namedtuple(
'sdiskio', ['read_count', 'write_count',
'read_bytes', 'write_bytes',
'read_time', 'write_time',
'read_merged_count', 'write_merged_count',
'busy_time'])
# psutil.Process().open_files()
popenfile = namedtuple(
'popenfile', ['path', 'fd', 'position', 'mode', 'flags'])
# psutil.Process().memory_info()
pmem = namedtuple('pmem', 'rss vms shared text lib data dirty')
# psutil.Process().memory_full_info()
pfullmem = namedtuple('pfullmem', pmem._fields + ('uss', 'pss', 'swap'))
# psutil.Process().memory_maps(grouped=True)
pmmap_grouped = namedtuple(
'pmmap_grouped',
['path', 'rss', 'size', 'pss', 'shared_clean', 'shared_dirty',
'private_clean', 'private_dirty', 'referenced', 'anonymous', 'swap'])
# psutil.Process().memory_maps(grouped=False)
pmmap_ext = namedtuple(
'pmmap_ext', 'addr perms ' + ' '.join(pmmap_grouped._fields))
# psutil.Process.io_counters()
pio = namedtuple('pio', ['read_count', 'write_count',
'read_bytes', 'write_bytes',
'read_chars', 'write_chars'])
# psutil.Process.cpu_times()
pcputimes = namedtuple('pcputimes',
['user', 'system', 'children_user', 'children_system',
'iowait'])
# =====================================================================
# --- utils
# =====================================================================
def readlink(path):
"""Wrapper around os.readlink()."""
assert isinstance(path, basestring), path
path = os.readlink(path)
# readlink() might return paths containing null bytes ('\x00')
# resulting in "TypeError: must be encoded string without NULL
# bytes, not str" errors when the string is passed to other
# fs-related functions (os.*, open(), ...).
# Apparently everything after '\x00' is garbage (we can have
# ' (deleted)', 'new' and possibly others), see:
# https://github.com/giampaolo/psutil/issues/717
path = path.split('\x00')[0]
# Certain paths have ' (deleted)' appended. Usually this is
# bogus as the file actually exists. Even if it doesn't we
# don't care.
if path.endswith(' (deleted)') and not path_exists_strict(path):
path = path[:-10]
return path
def file_flags_to_mode(flags):
"""Convert file's open() flags into a readable string.
Used by Process.open_files().
"""
modes_map = {os.O_RDONLY: 'r', os.O_WRONLY: 'w', os.O_RDWR: 'w+'}
mode = modes_map[flags & (os.O_RDONLY | os.O_WRONLY | os.O_RDWR)]
if flags & os.O_APPEND:
mode = mode.replace('w', 'a', 1)
mode = mode.replace('w+', 'r+')
# possible values: r, w, a, r+, a+
return mode
def is_storage_device(name):
"""Return True if the given name refers to a root device (e.g.
"sda", "nvme0n1") as opposed to a logical partition (e.g. "sda1",
"nvme0n1p1"). If name is a virtual device (e.g. "loop1", "ram")
return True.
"""
# Re-adapted from iostat source code, see:
# https://github.com/sysstat/sysstat/blob/
# 97912938cd476645b267280069e83b1c8dc0e1c7/common.c#L208
# Some devices may have a slash in their name (e.g. cciss/c0d0...).
name = name.replace('/', '!')
including_virtual = True
if including_virtual:
path = "/sys/block/%s" % name
else:
path = "/sys/block/%s/device" % name
return os.access(path, os.F_OK)
@memoize
def set_scputimes_ntuple(procfs_path):
"""Set a namedtuple of variable fields depending on the CPU times
available on this Linux kernel version which may be:
(user, nice, system, idle, iowait, irq, softirq, [steal, [guest,
[guest_nice]]])
Used by cpu_times() function.
"""
global scputimes
with open_binary('%s/stat' % procfs_path) as f:
values = f.readline().split()[1:]
fields = ['user', 'nice', 'system', 'idle', 'iowait', 'irq', 'softirq']
vlen = len(values)
if vlen >= 8:
# Linux >= 2.6.11
fields.append('steal')
if vlen >= 9:
# Linux >= 2.6.24
fields.append('guest')
if vlen >= 10:
# Linux >= 3.2.0
fields.append('guest_nice')
scputimes = namedtuple('scputimes', fields)
try:
set_scputimes_ntuple("/proc")
except Exception: # pragma: no cover
# Don't want to crash at import time.
traceback.print_exc()
scputimes = namedtuple('scputimes', 'user system idle')(0.0, 0.0, 0.0)
# =====================================================================
# --- prlimit
# =====================================================================
# Backport of resource.prlimit() for Python 2. Originally this was done
# in C, but CentOS-6 which we use to create manylinux wheels is too old
# and does not support prlimit() syscall. As such the resulting wheel
# would not include prlimit(), even when installed on newer systems.
# This is the only part of psutil using ctypes.
prlimit = None
try:
from resource import prlimit # python >= 3.4
except ImportError:
import ctypes
libc = ctypes.CDLL(None, use_errno=True)
if hasattr(libc, "prlimit"):
def prlimit(pid, resource_, limits=None):
class StructRlimit(ctypes.Structure):
_fields_ = [('rlim_cur', ctypes.c_longlong),
('rlim_max', ctypes.c_longlong)]
current = StructRlimit()
if limits is None:
# get
ret = libc.prlimit(pid, resource_, None, ctypes.byref(current))
else:
# set
new = StructRlimit()
new.rlim_cur = limits[0]
new.rlim_max = limits[1]
ret = libc.prlimit(
pid, resource_, ctypes.byref(new), ctypes.byref(current))
if ret != 0:
errno_ = ctypes.get_errno()
raise OSError(errno_, os.strerror(errno_))
return (current.rlim_cur, current.rlim_max)
if prlimit is not None:
__extra__all__.extend(
[x for x in dir(cext) if x.startswith('RLIM') and x.isupper()])
# =====================================================================
# --- system memory
# =====================================================================
def calculate_avail_vmem(mems):
"""Fallback for kernels < 3.14 where /proc/meminfo does not provide
"MemAvailable", see:
https://blog.famzah.net/2014/09/24/
This code reimplements the algorithm outlined here:
https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/
commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773
We use this function also when "MemAvailable" returns 0 (possibly a
kernel bug, see: https://github.com/giampaolo/psutil/issues/1915).
In that case this routine matches "free" CLI tool result ("available"
column).
XXX: on recent kernels this calculation may differ by ~1.5% compared
to "MemAvailable:", as it's calculated slightly differently.
It is still way more realistic than doing (free + cached) though.
See:
* https://gitlab.com/procps-ng/procps/issues/42
* https://github.com/famzah/linux-memavailable-procfs/issues/2
"""
# Note about "fallback" value. According to:
# https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/
# commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773
# ...long ago "available" memory was calculated as (free + cached),
# We use fallback when one of these is missing from /proc/meminfo:
# "Active(file)": introduced in 2.6.28 / Dec 2008
# "Inactive(file)": introduced in 2.6.28 / Dec 2008
# "SReclaimable": introduced in 2.6.19 / Nov 2006
# /proc/zoneinfo: introduced in 2.6.13 / Aug 2005
free = mems[b'MemFree:']
fallback = free + mems.get(b"Cached:", 0)
try:
lru_active_file = mems[b'Active(file):']
lru_inactive_file = mems[b'Inactive(file):']
slab_reclaimable = mems[b'SReclaimable:']
except KeyError as err:
debug("%r is missing from /proc/meminfo; using an approximation "
"for calculating available memory" % err.args[0])
return fallback
try:
f = open_binary('%s/zoneinfo' % get_procfs_path())
except IOError:
return fallback # kernel 2.6.13
watermark_low = 0
with f:
for line in f:
line = line.strip()
if line.startswith(b'low'):
watermark_low += int(line.split()[1])
watermark_low *= PAGESIZE
avail = free - watermark_low
pagecache = lru_active_file + lru_inactive_file
pagecache -= min(pagecache / 2, watermark_low)
avail += pagecache
avail += slab_reclaimable - min(slab_reclaimable / 2.0, watermark_low)
return int(avail)
def virtual_memory():
"""Report virtual memory stats.
This implementation mimicks procps-ng-3.3.12, aka "free" CLI tool:
https://gitlab.com/procps-ng/procps/blob/
24fd2605c51fccc375ab0287cec33aa767f06718/proc/sysinfo.c#L778-791
The returned values are supposed to match both "free" and "vmstat -s"
CLI tools.
"""
missing_fields = []
mems = {}
with open_binary('%s/meminfo' % get_procfs_path()) as f:
for line in f:
fields = line.split()
mems[fields[0]] = int(fields[1]) * 1024
# /proc doc states that the available fields in /proc/meminfo vary
# by architecture and compile options, but these 3 values are also
# returned by sysinfo(2); as such we assume they are always there.
total = mems[b'MemTotal:']
free = mems[b'MemFree:']
try:
buffers = mems[b'Buffers:']
except KeyError:
# https://github.com/giampaolo/psutil/issues/1010
buffers = 0
missing_fields.append('buffers')
try:
cached = mems[b"Cached:"]
except KeyError:
cached = 0
missing_fields.append('cached')
else:
# "free" cmdline utility sums reclaimable to cached.
# Older versions of procps used to add slab memory instead.
# This got changed in:
# https://gitlab.com/procps-ng/procps/commit/
# 05d751c4f076a2f0118b914c5e51cfbb4762ad8e
cached += mems.get(b"SReclaimable:", 0) # since kernel 2.6.19
try:
shared = mems[b'Shmem:'] # since kernel 2.6.32
except KeyError:
try:
shared = mems[b'MemShared:'] # kernels 2.4
except KeyError:
shared = 0
missing_fields.append('shared')
try:
active = mems[b"Active:"]
except KeyError:
active = 0
missing_fields.append('active')
try:
inactive = mems[b"Inactive:"]
except KeyError:
try:
inactive = \
mems[b"Inact_dirty:"] + \
mems[b"Inact_clean:"] + \
mems[b"Inact_laundry:"]
except KeyError:
inactive = 0
missing_fields.append('inactive')
try:
slab = mems[b"Slab:"]
except KeyError:
slab = 0
used = total - free - cached - buffers
if used < 0:
# May be symptomatic of running within a LCX container where such
# values will be dramatically distorted over those of the host.
used = total - free
# - starting from 4.4.0 we match free's "available" column.
# Before 4.4.0 we calculated it as (free + buffers + cached)
# which matched htop.
# - free and htop available memory differs as per:
# http://askubuntu.com/a/369589
# http://unix.stackexchange.com/a/65852/168884
# - MemAvailable has been introduced in kernel 3.14
try:
avail = mems[b'MemAvailable:']
except KeyError:
avail = calculate_avail_vmem(mems)
else:
if avail == 0:
# Yes, it can happen (probably a kernel bug):
# https://github.com/giampaolo/psutil/issues/1915
# In this case "free" CLI tool makes an estimate. We do the same,
# and it matches "free" CLI tool.
avail = calculate_avail_vmem(mems)
if avail < 0:
avail = 0
missing_fields.append('available')
elif avail > total:
# If avail is greater than total or our calculation overflows,
# that's symptomatic of running within a LCX container where such
# values will be dramatically distorted over those of the host.
# https://gitlab.com/procps-ng/procps/blob/
# 24fd2605c51fccc375ab0287cec33aa767f06718/proc/sysinfo.c#L764
avail = free
percent = usage_percent((total - avail), total, round_=1)
# Warn about missing metrics which are set to 0.
if missing_fields:
msg = "%s memory stats couldn't be determined and %s set to 0" % (
", ".join(missing_fields),
"was" if len(missing_fields) == 1 else "were")
warnings.warn(msg, RuntimeWarning, stacklevel=2)
return svmem(total, avail, percent, used, free,
active, inactive, buffers, cached, shared, slab)
def swap_memory():
"""Return swap memory metrics."""
mems = {}
with open_binary('%s/meminfo' % get_procfs_path()) as f:
for line in f:
fields = line.split()
mems[fields[0]] = int(fields[1]) * 1024
# We prefer /proc/meminfo over sysinfo() syscall so that
# psutil.PROCFS_PATH can be used in order to allow retrieval
# for linux containers, see:
# https://github.com/giampaolo/psutil/issues/1015
try:
total = mems[b'SwapTotal:']
free = mems[b'SwapFree:']
except KeyError:
_, _, _, _, total, free, unit_multiplier = cext.linux_sysinfo()
total *= unit_multiplier
free *= unit_multiplier
used = total - free
percent = usage_percent(used, total, round_=1)
# get pgin/pgouts
try:
f = open_binary("%s/vmstat" % get_procfs_path())
except IOError as err:
# see https://github.com/giampaolo/psutil/issues/722
msg = "'sin' and 'sout' swap memory stats couldn't " \
"be determined and were set to 0 (%s)" % str(err)
warnings.warn(msg, RuntimeWarning, stacklevel=2)
sin = sout = 0
else:
with f:
sin = sout = None
for line in f:
# values are expressed in 4 kilo bytes, we want
# bytes instead
if line.startswith(b'pswpin'):
sin = int(line.split(b' ')[1]) * 4 * 1024
elif line.startswith(b'pswpout'):
sout = int(line.split(b' ')[1]) * 4 * 1024
if sin is not None and sout is not None:
break
else:
# we might get here when dealing with exotic Linux
# flavors, see:
# https://github.com/giampaolo/psutil/issues/313
msg = "'sin' and 'sout' swap memory stats couldn't " \
"be determined and were set to 0"
warnings.warn(msg, RuntimeWarning, stacklevel=2)
sin = sout = 0
return _common.sswap(total, used, free, percent, sin, sout)
# =====================================================================
# --- CPU
# =====================================================================
def cpu_times():
"""Return a named tuple representing the following system-wide
CPU times:
(user, nice, system, idle, iowait, irq, softirq [steal, [guest,
[guest_nice]]])
Last 3 fields may not be available on all Linux kernel versions.
"""
procfs_path = get_procfs_path()
set_scputimes_ntuple(procfs_path)
with open_binary('%s/stat' % procfs_path) as f:
values = f.readline().split()
fields = values[1:len(scputimes._fields) + 1]
fields = [float(x) / CLOCK_TICKS for x in fields]
return scputimes(*fields)
def per_cpu_times():
"""Return a list of namedtuple representing the CPU times
for every CPU available on the system.
"""
procfs_path = get_procfs_path()
set_scputimes_ntuple(procfs_path)
cpus = []
with open_binary('%s/stat' % procfs_path) as f:
# get rid of the first line which refers to system wide CPU stats
f.readline()
for line in f:
if line.startswith(b'cpu'):
values = line.split()
fields = values[1:len(scputimes._fields) + 1]
fields = [float(x) / CLOCK_TICKS for x in fields]
entry = scputimes(*fields)
cpus.append(entry)
return cpus
def cpu_count_logical():
"""Return the number of logical CPUs in the system."""
try:
return os.sysconf("SC_NPROCESSORS_ONLN")
except ValueError:
# as a second fallback we try to parse /proc/cpuinfo
num = 0
with open_binary('%s/cpuinfo' % get_procfs_path()) as f:
for line in f:
if line.lower().startswith(b'processor'):
num += 1
# unknown format (e.g. amrel/sparc architectures), see:
# https://github.com/giampaolo/psutil/issues/200
# try to parse /proc/stat as a last resort
if num == 0:
search = re.compile(r'cpu\d')
with open_text('%s/stat' % get_procfs_path()) as f:
for line in f:
line = line.split(' ')[0]
if search.match(line):
num += 1
if num == 0:
# mimic os.cpu_count()
return None
return num
def cpu_count_cores():
"""Return the number of CPU cores in the system."""
# Method #1
ls = set()
# These 2 files are the same but */core_cpus_list is newer while
# */thread_siblings_list is deprecated and may disappear in the future.
# https://www.kernel.org/doc/Documentation/admin-guide/cputopology.rst
# https://github.com/giampaolo/psutil/pull/1727#issuecomment-707624964
# https://lkml.org/lkml/2019/2/26/41
p1 = "/sys/devices/system/cpu/cpu[0-9]*/topology/core_cpus_list"
p2 = "/sys/devices/system/cpu/cpu[0-9]*/topology/thread_siblings_list"
for path in glob.glob(p1) or glob.glob(p2):
with open_binary(path) as f:
ls.add(f.read().strip())
result = len(ls)
if result != 0:
return result
# Method #2
mapping = {}
current_info = {}
with open_binary('%s/cpuinfo' % get_procfs_path()) as f:
for line in f:
line = line.strip().lower()
if not line:
# new section
try:
mapping[current_info[b'physical id']] = \
current_info[b'cpu cores']
except KeyError:
pass
current_info = {}
else:
# ongoing section
if line.startswith((b'physical id', b'cpu cores')):
key, value = line.split(b'\t:', 1)
current_info[key] = int(value)
result = sum(mapping.values())
return result or None # mimic os.cpu_count()
def cpu_stats():
"""Return various CPU stats as a named tuple."""
with open_binary('%s/stat' % get_procfs_path()) as f:
ctx_switches = None
interrupts = None
soft_interrupts = None
for line in f:
if line.startswith(b'ctxt'):
ctx_switches = int(line.split()[1])
elif line.startswith(b'intr'):
interrupts = int(line.split()[1])
elif line.startswith(b'softirq'):
soft_interrupts = int(line.split()[1])
if ctx_switches is not None and soft_interrupts is not None \
and interrupts is not None:
break
syscalls = 0
return _common.scpustats(
ctx_switches, interrupts, soft_interrupts, syscalls)
def _cpu_get_cpuinfo_freq():
"""Return current CPU frequency from cpuinfo if available.
"""
ret = []
with open_binary('%s/cpuinfo' % get_procfs_path()) as f:
for line in f:
if line.lower().startswith(b'cpu mhz'):
ret.append(float(line.split(b':', 1)[1]))
return ret
if os.path.exists("/sys/devices/system/cpu/cpufreq/policy0") or \
os.path.exists("/sys/devices/system/cpu/cpu0/cpufreq"):
def cpu_freq():
"""Return frequency metrics for all CPUs.
Contrarily to other OSes, Linux updates these values in
real-time.
"""
cpuinfo_freqs = _cpu_get_cpuinfo_freq()
paths = \
glob.glob("/sys/devices/system/cpu/cpufreq/policy[0-9]*") or \
glob.glob("/sys/devices/system/cpu/cpu[0-9]*/cpufreq")
paths.sort(key=lambda x: int(re.search(r"[0-9]+", x).group()))
ret = []
pjoin = os.path.join
for i, path in enumerate(paths):
if len(paths) == len(cpuinfo_freqs):
# take cached value from cpuinfo if available, see:
# https://github.com/giampaolo/psutil/issues/1851
curr = cpuinfo_freqs[i] * 1000
else:
curr = bcat(pjoin(path, "scaling_cur_freq"), fallback=None)
if curr is None:
# Likely an old RedHat, see:
# https://github.com/giampaolo/psutil/issues/1071
curr = bcat(pjoin(path, "cpuinfo_cur_freq"), fallback=None)
if curr is None:
raise NotImplementedError(
"can't find current frequency file")
curr = int(curr) / 1000
max_ = int(bcat(pjoin(path, "scaling_max_freq"))) / 1000
min_ = int(bcat(pjoin(path, "scaling_min_freq"))) / 1000
ret.append(_common.scpufreq(curr, min_, max_))
return ret
else:
def cpu_freq():
"""Alternate implementation using /proc/cpuinfo.
min and max frequencies are not available and are set to None.
"""
return [_common.scpufreq(x, 0., 0.) for x in _cpu_get_cpuinfo_freq()]
# =====================================================================
# --- network
# =====================================================================
net_if_addrs = cext_posix.net_if_addrs
class _Ipv6UnsupportedError(Exception):
pass
class Connections:
"""A wrapper on top of /proc/net/* files, retrieving per-process
and system-wide open connections (TCP, UDP, UNIX) similarly to
"netstat -an".
Note: in case of UNIX sockets we're only able to determine the
local endpoint/path, not the one it's connected to.
According to [1] it would be possible but not easily.
[1] http://serverfault.com/a/417946
"""
def __init__(self):
# The string represents the basename of the corresponding
# /proc/net/{proto_name} file.
tcp4 = ("tcp", socket.AF_INET, socket.SOCK_STREAM)
tcp6 = ("tcp6", socket.AF_INET6, socket.SOCK_STREAM)
udp4 = ("udp", socket.AF_INET, socket.SOCK_DGRAM)
udp6 = ("udp6", socket.AF_INET6, socket.SOCK_DGRAM)
unix = ("unix", socket.AF_UNIX, None)
self.tmap = {
"all": (tcp4, tcp6, udp4, udp6, unix),
"tcp": (tcp4, tcp6),
"tcp4": (tcp4,),
"tcp6": (tcp6,),
"udp": (udp4, udp6),
"udp4": (udp4,),
"udp6": (udp6,),
"unix": (unix,),
"inet": (tcp4, tcp6, udp4, udp6),
"inet4": (tcp4, udp4),
"inet6": (tcp6, udp6),
}
self._procfs_path = None
def get_proc_inodes(self, pid):
inodes = defaultdict(list)
for fd in os.listdir("%s/%s/fd" % (self._procfs_path, pid)):
try:
inode = readlink("%s/%s/fd/%s" % (self._procfs_path, pid, fd))
except (FileNotFoundError, ProcessLookupError):
# ENOENT == file which is gone in the meantime;
# os.stat('/proc/%s' % self.pid) will be done later
# to force NSP (if it's the case)
continue
except OSError as err:
if err.errno == errno.EINVAL:
# not a link
continue
if err.errno == errno.ENAMETOOLONG:
# file name too long
debug(err)
continue
raise
else:
if inode.startswith('socket:['):
# the process is using a socket
inode = inode[8:][:-1]
inodes[inode].append((pid, int(fd)))
return inodes
def get_all_inodes(self):
inodes = {}
for pid in pids():
try:
inodes.update(self.get_proc_inodes(pid))
except (FileNotFoundError, ProcessLookupError, PermissionError):
# os.listdir() is gonna raise a lot of access denied
# exceptions in case of unprivileged user; that's fine
# as we'll just end up returning a connection with PID
# and fd set to None anyway.
# Both netstat -an and lsof does the same so it's
# unlikely we can do any better.
# ENOENT just means a PID disappeared on us.
continue
return inodes
@staticmethod
def decode_address(addr, family):
"""Accept an "ip:port" address as displayed in /proc/net/*
and convert it into a human readable form, like:
"0500000A:0016" -> ("10.0.0.5", 22)
"0000000000000000FFFF00000100007F:9E49" -> ("::ffff:127.0.0.1", 40521)
The IP address portion is a little or big endian four-byte
hexadecimal number; that is, the least significant byte is listed
first, so we need to reverse the order of the bytes to convert it
to an IP address.
The port is represented as a two-byte hexadecimal number.
Reference:
http://linuxdevcenter.com/pub/a/linux/2000/11/16/LinuxAdmin.html
"""
ip, port = addr.split(':')
port = int(port, 16)
# this usually refers to a local socket in listen mode with
# no end-points connected
if not port:
return ()
if PY3:
ip = ip.encode('ascii')
if family == socket.AF_INET:
# see: https://github.com/giampaolo/psutil/issues/201
if LITTLE_ENDIAN:
ip = socket.inet_ntop(family, base64.b16decode(ip)[::-1])
else:
ip = socket.inet_ntop(family, base64.b16decode(ip))
else: # IPv6
ip = base64.b16decode(ip)
try:
# see: https://github.com/giampaolo/psutil/issues/201
if LITTLE_ENDIAN:
ip = socket.inet_ntop(
socket.AF_INET6,
struct.pack('>4I', *struct.unpack('<4I', ip)))
else:
ip = socket.inet_ntop(
socket.AF_INET6,
struct.pack('<4I', *struct.unpack('<4I', ip)))
except ValueError:
# see: https://github.com/giampaolo/psutil/issues/623
if not supports_ipv6():
raise _Ipv6UnsupportedError
else:
raise
return _common.addr(ip, port)
@staticmethod
def process_inet(file, family, type_, inodes, filter_pid=None):
"""Parse /proc/net/tcp* and /proc/net/udp* files."""
if file.endswith('6') and not os.path.exists(file):
# IPv6 not supported
return
with open_text(file) as f:
f.readline() # skip the first line
for lineno, line in enumerate(f, 1):
try:
_, laddr, raddr, status, _, _, _, _, _, inode = \
line.split()[:10]
except ValueError:
raise RuntimeError(
"error while parsing %s; malformed line %s %r" % (
file, lineno, line))
if inode in inodes:
# # We assume inet sockets are unique, so we error
# # out if there are multiple references to the
# # same inode. We won't do this for UNIX sockets.
# if len(inodes[inode]) > 1 and family != socket.AF_UNIX:
# raise ValueError("ambiguous inode with multiple "
# "PIDs references")
pid, fd = inodes[inode][0]
else:
pid, fd = None, -1
if filter_pid is not None and filter_pid != pid:
continue
else:
if type_ == socket.SOCK_STREAM:
status = TCP_STATUSES[status]
else:
status = _common.CONN_NONE
try:
laddr = Connections.decode_address(laddr, family)
raddr = Connections.decode_address(raddr, family)
except _Ipv6UnsupportedError:
continue
yield (fd, family, type_, laddr, raddr, status, pid)
@staticmethod
def process_unix(file, family, inodes, filter_pid=None):
"""Parse /proc/net/unix files."""
with open_text(file) as f:
f.readline() # skip the first line
for line in f:
tokens = line.split()
try:
_, _, _, _, type_, _, inode = tokens[0:7]
except ValueError:
if ' ' not in line:
# see: https://github.com/giampaolo/psutil/issues/766
continue
raise RuntimeError(
"error while parsing %s; malformed line %r" % (
file, line))
if inode in inodes:
# With UNIX sockets we can have a single inode
# referencing many file descriptors.
pairs = inodes[inode]
else:
pairs = [(None, -1)]
for pid, fd in pairs:
if filter_pid is not None and filter_pid != pid:
continue
else:
if len(tokens) == 8:
path = tokens[-1]
else:
path = ""
type_ = _common.socktype_to_enum(int(type_))
# XXX: determining the remote endpoint of a
# UNIX socket on Linux is not possible, see:
# https://serverfault.com/questions/252723/
raddr = ""
status = _common.CONN_NONE
yield (fd, family, type_, path, raddr, status, pid)
def retrieve(self, kind, pid=None):
if kind not in self.tmap:
raise ValueError("invalid %r kind argument; choose between %s"
% (kind, ', '.join([repr(x) for x in self.tmap])))
self._procfs_path = get_procfs_path()
if pid is not None:
inodes = self.get_proc_inodes(pid)
if not inodes:
# no connections for this process
return []
else:
inodes = self.get_all_inodes()
ret = set()
for proto_name, family, type_ in self.tmap[kind]:
path = "%s/net/%s" % (self._procfs_path, proto_name)
if family in (socket.AF_INET, socket.AF_INET6):
ls = self.process_inet(
path, family, type_, inodes, filter_pid=pid)