feat: Add new gcloud commands, API clients, and third-party libraries across various services.

This commit is contained in:
2026-01-01 20:26:35 +01:00
parent 5e23cbece0
commit a19e592eb7
25221 changed files with 8324611 additions and 0 deletions

View File

@@ -0,0 +1,24 @@
Want to contribute? Great! First, read this page (including the small print at the end).
### Before you contribute
Before we can use your code, you must sign the
[Google Individual Contributor License Agreement](https://developers.google.com/open-source/cla/individual?csw=1)
(CLA), which you can do online. The CLA is necessary mainly because you own the
copyright to your changes, even after your contribution becomes part of our
codebase, so we need your permission to use and distribute your code. We also
need to be sure of various other things—for instance that you'll tell us if you
know that your code infringes on other people's patents. You don't have to sign
the CLA until after you've submitted your code for review and a member has
approved it, but you must do it before we can put your code into our codebase.
Before you start working on a larger contribution, you should get in touch with
us first through the issue tracker with your idea so that we can help out and
possibly guide you. Coordinating up front makes it much easier to avoid
frustration later on.
### Code reviews
All submissions, including submissions by project members, require review. We
use Github pull requests for this purpose.
### The small print
Contributions made by corporations are covered by a different agreement than
the one above, the Software Grant and Corporate Contributor License Agreement.

View File

@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,6 @@
Node.js Externalized Runtime
============================
This is the node.js runtime definition that will soon be used by gcloud for
generating dockerfiles for GAE.

View File

@@ -0,0 +1,145 @@
#!/usr/bin/python
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Language detection script.
import json
import os
import re
import sys
import subprocess
DEV_NULL = open(os.devnull, 'w')
# Augment the path with our library directory.
ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(sys.argv[0])))
sys.path.append(os.path.join(ROOT_DIR, 'lib'))
import comm
def asList(val):
"""Returns the value if it is a list else returns a list with the value.
"""
return val if isinstance(val, list) else [val]
def main(args):
if len(args) != 2:
# If we're being called incorrectly, this probably isn't happening from a
# framework.
sys.stderr.write('Invalid Usage: %s <source-root-directory>' %
sys.argv[0])
return 1
# Get the first argument, should be the source root directory.
path = args[1]
# Show failures in debug or error depending on whether nodejs has been
# explicitly specified.
config = comm.get_config()
if ((config.params.appinfo and config.params.appinfo.runtime) or
config.params.runtime):
log_detect_error = comm.error
else:
log_detect_error = comm.debug
comm.info('Checking for Node.js.')
package_json = os.path.join(path, 'package.json')
yarn_lock_name = 'yarn.lock'
yarn_lock = os.path.join(path, yarn_lock_name)
got_shrinkwrap = False
if not os.path.isfile(package_json):
comm.debug('node.js checker: No package.json file.')
got_package_json = False
got_scripts_start = False
node_version = None
use_yarn = False
else:
got_package_json = True
# If there's a package.json file, that's unusual enough that any
# errors should be surfaced to the user.
log_detect_error = comm.error
# Consider the yarn.lock file as present if and only if the yarn.lock
# file exists and is not specified as being skipped in app.yaml.
try:
raw_skip_files = config.params.appinfo.skip_files
skip_files = [] if raw_skip_files is None else asList(raw_skip_files)
except AttributeError:
# If the skip_file attribute or any other parent attribute
# does not exist, treat the skip_files as not user specified.
skip_files = []
yarn_lock_exists = os.path.isfile(yarn_lock)
yarn_lock_skipped = False
for pattern in skip_files:
if re.match(pattern, yarn_lock_name) is not None:
yarn_lock_skipped = True
break;
use_yarn = yarn_lock_exists and not yarn_lock_skipped
# Try to read the package.json file.
try:
with open(package_json) as f:
contents = json.load(f)
except (IOError, ValueError) as ex:
# If we have an invalid or unreadable package.json file, there's
# something funny going on here so fail recognition.
# A package.json that exists is unusual enough that we want to warn
# regardless of whether the nodejs runtime was specified.
log_detect_error('node.js checker: error accessing package.json: '
'%r' % ex)
return 1
# See if we've got a scripts.start field.
got_scripts_start = bool(contents.get('scripts', {}).get('start'))
# See if a version of node is specified.
try:
node_version = contents.get('engines', {}).get('node', None)
comm.info('node version is %s', node_version)
except AttributeError:
# Most likely "engines" wasn't a dictionary.
comm.warn('node.js checker: ignoring invalid "engines" field in '
'package.json')
node_version = None
if node_version is None:
comm.warn('No node version specified. Please add your node '
'version, see '
'https://docs.npmjs.com/files/package.json#engines')
if got_scripts_start or os.path.exists(os.path.join(path, 'server.js')):
runtime = 'custom' if config.params.custom else 'nodejs'
appinfo = {'runtime': runtime,
'env': 'flex'}
comm.send_runtime_params({'got_package_json': got_package_json,
'got_scripts_start': got_scripts_start,
'node_version': node_version,
'use_yarn': use_yarn},
appinfo=appinfo)
else:
log_detect_error('node.js checker: Neither "start" in the "scripts" '
'section of "package.json" nor the "server.js" file '
'were found.')
return 1
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))

