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 = {'CephPools': ['description',
52 'ManagementNetCidr': ['default'],
53 'ManagementAllocationPools': ['default'],
54 'ExternalNetCidr': ['default'],
55 'ExternalAllocationPools': ['default'],
56 'StorageNetCidr': ['default'],
57 'StorageAllocationPools': ['default'],
58 'StorageMgmtNetCidr': ['default'],
59 'StorageMgmtAllocationPools': ['default'],
60 'TenantNetCidr': ['default'],
61 'TenantAllocationPools': ['default'],
62 'InternalApiNetCidr': ['default'],
63 'InternalApiAllocationPools': ['default'],
64 'UpdateIdentifier': ['description'],
65 'key_name': ['default'],
66 # There's one template that defines this
67 # differently, and I'm not sure if we can
69 'EC2MetadataIp': ['default'],
70 # Same as EC2MetadataIp
71 'ControlPlaneDefaultRoute': ['default'],
72 # TODO(bnemec): Address these existing
74 'ServiceNetMap': ['description', 'default'],
75 'network': ['default'],
76 'ControlPlaneIP': ['default',
78 'ControlPlaneIp': ['default',
80 'NeutronBigswitchLLDPEnabled': ['default'],
81 'NeutronWorkers': ['description'],
82 'ServerMetadata': ['description'],
83 'server': ['description'],
84 'servers': ['description'],
85 'ExtraConfig': ['description'],
86 'DefaultPasswords': ['description',
88 'BondInterfaceOvsOptions': ['description',
91 'KeyName': ['constraints'],
92 'OVNSouthboundServerPort': ['description'],
93 'ExternalInterfaceDefaultRoute':
94 ['description', 'default'],
95 'ManagementInterfaceDefaultRoute':
96 ['description', 'default'],
97 'IPPool': ['description'],
98 'SSLCertificate': ['description',
101 'HostCpusList': ['default', 'constraints'],
102 'NodeIndex': ['description'],
103 'name': ['description', 'default'],
104 'image': ['description', 'default'],
105 'NeutronBigswitchAgentEnabled': ['default'],
106 'EndpointMap': ['description', 'default'],
107 'DockerManilaConfigImage': ['description',
109 'replacement_policy': ['default'],
110 'CloudDomain': ['description', 'default'],
111 'EnableLoadBalancer': ['description'],
112 'ControllerExtraConfig': ['description'],
113 'NovaComputeExtraConfig': ['description'],
114 'controllerExtraConfig': ['description'],
115 'DockerSwiftConfigImage': ['default']
118 PREFERRED_CAMEL_CASE = {
120 'haproxy': 'HAProxy',
123 # Overrides for docker/puppet validation
124 # <filename>: True explicitly enables validation
125 # <filename>: False explicitly disables validation
127 # If a filename is not found in the overrides then the top level directory is
128 # used to determine which validation method to use.
129 VALIDATE_PUPPET_OVERRIDE = {
130 # docker/service/sshd.yaml is a variation of the puppet sshd service
131 './docker/services/sshd.yaml': True,
132 # qdr aliases rabbitmq service to provide alternative messaging backend
133 './puppet/services/qdr.yaml': False,
135 VALIDATE_DOCKER_OVERRIDE = {
136 # docker/service/sshd.yaml is a variation of the puppet sshd service
137 './docker/services/sshd.yaml': False,
141 print('Usage %s <yaml file or directory>' % sys.argv[0])
145 def to_camel_case(string):
146 return PREFERRED_CAMEL_CASE.get(string, ''.join(s.capitalize() or '_' for
147 s in string.split('_')))
150 def get_base_endpoint_map(filename):
152 tpl = yaml.load(open(filename).read())
153 return tpl['parameters']['EndpointMap']['default']
155 print(traceback.format_exc())
159 def get_endpoint_map_from_env(filename):
161 tpl = yaml.load(open(filename).read())
164 'map': tpl['parameter_defaults']['EndpointMap']
167 print(traceback.format_exc())
171 def validate_endpoint_map(base_map, env_map):
172 return sorted(base_map.keys()) == sorted(env_map.keys())
175 def validate_hci_compute_services_default(env_filename, env_tpl):
176 env_services_list = env_tpl['parameter_defaults']['ComputeServices']
177 env_services_list.remove('OS::TripleO::Services::CephOSD')
178 roles_filename = os.path.join(os.path.dirname(env_filename),
179 '../roles/Compute.yaml')
180 roles_tpl = yaml.load(open(roles_filename).read())
181 for role in roles_tpl:
182 if role['name'] == 'Compute':
183 roles_services_list = role['ServicesDefault']
184 if sorted(env_services_list) != sorted(roles_services_list):
185 print('ERROR: ComputeServices in %s is different from '
186 'ServicesDefault in roles/Compute.yaml' % env_filename)
191 def validate_hci_computehci_role(hci_role_filename, hci_role_tpl):
192 compute_role_filename = os.path.join(os.path.dirname(hci_role_filename),
194 compute_role_tpl = yaml.load(open(compute_role_filename).read())
195 compute_role_services = compute_role_tpl[0]['ServicesDefault']
196 for role in hci_role_tpl:
197 if role['name'] == 'ComputeHCI':
198 hci_role_services = role['ServicesDefault']
199 hci_role_services.remove('OS::TripleO::Services::CephOSD')
200 if sorted(hci_role_services) != sorted(compute_role_services):
201 print('ERROR: ServicesDefault in %s is different from'
202 'ServicesDefault in roles/Compute.yaml' % hci_role_filename)
207 def search(item, check_item, check_key):
210 elif isinstance(item, list):
212 if search(i, check_item, check_key):
214 elif isinstance(item, dict):
215 for k in item.keys():
216 if check_key(k, item[k]):
218 elif search(item[k], check_item, check_key):
223 def validate_mysql_connection(settings):
224 no_op = lambda *args: False
227 def mysql_protocol(items):
228 return items == ['EndpointMap', 'MysqlInternal', 'protocol']
230 def client_bind_address(item):
231 return 'read_default_file' in item and \
232 'read_default_group' in item
234 def validate_mysql_uri(key, items):
235 # Only consider a connection if it targets mysql
236 if key.endswith('connection') and \
237 search(items, mysql_protocol, no_op):
238 # Assume the "bind_address" option is one of
239 # the token that made up the uri
240 if not search(items, client_bind_address, no_op):
244 search(settings, no_op, validate_mysql_uri)
245 return error_status[0]
248 def validate_docker_service_mysql_usage(filename, tpl):
249 no_op = lambda *args: False
252 def match_included_res(item):
253 is_config_setting = isinstance(item, list) and len(item) > 1 and \
254 item[1:] == ['role_data', 'config_settings']
255 if is_config_setting:
256 included_res.append(item[0])
257 return is_config_setting
259 def match_use_mysql_protocol(items):
260 return items == ['EndpointMap', 'MysqlInternal', 'protocol']
264 def read_all(incfile, inctpl):
265 # search for included content
266 content = inctpl['outputs']['role_data']['value'].get('config_settings',{})
267 all_content.append(content)
269 if search(content, match_included_res, no_op):
270 files = [inctpl['resources'][x]['type'] for x in included_res]
271 # parse included content
272 for r, f in zip(included_res, files):
273 # disregard class names, only consider file names
276 newfile = os.path.normpath(os.path.dirname(incfile)+'/'+f)
277 newtmp = yaml.load(open(newfile).read())
278 read_all(newfile, newtmp)
280 read_all(filename, tpl)
281 if search(all_content, match_use_mysql_protocol, no_op):
282 # ensure this service includes the mysqlclient service
283 resources = tpl['resources']
284 mysqlclient = [x for x in resources
285 if resources[x]['type'].endswith('mysql-client.yaml')]
286 if len(mysqlclient) == 0:
287 print("ERROR: containerized service %s uses mysql but "
288 "resource mysql-client.yaml is not used"
292 # and that mysql::client puppet module is included in puppet-config
293 match_mysqlclient = \
294 lambda x: x == [mysqlclient[0], 'role_data', 'step_config']
295 role_data = tpl['outputs']['role_data']
296 puppet_config = role_data['value']['puppet_config']['step_config']
297 if not search(puppet_config, match_mysqlclient, no_op):
298 print("ERROR: containerized service %s uses mysql but "
299 "puppet_config section does not include "
300 "::tripleo::profile::base::database::mysql::client"
307 def validate_docker_service(filename, tpl):
308 if 'outputs' in tpl and 'role_data' in tpl['outputs']:
309 if 'value' not in tpl['outputs']['role_data']:
310 print('ERROR: invalid role_data for filename: %s'
313 role_data = tpl['outputs']['role_data']['value']
315 for section_name in REQUIRED_DOCKER_SECTIONS:
316 if section_name not in role_data:
317 print('ERROR: %s is required in role_data for %s.'
318 % (section_name, filename))
321 for section_name in role_data.keys():
322 if section_name in REQUIRED_DOCKER_SECTIONS:
325 if section_name in OPTIONAL_DOCKER_SECTIONS:
327 elif section_name in OPTIONAL_SECTIONS:
330 print('ERROR: %s is extra in role_data for %s.'
331 % (section_name, filename))
334 if 'puppet_config' in role_data:
335 if validate_docker_service_mysql_usage(filename, tpl):
336 print('ERROR: could not validate use of mysql service for %s.'
339 puppet_config = role_data['puppet_config']
340 for key in puppet_config:
341 if key in REQUIRED_DOCKER_PUPPET_CONFIG_SECTIONS:
344 if key in OPTIONAL_DOCKER_PUPPET_CONFIG_SECTIONS:
347 print('ERROR: %s should not be in puppet_config section.'
350 for key in REQUIRED_DOCKER_PUPPET_CONFIG_SECTIONS:
351 if key not in puppet_config:
352 print('ERROR: %s is required in puppet_config for %s.'
356 config_volume = puppet_config.get('config_volume')
357 expected_config_image_parameter = "Docker%sConfigImage" % to_camel_case(config_volume)
358 if config_volume and not expected_config_image_parameter in tpl.get('parameters', []):
359 print('ERROR: Missing %s heat parameter for %s config_volume.'
360 % (expected_config_image_parameter, config_volume))
363 if 'docker_config' in role_data:
364 docker_config = role_data['docker_config']
365 for _, step in docker_config.items():
366 if not isinstance(step, dict):
367 # NOTE(mandre) this skips everything that is not a dict
368 # so we may ignore some containers definitions if they
369 # are in a map_merge for example
371 for _, container in step.items():
372 if not isinstance(container, dict):
374 command = container.get('command', '')
375 if isinstance(command, list):
376 command = ' '.join(map(str, command))
377 if 'bootstrap_host_exec' in command \
378 and container.get('user') != 'root':
379 print('ERROR: bootstrap_host_exec needs to run as the root user.')
382 if 'parameters' in tpl:
383 for param in required_params:
384 if param not in tpl['parameters']:
385 print('ERROR: parameter %s is required for %s.'
391 def validate_service(filename, tpl):
392 if 'outputs' in tpl and 'role_data' in tpl['outputs']:
393 if 'value' not in tpl['outputs']['role_data']:
394 print('ERROR: invalid role_data for filename: %s'
397 role_data = tpl['outputs']['role_data']['value']
398 if 'service_name' not in role_data:
399 print('ERROR: service_name is required in role_data for %s.'
402 # service_name must match the filename, but with an underscore
403 if (role_data['service_name'] !=
404 os.path.basename(filename).split('.')[0].replace("-", "_")):
405 print('ERROR: service_name should match file name for service: %s.'
408 # if service connects to mysql, the uri should use option
409 # bind_address to avoid issues with VIP failover
410 if 'config_settings' in role_data and \
411 validate_mysql_connection(role_data['config_settings']):
412 print('ERROR: mysql connection uri should use option bind_address')
414 if 'parameters' in tpl:
415 for param in required_params:
416 if param not in tpl['parameters']:
417 print('ERROR: parameter %s is required for %s.'
423 def validate(filename, param_map):
424 """Validate a Heat template
426 :param filename: The path to the file to validate
427 :param param_map: A dict which will be populated with the details of the
428 parameters in the template. The dict will have the
432 {'filename': ./file1.yaml,
433 'data': {'description': '',
438 {'filename': ./file2.yaml,
439 'data': {'description': '',
447 print('Validating %s' % filename)
450 tpl = yaml.load(open(filename).read())
452 # The template alias version should be used instead a date, this validation
453 # will be applied to all templates not just for those in the services folder.
454 if 'heat_template_version' in tpl and not str(tpl['heat_template_version']).isalpha():
455 print('ERROR: heat_template_version needs to be the release alias not a date: %s'
459 if VALIDATE_PUPPET_OVERRIDE.get(filename, False) or (
460 filename.startswith('./puppet/services/') and
461 VALIDATE_PUPPET_OVERRIDE.get(filename, True)):
462 retval = validate_service(filename, tpl)
464 if VALIDATE_DOCKER_OVERRIDE.get(filename, False) or (
465 filename.startswith('./docker/services/') and
466 VALIDATE_DOCKER_OVERRIDE.get(filename, True)):
467 retval = validate_docker_service(filename, tpl)
469 if filename.endswith('hyperconverged-ceph.yaml'):
470 retval = validate_hci_compute_services_default(filename, tpl)
472 if filename.startswith('./roles/ComputeHCI.yaml'):
473 retval = validate_hci_computehci_role(filename, tpl)
476 print(traceback.format_exc())
478 # yaml is OK, now walk the parameters and output a warning for unused ones
479 if 'heat_template_version' in tpl:
480 for p, data in tpl.get('parameters', {}).items():
481 definition = {'data': data, 'filename': filename}
482 param_map.setdefault(p, []).append(definition)
483 if p in required_params:
486 in_resources = str_p in str(tpl.get('resources', {}))
487 in_outputs = str_p in str(tpl.get('outputs', {}))
488 if not in_resources and not in_outputs:
489 print('Warning: parameter %s in template %s '
490 'appears to be unused' % (p, filename))
494 if len(sys.argv) < 2:
497 path_args = sys.argv[1:]
500 base_endpoint_map = None
501 env_endpoint_maps = list()
504 for base_path in path_args:
505 if os.path.isdir(base_path):
506 for subdir, dirs, files in os.walk(base_path):
510 if f.endswith('.yaml') and not f.endswith('.j2.yaml'):
511 file_path = os.path.join(subdir, f)
512 failed = validate(file_path, param_map)
514 failed_files.append(file_path)
516 if f == ENDPOINT_MAP_FILE:
517 base_endpoint_map = get_base_endpoint_map(file_path)
518 if f in envs_containing_endpoint_map:
519 env_endpoint_map = get_endpoint_map_from_env(file_path)
521 env_endpoint_maps.append(env_endpoint_map)
522 elif os.path.isfile(base_path) and base_path.endswith('.yaml'):
523 failed = validate(base_path, param_map)
525 failed_files.append(base_path)
528 print('Unexpected argument %s' % base_path)
531 if base_endpoint_map and \
532 len(env_endpoint_maps) == len(envs_containing_endpoint_map):
533 for env_endpoint_map in env_endpoint_maps:
534 matches = validate_endpoint_map(base_endpoint_map,
535 env_endpoint_map['map'])
537 print("ERROR: %s needs to be updated to match changes in base "
538 "endpoint map" % env_endpoint_map['file'])
539 failed_files.append(env_endpoint_map['file'])
542 print("%s matches base endpoint map" % env_endpoint_map['file'])
544 print("ERROR: Did not find expected number of environments containing the "
545 "EndpointMap parameter. If you meant to add or remove one of these "
546 "environments then you also need to update this tool.")
547 if not base_endpoint_map:
548 failed_files.append(ENDPOINT_MAP_FILE)
549 if len(env_endpoint_maps) != len(envs_containing_endpoint_map):
550 matched_files = set(os.path.basename(matched_env_file['file'])
551 for matched_env_file in env_endpoint_maps)
552 failed_files.extend(set(envs_containing_endpoint_map) - matched_files)
555 # Validate that duplicate parameters defined in multiple files all have the
558 for p, defs in param_map.items():
559 # Nothing to validate if the parameter is only defined once
562 check_data = [d['data'] for d in defs]
563 # Override excluded fields so they don't affect the result
564 exclusions = PARAMETER_DEFINITION_EXCLUSIONS.get(p, [])
566 for field in exclusions:
567 ex_dict[field] = 'IGNORED'
570 # If all items in the list are not == the first, then the check fails
571 if check_data.count(check_data[0]) != len(check_data):
574 failed_files.extend([d['filename'] for d in defs])
575 print('Mismatched parameter definitions found for "%s"' % p)
576 print('Definitions found:')
578 print(' %s:\n %s' % (d['filename'], d['data']))
579 print('Mismatched parameter definitions: %d' % mismatch_count)
582 print('Validation failed on:')
583 for f in failed_files:
586 print('Validation successful!')