f7a45d7baab6edd449c1ac8ad9c9510018a9c198
[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 OPTIONAL_SECTIONS = ['workflow_tasks']
35 REQUIRED_DOCKER_SECTIONS = ['service_name', 'docker_config', 'puppet_config',
36                             'config_settings', 'step_config']
37 OPTIONAL_DOCKER_SECTIONS = ['docker_puppet_tasks', 'upgrade_tasks',
38                             'post_upgrade_tasks', 'service_config_settings',
39                             'host_prep_tasks', 'metadata_settings',
40                             'kolla_config']
41 REQUIRED_DOCKER_PUPPET_CONFIG_SECTIONS = ['config_volume', 'step_config',
42                                           'config_image']
43 OPTIONAL_DOCKER_PUPPET_CONFIG_SECTIONS = [ 'puppet_tags', 'volumes' ]
44 # Mapping of parameter names to a list of the fields we should _not_ enforce
45 # consistency across files on.  This should only contain parameters whose
46 # definition we cannot change for backwards compatibility reasons.  New
47 # parameters to the templates should not be added to this list.
48 PARAMETER_DEFINITION_EXCLUSIONS = {'ManagementNetCidr': ['default'],
49                                    'ManagementAllocationPools': ['default'],
50                                    'ExternalNetCidr': ['default'],
51                                    'ExternalAllocationPools': ['default'],
52                                    'StorageNetCidr': ['default'],
53                                    'StorageAllocationPools': ['default'],
54                                    'StorageMgmtNetCidr': ['default'],
55                                    'StorageMgmtAllocationPools': ['default'],
56                                    'TenantNetCidr': ['default'],
57                                    'TenantAllocationPools': ['default'],
58                                    'InternalApiNetCidr': ['default'],
59                                    'InternalApiAllocationPools': ['default'],
60                                    'UpdateIdentifier': ['description'],
61                                    'key_name': ['default'],
62                                    # There's one template that defines this
63                                    # differently, and I'm not sure if we can
64                                    # safely change it.
65                                    'EC2MetadataIp': ['default'],
66                                    # Same as EC2MetadataIp
67                                    'ControlPlaneDefaultRoute': ['default'],
68                                    # TODO(bnemec): Address these existing
69                                    # inconsistencies.
70                                    'ServiceNetMap': ['description', 'default'],
71                                    'network': ['default'],
72                                    'ControlPlaneIP': ['default',
73                                                       'description'],
74                                    'ControlPlaneIp': ['default',
75                                                       'description'],
76                                    'NeutronBigswitchLLDPEnabled': ['default'],
77                                    'NeutronWorkers': ['description'],
78                                    'ServerMetadata': ['description'],
79                                    'server': ['description'],
80                                    'servers': ['description'],
81                                    'ExtraConfig': ['description'],
82                                    'DefaultPasswords': ['description',
83                                                         'default'],
84                                    'BondInterfaceOvsOptions': ['description',
85                                                                'default',
86                                                                'constraints'],
87                                    'KeyName': ['constraints'],
88                                    'OVNSouthboundServerPort': ['description'],
89                                    'ExternalInterfaceDefaultRoute':
90                                        ['description', 'default'],
91                                    'ManagementInterfaceDefaultRoute':
92                                        ['description', 'default'],
93                                    'IPPool': ['description'],
94                                    'SSLCertificate': ['description',
95                                                       'default',
96                                                       'hidden'],
97                                    'HostCpusList': ['default', 'constraints'],
98                                    'NodeIndex': ['description'],
99                                    'name': ['description', 'default'],
100                                    'image': ['description', 'default'],
101                                    'NeutronBigswitchAgentEnabled': ['default'],
102                                    'EndpointMap': ['description', 'default'],
103                                    'DockerManilaConfigImage': ['description',
104                                                                'default'],
105                                    'replacement_policy': ['default'],
106                                    'CloudDomain': ['description', 'default'],
107                                    'EnableLoadBalancer': ['description'],
108                                    'ControllerExtraConfig': ['description'],
109                                    'NovaComputeExtraConfig': ['description'],
110                                    'controllerExtraConfig': ['description'],
111                                    'DockerSwiftConfigImage': ['default']
112                                    }
113
114 PREFERRED_CAMEL_CASE = {
115     'ec2api': 'Ec2Api',
116     'haproxy': 'HAProxy',
117 }
118
119
120 def exit_usage():
121     print('Usage %s <yaml file or directory>' % sys.argv[0])
122     sys.exit(1)
123
124
125 def to_camel_case(string):
126     return PREFERRED_CAMEL_CASE.get(string, ''.join(s.capitalize() or '_' for
127                                                     s in string.split('_')))
128
129
130 def get_base_endpoint_map(filename):
131     try:
132         tpl = yaml.load(open(filename).read())
133         return tpl['parameters']['EndpointMap']['default']
134     except Exception:
135         print(traceback.format_exc())
136     return None
137
138
139 def get_endpoint_map_from_env(filename):
140     try:
141         tpl = yaml.load(open(filename).read())
142         return {
143             'file': filename,
144             'map': tpl['parameter_defaults']['EndpointMap']
145         }
146     except Exception:
147         print(traceback.format_exc())
148     return None
149
150
151 def validate_endpoint_map(base_map, env_map):
152     return sorted(base_map.keys()) == sorted(env_map.keys())
153
154
155 def validate_hci_compute_services_default(env_filename, env_tpl):
156     env_services_list = env_tpl['parameter_defaults']['ComputeServices']
157     env_services_list.remove('OS::TripleO::Services::CephOSD')
158     roles_filename = os.path.join(os.path.dirname(env_filename),
159                                   '../roles/Compute.yaml')
160     roles_tpl = yaml.load(open(roles_filename).read())
161     for role in roles_tpl:
162         if role['name'] == 'Compute':
163             roles_services_list = role['ServicesDefault']
164             if sorted(env_services_list) != sorted(roles_services_list):
165                 print('ERROR: ComputeServices in %s is different from '
166                       'ServicesDefault in roles/Compute.yaml' % env_filename)
167                 return 1
168     return 0
169
170
171 def validate_hci_computehci_role(hci_role_filename, hci_role_tpl):
172     compute_role_filename = os.path.join(os.path.dirname(hci_role_filename),
173                                          './Compute.yaml')
174     compute_role_tpl = yaml.load(open(compute_role_filename).read())
175     compute_role_services = compute_role_tpl[0]['ServicesDefault']
176     for role in hci_role_tpl:
177         if role['name'] == 'ComputeHCI':
178             hci_role_services = role['ServicesDefault']
179             hci_role_services.remove('OS::TripleO::Services::CephOSD')
180             if sorted(hci_role_services) != sorted(compute_role_services):
181                 print('ERROR: ServicesDefault in %s is different from'
182                       'ServicesDefault in roles/Compute.yaml' % hci_role_filename)
183                 return 1
184     return 0
185
186
187 def search(item, check_item, check_key):
188     if check_item(item):
189         return True
190     elif isinstance(item, list):
191         for i in item:
192             if search(i, check_item, check_key):
193                 return True
194     elif isinstance(item, dict):
195         for k in item.keys():
196             if check_key(k, item[k]):
197                 return True
198             elif search(item[k], check_item, check_key):
199                 return True
200     return False
201
202
203 def validate_mysql_connection(settings):
204     no_op = lambda *args: False
205     error_status = [0]
206
207     def mysql_protocol(items):
208         return items == ['EndpointMap', 'MysqlInternal', 'protocol']
209
210     def client_bind_address(item):
211         return 'read_default_file' in item and \
212                'read_default_group' in item
213
214     def validate_mysql_uri(key, items):
215         # Only consider a connection if it targets mysql
216         if key.endswith('connection') and \
217            search(items, mysql_protocol, no_op):
218             # Assume the "bind_address" option is one of
219             # the token that made up the uri
220             if not search(items, client_bind_address, no_op):
221                 error_status[0] = 1
222         return False
223
224     search(settings, no_op, validate_mysql_uri)
225     return error_status[0]
226
227
228 def validate_docker_service_mysql_usage(filename, tpl):
229     no_op = lambda *args: False
230     included_res = []
231
232     def match_included_res(item):
233         is_config_setting = isinstance(item, list) and len(item) > 1 and \
234             item[1:] == ['role_data', 'config_settings']
235         if is_config_setting:
236             included_res.append(item[0])
237         return is_config_setting
238
239     def match_use_mysql_protocol(items):
240         return items == ['EndpointMap', 'MysqlInternal', 'protocol']
241
242     all_content = []
243
244     def read_all(incfile, inctpl):
245         # search for included content
246         content = inctpl['outputs']['role_data']['value'].get('config_settings',{})
247         all_content.append(content)
248         included_res[:] = []
249         if search(content, match_included_res, no_op):
250             files = [inctpl['resources'][x]['type'] for x in included_res]
251             # parse included content
252             for r, f in zip(included_res, files):
253                 # disregard class names, only consider file names
254                 if 'OS::' in f:
255                     continue
256                 newfile = os.path.normpath(os.path.dirname(incfile)+'/'+f)
257                 newtmp = yaml.load(open(newfile).read())
258                 read_all(newfile, newtmp)
259
260     read_all(filename, tpl)
261     if search(all_content, match_use_mysql_protocol, no_op):
262         # ensure this service includes the mysqlclient service
263         resources = tpl['resources']
264         mysqlclient = [x for x in resources
265                        if resources[x]['type'].endswith('mysql-client.yaml')]
266         if len(mysqlclient) == 0:
267             print("ERROR: containerized service %s uses mysql but "
268                   "resource mysql-client.yaml is not used"
269                   % filename)
270             return 1
271
272         # and that mysql::client puppet module is included in puppet-config
273         match_mysqlclient = \
274             lambda x: x == [mysqlclient[0], 'role_data', 'step_config']
275         role_data = tpl['outputs']['role_data']
276         puppet_config = role_data['value']['puppet_config']['step_config']
277         if not search(puppet_config, match_mysqlclient, no_op):
278             print("ERROR: containerized service %s uses mysql but "
279                   "puppet_config section does not include "
280                   "::tripleo::profile::base::database::mysql::client"
281                   % filename)
282             return 1
283
284     return 0
285
286
287 def validate_docker_service(filename, tpl):
288     if 'outputs' in tpl and 'role_data' in tpl['outputs']:
289         if 'value' not in tpl['outputs']['role_data']:
290             print('ERROR: invalid role_data for filename: %s'
291                   % filename)
292             return 1
293         role_data = tpl['outputs']['role_data']['value']
294
295         for section_name in REQUIRED_DOCKER_SECTIONS:
296             if section_name not in role_data:
297                 print('ERROR: %s is required in role_data for %s.'
298                       % (section_name, filename))
299                 return 1
300
301         for section_name in role_data.keys():
302             if section_name in REQUIRED_DOCKER_SECTIONS:
303                 continue
304             else:
305                 if section_name in OPTIONAL_DOCKER_SECTIONS:
306                     continue
307                 elif section_name in OPTIONAL_SECTIONS:
308                     continue
309                 else:
310                     print('ERROR: %s is extra in role_data for %s.'
311                           % (section_name, filename))
312                     return 1
313
314         if 'puppet_config' in role_data:
315             if validate_docker_service_mysql_usage(filename, tpl):
316                 print('ERROR: could not validate use of mysql service for %s.'
317                       % filename)
318                 return 1
319             puppet_config = role_data['puppet_config']
320             for key in puppet_config:
321                 if key in REQUIRED_DOCKER_PUPPET_CONFIG_SECTIONS:
322                     continue
323                 else:
324                     if key in OPTIONAL_DOCKER_PUPPET_CONFIG_SECTIONS:
325                         continue
326                     else:
327                       print('ERROR: %s should not be in puppet_config section.'
328                             % key)
329                       return 1
330             for key in REQUIRED_DOCKER_PUPPET_CONFIG_SECTIONS:
331               if key not in puppet_config:
332                   print('ERROR: %s is required in puppet_config for %s.'
333                         % (key, filename))
334                   return 1
335
336             config_volume = puppet_config.get('config_volume')
337             expected_config_image_parameter = "Docker%sConfigImage" % to_camel_case(config_volume)
338             if config_volume and not expected_config_image_parameter in tpl.get('parameters', []):
339                 print('ERROR: Missing %s heat parameter for %s config_volume.'
340                       % (expected_config_image_parameter, config_volume))
341                 return 1
342
343         if 'docker_config' in role_data:
344             docker_config = role_data['docker_config']
345             for _, step in docker_config.items():
346                 if not isinstance(step, dict):
347                     # NOTE(mandre) this skips everything that is not a dict
348                     # so we may ignore some containers definitions if they
349                     # are in a map_merge for example
350                     continue
351                 for _, container in step.items():
352                     if not isinstance(container, dict):
353                         continue
354                     command = container.get('command', '')
355                     if isinstance(command, list):
356                         command = ' '.join(map(str, command))
357                     if 'bootstrap_host_exec' in command \
358                             and container.get('user') != 'root':
359                       print('ERROR: bootstrap_host_exec needs to run as the root user.')
360                       return 1
361
362     if 'parameters' in tpl:
363         for param in required_params:
364             if param not in tpl['parameters']:
365                 print('ERROR: parameter %s is required for %s.'
366                       % (param, filename))
367                 return 1
368     return 0
369
370
371 def validate_service(filename, tpl):
372     if 'outputs' in tpl and 'role_data' in tpl['outputs']:
373         if 'value' not in tpl['outputs']['role_data']:
374             print('ERROR: invalid role_data for filename: %s'
375                   % filename)
376             return 1
377         role_data = tpl['outputs']['role_data']['value']
378         if 'service_name' not in role_data:
379             print('ERROR: service_name is required in role_data for %s.'
380                   % filename)
381             return 1
382         # service_name must match the filename, but with an underscore
383         if (role_data['service_name'] !=
384                 os.path.basename(filename).split('.')[0].replace("-", "_")):
385             print('ERROR: service_name should match file name for service: %s.'
386                   % filename)
387             return 1
388         # if service connects to mysql, the uri should use option
389         # bind_address to avoid issues with VIP failover
390         if 'config_settings' in role_data and \
391            validate_mysql_connection(role_data['config_settings']):
392             print('ERROR: mysql connection uri should use option bind_address')
393             return 1
394     if 'parameters' in tpl:
395         for param in required_params:
396             if param not in tpl['parameters']:
397                 print('ERROR: parameter %s is required for %s.'
398                       % (param, filename))
399                 return 1
400     return 0
401
402
403 def validate(filename, param_map):
404     """Validate a Heat template
405
406     :param filename: The path to the file to validate
407     :param param_map: A dict which will be populated with the details of the
408                       parameters in the template.  The dict will have the
409                       following structure:
410
411                           {'ParameterName': [
412                                {'filename': ./file1.yaml,
413                                 'data': {'description': '',
414                                          'type': string,
415                                          'default': '',
416                                          ...}
417                                 },
418                                {'filename': ./file2.yaml,
419                                 'data': {'description': '',
420                                          'type': string,
421                                          'default': '',
422                                          ...}
423                                 },
424                                 ...
425                            ]}
426     """
427     print('Validating %s' % filename)
428     retval = 0
429     try:
430         tpl = yaml.load(open(filename).read())
431
432         # The template alias version should be used instead a date, this validation
433         # will be applied to all templates not just for those in the services folder.
434         if 'heat_template_version' in tpl and not str(tpl['heat_template_version']).isalpha():
435             print('ERROR: heat_template_version needs to be the release alias not a date: %s'
436                   % filename)
437             return 1
438
439         # qdr aliases rabbitmq service to provide alternative messaging backend
440         if (filename.startswith('./puppet/services/') and
441                 filename not in ['./puppet/services/qdr.yaml']):
442             retval = validate_service(filename, tpl)
443
444         if filename.startswith('./docker/services/'):
445             retval = validate_docker_service(filename, tpl)
446
447         if filename.endswith('hyperconverged-ceph.yaml'):
448             retval = validate_hci_compute_services_default(filename, tpl)
449
450         if filename.startswith('./roles/ComputeHCI.yaml'):
451             retval = validate_hci_computehci_role(filename, tpl)
452
453     except Exception:
454         print(traceback.format_exc())
455         return 1
456     # yaml is OK, now walk the parameters and output a warning for unused ones
457     if 'heat_template_version' in tpl:
458         for p, data in tpl.get('parameters', {}).items():
459             definition = {'data': data, 'filename': filename}
460             param_map.setdefault(p, []).append(definition)
461             if p in required_params:
462                 continue
463             str_p = '\'%s\'' % p
464             in_resources = str_p in str(tpl.get('resources', {}))
465             in_outputs = str_p in str(tpl.get('outputs', {}))
466             if not in_resources and not in_outputs:
467                 print('Warning: parameter %s in template %s '
468                       'appears to be unused' % (p, filename))
469
470     return retval
471
472 if len(sys.argv) < 2:
473     exit_usage()
474
475 path_args = sys.argv[1:]
476 exit_val = 0
477 failed_files = []
478 base_endpoint_map = None
479 env_endpoint_maps = list()
480 param_map = {}
481
482 for base_path in path_args:
483     if os.path.isdir(base_path):
484         for subdir, dirs, files in os.walk(base_path):
485             if '.tox' in dirs:
486                 dirs.remove('.tox')
487             for f in files:
488                 if f.endswith('.yaml') and not f.endswith('.j2.yaml'):
489                     file_path = os.path.join(subdir, f)
490                     failed = validate(file_path, param_map)
491                     if failed:
492                         failed_files.append(file_path)
493                     exit_val |= failed
494                     if f == ENDPOINT_MAP_FILE:
495                         base_endpoint_map = get_base_endpoint_map(file_path)
496                     if f in envs_containing_endpoint_map:
497                         env_endpoint_map = get_endpoint_map_from_env(file_path)
498                         if env_endpoint_map:
499                             env_endpoint_maps.append(env_endpoint_map)
500     elif os.path.isfile(base_path) and base_path.endswith('.yaml'):
501         failed = validate(base_path, param_map)
502         if failed:
503             failed_files.append(base_path)
504         exit_val |= failed
505     else:
506         print('Unexpected argument %s' % base_path)
507         exit_usage()
508
509 if base_endpoint_map and \
510         len(env_endpoint_maps) == len(envs_containing_endpoint_map):
511     for env_endpoint_map in env_endpoint_maps:
512         matches = validate_endpoint_map(base_endpoint_map,
513                                         env_endpoint_map['map'])
514         if not matches:
515             print("ERROR: %s needs to be updated to match changes in base "
516                   "endpoint map" % env_endpoint_map['file'])
517             failed_files.append(env_endpoint_map['file'])
518             exit_val |= 1
519         else:
520             print("%s matches base endpoint map" % env_endpoint_map['file'])
521 else:
522     print("ERROR: Did not find expected number of environments containing the "
523           "EndpointMap parameter.  If you meant to add or remove one of these "
524           "environments then you also need to update this tool.")
525     if not base_endpoint_map:
526         failed_files.append(ENDPOINT_MAP_FILE)
527     if len(env_endpoint_maps) != len(envs_containing_endpoint_map):
528         matched_files = set(os.path.basename(matched_env_file['file'])
529                             for matched_env_file in env_endpoint_maps)
530         failed_files.extend(set(envs_containing_endpoint_map) - matched_files)
531     exit_val |= 1
532
533 # Validate that duplicate parameters defined in multiple files all have the
534 # same definition.
535 mismatch_count = 0
536 for p, defs in param_map.items():
537     # Nothing to validate if the parameter is only defined once
538     if len(defs) == 1:
539         continue
540     check_data = [d['data'] for d in defs]
541     # Override excluded fields so they don't affect the result
542     exclusions = PARAMETER_DEFINITION_EXCLUSIONS.get(p, [])
543     ex_dict = {}
544     for field in exclusions:
545         ex_dict[field] = 'IGNORED'
546     for d in check_data:
547         d.update(ex_dict)
548     # If all items in the list are not == the first, then the check fails
549     if check_data.count(check_data[0]) != len(check_data):
550         mismatch_count += 1
551         exit_val |= 1
552         failed_files.extend([d['filename'] for d in defs])
553         print('Mismatched parameter definitions found for "%s"' % p)
554         print('Definitions found:')
555         for d in defs:
556             print('  %s:\n    %s' % (d['filename'], d['data']))
557 print('Mismatched parameter definitions: %d' % mismatch_count)
558
559 if failed_files:
560     print('Validation failed on:')
561     for f in failed_files:
562         print(f)
563 else:
564     print('Validation successful!')
565 sys.exit(exit_val)