o
    r_                     @   s  d dl Z d dlZd dlmZ d dlZd dlZd dlmZ d dlm	Z	 dZ
dd Zdd	 ZG d
d dZdd Zdd ZG dd dZG dd dZG dd dZG dd dZG dd dZG dd dZG dd dZG dd dZG d d! d!ZG d"d# d#Zed$kr>d dlZe Zeej D ]Ze d%eeje f  qe Z!ee!j! D ]Z"e d%e"e!j!e" f  qe Z#e d&e#j$  ee# D ]Z%e d'e%e#e% f  qe d( ee&ej'd) Z(ee(j)D ]Ze d*e(j*e j+e(j*e j,f  qe d+ e(-ej'd, D ]	Z.e e.d-  qe Z/e e/d)  e Z0	 e1d) e02  e0D ]Z#e d/e#j,e#j3f  q*e d0 qdS )1    N)reduce)range)bitmasklistz0.5c                  C   s   t  } ttd| S )z) Return True if running on s390 or s390x s390)platformmachineboolresearch)r    r   //usr/lib/python3/dist-packages/procfs/procfs.pyis_s390    s   r   c                 C   s*   | d rt dd | d  S | d d S )z
    Returns the process command line, if available in the given `process' class, if
    not available, falls back to using the comm (short process name) in its pidstat key.
    cmdlinec                 S   s   | d|  S )Nz %sr   )abr   r   r   <lambda>,   s    z!process_cmdline.<locals>.<lambda>statcomm)r   strip)pid_infor   r   r   process_cmdline&   s   r   c                   @   s   e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZ dZ!dZ"dZ#dZ$d Z%d!Z&d!Z'g d"Z(d9d$d%Z)d&d' Z*d(d) Z+d*d+ Z,d,d- Z-d.d/ Z.d0d1 Z/d9d2d3Z0d4d5 Z1d6d7 Z2d8S ):pidstatag  Provides a dictionary to access the fields in the per process /proc/PID/stat
       files.

       One can obtain the available fields asking for the keys of the dictionary, e.g.:

        >>> p = procfs.pidstat(1)
        >>> print p.keys()
        ['majflt', 'rss', 'cnswap', 'cstime', 'pid', 'session', 'startstack', 'startcode', 'cmajflt', 'blocked', 'exit_signal', 'minflt', 'nswap', 'environ', 'priority', 'state', 'delayacct_blkio_ticks', 'policy', 'rt_priority', 'ppid', 'nice', 'cutime', 'endcode', 'wchan', 'num_threads', 'sigcatch', 'comm', 'stime', 'sigignore', 'tty_nr', 'kstkeip', 'utime', 'tpgid', 'itrealvalue', 'kstkesp', 'rlim', 'signal', 'pgrp', 'flags', 'starttime', 'cminflt', 'vsize', 'processor']

       And then access the various process properties using it as a dictionary:

        >>> print p['comm']
        systemd
        >>> print p['priority']
        20
        >>> print p['state']
        S

       Please refer to the 'procfs(5)' man page, by using:

        $ man 5 procfs

       To see information for each of the above fields, it is part of the
           'man-pages' RPM package.
                       @         i   i   i   i   i    i @  i   i   i   i   i   i   i    i  @ i   i   i      i   i   i    i   @l        )+pidr   stateppidpgrpsessiontty_nrtpgidflagsminfltcminfltmajfltcmajfltutimestimecutimecstimeprioritynicenum_threadsitrealvalue	starttimevsizerssrlim	startcodeendcode
startstackkstkespkstkeipsignalblocked	sigignoresigcatchwchannswapcnswapexit_signal	processorrt_prioritypolicydelayacct_blkio_ticksenviron/procc                 C      || _ | | d S Nr"   loadselfr"   basedirr   r   r   __init__      zpidstat.__init__c                 C   
   | j | S rN   fieldsrR   	fieldnamer   r   r   __getitem__      
zpidstat.__getitem__c                 C      t | j S rN   listrX   keysrR   r   r   r   r`         zpidstat.keysc                 C   r]   rN   r_   rX   valuesra   r   r   r   rd      rb   zpidstat.valuesc                 C   
   || j v S rN   rW   rY   r   r   r   has_key   r\   zpidstat.has_keyc                 C      | j S rN   rW   ra   r   r   r   items      zpidstat.itemsc                 C   re   rN   rW   rY   r   r   r   __contains__   r\   zpidstat.__contains__c                 C   s   t d|| jf }|  d}|  |d d|d   }i | _tt|t| j	}t
