Linux virtualbox синхронизация времени

How to sync time on host wake-up within VirtualBox?

I am running an Ubuntu 12.04-based box inside of Vagrant using VirtualBox. So far, everything is fine — except for one thing: Let’s assume that the VM is running. Then, the host goes to standby-mode. After waking it up again, the VM is still running, but its internal clock continues where it stopped when the host went down. So this basically means: Put the host to sleep for 15 minutes, wake it up again, then the VM’s internal clock is 15 minutes late. How can I fix this (setting the time manually is not an option for obvious reasons ;-))? Is there a way to run a script inside of a Vagrant VM whenever the host system changes its state? I’ve read in the documentation that by default the VirtualBox Guest Additions sync the time with the host every 10 seconds. Apparently this is not happening, but I can not find any place where it is disabled. So any ideas? PS: The Guest Additions are installed and match the version of VirtualBox being used.

6 Answers 6

The documentation lacks some details here.

What VirtualBox does every 10 seconds is just slight adjustement (something like 0.005 seconds). Only when the time difference reaches a threshold (20 minutes by default) a «real» resync is done.

You can reduce the thresold (i.e. to 10 seconds) with the following command:

VBoxManage guestproperty set "/VirtualBox/GuestAdd/VBoxService/--timesync-set-threshold" 10000 

@GoloRoden Thanks for the vb.customize , but the parameters are wrong. The correct command is vb.customize [ «guestproperty», «set», :id, «/VirtualBox/GuestAdd/VBoxService/—timesync-set-threshold», 10000 ]

Might be worth mentioning that vb.customize should be within a block such as: config.vm.provider «virtualbox» do |vb|

I have no idea why, but for me the time is not re-syncing. It is out by several hours, guest is MS-Windows7, host is debian. Virtualbox guest additions service is running in the guest.

Источник

VirtualBox: Как синхронизировать время хоста и гостя?

Время в моей гостевой виртуальной машине быстрее, чем время хоста, примерно на 20-30 минут. Что я могу сделать, чтобы время в гостевой системе было таким же, как и на хосте?

3 ответа 3

Следующая настройка позволяет моему гостю надежно поддерживать время с точностью до 1 секунды от моего хоста. Он протестирован с хостом, на котором работает VirtualBox 4.3.26, и с гостем, работающим с той же версией VirtualBox Guest Additions. Что касается VirtualBox 5.x, у меня до сих пор не было необходимости вносить эти изменения в конфигурацию; время было автоматически синхронизировано. Ссылка: https://www.virtualbox.org/manual/ch09.html#changetimesync На хосте укажите виртуальные машины, чтобы определить имя соответствующей виртуальной машины.

$ VBoxManage list vms | awk '' "CentOS6" 

На хосте настройте параметры синхронизации времени для гостя, выполнив следующие команды. Сначала установите $VMNAME с соответствующим значением. Если значение $VMNAME содержит пробел, его, конечно, следует заключить в кавычки.

$ VBoxManage guestproperty set $ "/VirtualBox/GuestAdd/VBoxService/--timesync-interval" 10000 $ VBoxManage guestproperty set $ "/VirtualBox/GuestAdd/VBoxService/--timesync-min-adjust" 100 $ VBoxManage guestproperty set $ "/VirtualBox/GuestAdd/VBoxService/--timesync-set-on-restore" 1 $ VBoxManage guestproperty set $ "/VirtualBox/GuestAdd/VBoxService/--timesync-set-threshold" 1000 

Значения вышеуказанных временных параметров ограничены кратными 10. Вместо этого может быть соблазнительно установить timesync-set-threshold равным 10000, но это может привести к довольно резкому изменению времени при его срабатывании и, следовательно, к поломке приложений. На хосте просмотрите обновленные релевантные значения для гостя. Они могут быть подтверждены в любое время.

$ VBoxManage guestproperty enumerate $ | grep timesync | sort Name: /VirtualBox/GuestAdd/VBoxService/--timesync-interval, value: 10000, timestamp: 1402110397618554000, flags: Name: /VirtualBox/GuestAdd/VBoxService/--timesync-min-adjust, value: 100, timestamp: 1402110777505446000, flags: Name: /VirtualBox/GuestAdd/VBoxService/--timesync-set-on-restore, value: 1, timestamp: 1402110904964050000, flags: Name: /VirtualBox/GuestAdd/VBoxService/--timesync-set-threshold, value: 1000, timestamp: 1402110660162295000, flags: 

