| 1 |
""" |
| 2 |
Utilities for streamlining common services actions (used in pbcromwell test |
| 3 |
runner among others). |
| 4 |
The old CLI program is largely replaced by the Scala version in 'smrtflow'. |
| 5 |
""" |
| 6 |
|
| 7 |
from functools import cmp_to_key |
| 8 |
import functools |
| 9 |
import json |
| 10 |
import logging |
| 11 |
import os |
| 12 |
import pprint |
| 13 |
import sys |
| 14 |
import time |
| 15 |
import uuid |
| 16 |
|
| 17 |
import iso8601 |
| 18 |
from requests import RequestException |
| 19 |
|
| 20 |
from pbcommand.models import FileTypes |
| 21 |
from pbcommand.services import (ServiceAccessLayer, |
| 22 |
ServiceEntryPoint, |
| 23 |
JobExeError) |
| 24 |
from pbcommand.services._service_access_layer import ( |
| 25 |
DATASET_METATYPES_TO_ENDPOINTS, ) |
| 26 |
from pbcommand.validators import validate_file, validate_or |
| 27 |
from pbcommand.utils import (is_dataset, walker, compose) |
| 28 |
from pbcommand import to_ascii |
| 29 |
|
| 30 |
__version__ = "0.3.0" |
| 31 |
|
| 32 |
log = logging.getLogger(__name__) |
| 33 |
log.addHandler(logging.NullHandler()) |
| 34 |
|
| 35 |
|
| 36 |
def _list_dict_printer(list_d): |
| 37 |
for i in list_d: |
| 38 |
print(i) |
| 39 |
|
| 40 |
|
| 41 |
try: |
| 42 |
|
| 43 |
from tabulate import tabulate |
| 44 |
|
| 45 |
def printer(list_d): |
| 46 |
print(tabulate(list_d)) |
| 47 |
list_dict_printer = printer |
| 48 |
except ImportError: |
| 49 |
list_dict_printer = _list_dict_printer |
| 50 |
|
| 51 |
|
| 52 |
class Constants: |
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
ENV_PB_SERVICE_HOST = "PB_SERVICE_HOST" |
| 57 |
ENV_PB_SERVICE_PORT = "PB_SERVICE_PORT" |
| 58 |
|
| 59 |
DEFAULT_HOST = "http://localhost" |
| 60 |
DEFAULT_PORT = 8070 |
| 61 |
|
| 62 |
FASTA_TO_REFERENCE = "fasta-to-reference" |
| 63 |
RS_MOVIE_TO_DS = "movie-metadata-to-dataset" |
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
MAX_FASTA_FILE_MB = 100 |
| 68 |
|
| 69 |
|
| 70 |
def _is_xml(path): |
| 71 |
return path.endswith(".xml") |
| 72 |
|
| 73 |
|
| 74 |
def add_max_items_option(default, desc="Max items to return"): |
| 75 |
def f(p): |
| 76 |
p.add_argument( |
| 77 |
'-m', |
| 78 |
'--max-items', |
| 79 |
type=int, |
| 80 |
default=default, |
| 81 |
help=desc) |
| 82 |
return p |
| 83 |
return f |
| 84 |
|
| 85 |
|
| 86 |
validate_int_or_uuid = validate_or(int, uuid.UUID, "Expected Int or UUID") |
| 87 |
|
| 88 |
|
| 89 |
def _get_size_mb(path): |
| 90 |
return os.stat(path).st_size / 1024.0 / 1024.0 |
| 91 |
|
| 92 |
|
| 93 |
def get_sal_and_status(host, port): |
| 94 |
"""Get Sal or Raise if status isn't successful""" |
| 95 |
try: |
| 96 |
sal = ServiceAccessLayer(host, port) |
| 97 |
sal.get_status() |
| 98 |
return sal |
| 99 |
except RequestException as e: |
| 100 |
log.error("Failed to connect to {h}:{p}".format(h=host, p=port)) |
| 101 |
raise |
| 102 |
|
| 103 |
|
| 104 |
def run_file_or_dir(file_func, dir_func, xml_or_dir): |
| 105 |
if os.path.isdir(xml_or_dir): |
| 106 |
return dir_func(xml_or_dir) |
| 107 |
elif os.path.isfile(xml_or_dir): |
| 108 |
return file_func(xml_or_dir) |
| 109 |
else: |
| 110 |
raise ValueError("Unsupported value {x}".format(x=xml_or_dir)) |
| 111 |
|
| 112 |
|
| 113 |
def is_xml_dataset(path): |
| 114 |
if _is_xml(path): |
| 115 |
if is_dataset(path): |
| 116 |
return True |
| 117 |
return False |
| 118 |
|
| 119 |
|
| 120 |
def dataset_walker(root_dir): |
| 121 |
filter_func = is_xml_dataset |
| 122 |
return walker(root_dir, filter_func) |
| 123 |
|
| 124 |
|
| 125 |
def import_local_dataset(sal, path): |
| 126 |
""":type sal: ServiceAccessLayer""" |
| 127 |
|
| 128 |
try: |
| 129 |
from pbcore.io import openDataSet, ReadSet, HdfSubreadSet |
| 130 |
except ImportError: |
| 131 |
log.warn("Can't import pbcore, skipping dataset sanity check") |
| 132 |
else: |
| 133 |
ds = openDataSet(path, strict=True) |
| 134 |
if isinstance(ds, ReadSet) and not isinstance(ds, HdfSubreadSet): |
| 135 |
if len(ds) > 0: |
| 136 |
log.info("checking BAM file integrity") |
| 137 |
for rr in ds.resourceReaders(): |
| 138 |
try: |
| 139 |
_ = rr[-1] |
| 140 |
except Exception as e: |
| 141 |
log.exception("Import failed because the underlying " + |
| 142 |
"data appear to be corrupted. Run " + |
| 143 |
"'pbvalidate' on the dataset for more " + |
| 144 |
"thorough checking.") |
| 145 |
return 1 |
| 146 |
else: |
| 147 |
log.warn("Empty dataset - will import anyway") |
| 148 |
|
| 149 |
|
| 150 |
_ = sal.run_import_local_dataset(path) |
| 151 |
log.info("Successfully import dataset from {f}".format(f=path)) |
| 152 |
return 0 |
| 153 |
|
| 154 |
|
| 155 |
def import_datasets(sal, root_dir): |
| 156 |
|
| 157 |
rcodes = [] |
| 158 |
for path in dataset_walker(root_dir): |
| 159 |
try: |
| 160 |
import_local_dataset(sal, path) |
| 161 |
rcodes.append(0) |
| 162 |
except Exception as e: |
| 163 |
log.error("Failed to import dataset {e}".format(e=e)) |
| 164 |
rcodes.append(1) |
| 165 |
|
| 166 |
state = all(v == 0 for v in rcodes) |
| 167 |
return 0 if state else 1 |
| 168 |
|
| 169 |
|
| 170 |
def run_import_local_datasets(host, port, xml_or_dir): |
| 171 |
sal = ServiceAccessLayer(host, port) |
| 172 |
file_func = functools.partial(import_local_dataset, sal) |
| 173 |
dir_func = functools.partial(import_datasets, sal) |
| 174 |
return run_file_or_dir(file_func, dir_func, xml_or_dir) |
| 175 |
|
| 176 |
|
| 177 |
def run_import_fasta(host, port, fasta_path, name, |
| 178 |
organism, ploidy, block=False): |
| 179 |
sal = ServiceAccessLayer(host, port) |
| 180 |
log.info("importing ({s:.2f} MB) {f} ".format( |
| 181 |
s=_get_size_mb(fasta_path), f=fasta_path)) |
| 182 |
if block is True: |
| 183 |
result = sal.run_import_fasta(fasta_path, name, organism, ploidy) |
| 184 |
log.info("Successfully imported {f}".format(f=fasta_path)) |
| 185 |
log.info("result {r}".format(r=result)) |
| 186 |
else: |
| 187 |
sal.import_fasta(fasta_path, name, organism, ploidy) |
| 188 |
|
| 189 |
return 0 |
| 190 |
|
| 191 |
|
| 192 |
def load_analysis_job_json(d): |
| 193 |
"""Translate a dict to args for scenario runner inputs""" |
| 194 |
job_name = to_ascii(d['name']) |
| 195 |
pipeline_template_id = to_ascii(d["pipelineId"]) |
| 196 |
service_epoints = [ServiceEntryPoint.from_d(x) for x in d['entryPoints']] |
| 197 |
tags = d.get('tags', []) |
| 198 |
return job_name, pipeline_template_id, service_epoints, tags |
| 199 |
|
| 200 |
|
| 201 |
def run_analysis_job(sal, job_name, pipeline_id, service_entry_points, |
| 202 |
block=False, time_out=None, task_options=(), tags=()): |
| 203 |
"""Run analysis (pbsmrtpipe) job |
| 204 |
|
| 205 |
:rtype ServiceJob: |
| 206 |
""" |
| 207 |
if time_out is None: |
| 208 |
time_out = sal.JOB_DEFAULT_TIMEOUT |
| 209 |
status = sal.get_status() |
| 210 |
log.info( |
| 211 |
"System:{i} v:{v} Status:{x}".format( |
| 212 |
x=status['message'], |
| 213 |
i=status['id'], |
| 214 |
v=status['version'])) |
| 215 |
|
| 216 |
resolved_service_entry_points = [] |
| 217 |
for service_entry_point in service_entry_points: |
| 218 |
|
| 219 |
ds = sal.get_dataset_by_uuid(service_entry_point.resource) |
| 220 |
if ds is None: |
| 221 |
raise ValueError( |
| 222 |
"Failed to find DataSet with id {r} {s}".format( |
| 223 |
s=service_entry_point, |
| 224 |
r=service_entry_point.resource)) |
| 225 |
|
| 226 |
dataset_id = ds['id'] |
| 227 |
ep = ServiceEntryPoint( |
| 228 |
service_entry_point.entry_id, |
| 229 |
service_entry_point.dataset_type, |
| 230 |
dataset_id) |
| 231 |
log.debug("Resolved dataset {e}".format(e=ep)) |
| 232 |
resolved_service_entry_points.append(ep) |
| 233 |
|
| 234 |
if block: |
| 235 |
job_result = sal.run_by_pipeline_template_id( |
| 236 |
job_name, |
| 237 |
pipeline_id, |
| 238 |
resolved_service_entry_points, |
| 239 |
time_out=time_out, |
| 240 |
task_options=task_options, |
| 241 |
tags=tags) |
| 242 |
job_id = job_result.job.id |
| 243 |
|
| 244 |
result = sal.get_analysis_job_by_id(job_id) |
| 245 |
if not result.was_successful(): |
| 246 |
raise JobExeError( |
| 247 |
"Job {i} failed:\n{e}".format( |
| 248 |
i=job_id, e=job_result.job.error_message)) |
| 249 |
else: |
| 250 |
|
| 251 |
result = sal.create_by_pipeline_template_id( |
| 252 |
job_name, pipeline_id, resolved_service_entry_points, tags=tags) |
| 253 |
|
| 254 |
log.info("Result {r}".format(r=result)) |
| 255 |
return result |
| 256 |
|
| 257 |
|
| 258 |
def run_get_job_summary(host, port, job_id): |
| 259 |
sal = get_sal_and_status(host, port) |
| 260 |
job = sal.get_job_by_id(job_id) |
| 261 |
epoints = sal.get_analysis_job_entry_points(job_id) |
| 262 |
|
| 263 |
if job is None: |
| 264 |
log.error( |
| 265 |
"Unable to find job {i} from {u}".format( |
| 266 |
i=job_id, u=sal.uri)) |
| 267 |
else: |
| 268 |
|
| 269 |
|
| 270 |
print("Job {}".format(job_id)) |
| 271 |
|
| 272 |
print(job._replace(settings={})) |
| 273 |
print(" Entry Points {}".format(len(epoints))) |
| 274 |
for epoint in epoints: |
| 275 |
print(" {}".format(epoint)) |
| 276 |
|
| 277 |
return 0 |
| 278 |
|
| 279 |
|
| 280 |
def run_job_list_summary(host, port, max_items, sort_by=None): |
| 281 |
sal = get_sal_and_status(host, port) |
| 282 |
|
| 283 |
jobs = sal.get_analysis_jobs() |
| 284 |
|
| 285 |
jobs_list = jobs if sort_by is None else sorted( |
| 286 |
jobs, key=cmp_to_key(sort_by)) |
| 287 |
|
| 288 |
printer(jobs_list[:max_items]) |
| 289 |
|
| 290 |
return 0 |
| 291 |
|
| 292 |
|
| 293 |
def run_get_dataset_summary(host, port, dataset_id_or_uuid): |
| 294 |
|
| 295 |
sal = get_sal_and_status(host, port) |
| 296 |
|
| 297 |
log.debug("Getting dataset {d}".format(d=dataset_id_or_uuid)) |
| 298 |
ds = sal.get_dataset_by_uuid(dataset_id_or_uuid) |
| 299 |
|
| 300 |
if ds is None: |
| 301 |
log.error( |
| 302 |
"Unable to find DataSet '{i}' on {u}".format( |
| 303 |
i=dataset_id_or_uuid, |
| 304 |
u=sal.uri)) |
| 305 |
else: |
| 306 |
print(pprint.pformat(ds, indent=2)) |
| 307 |
|
| 308 |
return 0 |
| 309 |
|
| 310 |
|
| 311 |
def run_get_dataset_list_summary( |
| 312 |
host, port, dataset_type, max_items, sort_by=None): |
| 313 |
""" |
| 314 |
|
| 315 |
Display a list of Dataset summaries |
| 316 |
|
| 317 |
:param host: |
| 318 |
:param port: |
| 319 |
:param dataset_type: |
| 320 |
:param max_items: |
| 321 |
:param sort_by: func to sort resources sort_by = lambda x.created_at |
| 322 |
:return: |
| 323 |
""" |
| 324 |
sal = get_sal_and_status(host, port) |
| 325 |
|
| 326 |
def to_ep(file_type): |
| 327 |
return DATASET_METATYPES_TO_ENDPOINTS[file_type] |
| 328 |
|
| 329 |
|
| 330 |
|
| 331 |
fs = {to_ep(FileTypes.DS_SUBREADS): sal.get_subreadsets, |
| 332 |
to_ep(FileTypes.DS_REF): sal.get_referencesets, |
| 333 |
to_ep(FileTypes.DS_ALIGN): sal.get_alignmentsets, |
| 334 |
to_ep(FileTypes.DS_BARCODE): sal.get_barcodesets |
| 335 |
} |
| 336 |
|
| 337 |
f = fs.get(dataset_type) |
| 338 |
|
| 339 |
if f is None: |
| 340 |
raise KeyError( |
| 341 |
"Unsupported dataset type {t} Supported types {s}".format( |
| 342 |
t=dataset_type, s=list( |
| 343 |
fs.keys()))) |
| 344 |
else: |
| 345 |
datasets = f() |
| 346 |
|
| 347 |
sorted_datasets = datasets if sort_by is None else sorted( |
| 348 |
datasets, key=cmp_to_key(sort_by)) |
| 349 |
|
| 350 |
print( |
| 351 |
"Number of {t} Datasets {n}".format( |
| 352 |
t=dataset_type, |
| 353 |
n=len(datasets))) |
| 354 |
list_dict_printer(sorted_datasets[:max_items]) |
| 355 |
|
| 356 |
return 0 |