|
| 1 | +# |
| 2 | +# The MIT License |
| 3 | +# |
| 4 | +# @copyright Copyright (c) 2017 Intel Corporation |
| 5 | +# @copyright Copyright (c) 2021 ApertureData Inc |
| 6 | +# |
| 7 | +# Permission is hereby granted, free of charge, to any person obtaining a copy |
| 8 | +# of this software and associated documentation files (the "Software"), |
| 9 | +# to deal in the Software without restriction, |
| 10 | +# including without limitation the rights to use, copy, modify, |
| 11 | +# merge, publish, distribute, sublicense, and/or sell |
| 12 | +# copies of the Software, and to permit persons to whom the Software is |
| 13 | +# furnished to do so, subject to the following conditions: |
| 14 | +# |
| 15 | +# The above copyright notice and this permission notice shall be included in |
| 16 | +# all copies or substantial portions of the Software. |
| 17 | +# |
| 18 | +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 19 | +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 20 | +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 21 | +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 22 | +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, |
| 23 | +# ARISING FROM, |
| 24 | +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 25 | +# THE SOFTWARE. |
| 26 | +# |
| 27 | +from __future__ import annotations |
| 28 | +import os |
| 29 | +import requests |
| 30 | +import time |
| 31 | +import json |
| 32 | +import logging |
| 33 | + |
| 34 | +from threading import Lock |
| 35 | +from types import SimpleNamespace |
| 36 | +from dataclasses import dataclass |
| 37 | +from aperturedb.Connector import Connector |
| 38 | + |
| 39 | +logger = logging.getLogger(__name__) |
| 40 | + |
| 41 | +PROTOCOL_VERSION = 1 |
| 42 | + |
| 43 | + |
| 44 | +class UnauthorizedException(Exception): |
| 45 | + pass |
| 46 | + |
| 47 | + |
| 48 | +@dataclass |
| 49 | +class Session(): |
| 50 | + |
| 51 | + session_token: str |
| 52 | + refresh_token: str |
| 53 | + session_token_ttl: int |
| 54 | + refresh_token_ttl: int |
| 55 | + session_started: time.time = time.time() |
| 56 | + |
| 57 | + def valid(self) -> bool: |
| 58 | + session_age = time.time() - self.session_started |
| 59 | + |
| 60 | + # This triggers refresh if the session is about to expire. |
| 61 | + if session_age > self.session_token_ttl - \ |
| 62 | + int(os.getenv("SESSION_EXPIRTY_OFFSET_SEC", 10)): |
| 63 | + return False |
| 64 | + |
| 65 | + return True |
| 66 | + |
| 67 | + |
| 68 | +class ConnectorRest(Connector): |
| 69 | + """ |
| 70 | + .. _connector-label: |
| 71 | +
|
| 72 | + **Class to use aperturedb's REST interface** |
| 73 | +
|
| 74 | + Args: |
| 75 | + str (host): Address of the host to connect to. |
| 76 | + int (port): Port to connect to. |
| 77 | + str (user): Username to specify while establishing a connection. |
| 78 | + str (password): Password to specify while connecting to the db. |
| 79 | + str (token): Token to use while connecting to the database. |
| 80 | + bool (use_ssl): Use SSL to encrypt communication with the database. |
| 81 | + """ |
| 82 | + |
| 83 | + def __init__(self, host="localhost", port=80, |
| 84 | + user="", password="", token="", |
| 85 | + use_ssl=True, shared_data=None): |
| 86 | + |
| 87 | + self.host = host |
| 88 | + self.port = port |
| 89 | + self.use_ssl = use_ssl |
| 90 | + self.connected = False |
| 91 | + |
| 92 | + self.last_response = '' |
| 93 | + self.last_query_time = 0 |
| 94 | + |
| 95 | + self.url = ('https' if self.use_ssl else 'http') + \ |
| 96 | + '://' + host + ':' + str(port) + '/api/' |
| 97 | + |
| 98 | + if shared_data is None: |
| 99 | + self.shared_data = SimpleNamespace() |
| 100 | + self.shared_data.session = None |
| 101 | + self.shared_data.lock = Lock() |
| 102 | + try: |
| 103 | + self._authenticate(user, password, token) |
| 104 | + except Exception as e: |
| 105 | + raise Exception("Authentication failed:", str(e)) |
| 106 | + else: |
| 107 | + self.shared_data = shared_data |
| 108 | + |
| 109 | + def __del__(self): |
| 110 | + logger.info("Done with connector") |
| 111 | + |
| 112 | + def _query(self, query, blob_array = []): |
| 113 | + response_blob_array = [] |
| 114 | + # Check the query type |
| 115 | + if not isinstance(query, str): # assumes json |
| 116 | + query_str = json.dumps(query) |
| 117 | + else: |
| 118 | + query_str = query |
| 119 | + |
| 120 | + files = [ |
| 121 | + ('query', (None, query_str)), |
| 122 | + ] |
| 123 | + |
| 124 | + for blob in blob_array: |
| 125 | + files.append(('blobs', blob)) |
| 126 | + |
| 127 | + # Set Auth token, only when not authenticated before |
| 128 | + if self.shared_data.session: |
| 129 | + headers = {'Authorization': "Bearer " + |
| 130 | + self.shared_data.session.session_token} |
| 131 | + else: |
| 132 | + headers = None |
| 133 | + tries = 0 |
| 134 | + response = SimpleNamespace() |
| 135 | + response.status_code = 0 |
| 136 | + while tries < 3: |
| 137 | + tries += 1 |
| 138 | + response = requests.post(self.url, |
| 139 | + headers = headers, |
| 140 | + files = files, |
| 141 | + verify = self.use_ssl) |
| 142 | + if response.status_code == 200: |
| 143 | + # Parse response: |
| 144 | + json_response = json.loads(response.text) |
| 145 | + import base64 |
| 146 | + response_blob_array = [base64.b64decode( |
| 147 | + b) for b in json_response['blobs']] |
| 148 | + self.last_response = json_response["json"] |
| 149 | + break |
| 150 | + logger.error( |
| 151 | + f"Response not OK = {response.status_code} {response.text[:1000]}\n\ |
| 152 | + attempt [{tries}/3] .. PID = {os.getpid()}") |
| 153 | + time.sleep(1) |
| 154 | + |
| 155 | + if tries == 3: |
| 156 | + raise Exception( |
| 157 | + f"Could not query apertureDB using REST.") |
| 158 | + return (self.last_response, response_blob_array) |
0 commit comments