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 Data *types.ContextData cidrs []string gw string 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.Data, nf.s.log).NotFound() } // NewHTTPServer returns a new HTTPServer func NewServer(c *config.Config, log logr.Logger) *Server { s := &Server{ mux: mux.NewRouter(), log: log, cidrs: c.VIP.VirtualIPs, gw: c.VIP.Gateway, Data: &types.ContextData{ 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.Data.DB = db if s.Data.Alloc == nil { alloc, err := alloc.NewAlloc(db, s.cidrs, s.gw) if err != nil { return err } s.Data.Alloc = alloc close(s.init) } else { s.Data.Alloc.UpdateDB(db) } return nil } func (s *Server) start() error { <-s.init l, err := net.Listen("tcp", s.laddr) if err != nil { return err } // TODO tls config s.srv = &http.Server{ Handler: s.mux, //TLSConfig: cfg, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, } go func() { err := s.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.Data, s.log)) } } // 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 := s.srv.Shutdown(ctx) if err != nil { s.log.Error(err, "") } s.log.Info("stopped") }