Skip to content

Commit

Permalink
refactor(ssh): graceful disconnect session record websocket
Browse files Browse the repository at this point in the history
  • Loading branch information
henrybarreto authored and gustavosbarreto committed Nov 29, 2024
1 parent 37e67c9 commit 7857c3b
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 4 deletions.
2 changes: 1 addition & 1 deletion ssh/server/channels/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ func pipe(ctx gliderssh.Context, sess *session.Session, client gossh.Channel, ag
}

if recording {
if err := camera.WriteJSON(&models.SessionRecorded{ //nolint:errcheck
if err := camera.WriteFrame(&models.SessionRecorded{ //nolint:errcheck
UID: sess.UID,
Namespace: sess.Lookup["domain"],
Message: string(buffer[:read]),
Expand Down
37 changes: 37 additions & 0 deletions ssh/session/camera.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package session

import (
"time"

"github.com/gorilla/websocket"
"github.com/shellhub-io/shellhub/pkg/models"
)

type Camera struct {
conn *websocket.Conn
}

// Close closes the camera's WebSocket connections normally.
func (c *Camera) Close() error {
if err := c.conn.WriteControl(
websocket.CloseMessage,
websocket.FormatCloseMessage(websocket.CloseNormalClosure, "session record connection done"),
time.Now().Add(time.Minute),
); err != nil {
return err
}

return c.conn.Close()
}

// WriteFrame writes a session's frame into the WebSocket connection.
func (c *Camera) WriteFrame(frame *models.SessionRecorded) error {
return c.conn.WriteJSON(frame)
}

// NewCamera creates a new camera, using a WebSocket connections.
func NewCamera(conn *websocket.Conn) *Camera {
return &Camera{
conn: conn,
}
}
5 changes: 2 additions & 3 deletions ssh/session/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import (
"time"

gliderssh "github.com/gliderlabs/ssh"
"github.com/gorilla/websocket"
"github.com/shellhub-io/shellhub/pkg/api/internalclient"
"github.com/shellhub-io/shellhub/pkg/api/requests"
"github.com/shellhub-io/shellhub/pkg/cache"
Expand Down Expand Up @@ -425,15 +424,15 @@ func (s *Session) Auth(ctx gliderssh.Context, auth Auth) error {
return nil
}

func (s *Session) Record(ctx context.Context, url string) (*websocket.Conn, error) {
func (s *Session) Record(ctx context.Context, url string) (*Camera, error) {
conn, err := s.api.RecordSession(ctx, s.UID, url)
if err != nil {
log.WithError(err).Error("failed to start the record session process")

return nil, err
}

return conn, nil
return NewCamera(conn), nil
}

func Event[D any](sess *Session, t string, data []byte) {
Expand Down

0 comments on commit 7857c3b

Please sign in to comment.