Debian Codegraph @

case_studies/micromanage/micromanage.py

raw
1 # Copyright 2015 Google Inc. All rights reserved.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 import collections
16 import json
17 import os
18 import shutil
19 import subprocess
20 import sys
21 import tempfile
22 import traceback
23
24 import _jsonnet
25
26 import service_google
27 import service_amazon
28 import util
29 import validate
30
31 # TODO: Simple constraint language for expressing constraints on the generated
32 # infrastructure of production services that if broken during an apply, will
33 # cause the apply to be rejected. Examples:
34 # - resource x must exist (e.g. data integrity)
35 # - at least x things of this type must exist
36
37 service_compilers = {
38 'Google': service_google.GoogleService(),
39 'Amazon': service_amazon.AmazonService(),
40 }
41
42 def get_compiler(config, service):
43 environments = config['environments']
44 environment = environments[service.get('environment', 'default')]
45 return service_compilers[environment['kind']], environment
46
47
48 def config_check_service(environments, root, path):
49 try:
50 service = validate.path_val(root, path, 'object')
51 env_name = validate.path_val(root, path + ['environment'], 'string', 'default')
52 default = env_name == 'default'
53 env = environments.get(env_name)
54 if env is None:
55 if default:
56 raise validate.ConfigError(('The service at %s has no environment field, and no ' +
57 'environment called "default" exists.')
58 % validate.render_path(path))
59 else:
60 raise validate.ConfigError('In %s, unrecognized environment %s'
61 % (validate.render_path(path), env_name))
62 compiler = service_compilers.get(env['kind'])
63 compiler.validateService(root, path)
64 for child_name, child in compiler.children(service):
65 config_check_service(environments, root, path + [child_name])
66 except validate.ConfigError as e:
67 if e.note is None:
68 e.note = ('Did you mean for %s to be a visible field (: instead of ::)?'
69 % validate.render_path(path))
70 raise
71
72 def services(config):
73 for service_name, service in config.iteritems():
74 if service_name == 'environments':
75 continue
76 yield service_name, service
77
78 def config_check(config):
79 validate.path_val(config, [], 'object')
80 environments = validate.path_val(config, ['environments'], 'object', {})
81
82 # Check environments
83 environments = config['environments']
84 for env_name, env in environments.iteritems():
85 kind_name = validate.path_val(config, ['environments', env_name, 'kind'], 'string')
86 compiler = service_compilers.get(kind_name)
87 if not compiler:
88 raise validate.ConfigError(
89 'Unrecognized kind "%s" in environment %s' % (kind_name, env_name))
90 compiler.validateEnvironment(config, ['environments', env_name])
91
92 # Check services
93 for service_name, service in services(config):
94 config_check_service(environments, config, [service_name])
95
96
97 ext_vars = {} # For Jsonnet evaluation
98 search_paths = [ # Where we look for imported jsonnet files
99 os.path.dirname(os.path.realpath(__file__)) + '/lib/'
100 ]
101 debug = False
102
103 # Returns content if worked, None if file not found, or throws an exception
104 def jsonnet_try_path(dir, rel):
105 if not rel:
106 raise RuntimeError('Got invalid filename (empty string).')
107 if rel[0] == '/':
108 full_path = rel
109 else:
110 full_path = dir + rel
111 if full_path[-1] == '/':
112 raise RuntimeError('Attempted to import a directory')
113
114 if not os.path.isfile(full_path):
115 return full_path, None
116 with open(full_path) as f:
117 return full_path, f.read()
118
119
120 def jsonnet_import_callback(dir, rel):
121 full_path, content = jsonnet_try_path(dir, rel)
122 if content:
123 return full_path, content
124 for path in search_paths:
125 full_path, content = jsonnet_try_path(path, rel)
126 if content:
127 return full_path, content
128 raise RuntimeError('File not found')
129
130
131 def config_load(filename, ext_vars):
132 try:
133 text = _jsonnet.evaluate_file(
134 filename,
135 max_trace=100,
136 ext_vars=ext_vars,
137 import_callback=jsonnet_import_callback)
138 except RuntimeError as e:
139 # Error from Jsonnet
140 sys.stderr.write(e.message)
141 sys.stderr.write('\n')
142 sys.exit(1)
143
144 config = json.loads(text)
145 try:
146 config_check(config)
147 except validate.ConfigError as e:
148 if debug:
149 traceback.print_exc()
150 else:
151 sys.stderr.write('Config error: %s\n' % e.message)
152 if e.note:
153 sys.stderr.write('%s\n' % e.note)
154 sys.exit(1)
155 return config
156
157
158 def preprocess(config):
159 """Return a copy of the config with ${-} handled."""
160
161 def aux(service):
162 compiler, _ = get_compiler(config, service)
163 r2 = compiler.preprocess(service)
164 for child_name, child in compiler.children(service):
165 r2[child_name] = aux(child)
166 return r2
167
168 r = {
169 'environments': config['environments'],
170 }
171
172 for service_name, service in services(config):
173 r[service_name] = aux(service)
174
175 return r
176
177
178 def get_build_artefacts(config):
179 """Create all required build artefacts, modify config to refer to them."""
180
181 def aux(ctx, service_name, service):
182 compiler, environment = get_compiler(config, service)
183 new_service, service_barts = compiler.getBuildArtefacts(environment, ctx, service)
184 ctx = ctx + [service_name]
185 for child_name, child in compiler.children(service):
186 new_child, child_barts = aux(ctx, child_name, child)
187 util.merge_into(service_barts, child_barts)
188 new_service[child_name] = new_child
189 return new_service, service_barts
190
191 barts = {}
192 new_config = {
193 'environments': config['environments'],
194 }
195 for service_name, service in services(config):
196 new_service, service_barts = aux([], service_name, service)
197 new_config[service_name] = new_service
198 util.merge_into(barts, service_barts)
199 return new_config, barts
200
201
202 def compile(config, barts):
203 def aux(ctx, service_name, service):
204 compiler, _ = get_compiler(config, service)
205 service_tfs = compiler.compile(ctx, service_name, service, barts)
206 ctx = ctx + [service_name]
207 for child_name, child in compiler.children(service):
208 util.merge_into(service_tfs, aux(ctx, child_name, child))
209 return service_tfs
210
211 tfs = {}
212
213 for service_name, service in services(config):
214 util.merge_into(tfs, aux([], service_name, service))
215
216 for environment_name, environment in config['environments'].iteritems():
217 compiler = service_compilers[environment['kind']]
218 tf_dict = compiler.compileProvider(environment_name, environment)
219 util.merge_into(tfs, tf_dict)
220
221 # Avoid a warning from Terraform that there are no tf files
222 if not len(tfs):
223 tfs['empty.tf.json'] = {}
224
225 # Clean up the output JSON files because Terraform is quite picky.
226 for tfname, tf in tfs.iteritems():
227 if 'resource' in tf:
228 new_resources = {}
229 for rtype_name, rtype_dict in list(tf['resource'].iteritems()):
230 for r_name, r_dict in rtype_dict.iteritems():
231 # Ensure depends_on is always a list.
232 # TODO: Doesn't seem too hard to make sure all configs just provide it as a
233 # list.
234 if 'depends_on' in r_dict and isinstance(r_dict['depends_on'], basestring):
235 r_dict['depends_on'] = [r_dict['depends_on']]
236
237 # Remove types that have no resources.
238 if not rtype_dict:
239 del tf['resource'][rtype_name]
240
241 # Remove empty dicts at the top level.
242 if 'resource' in tf and not tf['resource']:
243 del tf['resource']
244 if 'output' in tf and not tf['output']:
245 del tf['output']
246 return tfs
247
248
249 def confirmation_dialog(msg):
250 sys.stdout.write('%s [y/N]: ' % msg)
251 while True:
252 choice = raw_input().lower()
253 if choice == '':
254 choice = 'n'
255 if choice in ['y', 'n']:
256 break
257 sys.stdout.write('Please press either y or n, then hit enter: ')
258 return choice
259
260
261 def output_delete(dirpath):
262 shutil.rmtree(dirpath)
263
264
265 def action_blueprint(config_file, config, args):
266 if args:
267 sys.stderr.write('Action "blueprint" accepts no arguments, but got: %s\n' % ' '.join(args))
268 sys.exit(1)
269 print(util.jsonstr(config))
270
271
272 def generate(dirpath, config, do_build):
273 files = []
274
275 config = preprocess(config)
276 config, barts = get_build_artefacts(config)
277
278 for bart_name, bart in barts.iteritems():
279 bart.outputFiles(dirpath)
280 files += bart.getOutputFiles(dirpath)
281
282 if not do_build:
283 barts = {}
284
285 barts_to_build = {}
286 # Output build artefact files
287 for bart_name, bart in barts.iteritems():
288 if bart.needsBuild():
289 barts_to_build[bart_name] = bart
290
291 for bart_name, bart in barts_to_build.iteritems():
292 bart.doBuild(dirpath)
293
294 for bart_name, bart in barts_to_build.iteritems():
295 bart.wait(dirpath)
296
297 for bart_name, bart in barts.iteritems():
298 bart.postBuild()
299
300 tfs = compile(config, barts)
301
302 # Output Terraform configs
303 for filename, tf in tfs.iteritems():
304 dirfilename = '%s/%s' % (dirpath, filename)
305 files += [dirfilename]
306 with open(dirfilename, 'w') as f:
307 f.write(util.jsonstr(tf))
308
309 # Copy terraform plugins into the output dir.
310 config_dir = '%s/.terraform' % os.getcwd()
311 if os.path.exists(config_dir):
312 shutil.copytree(config_dir, dirpath + '/.terraform')
313
314 return files
315
316 class SubprocessException(Exception):
317 pass
318
319 def sync_popen(dirpath, command, successful_exit_codes=(0,), stdout=None):
320 try:
321 process = subprocess.Popen(command, cwd=dirpath, stdout=stdout)
322 exit_code = process.wait()
323 if successful_exit_codes is not None and exit_code not in successful_exit_codes:
324 raise SubprocessException('Error from subprocess, ran in %s: %s' % (dirpath, command))
325 return exit_code
326 except OSError as e:
327 raise SubprocessException('Error starting subprocess, ran in %s: %s: (%s)' % (dirpath, command, e))
328
329 def action_generate_to_editor(config_file, config, args):
330 if args:
331 sys.stderr.write('Action "generate-to-editor" accepts no arguments, but got: %s\n' % ' '.join(args))
332 sys.exit(1)
333 dirpath = tempfile.mkdtemp()
334 files = generate(dirpath, config, False)
335 sync_popen(os.getcwd(), [os.getenv('EDITOR')] + files, None)
336 output_delete(dirpath)
337
338 def action_diff(config_file, config, args):
339 if args:
340 sys.stderr.write('Action "diff" accepts no arguments, but got: %s\n' % ' '.join(args))
341 sys.exit(1)
342
343 dirpath = tempfile.mkdtemp()
344 generate(dirpath, config, True)
345
346 command = ['terraform', 'plan',
347 '-state', '%s/%s' % (os.getcwd(), config_file + '.tfstate')]
348 sync_popen(dirpath, command, (0, 2))
349
350 output_delete(dirpath)
351
352 def action_apply(config_file, config, args):
353 if args:
354 sys.stderr.write('Action "apply" accepts no arguments, but got: %s\n' % ' '.join(args))
355 sys.exit(1)
356
357 dirpath = tempfile.mkdtemp()
358 generate(dirpath, config, True)
359
360 state_file = config_file + '.tfstate'
361
362 command = ['terraform', 'plan',
363 '-state', '%s/%s' % (os.getcwd(), state_file),
364 '-detailed-exitcode',
365 '-out', 'tf.plan']
366 plan_exitcode = sync_popen(dirpath, command, (0, 2))
367 if plan_exitcode == 0:
368 pass # Empty plan, nothing to do
369 elif plan_exitcode == 2:
370 choice = confirmation_dialog('Apply these changes?')
371
372 if choice == 'y':
373 command = ['terraform', 'apply', '-state', '%s/%s' % (os.getcwd(), state_file), 'tf.plan']
374 sync_popen(dirpath, command)
375 else:
376 print 'Not applying the changes.'
377
378 output_delete(dirpath)
379
380
381 def action_destroy(config_file, config, args):
382 if args:
383 sys.stderr.write('Action "destroy" accepts no arguments, but got: %s\n' % ' '.join(args))
384 sys.exit(1)
385
386 choice = confirmation_dialog('Destroy all infrastructure?')
387
388 if choice != 'y':
389 print 'Phew, that was a close one.'
390 return
391
392 dirpath = tempfile.mkdtemp()
393 generate(dirpath, config, False)
394 command = ['terraform', 'destroy', '-force', '-state', '%s/%s.tfstate' % (os.getcwd(), config_file)]
395 exitcode = sync_popen(dirpath, command)
396 output_delete(dirpath)
397
398
399 def action_graph(config_file, config, args):
400 if args:
401 sys.stderr.write('Action "graph" accepts no arguments, but got: %s\n' % ' '.join(args))
402 sys.exit(1)
403
404 dirpath = tempfile.mkdtemp()
405 generate(dirpath, config, False)
406 exitcode = sync_popen(dirpath, ['terraform', 'init'])
407 output_delete(dirpath)
408
409
410 def action_init(config_file, config, args):
411 if args:
412 sys.stderr.write('Action "destroy" accepts no arguments, but got: %s\n' % ' '.join(args))
413 sys.exit(1)
414
415 dirpath = tempfile.mkdtemp()
416 generate(dirpath, config, False)
417 sync_popen(dirpath, ['terraform', 'init'])
418 # Copy terraform plugins into the output dir.
419 shutil.copytree('%s/.terraform' % dirpath, os.getcwd() + '/.terraform')
420
421 output_delete(dirpath)
422
423
424 def action_list_services(config_file, config, args):
425 if args:
426 sys.stderr.write('Action "list-services" accepts no arguments, but got: %s\n' % ' '.join(args))
427 sys.exit(1)
428
429 def services_in_subtree(ctx, service_name, service):
430 compiler, environment = get_compiler(config, service)
431 services = ['-'.join(ctx + [service_name])]
432 for child_name, child in compiler.children(service):
433 services += services_in_subtree(ctx + [service_name], child_name, child)
434 return services
435
436 services = []
437 for key in sorted(config.keys()):
438 if key == 'environments':
439 continue
440 services += services_in_subtree([], key, config[key])
441
442 for service in services:
443 print(service)
444
445
446 def action_show(config_file, config, args):
447 if args:
448 sys.stderr.write('Action "show" accepts no arguments, but got: %s\n' % ' '.join(args))
449 sys.exit(1)
450
451 # terraform show assumes that the current directory contains a filename called terraform.tfstate
452 # so create such a directory to make it happy.
453 dirpath = tempfile.mkdtemp()
454 generate(dirpath, config, False)
455 shutil.copyfile('%s/%s.tfstate' % (os.getcwd(), config_file), dirpath + '/terraform.tfstate')
456 sync_popen(dirpath, ['terraform', 'show'])
457 output_delete(dirpath)
458
459
460 def action_output(config_file, config, args):
461 if args:
462 sys.stderr.write('Action "output" accepts no arguments, but got: %s\n' % ' '.join(args))
463 sys.exit(1)
464
465 dirpath = tempfile.mkdtemp()
466 generate(dirpath, config, False)
467 tfstate = '%s/%s.tfstate' % (os.getcwd(), config_file)
468 exitcode = sync_popen(dirpath, ['terraform', 'output', '-state=' + tfstate])
469 output_delete(dirpath)
470
471
472 def action_image_gc(config_file, config, args):
473 raise RuntimeError('Sorry, this code is currently in a state of ill-repair.')
474 config = preprocess(config)
475 config, barts = get_build_artefacts(config)
476
477 used_images = collections.defaultdict(lambda: [])
478 google_images = {}
479 amazon_amis = {}
480
481
482 for bart_name, bart in barts.iteritems():
483 environment = bart.environment
484 if environment['kind'] == 'Google':
485 project = environment['project']
486 used_images[project].append(bart.name())
487 if project not in google_images:
488 image_tuples = google_get_images_json_key(project, environment['serviceAccount'])
489 google_images[project] = image_tuples
490 elif environment['kind'] == 'Amazon':
491 access_key = environment['accessKey']
492 used_images[access_key].append(bart.name())
493 if access_key not in amazon_amis:
494 image_tuples = amazon_get_images(environment['region'], access_key, environment['secretKey'])
495 amazon_amis[access_key] = [image_tuple + (environment,) for image_tuple in image_tuples]
496 else:
497 raise RuntimeError('Got invalid environment kind: "%s"' % iamge_type)
498
499
500 # Delete all images older than X which are not currently in a version / module
501 got_any_google = False
502 for project, imgs in google_images.iteritems():
503 mmimgs = [img for img in imgs if img[0].startswith('micromanage-') and not img[0] in used_images[project]]
504 for img in mmimgs:
505 if (now - img[1]).days > 7:
506 if not got_any_google:
507 got_any_google = True
508 print 'Execute the following commands to clean up Google images:'
509 print 'gcloud --project=%s compute images delete -q %s # %s days old' % (project, img[0], (now - img[1]).days)
510 if not got_any_google:
511 print 'There were no Google images to clean up.'
512
513 got_any_amazon = False
514 for access_key, imgs in google_images.iteritems():
515 mmimgs = [img for img in imgs if img[0].startswith('micromanage-') and not img[0] in used_images[access_key]]
516 for img in mmimgs:
517 img_name, img_creation_timestamp, env = img
518 days_old = (now - img_creation_timestamp).days
519 if days_old > 7:
520 if not got_any_amazon:
521 got_any_amazon = True
522 print 'Execute the following commands to clean up Amazon AMIs:'
523 region = img[2]['region']
524 secret_key = img[2]['secretKey']
525 print 'ec2-deregister --region %s --aws-access-key %s --aws-secret-key %s %s # %s days old' % (region, access_key, secret_key, img_name, days_old)
526 #TODO(dcunnin): need to delete by snapshot-id, not by ami id
527 print 'ec2-delete-snapshot --region %s --aws-access-key %s --aws-secret-key %s %s # %s days old' % (region, access_key, secret_key, img_name, days_old)
528 if not got_any_amazon:
529 print 'There were no Amazon AMIs to clean up.'
530
531
532 actions = {
533 'blueprint': action_blueprint,
534 'generate-to-editor': action_generate_to_editor,
535 'apply': action_apply,
536 'destroy': action_destroy,
537 'diff': action_diff,
538 'graph': action_graph,
539 'init': action_init,
540 'list-services': action_list_services,
541 'show': action_show,
542 'output': action_output,
543 'image-gc': action_image_gc,
544 }
545
546
547 def print_usage(channel):
548 channel.write("Usage: python micromanage.py <config.jsonnet> <action> <args>\n")
549 channel.write("Available actions: %s\n" % ', '.join(actions.keys()))
550
551 remaining_args = []
552 i = 1
553
554 def next_arg(i):
555 i += 1
556 if i >= len(sys.argv):
557 sys.stderr.write('Expected another commandline argument.\n')
558 sys.exit(1)
559 return i, sys.argv[i]
560
561 while i < len(sys.argv):
562 arg = sys.argv[i]
563 if arg == '-E' or arg == '--env':
564 i, env_var = next_arg(i)
565 env_val = os.environ.get(env_var)
566 if not env_val:
567 sys.stderr.write('-E referred to non-existent environment variable "%s".\n' % env_var)
568 sys.exit(1)
569 ext_vars[env_var] = env_val
570 elif arg == '-V' or arg == '--var':
571 i, data = next_arg(i)
572 splits = string.split(data, '=', 1)
573 if len(splits) < 2:
574 sys.stderr.write('-V must be followed by key=val, got "%s".\n' % data)
575 sys.exit(1)
576 ext_vars[splits[0]] = splits[1]
577 elif arg == '-J' or arg == '--jpath':
578 i, val = next_arg(i)
579 search_paths = [val] + search_paths
580 elif arg == '-d' or arg == '--debug':
581 debug = True
582 elif arg == '-f' or arg == '--force':
583 force = True
584 else:
585 remaining_args.append(arg)
586 i += 1
587
588 if len(remaining_args) < 2:
589 sys.stderr.write('Not enough commandline arguments.\n')
590 print_usage(sys.stderr)
591 sys.exit(1)
592
593 config_file = remaining_args[0]
594 action = remaining_args[1]
595 args = remaining_args[2:]
596
597 if action not in actions:
598 sys.stderr.write('Invalid action: "%s"' % action)
599 print_usage(sys.stderr)
600 sys.exit(1)
601
602 config = config_load(config_file, ext_vars)
603 try:
604 actions[action](config_file, config, args)
605 except SubprocessException as e:
606 sys.stderr.write('%s\n' % e)
607 sys.exit(1)