o
    -7_W                     @   s  d Z ddlmZ ddlmZ ddlmZ ddlmZ ddlZddlZddlZddl	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m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 dd
lmZ ddlmZ ddlmZ G dd deZ dd Z!dd Z"dd Z#dS )zPython client for InfluxDB.    )absolute_import)division)print_function)unicode_literalsN)chainislice)urlparse)
make_linesquote_identquote_literal	ResultSet   )InfluxDBClientError)InfluxDBServerErrorc                   @   s  e Zd ZdZ															
				dlddZdd Zdd Zedd Zedd Z	edd Z
edd Zedd Zedd Zedd Zdd  Zd!d" Z		dmd%d&Z	'	(dnd)d*Zedod,d-Z				$		+		.	#dpd/d0Z						(	dqd1d2Zd3d4 Zed5d6 Z	(	drd7d8Zd9d: Zdsd;d<Zd=d> Zd?d@ ZdAdB ZdCdD Z 		EdtdFdGZ!			dudHdIZ"dvdJdKZ#dvdLdMZ$dNdO Z%dwdPdQZ&dRdS Z'dTdU Z(dsdVdWZ)dXdY Z*dZd[ Z+d\d] Z,d^d_ Z-d`da Z.dbdc Z/		dxdddeZ0dvdfdgZ1drdhdiZ2djdk Z3dS )yInfluxDBClientu
  InfluxDBClient primary client object to connect InfluxDB.

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

    The client supports the use as a `context manager
    <https://docs.python.org/3/reference/datamodel.html#context-managers>`_.

    :param host: hostname to connect to InfluxDB, defaults to 'localhost'
    :type host: str
    :param port: port to connect to InfluxDB, defaults to 8086
    :type port: int
    :param username: user to connect, defaults to 'root'
    :type username: str
    :param password: password of the user, defaults to 'root'
    :type password: str
    :param pool_size: urllib3 connection pool size, defaults to 10.
    :type pool_size: int
    :param database: database name to connect to, defaults to None
    :type database: str
    :param ssl: use https instead of http to connect to InfluxDB, defaults to
        False
    :type ssl: bool
    :param verify_ssl: verify SSL certificates for HTTPS requests, defaults to
        False
    :type verify_ssl: bool
    :param timeout: number of seconds Requests will wait for your client to
        establish a connection, defaults to None
    :type timeout: int
    :param retries: number of attempts your client will make before aborting,
        defaults to 3
        0 - try until success
        1 - attempt only once (without retry)
        2 - maximum two attempts (including one retry)
        3 - maximum three attempts (default option)
    :type retries: int
    :param use_udp: use UDP to connect to InfluxDB, defaults to False
    :type use_udp: bool
    :param udp_port: UDP port to connect to InfluxDB, defaults to 4444
    :type udp_port: int
    :param proxies: HTTP(S) proxy to use for Requests, defaults to {}
    :type proxies: dict
    :param path: path of InfluxDB on the server to connect, defaults to ''
    :type path: str
    :param cert: Path to client certificate information to use for mutual TLS
        authentication. You can specify a local cert to use
        as a single file containing the private key and the certificate, or as
        a tuple of both files’ paths, defaults to None
    :type cert: str
    :param gzip: use gzip content encoding to compress requests
    :type gzip: bool
    :param session: allow for the new client request to use an existing
        requests Session, defaults to None
    :type session: requests.Session
    :param headers: headers to add to Requests, will add 'Content-Type'
        and 'Accept' unless these are already present, defaults to {}
    :type headers: dict
    :raises ValueError: if cert is provided but ssl is disabled (set to False)
    	localhost  rootNF   \  
    c                 C   sR  || _ t|| _|| _|| _|| _|| _|	| _|| _|
| _	t|| _
|s(t }|| _tjjt|t|d}|
rBttjtj| _|sHd| _n|d dkrR|| _nd| | _d| _|du rad| _| j| jd | |d	u rsi | _n|| _|r|s~td
|| j_d| j| j| j| j| _|d	u ri }|dd |dd || _ || _!d	S )z&Construct a new InfluxDBClient object.)Zpool_connectionsZpool_maxsizer   r   /ZhttpThttpsz://Nz0Client certificate provided but ssl is disabled.z{0}://{1}:{2}{3}Content-Typezapplication/jsonZAcceptapplication/x-msgpack)"_InfluxDBClient__hostint_InfluxDBClient__port	_username	_password	_database_timeout_retries_verify_ssl_InfluxDBClient__use_udp_InfluxDBClient__udp_portrequestsSession_sessionZadaptersZHTTPAdaptersocketZAF_INETZ
SOCK_DGRAM
udp_socket_InfluxDBClient__pathZ_schemeZmount_proxies
ValueErrorcertformat_host_port_path_InfluxDBClient__baseurl
setdefault_headers_gzip)selfhostportusernamepassworddatabasesslZ
verify_ssltimeoutZretriesuse_udpZudp_portproxiesZ	pool_sizepathr0   gzipZsessionheadersZadapter rF   1/usr/lib/python3/dist-packages/influxdb/client.py__init__]   sb   



