17229: Webshell add idle timer and auto log out
[arvados.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 } 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';
20
21 const EXTRA_TOKEN = "exra";
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 });
61
62 const mapStateToProps = (state: RootState) => {
63     return {
64         requestedDate: state.virtualMachines.date,
65         userUuid: state.auth.user!.uuid,
66         helpText: state.auth.config.clusterConfig.Workbench.SSHHelpPageHTML,
67         hostSuffix: state.auth.config.clusterConfig.Workbench.SSHHelpHostSuffix || "",
68         token: state.auth.extraApiToken || state.auth.apiToken || '',
69         tokenLocation: state.auth.extraApiToken ? EXTRA_TOKEN : (state.auth.apiTokenLocation || ''),
70         webshellUrl: state.auth.config.clusterConfig.Services.WebShell.ExternalURL,
71         idleTimeout: parse(state.auth.config.clusterConfig.Workbench.IdleTimeout, 's') || 0,
72         ...state.virtualMachines
73     };
74 };
75
76 const mapDispatchToProps = (dispatch: Dispatch): Pick<VirtualMachinesPanelActionProps, 'loadVirtualMachinesData' | 'saveRequestedDate'> => ({
77     saveRequestedDate: () => dispatch<any>(saveRequestedDate()),
78     loadVirtualMachinesData: () => dispatch<any>(loadVirtualMachinesUserData()),
79 });
80
81 interface VirtualMachinesPanelDataProps {
82     requestedDate: string;
83     virtualMachines: ListResults<any>;
84     userUuid: string;
85     links: ListResults<any>;
86     helpText: string;
87     hostSuffix: string;
88     token: string;
89     tokenLocation: string;
90     webshellUrl: string;
91     idleTimeout: number;
92 }
93
94 interface VirtualMachinesPanelActionProps {
95     saveRequestedDate: () => void;
96     loadVirtualMachinesData: () => string;
97 }
98
99 type VirtualMachineProps = VirtualMachinesPanelActionProps & VirtualMachinesPanelDataProps & WithStyles<CssRules>;
100
101 export const VirtualMachineUserPanel = compose(
102     withStyles(styles),
103     connect(mapStateToProps, mapDispatchToProps))(
104         class extends React.Component<VirtualMachineProps> {
105             componentDidMount() {
106                 this.props.loadVirtualMachinesData();
107             }
108
109             render() {
110                 const { virtualMachines, links } = this.props;
111                 return (
112                     <Grid container spacing={16}>
113                         {virtualMachines.itemsAvailable === 0 && <CardContentWithoutVirtualMachines {...this.props} />}
114                         {virtualMachines.itemsAvailable > 0 && links.itemsAvailable > 0 && <CardContentWithVirtualMachines {...this.props} />}
115                         {<CardSSHSection {...this.props} />}
116                     </Grid>
117                 );
118             }
119         }
120     );
121
122 const CardContentWithoutVirtualMachines = (props: VirtualMachineProps) =>
123     <Grid item xs={12}>
124         <Card>
125             <CardContent className={props.classes.cardWithoutMachines}>
126                 <Grid item xs={6}>
127                     <Typography variant='body1'>
128                         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.
129                     </Typography>
130                 </Grid>
131                 <Grid item xs={6} className={props.classes.rightAlign}>
132                     {virtualMachineSendRequest(props)}
133                 </Grid>
134             </CardContent>
135         </Card>
136     </Grid>;
137
138 const CardContentWithVirtualMachines = (props: VirtualMachineProps) =>
139     <Grid item xs={12}>
140         <Card>
141             <CardContent>
142                 <span>
143                     <div className={props.classes.rightAlign}>
144                         {virtualMachineSendRequest(props)}
145                     </div>
146                     <div className={props.classes.icon}>
147                         <a href="https://doc.arvados.org/user/getting_started/vm-login-with-webshell.html" target="_blank" rel="noopener noreferrer" className={props.classes.linkIcon}>
148                             <Tooltip title="Access VM using webshell">
149                                 <HelpIcon />
150                             </Tooltip>
151                         </a>
152                     </div>
153                     {virtualMachinesTable(props)}
154                 </span>
155
156             </CardContent>
157         </Card>
158     </Grid>;
159
160 const virtualMachineSendRequest = (props: VirtualMachineProps) =>
161     <span>
162         <Button variant="contained" color="primary" className={props.classes.button} onClick={props.saveRequestedDate}>
163             SEND REQUEST FOR SHELL ACCESS
164         </Button>
165         {props.requestedDate &&
166             <Typography >
167                 A request for shell access was sent on {props.requestedDate}
168             </Typography>}
169     </span>;
170
171 const virtualMachinesTable = (props: VirtualMachineProps) =>
172     <Table>
173         <TableHead>
174             <TableRow>
175                 <TableCell>Host name</TableCell>
176                 <TableCell>Login name</TableCell>
177                 <TableCell>Command line</TableCell>
178                 <TableCell>Web shell</TableCell>
179             </TableRow>
180         </TableHead>
181         <TableBody>
182             {props.virtualMachines.items.map(it =>
183                 props.links.items.map(lk => {
184                     if (lk.tailUuid === props.userUuid) {
185                         const username = lk.properties.username;
186                         const command = `ssh ${username}@${it.hostname}${props.hostSuffix}`;
187                         let tokenParam = "";
188                         if (props.tokenLocation === SESSION_STORAGE || props.tokenLocation === EXTRA_TOKEN) {
189                           tokenParam = `&token=${encodeURIComponent(props.token)}`;
190                         }
191                         return <TableRow key={lk.uuid}>
192                             <TableCell>{it.hostname}</TableCell>
193                             <TableCell>{username}</TableCell>
194                             <TableCell>
195                                 {command}
196                             </TableCell>
197                             <TableCell>
198                                 <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}>
199                                     Log in as {username}
200                                 </a>
201                             </TableCell>
202                         </TableRow>;
203                     }
204                     return null;
205                 }
206                 ))}
207         </TableBody>
208     </Table>;
209
210 const CardSSHSection = (props: VirtualMachineProps) =>
211     <Grid item xs={12}>
212         <Card>
213             <CardContent>
214                 <Typography>
215                     <div dangerouslySetInnerHTML={{ __html: props.helpText }} style={{ margin: "1em" }} />
216                 </Typography>
217             </CardContent>
218         </Card>
219     </Grid>;