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