zInfluxDBClient.__init__c                 C   s   dS )z*Enter function as used by context manager.NrF   r9   rF   rF   rG   	__enter__   s   zInfluxDBClient.__enter__c                 C   s   |    dS )z)Exit function as used by context manager.N)close)r9   Z	_exc_typeZ
_exc_valueZ
_tracebackrF   rF   rG   __exit__   s   zInfluxDBClient.__exit__c                 C      | j S N)r5   rI   rF   rF   rG   _baseurl      zInfluxDBClient._baseurlc                 C   rM   rN   )r   rI   rF   rF   rG   r2      rP   zInfluxDBClient._hostc                 C   rM   rN   )r   rI   rF   rF   rG   r3      rP   zInfluxDBClient._portc                 C   rM   rN   )r-   rI   rF   rF   rG   r4      rP   zInfluxDBClient._pathc                 C   rM   rN   )r'   rI   rF   rF   rG   	_udp_port   rP   zInfluxDBClient._udp_portc                 C   rM   rN   )r&   rI   rF   rF   rG   _use_udp   rP   zInfluxDBClient._use_udpc                 K   sB   t |}|dd \}}||d< ||d< || | di |S )ah  Generate an instance of InfluxDBClient from given data source name.

        Return an instance of :class:`~.InfluxDBClient` from the provided
        data source name. Supported schemes are "influxdb", "https+influxdb"
        and "udp+influxdb". Parameters for the :class:`~.InfluxDBClient`
        constructor may also be passed to this method.

        :param dsn: data source name
        :type dsn: string
        :param kwargs: additional parameters for `InfluxDBClient`
        :type kwargs: dict
        :raises ValueError: if the provided DSN has any unexpected values

        :Example:

        ::

            >> 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

        .. 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).
        hostsr   r:   r;   NrF   )
_parse_dsnpopupdate)clsdsnkwargs	init_argsr:   r;   rF   rF   rG   from_dsn   s   !
zInfluxDBClient.from_dsnc                 C   s
   || _ dS )zChange the client's database.

        :param database: the name of the database to switch to
        :type database: str
        N)r"   )r9   r>   rF   rF   rG   switch_database   s   
zInfluxDBClient.switch_databasec                 C   s   || _ || _dS )zChange the client's username.

        :param username: the username to switch to
        :type username: str
        :param password: the password for the username
        :type password: str
        N)r    r!   )r9   r<   r=   rF   rF   rG   switch_user  s   
zInfluxDBClient.switch_userGET   c                 C   s  d | j|}|du r| j}|du ri }t|ttfr t|}| jrT|	ddd |durTt
 }tjd|dd}	|	| W d   n1 sKw   Y  | }d}
d	}|
rz!| j| jf}| jj||d|vrl|nd||||| j| j| jd

}W n6 tjjtjjtjjfy   |d7 }| jd	kr|| jk }
|
s |dkrtd| t  d  Y nw |
sZ|j o|j !d}|dkr|j"rt#j$|j"t%dd|_&nd|_&dd }d|j'  krdk rn nt(|||j'|kr|S ||}t)||j')aJ  Make a HTTP request to the InfluxDB API.

        :param url: the path of the HTTP request, e.g. write, query, etc.
        :type url: str
        :param method: the HTTP method for the request, defaults to GET
        :type method: str
        :param params: additional parameters for the request, defaults to None
        :type params: dict
        :param data: the data of the request, defaults to None
        :type data: str
        :param stream: True if a query uses chunked responses
        :type stream: bool
        :param expected_response_code: the expected response code of
            the request, defaults to 200
        :type expected_response_code: int
        :param headers: headers to add to the request
        :type headers: dict
        :returns: the response from the request
        :rtype: :class:`requests.Response`
        :raises InfluxDBServerError: if the response code is any server error
            code (5xx)
        :raises InfluxDBClientError: if the response code is not the
            same as `expected_response_code` and is not a server error code
        z{0}/{1}NrD   )zAccept-EncodingzContent-Encoding	   w)compresslevelZfileobjmodeTr   )
