o
    va Q                     @   s   d dl Z d dlmZ d dlmZmZmZmZ d dlm	Z	m
Z
 d dlmZ d dlmZ d dlZg dZG dd	 d	eZd
d Z		dddZ		dddZ		dddZ			dddZe ZdS )    N)iterkeys)BSDLINUXMACOSWINDOWS)TimergetTimeSinceLastUpdate)GlancesFilter)logger)cpu_percentmemory_percentusername	cpu_timesio_countersnamec                   @   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
edd Zedd Zedd Zejdd Zedd Zedd Zejdd Zedd Zedd  Zd!d" Zed#d$ Zd%d& Zd'd( Zd)d* Zd+d, Zd-d. Zd/d0 Zd=d2d3Zed4d5 Zd>d7d8Zd?d:d;Zd1S )@GlancesProcessesz-Get processed stats using the psutil library.<   c              
   C   sH  i | _ i | _|| _td| _i | _d| _d| _| jddd g | _	| 
  i | _d| _d| _z
t }|  W n tyU } ztd| d| _W Y d}~nd}~ww td d| _z
t }|  W n ty } ztd	| d| _W Y d}~nd}~ww td
 d| _d| _t | _d| _d| _i | _|   dS )z0Init the class to collect stats about processes.r   NautoT)r   Fz.PsUtil can not grab processes io_counters ({})z%PsUtil can grab processes io_countersz'PsUtil can not grab processes gids ({})zPsUtil can grab processes gidsr   r   ) Zusername_cacheZcmdline_cachecache_timeoutr   cache_timerio_old	auto_sort	_sort_keyset_sort_keyprocesslistreset_processcountprocesslist_cachedisable_tagdisable_extended_tagpsutilProcessr   	Exceptionr
   Zwarningformatdisable_io_countersdebuggidsdisable_gids_max_processesr	   _filterno_kernel_threads_max_values_list_max_valuesreset_max_values)selfr   pe r1   3/usr/lib/python3/dist-packages/glances/processes.py__init__*   sN   


zGlancesProcesses.__init__c                 C   s   dddddd| _ dS )zReset the global process countr   N)totalrunningZsleepingthreadpid_maxprocesscountr.   r1   r1   r2   r   t   s   z#GlancesProcesses.reset_processcountc                    sf   | j | jd< t| jD ] ttt fdd|| j < qtdd |D | jd< t|| jd< dS )	z?Update the global process count from the current processes listr7   c                    s   | d  u S )Nstatusr1   )vkr1   r2   <lambda>   s    z6GlancesProcesses.update_processcount.<locals>.<lambda>c                 s   s$    | ]}|d  dur|d  V  qdS )num_threadsNr1   .0ir1   r1   r2   	<genexpr>   s    
z7GlancesProcesses.update_processcount.<locals>.<genexpr>r6   r4   N)r7   r9   r   lenlistfiltersum)r.   Zplistr1   r=   r2   update_processcount|   s   z$GlancesProcesses.update_processcountc                 C      d| _ |   dS )zEnable process stats.FN)r   updater:   r1   r1   r2   enable      zGlancesProcesses.enablec                 C   
   d| _ dS )zDisable process stats.TN)r   r:   r1   r1   r2   disable      
zGlancesProcesses.disablec                 C   rJ   )zEnable extended process stats.FN)r   rK   r:   r1   r1   r2   enable_extended   rM   z GlancesProcesses.enable_extendedc                 C   rN   )zDisable extended process stats.TN)r   r:   r1   r1   r2   disable_extended   rP   z!GlancesProcesses.disable_extendedc              	   C   s`   t r.ztdd}t| W  d   W S 1 sw   Y  W dS  ttfy-   Y dS w dS )a  
        Get the maximum PID value.

        On Linux, the value is read from the `/proc/sys/kernel/pid_max` file.

        From `man 5 proc`:
        The default value for this file, 32768, results in the same range of
        PIDs as on earlier kernels. On 32-bit platfroms, 32768 is the maximum
        value for pid_max. On 64-bit systems, pid_max can be set to any value
        up to 2^22 (PID_MAX_LIMIT, approximately 4 million).

        If the file is unreadable or not available for whatever reason,
        returns None.

        Some other OSes:
        - On FreeBSD and macOS the maximum is 99999.
        - On OpenBSD >= 6.0 the maximum is 99999 (was 32766).
        - On NetBSD the maximum is 30000.

        :returns: int or None
        z/proc/sys/kernel/pid_maxrbN)r   openintreadOSErrorIOError)r.   fr1   r1   r2   r7      s   
(zGlancesProcesses.pid_maxc                 C   s   t | jd tjd d S )z5Get the current number of processes showed in the UI.   r4      )minr(   glances_processesr9   r:   r1   r1   r2   processes_count   s   z GlancesProcesses.processes_countc                 C      | j S )z5Get the maximum number of processes showed in the UI.r(   r:   r1   r1   r2   max_processes      zGlancesProcesses.max_processesc                 C   s
   || _ dS )z5Set the maximum number of processes showed in the UI.Nr`   r.   valuer1   r1   r2   ra      s   
