| 1 |
""" |
| 2 |
Services Specific Data Models |
| 3 |
""" |
| 4 |
|
| 5 |
import json |
| 6 |
import uuid |
| 7 |
from collections import namedtuple |
| 8 |
import os |
| 9 |
|
| 10 |
import iso8601 |
| 11 |
from requests.exceptions import RequestException |
| 12 |
|
| 13 |
from pbcommand.utils import to_ascii |
| 14 |
|
| 15 |
__all__ = [ |
| 16 |
'ServiceJob', |
| 17 |
'ServiceEntryPoint', |
| 18 |
'JobEntryPoint', |
| 19 |
'JobStates', |
| 20 |
'JobTypes', |
| 21 |
] |
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
class LogLevels: |
| 26 |
TRACE = "TRACE" |
| 27 |
DEBUG = "DEBUG" |
| 28 |
INFO = "INFO" |
| 29 |
NOTICE = "NOTICE" |
| 30 |
WARN = "WARN" |
| 31 |
ERROR = "ERROR" |
| 32 |
CRITICAL = "CRITICAL" |
| 33 |
FATAL = "FATAL" |
| 34 |
|
| 35 |
ALL = (TRACE, DEBUG, INFO, NOTICE, WARN, ERROR, CRITICAL, FATAL) |
| 36 |
|
| 37 |
@classmethod |
| 38 |
def is_valid(cls, level): |
| 39 |
return level in cls.ALL |
| 40 |
|
| 41 |
|
| 42 |
SERVICE_LOGGER_RESOURCE_ID = "pbsmrtpipe" |
| 43 |
|
| 44 |
LogResource = namedtuple("LogResource", "id name description") |
| 45 |
LogMessage = namedtuple("LogMessage", "sourceId level message") |
| 46 |
|
| 47 |
PbsmrtpipeLogResource = LogResource(SERVICE_LOGGER_RESOURCE_ID, "Pbsmrtpipe", |
| 48 |
"Secondary Analysis Pbsmrtpipe Job logger") |
| 49 |
|
| 50 |
|
| 51 |
class ServiceJob: |
| 52 |
|
| 53 |
def __init__(self, ix, job_uuid, name, state, path, job_type, created_at, |
| 54 |
settings, |
| 55 |
is_active=True, |
| 56 |
smrtlink_version=None, |
| 57 |
created_by=None, |
| 58 |
updated_at=None, |
| 59 |
error_message=None, |
| 60 |
imported_at=None, |
| 61 |
job_updated_at=None, |
| 62 |
created_by_email=None, |
| 63 |
is_multi_job=False, |
| 64 |
tags="", |
| 65 |
parent_multi_job_id=None, |
| 66 |
workflow=None, |
| 67 |
project_id=1, |
| 68 |
job_started_at=None, |
| 69 |
job_completed_at=None, |
| 70 |
sub_job_type_id=None, |
| 71 |
external_job_id=None): |
| 72 |
""" |
| 73 |
|
| 74 |
:param ix: Job Integer Id |
| 75 |
:param job_uuid: Globally unique Job UUID |
| 76 |
:param name: Display name of job |
| 77 |
:param state: Job State |
| 78 |
:param path: Absolute Path to the job directory |
| 79 |
:param job_type: Job Type |
| 80 |
:param created_at: when the job was created at |
| 81 |
:param settings: dict of job specific settings |
| 82 |
:param is_active: If the Job is active (only active jobs are displayed in the SL UI) |
| 83 |
:param smrtlink_version: SMRT Link Version (if known) |
| 84 |
:param created_by: User that created the job |
| 85 |
:param updated_at: when the last update of the job occurred |
| 86 |
:param error_message: Error message if the job has failed |
| 87 |
:param job_started_at: Job start time (if the job has started running) |
| 88 |
:param job_completed_at: Job completed time (if the job has completed) |
| 89 |
|
| 90 |
:type ix: int |
| 91 |
:type job_uuid: str |
| 92 |
:type name: str |
| 93 |
:type state: str |
| 94 |
:type job_type: str |
| 95 |
:type created_at: DateTime |
| 96 |
:type updated_at: DateTime | None |
| 97 |
:type job_updated_at: DateTime | None |
| 98 |
:type settings: dict |
| 99 |
:type is_active: bool |
| 100 |
:type smrtlink_version: str | None |
| 101 |
:type created_by: str | None |
| 102 |
:type created_by_email: str | None |
| 103 |
:type error_message: str | None |
| 104 |
:type is_multi_job: bool |
| 105 |
:type tags: str |
| 106 |
:type workflow: dict | None |
| 107 |
:type project_id: int |
| 108 |
""" |
| 109 |
self.id = int(ix) |
| 110 |
|
| 111 |
_ = uuid.UUID(job_uuid) |
| 112 |
self.uuid = job_uuid |
| 113 |
self.name = name |
| 114 |
self.state = state |
| 115 |
self.path = path |
| 116 |
self.job_type = job_type |
| 117 |
self.created_at = created_at |
| 118 |
self.settings = settings |
| 119 |
self.is_active = is_active |
| 120 |
self.smrtlink_version = smrtlink_version |
| 121 |
self.created_by = created_by |
| 122 |
self.created_by_email = created_by_email |
| 123 |
|
| 124 |
self.updated_at = updated_at |
| 125 |
self.error_message = error_message |
| 126 |
self.imported_at = imported_at |
| 127 |
|
| 128 |
self.job_updated_at = updated_at if job_updated_at is None else job_updated_at |
| 129 |
self.is_multi_job = is_multi_job |
| 130 |
self.tags = tags |
| 131 |
self.parent_multi_job_id = parent_multi_job_id |
| 132 |
|
| 133 |
self.workflow = {} if workflow is None else workflow |
| 134 |
self.project_id = project_id |
| 135 |
self.sub_job_type_id = sub_job_type_id |
| 136 |
self.external_job_id = external_job_id |
| 137 |
|
| 138 |
|
| 139 |
|
| 140 |
|
| 141 |
|
| 142 |
self.job_started_at = job_started_at |
| 143 |
self.job_completed_at = job_completed_at |
| 144 |
|
| 145 |
def __repr__(self): |
| 146 |
|
| 147 |
max_length = 15 |
| 148 |
if len(self.name) >= max_length: |
| 149 |
name = self.name[:max_length] + "..." |
| 150 |
else: |
| 151 |
name = self.name |
| 152 |
|
| 153 |
created_by = "Unknown" if self.created_by is None else self.created_by |
| 154 |
|
| 155 |
ix = str(self.id).rjust(5) |
| 156 |
state = self.state.rjust(11) |
| 157 |
|
| 158 |
created_at = self.created_at.strftime("%m-%d-%Y %I:%M.%S") |
| 159 |
|
| 160 |
|
| 161 |
|
| 162 |
def _format_dt(n_seconds): |
| 163 |
if n_seconds >= 60: |
| 164 |
|
| 165 |
|
| 166 |
return "{m} min ".format(m=int(n_seconds // 60)) |
| 167 |
else: |
| 168 |
return "{s:.2f} sec".format(s=n_seconds) |
| 169 |
|
| 170 |
run_time = "NA" if self.run_time_sec is None else _format_dt( |
| 171 |
self.run_time_sec) |
| 172 |
|
| 173 |
_d = dict(k=self.__class__.__name__, |
| 174 |
i=ix, |
| 175 |
n=name, |
| 176 |
c=created_at, |
| 177 |
u=self.uuid, |
| 178 |
s=state, b=created_by, |
| 179 |
r=run_time) |
| 180 |
|
| 181 |
return "<{k} i:{i} state:{s} created:{c} by:{b} name:{n} runtime: {r} >".format( |
| 182 |
**_d) |
| 183 |
|
| 184 |
@property |
| 185 |
def execution_time_sec(self): |
| 186 |
""" |
| 187 |
Return the Job Execution time (in sec) for completed jobs or return None for |
| 188 |
non-completed jobs |
| 189 |
|
| 190 |
Note, for Jobs from SL > 6.0.0, this was not defined and will always return None |
| 191 |
|
| 192 |
:rtype: None | int |
| 193 |
""" |
| 194 |
if self.job_started_at is not None: |
| 195 |
if self.job_completed_at is not None: |
| 196 |
return (self.job_completed_at - |
| 197 |
self.job_started_at).total_seconds() |
| 198 |
return None |
| 199 |
|
| 200 |
@property |
| 201 |
def run_time_sec(self): |
| 202 |
""" |
| 203 |
Note, prior to SL 6.0.X, jobs did not have a well defined job start/complete mechanism |
| 204 |
and the Job entity timestamps were used. This has assumptions that the Job is |
| 205 |
started when the job is created. This is often not true. |
| 206 |
|
| 207 |
For completed jobs from SL version >= 6.0.x, use execution_time_sec. |
| 208 |
|
| 209 |
:rtype: None | int |
| 210 |
""" |
| 211 |
if self.job_updated_at is not None: |
| 212 |
return (self.job_updated_at - self.created_at).total_seconds() |
| 213 |
|
| 214 |
return None |
| 215 |
|
| 216 |
@staticmethod |
| 217 |
def from_d(d): |
| 218 |
"""Convert from Service JSON response to `ServiceJob` instance""" |
| 219 |
|
| 220 |
def sx(x): |
| 221 |
return d[x] |
| 222 |
|
| 223 |
def s_or(x, default=None): |
| 224 |
return d.get(x, default) |
| 225 |
|
| 226 |
|
| 227 |
def se(x): |
| 228 |
return to_ascii(sx(x)) |
| 229 |
|
| 230 |
def se_or(x, default=None): |
| 231 |
v = s_or(x, default=default) |
| 232 |
return v if v is None else to_ascii(v) |
| 233 |
|
| 234 |
def to_t(x): |
| 235 |
return iso8601.parse_date(se(x)) |
| 236 |
|
| 237 |
def to_d(x): |
| 238 |
|
| 239 |
return json.loads(sx(x)) |
| 240 |
|
| 241 |
def to_opt_datetime(k): |
| 242 |
x = s_or(k) |
| 243 |
return iso8601.parse_date(x) if x is not None else None |
| 244 |
|
| 245 |
ix = int(sx('id')) |
| 246 |
job_uuid = sx('uuid') |
| 247 |
name = se('name') |
| 248 |
state = se('state') |
| 249 |
path = se('path') |
| 250 |
job_type = se('jobTypeId') |
| 251 |
created_at = to_t('createdAt') |
| 252 |
updated_at = to_opt_datetime('updatedAt') |
| 253 |
job_started_at = to_opt_datetime("jobStartedAt") |
| 254 |
job_completed_at = to_opt_datetime("jobCompletedAt") |
| 255 |
job_updated_at = to_opt_datetime('jobUpdatedAt') |
| 256 |
imported_at = to_opt_datetime('importedAt') |
| 257 |
|
| 258 |
project_id = s_or("projectId", 1) |
| 259 |
|
| 260 |
smrtlink_version = se_or("smrtlinkVersion") |
| 261 |
error_message = se_or("errorMessage") |
| 262 |
created_by = se_or("createdBy") |
| 263 |
created_by_email = se_or('createdByEmail') |
| 264 |
is_active = d.get('isActive', True) |
| 265 |
settings = se_or('jsonSettings') |
| 266 |
sub_job_type_id = se_or("subJobTypeId") |
| 267 |
external_job_id = se_or("externalJobId") |
| 268 |
|
| 269 |
is_multi_job = d.get("isMultiJob", False) |
| 270 |
parent_multi_job_id = s_or("parentMultiJobId") |
| 271 |
|
| 272 |
workflow = json.loads(se_or("workflow", "{}")) |
| 273 |
|
| 274 |
tags = se_or("tags", "") |
| 275 |
|
| 276 |
return ServiceJob(ix, |
| 277 |
job_uuid, |
| 278 |
name, |
| 279 |
state, |
| 280 |
path, |
| 281 |
job_type, |
| 282 |
created_at, |
| 283 |
settings, is_active=is_active, |
| 284 |
smrtlink_version=smrtlink_version, |
| 285 |
created_by=created_by, |
| 286 |
created_by_email=created_by_email, |
| 287 |
updated_at=updated_at, |
| 288 |
error_message=error_message, |
| 289 |
imported_at=imported_at, |
| 290 |
job_updated_at=job_updated_at, |
| 291 |
project_id=project_id, |
| 292 |
tags=tags, |
| 293 |
is_multi_job=is_multi_job, |
| 294 |
parent_multi_job_id=parent_multi_job_id, |
| 295 |
workflow=workflow, |
| 296 |
job_started_at=job_started_at, |
| 297 |
job_completed_at=job_completed_at, |
| 298 |
sub_job_type_id=sub_job_type_id, |
| 299 |
external_job_id=external_job_id) |
| 300 |
|
| 301 |
def was_successful(self): |
| 302 |
""" :rtype: bool """ |
| 303 |
return self.state == JobStates.SUCCESSFUL |
| 304 |
|
| 305 |
|
| 306 |
class JobExeError(ValueError): |
| 307 |
"""Service Job failed to complete successfully""" |
| 308 |
pass |
| 309 |
|
| 310 |
|
| 311 |
class SmrtServerConnectionError(RequestException): |
| 312 |
"""This is blunt to catch all status related errors""" |
| 313 |
pass |
| 314 |
|
| 315 |
|
| 316 |
class SMRTServiceBaseError(Exception): |
| 317 |
"""Fundamental Error datastructure in SMRT Server""" |
| 318 |
|
| 319 |
def __init__(self, http_code, error_type, message, **kwargs): |
| 320 |
self.http_code = http_code |
| 321 |
self.error_type = error_type |
| 322 |
self.msg = message |
| 323 |
message = "Http code={h} msg={m} type={t}".format( |
| 324 |
h=http_code, m=message, t=error_type) |
| 325 |
super().__init__(message) |
| 326 |
|
| 327 |
@staticmethod |
| 328 |
def from_d(d): |
| 329 |
"""Convert from SMRT Link Service Error JSON response to `SMRTServiceBaseError` instance""" |
| 330 |
return SMRTServiceBaseError( |
| 331 |
d['httpCode'], d['errorType'], d['message']) |
| 332 |
|
| 333 |
|
| 334 |
|
| 335 |
JobResult = namedtuple("JobResult", "job run_time errors") |
| 336 |
|
| 337 |
|
| 338 |
class JobTask(namedtuple( |
| 339 |
"JobTask", "task_uuid job_id task_id task_type name state created_at updated_at error_message")): |
| 340 |
|
| 341 |
@staticmethod |
| 342 |
def from_d(d): |
| 343 |
return JobTask(d['uuid'], d['jobId'], d['taskId'], d['taskTypeId'], |
| 344 |
d['name'], d['state'], d['createdAt'], |
| 345 |
d['updatedAt'], d.get('errorMessage')) |
| 346 |
|
| 347 |
|
| 348 |
def _to_resource_id(x): |
| 349 |
if isinstance(x, int): |
| 350 |
return x |
| 351 |
try: |
| 352 |
_ = uuid.UUID(x) |
| 353 |
return x |
| 354 |
except ValueError as e: |
| 355 |
raise ValueError( |
| 356 |
"Resource id '{x}' must be given as int or uuid".format( |
| 357 |
x=x)) |
| 358 |
|
| 359 |
|
| 360 |
class ServiceEntryPoint: |
| 361 |
"""Entry Points to initialize Pipelines""" |
| 362 |
|
| 363 |
def __init__(self, entry_id, dataset_type, path_or_uri): |
| 364 |
self.entry_id = entry_id |
| 365 |
self.dataset_type = dataset_type |
| 366 |
|
| 367 |
self._resource = path_or_uri |
| 368 |
|
| 369 |
@property |
| 370 |
def resource(self): |
| 371 |
"""Backwards compatible with path_or_uri""" |
| 372 |
return self._resource |
| 373 |
|
| 374 |
def __repr__(self): |
| 375 |
_d = dict(k=self.__class__.__name__, e=self.entry_id, |
| 376 |
r=self._resource, d=self.dataset_type) |
| 377 |
return "<{k} {e} {d} {r} >".format(**_d) |
| 378 |
|
| 379 |
@staticmethod |
| 380 |
def from_d(d): |
| 381 |
"""Convert from Service JSON response to `ServiceEntryPoint` instance""" |
| 382 |
i = _to_resource_id(d['datasetId']) |
| 383 |
return ServiceEntryPoint( |
| 384 |
to_ascii(d['entryId']), to_ascii(d['fileTypeId']), i) |
| 385 |
|
| 386 |
def to_d(self): |
| 387 |
return dict(entryId=self.entry_id, |
| 388 |
fileTypeId=self.dataset_type, |
| 389 |
datasetId=self.resource) |
| 390 |
|
| 391 |
|
| 392 |
class JobEntryPoint(namedtuple("JobEntryPoint", |
| 393 |
"job_id dataset_uuid dataset_metatype")): |
| 394 |
""" Returned from the Services /job/1234/entry-points """ |
| 395 |
@staticmethod |
| 396 |
def from_d(d): |
| 397 |
"""Convert from Service JSON response to `JobEntryPoint` instance""" |
| 398 |
return JobEntryPoint(d['jobId'], d['datasetUUID'], d['datasetType']) |
| 399 |
|
| 400 |
|
| 401 |
class JobStates: |
| 402 |
"""Allowed SMRT Link Service Job states""" |
| 403 |
CREATED = "CREATED" |
| 404 |
SUBMITTED = "SUBMITTED" |
| 405 |
RUNNING = "RUNNING" |
| 406 |
FAILED = "FAILED" |
| 407 |
SUCCESSFUL = "SUCCESSFUL" |
| 408 |
TERMINATED = "TERMINATED" |
| 409 |
ABORTED = "ABORTED" |
| 410 |
|
| 411 |
ALL = (RUNNING, CREATED, FAILED, SUCCESSFUL, SUBMITTED) |
| 412 |
|
| 413 |
|
| 414 |
ALL_COMPLETED = (FAILED, SUCCESSFUL, TERMINATED, ABORTED) |
| 415 |
ALL_FAILED = (FAILED, TERMINATED, ABORTED) |
| 416 |
|
| 417 |
|
| 418 |
class JobTypes: |
| 419 |
"""SMRT Link Analysis JOb Types""" |
| 420 |
IMPORT_DS = "import-dataset" |
| 421 |
IMPORT_DSTORE = "import-datastore" |
| 422 |
MERGE_DS = "merge-datasets" |
| 423 |
CROMWELL = "cromwell" |
| 424 |
ANALYSIS = "analysis" |
| 425 |
MOCK_PB_PIPE = "mock-pbsmrtpipe" |
| 426 |
CONVERT_FASTA = 'convert-fasta-reference' |
| 427 |
|
| 428 |
@classmethod |
| 429 |
def ALL(cls): |
| 430 |
"""ALL allowed SL Analysis Job Types""" |
| 431 |
return (cls.IMPORT_DS, cls.IMPORT_DSTORE, cls.MERGE_DS, |
| 432 |
cls.CROMWELL, cls.MOCK_PB_PIPE, cls.CONVERT_FASTA) |
| 433 |
|
| 434 |
|
| 435 |
class ServiceResourceTypes: |
| 436 |
REPORTS = "reports" |
| 437 |
DATASTORE = "datastore" |
| 438 |
ENTRY_POINTS = "entry-points" |
| 439 |
|
| 440 |
|
| 441 |
def add_smrtlink_server_args(p): |
| 442 |
DEFAULT_HOST = os.environ.get("PB_SERVICE_HOST", "localhost") |
| 443 |
DEFAULT_PORT = int(os.environ.get("PB_SERVICE_PORT", 8000)) |
| 444 |
DEFAULT_USER = os.environ.get("PB_SERVICE_AUTH_USER", None) |
| 445 |
DEFAULT_PASSWORD = os.environ.get("PB_SERVICE_AUTH_PASSWORD", None) |
| 446 |
p.add_argument("--host", |
| 447 |
action="store", |
| 448 |
default=DEFAULT_HOST, |
| 449 |
help="SL Server Hostname") |
| 450 |
p.add_argument("--port", |
| 451 |
action="store", |
| 452 |
type=int, |
| 453 |
default=DEFAULT_PORT, |
| 454 |
help="SL Server Port") |
| 455 |
p.add_argument("--user", |
| 456 |
action="store", |
| 457 |
default=DEFAULT_USER, |
| 458 |
help="SL Server User Name") |
| 459 |
p.add_argument("--password", |
| 460 |
action="store", |
| 461 |
default=DEFAULT_PASSWORD, |
| 462 |
help="SL Server Password") |
| 463 |
return p |