-
Notifications
You must be signed in to change notification settings - Fork 99
/
Copy pathGlacierWrapper.py
executable file
·2010 lines (1675 loc) · 76.3 KB
/
GlacierWrapper.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 -*-
"""
.. module:: GlacierWrapper
:platform: Unix, Windows
:synopsis: Wrapper for accessing Amazon Glacier, with Amazon SimpleDB
support and other features.
"""
import math
import json
import pytz
import re
import logging
import os.path
import time
import sys
import traceback
import glaciercorecalls
import select
import hashlib
import fcntl
import termios
import struct
import boto
import boto.sdb
from boto import sns
from functools import wraps
from dateutil.parser import parse as dtparse
from datetime import datetime
from pprint import pformat
from glaciercorecalls import GlacierConnection, GlacierWriter
from glacierexception import *
class log_class_call(object):
"""
Decorator that logs class calls to specific functions.
.. note::
Set loglevel to DEBUG to see these logs.
"""
def __init__(self, start, finish, getter=None):
"""
Decorator constructor.
:param start: Message logged when starting the class.
:type start: str.
:param finish: Message logged when finishing the class.
:type finish: str.
"""
self.start = start
self.finish = finish
self.getter = getter
def __call__(self, fn):
def wrapper(*args, **kwargs):
that = args[0]
that.logger.debug(self.start)
ret = fn(*args, **kwargs)
that.logger.debug(self.finish)
if self.getter:
that.logger.debug(pformat(self.getter(ret)))
else:
that.logger.debug(pformat(ret))
return ret
wrapper.func_name = fn.func_name
if hasattr(fn, '__name__'):
wrapper.__name__ = self.name = fn.__name__
if hasattr(fn, '__doc__'):
wrapper.__doc__ = fn.__doc__
if hasattr(fn, '__module__'):
wrapper.__module__ = fn.__module__
return wrapper
class mmap(object):
"""
Not really a mmap, just a simple read-only substitute that
does not require having a lot of RAM to upload large files.
"""
def __init__(self, file):
self.file = file
self.size = os.fstat(self.file.fileno()).st_size
def __getitem__(self, key):
self.file.seek(key.start)
if key.stop is None:
stop = self.size
else:
stop = key.stop
return self.file.read(stop - key.start)
class GlacierWrapper(object):
"""
Wrapper for accessing Amazon Glacier, with Amazon SimpleDB support
and other features.
"""
VAULT_NAME_ALLOWED_CHARACTERS = "[a-zA-Z\.\-\_0-9]+"
ID_ALLOWED_CHARACTERS = "[a-zA-Z\-\_0-9]+"
MAX_VAULT_NAME_LENGTH = 255
MAX_VAULT_DESCRIPTION_LENGTH = 1024
MAX_PARTS = 10000
AVAILABLE_REGIONS = ('us-east-1', 'us-west-2', 'us-west-1',
'eu-west-1', 'eu-central-1', 'sa-east-1',
'ap-northeast-1', 'ap-southeast-1', 'ap-southeast-2')
AVAILABLE_REGIONS_MESSAGE = """\
Invalid region. Available regions for Amazon Glacier are:
us-east-1 (US - Virginia)
us-west-1 (US - N. California)
us-west-2 (US - Oregon)
eu-west-1 (EU - Ireland)
eu-central-1 (EU - Frankfurt)
sa-east-1 (South America - Sao Paulo)
ap-northeast-1 (Asia-Pacific - Tokyo)
ap-southeast-1 (Asia Pacific (Singapore)
ap-southeast-2 (Asia-Pacific - Sydney)\
"""
def setuplogging(self, logfile, loglevel, logtostdout):
"""
Set up the logging facility.
* If no logging parameters are given, WARNING-level logging will be printed to stdout.
* If logtostdout is True, messages will be sent to stdout, even if a logfile is given.
* If a logfile is given but can not be written to, logs are sent to stderr instead.
:param logfile: the fully qualified file name of where to log to.
:type logfile: str
:param loglevel: the level of logging::
* CRITICAL
* ERROR
* WARNING
* INFO
* DEBUG
:type loglevel: str
:param logtostdout: whether to sent log messages to stdout.
:type logtostdout: boolean
"""
levels = {'3': logging.CRITICAL,
'CRITICAL': logging.CRITICAL,
'2': logging.ERROR,
'ERROR': logging.ERROR,
'1': logging.WARNING,
'WARNING': logging.WARNING,
'0': logging.INFO,
'INFO': logging.INFO,
'-1': logging.DEBUG,
'DEBUG': logging.DEBUG}
loglevel = 'WARNING' if not loglevel in levels.keys() else levels[loglevel]
datefmt = '%b %d %H:%M:%S'
logformat = '%(asctime)s %(levelname)-8s glacier-cmd %(message)s'
if logtostdout:
logging.basicConfig(level=loglevel,
stream=sys.stdout,
format=logformat,
datefmt=datefmt)
elif logfile:
try:
open(logfile, 'a')
except IOError:
# Can't open the specified log file, log to stderr instead.
logging.basicConfig(level=loglevel,
stream=sys.stderr,
format=logformat,
datefmt=datefmt)
else:
logging.basicConfig(level=loglevel,
filename=logfile,
format=logformat,
datefmt=datefmt)
else:
logging.basicConfig(level='WARNING',
stream=sys.stdout,
format=logformat,
datefmt=datefmt)
def glacier_connect(func):
"""
Decorator which handles the connection to Amazon Glacier.
:param func: Function to wrap
:type func: function
:returns: wrapper function
:rtype: function
:raises: :py:exc:`glacier.glacierexception.ConnectionException`
"""
@wraps(func)
@log_class_call("Connecting to Amazon Glacier.",
"Connection to Amazon Glacier successful.")
def glacier_connect_wrap(*args, **kwargs):
self = args[0]
if not hasattr(self, "glacierconn") or \
(hasattr(self, "glacierconn") and not self.glacierconn):
try:
self.logger.debug("""\
Connecting to Amazon Glacier with
aws_access_key %s
aws_secret_key %s
region %s\
""",
self.aws_access_key,
self.aws_secret_key,
self.region)
self.glacierconn = GlacierConnection(self.aws_access_key,
self.aws_secret_key,
region_name=self.region)
except boto.exception.AWSConnectionError as e:
raise ConnectionException(
"Cannot connect to Amazon Glacier.",
cause=e.cause,
code="GlacierConnectionError")
return func(*args, **kwargs)
return glacier_connect_wrap
def sdb_connect(func):
"""
Decorator which connects to Amazon SimpleDB.
:param func: Function to wrap
:type func: function
:returns: wrapper function
:rtype: function
:raises: :py:exc:`glacier.glacierexception.ConnectionException`
"""
@wraps(func)
@log_class_call("Connecting to Amazon SimpleDB.",
"Connection to Amazon SimpleDB successful.")
def sdb_connect_wrap(*args, **kwargs):
self = args[0]
if not self.bookkeeping:
return func(*args, **kwargs)
# TODO: give SimpleDB its own class? Or move the few calls
# we need to glaciercorecalls?
if not self.bookkeeping_domain_name:
raise InputException(
'''\
Bookkeeping enabled but no Amazon SimpleDB domain given.
Provide a domain in either the config file or via the
command line, or disable bookkeeping.''',
code="SdbConnectionError")
if not hasattr(self, 'sdb_conn'):
try:
self.logger.debug("""\
Connecting to Amazon SimpleDB domain %s with
aws_access_key %s
aws_secret_key %s\
""",
self.bookkeeping_domain_name,
self.aws_access_key,
self.aws_secret_key)
self.sdb_conn = boto.sdb.connect_to_region(
self.sdb_region,
aws_access_key_id=self.sdb_access_key,
aws_secret_access_key=self.sdb_secret_key)
domain_name = self.bookkeeping_domain_name
self.sdb_domain = self.sdb_conn.create_domain(domain_name)
except (boto.exception.AWSConnectionError, boto.exception.SDBResponseError) as e:
raise ConnectionException(
"Cannot connect to Amazon SimpleDB.",
cause=e,
code="SdbConnectionError")
return func(*args, **kwargs)
return sdb_connect_wrap
def sns_connect(func):
"""
Decorator which connects to Amazon SNS.
:param func: Function to wrap
:type func: function
:returns: wrapper function
:rtype: function
:raises: GlacierWrapper.ConnectionException
"""
@wraps(func)
def sns_connect_wrap(*args, **kwargs):
self = args[0]
if not hasattr(self, "sns_conn"):
try:
self.sns_conn = boto.sns.connect_to_region(
aws_access_key_id=self.aws_access_key,
aws_secret_access_key=self.aws_secret_key,
region_name=self.region)
except boto.exception.AWSConnectionError as e:
raise ConnectionException(
"Cannot connect to Amazon SNS.",
cause=e.cause,
code="SNSConnectionError")
return func(*args, **kwargs)
return sns_connect_wrap
@log_class_call('Checking whether vault name is valid.',
'Vault name is valid.')
def _check_vault_name(self, name):
"""
Checks whether we have a valid vault name.
:param name: Vault name
:type name: str
:returns: True if valid, raises exception otherwise.
:rtype: boolean
:raises: :py:exc:`glacier.glacierexception.InputException`
"""
if len(name) > self.MAX_VAULT_NAME_LENGTH:
raise InputException(
u"Vault name can be at most %s characters long." % self.MAX_VAULT_NAME_LENGTH,
cause="Vault name more than %s characters long." % self.MAX_VAULT_NAME_LENGTH,
code="VaultNameError")
if len(name) == 0:
raise InputException(
u"Vault name has to be at least 1 character long.",
cause='Vault name has to be at least 1 character long.',
code="VaultNameError")
# If the name starts with an illegal character, then result
# m is None. In that case the expression becomes '0 != len(name)'
# which of course is always True.
m = re.match(self.VAULT_NAME_ALLOWED_CHARACTERS, name)
if (m.end() if m else 0) != len(name):
raise InputException(
u"""Allowed characters are a-z, A-Z, 0-9, '_' (underscore), '-' (hyphen), and '.' (period)""",
cause='Illegal characters in the vault name.',
code="VaultNameError")
return True
@log_class_call('Checking whether vault description is valid.',
'Vault description is valid.')
def _check_vault_description(self, description):
"""
Checks whether a vault description is valid (at least one character,
not too long, no illegal characters).
:param description: Vault description
:type description: str
:returns: True if valid, raises exception otherwise.
:rtype: boolean
:raises: :py:exc:`glacier.glacierexception.InputException`
"""
if len(description) > self.MAX_VAULT_DESCRIPTION_LENGTH:
raise InputException(
u"Description must be no more than %s characters."% self.MAX_VAULT_DESCRIPTION_LENGTH,
cause='Vault description contains more than %s characters.'% self.MAX_VAULT_DESCRIPTION_LENGTH,
code="VaultDescriptionError")
for char in description:
n = ord(char)
if n < 32 or n > 126:
raise InputException(
u"""The allowed characters are 7-bit ASCII without \
control codes, specifically ASCII values 32-126 decimal \
or 0x20-0x7E hexadecimal.""",
cause="Invalid characters in the vault name.",
code="VaultDescriptionError")
return True
@log_class_call('Checking whether id is valid.',
'Id is valid.')
def _check_id(self, amazon_id, id_type):
"""
Checks if an id (jobID, uploadID, archiveID) is valid.
A jobID or uploadID is 92 characters long, an archiveID is
138 characters long.
Valid characters are a-z, A-Z, 0-9, '-' and '_'.
:param amazon_id: id to be validated
:type amazon_id: str
:param id_type: the case-sensity type of id (JobId, UploadId, ArchiveId).
:type id_type: str
:returns: True if valid, raises exception otherwise.
:rtype: boolean
:raises: :py:exc:`glacier.glacierexception.InputException`
"""
length = {'JobId': 92,
'UploadId': 92,
'ArchiveId': 138}
self.logger.debug('Checking a %s.' % id_type)
if len(amazon_id) != length[id_type]:
raise InputException(
'A %s must be %s characters long. This ID is %s characters.'% (id_type, length[id_type], len(amazon_id)),
cause='Incorrect length of the %s string.'% id_type,
code="IdError")
m = re.match(self.ID_ALLOWED_CHARACTERS, amazon_id)
if (m.end() if m else 0) != len(amazon_id):
raise InputException(u"""\
This %s contains invalid characters. \
Allowed characters are a-z, A-Z, 0-9, '_' (underscore) and '-' (hyphen)\
""" % id_type,
cause='Illegal characters in the %s string.' % id_type,
code="IdError")
return True
@log_class_call('Validating region.',
'Region is valid.')
def _check_region(self, region):
"""
Checks whether the region given is valid.
:param region: the region to be validated.
:type region: str
:returns: True if valid, raises exception otherwise.
:rtype: boolean
:raises: GlacierWrapper.InputException
"""
if not region in self.AVAILABLE_REGIONS:
raise InputException(
self.AVAILABLE_REGIONS_MESSAGE,
cause='Invalid region code: %s.' % region,
code='RegionError')
return True
def _check_part_size(self, part_size, total_size):
"""
Check the part size:
- check whether we have a part size, if not: use default.
- check whether part size is a power of two: if not,
increase until it is.
- check wehther part size is big enough for the archive
total size: if not, increase until it is.
Return part size to use.
"""
def _part_size_for_total_size(total_size):
return self._next_power_of_2(
int(math.ceil(
float(total_size) / (1024 * 1024 * self.MAX_PARTS)
)))
if part_size < 0:
if total_size > 0:
part_size = _part_size_for_total_size(total_size)
else:
part_size = GlacierWriter.DEFAULT_PART_SIZE
else:
ps = self._next_power_of_2(part_size)
if not ps == part_size:
self.logger.warning("""\
Part size in MB must be a power of 2, \
e.g. 1, 2, 4, 8 MB; automatically increased part size from %s to %s.\
""" % (part_size, ps))
part_size = ps
# Check if user specified value is big enough, and adjust if needed.
if total_size > part_size * 1024 * 1024 * self.MAX_PARTS:
part_size = _part_size_for_total_size(total_size)
self.logger.warning("Part size given is too small; \
using %s MB parts to upload." % part_size)
return part_size
def _next_power_of_2(self, v):
"""
Returns the next power of 2, or the argument if it's
already a power of 2.
:param v: the value to be tested.
:type v: int
:returns: the next power of 2.
:rtype: int
"""
if v == 0:
return 1
v -= 1
v |= v >> 1
v |= v >> 2
v |= v >> 4
v |= v >> 8
v |= v >> 16
return v + 1
def _bold(self, msg):
"""
Uses ANSI codes to make text bold for printing on the tty.
"""
return u'\033[1m%s\033[0m' % msg
def _progress(self, msg):
"""
A progress indicator. Prints the progress message if stdout
is connected to a tty (i.e. run from the command prompt).
:param msg: the progress message to be printed.
:type msg: str
"""
if sys.stdout.isatty():
# Get the current screen width.
cols = struct.unpack('hh', fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ, '1234'))[1]
# Make sure the message fits on a single line, strip if not,
# and add spaces to fill the line if it's shorter (to erase
# old characters from longer lines)
msg = msg[:cols] if len(msg) > cols else msg
if len(msg) < cols:
for i in range(cols - len(msg)):
msg += ' '
sys.stdout.write(msg + '\r')
sys.stdout.flush()
def _size_fmt(self, num, decimals=1):
"""
Formats byte sizes in human readable format. Anything bigger
than TB is returned as TB.
Number of decimals is optional, defaults to 1.
:param num: the size in bytes.
:type num: int
:param decimals: the number of decimals to return.
:type decimals: int
:returns: the formatted number.
:rtype: str
"""
fmt = "%%3.%sf %%s" % decimals
for x in ['bytes', 'KB', 'MB', 'GB']:
if num < 1024.0:
return fmt % (num, x)
num /= 1024.0
return fmt % (num, 'TB')
def _decode_error_message(self, e):
try:
e = json.loads(e)['message']
except:
e = None
return e
@glacier_connect
@log_class_call("Listing vaults.",
"Listing vaults complete.")
def lsvault(self, limit=None):
"""
Lists available vaults.
:returns: List of vault descriptions.
.. code-block:: python
[{u'CreationDate': u'2012-09-20T14:29:14.710Z',
u'LastInventoryDate': u'2012-10-01T02:10:12.497Z',
u'NumberOfArchives': 15,
u'SizeInBytes': 33932739443L,
u'VaultARN': u'arn:aws:glacier:us-east-1:012345678901:vaults/your_vault_name',
u'VaultName': u'your_vault_name'},
...
]
:rtype: list
:raises: :py:exc:`glacier.glacierexception.CommunicationException`,
:py:exc:`glacier.glacierexception.ResponseException`
"""
marker = None
vault_list = []
while True:
try:
response = self.glacierconn.list_vaults(marker=marker)
except boto.glacier.exceptions.UnexpectedHTTPResponseError as e:
raise ResponseException(
'Failed to recieve vault list.',
cause=self._decode_error_message(e.body),
code=e.code)
vault_list += response.copy()['VaultList']
marker = response.copy()['Marker']
if limit and len(vault_list) >= limit:
vault_list = vault_list[:limit]
break
if not marker:
break
return vault_list
@glacier_connect
@log_class_call("Creating vault.",
"Vault creation completed.")
def mkvault(self, vault_name):
"""
Creates a new vault.
:param vault_name: Name of vault to be created.
:type vault_name: str
:returns: Response data.
:rtype: :py:class:`boto.glacier.response.GlacierResponse`
:raises: :py:exc:`glacier.glacierexception.CommunicationException`
"""
self._check_vault_name(vault_name)
try:
response = self.glacierconn.create_vault(vault_name)
except boto.glacier.exceptions.UnexpectedHTTPResponseError as e:
raise ResponseException(
'Failed to create vault with name %s.' % vault_name,
cause=self._decode_error_message(e.body),
code=e.code)
return response.copy()
@glacier_connect
@sdb_connect
@log_class_call("Removing vault.",
"Vault removal complete.")
def rmvault(self, vault_name):
"""
Removes a vault. Vault must be empty before it can be removed.
:param vault_name: Name of vault to be removed.
:type vault_name: str
:returns: Response data. Raises exception on failure.
.. code-block:: python
[('x-amzn-requestid', 'Example_rkQ-xzxHfrI-997hphbfdcIbL74IhDf_Example'),
('date', 'Mon, 01 Oct 2012 13:54:06 GMT')]
:rtype: list
:raises: :py:exc:`glacier.glacierexception.CommunicationException`
"""
self._check_vault_name(vault_name)
try:
response = self.glacierconn.delete_vault(vault_name)
except boto.glacier.exceptions.UnexpectedHTTPResponseError as e:
raise ResponseException(
'Failed to remove vault with name %s.' % vault_name,
cause=self._decode_error_message(e.body),
code=e.code)
# Check for orphaned entries in the bookkeeping database, and
# remove them.
if self.bookkeeping:
query = "select * from `%s` where vault='%s'" % (self.bookkeeping_domain_name, vault_name)
result = self.sdb_domain.select(query)
try:
for item in result:
self.sdb_domain.delete_item(item)
self.logger.debug('Deleted orphaned archive from the database: %s.' % item.name)
except boto.exception.SDBResponseError as e:
raise ResponseException(
'SimpleDB did not respond correctly to our orphaned listings check.',
cause=self._decode_error_message(e.body),
code=e.code)
return response.copy()
@glacier_connect
@log_class_call("Requesting vault description.",
"Vault description received.")
def describevault(self, vault_name):
"""
Describes vault inventory and other details.
:param vault_name: Name of vault.
:type vault_name: str
:returns: vault description.
.. code-block:: python
{u'CreationDate': u'2012-10-01T13:24:55.791Z',
u'LastInventoryDate': None,
u'NumberOfArchives': 0,
u'SizeInBytes': 0,
u'VaultARN': u'arn:aws:glacier:us-east-1:012345678901:vaults/your_vault_name',
u'VaultName': u'your_vault_name'}
:rtype: dict
:raises: :py:exc:`glacier.glacierexception.CommunicationException`
"""
self._check_vault_name(vault_name)
try:
response = self.glacierconn.describe_vault(vault_name)
except boto.glacier.exceptions.UnexpectedHTTPResponseError as e:
raise ResponseException(
'Failed to get description of vault with name %s.' % vault_name,
cause=self._decode_error_message(e.body),
code=e.code)
return response.copy()
@glacier_connect
@log_class_call("Requesting jobs list.",
"Active jobs list received.")
def list_jobs(self, vault_name, completed=None,
status_code=None, limit=None):
"""
Provides a list of current Glacier jobs with status and other
job details.
If no jobs active it returns an empty list.
:param vault_name: Name of vault.
:type vault_name: str
:returns: job list
.. code-block:: python
[{u'Action': u'InventoryRetrieval',
u'ArchiveId': None,
u'ArchiveSizeInBytes': None,
u'Completed': False,
u'CompletionDate': None,
u'CreationDate': u'2012-10-01T14:54:51.919Z',
u'InventorySizeInBytes': None,
u'JobDescription': None,
u'JobId': u'Example_rctvAMVd3tgAbCuQkD2vjNQ6aw9ifwACvhjhIeKtNnZqeSIuMYRo3JUKsK_0M-VNYvb0-eEreSUp_Example',
u'SHA256TreeHash': None,
u'SNSTopic': None,
u'StatusCode': u'InProgress',
u'StatusMessage': None,
u'VaultARN': u'arn:aws:glacier:us-east-1:012345678901:vaults/your_vault_name'},
{...}]
:rtype: list
:raises: :py:exc:`glacier.glacierexception.ResponseException`
"""
self._check_vault_name(vault_name)
marker = None
job_list = []
while True:
try:
response = self.glacierconn.list_jobs(vault_name,
completed=completed,
status_code=status_code,
marker=marker)
except boto.glacier.exceptions.UnexpectedHTTPResponseError as e:
raise ResponseException(
'Failed to recieve the jobs list for vault %s.' % vault_name,
cause=self._decode_error_message(e.body),
code=e.code)
job_list += response.copy()['JobList']
marker = response.copy()['Marker']
if limit and len(job_list) >= limit:
job_list = job_list[:limit]
break
if not marker:
break
return job_list
@glacier_connect
@log_class_call("Requesting job description.",
"Job description received.")
def describejob(self, vault_name, job_id):
"""
Gives detailed description of a job.
:param vault_name: Name of vault.
:type vault_name: str
:param job_id: id of job to be described.
:type job_id: str
:returns: List of job properties.
.. code-block:: python
{u'Action': u'InventoryRetrieval',
u'ArchiveId': None,
u'ArchiveSizeInBytes': None,
u'Completed': False,
u'CompletionDate': None,
u'CreationDate': u'2012-10-01T14:54:51.919Z',
u'InventorySizeInBytes': None,
u'JobDescription': None,
u'JobId': u'Example_d3tgAbCuQ9vPRqRJkD2vjNQ6wBgga7Xaw9ifwACvhjhIeKtNnZqeSIuMYRo3JUKsK_0M-VNYvb0-_Example',
u'SHA256TreeHash': None,
u'SNSTopic': None,
u'StatusCode': u'InProgress',
u'StatusMessage': None,
u'VaultARN': u'arn:aws:glacier:us-east-1:012345678901:vaults/your_vault_name'}
:rtype: dict
:raises: :py:exc:`glacier.glacierexception.CommunicationException`
"""
self._check_vault_name(vault_name)
self._check_id(job_id, 'JobId')
try:
response = self.glacierconn.describe_job(vault_name, job_id)
except boto.glacier.exceptions.UnexpectedHTTPResponseError as e:
raise ResponseException(
'Failed to get description of job with job id %s.' % job_id,
cause=self._decode_error_message(e.body),
code=e.code)
return response.copy()
@glacier_connect
@log_class_call("Aborting multipart upload.",
"Multipart upload successfully aborted.")
def abortmultipart(self, vault_name, upload_id):
"""
Aborts an incomplete multipart upload, causing any uploaded data to be
removed from Amazon Glacier.
:param vault_name: Name of the vault.
:type vault_name: str
:param upload_id: the UploadId of the multipart upload to be aborted.
:type upload_id: str
:returns: server response.
.. code-block:: python
[('x-amzn-requestid', 'Example_ZJwjlLbvg8Dg_lnYUnC8bjV6cvlTBTO_Example'),
('date', 'Mon, 01 Oct 2012 16:08:23 GMT')]
:rtype: list
:raises: :py:exc:`glacier.glacierexception.CommunicationException`
"""
self._check_vault_name(vault_name)
self._check_id(upload_id, "UploadId")
try:
response = self.glacierconn.abort_multipart_upload(vault_name, upload_id)
except boto.glacier.exceptions.UnexpectedHTTPResponseError as e:
raise ResponseException(
'Failed to abort multipart upload with id %s.' % upload_id,
cause=self._decode_error_message(e.body),
code=e.code)
return response.copy()
@glacier_connect
@log_class_call("Listing multipart uploads.",
"Multipart uploads list received successfully.")
def listmultiparts(self, vault_name, limit=None):
"""
Provids a list of all currently active multipart uploads.
:param vault_name: Name of the vault.
:type vault_name: str
:return: list of uploads, or None.
.. code-block:: python
[{u'ArchiveDescription': u'myfile.tgz',
u'CreationDate': u'2012-09-30T15:21:35.890Z',
u'MultipartUploadId': u'Example_oiuhncYLvBRZLzYgVw7MO_OO4l6i78va8N83R9xLNqrFaa8Vyz4W_JsaXhLNicCCbi_OdsHD8dHK_Example',
u'PartSizeInBytes': 134217728,
u'VaultARN': u'arn:aws:glacier:us-east-1:012345678901:vaults/your_vault_name'},
{...}]
:rtype: list
:raises: :py:exc:`glacier.glacierexception.CommunicationException`
"""
self._check_vault_name(vault_name)
marker = None
uploads = []
while True:
try:
response = self.glacierconn.list_multipart_uploads(vault_name,
marker=marker)
except boto.glacier.exceptions.UnexpectedHTTPResponseError as e:
raise ResponseException(
'Failed to get a list of multipart uploads for vault %s.' % vault_name,
cause=self._decode_error_message(e.body),
code=e.code)
uploads += response.copy()['UploadsList']
marker = response.copy()['Marker']
if limit and len(uploads) >= limit:
uploads = uploads[:limit]
break
if not marker:
break
return uploads
@glacier_connect
@sdb_connect
@log_class_call("Uploading archive.",
"Upload of archive finished.")
def upload(self, vault_name, file_name, description, region,
stdin, alternative_name, part_size, uploadid, resume):
"""
Uploads a file to Amazon Glacier.
:param vault_name: Name of the vault.
:type vault_name: str
:param file_name: Name of the file to upload.
:type file_name: str
:param description: Description of the upload.
:type description: str
:param region: region where to upload to.
:type region: str
:param stdin: whether to use stdin to read data from.
:type stdin: boolan
:param part_size: the size (in MB) of the blocks to upload.
:type part_size: int
:returns: Tupple of (archive_id, sha256hash)
:rtype: tupple
:raises: :py:exc:`glacier.glacierexception.InputException`,
:py:exc:`glacier.glacierexception.ResponseException`
"""
# Switch off debug logging for boto, as otherwise it's
# filling up the log with the data sent!
if self.logger.getEffectiveLevel() == 10:
logging.getLogger('boto').setLevel(logging.INFO)
# Do some sanity checking on the user values.
self._check_vault_name(vault_name)
self._check_region(region)
if not description:
description = file_name if file_name else 'No description.'
if description:
self._check_vault_description(description)
if uploadid:
self._check_id(uploadid, 'UploadId')
if resume and stdin:
raise InputException(
'You must provide the UploadId to resume upload of streams from stdin.\nUse glacier-cmd listmultiparts <vault> to find the UploadId.',
code='CommandError')
# If file_name is given, try to use this file(s).
# Otherwise try to read data from stdin.
total_size = 0
reader = None
mmapped_file = None
if not stdin:
if not file_name:
raise InputException(
"No file name given for upload.",
code='CommandError')
try:
f = open(file_name, 'rb')
mmapped_file = mmap(f)