|D ]+}| j	| }|| }|dkrL|d| jd< q4z	t|| j|< W q4   || j|< Y q4d S )Nz
%s/%d/statz) r   z (r   r   z())openr"   readliner   splitcloserX   minlenproc_stat_fieldsr   int)rR   rS   frX   	nr_fieldsiattrnamevaluer   r   r   rP      s    
zpidstat.loadc                 C   s   | j d | j@ r
dpdS )z
        Returns true if this process has a fixed smp affinity mask,
                not allowing it to be moved to a different set of CPUs.
        r)   TF)rX   PF_THREAD_BOUNDra   r   r   r   is_bound_to_cpu   s
   zpidstat.is_bound_to_cpuc                 C   sJ   g }t | D ]}|dd dkrqt| |}|| jd @ r"|| q|S )a  
        Returns a list with all the process flags known, details depend
        on kernel version, declared in the file include/linux/sched.h in
        the kernel sources.

        As of v4.2-rc7 these include (from include/linux/sched.h comments):

            PF_EXITING       Getting shut down
            PF_EXITPIDONE       Pi exit done on shut down
            PF_VCPU           I'm a virtual CPU
            PF_WQ_WORKER       I'm a workqueue worker
            PF_FORKNOEXEC       Forked but didn't exec
            PF_MCE_PROCESS       Process policy on mce errors
            PF_SUPERPRIV       Used super-user privileges
            PF_DUMPCORE       Dumped core
            PF_SIGNALED       Killed by a signal
            PF_MEMALLOC       Allocating memory
            PF_NPROC_EXCEEDED  Set_user noticed that RLIMIT_NPROC was exceeded
            PF_USED_MATH       If unset the fpu must be initialized before use
            PF_USED_ASYNC       Used async_schedule*(), used by module init
            PF_NOFREEZE       This thread should not be frozen
            PF_FROZEN       Frozen for system suspend
            PF_FSTRANS       Inside a filesystem transaction
            PF_KSWAPD       I am kswapd
            PF_MEMALLOC_NOIO   Allocating memory without IO involved
            PF_LESS_THROTTLE   Throttle me less: I clean memory
            PF_KTHREAD       I am a kernel thread
            PF_RANDOMIZE       Randomize virtual address space
            PF_SWAPWRITE       Allowed to write to swap
            PF_NO_SETAFFINITY  Userland is not allowed to meddle with cpus_allowed
            PF_MCE_EARLY       Early kill for mce process policy
            PF_MUTEX_TESTER       Thread belongs to the rt mutex tester
            PF_FREEZER_SKIP       Freezer should not count it as freezable
            PF_SUSPEND_TASK       This thread called freeze_processes and should not be frozen

        N   PF_r)   )dirgetattrrX   append)rR   sflagsattrrw   r   r   r   process_flags   s   %

