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