blob: 0e133eab01e384c9b12b65fc3b19182393c126f6 [file] [log] [blame]
Dmitry Puzikovd0101df2019-04-25 14:33:48 +02001#!/usr/bin/env python
BorislavG06518262018-02-14 17:40:49 +02002import getopt
3import logging
4import os
5import sys
6import time
Dmitry Puzikov0c588d52019-04-25 14:53:03 +02007import random
Mandeep Khindad6ea9872017-06-24 11:49:37 -04008
BorislavG06518262018-02-14 17:40:49 +02009from kubernetes import client
10
11# extract env variables.
Mandeep Khindad6ea9872017-06-24 11:49:37 -040012namespace = os.environ['NAMESPACE']
13cert = os.environ['CERT']
14host = os.environ['KUBERNETES_SERVICE_HOST']
15token_path = os.environ['TOKEN']
16
17with open(token_path, 'r') as token_file:
18 token = token_file.read().replace('\n', '')
19
BorislavG06518262018-02-14 17:40:49 +020020# setup logging
Mandeep Khindad6ea9872017-06-24 11:49:37 -040021log = logging.getLogger(__name__)
22handler = logging.StreamHandler(sys.stdout)
23handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
24handler.setLevel(logging.INFO)
25log.addHandler(handler)
26log.setLevel(logging.INFO)
27
BorislavG06518262018-02-14 17:40:49 +020028configuration = client.Configuration()
29configuration.host = "https://" + host
30configuration.ssl_ca_cert = cert
31configuration.api_key['authorization'] = token
32configuration.api_key_prefix['authorization'] = 'Bearer'
33coreV1Api = client.CoreV1Api(client.ApiClient(configuration))
Mahendra Raghuwanshi6a8304c2019-01-28 09:49:30 +000034api_instance=client.ExtensionsV1beta1Api(client.ApiClient(configuration))
35api = client.AppsV1beta1Api(client.ApiClient(configuration))
36batchV1Api = client.BatchV1Api(client.ApiClient(configuration))
37
38def is_job_complete(job_name):
39 complete = False
40 log.info("Checking if " + job_name + " is complete")
41 response = ""
42 try:
43 response = batchV1Api.read_namespaced_job_status(job_name, namespace)
44 if response.status.succeeded == 1:
45 job_status_type = response.status.conditions[0].type
46 if job_status_type == "Complete":
47 complete = True
48 log.info(job_name + " is complete")
49 else:
50 log.info(job_name + " is not complete")
51 else:
52 log.info(job_name + " has not succeeded yet")
53 return complete
54 except Exception as e:
55 log.error("Exception when calling read_namespaced_job_status: %s\n" % e)
56
57def wait_for_statefulset_complete(statefulset_name):
58 try:
59 response = api.read_namespaced_stateful_set(statefulset_name, namespace)
60 s = response.status
61 if ( s.updated_replicas == response.spec.replicas and
62 s.replicas == response.spec.replicas and
63 s.ready_replicas == response.spec.replicas and
64 s.current_replicas == response.spec.replicas and
65 s.observed_generation == response.metadata.generation):
66 log.info("Statefulset " + statefulset_name + " is ready")
67 return True
68 else:
69 log.info("Statefulset " + statefulset_name + " is not ready")
70 return False
71 except Exception as e:
72 log.error("Exception when waiting for Statefulset status: %s\n" % e)
73
74def wait_for_deployment_complete(deployment_name):
75 try:
76 response = api.read_namespaced_deployment(deployment_name, namespace)
77 s = response.status
78 if ( s.unavailable_replicas == None and
79 s.updated_replicas == response.spec.replicas and
80 s.replicas == response.spec.replicas and
81 s.ready_replicas == response.spec.replicas and
82 s.observed_generation == response.metadata.generation):
83 log.info("Deployment " + deployment_name + " is ready")
84 return True
85 else:
86 log.info("Deployment " + deployment_name + " is not ready")
87 return False
88 except Exception as e:
89 log.error("Exception when waiting for deployment status: %s\n" % e)
Mandeep Khindad6ea9872017-06-24 11:49:37 -040090
91def is_ready(container_name):
Mandeep Khindad6ea9872017-06-24 11:49:37 -040092 ready = False
BorislavG06518262018-02-14 17:40:49 +020093 log.info("Checking if " + container_name + " is ready")
Mandeep Khindad6ea9872017-06-24 11:49:37 -040094 try:
BorislavG06518262018-02-14 17:40:49 +020095 response = coreV1Api.list_namespaced_pod(namespace=namespace, watch=False)
Mandeep Khindad6ea9872017-06-24 11:49:37 -040096 for i in response.items:
BorislavG07dc7db2018-02-14 15:23:51 +020097 # container_statuses can be None, which is non-iterable.
98 if i.status.container_statuses is None:
BorislavG06518262018-02-14 17:40:49 +020099 continue
Mandeep Khindad6ea9872017-06-24 11:49:37 -0400100 for s in i.status.container_statuses:
Mahendra Raghuwanshi6a8304c2019-01-28 09:49:30 +0000101 if s.name == container_name:
102 if i.metadata.owner_references[0].kind == "StatefulSet":
103 ready = wait_for_statefulset_complete(i.metadata.owner_references[0].name)
104 elif i.metadata.owner_references[0].kind == "ReplicaSet":
105 api_response = api_instance.read_namespaced_replica_set_status(i.metadata.owner_references[0].name, namespace)
106 ready = wait_for_deployment_complete(api_response.metadata.owner_references[0].name)
107 elif i.metadata.owner_references[0].kind == "Job":
108 ready = is_job_complete(i.metadata.owner_references[0].name)
109
110 return ready
111
Mandeep Khindad6ea9872017-06-24 11:49:37 -0400112 else:
113 continue
114 return ready
115 except Exception as e:
116 log.error("Exception when calling list_namespaced_pod: %s\n" % e)
117
BorislavG06518262018-02-14 17:40:49 +0200118DEF_TIMEOUT = 10
119DESCRIPTION = "Kubernetes container readiness check utility"
120USAGE = "Usage: ready.py [-t <timeout>] -c <container_name> [-c <container_name> ...]\n" \
121 "where\n" \
122 "<timeout> - wait for container readiness timeout in min, default is " + str(DEF_TIMEOUT) + "\n" \
123 "<container_name> - name of the container to wait for\n"
124
125def main(argv):
Mandeep Khindad6ea9872017-06-24 11:49:37 -0400126 # args are a list of container names
BorislavG06518262018-02-14 17:40:49 +0200127 container_names = []
128 timeout = DEF_TIMEOUT
129 try:
130 opts, args = getopt.getopt(argv, "hc:t:", ["container-name=", "timeout=", "help"])
131 for opt, arg in opts:
132 if opt in ("-h", "--help"):
133 print("%s\n\n%s" % (DESCRIPTION, USAGE))
134 sys.exit()
135 elif opt in ("-c", "--container-name"):
136 container_names.append(arg)
137 elif opt in ("-t", "--timeout"):
138 timeout = float(arg)
139 except (getopt.GetoptError, ValueError) as e:
140 print("Error parsing input parameters: %s\n" % e)
141 print(USAGE)
142 sys.exit(2)
143 if container_names.__len__() == 0:
144 print("Missing required input parameter(s)\n")
145 print(USAGE)
146 sys.exit(2)
147
148 for container_name in container_names:
149 timeout = time.time() + timeout * 60
Mandeep Khindad6ea9872017-06-24 11:49:37 -0400150 while True:
151 ready = is_ready(container_name)
152 if ready is True:
153 break
154 elif time.time() > timeout:
BorislavG06518262018-02-14 17:40:49 +0200155 log.warning("timed out waiting for '" + container_name + "' to be ready")
Mandeep Khindad6ea9872017-06-24 11:49:37 -0400156 exit(1)
157 else:
Dmitry Puzikov0c588d52019-04-25 14:53:03 +0200158 # spread in time potentially parallel execution in multiple containers
159 time.sleep(random.randint(5, 11))
Mandeep Khindad6ea9872017-06-24 11:49:37 -0400160
Mandeep Khindad6ea9872017-06-24 11:49:37 -0400161if __name__ == "__main__":
BorislavG06518262018-02-14 17:40:49 +0200162 main(sys.argv[1:])
Mandeep Khindad6ea9872017-06-24 11:49:37 -0400163