-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrpc.go
More file actions
395 lines (313 loc) · 8.12 KB
/
Copy pathrpc.go
File metadata and controls
395 lines (313 loc) · 8.12 KB
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
package kv
import (
"context"
"errors"
"sync"
"time"
pb "github.com/SuhasHebbar/CS739-P2/proto"
"golang.org/x/exp/slog"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
empty "github.com/golang/protobuf/ptypes/empty"
wrappers "github.com/golang/protobuf/ptypes/wrappers"
"github.com/google/uuid"
)
const REQUEST_TERMINATED = "Request was terminated."
const NOT_LEADER = "Server is not a leader."
const SIMULATED_PARTITION = "Simulated Partition"
const UNAVAILABLE_READ_LEASE = "Leader read lease is unavailable"
type RaftRpcServer struct {
raft *Raft
clients map[PeerId]pb.RaftRpcClient
kv *KVStore
pendingOps map[string]chan *KVResult
mu sync.Mutex
pb.UnimplementedRaftRpcServer
config *Config
}
type RpcServer interface {
GetClient(peerId PeerId) pb.RaftRpcClient
}
type PendingOperation struct {
isLeader bool
currentLeader PeerId
logIndex int32
allowFastPath bool
}
func NewRaftRpcServer(id PeerId, config *Config) *RaftRpcServer {
peers := map[PeerId]Empty{}
clients := map[PeerId]pb.RaftRpcClient{}
for peerId := range config.Peers {
peers[peerId] = Empty{}
if peerId == id {
// we do not need to contact ourselves via RPC
clients[peerId] = nil
continue
}
opts := []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}
conn, err := grpc.Dial(config.Peers[peerId], opts...)
if err != nil {
slog.Error("Failed to dial", "err", err)
panic(err)
}
clients[peerId] = pb.NewRaftRpcClient(conn)
}
self := &RaftRpcServer{}
self.raft = NewRaft(id, peers, self)
self.clients = clients
self.kv = NewKVStore()
self.pendingOps = map[string]chan *KVResult{}
self.config = config
go func() {
self.raft.startServerLoop()
}()
go self.startCommitListerLoop()
return self
}
type KVResult struct {
Value string
Err error
}
func (rs *RaftRpcServer) startCommitListerLoop() {
for {
op := <-rs.raft.commitCh
kvop := op.Operation
rs.raft.Info("Applying operation. index: %v, operation: %v", op.Index, op.Operation)
rs.mu.Lock()
result := &KVResult{}
if kvop.Type == pb.OperationType_GET {
value, err := rs.kv.Get(kvop.Key)
result.Value = value
result.Err = err
} else if kvop.Type == pb.OperationType_SET {
rs.kv.Set(kvop.Key, kvop.Value)
} else if kvop.Type == pb.OperationType_DELETE {
err := rs.kv.Delete(kvop.Key)
result.Err = err
} else {
panic("Invalid operation passed to commit listener loop")
}
pendingOpCh := rs.pendingOps[op.Operation.Id]
rs.mu.Unlock()
// Infof("Returning response for %v", op.Operation)
if pendingOpCh != nil {
pendingOpCh <- result
}
if rs.raft.role == LEADER && rs.raft.p.InitialLogSize >= int(op.Index) {
Infof("Initial Log Size: %v, index: %v, Startup time %v",
rs.raft.p.InitialLogSize, op.Index, time.Since(rs.raft.p.StartTime))
}
}
}
func (rs *RaftRpcServer) GetClient(peerId PeerId) pb.RaftRpcClient {
if rs.config.Partitioned {
//Debugf("Still partitioned")
return nil
}
return rs.clients[peerId]
}
func (rs *RaftRpcServer) RequestVote(ctx context.Context, in *pb.RequestVoteRequest) (*pb.RequestVoteReply, error) {
if rs.config.Partitioned {
<-ctx.Done()
return nil, errors.New(SIMULATED_PARTITION)
}
cmd := RpcCommand{
Command: in,
resp: make(chan any, 1),
}
rs.raft.rpcCh <- cmd
resp, ok := (<-cmd.resp).(*pb.RequestVoteReply)
if !ok {
Debugf("Could not convert to RequestVoteReply")
panic(ok)
}
return resp, nil
}
func (rs *RaftRpcServer) AppendEntries(ctx context.Context, in *pb.AppendEntriesRequest) (*pb.AppendEntriesResponse, error) {
if rs.config.Partitioned {
<-ctx.Done()
return nil, errors.New(SIMULATED_PARTITION)
}
cmd := RpcCommand{
Command: in,
resp: make(chan any, 1),
}
rs.raft.rpcCh <- cmd
resp, ok := (<-cmd.resp).(*pb.AppendEntriesResponse)
if !ok {
Debugf("Could not convert to AppendEntriesResponse")
panic(ok)
}
return resp, nil
}
func (rs *RaftRpcServer) scheduleRpcCommand(ctx context.Context, cmd RpcCommand) (PendingOperation, error) {
rs.raft.rpcCh <- cmd
select {
case <-ctx.Done():
var pendingOperation PendingOperation
return pendingOperation, errors.New(REQUEST_TERMINATED)
case resp := <-cmd.resp:
pendingOp, ok := resp.(PendingOperation)
if !ok {
panic(ok)
}
if !pendingOp.isLeader {
return pendingOp, errors.New(NOT_LEADER)
}
return pendingOp, nil
}
}
func (rs *RaftRpcServer) FastGet(ctx context.Context, key *pb.Key) (*pb.Response, error) {
resp := &pb.Response{}
op := &pb.Operation{
Type: pb.OperationType_FAST_GET,
Key: key.Key,
Id: uuid.New().String(),
}
cmd := RpcCommand{
Command: op,
resp: make(chan any, 1),
}
pendingOp, err := rs.scheduleRpcCommand(ctx, cmd)
resp.IsLeader = pendingOp.isLeader
resp.NewLeader = pendingOp.currentLeader
if err != nil {
resp.Ok = false
resp.Response = err.Error()
return resp, nil
}
if !pendingOp.allowFastPath {
resp.Ok = false
resp.Response = UNAVAILABLE_READ_LEASE
}
rs.mu.Lock()
result, err := rs.kv.Get(key.Key)
if err != nil {
resp.Ok = false
resp.Response = err.Error()
} else {
resp.Ok = true
resp.Response = result
}
rs.mu.Unlock()
return resp, nil
}
func (rs *RaftRpcServer) Get(ctx context.Context, key *pb.Key) (*pb.Response, error) {
resp := &pb.Response{}
op := &pb.Operation{
Type: pb.OperationType_GET,
Key: key.Key,
Id: uuid.New().String(),
}
cmd := RpcCommand{
Command: op,
resp: make(chan any, 1),
}
rs.InitPendingOp(op.Id)
defer rs.ClearPendingOp(op.Id)
pendingOp, err := rs.scheduleRpcCommand(ctx, cmd)
resp.IsLeader = pendingOp.isLeader
resp.NewLeader = pendingOp.currentLeader
if err != nil {
resp.Ok = false
resp.Response = err.Error()
return resp, nil
}
res := rs.waitForResult(op.Id, ctx)
if res.Err != nil {
resp.Ok = false
resp.Response = res.Err.Error()
return resp, nil
} else {
resp.Ok = true
resp.Response = res.Value
return resp, nil
}
}
func (rs *RaftRpcServer) Set(ctx context.Context, kvp *pb.KeyValuePair) (*pb.Response, error) {
resp := &pb.Response{}
op := &pb.Operation{
Type: pb.OperationType_SET,
Key: kvp.Key,
Value: kvp.Value,
Id: uuid.New().String(),
}
cmd := RpcCommand{
Command: op,
resp: make(chan any, 1),
}
rs.InitPendingOp(op.Id)
defer rs.ClearPendingOp(op.Id)
pendingOp, err := rs.scheduleRpcCommand(ctx, cmd)
resp.IsLeader = pendingOp.isLeader
resp.NewLeader = pendingOp.currentLeader
if err != nil {
resp.Ok = false
resp.Response = err.Error()
return resp, nil
}
rs.waitForResult(op.Id, ctx)
resp.Ok = true
return resp, nil
}
func (rs *RaftRpcServer) InitPendingOp(opId string) {
rs.mu.Lock()
rs.pendingOps[opId] = make(chan *KVResult, 1)
rs.mu.Unlock()
}
func (rs *RaftRpcServer) ClearPendingOp(opId string) {
rs.mu.Lock()
delete(rs.pendingOps, opId)
rs.mu.Unlock()
}
func (rs *RaftRpcServer) Delete(ctx context.Context, key *pb.Key) (*pb.Response, error) {
resp := &pb.Response{}
op := &pb.Operation{
Type: pb.OperationType_DELETE,
Key: key.Key,
Id: uuid.New().String(),
}
cmd := RpcCommand{
Command: op,
resp: make(chan any, 1),
}
rs.InitPendingOp(op.Id)
defer rs.ClearPendingOp(op.Id)
pendingOp, err := rs.scheduleRpcCommand(ctx, cmd)
resp.IsLeader = pendingOp.isLeader
resp.NewLeader = pendingOp.currentLeader
if err != nil {
resp.Ok = false
resp.Response = err.Error()
return resp, nil
}
res := rs.waitForResult(op.Id, ctx)
if res.Err != nil {
resp.Ok = false
resp.Response = res.Err.Error()
} else {
resp.Ok = true
resp.Response = res.Value
}
return resp, nil
}
func (rs *RaftRpcServer) waitForResult(opId string, ctx context.Context) *KVResult {
start := time.Now()
rs.mu.Lock()
pendingOpsCh := rs.pendingOps[opId]
rs.mu.Unlock()
select {
case <-ctx.Done():
return &KVResult{Err: errors.New("Deadline exceeded")}
case result := <-pendingOpsCh:
rs.raft.Debug("operation took %v", time.Since(start))
return result
}
}
func (rs *RaftRpcServer) Partition(ctx context.Context, in *wrappers.BoolValue) (*empty.Empty, error) {
rs.config.Partitioned = in.Value
if rs.config.Partitioned {
rs.raft.Debug("Started simulating partition")
}
return &empty.Empty{}, nil
}