Add message-router dependency in blueprint-processor for kafka-listener.
[oom.git] / kubernetes / readiness / docker / init / job_complete.py
1 #!/usr/bin/env python
2 import getopt
3 import logging
4 import os
5 import sys
6 import time
7 import random
8
9 from kubernetes import client
10
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']
16
17 with open(token_path, 'r') as token_file:
18     token = token_file.read().replace('\n', '')
19
20 # setup logging
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)
27
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))
34
35
36 def is_job_complete(job_name):
37     complete = False
38     log.info("Checking if " + job_name + "  is complete")
39     response = ""
40     try:
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":
45                 complete = True
46             else:
47                 log.info(job_name + " is not complete")
48         else:
49             log.info(job_name + " has not succeeded yet")
50         return complete
51     except Exception as e:
52         log.error("Exception when calling read_namespaced_job_status: %s\n" % e)
53
54
55 DEF_TIMEOUT = 10
56 DESCRIPTION = "Kubernetes container job complete check utility"
57 USAGE = "Usage: job_complete.py [-t <timeout>] -j <job_name> [-j <job_name> ...]\n" \
58         "where\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"
61
62 def main(argv):
63     # args are a list of job names
64     job_names = []
65     timeout = DEF_TIMEOUT
66     try:
67         opts, args = getopt.getopt(argv, "hj:t:", ["job-name=", "timeout=", "help"])
68         for opt, arg in opts:
69             if opt in ("-h", "--help"):
70                 print("%s\n\n%s" % (DESCRIPTION, USAGE))
71                 sys.exit()
72             elif opt in ("-j", "--job-name"):
73                 job_names.append(arg)
74             elif opt in ("-t", "--timeout"):
75                 timeout = float(arg)
76     except (getopt.GetoptError, ValueError) as e:
77         print("Error parsing input parameters: %s\n" % e)
78         print(USAGE)
79         sys.exit(2)
80     if job_names.__len__() == 0:
81         print("Missing required input parameter(s)\n")
82         print(USAGE)
83         sys.exit(2)
84
85     for job_name in job_names:
86         timeout = time.time() + timeout * 60
87         while True:
88             complete = is_job_complete(job_name)
89             if complete is True:
90                 break
91             elif time.time() > timeout:
92                 log.warning("timed out waiting for '" + job_name + "' to be completed")
93                 exit(1)
94             else:
95                 # spread in time potentially parallel execution in multiple containers
96                 time.sleep(random.randint(5, 11))
97
98 if __name__ == "__main__":
99     main(sys.argv[1:])