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.
File without changes
@@ -0,0 +1,523 @@
1
+ import json
2
+ import os
3
+ import sys
4
+ from functools import wraps
5
+ from typing import Dict, List, Any, Optional, Union
6
+ from outerbounds._vendor import click, yaml
7
+ from outerbounds.utils import metaflowconfig
8
+ from .app_config import (
9
+ AppConfig,
10
+ AppConfigError,
11
+ CODE_PACKAGE_PREFIX,
12
+ CAPSULE_DEBUG,
13
+ AuthType,
14
+ )
15
+ from .cli_to_config import build_config_from_options
16
+ from .utils import (
17
+ CommaSeparatedListType,
18
+ KVPairType,
19
+ )
20
+ from . import experimental
21
+ from .validations import deploy_validations
22
+ from .code_package import CodePackager
23
+ from .capsule import Capsule
24
+ import shlex
25
+ import time
26
+ import uuid
27
+ from datetime import datetime
28
+
29
+ LOGGER_TIMESTAMP = "magenta"
30
+ LOGGER_COLOR = "green"
31
+ LOGGER_BAD_COLOR = "red"
32
+
33
+
34
+ def _logger(
35
+ body="", system_msg=False, head="", bad=False, timestamp=True, nl=True, color=None
36
+ ):
37
+ if timestamp:
38
+ if timestamp is True:
39
+ dt = datetime.now()
40
+ else:
41
+ dt = timestamp
42
+ tstamp = dt.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
43
+ click.secho(tstamp + " ", fg=LOGGER_TIMESTAMP, nl=False)
44
+ if head:
45
+ click.secho(head, fg=LOGGER_COLOR, nl=False)
46
+ click.secho(
47
+ body,
48
+ bold=system_msg,
49
+ fg=LOGGER_BAD_COLOR if bad else color if color is not None else None,
50
+ nl=nl,
51
+ )
52
+
53
+
54
+ class CliState(object):
55
+ pass
56
+
57
+
58
+ def _pre_create_debug(app_config: AppConfig, capsule: Capsule, state_dir: str):
59
+ if CAPSULE_DEBUG:
60
+ os.makedirs(state_dir, exist_ok=True)
61
+ debug_path = os.path.join(state_dir, f"debug_{time.time()}.yaml")
62
+ with open(
63
+ debug_path,
64
+ "w",
65
+ ) as f:
66
+ f.write(
67
+ yaml.dump(
68
+ {
69
+ "app_state": app_config.dump_state(),
70
+ "capsule_input": capsule.create_input(),
71
+ },
72
+ default_flow_style=False,
73
+ indent=2,
74
+ )
75
+ )
76
+
77
+
78
+ @click.group()
79
+ def cli():
80
+ """Outerbounds CLI tool."""
81
+ pass
82
+
83
+
84
+ @cli.group(
85
+ help="Commands related to Deploying/Running/Managing Apps on Outerbounds Platform."
86
+ )
87
+ @click.pass_context
88
+ def app(ctx):
89
+ """App-related commands."""
90
+ ctx.obj = CliState()
91
+ ctx.obj.trace_id = str(uuid.uuid4())
92
+ ctx.obj.app_state_dir = os.path.join(os.curdir, ".ob_apps")
93
+ profile = os.environ.get("METAFLOW_PROFILE", "")
94
+ config_dir = os.path.expanduser(
95
+ os.environ.get("METAFLOW_HOME", "~/.metaflowconfig")
96
+ )
97
+ api_url = metaflowconfig.get_sanitized_url_from_config(
98
+ config_dir, profile, "OBP_API_SERVER"
99
+ )
100
+
101
+ ctx.obj.api_url = api_url
102
+ ctx.obj.perimeter = os.environ.get("OB_CURRENT_PERIMETER")
103
+ os.makedirs(ctx.obj.app_state_dir, exist_ok=True)
104
+
105
+
106
+ def parse_commands(app_config: AppConfig, cli_command_input):
107
+ # There can be two modes:
108
+ # 1. User passes command via `--` in the CLI
109
+ # 2. User passes the `commands` key in the config.
110
+ base_commands = []
111
+ if len(cli_command_input) > 0:
112
+ # TODO: we can be a little more fancy here by allowing the user to just call
113
+ # `outerbounds app deploy -- foo.py` and figure out if we need to stuff python
114
+ # in front of the command or not. But for sake of dumb simplicity, we can just
115
+ # assume what ever the user called on local needs to be called remotely, we can
116
+ # just ask them to add the outerbounds command in front of it.
117
+ # So the dev ex would be :
118
+ # `python foo.py` -> `outerbounds app deploy -- python foo.py`
119
+ if type(cli_command_input) == str:
120
+ base_commands.append(cli_command_input)
121
+ else:
122
+ base_commands.append(shlex.join(cli_command_input))
123
+ elif app_config.get("commands", None) is not None:
124
+ base_commands.extend(app_config.get("commands"))
125
+ return base_commands
126
+
127
+
128
+ def common_deploy_options(func):
129
+ @click.option(
130
+ "--name",
131
+ type=str,
132
+ help="The name of the app to deploy.",
133
+ )
134
+ @click.option("--port", type=int, help="Port where the app is hosted.")
135
+ @click.option(
136
+ "--tag",
137
+ "tags",
138
+ multiple=True,
139
+ type=KVPairType,
140
+ help="The tags of the app to deploy. Format KEY=VALUE. Example --tag foo=bar --tag x=y",
141
+ default=None,
142
+ )
143
+ @click.option(
144
+ "--image",
145
+ type=str,
146
+ help="The Docker image to deploy with the App",
147
+ default=None,
148
+ )
149
+ @click.option(
150
+ "--cpu",
151
+ type=str,
152
+ help="CPU resource request and limit",
153
+ default=None,
154
+ )
155
+ @click.option(
156
+ "--memory",
157
+ type=str,
158
+ help="Memory resource request and limit",
159
+ default=None,
160
+ )
161
+ @click.option(
162
+ "--gpu",
163
+ type=str,
164
+ help="GPU resource request and limit",
165
+ default=None,
166
+ )
167
+ @click.option(
168
+ "--disk",
169
+ type=str,
170
+ help="Storage resource request and limit",
171
+ default=None,
172
+ )
173
+ @click.option(
174
+ "--health-check-enabled",
175
+ type=bool,
176
+ help="Enable health checks",
177
+ default=None,
178
+ )
179
+ @click.option(
180
+ "--health-check-path",
181
+ type=str,
182
+ help="Health check path",
183
+ default=None,
184
+ )
185
+ @click.option(
186
+ "--health-check-initial-delay",
187
+ type=int,
188
+ help="Initial delay seconds for health check",
189
+ default=None,
190
+ )
191
+ @click.option(
192
+ "--health-check-period",
193
+ type=int,
194
+ help="Period seconds for health check",
195
+ default=None,
196
+ )
197
+ @click.option(
198
+ "--compute-pools",
199
+ type=CommaSeparatedListType,
200
+ help="The compute pools to deploy the app to. Example: --compute-pools default,large",
201
+ default=None,
202
+ )
203
+ @click.option(
204
+ "--auth-type",
205
+ type=click.Choice(AuthType.enums()),
206
+ help="The type of authentication to use for the app.",
207
+ default=None,
208
+ )
209
+ @click.option(
210
+ "--public-access/--private-access",
211
+ "auth_public",
212
+ type=bool,
213
+ help="Whether the app is public or not.",
214
+ default=None,
215
+ )
216
+ @click.option(
217
+ "--no-deps",
218
+ is_flag=True,
219
+ help="Do not any dependencies. Directly used the image provided",
220
+ default=False,
221
+ )
222
+ @click.option(
223
+ "--min-replicas",
224
+ type=int,
225
+ help="Minimum number of replicas to deploy",
226
+ default=None,
227
+ )
228
+ @click.option(
229
+ "--max-replicas",
230
+ type=int,
231
+ help="Maximum number of replicas to deploy",
232
+ default=None,
233
+ )
234
+ @wraps(func)
235
+ def wrapper(*args, **kwargs):
236
+ return func(*args, **kwargs)
237
+
238
+ return wrapper
239
+
240
+
241
+ def common_run_options(func):
242
+ """Common options for running and deploying apps."""
243
+
244
+ @click.option(
245
+ "--config-file",
246
+ type=str,
247
+ help="The config file to use for the App (YAML or JSON)",
248
+ default=None,
249
+ )
250
+ @click.option(
251
+ "--secret",
252
+ "secrets",
253
+ multiple=True,
254
+ type=str,
255
+ help="Secrets to deploy with the App",
256
+ default=None,
257
+ )
258
+ @click.option(
259
+ "--env",
260
+ "envs",
261
+ multiple=True,
262
+ type=KVPairType,
263
+ help="Environment variables to deploy with the App. Use format KEY=VALUE",
264
+ default=None,
265
+ )
266
+ @click.option(
267
+ "--package-src-path",
268
+ type=str,
269
+ help="The path to the source code to deploy with the App.",
270
+ default=None,
271
+ )
272
+ @click.option(
273
+ "--package-suffixes",
274
+ type=CommaSeparatedListType,
275
+ help="The suffixes of the source code to deploy with the App.",
276
+ default=None,
277
+ )
278
+ @click.option(
279
+ "--dep-from-requirements",
280
+ type=str,
281
+ help="Path to requirements.txt file for dependencies",
282
+ default=None,
283
+ )
284
+ @click.option(
285
+ "--dep-from-pyproject",
286
+ type=str,
287
+ help="Path to pyproject.toml file for dependencies",
288
+ default=None,
289
+ )
290
+ # TODO: [FIX ME]: Get better CLI abstraction for pypi/conda dependencies
291
+ @wraps(func)
292
+ def wrapper(*args, **kwargs):
293
+ return func(*args, **kwargs)
294
+
295
+ return wrapper
296
+
297
+
298
+ def _package_necessary_things(app_config: AppConfig, logger):
299
+ # Packaging has a few things to be thought through:
300
+ # 1. if `entrypoint_path` exists then should we package the directory
301
+ # where the entrypoint lives. For example : if the user calls
302
+ # `outerbounds app deploy foo/bar.py` should we package `foo` dir
303
+ # or should we package the cwd from which foo/bar.py is being called.
304
+ # 2. if the src path is used with the config file then how should we view
305
+ # that path ?
306
+ # 3. It becomes interesting when users call the deployment with config files
307
+ # where there is a `src_path` and then is the src_path relative to the config file
308
+ # or is it relative to where the caller command is sitting. Ideally it should work
309
+ # like Kustomizations where its relative to where the yaml file sits for simplicity
310
+ # of understanding relationships between config files. Ideally users can pass the src_path
311
+ # from the command line and that will aliviate any need to package any other directories for
312
+ #
313
+
314
+ package_dir = app_config.get_state("packaging_directory")
315
+ if package_dir is None:
316
+ app_config.set_state("code_package_url", None)
317
+ app_config.set_state("code_package_key", None)
318
+ return
319
+ from metaflow.metaflow_config import DEFAULT_DATASTORE
320
+
321
+ package = app_config.get_state("package") or {}
322
+ suffixes = package.get("suffixes", None)
323
+
324
+ packager = CodePackager(
325
+ datastore_type=DEFAULT_DATASTORE, code_package_prefix=CODE_PACKAGE_PREFIX
326
+ )
327
+ package_url, package_key = packager.store(
328
+ paths_to_include=[package_dir], file_suffixes=suffixes
329
+ )
330
+ app_config.set_state("code_package_url", package_url)
331
+ app_config.set_state("code_package_key", package_key)
332
+ logger("💾 Code Package Saved to : %s" % app_config.get_state("code_package_url"))
333
+
334
+
335
+ @app.command(help="Deploy an app to the Outerbounds Platform.")
336
+ @common_deploy_options
337
+ @common_run_options
338
+ @experimental.wrapping_cli_options
339
+ @click.pass_context
340
+ @click.argument("command", nargs=-1, type=click.UNPROCESSED, required=False)
341
+ def deploy(ctx, command, **options):
342
+ """Deploy an app to the Outerbounds Platform."""
343
+ from functools import partial
344
+
345
+ if not ctx.obj.perimeter:
346
+ raise AppConfigError("OB_CURRENT_PERIMETER is not set")
347
+
348
+ logger = partial(_logger, timestamp=True)
349
+ try:
350
+ # Create configuration
351
+ if options["config_file"]:
352
+ # Load from file
353
+ app_config = AppConfig.from_file(options["config_file"])
354
+
355
+ # Update with any CLI options using the unified method
356
+ app_config.update_from_cli_options(options)
357
+ else:
358
+ # Create from CLI options
359
+ config_dict = build_config_from_options(options)
360
+ app_config = AppConfig(config_dict)
361
+
362
+ # Validate the configuration
363
+ app_config.validate()
364
+ logger(
365
+ f"🚀 Deploying {app_config.get('name')} to the Outerbounds platform...",
366
+ color=LOGGER_COLOR,
367
+ system_msg=True,
368
+ )
369
+
370
+ packaging_directory = None
371
+ package_src_path = app_config.get("package", {}).get("src_path", None)
372
+ if package_src_path:
373
+ if os.path.isfile(package_src_path):
374
+ raise AppConfigError("src_path must be a directory, not a file")
375
+ elif os.path.isdir(package_src_path):
376
+ packaging_directory = os.path.abspath(package_src_path)
377
+ else:
378
+ raise AppConfigError(f"src_path '{package_src_path}' does not exist")
379
+ else:
380
+ # If src_path is None then we assume then we can assume for the moment
381
+ # that we can package the current working directory.
382
+ packaging_directory = os.getcwd()
383
+
384
+ app_config.set_state("packaging_directory", packaging_directory)
385
+ logger(
386
+ "📦 Packaging Directory : %s" % app_config.get_state("packaging_directory"),
387
+ )
388
+ # TODO: Construct the command needed to run the app
389
+ # If we are constructing the directory with the src_path
390
+ # then we need to add the command from the option otherwise
391
+ # we use the command from the entrypoint path and whatever follows `--`
392
+ # is the command to run.
393
+
394
+ # Set some defaults for the deploy command
395
+ app_config.set_deploy_defaults(packaging_directory)
396
+
397
+ if options.get("no_deps") == True:
398
+ # Setting this in the state will make it skip the fast-bakery step
399
+ # of building an image.
400
+ app_config.set_state("skip_dependencies", True)
401
+ else:
402
+ # Check if the user has set the dependencies in the app config
403
+ dependencies = app_config.get("dependencies", {})
404
+ if len(dependencies) == 0:
405
+ # The user has not set any dependencies, so we can sniff the packaging directory
406
+ # for a dependencies file.
407
+ requirements_file = os.path.join(
408
+ packaging_directory, "requirements.txt"
409
+ )
410
+ pyproject_toml = os.path.join(packaging_directory, "pyproject.toml")
411
+ if os.path.exists(pyproject_toml):
412
+ app_config.set_state(
413
+ "dependencies", {"from_pyproject_toml": pyproject_toml}
414
+ )
415
+ logger(
416
+ "📦 Using dependencies from pyproject.toml: %s" % pyproject_toml
417
+ )
418
+ elif os.path.exists(requirements_file):
419
+ app_config.set_state(
420
+ "dependencies", {"from_requirements_file": requirements_file}
421
+ )
422
+ logger(
423
+ "📦 Using dependencies from requirements.txt: %s"
424
+ % requirements_file
425
+ )
426
+
427
+ # Print the configuration
428
+ # 1. validate that the secrets for the app exist
429
+ # 2. TODO: validate that the compute pool specified in the app exists.
430
+ # 3. Building Docker image if necessary (based on parameters)
431
+ # - We will bake images with fastbakery and pass it to the deploy command
432
+ # TODO: validation logic can be wrapped in try catch so that we can provide
433
+ # better error messages.
434
+ cache_dir = os.path.join(
435
+ ctx.obj.app_state_dir, app_config.get("name", "default")
436
+ )
437
+ deploy_validations(
438
+ app_config,
439
+ cache_dir=cache_dir,
440
+ logger=logger,
441
+ )
442
+
443
+ base_commands = parse_commands(app_config, command)
444
+
445
+ app_config.set_state("commands", base_commands)
446
+
447
+ # TODO: Handle the case where packaging_directory is None
448
+ # This would involve:
449
+ # 1. Packaging the code:
450
+ # - We need to package the code and throw the tarball to some object store
451
+ _package_necessary_things(app_config, logger)
452
+
453
+ app_config.set_state("perimeter", ctx.obj.perimeter)
454
+
455
+ # 2. Convert to the IR that the backend accepts
456
+ capsule = Capsule(app_config, ctx.obj.api_url, debug_dir=cache_dir)
457
+
458
+ _pre_create_debug(app_config, capsule, cache_dir)
459
+ # 3. Throw the job into the platform and report deployment status
460
+ logger(
461
+ f"🚀 Deploying {capsule.capsule_type.lower()} to the platform...",
462
+ color=LOGGER_COLOR,
463
+ system_msg=True,
464
+ )
465
+ capsule.create()
466
+ capsule.wait_for_terminal_state(logger=logger)
467
+ logger(
468
+ f"💊 {capsule.capsule_type} {app_config.config['name']} ({capsule.identifier}) deployed successfully! You can access it at {capsule.status.out_of_cluster_url}",
469
+ color=LOGGER_COLOR,
470
+ system_msg=True,
471
+ )
472
+
473
+ except AppConfigError as e:
474
+ click.echo(f"Error in app configuration: {e}", err=True)
475
+ raise e
476
+ except Exception as e:
477
+ click.echo(f"Error deploying app: {e}", err=True)
478
+ raise e
479
+
480
+
481
+ @app.command(help="Run an app locally (for testing).")
482
+ @common_run_options
483
+ @click.pass_context
484
+ def run(ctx, **options):
485
+ """Run an app locally for testing."""
486
+ try:
487
+ # Create configuration
488
+ if options["config_file"]:
489
+ # Load from file
490
+ app_config = AppConfig.from_file(options["config_file"])
491
+
492
+ # Update with any CLI options using the unified method
493
+ app_config.update_from_cli_options(options)
494
+ else:
495
+ # Create from CLI options
496
+ config_dict = build_config_from_options(options)
497
+ app_config = AppConfig(config_dict)
498
+
499
+ # Validate the configuration
500
+ app_config.validate()
501
+
502
+ # Print the configuration
503
+ click.echo("Running App with configuration:")
504
+ click.echo(app_config.to_yaml())
505
+
506
+ # TODO: Implement local run logic
507
+ # This would involve:
508
+ # 1. Setting up the environment
509
+ # 2. Running the app locally
510
+ # 3. Reporting status
511
+
512
+ click.echo(f"App '{app_config.config['name']}' running locally!")
513
+
514
+ except AppConfigError as e:
515
+ click.echo(f"Error in app configuration: {e}", err=True)
516
+ ctx.exit(1)
517
+ except Exception as e:
518
+ click.echo(f"Error running app: {e}", err=True)
519
+ ctx.exit(1)
520
+
521
+
522
+ # if __name__ == "__main__":
523
+ # cli()