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,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,98 @@
#!/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.
"""Java detection plugin."""
import os
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
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]
entrypoint = None
server = None
openjdk = None
config = comm.get_config()
appinfo = config.params.appinfo
if appinfo and appinfo.entrypoint:
entrypoint = appinfo.entrypoint
comm.info('Checking for Java.')
if appinfo:
runtime_config = appinfo.runtime_config
if runtime_config:
for key, value in runtime_config.to_dict().iteritems():
if key == 'server':
if value != 'jetty9':
comm.error('Unknown server : %s.' % value)
return 1
server = value
elif key == 'jdk':
if value != 'openjdk8':
comm.error('Unknown JDK : %s.' % value)
return 1
openjdk = value
else:
comm.error('Unknown runtime_config entry : %s.' % key)
return 1
artifact_to_deploy = '?'
# check for any Java known artifacts: a jar, a war, or an exploded Web App.
# TODO(ludo): expand to more complex configs with multiple Jars.
number_of_possible_artifacts = 0
for filename in os.listdir(path):
if filename.endswith('.war'):
artifact_to_deploy = filename
number_of_possible_artifacts += 1
if filename.endswith('.jar'):
artifact_to_deploy = filename
number_of_possible_artifacts += 1
if filename.endswith('WEB-INF'):
artifact_to_deploy = '.'
number_of_possible_artifacts += 1
if number_of_possible_artifacts == 0:
return 1
if number_of_possible_artifacts > 1:
comm.error('Too many java artifacts to deploy (.jar, .war, or Java '
'Web App).')
return 1
if not appinfo:
appinfo = {'runtime': 'custom' if config.params.custom else 'java'}
comm.send_runtime_params({'entrypoint': entrypoint, 'server': server,
'openjdk': openjdk,
'artifact_to_deploy': artifact_to_deploy},
appinfo)
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))

View File

