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 batchV1Api = client.BatchV1Api(client.ApiClient(configuration))
36 def is_job_complete(job_name):
38 log.info("Checking if " + job_name + " is complete")
41 response = batchV1Api.read_namespaced_job_status(job_name, namespace)
42 if response.status.succeeded == 1:
43 job_status_type = response.status.conditions[0].type
44 if job_status_type == "Complete":
47 log.info(job_name + " is not complete")
49 log.info(job_name + " has not succeeded yet")
51 except Exception as e:
52 log.error("Exception when calling read_namespaced_job_status: %s\n" % e)
56 DESCRIPTION = "Kubernetes container job complete check utility"
57 USAGE = "Usage: job_complete.py [-t <timeout>] -j <job_name> [-j <job_name> ...]\n" \
59 "<timeout> - wait for container job complete timeout in min, default is " + str(DEF_TIMEOUT) + "\n" \
60 "<job_name> - name of the job to wait for\n"
63 # args are a list of job names
67 opts, args = getopt.getopt(argv, "hj:t:", ["job-name=", "timeout=", "help"])
69 if opt in ("-h", "--help"):
70 print("%s\n\n%s" % (DESCRIPTION, USAGE))
72 elif opt in ("-j", "--job-name"):
74 elif opt in ("-t", "--timeout"):
76 except (getopt.GetoptError, ValueError) as e:
77 print("Error parsing input parameters: %s\n" % e)
80 if job_names.__len__() == 0:
81 print("Missing required input parameter(s)\n")
85 for job_name in job_names:
86 timeout = time.time() + timeout * 60
88 complete = is_job_complete(job_name)
91 elif time.time() > timeout:
92 log.warning("timed out waiting for '" + job_name + "' to be completed")
95 # spread in time potentially parallel execution in multiple containers
96 time.sleep(random.randint(5, 11))
98 if __name__ == "__main__":