Skip to content

Autostart - #8

Closed
berrange wants to merge 26 commits into
oldmasterfrom
autostart
Closed

berrange wants to merge 26 commits into
oldmasterfrom
autostart

Conversation

@berrange

@berrange berrange commented Apr 23, 2025 •

Copy link
Copy Markdown
Owner
  • Requesting graceful OS shutdown if managed save failed
  • Force poweroff of VMs if no other action worked
  • Optionally enabling/disabling use of managed save,
    graceful shutdown and force poweroff, which is more flexible
    than ON_SHUTDOWN=nnn, as we can try the whole sequence of
    options
  • Ability to bypass cache in managed save
  • Support for one-time autostart of VMs as an official API

To aid in testing this logic, virt-admin gains a new command

'virt-admin daemon-shutdown --preserve'

All this new functionality is wired up into the QEMU driver, and is
made easily accessible to other hypervisor drivers, so would easily
be extendable to Xen, CH, LXC drivers, but this is not done in this
series. IOW, libvirt-guests.service is not yet fully obsolete.

The new functionality is also not enabled by default for the system
daemon, it requires explicit admin changes to /etc/libvirt/qemu.conf
to enable it. This is because it would clash with execution of the
libvirt-guests.service if both were enabled.

It is highly desirable that we enable this by default though, so we
need to figure out a upgrade story wrt libvirt-guests.service.

The only libvirt-guests.sh features not implemented are:

  • PARALLEL_SHUTDOWN=nn.

    When doing a graceful shutdown we initiate it on every single VM
    at once, and then monitor progress of all of them in parallel.

  • SYNC_TIME=nn

    When make not attempt to sync guest time when restoring from
    managed save. This ought to be fixed

Summary by Sourcery

Enhance libvirt's autostart and shutdown capabilities for virtual machines, introducing more flexible and configurable mechanisms for domain autostart and graceful system shutdown

New Features:

  • Introduce one-time autostart for domains, allowing a domain to be started only on the next boot
  • Add support for configurable VM shutdown strategies with managed save, graceful shutdown, and force poweroff
  • Implement ability to bypass cache during managed save
  • Add systemd notification support for various daemon states

Enhancements:

  • Refactor autostart logic across different hypervisor drivers to use a common approach
  • Improve shutdown sequence with more granular control and state preservation
  • Add configuration options for autostart delay and shutdown behavior
  • Extend virsh and virt-admin tools to support new autostart and shutdown features

Chores:

  • Update multiple driver implementations to use new autostart and shutdown mechanisms
  • Add new configuration options in QEMU driver configuration
  • Extend public and private APIs to support new functionality

Summary by CodeRabbit

  • New Features

    • Added support for "Autostart Once" domains, allowing a domain to be set to autostart only on the next boot.
    • Enhanced the "autostart" command with a new "--once" option to control one-time autostart behavior.
    • Updated domain information display to show "Autostart Once" status.
    • Introduced new configuration options for fine-grained control over VM autostart delay and shutdown/save behavior.
    • Added a "daemon-shutdown" command to virt-admin with an option to preserve state before shutdown.
  • Improvements

    • Refined daemon shutdown process to support multi-phase, state-preserving shutdowns with improved systemd integration.
    • Expanded systemd notification capabilities for more detailed service state reporting.
  • Refactor

    • Simplified and unified autostart logic across multiple drivers for maintainability and consistency.
  • Documentation

    • Added detailed comments and configuration documentation for new autostart and shutdown options.

We have a way to notify systemd when we're done starting the daemon.

Systemd supports many more notifications, however, and many of them
are quite relevant to our needs:

  https://www.freedesktop.org/software/systemd/man/latest/sd_notify.html

This renames the existing notification API to better reflect its
semantics, and adds new APIs for reporting

 * Initiation of config file reload
 * Initiation of daemon shutdown process
 * Adhoc progress status messages
 * Request to extend service shutdown timeout

Signed-off-by: Daniel P. Berrangé <[email protected]>
Switch to the 'notify-reload' service type and send notifications to
systemd when reloading configuration.

Signed-off-by: Daniel P. Berrangé <[email protected]>
There's a common pattern for autostart of iterating over VMs, acquiring
a lock and ref count, then checking the autostart & is-active flags.
Wrap this all up into a helper method.

Signed-off-by: Daniel P. Berrangé <[email protected]>
This delay can reduce the CPU/IO load storm when autostarting many
guests.

Signed-off-by: Daniel P. Berrangé <[email protected]>
This allows a user specified delay between autostart of each VM, giving
parity with the equivalent feature of libvirt-guests.

Signed-off-by: Daniel P. Berrangé <[email protected]>
This is a move of the code that currently exists in the QEMU
driver, into the common layer that can be used by multiple
drivers.

The code currently supports performing managed save of all
running guests, ignoring any failures.

Signed-off-by: Daniel P. Berrangé <[email protected]>
Currently the virStateStop method is only wired up to run save for
the unprivileged daemons, so there is no functional change.

IOW, session exit, or host OS shutdown will trigger VM managed saved
for QEMU session daemon, but not the system daemon.

This changes the daemon code to always run virStateStop for all
daemons. Instead the QEMU driver is responsible for skipping its
own logic when running privileged...for now.

This means that virStateStop will now be triggered by logind's
PrepareForShutdown signal.

Signed-off-by: Daniel P. Berrangé <[email protected]>
The auto shutdown code can currently only perform managed save,
which may fail in some cases, for example when PCI devices are
assigned. On failure, shutdown inhibitors remain in place which
may be undesirable.

This expands the logic to try a sequence of operations

 * Managed save
 * Graceful shutdown
 * Forced poweroff

Each of these operations can be enabled or disabled, but they
are always applied in this order.

With the shutdown option, a configurable time is allowed for
shutdown to complete, defaulting to 30 seconds, before moving
onto the forced poweroff phase.

Signed-off-by: Daniel P. Berrangé <[email protected]>
It may be desirable to treat transient VMs differently from persistent
VMs. For example, while performing managed save on persistent VMs makes
sense, the same not usually true of transient VMs, since by their
nature they will have no config to restore from.

Signed-off-by: Daniel P. Berrangé <[email protected]>
Currently automatic VM managed save is only performed in session
daemons, on desktop session close, or host OS shutdown request.

With this change it is possible to control shutdown behaviour for
all daemons. A recommended setup might be:

  auto_shutdown_try_save = "persistent"
  auto_shutdown_try_shutdown = "all"
  auto_shutdown_poweroff = "all"

Each setting accepts 'none', 'persistent', 'transient', and 'all'
to control what types of guest it applies to.

For historical compatibility, for the system daemon, the settings
currently default to:

  auto_shutdown_try_save = "none"
  auto_shutdown_try_shutdown = "none"
  auto_shutdown_poweroff = "none"

while for the session daemon they currently default to

  auto_shutdown_try_save = "all"
  auto_shutdown_try_shutdown = "none"
  auto_shutdown_poweroff = "none"

The system daemon settings should NOT be enabled if the traditional
libvirt-guests.service is already enabled.

Signed-off-by: Daniel P. Berrangé <[email protected]>
Currently the session daemon will try a managed save on all VMs,
leaving them running if that fails.

This limits the managed save just to persistent VMs, as there will
usually not be any way to restore transient VMs later.

It also enables graceful shutdown and then forced poweroff, should
save fail for some reason.

These new defaults can be overridden in the config file if needed.

Signed-off-by: Daniel P. Berrangé <[email protected]>
Allow users to control how many seconds libvirt waits for QEMU
shutdown before force powering off a guest.

Signed-off-by: Daniel P. Berrangé <[email protected]>
Bypassing cache can make save performance more predictable and avoids
trashing the OS cache with data that will not be read again.

Signed-off-by: Daniel P. Berrangé <[email protected]>
When doing managed save of VMs, triggered by OS shutdown, it may
be desirable to control cache usage.

Signed-off-by: Daniel P. Berrangé <[email protected]>
When a domain is marked for autostart, it will be started on every
subsequent host OS boot. There may be times when it is desirable to
mark a domain to be autostarted, on the next boot only.

Thus we add virDomainSetAutostartOnce / virDomainGetAutostartOnce.

An alternative would have been to overload the existing
virDomainSetAutostart method, to accept values '1' or '2' for
the autostart flag. This was not done because it is expected
that language bindings will have mapped the current autostart
flag to a boolean, and thus turning it into an enum would create
a compatibility problem.

A further alternative would have been to create a new method
virDomainSetAutostartFlags, with a VIR_DOMAIN_AUTOSTART_ONCE
flag defined. This was not done because it is felt desirable
to clearly separate the two flags. Setting the "once" flag
should not interfere with existing autostart setting, whether
it is enabled or disabled currently.

The 'virsh autostart' command, however, is still overloaded
by just adding a --once flag, while current state is added
to 'virsh dominfo'.

No ability to filter by 'autostart once' status is added to
the domain list APIs. The most common use of autostart once
will be to automatically set it on host shutdown, and it be
cleared on host startup. Thus there would rarely be scenarios
in which a running app will need to filter on this new flag.

Signed-off-by: Daniel P. Berrangé <[email protected]>
This is maintained in the same way as the autostart flag, using a
symlink. The difference is that instead of '.xml', the symlink
suffix is '.xml.once'. The link is also deleted immediately after
it has been read.

Signed-off-by: Daniel P. Berrangé <[email protected]>
When performing auto-shutdown of running domains, there is now the
option to mark them as "autostart once",  so that their state is
restored on next boot. This applies on top of the traditional
autostart flag.

Signed-off-by: Daniel P. Berrangé <[email protected]>
If shutting down running VMs at host shutdown, it can be useful to
automatically start them again on next boot. This adds a config
parameter 'auto_shutdown_restore', which defaults to enabled, which
leverages the autostart once feature.

Signed-off-by: Daniel P. Berrangé <[email protected]>
Currently the remote daemon code is responsible for calling virStateStop
in a background thread. The virNetDaemon code wants to synchronize with
this during shutdown, however, so the virThreadPtr must be passed over.

Even the limited synchronization done currently, however, is flawed and
to fix this requires the virNetDaemon code to be responsible for calling
virStateStop in a thread more directly.

Thus the logic is moved over into virStateStop via a further callback
to be registered by the remote daemon.

Signed-off-by: Daniel P. Berrangé <[email protected]>
The call to preserve state (ie running VMs) is triggered in response to
the desktop session dbus terminating (session daemon), or logind sending
a "PrepareForShutdown" signal. In the case of the latter, daemons
should only save their state, not actually exit yet. Other things on the
system may still expect the daemon to be running at this stage.

Signed-off-by: Daniel P. Berrangé <[email protected]>
The preserving of state (ie running VMs) requires a fully functional
daemon and hypervisor driver. If any part has started shutting down
then saving state may fail, or worse, hang.

The current shutdown sequence does not guarantee safe ordering, as
we synchronize with the state saving thread only after the hypervisor
driver has had its 'shutdownPrepare' callback invoked. In the case of
QEMU this means that worker threads processing monitor events may well
have been stopped.

