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