main.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  1. // Copyright (C) 2015 Audrius Butkevicius and Contributors (see the CONTRIBUTORS file).
  2. package main
  3. import (
  4. "context"
  5. "crypto/tls"
  6. "crypto/x509"
  7. "encoding/json"
  8. "flag"
  9. "fmt"
  10. "log"
  11. "net"
  12. "net/http"
  13. "net/url"
  14. "os"
  15. "path/filepath"
  16. "strconv"
  17. "strings"
  18. "sync/atomic"
  19. "time"
  20. lru "github.com/hashicorp/golang-lru/v2"
  21. "github.com/prometheus/client_golang/prometheus"
  22. "github.com/prometheus/client_golang/prometheus/promhttp"
  23. "github.com/syncthing/syncthing/cmd/strelaypoolsrv/auto"
  24. "github.com/syncthing/syncthing/lib/assets"
  25. _ "github.com/syncthing/syncthing/lib/automaxprocs"
  26. "github.com/syncthing/syncthing/lib/geoip"
  27. "github.com/syncthing/syncthing/lib/httpcache"
  28. "github.com/syncthing/syncthing/lib/protocol"
  29. "github.com/syncthing/syncthing/lib/rand"
  30. "github.com/syncthing/syncthing/lib/relay/client"
  31. "github.com/syncthing/syncthing/lib/sync"
  32. "github.com/syncthing/syncthing/lib/tlsutil"
  33. )
  34. type location struct {
  35. Latitude float64 `json:"latitude"`
  36. Longitude float64 `json:"longitude"`
  37. City string `json:"city"`
  38. Country string `json:"country"`
  39. Continent string `json:"continent"`
  40. }
  41. type relay struct {
  42. URL string `json:"url"`
  43. Location location `json:"location"`
  44. uri *url.URL
  45. Stats *stats `json:"stats"`
  46. StatsRetrieved time.Time `json:"statsRetrieved"`
  47. }
  48. type stats struct {
  49. StartTime time.Time `json:"startTime"`
  50. UptimeSeconds int `json:"uptimeSeconds"`
  51. PendingSessionKeys int `json:"numPendingSessionKeys"`
  52. ActiveSessions int `json:"numActiveSessions"`
  53. Connections int `json:"numConnections"`
  54. Proxies int `json:"numProxies"`
  55. BytesProxied int `json:"bytesProxied"`
  56. GoVersion string `json:"goVersion"`
  57. GoOS string `json:"goOS"`
  58. GoArch string `json:"goArch"`
  59. GoMaxProcs int `json:"goMaxProcs"`
  60. GoRoutines int `json:"goNumRoutine"`
  61. Rates []int64 `json:"kbps10s1m5m15m30m60m"`
  62. Options struct {
  63. NetworkTimeout int `json:"network-timeout"`
  64. PintInterval int `json:"ping-interval"`
  65. MessageTimeout int `json:"message-timeout"`
  66. SessionRate int `json:"per-session-rate"`
  67. GlobalRate int `json:"global-rate"`
  68. Pools []string `json:"pools"`
  69. ProvidedBy string `json:"provided-by"`
  70. } `json:"options"`
  71. }
  72. func (r relay) String() string {
  73. return r.URL
  74. }
  75. type request struct {
  76. relay *relay
  77. result chan result
  78. queueTimer *prometheus.Timer
  79. }
  80. type result struct {
  81. err error
  82. eviction time.Duration
  83. }
  84. var (
  85. testCert tls.Certificate
  86. knownRelaysFile = filepath.Join(os.TempDir(), "strelaypoolsrv_known_relays")
  87. listen = ":80"
  88. dir string
  89. evictionTime = time.Hour
  90. debug bool
  91. permRelaysFile string
  92. ipHeader string
  93. proto string
  94. statsRefresh = time.Minute
  95. requestQueueLen = 64
  96. requestProcessors = 8
  97. geoipLicenseKey = os.Getenv("GEOIP_LICENSE_KEY")
  98. geoipAccountID, _ = strconv.Atoi(os.Getenv("GEOIP_ACCOUNT_ID"))
  99. requests chan request
  100. mut = sync.NewRWMutex()
  101. knownRelays = make([]*relay, 0)
  102. permanentRelays = make([]*relay, 0)
  103. evictionTimers = make(map[string]*time.Timer)
  104. globalBlocklist = newErrorTracker(1000)
  105. )
  106. const (
  107. httpStatusEnhanceYourCalm = 429
  108. )
  109. func main() {
  110. log.SetOutput(os.Stdout)
  111. log.SetFlags(log.Lshortfile)
  112. flag.StringVar(&listen, "listen", listen, "Listen address")
  113. flag.StringVar(&dir, "keys", dir, "Directory where http-cert.pem and http-key.pem is stored for TLS listening")
  114. flag.BoolVar(&debug, "debug", debug, "Enable debug output")
  115. flag.DurationVar(&evictionTime, "eviction", evictionTime, "After how long the relay is evicted")
  116. flag.StringVar(&permRelaysFile, "perm-relays", "", "Path to list of permanent relays")
  117. flag.StringVar(&knownRelaysFile, "known-relays", knownRelaysFile, "Path to list of current relays")
  118. flag.StringVar(&ipHeader, "ip-header", "", "Name of header which holds clients ip:port. Only meaningful when running behind a reverse proxy.")
  119. flag.StringVar(&proto, "protocol", "tcp", "Protocol used for listening. 'tcp' for IPv4 and IPv6, 'tcp4' for IPv4, 'tcp6' for IPv6")
  120. flag.DurationVar(&statsRefresh, "stats-refresh", statsRefresh, "Interval at which to refresh relay stats")
  121. flag.IntVar(&requestQueueLen, "request-queue", requestQueueLen, "Queue length for incoming test requests")
  122. flag.IntVar(&requestProcessors, "request-processors", requestProcessors, "Number of request processor routines")
  123. flag.StringVar(&geoipLicenseKey, "geoip-license-key", geoipLicenseKey, "License key for GeoIP database")
  124. flag.Parse()
  125. requests = make(chan request, requestQueueLen)
  126. geoip, err := geoip.NewGeoLite2CityProvider(context.Background(), geoipAccountID, geoipLicenseKey, os.TempDir())
  127. if err != nil {
  128. log.Fatalln("Failed to create GeoIP provider:", err)
  129. }
  130. go geoip.Serve(context.TODO())
  131. var listener net.Listener
  132. if permRelaysFile != "" {
  133. permanentRelays = loadRelays(permRelaysFile, geoip)
  134. }
  135. testCert = createTestCertificate()
  136. for i := 0; i < requestProcessors; i++ {
  137. go requestProcessor(geoip)
  138. }
  139. // Load relays from cache in the background.
  140. // Load them in a serial fashion to make sure any genuine requests
  141. // are not dropped.
  142. go func() {
  143. for _, relay := range loadRelays(knownRelaysFile, geoip) {
  144. resultChan := make(chan result)
  145. requests <- request{relay, resultChan, nil}
  146. result := <-resultChan
  147. if result.err != nil {
  148. relayTestsTotal.WithLabelValues("failed").Inc()
  149. } else {
  150. relayTestsTotal.WithLabelValues("success").Inc()
  151. }
  152. }
  153. // Run the the stats refresher once the relays are loaded.
  154. statsRefresher(statsRefresh)
  155. }()
  156. if dir != "" {
  157. if debug {
  158. log.Println("Starting TLS listener on", listen)
  159. }
  160. certFile, keyFile := filepath.Join(dir, "http-cert.pem"), filepath.Join(dir, "http-key.pem")
  161. var cert tls.Certificate
  162. cert, err = tls.LoadX509KeyPair(certFile, keyFile)
  163. if err != nil {
  164. log.Fatalln("Failed to load HTTP X509 key pair:", err)
  165. }
  166. tlsCfg := &tls.Config{
  167. Certificates: []tls.Certificate{cert},
  168. MinVersion: tls.VersionTLS10, // No SSLv3
  169. ClientAuth: tls.RequestClientCert,
  170. CipherSuites: []uint16{
  171. // No RC4
  172. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  173. tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  174. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  175. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  176. tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  177. tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  178. tls.TLS_RSA_WITH_AES_128_CBC_SHA,
  179. tls.TLS_RSA_WITH_AES_256_CBC_SHA,
  180. tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
  181. tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA,
  182. },
  183. }
  184. listener, err = tls.Listen(proto, listen, tlsCfg)
  185. } else {
  186. if debug {
  187. log.Println("Starting plain listener on", listen)
  188. }
  189. listener, err = net.Listen(proto, listen)
  190. }
  191. if err != nil {
  192. log.Fatalln("listen:", err)
  193. }
  194. handler := http.NewServeMux()
  195. handler.HandleFunc("/", handleAssets)
  196. handler.Handle("/endpoint", httpcache.SinglePath(http.HandlerFunc(handleRequest), 15*time.Second))
  197. handler.HandleFunc("/metrics", handleMetrics)
  198. srv := http.Server{
  199. Handler: handler,
  200. ReadTimeout: 10 * time.Second,
  201. }
  202. err = srv.Serve(listener)
  203. if err != nil {
  204. log.Fatalln("serve:", err)
  205. }
  206. }
  207. func handleMetrics(w http.ResponseWriter, r *http.Request) {
  208. timer := prometheus.NewTimer(metricsRequestsSeconds)
  209. // Acquire the mutex just to make sure we're not caught mid-way stats collection
  210. mut.RLock()
  211. promhttp.Handler().ServeHTTP(w, r)
  212. mut.RUnlock()
  213. timer.ObserveDuration()
  214. }
  215. func handleAssets(w http.ResponseWriter, r *http.Request) {
  216. w.Header().Set("Cache-Control", "no-cache, must-revalidate")
  217. path := r.URL.Path[1:]
  218. if path == "" {
  219. path = "index.html"
  220. }
  221. as, ok := auto.Assets()[path]
  222. if !ok {
  223. w.WriteHeader(http.StatusNotFound)
  224. return
  225. }
  226. assets.Serve(w, r, as)
  227. }
  228. func handleRequest(w http.ResponseWriter, r *http.Request) {
  229. timer := prometheus.NewTimer(apiRequestsSeconds.WithLabelValues(r.Method))
  230. w = NewLoggingResponseWriter(w)
  231. defer func() {
  232. timer.ObserveDuration()
  233. lw := w.(*loggingResponseWriter)
  234. apiRequestsTotal.WithLabelValues(r.Method, strconv.Itoa(lw.statusCode)).Inc()
  235. }()
  236. if ipHeader != "" {
  237. hdr := r.Header.Get(ipHeader)
  238. fields := strings.Split(hdr, ",")
  239. if len(fields) > 0 {
  240. r.RemoteAddr = strings.TrimSpace(fields[len(fields)-1])
  241. }
  242. }
  243. w.Header().Set("Access-Control-Allow-Origin", "*")
  244. switch r.Method {
  245. case "GET":
  246. handleGetRequest(w, r)
  247. case "POST":
  248. handlePostRequest(w, r)
  249. default:
  250. if debug {
  251. log.Println("Unhandled HTTP method", r.Method)
  252. }
  253. http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
  254. }
  255. }
  256. func handleGetRequest(rw http.ResponseWriter, r *http.Request) {
  257. rw.Header().Set("Content-Type", "application/json; charset=utf-8")
  258. mut.RLock()
  259. relays := make([]*relay, len(permanentRelays)+len(knownRelays))
  260. n := copy(relays, permanentRelays)
  261. copy(relays[n:], knownRelays)
  262. mut.RUnlock()
  263. // Shuffle
  264. rand.Shuffle(relays)
  265. _ = json.NewEncoder(rw).Encode(map[string][]*relay{
  266. "relays": relays,
  267. })
  268. }
  269. func handlePostRequest(w http.ResponseWriter, r *http.Request) {
  270. // Get the IP address of the client
  271. rhost := r.RemoteAddr
  272. if host, _, err := net.SplitHostPort(rhost); err == nil {
  273. rhost = host
  274. }
  275. // Check the black list. A client is blacklisted if their last 10
  276. // attempts to join have all failed. The "Unauthorized" status return
  277. // causes strelaysrv to cease attempting to join.
  278. if globalBlocklist.IsBlocked(rhost) {
  279. log.Println("Rejected blocked client", rhost)
  280. http.Error(w, "Too many errors", http.StatusUnauthorized)
  281. globalBlocklist.ClearErrors(rhost)
  282. return
  283. }
  284. var relayCert *x509.Certificate
  285. if r.TLS != nil && len(r.TLS.PeerCertificates) > 0 {
  286. relayCert = r.TLS.PeerCertificates[0]
  287. log.Printf("Got TLS cert from relay server")
  288. }
  289. var newRelay relay
  290. err := json.NewDecoder(r.Body).Decode(&newRelay)
  291. r.Body.Close()
  292. if err != nil {
  293. if debug {
  294. log.Println("Failed to parse payload")
  295. }
  296. http.Error(w, err.Error(), http.StatusBadRequest)
  297. return
  298. }
  299. uri, err := url.Parse(newRelay.URL)
  300. if err != nil {
  301. if debug {
  302. log.Println("Failed to parse URI", newRelay.URL)
  303. }
  304. http.Error(w, err.Error(), http.StatusBadRequest)
  305. return
  306. }
  307. // Canonicalize the URL. In particular, parse and re-encode the query
  308. // string so that it's guaranteed to be valid.
  309. uri.RawQuery = uri.Query().Encode()
  310. newRelay.URL = uri.String()
  311. if relayCert != nil {
  312. advertisedId := uri.Query().Get("id")
  313. idFromCert := protocol.NewDeviceID(relayCert.Raw).String()
  314. if advertisedId != idFromCert {
  315. log.Println("Warning: Relay server requested to join with an ID different from the join request, rejecting")
  316. http.Error(w, "mismatched advertised id and join request cert", http.StatusBadRequest)
  317. return
  318. }
  319. }
  320. host, port, err := net.SplitHostPort(uri.Host)
  321. if err != nil {
  322. if debug {
  323. log.Println("Failed to split URI", newRelay.URL)
  324. }
  325. http.Error(w, err.Error(), http.StatusBadRequest)
  326. return
  327. }
  328. ip := net.ParseIP(host)
  329. // The client did not provide an IP address, use the IP address of the client.
  330. if ip == nil || ip.IsUnspecified() {
  331. uri.Host = net.JoinHostPort(rhost, port)
  332. newRelay.URL = uri.String()
  333. } else if host != rhost && relayCert == nil {
  334. if debug {
  335. log.Println("IP address advertised does not match client IP address", r.RemoteAddr, uri)
  336. }
  337. http.Error(w, fmt.Sprintf("IP advertised %s does not match client IP %s", host, rhost), http.StatusUnauthorized)
  338. return
  339. }
  340. newRelay.uri = uri
  341. for _, current := range permanentRelays {
  342. if current.uri.Host == newRelay.uri.Host {
  343. if debug {
  344. log.Println("Asked to add a relay", newRelay, "which exists in permanent list")
  345. }
  346. http.Error(w, "Invalid request", http.StatusBadRequest)
  347. return
  348. }
  349. }
  350. reschan := make(chan result)
  351. select {
  352. case requests <- request{&newRelay, reschan, prometheus.NewTimer(relayTestActionsSeconds.WithLabelValues("queue"))}:
  353. result := <-reschan
  354. if result.err != nil {
  355. log.Println("Join from", r.RemoteAddr, "failed:", result.err)
  356. globalBlocklist.AddError(rhost)
  357. relayTestsTotal.WithLabelValues("failed").Inc()
  358. http.Error(w, result.err.Error(), http.StatusBadRequest)
  359. return
  360. }
  361. log.Println("Join from", r.RemoteAddr, "succeeded")
  362. globalBlocklist.ClearErrors(rhost)
  363. relayTestsTotal.WithLabelValues("success").Inc()
  364. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  365. json.NewEncoder(w).Encode(map[string]time.Duration{
  366. "evictionIn": result.eviction,
  367. })
  368. default:
  369. relayTestsTotal.WithLabelValues("dropped").Inc()
  370. if debug {
  371. log.Println("Dropping request")
  372. }
  373. w.WriteHeader(httpStatusEnhanceYourCalm)
  374. }
  375. }
  376. func requestProcessor(geoip *geoip.Provider) {
  377. for request := range requests {
  378. if request.queueTimer != nil {
  379. request.queueTimer.ObserveDuration()
  380. }
  381. timer := prometheus.NewTimer(relayTestActionsSeconds.WithLabelValues("test"))
  382. handleRelayTest(request, geoip)
  383. timer.ObserveDuration()
  384. }
  385. }
  386. func handleRelayTest(request request, geoip *geoip.Provider) {
  387. if debug {
  388. log.Println("Request for", request.relay)
  389. }
  390. if err := client.TestRelay(context.TODO(), request.relay.uri, []tls.Certificate{testCert}, time.Second, 2*time.Second, 3); err != nil {
  391. if debug {
  392. log.Println("Test for relay", request.relay, "failed:", err)
  393. }
  394. request.result <- result{err, 0}
  395. return
  396. }
  397. stats := fetchStats(request.relay)
  398. location := getLocation(request.relay.uri.Host, geoip)
  399. mut.Lock()
  400. if stats != nil {
  401. updateMetrics(request.relay.uri.Host, *stats, location)
  402. }
  403. request.relay.Stats = stats
  404. request.relay.StatsRetrieved = time.Now().Truncate(time.Second)
  405. request.relay.Location = location
  406. timer, ok := evictionTimers[request.relay.uri.Host]
  407. if ok {
  408. if debug {
  409. log.Println("Stopping existing timer for", request.relay)
  410. }
  411. timer.Stop()
  412. }
  413. for i, current := range knownRelays {
  414. if current.uri.Host == request.relay.uri.Host {
  415. if debug {
  416. log.Println("Relay", request.relay, "already exists")
  417. }
  418. // Evict the old entry anyway, as configuration might have changed.
  419. last := len(knownRelays) - 1
  420. knownRelays[i] = knownRelays[last]
  421. knownRelays = knownRelays[:last]
  422. goto found
  423. }
  424. }
  425. if debug {
  426. log.Println("Adding new relay", request.relay)
  427. }
  428. found:
  429. knownRelays = append(knownRelays, request.relay)
  430. evictionTimers[request.relay.uri.Host] = time.AfterFunc(evictionTime, evict(request.relay))
  431. mut.Unlock()
  432. if err := saveRelays(knownRelaysFile, knownRelays); err != nil {
  433. log.Println("Failed to write known relays: " + err.Error())
  434. }
  435. request.result <- result{nil, evictionTime}
  436. }
  437. func evict(relay *relay) func() {
  438. return func() {
  439. mut.Lock()
  440. defer mut.Unlock()
  441. if debug {
  442. log.Println("Evicting", relay)
  443. }
  444. for i, current := range knownRelays {
  445. if current.uri.Host == relay.uri.Host {
  446. if debug {
  447. log.Println("Evicted", relay)
  448. }
  449. last := len(knownRelays) - 1
  450. knownRelays[i] = knownRelays[last]
  451. knownRelays = knownRelays[:last]
  452. deleteMetrics(current.uri.Host)
  453. }
  454. }
  455. delete(evictionTimers, relay.uri.Host)
  456. }
  457. }
  458. func loadRelays(file string, geoip *geoip.Provider) []*relay {
  459. content, err := os.ReadFile(file)
  460. if err != nil {
  461. log.Println("Failed to load relays: " + err.Error())
  462. return nil
  463. }
  464. var relays []*relay
  465. for _, line := range strings.Split(string(content), "\n") {
  466. if line == "" {
  467. continue
  468. }
  469. uri, err := url.Parse(line)
  470. if err != nil {
  471. if debug {
  472. log.Println("Skipping relay", line, "due to parse error", err)
  473. }
  474. continue
  475. }
  476. relays = append(relays, &relay{
  477. URL: line,
  478. Location: getLocation(uri.Host, geoip),
  479. uri: uri,
  480. })
  481. if debug {
  482. log.Println("Adding relay", line)
  483. }
  484. }
  485. return relays
  486. }
  487. func saveRelays(file string, relays []*relay) error {
  488. var content string
  489. for _, relay := range relays {
  490. content += relay.uri.String() + "\n"
  491. }
  492. return os.WriteFile(file, []byte(content), 0o777)
  493. }
  494. func createTestCertificate() tls.Certificate {
  495. tmpDir, err := os.MkdirTemp("", "relaypoolsrv")
  496. if err != nil {
  497. log.Fatal(err)
  498. }
  499. certFile, keyFile := filepath.Join(tmpDir, "cert.pem"), filepath.Join(tmpDir, "key.pem")
  500. cert, err := tlsutil.NewCertificate(certFile, keyFile, "relaypoolsrv", 20*365)
  501. if err != nil {
  502. log.Fatalln("Failed to create test X509 key pair:", err)
  503. }
  504. return cert
  505. }
  506. func getLocation(host string, geoip *geoip.Provider) location {
  507. timer := prometheus.NewTimer(locationLookupSeconds)
  508. defer timer.ObserveDuration()
  509. addr, err := net.ResolveTCPAddr("tcp", host)
  510. if err != nil {
  511. return location{}
  512. }
  513. city, err := geoip.City(addr.IP)
  514. if err != nil {
  515. return location{}
  516. }
  517. return location{
  518. Longitude: city.Location.Longitude,
  519. Latitude: city.Location.Latitude,
  520. City: city.City.Names["en"],
  521. Country: city.Country.IsoCode,
  522. Continent: city.Continent.Code,
  523. }
  524. }
  525. type loggingResponseWriter struct {
  526. http.ResponseWriter
  527. statusCode int
  528. }
  529. func NewLoggingResponseWriter(w http.ResponseWriter) *loggingResponseWriter {
  530. return &loggingResponseWriter{w, http.StatusOK}
  531. }
  532. func (lrw *loggingResponseWriter) WriteHeader(code int) {
  533. lrw.statusCode = code
  534. lrw.ResponseWriter.WriteHeader(code)
  535. }
  536. type errorTracker struct {
  537. errors *lru.TwoQueueCache[string, *errorCounter]
  538. }
  539. type errorCounter struct {
  540. count atomic.Int32
  541. }
  542. func newErrorTracker(size int) *errorTracker {
  543. cache, err := lru.New2Q[string, *errorCounter](size)
  544. if err != nil {
  545. panic(err)
  546. }
  547. return &errorTracker{
  548. errors: cache,
  549. }
  550. }
  551. func (b *errorTracker) AddError(host string) {
  552. entry, ok := b.errors.Get(host)
  553. if !ok {
  554. entry = &errorCounter{}
  555. b.errors.Add(host, entry)
  556. }
  557. c := entry.count.Add(1)
  558. log.Printf("Error count for %s is now %d", host, c)
  559. }
  560. func (b *errorTracker) ClearErrors(host string) {
  561. b.errors.Remove(host)
  562. }
  563. func (b *errorTracker) IsBlocked(host string) bool {
  564. if be, ok := b.errors.Get(host); ok {
  565. return be.count.Load() > 10
  566. }
  567. return false
  568. }