-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpeer.go
509 lines (448 loc) · 11.1 KB
/
peer.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
/*
Implements the solution to assignment 3 for UBC CS 416 2016 W2.
Usage:
Bootstrapping:
go run peer.go -b [physical-peerID] [peer-IP:port] [server ip:port]
Joining:
go run peer.go -j [physical-peerID] [peer-IP:port] [other-peer ip:port]
Example:
go run peer.go -b 0 127.0.0.1:19000 127.0.0.1:20000
go run peer.go -j 0 127.0.0.1:19001 127.0.0.1:19000
See run.sh for example running script.
*/
package main
import (
"fmt"
"os"
"strconv"
//can be deleted, only for example printing
//"math/rand"
"net"
"net/rpc"
"sort"
"sync"
"time"
// TODO
)
//Modes of operation
const (
BOOTSTRAP = iota
JOIN
)
// Resource server type.
type RServer int
type Peer int
type Join struct {
Resources []Resource
PeersIpPorts map[int]string
SID int
ResourceServer string
}
type JoinArg struct {
NewPeerId int
NewPeerIpPort string
}
// Request that peer sends in call to RServer.InitSession
// Return value is int
type Init struct {
IPaddr string // Must be set to ""
}
// Request that peer sends in call to RServer.GetResource
type ResourceRequest struct {
SessionID int
IPaddr string // Must be set to ""
}
// Response that the server returns from RServer.GetResource
type Resource struct {
Resource string
LogicalPeerID int
NumRemaining int
}
//An array of resources
type Resources []Resource
var LOCALPID int
var LOCALIPPORT string
var CAPTAIN bool
var RESOURCES Resources
var PEERSIPPORTS = make(map[int]string)
var SID int
var RESOURCESERVER string
var CAPTAINIP string
var mutex = &sync.Mutex{}
// Main workhorse method.
func main() {
var nextCap string
var last int
var first int
var peerIds []int
var i int
//var nextCapHeartMonitor string
nextCap = "nil"
// Parse the command line args, panic if error
mode, physicalPeerId, peerIpPort, otherIpPort, err := ParseArguments()
if err != nil {
panic(err)
}
go func() {
pServer := rpc.NewServer()
p := new(Peer)
pServer.Register(p)
l, _ := net.Listen("tcp", peerIpPort)
for {
conn, _ := l.Accept()
go pServer.ServeConn(conn)
}
}()
LOCALPID = physicalPeerId
LOCALIPPORT = peerIpPort
if mode == BOOTSTRAP {
CAPTAIN = true
RESOURCESERVER = otherIpPort
CAPTAINIP = LOCALIPPORT
resourceClient, _ := rpc.Dial("tcp", RESOURCESERVER)
initArgs := &Init{""}
err = resourceClient.Call("RServer.InitSession", initArgs, &SID)
PEERSIPPORTS[LOCALPID] = peerIpPort
resourceClient.Close()
}
if mode == JOIN {
CAPTAIN = false
peerClient, _ := rpc.Dial("tcp", otherIpPort)
joinArgs := &JoinArg{LOCALPID, LOCALIPPORT}
var joinReply Join
err = peerClient.Call("Peer.JoinPeer", joinArgs, &joinReply)
RESOURCES = joinReply.Resources
PEERSIPPORTS = joinReply.PeersIpPorts
SID = joinReply.SID
RESOURCESERVER = joinReply.ResourceServer
peerClient.Close()
}
//fmt.Println(PEERSIPPORTS)
JoinPrint(LOCALPID)
for {
//fmt.Println("looping ...")
//time.Sleep(5 * time.Second)
mutex.Lock()
for !CAPTAIN {
/*c, err := rpc.Dial("tcp", CAPTAINIP)
if err != nil {
peerIds = getPeerIds(PEERSIPPORTS)
nextCapHeartMonitor = PEERSIPPORTS[peerIds[0]]
if LOCALIPPORT == nextCapHeartMonitor {
CAPTAIN = true
}
CAPTAINIP = nextCapHeartMonitor
} else if err == nil {
c.Close()
}*/
time.Sleep(5 * time.Second)
if CAPTAINIP != "nil" {
peerIds1 := getPeerIds(PEERSIPPORTS)
nextCapHeartMonitor := PEERSIPPORTS[peerIds1[0]]
if LOCALIPPORT == nextCapHeartMonitor {
CAPTAIN = true
}
}
CAPTAINIP = "goo"
}
mutex.Unlock()
time.Sleep(3 * time.Second)
str := "nil"
updateCaptainIps(&str)
mutex.Lock()
if nextCap != "" {
fmt.Println("getting resource ...")
resourceArgs := ResourceRequest{SID, ""}
var resourceReply Resource
rr := &resourceReply
resourceClient, err := rpc.Dial("tcp", RESOURCESERVER)
if err != nil {
}
err = resourceClient.Call("RServer.GetResource", &resourceArgs, rr)
resourceClient.Close()
RESOURCES = append(RESOURCES, *rr)
sendOutResources(rr)
}
//relinquish captainhood
for {
peerIds = getPeerIds(PEERSIPPORTS)
last = len(PEERSIPPORTS) - 1
first = 0
for i = 0; i <= last; i++ {
if peerIds[i] == LOCALPID {
break
}
}
numRemaining := RESOURCES[len(RESOURCES)-1].NumRemaining
switch {
case last == first && numRemaining >= 1:
nextCap = ""
case i == last && last != first && numRemaining >= 1:
nextCap = PEERSIPPORTS[peerIds[first]]
case numRemaining < 1:
RESOURCES.FinalPrint(LOCALPID)
//fmt.Println(PEERSIPPORTS)
closePeers()
default:
nextCap = PEERSIPPORTS[peerIds[i+1]]
}
if nextCap == "" {
break
}
//updateCaptainIps(&nextCap)
CAPTAIN = false
newCapClient, err := rpc.Dial("tcp", nextCap)
if err != nil {
if i == last {
delete(PEERSIPPORTS, peerIds[first])
} else {
delete(PEERSIPPORTS, peerIds[i+1])
}
continue
}
var changeCapArgs string
var changeCapReply string
err = newCapClient.Call("Peer.ChangeCap", &changeCapArgs, &changeCapReply)
newCapClient.Close()
break
}
mutex.Unlock()
}
}
func (t *Peer) JoinPeer(newPeer *JoinArg, reply *Join) error {
mutex.Lock()
PEERSIPPORTS[newPeer.NewPeerId] = newPeer.NewPeerIpPort
//fmt.Println(PEERSIPPORTS)
//fmt.Println("joining ...")
var sendPeersReply string
for id, ip := range PEERSIPPORTS {
if (ip != LOCALIPPORT) && (ip != newPeer.NewPeerIpPort) {
peerClient, err := rpc.Dial("tcp", ip)
if err != nil {
delete(PEERSIPPORTS, id)
continue
}
err = peerClient.Call("Peer.SendPeers", &PEERSIPPORTS, &sendPeersReply)
peerClient.Close()
}
}
mutex.Unlock()
reply.Resources = RESOURCES
reply.PeersIpPorts = PEERSIPPORTS
reply.SID = SID
reply.ResourceServer = RESOURCESERVER
return nil
}
func sendOutResources(newResource *Resource) {
for id, ip := range PEERSIPPORTS {
if ip != LOCALIPPORT {
peerClient, err := rpc.Dial("tcp", ip)
if err != nil {
delete(PEERSIPPORTS, id)
continue
}
forwardResourceReply := ""
err = peerClient.Call("Peer.ForwardResource", newResource, &forwardResourceReply)
peerClient.Close()
}
}
}
func updateCaptainIps(newCap *string) {
for id, ip := range PEERSIPPORTS {
if ip != LOCALIPPORT {
peerClient, err := rpc.Dial("tcp", ip)
if err != nil {
delete(PEERSIPPORTS, id)
continue
}
forwardResourceReply := ""
err = peerClient.Call("Peer.ChangeMonitor", newCap, &forwardResourceReply)
peerClient.Close()
}
}
}
func getPeerIds(peersIpPorts map[int]string) []int {
peerIds := make([]int, 0, len(peersIpPorts))
for id := range peersIpPorts {
peerIds = append(peerIds, id)
}
sort.Ints(peerIds)
return peerIds
}
func closePeers() {
str := ""
for _, ip := range PEERSIPPORTS {
if ip != LOCALIPPORT {
conn, err := rpc.Dial("tcp", ip)
if err != nil {
continue
}
err = conn.Call("Peer.ClosePeer", &str, &str)
if err != nil {
continue
}
}
}
os.Exit(0)
}
func (t *Peer) ChangeMonitor(newCap *string, reply *string) error {
CAPTAINIP = *newCap
return nil
}
func (t *Peer) ClosePeer(args *string, reply *string) error {
os.Exit(0)
return nil
}
func (t *Peer) ChangeCap(args *string, reply *string) error {
CAPTAIN = true
return nil
}
func (t *Peer) ForwardResource(newResource *Resource, reply *string) error {
RESOURCES = append(RESOURCES, *newResource)
return nil
}
func (t *Peer) SendPeers(peers *map[int]string, reply *string) error {
PEERSIPPORTS = *peers
//fmt.Println(PEERSIPPORTS)
*reply = ""
return nil
}
// Parses the command line arguments, two cases are valid
func ParseArguments() (mode int, physicalPeerId int, peerIpPort string, serverOrJoinerIpPort string, err error) {
args := os.Args[1:]
if len(args) != 4 {
err = fmt.Errorf("Please supply 4 command line arguments as seen in the spec http://www.cs.ubc.ca/~bestchai/teaching/cs416_2016w2/assign3/index.html")
return
}
switch args[0] {
case "-b":
mode = BOOTSTRAP
case "-j":
mode = JOIN
default:
err = fmt.Errorf("Valid modes are bootstrapping -b and joining -j not %s", args[0])
return
}
physicalPeerId, err = strconv.Atoi(args[1])
if err != nil {
err = fmt.Errorf("unable to parse physical peer id (argument 2) please supply an integer Error:%s", err.Error())
}
peerIpPort = args[2]
serverOrJoinerIpPort = args[3]
return
}
/////////////////// Use functions below for state notifications (DO NOT MODIFY).
func JoinPrint(physicalPeerId int) {
fmt.Printf("JOINED: using %d\n", physicalPeerId)
}
//
func (r Resource) String() string {
return fmt.Sprintf("Resource: %s\tLogicalPeerID: %d\tNumRemaining: %d", r.Resource, r.LogicalPeerID, r.NumRemaining)
}
//
func (r Resources) String() (rString string) {
for _, resource := range r {
rString += resource.String() + "\n"
}
return
}
//
func (r Resources) FinalPrint(physicalPeerId int) {
for _, resource := range r {
fmt.Printf("ALLOC: %d %d %s\n", physicalPeerId, resource.LogicalPeerID, resource.Resource)
}
}
// Example illustrating JoinPrint and FinalPrint usage:
//
// var res Resources
// for i := 0; i < 5; i++ {
// res = append(res, Resource{Resource: fmt.Sprintf("%d", i), LogicalPeerID: rand.Int(), NumRemaining: 5 - i})
// }
// JoinPrint(physicalPeerId)
// res.FinalPrint(physicalPeerId)
//for {
/*numPeers := len(PEERSIPPORTS)
lockRequestArgs := ""
lockRequestReply := false
for i := 0; i < numPeers; i++ {
if PEERSIPPORTS[i] != LOCALIPPORT {
peerClient, err := rpc.Dial("tcp", PEERSIPPORTS[i])
if err != nil {
fmt.Println("DEAD")
os.Exit(0)
}
err = peerClient.Call("Peer.RequestLock", &lockRequestArgs, &lockRequestReply)
if !(lockRequestReply) {
break
}
peerClient.Close()
}
}
if numPeers == 1 {
lockRequestReply = true
}
if lockRequestReply {
mutex.Lock()
mutex.Unlock()
}*/
//}
//for {
//}
/*numPeers := len(PEERSIPPORTS)
lockRequestArgs := ""
lockRequestReply := false
//lock newPeer
peerClient, err := rpc.Dial("tcp", *newPeer)
if err != nil {
fmt.Println("DEAD")
os.Exit(0)
}
err = peerClient.Call("Peer.RequestLock", &lockRequestArgs, &lockRequestReply)
peerClient.Close()
for i := 0; i < numPeers; i++ {
if PEERSIPPORTS[i] != LOCALIPPORT {
peerClient, err = rpc.Dial("tcp", PEERSIPPORTS[i])
err = peerClient.Call("Peer.RequestLock", &lockRequestArgs, &lockRequestReply)
if !(lockRequestReply) {
break
}
peerClient.Close()
}
}
if numPeers == 1 {
lockRequestReply = true
}
if lockRequestReply {
mutex.Lock()
mutex.Unlock()
}*/
/*func (t *Peer) NewCaptainRequest(newCapIp *string, reply *bool) error {
mutex.Lock()
Captain = false
CAPTAINSNAME = *newCapIp
*reply = true
return nil
}*/
/*if CAPTAINSNAME != LOCALIPPORT{
lockRequestArgs := LOCALIPPORT
lockRequestReply := false
captainsClient, err := rpc.Dial("tcp", CAPTAINSNAME)
err = captainsClient.Call("Peer.NewCaptainRequest", &lockRequestArgs, &lockRequestReply)
if lockRequestReply {
CAPTAINSNAME = LOCALIPPORT
CAPTAIN = true
mutex.Unlock()
}
}*/
/*for id, ip := range PEERSIPPORTS {
if (ip != LOCALIPPORT) && (ip != newPeer.NewPeerIpPort) {
peerClient, err := rpc.Dial("tcp", ip)
if err != nil {}
forwardResourceReply := ""
err = peerClient.Call("Peer.ForwardResource", &resourceReply, &forwardResourceReply)
if err != nil {
delete(PEERSIPPORTS, id)
}
peerClient.Close()
}
}*/