Skip to content

Autoshutdown - #7

Merged
berrange merged 22 commits into
masterfrom
autoshutdown
Apr 24, 2025
Merged

berrange merged 22 commits into
masterfrom
autoshutdown

Conversation

@berrange

@berrange berrange commented Apr 23, 2025 •

Copy link
Copy Markdown
Owner

his series starts the work needed to obsolete the libvirt-guests.sh
script which has grown a surprisingly large amount of functionality.

Currently the virt daemons will acquire inhibitors to delay OS shutdown
when VMs are running. The libvirt-guests.service unit can be used to
call libvirt-guests.sh to shutdown running VMs on system shutdown.

This split is a bad architecture because libvirt-guests.service will
only run once the system has decided to initiate the shutdown sequence.

When the user requests as shutdown while inhibitors are present, logind
will emit a "PrepareForShutdown" signal over dbus. Applications are
supposed to respond to this by preserving state & releasing their
inhibitors, which in turns allows shutdown to be initiated.

The remote daemon already has support for listening for the
"PrepareForShutdown" signal, but only does this for session instances,
not system instances.

This series essentially takes that logic and expands it to run in the
system instances too, thus conceptually making libvirt-guests.service
obsolete.

It is slightly more complicated than that though for many reasons...

Saving running VMs can take a very long time. The inhibitor delay
can be as low as 5 seconds, and when killing a service, systemd may
not wait very long for it to terminate. libvirt-guests.service deals
with this by setting TimeoutStopSecs=0 to make systemd wait forever.

This is undesirable to set in libvirtd.service though, as we would
like systemd to kill the daemon aggressively if it hangs. The series
thus uses the notification protocol to request systemd give it more
time to shutdown, as long as we're in the phase of saving running
VMs. A bug in this code will still result in systemd waiting forever,
which is no different from libvirt-guests.service, but a bug in any
other part of the libvirt daemon shutdown code will result in systemd
killing us.

The existing logic for saving VMs in the session daemons had many
feature gaps compared to libvirt-guests.sh. Thus there is code to
add support

  • 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 daemon shutdown and VM autostart capabilities by implementing a more flexible and robust mechanism for handling system shutdown and VM lifecycle management

New Features:

  • Introduce one-time autostart functionality for domains
  • Add configurable auto-shutdown strategies for VMs during system shutdown
  • Implement new virt-admin daemon-shutdown command with optional state preservation

Enhancements:

  • Improve daemon shutdown process with more granular lifecycle management
  • Add support for preserving VM state during system shutdown
  • Extend autostart functionality to support one-time boot configuration

Chores:

  • Refactor daemon shutdown logic to support more complex shutdown scenarios
  • Update configuration handling for new auto-shutdown options

Summary by CodeRabbit

  • New Features

    • Added "autostart once" support, allowing domains to be set to autostart only on the next boot.
    • Extended the "autostart" command with a new "once" option in management tools.
    • Introduced a new daemon-shutdown command in virt-admin, with an optional --preserve flag to save daemon state before shutdown.
    • Enhanced domain information display to show "Autostart Once" status.
    • Added configuration options for automatic VM shutdown actions during host or session termination, including managed save, graceful shutdown, and forced poweroff.
  • Bug Fixes

    • Improved shutdown handling for daemons, providing more reliable and configurable shutdown processes.
  • Documentation

    • Updated manpages and configuration templates to describe new commands and options.
    • Expanded function documentation for shutdown and lifecycle management.
  • Refactor

    • Simplified and clarified the daemon shutdown process with a multi-phase state machine and improved callback handling.

berrange added 22 commits March 20, 2025 14:55
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.

Reviewed-by: Peter Krempa <[email protected]>
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.

Reviewed-by: Peter Krempa <[email protected]>
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.

Reviewed-by: Peter Krempa <[email protected]>
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.

This also lets us fix a long standing problem with incorrectly
attempting to perform managed save on transient VMs.

Reviewed-by: Peter Krempa <[email protected]>
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 = "persistent"
  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.

