Debian Codegraph @

pbcommand/services/_service_access_layer.py

raw symbols SCIP
1 """
2 Utils for Updating state/progress and results to WebServices
3 """
4
5 from .utils import to_sal_summary
6 from pbcommand.pb_io import load_report_from
7 from .models import (SMRTServiceBaseError,
8 JobResult, JobStates, JobExeError, JobTypes,
9 ServiceResourceTypes, ServiceJob, JobEntryPoint,
10 JobTask)
11 from pbcommand.utils import get_dataset_metadata
12 from pbcommand.models import (FileTypes,
13 DataSetFileType,
14 DataStore,
15 DataStoreFile)
16 import base64
17 import datetime
18 import json
19 import logging
20 import os
21 import pprint
22 import time
23 import warnings
24
25 import pytz
26 import requests
27 from requests import RequestException
28 from requests.exceptions import HTTPError, ConnectionError
29 from urllib3.exceptions import ProtocolError, InsecureRequestWarning # pylint: disable=import-error
30 # To disable the ssl cert check warning
31 import urllib3
32 urllib3.disable_warnings(InsecureRequestWarning) # pylint: disable=no-member
33
34
35 log = logging.getLogger(__name__)
36 logging.getLogger("requests").setLevel(logging.WARNING)
37 logging.getLogger("urllib3").setLevel(logging.WARNING)
38 # log.addHandler(logging.NullHandler()) # to prevent the annoying 'No
39 # handlers .. ' msg
40
41 # Everything else is considered a non-public
42 __all__ = [
43 'ServiceAccessLayer',
44 'SmrtLinkAuthClient',
45 ]
46
47
48 class Constants:
49 HEADERS = {
50 'Content-type': 'application/json',
51 'Accept-Encoding': 'gzip, deflate'
52 }
53
54
55 def __jsonable_request(request_method, headers):
56 def wrapper(url, d_):
57 data = json.dumps(d_)
58 # FIXME 'verify' should be passed in
59 return request_method(url, data=data, headers=headers, verify=False)
60 return wrapper
61
62
63 def _post_requests(headers):
64 return __jsonable_request(requests.post, headers)
65
66
67 def _put_requests(headers):
68 return __jsonable_request(requests.put, headers)
69
70
71 def _get_requests(headers):
72 def wrapper(url):
73 return requests.get(url, headers=headers, verify=False)
74 return wrapper
75
76
77 def _parse_base_service_error(response):
78 """:type response: requests.Response
79
80 Don't trust the services. Try to parse the response to SMRT Server Error
81 datastructure (even if a 200 is returned)
82 """
83 if response.ok:
84 try:
85 d = response.json()
86 emsg = SMRTServiceBaseError.from_d(d)
87 raise emsg
88 except (KeyError, TypeError):
89 # couldn't parse response -> error,
90 # so everything is fine
91 return response
92 else:
93 return response
94
95
96 def __get_headers(h):
97 if h is None:
98 return Constants.HEADERS
99 return h
100
101
102 def _process_rget(total_url, ignore_errors=False, headers=None):
103 """Process get request and return JSON response. Raise if not successful"""
104 r = _get_requests(__get_headers(headers))(total_url)
105 _parse_base_service_error(r)
106 if not r.ok and not ignore_errors:
107 log.warning(
108 "Failed ({s}) GET to {x}".format(
109 x=total_url,
110 s=r.status_code))
111 r.raise_for_status()
112 j = r.json()
113 return j
114
115
116 def _process_rget_or_empty(total_url, ignore_errors=False, headers=None):
117 """
118 Process get request and return JSON response if populated, otherwise None.
119 Raise if not successful
120 """
121 r = _get_requests(__get_headers(headers))(total_url)
122 if len(r.content) > 0:
123 _parse_base_service_error(r)
124 if not r.ok and not ignore_errors:
125 log.warning(
126 "Failed ({s}) GET to {x}".format(
127 x=total_url,
128 s=r.status_code))
129 r.raise_for_status()
130 if len(r.content) > 0:
131 object_d = r.json()
132 if len(object_d) > 0:
133 return object_d
134 return None
135
136
137 def _process_rget_with_transform(func, ignore_errors=False):
138 """Post process the JSON result (if successful) with F(json_d) -> T"""
139 def wrapper(total_url, headers=None):
140 j = _process_rget(
141 total_url,
142 ignore_errors=ignore_errors,
143 headers=headers)
144 return func(j)
145 return wrapper
146
147
148 def _process_rget_with_jobs_transform(
149 total_url, ignore_errors=False, headers=None):
150 # defining an internal method, because this used in several places
151 jobs_d = _process_rget(
152 total_url,
153 ignore_errors=ignore_errors,
154 headers=headers)
155 # Sort by Id desc so newer jobs show up first
156 jobs = [ServiceJob.from_d(job_d) for job_d in jobs_d]
157 return sorted(jobs, key=lambda x: x.id, reverse=True)
158
159
160 def _process_rget_or_none(func, ignore_errors=False):
161 """
162 apply the transform func to the output of GET request if it was successful, else returns None
163
164 This is intended to be used for looking up Results by Id where the a 404
165 is found.
166 """
167 def wrapper(total_url, headers):
168 try:
169 return _process_rget_with_transform(
170 func, ignore_errors)(total_url, headers)
171 except (RequestException, SMRTServiceBaseError):
172 # FIXME
173 # this should be a tighter exception case
174 # only look for 404
175 return None
176
177 return wrapper
178
179
180 def _process_rget_with_job_transform_or_none(total_url, headers=None):
181 return _process_rget_or_none(ServiceJob.from_d)(total_url, headers=headers)
182
183
184 def __process_creatable_to_json(f):
185 def wrapper(total_url, payload_d, headers):
186 r = f(__get_headers(headers))(total_url, payload_d)
187 _parse_base_service_error(r)
188 # FIXME This should be strict to only return a 201
189 if r.status_code not in (200, 201, 202, 204):
190 log.warning(
191 "Failed ({s} to call {u}".format(
192 u=total_url,
193 s=r.status_code))
194 log.warning("payload")
195 log.warning("\n" + pprint.pformat(payload_d))
196 r.raise_for_status()
197 j = r.json()
198 return j
199 return wrapper
200
201
202 _process_rpost = __process_creatable_to_json(_post_requests)
203 _process_rput = __process_creatable_to_json(_put_requests)
204
205
206 def _process_rpost_with_transform(func):
207 def wrapper(total_url, payload_d, headers=None):
208 j = _process_rpost(total_url, payload_d, headers)
209 return func(j)
210 return wrapper
211
212
213 def _process_rput_with_transform(func):
214 def wrapper(total_url, payload_d, headers=None):
215 j = _process_rput(total_url, payload_d, headers)
216 return func(j)
217 return wrapper
218
219
220 def _to_url(base, ext):
221 return "".join([base, ext])
222
223
224 def _null_func(x):
225 # Pass thorough func
226 return x
227
228
229 def _transform_job_tasks(j):
230 return [JobTask.from_d(d) for d in j]
231
232
233 def _get_job_by_id_or_raise(sal, job_id, error_klass,
234 error_messge_extras=None):
235 job = sal.get_job_by_id(job_id)
236
237 if job is None:
238 details = "" if error_messge_extras is None else error_messge_extras
239 base_msg = "Failed to find job {i}".format(i=job_id)
240 emsg = " ".join([base_msg, details])
241 raise error_klass(emsg)
242
243 return job
244
245
246 # FIXME this overlaps with job_poller.py, which is more fault-tolerant
247 def _block_for_job_to_complete(sal, job_id, time_out=1200, sleep_time=2,
248 abort_on_interrupt=True,
249 retry_on_failure=False):
250 """
251 Waits for job to complete
252
253 :param sal: ServiceAccessLayer
254 :param job_id: Job Id
255 :param time_out: Total runtime before aborting
256 :param sleep_time: polling interval (in sec)
257
258 :rtype: JobResult
259 :raises: KeyError if job is not initially found, or JobExeError
260 if the job fails during the polling process or times out
261 """
262
263 try:
264 external_job_id = None
265 time.sleep(sleep_time)
266 job = _get_job_by_id_or_raise(sal, job_id, KeyError)
267 log.info("SMRT Link job {i} ({u})".format(i=job.id, u=job.uuid))
268 log.debug("time_out = {t}".format(t=time_out))
269
270 error_msg = ""
271 job_result = JobResult(job, 0, error_msg)
272 started_at = time.time()
273
274 # number of polling steps
275 i = 0
276 while True:
277 run_time = time.time() - started_at
278 if external_job_id is None and job.external_job_id is not None:
279 external_job_id = job.external_job_id
280 log.info("Cromwell workflow ID is %s", external_job_id)
281
282 if job.state in JobStates.ALL_COMPLETED:
283 break
284
285 i += 1
286 time.sleep(sleep_time)
287
288 msg = "Running pipeline {n} (job {j}) state: {s} runtime:{r:.2f} sec {i} iteration".format(
289 n=job.name, j=job.id, s=job.state, r=run_time, i=i)
290 log.debug(msg)
291 # making the exceptions different to distinguish between an initial
292 # error and a "polling" error. Adding some msg details
293 # FIXME this should distinguish between failure modes - an HTTP 503
294 # or 401 is different from a 404 in this context
295 try:
296 job = _get_job_by_id_or_raise(
297 sal, job_id, JobExeError, error_messge_extras=msg)
298 except JobExeError as e:
299 if retry_on_failure:
300 log.warning(e)
301 log.warning("Polling job {i} failed".format(i=job_id))
302 continue
303 else:
304 raise
305
306 # FIXME, there's currently not a good way to get errors for jobs
307 job_result = JobResult(job, run_time, "")
308 if time_out is not None:
309 if run_time > time_out:
310 raise JobExeError(
311 "Exceeded runtime {r} of {t}. {m}".format(
312 r=run_time, t=time_out, m=msg))
313
314 return job_result
315 except KeyboardInterrupt:
316 if abort_on_interrupt:
317 sal.terminate_job_id(job_id)
318 raise
319
320
321 # Make this consistent somehow. Maybe defined 'shortname' in the core model?
322 # Martin is doing this for the XML file names
323 DATASET_METATYPES_TO_ENDPOINTS = {
324 FileTypes.DS_SUBREADS_H5.file_type_id: "hdfsubreads",
325 FileTypes.DS_SUBREADS.file_type_id: "subreads",
326 FileTypes.DS_ALIGN.file_type_id: "alignments",
327 FileTypes.DS_REF.file_type_id: "references",
328 FileTypes.DS_BARCODE.file_type_id: "barcodes",
329 FileTypes.DS_CCS.file_type_id: "ccsreads",
330 FileTypes.DS_CONTIG.file_type_id: "contigs",
331 FileTypes.DS_ALIGN_CCS.file_type_id: "cssalignments",
332 FileTypes.DS_GMAP_REF.file_type_id: "gmapreferences"}
333
334
335 def _get_endpoint_or_raise(ds_type):
336 if ds_type in DATASET_METATYPES_TO_ENDPOINTS:
337 return DATASET_METATYPES_TO_ENDPOINTS[ds_type]
338 raise KeyError("Unsupported datasettype {t}. Supported values {v}".format(
339 t=ds_type, v=list(DATASET_METATYPES_TO_ENDPOINTS.keys())))
340
341
342 def _job_id_or_error(job_or_error, custom_err_msg=None):
343 """
344 Extract job id from job creation service (by type)
345 or Raise exception from an EngineJob response
346
347 :raises: JobExeError
348 """
349 if isinstance(job_or_error, ServiceJob):
350 return job_or_error.id
351 else:
352 emsg = job_or_error.get('message', "Unknown")
353 if custom_err_msg is not None:
354 emsg += " {f}".format(f=custom_err_msg)
355 raise JobExeError(
356 "Failed to create job. {e}. Raw Response {x}".format(
357 e=emsg, x=job_or_error))
358
359
360 def _to_ds_file(d):
361 # is_chunk this isn't exposed at the service level
362 return DataStoreFile(d['uuid'], d['sourceId'], d['fileTypeId'], d['path'],
363 is_chunked=False, name=d.get("name", ""), description=d.get("description", ""))
364
365
366 def _to_datastore(dx):
367 # Friction to get around service endpoint not returning a list of files
368 ds_files = [_to_ds_file(d) for d in dx]
369 return DataStore(ds_files)
370
371
372 def _to_job_report_files(dx):
373 return [{u"reportTypeId": d["reportTypeId"],
374 u"dataStoreFile": _to_ds_file(d["dataStoreFile"])} for d in dx]
375
376
377 def _to_entry_points(d):
378 return [JobEntryPoint.from_d(i) for i in d]
379
380
381 def _get_all_report_attributes(
382 sal_get_reports_func, sal_get_reports_details_func, job_id):
383 """Util func for getting report Attributes
384
385 Note, this assumes that only one report type has been created. This is
386 probably not a great idea. Should re-evaluate this.
387 """
388 report_datafiles = sal_get_reports_func(job_id)
389 report_uuids = [list(r.values())[0].uuid for r in report_datafiles]
390 reports = [
391 sal_get_reports_details_func(
392 job_id,
393 r_uuid) for r_uuid in report_uuids]
394 all_report_attributes = {}
395
396 for r in reports:
397 for x in r['attributes']:
398 all_report_attributes[x['id']] = x['value']
399
400 return all_report_attributes
401
402
403 def _to_relative_tasks_url(job_type):
404 def wrapper(job_id_or_uuid):
405 return "/".join([ServiceAccessLayer.ROOT_JOBS,
406 job_type, str(job_id_or_uuid), "tasks"])
407 return wrapper
408
409
410 class ServiceAccessLayer: # pragma: no cover
411 """
412 General Client Access Layer for interfacing with the job types on
413 SMRT Link Analysis Services. This API only supports insecure (HTTP)
414 access to localhost.
415
416 As of 10-02-2018, this should only be used (minimally) for internal purposes. All
417 access to the Services should be done via SmrtLinkAuthClient.
418 """
419
420 ROOT_SL = "/smrt-link"
421 ROOT_JM = ROOT_SL + "/job-manager"
422 ROOT_JOBS = ROOT_JM + "/jobs"
423 ROOT_MJOBS = ROOT_JM + "/multi-jobs"
424 ROOT_RUNS = ROOT_SL + "/runs"
425 ROOT_SAMPLES = ROOT_SL + "/samples"
426 ROOT_DS = "/smrt-link/datasets"
427 ROOT_PT = '/smrt-link/resolved-pipeline-templates'
428
429 # in sec when blocking to run a job
430 JOB_DEFAULT_TIMEOUT = 60 * 30
431
432 def __init__(self, base_url, port, debug=False, sleep_time=2):
433 """
434
435 :param base_url: base url of the SL Server. This MUST be either 'localhost' or 'http://localhost'
436 :param port: port of the SL server
437 :param debug: set improved debugging output on Services request failures
438 :param sleep_time: sleep time (in seconds) between polling for job status
439 """
440 self.base_url = self._to_base_url(base_url)
441 self.port = port
442 # This will display verbose details with respect to the failed request
443 self.debug = debug
444 self._sleep_time = sleep_time
445
446 def _get_headers(self):
447 return Constants.HEADERS
448
449 def _to_base_url(self, h):
450 if h not in {"http://localhost", "localhost"}:
451 raise NotImplementedError(
452 "This API only supports HTTP connections to localhost")
453 prefix = "http://"
454 return h if h.startswith(prefix) else prefix + h
455
456 @property
457 def uri(self):
458 return "{b}:{u}".format(b=self.base_url, u=self.port)
459
460 def _to_url(self, rest):
461 return _to_url(self.uri, rest)
462
463 def __repr__(self):
464 return "<{k} {u} >".format(k=self.__class__.__name__, u=self.uri)
465
466 def to_summary(self):
467 """
468 Returns a summary of System status, DataSets, and Jobs in the system
469
470 :rtype: str
471 """
472 return to_sal_summary(self)
473
474 def get_status(self):
475 """Get status of the server
476
477 :rtype: dict
478 """
479 # This should be converted to a concrete typed object
480 return _process_rget(_to_url(self.uri, "/status"),
481 headers=self._get_headers())
482
483 def get_job_by_type_and_id(self, job_type, job_id):
484 return _process_rget_with_job_transform_or_none(_to_url(self.uri, "{p}/{t}/{i}".format(
485 i=job_id, t=job_type, p=ServiceAccessLayer.ROOT_JOBS)), headers=self._get_headers())
486
487 def get_job_by_id(self, job_id):
488 """Get a Job by int id"""
489 # FIXME. Make this an internal method It's ambiguous which job type
490 # type you're asking for
491 return _process_rget_with_job_transform_or_none(_to_url(
492 self.uri, "{r}/{i}".format(i=job_id, r=ServiceAccessLayer.ROOT_JOBS)), headers=self._get_headers())
493
494 def _get_job_resource_type(self, job_type, job_id, resource_type_id):
495 # grab the datastore or the reports
496 _d = dict(
497 t=job_type,
498 i=job_id,
499 r=resource_type_id,
500 p=ServiceAccessLayer.ROOT_JOBS)
501 return _process_rget_with_job_transform_or_none(
502 _to_url(self.uri, "{p}/{t}/{i}/{r}".format(**_d)), headers=self._get_headers())
503
504 def _get_job_resource_type_with_transform(
505 self, job_type, job_id, resource_type_id, transform_func):
506 _d = dict(
507 t=job_type,
508 i=job_id,
509 r=resource_type_id,
510 p=ServiceAccessLayer.ROOT_JOBS)
511 return _process_rget_with_transform(transform_func)(
512 _to_url(self.uri, "{p}/{t}/{i}/{r}".format(**_d)), headers=self._get_headers())
513
514 def _get_jobs_by_job_type(self, job_type, query=None):
515 base_url = "{p}/{t}".format(t=job_type, p=ServiceAccessLayer.ROOT_JOBS)
516 if query is not None:
517 base_url = "".join([base_url, "?", query])
518 return _process_rget_with_jobs_transform(_to_url(self.uri, base_url),
519 headers=self._get_headers())
520
521 def get_multi_analysis_jobs(self):
522 return _process_rget_with_jobs_transform(_to_url(self.uri, "{p}/{t}".format(
523 t="multi-analysis", p=ServiceAccessLayer.ROOT_MJOBS)), headers=self._get_headers())
524
525 def get_multi_analysis_job_by_id(self, int_or_uuid):
526 return _process_rget_with_job_transform_or_none(_to_url(self.uri, "{p}/{t}/{i}".format(
527 t="multi-analysis", p=ServiceAccessLayer.ROOT_MJOBS, i=int_or_uuid)), headers=self._get_headers())
528
529 def get_multi_analysis_job_children_by_id(self, multi_job_int_or_uuid):
530 return _process_rget_with_jobs_transform(
531 _to_url(self.uri,
532 "{p}/{t}/{i}/jobs".format(t="multi-analysis",
533 p=ServiceAccessLayer.ROOT_MJOBS,
534 i=multi_job_int_or_uuid)),
535 headers=self._get_headers())
536
537 def get_all_analysis_jobs(self):
538 return _process_rget_with_jobs_transform(
539 _to_url(self.uri, "{p}/analysis-jobs".format(
540 p=ServiceAccessLayer.ROOT_JM)),
541 headers=self._get_headers())
542
543 def get_analysis_jobs(self, query=None):
544 return self._get_jobs_by_job_type(JobTypes.ANALYSIS, query=query)
545
546 def get_cromwell_jobs(self, query=None):
547 """:rtype: list[ServiceJob]"""
548 return self._get_jobs_by_job_type(JobTypes.CROMWELL, query=query)
549
550 def get_import_dataset_jobs(self, query=None):
551 """:rtype: list[ServiceJob]"""
552 return self._get_jobs_by_job_type(JobTypes.IMPORT_DS, query=query)
553
554 def get_merge_dataset_jobs(self, query=None):
555 """:rtype: list[ServiceJob]"""
556 return self._get_jobs_by_job_type(JobTypes.MERGE_DS, query=query)
557
558 def get_fasta_convert_jobs(self, query=None):
559 """:rtype: list[ServiceJob]"""
560 self._get_jobs_by_job_type(JobTypes.CONVERT_FASTA, query=query)
561
562 def get_analysis_job_by_id(self, job_id):
563 """Get an Analysis job by id or UUID or return None
564
565 :rtype: ServiceJob
566 """
567 return self.get_job_by_type_and_id(JobTypes.ANALYSIS, job_id)
568
569 def get_import_job_by_id(self, job_id):
570 return self.get_job_by_type_and_id(JobTypes.IMPORT_DS, job_id)
571
572 def get_analysis_job_datastore(self, job_id):
573 """Get DataStore output from analysis job"""
574 # this doesn't work the list is sli
575 return self._get_job_resource_type_with_transform(
576 "analysis", job_id, ServiceResourceTypes.DATASTORE, _to_datastore)
577
578 def _to_dsf_id_url(self, job_id, dsf_uuid):
579 u = "/".join([ServiceAccessLayer.ROOT_JOBS, "analysis",
580 str(job_id), ServiceResourceTypes.DATASTORE, dsf_uuid])
581 return _to_url(self.uri, u)
582
583 def get_analysis_job_datastore_file(self, job_id, dsf_uuid):
584 return _process_rget_or_none(_to_ds_file)(
585 self._to_dsf_id_url(job_id, dsf_uuid), headers=self._get_headers())
586
587 def get_analysis_job_datastore_file_download(
588 self, job_id, dsf_uuid, output_file=None):
589 """
590 Download an DataStore file to an output file
591
592 :param job_id:
593 :param dsf_uuid:
594 :param output_file: if None, the file name from the server (content-disposition) will be used.
595 :return:
596 """
597 url = "{}/download".format(self._to_dsf_id_url(job_id, dsf_uuid))
598 dsf = self.get_analysis_job_datastore_file(job_id, dsf_uuid)
599
600 default_name = "download-job-{}-dsf-{}".format(job_id, dsf_uuid)
601
602 if dsf is not None:
603 r = requests.get(
604 url,
605 stream=True,
606 verify=False,
607 headers=self._get_headers())
608 if output_file is None:
609 try:
610 # 'attachment; filename="job-106-be2b5106-91dc-4ef9-b199-f1481f88b7e4-file-024.subreadset.xml'
611 raw_header = r.headers.get('content-disposition')
612 local_filename = raw_header.split(
613 "filename=")[-1].replace('"', '')
614 except (TypeError, IndexError, KeyError, AttributeError):
615 local_filename = default_name
616
617 else:
618 local_filename = output_file
619
620 with open(local_filename, 'wb') as f:
621 for chunk in r.iter_content(chunk_size=1024):
622 if chunk: # filter out keep-alive new chunks
623 f.write(chunk)
624 r.close()
625 return local_filename
626 else:
627 # This should probably return None to be consistent with the
628 # current API
629 raise KeyError(
630 "Unable to get DataStore file {} from Job {}".format(
631 dsf_uuid, job_id))
632
633 def get_analysis_job_reports(self, job_id):
634 """Get list of DataStore ReportFile types output from analysis job"""
635 return self._get_job_resource_type_with_transform(
636 JobTypes.ANALYSIS, job_id, ServiceResourceTypes.REPORTS, _to_job_report_files)
637
638 def get_analysis_job_reports_objs(self, job_id):
639 """
640 Get a List of Report Instances
641
642 :param job_id:
643 :rtype list[Report]
644 :return: List of Reports
645 """
646 job_reports = self.get_analysis_job_reports(job_id)
647 return [self.get_analysis_job_report_obj(
648 job_id, x['dataStoreFile'].uuid) for x in job_reports]
649
650 def __get_report_d(self, job_id, report_uuid, processor_func):
651 _d = dict(t=JobTypes.ANALYSIS, i=job_id, r=ServiceResourceTypes.REPORTS, p=ServiceAccessLayer.ROOT_JOBS,
652 u=report_uuid)
653 u = "{p}/{t}/{i}/{r}/{u}".format(**_d)
654 return _process_rget_or_none(processor_func)(
655 _to_url(self.uri, u), headers=self._get_headers())
656
657 def get_analysis_job_report_details(self, job_id, report_uuid):
658 return self.__get_report_d(job_id, report_uuid, lambda x: x)
659
660 def get_analysis_job_report_obj(self, job_id, report_uuid):
661 """
662 Fetch a SMRT Link Report Instance from a Job Id and Report UUID
663
664 There's inconsistencies in the API, hence the naming of the method is a bit verbose.
665 :rtype Report
666 """
667 return self.__get_report_d(job_id, report_uuid, load_report_from)
668
669 def get_analysis_job_report_attrs(self, job_id):
670 """Return a dict of all the Report Attributes"""
671 return _get_all_report_attributes(
672 self.get_analysis_job_reports, self.get_analysis_job_report_details, job_id)
673
674 def get_import_job_reports(self, job_id):
675 return self._get_job_resource_type_with_transform(
676 JobTypes.IMPORT_DS, job_id, ServiceResourceTypes.REPORTS, _to_job_report_files)
677
678 def get_import_job_report_details(self, job_id, report_uuid):
679 # It would have been better to return a Report instance, not raw json
680 _d = dict(
681 t=JobTypes.IMPORT_DS,
682 i=job_id,
683 r=ServiceResourceTypes.REPORTS,
684 p=ServiceAccessLayer.ROOT_JOBS,
685 u=report_uuid)
686 return _process_rget_or_none(lambda x: x)(_to_url(
687 self.uri, "{p}/{t}/{i}/{r}/{u}".format(**_d)), headers=self._get_headers())
688
689 def get_import_job_report_attrs(self, job_id):
690 """Return a dict of all the Report Attributes"""
691 return _get_all_report_attributes(
692 self.get_import_job_reports, self.get_import_job_report_details, job_id)
693
694 def get_analysis_job_entry_points(self, job_id):
695 return self._get_job_resource_type_with_transform(
696 JobTypes.ANALYSIS, job_id, ServiceResourceTypes.ENTRY_POINTS, _to_entry_points)
697
698 def get_import_dataset_job_datastore(self, job_id):
699 """Get a List of Service DataStore files from an import DataSet job"""
700 return self._get_job_resource_type(
701 JobTypes.IMPORT_DS, job_id, ServiceResourceTypes.DATASTORE)
702
703 def get_merge_dataset_job_datastore(self, job_id):
704 return self._get_job_resource_type(
705 JobTypes.MERGE_DS, job_id, ServiceResourceTypes.DATASTORE)
706
707 def import_dataset(self,
708 path,
709 avoid_duplicate_import=False):
710 # This returns a job resource
711 url = self._to_url(
712 "{p}/{x}".format(x=JobTypes.IMPORT_DS, p=ServiceAccessLayer.ROOT_JOBS))
713 d = {
714 "path": path,
715 "avoidDuplicateImport": avoid_duplicate_import
716 }
717 return _process_rpost_with_transform(
718 ServiceJob.from_d)(url, d, headers=self._get_headers())
719
720 def run_import_dataset(self,
721 path_to_xml,
722 avoid_duplicate_import=False):
723 job_or_error = self.import_dataset(
724 path_to_xml,
725 avoid_duplicate_import=avoid_duplicate_import)
726 custom_err_msg = "Import {p}".format(p=path_to_xml)
727 job_id = _job_id_or_error(job_or_error, custom_err_msg=custom_err_msg)
728 return _block_for_job_to_complete(
729 self, job_id, sleep_time=self._sleep_time)
730
731 def run_import_dataset_by_type(self, dataset_type, path_to_xml,
732 avoid_duplicate_import=False):
733 return self.run_import_dataset(path_to_xml, avoid_duplicate_import)
734
735 def _run_import_and_block(self, func, path, time_out=None):
736 # func while be self.import_dataset_X
737 job_or_error = func(path)
738 custom_err_msg = "Import {p}".format(p=path)
739 job_id = _job_id_or_error(job_or_error, custom_err_msg=custom_err_msg)
740 return _block_for_job_to_complete(self, job_id, time_out=time_out,
741 sleep_time=self._sleep_time)
742
743 def import_dataset_subread(self, path):
744 log.warn("DEPRECATED METHOD")
745 return self.import_dataset(path)
746
747 def run_import_dataset_subread(self, path, time_out=10):
748 return self._run_import_and_block(
749 self.import_dataset_subread, path, time_out=time_out)
750
751 def import_dataset_hdfsubread(self, path):
752 log.warn("DEPRECATED METHOD")
753 return self.import_dataset(path)
754
755 def run_import_dataset_hdfsubread(self, path, time_out=10):
756 return self._run_import_and_block(
757 self.import_dataset_hdfsubread, path, time_out=time_out)
758
759 def import_dataset_reference(self, path):
760 log.warn("DEPRECATED METHOD")
761 return self.import_dataset(path)
762
763 def run_import_dataset_reference(self, path, time_out=10):
764 return self._run_import_and_block(
765 self.import_dataset_reference, path, time_out=time_out)
766
767 def import_dataset_barcode(self, path):
768 log.warn("DEPRECATED METHOD")
769 return self.import_dataset(path)
770
771 def run_import_dataset_barcode(self, path, time_out=10):
772 return self._run_import_and_block(
773 self.import_dataset_barcode, path, time_out=time_out)
774
775 def run_import_local_dataset(self, path, avoid_duplicate_import=False):
776 """Import a file from FS that is local to where the services are running
777
778 Returns a JobResult instance
779
780 :rtype: JobResult
781 """
782 dsmd = get_dataset_metadata(path)
783 result = self.search_dataset_by_uuid(dsmd.uuid)
784
785 if result is None:
786 log.info("Importing dataset {p}".format(p=path))
787 job_result = self.run_import_dataset_by_type(
788 dsmd.metatype,
789 path,
790 avoid_duplicate_import=avoid_duplicate_import)
791 log.info("Confirming database update")
792 # validation 1: attempt to retrieve dataset info
793 result_new = self.get_dataset_by_uuid(dsmd.uuid)
794 if result_new is None:
795 raise JobExeError(("Dataset {u} was imported but could " +
796 "not be retrieved; this may indicate " +
797 "XML schema errors.").format(u=dsmd.uuid))
798 return job_result
799 else:
800 log.info(f"Already imported: {result}")
801 # need to clean this up
802 return JobResult(self.get_job_by_id(result['jobId']), 0, "")
803
804 def get_dataset_children_jobs(self, dataset_id):
805 """
806 Get a List of Children Jobs for the DataSet
807
808 :param dataset_id: DataSet Int or UUID
809 :type dataset_id: int | string
810 :rtype list[ServiceJob]
811 """
812 return _process_rget_with_jobs_transform(
813 _to_url(self.uri, "{t}/datasets/{i}/jobs".format(t=ServiceAccessLayer.ROOT_SL, i=dataset_id)), headers=self._get_headers())
814
815 def get_job_types(self):
816 u = _to_url(
817 self.uri, "{}/{}".format(ServiceAccessLayer.ROOT_JM, "job-types"))
818 return _process_rget(u, headers=self._get_headers())
819
820 def get_dataset_types(self):
821 """Get a List of DataSet Types"""
822 u = _to_url(self.uri,
823 "{}/{}".format(ServiceAccessLayer.ROOT_SL,
824 "dataset-types"))
825 return _process_rget(u, headers=self._get_headers())
826
827 def get_dataset_by_uuid(self, int_or_uuid, ignore_errors=False):
828 """The recommend model is to look up DataSet type by explicit MetaType
829
830 Returns None if the dataset was not found
831 """
832 return _process_rget_or_none(_null_func, ignore_errors=ignore_errors)(
833 _to_url(self.uri, "{p}/{i}".format(i=int_or_uuid,
834 p=ServiceAccessLayer.ROOT_DS)),
835 headers=self._get_headers())
836
837 def search_dataset_by_uuid(self, uuid):
838 """
839 Better alternative to get_dataset_by_uuid, that does not trigger a 404
840 """
841 return _process_rget_or_empty(
842 _to_url(self.uri, f"{ServiceAccessLayer.ROOT_DS}/search/{uuid}"),
843 headers=self._get_headers())
844
845 def get_dataset_by_id(self, dataset_type, int_or_uuid):
846 """Get a Dataset using the DataSetMetaType and (int|uuid) of the dataset"""
847 ds_endpoint = _get_endpoint_or_raise(dataset_type)
848 return _process_rget(_to_url(self.uri, "{p}/{t}/{i}".format(
849 t=ds_endpoint, i=int_or_uuid, p=ServiceAccessLayer.ROOT_DS)), headers=self._get_headers())
850
851 def _get_dataset_details_by_id(self, dataset_type, int_or_uuid):
852 """
853 Get a Dataset Details (XML converted to JSON via webservices
854 using the DataSetMetaType and (int|uuid) of the dataset
855 """
856 # FIXME There's some inconsistencies in the interfaces with regards to
857 # returning None or raising
858 ds_endpoint = _get_endpoint_or_raise(dataset_type)
859 return _process_rget(_to_url(self.uri, "{p}/{t}/{i}/details".format(
860 t=ds_endpoint, i=int_or_uuid, p=ServiceAccessLayer.ROOT_DS)), headers=self._get_headers())
861
862 def _get_datasets_by_type(self, dstype):
863 return _process_rget(_to_url(self.uri, "{p}/{i}".format(
864 i=dstype, p=ServiceAccessLayer.ROOT_DS)), headers=self._get_headers())
865
866 def get_subreadset_by_id(self, int_or_uuid):
867 return self.get_dataset_by_id(FileTypes.DS_SUBREADS, int_or_uuid)
868
869 def get_subreadset_details_by_id(self, int_or_uuid):
870 return self._get_dataset_details_by_id(
871 FileTypes.DS_SUBREADS, int_or_uuid)
872
873 def get_subreadsets(self):
874 return self._get_datasets_by_type("subreads")
875
876 def get_hdfsubreadset_by_id(self, int_or_uuid):
877 return self.get_dataset_by_id(FileTypes.DS_SUBREADS_H5, int_or_uuid)
878
879 def get_hdfsubreadset_details_by_id(self, int_or_uuid):
880 return self._get_dataset_details_by_id(
881 FileTypes.DS_SUBREADS_H5, int_or_uuid)
882
883 def get_hdfsubreadsets(self):
884 return self._get_datasets_by_type("hdfsubreads")
885
886 def get_referenceset_by_id(self, int_or_uuid):
887 return self.get_dataset_by_id(FileTypes.DS_REF, int_or_uuid)
888
889 def get_referenceset_details_by_id(self, int_or_uuid):
890 return self._get_dataset_details_by_id(FileTypes.DS_REF, int_or_uuid)
891
892 def get_referencesets(self):
893 return self._get_datasets_by_type("references")
894
895 def get_barcodeset_by_id(self, int_or_uuid):
896 return self.get_dataset_by_id(FileTypes.DS_BARCODE, int_or_uuid)
897
898 def get_barcodeset_details_by_id(self, int_or_uuid):
899 return self._get_dataset_details_by_id(
900 FileTypes.DS_BARCODE, int_or_uuid)
901
902 def get_barcodesets(self):
903 return self._get_datasets_by_type("barcodes")
904
905 def get_alignmentset_by_id(self, int_or_uuid):
906 return self.get_dataset_by_id(FileTypes.DS_ALIGN, int_or_uuid)
907
908 def get_alignmentset_details_by_id(self, int_or_uuid):
909 return self._get_dataset_details_by_id(FileTypes.DS_ALIGN, int_or_uuid)
910
911 def get_ccsreadset_by_id(self, int_or_uuid):
912 return self.get_dataset_by_id(FileTypes.DS_CCS, int_or_uuid)
913
914 def get_ccsreadset_details_by_id(self, int_or_uuid):
915 return self._get_dataset_details_by_id(FileTypes.DS_CCS, int_or_uuid)
916
917 def get_ccsreadsets(self):
918 return self._get_datasets_by_type("ccsreads")
919
920 def get_alignmentsets(self):
921 return self._get_datasets_by_type("alignments")
922
923 def import_fasta(self, fasta_path, name, organism, ploidy):
924 """Convert fasta file to a ReferenceSet and Import. Returns a Job """
925 d = dict(path=fasta_path,
926 name=name,
927 organism=organism,
928 ploidy=ploidy)
929 return _process_rpost_with_transform(ServiceJob.from_d)(self._to_url(
930 "{p}/{t}".format(p=ServiceAccessLayer.ROOT_JOBS, t=JobTypes.CONVERT_FASTA)), d, headers=self._get_headers())
931
932 def run_import_fasta(self, fasta_path, name, organism,
933 ploidy, time_out=JOB_DEFAULT_TIMEOUT):
934 """Import a Reference into a Block"""""
935 job_or_error = self.import_fasta(fasta_path, name, organism, ploidy)
936 _d = dict(f=fasta_path, n=name, o=organism, p=ploidy)
937 custom_err_msg = "Fasta-convert path:{f} name:{n} organism:{o} ploidy:{p}".format(
938 **_d)
939 job_id = _job_id_or_error(job_or_error, custom_err_msg=custom_err_msg)
940 return _block_for_job_to_complete(self, job_id, time_out=time_out,
941 sleep_time=self._sleep_time)
942
943 def create_logger_resource(self, idx, name, description):
944 _d = dict(id=idx, name=name, description=description)
945 return _process_rpost(
946 _to_url(self.uri, "/smrt-base/loggers"), _d, headers=self._get_headers())
947
948 def log_progress_update(self, job_type_id, job_id,
949 message, level, source_id):
950 """This is the generic job logging mechanism"""
951 _d = dict(message=message, level=level, sourceId=source_id)
952 return _process_rpost(_to_url(self.uri, "{p}/{t}/{i}/log".format(
953 t=job_type_id, i=job_id, p=ServiceAccessLayer.ROOT_JOBS)), _d, headers=self._get_headers())
954
955 def get_pipeline_template_by_id(self, pipeline_template_id):
956 return _process_rget(_to_url(self.uri, "{p}/{i}".format(
957 i=pipeline_template_id, p=ServiceAccessLayer.ROOT_PT)), headers=self._get_headers())
958
959 def get_pipeline_presets(self):
960 return _process_rget(_to_url(self.uri, "/smrt-link/workflow-presets"),
961 headers=self._get_headers())
962
963 def get_pipeline_preset(self, preset_id):
964 presets = self.get_pipeline_presets()
965 by_id = {p["presetId"]: p for p in presets}
966 by_shortid = {p["presetId"].split(".")[-1]: p for p in presets}
967 by_name = {p["name"]: p for p in presets}
968 return by_id.get(preset_id,
969 by_name.get(preset_id,
970 by_shortid.get(preset_id, None)))
971
972 def create_by_pipeline_template_id(self, *args, **kwds):
973 return self.create_analysis_job(*args, **kwds)
974
975 def create_analysis_job(self,
976 name,
977 pipeline_id,
978 epoints,
979 task_options=(),
980 workflow_options=(),
981 tags=(),
982 preset_id=None,
983 description=None,
984 project_id=1):
985 """Creates and runs an analysis workflow by workflow ID
986
987 :param tags: Tags should be a set of strings
988 """
989 if pipeline_id.startswith("pbsmrtpipe"):
990 raise NotImplementedError("pbsmrtpipe is no longer supported")
991
992 # sanity checking to see if pipeline is valid
993 _ = self.get_pipeline_template_by_id(pipeline_id)
994
995 service_eps = [dict(entryId=e.entry_id,
996 fileTypeId=e.dataset_type,
997 datasetId=e.resource) for e in epoints]
998
999 def _to_o(opt_id, opt_value, option_type_id):
1000 return dict(optionId=opt_id,
1001 value=opt_value,
1002 optionTypeId=option_type_id)
1003
1004 task_options = list(task_options)
1005 d = dict(name=name,
1006 pipelineId=pipeline_id,
1007 entryPoints=service_eps,
1008 taskOptions=task_options,
1009 workflowOptions=workflow_options,
1010 projectId=project_id)
1011 if description:
1012 d["description"] = description
1013 if preset_id:
1014 preset = self.get_pipeline_preset(preset_id)
1015 if preset is None:
1016 raise KeyError(f"Can't find a compute config for '{preset_id}'")
1017 d["presetId"] = preset["presetId"]
1018
1019 # Only add the request if the non empty.
1020 if tags:
1021 tags_str = ",".join(list(tags))
1022 d['tags'] = tags_str
1023 job_type = JobTypes.ANALYSIS
1024 path = "{r}/{p}".format(p=job_type, r=ServiceAccessLayer.ROOT_JOBS)
1025 raw_d = _process_rpost(_to_url(self.uri, path),
1026 d,
1027 headers=self._get_headers())
1028 return ServiceJob.from_d(raw_d)
1029
1030 def run_by_pipeline_template_id(self, *args, **kwds):
1031 return self.run_analysis_job(*args, **kwds)
1032
1033 def run_analysis_job(self,
1034 name,
1035 pipeline_id,
1036 epoints,
1037 task_options=(),
1038 workflow_options=(),
1039 time_out=JOB_DEFAULT_TIMEOUT,
1040 tags=(),
1041 abort_on_interrupt=True,
1042 retry_on_failure=False):
1043 """Blocks and runs a job with a timeout"""
1044
1045 job_or_error = self.create_analysis_job(
1046 name,
1047 pipeline_id,
1048 epoints,
1049 task_options=task_options,
1050 workflow_options=workflow_options,
1051 tags=tags)
1052
1053 _d = dict(name=name, p=pipeline_id, eps=epoints)
1054 custom_err_msg = "Job {n} args: {a}".format(n=name, a=_d)
1055
1056 job_id = _job_id_or_error(job_or_error, custom_err_msg=custom_err_msg)
1057 return _block_for_job_to_complete(self,
1058 job_id,
1059 time_out=time_out,
1060 sleep_time=self._sleep_time,
1061 abort_on_interrupt=abort_on_interrupt,
1062 retry_on_failure=retry_on_failure)
1063
1064 def run_cromwell_workflow(self,
1065 name,
1066 workflow_source,
1067 inputs_json,
1068 engine_options,
1069 dependencies_zip,
1070 time_out=JOB_DEFAULT_TIMEOUT,
1071 tags=(),
1072 abort_on_interrupt=True):
1073 d = dict(
1074 name=name,
1075 workflowSource=workflow_source,
1076 inputsJson=inputs_json,
1077 engineOptions=engine_options,
1078 dependenciesZip=dependencies_zip)
1079 if tags:
1080 tags_str = ",".join(list(tags))
1081 d['tags'] = tags_str
1082 raw_d = _process_rpost(_to_url(self.uri,
1083 "{r}/{p}".format(p=JobTypes.CROMWELL,
1084 r=ServiceAccessLayer.ROOT_JOBS)),
1085 d,
1086 headers=self._get_headers())
1087 job = ServiceJob.from_d(raw_d)
1088 return _block_for_job_to_complete(self, job.id, time_out=time_out,
1089 sleep_time=self._sleep_time,
1090 abort_on_interrupt=abort_on_interrupt)
1091
1092 def terminate_job(self, job):
1093 """
1094 POST a terminate request appropriate to the job type. Currently only
1095 supported for cromwell, and analysis job types.
1096 """
1097 log.warn("Terminating job {i} ({u})".format(i=job.id, u=job.uuid))
1098 if job.external_job_id is not None:
1099 log.warn("Will abort Cromwell workflow %s", job.external_job_id)
1100 return _process_rpost(
1101 _to_url(self.uri, "{r}/{p}/{i}/terminate".format(
1102 p=job.job_type,
1103 r=ServiceAccessLayer.ROOT_JOBS,
1104 i=job.id)),
1105 {},
1106 headers=self._get_headers())
1107
1108 def terminate_job_id(self, job_id):
1109 job = _get_job_by_id_or_raise(self, job_id, KeyError)
1110 return self.terminate_job(job)
1111
1112 def resume_job(self,
1113 job_id,
1114 time_out=JOB_DEFAULT_TIMEOUT,
1115 abort_on_interrupt=True):
1116 job = _get_job_by_id_or_raise(self, job_id, KeyError)
1117 if job.state in JobStates.ALL_COMPLETED:
1118 return JobResult(job, 0, "")
1119 return _block_for_job_to_complete(self, job.id, time_out=time_out,
1120 sleep_time=self._sleep_time,
1121 abort_on_interrupt=abort_on_interrupt)
1122
1123 def get_analysis_job_tasks(self, job_id_or_uuid):
1124 """Get all the Task associated with a Job by UUID or Int Id"""
1125 job_url = self._to_url(
1126 _to_relative_tasks_url(
1127 JobTypes.ANALYSIS)(job_id_or_uuid))
1128 return _process_rget_with_transform(_transform_job_tasks)(
1129 job_url, headers=self._get_headers())
1130
1131 def get_import_job_tasks(self, job_id_or_uuid):
1132 # this is more for testing purposes
1133 job_url = self._to_url(
1134 _to_relative_tasks_url(
1135 JobTypes.IMPORT_DS)(job_id_or_uuid))
1136 return _process_rget_with_transform(_transform_job_tasks)(
1137 job_url, headers=self._get_headers())
1138
1139 def get_manifests(self):
1140 u = self._to_url("{}/manifests".format(ServiceAccessLayer.ROOT_SL))
1141 return _process_rget_with_transform(
1142 _null_func)(u, headers=self._get_headers())
1143
1144 def get_manifest_by_id(self, ix):
1145 u = self._to_url(
1146 "{}/manifests/{}".format(ServiceAccessLayer.ROOT_SL, ix))
1147 return _process_rget_or_none(_null_func)(
1148 u, headers=self._get_headers())
1149
1150 def get_runs(self):
1151 u = self._to_url("{}".format(ServiceAccessLayer.ROOT_RUNS))
1152 return _process_rget_with_transform(
1153 _null_func)(u, headers=self._get_headers())
1154
1155 def get_run_details(self, run_uuid):
1156 u = self._to_url(
1157 "{}/{}".format(ServiceAccessLayer.ROOT_RUNS, run_uuid))
1158 return _process_rget_or_none(_null_func)(
1159 u, headers=self._get_headers())
1160
1161 def get_run_collections(self, run_uuid):
1162 u = self._to_url(
1163 "{}/{}/collections".format(ServiceAccessLayer.ROOT_RUNS, run_uuid))
1164 return _process_rget_with_transform(
1165 _null_func)(u, headers=self._get_headers())
1166
1167 def get_run_collection(self, run_uuid, collection_uuid):
1168 u = self._to_url(
1169 "{}/{}/collections/{}".format(ServiceAccessLayer.ROOT_RUNS, run_uuid, collection_uuid))
1170 return _process_rget_or_none(_null_func)(
1171 u, headers=self._get_headers())
1172
1173 def get_samples(self):
1174 u = self._to_url("{}/samples".format(ServiceAccessLayer.ROOT_SL, ))
1175 return _process_rget_with_transform(
1176 _null_func)(u, headers=self._get_headers())
1177
1178 def get_sample_by_id(self, sample_uuid):
1179 u = self._to_url(
1180 "{}/samples/{}".format(ServiceAccessLayer.ROOT_SL, sample_uuid))
1181 return _process_rget_or_none(_null_func)(
1182 u, headers=self._get_headers())
1183
1184 def submit_multi_job(self, job_options):
1185 u = self._to_url(
1186 "{}/multi-analysis".format(ServiceAccessLayer.ROOT_MJOBS))
1187 return _process_rpost_with_transform(ServiceJob.from_d)(
1188 u, job_options, headers=self._get_headers())
1189
1190 def get_sl_api(self, path):
1191 service_url = f"{self.uri}{path}"
1192 t1 = time.time()
1193 r = requests.get(service_url, headers=self._get_headers(), verify=False)
1194 t2 = time.time()
1195 log.info("Response time: {:.1f}s".format(t2 - t1))
1196 r.raise_for_status()
1197 return r.json()
1198
1199
1200 # -----------------------------------------------------------------------
1201 # SSL stuff
1202 class Wso2Constants: # pragma: no cover
1203 SECRET = "KMLz5g7fbmx8RVFKKdu0NOrJic4a"
1204 CONSUMER_KEY = "6NjRXBcFfLZOwHc0Xlidiz4ywcsa"
1205 SCOPES = ["welcome", "run-design", "run-qc", "openid", "analysis",
1206 "sample-setup", "data-management", "userinfo"]
1207
1208
1209 def _create_auth(secret, consumer_key): # pragma: no cover
1210 return base64.b64encode(":".join([secret, consumer_key]).encode("utf-8"))
1211
1212
1213 def get_token(url, user, password, scopes, secret, consumer_key): # pragma: no cover
1214 basic_auth = _create_auth(secret, consumer_key).decode("utf-8")
1215 # To be explicit for pedagogical purposes
1216 headers = {
1217 "Authorization": "Basic {}".format(basic_auth),
1218 "Content-Type": "application/x-www-form-urlencoded"
1219 }
1220
1221 scope_str = " ".join({s for s in scopes})
1222 payload = dict(grant_type="password",
1223 username=user,
1224 password=password,
1225 scope=scope_str)
1226
1227 # verify is false to disable the SSL cert verification
1228 return requests.post(url, payload, headers=headers, verify=False)
1229
1230
1231 def _get_smrtlink_wso2_token(user, password, url): # pragma: no cover
1232 r = get_token(
1233 url,
1234 user,
1235 password,
1236 Wso2Constants.SCOPES,
1237 Wso2Constants.SECRET,
1238 Wso2Constants.CONSUMER_KEY)
1239 j = r.json()
1240 access_token = j['access_token']
1241 refresh_token = j['refresh_token']
1242 scopes = j['scope'].split(" ")
1243 return access_token, refresh_token, scopes
1244
1245
1246 class SmrtLinkAuthClient(ServiceAccessLayer): # pragma: no cover
1247 """
1248 HTTPS-enabled client that routes via WSO2 and requires authentication.
1249 For internal use only - this is NOT an officially supported API. Currently
1250 somewhat sloppy w.r.t. SSL security features.
1251 """
1252
1253 def __init__(self, base_url, user, password, port=8243, debug=False,
1254 sleep_time=2, token=None):
1255 super().__init__(
1256 base_url,
1257 port,
1258 debug=debug,
1259 sleep_time=sleep_time)
1260 self._user = user
1261 self._password = password
1262
1263 if token is None:
1264 if (user is None or password is None):
1265 raise ValueError(
1266 "Both user and password must be defined unless an existing auth token is supplied")
1267 self._login()
1268 else:
1269 # assume token is valid. This will fail on the first client request
1270 # if not valid with an obvious error message
1271 self.auth_token = token
1272 self.refresh_token = None
1273
1274 def _login(self):
1275 url = "{u}:{p}/token".format(u=self.base_url, p=self.port)
1276 self.auth_token, self.refresh_token, _ = _get_smrtlink_wso2_token(
1277 self._user, self._password, url)
1278
1279 def _get_headers(self):
1280 return {
1281 "Authorization": "Bearer {}".format(self.auth_token),
1282 "Content-type": "application/json",
1283 "X-User-ID": self._user
1284 }
1285
1286 def _to_base_url(self, h):
1287 if h.startswith("http://"):
1288 raise ValueError("Invalid URL - this client requires HTTPS")
1289 prefix = "https://"
1290 return h if h.startswith(prefix) else prefix + h
1291
1292 @property
1293 def uri(self):
1294 return "{b}:{u}/SMRTLink/1.0.0".format(b=self.base_url, u=self.port)
1295
1296 def reauthenticate_if_necessary(self):
1297 """
1298 Check whether the client still has authorization to access the /status
1299 endpoint, and acquire a new auth token if not.
1300 """
1301 try:
1302 status = self.get_status()
1303 except requests.exceptions.HTTPError as e:
1304 if e.response.status_code == 401:
1305 self._login()
1306 else:
1307 raise e
1308
1309
1310 def get_smrtlink_client(host, port, user=None, password=None, sleep_time=5): # pragma: no cover
1311 """
1312 Convenience method for use in CLI testing tools. Returns an instance of
1313 the appropriate client class given the input parameters. Unlike the client
1314 itself this hardcodes 8243 as the WSO2 port number.
1315 """
1316 if host != "localhost" or None not in [user, password]:
1317 return SmrtLinkAuthClient(host, user, password, sleep_time=sleep_time)
1318 else:
1319 return ServiceAccessLayer(host, port, sleep_time=sleep_time)
1320
1321
1322 def get_smrtlink_client_from_args(args):
1323 return get_smrtlink_client(
1324 host=args.host,
1325 port=args.port,
1326 user=args.user,
1327 password=args.password)
1328
1329
1330 def run_client_with_retry(fx, host, port, user, password,
1331 sleep_time=60,
1332 retry_on=(500, 503)):
1333 """
1334 Obtain a services client and run the specified function on it - this can
1335 be essentially any services call - and return the result. If the query
1336 fails due to 401 Unauthorized, the call will be retried with a new token.
1337 HTTP 500 and 503 errors will be retried without re-authenticating.
1338 """
1339 def _get_client():
1340 return get_smrtlink_client(host, port, user, password)
1341 auth_errors = 0
1342 started_at = time.time()
1343 retry_time = sleep_time
1344 client = _get_client()
1345 while True:
1346 try:
1347 result = fx(client)
1348 except HTTPError as e:
1349 status = e.response.status_code
1350 log.info("Got error {e} (code = {c})".format(e=str(e), c=status))
1351 if status == 401:
1352 auth_errors += 1
1353 if auth_errors > 10:
1354 raise RuntimeError(
1355 "10 successive HTTP 401 errors, exiting")
1356 log.warning("Authentication error, will retry with new token")
1357 client = _get_client()
1358 continue
1359 elif status in retry_on:
1360 log.warning("Got HTTP {c}, will retry in {d}s".format(
1361 c=status, d=retry_time))
1362 time.sleep(retry_time)
1363 # if a retryable error occurs, we increment the retry time
1364 # up to a max of 30 minutes
1365 retry_time = max(1800, retry_time + sleep_time)
1366 continue
1367 else:
1368 raise
1369 except (ConnectionError, ProtocolError) as e:
1370 log.warning("Connection error: {e}".format(e=str(e)))
1371 log.info("Will retry in {d}s".format(d=retry_time))
1372 time.sleep(retry_time)
1373 # if a retryable error occurs, we increment the retry time
1374 # up to a max of 30 minutes
1375 retry_time = max(1800, retry_time + sleep_time)
1376 continue
1377 else:
1378 return result