This repository has been archived by the owner on Apr 19, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 216
/
client.py
1580 lines (1330 loc) · 66.2 KB
/
client.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
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# Copyright (c) 2013 Spotify AB
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
import snakebite.protobuf.ClientNamenodeProtocol_pb2 as client_proto
import snakebite.glob as glob
from snakebite.platformutils import get_current_username
from snakebite.channel import DataXceiverChannel
from snakebite.config import HDFSConfig
from snakebite.errors import (
ConnectionFailureException,
DirectoryException,
FileAlreadyExistsException,
FileException,
FileNotFoundException,
InvalidInputException,
OutOfNNException,
RequestError,
FatalException, TransientException)
from snakebite.namenode import Namenode
from snakebite.service import RpcService
import Queue
import zlib
import bz2
import logging
import os
import os.path
import posixpath
import fnmatch
import inspect
import socket
import errno
import time
import re
import sys
import random
if sys.version_info[0] == 3:
long = int
log = logging.getLogger(__name__)
class Client(object):
''' A pure python HDFS client.
**Example:**
>>> from snakebite.client import Client
>>> client = Client("localhost", 8020, use_trash=False)
>>> for x in client.ls(['/']):
... print x
.. warning::
Many methods return generators, which mean they need to be consumed to execute! Documentation will explicitly
specify which methods return generators.
.. note::
``paths`` parameters in methods are often passed as lists, since operations can work on multiple
paths.
.. note::
Parameters like ``include_children`` and ``recurse`` are not used
when paths contain globs.
.. note::
Different Hadoop distributions use different protocol versions. Snakebite defaults to 9, but this can be set by passing
in the ``hadoop_version`` parameter to the constructor.
'''
FILETYPES = {
1: "d",
2: "f",
3: "s"
}
def __init__(self, host, port=Namenode.DEFAULT_PORT, hadoop_version=Namenode.DEFAULT_VERSION,
use_trash=False, effective_user=None, use_sasl=False, hdfs_namenode_principal=None,
sock_connect_timeout=10000, sock_request_timeout=10000):
'''
:param host: Hostname or IP address of the NameNode
:type host: string
:param port: RPC Port of the NameNode
:type port: int
:param hadoop_version: What hadoop protocol version should be used (default: 9)
:type hadoop_version: int
:param use_trash: Use a trash when removing files.
:type use_trash: boolean
:param effective_user: Effective user for the HDFS operations (default: None - current user)
:type effective_user: string
:param use_sasl: Use SASL authentication or not
:type use_sasl: boolean
:param hdfs_namenode_principal: Kerberos principal to use for HDFS
:type hdfs_namenode_principal: string
:param sock_connect_timeout: Socket connection timeout in seconds
:type sock_connect_timeout: int
:param sock_request_timeout: Request timeout in seconds
:type sock_request_timeout: int
'''
if hadoop_version < 9:
raise FatalException("Only protocol versions >= 9 supported")
self.host = host
self.port = port
self.use_sasl = use_sasl
self.hdfs_namenode_principal = hdfs_namenode_principal
self.service_stub_class = client_proto.ClientNamenodeProtocol_Stub
self.service = RpcService(self.service_stub_class, self.port, self.host, hadoop_version,
effective_user,self.use_sasl, self.hdfs_namenode_principal,
sock_connect_timeout, sock_request_timeout)
self.use_trash = use_trash
self.trash = self._join_user_path(".Trash")
self._server_defaults = None
log.debug("Created client for %s:%s with trash=%s and sasl=%s" % (host, port, use_trash, use_sasl))
def ls(self, paths, recurse=False, include_toplevel=False, include_children=True):
''' Issues 'ls' command and returns a list of maps that contain fileinfo
:param paths: Paths to list
:type paths: list
:param recurse: Recursive listing
:type recurse: boolean
:param include_toplevel: Include the given path in the listing. If the path is a file, include_toplevel is always True.
:type include_toplevel: boolean
:param include_children: Include child nodes in the listing.
:type include_children: boolean
:returns: a generator that yields dictionaries
**Examples:**
Directory listing
>>> list(client.ls(["/"]))
[{'group': u'supergroup', 'permission': 420, 'file_type': 'f', 'access_time': 1367317324982L, 'block_replication': 1, 'modification_time': 1367317325346L, 'length': 6783L, 'blocksize': 134217728L, 'owner': u'wouter', 'path': '/Makefile'}, {'group': u'supergroup', 'permission': 493, 'file_type': 'd', 'access_time': 0L, 'block_replication': 0, 'modification_time': 1367317325431L, 'length': 0L, 'blocksize': 0L, 'owner': u'wouter', 'path': '/build'}, {'group': u'supergroup', 'permission': 420, 'file_type': 'f', 'access_time': 1367317326510L, 'block_replication': 1, 'modification_time': 1367317326522L, 'length': 100L, 'blocksize': 134217728L, 'owner': u'wouter', 'path': '/index.asciidoc'}, {'group': u'supergroup', 'permission': 493, 'file_type': 'd', 'access_time': 0L, 'block_replication': 0, 'modification_time': 1367317326628L, 'length': 0L, 'blocksize': 0L, 'owner': u'wouter', 'path': '/source'}]
File listing
>>> list(client.ls(["/Makefile"]))
[{'group': u'supergroup', 'permission': 420, 'file_type': 'f', 'access_time': 1367317324982L, 'block_replication': 1, 'modification_time': 1367317325346L, 'length': 6783L, 'blocksize': 134217728L, 'owner': u'wouter', 'path': '/Makefile'}]
Get directory information
>>> list(client.ls(["/source"], include_toplevel=True, include_children=False))
[{'group': u'supergroup', 'permission': 493, 'file_type': 'd', 'access_time': 0L, 'block_replication': 0, 'modification_time': 1367317326628L, 'length': 0L, 'blocksize': 0L, 'owner': u'wouter', 'path': '/source'}]
'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
for item in self._find_items(paths, self._handle_ls,
include_toplevel=include_toplevel,
include_children=include_children,
recurse=recurse):
if item:
yield item
LISTING_ATTRIBUTES = ['length', 'owner', 'group', 'block_replication',
'modification_time', 'access_time', 'blocksize']
def _handle_ls(self, path, node):
''' Handle every node received for an ls request'''
entry = {}
entry["file_type"] = self.FILETYPES[node.fileType]
entry["permission"] = node.permission.perm
entry["path"] = path
for attribute in self.LISTING_ATTRIBUTES:
entry[attribute] = node.__getattribute__(attribute)
return entry
def chmod(self, paths, mode, recurse=False):
''' Change the mode for paths. This returns a list of maps containing the resut of the operation.
:param paths: List of paths to chmod
:type paths: list
:param mode: Octal mode (e.g. 0o755)
:type mode: int
:param recurse: Recursive chmod
:type recurse: boolean
:returns: a generator that yields dictionaries
.. note:: The top level directory is always included when `recurse=True`'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
if not paths:
raise InvalidInputException("chmod: no path given")
if not mode:
raise InvalidInputException("chmod: no mode given")
processor = lambda path, node, mode=mode: self._handle_chmod(path, node, mode)
for item in self._find_items(paths, processor, include_toplevel=True,
include_children=False, recurse=recurse):
if item:
yield item
def _handle_chmod(self, path, node, mode):
request = client_proto.SetPermissionRequestProto()
request.src = path
request.permission.perm = mode
self.service.setPermission(request)
return {"result": True, "path": path}
def chown(self, paths, owner, recurse=False):
''' Change the owner for paths. The owner can be specified as `user` or `user:group`
:param paths: List of paths to chmod
:type paths: list
:param owner: New owner
:type owner: string
:param recurse: Recursive chown
:type recurse: boolean
:returns: a generator that yields dictionaries
This always include the toplevel when recursing.'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
if not paths:
raise InvalidInputException("chown: no path given")
if not owner:
raise InvalidInputException("chown: no owner given")
processor = lambda path, node, owner=owner: self._handle_chown(path, node, owner)
for item in self._find_items(paths, processor, include_toplevel=True,
include_children=False, recurse=recurse):
if item:
yield item
def _handle_chown(self, path, node, owner):
if ":" in owner:
(owner, group) = owner.split(":")
else:
group = ""
request = client_proto.SetOwnerRequestProto()
request.src = path
if owner:
request.username = owner
if group:
request.groupname = group
self.service.setOwner(request)
return {"result": True, "path": path}
def chgrp(self, paths, group, recurse=False):
''' Change the group of paths.
:param paths: List of paths to chgrp
:type paths: list
:param group: New group
:type mode: string
:param recurse: Recursive chgrp
:type recurse: boolean
:returns: a generator that yields dictionaries
'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
if not paths:
raise InvalidInputException("chgrp: no paths given")
if not group:
raise InvalidInputException("chgrp: no group given")
owner = ":%s" % group
processor = lambda path, node, owner=owner: self._handle_chown(path, node, owner)
for item in self._find_items(paths, processor, include_toplevel=True,
include_children=False, recurse=recurse):
if item:
yield item
def count(self, paths):
''' Count files in a path
:param paths: List of paths to count
:type paths: list
:returns: a generator that yields dictionaries
**Examples:**
>>> list(client.count(['/']))
[{'spaceConsumed': 260185L, 'quota': 2147483647L, 'spaceQuota': 18446744073709551615L, 'length': 260185L, 'directoryCount': 9L, 'path': '/', 'fileCount': 34L}]
'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
if not paths:
raise InvalidInputException("count: no path given")
for item in self._find_items(paths, self._handle_count, include_toplevel=True,
include_children=False, recurse=False):
if item:
yield item
COUNT_ATTRIBUTES = ['length', 'fileCount', 'directoryCount', 'quota', 'spaceConsumed', 'spaceQuota']
def _handle_count(self, path, node):
request = client_proto.GetContentSummaryRequestProto()
request.path = path
response = self.service.getContentSummary(request)
entry = {"path": path}
for attribute in self.COUNT_ATTRIBUTES:
entry[attribute] = response.summary.__getattribute__(attribute)
return entry
def df(self):
''' Get FS information
:returns: a dictionary
**Examples:**
>>> client.df()
{'used': 491520L, 'capacity': 120137519104L, 'under_replicated': 0L, 'missing_blocks': 0L, 'filesystem': 'hdfs://localhost:8020', 'remaining': 19669295104L, 'corrupt_blocks': 0L}
'''
processor = lambda path, node: self._handle_df(path, node)
return list(self._find_items(['/'], processor, include_toplevel=True, include_children=False, recurse=False))[0]
def _handle_df(self, path, node):
request = client_proto.GetFsStatusRequestProto()
response = self.service.getFsStats(request)
entry = {"filesystem": "hdfs://%s:%d" % (self.host, self.port)}
for i in ['capacity', 'used', 'remaining', 'under_replicated',
'corrupt_blocks', 'missing_blocks']:
entry[i] = response.__getattribute__(i)
return entry
def du(self, paths, include_toplevel=False, include_children=True):
'''Returns size information for paths
:param paths: Paths to du
:type paths: list
:param include_toplevel: Include the given path in the result. If the path is a file, include_toplevel is always True.
:type include_toplevel: boolean
:param include_children: Include child nodes in the result.
:type include_children: boolean
:returns: a generator that yields dictionaries
**Examples:**
Children:
>>> list(client.du(['/']))
[{'path': '/Makefile', 'length': 6783L}, {'path': '/build', 'length': 244778L}, {'path': '/index.asciidoc', 'length': 100L}, {'path': '/source', 'length': 8524L}]
Directory only:
>>> list(client.du(['/'], include_toplevel=True, include_children=False))
[{'path': '/', 'length': 260185L}]
'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
if not paths:
raise InvalidInputException("du: no path given")
processor = lambda path, node: self._handle_du(path, node)
for item in self._find_items(paths, processor, include_toplevel=include_toplevel,
include_children=include_children, recurse=False):
if item:
yield item
def _handle_du(self, path, node):
if self._is_dir(node):
request = client_proto.GetContentSummaryRequestProto()
request.path = path
try:
response = self.service.getContentSummary(request)
return {"path": path, "length": response.summary.length}
except RequestError as e:
print(e)
else:
return {"path": path, "length": node.length}
def rename(self, paths, dst):
''' Rename (move) path(s) to a destination
:param paths: Source paths
:type paths: list
:param dst: destination
:type dst: string
:returns: a generator that yields dictionaries
'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
if not paths:
raise InvalidInputException("rename: no path given")
if not dst:
raise InvalidInputException("rename: no destination given")
processor = lambda path, node, dst=dst: self._handle_rename(path, node, dst)
for item in self._find_items(paths, processor, include_toplevel=True):
if item:
yield item
def _handle_rename(self, path, node, dst):
if not dst.startswith("/"):
dst = self._join_user_path(dst)
dst = self._normalize_path(dst)
request = client_proto.RenameRequestProto()
request.src = path
request.dst = dst
response = self.service.rename(request)
return {"path": path, "result": response.result}
def rename2(self, path, dst, overwriteDest=False):
''' Rename (but don't move) path to a destination
By only renaming, we mean that you can't move a file or folder out or
in other folder. The renaming can only happen within the folder the
file or folder lies in.
Note that this operation "always succeeds" unless an exception is
raised, hence, the dict returned from this function doesn't have the
'result' key.
Since you can't move with this operation, and only rename, it would
not make sense to pass multiple paths to rename to a single
destination. This method uses the underlying rename2 method.
https://github.com/apache/hadoop/blob/ae91b13/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/protocol/ClientProtocol.java#L483-L523
Out of all the different exceptions mentioned in the link above, this
method only wraps the FileAlreadyExistsException exception. You will
also get a FileAlreadyExistsException if you have overwriteDest=True
and the destination folder is not empty. The other exceptions will just
be passed along.
:param path: Source path
:type path: string
:param dst: destination
:type dst: string
:returns: A dictionary or None
'''
if not path:
raise InvalidInputException("rename2: no path given")
if not dst:
raise InvalidInputException("rename2: no destination given")
if not isinstance(path, (str, unicode)):
raise InvalidInputException("rename2: Path should be a string")
processor = lambda path, node, dst=dst, overwriteDest=overwriteDest: self._handle_rename2(path, node, dst, overwriteDest)
for item in self._find_items([path], processor, include_toplevel=True):
return item
def _handle_rename2(self, path, node, dst, overwriteDest):
if not dst.startswith("/"):
dst = self._join_user_path(dst)
# Strip the last / if there is one. Hadoop doesn't like this
if dst.endswith("/"):
dst = dst[:-1]
request = client_proto.Rename2RequestProto()
request.src = path
request.dst = dst
request.overwriteDest = overwriteDest
try:
self.service.rename2(request)
except RequestError as ex:
if ("FileAlreadyExistsException" in str(ex) or
"rename destination directory is not empty" in str(ex)):
raise FileAlreadyExistsException(ex)
else:
raise
return {"path": path}
def delete(self, paths, recurse=False):
''' Delete paths
:param paths: Paths to delete
:type paths: list
:param recurse: Recursive delete (use with care!)
:type recurse: boolean
:returns: a generator that yields dictionaries
.. note:: Recursive deletion uses the NameNode recursive deletion functionality
instead of letting the client recurse. Hadoops client recurses
by itself and thus showing all files and directories that are
deleted. Snakebite doesn't.
'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
if not paths:
raise InvalidInputException("delete: no path given")
processor = lambda path, node, recurse=recurse: self._handle_delete(path, node, recurse)
for item in self._find_items(paths, processor, include_toplevel=True):
if item:
yield item
def _handle_delete(self, path, node, recurse):
if (self._is_dir(node) and not recurse):
raise DirectoryException("rm: `%s': Is a directory" % path)
# None might be passed in for recurse
if not recurse:
recurse = False
if self.__should_move_to_trash(path):
if path.endswith("/"):
suffix_path = path[1:-1]
else:
suffix_path = path[1:]
trash_path = posixpath.join(self.trash, "Current", suffix_path)
if trash_path.endswith("/"):
trash_path = trash_path[:-1]
base_trash_path = posixpath.join(self.trash, "Current", posixpath.dirname(suffix_path))
if base_trash_path.endswith("/"):
base_trash_path = base_trash_path[:-1]
# Try twice, in case checkpoint between mkdir() and rename()
for i in range(0, 2):
list(self.mkdir([base_trash_path], create_parent=True, mode=0o700))
original_path = trash_path
while self.test(trash_path, exists=True):
unix_timestamp = str(int(time.time() * 1000))
trash_path = "%s%s" % (original_path, unix_timestamp)
result = self._handle_rename(path, node, trash_path)
if result['result']:
result['message'] = ". Moved %s to %s" % (path, trash_path)
return result
raise FatalException("Failed to move to trash: %s" % path)
else:
request = client_proto.DeleteRequestProto()
request.src = path
request.recursive = recurse
response = self.service.delete(request)
return {"path": path, "result": response.result}
def __should_move_to_trash(self, path):
if not self.use_trash:
return False
if path.startswith(self.trash):
return False # Path already in trash
if posixpath.dirname(self.trash).startswith(path):
raise FatalException("Cannot move %s to the trash, as it contains the trash" % path)
return True
def rmdir(self, paths):
''' Delete a directory
:param paths: Paths to delete
:type paths: list
:returns: a generator that yields dictionaries
.. note: directories have to be empty.
'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
if not paths:
raise InvalidInputException("rmdir: no path given")
processor = lambda path, node: self._handle_rmdir(path, node)
for item in self._find_items(paths, processor, include_toplevel=True):
if item:
yield item
def _handle_rmdir(self, path, node):
if not self._is_dir(node):
raise DirectoryException("rmdir: `%s': Is not a directory" % path)
# Check if the directory is empty
files = self.ls([path])
if len(list(files)) > 0:
raise DirectoryException("rmdir: `%s': Directory is not empty" % path)
return self._handle_delete(path, node, recurse=True)
def touchz(self, paths, replication=None, blocksize=None):
''' Create a zero length file or updates the timestamp on a zero length file
:param paths: Paths
:type paths: list
:param replication: Replication factor
:type recurse: int
:param blocksize: Block size (in bytes) of the newly created file
:type blocksize: int
:returns: a generator that yields dictionaries
'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
if not paths:
raise InvalidInputException("touchz: no path given")
# Let's get the blocksize and replication from the server defaults
# provided by the namenode if they are not specified
if not replication or not blocksize:
defaults = self.serverdefaults()
if not replication:
replication = defaults['replication']
if not blocksize:
blocksize = defaults['blockSize']
processor = lambda path, node, replication=replication, blocksize=blocksize: self._handle_touchz(path, node, replication, blocksize)
for item in self._find_items(paths, processor, include_toplevel=True, check_nonexistence=True, include_children=False):
if item:
yield item
def _handle_touchz(self, path, node, replication, blocksize):
# Item already exists
if node:
if node.length != 0:
raise FileException("touchz: `%s': Not a zero-length file" % path)
if self._is_dir(node):
raise DirectoryException("touchz: `%s': Is a directory" % path)
response = self._create_file(path, replication, blocksize, overwrite=True)
else:
# Check if the parent directory exists
parent = self._get_file_info(posixpath.dirname(path))
if not parent:
raise DirectoryException("touchz: `%s': No such file or directory" % path)
else:
response = self._create_file(path, replication, blocksize, overwrite=False)
return {"path": path, "result": response.result}
def setrep(self, paths, replication, recurse=False):
''' Set the replication factor for paths
:param paths: Paths
:type paths: list
:param replication: Replication factor
:type recurse: int
:param recurse: Apply replication factor recursive
:type recurse: boolean
:returns: a generator that yields dictionaries
'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
if not paths:
raise InvalidInputException("setrep: no path given")
if not replication:
raise InvalidInputException("setrep: no replication given")
processor = lambda path, node, replication=replication: self._handle_setrep(path, node, replication)
for item in self._find_items(paths, processor, include_toplevel=True,
include_children=False, recurse=recurse):
if item:
yield item
def _handle_setrep(self, path, node, replication):
if not self._is_dir(node):
request = client_proto.SetReplicationRequestProto()
request.src = path
request.replication = replication
response = self.service.setReplication(request)
return {"result": response.result, "path": path}
def cat(self, paths, check_crc=False):
''' Fetch all files that match the source file pattern
and display their content on stdout.
:param paths: Paths to display
:type paths: list of strings
:param check_crc: Check for checksum errors
:type check_crc: boolean
:returns: a generator that yields strings
'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
if not paths:
raise InvalidInputException("cat: no path given")
processor = lambda path, node, check_crc=check_crc: self._handle_cat(path, node, check_crc)
for item in self._find_items(paths, processor, include_toplevel=True,
include_children=False, recurse=False):
if item:
yield item
def _handle_cat(self, path, node, check_crc):
if self._is_dir(node):
raise DirectoryException("cat: `%s': Is a directory" % path)
for load in self._read_file(path, node, False, check_crc):
if load:
yield load
def copyToLocal(self, paths, dst, check_crc=False):
''' Copy files that match the file source pattern
to the local name. Source is kept. When copying multiple,
files, the destination must be a directory.
:param paths: Paths to copy
:type paths: list of strings
:param dst: Destination path
:type dst: string
:param check_crc: Check for checksum errors
:type check_crc: boolean
:returns: a generator that yields strings
'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
if not paths:
raise InvalidInputException("copyToLocal: no path given")
if not dst:
raise InvalidInputException("copyToLocal: no destination given")
dst = self._normalize_path(dst)
processor = lambda path, node, dst=dst, check_crc=check_crc: self._handle_copyToLocal(path, node, dst, check_crc)
for path in paths:
self.base_source = None
for item in self._find_items([path], processor, include_toplevel=True, recurse=True, include_children=True):
if item:
yield item
def _handle_copyToLocal(self, path, node, dst, check_crc):
# _handle_copyToLocal makes sense only per on dir tree
# with common base_source
dst = os.path.abspath(dst)
if not self.base_source:
# base_source is shared for whole dir tree, and can
# be computed only once per dir tree
self.base_source = posixpath.dirname(path)
self.base_source = self.base_source if self.base_source.endswith("/") else self.base_source + "/"
# If input destination is an existing directory, include toplevel
if os.path.isdir(dst):
local_prefix = path.replace(self.base_source, "", 1)
target = os.path.join(dst, local_prefix)
else:
target = dst
error = ""
result = False
# Target is an existing file
if os.path.isfile(target):
error += "file exists"
# Target is an existing directory
elif os.path.isdir(target):
error += "directory exists"
# Source is a directory
elif self._is_dir(node):
os.makedirs(target, mode=node.permission.perm)
result = True
# Source is a file
elif self._is_file(node):
temporary_target = "%s._COPYING_" % target
f = open(temporary_target, 'wb')
try:
for load in self._read_file(path, node, tail_only=False, check_crc=check_crc):
f.write(load)
f.close()
os.rename(temporary_target, target)
result = True
except Exception as e:
result = False
error = e
if os.path.isfile(temporary_target):
os.remove(temporary_target)
return {"path": target, "result": result, "error": error, "source_path": path}
def getmerge(self, path, dst, newline=False, check_crc=False):
''' Get all the files in the directories that
match the source file pattern and merge and sort them to only
one file on local fs.
:param paths: Directory containing files that will be merged
:type paths: string
:param dst: Path of file that will be written
:type dst: string
:param nl: Add a newline character at the end of each file.
:type nl: boolean
:returns: string content of the merged file at dst
'''
if not path:
raise InvalidInputException("getmerge: no path given")
if not dst:
raise InvalidInputException("getmerge: no destination given")
temporary_target = "%s._COPYING_" % dst
f = open(temporary_target, 'w')
processor = lambda path, node, dst=dst, check_crc=check_crc: self._handle_getmerge(path, node, dst, check_crc)
try:
for item in self._find_items([path], processor, include_toplevel=True, recurse=False, include_children=True):
for load in item:
if load['result']:
f.write(load['response'])
elif not load['error'] is '':
if os.path.isfile(temporary_target):
os.remove(temporary_target)
raise FatalException(load['error'])
if newline and load['response']:
f.write("\n")
yield {"path": dst, "response": '', "result": True, "error": load['error'], "source_path": path}
finally:
if os.path.isfile(temporary_target):
f.close()
os.rename(temporary_target, dst)
def _handle_getmerge(self, path, node, dst, check_crc):
log.debug("in handle getmerge")
dst = self._normalize_path(dst)
error = ''
if not self._is_file(node):
# Target is an existing file
if os.path.isfile(dst):
error += "target file exists"
# Target is an existing directory
elif os.path.isdir(dst):
error += "target directory exists"
yield {"path": path, "response": '', "result": False, "error": error, "source_path": path}
# Source is a file
else:
if node.length == 0: # Empty file
yield {"path": path, "response": '', "result": True, "error": error, "source_path": path}
else:
try:
for load in self._read_file(path, node, tail_only=False, check_crc=check_crc):
yield {"path": path, "response": load, "result": True, "error": error, "source_path": path}
except Exception as e:
error = e
yield {"path": path, "response": '', "result": False, "error": error, "source_path": path}
def stat(self, paths):
''' Stat a fileCount
:param paths: Path
:type paths: string
:returns: a dictionary
**Example:**
>>> client.stat(['/index.asciidoc'])
{'blocksize': 134217728L, 'owner': u'wouter', 'length': 100L, 'access_time': 1367317326510L, 'group': u'supergroup', 'permission': 420, 'file_type': 'f', 'path': '/index.asciidoc', 'modification_time': 1367317326522L, 'block_replication': 1}
'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
if not paths:
raise InvalidInputException("stat: no path given")
processor = lambda path, node: self._handle_stat(path, node)
return list(self._find_items(paths, processor, include_toplevel=True))[0]
def _handle_stat(self, path, node):
return {"path": path,
"file_type": self.FILETYPES[node.fileType],
"length": node.length,
"permission": node.permission.perm,
"owner": node.owner,
"group": node.group,
"modification_time": node.modification_time,
"access_time": node.access_time,
"block_replication": node.block_replication,
"blocksize": node.blocksize}
def tail(self, path, tail_length=1024, append=False):
# Note: append is currently not implemented.
''' Show the end of the file - default 1KB, supports up to the Hadoop block size.
:param path: Path to read
:type path: string
:param tail_length: The length to read from the end of the file - default 1KB, up to block size.
:type tail_length: int
:param append: Currently not implemented
:type append: bool
:returns: a generator that yields strings
'''
#TODO: Make tail support multiple files at a time, like most other methods do
if not path:
raise InvalidInputException("tail: no path given")
block_size = self.serverdefaults()['blockSize']
if tail_length > block_size:
raise InvalidInputException("tail: currently supports length up to the block size (%d)" % (block_size,))
if tail_length <= 0:
raise InvalidInputException("tail: tail_length cannot be less than or equal to zero")
processor = lambda path, node: self._handle_tail(path, node, tail_length, append)
for item in self._find_items([path], processor, include_toplevel=True,
include_children=False, recurse=False):
if item:
yield item
def _handle_tail(self, path, node, tail_length, append):
data = ''
for load in self._read_file(path, node, tail_only=True, check_crc=False, tail_length=tail_length):
data += load
# We read only the necessary packets but still
# need to cut off at the packet level.
return data[max(0, len(data)-tail_length):len(data)]
def test(self, path, exists=False, directory=False, zero_length=False):
'''Test if a path exist, is a directory or has zero length
:param path: Path to test
:type path: string
:param exists: Check if the path exists
:type exists: boolean
:param directory: Check if the path is a directory
:type directory: boolean
:param zero_length: Check if the path is zero-length
:type zero_length: boolean
:returns: a boolean
.. note:: directory and zero length are AND'd.
'''
if not isinstance(path, (str, unicode)):
raise InvalidInputException("Path should be a string")
if not path:
raise InvalidInputException("test: no path given")
processor = lambda path, node, exists=exists, directory=directory, zero_length=zero_length: self._handle_test(path, node, exists, directory, zero_length)
try:
items = list(self._find_items([path], processor, include_toplevel=True))
if len(items) == 0:
return False
return all(items)
except FileNotFoundException as e:
if exists:
return False
else:
raise e
def _handle_test(self, path, node, exists, directory, zero_length):
return self._is_directory(directory, node) and self._is_zero_length(zero_length, node)
def text(self, paths, check_crc=False):
''' Takes a source file and outputs the file in text format.
The allowed formats are gzip and bzip2
:param paths: Paths to display
:type paths: list of strings
:param check_crc: Check for checksum errors
:type check_crc: boolean
:returns: a generator that yields strings
'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
if not paths:
raise InvalidInputException("text: no path given")
processor = lambda path, node, check_crc=check_crc: self._handle_text(path, node, check_crc)
for item in self._find_items(paths, processor, include_toplevel=True,
include_children=False, recurse=False):
if item:
yield item
def _handle_text(self, path, node, check_crc):
if self._is_dir(node):
raise DirectoryException("text: `%s': Is a directory" % path)
text = ''
for load in self._read_file(path, node, False, check_crc):
text += load
extension = os.path.splitext(path)[1]
if extension == '.gz':
return zlib.decompress(text, 16+zlib.MAX_WBITS)
elif extension == '.bz2':
return bz2.decompress(text)
else:
return text
def mkdir(self, paths, create_parent=False, mode=0o755):
''' Create a directoryCount
:param paths: Paths to create
:type paths: list of strings
:param create_parent: Also create the parent directories
:type create_parent: boolean
:param mode: Mode the directory should be created with
:type mode: int
:returns: a generator that yields dictionaries
'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")