network.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. import itertools
  2. import ipaddress
  3. import logging
  4. import atexit
  5. import socket
  6. import time
  7. import threading
  8. import subprocess
  9. from os import path
  10. import pyroute2
  11. from pyroute2.netlink.rtnl import rtypes
  12. import docker
  13. from flask import request, jsonify
  14. from . import interface
  15. from . import NetDhcpError, udhcpc, app
  16. LIBRARY = 'IPR'
  17. OPTS_KEY = 'com.docker.network.generic'
  18. OPT_BRIDGE = 'bridge'
  19. OPT_IPV6 = 'ipv6'
  20. logger = logging.getLogger('net-dhcp')
  21. interface.InitializeLibrary(LIBRARY)
  22. dockerClient = None
  23. def get_docker_client():
  24. global dockerClient
  25. if dockerClient is None:
  26. dockerClient = docker.from_env()
  27. @atexit.register
  28. def close_docker_client():
  29. global dockerClient
  30. if dockerClient is not None:
  31. dockerClient.close()
  32. dockerClient = None
  33. gateway_hints = {}
  34. container_dhcp_clients = {}
  35. @atexit.register
  36. def cleanup_dhcp():
  37. for endpoint, dhcp in container_dhcp_clients.items():
  38. logger.warning('cleaning up orphaned container DHCP client (endpoint "%s")', endpoint)
  39. dhcp.stop()
  40. def veth_pair(e):
  41. return f'dh-{e[:12]}', f'{e[:12]}-dh'
  42. def iface_addrs(iface):
  43. return list(map(lambda a: ipaddress.ip_interface((a['address'], a['prefixlen'])), iface.ipaddr))
  44. def iface_nets(iface):
  45. return list(map(lambda n: n.network, iface_addrs(iface)))
  46. def get_bridges():
  47. get_docker_client()
  48. reserved_nets = set(map(ipaddress.ip_network, map(lambda c: c['Subnet'], \
  49. itertools.chain.from_iterable(map(lambda i: i['Config'], filter(lambda i: i['Driver'] != 'net-dhcp', \
  50. map(lambda n: n.attrs['IPAM'], dockerClient.networks.list())))))))
  51. return dict(map(lambda i: (i['ifname'], i), filter(lambda i: i['kind'] == 'bridge' and not \
  52. set(iface_nets(i)).intersection(reserved_nets), map(lambda i: interface.GetInterface(LIBRARY, i['ifname']), \
  53. interface.GetInterfaces(LIBRARY)))))
  54. def net_bridge(n):
  55. get_docker_client()
  56. return interface.GetInterface(LIBRARY, dockerClient.networks.get(n).attrs['Options'][OPT_BRIDGE])
  57. def ipv6_enabled(n):
  58. get_docker_client()
  59. options = dockerClient.networks.get(n).attrs['Options']
  60. return OPT_IPV6 in options and options[OPT_IPV6] == 'true'
  61. def endpoint_container_iface(n, e):
  62. get_docker_client()
  63. for cid, info in dockerClient.networks.get(n).attrs['Containers'].items():
  64. if info['EndpointID'] == e:
  65. container = dockerClient.containers.get(cid)
  66. netns = f'/proc/{container.attrs["State"]["Pid"]}/ns/net'
  67. with pyroute2.NetNS(netns) as rtnl:
  68. for link in rtnl.get_links():
  69. attrs = dict(link['attrs'])
  70. if attrs['IFLA_ADDRESS'] == info['MacAddress']:
  71. return {
  72. 'netns': netns,
  73. 'ifname': attrs['IFLA_IFNAME'],
  74. 'address': attrs['IFLA_ADDRESS']
  75. }
  76. break
  77. return None
  78. def await_endpoint_container_iface(n, e, timeout=5):
  79. start = time.time()
  80. iface = None
  81. while time.time() - start < timeout:
  82. try:
  83. iface = endpoint_container_iface(n, e)
  84. except docker.errors.NotFound:
  85. time.sleep(0.5)
  86. if not iface:
  87. raise NetDhcpError('Timed out waiting for container to become availabile')
  88. return iface
  89. def endpoint_container_hostname(n, e):
  90. get_docker_client()
  91. for cid, info in dockerClient.networks.get(n).attrs['Containers'].items():
  92. if info['EndpointID'] == e:
  93. return dockerClient.containers.get(cid).attrs['Config']['Hostname']
  94. return None
  95. @app.route('/NetworkDriver.GetCapabilities', methods=['POST'])
  96. def net_get_capabilities():
  97. return jsonify({
  98. 'Scope': 'local',
  99. 'ConnectivityScope': 'global'
  100. })
  101. @app.route('/NetworkDriver.CreateNetwork', methods=['POST'])
  102. def create_net():
  103. req = request.get_json(force=True)
  104. for data in req['IPv4Data']:
  105. if data['AddressSpace'] != 'null' or data['Pool'] != '0.0.0.0/0':
  106. return jsonify({'Err': 'Only the null IPAM driver is supported'}), 400
  107. options = req['Options'][OPTS_KEY]
  108. if OPT_BRIDGE not in options:
  109. return jsonify({'Err': 'No bridge provided'}), 400
  110. # We have to use a custom "enable IPv6" option because Docker's null IPAM driver doesn't support IPv6 and a plugin
  111. # IPAM driver isn't allowed to return an empty address
  112. if OPT_IPV6 in options and options[OPT_IPV6] not in ('', 'true', 'false'):
  113. return jsonify({'Err': 'Invalid boolean value for ipv6'}), 400
  114. desired = options[OPT_BRIDGE]
  115. bridges = get_bridges()
  116. if desired not in bridges:
  117. return jsonify({'Err': f'Bridge "{desired}" not found (or the specified bridge is already used by Docker)'}), 400
  118. logger.info('Creating network "%s" (using bridge "%s")', req['NetworkID'], desired)
  119. return jsonify({})
  120. @app.route('/NetworkDriver.DeleteNetwork', methods=['POST'])
  121. def delete_net():
  122. return jsonify({})
  123. @app.route('/NetworkDriver.CreateEndpoint', methods=['POST'])
  124. def create_endpoint():
  125. req = request.get_json(force=True)
  126. network_id = req['NetworkID']
  127. endpoint_id = req['EndpointID']
  128. req_iface = req['Interface']
  129. bridge = net_bridge(network_id)
  130. bridge_addrs = iface_addrs(bridge)
  131. if_host, if_container = veth_pair(endpoint_id)
  132. logger.info('creating veth pair %s <=> %s', if_host, if_container)
  133. if_host = interface.CreateInterface(LIBRARY, if_host, 'veth', if_container)
  134. if_host.Up()
  135. try:
  136. start = time.time()
  137. while isinstance(if_container, str) and time.time() - start < 10:
  138. try:
  139. if_container = interface.GetInterface(LIBRARY, if_container)
  140. if_container.Up()
  141. except KeyError:
  142. time.sleep(0.5)
  143. if isinstance(if_container, str):
  144. raise NetDhcpError(f'timed out waiting for {if_container} to appear in host')
  145. interface.AddPort(LIBRARY, bridge.ifname, if_host.ifname)
  146. res_iface = {
  147. 'MacAddress': '',
  148. 'Address': '',
  149. 'AddressIPv6': ''
  150. }
  151. if 'MacAddress' in req_iface and req_iface['MacAddress']:
  152. if_container.SetAddress(req_iface['MacAddress'])
  153. else:
  154. res_iface['MacAddress'] = if_container['address']
  155. def try_addr(type_):
  156. addr = None
  157. k = 'AddressIPv6' if type_ == 'v6' else 'Address'
  158. if k in req_iface and req_iface[k]:
  159. # TODO: Should we allow static IP's somehow?
  160. # Just validate the address, Docker will add it to the interface for us
  161. #addr = ipaddress.ip_interface(req_iface[k])
  162. #for bridge_addr in bridge_addrs:
  163. # if addr.ip == bridge_addr.ip:
  164. # raise NetDhcpError(400, f'Address {addr} is already in use on bridge {bridge["ifname"]}')
  165. raise NetDhcpError('Only the null IPAM driver is supported')
  166. else:
  167. dhcp = udhcpc.DHCPClient(if_container, v6=type_ == 'v6', once=True)
  168. addr = dhcp.finish()
  169. if not addr:
  170. return
  171. res_iface[k] = str(addr)
  172. if dhcp.gateway:
  173. gateway_hints[endpoint_id] = dhcp.gateway
  174. logger.info('Adding IP%s address %s to %s', type_, addr, if_container['ifname'])
  175. try_addr('v4')
  176. if ipv6_enabled(network_id):
  177. try_addr('v6')
  178. res = jsonify({
  179. 'Interface': res_iface
  180. })
  181. except Exception as e:
  182. logger.exception(e)
  183. if not isinstance(if_container, str):
  184. interface.DelPort(LIBRARY, bridge.ifname, if_host.ifname)
  185. interface.RemoveInterface(LIBRARY, if_host.ifname)
  186. if isinstance(e, NetDhcpError):
  187. res = jsonify({'Err': str(e)}), e.status
  188. else:
  189. res = jsonify({'Err': str(e)}), 500
  190. finally:
  191. return res
  192. @app.route('/NetworkDriver.EndpointOperInfo', methods=['POST'])
  193. def endpoint_info():
  194. req = request.get_json(force=True)
  195. bridge = net_bridge(req['NetworkID'])
  196. if_host, _if_container = veth_pair(req['EndpointID'])
  197. if_host = interface.GetInterface(LIBRARY, if_host)
  198. return jsonify({
  199. 'bridge': bridge['ifname'],
  200. 'if_host': {
  201. 'name': if_host['ifname'],
  202. 'mac': if_host['address']
  203. }
  204. })
  205. @app.route('/NetworkDriver.DeleteEndpoint', methods=['POST'])
  206. def delete_endpoint():
  207. req = request.get_json(force=True)
  208. bridge = net_bridge(req['NetworkID'])
  209. if_host, _if_container = veth_pair(req['EndpointID'])
  210. if_host = interface.GetInterface(LIBRARY, if_host)
  211. interface.DelPort(LIBRARY, bridge.ifname, if_host.ifname)
  212. interface.RemoveInterface(LIBRARY, if_host.ifname)
  213. return jsonify({})
  214. @app.route('/NetworkDriver.Join', methods=['POST'])
  215. def join():
  216. req = request.get_json(force=True)
  217. network = req['NetworkID']
  218. endpoint = req['EndpointID']
  219. bridge = net_bridge(req['NetworkID'])
  220. _if_host, if_container = veth_pair(req['EndpointID'])
  221. res = {
  222. 'InterfaceName': {
  223. 'SrcName': if_container,
  224. 'DstPrefix': 'eth'
  225. },
  226. 'StaticRoutes': []
  227. }
  228. if endpoint in gateway_hints:
  229. gateway = gateway_hints[endpoint]
  230. logger.info('Setting IPv4 gateway from DHCP (%s)', gateway)
  231. res['Gateway'] = str(gateway)
  232. del gateway_hints[endpoint]
  233. ipv6 = ipv6_enabled(network)
  234. for route in bridge.routes:
  235. if route['type'] != rtypes['RTN_UNICAST'] or \
  236. (route['family'] == socket.AF_INET6 and not ipv6):
  237. continue
  238. if route['dst'] in ('', '/0'):
  239. if route['family'] == socket.AF_INET and 'Gateway' not in res:
  240. logger.info('Adding IPv4 gateway %s', route['gateway'])
  241. res['Gateway'] = route['gateway']
  242. elif route['family'] == socket.AF_INET6 and 'GatewayIPv6' not in res:
  243. logger.info('Adding IPv6 gateway %s', route['gateway'])
  244. res['GatewayIPv6'] = route['gateway']
  245. elif route['gateway']:
  246. dst = f'{route["dst"]}/{route["dst_len"]}'
  247. logger.info('Adding route to %s via %s', dst, route['gateway'])
  248. res['StaticRoutes'].append({
  249. 'Destination': dst,
  250. 'RouteType': 0,
  251. 'NextHop': route['gateway']
  252. })
  253. container_dhcp_clients[endpoint] = ContainerDHCPManager(network, endpoint)
  254. return jsonify(res)
  255. @app.route('/NetworkDriver.Leave', methods=['POST'])
  256. def leave():
  257. req = request.get_json(force=True)
  258. endpoint = req['EndpointID']
  259. if endpoint in container_dhcp_clients:
  260. container_dhcp_clients[endpoint].stop()
  261. del container_dhcp_clients[endpoint]
  262. return jsonify({})
  263. # Trying to grab the container's attributes (to get the network namespace)
  264. # will deadlock (since Docker is waiting on us), so we must defer starting
  265. # the DHCP client
  266. class ContainerDHCPManager:
  267. def __init__(self, network, endpoint):
  268. self.network = network
  269. self.endpoint = endpoint
  270. self.ipv6 = ipv6_enabled(network)
  271. self.dhcp = None
  272. self.dhcp6 = None
  273. self._thread = threading.Thread(target=self.run)
  274. self._thread.start()
  275. def _on_event(self, dhcp, event_type, _event):
  276. if event_type == udhcpc.EventType.DECONFIG:
  277. logger.info('[dhcp container] DECONFIG Event %s', _event)
  278. if path.lexists('{dhcp.netns}'):
  279. logger.info('[dhcp container] Flushing IP addresses')
  280. subprocess.check_call(['nsenter', f'-n{dhcp.netns}', '--', '/sbin/ip', 'address', 'flush', 'dev',
  281. str(dhcp.iface['ifname']), 'label', str(dhcp.iface['ifname'])],
  282. timeout=1, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
  283. else:
  284. logger.info('[dhcp container] Container gone, can\'t flush IP addresses')
  285. elif event_type == udhcpc.EventType.RENEW or event_type == udhcpc.EventType.BOUND:
  286. if event_type == udhcpc.EventType.RENEW:
  287. logger.info('[dhcp container] RENEW Event %s', _event)
  288. elif event_type == udhcpc.EventType.BOUND:
  289. logger.info('[dhcp container] BOUND Event %s', _event)
  290. logger.info('[dhcp container] Flushing IP addresses')
  291. subprocess.check_call(['nsenter', f'-n{dhcp.netns}', '--', '/sbin/ip', 'address', 'flush', 'dev',
  292. str(dhcp.iface['ifname']), 'label', str(dhcp.iface['ifname'])],
  293. timeout=1, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
  294. logger.info('[dhcp container] Adding IP addresses %s', dhcp.ip)
  295. subprocess.check_call(['nsenter', f'-n{dhcp.netns}', '--', '/sbin/ip', 'address', 'add', str(dhcp.ip), 'dev',
  296. str(dhcp.iface['ifname'])],
  297. timeout=1, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
  298. if dhcp.gateway:
  299. logger.info('[dhcp container] Replacing gateway with %s', dhcp.gateway)
  300. subprocess.check_call(['nsenter', f'-n{dhcp.netns}', '--', '/sbin/ip', 'route', 'replace', 'default', 'via',
  301. str(dhcp.gateway)],
  302. timeout=1, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
  303. else:
  304. logger.info('[dhcp container] Unhandled Event %s: %s', event_type,_event)
  305. def run(self):
  306. try:
  307. iface = await_endpoint_container_iface(self.network, self.endpoint)
  308. hostname = endpoint_container_hostname(self.network, self.endpoint)
  309. self.dhcp = udhcpc.DHCPClient(iface, event_listener=self._on_event, hostname=hostname)
  310. logger.info('Starting DHCPv4 client on %s in container namespace %s', iface['ifname'], \
  311. self.dhcp.netns)
  312. if self.ipv6:
  313. self.dhcp6 = udhcpc.DHCPClient(iface, v6=True, event_listener=self._on_event, hostname=hostname)
  314. logger.info('Starting DHCPv6 client on %s in container namespace %s', iface['ifname'], \
  315. self.dhcp6.netns)
  316. except Exception as e:
  317. logger.exception(e)
  318. if self.dhcp:
  319. self.dhcp.finish(timeout=1)
  320. def stop(self):
  321. if not self.dhcp:
  322. return
  323. try:
  324. logger.info('Shutting down DHCPv4 client on %s in container namespace %s', \
  325. self.dhcp.iface['ifname'], self.dhcp.netns)
  326. self.dhcp.finish(timeout=1)
  327. finally:
  328. try:
  329. if self.ipv6:
  330. logger.info('Shutting down DHCPv6 client on %s in container namespace %s', \
  331. self.dhcp6.iface['ifname'], self.dhcp.netns)
  332. self.dhcp6.finish(timeout=1)
  333. finally:
  334. self._thread.join()
  335. # we have to do this since the docker client leaks sockets...
  336. close_docker_client()
  337. get_docker_client()