|
| 1 | +""" |
| 2 | +How to check that connection credentials are suitable for queries and writes from/into specified bucket. |
| 3 | +""" |
| 4 | + |
| 5 | +from influxdb_client import InfluxDBClient |
| 6 | +from influxdb_client.client.write_api import SYNCHRONOUS |
| 7 | +from influxdb_client.rest import ApiException |
| 8 | + |
| 9 | +""" |
| 10 | +Define credentials |
| 11 | +""" |
| 12 | +url = "http://localhost:8086" |
| 13 | +token = "my-token" |
| 14 | +org = "my-org" |
| 15 | +bucket = "my-bucket" |
| 16 | + |
| 17 | + |
| 18 | +def check_connection(): |
| 19 | + """Check that the InfluxDB is running.""" |
| 20 | + print("> Checking connection ...", end=" ") |
| 21 | + client.api_client.call_api('/ping', 'GET') |
| 22 | + print("ok") |
| 23 | + |
| 24 | + |
| 25 | +def check_query(): |
| 26 | + """Check that the credentials has permission to query from the Bucket""" |
| 27 | + print("> Checking credentials for query ...", end=" ") |
| 28 | + try: |
| 29 | + client.query_api().query(f"from(bucket:\"{bucket}\") |> range(start: -1m) |> limit(n:1)", org) |
| 30 | + except ApiException as e: |
| 31 | + # missing credentials |
| 32 | + if e.status == 404: |
| 33 | + raise Exception(f"The specified token doesn't have sufficient credentials to read from '{bucket}' " |
| 34 | + f"or specified bucket doesn't exists.") from e |
| 35 | + raise |
| 36 | + print("ok") |
| 37 | + |
| 38 | + |
| 39 | +def check_write(): |
| 40 | + """Check that the credentials has permission to write into the Bucket""" |
| 41 | + print("> Checking credentials for write ...", end=" ") |
| 42 | + try: |
| 43 | + client.write_api(write_options=SYNCHRONOUS).write(bucket, org, b"") |
| 44 | + except ApiException as e: |
| 45 | + # bucket does not exist |
| 46 | + if e.status == 404: |
| 47 | + raise Exception(f"The specified bucket does not exist.") from e |
| 48 | + # insufficient permissions |
| 49 | + if e.status == 403: |
| 50 | + raise Exception(f"The specified token does not have sufficient credentials to write to '{bucket}'.") from e |
| 51 | + # 400 (BadRequest) caused by empty LineProtocol |
| 52 | + if e.status != 400: |
| 53 | + raise |
| 54 | + print("ok") |
| 55 | + |
| 56 | + |
| 57 | +with InfluxDBClient(url=url, token=token, org=org) as client: |
| 58 | + check_connection() |
| 59 | + check_query() |
| 60 | + check_write() |
| 61 | + pass |
0 commit comments