def GetServiceAccount(self, account): account_uri = ('http://metadata.google.internal/computeMetadata/' 'v1/instance/service-accounts') additional_headers = {'X-Google-Metadata-Request': 'True'} request = urllib2.Request(account_uri, headers=additional_headers) try: response = urllib2.urlopen(request) except urllib2.URLError as e: raise exceptions.CommunicationError( 'Could not reach metadata service: %s' % e.reason) response_lines = [ line.rstrip('/\n\r') for line in response.readlines() ] return account in response_lines
def GetInstanceScopes(self): # Extra header requirement can be found here: # https://developers.google.com/compute/docs/metadata scopes_uri = ( 'http://metadata.google.internal/computeMetadata/v1/instance/' 'service-accounts/%s/scopes') % self.__service_account_name additional_headers = {'X-Google-Metadata-Request': 'True'} request = urllib2.Request(scopes_uri, headers=additional_headers) try: response = urllib2.urlopen(request) except urllib2.URLError as e: raise exceptions.CommunicationError( 'Could not reach metadata service: %s' % e.reason) return util.NormalizeScopes(scope.strip() for scope in response.readlines())
def __StreamMedia(self, callback=None, finish_callback=None, additional_headers=None, use_chunks=True): """Helper function for StreamMedia / StreamInChunks.""" if self.strategy != RESUMABLE_UPLOAD: raise exceptions.InvalidUserInputError( 'Cannot stream non-resumable upload') callback = callback or self._ArgPrinter finish_callback = finish_callback or self._CompletePrinter # final_response is set if we resumed an already-completed upload. response = self.__final_response send_func = self.__SendChunk if use_chunks else self.__SendMediaBody if use_chunks: self.__ValidateChunksize(self.chunksize) self.EnsureInitialized() while not self.complete: response = send_func(self.stream.tell(), additional_headers=additional_headers) if response.status_code in (httplib.OK, httplib.CREATED): self.__complete = True break self.__progress = self.__GetLastByte(response.info['range']) if self.progress + 1 != self.stream.tell(): # TODO: Add a better way to recover here. raise exceptions.CommunicationError( 'Failed to transfer all bytes in chunk, upload paused at byte ' '%d' % self.progress) self._ExecuteCallback(callback, response) if self.__complete: # TODO: Decide how to handle errors in the non-seekable case. current_pos = self.stream.tell() self.stream.seek(0, os.SEEK_END) end_pos = self.stream.tell() self.stream.seek(current_pos) if current_pos != end_pos: raise exceptions.TransferInvalidError( 'Upload complete with %s additional bytes left in stream' % (long(end_pos) - long(current_pos))) self._ExecuteCallback(finish_callback, response) return response
def _refresh(self, do_request): # pylint: disable=g-bad-name """Refresh self.access_token. Args: do_request: A function matching httplib2.Http.request's signature. """ token_uri = ( 'http://metadata.google.internal/computeMetadata/v1/instance/' 'service-accounts/%s/token') % self.__service_account_name extra_headers = {'X-Google-Metadata-Request': 'True'} request = urllib2.Request(token_uri, headers=extra_headers) try: content = urllib2.urlopen(request).read() except urllib2.URLError as e: raise exceptions.CommunicationError( 'Could not reach metadata service: %s' % e.reason) try: credential_info = json.loads(content) except ValueError: raise exceptions.CredentialsError( 'Invalid credentials response: uri %s' % token_uri) self.access_token = credential_info['access_token']