Skip to content

Commit

Permalink
chore (refactoring): cleanup code
Browse files Browse the repository at this point in the history
  • Loading branch information
mickael-kerjean committed Jan 22, 2024
1 parent 5512428 commit 8b288e4
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 56 deletions.
42 changes: 25 additions & 17 deletions ctrl/socket.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,55 +97,63 @@ EOF
}
}()

Log.Info("connected client")
for {
messageType, reader, err := conn.NextReader()
if websocket.IsCloseError(err, websocket.CloseGoingAway) {
return
} else if err != nil {
Log.Error("socket.go::nextReader unexpected close error %s", err.Error())
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseNoStatusReceived) {
Log.Error("socket.go::nextReader unexpected close error %s", err.Error())
return
}
Log.Debug("socket.go::disconnection_event - browser is disconnected")
return
} else if messageType == websocket.TextMessage {
conn.WriteMessage(websocket.TextMessage, []byte("Unexpected text message"))
continue
Log.Debug("socket.go::expectation_failed - Unexpected text message")
return
}

dataTypeBuf := make([]byte, 1)
read, err := reader.Read(dataTypeBuf)
if err != nil {
conn.WriteMessage(websocket.TextMessage, []byte("Unable to read message type from reader"))
Log.Error("socket.go::error - Unable to read message type from reader")
return
} else if read != 1 {
Log.Error("socket.go::expectation_failed - Unexpected message size")
return
}

switch dataTypeBuf[0] {
case 0:
Log.Info("disconnected")
return
case 1:
b, err := io.ReadAll(reader)
if err != nil {
conn.WriteMessage(websocket.TextMessage, []byte("Error copying bytes: "+err.Error()))
continue
Log.Error("socket.go::error - copying bytes: %s", err.Error())
return
}
_, err = tty.Write(b)
if err != nil {
conn.WriteMessage(websocket.TextMessage, []byte("Error writing bytes: "+err.Error()))
continue
Log.Error("socket.go::error - writing bytes: %s", err.Error())
return
}
case 1:
case 2:
decoder := json.NewDecoder(reader)
if err := decoder.Decode(&resizeMessage); err != nil {
conn.WriteMessage(websocket.TextMessage, []byte("Error decoding resize message: "+err.Error()))
continue
Log.Error("socket.go::error - decoding resize message: %s", err.Error())
return
}
if _, _, errno := syscall.Syscall(
syscall.SYS_IOCTL,
tty.Fd(),
syscall.TIOCSWINSZ,
uintptr(unsafe.Pointer(&resizeMessage)),
); errno != 0 {
conn.WriteMessage(websocket.TextMessage, []byte("Unable to resize terminal: "+err.Error()))
Log.Error("socket.go::expectation_failed - errno[%+v]", errno)
return
}
default:
conn.WriteMessage(websocket.TextMessage, []byte("Unknown data type: "+err.Error()))
Log.Error("socket.go::expectation_failed - unknown socket data type: %+v", dataTypeBuf)
return
}
}
}
32 changes: 20 additions & 12 deletions ctrl/src/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -65,18 +65,27 @@
return;
}

