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