Merge branch 'main' into 18692-frozen-projects-workbench-support
[arvados-workbench2.git] / src / store / virtual-machines / virtual-machines-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 { navigateToUserVirtualMachines, navigateToAdminVirtualMachines, navigateToRootProject } from "store/navigation/navigation-action";
9 import { bindDataExplorerActions } from 'store/data-explorer/data-explorer-action';
10 import { formatDate } from "common/formatters";
11 import { unionize, ofType, UnionOf } from "common/unionize";
12 import { VirtualMachineLogins } from 'models/virtual-machines';
13 import { FilterBuilder } from "services/api/filter-builder";
14 import { ListResults } from "services/common-service/common-service";
15 import { dialogActions } from 'store/dialog/dialog-actions';
16 import { snackbarActions, SnackbarKind } from 'store/snackbar/snackbar-actions';
17 import { PermissionLevel } from "models/permission";
18 import { deleteResources, updateResources } from 'store/resources/resources-actions';
19 import { Participant } from "views-components/sharing-dialog/participant-select";
20 import { initialize, reset } from "redux-form";
21 import { getUserDisplayName, UserResource } from "models/user";
22
23 export const virtualMachinesActions = unionize({
24     SET_REQUESTED_DATE: ofType<string>(),
25     SET_VIRTUAL_MACHINES: ofType<ListResults<any>>(),
26     SET_LOGINS: ofType<VirtualMachineLogins>(),
27     SET_LINKS: ofType<ListResults<any>>()
28 });
29
30 export type VirtualMachineActions = UnionOf<typeof virtualMachinesActions>;
31
32 export const VIRTUAL_MACHINES_PANEL = 'virtualMachinesPanel';
33 export const VIRTUAL_MACHINE_ATTRIBUTES_DIALOG = 'virtualMachineAttributesDialog';
34 export const VIRTUAL_MACHINE_REMOVE_DIALOG = 'virtualMachineRemoveDialog';
35 export const VIRTUAL_MACHINE_ADD_LOGIN_DIALOG = 'virtualMachineAddLoginDialog';
36 export const VIRTUAL_MACHINE_ADD_LOGIN_FORM = 'virtualMachineAddLoginForm';
37 export const VIRTUAL_MACHINE_REMOVE_LOGIN_DIALOG = 'virtualMachineRemoveLoginDialog';
38
39 export const VIRTUAL_MACHINE_UPDATE_LOGIN_UUID_FIELD = 'uuid';
40 export const VIRTUAL_MACHINE_ADD_LOGIN_VM_FIELD = 'vmUuid';
41 export const VIRTUAL_MACHINE_ADD_LOGIN_USER_FIELD = 'user';
42 export const VIRTUAL_MACHINE_ADD_LOGIN_GROUPS_FIELD = 'groups';
43 export const VIRTUAL_MACHINE_ADD_LOGIN_EXCLUDE = 'excludedPerticipants';
44
45 export const openUserVirtualMachines = () =>
46     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
47         dispatch<any>(navigateToUserVirtualMachines);
48     };
49
50 export const openAdminVirtualMachines = () =>
51     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
52         const user = getState().auth.user;
53         if (user && user.isAdmin) {
54             dispatch<any>(navigateToAdminVirtualMachines);
55         } else {
56             dispatch<any>(navigateToRootProject);
57             dispatch(snackbarActions.OPEN_SNACKBAR({ message: "You don't have permissions to view this page", hideDuration: 2000, kind: SnackbarKind.ERROR }));
58         }
59     };
60
61 export const openVirtualMachineAttributes = (uuid: string) =>
62     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
63         const virtualMachineData = getState().virtualMachines.virtualMachines.items.find(it => it.uuid === uuid);
64         dispatch(dialogActions.OPEN_DIALOG({ id: VIRTUAL_MACHINE_ATTRIBUTES_DIALOG, data: { virtualMachineData } }));
65     };
66
67 const loadRequestedDate = () =>
68     (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
69         const date = services.virtualMachineService.getRequestedDate();
70         dispatch(virtualMachinesActions.SET_REQUESTED_DATE(date));
71     };
72
73 export const loadVirtualMachinesAdminData = () =>
74     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
75         dispatch<any>(loadRequestedDate());
76
77         const virtualMachines = await services.virtualMachineService.list();
78         dispatch(updateResources(virtualMachines.items));
79         dispatch(virtualMachinesActions.SET_VIRTUAL_MACHINES(virtualMachines));
80
81
82         const logins = await services.permissionService.list({
83             filters: new FilterBuilder()
84             .addIn('head_uuid', virtualMachines.items.map(item => item.uuid))
85             .addEqual('name', PermissionLevel.CAN_LOGIN)
86             .getFilters()
87         });
88         dispatch(updateResources(logins.items));
89         dispatch(virtualMachinesActions.SET_LINKS(logins));
90
91         const users = await services.userService.list({
92             filters: new FilterBuilder()
93             .addIn('uuid', logins.items.map(item => item.tailUuid))
94             .getFilters(),
95             count: "none"
96         });
97         dispatch(updateResources(users.items));
98
99         const getAllLogins = await services.virtualMachineService.getAllLogins();
100         dispatch(virtualMachinesActions.SET_LOGINS(getAllLogins));
101     };
102
103 export const loadVirtualMachinesUserData = () =>
104     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
105         dispatch<any>(loadRequestedDate());
106         const virtualMachines = await services.virtualMachineService.list();
107         const virtualMachinesUuids = virtualMachines.items.map(it => it.uuid);
108         const links = await services.linkService.list({
109             filters: new FilterBuilder()
110                 .addIn("head_uuid", virtualMachinesUuids)
111                 .getFilters()
112         });
113         dispatch(virtualMachinesActions.SET_VIRTUAL_MACHINES(virtualMachines));
114         dispatch(virtualMachinesActions.SET_LINKS(links));
115     };
116
117 export const openAddVirtualMachineLoginDialog = (vmUuid: string) =>
118     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
119         // Get login permissions of vm
120         const virtualMachines = await services.virtualMachineService.list();
121         dispatch(updateResources(virtualMachines.items));
122         const logins = await services.permissionService.list({
123             filters: new FilterBuilder()
124             .addIn('head_uuid', virtualMachines.items.map(item => item.uuid))
125             .addEqual('name', PermissionLevel.CAN_LOGIN)
126             .getFilters()
127         });
128         dispatch(updateResources(logins.items));
129
130         dispatch(initialize(VIRTUAL_MACHINE_ADD_LOGIN_FORM, {
131                 [VIRTUAL_MACHINE_ADD_LOGIN_VM_FIELD]: vmUuid,
132                 [VIRTUAL_MACHINE_ADD_LOGIN_GROUPS_FIELD]: [],
133             }));
134         dispatch(dialogActions.OPEN_DIALOG( {id: VIRTUAL_MACHINE_ADD_LOGIN_DIALOG, data: {excludedParticipants: logins.items.map(it => it.tailUuid)}} ));
135     }
136
137 export const openEditVirtualMachineLoginDialog = (permissionUuid: string) =>
138     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
139         const login = await services.permissionService.get(permissionUuid);
140         const user = await services.userService.get(login.tailUuid);
141         dispatch(initialize(VIRTUAL_MACHINE_ADD_LOGIN_FORM, {
142                 [VIRTUAL_MACHINE_UPDATE_LOGIN_UUID_FIELD]: permissionUuid,
143                 [VIRTUAL_MACHINE_ADD_LOGIN_USER_FIELD]: {name: getUserDisplayName(user, true, true), uuid: login.tailUuid},
144                 [VIRTUAL_MACHINE_ADD_LOGIN_GROUPS_FIELD]: login.properties.groups,
145             }));
146         dispatch(dialogActions.OPEN_DIALOG( {id: VIRTUAL_MACHINE_ADD_LOGIN_DIALOG, data: {updating: true}} ));
147     }
148
149 export interface AddLoginFormData {
150     [VIRTUAL_MACHINE_UPDATE_LOGIN_UUID_FIELD]: string;
151     [VIRTUAL_MACHINE_ADD_LOGIN_VM_FIELD]: string;
152     [VIRTUAL_MACHINE_ADD_LOGIN_USER_FIELD]: Participant;
153     [VIRTUAL_MACHINE_ADD_LOGIN_GROUPS_FIELD]: string[];
154 }
155
156
157 export const addUpdateVirtualMachineLogin = ({uuid, vmUuid, user, groups}: AddLoginFormData) =>
158     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
159         let userResource: UserResource | undefined = undefined;
160         try {
161             // Get user
162             userResource = await services.userService.get(user.uuid, false);
163         } catch (e) {
164                 dispatch(snackbarActions.OPEN_SNACKBAR({ message: "Failed to get user details.", hideDuration: 2000, kind: SnackbarKind.ERROR }));
165                 return;
166         }
167         try {
168             if (uuid) {
169                 const permission = await services.permissionService.update(uuid, {
170                     tailUuid: userResource.uuid,
171                     name: PermissionLevel.CAN_LOGIN,
172                     properties: {
173                         username: userResource.username,
174                         groups,
175                     }
176                 });
177                 dispatch(updateResources([permission]));
178             } else {
179                 const permission = await services.permissionService.create({
180                     headUuid: vmUuid,
181                     tailUuid: userResource.uuid,
182                     name: PermissionLevel.CAN_LOGIN,
183                     properties: {
184                         username: userResource.username,
185                         groups,
186                     }
187                 });
188                 dispatch(updateResources([permission]));
189             }
190
191             dispatch(reset(VIRTUAL_MACHINE_ADD_LOGIN_FORM));
192             dispatch(dialogActions.CLOSE_DIALOG({ id: VIRTUAL_MACHINE_ADD_LOGIN_DIALOG }));
193             dispatch<any>(loadVirtualMachinesAdminData());
194
195             dispatch(snackbarActions.OPEN_SNACKBAR({
196                 message: `Permission updated`,
197                 kind: SnackbarKind.SUCCESS
198             }));
199         } catch (e) {
200             dispatch(snackbarActions.OPEN_SNACKBAR({ message: e.message, hideDuration: 2000, kind: SnackbarKind.ERROR }));
201         }
202     };
203
204 export const openRemoveVirtualMachineLoginDialog = (uuid: string) =>
205     (dispatch: Dispatch, getState: () => RootState) => {
206         dispatch(dialogActions.OPEN_DIALOG({
207             id: VIRTUAL_MACHINE_REMOVE_LOGIN_DIALOG,
208             data: {
209                 title: 'Remove login permission',
210                 text: 'Are you sure you want to remove this permission?',
211                 confirmButtonLabel: 'Remove',
212                 uuid
213             }
214         }));
215     };
216
217 export const removeVirtualMachineLogin = (uuid: string) =>
218     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
219         try {
220             await services.permissionService.delete(uuid);
221             dispatch<any>(deleteResources([uuid]));
222
223             dispatch<any>(loadVirtualMachinesAdminData());
224
225             dispatch(snackbarActions.OPEN_SNACKBAR({
226                 message: `Login permission removed`,
227                 kind: SnackbarKind.SUCCESS
228             }));
229         } catch (e) {
230             dispatch(snackbarActions.OPEN_SNACKBAR({ message: e.message, hideDuration: 2000, kind: SnackbarKind.ERROR }));
231         }
232     };
233
234 export const saveRequestedDate = () =>
235     (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
236         const date = formatDate((new Date()).toISOString());
237         services.virtualMachineService.saveRequestedDate(date);
238         dispatch<any>(loadRequestedDate());
239     };
240
241 export const openRemoveVirtualMachineDialog = (uuid: string) =>
242     (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
243         dispatch(dialogActions.OPEN_DIALOG({
244             id: VIRTUAL_MACHINE_REMOVE_DIALOG,
245             data: {
246                 title: 'Remove virtual machine',
247                 text: 'Are you sure you want to remove this virtual machine?',
248                 confirmButtonLabel: 'Remove',
249                 uuid
250             }
251         }));
252     };
253
254 export const removeVirtualMachine = (uuid: string) =>
255     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
256         dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Removing ...', kind: SnackbarKind.INFO }));
257         await services.virtualMachineService.delete(uuid);
258         dispatch(snackbarActions.OPEN_SNACKBAR({ message: 'Removed.', hideDuration: 2000, kind: SnackbarKind.SUCCESS }));
259         dispatch<any>(loadVirtualMachinesAdminData());
260     };
261
262 const virtualMachinesBindedActions = bindDataExplorerActions(VIRTUAL_MACHINES_PANEL);
263
264 export const loadVirtualMachinesPanel = () =>
265     (dispatch: Dispatch) => {
266         dispatch(virtualMachinesBindedActions.REQUEST_ITEMS());
267     };