Debian Codegraph @

networking_bagpipe/bagpipe_bgp/cli/rest_attach.py

raw
1 # Copyright 2014 Orange
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 import copy
16 import functools
17 import logging
18 import os
19 import re
20 import sys
21 import urllib.error
22 import urllib.request
23
24
25 import netaddr
26 import optparse
27 from oslo_config import cfg
28 from oslo_serialization import jsonutils
29
30 from networking_bagpipe._i18n import _
31 from networking_bagpipe.bagpipe_bgp.api import config as api_config
32 from networking_bagpipe.bagpipe_bgp.common import net_utils
33 from networking_bagpipe.bagpipe_bgp.common import run_command
34 from networking_bagpipe.bagpipe_bgp import constants as const
35
36
37 DEFAULT_VPN_INSTANCE_ID = "bagpipe-test"
38
39 VPN2NS_INTERFACE_PREFIX = "ns-"
40
41 NS2VPN_DEFAULT_IFNAME = "tovpn"
42
43 # Needed so that the OVS bridge kernel interface can hava a high enough MTU
44 DEFAULT_MTU = 9000
45
46 log_formatter = logging.Formatter("[%(levelname)-5.5s] %(message)s")
47 log = logging.getLogger()
48
49 console_handler = logging.StreamHandler()
50 console_handler.setFormatter(log_formatter)
51 log.addHandler(console_handler)
52
53 log.setLevel(logging.WARNING)
54
55 run_log_command = functools.partial(run_command.run_command, log,
56 run_as_root=True)
57
58
59 def create_veth_pair(vpn_interface, ns_interface, ns_name):
60 run_log_command("ip netns exec %s ip link delete %s" %
61 (ns_name, ns_interface), raise_on_error=False,
62 acceptable_return_codes=[0, 1])
63 # in case the interface was previously attached to OVS,
64 # we need to remove that, or when then interface is re-created
65 # OVS will take it back!
66 run_log_command("ovs-vsctl del-port %s" %
67 vpn_interface, raise_on_error=False,
68 acceptable_return_codes=[0, 1])
69 run_log_command("ip link delete %s" %
70 vpn_interface, raise_on_error=False,
71 acceptable_return_codes=[0, 1])
72 run_log_command(
73 "ip link add %s type veth peer name %s netns %s mtu 65535" %
74 (vpn_interface, ns_interface, ns_name),
75 raise_on_error=False)
76 run_log_command("ip link set dev %s up" % vpn_interface)
77 run_log_command("ip link set dev %s mtu %d" % (vpn_interface, DEFAULT_MTU))
78 run_log_command("ip netns exec %s ip link set dev %s up" %
79 (ns_name, ns_interface))
80
81
82 def get_vpn2ns_if_name(namespace):
83 return (VPN2NS_INTERFACE_PREFIX + namespace)[:const.LINUX_DEV_LEN]
84
85
86 def create_special_netns_port(options):
87 print("Will plug local namespace %s into network" % options.netns)
88
89 # create namespace
90 run_log_command("ip netns add %s" %
91 options.netns, raise_on_error=False)
92
93 # create veth pair and move one into namespace
94 if options.ovs_vlan:
95 create_veth_pair(options.if2netns, "ns2vpn-raw", options.netns)
96
97 run_log_command("ip netns exec %s ip link add link ns2vpn-raw "
98 "name %s type vlan id %d"
99 % (options.netns, options.if2vpn, options.ovs_vlan))
100 run_log_command("ip netns exec %s ip link set %s up"
101 % (options.netns, options.if2vpn))
102 else:
103 create_veth_pair(options.if2netns, options.if2vpn, options.netns)
104
105 if options.mac:
106 run_log_command("ip netns exec %s ip link set %s address %s"
107 % (options.netns, options.if2vpn, options.mac))
108
109 run_log_command("ip netns exec %s ip addr add %s dev %s" %
110 (options.netns, options.ip, options.if2vpn),
111 raise_on_error=False)
112
113 run_log_command("ip netns exec %s ip route add default dev %s via %s" %
114 (options.netns, options.if2vpn, options.gw_ip),
115 raise_on_error=False)
116
117 run_log_command("ip netns exec %s ip link set %s mtu 1420" %
118 (options.netns, options.if2vpn),
119 raise_on_error=False)
120
121
122 def classifier_callback(option, opt_str, value, parser):
123 if not hasattr(parser.values, 'classifier'):
124 parser.values.classifier = dict()
125 parser.values.classifier.update({option.dest: value})
126
127
128 def main():
129 api_config.register_config()
130 cfg.CONF(args=[],
131 project='bagpipe-rest-attach',
132 default_config_files=['/etc/bagpipe-bgp/bgp.conf'])
133
134 usage = "usage: %prog [--attach|--detach] --network-type (ipvpn|evpn) "\
135 "--port (<port>|netns) --ip <ip>[/<mask>] [options] (see --help)"
136 parser = optparse.OptionParser(usage)
137
138 parser.add_option("--attach", dest="operation",
139 action="store_const", const="attach",
140 help="attach local port")
141 parser.add_option("--detach", dest="operation",
142 action="store_const", const="detach",
143 help="detach local port")
144
145 parser.add_option("--network-type", dest="network_type",
146 help="network type (ipvpn or evpn)",
147 choices=[const.IPVPN, const.EVPN])
148 parser.add_option("--vpn-instance-id", dest="vpn_instance_id",
149 help="UUID for the network instance "
150 "(default: %default-(ipvpn|evpn))",
151 default=DEFAULT_VPN_INSTANCE_ID)
152 parser.add_option("--port", dest="port",
153 help="local port to attach/detach (use special port "
154 "'netns[:if]' to have an interface to a local network "
155 "namespace attached/detached "
156 "[with 'if' as the name of the interface to the netns]")
157 parser.add_option("--direction", dest="direction",
158 choices=[const.TO_PORT, const.FROM_PORT, const.BOTH],
159 default=const.BOTH,
160 help=("local port direction (to-port|from-port|both) "
161 "in VPN (default: %default)"))
162 parser.add_option("--rt", dest="route_targets",
163 help="route target [default: 64512:0] (can be "
164 "specified multiple times)", default=[], action="append")
165 parser.add_option("--import-rt", dest="import_only_rts",
166 help="import-only route target (can be specified"
167 "multiple times)", default=[], action="append")
168 parser.add_option("--export-rt", dest="export_only_rts",
169 help="export-only route target (can be specified"
170 "multiple times)", default=[], action="append")
171
172 parser.add_option("--ip", dest="ip",
173 help="IP prefix / mask (mask defaults to /24)")
174 parser.add_option("--gateway-ip", dest="gw_ip",
175 help="IP address of network gateway (optional, "
176 "defaults to last IP in range)")
177 parser.add_option("--mac", dest="mac",
178 help="MAC address (required for evpn if port"
179 " is not 'netns')")
180
181 parser.set_defaults(advertise_subnet=False)
182 parser.add_option("--advertise-singleton", action="store_false",
183 dest="advertise_subnet",
184 help="advertise IP address as a /32 (default)")
185
186 parser.add_option("--advertise-subnet", action="store_true",
187 dest="advertise_subnet",
188 help="advertise the whole IP subnet")
189
190 parser.add_option("--ovs-preplug", action="store_true", dest="ovs_preplug",
191 default=False, help="should we prealably plug the port "
192 "into an OVS bridge")
193 parser.add_option("--ovs-bridge", dest="bridge", default="br-int",
194 help="if preplug, specifies which OVS bridge to use"
195 " (default: %default)")
196 parser.add_option("--ovs-vlan", dest="ovs_vlan", type='int',
197 help="if specified, only this VLAN from the OVS "
198 "interface will be attached to the VPN instance "
199 "(optional)")
200
201 parser.add_option("--netns", dest="netns",
202 help="name of network namespace (optional, for use with"
203 " --port netns)")
204 parser.add_option("--if2vpn", dest="if2vpn", default=NS2VPN_DEFAULT_IFNAME,
205 help="name of interface in netns toward VPN"
206 "defaults to %default "
207 "(optional, for use with --port netns)")
208
209 parser.add_option("--readv-from-rt", dest="readv_from_rts",
210 help="enables route readvertisement from these RTs,"
211 " works in conjunction with --readv-to-rt",
212 default=[], action="append")
213
214 parser.add_option("--readv-to-rt", dest="readv_to_rts",
215 help="enables route readvertisement to these RTs,"
216 " works in conjunction with --readv-from-rt",
217 default=[], action="append")
218
219 parser.add_option("--redirect-rts", dest="redirect_rts",
220 help="Redirection Route Targets to attract traffic, "
221 "matching the traffic classifier, in specified VRF from "
222 "any VRF importing this route target",
223 default=[], action="append")
224 parser.add_option("--source-prefix", dest="sourcePrefix",
225 type="string", help="Traffic classifier source prefix "
226 "filter",
227 action="callback", callback=classifier_callback)
228 parser.add_option("--destination-prefix", dest="destinationPrefix",
229 type="string", help="Traffic classifier destination "
230 "prefix filter",
231 action="callback", callback=classifier_callback)
232 parser.add_option("--source-port", dest="sourcePort",
233 type="string", help="Traffic classifier source port "
234 "number or range filter",
235 action="callback", callback=classifier_callback)
236 parser.add_option("--destination-port", dest="destinationPort",
237 type="string", help="Traffic classifier destination port"
238 " number or range filter",
239 action="callback", callback=classifier_callback)
240 parser.add_option("--protocol", dest="protocol",
241 type="string", help="Traffic classifier IP protocol "
242 "filter",
243 action="callback", callback=classifier_callback)
244 parser.add_option("--attract-to-rt", dest="attract_to_rts",
245 help="enables route advertisement to these RTs,"
246 " works in conjunction with "
247 "--static-destination-prefix",
248 default=[], action="append")
249 parser.add_option("--static-destination-prefix",
250 dest="static_dest_prefixes",
251 help="static destination prefix to advertise,"
252 " works in conjunction with --attract-to-rts",
253 default=[], action="append")
254 parser.add_option("--lb-consistent-hash-order",
255 dest="lb_consistent_hash_order",
256 default=0, type="int",
257 help="Load Balancing consistent hash sort order")
258 parser.add_option("--vni", dest="vni",
259 default=0,
260 type="int",
261 help="VXLAN VNI to use for this VPN instance (optional)")
262 parser.add_option("--local-pref", dest="local_pref",
263 default=None,
264 type="int",
265 help="BGP LOCAL PREF attribute (optional)")
266 (options, _unused) = parser.parse_args()
267
268 if not options.operation:
269 parser.error("Need to specify --attach or --detach")
270
271 if not options.port:
272 parser.error("Need to specify --port <localport>")
273
274 if not options.network_type:
275 parser.error("Need to specify --network-type")
276
277 if not options.ip:
278 parser.error("Need to specify --ip")
279
280 if (len(options.route_targets) == 0 and
281 not (options.import_only_rts or
282 options.export_only_rts)):
283 if options.network_type == const.IPVPN:
284 options.route_targets = ["64512:512"]
285 else:
286 options.route_targets = ["64512:513"]
287
288 import_rts = copy.copy(options.route_targets or [])
289 for rt in options.import_only_rts:
290 import_rts.append(rt)
291
292 export_rts = copy.copy(options.route_targets or [])
293 for rt in options.export_only_rts:
294 export_rts.append(rt)
295
296 if not re.match('.*/[0-9]+$', options.ip):
297 options.ip = options.ip + "/24"
298
299 if not options.gw_ip:
300 net = netaddr.IPNetwork(options.ip)
301 print("using %s as gateway address" % str(net[-2]))
302 options.gw_ip = str(net[-2])
303
304 if options.vpn_instance_id == DEFAULT_VPN_INSTANCE_ID:
305 options.vpn_instance_id = "{}-{}".format(
306 options.network_type, options.vpn_instance_id)
307
308 if options.port.startswith("netns"):
309
310 if not options.netns:
311 options.netns = options.vpn_instance_id
312
313 try:
314 (_unused, options.if2netns) = options.port.split(":")
315 except Exception:
316 options.if2netns = get_vpn2ns_if_name(options.netns)
317
318 if options.operation == "attach":
319 create_special_netns_port(options)
320
321 options.port = options.if2netns
322 if not options.mac:
323 options.mac = net_utils.get_device_mac(run_log_command,
324 options.if2vpn,
325 options.netns)
326
327 print("Local port: {} ({})".format(options.port, options.mac))
328 run_log_command("ip link show %s" % options.port)
329
330 local_port = {}
331 if options.port[:5] == "evpn:":
332 if (options.network_type == const.IPVPN):
333 print("will plug evpn %s into the IPVPN" % options.port[5:])
334 local_port['evpn'] = {'id': options.port[5:]}
335 else:
336 raise Exception(_("Can only plug an evpn into an ipvpn"))
337 else:
338 local_port['linuxif'] = options.port
339
340 # currently our only the MPLS OVS driver for ipvpn requires preplug
341 if (options.ovs_preplug and options.network_type == const.IPVPN):
342 print("pre-plugging {} into {}".format(options.port,
343 options.bridge))
344 run_log_command("ovs-vsctl del-port %s %s" %
345 (options.bridge, options.port),
346 raise_on_error=False)
347 run_log_command("ovs-vsctl add-port %s %s" %
348 (options.bridge, options.port))
349
350 local_port['ovs'] = {'port_name': options.port,
351 'plugged': True}
352
353 if options.ovs_vlan:
354 local_port['ovs']['vlan'] = options.ovs_vlan
355
356 if not options.mac:
357 if options.network_type == const.IPVPN:
358 options.mac = "52:54:00:99:99:22"
359 else:
360 parser.error("Need to specify --mac for an EVPN network "
361 "attachment if port is not 'netns'")
362
363 readvertise = None
364 if options.readv_to_rts:
365 readvertise = {"from_rt": options.readv_from_rts,
366 "to_rt": options.readv_to_rts}
367
368 attract_traffic = dict()
369 if options.redirect_rts:
370 if options.classifier:
371 attract_traffic.update(dict(redirect_rts=options.redirect_rts,
372 classifier=options.classifier))
373 else:
374 parser.error("Need to specify --redirect-rt and at least one "
375 "traffic classifier option")
376
377 if options.attract_to_rts:
378 if options.static_dest_prefixes:
379 attract_traffic.update(dict(
380 to=options.attract_to_rts,
381 static_destination_prefixes=options.static_dest_prefixes
382 ))
383 else:
384 parser.error("Need to specify --attract-to-rt and at least "
385 "one static destination prefix option")
386
387 data = {
388 "import_rt": import_rts,
389 "export_rt": export_rts,
390 "local_port": local_port,
391 "vpn_instance_id": options.vpn_instance_id,
392 "vpn_type": options.network_type,
393 "gateway_ip": options.gw_ip,
394 "mac_address": options.mac,
395 "ip_address": options.ip,
396 "advertise_subnet": options.advertise_subnet,
397 "readvertise": readvertise,
398 "attract_traffic": attract_traffic,
399 "lb_consistent_hash_order": options.lb_consistent_hash_order,
400 "vni": options.vni
401 }
402
403 if options.local_pref:
404 data['local_pref'] = options.local_pref
405
406 if options.direction:
407 data['direction'] = options.direction
408
409 json_data = jsonutils.dumps(data).encode('utf-8')
410
411 print("request: %s" % json_data)
412
413 os.environ['NO_PROXY'] = "127.0.0.1"
414 req = urllib.request.Request(
415 "http://127.0.0.1:%d/%s_localport" %
416 (cfg.CONF.API.port, options.operation),
417 json_data, {'Content-Type': 'application/json'})
418 try:
419 response = urllib.request.urlopen(req)
420 response_content = response.read()
421 response.close()
422
423 print("response: %d %s" % (response.getcode(), response_content))
424 except urllib.error.HTTPError as e:
425 error_content = e.read()
426 print(" %s" % error_content)
427 sys.exit("error %d, reason: %s" % (e.code, e.reason))