-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblobxfer-0.9.9.10.py
2570 lines (2459 loc) · 103 KB
/
blobxfer-0.9.9.10.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
#!/usr/bin/env python
# blobxfer.py Code Sample
#
# Copyright (c) Microsoft Corporation
#
# All rights reserved.
#
# MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
"""
Code sample to show data transfer to/from Azure blob storage
See notes in the README.rst file.
TODO list:
- convert from threading to multiprocessing
- move instruction queue data to class
"""
# pylint: disable=R0913,R0914
# stdlib imports
from __future__ import print_function
import argparse
import base64
import errno
import fnmatch
import hashlib
import hmac
import json
import mimetypes
import multiprocessing
import os
import platform
# pylint: disable=F0401
try:
import queue
except ImportError: # pragma: no cover
import Queue as queue
# pylint: enable=F0401
import socket
import sys
import threading
import time
import traceback
try:
from urllib.parse import quote as urlquote
except ImportError: # pramga: no cover
from urllib import quote as urlquote
import xml.etree.ElementTree as ET
# non-stdlib imports
import azure.common
try:
import azure.servicemanagement
except ImportError: # pragma: no cover
pass
try:
import azure.storage.blob
except ImportError: # pragma: no cover
pass
try:
import cryptography.hazmat.backends
import cryptography.hazmat.primitives.asymmetric.padding
import cryptography.hazmat.primitives.asymmetric.rsa
import cryptography.hazmat.primitives.ciphers
import cryptography.hazmat.primitives.ciphers.algorithms
import cryptography.hazmat.primitives.ciphers.modes
import cryptography.hazmat.primitives.constant_time
import cryptography.hazmat.primitives.hashes
import cryptography.hazmat.primitives.padding
import cryptography.hazmat.primitives.serialization
except ImportError: # pragma: no cover
pass
import requests
# remap keywords for Python3
# pylint: disable=W0622,C0103
try:
xrange
except NameError: # pragma: no cover
xrange = range
try:
long
except NameError: # pragma: no cover
long = int
# pylint: enable=W0622,C0103
# global defines
_SCRIPT_VERSION = '0.9.9.10'
_PY2 = sys.version_info.major == 2
_DEFAULT_MAX_STORAGEACCOUNT_WORKERS = multiprocessing.cpu_count() * 3
_MAX_BLOB_CHUNK_SIZE_BYTES = 4194304
_EMPTY_MAX_PAGE_SIZE_MD5 = 'tc+p1sj+vWGPkawoQ9UKHA=='
_MAX_LISTBLOBS_RESULTS = 1000
_PAGEBLOB_BOUNDARY = 512
_DEFAULT_BLOB_ENDPOINT = 'blob.core.windows.net'
_DEFAULT_MANAGEMENT_ENDPOINT = 'management.core.windows.net'
# encryption defines
_AES256_KEYLENGTH_BYTES = 32
_AES256_BLOCKSIZE_BYTES = 16
_HMACSHA256_DIGESTSIZE_BYTES = 32
_AES256CBC_HMACSHA256_OVERHEAD_BYTES = _AES256_BLOCKSIZE_BYTES + \
_HMACSHA256_DIGESTSIZE_BYTES
_ENCRYPTION_MODE_FULLBLOB = 'FullBlob'
_ENCRYPTION_MODE_CHUNKEDBLOB = 'ChunkedBlob'
_DEFAULT_ENCRYPTION_MODE = _ENCRYPTION_MODE_FULLBLOB
_ENCRYPTION_PROTOCOL_VERSION = '1.0'
_ENCRYPTION_ALGORITHM = 'AES_CBC_256'
_ENCRYPTION_AUTH_ALGORITHM = 'HMAC-SHA256'
_ENCRYPTION_CHUNKSTRUCTURE = 'IV || EncryptedData || Signature'
_ENCRYPTION_ENCRYPTED_KEY_SCHEME = 'RSA-OAEP'
_ENCRYPTION_METADATA_NAME = 'encryptiondata'
_ENCRYPTION_METADATA_MODE = 'EncryptionMode'
_ENCRYPTION_METADATA_ALGORITHM = 'Algorithm'
_ENCRYPTION_METADATA_MAC = 'MessageAuthenticationCode'
_ENCRYPTION_METADATA_LAYOUT = 'EncryptedDataLayout'
_ENCRYPTION_METADATA_CHUNKOFFSETS = 'ChunkByteOffsets'
_ENCRYPTION_METADATA_CHUNKSTRUCTURE = 'ChunkStructure'
_ENCRYPTION_METADATA_AGENT = 'EncryptionAgent'
_ENCRYPTION_METADATA_PROTOCOL = 'Protocol'
_ENCRYPTION_METADATA_ENCRYPTION_ALGORITHM = 'EncryptionAlgorithm'
_ENCRYPTION_METADATA_INTEGRITY_AUTH = 'EncryptionAuthentication'
_ENCRYPTION_METADATA_WRAPPEDCONTENTKEY = 'WrappedContentKey'
_ENCRYPTION_METADATA_ENCRYPTEDKEY = 'EncryptedKey'
_ENCRYPTION_METADATA_ENCRYPTEDAUTHKEY = 'EncryptedAuthenticationKey'
_ENCRYPTION_METADATA_CONTENT_IV = 'ContentEncryptionIV'
_ENCRYPTION_METADATA_KEYID = 'KeyId'
_ENCRYPTION_METADATA_BLOBXFER_EXTENSIONS = 'BlobxferExtensions'
_ENCRYPTION_METADATA_PREENCRYPTED_MD5 = 'PreEncryptedContentMD5'
_ENCRYPTION_METADATA_AUTH_NAME = 'encryptiondata_authentication'
_ENCRYPTION_METADATA_AUTH_METAAUTH = 'EncryptionMetadataAuthentication'
_ENCRYPTION_METADATA_AUTH_ENCODING = 'Encoding'
_ENCRYPTION_METADATA_AUTH_ENCODING_TYPE = 'UTF-8'
class EncryptionMetadataJson(object):
"""Class for handling encryption metadata json"""
def __init__(
self, args, symkey, signkey, iv, encdata_signature,
preencrypted_md5, rsakeyid=None):
"""Ctor for EncryptionMetadataJson
Parameters:
args - program arguments
symkey - symmetric key
signkey - signing key
iv - initialization vector
encdata_signature - encrypted data signature (MAC)
preencrypted_md5 - pre-encrypted md5 hash
rsakeyid - symmetric key id
Returns:
Nothing
Raises:
Nothing
"""
self.encmode = args.encmode
self.rsaprivatekey = args.rsaprivatekey
self.rsapublickey = args.rsapublickey
self.chunksizebytes = args.chunksizebytes
self.symkey = symkey
self.signkey = signkey
if rsakeyid is None:
self.rsakeyid = 'private:key1'
else:
self.rsakeyid = rsakeyid
self.iv = iv
self.hmac = encdata_signature
self.md5 = preencrypted_md5
def construct_metadata_json(self):
"""Constructs encryptiondata metadata
Paramters:
None
Returns:
dict of encryptiondata and encryptiondata_authentiation json
Raises:
Nothing
"""
encsymkey, _ = rsa_encrypt_key(
self.rsaprivatekey, self.rsapublickey, self.symkey)
encsignkey, _ = rsa_encrypt_key(
self.rsaprivatekey, self.rsapublickey, self.signkey)
encjson = {
_ENCRYPTION_METADATA_MODE: self.encmode,
_ENCRYPTION_METADATA_WRAPPEDCONTENTKEY: {
_ENCRYPTION_METADATA_KEYID: self.rsakeyid,
_ENCRYPTION_METADATA_ENCRYPTEDKEY: encsymkey,
_ENCRYPTION_METADATA_ENCRYPTEDAUTHKEY: encsignkey,
_ENCRYPTION_METADATA_ALGORITHM:
_ENCRYPTION_ENCRYPTED_KEY_SCHEME,
},
_ENCRYPTION_METADATA_AGENT: {
_ENCRYPTION_METADATA_PROTOCOL: _ENCRYPTION_PROTOCOL_VERSION,
_ENCRYPTION_METADATA_ENCRYPTION_ALGORITHM:
_ENCRYPTION_ALGORITHM
},
_ENCRYPTION_METADATA_INTEGRITY_AUTH: {
_ENCRYPTION_METADATA_ALGORITHM:
_ENCRYPTION_AUTH_ALGORITHM,
},
'KeyWrappingMetadata': {},
}
if self.md5 is not None:
encjson[_ENCRYPTION_METADATA_BLOBXFER_EXTENSIONS] = {
_ENCRYPTION_METADATA_PREENCRYPTED_MD5: self.md5
}
if self.encmode == _ENCRYPTION_MODE_FULLBLOB:
encjson[_ENCRYPTION_METADATA_CONTENT_IV] = base64encode(self.iv)
encjson[_ENCRYPTION_METADATA_INTEGRITY_AUTH][
_ENCRYPTION_METADATA_MAC] = base64encode(self.hmac)
elif self.encmode == _ENCRYPTION_MODE_CHUNKEDBLOB:
encjson[_ENCRYPTION_METADATA_LAYOUT] = {}
encjson[_ENCRYPTION_METADATA_LAYOUT][
_ENCRYPTION_METADATA_CHUNKOFFSETS] = \
self.chunksizebytes + _AES256CBC_HMACSHA256_OVERHEAD_BYTES + 1
encjson[_ENCRYPTION_METADATA_LAYOUT][
_ENCRYPTION_METADATA_CHUNKSTRUCTURE] = \
_ENCRYPTION_CHUNKSTRUCTURE
else:
raise RuntimeError(
'Unknown encryption mode: {}'.format(self.encmode))
bencjson = json.dumps(
encjson, sort_keys=True, ensure_ascii=False).encode(
_ENCRYPTION_METADATA_AUTH_ENCODING_TYPE)
encjson = {_ENCRYPTION_METADATA_NAME:
json.dumps(encjson, sort_keys=True)}
# compute MAC over encjson
hmacsha256 = hmac.new(self.signkey, digestmod=hashlib.sha256)
hmacsha256.update(bencjson)
authjson = {
_ENCRYPTION_METADATA_AUTH_METAAUTH: {
_ENCRYPTION_METADATA_ALGORITHM: _ENCRYPTION_AUTH_ALGORITHM,
_ENCRYPTION_METADATA_AUTH_ENCODING:
_ENCRYPTION_METADATA_AUTH_ENCODING_TYPE,
_ENCRYPTION_METADATA_MAC: base64encode(hmacsha256.digest()),
}
}
encjson[_ENCRYPTION_METADATA_AUTH_NAME] = json.dumps(
authjson, sort_keys=True)
return encjson
def parse_metadata_json(
self, blobname, rsaprivatekey, rsapublickey, mddict):
"""Parses a meta data dictionary containing the encryptiondata
metadata
Parameters:
blobname - name of blob
rsaprivatekey - RSA private key
rsapublickey - RSA public key
mddict - metadata dictionary
Returns:
Nothing
Raises:
RuntimeError if encryptiondata metadata contains invalid or
unknown fields
"""
if _ENCRYPTION_METADATA_NAME not in mddict:
return
# json parse internal dict
meta = json.loads(mddict[_ENCRYPTION_METADATA_NAME])
# populate preencryption md5
if (_ENCRYPTION_METADATA_BLOBXFER_EXTENSIONS in meta and
_ENCRYPTION_METADATA_PREENCRYPTED_MD5 in meta[
_ENCRYPTION_METADATA_BLOBXFER_EXTENSIONS]):
self.md5 = meta[_ENCRYPTION_METADATA_BLOBXFER_EXTENSIONS][
_ENCRYPTION_METADATA_PREENCRYPTED_MD5]
else:
self.md5 = None
# if RSA key is not present return
if rsaprivatekey is None and rsapublickey is None:
return
# check for required metadata fields
if (_ENCRYPTION_METADATA_MODE not in meta or
_ENCRYPTION_METADATA_AGENT not in meta):
return
# populate encryption mode
self.encmode = meta[_ENCRYPTION_METADATA_MODE]
# validate known encryption metadata is set to proper values
if self.encmode == _ENCRYPTION_MODE_CHUNKEDBLOB:
chunkstructure = meta[_ENCRYPTION_METADATA_LAYOUT][
_ENCRYPTION_METADATA_CHUNKSTRUCTURE]
if chunkstructure != _ENCRYPTION_CHUNKSTRUCTURE:
raise RuntimeError(
'{}: unknown encrypted chunk structure {}'.format(
blobname, chunkstructure))
protocol = meta[_ENCRYPTION_METADATA_AGENT][
_ENCRYPTION_METADATA_PROTOCOL]
if protocol != _ENCRYPTION_PROTOCOL_VERSION:
raise RuntimeError('{}: unknown encryption protocol: {}'.format(
blobname, protocol))
blockcipher = meta[_ENCRYPTION_METADATA_AGENT][
_ENCRYPTION_METADATA_ENCRYPTION_ALGORITHM]
if blockcipher != _ENCRYPTION_ALGORITHM:
raise RuntimeError('{}: unknown block cipher: {}'.format(
blobname, blockcipher))
if _ENCRYPTION_METADATA_INTEGRITY_AUTH in meta:
intauth = meta[_ENCRYPTION_METADATA_INTEGRITY_AUTH][
_ENCRYPTION_METADATA_ALGORITHM]
if intauth != _ENCRYPTION_AUTH_ALGORITHM:
raise RuntimeError(
'{}: unknown integrity/auth method: {}'.format(
blobname, intauth))
symkeyalg = meta[_ENCRYPTION_METADATA_WRAPPEDCONTENTKEY][
_ENCRYPTION_METADATA_ALGORITHM]
if symkeyalg != _ENCRYPTION_ENCRYPTED_KEY_SCHEME:
raise RuntimeError('{}: unknown key encryption scheme: {}'.format(
blobname, symkeyalg))
# populate iv and hmac
if self.encmode == _ENCRYPTION_MODE_FULLBLOB:
self.iv = base64.b64decode(meta[_ENCRYPTION_METADATA_CONTENT_IV])
# don't base64 decode hmac
if _ENCRYPTION_METADATA_INTEGRITY_AUTH in meta:
self.hmac = meta[_ENCRYPTION_METADATA_INTEGRITY_AUTH][
_ENCRYPTION_METADATA_MAC]
else:
self.hmac = None
# populate chunksize
if self.encmode == _ENCRYPTION_MODE_CHUNKEDBLOB:
self.chunksizebytes = long(
meta[_ENCRYPTION_METADATA_LAYOUT][
_ENCRYPTION_METADATA_CHUNKOFFSETS])
# if RSA key is a public key, stop here as keys cannot be decrypted
if rsaprivatekey is None:
return
# decrypt symmetric key
self.symkey = rsa_decrypt_key(
rsaprivatekey,
meta[_ENCRYPTION_METADATA_WRAPPEDCONTENTKEY][
_ENCRYPTION_METADATA_ENCRYPTEDKEY], None)
# decrypt signing key, if it exists
if _ENCRYPTION_METADATA_ENCRYPTEDAUTHKEY in meta[
_ENCRYPTION_METADATA_WRAPPEDCONTENTKEY]:
self.signkey = rsa_decrypt_key(
rsaprivatekey,
meta[_ENCRYPTION_METADATA_WRAPPEDCONTENTKEY][
_ENCRYPTION_METADATA_ENCRYPTEDAUTHKEY], None)
else:
self.signkey = None
# validate encryptiondata metadata using the signing key
if (self.signkey is not None and
_ENCRYPTION_METADATA_AUTH_NAME in mddict):
authmeta = json.loads(mddict[_ENCRYPTION_METADATA_AUTH_NAME])
if _ENCRYPTION_METADATA_AUTH_METAAUTH not in authmeta:
raise RuntimeError(
'{}: encryption metadata auth block not found'.format(
blobname))
if _ENCRYPTION_METADATA_AUTH_ENCODING not in authmeta[
_ENCRYPTION_METADATA_AUTH_METAAUTH]:
raise RuntimeError(
'{}: encryption metadata auth encoding not found'.format(
blobname))
intauth = authmeta[_ENCRYPTION_METADATA_AUTH_METAAUTH][
_ENCRYPTION_METADATA_ALGORITHM]
if intauth != _ENCRYPTION_AUTH_ALGORITHM:
raise RuntimeError(
'{}: unknown integrity/auth method: {}'.format(
blobname, intauth))
authhmac = base64.b64decode(
authmeta[_ENCRYPTION_METADATA_AUTH_METAAUTH][
_ENCRYPTION_METADATA_MAC])
bmeta = mddict[_ENCRYPTION_METADATA_NAME].encode(
authmeta[_ENCRYPTION_METADATA_AUTH_METAAUTH][
_ENCRYPTION_METADATA_AUTH_ENCODING])
hmacsha256 = hmac.new(self.signkey, digestmod=hashlib.sha256)
hmacsha256.update(bmeta)
if hmacsha256.digest() != authhmac:
raise RuntimeError(
'{}: encryption metadata authentication failed'.format(
blobname))
class PqTupleSort(tuple):
"""Priority Queue tuple sorter: handles priority collisions.
0th item in the tuple is the priority number."""
def __lt__(self, rhs):
return self[0] < rhs[0]
def __gt__(self, rhs):
return self[0] > rhs[0]
def __le__(self, rhs):
return self[0] <= rhs[0]
def __ge__(self, rhs):
return self[0] >= rhs[0]
class SasBlobList(object):
"""Sas Blob listing object"""
def __init__(self):
"""Ctor for SasBlobList"""
self.blobs = []
self.next_marker = None
def __iter__(self):
"""Iterator"""
return iter(self.blobs)
def __len__(self):
"""Length"""
return len(self.blobs)
def __getitem__(self, index):
"""Accessor"""
return self.blobs[index]
def add_blob(self, name, content_length, content_md5, blobtype, mddict):
"""Adds a blob to the list
Parameters:
name - blob name
content_length - content length
content_md5 - content md5
blobtype - blob type
mddict - metadata dictionary
Returns:
Nothing
Raises:
Nothing
"""
obj = type('bloblistobject', (object,), {})
obj.name = name
obj.metadata = mddict
obj.properties = type('properties', (object,), {})
obj.properties.content_length = content_length
if content_md5 is not None and len(content_md5) > 0:
obj.properties.content_md5 = content_md5
else:
obj.properties.content_md5 = None
obj.properties.blobtype = blobtype
self.blobs.append(obj)
def set_next_marker(self, marker):
"""Set the continuation token
Parameters:
marker - next marker
Returns:
Nothing
Raises:
Nothing
"""
if marker is not None and len(marker) > 0:
self.next_marker = marker
class SasBlobService(object):
"""BlobService supporting SAS for functions used in the Python SDK.
create_container method does not exist because it is not a supported
operation under SAS"""
def __init__(self, blobep, saskey, timeout):
"""SAS Blob Service ctor
Parameters:
blobep - blob endpoint
saskey - saskey
timeout - timeout
Returns:
Nothing
Raises:
Nothing
"""
self.blobep = blobep
# normalize sas key
if saskey[0] != '?':
self.saskey = '?' + saskey
else:
self.saskey = saskey
self.timeout = timeout
def _parse_blob_list_xml(self, content):
"""Parse blob list in xml format to an attribute-based object
Parameters:
content - http response content in xml
Returns:
attribute-based object
Raises:
No special exception handling
"""
result = SasBlobList()
root = ET.fromstring(content)
blobs = root.find('Blobs')
for blob in blobs.iter('Blob'):
name = blob.find('Name').text
props = blob.find('Properties')
cl = long(props.find('Content-Length').text)
md5 = props.find('Content-MD5').text
bt = props.find('BlobType').text
metadata = blob.find('Metadata')
mddict = {}
for md in metadata:
mddict[md.tag] = md.text
result.add_blob(name, cl, md5, bt, mddict)
try:
result.set_next_marker(root.find('NextMarker').text)
except Exception:
pass
return result
def list_blobs(
self, container_name, marker=None,
maxresults=_MAX_LISTBLOBS_RESULTS, include=None):
"""List blobs in container
Parameters:
container_name - container name
marker - marker
maxresults - max results
include - optional datasets to include in response
Returns:
List of blobs
Raises:
IOError if unexpected status code
"""
url = '{blobep}{container_name}{saskey}'.format(
blobep=self.blobep, container_name=container_name,
saskey=self.saskey)
reqparams = {
'restype': 'container',
'comp': 'list',
'maxresults': str(maxresults)}
if marker is not None:
reqparams['marker'] = marker
if include is not None:
reqparams['include'] = include
response = azure_request(
requests.get, url=url, params=reqparams, timeout=self.timeout)
response.raise_for_status()
if response.status_code != 200:
raise IOError(
'incorrect status code returned for list_blobs: {}'.format(
response.status_code))
return self._parse_blob_list_xml(response.content)
def get_blob(self, container_name, blob_name, x_ms_range):
"""Get blob
Parameters:
container_name - container name
blob_name - name of blob
x_ms_range - byte range
Returns:
blob content
Raises:
IOError if unexpected status code
"""
url = '{blobep}{container_name}/{blob_name}{saskey}'.format(
blobep=self.blobep, container_name=container_name,
blob_name=blob_name, saskey=self.saskey)
reqheaders = {'x-ms-range': x_ms_range}
response = azure_request(
requests.get, url=url, headers=reqheaders, timeout=self.timeout)
response.raise_for_status()
if response.status_code != 200 and response.status_code != 206:
raise IOError(
'incorrect status code returned for get_blob: {}'.format(
response.status_code))
return response.content
def get_blob_properties(self, container_name, blob_name):
"""Get blob properties
Parameters:
container_name - container name
blob_name - name of blob
Returns:
blob properties (response header)
Raises:
IOError if unexpected status code
"""
url = '{blobep}{container_name}/{blob_name}{saskey}'.format(
blobep=self.blobep, container_name=container_name,
blob_name=blob_name, saskey=self.saskey)
response = azure_request(
requests.head, url=url, timeout=self.timeout)
response.raise_for_status()
if response.status_code != 200:
raise IOError('incorrect status code returned for '
'get_blob_properties: {}'.format(
response.status_code))
return response.headers
def set_blob_metadata(
self, container_name, blob_name, x_ms_meta_name_values):
"""Set blob metadata
Parameters:
container_name - container name
blob_name - name of blob
x_ms_meta_name_values - blob metadata dictionary
Returns:
Nothing
Raises:
IOError if unexpected status code
"""
if x_ms_meta_name_values is None or len(x_ms_meta_name_values) == 0:
return
url = '{blobep}{container_name}/{blob_name}{saskey}'.format(
blobep=self.blobep, container_name=container_name,
blob_name=blob_name, saskey=self.saskey)
reqparams = {'comp': 'metadata'}
reqheaders = {}
for key in x_ms_meta_name_values:
reqheaders['x-ms-meta-' + key] = x_ms_meta_name_values[key]
response = azure_request(
requests.put, url=url, params=reqparams, headers=reqheaders,
timeout=self.timeout)
response.raise_for_status()
if response.status_code != 200:
raise IOError(
'incorrect status code returned for '
'set_blob_metadata: {}'.format(response.status_code))
def put_blob(
self, container_name, blob_name, blob, x_ms_blob_type,
x_ms_blob_content_type, x_ms_blob_content_md5,
x_ms_blob_content_length):
"""Put blob for initializing page blobs
Parameters:
container_name - container name
blob_name - name of blob
blob - should be None for PageBlob (unused)
x_ms_blob_type - should be 'PageBlob' or 'BlockBlob'
x_ms_blob_content_md5 - blob MD5 hash
x_ms_blob_content_type - content-type of blob
x_ms_blob_content_length - content length aligned to
512-byte boundary if PageBlob
Returns:
blob content
Raises:
IOError if unexpected status code
"""
url = '{blobep}{container_name}/{blob_name}{saskey}'.format(
blobep=self.blobep, container_name=container_name,
blob_name=blob_name, saskey=self.saskey)
reqheaders = {
'x-ms-blob-type': x_ms_blob_type}
if x_ms_blob_type == 'PageBlob':
reqheaders['x-ms-blob-content-length'] = str(
x_ms_blob_content_length)
if x_ms_blob_content_md5 is not None:
reqheaders['x-ms-blob-content-md5'] = x_ms_blob_content_md5
if x_ms_blob_content_type is not None:
reqheaders['x-ms-blob-content-type'] = x_ms_blob_content_type
response = azure_request(
requests.put, url=url, headers=reqheaders, timeout=self.timeout)
response.raise_for_status()
if response.status_code != 201:
raise IOError(
'incorrect status code returned for put_blob: {}'.format(
response.status_code))
return response.content
def put_page(
self, container_name, blob_name, page, x_ms_range,
x_ms_page_write, content_md5):
"""Put page for page blob
Parameters:
container_name - container name
blob_name - name of blob
page - page data
x_ms_range - byte range
x_ms_page_write - page write option
content_md5 - md5 hash for page data
Returns:
Nothing
Raises:
IOError if unexpected status code
"""
url = '{blobep}{container_name}/{blob_name}{saskey}'.format(
blobep=self.blobep, container_name=container_name,
blob_name=blob_name, saskey=self.saskey)
reqheaders = {
'x-ms-range': x_ms_range,
'x-ms-page-write': x_ms_page_write,
'Content-MD5': content_md5}
reqparams = {'comp': 'page'}
response = azure_request(
requests.put, url=url, params=reqparams, headers=reqheaders,
data=page, timeout=self.timeout)
response.raise_for_status()
if response.status_code != 201:
raise IOError(
'incorrect status code returned for put_page: {}'.format(
response.status_code))
def put_block(
self, container_name, blob_name, block, blockid, content_md5):
"""Put block for blob
Parameters:
container_name - container name
blob_name - name of blob
block - block data
blockid - block id
content_md5 - md5 hash for block data
Returns:
Nothing
Raises:
IOError if unexpected status code
"""
url = '{blobep}{container_name}/{blob_name}{saskey}'.format(
blobep=self.blobep, container_name=container_name,
blob_name=blob_name, saskey=self.saskey)
reqheaders = {'Content-MD5': content_md5}
reqparams = {'comp': 'block', 'blockid': blockid}
response = azure_request(
requests.put, url=url, params=reqparams, headers=reqheaders,
data=block, timeout=self.timeout)
response.raise_for_status()
if response.status_code != 201:
raise IOError(
'incorrect status code returned for put_block: {}'.format(
response.status_code))
def put_block_list(
self, container_name, blob_name, block_list,
x_ms_blob_content_type, x_ms_blob_content_md5):
"""Put block list for blob
Parameters:
container_name - container name
blob_name - name of blob
block_list - block list for blob
x_ms_blob_content_md5 - md5 hash for blob
Returns:
Nothing
Raises:
IOError if unexpected status code
"""
url = '{blobep}{container_name}/{blob_name}{saskey}'.format(
blobep=self.blobep, container_name=container_name,
blob_name=blob_name, saskey=self.saskey)
reqheaders = {'x-ms-blob-content-md5': x_ms_blob_content_md5}
if x_ms_blob_content_type is not None:
reqheaders['x-ms-blob-content-type'] = x_ms_blob_content_type
reqparams = {'comp': 'blocklist'}
body = ['<?xml version="1.0" encoding="utf-8"?><BlockList>']
for block in block_list:
body.append('<Latest>{}</Latest>'.format(block))
body.append('</BlockList>')
response = azure_request(
requests.put, url=url, params=reqparams, headers=reqheaders,
data=''.join(body), timeout=self.timeout)
response.raise_for_status()
if response.status_code != 201:
raise IOError(
'incorrect status code returned for put_block_list: {}'.format(
response.status_code))
def set_blob_properties(
self, container_name, blob_name, x_ms_blob_content_md5):
"""Sets blob properties (MD5 only)
Parameters:
container_name - container name
blob_name - name of blob
x_ms_blob_content_md5 - md5 hash for blob
Returns:
Nothing
Raises:
IOError if unexpected status code
"""
url = '{blobep}{container_name}/{blob_name}{saskey}'.format(
blobep=self.blobep, container_name=container_name,
blob_name=blob_name, saskey=self.saskey)
reqheaders = {'x-ms-blob-content-md5': x_ms_blob_content_md5}
reqparams = {'comp': 'properties'}
response = azure_request(
requests.put, url=url, params=reqparams, headers=reqheaders,
timeout=self.timeout)
response.raise_for_status()
if response.status_code != 200:
raise IOError('incorrect status code returned for '
'set_blob_properties: {}'.format(
response.status_code))
def delete_blob(
self, container_name, blob_name):
"""Deletes a blob
Parameters:
container_name - container name
blob_name - name of blob
Returns:
Nothing
Raises:
IOError if unexpected status code
"""
url = '{blobep}{container_name}/{blob_name}{saskey}'.format(
blobep=self.blobep, container_name=container_name,
blob_name=blob_name, saskey=self.saskey)
response = azure_request(
requests.delete, url=url, timeout=self.timeout)
response.raise_for_status()
if response.status_code != 202:
raise IOError(
'incorrect status code returned for delete_blob: {}'.format(
response.status_code))
class BlobChunkWorker(threading.Thread):
"""Chunk worker for a Blob"""
def __init__(
self, exc, s_in_queue, s_out_queue, args, blob_service,
xfertoazure):
"""Blob Chunk worker Thread ctor
Parameters:
exc - exception list
s_in_queue - storage in queue
s_out_queue - storage out queue
args - program arguments
blob_service - blob service
xfertoazure - xfer to azure (direction)
Returns:
Nothing
Raises:
Nothing
"""
threading.Thread.__init__(self)
self.terminate = False
self._exc = exc
self._in_queue = s_in_queue
self._out_queue = s_out_queue
self._pageblob = args.pageblob
self._autovhd = args.autovhd
self.blob_service = blob_service
self.timeout = args.timeout
self.xfertoazure = xfertoazure
self.rsaprivatekey = args.rsaprivatekey
self.rsapublickey = args.rsapublickey
self.encmode = args.encmode
def run(self):
"""Thread code
Parameters:
Nothing
Returns:
Nothing
Raises:
Nothing
"""
while not self.terminate:
try:
pri, (localresource, container, remoteresource, blockid,
offset, bytestoxfer, encparam, flock, filedesc) = \
self._in_queue.get_nowait()
except queue.Empty:
break
# detect termination early and break if necessary
if self.terminate:
break
try:
if self.xfertoazure:
# if iv is not ready for this chunk, re-add back to queue
if (not as_page_blob(
self._pageblob, self._autovhd, localresource) and
((self.rsaprivatekey is not None or
self.rsapublickey is not None) and
self.encmode == _ENCRYPTION_MODE_FULLBLOB)):
_iblockid = int(blockid)
if _iblockid not in encparam[2]:
self._in_queue.put(
PqTupleSort((
pri,
(localresource, container, remoteresource,
blockid, offset, bytestoxfer, encparam,
flock, filedesc))))
continue
# upload block/page
self.putblobdata(
localresource, container, remoteresource, blockid,
offset, bytestoxfer, encparam, flock, filedesc)
else:
# download range
self.getblobrange(
localresource, container, remoteresource, blockid,
offset, bytestoxfer, encparam, flock, filedesc)
# pylint: disable=W0703
except Exception:
# pylint: enable=W0703
self._exc.append(traceback.format_exc())
self._out_queue.put((localresource, encparam))
if len(self._exc) > 0:
break
def putblobdata(
self, localresource, container, remoteresource, blockid, offset,
bytestoxfer, encparam, flock, filedesc):
"""Puts data (blob or page) into Azure storage
Parameters:
localresource - name of local resource
container - blob container
remoteresource - name of remote resource
blockid - block id (ignored for page blobs)
offset - file offset
bytestoxfer - number of bytes to xfer
encparam - encryption metadata: (symkey, signkey, ivmap, pad)
flock - file lock
filedesc - file handle
Returns:
Nothing
Raises:
IOError if file cannot be read
"""
# if bytestoxfer is zero, then we're transferring a zero-byte
# file, use put blob instead of page/block ops
if bytestoxfer == 0:
contentmd5 = compute_md5_for_data_asbase64(b'')
if as_page_blob(self._pageblob, self._autovhd, localresource):
blob_type = 'PageBlob'
contentlength = bytestoxfer
else:
blob_type = 'BlockBlob'
contentlength = None
azure_request(
self.blob_service.put_blob, container_name=container,
blob_name=remoteresource, blob=None, x_ms_blob_type=blob_type,
x_ms_blob_content_md5=contentmd5,
x_ms_blob_content_length=contentlength,
x_ms_blob_content_type=get_mime_type(localresource))
return
# read the file at specified offset, must take lock
data = None
with flock:
closefd = False
if not filedesc:
filedesc = open(localresource, 'rb')
closefd = True
filedesc.seek(offset, 0)
data = filedesc.read(bytestoxfer)
if closefd:
filedesc.close()
if not data:
raise IOError('could not read {}: {} -> {}'.format(
localresource, offset, offset + bytestoxfer))
# issue REST put
if as_page_blob(self._pageblob, self._autovhd, localresource):
aligned = page_align_content_length(bytestoxfer)
# fill data to boundary
if aligned != bytestoxfer:
data = data.ljust(aligned, b'\0')
# compute page md5
contentmd5 = compute_md5_for_data_asbase64(data)
# check if this page is empty
if contentmd5 == _EMPTY_MAX_PAGE_SIZE_MD5:
return
elif len(data) != _MAX_BLOB_CHUNK_SIZE_BYTES:
data_chk = b'\0' * len(data)
data_chk_md5 = compute_md5_for_data_asbase64(data_chk)
del data_chk
if data_chk_md5 == contentmd5:
return
del data_chk_md5
# upload page range
rangestr = 'bytes={}-{}'.format(offset, offset + aligned - 1)
azure_request(
self.blob_service.put_page, container_name=container,
blob_name=remoteresource, page=data, x_ms_range=rangestr,
x_ms_page_write='update', content_md5=contentmd5,
timeout=self.timeout)
else:
# encrypt block if required
if (encparam is not None and
(self.rsaprivatekey is not None or
self.rsapublickey is not None)):
symkey = encparam[0]
signkey = encparam[1]
if self.encmode == _ENCRYPTION_MODE_FULLBLOB:
_blkid = int(blockid)
iv = encparam[2][_blkid]
pad = encparam[3]
else:
iv = None
pad = True
data = encrypt_chunk(
symkey, signkey, data, self.encmode, iv=iv, pad=pad)
with flock:
if self.encmode == _ENCRYPTION_MODE_FULLBLOB:
# compute hmac for chunk
if _blkid == 0:
encparam[2]['hmac'].update(iv + data)
else:
encparam[2]['hmac'].update(data)
# store iv for next chunk
encparam[2][_blkid + 1] = data[
len(data) - _AES256_BLOCKSIZE_BYTES:]
# compute md5 for encrypted data chunk
encparam[2]['md5'].update(data)
# compute block md5
contentmd5 = compute_md5_for_data_asbase64(data)
azure_request(
self.blob_service.put_block, container_name=container,