76f856dbef064dea7f3486d2539f6108b18ba527
[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 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',
43                                           'config_image']
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',
50                                                  'type',
51                                                  'default'],
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
68                                    # safely change it.
69                                    'EC2MetadataIp': ['default'],
70                                    # Same as EC2MetadataIp
71                                    'ControlPlaneDefaultRoute': ['default'],
72                                    # TODO(bnemec): Address these existing
73                                    # inconsistencies.
74                                    'ServiceNetMap': ['description', 'default'],
75                                    'network': ['default'],
76                                    'ControlPlaneIP': ['default',
77                                                       'description'],
78                                    'ControlPlaneIp': ['default',
79                                                       'description'],
80                                    'NeutronBigswitchLLDPEnabled': ['default'],
81                                    'NeutronWorkers': ['description'],
82                                    'ServerMetadata': ['description'],
83                                    'server': ['description'],
84                                    'servers': ['description'],
85                                    'ExtraConfig': ['description'],
86                                    'DefaultPasswords': ['description',
87                                                         'default'],
88                                    'BondInterfaceOvsOptions': ['description',
89                                                                'default',
90                                                                'constraints'],
91                                    'KeyName': ['constraints'],
92                                    'OVNSouthboundServerPort': ['description'],
93                                    'ExternalInterfaceDefaultRoute':
94                                        ['description', 'default'],
95                                    'ManagementInterfaceDefaultRoute':
96                                        ['description', 'default'],
97                                    'IPPool': ['description'],
98                                    'SSLCertificate': ['description',
99                                                       'default',
100                                                       'hidden'],
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',
108                                                                'default'],
109                                    'replacement_policy': ['default'],
110                                    'CloudDomain': ['description', 'default'],
111                                    'EnableLoadBalancer': ['description'],
112                                    'ControllerExtraConfig': ['description'],
113                                    'NovaComputeExtraConfig': ['description'],
114                                    'controllerExtraConfig': ['description'],
115                                    'DockerSwiftConfigImage': ['default']
116                                    }
117
118 PREFERRED_CAMEL_CASE = {
119     'ec2api': 'Ec2Api',
120     'haproxy': 'HAProxy',
121 }
122
123 # Overrides for docker/puppet validation
124 # <filename>: True explicitly enables validation
125 # <filename>: False explicitly disables validation
126 #
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,
134 }
135 VALIDATE_DOCKER_OVERRIDE = {
136   # docker/service/sshd.yaml is a variation of the puppet sshd service
137   './docker/services/sshd.yaml': False,
138 }
139
140 def exit_usage():
141     print('Usage %s <yaml file or directory>' % sys.argv[0])
142     sys.exit(1)
143
144
145 def to_camel_case(string):
146     return PREFERRED_CAMEL_CASE.get(string, ''.join(s.capitalize() or '_' for
147                                                     s in string.split('_')))
148
149
150 def get_base_endpoint_map(filename):
151     try:
152         tpl = yaml.load(open(filename).read())
153         return tpl['parameters']['EndpointMap']['default']
154     except Exception:
155         print(traceback.format_exc())
156     return None
157
158
159 def get_endpoint_map_from_env(filename):
160     try:
161         tpl = yaml.load(open(filename).read())
162         return {
163             'file': filename,
164             'map': tpl['parameter_defaults']['EndpointMap']
165         }
166     except Exception:
167         print(traceback.format_exc())
168     return None
169
170
171 def validate_endpoint_map(base_map, env_map):
172     return sorted(base_map.keys()) == sorted(env_map.keys())
173
174
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)
187                 return 1
188     return 0
189
190
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),
193                                          './Compute.yaml')
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)
203                 return 1
204     return 0
205
206
207 def search(item, check_item, check_key):
208     if check_item(item):
209         return True
210     elif isinstance(item, list):
211         for i in item:
212             if search(i, check_item, check_key):
213                 return True
214     elif isinstance(item, dict):
215         for k in item.keys():
216             if check_key(k, item[k]):
217                 return True
218             elif search(item[k], check_item, check_key):
219                 return True
220     return False
221
222
223 def validate_mysql_connection(settings):
224     no_op = lambda *args: False
225     error_status = [0]
226
227     def mysql_protocol(items):
228         return items == ['EndpointMap', 'MysqlInternal', 'protocol']
229
230     def client_bind_address(item):
231         return 'read_default_file' in item and \
232                'read_default_group' in item
233
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):
241                 error_status[0] = 1
242         return False
243
244     search(settings, no_op, validate_mysql_uri)
245     return error_status[0]
246
247
248 def validate_docker_service_mysql_usage(filename, tpl):
249     no_op = lambda *args: False
250     included_res = []
251
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
258
259     def match_use_mysql_protocol(items):
260         return items == ['EndpointMap', 'MysqlInternal', 'protocol']
261
262     all_content = []
263
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)
268         included_res[:] = []
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
274                 if 'OS::' in f:
275                     continue
276                 newfile = os.path.normpath(os.path.dirname(incfile)+'/'+f)
277                 newtmp = yaml.load(open(newfile).read())
278                 read_all(newfile, newtmp)
279
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"
289                   % filename)
290             return 1
291
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"
301                   % filename)
302             return 1
303
304     return 0
305
306
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'
311                   % filename)
312             return 1
313         role_data = tpl['outputs']['role_data']['value']
314
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))
319                 return 1
320
321         for section_name in role_data.keys():
322             if section_name in REQUIRED_DOCKER_SECTIONS:
323                 continue
324             else:
325                 if section_name in OPTIONAL_DOCKER_SECTIONS:
326                     continue
327                 elif section_name in OPTIONAL_SECTIONS:
328                     continue
329                 else:
330                     print('ERROR: %s is extra in role_data for %s.'
331                           % (section_name, filename))
332                     return 1
333
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.'
337                       % filename)
338                 return 1
339             puppet_config = role_data['puppet_config']
340             for key in puppet_config:
341                 if key in REQUIRED_DOCKER_PUPPET_CONFIG_SECTIONS:
342                     continue
343                 else:
344                     if key in OPTIONAL_DOCKER_PUPPET_CONFIG_SECTIONS:
345                         continue
346                     else:
347                       print('ERROR: %s should not be in puppet_config section.'
348                             % key)
349                       return 1
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.'
353                         % (key, filename))
354                   return 1
355
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))
361                 return 1
362
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
370                     continue
371                 for _, container in step.items():
372                     if not isinstance(container, dict):
373                         continue
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.')
380                       return 1
381
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.'
386                       % (param, filename))
387                 return 1
388     return 0
389
390
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'
395                   % filename)
396             return 1
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.'
400                   % filename)
401             return 1
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.'
406                   % filename)
407             return 1
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')
413             return 1
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.'
418                       % (param, filename))
419                 return 1
420     return 0
421
422
423 def validate(filename, param_map):
424     """Validate a Heat template
425
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
429                       following structure:
430
431                           {'ParameterName': [
432                                {'filename': ./file1.yaml,
433                                 'data': {'description': '',
434                                          'type': string,
435                                          'default': '',
436                                          ...}
437                                 },
438                                {'filename': ./file2.yaml,
439                                 'data': {'description': '',
440                                          'type': string,
441                                          'default': '',
442                                          ...}
443                                 },
444                                 ...
445                            ]}
446     """
447     print('Validating %s' % filename)
448     retval = 0
449     try:
450         tpl = yaml.load(open(filename).read())
451
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'
456                   % filename)
457             return 1
458
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)
463
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)
468
469         if filename.endswith('hyperconverged-ceph.yaml'):
470             retval = validate_hci_compute_services_default(filename, tpl)
471
472         if filename.startswith('./roles/ComputeHCI.yaml'):
473             retval = validate_hci_computehci_role(filename, tpl)
474
475     except Exception:
476         print(traceback.format_exc())
477         return 1
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:
484                 continue
485             str_p = '\'%s\'' % p
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))
491
492     return retval
493
494 if len(sys.argv) < 2:
495     exit_usage()
496
497 path_args = sys.argv[1:]
498 exit_val = 0
499 failed_files = []
500 base_endpoint_map = None
501 env_endpoint_maps = list()
502 param_map = {}
503
504 for base_path in path_args:
505     if os.path.isdir(base_path):
506         for subdir, dirs, files in os.walk(base_path):
507             if '.tox' in dirs:
508                 dirs.remove('.tox')
509             for f in files:
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)
513                     if failed:
514                         failed_files.append(file_path)
515                     exit_val |= failed
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)
520                         if env_endpoint_map:
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)
524         if failed:
525             failed_files.append(base_path)
526         exit_val |= failed
527     else:
528         print('Unexpected argument %s' % base_path)
529         exit_usage()
530
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'])
536         if not matches:
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'])
540             exit_val |= 1
541         else:
542             print("%s matches base endpoint map" % env_endpoint_map['file'])
543 else:
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)
553     exit_val |= 1
554
555 # Validate that duplicate parameters defined in multiple files all have the
556 # same definition.
557 mismatch_count = 0
558 for p, defs in param_map.items():
559     # Nothing to validate if the parameter is only defined once
560     if len(defs) == 1:
561         continue
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, [])
565     ex_dict = {}
566     for field in exclusions:
567         ex_dict[field] = 'IGNORED'
568     for d in check_data:
569         d.update(ex_dict)
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):
572         mismatch_count += 1
573         exit_val |= 1
574         failed_files.extend([d['filename'] for d in defs])
575         print('Mismatched parameter definitions found for "%s"' % p)
576         print('Definitions found:')
577         for d in defs:
578             print('  %s:\n    %s' % (d['filename'], d['data']))
579 print('Mismatched parameter definitions: %d' % mismatch_count)
580
581 if failed_files:
582     print('Validation failed on:')
583     for f in failed_files:
584         print(f)
585 else:
586     print('Validation successful!')
587 sys.exit(exit_val)