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 batchV1Api = client.BatchV1Api(client.ApiClient(configuration))
37 def is_job_complete(job_name):
39 log.info("Checking if " + job_name + " is complete")
42 response = batchV1Api.read_namespaced_job_status(job_name, namespace)
43 if response.status.succeeded == 1:
44 job_status_type = response.status.conditions[0].type
45 if job_status_type == "Complete":
48 log.info(job_name + " is not complete")
50 log.info(job_name + " has not succeeded yet")
52 except Exception as e:
53 log.error("Exception when calling read_namespaced_job_status: %s\n" % e)
57 DESCRIPTION = "Kubernetes container job complete check utility"
58 USAGE = "Usage: job_complete.py [-t <timeout>] -j <job_name> " \
59 "[-j <job_name> ...]\n" \
61 "<timeout> - wait for container job complete timeout in min, " \
62 "default is " + str(DEF_TIMEOUT) + "\n" \
63 "<job_name> - name of the job to wait for\n"
67 # args are a list of job names
71 opts, args = getopt.getopt(argv, "hj:t:", ["job-name=",
75 if opt in ("-h", "--help"):
76 print("%s\n\n%s" % (DESCRIPTION, USAGE))
78 elif opt in ("-j", "--job-name"):
80 elif opt in ("-t", "--timeout"):
82 except (getopt.GetoptError, ValueError) as e:
83 print("Error parsing input parameters: %s\n" % e)
86 if job_names.__len__() == 0:
87 print("Missing required input parameter(s)\n")
91 for job_name in job_names:
92 timeout = time.time() + timeout * 60
94 complete = is_job_complete(job_name)
97 elif time.time() > timeout:
98 log.warning("timed out waiting for '" + job_name +
102 # spread in time potentially parallel execution in multiple
104 time.sleep(random.randint(5, 11))
107 if __name__ == "__main__":