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 = ['service_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 'service_config_settings', 'host_prep_tasks',
39 'metadata_settings', 'kolla_config']
40 REQUIRED_DOCKER_PUPPET_CONFIG_SECTIONS = ['config_volume', 'step_config',
42 OPTIONAL_DOCKER_PUPPET_CONFIG_SECTIONS = [ 'puppet_tags', 'volumes' ]
43 # Mapping of parameter names to a list of the fields we should _not_ enforce
44 # consistency across files on. This should only contain parameters whose
45 # definition we cannot change for backwards compatibility reasons. New
46 # parameters to the templates should not be added to this list.
47 PARAMETER_DEFINITION_EXCLUSIONS = {'ManagementNetCidr': ['default'],
48 'ManagementAllocationPools': ['default'],
49 'ExternalNetCidr': ['default'],
50 'ExternalAllocationPools': ['default'],
51 'StorageNetCidr': ['default'],
52 'StorageAllocationPools': ['default'],
53 'StorageMgmtNetCidr': ['default'],
54 'StorageMgmtAllocationPools': ['default'],
55 'TenantNetCidr': ['default'],
56 'TenantAllocationPools': ['default'],
57 'InternalApiNetCidr': ['default'],
58 'InternalApiAllocationPools': ['default'],
59 'UpdateIdentifier': ['description'],
60 'key_name': ['default'],
61 # There's one template that defines this
62 # differently, and I'm not sure if we can
64 'EC2MetadataIp': ['default'],
65 # Same as EC2MetadataIp
66 'ControlPlaneDefaultRoute': ['default'],
67 # TODO(bnemec): Address these existing
69 'ServiceNetMap': ['description', 'default'],
70 'network': ['default'],
71 'ControlPlaneIP': ['default',
73 'ControlPlaneIp': ['default',
75 'NeutronBigswitchLLDPEnabled': ['default'],
76 'NeutronWorkers': ['description'],
77 'ServerMetadata': ['description'],
78 'server': ['description'],
79 'servers': ['description'],
80 'ExtraConfig': ['description'],
81 'DefaultPasswords': ['description',
83 'BondInterfaceOvsOptions': ['description',
86 'KeyName': ['constraints'],
87 'OVNSouthboundServerPort': ['description'],
88 'ExternalInterfaceDefaultRoute':
89 ['description', 'default'],
90 'IPPool': ['description'],
91 'SSLCertificate': ['description',
94 'HostCpusList': ['default', 'constraints'],
95 'NodeIndex': ['description'],
96 'name': ['description', 'default'],
97 'image': ['description', 'default'],
98 'NeutronBigswitchAgentEnabled': ['default'],
99 'EndpointMap': ['description', 'default'],
100 'DockerManilaConfigImage': ['description',
102 'replacement_policy': ['default'],
103 'CloudDomain': ['description', 'default'],
104 'EnableLoadBalancer': ['description'],
105 'ControllerExtraConfig': ['description'],
106 'NovaComputeExtraConfig': ['description'],
107 'controllerExtraConfig': ['description'],
108 'DockerSwiftConfigImage': ['default'],
111 PREFERRED_CAMEL_CASE = {
113 'haproxy': 'HAProxy',
118 print('Usage %s <yaml file or directory>' % sys.argv[0])
122 def to_camel_case(string):
123 return PREFERRED_CAMEL_CASE.get(string, ''.join(s.capitalize() or '_' for
124 s in string.split('_')))
127 def get_base_endpoint_map(filename):
129 tpl = yaml.load(open(filename).read())
130 return tpl['parameters']['EndpointMap']['default']
132 print(traceback.format_exc())
136 def get_endpoint_map_from_env(filename):
138 tpl = yaml.load(open(filename).read())
141 'map': tpl['parameter_defaults']['EndpointMap']
144 print(traceback.format_exc())
148 def validate_endpoint_map(base_map, env_map):
149 return sorted(base_map.keys()) == sorted(env_map.keys())
152 def validate_hci_compute_services_default(env_filename, env_tpl):
153 env_services_list = env_tpl['parameter_defaults']['ComputeServices']
154 env_services_list.remove('OS::TripleO::Services::CephOSD')
155 roles_filename = os.path.join(os.path.dirname(env_filename),
156 '../roles/Compute.yaml')
157 roles_tpl = yaml.load(open(roles_filename).read())
158 for role in roles_tpl:
159 if role['name'] == 'Compute':
160 roles_services_list = role['ServicesDefault']
161 if sorted(env_services_list) != sorted(roles_services_list):
162 print('ERROR: ComputeServices in %s is different from '
163 'ServicesDefault in roles/Compute.yaml' % env_filename)
168 def validate_hci_computehci_role(hci_role_filename, hci_role_tpl):
169 compute_role_filename = os.path.join(os.path.dirname(hci_role_filename),
171 compute_role_tpl = yaml.load(open(compute_role_filename).read())
172 compute_role_services = compute_role_tpl[0]['ServicesDefault']
173 for role in hci_role_tpl:
174 if role['name'] == 'ComputeHCI':
175 hci_role_services = role['ServicesDefault']
176 hci_role_services.remove('OS::TripleO::Services::CephOSD')
177 if sorted(hci_role_services) != sorted(compute_role_services):
178 print('ERROR: ServicesDefault in %s is different from'
179 'ServicesDefault in roles/Compute.yaml' % hci_role_filename)
184 def search(item, check_item, check_key):
187 elif isinstance(item, list):
189 if search(i, check_item, check_key):
191 elif isinstance(item, dict):
192 for k in item.keys():
193 if check_key(k, item[k]):
195 elif search(item[k], check_item, check_key):
200 def validate_mysql_connection(settings):
201 no_op = lambda *args: False
204 def mysql_protocol(items):
205 return items == ['EndpointMap', 'MysqlInternal', 'protocol']
207 def client_bind_address(item):
208 return 'read_default_file' in item and \
209 'read_default_group' in item
211 def validate_mysql_uri(key, items):
212 # Only consider a connection if it targets mysql
213 if key.endswith('connection') and \
214 search(items, mysql_protocol, no_op):
215 # Assume the "bind_address" option is one of
216 # the token that made up the uri
217 if not search(items, client_bind_address, no_op):
221 search(settings, no_op, validate_mysql_uri)
222 return error_status[0]
225 def validate_docker_service_mysql_usage(filename, tpl):
226 no_op = lambda *args: False
229 def match_included_res(item):
230 is_config_setting = isinstance(item, list) and len(item) > 1 and \
231 item[1:] == ['role_data', 'config_settings']
232 if is_config_setting:
233 included_res.append(item[0])
234 return is_config_setting
236 def match_use_mysql_protocol(items):
237 return items == ['EndpointMap', 'MysqlInternal', 'protocol']
241 def read_all(incfile, inctpl):
242 # search for included content
243 content = inctpl['outputs']['role_data']['value'].get('config_settings',{})
244 all_content.append(content)
246 if search(content, match_included_res, no_op):
247 files = [inctpl['resources'][x]['type'] for x in included_res]
248 # parse included content
249 for r, f in zip(included_res, files):
250 # disregard class names, only consider file names
253 newfile = os.path.normpath(os.path.dirname(incfile)+'/'+f)
254 newtmp = yaml.load(open(newfile).read())
255 read_all(newfile, newtmp)
257 read_all(filename, tpl)
258 if search(all_content, match_use_mysql_protocol, no_op):
259 # ensure this service includes the mysqlclient service
260 resources = tpl['resources']
261 mysqlclient = [x for x in resources
262 if resources[x]['type'].endswith('mysql-client.yaml')]
263 if len(mysqlclient) == 0:
264 print("ERROR: containerized service %s uses mysql but "
265 "resource mysql-client.yaml is not used"
269 # and that mysql::client puppet module is included in puppet-config
270 match_mysqlclient = \
271 lambda x: x == [mysqlclient[0], 'role_data', 'step_config']
272 role_data = tpl['outputs']['role_data']
273 puppet_config = role_data['value']['puppet_config']['step_config']
274 if not search(puppet_config, match_mysqlclient, no_op):
275 print("ERROR: containerized service %s uses mysql but "
276 "puppet_config section does not include "
277 "::tripleo::profile::base::database::mysql::client"
284 def validate_docker_service(filename, tpl):
285 if 'outputs' in tpl and 'role_data' in tpl['outputs']:
286 if 'value' not in tpl['outputs']['role_data']:
287 print('ERROR: invalid role_data for filename: %s'
290 role_data = tpl['outputs']['role_data']['value']
292 for section_name in REQUIRED_DOCKER_SECTIONS:
293 if section_name not in role_data:
294 print('ERROR: %s is required in role_data for %s.'
295 % (section_name, filename))
298 for section_name in role_data.keys():
299 if section_name in REQUIRED_DOCKER_SECTIONS:
302 if section_name in OPTIONAL_DOCKER_SECTIONS:
304 elif section_name in OPTIONAL_SECTIONS:
307 print('ERROR: %s is extra in role_data for %s.'
308 % (section_name, filename))
311 if 'puppet_config' in role_data:
312 if validate_docker_service_mysql_usage(filename, tpl):
313 print('ERROR: could not validate use of mysql service for %s.'
316 puppet_config = role_data['puppet_config']
317 for key in puppet_config:
318 if key in REQUIRED_DOCKER_PUPPET_CONFIG_SECTIONS:
321 if key in OPTIONAL_DOCKER_PUPPET_CONFIG_SECTIONS:
324 print('ERROR: %s should not be in puppet_config section.'
327 for key in REQUIRED_DOCKER_PUPPET_CONFIG_SECTIONS:
328 if key not in puppet_config:
329 print('ERROR: %s is required in puppet_config for %s.'
333 config_volume = puppet_config.get('config_volume')
334 expected_config_image_parameter = "Docker%sConfigImage" % to_camel_case(config_volume)
335 if config_volume and not expected_config_image_parameter in tpl.get('parameters', []):
336 print('ERROR: Missing %s heat parameter for %s config_volume.'
337 % (expected_config_image_parameter, config_volume))
340 if 'docker_config' in role_data:
341 docker_config = role_data['docker_config']
342 for _, step in docker_config.items():
343 if not isinstance(step, dict):
344 # NOTE(mandre) this skips everything that is not a dict
345 # so we may ignore some containers definitions if they
346 # are in a map_merge for example
348 for _, container in step.items():
349 if not isinstance(container, dict):
351 command = container.get('command', '')
352 if isinstance(command, list):
353 command = ' '.join(map(str, command))
354 if 'bootstrap_host_exec' in command \
355 and container.get('user') != 'root':
356 print('ERROR: bootstrap_host_exec needs to run as the root user.')
359 if 'parameters' in tpl:
360 for param in required_params:
361 if param not in tpl['parameters']:
362 print('ERROR: parameter %s is required for %s.'
368 def validate_service(filename, tpl):
369 if 'outputs' in tpl and 'role_data' in tpl['outputs']:
370 if 'value' not in tpl['outputs']['role_data']:
371 print('ERROR: invalid role_data for filename: %s'
374 role_data = tpl['outputs']['role_data']['value']
375 if 'service_name' not in role_data:
376 print('ERROR: service_name is required in role_data for %s.'
379 # service_name must match the filename, but with an underscore
380 if (role_data['service_name'] !=
381 os.path.basename(filename).split('.')[0].replace("-", "_")):
382 print('ERROR: service_name should match file name for service: %s.'
385 # if service connects to mysql, the uri should use option
386 # bind_address to avoid issues with VIP failover
387 if 'config_settings' in role_data and \
388 validate_mysql_connection(role_data['config_settings']):
389 print('ERROR: mysql connection uri should use option bind_address')
391 if 'parameters' in tpl:
392 for param in required_params:
393 if param not in tpl['parameters']:
394 print('ERROR: parameter %s is required for %s.'
400 def validate(filename, param_map):
401 """Validate a Heat template
403 :param filename: The path to the file to validate
404 :param param_map: A dict which will be populated with the details of the
405 parameters in the template. The dict will have the
409 {'filename': ./file1.yaml,
410 'data': {'description': '',
415 {'filename': ./file2.yaml,
416 'data': {'description': '',
424 print('Validating %s' % filename)
427 tpl = yaml.load(open(filename).read())
429 # The template alias version should be used instead a date, this validation
430 # will be applied to all templates not just for those in the services folder.
431 if 'heat_template_version' in tpl and not str(tpl['heat_template_version']).isalpha():
432 print('ERROR: heat_template_version needs to be the release alias not a date: %s'
436 # qdr aliases rabbitmq service to provide alternative messaging backend
437 if (filename.startswith('./puppet/services/') and
438 filename not in ['./puppet/services/qdr.yaml']):
439 retval = validate_service(filename, tpl)
441 if filename.startswith('./docker/services/'):
442 retval = validate_docker_service(filename, tpl)
444 if filename.endswith('hyperconverged-ceph.yaml'):
445 retval = validate_hci_compute_services_default(filename, tpl)
447 if filename.startswith('./roles/ComputeHCI.yaml'):
448 retval = validate_hci_computehci_role(filename, tpl)
451 print(traceback.format_exc())
453 # yaml is OK, now walk the parameters and output a warning for unused ones
454 if 'heat_template_version' in tpl:
455 for p, data in tpl.get('parameters', {}).items():
456 definition = {'data': data, 'filename': filename}
457 param_map.setdefault(p, []).append(definition)
458 if p in required_params:
461 in_resources = str_p in str(tpl.get('resources', {}))
462 in_outputs = str_p in str(tpl.get('outputs', {}))
463 if not in_resources and not in_outputs:
464 print('Warning: parameter %s in template %s '
465 'appears to be unused' % (p, filename))
469 if len(sys.argv) < 2:
472 path_args = sys.argv[1:]
475 base_endpoint_map = None
476 env_endpoint_maps = list()
479 for base_path in path_args:
480 if os.path.isdir(base_path):
481 for subdir, dirs, files in os.walk(base_path):
485 if f.endswith('.yaml') and not f.endswith('.j2.yaml'):
486 file_path = os.path.join(subdir, f)
487 failed = validate(file_path, param_map)
489 failed_files.append(file_path)
491 if f == ENDPOINT_MAP_FILE:
492 base_endpoint_map = get_base_endpoint_map(file_path)
493 if f in envs_containing_endpoint_map:
494 env_endpoint_map = get_endpoint_map_from_env(file_path)
496 env_endpoint_maps.append(env_endpoint_map)
497 elif os.path.isfile(base_path) and base_path.endswith('.yaml'):
498 failed = validate(base_path, param_map)
500 failed_files.append(base_path)
503 print('Unexpected argument %s' % base_path)
506 if base_endpoint_map and \
507 len(env_endpoint_maps) == len(envs_containing_endpoint_map):
508 for env_endpoint_map in env_endpoint_maps:
509 matches = validate_endpoint_map(base_endpoint_map,
510 env_endpoint_map['map'])
512 print("ERROR: %s needs to be updated to match changes in base "
513 "endpoint map" % env_endpoint_map['file'])
514 failed_files.append(env_endpoint_map['file'])
517 print("%s matches base endpoint map" % env_endpoint_map['file'])
519 print("ERROR: Did not find expected number of environments containing the "
520 "EndpointMap parameter. If you meant to add or remove one of these "
521 "environments then you also need to update this tool.")
522 if not base_endpoint_map:
523 failed_files.append(ENDPOINT_MAP_FILE)
524 if len(env_endpoint_maps) != len(envs_containing_endpoint_map):
525 matched_files = set(os.path.basename(matched_env_file['file'])
526 for matched_env_file in env_endpoint_maps)
527 failed_files.extend(set(envs_containing_endpoint_map) - matched_files)
530 # Validate that duplicate parameters defined in multiple files all have the
533 for p, defs in param_map.items():
534 # Nothing to validate if the parameter is only defined once
537 check_data = [d['data'] for d in defs]
538 # Override excluded fields so they don't affect the result
539 exclusions = PARAMETER_DEFINITION_EXCLUSIONS.get(p, [])
541 for field in exclusions:
542 ex_dict[field] = 'IGNORED'
545 # If all items in the list are not == the first, then the check fails
546 if check_data.count(check_data[0]) != len(check_data):
549 failed_files.extend([d['filename'] for d in defs])
550 print('Mismatched parameter definitions found for "%s"' % p)
551 print('Definitions found:')
553 print(' %s:\n %s' % (d['filename'], d['data']))
554 print('Mismatched parameter definitions: %d' % mismatch_count)
557 print('Validation failed on:')
558 for f in failed_files:
561 print('Validation successful!')