Created
February 25, 2021 12:30
-
-
Save artizirk/1d449e58fab530efd46681af998f99f0 to your computer and use it in GitHub Desktop.
a stupid watch dog
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
""" | |
run this to keep the watchdog happy | |
curl localhost:8080 | |
or from js | |
setInterval(function(){ fetch("localhost:8080"); }, 3000); | |
""" | |
from http.server import BaseHTTPRequestHandler, HTTPServer | |
import time | |
import threading | |
from subprocess import run | |
hostName = "localhost" | |
serverPort = 8080 | |
last_check = time.time() # Last time watchdog was poked | |
max_watchdog_time = 10 # How long to wait before running shell command | |
def watchdog_target(): | |
global last_check | |
print("watchdog thread is running") | |
while True: | |
if time.time() - last_check > max_watchdog_time: | |
print("Watchdog not happy, last poke was >{}s ago".format(max_watchdog_time)) | |
run("echo 'a command'", shell=True) | |
time.sleep(10) | |
time.sleep(1) | |
class MyServer(BaseHTTPRequestHandler): | |
def do_GET(self): | |
global last_check | |
last_check = time.time() | |
self.send_response(200) | |
self.send_header("Content-type", "text/plain") | |
self.send_header("Access-Control-Allow-Origin", "*") | |
self.end_headers() | |
self.wfile.write(bytes("Watchdog is happy!\n", "utf-8")) | |
if __name__ == "__main__": | |
webServer = HTTPServer((hostName, serverPort), MyServer) | |
print("Server started http://%s:%s" % (hostName, serverPort)) | |
watchdog_thread = threading.Thread(target=watchdog_target, daemon=True) | |
watchdog_thread.start() | |
try: | |
webServer.serve_forever() | |
except KeyboardInterrupt: | |
pass | |
webServer.server_close() | |
print("Server stopped.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment