more 2to3 fallout

This commit is contained in:
2019-12-16 19:42:47 +01:00
parent 83a43a1897
commit 17083f186d
2 changed files with 63 additions and 56 deletions
+58 -55
View File
@@ -29,13 +29,15 @@ import zlib
from subprocess import Popen, STDOUT, PIPE from subprocess import Popen, STDOUT, PIPE
from hbdclass import * #from hbdclass import *
import hbdclass
SEND_EMAIL=False SEND_EMAIL=False
SEND_PUSHOVER=True SEND_PUSHOVER=True
DEBUG = 3 DEBUG = 2
hbdclass.DEBUG = DEBUG
MAXRECV = 32767 MAXRECV = 32767
LOGFILE = "/home/andreas/public_html/messages/andreas" LOGFILE = "/home/andreas/public_html/messages/andreas"
@@ -247,7 +249,7 @@ answer
except: except:
return "nsupdate: some error occured" return "nsupdate: some error occured"
(output, err) = p.communicate(nsup) (output, err) = p.communicate(nsup.encode())
if output.find('status: NOERROR') >= 0: if output.find('status: NOERROR') >= 0:
return None return None
return output return output
@@ -267,11 +269,11 @@ def dur(sec):
def fixsort(): def fixsort():
s = list(Host.hosts.keys()) s = list(hbdclass.Host.hosts.keys())
s.sort() s.sort()
x = 0 x = 0
for n in s: for n in s:
Host.hosts[n].num = x hbdclass.Host.hosts[n].num = x
x += 1 x += 1
# #
@@ -296,18 +298,18 @@ def initlog(logfile):
# #
def checkoverdue(): def checkoverdue():
now = time.time() now = time.time()
for h in list(Host.hosts.keys()): for h in list(hbdclass.Host.hosts.keys()):
pmsg = [] pmsg = []
for c in Host.hosts[h].connections: for c in hbdclass.Host.hosts[h].connections:
conn = Host.hosts[h].connections[c] conn = hbdclass.Host.hosts[h].connections[c]
if conn.state == Connection.down: if conn.state == hbdclass.Connection.down:
continue continue
timeout = Host.hosts[h].interval + grace timeout = hbdclass.Host.hosts[h].interval + grace
if conn.state == Connection.up and (now - conn.lastbeat) > timeout: if conn.state == hbdclass.Connection.up and (now - conn.lastbeat) > timeout:
conn.newstate(Connection.overdue, now, grace) conn.newstate(hbdclass.Connection.overdue, now, grace)
pmsg.append(conn.afam) pmsg.append(conn.afam)
if conn.state == Connection.overdue and (now - conn.lastbeat) > DROPOVERDUE: if conn.state == hbdclass.Connection.overdue and (now - conn.lastbeat) > DROPOVERDUE:
conn.newstate(Connection.unknown, conn.lastbeat) conn.newstate(hbdclass.Connection.unknown, conn.lastbeat)
if pmsg != []: if pmsg != []:
if h in watchhosts: if h in watchhosts:
email("overdue", "%s overdue" % " and ".join(pmsg)) email("overdue", "%s overdue" % " and ".join(pmsg))
@@ -316,7 +318,7 @@ def checkoverdue():
def log(host, m, service=None): def log(host, m, service=None):
if DEBUG > 0: print(("Log: %s %s" % (host, m))) if DEBUG > 0: print("Log: %s %s" % (host, m))
now = time.time() now = time.time()
ts = time.strftime("%b %d %H:%M:%S", time.localtime(now)) ts = time.strftime("%b %d %H:%M:%S", time.localtime(now))
if service: if service:
@@ -341,7 +343,7 @@ def log(host, m, service=None):
def dnsupdatethread(): def dnsupdatethread():
while True: while True:
name, addr = Host.dnsQ.get() name, addr = hbdclass.Host.dnsQ.get()
m = "changed address to %s" % (addr) m = "changed address to %s" % (addr)
err = nsupdate(name, addr) err = nsupdate(name, addr)
if err: if err:
@@ -349,7 +351,7 @@ def dnsupdatethread():
email("error: nsupdate failed", "%s: %s" % (name, m)) email("error: nsupdate failed", "%s: %s" % (name, m))
else: else:
m += ", DNS updated." m += ", DNS updated."
Host.dnsQ.task_done() hbdclass.Host.dnsQ.task_done()
log(name, m) log(name, m)
# #
@@ -377,17 +379,20 @@ def readsock(sock):
addr = addrp[0:2] addr = addrp[0:2]
name = shortname(msg.get('name', "unknown")) name = shortname(msg.get('name', "unknown"))
if not name in Host.hosts: # was: hosts.has_key(name): if not name in hbdclass.Host.hosts: # was: hosts.has_key(name):
host = Host(name) host = hbdclass.Host(name)
host.dyn = name in dyndnshosts host.dyn = name in dyndnshosts
if verbose: print(("XX: New host, num now %s" % (len(Host.hosts)))) if verbose: print(("XX: New host, num now %s" % (len(hbdclass.Host.hosts))))
newh=True newh=True
else: else:
host = Host.hosts[name] host = hbdclass.Host.hosts[name]
newh=False newh=False
cid = msg.get('id', 0) cid = msg.get('id', 0)
rtt = msg.get('rtt',None) try:
rtt = float(msg.get('rtt',None))
except:
rtt = None
if msg['ID'] == 'HTB': if msg['ID'] == 'HTB':
host.doesack = msg.get('acks', -1) host.doesack = msg.get('acks', -1)
@@ -417,9 +422,9 @@ def readsock(sock):
email("address change", "%s %s" % (host.name, res)) email("address change", "%s %s" % (host.name, res))
pushover("%s %s" % (host.name, res)) pushover("%s %s" % (host.name, res))
if conn.getstate() != Connection.up: # XXX and interval > 0: if conn.getstate() != hbdclass.Connection.up: # XXX and interval > 0:
lasts = conn.state lasts = conn.state
d = conn.newstate(Connection.up, now) d = conn.newstate(hbdclass.Connection.up, now)
m = "%s back after being %s for %s" % (conn.afam, lasts, dur(d)) m = "%s back after being %s for %s" % (conn.afam, lasts, dur(d))
log(name, m) log(name, m)
if name in watchhosts: if name in watchhosts:
@@ -437,7 +442,7 @@ def readsock(sock):
if name in watchhosts: if name in watchhosts:
email("shutdown", "%s %s shutdown" % (name, conn.afam)) email("shutdown", "%s %s shutdown" % (name, conn.afam))
pushover("%s %s shutdown" % (name, conn.afam)) pushover("%s %s shutdown" % (name, conn.afam))
conn.newstate(Connection.down, now) conn.newstate(hbdclass.Connection.down, now)
if interval > 0: if interval > 0:
host.interval = interval host.interval = interval
@@ -500,7 +505,7 @@ def updatecode(ucode, uname):
m.update(new_code) m.update(new_code)
icsum = m.hexdigest() icsum = m.hexdigest()
rmsg = {'csum': icsum, 'code': new_code.encode('base64','strict') } rmsg = {'csum': icsum, 'code': new_code.encode('base64','strict') }
Host.hosts[uname].cmds.append(('UPD',rmsg)) hbdclass.Host.hosts[uname].cmds.append(('UPD',rmsg))
return fail return fail
# #
@@ -538,7 +543,7 @@ class HttpHandler(http.server.BaseHTTPRequestHandler):
self.send_response(code) self.send_response(code)
self.send_header("Last-Modified", time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(now))) self.send_header("Last-Modified", time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(now)))
# self.send_header("Accept-Ranges","bytes") # self.send_header("Accept-Ranges","bytes")
# self.send_header("Connection","close") # self.send_header("hbdclass.Connection","close")
for h in headerdict: for h in headerdict:
self.send_header(h, headerdict[h]) self.send_header(h, headerdict[h])
self.end_headers() self.end_headers()
@@ -562,10 +567,8 @@ class HttpHandler(http.server.BaseHTTPRequestHandler):
def buildpage(self): def buildpage(self):
res=self.buildhead(refresh=60, extras=tcss) res=self.buildhead(refresh=60, extras=tcss)
res.append("<H2>Heartbeat status %s</h2>" % VER) res.append("<H2>Heartbeat status %s</h2>" % VER)
res += hbdclass.ubHost.buildhosttable()
res += hbdclass.ubHost.buildmsgtable(msgs)
res += ubHost.buildhosttable()
res += ubHost.buildmsgtable(msgs)
res.append('<p> %s (%s)</p>' % (time.strftime("%H:%M:%S", time.localtime(now)), os.environ.get('TZ', 'CET-1CDT'))) res.append('<p> %s (%s)</p>' % (time.strftime("%H:%M:%S", time.localtime(now)), os.environ.get('TZ', 'CET-1CDT')))
res.append("</body></html>") res.append("</body></html>")
return res return res
@@ -604,10 +607,10 @@ class HttpHandler(http.server.BaseHTTPRequestHandler):
ucmd=qa.get('c', [None])[0] ucmd=qa.get('c', [None])[0]
if not ucmd or not uname: if not ucmd or not uname:
code, res=self.builderror(400, 'Argument error', "need h= and c= arguments") code, res=self.builderror(400, 'Argument error', "need h= and c= arguments")
elif uname not in Host.hosts: elif uname not in hbdclass.Host.hosts:
code, res=self.builderror(400, 'Data error', "h=%s not found" % uname) code, res=self.builderror(400, 'Data error', "h=%s not found" % uname)
else: else:
Host.hosts[uname].cmds.append(('CMD', {'cmd': urllib.parse.unquote(ucmd)})) hbdclass.Host.hosts[uname].cmds.append(('CMD', {'cmd': urllib.parse.unquote(ucmd)}))
res=self.buildhead() res=self.buildhead()
res.append("cmd %s queued for host %s" % (uname, ucmd)) res.append("cmd %s queued for host %s" % (uname, ucmd))
@@ -615,12 +618,12 @@ class HttpHandler(http.server.BaseHTTPRequestHandler):
uname=qa.get('h',[None])[0] uname=qa.get('h',[None])[0]
if not uname: if not uname:
code, res=self.builderror(400, 'Argument error', "need h= argument") code, res=self.builderror(400, 'Argument error', "need h= argument")
if not uname in Host.hosts: if not uname in hbdclass.Host.hosts:
code, res=self.builderror(400, 'Data error', "h=%s not found" % uname) code, res=self.builderror(400, 'Data error', "h=%s not found" % uname)
else: else:
log(uname, "dropped") log(uname, "dropped")
# for addr in Host.hosts[uname].0i # for addr in hbdclass.Host.hosts[uname].0i
del Host.hosts[uname] del hbdclass.Host.hosts[uname]
res=self.buildhead() res=self.buildhead()
res.append("Done") res.append("Done")
@@ -628,10 +631,10 @@ class HttpHandler(http.server.BaseHTTPRequestHandler):
uname=qa.get('h',[None])[0] uname=qa.get('h',[None])[0]
if not uname: if not uname:
code, res=self.builderror(400, 'Argument error', "need h= argument") code, res=self.builderror(400, 'Argument error', "need h= argument")
if not uname in Host.hosts: if not uname in hbdclass.Host.hosts:
code, res=self.builderror(400, 'Data error', "h=%s not found" % uname) code, res=self.builderror(400, 'Data error', "h=%s not found" % uname)
else: else:
ll = Host.hosts[uname].registerDns() ll = hbdclass.Host.hosts[uname].registerDns()
res.append(ll) res.append(ll)
log(uname, ll) log(uname, ll)
@@ -640,7 +643,7 @@ class HttpHandler(http.server.BaseHTTPRequestHandler):
ucode=qa.get('c', [None])[0] ucode=qa.get('c', [None])[0]
if not ucode or not uname: if not ucode or not uname:
code, res=self.builderror(400, 'Argument error', "need h= and c= arguments") code, res=self.builderror(400, 'Argument error', "need h= and c= arguments")
elif uname != 'All' and uname not in Host.hosts: elif uname != 'All' and uname not in hbdclass.Host.hosts:
code, res=self.builderror(400, 'Data error', "h=%s not found" % uname) code, res=self.builderror(400, 'Data error', "h=%s not found" % uname)
else: else:
res=self.buildhead() res=self.buildhead()
@@ -648,8 +651,8 @@ class HttpHandler(http.server.BaseHTTPRequestHandler):
names = [uname] names = [uname]
else: else:
names = [] names = []
for n in Host.hosts: for n in hbdclass.Host.hosts:
if Host.hosts[n].cver >= 2: # earliest version that supports update if hbdclass.Host.hosts[n].cver >= 2: # earliest version that supports update
names.append(n) names.append(n)
for n in names: for n in names:
err = updatecode(ucode, n) err = updatecode(ucode, n)
@@ -659,8 +662,8 @@ class HttpHandler(http.server.BaseHTTPRequestHandler):
elif qr.path == "/api/0/hosts": # api access to host table elif qr.path == "/api/0/hosts": # api access to host table
headerdict = {"Content-Type": "application/json; charset=utf-8" } headerdict = {"Content-Type": "application/json; charset=utf-8" }
l=[] l=[]
for h in Host.hosts: for h in hbdclass.Host.hosts:
l.append(Host.hosts[h].jsons()) l.append(hbdclass.Host.hosts[h].jsons())
res=["["+",".join(l)+"]"] res=["["+",".join(l)+"]"]
elif qr.path == "/api/0/messages": # api access to host table elif qr.path == "/api/0/messages": # api access to host table
@@ -745,7 +748,7 @@ def saveandrestart():
def pickleit(): def pickleit():
pickf = open(pickfile, 'wb') pickf = open(pickfile, 'wb')
pick = pickle.Pickler(pickf) pick = pickle.Pickler(pickf)
pick.dump(Host.hosts) pick.dump(hbdclass.Host.hosts)
pick.dump(msgs) pick.dump(msgs)
pick.dump(lastfm) pick.dump(lastfm)
pickf.close() pickf.close()
@@ -885,7 +888,7 @@ if 1 and os.path.exists(pickfile):
pickf = open(pickfile, 'rb') pickf = open(pickfile, 'rb')
pick = pickle.Unpickler(pickf) pick = pickle.Unpickler(pickf)
try: try:
Host.hosts = pick.load() hbdclass.Host.hosts = pick.load()
msgs = pick.load() msgs = pick.load()
try: try:
lastfm = pick.load() lastfm = pick.load()
@@ -895,14 +898,14 @@ if 1 and os.path.exists(pickfile):
except Exception as e: except Exception as e:
print(("load pickled failed: %s" % e)) print(("load pickled failed: %s" % e))
os.unlink(pickfile) os.unlink(pickfile)
Connection.htab = {} hbdclass.Connection.htab = {}
for h in list(Host.hosts.keys()): for h in list(hbdclass.Host.hosts.keys()):
Host.hosts[h].dyn = h in dyndnshosts hbdclass.Host.hosts[h].dyn = h in dyndnshosts
Host.hosts[h].fixup() hbdclass.Host.hosts[h].fixup()
for h in drophosts: for h in drophosts:
if h in Host.hosts: if h in hbdclass.Host.hosts:
del Host.hosts[h] del hbdclass.Host.hosts[h]
if verbose: print(("%s pickled hosts loaded" % len(Host.hosts))) if verbose: print(("%s pickled hosts loaded" % len(hbdclass.Host.hosts)))
else: else:
if verbose: print("no pickled data") if verbose: print("no pickled data")
@@ -960,7 +963,7 @@ servthread = threading.Thread(target=serv.serve_forever)
servthread.daemon = True servthread.daemon = True
servthread.start() servthread.start()
Host.dnsQ = queue.Queue() hbdclass.Host.dnsQ = queue.Queue()
dnsT = threading.Thread(target=dnsupdatethread) dnsT = threading.Thread(target=dnsupdatethread)
dnsT.daemon = True dnsT.daemon = True
dnsT.start() dnsT.start()
@@ -1010,8 +1013,8 @@ while running:
ts=time.strftime(tsfm[v], time.localtime(now)) ts=time.strftime(tsfm[v], time.localtime(now))
if ts != lastfm[v]: if ts != lastfm[v]:
lastfm[v]=ts lastfm[v]=ts
for h in list(Host.hosts.keys()): for h in list(hbdclass.Host.hosts.keys()):
Host.hosts[h].hdwcounts[v] = [Host.hosts[h].doesack, Host.hosts[h].upcount] hbdclass.Host.hosts[h].hdwcounts[v] = [hbdclass.Host.hosts[h].doesack, hbdclass.Host.hosts[h].upcount]
if now >= rnext and now >= firstcheck: if now >= rnext and now >= firstcheck:
rnext = now+1 rnext = now+1
+5 -1
View File
@@ -13,7 +13,7 @@ num = 0
MAXRTTS = 10 MAXRTTS = 10
DEBUG=1 DEBUG=2
def log(host, m): def log(host, m):
if DEBUG: if DEBUG:
@@ -335,6 +335,8 @@ class Host:
def buildhosttable(self, short=False): def buildhosttable(self, short=False):
if DEBUG > 1:
print("DBG buildhosttable: start")
res = [] res = []
res.append('<table id="ntable" class="sortable">') res.append('<table id="ntable" class="sortable">')
res.append(ubHost.htmltable('th', ubHost.headerdict(), short)) res.append(ubHost.htmltable('th', ubHost.headerdict(), short))
@@ -344,6 +346,8 @@ class Host:
for h in hosts_sorted: for h in hosts_sorted:
res.append(ubHost.htmltable('td', Host.hosts[h].statedict(), short)) res.append(ubHost.htmltable('td', Host.hosts[h].statedict(), short))
res.append("</table>") res.append("</table>")
if DEBUG > 1:
print("DBG buildhosttable: %s" % res)
return res return res