outerbounds 0.3.174__py3-none-any.whl → 0.3.175rc0__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.
@@ -0,0 +1,164 @@
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
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 TODOException(
137
+ "Failed to create capsule: 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
+ )
@@ -0,0 +1,228 @@
1
+ import random
2
+ import time
3
+ import sys
4
+ import json
5
+ import requests
6
+ from outerbounds._vendor import click
7
+ from .app_config import CAPSULE_DEBUG
8
+
9
+
10
+ class MaximumRetriesExceeded(Exception):
11
+ def __init__(self, url, method, status_code, text):
12
+ self.url = url
13
+ self.method = method
14
+ self.status_code = status_code
15
+ self.text = text
16
+
17
+ def __str__(self):
18
+ return f"Maximum retries exceeded for {self.url}[{self.method}] {self.status_code} {self.text}"
19
+
20
+
21
+ class KeyValuePair(click.ParamType):
22
+ name = "KV-PAIR"
23
+
24
+ def convert(self, value, param, ctx):
25
+ # Parse a string of the form KEY=VALUE into a dict {KEY: VALUE}
26
+ if len(value.split("=", 1)) != 2:
27
+ self.fail(
28
+ f"Invalid format for {value}. Expected format: KEY=VALUE", param, ctx
29
+ )
30
+
31
+ key, _value = value.split("=", 1)
32
+ try:
33
+ return {key: json.loads(_value)}
34
+ except json.JSONDecodeError:
35
+ return {key: _value}
36
+ except Exception as e:
37
+ self.fail(f"Invalid value for {value}. Error: {e}", param, ctx)
38
+
39
+ def __str__(self):
40
+ return repr(self)
41
+
42
+ def __repr__(self):
43
+ return "KV-PAIR"
44
+
45
+
46
+ class MountMetaflowArtifact(click.ParamType):
47
+ name = "MOUNT-METAFLOW-ARTIFACT"
48
+
49
+ def convert(self, value, param, ctx):
50
+ """
51
+ Convert a string like "flow=MyFlow,artifact=my_model,path=/tmp/abc" or
52
+ "pathspec=MyFlow/123/foo/345/my_model,path=/tmp/abc" to a dict.
53
+ """
54
+ artifact_dict = {}
55
+ parts = value.split(",")
56
+
57
+ for part in parts:
58
+ if "=" not in part:
59
+ self.fail(
60
+ f"Invalid format in part '{part}'. Expected 'key=value'", param, ctx
61
+ )
62
+
63
+ key, val = part.split("=", 1)
64
+ artifact_dict[key.strip()] = val.strip()
65
+
66
+ # Validate required fields
67
+ if "pathspec" in artifact_dict:
68
+ if "path" not in artifact_dict:
69
+ self.fail(
70
+ "When using 'pathspec', you must also specify 'path'", param, ctx
71
+ )
72
+
73
+ # Return as pathspec format
74
+ return {
75
+ "pathspec": artifact_dict["pathspec"],
76
+ "path": artifact_dict["path"],
77
+ }
78
+ elif (
79
+ "flow" in artifact_dict
80
+ and "artifact" in artifact_dict
81
+ and "path" in artifact_dict
82
+ ):
83
+ # Return as flow/artifact format
84
+ result = {
85
+ "flow": artifact_dict["flow"],
86
+ "artifact": artifact_dict["artifact"],
87
+ "path": artifact_dict["path"],
88
+ }
89
+
90
+ # Add optional namespace if provided
91
+ if "namespace" in artifact_dict:
92
+ result["namespace"] = artifact_dict["namespace"]
93
+
94
+ return result
95
+ else:
96
+ self.fail(
97
+ "Invalid format. Must be either 'flow=X,artifact=Y,path=Z' or 'pathspec=X,path=Z'",
98
+ param,
99
+ ctx,
100
+ )
101
+
102
+ def __str__(self):
103
+ return repr(self)
104
+
105
+ def __repr__(self):
106
+ return "MOUNT-METAFLOW-ARTIFACT"
107
+
108
+
109
+ class MountSecret(click.ParamType):
110
+ name = "MOUNT-SECRET"
111
+
112
+ def convert(self, value, param, ctx):
113
+ """
114
+ Convert a string like "id=my_secret,path=/tmp/secret" to a dict.
115
+ """
116
+ secret_dict = {}
117
+ parts = value.split(",")
118
+
119
+ for part in parts:
120
+ if "=" not in part:
121
+ self.fail(
122
+ f"Invalid format in part '{part}'. Expected 'key=value'", param, ctx
123
+ )
124
+
125
+ key, val = part.split("=", 1)
126
+ secret_dict[key.strip()] = val.strip()
127
+
128
+ # Validate required fields
129
+ if "id" in secret_dict and "path" in secret_dict:
130
+ return {"id": secret_dict["id"], "path": secret_dict["path"]}
131
+ else:
132
+ self.fail("Invalid format. Must be 'key=X,path=Y'", param, ctx)
133
+
134
+ def __str__(self):
135
+ return repr(self)
136
+
137
+ def __repr__(self):
138
+ return "MOUNT-SECRET"
139
+
140
+
141
+ class CommaSeparatedList(click.ParamType):
142
+ name = "COMMA-SEPARATED-LIST"
143
+
144
+ def convert(self, value, param, ctx):
145
+ return value.split(",")
146
+
147
+ def __str__(self):
148
+ return repr(self)
149
+
150
+ def __repr__(self):
151
+ return "COMMA-SEPARATED-LIST"
152
+
153
+
154
+ KVPairType = KeyValuePair()
155
+ MetaflowArtifactType = MountMetaflowArtifact()
156
+ SecretMountType = MountSecret()
157
+ CommaSeparatedListType = CommaSeparatedList()
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
+ **kwargs,
181
+ ):
182
+ """
183
+ There are two categories of errors that we need to handle when dealing with any API server.
184
+ 1. HTTP errors. These are are errors that are returned from the API server.
185
+ - How to handle retries for this case will be application specific.
186
+ 2. Errors when the API server may not be reachable (DNS resolution / network issues)
187
+ - In this scenario, we know that something external to the API server is going wrong causing the issue.
188
+ - Failing pre-maturely in the case might not be the best course of action since critical user jobs might crash on intermittent issues.
189
+ - So in this case, we can just planely retry the request.
190
+
191
+ This function handles the second case. It's a simple wrapper to handle the retry logic for connection errors.
192
+ If this function is provided a `conn_error_retries` of 5, then the last retry will have waited 32 seconds.
193
+ Generally this is a safe enough number of retries after which we can assume that something is really broken. Until then,
194
+ there can be intermittent issues that would resolve themselves if we retry gracefully.
195
+ """
196
+ if requests_module_fn not in requests_funcs:
197
+ raise TODOException(
198
+ f"safe_requests_wrapper doesn't support {requests_module_fn.__name__}. You can only use the following functions: {requests_funcs}"
199
+ )
200
+
201
+ _num_retries = 0
202
+ noise = random.uniform(-0.5, 0.5)
203
+ response = None
204
+ while _num_retries < conn_error_retries:
205
+ try:
206
+ response = requests_module_fn(*args, **kwargs)
207
+ if response.status_code not in retryable_status_codes:
208
+ return response
209
+ if CAPSULE_DEBUG:
210
+ print(
211
+ f"[outerbounds-debug] safe_requests_wrapper: {response.url}[{requests_module_fn.__name__}] {response.status_code} {response.text}",
212
+ file=sys.stderr,
213
+ )
214
+ _num_retries += 1
215
+ time.sleep((2 ** (_num_retries + 1)) + noise)
216
+ except requests.exceptions.ConnectionError:
217
+ if _num_retries <= conn_error_retries - 1:
218
+ # Exponential backoff with 2^(_num_retries+1) seconds
219
+ time.sleep((2 ** (_num_retries + 1)) + noise)
220
+ _num_retries += 1
221
+ else:
222
+ raise
223
+ raise MaximumRetriesExceeded(
224
+ response.url,
225
+ requests_module_fn.__name__,
226
+ response.status_code,
227
+ response.text,
228
+ )
@@ -0,0 +1,34 @@
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
+ logger("🍞 Baking Docker Image")
20
+ baking_status = bake_deployment_image(
21
+ app_config=app_config,
22
+ cache_file_path=os.path.join(cache_dir, "image_cache"),
23
+ logger=logger,
24
+ )
25
+ app_config.set_state(
26
+ "image",
27
+ baking_status.resolved_image,
28
+ )
29
+ app_config.set_state("python_path", baking_status.python_path)
30
+ logger("🐳 Using The Docker Image : %s" % app_config.get_state("image"))
31
+
32
+
33
+ def run_validations(app_config: AppConfig):
34
+ pass
@@ -8,6 +8,7 @@ import shutil
8
8
  import subprocess
9
9
 
10
10
  from ..utils import metaflowconfig
11
+ from ..apps.app_cli import app
11
12
 
12
13
  APP_READY_POLL_TIMEOUT_SECONDS = 300
13
14
  # Even after our backend validates that the app routes are ready, it takes a few seconds for
@@ -20,11 +21,6 @@ def cli(**kwargs):
20
21
  pass
21
22
 
22
23
 
23
- @click.group(help="Manage apps")
24
- def app(**kwargs):
25
- pass
26
-
27
-
28
24
  @app.command(help="Start an app using a port and a name")
29
25
  @click.option(
30
26
  "-d",
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: outerbounds
3
- Version: 0.3.174
3
+ Version: 0.3.175rc0
4
4
  Summary: More Data Science, Less Administration
5
5
  License: Proprietary
6
6
  Keywords: data science,machine learning,MLOps
@@ -29,8 +29,8 @@ Requires-Dist: google-cloud-secret-manager (>=2.20.0,<3.0.0) ; extra == "gcp"
29
29
  Requires-Dist: google-cloud-storage (>=2.14.0,<3.0.0) ; extra == "gcp"
30
30
  Requires-Dist: metaflow-checkpoint (==0.2.1)
31
31
  Requires-Dist: ob-metaflow (==2.15.14.1)
32
- Requires-Dist: ob-metaflow-extensions (==1.1.161)
33
- Requires-Dist: ob-metaflow-stubs (==6.0.3.174)
32
+ Requires-Dist: ob-metaflow-extensions (==1.1.162rc0)
33
+ Requires-Dist: ob-metaflow-stubs (==6.0.3.175rc0)
34
34
  Requires-Dist: opentelemetry-distro (>=0.41b0) ; extra == "otel"
35
35
  Requires-Dist: opentelemetry-exporter-otlp-proto-http (>=1.20.0) ; extra == "otel"
36
36
  Requires-Dist: opentelemetry-instrumentation-requests (>=0.41b0) ; extra == "otel"
@@ -39,9 +39,25 @@ outerbounds/_vendor/yaml/resolver.py,sha256=dPhU1d7G1JCMktPFvNhyqwj2oNvx1yf_Jfa3
39
39
  outerbounds/_vendor/yaml/scanner.py,sha256=ZcI8IngR56PaQ0m27WU2vxCqmDCuRjz-hr7pirbMPuw,52982
40
40
  outerbounds/_vendor/yaml/serializer.py,sha256=8wFZRy9SsQSktF_f9OOroroqsh4qVUe53ry07P9UgCc,4368
41
41
  outerbounds/_vendor/yaml/tokens.py,sha256=JBSu38wihGr4l73JwbfMA7Ks1-X84g8-NskTz7KwPmA,2578
42
+ outerbounds/apps/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
43
+ outerbounds/apps/app_cli.py,sha256=oUsPGDr3jnW5l7h4Mp1I4WnRZAanXN1se9_aQ1ybhNQ,17559
44
+ outerbounds/apps/app_config.py,sha256=KBmW9grhiuG9XZG-R0GZkM-024cjj6ztGzOX_2wZW34,11291
45
+ outerbounds/apps/artifacts.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
46
+ outerbounds/apps/capsule.py,sha256=n23uJi9877IVnArgqdq_ES_c2vAql8rzVm7jlTYUr1M,13351
47
+ outerbounds/apps/cli_to_config.py,sha256=IjPHeH1lC7l9WPkNLQIWU7obRS3G0G8aTNVZemUvmuw,3168
48
+ outerbounds/apps/code_package/__init__.py,sha256=8McF7pgx8ghvjRnazp2Qktlxi9yYwNiwESSQrk-2oW8,68
49
+ outerbounds/apps/code_package/code_packager.py,sha256=SQDBXKwizzpag5GpwoZpvvkyPOodRSQwk2ecAAfO0HI,23316
50
+ outerbounds/apps/code_package/examples.py,sha256=aF8qKIJxCVv_ugcShQjqUsXKKKMsm1oMkQIl8w3QKuw,4016
51
+ outerbounds/apps/config_schema.yaml,sha256=D-qopf3mGZusa4n5GIbrssoJHS3v96_yponFEM127b4,8275
52
+ outerbounds/apps/dependencies.py,sha256=SqvdFQdFZZW0wXX_CHMHCrfE0TwaRkTvGCRbQ2Mx3q0,3935
53
+ outerbounds/apps/deployer.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
54
+ outerbounds/apps/experimental/__init__.py,sha256=12L_FzZyzv162uo4I6cmlrxat7feUtIu_kxbObTJZTA,3059
55
+ outerbounds/apps/secrets.py,sha256=27qf04lOBqRjvcswj0ldHOmntP2T6SEjtMJtkJQ_GUg,6100
56
+ outerbounds/apps/utils.py,sha256=JymjsgpU0osF-eDvstFS9zkM7bqliJdqAEV7kAjqxCM,7298
57
+ outerbounds/apps/validations.py,sha256=AVEw9eCvkzqq1m5ZC8btaWrSR6kWYKzarELfrASuAwQ,1117
42
58
  outerbounds/cli_main.py,sha256=e9UMnPysmc7gbrimq2I4KfltggyU7pw59Cn9aEguVcU,74
43
59
  outerbounds/command_groups/__init__.py,sha256=QPWtj5wDRTINDxVUL7XPqG3HoxHNvYOg08EnuSZB2Hc,21
44
- outerbounds/command_groups/apps_cli.py,sha256=v9OlQ1b4BGB-cBZiHB6W5gDocDoMmrQ7zdK11QiJ-B8,20847
60
+ outerbounds/command_groups/apps_cli.py,sha256=weXYgUbTVIxMSweLVdod_C1laiB32YKwYhf22OfqQJE,20815
45
61
  outerbounds/command_groups/cli.py,sha256=de4_QY1UeoKX6y-IXIbmklAi6bz0DsdBSmAoCg6lq1o,482
46
62
  outerbounds/command_groups/fast_bakery_cli.py,sha256=5kja7v6C651XAY6dsP_IkBPJQgfU4hA4S9yTOiVPhW0,6213
47
63
  outerbounds/command_groups/local_setup_cli.py,sha256=tuuqJRXQ_guEwOuQSIf9wkUU0yg8yAs31myGViAK15s,36364
@@ -55,7 +71,7 @@ outerbounds/utils/metaflowconfig.py,sha256=l2vJbgPkLISU-XPGZFaC8ZKmYFyJemlD6bwB-
55
71
  outerbounds/utils/schema.py,sha256=lMUr9kNgn9wy-sO_t_Tlxmbt63yLeN4b0xQXbDUDj4A,2331
56
72
  outerbounds/utils/utils.py,sha256=4Z8cszNob_8kDYCLNTrP-wWads_S_MdL3Uj3ju4mEsk,501
57
73
  outerbounds/vendor.py,sha256=gRLRJNXtZBeUpPEog0LOeIsl6GosaFFbCxUvR4bW6IQ,5093
58
- outerbounds-0.3.174.dist-info/METADATA,sha256=iZlYVROqXN-KK7dEtyZASVkm53ICK8Jq4M5fNElIrR8,1837
59
- outerbounds-0.3.174.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
60
- outerbounds-0.3.174.dist-info/entry_points.txt,sha256=7ye0281PKlvqxu15rjw60zKg2pMsXI49_A8BmGqIqBw,47
61
- outerbounds-0.3.174.dist-info/RECORD,,
74
+ outerbounds-0.3.175rc0.dist-info/METADATA,sha256=c69bE_dY1O_vbcTLpQ0FWj2xL0rF1sIvuI-e3A8MTXA,1846
75
+ outerbounds-0.3.175rc0.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
76
+ outerbounds-0.3.175rc0.dist-info/entry_points.txt,sha256=7ye0281PKlvqxu15rjw60zKg2pMsXI49_A8BmGqIqBw,47
77
+ outerbounds-0.3.175rc0.dist-info/RECORD,,