9 from kubernetes import client
11 # extract env variables.
12 namespace = os.environ['NAMESPACE']
13 cert = os.environ['CERT']
14 host = os.environ['KUBERNETES_SERVICE_HOST']
15 token_path = os.environ['TOKEN']
17 with open(token_path, 'r') as token_file:
18 token = token_file.read().replace('\n', '')
21 log = logging.getLogger(__name__)
22 handler = logging.StreamHandler(sys.stdout)
23 formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
24 handler.setFormatter(formatter)
25 handler.setLevel(logging.INFO)
26 log.addHandler(handler)
27 log.setLevel(logging.INFO)
29 configuration = client.Configuration()
30 configuration.host = "https://" + host
31 configuration.ssl_ca_cert = cert
32 configuration.api_key['authorization'] = token
33 configuration.api_key_prefix['authorization'] = 'Bearer'
34 coreV1Api = client.CoreV1Api(client.ApiClient(configuration))
35 api_instance = client.ExtensionsV1beta1Api(client.ApiClient(configuration))
36 api = client.AppsV1beta1Api(client.ApiClient(configuration))
37 batchV1Api = client.BatchV1Api(client.ApiClient(configuration))
40 def is_job_complete(job_name):
42 log.info("Checking if " + job_name + " is complete")
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":
49 log.info(job_name + " is complete")
51 log.info(job_name + " is not complete")
53 log.info(job_name + " has not succeeded yet")
55 except Exception as e:
56 log.error("Exception when calling read_namespaced_job_status: %s\n" % e)
59 def wait_for_statefulset_complete(statefulset_name):
61 response = api.read_namespaced_stateful_set(statefulset_name, namespace)
63 if (s.updated_replicas == response.spec.replicas and
64 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")
71 log.info("Statefulset " + statefulset_name + " is not ready")
73 except Exception as e:
74 log.error("Exception when waiting for Statefulset status: %s\n" % e)
77 def wait_for_deployment_complete(deployment_name):
79 response = api.read_namespaced_deployment(deployment_name, namespace)
81 if (s.unavailable_replicas is None and
82 ( s.updated_replicas is None or s.updated_replicas == response.spec.replicas ) and
83 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")
89 log.info("Deployment " + deployment_name + " is not ready")
91 except Exception as e:
92 log.error("Exception when waiting for deployment status: %s\n" % e)
95 def is_ready(container_name):
97 log.info("Checking if " + container_name + " is ready")
99 response = coreV1Api.list_namespaced_pod(namespace=namespace,
101 for i in response.items:
102 # container_statuses can be None, which is non-iterable.
103 if i.status.container_statuses is None:
105 for s in i.status.container_statuses:
106 if s.name == container_name:
108 if i.metadata.owner_references[0].kind == "StatefulSet":
109 ready = wait_for_statefulset_complete(name)
110 elif i.metadata.owner_references[0].kind == "ReplicaSet":
111 deployment_name = get_deployment_name(name)
112 ready = wait_for_deployment_complete(deployment_name)
113 elif i.metadata.owner_references[0].kind == "Job":
114 ready = is_job_complete(name)
121 except Exception as e:
122 log.error("Exception when calling list_namespaced_pod: %s\n" % e)
126 return item.metadata.owner_reference[0].name
129 def get_deployment_name(replicaset):
130 api_response = api_instance.read_namespaced_replica_set_status(replicaset,
132 deployment_name = read_name(api_response)
133 return deployment_name
137 DESCRIPTION = "Kubernetes container readiness check utility"
138 USAGE = "Usage: ready.py [-t <timeout>] -c <container_name> " \
139 "[-c <container_name> ...]\n" \
141 "<timeout> - wait for container readiness timeout in min, " \
142 "default is " + str(DEF_TIMEOUT) + "\n" \
143 "<container_name> - name of the container to wait for\n"
147 # args are a list of container names
149 timeout = DEF_TIMEOUT
151 opts, args = getopt.getopt(argv, "hc:t:", ["container-name=",
154 for opt, arg in opts:
155 if opt in ("-h", "--help"):
156 print("%s\n\n%s" % (DESCRIPTION, USAGE))
158 elif opt in ("-c", "--container-name"):
159 container_names.append(arg)
160 elif opt in ("-t", "--timeout"):
162 except (getopt.GetoptError, ValueError) as e:
163 print("Error parsing input parameters: %s\n" % e)
166 if container_names.__len__() == 0:
167 print("Missing required input parameter(s)\n")
171 for container_name in container_names:
172 timeout = time.time() + timeout * 60
174 ready = is_ready(container_name)
177 elif time.time() > timeout:
178 log.warning("timed out waiting for '" + container_name +
182 # spread in time potentially parallel execution in multiple
184 time.sleep(random.randint(5, 11))
187 if __name__ == "__main__":