8 from kubernetes import config
9 from kubernetes.client import Configuration
10 from kubernetes.client.api import core_v1_api
11 from kubernetes.client.rest import ApiException
12 from kubernetes.stream import stream
14 from kubernetes import client
16 # extract env variables.
17 namespace = os.environ['NAMESPACE']
18 cert = os.environ['CERT']
19 host = os.environ['KUBERNETES_SERVICE_HOST']
20 token_path = os.environ['TOKEN']
22 with open(token_path, 'r') as token_file:
23 token = token_file.read().replace('\n', '')
26 log = logging.getLogger(__name__)
27 handler = logging.StreamHandler(sys.stdout)
28 handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
29 handler.setLevel(logging.INFO)
30 log.addHandler(handler)
31 log.setLevel(logging.INFO)
33 configuration = client.Configuration()
34 configuration.host = "https://" + host
35 configuration.ssl_ca_cert = cert
36 configuration.api_key['authorization'] = token
37 configuration.api_key_prefix['authorization'] = 'Bearer'
38 configuration.assert_hostname = False
39 coreV1Api = client.CoreV1Api(client.ApiClient(configuration))
40 api_instance = client.CoreV1Api(client.ApiClient(configuration))
42 def run_command( pod_name, command ):
48 resp = stream(api_instance.connect_get_namespaced_pod_exec, pod_name, namespace,
50 stderr=True, stdin=False,
51 stdout=True, tty=False)
52 except ApiException as e:
53 print("Exception when calling CoreV1Api->connect_get_namespaced_pod_exec: %s\n" % e)
58 def find_pod(container_name,command,pods):
61 response = coreV1Api.list_namespaced_pod(namespace=namespace, watch=False)
62 for i in response.items:
63 # container_statuses can be None, which is non-iterable.
64 if i.status.container_statuses is None:
66 for s in i.status.container_statuses:
67 if s.name == container_name:
69 print (i.metadata.name)
71 ready = run_command(i.metadata.name,command)
74 except Exception as e:
75 log.error("Exception when calling list_namespaced_pod: %s\n" % e)
80 DESCRIPTION = "Kubernetes container readiness check utility"
81 USAGE = "Usage: ready.py [-t <timeout>] -c <container_name> [-c <container_name> ...]\n" \
83 "<container_name> - name of the container to wait for\n"
90 opts, args = getopt.getopt(argv, "ghp:c:", ["pod-container-name=", "command=", "help","getpods"])
92 if opt in ("-h", "--help"):
93 print("%s\n\n%s" % (DESCRIPTION, USAGE))
95 elif opt in ("-p", "--pod-container-name"):
97 elif opt in ("-c", "--command"):
99 elif opt in ("-g", "--getpods"):
101 except (getopt.GetoptError, ValueError) as e:
102 print("Error parsing input parameters: %s\n" % e)
105 if container_name.__len__() == 0:
106 print("Missing required input parameter(s)\n")
111 if command.__len__() == 0:
112 print("Missing required input parameter(s)\n")
115 ready = find_pod(container_name,command,pods)
119 if __name__ == "__main__":