Reviewed-by: Peter Krempa <[email protected]>
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.

Reviewed-by: Peter Krempa <[email protected]>
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.

Reviewed-by: Peter Krempa <[email protected]>
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.

Reviewed-by: Peter Krempa <[email protected]>
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.

Reviewed-by: Peter Krempa <[email protected]>
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.

Reviewed-by: Peter Krempa <[email protected]>
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'.

Reviewed-by: Peter Krempa <[email protected]>
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.

Reviewed-by: Peter Krempa <[email protected]>
Signed-off-by: Daniel P. Berrangé <[email protected]>
Reviewed-by: Peter Krempa <[email protected]>
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.

Reviewed-by: Peter Krempa <[email protected]>
Signed-off-by: Daniel P. Berrangé <[email protected]>
It is not documented what the various virStateNNN methods are each
responsible for doing and the names give little guidance either.
Provide some useful documentation comments to explain the intended
usage of each.

Reviewed-by: Peter Krempa <[email protected]>
Signed-off-by: Daniel P. Berrangé <[email protected]>
The next patch will be introducing a new callback, so rename the method
to virNetDaemonSetLifecycleCallbacks to reflect the more general usage.

Reviewed-by: Peter Krempa <[email protected]>
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.

Reviewed-by: Peter Krempa <[email protected]>
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.

Reviewed-by: Peter Krempa <[email protected]>
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.

Reviewed-by: Peter Krempa <[email protected]>
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.

Reviewed-by: Peter Krempa <[email protected]>
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.

Reviewed-by: Peter Krempa <[email protected]>
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.

The systemd status is a point-in-time message, with no ability to
look at the history of received messages. So in the systemd status
we include the progress information. For the same reason there is
no benefit in sending failure messages, as they'll disappear as soon
as a status is sent for the subsequent VM to be processed.

The libvirt log statements can be viewed as a complete log record
so don't need progress info, but do include warnings about failures
(present from earlier commits).

Reviewed-by: Peter Krempa <[email protected]>
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 a comprehensive auto-shutdown mechanism for libvirt, replacing the libvirt-guests.sh script. It includes configurable shutdown strategies (save, graceful shutdown, poweroff), one-time autostart functionality, and a new virt-admin daemon-shutdown command. The changes span multiple files, including core libvirt components, the QEMU driver, the remote daemon, and various tools.

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).
  • Added VIR_ENUM_IMPL macro to implement the enum.
  • Added virDomainDriverAutoShutdownScopeTypeToString and virDomainDriverAutoShutdownScopeTypeFromString functions.
src/hypervisor/domain_driver.c
src/hypervisor/domain_driver.h
Implemented the virDomainDriverAutoShutdown function to manage VM shutdown during host OS shutdown, including saving, graceful shutdown, and poweroff based on the configured scope.
  • Opened a connection to libvirt.
  • Listed all active domains.
  • Iterated through domains, determining if they are persistent or transient.
  • Managed saving VMs based on the trySave scope.
  • Managed graceful shutdown of VMs based on the tryShutdown scope.
  • Managed poweroff of VMs based on the poweroff scope.
  • Used virSystemdNotifyStatus to update systemd about the shutdown progress.
src/hypervisor/domain_driver.c
Modified the daemon's lifecycle to include a stop phase, shutdown preparation, and a wait phase, managed by callbacks.
  • Added virNetDaemonQuitPhase enum to track the daemon's shutdown state.
  • Added stopCb, shutdownPrepareCb, and shutdownWaitCb callbacks to virNetDaemon struct.
  • Implemented virNetDaemonStop to handle the stop phase, using a worker thread.
  • Modified virNetDaemonRun to manage the shutdown lifecycle, including timers and systemd notifications.
src/rpc/virnetdaemon.c
src/rpc/virnetdaemon.h
Integrated the new auto-shutdown logic into the QEMU driver, utilizing the virDomainDriverAutoShutdown function.
  • Modified qemuStateStop to use virDomainDriverAutoShutdown for VM shutdown.
  • Added qemuDomainGetAutostartOnce and qemuDomainSetAutostartOnce functions to manage one-time autostart.
  • Updated qemuHypervisorDriver struct to include the new functions.
