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