This implements a full state machine that has a well defined ordering
that an earlier commit documented as the desired semantics.

With this change, nothing will start shutting down if the state saving
thread is still running.

Signed-off-by: Daniel P. Berrangé <[email protected]>
The daemons are wired up to shutdown in responsible to UNIX process
signals, as well as in response to login1 dbus signals, or loss of
desktop session. The latter two options can optionally preserve state
(ie running VMs).

In non-systemd environments, as well as for testing, it would be useful
to have a way to trigger shutdown with state preservation more directly.

Thus a new admin protocol API is introduced

  virAdmConnectDaemonShutdown

which will trigger a daemon shutdown, and preserve running VMs if the
VIR_DAEMON_SHUTDOWN_PRESERVE flag is set.

It has a corresponding 'virt-admin daemon-shutdown [--preserve]' command
binding.

Signed-off-by: Daniel P. Berrangé <[email protected]>
The service unit "TimeoutStopSec" setting controls how long systemd
waits for a service to stop before aggressively killing it, defaulting
to 30 seconds if not set.

When we're processing shutdown of VMs in response to OS shutdown, we
very likely need more than 30 seconds to complete this job, and can
not stop the daemon during this time.

To avoid being prematurely killed, setup a timer that repeatedly
extends the "TimeoutStopSec" value while stop of running VMs is
arranged.

This does mean if libvirt hangs while stoppping VMs, systemd won't
get to kill the libvirt daemon, but this is considered less harmful
that forcefully killing running VMs.

Signed-off-by: Daniel P. Berrangé <[email protected]>
Since processing running VMs on OS shutdown can take a while, it is
beneficial to send systemd status messages about the progress.

Signed-off-by: Daniel P. Berrangé <[email protected]>
@sourcery-ai

sourcery-ai Bot commented Apr 23, 2025 •

Copy link
Copy Markdown

Reviewer's Guide by Sourcery

This pull request introduces significant enhancements to libvirt's autostart and shutdown capabilities. It provides more flexible and configurable mechanisms for domain autostart and graceful system shutdown. The changes include one-time autostart for domains, configurable VM shutdown strategies, ability to bypass cache during managed save, and improved systemd integration. The QEMU driver is the primary focus, with updates to other hypervisor drivers as well. A new command is added to virt-admin to trigger daemon shutdown with optional state preservation.

No diagrams generated as the changes look simple and do not need a visual representation.

File-Level Changes

Change Details Files
Introduced a new enum virDomainDriverAutoShutdownScope to define the scope of auto-shutdown actions (none, persistent, transient, all) and implemented functions to convert between the enum and its string representation.
  • Added VIR_DOMAIN_DRIVER_AUTO_SHUTDOWN_SCOPE_NONE, VIR_DOMAIN_DRIVER_AUTO_SHUTDOWN_SCOPE_PERSISTENT, VIR_DOMAIN_DRIVER_AUTO_SHUTDOWN_SCOPE_TRANSIENT, and VIR_DOMAIN_DRIVER_AUTO_SHUTDOWN_SCOPE_ALL to the virDomainDriverAutoShutdownScope enum.
  • Implemented VIR_ENUM_IMPL for virDomainDriverAutoShutdownScope.
  • Added virDomainDriverAutoShutdownScopeTypeFromString and virDomainDriverAutoShutdownScopeTypeToString functions.
src/hypervisor/domain_driver.c
src/hypervisor/domain_driver.h
Implemented autostart and autoshutdown functionalities in the domain driver, including delaying autostart, and handling managed save, graceful shutdown, and poweroff based on domain persistence.
  • Added virDomainDriverAutoStart function to autostart domains based on configuration, including a delay between starting each guest.
  • Added virDomainDriverAutoShutdown function to handle managed save, graceful shutdown, and poweroff of domains based on their persistence and configured scopes.
  • Added virDomainDriverAutoStartConfig and virDomainDriverAutoShutdownConfig structs to encapsulate autostart and autoshutdown configurations, respectively.
src/hypervisor/domain_driver.c
src/hypervisor/domain_driver.h
Enhanced the libvirtd daemon to support state preservation during shutdown, including callbacks for preserve, prepare, and wait phases, and integration with systemd for timeout extension.
  • Added shutdownPreserveCb, shutdownPrepareCb, and shutdownWaitCb to the virNetDaemon struct.
  • Implemented virNetDaemonPreserve to trigger state preservation during shutdown.
  • Added virNetDaemonSetShutdownCallbacks to set the shutdown callbacks.
  • Integrated with systemd to extend the shutdown timeout during state preservation using virSystemdNotifyExtendTimeout.
src/rpc/virnetdaemon.c
src/rpc/virnetdaemon.h
Modified the QEMU driver to utilize the new autostart and autoshutdown functionalities, including configurable delays, scopes, and bypass cache options.
  • Modified qemuAutostartDomain to use qemuProcessBeginJob and qemuProcessEndJob.
  • Modified qemuStateInitialize to use virDomainDriverAutoStart with a configuration struct.
  • Modified qemuStateStop to use virDomainDriverAutoShutdown with a configuration struct.
  • Added new configuration options in virQEMUDriverConfig for autostart delay, autoshutdown scopes, and bypass cache options.
src/qemu/qemu_driver.c
src/qemu/qemu_conf.c
src/qemu/qemu_conf.h
src/qemu/libvirtd_qemu.aug
src/qemu/test_libvirtd_qemu.aug.in
Added support for one-time autostart of domains, allowing a domain to be started only on the next boot.
  • Added autostartOnce field to the virDomainObj struct.
  • Implemented qemuDomainGetAutostartOnce and qemuDomainSetAutostartOnce functions in the QEMU driver.
  • Added virDomainGetAutostartOnce and virDomainSetAutostartOnce functions to the libvirt API.
  • Modified virsh and virt-admin tools to support the new autostart-once feature.
src/qemu/qemu_driver.c
src/libvirt-domain.c
src/conf/domain_conf.h
src/conf/virdomainobjlist.c
tools/virt-admin.c
tools/virsh-domain.c
include/libvirt/libvirt-domain.h
src/remote/remote_driver.c
src/remote/remote_protocol.x
src/rpc/gendispatch.pl
Updated other hypervisor drivers (Bhyve, LXC, LibXL) to use the new autostart APIs.
  • Modified bhyveStateInitialize to use virDomainDriverAutoStart.
  • Modified lxcStateInitialize to use virDomainDriverAutoStart.
  • Modified libxlStateInitialize to use virDomainDriverAutoStart.
src/bhyve/bhyve_driver.c
src/lxc/lxc_driver.c
src/libxl/libxl_driver.c
src/lxc/lxc_process.c
Added a new command to virt-admin to trigger daemon shutdown with optional state preservation.
  • Added cmdDaemonShutdown function to handle the daemon-shutdown command.
  • Added VIR_DAEMON_SHUTDOWN_PRESERVE flag to libvirt-admin.h.
  • Implemented virAdmConnectDaemonShutdown in admin/libvirt-admin.c and admin_server_dispatch.c.
  • Updated admin_protocol.x to include the new procedure for daemon shutdown.
tools/virt-admin.c
include/libvirt/libvirt-admin.h
src/admin/libvirt-admin.c
src/admin/admin_server_dispatch.c
src/admin/admin_protocol.x
Enhanced systemd integration to notify about daemon states such as ready, reloading, stopping, and extending timeout.
  • Added virSystemdNotifyReady, virSystemdNotifyReload, virSystemdNotifyStopping, virSystemdNotifyExtendTimeout, and virSystemdNotifyStatus functions.
  • Used these functions in remote/remote_daemon.c and hypervisor/domain_driver.c to notify systemd about daemon states.
src/util/virsystemd.c
src/util/virsystemd.h
src/remote/remote_daemon.c
src/hypervisor/domain_driver.c

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @berrange - I've reviewed your changes - here's some feedback:

Overall Comments:

  • The introduction of virDomainDriverAutoStart and virDomainDriverAutoShutdown seems like a good way to share code between drivers.
  • Consider adding a comment to virNetDaemonSetShutdownCallbacks explaining the order in which the callbacks are invoked.
Here's what I looked at during the review
  • 🟡 General issues: 1 issue found
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread src/rpc/virnetdaemon.c
@@ -766,17 +824,40 @@ virNetDaemonRun(virNetDaemon *dmn)
virHashForEach(dmn->servers, daemonServerProcessClients, NULL);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Recommend adding comments on daemon shutdown phase transitions.

The state machine using VIR_NET_DAEMON_QUIT_* phases in virNetDaemonRun is non-trivial. Briefly documenting the transitions (especially the roles of PRESERVING, READY, WAITING, and COMPLETED) could help future developers understand the shutdown sequencing without having to reverse-engineer the logic.

Suggested change
virHashForEach(dmn->servers, daemonServerProcessClients, NULL);
virHashForEach(dmn->servers, daemonServerProcessClients, NULL);
/* Daemon Shutdown Phase Transitions:
*
* VIR_NET_DAEMON_QUIT_REQUESTED:
* Initial shutdown request received.
*
* VIR_NET_DAEMON_QUIT_PRESERVING:
* Shutdown preserve thread is active.
* The daemon preserves in-flight operations by extending the shutdown timeout.
*
* VIR_NET_DAEMON_QUIT_READY:
* (Not shown here) Indicates that all active connections and services have been gracefully closed.
*
* VIR_NET_DAEMON_QUIT_WAITING:
* (Not shown here) Denotes that the daemon is waiting for external cleanup operations to finish.
*
* VIR_NET_DAEMON_QUIT_COMPLETED:
* (Not shown here) Final phase; all cleanup is complete and shutdown is finalized.
*
* These transitions in virNetDaemonRun help coordinate a graceful shutdown sequence.
*/

@berrange

Copy link
Copy Markdown
Owner Author

@sourcery-ai review

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @berrange - I've reviewed your changes - here's some feedback:

Overall Comments:

  • The introduction of virDomainDriverAutoShutdownScope enum and its usage looks good, but consider adding a validation function to ensure the configured scope is valid.
  • The addition of virDomainGet/SetAutostartOnce is a useful feature; ensure that the documentation clearly explains the difference between autostart and autostartOnce.
Here's what I looked at during the review
  • 🟢 General issues: all looks good
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@berrange

Copy link
Copy Markdown
Owner Author

@sourcery-ai review

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @berrange - I've reviewed your changes - here's some feedback:

Overall Comments:

  • The introduction of virDomainDriverAutoShutdownScope enum and its usage looks good, but consider adding a validation function to ensure the configured scope is valid.
  • The virNetDaemonPreserve function could benefit from additional error handling if shutdownPreserveCb fails.
Here's what I looked at during the review
  • 🟢 General issues: all looks good
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@berrange

Copy link
Copy Markdown
Owner Author

@sourcery-ai review

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @berrange - I've reviewed your changes - here's some feedback:

