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