# pylint: disable=W0613
"""
Smarter API command-line interface 'apply' view.
/api/v1/cli/apply/
"""
from http import HTTPStatus
import yaml
from django.core.handlers.asgi import ASGIRequest
from smarter.lib import logging
from smarter.lib.django.waffle import SmarterWaffleSwitches
from .base import APIV1CLIViewBadRequestError, APIV1CLIViewError, CliBaseApiView
logger = logging.getSmarterLogger(
__name__, any_switches=[SmarterWaffleSwitches.API_LOGGING, SmarterWaffleSwitches.MANIFEST_LOGGING]
)
[docs]
class APIV1CLIViewManifestNotFoundError(APIV1CLIViewBadRequestError):
"""Custom error for when a manifest is not found."""
[docs]
class ApiV1CliApplyApiView(CliBaseApiView):
"""
This is the API endpoint for the 'apply' command in the Smarter command-line interface (CLI).
The 'apply' command is a Smarter Brokered and Journaled operation that is used with all Smarter resources. It expects a YAML manifest in smarter.sh/v1 format.
The client making the HTTP request to this endpoint is expected to be the Smarter CLI, which is written in Golang and available on Windows, macOS, and Linux.
The response from this endpoint is a JSON object.
This class is a child of the Django Rest Framework View.
"""
@property
def formatted_class_name(self) -> str:
"""Returns the class name in a formatted string along with the name of this mixin."""
inherited_class = super().formatted_class_name
this_class = f".{ApiV1CliApplyApiView.__name__}[{id(self)}]"
return f"{inherited_class}{self.formatted_text(this_class)}"
[docs]
def raise_for_unparseable_manifest(self, request: ASGIRequest) -> None:
"""Raise a malformed manifest error if the request body is text that is not a YAML or JSON object."""
try:
body = request.body.decode("utf-8")
# pylint: disable=broad-except
except Exception:
return
if not body.strip():
return
try:
parsed = yaml.safe_load(body)
except yaml.YAMLError as e:
raise APIV1CLIViewManifestMalFormedError(f"The manifest is not valid YAML: {e}") from e
if not isinstance(parsed, dict):
raise APIV1CLIViewManifestMalFormedError(
f"The manifest must be a YAML object with apiVersion, kind, metadata and spec, not a {type(parsed).__name__}."
)
[docs]
def post(self, request: ASGIRequest, *args, **kwargs):
"""Handles POST requests to apply a Smarter manifest."""
logger.debug(
"called with request=%s, args=%s, kwargs=%s",
request,
args,
kwargs,
)
if not self.manifest_data:
self.raise_for_unparseable_manifest(request)
raise APIV1CLIViewManifestNotFoundError("No YAML manifest provided.")
user = kwargs.pop("user", None)
account = kwargs.pop("account", None)
user_profile = kwargs.pop("user_profile", None)
if self.broker is None:
# an invalid manifest is not why: the broker raises a client error, a 400, for one.
raise APIV1CLIViewError(f"No broker found for manifest kind '{self.manifest_kind}'.")
response = self.broker.apply(
request, user=user, account=account, user_profile=user_profile, args=args, kwargs=kwargs
)
if response and response.status_code == HTTPStatus.OK:
logger.debug(
"Applied %s manifest for %s",
self.manifest_kind,
self.manifest_name,
)
return response