def get_gke_resources()

in opentelemetry-resourcedetector-gcp/src/opentelemetry/resourcedetector/gcp_resource_detector/__init__.py [0:0]


def get_gke_resources():
    """Resource finder for GKE attributes"""

    if os.getenv("KUBERNETES_SERVICE_HOST") is None:
        return {}

    (
        common_attributes,
        all_metadata,
    ) = _get_google_metadata_and_common_attributes()

    container_name = os.getenv("CONTAINER_NAME")
    if container_name is not None:
        common_attributes["container.name"] = container_name

    # Fallback to reading namespace from a file is the env var is not set
    pod_namespace = os.getenv("NAMESPACE")
    if pod_namespace is None:
        try:
            with open(
                "/var/run/secrets/kubernetes.io/serviceaccount/namespace", "r"
            ) as namespace_file:
                pod_namespace = namespace_file.read().strip()
        except FileNotFoundError:
            pod_namespace = ""

    common_attributes.update(
        {
            "k8s.cluster.name": all_metadata["instance"]["attributes"][
                "cluster-name"
            ],
            "k8s.namespace.name": pod_namespace,
            "k8s.pod.name": os.getenv("POD_NAME", os.getenv("HOSTNAME", "")),
            "host.id": all_metadata["instance"]["id"],
            "gcp.resource_type": "gke_container",
        }
    )
    return common_attributes