Merge branch '21128-toolbar-context-menu'
[arvados-workbench2.git] / src / views / virtual-machine-panel / virtual-machine-user-panel.tsx
index fbb1f23f51cb33069167cb763ea76833eed6e4bf..56c92805e24946a0499821fd31c7afb77dc48dce 100644 (file)
@@ -2,21 +2,27 @@
 //
 // SPDX-License-Identifier: AGPL-3.0
 
-import * as React from 'react';
+import React from 'react';
 import { connect } from 'react-redux';
-import { Grid, Typography, Button, Card, CardContent, TableBody, TableCell, TableHead, TableRow, Table, Tooltip } from '@material-ui/core';
+import { Grid, Typography, Button, Card, CardContent, TableBody, TableCell, TableHead, TableRow, Table, Tooltip, Chip } from '@material-ui/core';
 import { StyleRulesCallback, WithStyles, withStyles } from '@material-ui/core/styles';
-import { ArvadosTheme } from '~/common/custom-theme';
-import { DefaultCodeSnippet } from '~/components/default-code-snippet/default-code-snippet';
-import { Link } from 'react-router-dom';
+import { ArvadosTheme } from 'common/custom-theme';
 import { compose, Dispatch } from 'redux';
-import { saveRequestedDate, loadVirtualMachinesUserData } from '~/store/virtual-machines/virtual-machines-actions';
-import { RootState } from '~/store/store';
-import { ListResults } from '~/services/common-service/common-service';
-import { HelpIcon } from '~/components/icon/icon';
-import { Routes } from '~/routes/routes';
+import { saveRequestedDate, loadVirtualMachinesUserData } from 'store/virtual-machines/virtual-machines-actions';
+import { RootState } from 'store/store';
+import { ListResults } from 'services/common-service/common-service';
+import { HelpIcon } from 'components/icon/icon';
+import { SESSION_STORAGE } from "services/auth-service/auth-service";
+// import * as CopyToClipboard from 'react-copy-to-clipboard';
+import parse from "parse-duration";
+import { CopyIcon } from 'components/icon/icon';
+import CopyToClipboard from 'react-copy-to-clipboard';
+import { snackbarActions, SnackbarKind } from 'store/snackbar/snackbar-actions';
+import { sanitizeHTML } from 'common/html-sanitize';
 
-type CssRules = 'button' | 'codeSnippet' | 'link' | 'linkIcon' | 'rightAlign' | 'cardWithoutMachines' | 'icon';
+type CssRules = 'button' | 'codeSnippet' | 'link' | 'linkIcon' | 'rightAlign' | 'cardWithoutMachines' | 'icon' | 'chipsRoot' | 'copyIcon' | 'tableWrapper' | 'webshellButton';
+
+const EXTRA_TOKEN = "exraToken";
 
 const styles: StyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
     button: {
@@ -54,30 +60,70 @@ const styles: StyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
     icon: {
         textAlign: "right",
         marginTop: theme.spacing.unit
-    }
+    },
+    chipsRoot: {
+        margin: `0px -${theme.spacing.unit / 2}px`,
+    },
+    copyIcon: {
+        marginLeft: theme.spacing.unit,
+        color: theme.palette.grey["500"],
+        cursor: 'pointer',
+        display: 'inline',
+        '& svg': {
+            fontSize: '1rem'
+        }
+    },
+    tableWrapper: {
+        overflowX: 'auto',
+    },
+    webshellButton: {
+        textTransform: "initial",
+    },
 });
 
