Merge "expose ansible container on nfs mount"
[oom.git] / kubernetes / readiness / docker / init / ready.py
1 #!/usr/bin/python
2 import getopt
3 import logging
4 import os
5 import sys
6 import time
7
8 from kubernetes import client
9
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']
15
16 with open(token_path, 'r') as token_file:
17     token = token_file.read().replace('\n', '')
18
19 # setup logging
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)
26
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))
33
34 def is_ready(container_name):
35     ready = False
36     log.info("Checking if " + container_name + "  is ready")
37     try:
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:
42                 continue
43             for s in i.status.container_statuses:
44                 if i.metadata.owner_references[0].kind  == "StatefulSet":
45                     if i.metadata.name == container_name:
46                         ready = s.ready
47                         if not ready:
48                             log.info(container_name + " is not ready.")
49                         else:
50                             log.info(container_name + " is ready!")
51                     else:
52                         continue
53                 elif s.name == container_name:
54                     ready = s.ready
55                     if not ready:
56                         log.info(container_name + " is not ready.")
57                     else:
58                         log.info(container_name + " is ready!")
59                 else:
60                     continue
61         return ready
62     except Exception as e:
63         log.error("Exception when calling list_namespaced_pod: %s\n" % e)
64
65
66 DEF_TIMEOUT = 10
67 DESCRIPTION = "Kubernetes container readiness check utility"
68 USAGE = "Usage: ready.py [-t <timeout>] -c <container_name> [-c <container_name> ...]\n" \
69         "where\n" \
70         "<timeout> - wait for container readiness timeout in min, default is " + str(DEF_TIMEOUT) + "\n" \
71         "<container_name> - name of the container to wait for\n"
72
73 def main(argv):
74     # args are a list of container names
75     container_names = []
76     timeout = DEF_TIMEOUT
77     try:
78         opts, args = getopt.getopt(argv, "hc:t:", ["container-name=", "timeout=", "help"])
79         for opt, arg in opts:
80             if opt in ("-h", "--help"):
81                 print("%s\n\n%s" % (DESCRIPTION, USAGE))
82                 sys.exit()
83             elif opt in ("-c", "--container-name"):
84                 container_names.append(arg)
85             elif opt in ("-t", "--timeout"):
86                 timeout = float(arg)
87     except (getopt.GetoptError, ValueError) as e:
88         print("Error parsing input parameters: %s\n" % e)
89         print(USAGE)
90         sys.exit(2)
91     if container_names.__len__() == 0:
92         print("Missing required input parameter(s)\n")
93         print(USAGE)
94         sys.exit(2)
95
96     for container_name in container_names:
97         timeout = time.time() + timeout * 60
98         while True:
99             ready = is_ready(container_name)
100             if ready is True:
101                 break
102             elif time.time() > timeout:
103                 log.warning("timed out waiting for '" + container_name + "' to be ready")
104                 exit(1)
105             else:
106                 time.sleep(5)
107
108
109 if __name__ == "__main__":
110     main(sys.argv[1:])
111