1 # Copyright (c) 2015 The Chromium Authors. All rights reserved. 2 # Use of this source code is governed by a BSD-style license that can be 3 # found in the LICENSE file. 4 import os 5 import subprocess 6 import sys 7 8 _GSUTIL_PATH = os.path.abspath( 9 os.path.join( 10 os.path.dirname(__file__), 11 '..', '..', 'third_party', 'gsutil', 'gsutil')) 12 13 14 class CloudStorageError(Exception): 15 16 @staticmethod 17 def _GetConfigInstructions(): 18 command = _GSUTIL_PATH 19 return ('To configure your credentials:\n' 20 ' 1. Run "%s config" and follow its instructions.\n' 21 ' 2. If you have a @google.com account, use that account.\n' 22 ' 3. For the project-id, just enter 0.' % command) 23 24 25 class PermissionError(CloudStorageError): 26 27 def __init__(self): 28 super(PermissionError, self).__init__( 29 'Attempted to access a file from Cloud Storage but you don\'t ' 30 'have permission. ' + self._GetConfigInstructions()) 31 32 33 class CredentialsError(CloudStorageError): 34 35 def __init__(self): 36 super(CredentialsError, self).__init__( 37 'Attempted to access a file from Cloud Storage but you have no ' 38 'configured credentials. ' + self._GetConfigInstructions()) 39 40 41 class NotFoundError(CloudStorageError): 42 pass 43 44 45 class ServerError(CloudStorageError): 46 pass 47 48 49 def Copy(src, dst): 50 # TODO(simonhatch): switch to use py_utils.cloud_storage. 51 args = [sys.executable, _GSUTIL_PATH, 'cp', src, dst] 52 gsutil = subprocess.Popen(args, stdout=subprocess.PIPE, 53 stderr=subprocess.PIPE) 54 _, stderr = gsutil.communicate() 55 56 if gsutil.returncode: 57 if stderr.startswith(( 58 'You are attempting to access protected data with no configured', 59 'Failure: No handler was ready to authenticate.')): 60 raise CredentialsError() 61 if ('status=403' in stderr or 'status 403' in stderr or 62 '403 Forbidden' in stderr): 63 raise PermissionError() 64 if (stderr.startswith('InvalidUriError') or 'No such object' in stderr or 65 'No URLs matched' in stderr or 66 'One or more URLs matched no' in stderr): 67 raise NotFoundError(stderr) 68 if '500 Internal Server Error' in stderr: 69 raise ServerError(stderr) 70 raise CloudStorageError(stderr) 71 return gsutil.returncode 72