4 Generate the endpoint_map.yaml template from data in the endpoint_data.yaml
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.
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
15 from __future__ import print_function
18 __all__ = ['load_endpoint_data', 'generate_endpoint_map_template',
19 'write_template', 'build_endpoint_map', 'check_up_to_date']
30 (IN_FILE, OUT_FILE) = ('endpoint_data.yaml', 'endpoint_map.yaml')
32 SUBST = (SUBST_IP_ADDRESS, SUBST_CLOUDNAME) = ('IP_ADDRESS', 'CLOUDNAME')
33 PARAMS = (PARAM_CLOUDNAME, PARAM_ENDPOINTMAP) = ('CloudName', 'EndpointMap')
34 FIELDS = (F_PORT, F_PROTOCOL, F_HOST) = ('port', 'protocol', 'host')
36 ENDPOINT_TYPES = frozenset(['Internal', 'Public', 'Admin'])
39 def get_file(default_fn, override=None, writable=False):
46 if override is not None:
49 filename = os.path.join(os.path.dirname(__file__), default_fn)
51 return open(filename, 'w' if writable else 'r')
54 def load_endpoint_data(infile=None):
55 with get_file(IN_FILE, infile) as f:
56 return yaml.safe_load(f)
59 def vip_param_name(endpoint_type_defn):
60 return endpoint_type_defn['vip_param'] + 'VirtualIP'
63 def vip_param_names(config):
65 return (v for k, v in svc.items() if k in ENDPOINT_TYPES or not k)
67 return set(vip_param_name(defn)
68 for svc in config.values() for defn in ep_types(svc))
71 def endpoint_map_default(config):
72 def map_item(ep_name, ep_type, svc):
73 values = collections.OrderedDict([
74 (F_PROTOCOL, svc.get(F_PROTOCOL, 'http')),
75 (F_PORT, str(svc[ep_type].get(F_PORT, svc[F_PORT]))),
76 (F_HOST, SUBST_IP_ADDRESS),
78 return ep_name + ep_type, values
80 return collections.OrderedDict(map_item(ep_name, ep_type, svc)
81 for ep_name, svc in sorted(config.items())
82 for ep_type in sorted(set(svc) &
86 def make_parameter(ptype, default, description=None):
87 param = collections.OrderedDict([('type', ptype), ('default', default)])
88 if description is not None:
89 param['description'] = description
93 def template_parameters(config):
94 params = collections.OrderedDict((n, make_parameter('string', ''))
95 for n in sorted(vip_param_names(config)))
97 params[PARAM_ENDPOINTMAP] = make_parameter('json',
98 endpoint_map_default(config),
99 'Mapping of service endpoint '
100 '-> protocol. Typically set '
101 'via parameter_defaults in the '
102 'resource registry.')
104 params[PARAM_CLOUDNAME] = make_parameter('string',
106 'The DNS name of this cloud. '
107 'e.g. ci-overcloud.tripleo.org')
111 def template_output_definition(endpoint_name,
117 def extract_field(field):
118 assert field in FIELDS
119 return {'get_param': ['EndpointMap',
120 endpoint_name + endpoint_type,
123 port = extract_field(F_PORT)
124 protocol = extract_field(F_PROTOCOL)
126 'str_replace': collections.OrderedDict([
127 ('template', extract_field(F_HOST)),
129 SUBST_IP_ADDRESS: {'get_param': vip_param},
130 SUBST_CLOUDNAME: {'get_param': PARAM_CLOUDNAME},
134 uri_fields = [protocol, '://', copy.deepcopy(host), ':', port]
135 uri_fields_suffix = (copy.deepcopy(uri_fields) +
136 ([uri_suffix] if uri_suffix is not None else []))
138 name = name_override if name_override is not None else (endpoint_name +
144 'port': extract_field('port'),
145 'protocol': extract_field('protocol'),
147 'list_join': ['', uri_fields_suffix]
150 'list_join': ['', uri_fields]
155 def template_endpoint_items(config):
156 def get_svc_endpoints(ep_name, svc):
157 for ep_type in set(svc) & ENDPOINT_TYPES:
159 for variant, suffix in defn.get('uri_suffixes',
161 name_override = defn.get('names', {}).get(variant)
162 yield template_output_definition(ep_name, variant, ep_type,
163 vip_param_name(defn),
167 return itertools.chain.from_iterable(sorted(get_svc_endpoints(ep_name,
170 svc) in sorted(config.items()))
173 def generate_endpoint_map_template(config):
174 return collections.OrderedDict([
175 ('heat_template_version', '2015-04-30'),
176 ('description', 'A map of OpenStack endpoints. Since the endpoints '
177 'are URLs, we need to have brackets around IPv6 IP addresses. The '
178 'inputs to these parameters come from net_ip_uri_map, which will '
179 'include these brackets in IPv6 addresses.'),
180 ('parameters', template_parameters(config)),
184 collections.OrderedDict(template_endpoint_items(config))
190 autogen_warning = """### DO NOT MODIFY THIS FILE
191 ### This file is automatically generated from endpoint_data.yaml
192 ### by the script build_endpoint_map.py
197 class TemplateDumper(yaml.SafeDumper):
198 def represent_ordered_dict(self, data):
199 return self.represent_dict(data.items())
202 TemplateDumper.add_representer(collections.OrderedDict,
203 TemplateDumper.represent_ordered_dict)
206 def write_template(template, filename=None):
207 with get_file(OUT_FILE, filename, writable=True) as f:
208 f.write(autogen_warning)
209 yaml.dump(template, f, TemplateDumper, width=68)
212 def read_template(template, filename=None):
213 with get_file(OUT_FILE, filename) as f:
214 return yaml.safe_load(f)
217 def build_endpoint_map(output_filename=None, input_filename=None):
218 if output_filename is not None and output_filename == input_filename:
219 raise Exception('Cannot read from and write to the same file')
220 config = load_endpoint_data(input_filename)
221 template = generate_endpoint_map_template(config)
222 write_template(template, output_filename)
225 def check_up_to_date(output_filename=None, input_filename=None):
226 if output_filename is not None and output_filename == input_filename:
227 raise Exception('Input and output filenames must be different')
228 config = load_endpoint_data(input_filename)
229 template = generate_endpoint_map_template(config)
230 existing_template = read_template(output_filename)
231 return existing_template == template
235 from optparse import OptionParser
237 parser = OptionParser('usage: %prog'
238 ' [-i INPUT_FILE] [-o OUTPUT_FILE] [--check]',
240 parser.add_option('-i', '--input', dest='input_file', action='store',
242 help='Specify a different endpoint data file')
243 parser.add_option('-o', '--output', dest='output_file', action='store',
245 help='Specify a different endpoint map template file')
246 parser.add_option('-c', '--check', dest='check', action='store_true',
247 default=False, help='Check that the output file is '
248 'up to date with the data')
249 parser.add_option('-d', '--debug', dest='debug', action='store_true',
250 default=False, help='Print stack traces on error')
252 return parser.parse_args()
256 options, args = get_options()
258 print('Warning: ignoring positional args: %s' % ' '.join(args),
263 if not check_up_to_date(options.output_file, options.input_file):
264 print('EndpointMap template does not match input data',
268 build_endpoint_map(options.output_file, options.input_file)
269 except Exception as exc:
272 print('%s: %s' % (type(exc).__name__, str(exc)), file=sys.stderr)
276 if __name__ == '__main__':