o
    va                     @   s   d Z ddlZddlZddlZddlmZ ddlmZmZm	Z	m
Z
mZmZ ddlmZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZmZ ddiZdddddddddddddZG dd deZdS )z2
I am your father...

...for all Glances plugins.
    N)
itemgetter)iterkeys
itervalueslistkeysmapmean	nativestr)GlancesActions)GlancesHistory)logger)glances_events)glances_thresholds)CounterTimerpercent%floatint)r   percentsnumberZnumbersr   Zintsr   ZfloatssecondZsecondsZbytebytesc                   @   s  e Zd ZdZdddi dfddZdd Zdd Zd	d
 Zdd Zdd Z	dd Z
dddZdddZdd Zdd Zdd Zdd Zdd Zdd  Zdd"d#Zdd$d%Zdd&d'Zdd(d)Zdd+d,Zed-d. Zejd/d. Zed0d1 Zd2d3 Zejd4d1 Zd5d6 Zdd8d9Zd:d; Zd<d= Z d>d? Z!d@dA Z"dBdC Z#dDdE Z$dFdG Z%dHdI Z&ddJdKZ'ddLdMZ(dNdO Z)edPdQ Z*e*jdRdQ Z*dSdT Z+dUdV Z,dWdX Z-dYdZ Z.dd[d\Z/d]d^ Z0dd`daZ1	!	!	b	c	7	_		7ddddeZ2dfdg Z3dhdi Z4	!	!	b	_	ddjdkZ5ddldmZ6ddndoZ7ddpdqZ8ddrdsZ9d_dg fdtduZ:ddvdwZ;ddxdyZ<dzd{ Z=dd|d}Z>dd~dZ?		7	7dddZ@dd ZA		_dddZBedd ZCeCjdd ZC	7	dddZDdddZEdd ZFdd ZGeHeFZFeHeGZGdS )GlancesPluginzMain class for Glances plugin.Nc                 C   s   | j jdtd d }| j j|d | _|| _d| _d| _d| _|| _	| 
 | _t | _|durDtd| j|  | j|d t|d	| _t | _d
| _g | _td| _|| _|| _d| _|   dS )a
  Init the plugin of plugins class.

        All Glances' plugins should inherit from this class. Most of the
        methods are already implemented in the father classes.

        Your plugin should return a dict or a list of dicts (stored in the
        self.stats). As an example, you can have a look on the mem plugin
        (for dict) or network (for list of dicts).

        A plugin should implement:
        - the __init__ constructor: define the self.display_curse
        - the reset method: to set your self.stats variable to {} or []
        - the update method: where your self.stats variable is set
        and optionnaly:
        - the get_key method: set the key of the dict (only for list of dict)
        - the update_view method: only if you need to trick your output
        - the msg_curse: define the curse (UI) message (if display_curse is True)

        :args: args parameters
        :items_history_list: list of items to store in the history
        :stats_init_value: Default value for a stats item
        glances_Zglances   NleftZlocalzLoad section {} in {})config)argsFr   )	__class__
__module__findlenplugin_namer   _align_input_method_short_system_nameitems_history_listinit_stats_historystats_historydict_limitsr   debugformatZconfig_file_pathsload_limitsr	   actionsviews	hide_zerohide_zero_fieldsr   refresh_timerfields_descriptionstats_init_valuestatsreset)selfr   r   r&   r4   r3   pos r9   @/usr/lib/python3/dist-packages/glances/plugins/glances_plugin.py__init__?   s.   

zGlancesPlugin.__init__c                 C      | j S )zReturn the raw stats.r5   r7   r9   r9   r:   __repr__      zGlancesPlugin.__repr__c                 C   s
   t | jS )z Return the human-readable stats.)strr5   r>   r9   r9   r:   __str__      
