Merge "Move RabbitMQ settings out of controller.yaml"
[apex-tripleo-heat-templates.git] / network / endpoints / build_endpoint_map.py
1 #!/usr/bin/env python
2
3 """
4 Generate the endpoint_map.yaml template from data in the endpoint_data.yaml
5 file.
6
7 By default the files in the same directory as this script are operated on, but
8 different files can be optionally specified on the command line.
9
10 The --check option verifies that the current output file is up-to-date with the
11 latest data in the input file. The script exits with status code 2 if a
12 mismatch is detected.
13 """
14
15 from __future__ import print_function
16
17
18 __all__ = ['load_endpoint_data', 'generate_endpoint_map_template',
19            'write_template', 'build_endpoint_map', 'check_up_to_date']
20
21
22 import collections
23 import copy
24 import itertools
25 import os
26 import sys
27 import yaml
28
29
30 (IN_FILE, OUT_FILE) = ('endpoint_data.yaml', 'endpoint_map.yaml')
31
32 SUBST = (SUBST_IP_ADDRESS, SUBST_CLOUDNAME) = ('IP_ADDRESS', 'CLOUDNAME')
33 PARAMS = (PARAM_CLOUDNAME, PARAM_ENDPOINTMAP, PARAM_NETIPMAP,
34           PARAM_SERVICENETMAP) = (
35           'CloudName', 'EndpointMap', 'NetIpMap', 'ServiceNetMap')
36 FIELDS = (F_PORT, F_PROTOCOL, F_HOST) = ('port', 'protocol', 'host')
37
38 ENDPOINT_TYPES = frozenset(['Internal', 'Public', 'Admin'])
39
40
41 def get_file(default_fn, override=None, writable=False):
42     if override == '-':
43         if writable:
44             return sys.stdout
45         else:
46             return sys.stdin
47
48     if override is not None:
49         filename = override
50     else:
51         filename = os.path.join(os.path.dirname(__file__), default_fn)
52
53     return open(filename, 'w' if writable else 'r')
54
55
56 def load_endpoint_data(infile=None):
57     with get_file(IN_FILE, infile) as f:
58         return yaml.safe_load(f)
59
60
61 def net_param_name(endpoint_type_defn):
62     return endpoint_type_defn['net_param'] + 'Network'
63
64
65 def endpoint_map_default(config):
66     def map_item(ep_name, ep_type, svc):
67         values = collections.OrderedDict([
68             (F_PROTOCOL, svc.get(F_PROTOCOL, 'http')),
69             (F_PORT, str(svc[ep_type].get(F_PORT, svc[F_PORT]))),
70             (F_HOST, SUBST_IP_ADDRESS),
71         ])
72         return ep_name + ep_type, values
73
74     return collections.OrderedDict(map_item(ep_name, ep_type, svc)
75                                    for ep_name, svc in sorted(config.items())
76                                    for ep_type in sorted(set(svc) &
77                                                          ENDPOINT_TYPES))
78
79
80 def make_parameter(ptype, default, description=None):
81     param = collections.OrderedDict([('type', ptype), ('default', default)])
82     if description is not None:
83         param['description'] = description
84     return param
85
86
87 def template_parameters(config):
88     params = collections.OrderedDict()
89     params[PARAM_NETIPMAP] = make_parameter('json', {}, 'The Net IP map')
90     params[PARAM_SERVICENETMAP] = make_parameter('json', {}, 'The Service Net map')
91     params[PARAM_ENDPOINTMAP] = make_parameter('json',
92                                                endpoint_map_default(config),
93                                                'Mapping of service endpoint '
94                                                '-> protocol. Typically set '
95                                                'via parameter_defaults in the '
96                                                'resource registry.')
97
98     params[PARAM_CLOUDNAME] = make_parameter('string',
99                                              'overcloud',
100                                              'The DNS name of this cloud. '
101                                              'e.g. ci-overcloud.tripleo.org')
102     return params
103
104
105 def template_output_definition(endpoint_name,
106                                endpoint_variant,
107                                endpoint_type,
108                                net_param,
109                                uri_suffix=None,
110                                name_override=None):
111     def extract_field(field):
112         assert field in FIELDS
113         return {'get_param': ['EndpointMap',
114                               endpoint_name + endpoint_type,
115                               copy.copy(field)]}
116
117     port = extract_field(F_PORT)
118     protocol = extract_field(F_PROTOCOL)
119     host_nobrackets = {
120         'str_replace': collections.OrderedDict([
121             ('template', extract_field(F_HOST)),
122             ('params', {
123                 SUBST_IP_ADDRESS: {'get_param':
124                                    ['NetIpMap',
125                                     {'get_param': ['ServiceNetMap',
126                                      net_param]}]},
127                 SUBST_CLOUDNAME: {'get_param': PARAM_CLOUDNAME},
128             })
129         ])
130     }
131     host = {
132         'str_replace': collections.OrderedDict([
133             ('template', extract_field(F_HOST)),
134             ('params', {
135                 SUBST_IP_ADDRESS: {'get_param':
136                                    ['NetIpMap',
137                                     {'str_replace':
138                                     {'template': 'NETWORK_uri',
139                                      'params': {'NETWORK':
140                                      {'get_param': ['ServiceNetMap',
141                                                     net_param]}}}}]},
142                 SUBST_CLOUDNAME: {'get_param': PARAM_CLOUDNAME},
143             })
144         ])
145     }
146     uri_fields = [protocol, '://', copy.deepcopy(host), ':', port]
147     uri_fields_suffix = (copy.deepcopy(uri_fields) +
148                          ([uri_suffix] if uri_suffix is not None else []))
149
150     name = name_override if name_override is not None else (endpoint_name +
151                                                             endpoint_variant +
152                                                             endpoint_type)
153
154     return name, {
155         'host_nobrackets': host_nobrackets,
156         'host': host,
157         'port': extract_field('port'),
158         'protocol': extract_field('protocol'),
159         'uri': {
160             'list_join': ['', uri_fields_suffix]
161         },
162         'uri_no_suffix': {
163             'list_join': ['', uri_fields]
164         },
165     }
166
167
168 def template_endpoint_items(config):
169     def get_svc_endpoints(ep_name, svc):
170         for ep_type in set(svc) & ENDPOINT_TYPES:
171             defn = svc[ep_type]
172             for variant, suffix in defn.get('uri_suffixes',
173                                             {'': None}).items():
174                 name_override = defn.get('names', {}).get(variant)
175                 yield template_output_definition(ep_name, variant, ep_type,
176                                                  net_param_name(defn),
177                                                  suffix,
178                                                  name_override)
179     return itertools.chain.from_iterable(sorted(get_svc_endpoints(ep_name,
180                                                                   svc))
181                                          for (ep_name,
182                                               svc) in sorted(config.items()))
183
184
185 def generate_endpoint_map_template(config):
186     return collections.OrderedDict([
187         ('heat_template_version', '2015-04-30'),
188         ('description', 'A map of OpenStack endpoints. Since the endpoints '
189          'are URLs, we need to have brackets around IPv6 IP addresses. The '
190          'inputs to these parameters come from net_ip_uri_map, which will '
191          'include these brackets in IPv6 addresses.'),
192         ('parameters', template_parameters(config)),
193         ('outputs', {
194             'endpoint_map': {
195                 'value':
196                     collections.OrderedDict(template_endpoint_items(config))
197             }
198         }),
199     ])
200
201
202 autogen_warning = """### DO NOT MODIFY THIS FILE
203 ### This file is automatically generated from endpoint_data.yaml
204 ### by the script build_endpoint_map.py
205
206 """
207
208
209 class TemplateDumper(yaml.SafeDumper):
210     def represent_ordered_dict(self, data):
211         return self.represent_dict(data.items())
212
213
214 TemplateDumper.add_representer(collections.OrderedDict,
215                                TemplateDumper.represent_ordered_dict)
216
217
218 def write_template(template, filename=None):
219     with get_file(OUT_FILE, filename, writable=True) as f:
220         f.write(autogen_warning)
221         yaml.dump(template, f, TemplateDumper, width=68)
222
223
224 def read_template(template, filename=None):
225     with get_file(OUT_FILE, filename) as f:
226         return yaml.safe_load(f)
227
228
229 def build_endpoint_map(output_filename=None, input_filename=None):
230     if output_filename is not None and output_filename == input_filename:
231         raise Exception('Cannot read from and write to the same file')
232     config = load_endpoint_data(input_filename)
233     template = generate_endpoint_map_template(config)
234     write_template(template, output_filename)
235
236
237 def check_up_to_date(output_filename=None, input_filename=None):
238     if output_filename is not None and output_filename == input_filename:
239         raise Exception('Input and output filenames must be different')
240     config = load_endpoint_data(input_filename)
241     template = generate_endpoint_map_template(config)
242     existing_template = read_template(output_filename)
243     return existing_template == template
244
245
246 def get_options():
247     from optparse import OptionParser
248
249     parser = OptionParser('usage: %prog'
250                           ' [-i INPUT_FILE] [-o OUTPUT_FILE] [--check]',
251                           description=__doc__)
252     parser.add_option('-i', '--input', dest='input_file', action='store',
253                       default=None,
254                       help='Specify a different endpoint data file')
255     parser.add_option('-o', '--output', dest='output_file', action='store',
256                       default=None,
257                       help='Specify a different endpoint map template file')
258     parser.add_option('-c', '--check', dest='check', action='store_true',
259                       default=False, help='Check that the output file is '
260                                           'up to date with the data')
261     parser.add_option('-d', '--debug', dest='debug', action='store_true',
262                       default=False, help='Print stack traces on error')
263
264     return parser.parse_args()
265
266
267 def main():
268     options, args = get_options()
269     if args:
270         print('Warning: ignoring positional args: %s' % ' '.join(args),
271               file=sys.stderr)
272
273     try:
274         if options.check:
275             if not check_up_to_date(options.output_file, options.input_file):
276                 print('EndpointMap template does not match input data',
277                       file=sys.stderr)
278                 sys.exit(2)
279         else:
280             build_endpoint_map(options.output_file, options.input_file)
281     except Exception as exc:
282         if options.debug:
283             raise
284         print('%s: %s' % (type(exc).__name__, str(exc)), file=sys.stderr)
285         sys.exit(1)
286
287
288 if __name__ == '__main__':
289     main()