Skip to content

Commit

Permalink
feat(runner): add runner server util funcs
Browse files Browse the repository at this point in the history
  • Loading branch information
dwisiswant0 committed Jul 11, 2023
1 parent 9955366 commit feeaf42
Showing 1 changed file with 43 additions and 10 deletions.
53 changes: 43 additions & 10 deletions internal/runner/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"fmt"
"os"
"syscall"
"time"

"net/http"
Expand All @@ -14,6 +15,10 @@ import (
"github.com/kitabisa/teler-proxy/pkg/tunnel"
)

type Runner struct {
*http.Server
}

func New(opt *common.Options) error {
reachable := isReachable(opt.Destination, 5*time.Second)
if !reachable {
Expand All @@ -35,27 +40,55 @@ func New(opt *common.Options) error {
ErrorLog: logger,
}

run := &Runner{Server: server}
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt)

go func() {
<-sig
log.Warn("Interuppted. Shutting down...")
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM, syscall.SIGUSR1)

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

if err := server.Shutdown(ctx); err != nil {
log.Fatal("Server shutdown error", "error", err)
go func() {
if err := run.notify(sig); err != nil {
log.Fatal("Something went wrong", "err", err)
}
}()

log.Info("Server started", "port", opt.Port, "pid", os.Getpid())
return run.start()
}

err = server.ListenAndServe()
func (r *Runner) start() error {
err := r.Server.ListenAndServe()
if err != nil && err != http.ErrServerClosed {
return err
}

return nil
}

func (r *Runner) shutdown() error {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

return r.Server.Shutdown(ctx)
}

func (r *Runner) restart() error {
if err := r.shutdown(); err != nil {
return err
}

return r.start()
}

func (r *Runner) notify(sigCh chan os.Signal) error {
for {
sig := <-sigCh
switch sig {
case syscall.SIGINT, syscall.SIGTERM:
log.Warn("Interrupted. Shutting down...")
return r.shutdown()
case syscall.SIGUSR1:
log.Info("Restarting server...")
return r.restart()
}
}
}

0 comments on commit feeaf42

Please sign in to comment.