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