View File

@@ -0,0 +1,90 @@
#!/usr/bin/python
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import StringIO
import pipes
import sys
# Augment the path with our library directory.
ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(sys.argv[0])))
sys.path.append(os.path.join(ROOT_DIR, 'lib'))
import comm
ROOT = comm.RuntimeDefinitionRoot(ROOT_DIR)
# The template for the docker command that is injected into the Dockerfile
# when the user specifies a node version in their "engines" section.
INSTALL_NODE_TEMPLATE = ROOT.read_file('data/install-node-version')
def main(args):
"""Generate all config files for the module."""
# Get runtime parameters from the controller.
info = comm.get_config()
runtime_data = info.runtime_data
params = info.params
# Generate app.yaml.
if not params.appinfo:
app_yaml = 'app.yaml'
runtime = 'custom' if params.custom else 'nodejs'
app_yaml_contents = ROOT.read_file('data/app.yaml')
comm.gen_file(app_yaml,
app_yaml_contents.format(runtime=runtime))
if params.custom or params.deploy:
dockerfile = 'Dockerfile'
# Customize the dockerfile.
out = StringIO.StringIO()
out.write(ROOT.read_file('data', 'Dockerfile'))
if runtime_data.node_version:
# Let node check to see if it satisfies the version constraint and
# try to install the correct version if not.
out.write(INSTALL_NODE_TEMPLATE %
{'version_spec': pipes.quote(runtime_data.node_version)})
# If the directory structure indicates that yarn is being used
# then install yarn since (unlike npm) Node.js doesn't include it
if runtime_data.use_yarn:
out.write(ROOT.read_file('data', 'install-yarn'))
out.write('COPY . /app/\n')
# Generate npm or yarn install if there is a package.json.
if runtime_data.got_package_json:
out.write(
ROOT.read_file('data/{0}-package-json-install'.
format('yarn' if runtime_data.use_yarn
else 'npm')))
# Generate the appropriate start command.
if runtime_data.got_scripts_start:
out.write(
'CMD {0} start\n'.format('yarn' if runtime_data.use_yarn
else 'npm'))
else:
out.write('CMD node server.js\n')
comm.gen_file('Dockerfile', out.getvalue())
# Generate .dockerignore
dockerignore = '.dockerignore'
comm.gen_file(dockerignore, ROOT.read_file('data/dockerignore'))
if __name__ == '__main__':
main(sys.argv)

View File

@@ -0,0 +1,3 @@
# Dockerfile extending the generic Node image with application files for a
# single application.
FROM gcr.io/google_appengine/nodejs

View File

@@ -0,0 +1,2 @@
env: flex
runtime: {runtime}

View File

@@ -0,0 +1,22 @@
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
node_modules
.dockerignore
Dockerfile
npm-debug.log
yarn-error.log
.git
.hg
.svn

View File

@@ -0,0 +1,4 @@
# Check to see if the the version included in the base runtime satisfies
# %(version_spec)s, if not then do an npm install of the latest available
# version that satisfies it.
RUN /usr/local/bin/install_node %(version_spec)s

View File

@@ -0,0 +1,6 @@
# You have to specify "--unsafe-perm" with npm install
# when running as root. Failing to do this can cause
# install to appear to succeed even if a preinstall
# script fails, and may have other adverse consequences
# as well.
RUN npm install --unsafe-perm --global yarn

View File

