blob: 3f76d10395abc60559332af902485387753965c8 [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)
k.kedron19664b32019-05-14 16:13:00 +020023formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
24handler.setFormatter(formatter)
Mandeep Khindad6ea9872017-06-24 11:49:37 -040025handler.setLevel(logging.INFO)
26log.addHandler(handler)
27log.setLevel(logging.INFO)
28
BorislavG06518262018-02-14 17:40:49 +020029configuration = client.Configuration()
30configuration.host = "https://" + host
31configuration.ssl_ca_cert = cert
32configuration.api_key['authorization'] = token
33configuration.api_key_prefix['authorization'] = 'Bearer'
34coreV1Api = client.CoreV1Api(client.ApiClient(configuration))
k.kedron19664b32019-05-14 16:13:00 +020035api_instance = client.ExtensionsV1beta1Api(client.ApiClient(configuration))
Mahendra Raghuwanshi6a8304c2019-01-28 09:49:30 +000036api = client.AppsV1beta1Api(client.ApiClient(configuration))
37batchV1Api = client.BatchV1Api(client.ApiClient(configuration))
38
k.kedron19664b32019-05-14 16:13:00 +020039
Mahendra Raghuwanshi6a8304c2019-01-28 09:49:30 +000040def is_job_complete(job_name):
41 complete = False
42 log.info("Checking if " + job_name + " is complete")
Mahendra Raghuwanshi6a8304c2019-01-28 09:49:30 +000043 try:
44 response = batchV1Api.read_namespaced_job_status(job_name, namespace)
45 if response.status.succeeded == 1:
46 job_status_type = response.status.conditions[0].type
47 if job_status_type == "Complete":
48 complete = True
49 log.info(job_name + " is complete")
50 else:
51 log.info(job_name + " is not complete")
52 else:
53 log.info(job_name + " has not succeeded yet")
54 return complete
55 except Exception as e:
56 log.error("Exception when calling read_namespaced_job_status: %s\n" % e)
57
k.kedron19664b32019-05-14 16:13:00 +020058
Mahendra Raghuwanshi6a8304c2019-01-28 09:49:30 +000059def wait_for_statefulset_complete(statefulset_name):
60 try:
61 response = api.read_namespaced_stateful_set(statefulset_name, namespace)
62 s = response.status
k.kedron19664b32019-05-14 16:13:00 +020063 if (s.updated_replicas == response.spec.replicas and
Mahendra Raghuwanshi6a8304c2019-01-28 09:49:30 +000064 s.replicas == response.spec.replicas and
65 s.ready_replicas == response.spec.replicas and
66 s.current_replicas == response.spec.replicas and
67 s.observed_generation == response.metadata.generation):
68 log.info("Statefulset " + statefulset_name + " is ready")
69 return True
70 else:
71 log.info("Statefulset " + statefulset_name + " is not ready")
72 return False
73 except Exception as e:
74 log.error("Exception when waiting for Statefulset status: %s\n" % e)
75
k.kedron19664b32019-05-14 16:13:00 +020076
Mahendra Raghuwanshi6a8304c2019-01-28 09:49:30 +000077def wait_for_deployment_complete(deployment_name):
78 try:
79 response = api.read_namespaced_deployment(deployment_name, namespace)
80 s = response.status
k.kedron19664b32019-05-14 16:13:00 +020081 if (s.unavailable_replicas is None and
Akansha Duab77da7a2019-10-03 17:15:21 +053082 ( s.updated_replicas is None or s.updated_replicas == response.spec.replicas ) and
Mahendra Raghuwanshi6a8304c2019-01-28 09:49:30 +000083 s.replicas == response.spec.replicas and
84 s.ready_replicas == response.spec.replicas and
85 s.observed_generation == response.metadata.generation):
86 log.info("Deployment " + deployment_name + " is ready")
87 return True
88 else:
89 log.info("Deployment " + deployment_name + " is not ready")
90 return False
91 except Exception as e:
92 log.error("Exception when waiting for deployment status: %s\n" % e)
Mandeep Khindad6ea9872017-06-24 11:49:37 -040093
k.kedron19664b32019-05-14 16:13:00 +020094
Mandeep Khindad6ea9872017-06-24 11:49:37 -040095def is_ready(container_name):
Mandeep Khindad6ea9872017-06-24 11:49:37 -040096 ready = False
BorislavG06518262018-02-14 17:40:49 +020097 log.info("Checking if " + container_name + " is ready")
Mandeep Khindad6ea9872017-06-24 11:49:37 -040098 try:
k.kedron19664b32019-05-14 16:13:00 +020099 response = coreV1Api.list_namespaced_pod(namespace=namespace,
100 watch=False)
Mandeep Khindad6ea9872017-06-24 11:49:37 -0400101 for i in response.items:
BorislavG07dc7db2018-02-14 15:23:51 +0200102 # container_statuses can be None, which is non-iterable.
103 if i.status.container_statuses is None:
BorislavG06518262018-02-14 17:40:49 +0200104 continue
Mandeep Khindad6ea9872017-06-24 11:49:37 -0400105 for s in i.status.container_statuses:
Mahendra Raghuwanshi6a8304c2019-01-28 09:49:30 +0000106 if s.name == container_name:
k.kedron19664b32019-05-14 16:13:00 +0200107 name = read_name(i)
108 if i.metadata.owner_references[0].kind == "StatefulSet":
109 ready = wait_for_statefulset_complete(name)
Mahendra Raghuwanshi6a8304c2019-01-28 09:49:30 +0000110 elif i.metadata.owner_references[0].kind == "ReplicaSet":
k.kedron19664b32019-05-14 16:13:00 +0200111 deployment_name = get_deployment_name(name)
112 ready = wait_for_deployment_complete(deployment_name)
Mahendra Raghuwanshi6a8304c2019-01-28 09:49:30 +0000113 elif i.metadata.owner_references[0].kind == "Job":
k.kedron19664b32019-05-14 16:13:00 +0200114 ready = is_job_complete(name)
Mahendra Raghuwanshi6a8304c2019-01-28 09:49:30 +0000115
116 return ready
117
Mandeep Khindad6ea9872017-06-24 11:49:37 -0400118 else:
119 continue
120 return ready
121 except Exception as e:
122 log.error("Exception when calling list_namespaced_pod: %s\n" % e)
123
k.kedron19664b32019-05-14 16:13:00 +0200124
125def read_name(item):
126 return item.metadata.owner_reference[0].name
127
128
129def get_deployment_name(replicaset):
130 api_response = api_instance.read_namespaced_replica_set_status(replicaset,
131 namespace)
132 deployment_name = read_name(api_response)
133 return deployment_name
134
135
BorislavG06518262018-02-14 17:40:49 +0200136DEF_TIMEOUT = 10
137DESCRIPTION = "Kubernetes container readiness check utility"
k.kedron19664b32019-05-14 16:13:00 +0200138USAGE = "Usage: ready.py [-t <timeout>] -c <container_name> " \
139 "[-c <container_name> ...]\n" \
BorislavG06518262018-02-14 17:40:49 +0200140 "where\n" \
k.kedron19664b32019-05-14 16:13:00 +0200141 "<timeout> - wait for container readiness timeout in min, " \
142 "default is " + str(DEF_TIMEOUT) + "\n" \
BorislavG06518262018-02-14 17:40:49 +0200143 "<container_name> - name of the container to wait for\n"
144
k.kedron19664b32019-05-14 16:13:00 +0200145
BorislavG06518262018-02-14 17:40:49 +0200146def main(argv):
Mandeep Khindad6ea9872017-06-24 11:49:37 -0400147 # args are a list of container names
BorislavG06518262018-02-14 17:40:49 +0200148 container_names = []
149 timeout = DEF_TIMEOUT
150 try:
k.kedron19664b32019-05-14 16:13:00 +0200151 opts, args = getopt.getopt(argv, "hc:t:", ["container-name=",
152 "timeout=",
153 "help"])
BorislavG06518262018-02-14 17:40:49 +0200154 for opt, arg in opts:
155 if opt in ("-h", "--help"):
156 print("%s\n\n%s" % (DESCRIPTION, USAGE))
157 sys.exit()
158 elif opt in ("-c", "--container-name"):
159 container_names.append(arg)
160 elif opt in ("-t", "--timeout"):
161 timeout = float(arg)
162 except (getopt.GetoptError, ValueError) as e:
163 print("Error parsing input parameters: %s\n" % e)
164 print(USAGE)
165 sys.exit(2)
166 if container_names.__len__() == 0:
167 print("Missing required input parameter(s)\n")
168 print(USAGE)
169 sys.exit(2)
170
171 for container_name in container_names:
172 timeout = time.time() + timeout * 60
Mandeep Khindad6ea9872017-06-24 11:49:37 -0400173 while True:
174 ready = is_ready(container_name)
175 if ready is True:
176 break
177 elif time.time() > timeout:
k.kedron19664b32019-05-14 16:13:00 +0200178 log.warning("timed out waiting for '" + container_name +
179 "' to be ready")
Mandeep Khindad6ea9872017-06-24 11:49:37 -0400180 exit(1)
181 else:
k.kedron19664b32019-05-14 16:13:00 +0200182 # spread in time potentially parallel execution in multiple
183 # containers
Dmitry Puzikov0c588d52019-04-25 14:53:03 +0200184 time.sleep(random.randint(5, 11))
Mandeep Khindad6ea9872017-06-24 11:49:37 -0400185
k.kedron19664b32019-05-14 16:13:00 +0200186
Mandeep Khindad6ea9872017-06-24 11:49:37 -0400187if __name__ == "__main__":
BorislavG06518262018-02-14 17:40:49 +0200188 main(sys.argv[1:])
Mandeep Khindad6ea9872017-06-24 11:49:37 -0400189