tracker/frontend/http/frontend.go

192 lines
5 KiB
Go
Raw Normal View History

2016-08-07 04:41:33 +02:00
// Package http implements a BitTorrent frontend via the HTTP protocol as
2016-08-04 20:08:26 +02:00
// described in BEP 3 and BEP 23.
package http
2016-08-05 07:47:04 +02:00
import (
2016-08-17 04:32:15 +02:00
"context"
2016-08-05 07:47:04 +02:00
"net"
"net/http"
"time"
log "github.com/Sirupsen/logrus"
2016-08-05 07:47:04 +02:00
"github.com/julienschmidt/httprouter"
"github.com/prometheus/client_golang/prometheus"
"github.com/tylerb/graceful"
2016-08-17 03:42:08 +02:00
"github.com/chihaya/chihaya/frontend"
"github.com/chihaya/chihaya/middleware"
2016-08-05 07:47:04 +02:00
)
2016-08-05 09:35:17 +02:00
func init() {
prometheus.MustRegister(promResponseDurationMilliseconds)
recordResponseDuration("action", nil, time.Second)
}
2016-08-04 20:48:32 +02:00
var promResponseDurationMilliseconds = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
2016-08-17 03:42:08 +02:00
Name: "chihaya_http_response_duration_milliseconds",
2016-08-04 20:48:32 +02:00
Help: "The duration of time it takes to receive and write a response to an API request",
Buckets: prometheus.ExponentialBuckets(9.375, 2, 10),
},
[]string{"action", "error"},
)
2016-08-07 04:41:33 +02:00
// recordResponseDuration records the duration of time to respond to a Request
// in milliseconds .
2016-08-05 07:47:04 +02:00
func recordResponseDuration(action string, err error, duration time.Duration) {
var errString string
if err != nil {
errString = err.Error()
}
2016-08-04 20:48:32 +02:00
promResponseDurationMilliseconds.
2016-08-05 07:47:04 +02:00
WithLabelValues(action, errString).
2016-08-04 20:48:32 +02:00
Observe(float64(duration.Nanoseconds()) / float64(time.Millisecond))
}
2016-08-04 20:08:26 +02:00
// Config represents all of the configurable options for an HTTP BitTorrent
2016-08-07 04:41:33 +02:00
// Frontend.
type Config struct {
Addr string `yaml:"addr"`
ReadTimeout time.Duration `yaml:"read_timeout"`
WriteTimeout time.Duration `yaml:"write_timeout"`
RequestTimeout time.Duration `yaml:"request_timeout"`
AllowIPSpoofing bool `yaml:"allow_ip_spoofing"`
RealIPHeader string `yaml:"real_ip_header"`
}
2016-08-07 04:41:33 +02:00
// Frontend holds the state of an HTTP BitTorrent Frontend.
type Frontend struct {
grace *graceful.Server
2016-08-10 02:08:15 +02:00
logic frontend.TrackerLogic
Config
}
2016-08-07 04:41:33 +02:00
// NewFrontend allocates a new instance of a Frontend.
2016-08-10 02:08:15 +02:00
func NewFrontend(logic frontend.TrackerLogic, cfg Config) *Frontend {
2016-08-07 04:41:33 +02:00
return &Frontend{
2016-08-10 02:08:15 +02:00
logic: logic,
Config: cfg,
}
}
2016-08-04 20:08:26 +02:00
// Stop provides a thread-safe way to shutdown a currently running Tracker.
2016-08-07 04:41:33 +02:00
func (t *Frontend) Stop() {
2016-08-04 06:18:58 +02:00
t.grace.Stop(t.grace.Timeout)
<-t.grace.StopChan()
}
2016-08-07 04:41:33 +02:00
func (t *Frontend) handler() http.Handler {
router := httprouter.New()
2016-08-04 06:18:58 +02:00
router.GET("/announce", t.announceRoute)
router.GET("/scrape", t.scrapeRoute)
2016-08-05 07:47:04 +02:00
return router
}
2016-08-04 20:08:26 +02:00
// ListenAndServe listens on the TCP network address t.Addr and blocks serving
// BitTorrent requests until t.Stop() is called or an error is returned.
2016-08-07 04:41:33 +02:00
func (t *Frontend) ListenAndServe() error {
2016-08-04 06:18:58 +02:00
t.grace = &graceful.Server{
Server: &http.Server{
2016-08-04 06:18:58 +02:00
Addr: t.Addr,
Handler: t.handler(),
ReadTimeout: t.ReadTimeout,
WriteTimeout: t.WriteTimeout,
},
2016-08-04 06:18:58 +02:00
Timeout: t.RequestTimeout,
NoSignalHandling: true,
ConnState: func(conn net.Conn, state http.ConnState) {
switch state {
case http.StateNew:
//stats.RecordEvent(stats.AcceptedConnection)
case http.StateClosed:
//stats.RecordEvent(stats.ClosedConnection)
case http.StateHijacked:
panic("http: connection impossibly hijacked")
// Ignore the following cases.
case http.StateActive, http.StateIdle:
default:
panic("http: connection transitioned to unknown state")
}
},
}
2016-08-04 06:18:58 +02:00
t.grace.SetKeepAlivesEnabled(false)
2016-08-04 06:18:58 +02:00
if err := t.grace.ListenAndServe(); err != nil {
if opErr, ok := err.(*net.OpError); !ok || (ok && opErr.Op != "accept") {
panic("http: failed to gracefully run HTTP server: " + err.Error())
}
}
2016-08-05 07:47:04 +02:00
return nil
}
2016-08-10 01:28:59 +02:00
// announceRoute parses and responds to an Announce by using t.TrackerLogic.
2016-08-07 04:41:33 +02:00
func (t *Frontend) announceRoute(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
2016-08-05 07:47:04 +02:00
var err error
2016-08-04 20:48:32 +02:00
start := time.Now()
2016-08-05 07:47:04 +02:00
defer recordResponseDuration("announce", err, time.Since(start))
2016-08-04 20:48:32 +02:00
2016-08-04 06:18:58 +02:00
req, err := ParseAnnounce(r, t.RealIPHeader, t.AllowIPSpoofing)
if err != nil {
WriteError(w, err)
return
}
2016-09-05 18:25:11 +02:00
resp, err := t.logic.HandleAnnounce(context.Background(), req)
if err != nil {
WriteError(w, err)
return
}
err = WriteAnnounceResponse(w, resp)
if err != nil {
WriteError(w, err)
return
}
2016-09-05 18:25:11 +02:00
go t.logic.AfterAnnounce(context.Background(), req, resp)
}
2016-08-10 01:28:59 +02:00
// scrapeRoute parses and responds to a Scrape by using t.TrackerLogic.
2016-08-07 04:41:33 +02:00
func (t *Frontend) scrapeRoute(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
2016-08-05 07:47:04 +02:00
var err error
2016-08-04 20:48:32 +02:00
start := time.Now()
2016-08-05 07:47:04 +02:00
defer recordResponseDuration("scrape", err, time.Since(start))
2016-08-04 20:48:32 +02:00
req, err := ParseScrape(r)
if err != nil {
WriteError(w, err)
return
}
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
log.Errorln("http: unable to determine remote address for scrape:", err)
WriteError(w, err)
return
}
ip := net.ParseIP(host)
ctx := context.WithValue(context.Background(), middleware.ScrapeIsIPv6Key, len(ip) == net.IPv6len)
resp, err := t.logic.HandleScrape(ctx, req)
if err != nil {
WriteError(w, err)
return
}
err = WriteScrapeResponse(w, resp)
if err != nil {
WriteError(w, err)
return
}
2016-09-05 18:25:11 +02:00
go t.logic.AfterScrape(context.Background(), req, resp)
}