import agent_util
import time
from datetime import datetime
import socket
import struct
def getNTPTime(host="pool.ntp.org", port=123):
buf = 1024
address = (host, port)
msg = '\x1b' + 47 * '\0'
TIME1970 = 2208988800 # 1970-01-01 00:00:00
# connect to server
try:
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.settimeout(15)
client.sendto(msg.encode(), address)
msg, address = client.recvfrom(buf)
t = struct.unpack("!12I", msg)[10]
t -= TIME1970
## t = time.gmtime(t)
## t = datetime(year=t.tm_year, month=t.tm_mon, day=t.tm_mday, hour=t.tm_hour, minute=t.tm_min, second=t.tm_sec)
return t
except:
return None
class NTPPlugin(agent_util.Plugin):
textkey = "ntp"
label = "NTP"
@classmethod
def get_metadata(self, config):
status = agent_util.SUPPORTED
msg = None
metadata = {
"ntp_diff": {
"label": "Difference between machine and NTP time",
"options": None,
"status": status,
"error_message": msg,
"unit": "second"
}
}
return metadata
def check(self, textkey, data, config={}):
if textkey == 'ntp_diff':
host = config.get("ntp_host", "pool.ntp.org")
port = int(config.get("ntp_port", 123))
ntp_time = getNTPTime(host, port)
local_time = time.mktime(datetime.now().timetuple())
if not ntp_time:
self.log.critical("Unable to get NTP time from %s:%s" % (host, port))
return
else:
self.log.info("NTP: %s, local: %s" % (ntp_time, local_time))
time_diff = abs(local_time - ntp_time)
if time_diff < 86400*365:
# Return the value if it's less than a year out of sync
return time_diff
else:
return None
return 0