Path: blob/master/pkg/cidata/cidata.TEMPLATE.d/boot/00-check-rtc-and-wait-ntp.sh
2685 views
#!/bin/sh12# SPDX-FileCopyrightText: Copyright The Lima Authors3# SPDX-License-Identifier: Apache-2.045set -eu67# In vz, the VM lacks an RTC when booting with a kernel image (see: https://developer.apple.com/forums/thread/760344).8# This causes incorrect system time until NTP synchronizes it, leading to TLS errors.9# To avoid TLS errors, this script waits for NTP synchronization if RTC is unavailable.10test ! -c /dev/rtc0 || exit 01112# This script is intended for services running with systemd.13command -v systemctl >/dev/null 2>&1 || exit 01415echo_with_time_usec() {16time_usec=$(timedatectl show --property=TimeUSec)17echo "${time_usec}, ${1}"18}1920# For the first boot, where the above setting is not yet active, wait for NTP synchronization here.21max_retry=60 retry=022until ntp_synchronized=$(timedatectl show --property=NTPSynchronized --value) && [ "${ntp_synchronized}" = "yes" ] ||23[ "${retry}" -gt "${max_retry}" ]; do24if [ "${retry}" -eq 0 ]; then25# If /dev/rtc is not available, the system time set during the Linux kernel build is used.26# The larger the difference between this system time and the NTP server time, the longer the NTP synchronization will take.27# By setting the system time to the modification time of the reference file, which is likely to be closer to the actual time,28reference_file="${LIMA_CIDATA_MNT:-/mnt/lima-cidata}/user-data"29[ -f "${reference_file}" ] || reference_file="${0}"3031# the NTP synchronization time can be shortened.32echo_with_time_usec "Setting the system time to the modification time of ${reference_file}."3334# To set the time to a specified time, it is necessary to stop systemd-timesyncd.35systemctl stop systemd-timesyncd3637# Since `timedatectl set-time` fails if systemd-timesyncd is not stopped,38# ensure that it is completely stopped before proceeding.39until pid_of_timesyncd=$(systemctl show systemd-timesyncd --property=MainPID --value) && [ "${pid_of_timesyncd}" -eq 0 ]; do40echo_with_time_usec "Waiting for systemd-timesyncd to stop..."41sleep 142done4344# Set the system time to the modification time of the reference file.45modification_time=$(stat -c %y "${reference_file}")46echo_with_time_usec "Setting the system time to ${modification_time}."47timedatectl set-time "${modification_time}"4849# Restart systemd-timesyncd50systemctl start systemd-timesyncd51else52echo_with_time_usec "Waiting for NTP synchronization..."53fi54retry=$((retry + 1))55sleep 156done57# Print the result of NTP synchronization58ntp_message=$(timedatectl show-timesync --property=NTPMessage)59if [ "${ntp_synchronized}" = "yes" ]; then60echo_with_time_usec "NTP synchronization complete."61echo "${ntp_message}"62else63echo_with_time_usec "NTP synchronization timed out."64echo "${ntp_message}"65exit 166fi676869