-
Notifications
You must be signed in to change notification settings - Fork 1
/
masterServer.py
224 lines (181 loc) · 7.61 KB
/
masterServer.py
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
import os
import time
import uuid
import grpc
import random
import gfs_pb2
import gfs_pb2_grpc
from concurrent import futures
from util import Status, Config
from collections import OrderedDict
class loadBalancer():
def __init__(self):
self.locs = Config.chunkserverLocs
self.csLoad = {}
for cs in self.locs:
self.csLoad[cs] = 0
def getLocs(self):
locs = []
for loc in sorted(self.csLoad.items(), key=lambda x: x[1]):
self.csLoad[loc[0]] += 1
locs.append(loc[0])
if(len(locs) == 3):
return locs
return locs
def decreaseLoad(self, loc):
self.csLoad[loc] -= 1
class Chunk(object):
def __init__(self):
self.locs = []
class File(object):
def __init__(self, filePath):
self.filePath = filePath
self.chunks = OrderedDict()
class MasterServer(object):
def __init__(self):
self.files = {}
self.locs = Config.chunkserverLocs
self.loadBalancer = loadBalancer()
def getLatestChunk(self, filePath):
latestChunkHandle = list(self.files[filePath].chunks.keys())[-1]
return latestChunkHandle
def listFiles(self, filePath):
fileList = []
for fp in self.files.keys():
if fp.startswith(filePath):
fileList.append(fp)
return fileList
def createFile(self, filePath):
if filePath in self.files:
return Status(-1, "ERROR: File exists already: {}".format(filePath))
self.files[filePath] = File(filePath)
return self.createChunk(filePath, -1)
def appendFile(self, filePath):
if filePath not in self.files:
return None, None, Status(-1, "ERROR: file {} doesn't exist".format(filePath))
latestChunkHandle = self.getLatestChunk(filePath)
locs = self.files[filePath].chunks[latestChunkHandle].locs
status = Status(0, "Success")
return latestChunkHandle, locs, status
def createChunk(self, filePath, prevChunkHandle):
if filePath not in self.files:
return Status(-2, "ERROR: New chunk file doesn't exist: {}".format(filePath))
latestChunk = None if prevChunkHandle == -1 else self.getLatestChunk(filePath)
if prevChunkHandle != -1 and latestChunk != prevChunkHandle:
return Status(-3, "ERROR: New chunk already created: {} : {}".format(filePath, chunkHandle))
chunkHandle = str(uuid.uuid1())
self.files[filePath].chunks[chunkHandle] = Chunk()
locs = self.loadBalancer.getLocs()
for loc in locs:
self.files[filePath].chunks[chunkHandle].locs.append(loc)
return chunkHandle, locs, Status(0, "New Chunk Created")
def getChunkSpace(self, filePath):
try:
latestChunkHandle = self.getLatestChunk(filePath)
path = os.path.join(Config.rootDir, self.files[filePath].chunks[latestChunkHandle].locs[0])
chunkSpace = Config.chunkSize - os.stat(os.path.join(path, latestChunkHandle)).st_size
except Exception as e:
return None, Status(-1, "ERROR: " + str(e))
else:
return str(chunkSpace), Status(0, "")
def readFile(self, filePath, offset, numbytes):
if filePath not in self.files:
return Status(-1, "ERROR: file {} doesn't exist".format(filePath))
startChunk = offset // Config.chunkSize
allChunks = list(self.files[filePath].chunks.keys())
if startChunk > len(allChunks):
return Status(-1, "ERROR: Offset is too large")
startOffset = offset % Config.chunkSize
if numbytes == -1:
endOffset = Config.chunkSize
endChunk = len(allChunks) - 1
else:
endOffset = offset + numbytes - 1
endChunk = endOffset // Config.chunkSize
endOffset = endOffset % Config.chunkSize
allChunkHandles = allChunks[startChunk:endChunk+1]
ret = []
for idx, chunkHandle in enumerate(allChunkHandles):
if idx == 0:
stof = startOffset
else:
stof = 0
if idx == len(allChunkHandles) - 1:
enof = endOffset
else:
enof = Config.chunkSize - 1
loc = self.files[filePath].chunks[chunkHandle].locs[0]
ret.append(chunkHandle + "*" + loc + "*" + str(stof) + "*" + str(enof - stof + 1))
ret = "|".join(ret)
return Status(0, ret)
def deleteFile(self, filePath):
if filePath not in self.files:
return Status(-1, "ERROR: file {} doesn't exist".format(filePath))
chunksToDel = []
for handle, chunk in self.files[filePath].chunks.items():
for loc in chunk.locs:
self.loadBalancer.decreaseLoad(loc)
os.remove(os.path.join(Config.rootDir, os.path.join(loc, handle)))
chunksToDel.append(chunk)
for chunk in chunksToDel:
del chunk
del self.files[filePath]
return Status(0, "SUCCESS: file {} is deleted".format(filePath))
class MasterServicer(gfs_pb2_grpc.MasterServicer):
def __init__(self, master):
self.master = master
def ListFiles(self, request, context):
filePath = request.st
print("Command List {}".format(filePath))
fpls = self.master.listFiles(filePath)
st = "|".join(fpls)
return gfs_pb2.String(st=st)
def CreateFile(self, request, context):
filePath = request.st
print("Command Create {}".format(filePath))
chunkHandle, locs, status = self.master.createFile(filePath)
if status.v != 0:
return gfs_pb2.String(st=status.e)
st = chunkHandle + "|" + "|".join(locs)
return gfs_pb2.String(st=st)
def AppendFile(self, request, context):
filePath = request.st
print("Command Append {}".format(filePath))
latestChunkHandle, locs, status = self.master.appendFile(filePath)
if status.v != 0:
return gfs_pb2.String(st=status.e)
chunkRemSpace, status = self.master.getChunkSpace(filePath)
if status.v != 0:
return gfs_pb2.String(st=status.e)
st = chunkRemSpace + "|"+ latestChunkHandle + "|" + "|".join(locs)
return gfs_pb2.String(st=st)
def CreateChunk(self, request, context):
filePath, prevChunkHandle = request.st.split("|")
print("Command CreateChunk {} {}".format(filePath, prevChunkHandle))
chunkHandle, locs, status = self.master.createChunk(filePath, prevChunkHandle)
st = chunkHandle + "|" + "|".join(locs)
return gfs_pb2.String(st=st)
def ReadFile(self, request, context):
filePath, offset, numbytes = request.st.split("|")
print("Command ReadFile {} {} {}".format(filePath, offset, numbytes))
status = self.master.readFile(filePath, int(offset), int(numbytes))
return gfs_pb2.String(st=status.e)
def DeleteFile(self, request, context):
filePath = request.st
print("Command Delete {}".format(filePath))
status = self.master.deleteFile(filePath)
return gfs_pb2.String(st=status.e)
def serve():
master = MasterServer()
server = grpc.server(futures.ThreadPoolExecutor(max_workers=3))
gfs_pb2_grpc.add_MasterServicer_to_server(MasterServicer(master=master), server)
server.add_insecure_port('[::]:'+Config.masterLoc)
server.start()
print('Master serving at '+Config.masterLoc)
try:
while True:
time.sleep(2000)
except KeyboardInterrupt:
server.stop(0)
if __name__ == "__main__":
serve()