Merge "Add os-collect-config data as an output"
[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']
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 REQUIRED_DOCKER_SECTIONS = ['service_name', 'docker_config', 'puppet_config',
35                             'config_settings', 'step_config']
36 OPTIONAL_DOCKER_SECTIONS = ['docker_puppet_tasks', 'upgrade_tasks',
37                             'service_config_settings', 'host_prep_tasks',
38                             'metadata_settings', 'kolla_config']
39 REQUIRED_DOCKER_PUPPET_CONFIG_SECTIONS = ['config_volume', 'step_config',
40                                           'config_image']
41 OPTIONAL_DOCKER_PUPPET_CONFIG_SECTIONS = [ 'puppet_tags' ]
42
43
44 def exit_usage():
45     print('Usage %s <yaml file or directory>' % sys.argv[0])
46     sys.exit(1)
47
48
49 def get_base_endpoint_map(filename):
50     try:
51         tpl = yaml.load(open(filename).read())
52         return tpl['parameters']['EndpointMap']['default']
53     except Exception:
54         print(traceback.format_exc())
55     return None
56
57
58 def get_endpoint_map_from_env(filename):
59     try:
60         tpl = yaml.load(open(filename).read())
61         return {
62             'file': filename,
63             'map': tpl['parameter_defaults']['EndpointMap']
64         }
65     except Exception:
66         print(traceback.format_exc())
67     return None
68
69
70 def validate_endpoint_map(base_map, env_map):
71     return sorted(base_map.keys()) == sorted(env_map.keys())
72
73
74 def validate_hci_compute_services_default(env_filename, env_tpl):
75     env_services_list = env_tpl['parameter_defaults']['ComputeServices']
76     env_services_list.remove('OS::TripleO::Services::CephOSD')
77     roles_filename = os.path.join(os.path.dirname(env_filename),
78                                   '../roles_data.yaml')
79     roles_tpl = yaml.load(open(roles_filename).read())
80     for role in roles_tpl:
81         if role['name'] == 'Compute':
82             roles_services_list = role['ServicesDefault']
83             if sorted(env_services_list) != sorted(roles_services_list):
84                 print('ERROR: ComputeServices in %s is different '
85                       'from ServicesDefault in roles_data.yaml' % env_filename)
86                 return 1
87     return 0
88
89
90 def validate_mysql_connection(settings):
91     no_op = lambda *args: False
92     error_status = [0]
93
94     def mysql_protocol(items):
95         return items == ['EndpointMap', 'MysqlInternal', 'protocol']
96
97     def client_bind_address(item):
98         return 'read_default_file' in item and \
99                'read_default_group' in item
100
101     def validate_mysql_uri(key, items):
102         # Only consider a connection if it targets mysql
103         if key.endswith('connection') and \
104            search(items, mysql_protocol, no_op):
105             # Assume the "bind_address" option is one of
106             # the token that made up the uri
107             if not search(items, client_bind_address, no_op):
108                 error_status[0] = 1
109         return False
110
111     def search(item, check_item, check_key):
112         if check_item(item):
113             return True
114         elif isinstance(item, list):
115             for i in item:
116                 if search(i, check_item, check_key):
117                     return True
118         elif isinstance(item, dict):
119             for k in item.keys():
120                 if check_key(k, item[k]):
121                     return True
122                 elif search(item[k], check_item, check_key):
123                     return True
124         return False
125
126     search(settings, no_op, validate_mysql_uri)
127     return error_status[0]
128
129
130 def validate_docker_service(filename, tpl):
131     if 'outputs' in tpl and 'role_data' in tpl['outputs']:
132         if 'value' not in tpl['outputs']['role_data']:
133             print('ERROR: invalid role_data for filename: %s'
134                   % filename)
135             return 1
136         role_data = tpl['outputs']['role_data']['value']
137
138         for section_name in REQUIRED_DOCKER_SECTIONS:
139             if section_name not in role_data:
140                 print('ERROR: %s is required in role_data for %s.'
141                       % (section_name, filename))
142                 return 1
143
144         for section_name in role_data.keys():
145             if section_name in REQUIRED_DOCKER_SECTIONS:
146                 continue
147             else:
148                 if section_name in OPTIONAL_DOCKER_SECTIONS:
149                     continue
150                 else:
151                     print('ERROR: %s is extra in role_data for %s.'
152                           % (section_name, filename))
153                     return 1
154
155         if 'puppet_config' in role_data:
156             puppet_config = role_data['puppet_config']
157             for key in puppet_config:
158                 if key in REQUIRED_DOCKER_PUPPET_CONFIG_SECTIONS:
159                     continue
160                 else:
161                     if key in OPTIONAL_DOCKER_PUPPET_CONFIG_SECTIONS:
162                         continue
163                     else:
164                       print('ERROR: %s should not be in puppet_config section.'
165                             % key)
166                       return 1
167             for key in REQUIRED_DOCKER_PUPPET_CONFIG_SECTIONS:
168               if key not in puppet_config:
169                   print('ERROR: %s is required in puppet_config for %s.'
170                         % (key, filename))
171                   return 1
172
173     if 'parameters' in tpl:
174         for param in required_params:
175             if param not in tpl['parameters']:
176                 print('ERROR: parameter %s is required for %s.'
177                       % (param, filename))
178                 return 1
179     return 0
180
181
182 def validate_service(filename, tpl):
183     if 'outputs' in tpl and 'role_data' in tpl['outputs']:
184         if 'value' not in tpl['outputs']['role_data']:
185             print('ERROR: invalid role_data for filename: %s'
186                   % filename)
187             return 1
188         role_data = tpl['outputs']['role_data']['value']
189         if 'service_name' not in role_data:
190             print('ERROR: service_name is required in role_data for %s.'
191                   % filename)
192             return 1
193         # service_name must match the filename, but with an underscore
194         if (role_data['service_name'] !=
195                 os.path.basename(filename).split('.')[0].replace("-", "_")):
196             print('ERROR: service_name should match file name for service: %s.'
197                   % filename)
198             return 1
199         # if service connects to mysql, the uri should use option
200         # bind_address to avoid issues with VIP failover
201         if 'config_settings' in role_data and \
202            validate_mysql_connection(role_data['config_settings']):
203             print('ERROR: mysql connection uri should use option bind_address')
204             return 1
205     if 'parameters' in tpl:
206         for param in required_params:
207             if param not in tpl['parameters']:
208                 print('ERROR: parameter %s is required for %s.'
209                       % (param, filename))
210                 return 1
211     return 0
212
213
214 def validate(filename):
215     print('Validating %s' % filename)
216     retval = 0
217     try:
218         tpl = yaml.load(open(filename).read())
219
220         # The template alias version should be used instead a date, this validation
221         # will be applied to all templates not just for those in the services folder.
222         if 'heat_template_version' in tpl and not str(tpl['heat_template_version']).isalpha():
223             print('ERROR: heat_template_version needs to be the release alias not a date: %s'
224                   % filename)
225             return 1
226
227         # qdr aliases rabbitmq service to provide alternative messaging backend
228         if (filename.startswith('./puppet/services/') and
229                 filename not in ['./puppet/services/qdr.yaml']):
230             retval = validate_service(filename, tpl)
231
232         if filename.startswith('./docker/services/'):
233             retval = validate_docker_service(filename, tpl)
234
235         if filename.endswith('hyperconverged-ceph.yaml'):
236             retval = validate_hci_compute_services_default(filename, tpl)
237
238     except Exception:
239         print(traceback.format_exc())
240         return 1
241     # yaml is OK, now walk the parameters and output a warning for unused ones
242     if 'heat_template_version' in tpl:
243         for p in tpl.get('parameters', {}):
244             if p in required_params:
245                 continue
246             str_p = '\'%s\'' % p
247             in_resources = str_p in str(tpl.get('resources', {}))
248             in_outputs = str_p in str(tpl.get('outputs', {}))
249             if not in_resources and not in_outputs:
250                 print('Warning: parameter %s in template %s '
251                       'appears to be unused' % (p, filename))
252
253     return retval
254
255 if len(sys.argv) < 2:
256     exit_usage()
257
258 path_args = sys.argv[1:]
259 exit_val = 0
260 failed_files = []
261 base_endpoint_map = None
262 env_endpoint_maps = list()
263
264 for base_path in path_args:
265     if os.path.isdir(base_path):
266         for subdir, dirs, files in os.walk(base_path):
267             for f in files:
268                 if f.endswith('.yaml') and not f.endswith('.j2.yaml'):
269                     file_path = os.path.join(subdir, f)
270                     failed = validate(file_path)
271                     if failed:
272                         failed_files.append(file_path)
273                     exit_val |= failed
274                     if f == ENDPOINT_MAP_FILE:
275                         base_endpoint_map = get_base_endpoint_map(file_path)
276                     if f in envs_containing_endpoint_map:
277                         env_endpoint_map = get_endpoint_map_from_env(file_path)
278                         if env_endpoint_map:
279                             env_endpoint_maps.append(env_endpoint_map)
280     elif os.path.isfile(base_path) and base_path.endswith('.yaml'):
281         failed = validate(base_path)
282         if failed:
283             failed_files.append(base_path)
284         exit_val |= failed
285     else:
286         print('Unexpected argument %s' % base_path)
287         exit_usage()
288
289 if base_endpoint_map and \
290         len(env_endpoint_maps) == len(envs_containing_endpoint_map):
291     for env_endpoint_map in env_endpoint_maps:
292         matches = validate_endpoint_map(base_endpoint_map,
293                                         env_endpoint_map['map'])
294         if not matches:
295             print("ERROR: %s needs to be updated to match changes in base "
296                   "endpoint map" % env_endpoint_map['file'])
297             failed_files.append(env_endpoint_map['file'])
298             exit_val |= 1
299         else:
300             print("%s matches base endpoint map" % env_endpoint_map['file'])
301 else:
302     print("ERROR: Did not find expected number of environments containing the "
303           "EndpointMap parameter.  If you meant to add or remove one of these "
304           "environments then you also need to update this tool.")
305     if not base_endpoint_map:
306         failed_files.append(ENDPOINT_MAP_FILE)
307     if len(env_endpoint_maps) != len(envs_containing_endpoint_map):
308         matched_files = set(os.path.basename(matched_env_file['file'])
309                             for matched_env_file in env_endpoint_maps)
310         failed_files.extend(set(envs_containing_endpoint_map) - matched_files)
311     exit_val |= 1
312
313 if failed_files:
314     print('Validation failed on:')
315     for f in failed_files:
316         print(f)
317 else:
318     print('Validation successful!')
319 sys.exit(exit_val)