На госте остановите и отключите все внутренние NTP и связанные службы хронометража. Их не следует использовать, поскольку они могут создавать помехи для VirtualBox. На гостях CentOS 6:

$ sudo /sbin/chkconfig ntpd off $ /sbin/chkconfig --list | grep ntp ntpd 0:off 1:off 2:off 3:off 4:off 5:off 6:off ntpdate 0:off 1:off 2:off 3:off 4:off 5:off 6:off 

На госте перезапустите службу с именем vboxadd-service . Если предположить, что гостевые дополнения были ранее установлены, эта служба была бы установлена и включена. На гостях CentOS 6:

$ /sbin/service vboxadd-service status Checking for VBoxService . running $ sudo /sbin/service vboxadd-service restart Stopping VirtualBox Guest Addition service [ OK ] Starting VirtualBox Guest Addition service [ OK ] $ /sbin/service vboxadd-service status Checking for VBoxService . running 

Источник

Читайте также:  Температура процессора linux centos

How to disable VirtualBox time sync from within the guest at runtime

When I run sudo VBoxControl guestproperty enumerate I don’t see anything to do with time syncing.

So… a way to disable and enable time sync from within a VirtualBox VM without disabling the vboxadd-service service please 🙂

4 Answers 4

You should be able to edit the vboxadd-service script on the client and add the —disable-timesync option. Then sudo service vboxadd-service restart and time sync should be disabled.

But I have windows guest and the change in registry was necessary to make it work. I don’t know what is equivalent to windows registry settings in your guest CentOS system.

I have a ubuntu/trusty64 virtual machine I built with vagrant. I had to turn off the time sync in the virtualbox guest addition on the virtual machine. To do this I added VBOX_OPTS to /etc/init.d/virtualbox-guest-utils like so:

edit /etc/init.d/virtualbox-guest-utils insert these lines:

if [ -n "$2" ]; then VBOX_OPTS="$VBOX_OPTS $2" fi 
start-stop-daemon --start --quiet --oknodo --exec /usr/sbin/VBoxService -- $VBOX_OPTS 

Now stop and start the service like so

sudo service virtualbox-guest-utils stop sudo service virtualbox-guest-utils start --disable-timesync 

Now I can set the date to what I need and it stays that way until I reboot the machine.

date -s "2024-02-22 22:41:49,332" && date --rfc-3339=ns date Sat Feb 22 23:27:31 EST 2024 

I tried the —disable-timesync solution, but on my VM it made no difference.

Note that in Ubuntu 18.04 the setup changed to partially make use of the systemd environment. The service is found in this file:

/lib/systemd/system/vboxadd-service.service 

The ExecStart= line gives us the name of the script where the file is found:

/opt/VBoxGuestAdditions-6.1.20/init/vboxadd-service 

You have to be careful as they reimplemented the daemon() and you can’t just add a new option. You have to make sure all entries will know of that additional option.

Читайте также:  Linux at job delete

The first one is here and you have to add $4 :

There is another definition where you also need to add $4 that looks like this:

Then you can add ONE option on the line like so:

 daemon $binary --disable-timesync --pidfile $PIDFILE > /dev/null 

Without the previous two editing, it will fail.

Now, as I mentioned above, that didn’t work for me. What I instead had to do is change the VM paravirtualization setup. By default it’s set to Default which, I think, means KVM. Instead, I now use Minimal.

With the Minimal setup, now my VM keeps time properly with ntp . The Jitter is only around 4 or less. The offset is also very small. I kept the —disable-timesync because it shouldn’t be necessary.

Источник

Синхронизация времени в виртуальной среде

Синхронность показаний времени на взаимодействующих компьютерах — одно из важнейших требований корректной работы в домене.
Нарушение синхронности времени может вести к невозможности входа в домен, ошибкам репликации данных, потере информации.

При работе с виртуальными машинами типичной становится ситуация, когда в восстановленном из длительного «сна» образе виртуальной машины время может отставать иногда на несколько суток.

В современных системах виртуализации при установленных на виртуальных машинах агентах гостевых агентов (KVM/QEMU) или гостевых дополнениях (Oracle VirtualBox) синхронизацию времени в таких ситуациях обеспечивает сама система виртуализации.