Overall Comments:

  • The introduction of virDomainDriverAutoShutdownScope enum and its usage looks good, but consider adding a validation function to ensure the configured scope is valid.
  • The addition of virDomainGet/SetAutostartOnce is a useful feature; ensure that the documentation clearly explains the difference between autostart and autostartOnce.
Here's what I looked at during the review
  • 🟢 General issues: all looks good
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@berrange

Copy link
Copy Markdown
Owner Author

Hey @berrange - I've reviewed your changes - here's some feedback:

Overall Comments:

* The introduction of virDomainDriverAutoShutdownScope enum and its usage looks good, but consider adding a validation function to ensure the configured scope is valid.

* The addition of virDomainGet/SetAutostartOnce is a useful feature; ensure that the documentation clearly explains the difference between autostart and autostartOnce.

Here's what I looked at during the review

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

That is a poor review - there are a number of significant functional flaws in this code - try harder to find them, without making silly generic nitpicking review comments.

@berrange

Copy link
Copy Markdown
Owner Author

@CodiumAI-Agent /review

@QodoAI-Agent

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 5 🔵🔵🔵🔵🔵
🧪 No relevant tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Timer Cleanup

Ensure that preserve and quit timers are always removed and freed on all shutdown paths, and that the preserve thread is properly joined or terminated to avoid resource leaks or dangling references.

virNetDaemonPreserveTimer(int timerid G_GNUC_UNUSED,
                          void *opaque)
{
    virNetDaemon *dmn = opaque;
    VIR_LOCK_GUARD lock = virObjectLockGuard(dmn);
    unsigned long long now = g_get_monotonic_time();
    unsigned long long delta;

    if (dmn->quit != VIR_NET_DAEMON_QUIT_PRESERVING)
        return;

    VIR_DEBUG("Started at %llu now %llu extended %u",
              dmn->preserveStart, now, dmn->preserveExtended);

    /* Time since start of preserving state in usec */
    delta = now - dmn->preserveStart;
    /* Converts to secs */
    delta /= (1000ull * 1000ull);

    /* Want extra seconds grace to ensure this timer fires
     * again before system timeout expires, under high
     * load conditions */
    delta += VIR_NET_DAEMON_PRESERVE_MIN_TIME;

    /* Deduct any extension we've previously asked for */
    delta -= dmn->preserveExtended;

    /* Tell systemd how much more we need to extend by */
    virSystemdNotifyExtendTimeout(delta);
    dmn->preserveExtended += delta;

    VIR_DEBUG("Extended by %llu", delta);
}
Missing Lock/Unref

The new qemuAutostartDomain callback no longer locks or calls virDomainObjEndAPI, which may lead to unbalanced reference counts or unlocked objects; align with existing driver patterns.

    if (qemuProcessBeginJob(vm, VIR_DOMAIN_JOB_OPERATION_START,
                            flags) < 0)
        return;

    if (qemuDomainObjStart(NULL, driver, vm, flags,
                           VIR_ASYNC_JOB_START) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to autostart VM '%1$s': %2$s"),
                           vm->def->name, virGetLastErrorMessage());
    }

    qemuProcessEndJob(vm);
}
Config Parsing

The reuse of autoShutdownScope without clearing between successive calls may carry over stale values; validate each retrieval and reset appropriately.

if (virConfGetValueInt(conf, "auto_start_delay", &cfg->autoStartDelayMS) < 0)
    return -1;
if (virConfGetValueString(conf, "auto_shutdown_try_save", &autoShutdownScope) < 0)
    return -1;

if (autoShutdownScope != NULL &&
    (cfg->autoShutdownTrySave =
     virDomainDriverAutoShutdownScopeTypeFromString(autoShutdownScope)) < 0) {
    virReportError(VIR_ERR_INVALID_ARG,
                   _("unknown auto_shutdown_try_save '%1$s'"),
                   autoShutdownScope);
    return -1;
}

if (virConfGetValueString(conf, "auto_shutdown_try_shutdown", &autoShutdownScope) < 0)
    return -1;

if (autoShutdownScope != NULL &&
    (cfg->autoShutdownTryShutdown =
     virDomainDriverAutoShutdownScopeTypeFromString(autoShutdownScope)) < 0) {
    virReportError(VIR_ERR_INVALID_ARG,
                   _("unknown auto_shutdown_try_shutdown '%1$s'"),
                   autoShutdownScope);
    return -1;
}
if (virConfGetValueString(conf, "auto_shutdown_poweroff", &autoShutdownScope) < 0)
    return -1;

