a M_@ @sdZddlmZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlmZddlmZddlmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%ddlm&Z&ddlm'Z'ddlm(Z(ddlm)Z)ddl*m+Z+ddl*m,Z,ddl*m-Z-dd l*m.Z.dd!l*m/Z/dd"l*m0Z0e j1d#krddl2Z2ndZ2gd$Z3d%Z4ej56d&e7Z8e9ed'Z:e9ed(Z;e<Z=e>d)Z?e@ZAdaBe0rLd*nd+ZCe jDd,kZEd-ZFe2durpe jGZHne2Id.d/eJe jGiZKeKjHZHe2durdZLdZMd0ZNd1ZOn Gd2d3d3e2jIZPeQRePjSejTejUejVejWejXejYejZejZej[ej\ej]ej^d4 Z_ej`ejaejbejcejdejeejfejgejhejiejjd5 Zked6gd7Zled8gd9Zmed:gd;Znedeojpd?Zqed@gdAZredBdCdDserjpZtedEgdFZuedGgdHZvdIdJZwdKdLZxdMdNZyedOdPZze=dQfdRdSZ{z ezdTWn.e|y e }edUdVdWdWdWa~Yn0dZzddXlmZWn@eyvddlZejddQdYZe9edZrrdd[dZZYn0edure3d\d]eeDd^d_Zd`daZdbdcZdddeZdfdgZdhdiZdjdkZdldmZej56dnsej56dordpdqZn ej56drrdsdqZndtdqZejZGdudvdve|ZGdwdxdxZeZddzd{Zd|d}Zd~dZejZdddZdddZddZddZddZddZddZddZddZddZddZGddde<ZdS)zLinux platform implementation.)divisionN) defaultdict) namedtuple)_common)_psposix) _psutil_linux) _psutil_posix) AccessDenied)debug)decode)get_procfs_path) isfile_strict)memoize)memoize_when_activated)NIC_DUPLEX_FULL)NIC_DUPLEX_HALF)NIC_DUPLEX_UNKNOWN) NoSuchProcess) open_binary) open_text)parse_environ_block)path_exists_strict) supports_ipv6) usage_percent) ZombieProcess)b) basestring)FileNotFoundError)PermissionError)ProcessLookupError)PY3))Z PROCFS_PATHIOPRIO_CLASS_NONEIOPRIO_CLASS_RTIOPRIO_CLASS_BEIOPRIO_CLASS_IDLECONN_ESTABLISHED CONN_SYN_SENT CONN_SYN_RECVCONN_FIN_WAIT1CONN_FIN_WAIT2CONN_TIME_WAIT CONN_CLOSECONN_CLOSE_WAIT CONN_LAST_ACK CONN_LISTEN CONN_CLOSINGz/sys/class/power_supplyz/proc/%s/smapsproc_ioprio_getproc_cpu_affinity_get SC_CLK_TCKi littlei AddressFamilyAF_LINKr"c@seZdZdZdZdZdZdS) IOPriorityrrr:r"N)__name__ __module__ __qualname__r$r%r&r'r?r?5/usr/lib64/python3.9/site-packages/psutil/_pslinux.pyr;wsr;) RSDTtZXxKWIP) Z01Z02Z03Z04Z05Z06Z07Z08Z09Z0AZ0Bsvmem) total availablepercentusedfreeactiveinactivebufferscachedsharedslabsdiskio) read_count write_count read_bytes write_bytesZ read_timeZ write_timeZread_merged_countZwrite_merged_count busy_time popenfile)pathfdZpositionmodeflagspmemz"rss vms shared text lib data dirtypfullmem)usspssswap pmmap_grouped) r`rsssizergZ shared_cleanZ shared_dirtyZ private_cleanZ private_dirtyZ referencedZ anonymousrh pmmap_extz addr perms  pio)rZr[r\r]Z read_charsZ write_chars pcputimes)usersystem children_userchildren_systemiowaitcCs:t|}|dd}|dr6t|s6|dd}|S)zWrapper around os.readlink().r (deleted)N)osreadlinksplitendswithr)r`r?r?r@rys   rycCsXtjdtjdtjdi}||tjtjBtjB@}|tj@rH|ddd}|dd}|S)zZConvert file's open() flags into a readable string. Used by Process.open_files(). rwzw+arzr+)rxO_RDONLYO_WRONLYO_RDWRO_APPENDreplace)rcZ modes_maprbr?r?r@file_flags_to_modes   rcCs4|dd}d}|rd|}nd|}t|tjS)zReturn 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. /!Tz /sys/block/%sz/sys/block/%s/device)rrxaccessF_OK)nameZincluding_virtualr`r?r?r@is_storage_devices  rcCstd|$}|dd}Wdn1s60Ygd}t|}|dkrb|d|dkrt|d|d kr|d td |adS) zSet 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. %s/statrN)rpnicerqZidlertZirqZsoftirqZsteal Zguest Z guest_nice scputimes)rreadlinerzlenappendrr) procfs_pathfvaluesfieldsZvlenr?r?r@set_scputimes_ntuples 2   rTc CstzF|rt|nt|}|WdWS1s:0YWn(ttfyn|turh|YSYn0dS)zReturn file content. fallback: the value returned in case the file does not exist or cannot be read binary: whether to open the file in binary or text mode. N)rrreadstripIOErrorOSError_DEFAULT)fnamefallbackbinaryrr?r?r@cats0r/procrzuser system idle)prlimit)Z use_errnorcCsGdddtj}|}|dur8t||dt|}n6|}|d|_|d|_t||t|t|}|dkrt}t|t ||j|jfS)Nc@s eZdZdejfdejfgZdS)zprlimit..StructRlimitrlim_currlim_maxN)r<r=r>ctypesZ c_longlongZ_fields_r?r?r?r@ StructRlimitJsrrr) rZ StructurelibcrZbyrefrrZ get_errnorrxstrerror)pid resource_limitsrcurrentretnewerrnor?r?r@rIs  cCs"g|]}|dr|r|qS)ZRLIM) startswithisupper.0rHr?r?r@ brc Cs|d}||dd}z|d}|d}|d}WntyJ|YS0ztdt}Wntyt|YS0d}|@|D]*}|}|dr|t|d 7}qWd n1s0Y|t 9}||} ||} | t | d |8} | | 7} | |t |d |7} t| S) aFallback for kernels < 3.14 where /proc/meminfo does not provide "MemAvailable:" column, 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 XXX: on recent kernels this calculation differs by ~1.5% than "MemAvailable:" as it's calculated slightly differently, see: https://gitlab.com/procps-ng/procps/issues/42 https://github.com/famzah/linux-memavailable-procfs/issues/2 It is still way more realistic than doing (free + cached) though. MemFree:Cached:rs Active(file):sInactive(file): SReclaimable:z %s/zoneinfoslowrNr:g@) getKeyErrorrr rrrintrzPAGESIZEmin) memsrRrZlru_active_fileZlru_inactive_fileZslab_reclaimablerZ watermark_lowlineavailZ pagecacher?r?r@calculate_avail_vmemjs2      4rc Csg}i}tdt:}|D]$}|}t|dd||d<qWdn1sV0Y|d}|d}z |d}Wn tyd}|d Yn0z |d }Wn tyd}|d Yn0||d d7}z |d } WnDty,z |d} Wn"ty&d} |dYn0Yn0z |d} Wn"ty\d} |dYn0z |d} WnTtyz|d|d|d} Wn"tyd} |dYn0Yn0z |d} Wntyd} Yn0||||} | dkr||} z |d}Wnty0t|}Yn0|dkrJd}|d||krX|}t|||dd}|rdd |t |dkrdndf}t |t t|||| || | ||| | S)aReport virtual memory stats. This implementation matches "free" and "vmstat -s" cmdline utility values and procps-ng-3.3.12 source was used as a reference (2016-09-18): https://gitlab.com/procps-ng/procps/blob/ 24fd2605c51fccc375ab0287cec33aa767f06718/proc/sysinfo.c For reference, procps-ng-3.3.10 is the version available on Ubuntu 16.04. Note about "available" memory: up until psutil 4.3 it was calculated as "avail = (free + buffers + cached)". Now "MemAvailable:" column (kernel 3.14) from /proc/meminfo is used as it's more accurate. That matches "available" column in newer versions of "free". %s/meminforrNs MemTotal:rsBuffers:rUrrVrsShmem:s MemShared:rWsActive:rSs Inactive:s Inact_dirty:s Inact_clean:sInact_laundry:rTsSlab:s MemAvailable:rOZround_z6%s memory stats couldn't be determined and %s set to 0, ZwasZwere)rr rzrrrrrrjoinrwarningswarnRuntimeWarningrM)Zmissing_fieldsrrrrrNrRrUrVrWrSrTrXrQrrPmsgr?r?r@virtual_memorys8                   rc Csi}tdt:}|D]$}|}t|dd||d<qWdn1sR0Yz|d}|d}Wn8tyt\}}}}}}}||9}||9}Yn0||}t||dd} ztd t}WnFty} z,d t | } t | t d} } WYd} ~ nd} ~ 00|d} } |D]n}| d rXt|d dd d} n&| dr~t|d dd d} | dur,| dur,qq,d} t | t d} } Wdn1s0Yt|||| | | S)zReturn swap memory metrics.rrrrNs SwapTotal:s SwapFree:rz %s/vmstatzP'sin' and 'sout' swap memory stats couldn't be determined and were set to 0 (%s)spswpin r#spswpoutzK'sin' and 'sout' swap memory stats couldn't be determined and were set to 0)rr rzrrcextZ linux_sysinforrstrrrrrrZsswap)rrrrrNrR_Zunit_multiplierrQrPerrrZsinZsoutr?r?r@ swap_memorysF8       (rcCsrt}t|td|}|}Wdn1s<0Y|dttjd}dd|D}t|S)zReturn 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. rNrcSsg|]}t|tqSr?float CLOCK_TICKSrr?r?r@r^rzcpu_times..)r rrrrzrr_fields)rrrrr?r?r@ cpu_timesRs*rcCst}t|g}td|n}||D]L}|dr,|}|dttjd}dd|D}t|}| |q,|WdS1s0YdS)zfReturn a list of namedtuple representing the CPU times for every CPU available on the system. rscpurcSsg|]}t|tqSr?rrr?r?r@rprz!per_cpu_times..N) r rrrrrzrrrr)rcpusrrrrentryr?r?r@ per_cpu_timesbs  rc Csz tdWStyd}tdt0}|D]}|dr2|d7}q2Wdn1sb0Y|dkrtd}t dt:}|D]$}| d d}| |r|d7}qWdn1s0Y|dkrYdS|YS0dS) z0Return the number of logical CPUs in the system.SC_NPROCESSORS_ONLNr %s/cpuinfos processorrNzcpu\drrm) rxsysconf ValueErrorrr lowerrrecompilerrzmatch)numrrsearchr?r?r@cpu_count_logicalvs$  (  (rc Cs2t}d}d}t|p t|D]>}t|"}||Wdq"1sV0Yq"t|}|dkrv|Si}i}tdt~}|D]h}|}|sz|d||d<Wnt yYn0i}q| dr| d d \} } t | || <qWdn1s0Yt |}|p0dS) z2Return the number of physical cores in the system.z9/sys/devices/system/cpu/cpu[0-9]*/topology/core_cpus_listz?/sys/devices/system/cpu/cpu[0-9]*/topology/thread_siblings_listNrr cpu cores physical id)rrs :r)setglobraddrrrr rrrrzrsumr) lsZp1Zp2r`rresultmappingZ current_inforkeyvaluer?r?r@cpu_count_physicals4 2   . rcCstdt}d}d}d}|D]r}|dr@t|d}n6|dr\t|d}n|drvt|d}|dur |dur |dur qq Wdn1s0Yd}t||||S)z*Return various CPU stats as a named tuple.rNsctxtrsintrssoftirqr)rr rrrzrZ scpustats)rZ ctx_switchesZ interruptsZsoft_interruptsrZsyscallsr?r?r@ cpu_statss&   $rz'/sys/devices/system/cpu/cpufreq/policy0z$/sys/devices/system/cpu/cpu0/cpufreqcCsdd}g}ttD]}||}|s(qtjj}t||ddd}|durlt||ddd}|durltdt|d}tt||d d}tt||d d}|t |||q|S) zReturn frequency metrics for all CPUs. Contrarily to other OSes, Linux updates these values in real-time. cSs.d|d|fD]}tj|r|SqdS)Nz(/sys/devices/system/cpu/cpufreq/policy%sz%/sys/devices/system/cpu/cpu%s/cpufreq)rxr`exists)rpr?r?r@get_paths  zcpu_freq..get_pathZscaling_cur_freqNrZcpuinfo_cur_freqz!can't find current frequency fileiZscaling_max_freqZscaling_min_freq) rangerrxr`rrNotImplementedErrorrrrscpufreq)rrnr`ZpjoinZcurrZmax_Zmin_r?r?r@cpu_freqs& rz /proc/cpuinfoc Csvg}tdtP}|D]:}|dr|dd\}}|tt|ddqWdn1sh0Y|S)z}Alternate implementation using /proc/cpuinfo. min and max frequencies are not available and are set to None. rscpu mhz:rrN) rr rrrzrrrr)rrrrrr?r?r@rs8cCsgS)zGDummy implementation when none of the above files are present. r?r?r?r?r@rsc@s eZdZdS)_Ipv6UnsupportedErrorN)r<r=r>r?r?r?r@rsrc@sZeZdZdZddZddZddZedd Zedd d Z edd dZ dddZ d S) ConnectionsawA 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 c Csdtjtjf}dtjtjf}dtjtjf}dtjtjf}dtjdf}|||||f||f|f|f||f|f|f|f||||f||f||fd |_d|_dS)Ntcptcp6udpudp6unix) allrtcp4rrudp4rrinetZinet4Zinet6)socketAF_INET SOCK_STREAMAF_INET6Z SOCK_DGRAMZAF_UNIXtmap _procfs_path)selfrrrrrr?r?r@__init__ s$    zConnections.__init__c Cstt}td|j|fD]}ztd|j||f}WnVttfyRYqYqty}z&|j t j krxWYd}~qWYd}~qd}~00| dr|dddd}|| |t |fq|S)N%s/%s/fd %s/%s/fd/%szsocket:[rr6)rlistrxlistdirrryrr rrEINVALrrr)rrinodesrainoderr?r?r@get_proc_inodes7s   zConnections.get_proc_inodesc CsFi}tD]6}z|||Wq tttfy>Yq Yq 0q |SN)pidsupdaterrr r)rrrr?r?r@get_all_inodesMs  zConnections.get_all_inodesc Cs|d\}}t|d}|s dStr.|d}|tjkrntrZt|t |ddd}qt|t |}n~t |}zRtrttj t j dgt d|R}n$ttj t j dgt d|R}Wn tytstnYn0t||S) aAccept 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 :r?asciiNr6z>4Iz<4I)rzrr!encoder r  LITTLE_ENDIANZ inet_ntopbase64Z b16decoder structpackunpackrrrraddr)r&familyZipportr?r?r@decode_address]s4     zConnections.decode_addressNc csR|drtj|sdSt|td}|t|dD]\}}z(|dd\ }} } } }}}}}} Wn$t yt d|||fYn0| |vr|| d\} }nd\} }|dur|| krq.z %s/net/%s)r5)r rrr rrrrr r r r:r?rZpconnZsconnrr)rkindrrrZ proto_namer'r4r`rrar7r8r9Z bound_pidZconnr?r?r@retrieves<   zConnections.retrieve)N)N)N) r<r=r>__doc__rrr staticmethodr)r:r?rBr?r?r?r@rs  2 ' %rrcCs t|S)z$Return system-wide open connections.) _connectionsrB)rAr?r?r@net_connectionssrFcCstdt}|}Wdn1s,0Yi}|ddD]x}|d}|d|}||dd}tt|\}}} } } } } }}}}}}}}}||||| || |f||<qF|S)zsReturn network I/O statistics for every network interface installed on the system as a dict of raw tuples. z %s/net/devNr:rr)rr readlinesrfindrrzmapr)rlinesretdictrcolonrrZ bytes_recvZ packets_recvZerrinZdropinZfifoinZframeinZ compressedinZ multicastinZ bytes_sentZ packets_sentZerroutZdropoutZfifooutZ collisionsoutZ carrieroutZ compressedoutr?r?r@net_io_counterss8&  rMc Cstjttjttjti}t}i}|D]v}z&t |}t |}t |\}}Wn2t y}z|jtjkrpWYd}~q(d}~00t|||||||<q(|S)z)Get NIC stats (isup, duplex, speed, mtu).N)rZ DUPLEX_FULLrZ DUPLEX_HALFrZDUPLEX_UNKNOWNrrMkeys cext_posixZ net_if_mtuZnet_if_is_runningZnet_if_duplex_speedrrZENODEVrZ snicstats) Z duplex_mapnamesrrZmtuZisupZduplexZspeedrr?r?r@ net_if_stats+s     rQFc Csdd}dd}tjdtr*|}n"tjdr>|}ntdti}|D]T}|\ }}}} } } } } }}|s~t|s~qT| t9} | t9} ||| | | | | ||f ||<qT|S)zcReturn disk I/O statistics for every disk installed on the system as a dict of raw tuples. c ssDtdt}|}Wdn1s,0Y|D]}|}t|}|dkr|d}t|d}tt|dd\ }}} } } } } }}}n|dks|dkr|d}tt|dd\ }}}} } } } } }}}nN|dkr|d}tt|dd\}}} } d } } }} }n td |||| || | | || |f Vq:dS) N %s/diskstatsr"r:r#r;rz!not sure how to interpret line %r)rr rGrzrrrIr)rrJrrZflenrreads reads_mergedrbytesrtimewrites writes_mergedwbyteswtimerr^r?r?r@ read_procfsLs4&       z%disk_io_counters..read_procfsc sstdD]}ttjd|D]\}}}d|vr6q"ttj|d }|}Wdn1sn0Ytj |}t t |dd\ }}} } } } } }}}||| | | | ||| |f Vq"q dS)N /sys/blockstatr) rxrwalkr`rrrrrzbasenamerIr)blockrootrfilesrrrrVrWrXrYrZr[r\r]r^r?r?r@ read_sysfsws.  z$disk_io_counters..read_sysfsrRr_zC%s/diskstats nor /sys/block filesystem are available on this system)rxr`rr rrDISK_SECTOR_SIZE)Zperdiskr^rfgenrKrrrVrZrXr\rYr]rWr[r^r?r?r@disk_io_countersHs0+     ric Cs&t}t}td|\}|D]F}|}|dsD||q|dd}|dkr|dqWdn1sz0Y|dkrtj drtj d}ntj d |}g}t |}|D]X} | \} } }} | d krd } |s| d ks||vrqd} }t | | || | |}||q|S) z8Return mounted disk partitions as a list of namedtuples.z%s/filesystemsZnodev rZzfsNrz /etc/mtabz%s/self/mountsZnoner<)rr rrrrrzrxr`isfilerealpathrdisk_partitionsrZ sdiskpartr)rZfstypesrrrZfstypeZ mounts_pathretlistZ partitions partitionZdeviceZ mountpointZoptsZmaxfileZmaxpathntupler?r?r@rms8 *    rmc Csdtt}td}|tdttdd|D}td}td}|D]"}| d|}||vrR| |qR|D]}z>|d}t t |d }t jt j|d }t |d d } WntttfyYqzYn0t |d dd} t |ddd} t |ddd d} | durBzt | d } Wnty@d} Yn0| durvzt | d } Wntytd} Yn0||  | || | fqz|s\td}tt|}|D]}z.z5/sys/devices/platform/coretemp.*/hwmon/hwmon*/temp*_*z'/sys/devices/platform/coretemp.*/hwmon/z/sys/class/hwmon/_inputg@@rFrZ_maxNrZ_crit_labelr<rrz /sys/class/thermal/thermal_zone*Ztemptypezignoring %r for file %rz /trip_point*cSs,g|]$}dtj|dddqS)rrr")rrxr`rbrz)rrr?r?r@r%sZ_typecriticalZ_temphigh) collectionsrrrextendsortedrrrsubrrrrxr`rdirnamerrrr dict)r basenamesZ basenames2replrZaltnamebaser`r unit_nameryrxlabelrZ trip_pathsZ trip_pointsZ trip_pointZ trip_typer?r?r@sensors_temperaturess              $     rc Cstt}td}|s"td}ttdd|D}|D]}ztt|d}WnDtt fy}z(t d|t WYd}~q.rsz ignoring %rNrFrtrur<rv)rzrrrr|rrrrrrrrrxr`rr~rrZsfanr)rrrrrrrr?r?r@ sensors_fansCs"   "rc stfdd}ddttD}|s.dStjtt|d}||d|d}||d |d }||d |d }||d }|dur|durzd||}Wqtyd}Yq0n tt |ddd}|dkrdSd}|tjtdtjtd} | dur| dk}n4t |dddd } | dkr.multi_catcSs&g|]}|dsd|vr|qS)ZBATZbattery)rrrr?r?r@rvs z#sensors_battery..Nrz /energy_nowz /charge_nowz /power_nowz /current_nowz /energy_fullz /charge_fullz/time_to_empty_nowgY@rz /capacityr6rz AC0/onlinez AC/onlinerz/statusr<FrvZ discharging)ZchargingZfullTi<)objectrxrPOWER_SUPPLY_PATHr`rr|ZeroDivisionErrorrrrrZPOWER_TIME_UNLIMITEDZPOWER_TIME_UNKNOWNZsbattery) rZbatsrdZ energy_nowZ power_nowZ energy_fullZ time_to_emptyrPZ power_pluggedZonliner9Zsecsleftr?rr@sensors_batterycsh             rc Cs\g}t}|D]F}|\}}}}}}|s*q|dvr6d}t||pBd|||} || q|S)z:Return currently connected users as a list of namedtuples.)z:0.0z:0Z localhostN)rusersrZsuserr) rnZrawlistitemrpZttyhostnameZtstampZ user_processrntr?r?r@rs rcCsdt}t|^}|D]<}|drt|d}|a|WdSqtd|Wdn1sv0YdS)zAReturn the system boot time expressed in seconds since the epoch.rsbtimerNzline 'btime' not found in %s)r rrrrrz BOOT_TIMEr0)r`rrrr?r?r@ boot_times   rcCsddtttDS)z7Returns a list of PIDs currently running on the system.cSsg|]}|rt|qSr?)rrrr?r?r@rrzpids..)rxrrr r?r?r?r@rsrc Cst|sdSzdt|f}t|\}|D]:}|dr,t|d}||kWdWSq,td|Wdn1s0YWn ttfy|t vYS0dS)zcCheck for the existence of a unix PID. Linux TIDs are not supported (always return False). F %s/%s/statussTgid:rNz'Tgid' line not found in %s) r pid_existsr rrrrzrEnvironmentErrorr)rr`rrZtgidr?r?r@rs    .rc Csi}t}tD]}z.wrapper) functoolswraps)rrr?rr@wrap_exceptions!s rc@sneZdZdZgdZddZddZeeddZ eed d Z eed d Z d dZ ddZ eddZddZeddZeddZeddZejdereddZeddZed d!Zed\d#d$Zed%d&Zed'd(Zer(eed)ed*ed+fd,d-Z neZ er>ed.d/Z!ed0d1Z"eed2fd3d4Z#eed5fd6d7Z$ed8d9Z%ed:d;Z&edd?Z)ed@fdAdBZ*edCdDZ+e,redEdFZ-edGdHZ.e/d"ured]dIdJZ0edKdLZ1edMdNZ2ed^dPdQZ3edRdSZ4edTdUZ5eedVfdWdXZ6eedYfdZd[Z7d"S)_ProcesszLinux process implementation.)rr_ppidr_cachecCs||_d|_d|_t|_dSr)rrrr r)rrr?r?r@r;szProcess.__init__cCstd|j|jfdS)z+Raise NSP if the process disappeared on us.rN)rxr`rrrr?r?r@ _assert_aliveAszProcess._assert_alivecCstd|j|jf}|}Wdn1s20Y|d}||dd|}||dd}i}||d<|d|d <|d|d <|d |d <|d |d<|d|d<|d|d<|d|d<|d|d<|d|d<|d|d<|S)aZParse /proc/{pid}/stat file and return a dict with various process info. Using "man proc" as a reference: where "man proc" refers to position N always substract 3 (e.g ppid position 4 in 'man proc' == position 1 in here). The return value is cached in case oneshot() ctx manager is in use. rNr(rr:rrr9rr#ttynr utime stime children_utimerTchildren_stime create_time$cpu_num' blkio_ticks)rrrrrHfindrz)rrrrrrrr?r?r@_parse_stat_fileGs$ &           zProcess._parse_stat_filecCs@td|j|jf}|WdS1s20YdS)zRead /proc/{pid}/stat file and return its content. The return value is cached in case oneshot() ctx manager is in use. rN)rrrrrrr?r?r@_read_status_filejszProcess._read_status_filecCsHtd|j|jftd}|WdS1s:0YdS)Nz %s/%s/smapsr+)rrrr.rrrr?r?r@_read_smaps_filets zProcess._read_smaps_filecCs(|j||j||j|dSr)rZcache_activaterrrr?r?r@ oneshot_enter{s  zProcess.oneshot_entercCs(|j||j||j|dSr)rZcache_deactivaterrrr?r?r@ oneshot_exits  zProcess.oneshot_exitcCs|d}trt|}|S)Nr)rr!r )rrr?r?r@rs z Process.namec Csztd|j|jfWSttfyvtjd|j|jfrFYdSt|js`t |j|j nt |j|j |j Yn t yt|j|j Yn0dS)Nz %s/%s/exerr<)ryrrrr rxr`lexistsrrrrrrr rr?r?r@exes  z Process.execCstd|j|jf}|}Wdn1s20Y|sDgS|drRdnd}||rl|dd}||}|dkrt|dkrd|vr|d}|S)Nz %s/%s/cmdlinerurmr6r)rrrrr{rzr)rrrsepcmdliner?r?r@rs&    zProcess.cmdlinecCsDtd|j|jf}|}Wdn1s20Yt|S)Nz %s/%s/environ)rrrrr)rrrr?r?r@environs&zProcess.environcCs<t|d}t}z ||WSty6YdS0dS)Nr)rrrZget_terminal_mapr)rZtty_nrr r?r?r@terminals   zProcess.terminalz /proc/%s/ioc Csd|j|jf}i}t|\}|D]F}|}|r"z|d\}}WntyZYq"Yq"0t|||<q"Wdn1s~0Y|std|z,t|d|d|d|d|d|d WSt y}z"td |d ||fWYd}~n d}~00dS) Nz%s/%s/ios: z%s file was emptyssyscrssyscws read_bytess write_bytessrcharswcharz1%r field was not found in %s; found fields are %rr) rrrrrzrrr0rnr)rrrrrrrrr?r?r@ io_counterss4   ,  zProcess.io_counterscCsh|}t|dt}t|dt}t|dt}t|dt}t|dt}t|||||S)Nrrrrr)rrrro)rrrrrrrtr?r?r@rszProcess.cpu_timescCst|dS)zWhat CPU the process is on.rrrrr?r?r@rszProcess.cpu_numNcCst|j||jSr)rZwait_pidrr)rtimeoutr?r?r@waitsz Process.waitcCs&t|d}tpt}|t|S)Nr)rrrrr)rctimeZbtr?r?r@rs zProcess.create_timec Csttd|j|jf<}dd|ddD\}}}}}}}Wdn1sV0Yt|||||||S)Nz %s/%s/statmcSsg|]}t|tqSr?)rrrr?r?r@rrz'Process.memory_info..r;)rrrrrzrd) rrZvmsrjrWtextlibrZdirtyr?r?r@ memory_infos .zProcess.memory_infos\nPrivate.*:\s+(\d+)s\nPss\:\s+(\d+)s\nSwap\:\s+(\d+)c Csj|}|}ttt||d}ttt||d}ttt||d}t||||fS)Nr)rrrrIrfindallre) rZ _private_reZ_pss_reZ_swap_reZ basic_memZ smaps_datarfrgrhr?r?r@memory_full_infos  zProcess.memory_full_infocCsRdd}|}|sgS|d}g}|d}|g}|||D] \}}|dd}z|\} } } } } }Wn(ty|dg\} } } } } }Yn0|sd}n2trt|}|}|d rt|s|dd }| t| t| || d d| d d| d d| dd| dd| dd| dd| dd| dd| ddf q@|S)aPReturn process's mapped memory regions as a list of named tuples. Fields are explained in 'man proc'; here is an updated (Apr 2012) version: http://goo.gl/fmebo /proc/{PID}/smaps does not exist on kernels < 2.6.14 or if CONFIG_MMU kernel configuration option is not enabled. c ssi}|D]}|dd}|dds@||fV||qzt|dd||d<Wqty|ddr~Yqn td|Yq0q||fVdS)NrrrrsVmFlags:z#don't know how to interpret line %r)rzr{poprrrr)rJ current_blockrrrr?r?r@ get_blocksEs   z'Process.memory_maps..get_blocks rNrr<z[anon]rvrwsRss:sSize:sPss:s Shared_Clean:s Shared_Dirty:sPrivate_Clean:sPrivate_Dirty:s Referenced:s Anonymous:sSwap:) rrzrrr!r rr{rrr)rrrrJrZ first_linerheaderZhfieldsr&Zpermsoffsetdevrr`r?r?r@ memory_maps<sL                  zProcess.memory_mapsc Cs^ztd|j|jfWSttfyXt|jsBt|j|jnt|j|j|j Yn0dS)Nz %s/%s/cwd) ryrrrr rrrrrrr?r?r@cwds  z Process.cwdsctxt_switches:\t(\d+)cCsL|}||}|s,td|j|jfntt|dt|dSdS)Nz'voluntary_ctxt_switches' and 'nonvoluntary_ctxt_switches'lines were not found in %s/%s/status; the kernel is probably older than 2.6.23rr)rrrrrrZpctxswr)rZ _ctxsw_rerZctxswr?r?r@num_ctx_switchess zProcess.num_ctx_switchessThreads:\t(\d+)cCs|}t||dSNr)rrr)rZ_num_threads_rerr?r?r@ num_threadsszProcess.num_threadsc Cstd|j|jf}|g}d}|D]}d|j|j|f}z8t|}|}Wdn1sl0YWntyd}Yq*Yn0|| ddd}| d}t |dt } t |d t } t t|| | } || q*|r||S) Nz %s/%s/taskFz%s/%s/task/%s/statTrr:rrr)rxrrrsortrrrrrrzrrrZpthreadrrr) rZ thread_idsrn hit_enoentZ thread_idrrstrrrrpr?r?r@threadss.  .    zProcess.threadscCs t|jSr)rO getpriorityrrr?r?r@nice_getszProcess.nice_getcCst|j|Sr)rO setpriorityr)rrr?r?r@nice_setszProcess.nice_setcCs t|jSr)rr4rrr?r?r@cpu_affinity_getszProcess.cpu_affinity_getsCpus_allowed_list:\t(\d+)-(\d+)cCsV|}||}|r@ttt|ddt|dddSttttSdS)Nrr)rrrrrrr)r_rerrr?r?r@_get_eligible_cpuss  *zProcess._get_eligible_cpusc Cszt|j|Wnttfy}zxt|ts<|jtjkr|}t t t t }|D]4}||vrvtd||f||vrZtd||fqZWYd}~n d}~00dS)Nz(invalid CPU number %r; choose between %sz0CPU number %r is not eligible; choose between %s) rZproc_cpu_affinity_setrrr isinstancerrrtuplerrr)rrrZ eligible_cpusZall_cpusZcpur?r?r@cpu_affinity_sets(zProcess.cpu_affinity_setcCs,t|j\}}tdur t|}t||Sr)rr3renumr;rZpionicerZioclassrr?r?r@ ionice_getszProcess.ionice_getcCsP|dur d}|r(|ttfvr(td||dks8|dkr@tdt|j||S)Nrz%r ioclass accepts no valuer;zvalue not in 0-7 range)r'r$rrZproc_ioprio_setrrr?r?r@ ionice_sets zProcess.ionice_setc Cs|jdkrtdzD|dur*t|j|WSt|dkrFtdt|t|j||WnPty}z8|jtjkrt|jrt |j|j |j nWYd}~n d}~00dS)Nrz)can't use prlimit() against PID 0 processr:z4second argument must be a (soft, hard) tuple, got %s) rrrrr@rrZENOSYSrrrr)rrrrr?r?r@rlimits   zProcess.rlimitcCs$|d}tr|}t|dS)Nr9?)rr!r PROC_STATUSESr)rZletterr?r?r@r9s zProcess.statusc Csvg}td|j|jf}d}|D]>}d|j|j|f}z t|}WnZttfydd}Yq"Yq"ty}z&|jtj krWYd}~q"WYd}~q"d}~00| dr"t |r"d|j|j|f}zXt |:}t |d} t |dd} Wdn1s0YWnty6d}Yq"0t| } t|t |t | | | } || q"|rr||S) NrFrTrz%s/%s/fdinfo/%srr)rxrrrryrr rrrrrrrrrzrr_rr) rrnrerrar3r`rrposrcrbrpr?r?r@ open_files&s@      :  zProcess.open_filesrcCst||j}||Sr)rErBrr)rrArr?r?r@ connectionsRszProcess.connectionscCsttd|j|jfS)Nr)rrxrrrrr?r?r@num_fdsXszProcess.num_fdscCst|dS)Nrrrr?r?r@r\sz Process.ppidsUid:\t(\d+)\t(\d+)\t(\d+)cCs6|}||d\}}}tt|t|t|Sr)rrrZpuidsr)rZ_uids_rerreal effectivesavedr?r?r@uids`sz Process.uidssGid:\t(\d+)\t(\d+)\t(\d+)cCs6|}||d\}}}tt|t|t|Sr)rrrZpgidsr)rZ_gids_rerrrrr?r?r@gidsfsz Process.gids)N)N)r)8r<r=r>rC __slots__rrrrrrrrrrrrrrrxr`rgetpidrrrrrr HAS_SMAPSrrrrrrrrrrHAS_CPU_AFFINITYrrrHAS_PROC_IO_PRIORITYrrrrr9rrrrrrr?r?r?r@r6s !             C             +   r)N)r)F)F)rCZ __future__rr"rzrrrrxrr r#sys tracebackrrrr<rrrrr rOr r r r rrrrrrrrrrrrrrZ_compatrrrrr r! version_inforZ__extra__all__rr`rrrhasattrrrrrrrZ getpagesizerrr. byteorderr!rgZ AF_PACKETr9IntEnumrr8r$r%r&r'r;globalsr __members__ZSTATUS_RUNNINGZSTATUS_SLEEPINGZSTATUS_DISK_SLEEPZSTATUS_STOPPEDZSTATUS_TRACING_STOPZ STATUS_ZOMBIEZ STATUS_DEADZSTATUS_WAKE_KILLZ STATUS_WAKINGZ STATUS_IDLEZ STATUS_PARKEDrr(r)r*r+r,r-r.r/r0r1r2r1rMrYr_rdrrerirrlrnroryrrrr Exception print_excrrresource ImportErrorrZCDLLrr{dirrrrrrrrrrZ net_if_addrsrrrErFrMrQ disk_usagerirmrrrrrrrrrrr?r?r?r@sb                                                 4z:*    k % _ +q ^