src/qemu/qemu_driver.c
Added virDomainGetAutostartOnce and virDomainSetAutostartOnce functions to the libvirt API to manage one-time autostart for domains.
  • Implemented the new API functions in libvirt-domain.c.
  • Updated the virHypervisorDriver struct in driver-hypervisor.h to include the new functions.
  • Updated the remote protocol to include the new functions.
src/libvirt-domain.c
src/driver-hypervisor.h
src/remote/remote_protocol.x
Modified the remote daemon to handle system shutdown signals and session disconnects, triggering the daemon stop and quit procedures.
  • Updated handleSystemMessageFunc and handleSessionMessageFunc to call virNetDaemonStop and virNetDaemonQuit.
  • Registered signal handlers for PrepareForShutdown and Disconnected events.
src/remote/remote_daemon.c
Added new configuration options to qemu.conf to control auto-shutdown behavior, including scopes for save, shutdown, and poweroff actions.
  • Added autoShutdownTrySave, autoShutdownTryShutdown, and autoShutdownPoweroff options.
  • Added autoShutdownWait, autoShutdownRestore, and autoSaveBypassCache options.
  • Updated virQEMUDriverConfigLoadSaveEntry to load the new configuration options.
src/qemu/qemu_conf.c
src/qemu/qemu_conf.h
src/qemu/libvirtd_qemu.aug
Added a new daemon-shutdown command to virt-admin to trigger daemon shutdown with an option to preserve state.
  • Implemented the cmdDaemonShutdown function.
  • Added the daemon-shutdown command to the managementCmds array.
  • Updated virAdmConnectDaemonShutdown in libvirt-admin.c and admin_server_dispatch.c.
  • Updated the remote protocol to include the new command.
tools/virt-admin.c
src/admin/libvirt-admin.c
src/admin/admin_server_dispatch.c
src/remote/remote_protocol.x
Added a --once option to the virsh autostart command to control the autostart behavior for the next boot only.
  • Added the once option to the opts_autostart array.
  • Modified the cmdAutostart function to handle the once option.
  • Used virDomainSetAutostartOnce to set the autostart-once state.
tools/virsh-domain.c
Added support for displaying the autostart-once state in the virsh dominfo command.
  • Modified the cmdDominfo function to display the autostart-once state.
tools/virsh-domain-monitor.c
Modified the domain object to include an autostartOnce flag and a link to the autostart-once file.
  • Added autostartOnce and autostartOnceLink members to the _virDomainObj struct.
  • Updated virDomainObjDispose to free the autostartOnceLink.
  • Updated virDomainObjListLoadConfig to load the autostartOnce state from the config file.
src/conf/domain_conf.c
src/conf/domain_conf.h
src/conf/virdomainobjlist.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:

  • Consider adding a comment about the upgrade story with libvirt-guests.service to the documentation.
  • The commit message mentions virt-admin, but there are no tests for the new virt-admin command.
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 virNetDaemonQuitPhase and the refactoring of the shutdown process in virNetDaemonRun looks good.
  • Consider adding a comment to explain why the stopCb is only called if quit != VIR_NET_DAEMON_QUIT_NONE in virNetDaemonStop.
Here's what I looked at during the review
  • 🟡 General issues: 1 issue found
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟡 Complexity: 1 issue found
  • 🟢 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.


Instruct the daemon to exit gracefully. If the ``--preserve`` flag is given,
it will save state in the same manner that would be done on a host OS shutdown
(privileged daemons) or a login session quit (unprivileged daemons).

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

nitpick (typo): Minor typo: 'host OS shutdown'

It seems like there's a small typo. Should it be 'host OS shutdown' instead of just 'OS shutdown'?

Suggested implementation:

it will save state in the same manner that would be done on a host OS shutdown

Ensure that if there are any other occurrences of "OS shutdown" that lack the "host" prefix, they are updated similarly.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

