Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
150 changes: 149 additions & 1 deletion dnastack/cli/commands/workbench/runs/commands.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import os
import uuid
from functools import cache
from http import HTTPStatus
from typing import Optional, Iterable, List

import click
Expand All @@ -16,11 +17,41 @@
from dnastack.cli.helpers.iterator_printer import show_iterator, OutputFormat
from dnastack.client.workbench.ewes.models import ExtendedRunListOptions, ExtendedRunRequest, \
BatchRunRequest, \
MinimalExtendedRunWithOutputs, MinimalExtendedRunWithInputs, ExecutionEngineListOptions, SimpleSample
MinimalExtendedRunWithOutputs, MinimalExtendedRunWithInputs, ExecutionEngineListOptions, SimpleSample, \
OrchestrationRequest, OrchestrationRunRequestTemplate, EngineParamPresetListOptions
from dnastack.client.workbench.ewes.client import EWesClient
from dnastack.client.workbench.common.models import State
from dnastack.client.workbench.ewes.models import LogType
from dnastack.common.json_argument_parser import JsonLike, parse_and_merge_arguments, merge, merge_param_json_data
from dnastack.common.tracing import Span
from dnastack.http.session import ClientError


def _get_default_engine_id(ewes_client: EWesClient) -> str:
for engine in ewes_client.list_engines(ExecutionEngineListOptions()):
if engine.default:
return engine.id
raise NoDefaultEngineError("No default engine found. Please specify an engine id using the --engine flag.")


def _resolve_engine_parameters(ewes_client: EWesClient, engine_id: str, engine_params: Optional[JsonLike]) -> dict:
if not engine_params:
default_preset = next((preset for preset in
ewes_client.list_engine_param_presets(engine_id, EngineParamPresetListOptions())
if preset.default), None)
return {'engine_id': engine_id, **(default_preset.preset_values if default_preset else {})}

[param_ids_list, kv_pairs_list, json_literals_list, files_list] = engine_params.extract_arguments_list()
resolved = merge_param_json_data(kv_pairs_list, json_literals_list, files_list)
for param_id in param_ids_list or []:
try:
preset = ewes_client.get_engine_param_preset(engine_id, param_id)
except ClientError as e:
if e.response.status_code != HTTPStatus.NOT_FOUND:
raise
raise UnableToFindParameterError(f"Unable to find engine parameter preset with id {param_id}. {e}")
merge(resolved, preset.preset_values)
return resolved


def init_runs_commands(group: Group):
Expand Down Expand Up @@ -660,3 +691,120 @@ def get_default_engine_id():
else:
minimal_batch = ewes_client.submit_batch(batch_request)
click.echo(to_json(normalize(minimal_batch)))

@formatted_command(
group=group,
name='orchestrate',
specs=[
ArgumentSpec(
name='workflow',
arg_names=['--workflow'],
help='The id of the workflow to run.',
required=True,
),
ArgumentSpec(
name='version',
arg_names=['--version'],
help='The version of the workflow to run.',
required=True,
),
ArgumentSpec(
name='samples',
arg_names=['--sample'],
help='The ID of a sample to run the workflow on. Can be specified multiple times. '
'The server decides how the samples are grouped into runs.',
multiple=True,
),
ArgumentSpec(
name='storage_account_id',
arg_names=['--storage-account'],
help='The storage account ID that the samples belong to. ' + STORAGE_ACCOUNT_DEFAULT_HELP,
),
ArgumentSpec(
name='engine_id',
arg_names=['--engine'],
help='Use the given engine id for execution of runs. If this value is not defined then the '
'default engine will be used.',
),
ArgumentSpec(
name='engine_params',
arg_names=['--engine-params'],
help='Set the engine parameters for all runs. '
'Engine params can be specified as inlined JSON, json file preceded by the "@" symbol, '
'KV pair, parameter preset ID, or as a comma-separated-list containing any of those types '
'(e.g. my-preset-id,key=value,\'{"literal":"json"}\',@file.json). '
'If not specified, the default parameter preset of the engine is used.',
type=JsonLike,
),
ArgumentSpec(
name='tags',
help='Set the tags for all runs. '
'Tags must be a JSON object, given as inline JSON, comma separated key=value pairs or '
'a json file referenced preceded by the "@" symbol.',
type=JsonLike,
),
ArgumentSpec(
name='dry_run',
arg_names=['--dry-run'],
help='Ask the server how the samples would be grouped into runs, and print that plan. '
'No runs are created. This differs from "runs submit --dry-run", which only prints '
'the request and calls nothing.',
type=bool,
),
ArgumentSpec(
name='no_ingest_variants',
arg_names=['--no-ingest-variants'],
help='Do not run the variant ingestion step. Without this flag the server decides: it ingests '
'variants when the workflow is labelled "tertiary". This applies to the workflow named '
'here, not to the prerequisite workflows the server adds.',
type=bool,
),
NAMESPACE_ARG,
CONTEXT_ARG,
SINGLE_ENDPOINT_ID_ARG,
]
)
def orchestrate(context: Optional[str],
endpoint_id: Optional[str],
namespace: Optional[str],
workflow: str,
version: str,
samples: List[str],
storage_account_id: Optional[str],
engine_id: Optional[str],
engine_params: Optional[JsonLike],
tags: Optional[JsonLike],
dry_run: bool,
no_ingest_variants: bool):
"""
Create runs of a workflow from samples, grouped by the server

The server decides how the samples are grouped into runs, as Workbench does when you select samples.
"""
if not samples:
raise click.UsageError('You must specify at least one --sample.')

