-
Notifications
You must be signed in to change notification settings - Fork 0
/
tracker.go
363 lines (305 loc) · 8.14 KB
/
tracker.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
package main
import (
"bufio"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"math"
"net"
"strconv"
"strings"
"sync"
)
// TODO: Handle disconnect removals
/*
JSON Unmarshalling:
To unmarshal JSON into an interface value, Unmarshal stores one of these in the interface value:
bool, for JSON booleans float64, for JSON numbers string, for JSON strings []interface{}, for JSON arrays map[string]interface{}, for JSON objects nil for JSON null
*/
type Peer struct {
IP string `json:"ip"`
Port int `json:"port"`
ListenPort int `json:"listen_port"`
// Link back to the chunks it's related to.
chunks []*Chunk // Loopback
}
func (p Peer) RemoteAddr() string {
return fmt.Sprintf("%s:%d", p.IP, p.Port)
}
type Chunk struct {
seqId int
//hash string // SHA-1 Hash function
size uint64 // number of bytes
peers []*Peer
}
type File struct {
filename string
length uint64 // Size in bytes
chunks []Chunk
sync.RWMutex
}
type Packet struct {
Type string `json:"t"`
Subject string `json:"s"`
Message map[string]interface{} `json:"m"`
peer *Peer
}
type Tracker struct {
fileMap map[string]*File
fileMut *sync.RWMutex
peerMap map[string]*Peer
peerMut *sync.RWMutex
}
func copyPeers(peers []*Peer) []Peer {
resp := make([]Peer, len(peers))
for i, peer := range peers {
resp[i] = Peer{
IP: peer.IP,
Port: peer.ListenPort,
}
}
return resp
}
func (t *Tracker) ChunkRegister(p Packet) (resp Packet, toSend bool) {
filename := p.Message["filename"].(string)
chunkSeqId := int(p.Message["seqId"].(float64))
t.fileMut.RLock()
if actualFile, ok := t.fileMap[filename]; ok {
t.fileMut.RUnlock()
chunk := &actualFile.chunks[chunkSeqId]
actualFile.Lock()
chunk.peers = append(chunk.peers, p.peer)
actualFile.Unlock()
// Add to Peer Loopback
p.peer.chunks = append(p.peer.chunks, chunk)
}
return Packet{"r", "cr", map[string]interface{}{"ack": true}, &Peer{}}, true
}
func (t Tracker) FileLocation(p Packet) (resp Packet, toSend bool) {
// Serialization Struct
type ChunkSer struct {
Peers []Peer `json:"peers"`
Size uint64 `json:"size"`
}
res := map[int]ChunkSer{}
var fileLen uint64 = 0
numChunks := 0
filename := p.Message["filename"].(string)
t.fileMut.RLock()
if file, ok := t.fileMap[filename]; ok {
t.fileMut.RUnlock()
file.RLock()
fileLen = file.length
numChunks = len(file.chunks)
for _, chunk := range file.chunks {
res[chunk.seqId] = ChunkSer{
Peers: copyPeers(chunk.peers),
Size: chunk.size,
}
}
file.RUnlock()
}
return Packet{"r", "floc", map[string]interface{}{"chunks": res, "length": fileLen, "numChunks": numChunks}, &Peer{}}, true
}
func (t Tracker) FileList(p Packet) (resp Packet, toSend bool) {
res := map[string]uint64{}
t.fileMut.RLock()
for filename, file := range t.fileMap {
res[filename] = file.length
}
t.fileMut.RUnlock()
return Packet{"r", "fl", map[string]interface{}{"files": res}, &Peer{}}, true
}
func (t *Tracker) RegisterPeer(p Packet) (resp Packet, toSend bool) {
peer := p.peer
remoteAddr := peer.RemoteAddr()
t.peerMut.RLock()
if _, ok := t.peerMap[remoteAddr]; !ok {
t.peerMut.RUnlock()
listenPort, _ := strconv.Atoi(p.Message["listen_port"].(string))
peer.ListenPort = listenPort
t.peerMut.Lock()
// TODO: ReRegister?
t.peerMap[remoteAddr] = peer
t.peerMut.Unlock()
} else {
t.peerMut.RUnlock()
}
files := p.Message["files"].(map[string]interface{})
for filename, lenNoType := range files {
fileLen := lenNoType.(float64)
numChunks := int(math.Ceil(fileLen / CHUNK_SIZE_BYTES))
var actualFile *File
t.fileMut.RLock()
if currentFile, ok := t.fileMap[filename]; ok {
t.fileMut.RUnlock()
actualFile = currentFile
} else {
t.fileMut.RUnlock()
t.fileMut.Lock()
actualFile = &File{filename: filename, length: uint64(fileLen), chunks: make([]Chunk, numChunks)}
t.fileMap[filename] = actualFile
t.fileMut.Unlock()
}
for i := 0; i < numChunks; i++ {
chunk := &(actualFile.chunks[i])
chunk.seqId = i
if i == int(numChunks)-1 {
// >///<
chunk.size = uint64(math.Min(float64(uint64(fileLen)%CHUNK_SIZE_BYTES_INT), CHUNK_SIZE_BYTES))
} else {
chunk.size = CHUNK_SIZE_BYTES_INT
}
if chunk.peers == nil {
chunk.peers = make([]*Peer, 1)
chunk.peers[0] = peer
} else {
// Current Peer as peer to all chunks
chunk.peers = append(chunk.peers, peer)
}
// Add chunk to peer
peer.chunks = append(peer.chunks, chunk)
}
}
return Packet{Type: "r", Subject: "reg", Message: map[string]interface{}{"ack": true, "filename": true}}, true
}
var tracker = Tracker{fileMap: make(map[string]*File), peerMap: make(map[string]*Peer), fileMut: &sync.RWMutex{}, peerMut: &sync.RWMutex{}}
var funcMap = map[string]func(Packet) (Packet, bool){
"reg": tracker.RegisterPeer,
"fl": tracker.FileList,
"floc": tracker.FileLocation,
"cr": tracker.ChunkRegister,
}
func clearPeerChunks(p *Peer) {
remote := p.RemoteAddr()
for _, chunk := range p.chunks {
for i, tP := range chunk.peers {
if tP.RemoteAddr() == remote {
n := len(chunk.peers)
chunk.peers[i] = chunk.peers[n - 1] // Replace into removed position
chunk.peers = chunk.peers[:n-1] // Reslice to make it smaller
}
}
}
}
func handleConnection(c net.Conn) {
defer c.Close()
remoteAddr := c.RemoteAddr().String()
splits := strings.Split(remoteAddr, ":")
var currentPeer *Peer
if peer, ok := tracker.peerMap[remoteAddr]; ok {
currentPeer = peer
} else {
port, e := strconv.Atoi(splits[1])
if e != nil {
return
}
currentPeer = &Peer{
IP: splits[0],
Port: port,
chunks: make([]*Chunk, 0),
}
}
fmt.Printf(" [debug] Accepted Connection from %s\n", remoteAddr)
for {
reader := bufio.NewReader(c)
netData, err := reader.ReadString('\n')
if err != nil {
fmt.Printf("[debug] Disconnected from peer %s with reason: %s\n", remoteAddr, err)
clearPeerChunks(currentPeer)
return
}
temp := strings.TrimSpace(netData)
header := strings.Split(temp, "=")
if header[0] != "LENGTH" {
continue
}
jsonByteLength, err := strconv.Atoi(header[1])
if err != nil {
fmt.Printf("[error][%s] At reading length: %s\n", remoteAddr, err)
return
}
buf := make([]byte, jsonByteLength)
n, err := io.ReadFull(reader, buf)
if err != nil || n < jsonByteLength {
fmt.Printf("[error][%s] Reading %d json bytes : %s\n", remoteAddr, jsonByteLength, err)
return
}
var p Packet
err = json.Unmarshal(buf, &p)
if err != nil {
fmt.Printf("[error][%s] Parsing json: %s\n", remoteAddr, jsonByteLength, err)
return
}
p.peer = currentPeer
fmt.Printf("[info][%s] Got Packet: %s\n", remoteAddr, p)
if p.Type == "q" && p.Subject == "stop" {
// Deferred close is enabled.
return
}
if pFunc, ok := funcMap[p.Subject]; ok {
resp, toSend := pFunc(p)
if toSend {
b, _ := json.Marshal(resp)
fmt.Fprintf(c, "LENGTH=%d\n", len(b))
_, err = c.Write(b)
if err != nil {
fmt.Printf("[error][%s] Error Writing to Conn: %s\n", remoteAddr, err)
return
}
}
}
}
}
var (
PORT = "8080"
CHUNK_SIZE_BYTES = 1e6
CHUNK_SIZE_BYTES_INT = uint64(CHUNK_SIZE_BYTES)
)
func main() {
l, err := net.Listen("tcp4", "0.0.0.0:"+PORT)
if err != nil {
fmt.Println(err)
return
}
defer l.Close()
fmt.Println("Server started listening on", PORT)
for {
c, err := l.Accept()
if err != nil {
fmt.Println(err)
return
}
go handleConnection(c)
}
}
func main2() {
p := Packet{"r", "flist", map[string]interface{}{"test": 1}, &Peer{}}
fmt.Println(p)
b, _ := json.Marshal(p)
fmt.Println(string(b))
type ChunkSer struct {
Peers []Peer `json:"peers"`
Size uint64 `json:"size"`
}
b, _ = json.Marshal(map[string]interface{}{
"chunks": map[int]interface{}{
1: ChunkSer{
Peers: []Peer{Peer{
IP: "127.0.0.1",
Port: 23234,
}},
Size: 1234,
},
},
})
fmt.Println(string(b))
s := map[string]interface{}{}
json.Unmarshal(b, &s)
fmt.Println(((s["chunks"].(map[string]interface{}))["1"].(map[string]interface{}))["peers"].([]interface{})[0])
o := base64.StdEncoding.EncodeToString(b)
fmt.Println(o)
b, _ = base64.StdEncoding.DecodeString(o)
fmt.Println(string(b))
}