c                 C      | j jS )z+Get the process filter (given by the user).)r)   Zfilter_inputr:   r1   r1   r2   process_filter_input      z%GlancesProcesses.process_filter_inputc                 C   re   )z.Get the process filter (current apply filter).r)   rG   r:   r1   r1   r2   process_filter   rg   zGlancesProcesses.process_filterc                 C   s   || j _dS )zSet the process filter.Nrh   rc   r1   r1   r2   ri      s   c                 C   re   )zGet the process filter key.)r)   Z
filter_keyr:   r1   r1   r2   process_filter_key   rg   z#GlancesProcesses.process_filter_keyc                 C   re   )z,Get the process regular expression compiled.)r)   Z	filter_rer:   r1   r1   r2   process_filter_re   rg   z"GlancesProcesses.process_filter_rec                 C   rN   )z&Ignore kernel threads in process list.TN)r*   r:   r1   r1   r2   disable_kernel_threads   rP   z'GlancesProcesses.disable_kernel_threadsc                 C   s   | j dks
| j dkrdS dS )zDReturn True to sort processes in reverse 'key' order, False instead.r   r   FT)sort_keyr:   r1   r1   r2   sort_reverse   s   zGlancesProcesses.sort_reversec                 C   r_   )zReturn the max values dict.r,   r:   r1   r1   r2   
max_values      zGlancesProcesses.max_valuesc                 C   s
   | j | S )z/Get the maximum values of the given stat (key).ro   )r.   keyr1   r1   r2   get_max_values   rP   zGlancesProcesses.get_max_valuesc                 C   s   || j |< dS )z0Set the maximum value for a specific stat (key).Nro   )r.   rr   rd   r1   r1   r2   set_max_values   s   zGlancesProcesses.set_max_valuesc                 C   s    i | _ | jD ]}d| j |< qdS )zReset the maximum values dict.g        N)r,   r+   )r.   r>   r1   r1   r2   r-      s   
z!GlancesProcesses.reset_max_valuesc                    s0  g _   jrdS td}g d}g d}ddg}js$|d js,|d || j	 rI||7 }j
j j  d	}nd
}fddtj|ddD _ tj jd
d_ j  d
}j D ]||r-js-i }z{td }g d}	tr|	dg7 }	tr|	dg7 }	|j|	dd}trztdd | D |d< W n tjtfy   Y n tjtfy   d|d< Y nw zt|jdd|d< t|jdd|d< W n tjtjfy   d|d< d|d< Y nw W n# tjtt fy }
 zt!"d#|
 d	|d< W Y d}
~
nd}
~
ww t!$d#d  d
|d< %| d	}dd< |d< t&d dd ' d< dv rd durd j(d j)g}z|j*d   d< d}W n ty~   |ddg d< d}Y nw |j*d < nddgddg d< d}d  |g7  < |rވd j+vrztjd d j|ddj+d < W n tjy   Y nw z%j+d   W qo ty   Y qow fd!d"|D j+d < qofd#dj D _ j,D ]  fd$dj D }|g kr- t.| qdS )%zUpdate the processes stats.NZprocess_disk)r   r   r   r   r;   r;   r@   )Zmemory_infonicepidZppidZcmdliner   r   r&   FTc                    sb   g | ]-}t r|jd  dkstr|jd  dkstr|jd  dks jr,tr,|jd jdks|jqS )r   ZidlezSystem Idle ProcessZkernel_taskr&   r   )r   infor   r   r*   r   realrB   r/   r:   r1   r2   
<listcomp>,  s(    z+GlancesProcesses.update.<locals>.<listcomp>)ZattrsZad_value)sortedbyreverserv   )Zcpu_affinityZioniceZnum_ctx_switchesZnum_fdsZnum_handlesc                 S   s   g | ]}|j qS r1   )Zswap)rB   r<   r1   r1   r2   rz   \  s    Zmemory_swapZtcp)kindZudpz Can not grab extended stats ({})extended_statsz"Grab extended stats for process {}rr   time_since_updater;   r[   r   )rv   c                    s   i | ]}| | qS r1   r1   )rB   cached)procr1   r2   
<dictcomp>  s    z+GlancesProcesses.update.<locals>.<dictcomp>c                    s   g | ]
} j |s|qS r1   )r)   Zis_filteredry   r:   r1   r2   rz     s    c                    s    g | ]}|  d ur|  qS Nr1   rA   r=   r1   r2   rz     s     )/r   r   r   r   r$   appendr'   extendr   Zfinishedsetr   resetr    Zprocess_iter
sort_statsrm   rI   r   r!   r   r   Zas_dictrH   Zmemory_mapsZNoSuchProcessKeyErrorZAccessDeniedNotImplementedErrorrE   Zconnections
ValueErrorAttributeErrorr
   errorr#   r%   rK   strupperZ