-const mapStateToProps = ({ virtualMachines }: RootState) => {
+const mapStateToProps = (state: RootState) => {
     return {
-        requestedDate: virtualMachines.date,
-        ...virtualMachines
+        requestedDate: state.virtualMachines.date,
+        userUuid: state.auth.user!.uuid,
+        helpText: state.auth.config.clusterConfig.Workbench.SSHHelpPageHTML,
+        hostSuffix: state.auth.config.clusterConfig.Workbench.SSHHelpHostSuffix || "",
+        token: state.auth.extraApiToken || state.auth.apiToken || '',
+        tokenLocation: state.auth.extraApiToken ? EXTRA_TOKEN : (state.auth.apiTokenLocation || ''),
+        webshellUrl: state.auth.config.clusterConfig.Services.WebShell.ExternalURL,
+        idleTimeout: parse(state.auth.config.clusterConfig.Workbench.IdleTimeout, 's') || 0,
+        ...state.virtualMachines
     };
 };
 
-const mapDispatchToProps = (dispatch: Dispatch): Pick<VirtualMachinesPanelActionProps, 'loadVirtualMachinesData' | 'saveRequestedDate'> => ({
+const mapDispatchToProps = (dispatch: Dispatch): Pick<VirtualMachinesPanelActionProps, 'loadVirtualMachinesData' | 'saveRequestedDate' | 'onCopy'> => ({
     saveRequestedDate: () => dispatch<any>(saveRequestedDate()),
     loadVirtualMachinesData: () => dispatch<any>(loadVirtualMachinesUserData()),
+    onCopy: (message: string) => {
+        dispatch(snackbarActions.OPEN_SNACKBAR({
+            message,
+            hideDuration: 2000,
+            kind: SnackbarKind.SUCCESS
+        }));
+    },
 });
 
 interface VirtualMachinesPanelDataProps {
     requestedDate: string;
     virtualMachines: ListResults<any>;
+    userUuid: string;
     links: ListResults<any>;
+    helpText: string;
+    hostSuffix: string;
+    token: string;
+    tokenLocation: string;
+    webshellUrl: string;
+    idleTimeout: number;
 }
 
 interface VirtualMachinesPanelActionProps {
     saveRequestedDate: () => void;
     loadVirtualMachinesData: () => string;
+    onCopy: (message: string) => void;
 }
 
 type VirtualMachineProps = VirtualMachinesPanelActionProps & VirtualMachinesPanelDataProps & WithStyles<CssRules>;
@@ -93,7 +139,7 @@ export const VirtualMachineUserPanel = compose(
             render() {
                 const { virtualMachines, links } = this.props;
                 return (
-                    <Grid container spacing={16}>
+                    <Grid container spacing={16} data-cy="vm-user-panel">
                         {virtualMachines.itemsAvailable === 0 && <CardContentWithoutVirtualMachines {...this.props} />}
                         {virtualMachines.itemsAvailable > 0 && links.itemsAvailable > 0 && <CardContentWithVirtualMachines {...this.props} />}
                         {<CardSSHSection {...this.props} />}
@@ -108,7 +154,7 @@ const CardContentWithoutVirtualMachines = (props: VirtualMachineProps) =>
         <Card>
             <CardContent className={props.classes.cardWithoutMachines}>
                 <Grid item xs={6}>
-                    <Typography variant="body2">
+                    <Typography variant='body1'>
                         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.
                     </Typography>
                 </Grid>
@@ -128,13 +174,15 @@ const CardContentWithVirtualMachines = (props: VirtualMachineProps) =>
                         {virtualMachineSendRequest(props)}
                     </div>
                     <div className={props.classes.icon}>
-                        <a href="https://doc.arvados.org/user/getting_started/vm-login-with-webshell.html" target="_blank" className={props.classes.linkIcon}>
+                        <a href="https://doc.arvados.org/user/getting_started/vm-login-with-webshell.html" target="_blank" rel="noopener noreferrer" className={props.classes.linkIcon}>
                             <Tooltip title="Access VM using webshell">
                                 <HelpIcon />
                             </Tooltip>
                         </a>
                     </div>
-                    {virtualMachinesTable(props)}
+                    <div className={props.classes.tableWrapper}>
+                        {virtualMachinesTable(props)}
+                    </div>
                 </span>
 
             </CardContent>
@@ -147,56 +195,83 @@ const virtualMachineSendRequest = (props: VirtualMachineProps) =>
             SEND REQUEST FOR SHELL ACCESS
         </Button>
         {props.requestedDate &&
-            <Typography variant="body1">
+            <Typography >
                 A request for shell access was sent on {props.requestedDate}
             </Typography>}
     </span>;
 
 const virtualMachinesTable = (props: VirtualMachineProps) =>
-    <Table>
+    <Table data-cy="vm-user-table">
         <TableHead>
             <TableRow>
                 <TableCell>Host name</TableCell>
                 <TableCell>Login name</TableCell>
+                <TableCell>Groups</TableCell>
                 <TableCell>Command line</TableCell>
                 <TableCell>Web shell</TableCell>
             </TableRow>
         </TableHead>
         <TableBody>
-            {props.virtualMachines.items.map((it, index) =>
-                <TableRow key={index}>
-                    <TableCell>{it.hostname}</TableCell>
-                    <TableCell>{getUsername(props.links)}</TableCell>
-                    <TableCell>ssh {getUsername(props.links)}@{it.hostname}.arvados</TableCell>
-                    <TableCell>
-                        <a href={`https://workbench.c97qk.arvadosapi.com${it.href}/webshell/${getUsername(props.links)}`} target="_blank" className={props.classes.link}>
-                            Log in as {getUsername(props.links)}
-                        </a>
-                    </TableCell>
-                </TableRow>
-            )}
+            {props.virtualMachines.items.map(it =>
+                props.links.items.map(lk => {
+                    if (lk.tailUuid === props.userUuid && lk.headUuid === it.uuid) {
+                        const username = lk.properties.username;
+                        const command = `ssh ${username}@${it.hostname}${props.hostSuffix}`;
+                        let tokenParam = "";
+                        if (props.tokenLocation === SESSION_STORAGE || props.tokenLocation === EXTRA_TOKEN) {
+                          tokenParam = `&token=${encodeURIComponent(props.token)}`;
+                        }
+                        const loginHref = `/webshell/?host=${encodeURIComponent(props.webshellUrl + '/' + it.hostname)}&timeout=${props.idleTimeout}&login=${encodeURIComponent(username)}${tokenParam}`;
+                        return <TableRow key={lk.uuid}>
+                            <TableCell>{it.hostname}</TableCell>
+                            <TableCell>{username}</TableCell>
+                            <TableCell>
+                                <Grid container spacing={8} className={props.classes.chipsRoot}>
+                                    {
+                                    (lk.properties.groups || []).map((group, i) => (
+                                        <Grid item key={i}>
+                                            <Chip label={group} />
+                                        </Grid>
+                                    ))
+                                    }
+                                </Grid>
+                            </TableCell>
+                            <TableCell>
+                                {command}
+                                <Tooltip title="Copy to clipboard">
+                                    <span className={props.classes.copyIcon}>
+                                        <CopyToClipboard text={command || ""} onCopy={() => props.onCopy!("Copied")}>
+                                            <CopyIcon />
+                                        </CopyToClipboard>
+                                    </span>
+                                </Tooltip>
+                            </TableCell>
+                            <TableCell>
+                                <Button
+                                    className={props.classes.webshellButton}
+                                    variant="contained"
+                                    size="small"
+                                    href={loginHref}
+                                    target="_blank"
+                                    rel="noopener noreferrer">
+                                        Log in as {username}
+                                </Button>
+                            </TableCell>
+                        </TableRow>;
+                    }
+                    return null;
+                }
+                ))}
         </TableBody>
     </Table>;
 
-const getUsername = (links: ListResults<any>) => {
-    return links.items[0].properties.username;
-};
-
 const CardSSHSection = (props: VirtualMachineProps) =>
     <Grid item xs={12}>
         <Card>
             <CardContent>
-                <Typography variant="body2">
-                    In order to access virtual machines using SSH, <Link to={Routes.SSH_KEYS_USER} className={props.classes.link}>add an SSH key to your account</Link> and add a section like this to your SSH configuration file ( ~/.ssh/config):
+                <Typography>
+                    <div dangerouslySetInnerHTML={{ __html: sanitizeHTML(props.helpText) }} style={{ margin: "1em" }} />
                 </Typography>
-                <DefaultCodeSnippet
-                    className={props.classes.codeSnippet}
-                    lines={[textSSH]} />
             </CardContent>
         </Card>
     </Grid>;
-
-const textSSH = `Host *.arvados
-    TCPKeepAlive yes
-    ServerAliveInterval 60
-    ProxyCommand ssh -p2222 turnout@switchyard.api.ardev.roche.com -x -a $SSH_PROXY_FLAGS %h`;
\ No newline at end of file