|
| 1 | +import logging |
| 2 | + |
| 3 | +from virttest import utils_misc |
| 4 | +from virttest.vt_utils.net import interface, tap |
| 5 | +from virttest.vt_utils.net.drivers import bridge |
| 6 | + |
| 7 | +from ...backing import _ResourceBacking |
| 8 | + |
| 9 | +LOG = logging.getLogger("avocado.service.resource_backings.network.tap" + __name__) |
| 10 | + |
| 11 | + |
| 12 | +class _TapPortBacking(_ResourceBacking): |
| 13 | + _SOURCE_POOL_TYPE = "linux_bridge" |
| 14 | + _BINDING_RESOURCE_TYPE = "port" |
| 15 | + |
| 16 | + def __init__(self, backing_config): |
| 17 | + super().__init__(backing_config) |
| 18 | + self.switch = None |
| 19 | + self.tap_fd = None |
| 20 | + self.tap_ifname = None |
| 21 | + |
| 22 | + def create(self, network_connection): |
| 23 | + if not self.switch: |
| 24 | + self.switch = network_connection.switch |
| 25 | + |
| 26 | + def destroy(self, network_connection): |
| 27 | + super().destroy(network_connection) |
| 28 | + self.switch = None |
| 29 | + |
| 30 | + def allocate_resource(self, network_connection, arguments=None): |
| 31 | + """ |
| 32 | + Create a tap device and put this device in to network_connection. |
| 33 | +
|
| 34 | + :params network_connection: the _TapNetworkConnection object. |
| 35 | + :type network_connection: class _TapNetworkConnection. |
| 36 | + :params arguments: the device's params |
| 37 | + :type arguments: dict. |
| 38 | +
|
| 39 | + :return: the resource info. |
| 40 | + :rtype: dict. |
| 41 | + """ |
| 42 | + if not self.tap_ifname: |
| 43 | + self.tap_ifname = "tap_" + utils_misc.generate_random_string(8) |
| 44 | + self.tap_fd = tap.open_tap("/dev/net/tun", self.tap_ifname, vnet_hdr=True) |
| 45 | + self.tap_fd = self.tap_fd.split(":") |
| 46 | + interface.bring_up_ifname(self.tap_ifname) |
| 47 | + bridge.add_to_bridge(self.tap_ifname, self.switch) |
| 48 | + |
| 49 | + return self.get_resource_info(network_connection) |
| 50 | + |
| 51 | + def release_resource(self, network_connection, arguments=None): |
| 52 | + bridge.del_from_bridge(self.tap_ifname) |
| 53 | + interface.bring_down_ifname(self.tap_ifname) |
| 54 | + self.tap_fd = None |
| 55 | + self.tap_ifname = None |
| 56 | + |
| 57 | + return self.get_resource_info(network_connection) |
| 58 | + |
| 59 | + def get_resource_info(self, network_connection=None, arguments=None): |
| 60 | + if self.switch and self.tap_fd and self.tap_ifname: |
| 61 | + allocated = ( |
| 62 | + True |
| 63 | + if self.switch in (bridge.find_bridge_name(self.tap_ifname),) |
| 64 | + else False |
| 65 | + ) |
| 66 | + else: |
| 67 | + allocated = False |
| 68 | + |
| 69 | + return { |
| 70 | + "meta": { |
| 71 | + "allocated": allocated, |
| 72 | + }, |
| 73 | + "spec": { |
| 74 | + "switch": self.switch, |
| 75 | + "fds": self.tap_fd, |
| 76 | + "ifname": self.tap_ifname, |
| 77 | + }, |
| 78 | + } |
0 commit comments