App-FuguVM

 view release on metacpan or  search on metacpan

lib/App/FuguVM/Guest.pm  view on Meta::CPAN

		$log->info("VM '$config->{name}' is already running");
		return EXIT_SUCCESS;
	}

	# The version gate runs one time for each invocation, before
	# any expensive work starts.
	my $failure = $self->_check_qemu_version;
	return $failure if defined $failure;

	# Verify the backing chain of the disk before other checks read
	# the disk. A base image that is missing from the cache is not
	# corruption. The unclean-shutdown check below would report it as
	# corruption and recommend 'fuguvm disk repair'. That command
	# cannot make a missing backing file again.
	if ( $state->disk_exists && !$self->_verify_backing_chain ) {
		return EXIT_ERROR;
	}

	# Check for an unclean shutdown. Then check the disk integrity.
	if ( $state->was_unclean_shutdown ) {
		$log->warning("Detected unclean shutdown, checking disk...");
		my $disk  = App::FuguVM::Disk->new( $state->state_dir );
		my $check = $disk->check( $config->{name} );

		if ( defined $check && $check->{status} ne 'ok' ) {
			$log->error(
"Disk corruption detected. Run 'fuguvm disk repair' to fix"
			);
			return EXIT_ERROR;
		}
		$state->clear_shutdown_state;
	}

	# The mode decides the origin of the disk. The configuration
	# loader derives the value, and no module compares the
	# directives again.
	my $mode = $config->{install_mode} // 'expect';

	# Derive the installed-image cache key one time only, before the
	# installer runs. key() hashes its script at call time. An
	# install takes tens of minutes. A key derived again after the
	# install would publish the image the OLD installer made under
	# the NEW digest.
	my $cache     = $self->_image_cache;
	my $cache_key = defined $cache ? $cache->key($config) : undef;

	# An imported base lives in the cache, so the import mode
	# cannot run without one. The configuration loader refuses
	# 'image_cache no'; this check covers 'up --no-cache'.
	if ( $mode eq 'import' && !defined $cache ) {
		$log->error(  "base_disk needs the image cache;"
			    . " run 'fuguvm up' without --no-cache" );
		return EXIT_CONFIG_ERROR;
	}
	if ( $mode eq 'import' && !defined $cache_key ) {
		$log->error("Cannot derive the cache key of the imported base");
		return EXIT_ERROR;
	}

	# Outside the expect mode the operator owns the credential.
	# Seed the state from root_password_file, so the SSH key setup
	# can authenticate. The state then behaves as after an expect
	# install.
	if ( $mode ne 'expect' && defined $config->{root_password_file} ) {
		my $password = $self->_root_password;
		$state->set_root_password($password) if defined $password;
	}

	# Restore from the installed-image cache when there is no disk
	# yet. A miss can mean that a sibling run installs this entry
	# right now. The lock makes this run wait, and the second lookup
	# then uses the entry that the sibling published. A run without
	# the lock still installs correctly, because store() is
	# write-once: it wastes an install, never the cache.
	my $cache_lock;
	if ( !$state->disk_exists && defined $cache_key ) {
		if ( !$self->_cache_restore( $cache, $cache_key ) ) {

			# The wait can last as long as one installation,
			# so the operator hears about it first.
			$log->info("Taking the image-cache lock of $cache_key");
			$cache_lock = $cache->lock_entry($cache_key);
			if ( !defined $cache_lock ) {
				$log->warning(
"Image-cache lock not acquired, installing without it"
				);
			}
			elsif ( $self->_cache_restore( $cache, $cache_key ) ) {

				# The entry exists now, so nothing here
				# installs. Release the lock at once: a
				# sibling behind it needs only the entry.
				close $cache_lock;
				undef $cache_lock;
			}

			# The import mode installs nothing: publish the
			# outside file as the entry, then overlay it. The
			# lock above serializes the publication, so a
			# parallel fleet publishes one time.
			if ( !$state->disk_exists && $mode eq 'import' ) {
				my $imported =
				    $self->_import_base( $cache, $cache_key )
				    && $self->_cache_restore( $cache,
					$cache_key );
				if ( defined $cache_lock ) {
					close $cache_lock;
					undef $cache_lock;
				}
				return EXIT_ERROR if !$imported;
			}
		}
	}

	# Start the caching proxy for the VM installation. The VM
	# downloads its packages through the proxy. The first run also
	# uses the proxy to download the miniroot image.
	my $proxy = $self->_ensure_proxy;
	my $proxy_vm_url;    # For downloads inside the OpenBSD guest

	if ( defined $proxy ) {
		$proxy_vm_url = $proxy->guest_url;
		$log->info("Proxy started: $proxy_vm_url");
	}
	else {
		$log->info(

lib/App/FuguVM/Guest.pm  view on Meta::CPAN

		$image_path = $image->ensure;

		if ( !defined $image_path ) {
			my $url = $image->url;
			$log->error(
"Failed to get a verified image for OpenBSD $config->{version}"
			);
			$log->error( $mirror->error ) if defined $mirror->error;
			$log->error("URL: $url");
			return EXIT_ERROR;
		}

		$log->info("Using cached image: $image_path");
	}

	# Make sure that the disk exists
	my $disk_path = $state->disk_path;

	if ( !$state->disk_exists ) {
		$log->info("Creating disk image ($config->{disk_size})...");
		my $disk = App::FuguVM::Disk->new( $state->state_dir );
		my $result =
		    $disk->create( $config->{name}, $config->{disk_size} );
		if ( !defined $result ) {
			$log->error("Failed to create disk");
			return EXIT_ERROR;
		}
	}

	# Resolve and record the ports directly before the spawn. An
	# 'up' that failed above then reserves no port for a guest
	# that never started.
	$failure = $self->_resolve_ports;
	return $failure if defined $failure;

	# Start the VM
	$log->info("Starting VM...");

	# Attach the install media only when the system is not installed
	my $boot_image = $state->is_installed ? undef : $image_path;
	my $pid        = $self->_start_qemu($boot_image);
	if ( !defined $pid ) {
		$log->error("Failed to start VM");
		return EXIT_ERROR;
	}

	$log->info("Started $config->{name} (PID: $pid)");

	# Install the system if necessary
	if ( !$state->is_installed ) {

		# The proxy already runs. The code above started it for the
		# image download. Use the VM-accessible URL for the
		# installation. The VM connects to the host through the
		# gateway.
		my $install_proxy_url = $proxy_vm_url // 'none';

		# The tool owns the credential in the expect mode only.
		# In the autoinstall mode the response file owns it, and
		# the seeding above stored the operator's copy.
		my $root_password;
		if ( $mode eq 'expect' ) {
			$root_password = $self->_root_password;
			$state->set_root_password($root_password);
		}
		else {
			$root_password = $state->get_root_password;
		}

		$log->info("Installing OpenBSD...");
		my $expect = App::FuguVM::Console->new(
			host => $self->connect_address,
			port => $self->console_port,
		);

		if ( $mode eq 'autoinstall' ) {
			my $failure =
			    $self->_run_autoinstall( $expect, $proxy_vm_url );
			return $failure if defined $failure;
		}
		else {
			# Use the generated password for the installation
			my $ok = $expect->run_install(
				$self->_install_config(
					$root_password, $install_proxy_url
				) );
			if ( !$ok ) {
				$log->error("Installation failed");
				return EXIT_EXPECT_FAILED;
			}
		}

		$state->mark_installed( $config->{arch} );
		$log->info("Installation complete");

		# Stop the VM gracefully through QMP. The image cache
		# captures the disk at exactly this point: installed,
		# pristine, and without the per-checkout SSH key. Thus the
		# capture must know that QEMU is really gone. It must not
		# assume it.
		$log->info("Stopping installation VM...");
		$self->_qmp_quit;
		my $clean_exit = $self->_wait_exit(30);

		if ( !$clean_exit ) {
			$log->warning(
"Installation VM did not exit on request, force stopping"
			);
			$self->_force_stop;
			$self->_wait_exit(10);
		}
		$state->clear_vm_pid;

		# The runtime record stays: the restart below uses the
		# same ports, and a sibling that resolves ports in this
		# window must still skip them.

		# Publish the installed disk as a cached base image. A VM
		# that was force stopped can leave the disk mid-write. Thus
		# the code skips that capture and does not publish it.
		if ( defined $cache_key ) {
			if ($clean_exit) {
				$self->_cache_store( $cache, $cache_key,
					$root_password );
			}
			else {
				$log->warning(
"Skipping image cache: installation VM was force stopped"
				);
			}
		}

		# The entry is published, or this run cannot publish it.
		# Either way a waiting sibling can proceed now.
		if ( defined $cache_lock ) {
			close $cache_lock;
			undef $cache_lock;
		}

		# Restart the VM without the install media
		$log->info("Restarting installed system...");
		$pid = $self->_start_qemu;    # No boot image, no exit_on_halt
		if ( !defined $pid ) {
			$log->error("Failed to restart VM");
			return EXIT_ERROR;
		}
		$log->info("Started $config->{name} (PID: $pid)");

		# Install the SSH authorized key for future key-based
		# authentication. Outside the expect mode a guest can
		# carry no configured key: the image must trust the key
		# of the operator already, and the wait below proves it.
		if ( $mode eq 'expect' || $self->_needs_ssh_key_update ) {
			return $self->_complete_ssh_setup;
		}
	}

	# The VM is installed. Check if the SSH key must be installed or
	# updated.
	if ( $self->_needs_ssh_key_update ) {

		# The SSH key is not installed, or it changed in the
		# configuration. Use password authentication to wait for
		# SSH. Then install the key.
		return $self->_complete_ssh_setup;
	}

	# Wait for SSH. An installed VM uses key-based authentication.
	$log->info("Waiting for SSH...");
	if ( !$self->wait_ssh(120) ) {
		$log->error("Timeout waiting for SSH");
		return EXIT_TIMEOUT;
	}

	$log->info("VM ready");
	return EXIT_SUCCESS;
}

