ob-metaflow-extensions 1.1.45rc3__py2.py3-none-any.whl → 1.5.1__py2.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.

Potentially problematic release.


This version of ob-metaflow-extensions might be problematic. Click here for more details.

Files changed (128) hide show
  1. metaflow_extensions/outerbounds/__init__.py +1 -7
  2. metaflow_extensions/outerbounds/config/__init__.py +35 -0
  3. metaflow_extensions/outerbounds/plugins/__init__.py +186 -57
  4. metaflow_extensions/outerbounds/plugins/apps/__init__.py +0 -0
  5. metaflow_extensions/outerbounds/plugins/apps/app_cli.py +0 -0
  6. metaflow_extensions/outerbounds/plugins/apps/app_utils.py +187 -0
  7. metaflow_extensions/outerbounds/plugins/apps/consts.py +3 -0
  8. metaflow_extensions/outerbounds/plugins/apps/core/__init__.py +15 -0
  9. metaflow_extensions/outerbounds/plugins/apps/core/_state_machine.py +506 -0
  10. metaflow_extensions/outerbounds/plugins/apps/core/_vendor/__init__.py +0 -0
  11. metaflow_extensions/outerbounds/plugins/apps/core/_vendor/spinner/__init__.py +4 -0
  12. metaflow_extensions/outerbounds/plugins/apps/core/_vendor/spinner/spinners.py +478 -0
  13. metaflow_extensions/outerbounds/plugins/apps/core/app_config.py +128 -0
  14. metaflow_extensions/outerbounds/plugins/apps/core/app_deploy_decorator.py +330 -0
  15. metaflow_extensions/outerbounds/plugins/apps/core/artifacts.py +0 -0
  16. metaflow_extensions/outerbounds/plugins/apps/core/capsule.py +958 -0
  17. metaflow_extensions/outerbounds/plugins/apps/core/click_importer.py +24 -0
  18. metaflow_extensions/outerbounds/plugins/apps/core/code_package/__init__.py +3 -0
  19. metaflow_extensions/outerbounds/plugins/apps/core/code_package/code_packager.py +618 -0
  20. metaflow_extensions/outerbounds/plugins/apps/core/code_package/examples.py +125 -0
  21. metaflow_extensions/outerbounds/plugins/apps/core/config/__init__.py +15 -0
  22. metaflow_extensions/outerbounds/plugins/apps/core/config/cli_generator.py +165 -0
  23. metaflow_extensions/outerbounds/plugins/apps/core/config/config_utils.py +966 -0
  24. metaflow_extensions/outerbounds/plugins/apps/core/config/schema_export.py +299 -0
  25. metaflow_extensions/outerbounds/plugins/apps/core/config/typed_configs.py +233 -0
  26. metaflow_extensions/outerbounds/plugins/apps/core/config/typed_init_generator.py +537 -0
  27. metaflow_extensions/outerbounds/plugins/apps/core/config/unified_config.py +1125 -0
  28. metaflow_extensions/outerbounds/plugins/apps/core/config_schema.yaml +337 -0
  29. metaflow_extensions/outerbounds/plugins/apps/core/dependencies.py +115 -0
  30. metaflow_extensions/outerbounds/plugins/apps/core/deployer.py +959 -0
  31. metaflow_extensions/outerbounds/plugins/apps/core/experimental/__init__.py +89 -0
  32. metaflow_extensions/outerbounds/plugins/apps/core/perimeters.py +87 -0
  33. metaflow_extensions/outerbounds/plugins/apps/core/secrets.py +164 -0
  34. metaflow_extensions/outerbounds/plugins/apps/core/utils.py +233 -0
  35. metaflow_extensions/outerbounds/plugins/apps/core/validations.py +17 -0
  36. metaflow_extensions/outerbounds/plugins/apps/deploy_decorator.py +201 -0
  37. metaflow_extensions/outerbounds/plugins/apps/supervisord_utils.py +243 -0
  38. metaflow_extensions/outerbounds/plugins/auth_server.py +28 -8
  39. metaflow_extensions/outerbounds/plugins/aws/__init__.py +4 -0
  40. metaflow_extensions/outerbounds/plugins/aws/assume_role.py +3 -0
  41. metaflow_extensions/outerbounds/plugins/aws/assume_role_decorator.py +118 -0
  42. metaflow_extensions/outerbounds/plugins/card_utilities/__init__.py +0 -0
  43. metaflow_extensions/outerbounds/plugins/card_utilities/async_cards.py +142 -0
  44. metaflow_extensions/outerbounds/plugins/card_utilities/extra_components.py +545 -0
  45. metaflow_extensions/outerbounds/plugins/card_utilities/injector.py +70 -0
  46. metaflow_extensions/outerbounds/plugins/checkpoint_datastores/__init__.py +2 -0
  47. metaflow_extensions/outerbounds/plugins/checkpoint_datastores/coreweave.py +71 -0
  48. metaflow_extensions/outerbounds/plugins/checkpoint_datastores/external_chckpt.py +85 -0
  49. metaflow_extensions/outerbounds/plugins/checkpoint_datastores/nebius.py +73 -0
  50. metaflow_extensions/outerbounds/plugins/fast_bakery/__init__.py +0 -0
  51. metaflow_extensions/outerbounds/plugins/fast_bakery/baker.py +110 -0
  52. metaflow_extensions/outerbounds/plugins/fast_bakery/docker_environment.py +391 -0
  53. metaflow_extensions/outerbounds/plugins/fast_bakery/fast_bakery.py +188 -0
  54. metaflow_extensions/outerbounds/plugins/fast_bakery/fast_bakery_cli.py +54 -0
  55. metaflow_extensions/outerbounds/plugins/fast_bakery/fast_bakery_decorator.py +50 -0
  56. metaflow_extensions/outerbounds/plugins/kubernetes/kubernetes_client.py +79 -0
  57. metaflow_extensions/outerbounds/plugins/kubernetes/pod_killer.py +374 -0
  58. metaflow_extensions/outerbounds/plugins/nim/card.py +140 -0
  59. metaflow_extensions/outerbounds/plugins/nim/nim_decorator.py +101 -0
  60. metaflow_extensions/outerbounds/plugins/nim/nim_manager.py +379 -0
  61. metaflow_extensions/outerbounds/plugins/nim/utils.py +36 -0
  62. metaflow_extensions/outerbounds/plugins/nvcf/__init__.py +0 -0
  63. metaflow_extensions/outerbounds/plugins/nvcf/constants.py +3 -0
  64. metaflow_extensions/outerbounds/plugins/nvcf/exceptions.py +94 -0
  65. metaflow_extensions/outerbounds/plugins/nvcf/heartbeat_store.py +178 -0
  66. metaflow_extensions/outerbounds/plugins/nvcf/nvcf.py +417 -0
  67. metaflow_extensions/outerbounds/plugins/nvcf/nvcf_cli.py +280 -0
  68. metaflow_extensions/outerbounds/plugins/nvcf/nvcf_decorator.py +242 -0
  69. metaflow_extensions/outerbounds/plugins/nvcf/utils.py +6 -0
  70. metaflow_extensions/outerbounds/plugins/nvct/__init__.py +0 -0
  71. metaflow_extensions/outerbounds/plugins/nvct/exceptions.py +71 -0
  72. metaflow_extensions/outerbounds/plugins/nvct/nvct.py +131 -0
  73. metaflow_extensions/outerbounds/plugins/nvct/nvct_cli.py +289 -0
  74. metaflow_extensions/outerbounds/plugins/nvct/nvct_decorator.py +286 -0
  75. metaflow_extensions/outerbounds/plugins/nvct/nvct_runner.py +218 -0
  76. metaflow_extensions/outerbounds/plugins/nvct/utils.py +29 -0
  77. metaflow_extensions/outerbounds/plugins/ollama/__init__.py +225 -0
  78. metaflow_extensions/outerbounds/plugins/ollama/constants.py +1 -0
  79. metaflow_extensions/outerbounds/plugins/ollama/exceptions.py +22 -0
  80. metaflow_extensions/outerbounds/plugins/ollama/ollama.py +1924 -0
  81. metaflow_extensions/outerbounds/plugins/ollama/status_card.py +292 -0
  82. metaflow_extensions/outerbounds/plugins/optuna/__init__.py +48 -0
  83. metaflow_extensions/outerbounds/plugins/perimeters.py +19 -5
  84. metaflow_extensions/outerbounds/plugins/profilers/deco_injector.py +70 -0
  85. metaflow_extensions/outerbounds/plugins/profilers/gpu_profile_decorator.py +88 -0
  86. metaflow_extensions/outerbounds/plugins/profilers/simple_card_decorator.py +96 -0
  87. metaflow_extensions/outerbounds/plugins/s3_proxy/__init__.py +7 -0
  88. metaflow_extensions/outerbounds/plugins/s3_proxy/binary_caller.py +132 -0
  89. metaflow_extensions/outerbounds/plugins/s3_proxy/constants.py +11 -0
  90. metaflow_extensions/outerbounds/plugins/s3_proxy/exceptions.py +13 -0
  91. metaflow_extensions/outerbounds/plugins/s3_proxy/proxy_bootstrap.py +59 -0
  92. metaflow_extensions/outerbounds/plugins/s3_proxy/s3_proxy_api.py +93 -0
  93. metaflow_extensions/outerbounds/plugins/s3_proxy/s3_proxy_decorator.py +250 -0
  94. metaflow_extensions/outerbounds/plugins/s3_proxy/s3_proxy_manager.py +225 -0
  95. metaflow_extensions/outerbounds/plugins/secrets/__init__.py +0 -0
  96. metaflow_extensions/outerbounds/plugins/secrets/secrets.py +204 -0
  97. metaflow_extensions/outerbounds/plugins/snowflake/__init__.py +3 -0
  98. metaflow_extensions/outerbounds/plugins/snowflake/snowflake.py +378 -0
  99. metaflow_extensions/outerbounds/plugins/snowpark/__init__.py +0 -0
  100. metaflow_extensions/outerbounds/plugins/snowpark/snowpark.py +309 -0
  101. metaflow_extensions/outerbounds/plugins/snowpark/snowpark_cli.py +277 -0
  102. metaflow_extensions/outerbounds/plugins/snowpark/snowpark_client.py +150 -0
  103. metaflow_extensions/outerbounds/plugins/snowpark/snowpark_decorator.py +273 -0
  104. metaflow_extensions/outerbounds/plugins/snowpark/snowpark_exceptions.py +13 -0
  105. metaflow_extensions/outerbounds/plugins/snowpark/snowpark_job.py +241 -0
  106. metaflow_extensions/outerbounds/plugins/snowpark/snowpark_service_spec.py +259 -0
  107. metaflow_extensions/outerbounds/plugins/tensorboard/__init__.py +50 -0
  108. metaflow_extensions/outerbounds/plugins/torchtune/__init__.py +163 -0
  109. metaflow_extensions/outerbounds/plugins/vllm/__init__.py +255 -0
  110. metaflow_extensions/outerbounds/plugins/vllm/constants.py +1 -0
  111. metaflow_extensions/outerbounds/plugins/vllm/exceptions.py +1 -0
  112. metaflow_extensions/outerbounds/plugins/vllm/status_card.py +352 -0
  113. metaflow_extensions/outerbounds/plugins/vllm/vllm_manager.py +621 -0
  114. metaflow_extensions/outerbounds/profilers/gpu.py +131 -47
  115. metaflow_extensions/outerbounds/remote_config.py +53 -16
  116. metaflow_extensions/outerbounds/toplevel/global_aliases_for_metaflow_package.py +138 -2
  117. metaflow_extensions/outerbounds/toplevel/ob_internal.py +4 -0
  118. metaflow_extensions/outerbounds/toplevel/plugins/ollama/__init__.py +1 -0
  119. metaflow_extensions/outerbounds/toplevel/plugins/optuna/__init__.py +1 -0
  120. metaflow_extensions/outerbounds/toplevel/plugins/snowflake/__init__.py +1 -0
  121. metaflow_extensions/outerbounds/toplevel/plugins/torchtune/__init__.py +1 -0
  122. metaflow_extensions/outerbounds/toplevel/plugins/vllm/__init__.py +1 -0
  123. metaflow_extensions/outerbounds/toplevel/s3_proxy.py +88 -0
  124. {ob_metaflow_extensions-1.1.45rc3.dist-info → ob_metaflow_extensions-1.5.1.dist-info}/METADATA +2 -2
  125. ob_metaflow_extensions-1.5.1.dist-info/RECORD +133 -0
  126. ob_metaflow_extensions-1.1.45rc3.dist-info/RECORD +0 -19
  127. {ob_metaflow_extensions-1.1.45rc3.dist-info → ob_metaflow_extensions-1.5.1.dist-info}/WHEEL +0 -0
  128. {ob_metaflow_extensions-1.1.45rc3.dist-info → ob_metaflow_extensions-1.5.1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,132 @@
1
+ import sys
2
+ import os
3
+ import subprocess
4
+ from metaflow.mflog.mflog import decorate
5
+ from metaflow.mflog import TASK_LOG_SOURCE
6
+ from typing import Union, TextIO, BinaryIO, Callable, Optional
7
+ from queue import Queue, Empty
8
+ from concurrent.futures import ThreadPoolExecutor
9
+ import subprocess
10
+
11
+
12
+ def enqueue_output(file, queue):
13
+ for line in iter(file.readline, ""):
14
+ queue.put(line)
15
+ file.close()
16
+
17
+
18
+ def read_popen_pipes(p: subprocess.Popen):
19
+
20
+ with ThreadPoolExecutor(2) as pool:
21
+ q_stdout, q_stderr = Queue(), Queue()
22
+ pool.submit(enqueue_output, p.stdout, q_stdout)
23
+ pool.submit(enqueue_output, p.stderr, q_stderr)
24
+ while True:
25
+
26
+ if p.poll() is not None and q_stdout.empty() and q_stderr.empty():
27
+ break
28
+
29
+ out_line = err_line = ""
30
+
31
+ try:
32
+ out_line = q_stdout.get_nowait()
33
+ except Empty:
34
+ pass
35
+ try:
36
+ err_line = q_stderr.get_nowait()
37
+ except Empty:
38
+ pass
39
+
40
+ yield (out_line, err_line)
41
+
42
+
43
+ class LogBroadcaster:
44
+ def __init__(
45
+ self,
46
+ process: subprocess.Popen,
47
+ ):
48
+ self._process = process
49
+ self._file_descriptors_and_parsers = []
50
+
51
+ def add_channel(
52
+ self, file_path: str, parser: Optional[Callable[[str], str]] = None
53
+ ):
54
+ self._file_descriptors_and_parsers.append((open(file_path, "a"), parser))
55
+
56
+ def _broadcast_lines(self, out_line: str, err_line: str):
57
+ for file_descriptor, parser in self._file_descriptors_and_parsers:
58
+ if out_line != "":
59
+ if parser:
60
+ out_line = parser(out_line)
61
+ print(out_line, file=file_descriptor, end="", flush=True)
62
+ if err_line != "":
63
+ if parser:
64
+ err_line = parser(err_line)
65
+ print(err_line, file=file_descriptor, end="", flush=True)
66
+
67
+ def publish_line(self, out_line: str, err_line: str):
68
+ self._broadcast_lines(out_line, err_line)
69
+
70
+ def broadcast_logs_to_files(self):
71
+ for out_line, err_line in read_popen_pipes(self._process):
72
+ self._broadcast_lines(out_line, err_line)
73
+
74
+ self._process.wait()
75
+
76
+ for file_descriptor, _ in self._file_descriptors_and_parsers:
77
+ file_descriptor.close()
78
+
79
+
80
+ def run_with_mflog_capture(command, debug=False):
81
+ """
82
+ Run a subprocess with proper mflog integration for stdout/stderr capture.
83
+ This mimics what bash_capture_logs does but in Python.
84
+ """
85
+ # Get the log file paths from environment variables
86
+ stdout_path = os.environ.get("MFLOG_STDOUT")
87
+ stderr_path = os.environ.get("MFLOG_STDERR")
88
+
89
+ if not stdout_path or not stderr_path:
90
+ # Fallback to regular subprocess if mflog env vars aren't set
91
+ return subprocess.run(command, check=True, shell=True)
92
+
93
+ pipe = subprocess.PIPE if debug else subprocess.DEVNULL
94
+ # Start the subprocess with pipes
95
+ process = subprocess.Popen(
96
+ command,
97
+ shell=True,
98
+ stdout=pipe,
99
+ stderr=pipe,
100
+ text=False, # Use bytes for proper mflog handling
101
+ bufsize=0, # Unbuffered for real-time logging
102
+ )
103
+
104
+ broadcaster = LogBroadcaster(process)
105
+
106
+ broadcaster.add_channel(
107
+ stderr_path, lambda line: decorate(TASK_LOG_SOURCE, line).decode("utf-8")
108
+ )
109
+ broadcaster.publish_line(f"[S3 PROXY] Starting Fast S3 Proxy.....\n", "")
110
+ broadcaster.broadcast_logs_to_files()
111
+
112
+ # Check the return code and raise if non-zero
113
+ if process.returncode != 0:
114
+ raise subprocess.CalledProcessError(process.returncode, command)
115
+
116
+ return process.returncode
117
+
118
+
119
+ if __name__ == "__main__":
120
+ s3_proxy_binary_path = os.environ.get("S3_PROXY_BINARY_COMMAND")
121
+ s3_proxy_debug = bool(os.environ.get("S3_PROXY_BINARY_DEBUG", False))
122
+ if not s3_proxy_binary_path:
123
+ print("S3_PROXY_BINARY_COMMAND environment variable not set")
124
+ sys.exit(1)
125
+
126
+ try:
127
+ run_with_mflog_capture(s3_proxy_binary_path, debug=s3_proxy_debug)
128
+ except subprocess.CalledProcessError as e:
129
+ sys.exit(e.returncode)
130
+ except Exception as e:
131
+ print(f"Error running S3 proxy binary: {e}", file=sys.stderr)
132
+ sys.exit(1)
@@ -0,0 +1,11 @@
1
+ S3_PROXY_BINARY_URLS = {
2
+ "aarch64": "https://fast-s3-proxy.outerbounds.sh/linux-arm64/s3-proxy-0.1.1.gz",
3
+ "x86_64": "https://fast-s3-proxy.outerbounds.sh/linux-amd64/s3-proxy-0.1.1.gz",
4
+ }
5
+
6
+ DEFAULT_PROXY_PORT = 8081
7
+ DEFAULT_PROXY_HOST = "localhost"
8
+ S3_PROXY_WRITE_MODES = [
9
+ "origin-and-cache",
10
+ "origin",
11
+ ]
@@ -0,0 +1,13 @@
1
+ from metaflow.exception import MetaflowException
2
+
3
+
4
+ class S3ProxyException(MetaflowException):
5
+ headline = "S3 Proxy Error"
6
+
7
+
8
+ class S3ProxyConfigException(S3ProxyException):
9
+ headline = "S3 Proxy Configuration Error"
10
+
11
+
12
+ class S3ProxyApiException(S3ProxyException):
13
+ headline = "S3 Proxy API Error"
@@ -0,0 +1,59 @@
1
+ from .s3_proxy_manager import S3ProxyManager
2
+ from metaflow._vendor import click
3
+ from metaflow import JSONType
4
+ import json
5
+
6
+
7
+ @click.group()
8
+ def cli():
9
+ pass
10
+
11
+
12
+ @cli.command()
13
+ @click.option(
14
+ "--integration-name", type=str, help="The integration name", required=True
15
+ )
16
+ @click.option("--write-mode", type=str, help="The write mode")
17
+ @click.option("--debug", type=bool, help="The debug mode", default=False)
18
+ @click.option(
19
+ "--uc-proxy-cfg-write-path",
20
+ type=str,
21
+ help="The path to write the user code proxy config",
22
+ required=True,
23
+ )
24
+ @click.option(
25
+ "--proxy-status-write-path",
26
+ type=str,
27
+ help="The path to write the proxy status",
28
+ required=True,
29
+ )
30
+ def bootstrap(
31
+ integration_name,
32
+ write_mode,
33
+ debug,
34
+ uc_proxy_cfg_write_path,
35
+ proxy_status_write_path,
36
+ ):
37
+ manager = S3ProxyManager(
38
+ integration_name=integration_name,
39
+ write_mode=write_mode,
40
+ debug=debug,
41
+ )
42
+ user_code_proxy_config, proxy_pid, config_path, binary_path = manager.setup_proxy()
43
+ with open(uc_proxy_cfg_write_path, "w") as f:
44
+ f.write(json.dumps(user_code_proxy_config))
45
+ with open(proxy_status_write_path, "w") as f:
46
+ f.write(
47
+ json.dumps(
48
+ {
49
+ "proxy_pid": proxy_pid,
50
+ "config_path": config_path,
51
+ "binary_path": binary_path,
52
+ }
53
+ )
54
+ )
55
+
56
+
57
+ if __name__ == "__main__":
58
+ print("[@s3_proxy] Jumpstarting the proxy....")
59
+ cli()
@@ -0,0 +1,93 @@
1
+ import json
2
+ import time
3
+ from typing import Dict, Optional
4
+
5
+ from .exceptions import S3ProxyConfigException, S3ProxyApiException
6
+
7
+
8
+ class S3ProxyConfigResponse:
9
+ def __init__(self, data: Dict):
10
+ self.bucket_name = data.get("bucket_name")
11
+ self.endpoint_url = data.get("endpoint_url")
12
+ self.access_key_id = data.get("access_key_id")
13
+ self.secret_access_key = data.get("secret_access_key")
14
+ self.region = data.get("region")
15
+
16
+
17
+ class S3ProxyApiClient:
18
+ def __init__(self):
19
+ self.perimeter, self.integrations_url = self._get_api_configs()
20
+
21
+ def _get_api_configs(self):
22
+ from metaflow_extensions.outerbounds.remote_config import init_config
23
+ from os import environ
24
+
25
+ conf = init_config()
26
+ perimeter = conf.get("OBP_PERIMETER") or environ.get("OBP_PERIMETER", "")
27
+ integrations_url = conf.get("OBP_INTEGRATIONS_URL") or environ.get(
28
+ "OBP_INTEGRATIONS_URL", ""
29
+ )
30
+
31
+ if not perimeter:
32
+ raise S3ProxyConfigException(
33
+ "No perimeter set. Please run `outerbounds configure` command."
34
+ )
35
+
36
+ if not integrations_url:
37
+ raise S3ProxyConfigException(
38
+ "No integrations URL set. Please contact your Outerbounds support team."
39
+ )
40
+
41
+ return perimeter, integrations_url
42
+
43
+ def fetch_s3_proxy_config(
44
+ self, integration_name: Optional[str] = None
45
+ ) -> S3ProxyConfigResponse:
46
+ url = f"{self.integrations_url}/s3proxy"
47
+
48
+ payload = {"perimeter_name": self.perimeter}
49
+ if integration_name:
50
+ payload["integration_name"] = integration_name
51
+
52
+ headers = {"Content-Type": "application/json"}
53
+
54
+ try:
55
+ from metaflow.metaflow_config import SERVICE_HEADERS
56
+
57
+ headers.update(SERVICE_HEADERS or {})
58
+ except ImportError:
59
+ pass
60
+
61
+ response = self._make_request(url, headers, payload)
62
+ return S3ProxyConfigResponse(response)
63
+
64
+ def _make_request(self, url: str, headers: Dict, payload: Dict) -> Dict:
65
+ from metaflow_extensions.outerbounds.plugins.secrets.secrets import (
66
+ _api_server_get,
67
+ )
68
+
69
+ retryable_status_codes = [409]
70
+ json_payload = json.dumps(payload)
71
+
72
+ for attempt in range(3):
73
+ response = _api_server_get(
74
+ url, data=json_payload, headers=headers, conn_error_retries=5
75
+ )
76
+
77
+ if response.status_code not in retryable_status_codes:
78
+ break
79
+
80
+ if attempt < 2:
81
+ time.sleep(0.5 * (attempt + 1))
82
+
83
+ if response.status_code != 200:
84
+ error_msg = f"API request failed with status {response.status_code}"
85
+ try:
86
+ error_data = response.json()
87
+ if "message" in error_data:
88
+ error_msg = error_data["message"]
89
+ except:
90
+ pass
91
+ raise S3ProxyApiException(error_msg)
92
+
93
+ return response.json()
@@ -0,0 +1,250 @@
1
+ import os
2
+ import functools
3
+ import json
4
+ import signal
5
+ import time
6
+ from typing import Dict, List, Optional, Tuple
7
+
8
+ from metaflow import current
9
+ from metaflow.decorators import StepDecorator
10
+ from .exceptions import S3ProxyException
11
+ from .constants import S3_PROXY_WRITE_MODES
12
+ from collections import namedtuple
13
+
14
+ S3ProxyBinaryConfig = namedtuple(
15
+ "S3ProxyBinaryConfig", ["integration_name", "write_mode", "debug"]
16
+ )
17
+
18
+
19
+ def monkey_patch_environment(
20
+ environment, step_name_and_deco_attrs: Dict[str, S3ProxyBinaryConfig]
21
+ ):
22
+ wrapping_func = environment.bootstrap_commands
23
+
24
+ @functools.wraps(wrapping_func)
25
+ def wrapper(step_name, ds_type, *args):
26
+ base_boostrap_cmd = wrapping_func(step_name, ds_type, *args)
27
+ additional_cmd = []
28
+
29
+ if step_name in step_name_and_deco_attrs:
30
+ integration_name = step_name_and_deco_attrs[step_name].integration_name
31
+ write_mode = step_name_and_deco_attrs[step_name].write_mode
32
+ debug = step_name_and_deco_attrs[step_name].debug
33
+ additional_cmd = [
34
+ "echo 'Setting up the S3 proxy.'",
35
+ f"python -m metaflow_extensions.outerbounds.plugins.s3_proxy.proxy_bootstrap bootstrap --integration-name {integration_name} --write-mode {write_mode} --debug {debug} --uc-proxy-cfg-write-path ./.uc_proxy_cfg_file --proxy-status-write-path ./.proxy_status_file",
36
+ "export METAFLOW_S3_PROXY_USER_CODE_CONFIG=$(cat ./.uc_proxy_cfg_file)",
37
+ "export METAFLOW_S3_PROXY_STATUS=$(cat ./.proxy_status_file)",
38
+ "export METAFLOW_S3_PROXY_SETUP_SUCCESS=True",
39
+ "flush_mflogs",
40
+ ]
41
+ return base_boostrap_cmd + additional_cmd
42
+
43
+ environment.bootstrap_commands = wrapper
44
+
45
+
46
+ class S3ProxyDecorator(StepDecorator):
47
+ """
48
+ Set up an S3 proxy that caches objects in an external, S3‑compatible bucket
49
+ for S3 read and write requests.
50
+
51
+ This decorator requires an integration in the Outerbounds platform that
52
+ points to an external bucket. It affects S3 operations performed via
53
+ Metaflow's `get_aws_client` and `S3` within a `@step`.
54
+
55
+ Read operations
56
+ ---------------
57
+ All read operations pass through the proxy. If an object does not already
58
+ exist in the external bucket, it is cached there. For example, if code reads
59
+ from buckets `FOO` and `BAR` using the `S3` interface, objects from both
60
+ buckets are cached in the external bucket.
61
+
62
+ During task execution, all S3‑related read requests are routed through the
63
+ proxy:
64
+ - If the object is present in the external object store, the proxy
65
+ streams it directly from there without accessing the requested origin
66
+ bucket.
67
+ - If the object is not present in the external storage, the proxy
68
+ fetches it from the requested bucket, caches it in the external
69
+ storage, and streams the response from the origin bucket.
70
+
71
+ Warning
72
+ -------
73
+ All READ operations (e.g., GetObject, HeadObject) pass through the external
74
+ bucket regardless of the bucket specified in user code. Even
75
+ `S3(run=self)` and `S3(s3root="mybucketfoo")` requests go through the
76
+ external bucket cache.
77
+
78
+ Write operations
79
+ ----------------
80
+ Write behavior is controlled by the `write_mode` parameter, which determines
81
+ whether writes also persist objects in the cache.
82
+
83
+ `write_mode` values:
84
+ - `origin-and-cache`: objects are written both to the cache and to their
85
+ intended origin bucket.
86
+ - `origin`: objects are written only to their intended origin bucket.
87
+
88
+ Parameters
89
+ ----------
90
+ integration_name : str, optional
91
+ [Outerbounds integration name](https://docs.outerbounds.com/outerbounds/configuring-secrets/#integrations-view)
92
+ that holds the configuration for the external, S3‑compatible object
93
+ storage bucket. If not specified, the only available S3 proxy
94
+ integration in the namespace is used (fails if multiple exist).
95
+ write_mode : str, optional
96
+ Controls whether writes also go to the external bucket.
97
+ - `origin` (default)
98
+ - `origin-and-cache`
99
+ debug : bool, optional
100
+ Enables debug logging for proxy operations.
101
+ """
102
+
103
+ name = "s3_proxy"
104
+ defaults = {
105
+ "integration_name": None,
106
+ "write_mode": None,
107
+ "debug": False,
108
+ }
109
+
110
+ _environment_patched = False
111
+
112
+ _proxy_status = None
113
+
114
+ @classmethod
115
+ def patch_environment(cls, flow, environment):
116
+ """
117
+ We need to patch the environment boostrap command so that
118
+ we can launch the s3 proxy before the step code execution.
119
+ We also want to ensure that we are running the proxy bootstrap
120
+ only for the steps that have the decorator set. This is why we pass down all
121
+ the step names that will change the boostrap commands.
122
+ """
123
+ if cls._environment_patched:
124
+ return
125
+
126
+ steps_with_s3_proxy = [
127
+ step
128
+ for step in flow
129
+ if any(deco.name == "s3_proxy" for deco in step.decorators)
130
+ ]
131
+ if len(steps_with_s3_proxy) == 0: # weird but y not?
132
+ return
133
+
134
+ step_names_and_deco_attrs = {}
135
+ for s in steps_with_s3_proxy:
136
+ _decos = [x for x in s.decorators if x.name == "s3_proxy"]
137
+ deco = _decos[0]
138
+ step_names_and_deco_attrs[s.name] = S3ProxyBinaryConfig(
139
+ integration_name=deco.attributes["integration_name"],
140
+ write_mode=deco.attributes["write_mode"],
141
+ debug=deco.attributes["debug"],
142
+ )
143
+
144
+ monkey_patch_environment(environment, step_names_and_deco_attrs)
145
+ cls._environment_patched = True
146
+
147
+ def step_init(self, flow, graph, step, decos, environment, flow_datastore, logger):
148
+ write_mode = self.attributes["write_mode"]
149
+ if write_mode and write_mode not in S3_PROXY_WRITE_MODES:
150
+ raise S3ProxyException(
151
+ f"unexpected write_mode specified: {write_mode}. Allowed values are: {','.join(S3_PROXY_WRITE_MODES)}."
152
+ )
153
+
154
+ self.patch_environment(flow, environment)
155
+ if (
156
+ os.environ.get("METAFLOW_S3_PROXY_USER_CODE_CONFIG")
157
+ and os.environ.get("METAFLOW_S3_PROXY_STATUS")
158
+ and self.attributes["debug"]
159
+ ):
160
+ print("[@s3_proxy] S3 Proxy detected. Debug mode is enabled.")
161
+
162
+ if os.environ.get("METAFLOW_S3_PROXY_STATUS"):
163
+ proxy_status = json.loads(os.environ.get("METAFLOW_S3_PROXY_STATUS"))
164
+ self._proxy_status = proxy_status
165
+
166
+ def task_pre_step(
167
+ self,
168
+ step_name,
169
+ task_datastore,
170
+ metadata,
171
+ run_id,
172
+ task_id,
173
+ flow,
174
+ graph,
175
+ retry_count,
176
+ max_user_code_retries,
177
+ ubf_context,
178
+ inputs,
179
+ ):
180
+ """Setup S3 proxy before step execution"""
181
+ pass
182
+
183
+ def task_finished(
184
+ self, step_name, flow, graph, is_task_ok, retry_count, max_retries
185
+ ):
186
+ if not self._proxy_status:
187
+ return
188
+
189
+ status = self._proxy_status
190
+ proxy_pid = status.get("proxy_pid")
191
+ config_path = status.get("config_path")
192
+ binary_path = status.get("binary_path")
193
+
194
+ # 1) Stop processes: try to terminate the process group for clean child shutdown
195
+ if proxy_pid:
196
+ try:
197
+ pgid = os.getpgid(proxy_pid)
198
+ os.killpg(pgid, signal.SIGTERM)
199
+ time.sleep(1)
200
+ except Exception:
201
+ # Fall back to killing the pid directly if pgid is unavailable
202
+ try:
203
+ os.kill(proxy_pid, signal.SIGTERM)
204
+ except Exception:
205
+ pass
206
+
207
+ # 2) Clear files based on status
208
+ for path in (config_path, binary_path):
209
+ try:
210
+ if path and os.path.exists(path):
211
+ os.remove(path)
212
+ except Exception:
213
+ pass
214
+
215
+
216
+ class NebiusS3ProxyDecorator(S3ProxyDecorator):
217
+
218
+ __doc__ = (
219
+ """
220
+ `@nebius_s3_proxy` is a Nebius-specific S3 Proxy decorator for routing S3 requests through a local proxy service.
221
+ It exists to make it easier for users to know that this decorator should only be used with
222
+ a Neo Cloud like Nebius. The underlying mechanics of the decorator is the same as the `@s3_proxy`:\n
223
+ """
224
+ + S3ProxyDecorator.__doc__
225
+ )
226
+
227
+ name = "nebius_s3_proxy"
228
+ defaults = {
229
+ "integration_name": None,
230
+ "write_mode": None,
231
+ "debug": False,
232
+ }
233
+
234
+
235
+ class CoreWeaveS3ProxyDecorator(S3ProxyDecorator):
236
+ __doc__ = (
237
+ """
238
+ `@coreweave_s3_proxy` is a CoreWeave-specific S3 Proxy decorator for routing S3 requests through a local proxy service.
239
+ It exists to make it easier for users to know that this decorator should only be used with
240
+ a Neo Cloud like CoreWeave. The underlying mechanics of the decorator is the same as the `@s3_proxy`:\n
241
+ """
242
+ + S3ProxyDecorator.__doc__
243
+ )
244
+
245
+ name = "coreweave_s3_proxy"
246
+ defaults = {
247
+ "integration_name": None,
248
+ "write_mode": None,
249
+ "debug": False,
250
+ }