From e079cd1d4008c8088fcd31a4acb64a45ff57307b Mon Sep 17 00:00:00 2001 From: GandC Snow Date: Wed, 8 Dec 2021 00:29:49 +0300 Subject: [PATCH] improvement --- irc_monitor.py | 42 +++++++++++++++++++++++------------------- 1 file changed, 23 insertions(+), 19 deletions(-) diff --git a/irc_monitor.py b/irc_monitor.py index 422887a..33af23e 100644 --- a/irc_monitor.py +++ b/irc_monitor.py @@ -16,13 +16,6 @@ config['Global'] = {'check_delay': '5 * 60', # every 5 min config.read('monitor.conf') -def check(host, port): - s = socket() - s.settimeout(1) - for _ in range(int(config['Global']['attempts'])): - if not s.connect_ex((host, int(port))): return True - sleep(int(config['Global']['attempts_delay'])) - return False def on_connect(connection, event): connection.mode(config['Global']['IRC_bot_nickname'], '+B') @@ -31,9 +24,29 @@ def on_connect(connection, event): def on_join(connection, event): connection.privmsg(config['Global']['IRC_chat_name'], 'Bot started') - def on_disconnect(connection, event): - exit() + exit(1) + + +def check_port(host, port): + s = socket() + s.settimeout(1) + for _ in range(int(config['Global']['attempts'])): + if not s.connect_ex((host, int(port))): return True + sleep(int(config['Global']['attempts_delay'])) + return False + +def check_service(host, services): + for service_name, service_port in services.items(): + result = check_port(host, service_port) + if connection_states[host][service_name] != result: + if result: + irc.privmsg(config['Global']['IRC_chat_name'], '{} on {} is up' + .format(service_name, host)) + else: + irc.privmsg(config['Global']['IRC_chat_name'], '{}:{} on {} is down!' + .format(config['Global']['IRC_admin_nickname'], service_name, host)) + connection_states[host][service_name] = result ## reactor = client.Reactor() irc = reactor.server() @@ -59,16 +72,7 @@ try: #print('Checking') for host, services in hosts.items(): if host == 'Global': continue - for service_name, service_port in services.items(): - result = check(host, service_port) - if connection_states[host][service_name] != result: - if result: - irc.privmsg(config['Global']['IRC_chat_name'], '{} on {} is up' - .format(service_name, host)) - else: - irc.privmsg(config['Global']['IRC_chat_name'], '{}:{} on {} is down!' - .format(config['Global']['IRC_admin_nickname'], service_name, host)) - connection_states[host][service_name] = result + Thread(target=check_service, args=(host, services)).start() last_check = time() reactor.process_once(timeout=1) except KeyboardInterrupt: