Merge "Validate that endpoint_map.yaml is up to date in the gate"
[apex-tripleo-heat-templates.git] / tools / process-templates.py
1 #!/usr/bin/env python
2 #    Licensed under the Apache License, Version 2.0 (the "License"); you may
3 #    not use this file except in compliance with the License. You may obtain
4 #    a copy of the License at
5 #
6 #         http://www.apache.org/licenses/LICENSE-2.0
7 #
8 #    Unless required by applicable law or agreed to in writing, software
9 #    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
10 #    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
11 #    License for the specific language governing permissions and limitations
12 #    under the License.
13
14 import argparse
15 import jinja2
16 import os
17 import shutil
18 import six
19 import sys
20 import yaml
21
22 __tht_root_dir = os.path.dirname(os.path.dirname(__file__))
23
24
25 def parse_opts(argv):
26     parser = argparse.ArgumentParser(
27         description='Configure host network interfaces using a JSON'
28         ' config file format.')
29     parser.add_argument('-p', '--base_path', metavar='BASE_PATH',
30                         help="""base path of templates to process.""",
31                         default='.')
32     parser.add_argument('-r', '--roles-data', metavar='ROLES_DATA',
33                         help="""relative path to the roles_data.yaml file.""",
34                         default='roles_data.yaml')
35     parser.add_argument('--safe',
36                         action='store_true',
37                         help="""Enable safe mode (do not overwrite files).""",
38                         default=False)
39     parser.add_argument('-o', '--output-dir', metavar='OUTPUT_DIR',
40                         help="""Output dir for all the templates""",
41                         default='')
42     opts = parser.parse_args(argv[1:])
43
44     return opts
45
46
47 def _j2_render_to_file(j2_template, j2_data, outfile_name=None,
48                        overwrite=True):
49     yaml_f = outfile_name or j2_template.replace('.j2.yaml', '.yaml')
50     print('rendering j2 template to file: %s' % outfile_name)
51
52     if not overwrite and os.path.exists(outfile_name):
53         print('ERROR: path already exists for file: %s' % outfile_name)
54         sys.exit(1)
55
56     # Search for templates relative to the current template path first
57     template_base = os.path.dirname(yaml_f)
58     j2_loader = jinja2.loaders.FileSystemLoader([template_base, __tht_root_dir])
59
60     try:
61         # Render the j2 template
62         template = jinja2.Environment(loader=j2_loader).from_string(
63             j2_template)
64         r_template = template.render(**j2_data)
65     except jinja2.exceptions.TemplateError as ex:
66         error_msg = ("Error rendering template %s : %s"
67                      % (yaml_f, six.text_type(ex)))
68         print(error_msg)
69         raise Exception(error_msg)
70     with open(outfile_name, 'w') as out_f:
71         out_f.write(r_template)
72
73
74 def process_templates(template_path, role_data_path, output_dir, overwrite):
75
76     with open(role_data_path) as role_data_file:
77         role_data = yaml.safe_load(role_data_file)
78
79     j2_excludes_path = os.path.join(template_path, 'j2_excludes.yaml')
80     with open(j2_excludes_path) as role_data_file:
81         j2_excludes = yaml.safe_load(role_data_file)
82
83     if output_dir and not os.path.isdir(output_dir):
84         if os.path.exists(output_dir):
85             raise RuntimeError('Output dir %s is not a directory' % output_dir)
86         os.mkdir(output_dir)
87
88     role_names = [r.get('name') for r in role_data]
89     r_map = {}
90     for r in role_data:
91         r_map[r.get('name')] = r
92     excl_templates = ['%s/%s' % (template_path, e)
93                       for e in j2_excludes.get('name')]
94
95     if os.path.isdir(template_path):
96         for subdir, dirs, files in os.walk(template_path):
97
98             # NOTE(flaper87): Ignore hidden dirs as we don't
99             # generate templates for those.
100             # Note the slice assigment for `dirs` is necessary
101             # because we need to modify the *elements* in the
102             # dirs list rather than the reference to the list.
103             # This way we'll make sure os.walk will iterate over
104             # the shrunk list. os.walk doesn't have an API for
105             # filtering dirs at this point.
106             dirs[:] = [d for d in dirs if not d[0] == '.']
107             files = [f for f in files if not f[0] == '.']
108
109             # NOTE(flaper87): We could have used shutil.copytree
110             # but it requires the dst dir to not be present. This
111             # approach is safer as it doesn't require us to delete
112             # the output_dir in advance and it allows for running
113             # the command multiple times with the same output_dir.
114             out_dir = subdir
115             if output_dir:
116                 out_dir = os.path.join(output_dir, subdir)
117                 if not os.path.exists(out_dir):
118                     os.mkdir(out_dir)
119
120             for f in files:
121                 file_path = os.path.join(subdir, f)
122                 # We do two templating passes here:
123                 # 1. *.role.j2.yaml - we template just the role name
124                 #    and create multiple files (one per role)
125                 # 2. *.j2.yaml - we template with all roles_data,
126                 #    and create one file common to all roles
127                 if f.endswith('.role.j2.yaml'):
128                     print("jinja2 rendering role template %s" % f)
129                     with open(file_path) as j2_template:
130                         template_data = j2_template.read()
131                         print("jinja2 rendering roles %s" % ","
132                               .join(role_names))
133                         for role in role_names:
134                             j2_data = {'role': role}
135                             # (dprince) For the undercloud installer we don't
136                             # want to have heat check nova/glance API's
137                             if r_map[role].get('disable_constraints', False):
138                                 j2_data['disable_constraints'] = True
139                             out_f = "-".join(
140                                 [role.lower(),
141                                  os.path.basename(f).replace('.role.j2.yaml',
142                                                              '.yaml')])
143                             out_f_path = os.path.join(out_dir, out_f)
144                             if not (out_f_path in excl_templates):
145                                 _j2_render_to_file(template_data, j2_data,
146                                                    out_f_path, overwrite)
147                             else:
148                                 print('skipping rendering of %s' % out_f_path)
149                 elif f.endswith('.j2.yaml'):
150                     print("jinja2 rendering normal template %s" % f)
151                     with open(file_path) as j2_template:
152                         template_data = j2_template.read()
153                         j2_data = {'roles': role_data}
154                         out_f = os.path.basename(f).replace('.j2.yaml', '.yaml')
155                         out_f_path = os.path.join(out_dir, out_f)
156                         _j2_render_to_file(template_data, j2_data, out_f_path,
157                                            overwrite)
158                 elif output_dir:
159                     shutil.copy(os.path.join(subdir, f), out_dir)
160
161     else:
162         print('Unexpected argument %s' % template_path)
163
164 opts = parse_opts(sys.argv)
165
166 role_data_path = os.path.join(opts.base_path, opts.roles_data)
167
168 process_templates(opts.base_path, role_data_path, opts.output_dir, (not opts.safe))