Linux下chrony授时监测脚本

1.背景概述

Linux下基于gpsd+chrony授时,在有些情况下会存在收敛慢或者参考时间选择错误问题,因此需要授时监测脚本进行监测,便于在异常时候发现并处理。

2. gpsd+chrony授时配置方法

2.1 安装chrony

sudo apt-get install chrony
service chrony restart

修改chrony配置文件:/etc/chrony/chrony.conf

# Welcome to the chrony configuration file. See chrony.conf(5) for more
# information about usuable directives.

# This will use (up to):
# - 4 sources from ntp.ubuntu.com which some are ipv6 enabled
# - 2 sources from 2.ubuntu.pool.ntp.org which is ipv6 enabled as well
# - 1 source from [01].ubuntu.pool.ntp.org each (ipv4 only atm)
# This means by default, up to 6 dual-stack and up to 2 additional IPv4-only
# sources will be used.
# At the same time it retains some protection against one of the entries being
# down (compare to just using one of the lines). See (LP: #1754358) for the
# discussion.
#
# About using servers from the NTP Pool Project in general see (LP: #104525).
# Approved by Ubuntu Technical Board on 2011-02-08.
# See http://www.pool.ntp.org/join.html for more information.
#pool ntp.aliyun.com        iburst maxsources 4
#pool 0.ntp.aliyun.com      iburst maxsources 1
#pool 1.ntp.aliyun.com      iburst maxsources 1
#pool 2.ntp.aliyun.com      iburst maxsources 2
#server ntp.aliyun.com       iburst

# This directive specify the location of the file containing ID/key pairs for
# NTP authentication.
keyfile /etc/chrony/chrony.keys

# This directive specify the file into which chronyd will store the rate
# information.
driftfile /var/lib/chrony/chrony.drift

# Uncomment the following line to turn logging on.
#log tracking measurements statistics

refclock PPS /dev/pps0 lock NMEA refid PPS
refclock SHM 0 offset 0.5 delay 0.2 refid NMEA noselect

#refclock PPS /dev/pps0 lock GPSD prefer refid PPS
#refclock SHM 0 offset 0.0 delay 0.2 refid GPSD
# Log files location.
logdir /var/log/chrony

# Stop bad estimates upsetting machine clock.
maxupdateskew 1.0

leapsectz right/UTC
# This directive enables kernel synchronisation (every 11 minutes) of the
# real-time clock. Note that it can’t be used along with the 'rtcfile' directive.
rtcsync

# Step the system clock instead of slewing it if the adjustment is larger than
# one second, but only in the first three clock updates.
makestep 1.0 -1

2.2 安装gpsd

sudo apt-get install gpsd

修改GPSD配置文件:/etc/default/gpsd,其中/dev/ttyTHS1为gps数据输出串口(波特率自动识别)

# Default settings for the gpsd init script and the hotplug wrapper.

# Start the gpsd daemon automatically at boot time
START_DAEMON="true"

# Use USB hotplugging to add new USB devices automatically to the daemon
USBAUTO="true"

# Devices gpsd should collect to at boot time.
# They need to be read/writeable, either by user gpsd or the group dialout.
DEVICES="/dev/ttyTHS1"

# Other options you want to pass to gpsd
GPSD_OPTIONS="-n -G"

开机自动启配置:

sudo systemctl enable gpsd

2.3 查看gpsd是否接收到gps数据

安装完成后执行 cgps –s查看是否有GPS数据安装完成后执行 cgps –s查看是否有GPS数据
在这里插入图片描述
验证授时是否成功
在终端执行watch chronyc sources –v会出现如下图所示结果:
在这里插入图片描述
红色框内的GPSD前有 * 标志表示接收到GPS信号

3. 监测脚本

功能说明:

  • 授时时间差大于1ms,将认为授时异常
  • 参考时间小于2023,将认为授时异常
  • 授时源不是PPS时,将认为授时异常
  • 授时异常时,将重启授时服务(gpsd+chrony)
#!/usr/bin/env python
# coding: utf-8
# author: rui.peng
# date: 2023-03-24

import os
import sys
import time
import socket
import subprocess


def printt(string):
    print('{} {}'.format(time.ctime(), string))
    sys.stdout.flush()


def get_hostname():
    return socket.gethostname()


def get_chrony_sync_server():
    try:
        source = ''
        reftime = 2020
        r = os.popen('chronyc tracking').readlines()
        print('{}'.format(r))
        if len(r) == 13:
            source = r[0].split('(')[-1][:-2]
            if len(r[2].split(' ')) == 10 :
                reftime = int(r[2].split(' ')[9][:-1])
            offset = float(r[3].split()[3])*1e6
            if 'slow' in r[3]:
                offset = -offset
            printt('{} {:.3f}us'.format(source, offset))
        else:
            printt('cmd exe failed!')
    except Exception as e:
        printt(e)
    return source, offset, reftime


def restart_gpsd():
    subprocess.Popen(['sudo', 'service', 'gpsd', 'restart'])
    printt('restart gpsd!')
    time.sleep(5)


def restart_chrony():
    subprocess.Popen(['sudo', 'service', 'chrony', 'restart'])
    printt('restart chrony!')
    time.sleep(60)


if __name__ == '__main__':
    # sleep a while when the server is booting...
#    time.sleep(60)

    hostname = get_hostname()
    printt('I am {}'.format(hostname))

#    while True:
        # server-a: check if gpsd is working. if not, restart it.
    source, offset, reftime = get_chrony_sync_server()
    printt('{} {:.3f}us reftime:{}'.format(source, offset, reftime))
    #if source != 'PPS':
    if offset > 1000 or offset < -1000 or source != 'PPS' or reftime < 2023:
        restart_gpsd()
        restart_chrony()
        #time.sleep(60)
        print('restart gpsd and chrony')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值