diff --git a/py/README.md b/py/README.md index e87274450..46ef7660b 100644 --- a/py/README.md +++ b/py/README.md @@ -64,6 +64,10 @@ Available extras: - `temporal`: installs Temporal integration dependencies - `all`: installs all optional extras +The `braintrust install` commands for AWS CloudFormation are deprecated. Use the +[CloudFormation guide](https://docs.braintrust.dev/admin/self-hosting/aws-cloudformation) +to manage existing stacks. + ### Audio encoding `braintrust[audio]` requires Python 3.12+ and uses PyAV's bundled FFmpeg codecs. diff --git a/py/src/braintrust/cli/install/__init__.py b/py/src/braintrust/cli/install/__init__.py index 849eda602..cd1025e4c 100644 --- a/py/src/braintrust/cli/install/__init__.py +++ b/py/src/braintrust/cli/install/__init__.py @@ -1,39 +1,18 @@ -import argparse -import textwrap +from argparse import RawDescriptionHelpFormatter - -_module_not_found_error = None -try: - from . import api, bump_versions, logs, run_migrations -except ModuleNotFoundError as e: - _module_not_found_error = e - - -def fail_with_module_not_found_error(*args, **kwargs): - raise ModuleNotFoundError( - textwrap.dedent( - f"""\ - At least one dependency not found: {str(_module_not_found_error)!r} - It is possible that braintrust was installed without the CLI dependencies. Run: - - pip install 'braintrust[cli]' - - to install braintrust with the CLI dependencies (make sure to quote 'braintrust[cli]').""" - ) - ) +from . import api, bump_versions, logs, run_migrations +from ._deprecation import DEPRECATION def build_parser(subparsers, parent_parser): install_parser = subparsers.add_parser( "install", - help="Tools to setup and verify Braintrust's installation in your environment.", + help="Set up and verify a Braintrust CloudFormation stack (deprecated)", + description=DEPRECATION, + formatter_class=RawDescriptionHelpFormatter, parents=[parent_parser], ) - if _module_not_found_error: - install_parser.add_argument("args", nargs=argparse.REMAINDER) - install_parser.set_defaults(func=fail_with_module_not_found_error) - else: - install_subparsers = install_parser.add_subparsers(dest="install_subcommand", required=True) + install_subparsers = install_parser.add_subparsers(dest="install_subcommand", required=True) - for module in [api, logs, bump_versions, run_migrations]: - module.build_parser(install_subparsers, parents=[parent_parser]) + for module in [api, logs, bump_versions, run_migrations]: + module.build_parser(install_subparsers, parents=[parent_parser]) diff --git a/py/src/braintrust/cli/install/_deprecation.py b/py/src/braintrust/cli/install/_deprecation.py new file mode 100644 index 000000000..41929000a --- /dev/null +++ b/py/src/braintrust/cli/install/_deprecation.py @@ -0,0 +1,44 @@ +import sys +import textwrap +from argparse import RawDescriptionHelpFormatter +from functools import wraps + + +DEPRECATION = ( + "The braintrust install commands are deprecated.\n" + "Use the CloudFormation guide for existing stacks:\n" + "https://docs.braintrust.dev/admin/self-hosting/aws-cloudformation" +) + + +def add_deprecated_parser(subparsers, name, summary, parents, handler): + parser = subparsers.add_parser( + name, + help=f"{summary} (deprecated)", + description=f"{summary}.\n\n{DEPRECATION}", + formatter_class=RawDescriptionHelpFormatter, + parents=parents, + ) + + @wraps(handler) + def run(args): + print("Warning: " + DEPRECATION.replace("\n", " "), file=sys.stderr) + try: + return handler(args) + except ModuleNotFoundError as exc: + if exc.name not in {"boto3", "botocore"}: + raise + raise ModuleNotFoundError( + textwrap.dedent( + f"""\ + At least one dependency not found: {str(exc)!r} + It is possible that braintrust was installed without the CLI dependencies. Run: + + pip install 'braintrust[cli]' + + to install braintrust with the CLI dependencies (make sure to quote 'braintrust[cli]').""" + ) + ) from exc + + parser.set_defaults(func=run) + return parser diff --git a/py/src/braintrust/cli/install/api.py b/py/src/braintrust/cli/install/api.py index cb54523ef..e757c8943 100644 --- a/py/src/braintrust/cli/install/api.py +++ b/py/src/braintrust/cli/install/api.py @@ -3,12 +3,10 @@ import textwrap import time -from botocore.exceptions import ClientError from braintrust.logger import app_conn, login -# pylint: disable=no-name-in-module -from ...aws import cloudformation from ...util import response_raise_for_status +from ._deprecation import add_deprecated_parser _logger = logging.getLogger("braintrust.install.api") @@ -60,7 +58,7 @@ def build_parser(subparsers, parents): - parser = subparsers.add_parser("api", help="Install the Braintrust function API", parents=parents) + parser = add_deprecated_parser(subparsers, "api", "Install the Braintrust function API", parents, main) parser.add_argument("name", help="Name of the CloudFormation stack to create or update") parser.add_argument( @@ -275,10 +273,13 @@ def build_parser(subparsers, parents): default=None, ) - parser.set_defaults(func=main) - def main(args): + from botocore.exceptions import ClientError + + # pylint: disable-next=no-name-in-module + from ...aws import cloudformation + template = args.template or LATEST_TEMPLATE status = None diff --git a/py/src/braintrust/cli/install/bump_versions.py b/py/src/braintrust/cli/install/bump_versions.py index 04a2fc71c..9402b4345 100644 --- a/py/src/braintrust/cli/install/bump_versions.py +++ b/py/src/braintrust/cli/install/bump_versions.py @@ -1,21 +1,22 @@ import logging -# pylint: disable=no-name-in-module -from ...aws import LazyClient, cloudformation +from ._deprecation import add_deprecated_parser _logger = logging.getLogger("braintrust.install.logs") def build_parser(subparsers, parents): - parser = subparsers.add_parser( - "bump-versions", help="Bump the version of each serverless function", parents=parents + parser = add_deprecated_parser( + subparsers, "bump-versions", "Bump the version of each serverless function", parents, main ) parser.add_argument("name", help="Name of the CloudFormation stack") - parser.set_defaults(func=main) def main(args): + # pylint: disable-next=no-name-in-module + from ...aws import LazyClient, cloudformation + resources = cloudformation.describe_stack_resources(StackName=args.name) lambda_ = LazyClient("lambda") diff --git a/py/src/braintrust/cli/install/logs.py b/py/src/braintrust/cli/install/logs.py index 2b840aec9..2f2725521 100644 --- a/py/src/braintrust/cli/install/logs.py +++ b/py/src/braintrust/cli/install/logs.py @@ -2,22 +2,23 @@ import time from concurrent.futures import ThreadPoolExecutor -# pylint: disable=no-name-in-module -from ...aws import cloudformation, logs +from ._deprecation import add_deprecated_parser _logger = logging.getLogger("braintrust.install.logs") def build_parser(subparsers, parents): - parser = subparsers.add_parser("logs", help="Capture recent logs", parents=parents) + parser = add_deprecated_parser(subparsers, "logs", "Capture recent logs", parents, main) parser.add_argument("name", help="Name of the CloudFormation stack to collect logs from") parser.add_argument("--service", help="Name of the service", default="api", choices=["api", "brainstore", "all"]) parser.add_argument("--hours", help="Number of hours in the past to collect logs from", default=1, type=float) - parser.set_defaults(func=main) def main(args): + # pylint: disable-next=no-name-in-module + from ...aws import cloudformation, logs + stacks = cloudformation.describe_stacks(StackName=args.name)["Stacks"] if len(stacks) == 0: raise ValueError(f"Stack with name {args.name} does not exist") diff --git a/py/src/braintrust/cli/install/run_migrations.py b/py/src/braintrust/cli/install/run_migrations.py index 68fb29a7e..8017aa7c7 100644 --- a/py/src/braintrust/cli/install/run_migrations.py +++ b/py/src/braintrust/cli/install/run_migrations.py @@ -1,19 +1,20 @@ import logging -# pylint: disable=no-name-in-module -from ...aws import LazyClient, cloudformation +from ._deprecation import add_deprecated_parser _logger = logging.getLogger("braintrust.install.logs") def build_parser(subparsers, parents): - parser = subparsers.add_parser("run-migrations", help="Run schema migrations", parents=parents) + parser = add_deprecated_parser(subparsers, "run-migrations", "Run schema migrations", parents, main) parser.add_argument("name", help="Name of the CloudFormation stack") - parser.set_defaults(func=main) def main(args): + # pylint: disable-next=no-name-in-module + from ...aws import LazyClient, cloudformation + resources = cloudformation.describe_stack_resources(StackName=args.name) migration_lambda = [r for r in resources["StackResources"] if r["LogicalResourceId"] == "MigrateDatabaseFunction"] if not migration_lambda: diff --git a/py/src/braintrust/cli/test_install.py b/py/src/braintrust/cli/test_install.py new file mode 100644 index 000000000..a5846cb58 --- /dev/null +++ b/py/src/braintrust/cli/test_install.py @@ -0,0 +1,74 @@ +import os +import shutil +import subprocess +import sysconfig + +import pytest + + +COMMANDS = ("api", "logs", "bump-versions", "run-migrations") +GUIDE_URL = "https://docs.braintrust.dev/admin/self-hosting/aws-cloudformation" + + +@pytest.fixture +def cli(): + executable = shutil.which("braintrust", path=sysconfig.get_path("scripts")) + assert executable is not None + return executable + + +@pytest.mark.parametrize("command", [(), *((name,) for name in COMMANDS)]) +def test_install_help(cli, command): + result = subprocess.run( + [cli, "install", *command, "--help"], + capture_output=True, + text=True, + check=False, + ) + + assert result.returncode == 0, result.stderr + assert result.stderr == "" + assert "deprecated" in result.stdout + assert "Terraform" not in result.stdout + assert GUIDE_URL in result.stdout + if not command: + assert result.stdout.count("(deprecated)") == len(COMMANDS) + + +@pytest.mark.parametrize("command", COMMANDS) +def test_install_warns_on_stderr_before_aws_setup(cli, command, tmp_path): + result = subprocess.run( + [cli, "install", command, "test-stack"], + capture_output=True, + text=True, + check=False, + env={ + **os.environ, + "AWS_CONFIG_FILE": str(tmp_path / "config"), + "AWS_SHARED_CREDENTIALS_FILE": str(tmp_path / "credentials"), + "AWS_DEFAULT_PROFILE": "missing-test-profile", + "AWS_PROFILE": "missing-test-profile", + "AWS_EC2_METADATA_DISABLED": "true", + }, + ) + + assert result.returncode == 1 + warning = result.stderr.splitlines()[0] + assert warning.startswith("Warning:") + assert "deprecated" in warning + assert "Terraform" not in warning + assert GUIDE_URL in warning + assert GUIDE_URL not in result.stdout + + +def test_install_requires_subcommand(cli): + result = subprocess.run( + [cli, "install"], + capture_output=True, + text=True, + check=False, + ) + + assert result.returncode == 2 + assert "usage:" in result.stderr + assert "Warning:" not in result.stderr