-
Notifications
You must be signed in to change notification settings - Fork 0
/
Raft2.go
458 lines (392 loc) · 9.38 KB
/
Raft2.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
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
package main
import (
"fmt"
"net"
"os"
"time"
"runtime"
"bufio"
"sync"
"strings"
)
var mutex = &sync.Mutex{}
var candidateTimer bool
var memberCount int
var state string
var voteCount int
var voteTo string
var heartBeat bool
var leader string
var heartBeatTrack bool
var leaderDead string
/*
Candidate Timer
*/
func CandidateTimer() {
time.Sleep(5 * time.Second)
if candidateTimer != true {
mutex.Lock()
candidateTimer=true
fmt.Println("CandidatTimer Expired")
if voteTo == "" {
// Promote slef for candidate Position
voteTo ="5000"
fmt.Println("PromotedSelf for candidate Position")
}
mutex.Unlock()
} else {
fmt.Println("Timer Already Expired")
}
}
/*
Process Received Message
*/
func ProcessMessage(message string) string{
if strings.Contains(message,"RequestVote 5000") {
if(voteTo == "") {
mutex.Lock()
voteTo="5000"
message = "Vote"
state = "follower"
fmt.Println("Casted voted for 5001")
defer mutex.Unlock()
} else {
message = "Novote"
fmt.Println("Request 5001 denied,as I have already voted for",voteTo)
}
} else if strings.Contains(message,"RequestVote 5002") {
if(voteTo == "") {
mutex.Lock()
voteTo="5002"
message = "Vote"
state = "follower"
fmt.Println("Casted voted for 5002")
defer mutex.Unlock()
} else {
message = "NoVote"
fmt.Println("Request 5002 denied,as I have already voted for",voteTo)
}
} else if strings.Contains(message,"RequestVote 5003") {
if(voteTo == "") {
mutex.Lock()
voteTo="5003"
message = "Vote"
state = "follower"
fmt.Println("Casted voted for 5003")
defer mutex.Unlock()
} else {
message = "NoVote"
fmt.Println("Request 5003 denied,as I have already voted for",voteTo)
}
} else if strings.Contains(message,"RequestVote 5004") {
if(voteTo == "") {
mutex.Lock()
voteTo="5003"
message = "Vote"
state = "follower"
fmt.Println("Casted voted for 5004")
defer mutex.Unlock()
} else {
message = "NoVote"
fmt.Println("Request 5004 denied,as I have already voted for",voteTo)
}
} else if strings.Contains(message,"Leader 5000") && leader == ""{
mutex.Lock()
leader="5000"
message="Ack Leader"
defer mutex.Unlock()
} else if strings.Contains(message,"Leader 5002") && leader == ""{
mutex.Lock()
leader="5002"
message="Ack Leader"
defer mutex.Unlock()
} else if strings.Contains(message,"Leader 5003") && leader == ""{
mutex.Lock()
leader="5003"
message="Ack Leader"
defer mutex.Unlock()
} else if strings.Contains(message,"Leader 5004") && leader == ""{
mutex.Lock()
leader="5004"
message="Ack Leader"
defer mutex.Unlock()
} else if strings.Contains(message,"HeartBeat") && leader == "5001" {
message="HeartBeatResponse"
}
return message
}
/*
Monitor HeartBeat
*/
func MonitorHeartBeat(conn net.Conn) {
timeoutDuration :=100 * time.Second
conn.SetReadDeadline(time.Now().Add(timeoutDuration))
var count int
for {
time.Sleep(time.Second * 2)
message, _ := bufio.NewReader(conn).ReadString('\n')
if strings.Contains(message,"HeartBeat") {
if heartBeatTrack !=true {
mutex.Lock()
heartBeatTrack = true
mutex.Unlock()
}
message ="HeartBeatResponse"
conn.Write([]byte(message + "\n"))
fmt.Println("Heart Beat Response Sent")
} else if message == "" {
if count == 3 {
mutex.Lock()
leaderDead = leader
state = ""
leader = ""
voteTo = ""
heartBeat=false
defer mutex.Unlock()
conn.Close()
break
}
fmt.Println("Heart Beat Not Received")
count++
} else {
break
}
}
return
}
/*
Receive and Serve Messages
for connected Client to this terminal
*/
func ReceiveAndServe(conn net.Conn) {
var message string
for {
message, _ = bufio.NewReader(conn).ReadString('\n')
message1 := message
message1 =ProcessMessage(message1)
conn.Write([]byte(message1 + "\n"))
if strings.Contains(message,"HeartBeat") && leader != "" {
fmt.Println("Leader Elected =",leader)
MonitorHeartBeat(conn)
}
}
}
/*
SendHearBeat Messages to followers
*/
func SendHeartBeat (conn net.Conn, ports string) {
for {
message :="HeartBeat"
conn.Write([]byte(message + "\n"))
message, _ = bufio.NewReader(conn).ReadString('\n')
if strings.Contains(message,"HeartBeatResponse") {
fmt.Println("Received Heart Beat Response From ",ports)
} else {
fmt.Println("Missed an Heart Beat Response From",ports)
}
}
}
/*
BroadCastLeaderMessage
*/
func SendLeaderMessage(conn net.Conn,ports string) {
message :="Leader 5001"
conn.Write([]byte(message + "\n"))
fmt.Println("Leader Update Message Sent to",ports)
message,_ =bufio.NewReader(conn).ReadString('\n')
if strings.Contains(message,"Ack Leader") {
fmt.Println("Successfully updated Leader information by",ports)
} else {
fmt.Println("Not Received Leader Ack from",ports)
}
}
/*
Request For Votes from Peers
*/
func RequestForVote(conn net.Conn,ports string) {
message :="RequestVote 5001"
_,err :=conn.Write([]byte(message + "\n"))
fmt.Println("Requested Vote from ",ports)
message,_ =bufio.NewReader(conn).ReadString('\n')
if err != nil {
fmt.Println("error from port =",ports)
}
mutex.Lock()
if strings.Contains(message,"Vote") {
voteCount++
fmt.Println("CurrentVoteCount =",voteCount)
fmt.Println("Vote Successfully Received from",ports)
}
mutex.Unlock()
time.Sleep(time.Second * 10)
if voteCount >= memberCount-1 && voteTo =="5001" {
mutex.Lock()
fmt.Println("ReceivedMajority Vote")
fmt.Println("Will communicate with Peers")
state="leader"
if(heartBeat == false) {
heartBeat = true
}
mutex.Unlock()
SendLeaderMessage(conn,ports)
} else if voteCount >= memberCount-1 && leaderDead != "" && voteTo == "5001"{
mutex.Lock()
fmt.Println("ReceivedMajority Vote")
fmt.Println("Will communicate with Peers")
state="leader"
if(heartBeat == false) {
heartBeat = true
}
mutex.Unlock()
SendLeaderMessage(conn,ports)
} else {
state = "follower"
fmt.Println("Didn't Receive Majority Vote , voteCount = ",voteCount)
}
}
/*
Listen on Connected and ports and repond back
*/
func ListenAndServe (conn net.Conn, port string) {
/*
Increment Member Count And wait till Network is setup
*/
mutex.Lock()
memberCount++
mutex.Unlock()
for {
if memberCount != 4 {
} else {
break
}
}
fmt.Println("All Members registered to network,Candidate Timer Begins")
go CandidateTimer()
ReceiveAndServe(conn)
}
/*
Check and Communicate with Peers when Needed
*/
func CommunicateWithPeers(conn net.Conn,ports string) {
for {
if candidateTimer == true {
if voteTo == "" || voteTo == "5001" {
RequestForVote(conn,ports)
break
} else if leaderDead != "" && voteTo == ""{
RequestForVote(conn,ports)
break
} else {
time.Sleep(5 * time.Second)
fmt.Println("Cant Request For Vote as I'm",state)
break
}
}
}
if heartBeat == true {
for {
SendHeartBeat(conn, ports)
}
} else {
fmt.Println("Monitoring HeartBeatFrom ",voteTo)
}
for {
if leaderDead != "" {
if leaderDead == ports {
mutex.Lock()
memberCount--
mutex.Unlock()
fmt.Println("link to old leader closed")
conn.Close()
break
} else {
if voteTo == "" || voteTo == "5001" {
time.Sleep(1*time.Second)
RequestForVote(conn,ports)
}
break
}
}
}
if heartBeat == true {
for {
SendHeartBeat(conn, ports)
}
} else {
fmt.Println("Monitoring HeartBeatFrom ",voteTo)
}
}
/*
SetupListen Port
*/
func SetupListenPort(port string) {
service := ":"+port
tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
if err!= nil {
fmt.Println("Resovle failed ",err.Error())
os.Exit(1)
}
listener, err := net.ListenTCP("tcp", tcpAddr)
if err != nil {
// Handle error
fmt.Println(err.Error())
}
for {
conn, err := listener.Accept()
if err != nil {
// Handle error
fmt.Println(err.Error())
}
go ListenAndServe(conn,port)
}
}
/*
Dail Ports
*/
func DailPorts(address string, ports string, port string,) {
var dial net.Conn
for {
servAddr := address+":"+ports
tcpAddr, err := net.ResolveTCPAddr("tcp", servAddr)
if err != nil {
fmt.Println("ResolveTCPAddr failed:", err.Error())
os.Exit(1)
}
time.Sleep(1000 * time.Millisecond)
dial, err = net.DialTCP("tcp", nil, tcpAddr)
if err != nil {
//fmt.Println("Dial failed:", err.Error())
//os.Exit(1)
} else {
break
}
}
CommunicateWithPeers(dial,ports)
fmt.Println("Connection successful to ",address,ports, " by ",port)
//fmt.Println("getting out of peer")
}
/*
Setup the server
*/
func CreateServer(ports [5]string, address string,) {
go SetupListenPort(ports[0])
for i :=1;i<5;i++ {
go DailPorts(address,ports[i],ports[0])
}
}
func main () {
var address string
var ports [5]string
runtime.GOMAXPROCS(100000000000)
candidateTimer=false
heartBeatTrack=false
ports[0]="5001"
ports[1]="5000"
ports[2]="5002"
ports[3]="5003"
ports[4]="5004"
CreateServer(ports,address)
var input string
fmt.Scanln(&input)
//Election(address)
}