This is nonsense. The code is already written the way you've suggested to write it.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

I apologize for my previous review comment. Upon reviewing the code and the conversation, it's clear that my suggestion was unnecessary and incorrect. The original text is already correct and precise.

In this case, the best response is to acknowledge the maintainer's feedback and recognize that no change is needed. I'll refrain from making further comments on this specific detail.

}


void

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

issue (complexity): Consider extracting the shutdown actions into separate helper functions to improve readability and maintainability of the code in virDomainDriverAutoShutdown function, by reducing its cyclomatic complexity and improving its structure..

Consider extracting the different shutdown actions into separate helper functions. This will simplify the nested loops and conditionals in virDomainDriverAutoShutdown while keeping the functionality intact. For example, you might create three helpers, one for each action:

static void perform_managed_save(virDomainPtr *domains, bool *transient, size_t numDomains,
                                 virDomainDriverAutoShutdownConfig *cfg) {
    unsigned int *flags = g_new0(unsigned int, numDomains);
    for (size_t i = 0; i < numDomains; i++) {
        int state;
        if ((transient[i] && cfg->trySave == VIR_DOMAIN_DRIVER_AUTO_SHUTDOWN_SCOPE_PERSISTENT) ||
            (!transient[i] && cfg->trySave == VIR_DOMAIN_DRIVER_AUTO_SHUTDOWN_SCOPE_TRANSIENT))
            continue;
        // ... Prepare flags, pause domains, etc.
    }
    for (size_t i = 0; i < numDomains; i++) {
        // ... Perform managed save, handle failures, etc.
    }
}

Similarly, extract shutdown and poweroff actions:

static void perform_shutdown(virDomainPtr *domains, bool *transient, size_t numDomains,
                             virDomainDriverAutoShutdownConfig *cfg) {
    for (size_t i = 0; i < numDomains; i++) {
        if (!domains[i])
            continue;
        if ((transient[i] && cfg->tryShutdown == VIR_DOMAIN_DRIVER_AUTO_SHUTDOWN_SCOPE_PERSISTENT) ||
            (!transient[i] && cfg->tryShutdown == VIR_DOMAIN_DRIVER_AUTO_SHUTDOWN_SCOPE_TRANSIENT))
            continue;
        // ... Initiate shutdown request and log messages
    }
    // Extract and use a helper for the waiting loop if desired.
}

static void perform_poweroff(virDomainPtr *domains, bool *transient, size_t numDomains,
                            virDomainDriverAutoShutdownConfig *cfg) {
    for (size_t i = 0; i < numDomains; i++) {
        if (!domains[i])
            continue;
        if ((transient[i] && cfg->poweroff == VIR_DOMAIN_DRIVER_AUTO_SHUTDOWN_SCOPE_PERSISTENT) ||
            (!transient[i] && cfg->poweroff == VIR_DOMAIN_DRIVER_AUTO_SHUTDOWN_SCOPE_TRANSIENT))
            continue;
        // ... Perform destroy and unref logic.
    }
}

Finally, refactor virDomainDriverAutoShutdown to orchestrate these helpers:

void virDomainDriverAutoShutdown(virDomainDriverAutoShutdownConfig *cfg) {
    // ... Setup and common logic

    // Mark for auto-restore loop
    for (size_t i = 0; i < numDomains; i++) {
      // ... Auto-restore logic
    }

    if (cfg->trySave != VIR_DOMAIN_DRIVER_AUTO_SHUTDOWN_SCOPE_NONE)
        perform_managed_save(domains, transient, numDomains, cfg);

    if (cfg->tryShutdown != VIR_DOMAIN_DRIVER_AUTO_SHUTDOWN_SCOPE_NONE)
        perform_shutdown(domains, transient, numDomains, cfg);

    if (cfg->poweroff != VIR_DOMAIN_DRIVER_AUTO_SHUTDOWN_SCOPE_NONE)
        perform_poweroff(domains, transient, numDomains, cfg);

    // ... Cleanup logic
}

