Atrase a inicialização até que o tempo seja sincronizado

2

Estou executando um Raspberry Pi Model 2B com o Raspbian Stretch (Debian).

Eu tenho um aplicativo de interface do usuário (chromium-browser, iniciado via /home/pi/.config/lxsession/LXDE-pi/autostart ) e um script iniciado via cron, os quais dependem da hora atual real que está sendo definida quando eles iniciam (ou eu teria que colocar alguns hacks feios no código para lidar com isso).

O tempo de inicialização fica várias horas atrasado, até que, em algum momento, a hora é sincronizada pela WLAN.

Eu estava pensando que talvez eu pudesse de alguma forma atrasar a execução do autostart e cron, até que o NTP tivesse a chance de sincronizar.

Como eu faria isso? Ou posso começar de alguma outra forma?

    
por user3768649 26.07.2018 / 20:59

2 respostas

0

Então o que acabei fazendo é implementar algum reconhecimento rudimentar de saltos no script e no aplicativo.

    
por 21.08.2018 / 16:59
2

Isso foi abordado no site do Raspberry Pi SE neste Q & A intitulado: Como forçar o NTPD a atualizar data / hora após a inicialização? .

Método 1

Esta abordagem parece ser o método preferido mais recente:

$ timedatectl
      Local time: Thu 2018-07-26 16:10:31 EDT
  Universal time: Thu 2018-07-26 20:10:31 UTC
        RTC time: n/a
       Time zone: America/New_York (EDT, -0400)
 Network time on: no
NTP synchronized: yes
 RTC in local TZ: no

Se não estiver ativado:

$ timedatectl set-ntp True
root@pi-hole:~ # timedatectl
      Local time: Thu 2018-07-26 16:11:45 EDT
  Universal time: Thu 2018-07-26 20:11:45 UTC
        RTC time: n/a
       Time zone: America/New_York (EDT, -0400)
 Network time on: yes
NTP synchronized: yes
 RTC in local TZ: no

Método # 2

Essa abordagem parece ser o método mais antigo para fazer isso:

$ sudo apt-get install ntpdate

De acordo com essa pergunta:

ntpdate will run when an ethernet interface is brought up, and set the time from an ntp server (see /etc/default/ntpdate).

If ntpd is running, ntpdate will do nothing, however ntpdate will run prior to ntpd at bootup - so this should work out to set the time at bootup as long as there's an ethernet connection.

A propósito, minha versão do Raspian também não habilitou isso:

$ more /etc/os-release
PRETTY_NAME="Raspbian GNU/Linux 9 (stretch)"
NAME="Raspbian GNU/Linux"
VERSION_ID="9"
VERSION="9 (stretch)"
ID=raspbian
ID_LIKE=debian
HOME_URL="http://www.raspbian.org/"
SUPPORT_URL="http://www.raspbian.org/RaspbianForums"
BUG_REPORT_URL="http://www.raspbian.org/RaspbianBugs"

Minhas conclusões sobre os métodos 1 & 2

Pesquisando mais sobre essas soluções, eu não vi indicações de onde isso realmente funcionaria, então os comentários dos outros Q & A da UA são um pouco desconcertantes para mim. Se estivesse conectado ao estado ativo da NIC, esperaria ver algo assim:

$ cat /etc/network/interfaces
auto eth0
    iface eth0 inet dhcp
    post-up /usr/local/sbin/update-time.sh

# REF: https://askubuntu.com/a/708832/17531

Método 3

Dado o estado de coisas acima, acabei implementando a sincronização de NTP assim em meu Raspberry Pi (Raspian) também.

No final, eu simplesmente adicionei isso ao meu /etc/rc.local :

$ cat /etc/rc.local
logger "Beginning force syncing NTP..."
service ntp stop
ntpd -gq
service ntp start
logger "Finished force syncing NTP..."

O que resulta disso em /var/log/syslog :

