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