1 # Copyright 2011-2012 GRNET S.A. All rights reserved.
3 # Redistribution and use in source and binary forms, with or
4 # without modification, are permitted provided that the following
7 # 1. Redistributions of source code must retain the above
8 # copyright notice, this list of conditions and the following
11 # 2. Redistributions in binary form must reproduce the above
12 # copyright notice, this list of conditions and the following
13 # disclaimer in the documentation and/or other materials
14 # provided with the distribution.
16 # THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17 # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19 # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20 # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23 # USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24 # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 # POSSIBILITY OF SUCH DAMAGE.
29 # The views and conclusions contained in the software and
30 # documentation are those of the authors and should not be
31 # interpreted as representing official policies, either expressed
32 # or implied, of GRNET S.A.
34 from threading import enumerate as activethreads
37 from hashlib import new as newhashlib
40 from binascii import hexlify
42 from kamaki.clients import SilentEvent
43 from kamaki.clients.pithos_rest_api import PithosRestAPI
44 from kamaki.clients.storage import ClientError
45 from kamaki.clients.utils import path4url, filter_in
46 from StringIO import StringIO
49 def _pithos_hash(block, blockhash):
50 h = newhashlib(blockhash)
51 h.update(block.rstrip('\x00'))
55 def _range_up(start, end, a_range):
57 (rstart, rend) = a_range.split('-')
58 (rstart, rend) = (int(rstart), int(rend))
59 if rstart > end or rend < start:
68 class PithosClient(PithosRestAPI):
69 """GRNet Pithos API client"""
71 _thread_exceptions = []
73 def __init__(self, base_url, token, account=None, container=None):
74 super(PithosClient, self).__init__(base_url, token, account, container)
76 def purge_container(self):
77 """Delete an empty container and destroy associated blocks
79 r = self.container_delete(until=unicode(time()))
82 def upload_object_unchunked(self, obj, f,
86 content_encoding=None,
87 content_disposition=None,
92 :param obj: (str) remote object path
94 :param f: open file descriptor
96 :param withHashFile: (bool)
98 :param size: (int) size of data to upload
102 :param content_encoding: (str)
104 :param content_disposition: (str)
106 :param content_type: (str)
108 :param sharing: {'read':[user and/or grp names],
109 'write':[usr and/or grp names]}
111 :param public: (bool)
113 self._assert_container()
119 data = json.dumps(json.loads(data))
121 raise ClientError(message='"%s" is not json-formated' % f.name,
124 raise ClientError(message='"%s" is not a valid hashmap file'\
127 data = f.read(size) if size is not None else f.read()
128 r = self.object_put(obj,
131 content_encoding=content_encoding,
132 content_disposition=content_disposition,
133 content_type=content_type,
139 def create_object_by_manifestation(self, obj,
141 content_encoding=None,
142 content_disposition=None,
147 :param obj: (str) remote object path
151 :param content_encoding: (str)
153 :param content_disposition: (str)
155 :param content_type: (str)
157 :param sharing: {'read':[user and/or grp names],
158 'write':[usr and/or grp names]}
160 :param public: (bool)
162 self._assert_container()
163 r = self.object_put(obj,
166 content_encoding=content_encoding,
167 content_disposition=content_disposition,
168 content_type=content_type,
171 manifest='%s/%s' % (self.container, obj))
174 # upload_* auxiliary methods
175 def _put_block_async(self, data, hash):
176 event = SilentEvent(method=self._put_block, data=data, hash=hash)
180 def _put_block(self, data, hash):
181 r = self.container_post(update=True,
182 content_type='application/octet-stream',
183 content_length=len(data),
186 assert r.json[0] == hash, 'Local hash does not match server'
188 def _get_file_block_info(self, fileobj, size=None):
189 meta = self.get_container_info()
190 blocksize = int(meta['x-container-block-size'])
191 blockhash = meta['x-container-block-hash']
192 size = size if size is not None else fstat(fileobj.fileno()).st_size
193 nblocks = 1 + (size - 1) // blocksize
194 return (blocksize, blockhash, size, nblocks)
196 def _get_missing_hashes(self, obj, json,
202 content_encoding=None,
203 content_disposition=None,
207 r = self.object_put(obj,
210 content_type=content_type,
213 content_encoding=content_encoding,
214 content_disposition=content_disposition,
215 permissions=permissions,
218 if r.status_code == 201:
223 def _caclulate_uploaded_blocks(self,
234 hash_gen = hash_cb(nblocks)
237 for i in range(nblocks):
238 block = fileobj.read(min(blocksize, size - offset))
240 hash = _pithos_hash(block, blockhash)
242 hmap[hash] = (offset, bytes)
246 assert offset == size
248 def _upload_missing_blocks(self, missing, hmap, fileobj, upload_cb=None):
249 """upload missing blocks asynchronously.
252 upload_gen = upload_cb(len(missing))
255 self._init_thread_limit()
259 offset, bytes = hmap[hash]
261 data = fileobj.read(bytes)
262 r = self._put_block_async(data, hash)
265 for i, thread in enumerate(flying):
267 unfinished = self._watch_thread_limit(unfinished)
269 if thread.isAlive() or thread.exception:
270 unfinished.append(thread)
276 for thread in flying:
279 failures = [r for r in flying if r.exception]
281 details = ', '.join([' (%s).%s' % (i, r.exception)\
282 for i, r in enumerate(failures)])
283 raise ClientError(message="Block uploading failed",
290 except StopIteration:
293 def upload_object(self, obj, f,
298 content_encoding=None,
299 content_disposition=None,
303 """Upload an object using multiple connections (threads)
305 :param obj: (str) remote object path
307 :param f: open file descriptor (rb)
309 :param hash_cb: optional progress.bar object for calculating hashes
311 :param upload_cb: optional progress.bar object for uploading
315 :param content_encoding: (str)
317 :param content_disposition: (str)
319 :param content_type: (str)
321 :param sharing: {'read':[user and/or grp names],
322 'write':[usr and/or grp names]}
324 :param public: (bool)
326 self._assert_container()
329 block_info = (blocksize, blockhash, size, nblocks) =\
330 self._get_file_block_info(f, size)
331 (hashes, hmap, offset) = ([], {}, 0)
332 if content_type is None:
333 content_type = 'application/octet-stream'
335 self._caclulate_uploaded_blocks(*block_info,
341 hashmap = dict(bytes=size, hashes=hashes)
342 missing = self._get_missing_hashes(obj, hashmap,
343 content_type=content_type,
346 content_encoding=content_encoding,
347 content_disposition=content_disposition,
354 self._upload_missing_blocks(missing, hmap, f, upload_cb=upload_cb)
355 except KeyboardInterrupt:
356 print('- - - wait for threads to finish')
357 for thread in activethreads():
365 content_type=content_type,
370 # download_* auxiliary methods
371 def _get_remote_blocks_info(self, obj, **restargs):
372 #retrieve object hashmap
373 myrange = restargs.pop('data_range', None)
374 hashmap = self.get_object_hashmapp(obj, **restargs)
375 restargs['data_range'] = myrange
376 blocksize = int(hashmap['block_size'])
377 blockhash = hashmap['block_hash']
378 total_size = hashmap['bytes']
379 #assert total_size/blocksize + 1 == len(hashmap['hashes'])
381 for i, h in enumerate(hashmap['hashes']):
383 return (blocksize, blockhash, total_size, hashmap['hashes'], map_dict)
385 def _dump_blocks_sync(self,
393 for blockid, blockhash in enumerate(remote_hashes):
394 if blockhash == None:
396 start = blocksize * blockid
397 end = total_size - 1 if start + blocksize > total_size\
398 else start + blocksize - 1
399 (start, end) = _range_up(start, end, range)
400 restargs['data_range'] = 'bytes=%s-%s' % (start, end)
401 r = self.object_get(obj, success=(200, 206), **restargs)
406 def _get_block_async(self, obj, **restargs):
407 event = SilentEvent(self.object_get,
414 def _hash_from_file(self, fp, start, size, blockhash):
416 block = fp.read(size)
417 h = newhashlib(blockhash)
418 h.update(block.strip('\x00'))
419 return hexlify(h.digest())
421 def _thread2file(self,
426 """write the results of a greenleted rest call to a file
427 @offset: the offset of the file up to blocksize
428 - e.g. if the range is 10-100, all
429 blocks will be written to normal_position - 10"""
431 for i, (start, g) in enumerate(flying.items()):
435 block = g.value.content
436 local_file.seek(start - offset)
437 local_file.write(block)
439 finished.append(flying.pop(start))
443 def _dump_blocks_async(self,
454 file_size = fstat(local_file.fileno()).st_size if resume else 0
458 if filerange is not None:
459 rstart = int(filerange.split('-')[0])
460 offset = rstart if blocksize > rstart else rstart % blocksize
462 self._init_thread_limit()
463 for block_hash, blockid in remote_hashes.items():
464 start = blocksize * blockid
465 if start < file_size\
466 and block_hash == self._hash_from_file(
473 self._watch_thread_limit(flying.values())
474 finished += self._thread2file(
479 end = total_size - 1 if start + blocksize > total_size\
480 else start + blocksize - 1
481 (start, end) = _range_up(start, end, filerange)
485 restargs['async_headers'] = {'Range': 'bytes=%s-%s' % (start, end)}
486 flying[start] = self._get_block_async(obj, **restargs)
488 for thread in flying.values():
490 finished += self._thread2file(flying, local_file, offset, **restargs)
492 def download_object(self,
501 if_modified_since=None,
502 if_unmodified_since=None):
503 """Download an object using multiple connections (threads) and
504 writing to random parts of the file
506 :param obj: (str) remote object path
508 :param dst: open file descriptor (wb+)
510 :param download_cb: optional progress.bar object for downloading
512 :param version: (str) file version
514 :param resume: (bool) if set, preserve already downloaded file parts
516 :param range: (str) from-to where from and to are integers denoting
517 file positions in bytes
519 :param if_match: (str)
521 :param if_none_match: (str)
523 :param if_modified_since: (str) formated date
525 :param if_unmodified_since: (str) formated date
528 restargs = dict(version=version,
529 data_range=None if range is None else 'bytes=%s' % range,
531 if_none_match=if_none_match,
532 if_modified_since=if_modified_since,
533 if_unmodified_since=if_unmodified_since)
539 remote_hashes) = self._get_remote_blocks_info(obj, **restargs)
540 assert total_size >= 0
543 self.progress_bar_gen = download_cb(len(remote_hashes))
547 self._dump_blocks_sync(obj,
555 self._dump_blocks_async(obj,
565 dst.truncate(total_size)
569 #Command Progress Bar method
571 if hasattr(self, 'progress_bar_gen'):
573 self.progress_bar_gen.next()
577 def _complete_cb(self):
580 self.progress_bar_gen.next()
584 def get_object_hashmapp(self, obj,
588 if_modified_since=None,
589 if_unmodified_since=None,
592 :param obj: (str) remote object path
594 :param if_match: (str)
596 :param if_none_match: (str)
598 :param if_modified_since: (str) formated date
600 :param if_unmodified_since: (str) formated date
602 :param data_range: (str) from-to where from and to are integers
603 denoting file positions in bytes
608 r = self.object_get(obj,
611 if_etag_match=if_match,
612 if_etag_not_match=if_none_match,
613 if_modified_since=if_modified_since,
614 if_unmodified_since=if_unmodified_since,
615 data_range=data_range)
616 except ClientError as err:
617 if err.status == 304 or err.status == 412:
622 def set_account_group(self, group, usernames):
626 :param usernames: (list)
628 r = self.account_post(update=True, groups={group: usernames})
631 def del_account_group(self, group):
635 r = self.account_post(update=True, groups={group: []})
638 def get_account_info(self, until=None):
640 :param until: (str) formated date
644 r = self.account_head(until=until)
645 if r.status_code == 401:
646 raise ClientError("No authorization")
649 def get_account_quota(self):
653 return filter_in(self.get_account_info(),
654 'X-Account-Policy-Quota',
657 def get_account_versioning(self):
661 return filter_in(self.get_account_info(),
662 'X-Account-Policy-Versioning',
665 def get_account_meta(self, until=None):
667 :meta until: (str) formated date
671 return filter_in(self.get_account_info(until=until), 'X-Account-Meta-')
673 def get_account_group(self):
677 return filter_in(self.get_account_info(), 'X-Account-Group-')
679 def set_account_meta(self, metapairs):
681 :param metapairs: (dict) {key1:val1, key2:val2, ...}
683 assert(type(metapairs) is dict)
684 r = self.account_post(update=True, metadata=metapairs)
687 def del_account_meta(self, metakey):
689 :param metakey: (str) metadatum key
691 r = self.account_post(update=True, metadata={metakey: ''})
694 def set_account_quota(self, quota):
698 r = self.account_post(update=True, quota=quota)
701 def set_account_versioning(self, versioning):
703 "param versioning: (str)
705 r = self.account_post(update=True, versioning=versioning)
708 def list_containers(self):
712 r = self.account_get()
715 def del_container(self, until=None, delimiter=None):
717 :param until: (str) formated date
719 :param delimiter: (str) with / empty container
721 :raises ClientError: 404 Container does not exist
723 :raises ClientError: 409 Container is not empty
725 self._assert_container()
726 r = self.container_delete(until=until,
728 success=(204, 404, 409))
730 if r.status_code == 404:
731 raise ClientError('Container "%s" does not exist' % self.container,
733 elif r.status_code == 409:
734 raise ClientError('Container "%s" is not empty' % self.container,
737 def get_container_versioning(self, container):
739 :param container: (str)
743 self.container = container
744 return filter_in(self.get_container_info(),
745 'X-Container-Policy-Versioning')
747 def get_container_quota(self, container):
749 :param container: (str)
753 self.container = container
754 return filter_in(self.get_container_info(), 'X-Container-Policy-Quota')
756 def get_container_info(self, until=None):
758 :param until: (str) formated date
762 r = self.container_head(until=until)
765 def get_container_meta(self, until=None):
767 :param until: (str) formated date
771 return filter_in(self.get_container_info(until=until),
774 def get_container_object_meta(self, until=None):
776 :param until: (str) formated date
780 return filter_in(self.get_container_info(until=until),
781 'X-Container-Object-Meta')
783 def set_container_meta(self, metapairs):
785 :param metapairs: (dict) {key1:val1, key2:val2, ...}
787 assert(type(metapairs) is dict)
788 r = self.container_post(update=True, metadata=metapairs)
791 def del_container_meta(self, metakey):
793 :param metakey: (str) metadatum key
795 r = self.container_post(update=True, metadata={metakey: ''})
798 def set_container_quota(self, quota):
802 r = self.container_post(update=True, quota=quota)
805 def set_container_versioning(self, versioning):
807 :param versioning: (str)
809 r = self.container_post(update=True, versioning=versioning)
812 def del_object(self, obj, until=None, delimiter=None):
814 :param obj: (str) remote object path
816 :param until: (str) formated date
818 :param delimiter: (str)
820 self._assert_container()
821 r = self.object_delete(obj, until=until, delimiter=delimiter)
824 def set_object_meta(self, obj, metapairs):
826 :param obj: (str) remote object path
828 :param metapairs: (dict) {key1:val1, key2:val2, ...}
830 assert(type(metapairs) is dict)
831 r = self.object_post(obj, update=True, metadata=metapairs)
834 def del_object_meta(self, obj, metakey):
836 :param obj: (str) remote object path
838 :param metakey: (str) metadatum key
840 r = self.object_post(obj, update=True, metadata={metakey: ''})
843 def publish_object(self, obj):
845 :param obj: (str) remote object path
847 r = self.object_post(obj, update=True, public=True)
850 def unpublish_object(self, obj):
852 :param obj: (str) remote object path
854 r = self.object_post(obj, update=True, public=False)
857 def get_object_info(self, obj, version=None):
859 :param obj: (str) remote object path
861 :param version: (str)
865 r = self.object_head(obj, version=version)
868 def get_object_meta(self, obj, version=None):
870 :param obj: (str) remote object path
872 :param version: (str)
876 return filter_in(self.get_object_info(obj, version=version),
879 def get_object_sharing(self, obj):
881 :param obj: (str) remote object path
885 r = filter_in(self.get_object_info(obj),
890 perms = r['x-object-sharing'].split(';')
895 raise ClientError('Incorrect reply format')
896 (key, val) = perm.strip().split('=')
900 def set_object_sharing(self, obj,
901 read_permition=False,
902 write_permition=False):
903 """Give read/write permisions to an object.
905 :param obj: (str) remote object path
907 :param read_permition: (list - bool) users and user groups that get
908 read permition for this object - False means all previous read
909 permissions will be removed
911 :param write_perimition: (list - bool) of users and user groups to get
912 write permition for this object - False means all previous write
913 permissions will be removed
916 perms = dict(read='' if not read_permition else read_permition,
917 write='' if not write_permition else write_permition)
918 r = self.object_post(obj, update=True, permissions=perms)
921 def del_object_sharing(self, obj):
923 :param obj: (str) remote object path
925 self.set_object_sharing(obj)
927 def append_object(self, obj, source_file, upload_cb=None):
929 :param obj: (str) remote object path
931 :param source_file: open file descriptor
933 :param upload_db: progress.bar for uploading
936 self._assert_container()
937 meta = self.get_container_info()
938 blocksize = int(meta['x-container-block-size'])
939 filesize = fstat(source_file.fileno()).st_size
940 nblocks = 1 + (filesize - 1) // blocksize
942 if upload_cb is not None:
943 upload_gen = upload_cb(nblocks)
944 for i in range(nblocks):
945 block = source_file.read(min(blocksize, filesize - offset))
947 r = self.object_post(obj,
949 content_range='bytes */*',
950 content_type='application/octet-stream',
951 content_length=len(block),
955 if upload_cb is not None:
958 def truncate_object(self, obj, upto_bytes):
960 :param obj: (str) remote object path
962 :param upto_bytes: max number of bytes to leave on file
964 r = self.object_post(obj,
966 content_range='bytes 0-%s/*' % upto_bytes,
967 content_type='application/octet-stream',
968 object_bytes=upto_bytes,
969 source_object=path4url(self.container, obj))
972 def overwrite_object(self,
978 """Overwrite a part of an object from local source file
980 :param obj: (str) remote object path
982 :param start: (int) position in bytes to start overwriting from
984 :param end: (int) position in bytes to stop overwriting at
986 :param source_file: open file descriptor
988 :param upload_db: progress.bar for uploading
991 self._assert_container()
992 meta = self.get_container_info()
993 blocksize = int(meta['x-container-block-size'])
994 filesize = fstat(source_file.fileno()).st_size
995 datasize = int(end) - int(start) + 1
996 nblocks = 1 + (datasize - 1) // blocksize
998 if upload_cb is not None:
999 upload_gen = upload_cb(nblocks)
1000 for i in range(nblocks):
1001 block = source_file.read(min(blocksize,
1004 offset += len(block)
1005 r = self.object_post(obj,
1007 content_type='application/octet-stream',
1008 content_length=len(block),
1009 content_range='bytes %s-%s/*' % (start, end),
1013 if upload_cb is not None:
1016 def copy_object(self, src_container, src_object, dst_container,
1018 source_version=None,
1023 :param src_container: (str) source container
1025 :param src_object: (str) source object path
1027 :param dst_container: (str) destination container
1029 :param dst_object: (str) destination object path
1031 :param source_version: (str) source object version
1033 :param public: (bool)
1035 :param content_type: (str)
1037 :param delimiter: (str)
1039 self._assert_account()
1040 self.container = dst_container
1041 dst_object = dst_object or src_object
1042 src_path = path4url(src_container, src_object)
1043 r = self.object_put(dst_object,
1047 source_version=source_version,
1049 content_type=content_type,
1050 delimiter=delimiter)
1053 def move_object(self, src_container, src_object, dst_container,
1055 source_version=None,
1060 :param src_container: (str) source container
1062 :param src_object: (str) source object path
1064 :param dst_container: (str) destination container
1066 :param dst_object: (str) destination object path
1068 :param source_version: (str) source object version
1070 :param public: (bool)
1072 :param content_type: (str)
1074 :param delimiter: (str)
1076 self._assert_account()
1077 self.container = dst_container
1078 dst_object = dst_object or src_object
1079 src_path = path4url(src_container, src_object)
1080 r = self.object_put(dst_object,
1084 source_version=source_version,
1086 content_type=content_type,
1087 delimiter=delimiter)
1090 def get_sharing_accounts(self, limit=None, marker=None, *args, **kwargs):
1091 """Get accounts that share with self.account
1095 :param marker: (str)
1099 self._assert_account()
1101 self.set_param('format', 'json')
1102 self.set_param('limit', limit, iff=limit is not None)
1103 self.set_param('marker', marker, iff=marker is not None)
1106 success = kwargs.pop('success', (200, 204))
1107 r = self.get(path, *args, success=success, **kwargs)
1110 def get_object_versionlist(self, obj):
1112 :param obj: (str) remote object path
1116 self._assert_container()
1117 r = self.object_get(obj, format='json', version='list')
1118 return r.json['versions']