o
    -7_<e                     @   s|   d Z ddlZddlZddlZddlZddlZddlmZ ddlm	Z	 ddl
mZ e ZG dd deZG dd	 d	eZdS )
z Python client for InfluxDB v0.8.    N)xrange)urlparse)chunked_jsonc                       s"   e Zd ZdZd fdd	Z  ZS )InfluxDBClientErrorz+Raised when an error occurs in the request.c                    s(   t t| d|| || _|| _dS )z*Initialize an InfluxDBClientError handler.z{0}: {1}N)superr   __init__formatcontentcode)selfr
   r   	__class__ </usr/lib/python3/dist-packages/influxdb/influxdb08/client.pyr      s
   


zInfluxDBClientError.__init__)r   )__name__
__module____qualname____doc__r   __classcell__r   r   r   r   r      s    r   c                   @   s  e Zd ZdZ											d^d	d
Zedd Zdd Zdd Zdd Z			d_ddZ
dd Zd`ddZd`ddZdd Zd d! Zd"d# Zd$d% Zd&d' Zdad(d)Zdad*d+Zd,d- Zd.d/ Zd0d1 Zd2d3 Zd4d5 Zd6d7 Zd8d9 Zd:d; Zd<d= Zd>d? Zd@dA ZdBdC Z dDdE Z!dFdG Z"dHdI Z#dJdK Z$dLdM Z%dNdO Z&dPdQ Z'dbdRdSZ(dTdU Z)dcdVdWZ*dXdY Z+dZd[ Z,d\d] Z-dS )dInfluxDBClientap  Define the standard InfluxDBClient for influxdb v0.8.

    The ``InfluxDBClient`` object holds information necessary to connect
    to InfluxDB. Requests can be made to InfluxDB directly through the client.

    :param host: hostname to connect to InfluxDB, defaults to 'localhost'
    :type host: string
    :param port: port to connect to InfluxDB, defaults to 'localhost'
    :type port: int
    :param username: user to connect, defaults to 'root'
    :type username: string
    :param password: password of the user, defaults to 'root'
    :type password: string
    :param database: database name to connect to, defaults is None
    :type database: string
    :param ssl: use https instead of http to connect to InfluxDB, defaults is
        False
    :type ssl: boolean
    :param verify_ssl: verify SSL certificates for HTTPS requests, defaults is
        False
    :type verify_ssl: boolean
    :param retries: number of retries your client will try before aborting,
        defaults to 3. 0 indicates try until success
    :type retries: int
    :param timeout: number of seconds Requests will wait for your client to
        establish a connection, defaults to None
    :type timeout: int
    :param use_udp: use UDP to connect to InfluxDB, defaults is False
    :type use_udp: int
    :param udp_port: UDP port to connect to InfluxDB, defaults is 4444
    :type udp_port: int
    	localhost  rootNF   \  c                 C   s   || _ || _|| _|| _|| _|| _|	| _|| _|
| _|| _	|
r)t

