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