This repository has been archived by the owner on Apr 13, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hdfs.py
executable file
·406 lines (321 loc) · 9.51 KB
/
hdfs.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
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
#!/usr/bin/python
# -*- coding: : utf-8 -*-
import logging
import struct
from urlparse import urlparse
from tornado import gen
from tornado.ioloop import IOLoop
from tornado.tcpclient import TCPClient
from nonblocking import HadoopRPC
from nonblocking import MultiRPC
from nonblocking import ProtocolBuffer
from streams import BufferedStream
from streams import ClosableStream
from streams import SwitchableStream
from gen import ClientNamenodeProtocol_pb2
from gen import datatransfer_pb2
class Namenode(MultiRPC):
def __init__(self,hosts):
super(Namenode,self).__init__(hosts)
self._protocol = 'org.apache.hadoop.hdfs.protocol.ClientProtocol'
def ha_switching(self,response):
if super(Namenode,self).ha_switching(response):
return True
ok,response = response
if not ok and response.exceptionClassName == 'org.apache.hadoop.ipc.StandbyException':
logging.info('namenode ha switch...')
return True
return False
@gen.coroutine
def file_info(self,path):
request = ClientNamenodeProtocol_pb2.GetFileInfoRequestProto()
request.src = path
response = ClientNamenodeProtocol_pb2.GetFileInfoResponseProto()
ok,response = yield self.call(
self._protocol,
'getFileInfo',
request,
response,
)
if ok and response.fs.fileId != 0:
raise gen.Return(response)
raise gen.Return(None)
@gen.coroutine
def blocks(self,path,offset,length):
request = ClientNamenodeProtocol_pb2.GetBlockLocationsRequestProto()
request.src = path
request.offset = offset
request.length = length
response = ClientNamenodeProtocol_pb2.GetBlockLocationsResponseProto()
ok,response = yield self.call(
self._protocol,
'getBlockLocations',
request,
response,
)
raise gen.Return(response if ok else None)
@gen.coroutine
def list_dirs(self,path,after_child='',location=False):
request = ClientNamenodeProtocol_pb2.GetListingRequestProto()
request.src = path
request.startAfter = after_child
request.needLocation = location
response = ClientNamenodeProtocol_pb2.GetListingResponseProto()
ok,response = yield self.call(
self._protocol,
'getListing',
request,
response,
)
raise gen.Return(response if ok else None)
@gen.coroutine
def list_dirs_all(self,path,each,location=False):
after_child = ''
while True:
response = yield self.list_dirs(path,after_child,False)
if response is None:
break
# gen child
for entry in response.dirList.partialListing:
# update last
after_child = entry.path
yield each(entry)
# more?
if response.dirList.remainingEntries <= 0:
break
@gen.coroutine
def mkdirs(self,path,permission=0x777):
request = ClientNamenodeProtocol_pb2.MkdirsRequestProto()
request.src = path
request.createParent = True
request.masked.perm = permission
response = ClientNamenodeProtocol_pb2.MkdirsResponseProto()
ok,response = yield self.call(
self._protocol,
'mkdirs',
request,
response,
)
raise gen.Return(response if ok else None)
@gen.coroutine
def move(self,source,destination,force=False):
request = ClientNamenodeProtocol_pb2.Rename2RequestProto()
request.src = source
request.dst = destination
request.moveToTrash = True
request.overwriteDest = force
response = ClientNamenodeProtocol_pb2.Rename2ResponseProto()
ok,response = yield self.call(
self._protocol,
'rename2',
request,
response,
)
if not ok:
logging.warn(response)
raise gen.Return(response if ok else None)
@gen.coroutine
def stream(self,path):
file_info = yield self.file_info(path)
blocks = [ x for x in (yield self.blocks(path,0,file_info.fs.length)).locations.blocks ]
blocks.sort(key=lambda x:x.offset,reverse=True)
def next_stream(this,current):
if current is not None:
current.close()
# pop one
block = blocks.pop()
# build datanode
hosts = map(
lambda x:(x.id.ipAddr,x.id.xferPort),
block.locs,
)
lazy_stream = lambda host,block: \
lambda : Datanode(host).stream({
'block' : block.b.blockId,
'pool' : block.b.poolId,
'timestamp' : block.b.generationStamp,
'length' : block.b.numBytes,
'offset' : 0,
})
return SwitchableStream(map(
(lambda block: \
lambda host:
lazy_stream(host,block)
)(block),
hosts,
))
raise gen.Return(_BoundedMultiStream(
None,
file_info.fs.length,
next_stream,
))
class Namenodes(object):
def __init__(self,namenodes):
super(Namenodes,self).__init__()
self._namenodes = namenodes
def resolve(self,path):
path = urlparse(path)
if path.scheme != 'hdfs':
return None
name_service = path.netloc.split(':')[0]
namenode = self._namenodes.get(name_service,None)
if namenode is None:
return None
return namenode
class Datanode(ProtocolBuffer):
def __init__(self,host):
super(Datanode,self).__init__()
self._host = host
self._ioloop = None
def _op(self,op):
return ''.join([
struct.pack('!H',28), # transfer protocol version
struct.pack('!B',op),
])
@gen.coroutine
def stream(self,block):
logging.info('connect to:%s fetch blcok:%s' % (self._host,block))
# send op
op = self._op(81) # org.apache.hadoop.hdfs.protocol.datatransfer.Op#READ_BLOCK
# then payload
payload = datatransfer_pb2.OpReadBlockProto()
payload.offset = block['offset']
payload.len = block['length']
payload.sendChecksums = False
payload.header.clientName = HadoopRPC.CLIENT_ID
payload.header.baseHeader.block.poolId = block['pool']
payload.header.baseHeader.block.blockId = block['block']
payload.header.baseHeader.block.generationStamp = block['timestamp']
# send request
content = ''.join([
op,
self.wrap(payload)
])
stream = None
try:
# establish connection
ioloop = self._ioloop if self._ioloop is not None else IOLoop.current()
stream = BufferedStream((yield TCPClient(io_loop=ioloop).connect(*self._host)))
# send reqeust
yield stream.write(content)
# read response length
partial = yield stream.peek(4)
response_length,offset = self.read_varint32(partial,0)
yield stream.read(offset)
# parse response
response = datatransfer_pb2.BlockOpResponseProto()
response.ParseFromString((yield stream.read(response_length)))
# check status
if response.status != datatransfer_pb2.SUCCESS:
raise IOError('read block %s fail: %s' % (
block,
response,
))
raise gen.Return(
_BlockStream(
self,
block,
stream,
lambda self,_:_PacketStream(self.stream()),
)
)
except gen.Return as result:
raise result
except:
logging.exception('unexpected io excetion,close stream for%s'%(
str(self._host),
))
stream.close()
class _PacketStream(ClosableStream):
def __init__(self,buffered_stream):
super(_PacketStream,self).__init__(buffered_stream)
self._inited = False
self._remainds = 0
@gen.coroutine
def read(self,hint):
if not self._inited:
yield self._init()
if self._remainds == 0:
raise gen.Return(None)
# correct hint
if self._remainds < hint:
hint = self._remainds
content = yield self.stream().read(hint)
self._remainds -= len(content)
raise gen.Return(content)
@gen.coroutine
def _init(self):
stream = self.stream()
partial = yield stream.read(6)
payload_length = struct.unpack('!I',partial[:4])[0]
header_length = struct.unpack('!H',partial[4:])[0]
# parse header
header = datatransfer_pb2.PacketHeaderProto()
header.ParseFromString((yield stream.read(header_length)))
# calculate checksum length
checksum_length = payload_length - 4 - header.dataLen
# skip checksum
yield stream.read(checksum_length)
self._remainds = header.dataLen
# flag it
self._inited = True
class _BoundedMultiStream(ClosableStream):
def __init__(self,buffered_stream,logical_length,next_stream=None):
super(_BoundedMultiStream,self).__init__(buffered_stream)
self._remainds = logical_length
self._current = None
# with argument (self,current_stream)
self._next_stream = next_stream
@gen.coroutine
def read(self,hint):
# no more
if self._remainds == 0:
raise gen.Return(None)
# any packet?
if self._current is None:
current = self._next_stream(self,self._current)
# check if is future
# a bit ugly and tricky
if isinstance(current,gen.Future):
current = yield current
self._current = current
# do read
content = yield self._current.read(hint)
# end of packet?
if content is None:
self._current = None
# drill down
raise gen.Return((yield self.read(hint)))
# did read something,update trackers
self._remainds -= len(content)
raise gen.Return(content)
def limit(self,logical_length):
self._remainds = logical_length
def remainds(self):
return self._remainds
class _BlockStream(_BoundedMultiStream):
def __init__(self,datanode,block,buffered_stream,next_stream=None):
super(_BlockStream,self).__init__(buffered_stream,block['length'],next_stream)
# copy config
self._block = dict(block)
self._datanode = datanode
@gen.coroutine
def seek(self,offset):
current = self.stream()
if current is not None:
current.close()
# update block info
block = self._block
block['length'] = block['length'] - (offset - block['offset'])
block['offset'] = offset
self._block = block
# reconnect
block_stream = yield self._datanode.stream(self._block)
# steal it
current = block_stream.stream()
# switch
block_stream.switch(None)
block_stream.close()
self.switch(current)
# update limit
self.limit(self._block['length'] - offset)