syncthing/cmd/strelaysrv/pool.go

66 lines
1.7 KiB
Go
Raw Normal View History

2016-06-02 14:16:02 +02:00
// Copyright (C) 2015 Audrius Butkevicius and Contributors.
2015-09-07 10:21:23 +02:00
package main
import (
"bytes"
"encoding/json"
"io/ioutil"
"log"
"net/url"
"time"
)
func poolHandler(pool string, uri *url.URL, mapping mapping) {
2015-09-21 23:33:29 +02:00
if debug {
log.Println("Joining", pool)
}
2015-09-07 10:21:23 +02:00
for {
uriCopy := *uri
uriCopy.Host = mapping.Address().String()
2015-09-07 10:21:23 +02:00
var b bytes.Buffer
json.NewEncoder(&b).Encode(struct {
URL string `json:"url"`
}{
uriCopy.String(),
2015-09-07 10:21:23 +02:00
})
resp, err := httpClient.Post(pool, "application/json", &b)
2015-09-07 10:21:23 +02:00
if err != nil {
log.Println("Error joining pool", pool, err)
2015-09-07 10:21:23 +02:00
} else if resp.StatusCode == 500 {
bs, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println("Failed to join", pool, "due to an internal server error. Could not read response:", err)
} else {
log.Println("Failed to join", pool, "due to an internal server error:", string(bs))
2015-09-07 10:21:23 +02:00
}
resp.Body.Close()
2015-09-07 10:21:23 +02:00
} else if resp.StatusCode == 429 {
log.Println(pool, "under load, will retry in a minute")
2015-09-07 10:21:23 +02:00
time.Sleep(time.Minute)
continue
} else if resp.StatusCode == 401 {
log.Println(pool, "failed to join due to IP address not matching external address. Aborting")
2015-09-07 19:12:18 +02:00
return
2015-09-07 10:21:23 +02:00
} else if resp.StatusCode == 200 {
var x struct {
EvictionIn time.Duration `json:"evictionIn"`
}
err := json.NewDecoder(resp.Body).Decode(&x)
if err == nil {
rejoin := x.EvictionIn - (x.EvictionIn / 5)
2015-09-21 23:33:29 +02:00
log.Println("Joined", pool, "rejoining in", rejoin)
2015-09-07 10:21:23 +02:00
time.Sleep(rejoin)
continue
} else {
2015-09-21 23:33:29 +02:00
log.Println("Failed to deserialize response", err)
2015-09-07 10:21:23 +02:00
}
} else {
log.Println(pool, "unknown response type from server", resp.StatusCode)
2015-09-07 10:21:23 +02:00
}
time.Sleep(time.Hour)
}
}