97 lines
2.3 KiB
Go
97 lines
2.3 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"os/signal"
|
|
"syscall"
|
|
"time"
|
|
|
|
"scm.bstein.dev/bstein/soteria/internal/config"
|
|
"scm.bstein.dev/bstein/soteria/internal/k8s"
|
|
"scm.bstein.dev/bstein/soteria/internal/longhorn"
|
|
"scm.bstein.dev/bstein/soteria/internal/server"
|
|
)
|
|
|
|
type applicationServer interface {
|
|
Start(context.Context)
|
|
Handler() http.Handler
|
|
}
|
|
|
|
var (
|
|
loadConfigFn = config.Load
|
|
newK8sClientFn = k8s.New
|
|
newLonghornClient = longhorn.New
|
|
newServerFn = func(cfg *config.Config, client *k8s.Client, lh *longhorn.Client) applicationServer {
|
|
return server.New(cfg, client, lh)
|
|
}
|
|
listenAndServeFn = func(s *http.Server) error { return s.ListenAndServe() }
|
|
shutdownServerFn = func(s *http.Server, ctx context.Context) error { return s.Shutdown(ctx) }
|
|
runApplicationFunc = run
|
|
)
|
|
|
|
func main() {
|
|
log.SetFlags(log.LstdFlags | log.LUTC)
|
|
runCtx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
|
defer stop()
|
|
|
|
if err := runApplicationFunc(runCtx); err != nil {
|
|
log.Fatalf("%v", err)
|
|
}
|
|
}
|
|
|
|
func run(runCtx context.Context) error {
|
|
cfg, err := loadConfigFn()
|
|
if err != nil {
|
|
return fmt.Errorf("config: %w", err)
|
|
}
|
|
|
|
client, err := newK8sClientFn()
|
|
if err != nil {
|
|
return fmt.Errorf("k8s client: %w", err)
|
|
}
|
|
|
|
longhornClient := newLonghornClient(cfg.LonghornURL)
|
|
srv := newServerFn(cfg, client, longhornClient)
|
|
srv.Start(runCtx)
|
|
httpServer := &http.Server{
|
|
Addr: cfg.ListenAddr,
|
|
Handler: srv.Handler(),
|
|
ReadHeaderTimeout: 5 * time.Second,
|
|
ReadTimeout: 15 * time.Second,
|
|
WriteTimeout: 60 * time.Second,
|
|
IdleTimeout: 30 * time.Second,
|
|
}
|
|
|
|
errCh := make(chan error, 1)
|
|
go func() {
|
|
log.Printf("soteria listening on %s", cfg.ListenAddr)
|
|
errCh <- listenAndServeFn(httpServer)
|
|
}()
|
|
|
|
select {
|
|
case <-runCtx.Done():
|
|
log.Printf("shutdown signal: %v", runCtx.Err())
|
|
case err := <-errCh:
|
|
if err != nil && !errors.Is(err, http.ErrServerClosed) {
|
|
return fmt.Errorf("server error: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
defer cancel()
|
|
if err := shutdownServerFn(httpServer, ctx); err != nil {
|
|
log.Printf("shutdown error: %v", err)
|
|
}
|
|
|
|
err = <-errCh
|
|
if err != nil && !errors.Is(err, http.ErrServerClosed) {
|
|
log.Printf("server error: %v", err)
|
|
}
|
|
return nil
|
|
}
|