network.py 14 KB

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