ob-metaflow-extensions 1.1.138__tar.gz → 1.1.141__tar.gz

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 (70) hide show
  1. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/PKG-INFO +1 -1
  2. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/__init__.py +1 -0
  3. ob-metaflow-extensions-1.1.141/metaflow_extensions/outerbounds/plugins/apps/app_utils.py +187 -0
  4. ob-metaflow-extensions-1.1.141/metaflow_extensions/outerbounds/plugins/apps/consts.py +3 -0
  5. ob-metaflow-extensions-1.1.141/metaflow_extensions/outerbounds/plugins/apps/deploy_decorator.py +201 -0
  6. ob-metaflow-extensions-1.1.141/metaflow_extensions/outerbounds/plugins/apps/supervisord_utils.py +243 -0
  7. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/fast_bakery/fast_bakery.py +11 -0
  8. ob-metaflow-extensions-1.1.141/metaflow_extensions/outerbounds/plugins/snowpark/__init__.py +0 -0
  9. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/ob_metaflow_extensions.egg-info/PKG-INFO +1 -1
  10. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/ob_metaflow_extensions.egg-info/SOURCES.txt +5 -0
  11. ob-metaflow-extensions-1.1.141/ob_metaflow_extensions.egg-info/requires.txt +3 -0
  12. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/setup.py +2 -2
  13. ob-metaflow-extensions-1.1.138/ob_metaflow_extensions.egg-info/requires.txt +0 -3
  14. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/README.md +0 -0
  15. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/__init__.py +0 -0
  16. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/config/__init__.py +0 -0
  17. {ob-metaflow-extensions-1.1.138/metaflow_extensions/outerbounds/plugins/card_utilities → ob-metaflow-extensions-1.1.141/metaflow_extensions/outerbounds/plugins/apps}/__init__.py +0 -0
  18. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/auth_server.py +0 -0
  19. {ob-metaflow-extensions-1.1.138/metaflow_extensions/outerbounds/plugins/fast_bakery → ob-metaflow-extensions-1.1.141/metaflow_extensions/outerbounds/plugins/card_utilities}/__init__.py +0 -0
  20. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/card_utilities/async_cards.py +0 -0
  21. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/card_utilities/extra_components.py +0 -0
  22. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/card_utilities/injector.py +0 -0
  23. {ob-metaflow-extensions-1.1.138/metaflow_extensions/outerbounds/plugins/nvcf → ob-metaflow-extensions-1.1.141/metaflow_extensions/outerbounds/plugins/fast_bakery}/__init__.py +0 -0
  24. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/fast_bakery/docker_environment.py +0 -0
  25. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/fast_bakery/fast_bakery_cli.py +0 -0
  26. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/fast_bakery/fast_bakery_decorator.py +0 -0
  27. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/kubernetes/__init__.py +0 -0
  28. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/kubernetes/kubernetes_client.py +0 -0
  29. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/nim/__init__.py +0 -0
  30. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/nim/card.py +0 -0
  31. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/nim/nim_manager.py +0 -0
  32. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/nim/utilities.py +0 -0
  33. {ob-metaflow-extensions-1.1.138/metaflow_extensions/outerbounds/plugins/secrets → ob-metaflow-extensions-1.1.141/metaflow_extensions/outerbounds/plugins/nvcf}/__init__.py +0 -0
  34. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/nvcf/constants.py +0 -0
  35. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/nvcf/exceptions.py +0 -0
  36. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/nvcf/heartbeat_store.py +0 -0
  37. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/nvcf/nvcf.py +0 -0
  38. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/nvcf/nvcf_cli.py +0 -0
  39. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/nvcf/nvcf_decorator.py +0 -0
  40. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/nvcf/utils.py +0 -0
  41. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/ollama/__init__.py +0 -0
  42. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/ollama/ollama.py +0 -0
  43. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/perimeters.py +0 -0
  44. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/profilers/deco_injector.py +0 -0
  45. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/profilers/gpu_profile_decorator.py +0 -0
  46. {ob-metaflow-extensions-1.1.138/metaflow_extensions/outerbounds/plugins/snowpark → ob-metaflow-extensions-1.1.141/metaflow_extensions/outerbounds/plugins/secrets}/__init__.py +0 -0
  47. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/secrets/secrets.py +0 -0
  48. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/snowflake/__init__.py +0 -0
  49. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/snowflake/snowflake.py +0 -0
  50. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/snowpark/snowpark.py +0 -0
  51. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/snowpark/snowpark_cli.py +0 -0
  52. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/snowpark/snowpark_client.py +0 -0
  53. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/snowpark/snowpark_decorator.py +0 -0
  54. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/snowpark/snowpark_exceptions.py +0 -0
  55. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/snowpark/snowpark_job.py +0 -0
  56. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/snowpark/snowpark_service_spec.py +0 -0
  57. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/plugins/tensorboard/__init__.py +0 -0
  58. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/profilers/__init__.py +0 -0
  59. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/profilers/gpu.py +0 -0
  60. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/remote_config.py +0 -0
  61. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/toplevel/__init__.py +0 -0
  62. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/toplevel/global_aliases_for_metaflow_package.py +0 -0
  63. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/toplevel/plugins/azure/__init__.py +0 -0
  64. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/toplevel/plugins/gcp/__init__.py +0 -0
  65. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/toplevel/plugins/kubernetes/__init__.py +0 -0
  66. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/toplevel/plugins/ollama/__init__.py +0 -0
  67. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/metaflow_extensions/outerbounds/toplevel/plugins/snowflake/__init__.py +0 -0
  68. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/ob_metaflow_extensions.egg-info/dependency_links.txt +0 -0
  69. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/ob_metaflow_extensions.egg-info/top_level.txt +0 -0
  70. {ob-metaflow-extensions-1.1.138 → ob-metaflow-extensions-1.1.141}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: ob-metaflow-extensions
