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