t
jt
j| _d| _|du r3d| _d| j| j | j| _ddd| _dS )	z&Construct a new InfluxDBClient object.ZhttpThttpsz{0}://{1}:{2}zapplication/jsonz
text/plain)zContent-typeZAcceptN)_hostZ_port	_username	_password	_database_timeout_retries_verify_ssl_use_udp	_udp_portsocketZAF_INETZ
SOCK_DGRAM
udp_socketZ_schemer	   _baseurl_headers)r   hostportusernamepassworddatabasesslZ
verify_ssltimeoutZretriesuse_udpZudp_portr   r   r   r   ?   s.   zInfluxDBClient.__init__c                 K   s  i }t | }|jd}t|dkr|d }d}n|\}}|dkr(td||rC|dkr3d|d	< n|d
kr<d|d< ntd||jrK|j|d< |jrS|j|d< |jr[|j|d< |j	rc|j	|d< |j
rvt|j
dkrv|j
dd |d< || tdi |S )a@  Return an instaance of InfluxDBClient from given data source name.

        Returns an instance of InfluxDBClient from the provided data source
        name. Supported schemes are "influxdb", "https+influxdb",
        "udp+influxdb". Parameters for the InfluxDBClient constructor may be
        also be passed to this function.

        Examples:
            >> cli = InfluxDBClient.from_dsn('influxdb://username:password@\
            ... localhost:8086/databasename', timeout=5)
            >> type(cli)
            <class 'influxdb.client.InfluxDBClient'>
            >> cli = InfluxDBClient.from_dsn('udp+influxdb://username:pass@\
            ... localhost:8086/databasename', timeout=5, udp_port=159)
            >> print('{0._baseurl} - {0.use_udp} {0.udp_port}'.format(cli))
            http://localhost:8086 - True 159

        :param dsn: data source name
        :type dsn: string
        :param **kwargs: additional parameters for InfluxDBClient.
        :type **kwargs: dict
        :note: parameters provided in **kwargs may override dsn parameters.
        :note: when using "udp+influxdb" the specified port (if any) will be
        used for the TCP connection; specify the udp port with the additional
        udp_port parameter (cf. examples).
        :raise ValueError: if the provided DSN has any unexpected value.

        +   r   NinfluxdbzUnknown scheme "{0}".ZudpTr1   r   r/   zUnknown modifier "{0}".r*   r+   r,   r-   r.   r   )r   schemesplitlen
ValueErrorr	   Zhostnamer+   r,   r-   pathupdater   )ZdsnkwargsZ	init_argsZconn_paramsZscheme_infor5   modifierr   r   r   from_dsni   s6   






zInfluxDBClient.from_dsnc                 C   s
   || _ dS )z|Change client database.

        :param database: the new database name to switch to
        :type database: string
        N)r    r   r.   r   r   r   switch_database   s   
zInfluxDBClient.switch_databasec                 C   s   t dt | |S )z5Change client database.

        DEPRECATED.
        zswitch_db is deprecated, and will be removed in future versions. Please use ``InfluxDBClient.switch_database(database)`` instead.)warningswarnFutureWarningr?   r>   r   r   r   	switch_db   s
   
zInfluxDBClient.switch_dbc                 C   s   || _ || _dS )zChange client username.

        :param username: the new username to switch to
        :type username: string
        :param password: the new password to switch to
        :type password: string
        N)r   r   )r   r,   r-   r   r   r   switch_user   s   
zInfluxDBClient.switch_userGET   c           
   	   C   s   d | j|}|du ri }| j| jd}|| |dur't|ts't|}d}d}|r^zt	j
||||| j| j| jd}	W n# tjjtjjfy[   |d7 }| jdkrY|| jk }Y nw |s-tjj|	j|kri|	S t|	j|	j)zMake a http request to API.z{0}/{1}N)upTr   )methodurlparamsdataZheadersZverifyr0   r3   )r	   r(   r   r   r:   
isinstancestrjsondumpssessionrequestr)   r#   r!   requests
exceptionsConnectionErrorZTimeoutr"   Zstatus_coder   r
   )
r   rJ   rI   rK   rL   expected_response_codeZauthZretryZ_tryresponser   r   r   rR      sH   

	



zInfluxDBClient.requestc                 C   s   | j ddd|dd dS )z<Provide as convenience for influxdb v0.9.0, this may change.writePOSTNrF   rJ   rI   rK   rL   rV   TrR   )r   rL   r   r   r   rX      s   zInfluxDBClient.writesc                 O   s   dd }| d}|r<|dkr<|D ](}| d}| d}	| dg }
||
|D ]}|||	dg}| j||d	 q(qd
S | j||d	S )a  Write to multiple time series names.

        An example data blob is:

        data = [
            {
                "points": [
                    [
                        12
                    ]
                ],
                "name": "cpu_load_short",
                "columns": [
                    "value"
                ]
            }
        ]

        :param data: A list of dicts in InfluxDB 0.8.x data format.
        :param time_precision: [Optional, default 's'] Either 's', 'm', 'ms'
            or 'u'.
        :param batch_size: [Optional] Value to write the points in batches
            instead of all at one time. Useful for when doing data dumps from
            one database to another or when doing a massive write operation
        :type batch_size: int

        c                 s   s.    t dt| |D ]}| |||  V  q	dS )z'Yield successive n-sized chunks from l.r   N)r   r7   )Z	data_listnir   r   r   list_chunks'  s   z0InfluxDBClient.write_points.<locals>.list_chunks