window.onresize = function() {
fitAddon.fit();
function debounce(callback, delay) {
let timer;
return function() {
clearTimeout(timer)
timer = setTimeout(() => {
callback();
}, delay)
}
}
window.onresize = debounce(function() {
fitAddon.fit();
}, 150);

websocket.onopen = function(e) {
term.onData(function(data) {
websocket.send(new TextEncoder().encode("\x00" + data));
websocket.send(new TextEncoder().encode("\x01" + JSON.stringify({cols: term.cols, rows: term.rows})))
websocket.send(new TextEncoder().encode("\x01" + data));
websocket.send(new TextEncoder().encode("\x02" + JSON.stringify({cols: term.cols, rows: term.rows})))
});
term.onResize(function(evt) {
fitAddon.fit();
websocket.send(new TextEncoder().encode("\x01" + JSON.stringify({cols: evt.cols, rows: evt.rows})))
websocket.send(new TextEncoder().encode("\x02" + JSON.stringify({cols: evt.cols, rows: evt.rows})))
});
term.onTitleChange(function(title) {
document.title = title;
Expand All @@ -89,23 +98,22 @@
term.write(textDecoder.decode(new Uint8Array(e.data)));
return;
}
websocket.onclose = null;
websocket.close();
if (e.type === "message" && e.data.indexOf("input/output error") > 0) {
// even triggered on exit
term.dispose();
location.href = "/";
if (location.pathname !== "/") location.pathname = "/";
return;
}
term.writeln("Something went wrong");
}

websocket.onclose = function(){
term.writeln("Session terminated");
location.href = "/";
websocket.onclose = function() {
window.alert("Disconnected");
location.pathname = "/";
}

websocket.onerror = function(e){
term.writeln("Websocket Error");
term.writeln("Socket error");
}
}

Expand Down
59 changes: 32 additions & 27 deletions webfleet/ctrl/socket.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"io"
"net/http"
"os"
"strings"
"time"

Expand All @@ -19,23 +20,29 @@ import (
"github.com/sirupsen/logrus"
)

var srv *remotedialer.Server
var (
srv *remotedialer.Server
upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
)

func init() {
logrus.SetFormatter(&logrus.TextFormatter{
DisableColors: true,
})
// logrus.SetLevel(logrus.DebugLevel)
// remotedialer.PrintTunnelData = true
logrus.SetLevel(logrus.FatalLevel)

authorizer := func(req *http.Request) (string, bool, error) {
id := req.Header.Get("x-machine-id")
return id, id != "", nil
if os.Getenv("DEBUG") == "true" {
logrus.SetLevel(logrus.DebugLevel)
remotedialer.PrintTunnelData = true
}
srv = remotedialer.New(
authorizer,
func(rw http.ResponseWriter, req *http.Request, code int, err error) { // error writer
func(req *http.Request) (string, bool, error) {
id := req.Header.Get("x-machine-id")
return id, id != "", nil
},
func(rw http.ResponseWriter, req *http.Request, code int, err error) {
rw.WriteHeader(code)
rw.Write([]byte(err.Error()))
},
Expand All @@ -44,15 +51,10 @@ func init() {
srv.PeerID = "id"
}

var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}

func ClientSocket(w http.ResponseWriter, r *http.Request, dialer remotedialer.Dialer, url string, tenant string) {
proxyConn, err := upgrader.Upgrade(w, r, nil)
browserConn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
Log.Error("socket.go::upgrade_error tenant[%s] err[%s]", tenant, err.Error())
Log.Error("socket.go::upgrade_error tenant=%s err=%s", tenant, err.Error())
w.Write([]byte(err.Error()))
return
}
Expand All @@ -79,33 +81,36 @@ func ClientSocket(w http.ResponseWriter, r *http.Request, dialer remotedialer.Di
}(),
)
if err != nil {
Log.Error("socket.go::connection_failed tenant[%s] err[%s]", tenant, err.Error())
Log.Error("socket.go::connection_failed tenant=%s err=%s", tenant, err.Error())
return
}
Log.Info("connected to %s", url)
Log.Info("socket.go::connected tenant=%s", tenant)
go func() {
for {
mtype, message, err := appConn.ReadMessage()
if err != nil {
Log.Error("socket.go::conn::read_message tenant[%s] err[%s]", tenant, err.Error())
Log.Error("socket.go::conn::read_message tenant=%s err=%s", tenant, err.Error())
return
}
err = proxyConn.WriteMessage(mtype, message)
if err != nil {
Log.Error("socket.go::conn::write_message tenant[%s] err[%s]", tenant, err.Error())
if err = browserConn.WriteMessage(mtype, message); err != nil {
Log.Error("socket.go::conn::write_message tenant=%s err=%s", tenant, err.Error())
return
}
}
}()
for {
mtype, message, err := proxyConn.ReadMessage()
mtype, message, err := browserConn.ReadMessage()
if err != nil {
Log.Error("socket.go::proxy::read_message tenant[%s] err[%s]", tenant, err.Error())
if websocket.IsCloseError(err, websocket.CloseGoingAway, websocket.CloseNoStatusReceived) {
Log.Debug("socket.go::disconnected::browser tenant=%s", tenant)
appConn.WriteMessage(websocket.BinaryMessage, []byte{0})
return
}
Log.Error("socket.go::proxy::read_message tenant=%s err=%s", tenant, err.Error())
return
}
err = appConn.WriteMessage(mtype, message)
if err != nil {
Log.Error("socket.go::proxy::write_message tenant[%s] err[%s]", tenant, err.Error())
if err = appConn.WriteMessage(mtype, message); err != nil {
Log.Error("socket.go::proxy::write_message tenant=%s err=%s", tenant, err.Error())
return
}
}
Expand Down

0 comments on commit 8b288e4

Please sign in to comment.