Mercurial > repos > shellac > guppy_basecaller
comparison env/lib/python3.7/site-packages/psutil/_pssunos.py @ 5:9b1c78e6ba9c draft default tip
"planemo upload commit 6c0a8142489327ece472c84e558c47da711a9142"
author | shellac |
---|---|
date | Mon, 01 Jun 2020 08:59:25 -0400 |
parents | 79f47841a781 |
children |
comparison
equal
deleted
inserted
replaced
4:79f47841a781 | 5:9b1c78e6ba9c |
---|---|
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 | |
5 """Sun OS Solaris platform implementation.""" | |
6 | |
7 import errno | |
8 import functools | |
9 import os | |
10 import socket | |
11 import subprocess | |
12 import sys | |
13 from collections import namedtuple | |
14 from socket import AF_INET | |
15 | |
16 from . import _common | |
17 from . import _psposix | |
18 from . import _psutil_posix as cext_posix | |
19 from . import _psutil_sunos as cext | |
20 from ._common import AccessDenied | |
21 from ._common import AF_INET6 | |
22 from ._common import debug | |
23 from ._common import get_procfs_path | |
24 from ._common import isfile_strict | |
25 from ._common import memoize_when_activated | |
26 from ._common import NoSuchProcess | |
27 from ._common import sockfam_to_enum | |
28 from ._common import socktype_to_enum | |
29 from ._common import usage_percent | |
30 from ._common import ZombieProcess | |
31 from ._compat import b | |
32 from ._compat import FileNotFoundError | |
33 from ._compat import PermissionError | |
34 from ._compat import ProcessLookupError | |
35 from ._compat import PY3 | |
36 | |
37 | |
38 __extra__all__ = ["CONN_IDLE", "CONN_BOUND", "PROCFS_PATH"] | |
39 | |
40 | |
41 # ===================================================================== | |
42 # --- globals | |
43 # ===================================================================== | |
44 | |
45 | |
46 PAGE_SIZE = os.sysconf('SC_PAGE_SIZE') | |
47 AF_LINK = cext_posix.AF_LINK | |
48 IS_64_BIT = sys.maxsize > 2**32 | |
49 | |
50 CONN_IDLE = "IDLE" | |
51 CONN_BOUND = "BOUND" | |
52 | |
53 PROC_STATUSES = { | |
54 cext.SSLEEP: _common.STATUS_SLEEPING, | |
55 cext.SRUN: _common.STATUS_RUNNING, | |
56 cext.SZOMB: _common.STATUS_ZOMBIE, | |
57 cext.SSTOP: _common.STATUS_STOPPED, | |
58 cext.SIDL: _common.STATUS_IDLE, | |
59 cext.SONPROC: _common.STATUS_RUNNING, # same as run | |
60 cext.SWAIT: _common.STATUS_WAITING, | |
61 } | |
62 | |
63 TCP_STATUSES = { | |
64 cext.TCPS_ESTABLISHED: _common.CONN_ESTABLISHED, | |
65 cext.TCPS_SYN_SENT: _common.CONN_SYN_SENT, | |
66 cext.TCPS_SYN_RCVD: _common.CONN_SYN_RECV, | |
67 cext.TCPS_FIN_WAIT_1: _common.CONN_FIN_WAIT1, | |
68 cext.TCPS_FIN_WAIT_2: _common.CONN_FIN_WAIT2, | |
69 cext.TCPS_TIME_WAIT: _common.CONN_TIME_WAIT, | |
70 cext.TCPS_CLOSED: _common.CONN_CLOSE, | |
71 cext.TCPS_CLOSE_WAIT: _common.CONN_CLOSE_WAIT, | |
72 cext.TCPS_LAST_ACK: _common.CONN_LAST_ACK, | |
73 cext.TCPS_LISTEN: _common.CONN_LISTEN, | |
74 cext.TCPS_CLOSING: _common.CONN_CLOSING, | |
75 cext.PSUTIL_CONN_NONE: _common.CONN_NONE, | |
76 cext.TCPS_IDLE: CONN_IDLE, # sunos specific | |
77 cext.TCPS_BOUND: CONN_BOUND, # sunos specific | |
78 } | |
79 | |
80 proc_info_map = dict( | |
81 ppid=0, | |
82 rss=1, | |
83 vms=2, | |
84 create_time=3, | |
85 nice=4, | |
86 num_threads=5, | |
87 status=6, | |
88 ttynr=7, | |
89 uid=8, | |
90 euid=9, | |
91 gid=10, | |
92 egid=11) | |
93 | |
94 | |
95 # ===================================================================== | |
96 # --- named tuples | |
97 # ===================================================================== | |
98 | |
99 | |
100 # psutil.cpu_times() | |
101 scputimes = namedtuple('scputimes', ['user', 'system', 'idle', 'iowait']) | |
102 # psutil.cpu_times(percpu=True) | |
103 pcputimes = namedtuple('pcputimes', | |
104 ['user', 'system', 'children_user', 'children_system']) | |
105 # psutil.virtual_memory() | |
106 svmem = namedtuple('svmem', ['total', 'available', 'percent', 'used', 'free']) | |
107 # psutil.Process.memory_info() | |
108 pmem = namedtuple('pmem', ['rss', 'vms']) | |
109 pfullmem = pmem | |
110 # psutil.Process.memory_maps(grouped=True) | |
111 pmmap_grouped = namedtuple('pmmap_grouped', | |
112 ['path', 'rss', 'anonymous', 'locked']) | |
113 # psutil.Process.memory_maps(grouped=False) | |
114 pmmap_ext = namedtuple( | |
115 'pmmap_ext', 'addr perms ' + ' '.join(pmmap_grouped._fields)) | |
116 | |
117 | |
118 # ===================================================================== | |
119 # --- memory | |
120 # ===================================================================== | |
121 | |
122 | |
123 def virtual_memory(): | |
124 """Report virtual memory metrics.""" | |
125 # we could have done this with kstat, but IMHO this is good enough | |
126 total = os.sysconf('SC_PHYS_PAGES') * PAGE_SIZE | |
127 # note: there's no difference on Solaris | |
128 free = avail = os.sysconf('SC_AVPHYS_PAGES') * PAGE_SIZE | |
129 used = total - free | |
130 percent = usage_percent(used, total, round_=1) | |
131 return svmem(total, avail, percent, used, free) | |
132 | |
133 | |
134 def swap_memory(): | |
135 """Report swap memory metrics.""" | |
136 sin, sout = cext.swap_mem() | |
137 # XXX | |
138 # we are supposed to get total/free by doing so: | |
139 # http://cvs.opensolaris.org/source/xref/onnv/onnv-gate/ | |
140 # usr/src/cmd/swap/swap.c | |
141 # ...nevertheless I can't manage to obtain the same numbers as 'swap' | |
142 # cmdline utility, so let's parse its output (sigh!) | |
143 p = subprocess.Popen(['/usr/bin/env', 'PATH=/usr/sbin:/sbin:%s' % | |
144 os.environ['PATH'], 'swap', '-l'], | |
145 stdout=subprocess.PIPE) | |
146 stdout, stderr = p.communicate() | |
147 if PY3: | |
148 stdout = stdout.decode(sys.stdout.encoding) | |
149 if p.returncode != 0: | |
150 raise RuntimeError("'swap -l' failed (retcode=%s)" % p.returncode) | |
151 | |
152 lines = stdout.strip().split('\n')[1:] | |
153 if not lines: | |
154 raise RuntimeError('no swap device(s) configured') | |
155 total = free = 0 | |
156 for line in lines: | |
157 line = line.split() | |
158 t, f = line[-2:] | |
159 total += int(int(t) * 512) | |
160 free += int(int(f) * 512) | |
161 used = total - free | |
162 percent = usage_percent(used, total, round_=1) | |
163 return _common.sswap(total, used, free, percent, | |
164 sin * PAGE_SIZE, sout * PAGE_SIZE) | |
165 | |
166 | |
167 # ===================================================================== | |
168 # --- CPU | |
169 # ===================================================================== | |
170 | |
171 | |
172 def cpu_times(): | |
173 """Return system-wide CPU times as a named tuple""" | |
174 ret = cext.per_cpu_times() | |
175 return scputimes(*[sum(x) for x in zip(*ret)]) | |
176 | |
177 | |
178 def per_cpu_times(): | |
179 """Return system per-CPU times as a list of named tuples""" | |
180 ret = cext.per_cpu_times() | |
181 return [scputimes(*x) for x in ret] | |
182 | |
183 | |
184 def cpu_count_logical(): | |
185 """Return the number of logical CPUs in the system.""" | |
186 try: | |
187 return os.sysconf("SC_NPROCESSORS_ONLN") | |
188 except ValueError: | |
189 # mimic os.cpu_count() behavior | |
190 return None | |
191 | |
192 | |
193 def cpu_count_physical(): | |
194 """Return the number of physical CPUs in the system.""" | |
195 return cext.cpu_count_phys() | |
196 | |
197 | |
198 def cpu_stats(): | |
199 """Return various CPU stats as a named tuple.""" | |
200 ctx_switches, interrupts, syscalls, traps = cext.cpu_stats() | |
201 soft_interrupts = 0 | |
202 return _common.scpustats(ctx_switches, interrupts, soft_interrupts, | |
203 syscalls) | |
204 | |
205 | |
206 # ===================================================================== | |
207 # --- disks | |
208 # ===================================================================== | |
209 | |
210 | |
211 disk_io_counters = cext.disk_io_counters | |
212 disk_usage = _psposix.disk_usage | |
213 | |
214 | |
215 def disk_partitions(all=False): | |
216 """Return system disk partitions.""" | |
217 # TODO - the filtering logic should be better checked so that | |
218 # it tries to reflect 'df' as much as possible | |
219 retlist = [] | |
220 partitions = cext.disk_partitions() | |
221 for partition in partitions: | |
222 device, mountpoint, fstype, opts = partition | |
223 if device == 'none': | |
224 device = '' | |
225 if not all: | |
226 # Differently from, say, Linux, we don't have a list of | |
227 # common fs types so the best we can do, AFAIK, is to | |
228 # filter by filesystem having a total size > 0. | |
229 try: | |
230 if not disk_usage(mountpoint).total: | |
231 continue | |
232 except OSError as err: | |
233 # https://github.com/giampaolo/psutil/issues/1674 | |
234 debug("skipping %r: %r" % (mountpoint, err)) | |
235 continue | |
236 ntuple = _common.sdiskpart(device, mountpoint, fstype, opts) | |
237 retlist.append(ntuple) | |
238 return retlist | |
239 | |
240 | |
241 # ===================================================================== | |
242 # --- network | |
243 # ===================================================================== | |
244 | |
245 | |
246 net_io_counters = cext.net_io_counters | |
247 net_if_addrs = cext_posix.net_if_addrs | |
248 | |
249 | |
250 def net_connections(kind, _pid=-1): | |
251 """Return socket connections. If pid == -1 return system-wide | |
252 connections (as opposed to connections opened by one process only). | |
253 Only INET sockets are returned (UNIX are not). | |
254 """ | |
255 cmap = _common.conn_tmap.copy() | |
256 if _pid == -1: | |
257 cmap.pop('unix', 0) | |
258 if kind not in cmap: | |
259 raise ValueError("invalid %r kind argument; choose between %s" | |
260 % (kind, ', '.join([repr(x) for x in cmap]))) | |
261 families, types = _common.conn_tmap[kind] | |
262 rawlist = cext.net_connections(_pid) | |
263 ret = set() | |
264 for item in rawlist: | |
265 fd, fam, type_, laddr, raddr, status, pid = item | |
266 if fam not in families: | |
267 continue | |
268 if type_ not in types: | |
269 continue | |
270 # TODO: refactor and use _common.conn_to_ntuple. | |
271 if fam in (AF_INET, AF_INET6): | |
272 if laddr: | |
273 laddr = _common.addr(*laddr) | |
274 if raddr: | |
275 raddr = _common.addr(*raddr) | |
276 status = TCP_STATUSES[status] | |
277 fam = sockfam_to_enum(fam) | |
278 type_ = socktype_to_enum(type_) | |
279 if _pid == -1: | |
280 nt = _common.sconn(fd, fam, type_, laddr, raddr, status, pid) | |
281 else: | |
282 nt = _common.pconn(fd, fam, type_, laddr, raddr, status) | |
283 ret.add(nt) | |
284 return list(ret) | |
285 | |
286 | |
287 def net_if_stats(): | |
288 """Get NIC stats (isup, duplex, speed, mtu).""" | |
289 ret = cext.net_if_stats() | |
290 for name, items in ret.items(): | |
291 isup, duplex, speed, mtu = items | |
292 if hasattr(_common, 'NicDuplex'): | |
293 duplex = _common.NicDuplex(duplex) | |
294 ret[name] = _common.snicstats(isup, duplex, speed, mtu) | |
295 return ret | |
296 | |
297 | |
298 # ===================================================================== | |
299 # --- other system functions | |
300 # ===================================================================== | |
301 | |
302 | |
303 def boot_time(): | |
304 """The system boot time expressed in seconds since the epoch.""" | |
305 return cext.boot_time() | |
306 | |
307 | |
308 def users(): | |
309 """Return currently connected users as a list of namedtuples.""" | |
310 retlist = [] | |
311 rawlist = cext.users() | |
312 localhost = (':0.0', ':0') | |
313 for item in rawlist: | |
314 user, tty, hostname, tstamp, user_process, pid = item | |
315 # note: the underlying C function includes entries about | |
316 # system boot, run level and others. We might want | |
317 # to use them in the future. | |
318 if not user_process: | |
319 continue | |
320 if hostname in localhost: | |
321 hostname = 'localhost' | |
322 nt = _common.suser(user, tty, hostname, tstamp, pid) | |
323 retlist.append(nt) | |
324 return retlist | |
325 | |
326 | |
327 # ===================================================================== | |
328 # --- processes | |
329 # ===================================================================== | |
330 | |
331 | |
332 def pids(): | |
333 """Returns a list of PIDs currently running on the system.""" | |
334 return [int(x) for x in os.listdir(b(get_procfs_path())) if x.isdigit()] | |
335 | |
336 | |
337 def pid_exists(pid): | |
338 """Check for the existence of a unix pid.""" | |
339 return _psposix.pid_exists(pid) | |
340 | |
341 | |
342 def wrap_exceptions(fun): | |
343 """Call callable into a try/except clause and translate ENOENT, | |
344 EACCES and EPERM in NoSuchProcess or AccessDenied exceptions. | |
345 """ | |
346 @functools.wraps(fun) | |
347 def wrapper(self, *args, **kwargs): | |
348 try: | |
349 return fun(self, *args, **kwargs) | |
350 except (FileNotFoundError, ProcessLookupError): | |
351 # ENOENT (no such file or directory) gets raised on open(). | |
352 # ESRCH (no such process) can get raised on read() if | |
353 # process is gone in meantime. | |
354 if not pid_exists(self.pid): | |
355 raise NoSuchProcess(self.pid, self._name) | |
356 else: | |
357 raise ZombieProcess(self.pid, self._name, self._ppid) | |
358 except PermissionError: | |
359 raise AccessDenied(self.pid, self._name) | |
360 except OSError: | |
361 if self.pid == 0: | |
362 if 0 in pids(): | |
363 raise AccessDenied(self.pid, self._name) | |
364 else: | |
365 raise | |
366 raise | |
367 return wrapper | |
368 | |
369 | |
370 class Process(object): | |
371 """Wrapper class around underlying C implementation.""" | |
372 | |
373 __slots__ = ["pid", "_name", "_ppid", "_procfs_path", "_cache"] | |
374 | |
375 def __init__(self, pid): | |
376 self.pid = pid | |
377 self._name = None | |
378 self._ppid = None | |
379 self._procfs_path = get_procfs_path() | |
380 | |
381 def _assert_alive(self): | |
382 """Raise NSP if the process disappeared on us.""" | |
383 # For those C function who do not raise NSP, possibly returning | |
384 # incorrect or incomplete result. | |
385 os.stat('%s/%s' % (self._procfs_path, self.pid)) | |
386 | |
387 def oneshot_enter(self): | |
388 self._proc_name_and_args.cache_activate(self) | |
389 self._proc_basic_info.cache_activate(self) | |
390 self._proc_cred.cache_activate(self) | |
391 | |
392 def oneshot_exit(self): | |
393 self._proc_name_and_args.cache_deactivate(self) | |
394 self._proc_basic_info.cache_deactivate(self) | |
395 self._proc_cred.cache_deactivate(self) | |
396 | |
397 @wrap_exceptions | |
398 @memoize_when_activated | |
399 def _proc_name_and_args(self): | |
400 return cext.proc_name_and_args(self.pid, self._procfs_path) | |
401 | |
402 @wrap_exceptions | |
403 @memoize_when_activated | |
404 def _proc_basic_info(self): | |
405 if self.pid == 0 and not \ | |
406 os.path.exists('%s/%s/psinfo' % (self._procfs_path, self.pid)): | |
407 raise AccessDenied(self.pid) | |
408 ret = cext.proc_basic_info(self.pid, self._procfs_path) | |
409 assert len(ret) == len(proc_info_map) | |
410 return ret | |
411 | |
412 @wrap_exceptions | |
413 @memoize_when_activated | |
414 def _proc_cred(self): | |
415 return cext.proc_cred(self.pid, self._procfs_path) | |
416 | |
417 @wrap_exceptions | |
418 def name(self): | |
419 # note: max len == 15 | |
420 return self._proc_name_and_args()[0] | |
421 | |
422 @wrap_exceptions | |
423 def exe(self): | |
424 try: | |
425 return os.readlink( | |
426 "%s/%s/path/a.out" % (self._procfs_path, self.pid)) | |
427 except OSError: | |
428 pass # continue and guess the exe name from the cmdline | |
429 # Will be guessed later from cmdline but we want to explicitly | |
430 # invoke cmdline here in order to get an AccessDenied | |
431 # exception if the user has not enough privileges. | |
432 self.cmdline() | |
433 return "" | |
434 | |
435 @wrap_exceptions | |
436 def cmdline(self): | |
437 return self._proc_name_and_args()[1].split(' ') | |
438 | |
439 @wrap_exceptions | |
440 def environ(self): | |
441 return cext.proc_environ(self.pid, self._procfs_path) | |
442 | |
443 @wrap_exceptions | |
444 def create_time(self): | |
445 return self._proc_basic_info()[proc_info_map['create_time']] | |
446 | |
447 @wrap_exceptions | |
448 def num_threads(self): | |
449 return self._proc_basic_info()[proc_info_map['num_threads']] | |
450 | |
451 @wrap_exceptions | |
452 def nice_get(self): | |
453 # Note #1: getpriority(3) doesn't work for realtime processes. | |
454 # Psinfo is what ps uses, see: | |
455 # https://github.com/giampaolo/psutil/issues/1194 | |
456 return self._proc_basic_info()[proc_info_map['nice']] | |
457 | |
458 @wrap_exceptions | |
459 def nice_set(self, value): | |
460 if self.pid in (2, 3): | |
461 # Special case PIDs: internally setpriority(3) return ESRCH | |
462 # (no such process), no matter what. | |
463 # The process actually exists though, as it has a name, | |
464 # creation time, etc. | |
465 raise AccessDenied(self.pid, self._name) | |
466 return cext_posix.setpriority(self.pid, value) | |
467 | |
468 @wrap_exceptions | |
469 def ppid(self): | |
470 self._ppid = self._proc_basic_info()[proc_info_map['ppid']] | |
471 return self._ppid | |
472 | |
473 @wrap_exceptions | |
474 def uids(self): | |
475 try: | |
476 real, effective, saved, _, _, _ = self._proc_cred() | |
477 except AccessDenied: | |
478 real = self._proc_basic_info()[proc_info_map['uid']] | |
479 effective = self._proc_basic_info()[proc_info_map['euid']] | |
480 saved = None | |
481 return _common.puids(real, effective, saved) | |
482 | |
483 @wrap_exceptions | |
484 def gids(self): | |
485 try: | |
486 _, _, _, real, effective, saved = self._proc_cred() | |
487 except AccessDenied: | |
488 real = self._proc_basic_info()[proc_info_map['gid']] | |
489 effective = self._proc_basic_info()[proc_info_map['egid']] | |
490 saved = None | |
491 return _common.puids(real, effective, saved) | |
492 | |
493 @wrap_exceptions | |
494 def cpu_times(self): | |
495 try: | |
496 times = cext.proc_cpu_times(self.pid, self._procfs_path) | |
497 except OSError as err: | |
498 if err.errno == errno.EOVERFLOW and not IS_64_BIT: | |
499 # We may get here if we attempt to query a 64bit process | |
500 # with a 32bit python. | |
501 # Error originates from read() and also tools like "cat" | |
502 # fail in the same way (!). | |
503 # Since there simply is no way to determine CPU times we | |
504 # return 0.0 as a fallback. See: | |
505 # https://github.com/giampaolo/psutil/issues/857 | |
506 times = (0.0, 0.0, 0.0, 0.0) | |
507 else: | |
508 raise | |
509 return _common.pcputimes(*times) | |
510 | |
511 @wrap_exceptions | |
512 def cpu_num(self): | |
513 return cext.proc_cpu_num(self.pid, self._procfs_path) | |
514 | |
515 @wrap_exceptions | |
516 def terminal(self): | |
517 procfs_path = self._procfs_path | |
518 hit_enoent = False | |
519 tty = wrap_exceptions( | |
520 self._proc_basic_info()[proc_info_map['ttynr']]) | |
521 if tty != cext.PRNODEV: | |
522 for x in (0, 1, 2, 255): | |
523 try: | |
524 return os.readlink( | |
525 '%s/%d/path/%d' % (procfs_path, self.pid, x)) | |
526 except FileNotFoundError: | |
527 hit_enoent = True | |
528 continue | |
529 if hit_enoent: | |
530 self._assert_alive() | |
531 | |
532 @wrap_exceptions | |
533 def cwd(self): | |
534 # /proc/PID/path/cwd may not be resolved by readlink() even if | |
535 # it exists (ls shows it). If that's the case and the process | |
536 # is still alive return None (we can return None also on BSD). | |
537 # Reference: http://goo.gl/55XgO | |
538 procfs_path = self._procfs_path | |
539 try: | |
540 return os.readlink("%s/%s/path/cwd" % (procfs_path, self.pid)) | |
541 except FileNotFoundError: | |
542 os.stat("%s/%s" % (procfs_path, self.pid)) # raise NSP or AD | |
543 return None | |
544 | |
545 @wrap_exceptions | |
546 def memory_info(self): | |
547 ret = self._proc_basic_info() | |
548 rss = ret[proc_info_map['rss']] * 1024 | |
549 vms = ret[proc_info_map['vms']] * 1024 | |
550 return pmem(rss, vms) | |
551 | |
552 memory_full_info = memory_info | |
553 | |
554 @wrap_exceptions | |
555 def status(self): | |
556 code = self._proc_basic_info()[proc_info_map['status']] | |
557 # XXX is '?' legit? (we're not supposed to return it anyway) | |
558 return PROC_STATUSES.get(code, '?') | |
559 | |
560 @wrap_exceptions | |
561 def threads(self): | |
562 procfs_path = self._procfs_path | |
563 ret = [] | |
564 tids = os.listdir('%s/%d/lwp' % (procfs_path, self.pid)) | |
565 hit_enoent = False | |
566 for tid in tids: | |
567 tid = int(tid) | |
568 try: | |
569 utime, stime = cext.query_process_thread( | |
570 self.pid, tid, procfs_path) | |
571 except EnvironmentError as err: | |
572 if err.errno == errno.EOVERFLOW and not IS_64_BIT: | |
573 # We may get here if we attempt to query a 64bit process | |
574 # with a 32bit python. | |
575 # Error originates from read() and also tools like "cat" | |
576 # fail in the same way (!). | |
577 # Since there simply is no way to determine CPU times we | |
578 # return 0.0 as a fallback. See: | |
579 # https://github.com/giampaolo/psutil/issues/857 | |
580 continue | |
581 # ENOENT == thread gone in meantime | |
582 if err.errno == errno.ENOENT: | |
583 hit_enoent = True | |
584 continue | |
585 raise | |
586 else: | |
587 nt = _common.pthread(tid, utime, stime) | |
588 ret.append(nt) | |
589 if hit_enoent: | |
590 self._assert_alive() | |
591 return ret | |
592 | |
593 @wrap_exceptions | |
594 def open_files(self): | |
595 retlist = [] | |
596 hit_enoent = False | |
597 procfs_path = self._procfs_path | |
598 pathdir = '%s/%d/path' % (procfs_path, self.pid) | |
599 for fd in os.listdir('%s/%d/fd' % (procfs_path, self.pid)): | |
600 path = os.path.join(pathdir, fd) | |
601 if os.path.islink(path): | |
602 try: | |
603 file = os.readlink(path) | |
604 except FileNotFoundError: | |
605 hit_enoent = True | |
606 continue | |
607 else: | |
608 if isfile_strict(file): | |
609 retlist.append(_common.popenfile(file, int(fd))) | |
610 if hit_enoent: | |
611 self._assert_alive() | |
612 return retlist | |
613 | |
614 def _get_unix_sockets(self, pid): | |
615 """Get UNIX sockets used by process by parsing 'pfiles' output.""" | |
616 # TODO: rewrite this in C (...but the damn netstat source code | |
617 # does not include this part! Argh!!) | |
618 cmd = "pfiles %s" % pid | |
619 p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, | |
620 stderr=subprocess.PIPE) | |
621 stdout, stderr = p.communicate() | |
622 if PY3: | |
623 stdout, stderr = [x.decode(sys.stdout.encoding) | |
624 for x in (stdout, stderr)] | |
625 if p.returncode != 0: | |
626 if 'permission denied' in stderr.lower(): | |
627 raise AccessDenied(self.pid, self._name) | |
628 if 'no such process' in stderr.lower(): | |
629 raise NoSuchProcess(self.pid, self._name) | |
630 raise RuntimeError("%r command error\n%s" % (cmd, stderr)) | |
631 | |
632 lines = stdout.split('\n')[2:] | |
633 for i, line in enumerate(lines): | |
634 line = line.lstrip() | |
635 if line.startswith('sockname: AF_UNIX'): | |
636 path = line.split(' ', 2)[2] | |
637 type = lines[i - 2].strip() | |
638 if type == 'SOCK_STREAM': | |
639 type = socket.SOCK_STREAM | |
640 elif type == 'SOCK_DGRAM': | |
641 type = socket.SOCK_DGRAM | |
642 else: | |
643 type = -1 | |
644 yield (-1, socket.AF_UNIX, type, path, "", _common.CONN_NONE) | |
645 | |
646 @wrap_exceptions | |
647 def connections(self, kind='inet'): | |
648 ret = net_connections(kind, _pid=self.pid) | |
649 # The underlying C implementation retrieves all OS connections | |
650 # and filters them by PID. At this point we can't tell whether | |
651 # an empty list means there were no connections for process or | |
652 # process is no longer active so we force NSP in case the PID | |
653 # is no longer there. | |
654 if not ret: | |
655 # will raise NSP if process is gone | |
656 os.stat('%s/%s' % (self._procfs_path, self.pid)) | |
657 | |
658 # UNIX sockets | |
659 if kind in ('all', 'unix'): | |
660 ret.extend([_common.pconn(*conn) for conn in | |
661 self._get_unix_sockets(self.pid)]) | |
662 return ret | |
663 | |
664 nt_mmap_grouped = namedtuple('mmap', 'path rss anon locked') | |
665 nt_mmap_ext = namedtuple('mmap', 'addr perms path rss anon locked') | |
666 | |
667 @wrap_exceptions | |
668 def memory_maps(self): | |
669 def toaddr(start, end): | |
670 return '%s-%s' % (hex(start)[2:].strip('L'), | |
671 hex(end)[2:].strip('L')) | |
672 | |
673 procfs_path = self._procfs_path | |
674 retlist = [] | |
675 try: | |
676 rawlist = cext.proc_memory_maps(self.pid, procfs_path) | |
677 except OSError as err: | |
678 if err.errno == errno.EOVERFLOW and not IS_64_BIT: | |
679 # We may get here if we attempt to query a 64bit process | |
680 # with a 32bit python. | |
681 # Error originates from read() and also tools like "cat" | |
682 # fail in the same way (!). | |
683 # Since there simply is no way to determine CPU times we | |
684 # return 0.0 as a fallback. See: | |
685 # https://github.com/giampaolo/psutil/issues/857 | |
686 return [] | |
687 else: | |
688 raise | |
689 hit_enoent = False | |
690 for item in rawlist: | |
691 addr, addrsize, perm, name, rss, anon, locked = item | |
692 addr = toaddr(addr, addrsize) | |
693 if not name.startswith('['): | |
694 try: | |
695 name = os.readlink( | |
696 '%s/%s/path/%s' % (procfs_path, self.pid, name)) | |
697 except OSError as err: | |
698 if err.errno == errno.ENOENT: | |
699 # sometimes the link may not be resolved by | |
700 # readlink() even if it exists (ls shows it). | |
701 # If that's the case we just return the | |
702 # unresolved link path. | |
703 # This seems an incosistency with /proc similar | |
704 # to: http://goo.gl/55XgO | |
705 name = '%s/%s/path/%s' % (procfs_path, self.pid, name) | |
706 hit_enoent = True | |
707 else: | |
708 raise | |
709 retlist.append((addr, perm, name, rss, anon, locked)) | |
710 if hit_enoent: | |
711 self._assert_alive() | |
712 return retlist | |
713 | |
714 @wrap_exceptions | |
715 def num_fds(self): | |
716 return len(os.listdir("%s/%s/fd" % (self._procfs_path, self.pid))) | |
717 | |
718 @wrap_exceptions | |
719 def num_ctx_switches(self): | |
720 return _common.pctxsw( | |
721 *cext.proc_num_ctx_switches(self.pid, self._procfs_path)) | |
722 | |
723 @wrap_exceptions | |
724 def wait(self, timeout=None): | |
725 return _psposix.wait_pid(self.pid, timeout, self._name) |