ewes_client = get_ewes_client(context_name=context, endpoint_id=endpoint_id, namespace=namespace)
storage_account_id = resolve_storage_account_id(storage_account_id,
context_name=context,
namespace=ewes_client.namespace)
engine_id = engine_id or _get_default_engine_id(ewes_client)

template_fields = {'ingest_variants': False} if no_ingest_variants else {}
request = OrchestrationRequest(
samples=[SimpleSample(id=sample_id, storage_account_id=storage_account_id) for sample_id in samples],
request_templates=[OrchestrationRunRequestTemplate(
workflow_id=workflow,
workflow_version_id=version,
workflow_url=f'{workflow}/{version}',
workflow_type='WDL',
engine_id=engine_id,
default_workflow_engine_parameters=_resolve_engine_parameters(ewes_client, engine_id, engine_params),
**template_fields,
)],
engine_id=engine_id,
dry_run=bool(dry_run),
**({'tags': tags.parsed_value()} if tags else {}),
)

click.echo(to_json(normalize(ewes_client.orchestrate(request))))
10 changes: 9 additions & 1 deletion dnastack/client/workbench/ewes/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
from dnastack.client.workbench.ewes.models import ExtendedRunEvents, WesServiceInfo, ExtendedRunStatus, \
ExtendedRunListOptions, \
ExtendedRunListResponse, ExtendedRun, RunId, WorkbenchApiError, BatchActionResult, MinimalExtendedRun, \
BatchRunResponse, BatchRunRequest, ExtendedRunRequest, Log, TaskListOptions, \
BatchRunResponse, BatchRunRequest, ExtendedRunRequest, OrchestrationRequest, OrchestrationRunsResponse, \
Log, TaskListOptions, \
TaskListResponse, LogType, ExecutionEngineListOptions, ExecutionEngineListResponse, ExecutionEngine, \
EngineParamPreset, EngineParamPresetListOptions, EngineParamPresetListResponse, \
EngineHealthCheck, EngineHealthCheckListOptions, EngineHealthCheckListResponse, \
Expand Down Expand Up @@ -234,6 +235,13 @@ def submit_batch(self, data: BatchRunRequest, trace: Optional[Span] = None) -> B
trace_context=trace)
return BatchRunResponse(**response.json())

def orchestrate(self, data: OrchestrationRequest, trace: Optional[Span] = None) -> OrchestrationRunsResponse:
with self.create_http_session() as session:
response = session.post(urljoin(self.endpoint.url, f'{self.namespace}/ga4gh/wes/v1/runs/orchestrate'),
json=data.model_dump(exclude_unset=True),
trace_context=trace)
return OrchestrationRunsResponse(**response.json())

def stream_run_logs(self,
run_id: str,
log_type: LogType = LogType.STDOUT,
Expand Down
28 changes: 28 additions & 0 deletions dnastack/client/workbench/ewes/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,34 @@ class BatchRunResponse(BaseModel):
runs: List[MinimalExtendedRun]


class OrchestrationRunRequestTemplate(BaseModel):
workflow_id: str
workflow_version_id: str
workflow_url: str
workflow_type: str
engine_id: Optional[str] = None
default_workflow_engine_parameters: Optional[Dict] = None
ingest_variants: Optional[bool] = None


class OrchestrationRequest(BaseModel):
samples: List[SimpleSample]
request_templates: List[OrchestrationRunRequestTemplate]
engine_id: Optional[str] = None
tags: Optional[Dict] = None
dry_run: bool = False


class OrchestrationRun(BaseModel):
samples: List[SimpleSample]
runs: List[Dict]


class OrchestrationRunsResponse(BaseModel):
orchestration_runs: List[OrchestrationRun]
grouping: Optional[List[Dict]] = None


class RunId(BaseModel):
run_id: str
state: Optional[State] = None
Expand Down
Loading
Loading