Skip to content

Autoshutdown - #10

Closed
berrange wants to merge 22 commits into
middlemasterfrom
autoshutdown
Closed

berrange wants to merge 22 commits into
middlemasterfrom
autoshutdown

Conversation

@berrange

@berrange berrange commented Apr 24, 2025 •

Copy link
Copy Markdown
Owner

Summary by Sourcery

Implement advanced domain autostart and daemon shutdown features, enhancing system shutdown and VM lifecycle management

New Features:

  • Add support for one-time domain autostart
  • Implement configurable auto-shutdown scopes for VMs during system shutdown
  • Add daemon shutdown with state preservation option

Enhancements:

  • Improve daemon shutdown process with more granular state management
  • Add more flexible VM autostart configuration
  • Enhance systemd integration for daemon and VM lifecycle management

Chores:

  • Update multiple configuration and protocol files to support new features
  • Add new API methods for domain and daemon management

Summary by CodeRabbit

  • New Features

    • Added support for configuring domains to autostart only once on the next boot, with new commands and options in management tools.
    • Introduced a new daemon-shutdown command in virt-admin, allowing graceful daemon shutdown with an optional state preservation flag.
    • Enhanced QEMU configuration with options for automatic VM shutdown actions during host or session shutdown, including managed save, graceful shutdown, forced poweroff, wait time, restore, and cache bypass settings.
  • Improvements

    • Updated domain information and autostart commands in management tools to display and control the new "autostart once" property.
    • Improved daemon shutdown handling with multi-phase lifecycle callbacks and better integration with system shutdown signals.
  • Documentation

    • Expanded manpages and configuration file comments to document new commands and configuration options for shutdown and autostart behavior.

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 24, 2025 •

Copy link
Copy Markdown

Reviewer's Guide by Sourcery

This pull request introduces several major features:

  1. Automatic shutdown of domains based on configuration, including save, shutdown, and poweroff actions.
  2. Support for 'autostartOnce' to automatically start domains only on the next boot.
  3. Refactoring of the daemon shutdown process to use a state machine and lifecycle callbacks for more controlled shutdown.
  4. Adds configuration options for auto-shutdown behavior to the QEMU driver.

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

File-Level Changes

Change Details Files
Introduces a new enum virDomainDriverAutoShutdownScope to define the scope of auto-shutdown actions (none, persistent, transient, all).
  • Adds VIR_DOMAIN_DRIVER_AUTO_SHUTDOWN_SCOPE_NONE
  • Adds VIR_DOMAIN_DRIVER_AUTO_SHUTDOWN_SCOPE_PERSISTENT
  • Adds VIR_DOMAIN_DRIVER_AUTO_SHUTDOWN_SCOPE_TRANSIENT
  • Adds VIR_DOMAIN_DRIVER_AUTO_SHUTDOWN_SCOPE_ALL
  • Adds VIR_DOMAIN_DRIVER_AUTO_SHUTDOWN_SCOPE_LAST
  • Implements VIR_ENUM_IMPL for the new enum.
src/hypervisor/domain_driver.c
src/hypervisor/domain_driver.h
Implements automatic shutdown functionality for domains based on the defined scope, including saving, shutting down, and powering off domains.
  • Adds a new function virDomainDriverAutoShutdown to handle the auto-shutdown process.
  • Retrieves a list of active domains.
  • Iterates through the domains and performs actions (save, shutdown, poweroff) based on the configuration and domain type (persistent/transient).
  • Uses virDomainManagedSave to save domains.
  • Uses virDomainShutdown to gracefully shutdown domains.
  • Uses virDomainDestroy to power off domains.
  • Logs warnings for domains that fail to shut down properly.
  • Introduces virDomainDriverAutoShutdownConfig struct to configure the auto shutdown.
  • Uses virSystemdNotifyStatus to update systemd about the shutdown progress.
src/hypervisor/domain_driver.c
Adds support for 'autostartOnce' to domains, allowing them to be automatically started only on the next boot.
  • Adds autostartOnce field to virDomainObj struct.
  • Adds functions qemuDomainGetAutostartOnce and qemuDomainSetAutostartOnce to manage the autostartOnce setting for QEMU domains.
  • Adds functions virDomainGetAutostartOnce and virDomainSetAutostartOnce to the libvirt API.
  • Modifies virDomainDriverAutoStartOne to respect the autostartOnce flag.
  • Adds a new option '--once' to the 'virsh autostart' command to control the autostart once setting.
  • Adds logic to create and remove a symlink with a '.once' suffix in the autostart directory to persist the autostartOnce setting.
  • Adds autostartOnceLink field to virDomainObj struct to store the path to the autostart once symlink.
src/hypervisor/domain_driver.c
src/qemu/qemu_driver.c
src/libvirt-domain.c
tools/virsh-domain.c
src/conf/virdomainobjlist.c
src/conf/domain_conf.c
include/libvirt/libvirt-domain.h
Refactors the daemon shutdown process to use a state machine and lifecycle callbacks, allowing for more controlled and flexible shutdown procedures.
  • Introduces a new enum virNetDaemonQuitPhase to represent the different phases of the daemon shutdown process.
  • Adds stopCb, shutdownPrepareCb, and shutdownWaitCb lifecycle callbacks to the virNetDaemon struct.
  • Replaces the quit and finished boolean flags with the quit enum to track the shutdown phase.
  • Adds a stopTimer and quitTimer to manage timeouts during the shutdown process.
  • Modifies virNetDaemonRun to use the state machine and lifecycle callbacks to manage the shutdown process.
  • Adds a virNetDaemonStop function to initiate the state stop process.
  • Adds a virNetDaemonSetLifecycleCallbacks function to set the lifecycle callbacks.
  • Removes the virNetDaemonSetStateStopWorkerThread function.
  • Updates the remote daemon to use the new lifecycle callbacks and state stop mechanism.
  • Adds virAdmConnectDaemonShutdown to trigger the daemon shutdown.
src/rpc/virnetdaemon.c
src/rpc/virnetdaemon.h
src/remote/remote_daemon.c
src/admin/libvirt-admin.c
src/admin/admin_server_dispatch.c
src/admin/admin_protocol.x
include/libvirt/libvirt-admin.h
Adds configuration options for auto-shutdown behavior to the QEMU driver, including settings for save, shutdown, poweroff, wait time, restore, and bypass cache.
  • Adds autoShutdownTrySave, autoShutdownTryShutdown, autoShutdownPoweroff, autoShutdownWait, autoShutdownRestore, and autoSaveBypassCache fields to the virQEMUDriverConfig struct.
  • Updates virQEMUDriverConfigNew to initialize the new configuration options.
  • Updates virQEMUDriverConfigLoadSaveEntry to load the new configuration options from the configuration file.
  • Updates qemuStateStop to use virDomainDriverAutoShutdown to perform the auto-shutdown actions.
  • Adds corresponding entries to the libvirtd_qemu.aug Augeas lens file to manage the new configuration options.
src/qemu/qemu_driver.c
src/qemu/qemu_conf.c
src/qemu/qemu_conf.h
src/qemu/libvirtd_qemu.aug
Updates the virState functions to use the new lifecycle callbacks for driver shutdown.
  • Updates virStateShutdownPrepare to call the shutdownPrepare callback for each driver.
  • Updates virStateShutdownWait to call the shutdownWait callback for each driver.
  • Updates virStateStop to call the stop callback for each driver.
src/libvirt.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

@coderabbitai

coderabbitai Bot commented Apr 24, 2025 •

Copy link
Copy Markdown

Walkthrough

This update introduces two significant features to the virtualization management system. First, it adds a new "autostart once" capability for domains, allowing administrators to configure a domain to automatically start only on the next boot, with corresponding API, driver, remote protocol, and CLI support. Second, it implements a multi-phase, stateful shutdown process for the daemon, including a new daemon-shutdown command (with an optional --preserve flag) in the admin CLI and protocol, enhanced daemon lifecycle callbacks, and improved systemd integration. Additionally, new configuration options for automatic domain shutdown and save behavior are added to QEMU driver configuration and documentation.

Changes

File(s) / Path(s) Change Summary
docs/manpages/virt-admin.rst, tools/virt-admin.c Added documentation and implementation for the new daemon-shutdown command in virt-admin, supporting an optional --preserve flag to save daemon state before shutdown.
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, src/admin_protocol-structs Added API, protocol, and server-side handling for virAdmConnectDaemonShutdown, including a new flag for preserving state. Updated symbol exports accordingly.
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, src/qemu/qemu_driver.c, tools/virsh-domain.c, tools/virsh-domain-monitor.c Introduced "autostart once" feature for domains: new API functions (virDomainGetAutostartOnce, virDomainSetAutostartOnce), protocol support, remote driver implementation, QEMU driver support, and CLI integration in virsh commands and info output. Updated symbol exports.
src/conf/domain_conf.h, src/conf/domain_conf.c, src/conf/virdomainobjlist.c Extended domain object structure and configuration management to support autostartOnce flag and associated symlink, including cleanup and load logic.
src/driver-hypervisor.h, src/hypervisor/domain_driver.c, src/hypervisor/domain_driver.h, src/libvirt_private.syms Added domain driver interface and implementation for automatic domain shutdown, including a configuration structure, shutdown scope enum, and the virDomainDriverAutoShutdown function. Updated symbol exports.
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 Added new configuration fields and documentation for automatic shutdown and save behavior in QEMU driver, including parsing, validation, and defaulting logic for new options. Updated Augeas lens and test configuration.
src/rpc/virnetdaemon.c, src/rpc/virnetdaemon.h, src/libvirt_remote.syms Refactored daemon shutdown to a multi-phase state machine with explicit lifecycle callbacks (stopCb, prepareCb, waitCb), added virNetDaemonStop, and updated callback registration. Updated symbol exports and header.
src/remote/remote_daemon.c Simplified daemon stop logic by removing asynchronous stop worker/thread, directly calling stop and quit functions in D-Bus signal handlers, and updating lifecycle callback registration and signal subscription logic.
src/rpc/gendispatch.pl Updated regex patterns to handle new GetAutostartOnce procedures for server/client dispatch code generation.
src/libvirt.c Expanded and clarified documentation comments for shutdown, stop, and cleanup lifecycle functions; no code changes.

Sequence Diagram(s)

sequenceDiagram
    participant AdminCLI as virt-admin
    participant AdminAPI as libvirt-admin
    participant Daemon as libvirt daemon

    AdminCLI->>AdminAPI: virAdmConnectDaemonShutdown(flags)
    AdminAPI->>Daemon: ADMIN_PROC_CONNECT_DAEMON_SHUTDOWN (flags)
    Daemon->>Daemon: If preserve flag: prepare state
    Daemon->>Daemon: Initiate shutdown (multi-phase)
    Daemon-->>AdminAPI: Success/Failure
    AdminAPI-->>AdminCLI: Return result
Loading
sequenceDiagram
    participant User as virsh
    participant Libvirt as libvirt
    participant Driver as QEMU/Remote Driver

    User->>Libvirt: virDomainSetAutostartOnce(domain, autostart)
    Libvirt->>Driver: .domainSetAutostartOnce(domain, autostart)
    Driver->>Driver: Update autostartOnce flag and symlink
    Driver-->>Libvirt: Return status
    Libvirt-->>User: Success/Failure

    User->>Libvirt: virDomainGetAutostartOnce(domain, &autostart)
    Libvirt->>Driver: .domainGetAutostartOnce(domain, &autostart)
    Driver-->>Libvirt: Return autostartOnce value
    Libvirt-->>User: Return autostartOnce value
Loading

Possibly related PRs

  • berrange/libvirt#7: Implements the same features—daemon shutdown with preserve flag, new admin protocol, and the "autostart once" domain property—indicating direct overlap in code and functionality.

Poem

In the warren of code, a new dawn is begun,
Domains leap up just once, then their race is run.
The daemon now slumbers in orderly grace,
With shutdowns in phases, not a moment to waste.
New configs for QEMU, more power to wield—
This bunny’s delighted by the features revealed!
🐇✨

✨ 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.

@berrange

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Apr 24, 2025

Copy link
Copy Markdown
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@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 virNetDaemon lifecycle callbacks should be documented in virNetDaemonSetLifecycleCallbacks.
  • The auto-shutdown feature should have a test case to ensure it functions as expected.
Here's what I looked at during the review
  • 🟢 General issues: all looks good
  • 🟢 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.

}


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 refactoring the virDomainDriverAutoShutdown function into smaller helper functions to improve readability and reduce complexity.

The new function increases complexity by combining many behaviors into one large function. Consider breaking it into several smaller helpers to isolate concerns and reduce deeply nested conditionals.

For example, you could split the auto-restore, managed save, graceful shutdown, and power-off steps into separate functions. Here’s a small sketch to illustrate one possible refactoring:

