public inbox for pve-devel@lists.proxmox.com
 help / color / mirror / Atom feed
From: "Jakob Klocker" <j.klocker@proxmox.com>
To: "Fiona Ebner" <f.ebner@proxmox.com>, <pve-devel@lists.proxmox.com>
Subject: Re: [PATCH qemu-server v6 3/3] fix #5032: agent: sync guest time via QGA when the clock falls behind
Date: Mon, 16 Nov 2026 13:21:41 +0100	[thread overview]
Message-ID: <DMWMQKNA9U3Q.9GSB3CN09NUY@proxmox.com> (raw)
In-Reply-To: <c9171730-2f6b-4f96-ab75-5e033a99771c@proxmox.com>

Thanks for the feedback!
On Fri Nov 13, 2026 at 3:10 PM CET, Fiona Ebner wrote:
> Needs a rebase
ack

>
> Am 10.11.26 um 11:49 AM schrieb Jakob Klocker:
>> diff --git a/src/PVE/API2/Qemu.pm b/src/PVE/API2/Qemu.pm
>> index 7830d09b..df2076a6 100644
>> --- a/src/PVE/API2/Qemu.pm
>> +++ b/src/PVE/API2/Qemu.pm
>> @@ -3599,6 +3599,24 @@ __PACKAGE__->register_method({
>>                  description => 'Whether to migrate conntrack entries for running VMs.',
>>              },
>>              'nets-host-mtu' => get_standard_option('pve-qm-nets-host-mtu'),
>> +            'sync-time-on-resume' => {
>> +                type => 'boolean',
>> +                description =>
>> +                    "Override the 'sync-time-on-resume' setting from the VM's guest agent (QGA)"
>> +                    . " config for this start only. Controls whether the guest's clock is"
>
> Should explicitly state that this is for migration and hibernate and not
> regular start.

Agreed about mentioning hibernate here; I'll make that explicit in v7.
It is not used for migration though, see below.

>
>> +                    . " synchronized after the RAM state is restored. The guest agent must be"
>> +                    . " enabled.",
>
> Nit: For this and all others: maybe we should drop the last sentence for
> the short description? It already is mentioned that it's about the guest
> agent setting. But fine either way.
>

ack, will remove 

>> +                verbose_description =>
>> +                    "Override the 'sync-time-on-resume' setting from the VM's guest agent (QGA)"
>> +                    . " config for this start only. When enabled, the 'guest-set-time' QEMU guest"
>> +                    . " agent command is issued to synchronize the guest's clock to the host's current"
>> +                    . " time after the RAM state is restored, which happens here when starting a VM"
>> +                    . " that was hibernated (suspended to disk). Without synchronization the guest's"
>> +                    . " clock may still reflect the time from when the VM was hibernated. The time is"
>
> It's also for migration, or?
>

No. The migration target is started through this endpoint, but the RAM
only arrives after vm_start returns AFAICT, so at that point the guest
is not running yet and the agent can't respond. That's why the sync in
vm_start_nolock is skipped when 'migratedfrom' is set. 

For migration, the clock is synced in vm_resume on the target, when 
the source sends the 'resume' command through the migration tunnel 
after the switchover. That always uses the value from the agent config.

>> +                    . " only synchronized when the QEMU Guest Agent option is enabled in the guest's"
>> +                    . " configuration and the agent is running inside of the guest.",
>> +                optional => 1,
>> +            },
>>          },
>>      },
>>      returns => {
>
> ---snip 8<---
>
>> diff --git a/src/PVE/QemuMigrate.pm b/src/PVE/QemuMigrate.pm
>> index 8176afe5..e24544a7 100644
>> --- a/src/PVE/QemuMigrate.pm
>> +++ b/src/PVE/QemuMigrate.pm
>> @@ -1778,6 +1778,9 @@ sub phase3_cleanup {
>>                      $self->{errors} = 1;
>>                  }
>>              }
>> +            $self->log('info', "guest clock sync requested, will run on target after resume")
>> +                if !$self->{errors}
>> +                && PVE::QemuServer::Agent::should_sync_time_on_resume($conf->{agent});
>
> Style nit: multiline post-if

ack

