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