zpidstat.process_flagsNrL   )3__name__
__module____qualname____doc__PF_ALIGNWARNPF_STARTING
PF_EXITINGPF_EXITPIDONEPF_VCPUPF_WQ_WORKERPF_FORKNOEXECPF_MCE_PROCESSPF_SUPERPRIVPF_DUMPCOREPF_SIGNALEDPF_MEMALLOCPF_NPROC_EXCEEDED
PF_FLUSHERPF_USED_MATHPF_USED_ASYNCPF_NOFREEZE	PF_FROZEN
PF_FSTRANS	PF_KSWAPDPF_MEMALLOC_NOIO
PF_SWAPOFFPF_LESS_THROTTLE
PF_KTHREADPF_RANDOMIZEPF_SWAPWRITEPF_SPREAD_PAGEPF_SPREAD_SLABrx   PF_NO_SETAFFINITYPF_MCE_EARLYPF_MEMPOLICYPF_MUTEX_TESTERPF_FREEZER_SKIPPF_FREEZER_NOSIGPF_SUSPEND_TASKrq   rT   r[   r`   rd   rf   rh   rj   rP   ry   r   r   r   r   r   r   1   sb    

r   c                 C   s6   d}zt | j| d d |@ rdpdW S    Y dS Nr!   r   r)   TF)rr   	processes)rR   r"   r   r   r   r   cannot_set_affinity   s   r   c                 C   s<   d}zt | j| j| d d |@ rdpdW S    Y dS r   )rr   r   threads)rR   r"   tidr   r   r   r   cannot_set_thread_affinity   s   r   c                   @   sT   e Zd ZdZdddZdd Zdd Zd	d
 Zdd Zdd Z	dd Z
dddZdS )	pidstatusa  
    Provides a dictionary to access the fields in the per process /proc/PID/status
    files. This provides additional information about processes and threads to what
    can be obtained with the procfs.pidstat() class.

    One can obtain the available fields asking for the keys of the dictionary, e.g.:

        >>> import procfs
        >>> p = procfs.pidstatus(1)
        >>> print p.keys()
        ['VmExe', 'CapBnd', 'NSpgid', 'Tgid', 'NSpid', 'VmSize', 'VmPMD', 'ShdPnd', 'State', 'Gid', 'nonvoluntary_ctxt_switches', 'SigIgn', 'VmStk', 'VmData', 'SigCgt', 'CapEff', 'VmPTE', 'Groups', 'NStgid', 'Threads', 'PPid', 'VmHWM', 'NSsid', 'VmSwap', 'Name', 'SigBlk', 'Mems_allowed_list', 'VmPeak', 'Ngid', 'VmLck', 'SigQ', 'VmPin', 'Mems_allowed', 'CapPrm', 'Seccomp', 'VmLib', 'Cpus_allowed', 'Uid', 'SigPnd', 'Pid', 'Cpus_allowed_list', 'TracerPid', 'CapInh', 'voluntary_ctxt_switches', 'VmRSS', 'FDSize']
        >>> print p["Pid"]
        1
        >>> print p["Threads"]
        1
        >>> print p["VmExe"]
        1248 kB
        >>> print p["Cpus_allowed"]
        f
        >>> print p["SigQ"]
        0/30698
        >>> print p["VmPeak"]
        320300 kB
        >>>

    Please refer to the 'procfs(5)' man page, by using:

        $ man 5 procfs

    To see information for each of the above fields, it is part of the
    'man-pages' RPM package.

    In the man page there will be references to further documentation, like
        referring to the "getrlimit(2)" man page when explaining the "SigQ"
        line/field.
    rL   c                 C   rM   rN   rO   rQ   r   r   r   rT     rU   zpidstatus.__init__c                 C   rV   rN   rW   rY   r   r   r   r[     r\   zpidstatus.__getitem__c                 C   r]   rN   r^   ra   r   r   r   r`   "  rb   zpidstatus.keysc                 C   r]   rN   rc   ra   r   r   r   rd   %  rb   zpidstatus.valuesc                 C   re   rN   rW   rY   r   r   r   rf   (  r\   zpidstatus.has_keyc                 C   rg   rN   rW   ra   r   r   r   rh   +  ri   zpidstatus.itemsc                 C   re   rN   rW   rY   r   r   r   rj   .  r\   zpidstatus.__contains__c                 C   s   t d|| jf }i | _| D ]+}|d}t|dkrq|d }|d  }z	t|| j|< W q   || j|< Y q|  d S )Nz%s/%d/status:r   r   r   )	rk   r"   rX   	readlinesrm   rp   r   rr   rn   )rR   rS   rs   linerX   namerw   r   r   r   rP   1  s   
