From d81b39c74c140adf012a69a0110de9099302e41b Mon Sep 17 00:00:00 2001 From: FrantiĊĦek Zatloukal Date: Feb 26 2018 14:49:48 +0000 Subject: Add instance clean command testcloud instance clean will remove instances that no longer exist in libvirt --- diff --git a/testcloud/cli.py b/testcloud/cli.py index 27c74a9..dc0300c 100644 --- a/testcloud/cli.py +++ b/testcloud/cli.py @@ -156,6 +156,15 @@ def _remove_instance(args): tc_instance.remove(autostop=args.force) +def _clean_instances(args): + """Handler for 'instance clean' command. Expects the following elements in args: + * name(str) + + :param args: args from argparser + """ + + instance.clean_instances() + def _reboot_instance(args): """Handler for 'instance reboot' command. Expects the following elements in args: @@ -256,6 +265,11 @@ def get_argparser(): help="Stop the instance if it's running", action="store_true") instarg_destroy.set_defaults(func=_remove_instance) + + # instance clean + instarg_clean = instarg_subp.add_parser("clean", help="remove non-existing libvirt vms from testcloud") + instarg_clean.set_defaults(func=_clean_instances) + # instance reboot instarg_reboot = instarg_subp.add_parser("reboot", help="reboot instance") instarg_reboot.add_argument("name", diff --git a/testcloud/instance.py b/testcloud/instance.py index 8eb6bb7..8d319f6 100644 --- a/testcloud/instance.py +++ b/testcloud/instance.py @@ -144,7 +144,7 @@ def list_instances(connection='qemu:///system'): for instance in all_instances: if instance['name'] not in domains.keys(): - log.warn('{} is not registered, might want to delete it.'.format(instance['name'])) + log.warn("{} is not registered, might want to delete it via 'testcloud instance clean'.".format(instance['name'])) instance['state'] = 'de-sync' instances.append(instance) @@ -158,6 +158,20 @@ def list_instances(connection='qemu:///system'): return instances +def clean_instances(connection='qemu:///system'): + """ + Removes all instances in 'de-sync' state. + """ + domains = _list_domains(connection) + all_instances = _list_instances() + + for instance in all_instances: + if instance['name'] not in domains.keys(): + log.debug("Removing de-synced instance {}".format(instance['name'])) + instance_path = "{}/instances/{}".format(config_data.DATA_DIR, instance['name']) + + # remove from disk + shutil.rmtree(instance_path) class Instance(object): """Handles creating, starting, stopping and removing virtual machines