@@ -0,0 +1,141 @@
#!/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.
"""Java config generation plugin."""
import os
import StringIO
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
import constants
ROOT = comm.RuntimeDefinitionRoot(ROOT_DIR)
def is_flex(env):
return env in ['2', 'flex', 'flexible']
class JavaConfigurator(object):
"""Generates configuration for a Java application.
What is supported is:
- jar file (run with Open JDK8 image)
- war file (run with Jetty9 image)
- Exploded war directory (with WEB-INF/):
- if env: 2, we use the latest Jetty9 compat runtime image
- if not, we use the current Jetty9 compat image we build.
This will ease the transition to the new Jetty9 compat runtime for
people migrating to env: 2. Once all are on env: 2, we will remove
entirely the support for the legacy Jetty9 compat runtime.
"""
def __init__(self, appinfo, deploy, entrypoint, server,
openjdk, artifact_to_deploy, custom):
"""Constructor.
Args:
appinfo: (apphosting.api.appinfo.AppInfoExternal or None) The parsed
app.yaml file for the module if it exists.
deploy: (bool) True if run in deployment mode.
entrypoint: (str) Name of the entrypoint to generate.
server: (str) Name of the server to use (jetty9 or None for now).
openjdk: (str) Name of the jdk to use (openjdk8 or None for now).
artifact_to_deploy: (str) Name of the file or directory to deploy.
custom: (bool) True if it is a custom runtime.
"""
self.appinfo = appinfo
self.deploy = deploy
self.custom = custom
self.entrypoint = entrypoint
self.server = server
self.openjdk = openjdk
self.artifact_to_deploy = artifact_to_deploy
def GenerateConfigs(self):
"""Generates config files for the module, not including app.yaml.
For app.yaml generation, see gae-xrt-java/bin/detect.
"""
if self.custom or self.deploy:
self._GenerateDockerfile()
self._GenerateDockerignore()
def _GenerateDockerfile(self):
"""Generates a Dockerfile appropriate to this application.
Raises:
JavaConfigError: if there is an app.yaml configuration error.
"""
# Customize the dockerfile.
out = StringIO.StringIO()
if self.artifact_to_deploy.endswith('.war'):
if self.appinfo and is_flex(self.appinfo.env):
out.write(constants.DOCKERFILE_JETTY_PREAMBLE)
else:
out.write(constants.DOCKERFILE_JETTY9_PREAMBLE)
out.write(constants.DOCKERFILE_INSTALL_WAR.format(
self.artifact_to_deploy))
if self.artifact_to_deploy.endswith('.jar'):
if self.server is not None:
raise JavaConfigError('Cannot use server %s '
'for jar deployment.' % self.server)
if self.appinfo and is_flex(self.appinfo.env):
out.write(constants.DOCKERFILE_JAVA_PREAMBLE)
else:
out.write(constants.DOCKERFILE_JAVA8_PREAMBLE)
out.write(constants.DOCKERFILE_INSTALL_APP.format(
self.artifact_to_deploy))
if self.artifact_to_deploy == '.':
if self.appinfo and is_flex(self.appinfo.env):
out.write(constants.DOCKERFILE_COMPAT_PREAMBLE)
elif self.openjdk == 'openjdk8':
out.write(constants.DOCKERFILE_COMPAT_PREAMBLE)
else:
out.write(constants.DOCKERFILE_LEGACY_PREAMBLE)
out.write(constants.DOCKERFILE_INSTALL_APP.format(
self.artifact_to_deploy))
# Generate the appropriate start command.
if self.entrypoint:
out.write(constants.DOCKERFILE_CMD % self.entrypoint)
elif self.artifact_to_deploy.endswith('.jar'):
# for jar execution generate the command to run:
out.write(constants.DOCKERFILE_JAVA8_JAR_CMD.format(
self.artifact_to_deploy))
comm.gen_file('Dockerfile', out.getvalue())
def _GenerateDockerignore(self):
"""Generates a .dockerignore file appropriate to this application."""
comm.gen_file('.dockerignore', ROOT.read_file('data', 'dockerignore'))
def main(args):
config = comm.get_config()
JavaConfigurator(config.params.appinfo,
config.params.deploy,
config.runtime_data.entrypoint,
config.runtime_data.server,
config.runtime_data.openjdk,
config.runtime_data.artifact_to_deploy,
config.params.custom).GenerateConfigs()
if __name__ == '__main__':
sys.exit(main(sys.argv))

View File

@@ -0,0 +1,6 @@
.dockerignore
Dockerfile
.git
.hg
.svn
app.yaml

View File

