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