Worker: auto reconnect to server

This commit is contained in:
Samuel Lorch 2024-04-26 22:43:28 +02:00
parent ab71e2b90c
commit 5dbd15c71c

View file

@ -5,6 +5,8 @@ import (
"io"
"log/slog"
"net/http"
"os"
"os/signal"
"time"
"git.lastassault.de/speatzle/morffix/config"
@ -15,10 +17,45 @@ import (
"nhooyr.io/websocket"
)
var conf config.Config
func Start(_conf config.Config) {
conf = _conf
ctx, cancel := context.WithCancel(context.Background())
uuid := uuid.New()
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, os.Interrupt)
exit := false
go func() {
<-sigs
slog.InfoContext(ctx, "Got Signal...")
exit = true
cancel()
}()
for {
if exit {
slog.InfoContext(ctx, "Done")
return
}
connectToServer(ctx, uuid)
if exit {
slog.InfoContext(ctx, "Done")
return
}
time.Sleep(time.Second)
}
}
func connectToServer(ctx context.Context, uuid uuid.UUID) {
slog.InfoContext(ctx, "Connecting to Server...", "Address", conf.Worker.Address)
headers := http.Header{}
headers.Add(constants.SHARED_SECRET_HEADER, conf.SharedSecret)
headers.Add(constants.NAME_HEADER, conf.Worker.Name)
headers.Add(constants.UUID_HEADER, uuid.String())
c, res, err := websocket.Dial(ctx, conf.Worker.Address, &websocket.DialOptions{
HTTPHeader: headers,
})