• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mendersoftware / gui / 913068613

pending completion
913068613

Pull #3803

gitlab-ci

web-flow
Merge pull request #3801 from mzedel/men-6383

MEN-6383 - device check in time
Pull Request #3803: staging alignment

4418 of 6435 branches covered (68.66%)

178 of 246 new or added lines in 27 files covered. (72.36%)

8352 of 10138 relevant lines covered (82.38%)

160.95 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

57.3
/src/js/components/devices/dialogs/troubleshootdialog.js
1
// Copyright 2021 Northern.tech AS
2
//
3
//    Licensed under the Apache License, Version 2.0 (the "License");
4
//    you may not use this file except in compliance with the License.
5
//    You may obtain a copy of the License at
6
//
7
//        http://www.apache.org/licenses/LICENSE-2.0
8
//
9
//    Unless required by applicable law or agreed to in writing, software
10
//    distributed under the License is distributed on an "AS IS" BASIS,
11
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
//    See the License for the specific language governing permissions and
13
//    limitations under the License.
14
import React, { useCallback, useEffect, useRef, useState } from 'react';
15
import Dropzone from 'react-dropzone';
16
import { useDispatch, useSelector } from 'react-redux';
17
import { Link } from 'react-router-dom';
18

19
import { Button, Dialog, DialogActions, DialogContent, DialogTitle, Tab, Tabs } from '@mui/material';
20
import { makeStyles } from 'tss-react/mui';
21

22
import { mdiConsole as ConsoleIcon } from '@mdi/js';
23
import moment from 'moment';
24
import momentDurationFormatSetup from 'moment-duration-format';
25

26
import { setSnackbar } from '../../../actions/appActions';
27
import { deviceFileUpload, getDeviceFileDownloadLink } from '../../../actions/deviceActions';
28
import { BEGINNING_OF_TIME, TIMEOUTS } from '../../../constants/appConstants';
29
import { createDownload } from '../../../helpers';
30
import { getFeatures, getIdAttribute, getIsEnterprise, getIsPreview, getTenantCapabilities, getUserCapabilities } from '../../../selectors';
31
import { useSession } from '../../../utils/sockethook';
32
import { TwoColumns } from '../../common/configurationobject';
33
import MaterialDesignIcon from '../../common/materialdesignicon';
34
import { MaybeTime } from '../../common/time';
35
import FileTransfer from '../troubleshoot/filetransfer';
36
import Terminal from '../troubleshoot/terminal';
37
import ListOptions from '../widgets/listoptions';
38
import DeviceIdentityDisplay from './../../common/deviceidentity';
39
import { getCode } from './make-gateway-dialog';
40

41
momentDurationFormatSetup(moment);
12✔
42

43
const useStyles = makeStyles()(theme => ({
12✔
44
  content: { padding: 0, margin: '0 24px', height: '75vh' },
45
  title: { marginRight: theme.spacing(0.5) },
46
  connectionButton: { background: theme.palette.text.primary },
47
  connectedIcon: { color: theme.palette.success.main, marginLeft: theme.spacing() },
48
  disconnectedIcon: { color: theme.palette.error.main, marginLeft: theme.spacing() },
49
  sessionInfo: { maxWidth: 'max-content' },
50
  terminalContent: {
51
    display: 'grid',
52
    gridTemplateRows: 'max-content 0',
53
    flexGrow: 1,
54
    overflow: 'hidden',
55
    '&.device-connected': {
56
      gridTemplateRows: 'max-content minmax(min-content, 1fr)'
57
    }
58
  },
59
  terminalStatePlaceholder: {
60
    width: 280
61
  }
62
}));
63

64
const ConnectionIndicator = ({ isConnected }) => {
12✔
65
  const { classes } = useStyles();
1✔
66
  return (
1✔
67
    <div className="flexbox center-aligned">
68
      Remote terminal {<MaterialDesignIcon className={isConnected ? classes.connectedIcon : classes.disconnectedIcon} path={ConsoleIcon} />}
1!
69
    </div>
70
  );
71
};
72

