Source code for smarter.apps.infrastructure.providers.base

"""
The base class of the cloud providers.

A cloud provider implements the services that depend on a cloud, :class:`CloudProvider.dns`,
:class:`CloudProvider.certificates` and :class:`CloudProvider.storage`, and contributes what the cloud-independent services need
from it: the Kubernetes cluster's kubeconfig, the cluster's description, and the cloud resources
of the cluster, for the inventory.

To add a cloud, e.g. Azure:

1. Add a package, ``smarter.apps.infrastructure.providers.azure``, with a :class:`CloudProvider`
   whose DNS, certificate and storage services implement the primitives of
   :class:`~smarter.apps.infrastructure.services.dns.DNSService`,
   :class:`~smarter.apps.infrastructure.services.certificates.CertificateService` and
   :class:`~smarter.apps.infrastructure.services.storage.StorageService`.
2. Register it, in :mod:`smarter.apps.infrastructure.providers`, under its
   :class:`~smarter.apps.infrastructure.const.CloudProviders` name.
3. Set ``SMARTER_CLOUD_PROVIDER=azure``.

The platform does not change.
"""

from abc import abstractmethod
from typing import Optional

from smarter.apps.infrastructure.cluster_health import ClusterHealth, HealthIssue
from smarter.apps.infrastructure.const import InfrastructureServiceNames
from smarter.apps.infrastructure.services.base import (
    DiscoveredResource,
    InfrastructureService,
)
from smarter.apps.infrastructure.services.certificates import CertificateService
from smarter.apps.infrastructure.services.dns import DNSService
from smarter.apps.infrastructure.services.storage import StorageService
from smarter.apps.infrastructure.signals import (
    infrastructure_authenticated,
    infrastructure_authentication_failed,
)
from smarter.lib.typing import SmarterDictType


[docs] class CloudProvider(InfrastructureService): """ A cloud provider: the cloud-specific half of the infrastructure services. :param allow_in_tests: Allow the provider to reach its cloud in the unit tests, e.g. in a test tagged :data:`~smarter.lib.unittest.runner.INFRASTRUCTURE`. """ name: str = "cloud" """The provider's name, see :class:`~smarter.apps.infrastructure.const.CloudProviders`.""" service_name = InfrastructureServiceNames.PROVIDER
[docs] def __init__(self, allow_in_tests: bool = False, **kwargs): super().__init__(provider_name=self.name, **kwargs) self.allow_in_tests = allow_in_tests self._authenticated: Optional[bool] = None
[docs] def authentication_state(self, identity: Optional[SmarterDictType], error: Optional[str] = None) -> bool: """ Record whether the provider is authenticated with its cloud. Sends :data:`~smarter.apps.infrastructure.signals.infrastructure_authenticated` or :data:`~smarter.apps.infrastructure.signals.infrastructure_authentication_failed` when the state changes, rather than on every check. :param identity: The provider's identity, or None if it is not authenticated. :param error: Why it is not authenticated. :returns: Whether it is authenticated. """ authenticated = isinstance(identity, dict) if authenticated != self._authenticated: if authenticated: self.send(infrastructure_authenticated, identity=identity) else: self.send(infrastructure_authentication_failed, error=error or "not authenticated") self._authenticated = authenticated return authenticated
@property @abstractmethod def identity(self) -> Optional[SmarterDictType]: """The identity that the provider authenticates as, e.g. its account, or None.""" @property def account_id(self) -> Optional[str]: """The cloud account's id, or None if the provider is not authenticated.""" return None @property @abstractmethod def sdk_version(self) -> str: """The version of the provider's SDK.""" @property @abstractmethod def dns(self) -> DNSService: """The provider's DNS service.""" @property @abstractmethod def certificates(self) -> CertificateService: """The provider's TLS certificate service.""" @property @abstractmethod def storage(self) -> StorageService: """The provider's private object storage."""
[docs] @abstractmethod def update_kubeconfig(self) -> bool: """ Write the kubeconfig of the platform's Kubernetes cluster, for kubectl. :returns: True if it was written. """
[docs] def get_kubernetes_token(self) -> Optional[tuple[str, float]]: """ Return a bearer token for the platform's Kubernetes cluster, which kubectl uses instead of its kubeconfig's. The kubeconfig of a managed cluster usually runs a command to fetch a token, e.g. ``aws eks get-token``, on every kubectl call, which takes seconds. A provider that can create a token itself returns one, which is used until it expires. :returns: The token and when it expires, as a :func:`time.time`, or None for kubectl to use its kubeconfig's credentials. """ return None
[docs] @abstractmethod def get_kubernetes_cluster_info(self) -> SmarterDictType: """ Describe the platform's Kubernetes cluster, e.g. for the status API. :raises InfrastructureNotReadyError: If the provider is not ready. """
[docs] def get_kubernetes_cluster_health(self) -> ClusterHealth: """ Describe the health of the platform's Kubernetes cluster, as the cloud provider sees it. The MCPServer's staff-only ``eks_status`` tool reports it. This implementation knows only what :meth:`get_kubernetes_cluster_info` returns: the control plane's status, versions and health issues. A provider overrides it to add its node groups, add-ons and recommendations, as :class:`~smarter.apps.infrastructure.providers.aws.AWSProvider` does with EKS. :returns: The cluster's health, with no node groups, add-ons or insights. :raises InfrastructureNotReadyError: If the provider is not ready. """ info = self.get_kubernetes_cluster_info() health = info.get("health") or {} issues = [] for issue in health.get("issues") or []: if not isinstance(issue, dict): continue code = str(issue.get("code", "")) message = str(issue.get("message", "")) issues.append(HealthIssue(code=code, message=message)) return ClusterHealth( status=str(info.get("status") or ""), version=str(info.get("version") or ""), platform_version=str(info.get("platformVersion") or ""), issues=tuple(issues), )
[docs] def get_kubernetes_cluster_resources(self) -> dict[str, list[DiscoveredResource]]: """ Return the cloud resources of the platform's Kubernetes cluster, for the inventory. e.g. the cluster itself, its add-ons, and its node groups, which are provisioned outside the platform, e.g. with Terraform, so that no signal records them. :returns: The resources, by resource type, e.g. ``kubernetes.cluster``. A type that could not be listed is left out, so that the inventory does not record its resources as destroyed. This implementation lists none. """ return {}
__all__ = ["CloudProvider"]