zGlancesPlugin.__str__c                 C   s   t  | jS )z Return a copy of the init value.)copyr4   r>   r9   r9   r:   get_init_value      zGlancesPlugin.get_init_valuec                 C   s   |   | _dS )zWReset the stats.

        This method should be overwrited by childs' classes.
        N)rE   r5   r>   r9   r9   r:   r6      s   zGlancesPlugin.resetc                 C   s   t d| j dS )z$Just log an event when Glances exit.zStop the {} pluginN)r   r+   r,   r"   r>   r9   r9   r:   exit   s   zGlancesPlugin.exitc                 C   s   dS )zReturn the key of the list.Nr9   r>   r9   r9   r:   get_key   s   zGlancesPlugin.get_keyc                 C   sP   |s| j }zt| jd| }W |du S  ty'   t| jd| d}Y |du S w )z!Return true if plugin is enabled.Zdisable_Zenable_TF)r"   getattrr   AttributeError)r7   r"   dr9   r9   r:   
is_enabled   s   zGlancesPlugin.is_enabledc                 C   s   | j |d S )z"Return true if plugin is disabled.r"   )rL   )r7   r"   r9   r9   r:   is_disabled   s   zGlancesPlugin.is_disabledc                 C   s.   zt |W S  ty   t j|dd Y S w )z^Return the object 'd' in a JSON format.

        Manage the issue #815 for Windows OS
        F)Zensure_ascii)jsondumpsUnicodeDecodeError)r7   rK   r9   r9   r:   _json_dumps   s
   zGlancesPlugin._json_dumpsc                 C   s    | j d uo| j j o|  d uS N)r   Zdisable_historyget_items_history_listr>   r9   r9   r:   history_enable   s
   

zGlancesPlugin.history_enablec                 C   s4   |   rdd |  D }td| j| t S )z2Init the stats history (dict of GlancesAttribute).c                 S      g | ]}|d  qS namer9   .0ar9   r9   r:   
<listcomp>       z4GlancesPlugin.init_stats_history.<locals>.<listcomp>z1Stats history activated for plugin {} (items: {}))rU   rT   r   r+   r,   r"   r
   )r7   Z	init_listr9   r9   r:   r'      s   z GlancesPlugin.init_stats_historyc                 C   s@   |   rdd |  D }td| j| | j  dS dS )z3Reset the stats history (dict of GlancesAttribute).c                 S   rV   rW   r9   rY   r9   r9   r:   r\      r]   z5GlancesPlugin.reset_stats_history.<locals>.<listcomp>z'Reset history for plugin {} (items: {})N)rU   rT   r   r+   r,   r"   r(   r6   )r7   Z
reset_listr9   r9   r:   reset_stats_history   s
   z!GlancesPlugin.reset_stats_historyc                 C   s   |   du r	d}n|   }|  rc|  re|  D ]M}t|  trI|  D ]!}| jjt|| d t|d  ||d  |d | j	d d q&q| jjt|d |  |d  |d | j	d d qdS dS dS )zUpdate stats history.N _rX   descriptionhistory_size)ra   Zhistory_max_size)
rH   
get_exportrU   rT   
isinstancelistr(   addr   r*   )r7   Z	item_nameiZl_exportr9   r9   r:   update_stats_history   s*   
	z"GlancesPlugin.update_stats_historyc                 C   r<   )zReturn the items history list.)r&   r>   r9   r9   r:   rT      r@   z$GlancesPlugin.get_items_history_listr   c                 C   .   | j j|d}|du r|S ||v r|| S dS )zReturn the history (RAW format).

        - the stats history (dict of list) if item is None
        - the stats history for the given item (list) instead
        - None if item did not exist in the history
        nbN)r(   getr7   itemrk   sr9   r9   r:   get_raw_history   s   zGlancesPlugin.get_raw_historyc                 C   ri   )a  Return the history (JSON format).

        - the stats history (dict of list) if item is None
        - the stats history for the given item (list) instead
        - None if item did not exist in the history
        Limit to lasts nb items (all if nb=0)
        rj   N)r(   Zget_jsonrm   r9   r9   r:   get_json_history  s   zGlancesPlugin.get_json_historyc                 C   s   | j |dS )z*Return the stats history object to export.rn   )rp   r7   rn   r9   r9   r:   get_export_history  rF   z GlancesPlugin.get_export_historyc              
   C   s   | j |d}|du r| |S t|tr;z
