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