outerbounds 0.3.174__py3-none-any.whl → 0.3.175rc1__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,535 @@
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
+ @click.option(
235
+ "--description",
236
+ type=str,
237
+ help="The description of the app to deploy.",
238
+ default=None,
239
+ )
240
+ @click.option(
241
+ "--app-type",
242
+ type=str,
243
+ help="The type of app to deploy.",
244
+ default=None,
245
+ )
246
+ @wraps(func)
247
+ def wrapper(*args, **kwargs):
248
+ return func(*args, **kwargs)
249
+
250
+ return wrapper
251
+
252
+
253
+ def common_run_options(func):
254
+ """Common options for running and deploying apps."""
255
+
256
+ @click.option(
257
+ "--config-file",
258
+ type=str,
259
+ help="The config file to use for the App (YAML or JSON)",
260
+ default=None,
261
+ )
262
+ @click.option(
263
+ "--secret",
264
+ "secrets",
265
+ multiple=True,
266
+ type=str,
267
+ help="Secrets to deploy with the App",
268
+ default=None,
269
+ )
270
+ @click.option(
271
+ "--env",
272
+ "envs",
273
+ multiple=True,
274
+ type=KVPairType,
275
+ help="Environment variables to deploy with the App. Use format KEY=VALUE",
276
+ default=None,
277
+ )
278
+ @click.option(
279
+ "--package-src-path",
280
+ type=str,
281
+ help="The path to the source code to deploy with the App.",
282
+ default=None,
283
+ )
284
+ @click.option(
285
+ "--package-suffixes",
286
+ type=CommaSeparatedListType,
287
+ help="The suffixes of the source code to deploy with the App.",
288
+ default=None,
289
+ )
290
+ @click.option(
291
+ "--dep-from-requirements",
292
+ type=str,
293
+ help="Path to requirements.txt file for dependencies",
294
+ default=None,
295
+ )
296
+ @click.option(
297
+ "--dep-from-pyproject",
298
+ type=str,
299
+ help="Path to pyproject.toml file for dependencies",
300
+ default=None,
301
+ )
302
+ # TODO: [FIX ME]: Get better CLI abstraction for pypi/conda dependencies
303
+ @wraps(func)
304
+ def wrapper(*args, **kwargs):
305
+ return func(*args, **kwargs)
306
+
307
+ return wrapper
308
+
309
+
310
+ def _package_necessary_things(app_config: AppConfig, logger):
311
+ # Packaging has a few things to be thought through:
312
+ # 1. if `entrypoint_path` exists then should we package the directory
313
+ # where the entrypoint lives. For example : if the user calls
314
+ # `outerbounds app deploy foo/bar.py` should we package `foo` dir
315
+ # or should we package the cwd from which foo/bar.py is being called.
316
+ # 2. if the src path is used with the config file then how should we view
317
+ # that path ?
318
+ # 3. It becomes interesting when users call the deployment with config files
319
+ # where there is a `src_path` and then is the src_path relative to the config file
320
+ # or is it relative to where the caller command is sitting. Ideally it should work
321
+ # like Kustomizations where its relative to where the yaml file sits for simplicity
322
+ # of understanding relationships between config files. Ideally users can pass the src_path
323
+ # from the command line and that will aliviate any need to package any other directories for
324
+ #
325
+
326
+ package_dir = app_config.get_state("packaging_directory")
327
+ if package_dir is None:
328
+ app_config.set_state("code_package_url", None)
329
+ app_config.set_state("code_package_key", None)
330
+ return
331
+ from metaflow.metaflow_config import DEFAULT_DATASTORE
332
+
333
+ package = app_config.get_state("package") or {}
334
+ suffixes = package.get("suffixes", None)
335
+
336
+ packager = CodePackager(
337
+ datastore_type=DEFAULT_DATASTORE, code_package_prefix=CODE_PACKAGE_PREFIX
338
+ )
339
+ package_url, package_key = packager.store(
340
+ paths_to_include=[package_dir], file_suffixes=suffixes
341
+ )
342
+ app_config.set_state("code_package_url", package_url)
343
+ app_config.set_state("code_package_key", package_key)
344
+ logger("💾 Code Package Saved to : %s" % app_config.get_state("code_package_url"))
345
+
346
+
347
+ @app.command(help="Deploy an app to the Outerbounds Platform.")
348
+ @common_deploy_options
349
+ @common_run_options
350
+ @experimental.wrapping_cli_options
351
+ @click.pass_context
352
+ @click.argument("command", nargs=-1, type=click.UNPROCESSED, required=False)
353
+ def deploy(ctx, command, **options):
354
+ """Deploy an app to the Outerbounds Platform."""
355
+ from functools import partial
356
+
357
+ if not ctx.obj.perimeter:
358
+ raise AppConfigError("OB_CURRENT_PERIMETER is not set")
359
+
360
+ logger = partial(_logger, timestamp=True)
361
+ try:
362
+ # Create configuration
363
+ if options["config_file"]:
364
+ # Load from file
365
+ app_config = AppConfig.from_file(options["config_file"])
366
+
367
+ # Update with any CLI options using the unified method
368
+ app_config.update_from_cli_options(options)
369
+ else:
370
+ # Create from CLI options
371
+ config_dict = build_config_from_options(options)
372
+ app_config = AppConfig(config_dict)
373
+
374
+ # Validate the configuration
375
+ app_config.validate()
376
+ logger(
377
+ f"🚀 Deploying {app_config.get('name')} to the Outerbounds platform...",
378
+ color=LOGGER_COLOR,
379
+ system_msg=True,
380
+ )
381
+
382
+ packaging_directory = None
383
+ package_src_path = app_config.get("package", {}).get("src_path", None)
384
+ if package_src_path:
385
+ if os.path.isfile(package_src_path):
386
+ raise AppConfigError("src_path must be a directory, not a file")
387
+ elif os.path.isdir(package_src_path):
388
+ packaging_directory = os.path.abspath(package_src_path)
389
+ else:
390
+ raise AppConfigError(f"src_path '{package_src_path}' does not exist")
391
+ else:
392
+ # If src_path is None then we assume then we can assume for the moment
393
+ # that we can package the current working directory.
394
+ packaging_directory = os.getcwd()
395
+
396
+ app_config.set_state("packaging_directory", packaging_directory)
397
+ logger(
398
+ "📦 Packaging Directory : %s" % app_config.get_state("packaging_directory"),
399
+ )
400
+ # TODO: Construct the command needed to run the app
401
+ # If we are constructing the directory with the src_path
402
+ # then we need to add the command from the option otherwise
403
+ # we use the command from the entrypoint path and whatever follows `--`
404
+ # is the command to run.
405
+
406
+ # Set some defaults for the deploy command
407
+ app_config.set_deploy_defaults(packaging_directory)
408
+
409
+ if options.get("no_deps") == True:
410
+ # Setting this in the state will make it skip the fast-bakery step
411
+ # of building an image.
412
+ app_config.set_state("skip_dependencies", True)
413
+ else:
414
+ # Check if the user has set the dependencies in the app config
415
+ dependencies = app_config.get("dependencies", {})
416
+ if len(dependencies) == 0:
417
+ # The user has not set any dependencies, so we can sniff the packaging directory
418
+ # for a dependencies file.
419
+ requirements_file = os.path.join(
420
+ packaging_directory, "requirements.txt"
421
+ )
422
+ pyproject_toml = os.path.join(packaging_directory, "pyproject.toml")
423
+ if os.path.exists(pyproject_toml):
424
+ app_config.set_state(
425
+ "dependencies", {"from_pyproject_toml": pyproject_toml}
426
+ )
427
+ logger(
428
+ "📦 Using dependencies from pyproject.toml: %s" % pyproject_toml
429
+ )
430
+ elif os.path.exists(requirements_file):
431
+ app_config.set_state(
432
+ "dependencies", {"from_requirements_file": requirements_file}
433
+ )
434
+ logger(
435
+ "📦 Using dependencies from requirements.txt: %s"
436
+ % requirements_file
437
+ )
438
+
439
+ # Print the configuration
440
+ # 1. validate that the secrets for the app exist
441
+ # 2. TODO: validate that the compute pool specified in the app exists.
442
+ # 3. Building Docker image if necessary (based on parameters)
443
+ # - We will bake images with fastbakery and pass it to the deploy command
444
+ # TODO: validation logic can be wrapped in try catch so that we can provide
445
+ # better error messages.
446
+ cache_dir = os.path.join(
447
+ ctx.obj.app_state_dir, app_config.get("name", "default")
448
+ )
449
+ deploy_validations(
450
+ app_config,
451
+ cache_dir=cache_dir,
452
+ logger=logger,
453
+ )
454
+
455
+ base_commands = parse_commands(app_config, command)
456
+
457
+ app_config.set_state("commands", base_commands)
458
+
459
+ # TODO: Handle the case where packaging_directory is None
460
+ # This would involve:
461
+ # 1. Packaging the code:
462
+ # - We need to package the code and throw the tarball to some object store
463
+ _package_necessary_things(app_config, logger)
464
+
465
+ app_config.set_state("perimeter", ctx.obj.perimeter)
466
+
467
+ # 2. Convert to the IR that the backend accepts
468
+ capsule = Capsule(app_config, ctx.obj.api_url, debug_dir=cache_dir)
469
+
470
+ _pre_create_debug(app_config, capsule, cache_dir)
471
+ # 3. Throw the job into the platform and report deployment status
472
+ logger(
473
+ f"🚀 Deploying {capsule.capsule_type.lower()} to the platform...",
474
+ color=LOGGER_COLOR,
475
+ system_msg=True,
476
+ )
477
+ capsule.create()
478
+ capsule.wait_for_terminal_state(logger=logger)
479
+ logger(
480
+ f"💊 {capsule.capsule_type} {app_config.config['name']} ({capsule.identifier}) deployed successfully! You can access it at {capsule.status.out_of_cluster_url}",
481
+ color=LOGGER_COLOR,
482
+ system_msg=True,
483
+ )
484
+
485
+ except AppConfigError as e:
486
+ click.echo(f"Error in app configuration: {e}", err=True)
487
+ raise e
488
+ except Exception as e:
489
+ click.echo(f"Error deploying app: {e}", err=True)
490
+ raise e
491
+
492
+
493
+ @app.command(help="Run an app locally (for testing).")
494
+ @common_run_options
495
+ @click.pass_context
496
+ def run(ctx, **options):
497
+ """Run an app locally for testing."""
498
+ try:
499
+ # Create configuration
500
+ if options["config_file"]:
501
+ # Load from file
502
+ app_config = AppConfig.from_file(options["config_file"])
503
+
504
+ # Update with any CLI options using the unified method
505
+ app_config.update_from_cli_options(options)
506
+ else:
507
+ # Create from CLI options
508
+ config_dict = build_config_from_options(options)
509
+ app_config = AppConfig(config_dict)
510
+
511
+ # Validate the configuration
512
+ app_config.validate()
513
+
514
+ # Print the configuration
515
+ click.echo("Running App with configuration:")
516
+ click.echo(app_config.to_yaml())
517
+
518
+ # TODO: Implement local run logic
519
+ # This would involve:
520
+ # 1. Setting up the environment
521
+ # 2. Running the app locally
522
+ # 3. Reporting status
523
+
524
+ click.echo(f"App '{app_config.config['name']}' running locally!")
525
+
526
+ except AppConfigError as e:
527
+ click.echo(f"Error in app configuration: {e}", err=True)
528
+ ctx.exit(1)
529
+ except Exception as e:
530
+ click.echo(f"Error running app: {e}", err=True)
531
+ ctx.exit(1)
532
+
533
+
534
+ # if __name__ == "__main__":
535
+ # cli()