| ||| iW S  ty: } ztd|| W Y d}~dS d}~ww t|trlz| |t	t
||iW S  ttfyk } ztd|| W Y d}~dS d}~ww dS )z'Return the stats history (JSON format).rj   NzCannot get item history {} ({}))rq   rR   rd   r)   KeyErrorr   errorr,   re   r   r   
ValueError)r7   rn   rk   ro   er9   r9   r:   get_stats_history  s(   


zGlancesPlugin.get_stats_history   c                 C   sL   | j ||d}|du st||k rdS dd |D }|d t|dd  S )zGet the trend regarding to the last nb values.

        The trend is the diff between the mean of the last nb values
        and the current one.
        )rn   rk   Nc                 S   rV   r   r9   )rZ   vr9   r9   r:   r\   7  r]   z+GlancesPlugin.get_trend.<locals>.<listcomp>)rp   r!   r   )r7   rn   rk   Zraw_historyZlast_nbr9   r9   r:   	get_trend.  s
   zGlancesPlugin.get_trendc                 C   r<   )zGet the input method.r$   r>   r9   r9   r:   input_method:     zGlancesPlugin.input_methodc                 C   
   || _ dS )zSet the input method.

        * local: system local grab (psutil or direct access)
        * snmp: Client server mode via SNMP
        * glances: Client server mode via Glances API
        Nr   )r7   r   r9   r9   r:   r   ?  s   
c                 C   r<   )z&Get the short detected OS name (SNMP).r%   r>   r9   r9   r:   short_system_nameI  r   zGlancesPlugin.short_system_namec                    sN      ztj fdddW S  ty&   tj fddd Y S w )z5Get the stats sorted by an alias (if present) or key.c              
      ,   t tdd td|   p|   S )Nc                 S   s   |   rt| S |  S rS   )isdigitr   lowerpartr9   r9   r:   <lambda>S      >GlancesPlugin.sorted_stats.<locals>.<lambda>.<locals>.<lambda>	(\d+|\D+)tupler   resplit	has_aliasstatkeyr7   r9   r:   r   R      z,GlancesPlugin.sorted_stats.<locals>.<lambda>)r   c              
      r   )Nc                 S      |   S rS   )r   r   r9   r9   r:   r   Y  s    r   r   r   r   r   r9   r:   r   X  r   )rH   sortedr5   	TypeErrorr>   r9   r   r:   sorted_statsN  s   zGlancesPlugin.sorted_statsc                 C   r   )z&Set the short detected OS name (SNMP).Nr   )r7   
short_namer9   r9   r:   r   ]     
c                 C   r   )zSet the stats to input_stats.Nr=   )r7   Zinput_statsr9   r9   r:   	set_statsb  rC   zGlancesPlugin.set_statsFc                 C   s^  |pi }ddl m} || jj| jj| jj| jjd}i }|r|ddt| }t	|dkr\|D ]*}t
|d t|d rYt|d |t
|d t
|d t|d d  < q/|S d}|D ]4}i }	d}
t
|D ]}|| d t| }||v r|
du r|| }
qj|| |	|< qj|	r|	||
< |d7 }q`|S |t| }t
|D ]
}|||  ||< q|S )zeUpdate stats using SNMP.

        If bulk=True, use a bulk request instead of a get request.
        r   )GlancesSNMPClient)ZhostZportversionZ	community
   r   N.)Zglances.snmpr   r   ZclientZ	snmp_portZsnmp_versionZsnmp_communityZgetbulk_by_oidr   r!   r   
startswithr   rA   Z
get_by_oid)r7   ZbulkZsnmp_oidr   Z
clientsnmpretZ
snmpresultrn   indexZ
item_statsZitem_keyr   Zoidr9   r9   r:   get_stats_snmpf  sP   


	zGlancesPlugin.get_stats_snmpc                 C   r<   )zReturn the stats object.r=   r>   r9   r9   r:   get_raw  r@   zGlancesPlugin.get_rawc                 C   r   )z"Return the stats object to export.r   r>   r9   r9   r:   rc        zGlancesPlugin.get_exportc                 C   s   |  | jS )z'Return the stats object in JSON format.)rR   r5   r>   r9   r9   r:   	get_stats  rF   zGlancesPlugin.get_statsc              
   C   s   t | jtr.z| || j| iW S  ty- } ztd|| W Y d}~dS d}~ww t | jtrcz| |tt	t
|| jiW S  ttfyb } ztd|| W Y d}~dS d}~ww dS )zReturn the stats object for a specific item in JSON format.

        Stats should be a list of dict (processlist, network...)
        zCannot get item {} ({})N)rd   r5   r)   rR   ru   r   rv   r,   re   r   r   rw   )r7   rn   rx   r9   r9   r:   get_stats_item  s"    zGlancesPlugin.get_stats_itemc              
      s   t | jtsdS t ts rtz|  fdd| jD iW S  ttfyE } zt	d
 | W Y d}~dS d}~ww )zReturn the stats object for a specific item=value in JSON format.

        Stats should be a list of dict (processlist, network...)
        Nc                    s   g | ]
}|  kr|qS r9   r9   rZ   rg   rn   valuer9   r:   r\     s    z1GlancesPlugin.get_stats_value.<locals>.<listcomp>z"Cannot get item({})=value({}) ({}))rd   r5   re   r   r   rR   ru   rw   r   rv   r,   )r7   rn   r   rx   r9   r   r:   get_stats_value  s   "zGlancesPlugin.get_stats_valuec                    sx  j sdS t tro duro duro D ]P t fddjD rHjD ]}j    | d j    | d< q-jD ] }j    | d o_ | dkj    | d< qKqd	S t tr durt	 D ]7}tfddjD rjD ]}j| d j| d< qjD ]}jd oj| dkj| d< qqd	S )
a  If the self.hide_zero is set then update the hidden field of the view
        It will check if all fields values are already be different from 0
        In this case, the hidden field is set to True

        Note: This function should be called by plugin (in the update_views method)

        Example (for network plugin):
        __Init__
            self.hide_zero_fields = ['rx', 'tx']
        Update views
            ...
            self.update_views_hidden()
        FNc                    s   g | ]} | qS r9   r9   rZ   f)rg   r9   r:   r\     r]   z5GlancesPlugin.update_views_hidden.<locals>.<listcomp>hidden_zeror   c                    s   g | ]}   | qS r9   r   r   r>   r9   r:   r\     r   T)
r0   rd   r   re   rH   anyr1   r/   r)   r   )r7   r   r   r9   )rg   r7   r:   update_views_hidden  sD   



$

$z!GlancesPlugin.update_views_hiddenc                 C   sR  i }t |  trm|  durm|  durm|  D ]R}i |||   < t|D ]C}ddddd||   | jv r\|| j||    v r\d| j||    | v r\| j||    | d ndd}||||    |< q'qn6t |  tr|  durt|  D ]"}ddddd|| jv rd| j| v r| j| d ndd}|||< q|| _| jS )a  Update the stats views.

        The V of MVC
        A dict of dict with the needed information to display the stats.
        Example for the stat xxx:
        'xxx': {'decoration': 'DEFAULT',  >>> The decoration of the stats
                'optional': False,        >>> Is the stat optional
                'additional': False,      >>> Is the stat provide additional information
                'splittable': False,      >>> Is the stat can be cut (like process lon name)
                'hidden': False,          >>> Is the stats should be hidden in the UI
                '_zero': True}            >>> For internal purpose only
        NDEFAULTFZzeror   T)
decorationoptional
additional
splittabler   r   )rd   r   re   rH   r   r/   r)   )r7   r   rg   r   r   r9   r9   r:   update_views  s>   

^(
zGlancesPlugin.update_viewsc                 C   r   )zSet the views to input_views.Nr/   )r7   Zinput_viewsr9   r9   r:   	set_views)  rC   zGlancesPlugin.set_viewsc                 C   sR   |du r| j }n| j | }|du r|S |du r|| S ||| v r'|| | S dS )aC  Return the views object.

        If key is None, return all the view for the current plugin
        else if option is None return the view for the specific key (all option)
        else return the view fo the specific key/option

        Specify item if the stats are stored in a dict of dict (ex: NETWORK, FS...)
        Nr   r   )r7   rn   r   optionZ
item_viewsr9   r9   r:   	get_views-  s   	
zGlancesPlugin.get_viewsc                 C   s   |  | |||S )zReturn the views (in JSON).)rR   r   )r7   rn   r   r   r9   r9   r:   get_json_viewsF  s   zGlancesPlugin.get_json_viewsc              	   C   s   d| j d< t|dsdS |dr(|jdddd| j d< tdd| j d  || jrp|| jD ];\}}d	| j|g}z|| j|| j |< W n t
yb   || j|d	| j |< Y nw td
|| j |  q4dS )z6Load limits from the configuration file, if it exists.ip  rb   has_sectionFglobal)defaultzLoad configuration key: {} = {}r`   ,zLoad limit: {} = {}T)r*   hasattrr   Zget_float_valuer   r+   r,   r"   itemsjoinrw   Z	get_valuer   )r7   r   levelr`   limitr9   r9   r:   r-   J  s    


