Debian Codegraph @

pbcommand/services/job_poller.py

raw symbols SCIP
1 #!/usr/bin/env python3
2
3 """
4 SMRT Link job poller with retry mechanism
5 """
6
7 import logging
8 import time
9 import json
10 import sys
11
12 from urllib3.exceptions import ProtocolError
13
14 from requests.exceptions import HTTPError, ConnectionError
15
16 from pbcommand.cli.core import get_default_argparser_with_base_opts, pacbio_args_runner
17 from pbcommand.services._service_access_layer import (get_smrtlink_client,
18 _to_url,
19 _process_rget)
20 from pbcommand.services.models import add_smrtlink_server_args, JobExeError, JobStates, ServiceJob
21 from pbcommand.utils import setup_log
22
23 __version__ = "0.1"
24 log = logging.getLogger(__name__)
25
26
27 # FIXME this overlaps with run_client_with_retry, can we consolidate the
28 # general error handling?
29 def poll_for_job_completion(job_id,
30 host,
31 port,
32 user,
33 password,
34 time_out=None,
35 sleep_time=60,
36 retry_on=(),
37 abort_on_interrupt=False):
38 def _get_client():
39 return get_smrtlink_client(host, port, user, password)
40 started_at = time.time()
41 retry_time = sleep_time
42 auth_errors = 0
43 external_job_id = None
44 LOG_INTERVAL = 600
45 SLEEP_TIME_MAX = 600
46 i = 0
47 try:
48 client = _get_client()
49 while True:
50 i += 1
51 job_uri = "/smrt-link/job-manager/jobs/analysis/{}".format(job_id)
52 url = _to_url(client.uri, job_uri)
53 try:
54 job_json = _process_rget(url, headers=client._get_headers())
55 except HTTPError as e:
56 status = e.response.status_code
57 log.info("Got error {e} (code = {c})".format(
58 e=str(e), c=status))
59 if status == 401:
60 auth_errors += 1
61 if auth_errors > 10:
62 raise RuntimeError(
63 "10 successive HTTP 401 errors, exiting")
64 log.warning(
65 "Authentication error, will retry with new token")
66 client = _get_client()
67 continue
68 elif status in retry_on:
69 log.warning("Got HTTP {c}, will retry in {d}s".format(
70 c=status, d=retry_time))
71 time.sleep(retry_time)
72 # if a retryable error occurs, we increment the retry time
73 # up to a max of 30 minutes
74 retry_time = max(1800, retry_time + sleep_time)
75 continue
76 else:
77 raise
78 except (ConnectionError, ProtocolError) as e:
79 log.warning("Connection error: {e}".format(e=str(e)))
80 log.info("Will retry in {d}s".format(d=retry_time))
81 time.sleep(retry_time)
82 # if a retryable error occurs, we increment the retry time
83 # up to a max of 30 minutes
84 retry_time = max(1800, retry_time + sleep_time)
85 continue
86 else:
87 # if request succeeded, reset the retry_time
88 auth_errors = 0
89 retry_time = sleep_time
90 run_time = time.time() - started_at
91 job = ServiceJob.from_d(job_json)
92 if external_job_id is None and job.external_job_id is not None:
93 external_job_id = job.external_job_id
94 log.info("Cromwell workflow ID is %s", external_job_id)
95 if job.state in JobStates.ALL_COMPLETED or sleep_time == 0:
96 return job_json
97 msg = "Running pipeline {n} (job {j}) state: {s} runtime:{r:.2f} sec {i} iteration".format(
98 n=job.name, j=job.id, s=job.state, r=run_time, i=i)
99 if run_time % LOG_INTERVAL < sleep_time:
100 log.info(msg)
101 else:
102 log.debug(msg)
103 if time_out is not None:
104 if run_time > time_out:
105 raise JobExeError(
106 "Exceeded runtime {r} of {t}".format(
107 r=run_time, t=time_out))
108 time.sleep(sleep_time)
109 # after an hour we increase the wait
110 if run_time > 3600:
111 sleep_time = min(SLEEP_TIME_MAX, sleep_time * 5)
112 except KeyboardInterrupt:
113 if abort_on_interrupt:
114 client.terminate_job_id(job_id)
115 raise
116
117
118 def run_args(args):
119 d = poll_for_job_completion(
120 args.job_id,
121 args.host,
122 args.port,
123 args.user,
124 args.password,
125 time_out=args.max_time,
126 sleep_time=args.poll_interval,
127 retry_on=args.retry_on,
128 abort_on_interrupt=False)
129 job = ServiceJob.from_d(d)
130 log.info(str(job))
131 if args.json is not None:
132 with open(args.json, "wt") as json_out:
133 json_out.write(json.dumps(d))
134 log.info("Wrote job JSON to {f}".format(f=args.json))
135 if job.state in JobStates.ALL_FAILED:
136 return 1
137 return 0
138
139
140 def _get_parser():
141 p = get_default_argparser_with_base_opts(
142 description=__doc__,
143 version=__version__,
144 default_level="INFO")
145 p.add_argument("job_id", help="SMRT Link Job ID (or UUID)")
146 add_smrtlink_server_args(p)
147 p.add_argument("--retry-on",
148 action="store",
149 type=lambda arg: [int(x) for x in arg.split(",")],
150 default=[],
151 help="HTTP error codes to retry")
152 p.add_argument("--json",
153 action="store",
154 default=None,
155 help="Name of output file to write")
156 p.add_argument("--max-time",
157 action="store",
158 type=int,
159 default=None,
160 help="Max time to wait before aborting")
161 p.add_argument("--poll-interval",
162 action="store",
163 type=int,
164 default=60,
165 help="Time to sleep between polling for job state. If set to zero, the program will exit immediately after getting job status, regardless of state.")
166 return p
167
168
169 def main(argv=sys.argv):
170 return pacbio_args_runner(
171 argv=argv[1:],
172 parser=_get_parser(),
173 args_runner_func=run_args,
174 alog=log,
175 setup_log_func=setup_log)
176
177
178 if __name__ == "__main__":
179 sys.exit(main(sys.argv))