73
const tabs = {
12✔
74
  terminal: {
75
    link: 'session logs',
76
    title: ConnectionIndicator,
77
    value: 'terminal',
78
    canShow: ({ canTroubleshoot, canWriteDevices }) => canTroubleshoot && canWriteDevices
1✔
79
  },
80
  transfer: { link: 'file transfer logs', title: () => 'File transfer', value: 'transfer', canShow: ({ canTroubleshoot }) => canTroubleshoot }
1✔
81
};
82

83
export const TroubleshootDialog = ({ device, onCancel, open, setSocketClosed, type = tabs.terminal.value }) => {
12✔
84
  const [currentTab, setCurrentTab] = useState(type);
2✔
85
  const [availableTabs, setAvailableTabs] = useState(Object.values(tabs));
2✔
86
  const [downloadPath, setDownloadPath] = useState('');
2✔
87
  const [elapsed, setElapsed] = useState(moment());
2✔
88
  const [file, setFile] = useState();
2✔
89
  const [socketInitialized, setSocketInitialized] = useState(false);
2✔
90
  const [startTime, setStartTime] = useState();
2✔
91
  const [uploadPath, setUploadPath] = useState('');
2✔
92
  const [terminalInput, setTerminalInput] = useState('');
2✔
93
  const [snackbarAlreadySet, setSnackbarAlreadySet] = useState(false);
2✔
94
  const closeTimer = useRef();
2✔
95
  const snackTimer = useRef();
2✔
96
  const timer = useRef();
2✔
97
  const termRef = useRef({ terminal: React.createRef(), terminalRef: React.createRef() });
2✔
98
  const { classes } = useStyles();
2✔
99
  const { isHosted } = useSelector(getFeatures);
2✔
100
  const isEnterprise = useSelector(getIsEnterprise);
2✔
101
  const canPreview = useSelector(getIsPreview);
2✔
102
  const idAttribute = useSelector(getIdAttribute);
2✔
103
  const userCapabilities = useSelector(getUserCapabilities);
2✔
104
  const { canAuditlog, canTroubleshoot, canWriteDevices } = userCapabilities;
2✔
105
  const { hasAuditlogs } = useSelector(getTenantCapabilities);
2✔
106
  const dispatch = useDispatch();
2✔
107
  const dispatchedSetSnackbar = (...args) => dispatch(setSnackbar(...args));
2✔
108

109
  useEffect(() => {
2✔
110
    if (open) {
1!
111
      setCurrentTab(type);
1✔
112
      return;
1✔
113
    }
114
    setDownloadPath('');
×
115
    setUploadPath('');
×
116
    setFile();
×
117
    return () => {
×
118
      clearTimeout(closeTimer.current);
×
119
      clearTimeout(snackTimer.current);
×
120
    };
121
  }, [open]);
122

123
  useEffect(() => {
2✔
124
    const allowedTabs = Object.values(tabs).reduce((accu, tab) => {
1✔
125
      if (tab.canShow(userCapabilities)) {
2!
126
        accu.push(tab);
2✔
127
      }
128
      return accu;
2✔
129
    }, []);
130
    setAvailableTabs(allowedTabs);
1✔
131
  }, [canTroubleshoot, canWriteDevices]);
132

133
  useEffect(() => {
2✔
134
    if (socketInitialized === undefined) {
2✔
135
      return;
1✔
136
    }
137
    clearInterval(timer.current);
1✔
138
    if (socketInitialized) {
1!
139
      setStartTime(new Date());
×
140
      timer.current = setInterval(() => setElapsed(moment()), TIMEOUTS.halfASecond);
×
141
    } else {
142
      close();
1✔
143
    }
144
    return () => {
1✔
145
      clearInterval(timer.current);
1✔
146
    };
147
  }, [socketInitialized]);
148

149
  useEffect(() => {
2✔
150
    if (!(open || socketInitialized) || socketInitialized) {
1!
151
      return;
×
152
    }
153
    canTroubleshoot ? connect(device.id) : undefined;
1!
154
    return () => {
1✔
155
      close();
1✔
156
      setTimeout(() => setSocketClosed(true), TIMEOUTS.fiveSeconds);
1✔
157
    };
158
  }, [device.id, open]);
159

160
  const onConnectionToggle = () => {
2✔
161
    if (socketInitialized) {
×
162
      close();
×
163
    } else {
164
      setSocketInitialized(false);
×
165
      connect(device.id);
×
166
    }
167
  };
168

169
  const onDrop = acceptedFiles => {
2✔
170
    if (acceptedFiles.length === 1) {
×
171
      setFile(acceptedFiles[0]);
×
172
      setUploadPath(`/tmp/${acceptedFiles[0].name}`);
×
173
      setCurrentTab(tabs.transfer.value);
×
174
    }
175
  };
176

177
  const onDownloadClick = path => {
2✔
178
    setDownloadPath(path);
×
179
    dispatch(getDeviceFileDownloadLink(device.id, path)).then(address => {
×
180
      const filename = path.substring(path.lastIndexOf('/') + 1) || 'file';
×
181
      createDownload(address, filename);
×
182
    });
183
  };
184

185
  const onSocketOpen = () => {
2✔
186
    setSocketInitialized(true);
×
NEW
187
    dispatch(setSnackbar('Connection with the device established.', TIMEOUTS.fiveSeconds));
×
188
  };
189

190
  const onNotify = content => {
2✔
191
    setSnackbarAlreadySet(true);
×
NEW
192
    dispatch(setSnackbar(content, TIMEOUTS.fiveSeconds));
×
193
    snackTimer.current = setTimeout(() => setSnackbarAlreadySet(false), TIMEOUTS.fiveSeconds + TIMEOUTS.debounceShort);
×
194
  };
195

196
  const onHealthCheckFailed = () => {
2✔
197
    if (snackbarAlreadySet) {
×
198
      return;
×
199
    }
200
    onNotify('Health check failed: connection with the device lost.');
×
201
  };
202

203
  const onSocketClose = event => {
2✔
204
    if (snackbarAlreadySet) {
×
205
      return;
×
206
    }
207
    if (event.wasClean) {
×
208
      onNotify(`Connection with the device closed.`);
×
209
    } else if (event.code == 1006) {
×
210
      // 1006: abnormal closure
211
      onNotify('Connection to the remote terminal is forbidden.');
×
212
    } else {
213
      onNotify('Connection with the device died.');
×
214
    }
215
    closeTimer.current = setTimeout(() => setSocketClosed(true), TIMEOUTS.fiveSeconds);
×
216
  };
217

218
  const onMessageReceived = useCallback(
2✔
219
    message => {
220
      if (!termRef.current.terminal) {
×
221
        return;
×
222
      }
223
      termRef.current.terminal.write(new Uint8Array(message));
×
224
    },
225
    [termRef.current]
226
  );
227

228
  const [connect, sendMessage, close, sessionState, sessionId] = useSession({
2✔
229
    onClose: onSocketClose,
230
    onHealthCheckFailed,
231
    onMessageReceived,
232
    onNotify,
233
    onOpen: onSocketOpen
234
  });
235

236
  useEffect(() => {
2✔
237
    setSocketInitialized(sessionState === WebSocket.OPEN && sessionId);
1✔
238
  }, [sessionId, sessionState]);
239

240
  const onMakeGatewayClick = () => {
2✔
241
    const code = getCode(canPreview);
×
242
    setTerminalInput(code);
×
243
  };
244

245
  const commandHandlers = isHosted && isEnterprise ? [{ key: 'thing', onClick: onMakeGatewayClick, title: 'Promote to Mender gateway' }] : [];
2!
246

247
  const duration = moment.duration(elapsed.diff(moment(startTime)));
2✔
248
  const visibilityToggle = !socketInitialized ? { maxHeight: 0, overflow: 'hidden' } : {};
2!
249
  return (
2✔
250
    <Dialog open={open} fullWidth={true} maxWidth="lg">
251
      <DialogTitle className="flexbox">
252
        <div className={classes.title}>Troubleshoot -</div>
253
        <DeviceIdentityDisplay device={device} idAttribute={idAttribute} isEditable={false} />
254
      </DialogTitle>
255
      <DialogContent className={`dialog-content flexbox column ${classes.content}`}>
256
        <Tabs value={currentTab} onChange={(e, tab) => setCurrentTab(tab)} textColor="primary" TabIndicatorProps={{ className: 'hidden' }}>
×
257
          {availableTabs.map(({ title: Title, value }) => (
258
            <Tab key={value} label={<Title isConnected={socketInitialized} />} value={value} />
4✔
259
          ))}
260
        </Tabs>
261
        {currentTab === tabs.transfer.value && (
2!
262
          <FileTransfer
263
            deviceId={device.id}
264
            downloadPath={downloadPath}
265
            file={file}
266
            onDownload={onDownloadClick}
267
            onUpload={(...args) => dispatch(deviceFileUpload(...args))}
×
268
            setDownloadPath={setDownloadPath}
269
            setFile={setFile}
270
            setSnackbar={dispatchedSetSnackbar}
271
            setUploadPath={setUploadPath}
272
            uploadPath={uploadPath}
273
            userCapabilities={userCapabilities}
274
          />
275
        )}
276
        <div className={`${classes.terminalContent} ${socketInitialized ? 'device-connected' : ''} ${currentTab === tabs.terminal.value ? '' : 'hidden'}`}>
4!
277
          <TwoColumns
278
            className={`margin-top-small margin-bottom-small ${classes.sessionInfo}`}
279
            items={{
280
              'Session status': socketInitialized ? 'connected' : 'disconnected',
2!
281
              'Connection start': <MaybeTime value={startTime} />,
282
              'Duration': `${duration.format('hh:mm:ss', { trim: false })}`
283
            }}
284
          />
285
          <Dropzone activeClassName="active" rejectClassName="active" multiple={false} onDrop={onDrop} noClick>
286
            {({ getRootProps }) => (
287
              <div {...getRootProps()} style={{ position: 'relative', ...visibilityToggle }}>
1✔
288
                <Terminal
289
                  onDownloadClick={onDownloadClick}
290
                  sendMessage={sendMessage}
291
                  sessionId={sessionId}
292
                  setSnackbar={dispatchedSetSnackbar}
293
                  socketInitialized={socketInitialized}
294
                  style={{ position: 'absolute', width: '100%', height: '100%', ...visibilityToggle }}
295
                  textInput={terminalInput}
296
                  xtermRef={termRef}
297
                />
298
              </div>
299
            )}
300
          </Dropzone>
301
          {!socketInitialized && (
4✔
302
            <div className={`flexbox centered ${classes.connectionButton}`}>
303
              <Button variant="contained" color="secondary" onClick={onConnectionToggle}>
304
                Connect Terminal
305
              </Button>
306
            </div>
307
          )}
308
        </div>
309
      </DialogContent>
310
      <DialogActions className="flexbox space-between">
311
        <div>
312
          {currentTab === tabs.terminal.value ? (
2!
313
            <Button onClick={onConnectionToggle}>{socketInitialized ? 'Disconnect' : 'Connect'} Terminal</Button>
2!
314
          ) : (
315
            <div className={classes.terminalStatePlaceholder} />
316
          )}
317
          {canAuditlog && hasAuditlogs && (
4!
318
            <Button component={Link} to={`/auditlog?objectType=device&objectId=${device.id}&startDate=${BEGINNING_OF_TIME}`}>
319
              View {tabs[currentTab].link} for this device
320
            </Button>
321
          )}
322
        </div>
323
        <div>
324
          {currentTab === tabs.terminal.value && socketInitialized && !!commandHandlers.length && (
4!
325
            <ListOptions options={commandHandlers} title="Quick commands" />
326
          )}
327
          <Button onClick={onCancel}>Close</Button>
328
        </div>
329
      </DialogActions>
330
    </Dialog>
331
  );
332
};
333

334
export default TroubleshootDialog;
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc