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