# $self->_image_cache:
#	Return the installed-image cache for this VM's configured
#	cache_dir. Return undef when caching is off. 'up --no-cache'
#	turns caching off for a single invocation. 'image_cache no'
#	turns it off in the configuration. Both stop restore and save
#	together. A half-cached run would leave an overlay with a base
#	that nothing published.
sub _image_cache ($self)
{
	return if $self->{no_cache};

	my $enabled = $self->{config}{image_cache};
	return if defined $enabled && !$enabled;

	return App::FuguVM::DiskCache->new( $self->_cache_dir );
}

# $self->_verify_backing_chain:
#	Make sure that the backing image of the working disk, if the
#	disk has one, is present. Return true when the chain resolves.
#	On a break, log the missing file and a remedy, and return
#	false. Thus a pruned or evicted cache entry fails with an
#	explanation, not with an opaque QEMU open error at boot.
sub _verify_backing_chain ($self)
{
	my $config = $self->{config};
	my $state  = $self->{state};
	my $log    = $self->{log};

	my $disk    = App::FuguVM::Disk->new( $state->state_dir );
	my $backing = $disk->backing_file( $config->{name} );
	return 1 if !defined $backing;
	return 1 if -f $backing;

	$log->error("Backing image missing: $backing");

	my $cache_dir = $self->_cache_dir;
	if ( index( $backing, "$cache_dir/" ) == 0 ) {
		$log->error(
"The image cache no longer holds this disk's base image."
		);
	}
	$log->error("Run 'fuguvm destroy' and 'fuguvm up' to rebuild the VM.");

	return 0;
}

