Debian Codegraph @

pbcommand/services/smrtlink_client.py

raw symbols SCIP
1 #!/usr/bin/env python3
2
3 # Copyright (c) 2023, Pacific Biosciences of California, Inc.
4 ##
5 # All rights reserved.
6 ##
7 # Redistribution and use in source and binary forms, with or without
8 # modification, are permitted provided that the following conditions are met:
9 # * Redistributions of source code must retain the above copyright
10 # notice, this list of conditions and the following disclaimer.
11 # * Redistributions in binary form must reproduce the above copyright
12 # notice, this list of conditions and the following disclaimer in the
13 # documentation and/or other materials provided with the distribution.
14 # * Neither the name of Pacific Biosciences nor the names of its
15 # contributors may be used to endorse or promote products derived from
16 # this software without specific prior written permission.
17 ##
18 # NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY
19 # THIS LICENSE. THIS SOFTWARE IS PROVIDED BY PACIFIC BIOSCIENCES AND ITS
20 # CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
21 # NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
22 # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL PACIFIC BIOSCIENCES OR
23 # ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
26 # OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
27 # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
28 # OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
29 # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31 """
32 SMRT Link REST API reference client implementation, for version 12.0.0
33 or newer. This is written to be self-contained without any
34 dependencies on internal PacBio libraries, and can be copied, modified, and
35 redistributed without limitation (see module comments for license terms).
36
37 The SmrtLinkClient does not cover the entire API, but the code is intended to
38 be easily extended and translated into other languages. For simplicity and
39 readability, the returned objects are weakly typed lists
40 and dicts containing basic Python types (str, int, float, bool, None).
41 The Swagger documentation in the SMRT Link GUI online help
42 (https://servername:8243/sl/docs/services) provides a comprehensive listing
43 of endpoints and data models.
44
45 Software requirements: Python >= 3.9; 'requests' module
46
47 Example module usage:
48
49 - Creating a client object, including authentication::
50
51 client = SmrtLinkClient.connect("localhost", user="pbuser", password="XXX")
52
53 - Get all analysis jobs associated with a run::
54
55 run = client.get_run(run_uuid)
56 collections = client.get_run_collections(run_uuid)
57 jobs = []
58 for collection in collections:
59 jobs.extend(client.get_dataset_jobs(collection["ccsId"]))
60
61 - Import a HiFi dataset XML, and fetch a list of all datasets that were
62 loaded (including any demultiplexed children)::
63
64 import_job = client.create_import_dataset_job(xml_file)
65 finished_job = client.poll_for_successful_job(import_job["id"])
66 datasets = client.get_consensusreadsets(jobId=import_job["id"])
67
68 - Retrieve barcoded sample metrics for a run collection and dump to CSV::
69
70 reports = client.get_run_collection_reports(run_uuid, collection_uuid)
71 for r in reports:
72 if r["reportTypeId"].split(".")[-1] == "report_barcode":
73 report_uuid = r["dataStoreFile"]["uuid"]
74 report = client.load_datastore_report_file(report_uuid)
75 bc_table = report["tables"][0]
76 headers = [c["header"] for c in bc_table["columns"]]
77 col_data = [c["values"] for c in bc_table["columns"]]
78 table_rows = [[c[i] for c in col_data] for i in len(col_data[0])]
79 write_csv(csv_file_name, headers, table_rows)
80
81 - Retrieve loading metrics for a run collection and return as a dict::
82
83 reports = client.get_run_collection_reports(run_uuid, collection_uuid)
84 for r in reports:
85 if "loading" in r["reportTypeId"]:
86 report_uuid = r["dataStoreFile"]["uuid"]
87 report = client.load_datastore_report_file(report_uuid)
88 print({attr["id"]:attr["value"] for attr in report["attributes"]})
89
90 - Combine a sample split across multiple cells:
91
92 DS_TYPE = "PacBio.DataSet.ConsensusReadSet"
93 datasets = client.get_consensusreadsets(bioSampleName="MySample1234")
94 job = client.create_merge_datasets_job([d["uuid"] for d in datasets])
95 job = client.poll_for_successful_job(job["id"])
96 datastore = client.get_job_datastore(job["id"])
97 merged_datasets = [f for f in datastore if f["fileTypeId"] == DS_TYPE]
98 # alternately:
99 merged_datasets = client.get_consensusreadsets(jobId=job["id"])
100
101 - Find the Run QC reports associated with an analysis job::
102
103 entry_points = client.get_job_entry_points(job_id)
104 movie_names = set([])
105 for entry_point in entry_points:
106 if entry_point["datasetType"] == "PacBio.DataSet.ConsensusReadSet":
107 dataset = client.get_consensusreadset(entry_point["datasetUUID"])
108 movie_names.append(dataset["metadataContextId"])
109 qc_reports = []
110 for movie_name in movie_names:
111 runs = client.get_runs(movieName=movie_name)
112 if len(runs) == 1:
113 collections = client.get_run_collection(runs[0]["unique_id"])
114 for collection in collections:
115 if collection["context"] == movie_name:
116 reports = client.get_collection_reports(run_id,
117 collection["unique_id"])
118 qc_reports.append(reports)
119
120 - Poll every 10 minutes until a collection is complete, then launch a HiFi
121 Mapping job using the official PacBio hg38 reference, and poll until it
122 completes successfully::
123
124 collection = client.get_run_collection(run_id, collection_id)
125 while True:
126 dataset = client.get_dataset_search(collection["ccsId"])
127 if dataset:
128 break
129 else:
130 time.sleep(600)
131 job = client.create_analysis_job({
132 "name": "My Mapping Job",
133 "pipelineId": "cromwell.workflows.pb_align_ccs",
134 "entryPoints": [
135 {
136 "entryId": "eid_ccs",
137 "datasetId": collection["ccsId"],
138 "fileTypeId": "PacBio.DataSet.ConsensusReadSet"
139 },
140 {
141 "entryId": "eid_ref_dataset",
142 "datasetId": "ba3866bf-2aba-7c99-0570-0d6709174e4a",
143 "fileTypeId": "PacBio.DataSet.ReferenceSet"
144 }
145 ],
146 "taskOptions": [],
147 "workflowOptions": []
148 })
149 job = client.poll_for_successful_job(job["id"])
150 """
151
152 from abc import ABC, abstractmethod
153 import urllib.parse
154 import argparse
155 import logging
156 import json
157 import time
158 import os
159 import sys
160
161 # This is the only non-standard dependency
162 import requests
163
164 __all__ = [
165 "SmrtLinkClient",
166 "add_smrtlink_server_args",
167 "get_smrtlink_client_from_args",
168 ]
169
170 log = logging.getLogger(__name__)
171
172
173 class Constants:
174 API_PORT = 8243
175 H_CT_AUTH = "application/x-www-form-urlencoded"
176 H_CT_JSON = "application/json"
177 # SSL is good and we should not disable it by default
178 DEFAULT_VERIFY = True
179
180
181 def refresh_on_401(f):
182 """
183 Method decorator to trigger a token refresh when an HTTP 401 error is
184 received.
185 """
186
187 def wrapper(self, *args, **kwds):
188 try:
189 return f(self, *args, **kwds)
190 except requests.exceptions.HTTPError as e:
191 if e.response.status_code == 401:
192 self.refresh()
193 return f(self, *args, **kwds)
194 else:
195 raise
196 return wrapper
197
198
199 def _disable_insecure_warning():
200 """
201 Workaround to silence SSL warnings when the invoker has explicitly
202 requested insecure mode.
203 """
204 from urllib3.exceptions import ProtocolError, InsecureRequestWarning # pylint: disable=import-error
205 # To disable the ssl cert check warning
206 import urllib3
207 import warnings
208 warnings.warn("You are running with some SSL security features disabled (verify=False). Please note that this is considered risky and exposes you to remote attacks that can steal your authorization credentials or sensitive data.", InsecureRequestWarning)
209 urllib3.disable_warnings(
210 InsecureRequestWarning) # pylint: disable=no-member
211
212
213 class RESTClient(ABC):
214 """
215 Base class for interacting with any REST API that communicates primarily
216 in JSON.
217 """
218 PROTOCOL = "http"
219
220 def __init__(self, host, port, verify=Constants.DEFAULT_VERIFY):
221 self.host = host
222 self.port = port
223 self._verify = verify
224
225 @abstractmethod
226 def refresh(self):
227 ...
228
229 @property
230 def headers(self):
231 return {"Content-Type": Constants.H_CT_JSON}
232
233 @property
234 def base_url(self):
235 return f"{self.PROTOCOL}://{self.host}:{self.port}"
236
237 def to_url(self, path):
238 """Convert an API method path to the full server URL"""
239 return f"{self.base_url}{path}"
240
241 def _get_headers(self, other_headers={}):
242 headers = dict(self.headers)
243 if other_headers:
244 headers.update(other_headers)
245 return headers
246
247 @refresh_on_401
248 def _http_get(self, path, params=None, headers={}):
249 if isinstance(params, dict):
250 if len(params) == 0:
251 params = None
252 else:
253 # get rid of queryParam=None elements
254 params = {k: v for k, v in params.items() if v is not None}
255 url = self.to_url(path)
256 log.info(f"Method: GET {path}")
257 log.debug(f"Full URL: {url}")
258 response = requests.get(url,
259 params=params,
260 headers=self._get_headers(headers),
261 verify=self._verify)
262 log.debug(response)
263 response.raise_for_status()
264 return response
265
266 @refresh_on_401
267 def _http_post(self, path, data, headers={}):
268 url = self.to_url(path)
269 log.info(f"Method: POST {path} {data}")
270 log.debug(f"Full URL: {url}")
271 response = requests.post(url,
272 data=json.dumps(data),
273 headers=self._get_headers(headers),
274 verify=self._verify)
275 log.debug(response)
276 response.raise_for_status()
277 return response
278
279 @refresh_on_401
280 def _http_put(self, path, data, headers={}):
281 url = self.to_url(path)
282 log.info(f"Method: PUT {path} {data}")
283 log.debug(f"Full URL: {url}")
284 response = requests.put(url,
285 data=json.dumps(data),
286 headers=self._get_headers(headers),
287 verify=self._verify)
288 log.debug(response)
289 response.raise_for_status()
290 return response
291
292 @refresh_on_401
293 def _http_delete(self, path, headers={}):
294 url = self.to_url(path)
295 log.info(f"Method: DELETE {path}")
296 log.debug(f"Full URL: {url}")
297 response = requests.delete(url,
298 headers=self._get_headers(headers),
299 verify=self._verify)
300 log.debug(response)
301 response.raise_for_status()
302 return response
303
304 @refresh_on_401
305 def _http_options(self, path, headers={}):
306 url = self.to_url(path)
307 log.info(f"Method: OPTIONS {url}")
308 log.debug(f"Full URL: {url}")
309 response = requests.options(url,
310 headers=self._get_headers(headers),
311 verify=self._verify)
312 log.debug(response)
313 response.raise_for_status()
314 return response
315
316 def get(self, path, params=None, headers={}):
317 """Generic JSON GET method handler"""
318 return self._http_get(path, params, headers).json()
319
320 def post(self, path, data, headers={}):
321 """Generic JSON POST method handler"""
322 return self._http_post(path, data, headers).json()
323
324 def put(self, path, data, headers={}):
325 """Generic JSON PUT method handler"""
326 return self._http_put(path, data, headers).json()
327
328 def delete(self, path, headers={}):
329 """Generic JSON DELETE method handler"""
330 return self._http_delete(path, headers).json()
331
332 def options(self, path, headers={}):
333 """
334 OPTIONS handler, used only for getting CORS settings in ReactJS.
335 Since the response body is empty, the return value is the response
336 headers (as a dict).
337 """
338 return self._http_options(path, headers).headers()
339
340 def execute_call(self, method, path, data, headers):
341 """Execute any supported JSON-returning HTTP call by name"""
342 if method == "GET":
343 return self.get(path, headers=headers)
344 elif method == "POST":
345 return self.post(path, data=data, headers=headers)
346 elif method == "PUT":
347 return self.put(path, data=data, headers=headers)
348 elif method == "DELETE":
349 return self.get(path, headers=headers)
350 elif method == "OPTIONS":
351 return self.options(path, headers=headers)
352 else:
353 raise ValueError(f"Method '{method}' not supported")
354
355
356 class AuthenticatedClient(RESTClient):
357 """
358 Base class for REST clients that require authorization via the Oauth2
359 token interface.
360 """
361
362 def __init__(self, host, port, username, password,
363 verify=Constants.DEFAULT_VERIFY):
364 super(AuthenticatedClient, self).__init__(host, port, verify)
365 self._user = username
366 self._oauth2 = self.get_authorization_token(username, password)
367
368 @property
369 def auth_token(self):
370 return self._oauth2["access_token"]
371
372 @property
373 def refresh_token(self):
374 return self._oauth2["refresh_token"]
375
376 @property
377 def headers(self):
378 """Dict of default HTTP headers for all endpoints"""
379 return {
380 "Content-Type": Constants.H_CT_JSON,
381 "Authorization": f"Bearer {self.auth_token}"
382 }
383
384 @abstractmethod
385 def get_authorization_token(self, username, password):
386 ...
387
388
389 class SmrtLinkClient(AuthenticatedClient):
390 """
391 Class for executing methods on the secure (authenticated) SMRT Link REST
392 API, via API gateway
393 """
394 PROTOCOL = "https"
395 JOBS_PATH = "/smrt-link/job-manager/jobs"
396
397 def __init__(self, *args, **kwds):
398 if not kwds.get("verify", Constants.DEFAULT_VERIFY):
399 _disable_insecure_warning()
400 super(SmrtLinkClient, self).__init__(*args, **kwds)
401
402 @staticmethod
403 def connect(host, username, password, verify=Constants.DEFAULT_VERIFY):
404 """
405 Convenience method for instantiating a client using the default
406 API port 8243
407 """
408 return SmrtLinkClient(host=host,
409 port=Constants.API_PORT,
410 username=username,
411 password=password,
412 verify=verify)
413
414 @property
415 def headers(self):
416 return {
417 "Content-Type": Constants.H_CT_JSON,
418 "Authorization": f"Bearer {self.auth_token}",
419 "X-User-ID": self._user
420 }
421
422 def to_url(self, path):
423 return f"{self.base_url}/SMRTLink/2.0.0{path}"
424
425 def get_authorization_token(self, username, password):
426 """
427 Request an Oauth2 authorization token from the SMRT Link API
428 server, which is actually a proxy to Keycloak. This token will
429 enable access to all API methods that are allowed for the role of
430 the authorized user.
431 """
432 auth_d = dict(username=username,
433 password=password,
434 grant_type="password")
435 resp = requests.post(f"{self.base_url}/token",
436 data=auth_d,
437 headers={"Content-Type": Constants.H_CT_AUTH},
438 verify=self._verify)
439 resp.raise_for_status()
440 t = resp.json()
441 log.info("Access token: {}...".format(t["access_token"][0:40]))
442 log.debug("Access token: {}".format(t["access_token"]))
443 return t
444
445 def refresh(self):
446 """
447 Attempt to refresh the authorization token, using the refresh token
448 obtained in a previous request.
449 """
450 log.info("Requesting new access token using refresh token")
451 auth_d = dict(grant_type="refresh_token",
452 refresh_token=self.refresh_token)
453 resp = requests.post(self.to_url("/token"),
454 data=auth_d,
455 headers={"Content-Type": Constants.H_CT_AUTH},
456 verify=self._verify)
457 resp.raise_for_status()
458 t = resp.json()
459 log.info("Access token: {}...".format(t["access_token"][0:40]))
460 log.debug("Access token: {}".format(t["access_token"]))
461 self._oauth2 = t
462 return t
463
464 # -----------------------------------------------------------------
465 # ADMINISTRATION
466 def get_status(self):
467 """Get status of server backend"""
468 return self.get("/status")
469
470 def set_system_config_param(self, key, value):
471 """
472 Set a SMRT Link system configuration parameter, such as the
473 instrument user password
474 """
475 body = dict(key=key, value=value)
476 return self.post("/smrt-link/admin-config", body)
477
478 def get_swagger_api(self):
479 """Fetch the Swagger API definition for the server"""
480 return self.get("/smrt-link/swagger")
481
482 def get_software_manifests(self):
483 """Get a list of software components and versions"""
484 return self.get("/smrt-link/manifests")
485
486 def get_software_manifest(self, component_id):
487 """Retrieve version information for a specific component"""
488 return self.get(f"/smrt-link/manifests/{component_id}")
489
490 def get_instrument_connections(self):
491 """
492 Get a list of Revio instrument connections.
493 """
494 return self.get("/smrt-link/instrument-config/connections")
495
496 def create_instrument_connection(self,
497 host,
498 secret_key,
499 name="Revio Instrument"):
500 """
501 Create a new Revio instrument connection in SMRT Link. The server
502 will automatically perform a full handshake and configure ICS.
503 """
504 body = {
505 "host": host,
506 "serial": "unknown", # NOTE the server gets this from ICS
507 "name": name,
508 "credentials": secret_key
509 }
510 return self.post("/smrt-link/instrument-config/connections", body)
511
512 def update_instrument_connection(self, instrument_id, update_d):
513 """Update an existing Revio instrument connection"""
514 path = f"/smrt-link/instrument-config/connections/{instrument_id}"
515 return self.put(path, update_d)
516
517 def connect_instrument(self, instrument_id):
518 """Activate an existing Revio instrument connection"""
519 return self.update_instrument_connection(instrument_id,
520 dict(isConnected=True))
521
522 def delete_instrument_connection(self, id_name_or_serial):
523 """Delete an instrument connection record"""
524 return self.delete(f"/smrt-link/instrument-config/connections/{id_name_or_serial}")
525
526 def get_instrument_states(self):
527 """
528 Return a list of instrument states, complex objects that include
529 configuration details and run progress. Connected instruments should
530 send state updates once per minute.
531 """
532 return self.get("/smrt-link/instruments")
533
534 def get_instrument_state(self, serial):
535 """
536 Return the last recorded state for a specific instrument by serial
537 number.
538 """
539 return self.get(f"/smrt-link/instruments/{serial}")
540
541 def delete_instrument_state(self, serial):
542 """
543 Remove an instrument from the Instruments status page in SMRT Link (but
544 not from the Instrument Settings page)
545 """
546 return self.delete(f"/smrt-link/instruments/{serial}")
547
548 # -----------------------------------------------------------------
549 # RUNS
550 def get_runs(self, **search_params):
551 """
552 Get a list of all PacBio instrument runs, with optional search
553 parameters.
554
555 Partial list of supported search parameters:
556 name (partial matches supported)
557 reserved (boolean, true means selected on instrument)
558 instrumentType (Revio, Sequel2e, or Sequel2)
559 chipType (8mChip or 25mChip)
560 collectionUuid (retrieve the run for a specific collection)
561 movieName
562 """
563 return self.get("/smrt-link/runs", dict(search_params))
564
565 def get_run(self, run_id):
566 """Retrieve a PacBio instrument run description by UUID"""
567 return self.get(f"/smrt-link/runs/{run_id}")
568
569 def get_run_xml(self, run_id):
570 """
571 Retrieve the XML data model for a PacBio instrument run
572 """
573 return self._http_get(f"/smrt-link/runs/{run_id}/datamodel").text
574
575 def get_run_collections(self, run_id):
576 """Retrieve a list of collections/samples for a run"""
577 return self.get(f"/smrt-link/runs/{run_id}/collections")
578
579 def get_run_collection(self, run_id, collection_id):
580 """Retrieve metadata for a single collection in a run"""
581 return self.get(f"/smrt-link/runs/{run_id}/collections/{collection_id}")
582
583 def get_run_from_collection_id(self, collection_id):
584 """
585 Convenience method wrapping get_runs(), for retrieving a run based
586 on collection UUID alone. Returns None if no matching run is found.
587 """
588 runs = self.get_runs(collectionUuid=collection_id)
589 return None if len(runs) == 0 else runs[0]
590
591 def get_run_collection_reports(self, run_id, collection_id):
592 """
593 Get all reports associated with a run collection
594 Introduced in SMRT Link 13.0
595 """
596 return self.get(f"/smrt-link/runs/{run_id}/collections/{collection_id}/reports")
597
598 def get_run_collection_barcodes(self, run_id, collection_id):
599 """Get a list of barcoded samples associated with a run collection"""
600 return self.get(f"/smrt-link/runs/{run_id}/collections/{collection_id}/barcodes")
601
602 def get_run_collection_hifi_reads(self, run_id, collection_id):
603 """
604 Retrieve the HiFi dataset that is the primary output of a PacBio
605 instrument run.
606 """
607 collection = self.get_run_collection(run_id, collection_id)
608 return self.get_consensusreadset(collection["ccsId"])
609
610 def get_run_collection_hifi_reads_barcoded_datasets(self,
611 run_id,
612 collection_id,
613 barcode_name=None,
614 biosample_name=None):
615 """
616 Retrieve the demultiplexed "child" datasets for a PacBio instrument
617 run, optionally filtering by barcode name (e.g. 'bc2001--bc2001') or
618 biosample name.
619 """
620 collection = self.get_run_collection(run_id, collection_id)
621 return self.get_barcoded_child_datasets(collection["ccsId"],
622 barcode_name=barcode_name,
623 biosample_name=biosample_name)
624
625 def get_run_reports(self, run_id):
626 """
627 Get all collection-level reports associated with a run.
628 Introduced in SMRT Link 13.0
629 """
630 return self.get(f"/smrt-link/runs/{run_id}/reports")
631
632 def get_run_design(self, run_id):
633 """Return the run design JSON object used by the SMRT Link GUI"""
634 return self.get(f"/smrt-link/run-design/{run_id}")
635
636 def import_run_design_csv(self, csv_file):
637 """
638 Import a Run CSV definition and return the run-design data model.
639 This is the officially supported interface for creating a Run Design
640 programatically.
641 """
642 csv_d = {"content": open(csv_file, "rt").read()}
643 return self.post("/smrt-link/import-run-design", csv_d)
644
645 def delete_run(self, run_id):
646 """Delete a PacBio run description by UUID"""
647 return self.delete(f"/smrt-link/runs/{run_id}")
648
649 def import_run_xml(self, xml_file):
650 """
651 Post a Run XML directly to the API. This is not officially supported
652 as an integration mechanism, but is useful for transferring Run QC
653 results between servers.
654 """
655 return self.post("/smrt-link/runs", {"dataModel": open(xml_file).read()})
656
657 def update_run_xml(self, xml_file, run_id, is_reserved=None):
658 """
659 Update a Run data model XML. This endpoint is what the Revio and Sequel
660 II/IIe instruments use to communicate run progress, and to mark a run
661 as "reserved" by a particular instrument. It can be used as a workaround
662 for updating the status of incomplete runs after manual XML edits.
663 """
664 opts_d = {"dataModel": open(xml_file).read()}
665 if is_reserved is not None:
666 opts_d["reserved"] = is_reserved
667 return self.post(f"/smrt-link/runs/{run_id}", opts_d)
668
669 # -----------------------------------------------------------------
670 # CHEMISTRY BUNDLE
671 def get_active_bundle_metadata(self, bundle_type):
672 """
673 Return the metadata for the current version of a bundle
674 """
675 return self.get(f"/smrt-link/bundles/{bundle_type}/active")
676
677 def get_chemistry_bundle_metadata(self):
678 """
679 Return the metadata for the current version of the chemistry-pb
680 bundle used by Sample Setup, Run Design, and the instrument software
681 """
682 return self.get_active_bundle_metadata("chemistry-pb")
683
684 def get_active_bundle_file(self, bundle_type, relative_path):
685 """
686 Retrieve the contents of a file in a bundle
687 """
688 relpath = urllib.parse.quote(relative_path)
689 path = f"/smrt-link/bundles/{bundle_type}/active/files/{relpath}"
690 return self._http_get(path).text
691
692 def get_chemistry_bundle_file(self, relative_path):
693 """
694 Retrieve the contents of a file in the chemistry bundle. The list
695 of consumables is in 'definitions/PacBioAutomationConstraints.xml';
696 settings for Run Design applications are in 'RunDesignDefaults.json'.
697 """
698 return self.get_active_bundle_file("chemistry-pb", relative_path)
699
700 # -----------------------------------------------------------------
701 # MISC SERVICES
702 def download_datastore_file(self, file_uuid):
703 path = f"/smrt-link/datastore-files/{file_uuid}/download"
704 return self._http_get(path).content
705
706 def load_datastore_report_file(self, file_uuid):
707 """
708 Convenience wrapper for downloading a datastore report.json file in
709 memory and and converting to Python objects.
710 """
711 return json.loads(self.download_datastore_file(file_uuid))
712
713 def download_file_resource(self, file_uuid, resource_name):
714 """
715 Retrieve another file (usually a PNG file) referenced by a datastore
716 file (usually a Report) and return the raw data
717 """
718 path = f"/smrt-link/datastore-files/{file_uuid}/resources"
719 return self._http_get(path, params={"relpath": resource_name}).content
720
721 # -----------------------------------------------------------------
722 # DATASETS
723 def _get_datasets_by_type(self, dataset_type, **query_args):
724 return self.get(f"/smrt-link/datasets/{dataset_type}",
725 params=dict(query_args))
726
727 def _get_dataset_by_type_and_id(self, dataset_type, dataset_id):
728 return self.get(f"/smrt-link/datasets/{dataset_type}/{dataset_id}")
729
730 def _get_dataset_resources_by_type_and_id(self, dataset_type, dataset_id, resource_type):
731 return self.get(f"/smrt-link/datasets/{dataset_type}/{dataset_id}/{resource_type}")
732
733 def get_consensusreadsets(self, **query_args):
734 """
735 Retrieve a list of HiFi datasets, with optional search parameters.
736 Partial list of supported search terms:
737 name
738 bioSampleName
739 wellSampleName
740 metadataContextId (movie name)
741 String searches are always case-insensitive.
742 Most of the non-timestamp string fields in the data model are
743 searchable with partial strings by adding the prefix 'like:' to the
744 search term, thus:
745 client.get_consensusreadsets(bioSampleName="like:HG002")
746 The refixes 'not:' (inequality), 'unlike:', 'start:', and 'end:' are
747 also recognized. For numerical fields, 'not:', 'lt:', 'lte:', 'gt:',
748 'gte:' are supported, plus 'range:{start},{end}'.
749 """
750 return self._get_datasets_by_type("ccsreads", **query_args)
751
752 def get_consensusreadsets_by_movie(self, movie_name):
753 """
754 Retrieve a list of HiFi datasets for a unique movie name (AKA
755 'context' or 'metadataContextId'), such as 'm84001_230601_123456'
756 """
757 return self.get_consensusreadsets(metadataContextId=movie_name)
758
759 def get_barcoded_child_datasets(self,
760 parent_dataset_id,
761 barcode_name=None,
762 biosample_name=None):
763 """Get a list of demultiplexed children (if any) of a HiFi dataset"""
764 return self.get_consensusreadsets(parentUuid=parent_dataset_id,
765 dnaBarcodeName=barcode_name,
766 bioSampleName=biosample_name)
767
768 def get_subreadsets(self, **query_args):
769 """
770 Retrieve a list of CLR/subread datasets, with optional search
771 parameters. (DEPRECATED)
772 """
773 return self._get_datasets_by_type("subreads", **query_args)
774
775 def get_referencesets(self, **query_args):
776 """Get a list of ReferenceSet datasets"""
777 return self._get_datasets_by_type("references", **query_args)
778
779 def get_barcodesets(self, **query_args):
780 """Get a list of BarcodeSet datasets (including MAS-Seq adapters and Iso-Seq primers)"""
781 return self._get_datasets_by_type("barcodes", **query_args)
782
783 def get_consensusreadset(self, dataset_id):
784 """Get a HiFi dataset by UUID or integer ID"""
785 return self._get_dataset_by_type_and_id("ccsreads", dataset_id)
786
787 def get_subreadset(self, dataset_id):
788 """Get a CLR (subread) dataset by UUID or integer ID (DEPRECATED)"""
789 return self._get_dataset_by_type_and_id("subreads", dataset_id)
790
791 def get_referenceset(self, dataset_id):
792 """GET /smrt-link/datasets/references/{dataset_id}"""
793 return self._get_dataset_by_type_and_id("references", dataset_id)
794
795 def get_barcodeset(self, dataset_id):
796 """GET /smrt-link/datasets/barcodes/{dataset_id}"""
797 return self._get_dataset_by_type_and_id("barcodes", dataset_id)
798
799 def get_consensusreadset_reports(self, dataset_id):
800 """Get a list of reports associated with a HiFi dataset"""
801 return self._get_dataset_resources_by_type_and_id("ccsreads", dataset_id, "reports")
802
803 def get_barcodeset_contents(self, dataset_id):
804 """
805 Retrieve the entire contents of a BarcodeSet dataset, as a
806 raw FASTA string (not JSON!)
807 """
808 path = f"/smrt-link/datasets/barcodes/{dataset_id}/contents"
809 return self._http_get(path).text
810
811 def get_barcodeset_record_names(self, dataset_id):
812 """Retrieve a list of barcode/primer/adapter names in a BarcodeSet"""
813 return self._get_dataset_resources_by_type_and_id("barcodes", dataset_id, "record-names")
814
815 def get_dataset_metadata(self, dataset_id):
816 """Retrieve a type-independent dataset metadata object"""
817 return self._get_dataset_by_type_and_id("meta", dataset_id)
818
819 def get_dataset_jobs(self, dataset_id):
820 """Get a list of analysis jobs that used the specified dataset as input"""
821 return self._get_dataset_resources_by_type_and_id("meta", dataset_id, "jobs")
822
823 def get_dataset_search(self, dataset_id):
824 """
825 Retrieve a single dataset if it is present in the database, or None
826 if it is missing, without triggering an HTTP 404 error in the latter
827 case.
828 """
829 result_d = self.get(f"/smrt-link/datasets/search/{dataset_id}")
830 if not result_d: # empty dict is the "not found" response
831 return None
832 return result_d
833
834 # -----------------------------------------------------------------
835 # JOBS
836 def _get_jobs_by_type(self, job_type, params=None):
837 return self.get(f"{self.JOBS_PATH}/{job_type}", params=params)
838
839 def _post_job_by_type(self, job_type, opts_d):
840 return self.post(f"{self.JOBS_PATH}/{job_type}", opts_d)
841
842 def _get_job_by_type_and_id(self, job_type, job_id):
843 return self.get(f"{self.JOBS_PATH}/{job_type}/{job_id}")
844
845 def _get_job_resources_by_type_and_id(self, job_type, job_id, resource_type):
846 return self.get(f"{self.JOBS_PATH}/{job_type}/{job_id}/{resource_type}")
847
848 def _get_job_resource_by_type_and_id(self, job_type, job_id, resource_type, resource_id):
849 return self.get(f"{self.JOBS_PATH}/{job_type}/{job_id}/{resource_type}/{resource_id}")
850
851 # NOTE our API routing is deliberately very permissive due to
852 # limitations of the underlying toolkits, so we often use the
853 # 'analysis' endpoints for GETting individual job attributes,
854 # regardless of job type
855 def get_job(self, job_id):
856 """
857 Retrieve a job of any type by integer ID or UUID.
858 """
859 return self._get_job_by_type_and_id("analysis", job_id)
860
861 def get_job_reports(self, job_id):
862 """
863 Get a list of reports generated by a job. The UUIDs of these
864 objects can be used to retrieve the full report content using
865 get_job_report()
866 """
867 return self._get_job_resources_by_type_and_id("analysis", job_id,
868 "reports")
869
870 def get_job_report(self, job_id, report_uuid):
871 """
872 Retrieve the Report data for a specific report output by a job.
873 """
874 return self._get_job_resource_by_type_and_id("analysis", job_id,
875 "reports", report_uuid)
876
877 def download_job_report_resource(self, job_id, report_uuid, resource_name):
878 """
879 Retrieve a plot (usually a PNG file) referenced by a Report object,
880 and return the raw image data
881 """
882 path = f"{self.JOBS_PATH}/analysis/{job_id}/reports/{report_uuid}/resources"
883 return self._http_get(path, params={"relpath": resource_name}).content
884
885 def get_job_datastore(self, job_id):
886 """
887 Get a list of all exposed output files generated by a job
888 """
889 return self._get_job_resources_by_type_and_id("analysis", job_id,
890 "datastore")
891
892 def get_job_entry_points(self, job_id):
893 """Get the dataset UUIDs used to create the job"""
894 return self._get_job_resources_by_type_and_id("analysis", job_id,
895 "entry-points")
896
897 def get_job_datasets(self, job_id):
898 """Alias for get_job_entry_points(job_id)"""
899 return self.get_job_entry_points(job_id)
900
901 def get_job_options(self, job_id):
902 """Get the options model used to create the job"""
903 return self._get_job_resources_by_type_and_id("analysis", job_id,
904 "options")
905
906 def download_job_datastore_file(self, job_id, file_id):
907 """
908 Get the raw content for a specific file in the job datastore. Note
909 that this is effectively redundant with download_datastore_file.
910 """
911 path = f"{self.JOBS_PATH}/analysis/{job_id}/datastore/{file_id}/download"
912 return self._http_get(path).content
913
914 def get_analysis_jobs(self, **search_params):
915 """
916 Get a list of standalone analysis jobs, with optional search/filter
917 parameters. This is equivalent to the "flat view" in the SMRT Analysis
918 job catalog.
919 """
920 return self._get_jobs_by_type("analysis", search_params)
921
922 def get_analysis_jobs_by_state(self, state):
923 """
924 Get a list of analysis jobs in a specified state. Supported states:
925 CREATED SUBMITTED RUNNING SUCCESSFUL FAILED TERMINATED ABORTED
926 """
927 return self.get_analysis_jobs(state=state)
928
929 def get_analysis_jobs_by_parent(self, multi_job_id):
930 """
931 Get all children of the multi-analysis job whose ID is specified
932 """
933 return self.get_analysis_jobs(parentMultiJobId=multi_job_id)
934
935 def get_smrt_analysis_nested_jobs(self, **search_params):
936 """
937 Get the 'nested' view of analysis jobs displayed by default in the
938 SMRT Analysis jobs catalog, where children of a multi-analysis job are
939 hidden at the top level
940 """
941 return self.get("/smrt-link/job-manager/analysis-jobs",
942 params=search_params)
943
944 def create_analysis_job(self, opts_d):
945 """
946 Submit a SMRT Analysis job to be run as soon as possible. Requires
947 that all input datasets have already been imported.
948
949 Job options schema:
950 pipelineId: string such as 'cromwell.workflows.pb_align_ccs'
951 name: job name string
952 entryPoints: list of dataset entry points
953 taskOptions: list of workflow task options
954 projectId: int or null
955 presetId: string or null
956
957 Entry point model:
958 entryId: pre-set identifier, can be any of 'eid_ccs',
959 'eid_barcode', 'eid_ref_dataset', 'eid_barcode_2',
960 or 'eid_subread'
961 fileTypeId: dataset MetaType, from the top-level XML tag
962 datasetId: dataset UniqueID (UUID)
963
964 Task/workflow option model:
965 optionId: string ID such as 'mapping_min_length'
966 value: string, float, int, bool, or occasionally null
967 optionTypeId: type of 'value' field
968 """
969 # NOTE workflowOptions is still technically required by the REST API
970 # but will become optional in future releases
971 if "workflowOptions" not in opts_d:
972 opts_d["workflowOptions"] = []
973 return self._post_job_by_type("analysis", opts_d)
974
975 def terminate_analysis_job(self, job_id):
976 """Immediately terminate a running analysis job."""
977 return self.post(f"{self.JOBS_PATH}/analysis/{job_id}/terminate", {})
978
979 def get_import_dataset_jobs(self, **search_params):
980 """Get a list of import-dataset jobs"""
981 return self._get_jobs_by_type("import-dataset", search_params)
982
983 def _post_job_with_path_opt(self, job_type, opts_d_or_path, key="path"):
984 opts_d = opts_d_or_path
985 if isinstance(opts_d_or_path, str):
986 opts_d = {key: opts_d_or_path}
987 return self._post_job_by_type(job_type, opts_d)
988
989 def create_import_dataset_job(self, opts_d_or_path):
990 """
991 Submit an import-dataset job, using the path to the dataset XML.
992
993 :param opts_d_or_path: either a dictionary containing at least the
994 'path' field, or an actual path string
995 """
996 return self._post_job_with_path_opt("import-dataset", opts_d_or_path)
997
998 def create_import_datasets_zip_job(self, opts_d):
999 """
1000 Submit an import-datasets-zip job, using the path to the zipfile
1001 exported by another SMRT Link server.
1002
1003 :param opts_d: a dictionary containing at least the 'zipFile' field
1004 """
1005 return self._post_job_by_type("import-datasets-zip", opts_d)
1006
1007 def create_import_collection_job(self, opts_d_or_path):
1008 """
1009 Submit an import-collection job, using the path to the instrument file
1010 moviename.reports.zip. In SMRT Link Lite this is used to populate the
1011 Run QC and Data Management pages, without direct access to the XML
1012 files.
1013
1014 :param opts_d_or_path: either a dictionary containing at least the
1015 'path' field, or an actual path string
1016 """
1017 return self._post_job_with_path_opt("import-collection", opts_d_or_path)
1018
1019 def create_merge_datasets_job(self, opts_d_or_dataset_ids):
1020 """
1021 Submit a merge-datasets job, using two or more unique IDs for
1022 ConsensusReadSet datasets.
1023
1024 :param opts_d_or_dataset_ids: either a dictionary containing at least
1025 the 'ids' field, or a list of integers
1026 or UUID strings
1027 """
1028 opts_d = opts_d_or_dataset_ids
1029 if isinstance(opts_d_or_dataset_ids, list):
1030 opts_d = {"ids": opts_d_or_dataset_ids}
1031 return self._post_job_by_type("merge-datasets", opts_d)
1032
1033 def get_pipelines(self, public_only=True):
1034 """
1035 Retrieve a list of SMRT Analysis workflow interface descriptions
1036 """
1037 def _is_private(tags):
1038 hidden_tags = {"dev", "internal", "alpha", "obsolete"}
1039 return len(set(tags).intersection(hidden_tags)) > 0
1040
1041 pipelines = self.get("/smrt-link/resolved-pipeline-templates")
1042 if public_only:
1043 return [p for p in pipelines if not _is_private(p["tags"])]
1044 else:
1045 return pipelines
1046
1047 def get_pipeline(self, pipeline_id):
1048 """
1049 Retrieve a SMRT Analysis workflow interface description by ID,
1050 such as 'pb_align_ccs' or 'cromwell.workflows.pb_align_ccs'
1051 """
1052 if not pipeline_id.startswith("cromwell.workflows"):
1053 pipeline_id = f"cromwell.workflows.{pipeline_id}"
1054 return self.get(f"/smrt-link/resolved-pipeline-templates/{pipeline_id}")
1055
1056 def poll_for_successful_job(self, job_id, sleep_time=10, max_time=28800):
1057 """
1058 Poll a submitted services job of any type until it completes
1059 successfully within the specified timeout, or raise an exception.
1060 This lacks the error handling that we need for heavily used servers.
1061 """
1062 t_start = time.time()
1063 final_states = {"SUCCESSFUL", "FAILED", "TERMINATED", "ABORTED"}
1064 while True:
1065 job = self.get_job(job_id)
1066 log.debug(f"Current job: {job}")
1067 state = job["state"]
1068 if state in final_states:
1069 log.info(f"Job {job_id} is in state {state}, polling complete")
1070 break
1071 else:
1072 t_current = time.time()
1073 if t_current - t_start > max_time:
1074 raise RuntimeError(
1075 f"Polling time ({max_time}s) exceeded, aborting")
1076 log.debug(f"Sleeping {sleep_time}s until next status check")
1077 time.sleep(sleep_time)
1078 if state != "SUCCESSFUL":
1079 raise RuntimeError(f"Job {job_id} exited with state {state}")
1080 return job
1081
1082 # -----------------------------------------------------------------
1083 # OTHER
1084 def upload_file(self, file_path):
1085 files_d = {
1086 "upload_file": open(file_path, "rb")
1087 }
1088 url = self.to_url("/smrt-link/uploader")
1089 log.info(f"Method: POST /smrt-link/uploader {files_d}")
1090 log.debug(f"Full URL: {url}")
1091 # XXX the Content-Type header is added automatically by the requests
1092 # library - sending application/json results in a 404 response from
1093 # the akka-http API backend
1094 headers = {
1095 "Authorization": f"Bearer {self.auth_token}"
1096 }
1097 response = requests.post(url,
1098 files=files_d,
1099 headers=headers,
1100 verify=self._verify)
1101 log.debug(response)
1102 response.raise_for_status()
1103 return response.json()
1104
1105
1106 ########################################################################
1107 # COMMAND LINE TOOLING
1108 #
1109 def get_smrtlink_client_from_args(args):
1110 """
1111 Instantiate a client using the argparse object, when defined with the
1112 add_smrtlink_server_args function
1113 """
1114 return SmrtLinkClient(
1115 host=args.host,
1116 port=args.port,
1117 username=args.user,
1118 password=args.password,
1119 verify=not args.insecure)
1120
1121
1122 def add_smrtlink_server_args(p):
1123 """
1124 Add argparse arguments for connecting to a SMRT Link REST API, for
1125 developers who want to use this client in other CLI programs
1126 """
1127 DEFAULT_HOST = os.environ.get("PB_SERVICE_HOST", "localhost")
1128 DEFAULT_PORT = int(os.environ.get("PB_SERVICE_PORT", Constants.API_PORT))
1129 DEFAULT_USER = os.environ.get("PB_SERVICE_AUTH_USER", None)
1130 DEFAULT_PASSWORD = os.environ.get("PB_SERVICE_AUTH_PASSWORD", None)
1131 p.add_argument("--host",
1132 action="store",
1133 default=DEFAULT_HOST,
1134 help="SL Server Hostname")
1135 p.add_argument("--port",
1136 action="store",
1137 type=int,
1138 default=DEFAULT_PORT,
1139 help="SL Server Port")
1140 p.add_argument("--user",
1141 action="store",
1142 default=DEFAULT_USER,
1143 help="SL Server User Name")
1144 p.add_argument("--password",
1145 action="store",
1146 default=DEFAULT_PASSWORD,
1147 help="SL Server Password")
1148 p.add_argument("-k", "--insecure",
1149 action="store_true",
1150 default=not Constants.DEFAULT_VERIFY,
1151 help="Run in insecure mode without validating the SSL certificate")
1152 return p
1153
1154
1155 def _main(argv=sys.argv):
1156 """
1157 Command line utility for generic method calls returning JSON:
1158
1159 $ smrtlink_client.py GET /smrt-link/runs \\
1160 --host smrtlink.lab.company.com \\
1161 --user pbuser --password XXX
1162 [
1163 {
1164 "uniqueId": "2707e6c2-8bc8-4d84-98b3-5f112e7d77ff",
1165 "name": "Run_2023_06_01_84001",
1166 ...
1167 },
1168 ...
1169 ]
1170 """
1171
1172 def _validate_api_path(s):
1173 if not s.startswith("/"):
1174 raise ValueError(f"Invalid URL path {s}")
1175 elif s.startswith("/SMRTLink"):
1176 raise ValueError(
1177 f"Please use the base API path, without /SMRTLink/1.0.0")
1178 return s
1179
1180 parser = argparse.ArgumentParser(_main.__doc__)
1181 add_smrtlink_server_args(parser)
1182 parser.add_argument("method",
1183 choices=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
1184 help="HTTP method (GET, POST, PUT, DELETE, OPTIONS)")
1185 parser.add_argument("path",
1186 type=_validate_api_path,
1187 help="API method path, e.g. /smrt-link/runs")
1188 parser.add_argument("-d", "--data",
1189 type=json.loads,
1190 default={},
1191 help="JSON request body (POST/PUT only)")
1192 parser.add_argument("-H", "--header",
1193 dest="headers",
1194 action="append",
1195 default=[],
1196 help="Optional HTTP header (multiple allowed)")
1197 parser.add_argument("-v", "--verbose",
1198 action="store_true",
1199 default=False,
1200 help="Verbose mode logging (INFO)")
1201 parser.add_argument("--debug",
1202 action="store_true",
1203 default=False,
1204 help="Debug mode logging (DEBUG)")
1205 parser.add_argument("--quiet",
1206 action="store_true",
1207 default=False,
1208 help="Quiet mode logging (ERROR)")
1209 args = parser.parse_args(argv[1:])
1210 log_level = logging.WARN
1211 if args.debug:
1212 log_level = logging.DEBUG
1213 elif args.verbose:
1214 log_level = logging.INFO
1215 elif args.quiet:
1216 log_level = logging.ERROR
1217 logging.basicConfig(level=log_level,
1218 stream=sys.stdout,
1219 format="[%(levelname)s] %(asctime)-15sZ %(message)s")
1220 if args.insecure:
1221 _disable_insecure_warning()
1222 client = get_smrtlink_client_from_args(args)
1223 headers_d = dict([(s.strip() for s in h.split(":")) for h in args.headers])
1224 response = client.execute_call(args.method,
1225 args.path,
1226 args.data,
1227 headers_d)
1228 print(json.dumps(response, indent=2))
1229 return 0
1230
1231
1232 if __name__ == "__main__":
1233 sys.exit(_main(sys.argv))