This refactoring improves readability and makes it easier to maintain or test each shutdown action individually.

@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 virNetDaemonQuitPhase and the refactoring of the shutdown process in virNetDaemonRun looks good.
  • Consider adding a comment to explain why the stopCb is only called if quit != VIR_NET_DAEMON_QUIT_NONE in virNetDaemonStop.
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/hypervisor/domain_driver.c Resolved
@berrange
berrange merged commit 563d3cf into master Apr 24, 2025
@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

Pointer Initialization

The new autostartOnceLink field must be initialized to NULL in every code path (especially in virDomainObjNew) to avoid uninitialized-pointer free or unlink calls later.

virDomainDeleteConfig(const char *configDir,
                      const char *autostartDir,
                      virDomainObj *dom)
{
    g_autofree char *configFile = NULL;
    g_autofree char *autostartLink = NULL;
    g_autofree char *autostartOnceLink = NULL;

    configFile = virDomainConfigFile(configDir, dom->def->name);
    autostartLink = virDomainConfigFile(autostartDir, dom->def->name);
    autostartOnceLink = g_strdup_printf("%s.once", autostartLink);
Safe Unlink

The call to unlink(autostartOnceLink) in virDomainDeleteConfig is unguarded; verify that the path is valid and that autostartOnceLink wasn’t empty or stale to prevent spurious errors or unintended file operations.

autostartOnceLink = g_strdup_printf("%s.once", autostartLink);

/* Not fatal if these don't work */
unlink(autostartLink);
unlink(autostartOnceLink);
dom->autostart = 0;
dom->autostartOnce = 0;
Shutdown Ordering

The new virNetDaemonStop and virNetDaemonQuit calls in DBus signal handlers may race with the main loop’s shutdown; double-check that lifecycle callbacks and locks correctly serialize stop, prepare, and quit phases to avoid deadlocks or premature exit.

{ REMOTE_PROC_DOMAIN_EVENT_CALLBACK_RTC_CHANGE,
  remoteDomainBuildEventCallbackRTCChange,
  sizeof(remote_domain_event_callback_rtc_change_msg),
  (xdrproc_t)xdr_remote_domain_event_callback_rtc_change_msg },
{ REMOTE_PROC_DOMAIN_EVENT_CALLBACK_WATCHDOG,
  remoteDomainBuildEventCallbackWatchdog,
  sizeof(remote_domain_event_callback_watchdog_msg),
  (xdrproc_t)xdr_remote_domain_event_callback_watchdog_msg},
{ REMOTE_PROC_DOMAIN_EVENT_CALLBACK_IO_ERROR,

@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

Caution

Review failed

The pull request is closed.

Walkthrough

This update introduces new features and enhancements to libvirt's domain and daemon management. It adds a "one-time autostart" capability for domains, allowing them to be configured to autostart only on the next boot, with corresponding API, driver, and CLI support. The shutdown process for the daemon is refactored into a multi-phase state machine, enabling more granular lifecycle management and explicit stop, prepare, and wait callbacks. New configuration options are provided for automatic VM shutdown behavior during host or session termination, including managed save, graceful shutdown, and forced poweroff, with tunable scopes and timeouts. The virt-admin and virsh tools are extended with new commands and options to utilize these features.

Changes

File(s) / Path(s) Change Summary
include/libvirt/libvirt-domain.h, src/libvirt-domain.c, src/libvirt_public.syms, tools/virsh-domain-monitor.c, tools/virsh-domain.c, src/remote/remote_protocol.x, src/remote_protocol-structs, src/remote/remote_driver.c, src/qemu/qemu_driver.c, src/conf/domain_conf.h, src/conf/domain_conf.c, src/conf/virdomainobjlist.c Added "autostart once" feature for domains: new APIs, driver support, CLI options, and internal fields to set/get one-time autostart behavior.
include/libvirt/libvirt-admin.h, src/admin/libvirt-admin.c, src/admin/admin_protocol.x, src/admin_protocol-structs, src/admin/admin_server_dispatch.c, src/admin/libvirt_admin_public.syms, tools/virt-admin.c, docs/manpages/virt-admin.rst Added new daemon shutdown API and CLI command, supporting a --preserve flag to save state before shutdown, with protocol and documentation updates.
src/rpc/virnetdaemon.c, src/rpc/virnetdaemon.h, src/libvirt_remote.syms, src/remote/remote_daemon.c Refactored daemon shutdown to a multi-phase state machine with explicit stop, prepare, and wait lifecycle callbacks, improved systemd notification, and updated callback registration.
src/hypervisor/domain_driver.c, src/hypervisor/domain_driver.h, src/libvirt_private.syms Added automatic domain shutdown logic with configurable scopes (none, persistent, transient, all), new config struct, and shutdown orchestration function.
src/qemu/qemu_conf.c, src/qemu/qemu_conf.h, src/qemu/qemu.conf.in, src/qemu/libvirtd_qemu.aug, src/qemu/test_libvirtd_qemu.aug.in Introduced new configuration options for auto shutdown/save behavior, including scope, wait time, restore, and cache bypass, with documentation and parser updates.
src/qemu/qemu_driver.c Simplified QEMU driver shutdown logic to delegate to new auto-shutdown function; registered new autostart-once driver methods.
src/rpc/gendispatch.pl Updated internal pattern matching to support new autostart-once procedures for code generation.
src/libvirt.c Enhanced documentation for shutdown/stop/reload/cleanup driver lifecycle functions; no code logic changes.
src/driver-hypervisor.h Added new function pointers for autostart-once operations to driver interface.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant virsh/virt-admin
    participant libvirt API
    participant Hypervisor Driver
    participant Daemon

    User->>virsh/virt-admin: Run "autostart --once" or "daemon-shutdown --preserve"
    virsh/virt-admin->>libvirt API: virDomainSetAutostartOnce / virAdmConnectDaemonShutdown
    libvirt API->>Hypervisor Driver: Set/Get autostartOnce / Initiate shutdown
    Hypervisor Driver->>Daemon: Update domain config / Begin shutdown sequence
    Daemon->>Hypervisor Driver: (On shutdown) stop, prepare, wait callbacks
    Daemon->>User: Command result (success/failure)
Loading
sequenceDiagram
    participant Systemd/OS
    participant Daemon
    participant Hypervisor Driver

    Systemd/OS->>Daemon: Host shutdown or session end signal
    Daemon->>Hypervisor Driver: stopCb (preserve state)
    Daemon->>Hypervisor Driver: prepareCb (prepare for shutdown)
    Daemon->>Hypervisor Driver: waitCb (finalize shutdown)
    Daemon->>Systemd/OS: Notify completion
Loading

Poem

In the warren of code, new features bloom,
One-time autostart hops into the room.
Daemons now slumber with graceful finesse,
Preserving their state at your gentle request.
Domains can awaken just once, then rest,
While shutdowns proceed in orderly quest.
🐇 Cheers to the team—onward, hop to the next!


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f48fb17 and 563d3cf.

📒 Files selected for processing (35)
  • docs/manpages/virt-admin.rst (1 hunks)
  • 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/admin_protocol-structs (2 hunks)
  • src/conf/domain_conf.c (2 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 (4 hunks)
  • src/hypervisor/domain_driver.h (2 hunks)
  • src/libvirt-domain.c (1 hunks)
  • src/libvirt.c (5 hunks)
  • src/libvirt_private.syms (1 hunks)
  • src/libvirt_public.syms (1 hunks)
  • src/libvirt_remote.syms (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 (2 hunks)
  • src/qemu/qemu_driver.c (3 hunks)
  • src/qemu/test_libvirtd_qemu.aug.in (1 hunks)
  • src/remote/remote_daemon.c (3 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)
  • tools/virsh-domain-monitor.c (1 hunks)
  • tools/virsh-domain.c (2 hunks)
  • tools/virt-admin.c (2 hunks)
✨ 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 mentioned this pull request Apr 24, 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