outerbounds 0.3.182rc1__py3-none-any.whl → 0.3.183__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,1474 +0,0 @@
1
- import json
2
- import os
3
- import sys
4
- import random
5
- from functools import wraps, partial
6
- from typing import Dict, List, Any, Optional, Union
7
-
8
- # IF this CLI is supposed to be reusable across Metaflow Too
9
- # Then we need to ensure that the click IMPORT happens from metaflow
10
- # so that any object class comparisons end up working as expected.
11
- # since Metaflow lazy loads Click Modules, we need to ensure that the
12
- # module's click Groups correlate to the same module otherwise Metaflow
13
- # will not accept the cli as valid.
14
- # But the BIGGEST Problem of adding a `metaflow._vendor` import is that
15
- # It will run the remote-config check and that can raise a really dirty exception
16
- # That will break the CLI.
17
- # So we need to find a way to import click without having it try to check for remote-config
18
- # or load the config from the environment.
19
- # If we import click from metaflow over here then it might
20
- # end up creating issues with click in general. So we need to figure a
21
- # way to figure the right import of click dynamically. a neat way to handle that would be
22
- # to have a function that can import the correct click based on the context in which stuff is being loaded.
23
- from .click_importer import click
24
- from outerbounds._vendor import yaml
25
- from outerbounds.utils import metaflowconfig
26
- from .app_config import (
27
- AppConfig,
28
- AppConfigError,
29
- CODE_PACKAGE_PREFIX,
30
- CAPSULE_DEBUG,
31
- AuthType,
32
- )
33
- from .perimeters import PerimeterExtractor
34
- from .cli_to_config import build_config_from_options
35
- from .utils import (
36
- MultiStepSpinner,
37
- )
38
- from . import experimental
39
- from .validations import deploy_validations
40
- from .code_package import CodePackager
41
- from .capsule import (
42
- CapsuleDeployer,
43
- list_and_filter_capsules,
44
- CapsuleApi,
45
- DEPLOYMENT_READY_CONDITIONS,
46
- CapsuleApiException,
47
- CapsuleDeploymentException,
48
- )
49
- from .dependencies import bake_deployment_image
50
- import shlex
51
- import time
52
- import uuid
53
- from datetime import datetime
54
-
55
-
56
- class KeyValueDictPair(click.ParamType):
57
- name = "KV-DICT-PAIR" # type: ignore
58
-
59
- def convert(self, value, param, ctx):
60
- # Parse a string of the form KEY=VALUE into a dict {KEY: VALUE}
61
- if len(value.split("=", 1)) != 2:
62
- self.fail(
63
- f"Invalid format for {value}. Expected format: KEY=VALUE", param, ctx
64
- )
65
-
66
- key, _value = value.split("=", 1)
67
- try:
68
- return {"key": key, "value": json.loads(_value)}
69
- except json.JSONDecodeError:
70
- return {"key": key, "value": _value}
71
- except Exception as e:
72
- self.fail(f"Invalid value for {value}. Error: {e}", param, ctx)
73
-
74
- def __str__(self):
75
- return repr(self)
76
-
77
- def __repr__(self):
78
- return "KV-PAIR"
79
-
80
-
81
- class KeyValuePair(click.ParamType):
82
- name = "KV-PAIR" # type: ignore
83
-
84
- def convert(self, value, param, ctx):
85
- # Parse a string of the form KEY=VALUE into a dict {KEY: VALUE}
86
- if len(value.split("=", 1)) != 2:
87
- self.fail(
88
- f"Invalid format for {value}. Expected format: KEY=VALUE", param, ctx
89
- )
90
-
91
- key, _value = value.split("=", 1)
92
- try:
93
- return {key: json.loads(_value)}
94
- except json.JSONDecodeError:
95
- return {key: _value}
96
- except Exception as e:
97
- self.fail(f"Invalid value for {value}. Error: {e}", param, ctx)
98
-
99
- def __str__(self):
100
- return repr(self)
101
-
102
- def __repr__(self):
103
- return "KV-PAIR"
104
-
105
-
106
- class MountMetaflowArtifact(click.ParamType):
107
- name = "MOUNT-METAFLOW-ARTIFACT" # type: ignore
108
-
109
- def convert(self, value, param, ctx):
110
- """
111
- Convert a string like "flow=MyFlow,artifact=my_model,path=/tmp/abc" or
112
- "pathspec=MyFlow/123/foo/345/my_model,path=/tmp/abc" to a dict.
113
- """
114
- artifact_dict = {}
115
- parts = value.split(",")
116
-
117
- for part in parts:
118
- if "=" not in part:
119
- self.fail(
120
- f"Invalid format in part '{part}'. Expected 'key=value'", param, ctx
121
- )
122
-
123
- key, val = part.split("=", 1)
124
- artifact_dict[key.strip()] = val.strip()
125
-
126
- # Validate required fields
127
- if "pathspec" in artifact_dict:
128
- if "path" not in artifact_dict:
129
- self.fail(
130
- "When using 'pathspec', you must also specify 'path'", param, ctx
131
- )
132
-
133
- # Return as pathspec format
134
- return {
135
- "pathspec": artifact_dict["pathspec"],
136
- "path": artifact_dict["path"],
137
- }
138
- elif (
139
- "flow" in artifact_dict
140
- and "artifact" in artifact_dict
141
- and "path" in artifact_dict
142
- ):
143
- # Return as flow/artifact format
144
- result = {
145
- "flow": artifact_dict["flow"],
146
- "artifact": artifact_dict["artifact"],
147
- "path": artifact_dict["path"],
148
- }
149
-
150
- # Add optional namespace if provided
151
- if "namespace" in artifact_dict:
152
- result["namespace"] = artifact_dict["namespace"]
153
-
154
- return result
155
- else:
156
- self.fail(
157
- "Invalid format. Must be either 'flow=X,artifact=Y,path=Z' or 'pathspec=X,path=Z'",
158
- param,
159
- ctx,
160
- )
161
-
162
- def __str__(self):
163
- return repr(self)
164
-
165
- def __repr__(self):
166
- return "MOUNT-METAFLOW-ARTIFACT"
167
-
168
-
169
- class MountSecret(click.ParamType):
170
- name = "MOUNT-SECRET" # type: ignore
171
-
172
- def convert(self, value, param, ctx):
173
- """
174
- Convert a string like "id=my_secret,path=/tmp/secret" to a dict.
175
- """
176
- secret_dict = {}
177
- parts = value.split(",")
178
-
179
- for part in parts:
180
- if "=" not in part:
181
- self.fail(
182
- f"Invalid format in part '{part}'. Expected 'key=value'", param, ctx
183
- )
184
-
185
- key, val = part.split("=", 1)
186
- secret_dict[key.strip()] = val.strip()
187
-
188
- # Validate required fields
189
- if "id" in secret_dict and "path" in secret_dict:
190
- return {"id": secret_dict["id"], "path": secret_dict["path"]}
191
- else:
192
- self.fail("Invalid format. Must be 'key=X,path=Y'", param, ctx)
193
-
194
- def __str__(self):
195
- return repr(self)
196
-
197
- def __repr__(self):
198
- return "MOUNT-SECRET"
199
-
200
-
201
- class CommaSeparatedList(click.ParamType):
202
- name = "COMMA-SEPARATED-LIST" # type: ignore
203
-
204
- def convert(self, value, param, ctx):
205
- return value.split(",")
206
-
207
- def __str__(self):
208
- return repr(self)
209
-
210
- def __repr__(self):
211
- return "COMMA-SEPARATED-LIST"
212
-
213
-
214
- KVPairType = KeyValuePair()
215
- MetaflowArtifactType = MountMetaflowArtifact()
216
- SecretMountType = MountSecret()
217
- CommaSeparatedListType = CommaSeparatedList()
218
- KVDictType = KeyValueDictPair()
219
-
220
-
221
- class ColorTheme:
222
- TIMESTAMP = "magenta"
223
- LOADING_COLOR = "cyan"
224
- BAD_COLOR = "red"
225
- INFO_COLOR = "green"
226
-
227
- TL_HEADER_COLOR = "magenta"
228
- ROW_COLOR = "bright_white"
229
-
230
- INFO_KEY_COLOR = "green"
231
- INFO_VALUE_COLOR = "bright_white"
232
-
233
-
234
- NativeList = list
235
-
236
-
237
- def _logger(
238
- body="", system_msg=False, head="", bad=False, timestamp=True, nl=True, color=None
239
- ):
240
- if timestamp:
241
- if timestamp is True:
242
- dt = datetime.now()
243
- else:
244
- dt = timestamp
245
- tstamp = dt.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
246
- click.secho(tstamp + " ", fg=ColorTheme.TIMESTAMP, nl=False)
247
- if head:
248
- click.secho(head, fg=ColorTheme.INFO_COLOR, nl=False)
249
- click.secho(
250
- body,
251
- bold=system_msg,
252
- fg=ColorTheme.BAD_COLOR if bad else color if color is not None else None,
253
- nl=nl,
254
- )
255
-
256
-
257
- def _logger_styled(
258
- body="", system_msg=False, head="", bad=False, timestamp=True, nl=True, color=None
259
- ):
260
- message_parts = []
261
-
262
- if timestamp:
263
- if timestamp is True:
264
- dt = datetime.now()
265
- else:
266
- dt = timestamp
267
- tstamp = dt.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
268
- message_parts.append(click.style(tstamp + " ", fg=ColorTheme.TIMESTAMP))
269
-
270
- if head:
271
- message_parts.append(click.style(head, fg=ColorTheme.INFO_COLOR))
272
-
273
- message_parts.append(
274
- click.style(
275
- body,
276
- bold=system_msg,
277
- fg=ColorTheme.BAD_COLOR if bad else color if color is not None else None,
278
- )
279
- )
280
-
281
- return "".join(message_parts)
282
-
283
-
284
- def _spinner_logger(spinner, *msg):
285
- spinner.log(*[_logger_styled(x, timestamp=True) for x in msg])
286
-
287
-
288
- class CliState(object):
289
- pass
290
-
291
-
292
- def _pre_create_debug(
293
- app_config: AppConfig,
294
- capsule: CapsuleDeployer,
295
- state_dir: str,
296
- options: Dict[str, Any],
297
- cli_parsed_config: Dict[str, Any],
298
- ):
299
- if CAPSULE_DEBUG:
300
- os.makedirs(state_dir, exist_ok=True)
301
- debug_path = os.path.join(state_dir, f"debug_{time.time()}.yaml")
302
- with open(
303
- debug_path,
304
- "w",
305
- ) as f:
306
- f.write(
307
- json.dumps(
308
- {
309
- "app_state": app_config.dump_state(), # This is the state of the app config after parsing the CLI options and right before the capsule deploy API is called
310
- "capsule_input": capsule.create_input(), # This is the input that is passed to the capsule deploy API
311
- "deploy_response": capsule._capsule_deploy_response, # This is the response from the capsule deploy API
312
- "cli_options": options, # These are the actual options passing down to the CLI
313
- "cli_parsed_config": cli_parsed_config, # This is the config object that is created after parsing options from the CLI
314
- },
315
- indent=2,
316
- default=str,
317
- )
318
- )
319
-
320
-
321
- def _post_create_debug(capsule: CapsuleDeployer, state_dir: str):
322
- if CAPSULE_DEBUG:
323
- debug_path = os.path.join(
324
- state_dir, f"debug_deploy_response_{time.time()}.yaml"
325
- )
326
- with open(debug_path, "w") as f:
327
- f.write(
328
- yaml.dump(
329
- capsule._capsule_deploy_response, default_flow_style=False, indent=2
330
- )
331
- )
332
-
333
-
334
- def _bake_image(app_config: AppConfig, cache_dir: str, logger):
335
- baking_status = bake_deployment_image(
336
- app_config=app_config,
337
- cache_file_path=os.path.join(cache_dir, "image_cache"),
338
- logger=logger,
339
- )
340
- app_config.set_state(
341
- "image",
342
- baking_status.resolved_image,
343
- )
344
- app_config.set_state("python_path", baking_status.python_path)
345
- logger("🐳 Using The Docker Image : %s" % app_config.get_state("image"))
346
-
347
-
348
- def print_table(data, headers):
349
- """Print data in a formatted table."""
350
-
351
- if not data:
352
- return
353
-
354
- # Calculate column widths
355
- col_widths = [len(h) for h in headers]
356
-
357
- # Calculate actual widths based on data
358
- for row in data:
359
- for i, cell in enumerate(row):
360
- col_widths[i] = max(col_widths[i], len(str(cell)))
361
-
362
- # Print header
363
- header_row = " | ".join(
364
- [headers[i].ljust(col_widths[i]) for i in range(len(headers))]
365
- )
366
- click.secho("-" * len(header_row), fg=ColorTheme.TL_HEADER_COLOR)
367
- click.secho(header_row, fg=ColorTheme.TL_HEADER_COLOR, bold=True)
368
- click.secho("-" * len(header_row), fg=ColorTheme.TL_HEADER_COLOR)
369
-
370
- # Print data rows
371
- for row in data:
372
- formatted_row = " | ".join(
373
- [str(row[i]).ljust(col_widths[i]) for i in range(len(row))]
374
- )
375
- click.secho(formatted_row, fg=ColorTheme.ROW_COLOR, bold=True)
376
- click.secho("-" * len(header_row), fg=ColorTheme.TL_HEADER_COLOR)
377
-
378
-
379
- @click.group()
380
- def cli():
381
- """Outerbounds CLI tool."""
382
- pass
383
-
384
-
385
- @cli.group(
386
- help="Commands related to Deploying/Running/Managing Apps on Outerbounds Platform."
387
- )
388
- @click.pass_context
389
- def app(ctx):
390
- """App-related commands."""
391
- metaflow_set_context = getattr(ctx, "obj", None)
392
- ctx.obj = CliState()
393
- ctx.obj.trace_id = str(uuid.uuid4())
394
- ctx.obj.app_state_dir = os.path.join(os.curdir, ".ob_apps")
395
- profile = os.environ.get("METAFLOW_PROFILE", "")
396
- config_dir = os.path.expanduser(
397
- os.environ.get("METAFLOW_HOME", "~/.metaflowconfig")
398
- )
399
- perimeter, api_server = PerimeterExtractor.for_ob_cli(
400
- config_dir=config_dir, profile=profile
401
- )
402
- if perimeter is None or api_server is None:
403
- raise AppConfigError(
404
- "Perimeter not found in the environment, Found perimeter: %s, api_server: %s"
405
- % (perimeter, api_server)
406
- )
407
- ctx.obj.perimeter = perimeter
408
- ctx.obj.api_url = api_server
409
- os.makedirs(ctx.obj.app_state_dir, exist_ok=True)
410
-
411
-
412
- def parse_commands(app_config: AppConfig, cli_command_input):
413
- # There can be two modes:
414
- # 1. User passes command via `--` in the CLI
415
- # 2. User passes the `commands` key in the config.
416
- base_commands = []
417
- if len(cli_command_input) > 0:
418
- # TODO: we can be a little more fancy here by allowing the user to just call
419
- # `outerbounds app deploy -- foo.py` and figure out if we need to stuff python
420
- # in front of the command or not. But for sake of dumb simplicity, we can just
421
- # assume what ever the user called on local needs to be called remotely, we can
422
- # just ask them to add the outerbounds command in front of it.
423
- # So the dev ex would be :
424
- # `python foo.py` -> `outerbounds app deploy -- python foo.py`
425
- if type(cli_command_input) == str:
426
- base_commands.append(cli_command_input)
427
- else:
428
- base_commands.append(shlex.join(cli_command_input))
429
- elif app_config.get("commands", None) is not None:
430
- base_commands.extend(app_config.get("commands"))
431
- return base_commands
432
-
433
-
434
- def deployment_instance_options(func):
435
- # These parameters influence how the CLI behaves for each instance of a launched deployment.
436
- @click.option(
437
- "--readiness-condition",
438
- type=click.Choice(DEPLOYMENT_READY_CONDITIONS.enums()),
439
- help=DEPLOYMENT_READY_CONDITIONS.__doc__,
440
- default=DEPLOYMENT_READY_CONDITIONS.ATLEAST_ONE_RUNNING,
441
- )
442
- @click.option(
443
- "--readiness-wait-time",
444
- type=int,
445
- help="The time (in seconds) to monitor the deployment for readiness after the readiness condition is met.",
446
- default=4,
447
- )
448
- @click.option(
449
- "--max-wait-time",
450
- type=int,
451
- help="The maximum time (in seconds) to wait for the deployment to be ready.",
452
- default=600,
453
- )
454
- @click.option(
455
- "--no-loader",
456
- is_flag=True,
457
- help="Do not use the loading spinner for the deployment.",
458
- default=False,
459
- )
460
- @wraps(func)
461
- def wrapper(*args, **kwargs):
462
- return func(*args, **kwargs)
463
-
464
- return wrapper
465
-
466
-
467
- def common_deploy_options(func):
468
- @click.option(
469
- "--name",
470
- type=str,
471
- help="The name of the app to deploy.",
472
- )
473
- @click.option("--port", type=int, help="Port where the app is hosted.")
474
- @click.option(
475
- "--tag",
476
- "tags",
477
- multiple=True,
478
- type=KVPairType,
479
- help="The tags of the app to deploy. Format KEY=VALUE. Example --tag foo=bar --tag x=y",
480
- default=None,
481
- )
482
- @click.option(
483
- "--image",
484
- type=str,
485
- help="The Docker image to deploy with the App",
486
- default=None,
487
- )
488
- @click.option(
489
- "--cpu",
490
- type=str,
491
- help="CPU resource request and limit",
492
- default=None,
493
- )
494
- @click.option(
495
- "--memory",
496
- type=str,
497
- help="Memory resource request and limit",
498
- default=None,
499
- )
500
- @click.option(
501
- "--gpu",
502
- type=str,
503
- help="GPU resource request and limit",
504
- default=None,
505
- )
506
- @click.option(
507
- "--disk",
508
- type=str,
509
- help="Storage resource request and limit",
510
- default=None,
511
- )
512
- @click.option(
513
- "--health-check-enabled",
514
- type=bool,
515
- help="Enable health checks",
516
- default=None,
517
- )
518
- @click.option(
519
- "--health-check-path",
520
- type=str,
521
- help="Health check path",
522
- default=None,
523
- )
524
- @click.option(
525
- "--health-check-initial-delay",
526
- type=int,
527
- help="Initial delay seconds for health check",
528
- default=None,
529
- )
530
- @click.option(
531
- "--health-check-period",
532
- type=int,
533
- help="Period seconds for health check",
534
- default=None,
535
- )
536
- @click.option(
537
- "--compute-pools",
538
- type=CommaSeparatedListType,
539
- help="The compute pools to deploy the app to. Example: --compute-pools default,large",
540
- default=None,
541
- )
542
- @click.option(
543
- "--auth-type",
544
- type=click.Choice(AuthType.enums()),
545
- help="The type of authentication to use for the app.",
546
- default=None,
547
- )
548
- @click.option(
549
- "--public-access/--private-access",
550
- "auth_public",
551
- type=bool,
552
- help="Whether the app is public or not.",
553
- default=None,
554
- )
555
- @click.option(
556
- "--no-deps",
557
- is_flag=True,
558
- help="Do not any dependencies. Directly used the image provided",
559
- default=False,
560
- )
561
- @click.option(
562
- "--min-replicas",
563
- type=int,
564
- help="Minimum number of replicas to deploy",
565
- default=None,
566
- )
567
- @click.option(
568
- "--max-replicas",
569
- type=int,
570
- help="Maximum number of replicas to deploy",
571
- default=None,
572
- )
573
- @click.option(
574
- "--description",
575
- type=str,
576
- help="The description of the app to deploy.",
577
- default=None,
578
- )
579
- @click.option(
580
- "--app-type",
581
- type=str,
582
- help="The type of app to deploy.",
583
- default=None,
584
- )
585
- @click.option(
586
- "--force-upgrade",
587
- is_flag=True,
588
- help="Force upgrade the app even if it is currently being upgraded.",
589
- default=False,
590
- )
591
- @wraps(func)
592
- def wrapper(*args, **kwargs):
593
- return func(*args, **kwargs)
594
-
595
- return wrapper
596
-
597
-
598
- def common_run_options(func):
599
- """Common options for running and deploying apps."""
600
-
601
- @click.option(
602
- "--config-file",
603
- type=str,
604
- help="The config file to use for the App (YAML or JSON)",
605
- default=None,
606
- )
607
- @click.option(
608
- "--secret",
609
- "secrets",
610
- multiple=True,
611
- type=str,
612
- help="Secrets to deploy with the App",
613
- default=None,
614
- )
615
- @click.option(
616
- "--env",
617
- "envs",
618
- multiple=True,
619
- type=KVPairType,
620
- help="Environment variables to deploy with the App. Use format KEY=VALUE",
621
- default=None,
622
- )
623
- @click.option(
624
- "--package-src-path",
625
- type=str,
626
- help="The path to the source code to deploy with the App.",
627
- default=None,
628
- )
629
- @click.option(
630
- "--package-suffixes",
631
- type=CommaSeparatedListType,
632
- help="The suffixes of the source code to deploy with the App.",
633
- default=None,
634
- )
635
- @click.option(
636
- "--dep-from-requirements",
637
- type=str,
638
- help="Path to requirements.txt file for dependencies",
639
- default=None,
640
- )
641
- @click.option(
642
- "--dep-from-pyproject",
643
- type=str,
644
- help="Path to pyproject.toml file for dependencies",
645
- default=None,
646
- )
647
- # TODO: [FIX ME]: Get better CLI abstraction for pypi/conda dependencies
648
- @wraps(func)
649
- def wrapper(*args, **kwargs):
650
- return func(*args, **kwargs)
651
-
652
- return wrapper
653
-
654
-
655
- def _package_necessary_things(app_config: AppConfig, logger):
656
- # Packaging has a few things to be thought through:
657
- # 1. if `entrypoint_path` exists then should we package the directory
658
- # where the entrypoint lives. For example : if the user calls
659
- # `outerbounds app deploy foo/bar.py` should we package `foo` dir
660
- # or should we package the cwd from which foo/bar.py is being called.
661
- # 2. if the src path is used with the config file then how should we view
662
- # that path ?
663
- # 3. It becomes interesting when users call the deployment with config files
664
- # where there is a `src_path` and then is the src_path relative to the config file
665
- # or is it relative to where the caller command is sitting. Ideally it should work
666
- # like Kustomizations where its relative to where the yaml file sits for simplicity
667
- # of understanding relationships between config files. Ideally users can pass the src_path
668
- # from the command line and that will aliviate any need to package any other directories for
669
- #
670
-
671
- package_dir = app_config.get_state("packaging_directory")
672
- if package_dir is None:
673
- app_config.set_state("code_package_url", None)
674
- app_config.set_state("code_package_key", None)
675
- return
676
- from metaflow.metaflow_config import DEFAULT_DATASTORE
677
-
678
- package = app_config.get_state("package") or {}
679
- suffixes = package.get("suffixes", None)
680
-
681
- packager = CodePackager(
682
- datastore_type=DEFAULT_DATASTORE, code_package_prefix=CODE_PACKAGE_PREFIX
683
- )
684
- package_url, package_key = packager.store(
685
- paths_to_include=[package_dir], file_suffixes=suffixes
686
- )
687
- app_config.set_state("code_package_url", package_url)
688
- app_config.set_state("code_package_key", package_key)
689
- logger("💾 Code Package Saved to : %s" % app_config.get_state("code_package_url"))
690
-
691
-
692
- @app.command(help="Deploy an app to the Outerbounds Platform.")
693
- @common_deploy_options
694
- @common_run_options
695
- @deployment_instance_options
696
- @experimental.wrapping_cli_options
697
- @click.pass_context
698
- @click.argument("command", nargs=-1, type=click.UNPROCESSED, required=False)
699
- def deploy(
700
- ctx,
701
- command,
702
- readiness_condition=None,
703
- max_wait_time=None,
704
- readiness_wait_time=None,
705
- no_loader=False,
706
- **options,
707
- ):
708
- """Deploy an app to the Outerbounds Platform."""
709
- from functools import partial
710
-
711
- if not ctx.obj.perimeter:
712
- raise AppConfigError("OB_CURRENT_PERIMETER is not set")
713
-
714
- logger = partial(_logger, timestamp=True)
715
- try:
716
- _cli_parsed_config = build_config_from_options(options)
717
- # Create configuration
718
- if options["config_file"]:
719
- # Load from file
720
- app_config = AppConfig.from_file(options["config_file"])
721
-
722
- # Update with any CLI options using the unified method
723
- app_config.update_from_cli_options(options)
724
- else:
725
- # Create from CLI options
726
- app_config = AppConfig(_cli_parsed_config)
727
-
728
- # Validate the configuration
729
- app_config.validate()
730
- logger(
731
- f"🚀 Deploying {app_config.get('name')} to the Outerbounds platform...",
732
- color=ColorTheme.INFO_COLOR,
733
- system_msg=True,
734
- )
735
-
736
- packaging_directory = None
737
- package_src_path = app_config.get("package", {}).get("src_path", None)
738
- if package_src_path:
739
- if os.path.isfile(package_src_path):
740
- raise AppConfigError("src_path must be a directory, not a file")
741
- elif os.path.isdir(package_src_path):
742
- packaging_directory = os.path.abspath(package_src_path)
743
- else:
744
- raise AppConfigError(f"src_path '{package_src_path}' does not exist")
745
- else:
746
- # If src_path is None then we assume then we can assume for the moment
747
- # that we can package the current working directory.
748
- packaging_directory = os.getcwd()
749
-
750
- app_config.set_state("packaging_directory", packaging_directory)
751
- logger(
752
- "📦 Packaging Directory : %s" % app_config.get_state("packaging_directory"),
753
- )
754
- # TODO: Construct the command needed to run the app
755
- # If we are constructing the directory with the src_path
756
- # then we need to add the command from the option otherwise
757
- # we use the command from the entrypoint path and whatever follows `--`
758
- # is the command to run.
759
-
760
- # Set some defaults for the deploy command
761
- app_config.set_deploy_defaults(packaging_directory)
762
-
763
- if options.get("no_deps") == True:
764
- # Setting this in the state will make it skip the fast-bakery step
765
- # of building an image.
766
- app_config.set_state("skip_dependencies", True)
767
- else:
768
- # Check if the user has set the dependencies in the app config
769
- dependencies = app_config.get("dependencies", {})
770
- if len(dependencies) == 0:
771
- # The user has not set any dependencies, so we can sniff the packaging directory
772
- # for a dependencies file.
773
- requirements_file = os.path.join(
774
- packaging_directory, "requirements.txt"
775
- )
776
- pyproject_toml = os.path.join(packaging_directory, "pyproject.toml")
777
- if os.path.exists(pyproject_toml):
778
- app_config.set_state(
779
- "dependencies", {"from_pyproject_toml": pyproject_toml}
780
- )
781
- logger(
782
- "📦 Using dependencies from pyproject.toml: %s" % pyproject_toml
783
- )
784
- elif os.path.exists(requirements_file):
785
- app_config.set_state(
786
- "dependencies", {"from_requirements_file": requirements_file}
787
- )
788
- logger(
789
- "📦 Using dependencies from requirements.txt: %s"
790
- % requirements_file
791
- )
792
-
793
- # Print the configuration
794
- # 1. validate that the secrets for the app exist
795
- # 2. TODO: validate that the compute pool specified in the app exists.
796
- # 3. Building Docker image if necessary (based on parameters)
797
- # - We will bake images with fastbakery and pass it to the deploy command
798
- # TODO: validation logic can be wrapped in try catch so that we can provide
799
- # better error messages.
800
- cache_dir = os.path.join(
801
- ctx.obj.app_state_dir, app_config.get("name", "default")
802
- )
803
-
804
- def _non_spinner_logger(*msg):
805
- for m in msg:
806
- logger(m)
807
-
808
- deploy_validations(
809
- app_config,
810
- cache_dir=cache_dir,
811
- logger=logger,
812
- )
813
- image_spinner = None
814
- img_logger = _non_spinner_logger
815
- if not no_loader:
816
- image_spinner = MultiStepSpinner(
817
- text=lambda: _logger_styled(
818
- "🍞 Baking Docker Image",
819
- timestamp=True,
820
- ),
821
- color=ColorTheme.LOADING_COLOR,
822
- )
823
- img_logger = partial(_spinner_logger, image_spinner)
824
- image_spinner.start()
825
-
826
- _bake_image(app_config, cache_dir, img_logger)
827
- if image_spinner:
828
- image_spinner.stop()
829
-
830
- base_commands = parse_commands(app_config, command)
831
-
832
- app_config.set_state("commands", base_commands)
833
-
834
- # TODO: Handle the case where packaging_directory is None
835
- # This would involve:
836
- # 1. Packaging the code:
837
- # - We need to package the code and throw the tarball to some object store
838
- _package_necessary_things(app_config, logger)
839
-
840
- app_config.set_state("perimeter", ctx.obj.perimeter)
841
-
842
- # 2. Convert to the IR that the backend accepts
843
- capsule = CapsuleDeployer(
844
- app_config,
845
- ctx.obj.api_url,
846
- debug_dir=cache_dir,
847
- success_terminal_state_condition=readiness_condition,
848
- create_timeout=max_wait_time,
849
- readiness_wait_time=readiness_wait_time,
850
- )
851
- currently_present_capsules = list_and_filter_capsules(
852
- capsule.capsule_api,
853
- None,
854
- None,
855
- capsule.name,
856
- None,
857
- None,
858
- None,
859
- )
860
-
861
- force_upgrade = app_config.get_state("force_upgrade", False)
862
-
863
- _pre_create_debug(app_config, capsule, cache_dir, options, _cli_parsed_config)
864
-
865
- if len(currently_present_capsules) > 0:
866
- # Only update the capsule if there is no upgrade in progress
867
- # Only update a "already updating" capsule if the `--force-upgrade` flag is provided.
868
- _curr_cap = currently_present_capsules[0]
869
- this_capsule_is_being_updated = _curr_cap.get("status", {}).get(
870
- "updateInProgress", False
871
- )
872
-
873
- if this_capsule_is_being_updated and not force_upgrade:
874
- _upgrader = _curr_cap.get("metadata", {}).get("lastModifiedBy", None)
875
- message = f"{capsule.capsule_type} is currently being upgraded"
876
- if _upgrader:
877
- message = (
878
- f"{capsule.capsule_type} is currently being upgraded. Upgrade was launched by {_upgrader}. "
879
- "If you wish to force upgrade, you can do so by providing the `--force-upgrade` flag."
880
- )
881
- raise AppConfigError(message)
882
- logger(
883
- f"🚀 {'' if not force_upgrade else 'Force'} Upgrading {capsule.capsule_type.lower()} `{capsule.name}`....",
884
- color=ColorTheme.INFO_COLOR,
885
- system_msg=True,
886
- )
887
- else:
888
- logger(
889
- f"🚀 Deploying {capsule.capsule_type.lower()} to the platform....",
890
- color=ColorTheme.INFO_COLOR,
891
- system_msg=True,
892
- )
893
- # 3. Throw the job into the platform and report deployment status
894
- capsule.create()
895
- _post_create_debug(capsule, cache_dir)
896
-
897
- capsule_spinner = None
898
- capsule_logger = _non_spinner_logger
899
- if not no_loader:
900
- capsule_spinner = MultiStepSpinner(
901
- text=lambda: _logger_styled(
902
- "💊 Waiting for %s %s to be ready to serve traffic"
903
- % (capsule.capsule_type.lower(), capsule.identifier),
904
- timestamp=True,
905
- ),
906
- color=ColorTheme.LOADING_COLOR,
907
- )
908
- capsule_logger = partial(_spinner_logger, capsule_spinner)
909
- capsule_spinner.start()
910
-
911
- capsule.wait_for_terminal_state(logger=capsule_logger)
912
- if capsule_spinner:
913
- capsule_spinner.stop()
914
-
915
- logger(
916
- f"💊 {capsule.capsule_type} {app_config.config['name']} ({capsule.identifier}) deployed successfully! You can access it at {capsule.status.out_of_cluster_url}",
917
- color=ColorTheme.INFO_COLOR,
918
- system_msg=True,
919
- )
920
-
921
- except Exception as e:
922
- logger(
923
- f"Deployment failed: [{e.__class__.__name__}]: {e}",
924
- bad=True,
925
- system_msg=True,
926
- )
927
- exit(1)
928
-
929
-
930
- def _parse_capsule_table(filtered_capsules):
931
- headers = ["Name", "ID", "Ready", "App Type", "Port", "Tags", "URL"]
932
- table_data = []
933
-
934
- for capsule in filtered_capsules:
935
- spec = capsule.get("spec", {})
936
- status = capsule.get("status", {}) or {}
937
- cap_id = capsule.get("id")
938
- display_name = spec.get("displayName", "")
939
- ready = str(status.get("readyToServeTraffic", False))
940
- auth_type = spec.get("authConfig", {}).get("authType", "")
941
- port = str(spec.get("port", ""))
942
- tags_str = ", ".join(
943
- [f"{tag['key']}={tag['value']}" for tag in spec.get("tags", [])]
944
- )
945
- access_info = status.get("accessInfo", {}) or {}
946
- url = access_info.get("outOfClusterURL", None)
947
-
948
- table_data.append(
949
- [
950
- display_name,
951
- cap_id,
952
- ready,
953
- auth_type,
954
- port,
955
- tags_str,
956
- f"https://{url}" if url else "URL not available",
957
- ]
958
- )
959
- return headers, table_data
960
-
961
-
962
- @app.command(help="List apps in the Outerbounds Platform.")
963
- @click.option("--project", type=str, help="Filter apps by project")
964
- @click.option("--branch", type=str, help="Filter apps by branch")
965
- @click.option("--name", type=str, help="Filter apps by name")
966
- @click.option(
967
- "--tag",
968
- "tags",
969
- type=KVDictType,
970
- 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.",
971
- multiple=True,
972
- )
973
- @click.option(
974
- "--format",
975
- type=click.Choice(["json", "text"]),
976
- help="Format the output",
977
- default="text",
978
- )
979
- @click.option(
980
- "--auth-type", type=click.Choice(AuthType.enums()), help="Filter apps by Auth type"
981
- )
982
- @click.pass_context
983
- def list(ctx, project, branch, name, tags, format, auth_type):
984
- """List apps in the Outerbounds Platform."""
985
- capsule_api = CapsuleApi(
986
- ctx.obj.api_url,
987
- ctx.obj.perimeter,
988
- )
989
- filtered_capsules = list_and_filter_capsules(
990
- capsule_api, project, branch, name, tags, auth_type, None
991
- )
992
- if format == "json":
993
- click.echo(json.dumps(filtered_capsules, indent=4))
994
- else:
995
- headers, table_data = _parse_capsule_table(filtered_capsules)
996
- print_table(table_data, headers)
997
-
998
-
999
- @app.command(help="Delete an app/apps from the Outerbounds Platform.")
1000
- @click.option("--name", type=str, help="Filter app to delete by name")
1001
- @click.option("--id", "cap_id", type=str, help="Filter app to delete by id")
1002
- @click.option("--project", type=str, help="Filter apps to delete by project")
1003
- @click.option("--branch", type=str, help="Filter apps to delete by branch")
1004
- @click.option(
1005
- "--tag",
1006
- "tags",
1007
- multiple=True,
1008
- type=KVDictType,
1009
- 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.",
1010
- )
1011
- @click.option("--auto-approve", is_flag=True, help="Do not prompt for confirmation")
1012
- @click.pass_context
1013
- def delete(ctx, name, cap_id, project, branch, tags, auto_approve):
1014
-
1015
- """Delete an app/apps from the Outerbounds Platform."""
1016
- # Atleast one of the args need to be provided
1017
- if not any(
1018
- [
1019
- name is not None,
1020
- cap_id is not None,
1021
- project is not None,
1022
- branch is not None,
1023
- len(tags) != 0,
1024
- ]
1025
- ):
1026
- raise AppConfigError(
1027
- "Atleast one of the options need to be provided. You can use --name, --id, --project, --branch, --tag"
1028
- )
1029
-
1030
- capsule_api = CapsuleApi(ctx.obj.api_url, ctx.obj.perimeter)
1031
- filtered_capsules = list_and_filter_capsules(
1032
- capsule_api, project, branch, name, tags, None, cap_id
1033
- )
1034
-
1035
- headers, table_data = _parse_capsule_table(filtered_capsules)
1036
- click.secho("The following apps will be deleted:", fg="red", bold=True)
1037
- print_table(table_data, headers)
1038
-
1039
- # Confirm the deletion
1040
- if not auto_approve:
1041
- confirm = click.prompt(
1042
- click.style(
1043
- "💊 Are you sure you want to delete these apps?", fg="red", bold=True
1044
- ),
1045
- default="no",
1046
- type=click.Choice(["yes", "no"]),
1047
- )
1048
- if confirm == "no":
1049
- exit(1)
1050
-
1051
- def item_show_func(x):
1052
- if not x:
1053
- return None
1054
- name = x.get("spec", {}).get("displayName", "")
1055
- id = x.get("id", "")
1056
- return click.style(
1057
- "💊 deleting %s [%s]" % (name, id),
1058
- fg=ColorTheme.BAD_COLOR,
1059
- bold=True,
1060
- )
1061
-
1062
- with click.progressbar(
1063
- filtered_capsules,
1064
- label=click.style("💊 Deleting apps...", fg=ColorTheme.BAD_COLOR, bold=True),
1065
- fill_char=click.style("█", fg=ColorTheme.BAD_COLOR, bold=True),
1066
- empty_char=click.style("░", fg=ColorTheme.BAD_COLOR, bold=True),
1067
- item_show_func=item_show_func,
1068
- ) as bar:
1069
- for capsule in bar:
1070
- capsule_api.delete(capsule.get("id"))
1071
- time.sleep(0.5 + random.random() * 2) # delay to avoid rate limiting
1072
-
1073
-
1074
- @app.command(help="Run an app locally (for testing).")
1075
- @common_run_options
1076
- @click.pass_context
1077
- def run(ctx, **options):
1078
- """Run an app locally for testing."""
1079
- try:
1080
- # Create configuration
1081
- if options["config_file"]:
1082
- # Load from file
1083
- app_config = AppConfig.from_file(options["config_file"])
1084
-
1085
- # Update with any CLI options using the unified method
1086
- app_config.update_from_cli_options(options)
1087
- else:
1088
- # Create from CLI options
1089
- config_dict = build_config_from_options(options)
1090
- app_config = AppConfig(config_dict)
1091
-
1092
- # Validate the configuration
1093
- app_config.validate()
1094
-
1095
- # Print the configuration
1096
- click.echo("Running App with configuration:")
1097
- click.echo(app_config.to_yaml())
1098
-
1099
- # TODO: Implement local run logic
1100
- # This would involve:
1101
- # 1. Setting up the environment
1102
- # 2. Running the app locally
1103
- # 3. Reporting status
1104
-
1105
- click.echo(f"App '{app_config.config['name']}' running locally!")
1106
-
1107
- except AppConfigError as e:
1108
- click.echo(f"Error in app configuration: {e}", err=True)
1109
- ctx.exit(1)
1110
- except Exception as e:
1111
- click.echo(f"Error running app: {e}", err=True)
1112
- ctx.exit(1)
1113
-
1114
-
1115
- @app.command(
1116
- help="Get detailed information about an app from the Outerbounds Platform."
1117
- )
1118
- @click.option("--name", type=str, help="Get info for app by name")
1119
- @click.option("--id", "cap_id", type=str, help="Get info for app by id")
1120
- @click.option(
1121
- "--format",
1122
- type=click.Choice(["json", "text"]),
1123
- help="Format the output",
1124
- default="text",
1125
- )
1126
- @click.pass_context
1127
- def info(ctx, name, cap_id, format):
1128
- """Get detailed information about an app from the Outerbounds Platform."""
1129
- # Require either name or id
1130
- if not any([name is not None, cap_id is not None]):
1131
- raise AppConfigError(
1132
- "Either --name or --id must be provided to get app information."
1133
- )
1134
-
1135
- # Ensure only one is provided
1136
- if name is not None and cap_id is not None:
1137
- raise AppConfigError("Please provide either --name or --id, not both.")
1138
-
1139
- capsule_api = CapsuleApi(
1140
- ctx.obj.api_url,
1141
- ctx.obj.perimeter,
1142
- )
1143
-
1144
- # First, find the capsule using list_and_filter_capsules
1145
- filtered_capsules = list_and_filter_capsules(
1146
- capsule_api, None, None, name, None, None, cap_id
1147
- )
1148
-
1149
- if len(filtered_capsules) == 0:
1150
- identifier = name if name else cap_id
1151
- identifier_type = "name" if name else "id"
1152
- raise AppConfigError(f"No app found with {identifier_type}: {identifier}")
1153
-
1154
- if len(filtered_capsules) > 1:
1155
- raise AppConfigError(
1156
- f"Multiple apps found with name: {name}. Please use --id to specify exactly which app you want info for."
1157
- )
1158
-
1159
- # Get the capsule info
1160
- capsule = filtered_capsules[0]
1161
- capsule_id = capsule.get("id")
1162
-
1163
- # Get detailed capsule info and workers
1164
- try:
1165
- detailed_capsule_info = capsule_api.get(capsule_id)
1166
- workers_info = capsule_api.get_workers(capsule_id)
1167
-
1168
- if format == "json":
1169
- # Output in JSON format for piping to jq
1170
- info_data = {"capsule": detailed_capsule_info, "workers": workers_info}
1171
- click.echo(json.dumps(info_data, indent=4))
1172
- else:
1173
- # Output in text format
1174
- _display_capsule_info_text(detailed_capsule_info, workers_info)
1175
-
1176
- except Exception as e:
1177
- raise AppConfigError(f"Error retrieving information for app {capsule_id}: {e}")
1178
-
1179
-
1180
- def _display_capsule_info_text(capsule_info, workers_info):
1181
- """Display capsule information in a human-readable text format."""
1182
- spec = capsule_info.get("spec", {})
1183
- status = capsule_info.get("status", {}) or {}
1184
- metadata = capsule_info.get("metadata", {}) or {}
1185
-
1186
- info_color = ColorTheme.INFO_COLOR
1187
- tl_color = ColorTheme.TL_HEADER_COLOR
1188
-
1189
- def _key_style(key: str, value: str):
1190
- return "%s: %s" % (
1191
- click.style(
1192
- key,
1193
- fg=ColorTheme.INFO_KEY_COLOR,
1194
- ),
1195
- click.style(str(value), fg=ColorTheme.INFO_VALUE_COLOR, bold=True),
1196
- )
1197
-
1198
- # Basic Info
1199
- click.secho("=== App Information ===", fg=tl_color, bold=True)
1200
- click.secho(_key_style("Name", spec.get("displayName", "N/A")), fg=info_color)
1201
- click.secho(_key_style("ID", capsule_info.get("id", "N/A")), fg=info_color)
1202
- click.secho(
1203
- _key_style("Version", capsule_info.get("version", "N/A")), fg=info_color
1204
- )
1205
- click.secho(
1206
- _key_style(
1207
- "Ready to Serve Traffic", str(status.get("readyToServeTraffic", False))
1208
- ),
1209
- fg=info_color,
1210
- )
1211
- click.secho(
1212
- _key_style("Update In Progress", str(status.get("updateInProgress", False))),
1213
- fg=info_color,
1214
- )
1215
- click.secho(
1216
- _key_style(
1217
- "Currently Served Version", str(status.get("currentlyServedVersion", "N/A"))
1218
- ),
1219
- fg=info_color,
1220
- )
1221
-
1222
- # URLs
1223
- access_info = status.get("accessInfo", {}) or {}
1224
- out_cluster_url = access_info.get("outOfClusterURL")
1225
- in_cluster_url = access_info.get("inClusterURL")
1226
-
1227
- if out_cluster_url:
1228
- click.secho(
1229
- _key_style("External URL", f"https://{out_cluster_url}"), fg=info_color
1230
- )
1231
- if in_cluster_url:
1232
- click.secho(
1233
- _key_style("Internal URL", f"https://{in_cluster_url}"), fg=info_color
1234
- )
1235
-
1236
- # Resource Configuration
1237
- click.secho("\n=== Resource Configuration ===", fg=tl_color, bold=True)
1238
- resource_config = spec.get("resourceConfig", {})
1239
- click.secho(_key_style("CPU", resource_config.get("cpu", "N/A")), fg=info_color)
1240
- click.secho(
1241
- _key_style("Memory", resource_config.get("memory", "N/A")), fg=info_color
1242
- )
1243
- click.secho(
1244
- _key_style("Ephemeral Storage", resource_config.get("ephemeralStorage", "N/A")),
1245
- fg=info_color,
1246
- )
1247
- if resource_config.get("gpu"):
1248
- click.secho(_key_style("GPU", resource_config.get("gpu")), fg=info_color)
1249
-
1250
- # Autoscaling
1251
- click.secho("\n=== Autoscaling Configuration ===", fg=tl_color, bold=True)
1252
- autoscaling_config = spec.get("autoscalingConfig", {})
1253
- click.secho(
1254
- _key_style("Min Replicas", str(autoscaling_config.get("minReplicas", "N/A"))),
1255
- fg=info_color,
1256
- )
1257
- click.secho(
1258
- _key_style("Max Replicas", str(autoscaling_config.get("maxReplicas", "N/A"))),
1259
- fg=info_color,
1260
- )
1261
- click.secho(
1262
- _key_style("Available Replicas", str(status.get("availableReplicas", "N/A"))),
1263
- fg=info_color,
1264
- )
1265
-
1266
- # Auth Configuration
1267
- click.secho("\n=== Authentication Configuration ===", fg=tl_color, bold=True)
1268
- auth_config = spec.get("authConfig", {})
1269
- click.secho(
1270
- _key_style("Auth Type", auth_config.get("authType", "N/A")), fg=info_color
1271
- )
1272
- click.secho(
1273
- _key_style("Public Access", str(auth_config.get("publicToDeployment", "N/A"))),
1274
- fg=info_color,
1275
- )
1276
-
1277
- # Tags
1278
- tags = spec.get("tags", [])
1279
- if tags:
1280
- click.secho("\n=== Tags ===", fg=tl_color, bold=True)
1281
- for tag in tags:
1282
- click.secho(
1283
- _key_style(str(tag.get("key", "N/A")), str(tag.get("value", "N/A"))),
1284
- fg=info_color,
1285
- )
1286
-
1287
- # Metadata
1288
- click.secho("\n=== Metadata ===", fg=tl_color, bold=True)
1289
- click.secho(
1290
- _key_style("Created At", metadata.get("createdAt", "N/A")), fg=info_color
1291
- )
1292
- click.secho(
1293
- _key_style("Last Modified At", metadata.get("lastModifiedAt", "N/A")),
1294
- fg=info_color,
1295
- )
1296
- click.secho(
1297
- _key_style("Last Modified By", metadata.get("lastModifiedBy", "N/A")),
1298
- fg=info_color,
1299
- )
1300
-
1301
- # Workers Information
1302
- click.secho("\n=== Workers Information ===", fg=tl_color, bold=True)
1303
- if not workers_info:
1304
- click.secho("No workers found", fg=info_color)
1305
- else:
1306
- click.secho(_key_style("Total Workers", str(len(workers_info))), fg=tl_color)
1307
-
1308
- # Create a table for workers
1309
- workers_headers = [
1310
- "Worker ID",
1311
- "Phase",
1312
- "Version",
1313
- "Activity",
1314
- "Activity Data Available",
1315
- ]
1316
- workers_table_data = []
1317
-
1318
- for worker in workers_info:
1319
- worker_id = worker.get("workerId", "N/A")
1320
- phase = worker.get("phase", "N/A")
1321
- version = worker.get("version", "N/A")
1322
- activity = str(worker.get("activity", "N/A"))
1323
- activity_data_available = str(worker.get("activityDataAvailable", False))
1324
-
1325
- workers_table_data.append(
1326
- [
1327
- worker_id[:20] + "..." if len(worker_id) > 23 else worker_id,
1328
- phase,
1329
- version[:10] + "..." if len(version) > 13 else version,
1330
- activity,
1331
- activity_data_available,
1332
- ]
1333
- )
1334
-
1335
- print_table(workers_table_data, workers_headers)
1336
-
1337
-
1338
- @app.command(help="Get logs for an app worker from the Outerbounds Platform.")
1339
- @click.option("--name", type=str, help="Get logs for app by name")
1340
- @click.option("--id", "cap_id", type=str, help="Get logs for app by id")
1341
- @click.option("--worker-id", type=str, help="Get logs for specific worker")
1342
- @click.option("--file", type=str, help="Save logs to file")
1343
- @click.option(
1344
- "--previous",
1345
- is_flag=True,
1346
- help="Get logs from previous container instance",
1347
- default=False,
1348
- )
1349
- @click.pass_context
1350
- def logs(ctx, name, cap_id, worker_id, file, previous):
1351
- """Get logs for an app worker from the Outerbounds Platform."""
1352
- # Require either name or id
1353
- if not any([name is not None, cap_id is not None]):
1354
- raise AppConfigError("Either --name or --id must be provided to get app logs.")
1355
-
1356
- # Ensure only one is provided
1357
- if name is not None and cap_id is not None:
1358
- raise AppConfigError("Please provide either --name or --id, not both.")
1359
-
1360
- capsule_api = CapsuleApi(
1361
- ctx.obj.api_url,
1362
- ctx.obj.perimeter,
1363
- )
1364
-
1365
- # First, find the capsule using list_and_filter_capsules
1366
- filtered_capsules = list_and_filter_capsules(
1367
- capsule_api, None, None, name, None, None, cap_id
1368
- )
1369
-
1370
- if len(filtered_capsules) == 0:
1371
- identifier = name if name else cap_id
1372
- identifier_type = "name" if name else "id"
1373
- raise AppConfigError(f"No app found with {identifier_type}: {identifier}")
1374
-
1375
- if len(filtered_capsules) > 1:
1376
- raise AppConfigError(
1377
- f"Multiple apps found with name: {name}. Please use --id to specify exactly which app you want logs for."
1378
- )
1379
-
1380
- capsule = filtered_capsules[0]
1381
- capsule_id = capsule.get("id")
1382
-
1383
- # Get workers
1384
- try:
1385
- workers_info = capsule_api.get_workers(capsule_id)
1386
- except Exception as e:
1387
- raise AppConfigError(f"Error retrieving workers for app {capsule_id}: {e}")
1388
-
1389
- if not workers_info:
1390
- raise AppConfigError(f"No workers found for app {capsule_id}")
1391
-
1392
- # If worker_id not provided, show interactive selection
1393
- if not worker_id:
1394
- if len(workers_info) == 1:
1395
- # Only one worker, use it automatically
1396
- selected_worker = workers_info[0]
1397
- worker_id = selected_worker.get("workerId")
1398
- worker_phase = selected_worker.get("phase", "N/A")
1399
- worker_version = selected_worker.get("version", "N/A")[:10]
1400
- click.echo(
1401
- f"📋 Using the only available worker: {worker_id[:20]}... (phase: {worker_phase}, version: {worker_version}...)"
1402
- )
1403
- else:
1404
- # Multiple workers, show selection
1405
- click.secho(
1406
- "📋 Multiple workers found. Please select one:",
1407
- fg=ColorTheme.INFO_COLOR,
1408
- bold=True,
1409
- )
1410
-
1411
- # Display workers in a table format for better readability
1412
- headers = ["#", "Worker ID", "Phase", "Version", "Activity"]
1413
- table_data = []
1414
-
1415
- for i, worker in enumerate(workers_info, 1):
1416
- w_id = worker.get("workerId", "N/A")
1417
- phase = worker.get("phase", "N/A")
1418
- version = worker.get("version", "N/A")
1419
- activity = str(worker.get("activity", "N/A"))
1420
-
1421
- table_data.append(
1422
- [
1423
- str(i),
1424
- w_id[:30] + "..." if len(w_id) > 33 else w_id,
1425
- phase,
1426
- version[:15] + "..." if len(version) > 18 else version,
1427
- activity,
1428
- ]
1429
- )
1430
-
1431
- print_table(table_data, headers)
1432
-
1433
- # Create choices for the prompt
1434
- worker_choices = []
1435
- for i, worker in enumerate(workers_info, 1):
1436
- worker_choices.append(str(i))
1437
-
1438
- selected_index = click.prompt(
1439
- click.style(
1440
- "Select worker number", fg=ColorTheme.INFO_COLOR, bold=True
1441
- ),
1442
- type=click.Choice(worker_choices),
1443
- )
1444
-
1445
- # Get the selected worker
1446
- selected_worker = workers_info[int(selected_index) - 1]
1447
- worker_id = selected_worker.get("workerId")
1448
-
1449
- # Get logs for the selected worker
1450
- try:
1451
- logs_response = capsule_api.logs(capsule_id, worker_id, previous=previous)
1452
- except Exception as e:
1453
- raise AppConfigError(f"Error retrieving logs for worker {worker_id}: {e}")
1454
-
1455
- # Format logs content
1456
- logs_content = "\n".join([log.get("message", "") for log in logs_response])
1457
-
1458
- # Display or save logs
1459
- if file:
1460
- try:
1461
- with open(file, "w") as f:
1462
- f.write(logs_content)
1463
- click.echo(f"📁 Logs saved to {file}")
1464
- except Exception as e:
1465
- raise AppConfigError(f"Error saving logs to file {file}: {e}")
1466
- else:
1467
- if logs_content.strip():
1468
- click.echo(logs_content)
1469
- else:
1470
- click.echo("📝 No logs available for this worker.")
1471
-
1472
-
1473
- # if __name__ == "__main__":
1474
- # cli()