static void processAutoRestore(virDomainPtr domains[], bool transient[], int numDomains,
                               virDomainDriverAutoShutdownConfig *cfg) {
    for (size_t i = 0; i < numDomains; i++) {
        if (cfg->autoRestore) {
            if (transient[i]) {
                VIR_DEBUG("Cannot auto-restore transient VM %s", virDomainGetName(domains[i]));
            } else {
                VIR_DEBUG("Mark %s for autostart on next boot", virDomainGetName(domains[i]));
                if (virDomainSetAutostartOnce(domains[i], 1) < 0) {
                    VIR_WARN("Unable to mark domain '%s' for auto restore: %s",
                             virDomainGetName(domains[i]), virGetLastErrorMessage());
                }
            }
        }
    }
}

static void performManagedSave(virDomainPtr domains[], bool transient[], int 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;

        virSystemdNotifyStatus("Suspending '%s' (%zu of %d)",
                               virDomainGetName(domains[i]), i + 1, numDomains);
        VIR_INFO("Suspending '%s'", virDomainGetName(domains[i]));

        flags[i] = VIR_DOMAIN_SAVE_RUNNING;
        if (virDomainGetState(domains[i], &state, NULL, 0) == 0) {
            if (state == VIR_DOMAIN_PAUSED)
                flags[i] = VIR_DOMAIN_SAVE_PAUSED;
        }
        if (cfg->saveBypassCache)
            flags[i] |= VIR_DOMAIN_SAVE_BYPASS_CACHE;

        if (flags[i] & VIR_DOMAIN_SAVE_RUNNING)
            virDomainSuspend(domains[i]);
    }

    for (size_t i = 0; i < numDomains; i++) {
        virSystemdNotifyStatus("Saving '%s' (%zu of %d)",
                               virDomainGetName(domains[i]), i + 1, numDomains);
        VIR_INFO("Saving '%s'", virDomainGetName(domains[i]));

        if (virDomainManagedSave(domains[i], flags[i]) < 0) {
            VIR_WARN("auto-shutdown: unable to perform managed save of '%s': %s",
                     domains[i]->name, virGetLastErrorMessage());
            if (flags[i] & VIR_DOMAIN_SAVE_RUNNING)
                virDomainResume(domains[i]);
            continue;
        }
        virObjectUnref(domains[i]);
        domains[i] = NULL;
    }
    g_free(flags);
}

Then in your main virDomainDriverAutoShutdown function you can delegate tasks:

// ... domain discovery code ...

// Process auto-restore
processAutoRestore(domains, transient, numDomains, cfg);

// Process managed save, if enabled
if (cfg->trySave != VIR_DOMAIN_DRIVER_AUTO_SHUTDOWN_SCOPE_NONE)
    performManagedSave(domains, transient, numDomains, cfg);

// Similarly, extract shutdown and poweroff steps into helper functions
// ...

Actionable steps:

  1. Identify distinct operations (auto-restore, managed save, shutdown, poweroff).
  2. Create helper functions for each operation.
  3. Replace the nested loops and conditionals with calls to these helpers.
  4. Verify that each helper preserves the original functionality.

This refactoring will improve readability and reduce the cognitive load when maintaining this section of the code.

@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: 4

🔭 Outside diff range comments (2)
src/hypervisor/domain_driver.c (1)

687-708: 🛠️ Refactor suggestion

Autostart-once flag cleared even on failed start
vm->autostartOnce is reset (and the link unlinked) immediately after invoking callback, but the code does not verify that the VM actually became active. A failed start therefore loses the “once” request permanently.

-        state->cfg->callback(vm, state->cfg->opaque);
-        vm->autostartOnce = 0;
+        if (state->cfg->callback(vm, state->cfg->opaque) == 0 &&
+            virDomainObjIsActive(vm)) {
+            /* start succeeded – clear the flag */
+            vm->autostartOnce = 0;
+        }

(You may also want to move the symlink unlink() into the success branch.)

src/rpc/virnetdaemon.c (1)

138-147: ⚠️ Potential issue

Join the stateStopThread before freeing to avoid use-after-free / undefined behaviour

dmn->stateStopThread may still be running when virNetDaemonDispose is invoked (e.g. if virObjectUnref() is called while the stop thread is still in progress).
Calling g_free() on the virThread structure without first joining the thread risks:

  • the memory backing the virThread object being reclaimed while the worker is still active, causing a use-after-free in libglib’s thread implementation;
  • the daemon exiting while the stop callback is still mutating internal state, leading to data races or a torn shutdown sequence.

A minimal, safe teardown sequence is to join the thread (if it exists) and then free the wrapper:

-    g_free(dmn->stateStopThread);
+    if (dmn->stateStopThread) {
+        /* Ensure the worker has finished before reclaiming memory */
+        virThreadJoin(dmn->stateStopThread);
+        g_free(dmn->stateStopThread);
+    }

If joining unconditionally is undesirable (e.g. inside a signal path), an explicit check that the stop phase has completed before disposal would also work, but we must not free the structure while the thread is live.

🧹 Nitpick comments (8)
src/qemu/qemu_conf.h (1)

215-220: LGTM - Complete auto-shutdown configuration fields added

The six new configuration fields provide a comprehensive set of options for controlling VM behavior during system shutdown:

  • Scope controls for try-save, try-shutdown, and poweroff operations
  • Wait time configuration
  • Restoration flag for saved VMs
  • Cache bypass flag for VM state saving

These fields properly correspond to the Augeas lens entries added in libvirtd_qemu.aug.

Consider adding brief documentation comments for these new fields to describe their purpose and valid values, similar to other commented sections in this structure. This would make their intended usage clearer without requiring readers to reference other files.

+    /* Auto-shutdown configuration - controls VM lifecycle during daemon shutdown */
     virDomainDriverAutoShutdownScope autoShutdownTrySave;
     virDomainDriverAutoShutdownScope autoShutdownTryShutdown;
     virDomainDriverAutoShutdownScope autoShutdownPoweroff;
     unsigned int autoShutdownWait;
     bool autoShutdownRestore;
     bool autoSaveBypassCache;
tools/virt-admin.c (1)

1099-1112: Consider adding an explicit error message for shutdown failures

The implementation correctly follows the pattern used by other commands, but unlike other command implementations (e.g., cmdClientDisconnect at line 729), there's no specific error message when the operation fails.

Consider adding an error message to improve user experience:

-    if (virAdmConnectDaemonShutdown(priv->conn, flags) < 0)
-        return false;
+    if (virAdmConnectDaemonShutdown(priv->conn, flags) < 0) {
+        vshError(ctl, "%s", _("Failed to shutdown the daemon"));
+        return false;
+    }
tools/virsh-domain.c (1)