>
>>          }
>>  
>>          if (
>> diff --git a/src/PVE/QemuServer.pm b/src/PVE/QemuServer.pm
>> index 8149184e..55733ee1 100644
>> --- a/src/PVE/QemuServer.pm
>> +++ b/src/PVE/QemuServer.pm
>> @@ -5047,7 +5047,10 @@ sub vmconfig_update_agent {
>>  
>>      die "skip\n" if !$conf->{$opt};
>>  
>> -    my $hotplug_options = { fstrim_cloned_disks => 1 };
>> +    my $hotplug_options = {
>> +        fstrim_cloned_disks => 1,
>> +        'sync-time-on-resume' => 1,
>> +    };
>>  
>>      my $old_agent = parse_guest_agent($conf->{agent});
>>      my $agent = parse_guest_agent($value);
>> @@ -5910,6 +5913,19 @@ sub vm_start_nolock {
>>          );
>>      }
>>  
>> +    # $resume = suspend-to-disk, $statefile = rollback with RAM. Rollback carries the snapshot's
>> +    # agent setting in params; hibernate resume falls back to the live config
>> +    if ($resume || ($statefile && !$migratedfrom)) {
>> +        my $agent = $params->{agent} // $conf->{agent};
>> +        if (PVE::QemuServer::Agent::should_sync_time_on_resume(
>> +            $agent,
>> +            $params->{'sync-time-on-resume'},
>> +        )) {
>> +            eval { PVE::QemuServer::Agent::guest_set_time($vmid); 1 };
>
> Did you intend to pass 1 as an argument?
>

No, this shouldn't be `quiet`. I'm not sure how this sneaked in. Will
be removed in v7.

>
>> +            warn "could not sync guest time after resume from saved state - $@" if $@;
>> +        }
>> +    }
>> +
>>      return $res;
>>  }
>>  
>> diff --git a/src/PVE/QemuServer/Agent.pm b/src/PVE/QemuServer/Agent.pm
>> index be6df443..5aaf76b2 100644
>> --- a/src/PVE/QemuServer/Agent.pm
>> +++ b/src/PVE/QemuServer/Agent.pm
>> @@ -4,6 +4,8 @@ use v5.36;
>>  
>>  use JSON;
>>  use MIME::Base64 qw(decode_base64 encode_base64);
>> +use Time::HiRes qw(time);
>> +use POSIX qw(strftime);
>>  
>>  use PVE::JSONSchema;
>>  
>> @@ -52,6 +54,25 @@ our $agent_fmt = {
>>          optional => 1,
>>          default => 1,
>>      },
>> +    # FIXME: MAJOR VERSION: 10.0.0 - reconsider setting option on as default
>> +    'sync-time-on-resume' => {
>> +        description =>
>> +            "Synchronize the guest's clock through QGA after operations that can leave"
>> +            . " the guest's clock behind.",
>> +        verbose_description =>
>> +            "Whether to issue the 'guest-set-time' QEMU guest agent command to synchronize the"
>> +            . " guest's clock to the host's current time after operations that can leave the guest's"
>> +            . " clock behind. This happens when resuming from hibernation, resuming from a paused"
>> +            . " state, taking a snapshot, after a migration, after a backup in suspend mode, and"
>> +            . " after rolling back to a snapshot that includes RAM. In these cases the guest's"
>> +            . " clock may still reflect an earlier time. The time is only synchronized when the"
>> +            . " QEMU Guest Agent option is enabled in the guest's configuration and the agent is"
>> +            . " running inside of the guest. For resume, hibernation resume and snapshot rollback,"
>> +            . " the synchronization can be overridden per operation.",
>> +        type => 'boolean',
>> +        optional => 1,
>> +        default => 0,
>> +    },
>>      type => {
>>          description => "Select the agent type",
>>          type => 'string',
>> @@ -332,4 +353,47 @@ sub guest_fs_freeze_applicable($agent_str, $vmid, $logfunc = undef) {
>>      return 1;
>>  }
>>  
>> +=head3 should_sync_time_on_resume
>> +
>> +Returns whether the guest's clock should be synchronized to the host's via the QEMU Guest Agent
>> +when the VM is resumed from saved state. Requires the guest agent to be enabled. An explicit
>
> This function can deal just fine with the situation where the agent is
> not enabled. Maybe state: "Returns 0 if the agent is not enabled.".
>

Agreed, will change in v7

>> +C<$override> (from an API parameter) takes precedence over the C<sync-time-on-resume> agent
>> +config property when defined; otherwise the config value is used (defaulting to off). Does B<not>
>> +check whether the agent is actually running.
>> +
>> +=cut
>> +
>> +sub should_sync_time_on_resume($agent_str, $override = undef) {
>> +    my $agent = parse_guest_agent($agent_str);
>> +    return 0 if !$agent->{enabled};
>> +    return $override ? 1 : 0 if defined($override);
>> +    return $agent->{'sync-time-on-resume'} // 0;
>> +}
>> +
>> +=head3 guest_set_time
>> +
>> +Sets the guest's clock to the current host time via the QEMU Guest Agent's
>> +C<guest-set-time> command. The host time is passed explicitly (as nanoseconds
>> +since the UNIX epoch) because the argument-less form reads the time from the
>> +guest's RTC, which isn't supported on all platforms (e.g. Windows); passing
>> +the value directly works regardless of guest OS.
>> +
>> +Returns 1 if the time was set, 0 if it was skipped because the agent is not running.
>> +Dies if the agent returns an error.
>
> Style nit: above used a length limit of 100 for wrapping, the first
> paragraph here 80, the second paragraph seems to be something in between.
>

ack

>> +
>> +=cut
>> +
>> +sub guest_set_time($vmid, $quiet = undef) {
>> +    if (!qga_check_running($vmid, 1)) {
>> +        print "skipping guest set time - agent configured but not running?\n" if !$quiet;
>> +        return 0;
>> +    }
>> +    my $time_ns = time() * 1_000_000_000;
>> +    my $res = PVE::QemuServer::Monitor::mon_cmd($vmid, 'guest-set-time', time => int($time_ns));
>> +    check_agent_error($res, "unable to set guest time");
>> +    my $time_str = strftime("%F %T", localtime($time_ns / 1_000_000_000));
>> +    print "synced guest clock via guest agent to $time_str\n" if !$quiet;
>> +    return 1;
>> +}
>> +
>>  1;
>> diff --git a/src/PVE/QemuServer/RunState.pm b/src/PVE/QemuServer/RunState.pm
>> index 889ddd28..2588dabb 100644
>> --- a/src/PVE/QemuServer/RunState.pm
>> +++ b/src/PVE/QemuServer/RunState.pm
>> @@ -131,7 +131,7 @@ sub vm_suspend($vmid, $skiplock = undef, $includestate = undef, $statestorage =
>>  # $nocheck is set when called as part of a migration - in this context the
>>  # location of the config file (source or target node) is not deterministic,
>>  # since migration cannot wait for pmxcfs to process the rename
>> -sub vm_resume($vmid, $skiplock = undef, $nocheck = undef) {
>> +sub vm_resume($vmid, $skiplock = undef, $nocheck = undef, $sync_time = undef, $quiet = undef) {
>>  
>>      PVE::QemuConfig->lock_config(
>>          $vmid,
>> @@ -183,6 +183,19 @@ sub vm_resume($vmid, $skiplock = undef, $nocheck = undef) {
>>                  if $resume_cmd eq 'cont';
>>  
>>              mon_cmd($vmid, $resume_cmd);
>> +
>> +            # A VM in 'prelaunch' never ran, and a VM that shut down during a backup is reset
>> +            # above. Both boot fresh, so the clock is not behind and the agent is not up yet.
>> +            my $guest_was_running = !$reset && ($res->{status} // '') ne 'prelaunch';
>
> Nit: could also skip 'shutdown' state for completeness.
>

That's already covered: $reset is only set for the `shutdown` state,
and $guest_was_running checks !$reset. I'll check the status directly
in v7, so this is more obvious. Something along the lines:

my $status = $res->{status} // '';
my $guest_was_running = $status ne 'prelaunch' && $status ne 'shutdown';

>> +            if (
>> +                $resume_cmd eq 'cont'
>> +                && $guest_was_running
>> +                && PVE::QemuServer::Agent::should_sync_time_on_resume($conf->{agent},
>> +                    $sync_time)
>> +            ) {
>> +                eval { PVE::QemuServer::Agent::guest_set_time($vmid, $quiet); };
>> +                warn "could not sync guest time after resume - $@" if $@;
>> +            }
>>          },
>>      );
>>  }





  reply	other threads:[~2026-11-16 12:21 UTC|newest]

Thread overview: 10+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-11-10 10:45 [PATCH guest-common/manager/qemu-server v6 0/3] fix #5032: add guest time sync via QGA Jakob Klocker
2026-11-10 10:45 ` [PATCH pve-guest-common v6 1/3] AbstractConfig: allow passing options to snapshot_rollback Jakob Klocker
2026-11-13 14:10   ` Fiona Ebner
2026-11-16 12:23     ` Jakob Klocker
2026-11-10 10:46 ` [PATCH pve-manager v6 2/3] fix #5032: ui: qemu agent: add sync-time-on-resume option Jakob Klocker
2026-11-10 10:46 ` [PATCH qemu-server v6 3/3] fix #5032: agent: sync guest time via QGA when the clock falls behind Jakob Klocker
2026-11-13 14:10   ` Fiona Ebner
2026-11-16 12:21     ` Jakob Klocker [this message]
2026-11-17  8:57       ` Fiona Ebner
2026-11-17 12:41 ` superseded: [PATCH guest-common/manager/qemu-server v6 0/3] fix #5032: add guest time sync via QGA Jakob Klocker

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=DMWMQKNA9U3Q.9GSB3CN09NUY@proxmox.com \
    --to=j.klocker@proxmox.com \
    --cc=f.ebner@proxmox.com \
    --cc=pve-devel@lists.proxmox.com \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox
Service provided by Proxmox Server Solutions GmbH | Privacy | Legal