Aug  5 09:10:20 pi-hole ntp[526]: Starting NTP server: ntpd.
Aug  5 09:10:20 pi-hole ntpd[555]: proto: precision = 1.458 usec (-19)
Aug  5 09:10:20 pi-hole ntpd[555]: Listen and drop on 0 v6wildcard [::]:123
Aug  5 09:10:20 pi-hole ntpd[555]: Listen and drop on 1 v4wildcard 0.0.0.0:123
Aug  5 09:10:20 pi-hole ntpd[555]: Listen normally on 2 lo 127.0.0.1:123
Aug  5 09:10:20 pi-hole ntpd[555]: Listen normally on 3 eth0 192.168.1.85:123
Aug  5 09:10:20 pi-hole ntpd[555]: Listen normally on 4 lo [::1]:123
Aug  5 09:10:20 pi-hole ntpd[555]: Listen normally on 5 eth0 [fe80::f5ea:7663:4ec:784d%2]:123
Aug  5 09:10:20 pi-hole ntpd[555]: Listening on routing socket on fd #22 for interface updates
Aug  5 09:10:21 pi-hole ntpd[555]: ntpd exiting on signal 15 (Terminated)
Aug  5 09:10:21 pi-hole ntp[661]: Stopping NTP server: ntpd.
Aug  5 09:10:21 pi-hole ntpd[674]: ntpd [email protected] Sat Mar 10 18:03:33 UTC 2018 (1): Starting
Aug  5 09:10:21 pi-hole ntpd[674]: Command line: ntpd -gq
Aug  5 09:10:21 pi-hole ntpd[674]: proto: precision = 0.625 usec (-21)
Aug  5 09:10:21 pi-hole ntpd[674]: Listen and drop on 0 v6wildcard [::]:123
Aug  5 09:10:21 pi-hole ntpd[674]: Listen and drop on 1 v4wildcard 0.0.0.0:123
Aug  5 09:10:21 pi-hole ntpd[674]: Listen normally on 2 lo 127.0.0.1:123
Aug  5 09:10:21 pi-hole ntpd[674]: Listen normally on 3 eth0 192.168.1.85:123
Aug  5 09:10:21 pi-hole ntpd[674]: Listen normally on 4 lo [::1]:123
Aug  5 09:10:21 pi-hole ntpd[674]: Listen normally on 5 eth0 [fe80::f5ea:7663:4ec:784d%2]:123
Aug  5 09:10:21 pi-hole ntpd[674]: Listening on routing socket on fd #22 for interface updates
Aug  5 09:10:34 pi-hole ntpd[674]: Soliciting pool server 198.98.57.16
Aug  5 09:10:35 pi-hole ntpd[674]: Soliciting pool server 74.82.59.149
Aug  5 09:10:36 pi-hole ntpd[674]: Soliciting pool server 23.131.160.7
Aug  5 09:10:36 pi-hole ntpd[674]: Soliciting pool server 52.37.26.163
Aug  5 09:10:36 pi-hole ntpd[674]: Soliciting pool server 204.2.134.163
Aug  5 09:10:36 pi-hole ntpd[674]: Soliciting pool server 96.126.100.203
Aug  5 09:10:36 pi-hole ntpd[674]: Soliciting pool server 199.223.248.101
Aug  5 09:10:36 pi-hole ntpd[674]: Soliciting pool server 66.228.42.59
Aug  5 09:10:36 pi-hole ntpd[674]: Soliciting pool server 208.75.89.4
Aug  5 09:10:37 pi-hole ntpd[674]: Soliciting pool server 204.2.134.164
Aug  5 09:10:37 pi-hole ntpd[674]: Soliciting pool server 104.236.116.147
Aug  5 09:10:38 pi-hole ntpd[674]: Soliciting pool server 204.9.54.119
Aug  5 09:10:48 pi-hole ntpd[674]: ntpd: time set +6.769186 s
Aug  5 09:10:49 pi-hole ntpd[853]: ntpd [email protected] Sat Mar 10 18:03:33 UTC 2018 (1): Starting
Aug  5 09:10:49 pi-hole ntpd[853]: Command line: /usr/sbin/ntpd -p /var/run/ntpd.pid -g -u 111:114
Aug  5 09:10:49 pi-hole ntp[844]: Starting NTP server: ntpd.
Aug  5 09:10:49 pi-hole ntpd[856]: proto: precision = 0.625 usec (-21)
Aug  5 09:10:49 pi-hole ntpd[856]: Listen and drop on 0 v6wildcard [::]:123
Aug  5 09:10:49 pi-hole ntpd[856]: Listen and drop on 1 v4wildcard 0.0.0.0:123
Aug  5 09:10:49 pi-hole ntpd[856]: Listen normally on 2 lo 127.0.0.1:123
Aug  5 09:10:49 pi-hole ntpd[856]: Listen normally on 3 eth0 192.168.1.85:123
Aug  5 09:10:49 pi-hole ntpd[856]: Listen normally on 4 lo [::1]:123
Aug  5 09:10:49 pi-hole ntpd[856]: Listen normally on 5 eth0 [fe80::f5ea:7663:4ec:784d%2]:123
Aug  5 09:10:49 pi-hole ntpd[856]: Listening on routing socket on fd #22 for interface updates
Aug  5 09:10:49 pi-hole root: Finished force syncing NTP...

Por que eu precisaria de rc.local?

As coisas que notei enquanto analisava isso giravam em torno da instalação de outros serviços NTP, como chrony ou ntpd . Ter estes em um sistema negaria as facilidades timedatectl do systemd, principalmente através deste arquivo:

$ cat /lib/systemd/system/systemd-timesyncd.service.d/disable-with-time-daemon.conf
[Unit]
# don't run timesyncd if we have another NTP daemon installed
ConditionFileIsExecutable=!/usr/sbin/ntpd
ConditionFileIsExecutable=!/usr/sbin/openntpd
ConditionFileIsExecutable=!/usr/sbin/chronyd
ConditionFileIsExecutable=!/usr/sbin/VBoxService

Resultando nisso:

$ systemctl status systemd-timesyncd.service
● systemd-timesyncd.service - Network Time Synchronization
   Loaded: loaded (/lib/systemd/system/systemd-timesyncd.service; enabled; vendor preset: enabled)
  Drop-In: /lib/systemd/system/systemd-timesyncd.service.d
           └─disable-with-time-daemon.conf
   Active: inactive (dead)
Condition: start condition failed at Sun 2018-08-05 10:05:53 EDT; 1s ago
           └─ ConditionFileIsExecutable=!/usr/sbin/ntpd was not met
     Docs: man:systemd-timesyncd.service(8)

Removendo tudo para que dependamos apenas do recurso timeyncd de systemd :

$ cat /lib/systemd/system/systemd-timesyncd.service.d/disable-with-time-daemon.conf |awk -F'=!' '/Condition/ {print $2}' | xargs ls
ls: cannot access '/usr/sbin/ntpd': No such file or directory
ls: cannot access '/usr/sbin/openntpd': No such file or directory
ls: cannot access '/usr/sbin/chronyd': No such file or directory
ls: cannot access '/usr/sbin/VBoxService': No such file or directory

Agora permite que ele seja executado:

$ systemctl status systemd-timesyncd.service
● systemd-timesyncd.service - Network Time Synchronization
   Loaded: loaded (/lib/systemd/system/systemd-timesyncd.service; enabled; vendor preset: enabled)
  Drop-In: /lib/systemd/system/systemd-timesyncd.service.d
           └─disable-with-time-daemon.conf
   Active: active (running) since Sun 2018-08-05 10:14:44 EDT; 5s ago
     Docs: man:systemd-timesyncd.service(8)
 Main PID: 3714 (systemd-timesyn)
   Status: "Synchronized to time server 108.59.2.24:123 (0.debian.pool.ntp.org)."
   CGroup: /system.slice/systemd-timesyncd.service
           └─3714 /lib/systemd/systemd-timesyncd

Aug 05 10:14:44 pi-hole systemd[1]: Starting Network Time Synchronization...
Aug 05 10:14:44 pi-hole systemd[1]: Started Network Time Synchronization.
Aug 05 10:14:45 pi-hole systemd-timesyncd[3714]: Synchronized to time server 108.59.2.24:123 (0.debian.pool.ntp.org).

No Raspian (supondo que o Ubuntu e o Debian também seriam assim), os comentários no arquivo de configuração para timesyncd.conf parecem indicar que já há servidores NTP codificados:

$ cat /etc/systemd/timesyncd.conf
...
...
# Entries in this file show the compile time defaults.
# You can change settings by editing this file.
# Defaults can be restored by simply deleting this file.
#
# See timesyncd.conf(5) for details.

[Time]
#NTP=
#FallbackNTP=0.debian.pool.ntp.org 1.debian.pool.ntp.org 2.debian.pool.ntp.org 3.debian.pool.ntp.org

Forçando uma sincronização

Não parece haver qualquer método para forçar uma sincronização diretamente. Reiniciar o serviço systemd-timesyncd , na verdade, aciona uma ressincronização:

$ systemctl restart systemd-timesyncd

Você pode ver isso nos registros:

$ journalctl -u systemd-timesyncd
-- Logs begin at Thu 2016-11-03 13:16:42 EDT, end at Sun 2018-08-05 10:44:37 EDT. --
Aug 05 10:14:44 pi-hole systemd[1]: Starting Network Time Synchronization...
Aug 05 10:14:44 pi-hole systemd[1]: Started Network Time Synchronization.
Aug 05 10:14:45 pi-hole systemd-timesyncd[3714]: Synchronized to time server 108.59.2.24:123 (0.debian.pool.ntp.org).
Aug 05 10:44:37 pi-hole systemd[1]: Stopping Network Time Synchronization...
Aug 05 10:44:37 pi-hole systemd[1]: Stopped Network Time Synchronization.
Aug 05 10:44:37 pi-hole systemd[1]: Starting Network Time Synchronization...
Aug 05 10:44:37 pi-hole systemd[1]: Started Network Time Synchronization.
Aug 05 10:44:37 pi-hole systemd-timesyncd[4157]: Synchronized to time server 208.75.88.4:123 (0.debian.pool.ntp.org).

A última linha é do meu reinício. Além de um reinício, a versão de systemd-timesyncd desta versão particular do Raspian não inclui este patch - timesync: torna o intervalo de sondagem configurável # 7268 , portanto, você não pode controlar a sincronização além da reinicialização.

Nas versões posteriores de systemd-timesyncd você pode com esta opção:

   PollIntervalMinSec=, PollIntervalMaxSec=

   The minimum and maximum poll intervals for NTP messages. Each setting takes a time 
   value (in seconds). PollIntervalMinSec= must not be smaller than 16 seconds. 
   PollIntervalMaxSec= must be larger than PollIntervalMinSec=. PollIntervalMinSec= 
   defaults to 32 seconds, and PollIntervalMaxSec= defaults to 2048 seconds.

Referências

por 26.07.2018 / 22:05