1160-1163: Help message could be more specific.

The help message "control next boot state" is somewhat vague about what the option actually does. Consider making it more explicit to improve user understanding.

 {.name = "once",
  .type = VSH_OT_BOOL,
- .help = N_("control next boot state")
+ .help = N_("autostart only on next boot")
 },
src/libvirt.c (1)

744-749: Minor nit – consider cross-referencing the earlier phase
To make the life-cycle narrative easier to follow, you could explicitly reference “see virStateShutdownPrepare” the same way you do for virStateShutdownWait.

src/hypervisor/domain_driver.c (2)

884-913: Busy-wait loop uses wall clock; consider monotonic clock & exponential back-off
g_timer_elapsed() uses the monotonic clock, which is fine, but the fixed 500 ms sleep can waste time when hundreds of domains are present. A simple back-off (e.g. 0.5 s → 1 s → 2 s) would reduce wake-ups without significantly delaying shutdown.


915-937: Error handling of virDomainDestroy is discarded
Ignoring the return value hides real hypervisor failures (e.g. permission errors). At least log the error message to aid post-mortem analysis.

src/rpc/virnetdaemon.c (2)

762-776: Timer periodically extends systemd deadline but never removed

virNetDaemonStopTimer() keeps extending the systemd stop deadline, but the associated timer (dmn->stopTimer) is cleared only in the success path inside virNetDaemonStopWorker.
If the shutdown ultimately times out (or fails) and we transition to VIR_NET_DAEMON_QUIT_COMPLETED without hitting the success path, the timer will remain registered until the process exits, which is a minor resource leak and can spam the journal with further sd_notify() calls.

Consider unconditionally removing the timeout once the main loop leaves the STOPPING phase:

case VIR_NET_DAEMON_QUIT_COMPLETED:
     if (dmn->stopTimer != -1) {
         virEventRemoveTimeout(dmn->stopTimer);
         dmn->stopTimer = -1;
     }
     break;

This keeps the event loop tidy and avoids unintended time-extension attempts after the outcome has already been decided.


1009-1024: Silently ignoring repeated lifecycle-callback registration hides configuration mistakes

virNetDaemonSetLifecycleCallbacks() treats the first successful call as immutable and silently ignores subsequent calls. If a second component (or a future refactor) tries to set a different callback set, the absence of an error makes the bug very hard to diagnose.

Recommend returning an explicit error (e.g. ‑EINVAL) when the callbacks have already been initialised, or at least emitting a VIR_WARN so the caller realises their request was ignored.

-    if (dmn->stopCb || dmn->shutdownPrepareCb || dmn->shutdownWaitCb)
-        return;
+    if (dmn->stopCb || dmn->shutdownPrepareCb || dmn->shutdownWaitCb) {
+        virReportError(VIR_ERR_INVALID_ARG,
+                       "%s", _("Lifecycle callbacks already set"));
+        return;
+    }

Fail-fast behaviour prevents silent mis-configuration.

📜 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)
🧰 Additional context used
🧬 Code Graph Analysis (3)
src/admin/libvirt-admin.c (1)
include/libvirt/libvirt-admin.h (2)
  • virAdmConnectDaemonShutdown (497-498)
  • conn (126-128)
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/libvirt-domain.c (2)
include/libvirt/libvirt-domain.h (2)
  • virDomainGetAutostartOnce (2432-2433)
  • virDomainSetAutostartOnce (2434-2435)
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)
🪛 Cppcheck (2.10-2)
src/rpc/virnetdaemon.c

[error] 86-86: There is an unknown macro here somewhere. Configuration is required. If ATTRIBUTE_NONNULL is a macro then please configure it.

(unknownMacro)

🔇 Additional comments (54)
src/libvirt_public.syms (1)

951-956: New autostart once feature symbols look good.

The new version block LIBVIRT_11.2.0 correctly exports the two new functions virDomainGetAutostartOnce and virDomainSetAutostartOnce for the domain autostart once functionality, inheriting from the previous version block.

src/admin/libvirt_admin_public.syms (1)

57-60: New daemon shutdown API symbol added appropriately.

The new version block LIBVIRT_ADMIN_11.2.0 correctly exports the virAdmConnectDaemonShutdown function, which implements the daemon shutdown functionality mentioned in the PR objectives.

src/admin_protocol-structs (2)

151-153: Daemon shutdown RPC argument structure looks good.

The new structure admin_connect_daemon_shutdown_args is properly defined with a flags field to control the daemon shutdown behavior.


174-174: New daemon shutdown procedure properly added to enum.

The new procedure ADMIN_PROC_CONNECT_DAEMON_SHUTDOWN is correctly added as the next sequential value (20) in the admin_procedure enum.

src/conf/domain_conf.h (1)

3331-3332: Domain object autostart once fields correctly implemented.

The autostartOnce bit flag and autostartOnceLink string pointer are correctly added to the _virDomainObj struct to support one-time domain autostart functionality. The bit flag is efficiently defined as a single bit, and the string pointer will store the path to the autostart-once symlink.

This implementation aligns with the PR objectives of adding support for one-time domain autostart, allowing domains to be configured to automatically start only on the next boot.

Also applies to: 3335-3335

docs/manpages/virt-admin.rst (1)

329-341: Well-documented daemon-shutdown command

The new daemon-shutdown command is documented clearly with proper syntax, description, and explanation of the --preserve flag's behavior.

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

1239-1245: Well-implemented autostart once status display

The implementation correctly adds "Autostart Once" status reporting to domain info output, following the same pattern as other domain attributes and properly handling error cases.

src/admin/admin_server_dispatch.c (1)

477-489: Properly implemented daemon shutdown handling

The function correctly implements controlled daemon shutdown with optional state preservation. It validates flags appropriately and follows the proper daemon lifecycle sequence by conditionally calling stop before quit.

src/admin/admin_protocol.x (2)

222-224: Well-defined argument structure for daemon shutdown

The structure correctly defines the flags parameter needed for the daemon shutdown operation.


341-346: Properly implemented RPC procedure for daemon shutdown

The procedure is correctly defined with proper annotation for stub generation and follows the protocol numbering sequence.

src/remote/remote_driver.c (1)

7675-7676: Two new function pointers added for domain autostart once feature

These additions to the hypervisor_driver structure implement the new "autostart once" feature that allows domains to automatically start only on the next boot cycle, after which the autostart flag is automatically cleared.

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

83-88: New auto-shutdown configuration settings look well-structured and positioned appropriately.

The newly added auto-shutdown configuration settings are correctly positioned after existing auto-start related settings and before the hugetlbfs configuration. The settings appear to implement a comprehensive auto-shutdown strategy with appropriate defaults:

  • auto_shutdown_try_save: Controls which domains to try managed save for (persistent domains)
  • auto_shutdown_try_shutdown: Controls which domains to attempt graceful shutdown for (all domains)
  • auto_shutdown_poweroff: Controls which domains to force power off if needed (all domains)
  • auto_shutdown_wait: Sets timeout (30 seconds) for shutdown operations
  • auto_shutdown_restore: Controls whether state is restored on next boot (enabled)
  • auto_save_bypass_cache: Controls cache bypassing during auto-save (disabled)

These settings align with the PR objectives of providing more configurable auto-shutdown scopes for VMs during system shutdown.

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

1361-1392: New daemon shutdown API function adheres to project standards and provides needed functionality.

The virAdmConnectDaemonShutdown function is well-implemented with proper error handling and adheres to the existing coding patterns. The function enables clients to trigger a graceful daemon shutdown with an optional state preservation flag.

Key observations:

  • Function follows the standard pattern: reset errors, validate connection, invoke RPC, handle errors
  • Documentation clearly explains the purpose and parameters
  • Flag parameter allows for state preservation during shutdown (VIR_DAEMON_SHUTDOWN_PRESERVE)
  • Includes appropriate API version tag (Since: 11.2.0)

This function directly supports the PR objective of adding "daemon shutdown option with state preservation."

src/libvirt_private.syms (1)

1652-1654: New private auto-shutdown symbols properly export required functionality.

The addition of these three private symbols supports the new auto-shutdown feature:

  • virDomainDriverAutoShutdown: Main function to handle VM shutdown during daemon termination
  • virDomainDriverAutoShutdownScopeTypeFromString: Conversion function for string-to-enum (needed for config parsing)
  • virDomainDriverAutoShutdownScopeTypeToString: Conversion function for enum-to-string (needed for logging/error messages)

These symbols are necessary to implement the configurable auto-shutdown scopes for VMs during system shutdown as described in the PR objectives.

src/libvirt_remote.syms (1)

97-98: Improved daemon lifecycle management API with finer-grained control.

The API changes reflect a more comprehensive approach to daemon lifecycle management:

  • Replacing virNetDaemonSetShutdownCallbacks with virNetDaemonSetLifecycleCallbacks suggests a more flexible callback system that can handle various lifecycle events beyond just shutdown.
  • Adding virNetDaemonStop provides an explicit function to initiate the daemon stop sequence, which allows for cleaner separation between stopping the daemon and quitting the main loop.

This aligns with the PR goal of "refining the daemon shutdown process with more granular state management" and is part of the multi-phase, stateful shutdown process mentioned in the PR objectives.

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

2432-2435: New autostart-once API declarations look good.

These new function declarations add a valuable feature that allows a domain to be configured to autostart only on the next host boot, rather than persistently. This complements the existing autostart API and follows the same style conventions. The parameter types and return values are consistent with the existing API pattern.

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

487-499: Well-structured enum and function declaration for daemon shutdown with preservation option.

The new enumeration virAdmConnectDaemonShutdownFlags with the VIR_DAEMON_SHUTDOWN_PRESERVE flag and the function declaration virAdmConnectDaemonShutdown are cleanly implemented. They follow the project's coding style and include proper API version documentation. This provides a clean interface for controlled daemon shutdowns with an option to preserve state.

src/rpc/gendispatch.pl (2)

842-843: Good pattern extension to support GetAutostartOnce API.

The regex pattern has been extended from GetAutostart$ to GetAutostart(Once)?$ to handle both GetAutostart and the new GetAutostartOnce procedure types in the server dispatch function generation. This is the correct approach to reuse the existing special-case handling.


1653-1654: Consistent pattern extension in client function generation.

The same regex pattern extension (GetAutostart(Once)?$) is applied here in the client function generation code, ensuring consistent handling of the special-case for both GetAutostart and GetAutostartOnce on both client and server sides.

src/conf/virdomainobjlist.c (3)

490-494: Added new autostart-once variables.

The additions of autostartOnceLink and autostartOnce variables parallel the existing pattern for handling regular autostart functionality. This sets up the foundation for implementing the one-time autostart feature.


505-508: Well-implemented autostart-once link path and detection.

The code creates the autostart-once symlink path by appending ".once" to the regular autostart link path, then checks if this link points to the domain configuration file. This is a clean approach that follows the same pattern as the existing autostart detection.


514-517: Proper state storage for autostart-once.

The domain object's autostartOnce flag is set based on the symlink check, and if enabled, the symlink path is stored in the domain object. This follows the pattern used for regular autostart and ensures the domain has all the information needed for later management of this feature.

src/driver-hypervisor.h (2)

481-487: Consistent addition of autostart-once function typedefs

The typedefs for the new autostart-once functions follow the existing pattern established by the regular autostart functionality. These additions enhance the domain lifecycle management capabilities by allowing virtual machines to be configured for a one-time autostart.


1575-1576: Well-placed struct member additions

The new function pointers are properly added to the hypervisor driver structure, maintaining consistency with the existing autostart-related members and following the established pattern for extending driver capabilities.

src/conf/domain_conf.c (2)

4173-4173: Proper resource cleanup for new autostartOnceLink

The cleanup of the newly added autostartOnceLink member follows the established pattern for resource management in this codebase. This ensures memory is properly freed during domain object disposal, preventing potential memory leaks.


29163-29163: Complete implementation of autostartOnce configuration management

The changes correctly handle the lifecycle of the autostartOnce feature:

  1. Adding a local variable for the autostartOnceLink
  2. Constructing the path by appending ".once" to the existing autostartLink
  3. Removing the symlink from the filesystem when deleting configuration
  4. Resetting the autostartOnce flag to maintain consistency

This implementation follows the same pattern used for the regular autostart feature, ensuring consistent behavior and resource management.

Also applies to: 29167-29167, 29171-29171, 29173-29173

src/qemu/libvirtd_qemu.aug (1)

106-111: Correctly adds new configuration entries

The six new configuration entries added to the save_entry group are properly defined with their appropriate types:

  • Three string entries for policy configuration (auto_shutdown_try_save, auto_shutdown_try_shutdown, auto_shutdown_poweroff)
  • One integer entry for timeout configuration (auto_shutdown_wait)
  • Two boolean entries for behavior flags (auto_shutdown_restore, auto_save_bypass_cache)

These additions follow the established pattern in the Augeas lens and align with the corresponding fields added to the QEMU driver config structure.

