Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New terminal #1297

Draft
wants to merge 17 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions rust/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions rust/agama-server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,14 @@ chrono = { version = "0.4.34", default-features = false, features = [
"clock",
] }
pam = "0.8.0"
pty-process = { version = "0.4.0", features = ["async"] }
serde_with = "3.6.1"
pin-project = "1.1.5"
openssl = "0.10.64"
hyper = "1.2.0"
hyper-util = "0.1.3"
tokio-openssl = "0.6.4"
tokio-util = "0.7.11"
futures-util = { version = "0.3.30", default-features = false, features = [
"alloc",
] }
Expand Down
1 change: 1 addition & 0 deletions rust/agama-server/src/web.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ mod event;
mod http;
mod service;
mod state;
mod terminal_ws;
mod ws;

use agama_lib::{connection, error::ServiceError};
Expand Down
4 changes: 3 additions & 1 deletion rust/agama-server/src/web/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,9 @@ impl MainServiceBuilder {
where
P: AsRef<Path>,
{
let api_router = Router::new().route("/ws", get(super::ws::ws_handler));
let api_router = Router::new()
.route("/ws", get(super::ws::ws_handler))
.route("/terminal", get(super::terminal_ws::handler));
let config = ServiceConfig::default();

Self {
Expand Down
90 changes: 90 additions & 0 deletions rust/agama-server/src/web/terminal_ws.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
use axum::{
extract::{
ws::{close_code, CloseFrame, Message, WebSocket},
WebSocketUpgrade,
},
response::IntoResponse,
};
use pty_process::{OwnedReadPty, OwnedWritePty};
use std::borrow::Cow;
use tokio::io::AsyncWriteExt;
use tokio_stream::StreamExt;

pub(crate) async fn handler(ws: WebSocketUpgrade) -> impl IntoResponse {
ws.on_upgrade(move |socket| handle_socket(socket))
}

fn start_shell() -> Result<(OwnedReadPty, OwnedWritePty, tokio::process::Child), pty_process::Error>
{
let pty = pty_process::Pty::new()?;
pty.resize(pty_process::Size::new(24, 80))?;
let mut cmd = pty_process::Command::new("bash");
let child = cmd.spawn(&pty.pts()?)?;
let (pty_out, pty_in) = pty.into_split();
Ok((pty_out, pty_in, child))
}

async fn handle_socket(mut socket: WebSocket) {
tracing::info!("Terminal connected");

// TODO: handle failed start of shell
let (pty_out, mut pty_in, mut child) = start_shell().unwrap();
let mut reader_stream = tokio_util::io::ReaderStream::new(pty_out);

loop {
tokio::select! {
message = socket.recv() => {
match message {
Some(Ok(Message::Text(s))) => {
let res = pty_in.write_all(s.as_bytes()).await;
if res.is_err() {
tracing::warn!("Failed to write to pty: {:?}", res);
}

continue;
},
Some(Ok(Message::Close(_))) => {
tracing::info!("websocket close {:?}", message);
break;
},
None => {
tracing::info!("Socket closed");
break;
}
_ => {
tracing::info!("websocket other {:?}", message);
continue
},
}
},
shell_output = reader_stream.next() => {
if let Some(some_output) = shell_output {
match some_output {
Ok(output_bytes) => socket.send(Message::Binary(output_bytes.into())).await.unwrap(),
Err(e) => tracing::warn!("Shell error {}", e),
}

}
},
status = child.wait() => {
match status {
Err(err) => tracing::warn!("Child status error: {}", err),
Ok(status) => {
let code = status.code().unwrap_or(0);
let msg = format!("Bash exited with code: {code}");
let res = socket.send(Message::Close(Some(CloseFrame {
code: close_code::NORMAL,
reason: Cow::from(msg),
}))).await;
if res.is_err() {
tracing::warn!("Failed to send close message: {:?}", res);
}
break;
}
}
}
}
}

tracing::info!("Terminal disconnected.");
}
3 changes: 3 additions & 0 deletions web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,9 @@
"@patternfly/patternfly": "^5.1.0",
"@patternfly/react-core": "^5.1.1",
"@patternfly/react-table": "^5.1.1",
"@xterm/addon-attach": "0.11.0",
"@xterm/addon-fit": "0.10.0",
"@xterm/xterm": "5.5.0",
"fast-sort": "^3.4.0",
"ipaddr.js": "^2.1.0",
"react": "^18.2.0",
Expand Down
3 changes: 2 additions & 1 deletion web/src/MainLayout.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import {
Toolbar, ToolbarContent, ToolbarGroup, ToolbarItem
} from "@patternfly/react-core";
import { Icon } from "~/components/layout";
import { About, InstallerOptions } from "~/components/core";
import { About, InstallerOptions, TerminalDialog } from "~/components/core";
import { _ } from "~/i18n";
import { rootRoutes } from "~/router";
import { useProduct } from "~/context/product";
Expand Down Expand Up @@ -60,6 +60,7 @@ const Header = () => {
<ToolbarContent>
<ToolbarGroup align={{ default: "alignRight" }}>
<ToolbarItem>
<TerminalDialog />
<InstallerOptions />
</ToolbarItem>
</ToolbarGroup>
Expand Down
3 changes: 2 additions & 1 deletion web/src/SimpleLayout.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import {
Page,
Toolbar, ToolbarContent, ToolbarGroup, ToolbarItem
} from "@patternfly/react-core";
import { InstallerOptions } from "~/components/core";
import { InstallerOptions, TerminalDialog } from "~/components/core";
import { _ } from "~/i18n";

/**
Expand All @@ -42,6 +42,7 @@ export default function SimpleLayout({ showOutlet = true, showInstallerOptions =
<ToolbarContent>
<ToolbarGroup align={{ default: "alignRight" }}>
<ToolbarItem>
{showInstallerOptions && <TerminalDialog />}
{showInstallerOptions && <InstallerOptions />}
</ToolbarItem>
</ToolbarGroup>
Expand Down
7 changes: 4 additions & 3 deletions web/src/client/http.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ class WSClient {
/**
* @param {URL} url - Websocket URL.
*/
constructor(url) {
constructor(url, json = true) {
this.url = url.toString();

this.handlers = {
Expand All @@ -66,6 +66,7 @@ class WSClient {

this.reconnectAttempts = 0;
this.client = this.buildClient();
this.json = json;
}

wsState() {
Expand Down Expand Up @@ -196,7 +197,7 @@ class WSClient {
* @param {object} event - Event object, which is basically a websocket message.
*/
dispatchEvent(event) {
const eventObject = JSON.parse(event.data);
const eventObject = this.json ? JSON.parse(event.data) : event.data;
this.handlers.events.forEach((f) => f(eventObject));
}

Expand Down Expand Up @@ -375,4 +376,4 @@ class HTTPClient {
}
}

export { HTTPClient };
export { WSClient, HTTPClient };
88 changes: 88 additions & 0 deletions web/src/components/core/Terminal.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/*
* Copyright (c) [2024] SUSE LLC
*
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as published
* by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, contact SUSE LLC.
*
* To contact SUSE LLC about this file by physical or electronic mail, you may
* find current contact information at www.suse.com.
*/

// @ts-check

import React from "react";
import { WSClient } from "~/client/http";
import { Terminal as Term } from "@xterm/xterm";
import { AttachAddon } from "@xterm/addon-attach";
import "@xterm/xterm/css/xterm.css";

const buildWs = () => {
const url = new URL(window.location.toString());
url.hash = "";
url.pathname += "api/terminal";
url.protocol = url.protocol === "http:" ? "ws" : "wss";

return new WSClient(url, false);
};

const buildTerm = () => {
return new Term({
rows: 25,
cols: 100,
cursorBlink: true,
screenReaderMode: true,
theme: {
background: "#ffffff",
foreground: "#000000",
cursor: "#000000",
}
});
};

/**
* Simple component that displayes terminal.
* @component
*
* // FIXME: if possible, convert to a functional component
*
* @param {object} props
* @param {Location} props.url url of websocket answering terminal
*/
export default class Terminal extends React.Component {
constructor() {
super();
this.terminalRef = React.createRef();
this.ws = buildWs();
this.term = buildTerm();
this.ws.onOpen(() => {
if (this.attachAddon === undefined) {
this.attachAddon = new AttachAddon(this.ws.client);
// Attach the socket to term
this.term.loadAddon(this.attachAddon);
}
});
this.ws.connect();
}

componentDidMount() {
this.term.open(this.terminalRef.current);
this.term.input("agetty --show-issue/n");
this.term.writeln("Welcome to agama shell");
this.term.focus();
}

render() {
return <div ref={this.terminalRef} />;
}
}
Loading
Loading