19319: Add cost field to loadContainers select query to prevent clearing cost race...
[arvados-workbench2.git] / src / store / processes / processes-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 { RootState } from 'store/store';
7 import { ServiceRepository } from 'services/services';
8 import { updateResources } from 'store/resources/resources-actions';
9 import { Process } from './process';
10 import { dialogActions } from 'store/dialog/dialog-actions';
11 import { snackbarActions, SnackbarKind } from 'store/snackbar/snackbar-actions';
12 import { projectPanelActions } from 'store/project-panel/project-panel-action';
13 import { navigateToRunProcess } from 'store/navigation/navigation-action';
14 import { goToStep, runProcessPanelActions } from 'store/run-process-panel/run-process-panel-actions';
15 import { getResource } from 'store/resources/resources';
16 import { initialize } from "redux-form";
17 import { RUN_PROCESS_BASIC_FORM, RunProcessBasicFormData } from "views/run-process-panel/run-process-basic-form";
18 import { RunProcessAdvancedFormData, RUN_PROCESS_ADVANCED_FORM } from "views/run-process-panel/run-process-advanced-form";
19 import { MOUNT_PATH_CWL_WORKFLOW, MOUNT_PATH_CWL_INPUT } from 'models/process';
20 import { CommandInputParameter, getWorkflow, getWorkflowInputs, getWorkflowOutputs } from "models/workflow";
21 import { ProjectResource } from "models/project";
22 import { UserResource } from "models/user";
23 import { CommandOutputParameter } from "cwlts/mappings/v1.0/CommandOutputParameter";
24
25 export const loadProcess = (containerRequestUuid: string) =>
26     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository): Promise<Process> => {
27         const containerRequest = await services.containerRequestService.get(containerRequestUuid);
28         dispatch<any>(updateResources([containerRequest]));
29
30         if (containerRequest.outputUuid) {
31             const collection = await services.collectionService.get(containerRequest.outputUuid);
32             dispatch<any>(updateResources([collection]));
33         }
34
35         if (containerRequest.containerUuid) {
36             const container = await services.containerService.get(containerRequest.containerUuid);
37             dispatch<any>(updateResources([container]));
38             if (container.runtimeUserUuid) {
39                 const runtimeUser = await services.userService.get(container.runtimeUserUuid);
40                 dispatch<any>(updateResources([runtimeUser]));
41             }
42             return { containerRequest, container };
43         }
44         return { containerRequest };
45     };
46
47 export const loadContainers = (filters: string, loadMounts: boolean = true) =>
48     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
49         let args: any = { filters };
50         if (!loadMounts) {
51             args.select = containerFieldsNoMounts;
52         }
53         const { items } = await services.containerService.list(args);
54         dispatch<any>(updateResources(items));
55         return items;
56     };
57
58 // Until the api supports unselecting fields, we need a list of all other fields to omit mounts
59 const containerFieldsNoMounts = [
60     "auth_uuid",
61     "command",
62     "container_image",
63     "cost",
64     "created_at",
65     "cwd",
66     "environment",
67     "etag",
68     "exit_code",
69     "finished_at",
70     "gateway_address",
71     "href",
72     "interactive_session_started",
73     "kind",
74     "lock_count",
75     "locked_by_uuid",
76     "log",
77     "modified_at",
78     "modified_by_client_uuid",
79     "modified_by_user_uuid",
80     "output_path",
81     "output_properties",
82     "output_storage_classes",
83     "output",
84     "owner_uuid",
85     "priority",
86     "progress",
87     "runtime_auth_scopes",
88     "runtime_constraints",
89     "runtime_status",
90     "runtime_user_uuid",
91     "scheduling_parameters",
92     "started_at",
93     "state",
94     "uuid",
95 ]
96
97 export const cancelRunningWorkflow = (uuid: string) =>
98     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
99         try {
100             const process = await services.containerRequestService.update(uuid, { priority: 0 });
101             return process;
102         } catch (e) {
103             throw new Error('Could not cancel the process.');
104         }
105     };
106
107 export const reRunProcess = (processUuid: string, workflowUuid: string) =>
108     (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
109         const process = getResource<any>(processUuid)(getState().resources);
110         const workflows = getState().runProcessPanel.searchWorkflows;
111         const workflow = workflows.find(workflow => workflow.uuid === workflowUuid);
112         if (workflow && process) {
113             const mainWf = getWorkflow(process.mounts[MOUNT_PATH_CWL_WORKFLOW]);
114             if (mainWf) { mainWf.inputs = getInputs(process); }
115             const stringifiedDefinition = JSON.stringify(process.mounts[MOUNT_PATH_CWL_WORKFLOW].content);
116             const newWorkflow = { ...workflow, definition: stringifiedDefinition };
117
118             const owner = getResource<ProjectResource | UserResource>(workflow.ownerUuid)(getState().resources);
119             const basicInitialData: RunProcessBasicFormData = { name: `Copy of: ${process.name}`, description: process.description, owner };
120             dispatch<any>(initialize(RUN_PROCESS_BASIC_FORM, basicInitialData));
121
122             const advancedInitialData: RunProcessAdvancedFormData = {
123                 output: process.outputName,
124                 runtime: process.schedulingParameters.max_run_time,
125                 ram: process.runtimeConstraints.ram,
126                 vcpus: process.runtimeConstraints.vcpus,
127                 keep_cache_ram: process.runtimeConstraints.keep_cache_ram,
128                 acr_container_image: process.containerImage
129             };
130             dispatch<any>(initialize(RUN_PROCESS_ADVANCED_FORM, advancedInitialData));
131
132             dispatch<any>(navigateToRunProcess);
133             dispatch<any>(goToStep(1));
134             dispatch(runProcessPanelActions.SET_STEP_CHANGED(true));
135             dispatch(runProcessPanelActions.SET_SELECTED_WORKFLOW(newWorkflow));
136         } else {
137             dispatch<any>(snackbarActions.OPEN_SNACKBAR({ message: `You can't re-run this process`, kind: SnackbarKind.ERROR }));
138         }
139     };
140
141 /*
142  * Fetches raw inputs from containerRequest mounts with fallback to properties
143  * Returns undefined if containerRequest not loaded
144  * Returns [] if inputs not found in mounts or props
145  */
146 export const getRawInputs = (data: any): CommandInputParameter[] | undefined => {
147     if (!data) { return undefined; }
148     const mountInput = data.mounts?.[MOUNT_PATH_CWL_INPUT]?.content;
149     const propsInput = data.properties?.cwl_input;
150     if (!mountInput && !propsInput) { return []; }
151     return (mountInput || propsInput);
152 }
153
154 export const getInputs = (data: any): CommandInputParameter[] => {
155     // Definitions from mounts are needed so we return early if missing
156     if (!data || !data.mounts || !data.mounts[MOUNT_PATH_CWL_WORKFLOW]) { return []; }
157     const content  = getRawInputs(data) as any;
158     if (!content) { return []; }
159
160     const inputs = getWorkflowInputs(data.mounts[MOUNT_PATH_CWL_WORKFLOW].content);
161     return inputs ? inputs.map(
162         (it: any) => (
163             {
164                 type: it.type,
165                 id: it.id,
166                 label: it.label,
167                 default: content[it.id],
168                 value: content[it.id.split('/').pop()] || [],
169                 doc: it.doc
170             }
171         )
172     ) : [];
173 };
174
175 /*
176  * Fetches raw outputs from containerRequest properties
177  * Assumes containerRequest is loaded
178  */
179 export const getRawOutputs = (data: any): CommandInputParameter[] | undefined => {
180     if (!data || !data.properties || !data.properties.cwl_output) { return undefined; }
181     return (data.properties.cwl_output);
182 }
183
184 export type InputCollectionMount = {
185     path: string;
186     pdh: string;
187 }
188
189 export const getInputCollectionMounts = (data: any): InputCollectionMount[] => {
190     if (!data || !data.mounts) { return []; }
191     return Object.keys(data.mounts)
192         .map(key => ({
193             ...data.mounts[key],
194             path: key,
195         }))
196         .filter(mount => mount.kind === 'collection' &&
197                 mount.portable_data_hash &&
198                 mount.path)
199         .map(mount => ({
200             path: mount.path,
201             pdh: mount.portable_data_hash,
202         }));
203 };
204
205 export const getOutputParameters = (data: any): CommandOutputParameter[] => {
206     if (!data || !data.mounts || !data.mounts[MOUNT_PATH_CWL_WORKFLOW]) { return []; }
207     const outputs = getWorkflowOutputs(data.mounts[MOUNT_PATH_CWL_WORKFLOW].content);
208     return outputs ? outputs.map(
209         (it: any) => (
210             {
211                 type: it.type,
212                 id: it.id,
213                 label: it.label,
214                 doc: it.doc
215             }
216         )
217     ) : [];
218 };
219
220 export const openRemoveProcessDialog = (uuid: string) =>
221     (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
222         dispatch(dialogActions.OPEN_DIALOG({
223             id: REMOVE_PROCESS_DIALOG,
224             data: {
225                 title: 'Remove process permanently',
226                 text: 'Are you sure you want to remove this process?',
227                 confirmButtonLabel: 'Remove',
228                 uuid
229             }
230         }));
231     };
232
233 export const REMOVE_PROCESS_DIALOG = 'removeProcessDialog';
234
235 export const removeProcessPermanently = (uuid: string) =>
236     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
237         dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Removing ...', kind: SnackbarKind.INFO }));
238         await services.containerRequestService.delete(uuid);
239         dispatch(projectPanelActions.REQUEST_ITEMS());
240         dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Removed.', hideDuration: 2000, kind: SnackbarKind.SUCCESS }));
241     };