src/qemu/qemu_conf.h (1)

46-46: LGTM - Header inclusion required for auto-shutdown types

The inclusion of "domain_driver.h" is necessary to access the virDomainDriverAutoShutdownScope type used by the new configuration fields.

src/libvirt-domain.c (1)

7347-7388: Functions follow established patterns and error handling conventions.
The implementation of virDomainGetAutostartOnce correctly validates its arguments, resets and dispatches errors consistently, and delegates to the driver when supported. It mirrors the structure of existing helpers like virDomainGetAutostart, ensuring consistency across the API.

tools/virt-admin.c (3)

1080-1087: Good addition of the daemon-shutdown command

The new command is clearly documented with appropriate help and description texts that explain its purpose - to stop the daemon. The implementation follows the established pattern of other commands in the file.


1089-1097: Command options are well defined

The --preserve option is correctly defined as an optional boolean flag with a clear help message that explains its purpose to preserve state before shutting down the daemon.


1507-1512: Command registration looks good

The daemon-shutdown command is properly registered in the managementCmds array, which is appropriate since it's a management operation. The registration includes all necessary fields and matches the pattern of other commands.

tools/virsh-domain.c (1)

1173-1207: LGTM - Correct implementation of the autostart once feature.

The implementation correctly handles both the standard autostart behavior and the new "once" flag with appropriate API calls and error messages. The code structure is clean with proper error handling and user feedback.

src/remote_protocol-structs (2)

3309-3318: Properly implemented domain autostart-once feature structures.

The three new struct definitions follow the correct pattern for remote procedure call arguments and return values:

  • remote_domain_get_autostart_once_args holds a domain reference
  • remote_domain_get_autostart_once_ret returns the autostart flag
  • remote_domain_set_autostart_once_args contains both domain and autostart flag

These are consistent with similar structures like the regular autostart functionality.


3768-3769: Correctly defined remote procedure identifiers for the new feature.

The two new procedure identifiers for domain autostart-once operations:

  • REMOTE_PROC_DOMAIN_GET_AUTOSTART_ONCE = 449
  • REMOTE_PROC_DOMAIN_SET_AUTOSTART_ONCE = 450

These are properly added at the end of the enum to maintain backward compatibility, following the protocol's extension pattern.

src/remote/remote_protocol.x (2)

3977-3988: New data structures look correct for autostart-once functionality

These data structures follow the established pattern for domain-related RPC parameters. The implementation correctly includes both argument and return structures for getting/setting the autostart-once state.


7067-7079: Remote procedures correctly implement autostart-once feature

The new RPC procedures for domain autostart-once functionality have appropriate:

  • Procedure IDs (449, 450) incrementing from the last used ID (448)
  • Access control annotations for security (domain:read for get, domain:write for set)
  • High priority markers for efficient handling
  • Consistent naming matching the existing style

This implementation matches established patterns in the codebase for similar features.

src/qemu/qemu_driver.c (3)

7799-7891: Comprehensive implementation of autostart-once functionality

The implementation of qemuDomainGetAutostartOnce and qemuDomainSetAutostartOnce is thorough and follows established code patterns. The functions correctly:

  1. Perform ACL checks
  2. Handle transient domain errors
  3. Manage domain modification jobs to prevent race conditions
  4. Create or remove .once symlinks in the autostart directory
  5. Update the domain object state
  6. Implement proper error handling and cleanup

The implementation properly handles file permission errors and symlink operation failures, ensuring reliable operation.


20286-20287: LGTM: Functions properly registered with API version

The new functions are correctly registered in the hypervisor driver structure with version 11.2.0, following the standard versioning practices for new API capabilities.


963-980:

Details

✅ Verification successful

Well-designed simplification of shutdown logic

The refactoring of qemuStateStop simplifies the function by delegating domain shutdown handling to the new virDomainDriverAutoShutdown function. This improves code organization and leverages the centralized shutdown mechanism.

Note that the function now always returns 0 regardless of what happens in virDomainDriverAutoShutdown. Confirm that this is intentional and that virDomainDriverAutoShutdown properly handles errors internally rather than requiring error propagation.


🏁 Script executed:

#!/bin/bash
# Check if virDomainDriverAutoShutdown returns errors that should be propagated
rg "virDomainDriverAutoShutdown" src/hypervisor/domain_driver.c -A 5 -B 5

Length of output: 1282


qemuStateStop intentionally returns success

qemuStateStop now delegates all shutdown work to virDomainDriverAutoShutdown, which is declared as void and performs its own error logging and handling internally. Since there is no return value to propagate, always returning 0 here is the correct and intended behavior.

src/rpc/virnetdaemon.h (2)

73-73: New function added for daemon control.

The virNetDaemonStop function extends the daemon API to better support controlled shutdown and clean state preservation.


83-110: Well-designed lifecycle callback architecture.

This introduces a more granular and structured approach to daemon lifecycle management with a three-phase shutdown process:

  1. stopCb - preserves active state
  2. prepareCb - initiates shutdown
  3. waitCb - waits for completion

The comprehensive documentation clearly explains the execution sequence and purpose of each callback, which will help maintainers understand the shutdown flow.

The implementation follows good design principles by:

  • Making callbacks immutable once set
  • Providing a clear sequence of operations
  • Supporting different daemon states (privileged vs. unprivileged)
  • Properly documenting the expected behavior
src/hypervisor/domain_driver.h (2)

95-104: Well-structured enum for shutdown scopes.

The new enum provides clear categorization for automatic shutdown behaviors. Using VIR_ENUM_DECL ensures proper integration with the existing enum system.


106-119: Comprehensive configuration structure for automatic domain shutdown.

This configuration structure provides a complete set of parameters to control automatic shutdown behavior:

  • URI for identification
  • Separate scopes for different actions (save, shutdown, poweroff)
  • Configurable timeout
  • Flags for cache and restoration behavior

The design enables fine-grained control over how domains behave during system shutdown.

src/qemu/qemu_conf.c (2)

317-332: Sensible default auto-shutdown configuration based on privilege level.

The defaults are properly differentiated by privilege level:

  • Privileged (system) daemons default to "none" to defer to libvirt-guests.service
  • Unprivileged (session) daemons use more aggressive defaults to ensure VMs aren't left running

This aligns with user expectations in different contexts.


678-774: Robust configuration parsing with validation.

The implementation properly validates auto-shutdown scope combinations and prevents invalid configurations:

  • Manages save operation isn't allowed for transient domains (lines 732-737)
  • Each scope string is properly validated against the enum
  • Configuration loading is consistent with the rest of the file

