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