Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
for serial in self.params.objects("isa_serials"):
self.serial_ports.append(serial)
if self.serial_console is None:
try:
cmd = 'virsh'
if self.connect_uri:
cmd += ' --uri=%s' % self.connect_uri
cmd += (" console %s %s" % (self.name, self.serial_ports[0]))
except IndexError:
raise virt_vm.VMConfigMissingError(self.name, "isa_serial")
output_func = utils_misc.log_line # Because qemu-kvm uses this
# Because qemu-kvm hard-codes this
output_filename = self.get_serial_console_filename(self.serial_ports[0])
output_params = (output_filename,)
prompt = self.params.get("shell_prompt", "[\#\$]")
self.serial_console = aexpect.ShellSession(command=cmd, auto_close=False,
output_func=output_func,
output_params=output_params)
# Cause serial_console.close() to close open log file
self.serial_console.set_log_file(output_filename)
self.serial_ports.append(serial)
if self.serial_console is None or self.serial_console.closed:
try:
cmd = 'virsh'
if self.connect_uri:
cmd += ' -c %s' % self.connect_uri
cmd += (" console %s %s" % (self.name, self.serial_ports[0]))
except IndexError:
raise virt_vm.VMConfigMissingError(self.name, "serial")
output_func = utils_misc.log_line # Because qemu-kvm uses this
# Because qemu-kvm hard-codes this
output_filename = self.get_serial_console_filename(self.serial_ports[0])
output_params = (output_filename,)
prompt = self.params.get("shell_prompt", "[\#\$]")
logging.debug("Command used to create serial console: %s", cmd)
self.serial_console = aexpect.ShellSession(command=cmd, auto_close=False,
output_func=output_func,
output_params=output_params,
prompt=prompt)
if not self.serial_console.is_alive():
logging.error("Failed to create serial_console")
# Cause serial_console.close() to close open log file
self.serial_console.set_log_file(output_filename)
self.serial_console_log = os.path.join(utils_misc.get_log_file_dir(),
output_filename)
vcpu_thread_pattern = params.get("vcpu_thread_pattern",
"thread_id=(\d+)")
self.vcpu_threads = re.findall(vcpu_thread_pattern, str(o))
o = commands.getoutput("ps aux")
self.vhost_threads = re.findall("\w+\s+(\d+)\s.*\[vhost-%s\]" %
self.get_pid(), o)
# Establish a session with the serial console
# Let's consider the first serial port as serial console.
# Note: requires a version of netcat that supports -U
try:
tmp_serial = self.serial_ports[0]
except IndexError:
raise virt_vm.VMConfigMissingError(name, "isa_serial")
self.serial_console = aexpect.ShellSession(
"nc -U %s" % self.get_serial_console_filename(tmp_serial),
auto_close=False,
output_func=utils_misc.log_line,
output_params=("serial-%s-%s.log" % (tmp_serial, name),),
prompt=self.params.get("shell_prompt", "[\#\$]"))
del tmp_serial
for key, value in self.logs.items():
outfile = "%s-%s.log" % (key, name)
self.logsessions[key] = aexpect.Tail(
"nc -U %s" % value,
auto_close=False,
output_func=utils_misc.log_line,
output_params=(outfile,))
self.logsessions[key].set_log_file(outfile)
"""
Log into the hypervisor using required URIs .
@timeout: Time in seconds that we will wait before giving up on logging
into the host.
@return: A ShellSession object.
"""
if self.driver is None:
uri = utils.system_output('%s uri' % self.virsh_exec)
else:
uri = "%s+ssh://%s@%s/system" % (self.driver, self.username,
self.host)
command = "%s --connect %s" % (self.virsh_exec, uri)
session = aexpect.ShellSession(command, linesep=self.linesep,
prompt=self.prompt)
if self.username is not None:
try:
remote._remote_login(session, self.username, self.password,
self.prompt, timeout)
except aexpect.ShellError:
session.close()
session = None
return session
# Make qemu command
install_command = self.__make_libvirt_command()
logging.info("Running libvirt command (reformatted):")
for item in install_command.replace(" -", " \n -").splitlines():
logging.info("%s", item)
utils.run(install_command, verbose=False)
# Wait for the domain to be created
utils_misc.wait_for(func=self.is_alive, timeout=60,
text=("waiting for domain %s to start" %
self.name))
self.uuid = virsh.domuuid(self.name, uri=self.connect_uri)
# Establish a session with the serial console
if self.only_pty == True:
self.serial_console = aexpect.ShellSession(
"virsh console %s" % self.name,
auto_close=False,
output_func=utils_misc.log_line,
output_params=("serial-%s.log" % name,))
else:
self.serial_console = aexpect.ShellSession(
"tail -f %s" % self.get_serial_console_filename(),
auto_close=False,
output_func=utils_misc.log_line,
output_params=("serial-%s.log" % name,))
finally:
fcntl.lockf(lockfile, fcntl.LOCK_UN)
lockfile.close()
def login_guest(guestname, username, password, logger):
cmd = "virsh console %s --force" % guestname
session = aexpect.ShellSession(cmd)
try:
while True:
match, text = session.read_until_last_line_matches(
[r"[E|e]scape character is", r"login:",
r"[P|p]assword:", session.prompt],
10, internal_timeout=1)
if match == 0:
logger.debug("Got '^]', sending '\\n'")
session.sendline()
elif match == 1:
logger.debug("Got 'login:', sending '%s'", username)
session.sendline(username)
elif match == 2:
logger.debug("Got 'Password:', sending '%s'", password)
session.sendline(password)
elif match == 3:
Execute built-in command in a complete guestfish command
(Not a guestfish session).
command: guestfish [--options] [commands]
"""
guestfs_exec = self.__dict_get__('lgf_exec')
ignore_status = self.__dict_get__('ignore_status')
debug = self.__dict_get__('debug')
timeout = self.__dict_get__('timeout')
if command:
guestfs_exec += " %s" % command
return lgf_command(guestfs_exec, ignore_status, debug, timeout)
else:
raise LibguestfsCmdError("No built-in command was passed.")
class GuestfishSession(aexpect.ShellSession):
"""
A shell session of guestfish.
"""
# Check output against list of known error-status strings
ERROR_REGEX_LIST = ['libguestfs: error:\s*']
def __init__(self, guestfs_exec=None, a_id=None, prompt=r">\s*"):
"""
Initialize guestfish session server, or client if id set.
:param guestfs_cmd: path to guestfish executable
:param id: ID of an already running server, if accessing a running
server, or None if starting a new one.
:param prompt: Regular expression describing the shell's prompt line.
def __getitem__(self, key):
"""
Look up key's value on instance, then parent instance attributes
@param: key: key to look up non-None value
@raises: KeyError: When value is None, undefined locally or on parent.
"""
try:
return super(DArgMangler, self).__getitem__(key)
except KeyError:
# Assume parent raises KeyError if value == None
return self._parent.__getitem__(key)
class VirshSession(aexpect.ShellSession):
"""
A virsh shell session, used with Virsh instances.
"""
# No way to get virsh sub-command "exit" status
# Check output against list of known error-status strings
ERROR_REGEX_LIST = ['error:\s*', 'failed']
def __init__(self, virsh_exec=None, uri=None, id=None,
prompt=r"virsh\s*\#\s*"):
"""
Initialize virsh session server, or client if id set.
@param: virsh_exec: path to virsh executable
@param: uri: uri of libvirt instance to connect to
@param: id: ID of an already running server, if accessing a running
@raise: Whatever _remote_login() raises
@return: A ShellSession object.
"""
if client == "ssh":
cmd = ("ssh -o UserKnownHostsFile=/dev/null "
"-o PreferredAuthentications=password -p %s %s@%s" %
(port, username, host))
elif client == "telnet":
cmd = "telnet -l %s %s %s" % (username, host, port)
elif client == "nc":
cmd = "nc %s %s" % (host, port)
else:
raise LoginBadClientError(client)
logging.debug("Login command: '%s'", cmd)
session = aexpect.ShellSession(cmd, linesep=linesep, prompt=prompt)
try:
_remote_login(session, username, password, prompt, timeout)
except Exception:
session.close()
raise
if log_filename:
session.set_output_func(utils_misc.log_line)
session.set_output_params((log_filename,))
return session
def cmd_output(self, command, timeout=60):
"""
Get output from shell session. If the create flag is True, init the
shell session and set the create flag to False.
@param command: command to execute in qemu-io
@param timeout: timeout for execute the command
"""
qemu_io_cmd = self.qemu_io_cmd
prompt = self.prompt
output_func = self.output_func
output_params = self.output_params
output_prefix = self.output_prefix
if self.create_session:
error.context("Running command: %s" % qemu_io_cmd, self.log_func)
self.session = aexpect.ShellSession(qemu_io_cmd, echo=True,
prompt=prompt,
output_func=output_func,
output_params=output_params,
output_prefix=output_prefix)
# Record the command line in log file
if self.output_func:
params = self.output_params + (qemu_io_cmd, )
self.output_func(*params)
self.create_session = False
# Get the reaction from session
self.session.cmd_output("\n")
error.context("Executing command: %s" % command, self.log_func)
return self.session.cmd_output(command, timeout=timeout)