zpidstatus.loadNr   )r   r   r   r   rT   r[   r`   rd   rf   rh   rj   rP   r   r   r   r   r      s    
%r   c                   @   R   e Zd ZdZdddZdd Zdd Zd	d
 Zdd Zdd Z	dd Z
dd ZdS )processa+  
    Information about a process with a given pid, provides a dictionary with
    two entries, instances of different wrappers for /proc/ process related
    meta files: "stat" and "status", see the documentation for procfs.pidstat
    and procfs.pidstatus for further info about those classes.
    rL   c                 C   s   || _ || _d S rN   )r"   rS   rQ   r   r   r   rT   I  s   
zprocess.__init__c                 C   s   t | |sA|dv r|dkrt}nt}t| ||| j| j n#|dkr'|   n|dkr0|   n|dkr9|   n|dkrA| 	  t
| |S )N)r   statusr   r   r   cgroupsrK   )hasattrr   r   setattrr"   rS   load_cmdlineload_threadsload_cgroupsload_environr}   )rR   r   sclassr   r   r   r[   M  s   




zprocess.__getitem__c                 C   
   t | |S rN   r   rR   r   r   r   r   rf   a  r\   zprocess.has_keyc                 C   r   rN   r   r   r   r   r   rj   d  r\   zprocess.__contains__c                 C   s6   t d| j }|  dd d | _|  d S )Nz/proc/%d/cmdline )rk   r"   rl   r   rm   r   rn   )rR   rs   r   r   r   r   g  s   zprocess.load_cmdlinec                 C   s   t d| j | _| j| j= d S )Nz/proc/%d/task/)pidstatsr"   r   ra   r   r   r   r   l  s   zprocess.load_threadsc                 C   sh   t d| j }d| _t| D ]}t| jdkr&| jd |d d  | _q|d d | _q|  d S )Nz/proc/%d/cgroup r   ,r   )rk   r"   r   reversedr   rp   rn   rR   rs   r   r   r   r   r   q  s   zprocess.load_cgroupsc                 C   s\   i | _ td| j }| dD ]}t|dkr'|d}|d | j |d < q|  dS )aD  
        Loads the environment variables for this process. The entries then
        become available via the 'environ' member, or via the 'environ'
        dict key when accessing as p["environ"].

        E.g.:


        >>> all_processes = procfs.pidstats()
        >>> firefox_pid = all_processes.find_by_name("firefox")
        >>> firefox_process = all_processes[firefox_pid[0]]
        >>> print firefox_process["environ"]["PWD"]
        /home/acme
        >>> print len(firefox_process.environ.keys())
        66
        >>> print firefox_process["environ"]["SHELL"]
        /bin/bash
        >>> print firefox_process["environ"]["USERNAME"]
        acme
        >>> print firefox_process["environ"]["HOME"]
        /home/acme
        >>> print firefox_process["environ"]["MAIL"]
        /var/spool/mail/acme
        >>>
        z/proc/%d/environr   r   =r   N)rK   rk   r"   rl   rm   rp   rn   )rR   rs   xyr   r   r   r   {  s   
zprocess.load_environNr   )r   r   r   r   rT   r[   rf   rj   r   r   r   r   r   r   r   r   r   A  s    

r   c                   @   s   e Zd ZdZd$ddZdd Zdd Zd	d
 Zdd Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Zdd  Zd!d" Zd#S )%r   a#  
    Provides access to all the processes in the system, to get a picture of
    how many processes there are at any given moment.

    The entries can be accessed as a dictionary, keyed by pid. Also there are
    methods to find processes that match a given COMM or regular expression.
    rL   c                 C   s   || _ i | _|   d S rN   )rS   r   reload)rR   rS   r   r   r   rT        zpidstats.__init__c                 C   rV   rN   r   rR   keyr   r   r   r[     r\   zpidstats.__getitem__c                 C   s   z| j |= W d S    Y d S rN   r   r   r   r   r   __delitem__  s   zpidstats.__delitem__c                 C   r]   rN   )r_   r   r`   ra   r   r   r   r`     rb   zpidstats.keysc                 C   r]   rN   )r_   r   rd   ra   r   r   r   rd     rb   zpidstats.valuesc                 C   re   rN   r   r   r   r   r   rf     r\   zpidstats.has_keyc                 C   rg   rN   r   ra   r   r   r   rh     ri   zpidstats.itemsc                 C   re   rN   r   r   r   r   r   rj     r\   zpidstats.__contains__c                 C   sN   | ` i | _ t| j}|D ]}zt|}W n   Y qt|| j| j |< qdS )a'  
        This operation will throw away the current dictionary contents, if any, and
        read all the pid files from /proc/, instantiating a 'process' instance for
        each of them.

        This is a high overhead operation, and should be avoided if the perf python
        binding can be used to detect when new threads appear and existing ones
        terminate.

        In RHEL it is found in the python-perf rpm package.

        More information about the perf facilities can be found in the 'perf_event_open'
        man page.
        N)r   oslistdirrS   rr   r   )rR   pidsspidr"   r   r   r   r     s   zpidstats.reloadc              	   C   s\   g }t | j D ]}z	| j|   W q	 ty"   || Y q	w |D ]}| j|= q%d S rN   )r_   r   r`   r   OSErrorr~   )rR   	to_remover"   r   r   r   reload_threads  s   
zpidstats.reload_threadsc              	   C   sf   |d d }g }t | j D ]!}z|| j| d d kr"|| W q ty0   | j|= Y qw |S )N   r   r   )r_   r   r`   r~   IOError)rR   r   r   r"   r   r   r   find_by_name  s   
zpidstats.find_by_namec              	   C   s\   g }t | j D ]"}z|| j| d d r|| W q	 ty+   | j|= Y q	w |S )Nr   r   )r_   r   r`   matchr~   r   rR   regexr   r"   r   r   r   find_by_regex  s   
zpidstats.find_by_regexc              	   C   sX   g }t | j D ] }z|t| j| r|| W q	 ty)   | j|= Y q	w |S rN   )r_   r   r`   r   r   r~   r   r   r   r   r   find_by_cmdline_regex  s   
zpidstats.find_by_cmdline_regexc              	      s   d}d}g  	 d||f }|  |}|r!t fdd|D dkr"n*|D ]}z|d| j| d d	  7 }W q$ tyB   | j|= Y q$w  |7  |d
7 }q|d}|S )Nr   r   Tz%s/%dc                       g | ]}| vr|qS r   r   .0nprocessed_pidsr   r   
<listcomp>      z0pidstats.get_per_cpu_rtprios.<locals>.<listcomp>%s,r   rH   r   r   r   rp   r   r   r   )rR   basenamecpu
prioritiesr   r   r"   r   r   r   get_per_cpu_rtprios  s&   

zpidstats.get_per_cpu_rtpriosc              	      s   d}d}g  	 |  |}|rt fdd|D dkrn*|D ]}z|d| j| d d  7 }W q ty<   | j|= Y qw  |7  |d	7 }q|d
}|S )Nr   r   Tc                    r   r   r   r   r   r   r   r   0  r   z(pidstats.get_rtprios.<locals>.<listcomp>r   r   rH   r   r   r   )rR   r   r   r   r   r"   r   r   r   get_rtprios*  s$   

zpidstats.get_rtpriosc                 C   s   | j | d  S )zQ
        Checks if a given pid can't have its SMP affinity mask changed.
        r   )r   ry   rR   r"   r   r   r   ry   @  s   zpidstats.is_bound_to_cpuNr   )r   r   r   r   rT   r[   r   r`   rd   rf   rh   rj   r   r   r   r   r   r   r   ry   r   r   r   r   r     s$    
