|
| 1 | +""" |
| 2 | +Copyright (c) 2023, Oracle and/or its affiliates. |
| 3 | +
|
| 4 | + Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + you may not use this file except in compliance with the License. |
| 6 | + You may obtain a copy of the License at |
| 7 | +
|
| 8 | + https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | + Unless required by applicable law or agreed to in writing, software |
| 11 | + distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + See the License for the specific language governing permissions and |
| 14 | + limitations under the License. |
| 15 | +""" |
| 16 | +import datetime |
| 17 | +import http |
| 18 | +import json |
| 19 | +from typing import Dict |
| 20 | + |
| 21 | +import requests |
| 22 | +import time |
| 23 | + |
| 24 | +import dbt.exceptions |
| 25 | +from dbt.adapters.oracle import OracleAdapterCredentials |
| 26 | +from dbt.events import AdapterLogger |
| 27 | +from dbt.ui import red, green |
| 28 | + |
| 29 | +# ADB-S OML Rest API minimum timeout is 1800 seconds |
| 30 | +DEFAULT_TIMEOUT_IN_SECONDS = 1800 |
| 31 | +DEFAULT_DELAY_BETWEEN_POLL_IN_SECONDS = 2 |
| 32 | + |
| 33 | +OMLUSERS_OAUTH_API = "/omlusers/api/oauth2/v1/token" |
| 34 | +OML_DO_EVAL_API = "/oml/api/py-scripts/v1/do-eval/{script_name}" |
| 35 | + |
| 36 | +logger = AdapterLogger("oracle") |
| 37 | + |
| 38 | + |
| 39 | +class OracleOML4PYClient: |
| 40 | + |
| 41 | + def __init__(self, oml_cloud_service_url, username, password): |
| 42 | + self.base_url = oml_cloud_service_url |
| 43 | + self._username = username |
| 44 | + self._password = password |
| 45 | + self.token = None |
| 46 | + self.token_expires_at = None |
| 47 | + self.token_url = self.base_url + OMLUSERS_OAUTH_API |
| 48 | + self._session = requests.Session() |
| 49 | + |
| 50 | + @property |
| 51 | + def session(self): |
| 52 | + return self._session |
| 53 | + |
| 54 | + def get_token(self): |
| 55 | + """Get access_token or refresh_token""" |
| 56 | + # If access token is about to expire then refresh the token |
| 57 | + if self.token_expires_at and self.token_expires_at - datetime.datetime.utcnow() < datetime.timedelta(minutes=1): |
| 58 | + return self._get_token(grant_type="refresh_token") |
| 59 | + elif self.token: # Token is valid |
| 60 | + return self.token |
| 61 | + else: # Generate a new token |
| 62 | + return self._get_token(grant_type="password") |
| 63 | + |
| 64 | + def _get_token(self, grant_type="password"): |
| 65 | + """Gets access_token or refresh_token using /broker/pdbcs/private/v1/token""" |
| 66 | + data = {"grant_type": grant_type} |
| 67 | + if grant_type == "password": |
| 68 | + data["username"] = self._username |
| 69 | + data["password"] = self._password |
| 70 | + else: |
| 71 | + data["token"] = self.token |
| 72 | + |
| 73 | + r = self.session.post( |
| 74 | + url=self.token_url, |
| 75 | + json=data, |
| 76 | + headers={ |
| 77 | + "Accept": "application/json", |
| 78 | + "Content-type": "application/json", |
| 79 | + }, |
| 80 | + ) |
| 81 | + r.raise_for_status() |
| 82 | + response = r.json() |
| 83 | + self.token = response["accessToken"] |
| 84 | + self.token_expires_at = datetime.datetime.utcnow() + datetime.timedelta(seconds=response["expiresIn"]) |
| 85 | + return self.token |
| 86 | + |
| 87 | + @property |
| 88 | + def default_headers(self): |
| 89 | + """Default headers added to every request""" |
| 90 | + return { |
| 91 | + "Content-type": "application/json", |
| 92 | + "Accept": "application/json", |
| 93 | + "Authorization": f"Bearer {self.get_token()}", |
| 94 | + } |
| 95 | + |
| 96 | + def request(self, method: str, path: str, |
| 97 | + raise_for_status: bool = False, |
| 98 | + **kwargs) -> requests.Response: |
| 99 | + """ |
| 100 | + Description: |
| 101 | + Perform a desired action (GET, PUT, POST) on a certain resource |
| 102 | +
|
| 103 | + Args: |
| 104 | + method (str) -> HTTP verb like GET, PUT, POST, etc |
| 105 | + path (str) -> path to the resource e.g. /job/{job_id} |
| 106 | + raise_for_status (bool) -> True if HTTPError should be raised in case of an error else False |
| 107 | +
|
| 108 | + Returns: |
| 109 | + object of type request.Response |
| 110 | +
|
| 111 | + Raises: |
| 112 | + requests.HTTPError() in case of en error, if raise_for_status is True |
| 113 | +
|
| 114 | + """ |
| 115 | + url = path if path.startswith(self.base_url) else self.base_url + path |
| 116 | + self.session.headers.update(self.default_headers) |
| 117 | + r = self.session.request(method=method, url=url, **kwargs) |
| 118 | + try: |
| 119 | + r.raise_for_status() |
| 120 | + except requests.HTTPError: |
| 121 | + if raise_for_status: |
| 122 | + raise |
| 123 | + return r |
| 124 | + |
| 125 | + |
| 126 | +class OracleADBSPythonJob: |
| 127 | + """Callable to submit Python Script to ADB-S |
| 128 | +
|
| 129 | + """ |
| 130 | + |
| 131 | + def __init__(self, |
| 132 | + parsed_model: Dict, |
| 133 | + credential: OracleAdapterCredentials) -> None: |
| 134 | + self.identifier = parsed_model["alias"] |
| 135 | + self.py_q_script_name = f"{self.identifier}_dbt_py_script" |
| 136 | + self.conda_env_name = parsed_model["config"].get("conda_env_name") |
| 137 | + self.timeout = parsed_model["config"].get("timeout", DEFAULT_TIMEOUT_IN_SECONDS) |
| 138 | + self.async_flag = parsed_model["config"].get("async_flag", False) |
| 139 | + self.service = parsed_model["config"].get("service", "HIGH") |
| 140 | + self.oml4py_client = OracleOML4PYClient(oml_cloud_service_url=credential.oml_cloud_service_url, |
| 141 | + username=credential.user, |
| 142 | + password=credential.password) |
| 143 | + |
| 144 | + def schedule_async_job_and_wait_for_completion(self, data): |
| 145 | + logger.info(f"Running Python aysnc job using {data}") |
| 146 | + try: |
| 147 | + r = self.oml4py_client.request(method="POST", |
| 148 | + path=OML_DO_EVAL_API.format(script_name=self.py_q_script_name), |
| 149 | + data=json.dumps(data), |
| 150 | + raise_for_status=False) |
| 151 | + if r.status_code in (http.HTTPStatus.BAD_REQUEST, http.HTTPStatus.INTERNAL_SERVER_ERROR): |
| 152 | + logger.error(red(r.json())) |
| 153 | + r.raise_for_status() |
| 154 | + except requests.exceptions.RequestException as e: |
| 155 | + logger.error(red(f"Error {e} scheduling async Python job for model {self.identifier}")) |
| 156 | + raise dbt.exceptions.DbtRuntimeError(f"Error scheduling Python model {self.identifier}") |
| 157 | + |
| 158 | + job_location = r.headers["location"] |
| 159 | + logger.info(f"Started async job {job_location}") |
| 160 | + start_time = time.time() |
| 161 | + |
| 162 | + while time.time() - start_time < self.timeout: |
| 163 | + logger.debug(f"Checking Job status for : {job_location}") |
| 164 | + try: |
| 165 | + job_status = self.oml4py_client.request(method="GET", |
| 166 | + path=job_location, |
| 167 | + raise_for_status=False) |
| 168 | + job_status_code = job_status.status_code |
| 169 | + logger.debug(f"Job status code is: {job_status_code}") |
| 170 | + if job_status_code == http.HTTPStatus.FOUND: |
| 171 | + logger.info(green(f"Job {job_location} completed")) |
| 172 | + job_result = self.oml4py_client.request(method="GET", |
| 173 | + path=f"{job_location}/result", |
| 174 | + raise_for_status=False) |
| 175 | + job_result_json = job_result.json() |
| 176 | + if 'errorMessage' in job_result_json: |
| 177 | + logger.error(red(f"FAILURE - Python model {self.identifier} Job failure is: {job_result_json}")) |
| 178 | + raise dbt.exceptions.DbtRuntimeError(f"Error running Python model {self.identifier}") |
| 179 | + job_result.raise_for_status() |
| 180 | + logger.info(green(f"SUCCESS - Python model {self.identifier} Job result is: {job_result_json}")) |
| 181 | + return |
| 182 | + elif job_status_code == http.HTTPStatus.INTERNAL_SERVER_ERROR: |
| 183 | + logger.error(red(f"FAILURE - Job status is: {job_status.json()}")) |
| 184 | + raise dbt.exceptions.DbtRuntimeError(f"Error running Python model {self.identifier}") |
| 185 | + else: |
| 186 | + logger.debug(f"Python model {self.identifier} job status is: {job_status.json()}") |
| 187 | + job_status.raise_for_status() |
| 188 | + |
| 189 | + except requests.exceptions.RequestException as e: |
| 190 | + logger.error(red(f"Error {e} checking status of Python job {job_location} for model {self.identifier}")) |
| 191 | + raise dbt.exceptions.DbtRuntimeError(f"Error checking status for job {job_location}") |
| 192 | + |
| 193 | + time.sleep(DEFAULT_DELAY_BETWEEN_POLL_IN_SECONDS) |
| 194 | + logger.error(red(f"Timeout error for Python model {self.identifier}")) |
| 195 | + raise dbt.exceptions.DbtRuntimeError(f"Timeout error for Python model {self.identifier}") |
| 196 | + |
| 197 | + def __call__(self, *args, **kwargs): |
| 198 | + data = { |
| 199 | + "service": self.service |
| 200 | + } |
| 201 | + if self.async_flag: |
| 202 | + data["asyncFlag"] = self.async_flag |
| 203 | + data["timeout"] = self.timeout |
| 204 | + if self.conda_env_name: |
| 205 | + data["envName"] = self.conda_env_name |
| 206 | + |
| 207 | + if self.async_flag: |
| 208 | + self.schedule_async_job_and_wait_for_completion(data=data) |
| 209 | + else: # Run in blocking mode |
| 210 | + logger.info(f"Running Python model {self.identifier} with args {data}") |
| 211 | + try: |
| 212 | + r = self.oml4py_client.request(method="POST", |
| 213 | + path=OML_DO_EVAL_API.format(script_name=self.py_q_script_name), |
| 214 | + data=json.dumps(data), |
| 215 | + raise_for_status=False) |
| 216 | + job_result = r.json() |
| 217 | + if 'errorMessage' in job_result: |
| 218 | + logger.error(red(f"FAILURE - Python model {self.identifier} Job failure is: {job_result}")) |
| 219 | + raise dbt.exceptions.DbtRuntimeError(f"Error running Python model {self.identifier}") |
| 220 | + r.raise_for_status() |
| 221 | + logger.info(green(f"SUCCESS - Python model {self.identifier} Job result is: {job_result}")) |
| 222 | + except requests.exceptions.RequestException as e: |
| 223 | + logger.error(red(f"Error {e} running Python model {self.identifier}")) |
| 224 | + raise dbt.exceptions.DbtRuntimeError(f"Error running Python model {self.identifier}") |
| 225 | + |
0 commit comments