network.py 14 KB

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