3
- Version: 1.1.138
3
+ Version: 1.1.141
4
4
  Summary: Outerbounds Platform Extensions for Metaflow
5
5
  Author: Outerbounds, Inc.
6
6
  License: Commercial
@@ -321,6 +321,7 @@ STEP_DECORATORS_DESC = [
321
321
  ("gpu_profile", ".profilers.gpu_profile_decorator.GPUProfileDecorator"),
322
322
  ("nim", ".nim.NimDecorator"),
323
323
  ("ollama", ".ollama.OllamaDecorator"),
324
+ ("app_deploy", ".apps.deploy_decorator.WorkstationAppDeployDecorator"),
324
325
  ]
325
326
 
326
327
  TOGGLE_STEP_DECORATOR = [
@@ -0,0 +1,187 @@
1
+ from metaflow.exception import MetaflowException
2
+ import os
3
+ from metaflow.metaflow_config_funcs import init_config
4
+ import requests
5
+ import time
6
+ import random
7
+
8
+ # IMPORTANT: Currently contents of this file are mostly duplicated from the outerbounds package.
9
+ # This is purely due to the time rush of having to deliver this feature. As a fast forward, we
10
+ # will reorganize things in a way that the amount of duplication in minimum.
11
+
12
+
13
+ APP_READY_POLL_TIMEOUT_SECONDS = 300
14
+ # Even after our backend validates that the app routes are ready, it takes a few seconds for
15
+ # the app to be accessible via the browser. Till we hunt down this delay, add an extra buffer.
16
+ APP_READY_EXTRA_BUFFER_SECONDS = 30
17
+
18
+
19
+ def start_app(port=-1, name=""):
20
+ """
21
+ Starts an app on the workstation.
22
+ List workstations, looks for "NamedPorts", then makes an update call to the NamedPorts for the workstation.
23
+ """
24
+ if len(name) == 0 or len(name) >= 20:
25
+ raise MetaflowException("App name should not be more than 20 characters long.")
26
+ elif not name.isalnum() or not name.islower():
27
+ raise MetaflowException(
28
+ "App name can only contain lowercase alphanumeric characters."
29
+ )
30
+
31
+ if "WORKSTATION_ID" not in os.environ:
32
+ raise MetaflowException(
33
+ "All outerbounds app commands can only be run from a workstation."
34
+ )
35
+
36
+ # Every workstation has this environment variable set.
37
+ workstation_id = os.environ["WORKSTATION_ID"]
38
+
39
+ try:
40
+ try:
41
+ conf = init_config()
42
+ metaflow_token = conf["METAFLOW_SERVICE_AUTH_KEY"]
43
+ api_url = conf["OBP_API_SERVER"]
44
+
45
+ workstations_response = requests.get(
46
+ f"https://{api_url}/v1/workstations",
47
+ headers={"x-api-key": metaflow_token},
48
+ )
49
+ workstations_response.raise_for_status()
50
+ except:
51
+ raise MetaflowException("Failed to list workstations!")
52
+
53
+ workstations_json = workstations_response.json()["workstations"]
54
+ for workstation in workstations_json:
55
+ if workstation["instance_id"] == os.environ["WORKSTATION_ID"]:
56
+ if "named_ports" in workstation["spec"]:
57
+ try:
58
+ ensure_app_start_request_is_valid(
59
+ workstation["spec"]["named_ports"], port, name
60
+ )
61
+ except ValueError as e:
62
+ raise MetaflowException(str(e))
63
+
64
+ for named_port in workstation["spec"]["named_ports"]:
65
+ if int(named_port["port"]) == port:
66
+ if named_port["enabled"] and named_port["name"] == name:
67
+ print(f"App {name} started on port {port}!")
68
+ print(
69
+ f"Browser URL: https://{api_url.replace('api', 'ui')}/apps/{os.environ['WORKSTATION_ID']}/{name}/"
70
+ )
71
+ print(
72
+ f"API URL: https://{api_url}/apps/{os.environ['WORKSTATION_ID']}/{name}/"
73
+ )
74
+ return
75
+ else:
76
+ try:
77
+ response = requests.put(
78
+ f"https://{api_url}/v1/workstations/update/{workstation_id}/namedports",
79
+ headers={"x-api-key": metaflow_token},
80
+ json={
81
+ "port": port,
82
+ "name": name,
83
+ "enabled": True,
84
+ },
85
+ )
86
+
87
+ response.raise_for_status()
88
+ poll_success = wait_for_app_port_to_be_accessible(
89
+ api_url,
90
+ metaflow_token,
91
+ workstation_id,
92
+ name,
93
+ APP_READY_POLL_TIMEOUT_SECONDS,
94
+ )
95
+ if poll_success:
96
+ print(f"App {name} started on port {port}!")
97
+ print(
98
+ f"Browser URL: https://{api_url.replace('api', 'ui')}/apps/{os.environ['WORKSTATION_ID']}/{name}/"
99
+ )
100
+ print(
101
+ f"API URL: https://{api_url}/apps/{os.environ['WORKSTATION_ID']}/{name}/"
102
+ )
103
+ else:
104
+ raise MetaflowException(
105
+ f"The app could not be deployed in {APP_READY_POLL_TIMEOUT_SECONDS / 60} minutes. Please try again later."
106
+ )
107
+ except Exception:
108
+ raise MetaflowException(
109
+ f"Failed to start app {name} on port {port}!"
110
+ )
111
+ except Exception as e:
112
+ raise MetaflowException(f"Failed to start app {name} on port {port}!")
113
+
114
+
115
+ def ensure_app_start_request_is_valid(existing_named_ports, port: int, name: str):
116
+ """
117
+ Ensures that the port number is available on the workstation and that an app of
118
+ the same name is not already opened on a different port.
119
+
120
+ Args:
121
+ existing_named_ports: A list of named ports on the workstation.
122
+ port: The port number to check.
123
+ name: The name of the app to check.
124
+ """
125
+ existing_apps_by_port = {np["port"]: np for np in existing_named_ports}
126
+
127
+ if port not in existing_apps_by_port:
128
+ raise MetaflowException(f"Port {port} not found on workstation")
129
+
130
+ for existing_named_port in existing_named_ports:
131
+ if (
132
+ name == existing_named_port["name"]
133
+ and existing_named_port["port"] != port
134
+ and existing_named_port["enabled"]
135
+ ):
136
+ raise MetaflowException(
137
+ f"App with name '{name}' is already deployed on port {existing_named_port['port']}"
138
+ )
139
+
140
+
141
+ def wait_for_app_port_to_be_accessible(
142
+ api_url, metaflow_token, workstation_id, app_name, poll_timeout_seconds
143
+ ) -> bool:
144
+ """
145
+ Waits for the app to be ready by polling the workstation status.
146
+ """
147
+ num_retries_per_request = 3
148
+ start_time = time.time()
149
+ retry_delay = 1.0
150
+ poll_interval = 10
151
+ wait_message = f"App {app_name} is currently being deployed..."
152
+ while time.time() - start_time < poll_timeout_seconds:
153
+ for _ in range(num_retries_per_request):
154
+ try:
155
+ workstations_response = requests.get(
156
+ f"https://{api_url}/v1/workstations",
157
+ headers={"x-api-key": metaflow_token},
158
+ )
159
+ workstations_response.raise_for_status()
160
+ if is_app_ready(workstations_response.json(), workstation_id, app_name):
161
+ print(wait_message)
162
+ time.sleep(APP_READY_EXTRA_BUFFER_SECONDS)
163
+ return True
164
+ else:
165
+ print(wait_message)
166
+ time.sleep(poll_interval)
167
+ except (
168
+ requests.exceptions.ConnectionError,
169
+ requests.exceptions.ReadTimeout,
170
+ ):
171
+ time.sleep(retry_delay)
172
+ retry_delay *= 2 # Double the delay for the next attempt
173
+ retry_delay += random.uniform(0, 1) # Add jitter
174
+ retry_delay = min(retry_delay, 10)
175
+ return False
176
+
177
+
178
+ def is_app_ready(response_json: dict, workstation_id: str, app_name: str) -> bool:
179
+ """Checks if the app is ready in the given workstation's response."""
180
+ workstations = response_json.get("workstations", [])
181
+ for workstation in workstations:
182
+ if workstation.get("instance_id") == workstation_id:
183
+ hosted_apps = workstation.get("status", {}).get("hosted_apps", [])
184
+ for hosted_app in hosted_apps:
185
+ if hosted_app.get("name") == app_name:
186
+ return bool(hosted_app.get("ready"))
187
+ return False
@@ -0,0 +1,3 @@
1
+ DEFAULT_WAIT_TIME_SECONDS_FOR_PROCESS_TO_START = 10
2
+ BASE_DIR_FOR_APP_ASSETS = "/home/ob-workspace/.appdaemon/apps/"
3
+ APP_DAEMON_WORKSTAION_PATH = "/home/ob-workspace/.appdaemon"
@@ -0,0 +1,201 @@
1
+ from metaflow.exception import MetaflowException
2
+ from metaflow.decorators import StepDecorator
3
+ from metaflow import current
4
+ from .app_utils import start_app
5
+ from .supervisord_utils import SupervisorClient, SupervisorClientException
6
+ import os
7
+ import random
8
+ import string
9
+ import tempfile
10
+ import sys
11
+ from .consts import (
12
+ BASE_DIR_FOR_APP_ASSETS,
13
+ DEFAULT_WAIT_TIME_SECONDS_FOR_PROCESS_TO_START,
14
+ )
15
+
16
+ """
17
+ There are 3 variants of starting apps that we support through this function. Which variant is applied is
18
+ a result of the user setting (or not setting) self.entrypoint and self.app_dir.
19
+
20
+ The chosen variant determines whether or not the user will have an easy (auto-magical) way to write their
21
+ Metaflow artifacts the the directory where their app will be run from. This will simplify managing models
22
+ from inside the code.
23
+
24
+ Case 1:
25
+ Desired Behavior:
26
+ The user doesn't care about auto-magical artifact management, they just have a server.py somewhere and
27
+ they want to run it.
28
+ How:
29
+ The user sets self.entrypoint to the name of their file (optionally with any args).
30
+ The value of self.app_dir is irrelevant.
31
+ Example: self.entrypoint = "/home/ob-workspace/my_random_directory/my_subfolder/server.py --my_arg 764"
32
+ Expected Behavior:
33
+ The users app will be started using a conda environment built by Metaflow, that's it.
34
+
35
+ Case 2:
36
+ Desired Behavior:
37
+ The user has defined a clean package/module structure with a __main__.py in a folder somewhere. They would like
38
+ to run this module as an app. They would like to access models in the same top level directory as their app.
39
+ How:
40
+ The user sets self.entrypoint to None.
41
+ The user sets self.app_dir to the top level directory of their app.
42
+ Example: self.app_dir = "/home/ob-workspace/my_random_directory/my_subfolder"
43
+ (my_subfolder HAS to contain a __main__.py file.)
44
+ Expected Behavior:
45
+ The users app will be started using a conda environment built by Metaflow. The user gets access to self.deploy_dir where they
46
+ write their artifacts. After the user writes their artifacts to self.deploy_dir, the artifacts and the app is copied over
47
+ to an internal directory where we will deploy the app from.
48
+ The internal directory is: /home/ob-workspace/.appdaemon/apps/<app_port>.
49
+ <app_port> will contain user's __main__.py and other files (copied recursively), as well as their artifacts that they wrote to
50
+ self.deploy_dir. self.deploy_dir/my_model becomes <app_port>/my_model. my_subfolder/__main__.py becomes <app_port>/__main__.py.
51
+
52
+ Case 3:
53
+ Desired Behavior:
54
+ The user follows the Outerbounds convention, which is the same as Case 2, except the app is actually in the same top level folder
55
+ as the Deployer flow. They would like to access models as usual.
56
+ How:
57
+ The user sets self.entrypoint to None (or doesn't set it at all).
58
+ The user sets self.app_dir to None (or doesn't set it at all).
59
+ Expected Behavior:
60
+ The users app will be started using a conda environment built by Metaflow. Everything else is exactly the same as Case 2.
61
+ """
62
+
63
+
64
+ class WorkstationAppDeployDecorator(StepDecorator):
65
+ """
66
+ Specifies that this step is used to deploy an instance of the app.
67
+ Requires that self.app_name, self.app_port, self.entrypoint and self.deployDir is set.
68
+
69
+ Parameters
70
+ ----------
71
+ app_port : int
72
+ Number of GPUs to use.
73
+ app_name : str
74
+ Name of the app to deploy.
75
+ """
76
+
77
+ name = "app_deploy"
78
+ defaults = {"app_port": 8080, "app_name": "app"}
79
+
80
+ def step_init(self, flow, graph, step, decos, environment, flow_datastore, logger):
81
+ if any([deco.name == "kubernetes" for deco in decos]):
82
+ raise MetaflowException(
83
+ "@app_deploy decorator is only supported locally and does not work with remote execution environments like @kubernetes, @nvidia."
84
+ )
85
+
86
+ # We always need to have some environment defined through the flow to deploy and app.
87
+ # Which means either step decorators like @pypi / @conda must be defined.
88
+ # or flow level decorators like @conda_base / @pypi_base.
89
+ if not any([deco.name == "pypi" or deco.name == "conda" for deco in decos]):
90
+ flow_decorators = flow._flow_decorators.keys()
91
+ if (
92
+ "conda_base" not in flow_decorators
93
+ and "pypi_base" not in flow_decorators
94
+ ):
95
+ raise MetaflowException(
96
+ "@app_deploy requires either step decorators like @pypi / @conda or flow level decorators like @conda_base / @pypi_base to be defined."
97
+ )
98
+
99
+ app_port = self.attributes["app_port"]
100
+ app_name = self.attributes["app_name"]
101
+
102
+ # Currently this decorator is expected to only execute on workstation.
103
+ if app_port is None or app_port < 6000 or app_port > 6002:
104
+ raise MetaflowException(
105
+ "AppDeployDecorator requires app_port to be between 6000 and 6002."
106
+ )
107
+
108
+ if app_name is None:
109
+ raise MetaflowException("AppDeployDecorator requires app_name to be set.")
110
+
111
+ def task_pre_step(
112
+ self,
113
+ step_name,
114
+ task_datastore,
115
+ metadata,
116
+ run_id,
117
+ task_id,
118
+ flow,
119
+ graph,
120
+ retry_count,
121
+ max_user_code_retries,
122
+ ubf_context,
123
+ inputs,
124
+ ):
125
+ """
126
+ Runs before the step decorated with @app_deploy has started.
127
+ We create a directory where the user can write their artifacts and expose it via self.deploy_dir.
128
+ """
129
+ os.makedirs(BASE_DIR_FOR_APP_ASSETS, exist_ok=True)
130
+ # First we want to create a directory where the user's app directory and artifacts can be stored.
131
+ with tempfile.TemporaryDirectory(
132
+ prefix=BASE_DIR_FOR_APP_ASSETS, delete=False
133
+ ) as temp_dir:
134
+ launch_temp_dir = temp_dir
135
+
136
+ # Expose this to the user, so that they can use it write their artifacts.
137
+ setattr(flow, "deploy_dir", launch_temp_dir)
138
+
139
+ # Make sure to record deploy_dir so that the user cannot accidentally override it.
140
+ self._deploy_dir = launch_temp_dir
141
+
142
+ def task_post_step(
143
+ self, step_name, flow, graph, retry_count, max_user_code_retries
144
+ ):
145
+ """
146
+ Runs after the step decorated with @app_deploy has finished.
147
+ Based on the cases above, things that we care about are self.entrypoint and self.app_dir.
148
+ """
149
+
150
+ deploy_dir = self._deploy_dir
151
+
152
+ # By default we assume that the user has a __main__.py file in their app directory.
153
+ # They can always override this behavior.
154
+ user_provided_entrypoint = getattr(flow, "entrypoint", None)
155
+
156
+ if user_provided_entrypoint is not None and not isinstance(
157
+ user_provided_entrypoint, str
158
+ ):
159
+ raise MetaflowException(
160
+ f"@app_deploy requires entrypoint to be set to a string. The current value of entrypoint {user_provided_entrypoint} is not valid."
161
+ )
162
+
163
+ flow_directory = os.path.dirname(os.path.abspath(sys.argv[0]))
164
+
165
+ app_location = getattr(
166
+ flow, "app_dir", os.path.join(flow_directory, self.attributes["app_name"])
167
+ )
168
+
169
+ if user_provided_entrypoint is None and not os.path.exists(app_location):
170
+ raise MetaflowException(f"App directory {app_location} does not exist.")
171
+
172
+ wait_time_for_app_start = getattr(
173
+ flow,
174
+ "wait_time_for_app_start",
175
+ DEFAULT_WAIT_TIME_SECONDS_FOR_PROCESS_TO_START,
176
+ )
177
+
178
+ try:
179
+ supervisor_client = SupervisorClient(
180
+ wait_time_seconds_for_app_start=wait_time_for_app_start
181
+ )
182
+
183
+ # First, let's deploy the app.
184
+ start_app(
185
+ port=self.attributes["app_port"], name=self.attributes["app_name"]
186
+ )
187
+
188
+ # Now, let's add the app to supervisor.
189
+ supervisor_client.start_process_with_supervisord(
190
+ self.attributes["app_name"],
191
+ self.attributes["app_port"],
192
+ user_provided_entrypoint,
193
+ deploy_dir,
194
+ app_location,
195
+ )
196
+ except SupervisorClientException as e:
197
+ raise MetaflowException(str(e))
198
+ except Exception as e:
199
+ raise MetaflowException(
200
+ f"Failed to start {self.attributes['app_name']}! Cause: {str(e)}"
201
+ ) from e
@@ -0,0 +1,243 @@
1
+ import argparse
2
+ import os
3
+ import configparser
4
+ import tempfile
5
+ import sys
6
+ import subprocess
7
+ from pathlib import Path
8
+ import shutil
9
+ from enum import Enum
10
+ import time
11
+ from .consts import BASE_DIR_FOR_APP_ASSETS, APP_DAEMON_WORKSTAION_PATH
12
+
13
+
14
+ class SupervisorClientException(Exception):
15
+ pass
16
+
17
+
18
+ class SupervisorClient:
19
+ """
20
+ A client for starting and stopping apps using supervisor.
21
+ """
22
+
23
+ def __init__(self, wait_time_seconds_for_app_start: int):
24
+ self.supervisor_conf_loc = os.environ.get("SUPERVISOR_CONF_PATH")
25
+
26
+ self.wait_time_seconds_for_app_start = wait_time_seconds_for_app_start
27
+ if self.supervisor_conf_loc is None or not os.path.exists(
28
+ self.supervisor_conf_loc
29
+ ):
30
+ raise SupervisorClientException(
31
+ "This workstation does not support deploying apps! Please reach out to Outerbounds for support."
32
+ )
33
+
34
+ self.metaflow_envs_persistent_path = os.environ.get(
35
+ "SUPERVISOR_PYTHON_ENVS_PATH"
36
+ )
37
+ if self.metaflow_envs_persistent_path is None:
38
+ raise SupervisorClientException(
39
+ "This workstation does not support deploying apps! Please reach out to Outerbounds for support."
40
+ )
41
+
42
+ # Check if supervisorctl is installed
43
+ if not shutil.which("supervisorctl"):
44
+ raise SupervisorClientException(
45
+ "This workstation does not support deploying apps! Please reach out to Outerbounds for support."
46
+ )
47
+
48
+ def _stop_existing_app_at_port(self, app_port):
49
+ supervisor_config = configparser.ConfigParser()
50
+ supervisor_config.read(self.supervisor_conf_loc)
51
+
52
+ for program in supervisor_config.sections():
53
+ if "obp_app_port" in supervisor_config[program]:
54
+ if supervisor_config[program]["obp_app_port"].strip() == str(app_port):
55
+ res = subprocess.run(
56
+ ["supervisorctl", "stop", program],
57
+ stdout=subprocess.DEVNULL,
58
+ stderr=subprocess.DEVNULL,
59
+ )
60
+
61
+ del supervisor_config[program]
62
+
63
+ with tempfile.NamedTemporaryFile(
64
+ "w", dir=os.path.dirname(self.supervisor_conf_loc), delete=False
65
+ ) as f:
66
+ supervisor_config.write(f)
67
+ tmp_file = f.name
68
+
69
+ os.rename(tmp_file, self.supervisor_conf_loc)
70
+
71
+ def _create_supervisor_conf_entry(
72
+ self, command, launch_directory, app_port, app_name
73
+ ):
74
+ entry = {
75
+ "command": command,
76
+ "directory": launch_directory,
77
+ "autostart": "true",
78
+ "autorestart": "true",
79
+ "obp_app_port": app_port, # Record the app port for internal reference. This is not used by supervisor.
80
+ }
81
+
82
+ supervisor_config = configparser.ConfigParser()
83
+ supervisor_config.read(self.supervisor_conf_loc)
84
+
85
+ supervisor_config[f"program:{app_name}"] = entry
86
+
87
+ with tempfile.NamedTemporaryFile(
88
+ "w", dir=os.path.dirname(self.supervisor_conf_loc), delete=False
89
+ ) as f:
90
+ supervisor_config.write(f)
91
+ tmp_file = f.name
92
+
93
+ os.rename(tmp_file, self.supervisor_conf_loc)
94
+
95
+ def start_process_with_supervisord(
96
+ self,
97
+ app_name,
98
+ app_port,
99
+ user_provided_entrypoint,
100
+ deploy_dir=None,
101
+ app_dir=None,
102
+ ):
103
+ """
104
+ Starts the app using supervisor.
105
+
106
+ Args:
107
+ app_name: The name of the app to start.
108
+ app_port: The port to start the app on.
109
+ user_provided_entrypoint: The entrypoint to start the app with.
110
+ deploy_dir: The directory to copy the app to and deploy from.
111
+ app_dir: The directory to copy the app from.
112
+ """
113
+
114
+ entrypoint = user_provided_entrypoint
115
+ deploy_dir_for_port = os.path.join(BASE_DIR_FOR_APP_ASSETS, str(app_port))
116
+ launch_directory = (
117
+ BASE_DIR_FOR_APP_ASSETS
118
+ if entrypoint is None
119
+ else APP_DAEMON_WORKSTAION_PATH
120
+ )
121
+
122
+ # Stop any existing apps that are running on the same port.
123
+ self._stop_existing_app_at_port(app_port)
124
+
125
+ # This means the user has opted for either case 2 or case 3.
126
+ # Cases 2 and 3 are handled the same way, the only thing that differs is self.app_dir.
127
+ if user_provided_entrypoint is None:
128
+ # Copy the app_dir to the deploy_dir.
129
+ # This is also where all (if any) artifacts are written.
130
+ recursive_copy(app_dir, deploy_dir)
131
+
132
+ # Copy the entire deploy_dir to the port specific directory.
133
+ # Clear out anything that was there before (maybe a different app's assets)
134
+ if os.path.exists(deploy_dir_for_port):
135
+ shutil.rmtree(deploy_dir_for_port)
136
+
137
+ os.makedirs(deploy_dir_for_port)
138
+ recursive_copy(deploy_dir, deploy_dir_for_port)
139
+
140
+ # Apply default value
141
+ # We launch the module from BASE_DIR_FOR_APP_ASSETS, so when we provide the -m flag we don't need (and can't use) the full path.
142
+ # We just need to provide the port number (which is also the name of the folder where all app assets are stored)
143
+ entrypoint = f"-m {str(app_port)}"
144
+
145
+ # deploy_dir is meant to be temporary. No need to keep it around after everything has been copied over.
146
+ shutil.rmtree(deploy_dir)
147
+
148
+ # Metaflow by default generates the environment in /root/... (which is not persisted on workstations).
149
+ # Since the environment is fully self contained, we can copy it to a persistent location.
150
+ persistent_path_for_executable = (
151
+ self._persist_metaflow_generated_python_environment()
152
+ )
153
+
154
+ # This is the command used by supervisord to launch the app.
155
+ command = f"{persistent_path_for_executable} {entrypoint}"
156
+
157
+ self._create_supervisor_conf_entry(
158
+ command, launch_directory, app_port, app_name
159
+ )
160
+
161
+ # Execute supervisorctl reload
162
+ # Capture the exit code
163
+ exit_code = subprocess.run(
164
+ ["supervisorctl", "reload"],
165
+ stdout=subprocess.DEVNULL,
166
+ stderr=subprocess.DEVNULL,
167
+ ).returncode
168
+ if exit_code != 0:
169
+ raise SupervisorClientException(
170
+ "Failed to start app! Contact Outerbounds for support."
171
+ )
172
+
173
+ print(
174
+ f"Waiting for {self.wait_time_seconds_for_app_start} seconds for {app_name} to start..."
175
+ )
176
+ time.sleep(self.wait_time_seconds_for_app_start)
177
+
178
+ self._raise_on_bad_status(app_name, command)
179
+
180
+ def _get_launched_prcoess_status(self, app_name, debug_command):
181
+ """
182
+ Checks the status of the launched process. If the status is not RUNNING or STARTING, it raises an exception.
183
+ Possible statuses: RUNNING, STARTING, STOPPED, BACKOFF, STOPPING, EXITED, FATAL, UNKNOWN
184
+
185
+ Args:
186
+ app_name: The name of the app to check the status of.
187
+ debug_command: The command to run to debug the app.
188
+ """
189
+ status_cmd_output = subprocess.run(
190
+ ["supervisorctl", "status", app_name],
191
+ stdout=subprocess.PIPE,
192
+ stderr=subprocess.PIPE,
193
+ ).stdout.decode("utf-8")
194
+
195
+ status_cmd_output_parts = [
196
+ x.strip() for x in status_cmd_output.split(" ") if x.strip()
197
+ ]
198
+
199
+ status_str = status_cmd_output_parts[1]
200
+
201
+ if not status_str == "RUNNING" and not status_str == "STARTING":
202
+ raise SupervisorClientException(
203
+ f"Failed to start {app_name}! Try running {debug_command} manually to debug."
204
+ )
205
+
206
+ def _persist_metaflow_generated_python_environment(self):
207
+ """
208
+ Persists the metaflow generated python environment to a persistent location.
209
+ The step already runs in the environment generated by Metaflow.
210
+ """
211
+ current_executable = sys.executable
212
+ environment_path = Path(current_executable).parent.parent
213
+
214
+ persistent_path_for_this_environment = os.path.join(
215
+ self.metaflow_envs_persistent_path,
216
+ environment_path.parent.name,
217
+ environment_path.name,
218
+ )
219
+
220
+ final_executable_path = os.path.join(
221
+ persistent_path_for_this_environment,
222
+ Path(current_executable).parent.name,
223
+ Path(current_executable).name,
224
+ )
225
+
226
+ if os.path.exists(final_executable_path):
227
+ return final_executable_path
228
+
229
+ os.makedirs(persistent_path_for_this_environment, exist_ok=True)
230
+
231
+ recursive_copy(environment_path, persistent_path_for_this_environment)
232
+
233
+ return final_executable_path
234
+
235
+
236
+ def recursive_copy(src, dst):
237
+ for item in os.listdir(src):
238
+ s = os.path.join(src, item)
239
+ d = os.path.join(dst, item)
240
+ if os.path.isdir(s):
241
+ shutil.copytree(s, d, dirs_exist_ok=True)
242
+ else:
243
+ shutil.copy2(s, d)
@@ -81,6 +81,17 @@ class FastBakery:
81
81
 
82
82
  def _reset_payload(self):
83
83
  self._payload = {}
84
+ from metaflow_extensions.outerbounds.remote_config import init_config
85
+ from os import environ
86
+
87
+ conf = init_config()
88
+ if "OBP_PERIMETER" in conf:
89
+ perimeter = conf["OBP_PERIMETER"]
90
+ else:
91
+ # if the perimeter is not in metaflow config, try to get it from the environment
92
+ perimeter = environ.get("OBP_PERIMETER", "")
93
+
94
+ self._payload["perimeterName"] = perimeter
84
95
 
85
96
  def python_version(self, version: str):
86
97
  self._payload["pythonVersion"] = version
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: ob-metaflow-extensions
3
- Version: 1.1.138
3
+ Version: 1.1.141
4
4
  Summary: Outerbounds Platform Extensions for Metaflow
5
5
  Author: Outerbounds, Inc.
6
6
  License: Commercial
@@ -6,6 +6,11 @@ metaflow_extensions/outerbounds/config/__init__.py
6
6
  metaflow_extensions/outerbounds/plugins/__init__.py
7
7
  metaflow_extensions/outerbounds/plugins/auth_server.py
8
8
  metaflow_extensions/outerbounds/plugins/perimeters.py
9
+ metaflow_extensions/outerbounds/plugins/apps/__init__.py
10
+ metaflow_extensions/outerbounds/plugins/apps/app_utils.py
11
+ metaflow_extensions/outerbounds/plugins/apps/consts.py
12
+ metaflow_extensions/outerbounds/plugins/apps/deploy_decorator.py
13
+ metaflow_extensions/outerbounds/plugins/apps/supervisord_utils.py
9
14
  metaflow_extensions/outerbounds/plugins/card_utilities/__init__.py
10
15
  metaflow_extensions/outerbounds/plugins/card_utilities/async_cards.py
11
16
  metaflow_extensions/outerbounds/plugins/card_utilities/extra_components.py
@@ -0,0 +1,3 @@
1
+ boto3
2
+ kubernetes
3
+ ob-metaflow==2.15.7.1
@@ -2,7 +2,7 @@ from setuptools import setup, find_namespace_packages
2
2
  from pathlib import Path
3
3
 
4
4
 
5
- version = "1.1.138"
5
+ version = "1.1.141"
6
6
  this_directory = Path(__file__).parent
7
7
  long_description = (this_directory / "README.md").read_text()
8
8
 
@@ -18,6 +18,6 @@ setup(
18
18
  install_requires=[
19
19
  "boto3",
20
20
  "kubernetes",
21
- "ob-metaflow == 2.15.6.1",
21
+ "ob-metaflow == 2.15.7.1",
22
22
  ],
23
23
  )
@@ -1,3 +0,0 @@
1
- boto3
2
- kubernetes
3
- ob-metaflow==2.15.6.1