Good error reporting is provided with clear messages when invalid configurations are detected.

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

667-674: Clear documentation for auto-shutdown scope options.

The configuration file properly explains all possible values for the auto-shutdown scopes, making it easy for administrators to understand the options.


675-687: Well-documented auto-shutdown managed save configuration.

The documentation clearly explains:

  • The purpose of the setting
  • Default values for different daemon types
  • Important restrictions (can't be used for transient VMs)
  • Interaction with libvirt-guests.service

This provides administrators with all necessary information for proper configuration.


688-698: Well-documented auto-shutdown graceful shutdown configuration.

The documentation clearly explains the purpose, defaults, and interaction with libvirt-guests.service, maintaining consistency with the previous setting's documentation style.


699-709: Well-documented auto-shutdown forced poweroff configuration.

The documentation maintains the same clear format as previous settings, providing a complete explanation of this last-resort shutdown option.


710-727: Well-documented auto-shutdown auxiliary options.

The documentation for wait time, restore behavior, and cache bypass options is clear and consistent with the main shutdown options. The explicit mention of default values (30 seconds for wait time) is particularly helpful.

src/libvirt.c (1)

688-698: Documentation clarification looks good
The new commentary clearly explains the threading model and when the event loop is blocked/un-blocked. This extra precision will be invaluable for driver writers and future maintainers.

src/hypervisor/domain_driver.c (1)

39-44: Enum should be frozen for external ABI users
If this enum is (or may later become) part of any public header / RPC payload, consider assigning explicit values and adding a _MAX sentinel to avoid accidental re-ordering problems:

-    "none",
-    "persistent",
-    "transient",
-    "all");
+    [VIR_DOMAIN_DRIVER_AUTO_SHUTDOWN_SCOPE_NONE] = "none",
+    [VIR_DOMAIN_DRIVER_AUTO_SHUTDOWN_SCOPE_PERSISTENT] = "persistent",
+    [VIR_DOMAIN_DRIVER_AUTO_SHUTDOWN_SCOPE_TRANSIENT] = "transient",
+    [VIR_DOMAIN_DRIVER_AUTO_SHUTDOWN_SCOPE_ALL] = "all");

Do any protocol files already rely on the numeric order?

src/remote/remote_daemon.c (1)

529-533: Double-stop / missing quit on host shutdown
For session logout you now call both virNetDaemonStop and virNetDaemonQuit, but for host PrepareForShutdown you only invoke Stop. If no further code triggers Quit, the event loop may linger until SIGTERM. Is that intentional? Consider mirroring the two handlers for consistency or documenting the distinction.

Comment thread src/libvirt-domain.c
Comment on lines +7391 to +7432
/**
* 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.2.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 boolean argument to prevent invalid values.
virDomainSetAutostartOnce currently accepts any integer for autostart, but this flag is intended to be boolean (0 or 1). Without validation, drivers may receive unexpected values.

Apply this diff to enforce proper boolean semantics:

diff --git a/src/libvirt-domain.c b/src/libvirt-domain.c
index abcdef..123456 100644
--- a/src/libvirt-domain.c
+++ b/src/libvirt-domain.c
@@ -7411,6 +7411,13 @@ int virDomainSetAutostartOnce(virDomainPtr domain,
     virResetLastError();
 
     virCheckDomainReturn(domain, -1);
+    /* Ensure autostart flag is strictly 0 or 1 */
+    if (autostart != 0 && autostart != 1) {
+        virReportError(VIR_ERR_ARGUMENT, "%s",
+                       "autostartOnce value must be 0 or 1");
+        goto error;
+    }
 
     conn = domain->conn;
 
     virCheckReadOnlyGoto(conn->flags, error);

This check will catch invalid inputs early and maintain a clear contract with driver implementations.

Comment on lines +743 to +749
VIR_DEBUG("Run autoshutdown uri=%s trySave=%s tryShutdown=%s poweroff=%s waitShutdownSecs=%u saveBypassCache=%d autoRestore=%d",
cfg->uri,
virDomainDriverAutoShutdownScopeTypeToString(cfg->trySave),
virDomainDriverAutoShutdownScopeTypeToString(cfg->tryShutdown),
virDomainDriverAutoShutdownScopeTypeToString(cfg->poweroff),
cfg->waitShutdownSecs, cfg->saveBypassCache, cfg->autoRestore);

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

Memory leak of transient helper array
transient is allocated with g_new0 but never freed. Mark it g_autofree (as you did for flags) or VIR_FREE(transient) in the cleanup: section.

