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', 'service_config_settings',
39 'host_prep_tasks', 'metadata_settings',
40 'kolla_config', 'logging_source', 'logging_groups']
41 REQUIRED_DOCKER_PUPPET_CONFIG_SECTIONS = ['config_volume', 'step_config',
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
65 'EC2MetadataIp': ['default'],
66 # Same as EC2MetadataIp
67 'ControlPlaneDefaultRoute': ['default'],
68 # TODO(bnemec): Address these existing
70 'ServiceNetMap': ['description', 'default'],
71 'network': ['default'],
72 'ControlPlaneIP': ['default',
74 'ControlPlaneIp': ['default',
76 'NeutronBigswitchLLDPEnabled': ['default'],
77 'NeutronWorkers': ['description'],
78 'ServerMetadata': ['description'],
79 'server': ['description'],
80 'servers': ['description'],
81 'ExtraConfig': ['description'],
82 'DefaultPasswords': ['description',
84 'BondInterfaceOvsOptions': ['description',
87 'KeyName': ['constraints'],
88 'OVNSouthboundServerPort': ['description'],
89 'ExternalInterfaceDefaultRoute':
90 ['description', 'default'],
91 'ManagementInterfaceDefaultRoute':
92 ['description', 'default'],
93 'IPPool': ['description'],
94 'SSLCertificate': ['description',
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',
105 'replacement_policy': ['default'],
106 'CloudDomain': ['description', 'default'],
107 'EnableLoadBalancer': ['description'],
108 'ControllerExtraConfig': ['description'],
109 'NovaComputeExtraConfig': ['description'],
110 'controllerExtraConfig': ['description'],
111 'DockerSwiftConfigImage': ['default']
114 PREFERRED_CAMEL_CASE = {
116 'haproxy': 'HAProxy',
119 # Overrides for docker/puppet validation
120 # <filename>: True explicitly enables validation
121 # <filename>: False explicitly disables validation
123 # If a filename is not found in the overrides then the top level directory is
124 # used to determine which validation method to use.
125 VALIDATE_PUPPET_OVERRIDE = {
126 # docker/service/sshd.yaml is a variation of the puppet sshd service
127 './docker/services/sshd.yaml': True,
128 # qdr aliases rabbitmq service to provide alternative messaging backend
129 './puppet/services/qdr.yaml': False,
131 VALIDATE_DOCKER_OVERRIDE = {
132 # docker/service/sshd.yaml is a variation of the puppet sshd service
133 './docker/services/sshd.yaml': False,
137 print('Usage %s <yaml file or directory>' % sys.argv[0])
141 def to_camel_case(string):
142 return PREFERRED_CAMEL_CASE.get(string, ''.join(s.capitalize() or '_' for
143 s in string.split('_')))
146 def get_base_endpoint_map(filename):
148 tpl = yaml.load(open(filename).read())
149 return tpl['parameters']['EndpointMap']['default']
151 print(traceback.format_exc())
155 def get_endpoint_map_from_env(filename):
157 tpl = yaml.load(open(filename).read())
160 'map': tpl['parameter_defaults']['EndpointMap']
163 print(traceback.format_exc())
167 def validate_endpoint_map(base_map, env_map):
168 return sorted(base_map.keys()) == sorted(env_map.keys())
171 def validate_hci_compute_services_default(env_filename, env_tpl):
172 env_services_list = env_tpl['parameter_defaults']['ComputeServices']
173 env_services_list.remove('OS::TripleO::Services::CephOSD')
174 roles_filename = os.path.join(os.path.dirname(env_filename),
175 '../roles/Compute.yaml')
176 roles_tpl = yaml.load(open(roles_filename).read())
177 for role in roles_tpl:
178 if role['name'] == 'Compute':
179 roles_services_list = role['ServicesDefault']
180 if sorted(env_services_list) != sorted(roles_services_list):
181 print('ERROR: ComputeServices in %s is different from '
182 'ServicesDefault in roles/Compute.yaml' % env_filename)
187 def validate_hci_computehci_role(hci_role_filename, hci_role_tpl):
188 compute_role_filename = os.path.join(os.path.dirname(hci_role_filename),
190 compute_role_tpl = yaml.load(open(compute_role_filename).read())
191 compute_role_services = compute_role_tpl[0]['ServicesDefault']
192 for role in hci_role_tpl:
193 if role['name'] == 'ComputeHCI':
194 hci_role_services = role['ServicesDefault']
195 hci_role_services.remove('OS::TripleO::Services::CephOSD')
196 if sorted(hci_role_services) != sorted(compute_role_services):
197 print('ERROR: ServicesDefault in %s is different from'
198 'ServicesDefault in roles/Compute.yaml' % hci_role_filename)
203 def search(item, check_item, check_key):
206 elif isinstance(item, list):
208 if search(i, check_item, check_key):
210 elif isinstance(item, dict):
211 for k in item.keys():
212 if check_key(k, item[k]):
214 elif search(item[k], check_item, check_key):
219 def validate_mysql_connection(settings):
220 no_op = lambda *args: False
223 def mysql_protocol(items):
224 return items == ['EndpointMap', 'MysqlInternal', 'protocol']
226 def client_bind_address(item):
227 return 'read_default_file' in item and \
228 'read_default_group' in item
230 def validate_mysql_uri(key, items):
231 # Only consider a connection if it targets mysql
232 if key.endswith('connection') and \
233 search(items, mysql_protocol, no_op):
234 # Assume the "bind_address" option is one of
235 # the token that made up the uri
236 if not search(items, client_bind_address, no_op):
240 search(settings, no_op, validate_mysql_uri)
241 return error_status[0]
244 def validate_docker_service_mysql_usage(filename, tpl):
245 no_op = lambda *args: False
248 def match_included_res(item):
249 is_config_setting = isinstance(item, list) and len(item) > 1 and \
250 item[1:] == ['role_data', 'config_settings']
251 if is_config_setting:
252 included_res.append(item[0])
253 return is_config_setting
255 def match_use_mysql_protocol(items):
256 return items == ['EndpointMap', 'MysqlInternal', 'protocol']
260 def read_all(incfile, inctpl):
261 # search for included content
262 content = inctpl['outputs']['role_data']['value'].get('config_settings',{})
263 all_content.append(content)
265 if search(content, match_included_res, no_op):
266 files = [inctpl['resources'][x]['type'] for x in included_res]
267 # parse included content
268 for r, f in zip(included_res, files):
269 # disregard class names, only consider file names
272 newfile = os.path.normpath(os.path.dirname(incfile)+'/'+f)
273 newtmp = yaml.load(open(newfile).read())
274 read_all(newfile, newtmp)
276 read_all(filename, tpl)
277 if search(all_content, match_use_mysql_protocol, no_op):
278 # ensure this service includes the mysqlclient service
279 resources = tpl['resources']
280 mysqlclient = [x for x in resources
281 if resources[x]['type'].endswith('mysql-client.yaml')]
282 if len(mysqlclient) == 0:
283 print("ERROR: containerized service %s uses mysql but "
284 "resource mysql-client.yaml is not used"
288 # and that mysql::client puppet module is included in puppet-config
289 match_mysqlclient = \
290 lambda x: x == [mysqlclient[0], 'role_data', 'step_config']
291 role_data = tpl['outputs']['role_data']
292 puppet_config = role_data['value']['puppet_config']['step_config']
293 if not search(puppet_config, match_mysqlclient, no_op):
294 print("ERROR: containerized service %s uses mysql but "
295 "puppet_config section does not include "
296 "::tripleo::profile::base::database::mysql::client"
303 def validate_docker_service(filename, tpl):
304 if 'outputs' in tpl and 'role_data' in tpl['outputs']:
305 if 'value' not in tpl['outputs']['role_data']:
306 print('ERROR: invalid role_data for filename: %s'
309 role_data = tpl['outputs']['role_data']['value']
311 for section_name in REQUIRED_DOCKER_SECTIONS:
312 if section_name not in role_data:
313 print('ERROR: %s is required in role_data for %s.'
314 % (section_name, filename))
317 for section_name in role_data.keys():
318 if section_name in REQUIRED_DOCKER_SECTIONS:
321 if section_name in OPTIONAL_DOCKER_SECTIONS:
323 elif section_name in OPTIONAL_SECTIONS:
326 print('ERROR: %s is extra in role_data for %s.'
327 % (section_name, filename))
330 if 'puppet_config' in role_data:
331 if validate_docker_service_mysql_usage(filename, tpl):
332 print('ERROR: could not validate use of mysql service for %s.'
335 puppet_config = role_data['puppet_config']
336 for key in puppet_config:
337 if key in REQUIRED_DOCKER_PUPPET_CONFIG_SECTIONS:
340 if key in OPTIONAL_DOCKER_PUPPET_CONFIG_SECTIONS:
343 print('ERROR: %s should not be in puppet_config section.'
346 for key in REQUIRED_DOCKER_PUPPET_CONFIG_SECTIONS:
347 if key not in puppet_config:
348 print('ERROR: %s is required in puppet_config for %s.'
352 config_volume = puppet_config.get('config_volume')
353 expected_config_image_parameter = "Docker%sConfigImage" % to_camel_case(config_volume)
354 if config_volume and not expected_config_image_parameter in tpl.get('parameters', []):
355 print('ERROR: Missing %s heat parameter for %s config_volume.'
356 % (expected_config_image_parameter, config_volume))
359 if 'docker_config' in role_data:
360 docker_config = role_data['docker_config']
361 for _, step in docker_config.items():
362 if not isinstance(step, dict):
363 # NOTE(mandre) this skips everything that is not a dict
364 # so we may ignore some containers definitions if they
365 # are in a map_merge for example
367 for _, container in step.items():
368 if not isinstance(container, dict):
370 command = container.get('command', '')
371 if isinstance(command, list):
372 command = ' '.join(map(str, command))
373 if 'bootstrap_host_exec' in command \
374 and container.get('user') != 'root':
375 print('ERROR: bootstrap_host_exec needs to run as the root user.')
378 if 'parameters' in tpl:
379 for param in required_params:
380 if param not in tpl['parameters']:
381 print('ERROR: parameter %s is required for %s.'
387 def validate_service(filename, tpl):
388 if 'outputs' in tpl and 'role_data' in tpl['outputs']:
389 if 'value' not in tpl['outputs']['role_data']:
390 print('ERROR: invalid role_data for filename: %s'
393 role_data = tpl['outputs']['role_data']['value']
394 if 'service_name' not in role_data:
395 print('ERROR: service_name is required in role_data for %s.'
398 # service_name must match the filename, but with an underscore
399 if (role_data['service_name'] !=
400 os.path.basename(filename).split('.')[0].replace("-", "_")):
401 print('ERROR: service_name should match file name for service: %s.'
404 # if service connects to mysql, the uri should use option
405 # bind_address to avoid issues with VIP failover
406 if 'config_settings' in role_data and \
407 validate_mysql_connection(role_data['config_settings']):
408 print('ERROR: mysql connection uri should use option bind_address')
410 if 'parameters' in tpl:
411 for param in required_params:
412 if param not in tpl['parameters']:
413 print('ERROR: parameter %s is required for %s.'
419 def validate(filename, param_map):
420 """Validate a Heat template
422 :param filename: The path to the file to validate
423 :param param_map: A dict which will be populated with the details of the
424 parameters in the template. The dict will have the
428 {'filename': ./file1.yaml,
429 'data': {'description': '',
434 {'filename': ./file2.yaml,
435 'data': {'description': '',
443 print('Validating %s' % filename)
446 tpl = yaml.load(open(filename).read())
448 # The template alias version should be used instead a date, this validation
449 # will be applied to all templates not just for those in the services folder.
450 if 'heat_template_version' in tpl and not str(tpl['heat_template_version']).isalpha():
451 print('ERROR: heat_template_version needs to be the release alias not a date: %s'
455 if VALIDATE_PUPPET_OVERRIDE.get(filename, False) or (
456 filename.startswith('./puppet/services/') and
457 VALIDATE_PUPPET_OVERRIDE.get(filename, True)):
458 retval = validate_service(filename, tpl)
460 if VALIDATE_DOCKER_OVERRIDE.get(filename, False) or (
461 filename.startswith('./docker/services/') and
462 VALIDATE_DOCKER_OVERRIDE.get(filename, True)):
463 retval = validate_docker_service(filename, tpl)
465 if filename.endswith('hyperconverged-ceph.yaml'):
466 retval = validate_hci_compute_services_default(filename, tpl)
468 if filename.startswith('./roles/ComputeHCI.yaml'):
469 retval = validate_hci_computehci_role(filename, tpl)
472 print(traceback.format_exc())
474 # yaml is OK, now walk the parameters and output a warning for unused ones
475 if 'heat_template_version' in tpl:
476 for p, data in tpl.get('parameters', {}).items():
477 definition = {'data': data, 'filename': filename}
478 param_map.setdefault(p, []).append(definition)
479 if p in required_params:
482 in_resources = str_p in str(tpl.get('resources', {}))
483 in_outputs = str_p in str(tpl.get('outputs', {}))
484 if not in_resources and not in_outputs:
485 print('Warning: parameter %s in template %s '
486 'appears to be unused' % (p, filename))
490 if len(sys.argv) < 2:
493 path_args = sys.argv[1:]
496 base_endpoint_map = None
497 env_endpoint_maps = list()
500 for base_path in path_args:
501 if os.path.isdir(base_path):
502 for subdir, dirs, files in os.walk(base_path):
506 if f.endswith('.yaml') and not f.endswith('.j2.yaml'):
507 file_path = os.path.join(subdir, f)
508 failed = validate(file_path, param_map)
510 failed_files.append(file_path)
512 if f == ENDPOINT_MAP_FILE:
513 base_endpoint_map = get_base_endpoint_map(file_path)
514 if f in envs_containing_endpoint_map:
515 env_endpoint_map = get_endpoint_map_from_env(file_path)
517 env_endpoint_maps.append(env_endpoint_map)
518 elif os.path.isfile(base_path) and base_path.endswith('.yaml'):
519 failed = validate(base_path, param_map)
521 failed_files.append(base_path)
524 print('Unexpected argument %s' % base_path)
527 if base_endpoint_map and \
528 len(env_endpoint_maps) == len(envs_containing_endpoint_map):
529 for env_endpoint_map in env_endpoint_maps:
530 matches = validate_endpoint_map(base_endpoint_map,
531 env_endpoint_map['map'])
533 print("ERROR: %s needs to be updated to match changes in base "
534 "endpoint map" % env_endpoint_map['file'])
535 failed_files.append(env_endpoint_map['file'])
538 print("%s matches base endpoint map" % env_endpoint_map['file'])
540 print("ERROR: Did not find expected number of environments containing the "
541 "EndpointMap parameter. If you meant to add or remove one of these "
542 "environments then you also need to update this tool.")
543 if not base_endpoint_map:
544 failed_files.append(ENDPOINT_MAP_FILE)
545 if len(env_endpoint_maps) != len(envs_containing_endpoint_map):
546 matched_files = set(os.path.basename(matched_env_file['file'])
547 for matched_env_file in env_endpoint_maps)
548 failed_files.extend(set(envs_containing_endpoint_map) - matched_files)
551 # Validate that duplicate parameters defined in multiple files all have the
554 for p, defs in param_map.items():
555 # Nothing to validate if the parameter is only defined once
558 check_data = [d['data'] for d in defs]
559 # Override excluded fields so they don't affect the result
560 exclusions = PARAMETER_DEFINITION_EXCLUSIONS.get(p, [])
562 for field in exclusions:
563 ex_dict[field] = 'IGNORED'
566 # If all items in the list are not == the first, then the check fails
567 if check_data.count(check_data[0]) != len(check_data):
570 failed_files.extend([d['filename'] for d in defs])
571 print('Mismatched parameter definitions found for "%s"' % p)
572 print('Definitions found:')
574 print(' %s:\n %s' % (d['filename'], d['data']))
575 print('Mismatched parameter definitions: %d' % mismatch_count)
578 print('Validation failed on:')
579 for f in failed_files:
582 print('Validation successful!')