This repository has been archived by the owner on Dec 29, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 63
/
deploy_impl.py
581 lines (475 loc) · 18.6 KB
/
deploy_impl.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
# Copyright 2018 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.
# Lint as: python2, python3
"""The Grab n Go App Management Script.
usage: deploy_impl.py [FLAGS] [APPLICATION] [DEPLOYMENT]
Build and deploy the Grab n Go Loaner Web and Chrome Applications.
FLAGS (defaults set in deploy.sh)
APPLICATION: web or chrome
DEPLOYMENT: local, dev, qa, or prod
If no deployment is supplied the script defaults to building the application
locally.
Running the script with no arguments will show this help message.
Do not invoke directly -- use deploy.sh for instructions.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import datetime
import getpass
import json
import os
import shutil
import subprocess
import sys
import zipfile
from absl import app
from absl import flags
from absl import logging
import six
from six.moves import input
FLAGS = flags.FLAGS
flags.DEFINE_list(
'app_servers', None,
'A comma separated list of available app servers. '
'They should be in the format of name=project')
flags.DEFINE_string(
'build_target', None,
'The BUILD target specified in the loaner_appengine_binary rule found in '
'the //web_app_dir/BUILD file')
flags.DEFINE_string(
'chrome_app_dir', None,
'The Chrome App Directory, relative to the @gng bazel WORKSPACE.')
flags.DEFINE_string(
'loaner_path', None,
'The absolute path to the loaner directory inside the @gng bazel '
'WORKSPACE.')
flags.DEFINE_string(
'version', None,
'The version string to use.\n'
'NOTE: If supplied it overrides the default version string which consists '
'of the username of the user executing this script and the current date. '
'The default version is unique for each user on a given day. '
'Multiple deployments on a given day without a version specified will '
'overwrite the existing App Engine version.')
flags.DEFINE_string(
'web_app_dir', None,
'The Web App Directory, relative to the @gng bazel WORKSPACE.')
flags.DEFINE_list(
'yaml_files', None,
'A comma separated list of the App Engine services to deploy.')
_LOCAL = 'local'
_MANIFEST_FILENAME = 'manifest.json'
_ZIPFILENAME = 'loaner_chrome_app.zip'
_APP_SERVER_ERROR = (
'App Servers need to be a comma separated list in the following format:'
' type=project\nInstead received: {}\n'
'Please check the deploy.sh configuration.')
class Error(Exception):
"""Base error class for this module."""
class ManifestError(Error):
"""Raised when there is an error with the manifest.json file."""
def __init__(self, errno):
self.errno = errno
super(ManifestError, self).__init__()
def _EnsureStr(s, encoding='utf-8', errors='strict'):
"""Coerce *s* to `str`.
Args:
s: string or bytes
encoding: string encoding
errors: raise errors
Returns:
PY3 and PY3 str type
For Python 2:
- `unicode` -> encoded to `str`
- `str` -> `str`
For Python 3:
- `str` -> `str`
- `bytes` -> decoded to `str`
# Needs to be removed once six version is uograded to 1.12.0 or above
# And replace with `six.ensure_str`
"""
if not isinstance(s, (six.text_type, six.binary_type)):
raise TypeError("not expecting type '%s'" % type(s))
if six.PY2 and isinstance(s, six.text_type):
s = s.encode(encoding, errors)
elif six.PY3 and isinstance(s, six.binary_type):
s = s.decode(encoding, errors)
return s
def _ParseAppServers(app_servers):
"""Parse the app servers for name and project id.
Args:
app_servers: list|str|, a list of strings defining the Google Cloud Project
IDs by friendly name.
Returns:
A dictionary with the friendly name as the key and the Google Cloud Project
ID as the value.
"""
return dict(_EnsureStr(server).split('=', 1) for server in app_servers)
def _AppServerValidator(app_servers):
"""Validate the App Engine servers are of the right format.
Args:
app_servers: list|str|, a list of strings defining the Google Cloud Project
IDs by friendly name.
Returns:
True if the app_servers are in the correct format.
Raises:
flags.ValidationError, if the app_servers are in the incorrect format.
"""
try:
_ParseAppServers(app_servers)
except ValueError:
raise flags.ValidationError(_APP_SERVER_ERROR.format(app_servers))
return True
def _ExecuteCommand(command):
"""Execute a command in the shell.
Args:
command: list, a list of strings the build a command to execute.
Returns:
A running process.
"""
process = subprocess.Popen(command)
result = process.wait()
if result:
sys.exit(result)
return process
def _ZipRelativePath(path, name, root):
"""Create a new relative path ZipFile.
Args:
path: str, the path to begin zipping.
name: str, the name of the archive.
root: str, the root path to strip off the archived files.
"""
archive = zipfile.ZipFile(name, 'w', zipfile.ZIP_DEFLATED)
if os.path.isdir(path):
_ZipRecursively(path, archive, root)
else:
archive.write(path)
archive.close()
def _ZipRecursively(path, archive, root):
"""Recursive path ziping relative to the Chrome Application Bundle.
Args:
path: str, the path to traverse for the zip.
archive: ZipFile, the archive instance to write to.
root: str, the root path to strip off the archived files.
"""
paths = os.listdir(path)
for p in paths:
p = os.path.join(path, p)
if os.path.isdir(p):
_ZipRecursively(p, archive, root)
else:
archive.write(p, os.path.relpath(p, root))
return
class LoanerConfig(object):
"""Loaner configuration object to store relevant variables.
Attributes:
deployment_type: str, the friendly name of the Google Cloud Project to
deploy to.
loaner_path: str, the relative path to the loaner directory in the @gng
bazel WORKSPACE.
"""
def __init__(self, deployment_type, loaner_path):
self._deployment_type = deployment_type
self._loaner_path = loaner_path
@property
def workspace_path(self):
"""Returns the absolute loaner path as a string."""
return os.path.abspath(os.path.join(self._loaner_path, '..'))
@property
def npm_path(self):
"""Retrieve the npm root path as a string."""
return os.path.abspath(self._loaner_path)
@property
def node_modules_path(self):
"""Retrieve the node_modules path as a string."""
return os.path.join(self.npm_path, 'node_modules')
@property
def on_local(self):
"""Returns whether or not this is to be deployed locally."""
return self._deployment_type == _LOCAL
@property
def on_google_cloud_shell(self):
"""Returns whether or not we are on Google Cloud Shell."""
return os.environ.get('CLOUD_SHELL') == 'true'
class AppEngineServerConfig(LoanerConfig):
"""App Engine specific server configurations.
Attributes:
app_servers: list|str|, app server definitions in the format name=project.
build_target: str, the BUILD target for the App Engine binary.
deployment_type: str, the friendly name of the Google Cloud Project to
deploy to.
loaner_path: str, the relative path to the loaner directory in the @gng
bazel WORKSPACE.
version: str, the App Engine version for this deployment.
web_app_dir: str, the relative path to the web_app directory in the @gng
bazel WORKSPACE.
yaml_files: list|str|, a list of the yaml files defining the App Engine
services to deploy.
"""
def __init__(
self, app_servers, build_target, deployment_type, loaner_path, version,
web_app_dir, yaml_files):
super(AppEngineServerConfig, self).__init__(deployment_type, loaner_path)
self._build_target = build_target
self._version = version
self._web_app_dir = web_app_dir
self._yaml_files = yaml_files
self._app_servers = _ParseAppServers(app_servers)
if self._deployment_type not in list(self._app_servers.keys()):
raise app.UsageError(
'Application name provided is not in the list of App Servers.\n'
'Please check the name and/or the deploy.sh configuration.')
@property
def project_id(self):
"""Returns the Google Cloud Project ID as a string."""
return self._app_servers[self._deployment_type]
@property
def version(self):
"""Returns the version string for the App Engine services as a string."""
if self._version:
return self._version
return '{user}-{date}'.format(
user=getpass.getuser(), date=datetime.datetime.strftime(
datetime.datetime.now(), '%Y%m%d'))
@property
def bundle_path(self):
"""Retrieve the path to the bazel built bundle as a string."""
return os.path.join(
self.workspace_path, 'bazel-bin', self._web_app_dir,
'{bundle}.runfiles'.format(bundle=self._build_target))
@property
def app_path(self):
"""Retrieve the path to the bazel built application as a string."""
return os.path.join(self.bundle_path, 'gng')
@property
def app_engine_deps_path(self):
"""Retrieve the App Engine Dependencies path as a string."""
return os.path.join(self.app_path, 'external', 'com_google_appengine_py')
@property
def frontend_src_path(self):
"""Retrieve the Frontend path as a string."""
return os.path.join(self.workspace_path, 'loaner', 'web_app', 'frontend')
@property
def frontend_bundle_path(self):
"""Retrieve the path to the bundled Frontend as a string."""
return os.path.join(self.app_path, 'loaner', 'web_app', 'frontend', 'src')
def _DeleteAppEngExtDepDir(self):
"""Deletes the GAE external dependencies directory."""
if os.path.isdir(self.app_engine_deps_path):
logging.info('Removing the local copy of the App Engine dependencies.')
shutil.rmtree(self.app_engine_deps_path)
def _DeleteNodeModulesDir(self):
"""Deletes the node_modules directory."""
if os.path.isdir(self.node_modules_path):
logging.info(
'Removing the node_modules directory because we are building on '
'Google Cloud Shell.')
shutil.rmtree(self.node_modules_path)
def _MoveWebAppFrontendBundle(self):
"""Prepare frontend bundle destination and move the build there."""
if os.path.isdir(self.frontend_bundle_path):
logging.info(
'The bundled frontend exists, we are replacing it with a new build.')
shutil.rmtree(self.frontend_bundle_path)
logging.debug('Moving the frontend bundle into the web app bundle.')
shutil.move(
os.path.join(self.frontend_src_path, 'dist'), self.frontend_bundle_path)
def _CleanWebAppBackend(self):
"""Run bazel clean --expunge in order to reduce filesystem utilziation."""
logging.info('Running bazel clean --expunge_async because we are building '
'on Google Cloud Shell')
_ExecuteCommand(['bazel', 'clean', '--expunge_async'])
def _BuildWebAppBackend(self):
"""Build the Web Application's backend services."""
logging.debug('Building the backend using Bazel...')
_ExecuteCommand([
'bazel', 'build', '//{}:{}'.format(
self._web_app_dir, self._build_target)])
if not self.on_local:
self._DeleteAppEngExtDepDir()
def _BuildWebAppFrontend(self):
"""Build the Web Application's frontend services."""
logging.debug('Building the frontend using npm...')
os.chdir(self.npm_path)
_ExecuteCommand(['npm', 'install'])
_ExecuteCommand(['npm', 'run', 'build:frontend'])
if self.on_google_cloud_shell:
self._DeleteNodeModulesDir()
def _BundleWebApp(self):
"""Bundle the web application using bazel and npm."""
self._BuildWebAppFrontend()
self._BuildWebAppBackend()
self._MoveWebAppFrontendBundle()
def _GetYamlFile(self, yaml_filename):
"""Returns the full path for a given yaml file in the bundle.
Args:
yaml_filename: str, the basename for a yaml file.
Returns:
The full path for the yaml file in the App Engine bundle as a string.
"""
return os.path.join(self.app_path, yaml_filename)
def DeployWebApp(self):
"""Bundle then deploy (or run locally) the web application."""
self._BundleWebApp()
if self.on_local:
print('Run locally...')
else:
cmds = [
'gcloud', 'app', 'deploy', '--no-promote', '--project={}'.format(
self.project_id), '--version={}'.format(self.version)]
for yaml_filename in self._yaml_files:
cmds.append(self._GetYamlFile(yaml_filename))
logging.info(
'Deploying to the Google Cloud project: %s using gcloud...',
self.project_id)
_ExecuteCommand(cmds)
if self.on_google_cloud_shell:
self._CleanWebAppBackend()
class ChromeAppConfig(LoanerConfig):
"""Chrome Application specific configurations.
Attributes:
chrome_app_dir: str, the relative path to the chrome_app directory in the
@gng bazel WORKSPACE.
deployment_type: str, the friendly name of the Google Cloud Project to
deploy to.
loaner_path: str, the relative path to the loaner directory in the @gng
bazel WORKSPACE.
"""
def __init__(self, chrome_app_dir, deployment_type, loaner_path):
super(ChromeAppConfig, self).__init__(deployment_type, loaner_path)
self._chrome_app_dir = chrome_app_dir
@property
def chrome_app_src_dir(self):
"""Retrieve the absolute path for the Chrome App source as a string."""
return os.path.join(self.workspace_path, self._chrome_app_dir)
@property
def manifest_file(self):
"""Retrieve the absolute path for the manifest.json file as a string."""
return os.path.join(self.chrome_app_src_dir, _MANIFEST_FILENAME)
@property
def chrome_app_temp_dir(self):
"""Retrieve the absolute path for the bundled Chrome App as a string."""
return os.path.join(self.chrome_app_src_dir, 'dist')
@property
def chrome_app_archive(self):
"""Retrieve the final location of the Chrome Application's archive."""
return os.path.join(self.workspace_path, _ZIPFILENAME)
def _ManifestCheck(self):
"""Check the manifest.json file for required key/value pairs.
Raises:
ManifestError: when there is an issue with the manifest.json file.
"""
logging.debug('Checking the manifest file...')
with open(self.manifest_file, 'r') as manifest_data:
try:
data = json.load(manifest_data)
# Catch syntax errors.
except ValueError:
sys.stderr.write(
"The there is a syntax error in the Chrome App's"
"manifest.json file, located at: {}\n".format(self.manifest_file))
raise ManifestError(os.EX_SOFTWARE)
# Set the new version.
current_version = data['version']
data['version'] = input(
'The current Chrome App version is {}, '
'please enter the new version: '.format(current_version))
# Check for the Chrome App Key.
if not data['key']:
sys.stderr.write(
"The manifest key is missing, please place it in the Chrome App's "
"manifest.json file, located at: {}\n".format(self.manifest_file))
raise ManifestError(os.EX_SOFTWARE)
# Check for the OAuth2 Client ID.
if not data['oauth2']['client_id']:
sys.stderr.write(
"The OAuth2 Client ID is missing for the Chrome App, please place "
"it in the Chrome App's manifest.json, "
"file located at: {}\n".format(
self.manifest_file))
raise ManifestError(os.EX_SOFTWARE)
# Write new version to manifest.
with open(self.manifest_file, 'w+') as manifest_data:
json.dump(
data, manifest_data, sort_keys=True, indent=2, separators=(',', ': '))
def _BuildChromeApp(self):
"""Build and bundle the Chrome App."""
logging.debug('Building the Chrome Application...')
self._ManifestCheck()
os.chdir(self.npm_path)
_ExecuteCommand(['npm', 'install'])
_ExecuteCommand(['npm', 'run', 'build:chromeapp:once'])
os.chdir(self.chrome_app_src_dir)
if self.on_local:
print('Local bundling coming soon...')
else:
logging.info('Zipping the Loaner Chrome Application...')
_ZipRelativePath(
self.chrome_app_temp_dir, _ZIPFILENAME, self.chrome_app_temp_dir)
if os.path.isfile(self.chrome_app_archive):
os.remove(self.chrome_app_archive)
shutil.move(
os.path.join(self.chrome_app_src_dir, _ZIPFILENAME),
self.chrome_app_archive)
logging.info(
'The Loaner Chrome Application zip can be found %s',
self.chrome_app_archive)
logging.info('Removing the temp files for the Chrome App...')
shutil.rmtree(self.chrome_app_temp_dir)
def DeployChromeApp(self):
"""Bundle and deploy the Chrome App."""
self._BuildChromeApp()
def main(argv):
argv = argv[1:] # Discard the script name.
# No arguments passed, show usage statement.
if len(argv) < 1:
app.usage(shorthelp=True, exitcode=1)
# Application to deploy: web or chrome.
application = argv[0]
# Server to deploy to: local, dev, or prod.
try:
deployment_type = argv[1]
except IndexError:
logging.info('No deployment type was provided, defaulting to local.')
deployment_type = _LOCAL
if application == 'web':
# If application is web, begin build and deploy for the web app.
app_engine_server_config = AppEngineServerConfig(
app_servers=FLAGS.app_servers,
build_target=FLAGS.build_target,
deployment_type=deployment_type,
loaner_path=FLAGS.loaner_path,
web_app_dir=FLAGS.web_app_dir,
yaml_files=FLAGS.yaml_files,
version=FLAGS.version)
app_engine_server_config.DeployWebApp()
elif application == 'chrome':
# If application is chrome, begin build and deploy for the chrome app.
chrome_app_config = ChromeAppConfig(
chrome_app_dir=FLAGS.chrome_app_dir,
deployment_type=deployment_type,
loaner_path=FLAGS.loaner_path)
try:
chrome_app_config.DeployChromeApp()
except ManifestError as err:
sys.exit(err.errno)
else:
app.usage(shorthelp=True, exitcode=1)
if __name__ == '__main__':
flags.register_validator('app_servers', _AppServerValidator)
flags.mark_flags_as_required([
'app_servers', 'build_target', 'chrome_app_dir', 'loaner_path',
'web_app_dir', 'yaml_files'])
app.run(main)