if (autoShutdownScope != NULL &&
    (cfg->autoShutdownPoweroff =
     virDomainDriverAutoShutdownScopeTypeFromString(autoShutdownScope)) < 0) {
    virReportError(VIR_ERR_INVALID_ARG,
                   _("unknown auto_shutdown_poweroff '%1$s'"),
                   autoShutdownScope);
    return -1;

@berrange

Copy link
Copy Markdown
Owner Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Apr 24, 2025

Copy link
Copy Markdown
✅ Actions performed

Full review triggered.

@coderabbitai

coderabbitai Bot commented Apr 24, 2025 •

Copy link
Copy Markdown

Walkthrough

This update introduces comprehensive enhancements to domain autostart and shutdown management across the codebase. A new "autostart once" feature is added, allowing domains to be configured for one-time autostart on the next host boot, with corresponding API, driver, and CLI support. The daemon shutdown process is refactored to support multi-phase, state-preserving shutdowns, including systemd timeout management and explicit preservation callbacks. Configuration files and parsers are extended to support granular autostart/shutdown behaviors and delays. Systemd notification handling is modularized and expanded. The virt-admin and virsh tools gain new options and commands for these features, and the service units are updated to use notify-reload for improved systemd integration.

Changes

File(s) / Path(s) Change Summary
include/libvirt/libvirt-admin.h, src/admin/libvirt-admin.c, src/admin/libvirt_admin_public.syms, src/admin/admin_protocol.x, src/admin/admin_server_dispatch.c Added virAdmConnectDaemonShutdown API and supporting protocol, server dispatch, and symbol version for daemon shutdown with optional state preservation.
include/libvirt/libvirt-domain.h, src/libvirt-domain.c, src/libvirt_public.syms, src/remote/remote_protocol.x, src/remote_protocol-structs, src/remote/remote_driver.c Introduced "autostart once" domain API: virDomainGetAutostartOnce, virDomainSetAutostartOnce, with protocol, driver, and symbol support.
src/conf/domain_conf.h, src/conf/domain_conf.c, src/conf/virdomainobjlist.c Added autostartOnce flag to domain object, managed .once symlink for transient autostart, and updated config load/delete logic.
src/driver-hypervisor.h, src/hypervisor/domain_driver.c, src/hypervisor/domain_driver.h, src/libvirt_private.syms Added generic autostart and autoshutdown driver interfaces, enums, configuration structs, and symbol exports for lifecycle management.
src/qemu/qemu_driver.c, src/qemu/qemu_conf.h, src/qemu/qemu_conf.c, src/qemu/qemu.conf.in, src/qemu/libvirtd_qemu.aug, src/qemu/test_libvirtd_qemu.aug.in Extended QEMU driver and config for autostart delay, shutdown scope, wait, restore, and cache bypass; updated config parsing and test data.
src/bhyve/bhyve_driver.c, src/libxl/libxl_driver.c, src/lxc/lxc_driver.c, src/lxc/lxc_process.c, src/lxc/lxc_process.h Refactored domain autostart logic to use new generic autostart API and callback config; simplified per-driver autostart implementations.
src/rpc/virnetdaemon.c, src/rpc/virnetdaemon.h, src/libvirt_remote.syms Refactored daemon shutdown to multi-phase state machine with preservation, timers, and new virNetDaemonPreserve API; updated callbacks and symbol exports.
src/remote/remote_daemon.c Replaced threaded daemon stop with direct preserve/quit calls, improved systemd notifications, and adjusted DBus signal handling for shutdown.
src/util/virsystemd.c, src/util/virsystemd.h Replaced virSystemdNotifyStartup with modular notification functions for ready, reload, stopping, extend timeout, and status updates.
src/remote/libvirtd.service.in, src/virtd.service.in Changed systemd service type from notify to notify-reload for improved reload handling.
tools/virt-admin.c Added daemon-shutdown command with preserve option for controlled daemon shutdown via CLI.
tools/virsh-domain-monitor.c, tools/virsh-domain.c Added CLI support for "autostart once" feature, including display in dominfo and new --once option for autostart command.
src/rpc/gendispatch.pl Updated code generation to handle "GetAutostartOnce" procedures similarly to "GetAutostart".

Sequence Diagram(s)

Domain "Autostart Once" Set/Query Flow

sequenceDiagram
    participant User
    participant Virsh
    participant libvirt API
    participant Hypervisor Driver

    User->>Virsh: virsh autostart --once <domain>
    Virsh->>libvirt API: virDomainSetAutostartOnce(domain, 1)
    libvirt API->>Hypervisor Driver: .domainSetAutostartOnce(domain, 1)
    Hypervisor Driver-->>libvirt API: result
    libvirt API-->>Virsh: result
    Virsh-->>User: Print success/failure

    User->>Virsh: virsh dominfo <domain>
    Virsh->>libvirt API: virDomainGetAutostartOnce(domain, &autostart)
    libvirt API->>Hypervisor Driver: .domainGetAutostartOnce(domain, &autostart)
    Hypervisor Driver-->>libvirt API: autostart value
    libvirt API-->>Virsh: autostart value
    Virsh-->>User: Show "Autostart Once: enable/disable"
Loading

Daemon Shutdown with State Preservation

sequenceDiagram
    participant Admin
    participant virt-admin
    participant libvirt-admin API
    participant Daemon

    Admin->>virt-admin: virt-admin daemon-shutdown --preserve
    virt-admin->>libvirt-admin API: virAdmConnectDaemonShutdown(conn, PRESERVE)
    libvirt-admin API->>Daemon: ADMIN_PROC_CONNECT_DAEMON_SHUTDOWN(flags=PRESERVE)
    Daemon->>Daemon: virNetDaemonPreserve()
    Daemon->>Daemon: Preserve state (async)
    Daemon->>Daemon: virNetDaemonQuit()
    Daemon->>libvirt-admin API: Result
    libvirt-admin API-->>virt-admin: Result
    virt-admin-->>Admin: Print shutdown result
Loading

Poem

In the warren of code, a new spring has begun,
Domains can now autostart—just once, then they’re done!
The daemon, much wiser, preserves state with care,
Notifies systemd, extends time, everywhere.
With virt-admin and virsh, commands hop with delight,
"Shutdown, but preserve!"—all handled just right.
🐇✨ Here’s to smooth boots and graceful goodnight!

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 10

🔭 Outside diff range comments (2)
src/qemu/qemu_conf.c (1)

645-695: ⚠️ Potential issue

Memory-leak + stale-value hazard when reusing autoShutdownScope

autoShutdownScope is a single g_autofree variable reused for three different keys (*_try_save, *_try_shutdown, *_poweroff).
Each subsequent virConfGetValueString() overwrites the pointer without first freeing or NULL-ing it:

if (virConfGetValueString(conf, "auto_shutdown_try_shutdown", &autoShutdownScope) < 0)
    return -1;

This causes

  1. a leak of the previous allocation, and
  2. if the second/third key is missing, the pointer still contains the
    previous value, so you parse the wrong string for the wrong field.

A minimal, leak-free fix:

-    if (virConfGetValueString(conf, "auto_shutdown_try_save", &autoShutdownScope) < 0)
+    g_clear_pointer(&autoShutdownScope, g_free);
+    if (virConfGetValueString(conf, "auto_shutdown_try_save", &autoShutdownScope) < 0)
         return -1;

Repeat the g_clear_pointer() (or simply declare three independent
variables) before each call.

src/util/virsystemd.c (1)

648-666: ⚠️ Potential issue

Incorrect length calculation for abstract sockets

When the notify socket path begins with ‘@’ the code rewrites
un.sun_path[0] = '\0', but mh.msg_namelen is still computed with
strlen(path) which includes the leading ‘@’.
For an abstract socket the correct length is

offsetof(struct sockaddr_un, sun_path) + 1 + strlen(path + 1)

Using the current value makes sendmsg() transmit an over-short address
(namelen too small), so the datagram is silently dropped and systemd
never receives the notification.

-    mh.msg_namelen = offsetof(struct sockaddr_un, sun_path) + strlen(path);
+    mh.msg_namelen = offsetof(struct sockaddr_un, sun_path) +
+                     1 + strlen(path + (path[0] == '@' ? 1 : 0));
🧹 Nitpick comments (9)
tools/virsh-domain.c (1)

1174-1174: Implementation handles both persistent and one-time autostart correctly.

The code correctly implements the new functionality to handle one-time autostart when the "once" flag is specified, while preserving the original persistent autostart behavior otherwise. Error handling and success messages are appropriate for both paths.

One minor suggestion would be to improve the help text for the "once" option to more explicitly indicate it's for one-time autostart vs. persistent autostart.

 {.name = "once",
  .type = VSH_OT_BOOL,
- .help = N_("control next boot state")
+ .help = N_("enable one-time autostart for next boot only")
 },

Also applies to: 1180-1208

src/qemu/qemu.conf.in (1)

688-694: Option to bypass cache during managed save

This setting is important for ensuring data integrity during emergency shutdowns, trading performance for durability. The comment clearly explains the performance implications.

There's a slight typo in the comment ("may" instead of "many" in line 680), but it doesn't affect functionality.

-# How may seconds to wait for running VMs to gracefully shutdown
+# How many seconds to wait for running VMs to gracefully shutdown
src/util/virsystemd.c (1)

693-699: No guard against negative or excessively large timeout values

virSystemdNotifyExtendTimeout() trusts the caller and multiplies secs
into µs, risking wrap-around for large or negative inputs.

g_strdup_printf("EXTEND_TIMEOUT_USEC=%llu", secs * 1000000ull);

Consider validating secs > 0 && secs <= INT_MAX/1e6 (or similar) to
avoid sending nonsense to systemd.

src/hypervisor/domain_driver.h (1)

77-116: Expose public API but no documentation block

The newly-introduced auto-start/shutdown structs and enums are public to
all drivers but lack a brief comment explaining each field and its valid
range (e.g. that delayMS is milliseconds and may be 0–…; that
waitShutdownSecs<=0 falls back to default). A short doxygen-style
description will make embedding drivers much easier.

src/hypervisor/domain_driver.c (1)

850-877: Unbounded wait loop can underrun systemd timeout

The polling loop waits until either all domains are down or the timer
expires, but it never extends the watchdog timeout while waiting. If
waitShutdownSecs is large (or the default 30 s but many VMs), systemd
may kill libvirtd early. Consider calling
virSystemdNotifyExtendTimeout() inside the loop whenever the remaining
time would cross systemd’s limit.

src/qemu/qemu_driver.c (1)

948-958: Consider error propagation from virDomainDriverAutoShutdown

The qemuStateStop function now unconditionally returns 0, potentially masking errors from the shutdown process. Consider checking and propagating errors from virDomainDriverAutoShutdown if they represent critical failures that should affect the driver shutdown.

- virDomainDriverAutoShutdown(&ascfg);
- 
- return 0;
+ int ret = virDomainDriverAutoShutdown(&ascfg);
+ 
+ return ret;
src/remote/remote_daemon.c (2)

527-533: Race-order when mixing Preserve + Quit calls

Calling virNetDaemonPreserve() immediately followed by virNetDaemonQuit() (in that order) is logically sound, but be aware of this subtle race:

  1. virNetDaemonPreserve() spawns the preserve thread without changing dmn->quit.
  2. The next line sets dmn->quit = REQUESTED.
  3. If the main loop sees the REQUESTED state before the preserve thread flips it to PRESERVING, the “preserve” path is still taken – but the window is narrow and non-obvious to future readers.

A short comment explaining why the order is intentional (and safe) will help maintainers reason about the state machine.


609-621: Potential lifetime leak for systemBus subscription

g_dbus_connection_signal_subscribe() returns a subscription ID that should be tracked and later unsubscribed with g_dbus_connection_signal_unsubscribe() when the daemon exits.
At the moment the ID is ignored, so the connection keeps the handler around even when dmn is freed. That is benign on normal shutdown but becomes problematic in an exec-restart scenario where the same process keeps the bus FD open.

Stash the returned handler ID and remove it during cleanup.

src/rpc/virnetdaemon.c (1)

876-884: Typo in log message

"Make forcefull daemon shutdown" → "Making forceful daemon shutdown" or simply "Forcing daemon shutdown".

-        VIR_WARN("Make forcefull daemon shutdown");
+        VIR_WARN("Forcing daemon shutdown");
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c97766a and 57b1ae9.

📒 Files selected for processing (41)
  • include/libvirt/libvirt-admin.h (1 hunks)
  • include/libvirt/libvirt-domain.h (1 hunks)
  • src/admin/admin_protocol.x (2 hunks)
  • src/admin/admin_server_dispatch.c (1 hunks)
  • src/admin/libvirt-admin.c (1 hunks)
  • src/admin/libvirt_admin_public.syms (1 hunks)
  • src/bhyve/bhyve_driver.c (3 hunks)
  • src/conf/domain_conf.c (1 hunks)
  • src/conf/domain_conf.h (1 hunks)
  • src/conf/virdomainobjlist.c (2 hunks)
  • src/driver-hypervisor.h (2 hunks)
  • src/hypervisor/domain_driver.c (2 hunks)
  • src/hypervisor/domain_driver.h (2 hunks)
  • src/libvirt-domain.c (1 hunks)
  • src/libvirt_private.syms (2 hunks)
  • src/libvirt_public.syms (1 hunks)
  • src/libvirt_remote.syms (1 hunks)
  • src/libxl/libxl_driver.c (3 hunks)
  • src/lxc/lxc_driver.c (2 hunks)
  • src/lxc/lxc_process.c (1 hunks)
  • src/lxc/lxc_process.h (1 hunks)
  • src/qemu/libvirtd_qemu.aug (1 hunks)
  • src/qemu/qemu.conf.in (1 hunks)
  • src/qemu/qemu_conf.c (3 hunks)
  • src/qemu/qemu_conf.h (1 hunks)
  • src/qemu/qemu_driver.c (6 hunks)
  • src/qemu/test_libvirtd_qemu.aug.in (1 hunks)
  • src/remote/libvirtd.service.in (1 hunks)
  • src/remote/remote_daemon.c (4 hunks)
  • src/remote/remote_driver.c (1 hunks)
  • src/remote/remote_protocol.x (2 hunks)
  • src/remote_protocol-structs (2 hunks)
  • src/rpc/gendispatch.pl (2 hunks)
  • src/rpc/virnetdaemon.c (12 hunks)
  • src/rpc/virnetdaemon.h (2 hunks)
  • src/util/virsystemd.c (3 hunks)
  • src/util/virsystemd.h (1 hunks)
  • src/virtd.service.in (1 hunks)
  • tools/virsh-domain-monitor.c (1 hunks)
  • tools/virsh-domain.c (2 hunks)
  • tools/virt-admin.c (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (9)
src/admin/admin_server_dispatch.c (1)
src/rpc/virnetdaemon.c (4)
  • dmn (734-739)
  • dmn (921-931)
  • virNetDaemonPreserve (938-967)
  • virNetDaemonQuit (890-897)
src/admin/libvirt-admin.c (1)
include/libvirt/libvirt-admin.h (2)
  • virAdmConnectDaemonShutdown (497-498)
  • conn (126-128)
src/hypervisor/domain_driver.c (3)
src/hypervisor/domain_driver.h (3)
  • vm (81-82)
  • virDomainDriverAutoStart (91-92)
  • virDomainDriverAutoShutdown (115-115)
src/conf/virdomainobjlist.c (1)
  • virDomainObjListForEach (813-830)
src/libvirt.c (1)
  • virConnectOpen (1200-1215)
src/conf/domain_conf.c (1)
src/conf/domain_conf.h (2)
  • virDomainConfigFile (4106-4107)
  • dom (4098-4100)
tools/virt-admin.c (3)
tools/vsh.c (1)
  • vshCommandOptBool (1235-1241)
include/libvirt/libvirt-admin.h (1)
  • virAdmConnectDaemonShutdown (497-498)
src/admin/libvirt-admin.c (1)
  • virAdmConnectDaemonShutdown (1375-1392)
src/rpc/virnetdaemon.h (1)
src/rpc/virnetdaemon.c (2)
  • dmn (734-739)
  • dmn (921-931)
src/remote/remote_daemon.c (3)
src/libvirt.c (4)
  • virStateReload (759-771)
  • virStateStop (781-793)
  • virStateShutdownPrepare (695-706)
  • virStateShutdownWait (716-727)
src/rpc/virnetdaemon.c (5)
  • virNetDaemonPreserve (938-967)
  • dmn (734-739)
  • dmn (921-931)
  • virNetDaemonQuit (890-897)
  • virNetDaemonIsPrivileged (419-425)
src/rpc/virnetdaemon.h (5)
  • virNetDaemonPreserve (73-73)
  • dmn (35-38)
  • dmn (59-59)
  • virNetDaemonQuit (71-71)
  • virNetDaemonIsPrivileged (47-47)
src/util/virsystemd.c (1)
src/util/virsystemd.h (5)
  • virSystemdNotifyReady (47-47)
  • virSystemdNotifyReload (48-48)
  • virSystemdNotifyStopping (49-49)
  • virSystemdNotifyExtendTimeout (50-50)
  • virSystemdNotifyStatus (51-51)
src/libvirt-domain.c (2)
include/libvirt/libvirt-domain.h (2)
  • virDomainGetAutostartOnce (2401-2402)
  • virDomainSetAutostartOnce (2403-2404)
src/driver-hypervisor.h (16)
  • domain (121-121)
  • domain (124-124)
  • domain (133-134)
  • domain (137-137)
  • domain (140-141)
  • domain (144-145)
  • domain (148-148)
  • domain (151-152)
  • domain (155-155)
  • domain (158-159)
  • domain (162-162)
  • domain (165-166)
  • domain (169-170)
  • domain (173-175)
  • domain (178-180)
  • domain (183-186)
🔇 Additional comments (59)
src/util/virsystemd.h (1)

47-51: Well-designed systemd notification interface.

These new functions replace the previous single function with a more granular and comprehensive systemd notification API, which aligns with the PR goal of enhancing libvirt's lifecycle management.

src/libvirt_public.syms (1)

951-955: LGTM! New API symbols correctly exposed for autostart-once feature.

The new version block LIBVIRT_11.0.0 properly inherits from the previous version and exports the two new API functions that implement the one-time autostart functionality described in the PR objectives.

src/libvirt_remote.syms (1)

93-93: LGTM! New daemon preservation API exported.

The virNetDaemonPreserve symbol is correctly added to support the new multi-phase, preservation-aware shutdown sequence described in the PR objectives.

src/lxc/lxc_process.h (1)

37-38:

Details

✅ Verification successful

Consistent with new autostart callback architecture.

This new function aligns with the PR objective of providing a unified autostart framework across hypervisor drivers. The void return type suggests that error handling may be managed internally or through a different mechanism.

Is error handling for autostart domain failures addressed elsewhere? The void return type doesn't allow reporting errors to callers.


🏁 Script executed:

#!/bin/bash
# Look at the implementation of virLXCProcessAutostartDomain
echo "Examining implementation of virLXCProcessAutostartDomain..."
rg -A 10 "virLXCProcessAutostartDomain" --type c

Length of output: 2077


🏁 Script executed:

#!/bin/bash
# Extract extended implementation of virLXCProcessAutostartDomain
rg -n "virLXCProcessAutostartDomain" -A50 src/lxc/lxc_process.c

Length of output: 2099


No action needed on autostart error handling

The virLXCProcessAutostartDomain callback already handles failures by:

  • Logging the error via VIR_ERROR (lines 1576–1581)
  • Recording success/failure with virDomainAuditStart(vm, "booted", rc >= 0)

The void callback signature is defined by the generic virDomainDriverAutoStart framework, which uses audit events (and absence of a start event) to detect failures rather than a return code. No further changes are required.

src/remote/libvirtd.service.in (1)

29-29: Good change to improve systemd integration.

The service type update from notify to notify-reload aligns with the enhanced daemon shutdown sequence and reload handling in this PR. This change enables the daemon to properly inform systemd about reload operations with explicit RELOAD=1 and READY=1 notifications, as well as send additional notifications like STOPPING=1 and EXTEND_TIMEOUT_USEC= during shutdown process phases.

src/conf/domain_conf.h (1)

3285-3285: Good implementation of the "autostart once" feature.

The addition of this 1-bit flag field is a clean way to implement the transient autostart state. The placement immediately after the existing autostart flag maintains good struct organization, and the bit-field approach is memory-efficient for this Boolean flag. This change is foundational for the "autostart once" functionality that allows VMs to be configured for one-time autostart on the next host boot.

tools/virsh-domain-monitor.c (1)

1239-1243: Good addition of the "Autostart Once" status feature.

This code nicely extends the domain information display to include the new "autostart once" status, following the same pattern as the existing autostart status check. The formatting is consistent with other status display lines in the function.

src/virtd.service.in (1)

18-18: Appropriate service type change to support notification enhancements.

Changing from Type=notify to Type=notify-reload enables the daemon to properly integrate with systemd's notification system for both startup readiness and reload events.

src/admin/libvirt_admin_public.syms (1)

57-60: Good addition of new API symbol for daemon shutdown.

The new symbol version block follows the established pattern for versioning symbols, properly inheriting from the previous version (8.6.0) while adding the new virAdmConnectDaemonShutdown function to support the enhanced shutdown capabilities.

src/qemu/test_libvirtd_qemu.aug.in (1)

78-84: Well-structured addition of autostart and shutdown configuration options.

These new configuration parameters align with the PR objectives to enhance VM autostart and shutdown capabilities:

  1. auto_start_delay - Controls domain autostart timing
  2. auto_shutdown_try_save, auto_shutdown_try_shutdown, auto_shutdown_poweroff - Configure the multi-phase shutdown sequence
  3. auto_shutdown_wait - Defines timeout period during shutdown
  4. auto_shutdown_restore - Controls managed save image restoration
  5. auto_save_bypass_cache - Controls cache behavior during save operations

The additions follow the consistent format of the existing configuration entries.

src/admin/admin_server_dispatch.c (1)

477-489: Implementation looks correct and properly handles flag validation and shutdown sequence.

The new adminConnectDaemonShutdown function properly validates flags using virCheckFlags and implements a clean shutdown sequence by optionally preserving state before initiating the quit process. This aligns well with the PR objective of enhancing VM autostart and shutdown capabilities.

src/admin/admin_protocol.x (2)

222-224: RPC structure definition looks good.

The new structure for daemon shutdown contains just the necessary flags parameter, keeping the protocol extension minimal and focused.


343-346: Procedure registration correctly configured.

The ADMIN_PROC_CONNECT_DAEMON_SHUTDOWN procedure is correctly annotated with @generate: both to ensure both client and server stubs are generated, and uses the next available procedure number (20).

src/remote/remote_driver.c (1)

7675-7676: LGTM: Clean addition of autostart once API function pointers

The addition of these two function pointers domainGetAutostartOnce and domainSetAutostartOnce to the hypervisor driver struct is well-structured and follows the existing code style and naming conventions. The version annotation (11.0.0) correctly documents when these interfaces were added.

include/libvirt/libvirt-domain.h (1)

2401-2404: API addition for one-time autostart feature looks good.

The new functions virDomainGetAutostartOnce and virDomainSetAutostartOnce follow the same pattern as the existing autostart functions and provide a clear API for the new "autostart once" feature described in the PR objectives. This allows domains to be configured to start automatically only on the next boot, which is a useful enhancement to the existing autostart functionality.

src/conf/domain_conf.c (1)

29086-29096: LGTM! Implementation of "autostart once" cleanup looks correct.

The changes correctly implement cleanup for the new "autostart once" feature by:

  1. Adding an autostartOnceLink variable with .once suffix
  2. Cleaning up the link file during domain deletion
  3. Resetting the autostartOnce flag to maintain consistency

This implementation aligns well with the PR objective of adding one-time autostart functionality for virtual machines.

include/libvirt/libvirt-admin.h (1)

487-498: LGTM! Well-designed API extension for daemon shutdown control.

The new API follows proper libvirt conventions with clear versioning, appropriate flag pattern for extensibility, and good documentation. The VIR_DAEMON_SHUTDOWN_PRESERVE flag provides the capability to preserve state before shutting down the daemon as described in the PR objectives.

src/admin/libvirt-admin.c (1)

1361-1392: Implementation follows standard libvirt API patterns.

The function implementation properly handles error states, parameter validation, and delegation to the remote implementation. The debug logging, error handling, and function structure are consistent with libvirt API patterns.

src/conf/virdomainobjlist.c (1)

488-514: Smart implementation of the "autostart once" feature.

The implementation uses a ".once" symlink extension to enable a one-time autostart capability. By checking for the symlink and then immediately removing it after detection, the code ensures that the autostart happens only once (on the next boot), which aligns with the feature's purpose. The approach is consistent with how regular autostart is handled.

src/qemu/qemu_conf.h (1)

203-209: Well-structured configuration additions for enhanced auto-start/shutdown.

These new configuration options provide granular control over domain lifecycle operations:

  • Delay between domain startups (autoStartDelayMS)
  • Configurable shutdown sequence with multiple phases (try save, graceful shutdown, force poweroff)
  • Waiting periods between shutdown attempts
  • Options to control restore behavior and cache usage

These fields align perfectly with the PR objectives of providing "configurable options to enable or disable managed save, graceful shutdown, and force poweroff, offering more flexibility than the previous ON_SHUTDOWN setting."

src/rpc/gendispatch.pl (2)

842-843: Support for new GetAutostartOnce API looks correct

The regex pattern has been expanded to match both "GetAutostart" and "GetAutostartOnce" procedure names, ensuring that the new API function will have its return value correctly handled as a passed-by-reference parameter.


1653-1654: Consistent client-side implementation for GetAutostartOnce

The same pattern expansion is correctly applied in the client function generation, ensuring that both GetAutostart and GetAutostartOnce functions handle their arguments consistently. This matches the server-side implementation and completes the RPC support for the new autostart-once feature.

src/lxc/lxc_driver.c (1)

1406-1507: Autostart logic refactoring looks good.

The refactored code replaces the previous boolean flag approach with a structured configuration object, aligning with the unified autostart framework used across hypervisor drivers. This change provides more flexibility for the autostart implementation and properly supports the new features outlined in the PR objectives.

src/driver-hypervisor.h (2)

481-487: New API functions to support one-time autostart.

The addition of these typedefs extends the driver interface to support "autostart once" functionality, enabling domains to be configured for one-time autostart on the next host boot.


1575-1576: New function pointers in hypervisor driver struct.

These new members in the hypervisor driver struct correctly align with the previously defined function prototypes to enable the autostart-once functionality across hypervisor drivers.

src/lxc/lxc_process.c (1)

1565-1587: Simplified autostart domain implementation.

The virLXCProcessAutostartDomain function has been refactored as part of the common autostart approach. Key changes:

  1. Return type changed from int to void
  2. Removed domain state and autostart flag checks
  3. Now unconditionally attempts to start the domain

This implementation aligns with the centralized approach to domain autostart where filtering of domains to autostart is now managed by the common virDomainDriverAutoStart framework, simplifying the hypervisor-specific implementation.

tools/virt-admin.c (2)

1080-1112: Good implementation of the daemon-shutdown command.

The new daemon-shutdown command follows the established pattern for command implementation in virt-admin, with clear help text and proper flag handling. The implementation correctly passes the preserve flag to the virAdmConnectDaemonShutdown API.

This addition aligns well with the PR objective of providing tools to test the new state-preserving shutdown functionality.


1507-1512: Command registration looks good.

The new command is properly registered in the managementCmds array, making it available in the virt-admin tool interface.

src/qemu/libvirtd_qemu.aug (1)

100-106: Well-structured configuration additions for autostart/shutdown management.

The new configuration entries appropriately extend the save_entry section with the required parameters for the enhanced VM lifecycle management:

  • auto_start_delay for controlling VM startup timing
  • auto_shutdown_try_save, auto_shutdown_try_shutdown, and auto_shutdown_poweroff for configuring the multi-phase shutdown sequence
  • auto_shutdown_wait for timeout control
  • auto_shutdown_restore and auto_save_bypass_cache for controlling state preservation behavior

These additions match the PR objectives of providing more flexible and configurable VM lifecycle management.

tools/virsh-domain.c (1)

1161-1164: LGTM! Command option for one-time autostart is well-defined.

The addition of the "once" option to control next boot state is clear and follows the existing pattern for command options.

src/rpc/virnetdaemon.h (3)

73-73: Function addition aligned with new multi-phase shutdown sequence.

The new virNetDaemonPreserve function adds support for the asynchronous preservation phase in the refined shutdown sequence.


85-99: Well-documented shutdown sequence.

This detailed documentation clearly explains the refined multi-phase shutdown sequence with preservation, preparation, and wait phases. The comment effectively describes the operation order and responsibility of each callback, making the new functionality clear to implementers.


100-103: Callback signature updated for preservation support.

Adding the preserveCb parameter appropriately extends the shutdown callback interface to support the new preservation phase, aligning with the documented sequence.

src/remote_protocol-structs (2)

3309-3318: Good implementation of autostart once RPC structures.

The new RPC structures properly define the interface for the domain autostart once functionality, following the established pattern of other autostart-related operations in the protocol.


3768-3769: Correctly added procedure enum values.

The new procedure enum values are appropriately appended at the end of the enum, maintaining backward compatibility of the RPC protocol.

src/bhyve/bhyve_driver.c (2)

74-87: Simplified autostart domain callback.

The callback has been appropriately simplified to focus solely on starting the domain, removing the opaque data handling and validation logic that is now managed by the common autostart infrastructure.


1162-1252: Proper implementation of common autostart configuration.

The changes correctly refactor the bhyve driver to use the common domain autostart infrastructure by:

  1. Creating a configuration structure with the appropriate state directory
  2. Setting the simplified callback
  3. Providing the driver as opaque data
  4. Calling the common autostart function

This aligns with the PR objective of standardizing autostart logic across hypervisor drivers.

src/remote/remote_protocol.x (3)

3977-3983: Addition of remote domain get autostart once data structures looks good

The structures for the "get autostart once" API match the established pattern in the codebase for similar operations. The argument structure contains just the domain parameter while the return structure contains the autostart flag.


3985-3988: Set autostart once parameter structure correctly follows existing patterns

The structure for setting the autostart once flag follows the same pattern as other setter functions in the codebase, containing both the domain reference and the boolean flag parameter.


7072-7079: New RPC procedures are properly defined and annotated

The RPC procedure declarations for domain autostart once operations are correctly defined with:

  • Procedure numbers that follow sequentially (449 and 450)
  • Appropriate ACL annotations for access control
  • Priority marked as "high" to ensure non-blocking behavior
  • Generation marked for "both" client and server sides

These procedures align perfectly with the overall architecture of the remote protocol.

src/libvirt_private.syms (2)

1643-1646: Well-defined domain lifecycle management functions added

These new symbols provide a centralized implementation for VM autostart and shutdown operations, supporting the enhanced lifecycle management described in the PR objectives. The naming is clear and follows the existing code style conventions.


3531-3535: Improved granular systemd notification handling

The old single notification function has been replaced with multiple purpose-specific functions that align with systemd's notification protocol. This change provides better flexibility for precise lifecycle state communication with systemd.

src/qemu/qemu.conf.in (5)

637-640: Added autostart delay configuration

This setting allows administrators to control the delay between starting VMs during autostart, helping to prevent resource contention during host bootup when many VMs are being started.


641-655: Added configurable managed save behavior for shutdown

This configuration option provides flexibility for how running VMs should be handled during host shutdown, with appropriate scope filtering options (none/persistent/transient/all).

The comment usefully warns about potential conflicts with libvirt-guests.service if both are enabled.


656-679: Well-designed shutdown fallback sequence

The configuration implements a robust fallback sequence: first try managed save, then graceful shutdown, and finally forced poweroff. The scope filtering options for each stage provide excellent flexibility.

Each stage is only attempted if the previous stage fails, creating a sensible progressive shutdown strategy.


680-683: Configurable shutdown timeout

Allowing administrators to specify the wait time for graceful shutdown gives them control over the balance between giving VMs enough time to shutdown cleanly versus not delaying the host shutdown process excessively.


684-687: Auto-restore on boot setting

This setting provides a clean way to ensure VMs return to their prior state after a host reboot, maintaining service continuity. The default of enabled (1) is sensible for most use cases.

src/libxl/libxl_driver.c (3)

318-334: Well-structured simplification of the autostart domain callback.

The function has been changed to return void instead of int, which simplifies the implementation by focusing on reporting errors rather than propagating return codes. This change aligns with the standardized autostart framework approach mentioned in the PR objectives.


643-644: Appropriate variable declaration for autostart configuration.

Adding the virDomainDriverAutoStartConfig structure is the first step in migrating to the common autostart framework.


796-802: Good implementation of the common autostart approach.

This change replaces direct domain iteration with a call to the common virDomainDriverAutoStart helper, properly configuring the callback and state directory. This standardizes the autostart logic across hypervisor drivers, making the code more maintainable.

src/qemu/qemu_driver.c (6)

181-192: Early return without error propagation is acceptable

The function now returns early if job acquisition fails rather than propagating the error, which is appropriate for a callback used in automated domain starting. Errors are properly reported for logging but don't affect the autostart process of other domains.


886-892: LGTM - Clean domain autostart implementation

The new generic autostart framework implementation is well structured, with proper configuration of callback, state directory, and delay parameters. This is a good simplification of the previous manual domain autostart process.


7782-7872: Well-implemented autostart once feature

The implementation of the autostart once feature is thorough and follows best practices:

  • Proper ACL checking
  • Persistent domain validation
  • Clean error handling with g_autofree for memory management
  • Good separation of concerns with job handling
  • Consistent API pattern matching existing domain functions

20354-20355: API versioning is appropriate

The new autostart once functions are properly registered with version 11.0.0, correctly indicating these are new API additions.


7835-7860:

Details

❓ Verification inconclusive

Consider file permissions for autostart symlinks

When creating the autostart directory and symlinks, consider if the default permissions (0777) are appropriate or if more restrictive permissions would be better for security.

Additionally, verify that error handling for symlink operations is consistent with other similar operations in the codebase.


🏁 Script executed:

#!/bin/bash
# Check permissions used elsewhere for autostart directories
rg "mkdir.*autostart" --include="*.c" --type c -A 2 -B 2

# Check symlink error handling in other parts of the codebase
rg "symlink\(.*\).*?errno" --include="*.c" --type c -A 2 -B 2

Length of output: 1006


Limit Autostart Directory Permissions and Standardize Symlink Error Handling

  • Replace the 0777 mode in
    g_mkdir_with_parents(cfg->autostartDir, 0777)
    with a more restrictive value (e.g. 0755 or 0700) to avoid creating a world-writable directory unless there’s a clear need.
  • Symlinks don’t carry their own mode bits, but ensure your handling of symlink(configFile, autostartOnceLink) failures matches other parts of the codebase: for example, some callers treat EEXIST as non-fatal (unlinking first or ignoring it).
  • Manually review other g_mkdir_with_parents(…, autostartDir) and symlink() usages in the repo to confirm the chosen permissions and error-handling strategy are applied consistently.

170-193:

Details

❌ Incorrect review comment

Consider domain locking and reference handling in qemuAutostartDomain

The refactored qemuAutostartDomain function processes domains without explicit domain locking or reference handling that was typically present in similar driver functions. While the job API provides some protection, this differs from patterns in other driver functions where explicit calls to virObjectLock and virDomainObjEndAPI are common.


🏁 Script executed:

#!/bin/bash
# Check other domain callback functions to verify the pattern
rg "static (void|int) \w+Domain\(" src/qemu --type c -A 2 -B 2

Length of output: 296


🏁 Script executed:

#!/bin/bash
# Display the qemuNotifyLoadDomain function with surrounding context
grep -R "static void qemuNotifyLoadDomain" -n src/qemu/qemu_driver.c -A 50 -B 2

Length of output: 1715


🏁 Script executed:

#!/bin/bash
# Search for explicit locking calls in qemu_driver.c
rg "virObjectLock" -n src/qemu/qemu_driver.c -A2 -B2
rg "virDomainObjEndAPI" -n src/qemu/qemu_driver.c -A2 -B2

Length of output: 19149


Ignore domain locking in qemuAutostartDomain
The qemuAutostartDomain callback runs inside the job API (qemuProcessBeginJob/qemuProcessEndJob), which already acquires/releases the domain lock and manages the object reference. Explicit calls to virObjectLock(vm) or virDomainObjEndAPI(&vm) are not required here and match the existing pattern used in other callbacks (e.g. qemuNotifyLoadDomain).

Likely an incorrect or invalid review comment.

src/remote/remote_daemon.c (2)

551-552: Prepare-for-shutdown only triggers preservation

handleSystemMessageFunc() requests preservation but never calls virNetDaemonQuit(). That means the daemon will keep running indefinitely unless something else eventually calls Quit.

Is that deliberate? If the host shutdown sequence relies on a later SIGINT/SIGTERM to finish the job, add a comment clarifying the expectation; otherwise, you may want to invoke Quit here as well.


594-598: Callback order looks reversed w.r.t. historic API

The first argument of virNetDaemonSetShutdownCallbacks() is now treated as the preserve callback, but historically it was prepare. You changed the call site accordingly (virStateStop is now first), which is correct; just flagging that all other callers (drivers, tests) must be updated too or they’ll suddenly run the wrong phase at the wrong time.

src/rpc/virnetdaemon.c (1)

952-967: ⚠️ Potential issue

Possible leak if thread creation fails

When virThreadCreateFull() fails, we clear shutdownPreserveThread but keep the earlier virObjectRef(dmn) taken at line 957, leaking one reference. Move the virObjectRef(dmn) after successful thread creation, or drop it in the failure path:

-    virObjectRef(dmn);
-    dmn->shutdownPreserveThread = g_new0(virThread, 1);
-
-    if (virThreadCreateFull(..., dmn) < 0) {
-        virObjectUnref(dmn);
+    dmn->shutdownPreserveThread = g_new0(virThread, 1);
+    if (virThreadCreateFull(..., dmn) < 0) {
         g_clear_pointer(&dmn->shutdownPreserveThread, g_free);
         return;
     }
+    virObjectRef(dmn); /* paired with unref in worker */

Likely an incorrect or invalid review comment.

Comment thread src/lxc/lxc_process.h
@@ -34,6 +34,8 @@ int virLXCProcessStop(virLXCDriver *driver,
unsigned int cleanupFlags);

void virLXCProcessAutostartAll(virLXCDriver *driver);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Verify if this function declaration should be removed.

According to the summary and PR objectives, autostart logic is being refactored to use a common approach across hypervisor drivers. The AI summary states that virLXCProcessAutostartAll was removed, but the declaration is still present here.


🏁 Script executed:

#!/bin/bash
# Check if virLXCProcessAutostartAll is still used in implementation files
echo "Checking for virLXCProcessAutostartAll implementation and usage..."
rg -l "virLXCProcessAutostartAll" --type c

Length of output: 207


Remove stale declaration of virLXCProcessAutostartAll

Search confirms no implementation or references for this function—remove its declaration.

• src/lxc/lxc_process.h, line 36: delete the unused declaration

- void virLXCProcessAutostartAll(virLXCDriver *driver);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
void virLXCProcessAutostartAll(virLXCDriver *driver);

Comment thread src/libvirt-domain.c
Comment on lines +7388 to +7428
/**
* virDomainSetAutostartOnce:
* @domain: a domain object
* @autostart: whether the domain should be automatically started 0 or 1
*
* Configure the domain to be automatically started
* the next time the host machine boots only.
*
* Returns -1 in case of error, 0 in case of success
*
* Since: 11.0.0
*/
int
virDomainSetAutostartOnce(virDomainPtr domain,
int autostart)
{
virConnectPtr conn;

VIR_DOMAIN_DEBUG(domain, "autostart=%d", autostart);

virResetLastError();

virCheckDomainReturn(domain, -1);
conn = domain->conn;

virCheckReadOnlyGoto(conn->flags, error);

if (conn->driver->domainSetAutostartOnce) {
int ret;
ret = conn->driver->domainSetAutostartOnce(domain, autostart);
if (ret < 0)
goto error;
return ret;
}

virReportUnsupportedError();

error:
virDispatchError(domain->conn);
return -1;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Validate parameter range and improve docs for virDomainSetAutostartOnce.

The docstring line

 * @autostart: whether the domain should be automatically started 0 or 1

can be made clearer (e.g., “1 to enable autostart once, 0 to disable”) and you should validate the incoming autostart value to prevent undefined driver behavior:

@@ -7391,1 +7391,1 @@
- * @autostart: whether the domain should be automatically started 0 or 1
+ * @autostart: 1 to enable autostart once, 0 to disable
@@ 7408,6 +7408,12 @@ virDomainSetAutostartOnce(virDomainPtr domain,
     virResetLastError();

     virCheckDomainReturn(domain, -1);
+    if (autostart != 0 && autostart != 1) {
+        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED,
+                       "Invalid autostart value: %d (expected 0 or 1)",
+                       autostart);
+        goto error;
+    }
     conn = domain->conn;

This ensures only valid flags are passed to the driver. Otherwise, the function follows established error-handling and read-only checks.

Comment thread src/libvirt-domain.c
Comment on lines +7344 to +7385
/**
* virDomainGetAutostartOnce:
* @domain: a domain object
* @autostart: the value returned
*
* Provides a boolean value indicating whether the domain
* is configured to be automatically started the next time
* the host machine boots only.
*
* Returns -1 in case of error, 0 in case of success
*
* Since: 11.0.0
*/
int
virDomainGetAutostartOnce(virDomainPtr domain,
int *autostart)
{
virConnectPtr conn;

VIR_DOMAIN_DEBUG(domain, "autostart=%p", autostart);

virResetLastError();

virCheckDomainReturn(domain, -1);
virCheckNonNullArgGoto(autostart, error);

conn = domain->conn;

if (conn->driver->domainGetAutostartOnce) {
int ret;
ret = conn->driver->domainGetAutostartOnce(domain, autostart);
if (ret < 0)
goto error;
return ret;
}

virReportUnsupportedError();

error:
virDispatchError(domain->conn);
return -1;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Ensure consistent success return and clarify doc for virDomainGetAutostartOnce.

The doc block effectively explains the feature but the trailing “only” is redundant and could be removed for clarity. More importantly, if a driver’s domainGetAutostartOnce callback were to return a positive value (ret > 0), it would be propagated, even though the API contract specifies 0 on success. To enforce the contract, mask the driver’s return code so the public API always returns 0 on success:

@@ 7372,6 +7372,8 @@ virDomainGetAutostartOnce(virDomainPtr domain,
-        ret = conn->driver->domainGetAutostartOnce(domain, autostart);
-        if (ret < 0)
-            goto error;
-        return ret;
+        ret = conn->driver->domainGetAutostartOnce(domain, autostart);
+        if (ret < 0)
+            goto error;
+        return 0;

As a follow-up, run this script to verify that the persistent autostart functions follow the same return pattern:


🏁 Script executed:

#!/bin/bash
# Verify return-handling in persistent autostart getters/setters
rg -n -A5 "virDomainGetAutostart(" src/libvirt-domain.c
rg -n -A5 "virDomainSetAutostart(" src/libvirt-domain.c

Length of output: 305


🏁 Script executed:

#!/bin/bash
# Re-run with escaped parentheses to locate persistent autostart getters/setters
rg -n -A5 'virDomainGetAutostart\(' src/libvirt-domain.c
rg -n -A5 'virDomainSetAutostart\(' src/libvirt-domain.c

Length of output: 506


🏁 Script executed:

#!/bin/bash
# Extract full bodies of persistent autostart getters/setters for review
rg -n -A20 'virDomainGetAutostart\(' src/libvirt-domain.c
rg -n -A20 'virDomainSetAutostart\(' src/libvirt-domain.c

Length of output: 1332


Enforce consistent return codes across all autostart APIs

Remove the redundant “only” in the virDomainGetAutostartOnce doc and ensure that all three autostart APIs mask driver‐callback returns so they return 0 on success and -1 on error.

• File: src/libvirt-domain.c

--- a/src/libvirt-domain.c
@@ -7347,7 +7347,7 @@
- * is configured to be automatically started the next time
- * the host machine boots only.
+ * is configured to be automatically started the next time
+ * the host machine boots.
@@ -7372,8 +7372,8 @@ virDomainGetAutostartOnce(virDomainPtr domain,
-        ret = conn->driver->domainGetAutostartOnce(domain, autostart);
-        if (ret < 0)
-            goto error;
-        return ret;
+        ret = conn->driver->domainGetAutostartOnce(domain, autostart);
+        if (ret < 0)
+            goto error;
+        return 0;
@@ -7285,8 +7285,8 @@ virDomainGetAutostart(virDomainPtr domain,
-        ret = conn->driver->domainGetAutostart(domain, autostart);
-        if (ret < 0)
-            goto error;
-        return ret;
+        ret = conn->driver->domainGetAutostart(domain, autostart);
+        if (ret < 0)
+            goto error;
+        return 0;
@@ -7328,8 +7328,8 @@ virDomainSetAutostart(virDomainPtr domain,
-        ret = conn->driver->domainSetAutostart(domain, autostart);
-        if (ret < 0)
-            goto error;
-        return ret;
+        ret = conn->driver->domainSetAutostart(domain, autostart);
+        if (ret < 0)
+            goto error;
+        return 0;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
/**
* virDomainGetAutostartOnce:
* @domain: a domain object
* @autostart: the value returned
*
* Provides a boolean value indicating whether the domain
* is configured to be automatically started the next time
* the host machine boots only.
*
* Returns -1 in case of error, 0 in case of success
*
* Since: 11.0.0
*/
int
virDomainGetAutostartOnce(virDomainPtr domain,
int *autostart)
{
virConnectPtr conn;
VIR_DOMAIN_DEBUG(domain, "autostart=%p", autostart);
virResetLastError();
virCheckDomainReturn(domain, -1);
virCheckNonNullArgGoto(autostart, error);
conn = domain->conn;
if (conn->driver->domainGetAutostartOnce) {
int ret;
ret = conn->driver->domainGetAutostartOnce(domain, autostart);
if (ret < 0)
goto error;
return ret;
}
virReportUnsupportedError();
error:
virDispatchError(domain->conn);
return -1;
}
/**
* virDomainGetAutostartOnce:
* @domain: a domain object
* @autostart: the value returned
*
* Provides a boolean value indicating whether the domain
* is configured to be automatically started the next time
- * the host machine boots only.
+ * the host machine boots.
*
* Returns -1 in case of error, 0 in case of success
*
* Since: 11.0.0
*/
int
virDomainGetAutostartOnce(virDomainPtr domain,
int *autostart)
{
virConnectPtr conn;
VIR_DOMAIN_DEBUG(domain, "autostart=%p", autostart);
virResetLastError();
virCheckDomainReturn(domain, -1);
virCheckNonNullArgGoto(autostart, error);
conn = domain->conn;
if (conn->driver->domainGetAutostartOnce) {
int ret;
- ret = conn->driver->domainGetAutostartOnce(domain, autostart);
- if (ret < 0)
- goto error;
- return ret;
+ ret = conn->driver->domainGetAutostartOnce(domain, autostart);
+ if (ret < 0)
+ goto error;
+ return 0;
}
virReportUnsupportedError();
error:
virDispatchError(domain->conn);
return -1;
}

Comment thread src/qemu/qemu_conf.c
Comment on lines +306 to +321
if (privileged) {
/*
* Defer to libvirt-guests.service.
*
* XXX, or query if libvirt-guests.service is enabled perhaps ?
*/
cfg->autoShutdownTrySave = VIR_DOMAIN_DRIVER_AUTO_SHUTDOWN_SCOPE_NONE;
cfg->autoShutdownTryShutdown = VIR_DOMAIN_DRIVER_AUTO_SHUTDOWN_SCOPE_NONE;
cfg->autoShutdownPoweroff = VIR_DOMAIN_DRIVER_AUTO_SHUTDOWN_SCOPE_NONE;
} else {
cfg->autoShutdownTrySave = VIR_DOMAIN_DRIVER_AUTO_SHUTDOWN_SCOPE_PERSISTENT;
cfg->autoShutdownTryShutdown = VIR_DOMAIN_DRIVER_AUTO_SHUTDOWN_SCOPE_ALL;
cfg->autoShutdownPoweroff = VIR_DOMAIN_DRIVER_AUTO_SHUTDOWN_SCOPE_ALL;
}
cfg->autoShutdownRestore = true;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Inconsistent default handling – autoShutdownWait remains un-initialised for the privileged path

The newly-added defaults set autoShutdown* scopes when running privileged/unprivileged, but cfg->autoShutdownWait is left at its implicit zero. A later call to virDomainDriverAutoShutdown treats <=0 as “use 30 s”, so privileged installs silently get 30 s while unprivileged users can still override the value in qemu.conf. If the intent is to disable the wait entirely for the system instance (because libvirt-guests.service already handles it), set it explicitly to ‑1 (or a documented sentinel) so that behaviour is unambiguous.

Comment on lines +838 to +847
virSystemdNotifyStatus("Shutting down '%s' (%zu of %d)",
virDomainGetName(domains[i]), i + 1, numDomains);

if (virDomainShutdown(domains[i]) < 0) {
VIR_WARN("Unable to perform graceful shutdown of '%s': %s",
virDomainGetName(domains[i]),
virGetLastErrorMessage());
break;
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Loop aborts on first graceful-shutdown failure – remaining guests skipped

Inside tryShutdown the code breaks out of the outer loop on the first
virDomainShutdown() error:

if (virDomainShutdown(domains[i]) < 0) {
    ...
    break;   // stops processing subsequent domains
}

As a result all VMs after the failing one are left running and never
reach the forced power-off stage. Replace break with continue so the
shutdown continues best-effort for the rest of the list.

Comment on lines +681 to +697
VIR_DEBUG("Autostart %s: autostart=%d autostartOnce=%d",
vm->def->name, vm->autostart, vm->autostartOnce);

if ((vm->autostart || vm->autostartOnce)
&& !virDomainObjIsActive(vm)) {
virResetLastError();
if (state->cfg->delayMS) {
if (!state->first) {
g_usleep(state->cfg->delayMS * 1000ull);
} else {
state->first = false;
}
}

state->cfg->callback(vm, state->cfg->opaque);
vm->autostartOnce = 0;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

autostartOnce flag is cleared but never persisted

virDomainDriverAutoStartOne() resets vm->autostartOnce = 0, yet it
never calls virDomainSaveStatus()/virDomainObjSaveStatus() (driver
dependent) to flush the change to disk. If libvirtd crashes after
starting the VM, the flag will still be set on next daemon start and the
VM autostarts again, violating the “once” contract.

Ensure the driver’s state-save helper is invoked after modifying the
flag, e.g.:

     vm->autostartOnce = 0;
+    if (virDomainObjSaveStatus(vm, state->cfg->stateDir) < 0)
+        VIR_WARN("Failed to persist autostartOnce reset for %s",
+                 vm->def->name);

Comment on lines +455 to 460
virSystemdNotifyReload();
if (virStateReload() < 0) {
VIR_WARN("Error while reloading drivers");
}
virSystemdNotifyReady();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider failing hard (or downgrading readiness) when reload fails

virSystemdNotifyReady() is invoked even if virStateReload() reports an error at line 456.
That means systemd will still be told the daemon is “ready” although at least one driver failed to re-initialise, which could mask a broken runtime state.

If the intent is to keep running in a degraded mode, that should be made explicit (e.g. send STATUS= with a degraded message). Otherwise, consider aborting or exiting with a non-zero status so systemd can restart the service.

Comment thread src/rpc/virnetdaemon.c
Comment on lines +891 to 908
virNetDaemonQuit(virNetDaemon *dmn)
{
VIR_LOCK_GUARD lock = virObjectLockGuard(dmn);

VIR_DEBUG("Setting state stop worker thread on dmn=%p to thr=%p", dmn, thr);
dmn->stateStopThread = g_steal_pointer(thr);
VIR_DEBUG("Quit requested %p", dmn);
dmn->quit = VIR_NET_DAEMON_QUIT_REQUESTED;
}


void
virNetDaemonQuit(virNetDaemon *dmn)
virNetDaemonQuitExecRestart(virNetDaemon *dmn)
{
VIR_LOCK_GUARD lock = virObjectLockGuard(dmn);

VIR_DEBUG("Quit requested %p", dmn);
dmn->quit = true;
VIR_DEBUG("Exec-restart requested %p", dmn);
dmn->quit = VIR_NET_DAEMON_QUIT_REQUESTED;
dmn->execRestart = true;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Idempotent quit requests & concurrent state checks

virNetDaemonQuit() and virNetDaemonQuitExecRestart() blindly overwrite dmn->quit, even if a more advanced phase (e.g. PRESERVING or WAITING) is already in progress.
That could regress the state machine (e.g. READY → REQUESTED) if multiple callers issue quit requests.

Recommend guarding with a “forward-only” update:

if (dmn->quit < VIR_NET_DAEMON_QUIT_REQUESTED)
    dmn->quit = VIR_NET_DAEMON_QUIT_REQUESTED;

Same applies to the exec-restart variant.

Comment thread src/rpc/virnetdaemon.c
Comment on lines +830 to +851
if (dmn->quit == VIR_NET_DAEMON_QUIT_REQUESTED) {
VIR_DEBUG("Process quit request");
virSystemdNotifyStopping();
virHashForEach(dmn->servers, daemonServerClose, NULL);

if (dmn->shutdownPreserveThread) {
VIR_DEBUG("Shutdown preserve thread running");
dmn->quit = VIR_NET_DAEMON_QUIT_PRESERVING;
dmn->preserveStart = g_get_monotonic_time();
dmn->preserveExtended = VIR_NET_DAEMON_PRESERVE_MIN_TIME;
virSystemdNotifyExtendTimeout(dmn->preserveExtended);
if ((dmn->preserveTimer = virEventAddTimeout(5 * 1000,
virNetDaemonPreserveTimer,
dmn, NULL)) < 0) {
VIR_WARN("Failed to register preservation timer");
/* hope for the best */
}
} else {
VIR_DEBUG("Ready to shutdown");
dmn->quit = VIR_NET_DAEMON_QUIT_READY;
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Error-handling gap when preservation timer registration fails

If virEventAddTimeout() at line 841 fails we merely print a warning and continue as if preservation were under way. The state machine will then sit forever in PRESERVING, because neither the timer nor the worker can advance us to READY.

Consider falling back to READY immediately when the timer cannot be registered:

-                if ((dmn->preserveTimer = virEventAddTimeout(...)) < 0) {
-                    VIR_WARN("Failed to register preservation timer");
-                    /* hope for the best */
-                }
+                if ((dmn->preserveTimer = virEventAddTimeout(...)) < 0) {
+                    VIR_WARN("Failed to register preservation timer – continuing without timeout extension");
+                    dmn->quit = VIR_NET_DAEMON_QUIT_READY;
+                }

Committable suggestion skipped: line range outside the PR's diff.

Comment thread src/rpc/virnetdaemon.c
Comment on lines +748 to +775
unsigned long long now = g_get_monotonic_time();
unsigned long long delta;

dmn->finished = true;
if (dmn->quit != VIR_NET_DAEMON_QUIT_PRESERVING)
return;

VIR_DEBUG("Started at %llu now %llu extended %u",
dmn->preserveStart, now, dmn->preserveExtended);

/* Time since start of preserving state in usec */
delta = now - dmn->preserveStart;
/* Converts to secs */
delta /= (1000ull * 1000ull);

/* Want extra seconds grace to ensure this timer fires
* again before system timeout expires, under high
* load conditions */
delta += VIR_NET_DAEMON_PRESERVE_MIN_TIME;

/* Deduct any extension we've previously asked for */
delta -= dmn->preserveExtended;

/* Tell systemd how much more we need to extend by */
virSystemdNotifyExtendTimeout(delta);
dmn->preserveExtended += delta;

VIR_DEBUG("Extended by %llu", delta);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Possible overflow & negative extension in timeout calculation

delta is computed in seconds from two g_get_monotonic_time() values (µs precision).
If preservation runs for a very long time the subtraction at line 768 (delta -= dmn->preserveExtended) may under-flow to a huge unsigned value, resulting in an absurd request to virSystemdNotifyExtendTimeout().

A safer formulation:

-    delta -= dmn->preserveExtended;
+    if (delta > dmn->preserveExtended)
+        delta -= dmn->preserveExtended;
+    else
+        delta = 0;

Also confirm that virSystemdNotifyExtendTimeout() accepts 64-bit input; if it’s only unsigned int, large values will wrap.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
unsigned long long now = g_get_monotonic_time();
unsigned long long delta;
dmn->finished = true;
if (dmn->quit != VIR_NET_DAEMON_QUIT_PRESERVING)
return;
VIR_DEBUG("Started at %llu now %llu extended %u",
dmn->preserveStart, now, dmn->preserveExtended);
/* Time since start of preserving state in usec */
delta = now - dmn->preserveStart;
/* Converts to secs */
delta /= (1000ull * 1000ull);
/* Want extra seconds grace to ensure this timer fires
* again before system timeout expires, under high
* load conditions */
delta += VIR_NET_DAEMON_PRESERVE_MIN_TIME;
/* Deduct any extension we've previously asked for */
delta -= dmn->preserveExtended;
/* Tell systemd how much more we need to extend by */
virSystemdNotifyExtendTimeout(delta);
dmn->preserveExtended += delta;
VIR_DEBUG("Extended by %llu", delta);
}
unsigned long long now = g_get_monotonic_time();
unsigned long long delta;
if (dmn->quit != VIR_NET_DAEMON_QUIT_PRESERVING)
return;
VIR_DEBUG("Started at %llu now %llu extended %u",
dmn->preserveStart, now, dmn->preserveExtended);
/* Time since start of preserving state in usec */
delta = now - dmn->preserveStart;
/* Converts to secs */
delta /= (1000ull * 1000ull);
/* Want extra seconds grace to ensure this timer fires
* again before system timeout expires, under high
* load conditions */
delta += VIR_NET_DAEMON_PRESERVE_MIN_TIME;
/* Deduct any extension we've previously asked for */
if (delta > dmn->preserveExtended)
delta -= dmn->preserveExtended;
else
delta = 0;
/* Tell systemd how much more we need to extend by */
virSystemdNotifyExtendTimeout(delta);
dmn->preserveExtended += delta;
VIR_DEBUG("Extended by %llu", delta);
}

@berrange berrange closed this May 16, 2025
berrange pushed a commit that referenced this pull request Oct 6, 2025
Variable 'master' needs to be free because it will be reassigned in
virNetDevOpenvswitchInterfaceGetMaster().

The leaked stack:
Direct leak of 11 byte(s) in 1 object(s) allocated from:
    #0 0x7f7dad8ba6df in __interceptor_malloc (/lib64/libasan.so.8+0xba6df)
    #1 0x7f7dad715728 in g_malloc (/lib64/libglib-2.0.so.0+0x60728)
    #2 0x7f7dad72d8b2 in g_strdup (/lib64/libglib-2.0.so.0+0x788b2)
    #3 0x7f7dacb63088 in g_strdup_inline /usr/include/glib-2.0/glib/gstrfuncs.h:321
    #4 0x7f7dacb63088 in virNetDevGetName ../src/util/virnetdev.c:823
    #5 0x7f7dacb63886 in virNetDevGetMaster ../src/util/virnetdev.c:909
    #6 0x7f7dacb90288 in virNetDevTapReattachBridge ../src/util/virnetdevtap.c:527
    #7 0x7f7dacd5cd67 in virDomainNetNotifyActualDevice ../src/conf/domain_conf.c:30505
    #8 0x7f7da3a10bc3 in qemuProcessNotifyNets ../src/qemu/qemu_process.c:3290
    #9 0x7f7da3a375c6 in qemuProcessReconnect ../src/qemu/qemu_process.c:9211
    #10 0x7f7dacc0cc53 in virThreadHelper ../src/util/virthread.c:256
    #11 0x7f7dac2875d4 in start_thread (/lib64/libc.so.6+0x875d4)
    #12 0x7f7dac3091bb in __GI___clone3 (/lib64/libc.so.6+0x1091bb)

Fixes: de938b9
Signed-off-by: QiangWei Zhang <[email protected]>
Reviewed-by: Peter Krempa <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants