5
votes

I have a relatively simple requirement: I want the clock on the CentOS guests that I create under KVM to be synchronized with their CentOS host from the very first boot of the VMs.

It's easy enough to synchronize them with NTP after they are up and running. However, if the host's clock and the VM's clock are widely different when NTP starts, it can cause a large jump in the VM's time. Many of our applications running under the VMs do not handle this time jump well, so we want to prevent this from happening.

So my question is how can I configure my VMs to start with the same time as their host? In the test I just ran, my host's time was 14:00 PDT. A VM I created under that host came up with an initial time of 21:00 PDT. This was adjusted by NTP to 14:00 PDT shortly after it started to 14:00 PDT, matching the host's time, and subsequent reboots of the VM always had the correct time. The problem only occurs on the first boot. I want the VM to come up with 14:00 PDT one the very first boot to avoid the NTP time jump.

1

1 Answers

3
votes

Okay, I've answered my own question. The combination of settings that I used to give me the results I need are:

  1. Set the hwclock on the host and to use UTC time. This is done with the --utc option of the hwclock command. I run the following command on my host OS:

    hwclock --utc --set --date="time-string"

  2. Tell CentOS that the hwclock is using UTC via the file /etc/adjtime. For example, you could initialize this file using

    echo -e "0.0 0 0.0\n0\n\nUTC" >/etc/adjtime

Create this file on both the host and your guest VMs. I create the file on my guests before I boot them for the first time by directly accessing the guest file system from the host.

  1. Set the time zone you want for your system time. Again, do this on both your host and your guests:

    ln -sf /usr/share/zoneinfo/time-zone /etc/localtime
    echo "ZONE=time-zone" >/etc/sysconfig/clock
    export TZ=time-zone

where time-zone is a standard CentOS time zone string, for example "US/Pacific".

  1. Set the system time on your host based on the hwclock. The --utc option is needed to tell CentOS that the hwclock is in UTC time. It will take the UTC time and set your system time based on the TZ environment variable:

    hwclock --utc --hctosys

  2. The steps above are all done once, when you are configuring your host and guests. To keep time synced on all your servers after they are up and running you'll want to configure NTP on your host and guests.