def start(): from datetime import datetime vm_state = state() if vm_state == State.NotInitialized: raise VMException("VM has not yet been initialized.") if vm_state == State.Running: logging.info("VM is already running.") return try: logging.info("Booting up...") console_file_name = os.path.join(config.vm_install_dir, "console.log") vbox.attach_serial_console(_VM_NAME, console_file_name) vbox.start_vm(_VM_NAME) util.sleep_for(10, show_spinner=True) logging.info("Waiting for the machine to be ready...") util.sleep_for(10, show_spinner=True) current_port = config.get_config(config.Key.ssh_port) host_ssh_port = vbox.setup_ssh_port_forwarding(_VM_NAME, current_port) config.set_config(config.Key.ssh_port, host_ssh_port) vbox.setup_lxd_port_forwarding(_VM_NAME) except (VBoxException, ConfigReadException) as e: logging.error(e.message) raise VMException("Start up failed")
def get_pylxd_client(): lxd_port = config.get_config(config.Key.lxd_port) try: return pylxd.Client(endpoint=f"http://127.0.0.1:{lxd_port}") except pylxd.exceptions.ClientConnectionFailed as e: logging.debug(e) raise LXCException( "Error connecting to LXD. Try restarting the VM: 'yurt vm restart'")
def _get_ssh_connection(port=None): from fabric import Connection if not port: port = config.get_config(config.Key.ssh_port) return Connection( "localhost", user=config.ssh_user_name, port=port, connect_kwargs={"key_filename": config.ssh_private_key_file})
def _connection(): connection = FabricConnection( "localhost", user=config.user_name, port=config.get_config(config.Key.ssh_port), connect_kwargs={"key_filename": config.ssh_private_key_file} ) try: yield connection finally: connection.close()
def get_ip_config(): from ipaddress import ip_interface host_ip_address = config.get_config( config.Key.interface_ip_address) network_mask = config.get_config( config.Key.interface_netmask) if not (host_ip_address and network_mask): raise LXCException("Bad IP Configuration. ip: {0}, mask: {1}".format( host_ip_address, network_mask)) full_host_address = ip_interface( "{0}/{1}".format(host_ip_address, network_mask)) bridge_address = ip_interface( "{0}/{1}".format((full_host_address + 1).ip, network_mask)).exploded return { "bridgeAddress": bridge_address, "dhcpRangeLow": (full_host_address + 10).ip.exploded, "dhcpRangeHigh": (full_host_address + 249).ip.exploded }
def exec_interactive(instance_name: str, cmd: List[str], environment=None): from . import term instance = get_instance(instance_name) response = instance.raw_interactive_execute(cmd, environment=environment) lxd_port = config.get_config(config.Key.lxd_port) try: ws_url = f"ws://127.0.0.1:{lxd_port}{response['ws']}" term.run(ws_url) except KeyError as e: raise LXCException(f"Missing ws URL {e}")
def destroy(): vm_name = util.vm_name() try: vbox.destroy_vm(vm_name) interface_name = config.get_config(config.Key.interface) vbox.remove_hostonly_interface(interface_name) config.clear() except VBoxException as e: logging.error(e.message) raise VMException("Failed to destroy VM.")
def destroy(): global _VM_NAME try: vbox.destroy_vm(_VM_NAME) interface_name = config.get_config(config.Key.interface) vbox.remove_hostonly_interface(interface_name) _VM_NAME = None config.clear() except VBoxException as e: logging.error(e.message) raise VMException("Failed to destroy VM.")
import logging from enum import Enum import shutil import os from yurt import util, config from . import vbox from yurt.exceptions import (ConfigReadException, ConfigWriteException, VMException, VBoxException, YurtException) _VM_NAME = config.get_config(config.Key.vm_name) class State(Enum): NotInitialized = 1 Stopped = 2 Running = 3 def state(): if _VM_NAME: try: vm_info = vbox.get_vm_info(_VM_NAME) is_running = vm_info["VMState"].strip('"') == "running" return State.Running if is_running else State.Stopped except (VBoxException, KeyError) as e: logging.debug(e) raise VMException("An error occurred while fetching VM status.") return State.NotInitialized
def ssh_vm(): import subprocess ssh_port = config.get_config(config.Key.ssh_port) subprocess.run( f"ssh -i {config.ssh_private_key_file} yurt@localhost -p {ssh_port}", )
def is_initialized(): return config.get_config(config.Key.is_lxd_initialized)
def launch_ssh(): import subprocess ssh_port = config.get_config(config.Key.ssh_port) subprocess.run( f"ssh -i {config.ssh_private_key_file} [email protected] -p {ssh_port}", )
def vm_name(): name = config.get_config(config.Key.vm_name) if not name: raise VMException("VM name has not yet been set.") return name