-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
410 lines (324 loc) · 9.32 KB
/
server.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
// Stores functionality for responding to messages.
package main
import (
"encoding/json"
"fmt"
"log"
"net"
"os"
"strings"
)
func startServer(clientServerChan chan int) {
server, err := net.Listen("tcp", fmt.Sprintf(":%d", SERVER_PORT))
if err != nil {
log.Fatalf("Couldn't start server: %s", err.Error())
}
clientServerChan <- 1
for {
conn, err := server.Accept()
if err != nil {
log.Fatalf("Error accepting: %s", err.Error())
}
buf := make([]byte, 8192)
mlen, err := conn.Read(buf)
var message Message
json.Unmarshal(buf[:mlen], &message)
var messagesToPiggyback Messages
remoteAddress := strings.Split(conn.RemoteAddr().String(), ":")[0]
switch message.Kind {
case PING:
messagesToPiggyback = GetUnexpiredPiggybackMessages()
PrintMessage("Incoming", message, remoteAddress)
var messages Messages
err = json.Unmarshal([]byte(message.Data), &messages)
if err != nil {
LogError("Failed to unmarshal PING messages, skipping")
continue
}
// Each PING contains multiple messages within it.
for _, subMessage := range messages {
switch subMessage.Kind {
case HELLO:
ProcessHelloMessage(subMessage)
case LEAVE:
ProcessFailOrLeaveMessage(subMessage)
case FAIL:
ProcessFailOrLeaveMessage(subMessage)
default:
log.Fatalf("Unexpected submessage kind in PING")
}
}
case JOIN:
PrintMessage("Incoming", message, "")
responseMessage, err := ProcessJoinMessage(message, remoteAddress)
if err != nil {
log.Fatalln("Failed to process join message", message)
}
// Piggyback the JOIN message
messagesToPiggyback = Messages{responseMessage}
case LEAVE:
messagesToPiggyback = GetUnexpiredPiggybackMessages()
ProcessFailOrLeaveMessage(message)
case REPLICATE:
// Replicate does not piggyback anything.
err = ProcessReplicateMessage(message)
case CREATE:
err = ProcessCreateMessage(message, false)
case TEMP_CREATE:
err = ProcessCreateMessage(message, true)
case APPEND:
err = ProcessAppendMessage(message, false)
case TEMP_APPEND:
err = ProcessAppendMessage(message, true)
case CHECK:
err = ProcessCheckMessage(message, conn, remoteAddress)
if err != nil {
fmt.Println(err.Error())
}
conn.Close()
continue
case FILES:
err = ProcessFilesMessage(message, conn, remoteAddress)
if err != nil {
fmt.Println(err.Error())
}
conn.Close()
continue
case GETFILE:
err = ProcessGetFileMessage(message, conn, remoteAddress)
if err != nil {
fmt.Println(err.Error())
}
conn.Close()
continue
case MERGE:
err = ProcessMergeMessage(message, conn, remoteAddress)
if err != nil {
fmt.Println(err.Error())
}
conn.Close()
continue
case DELETE:
err = ProcessDeleteMessage(message)
default:
log.Fatalln("Unexpected message kind: ", message)
}
if err != nil {
fmt.Println(err.Error())
}
ackResponse, err := EncodeAckMessage(messagesToPiggyback)
if err != nil {
LogError("Failed to generate response.")
continue
}
var ackMessage Message
err = json.Unmarshal(ackResponse, &ackMessage)
if err != nil {
LogError("Unable to decode outgoing ACK message")
continue
}
PrintMessage("outgoing", ackMessage, "")
conn.Write(ackResponse)
conn.Close()
}
}
// request contains the encoded Data of the JOIN message.
// addr is the address of the host that sent this PING.
func ProcessJoinMessage(message Message, addr string) (Message, error) {
if isLeader {
joinResponse, err := IntroduceNodeToGroup(message.Data, addr)
return joinResponse, err
} else {
return Message{}, fmt.Errorf("unexpected JOIN message received for non Introducer node")
}
}
func ProcessHelloMessage(message Message) error {
PrintMessage("incoming", message, "")
nodeId := message.Data
_, ok := GetMemberInfo(nodeId)
if ok {
LogMessage(fmt.Sprintf("Node %s already exists in membership info, Skipping HELLO \n", nodeId))
return nil
}
if nodeId == NODE_ID {
LogMessage(fmt.Sprintf("Received self hello message for ID: %s Skip \n", nodeId))
return nil
}
err := AddNewMemberToMembershipInfo(nodeId)
if err != nil {
return err
}
AddPiggybackMessage(message)
return nil
}
func ProcessFailOrLeaveMessage(message Message) error {
PrintMessage("incoming", message, "")
// For the fail message, Data is expected to be the node Id.
nodeId := message.Data
// If it's you, be very confused.
if nodeId == NODE_ID {
fmt.Println("Received self failure message.")
os.Exit(0)
}
_, ok := GetMemberInfo(nodeId)
if ok { // node exists in membership info, remove and disseminate
DeleteMemberAndReReplicate(nodeId)
// disseminating info that the node left
AddPiggybackMessage(message)
return nil
}
return nil
}
func ProcessReplicateMessage(message Message) error {
PrintMessage("incoming", message, "")
encodedFiles := message.Data
var files []FileInfo
err := json.Unmarshal([]byte(encodedFiles), &files)
if err != nil {
return err
}
for _, file := range files {
// This file was received over the network, ensure isPrimary is false for safety.
file.isPrimary = false
// StoreFileLocally(&file)
}
return nil
}
func ProcessCreateMessage(message Message, isTemp bool) error {
PrintMessage("incoming", message, "")
encodedFileInfo := message.Data
var fileInfo FileInfo
err := json.Unmarshal([]byte(encodedFileInfo), &fileInfo)
if err != nil {
return err
}
return CreateLocalFile(fileInfo.Name, isTemp)
}
func ProcessAppendMessage(message Message, isTemp bool) error {
PrintMessage("incoming", message, "")
encodedFileBlock := message.Data
var fileBlock FileBlock
err := json.Unmarshal([]byte(encodedFileBlock), &fileBlock)
if err != nil {
return err
}
return AppendToLocalFile(fileBlock.Name, fileBlock.Content, isTemp)
}
func ProcessDeleteMessage(message Message) error {
PrintMessage("incoming", message, "")
hdfsfilename := message.Data
delete(fileInfoMap, hdfsfilename)
delete(fileBlockMap, hdfsfilename)
return nil
}
func ProcessMergeMessage(message Message, conn net.Conn, remoteAddress string) error {
PrintMessage("incoming", message, "")
hdfsFileName := message.Data
// Send the FileInfo just so that the connection does not timeout
var checkFileInfo FileInfo
_, ok := fileInfoMap[hdfsFileName]
if ok {
checkFileInfo = *fileInfoMap[hdfsFileName]
}
encodedFileInfo, err := json.Marshal(checkFileInfo)
if err != nil {
return err
}
checkResponse := Message{Kind: CHECK, Data: string(encodedFileInfo)}
encodedCheckResponse, err := json.Marshal(checkResponse)
if err != nil {
return err
}
conn.Write(encodedCheckResponse)
conn.Close()
MergeHDFSFile(hdfsFileName)
return nil
}
func ProcessCheckMessage(message Message, conn net.Conn, remoteAddress string) error {
PrintMessage("incoming", message, remoteAddress)
filenameToCheck := message.Data
var checkFileInfo FileInfo
_, ok := fileInfoMap[filenameToCheck]
if ok {
checkFileInfo = *fileInfoMap[filenameToCheck]
}
encodedFileInfo, err := json.Marshal(checkFileInfo)
if err != nil {
return err
}
checkResponse := Message{Kind: CHECK, Data: string(encodedFileInfo)}
encodedCheckResponse, err := json.Marshal(checkResponse)
if err != nil {
return err
}
conn.Write(encodedCheckResponse)
conn.Close()
return nil
}
func ProcessFilesMessage(message Message, conn net.Conn, remoteAddress string) error {
PrintMessage("incoming", message, remoteAddress)
filenames := GetFilesNamesOnNode()
encodedFilenames, err := json.Marshal(filenames)
if err != nil {
return err
}
filesResponse := Message{Kind: FILES, Data: string(encodedFilenames)}
encodedFilesResponse, err := json.Marshal(filesResponse)
if err != nil {
return err
}
conn.Write(encodedFilesResponse)
conn.Close()
return nil
}
func ProcessGetFileMessage(message Message, conn net.Conn, remoteAddress string) error {
PrintMessage("incoming", message, remoteAddress)
encodedGetFileRequest := message.Data
var getFileStruct GetMessage
err := json.Unmarshal([]byte(encodedGetFileRequest), &getFileStruct)
if err != nil {
return err
}
var checkFileInfo FileInfo
// Check if you have the file that is being requested
_, ok := fileInfoMap[getFileStruct.Name]
if ok {
checkFileInfo = *fileInfoMap[getFileStruct.Name]
}
encodedFileInfo, err := json.Marshal(checkFileInfo)
if err != nil {
return err
}
checkResponse := Message{Kind: CHECK, Data: string(encodedFileInfo)}
encodedcheckResponse, err := json.Marshal(checkResponse)
if err != nil {
return err
}
// Write the file info of the requested file so that the port doesn't time out
// You will asynchronously push the file right affter
conn.Write(encodedcheckResponse)
// Send the file CREATE message
encodedFileInfo, err = json.Marshal(fileInfoMap[getFileStruct.Name])
if err != nil {
return err
}
createMessage := Message{Kind: TEMP_CREATE, Data: string(encodedFileInfo)}
err = SendMessage(getFileStruct.Requester, createMessage)
if err != nil {
return err
}
// Send all the file blocks as APPEND messages
for _, eachhdfsfileblock := range fileBlockMap[getFileStruct.Name] {
// _, err = f.Write(eachhdfsfileblock.Content)
encodedFileBlock, err := json.Marshal(eachhdfsfileblock)
if err != nil {
return err
}
appendMessage := Message{Kind: TEMP_APPEND, Data: string(encodedFileBlock)}
err = SendMessage(getFileStruct.Requester, appendMessage)
if err != nil {
return err
}
}
return nil
}