r   c                   @   sp   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd ZdS )
interruptsam  
    Information about IRQs in the system. A dictionary keyed by IRQ number
    will have as its value another dictionary with "cpu", "type" and "users"
    keys, with the SMP affinity mask, type of IRQ and the drivers associated
    with each interrupt.

    The information comes from the /proc/interrupts file, documented in
    'man procfs(5)', for instance, the 'cpu' dict is an array with one entry
    per CPU present in the sistem, each value being the number of interrupts
    that took place per CPU.

    E.g.:

    >>> import procfs
    >>> interrupts = procfs.interrupts()
    >>> thunderbolt_irq = interrupts.find_by_user("thunderbolt")
    >>> print thunderbolt_irq
    34
    >>> thunderbolt = interrupts[thunderbolt_irq]
    >>> print thunderbolt
    {'affinity': [0, 1, 2, 3], 'type': 'PCI-MSI', 'cpu': [3495, 0, 81, 0], 'users': ['thunderbolt']}
    >>>
    c                 C      i | _ |   d S rN   )r   r   ra   r   r   r   rT   `     zinterrupts.__init__c                 C   s   | j t| S rN   )r   strr   r   r   r   r[   d  rb   zinterrupts.__getitem__c                 C   r]   rN   r_   r   r`   ra   r   r   r   r`   g  rb   zinterrupts.keysc                 C   r]   rN   )r_   r   rd   ra   r   r   r   rd   j  rb   zinterrupts.valuesc                 C      t || jv S rN   r   r   r   r   r   r   rf   m  rb   zinterrupts.has_keyc                 C   rg   rN   )r   ra   r   r   r   rh   p  ri   zinterrupts.itemsc                 C   r   rN   r   r   r   r   r   rj   s  rb   zinterrupts.__contains__c                 C   s   | ` i | _ td}| D ]I}| }| }|d d d dkr't|| _q|d d}i | j |< | |dd  || j |< zt|}W n   Y q| 	|| j | d< q|
  d S )Nz/proc/interruptsr   rz   CPUr   r   affinity)r   rk   r   r   rm   rp   nr_cpusparse_entryrr   parse_affinityrn   )rR   rs   r   rX   irqnirqr   r   r   r   v  s$   

zinterrupts.reloadc                 C   s   i }g |d< |d  t|d  t|}|| jkrU|d  dd |d| j D 7  < || jkrU|| j |d< || jd krQdd ||d  dD |d	< |S g |d	< |S )
Nr   r   c                 S      g | ]}t |qS r   rr   r   ru   r   r   r   r         z*interrupts.parse_entry.<locals>.<listcomp>r   typec                 S   s   g | ]}|  qS r   )r   r   r   r   r   r   r     s    r   users)r~   rr   rp   r   rm   )rR   rX   r   dictrt   r   r   r   r     s   
$

