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
6 # http://www.apache.org/licenses/LICENSE-2.0
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
20 required_params = ['EndpointMap', 'ServiceNetMap', 'DefaultPasswords',
21 'RoleName', 'RoleParameters', 'ServiceData']
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', 'update_tasks',
39 'service_config_settings',
40 'host_prep_tasks', 'metadata_settings',
41 'kolla_config', 'logging_source', 'logging_groups']
42 REQUIRED_DOCKER_PUPPET_CONFIG_SECTIONS = ['config_volume', 'step_config',
44 OPTIONAL_DOCKER_PUPPET_CONFIG_SECTIONS = [ 'puppet_tags', 'volumes' ]
45 # Mapping of parameter names to a list of the fields we should _not_ enforce
46 # consistency across files on. This should only contain parameters whose
47 # definition we cannot change for backwards compatibility reasons. New
48 # parameters to the templates should not be added to this list.
49 PARAMETER_DEFINITION_EXCLUSIONS = {'ManagementNetCidr': ['default'],
50 'ManagementAllocationPools': ['default'],
51 'ExternalNetCidr': ['default'],
52 'ExternalAllocationPools': ['default'],
53 'StorageNetCidr': ['default'],
54 'StorageAllocationPools': ['default'],
55 'StorageMgmtNetCidr': ['default'],
56 'StorageMgmtAllocationPools': ['default'],
57 'TenantNetCidr': ['default'],
58 'TenantAllocationPools': ['default'],
59 'InternalApiNetCidr': ['default'],
60 'InternalApiAllocationPools': ['default'],
61 'UpdateIdentifier': ['description'],
62 'key_name': ['default'],
63 # There's one template that defines this
64 # differently, and I'm not sure if we can
66 'EC2MetadataIp': ['default'],
67 # Same as EC2MetadataIp
68 'ControlPlaneDefaultRoute': ['default'],
69 # TODO(bnemec): Address these existing
71 'ServiceNetMap': ['description', 'default'],
72 'network': ['default'],
73 'ControlPlaneIP': ['default',
75 'ControlPlaneIp': ['default',
77 'NeutronBigswitchLLDPEnabled': ['default'],
78 'NeutronWorkers': ['description'],
79 'ServerMetadata': ['description'],
80 'server': ['description'],
81 'servers': ['description'],
82 'ExtraConfig': ['description'],
83 'DefaultPasswords': ['description',
85 'BondInterfaceOvsOptions': ['description',
88 'KeyName': ['constraints'],
89 'OVNSouthboundServerPort': ['description'],
90 'ExternalInterfaceDefaultRoute':
91 ['description', 'default'],
92 'ManagementInterfaceDefaultRoute':
93 ['description', 'default'],
94 'IPPool': ['description'],
95 'SSLCertificate': ['description',
98 'HostCpusList': ['default', 'constraints'],
99 'NodeIndex': ['description'],
100 'name': ['description', 'default'],
101 'image': ['description', 'default'],
102 'NeutronBigswitchAgentEnabled': ['default'],
103 'EndpointMap': ['description', 'default'],
104 'DockerManilaConfigImage': ['description',
106 'replacement_policy': ['default'],
107 'CloudDomain': ['description', 'default'],
108 'EnableLoadBalancer': ['description'],
109 'ControllerExtraConfig': ['description'],
110 'NovaComputeExtraConfig': ['description'],
111 'controllerExtraConfig': ['description'],
112 'DockerSwiftConfigImage': ['default']
115 PREFERRED_CAMEL_CASE = {
117 'haproxy': 'HAProxy',
120 # Overrides for docker/puppet validation
121 # <filename>: True explicitly enables validation
122 # <filename>: False explicitly disables validation
124 # If a filename is not found in the overrides then the top level directory is
125 # used to determine which validation method to use.
126 VALIDATE_PUPPET_OVERRIDE = {
127 # docker/service/sshd.yaml is a variation of the puppet sshd service
128 './docker/services/sshd.yaml': True,
129 # qdr aliases rabbitmq service to provide alternative messaging backend
130 './puppet/services/qdr.yaml': False,
132 VALIDATE_DOCKER_OVERRIDE = {
133 # docker/service/sshd.yaml is a variation of the puppet sshd service
134 './docker/services/sshd.yaml': False,
138 print('Usage %s <yaml file or directory>' % sys.argv[0])
142 def to_camel_case(string):
143 return PREFERRED_CAMEL_CASE.get(string, ''.join(s.capitalize() or '_' for
144 s in string.split('_')))
147 def get_base_endpoint_map(filename):
149 tpl = yaml.load(open(filename).read())
150 return tpl['parameters']['EndpointMap']['default']
152 print(traceback.format_exc())
156 def get_endpoint_map_from_env(filename):
158 tpl = yaml.load(open(filename).read())
161 'map': tpl['parameter_defaults']['EndpointMap']
164 print(traceback.format_exc())
168 def validate_endpoint_map(base_map, env_map):
169 return sorted(base_map.keys()) == sorted(env_map.keys())
172 def validate_hci_compute_services_default(env_filename, env_tpl):
173 env_services_list = env_tpl['parameter_defaults']['ComputeServices']
174 env_services_list.remove('OS::TripleO::Services::CephOSD')
175 roles_filename = os.path.join(os.path.dirname(env_filename),
176 '../roles/Compute.yaml')
177 roles_tpl = yaml.load(open(roles_filename).read())
178 for role in roles_tpl:
179 if role['name'] == 'Compute':
180 roles_services_list = role['ServicesDefault']
181 if sorted(env_services_list) != sorted(roles_services_list):
182 print('ERROR: ComputeServices in %s is different from '
183 'ServicesDefault in roles/Compute.yaml' % env_filename)
188 def validate_hci_computehci_role(hci_role_filename, hci_role_tpl):
189 compute_role_filename = os.path.join(os.path.dirname(hci_role_filename),
191 compute_role_tpl = yaml.load(open(compute_role_filename).read())
192 compute_role_services = compute_role_tpl[0]['ServicesDefault']
193 for role in hci_role_tpl:
194 if role['name'] == 'ComputeHCI':
195 hci_role_services = role['ServicesDefault']
196 hci_role_services.remove('OS::TripleO::Services::CephOSD')
197 if sorted(hci_role_services) != sorted(compute_role_services):
198 print('ERROR: ServicesDefault in %s is different from'
199 'ServicesDefault in roles/Compute.yaml' % hci_role_filename)
204 def search(item, check_item, check_key):
207 elif isinstance(item, list):
209 if search(i, check_item, check_key):
211 elif isinstance(item, dict):
212 for k in item.keys():
213 if check_key(k, item[k]):
215 elif search(item[k], check_item, check_key):
220 def validate_mysql_connection(settings):
221 no_op = lambda *args: False
224 def mysql_protocol(items):
225 return items == ['EndpointMap', 'MysqlInternal', 'protocol']
227 def client_bind_address(item):
228 return 'read_default_file' in item and \
229 'read_default_group' in item
231 def validate_mysql_uri(key, items):
232 # Only consider a connection if it targets mysql
233 if key.endswith('connection') and \
234 search(items, mysql_protocol, no_op):
235 # Assume the "bind_address" option is one of
236 # the token that made up the uri
237 if not search(items, client_bind_address, no_op):
241 search(settings, no_op, validate_mysql_uri)
242 return error_status[0]
245 def validate_docker_service_mysql_usage(filename, tpl):
246 no_op = lambda *args: False
249 def match_included_res(item):
250 is_config_setting = isinstance(item, list) and len(item) > 1 and \
251 item[1:] == ['role_data', 'config_settings']
252 if is_config_setting:
253 included_res.append(item[0])
254 return is_config_setting
256 def match_use_mysql_protocol(items):
257 return items == ['EndpointMap', 'MysqlInternal', 'protocol']
261 def read_all(incfile, inctpl):
262 # search for included content
263 content = inctpl['outputs']['role_data']['value'].get('config_settings',{})
264 all_content.append(content)
266 if search(content, match_included_res, no_op):
267 files = [inctpl['resources'][x]['type'] for x in included_res]
268 # parse included content
269 for r, f in zip(included_res, files):
270 # disregard class names, only consider file names
273 newfile = os.path.normpath(os.path.dirname(incfile)+'/'+f)
274 newtmp = yaml.load(open(newfile).read())
275 read_all(newfile, newtmp)
277 read_all(filename, tpl)
278 if search(all_content, match_use_mysql_protocol, no_op):
279 # ensure this service includes the mysqlclient service
280 resources = tpl['resources']
281 mysqlclient = [x for x in resources
282 if resources[x]['type'].endswith('mysql-client.yaml')]
283 if len(mysqlclient) == 0:
284 print("ERROR: containerized service %s uses mysql but "
285 "resource mysql-client.yaml is not used"
289 # and that mysql::client puppet module is included in puppet-config
290 match_mysqlclient = \
291 lambda x: x == [mysqlclient[0], 'role_data', 'step_config']
292 role_data = tpl['outputs']['role_data']
293 puppet_config = role_data['value']['puppet_config']['step_config']
294 if not search(puppet_config, match_mysqlclient, no_op):
295 print("ERROR: containerized service %s uses mysql but "
296 "puppet_config section does not include "
297 "::tripleo::profile::base::database::mysql::client"
304 def validate_docker_service(filename, tpl):
305 if 'outputs' in tpl and 'role_data' in tpl['outputs']:
306 if 'value' not in tpl['outputs']['role_data']:
307 print('ERROR: invalid role_data for filename: %s'
310 role_data = tpl['outputs']['role_data']['value']
312 for section_name in REQUIRED_DOCKER_SECTIONS:
313 if section_name not in role_data:
314 print('ERROR: %s is required in role_data for %s.'
315 % (section_name, filename))
318 for section_name in role_data.keys():
319 if section_name in REQUIRED_DOCKER_SECTIONS:
322 if section_name in OPTIONAL_DOCKER_SECTIONS:
324 elif section_name in OPTIONAL_SECTIONS:
327 print('ERROR: %s is extra in role_data for %s.'
328 % (section_name, filename))
331 if 'puppet_config' in role_data:
332 if validate_docker_service_mysql_usage(filename, tpl):
333 print('ERROR: could not validate use of mysql service for %s.'
336 puppet_config = role_data['puppet_config']
337 for key in puppet_config:
338 if key in REQUIRED_DOCKER_PUPPET_CONFIG_SECTIONS:
341 if key in OPTIONAL_DOCKER_PUPPET_CONFIG_SECTIONS:
344 print('ERROR: %s should not be in puppet_config section.'
347 for key in REQUIRED_DOCKER_PUPPET_CONFIG_SECTIONS:
348 if key not in puppet_config:
349 print('ERROR: %s is required in puppet_config for %s.'
353 config_volume = puppet_config.get('config_volume')
354 expected_config_image_parameter = "Docker%sConfigImage" % to_camel_case(config_volume)
355 if config_volume and not expected_config_image_parameter in tpl.get('parameters', []):
356 print('ERROR: Missing %s heat parameter for %s config_volume.'
357 % (expected_config_image_parameter, config_volume))
360 if 'docker_config' in role_data:
361 docker_config = role_data['docker_config']
362 for _, step in docker_config.items():
363 if not isinstance(step, dict):
364 # NOTE(mandre) this skips everything that is not a dict
365 # so we may ignore some containers definitions if they
366 # are in a map_merge for example
368 for _, container in step.items():
369 if not isinstance(container, dict):
371 command = container.get('command', '')
372 if isinstance(command, list):
373 command = ' '.join(map(str, command))
374 if 'bootstrap_host_exec' in command \
375 and container.get('user') != 'root':
376 print('ERROR: bootstrap_host_exec needs to run as the root user.')
379 if 'parameters' in tpl:
380 for param in required_params:
381 if param not in tpl['parameters']:
382 print('ERROR: parameter %s is required for %s.'
388 def validate_service(filename, tpl):
389 if 'outputs' in tpl and 'role_data' in tpl['outputs']:
390 if 'value' not in tpl['outputs']['role_data']:
391 print('ERROR: invalid role_data for filename: %s'
394 role_data = tpl['outputs']['role_data']['value']
395 if 'service_name' not in role_data:
396 print('ERROR: service_name is required in role_data for %s.'
399 # service_name must match the filename, but with an underscore
400 if (role_data['service_name'] !=
401 os.path.basename(filename).split('.')[0].replace("-", "_")):
402 print('ERROR: service_name should match file name for service: %s.'
405 # if service connects to mysql, the uri should use option
406 # bind_address to avoid issues with VIP failover
407 if 'config_settings' in role_data and \
408 validate_mysql_connection(role_data['config_settings']):
409 print('ERROR: mysql connection uri should use option bind_address')
411 if 'parameters' in tpl:
412 for param in required_params:
413 if param not in tpl['parameters']:
414 print('ERROR: parameter %s is required for %s.'
420 def validate(filename, param_map):
421 """Validate a Heat template
423 :param filename: The path to the file to validate
424 :param param_map: A dict which will be populated with the details of the
425 parameters in the template. The dict will have the
429 {'filename': ./file1.yaml,
430 'data': {'description': '',
435 {'filename': ./file2.yaml,
436 'data': {'description': '',
444 print('Validating %s' % filename)
447 tpl = yaml.load(open(filename).read())
449 # The template alias version should be used instead a date, this validation
450 # will be applied to all templates not just for those in the services folder.
451 if 'heat_template_version' in tpl and not str(tpl['heat_template_version']).isalpha():
452 print('ERROR: heat_template_version needs to be the release alias not a date: %s'
456 if VALIDATE_PUPPET_OVERRIDE.get(filename, False) or (
457 filename.startswith('./puppet/services/') and
458 VALIDATE_PUPPET_OVERRIDE.get(filename, True)):
459 retval = validate_service(filename, tpl)
461 if VALIDATE_DOCKER_OVERRIDE.get(filename, False) or (
462 filename.startswith('./docker/services/') and
463 VALIDATE_DOCKER_OVERRIDE.get(filename, True)):
464 retval = validate_docker_service(filename, tpl)
466 if filename.endswith('hyperconverged-ceph.yaml'):
467 retval = validate_hci_compute_services_default(filename, tpl)
469 if filename.startswith('./roles/ComputeHCI.yaml'):
470 retval = validate_hci_computehci_role(filename, tpl)
473 print(traceback.format_exc())
475 # yaml is OK, now walk the parameters and output a warning for unused ones
476 if 'heat_template_version' in tpl:
477 for p, data in tpl.get('parameters', {}).items():
478 definition = {'data': data, 'filename': filename}
479 param_map.setdefault(p, []).append(definition)
480 if p in required_params:
483 in_resources = str_p in str(tpl.get('resources', {}))
484 in_outputs = str_p in str(tpl.get('outputs', {}))
485 if not in_resources and not in_outputs:
486 print('Warning: parameter %s in template %s '
487 'appears to be unused' % (p, filename))
491 if len(sys.argv) < 2:
494 path_args = sys.argv[1:]
497 base_endpoint_map = None
498 env_endpoint_maps = list()
501 for base_path in path_args:
502 if os.path.isdir(base_path):
503 for subdir, dirs, files in os.walk(base_path):
507 if f.endswith('.yaml') and not f.endswith('.j2.yaml'):
508 file_path = os.path.join(subdir, f)
509 failed = validate(file_path, param_map)
511 failed_files.append(file_path)
513 if f == ENDPOINT_MAP_FILE:
514 base_endpoint_map = get_base_endpoint_map(file_path)
515 if f in envs_containing_endpoint_map:
516 env_endpoint_map = get_endpoint_map_from_env(file_path)
518 env_endpoint_maps.append(env_endpoint_map)
519 elif os.path.isfile(base_path) and base_path.endswith('.yaml'):
520 failed = validate(base_path, param_map)
522 failed_files.append(base_path)
525 print('Unexpected argument %s' % base_path)
528 if base_endpoint_map and \
529 len(env_endpoint_maps) == len(envs_containing_endpoint_map):
530 for env_endpoint_map in env_endpoint_maps:
531 matches = validate_endpoint_map(base_endpoint_map,
532 env_endpoint_map['map'])
534 print("ERROR: %s needs to be updated to match changes in base "
535 "endpoint map" % env_endpoint_map['file'])
536 failed_files.append(env_endpoint_map['file'])
539 print("%s matches base endpoint map" % env_endpoint_map['file'])
541 print("ERROR: Did not find expected number of environments containing the "
542 "EndpointMap parameter. If you meant to add or remove one of these "
543 "environments then you also need to update this tool.")
544 if not base_endpoint_map:
545 failed_files.append(ENDPOINT_MAP_FILE)
546 if len(env_endpoint_maps) != len(envs_containing_endpoint_map):
547 matched_files = set(os.path.basename(matched_env_file['file'])
548 for matched_env_file in env_endpoint_maps)
549 failed_files.extend(set(envs_containing_endpoint_map) - matched_files)
552 # Validate that duplicate parameters defined in multiple files all have the
555 for p, defs in param_map.items():
556 # Nothing to validate if the parameter is only defined once
559 check_data = [d['data'] for d in defs]
560 # Override excluded fields so they don't affect the result
561 exclusions = PARAMETER_DEFINITION_EXCLUSIONS.get(p, [])
563 for field in exclusions:
564 ex_dict[field] = 'IGNORED'
567 # If all items in the list are not == the first, then the check fails
568 if check_data.count(check_data[0]) != len(check_data):
571 failed_files.extend([d['filename'] for d in defs])
572 print('Mismatched parameter definitions found for "%s"' % p)
573 print('Definitions found:')
575 print(' %s:\n %s' % (d['filename'], d['data']))
576 print('Mismatched parameter definitions: %d' % mismatch_count)
579 print('Validation failed on:')
580 for f in failed_files:
583 print('Validation successful!')