outerbounds 0.3.183rc1__py3-none-any.whl → 0.3.185__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,164 +0,0 @@
1
- from typing import Dict
2
-
3
- import base64
4
- import json
5
- import requests
6
- import random
7
- import time
8
- import sys
9
-
10
- from .utils import safe_requests_wrapper, TODOException
11
-
12
-
13
- class OuterboundsSecretsException(Exception):
14
- pass
15
-
16
-
17
- class SecretNotFound(OuterboundsSecretsException):
18
- pass
19
-
20
-
21
- class OuterboundsSecretsApiResponse:
22
- def __init__(self, response):
23
- self.response = response
24
-
25
- @property
26
- def secret_resource_id(self):
27
- return self.response["secret_resource_id"]
28
-
29
- @property
30
- def secret_backend_type(self):
31
- return self.response["secret_backend_type"]
32
-
33
-
34
- class SecretRetriever:
35
- def get_secret_as_dict(self, secret_id, options={}, role=None):
36
- """
37
- Supports a special way of specifying secrets sources in outerbounds using the format:
38
- @secrets(sources=["outerbounds.<integrations_name>"])
39
-
40
- When invoked it makes a requests to the integrations secrets metadata endpoint on the
41
- keywest server to get the cloud resource id for a secret. It then uses that to invoke
42
- secrets manager on the core oss and returns the secrets.
43
- """
44
- headers = {"Content-Type": "application/json", "Connection": "keep-alive"}
45
- perimeter, integrations_url = self._get_secret_configs()
46
- integration_name = secret_id
47
- request_payload = {
48
- "perimeter_name": perimeter,
49
- "integration_name": integration_name,
50
- }
51
- response = self._make_request(integrations_url, headers, request_payload)
52
- secret_resource_id = response.secret_resource_id
53
- secret_backend_type = response.secret_backend_type
54
-
55
- from metaflow.plugins.secrets.secrets_decorator import (
56
- get_secrets_backend_provider,
57
- )
58
-
59
- secrets_provider = get_secrets_backend_provider(secret_backend_type)
60
- secret_dict = secrets_provider.get_secret_as_dict(
61
- secret_resource_id, options={}, role=role
62
- )
63
-
64
- # Outerbounds stores secrets as binaries. Hence we expect the returned secret to be
65
- # {<cloud-secret-name>: <base64 encoded full secret>}. We decode the secret here like:
66
- # 1. decode the base64 encoded full secret
67
- # 2. load the decoded secret as a json
68
- # 3. decode the base64 encoded values in the dict
69
- # 4. return the decoded dict
70
- binary_secret = next(iter(secret_dict.values()))
71
- return self._decode_secret(binary_secret)
72
-
73
- def _is_base64_encoded(self, data):
74
- try:
75
- if isinstance(data, str):
76
- # Check if the string can be base64 decoded
77
- base64.b64decode(data).decode("utf-8")
78
- return True
79
- return False
80
- except Exception:
81
- return False
82
-
83
- def _decode_secret(self, secret):
84
- try:
85
- result = {}
86
- secret_str = secret
87
- if self._is_base64_encoded(secret):
88
- # we check if the secret string is base64 encoded because the returned secret from
89
- # AWS secret manager is base64 encoded while the secret from GCP is not
90
- secret_str = base64.b64decode(secret).decode("utf-8")
91
-
92
- secret_dict = json.loads(secret_str)
93
- for key, value in secret_dict.items():
94
- result[key] = base64.b64decode(value).decode("utf-8")
95
-
96
- return result
97
- except Exception as e:
98
- raise OuterboundsSecretsException(f"Error decoding secret: {e}")
99
-
100
- def _get_secret_configs(self):
101
- from metaflow_extensions.outerbounds.remote_config import init_config # type: ignore
102
- from os import environ
103
-
104
- conf = init_config()
105
- if "OBP_PERIMETER" in conf:
106
- perimeter = conf["OBP_PERIMETER"]
107
- else:
108
- # if the perimeter is not in metaflow config, try to get it from the environment
109
- perimeter = environ.get("OBP_PERIMETER", "")
110
-
111
- if "OBP_INTEGRATIONS_URL" in conf:
112
- integrations_url = conf["OBP_INTEGRATIONS_URL"]
113
- else:
114
- # if the integrations is not in metaflow config, try to get it from the environment
115
- integrations_url = environ.get("OBP_INTEGRATIONS_URL", "")
116
-
117
- if not perimeter:
118
- raise OuterboundsSecretsException(
119
- "No perimeter set. Please make sure to run `outerbounds configure <...>` command which can be found on the Ourebounds UI or reach out to your Outerbounds support team."
120
- )
121
-
122
- if not integrations_url:
123
- raise OuterboundsSecretsException(
124
- "No integrations url set. Please notify your Outerbounds support team about this issue."
125
- )
126
-
127
- integrations_secrets_metadata_url = f"{integrations_url}/secrets/metadata"
128
- return perimeter, integrations_secrets_metadata_url
129
-
130
- def _make_request(self, url, headers: Dict, payload: Dict):
131
- try:
132
- from metaflow.metaflow_config import SERVICE_HEADERS
133
-
134
- request_headers = {**headers, **(SERVICE_HEADERS or {})}
135
- except ImportError:
136
- raise OuterboundsSecretsException(
137
- "Failed to create app: No Metaflow service headers found"
138
- )
139
-
140
- response = safe_requests_wrapper(
141
- requests.get,
142
- url,
143
- data=json.dumps(payload),
144
- headers=request_headers,
145
- conn_error_retries=5,
146
- retryable_status_codes=[409],
147
- )
148
- self._handle_error_response(response)
149
- return OuterboundsSecretsApiResponse(response.json())
150
-
151
- @staticmethod
152
- def _handle_error_response(response: requests.Response):
153
- if response.status_code >= 500:
154
- raise OuterboundsSecretsException(
155
- f"Server error: {response.text}. Please reach out to your Outerbounds support team."
156
- )
157
- status_code = response.status_code
158
- if status_code == 404:
159
- raise SecretNotFound(f"Secret not found: {response.text}")
160
-
161
- if status_code >= 400:
162
- raise OuterboundsSecretsException(
163
- f"status_code={status_code}\t\n\t\t{response.text}"
164
- )
outerbounds/apps/utils.py DELETED
@@ -1,234 +0,0 @@
1
- import random
2
- import time
3
- import sys
4
- import json
5
- import requests
6
- from typing import Optional
7
-
8
- # This click import is not used to construct any ob
9
- # package cli. Its used only for printing stuff.
10
- # So we can use the static metaflow._vendor import path
11
- from metaflow._vendor import click
12
- from .app_config import CAPSULE_DEBUG
13
- import sys
14
- import threading
15
- import time
16
- import logging
17
- import itertools
18
- from typing import Union, Callable, Any, List
19
-
20
- # TODO: remove vendor'd dependency where.
21
- from outerbounds._vendor.spinner import (
22
- Spinners,
23
- )
24
-
25
-
26
- class MultiStepSpinner:
27
- """
28
- A spinner that supports multi-step progress and configurable alignment.
29
-
30
- Parameters
31
- ----------
32
- spinner : Spinners
33
- Which spinner frames/interval to use.
34
- text : str
35
- Static text to display beside the spinner.
36
- color : str, optional
37
- Click color name.
38
- align : {'left','right'}
39
- Whether to render the spinner to the left (default) or right of the text.
40
- """
41
-
42
- def __init__(
43
- self,
44
- spinner: Spinners = Spinners.dots,
45
- text: str = "",
46
- color: Optional[str] = None,
47
- align: str = "right",
48
- file=sys.stdout,
49
- ):
50
- cfg = spinner.value
51
- self.frames = cfg["frames"]
52
- self.interval = float(cfg["interval"]) / 1000.0 # type: ignore
53
- self.text = text
54
- self.color = color
55
- if align not in ("left", "right"):
56
- raise ValueError("align must be 'left' or 'right'")
57
- self.align = align
58
- self._write_file = file
59
- # precompute clear length: max frame width + space + text length
60
- max_frame = max(self.frames, key=lambda x: len(x)) # type: ignore
61
- self.clear_len = len(self.main_text) + len(max_frame) + 1
62
-
63
- self._stop_evt = threading.Event()
64
- self._pause_evt = threading.Event()
65
- self._thread = None
66
- self._write_lock = threading.Lock()
67
-
68
- @property
69
- def main_text(self):
70
- # if self.text is a callable then call it
71
- if callable(self.text):
72
- return self.text()
73
- return self.text
74
-
75
- def _spin(self):
76
- for frame in itertools.cycle(self.frames):
77
- if self._stop_evt.is_set():
78
- break
79
- if self._pause_evt.is_set():
80
- time.sleep(0.05)
81
- continue
82
-
83
- # ---- Core logging critical section ----
84
- with self._write_lock:
85
- symbol = click.style(frame, fg=self.color) if self.color else frame
86
- if self.align == "left":
87
- msg = f"{symbol} {self.main_text}"
88
- else:
89
- msg = f"{self.main_text} {symbol}"
90
-
91
- click.echo(msg, nl=False, file=self._write_file)
92
- click.echo("\r", nl=False, file=self._write_file)
93
- self._write_file.flush()
94
- # ---- End of critical section ----
95
- time.sleep(self.interval)
96
- # clear the line when done
97
- self._clear_line()
98
-
99
- def _clear_line(self):
100
- with self._write_lock:
101
- click.echo(" " * self.clear_len, nl=False, file=self._write_file)
102
- click.echo("\r", nl=False, file=self._write_file)
103
- self._write_file.flush()
104
-
105
- def start(self):
106
- if self._thread and self._thread.is_alive():
107
- return
108
- self._stop_evt.clear()
109
- self._pause_evt.clear()
110
- self._thread = threading.Thread(target=self._spin, daemon=True)
111
- self._thread.start()
112
-
113
- def stop(self):
114
- self._stop_evt.set()
115
- if self._thread:
116
- self._thread.join()
117
-
118
- def log(self, *messages: str):
119
- """Pause the spinner, emit a ✔ + message, then resume."""
120
- self._pause_evt.set()
121
- self._clear_line()
122
- # ---- Core logging critical section ----
123
- with self._write_lock:
124
- self._write_file.flush()
125
- for message in messages:
126
- click.echo(f"{message}", file=self._write_file, nl=True)
127
- self._write_file.flush()
128
- # ---- End of critical section ----
129
- self._pause_evt.clear()
130
-
131
- def __enter__(self):
132
- self.start()
133
- return self
134
-
135
- def __exit__(self, exc_type, exc, tb):
136
- self.stop()
137
-
138
-
139
- class SpinnerLogHandler(logging.Handler):
140
- def __init__(self, spinner: MultiStepSpinner, *args, **kwargs):
141
- super().__init__(*args, **kwargs)
142
- self.spinner = spinner
143
-
144
- def emit(self, record):
145
- msg = self.format(record)
146
- self.spinner.log(msg)
147
-
148
-
149
- class MaximumRetriesExceeded(Exception):
150
- def __init__(self, url, method, status_code, text):
151
- self.url = url
152
- self.method = method
153
- self.status_code = status_code
154
- self.text = text
155
-
156
- def __str__(self):
157
- return f"Maximum retries exceeded for {self.url}[{self.method}] {self.status_code} {self.text}"
158
-
159
-
160
- class TODOException(Exception):
161
- pass
162
-
163
-
164
- requests_funcs = [
165
- requests.get,
166
- requests.post,
167
- requests.put,
168
- requests.delete,
169
- requests.patch,
170
- requests.head,
171
- requests.options,
172
- ]
173
-
174
-
175
- def safe_requests_wrapper(
176
- requests_module_fn,
177
- *args,
178
- conn_error_retries=2,
179
- retryable_status_codes=[409],
180
- logger_fn=None,
181
- **kwargs,
182
- ):
183
- """
184
- There are two categories of errors that we need to handle when dealing with any API server.
185
- 1. HTTP errors. These are are errors that are returned from the API server.
186
- - How to handle retries for this case will be application specific.
187
- 2. Errors when the API server may not be reachable (DNS resolution / network issues)
188
- - In this scenario, we know that something external to the API server is going wrong causing the issue.
189
- - Failing pre-maturely in the case might not be the best course of action since critical user jobs might crash on intermittent issues.
190
- - So in this case, we can just planely retry the request.
191
-
192
- This function handles the second case. It's a simple wrapper to handle the retry logic for connection errors.
193
- If this function is provided a `conn_error_retries` of 5, then the last retry will have waited 32 seconds.
194
- Generally this is a safe enough number of retries after which we can assume that something is really broken. Until then,
195
- there can be intermittent issues that would resolve themselves if we retry gracefully.
196
- """
197
- if requests_module_fn not in requests_funcs:
198
- raise ValueError(
199
- f"safe_requests_wrapper doesn't support {requests_module_fn.__name__}. You can only use the following functions: {requests_funcs}"
200
- )
201
-
202
- _num_retries = 0
203
- noise = random.uniform(-0.5, 0.5)
204
- response = None
205
- while _num_retries < conn_error_retries:
206
- try:
207
- response = requests_module_fn(*args, **kwargs)
208
- if response.status_code not in retryable_status_codes:
209
- return response
210
- if CAPSULE_DEBUG:
211
- if logger_fn:
212
- logger_fn(
213
- f"[outerbounds-debug] safe_requests_wrapper: {response.url}[{requests_module_fn.__name__}] {response.status_code} {response.text}",
214
- )
215
- else:
216
- print(
217
- f"[outerbounds-debug] safe_requests_wrapper: {response.url}[{requests_module_fn.__name__}] {response.status_code} {response.text}",
218
- file=sys.stderr,
219
- )
220
- _num_retries += 1
221
- time.sleep((2 ** (_num_retries + 1)) + noise)
222
- except requests.exceptions.ConnectionError:
223
- if _num_retries <= conn_error_retries - 1:
224
- # Exponential backoff with 2^(_num_retries+1) seconds
225
- time.sleep((2 ** (_num_retries + 1)) + noise)
226
- _num_retries += 1
227
- else:
228
- raise
229
- raise MaximumRetriesExceeded(
230
- response.url,
231
- requests_module_fn.__name__,
232
- response.status_code,
233
- response.text,
234
- )
@@ -1,22 +0,0 @@
1
- import os
2
- from .app_config import AppConfig, AppConfigError
3
- from .secrets import SecretRetriever, SecretNotFound
4
- from .dependencies import bake_deployment_image
5
-
6
-
7
- def deploy_validations(app_config: AppConfig, cache_dir: str, logger):
8
-
9
- # First check if the secrets for the app exist.
10
- app_secrets = app_config.get("secrets", [])
11
- secret_retriever = SecretRetriever()
12
- for secret in app_secrets:
13
- try:
14
- secret_retriever.get_secret_as_dict(secret)
15
- except SecretNotFound:
16
- raise AppConfigError(f"Secret not found: {secret}")
17
-
18
- # TODO: Next check if the compute pool exists.
19
-
20
-
21
- def run_validations(app_config: AppConfig):
22
- pass
@@ -1,3 +0,0 @@
1
- [console_scripts]
2
- outerbounds=outerbounds.cli_main:cli
3
-