-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
233 lines (205 loc) · 5.71 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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
package main
import (
"bytes"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"github.com/austingebauer/raft-kv-db/command"
"github.com/austingebauer/raft-kv-db/raft"
"github.com/austingebauer/raft-kv-db/storage"
)
var id uint64
var apiAddr string
var raftAddr string
var storageFile string
var peerList string
func init() {
flag.Uint64Var(&id, "id", 1, "ID to assign to this peer")
flag.StringVar(&apiAddr, "api-addr", "127.0.0.1:8501", "Listen address for key/value API requests")
flag.StringVar(&raftAddr, "raft-addr", "127.0.0.1:8601", "Listen address for Raft peer connections")
flag.StringVar(&storageFile, "storage-file", "", "File to store the Raft log in. Will be created if it doesn't exist")
flag.StringVar(&peerList, "peer-list", "1=http://127.0.0.1:8601,2=http://127.0.0.1:8602", "List of raft peers in the form <peer_1_id>=<peer_1_url>,<peer_2_id>=<peer_2_url>")
}
func main() {
// Parse and print command line arguments
flag.Parse()
log.Printf("id: %d", id)
log.Printf("api-addr: %s", apiAddr)
log.Printf("raft-addr: %s", raftAddr)
log.Printf("storage-file: %s", storageFile)
log.Printf("peer-list: %s", peerList)
// Parse the raft address into a URL
raftURL, err := url.Parse("http://" + raftAddr)
if err != nil {
log.Fatal(err)
}
// Parse the peer list
parsedPeerMap, err := parsePeerList(peerList)
if err != nil {
log.Fatal(err)
}
parsedPeerMap[id] = raftURL
// Check if raft log storage file exists and create it if not
var store io.ReadWriter = &bytes.Buffer{}
if storageFile != "" {
e, err := exists(storageFile)
if err != nil {
log.Fatal(err)
}
if !e {
store, err = os.Create(storageFile)
} else {
store, err = os.Open(storageFile)
}
}
// Create an in-memory DB for the key/value FSM
fsm := storage.NewMemDB()
cb := func(_ uint64, cmd []byte) []byte {
cmdParsed, err := command.Deserialize(cmd)
if err != nil {
log.Fatal(err)
}
switch cmdParsed.Action {
case command.Put:
fsm.Put(cmdParsed.Key, string(cmdParsed.Value))
case command.Delete:
fsm.Delete(cmdParsed.Key)
default:
log.Fatal("unknown command action")
}
return nil
}
// Start the raft server
server := raft.NewServer(id, store, cb)
raft.SetupServeMux(http.DefaultServeMux, server)
// Set the list of raft peers
peers := make([]raft.Peer, 0, len(parsedPeerMap))
for id, peerURL := range parsedPeerMap {
peers = append(peers, &raft.HTTPPeer{
RemoteID: id,
URL: peerURL,
})
}
if err := server.SetConfiguration(peers...); err != nil {
log.Fatal(err)
}
// Start the raft server
go http.ListenAndServe(raftAddr, nil)
server.Start()
// Create the key/value DB API handler
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.URL.Path, "/kvdb/") {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("Bad Request\n"))
return
}
switch r.Method {
case http.MethodGet:
kvPath := strings.Split(r.URL.Path, "/kvdb/")[1]
w.Header().Set("Content-Type", "application/json")
v, ok := fsm.Get(kvPath)
if !ok {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("Not Found\n"))
return
}
w.Write([]byte(fmt.Sprintf("%s\n", v)))
case http.MethodDelete:
kvPath := strings.Split(r.URL.Path, "/kvdb/")[1]
serialized, err := command.Serialize(&command.Command{
Action: command.Delete,
Key: kvPath,
})
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Internal Server Error\n"))
return
}
if err := server.Command(serialized, nil); err != nil {
log.Printf("error submitting command: %v", err.Error())
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Internal Server Error\n"))
return
}
w.WriteHeader(http.StatusNoContent)
w.Write([]byte("\n"))
case http.MethodPut:
kvPath := strings.Split(r.URL.Path, "/kvdb/")[1]
body, err := ioutil.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Internal Server Error\n"))
return
}
serialized, err := command.Serialize(&command.Command{
Action: command.Put,
Key: kvPath,
Value: body,
})
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Internal Server Error\n"))
return
}
if err := server.Command(serialized, nil); err != nil {
log.Printf("error submitting command: %v", err.Error())
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Internal Server Error\n"))
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("\n"))
default:
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("Unsupported request method\n"))
}
})
// Serve up the key/value DB API
log.Fatal(http.ListenAndServe(apiAddr, nil))
}
// Parses a peer list, which has the form:
// <peer_1_id>=<peer_1_url>,<peer_2_id>=<peer_2_url>
//
// For example:
// 1=10.0.1.11:2380,2=10.0.1.12:2380
//
// Returns a map from peer ID to peer URL.
func parsePeerList(l string) (map[uint64]*url.URL, error) {
peerMap := make(map[uint64]*url.URL)
p1 := strings.Split(l, ",")
for _, p := range p1 {
p2 := strings.Split(p, "=")
if len(p2) != 2 {
return nil, errors.New("invalid peer list format")
}
id, err := strconv.Atoi(p2[0])
if err != nil {
return nil, errors.New("invalid peer list format")
}
u, err := url.Parse(p2[1])
if err != nil {
return nil, errors.New("failed to parse peer list URL")
}
peerMap[uint64(id)] = u
}
return peerMap, nil
}
// Returns true if the given file at path exists.
func exists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if errors.Is(err, os.ErrNotExist) {
return false, nil
}
return false, err
}