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