@@ -0,0 +1,11 @@
# You have to specify "--unsafe-perm" with npm install
# when running as root. Failing to do this can cause
# install to appear to succeed even if a preinstall
# script fails, and may have other adverse consequences
# as well.
# This command will also cat the npm-debug.log file after the
# build, if it exists.
RUN npm install --unsafe-perm || \
((if [ -f npm-debug.log ]; then \
cat npm-debug.log; \
fi) && false)

View File

@@ -0,0 +1,5 @@
RUN yarn install --production || \
((if [ -f yarn-error.log ]; then \
cat yarn-error.log; \
fi) && false)

View File

@@ -0,0 +1,121 @@
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import os
import sys
def _write_msg(**message):
"""Write a message to standard output.
Args:
**message: ({str: object, ...}) A JSON message encoded in keyword
arguments.
"""
json.dump(message, sys.stdout)
sys.stdout.write('\n')
sys.stdout.flush()
def error(message, *args):
_write_msg(type='error', message=message % args)
def warn(message, *args):
_write_msg(type='warn', message=message % args)
def info(message, *args):
_write_msg(type='info', message=message % args)
def debug(message, *args):
_write_msg(type='debug', message=message % args)
def print_status(message, *args):
_write_msg(type='print_status', message=message % args)
def send_runtime_params(params, appinfo=None):
"""Send runtime parameters back to the controller.
Args:
params: ({str: object, ...}) Set of runtime parameters. Must be
json-encodable.
appinfo: ({str: object, ...}) Contents of the app.yaml file to
be produced by the runtime definition. Required fields may be
added to this by the framework, the only thing an application
needs to provide is the "runtime" field and any additional data
fields.
"""
if appinfo is not None:
_write_msg(type='runtime_parameters', runtime_data=params,
appinfo=appinfo)
else:
_write_msg(type='runtime_parameters', runtime_data=params)
def get_config():
"""Request runtime parameters from the controller.
Returns:
(object) The runtime parameters represented as an object.
"""
_write_msg(type='get_config')
return dict_to_object(json.loads(sys.stdin.readline()))
def dict_to_object(json_dict):
"""Converts a dictionary to a python object.
Converts key-values to attribute-values.
Args:
json_dict: ({str: object, ...})
Returns:
(object)
"""
class Object(object):
pass
obj = Object()
for name, val in json_dict.iteritems():
if isinstance(val, dict):
val = dict_to_object(val)
setattr(obj, name, val)
return obj
class RuntimeDefinitionRoot(object):
"""Abstraction that allows us to access files in the runtime definiton."""
def __init__(self, path):
self.root = path
def read_file(self, *name):
with open(os.path.join(self.root, *name)) as src:
return src.read()
def gen_file(name, contents):
"""Generate the file.
This writes the file to be generated back to the controller.
Args:
name: (str) The UNIX-style relative path of the file.
contents: (str) The complete file contents.
"""
_write_msg(type='gen_file', filename=name, contents=contents)

View File

@@ -0,0 +1,8 @@
author: mmuller@google.com
name: nodejs
description: Official Google Node.js runtime definition.
api_version: 0.1
detect:
python: bin/detect
generate_configs:
python: bin/generate_configs

View File

