-
Notifications
You must be signed in to change notification settings - Fork 10
/
main.go
106 lines (90 loc) · 2.42 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
97
98
99
100
101
102
103
104
105
106
package main
import (
"io/ioutil"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/alecthomas/kingpin"
"github.com/gorilla/mux"
"github.com/hashicorp/logutils"
"github.com/pelletier/go-toml"
"github.com/INFURA/keyrouter/consistent"
"github.com/INFURA/keyrouter/server"
)
type Config struct {
Services []struct {
Name string
Nodes consistent.Members
}
}
var (
version = "dev"
commit = "none"
date = "unknown"
app = kingpin.New("keyrouter", "A simple microservice for consistent hashing of service entries")
conf = app.Flag("services", "location of services.toml").Default("services.toml").String()
bind = app.Flag("address", "address to bind to").Default(":8080").TCP()
logLevel = app.Flag("log-level", "minimum log level").Default("INFO").String()
)
func main() {
app.Version(version + "-" + commit).Author("INFURA")
_ = kingpin.MustParse(app.Parse(os.Args[1:]))
address := (*bind).String()
router := mux.NewRouter()
srv := server.New()
filter := &logutils.LevelFilter{
Levels: []logutils.LogLevel{"SPAM", "DEBUG", "INFO", "WARN", "ERROR"},
MinLevel: logutils.LogLevel(*logLevel),
Writer: os.Stdout,
}
log.SetOutput(filter)
loader := func() {
b, err := ioutil.ReadFile(*conf)
if err != nil {
app.FatalUsage("cannot read config file: %v", err)
}
cfg := Config{}
err = toml.Unmarshal(b, &cfg)
if err != nil {
log.Fatalf("[FATAL] error reading config: %v", err)
}
for _, s := range cfg.Services {
log.Printf("[DEBUG] Populating Service %s", s.Name)
added, removed, err := srv.PopulateService(s.Name, s.Nodes)
if err != nil {
log.Fatalf("[FATAL] error updating service %s: %v", s.Name, err)
}
if len(added) > 0 {
log.Printf("[DEBUG] Added: %v", added)
}
if len(removed) > 0 {
log.Printf("[DEBUG] Removed: %v", removed)
}
}
}
loader()
hups := make(chan os.Signal, 1)
signal.Notify(hups, syscall.SIGHUP)
go func() {
for range hups {
log.Printf("[INFO] Reloading config")
loader()
}
}()
router.Path("/service").Handler(srv.AllServicesHandler())
router.PathPrefix("/service/").Handler(http.StripPrefix("/service/", srv.ServiceQueryHandler()))
log.Printf("[INFO] Ready to serve at %v", address)
s := http.Server{
Addr: address,
ReadTimeout: 125 * time.Second,
WriteTimeout: 125 * time.Second,
Handler: router,
}
err := s.ListenAndServe()
if err != nil {
log.Fatalf("[FATAL] %v", err)
}
}