methodurlauthparamsdatastreamrE   rB   Zverifyr@   r   POST   g      Y@r   r   F)ZpackedZext_hookrawc                 S   s   | j rtj| j ddS | jS )N),:)Z
separators)_msgpackjsondumpscontent)responserF   rF   rG   reformat_errorm  s   z.InfluxDBClient.request.<locals>.reformat_errori  iX  )*r1   rO   r7   
isinstancedictlistrp   rq   r8   rV   ioBytesIOrD   ZGzipFilewritegetvaluer    r!   r*   requestr.   r%   r#   r(   
exceptionsConnectionErrorZ	HTTPErrorZTimeoutr$   timesleeprandomrE   getrr   msgpackZunpackb_msgpack_parse_hookro   Zstatus_coder   r   )r9   re   rd   rg   rh   ri   expected_response_coderE   
compressedfZretryZ_tryrf   rs   Ztype_headerrt   err_msgrF   rF   rG   r|     s   





zInfluxDBClient.request   rp   c                 C   s   | j  }d|d< |r|d}nd}|dkr t||d}n|dkr6t|tr,|g}d|d d}| jd	d
||||d dS )a  Write data to InfluxDB.

        :param data: the data to be written
        :type data: (if protocol is 'json') dict
                    (if protocol is 'line') sequence of line protocol strings
                                            or single string
        :param params: additional parameters for the request, defaults to None
        :type params: dict
        :param expected_response_code: the expected response code of the write
            operation, defaults to 204
        :type expected_response_code: int
        :param protocol: protocol of input data, either 'json' or 'line'
        :type protocol: str
        :returns: True, if the write operation is successful
        :rtype: bool
        zapplication/octet-streamr   	precisionNrp   utf-8line
rz   rj   )re   rd   rg   rh   r   rE   T)	r7   copyr   r	   encoderu   strjoinr|   )r9   rh   rg   r   protocolrE   r   rF   rF   rG   rz   |  s(   

zInfluxDBClient.writeTc                 c   s    |   D ]:}t|tr|d}t|}i }|dg D ]}|D ]}t|| tr6||g 	||  q"qt
||dV  qd S )Nr   resultsraise_errors)Z
iter_linesru   bytesdecoderp   loadsr   rw   r6   extendr   )rs   r   r   rh   Z
result_setresultZ_keyrF   rF   rG   _read_chunked_response  s"   


z%InfluxDBClient._read_chunked_responser   c                    s  |du ri }|durt |dd}|| t ||d< ||d< |p'| j|d< |dur2||d< |r@d|d< |	d	kr@|	|d
< | drOd| v rOd}
| jd|
|d||d}|j	}|sj|rf| 
|S |  } fdd|dg D }t|dkr|d	 S |S )a  Send a query to InfluxDB.

        .. danger::
            In order to avoid injection vulnerabilities (similar to `SQL
            injection <https://www.owasp.org/index.php/SQL_Injection>`_
            vulnerabilities), do not directly include untrusted data into the
            ``query`` parameter, use ``bind_params`` instead.

        :param query: the actual query string
        :type query: str

        :param params: additional parameters for the request,
            defaults to {}
        :type params: dict

        :param bind_params: bind parameters for the query:
            any variable in the query written as ``'$var_name'`` will be
            replaced with ``bind_params['var_name']``. Only works in the
            ``WHERE`` clause and takes precedence over ``params['params']``
        :type bind_params: dict

        :param epoch: response timestamps to be in epoch format either 'h',
            'm', 's', 'ms', 'u', or 'ns',defaults to `None` which is
            RFC3339 UTC format with nanosecond precision
        :type epoch: str

        :param expected_response_code: the expected status code of response,
            defaults to 200
        :type expected_response_code: int

        :param database: database to query, defaults to None
        :type database: str

        :param raise_errors: Whether or not to raise exceptions when InfluxDB
            returns errors, defaults to True
        :type raise_errors: bool

        :param chunked: Enable to use chunked responses from InfluxDB.
            With ``chunked`` enabled, one ResultSet is returned per chunk
            containing all results within that chunk
        :type chunked: bool

        :param chunk_size: Size of each chunk to tell InfluxDB to use.
        :type chunk_size: int

        :param method: the HTTP method for the request, defaults to GET
        :type method: str

        :returns: the queried data
        :rtype: :class:`~.ResultSet`
        Nrg   z{}qdbepochtruechunkedr   