@@ -0,0 +1,480 @@
#!/usr/bin/python
import mock
import os
import re
import sys
import stat
import shutil
import tempfile
import textwrap
import unittest
from gae_ext_runtime import ext_runtime
from gae_ext_runtime import testutil
RUNTIME_DEF_ROOT = os.path.dirname(os.path.dirname(__file__))
class RuntimeTests(testutil.TestBase):
def setUp(self):
self.runtime_def_root = RUNTIME_DEF_ROOT
super(RuntimeTests, self).setUp()
def read_dist_file(self, *args):
"""Read the entire contents of the file.
Returns the entire contents of the file identified by a set of
arguments forming a path relative to the root of the runtime
definition.
TODO: Move this down into the SDK.
Args:
*args: A set of path components (see full_path()). Note that
these are relative to the runtime definition root, not the
temporary directory.
"""
with open(os.path.join(self.runtime_def_root, *args)) as fp:
return fp.read()
def test_node_js_server_js_only(self):
self.write_file('server.js', 'fake contents')
self.generate_configs()
self.assert_file_exists_with_contents(
'app.yaml',
self.read_dist_file('data', 'app.yaml').format(runtime='nodejs'))
self.generate_configs(deploy=True)
self.assert_file_exists_with_contents(
'Dockerfile',
self.read_dist_file('data', 'Dockerfile') + textwrap.dedent("""\
COPY . /app/
CMD node server.js
"""))
self.assert_file_exists_with_contents(
'.dockerignore',
self.read_dist_file('data', 'dockerignore'))
self.assertEqual(set(os.listdir(self.temp_path)),
{'Dockerfile', '.dockerignore', 'app.yaml',
'server.js'})
def test_node_js_server_js_only_no_write(self):
"""Test generate_config_data with only .js files.
After running generate_configs(), app.yaml exists; after
generate_config_data(), only app.yaml should exist on disk --
Dockerfile and .dockerignore should be returned by the method."""
self.write_file('server.js', 'fake contents')
self.generate_configs()
self.assert_file_exists_with_contents(
'app.yaml',
self.read_dist_file('data', 'app.yaml').format(runtime='nodejs'))
cfg_files = self.generate_config_data(deploy=True)
self.assert_genfile_exists_with_contents(
cfg_files,
'Dockerfile',
self.read_dist_file('data', 'Dockerfile') + textwrap.dedent("""\
COPY . /app/
CMD node server.js
"""))
self.assert_genfile_exists_with_contents(
cfg_files,
'.dockerignore',
self.read_dist_file('data', 'dockerignore'))
self.assertEqual(set(os.listdir(self.temp_path)),
{'app.yaml', 'server.js'})
self.assertEqual({f.filename for f in cfg_files},
{'Dockerfile', '.dockerignore'})
def _validate_docker_files_for_npm(self):
base_dockerfile = self.read_dist_file('data', 'Dockerfile')
self.assert_file_exists_with_contents(
'Dockerfile',
base_dockerfile + 'COPY . /app/\n' +
self.read_dist_file('data', 'npm-package-json-install') +
'CMD npm start\n')
self.assert_file_exists_with_contents(
'.dockerignore',
self.read_dist_file('data', 'dockerignore'))
def test_node_js_package_json_npm(self):
self.write_file('foo.js', 'bogus contents')
self.write_file('package.json', '{"scripts": {"start": "foo.js"}}')
self.generate_configs()
self.assert_file_exists_with_contents(
'app.yaml',
self.read_dist_file('data', 'app.yaml').format(runtime='nodejs'))
self.generate_configs(deploy=True)
self._validate_docker_files_for_npm()
self.assertEqual(set(os.listdir(self.temp_path)),
{'Dockerfile', '.dockerignore', 'app.yaml',
'foo.js', 'package.json'})
def _validate_docker_files_for_yarn(self):
base_dockerfile = self.read_dist_file('data', 'Dockerfile')
install_yarn = self.read_dist_file('data', 'install-yarn')
self.assert_file_exists_with_contents(
'Dockerfile',
base_dockerfile + install_yarn + 'COPY . /app/\n' +
self.read_dist_file('data', 'yarn-package-json-install') +
'CMD yarn start\n')
self.assert_file_exists_with_contents(
'.dockerignore',
self.read_dist_file('data', 'dockerignore'))
def test_node_js_package_json_yarn(self):
self.write_file('foo.js', 'bogus contents')
self.write_file('package.json', '{"scripts": {"start": "foo.js"}}')
self.write_file('yarn.lock', 'yarn overridden')
self.generate_configs()
self.assert_file_exists_with_contents(
'app.yaml',
self.read_dist_file('data', 'app.yaml').format(runtime='nodejs'))
self.generate_configs(deploy=True)
self._validate_docker_files_for_yarn()
self.assertEqual(set(os.listdir(self.temp_path)),
{'Dockerfile', '.dockerignore', 'app.yaml',
'foo.js', 'package.json', 'yarn.lock'})
def _validate_file_list_for_skip_yarn_lock(self):
self.assertEqual(set(os.listdir(self.temp_path)),
{'Dockerfile', '.dockerignore', 'yarn.lock',
'foo.js', 'package.json'})
def test_skip_yarn_lock_with_other_files(self):
"""Ensure use_yarn is False with yarn.lock present but is being skipped.
Further, this test verifies that use_yarn is False even if multiple
other entries are present in skip_files.
A yarn executable is injected that passes all checks to ensure that if
yarn.lock is set to be skipped, use_yarn is set to False even if yarn
can be executed and reports that the yarn.lock file is valid.
"""
self.write_file('package.json', '{"scripts": {"start": "foo.js"}}')
self.write_file('foo.js', 'fake contents')
self.write_file('yarn.lock', 'fake contents')
config = testutil.AppInfoFake(runtime='nodejs',
skip_files=['^abc$',
'^xyz$',
'^yarn\.lock$',
'^node_modules$'])
configurator = self.detect(appinfo=config)
self.assertEqual(configurator.data['use_yarn'], False)
self.generate_configs(appinfo=config, deploy=True)
self._validate_docker_files_for_npm()
self._validate_file_list_for_skip_yarn_lock()
def test_only_skip_yarn_lock(self):
"""Ensure use_yarn is False with yarn.lock present but is being skipped.
Further, this test ensures use_yarn is false if the value obtained
from skip_files is a regex string and not a list of strings.
A yarn executable is injected that passes all checks to ensure that if
yarn.lock is set to be skipped, use_yarn is set to False even if yarn
can be executed and reports that the yarn.lock file is valid.
"""
self.write_file('package.json', '{"scripts": {"start": "foo.js"}}')
self.write_file('foo.js', 'fake contents')
self.write_file('yarn.lock', 'fake contents')
config = testutil.AppInfoFake(runtime='nodejs',
skip_files='^yarn\.lock$')
configurator = self.detect(appinfo=config)
self.assertEqual(configurator.data['use_yarn'], False)
self.generate_configs(appinfo=config, deploy=True)
self._validate_docker_files_for_npm()
self._validate_file_list_for_skip_yarn_lock()
def test_do_not_skip_yarn_lock(self):
"""Ensure use_yarn is True with yarn.lock present and not skipped.
"""
self.write_file('package.json', '{"scripts": {"start": "foo.js"}}')
self.write_file('foo.js', 'fake contents')
self.write_file('yarn.lock', 'fake contents')
# Here only 'node_modules' will be skipped
config = testutil.AppInfoFake(runtime='nodejs',
skip_files='^node_modules$')
configurator = self.detect(appinfo=config)
self.assertEqual(configurator.data['use_yarn'], True)
self.generate_configs(appinfo=config, deploy=True)
self._validate_docker_files_for_yarn()
self._validate_file_list_for_skip_yarn_lock()
def test_use_yarn_skip_files_not_present(self):
"""Ensure use_yarn is True with yarn.lock present and not skipped.
In particular, this test ensures use_yarn is True even if app.yaml
doesn't contain a skip_files section.
"""
self.write_file('package.json', '{"scripts": {"start": "foo.js"}}')
self.write_file('foo.js', 'fake contents')
self.write_file('yarn.lock', 'fake contents')
config = testutil.AppInfoFake(runtime='nodejs')
configurator = self.detect(appinfo=config)
self.assertEqual(configurator.data['use_yarn'], True)
self.generate_configs(appinfo=config, deploy=True)
self._validate_docker_files_for_yarn()
self._validate_file_list_for_skip_yarn_lock()
def test_node_js_package_json_no_write(self):
"""Test generate_config_data with a nodejs file and package.json."""
self.write_file('foo.js', 'bogus contents')
self.write_file('package.json', '{"scripts": {"start": "foo.js"}}')
self.generate_configs()
self.assert_file_exists_with_contents(
'app.yaml',
self.read_dist_file('data', 'app.yaml').format(runtime='nodejs'))
cfg_files = self.generate_config_data(deploy=True)
base_dockerfile = self.read_dist_file('data', 'Dockerfile')
self.assert_genfile_exists_with_contents(
cfg_files,
'Dockerfile',
base_dockerfile + 'COPY . /app/\n' +
self.read_dist_file('data', 'npm-package-json-install') +
'CMD npm start\n')
self.assert_genfile_exists_with_contents(
cfg_files,
'.dockerignore',
self.read_dist_file('data', 'dockerignore'))
self.assertEqual(set(os.listdir(self.temp_path)),
{'app.yaml', 'foo.js', 'package.json'})
self.assertEqual({f.filename for f in cfg_files},
{'Dockerfile', '.dockerignore'})
def test_detect_basic(self):
"""Ensure that appinfo will be generated in detect method."""
self.write_file('foo.js', 'bogus contents')
self.write_file('package.json', '{"scripts": {"start": "foo.js"}}')
configurator = self.detect()
self.assertEqual(configurator.generated_appinfo,
{u'runtime': 'nodejs',
u'env': 'flex'})
def test_detect_custom(self):
"""Ensure that appinfo is correct with custom=True."""
self.write_file('foo.js', 'bogus contents')
self.write_file('package.json', '{"scripts": {"start": "foo.js"}}')
configurator = self.detect(custom=True)
self.assertEqual(configurator.generated_appinfo,
{'runtime': 'custom',
'env': 'flex'})
def test_detect_no_start_no_server(self):
"""Ensure that detect fails if no scripts.start field, no server.js."""
self.write_file('foo.js', 'bogus contents')
self.write_file('package.json', '{"scripts": {"not-start": "foo.js"}}')
configurator = self.detect()
self.assertEqual(configurator, None)
def test_detect_no_start_with_server(self):
"""Ensure appinfo generated if no scripts.start, server.js exists."""
self.write_file('server.js', 'bogus contents')
self.write_file('package.json', '{"scripts": {"not-start": "foo.js"}}')
configurator = self.detect()
self.assertEqual(configurator.generated_appinfo,
{'runtime': 'nodejs',
'env': 'flex'})
def test_node_js_with_engines(self):
self.write_file('foo.js', 'bogus contents')
self.write_file('package.json',
'{"scripts": {"start": "foo.js"},'
'"engines": {"node": "0.12.3"}}')
self.generate_configs(deploy=True)
dockerfile_path = self.full_path('Dockerfile')
self.assertTrue(os.path.exists(dockerfile_path))
# This just verifies that the crazy node install line is generated, it
# says nothing about whether or not it works.
rx = re.compile(r'RUN npm install')
for line in open(dockerfile_path):
if rx.match(line):
break
else:
self.fail('node install line not generated')
def test_node_js_with_engines_no_write(self):
"""Test generate_config_data with 'engines' in package.json."""
self.write_file('foo.js', 'bogus contents')
self.write_file('package.json',
'{"scripts": {"start": "foo.js"},'
'"engines": {"node": "0.12.3"}}')
cfg_files = self.generate_config_data(deploy=True)
self.assertIn('Dockerfile', [f.filename for f in cfg_files])
# This just verifies that the crazy node install line is generated, it
# says nothing about whether or not it works.
rx = re.compile(r'RUN npm install')
line_generated = False
for cfg_file in cfg_files:
if cfg_file.filename == 'Dockerfile':
for line in cfg_file.contents.split('\n'):
if rx.match(line):
line_generated = True
if not line_generated:
self.fail('node install line not generated')
def test_node_js_custom_runtime(self):
self.write_file('server.js', 'fake contents')
self.generate_configs(custom=True)
self.assert_file_exists_with_contents(
'app.yaml',
self.read_dist_file('data', 'app.yaml').format(runtime='custom'))
self.assertEqual(sorted(os.listdir(self.temp_path)),
['.dockerignore', 'Dockerfile', 'app.yaml',
'server.js'])
def test_node_js_custom_runtime_no_write(self):
"""Test generate_config_data with custom runtime.
Should generate an app.yaml on disk, the Dockerfile and
.dockerignore in memory."""
self.write_file('server.js', 'fake contents')
cfg_files = self.generate_config_data(custom=True)
self.assert_file_exists_with_contents(
'app.yaml',
self.read_dist_file('data', 'app.yaml').format(runtime='custom'))
self.assertEqual(set(os.listdir(self.temp_path)),
{'app.yaml', 'server.js'})
self.assertEqual({f.filename for f in cfg_files},
{'Dockerfile', '.dockerignore'})
def test_node_js_runtime_field(self):
self.write_file('server.js', 'fake contents')
config = testutil.AppInfoFake(runtime='nodejs')
self.generate_configs(appinfo=config, deploy=True)
self.assertTrue(os.path.exists(self.full_path('Dockerfile')))
def test_node_js_custom_runtime_field(self):
self.write_file('server.js', 'fake contents')
config = testutil.AppInfoFake(runtime='custom')
self.assertTrue(self.generate_configs(appinfo=config, deploy=True))
def test_invalid_package_json(self):
self.write_file('package.json', '')
self.write_file('server.js', '')
self.generate_configs()
self.assertFalse(self.generate_configs())
# Tests that verify that the generated files match verbatim output.
# These will need to be maintained whenever the code generation changes,
# but this ensures that any diffs we introduce in the generate files will
# be reviewed.
def test_node_js_with_engines_retroactive(self):
self.write_file('foo.js', 'bogus contents')
self.write_file('package.json',
'{"scripts": {"start": "foo.js"},'
'"engines": {"node": "0.12.3"}}')
self.generate_configs(deploy=True)
self.assert_file_exists_with_contents(
'Dockerfile',
textwrap.dedent("""\
# Dockerfile extending the generic Node image with application files for a
# single application.
FROM gcr.io/google_appengine/nodejs
# Check to see if the the version included in the base runtime satisfies
# 0.12.3, if not then do an npm install of the latest available
# version that satisfies it.
RUN /usr/local/bin/install_node 0.12.3
COPY . /app/
# You have to specify "--unsafe-perm" with npm install
# when running as root. Failing to do this can cause
# install to appear to succeed even if a preinstall
# script fails, and may have other adverse consequences
# as well.
# This command will also cat the npm-debug.log file after the
# build, if it exists.
RUN npm install --unsafe-perm || \\
((if [ -f npm-debug.log ]; then \\
cat npm-debug.log; \\
fi) && false)
CMD npm start
"""))
class FailureLoggingTests(testutil.TestBase):
def setUp(self):
self.runtime_def_root = RUNTIME_DEF_ROOT
super(FailureLoggingTests, self).setUp()
self.errors = []
self.debug = []
self.warnings = []
def error_fake(self, message):
self.errors.append(message)
def debug_fake(self, message):
self.debug.append(message)
def warn_fake(self, message):
self.warnings.append(message)
def test_invalid_package_json(self):
self.write_file('package.json', '')
self.write_file('server.js', '')
variations = [
(testutil.AppInfoFake(runtime='nodejs'), None),
(None, 'nodejs'),
(None, None)
]
for appinfo, runtime in variations:
self.errors = []
with mock.patch.dict(ext_runtime._LOG_FUNCS,
{'error': self.error_fake}):
self.generate_configs(appinfo=appinfo, runtime=runtime)
self.assertTrue(self.errors[0].startswith(
'node.js checker: error accessing package.json'))
def test_no_startup_script(self):
with mock.patch.dict(ext_runtime._LOG_FUNCS,
{'debug': self.debug_fake}):
self.generate_configs()
print self.debug
self.assertTrue(self.debug[1].startswith(
'node.js checker: Neither "start" in the "scripts" section '
'of "package.json" nor the "server.js" file were found.'))
variations = [
(testutil.AppInfoFake(runtime='nodejs'), None),
(None, 'nodejs')
]
for appinfo, runtime in variations:
self.errors = []
with mock.patch.dict(ext_runtime._LOG_FUNCS,
{'error': self.error_fake}):
self.generate_configs(appinfo=appinfo, runtime=runtime)
self.assertTrue(self.errors[0].startswith(
'node.js checker: Neither "start" in the "scripts" section '
'of "package.json" nor the "server.js" file were found.'))
def test_package_json_no_startup_script(self):
self.write_file('package.json', '{"scripts": {"not-start": "foo.js"}}')
variations = [
(testutil.AppInfoFake(runtime='nodejs'), None),
(None, 'nodejs'),
(None, None)
]
for appinfo, runtime in variations:
self.errors = []
with mock.patch.dict(ext_runtime._LOG_FUNCS,
{'error': self.error_fake}):
self.generate_configs(appinfo=appinfo, runtime=runtime)
self.assertTrue(self.errors[0].startswith(
'node.js checker: Neither "start" in the "scripts" section '
'of "package.json" nor the "server.js" file were found.'))
if __name__ == '__main__':
unittest.main()

View File

@@ -0,0 +1,22 @@
Testing Notes
=============
To run the test script (`test/runtime_test.py`) you'll need to install the
Google Cloud SDK add this to your PYTHONPATH:
export PYTHONPATH=$CLOUD_SDK/lib:$CLOUD_SDK/platform/google_appengine:$PYTHONPATH
Where `$CLOUD_SDK` is the location where the cloud SDK is installed.
Debugging
---------
If you do "sys.stderr.write(...)" from a plugin script, your output will go
to a nice shiny bright warning message. Exceptions will show up as warning
messages simply by virtue of having been formatted to standard error.
Full logging can be made to happen by adding:
from googlecloudsdk.core import log
log.SetVerbosity(logging.DEBUG)