Merge "Fix Merge::Map for scatter-gather in Configs."
[apex-tripleo-heat-templates.git] / tripleo_heat_merge / merge.py
1 import os
2 import sys
3 import yaml
4 import argparse
5
6
7 def apply_maps(template):
8     """Apply Merge::Map within template.
9
10     Any dict {'Merge::Map': {'Foo': 'Bar', 'Baz': 'Quux'}}
11     will resolve to ['Bar', 'Quux'] - that is a dict with key
12     'Merge::Map' is replaced entirely by that dict['Merge::Map'].values().
13     """
14     if isinstance(template, dict):
15         if 'Merge::Map' in template:
16             return sorted(
17                 apply_maps(value) for value in template['Merge::Map'].values()
18                 )
19         else:
20             return dict((key, apply_maps(value))
21                 for key, value in template.items())
22     elif isinstance(template, list):
23         return [apply_maps(item) for item in template]
24     else:
25         return template
26
27
28 def apply_scaling(template, scaling, in_copies=None):
29     """Apply a set of scaling operations to template.
30
31     This is a single pass recursive function: for each call we process one
32     dict or list and recurse to handle children containers.
33
34     Values are handled via scale_value.
35
36     Keys in dicts are copied per the scaling rule.
37     Values are either replaced or copied depending on whether the given
38     scaling rule is in in_copies.
39
40     in_copies is reset to None when a dict {'Merge::Map': someobject} is
41     encountered.
42     """
43     in_copies = dict(in_copies or {})
44     # Shouldn't be needed but to avoid unexpected side effects/bugs we short
45     # circuit no-ops.
46     if not scaling:
47         return template
48     if isinstance(template, dict):
49         if 'Merge::Map' in template:
50             in_copies = None
51         new_template = {}
52         for key, value in template.items():
53             for prefix, copy_num, new_key in scale_value(
54                 key, scaling, in_copies):
55                 if prefix:
56                     # e.g. Compute0, 1, Compute1Foo
57                     in_copies[prefix] = prefix[:-1] + str(copy_num)
58                 if isinstance(value, (dict, list)):
59                     new_value = apply_scaling(value, scaling, in_copies)
60                     new_template[new_key] = new_value
61                 else:
62                     new_values = list(scale_value(value, scaling, in_copies))
63                     # We have nowhere to multiply a non-container value of a
64                     # dict, so it may be copied or unchanged but not scaled.
65                     assert len(new_values) == 1
66                     new_template[new_key] = new_values[0][2]
67                 if prefix:
68                     del in_copies[prefix]
69         return new_template
70     elif isinstance(template, list):
71         new_template = []
72         for value in template:
73             if isinstance(value, (dict, list)):
74                 new_template.append(apply_scaling(value, scaling, in_copies))
75             else:
76                 for _, _, new_value in scale_value(value, scaling, in_copies):
77                     new_template.append(new_value)
78         return new_template
79     else:
80         raise Exception("apply_scaling called with non-container %r" % template)
81
82
83 def scale_value(value, scaling, in_copies):
84     """Scale out a value.
85
86     :param value: The value to scale (not a container).
87     :param scaling: The scaling map to use.
88     :param in_copies: What containers we're currently copying.
89     :return: An iterator of the new values for the value as tuples:
90         (prefix, copy_num, value). E.g. Compute0, 1, Compute1Foo
91         prefix and copy_num are only set when:
92          - a prefix in scaling matches value
93          - and that prefix is not in in_copies
94     """
95     if isinstance(value, (str, unicode)):
96         for prefix, copies in scaling.items():
97             if not value.startswith(prefix):
98                 continue
99             suffix = value[len(prefix):]
100             if prefix in in_copies:
101                 # Adjust to the copy number we're on
102                 yield None, None, in_copies[prefix] + suffix
103                 return
104             else:
105                 for n in range(copies):
106                     yield prefix, n, prefix[:-1] + str(n) + suffix
107                 return
108         yield None, None, value
109     else:
110         yield None, None, value
111
112
113 def parse_scaling(scaling_args):
114     """Translate a list of scaling requests to a dict prefix:count."""
115     scaling_args = scaling_args or []
116     result = {}
117     for item in scaling_args:
118         key, value = item.split('=')
119         value = int(value)
120         result[key + '0'] = value
121     return result
122
123
124 def _translate_role(role, master_role, slave_roles):
125     if not master_role:
126         return role
127     if role == master_role:
128         return role
129     if role not in slave_roles:
130         return role
131     return master_role
132
133 def translate_role(role, master_role, slave_roles):
134     r = _translate_role(role, master_role, slave_roles)
135     if not isinstance(r, basestring):
136         raise Exception('%s -> %r' % (role, r))
137     return r
138
139 def resolve_params(item, param, value):
140     if item == {'Ref': param}:
141         return value
142     if isinstance(item, dict):
143         copy_item = dict(item)
144         for k, v in iter(copy_item.items()):
145             item[k] = resolve_params(v, param, value)
146     elif isinstance(item, list):
147         copy_item = list(item)
148         new_item = []
149         for v in copy_item:
150             new_item.append(resolve_params(v, param, value))
151         item = new_item
152     return item
153
154 MERGABLE_TYPES = {'OS::Nova::Server':
155                   {'image': 'image'},
156                   'AWS::EC2::Instance':
157                   {'image': 'ImageId'},
158                   'AWS::AutoScaling::LaunchConfiguration':
159                   {},
160                  }
161 INCLUDED_TEMPLATE_DIR = os.getcwd()
162
163
164 def resolve_includes(template, params=None):
165     new_template = {}
166     if params is None:
167         params = {}
168     for key, value in iter(template.items()):
169         if key == '__include__':
170             new_params = dict(params) # do not propagate up the stack
171             if not isinstance(value, dict):
172                 raise ValueError('__include__ must be a mapping')
173             if 'path' not in value:
174                 raise ValueError('__include__ must have path')
175             if 'params' in value:
176                 if not isinstance(value['params'], dict):
177                     raise ValueError('__include__ params must be a mapping')
178                 new_params.update(value['params'])
179             with open(value['path']) as include_file:
180                 sub_template = yaml.safe_load(include_file.read())
181                 if 'subkey' in value:
182                     if ((not isinstance(value['subkey'], int)
183                          and not isinstance(sub_template, dict))):
184                         raise RuntimeError('subkey requires mapping root or'
185                                            ' integer for list root')
186                     sub_template = sub_template[value['subkey']]
187                 for k, v in iter(new_params.items()):
188                     sub_template = resolve_params(sub_template, k, v)
189                 new_template.update(resolve_includes(sub_template))
190         else:
191             if isinstance(value, dict):
192                 new_template[key] = resolve_includes(value)
193             else:
194                 new_template[key] = value
195     return new_template
196
197 def main(argv=None):
198     if argv is None:
199         argv = sys.argv[1:]
200     parser = argparse.ArgumentParser()
201     parser.add_argument('templates', nargs='+')
202     parser.add_argument('--master-role', nargs='?',
203                         help='Translate slave_roles to this')
204     parser.add_argument('--slave-roles', nargs='*',
205                         help='Translate all of these to master_role')
206     parser.add_argument('--included-template-dir', nargs='?',
207                         default=INCLUDED_TEMPLATE_DIR,
208                         help='Path for resolving included templates')
209     parser.add_argument('--output',
210                         help='File to write output to. - for stdout',
211                         default='-')
212     parser.add_argument('--scale', action="append",
213         help="Names to scale out. Pass Prefix=1 to cause a key Prefix0Foo to "
214         "be copied to Prefix1Foo in the output, and value Prefix0Bar to be"
215         "renamed to Prefix1Bar inside that copy, or copied to Prefix1Bar "
216         "outside of any copy.")
217     parser.add_argument(
218         '--change-image-params', action='store_true', default=False,
219         help="Change parameters in templates to match resource names. This was "
220              " the default at one time but it causes issues when parameter "
221              " names need to remain stable.")
222     args = parser.parse_args(argv)
223     templates = args.templates
224     scaling = parse_scaling(args.scale)
225     merged_template = merge(templates, args.master_role, args.slave_roles,
226                             args.included_template_dir, scaling=scaling,
227                             change_image_params=args.change_image_params)
228     if args.output == '-':
229         out_file = sys.stdout
230     else:
231         out_file = file(args.output, 'wt')
232     out_file.write(merged_template)
233
234
235 def merge(templates, master_role=None, slave_roles=None,
236           included_template_dir=INCLUDED_TEMPLATE_DIR,
237           scaling=None, change_image_params=None):
238     scaling = scaling or {}
239     errors = []
240     end_template={'HeatTemplateFormatVersion': '2012-12-12',
241                   'Description': []}
242     resource_changes=[]
243     for template_path in templates:
244         template = yaml.safe_load(open(template_path))
245         # Resolve __include__ tags
246         template = resolve_includes(template)
247         end_template['Description'].append(template.get('Description',
248                                                         template_path))
249         new_parameters = template.get('Parameters', {})
250         for p, pbody in sorted(new_parameters.items()):
251             if p in end_template.get('Parameters', {}):
252                 if pbody != end_template['Parameters'][p]:
253                     errors.append('Parameter %s from %s conflicts.' % (p,
254                                                                        template_path))
255                 continue
256             if 'Parameters' not in end_template:
257                 end_template['Parameters'] = {}
258             end_template['Parameters'][p] = pbody
259
260         new_outputs = template.get('Outputs', {})
261         for o, obody in sorted(new_outputs.items()):
262             if o in end_template.get('Outputs', {}):
263                 if pbody != end_template['Outputs'][p]:
264                     errors.append('Output %s from %s conflicts.' % (o,
265                                                                        template_path))
266                 continue
267             if 'Outputs' not in end_template:
268                 end_template['Outputs'] = {}
269             end_template['Outputs'][o] = obody
270
271         new_resources = template.get('Resources', {})
272         for r, rbody in sorted(new_resources.items()):
273             if rbody['Type'] in MERGABLE_TYPES:
274                 if change_image_params:
275                     if 'image' in MERGABLE_TYPES[rbody['Type']]:
276                         image_key = MERGABLE_TYPES[rbody['Type']]['image']
277                         # XXX Assuming ImageId is always a Ref
278                         ikey_val = end_template['Parameters'][rbody['Properties'][image_key]['Ref']]
279                         del end_template['Parameters'][rbody['Properties'][image_key]['Ref']]
280                 role = rbody.get('Metadata', {}).get('OpenStack::Role', r)
281                 role = translate_role(role, master_role, slave_roles)
282                 if role != r:
283                     resource_changes.append((r, role))
284                 if role in end_template.get('Resources', {}):
285                     new_metadata = rbody.get('Metadata', {})
286                     for m, mbody in iter(new_metadata.items()):
287                         if m in end_template['Resources'][role].get('Metadata', {}):
288                             if m == 'OpenStack::ImageBuilder::Elements':
289                                 end_template['Resources'][role]['Metadata'][m].extend(mbody)
290                                 continue
291                             if mbody != end_template['Resources'][role]['Metadata'][m]:
292                                 errors.append('Role %s metadata key %s conflicts.' %
293                                               (role, m))
294                             continue
295                         end_template['Resources'][role]['Metadata'][m] = mbody
296                     continue
297                 if 'Resources' not in end_template:
298                     end_template['Resources'] = {}
299                 end_template['Resources'][role] = rbody
300                 if change_image_params:
301                     if 'image' in MERGABLE_TYPES[rbody['Type']]:
302                         ikey = '%sImage' % (role)
303                         end_template['Resources'][role]['Properties'][image_key] = {'Ref': ikey}
304                         end_template['Parameters'][ikey] = ikey_val
305             elif rbody['Type'] == 'FileInclude':
306                 # we trust os.path.join to DTRT: if FileInclude path isn't
307                 # absolute, join to included_template_dir (./)
308                 with open(os.path.join(included_template_dir, rbody['Path'])) as rfile:
309                     include_content = yaml.safe_load(rfile.read())
310                     subkeys = rbody.get('SubKey','').split('.')
311                     while len(subkeys) and subkeys[0]:
312                         include_content = include_content[subkeys.pop(0)]
313                     for replace_param, replace_value in iter(rbody.get('Parameters',
314                                                                        {}).items()):
315                         include_content = resolve_params(include_content,
316                                                          replace_param,
317                                                          replace_value)
318                     end_template['Resources'][r] = include_content
319             else:
320                 if r in end_template.get('Resources', {}):
321                     if rbody != end_template['Resources'][r]:
322                         errors.append('Resource %s from %s conflicts' % (r,
323                                                                          template_path))
324                     continue
325                 if 'Resources' not in end_template:
326                     end_template['Resources'] = {}
327                 end_template['Resources'][r] = rbody
328
329     end_template = apply_scaling(end_template, scaling)
330     end_template = apply_maps(end_template)
331
332     def fix_ref(item, old, new):
333         if isinstance(item, dict):
334             copy_item = dict(item)
335             for k, v in sorted(copy_item.items()):
336                 if k == 'Ref' and v == old:
337                     item[k] = new
338                     continue
339                 if k == 'DependsOn' and v == old:
340                     item[k] = new
341                     continue
342                 if k == 'Fn::GetAtt' and isinstance(v, list) and v[0] == old:
343                     new_list = list(v)
344                     new_list[0] = new
345                     item[k] = new_list
346                     continue
347                 if k == 'AllowedResources' and isinstance(v, list) and old in v:
348                     while old in v:
349                         pos = v.index(old)
350                         v[pos] = new
351                     continue
352                 fix_ref(v, old, new)
353         elif isinstance(item, list):
354             copy_item = list(item)
355             for v in item:
356                 fix_ref(v, old, new)
357
358     for change in resource_changes:
359         fix_ref(end_template, change[0], change[1])
360
361     if errors:
362         for e in errors:
363             sys.stderr.write("ERROR: %s\n" % e)
364     end_template['Description'] = ','.join(end_template['Description'])
365     return yaml.safe_dump(end_template, default_flow_style=False)
366
367 if __name__ == "__main__":
368       main()