chunk_sizezselect z into rj   query)re   rd   rg   rh   ri   r   c                    s   g | ]}t | d qS )r   r   ).0r   r   rF   rG   
<listcomp>  s    
z(InfluxDBClient.query.<locals>.<listcomp>r   r   )rp   r   r   rV   rq   r"   lower
startswithr|   ro   r   len)r9   r   rg   Zbind_paramsr   r   r>   r   r   r   rd   Zparams_dictrs   rh   r   rF   r   rG   r     sF   >
	


zInfluxDBClient.queryc	           
   
   C   sR   |r|dkr|  ||D ]}	| j|	||||||d qdS | j|||||||dS )a  Write to multiple time series names.

        :param points: the list of points to be written in the database
        :type points: list of dictionaries, each dictionary represents a point
        :type points: (if protocol is 'json') list of dicts, where each dict
                                            represents a point.
                    (if protocol is 'line') sequence of line protocol strings.
        :param time_precision: Either 's', 'm', 'ms' or 'u', defaults to None
        :type time_precision: str
        :param database: the database to write the points to. Defaults to
            the client's current database
        :type database: str
        :param tags: a set of key-value pairs associated with each point. Both
            keys and values must be strings. These are shared tags and will be
            merged with point-specific tags, defaults to None
        :type tags: dict
        :param retention_policy: the retention policy for the points. Defaults
            to None
        :type retention_policy: str
        :param batch_size: 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,
            defaults to None
        :type batch_size: int
        :param protocol: Protocol for writing data. Either 'line' or 'json'.
        :type protocol: str
        :param consistency: Consistency for the points.
            One of {'any','one','quorum','all'}.
        :type consistency: str
        :returns: True, if the operation is successful
        :rtype: bool

        .. note:: if no retention policy is specified, the default retention
            policy for the database is used
        r   )pointstime_precisionr>   retention_policytagsr   consistencyT)_batches_write_points)
r9   r   r   r>   r   r   Z
batch_sizer   r   ZbatchrF   rF   rG   write_points$  s"   -zInfluxDBClient.write_pointsc                 C   s   | j dddd}|jd S )zrCheck connectivity to InfluxDB.

        :returns: The version of the InfluxDB the client is connected to
        pingr^   r   )re   rd   r   zX-Influxdb-Version)r|   rE   )r9   rs   rF   rF   rG   r   b  s   
zInfluxDBClient.pingc                 c   sL    t | }	 zt|f}W n
 ty   Y d S w t||d }t||V  q)NTr   )iternextStopIterationr   r   )iterablesizeiteratorheadrestrF   rF   rG   r   o  s   zInfluxDBClient._batchesc           
      C   s   |dvrt d|dvrt d||dkr$d|i}|d ur#||d< n|}d|p+| ji}	|d ur5||	d	< |d ur=||	d
< |d urE||	d< | jrR| j|||d dS | j||	d|d dS )N)numssmhNzFInvalid time precision is given. (use 'n', 'u', 'ms', 's', 'm' or 'h'))anyZoneZquorumallNzInvalid consistency: {}rp   r   r   r   r   r   Zrp)r   r   r   )rh   rg   r   r   T)r/   r1   r"   rR   send_packetrz   )
r9   r   r   r>   r   r   r   r   rh   rg   rF   rF   rG   r   }  sB   
zInfluxDBClient._write_pointsc                 C      t | d S )a*  Get the list of databases in InfluxDB.

        :returns: all databases in InfluxDB
        :rtype: list of dictionaries

        :Example:

        ::

            >> dbs = client.get_list_database()
            >> dbs
            [{u'name': u'db1'}, {u'name': u'db2'}, {u'name': u'db3'}]
        zSHOW DATABASESrw   r   
get_pointsrI   rF   rF   rG   get_list_database  s   z InfluxDBClient.get_list_databasec                 C   sl   |p| j }d}|r|d|7 }|r"|dddd | D  7 }ttjdd | j||d	 D S )	a  
        Query SHOW SERIES returns the distinct series in your database.

        FROM and WHERE clauses are optional.

        :param measurement: Show all series from a measurement
        :type id: string
        :param tags: Show all series that match given tags
        :type id: dict
        :param database: the database from which the series should be
            shows, defaults to client's current database
        :type database: str
        zSHOW SERIESz FROM "{0}" WHERE z and c                 S   s   g | ]
