def k8s_cluster_domain()

in mysqloperator/controller/kubeutils.py [0:0]


def k8s_cluster_domain(logger: Optional[Logger], ns="kube-system") -> str:
    """Get the Kubernetes Cluster's Domain. Can
    be overwritten using environment MYSQL_OPERATOR_K8S_CLUSTER_DOMAIN.

    If this fails to detect it will retry in a blocking loop. This should only
    happen in operator_main before startup. If it constantly fails the process
    will be terminated.
    """

    global _k8s_cluster_domain

    # We use the cached value instead of querying multiple times
    if _k8s_cluster_domain:
        return _k8s_cluster_domain

    # The user could override the lookup using env
    _k8s_cluster_domain = os.getenv("MYSQL_OPERATOR_K8S_CLUSTER_DOMAIN")
    if _k8s_cluster_domain:
        if logger:
            logger.info(f"Environment provided cluster domain: {_k8s_cluster_domain}")
        return _k8s_cluster_domain

    for _ in range(15):
        try:
            # Try reverse lookup via some service having a cluster_ip set. Operator
            # is allowed to list all services and we assume some service is in
            # kube-system namespace.
            ip = next(
                filter(
                    lambda ip: ip,
                    map(
                        lambda service: service.spec.cluster_ip,
                        api_core.list_namespaced_service(ns).items
                    )
                )
            )

            if ip:
                fqdn = socket.gethostbyaddr(ip)[0]
                [_, _, _, _k8s_cluster_domain] = fqdn.split('.', maxsplit=3)
                if logger:
                    logger.info(f"Auto-detected cluster domain: {_k8s_cluster_domain}")

                return _k8s_cluster_domain
        except Exception as e:
            if logger:
                logger.warning("Failed to detect cluster domain. "
                                f"Reason: {e}")
            time.sleep(2)

    logger.error(
        """Failed to automatically identify the cluster domain. If this
        persists try setting MYSQL_OPERATOR_K8S_CLUSTER_DOMAIN via environment."""
    )

    sys.exit(1)