2020-03-24 23:22:16 +00:00
|
|
|
const ANSI_UI_GRAY_400 = '\x1b[38;2;142;150;163m';
|
|
|
|
|
2021-07-20 22:27:41 +00:00
|
|
|
import { base64DecodeString, base64EncodeString } from 'nomad-ui/utils/encode';
|
2020-03-24 23:22:16 +00:00
|
|
|
|
2020-08-28 15:13:33 +00:00
|
|
|
export const HEARTBEAT_INTERVAL = 10000; // ten seconds
|
|
|
|
|
2020-03-24 23:22:16 +00:00
|
|
|
export default class ExecSocketXtermAdapter {
|
2020-04-03 15:22:22 +00:00
|
|
|
constructor(terminal, socket, token) {
|
2020-03-24 23:22:16 +00:00
|
|
|
this.terminal = terminal;
|
|
|
|
this.socket = socket;
|
2020-04-03 15:22:22 +00:00
|
|
|
this.token = token;
|
2020-03-24 23:22:16 +00:00
|
|
|
|
|
|
|
socket.onopen = () => {
|
2020-04-03 15:22:22 +00:00
|
|
|
this.sendWsHandshake();
|
2020-03-24 23:22:16 +00:00
|
|
|
this.sendTtySize();
|
2020-08-28 15:13:33 +00:00
|
|
|
this.startHeartbeat();
|
2020-03-24 23:22:16 +00:00
|
|
|
|
2021-12-28 14:45:20 +00:00
|
|
|
terminal.onData((data) => {
|
2020-03-24 23:22:16 +00:00
|
|
|
this.handleData(data);
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
2021-12-28 14:45:20 +00:00
|
|
|
socket.onmessage = (e) => {
|
2020-03-24 23:22:16 +00:00
|
|
|
let json = JSON.parse(e.data);
|
|
|
|
|
|
|
|
// stderr messages will not be produced as the socket is opened with the tty flag
|
|
|
|
if (json.stdout && json.stdout.data) {
|
2021-07-20 22:27:41 +00:00
|
|
|
terminal.write(base64DecodeString(json.stdout.data));
|
2020-03-24 23:22:16 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
socket.onclose = () => {
|
2020-08-28 15:13:33 +00:00
|
|
|
this.stopHeartbeat();
|
2020-03-24 23:22:16 +00:00
|
|
|
this.terminal.writeln('');
|
|
|
|
this.terminal.write(ANSI_UI_GRAY_400);
|
|
|
|
this.terminal.writeln('The connection has closed.');
|
|
|
|
// Issue to add interpretation of close events: https://github.com/hashicorp/nomad/issues/7464
|
|
|
|
};
|
|
|
|
|
|
|
|
terminal.resized = () => {
|
|
|
|
this.sendTtySize();
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
sendTtySize() {
|
|
|
|
this.socket.send(
|
|
|
|
JSON.stringify({ tty_size: { width: this.terminal.cols, height: this.terminal.rows } })
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2020-04-03 15:22:22 +00:00
|
|
|
sendWsHandshake() {
|
|
|
|
this.socket.send(JSON.stringify({ version: 1, auth_token: this.token || '' }));
|
|
|
|
}
|
|
|
|
|
2020-08-28 15:13:33 +00:00
|
|
|
startHeartbeat() {
|
|
|
|
this.heartbeatTimer = setInterval(() => {
|
|
|
|
this.socket.send(JSON.stringify({}));
|
|
|
|
}, HEARTBEAT_INTERVAL);
|
|
|
|
}
|
|
|
|
|
|
|
|
stopHeartbeat() {
|
|
|
|
clearInterval(this.heartbeatTimer);
|
|
|
|
}
|
|
|
|
|
2020-03-24 23:22:16 +00:00
|
|
|
handleData(data) {
|
2021-07-20 22:27:41 +00:00
|
|
|
this.socket.send(JSON.stringify({ stdin: { data: base64EncodeString(data) } }));
|
2020-03-24 23:22:16 +00:00
|
|
|
}
|
|
|
|
}
|