o
    vad                     @   sT   d Z ddlZddlmZ ddlmZ ddlmZ ddlZddlZG dd deZ	dS )zCouchDB interface class.    N)datetime)logger)GlancesExportc                       s:   e Zd ZdZd fdd	Zdd Zdd Zd	d
 Z  ZS )Exportz-This class manages the CouchDB export module.Nc                    s^   t t| j||d d| _d| _d| _| jdg dddgd| _| js(t	d | 
 | _dS )	zInit the CouchDB export IF.)configargsNcouchdb)hostportdbuserpassword)Zmandatoriesoptions   )superr   __init__r   r   r   Z	load_confexport_enablesysexitinitclient)selfr   r   	__class__ A/usr/lib/python3/dist-packages/glances/exports/glances_couchdb.pyr   $   s   
zExport.__init__c              
   C   s   | j sdS | jdu rd| j| j}nd| j| j| j| j}zt|}W n  tyF } zt	
d||f  td W Y d}~nd}~ww t	d|  z|| j  W n tyn } z|| j W Y d}~|S d}~ww t	d| j  |S )z*Init the connection to the CouchDB server.Nzhttp://{}:{}/zhttp://{}:{}@{}:{}/z(Cannot connect to CouchDB server %s (%s)r   z"Connected to the CouchDB server %szThere is already a %s database)r   r   formatr	   r
   r   r   ZServer	Exceptionr   Zcriticalr   r   infor   Zcreate)r   Z
server_uriser   r   r   r   9   s8   
zExport.initc                 C   s   | j | j S )z"Return the CouchDB database object)r   r   )r   r   r   r   databaseZ   s   zExport.databasec              
   C   s   t d| tt||}||d< tj t	
 |d< z| j| j | W dS  tyG } zt d|| W Y d}~dS d}~ww )z'Write the points to the CouchDB server.zExport {} stats to CouchDBtypetimez&Cannot export {} stats to CouchDB ({})N)r   debugr   dictzipr   mappingZDateTimeFieldZ_to_jsonr   Znowr   r   Zsaver   error)r   namecolumnsZpointsdatar    r   r   r   export^   s    zExport.export)NN)	__name__
__module____qualname____doc__r   r   r!   r,   __classcell__r   r   r   r   r       s    !r   )
r0   r   r   Zglances.loggerr   Zglances.exports.glances_exportr   r   Zcouchdb.mappingr   r   r   r   r   <module>   s   