forked from jpoon/bootnode-registrar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
96 lines (80 loc) · 2.12 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package main
import (
"bytes"
"flag"
"fmt"
"io/ioutil"
"net/http"
"os"
"strings"
"sync"
"time"
log "github.com/Sirupsen/logrus"
)
const (
pollingDuration time.Duration = 20 * time.Second
listeningPort = ":9898"
)
var (
mu sync.RWMutex
ethereumNodes string
)
func updateEthereumNodes(addressRecord string) {
buffer := bytes.NewBufferString("")
// Resolve DNS A record to a set of IP addresses
ipAddresses, err := ResolveAddressRecord(addressRecord)
if err != nil {
log.Errorf("Error resolving DNS address record: %s", err)
goto updateNodes
}
log.Printf("%s resolved to %s", addressRecord, ipAddresses)
// Retrieve enode from each IP address
for _, ipAddress := range ipAddresses {
resp, err := http.Get(fmt.Sprintf("http://%s:%s", ipAddress, "8080"))
if err != nil {
log.Errorf("Error retrieving enode address: %s", err)
goto updateNodes
}
defer resp.Body.Close()
contents, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Errorf("Error parsing response: %s", err)
goto updateNodes
}
var enodeAddress = strings.TrimSpace(string(contents))
if buffer.Len() > 0 {
buffer.WriteString(",")
}
buffer.WriteString(enodeAddress)
log.Infof("%s with enode address %s", ipAddress, enodeAddress)
}
updateNodes:
// Update list
mu.Lock()
defer mu.Unlock()
ethereumNodes = buffer.String()
}
func startPollUpdateEthereumNodes(addressRecord string) {
for {
go updateEthereumNodes(addressRecord)
<-time.After(pollingDuration)
}
}
func webHandler(w http.ResponseWriter, r *http.Request) {
log.Debugf("handling request from %s", r.RemoteAddr)
mu.RLock()
defer mu.RUnlock()
fmt.Fprintln(w, ethereumNodes)
}
func main() {
bootNodeService := flag.String("service", os.Getenv("BOOTNODE_SERVICE"), "DNS A Record for `bootnode` services. Alternatively set `BOOTNODE_SERVICE` env.")
flag.Parse()
if *bootNodeService == "" {
flag.PrintDefaults()
os.Exit(1)
}
log.Infof("starting bootnode-registrar: %s.", *bootNodeService)
go startPollUpdateEthereumNodes(*bootNodeService)
http.HandleFunc("/", webHandler)
log.Fatal(http.ListenAndServe(listeningPort, nil))
}