Merge "Render isolated network templates using jinja2"
[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                                    'key_name': ['default'],
62                                    # TODO(bnemec): Address these existing
63                                    # inconsistencies.
64                                    'NeutronMetadataProxySharedSecret': [
65                                        'description', 'hidden'],
66                                    'ServiceNetMap': ['description', 'default'],
67                                    'EC2MetadataIp': ['default'],
68                                    'network': ['default'],
69                                    'ControlPlaneIP': ['default',
70                                                       'description'],
71                                    'ControlPlaneIp': ['default',
72                                                       'description'],
73                                    'NeutronBigswitchLLDPEnabled': ['default'],
74                                    'NeutronEnableL2Pop': ['description'],
75                                    'NeutronWorkers': ['description'],
76                                    'TenantIpSubnet': ['description'],
77                                    'ExternalNetName': ['description'],
78                                    'ControlPlaneDefaultRoute': ['default'],
79                                    'StorageMgmtNetName': ['description'],
80                                    'ServerMetadata': ['description'],
81                                    'InternalApiIpUri': ['description'],
82                                    'UpgradeLevelNovaCompute': ['default'],
83                                    'StorageMgmtIpUri': ['description'],
84                                    'server': ['description'],
85                                    'servers': ['description'],
86                                    'FixedIPs': ['description'],
87                                    'ExternalIpSubnet': ['description'],
88                                    'NeutronBridgeMappings': ['description'],
89                                    'ExtraConfig': ['description'],
90                                    'InternalApiIpSubnet': ['description'],
91                                    'DefaultPasswords': ['description',
92                                                         'default'],
93                                    'BondInterfaceOvsOptions': ['description',
94                                                                'default',
95                                                                'constraints'],
96                                    'KeyName': ['constraints'],
97                                    'TenantNetName': ['description'],
98                                    'StorageIpSubnet': ['description'],
99                                    'OVNSouthboundServerPort': ['description'],
100                                    'ExternalInterfaceDefaultRoute':
101                                        ['description', 'default'],
102                                    'ExternalIpUri': ['description'],
103                                    'IPPool': ['description'],
104                                    'ControlPlaneNetwork': ['description'],
105                                    'SSLCertificate': ['description',
106                                                       'default',
107                                                       'hidden'],
108                                    'HostCpusList': ['default', 'constraints'],
109                                    'InternalApiAllocationPools': ['default'],
110                                    'NodeIndex': ['description'],
111                                    'name': ['description', 'default'],
112                                    'StorageNetName': ['description'],
113                                    'ManagementNetName': ['description'],
114                                    'NeutronPublicInterface': ['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                                    '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 search(item, check_item, check_key):
210     if check_item(item):
211         return True
212     elif isinstance(item, list):
213         for i in item:
214             if search(i, check_item, check_key):
215                 return True
216     elif isinstance(item, dict):
217         for k in item.keys():
218             if check_key(k, item[k]):
219                 return True
220             elif search(item[k], check_item, check_key):
221                 return True
222     return False
223
224
225 def validate_mysql_connection(settings):
226     no_op = lambda *args: False
227     error_status = [0]
228
229     def mysql_protocol(items):
230         return items == ['EndpointMap', 'MysqlInternal', 'protocol']
231
232     def client_bind_address(item):
233         return 'read_default_file' in item and \
234                'read_default_group' in item
235
236     def validate_mysql_uri(key, items):
237         # Only consider a connection if it targets mysql
238         if key.endswith('connection') and \
239            search(items, mysql_protocol, no_op):
240             # Assume the "bind_address" option is one of
241             # the token that made up the uri
242             if not search(items, client_bind_address, no_op):
243                 error_status[0] = 1
244         return False
245
246     search(settings, no_op, validate_mysql_uri)
247     return error_status[0]
248
249
250 def validate_docker_service_mysql_usage(filename, tpl):
251     no_op = lambda *args: False
252     included_res = []
253
254     def match_included_res(item):
255         is_config_setting = isinstance(item, list) and len(item) > 1 and \
256             item[1:] == ['role_data', 'config_settings']
257         if is_config_setting:
258             included_res.append(item[0])
259         return is_config_setting
260
261     def match_use_mysql_protocol(items):
262         return items == ['EndpointMap', 'MysqlInternal', 'protocol']
263
264     all_content = []
265
266     def read_all(incfile, inctpl):
267         # search for included content
268         content = inctpl['outputs']['role_data']['value'].get('config_settings',{})
269         all_content.append(content)
270         included_res[:] = []
271         if search(content, match_included_res, no_op):
272             files = [inctpl['resources'][x]['type'] for x in included_res]
273             # parse included content
274             for r, f in zip(included_res, files):
275                 # disregard class names, only consider file names
276                 if 'OS::' in f:
277                     continue
278                 newfile = os.path.normpath(os.path.dirname(incfile)+'/'+f)
279                 newtmp = yaml.load(open(newfile).read())
280                 read_all(newfile, newtmp)
281
282     read_all(filename, tpl)
283     if search(all_content, match_use_mysql_protocol, no_op):
284         # ensure this service includes the mysqlclient service
285         resources = tpl['resources']
286         mysqlclient = [x for x in resources
287                        if resources[x]['type'].endswith('mysql-client.yaml')]
288         if len(mysqlclient) == 0:
289             print("ERROR: containerized service %s uses mysql but "
290                   "resource mysql-client.yaml is not used"
291                   % filename)
292             return 1
293
294         # and that mysql::client puppet module is included in puppet-config
295         match_mysqlclient = \
296             lambda x: x == [mysqlclient[0], 'role_data', 'step_config']
297         role_data = tpl['outputs']['role_data']
298         puppet_config = role_data['value']['puppet_config']['step_config']
299         if not search(puppet_config, match_mysqlclient, no_op):
300             print("ERROR: containerized service %s uses mysql but "
301                   "puppet_config section does not include "
302                   "::tripleo::profile::base::database::mysql::client"
303                   % filename)
304             return 1
305
306     return 0
307
308
309 def validate_docker_service(filename, tpl):
310     if 'outputs' in tpl and 'role_data' in tpl['outputs']:
311         if 'value' not in tpl['outputs']['role_data']:
312             print('ERROR: invalid role_data for filename: %s'
313                   % filename)
314             return 1
315         role_data = tpl['outputs']['role_data']['value']
316
317         for section_name in REQUIRED_DOCKER_SECTIONS:
318             if section_name not in role_data:
319                 print('ERROR: %s is required in role_data for %s.'
320                       % (section_name, filename))
321                 return 1
322
323         for section_name in role_data.keys():
324             if section_name in REQUIRED_DOCKER_SECTIONS:
325                 continue
326             else:
327                 if section_name in OPTIONAL_DOCKER_SECTIONS:
328                     continue
329                 elif section_name in OPTIONAL_SECTIONS:
330                     continue
331                 else:
332                     print('ERROR: %s is extra in role_data for %s.'
333                           % (section_name, filename))
334                     return 1
335
336         if 'puppet_config' in role_data:
337             if validate_docker_service_mysql_usage(filename, tpl):
338                 print('ERROR: could not validate use of mysql service for %s.'
339                       % filename)
340                 return 1
341             puppet_config = role_data['puppet_config']
342             for key in puppet_config:
343                 if key in REQUIRED_DOCKER_PUPPET_CONFIG_SECTIONS:
344                     continue
345                 else:
346                     if key in OPTIONAL_DOCKER_PUPPET_CONFIG_SECTIONS:
347                         continue
348                     else:
349                       print('ERROR: %s should not be in puppet_config section.'
350                             % key)
351                       return 1
352             for key in REQUIRED_DOCKER_PUPPET_CONFIG_SECTIONS:
353               if key not in puppet_config:
354                   print('ERROR: %s is required in puppet_config for %s.'
355                         % (key, filename))
356                   return 1
357
358             config_volume = puppet_config.get('config_volume')
359             expected_config_image_parameter = "Docker%sConfigImage" % to_camel_case(config_volume)
360             if config_volume and not expected_config_image_parameter in tpl.get('parameters', []):
361                 print('ERROR: Missing %s heat parameter for %s config_volume.'
362                       % (expected_config_image_parameter, config_volume))
363                 return 1
364
365         if 'docker_config' in role_data:
366             docker_config = role_data['docker_config']
367             for _, step in docker_config.items():
368                 if not isinstance(step, dict):
369                     # NOTE(mandre) this skips everything that is not a dict
370                     # so we may ignore some containers definitions if they
371                     # are in a map_merge for example
372                     continue
373                 for _, container in step.items():
374                     if not isinstance(container, dict):
375                         continue
376                     command = container.get('command', '')
377                     if isinstance(command, list):
378                         command = ' '.join(map(str, command))
379                     if 'bootstrap_host_exec' in command \
380                             and container.get('user') != 'root':
381                       print('ERROR: bootstrap_host_exec needs to run as the root user.')
382                       return 1
383
384     if 'parameters' in tpl:
385         for param in required_params:
386             if param not in tpl['parameters']:
387                 print('ERROR: parameter %s is required for %s.'
388                       % (param, filename))
389                 return 1
390     return 0
391
392
393 def validate_service(filename, tpl):
394     if 'outputs' in tpl and 'role_data' in tpl['outputs']:
395         if 'value' not in tpl['outputs']['role_data']:
396             print('ERROR: invalid role_data for filename: %s'
397                   % filename)
398             return 1
399         role_data = tpl['outputs']['role_data']['value']
400         if 'service_name' not in role_data:
401             print('ERROR: service_name is required in role_data for %s.'
402                   % filename)
403             return 1
404         # service_name must match the filename, but with an underscore
405         if (role_data['service_name'] !=
406                 os.path.basename(filename).split('.')[0].replace("-", "_")):
407             print('ERROR: service_name should match file name for service: %s.'
408                   % filename)
409             return 1
410         # if service connects to mysql, the uri should use option
411         # bind_address to avoid issues with VIP failover
412         if 'config_settings' in role_data and \
413            validate_mysql_connection(role_data['config_settings']):
414             print('ERROR: mysql connection uri should use option bind_address')
415             return 1
416     if 'parameters' in tpl:
417         for param in required_params:
418             if param not in tpl['parameters']:
419                 print('ERROR: parameter %s is required for %s.'
420                       % (param, filename))
421                 return 1
422     return 0
423
424
425 def validate(filename, param_map):
426     """Validate a Heat template
427
428     :param filename: The path to the file to validate
429     :param param_map: A dict which will be populated with the details of the
430                       parameters in the template.  The dict will have the
431                       following structure:
432
433                           {'ParameterName': [
434                                {'filename': ./file1.yaml,
435                                 'data': {'description': '',
436                                          'type': string,
437                                          'default': '',
438                                          ...}
439                                 },
440                                {'filename': ./file2.yaml,
441                                 'data': {'description': '',
442                                          'type': string,
443                                          'default': '',
444                                          ...}
445                                 },
446                                 ...
447                            ]}
448     """
449     print('Validating %s' % filename)
450     retval = 0
451     try:
452         tpl = yaml.load(open(filename).read())
453
454         # The template alias version should be used instead a date, this validation
455         # will be applied to all templates not just for those in the services folder.
456         if 'heat_template_version' in tpl and not str(tpl['heat_template_version']).isalpha():
457             print('ERROR: heat_template_version needs to be the release alias not a date: %s'
458                   % filename)
459             return 1
460
461         # qdr aliases rabbitmq service to provide alternative messaging backend
462         if (filename.startswith('./puppet/services/') and
463                 filename not in ['./puppet/services/qdr.yaml']):
464             retval = validate_service(filename, tpl)
465
466         if filename.startswith('./docker/services/'):
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)