From ad87982cf0a7bca5c1fa45d8146828d284a595a8 Mon Sep 17 00:00:00 2001 From: meow Date: Thu, 5 Dec 2019 18:30:41 +0500 Subject: [PATCH] ucloud now logs to /etc/ucloud/log.txt, delete network interfaces on stopping of VMs --- bin/ucloud | 2 +- ucloud/common/vm.py | 5 ++++ ucloud/host/virtualmachine.py | 45 +++++++++++++++++++++++++++++++++++ 3 files changed, 51 insertions(+), 1 deletion(-) diff --git a/bin/ucloud b/bin/ucloud index 0d4309a..7be6b24 100644 --- a/bin/ucloud +++ b/bin/ucloud @@ -19,7 +19,7 @@ if __name__ == "__main__": logging.basicConfig( level=logging.DEBUG, - filename=join_path("logs.txt"), + filename=join_path("/", "etc", "ucloud", "log.txt"), filemode="a", format="%(name)s %(asctime)s: %(levelname)s - %(message)s", datefmt="%d-%b-%y %H:%M:%S", diff --git a/ucloud/common/vm.py b/ucloud/common/vm.py index 1f5e43e..0fb5cea 100644 --- a/ucloud/common/vm.py +++ b/ucloud/common/vm.py @@ -65,6 +65,11 @@ class VmPool: _vms = self.vms return list(filter(lambda x: x.status == status, _vms)) + def by_owner(self, owner, _vms=None): + if _vms is None: + _vms = self.vms + return list(filter(lambda x: x.owner == owner, _vms)) + def except_status(self, status, _vms=None): if _vms is None: _vms = self.vms diff --git a/ucloud/host/virtualmachine.py b/ucloud/host/virtualmachine.py index bb26d25..7524083 100755 --- a/ucloud/host/virtualmachine.py +++ b/ucloud/host/virtualmachine.py @@ -38,6 +38,50 @@ class VM: return "VM({})".format(self.key) +def delete_network_interface(iface): + try: + sp.check_output(['ip', 'link', 'del', iface]) + except Exception: + pass + + +def resolve_network(network_name, network_owner): + network = etcd_client.get(join_path(env_vars.get("NETWORK_PREFIX"), + network_owner, + network_name), + value_in_json=True) + return network + + +def delete_vm_network(vm_entry): + try: + for network in vm_entry.network: + network_name = network[0] + tap_mac = network[1] + tap_id = network[2] + + delete_network_interface('tap{}'.format(tap_id)) + + owners_vms = vm_pool.by_owner(vm_entry.owner) + owners_running_vms = vm_pool.by_status(VMStatus.running, + _vms=owners_vms) + + networks = map(lambda n: n[0], + map(lambda vm: vm.network, owners_running_vms) + ) + networks_in_use_by_user_vms = [vm[0] for vm in networks] + if network_name not in networks_in_use_by_user_vms: + network_entry = resolve_network(network[0], vm_entry.owner) + if network_entry: + network_type = network_entry.value["type"] + network_id = network_entry.value["id"] + if network_type == "vxlan": + delete_network_interface('br{}'.format(network_id)) + delete_network_interface('vxlan{}'.format(network_id)) + except Exception: + logger.exception("Exception in network interface deletion") + + def create_dev(script, _id, dev, ip=None): command = [script, _id, dev] if ip: @@ -237,6 +281,7 @@ def stop(vm_entry): vm_entry.declare_stopped() vm_pool.put(vm_entry) running_vms.remove(vm) + delete_vm_network(vm_entry) def delete(vm_entry):