zGlancesPlugin.load_limitsc                 C   r<   )Return the limits object.r*   r>   r9   r9   r:   limitse  r   zGlancesPlugin.limitsc                 C   r   )zSet the limits to input_limits.Nr   )r7   Zinput_limitsr9   r9   r:   r   j  r   c                 C   s   |  d| dS )zSet the plugin refresh raterefreshN)
set_limitsr7   r   r9   r9   r:   set_refresho  s   zGlancesPlugin.set_refreshc                 C   s    | j dd}|du r| jj}|S )Return the plugin refresh timer   rr   N)
get_limitsr   time)r7   r   r9   r9   r:   get_refreshs  s   zGlancesPlugin.get_refreshc                 C   r   )r   )r   r>   r9   r9   r:   get_refresh_timez  r   zGlancesPlugin.get_refresh_timec                 C   s   || j d| j|< dS )zSet the limits object.{}_{}N)r*   r,   r"   )r7   rn   r   r9   r9   r:   r   ~  s   zGlancesPlugin.set_limitsc                 C   s&   |du r| j S | j d| j|dS )r   Nr   )r*   rl   r,   r"   rs   r9   r9   r:   r     s   zGlancesPlugin.get_limitsc                 C   r<   )zReturn stats for the action.

        By default return all the stats.
        Can be overwrite by plugins implementation.
        For example, Docker will return self.stats['containers']
        r=   r>   r9   r9   r:   get_stats_action  s   zGlancesPlugin.get_stats_actionr_   c                 C   s   | j }|dkr|d| 7 }|S )z-"Return the stat name with an optional headerr_   r`   rM   )r7   headerr   r9   r9   r:   get_stat_name  s   zGlancesPlugin.get_stat_named   Tc	                 C   s  |s|dkrdS z|d | }	W n t y   Y dS  ty#   Y dS w | j|d}
|r.dnd}z,|	| jd|
dkr=d	}n|	| jd
|
dkrId}n|	| jd|
dkrUd}n||k r[d}W n
 tyf   Y dS w d}| j|
|dr{d}t||
 |	 | 	|
| | 
|
| || || S )a  Return the alert status relative to a current value.

        Use this function for minor stats.

        If current < CAREFUL of max then alert = OK
        If current > CAREFUL of max then alert = CAREFUL
        If current > WARNING of max then alert = WARNING
        If current > CRITICAL of max then alert = CRITICAL

        If highlight=True than 0.0 is highlighted

        If defined 'header' is added between the plugin name and the status.
        Only useful for stats with several alert status.

        If defined, 'action_key' define the key for the actions.
        By default, the action_key is equal to the header.

        If log=True than add log if necessary
        elif log=False than do not log
        elif log=None than apply the config given in the conf file
        r   r   r   r   MAXZOKZcritical	stat_nameZCRITICALZwarningZWARNINGZcarefulZCAREFULr_   )r   default_actionZ_LOG)ZeroDivisionErrorr   r   	get_limitru   get_limit_logr   rf   uppermanage_thresholdmanage_actionr   )r7   currentminimummaximumZhighlight_zeroZis_maxr   
