Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(462)

Side by Side Diff: gslib/cloud_api.py

Issue 698893003: Update checked in version of gsutil to version 4.6 (Closed) Base URL: http://dart.googlecode.com/svn/third_party/gsutil/
Patch Set: Created 6 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « gslib/cat_helper.py ('k') | gslib/cloud_api_delegator.py » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
Property Changes:
Added: svn:eol-style
+ LF
OLDNEW
(Empty)
1 # -*- coding: utf-8 -*-
2 # Copyright 2013 Google Inc. All Rights Reserved.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 """Gsutil API for interacting with cloud storage providers."""
16
17 from __future__ import absolute_import
18
19
20 class CloudApi(object):
21 """Abstract base class for interacting with cloud storage providers.
22
23 Implementations of the gsutil Cloud API are not guaranteed to be thread-safe.
24 Behavior when calling a gsutil Cloud API instance simultaneously across
25 threads is undefined and doing so will likely cause errors. Therefore,
26 a separate instance of the gsutil Cloud API should be instantiated per-thread.
27 """
28
29 def __init__(self, bucket_storage_uri_class, logger, provider=None, debug=0):
30 """Performs necessary setup for interacting with the cloud storage provider.
31
32 Args:
33 bucket_storage_uri_class: boto storage_uri class, used by APIs that
34 provide boto translation or mocking.
35 logger: logging.logger for outputting log messages.
36 provider: Default provider prefix describing cloud storage provider to
37 connect to.
38 debug: Debug level for the API implementation (0..3).
39 """
40 self.bucket_storage_uri_class = bucket_storage_uri_class
41 self.logger = logger
42 self.provider = provider
43 self.debug = debug
44
45 def GetBucket(self, bucket_name, provider=None, fields=None):
46 """Gets Bucket metadata.
47
48 Args:
49 bucket_name: Name of the bucket.
50 provider: Cloud storage provider to connect to. If not present,
51 class-wide default is used.
52 fields: If present, return only these Bucket metadata fields, for
53 example, ['logging', 'defaultObjectAcl']
54
55 Raises:
56 ArgumentException for errors during input validation.
57 ServiceException for errors interacting with cloud storage providers.
58
59 Returns:
60 Bucket object.
61 """
62 raise NotImplementedError('GetBucket must be overloaded')
63
64 def ListBuckets(self, project_id=None, provider=None, fields=None):
65 """Lists bucket metadata for the given project.
66
67 Args:
68 project_id: Project owning the buckets, default from config if None.
69 provider: Cloud storage provider to connect to. If not present,
70 class-wide default is used.
71 fields: If present, return only these metadata fields for the listing,
72 for example:
73 ['items/logging', 'items/defaultObjectAcl'].
74 Note that the WildcardIterator class should be used to list
75 buckets instead of calling this function directly. It amends
76 the fields definition from get-like syntax such as
77 ['logging', 'defaultObjectAcl'] so that the caller does not
78 need to prepend 'items/' or specify fields necessary for listing
79 (like nextPageToken).
80
81 Raises:
82 ArgumentException for errors during input validation.
83 ServiceException for errors interacting with cloud storage providers.
84
85 Returns:
86 Iterator over Bucket objects.
87 """
88 raise NotImplementedError('ListBuckets must be overloaded')
89
90 def PatchBucket(self, bucket_name, metadata, preconditions=None,
91 provider=None, fields=None):
92 """Updates bucket metadata for the bucket with patch semantics.
93
94 Args:
95 bucket_name: Name of bucket to update.
96 metadata: Bucket object defining metadata to be updated.
97 preconditions: Preconditions for the request.
98 provider: Cloud storage provider to connect to. If not present,
99 class-wide default is used.
100 fields: If present, return only these Bucket metadata fields.
101
102 Raises:
103 ArgumentException for errors during input validation.
104 ServiceException for errors interacting with cloud storage providers.
105
106 Returns:
107 Bucket object describing new bucket metadata.
108 """
109 raise NotImplementedError('PatchBucket must be overloaded')
110
111 def CreateBucket(self, bucket_name, project_id=None, metadata=None,
112 provider=None, fields=None):
113 """Creates a new bucket with the specified metadata.
114
115 Args:
116 bucket_name: Name of the new bucket.
117 project_id: Project owner of the new bucket, default from config if None.
118 metadata: Bucket object defining new bucket metadata.
119 provider: Cloud storage provider to connect to. If not present,
120 class-wide default is used.
121 fields: If present, return only these Bucket metadata fields.
122
123 Raises:
124 ArgumentException for errors during input validation.
125 ServiceException for errors interacting with cloud storage providers.
126
127 Returns:
128 Bucket object describing new bucket metadata.
129 """
130 raise NotImplementedError('CreateBucket must be overloaded')
131
132 def DeleteBucket(self, bucket_name, preconditions=None, provider=None):
133 """Deletes a bucket.
134
135 Args:
136 bucket_name: Name of the bucket to delete.
137 preconditions: Preconditions for the request.
138 provider: Cloud storage provider to connect to. If not present,
139 class-wide default is used.
140
141 Raises:
142 ArgumentException for errors during input validation.
143 ServiceException for errors interacting with cloud storage providers.
144
145 Returns:
146 None.
147 """
148 raise NotImplementedError('DeleteBucket must be overloaded')
149
150 class CsObjectOrPrefixType(object):
151 """Enum class for describing CsObjectOrPrefix types."""
152 OBJECT = 'object' # Cloud object
153 PREFIX = 'prefix' # Cloud bucket subdirectory
154
155 class CsObjectOrPrefix(object):
156 """Container class for ListObjects results."""
157
158 def __init__(self, data, datatype):
159 """Stores a ListObjects result.
160
161 Args:
162 data: Root object, either an apitools Object or a string Prefix.
163 datatype: CsObjectOrPrefixType of data.
164 """
165 self.data = data
166 self.datatype = datatype
167
168 def ListObjects(self, bucket_name, prefix=None, delimiter=None,
169 all_versions=None, provider=None, fields=None):
170 """Lists objects (with metadata) and prefixes in a bucket.
171
172 Args:
173 bucket_name: Bucket containing the objects.
174 prefix: Prefix for directory-like behavior.
175 delimiter: Delimiter for directory-like behavior.
176 all_versions: If true, list all object versions.
177 provider: Cloud storage provider to connect to. If not present,
178 class-wide default is used.
179 fields: If present, return only these metadata fields for the listing,
180 for example:
181 ['items/acl', 'items/updated', 'prefixes'].
182 Note that the WildcardIterator class should be used to list
183 objects instead of calling this function directly. It amends
184 the fields definition from get-like syntax such as
185 ['acl', 'updated'] so that the caller does not need to
186 prepend 'items/' or specify any fields necessary for listing
187 (such as prefixes or nextPageToken).
188
189 Raises:
190 ArgumentException for errors during input validation.
191 ServiceException for errors interacting with cloud storage providers.
192
193 Returns:
194 Iterator over CsObjectOrPrefix wrapper class.
195 """
196 raise NotImplementedError('ListObjects must be overloaded')
197
198 def GetObjectMetadata(self, bucket_name, object_name, generation=None,
199 provider=None, fields=None):
200 """Gets object metadata.
201
202 Args:
203 bucket_name: Bucket containing the object.
204 object_name: Object name.
205 generation: Generation of the object to retrieve.
206 provider: Cloud storage provider to connect to. If not present,
207 class-wide default is used.
208 fields: If present, return only these Object metadata fields, for
209 example, ['acl', 'updated'].
210
211 Raises:
212 ArgumentException for errors during input validation.
213 ServiceException for errors interacting with cloud storage providers.
214
215 Returns:
216 Object object.
217 """
218 raise NotImplementedError('GetObjectMetadata must be overloaded')
219
220 def PatchObjectMetadata(self, bucket_name, object_name, metadata,
221 generation=None, preconditions=None, provider=None,
222 fields=None):
223 """Updates object metadata with patch semantics.
224
225 Args:
226 bucket_name: Bucket containing the object.
227 object_name: Object name for object.
228 metadata: Object object defining metadata to be updated.
229 generation: Generation (or version) of the object to update.
230 preconditions: Preconditions for the request.
231 provider: Cloud storage provider to connect to. If not present,
232 class-wide default is used.
233 fields: If present, return only these Object metadata fields.
234
235 Raises:
236 ArgumentException for errors during input validation.
237 ServiceException for errors interacting with cloud storage providers.
238
239 Returns:
240 Updated object metadata.
241 """
242 raise NotImplementedError('PatchObjectMetadata must be overloaded')
243
244 class DownloadStrategy(object):
245 """Enum class for specifying download strategy."""
246 ONE_SHOT = 'oneshot'
247 RESUMABLE = 'resumable'
248
249 def GetObjectMedia(self, bucket_name, object_name, download_stream,
250 provider=None, generation=None, object_size=None,
251 download_strategy=DownloadStrategy.ONE_SHOT, start_byte=0,
252 end_byte=None, progress_callback=None,
253 serialization_data=None, digesters=None):
254 """Gets object data.
255
256 Args:
257 bucket_name: Bucket containing the object.
258 object_name: Object name.
259 download_stream: Stream to send the object data to.
260 provider: Cloud storage provider to connect to. If not present,
261 class-wide default is used.
262 generation: Generation of the object to retrieve.
263 object_size: Total size of the object being downloaded.
264 download_strategy: Cloud API download strategy to use for download.
265 start_byte: Starting point for download (for resumable downloads and
266 range requests). Can be set to negative to request a range
267 of bytes (python equivalent of [:-3])
268 end_byte: Ending point for download (for range requests).
269 progress_callback: Optional callback function for progress notifications.
270 Receives calls with arguments
271 (bytes_transferred, total_size).
272 serialization_data: Implementation-specific dict containing serialization
273 information for the download.
274 digesters: Dict of {string : digester}, where string is a name of a hash
275 algorithm, and digester is a validation digester that supports
276 update(bytes) and digest() using that algorithm.
277 Implementation can set the digester value to None to indicate
278 bytes were not successfully digested on-the-fly.
279
280 Raises:
281 ArgumentException for errors during input validation.
282 ServiceException for errors interacting with cloud storage providers.
283
284 Returns:
285 Content-encoding string if it was detected that the server sent an encoded
286 object during transfer, None otherwise.
287 """
288 raise NotImplementedError('GetObjectMedia must be overloaded')
289
290 def UploadObject(self, upload_stream, object_metadata, canned_acl=None,
291 size=None, preconditions=None, progress_callback=None,
292 provider=None, fields=None):
293 """Uploads object data and metadata.
294
295 Args:
296 upload_stream: Seekable stream of object data.
297 object_metadata: Object metadata for new object. Must include bucket
298 and object name.
299 canned_acl: Optional canned ACL to apply to object. Overrides ACL set
300 in object_metadata.
301 size: Optional object size.
302 preconditions: Preconditions for the request.
303 progress_callback: Optional callback function for progress notifications.
304 Receives calls with arguments
305 (bytes_transferred, total_size).
306 provider: Cloud storage provider to connect to. If not present,
307 class-wide default is used.
308 fields: If present, return only these Object metadata fields.
309
310 Raises:
311 ArgumentException for errors during input validation.
312 ServiceException for errors interacting with cloud storage providers.
313
314 Returns:
315 Object object for newly created destination object.
316 """
317 raise NotImplementedError('UploadObject must be overloaded')
318
319 def UploadObjectStreaming(self, upload_stream, object_metadata,
320 canned_acl=None, preconditions=None,
321 progress_callback=None, provider=None,
322 fields=None):
323 """Uploads object data and metadata.
324
325 Args:
326 upload_stream: Stream of object data. May not be seekable.
327 object_metadata: Object metadata for new object. Must include bucket
328 and object name.
329 canned_acl: Optional canned ACL to apply to object. Overrides ACL set
330 in object_metadata.
331 preconditions: Preconditions for the request.
332 progress_callback: Optional callback function for progress notifications.
333 Receives calls with arguments
334 (bytes_transferred, total_size), but fills in only
335 bytes_transferred.
336 provider: Cloud storage provider to connect to. If not present,
337 class-wide default is used.
338 fields: If present, return only these Object metadata fields.
339
340 Raises:
341 ArgumentException for errors during input validation.
342 ServiceException for errors interacting with cloud storage providers.
343
344 Returns:
345 Object object for newly created destination object.
346 """
347 raise NotImplementedError('UploadObject must be overloaded')
348
349 def UploadObjectResumable(
350 self, upload_stream, object_metadata, canned_acl=None,
351 size=None, preconditions=None, serialization_data=None,
352 tracker_callback=None, progress_callback=None, provider=None,
353 fields=None):
354 """Uploads object data and metadata using a resumable upload strategy.
355
356 Args:
357 upload_stream: Seekable stream of object data.
358 object_metadata: Object metadata for new object. Must include bucket
359 and object name.
360 canned_acl: Optional canned ACL to apply to object. Overrides ACL set
361 in object_metadata.
362 size: Total size of the object.
363 preconditions: Preconditions for the request.
364 serialization_data: Dict of {'url' : UploadURL} allowing for uploads to
365 be resumed.
366 tracker_callback: Callback function taking a upload URL string.
367 Guaranteed to be called when the implementation gets an
368 upload URL, allowing the caller to resume the upload
369 across process breaks by saving the upload URL in
370 a tracker file.
371 progress_callback: Optional callback function for progress notifications.
372 Receives calls with arguments
373 (bytes_transferred, total_size).
374 provider: Cloud storage provider to connect to. If not present,
375 class-wide default is used.
376 fields: If present, return only these Object metadata fields when the
377 upload is complete.
378
379 Raises:
380 ArgumentException for errors during input validation.
381 ServiceException for errors interacting with cloud storage providers.
382
383 Returns:
384 Object object for newly created destination object.
385 """
386 raise NotImplementedError('UploadObjectResumable must be overloaded')
387
388 def CopyObject(self, src_bucket_name, src_obj_name, dst_obj_metadata,
389 src_generation=None, canned_acl=None, preconditions=None,
390 provider=None, fields=None):
391 """Copies an object in the cloud.
392
393 Args:
394 src_bucket_name: Bucket containing the source object
395 src_obj_name: Name of the source object.
396 dst_obj_metadata: Object metadata for new object. Must include bucket
397 and object name.
398 src_generation: Generation of the source object to copy.
399 canned_acl: Optional canned ACL to apply to destination object. Overrides
400 ACL set in dst_obj_metadata.
401 preconditions: Destination object preconditions for the request.
402 provider: Cloud storage provider to connect to. If not present,
403 class-wide default is used.
404 fields: If present, return only these Object metadata fields.
405
406 Raises:
407 ArgumentException for errors during input validation.
408 ServiceException for errors interacting with cloud storage providers.
409
410 Returns:
411 Object object for newly created destination object.
412 """
413 raise NotImplementedError('CopyObject must be overloaded')
414
415 def ComposeObject(self, src_objs_metadata, dst_obj_metadata,
416 preconditions=None, provider=None, fields=None):
417 """Composes an object in the cloud.
418
419 Args:
420 src_objs_metadata: List of ComposeRequest.SourceObjectsValueListEntries
421 specifying the objects to compose.
422 dst_obj_metadata: Metadata for the destination object including bucket
423 and object name.
424 preconditions: Destination object preconditions for the request.
425 provider: Cloud storage provider to connect to. If not present,
426 class-wide default is used.
427 fields: If present, return only these Object metadata fields.
428
429 Raises:
430 ArgumentException for errors during input validation.
431 ServiceException for errors interacting with cloud storage providers.
432
433 Returns:
434 Composed object metadata.
435 """
436 raise NotImplementedError('ComposeObject must be overloaded')
437
438 def DeleteObject(self, bucket_name, object_name, preconditions=None,
439 generation=None, provider=None):
440 """Deletes an object.
441
442 Args:
443 bucket_name: Name of the containing bucket.
444 object_name: Name of the object to delete.
445 preconditions: Preconditions for the request.
446 generation: Generation (or version) of the object to delete; if None,
447 deletes the live object.
448 provider: Cloud storage provider to connect to. If not present,
449 class-wide default is used.
450
451 Raises:
452 ArgumentException for errors during input validation.
453 ServiceException for errors interacting with cloud storage providers.
454
455 Returns:
456 None.
457 """
458 raise NotImplementedError('DeleteObject must be overloaded')
459
460 def WatchBucket(self, bucket_name, address, channel_id, token=None,
461 provider=None, fields=None):
462 """Creates a notification subscription for changes to objects in a bucket.
463
464 Args:
465 bucket_name: Bucket containing the objects.
466 address: Address to which to send notifications.
467 channel_id: Unique ID string for the channel.
468 token: If present, token string is delivered with each notification.
469 provider: Cloud storage provider to connect to. If not present,
470 class-wide default is used.
471 fields: If present, return only these Channel metadata fields.
472
473 Raises:
474 ArgumentException for errors during input validation.
475 ServiceException for errors interacting with cloud storage providers.
476
477 Returns:
478 Channel object describing the notification subscription.
479 """
480 raise NotImplementedError('WatchBucket must be overloaded')
481
482 def StopChannel(self, channel_id, resource_id, provider=None):
483 """Stops a notification channel.
484
485 Args:
486 channel_id: Unique ID string for the channel.
487 resource_id: Version-agnostic ID string for the channel.
488 provider: Cloud storage provider to connect to. If not present,
489 class-wide default is used.
490
491 Raises:
492 ArgumentException for errors during input validation.
493 ServiceException for errors interacting with cloud storage providers.
494
495 Returns:
496 None.
497 """
498 raise NotImplementedError('StopChannel must be overloaded')
499
500
501 class Preconditions(object):
502 """Preconditions class for specifying preconditions to cloud API requests."""
503
504 def __init__(self, gen_match=None, meta_gen_match=None):
505 """Instantiates a Preconditions object.
506
507 Args:
508 gen_match: Perform request only if generation of target object
509 matches the given integer. Ignored for bucket requests.
510 meta_gen_match: Perform request only if metageneration of target
511 object/bucket matches the given integer.
512 """
513 self.gen_match = gen_match
514 self.meta_gen_match = meta_gen_match
515
516
517 class ArgumentException(Exception):
518 """Exception raised when arguments to a Cloud API method are invalid.
519
520 This exception is never raised as a result of a failed call to a cloud
521 storage provider.
522 """
523
524 def __init__(self, reason):
525 Exception.__init__(self)
526 self.reason = reason
527
528 def __repr__(self):
529 return str(self)
530
531 def __str__(self):
532 return '%s: %s' % (self.__class__.__name__, self.reason)
533
534
535 class ProjectIdException(ArgumentException):
536 """Exception raised when a Project ID argument is required but not present."""
537
538
539 class ServiceException(Exception):
540 """Exception raised when a cloud storage provider request fails.
541
542 This exception is raised only as a result of a failed remote call.
543 """
544
545 def __init__(self, reason, status=None, body=None):
546 Exception.__init__(self)
547 self.reason = reason
548 self.status = status
549 self.body = body
550
551 def __repr__(self):
552 return str(self)
553
554 def __str__(self):
555 message = '%s:' % self.__class__.__name__
556 if self.status:
557 message += ' %s' % self.status
558 message += ' %s' % self.reason
559 if self.body:
560 message += '\n%s' % self.body
561 return message
562
563
564 class RetryableServiceException(ServiceException):
565 """Exception class for retryable exceptions."""
566
567
568 class ResumableDownloadException(RetryableServiceException):
569 """Exception raised for resumable downloads that can be retried later."""
570
571
572 class ResumableUploadException(RetryableServiceException):
573 """Exception raised for resumable uploads that can be retried later."""
574
575
576 class ResumableUploadAbortException(ServiceException):
577 """Exception raised for resumable uploads that cannot be retried later."""
578
579
580 class AuthenticationException(ServiceException):
581 """Exception raised for errors during the authentication process."""
582
583
584 class PreconditionException(ServiceException):
585 """Exception raised for precondition failures."""
586
587
588 class NotFoundException(ServiceException):
589 """Exception raised when a resource is not found (404)."""
590
591
592 class NotEmptyException(ServiceException):
593 """Exception raised when trying to delete a bucket is not empty."""
594
595
596 class BadRequestException(ServiceException):
597 """Exception raised for malformed requests.
598
599 Where it is possible to detect invalid arguments prior to sending them
600 to the server, an ArgumentException should be raised instead.
601 """
602
603
604 class AccessDeniedException(ServiceException):
605 """Exception raised when authenticated user has insufficient access rights.
606
607 This is raised when the authentication process succeeded but the
608 authenticated user does not have access rights to the requested resource.
609 """
610
611
OLDNEW
« no previous file with comments | « gslib/cat_helper.py ('k') | gslib/cloud_api_delegator.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698