Merge branch '20990-name-btree' refs #20990
[arvados.git] / services / workbench2 / src / store / run-process-panel / run-process-panel-actions.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { Dispatch } from 'redux';
6 import { unionize, ofType, UnionOf } from "common/unionize";
7 import { ServiceRepository } from "services/services";
8 import { RootState } from 'store/store';
9 import { getUserUuid } from "common/getuser";
10 import { WorkflowResource, WorkflowRunnerResources, getWorkflow, getWorkflowInputs, parseWorkflowDefinition } from 'models/workflow';
11 import { getFormValues, initialize } from 'redux-form';
12 import { RUN_PROCESS_BASIC_FORM, RunProcessBasicFormData } from 'views/run-process-panel/run-process-basic-form';
13 import { RUN_PROCESS_INPUTS_FORM } from 'views/run-process-panel/run-process-inputs-form';
14 import { WorkflowInputsData } from 'models/workflow';
15 import { createWorkflowMounts } from 'models/process';
16 import { ContainerRequestState } from 'models/container-request';
17 import { navigateTo } from '../navigation/navigation-action';
18 import {
19     RunProcessAdvancedFormData, RUN_PROCESS_ADVANCED_FORM, VCPUS_FIELD,
20     KEEP_CACHE_RAM_FIELD, RAM_FIELD, RUNTIME_FIELD, OUTPUT_FIELD, RUNNER_IMAGE_FIELD
21 } from 'views/run-process-panel/run-process-advanced-form';
22 import { dialogActions } from 'store/dialog/dialog-actions';
23 import { setBreadcrumbs } from 'store/breadcrumbs/breadcrumbs-actions';
24 import { getResource } from 'store/resources/resources';
25 import { ProjectResource } from "models/project";
26 import { UserResource } from "models/user";
27
28 export const runProcessPanelActions = unionize({
29     SET_PROCESS_PATHNAME: ofType<string>(),
30     SET_PROCESS_OWNER_UUID: ofType<string>(),
31     SET_CURRENT_STEP: ofType<number>(),
32     SET_STEP_CHANGED: ofType<boolean>(),
33     SET_WORKFLOWS: ofType<WorkflowResource[]>(),
34     SET_SELECTED_WORKFLOW: ofType<WorkflowResource>(),
35     SET_WORKFLOW_PRESETS: ofType<WorkflowResource[]>(),
36     SELECT_WORKFLOW_PRESET: ofType<WorkflowResource>(),
37     SEARCH_WORKFLOWS: ofType<string>(),
38     RESET_RUN_PROCESS_PANEL: ofType<{}>(),
39 });
40
41 export interface RunProcessSecondStepDataFormProps {
42     name: string;
43     description: string;
44 }
45
46 export const SET_WORKFLOW_DIALOG = 'setWorkflowDialog';
47 export const RUN_PROCESS_SECOND_STEP_FORM_NAME = 'runProcessSecondStepFormName';
48
49 export type RunProcessPanelAction = UnionOf<typeof runProcessPanelActions>;
50
51 export const loadRunProcessPanel = () =>
52     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
53         try {
54             dispatch(setBreadcrumbs([{ label: 'Run Process' }]));
55             const response = await services.workflowService.list();
56             dispatch(runProcessPanelActions.SET_WORKFLOWS(response.items));
57         } catch (e) {
58             return;
59         }
60     };
61
62 export const openSetWorkflowDialog = (workflow: WorkflowResource) =>
63     (dispatch: Dispatch, getState: () => RootState) => {
64         const selectedWorkflow = getState().runProcessPanel.selectedWorkflow;
65         const isStepChanged = getState().runProcessPanel.isStepChanged;
66         if (isStepChanged && selectedWorkflow && selectedWorkflow.uuid !== workflow.uuid) {
67             dispatch(dialogActions.OPEN_DIALOG({
68                 id: SET_WORKFLOW_DIALOG,
69                 data: {
70                     title: 'Form will be cleared',
71                     text: 'Changing a workflow will clean all input fields in next step.',
72                     confirmButtonLabel: 'Change Workflow',
73                     workflow
74                 }
75             }));
76         } else {
77             dispatch<any>(setWorkflow(workflow, false));
78         }
79     };
80
81 export const getWorkflowRunnerSettings = (workflow: WorkflowResource) => {
82     const advancedFormValues = {};
83     Object.assign(advancedFormValues, DEFAULT_ADVANCED_FORM_VALUES);
84
85     const wf = getWorkflow(parseWorkflowDefinition(workflow));
86     const hints = wf ? wf.hints : undefined;
87     if (hints) {
88         const resc = hints.find(item => item.class === 'http://arvados.org/cwl#WorkflowRunnerResources') as WorkflowRunnerResources | undefined;
89         if (resc) {
90             if (resc.ramMin) { advancedFormValues[RAM_FIELD] = resc.ramMin * (1024 * 1024); }
91             if (resc.coresMin) { advancedFormValues[VCPUS_FIELD] = resc.coresMin; }
92             if (resc.keep_cache) { advancedFormValues[KEEP_CACHE_RAM_FIELD] = resc.keep_cache * (1024 * 1024); }
93             if (resc.acrContainerImage) { advancedFormValues[RUNNER_IMAGE_FIELD] = resc.acrContainerImage; }
94         }
95     }
96     return advancedFormValues;
97 };
98
99 export const setWorkflow = (workflow: WorkflowResource, isWorkflowChanged = true) =>
100     (dispatch: Dispatch<any>, getState: () => RootState) => {
101         const isStepChanged = getState().runProcessPanel.isStepChanged;
102
103         const advancedFormValues = getWorkflowRunnerSettings(workflow);
104
105         let owner = getResource<ProjectResource | UserResource>(getState().runProcessPanel.processOwnerUuid)(getState().resources);
106         const userUuid = getUserUuid(getState());
107         if (!owner || !owner.canWrite) {
108             owner = undefined;
109         }
110
111         if (isStepChanged && isWorkflowChanged) {
112             dispatch(runProcessPanelActions.SET_STEP_CHANGED(false));
113             dispatch(runProcessPanelActions.SET_SELECTED_WORKFLOW(workflow));
114             dispatch<any>(loadPresets(workflow.uuid));
115             dispatch(initialize(RUN_PROCESS_BASIC_FORM, { name: workflow.name, owner }));
116             dispatch(initialize(RUN_PROCESS_ADVANCED_FORM, advancedFormValues));
117         }
118         if (!isWorkflowChanged) {
119             dispatch(runProcessPanelActions.SET_SELECTED_WORKFLOW(workflow));
120             dispatch<any>(loadPresets(workflow.uuid));
121             dispatch(initialize(RUN_PROCESS_BASIC_FORM, { name: workflow.name, owner }));
122             dispatch(initialize(RUN_PROCESS_ADVANCED_FORM, advancedFormValues));
123         }
124     };
125
126 export const loadPresets = (workflowUuid: string) =>
127     async (dispatch: Dispatch<any>, _: () => RootState, { workflowService }: ServiceRepository) => {
128         const { items } = await workflowService.presets(workflowUuid);
129         dispatch(runProcessPanelActions.SET_WORKFLOW_PRESETS(items));
130     };
131
132 export const selectPreset = (preset: WorkflowResource) =>
133     (dispatch: Dispatch<any>) => {
134         dispatch(runProcessPanelActions.SELECT_WORKFLOW_PRESET(preset));
135         const inputs = getWorkflowInputs(parseWorkflowDefinition(preset)) || [];
136         const values = inputs.reduce((values, input) => ({
137             ...values,
138             [input.id]: input.default,
139         }), {});
140         dispatch(initialize(RUN_PROCESS_INPUTS_FORM, values));
141     };
142
143 export const goToStep = (step: number) =>
144     (dispatch: Dispatch) => {
145         if (step === 1) {
146             dispatch(runProcessPanelActions.SET_STEP_CHANGED(true));
147         }
148         dispatch(runProcessPanelActions.SET_CURRENT_STEP(step));
149     };
150
151 export const runProcess = async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
152     const state = getState();
153     const basicForm = getFormValues(RUN_PROCESS_BASIC_FORM)(state) as RunProcessBasicFormData;
154     const inputsForm = getFormValues(RUN_PROCESS_INPUTS_FORM)(state) as WorkflowInputsData;
155     const userUuid = getUserUuid(getState());
156     if (!userUuid) { return; }
157     const { processOwnerUuid, selectedWorkflow } = state.runProcessPanel;
158     const ownerUUid = basicForm.owner ? basicForm.owner.uuid : (processOwnerUuid ? processOwnerUuid : userUuid);
159     if (selectedWorkflow) {
160         const advancedForm = getFormValues(RUN_PROCESS_ADVANCED_FORM)(state) as RunProcessAdvancedFormData || getWorkflowRunnerSettings(selectedWorkflow);
161         const newProcessData = {
162             ownerUuid: ownerUUid,
163             name: basicForm.name,
164             description: basicForm.description,
165             state: ContainerRequestState.COMMITTED,
166             mounts: createWorkflowMounts(selectedWorkflow, normalizeInputKeys(inputsForm)),
167             runtimeConstraints: {
168                 API: true,
169                 vcpus: advancedForm[VCPUS_FIELD],
170                 ram: (advancedForm[KEEP_CACHE_RAM_FIELD] + advancedForm[RAM_FIELD]),
171             },
172             schedulingParameters: {
173                 max_run_time: advancedForm[RUNTIME_FIELD]
174             },
175             containerImage: advancedForm[RUNNER_IMAGE_FIELD],
176             cwd: '/var/spool/cwl',
177             command: [
178                 'arvados-cwl-runner',
179                 '--api=containers',
180                 '--local',
181                 `--project-uuid=${ownerUUid}`,
182                 '/var/lib/cwl/workflow.json#main',
183                 '/var/lib/cwl/cwl.input.json'
184             ],
185             outputPath: '/var/spool/cwl',
186             priority: 500,
187             outputName: advancedForm[OUTPUT_FIELD] ? advancedForm[OUTPUT_FIELD] : `Output from ${basicForm.name}`,
188             properties: {
189                 template_uuid: selectedWorkflow.uuid,
190                 workflowName: selectedWorkflow.name
191             },
192             useExisting: false
193         };
194         const newProcess = await services.containerRequestService.create(newProcessData);
195         dispatch(navigateTo(newProcess.uuid));
196     }
197 };
198
199 const DEFAULT_ADVANCED_FORM_VALUES: Partial<RunProcessAdvancedFormData> = {
200     [VCPUS_FIELD]: 1,
201     [RAM_FIELD]: 1073741824,
202     [KEEP_CACHE_RAM_FIELD]: 268435456,
203     [RUNNER_IMAGE_FIELD]: "arvados/jobs"
204 };
205
206 const normalizeInputKeys = (inputs: WorkflowInputsData): WorkflowInputsData =>
207     Object.keys(inputs).reduce((normalizedInputs, key) => ({
208         ...normalizedInputs,
209         [key.split('/').slice(1).join('/')]: inputs[key],
210     }), {});
211 export const searchWorkflows = (term: string) => runProcessPanelActions.SEARCH_WORKFLOWS(term);