desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Translates an apiserving REST response so it\'s ready to return.
Currently, the only thing that needs to be fixed here is indentation,
so it\'s consistent with what the live app will return.
Args:
response_body: A string containing the backend response.
Returns:
A reformatted version of the response JSON.'
| def transform_rest_response(self, response_body):
| body_json = json.loads(response_body)
return json.dumps(body_json, indent=1, sort_keys=True)
|
'Translates an apiserving response to a JsonRpc response.
Args:
spi_request: An ApiRequest, the transformed request that was sent to the
SPI handler.
response_body: A string containing the backend response to transform
back to JsonRPC.
Returns:
A string with the updated, JsonRPC-formatted request body.'
| def transform_jsonrpc_response(self, spi_request, response_body):
| body_json = {'result': json.loads(response_body)}
if (spi_request.request_id is not None):
body_json['id'] = spi_request.request_id
if spi_request.is_batch():
body_json = [body_json]
return json.dumps(body_json, indent=1, sort_keys=True)
|
'Initializer for Module.
Args:
module_configuration: An application_configuration.ModuleConfiguration
instance storing the configuration data for a module.'
| def __init__(self, module_configuration):
| self._module_configuration = module_configuration
self._go_file_to_mtime = {}
self._extras_hash = None
self._go_executable = None
self._work_dir = None
self._arch = self._get_architecture()
self._pkg_path = self._get_pkg_path()
|
'The path to the Go executable. None if it has not been built.'
| @property
def go_executable(self):
| return self._go_executable
|
'Return the environment that used be used to run the Go executable.'
| def get_environment(self):
| environ = {'GOROOT': GOROOT, 'PWD': self._module_configuration.application_root, 'TZ': 'UTC', 'RUN_WITH_DEVAPPSERVER': '1'}
if ('SYSTEMROOT' in os.environ):
environ['SYSTEMROOT'] = os.environ['SYSTEMROOT']
if ('USER' in os.environ):
environ['USER'] = os.environ['USER']
return environ
|
'Returns a dict mapping all Go files to their mtimes.
Returns:
A dict mapping the path relative to the application root of every .go
file in the application root, or any of its subdirectories, to the file\'s
modification time.'
| def _get_go_files_to_mtime(self):
| app_root = self._module_configuration.application_root
go_file_to_mtime = {}
for rel_path in list_go_files(app_root, self._module_configuration.nobuild_files, self._module_configuration.skip_files):
full_path = os.path.join(app_root, rel_path)
try:
go_file_to_mtime[rel_path] = os... |
'Returns a hash of the names and mtimes of package dependencies.
Returns:
Returns a string representing a hash.
Raises:
BuildError: if the go application builder fails.'
| def _get_extras_hash(self):
| gab_args = ['-print_extras_hash']
gab_args.extend(self._go_file_to_mtime)
(gab_stdout, _) = self._run_gab(gab_args, env={})
return gab_stdout
|
'Builds an executable for the application if necessary.
Args:
maybe_modified_since_last_build: True if any files in the application root
or the GOPATH have changed since the last call to maybe_build, False
otherwise. This argument is used to decide whether a build is Required
or not.
Returns:
True if compilation was su... | def maybe_build(self, maybe_modified_since_last_build):
| if (not self._work_dir):
self._work_dir = tempfile.mkdtemp('appengine-go-bin')
atexit.register(_rmtree, self._work_dir)
if (not os.path.exists(_GAB_PATH)):
raise go_errors.BuildError('Required Go components are missing from the SDK.')
if (self._go_executable and ... |
'Test page with no login requirement, and no cookie.'
| def test_optional(self):
| url_map = appinfo.URLMap(url='/')
h = url_handler.UserConfiguredURLHandler(url_map, '/$')
def start_response(unused_status, unused_response_headers, unused_exc_info=None):
self.fail('start_response was called')
r = h.handle_authorization(self.environ, start_response)
self.assertEqual(N... |
'Test page with login: required; redirect, and no cookie.'
| def test_required_redirect_no_login(self):
| url_map = appinfo.URLMap(url='/', login='required')
h = url_handler.UserConfiguredURLHandler(url_map, '/$')
expected_status = '302 Requires login'
expected_location = 'https://localhost:1443/login?continue=http%3A//localhost%3A8080/my/album/of/pictures%3Fwith%3Dsome%26query%3Dparameters'
expec... |
'Test page with login: required; unauthorized, and no cookie.'
| def test_required_unauthorized_no_login(self):
| url_map = appinfo.URLMap(url='/', login='required', auth_fail_action='unauthorized')
h = url_handler.UserConfiguredURLHandler(url_map, '/$')
expected_status = '401 Not authorized'
expected_headers = {'Content-Type': 'text/html', 'Cache-Control': 'no-cache'}
expected_content = 'Login require... |
'Test page with login: required, and a valid cookie.'
| def test_required_succeed(self):
| url_map = appinfo.URLMap(url='/', login='required')
h = url_handler.UserConfiguredURLHandler(url_map, '/$')
self.environ['HTTP_COOKIE'] = COOKIE
def start_response(unused_status, unused_response_headers, unused_exc_info=None):
self.fail('start_response was called')
r = h.handle_authori... |
'Test page with login: required, no cookie, with fake-is-admin header.'
| def test_required_no_login_fake_is_admin(self):
| url_map = appinfo.URLMap(url='/', login='required')
h = url_handler.UserConfiguredURLHandler(url_map, '/$')
self.environ[constants.FAKE_IS_ADMIN_HEADER] = '1'
expected_status = '302 Requires login'
expected_location = 'https://localhost:1443/login?continue=http%3A//localhost%3A8080/my/album/of... |
'Tests page with login: admin, no cookie with fake login header.'
| def test_admin_no_login_fake_logged_in(self):
| url_map = appinfo.URLMap(url='/', login='admin')
h = url_handler.UserConfiguredURLHandler(url_map, '/$')
self.environ[constants.FAKE_LOGGED_IN_HEADER] = '1'
expected_status = '401 Not authorized'
expected_headers = {'Content-Type': 'text/html', 'Cache-Control': 'no-cache'}
expected_content... |
'Test page with login: admin; redirect, and no cookie.'
| def test_admin_redirect_no_login(self):
| url_map = appinfo.URLMap(url='/', login='admin')
h = url_handler.UserConfiguredURLHandler(url_map, '/$')
expected_status = '302 Requires login'
expected_location = 'https://localhost:1443/login?continue=http%3A//localhost%3A8080/my/album/of/pictures%3Fwith%3Dsome%26query%3Dparameters'
expected... |
'Test page with login: admin; unauthorized, and no cookie.'
| def test_admin_unauthorized_no_login(self):
| url_map = appinfo.URLMap(url='/', login='admin', auth_fail_action='unauthorized')
h = url_handler.UserConfiguredURLHandler(url_map, '/$')
expected_status = '401 Not authorized'
expected_headers = {'Content-Type': 'text/html', 'Cache-Control': 'no-cache'}
expected_content = 'Login required ... |
'Test page with login: admin, and a non-admin cookie.'
| def test_admin_no_admin(self):
| url_map = appinfo.URLMap(url='/', login='admin')
h = url_handler.UserConfiguredURLHandler(url_map, '/$')
self.environ['HTTP_COOKIE'] = COOKIE
expected_status = '401 Not authorized'
expected_headers = {'Content-Type': 'text/html', 'Cache-Control': 'no-cache'}
expected_content = 'Current ... |
'Test page with login: admin, and a valid admin cookie.'
| def test_admin_succeed(self):
| url_map = appinfo.URLMap(url='/', login='admin')
h = url_handler.UserConfiguredURLHandler(url_map, '/$')
self.environ['HTTP_COOKIE'] = COOKIE_ADMIN
def start_response(unused_status, unused_response_headers, unused_exc_info=None):
self.fail('start_response was called')
r = h.handle_auth... |
'Test page with login: admin, and no cookie, with fake-is-admin.'
| def test_admin_no_login_fake_is_admin(self):
| url_map = appinfo.URLMap(url='/', login='admin')
h = url_handler.UserConfiguredURLHandler(url_map, '/$')
self.environ[constants.FAKE_IS_ADMIN_HEADER] = '1'
def start_response(unused_status, unused_response_headers, unused_exc_info=None):
self.fail('start_response was called')
r = h.han... |
'Test with login: admin, and a non-admin cookie, with fake-is-admin.'
| def test_admin_no_admin_fake_is_admin(self):
| url_map = appinfo.URLMap(url='/', login='admin')
h = url_handler.UserConfiguredURLHandler(url_map, '/$')
self.environ['HTTP_COOKIE'] = COOKIE
self.environ[constants.FAKE_IS_ADMIN_HEADER] = '1'
def start_response(unused_status, unused_response_headers, unused_exc_info=None):
self.fail('start_... |
'Test with login: admin, and valid admin cookie, with fake-is-admin.'
| def test_admin_succeed_fake_is_admin(self):
| url_map = appinfo.URLMap(url='/', login='admin')
h = url_handler.UserConfiguredURLHandler(url_map, '/$')
self.environ['HTTP_COOKIE'] = COOKIE_ADMIN
self.environ[constants.FAKE_IS_ADMIN_HEADER] = '1'
def start_response(unused_status, unused_response_headers, unused_exc_info=None):
self.fail('... |
'Test page with login: admin, and no cookie, with fake-is-admin header.'
| def test_admin_no_login_fake_is_admin_header(self):
| url_map = appinfo.URLMap(url='/', login='admin')
h = url_handler.UserConfiguredURLHandler(url_map, '/$')
self.environ[constants.FAKE_IS_ADMIN_HEADER] = '1'
def start_response(unused_status, unused_response_headers, unused_exc_info=None):
self.fail('start_response was called')
r = h.han... |
'Test page with login: required with fake-login-required.'
| def test_login_required_no_login_fake_logged_in_header(self):
| url_map = appinfo.URLMap(url='/', login='required')
h = url_handler.UserConfiguredURLHandler(url_map, '/$')
self.environ[constants.FAKE_LOGGED_IN_HEADER] = '1'
def start_response(unused_status, unused_response_headers, unused_exc_info=None):
self.fail('start_response was called')
r = h... |
'Initializes a FileClassification instance.
Args:
config: The app.yaml object to check the filename against.
filename: The name of the file.'
| def __init__(self, config, filename):
| self.__static_mime_type = self.__GetMimeTypeIfStaticFile(config, filename)
self.__static_app_readable = self.__GetAppReadableIfStaticFile(config, filename)
(self.__error_mime_type, self.__error_code) = self.__LookupErrorBlob(config, filename)
|
'Looks up the mime type for \'filename\'.
Uses the handlers in \'config\' to determine if the file should
be treated as a static file.
Args:
config: The app.yaml object to check the filename against.
filename: The name of the file.
Returns:
The mime type string. For example, \'text/plain\' or \'image/gif\'.
None if th... | @staticmethod
def __GetMimeTypeIfStaticFile(config, filename):
| for handler in config.handlers:
handler_type = handler.GetHandlerType()
if (handler_type in ('static_dir', 'static_files')):
if (handler_type == 'static_dir'):
regex = os.path.join(re.escape(handler.GetHandler()), '.*')
else:
regex = handler.up... |
'Looks up whether a static file is readable by the application.
Uses the handlers in \'config\' to determine if the file should
be treated as a static file and if so, if the file should be readable by the
application.
Args:
config: The AppInfoExternal object to check the filename against.
filename: The name of the file... | @staticmethod
def __GetAppReadableIfStaticFile(config, filename):
| for handler in config.handlers:
handler_type = handler.GetHandlerType()
if (handler_type in ('static_dir', 'static_files')):
if (handler_type == 'static_dir'):
regex = os.path.join(re.escape(handler.GetHandler()), '.*')
else:
regex = handler.up... |
'Looks up the mime type and error_code for \'filename\'.
Uses the error handlers in \'config\' to determine if the file should
be treated as an error blob.
Args:
config: The app.yaml object to check the filename against.
filename: The name of the file.
Returns:
A tuple of (mime_type, error_code), or (None, None) if thi... | @staticmethod
def __LookupErrorBlob(config, filename):
| if (not config.error_handlers):
return (None, None)
for error_handler in config.error_handlers:
if (error_handler.file == filename):
error_code = error_handler.error_code
error_code = (error_code or 'default')
if error_handler.mime_type:
return... |
'Creates a new DatastoreIndexUpload.
Args:
rpcserver: The RPC server to use. Should be an instance of HttpRpcServer
or TestRpcServer.
config: The AppInfoExternal object derived from the app.yaml file.
definitions: An IndexDefinitions object.'
| def __init__(self, rpcserver, config, definitions):
| self.rpcserver = rpcserver
self.config = config
self.definitions = definitions
|
'Uploads the index definitions.'
| def DoUpload(self):
| StatusUpdate('Uploading index definitions.')
self.rpcserver.Send('/api/datastore/index/add', app_id=self.config.application, version=self.config.version, payload=self.definitions.ToYAML())
|
'Creates a new CronEntryUpload.
Args:
rpcserver: The RPC server to use. Should be an instance of a subclass of
AbstractRpcServer
config: The AppInfoExternal object derived from the app.yaml file.
cron: The CronInfoExternal object loaded from the cron.yaml file.'
| def __init__(self, rpcserver, config, cron):
| self.rpcserver = rpcserver
self.config = config
self.cron = cron
|
'Uploads the cron entries.'
| def DoUpload(self):
| StatusUpdate('Uploading cron entries.')
self.rpcserver.Send('/api/cron/update', app_id=self.config.application, version=self.config.version, payload=self.cron.ToYAML())
|
'Creates a new QueueEntryUpload.
Args:
rpcserver: The RPC server to use. Should be an instance of a subclass of
AbstractRpcServer
config: The AppInfoExternal object derived from the app.yaml file.
queue: The QueueInfoExternal object loaded from the queue.yaml file.'
| def __init__(self, rpcserver, config, queue):
| self.rpcserver = rpcserver
self.config = config
self.queue = queue
|
'Uploads the task queue entries.'
| def DoUpload(self):
| StatusUpdate('Uploading task queue entries.')
self.rpcserver.Send('/api/queue/update', app_id=self.config.application, version=self.config.version, payload=self.queue.ToYAML())
|
'Creates a new DosEntryUpload.
Args:
rpcserver: The RPC server to use. Should be an instance of a subclass of
AbstractRpcServer.
config: The AppInfoExternal object derived from the app.yaml file.
dos: The DosInfoExternal object loaded from the dos.yaml file.'
| def __init__(self, rpcserver, config, dos):
| self.rpcserver = rpcserver
self.config = config
self.dos = dos
|
'Uploads the dos entries.'
| def DoUpload(self):
| StatusUpdate('Uploading DOS entries.')
self.rpcserver.Send('/api/dos/update', app_id=self.config.application, version=self.config.version, payload=self.dos.ToYAML())
|
'Creates a new PagespeedEntryUpload.
Args:
rpcserver: The RPC server to use. Should be an instance of a subclass of
AbstractRpcServer.
config: The AppInfoExternal object derived from the app.yaml file.
pagespeed: The PagespeedEntry object from config.'
| def __init__(self, rpcserver, config, pagespeed):
| self.rpcserver = rpcserver
self.config = config
self.pagespeed = pagespeed
|
'Uploads the pagespeed entries.'
| def DoUpload(self):
| pagespeed_yaml = ''
if self.pagespeed:
StatusUpdate('Uploading PageSpeed configuration.')
pagespeed_yaml = self.pagespeed.ToYAML()
try:
self.rpcserver.Send('/api/appversion/updatepagespeed', app_id=self.config.application, version=self.config.version, payload=pagespeed_yaml)
... |
'Creates a new DefaultVersionSet.
Args:
rpcserver: The RPC server to use. Should be an instance of a subclass of
AbstractRpcServer.
app_id: The application to make the change to.
module: The module to set the default version of (if any).
version: The version to set as the default.'
| def __init__(self, rpcserver, app_id, module, version):
| self.rpcserver = rpcserver
self.app_id = app_id
self.module = module
self.version = version
|
'Sets the default version.'
| def SetVersion(self):
| if self.module:
StatusUpdate(('Setting default version of module %s of application %s to %s.' % (self.app_id, self.module, self.version)))
else:
StatusUpdate(('Setting default version of application %s to %s.' % (self.app_id, self.version)))
... |
'Creates a new IndexOperation.
Args:
rpcserver: The RPC server to use. Should be an instance of HttpRpcServer
or TestRpcServer.
config: appinfo.AppInfoExternal configuration object.'
| def __init__(self, rpcserver, config):
| self.rpcserver = rpcserver
self.config = config
|
'Retrieve diff file from the server.
Args:
definitions: datastore_index.IndexDefinitions as loaded from users
index.yaml file.
Returns:
A pair of datastore_index.IndexDefinitions objects. The first record
is the set of indexes that are present in the index.yaml file but missing
from the server. The second record is t... | def DoDiff(self, definitions):
| StatusUpdate('Fetching index definitions diff.')
response = self.rpcserver.Send('/api/datastore/index/diff', app_id=self.config.application, payload=definitions.ToYAML())
return datastore_index.ParseMultipleIndexDefinitions(response)
|
'Delete indexes from the server.
Args:
definitions: Index definitions to delete from datastore.
Returns:
A single datstore_index.IndexDefinitions containing indexes that were
not deleted, probably because they were already removed. This may
be normal behavior as there is a potential race condition between fetching
the... | def DoDelete(self, definitions):
| StatusUpdate('Deleting selected index definitions.')
response = self.rpcserver.Send('/api/datastore/index/delete', app_id=self.config.application, payload=definitions.ToYAML())
return datastore_index.ParseIndexDefinitions(response)
|
'Creates a new VacuumIndexesOperation.
Args:
rpcserver: The RPC server to use. Should be an instance of HttpRpcServer
or TestRpcServer.
config: appinfo.AppInfoExternal configuration object.
force: True to force deletion of indexes, else False.
confirmation_fn: Function used for getting input form user.'
| def __init__(self, rpcserver, config, force, confirmation_fn=raw_input):
| super(VacuumIndexesOperation, self).__init__(rpcserver, config)
self.force = force
self.confirmation_fn = confirmation_fn
|
'Get confirmation from user to delete an index.
This method will enter an input loop until the user provides a
response it is expecting. Valid input is one of three responses:
y: Confirm deletion of index.
n: Do not delete index.
a: Delete all indexes without asking for further confirmation.
If the user enters nothing... | def GetConfirmation(self, index):
| while True:
print 'This index is no longer defined in your index.yaml file.'
print
print index.ToYAML()
print
confirmation = self.confirmation_fn('Are you sure you want to delete this index? (N/y/a): ')
confirma... |
'Vacuum indexes in datastore.
This method will query the server to determine which indexes are not
being used according to the user\'s local index.yaml file. Once it has
made this determination, it confirms with the user which unused indexes
should be deleted. Once confirmation for each index is receives, it
deletes ... | def DoVacuum(self, definitions):
| (unused_new_indexes, notused_indexes) = self.DoDiff(definitions)
deletions = datastore_index.IndexDefinitions(indexes=[])
if (notused_indexes.indexes is not None):
for index in notused_indexes.indexes:
if (self.force or self.GetConfirmation(index)):
deletions.indexes.appe... |
'Constructor.
Args:
rpcserver: The RPC server to use. Should be an instance of HttpRpcServer
or TestRpcServer.
app_id: The application to fetch logs from.
module: The module of the app to fetch logs from, optional.
version_id: The version of the app to fetch logs for.
output_file: Output file name.
num_days: Number of... | def __init__(self, rpcserver, app_id, module, version_id, output_file, num_days, append, severity, end, vhost, include_vhost, include_all=None, time_func=time.time):
| self.rpcserver = rpcserver
self.app_id = app_id
self.output_file = output_file
self.append = append
self.num_days = num_days
self.severity = severity
self.vhost = vhost
self.include_vhost = include_vhost
self.include_all = include_all
self.module = module
self.version_id = ve... |
'Download the requested logs.
This will write the logs to the file designated by
self.output_file, or to stdout if the filename is \'-\'.
Multiple roundtrips to the server may be made.'
| def DownloadLogs(self):
| if self.module:
StatusUpdate(('Downloading request logs for app %s module %s version %s.' % (self.app_id, self.module, self.version_id)))
else:
StatusUpdate(('Downloading request logs for app %s version %s.' % (self.app_id, self.version_id)))
t... |
'Make a single roundtrip to the server.
Args:
tf: Writable binary stream to which the log lines returned by
the server are written, stripped of headers, and excluding
lines skipped due to self.sentinel or self.valid_dates filtering.
offset: Offset string for a continued request; None for the first.
Returns:
The offset ... | def RequestLogLines(self, tf, offset):
| logging.info('Request with offset %r.', offset)
kwds = {'app_id': self.app_id, 'version': self.version_id, 'limit': 1000}
if self.module:
kwds['module'] = self.module
if offset:
kwds['offset'] = offset
if (self.severity is not None):
kwds['severity'] = str(self.sever... |
'Constructor.
Args:
what: Either \'file\' or \'blob\' or \'errorblob\' indicating what kind of
objects this batcher uploads. Used in messages and URLs.
rpcserver: The RPC server.
params: A dictionary object containing URL params to add to HTTP requests.'
| def __init__(self, what, rpcserver, params):
| assert (what in ('file', 'blob', 'errorblob')), repr(what)
self.what = what
self.params = params
self.rpcserver = rpcserver
self.single_url = ('/api/appversion/add' + what)
self.batch_url = (self.single_url + 's')
self.batching = True
self.batch = []
self.batch_size = 0
|
'Send the current batch on its way.
If successful, resets self.batch and self.batch_size.
Raises:
HTTPError with code=404 if the server doesn\'t support batching.'
| def SendBatch(self):
| boundary = 'boundary'
parts = []
for (path, payload, mime_type) in self.batch:
while (boundary in payload):
boundary += ('%04x' % random.randint(0, 65535))
assert (len(boundary) < 80), 'Unexpected error, please try again.'
part = '\n'.join(['', ('X-Appcfg-... |
'Send a single file on its way.'
| def SendSingleFile(self, path, payload, mime_type):
| logging.info('Uploading %s %s (%s bytes, type=%s) to %s.', self.what, path, len(payload), mime_type, self.single_url)
self.rpcserver.Send(self.single_url, payload=payload, content_type=mime_type, path=path, **self.params)
|
'Flush the current batch.
This first attempts to send the batch as a single request; if that
fails because the server doesn\'t support batching, the files are
sent one by one, and self.batching is reset to False.
At the end, self.batch and self.batch_size are reset.'
| def Flush(self):
| if (not self.batch):
return
try:
self.SendBatch()
except urllib2.HTTPError as err:
if (err.code != 404):
raise
logging.info('Old server detected; turning off %s batching.', self.what)
self.batching = False
for (path, payload, mime... |
'Batch a file, possibly flushing first, or perhaps upload it directly.
Args:
path: The name of the file.
payload: The contents of the file.
mime_type: The MIME Content-type of the file, or None.
If mime_type is None, application/octet-stream is substituted.'
| def AddToBatch(self, path, payload, mime_type):
| if (not mime_type):
mime_type = 'application/octet-stream'
size = len(payload)
if (size <= MAX_BATCH_FILE_SIZE):
if ((len(self.batch) >= MAX_BATCH_COUNT) or ((self.batch_size + size) > MAX_BATCH_SIZE)):
self.Flush()
if self.batching:
logging.info('Adding %s... |
'Creates a new AppVersionUpload.
Args:
rpcserver: The RPC server to use. Should be an instance of HttpRpcServer
or TestRpcServer.
config: An AppInfoExternal object that specifies the configuration for
this application.
module_yaml_path: The (string) path to the yaml file corresponding to
<config>, relative to the bundl... | def __init__(self, rpcserver, config, module_yaml_path='app.yaml', backend=None, error_fh=None):
| self.rpcserver = rpcserver
self.config = config
self.app_id = self.config.application
self.module = self.config.module
self.backend = backend
self.error_fh = (error_fh or sys.stderr)
self.version = self.config.version
self.params = {}
if self.app_id:
self.params['app_id'] = s... |
'Sends a request to the server, with common params.'
| def Send(self, url, payload=''):
| logging.info('Send: %s, params=%s', url, self.params)
return self.rpcserver.Send(url, payload=payload, **self.params)
|
'Adds the provided file to the list to be pushed to the server.
Args:
path: The path the file should be uploaded as.
file_handle: A stream containing data to upload.'
| def AddFile(self, path, file_handle):
| assert (not self.in_transaction), 'Already in a transaction.'
assert (file_handle is not None)
reason = appinfo.ValidFilename(path)
if reason:
logging.error(reason)
return
content_hash = _HashFromFileHandle(file_handle)
self.files[path] = content_hash
self.all_files.... |
'Returns a string describing the object being updated.'
| def Describe(self):
| result = ('app: %s' % self.app_id)
if ((self.module is not None) and (self.module != appinfo.DEFAULT_MODULE)):
result += (', module: %s' % self.module)
if self.backend:
result += (', backend: %s' % self.backend)
elif self.version:
result += (', version: %s' %... |
'Begins the transaction, returning a list of files that need uploading.
All calls to AddFile must be made before calling Begin().
Returns:
A list of pathnames for files that should be uploaded using UploadFile()
before Commit() can be called.'
| def Begin(self):
| assert (not self.in_transaction), 'Already in a transaction.'
config_copy = copy.deepcopy(self.config)
for url in config_copy.handlers:
handler_type = url.GetHandlerType()
if url.application_readable:
if (handler_type == 'static_dir'):
url.static_dir = os... |
'Uploads a file to the hosting service.
Must only be called after Begin().
The path provided must be one of those that were returned by Begin().
Args:
path: The path the file is being uploaded as.
file_handle: A file-like object containing the data to upload.
Raises:
KeyError: The provided file is not amongst those to ... | def UploadFile(self, path, file_handle):
| assert self.in_transaction, 'Begin() must be called before UploadFile().'
if (path not in self.files):
raise KeyError(("File '%s' is not in the list of files to be uploaded." % path))
del self.files[path]
file_classification = FileClassification(se... |
'Handle bytecode precompilation.'
| def Precompile(self):
| StatusUpdate('Compilation starting.')
files = []
if (self.config.runtime == 'go'):
for f in self.all_files:
if (f.endswith('.go') and (not self.config.nobuild_files.match(f))):
files.append(f)
while True:
if files:
StatusUpdate(('Compilation: ... |
'Precompile a batch of files.
Args:
files: Either an empty list (for the initial request) or a list
of files to be precompiled.
Returns:
Either an empty list (if no more files need to be precompiled)
or a list of files to be precompiled subsequently.'
| def PrecompileBatch(self, files):
| payload = LIST_DELIMITER.join(files)
response = self.Send('/api/appversion/precompile', payload=payload)
if (not response):
return []
return response.split(LIST_DELIMITER)
|
'Commits the transaction, making the new app version available.
All the files returned by Begin() must have been uploaded with UploadFile()
before Commit() can be called.
This tries the new \'deploy\' method; if that fails it uses the old \'commit\'.
Returns:
An appinfo.AppInfoSummary if one was returned from the Deplo... | def Commit(self):
| assert self.in_transaction, 'Begin() must be called before Commit().'
if self.files:
raise Exception('Not all required files have been uploaded.')
def PrintRetryMessage(_, delay):
StatusUpdate(('Will check again in %s seconds.' % delay))
ap... |
'Deploys the new app version but does not make it default.
All the files returned by Begin() must have been uploaded with UploadFile()
before Deploy() can be called.
Returns:
An appinfo.AppInfoSummary if one was returned from the Deploy, None
otherwise.
Raises:
Exception: Some required files were not uploaded.'
| def Deploy(self):
| assert self.in_transaction, 'Begin() must be called before Deploy().'
if self.files:
raise Exception('Not all required files have been uploaded.')
StatusUpdate('Starting deployment.')
result = self.Send('/api/appversion/deploy')
self.deployed = True
if... |
'Check if the new app version is ready to serve traffic.
Raises:
Exception: Deploy has not yet been called.
Returns:
True if the server returned the app is ready to serve.'
| def IsReady(self):
| assert self.deployed, 'Deploy() must be called before IsReady().'
StatusUpdate('Checking if deployment succeeded.')
result = self.Send('/api/appversion/isready')
return (result == '1')
|
'Start serving with the newly created version.
Raises:
Exception: Deploy has not yet been called.
Returns:
The response body, as a string.'
| def StartServing(self):
| assert self.deployed, 'Deploy() must be called before StartServing().'
StatusUpdate('Deployment successful.')
self.params['willcheckserving'] = '1'
result = self.Send('/api/appversion/startserving')
del self.params['willcheckserving']
self.started = True
return result
|
'Check if the new app version is serving.
Raises:
Exception: Deploy has not yet been called.
Returns:
True if the deployed app version is serving.'
| def IsServing(self):
| assert self.started, 'StartServing() must be called before IsServing().'
StatusUpdate('Checking if updated app version is serving.')
result = self.Send('/api/appversion/isserving')
return (result == '1')
|
'Rolls back the transaction if one is in progress.'
| def Rollback(self):
| if (not self.in_transaction):
return
StatusUpdate('Rolling back the update.')
self.Send('/api/appversion/rollback')
self.in_transaction = False
self.files = {}
|
'Uploads a new appversion with the given config and files to the server.
Args:
paths: An iterator that yields the relative paths of the files to upload.
openfunc: A function that takes a path and returns a file-like object.
Returns:
An appinfo.AppInfoSummary if one was returned from the server, None
otherwise.'
| def DoUpload(self, paths, openfunc):
| logging.info('Reading app configuration.')
StatusUpdate(('\nStarting update of %s' % self.Describe()))
path = ''
try:
self.resource_limits = GetResourceLimits(self.rpcserver, self.config)
StatusUpdate('Scanning files on local disk.')
num_files = 0
... |
'Initializer. Parses the cmdline and selects the Action to use.
Initializes all of the attributes described in the class docstring.
Prints help or error messages if there is an error parsing the cmdline.
Args:
argv: The list of arguments passed to this program.
parser_class: Options parser to use for this application.... | def __init__(self, argv, parser_class=optparse.OptionParser, rpc_server_class=None, raw_input_fn=raw_input, password_input_fn=getpass.getpass, out_fh=sys.stdout, error_fh=sys.stderr, update_check_class=sdk_update_checker.SDKUpdateChecker, throttle_class=None, opener=open, file_iterator=FileIterator, time_func=time.time... | self.parser_class = parser_class
self.argv = argv
self.rpc_server_class = rpc_server_class
self.raw_input_fn = raw_input_fn
self.password_input_fn = password_input_fn
self.out_fh = out_fh
self.error_fh = error_fh
self.update_check_class = update_check_class
self.throttle_class = thro... |
'Executes the requested action.
Catches any HTTPErrors raised by the action and prints them to stderr.
Returns:
1 on error, 0 if successful.'
| def Run(self):
| try:
self.action(self)
except urllib2.HTTPError as e:
body = e.read()
if self.wrap_server_error_message:
error_format = 'Error %d: --- begin server output ---\n%s\n--- end server output ---'
else:
error_format = 'Error %d: ... |
'Returns a formatted string containing the short_descs for all actions.'
| def _GetActionDescriptions(self):
| action_names = self.actions.keys()
action_names.sort()
desc = ''
for action_name in action_names:
if (not self.actions[action_name].hidden):
desc += (' %s: %s\n' % (action_name, self.actions[action_name].short_desc))
return desc
|
'Creates an OptionParser with generic usage and description strings.
Returns:
An OptionParser instance.'
| def _GetOptionParser(self):
| class Formatter(optparse.IndentedHelpFormatter, ):
'Custom help formatter that does not reformat the description.'
def format_description(self, description):
'Very simple formatter.'
return (description + '\n')
desc = self._GetActionDescripti... |
'Creates a new parser with documentation specific to \'action\'.
Args:
action: An Action instance to be used when initializing the new parser.
Returns:
A tuple containing:
parser: An instance of OptionsParser customized to \'action\'.
options: The command line options after re-parsing.'
| def _MakeSpecificParser(self, action):
| parser = self._GetOptionParser()
parser.set_usage(action.usage)
parser.set_description(('%s\n%s' % (action.short_desc, action.long_desc)))
action.options(self, parser)
(options, unused_args) = parser.parse_args(self.argv[1:])
return (parser, options)
|
'Prints the parser\'s help message and exits the program.
Args:
exit_code: The integer code to pass to sys.exit().'
| def _PrintHelpAndExit(self, exit_code=2):
| self.parser.print_help()
sys.exit(exit_code)
|
'Returns an instance of an AbstractRpcServer.
Returns:
A new AbstractRpcServer, on which RPC calls can be made.
Raises:
OAuthNotAvailable: Oauth is requested but the dependecies aren\'t imported.'
| def _GetRpcServer(self):
| def GetUserCredentials():
'Prompts the user for a username and password.'
email = self.options.email
if (email is None):
email = self.raw_input_fn('Email: ')
password_prompt = ('Password for %s: ' % email)
if self.options.passin:
... |
'Find yaml files in application directory.
Args:
basepath: Base application directory.
file_name: Relative file path from basepath, without extension, to search
for.
Returns:
Path to located yaml file if one exists, else None.'
| def _FindYaml(self, basepath, file_name):
| if (not os.path.isdir(basepath)):
self.parser.error(('Not a directory: %s' % basepath))
alt_basepath = os.path.join(basepath, 'WEB-INF', 'appengine-generated')
for yaml_basepath in (basepath, alt_basepath):
for yaml_file in ((file_name + '.yaml'), (file_name + '.yml')):
... |
'Parses the app.yaml file.
Args:
basepath: The directory of the application.
basename: The relative file path, from basepath, to search for.
Returns:
An AppInfoExternal object.'
| def _ParseAppInfoFromYaml(self, basepath, basename='app'):
| appyaml = self._ParseYamlFile(basepath, basename, appinfo_includes.Parse)
if (appyaml is None):
self.parser.error(('Directory does not contain an %s.yaml configuration file.' % basename))
orig_application = appyaml.application
orig_module = appyaml.module
orig_version = ... |
'Parses a yaml file.
Args:
basepath: The base directory of the application.
basename: The relative file path, from basepath, (with the \'.yaml\'
stripped off).
parser: the function or method used to parse the file.
Returns:
A single parsed yaml file or None if the file does not exist.'
| def _ParseYamlFile(self, basepath, basename, parser):
| file_name = self._FindYaml(basepath, basename)
if (file_name is not None):
fh = self.opener(file_name, 'r')
try:
defns = parser(fh, open_fn=self.opener)
finally:
fh.close()
return defns
return None
|
'Parses the backends.yaml file.
Args:
basepath: the directory of the application.
Returns:
A BackendsInfoExternal object or None if the file does not exist.'
| def _ParseBackendsYaml(self, basepath):
| return self._ParseYamlFile(basepath, 'backends', backendinfo.LoadBackendInfo)
|
'Parses the index.yaml file.
Args:
basepath: the directory of the application.
Returns:
A single parsed yaml file or None if the file does not exist.'
| def _ParseIndexYaml(self, basepath):
| return self._ParseYamlFile(basepath, 'index', datastore_index.ParseIndexDefinitions)
|
'Parses the cron.yaml file.
Args:
basepath: the directory of the application.
Returns:
A CronInfoExternal object or None if the file does not exist.'
| def _ParseCronYaml(self, basepath):
| return self._ParseYamlFile(basepath, 'cron', croninfo.LoadSingleCron)
|
'Parses the queue.yaml file.
Args:
basepath: the directory of the application.
Returns:
A QueueInfoExternal object or None if the file does not exist.'
| def _ParseQueueYaml(self, basepath):
| return self._ParseYamlFile(basepath, 'queue', queueinfo.LoadSingleQueue)
|
'Parses the dispatch.yaml file.
Args:
basepath: the directory of the application.
Returns:
A DispatchInfoExternal object or None if the file does not exist.'
| def _ParseDispatchYaml(self, basepath):
| return self._ParseYamlFile(basepath, 'dispatch', dispatchinfo.LoadSingleDispatch)
|
'Parses the dos.yaml file.
Args:
basepath: the directory of the application.
Returns:
A DosInfoExternal object or None if the file does not exist.'
| def _ParseDosYaml(self, basepath):
| return self._ParseYamlFile(basepath, 'dos', dosinfo.LoadSingleDos)
|
'Prints help for a specific action.
Args:
action: If provided, print help for the action provided.
Expects self.args[0], or \'action\', to contain the name of the action in
question. Exits the program after printing the help message.'
| def Help(self, action=None):
| if (not action):
if (len(self.args) > 1):
self.args = [' '.join(self.args)]
if ((len(self.args) != 1) or (self.args[0] not in self.actions)):
self.parser.error(('Expected a single action argument. Must be one of:\n' + self._GetActionDescriptions... |
'Downloads the given app+version.'
| def DownloadApp(self):
| if (len(self.args) != 1):
self.parser.error((('"download_app" expects one non-option argument, found ' + str(len(self.args))) + '.'))
out_dir = self.args[0]
app_id = self.options.app_id
if (app_id is None):
self.parser.error('You must specify an app ID ... |
'Updates and deploys a new appversion.
Args:
rpcserver: An AbstractRpcServer instance on which RPC calls can be made.
basepath: The root directory of the version to update.
appyaml: The AppInfoExternal object parsed from an app.yaml-like file.
module_yaml_path: The (string) path to the yaml file, relative to the
bundle... | def UpdateVersion(self, rpcserver, basepath, appyaml, module_yaml_path, backend=None):
| if self.options.precompilation:
if (not appyaml.derived_file_type):
appyaml.derived_file_type = []
if (appinfo.PYTHON_PRECOMPILED not in appyaml.derived_file_type):
appyaml.derived_file_type.append(appinfo.PYTHON_PRECOMPILED)
paths = self.file_iterator(basepath, appyaml.s... |
'Updates and deploys new app versions based on given config files.'
| def UpdateUsingSpecificFiles(self):
| rpcserver = self._GetRpcServer()
all_files = ([self.basepath] + self.args)
has_python25_version = False
for yaml_path in all_files:
file_name = os.path.basename(yaml_path)
self.basepath = os.path.dirname(yaml_path)
if (not self.basepath):
self.basepath = '.'
m... |
'Updates and deploys a new appversion and global app configs.'
| def Update(self):
| appyaml = None
rpcserver = self._GetRpcServer()
if (not os.path.isdir(self.basepath)):
self.UpdateUsingSpecificFiles()
return
yaml_file_basename = 'app.yaml'
appyaml = self._ParseAppInfoFromYaml(self.basepath, basename=os.path.splitext(yaml_file_basename)[0])
if self.options.skip... |
'Adds update-specific options to \'parser\'.
Args:
parser: An instance of OptionsParser.'
| def _UpdateOptions(self, parser):
| parser.add_option('--no_precompilation', action='store_false', dest='precompilation', default=True, help='Disable automatic Python precompilation.')
parser.add_option('--backends', action='store_true', dest='backends', default=False, help='Update backends when performing appcfg update.')... |
'Deletes unused indexes.'
| def VacuumIndexes(self):
| if self.args:
self.parser.error('Expected a single <directory> argument.')
appyaml = self._ParseAppInfoFromYaml(self.basepath)
index_defs = self._ParseIndexYaml(self.basepath)
if (index_defs is None):
index_defs = datastore_index.IndexDefinitions()
rpcserver = self._GetRp... |
'Adds vacuum_indexes-specific options to \'parser\'.
Args:
parser: An instance of OptionsParser.'
| def _VacuumIndexesOptions(self, parser):
| parser.add_option('-f', '--force', action='store_true', dest='force_delete', default=False, help='Force deletion without being prompted.')
|
'Updates any new or changed cron definitions.'
| def UpdateCron(self):
| if self.args:
self.parser.error('Expected a single <directory> argument.')
appyaml = self._ParseAppInfoFromYaml(self.basepath)
rpcserver = self._GetRpcServer()
cron_yaml = self._ParseCronYaml(self.basepath)
if cron_yaml:
cron_upload = CronEntryUpload(rpcserver, appyaml, c... |
'Updates indexes.'
| def UpdateIndexes(self):
| if self.args:
self.parser.error('Expected a single <directory> argument.')
appyaml = self._ParseAppInfoFromYaml(self.basepath)
rpcserver = self._GetRpcServer()
index_defs = self._ParseIndexYaml(self.basepath)
if index_defs:
index_upload = IndexDefinitionUpload(rpcserver, ... |
'Updates any new or changed task queue definitions.'
| def UpdateQueues(self):
| if self.args:
self.parser.error('Expected a single <directory> argument.')
appyaml = self._ParseAppInfoFromYaml(self.basepath)
rpcserver = self._GetRpcServer()
queue_yaml = self._ParseQueueYaml(self.basepath)
if queue_yaml:
queue_upload = QueueEntryUpload(rpcserver, appya... |
'Updates new or changed dispatch definitions.'
| def UpdateDispatch(self):
| if self.args:
self.parser.error('Expected a single <directory> argument.')
rpcserver = self._GetRpcServer()
dispatch_yaml = self._ParseDispatchYaml(self.basepath)
if dispatch_yaml:
if self.options.app_id:
dispatch_yaml.application = self.options.app_id
if ... |
'Updates any new or changed dos definitions.'
| def UpdateDos(self):
| if self.args:
self.parser.error('Expected a single <directory> argument.')
appyaml = self._ParseAppInfoFromYaml(self.basepath)
rpcserver = self._GetRpcServer()
dos_yaml = self._ParseDosYaml(self.basepath)
if dos_yaml:
dos_upload = DosEntryUpload(rpcserver, appyaml, dos_ya... |
'Placeholder; we never expect this action to be invoked.'
| def BackendsAction(self):
| pass
|
'Check the backends.yaml file is sane and which backends to update.'
| def BackendsYamlCheck(self, appyaml, backend=None):
| if appyaml.backends:
self.parser.error('Backends are not allowed in app.yaml.')
backends_yaml = self._ParseBackendsYaml(self.basepath)
appyaml.backends = backends_yaml.backends
if (not appyaml.backends):
self.parser.error('No backends found in backends.yaml.')
... |
'Updates a backend.'
| def BackendsUpdate(self):
| self.backend = None
if (len(self.args) == 1):
self.backend = self.args[0]
elif (len(self.args) > 1):
self.parser.error('Expected an optional <backend> argument.')
yaml_file_basename = 'app'
appyaml = self._ParseAppInfoFromYaml(self.basepath, basename=yaml_file_basename)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.