Merge branch 'main' into 21720-material-ui-upgrade
[arvados.git] / services / workbench2 / src / views / virtual-machine-panel / virtual-machine-user-panel.tsx
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import React from 'react';
6 import { connect } from 'react-redux';
7 import { Grid, Typography, Button, Card, CardContent, TableBody, TableCell, TableHead, TableRow, Table, Tooltip, Chip } from '@mui/material';
8 import { CustomStyleRulesCallback } from 'common/custom-theme';
9 import { WithStyles } from '@mui/styles';
10 import withStyles from '@mui/styles/withStyles';
11 import { ArvadosTheme } from 'common/custom-theme';
12 import { compose, Dispatch } from 'redux';
13 import { saveRequestedDate, loadVirtualMachinesUserData } from 'store/virtual-machines/virtual-machines-actions';
14 import { RootState } from 'store/store';
15 import { ListResults } from 'services/common-service/common-service';
16 import { HelpIcon } from 'components/icon/icon';
17 import { SESSION_STORAGE } from "services/auth-service/auth-service";
18 // import * as CopyToClipboard from 'react-copy-to-clipboard';
19 import parse from "parse-duration";
20 import { CopyIcon } from 'components/icon/icon';
21 import CopyToClipboard from 'react-copy-to-clipboard';
22 import { snackbarActions, SnackbarKind } from 'store/snackbar/snackbar-actions';
23 import { sanitizeHTML } from 'common/html-sanitize';
24
25 type CssRules = 'button' | 'codeSnippet' | 'link' | 'linkIcon' | 'rightAlign' | 'cardWithoutMachines' | 'icon' | 'chipsRoot' | 'copyIcon' | 'tableWrapper' | 'webshellButton';
26
27 const EXTRA_TOKEN = "exraToken";
28
29 const styles: CustomStyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
30     button: {
31         marginTop: theme.spacing(1),
32         marginBottom: theme.spacing(1)
33     },
34     codeSnippet: {
35         borderRadius: theme.spacing(0.5),
36         border: '1px solid',
37         borderColor: theme.palette.grey["400"],
38     },
39     link: {
40         textDecoration: 'none',
41         color: theme.palette.primary.main,
42         "&:hover": {
43             color: theme.palette.primary.dark,
44             transition: 'all 0.5s ease'
45         }
46     },
47     linkIcon: {
48         textDecoration: 'none',
49         color: theme.palette.grey["500"],
50         textAlign: 'right',
51         "&:hover": {
52             color: theme.palette.common.black,
53             transition: 'all 0.5s ease'
54         }
55     },
56     rightAlign: {
57         textAlign: "right"
58     },
59     cardWithoutMachines: {
60         display: 'flex'
61     },
62     icon: {
63         textAlign: "right",
64         marginTop: theme.spacing(1)
65     },
66     chipsRoot: {
67         margin: `0px -${theme.spacing(0.5)}`,
68     },
69     copyIcon: {
70         marginLeft: theme.spacing(1),
71         color: theme.palette.grey["500"],
72         cursor: 'pointer',
73         display: 'inline',
74         '& svg': {
75             fontSize: '1rem'
76         }
77     },
78     tableWrapper: {
79         overflowX: 'auto',
80     },
81     webshellButton: {
82         textTransform: "initial",
83     },
84 });
85
86 const mapStateToProps = (state: RootState) => {
87     return {
88         requestedDate: state.virtualMachines.date,
89         userUuid: state.auth.user!.uuid,
90         helpText: state.auth.config.clusterConfig.Workbench.SSHHelpPageHTML,
91         hostSuffix: state.auth.config.clusterConfig.Workbench.SSHHelpHostSuffix || "",
92         token: state.auth.extraApiToken || state.auth.apiToken || '',
93         tokenLocation: state.auth.extraApiToken ? EXTRA_TOKEN : (state.auth.apiTokenLocation || ''),
94         webshellUrl: state.auth.config.clusterConfig.Services.WebShell.ExternalURL,
95         idleTimeout: parse(state.auth.config.clusterConfig.Workbench.IdleTimeout, 's') || 0,
96         ...state.virtualMachines
97     };
98 };
99
100 const mapDispatchToProps = (dispatch: Dispatch): Pick<VirtualMachinesPanelActionProps, 'loadVirtualMachinesData' | 'saveRequestedDate' | 'onCopy'> => ({
101     saveRequestedDate: () => dispatch<any>(saveRequestedDate()),
102     loadVirtualMachinesData: () => dispatch<any>(loadVirtualMachinesUserData()),
103     onCopy: (message: string) => {
104         dispatch(snackbarActions.OPEN_SNACKBAR({
105             message,
106             hideDuration: 2000,
107             kind: SnackbarKind.SUCCESS
108         }));
109     },
110 });
111
112 interface VirtualMachinesPanelDataProps {
113     requestedDate: string;
114     virtualMachines: ListResults<any>;
115     userUuid: string;
116     links: ListResults<any>;
117     helpText: string;
118     hostSuffix: string;
119     token: string;
120     tokenLocation: string;
121     webshellUrl: string;
122     idleTimeout: number;
123 }
124
125 interface VirtualMachinesPanelActionProps {
126     saveRequestedDate: () => void;
127     loadVirtualMachinesData: () => string;
128     onCopy: (message: string) => void;
129 }
130
131 type VirtualMachineProps = VirtualMachinesPanelActionProps & VirtualMachinesPanelDataProps & WithStyles<CssRules>;
132
133 export const VirtualMachineUserPanel = compose(
134     withStyles(styles),
135     connect(mapStateToProps, mapDispatchToProps))(
136         class extends React.Component<VirtualMachineProps> {
137             componentDidMount() {
138                 this.props.loadVirtualMachinesData();
139             }
140
141             render() {
142                 const { virtualMachines, links } = this.props;
143                 return (
144                     <Grid container spacing={2} data-cy="vm-user-panel">
145                         {virtualMachines.items.length === 0 && <CardContentWithoutVirtualMachines {...this.props} />}
146                         {virtualMachines.items.length > 0 && links.items.length > 0 && <CardContentWithVirtualMachines {...this.props} />}
147                         {<CardSSHSection {...this.props} />}
148                     </Grid>
149                 );
150             }
151         }
152     );
153
154 const CardContentWithoutVirtualMachines = (props: VirtualMachineProps) =>
155     <Grid item xs={12}>
156         <Card>
157             <CardContent className={props.classes.cardWithoutMachines}>
158                 <Grid item xs={6}>
159                     <Typography variant='body1'>
160                         You do not have access to any virtual machines. Some Arvados features require using the command line. You may request access to a hosted virtual machine with the command line shell.
161                     </Typography>
162                 </Grid>
163                 <Grid item xs={6} className={props.classes.rightAlign}>
164                     {virtualMachineSendRequest(props)}
165                 </Grid>
166             </CardContent>
167         </Card>
168     </Grid>;
169
170 const CardContentWithVirtualMachines = (props: VirtualMachineProps) =>
171     <Grid item xs={12}>
172         <Card>
173             <CardContent>
174                 <span>
175                     <div className={props.classes.rightAlign}>
176                         {virtualMachineSendRequest(props)}
177                     </div>
178                     <div className={props.classes.icon}>
179                         <a href="https://doc.arvados.org/user/getting_started/vm-login-with-webshell.html" target="_blank" rel="noopener noreferrer" className={props.classes.linkIcon}>
180                             <Tooltip title="Access VM using webshell">
181                                 <HelpIcon />
182                             </Tooltip>
183                         </a>
184                     </div>
185                     <div className={props.classes.tableWrapper}>
186                         {virtualMachinesTable(props)}
187                     </div>
188                 </span>
189
190             </CardContent>
191         </Card>
192     </Grid>;
193
194 const virtualMachineSendRequest = (props: VirtualMachineProps) =>
195     <span>
196         <Button variant="contained" color="primary" className={props.classes.button} onClick={props.saveRequestedDate}>
197             SEND REQUEST FOR SHELL ACCESS
198         </Button>
199         {props.requestedDate &&
200             <Typography >
201                 A request for shell access was sent on {props.requestedDate}
202             </Typography>}
203     </span>;
204
205 const virtualMachinesTable = (props: VirtualMachineProps) =>
206     <Table data-cy="vm-user-table">
207         <TableHead>
208             <TableRow>
209                 <TableCell>Host name</TableCell>
210                 <TableCell>Login name</TableCell>
211                 <TableCell>Groups</TableCell>
212                 <TableCell>Command line</TableCell>
213                 <TableCell>Web shell</TableCell>
214             </TableRow>
215         </TableHead>
216         <TableBody>
217             {props.virtualMachines.items.map(it =>
218                 props.links.items.map(lk => {
219                     if (lk.tailUuid === props.userUuid && lk.headUuid === it.uuid) {
220                         const username = lk.properties.username;
221                         const command = `ssh ${username}@${it.hostname}${props.hostSuffix}`;
222                         let tokenParam = "";
223                         if (props.tokenLocation === SESSION_STORAGE || props.tokenLocation === EXTRA_TOKEN) {
224                             tokenParam = `&token=${encodeURIComponent(props.token)}`;
225                         }
226                         const loginHref = `/webshell/?host=${encodeURIComponent(props.webshellUrl + '/' + it.hostname)}&timeout=${props.idleTimeout}&login=${encodeURIComponent(username)}${tokenParam}`;
227                         return <TableRow key={lk.uuid}>
228                             <TableCell>{it.hostname}</TableCell>
229                             <TableCell>{username}</TableCell>
230                             <TableCell>
231                                 <Grid container spacing={1} className={props.classes.chipsRoot}>
232                                     {
233                                         (lk.properties.groups || []).map((group, i) => (
234                                             <Grid item key={i}>
235                                                 <Chip label={group} />
236                                             </Grid>
237                                         ))
238                                     }
239                                 </Grid>
240                             </TableCell>
241                             <TableCell>
242                                 {command}
243                                 <Tooltip title="Copy link to clipboard">
244                                     <span className={props.classes.copyIcon}>
245                                         <CopyToClipboard text={command || ""} onCopy={() => props.onCopy!("Copied")}>
246                                             <CopyIcon />
247                                         </CopyToClipboard>
248                                     </span>
249                                 </Tooltip>
250                             </TableCell>
251                             <TableCell>
252                                 <Button
253                                     className={props.classes.webshellButton}
254                                     variant="contained"
255                                     size="small"
256                                     href={loginHref}
257                                     target="_blank"
258                                     rel="noopener">
259                                     Log in as {username}
260                                 </Button>
261                             </TableCell>
262                         </TableRow>;
263                     }
264                     return null;
265                 }
266                 ))}
267         </TableBody>
268     </Table>;
269
270 const CardSSHSection = (props: VirtualMachineProps) =>
271     <Grid item xs={12}>
272         <Card>
273             <CardContent>
274                 <Typography>
275                     <div dangerouslySetInnerHTML={{ __html: sanitizeHTML(props.helpText) }} style={{ margin: "1em" }} />
276                 </Typography>
277             </CardContent>
278         </Card>
279     </Grid>;