544bf52764e44ae17a2ba3a2b6956cced0c8ec14
David Blume first commit.

David Blume authored 5 years ago

1) #!/usr/bin/python3
2) #
3) # Since this is meant to be run as a daemon, do not use #!/usr/bin/env python3,
4) # because the process name would then be python3, not based on __FILE__.
5) #
6) # [filename] -d 3 192.168.1.1 192.168.1.12 &
7) # disown [jobid]
8) import os
9) import sys
10) import subprocess
11) import time
12) from argparse import ArgumentParser
13) import threading
14) import queue
David Blume Add notifications for SIGTE...

David Blume authored 5 years ago

15) import signal
David Blume Add type hints.

David Blume authored 4 years ago

16) from typing import Dict, Optional
David Blume first commit.

David Blume authored 5 years ago

17) 
David Blume Serialize the reading and w...

David Blume authored 5 years ago

18) pinger_lock = threading.Lock()
19) 
David Blume first commit.

David Blume authored 5 years ago

20) 
David Blume Add type hints.

David Blume authored 4 years ago

21) def log_exit(sig: int, frame) -> None:
David Blume Rename a parameter instead...

David Blume authored 5 years ago

22)     _print_queue.put([f'{time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())} '
23)                       f'PID={os.getpid()} signal={signal.Signals(sig).name} Exiting.'])
David Blume Add notifications for SIGTE...

David Blume authored 5 years ago

24)     _print_queue.join()
25)     sys.exit(0)
26) 
27) 
David Blume Add type hints.

David Blume authored 4 years ago

28) def pinger(host: str) -> None:
David Blume first commit.

David Blume authored 5 years ago

29)     """Executes one ping, prints if there was a change, exits thread."""
30)     now = time.localtime()
31)     success = ping(host)
David Blume Serialize the reading and w...

David Blume authored 5 years ago

32)     with pinger_lock:
33)         # Access to _results needs to be serialized
34)         need_update = success != _results[host]
35)         if need_update:
36)             _results[host] = success
37)     if need_update:
David Blume first commit.

David Blume authored 5 years ago

38)         status = "UP" if success else "DOWN"
39)         _print_queue.put([f'{time.strftime("%Y-%m-%d %H:%M:%S", now)} {host} {status}'])
40) 
41) 
David Blume Add type hints.

David Blume authored 4 years ago

42) def ping(host: str) -> int:
David Blume first commit.

David Blume authored 5 years ago

43)     """Returns True if host (str) responds to a ping request."""
44)     return subprocess.call([*_ping_cmd, host], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) == 0
45) 
46) 
David Blume Add type hints.

David Blume authored 4 years ago

47) def print_manager() -> None:
David Blume first commit.

David Blume authored 5 years ago

48)     """ The only thread allowed to write output. """
49)     while True:
50)         job = _print_queue.get()
51)         for line in job:
52)             log(line)
53)         _print_queue.task_done()
54) 
55) 
David Blume Add type hints.

David Blume authored 4 years ago

56) def log(*args, **kwargs) -> None:
David Blume first commit.

David Blume authored 5 years ago

57)     """Opens the logfile, writes the log, and closes the logfile."""
58)     # I don't leave the log file open for writing because another process needs access too.
59)     with open(_logname, 'a') as fp:
David Blume Add type hints.

David Blume authored 4 years ago

60)         print(*args, **kwargs, file=fp)
David Blume first commit.

David Blume authored 5 years ago

61) 
62) 
63) if __name__ == '__main__':
64)     parser = ArgumentParser(description="Repeatedly ping sites. Ex: %(prog)s -d 3 192.168.1.1 192.168.1.12")
David Blume Add notifications for SIGTE...

David Blume authored 5 years ago

65)     parser.add_argument('-d', '--delay', type=float, default=3.0, help='Delay between pings')
David Blume first commit.

David Blume authored 5 years ago

66)     parser.add_argument('addresses', nargs='+', help='Addresses to ping')
67)     parser_args = parser.parse_args()
68) 
David Blume Add type hints.

David Blume authored 4 years ago

69)     _results: Dict[str, Optional[int]] = dict()
David Blume first commit.

David Blume authored 5 years ago

70)     for addr in parser_args.addresses:
71)         _results[addr] = None
72)     delay = parser_args.delay
73)     _logname = os.path.join(os.path.expanduser('~'), 'log', os.path.basename(sys.argv[0]).replace('py', 'txt'))
74) 
75)     # Choose the ping parameters appropriate for the platform
76)     if sys.platform == 'cygwin' or sys.platform == 'win32':
77)         _ping_cmd = ('ping', '-n', '1', '-w', '2000')
78)     else:
79)         _ping_cmd = ('ping', '-c', '1', '-W', '2', '-q')
80) 
81)     _print_queue = queue.Queue()
82)     t = threading.Thread(target=print_manager, daemon=True)
83)     t.start()
84)     del t
85) 
David Blume Add notifications for SIGTE...

David Blume authored 5 years ago

86)     signal.signal(signal.SIGINT, log_exit)
87)     signal.signal(signal.SIGTERM, log_exit)
88) 
David Blume first commit.

David Blume authored 5 years ago

89)     _print_queue.put([f'{time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}'
David Blume Add notifications for SIGTE...

David Blume authored 5 years ago

90)         f' PID={os.getpid()} repeat={delay}s addresses={",".join(parser_args.addresses)} Starting'])