/
multegula.go
576 lines (516 loc) · 15.1 KB
/
multegula.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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
////////////////////////////////////////////////////////////
//Multegula - multegula.go
//Main Go Package for Multegula
//Armin Mahmoudi, Daniel Santoro, Garrett Miller, Lunwen He
////////////////////////////////////////////////////////////
package main
import (
"flag"
"fmt"
"reflect"
"sort"
"strconv"
"strings"
"sync"
"github.com/arminm/multegula/bootstrapClient"
"github.com/arminm/multegula/bridges"
"github.com/arminm/multegula/bullySelection"
"github.com/arminm/multegula/consensus"
"github.com/arminm/multegula/defs"
"github.com/arminm/multegula/messagePasser"
)
/*
* Channel to exit gracefully
*/
var exitChannel chan bool = make(chan bool)
/*
* channels to get game info at the start
*/
var localNameChannel chan string = make(chan string)
var gameTypeChannel chan string = make(chan string)
/*
* This is the sendChannel for message dispatcher.
* Any components like UI or bully algorithm will
* put messages into this channel if they want to
* send message out. Message dispatcher will get
* messages out from this channel and send them
* to messagePasser
*/
var sendChannel chan messagePasser.Message = make(chan messagePasser.Message, defs.QUEUE_SIZE)
/*
* keeping track of the proposal checks
*/
var propChecksMap map[string]*consensus.PropCheck = make(map[string]*consensus.PropCheck)
var propCheckMutex = &sync.Mutex{}
/*
* put message into sendChannel
* @param message - message to be put into sendChannel
*/
func putMessageIntoSendChannel(message messagePasser.Message) {
sendChannel <- message
}
/*
* get the operation, send or receive
* @return if send, return 1; otherwise return 0
**/
func getOperation() int {
var operation string
for {
fmt.Println("Send(s) / Receive(r) / Multicast (m): ")
fmt.Scanf("%s", &operation)
switch operation {
case "s":
return 0
case "r":
return 1
case "m":
return 2
default:
fmt.Printf("'%v' is Invalid. Please select a valid operation.", operation)
}
}
}
/*
* get destination name
* @param nodes
* the available nodes to contact
*
* @return destination name string
**/
func getDest(nodes []messagePasser.Node) string {
fmt.Println("To: (ex. lunwen OR 1)")
var destName string
fmt.Scanf("%v", &destName)
// Check if input is an ID
id, err := strconv.Atoi(destName)
if err == nil && id >= 0 && id < len(nodes) {
return nodes[id].Name
}
// else input must be a name
var destNode messagePasser.Node
for len(destName) > 0 {
_, destNode, err = messagePasser.FindNodeByName(nodes, destName)
if err == nil {
break
}
fmt.Printf("Couldn't find '%v', please try again:\n", destName)
fmt.Scanf("%v", &destName)
}
return destNode.Name
}
/*
* get string from stdin
* @param stringType
* the type of string: message content or message kind
*
* @return string got from stdin
**/
func getString(stringType string) string {
fmt.Println("Please input " + stringType + ":")
var res string
fmt.Scanf("%s", &res)
return res
}
/*
* Prompts the user for the configuration file's name
* @return configuration file's name string
*/
func getConfigName() string {
var configName string
fmt.Println("What's the config file's name? (ex. config)")
fmt.Scanf("%s", &configName)
if len(configName) == 0 {
configName = "config" // default name
}
return configName
}
/*
* Prompts the user for the local Node's name
* @return local Node's name string
*/
func getLocalName() string {
var localName string
fmt.Println("Who are you? (ex. armin)")
fmt.Scanf("%s", &localName)
if len(localName) == 0 {
localName = "unknown" // default name
}
return localName
}
/*
* prompts the user and builds a message
*/
func getMessage(nodes []messagePasser.Node, localNodeName string) messagePasser.Message {
dest := getDest(nodes)
kind := getString("message kind")
content := getString("message content")
return messagePasser.Message{Source: localNodeName, Destination: dest, Content: content, Kind: kind}
}
/*
* sets the orientation of the players to alphabetical
*/
func uiSetCompetitorLocation(myName string, peers *[]messagePasser.Node) {
var toSend messagePasser.Message
var nodeNames = []string{}
// loop through all nodes and pull out names
for _, node := range *peers {
nodeNames = append(nodeNames, node.Name)
}
// sort and get length
sort.Strings(nodeNames)
length := len(nodeNames)
// create content of message
content := fmt.Sprintf("%d", length)
for _, name := range nodeNames {
content = fmt.Sprintf("%v%v%v", content, defs.PAYLOAD_DELIMITER, name)
}
// create message and send message
toSend.Source = myName
toSend.Destination = myName
toSend.Kind = defs.MSG_PLAYER_LOC
toSend.Content = content
bridges.SendToPyBridge(toSend)
}
/* wait for incoming messages from the UI */
func PyBridgeReceiver() {
for {
message := bridges.ReceiveFromPyBridge()
switch message.Kind {
case defs.MSG_MYNAME:
localNameChannel <- message.Content
case defs.MSG_GAME_TYPE:
gameTypeChannel <- message.Content
case defs.MSG_CON_REQ:
valueType := strings.Split(message.Content, "|")[0]
consensus.Propose(message.Content, valueType)
case defs.MSG_CON_REPLY:
valueType := strings.Split(message.Content, "|")[0]
propCheckMutex.Lock()
propCheck := propChecksMap[valueType]
(*propCheck.Callback)(message.Content)
delete(propChecksMap, valueType)
propCheckMutex.Unlock()
case defs.MSG_EXIT:
// echo back to UI
bridges.SendToPyBridge(message)
// exit multegula
exitChannel <- true
default:
go putMessageIntoSendChannel(message)
}
}
}
/* wait for incoming messages from the bully algorithm */
func BullyReceiver() {
for {
message := bullySelection.GetMessageFromSendChannel()
go putMessageIntoSendChannel(message)
}
}
/*
* get unicorn update message from bullySelection,
* send unicorn update message to ui and consensus algorithm
*/
func UnicornReciever() {
for {
unicornUpdateMessage := bullySelection.GetUnicornUpdate()
go putMessageIntoSendChannel(unicornUpdateMessage)
}
}
/* wait for incoming messages from consensus algorithm */
func ConsensusReceiverRoutine() {
for {
message := consensus.SendMessage()
go putMessageIntoSendChannel(*message)
}
}
/*
* Routine to check proposals for a local value and respond
*/
func ConsensusCheckReceiverRoutine() {
for {
propCheck := consensus.ProposalCheck()
propCheckMutex.Lock()
propChecksMap[propCheck.Prop.Type] = propCheck
propCheckMutex.Unlock()
bridges.SendToPyBridge(messagePasser.Message{
Source: messagePasser.LocalNode.Name,
Destination: messagePasser.LocalNode.Name,
Kind: defs.MSG_CON_CHECK,
Content: propCheck.Prop.Value,
})
}
}
/*
* Routine to commit proposals that have reached consensus
*/
func ConsensusReachedRoutine() {
for {
proposal := consensus.ProposalToCommit()
commitMessage := messagePasser.Message{
Source: messagePasser.LocalNode.Name,
Destination: messagePasser.LocalNode.Name,
Kind: defs.MSG_CON_COMMIT,
Content: proposal.Value,
}
bridges.SendToPyBridge(commitMessage)
}
}
/* receive message from messagePasser and route to correct location */
func inboundDispatcher() {
for {
// get message from MessagePasser
message := messagePasser.Receive()
// Based on the type of message, determine where it needs routed
switch message.Kind {
// UI Messages
case defs.MSG_BALL_DEFLECTED:
fallthrough
case defs.MSG_BALL_MISSED:
fallthrough
case defs.MSG_BLOCK_BROKEN:
fallthrough
case defs.MSG_CON_CHECK:
fallthrough
case defs.MSG_CON_COMMIT:
fallthrough
case defs.MSG_DEAD_NODE:
fallthrough
case defs.MSG_DEAD_UNICORN:
fallthrough
case defs.MSG_FORCE_COMMIT:
fallthrough
case defs.MSG_KILL_NODE:
fallthrough
case defs.MSG_PADDLE_DIR:
fallthrough
case defs.MSG_PAUSE_UPDATE:
fallthrough
case defs.MSG_REJOIN_ACK:
fallthrough
case defs.MSG_REJOIN_REQ:
fallthrough
case defs.MSG_START_PLAY:
fallthrough
case defs.MSG_SYNC_ERROR:
bridges.SendToPyBridge(message)
case defs.MSG_UNICORN:
initConsensus(message)
bridges.SendToPyBridge(message)
// election messages
case defs.MSG_BULLY_ELECTION:
fallthrough
case defs.MSG_BULLY_ANSWER:
fallthrough
case defs.MSG_BULLY_ARE_YOU_ALIVE:
fallthrough
case defs.MSG_BULLY_IAM_ALIVE:
bullySelection.PutMessageToReceiveChannel(message)
case defs.MSG_BULLY_UNICORN:
initConsensus(message)
bullySelection.PutMessageToReceiveChannel(message)
// consensus messages
case defs.CONSENSUS_ACCEPT_KIND:
fallthrough
case defs.CONSENSUS_REJECT_KIND:
fallthrough
case defs.CONSENSUS_PROPOSE_KIND:
fallthrough
case defs.CONSENSUS_COMMIT_KIND:
consensus.ReceiveMessage(message)
default:
fmt.Printf("inboundDispatcher couldn't recognize message: %+v\n", message)
}
}
}
/* Handles all outbound messages */
func outboundDispatcher() {
for {
// get message from the send channel
message := <-sendChannel
// based on it's destination, determine which messagePasser
// routine is appropriate
if message.Destination == defs.MULTICAST_DEST {
messagePasser.Multicast(&message)
} else {
messagePasser.Send(message)
}
}
}
/*
* parses main arguments passed in through command-line
*/
func parseMainArguments(args []string) string {
var localNodeName string
if len(args) > 0 {
localNodeName = args[1]
} else {
localNodeName = getLocalName()
}
fmt.Println("Local Node Name:", localNodeName)
return localNodeName
}
/*
* Inits consensus when we receive a unicorn message
*/
func initConsensus(message messagePasser.Message) {
nodeIndex, node, err := messagePasser.FindNodeByName(messagePasser.PeerNodes, message.Content)
if err == nil {
peers := append(messagePasser.PeerNodes[:nodeIndex])
consensus.InitConsensus(node, peers, messagePasser.LocalNode.Name)
go ConsensusReceiverRoutine()
go ConsensusCheckReceiverRoutine()
go ConsensusReachedRoutine()
}
}
/*
*
*/
func runGame(gamePort int, uiPort int) {
/**** THIS IS LIKE ACTUAL GAMEPLAY ***/
// initialize communication with the UI
fmt.Printf("Port is:%d\n", uiPort)
bridges.InitPyBridge(uiPort)
go PyBridgeReceiver()
// get the localname
localNodeName := <-localNameChannel
fmt.Println("My name is:", localNodeName)
// determine the game type (multi or single player)
gameType := <-gameTypeChannel
if gameType == defs.GAME_TYPE_MULTI {
// get fellow players
localNode := messagePasser.Node{Name: localNodeName, IP: "127.0.0.1", Port: gamePort}
peers, err := bootstrapClient.GetNodes(localNode)
if err != nil {
fmt.Println("Couldn't get peers:", err)
panic(err)
}
*peers = append(*peers, localNode)
// set competitor location
uiSetCompetitorLocation(localNode.Name, peers)
// initialize message passer
messagePasser.InitMessagePasser(*peers, localNodeName)
fmt.Println(localNodeName, "made message passer.")
// initialize elections
go bullySelection.InitBullySelection(*peers, localNodeName)
go UnicornReciever()
/* start the routine waiting for messages coming from UI */
go BullyReceiver()
go inboundDispatcher()
go outboundDispatcher()
}
}
/* the Main function of the Multegula application */
func main() {
messagePasserTestFlag := flag.Bool("test", false, "MessagePasser Test Mode Flag")
bootstrapTestFlag := flag.Bool("bt", false, "Bootstrap Test Mode Flag")
consensusTestFlag := flag.Bool("ct", false, "Consensus Test Mode Flag")
uiPortFlag := flag.Int("uiport", defs.DEFAULT_UI_PORT, "Local port number for Python-Go bridge.")
gamePortFlag := flag.Int("gameport", defs.DEFAULT_GAME_PORT, "Local port number for MessagePasser.")
flag.Parse()
// Read command-line arguments and prompt the user if not provided
args := flag.Args()
// nodes used for testing purposes only
nodes := []messagePasser.Node{messagePasser.Node{Name: "armin", IP: "127.0.0.1", Port: 10011}, messagePasser.Node{Name: "garrett", IP: "127.0.0.1", Port: 10012}, messagePasser.Node{Name: "lunwen", IP: "127.0.0.1", Port: 10013}, messagePasser.Node{Name: "daniel", IP: "127.0.0.1", Port: 10014}}
// nodes := []messagePasser.Node{messagePasser.Node{Name: "armin", IP: "50.131.53.106", Port: 11111}, messagePasser.Node{Name: "garrett", IP: "71.199.96.75", Port: 44444}, messagePasser.Node{Name: "daniel", IP: "50.131.53.106", Port: 22222}, messagePasser.Node{Name: "lunwen", IP: "71.199.96.75", Port: 33333}}
// for testing consensus
if *consensusTestFlag {
testConsensus(nodes)
return
}
// for testing the bootstrapping
if *bootstrapTestFlag {
testBootstrap(nodes)
return
}
if *messagePasserTestFlag {
localNodeName := parseMainArguments(args)
localNode := messagePasser.Node{Name: localNodeName, IP: "127.0.0.1", Port: *gamePortFlag}
testMessagePasser(localNode)
return
}
// run actual game
runGame(*gamePortFlag, *uiPortFlag)
// Exit gracefully
<-exitChannel
fmt.Println("Quitting Multegula! Thank you for playing. :)")
}
/* testing functions */
var receiveQueue = []messagePasser.Message{}
func receiveRoutine() {
for {
messagePasser.Push(&receiveQueue, messagePasser.Receive())
}
}
func nonBlockingReceive() messagePasser.Message {
return messagePasser.Pop(&receiveQueue)
}
func testBootstrap(nodes messagePasser.Nodes) {
localName := getLocalName()
_, localNode, _ := messagePasser.FindNodeByName(nodes, localName)
fmt.Println("Contacting the bootstrap server...")
peers, err := bootstrapClient.GetNodes(localNode)
if err != nil {
fmt.Println("Got error:", err)
} else {
fmt.Printf("Got peers: %+v\n", peers)
}
}
func testMessagePasser(localNode messagePasser.Node) {
peers, err := bootstrapClient.GetNodes(localNode)
if err != nil {
fmt.Println("Couldn't get peers:", err)
panic(err)
}
*peers = append(*peers, localNode)
fmt.Print("--------------------------------\n")
fmt.Println("Available Nodes:")
for id, node := range *peers {
fmt.Printf(" ID:%d – %+v\n", id, node)
}
fmt.Println("Initing with localName:", localNode.Name)
messagePasser.InitMessagePasser(*peers, localNode.Name)
/* start a receiveRoutine to be able to use nonBlockingReceive */
go receiveRoutine()
fmt.Println("Please select the operation you want to do:")
for {
fmt.Println("Getting operation")
operation := getOperation()
if operation == 0 {
message := getMessage(*peers, localNode.Name)
messagePasser.Send(message)
} else if operation == 1 {
var message messagePasser.Message = nonBlockingReceive()
if (reflect.DeepEqual(message, messagePasser.Message{})) {
fmt.Print("No messages received.\n\n")
} else {
fmt.Printf("Received: %+v\n\n", message)
}
} else if operation == 2 {
message := getMessage(*peers, localNode.Name)
messagePasser.Multicast(&message)
fmt.Println("Did multicast")
} else {
fmt.Println("Operation not recognized. Please try again.")
}
}
}
func testConsensus(nodes messagePasser.Nodes) {
localName := getLocalName()
messagePasser.InitMessagePasser(nodes, localName)
go outboundDispatcher()
go inboundDispatcher()
leader := nodes[0]
consensus.InitConsensus(leader, nodes[1:], localName)
go ConsensusReceiverRoutine()
go ConsensusCheckReceiverRoutine()
go ConsensusReachedRoutine()
var proposalValue string
for {
if localName == leader.Name {
fmt.Println("Hit enter to propose.")
fmt.Scanf("%s", &proposalValue)
consensus.Propose(proposalValue, "test")
}
}
}