blob: 5b3ae333719a690ebd230ad40499601a018c173c [file] [log] [blame]
Akansha Dua7b6e1982019-09-04 13:36:12 +00001#!/usr/bin/python
2import getopt
3import logging
4import os
5import sys
6import time
7
8from kubernetes import config
9from kubernetes.client import Configuration
10from kubernetes.client.apis import core_v1_api
11from kubernetes.client.rest import ApiException
12from kubernetes.stream import stream
13
14from kubernetes import client
15
16# extract env variables.
17namespace = os.environ['NAMESPACE']
18cert = os.environ['CERT']
19host = os.environ['KUBERNETES_SERVICE_HOST']
20token_path = os.environ['TOKEN']
21
22with open(token_path, 'r') as token_file:
23 token = token_file.read().replace('\n', '')
24
25# setup logging
26log = logging.getLogger(__name__)
27handler = logging.StreamHandler(sys.stdout)
28handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
29handler.setLevel(logging.INFO)
30log.addHandler(handler)
31log.setLevel(logging.INFO)
32
33configuration = client.Configuration()
34configuration.host = "https://" + host
35configuration.ssl_ca_cert = cert
36configuration.api_key['authorization'] = token
37configuration.api_key_prefix['authorization'] = 'Bearer'
38configuration.assert_hostname = False
39coreV1Api = client.CoreV1Api(client.ApiClient(configuration))
40api_instance = client.CoreV1Api(client.ApiClient(configuration))
41
42def run_command( pod_name, command ):
43 try:
44 exec_command = [
45 '/bin/sh',
46 '-c',
47 command]
48 resp = stream(api_instance.connect_get_namespaced_pod_exec, pod_name, namespace,
49 command=exec_command,
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)
54 return False
55 print(resp)
56 return True
57
58def find_pod(container_name,command,pods):
59 ready = False
60 try:
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:
65 continue
66 for s in i.status.container_statuses:
67 if s.name == container_name:
68 if pods == True:
69 print (i.metadata.name)
70 else:
71 ready = run_command(i.metadata.name,command)
72 else:
73 continue
74 except Exception as e:
75 log.error("Exception when calling list_namespaced_pod: %s\n" % e)
76
77 return ready
78
79
80DESCRIPTION = "Kubernetes container readiness check utility"
81USAGE = "Usage: ready.py [-t <timeout>] -c <container_name> [-c <container_name> ...]\n" \
82 "where\n" \
83 "<container_name> - name of the container to wait for\n"
84
85def main(argv):
86 pods = False
87 command = ""
88 container_name = ""
89 try:
90 opts, args = getopt.getopt(argv, "ghp:c:", ["pod-container-name=", "command=", "help","getpods"])
91 for opt, arg in opts:
92 if opt in ("-h", "--help"):
93 print("%s\n\n%s" % (DESCRIPTION, USAGE))
94 sys.exit()
95 elif opt in ("-p", "--pod-container-name"):
96 container_name = arg
97 elif opt in ("-c", "--command"):
98 command = arg
99 elif opt in ("-g", "--getpods"):
100 pods = True
101 except (getopt.GetoptError, ValueError) as e:
102 print("Error parsing input parameters: %s\n" % e)
103 print(USAGE)
104 sys.exit(2)
105 if container_name.__len__() == 0:
106 print("Missing required input parameter(s)\n")
107 print(USAGE)
108 sys.exit(2)
109
110 if pods == False:
111 if command.__len__() == 0:
112 print("Missing required input parameter(s)\n")
113 print(USAGE)
114 sys.exit(2)
115 ready = find_pod(container_name,command,pods)
116 if ready == False:
117 sys.exit(2)
118
119if __name__ == "__main__":
120 main(sys.argv[1:])
121
122