From 068e6599b5ad02fa2dc7f6266613026c5a4f26c6 Mon Sep 17 00:00:00 2001 From: aqan213 <55431633+aqan213@users.noreply.github.com> Date: Wed, 27 Nov 2019 05:41:58 +0800 Subject: [PATCH] fix kubernetes api connect issue (#10) --- kube_obj_parser.py | 29 ++++++++++++++++++++--------- kubewatcher.py | 3 +++ 2 files changed, 23 insertions(+), 9 deletions(-) diff --git a/kube_obj_parser.py b/kube_obj_parser.py index 8a83052..5284924 100755 --- a/kube_obj_parser.py +++ b/kube_obj_parser.py @@ -404,22 +404,33 @@ def parse(self, url, endpoint): continue def _kube_get(self, url, endpoint): + headers = {} + k8s_cert_existed = False + + if os.path.exists(K8S_BEARER_TOKEN_FILE_NAME) and os.stat(K8S_BEARER_TOKEN_FILE_NAME).st_size > 0: + try: + with open(K8S_BEARER_TOKEN_FILE_NAME, 'r') as tokenfile: + headers = {'Authorization': 'Bearer ' + tokenfile.read() } + except: + Logger.log(sys.exc_info()[1], 'error') + traceback.print_exc() + sys.exit(1) + else: + Logger.log('Connect Kubernetes API server failed: Could not find bearer token at ' + K8S_BEARER_TOKEN_FILE_NAME + '. Exiting.') + sys.exit(1) + if os.path.exists(K8S_CA_CRT_FILE_NAME) and os.stat(K8S_CA_CRT_FILE_NAME).st_size > 0: + k8s_cert_existed = True + if url: - return requests.get(url + endpoint) + if k8s_cert_existed: + return requests.get(url + endpoint, verify = K8S_CA_CRT_FILE_NAME, headers=headers) else: kube_service_port = os.getenv('KUBERNETES_SERVICE_PORT_HTTPS') if kube_service_port is None: Logger.log('Autodiscover of Kubernetes API server failed:' + 'Could not find env variable KUBERNETES_SERVICE_PORT_HTTPS. Exiting.') sys.exit(1) - if os.path.exists(K8S_BEARER_TOKEN_FILE_NAME) and os.stat(K8S_BEARER_TOKEN_FILE_NAME).st_size > 0: - with open(K8S_BEARER_TOKEN_FILE_NAME, 'r') as tokenfile: - headers = {'Authorization': 'Bearer ' + tokenfile.read() } - else: - Logger.log('Autodiscover of Kubernetes API server failed: Could not find bearer token at ' + - K8S_BEARER_TOKEN_FILE_NAME + '. Exiting.') - sys.exit(1) - if os.path.exists(K8S_CA_CRT_FILE_NAME) and os.stat(K8S_CA_CRT_FILE_NAME).st_size > 0: + if k8s_cert_existed: return requests.get('https://' + K8S_DEFAULT_DNS_NAME + ':' + kube_service_port + endpoint, verify = K8S_CA_CRT_FILE_NAME, headers=headers) diff --git a/kubewatcher.py b/kubewatcher.py index 1cd1275..7604f12 100644 --- a/kubewatcher.py +++ b/kubewatcher.py @@ -6,6 +6,9 @@ import traceback from sdcclient import SdcClient from kube_obj_parser import KubeObjParser, KubeURLParser, Logger +# fix the 'InsecureRequestWarning' error +from requests.packages.urllib3.exceptions import InsecureRequestWarning +requests.packages.urllib3.disable_warnings(InsecureRequestWarning) def log(str, severity='info'): Logger.log(str, severity)