Update net-config-noop to use apply-config
[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 def exit_usage():
23     print('Usage %s <yaml file or directory>' % sys.argv[0])
24     sys.exit(1)
25
26
27 def validate_mysql_connection(settings):
28     no_op = lambda *args: False
29     error_status = [0]
30
31     def mysql_protocol(items):
32         return items == ['EndpointMap', 'MysqlInternal', 'protocol']
33
34     def client_bind_address(item):
35         return 'bind_address' in item
36
37     def validate_mysql_uri(key, items):
38         # Only consider a connection if it targets mysql
39         if key.endswith('connection') and \
40            search(items, mysql_protocol, no_op):
41             # Assume the "bind_address" option is one of
42             # the token that made up the uri
43             if not search(items, client_bind_address, no_op):
44                 error_status[0] = 1
45         return False
46
47     def search(item, check_item, check_key):
48         if check_item(item):
49             return True
50         elif isinstance(item, list):
51             for i in item:
52                 if search(i, check_item, check_key):
53                     return True
54         elif isinstance(item, dict):
55             for k in item.keys():
56                 if check_key(k, item[k]):
57                     return True
58                 elif search(item[k], check_item, check_key):
59                     return True
60         return False
61
62     search(settings, no_op, validate_mysql_uri)
63     return error_status[0]
64
65
66 def validate_service(filename, tpl):
67     if 'outputs' in tpl and 'role_data' in tpl['outputs']:
68         if 'value' not in tpl['outputs']['role_data']:
69             print('ERROR: invalid role_data for filename: %s'
70                   % filename)
71             return 1
72         role_data = tpl['outputs']['role_data']['value']
73         if 'service_name' not in role_data:
74             print('ERROR: service_name is required in role_data for %s.'
75                   % filename)
76             return 1
77         # service_name must match the filename, but with an underscore
78         if (role_data['service_name'] !=
79                 os.path.basename(filename).split('.')[0].replace("-", "_")):
80             print('ERROR: service_name should match file name for service: %s.'
81                   % filename)
82             return 1
83         # if service connects to mysql, the uri should use option
84         # bind_address to avoid issues with VIP failover
85         if 'config_settings' in role_data and \
86            validate_mysql_connection(role_data['config_settings']):
87             print('ERROR: mysql connection uri should use option bind_address')
88             return 1
89     if 'parameters' in tpl:
90         for param in required_params:
91             if param not in tpl['parameters']:
92                 print('ERROR: parameter %s is required for %s.'
93                       % (param, filename))
94                 return 1
95     return 0
96
97
98 def validate(filename):
99     print('Validating %s' % filename)
100     retval = 0
101     try:
102         tpl = yaml.load(open(filename).read())
103
104         if (filename.startswith('./puppet/services/') and
105                 filename != './puppet/services/services.yaml'):
106             retval = validate_service(filename, tpl)
107
108     except Exception:
109         print(traceback.format_exc())
110         return 1
111     # yaml is OK, now walk the parameters and output a warning for unused ones
112     if 'heat_template_version' in tpl:
113         for p in tpl.get('parameters', {}):
114             if p in required_params:
115                 continue
116             str_p = '\'%s\'' % p
117             in_resources = str_p in str(tpl.get('resources', {}))
118             in_outputs = str_p in str(tpl.get('outputs', {}))
119             if not in_resources and not in_outputs:
120                 print('Warning: parameter %s in template %s '
121                       'appears to be unused' % (p, filename))
122
123     return retval
124
125 if len(sys.argv) < 2:
126     exit_usage()
127
128 path_args = sys.argv[1:]
129 exit_val = 0
130 failed_files = []
131
132 for base_path in path_args:
133     if os.path.isdir(base_path):
134         for subdir, dirs, files in os.walk(base_path):
135             for f in files:
136                 if f.endswith('.yaml') and not f.endswith('.j2.yaml'):
137                     file_path = os.path.join(subdir, f)
138                     failed = validate(file_path)
139                     if failed:
140                         failed_files.append(file_path)
141                     exit_val |= failed
142     elif os.path.isfile(base_path) and base_path.endswith('.yaml'):
143         failed = validate(base_path)
144         if failed:
145             failed_files.append(base_path)
146         exit_val |= failed
147     else:
148         print('Unexpected argument %s' % base_path)
149         exit_usage()
150
151 if failed_files:
152     print('Validation failed on:')
153     for f in failed_files:
154         print(f)
155 else:
156     print('Validation successful!')
157 sys.exit(exit_val)