# $self->_cache_restore($cache, $key):
#	Create the working disk as an overlay on a cached base image.
#	Seed the state that the installation would have written. Return
#	true on a cache hit. Return false on a miss or on any failure.
#	In both cases the caller then installs from scratch.
sub _cache_restore ( $self, $cache, $key )
{
	my $config = $self->{config};
	my $state  = $self->{state};
	my $log    = $self->{log};

	my $hit = $cache->lookup($key);
	if ( !defined $hit ) {
		$log->info("No cached image for $key, installing");
		return 0;
	}

	my $disk = App::FuguVM::Disk->new( $state->state_dir );
	my $path =
	    $disk->create( $config->{name}, undef, $hit->{base} );
	if ( !defined $path ) {
		$log->warning(
			"Cannot overlay cached image $key, installing instead");
		return 0;
	}

	# The base was captured from an installed system. Thus the state
	# that the installer would have written comes from the metadata
	# of the base. The later SSH key install authenticates with the
	# root password. That password is baked into the image.
	$state->mark_installed( $config->{arch} );
	my $password = $hit->{meta}{root_password};
	$state->set_root_password($password) if defined $password;
	$state->data->{cached_from} = $key;
	$state->save;

	$log->info("Using cached image $key");
	return 1;
}

# $self->_cache_store($cache, $key, $root_password):
#	Publish the freshly installed disk as a cached base image. Then
#	replace the working disk with an overlay on that image. The
#	operation is best effort. On any failure it keeps the
#	standalone disk in place and warns. 'up' must never fail
#	because caching failed.
sub _cache_store ( $self, $cache, $key, $root_password )
{
	my $config = $self->{config};
	my $state  = $self->{state};
	my $log    = $self->{log};

	$log->info("Caching installed image as $key...");

	my $base = $cache->store(
		$key,
		$state->disk_path,
		{
			root_password => $root_password,
			version       => $config->{version},
			disk_size     => $config->{disk_size},
		} );
	if ( !defined $base ) {
		$log->warning("Could not cache installed image, continuing");
		return 0;
	}

	if ( !$self->_reparent_disk($base) ) {
		$log->warning(
			"Cached image saved but disk left standalone: $base");
		return 0;
	}

	$log->info("Cached installed image: $base");
	return 1;
}

