http.go 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. package main
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "log"
  8. "net/http"
  9. "strconv"
  10. "time"
  11. "github.com/abh/geodns/v3/monitor"
  12. "github.com/abh/geodns/v3/zones"
  13. "github.com/prometheus/client_golang/prometheus/promhttp"
  14. "golang.org/x/sync/errgroup"
  15. )
  16. type httpServer struct {
  17. mux *http.ServeMux
  18. zones *zones.MuxManager
  19. serverInfo *monitor.ServerInfo
  20. }
  21. type rate struct {
  22. Name string
  23. Count int64
  24. Metrics zones.ZoneMetrics
  25. }
  26. type rates []*rate
  27. func (s rates) Len() int { return len(s) }
  28. func (s rates) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  29. type ratesByCount struct{ rates }
  30. func (s ratesByCount) Less(i, j int) bool {
  31. ic := s.rates[i].Count
  32. jc := s.rates[j].Count
  33. if ic == jc {
  34. return s.rates[i].Name < s.rates[j].Name
  35. }
  36. return ic > jc
  37. }
  38. func topParam(req *http.Request, def int) int {
  39. req.ParseForm()
  40. topOption := def
  41. topParam := req.Form["top"]
  42. if len(topParam) > 0 {
  43. var err error
  44. topOption, err = strconv.Atoi(topParam[0])
  45. if err != nil {
  46. topOption = def
  47. }
  48. }
  49. return topOption
  50. }
  51. func NewHTTPServer(mm *zones.MuxManager, serverInfo *monitor.ServerInfo) *httpServer {
  52. hs := &httpServer{
  53. zones: mm,
  54. mux: &http.ServeMux{},
  55. serverInfo: serverInfo,
  56. }
  57. hs.mux.HandleFunc("/", hs.mainServer)
  58. hs.mux.Handle("/metrics", promhttp.Handler())
  59. return hs
  60. }
  61. func (hs *httpServer) Mux() *http.ServeMux {
  62. return hs.mux
  63. }
  64. func (hs *httpServer) Run(ctx context.Context, listen string) error {
  65. log.Println("Starting HTTP interface on", listen)
  66. srv := http.Server{
  67. Addr: listen,
  68. Handler: &basicauth{h: hs.mux},
  69. ReadTimeout: 5 * time.Second,
  70. IdleTimeout: 10 * time.Second,
  71. WriteTimeout: 10 * time.Second,
  72. }
  73. g, ctx := errgroup.WithContext(ctx)
  74. g.Go(func() error {
  75. err := srv.ListenAndServe()
  76. if err != nil {
  77. if !errors.Is(err, http.ErrServerClosed) {
  78. return err
  79. }
  80. }
  81. return nil
  82. })
  83. g.Go(func() error {
  84. <-ctx.Done()
  85. log.Printf("shutting down http server")
  86. return srv.Shutdown(ctx)
  87. })
  88. return g.Wait()
  89. }
  90. func (hs *httpServer) mainServer(w http.ResponseWriter, req *http.Request) {
  91. if req.RequestURI != "/version" {
  92. http.NotFound(w, req)
  93. return
  94. }
  95. w.Header().Set("Content-Type", "text/plain")
  96. w.WriteHeader(200)
  97. io.WriteString(w, `GeoDNS `+hs.serverInfo.Version+`\n`)
  98. }
  99. type basicauth struct {
  100. h http.Handler
  101. }
  102. func (b *basicauth) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  103. cfgMutex.RLock()
  104. user := Config.HTTP.User
  105. password := Config.HTTP.Password
  106. cfgMutex.RUnlock()
  107. if len(user) == 0 {
  108. b.h.ServeHTTP(w, r)
  109. return
  110. }
  111. ruser, rpass, ok := r.BasicAuth()
  112. if ok {
  113. if ruser == user && rpass == password {
  114. b.h.ServeHTTP(w, r)
  115. return
  116. }
  117. }
  118. w.Header().Set("WWW-Authenticate", fmt.Sprintf(`Basic realm=%q`, "GeoDNS Status"))
  119. http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
  120. }