2019-05-08 23:45:04 +02:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
"time"
|
|
|
|
|
2021-08-16 23:55:05 +02:00
|
|
|
"github.com/eko/pihole-exporter/internal/pihole"
|
2019-05-08 23:45:04 +02:00
|
|
|
"golang.org/x/net/context"
|
|
|
|
)
|
|
|
|
|
2019-05-09 21:11:31 +02:00
|
|
|
// Server is the struct for the HTTP server.
|
2019-05-08 23:45:04 +02:00
|
|
|
type Server struct {
|
|
|
|
httpServer *http.Server
|
|
|
|
}
|
|
|
|
|
2019-05-09 21:11:31 +02:00
|
|
|
// NewServer method initializes a new HTTP server instance and associates
|
|
|
|
// the different routes that will be used by Prometheus (metrics) or for monitoring (readiness, liveness).
|
2021-08-16 23:55:05 +02:00
|
|
|
func NewServer(port string, client *pihole.Client) *Server {
|
2019-05-08 23:45:04 +02:00
|
|
|
mux := http.NewServeMux()
|
|
|
|
httpServer := &http.Server{Addr: ":" + port, Handler: mux}
|
|
|
|
|
|
|
|
s := &Server{
|
|
|
|
httpServer: httpServer,
|
|
|
|
}
|
|
|
|
|
2021-08-16 23:55:05 +02:00
|
|
|
mux.Handle("/metrics", client.Metrics())
|
2019-05-08 23:45:04 +02:00
|
|
|
mux.Handle("/readiness", s.readinessHandler())
|
|
|
|
mux.Handle("/liveness", s.livenessHandler())
|
|
|
|
|
|
|
|
return s
|
|
|
|
}
|
|
|
|
|
2019-05-09 21:11:31 +02:00
|
|
|
// ListenAndServe method serves HTTP requests.
|
2019-05-08 23:45:04 +02:00
|
|
|
func (s *Server) ListenAndServe() {
|
|
|
|
log.Println("Starting HTTP server")
|
|
|
|
|
|
|
|
err := s.httpServer.ListenAndServe()
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("Failed to start serving HTTP requests: %v", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-05-09 21:11:31 +02:00
|
|
|
// Stop method stops the HTTP server (so the exporter become unavailable).
|
2019-05-08 23:45:04 +02:00
|
|
|
func (s *Server) Stop() {
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
s.httpServer.Shutdown(ctx)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) readinessHandler() http.HandlerFunc {
|
2021-08-16 23:55:05 +02:00
|
|
|
return func(w http.ResponseWriter, req *http.Request) {
|
2019-05-08 23:45:04 +02:00
|
|
|
if s.isReady() {
|
|
|
|
w.WriteHeader(http.StatusOK)
|
|
|
|
} else {
|
|
|
|
w.WriteHeader(http.StatusNotFound)
|
|
|
|
}
|
2021-08-16 23:55:05 +02:00
|
|
|
}
|
2019-05-08 23:45:04 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) livenessHandler() http.HandlerFunc {
|
2021-08-16 23:55:05 +02:00
|
|
|
return func(w http.ResponseWriter, req *http.Request) {
|
2019-05-08 23:45:04 +02:00
|
|
|
w.WriteHeader(http.StatusOK)
|
2021-08-16 23:55:05 +02:00
|
|
|
}
|
2019-05-08 23:45:04 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) isReady() bool {
|
|
|
|
return s.httpServer != nil
|
|
|
|
}
|