File: job_poller.py

package info (click to toggle)
python-pbcommand 2.1.1%2Bgit20231020.28d1635-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,016 kB
  • sloc: python: 7,676; makefile: 220; sh: 73
file content (179 lines) | stat: -rw-r--r-- 6,707 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
#!/usr/bin/env python3

"""
SMRT Link job poller with retry mechanism
"""

import logging
import time
import json
import sys

from urllib3.exceptions import ProtocolError

from requests.exceptions import HTTPError, ConnectionError

from pbcommand.cli.core import get_default_argparser_with_base_opts, pacbio_args_runner
from pbcommand.services._service_access_layer import (get_smrtlink_client,
                                                      _to_url,
                                                      _process_rget)
from pbcommand.services.models import add_smrtlink_server_args, JobExeError, JobStates, ServiceJob
from pbcommand.utils import setup_log

__version__ = "0.1"
log = logging.getLogger(__name__)


# FIXME this overlaps with run_client_with_retry, can we consolidate the
# general error handling?
def poll_for_job_completion(job_id,
                            host,
                            port,
                            user,
                            password,
                            time_out=None,
                            sleep_time=60,
                            retry_on=(),
                            abort_on_interrupt=False):
    def _get_client():
        return get_smrtlink_client(host, port, user, password)
    started_at = time.time()
    retry_time = sleep_time
    auth_errors = 0
    external_job_id = None
    LOG_INTERVAL = 600
    SLEEP_TIME_MAX = 600
    i = 0
    try:
        client = _get_client()
        while True:
            i += 1
            job_uri = "/smrt-link/job-manager/jobs/analysis/{}".format(job_id)
            url = _to_url(client.uri, job_uri)
            try:
                job_json = _process_rget(url, headers=client._get_headers())
            except HTTPError as e:
                status = e.response.status_code
                log.info("Got error {e} (code = {c})".format(
                    e=str(e), c=status))
                if status == 401:
                    auth_errors += 1
                    if auth_errors > 10:
                        raise RuntimeError(
                            "10 successive HTTP 401 errors, exiting")
                    log.warning(
                        "Authentication error, will retry with new token")
                    client = _get_client()
                    continue
                elif status in retry_on:
                    log.warning("Got HTTP {c}, will retry in {d}s".format(
                        c=status, d=retry_time))
                    time.sleep(retry_time)
                    # if a retryable error occurs, we increment the retry time
                    # up to a max of 30 minutes
                    retry_time = max(1800, retry_time + sleep_time)
                    continue
                else:
                    raise
            except (ConnectionError, ProtocolError) as e:
                log.warning("Connection error: {e}".format(e=str(e)))
                log.info("Will retry in {d}s".format(d=retry_time))
                time.sleep(retry_time)
                # if a retryable error occurs, we increment the retry time
                # up to a max of 30 minutes
                retry_time = max(1800, retry_time + sleep_time)
                continue
            else:
                # if request succeeded, reset the retry_time
                auth_errors = 0
                retry_time = sleep_time
                run_time = time.time() - started_at
                job = ServiceJob.from_d(job_json)
                if external_job_id is None and job.external_job_id is not None:
                    external_job_id = job.external_job_id
                    log.info("Cromwell workflow ID is %s", external_job_id)
                if job.state in JobStates.ALL_COMPLETED or sleep_time == 0:
                    return job_json
                msg = "Running pipeline {n} (job {j}) state: {s} runtime:{r:.2f} sec {i} iteration".format(
                    n=job.name, j=job.id, s=job.state, r=run_time, i=i)
                if run_time % LOG_INTERVAL < sleep_time:
                    log.info(msg)
                else:
                    log.debug(msg)
                if time_out is not None:
                    if run_time > time_out:
                        raise JobExeError(
                            "Exceeded runtime {r} of {t}".format(
                                r=run_time, t=time_out))
                time.sleep(sleep_time)
                # after an hour we increase the wait
                if run_time > 3600:
                    sleep_time = min(SLEEP_TIME_MAX, sleep_time * 5)
    except KeyboardInterrupt:
        if abort_on_interrupt:
            client.terminate_job_id(job_id)
        raise


def run_args(args):
    d = poll_for_job_completion(
        args.job_id,
        args.host,
        args.port,
        args.user,
        args.password,
        time_out=args.max_time,
        sleep_time=args.poll_interval,
        retry_on=args.retry_on,
        abort_on_interrupt=False)
    job = ServiceJob.from_d(d)
    log.info(str(job))
    if args.json is not None:
        with open(args.json, "wt") as json_out:
            json_out.write(json.dumps(d))
            log.info("Wrote job JSON to {f}".format(f=args.json))
    if job.state in JobStates.ALL_FAILED:
        return 1
    return 0


def _get_parser():
    p = get_default_argparser_with_base_opts(
        description=__doc__,
        version=__version__,
        default_level="INFO")
    p.add_argument("job_id", help="SMRT Link Job ID (or UUID)")
    add_smrtlink_server_args(p)
    p.add_argument("--retry-on",
                   action="store",
                   type=lambda arg: [int(x) for x in arg.split(",")],
                   default=[],
                   help="HTTP error codes to retry")
    p.add_argument("--json",
                   action="store",
                   default=None,
                   help="Name of output file to write")
    p.add_argument("--max-time",
                   action="store",
                   type=int,
                   default=None,
                   help="Max time to wait before aborting")
    p.add_argument("--poll-interval",
                   action="store",
                   type=int,
                   default=60,
                   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.")
    return p


def main(argv=sys.argv):
    return pacbio_args_runner(
        argv=argv[1:],
        parser=_get_parser(),
        args_runner_func=run_args,
        alog=log,
        setup_log_func=setup_log)


if __name__ == "__main__":
    sys.exit(main(sys.argv))