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

Websocket Termination Fixed #144

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
51 changes: 51 additions & 0 deletions services/client/client.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package client

import (
"time"
"context"
"github.com/gorilla/websocket"
"github.com/tiagorlampert/CHAOS/internal/utils"
Expand Down Expand Up @@ -43,3 +44,53 @@ type Service interface {
SendCommand(ctx context.Context, input SendCommandInput) (SendCommandOutput, error)
BuildClient(BuildClientBinaryInput) (string, error)
}

// function to handle reconnection
func (c *Client) reconnect() error {
backoff := time.Second
for {
c.conn, _, err := websocket.DefaultDialer.Dial(c.url, nil)
if err == nil {
return nil
}
if backoff > time.Minute {
return err
}
time.Sleep(backoff)
backoff *= 2
}
}

// Modify the main loop to handle unexpected termination
func (c *Client) run() {
for {
err := c.readPump()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
// Log the error here
log.Printf("Unexpected websocket closure: %v", err)
}
// Attempt to reconnect
if err := c.reconnect(); err != nil {
log.Printf("Failed to reconnect: %v", err)
return
}
// Reset any necessary client state here
}
}
}

// Modify the health check and device request functions
func (c *Client) sendHealthCheck() error {
if c.conn == nil {
return errors.New("Connection is not established")
}
return c.conn.WriteMessage(websocket.TextMessage, []byte("GET /health"))
}

func (c *Client) sendDeviceRequest() error {
if c.conn == nil {
return errors.New("Connection is not established")
}
return c.conn.WriteMessage(websocket.TextMessage, []byte("POST /device"))
}