Sort ResourceGroup resource list
[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_mysql_connection(settings):
58     no_op = lambda *args: False
59     error_status = [0]
60
61     def mysql_protocol(items):
62         return items == ['EndpointMap', 'MysqlInternal', 'protocol']
63
64     def client_bind_address(item):
65         return 'bind_address' in item
66
67     def validate_mysql_uri(key, items):
68         # Only consider a connection if it targets mysql
69         # TODO(owalsh): skip nova mysql uris,temporary workaround for
70         # tripleo/+bug/1662344
71         if not key.startswith('nova') and \
72            key.endswith('connection') and \
73            search(items, mysql_protocol, no_op):
74             # Assume the "bind_address" option is one of
75             # the token that made up the uri
76             if not search(items, client_bind_address, no_op):
77                 error_status[0] = 1
78         return False
79
80     def search(item, check_item, check_key):
81         if check_item(item):
82             return True
83         elif isinstance(item, list):
84             for i in item:
85                 if search(i, check_item, check_key):
86                     return True
87         elif isinstance(item, dict):
88             for k in item.keys():
89                 if check_key(k, item[k]):
90                     return True
91                 elif search(item[k], check_item, check_key):
92                     return True
93         return False
94
95     search(settings, no_op, validate_mysql_uri)
96     return error_status[0]
97
98
99 def validate_service(filename, tpl):
100     if 'outputs' in tpl and 'role_data' in tpl['outputs']:
101         if 'value' not in tpl['outputs']['role_data']:
102             print('ERROR: invalid role_data for filename: %s'
103                   % filename)
104             return 1
105         role_data = tpl['outputs']['role_data']['value']
106         if 'service_name' not in role_data:
107             print('ERROR: service_name is required in role_data for %s.'
108                   % filename)
109             return 1
110         # service_name must match the filename, but with an underscore
111         if (role_data['service_name'] !=
112                 os.path.basename(filename).split('.')[0].replace("-", "_")):
113             print('ERROR: service_name should match file name for service: %s.'
114                   % filename)
115             return 1
116         # if service connects to mysql, the uri should use option
117         # bind_address to avoid issues with VIP failover
118         if 'config_settings' in role_data and \
119            validate_mysql_connection(role_data['config_settings']):
120             print('ERROR: mysql connection uri should use option bind_address')
121             return 1
122     if 'parameters' in tpl:
123         for param in required_params:
124             if param not in tpl['parameters']:
125                 print('ERROR: parameter %s is required for %s.'
126                       % (param, filename))
127                 return 1
128     return 0
129
130
131 def validate(filename):
132     print('Validating %s' % filename)
133     retval = 0
134     try:
135         tpl = yaml.load(open(filename).read())
136
137         # The template alias version should be used instead a date, this validation
138         # will be applied to all templates not just for those in the services folder.
139         if 'heat_template_version' in tpl and not str(tpl['heat_template_version']).isalpha():
140             print('ERROR: heat_template_version needs to be the release alias not a date: %s'
141                   % filename)
142             return 1
143
144         if (filename.startswith('./puppet/services/') and
145                 filename != './puppet/services/services.yaml'):
146             retval = validate_service(filename, tpl)
147
148     except Exception:
149         print(traceback.format_exc())
150         return 1
151     # yaml is OK, now walk the parameters and output a warning for unused ones
152     if 'heat_template_version' in tpl:
153         for p in tpl.get('parameters', {}):
154             if p in required_params:
155                 continue
156             str_p = '\'%s\'' % p
157             in_resources = str_p in str(tpl.get('resources', {}))
158             in_outputs = str_p in str(tpl.get('outputs', {}))
159             if not in_resources and not in_outputs:
160                 print('Warning: parameter %s in template %s '
161                       'appears to be unused' % (p, filename))
162
163     return retval
164
165 if len(sys.argv) < 2:
166     exit_usage()
167
168 path_args = sys.argv[1:]
169 exit_val = 0
170 failed_files = []
171 base_endpoint_map = None
172 env_endpoint_maps = list()
173
174 for base_path in path_args:
175     if os.path.isdir(base_path):
176         for subdir, dirs, files in os.walk(base_path):
177             for f in files:
178                 if f.endswith('.yaml') and not f.endswith('.j2.yaml'):
179                     file_path = os.path.join(subdir, f)
180                     failed = validate(file_path)
181                     if failed:
182                         failed_files.append(file_path)
183                     exit_val |= failed
184                     if f == ENDPOINT_MAP_FILE:
185                         base_endpoint_map = get_base_endpoint_map(file_path)
186                     if f in envs_containing_endpoint_map:
187                         env_endpoint_map = get_endpoint_map_from_env(file_path)
188                         if env_endpoint_map:
189                             env_endpoint_maps.append(env_endpoint_map)
190     elif os.path.isfile(base_path) and base_path.endswith('.yaml'):
191         failed = validate(base_path)
192         if failed:
193             failed_files.append(base_path)
194         exit_val |= failed
195     else:
196         print('Unexpected argument %s' % base_path)
197         exit_usage()
198
199 if base_endpoint_map and \
200         len(env_endpoint_maps) == len(envs_containing_endpoint_map):
201     for env_endpoint_map in env_endpoint_maps:
202         matches = validate_endpoint_map(base_endpoint_map,
203                                         env_endpoint_map['map'])
204         if not matches:
205             print("ERROR: %s needs to be updated to match changes in base "
206                   "endpoint map" % env_endpoint_map['file'])
207             failed_files.append(env_endpoint_map['file'])
208             exit_val |= 1
209         else:
210             print("%s matches base endpoint map" % env_endpoint_map['file'])
211 else:
212     print("ERROR: Can't validate endpoint maps since a file is missing. "
213           "If you meant to delete one of these files you should update this "
214           "tool as well.")
215     if not base_endpoint_map:
216         failed_files.append(ENDPOINT_MAP_FILE)
217     if len(env_endpoint_maps) != len(envs_containing_endpoint_map):
218         matched_files = set(os.path.basename(matched_env_file['file'])
219                             for matched_env_file in env_endpoint_maps)
220         failed_files.extend(set(envs_containing_endpoint_map) - matched_files)
221     exit_val |= 1
222
223 if failed_files:
224     print('Validation failed on:')
225     for f in failed_files:
226         print(f)
227 else:
228     print('Validation successful!')
229 sys.exit(exit_val)