\}}d  ||qS )z	{0}='{1}')r1   r   kvrF   rF   rG   r     s    z2InfluxDBClient.get_list_series.<locals>.<listcomp>c                 S   s   g | ]}|  qS rF   )values)r   xrF   rF   rG   r     s    )r>   )
r"   r1   r   itemsrw   	itertoolsr   from_iterabler   r   )r9   r>   measurementr   	query_strrF   rF   rG   get_list_series  s    
zInfluxDBClient.get_list_seriesc                 C      | j dt|dd dS )zCreate a new database in InfluxDB.

        :param dbname: the name of the database to create
        :type dbname: str
        zCREATE DATABASE {0}rj   rd   Nr   r1   r
   r9   ZdbnamerF   rF   rG   create_database     
zInfluxDBClient.create_databasec                 C   r   )zzDrop a database from InfluxDB.

        :param dbname: the name of the database to drop
        :type dbname: str
        zDROP DATABASE {0}rj   r   Nr   r   rF   rF   rG   drop_database  r   zInfluxDBClient.drop_databasec                 C   r   )al  Get the list of measurements in InfluxDB.

        :returns: all measurements in InfluxDB
        :rtype: list of dictionaries

        :Example:

        ::

            >> dbs = client.get_list_measurements()
            >> dbs
            [{u'name': u'measurements1'},
             {u'name': u'measurements2'},
             {u'name': u'measurements3'}]
        zSHOW MEASUREMENTSr   rI   rF   rF   rG   get_list_measurements     z$InfluxDBClient.get_list_measurementsc                 C   r   )zDrop a measurement from InfluxDB.

        :param measurement: the name of the measurement to drop
        :type measurement: str
        zDROP MEASUREMENT {0}rj   r   Nr   )r9   r   rF   rF   rG   drop_measurement  r   zInfluxDBClient.drop_measurement0sc                 C   sB   d t|t|p
| j|||}|du r|d7 }| j|dd dS )a  Create a retention policy for a database.

        :param name: the name of the new retention policy
        :type name: str
        :param duration: the duration of the new retention policy.
            Durations such as 1h, 90m, 12h, 7d, and 4w, are all supported
            and mean 1 hour, 90 minutes, 12 hours, 7 day, and 4 weeks,
            respectively. For infinite retention - meaning the data will
            never be deleted - use 'INF' for duration.
            The minimum retention period is 1 hour.
        :type duration: str
        :param replication: the replication of the retention policy
        :type replication: str
        :param database: the database for which the retention policy is
            created. Defaults to current client's database
        :type database: str
        :param default: whether or not to set the policy as default
        :type default: bool
        :param shard_duration: the shard duration of the retention policy.
            Durations such as 1h, 90m, 12h, 7d, and 4w, are all supported and
            mean 1 hour, 90 minutes, 12 hours, 7 day, and 4 weeks,
            respectively. Infinite retention is not supported. As a workaround,
            specify a "1000w" duration to achieve an extremely long shard group
            duration. Defaults to "0s", which is interpreted by the database
            to mean the default value given the duration.
            The minimum shard group duration is 1 hour.
        :type shard_duration: str
        zRCREATE RETENTION POLICY {0} ON {1} DURATION {2} REPLICATION {3} SHARD DURATION {4}T DEFAULTrj   r   Nr1   r
   r"   r   )r9   namedurationreplicationr>   defaultshard_durationquery_stringrF   rF   rG   create_retention_policy  s    z&InfluxDBClient.create_retention_policyc                 C   sr   d t|t|p
| j}|r|d |7 }|r|d |7 }|r(|d |7 }|du r0|d7 }| j|dd d	S )
a9  Modify an existing retention policy for a database.

        :param name: the name of the retention policy to modify
        :type name: str
        :param database: the database for which the retention policy is
            modified. Defaults to current client's database
        :type database: str
        :param duration: the new duration of the existing retention policy.
            Durations such as 1h, 90m, 12h, 7d, and 4w, are all supported
            and mean 1 hour, 90 minutes, 12 hours, 7 day, and 4 weeks,
            respectively. For infinite retention, meaning the data will
            never be deleted, use 'INF' for duration.
            The minimum retention period is 1 hour.
        :type duration: str
        :param replication: the new replication of the existing
            retention policy
        :type replication: int
        :param default: whether or not to set the modified policy as default
        :type default: bool
        :param shard_duration: the shard duration of the retention policy.
            Durations such as 1h, 90m, 12h, 7d, and 4w, are all supported and
            mean 1 hour, 90 minutes, 12 hours, 7 day, and 4 weeks,
            respectively. Infinite retention is not supported. As a workaround,
            specify a "1000w" duration to achieve an extremely long shard group
            duration.
            The minimum shard group duration is 1 hour.
        :type shard_duration: str

        .. note:: at least one of duration, replication, or default flag
            should be set. Otherwise the operation will fail.
        z!ALTER RETENTION POLICY {0} ON {1}z DURATION {0}z SHARD DURATION {0}z REPLICATION {0}Tr   rj   r   Nr   )r9   r   r>   r   r   r   r   r   rF   rF   rG   alter_retention_policy;  s   #z%InfluxDBClient.alter_retention_policyc                 C   s,   d t|t|p