@@ -0,0 +1,174 @@
# 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.
# Note: this file is part of the sdk-ext-runtime package. It gets copied into
# individual GAE runtime modules so that they can be easily deployed.
import json
import os
import sys
class JSONObject(object):
"""Wrapper for a JSON object.
Presents a JSON object as a python object (where fields are attributes)
instead of a dictionary. Undefined attributes produce a value of None
instead of an AttributeError.
Note that attribute names beginning with an underscore are excluded.
"""
def __getattr__(self, attr):
return None
def to_dict(self):
result = {}
for attr, val in self.__dict__.iteritems():
if not attr.startswith('_'):
result[attr] = _make_serializable(val)
return result
# Alias old style naming so this interoperates with gcloud's appinfo.
ToDict = to_dict
def _make_serializable(obj):
"""Converts objects to serializable form."""
if isinstance(obj, JSONObject):
return obj.to_dict()
else:
return obj
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, default=_make_serializable)
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, ...} or None) 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:
(JSONObject)
"""
obj = JSONObject()
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)
def query_user(prompt, default=None):
"""Query the user for data.
Args:
prompt: (str) Prompt to display to the user.
default: (str or None) Default value to use if the user doesn't input
anything.
Returns:
(str) Value returned by the user.
"""
kwargs = {}
kwargs['prompt'] = prompt
if default is not None:
kwargs['default'] = default
_write_msg(type='query_user', **kwargs)
return json.loads(sys.stdin.readline())['result']

View File

@@ -0,0 +1,30 @@
# 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.
"""Constants shared by plugin and tests."""
# rutimes based on appengine-java-vm-runtime GitHub repo
DOCKERFILE_JAVA8_PREAMBLE = 'FROM gcr.io/google_appengine/openjdk8\n'
DOCKERFILE_JETTY9_PREAMBLE = 'FROM gcr.io/google_appengine/jetty9\n'
# runtimes based on openjdk-runtime and jetty-runtime GitHub repos
DOCKERFILE_JAVA_PREAMBLE = 'FROM gcr.io/google_appengine/openjdk\n'
DOCKERFILE_JETTY_PREAMBLE = 'FROM gcr.io/google_appengine/jetty\n'
DOCKERFILE_LEGACY_PREAMBLE = 'FROM gcr.io/google_appengine/java-compat\n'
DOCKERFILE_COMPAT_PREAMBLE = 'FROM gcr.io/google_appengine/jetty9-compat\n'
DOCKERFILE_CMD = 'CMD {0}\n'
DOCKERFILE_JAVA8_JAR_CMD = 'CMD ["java", "-jar", "/app/{0}"]\n'
DOCKERFILE_INSTALL_APP = 'ADD {0} /app/\n'
DOCKERFILE_INSTALL_WAR = 'ADD {0} $JETTY_BASE/webapps/root.war\n'

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.
name: java
author: mmuller@google.com
description: Official Google Java runtime definition.
api_version: 0.1
detect:
python: bin/detect
generate_configs:
python: bin/generate_configs

View File

@@ -0,0 +1,555 @@
#!/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.
"""Tests of the java runtime."""
import logging
import mock
import os
import re
import sys
import shutil
import tempfile
import textwrap
import unittest
from gae_ext_runtime import testutil
from gae_ext_runtime import ext_runtime
# Augment the path with our library directory.
ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(os.path.join(ROOT_DIR, 'lib'))
import constants
#from googlecloudsdk.third_party.appengine.api import appinfo
#from googlecloudsdk.core import log
#from googlecloudsdk.api_lib.app import ext_runtime
#from googlecloudsdk.api_lib.app.runtimes import fingerprinter
#from googlecloudsdk.api_lib.app.ext_runtimes import fingerprinting
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 assert_no_file(self, *path):
self.assertFalse(os.path.exists(self.full_path(*path)))
def make_app_yaml(self, runtime):
return 'env: flex\nruntime: {runtime}\n'.format(runtime=runtime)
def test_java_all_defaults(self):
self.write_file('foo.jar', '')
self.generate_configs()
self.assert_file_exists_with_contents('app.yaml',
self.make_app_yaml('java'))
self.assert_no_file('Dockerfile')
self.assert_no_file('.dockerignore')
self.generate_configs(deploy=True)
self.assert_file_exists_with_contents(
'.dockerignore',
self.read_runtime_def_file('data', 'dockerignore'))
dockerfile_contents = [
constants.DOCKERFILE_JAVA_PREAMBLE,
constants.DOCKERFILE_INSTALL_APP.format('foo.jar'),
constants.DOCKERFILE_JAVA8_JAR_CMD.format('foo.jar'),
]
self.assert_file_exists_with_contents('Dockerfile',
''.join(dockerfile_contents))
self.assertEqual(set(os.listdir(self.temp_path)),
{'.dockerignore', 'Dockerfile', 'app.yaml', 'foo.jar'})
def test_java_all_defaults_no_write(self):
"""Test generate_config_data after writing app.yaml."""
self.write_file('foo.jar', '')
self.generate_configs()
self.assert_file_exists_with_contents('app.yaml',
self.make_app_yaml('java'))
self.assert_no_file('Dockerfile')
self.assert_no_file('.dockerignore')
cfg_files = self.generate_config_data(deploy=True)
self.assert_genfile_exists_with_contents(
cfg_files,
'.dockerignore',
self.read_runtime_def_file('data', 'dockerignore'))
dockerfile_contents = [
constants.DOCKERFILE_JAVA_PREAMBLE,
constants.DOCKERFILE_INSTALL_APP.format('foo.jar'),
constants.DOCKERFILE_JAVA8_JAR_CMD.format('foo.jar'),
]
self.assert_genfile_exists_with_contents(
cfg_files,
'Dockerfile',
''.join(dockerfile_contents))
self.assertEqual(set(os.listdir(self.temp_path)),
{'app.yaml', 'foo.jar'})
def test_java_custom(self):
self.write_file('foo.jar', '')
self.generate_configs(deploy=False, custom=True)
self.assert_file_exists_with_contents('app.yaml',
self.make_app_yaml('custom'))
self.assert_file_exists_with_contents(
'.dockerignore',
self.read_runtime_def_file('data', 'dockerignore'))
dockerfile_contents = [
constants.DOCKERFILE_JAVA_PREAMBLE,
constants.DOCKERFILE_INSTALL_APP.format('foo.jar'),
constants.DOCKERFILE_JAVA8_JAR_CMD.format('foo.jar'),
]
self.assert_file_exists_with_contents('Dockerfile',
''.join(dockerfile_contents))
def test_java_custom_no_write(self):
"""Test generate_config_data with custom=True.
app.yaml should be written to disk. Also tests correct dockerfile
contents with a .jar.
"""
self.write_file('foo.jar', '')
cfg_files = self.generate_config_data(deploy=False, custom=True)
self.assert_file_exists_with_contents('app.yaml',
self.make_app_yaml('custom'))
self.assert_genfile_exists_with_contents(
cfg_files,
'.dockerignore',
self.read_runtime_def_file('data', 'dockerignore'))
dockerfile_contents = [
constants.DOCKERFILE_JAVA_PREAMBLE,
constants.DOCKERFILE_INSTALL_APP.format('foo.jar'),
constants.DOCKERFILE_JAVA8_JAR_CMD.format('foo.jar'),
]
self.assert_genfile_exists_with_contents(
cfg_files,
'Dockerfile',
''.join(dockerfile_contents))
def test_java_files_no_java(self):
self.write_file('foo.nojava', '')
self.assertFalse(self.generate_configs())
self.assertEqual(os.listdir(self.temp_path), ['foo.nojava'])
def test_java_files_with_war(self):
self.write_file('foo.war', '')
self.generate_configs()
self.assert_file_exists_with_contents('app.yaml',
self.make_app_yaml('java'))
self.assert_no_file('Dockerfile')
self.assert_no_file('.dockerignore')
self.generate_configs(deploy=True)
dockerfile_contents = [
constants.DOCKERFILE_JETTY_PREAMBLE,
constants.DOCKERFILE_INSTALL_WAR.format('foo.war'),
]
self.assert_file_exists_with_contents('Dockerfile',
''.join(dockerfile_contents))
self.assert_file_exists_with_contents(
'.dockerignore', self.read_runtime_def_file('data', 'dockerignore'))
def test_java_files_with_war_no_write(self):
"""Test generate_config_data Dockerfile contents with .war file."""
self.write_file('foo.war', '')
self.generate_configs()
self.assert_file_exists_with_contents('app.yaml',
self.make_app_yaml('java'))
self.assert_no_file('Dockerfile')
self.assert_no_file('.dockerignore')
cfg_files = self.generate_config_data(deploy=True)
dockerfile_contents = [
constants.DOCKERFILE_JETTY_PREAMBLE,
constants.DOCKERFILE_INSTALL_WAR.format('foo.war'),
]
self.assert_genfile_exists_with_contents(
cfg_files,
'Dockerfile',
''.join(dockerfile_contents))
self.assert_genfile_exists_with_contents(
cfg_files,
'.dockerignore',
self.read_runtime_def_file('data', 'dockerignore'))
def test_java_files_with_jar(self):
self.write_file('foo.jar', '')
self.generate_configs()
self.assert_file_exists_with_contents('app.yaml',
self.make_app_yaml('java'))
self.assert_no_file('Dockerfile')
self.assert_no_file('.dockerignore')
self.generate_configs(deploy=True)
dockerfile_contents = [
constants.DOCKERFILE_JAVA_PREAMBLE,
constants.DOCKERFILE_INSTALL_APP.format('foo.jar'),
constants.DOCKERFILE_JAVA8_JAR_CMD.format('foo.jar'),
]
self.assert_file_exists_with_contents('Dockerfile',
''.join(dockerfile_contents))
self.assert_file_exists_with_contents(
'.dockerignore',
self.read_runtime_def_file('data', 'dockerignore'))
def test_java_files_with_jar_no_write(self):
"""Test generate_config_data Dockerfile contents with .jar file."""
self.write_file('foo.jar', '')
self.generate_configs()
self.assert_file_exists_with_contents('app.yaml',
self.make_app_yaml('java'))
self.assert_no_file('Dockerfile')
self.assert_no_file('.dockerignore')
cfg_files = self.generate_config_data(deploy=True)
dockerfile_contents = [
constants.DOCKERFILE_JAVA_PREAMBLE,
constants.DOCKERFILE_INSTALL_APP.format('foo.jar'),
constants.DOCKERFILE_JAVA8_JAR_CMD.format('foo.jar'),
]
self.assert_genfile_exists_with_contents(
cfg_files,
'Dockerfile',
''.join(dockerfile_contents))
self.assert_genfile_exists_with_contents(
cfg_files,
'.dockerignore',
self.read_runtime_def_file('data', 'dockerignore'))
def test_java_files_with_webinf(self):
self.write_file('WEB-INF', '')
self.generate_configs()
self.assert_file_exists_with_contents('app.yaml',
self.make_app_yaml('java'))
self.assert_no_file('Dockerfile')
self.assert_no_file('.dockerignore')
self.generate_configs(deploy=True)
dockerfile_contents = [
constants.DOCKERFILE_COMPAT_PREAMBLE,
constants.DOCKERFILE_INSTALL_APP.format('.'),
]
self.assert_file_exists_with_contents('Dockerfile',
''.join(dockerfile_contents))
self.assert_file_exists_with_contents(
'.dockerignore',
self.read_runtime_def_file('data', 'dockerignore'))
def test_java_files_with_webinf_no_write(self):
"""Test generate_config_data Dockerfile contents with 'WEB-INF' file."""
self.write_file('WEB-INF', '')
self.generate_configs()
self.assert_file_exists_with_contents('app.yaml',
self.make_app_yaml('java'))
self.assert_no_file('Dockerfile')
self.assert_no_file('.dockerignore')
cfg_files = self.generate_config_data(deploy=True)
dockerfile_contents = [
constants.DOCKERFILE_COMPAT_PREAMBLE,
constants.DOCKERFILE_INSTALL_APP.format('.'),
]
self.assert_genfile_exists_with_contents(
cfg_files,
'Dockerfile',
''.join(dockerfile_contents))
self.assert_genfile_exists_with_contents(
cfg_files,
'.dockerignore',
self.read_runtime_def_file('data', 'dockerignore'))
def test_java_files_with_too_many_artifacts(self):
self.write_file('WEB-INF', '')
self.write_file('foo.jar', '')
errors = []
def ErrorFake(message):
errors.append(message)
with mock.patch.dict(ext_runtime._LOG_FUNCS, {'error': ErrorFake}):
self.assertFalse(self.generate_configs())
self.assertEqual(errors,
['Too many java artifacts to deploy (.jar, .war, or '
'Java Web App).'])
# TODO(b/63385240): cover the case were the app.yaml might not be called
# app.yaml. For example: "gen-config --config=foo.yaml <path>"
# will use foo.yaml
def test_java_files_with_war_and_yaml(self):
self.write_file('foo.war', '')
appinfo = testutil.AppInfoFake(
runtime='java',
env='flex',
runtime_config=dict(
jdk='openjdk8',
server='jetty9'))
self.generate_configs(appinfo=appinfo, deploy=True)
dockerfile_contents = [
constants.DOCKERFILE_JETTY_PREAMBLE,
constants.DOCKERFILE_INSTALL_WAR.format('foo.war'),
]
self.assert_file_exists_with_contents('Dockerfile',
''.join(dockerfile_contents))
self.assert_file_exists_with_contents(
'.dockerignore',
self.read_runtime_def_file('data', 'dockerignore'))
def test_java_files_with_war_and_yaml_no_write(self):
"""Test generate_config_data with .war and fake appinfo."""
self.write_file('foo.war', '')
appinfo = testutil.AppInfoFake(
runtime='java',
env='2',
runtime_config=dict(
jdk='openjdk8',
server='jetty9'))
cfg_files = self.generate_config_data(appinfo=appinfo, deploy=True)
dockerfile_contents = [
constants.DOCKERFILE_JETTY_PREAMBLE,
constants.DOCKERFILE_INSTALL_WAR.format('foo.war'),
]
self.assert_genfile_exists_with_contents(
cfg_files,
'Dockerfile',
''.join(dockerfile_contents))
self.assert_genfile_exists_with_contents(
cfg_files,
'.dockerignore',
self.read_runtime_def_file('data', 'dockerignore'))
def test_java_files_with_web_inf_and_yaml_and_env2(self):
self.write_file('WEB-INF', '')
config = testutil.AppInfoFake(
runtime='java',
env='2',
runtime_config=dict(
jdk='openjdk8',
server='jetty9'))
self.generate_configs(appinfo=config, deploy=True)
dockerfile_contents = [
constants.DOCKERFILE_COMPAT_PREAMBLE,
constants.DOCKERFILE_INSTALL_APP.format('.'),
]
self.assert_file_exists_with_contents('Dockerfile',
''.join(dockerfile_contents))
self.assert_file_exists_with_contents(
'.dockerignore',
self.read_runtime_def_file('data', 'dockerignore'))
def test_java_files_with_web_inf_and_yaml_and_env2_no_write(self):
"""Test generate_config_data with .war, fake appinfo, env=2."""
self.write_file('WEB-INF', '')
config = testutil.AppInfoFake(
runtime='java',
env='2',
runtime_config=dict(
jdk='openjdk8',
server='jetty9'))
cfg_files = self.generate_config_data(appinfo=config, deploy=True)
dockerfile_contents = [
constants.DOCKERFILE_COMPAT_PREAMBLE,
constants.DOCKERFILE_INSTALL_APP.format('.'),
]
self.assert_genfile_exists_with_contents(
cfg_files,
'Dockerfile',
''.join(dockerfile_contents))
self.assert_genfile_exists_with_contents(
cfg_files,
'.dockerignore',
self.read_runtime_def_file('data', 'dockerignore'))
def test_java_files_with_web_inf_and_yaml_and_no_env2(self):
self.write_file('WEB-INF', '')
config = testutil.AppInfoFake(
runtime='java',
vm=True,
runtime_config=dict(server='jetty9'))
self.generate_configs(appinfo=config, deploy=True)
dockerfile_contents = [
constants.DOCKERFILE_LEGACY_PREAMBLE,
constants.DOCKERFILE_INSTALL_APP.format('.'),
]
self.assert_file_exists_with_contents('Dockerfile',
''.join(dockerfile_contents))
self.assert_file_exists_with_contents(
'.dockerignore',
self.read_runtime_def_file('data', 'dockerignore'))
def test_java_files_with_web_inf_and_yaml_and_no_env2_no_write(self):
"""Test generate_config_data with .war, fake appinfo, env != 2."""
self.write_file('WEB-INF', '')
config = testutil.AppInfoFake(
runtime='java',
vm=True,
runtime_config=dict(server='jetty9'))
cfg_files = self.generate_config_data(appinfo=config, deploy=True)
dockerfile_contents = [
constants.DOCKERFILE_LEGACY_PREAMBLE,
constants.DOCKERFILE_INSTALL_APP.format('.'),
]
self.assert_genfile_exists_with_contents(
cfg_files,
'Dockerfile',
''.join(dockerfile_contents))
self.assert_genfile_exists_with_contents(
cfg_files,
'.dockerignore',
self.read_runtime_def_file('data', 'dockerignore'))
def test_java_files_with_web_inf_and_yaml_and_open_jdk8_no_env2(self):
self.write_file('WEB-INF', '')
config = testutil.AppInfoFake(
runtime='java',
vm=True,
runtime_config=dict(
jdk='openjdk8',
server='jetty9'))
self.generate_configs(appinfo=config, deploy=True)
dockerfile_contents = [
constants.DOCKERFILE_COMPAT_PREAMBLE,
constants.DOCKERFILE_INSTALL_APP.format('.'),
]
self.assert_file_exists_with_contents('Dockerfile',
''.join(dockerfile_contents))
self.assert_file_exists_with_contents(
'.dockerignore',
self.read_runtime_def_file('data', 'dockerignore'))
def test_java_files_with_web_inf_and_yaml_and_open_jdk8_no_env2_no_write(
self):
"""Test generate_config_data with WEB-INF file, fake appinfo."""
self.write_file('WEB-INF', '')
config = testutil.AppInfoFake(
runtime='java',
vm=True,
runtime_config=dict(
jdk='openjdk8',
server='jetty9'))
cfg_files = self.generate_config_data(appinfo=config, deploy=True)
dockerfile_contents = [
constants.DOCKERFILE_COMPAT_PREAMBLE,
constants.DOCKERFILE_INSTALL_APP.format('.'),
]
self.assert_genfile_exists_with_contents(
cfg_files,
'Dockerfile',
''.join(dockerfile_contents))
self.assert_genfile_exists_with_contents(
cfg_files,
'.dockerignore',
self.read_runtime_def_file('data', 'dockerignore'))
def test_java_files_with_config_error(self):
self.write_file('foo.war', '')
errors = []
def ErrorFake(message):
errors.append(message)
config = testutil.AppInfoFake(
runtime='java',
env='2',
runtime_config=dict(
jdk='openjdk9'))
with mock.patch.dict(ext_runtime._LOG_FUNCS, {'error': ErrorFake}):
self.assertFalse(self.generate_configs(appinfo=config, deploy=True))
self.assertEqual(errors, ['Unknown JDK : openjdk9.'])
def test_java_custom_runtime_field(self):
self.write_file('foo.jar', '')
config = testutil.AppInfoFake(
runtime='java',
env='2')
self.assertTrue(self.generate_configs(appinfo=config, deploy=True))
def test_java7_runtime(self):
self.write_file('WEB-INF', '')
config = testutil.AppInfoFake(
runtime='java7',
vm=True)
self.generate_configs(appinfo=config, deploy=True)
dockerfile_contents = [
constants.DOCKERFILE_LEGACY_PREAMBLE,
constants.DOCKERFILE_INSTALL_APP.format('.'),
]
self.assert_file_exists_with_contents('Dockerfile',
''.join(dockerfile_contents))
self.assert_file_exists_with_contents(
'.dockerignore',
self.read_runtime_def_file('data', 'dockerignore'))
def test_java7_runtime_no_write(self):
"""Test generate_config_data with java7 runtime."""
self.write_file('WEB-INF', '')
config = testutil.AppInfoFake(
runtime='java7',
vm=True)
cfg_files = self.generate_config_data(appinfo=config, deploy=True)
dockerfile_contents = [
constants.DOCKERFILE_LEGACY_PREAMBLE,
constants.DOCKERFILE_INSTALL_APP.format('.'),
]
self.assert_genfile_exists_with_contents(
cfg_files,
'Dockerfile',
''.join(dockerfile_contents))
self.assert_genfile_exists_with_contents(
cfg_files,
'.dockerignore',
self.read_runtime_def_file('data', 'dockerignore'))
def test_detect_appinfo_war(self):
self.write_file('foo.war', '')
configurator = self.detect()
self.assertEqual(configurator.generated_appinfo, {'runtime':'java',
'env': 'flex'})
def test_detect_appinfo_jar(self):
self.write_file('foo.jar', '')
configurator = self.detect()
self.assertEqual(configurator.generated_appinfo, {'runtime':'java',
'env': 'flex'})
if __name__ == '__main__':
unittest.main()