arm-pod10: Increase MaaS deploy timeout
[pharos.git] / config / utils / generate_config.py
1 #!/usr/bin/python
2 ##############################################################################
3 # Copyright (c) 2018 OPNFV and others.
4 #
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
9 ##############################################################################
10 """Generate configuration from PDF/IDF and jinja2 installer template"""
11
12 import argparse
13 import logging
14 from os.path import abspath, exists, isfile, split
15 from subprocess import CalledProcessError, check_output
16 import gen_config_lib
17 import yaml
18 from jinja2 import Environment, FileSystemLoader
19
20
21 LOADER = yaml.CSafeLoader if yaml.__with_libyaml__ else yaml.SafeLoader
22
23 PARSER = argparse.ArgumentParser()
24 PARSER.add_argument("--yaml", "-y", type=str, required=True)
25 PARSER.add_argument("--jinja2", "-j", type=str, required=True, action='append')
26 PARSER.add_argument("--includesdir", "-i", action='append', default=['/'])
27 PARSER.add_argument("--batch", "-b", action='store_true')
28 PARSER.add_argument("--verbose", "-v", action='count')
29 ARGS = PARSER.parse_args()
30
31 ARGS.jinja2 = [abspath(x) for x in ARGS.jinja2]
32
33 logging.basicConfig()
34 LOGGER = logging.getLogger('generate_config')
35 if ARGS.verbose:
36     LOGGER.setLevel(logging.INFO)
37
38 ENV = Environment(
39     loader=FileSystemLoader(ARGS.includesdir),
40     extensions=['jinja2.ext.do']
41 )
42 gen_config_lib.load_custom_filters(ENV)
43
44 # Run `eyaml decrypt` on the whole file, but only if PDF data is encrypted
45 # Note: eyaml return code is 0 even if keys are not available
46 try:
47     if isfile(ARGS.yaml) and 'ENC[PKCS7' in open(ARGS.yaml).read():
48         DICT = yaml.load(check_output(['eyaml', 'decrypt',
49                                        '-f', ARGS.yaml]), Loader=LOADER)
50 except CalledProcessError as ex:
51     LOGGER.error('eyaml decryption failed! Fallback to raw data.')
52 except OSError as ex:
53     LOGGER.warn('eyaml not found, skipping decryption. Fallback to raw data.')
54 try:
55     DICT['details']
56 except (NameError, TypeError) as ex:
57     with open(ARGS.yaml) as _:
58         DICT = yaml.load(_.read().replace('/', '__slash__'), Loader=LOADER)
59
60 # If an installer descriptor file (IDF) exists, include it (temporary)
61 IDF_PATH = '/idf-'.join(split(ARGS.yaml))
62 if exists(IDF_PATH):
63     with open(IDF_PATH) as _:
64         IDF = yaml.load(_, Loader=LOADER)
65         DICT['idf'] = IDF['idf']
66
67 # Print dictionary generated from yaml (uncomment for debug)
68 # print(DICT)
69
70 for _j2 in ARGS.jinja2:
71     TEMPLATE = ENV.get_template(_j2)
72     OUTPUT = TEMPLATE.render(conf=DICT).replace('__slash__', '/')
73     # Render template and write generated conf to file or stdout
74     if ARGS.batch:
75         if _j2.endswith('.j2'):
76             destination_file = _j2[:-3]  # Trim '.j2' suffix
77             LOGGER.info('Parsing {}'.format(_j2))
78             with open(destination_file, 'w') as _:
79                 _.write(OUTPUT)
80         else:
81             LOGGER.warn('Skipping {}, name does not end in ".j2"'.format(_j2))
82     else:
83         # pylint: disable=superfluous-parens
84         print(OUTPUT)