def vm_names_by_cluster(running_only: bool = False) -> Dict[str, Set[str]]: """ Return a mapping of Cluster IDs to the names of VMs in those clusters. Args: running_only: If ``True`` only return running VMs. """ ls_output = bytes(vertigo_py.ls(option='vms')) # type: ignore lines = ls_output.decode().strip().split('\n') lines = [line for line in lines if line] result = defaultdict(set) # type: Dict[str, Set[str]] for line in lines: vm_name_in_quotes, _ = line.rsplit(' ', 1) vm_name = vm_name_in_quotes[1:-1] state = _state_from_vm_name(vm_name=vm_name) description = _description_from_vm_name(vm_name=vm_name) try: data = json.loads(s=description) except json.decoder.JSONDecodeError: continue if running_only and state != 'running': # We do not show e.g. aborted VMs when listing clusters. # For example, a VM is aborted when the host is rebooted. # This is problematic as we cannot assume that the workspace # directory, # which might be in /tmp/ is still there. # # We do not show paused VMs when listing clusters. # A VM can be manually paused. # This can be problematic if someone pauses a VM, then creates a # new one with the same cluster ID. # However, we work on the assumption that a user will not manually # interfere with VirtualBox. continue # A VM is in a cluster if it has a description and that description is # valid JSON and has a known key. cluster_id = data.get(CLUSTER_ID_DESCRIPTION_KEY) if cluster_id is None: continue result[cluster_id].add(vm_name) return result
def existing_cluster_ids() -> Set[str]: """ Return the IDs of existing clusters. """ ls_output = vertigo_py.ls() # type: ignore vm_ls_output = ls_output['vms'] lines = vm_ls_output.decode().strip().split('\n') lines = [line for line in lines if line] cluster_ids = set() for line in lines: vm_name_in_quotes, _ = line.split(' ') vm_name = vm_name_in_quotes[1:-1] description = _description_from_vm_name(vm_name=vm_name) try: data = json.loads(s=description) except json.decoder.JSONDecodeError: continue cluster_id = data.get(CLUSTER_ID_DESCRIPTION_KEY) cluster_ids.add(cluster_id) return cluster_ids - set([None])
def _vm_names(self) -> Set[str]: """ Return VirtualBox and Vagrant names of VMs in this cluster. """ ls_output = vertigo_py.ls() # type: ignore vm_ls_output = ls_output['vms'] lines = vm_ls_output.decode().strip().split('\n') lines = [line for line in lines if line] vm_names = set() for line in lines: vm_name_in_quotes, _ = line.split(' ') vm_name = vm_name_in_quotes[1:-1] description = _description_from_vm_name(vm_name=vm_name) try: data = json.loads(s=description) except json.decoder.JSONDecodeError: continue cluster_id = data.get(CLUSTER_ID_DESCRIPTION_KEY) if cluster_id == self._cluster_id: vm_names.add(vm_name) return vm_names