zinterrupts.parse_entryc                 C   sD   zt d| }| }|  t|| jW S  ty!   dg Y S w )Nz/proc/irq/%s/smp_affinityr   )rk   rl   rn   r   r   r   )rR   r   rs   r   r   r   r   r     s   
zinterrupts.parse_affinityc                 C   s@   t | j D ]}d| j| v r|| j| d v r|  S qdS )a  
        Looks up a interrupt number by the name of one of its users"

        E.g.:

        >>> import procfs
        >>> interrupts = procfs.interrupts()
        >>> thunderbolt_irq = interrupts.find_by_user("thunderbolt")
        >>> print thunderbolt_irq
        34
        >>> thunderbolt = interrupts[thunderbolt_irq]
        >>> print thunderbolt
        {'affinity': [0, 1, 2, 3], 'type': 'PCI-MSI', 'cpu': [3495, 0, 81, 0], 'users': ['thunderbolt']}
        >>>
        r  Nr   )rR   userru   r   r   r   find_by_user  s   zinterrupts.find_by_userc                 C   sX   g }t | j D ] }d| j| vrq	| j| d D ]}||r(||  nqq	|S )a  
        Looks up a interrupt number by a regex that matches names of its users"

        E.g.:

        >>> import procfs
        >>> import re
        >>> interrupts = procfs.interrupts()
        >>> usb_controllers = interrupts.find_by_user_regex(re.compile(".*hcd"))
        >>> print usb_controllers
        ['22', '23', '31']
        >>> print [ interrupts[irq]["users"] for irq in usb_controllers ]
        [['ehci_hcd:usb4'], ['ehci_hcd:usb3'], ['xhci_hcd']]
        >>>
        r  )r_   r   r`   r   r~   )rR   r   irqsru   r  r   r   r   find_by_user_regex  s   

zinterrupts.find_by_user_regexN)r   r   r   r   rT   r[   r`   rd   rf   rh   rj   r   r   r   r	  r  r   r   r   r   r   G  s    	r   c                   @   @   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dS )r   a9  
    Parses the kernel command line (/proc/cmdline), turning it into a dictionary."

    Useful to figure out if some kernel boolean knob has been turned on, as well
    as to find the value associated to other kernel knobs.

    It can also be used to find out about parameters passed to the init process,
    such as 'BOOT_IMAGE', etc.

    E.g.:
    >>> import procfs
    >>> kcmd = procfs.cmdline()
    >>> print kcmd.keys()
    ['LANG', 'BOOT_IMAGE', 'quiet', 'rhgb', 'rd.lvm.lv', 'ro', 'root']
    >>> print kcmd["BOOT_IMAGE"]
    /vmlinuz-4.3.0-rc1+
    >>>
    c                 C   r   rN   )optionsparsera   r   r   r   rT     r   zcmdline.__init__c                 C   sb   t d}|   D ]}|d}t|dkr!d| j|d < q|d | j|d < q|  d S )Nz/proc/cmdliner   r   Tr   )rk   rl   r   rm   rp   r  rn   )rR   rs   optionrX   r   r   r   r    s   
