8 from kubernetes import client
10 # extract env variables.
11 namespace = os.environ['NAMESPACE']
12 cert = os.environ['CERT']
13 host = os.environ['KUBERNETES_SERVICE_HOST']
14 token_path = os.environ['TOKEN']
16 with open(token_path, 'r') as token_file:
17 token = token_file.read().replace('\n', '')
20 log = logging.getLogger(__name__)
21 handler = logging.StreamHandler(sys.stdout)
22 handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
23 handler.setLevel(logging.INFO)
24 log.addHandler(handler)
25 log.setLevel(logging.INFO)
27 configuration = client.Configuration()
28 configuration.host = "https://" + host
29 configuration.ssl_ca_cert = cert
30 configuration.api_key['authorization'] = token
31 configuration.api_key_prefix['authorization'] = 'Bearer'
32 coreV1Api = client.CoreV1Api(client.ApiClient(configuration))
34 def is_ready(container_name):
36 log.info("Checking if " + container_name + " is ready")
38 response = coreV1Api.list_namespaced_pod(namespace=namespace, watch=False)
39 for i in response.items:
40 # container_statuses can be None, which is non-iterable.
41 if i.status.container_statuses is None:
43 for s in i.status.container_statuses:
44 if s.name == container_name:
47 log.info(container_name + " is not ready.")
49 log.info(container_name + " is ready!")
53 except Exception as e:
54 log.error("Exception when calling list_namespaced_pod: %s\n" % e)
58 DESCRIPTION = "Kubernetes container readiness check utility"
59 USAGE = "Usage: ready.py [-t <timeout>] -c <container_name> [-c <container_name> ...]\n" \
61 "<timeout> - wait for container readiness timeout in min, default is " + str(DEF_TIMEOUT) + "\n" \
62 "<container_name> - name of the container to wait for\n"
65 # args are a list of container names
69 opts, args = getopt.getopt(argv, "hc:t:", ["container-name=", "timeout=", "help"])
71 if opt in ("-h", "--help"):
72 print("%s\n\n%s" % (DESCRIPTION, USAGE))
74 elif opt in ("-c", "--container-name"):
75 container_names.append(arg)
76 elif opt in ("-t", "--timeout"):
78 except (getopt.GetoptError, ValueError) as e:
79 print("Error parsing input parameters: %s\n" % e)
82 if container_names.__len__() == 0:
83 print("Missing required input parameter(s)\n")
87 for container_name in container_names:
88 timeout = time.time() + timeout * 60
90 ready = is_ready(container_name)
93 elif time.time() > timeout:
94 log.warning("timed out waiting for '" + container_name + "' to be ready")
100 if __name__ == "__main__":