HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux WebLive 5.15.0-79-generic #86-Ubuntu SMP Mon Jul 10 16:07:21 UTC 2023 x86_64
User: ubuntu (1000)
PHP: 7.4.33
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Upload Files
File: //usr/local/qcloud/monitor/barad/plugin/collector/vm/systime.py
# -*- coding: UTF-8 -*-
import sys
import os,time
sys.path.append(os.getcwd() + '/../../../comm/')
import constant
from plugin_base import VmBaseCollector
from utils.metric_handler import MetricHandler
import ntplib

class TimeCollector(VmBaseCollector):
    def init(self):
        self.set_frequency(60)
        self.handler = MetricHandler()
        self.handler.namespace = 'qce/cvm'
        self.handler.dimensions = [ 'vm_uuid', 'vmip']
        self.ntp_server = self.get_ntp_server()

    def get_time_offset(self):
        ntp_server = []
        offset_time = []
        ntp_conf_path = '/etc/ntp.conf'
        charony_conf_path = '/etc/chrony.conf'
        if os.path.exists(ntp_conf_path):
            with open(ntp_conf_path) as fd:
                for line in fd:
                    if line.startswith('server'):
                        server = line.split()[1]
                        ntp_server.append(server)
        else:
            if os.path.exists(charony_conf_path):
                with open(charony_conf_path) as fd:
                    for line in fd:
                        if line.startswith('server'):
                            server = line.split()[1]
                            ntp_server.append(server)
        
        if len(ntp_server) == 0:
            ntp_server.append(self.ntp_server)

        for i in (ntp_server):
            try:
                ntp = ntplib.NTPClient()
                ntpResponse = ntp.request(i)
                if (ntpResponse):
                    #之前版本offset=now - ntpResponse.tx_time(本地时间-服务器),ntplib中offset(服务器-本地时间),防止客户提单,offset统一选择(本地时间-服务器)
                    offset = (-ntpResponse.offset)
                    offset_time.append(offset)
            except Exception :
                pass
        if(len(offset_time) == 0):
            offset_time.append(0)
        offset_time = sorted(offset_time,key=(abs))
        time_offset = offset_time[0]
        time_offset_max = offset_time[-1]
        return time_offset, time_offset_max        

    def do_collect(self):
        now = int(time.time())
        time_offset = self.get_time_offset()
        self.logger().info("ntp time offset:%f,%f", time_offset[0],time_offset[-1])
        self.set_ntptime_offset(int(time_offset[0]))
        self.set_ntptime_offset(int(time_offset[-1]))

        vm_uuid = self.get_vm_uuid()
        vmip = self.get_vmip()

        dimensions = {'vm_uuid': vm_uuid, 'vmip': vmip }  # not in docker cluster

        batch_metric = [
            {'name':'time_offset' , 'value':time_offset[0]},
            {'name':'time_offset_max' , 'value':time_offset[-1]},
        ]
        self.handler.add_batch_metric(batch = batch_metric, dimensions = dimensions, timestamp = now)

        if (len( self.handler.get_metrics()) > 0) :
            data = {'sender':'nws_sender', 'datas': self.handler.pop_metrics()}
            self.put_data(data)

def main():
    collector = TimeCollector()
    collector.init()
    collector.collect()
    collector.dump_data()

if __name__ == '__main__':
    main()