outerbounds 0.3.176rc6__py3-none-any.whl → 0.3.178__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.
@@ -1,697 +0,0 @@
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 CommaSeparatedListType, KVPairType, KVDictType
17
- from . import experimental
18
- from .validations import deploy_validations
19
- from .code_package import CodePackager
20
- from .capsule import Capsule, list_and_filter_capsules
21
- import shlex
22
- import time
23
- import uuid
24
- from datetime import datetime
25
-
26
- LOGGER_TIMESTAMP = "magenta"
27
- LOGGER_COLOR = "green"
28
- LOGGER_BAD_COLOR = "red"
29
-
30
- NativeList = list
31
-
32
-
33
- def _logger(
34
- body="", system_msg=False, head="", bad=False, timestamp=True, nl=True, color=None
35
- ):
36
- if timestamp:
37
- if timestamp is True:
38
- dt = datetime.now()
39
- else:
40
- dt = timestamp
41
- tstamp = dt.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
42
- click.secho(tstamp + " ", fg=LOGGER_TIMESTAMP, nl=False)
43
- if head:
44
- click.secho(head, fg=LOGGER_COLOR, nl=False)
45
- click.secho(
46
- body,
47
- bold=system_msg,
48
- fg=LOGGER_BAD_COLOR if bad else color if color is not None else None,
49
- nl=nl,
50
- )
51
-
52
-
53
- class CliState(object):
54
- pass
55
-
56
-
57
- def _pre_create_debug(app_config: AppConfig, capsule: Capsule, state_dir: str):
58
- if CAPSULE_DEBUG:
59
- os.makedirs(state_dir, exist_ok=True)
60
- debug_path = os.path.join(state_dir, f"debug_{time.time()}.yaml")
61
- with open(
62
- debug_path,
63
- "w",
64
- ) as f:
65
- f.write(
66
- yaml.dump(
67
- {
68
- "app_state": app_config.dump_state(),
69
- "capsule_input": capsule.create_input(),
70
- },
71
- default_flow_style=False,
72
- indent=2,
73
- )
74
- )
75
-
76
-
77
- def print_table(data, headers):
78
- """Print data in a formatted table."""
79
- if not data:
80
- return
81
-
82
- # Calculate column widths
83
- col_widths = [len(h) for h in headers]
84
-
85
- # Calculate actual widths based on data
86
- for row in data:
87
- for i, cell in enumerate(row):
88
- col_widths[i] = max(col_widths[i], len(str(cell)))
89
-
90
- # Print header
91
- header_row = " | ".join(
92
- [headers[i].ljust(col_widths[i]) for i in range(len(headers))]
93
- )
94
- click.secho("-" * len(header_row), fg="yellow")
95
- click.secho(header_row, fg="yellow", bold=True)
96
- click.secho("-" * len(header_row), fg="yellow")
97
-
98
- # Print data rows
99
- for row in data:
100
- formatted_row = " | ".join(
101
- [str(row[i]).ljust(col_widths[i]) for i in range(len(row))]
102
- )
103
- click.secho(formatted_row, fg="green", bold=True)
104
- click.secho("-" * len(header_row), fg="yellow")
105
-
106
-
107
- @click.group()
108
- def cli():
109
- """Outerbounds CLI tool."""
110
- pass
111
-
112
-
113
- @cli.group(
114
- help="Commands related to Deploying/Running/Managing Apps on Outerbounds Platform."
115
- )
116
- @click.pass_context
117
- def app(ctx):
118
- """App-related commands."""
119
- ctx.obj = CliState()
120
- ctx.obj.trace_id = str(uuid.uuid4())
121
- ctx.obj.app_state_dir = os.path.join(os.curdir, ".ob_apps")
122
- profile = os.environ.get("METAFLOW_PROFILE", "")
123
- config_dir = os.path.expanduser(
124
- os.environ.get("METAFLOW_HOME", "~/.metaflowconfig")
125
- )
126
- api_url = metaflowconfig.get_sanitized_url_from_config(
127
- config_dir, profile, "OBP_API_SERVER"
128
- )
129
-
130
- ctx.obj.api_url = api_url
131
- ctx.obj.perimeter = os.environ.get("OB_CURRENT_PERIMETER")
132
- os.makedirs(ctx.obj.app_state_dir, exist_ok=True)
133
-
134
-
135
- def parse_commands(app_config: AppConfig, cli_command_input):
136
- # There can be two modes:
137
- # 1. User passes command via `--` in the CLI
138
- # 2. User passes the `commands` key in the config.
139
- base_commands = []
140
- if len(cli_command_input) > 0:
141
- # TODO: we can be a little more fancy here by allowing the user to just call
142
- # `outerbounds app deploy -- foo.py` and figure out if we need to stuff python
143
- # in front of the command or not. But for sake of dumb simplicity, we can just
144
- # assume what ever the user called on local needs to be called remotely, we can
145
- # just ask them to add the outerbounds command in front of it.
146
- # So the dev ex would be :
147
- # `python foo.py` -> `outerbounds app deploy -- python foo.py`
148
- if type(cli_command_input) == str:
149
- base_commands.append(cli_command_input)
150
- else:
151
- base_commands.append(shlex.join(cli_command_input))
152
- elif app_config.get("commands", None) is not None:
153
- base_commands.extend(app_config.get("commands"))
154
- return base_commands
155
-
156
-
157
- def common_deploy_options(func):
158
- @click.option(
159
- "--name",
160
- type=str,
161
- help="The name of the app to deploy.",
162
- )
163
- @click.option("--port", type=int, help="Port where the app is hosted.")
164
- @click.option(
165
- "--tag",
166
- "tags",
167
- multiple=True,
168
- type=KVPairType,
169
- help="The tags of the app to deploy. Format KEY=VALUE. Example --tag foo=bar --tag x=y",
170
- default=None,
171
- )
172
- @click.option(
173
- "--image",
174
- type=str,
175
- help="The Docker image to deploy with the App",
176
- default=None,
177
- )
178
- @click.option(
179
- "--cpu",
180
- type=str,
181
- help="CPU resource request and limit",
182
- default=None,
183
- )
184
- @click.option(
185
- "--memory",
186
- type=str,
187
- help="Memory resource request and limit",
188
- default=None,
189
- )
190
- @click.option(
191
- "--gpu",
192
- type=str,
193
- help="GPU resource request and limit",
194
- default=None,
195
- )
196
- @click.option(
197
- "--disk",
198
- type=str,
199
- help="Storage resource request and limit",
200
- default=None,
201
- )
202
- @click.option(
203
- "--health-check-enabled",
204
- type=bool,
205
- help="Enable health checks",
206
- default=None,
207
- )
208
- @click.option(
209
- "--health-check-path",
210
- type=str,
211
- help="Health check path",
212
- default=None,
213
- )
214
- @click.option(
215
- "--health-check-initial-delay",
216
- type=int,
217
- help="Initial delay seconds for health check",
218
- default=None,
219
- )
220
- @click.option(
221
- "--health-check-period",
222
- type=int,
223
- help="Period seconds for health check",
224
- default=None,
225
- )
226
- @click.option(
227
- "--compute-pools",
228
- type=CommaSeparatedListType,
229
- help="The compute pools to deploy the app to. Example: --compute-pools default,large",
230
- default=None,
231
- )
232
- @click.option(
233
- "--auth-type",
234
- type=click.Choice(AuthType.enums()),
235
- help="The type of authentication to use for the app.",
236
- default=None,
237
- )
238
- @click.option(
239
- "--public-access/--private-access",
240
- "auth_public",
241
- type=bool,
242
- help="Whether the app is public or not.",
243
- default=None,
244
- )
245
- @click.option(
246
- "--no-deps",
247
- is_flag=True,
248
- help="Do not any dependencies. Directly used the image provided",
249
- default=False,
250
- )
251
- @click.option(
252
- "--min-replicas",
253
- type=int,
254
- help="Minimum number of replicas to deploy",
255
- default=None,
256
- )
257
- @click.option(
258
- "--max-replicas",
259
- type=int,
260
- help="Maximum number of replicas to deploy",
261
- default=None,
262
- )
263
- @click.option(
264
- "--description",
265
- type=str,
266
- help="The description of the app to deploy.",
267
- default=None,
268
- )
269
- @click.option(
270
- "--app-type",
271
- type=str,
272
- help="The type of app to deploy.",
273
- default=None,
274
- )
275
- @wraps(func)
276
- def wrapper(*args, **kwargs):
277
- return func(*args, **kwargs)
278
-
279
- return wrapper
280
-
281
-
282
- def common_run_options(func):
283
- """Common options for running and deploying apps."""
284
-
285
- @click.option(
286
- "--config-file",
287
- type=str,
288
- help="The config file to use for the App (YAML or JSON)",
289
- default=None,
290
- )
291
- @click.option(
292
- "--secret",
293
- "secrets",
294
- multiple=True,
295
- type=str,
296
- help="Secrets to deploy with the App",
297
- default=None,
298
- )
299
- @click.option(
300
- "--env",
301
- "envs",
302
- multiple=True,
303
- type=KVPairType,
304
- help="Environment variables to deploy with the App. Use format KEY=VALUE",
305
- default=None,
306
- )
307
- @click.option(
308
- "--package-src-path",
309
- type=str,
310
- help="The path to the source code to deploy with the App.",
311
- default=None,
312
- )
313
- @click.option(
314
- "--package-suffixes",
315
- type=CommaSeparatedListType,
316
- help="The suffixes of the source code to deploy with the App.",
317
- default=None,
318
- )
319
- @click.option(
320
- "--dep-from-requirements",
321
- type=str,
322
- help="Path to requirements.txt file for dependencies",
323
- default=None,
324
- )
325
- @click.option(
326
- "--dep-from-pyproject",
327
- type=str,
328
- help="Path to pyproject.toml file for dependencies",
329
- default=None,
330
- )
331
- # TODO: [FIX ME]: Get better CLI abstraction for pypi/conda dependencies
332
- @wraps(func)
333
- def wrapper(*args, **kwargs):
334
- return func(*args, **kwargs)
335
-
336
- return wrapper
337
-
338
-
339
- def _package_necessary_things(app_config: AppConfig, logger):
340
- # Packaging has a few things to be thought through:
341
- # 1. if `entrypoint_path` exists then should we package the directory
342
- # where the entrypoint lives. For example : if the user calls
343
- # `outerbounds app deploy foo/bar.py` should we package `foo` dir
344
- # or should we package the cwd from which foo/bar.py is being called.
345
- # 2. if the src path is used with the config file then how should we view
346
- # that path ?
347
- # 3. It becomes interesting when users call the deployment with config files
348
- # where there is a `src_path` and then is the src_path relative to the config file
349
- # or is it relative to where the caller command is sitting. Ideally it should work
350
- # like Kustomizations where its relative to where the yaml file sits for simplicity
351
- # of understanding relationships between config files. Ideally users can pass the src_path
352
- # from the command line and that will aliviate any need to package any other directories for
353
- #
354
-
355
- package_dir = app_config.get_state("packaging_directory")
356
- if package_dir is None:
357
- app_config.set_state("code_package_url", None)
358
- app_config.set_state("code_package_key", None)
359
- return
360
- from metaflow.metaflow_config import DEFAULT_DATASTORE
361
-
362
- package = app_config.get_state("package") or {}
363
- suffixes = package.get("suffixes", None)
364
-
365
- packager = CodePackager(
366
- datastore_type=DEFAULT_DATASTORE, code_package_prefix=CODE_PACKAGE_PREFIX
367
- )
368
- package_url, package_key = packager.store(
369
- paths_to_include=[package_dir], file_suffixes=suffixes
370
- )
371
- app_config.set_state("code_package_url", package_url)
372
- app_config.set_state("code_package_key", package_key)
373
- logger("💾 Code Package Saved to : %s" % app_config.get_state("code_package_url"))
374
-
375
-
376
- @app.command(help="Deploy an app to the Outerbounds Platform.")
377
- @common_deploy_options
378
- @common_run_options
379
- @experimental.wrapping_cli_options
380
- @click.pass_context
381
- @click.argument("command", nargs=-1, type=click.UNPROCESSED, required=False)
382
- def deploy(ctx, command, **options):
383
- """Deploy an app to the Outerbounds Platform."""
384
- from functools import partial
385
-
386
- if not ctx.obj.perimeter:
387
- raise AppConfigError("OB_CURRENT_PERIMETER is not set")
388
-
389
- logger = partial(_logger, timestamp=True)
390
- try:
391
- # Create configuration
392
- if options["config_file"]:
393
- # Load from file
394
- app_config = AppConfig.from_file(options["config_file"])
395
-
396
- # Update with any CLI options using the unified method
397
- app_config.update_from_cli_options(options)
398
- else:
399
- # Create from CLI options
400
- config_dict = build_config_from_options(options)
401
- app_config = AppConfig(config_dict)
402
-
403
- # Validate the configuration
404
- app_config.validate()
405
- logger(
406
- f"🚀 Deploying {app_config.get('name')} to the Outerbounds platform...",
407
- color=LOGGER_COLOR,
408
- system_msg=True,
409
- )
410
-
411
- packaging_directory = None
412
- package_src_path = app_config.get("package", {}).get("src_path", None)
413
- if package_src_path:
414
- if os.path.isfile(package_src_path):
415
- raise AppConfigError("src_path must be a directory, not a file")
416
- elif os.path.isdir(package_src_path):
417
- packaging_directory = os.path.abspath(package_src_path)
418
- else:
419
- raise AppConfigError(f"src_path '{package_src_path}' does not exist")
420
- else:
421
- # If src_path is None then we assume then we can assume for the moment
422
- # that we can package the current working directory.
423
- packaging_directory = os.getcwd()
424
-
425
- app_config.set_state("packaging_directory", packaging_directory)
426
- logger(
427
- "📦 Packaging Directory : %s" % app_config.get_state("packaging_directory"),
428
- )
429
- # TODO: Construct the command needed to run the app
430
- # If we are constructing the directory with the src_path
431
- # then we need to add the command from the option otherwise
432
- # we use the command from the entrypoint path and whatever follows `--`
433
- # is the command to run.
434
-
435
- # Set some defaults for the deploy command
436
- app_config.set_deploy_defaults(packaging_directory)
437
-
438
- if options.get("no_deps") == True:
439
- # Setting this in the state will make it skip the fast-bakery step
440
- # of building an image.
441
- app_config.set_state("skip_dependencies", True)
442
- else:
443
- # Check if the user has set the dependencies in the app config
444
- dependencies = app_config.get("dependencies", {})
445
- if len(dependencies) == 0:
446
- # The user has not set any dependencies, so we can sniff the packaging directory
447
- # for a dependencies file.
448
- requirements_file = os.path.join(
449
- packaging_directory, "requirements.txt"
450
- )
451
- pyproject_toml = os.path.join(packaging_directory, "pyproject.toml")
452
- if os.path.exists(pyproject_toml):
453
- app_config.set_state(
454
- "dependencies", {"from_pyproject_toml": pyproject_toml}
455
- )
456
- logger(
457
- "📦 Using dependencies from pyproject.toml: %s" % pyproject_toml
458
- )
459
- elif os.path.exists(requirements_file):
460
- app_config.set_state(
461
- "dependencies", {"from_requirements_file": requirements_file}
462
- )
463
- logger(
464
- "📦 Using dependencies from requirements.txt: %s"
465
- % requirements_file
466
- )
467
-
468
- # Print the configuration
469
- # 1. validate that the secrets for the app exist
470
- # 2. TODO: validate that the compute pool specified in the app exists.
471
- # 3. Building Docker image if necessary (based on parameters)
472
- # - We will bake images with fastbakery and pass it to the deploy command
473
- # TODO: validation logic can be wrapped in try catch so that we can provide
474
- # better error messages.
475
- cache_dir = os.path.join(
476
- ctx.obj.app_state_dir, app_config.get("name", "default")
477
- )
478
- deploy_validations(
479
- app_config,
480
- cache_dir=cache_dir,
481
- logger=logger,
482
- )
483
-
484
- base_commands = parse_commands(app_config, command)
485
-
486
- app_config.set_state("commands", base_commands)
487
-
488
- # TODO: Handle the case where packaging_directory is None
489
- # This would involve:
490
- # 1. Packaging the code:
491
- # - We need to package the code and throw the tarball to some object store
492
- _package_necessary_things(app_config, logger)
493
-
494
- app_config.set_state("perimeter", ctx.obj.perimeter)
495
-
496
- # 2. Convert to the IR that the backend accepts
497
- capsule = Capsule(app_config, ctx.obj.api_url, debug_dir=cache_dir)
498
-
499
- _pre_create_debug(app_config, capsule, cache_dir)
500
- # 3. Throw the job into the platform and report deployment status
501
- logger(
502
- f"🚀 Deploying {capsule.capsule_type.lower()} to the platform...",
503
- color=LOGGER_COLOR,
504
- system_msg=True,
505
- )
506
- capsule.create()
507
- capsule.wait_for_terminal_state(logger=logger)
508
- logger(
509
- f"💊 {capsule.capsule_type} {app_config.config['name']} ({capsule.identifier}) deployed successfully! You can access it at {capsule.status.out_of_cluster_url}",
510
- color=LOGGER_COLOR,
511
- system_msg=True,
512
- )
513
-
514
- except AppConfigError as e:
515
- click.echo(f"Error in app configuration: {e}", err=True)
516
- raise e
517
- except Exception as e:
518
- click.echo(f"Error deploying app: {e}", err=True)
519
- raise e
520
-
521
-
522
- def _parse_capsule_table(filtered_capsules):
523
- headers = ["Name", "ID", "Ready", "App Type", "Port", "Tags", "URL"]
524
- table_data = []
525
-
526
- for capsule in filtered_capsules:
527
- spec = capsule.get("spec", {})
528
- status = capsule.get("status", {}) or {}
529
- cap_id = capsule.get("id")
530
- display_name = spec.get("displayName", "")
531
- ready = str(status.get("readyToServeTraffic", False))
532
- auth_type = spec.get("authConfig", {}).get("authType", "")
533
- port = str(spec.get("port", ""))
534
- tags_str = ", ".join(
535
- [f"{tag['key']}={tag['value']}" for tag in spec.get("tags", [])]
536
- )
537
- access_info = status.get("accessInfo", {}) or {}
538
- url = access_info.get("outOfClusterURL", None)
539
-
540
- table_data.append(
541
- [
542
- display_name,
543
- cap_id,
544
- ready,
545
- auth_type,
546
- port,
547
- tags_str,
548
- f"https://{url}" if url else "URL not available",
549
- ]
550
- )
551
- return headers, table_data
552
-
553
-
554
- @app.command(help="List apps in the Outerbounds Platform.")
555
- @click.option("--project", type=str, help="Filter apps by project")
556
- @click.option("--branch", type=str, help="Filter apps by branch")
557
- @click.option("--name", type=str, help="Filter apps by name")
558
- @click.option(
559
- "--tag",
560
- "tags",
561
- type=KVDictType,
562
- help="Filter apps by tag. Format KEY=VALUE. Example --tag foo=bar --tag x=y. If multiple tags are provided, the app must match all of them.",
563
- multiple=True,
564
- )
565
- @click.option(
566
- "--format",
567
- type=click.Choice(["json", "text"]),
568
- help="Format the output",
569
- default="text",
570
- )
571
- @click.option(
572
- "--auth-type", type=click.Choice(AuthType.enums()), help="Filter apps by Auth type"
573
- )
574
- @click.pass_context
575
- def list(ctx, project, branch, name, tags, format, auth_type):
576
- """List apps in the Outerbounds Platform."""
577
-
578
- filtered_capsules = list_and_filter_capsules(
579
- ctx.obj.api_url, ctx.obj.perimeter, project, branch, name, tags, auth_type, None
580
- )
581
- if format == "json":
582
- click.echo(json.dumps(filtered_capsules, indent=4))
583
- else:
584
- headers, table_data = _parse_capsule_table(filtered_capsules)
585
- print_table(table_data, headers)
586
-
587
-
588
- @app.command(help="Delete an app/apps from the Outerbounds Platform.")
589
- @click.option("--name", type=str, help="Filter app to delete by name")
590
- @click.option("--id", "cap_id", type=str, help="Filter app to delete by id")
591
- @click.option("--project", type=str, help="Filter apps to delete by project")
592
- @click.option("--branch", type=str, help="Filter apps to delete by branch")
593
- @click.option(
594
- "--tag",
595
- "tags",
596
- multiple=True,
597
- type=KVDictType,
598
- help="Filter apps to delete by tag. Format KEY=VALUE. Example --tag foo=bar --tag x=y. If multiple tags are provided, the app must match all of them.",
599
- )
600
- @click.pass_context
601
- def delete(ctx, name, cap_id, project, branch, tags):
602
-
603
- """Delete an app/apps from the Outerbounds Platform."""
604
- # Atleast one of the args need to be provided
605
- if not any(
606
- [
607
- name is not None,
608
- cap_id is not None,
609
- project is not None,
610
- branch is not None,
611
- len(tags) != 0,
612
- ]
613
- ):
614
- raise AppConfigError(
615
- "Atleast one of the options need to be provided. You can use --name, --id, --project, --branch, --tag"
616
- )
617
-
618
- filtered_capsules = list_and_filter_capsules(
619
- ctx.obj.api_url, ctx.obj.perimeter, project, branch, name, tags, None, cap_id
620
- )
621
-
622
- headers, table_data = _parse_capsule_table(filtered_capsules)
623
- click.secho("The following apps will be deleted:", fg="red", bold=True)
624
- print_table(table_data, headers)
625
-
626
- # Confirm the deletion
627
- confirm = click.prompt(
628
- click.style(
629
- "💊 Are you sure you want to delete these apps?", fg="red", bold=True
630
- ),
631
- default="no",
632
- type=click.Choice(["yes", "no"]),
633
- )
634
- if confirm == "no":
635
- exit(1)
636
-
637
- def item_show_func(x):
638
- if not x:
639
- return None
640
- name = x.get("spec", {}).get("displayName", "")
641
- id = x.get("id", "")
642
- return click.style("💊 deleting %s [%s]" % (name, id), fg="red", bold=True)
643
-
644
- with click.progressbar(
645
- filtered_capsules,
646
- label=click.style("💊 Deleting apps...", fg="red", bold=True),
647
- fill_char=click.style("█", fg="red", bold=True),
648
- empty_char=click.style("░", fg="red", bold=True),
649
- item_show_func=item_show_func,
650
- ) as bar:
651
- for capsule in bar:
652
- Capsule.delete(capsule.get("id"), ctx.obj.api_url, ctx.obj.perimeter)
653
-
654
-
655
- @app.command(help="Run an app locally (for testing).")
656
- @common_run_options
657
- @click.pass_context
658
- def run(ctx, **options):
659
- """Run an app locally for testing."""
660
- try:
661
- # Create configuration
662
- if options["config_file"]:
663
- # Load from file
664
- app_config = AppConfig.from_file(options["config_file"])
665
-
666
- # Update with any CLI options using the unified method
667
- app_config.update_from_cli_options(options)
668
- else:
669
- # Create from CLI options
670
- config_dict = build_config_from_options(options)
671
- app_config = AppConfig(config_dict)
672
-
673
- # Validate the configuration
674
- app_config.validate()
675
-
676
- # Print the configuration
677
- click.echo("Running App with configuration:")
678
- click.echo(app_config.to_yaml())
679
-
680
- # TODO: Implement local run logic
681
- # This would involve:
682
- # 1. Setting up the environment
683
- # 2. Running the app locally
684
- # 3. Reporting status
685
-
686
- click.echo(f"App '{app_config.config['name']}' running locally!")
687
-
688
- except AppConfigError as e:
689
- click.echo(f"Error in app configuration: {e}", err=True)
690
- ctx.exit(1)
691
- except Exception as e:
692
- click.echo(f"Error running app: {e}", err=True)
693
- ctx.exit(1)
694
-
695
-
696
- # if __name__ == "__main__":
697
- # cli()