| j}| j|dd dS )a0  Drop an existing retention policy for a database.

        :param name: the name of the retention policy to drop
        :type name: str
        :param database: the database for which the retention policy is
            dropped. Defaults to current client's database
        :type database: str
        z DROP RETENTION POLICY {0} ON {1}rj   r   Nr   r9   r   r>   r   rF   rF   rG   drop_retention_policyl  s   
z$InfluxDBClient.drop_retention_policyc                 C   s8   |s	| j s	td| dt|p| j }t| S )a)  Get the list of retention policies for a database.

        :param database: the name of the database, defaults to the client's
            current database
        :type database: str
        :returns: all retention policies for the database
        :rtype: list of dictionaries

        :Example:

        ::

            >> ret_policies = client.get_list_retention_policies('my_db')
            >> ret_policies
            [{u'default': True,
              u'duration': u'0',
              u'name': u'default',
              u'replicaN': 1}]
        zeget_list_retention_policies() requires a database as a parameter or the client to be using a databasezSHOW RETENTION POLICIES ON {0})r"   r   r   r1   r
   rw   r   )r9   r>   ZrsprF   rF   rG   get_list_retention_policiesz  s   
z*InfluxDBClient.get_list_retention_policiesc                 C   r   )ay  Get the list of all users in InfluxDB.

        :returns: all users in InfluxDB
        :rtype: list of dictionaries

        :Example:

        ::

            >> users = client.get_list_users()
            >> users
            [{u'admin': True, u'user': u'user1'},
             {u'admin': False, u'user': u'user2'},
             {u'admin': False, u'user': u'user3'}]
        z
