-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
105 lines (90 loc) · 2.26 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
package main
import (
"flag"
"fmt"
"log"
"net"
"net/http"
"os"
"path/filepath"
"time"
"github.com/dgraph-io/badger/v4"
"github.com/hashicorp/raft"
raftboltdb "github.com/hashicorp/raft-boltdb"
"github.com/qichengzx/m2/fsm"
"github.com/qichengzx/m2/server"
)
const (
tcpTimeout = 1 * time.Second
snapInterval = 30 * time.Second
snapThreshold = 1000
)
var (
nodeID = flag.String("node_id", "node_1", "raft node id")
port = flag.Int("port", 8001, "http port")
raftaddr = flag.String("raft_addr", "18001", "raft addr")
dir = flag.String("store_dir", "data", "db dir")
)
func main() {
flag.Parse()
raftConf := raft.DefaultConfig()
raftConf.LocalID = raft.ServerID(*nodeID)
raftConf.SnapshotInterval = snapInterval
raftConf.SnapshotThreshold = snapThreshold
badgerOpt := badger.DefaultOptions(*dir)
badgerDB, err := badger.Open(badgerOpt)
if err != nil {
log.Fatal(err)
return
}
fsmStore := fsm.NewBadger(badgerDB)
store, err := raftboltdb.NewBoltStore(filepath.Join(*dir, "raft"))
if err != nil {
log.Fatal(err)
return
}
cacheStore, err := raft.NewLogCache(256, store)
if err != nil {
log.Fatal(err)
return
}
snapshotStore, err := raft.NewFileSnapshotStore(*dir, 1, os.Stdout)
if err != nil {
log.Fatal(err)
return
}
tcpAddr, err := net.ResolveTCPAddr("tcp", *raftaddr)
if err != nil {
log.Fatal(err)
return
}
transport, err := raft.NewTCPTransport(*raftaddr, tcpAddr, 3, tcpTimeout, os.Stdout)
if err != nil {
log.Fatal(err)
return
}
raftServer, err := raft.NewRaft(raftConf, fsmStore, cacheStore, store, snapshotStore, transport)
if err != nil {
log.Fatal(err)
return
}
raftServer.BootstrapCluster(raft.Configuration{
Servers: []raft.Server{
{
ID: raft.ServerID(*nodeID),
Address: transport.LocalAddr(),
},
},
})
server := server.New(raftServer, badgerDB)
http.HandleFunc("/raft/join", server.RaftJoin)
http.HandleFunc("/raft/status", server.RaftStatus)
http.HandleFunc("/raft/leave", server.RaftLeave)
http.HandleFunc("/set", server.SetHandler)
http.HandleFunc("/get", server.GetHandler)
http.HandleFunc("/del", server.DelHandler)
fmt.Println("HTTP Server Listening on:", *port)
if err := http.ListenAndServe(fmt.Sprintf(":%d", *port), nil); err != nil {
log.Fatalln(err)
}
}