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 handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
24 handler.setLevel(logging.INFO)
25 log.addHandler(handler)
26 log.setLevel(logging.INFO)
28 configuration = client.Configuration()
29 configuration.host = "https://" + host
30 configuration.ssl_ca_cert = cert
31 configuration.api_key['authorization'] = token
32 configuration.api_key_prefix['authorization'] = 'Bearer'
33 coreV1Api = client.CoreV1Api(client.ApiClient(configuration))
34 api_instance=client.ExtensionsV1beta1Api(client.ApiClient(configuration))
35 api = client.AppsV1beta1Api(client.ApiClient(configuration))
36 batchV1Api = client.BatchV1Api(client.ApiClient(configuration))
38 def is_job_complete(job_name):
40 log.info("Checking if " + job_name + " is complete")
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":
48 log.info(job_name + " is complete")
50 log.info(job_name + " is not complete")
52 log.info(job_name + " has not succeeded yet")
54 except Exception as e:
55 log.error("Exception when calling read_namespaced_job_status: %s\n" % e)
57 def wait_for_statefulset_complete(statefulset_name):
59 response = api.read_namespaced_stateful_set(statefulset_name, namespace)
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")
69 log.info("Statefulset " + statefulset_name + " is not ready")
71 except Exception as e:
72 log.error("Exception when waiting for Statefulset status: %s\n" % e)
74 def wait_for_deployment_complete(deployment_name):
76 response = api.read_namespaced_deployment(deployment_name, namespace)
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")
86 log.info("Deployment " + deployment_name + " is not ready")
88 except Exception as e:
89 log.error("Exception when waiting for deployment status: %s\n" % e)
91 def is_ready(container_name):
93 log.info("Checking if " + container_name + " is ready")
95 response = coreV1Api.list_namespaced_pod(namespace=namespace, watch=False)
96 for i in response.items:
97 # container_statuses can be None, which is non-iterable.
98 if i.status.container_statuses is None:
100 for s in i.status.container_statuses:
101 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)
115 except Exception as e:
116 log.error("Exception when calling list_namespaced_pod: %s\n" % e)
119 DESCRIPTION = "Kubernetes container readiness check utility"
120 USAGE = "Usage: ready.py [-t <timeout>] -c <container_name> [-c <container_name> ...]\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"
126 # args are a list of container names
128 timeout = DEF_TIMEOUT
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))
135 elif opt in ("-c", "--container-name"):
136 container_names.append(arg)
137 elif opt in ("-t", "--timeout"):
139 except (getopt.GetoptError, ValueError) as e:
140 print("Error parsing input parameters: %s\n" % e)
143 if container_names.__len__() == 0:
144 print("Missing required input parameter(s)\n")
148 for container_name in container_names:
149 timeout = time.time() + timeout * 60
151 ready = is_ready(container_name)
154 elif time.time() > timeout:
155 log.warning("timed out waiting for '" + container_name + "' to be ready")
158 # spread in time potentially parallel execution in multiple containers
159 time.sleep(random.randint(5, 11))
161 if __name__ == "__main__":