read_bytesZwrite_bytesr   r   r+   rt   max)r.   r   Zsorted_attrsZdisplayed_attrZcached_attrsZ	is_cachedfirstZextendedZtop_processr~   r0   Zio_newZio_tagZvalues_listr1   )r>   r   r.   r2   rK     s   





	




zGlancesProcesses.updatec                 C   r_   )zGet the number of processes.r8   r:   r1   r1   r2   getcount  rq   zGlancesProcesses.getcountNc                 C   r_   )zGet the processlist.)r   )r.   r{   r1   r1   r2   getlist  rq   zGlancesProcesses.getlistc                 C   r_   )zGet the current sort key.)r   r:   r1   r1   r2   rm     rb   zGlancesProcesses.sort_keyTc                 C   s(   |dkrd| _ d| _dS || _ || _dS )zSet the current sort key.r   Tr   N)r   r   )r.   rr   r   r1   r1   r2   r     s
   

zGlancesProcesses.set_sort_key   c                 C   s@   |t  ks
J dt|}td| |  ||S )zKill process with pidzGlances can kill itself...zSend kill signal to process: {})	osgetpidr    r!   r
   r%   r#   killwait)r.   rv   Ztimeoutr/   r1   r1   r2   r     s
   

zGlancesProcesses.kill)r   r   )T)r   ) __name__
__module____qualname____doc__r3   r   rI   rL   rO   rQ   rR   propertyr7   r^   ra   setterrf   ri   rj   rk   rl   rn   rp   rs   rt   r-   rK   r   r   rm   r   r   r1   r1   r1   r2   r   '   sT    
J
 








 0


	r   c                 C   s   | du r	t d S | S )z Manage None value in dict value.Ninf)float)rd   r1   r1   r2   weighted  s   r   r   r   c                 C   s0   | | d | | d  | | d  | | d  S )z4Specific case for io_counters
    Sum of io_r + io_wr   rZ   r[   r   r1   processr{   sortedby_secondaryr1   r1   r2   _sort_io_counters  s   0r   r   c                 C   s   | | d | | d  S )a   Specific case for cpu_times
    Patch for "Sorting by process time works not as expected #1321"
    By default PsUtil only takes user time into account
    see (https://github.com/giampaolo/psutil/issues/1339)
    The following implementation takes user and system time into accountr   r[   r1   r   r1   r1   r2   _sort_cpu_times  s   r   r   c                 C   s$   d}| dkr
t }|S | dkrt}|S )z1Return a sort lambda function for the sortedbykeyNr   r   )r   r   )r{   r   retr1   r1   r2   _sort_lambda  s   r   Tc              	      s    du r
du r
| S t  d}|dur4z
| j||d W | S  ty3   | jfdd|d Y | S w z| j fdd|d W | S  ttfyX   | jdd dd Y | S w )	z\Return the stats (dict) sorted by (sortedby).

    Reverse the sort if reverse is True.
    Nr{   r   )rr   r|   c                    s   t | d t |   fS )Nr   r   r   )r   r1   r2   r?        
 
zsort_stats.<locals>.<lambda>c                    s   t |   t |  fS r   r   r   r   r1   r2   r?     r   c                 S   s   | d d ur
| d S dS )Nr   ~r1   r   r1   r1   r2   r?     s    F)r   sortr"   r   	TypeError)Zstatsr{   r   r|   Zsort_lambdar1   r   r2   r     s4   
r   )r   r   )r   r   r   )r   r   T)r   Zglances.compatr   Zglances.globalsr   r   r   r   Zglances.timerr   r   Zglances.filterr	   Zglances.loggerr
   r    Zsort_processes_key_listobjectr   r   r   r   r   r   r]   r1   r1   r1   r2   <module>   s6      .
	



'