Debian Codegraph @

influxdb/influxdb08/client.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 # -*- coding: utf-8 -*-
2 """Python client for InfluxDB v0.8."""
3
4 import warnings
5
6 import json
7 import socket
8 import requests
9 import requests.exceptions
10 from six.moves import xrange
11 from six.moves.urllib.parse import urlparse
12
13 from influxdb import chunked_json
14
15 session = requests.Session()
16
17
18 class InfluxDBClientError(Exception):
19 """Raised when an error occurs in the request."""
20
21 def __init__(self, content, code=-1):
22 """Initialize an InfluxDBClientError handler."""
23 super(InfluxDBClientError, self).__init__(
24 "{0}: {1}".format(code, content))
25 self.content = content
26 self.code = code
27
28
29 class InfluxDBClient(object):
30 """Define the standard InfluxDBClient for influxdb v0.8.
31
32 The ``InfluxDBClient`` object holds information necessary to connect
33 to InfluxDB. Requests can be made to InfluxDB directly through the client.
34
35 :param host: hostname to connect to InfluxDB, defaults to 'localhost'
36 :type host: string
37 :param port: port to connect to InfluxDB, defaults to 'localhost'
38 :type port: int
39 :param username: user to connect, defaults to 'root'
40 :type username: string
41 :param password: password of the user, defaults to 'root'
42 :type password: string
43 :param database: database name to connect to, defaults is None
44 :type database: string
45 :param ssl: use https instead of http to connect to InfluxDB, defaults is
46 False
47 :type ssl: boolean
48 :param verify_ssl: verify SSL certificates for HTTPS requests, defaults is
49 False
50 :type verify_ssl: boolean
51 :param retries: number of retries your client will try before aborting,
52 defaults to 3. 0 indicates try until success
53 :type retries: int
54 :param timeout: number of seconds Requests will wait for your client to
55 establish a connection, defaults to None
56 :type timeout: int
57 :param use_udp: use UDP to connect to InfluxDB, defaults is False
58 :type use_udp: int
59 :param udp_port: UDP port to connect to InfluxDB, defaults is 4444
60 :type udp_port: int
61 """
62
63 def __init__(self,
64 host='localhost',
65 port=8086,
66 username='root',
67 password='root',
68 database=None,
69 ssl=False,
70 verify_ssl=False,
71 timeout=None,
72 retries=3,
73 use_udp=False,
74 udp_port=4444):
75 """Construct a new InfluxDBClient object."""
76 self._host = host
77 self._port = port
78 self._username = username
79 self._password = password
80 self._database = database
81 self._timeout = timeout
82 self._retries = retries
83
84 self._verify_ssl = verify_ssl
85
86 self._use_udp = use_udp
87 self._udp_port = udp_port
88 if use_udp:
89 self.udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
90
91 self._scheme = "http"
92
93 if ssl is True:
94 self._scheme = "https"
95
96 self._baseurl = "{0}://{1}:{2}".format(
97 self._scheme,
98 self._host,
99 self._port)
100
101 self._headers = {
102 'Content-type': 'application/json',
103 'Accept': 'text/plain'}
104
105 @staticmethod
106 def from_dsn(dsn, **kwargs):
107 r"""Return an instaance of InfluxDBClient from given data source name.
108
109 Returns an instance of InfluxDBClient from the provided data source
110 name. Supported schemes are "influxdb", "https+influxdb",
111 "udp+influxdb". Parameters for the InfluxDBClient constructor may be
112 also be passed to this function.
113
114 Examples:
115 >> cli = InfluxDBClient.from_dsn('influxdb://username:password@\
116 ... localhost:8086/databasename', timeout=5)
117 >> type(cli)
118 <class 'influxdb.client.InfluxDBClient'>
119 >> cli = InfluxDBClient.from_dsn('udp+influxdb://username:pass@\
120 ... localhost:8086/databasename', timeout=5, udp_port=159)
121 >> print('{0._baseurl} - {0.use_udp} {0.udp_port}'.format(cli))
122 http://localhost:8086 - True 159
123
124 :param dsn: data source name
125 :type dsn: string
126 :param **kwargs: additional parameters for InfluxDBClient.
127 :type **kwargs: dict
128 :note: parameters provided in **kwargs may override dsn parameters.
129 :note: when using "udp+influxdb" the specified port (if any) will be
130 used for the TCP connection; specify the udp port with the additional
131 udp_port parameter (cf. examples).
132 :raise ValueError: if the provided DSN has any unexpected value.
133
134 """
135 init_args = {}
136 conn_params = urlparse(dsn)
137 scheme_info = conn_params.scheme.split('+')
138
139 if len(scheme_info) == 1:
140 scheme = scheme_info[0]
141 modifier = None
142 else:
143 modifier, scheme = scheme_info
144
145 if scheme != 'influxdb':
146 raise ValueError('Unknown scheme "{0}".'.format(scheme))
147
148 if modifier:
149 if modifier == 'udp':
150 init_args['use_udp'] = True
151 elif modifier == 'https':
152 init_args['ssl'] = True
153 else:
154 raise ValueError('Unknown modifier "{0}".'.format(modifier))
155
156 if conn_params.hostname:
157 init_args['host'] = conn_params.hostname
158 if conn_params.port:
159 init_args['port'] = conn_params.port
160 if conn_params.username:
161 init_args['username'] = conn_params.username
162 if conn_params.password:
163 init_args['password'] = conn_params.password
164 if conn_params.path and len(conn_params.path) > 1:
165 init_args['database'] = conn_params.path[1:]
166
167 init_args.update(kwargs)
168
169 return InfluxDBClient(**init_args)
170
171 # Change member variables
172
173 def switch_database(self, database):
174 """Change client database.
175
176 :param database: the new database name to switch to
177 :type database: string
178 """
179 self._database = database
180
181 def switch_db(self, database):
182 """Change client database.
183
184 DEPRECATED.
185 """
186 warnings.warn(
187 "switch_db is deprecated, and will be removed "
188 "in future versions. Please use "
189 "``InfluxDBClient.switch_database(database)`` instead.",
190 FutureWarning)
191 return self.switch_database(database)
192
193 def switch_user(self, username, password):
194 """Change client username.
195
196 :param username: the new username to switch to
197 :type username: string
198 :param password: the new password to switch to
199 :type password: string
200 """
201 self._username = username
202 self._password = password
203
204 def request(self, url, method='GET', params=None, data=None,
205 expected_response_code=200):
206 """Make a http request to API."""
207 url = "{0}/{1}".format(self._baseurl, url)
208
209 if params is None:
210 params = {}
211
212 auth = {
213 'u': self._username,
214 'p': self._password
215 }
216
217 params.update(auth)
218
219 if data is not None and not isinstance(data, str):
220 data = json.dumps(data)
221
222 retry = True
223 _try = 0
224 # Try to send the request more than once by default (see #103)
225 while retry:
226 try:
227 response = session.request(
228 method=method,
229 url=url,
230 params=params,
231 data=data,
232 headers=self._headers,
233 verify=self._verify_ssl,
234 timeout=self._timeout
235 )
236 break
237 except (requests.exceptions.ConnectionError,
238 requests.exceptions.Timeout):
239 _try += 1
240 if self._retries != 0:
241 retry = _try < self._retries
242 else:
243 raise requests.exceptions.ConnectionError
244
245 if response.status_code == expected_response_code:
246 return response
247 else:
248 raise InfluxDBClientError(response.content, response.status_code)
249
250 def write(self, data):
251 """Provide as convenience for influxdb v0.9.0, this may change."""
252 self.request(
253 url="write",
254 method='POST',
255 params=None,
256 data=data,
257 expected_response_code=200
258 )
259 return True
260
261 # Writing Data
262 #
263 # Assuming you have a database named foo_production you can write data
264 # by doing a POST to /db/foo_production/series?u=some_user&p=some_password
265 # with a JSON body of points.
266
267 def write_points(self, data, time_precision='s', *args, **kwargs):
268 """Write to multiple time series names.
269
270 An example data blob is:
271
272 data = [
273 {
274 "points": [
275 [
276 12
277 ]
278 ],
279 "name": "cpu_load_short",
280 "columns": [
281 "value"
282 ]
283 }
284 ]
285
286 :param data: A list of dicts in InfluxDB 0.8.x data format.
287 :param time_precision: [Optional, default 's'] Either 's', 'm', 'ms'
288 or 'u'.
289 :param batch_size: [Optional] Value to write the points in batches
290 instead of all at one time. Useful for when doing data dumps from
291 one database to another or when doing a massive write operation
292 :type batch_size: int
293
294 """
295 def list_chunks(data_list, n):
296 """Yield successive n-sized chunks from l."""
297 for i in xrange(0, len(data_list), n):
298 yield data_list[i:i + n]
299
300 batch_size = kwargs.get('batch_size')
301 if batch_size and batch_size > 0:
302 for item in data:
303 name = item.get('name')
304 columns = item.get('columns')
305 point_list = item.get('points', [])
306
307 for batch in list_chunks(point_list, batch_size):
308 item = [{
309 "points": batch,
310 "name": name,
311 "columns": columns
312 }]
313 self._write_points(
314 data=item,
315 time_precision=time_precision)
316 return True
317
318 return self._write_points(data=data,
319 time_precision=time_precision)
320
321 def write_points_with_precision(self, data, time_precision='s'):
322 """Write to multiple time series names.
323
324 DEPRECATED.
325 """
326 warnings.warn(
327 "write_points_with_precision is deprecated, and will be removed "
328 "in future versions. Please use "
329 "``InfluxDBClient.write_points(time_precision='..')`` instead.",
330 FutureWarning)
331 return self._write_points(data=data, time_precision=time_precision)
332
333 def _write_points(self, data, time_precision):
334 if time_precision not in ['s', 'm', 'ms', 'u']:
335 raise Exception(
336 "Invalid time precision is given. (use 's', 'm', 'ms' or 'u')")
337
338 if self._use_udp and time_precision != 's':
339 raise Exception(
340 "InfluxDB only supports seconds precision for udp writes"
341 )
342
343 url = "db/{0}/series".format(self._database)
344
345 params = {
346 'time_precision': time_precision
347 }
348
349 if self._use_udp:
350 self.send_packet(data)
351 else:
352 self.request(
353 url=url,
354 method='POST',
355 params=params,
356 data=data,
357 expected_response_code=200
358 )
359
360 return True
361
362 # One Time Deletes
363
364 def delete_points(self, name):
365 """Delete an entire series."""
366 url = "db/{0}/series/{1}".format(self._database, name)
367
368 self.request(
369 url=url,
370 method='DELETE',
371 expected_response_code=204
372 )
373
374 return True
375
376 # Regularly Scheduled Deletes
377
378 def create_scheduled_delete(self, json_body):
379 """Create schedule delete from database.
380
381 2013-11-08: This endpoint has not been implemented yet in ver0.0.8,
382 but it is documented in http://influxdb.org/docs/api/http.html.
383 See also: src/api/http/api.go:l57
384
385 """
386 raise NotImplementedError()
387
388 # get list of deletes
389 # curl http://localhost:8086/db/site_dev/scheduled_deletes
390 #
391 # remove a regularly scheduled delete
392 # curl -X DELETE http://localhost:8086/db/site_dev/scheduled_deletes/:id
393
394 def get_list_scheduled_delete(self):
395 """Get list of scheduled deletes.
396
397 2013-11-08: This endpoint has not been implemented yet in ver0.0.8,
398 but it is documented in http://influxdb.org/docs/api/http.html.
399 See also: src/api/http/api.go:l57
400
401 """
402 raise NotImplementedError()
403
404 def remove_scheduled_delete(self, delete_id):
405 """Remove scheduled delete.
406
407 2013-11-08: This endpoint has not been implemented yet in ver0.0.8,
408 but it is documented in http://influxdb.org/docs/api/http.html.
409 See also: src/api/http/api.go:l57
410
411 """
412 raise NotImplementedError()
413
414 def query(self, query, time_precision='s', chunked=False):
415 """Query data from the influxdb v0.8 database.
416
417 :param time_precision: [Optional, default 's'] Either 's', 'm', 'ms'
418 or 'u'.
419 :param chunked: [Optional, default=False] True if the data shall be
420 retrieved in chunks, False otherwise.
421 """
422 return self._query(query, time_precision=time_precision,
423 chunked=chunked)
424
425 # Querying Data
426 #
427 # GET db/:name/series. It takes five parameters
428 def _query(self, query, time_precision='s', chunked=False):
429 if time_precision not in ['s', 'm', 'ms', 'u']:
430 raise Exception(
431 "Invalid time precision is given. (use 's', 'm', 'ms' or 'u')")
432
433 if chunked is True:
434 chunked_param = 'true'
435 else:
436 chunked_param = 'false'
437
438 # Build the URL of the series to query
439 url = "db/{0}/series".format(self._database)
440
441 params = {
442 'q': query,
443 'time_precision': time_precision,
444 'chunked': chunked_param
445 }
446
447 response = self.request(
448 url=url,
449 method='GET',
450 params=params,
451 expected_response_code=200
452 )
453
454 if chunked:
455 try:
456 decoded = chunked_json.loads(response.content.decode())
457 except UnicodeDecodeError:
458 decoded = chunked_json.loads(response.content.decode('utf-8'))
459
460 return list(decoded)
461
462 return response.json()
463
464 # Creating and Dropping Databases
465 #
466 # ### create a database
467 # curl -X POST http://localhost:8086/db -d '{"name": "site_development"}'
468 #
469 # ### drop a database
470 # curl -X DELETE http://localhost:8086/db/site_development
471
472 def create_database(self, database):
473 """Create a database on the InfluxDB server.
474
475 :param database: the name of the database to create
476 :type database: string
477 :rtype: boolean
478 """
479 url = "db"
480
481 data = {'name': database}
482
483 self.request(
484 url=url,
485 method='POST',
486 data=data,
487 expected_response_code=201
488 )
489
490 return True
491
492 def delete_database(self, database):
493 """Drop a database on the InfluxDB server.
494
495 :param database: the name of the database to delete
496 :type database: string
497 :rtype: boolean
498 """
499 url = "db/{0}".format(database)
500
501 self.request(
502 url=url,
503 method='DELETE',
504 expected_response_code=204
505 )
506
507 return True
508
509 # ### get list of databases
510 # curl -X GET http://localhost:8086/db
511
512 def get_list_database(self):
513 """Get the list of databases."""
514 url = "db"
515
516 response = self.request(
517 url=url,
518 method='GET',
519 expected_response_code=200
520 )
521
522 return response.json()
523
524 def get_database_list(self):
525 """Get the list of databases.
526
527 DEPRECATED.
528 """
529 warnings.warn(
530 "get_database_list is deprecated, and will be removed "
531 "in future versions. Please use "
532 "``InfluxDBClient.get_list_database`` instead.",
533 FutureWarning)
534 return self.get_list_database()
535
536 def delete_series(self, series):
537 """Drop a series on the InfluxDB server.
538
539 :param series: the name of the series to delete
540 :type series: string
541 :rtype: boolean
542 """
543 url = "db/{0}/series/{1}".format(
544 self._database,
545 series
546 )
547
548 self.request(
549 url=url,
550 method='DELETE',
551 expected_response_code=204
552 )
553
554 return True
555
556 def get_list_series(self):
557 """Get a list of all time series in a database."""
558 response = self._query('list series')
559 return [series[1] for series in response[0]['points']]
560
561 def get_list_continuous_queries(self):
562 """Get a list of continuous queries."""
563 response = self._query('list continuous queries')
564 return [query[2] for query in response[0]['points']]
565
566 # Security
567 # get list of cluster admins
568 # curl http://localhost:8086/cluster_admins?u=root&p=root
569
570 # add cluster admin
571 # curl -X POST http://localhost:8086/cluster_admins?u=root&p=root \
572 # -d '{"name": "paul", "password": "i write teh docz"}'
573
574 # update cluster admin password
575 # curl -X POST http://localhost:8086/cluster_admins/paul?u=root&p=root \
576 # -d '{"password": "new pass"}'
577
578 # delete cluster admin
579 # curl -X DELETE http://localhost:8086/cluster_admins/paul?u=root&p=root
580
581 # Database admins, with a database name of site_dev
582 # get list of database admins
583 # curl http://localhost:8086/db/site_dev/admins?u=root&p=root
584
585 # add database admin
586 # curl -X POST http://localhost:8086/db/site_dev/admins?u=root&p=root \
587 # -d '{"name": "paul", "password": "i write teh docz"}'
588
589 # update database admin password
590 # curl -X POST http://localhost:8086/db/site_dev/admins/paul?u=root&p=root\
591 # -d '{"password": "new pass"}'
592
593 # delete database admin
594 # curl -X DELETE \
595 # http://localhost:8086/db/site_dev/admins/paul?u=root&p=root
596
597 def get_list_cluster_admins(self):
598 """Get list of cluster admins."""
599 response = self.request(
600 url="cluster_admins",
601 method='GET',
602 expected_response_code=200
603 )
604
605 return response.json()
606
607 def add_cluster_admin(self, new_username, new_password):
608 """Add cluster admin."""
609 data = {
610 'name': new_username,
611 'password': new_password
612 }
613
614 self.request(
615 url="cluster_admins",
616 method='POST',
617 data=data,
618 expected_response_code=200
619 )
620
621 return True
622
623 def update_cluster_admin_password(self, username, new_password):
624 """Update cluster admin password."""
625 url = "cluster_admins/{0}".format(username)
626
627 data = {
628 'password': new_password
629 }
630
631 self.request(
632 url=url,
633 method='POST',
634 data=data,
635 expected_response_code=200
636 )
637
638 return True
639
640 def delete_cluster_admin(self, username):
641 """Delete cluster admin."""
642 url = "cluster_admins/{0}".format(username)
643
644 self.request(
645 url=url,
646 method='DELETE',
647 expected_response_code=200
648 )
649
650 return True
651
652 def set_database_admin(self, username):
653 """Set user as database admin."""
654 return self.alter_database_admin(username, True)
655
656 def unset_database_admin(self, username):
657 """Unset user as database admin."""
658 return self.alter_database_admin(username, False)
659
660 def alter_database_admin(self, username, is_admin):
661 """Alter the database admin."""
662 url = "db/{0}/users/{1}".format(self._database, username)
663
664 data = {'admin': is_admin}
665
666 self.request(
667 url=url,
668 method='POST',
669 data=data,
670 expected_response_code=200
671 )
672
673 return True
674
675 def get_list_database_admins(self):
676 """Get list of database admins.
677
678 2013-11-08: This endpoint has not been implemented yet in ver0.0.8,
679 but it is documented in http://influxdb.org/docs/api/http.html.
680 See also: src/api/http/api.go:l57
681
682 """
683 raise NotImplementedError()
684
685 def add_database_admin(self, new_username, new_password):
686 """Add cluster admin.
687
688 2013-11-08: This endpoint has not been implemented yet in ver0.0.8,
689 but it is documented in http://influxdb.org/docs/api/http.html.
690 See also: src/api/http/api.go:l57
691
692 """
693 raise NotImplementedError()
694
695 def update_database_admin_password(self, username, new_password):
696 """Update database admin password.
697
698 2013-11-08: This endpoint has not been implemented yet in ver0.0.8,
699 but it is documented in http://influxdb.org/docs/api/http.html.
700 See also: src/api/http/api.go:l57
701
702 """
703 raise NotImplementedError()
704
705 def delete_database_admin(self, username):
706 """Delete database admin.
707
708 2013-11-08: This endpoint has not been implemented yet in ver0.0.8,
709 but it is documented in http://influxdb.org/docs/api/http.html.
710 See also: src/api/http/api.go:l57
711
712 """
713 raise NotImplementedError()
714
715 ###
716 # Limiting User Access
717
718 # Database users
719 # get list of database users
720 # curl http://localhost:8086/db/site_dev/users?u=root&p=root
721
722 # add database user
723 # curl -X POST http://localhost:8086/db/site_dev/users?u=root&p=root \
724 # -d '{"name": "paul", "password": "i write teh docz"}'
725
726 # update database user password
727 # curl -X POST http://localhost:8086/db/site_dev/users/paul?u=root&p=root \
728 # -d '{"password": "new pass"}'
729
730 # delete database user
731 # curl -X DELETE http://localhost:8086/db/site_dev/users/paul?u=root&p=root
732
733 def get_database_users(self):
734 """Get list of database users."""
735 url = "db/{0}/users".format(self._database)
736
737 response = self.request(
738 url=url,
739 method='GET',
740 expected_response_code=200
741 )
742
743 return response.json()
744
745 def add_database_user(self, new_username, new_password, permissions=None):
746 """Add database user.
747
748 :param permissions: A ``(readFrom, writeTo)`` tuple
749 """
750 url = "db/{0}/users".format(self._database)
751
752 data = {
753 'name': new_username,
754 'password': new_password
755 }
756
757 if permissions:
758 try:
759 data['readFrom'], data['writeTo'] = permissions
760 except (ValueError, TypeError):
761 raise TypeError(
762 "'permissions' must be (readFrom, writeTo) tuple"
763 )
764
765 self.request(
766 url=url,
767 method='POST',
768 data=data,
769 expected_response_code=200
770 )
771
772 return True
773
774 def update_database_user_password(self, username, new_password):
775 """Update password."""
776 return self.alter_database_user(username, new_password)
777
778 def alter_database_user(self, username, password=None, permissions=None):
779 """Alter a database user and/or their permissions.
780
781 :param permissions: A ``(readFrom, writeTo)`` tuple
782 :raise TypeError: if permissions cannot be read.
783 :raise ValueError: if neither password nor permissions provided.
784 """
785 url = "db/{0}/users/{1}".format(self._database, username)
786
787 if not password and not permissions:
788 raise ValueError("Nothing to alter for user {0}.".format(username))
789
790 data = {}
791
792 if password:
793 data['password'] = password
794
795 if permissions:
796 try:
797 data['readFrom'], data['writeTo'] = permissions
798 except (ValueError, TypeError):
799 raise TypeError(
800 "'permissions' must be (readFrom, writeTo) tuple"
801 )
802
803 self.request(
804 url=url,
805 method='POST',
806 data=data,
807 expected_response_code=200
808 )
809
810 if username == self._username:
811 self._password = password
812
813 return True
814
815 def delete_database_user(self, username):
816 """Delete database user."""
817 url = "db/{0}/users/{1}".format(self._database, username)
818
819 self.request(
820 url=url,
821 method='DELETE',
822 expected_response_code=200
823 )
824
825 return True
826
827 # update the user by POSTing to db/site_dev/users/paul
828
829 def update_permission(self, username, json_body):
830 """Update read/write permission.
831
832 2013-11-08: This endpoint has not been implemented yet in ver0.0.8,
833 but it is documented in http://influxdb.org/docs/api/http.html.
834 See also: src/api/http/api.go:l57
835
836 """
837 raise NotImplementedError()
838
839 def send_packet(self, packet):
840 """Send a UDP packet along the wire."""
841 data = json.dumps(packet)
842 byte = data.encode('utf-8')
843 self.udp_socket.sendto(byte, (self._host, self._udp_port))