SHOW USERSr   rI   rF   rF   rG   get_list_users  r   zInfluxDBClient.get_list_usersc                 C   s2   d t|t|}|r|d7 }| j|dd dS )aP  Create a new user in InfluxDB.

        :param username: the new username to create
        :type username: str
        :param password: the password for the new user
        :type password: str
        :param admin: whether the user should have cluster administration
            privileges or not
        :type admin: boolean
        z!CREATE USER {0} WITH PASSWORD {1}z WITH ALL PRIVILEGESrj   r   Nr1   r
   r   r   )r9   r<   r=   ZadmintextrF   rF   rG   create_user  s   zInfluxDBClient.create_userc                 C       d t|}| j|dd dS )znDrop a user from InfluxDB.

        :param username: the username to drop
        :type username: str
        zDROP USER {0}rj   r   Nr1   r
   r   r9   r<   r   rF   rF   rG   	drop_user  s   zInfluxDBClient.drop_userc                 C   s"   d t|t|}| | dS )zChange the password of an existing user.

        :param username: the username who's password is being changed
        :type username: str
        :param password: the new password for the user
        :type password: str
        zSET PASSWORD FOR {0} = {1}Nr   )r9   r<   r=   r   rF   rF   rG   set_user_password  s   z InfluxDBClient.set_user_passwordc                 C   s`   |p| j }d}|r|dt|7 }|r&dd | D }|dd| 7 }| j||dd d	S )
a  Delete series from a database.

        Series must be filtered by either measurement and tags.
        This method cannot be used to delete all series, use
        `drop_database` instead.

        :param database: the database from which the series should be
            deleted, defaults to client's current database
        :type database: str
        :param measurement: Delete all series from a measurement
        :type measurement: str
        :param tags: Delete all series that match given tags
        :type tags: dict
        zDROP SERIESz	 FROM {0}c                 S   s$   g | ]\}}d  t|t|qS )z{0}={1})r1   r
   r   r   rF   rF   rG   r     s    z0InfluxDBClient.delete_series.<locals>.<listcomp>r   z AND rj   )r>   rd   N)r"   r1   r
   r   r   r   )r9   r>   r   r   r   Ztag_eq_listrF   rF   rG   delete_series  s   
zInfluxDBClient.delete_seriesc                 C   r   )zGrant cluster administration privileges to a user.

        :param username: the username to grant privileges to
        :type username: str

        .. note:: Only a cluster administrator can create/drop databases
            and manage users.
        zGRANT ALL PRIVILEGES TO {0}rj   r   Nr   r   rF   rF   rG   grant_admin_privileges     	z%InfluxDBClient.grant_admin_privilegesc                 C   r   )a  Revoke cluster administration privileges from a user.

        :param username: the username to revoke privileges from
        :type username: str

        .. note:: Only a cluster administrator can create/ drop databases
            and manage users.
        zREVOKE ALL PRIVILEGES FROM {0}rj   r   Nr   r   rF   rF   rG   revoke_admin_privileges  r   z&InfluxDBClient.revoke_admin_privilegesc                 C   (   d |t|t|}| j|dd dS )a  Grant a privilege on a database to a user.

        :param privilege: the privilege to grant, one of 'read', 'write'
            or 'all'. The string is case-insensitive
        :type privilege: str
        :param database: the database to grant the privilege on
        :type database: str
        :param username: the username to grant the privilege to
        :type username: str
        zGRANT {0} ON {1} TO {2}rj   r   Nr   r9   Z	privileger>   r<   r   rF   rF   rG   grant_privilege  
   zInfluxDBClient.grant_privilegec                 C   r   )a  Revoke a privilege on a database from a user.

        :param privilege: the privilege to revoke, one of 'read', 'write'
            or 'all'. The string is case-insensitive
        :type privilege: str
        :param database: the database to revoke the privilege on
        :type database: str
        :param username: the username to revoke the privilege from
        :type username: str
        zREVOKE {0} ON {1} FROM {2}rj   r   Nr   r   rF   rF   rG   revoke_privilege  r   zInfluxDBClient.revoke_privilegec                 C   s    d t|}t| | S )a2  Get the list of all privileges granted to given user.

        :param username: the username to get privileges of
        :type username: str

        :returns: all privileges granted to given user
        :rtype: list of dictionaries

        :Example:

        ::

            >> privileges = client.get_list_privileges('user1')
            >> privileges
            [{u'privilege': u'WRITE', u'database': u'db1'},
             {u'privilege': u'ALL PRIVILEGES', u'database': u'db2'},
             {u'privilege': u'NO PRIVILEGES', u'database': u'db3'}]
        zSHOW GRANTS FOR {0})r1   r
   rw   r   r   r   rF   rF   rG   get_list_privileges#  s   z"InfluxDBClient.get_list_privilegesc                 C   s   d}dd |  | D S )a3  Get the list of continuous queries in InfluxDB.

        :return: all CQs in InfluxDB
        :rtype: list of dictionaries

        :Example:

        ::

            >> cqs = client.get_list_cqs()
            >> cqs
            [
                {
                    u'db1': []
                },
                {
                    u'db2': [
                        {
                            u'name': u'vampire',
                            u'query': u'CREATE CONTINUOUS QUERY vampire ON '
                                       'mydb BEGIN SELECT count(dracula) INTO '
                                       'mydb.autogen.all_of_them FROM '
                                       'mydb.autogen.one GROUP BY time(5m) END'
                        }
                    ]
                }
            ]
        zSHOW CONTINUOUS QUERIESc                 S   s    g | ]\}}|d  t |iqS )r   )rw   )r   skprF   rF   rG   r   W  s     z>InfluxDBClient.get_list_continuous_queries.<locals>.<listcomp>)r   r   )r9   r   rF   rF   rG   get_list_continuous_queries9  s   z*InfluxDBClient.get_list_continuous_queriesc                 C   s8   d t|t|p
| j|rd| nd|}| | dS )a  Create a continuous query for a database.

        :param name: the name of continuous query to create
        :type name: str
        :param select: select statement for the continuous query
        :type select: str
        :param database: the database for which the continuous query is
            created. Defaults to current client's database
        :type database: str
        :param resample_opts: resample options
        :type resample_opts: str

        :Example:

        ::

            >> select_clause = 'SELECT mean("value") INTO "cpu_mean" ' \
            ...                 'FROM "cpu" GROUP BY time(1m)'
            >> client.create_continuous_query(
            ...     'cpu_mean', select_clause, 'db_name', 'EVERY 10s FOR 2m'
            ... )
            >> client.get_list_continuous_queries()
            [
                {
                    'db_name': [
                        {
                            'name': 'cpu_mean',
                            'query': 'CREATE CONTINUOUS QUERY "cpu_mean" '
                                    'ON "db_name" '
                                    'RESAMPLE EVERY 10s FOR 2m '
                                    'BEGIN SELECT mean("value") '
                                    'INTO "cpu_mean" FROM "cpu" '
                                    'GROUP BY time(1m) END'
                        }
                    ]
                }
            ]
        z3CREATE CONTINUOUS QUERY {0} ON {1}{2} BEGIN {3} ENDz
 RESAMPLE r   Nr   )r9   r   Zselectr>   Zresample_optsr   rF   rF   rG   create_continuous_queryY  s   )z&InfluxDBClient.create_continuous_queryc                 C   s(   d t|t|p
| j}| | dS )a,  Drop an existing continuous query for a database.

        :param name: the name of continuous query to drop
        :type name: str
        :param database: the database for which the continuous query is
            dropped. Defaults to current client's database
        :type database: str
        z DROP CONTINUOUS QUERY {0} ON {1}Nr   r   rF   rF   rG   drop_continuous_query  s   
z$InfluxDBClient.drop_continuous_queryc                 C   sP   |dkrt ||d}n|dkrd|d d}| j|| j| jf dS )a  Send an UDP packet.

        :param packet: the packet to be sent
        :type packet: (if protocol is 'json') dict
                      (if protocol is 'line') list of line protocol strings
        :param protocol: protocol of input data, either 'json' or 'line'
        :type protocol: str
        :param time_precision: Either 's', 'm', 'ms' or 'u', defaults to None
        :type time_precision: str
        rp   r   r   r   N)r	   r   r   r,   Zsendtor2   rQ   )r9   Zpacketr   r   rh   rF   rF   rG   r     s
   zInfluxDBClient.send_packetc                 C   s    t | jtjr| j  dS dS )zClose http session.N)ru   r*   r(   r)   rK   rI   rF   rF   rG   rK     s   zInfluxDBClient.close)r   r   r   r   NFFNr   Fr   Nr   r   NFNN)r^   NNFr_   N)Nr   rp   )T)	NNNr_   NTFr   r^   )NNNNNrp   N)rp   N)NNN)NFr   )NNNNNrN   )F)NN)4__name__
__module____qualname____doc__rH   rJ   rL   propertyrO   r2   r3   r4   rQ   rR   classmethodr[   r\   r]   r|   rz   staticmethodr   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   rK   rF   rF   rF   rG   r      s    >
W






(
l
+
q
>

5
"		

*

1

	
 

.
r   c           	      C   s  t | }i }|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d}g |d< |D ]!}t|}|d |d t	|d f |d |d< |d |d< qO|j
rt|j
dkr|j
dd |d< |S )zParse data source name.

    This is a helper function to split the data source name provided in
    the from_dsn classmethod
    +r   r   NZinfluxdbzUnknown scheme "{0}".ZudpTrA   r   r?   zUnknown modifier "{0}".rm   rS   r:   r;   r<   r=   r>   )r   schemesplitr   r/   r1   netloc_parse_netlocappendr   rC   )	rX   Zconn_paramsrZ   Zscheme_infor
  modifierZnetlocsr  ZparsedrF   rF   rG   rT     s2   

rT   c                 C   s4   t d| }|jpd |jpd |jpd|jpddS )Nz
http://{0}r   r   )r<   r=   r:   r;   )r   r1   r<   r=   Zhostnamer;   )r  inforF   rF   rG   r    s   r  c                 C   sP   | dkr"t d|\}}tj|}|tj|d d7 }| d S t| |S )N   z>QIi  )ZmicrosecondsZ)structunpackdatetimeZutcfromtimestampZ	timedeltaZ	isoformatr   ZExtType)coderh   Zepoch_sZepoch_nsZ	timestamprF   rF   rG   r     s   r   )$r  Z
__future__r   r   r   r   r  rD   r   rx   rp   r   r+   r  r   r   r   r   r(   Zrequests.exceptionsZsix.moves.urllib.parser   Zinfluxdb.line_protocolr	   r
   r   Zinfluxdb.resultsetr   r}   r   r   objectr   rT   r  r   rF   rF   rF   rG   <module>   sH            )