Merge "Add ComputeHCI role and related validations"
[apex-tripleo-heat-templates.git] / tools / yaml-validate.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 os
15 import sys
16 import traceback
17 import yaml
18
19
20 required_params = ['EndpointMap', 'ServiceNetMap', 'DefaultPasswords',
21                    'RoleName', 'RoleParameters', 'ServiceData']
22
23 # NOTE(bnemec): The duplication in this list is intentional.  For the
24 # transition to generated environments we have two copies of these files,
25 # so they need to be listed twice.  Once the deprecated version can be removed
26 # the duplicate entries can be as well.
27 envs_containing_endpoint_map = ['tls-endpoints-public-dns.yaml',
28                                 'tls-endpoints-public-ip.yaml',
29                                 'tls-everywhere-endpoints-dns.yaml',
30                                 'tls-endpoints-public-dns.yaml',
31                                 'tls-endpoints-public-ip.yaml',
32                                 'tls-everywhere-endpoints-dns.yaml']
33 ENDPOINT_MAP_FILE = 'endpoint_map.yaml'
34 REQUIRED_DOCKER_SECTIONS = ['service_name', 'docker_config', 'puppet_config',
35                             'config_settings', 'step_config']
36 OPTIONAL_DOCKER_SECTIONS = ['docker_puppet_tasks', 'upgrade_tasks',
37                             'service_config_settings', 'host_prep_tasks',
38                             'metadata_settings', 'kolla_config']
39 REQUIRED_DOCKER_PUPPET_CONFIG_SECTIONS = ['config_volume', 'step_config',
40                                           'config_image']
41 OPTIONAL_DOCKER_PUPPET_CONFIG_SECTIONS = [ 'puppet_tags', 'volumes' ]
42 # Mapping of parameter names to a list of the fields we should _not_ enforce
43 # consistency across files on.  This should only contain parameters whose
44 # definition we cannot change for backwards compatibility reasons.  New
45 # parameters to the templates should not be added to this list.
46 PARAMETER_DEFINITION_EXCLUSIONS = {'ManagementNetCidr': ['default'],
47                                    'ManagementAllocationPools': ['default'],
48                                    'ExternalNetCidr': ['default'],
49                                    'ExternalAllocationPools': ['default'],
50                                    'StorageNetCidr': ['default'],
51                                    'StorageAllocationPools': ['default'],
52                                    'StorageMgmtNetCidr': ['default'],
53                                    'StorageMgmtAllocationPools': ['default'],
54                                    }
55
56 PREFERRED_CAMEL_CASE = {
57     'ec2api': 'Ec2Api',
58     'haproxy': 'HAProxy',
59 }
60
61
62 def exit_usage():
63     print('Usage %s <yaml file or directory>' % sys.argv[0])
64     sys.exit(1)
65
66
67 def to_camel_case(string):
68     return PREFERRED_CAMEL_CASE.get(string, ''.join(s.capitalize() or '_' for
69                                                     s in string.split('_')))
70
71
72 def get_base_endpoint_map(filename):
73     try:
74         tpl = yaml.load(open(filename).read())
75         return tpl['parameters']['EndpointMap']['default']
76     except Exception:
77         print(traceback.format_exc())
78     return None
79
80
81 def get_endpoint_map_from_env(filename):
82     try:
83         tpl = yaml.load(open(filename).read())
84         return {
85             'file': filename,
86             'map': tpl['parameter_defaults']['EndpointMap']
87         }
88     except Exception:
89         print(traceback.format_exc())
90     return None
91
92
93 def validate_endpoint_map(base_map, env_map):
94     return sorted(base_map.keys()) == sorted(env_map.keys())
95
96
97 def validate_hci_compute_services_default(env_filename, env_tpl):
98     env_services_list = env_tpl['parameter_defaults']['ComputeServices']
99     env_services_list.remove('OS::TripleO::Services::CephOSD')
100     roles_filename = os.path.join(os.path.dirname(env_filename),
101                                   '../roles/Compute.yaml')
102     roles_tpl = yaml.load(open(roles_filename).read())
103     for role in roles_tpl:
104         if role['name'] == 'Compute':
105             roles_services_list = role['ServicesDefault']
106             if sorted(env_services_list) != sorted(roles_services_list):
107                 print('ERROR: ComputeServices in %s is different from '
108                       'ServicesDefault in roles/Compute.yaml' % env_filename)
109                 return 1
110     return 0
111
112
113 def validate_hci_computehci_role(hci_role_filename, hci_role_tpl):
114     compute_role_filename = os.path.join(os.path.dirname(hci_role_filename),
115                                          './Compute.yaml')
116     compute_role_tpl = yaml.load(open(compute_role_filename).read())
117     compute_role_services = compute_role_tpl[0]['ServicesDefault']
118     for role in hci_role_tpl:
119         if role['name'] == 'ComputeHCI':
120             hci_role_services = role['ServicesDefault']
121             hci_role_services.remove('OS::TripleO::Services::CephOSD')
122             if sorted(hci_role_services) != sorted(compute_role_services):
123                 print('ERROR: ServicesDefault in %s is different from'
124                       'ServicesDefault in roles/Compute.yaml' % hci_role_filename)
125                 return 1
126     return 0
127
128
129 def validate_mysql_connection(settings):
130     no_op = lambda *args: False
131     error_status = [0]
132
133     def mysql_protocol(items):
134         return items == ['EndpointMap', 'MysqlInternal', 'protocol']
135
136     def client_bind_address(item):
137         return 'read_default_file' in item and \
138                'read_default_group' in item
139
140     def validate_mysql_uri(key, items):
141         # Only consider a connection if it targets mysql
142         if key.endswith('connection') and \
143            search(items, mysql_protocol, no_op):
144             # Assume the "bind_address" option is one of
145             # the token that made up the uri
146             if not search(items, client_bind_address, no_op):
147                 error_status[0] = 1
148         return False
149
150     def search(item, check_item, check_key):
151         if check_item(item):
152             return True
153         elif isinstance(item, list):
154             for i in item:
155                 if search(i, check_item, check_key):
156                     return True
157         elif isinstance(item, dict):
158             for k in item.keys():
159                 if check_key(k, item[k]):
160                     return True
161                 elif search(item[k], check_item, check_key):
162                     return True
163         return False
164
165     search(settings, no_op, validate_mysql_uri)
166     return error_status[0]
167
168
169 def validate_docker_service(filename, tpl):
170     if 'outputs' in tpl and 'role_data' in tpl['outputs']:
171         if 'value' not in tpl['outputs']['role_data']:
172             print('ERROR: invalid role_data for filename: %s'
173                   % filename)
174             return 1
175         role_data = tpl['outputs']['role_data']['value']
176
177         for section_name in REQUIRED_DOCKER_SECTIONS:
178             if section_name not in role_data:
179                 print('ERROR: %s is required in role_data for %s.'
180                       % (section_name, filename))
181                 return 1
182
183         for section_name in role_data.keys():
184             if section_name in REQUIRED_DOCKER_SECTIONS:
185                 continue
186             else:
187                 if section_name in OPTIONAL_DOCKER_SECTIONS:
188                     continue
189                 else:
190                     print('ERROR: %s is extra in role_data for %s.'
191                           % (section_name, filename))
192                     return 1
193
194         if 'puppet_config' in role_data:
195             puppet_config = role_data['puppet_config']
196             for key in puppet_config:
197                 if key in REQUIRED_DOCKER_PUPPET_CONFIG_SECTIONS:
198                     continue
199                 else:
200                     if key in OPTIONAL_DOCKER_PUPPET_CONFIG_SECTIONS:
201                         continue
202                     else:
203                       print('ERROR: %s should not be in puppet_config section.'
204                             % key)
205                       return 1
206             for key in REQUIRED_DOCKER_PUPPET_CONFIG_SECTIONS:
207               if key not in puppet_config:
208                   print('ERROR: %s is required in puppet_config for %s.'
209                         % (key, filename))
210                   return 1
211
212             config_volume = puppet_config.get('config_volume')
213             expected_config_image_parameter = "Docker%sConfigImage" % to_camel_case(config_volume)
214             if config_volume and not expected_config_image_parameter in tpl.get('parameters', []):
215                 print('ERROR: Missing %s heat parameter for %s config_volume.'
216                       % (expected_config_image_parameter, config_volume))
217                 return 1
218
219         if 'docker_config' in role_data:
220             docker_config = role_data['docker_config']
221             for _, step in docker_config.items():
222                 for _, container in step.items():
223                     if not isinstance(container, dict):
224                         # NOTE(mandre) this skips everything that is not a dict
225                         # so we may ignore some containers definitions if they
226                         # are in a map_merge for example
227                         continue
228                     command = container.get('command', '')
229                     if isinstance(command, list):
230                         command = ' '.join(map(str, command))
231                     if 'bootstrap_host_exec' in command \
232                             and container.get('user') != 'root':
233                       print('ERROR: bootstrap_host_exec needs to run as the root user.')
234                       return 1
235
236     if 'parameters' in tpl:
237         for param in required_params:
238             if param not in tpl['parameters']:
239                 print('ERROR: parameter %s is required for %s.'
240                       % (param, filename))
241                 return 1
242     return 0
243
244
245 def validate_service(filename, tpl):
246     if 'outputs' in tpl and 'role_data' in tpl['outputs']:
247         if 'value' not in tpl['outputs']['role_data']:
248             print('ERROR: invalid role_data for filename: %s'
249                   % filename)
250             return 1
251         role_data = tpl['outputs']['role_data']['value']
252         if 'service_name' not in role_data:
253             print('ERROR: service_name is required in role_data for %s.'
254                   % filename)
255             return 1
256         # service_name must match the filename, but with an underscore
257         if (role_data['service_name'] !=
258                 os.path.basename(filename).split('.')[0].replace("-", "_")):
259             print('ERROR: service_name should match file name for service: %s.'
260                   % filename)
261             return 1
262         # if service connects to mysql, the uri should use option
263         # bind_address to avoid issues with VIP failover
264         if 'config_settings' in role_data and \
265            validate_mysql_connection(role_data['config_settings']):
266             print('ERROR: mysql connection uri should use option bind_address')
267             return 1
268     if 'parameters' in tpl:
269         for param in required_params:
270             if param not in tpl['parameters']:
271                 print('ERROR: parameter %s is required for %s.'
272                       % (param, filename))
273                 return 1
274     return 0
275
276
277 def validate(filename, param_map):
278     """Validate a Heat template
279
280     :param filename: The path to the file to validate
281     :param param_map: A dict which will be populated with the details of the
282                       parameters in the template.  The dict will have the
283                       following structure:
284
285                           {'ParameterName': [
286                                {'filename': ./file1.yaml,
287                                 'data': {'description': '',
288                                          'type': string,
289                                          'default': '',
290                                          ...}
291                                 },
292                                {'filename': ./file2.yaml,
293                                 'data': {'description': '',
294                                          'type': string,
295                                          'default': '',
296                                          ...}
297                                 },
298                                 ...
299                            ]}
300     """
301     print('Validating %s' % filename)
302     retval = 0
303     try:
304         tpl = yaml.load(open(filename).read())
305
306         # The template alias version should be used instead a date, this validation
307         # will be applied to all templates not just for those in the services folder.
308         if 'heat_template_version' in tpl and not str(tpl['heat_template_version']).isalpha():
309             print('ERROR: heat_template_version needs to be the release alias not a date: %s'
310                   % filename)
311             return 1
312
313         # qdr aliases rabbitmq service to provide alternative messaging backend
314         if (filename.startswith('./puppet/services/') and
315                 filename not in ['./puppet/services/qdr.yaml']):
316             retval = validate_service(filename, tpl)
317
318         if filename.startswith('./docker/services/'):
319             retval = validate_docker_service(filename, tpl)
320
321         if filename.endswith('hyperconverged-ceph.yaml'):
322             retval = validate_hci_compute_services_default(filename, tpl)
323
324         if filename.startswith('./roles/ComputeHCI.yaml'):
325             retval = validate_hci_computehci_role(filename, tpl)
326
327     except Exception:
328         print(traceback.format_exc())
329         return 1
330     # yaml is OK, now walk the parameters and output a warning for unused ones
331     if 'heat_template_version' in tpl:
332         for p, data in tpl.get('parameters', {}).items():
333             definition = {'data': data, 'filename': filename}
334             param_map.setdefault(p, []).append(definition)
335             if p in required_params:
336                 continue
337             str_p = '\'%s\'' % p
338             in_resources = str_p in str(tpl.get('resources', {}))
339             in_outputs = str_p in str(tpl.get('outputs', {}))
340             if not in_resources and not in_outputs:
341                 print('Warning: parameter %s in template %s '
342                       'appears to be unused' % (p, filename))
343
344     return retval
345
346 if len(sys.argv) < 2:
347     exit_usage()
348
349 path_args = sys.argv[1:]
350 exit_val = 0
351 failed_files = []
352 base_endpoint_map = None
353 env_endpoint_maps = list()
354 param_map = {}
355
356 for base_path in path_args:
357     if os.path.isdir(base_path):
358         for subdir, dirs, files in os.walk(base_path):
359             if '.tox' in dirs:
360                 dirs.remove('.tox')
361             for f in files:
362                 if f.endswith('.yaml') and not f.endswith('.j2.yaml'):
363                     file_path = os.path.join(subdir, f)
364                     failed = validate(file_path, param_map)
365                     if failed:
366                         failed_files.append(file_path)
367                     exit_val |= failed
368                     if f == ENDPOINT_MAP_FILE:
369                         base_endpoint_map = get_base_endpoint_map(file_path)
370                     if f in envs_containing_endpoint_map:
371                         env_endpoint_map = get_endpoint_map_from_env(file_path)
372                         if env_endpoint_map:
373                             env_endpoint_maps.append(env_endpoint_map)
374     elif os.path.isfile(base_path) and base_path.endswith('.yaml'):
375         failed = validate(base_path, param_map)
376         if failed:
377             failed_files.append(base_path)
378         exit_val |= failed
379     else:
380         print('Unexpected argument %s' % base_path)
381         exit_usage()
382
383 if base_endpoint_map and \
384         len(env_endpoint_maps) == len(envs_containing_endpoint_map):
385     for env_endpoint_map in env_endpoint_maps:
386         matches = validate_endpoint_map(base_endpoint_map,
387                                         env_endpoint_map['map'])
388         if not matches:
389             print("ERROR: %s needs to be updated to match changes in base "
390                   "endpoint map" % env_endpoint_map['file'])
391             failed_files.append(env_endpoint_map['file'])
392             exit_val |= 1
393         else:
394             print("%s matches base endpoint map" % env_endpoint_map['file'])
395 else:
396     print("ERROR: Did not find expected number of environments containing the "
397           "EndpointMap parameter.  If you meant to add or remove one of these "
398           "environments then you also need to update this tool.")
399     if not base_endpoint_map:
400         failed_files.append(ENDPOINT_MAP_FILE)
401     if len(env_endpoint_maps) != len(envs_containing_endpoint_map):
402         matched_files = set(os.path.basename(matched_env_file['file'])
403                             for matched_env_file in env_endpoint_maps)
404         failed_files.extend(set(envs_containing_endpoint_map) - matched_files)
405     exit_val |= 1
406
407 # Validate that duplicate parameters defined in multiple files all have the
408 # same definition.
409 mismatch_count = 0
410 for p, defs in param_map.items():
411     # Nothing to validate if the parameter is only defined once
412     if len(defs) == 1:
413         continue
414     check_data = [d['data'] for d in defs]
415     # Override excluded fields so they don't affect the result
416     exclusions = PARAMETER_DEFINITION_EXCLUSIONS.get(p, [])
417     ex_dict = {}
418     for field in exclusions:
419         ex_dict[field] = 'IGNORED'
420     for d in check_data:
421         d.update(ex_dict)
422     # If all items in the list are not == the first, then the check fails
423     if check_data.count(check_data[0]) != len(check_data):
424         mismatch_count += 1
425         # TODO(bnemec): Make this a hard failure once all the templates have
426         #               been fixed.
427         #exit_val |= 1
428         #failed_files.extend([d['filename'] for d in defs])
429         print('Mismatched parameter definitions found for "%s"' % p)
430         print('Definitions found:')
431         for d in defs:
432             print('  %s:\n    %s' % (d['filename'], d['data']))
433 print('Mismatched parameter definitions: %d' % mismatch_count)
434
435 if failed_files:
436     print('Validation failed on:')
437     for f in failed_files:
438         print(f)
439 else:
440     print('Validation successful!')
441 sys.exit(exit_val)