# $self->_reparent_disk($base):
#	Replace the working disk with a fresh overlay backed by $base.
#	The method moves the old disk aside and does not delete it.
#	Thus a failure to create the overlay cannot leave the VM
#	without a disk.
sub _reparent_disk ( $self, $base )
{
	my $config = $self->{config};
	my $state  = $self->{state};
	my $log    = $self->{log};

	my $disk_path = $state->disk_path;
	my $saved     = "$disk_path.replaced";

	unlink $saved if -f $saved;
	rename $disk_path, $saved or do {
		$log->warning("Cannot move $disk_path aside: $!");
		return 0;
	};

	# Disk::create returns early on an existing path. Thus the
	# rename above is what makes this call create the overlay.
	my $disk = App::FuguVM::Disk->new( $state->state_dir );
	my $path = $disk->create( $config->{name}, undef, $base );
	if ( !defined $path ) {
		rename $saved, $disk_path
		    or $log->error("Cannot restore $disk_path: $!");
		return 0;
	}

	unlink $saved or $log->warning("Cannot remove $saved: $!");
	return 1;
}

# $self->_import_base($cache, $key):
#	Publish the configured base_disk as the cache entry of $key.
#	The publication costs one conversion of the whole image, and
#	it happens one time for each host: the entry is write-once,
#	and every guest of the project derives the same key. The tool
#	only reads the source file. The metadata holds no root
#	password, because the tool must not invent a credential for an
#	image that it did not install. Return 1 on success.
sub _import_base ( $self, $cache, $key )
{
	my $config = $self->{config};
	my $log    = $self->{log};
	my $source = $config->{base_disk};

	if ( !-f $source ) {
		$log->error(  "The base_disk file is gone: $source"
			    . " (cache miss for $key)" );
		return 0;
	}

	$log->info("Publishing $source as $key...");
	my $base = $cache->store(
		$key, $source,
		{
			imported_from => $source,
			install_mode  => 'import',
			version       => $config->{version},
		} );
	if ( !defined $base ) {

		# store is write-once, so a sibling can have published
		# the entry inside the window. A lookup decides.
		return defined $cache->lookup($key) ? 1 : 0;
	}

	$log->info("Published imported base: $base");
	return 1;
}