batch_sizer   namecolumnspoints)rc   ra   rb   rL   time_precisionT)get_write_points)r   rL   re   argsr;   r_   r`   itemra   rb   Z
point_listZbatchr   r   r   write_points  s*   


	zInfluxDBClient.write_pointsc                 C   s   t dt | j||dS )zBWrite to multiple time series names.

        DEPRECATED.
        zwrite_points_with_precision is deprecated, and will be removed in future versions. Please use ``InfluxDBClient.write_points(time_precision='..')`` instead.rd   )r@   rA   rB   rg   )r   rL   re   r   r   r   write_points_with_precisionA  s
   z*InfluxDBClient.write_points_with_precisionc                 C   sf   |dvrt d| jr|dkrt dd| j}d|i}| jr'| | d
S | j|d||dd	 d
S )Nr\   mmsrG   <Invalid time precision is given. (use 's', 'm', 'ms' or 'u')r\   z7InfluxDB only supports seconds precision for udp writesdb/{0}/seriesre   rY   rF   rZ   T)	Exceptionr$   r	   r    send_packetrR   )r   rL   re   rJ   rK   r   r   r   rg   M  s,   

zInfluxDBClient._write_pointsc                 C   "   d | j|}| j|ddd dS )zDelete an entire series.db/{0}/series/{1}DELETE   rJ   rI   rV   Tr	   r    rR   )r   ra   rJ   r   r   r   delete_pointsl     zInfluxDBClient.delete_pointsc                 C      t  )zCreate schedule delete from database.

        2013-11-08: This endpoint has not been implemented yet in ver0.0.8,
        but it is documented in http://influxdb.org/docs/api/http.html.
        See also: src/api/http/api.go:l57

        NotImplementedError)r   	json_bodyr   r   r   create_scheduled_deletez     z&InfluxDBClient.create_scheduled_deletec                 C   r{   )zGet list of scheduled deletes.

        2013-11-08: This endpoint has not been implemented yet in ver0.0.8,
        but it is documented in http://influxdb.org/docs/api/http.html.
        See also: src/api/http/api.go:l57

        r|   r   r   r   r   get_list_scheduled_delete  r   z(InfluxDBClient.get_list_scheduled_deletec                 C   r{   )zRemove scheduled delete.

        2013-11-08: This endpoint has not been implemented yet in ver0.0.8,
        but it is documented in http://influxdb.org/docs/api/http.html.
        See also: src/api/http/api.go:l57

        r|   )r   Z	delete_idr   r   r   remove_scheduled_delete  r   z&InfluxDBClient.remove_scheduled_deletec                 C   s   | j |||dS )a  Query data from the influxdb v0.8 database.

        :param time_precision: [Optional, default 's'] Either 's', 'm', 'ms'
            or 'u'.
        :param chunked: [Optional, default=False] True if the data shall be
            retrieved in chunks, False otherwise.
        )re   chunked_query)r   queryre   r   r   r   r   r     s   zInfluxDBClient.queryc           	      C   s   |dvrt d|du rd}nd}d| j}|||d}| j|d|d	d
}|rKzt|j }W t	|S  tyJ   t|jd}Y t	|S w |
 S )Nrl   ro   TtrueZfalserp   )qre   r   rE   rF   )rJ   rI   rK   rV   utf-8)rq   r	   r    rR   r   loadsr
   decodeUnicodeDecodeErrorlistrO   )	r   r   re   r   Zchunked_paramrJ   rK   rW   Zdecodedr   r   r   r     s6   zInfluxDBClient._queryc                 C   s"   d}d|i}| j |d|dd dS )zCreate a database on the InfluxDB server.

        :param database: the name of the database to create
        :type database: string
        :rtype: boolean
        dbra   rY      rJ   rI   rL   rV   Tr[   )r   r.   rJ   rL   r   r   r   create_database  s   zInfluxDBClient.create_databasec                 C      d |}| j|ddd dS )zDrop a database on the InfluxDB server.

        :param database: the name of the database to delete
        :type database: string
        :rtype: boolean
        zdb/{0}ru   rv   rw   Tr	   rR   )r   r.   rJ   r   r   r   delete_database  s   
zInfluxDBClient.delete_databasec                 C   s   d}| j |ddd}| S )zGet the list of databases.r   rE   rF   rw   rR   rO   r   rJ   rW   r   r   r   get_list_database   s   z InfluxDBClient.get_list_databasec                 C   s   t dt |  S )z8Get the list of databases.

        DEPRECATED.
        zget_database_list is deprecated, and will be removed in future versions. Please use ``InfluxDBClient.get_list_database`` instead.)r@   rA   rB   r   r   r   r   r   get_database_list  s
   z InfluxDBClient.get_database_listc                 C   rs   )zDrop a series on the InfluxDB server.

        :param series: the name of the series to delete
        :type series: string
        :rtype: boolean
        rt   ru   rv   rw   Trx   )r   seriesrJ   r   r   r   delete_series  s   zInfluxDBClient.delete_seriesc                 C       |  d}dd |d d D S )z,Get a list of all time series in a database.zlist seriesc                 S      g | ]}|d  qS )r3   r   ).0r   r   r   r   
<listcomp>/      z2InfluxDBClient.get_list_series.<locals>.<listcomp>r   rc   r   r   rW   r   r   r   get_list_series,     
zInfluxDBClient.get_list_seriesc                 C   r   )z!Get a list of continuous queries.zlist continuous queriesc                 S   r   )   r   )r   r   r   r   r   r   4  r   z>InfluxDBClient.get_list_continuous_queries.<locals>.<listcomp>r   rc   r   r   r   r   r   get_list_continuous_queries1  r   z*InfluxDBClient.get_list_continuous_queriesc                 C   s   | j dddd}| S )zGet list of cluster admins.cluster_adminsrE   rF   rw   r   r   r   r   r   get_list_cluster_adminsU  s   z&InfluxDBClient.get_list_cluster_adminsc                 C   s    ||d}| j dd|dd dS )zAdd cluster admin.ra   r-   r   rY   rF   r   Tr[   )r   new_usernamenew_passwordrL   r   r   r   add_cluster_admin_  s   z InfluxDBClient.add_cluster_adminc                 C   s(   d |}d|i}| j|d|dd dS )zUpdate cluster admin password.cluster_admins/{0}r-   rY   rF   r   Tr   )r   r,   r   rJ   rL   r   r   r   update_cluster_admin_passwordo  s   
z,InfluxDBClient.update_cluster_admin_passwordc                 C   r   )zDelete cluster admin.r   ru   rF   rw   Tr   r   r,   rJ   r   r   r   delete_cluster_admin  s   
z#InfluxDBClient.delete_cluster_adminc                 C      |  |dS )zSet user as database admin.Talter_database_adminr   r,   r   r   r   set_database_admin     z!InfluxDBClient.set_database_adminc                 C   r   )zUnset user as database admin.Fr   r   r   r   r   unset_database_admin  r   z#InfluxDBClient.unset_database_adminc                 C   s,   d | j|}d|i}| j|d|dd dS )zAlter the database admin.db/{0}/users/{1}ZadminrY   rF   r   Trx   )r   r,   Zis_adminrJ   rL   r   r   r   r     s   z#InfluxDBClient.alter_database_adminc                 C   r{   )zGet list of database admins.

        2013-11-08: This endpoint has not been implemented yet in ver0.0.8,
        but it is documented in http://influxdb.org/docs/api/http.html.
        See also: src/api/http/api.go:l57

        r|   r   r   r   r   get_list_database_admins  r   z'InfluxDBClient.get_list_database_adminsc                 C   r{   )zAdd cluster admin.

        2013-11-08: This endpoint has not been implemented yet in ver0.0.8,
        but it is documented in http://influxdb.org/docs/api/http.html.
        See also: src/api/http/api.go:l57

        r|   )r   r   r   r   r   r   add_database_admin  r   z!InfluxDBClient.add_database_adminc                 C   r{   )zUpdate database admin password.

        2013-11-08: This endpoint has not been implemented yet in ver0.0.8,
        but it is documented in http://influxdb.org/docs/api/http.html.
        See also: src/api/http/api.go:l57

        r|   r   r,   r   r   r   r   update_database_admin_password  r   z-InfluxDBClient.update_database_admin_passwordc                 C   r{   )zDelete database admin.

        2013-11-08: This endpoint has not been implemented yet in ver0.0.8,
        but it is documented in http://influxdb.org/docs/api/http.html.
        See also: src/api/http/api.go:l57

        r|   r   r   r   r   delete_database_admin  r   z$InfluxDBClient.delete_database_adminc                 C   s$   d | j}| j|ddd}| S )zGet list of database users.db/{0}/usersrE   rF   rw   )r	   r    rR   rO   r   r   r   r   get_database_users  s   z!InfluxDBClient.get_database_usersc              	   C   s`   d | j}||d}|r%z
