-
Notifications
You must be signed in to change notification settings - Fork 132
/
main.go
101 lines (87 loc) · 2.41 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
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"log"
"net/http"
"os"
"os/signal"
httpd "github.com/otoolep/hraftd/http"
"github.com/otoolep/hraftd/store"
)
// Command line defaults
const (
DefaultHTTPAddr = "localhost:11000"
DefaultRaftAddr = "localhost:12000"
)
// Command line parameters
var inmem bool
var httpAddr string
var raftAddr string
var joinAddr string
var nodeID string
func init() {
flag.BoolVar(&inmem, "inmem", false, "Use in-memory storage for Raft")
flag.StringVar(&httpAddr, "haddr", DefaultHTTPAddr, "Set the HTTP bind address")
flag.StringVar(&raftAddr, "raddr", DefaultRaftAddr, "Set Raft bind address")
flag.StringVar(&joinAddr, "join", "", "Set join address, if any")
flag.StringVar(&nodeID, "id", "", "Node ID. If not set, same as Raft bind address")
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: %s [options] <raft-data-path> \n", os.Args[0])
flag.PrintDefaults()
}
}
func main() {
flag.Parse()
if flag.NArg() == 0 {
fmt.Fprintf(os.Stderr, "No Raft storage directory specified\n")
os.Exit(1)
}
if nodeID == "" {
nodeID = raftAddr
}
// Ensure Raft storage exists.
raftDir := flag.Arg(0)
if raftDir == "" {
log.Fatalln("No Raft storage directory specified")
}
if err := os.MkdirAll(raftDir, 0700); err != nil {
log.Fatalf("failed to create path for Raft storage: %s", err.Error())
}
s := store.New(inmem)
s.RaftDir = raftDir
s.RaftBind = raftAddr
if err := s.Open(joinAddr == "", nodeID); err != nil {
log.Fatalf("failed to open store: %s", err.Error())
}
h := httpd.New(httpAddr, s)
if err := h.Start(); err != nil {
log.Fatalf("failed to start HTTP service: %s", err.Error())
}
// If join was specified, make the join request.
if joinAddr != "" {
if err := join(joinAddr, raftAddr, nodeID); err != nil {
log.Fatalf("failed to join node at %s: %s", joinAddr, err.Error())
}
}
// We're up and running!
log.Printf("hraftd started successfully, listening on http://%s", httpAddr)
terminate := make(chan os.Signal, 1)
signal.Notify(terminate, os.Interrupt)
<-terminate
log.Println("hraftd exiting")
}
func join(joinAddr, raftAddr, nodeID string) error {
b, err := json.Marshal(map[string]string{"addr": raftAddr, "id": nodeID})
if err != nil {
return err
}
resp, err := http.Post(fmt.Sprintf("http://%s/join", joinAddr), "application-type/json", bytes.NewReader(b))
if err != nil {
return err
}
defer resp.Body.Close()
return nil
}