Skip to content

Commit

Permalink
fix: graceful shutdown (#54)
Browse files Browse the repository at this point in the history
Signed-off-by: Carlos A Becker <[email protected]>
  • Loading branch information
caarlos0 authored Jan 11, 2022
1 parent 7efc677 commit 33176d0
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
24 changes: 21 additions & 3 deletions cmd/soft/main.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
package main

import (
"context"
"flag"
"fmt"
"log"
"os"
"os/signal"
"syscall"
"time"

"github.com/charmbracelet/soft-serve/config"
"github.com/charmbracelet/soft-serve/server"
Expand Down Expand Up @@ -49,9 +53,23 @@ func main() {

cfg := config.DefaultConfig()
s := server.NewServer(cfg)
log.Printf("Starting SSH server on %s:%d\n", cfg.Host, cfg.Port)
err := s.Start()
if err != nil {

done := make(chan os.Signal, 1)
signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)

log.Printf("Starting SSH server on %s:%d", cfg.Host, cfg.Port)
go func() {
if err := s.Start(); err != nil {
log.Fatalln(err)
}
}()

<-done

log.Printf("Stopping SSH server on %s:%d", cfg.Host, cfg.Port)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer func() { cancel() }()
if err := s.Shutdown(ctx); err != nil {
log.Fatalln(err)
}
}
6 changes: 6 additions & 0 deletions server/server.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package server

import (
"context"
"fmt"
"log"

Expand Down Expand Up @@ -63,3 +64,8 @@ func (srv *Server) Reload() error {
func (srv *Server) Start() error {
return srv.SSHServer.ListenAndServe()
}

// Shutdown lets the server gracefully shutdown.
func (srv *Server) Shutdown(ctx context.Context) error {
return srv.SSHServer.Shutdown(ctx)
}

0 comments on commit 33176d0

Please sign in to comment.