action_keylogr   r   r   Zlog_strr9   r9   r:   	get_alert  s>   zGlancesPlugin.get_alertc                 C   s   t || dS )z*Manage the threshold for the current stat.N)r   rf   )r7   r   triggerr9   r9   r:   r     s   zGlancesPlugin.manage_thresholdc           	      C   s   z| j ||d\}}W n ty   | j|| Y dS w |du r#|}t|  tr@i }|  D ]}||   |kr>|} nq0n|  }| jj|||||d dS )z'Manage the action for the current stat.r   N)mustache_dict)	get_limit_actionru   r.   setrd   r   re   rH   run)	r7   r   r   r   r   Zcommandrepeatr   rn   r9   r9   r:   r     s(   
zGlancesPlugin.manage_actionc                 C   s   | j |||||ddS )zGet the alert log.T)r   r   r   r   r   r   )r   )r7   r   r   r   r   r   r9   r9   r:   get_alert_log  s   zGlancesPlugin.get_alert_logc                 C   s.   |dkr| j d | | jv S |d | | jv S )z@Return true if the criticity limit exist for the given stat_namer_   r`   )r"   r*   )r7   	criticityr   r9   r9   r:   is_limit  s   zGlancesPlugin.is_limitc                 C   sB   z| j |d |  }W |S  ty    | j | jd |  }Y |S w )z%Return the limit value for the alert.r`   )r*   ru   r"   )r7   r   r   r   r9   r9   r:   r   &  s   	zGlancesPlugin.get_limitc                 C   s   |d | d df|d | d df| j d | d df| j d | d dfg}|D ]}|d | jv r@| j|d  |d f  S q*t)zxReturn the tuple (action, repeat) for the alert.

        - action is a command line
        - repeat is a bool
        r`   Z_actionFZ_action_repeatTr   r   r"   r*   ru   )r7   r   r   r   rr9   r9   r:   r   6  s   	zGlancesPlugin.get_limit_actionc                 C   sf   z	| j |d  }W n! ty*   z
| j | jd  }W n ty'   | Y  Y S w Y nw |d  dkS )z!Return the log tag for the alert.Z_logr   true)r*   ru   r"   r   )r7   r   r   Zlog_tagr9   r9   r:   r   J  s   
zGlancesPlugin.get_limit_logc                 C   sN   |du r| j }|dkr|d | }z
| j|d |  W S  ty&   | Y S w )z~Return the configuration (header_) value for the current plugin.

        ...or the one given by the plugin_name var.
        Nr_   r`   r   )r7   r   r   r"   r   r9   r9   r:   get_conf_value\  s   zGlancesPlugin.get_conf_valuec                    s@   | j d|dg krdS tdd  fdd| j d|dD D S )a-  Return True if the value is in the show configuration list.
        If the show value is empty, return True (show by default)

        The show configuration list is defined in the glances.conf file.
        It is a comma separed list of regexp.
        Example for diskio:
        show=sda.*
        Zshowr   Tc                 s       | ]}|V  qd S rS   r9   rZ   jr9   r9   r:   	<genexpr>{      z(GlancesPlugin.is_show.<locals>.<genexpr>c                       g | ]}t | qS r9   r   matchr   r   r9   r:   r\   {  r   z)GlancesPlugin.is_show.<locals>.<listcomp>)r   r   r7   r   r   r9   r  r:   is_shown  s   
