def __enter__(self): """Creates a fake metadata environment.""" log.Print('Surfacing credentials via {metadata}...'.format( metadata=self.name)) # Use JSON to inject structured data into the YAML since it # is an effective way to create indentation-insensitive YAML # NOTE: YAML 1.2 is a superset of JSON. with open(self.manifest_file, 'w') as f_out: f_out.write( MANIFEST_FORMAT.format( attributes=json.dumps(self._options.attributes), project_id=self._options.project, email=self._options.account, scopes=json.dumps(self._options.scopes))) # We refresh credentials in case a pull is needed. docker.UpdateDockerCredentials(constants.DEFAULT_REGISTRY) result = docker.Execute([ 'run', '-d', '--name', self.name, '-v', self.manifest_file + ':' + self.manifest_file, self.image, # Arguments to the //cloud/containers/metadata binary, # which is the entrypoint: '-manifest_file=' + self.manifest_file, '-refresh_token=' + self._options.credential.refresh_token ]) if result != 0: raise exceptions.Error('Unable to launch fake-metadata.') return self
def __exit__(self, type, value, traceback): """Cleans up a fake metadata environment.""" log.Print('Shutting down metadata credentials') result = docker.Execute(['rm', '-f', self.name]) if result != 0: raise exceptions.Error('Unable to tear down fake-metadata.') # Clean up the temporary file. os.remove(self.manifest_file)
def Run(self, args): """Executes the given docker command, after refreshing our credentials. Args: args: An argparse.Namespace that contains the values for the arguments specified in the .Args() method. Raises: exceptions.ExitCodeNoError: The docker command execution failed. """ force_refresh = True for server in args.server: if server not in _DEFAULT_REGISTRIES: log.warn( 'Authenticating to a non-default server: {server}.'.format( server=server)) docker.UpdateDockerCredentials(server, refresh=force_refresh) # Only force a refresh for the first server we authorize force_refresh = False if args.authorize_only: # NOTE: We don't know at this point how long the access token we have # placed in the docker configuration will last. More information needs # to be exposed from all credential kinds in order for us to have an # accurate awareness of lifetime here. log.err.Print('Short-lived access for {server} configured.'.format( server=args.server)) return # TODO(user): reconcile with the 'gcloud app' docker stuff, # which should be using a gcloud config property. docker_args = args.docker_args or [] docker_args = (docker_args if not args.docker_host else ['-H', args.docker_host] + docker_args) result = docker.Execute(docker_args) # Explicitly avoid displaying an error message that might # distract from the docker error message already displayed. if result: raise exceptions.ExitCodeNoError(exit_code=result) return