Debian Codegraph @

influxdb/influxdb08/client.py

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