Comment on lines +814 to +860
if (cfg->trySave != VIR_DOMAIN_DRIVER_AUTO_SHUTDOWN_SCOPE_NONE) {
g_autofree unsigned int *flags = g_new0(unsigned int, numDomains);
for (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;

virSystemdNotifyStatus("Suspending '%s' (%zu of %d)",
virDomainGetName(domains[i]), i + 1, numDomains);
VIR_INFO("Suspending '%s'", virDomainGetName(domains[i]));

/*
* Pause all VMs to make them stop dirtying pages,
* so save is quicker. We remember if any VMs were
* paused so we can restore that on resume.
*/
flags[i] = VIR_DOMAIN_SAVE_RUNNING;
if (virDomainGetState(domains[i], &state, NULL, 0) == 0) {
if (state == VIR_DOMAIN_PAUSED)
flags[i] = VIR_DOMAIN_SAVE_PAUSED;
}
if (cfg->saveBypassCache)
flags[i] |= VIR_DOMAIN_SAVE_BYPASS_CACHE;

if (flags[i] & VIR_DOMAIN_SAVE_RUNNING)
virDomainSuspend(domains[i]);
}

for (i = 0; i < numDomains; i++) {
virSystemdNotifyStatus("Saving '%s' (%zu of %d)",
virDomainGetName(domains[i]), i + 1, numDomains);
VIR_INFO("Saving '%s'", virDomainGetName(domains[i]));

if (virDomainManagedSave(domains[i], flags[i]) < 0) {
VIR_WARN("auto-shutdown: unable to perform managed save of '%s': %s",
domains[i]->name,
virGetLastErrorMessage());
if (flags[i] & VIR_DOMAIN_SAVE_RUNNING)
virDomainResume(domains[i]);
continue;
}
virObjectUnref(domains[i]);
domains[i] = 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.

⚠️ Potential issue

Managed-save loop ignores scope filter, may attempt to save transient VMs
In the first pass you correctly continue; for domains outside the chosen scope, but the second pass iterates over all domains again and unconditionally calls virDomainManagedSave(). This will try to save transient guests (and guests that were already skipped), violating the limitation you logged earlier.

-        for (i = 0; i < numDomains; i++) {
+        for (i = 0; i < numDomains; i++) {
+            if (domains[i] == NULL)
+                continue;   /* already handled / not in scope */
+
+            if ((transient[i] && cfg->trySave == VIR_DOMAIN_DRIVER_AUTO_SHUTDOWN_SCOPE_PERSISTENT) ||
+                (!transient[i] && cfg->trySave == VIR_DOMAIN_DRIVER_AUTO_SHUTDOWN_SCOPE_TRANSIENT))
+                continue;

Same conditional should be added to the later shutdown / power-off loops for consistency.

📝 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
if (cfg->trySave != VIR_DOMAIN_DRIVER_AUTO_SHUTDOWN_SCOPE_NONE) {
g_autofree unsigned int *flags = g_new0(unsigned int, numDomains);
for (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;
virSystemdNotifyStatus("Suspending '%s' (%zu of %d)",
virDomainGetName(domains[i]), i + 1, numDomains);
VIR_INFO("Suspending '%s'", virDomainGetName(domains[i]));
/*
* Pause all VMs to make them stop dirtying pages,
* so save is quicker. We remember if any VMs were
* paused so we can restore that on resume.
*/
flags[i] = VIR_DOMAIN_SAVE_RUNNING;
if (virDomainGetState(domains[i], &state, NULL, 0) == 0) {
if (state == VIR_DOMAIN_PAUSED)
flags[i] = VIR_DOMAIN_SAVE_PAUSED;
}
if (cfg->saveBypassCache)
flags[i] |= VIR_DOMAIN_SAVE_BYPASS_CACHE;
if (flags[i] & VIR_DOMAIN_SAVE_RUNNING)
virDomainSuspend(domains[i]);
}
for (i = 0; i < numDomains; i++) {
virSystemdNotifyStatus("Saving '%s' (%zu of %d)",
virDomainGetName(domains[i]), i + 1, numDomains);
VIR_INFO("Saving '%s'", virDomainGetName(domains[i]));
if (virDomainManagedSave(domains[i], flags[i]) < 0) {
VIR_WARN("auto-shutdown: unable to perform managed save of '%s': %s",
domains[i]->name,
virGetLastErrorMessage());
if (flags[i] & VIR_DOMAIN_SAVE_RUNNING)
virDomainResume(domains[i]);
continue;
}
virObjectUnref(domains[i]);
domains[i] = NULL;
}
}
if (cfg->trySave != VIR_DOMAIN_DRIVER_AUTO_SHUTDOWN_SCOPE_NONE) {
g_autofree unsigned int *flags = g_new0(unsigned int, numDomains);
for (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;
virSystemdNotifyStatus("Suspending '%s' (%zu of %d)",
virDomainGetName(domains[i]), i + 1, numDomains);
VIR_INFO("Suspending '%s'", virDomainGetName(domains[i]));
/*
* Pause all VMs to make them stop dirtying pages,
* so save is quicker. We remember if any VMs were
* paused so we can restore that on resume.
*/
flags[i] = VIR_DOMAIN_SAVE_RUNNING;
if (virDomainGetState(domains[i], &state, NULL, 0) == 0) {
if (state == VIR_DOMAIN_PAUSED)
flags[i] = VIR_DOMAIN_SAVE_PAUSED;
}
if (cfg->saveBypassCache)
flags[i] |= VIR_DOMAIN_SAVE_BYPASS_CACHE;
if (flags[i] & VIR_DOMAIN_SAVE_RUNNING)
virDomainSuspend(domains[i]);
}
for (i = 0; i < numDomains; i++) {
if (domains[i] == NULL)
continue; /* already handled / not in scope */
if ((transient[i] && cfg->trySave == VIR_DOMAIN_DRIVER_AUTO_SHUTDOWN_SCOPE_PERSISTENT) ||
(!transient[i] && cfg->trySave == VIR_DOMAIN_DRIVER_AUTO_SHUTDOWN_SCOPE_TRANSIENT))
continue;
virSystemdNotifyStatus("Saving '%s' (%zu of %d)",
virDomainGetName(domains[i]), i + 1, numDomains);
VIR_INFO("Saving '%s'", virDomainGetName(domains[i]));
if (virDomainManagedSave(domains[i], flags[i]) < 0) {
VIR_WARN("auto-shutdown: unable to perform managed save of '%s': %s",
domains[i]->name,
virGetLastErrorMessage());
if (flags[i] & VIR_DOMAIN_SAVE_RUNNING)
virDomainResume(domains[i]);
continue;
}
virObjectUnref(domains[i]);
domains[i] = NULL;
}
}

Comment thread src/rpc/virnetdaemon.c
Comment on lines +919 to +927
dmn->stopCb();

VIR_DEBUG("Completed stop dmn=%p", dmn);

VIR_WITH_OBJECT_LOCK_GUARD(dmn) {
if (dmn->quit == VIR_NET_DAEMON_QUIT_STOPPING) {
VIR_DEBUG("Marking shutdown as ready");
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

Propagate or at least log stopCb failures

dmn->stopCb() can fail (its prototype matches virStateStop, which returns int).
At present the return value is discarded, so callers cannot distinguish a clean stop from a failure, and the state machine proceeds as if everything is fine.

At minimum, capture and log the return code; ideally, surface the error up the state machine so that we can abort the graceful shutdown path and fall back to a forced exit:

-    dmn->stopCb();
+    int rc = dmn->stopCb();
+    if (rc < 0)
+        VIR_WARN("State stop callback failed: %d", rc);

This makes troubleshooting easier and preserves the semantics of existing driver callbacks.

📝 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
dmn->stopCb();
VIR_DEBUG("Completed stop dmn=%p", dmn);
VIR_WITH_OBJECT_LOCK_GUARD(dmn) {
if (dmn->quit == VIR_NET_DAEMON_QUIT_STOPPING) {
VIR_DEBUG("Marking shutdown as ready");
dmn->quit = VIR_NET_DAEMON_QUIT_READY;
}
int rc = dmn->stopCb();
if (rc < 0)
VIR_WARN("State stop callback failed: %d", rc);
VIR_DEBUG("Completed stop dmn=%p", dmn);
VIR_WITH_OBJECT_LOCK_GUARD(dmn) {
if (dmn->quit == VIR_NET_DAEMON_QUIT_STOPPING) {
VIR_DEBUG("Marking shutdown as ready");
dmn->quit = VIR_NET_DAEMON_QUIT_READY;
}

@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.

1 participant