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, PARAM_NETIPMAP,
34 PARAM_SERVICENETMAP) = (
35 'CloudName', 'EndpointMap', 'NetIpMap', 'ServiceNetMap')
36 FIELDS = (F_PORT, F_PROTOCOL, F_HOST) = ('port', 'protocol', 'host')
38 ENDPOINT_TYPES = frozenset(['Internal', 'Public', 'Admin'])
41 def get_file(default_fn, override=None, writable=False):
48 if override is not None:
51 filename = os.path.join(os.path.dirname(__file__), default_fn)
53 return open(filename, 'w' if writable else 'r')
56 def load_endpoint_data(infile=None):
57 with get_file(IN_FILE, infile) as f:
58 return yaml.safe_load(f)
61 def net_param_name(endpoint_type_defn):
62 return endpoint_type_defn['net_param'] + 'Network'
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),
72 return ep_name + ep_type, values
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) &
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
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 '
98 params[PARAM_CLOUDNAME] = make_parameter('string',
100 'The DNS name of this cloud. '
101 'e.g. ci-overcloud.tripleo.org')
105 def template_output_definition(endpoint_name,
111 def extract_field(field):
112 assert field in FIELDS
113 return {'get_param': ['EndpointMap',
114 endpoint_name + endpoint_type,
117 port = extract_field(F_PORT)
118 protocol = extract_field(F_PROTOCOL)
120 'str_replace': collections.OrderedDict([
121 ('template', extract_field(F_HOST)),
123 SUBST_IP_ADDRESS: {'get_param':
125 {'get_param': ['ServiceNetMap',
127 SUBST_CLOUDNAME: {'get_param': PARAM_CLOUDNAME},
132 'str_replace': collections.OrderedDict([
133 ('template', extract_field(F_HOST)),
135 SUBST_IP_ADDRESS: {'get_param':
138 {'template': 'NETWORK_uri',
139 'params': {'NETWORK':
140 {'get_param': ['ServiceNetMap',
142 SUBST_CLOUDNAME: {'get_param': PARAM_CLOUDNAME},
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 []))
150 name = name_override if name_override is not None else (endpoint_name +
155 'host_nobrackets': host_nobrackets,
157 'port': extract_field('port'),
158 'protocol': extract_field('protocol'),
160 'list_join': ['', uri_fields_suffix]
163 'list_join': ['', uri_fields]
168 def template_endpoint_items(config):
169 def get_svc_endpoints(ep_name, svc):
170 for ep_type in set(svc) & ENDPOINT_TYPES:
172 for variant, suffix in defn.get('uri_suffixes',
174 name_override = defn.get('names', {}).get(variant)
175 yield template_output_definition(ep_name, variant, ep_type,
176 net_param_name(defn),
179 return itertools.chain.from_iterable(sorted(get_svc_endpoints(ep_name,
182 svc) in sorted(config.items()))
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)),
196 collections.OrderedDict(template_endpoint_items(config))
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
209 class TemplateDumper(yaml.SafeDumper):
210 def represent_ordered_dict(self, data):
211 return self.represent_dict(data.items())
214 TemplateDumper.add_representer(collections.OrderedDict,
215 TemplateDumper.represent_ordered_dict)
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)
224 def read_template(template, filename=None):
225 with get_file(OUT_FILE, filename) as f:
226 return yaml.safe_load(f)
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)
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
247 from optparse import OptionParser
249 parser = OptionParser('usage: %prog'
250 ' [-i INPUT_FILE] [-o OUTPUT_FILE] [--check]',
252 parser.add_option('-i', '--input', dest='input_file', action='store',
254 help='Specify a different endpoint data file')
255 parser.add_option('-o', '--output', dest='output_file', action='store',
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')
264 return parser.parse_args()
268 options, args = get_options()
270 print('Warning: ignoring positional args: %s' % ' '.join(args),
275 if not check_up_to_date(options.output_file, options.input_file):
276 print('EndpointMap template does not match input data',
280 build_endpoint_map(options.output_file, options.input_file)
281 except Exception as exc:
284 print('%s: %s' % (type(exc).__name__, str(exc)), file=sys.stderr)
288 if __name__ == '__main__':