zcmdline.parsec                 C   rV   rN   r  r   r   r   r   r[     r\   zcmdline.__getitem__c                 C   r]   rN   )r_   r  r`   ra   r   r   r   r`     rb   zcmdline.keysc                 C   r]   rN   )r_   r  rd   ra   r   r   r   rd      rb   zcmdline.valuesc                 C   rg   rN   r  ra   r   r   r   rh     ri   zcmdline.itemsN)
r   r   r   r   rT   r  r[   r`   rd   rh   r   r   r   r   r     s    r   c                   @   sB   e Zd ZdZdddZdd Zdd Zd	d
 Zdd Zdd Z	dS )cpuinfoa  
    Dictionary with information about CPUs in the system.

    Please refer to 'man procfs(5)' for further information about the
        '/proc/cpuinfo' file, that is the source of the information provided by this
        class. The 'man lscpu(1)' also has information about a program that uses
    the '/proc/cpuinfo' file.

    Using this class one can obtain the number of CPUs in a system:

      >>> cpus = procfs.cpuinfo()
          >>> print cpus.nr_cpus
          4

    It is also possible to figure out aspects of the CPU topology, such as
    how many CPU physical sockets exists, i.e. groups of CPUs sharing components
    such as CPU memory caches:

      >>> print len(cpus.sockets)
      1

    Additionally dictionary with information common to all CPUs in the system is
    available:

      >>> print cpus["model name"]
          Intel(R) Core(TM) i7-3667U CPU @ 2.00GHz
          >>> print cpus["cache size"]
          4096 KB
          >>>
    /proc/cpuinfoc                 C   s    i | _ d| _g | _| | d S Nr   )tagsr   socketsr  rR   filenamer   r   r   rT   '  s   zcpuinfo.__init__c                 C      | j |  S rN   r  lowerr   r   r   r   r[   -  rb   zcpuinfo.__getitem__c                 C   r]   rN   r_   r  r`   ra   r   r   r   r`   0  rb   zcpuinfo.keysc                 C   r]   rN   r_   r  rd   ra   r   r   r   rd   3  rb   zcpuinfo.valuesc                 C   rg   rN   r  ra   r   r   r   rh   6  ri   zcpuinfo.itemsc                 C   s  t |}| D ]S}| }|sq|d}|d   }|dkr*|  jd7  _qt r9|dkr9|  jd7  _q|dkr>q|d  | j|< |dkr[| j| }|| jvr[| j	| q|
  | jrht| jpx| jd| jv rvt| jd pwd | _d	| jv rt| jd	 pd| j | _d S )
Nr   r   rG   r   z
cpu numberzcore idzphysical idsiblingsz	cpu cores)rk   r   r   rm   r  r   r   r  r  r~   rn   rp   rr   
nr_socketsnr_cores)rR   r  rs   r   rX   tagname	socket_idr   r   r   r  9  s@   



zcpuinfo.parseN)r  )
r   r   r   r   rT   r[   r`   rd   rh   r  r   r   r   r   r    s    
r  c                   @   s8   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d ZdS )	smaps_libap  
    Representation of an mmap in place for a process. Can be used to figure
    out which processes have an library mapped, etc.

    The 'perm' member can be used to figure out executable mmaps, i.e. libraries.

    The 'vm_start' and 'vm_end' in turn can be used when trying to resolve
    processor instruction pointer addresses to a symbol name in a library.
    c                 C   s   |d   }dd |d  dD \| _| _|d | _t|d d| _|d  d	\| _| _t|d
 | _t	|dkrA|d | _
nd | _
i | _|dd  D ]%}|  }|d d d  }zt|d | j|< W qM   || j|< Y qMd S )Nr   c                 S   s   g | ]}t |d qS )r   r  r  r   r   r   r   d  s    z&smaps_lib.__init__.<locals>.<listcomp>-r   r   r   rz   r   r      r   )rm   vm_startvm_endpermsrr   offsetmajorminorinoderp   r   r  r  )rR   linesrX   r   tagr   r   r   rT   b  s$    
zsmaps_lib.__init__c                 C   r  rN   r  r   r   r   r   r[   w  rb   zsmaps_lib.__getitem__c                 C   r]   rN   r  ra   r   r   r   r`   z  rb   zsmaps_lib.keysc                 C   r]   rN   r  ra   r   r   r   rd   }  rb   zsmaps_lib.valuesc                 C   rg   rN   r  ra   r   r   r   rh     ri   zsmaps_lib.itemsN)	r   r   r   r   rT   r[   r`   rd   rh   r   r   r   r   r#  W  s    
r#  c                   @   r  )smapsa~  
    List of libraries mapped by a process. Parses the lines in
    the /proc/PID/smaps file, that is further documented in the
    procfs(5) man page.

    Example: Listing the executable maps for the 'sshd' process:

          >>> import procfs
          >>> processes = procfs.pidstats()
          >>> sshd = processes.find_by_name("sshd")
          >>> sshd_maps = procfs.smaps(sshd[0])
          >>> for i in range(len(sshd_maps)):
          ...     if 'x' in sshd_maps[i].perms:
          ...         print "%s: %s" % (sshd_maps[i].name, sshd_maps[i].perms)
          ...
          /usr/sbin/sshd: r-xp
          /usr/lib64/libnss_files-2.20.so: r-xp
          /usr/lib64/librt-2.20.so: r-xp
          /usr/lib64/libkeyutils.so.1.5: r-xp
          /usr/lib64/libkrb5support.so.0.1: r-xp
          /usr/lib64/libfreebl3.so: r-xp
          /usr/lib64/libpthread-2.20.so: r-xp
      ...
    c                 C   s   || _ g | _|   d S rN   )r"   entriesr   r   r   r   r   rT     r   zsmaps.__init__c                 C   sv   g }|s
|   }|sd S || 	 |  }|sn| }| d d dkr/|| nnq| jt| |S )NTr   r   r   )rl   r   r~   rm   r0  r#  )rR   rs   r   r-  r   r   r   r     s"   
	zsmaps.parse_entryc                 C   
   t | jS rN   )rp   r0  ra   r   r   r   __len__  r\   zsmaps.__len__c                 C   rV   rN   r0  )rR   indexr   r   r   r[     r\   zsmaps.__getitem__c                 C   s@   t d| j }d }	 | ||}|snq
