Repository navigation
Autoshutdown - #10
Autoshutdown#10berrange wants to merge 22 commits into
Conversation
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]>
Reviewer's Guide by SourceryThis pull request introduces several major features:
No diagrams generated as the changes look simple and do not need a visual representation. File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
WalkthroughThis 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 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
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
Possibly related PRs
Poem
✨ Finishing Touches
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
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
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
| } | ||
|
|
||
|
|
||
| void |
There was a problem hiding this comment.
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:
- Identify distinct operations (auto-restore, managed save, shutdown, poweroff).
- Create helper functions for each operation.
- Replace the nested loops and conditionals with calls to these helpers.
- 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.
There was a problem hiding this comment.
Actionable comments posted: 4
🔭 Outside diff range comments (2)
src/hypervisor/domain_driver.c (1)
687-708: 🛠️ Refactor suggestionAutostart-once flag cleared even on failed start
vm->autostartOnceis reset (and the link unlinked) immediately after invokingcallback, 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 issueJoin the
stateStopThreadbefore freeing to avoid use-after-free / undefined behaviour
dmn->stateStopThreadmay still be running whenvirNetDaemonDisposeis invoked (e.g. ifvirObjectUnref()is called while the stop thread is still in progress).
Callingg_free()on thevirThreadstructure without first joining the thread risks:
- the memory backing the
virThreadobject 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 addedThe 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 failuresThe implementation correctly follows the pattern used by other commands, but unlike other command implementations (e.g.,
cmdClientDisconnectat 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 ofvirDomainDestroyis 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 insidevirNetDaemonStopWorker.
If the shutdown ultimately times out (or fails) and we transition toVIR_NET_DAEMON_QUIT_COMPLETEDwithout 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 furthersd_notify()calls.Consider unconditionally removing the timeout once the main loop leaves the
STOPPINGphase: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_WARNso 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
📒 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.0correctly exports the two new functionsvirDomainGetAutostartOnceandvirDomainSetAutostartOncefor 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.0correctly exports thevirAdmConnectDaemonShutdownfunction, 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_argsis 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_SHUTDOWNis correctly added as the next sequential value (20) in theadmin_procedureenum.src/conf/domain_conf.h (1)
3331-3332: Domain object autostart once fields correctly implemented.The
autostartOncebit flag andautostartOnceLinkstring pointer are correctly added to the_virDomainObjstruct 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 commandThe new daemon-shutdown command is documented clearly with proper syntax, description, and explanation of the
--preserveflag's behavior.tools/virsh-domain-monitor.c (1)
1239-1245: Well-implemented autostart once status displayThe 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 handlingThe 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 shutdownThe structure correctly defines the flags parameter needed for the daemon shutdown operation.
341-346: Properly implemented RPC procedure for daemon shutdownThe 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 featureThese 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 operationsauto_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
virAdmConnectDaemonShutdownfunction 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 terminationvirDomainDriverAutoShutdownScopeTypeFromString: 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
virNetDaemonSetShutdownCallbackswithvirNetDaemonSetLifecycleCallbackssuggests a more flexible callback system that can handle various lifecycle events beyond just shutdown.- Adding
virNetDaemonStopprovides 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
virAdmConnectDaemonShutdownFlagswith theVIR_DAEMON_SHUTDOWN_PRESERVEflag and the function declarationvirAdmConnectDaemonShutdownare 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$toGetAutostart(Once)?$to handle bothGetAutostartand the newGetAutostartOnceprocedure 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 bothGetAutostartandGetAutostartOnceon both client and server sides.src/conf/virdomainobjlist.c (3)
490-494: Added new autostart-once variables.The additions of
autostartOnceLinkandautostartOncevariables 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
autostartOnceflag 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 typedefsThe 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 additionsThe 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 autostartOnceLinkThe cleanup of the newly added
autostartOnceLinkmember 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 managementThe changes correctly handle the lifecycle of the autostartOnce feature:
- Adding a local variable for the autostartOnceLink
- Constructing the path by appending ".once" to the existing autostartLink
- Removing the symlink from the filesystem when deleting configuration
- 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 entriesThe six new configuration entries added to the
save_entrygroup 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 typesThe inclusion of "domain_driver.h" is necessary to access the
virDomainDriverAutoShutdownScopetype used by the new configuration fields.src/libvirt-domain.c (1)
7347-7388: Functions follow established patterns and error handling conventions.
The implementation ofvirDomainGetAutostartOncecorrectly validates its arguments, resets and dispatches errors consistently, and delegates to the driver when supported. It mirrors the structure of existing helpers likevirDomainGetAutostart, ensuring consistency across the API.tools/virt-admin.c (3)
1080-1087: Good addition of the daemon-shutdown commandThe 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 definedThe
--preserveoption 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 goodThe 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_argsholds a domain referenceremote_domain_get_autostart_once_retreturns the autostart flagremote_domain_set_autostart_once_argscontains both domain and autostart flagThese 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 = 449REMOTE_PROC_DOMAIN_SET_AUTOSTART_ONCE = 450These 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 functionalityThese 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 featureThe 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:readfor get,domain:writefor 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 functionalityThe implementation of
qemuDomainGetAutostartOnceandqemuDomainSetAutostartOnceis thorough and follows established code patterns. The functions correctly:
- Perform ACL checks
- Handle transient domain errors
- Manage domain modification jobs to prevent race conditions
- Create or remove
.oncesymlinks in the autostart directory- Update the domain object state
- 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 versionThe 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
qemuStateStopsimplifies the function by delegating domain shutdown handling to the newvirDomainDriverAutoShutdownfunction. 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 thatvirDomainDriverAutoShutdownproperly 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 5Length of output: 1282
qemuStateStop intentionally returns success
qemuStateStopnow delegates all shutdown work tovirDomainDriverAutoShutdown, which is declared asvoidand performs its own error logging and handling internally. Since there is no return value to propagate, always returning0here is the correct and intended behavior.src/rpc/virnetdaemon.h (2)
73-73: New function added for daemon control.The
virNetDaemonStopfunction 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:
stopCb- preserves active stateprepareCb- initiates shutdownwaitCb- waits for completionThe 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_DECLensures 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 bothvirNetDaemonStopandvirNetDaemonQuit, but for hostPrepareForShutdownyou only invokeStop. If no further code triggersQuit, the event loop may linger until SIGTERM. Is that intentional? Consider mirroring the two handlers for consistency or documenting the distinction.
| /** | ||
| * 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; | ||
| } | ||
|
|
There was a problem hiding this comment.
🛠️ 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.
| 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); | ||
|
|
There was a problem hiding this comment.
🛠️ 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.
| 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; | ||
| } | ||
| } |
There was a problem hiding this comment.
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.
| 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; | |
| } | |
| } |
| 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; | ||
| } |
There was a problem hiding this comment.
🛠️ 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.
| 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; | |
| } |
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]>
Summary by Sourcery
Implement advanced domain autostart and daemon shutdown features, enhancing system shutdown and VM lifecycle management
New Features:
Enhancements:
Chores:
Summary by CodeRabbit
New Features
daemon-shutdowncommand in virt-admin, allowing graceful daemon shutdown with an optional state preservation flag.Improvements
Documentation