|\|d< |d< W n ttfy$   tdw | j|d|dd d	S )
zXAdd database user.

        :param permissions: A ``(readFrom, writeTo)`` tuple
        r   r   readFromwriteTo/'permissions' must be (readFrom, writeTo) tuplerY   rF   r   T)r	   r    r8   	TypeErrorrR   )r   r   r   permissionsrJ   rL   r   r   r   add_database_user  s&   z InfluxDBClient.add_database_userc                 C   s   |  ||S )zUpdate password.)alter_database_userr   r   r   r   update_database_user_password  r   z,InfluxDBClient.update_database_user_passwordc              	   C   s   d | j|}|s|std |i }|r||d< |r4z
|\|d< |d< W n ttfy3   tdw | j|d|dd	 || jkrE|| _d
S )zAlter a database user and/or their permissions.

        :param permissions: A ``(readFrom, writeTo)`` tuple
        :raise TypeError: if permissions cannot be read.
        :raise ValueError: if neither password nor permissions provided.
        r   zNothing to alter for user {0}.r-   r   r   r   rY   rF   r   T)r	   r    r8   r   rR   r   r   )r   r,   r-   r   rJ   rL   r   r   r   r   
  s.   
z"InfluxDBClient.alter_database_userc                 C   rs   )zDelete database user.r   ru   rF   rw   Trx   r   r   r   r   delete_database_user/  rz   z#InfluxDBClient.delete_database_userc                 C   r{   )zUpdate read/write permission.

        2013-11-08: This endpoint has not been implemented yet in ver0.0.8,
        but it is documented in http://influxdb.org/docs/api/http.html.
        See also: src/api/http/api.go:l57

        r|   )r   r,   r~   r   r   r   update_permission=  r   z InfluxDBClient.update_permissionc                 C   s.   t |}|d}| j|| j| jf dS )z!Send a UDP packet along the wire.r   N)rO   rP   encoder'   Zsendtor   r%   )r   ZpacketrL   Zbyter   r   r   rr   G  s   

zInfluxDBClient.send_packet)r   r   r   r   NFFNr   Fr   )rE   NNrF   )r\   )r\   F)N)NN).r   r   r   r   r   staticmethodr=   r?   rC   rD   rR   rX   rj   rk   rg   ry   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   rr   r   r   r   r   r      sr    "
*
C
.

6



,$





%
r   )r   r@   rO   r&   rS   Zrequests.exceptionsZ	six.movesr   Zsix.moves.urllib.parser   r4   r   ZSessionrQ   rq   r   objectr   r   r   r   r   <module>   s   