|  t| j| _d S )Nz/proc/%d/smaps)rk   r"   r   rn   rp   r0  
nr_entriesr   r   r   r   r     s   zsmaps.reloadc                 C   sJ   g }t | jD ]}| j| jr"| j| j|dkr"|| j|  q|S r  )r   r5  r0  r   findr~   )rR   fragmentresultru   r   r   r   find_by_name_fragment  s   zsmaps.find_by_name_fragmentN)
r   r   r   r   rT   r   r2  r[   r   r9  r   r   r   r   r/    s    
r/  c                   @   s    e Zd ZdZdd Zdd ZdS )cpustatz
    CPU statistics, obtained from a line in the '/proc/stat' file, Please
    refer to 'man procfs(5)' for further information about the '/proc/stat'
    file, that is the source of the information provided by this class.
    c                 C   s|   |d | _ dd |dd D \| _| _| _| _| _| _| _t|dkr:t	|d | _
t|dkr<t	|d | _d S d S d S )Nr   c                 S   r   r   r  r  r   r   r   r     r  z$cpustat.__init__.<locals>.<listcomp>r   r      )r   r  r3   systemidleiowaitr   softirqrp   rr   stealguest)rR   rX   r   r   r   rT     s   
zcpustat.__init__c                 C   s\   d| j | j| j| j| j| j| jf }t| dr|d| j 7 }t| dr*|d| j	 7 }|d S )NzL< user: %s, nice: %s, system: %s, idle: %s, iowait: %s, irq: %s, softirq: %sr@  z, steal: %drA  z, guest: %d>)
r  r3   r<  r=  r>  r   r?  r   r@  rA  )rR   sr   r   r   __repr__  s   

zcpustat.__repr__N)r   r   r   r   rT   rD  r   r   r   r   r:    s    r:  c                   @   r   )	cpusstatsaN  
    Dictionary with information about CPUs in the system. First entry in the
    dictionary gives an aggregate view of all CPUs, each other entry is about
    separate CPUs. Please refer to 'man procfs(5)' for further information
    about the '/proc/stat' file, that is the source of the information provided
    by this class.
    
/proc/statc                 C   s*   i | _ d | _td| _|| _|   d S )Nr   )r0  timer   sysconfhertzr  r   r  r   r   r   rT     s
   zcpusstats.__init__c                 C   r1  rN   )iterr0  ra   r   r   r   __iter__   r\   zcpusstats.__iter__c                 C   rV   rN   r3  r   r   r   r   r[     r\   zcpusstats.__getitem__c                 C   s   t t| j S rN   )rp   r_   r0  r`   ra   r   r   r   r2    s   zcpusstats.__len__c                 C   r]   rN   )r_   r0  r`   ra   r   r   r   r`   	  rb   zcpusstats.keysc                 C   r]   rN   )r_   r0  rd   ra   r   r   r   rd     rb   zcpusstats.valuesc                 C   rg   rN   r3  ra   r   r   r   rh     ri   zcpusstats.itemsc                 C   s2  | j }i | _ t| j}| D ]1}|  }|d d d  dkr$qt|}|jdkr0d}nt	|jdd  d }|| j |< q|
  | j}t | _|r| j| }|| j }	t| j  D ]6}
|
|vrjd|_q`| j |
 }||
 }|j|j |j|j  |j|j  }||	 d |_|jdkrd|_q`d S d S )Nr   rz   r   r   d   )r0  rk   r  r   r   rm   r  r:  r   rr   rn   rG  rI  r_   r`   usager  r3   r<  )rR   last_entriesrs   r   rX   cidx	last_time	delta_secinterval_hzr   currprevdeltar   r   r   r     sF   









zcpusstats.reloadN)rF  )r   r   r   r   rT   rK  r[   r2  r`   rd   rh   r   r   r   r   r   rE    s    
rE  __main__z%s: %sz
cpuinfo data: %d processorsz%s=%sz/smaps:
----------------------------------------r   z%#x %sz(----------------------------------------r   SizeTz%s: %dz
----------)4r   rG  	functoolsr   r   r	   	six.movesr   procfs.utilistr   VERSIONr   r   r   r   r   r   r   r   r   r   r  r#  r/  r:  rE  r   sysintsr_   r`   ru   printr  or   r   r.  rr   argvrC  r5  r0  r&  r   r9  r   pscssleepr   rM  r   r   r   r   <module>   sp    3		L] * 0P-L 
D"
