3 JZb$@sdZddlmZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlmZddlmZddlmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddl$m%Z%ddl$m&Z&ddl$m'Z'ddl$m(Z(ddl)m*Z*ddl)m+Z+ddl)m,Z,e j-dkrddl.Z.ndZ.d d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/gZ/d0Z0ej1j2d1ej3Z4e5ed2Z6e7Z8e6r2x(e9eD]Z:e:j;d3re/jej=d5Z?da@e(rTdnd6ZAe jBd7kZCd8ZDe.dkrxe jEZFne.jGd9d:eHe jEiZIeIjFZFe.dkrdZJdZKd;ZLdZMn Gd Z[ej\ej]ej^ej_ej`ejaejbejcejdejeejfd? Zged@dAdBdCdDdEdFdGdHdIdJg ZhedKdLdMdNdOdPdQdRdSdTg ZiedUdVdWdXdYdZgZjed[d\Zked]ekjldZmedadVdbdcd_dddedfdgdhdid`g ZnedjdkdljoenjlZpedmdLdMdNdOdndogZqdpdqZrdrdsZse(rdtduZtndvduZtdwdxZudydzZvd{d|Zwd}d~ZxeddZye8dfddZzy eydWn0e{k re j|eddddda}YnXddZ~ddZddZddZddZddZddZddZej1j2dsej1j2drddZejZGddde{ZGdddZeZdddZddZddZejZddZdddZddZddZddZddZddZddZddZddZddZGddde7ZdS)zLinux platform implementation.)divisionN) defaultdict) namedtuple)_common)_psposix) _psutil_linux) _psutil_posix)ENCODING) ENCODING_ERRS) isfile_strict)memoize)memoize_when_activated)NIC_DUPLEX_FULL)NIC_DUPLEX_HALF)NIC_DUPLEX_UNKNOWN)parse_environ_block)path_exists_strict) supports_ipv6) usage_percent)b) basestring)long)PY3) AccessDenied) NoSuchProcess) ZombieProcess 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/smaps linux_prlimitZRLIM SC_CLK_TCK SC_PAGE_SIZEi littlei AddressFamilyAF_LINKc@seZdZdZdZdZdZdS) IOPriorityrrr5rN)__name__ __module__ __qualname__r r!r"r#r:r: /usr/lib64/python3.6/_pslinux.pyr6jsr6) RSDTtZXxKW) Z01Z02Z03Z04Z05Z06Z07Z08Z09Z0AZ0Bsvmemtotal availablepercentusedfreeactiveinactivebufferscachedsharedsdiskioZ read_countZ write_countZ read_bytesZ write_bytesZ read_timeZ write_timeZread_merged_countZwrite_merged_count busy_time popenfilepathfdZpositionmodeflagspmemz"rss vms shared text lib data dirtypfullmemusspssswap pmmap_groupedrsssizeZ shared_cleanZ shared_dirtyZ private_cleanZ private_dirtyZ referencedZ anonymous pmmap_extz addr perms  pioZ read_charsZ write_charscKst|df|S)Nrb)open)fnamekwargsr:r:r; open_binarysrgcKs*tr|jdt|jdtt|df|S)zOn Python 3 opens a file in text mode by using fs encoding and a proper en/decoding errors handler. On Python 2 this is just an alias for open(name, 'rt'). encodingerrorsrt)r setdefaultr r rd)rerfr:r:r; open_texts  rlcCs|jttdS)N)rhri)decoder r )sr:r:r;rmsrmcCs|S)Nr:)rnr:r:r;rmscCs tjdjS)z+Return updated psutil.PROCFS_PATH constant.Zpsutil)sysmodulesrr:r:r:r;get_procfs_pathsrqcCsNt|tst|tj|}|jdd}|jdrJt| rJ|dd}|S)zWrapper around os.readlink().rz (deleted)N i) isinstancerAssertionErrorosreadlinksplitendswithr)rTr:r:r;rws   rwcCsXtjdtjdtjdi}||tjtjBtjB@}|tj@rH|jddd}|jdd}|S)zZConvert file's open() flags into a readable string. Used by Process.open_files(). rwzw+arzr+)rvO_RDONLYO_WRONLYO_RDWRO_APPENDreplace)rWZ modes_maprVr:r:r;file_flags_to_modes   rcCsDy&td|d}t|jSQRXWnttfk r>tSXdS)zKReturn the sector size of a partition. Used by disk_io_counters(). z"/sys/block/%s/queue/hw_sector_sizerjN)rdintreadIOError ValueErrorSECTOR_SIZE_FALLBACK) partitionfr:r:r;get_sector_sizes rcCstd|}|jjdd}WdQRXdddddd d g}t|}|d krX|jd |d krj|jd|dkr||jdtd|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. z%s/statrNusernicesystemZidleZiowaitZirqZsoftirqZsteal ZguestrsZ guest_nice scputimes)rgreadlinerxlenappendrr) procfs_pathrvaluesfieldsZvlenr:r:r;set_scputimes_ntuples    rTcCsTy,|rt|nt|}|jjSQRXWn"tk rN|tk rH|SYnXdS)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)rgrlrstripr_DEFAULT)refallbackbinaryrr:r:r;cat srz/procrzuser system idlegc Cs|d}||jdd}y|d}|d}|d}Wntk rH|SXytdt}Wntk rp|SXd}|:x2|D]*}|j}|jdr|t|jd 7}qWWd QRX|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. sMemFree:sCached:rs Active(file):sInactive(file):s SReclaimable:z %s/zoneinfoslowrNr5g@) getKeyErrorrgrqrr startswithrrxPAGESIZEmin) memsrKrZlru_active_fileZlru_inactive_fileZslab_reclaimablerZ watermark_lowlineavailZ pagecacher:r:r;calculate_avail_vmem=s4   "rcNCsg}i}tdt4}x,|D]$}|j}t|dd||d<qWWdQRX|d}|d}y |d}Wn"tk rd}|jd YnXy |d }Wn"tk rd}|jd YnX||jd d7}y |d } WnHtk r$y |d} Wn$tk rd} |jdYnXYnXy |d} Wn$tk rVd} |jdYnXy |d} WnXtk ry|d|d|d} Wn$tk rd} |jdYnXYnX||||} | dkr||} y |d} Wntk r t|} YnX| dkr$d} |jd| |kr2|} t|| |dd}|rzddj |t |dkrfdndf}t j |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". z %s/meminforirNs MemTotal:sMemFree:sBuffers:rNsCached:rOs SReclaimable:sShmem:s MemShared:rPsActive:rLs Inactive:s Inact_dirty:s Inact_clean:sInact_laundry:rMs MemAvailable:rH)_roundz6%s memory stats couldn't be determined and %s set to 0z, ZwasZwere)rgrqrxrrrrrrjoinrwarningswarnRuntimeWarningrF)Zmissing_fieldsrrrrrGrKrNrOrPrLrMrJrrImsgr:r:r;virtual_memoryrsz &              rc%Csi}tdt4}x,|D]$}|j}t|dd||d<qWWdQRXy|d}|d}Wn:tk rtj\}}}}}}}||9}||9}YnX||}t||dd} ytd t}WnDtk r} z&d t | } t j | t d} } WYdd} ~ XnX|d} } x|D]j}|j d rJt|jd dd d} n&|j drpt|jd dd d} | dk r| dk rPqWd} t j | t d} } WdQRXtj|||| | | S)zReturn swap memory metrics.z %s/meminforirNs SwapTotal:s SwapFree:)rz %s/vmstatzP'sin' and 'sout' swap memory stats couldn't be determined and were set to 0 (%s)spswpin rspswpoutzK'sin' and 'sout' swap memory stats couldn't be determined and were set to 0)rgrqrxrrcextZ linux_sysinforrstrrrrrrZsswap)rrrrrGrK_Zunit_multiplierrJrIerrrZsinZsoutr:r:r; swap_memorysD &       rc Cs^t}t|td|}|jj}WdQRX|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. z%s/statNrcSsg|]}t|tqSr:)float CLOCK_TICKS).0rCr:r:r; -szcpu_times..)rqrrgrrxrr_fields)rrrrr:r:r; cpu_times!src Cst}t|g}td|d}|jxT|D]L}|jdr.|j}|dttjd}dd|D}t|}|j |q.W|SQRXdS)zfReturn a list of namedtuple representing the CPU times for every CPU available on the system. z%s/statscpurcSsg|]}t|tqSr:)rr)rrCr:r:r;r?sz!per_cpu_times..N) rqrrgrrrxrrrr)rcpusrrrrentryr:r:r; per_cpu_times1s  rcCsy tjdStk rd}tdt*}x"|D]}|jjdr4|d7}q4WWdQRX|dkrtjd}t dt4}x,|D]$}|j d d}|j |r|d7}qWWdQRX|dkrdS|SXdS) z0Return the number of logical CPUs in the system.SC_NPROCESSORS_ONLNrz %s/cpuinfos processorrNzcpu\dz%s/statra) rvsysconfrrgrqlowerrrecompilerlrxmatch)Znumrrsearchr:r:r;cpu_count_logicalEs$     rc Csi}i}tdtz}xr|D]j}|jj}|sXd|krRd|krR|d||d<i}q|jdsl|jdr|jdd\}}t|||<qWWdQRXt|jpdS)z2Return the number of physical cores in the system.z %s/cpuinfos physical ids cpu coress :rN) rgrqrrrrxrsumr)mappingZ current_inforrkeyvaluer:r:r;cpu_count_physicalbs    rc Cstdt}d}d}d}xx|D]p}|jdrBt|jd}n6|jdr^t|jd}n|jdrxt|jd}|dk r"|dk r"|dk r"Pq"WWdQRXd}tj||||S)z*Return various CPU stats as a named tuple.z%s/statNsctxtrsintrssoftirqr)rgrqrrrxrZ scpustats)rZ ctx_switchesZ interruptsZsoft_interruptsrZsyscallsr:r:r; cpu_stats{s"    rz/sys/devices/system/cpu/cpufreqz$/sys/devices/system/cpu/cpu0/cpufreqcCsg}tjd}|r$|jdddntjd}|jdddtjj}x|D]}t||ddd }|dkrt||d dd }|dkrtd t|d }tt||d d }tt||dd }|jt j |||qLW|S)zReturn frequency metrics for all CPUs. Contrarily to other OSes, Linux updates these values in real-time. z'/sys/devices/system/cpu/cpufreq/policy*cSsttjj|ddS)N)rrvrTbasename)rCr:r:r;szcpu_freq..)rz)/sys/devices/system/cpu/cpu[0-9]*/cpufreqcSsttjd|jdS)Nz[0-9]+r)rrrgroup)rCr:r:r;rsZscaling_cur_freqN)rZcpuinfo_cur_freqz!can't find current frequency fileiZscaling_max_freqZscaling_min_freq) globsortrvrTrrNotImplementedErrorrrrZscpufreq)retlsZpjoinrTZcurrZmax_Zmin_r:r:r;cpu_freqs&    rc@s eZdZdS)_Ipv6UnsupportedErrorN)r7r8r9r: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__cCstt}xtjd|j|fD]}ytd|j||f}WnJtk r}z.|jtjtj fkrbwn|jtj krrwnWYdd}~XqX|j dr|dddd}||j |t |fqW|S)Nz%s/%s/fdz %s/%s/fd/%szsocket:[rr)rlistrvlistdirrrwOSErrorerrnoENOENTESRCHEINVALrrr)rpidinodesrUinoderr:r:r;get_proc_inodess  zConnections.get_proc_inodescCsli}xbtD]X}y|j|j|Wq tk rb}z"|jtjtjtjtjfkrRWYdd}~Xq Xq W|S)N) pidsupdaterrrrrEPERMEACCES)rrrrr:r:r;get_all_inodess zConnections.get_all_inodesc Cs|jd\}}t|d}|s fStr.|jd}|tjkrntrZtj|tj |ddd}qtj|tj |}nxtj |}yJtrtjtj t j d t j d|}n tjtj t j d t j d|}Wn"tk rtstnYnXtj||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 :asciiNr>4I<4Ir)r)r)rxrrencoderr LITTLE_ENDIANZ inet_ntopbase64Z b16decoderstructpackunpackrrrraddr)rfamilyZipZportr:r:r;decode_address s0    zConnections.decode_addressNccsF|jdrtjj| rdSt|td}|jxt|dD]\}}y(|jdd\ }} } } }}}}}} Wn&t k rt d|||fYnX| |kr|| d\} }nd \} }|dk r|| krqBqB|t j krt | } ntj} ytj| |} tj| |} Wntk rwBYnX|||| | | | fVqBWWdQRXdS) z.Parse /proc/net/tcp* and /proc/net/udp* files.6N) bufferingrrsz,error while parsing %s; malformed line %s %rrr)Nr)ryrvrTexistsrlBIGFILE_BUFFERINGr enumeraterxr RuntimeErrorrr TCP_STATUSESr CONN_NONErrr)filertype_r filter_pidrlinenorrladdrraddrstatusrrrUr:r:r; process_inetDs2(   zConnections.process_inetccst|td}|jx|D]}|j}y|dd\}}}}}}} Wn.tk rtd|kr`wtd||fYnX| |kr|| } nd g} xd| D]\\} } |dk r|| krqqt|dkr|d } nd } t|}d }tj }| ||| ||| fVqWqWWdQRXdS) zParse /proc/net/unix files.)rrraz)error while parsing %s; malformed line %rNrrr)Nrr) rlr rrxrr rrrr )rrrrrrtokensrrrZpairsrrUrTrrr:r:r; process_unixls2    zConnections.process_unixc Cs"||jkr,td|djdd|jDft|_|dk rP|j|}|sXgSn|j}t}x|j|D]\}}}|tj tj fkr|j d|j|f||||d}n|j d|j|f|||d}xT|D]L\} }}} } } } |rt j| ||| | | }nt j| ||| | | | }|j|qWqjWt|S)Nz+invalid %r kind argument; choose between %sz, cSsg|] }t|qSr:)repr)rrCr:r:r;rsz(Connections.retrieve..z %s/net/%s)r)rrrrqrrrsetrrrrrrZpconnZsconnaddr)rkindrrrrrrrrUrrrZ bound_pidZconnr:r:r;retrieves4     zConnections.retrieve)N)N)N) r7r8r9__doc__rrr staticmethodrrrrr:r:r:r;rs  7 ' %rrcCs tj|S)z$Return system-wide open connections.) _connectionsr)rr:r:r;net_connectionssr"cCstdt}|j}WdQRXi}x|ddD]}|jd}|dksVtt||d|j}||ddjj}tt |\}}} } } } } }}}}}}}}}||||| || |f||<q4W|S)zsReturn network I/O statistics for every network interface installed on the system as a dict of raw tuples. z %s/net/devNr5rrr) rlrq readlinesrfindrurrrxmapr)rlinesretdictrZcolonnamerZ bytes_recvZ packets_recvZerrinZdropinZfifoinZframeinZ compressedinZ multicastinZ bytes_sentZ packets_sentZerroutZdropoutZfifooutZ collisionsoutZ carrieroutZ compressedoutr:r:r;net_io_counterss *r)cCsptjttjttjti}tj}i}xF|D]>}t j |}t j |}tj |\}}t j|||||||<q*W|S)z)Get NIC stats (isup, duplex, speed, mtu).)rZ DUPLEX_FULLrZ DUPLEX_HALFrZDUPLEX_UNKNOWNrr)keys cext_posixZ net_if_mtuZ net_if_flagsZnet_if_duplex_speedrZ snicstats)Z duplex_mapnamesrr(ZmtuZisupZduplexZspeedr:r:r; net_if_statss     r-cCs`dd}i}|}tdt}|j}WdQRXx$|D]}|j}t|}|dkr|d}t|d} tt|dd \ } } } } }}}}}}n|d kr|d}tt|dd \ } } } } } }}}}}}nN|d kr|d}tt|dd\} } } }d } }} }}n td |||kr.get_partitionsz %s/diskstatsNrr5rrrz!not sure how to interpret line %r) rlrqr#rxrrr%rr)r1r'r0rr&rrZ fields_lenr(ZreadsZ reads_mergedZrbytesZrtimeZwritesZ writes_mergedZwbytesZwtimerrRZssizer:r:r;disk_io_counterss6 (*   r4Fc Cst}tdtV}xN|D]F}|j}|jdsB|j|jq|jdd}|dkr|jdqWWdQRXg}tj}xT|D]L}|\}} }} |dkrd}|s|dks||krqt j || || } |j | qW|S) z8Return mounted disk partitions as a list of namedtuples.z%s/filesystemsZnodev rZzfsNZnoner) rrlrqrrrrxrdisk_partitionsrZ sdiskpartr) rZfstypesrrZfstyperetlistr0rZdeviceZ mountpointZoptsntupler:r:r;r6?s*    r6c Cs.tjt}tjd}|jtjdttdd|D}x|D]}ytt|dd}Wn8t t fk r}zt j d|t w@WYdd}~XnXttjjtjj|d d d }t|d dd }t|ddd }t|ddd d}|dk rt|d}|dk rt|d}||j||||fq@W|S)aReturn hardware (CPU and others) temperatures as a dict including hardware name, label, current, max and critical temperatures. Implementation notes: - /sys/class/hwmon looks like the most recent interface to retrieve this info, and this implementation relies on it only (old distros will probably use something else) - lm-sensors on Ubuntu 16.04 relies on /sys/class/hwmon - /sys/class/thermal/thermal_zone* is another one but it's more difficult to parse z/sys/class/hwmon/hwmon*/temp*_*z&/sys/class/hwmon/hwmon*/device/temp*_*cSsg|]}|jddqS)rr)rx)rrCr:r:r;rssz(sensors_temperatures.._inputg@@z ignoring %rNr(F)rZ_max)rZ_crit_labelr)rr) collectionsrrrextendsortedrrrrrrrrrvrTrdirnamer) r basenamesbasecurrentr unit_nameZhighZcriticallabelr:r:r;sensors_temperatures`s*      rDcCstjt}tjd}|s"tjd}ttdd|D}x|D]}ytt|d}Wn8tt fk r}zt j d|t w>WYdd}~XnXtt jjt jj|dd d }t|d d d d }||jtj||q>Wt|S)aReturn hardware fans info (for CPU and other peripherals) as a dict including hardware label and current speed. Implementation notes: - /sys/class/hwmon looks like the most recent interface to retrieve this info, and this implementation relies on it only (old distros will probably use something else) - lm-sensors on Ubuntu 16.04 relies on /sys/class/hwmon z/sys/class/hwmon/hwmon*/fan*_*z%/sys/class/hwmon/hwmon*/device/fan*_*cSsg|]}|jddqS)rr)rx)rrCr:r:r;rsz sensors_fans..r9z ignoring %rNr(F)rr:r)rr)r;rrrr=rrrrrrrrrvrTrr>rrZsfandict)rr?r@rArrBrCr:r:r; sensors_fanss    rFc stfdd}tjjtd}tjj|s0dS||d|d}||d|d}||d |d }|dksv|dkrzdS|dk ryd ||}Wqtk rd }YqXn tt|d dd}|dkrdSd}|tjjtdtjjtd}|dk r|dk}n4t|ddddj }|dkr*d}n|dkr8d}|rFt j } n2yt||d} Wntk rvt j } YnXt j || |S)aReturn battery information. Implementation note: it appears /sys/class/power_supply/BAT0/ directory structure may vary and provide files with the same meaning but under different names, see: https://github.com/giampaolo/psutil/issues/966 cs:x4|D],}t|d}|kr|jr.t|S|SqWdS)zvAttempt to read the content of multiple files which may not exist. If none of them exist return None. )rN)rr/r)pathsrTr)nullr:r; multi_cats   z"sensors_battery..multi_catZBAT0Nz /energy_nowz /charge_nowz /power_nowz /current_nowz /energy_fullz /charge_fullgY@gz /capacityr)rz AC0/onlinez AC/onlinez/statusrF)rrZ dischargingchargingfullTirr)rJrK)objectrvrTrPOWER_SUPPLY_PATHrZeroDivisionErrorrrrrZPOWER_TIME_UNLIMITEDZPOWER_TIME_UNKNOWNZsbattery) rIrootZ energy_nowZ power_nowZ energy_fullrIZ power_pluggedZonlinerZsecsleftr:)rHr;sensors_batterysT            rPc Cs`g}tj}xN|D]F}|\}}}}}}|s,q|dkr8d}tj||pDd|||} |j| qW|S)z:Return currently connected users as a list of namedtuples.:0.0:0Z localhostN)rQrR)rusersrZsuserr) r7ZrawlistitemrZttyZhostnameZtstampZ user_processrntr:r:r;rSs rSc Csbdt}t|F}x2|D]*}|jdrt|jjd}|a|SqWtd|WdQRXdS)zAReturn the system boot time expressed in seconds since the epoch.z%s/statsbtimerzline 'btime' not found in %sN)rqrgrrrrx BOOT_TIMEr )rTrrrr:r:r; boot_times    rWcCsddtjttDS)z7Returns a list of PIDs currently running on the system.cSsg|]}|jrt|qSr:)r/r)rrCr:r:r;r,szpids..)rvrrrqr:r:r:r;r*srcCstj|sdSybdt|f}t|B}x.|D]&}|jdr.t|jd}||kSq.Wtd|WdQRXWnttfk r|t kSXdS)zcCheck for the existence of a unix PID. Linux TIDs are not supported (always return False). Fz %s/%s/statussTgid:rz'Tgid' line not found in %sN) r pid_existsrqrgrrrxrEnvironmentErrorr)rrTrrZtgidr:r:r;rX/s      rXc Csi}t}xtD]}y(td||f}|j}WdQRXWn>tk r|}z"|jtjtjtjtj fkrlWYdd}~XqX|j d}||ddj }t |d}|||<qW|S)zsObtain a {pid: ppid, ...} dict for all running processes in one shot. Used to speed up Process.children(). z %s/%s/statN)r5r) rqrrgrrYrrrrrr$rxr) rrrrdatarrparZdsetppidr:r:r;ppid_mapOs     r^cstjfdd}|S)zlDecorator which translates bare OSError and IOError exceptions into NoSuchProcess and AccessDenied. csy|f||Stk r}zv|jtjtjfkrBt|j|j|jtjkr\t|j|j|jtj krt j j d|j |jf rt|j|jWYdd}~XnXdS)Nz%s/%s)rYrrrrr_namerrrrvrTrr)rargsrfr)funr:r;wrapperks z wrap_exceptions..wrapper) functoolswraps)rarbr:)rar;wrap_exceptionsgsrec@sneZdZdZddddgZddZedd Zed d Zed d Z ddZ ddZ e ddZ ddZe ddZe ddZe ddZejjdejre ddZnddZe d d!Ze d"d#Ze d`d%d&Ze d'd(Ze d)d*Zer"e ejd+ejd,ejd-fd.d/ZneZer:e d0d1Z nd2d1Z e d3d4Z!e ejd5fd6d7Z"e ejd8fd9d:Z#e d;d<Z$e d=d>Z%e d?d@Z&e dAdBZ'ejdCfdDdEZ(e dFdGZ)e*e+dHre dIdJZ,e dKdLZ-e.re dadMdNZ/e dOdPZ0e dQdRZ1e dbdTdUZ2e dVdWZ3e dXdYZ4e ejdZfd[d\Z5e ejd]fd^d_Z6d$S)cProcesszLinux process implementation.rr__ppidrcCs||_d|_d|_t|_dS)N)rr_rgrqr)rrr:r:r;rszProcess.__init__c Csftd|j|jf}|j}WdQRX|jd}||jdd|}||ddj}|g|S)a{Parse /proc/{pid}/stat file. Return a list of fields where process name is in position 0. Using "man proc" as a reference: where "man proc" refers to position N, always substract 2 (e.g starttime pos 22 in 'man proc' == pos 20 in the list returned here). The return value is cached in case oneshot() ctx manager is in use. z %s/%s/statNrZ(rr5)rgrrrr$findrx)rrr[r\r(Zothersr:r:r;_parse_stat_files  zProcess._parse_stat_filec Cs(td|j|jf }|jSQRXdS)zRead /proc/{pid}/stat file and return its content. The return value is cached in case oneshot() ctx manager is in use. z %s/%s/statusN)rgrrr)rrr:r:r;_read_status_fileszProcess._read_status_filec Cs0td|j|jftd}|jjSQRXdS)Nz %s/%s/smaps)r)rgrrr rr)rrr:r:r;_read_smaps_files zProcess._read_smaps_filecCs"|jj|jj|jjdS)N)rjZcache_activaterkrl)rr:r:r; oneshot_enters  zProcess.oneshot_entercCs"|jj|jj|jjdS)N)rjZcache_deactivaterkrl)rr:r:r; oneshot_exits  zProcess.oneshot_exitcCs|jd}trt|}|S)Nr)rjrrm)rr(r:r:r;r(s z Process.namecCsytd|j|jfStk r}z|jtjtjfkrtjj d|j|jfrTdSt |jsnt |j|j nt |j|j |j|jtjtjfkrt|j|j WYdd}~XnXdS)Nz %s/%s/exez%s/%sr)rwrrrrrrrvrTlexistsrXrr_rrgrrr)rrr:r:r;exes z Process.exec Csltd|j|jf}|j}WdQRX|s0gS|jdr>dnd}|j|rX|dd}dd|j|DS)Nz %s/%s/cmdlinerrrarcSsg|]}|qSr:r:)rrCr:r:r;rsz#Process.cmdline..r)rlrrrryrx)rrr[sepr:r:r;cmdlines  zProcess.cmdlinec Cs0td|j|jf}|j}WdQRXt|S)Nz %s/%s/environ)rlrrrr)rrr[r:r:r;environszProcess.environc Cs:t|jd}tj}y||Stk r4dSXdS)N)rrjrZget_terminal_mapr)rZtty_nrrr:r:r;terminals zProcess.terminalz /proc/%s/iocCsd|j|jf}i}t|:}x2|D]*}|j}|r$|jd\}}t|||<q$WWdQRX|sltd|t|d|d|d|d|d|d S) Nz%s/%s/ios: z%s file was emptyssyscrssyscws read_bytess write_bytessrcharswchar)rrrgrrxrr rb)rrerrrr(rr:r:r; io_counterss"   zProcess.io_counterscCstd|jdS)Nz+couldn't find /proc/%s/io (kernel too old?))rr)rr:r:r;rv scCsX|j}t|dt}t|dt}t|dt}t|dt}tj||||S)N r3r2)rjrrrZ pcputimes)rrutimestimeZchildren_utimeZchildren_stimer:r:r;rs zProcess.cpu_timescCst|jdS)zWhat CPU the process is on.%)rrj)rr:r:r;cpu_numszProcess.cpu_numNcCstj|j||jS)N)rZwait_pidrr_)rZtimeoutr:r:r;waitsz Process.waitcCs&|j}tpt}t|dt|S)N)rjrVrWrr)rrZbtr:r:r; create_time"s zProcess.create_timec Cs`td|j|jf2}dd|jjddD\}}}}}}}WdQRXt|||||||S)Nz %s/%s/statmcSsg|]}t|tqSr:)rr)rrCr:r:r;r<sz'Process.memory_info..r)rgrrrrxrX) rrZvmsr^rPtextlibr[Zdirtyr:r:r; memory_info-s 6zProcess.memory_infosPrivate.*:\s+(\d+)sPss.*:\s+(\d+)sSwap.*:\s+(\d+)c Csj|j}|j}ttt|j|d}ttt|j|d}ttt|j|d}t||||fS)Ni)rrlrr%rfindallrY) rZ _private_reZ_pss_reZ_swap_reZ basic_memZ smaps_datarZr[r\r:r:r;memory_full_infoCs  zProcess.memory_full_infocCsXdd}|j}|sgS|jd}g}|jd}|g}x|||D] \}}|jdd}y|\} } } } } }Wn*tk r|dg\} } } } } }YnX|sd}n4trt|}|j}|jd rt| r|dd}|j t| t| ||d |j d d|j d d|j dd|j dd|j dd|j dd|j dd|j dd|j ddf qDW|S)zReturn 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 c ssi}x|D]}|jdd}|djdsB|j|fV|j|q yt|dd||d<Wq tk r|djdrw n td|Yq Xq W|j|fVdS)Nrtr:risVmFlags:z#don't know how to interpret line %r)rxrypoprrrr)r& current_blockr[rrr:r:r; get_blocksis   z'Process.memory_maps..get_blocks rNrtrz[anon]z (deleted)rssRss:sSize:sPss:s Shared_Clean:s Shared_Dirty:sPrivate_Clean:sPrivate_Dirty:s Referenced:s Anonymous:sSwap:i) rlrxrrrrmrryrrr)rrr[r&rZ first_linerheaderZhfieldsrZpermsoffsetZdevrrTr:r:r; memory_mapscsF              zProcess.memory_mapscCstd|jdS)Nzn/proc/%s/smaps does not exist on kernels < 2.6.14 or if CONFIG_MMU kernel configuration option is not enabled.)rr)rr:r:r;rscCs|ytd|j|jfStk rv}zF|jtjtjfkrdt|jsRt|j|j nt |j|j |j WYdd}~XnXdS)Nz %s/%s/cwd) rwrrrrrrrXrr_rrg)rrr:r:r;cwds z Process.cwdsctxt_switches:\t(\d+)cCsL|j}|j|}|s,td|j|jfntjt|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)rkrrrrrZpctxswr)rZ _ctxsw_rer[Zctxswr:r:r;num_ctx_switchess zProcess.num_ctx_switchessThreads:\t(\d+)cCs|j}t|j|dS)Nr)rkrr)rZ_num_threads_rer[r:r:r; num_threadsszProcess.num_threadsc Cstjd|j|jf}|jg}d}x|D]}d|j|j|f}y$t|}|jj}WdQRXWn6tk r}z|j t j krd}w,WYdd}~XnX||j ddd}|j d} t | dt} t | d t} tjt|| | } |j| q,W|rtjd |j|jf|S) Nz %s/%s/taskFz%s/%s/task/%s/statTrZr5r rwz%s/%s)rvrrrrrgrrrrrrirxrrrZpthreadrrstat) rZ thread_idsr7 hit_enoentZ thread_idrerstrrryrzr8r:r:r;threadss0    zProcess.threadscCs tj|jS)N)r+ getpriorityr)rr:r:r;nice_getszProcess.nice_getcCstj|j|S)N)r+ setpriorityr)rrr:r:r;nice_setszProcess.nice_setcCs tj|jS)N)rZproc_cpu_affinity_getr)rr:r:r;cpu_affinity_getszProcess.cpu_affinity_getsCpus_allowed_list:\t(\d+)-(\d+)cCsV|j}|j|}|r@ttt|ddt|dddSttttSdS)Nrr)rkrrrangerrr)rZ_rer[rr:r:r;_get_eligible_cpuss  *zProcess._get_eligible_cpuscCsytj|j|Wnttfk r}zvt|ts>|jtjkr|j}t t t t }x<|D]4}||krztd||f||kr^td||fq^WWYdd}~XnXdS)Nz(invalid CPU number %r; choose between %sz0CPU number %r is not eligible; choose between %s) rZproc_cpu_affinity_setrrrrtrrrtuplerrr)rrrZ eligible_cpusZall_cpusZcpur:r:r;cpu_affinity_sets   zProcess.cpu_affinity_setproc_ioprio_getcCs,tj|j\}}tdk r t|}tj||S)N)rrrenumr6rZpionice)rioclassrr:r:r; ionice_getszProcess.ionice_getcCs|dk rNt r.t|ttf r.d|}t|d|ko@dknsNtd|tdfkrx|rnd|}t|t}d}nH|tkr|rd|}t|d}n&|tt fkr|dkrd}n td|t j |j ||S) Nz)value argument is not an integer (gor %r)rrz0value argument range expected is between 0 and 7z3can't specify value with IOPRIO_CLASS_NONE (got %r)z3can't specify value with IOPRIO_CLASS_IDLE (got %r)rzinvalid ioclass argument %r) rrtrr TypeErrorrr r#r!r"rZproc_ioprio_setr)rrrrr:r:r; ionice_set%s2   zProcess.ionice_setcCs|jdkrtdyP|dkr*tj|j|St|dkrFtdt||\}}tj|j|||WnNtk r}z2|jtjkrt |jrt |j|j |j nWYdd}~XnXdS)Nrz)can't use prlimit() against PID 0 processr5z4second argument must be a (soft, hard) tuple, got %s) rrrr/rrrrZENOSYSrXrr_rg)rZresourceZlimitsZsoftZhardrr:r:r;rlimitGs   zProcess.rlimitcCs$|jd}tr|j}tj|dS)Nr?)rjrrm PROC_STATUSESr)rZletterr:r:r;rbs zProcess.statusc Csg}tjd|j|jf}d}xH|D]>}d|j|j|f}y t|}WnNtk r}z2|jtjtjfkrvd}w&n|jtj krw&nWYdd}~Xq&X|j dot |r&d|j|j|f}yBt |0}t |jjd} t |jjdd} WdQRXWn:tk r:}z|jtjkr(d}nWYdd}~Xq&Xt| } t|t |t | | | } |j| q&W|rtjd |j|jf|S) Nz%s/%s/fdFz %s/%s/fd/%sT/z%s/%s/fdinfo/%srrz%s/%s)rvrrrrwrrrrrrr rgrrrxrrrSrr) rr7filesrrUrrTrrposrWrVr8r:r:r; open_filesjs@   $zProcess.open_filesrcCs(tj||j}tjd|j|jf|S)Nz%s/%s)r!rrrvrr)rrrr:r:r; connectionsszProcess.connectionscCsttjd|j|jfS)Nz%s/%s/fd)rrvrrr)rr:r:r;num_fdsszProcess.num_fdscCst|jdS)Nr5)rrj)rr:r:r;r]sz Process.ppidsUid:\t(\d+)\t(\d+)\t(\d+)cCs6|j}|j|d\}}}tjt|t|t|S)Nr)rkrrZpuidsr)rZ_uids_rer[real effectivesavedr:r:r;uidssz Process.uidssGid:\t(\d+)\t(\d+)\t(\d+)cCs6|j}|j|d\}}}tjt|t|t|S)Nr)rkrrZpgidsr)rZ_gids_rer[rrrr:r:r;gidssz Process.gids)N)N)r)7r7r8r9r __slots__rrrjrkrlrmrnrer(rprrrsrurvrTrgetpidrvrr|r}rr HAS_SMAPSrrrrrrrrrrrrrhasattrrrr HAS_PRLIMITrrrrrr]rrr:r:r:r;rfst          B         !   2   rf)rrr)rZr[r\)r)F)rZ __future__rrr;rrcrrvrrrro tracebackrrrrrrrrr r+r r r r rrrrrrrrZ_compatrrrr _exceptionsrrr version_inforZ__extra__all__rMrTrrrrrrLrdirr(rrrrrrVr  byteorderrrZ AF_PACKETr4IntEnumrr3r r!r"r#r6globalsr __members__ZSTATUS_RUNNINGZSTATUS_SLEEPINGZSTATUS_DISK_SLEEPZSTATUS_STOPPEDZSTATUS_TRACING_STOPZ STATUS_ZOMBIEZ STATUS_DEADZSTATUS_WAKE_KILLZ STATUS_WAKINGrr$r%r&r'r(r)r*r+r,r-r.r rFrQrSrXrrYr]rr`rbrgrlrmrqrwrrrr Exception print_excrrrrrrrrrrZ net_if_addrsrrr!r"r)r-Z disk_usager4r6rDrFrPrSrWrrXr^rerfr:r:r:r;sH                                              5u:*q %H !1 T