В случае отсутствия гостевых служб синхронизация времени должна выполняться штатными службами Astra Linux (см. Службы синхронизации времени в Astra Linux).

При этом одна из этих служб, а именно служба ntp обладает одной специфической особенностью:

При настройках службы ntp, принятых «по умолчанию», ситуация, когда время, полученное от сервера времени, отличается от показаний внутренних часов часов компьютера более, чем на тысячу секунд, считается фатальной ошибкой. Такое большое расхождение времени автоматически не корректируется, и требует вмешательства оператора.

В такой ситуации, для восстановления автоматической синхронизации времени, следует остановить службу синхронизации времени, провести принудительную синхронизацию, и повторно запустить службу:

sudo service ntp stop
sudo ntpdate -bv
sudo service ntp start

Источник

VirtualBox: How to sync host and guest time?

The time in my guest VM is faster than the host time by about 20-30 minutes. What can can I do so that the time in the guest is the same as on the host?

Читайте также:  Linux получить код возврата команды

3 Answers 3

For a Linux host, first install the DKMS (Dynamic Kernel Module Support) package on the guest machine (source):

Then install Guest Additions into guest system:

$ sudo apt-get install virtualbox-guest-additions 

On recent distributions, you will change those packages for virtualbox-guest-dkms and virtualbox-guest-utils .

apt is a package manager specifically for Debian-based distributions. This will not work on other Linux guests.

The following setup allows my guest to reliably maintain a time that is accurate to within 1 second of my host. It is tested with the host running VirtualBox 4.3.26 and the guest running the same version of VirtualBox Guest Additions. As for VirtualBox 5.x, I haven’t thus far had any need to make these configuration changes; the time has automatically been in sync.

On the host, list VMs to ascertain the name of the relevant VM.

$ VBoxManage list vms | awk '' "CentOS6" 

On the host, configure time synchronization parameters for the guest by running the commands below. First set $VMNAME with its appropriate value. If the value of $VMNAME contains a space, it should of course be quoted.

$ VBoxManage guestproperty set $ "/VirtualBox/GuestAdd/VBoxService/--timesync-interval" 10000 $ VBoxManage guestproperty set $ "/VirtualBox/GuestAdd/VBoxService/--timesync-min-adjust" 100 $ VBoxManage guestproperty set $ "/VirtualBox/GuestAdd/VBoxService/--timesync-set-on-restore" 1 $ VBoxManage guestproperty set $ "/VirtualBox/GuestAdd/VBoxService/--timesync-set-threshold" 1000 

The values of the time parameters above have been constrained to multiples of 10. It may be tempting to set timesync-set-threshold to 10000 instead, but this can risk a rather drastic time change when it’s triggered, and may therefore break applications.

On the host, view the updated relevant values for the guest. These can be reconfirmed at any time.

$ VBoxManage guestproperty enumerate $ | grep timesync | sort Name: /VirtualBox/GuestAdd/VBoxService/--timesync-interval, value: 10000, timestamp: 1402110397618554000, flags: Name: /VirtualBox/GuestAdd/VBoxService/--timesync-min-adjust, value: 100, timestamp: 1402110777505446000, flags: Name: /VirtualBox/GuestAdd/VBoxService/--timesync-set-on-restore, value: 1, timestamp: 1402110904964050000, flags: Name: /VirtualBox/GuestAdd/VBoxService/--timesync-set-threshold, value: 1000, timestamp: 1402110660162295000, flags: 

On the guest, stop and disable all internal NTP and related timekeeping services. They should not be used as they are likely to interfere with VirtualBox. On a CentOS 6 guest:

$ sudo /sbin/chkconfig ntpd off $ /sbin/chkconfig --list | grep ntp ntpd 0:off 1:off 2:off 3:off 4:off 5:off 6:off ntpdate 0:off 1:off 2:off 3:off 4:off 5:off 6:off 

On the guest, restart the service named vboxadd-service . Assuming Guest Additions was previously installed, this service would have been installed and enabled. On a CentOS 6 guest:

$ /sbin/service vboxadd-service status Checking for VBoxService . running $ sudo /sbin/service vboxadd-service restart Stopping VirtualBox Guest Addition service [ OK ] Starting VirtualBox Guest Addition service [ OK ] $ /sbin/service vboxadd-service status Checking for VBoxService . running 

If the time on the guest is not yet synced, reboot the guest.

Источник

Оцените статью
Adblock
detector