blob: a9570c595199990de4f14382f0480283c9a3ae2e [file] [log] [blame]
Dmitry Puzikovd0101df2019-04-25 14:33:48 +02001#!/usr/bin/env python
Mandeep Khinda67edf6d2018-03-26 23:30:25 +00002import getopt
3import logging
4import os
5import sys
6import time
Dmitry Puzikov0c588d52019-04-25 14:53:03 +02007import random
Mandeep Khinda67edf6d2018-03-26 23:30:25 +00008
9from kubernetes import client
10
11# extract env variables.
12namespace = 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
20# setup logging
21log = 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 Khinda67edf6d2018-03-26 23:30:25 +000025handler.setLevel(logging.INFO)
26log.addHandler(handler)
27log.setLevel(logging.INFO)
28
29configuration = client.Configuration()
30configuration.host = "https://" + host
31configuration.ssl_ca_cert = cert
32configuration.api_key['authorization'] = token
33configuration.api_key_prefix['authorization'] = 'Bearer'
34batchV1Api = client.BatchV1Api(client.ApiClient(configuration))
35
36
37def is_job_complete(job_name):
38 complete = False
39 log.info("Checking if " + job_name + " is complete")
40 response = ""
41 try:
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":
46 complete = True
47 else:
48 log.info(job_name + " is not complete")
49 else:
50 log.info(job_name + " has not succeeded yet")
51 return complete
52 except Exception as e:
53 log.error("Exception when calling read_namespaced_job_status: %s\n" % e)
54
55
56DEF_TIMEOUT = 10
57DESCRIPTION = "Kubernetes container job complete check utility"
k.kedron19664b32019-05-14 16:13:00 +020058USAGE = "Usage: job_complete.py [-t <timeout>] -j <job_name> " \
59 "[-j <job_name> ...]\n" \
Mandeep Khinda67edf6d2018-03-26 23:30:25 +000060 "where\n" \
k.kedron19664b32019-05-14 16:13:00 +020061 "<timeout> - wait for container job complete timeout in min, " \
62 "default is " + str(DEF_TIMEOUT) + "\n" \
Mandeep Khinda67edf6d2018-03-26 23:30:25 +000063 "<job_name> - name of the job to wait for\n"
64
k.kedron19664b32019-05-14 16:13:00 +020065
Mandeep Khinda67edf6d2018-03-26 23:30:25 +000066def main(argv):
67 # args are a list of job names
68 job_names = []
69 timeout = DEF_TIMEOUT
70 try:
k.kedron19664b32019-05-14 16:13:00 +020071 opts, args = getopt.getopt(argv, "hj:t:", ["job-name=",
72 "timeout=",
73 "help"])
Mandeep Khinda67edf6d2018-03-26 23:30:25 +000074 for opt, arg in opts:
75 if opt in ("-h", "--help"):
76 print("%s\n\n%s" % (DESCRIPTION, USAGE))
77 sys.exit()
78 elif opt in ("-j", "--job-name"):
79 job_names.append(arg)
80 elif opt in ("-t", "--timeout"):
81 timeout = float(arg)
82 except (getopt.GetoptError, ValueError) as e:
83 print("Error parsing input parameters: %s\n" % e)
84 print(USAGE)
85 sys.exit(2)
86 if job_names.__len__() == 0:
87 print("Missing required input parameter(s)\n")
88 print(USAGE)
89 sys.exit(2)
90
91 for job_name in job_names:
92 timeout = time.time() + timeout * 60
93 while True:
94 complete = is_job_complete(job_name)
95 if complete is True:
96 break
97 elif time.time() > timeout:
k.kedron19664b32019-05-14 16:13:00 +020098 log.warning("timed out waiting for '" + job_name +
99 "' to be completed")
Mandeep Khinda67edf6d2018-03-26 23:30:25 +0000100 exit(1)
101 else:
k.kedron19664b32019-05-14 16:13:00 +0200102 # spread in time potentially parallel execution in multiple
103 # containers
Dmitry Puzikov0c588d52019-04-25 14:53:03 +0200104 time.sleep(random.randint(5, 11))
Mandeep Khinda67edf6d2018-03-26 23:30:25 +0000105
k.kedron19664b32019-05-14 16:13:00 +0200106
Mandeep Khinda67edf6d2018-03-26 23:30:25 +0000107if __name__ == "__main__":
k.kedron19664b32019-05-14 16:13:00 +0200108 main(sys.argv[1:])