*zGlancesPlugin.is_showc                    s*   t dd  fdd| jd|dD D S )zReturn True if the value is in the hide configuration list.

        The hide configuration list is defined in the glances.conf file.
        It is a comma separed list of regexp.
        Example for diskio:
        hide=sda2,sda5,loop.*
        c                 s   r   rS   r9   r   r9   r9   r:   r     r   z(GlancesPlugin.is_hide.<locals>.<genexpr>c                    r   r9   r   r   r  r9   r:   r\     r   z)GlancesPlugin.is_hide.<locals>.<listcomp>Zhider   )r   r   r  r9   r  r:   is_hide}  s   *	zGlancesPlugin.is_hidec              	   C   s@   z| j | jd |  d d  d W S  ttfy   Y dS w )zBReturn the alias name for the relative header or None if nonexist.r`   aliasr   N)r*   r"   r   ru   
IndexError)r7   r   r9   r9   r:   r     s
   &zGlancesPlugin.has_aliasc                 C   s   |  t| jgS )z8Return default string to display in the curse interface.)curse_add_linerA   r5   )r7   r   	max_widthr9   r9   r:   	msg_curse  s   zGlancesPlugin.msg_cursec                 C   s\   d}t | dr
| j}t | dr| j}|dur#|| j||d|d}|S || ||d}|S )aI  Return a dict with all the information needed to display the stat.

        key     | description
        ----------------------------
        display | Display the stat (True or False)
        msgdict | Message to display (list of dict [{ 'msg': msg, 'decoration': decoration } ... ])
        align   | Message position
        Fdisplay_cursealignN)r  )ZdisplayZmsgdictr  )r   r
  r#   r	  )r7   r   r  r
  Zalign_curser   r9   r9   r:   get_stats_display  s    	

zGlancesPlugin.get_stats_displayr   c                 C   s   |||||dS )ag  Return a dict with.

        Where:
            msg: string
            decoration:
                DEFAULT: no decoration
                UNDERLINE: underline
                BOLD: bold
                TITLE: for stat title
                PROCESS: for process name
                STATUS: for process status
                NICE: for process niceness
                CPU_TIME: for process cpu time
                OK: Value is OK and non logged
                OK_LOG: Value is OK and logged
                CAREFUL: Value is CAREFUL and non logged
                CAREFUL_LOG: Value is CAREFUL and logged
                WARNING: Value is WARINING and non logged
                WARNING_LOG: Value is WARINING and logged
                CRITICAL: Value is CRITICAL and non logged
                CRITICAL_LOG: Value is CRITICAL and logged
            optional: True if the stat is optional (display only if space is available)
            additional: True if the stat is additional (display only if space is available after optional)
            spittable: Line can be splitted to fit on the screen (default is not)
        )msgr   r   r   r   r9   )r7   r  r   r   r   r   r9   r9   r:   r    s   zGlancesPlugin.curse_add_linec                 C   s
   |  dS )zGo to a new line.
)r  r>   r9   r9   r:   curse_new_line  rC   zGlancesPlugin.curse_new_linec                 C   sD  || j vrg S || jv rd| j| v r| j| d }n|}|| jv r<d| j| v r<| j| d tv r<t| j| d  }nd}|| jv r]d| j| v r]| j| d tv r]t| j| d  }nd}|| jv rd| j| v r| j| d du r| j | | j d  }	n| j | }	|du r|d	| | }
|dkrd
|	|| }ngd| j| v rd| jt|	| j| d d|| }nKdt|	|| }n@|dj||d d | }
|dkrd|	|| }n&d| j| v rd| jt|	| j| d d|| }n
dt|	|| }| j|dd}| j|dd}| j|
|d| j|||dgS )a  Return a list of dict messages with the 'key: value' result

          <=== width ===>
        __key     : 80.5%__
        | |       | |    |_ trailer
        | |       | |_ self.stats[key]
        | |       |_ separator
        | |_ key
        |_ trailer

        Instead of:
            msg = '  {:8}'.format('idle:')
            ret.append(self.curse_add_line(msg, optional=self.get_views(key='idle', option='optional')))
            msg = '{:5.1f}%'.format(self.stats['idle'])
            ret.append(self.curse_add_line(msg, optional=self.get_views(key='idle', option='optional')))

        Use:
            ret.extend(self.curse_add_stat('idle', width=15, header='  '))

        r   Zunitr_   r   ZrateTZtime_since_updateNz{}z{:.1f}{}
min_symbolz{}{})r  z
{:{width}}   )widthz	{:5.1f}{}z{:>5}{}r   )r   r   r   )r   )r   r   )	r5   r3   fields_unit_shortfields_unit_typer,   	auto_unitr   r   r  )r7   r   r  r   Z	separatorZtrailerZkey_nameZ
unit_shortZ	unit_typer   Zmsg_itemZ	msg_valuer   r   r9   r9   r:   curse_add_stat  st   





zGlancesPlugin.curse_add_statc                 C   r<   )zGet the curse align.r#   r>   r9   r9   r:   r  -  r   zGlancesPlugin.alignc                 C   r   )zBSet the curse align.

        value: left, right, bottom.
        Nr  r   r9   r9   r:   r  2  s   
Kc           	   	   C   s   d}||v r|| |d }ddddddd	d
d}t|D ]<}t|||  }|dkrZd}|dk r5d}n|dk r;d}|rJ|dv rDd}ntd|}n|dv rPd}dj|||d  S qd|S )aw  Make a nice human-readable string out of number.

        Number of decimal places increases as quantity approaches 1.
        CASE: 613421788        RESULT:       585M low_precision:       585M
        CASE: 5307033647       RESULT:      4.94G low_precision:       4.9G
        CASE: 44968414685      RESULT:      41.9G low_precision:      41.9G
        CASE: 838471403472     RESULT:       781G low_precision:       781G
        CASE: 9683209690677    RESULT:      8.81T low_precision:       8.8T
        CASE: 1073741824       RESULT:      1024M low_precision:      1024M
        CASE: 1181116006       RESULT:      1.10G low_precision:       1.1G

        :low_precision: returns less decimal places potentially (default is False)
                        sacrificing precision for more readability.
        :min_symbol: Do not approache if number < min_symbol (default is K)
        )r  MGTPEZYNl               l            l            l           l        i   @i   i   )r  r  r  r  r  r  r  r  r   r   r      r   ZMKr  z{:.{decimal}f}{symbol})Zdecimalsymbolz{!s})r   reversedr   minr,   )	r7   r   Zlow_precisionr  symbolsprefixr!  r   Zdecimal_precisionr9   r9   r:   r  :  s>   

zGlancesPlugin.auto_unitr   c                 C   s6   d}|du r
d}|S ||krd}|S || k rd}|S )z[Return the trend message.

        Do not take into account if trend < significant
        -N /\r9   )r7   ZtrendZsignificantr   r9   r9   r:   	trend_msgn  s   
zGlancesPlugin.trend_msgc                        fdd}|S )zCheck decorator for update method.
        It checks:
        - if the plugin is enabled.
        - if the refresh_timer is finished
        c                    s\   |   r)| j s| j| jkr) | g|R i |}| j|   | j  |S | j}|S rS   )rL   r2   Zfinishedr5   rE   r   r   r6   )r7   r   kwr   fctr9   r:   wrapper  s   
z/GlancesPlugin._check_decorator.<locals>.wrapperr9   r.  r/  r9   r-  r:   _check_decorator|  s   zGlancesPlugin._check_decoratorc                    r+  )z+Log (DEBUG) the result of the function fct.c                     sV   t  } | i |}| }td| d jj| d jjtdd   j||f  |S )Nz %s %s %s return %s in %s secondsr   r   )r   rl   r   r+   r   __name__r   r!   )r   r,  Zcounterr   Zdurationr-  r9   r:   r/    s   
z4GlancesPlugin._log_result_decorator.<locals>.wrapperr9   r0  r9   r-  r:   _log_result_decorator  s   
z#GlancesPlugin._log_result_decoratorrS   )Nr   )rz   )FN)NNN)r_   )r   r   r   TFr_   NF)r   r   r   r_   N)F)NN)r   FFF)Nr_   r_   r_   )Fr  r{   )Ir2  r   __qualname____doc__r;   r?   rB   rE   r6   rG   rH   rL   rN   rR   rU   r'   r^   rh   rT   rp   rq   rt   ry   r~   propertyr   setterr   r   r   r   r   rc   r   r   r   r   r   r   r   r   r-   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r   r	  r  r  r  r  r  r  r*  r1  r3  staticmethodr9   r9   r9   r:   r   <   s    
L










	


7+-





	
N%







	

"
W



4r   )r5  r   rO   rD   operatorr   Zglances.compatr   r   r   r   r   r   Zglances.actionsr	   Zglances.historyr
   Zglances.loggerr   Zglances.eventsr   Zglances.thresholdsr   Zglances.timerr   r   r  r  objectr   r9   r9   r9   r:   <module>   s8    