Skip to content

Commit

Permalink
fix: adds WebSocket ping to interactive terminal (#14191)
Browse files Browse the repository at this point in the history
This adds a WebSocket ping message on a 5-second interval, sent
from the server to the client. This ensures that the interactive
terminal will remain open and won't be closed by load balancers
that are reaping idle connections.

Signed-off-by: Edmund Rhudy <erhudy@users.noreply.github.com>
  • Loading branch information
erhudy committed Jun 23, 2023
1 parent ec2fff5 commit a218ef5
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
5 changes: 5 additions & 0 deletions server/application/terminal.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"io"
"net/http"
"time"

"github.com/argoproj/gitops-engine/pkg/utils/kube"
log "github.com/sirupsen/logrus"
Expand Down Expand Up @@ -228,6 +229,10 @@ func (s *terminalHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
defer session.Done()

// send pings across the WebSocket channel at regular intervals to keep it alive through
// load balancers which may close an idle connection after some period of time
go session.StartKeepalives(time.Second * 5)

if isValidShell(s.allowedShells, shell) {
cmd := []string{shell}
err = startProcess(kubeClientset, config, namespace, podName, container, cmd, session)
Expand Down
28 changes: 28 additions & 0 deletions server/application/websocket.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,23 @@ func (t *terminalSession) Done() {
close(t.doneChan)
}

func (t *terminalSession) StartKeepalives(dur time.Duration) {
ticker := time.NewTicker(dur)
defer ticker.Stop()
for {
select {
case <-ticker.C:
err := t.Ping()
if err != nil {
log.Errorf("ping error: %v", err)
return
}
case <-t.doneChan:
return
}
}
}

// Next called in a loop from remotecommand as long as the process is running
func (t *terminalSession) Next() *remotecommand.TerminalSize {
select {
Expand Down Expand Up @@ -86,6 +103,17 @@ func (t *terminalSession) Read(p []byte) (int, error) {
}
}

// Ping called periodically to ensure connection stays alive through load balancers
func (t *terminalSession) Ping() error {
t.writeLock.Lock()
err := t.wsConn.WriteMessage(websocket.PingMessage, []byte("ping"))
t.writeLock.Unlock()
if err != nil {
log.Errorf("ping message err: %v", err)
}
return err
}

// Write called from remotecommand whenever there is any output
func (t *terminalSession) Write(p []byte) (int, error) {
msg, err := json.Marshal(TerminalMessage{
Expand Down

0 comments on commit a218ef5

Please sign in to comment.