Source code for smarter.apps.provider.utils

# pylint: disable=W0613
"""Utility functions for Provider app."""

import google.auth.transport.requests
import requests
from google.auth.exceptions import GoogleAuthError
from google.oauth2 import service_account

from smarter.apps.account.utils import smarter_cached_objects
from smarter.apps.secret.models import Secret
from smarter.common.conf.env import is_missing_value
from smarter.lib import json, logging
from smarter.lib.django import waffle
from smarter.lib.django.waffle import SmarterWaffleSwitches

from .const import GOOGLE_MAPS_API_KEY_SECRET_NAME, GOOGLE_SERVICE_ACCOUNT_SECRET_NAME
from .models import (
    Provider,
    ProviderModel,
    ProviderModelVerification,
    ProviderModelVerificationTypes,
    ProviderVerification,
    ProviderVerificationTypes,
)
from .signals import (
    model_verification_failure,
    model_verification_success,
    provider_verification_failure,
    provider_verification_success,
)


[docs] def should_log(level): """Check if logging should be done based on the waffle switch.""" return waffle.switch_is_active(SmarterWaffleSwitches.PROVIDER_LOGGING) or waffle.switch_is_active( SmarterWaffleSwitches.PLUGIN_LOGGING )
logger = logging.getSmarterLogger(__name__, condition_func=should_log)
[docs] def get_provider_verification_for_type( provider: Provider, verification_type: ProviderVerificationTypes ) -> ProviderVerification: """ Get the provider verification for a specific type, creating it if it does not exist. :param provider: The provider. :param verification_type: The kind of verification. :returns: The existing or new ProviderVerification. """ logger.debug("Getting provider verification for %s of type %s", provider.name, verification_type) instance, _ = ProviderVerification.objects.get_or_create(provider=provider, verification_type=verification_type) if instance.is_valid: logger.debug("Provider verification for %s is still valid %s", provider, instance.updated_at) return instance
[docs] def get_model_verification_for_type( provider_model: ProviderModel, verification_type: ProviderModelVerificationTypes ) -> ProviderModelVerification: """ Get the model verification for a specific type, creating it if it does not exist. :param provider_model: The provider model. :param verification_type: The kind of verification. :returns: The existing or new ProviderModelVerification. """ logger.debug("Getting model verification for %s of type %s", provider_model.name, verification_type) instance, _ = ProviderModelVerification.objects.get_or_create( provider_model=provider_model, verification_type=verification_type ) if instance.is_valid: logger.debug("Streaming verification for %s is still valid %s", provider_model, instance.updated_at) return instance
[docs] def set_model_verification( provider_model_verification: ProviderModelVerification, is_successful: bool, **kwargs ) -> None: """ Save the model verification's outcome, and send the matching signal. Sends ``model_verification_success`` or ``model_verification_failure``. :param provider_model_verification: The verification to update. :param is_successful: Whether the verification passed. :param kwargs: Not used. """ logger.debug( "Setting model verification for %s to %s", provider_model_verification.provider_model.name, is_successful, ) provider_model_verification.is_successful = is_successful provider_model_verification.save() if is_successful: model_verification_success.send( sender=ProviderModelVerification, provider_model_verification=provider_model_verification ) else: model_verification_failure.send( sender=ProviderModelVerification, provider_model_verification=provider_model_verification )
[docs] def set_provider_verification(provider_verification: ProviderVerification, is_successful: bool, **kwargs) -> None: """ Save the provider verification's outcome, and send the matching signal. Sends ``provider_verification_success`` or ``provider_verification_failure``. :param provider_verification: The verification to update. :param is_successful: Whether the verification passed. :param kwargs: Not used. """ logger.debug( "Setting provider verification for %s to %s", provider_verification.provider.name, is_successful, ) provider_verification.is_successful = is_successful provider_verification.save() if is_successful: provider_verification_success.send(sender=ProviderVerification, provider_verification=provider_verification) else: provider_verification_failure.send(sender=ProviderVerification, provider_verification=provider_verification)
[docs] def test_web_page(url: str, test_str: str) -> bool: """ Fetch a web page, and check that it is an HTML page that contains a string. :param url: The page's URL, fetched with a 10 second timeout. :param test_str: The text that the page must contain, case-insensitively. :returns: True if the page returns 200, is HTML and contains ``test_str``; False otherwise, including on a network error. """ logger.debug("Testing web page %s", url) try: response = requests.get(url, timeout=10) page_text = response.text.lower() is_ok = response.status_code == 200 is_html = "<html" in page_text or "<!doctype html" in page_text has_test_str = test_str.lower() in page_text if is_ok and is_html and has_test_str: logger.debug("Web page test succeeded.") return True else: logger.error("Web page test failed: Non-200 status or missing documentation HTML.") return False except requests.RequestException as exc: logger.error("Web page test failed: %s", exc) return False
[docs] def get_google_service_account_bearer_token() -> str | None: """Get a Google service account bearer token.""" SCOPES = [ "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/generative-language.retriever", "https://www.googleapis.com/auth/generative-language", ] try: # the platform's Secret, which initialize_providers stores for the smarter admin. A Secret of # the same name in another account must not be found, nor make the name ambiguous. secret = Secret.get_cached_object( name=GOOGLE_SERVICE_ACCOUNT_SECRET_NAME, user_profile=smarter_cached_objects.smarter_admin_user_profile ) except Secret.DoesNotExist: logger.error( "google service account secret not found.", ) return None try: svc_account = secret.get_secret() if not svc_account: logger.error( "google service account secret is empty.", ) return None svc_account_dict = json.loads(svc_account) credentials = service_account.Credentials.from_service_account_info(svc_account_dict, scopes=SCOPES) auth_req = google.auth.transport.requests.Request() except json.JSONDecodeError as e: logger.error( "error decoding Google service account JSON: %s", e, ) return None except GoogleAuthError as e: logger.error( "error loading Google credentials: %s", e, ) return None # pylint: disable=broad-except except Exception as e: logger.error("unexpected error: %s", e) return None credentials.refresh(auth_req) bearer_token = credentials.token return bearer_token
[docs] def get_google_maps_api_key() -> str | None: """ Get the Google Maps API key from its Smarter Secret, ``google_maps_api_key``, the Smarter admin's. The Secret is the key's only source: the init Job creates it from the platform's bootstrap secrets (``initialize_bootstrap_secrets``, issue #1099), and no service reads an environment variable for it. :returns: The key, or None, logged with how to create it, if the Secret is missing or empty. """ user_profile = smarter_cached_objects.smarter_admin_user_profile try: secret = Secret.get_cached_object(name=GOOGLE_MAPS_API_KEY_SECRET_NAME, user_profile=user_profile) api_key = secret.get_secret() if is_missing_value(api_key): logger.error("Google Maps API key secret is empty.") return None return api_key except Secret.DoesNotExist: logger.error( "Google Maps API key secret %s not found. Create it with smarter apply, or in the web console, or set " "it in the Helm chart's bootstrapSecrets, or, locally, in bootstrap-secrets/, for the init Job. " "See https://developers.google.com/maps/documentation/geolocation/overview.", GOOGLE_MAPS_API_KEY_SECRET_NAME, ) return None # pylint: disable=broad-except except Exception as e: logger.error("Unexpected error retrieving Google Maps API key: %s", e) return None