PingPanel.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952
  1. #!/usr/bin/env python3
  2. # Copyright 2024 by Siegrist(SystemLoesungen) <PSS@ZweierNet.ch>
  3. # This program is free software: you can redistribute it and/or modify
  4. # it under the terms of the GNU General Public License as published by
  5. # the Free Software Foundation, either version 3 of the License, or
  6. # (at your option) any later version.
  7. #
  8. # This program is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #import datetime
  13. from datetime import datetime
  14. import os
  15. import errno
  16. import configparser
  17. import time
  18. import signal
  19. import sys
  20. import subprocess
  21. import re
  22. import argparse
  23. from threading import Thread
  24. import json
  25. import tornado.ioloop
  26. import tornado.web
  27. import tornado.websocket
  28. from tornado.gen import sleep
  29. import asyncio
  30. VERSION = '0.9.21'
  31. konfig_file = 'config.cfg'
  32. modal_konfigs = ''
  33. s_certfile = 'server.crt'
  34. s_keyfile = 'server.key'
  35. ws_method = 'ws'
  36. host_dict = dict()
  37. failed_pingc = dict()
  38. g_since = dict()
  39. y_since = dict()
  40. r_since = dict()
  41. g_timbar = dict()
  42. y_timbar = dict()
  43. r_timbar = dict()
  44. loop_interval = 3
  45. listen_port = 8888
  46. listen_addr = '0.0.0.0'
  47. anz_hosts = 0
  48. bar_duration = 3600
  49. ping_forever = False
  50. fping_parameter = []
  51. fping_cmd = 'fping'
  52. def signal_handler(signal, frame):
  53. print('\nCtrl+C, keyboardInterrupt detected!')
  54. sys.exit(0)
  55. signal.signal(signal.SIGINT, signal_handler)
  56. def to_bool(s):
  57. return s.strip().lower() in {"true", "1", "yes", "y"}
  58. config = configparser.ConfigParser(delimiters=('='), comment_prefixes=('#'), allow_no_value=False, strict=True, empty_lines_in_values=False)
  59. def read_config():
  60. try:
  61. if config.read([konfig_file]) != []:
  62. pass
  63. else:
  64. print("Configfile '" + konfig_file + "' not found!")
  65. sys.exit()
  66. except configparser.DuplicateSectionError as e:
  67. print("Error: Duplicate Section '%s' not allowed." % str(e.section))
  68. sys.exit()
  69. except configparser.DuplicateOptionError as e:
  70. print("Error: Duplicate Option '%s' in Section '%s' not allowed." % ( str(e.option), str(e.section) ))
  71. sys.exit()
  72. except configparser.Error as e:
  73. print("Error in Configfile: %s." % str(e))
  74. sys.exit()
  75. #print(config.sections())
  76. global anz_hosts
  77. for sect in config.sections():
  78. for key in config[sect]:
  79. if (sect == "Main"):
  80. try:
  81. global loop_interval
  82. loop_interval = int(config["Main"]["LoopInterval"])
  83. except KeyError:
  84. pass
  85. try:
  86. global listen_port
  87. listen_port = int(config["Main"]["ListenPort"])
  88. except KeyError:
  89. pass
  90. try:
  91. global listen_addr
  92. listen_addr = str(config["Main"]["ListenAddr"])
  93. except KeyError:
  94. pass
  95. try:
  96. title_add = str(config["Main"]["TitleAdd"])
  97. except KeyError:
  98. config["Main"]["TitleAdd"] = ''
  99. try:
  100. global ws_method
  101. if ( str(config["Main"]["UseHTTPS"]) ):
  102. ws_method = 'wss'
  103. s_certfile = str(config["Main"]["CertFile"])
  104. s_keyfile = str(config["Main"]["KeyFile"])
  105. apath = os.path.dirname(os.path.abspath(__file__))
  106. if not file_exists(s_certfile):
  107. print("CertFile not readable or does not exist: %s" % apath + '/' + s_certfile)
  108. sys.exit()
  109. if not file_exists(s_keyfile):
  110. print("KeyFile not readable or does not exist: %s" % apath + '/' + s_keyfile)
  111. sys.exit()
  112. except KeyError:
  113. pass
  114. try:
  115. global bar_duration
  116. bar_duration = restrict(int(config["Main"]["DurationBarSpan"]), 1, 5184000)
  117. except KeyError:
  118. pass
  119. try:
  120. global ping_forever
  121. ping_forever = to_bool(config["Main"]["PingForever"])
  122. except KeyError:
  123. pass
  124. if args.v: print(konfig_file + ": " + sect + ": " + key + " = " + config[sect][key])
  125. else:
  126. if args.s and sect_file:
  127. return
  128. else:
  129. #host_dict[key] = config[sect][key]
  130. host_dict[key] = sect.replace(' ','_')
  131. failed_pingc[key] = 0
  132. anz_hosts += 1
  133. if args.v: print(konfig_file + ": " + sect + ": " + key + " = " + config[sect][key])
  134. def read_sections_config():
  135. global anz_hosts
  136. try:
  137. if config.read([sect_file]) != []:
  138. pass
  139. else:
  140. print("Sectionsfile '" + sect_file + "' not found!")
  141. sys.exit()
  142. except configparser.DuplicateSectionError as e:
  143. print("Error: Duplicate Section '%s' not allowed." % str(e.section))
  144. sys.exit()
  145. except configparser.DuplicateOptionError as e:
  146. print("Error: Duplicate Option '%s' in Section '%s' not allowed." % ( str(e.option), str(e.section) ))
  147. sys.exit()
  148. except configparser.Error as e:
  149. print("Error in Configfile: %s." % str(e))
  150. sys.exit()
  151. #print(config.sections())
  152. for sect in config.sections():
  153. if (sect == "Main"):
  154. continue
  155. for key in config[sect]:
  156. #host_dict[key] = config[sect][key]
  157. host_dict[key] = sect.replace(' ','_')
  158. failed_pingc[key] = 0
  159. anz_hosts += 1
  160. if args.v: print(sect_file + ": " + sect + ": " + key + " = " + config[sect][key])
  161. def cmd_exists(cmd):
  162. path = os.environ["PATH"].split(os.pathsep)
  163. for prefix in path:
  164. filename = os.path.join(prefix, cmd)
  165. executable = os.access(filename, os.X_OK)
  166. is_not_directory = os.path.isfile(filename)
  167. if executable and is_not_directory:
  168. return True
  169. return False
  170. def file_exists(file):
  171. filename = os.path.dirname(os.path.abspath(__file__)) + '/' + file
  172. if os.access(filename, os.R_OK):
  173. return True
  174. return False
  175. def set_since(host,now,set,unset1,unset2):
  176. unset1[host]=None
  177. unset2[host]=None
  178. if set.get(host):
  179. pass
  180. else:
  181. set[host] = now
  182. def restrict(value, lower, upper):
  183. return lower if value < lower else upper if value > upper else value
  184. def create_fpingparam():
  185. global fping_parameter
  186. global fping_cmd
  187. try:
  188. fping_parameter.append(config["Main"]["fpingCommand"])
  189. fping_cmd = config["Main"]["fpingCommand"]
  190. except KeyError:
  191. fping_parameter.append(fping_cmd)
  192. fping_parameter += ['--quiet', '--vcount=3']
  193. try:
  194. fping_parameter.append('--interval=' + config["Main"]["Fping-interval"])
  195. except KeyError:
  196. fping_parameter.append('--interval=1')
  197. try:
  198. fping_parameter.append('--period=' + config["Main"]["Fping-period"])
  199. except KeyError:
  200. fping_parameter.append('--period=100')
  201. try:
  202. fping_parameter.append('--size=' + config["Main"]["Fping-size"])
  203. except KeyError:
  204. fping_parameter.append('--size=56')
  205. pass
  206. def ping(ip, packets=1, timeout=2):
  207. comd = ['ping', '-c', str(packets), '-w', str(timeout), ip]
  208. res = subprocess.run(comd, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
  209. return res.returncode == 0
  210. def fping(ips):
  211. comd = fping_parameter + ips
  212. res = subprocess.run(comd, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) #, universal_newlines = True)
  213. if args.v:
  214. print("fping finished: " + datetime.now().strftime("%H:%M:%S"))
  215. if res.returncode == 2:
  216. print("fping: any IP addresses were not found !")
  217. elif res.returncode == 3:
  218. print("fping: invalid command line arguments !")
  219. elif res.returncode == 4:
  220. print("fping: system call failure !")
  221. #print("RET:"+str(res.returncode))
  222. return res.stdout.decode("utf-8")
  223. # Pinging Loop
  224. async def PingLoop():
  225. print("PingLoop gestartet.")
  226. # sleep for a moment
  227. while True:
  228. await asyncio.sleep(3)
  229. # Sinnlos wenn niemend zuschaut:
  230. if ( len(BroadcastHandler.clients) < 1 ):
  231. continue
  232. for host, name in host_dict.items():
  233. #print("ping host: " + host)
  234. if ping(host,1,2):
  235. line = {
  236. "host": host, "status": "OK"
  237. }
  238. BroadcastHandler.broadcast(line)
  239. else:
  240. line = {
  241. "host": host, "status": "FAILED"
  242. }
  243. BroadcastHandler.broadcast(line)
  244. # End while True
  245. # Fping Loop
  246. async def FpingLoop():
  247. print("FpingLoop ready.")
  248. ip_list = list(host_dict.keys())
  249. create_fpingparam()
  250. # check for ping command
  251. if not cmd_exists(fping_cmd):
  252. print("Exit with Error: fping command not found or not executable: '%s'" % fping_cmd)
  253. sys.exit(1)
  254. if args.v:
  255. tmp_cmd = [] + fping_parameter + ip_list
  256. comd_out = ' '.join(tmp_cmd)
  257. comd_out.replace("'", "")
  258. print('ping command used: "' + comd_out + '"')
  259. # The Loop
  260. while True:
  261. # Sinnlos wenn niemend zuschaut:
  262. if len(BroadcastHandler.clients) < 1 and not ping_forever:
  263. await asyncio.sleep(3)
  264. continue
  265. ac_now = datetime.now()
  266. ac_time = ac_now.strftime("%H:%M:%S")
  267. ac_timed = ac_now.strftime("%a %d %H:%M:%S")
  268. tnow = int(ac_now.timestamp())
  269. if args.v: print("call fping: " + ac_time)
  270. ret = fping(ip_list)
  271. rl = ret.splitlines()
  272. json_bc = []
  273. cnt_ok = 0
  274. cnt_halb = 0
  275. cnt_fail = 0
  276. for line in rl:
  277. host,rtims = line.split(' : ')
  278. if ( re.search(r"duplicate", rtims, flags=re.I) ):
  279. #print(host+": "+rtims)
  280. continue
  281. host = host.strip()
  282. rtims = rtims.strip()
  283. #print(host+": "+rtims)
  284. ux_sect = 'ux_' + host_dict[host]
  285. if re.search(r"[\d\.]+ [\d\.]+ [\d\.]+", rtims):
  286. #print(host+" OK")
  287. cnt_ok += 1
  288. set_since(host, ac_timed, set=g_since,unset1=y_since,unset2=r_since)
  289. set_since(host, tnow, set=g_timbar,unset1=y_timbar,unset2=r_timbar)
  290. g_timb = restrict(int(100-(100 * ( (tnow - g_timbar[host]) / bar_duration))+1), 0, 100)
  291. json_bc.append({
  292. "host": host, "status": "OK", "rtt": rtims, "actime": ac_time, "sect": ux_sect, "since": g_since[host], "timbar": g_timb
  293. })
  294. failed_pingc[host] = 0
  295. #BroadcastHandler.broadcast(line)
  296. elif re.search(r"[\d\.]+ [\d\.]+ -", rtims) or re.search(r"[\d\.]+ - [\d\.]+", rtims) or re.search(r"- [\d\.]+ [\d\.]+", rtims):
  297. #print(host+" OK")
  298. cnt_ok += 1
  299. set_since(host, ac_timed, set=g_since,unset1=y_since,unset2=r_since)
  300. set_since(host, tnow, set=g_timbar,unset1=y_timbar,unset2=r_timbar)
  301. g_timb = restrict(int(100-(100 * ( (tnow - g_timbar[host]) / bar_duration))+1), 0, 100)
  302. json_bc.append({
  303. "host": host, "status": "OK", "rtt": rtims, "actime": ac_time, "sect": ux_sect, "since": g_since[host], "timbar": g_timb
  304. })
  305. failed_pingc[host] = 0
  306. #BroadcastHandler.broadcast(line)
  307. elif re.search(r"- - -", rtims):
  308. #print(host+" FAILED")
  309. cnt_fail += 1
  310. set_since(host, ac_timed, set=r_since,unset1=y_since,unset2=g_since)
  311. set_since(host, tnow, set=r_timbar,unset1=y_timbar,unset2=g_timbar)
  312. r_timb = restrict(int(100-(100 * ( (tnow - r_timbar[host]) / bar_duration))+1), 0, 100)
  313. if failed_pingc[host] < int(config["Main"]["FlashThreshold"]):
  314. json_bc.append({
  315. "host": host, "status": "NEWFAIL", "rtt": rtims, "actime": ac_time, "sect": ux_sect, "since": r_since[host], "timbar": r_timb
  316. })
  317. failed_pingc[host] += 1
  318. else:
  319. json_bc.append({
  320. "host": host, "status": "FAILED", "rtt": rtims, "actime": ac_time, "sect": ux_sect, "since": r_since[host], "timbar": r_timb
  321. })
  322. failed_pingc[host] = int(config["Main"]["FlashThreshold"]) + 1
  323. #BroadcastHandler.broadcast(line)
  324. elif re.search(r"[\d\.]+", rtims):
  325. #print(host+" HALB")
  326. cnt_halb += 1
  327. set_since(host, ac_timed, set=y_since,unset1=r_since,unset2=g_since)
  328. set_since(host, tnow, set=y_timbar,unset1=r_timbar,unset2=g_timbar)
  329. y_timb = restrict(int(100-(100 * ( (tnow - y_timbar[host]) / bar_duration))+1), 0, 100)
  330. json_bc.append({
  331. "host": host, "status": "HALB", "rtt": rtims, "actime": ac_time, "sect": ux_sect, "since": y_since[host], "timbar": y_timb
  332. })
  333. failed_pingc[host] = 0
  334. #BroadcastHandler.broadcast(line)
  335. else:
  336. print(host+" ???????????????????")
  337. if args.v: print("STAT(%d hosts, interval:%s ms, period:%s ms): green=%d / yellow=%d / red=%d / ping-round: %d sec" % (anz_hosts, config["Main"]["Fping-interval"], config["Main"]["Fping-period"], cnt_ok, cnt_halb, cnt_fail, int(datetime.now().timestamp()) - int(ac_now.timestamp())) )
  338. #print(g_timbar)
  339. #print(y_timbar)
  340. #print(r_timbar)
  341. #print(json.dumps(json_bc, separators=(',', ':'), ensure_ascii=False))
  342. BroadcastHandler.broadcast(json_bc)
  343. # sleep for Config-LoopInterval
  344. if ( len(BroadcastHandler.clients) >= 1 or ping_forever):
  345. await asyncio.sleep(loop_interval)
  346. # End while True
  347. class BroadcastHandler(tornado.websocket.WebSocketHandler):
  348. clients = []
  349. def open(self):
  350. o_time = datetime.now().strftime("%d.%m.%y %H:%M")
  351. if not re.search(r"^/websocket$", self.request.uri):
  352. log_msg = '"Bad request uri"'
  353. print("%s: Client %s: WebSocket Open-Error: %s " % (o_time, self.request.remote_ip, log_msg))
  354. self.close(1111)
  355. return
  356. BroadcastHandler.clients.append(self)
  357. print("%s: Client %s: WebSocket opened: %s " % (o_time, self.request.remote_ip, self.request)) # oder "self.request.remote_ip" etc. / oder "self.__dict__"
  358. def on_close(self):
  359. BroadcastHandler.clients.remove(self)
  360. c_time = datetime.now().strftime("%d.%m.%y %H:%M")
  361. if ( self.close_code ):
  362. print("%s: Client %s: WebSocket closed: %s (close_code: %d)" % (c_time, self.request.remote_ip, self.request, self.close_code))
  363. else:
  364. print("%s: Client %s: WebSocket undefined closed." % (c_time, self.request.remote_ip))
  365. @classmethod
  366. def broadcast(cls, message):
  367. errored = []
  368. for client in cls.clients:
  369. #print("Broadcasted: %s" % message)
  370. #print("Broadcasted: %s" % client.request.remote_ip)
  371. try:
  372. client.write_message(json.dumps(message, separators=(',', ':'), ensure_ascii=False))
  373. #print("Broadcasted: %s" % message)
  374. except tornado.websocket.WebSocketClosedError:
  375. print("Error sending Broadcast message: WebSocketClosedError() raised")
  376. errored.append(client)
  377. except tornado.websocket.Exception as e:
  378. print("Error sending message: " + str(e))
  379. errored.append(client)
  380. for conn in errored:
  381. cls.clients.remove(conn)
  382. class WWWSocketHandler(tornado.web.RequestHandler):
  383. #@tornado.gen.coroutine
  384. def prepare(self):
  385. #if self.request.protocol == 'http':
  386. # print("mmmm" + self.request.protocol)
  387. pass
  388. def get(self):
  389. #print(self.request.headers)
  390. #print(self.__dict__)
  391. if not re.search(r"^/$", self.request.uri):
  392. return
  393. html_modal01 = create_html_modal01()
  394. html_tab = create_html_table()
  395. self.write(html_html % (config["Main"]["TitleAdd"], ws_method, self.request.host, html_css, html_tab, html_modal01))
  396. def on_connection_close(self):
  397. print("RequestHandler on_connection_close(): " + str(self.__dict__))
  398. async def test():
  399. while True:
  400. print("test")
  401. await asyncio.sleep(5)
  402. def make_app():
  403. abs_path = os.path.dirname(os.path.abspath(__file__))
  404. web_app = tornado.web.Application([
  405. (r"^/websocket$", BroadcastHandler),
  406. (r"/", WWWSocketHandler),
  407. (r'/css/(.+\.css)', tornado.web.StaticFileHandler, {'path': abs_path + '/'}),
  408. (r'/img/(.+\.gif)', tornado.web.StaticFileHandler, {'path': abs_path + '/'}),
  409. (r'/(favicon.ico)', tornado.web.StaticFileHandler, {'path': abs_path + '/'}),
  410. ],debug=False,websocket_ping_interval=10,websocket_ping_timeout=30)
  411. if ws_method == 'ws':
  412. # http method in use:
  413. print("Serving HTTP and ws.")
  414. print("Listen on "+listen_addr+" Port "+str(listen_port)+" (http://"+listen_addr+":"+str(listen_port)+"/).")
  415. return web_app
  416. # https method in use:
  417. print("Serving HTTPS and wss.")
  418. print("Listen on "+listen_addr+" Port "+str(listen_port)+" (https://"+listen_addr+":"+str(listen_port)+"/).")
  419. http_server = tornado.httpserver.HTTPServer(web_app,
  420. ssl_options = {
  421. "certfile": abs_path + '/' + s_certfile,
  422. "keyfile": abs_path + '/' + s_keyfile,
  423. }
  424. )
  425. return http_server
  426. async def main():
  427. app = make_app()
  428. try:
  429. app.listen(int(listen_port), str(listen_addr))
  430. except OSError as e:
  431. if e.errno == errno.EADDRINUSE:
  432. print("listen(): 'EADDRINUSE': " + str(e.args[1]))
  433. sys.exit(1)
  434. else:
  435. raise
  436. #await asyncio.gather(PingLoop(), return_exceptions=True)
  437. #await asyncio.gather(PingLoop())
  438. await asyncio.gather(FpingLoop())
  439. # ------ Div -------------------------------
  440. def create_html_table():
  441. html_tab = ""
  442. html_tab += '<div id="top_header" class="top_header w3-black">'
  443. html_tab += '<span class="w3-left tbars" style="text-align: left;">V'+VERSION+' by <a href="https://pss.zweiernet.ch" target="_blank">PSS</a><br><span style="font-size:1em;opacity:0.8;background-color:#4e4ec4;cursor:pointer;" onclick="document.getElementById(\'modal_01\').style.display=\'block\'">&nbsp;<span class="w3-text-white w3-monospace"><b>i</b></span> &#x2754; </span></span>'
  444. html_tab += '<span class="w3-center top_head_tit">PingPanel<span class="top_head_tit_pfix"> ' + config["Main"]["TitleAdd"] + '</span></span>'
  445. html_tab += '<span class="w3-right tbars"><span id="cur_actime" style="text-align: right;color: #22ff00;font-weight: bold;"> </span><br><button id="close_button" onclick="socket_close(1000)" class="sbutt">stop</button><br></span>'
  446. html_tab += '</div>\n'
  447. html_tab += '<div class="w3-container">'
  448. for sect in config.sections():
  449. if (sect == "Main"):
  450. continue
  451. html_tab += '<div class="w3-container" style="padding: 0;font-size:14px;">'
  452. sect_x = sect.replace(' ','_')
  453. clickId = 'accord_' + sect_x
  454. html_tab += '<br><div onclick="Accordion(\'' + clickId + '\')" class="w3-container w3-teal" style="padding: 3px 10px;margin-top: 5px;box-shadow: 0 2px 5px 0 #04040424,0 2px 10px 0 #040404c4;letter-spacing: 2px;cursor: pointer;text-shadow: 0 0 0px #fff;">' + sect + '<span id="ux_' + sect_x + '" class="w3-right"></span></div>\n'
  455. html_tab += '<div id="' + clickId + '" class="w3-show">'
  456. for key in config[sect]:
  457. tkey = key.replace('.', '_')
  458. html_tab += '<div class="w3-left si3-dark-grey w3-border w3-border-teal tooltip" style="text-align: center;margin: 1px; min-width: 13ch; padding: 4px min(3px, 1vw) !important;box-shadow:3px 2px 4px #000 !important;">'
  459. html_tab += '<span id="tbar_' + tkey + '" class="time-bar-wrapper"><span class="time-bar"></span></span>'
  460. html_tab += '<span class="w3-card-2 tooltiptext">'+config[sect][key]+'<br><span id="ttip_' + tkey + '" class="ttip_small"></span></span>'
  461. html_tab += '<span id="' + tkey + '" class="ip_num">' + key + '</span><br><span id="stat_' + tkey + '" class="w3-center"></span></div>'
  462. html_tab += '</div>\n</div>\n'
  463. html_tab += '</div>\n'
  464. return html_tab
  465. html_html = '''
  466. <!doctype html>
  467. <html>
  468. <header>
  469. <title>PingPanel %s</title>
  470. <meta name="viewport" content="width=device-width, initial-scale=1">
  471. <meta charset="UTF-8">
  472. <script type="text/javascript">
  473. window.onload = start_websocket();
  474. function start_websocket() {
  475. var ws = new WebSocket("%s://%s/websocket");
  476. ws.onmessage = function (evt) {
  477. //let test = evt.data.replace(/'/g, '"'); // needed " by JSON.parse
  478. //var json_arr = JSON.parse(test);
  479. var json_arr = JSON.parse(evt.data);
  480. var cur_actime = "";
  481. // Colortable counters initialisation
  482. let M_red = new Map();
  483. let M_green = new Map();
  484. let M_yellow = new Map();
  485. for( let i = 0; i < json_arr.length; i++ ) {
  486. if ( M_red.has(json_arr[i].sect) ) {
  487. continue;
  488. } else {
  489. M_red.set(json_arr[i].sect, 0);
  490. M_green.set(json_arr[i].sect, 0);
  491. M_yellow.set(json_arr[i].sect, 0);
  492. }
  493. }
  494. // DOM Updates
  495. for(let i = 0; i < json_arr.length; i++) {
  496. var data_obj = json_arr[i];
  497. cur_actime = data_obj.actime;
  498. var cur_host = data_obj.host;
  499. var cur_status = data_obj.status;
  500. var cur_sect_ux = data_obj.sect;
  501. var cur_rtt = data_obj.rtt;
  502. var cur_since = data_obj.since;
  503. var cur_timbar = data_obj.timbar;
  504. cur_rtt = cur_rtt.replace(/ /g,' \/ ');
  505. var uc_cur_host = cur_host.replace(/\./g,'_');
  506. document.getElementById(uc_cur_host).textContent = cur_host;
  507. var stat_id = 'stat_' + uc_cur_host;
  508. var ttip_id = 'ttip_' + uc_cur_host;
  509. var tbar_id = 'tbar_' + uc_cur_host;
  510. var tbarsel = document.getElementById(tbar_id).querySelector('.time-bar');
  511. if (cur_status == 'OK') {
  512. M_green.set(cur_sect_ux, M_green.get(cur_sect_ux) + 1);
  513. document.getElementById(stat_id).innerHTML = '<img src="/img/green_on.gif">';
  514. document.getElementById(ttip_id).innerHTML = '<b>RTT</b>: '+cur_rtt+'<br><span style="color:#0f0;">since </span>: '+cur_since;
  515. tbarsel.style.width = cur_timbar+'%%';
  516. tbarsel.style.background = '#0f0';
  517. } else if (cur_status == 'FAILED') {
  518. M_red.set(cur_sect_ux, M_red.get(cur_sect_ux) + 1);
  519. document.getElementById(stat_id).innerHTML = '<img src="/img/red_on.gif">';
  520. document.getElementById(ttip_id).innerHTML = '<b>RTT</b>: '+cur_rtt+'<br><span style="color:red;">since </span>: '+cur_since;
  521. tbarsel.style.width = cur_timbar+'%%';
  522. tbarsel.style.background = 'red';
  523. } else if (cur_status == 'NEWFAIL') {
  524. M_red.set(cur_sect_ux, M_red.get(cur_sect_ux) + 1);
  525. document.getElementById(stat_id).innerHTML = '<img src="/img/red_anim.gif">';
  526. document.getElementById(ttip_id).innerHTML = '<b>RTT</b>: '+cur_rtt+'<br><span style="color:red;">since </span>: '+cur_since;
  527. tbarsel.style.width = cur_timbar+'%%';
  528. tbarsel.style.background = 'red';
  529. } else {
  530. M_yellow.set(cur_sect_ux, M_yellow.get(cur_sect_ux) + 1);
  531. document.getElementById(stat_id).innerHTML = '<img src="/img/yellow_on.gif">';
  532. document.getElementById(ttip_id).innerHTML = '<b>RTT</b>: '+cur_rtt+'<br><span style="color:yellow;">since </span>: '+cur_since;
  533. tbarsel.style.width = cur_timbar+'%%';
  534. tbarsel.style.background = 'yellow';
  535. }
  536. } // End for
  537. document.getElementById('cur_actime').innerHTML = cur_actime;
  538. //document.querySelector('.time-bar').style.width = "20px";
  539. for (let [sect, val] of M_red) {
  540. let tmp_r = '<span class="unreach_r">';
  541. tmp_r += (M_red.get(sect) == 0) ? '<span class="red_r opaq_r">'+M_red.get(sect).toString().padStart(3, " ")+'</span> | '
  542. : '<span class="red_r">'+M_red.get(sect).toString().padStart(3, " ")+'</span> | ';
  543. tmp_r += (M_yellow.get(sect) == 0) ? '<span class="yellow_r opaq_r">'+M_yellow.get(sect).toString().padStart(3, " ")+'</span> | '
  544. : '<span class="yellow_r">'+M_yellow.get(sect).toString().padStart(3, " ")+'</span> | ';
  545. tmp_r += (M_green.get(sect) == 0) ? '<span class="green_r opaq_r">'+M_green.get(sect).toString().padStart(3, " ")+'</span>'
  546. : '<span class="green_r">'+M_green.get(sect).toString().padStart(3, " ")+'</span>';
  547. tmp_r += '</span>';
  548. document.getElementById(sect).innerHTML = tmp_r;
  549. }
  550. };
  551. ws.onclose = function(evt) {
  552. //alert("WebSocket closed.");
  553. document.getElementById('cur_actime').innerHTML = '<span style="color:red;">stopped</span>';
  554. document.getElementById('close_button').style.opacity = "0.3";
  555. //document.getElementById('modal_alert_text').style.display='block';
  556. //document.getElementById('modal_alert_text').innerHTML = 'WebSocket closed.';
  557. };
  558. ws.onerror = function(evt) {
  559. alert("WebSocket closed due to an error.");
  560. document.getElementById('cur_actime').innerHTML = '<span style="color:red;">Error</span>';
  561. document.getElementById('close_button').style.opacity = "0.3";
  562. };
  563. socket_close = (code) => {
  564. document.getElementById('close_button').style.opacity = "0.3";
  565. ws.close(code);
  566. };
  567. };
  568. function Accordion(id) {
  569. var x = document.getElementById(id);
  570. if (x.className.indexOf("w3-show") == -1) {
  571. x.className = "w3-show";
  572. } else {
  573. x.className = x.className.replace("w3-show", "w3-hide");
  574. }
  575. };
  576. </script>
  577. <script>
  578. // modal handling
  579. var modal = document.getElementById('modal_01');
  580. // When the user clicks anywhere outside of the modal, close it
  581. window.onclick = function(event) {
  582. if (event.target == modal) {
  583. modal.style.display = "none";
  584. }
  585. }
  586. </script>
  587. <link rel="stylesheet" href="/css/w3.css">
  588. <style>
  589. %s
  590. </style>
  591. </header>
  592. <body>
  593. <div id="main">%s</div>\n
  594. <p><br></p>
  595. <div id="modal_01" class="w3-modal modal_01" onclick="this.style.display='none'">
  596. <div class="w3-modal-content modal_01_text">
  597. <div class="w3-container">
  598. <h4 style="font-variant:small-caps;letter-spacing:3px;">PingPanel</h4>
  599. %s
  600. </div>
  601. </div>
  602. </div>
  603. </body>
  604. </html>
  605. '''
  606. html_css = '''
  607. body {
  608. background: #333;
  609. font-family: Verdana, Arial, sans-serif;
  610. color: #ddd;
  611. line-height: 110%;
  612. font-size: 13px;
  613. }
  614. .red { color: red; }
  615. .green { color: #0f0; }
  616. .yellow { color: yellow; }
  617. .red_r { color: red; white-space: pre; text-align: right; font-family: monospace; width: 2em; display: inline-block;}
  618. .green_r { color: #0f0; white-space: pre; text-align: right;; font-family: monospace; width: 2em; display: inline-block;}
  619. .yellow_r { color: yellow; white-space: pre; text-align: right;; font-family: monospace; width: 2em; display: inline-block;}
  620. .ip_num { font-size: 80%; }
  621. .opaq_r { opacity: 0.2; }
  622. .si3-dark-grey{color:#fff!important;background-color:#626262!important;text-shadow: 0 0 0px #fff, 0 0 1px #000;}
  623. .top_header {
  624. text-align: center;
  625. padding: 5px 10px; height: 43px;
  626. box-shadow: 0px 1px 9px 1px #c3d0cd78 !important;
  627. position: sticky;
  628. z-index: 100;
  629. top: 0px;
  630. }
  631. .tbars {
  632. color: #aaa;
  633. font-size: 11px;
  634. font-stretch: semi-expanded;
  635. }
  636. .unreach_r {
  637. background-color:#313131;
  638. padding-left:5px;
  639. padding-right:5px;
  640. letter-spacing: 0px;
  641. border-radius: 2px;
  642. font-weight: bold;
  643. font-size: 12px;
  644. }
  645. .modal_01 {
  646. }
  647. .modal_01_text {
  648. background-color: #000;
  649. color: #f0f0ca;
  650. line-height: 120%;
  651. font-size: 1.1em;
  652. }
  653. .sbutt {
  654. border: none;
  655. display: inline-block;
  656. vertical-align: middle;
  657. overflow: hidden;
  658. text-decoration: none;
  659. text-align: center;
  660. cursor: pointer;
  661. white-space: nowrap;
  662. border-radius: 4px;
  663. padding: 0px 8px !important;
  664. background-color: #9b9b9b !important;
  665. color: #000 !important;
  666. }
  667. .top_head_tit {
  668. font-size: 22px;
  669. font-variant: small-caps;
  670. letter-spacing: 4px;
  671. top: 0.3em;
  672. position: sticky;
  673. }
  674. .top_head_tit_pfix {
  675. font-size: 0.5em;
  676. font-variant: small-caps;
  677. letter-spacing: 0px;
  678. }
  679. .ttip_small {
  680. font-size: 64%;
  681. text-align: center;
  682. padding-top: 6px;
  683. }
  684. .tooltip {
  685. position: relative;
  686. display: inline-block;
  687. border-bottom: 1px dotted black;
  688. }
  689. .tooltip .tooltiptext {
  690. font-family: Verdana, 'PT Sans Caption', Arial, sans-serif;
  691. visibility: hidden;
  692. width: 170px;
  693. background-color: black;
  694. color: #fff;
  695. text-align: center;
  696. font-size: 17px;
  697. border-radius: 6px;
  698. padding: 5px 5px;
  699. position: absolute;
  700. z-index: 1;
  701. top: 120%;
  702. left: 50%;
  703. margin-left: -60px;
  704. line-height: 1.1em;
  705. text-shadow: 0 0 0 #a8a8a8 !important;
  706. }
  707. .tooltip .tooltiptext::after {
  708. content: "";
  709. position: absolute;
  710. bottom: 100%;
  711. left: 50%;
  712. margin-left: -5px;
  713. border-width: 5px;
  714. border-style: solid;
  715. border-color: transparent transparent black transparent;
  716. }
  717. .tooltip:hover .tooltiptext {
  718. visibility: visible;
  719. }
  720. .sticky {
  721. position: fixed;
  722. top: 0;
  723. width: 100%;
  724. }
  725. .sticky + .content {
  726. padding-top: 50px;
  727. }
  728. .time-bar-wrapper {
  729. width: 100%;
  730. height:2px;
  731. position:absolute;
  732. top:0;
  733. left:0;
  734. background-color: inherit;
  735. }
  736. .time-bar {
  737. width:0;
  738. height: inherit;
  739. background-color: yellow;
  740. display: block;
  741. }
  742. '''
  743. def create_html_modal01():
  744. html_modal = '''
  745. <p style="font-size:1.2em;font-variant:small-caps;letter-spacing:3px;font-style:italic;text-decoration:underline">Info</p>
  746. Config File:
  747. ''' + modal_konfigs + '''<br>
  748. Total number of Devices: _NUM_HOSTS_ <br>
  749. LoopInterval:
  750. ''' + str(loop_interval) + ''' s<br>
  751. FlashThreshold:
  752. ''' + str(config["Main"]["FlashThreshold"]) + ''' rounds<br>
  753. DurationBarSpan:
  754. ''' + str(bar_duration) + ''' seconds<br>
  755. PingForever:
  756. ''' + str(ping_forever) + ''' <br>
  757. fping:
  758. ''' + fping_parameter[2].replace('--','') + '''<br>
  759. fping:
  760. ''' + fping_parameter[3].replace('--','') + ''' ms<br>
  761. fping:
  762. ''' + fping_parameter[4].replace('--','') + ''' ms<br>
  763. fping:
  764. ''' + fping_parameter[5].replace('--','') + ''' bytes<br>
  765. <br>
  766. <p style="font-size:1.2em;font-variant:small-caps;letter-spacing:3px;font-style:italic;text-decoration:underline">Help</p>
  767. The PingPanel board provides the header and the configured, expandable and collapsible sections with the corresponding devices to be monitored.<br>
  768. Among other things, the header contains the current time (<span class="green">green</span>) of the last ping run
  769. or the status "stopped" (<span class="red">red</span>) if the connection to the server has been lost or the "Stop" button below has been pressed.<br>
  770. Pressing the "Stop" button terminates the connection to the server and, if no other client is active, the server pauses the ping rounds.<p>
  771. The blue-green <span class="w3-teal">section bars</span> contain the name of the section and consolidated information about the status of the devices in this section.<br>
  772. The section bars can be expanded and collapsed by clicking or tapping on them.<br>
  773. Consolidated status information <img src="/img/stat-inf.gif"> is divided into <span class="red">failed</span>,
  774. <span class="yellow">partially answered</span> and <span class="green">answered</span> ping requests.<br>
  775. Each monitored device displays its IP address and status. By hovering over or tapping on it its comment
  776. is displayed and the three ping RTT's of each ping round is reported.<p>
  777. A <span class="red">flashing red</span> status light indicates that the device has recently not responded during 'FlashThreshold' ping rounds.<br>
  778. A <span class="red">red</span> status light indicates that the device has not answered any of the three pings.<br>
  779. A <span class="yellow">yellow</span> status light indicates that the device has answered one of three pings.<br>
  780. A <span class="green">green</span> status light indicates that the device has answered to all three or at least two pings.<br>
  781. <p></p>
  782. <p> </p>
  783. '''
  784. html_modal = html_modal.replace('_NUM_HOSTS_', str(anz_hosts))
  785. return html_modal
  786. # -------- MAIN ------------------------------
  787. if __name__ == "__main__":
  788. print("PingPanel v"+VERSION+" by PSS -- started at " + datetime.now().strftime("%F %H:%M:%S"))
  789. # Commandline parsing
  790. parser = argparse.ArgumentParser(description='PingPanel V'+VERSION+"\n2024 by sigi",
  791. formatter_class=argparse.RawDescriptionHelpFormatter)
  792. parser.add_argument('-c', help="Alternative configuration file (standard: config.cfg)", type=str, metavar='config-file')
  793. parser.add_argument('-s', help="User sections file (standard: None)", type=str, metavar='sections-file')
  794. parser.add_argument('-v', help="Verbose mode", action="store_true")
  795. args = parser.parse_args()
  796. if args.c:
  797. konfig_file = args.c
  798. print("Configfile: " + konfig_file)
  799. modal_konfigs = konfig_file
  800. if args.s:
  801. sect_file = args.s
  802. print("Sectionsfile: " + sect_file)
  803. modal_konfigs = konfig_file + " + " + sect_file
  804. # Config
  805. read_config()
  806. if args.s and sect_file:
  807. read_sections_config()
  808. if ping_forever:
  809. print("Pinging Forever !")
  810. print("Pinging " + str(anz_hosts) + " Devices in total.")
  811. # create the app
  812. asyncio.run(main())
  813. # ------