package api import ( "context" stdtls "crypto/tls" "net" "net/http" "time" "git.giftfish.de/ston1th/haproxy-lb/pkg/alloc" "git.giftfish.de/ston1th/haproxy-lb/pkg/api/types" serverv1 "git.giftfish.de/ston1th/haproxy-lb/pkg/api/v1/server" "git.giftfish.de/ston1th/haproxy-lb/pkg/config" "git.giftfish.de/ston1th/haproxy-lb/pkg/db" "github.com/go-logr/logr" "github.com/gorilla/mux" ) // Server is the webapp and api server type Server struct { srv *http.Server mux *mux.Router log logr.Logger Alloc *alloc.Alloc DB *db.DB cidrs []string gw string Auth []config.BasicAuth init chan struct{} stop chan struct{} stopKeyReset chan struct{} cert string key string laddr string } type notFoundHandler struct { s *Server } func (nf *notFoundHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { types.NewContext(w, r, nf.s).NotFound() } // NewHTTPServer returns a new HTTPServer func NewServer(c *config.Config, log logr.Logger) *Server { s := &Server{ mux: mux.NewRouter(), log: log.WithName("api"), cidrs: c.VIP.VirtualIPs, gw: c.VIP.Gateway, Auth: c.Server.BasicAuth, init: make(chan struct{}), stop: make(chan struct{}), stopKeyReset: make(chan struct{}), cert: c.Server.TLS.Cert, key: c.Server.TLS.Key, laddr: c.Server.Listen, } s.mux.NotFoundHandler = ¬FoundHandler{s} for _, v := range serverv1.Routes { s.mux.HandleFunc(v.Path, s.contextWrapper(v.Handler)).Methods(v.Methods...) } s.start() return s } func (s *Server) UpdateDB(db *db.DB) error { s.db = db if s.Alloc == nil { alloc, err := alloc.NewAlloc(db, s.cidrs, s.gw) if err != nil { return err } s.alloc = alloc close(s.init) } else { s.Alloc.UpdateDB(db) } return nil } func (s *Server) start() error { <-s.init l, err := net.Listen("tcp", h.laddr) if err != nil { return err } // TODO tls config h.srv = &http.Server{ Handler: h.mux, TLSConfig: cfg, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, } go func() { err := h.srv.Serve(l) if err != nil { s.log.Error(err, "") } }() return nil } func (s *Server) contextWrapper(h types.CtxHandler) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { h(types.NewContext(w, r, s)) } } // Stop stops listening for incoming connections and closes currently open connections func (s *Server) Stop() { s.log.Info("stopping") ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) defer cancel() err := h.srv.Shutdown(ctx) if err != nil { s.log.Error(err, "") } s.log.Info("stopped") }