示例#1
0
 def get_agent_pod_host(self, return_host_name=False):
     """Obtain host the agent is running on in Kubernetes.
     Used when trying to connect to services running on the node (Kubelet, cAdvisor)
     """
     # Get pod name and namespace from environment variables
     pod_name = os.environ.get("AGENT_POD_NAME")
     pod_namespace = os.environ.get("AGENT_POD_NAMESPACE")
     if not pod_name:
         raise exceptions.MissingEnvironmentVariables(
             "pod_name is not set as environment variables cannot derive"
             " host from Kubernetes API")
     if not pod_namespace:
         raise exceptions.MissingEnvironmentVariables(
             "pod_namespace is not set as environment variables cannot "
             "derive host from Kubernetes API")
     pod_url = "/api/v1/namespaces/{}/pods/{}".format(pod_namespace, pod_name)
     try:
         agent_pod = self.get_request(pod_url)
     except Exception as e:
         exception_message = "Could not get agent pod from Kubernetes API" \
                             " to get host IP with error - {}".format(e)
         log.exception(exception_message)
         raise exceptions.KubernetesAPIConnectionError(exception_message)
     if not return_host_name:
         return agent_pod['status']['hostIP']
     else:
         return agent_pod['spec']['nodeName']
示例#2
0
    def get_request(self, request_endpoint, as_json=True, retried=False):
        """Sends request to Kubernetes API with given endpoint.
        Will retry the request once, with updated token/cert, if unauthorized.
        """
        api_url = self.api_url
        if api_url[-1] == '/':
            api_url = api_url[:-1]

        if request_endpoint[0] == '/':
            request_endpoint = request_endpoint[1:]

        request_url = "{}/{}".format(api_url, request_endpoint)
        result = requests.get(request_url,
                              timeout=self.connection_timeout,
                              headers=self.api_request_header,
                              verify=self.api_verify)
        if result.status_code >= 300:
            if result.status_code == 401 and not retried:
                log.info("Could not authenticate with Kubernetes API at the"
                         " first time. Rereading in cert and token.")
                self._set_kubernetes_service_account_info()
                return self.get_request(request_endpoint, as_json=as_json,
                                        retried=True)
            exception_message = "Could not obtain data from {} with the " \
                                "given status code {} and return text {}".\
                format(request_url, result.status_code, result.text)
            raise exceptions.KubernetesAPIConnectionError(exception_message)
        return result.json() if as_json else result