# $self->_install_config($root_password, $proxy_url):
#	Return the configuration of one expect install. The verify
#	flag rides along as the word that the script reads: 'yes' or
#	'no'.
sub _install_config ( $self, $root_password, $proxy_url )
{
	return {
		%{ $self->{config} },
		root_password => $root_password,
		proxy_url     => $proxy_url // 'none',
		verify => ( $self->{config}{verify} // 1 ) ? 'yes' : 'no',
	};
}

# $self->_mirror($proxy):
#	Build the mirror of this guest over the cache of the proxy. A
#	run without a proxy still verifies: the mirror then builds a
#	cache over the same directory.
sub _mirror ( $self, $proxy = undef )
{
	my $config = $self->{config};

	my $cache =
	    defined $proxy
	    ? $proxy->cache
	    : App::FuguVM::Proxy::Cache->new( $self->_cache_dir );

	return App::FuguVM::Mirror->new(
		cache   => $cache,
		version => $config->{version},
		arch    => $config->{arch},
		verify  => $config->{verify} // 1,
		log     => $self->{log},
		(
			defined $config->{signify_dir}
			? ( keys_dir => $config->{signify_dir} )
			: ()
		),
	);
}

# $self->_run_autoinstall($expect, $proxy_url):
#	Start the responder, drive the autoinstall over the console,
#	and stop the responder on every path out of the install.
#	Return undef on success, and an exit code on failure.
sub _run_autoinstall ( $self, $expect, $proxy_url = undef )
{
	my $log = $self->{log};

	my $responder = $self->_autoinstall($proxy_url);
	if ( !defined $responder->start ) {
		$log->error( 'Responder did not start: '
			    . ( $responder->error // 'unknown' ) );
		return EXIT_ERROR;
	}

	my $url = $responder->guest_url;
	$log->info("Responder started: $url");

	my $ok = $expect->run_autoinstall(
		{ %{ $self->{config} }, autoinstall_url => $url } );

	$responder->stop;

	if ( !$ok ) {
		$log->error("Autoinstall failed");
		return EXIT_EXPECT_FAILED;
	}

	return;
}

# $self->_root_password:
#	Return the root password of this guest. The tool owns the
#	credential in the expect mode, so the method generates one
#	there. In every other mode the operator owns it, and the
#	method returns the first line of root_password_file, with no
#	trailing newline, or undef without the directive. Thus the
#	secret has a short life in the process, and no configuration
#	hash carries it.
sub _root_password ($self)
{
	my $config = $self->{config};
	my $mode   = $config->{install_mode} // 'expect';

	if ( $mode eq 'expect' ) {
		$self->{log}->info("Generated secure root password");
		return Fugu::Random->random_password(32);
	}

	my $file = $config->{root_password_file};
	return if !defined $file;

	my $bits = ( stat $file )[2];
	$self->{log}->warning("The group or other users can read $file")
	    if defined $bits && $bits & 0044;

	open my $fh, '<', $file or do {
		$self->{log}->error("Cannot read $file: $!");
		return;
	};
	my $line = <$fh>;
	close $fh;
	return if !defined $line;

	chomp $line;
	return $line;
}

sub down ($self)
{
	# Stop the responder and the proxy if they run
	if ( $self->_stop_autoinstall ) {
		$self->{log}->info("Autoinstall responder stopped");
	}
	if ( $self->_stop_proxy ) {
		$self->{log}->info("Proxy stopped");
	}

	return $self->stop;
}

sub destroy ($self)
{
	my $state  = $self->{state};
	my $log    = $self->{log};
	my $config = $self->{config};

	# Stop the responder and the proxy if they run
	if ( $self->_stop_autoinstall ) {
		$log->info("Autoinstall responder stopped");
	}
	if ( $self->_stop_proxy ) {
		$log->info("Proxy stopped");
	}

	# Stop the VM if it runs
	if ( $self->_is_running ) {
		$self->stop(1);
	}

	# Remove the disk
	my $disk_path = $state->disk_path;
	if ( -f $disk_path ) {
		$log->info("Removing disk image...");
		unlink $disk_path or do {
			$log->error("Cannot remove $disk_path: $!");
			return EXIT_ERROR;
		};
	}

lib/App/FuguVM/Guest.pm  view on Meta::CPAN

	return $self->_arch->accelerator( $^O, _host_arch(),
		-w '/dev/kvm' ? 1 : 0 );
}

# $self->bind_address:
#	Return the host address of the forwarded ports. The
#	configuration loader injects the value; the fallback only
#	serves VM objects built without a configuration.
sub bind_address ($self)
{
	return $self->{config}{bind_address}
	    // App::FuguVM::Config::DEFAULT_BIND_ADDRESS();
}

# $self->connect_address:
#	Return the address that the tool connects to. A bind address
#	of 0.0.0.0 is not a destination, so the loopback address
#	serves that one case.
sub connect_address ($self)
{
	my $address = $self->bind_address;
	return '127.0.0.1' if $address eq '0.0.0.0';

	return $address;
}

# The resolved ports. Each method returns the recorded port, and
# falls back to the configured number. It returns undef for 'auto'
# with no record: the record dies with the run, so a stopped guest
# has no port.
sub ssh_port ($self)
{
	return $self->_resolved_port('ssh_port');
}

sub console_port ($self)
{
	return $self->_resolved_port('console_port');
}

sub _resolved_port ( $self, $directive )
{
	# The record describes the current run, so it serves only
	# while the guest runs. A crashed guest leaves a record
	# behind. That record must not read as a live port.
	if ( $self->{state} && $self->_is_running ) {
		my $recorded = $self->{state}->get_runtime->{$directive};
		return $recorded if defined $recorded;
	}

	# The answer is one scalar, undef included: a caller builds a
	# hash with it, and a bare return would collapse the pair.
	my $configured = $self->{config}{$directive};
	$configured = undef
	    if defined $configured
	    && $configured eq App::FuguVM::Config::AUTO_PORT();

	return $configured;
}

# $self->wait_ssh($timeout, $password):
#	Wait for SSH to become available. Without a password, the
#	connection uses the SSH agent for authentication. The initial
#	installation gives the root password, because the SSH key is
#	not in yet.
sub wait_ssh ( $self, $timeout = 120, $password = undef )
{
	my $ssh = Fugu::SSH->new(
		host => $self->connect_address,
		port => $self->ssh_port,
		user => 'root',
		( defined $password ? ( password => $password ) : () ),
	);

	return $ssh->wait_available($timeout);
}

# $self->_needs_ssh_key_update:
#	Check if the SSH key must be installed or updated. Return true
#	if no key is installed. Also return true if the configured key
#	differs from the installed key.
sub _needs_ssh_key_update ($self)
{
	my $config = $self->{config};
	my $state  = $self->{state};

	my $configured_key = $config->{ssh_pubkey};
	my $installed_key  = $state->get_installed_ssh_pubkey;

	# No key is configured. There is nothing to install.
	return 0 if !defined $configured_key || $configured_key eq '';

	# No key is installed yet
	return 1 if !defined $installed_key;

	# Compare the keys. Normalize the whitespace for the comparison.
	my $configured_normalized = $configured_key =~ s/\s+/ /gr;
	my $installed_normalized  = $installed_key  =~ s/\s+/ /gr;

	return $configured_normalized ne $installed_normalized;
}

# $self->_complete_ssh_setup():
#	Install or update the SSH key on the VM. The method
#	authenticates with the stored root password. It runs to recover
#	from a failed first boot, or when the configured SSH key
#	changed.
sub _complete_ssh_setup ($self)
{
	my $state  = $self->{state};
	my $config = $self->{config};
	my $log    = $self->{log};

	my $root_password = $state->get_root_password;
	if ( !defined $root_password ) {
		$log->error(
			"No root password stored - cannot complete SSH setup");
		return EXIT_ERROR;
	}

	$log->info("Updating SSH key...");

	# Wait for SSH with password authentication
	$log->info("Waiting for SSH...");
	if ( !$self->wait_ssh( 120, $root_password ) ) {
		$log->error("Timeout waiting for SSH");
		return EXIT_TIMEOUT;
	}

	# Install the SSH authorized key
	if ( !$self->_install_ssh_key($root_password) ) {
		$log->error("Failed to install SSH key");
		return EXIT_ERROR;
	}
	$log->info("SSH key installed");

	$log->info("VM ready");
	return EXIT_SUCCESS;
}

# $self->_install_ssh_key($password):
#	Install the SSH public key from the configuration into
#	authorized_keys. The method uses password authentication,
#	because the key is not yet installed.
sub _install_ssh_key ( $self, $password )
{
	my $config = $self->{config};
	my $state  = $self->{state};
	my $log    = $self->{log};

	# Get the SSH public key from the configuration
	my $ssh_pubkey = $config->{ssh_pubkey};
	if ( !defined $ssh_pubkey || $ssh_pubkey eq '' ) {
		$log->error("No ssh_pubkey configured in ~/.fuguvmrc");
		return 0;
	}

	# Connect with the password
	my $ssh = Fugu::SSH->new(
		host     => $self->connect_address,
		port     => $self->ssh_port,
		user     => 'root',
		password => $password,
	);

	# Create the .ssh directory
	my $result =
	    $ssh->run_command('mkdir -p /root/.ssh && chmod 700 /root/.ssh');
	if ( $result->{exit_code} != 0 ) {
		return 0;
	}

	# Write the authorized_keys file
	my $authkeys_content = $ssh_pubkey . "\n";
	if (
		$ssh->write_file(
			'/root/.ssh/authorized_keys', $authkeys_content,
			0600
		) != 0
	    )
	{
		return 0;
	}

	# Store the installed pubkey for a future comparison
	$state->mark_ssh_key_installed($ssh_pubkey);
	return 1;
}

# Graceful shutdown with a filesystem sync: sync through SSH, then
# power off through the ACPI power button, and report the result.
sub _graceful_shutdown ($self)
{
	my $log = $self->{log};

	# Do a best-effort filesystem sync over SSH before the code
	# pulls the power. The sync has a hard time bound. A wedged
	# guest must never stall the shutdown. Also, libssh2 does not
	# reliably obey its own timeout on the connect and handshake. A
	# failure or a timeout here is acceptable. The ACPI powerdown
	# below runs the orderly shutdown of the guest, which syncs. A
	# force stop is the ultimate fallback.
	$self->_bounded(
		Fugu::SSH::DEFAULT_TIMEOUT() + 5,
		sub {
			my $ssh = Fugu::SSH->new(
				host => $self->connect_address,
				port => $self->ssh_port,
				user => 'root',
			);
			return $ssh->run_command('sync; sync; sync');
		} );

	# Ask the guest to power off through the ACPI power button. Then
	# wait.
	if ( $self->_qmp_powerdown && $self->_wait_exit(60) ) {
		$log->info("Shutdown via ACPI powerdown");
		return 1;
	}

	return 0;
}



( run in 0.754 second using v1.01-cache-2.11-cpan-f5f21f1076c )