Update code to retry connection 10 times max

This commit is contained in:
sudacode 2024-08-22 03:33:16 -07:00
parent c959f35ad0
commit 87c8c5c786

View File

@ -11,6 +11,7 @@ MPV_SOCKET = os.getenv("MPV_SOCKET", "/tmp/mpvsocket")
HOST_NAME = os.getenv("HOST_NAME", "0.0.0.0") HOST_NAME = os.getenv("HOST_NAME", "0.0.0.0")
PORT_NUMBER = int(os.getenv("PORT_NUMBER", "8080")) PORT_NUMBER = int(os.getenv("PORT_NUMBER", "8080"))
SOCKET_RETRY_DELAY = 5 # Time in seconds between retries to connect to the socket SOCKET_RETRY_DELAY = 5 # Time in seconds between retries to connect to the socket
MAX_RETRIES = 10 # Maximum number of retries to connect to the socket
# Set up basic logging # Set up basic logging
logging.basicConfig( logging.basicConfig(
@ -19,29 +20,25 @@ logging.basicConfig(
def send_to_mpv(command): def send_to_mpv(command):
"""Send a command to the mpv socket, retrying if the socket is not available.""" """Send a command to the mpv socket, retrying up to MAX_RETRIES times if the socket is not available."""
while True: attempts = 0
while attempts < MAX_RETRIES:
try: try:
# Check if the socket exists
if not os.path.exists(MPV_SOCKET):
logging.warning(
f"Socket {MPV_SOCKET} not found, retrying in {SOCKET_RETRY_DELAY} seconds..."
)
time.sleep(SOCKET_RETRY_DELAY)
continue
# Send command to mpv socket
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client_socket: with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client_socket:
client_socket.connect(MPV_SOCKET) client_socket.connect(MPV_SOCKET)
client_socket.sendall(command.encode("utf-8")) client_socket.sendall(command.encode("utf-8"))
logging.info("Command sent to mpv successfully.") logging.info("Command sent to mpv successfully.")
return True return True
except socket.error as e: except socket.error as e:
attempts += 1
logging.error( logging.error(
f"Failed to connect to socket: {e}. Retrying in {SOCKET_RETRY_DELAY} seconds..." f"Failed to connect to socket (attempt {attempts}/{MAX_RETRIES}): {e}. Retrying in {SOCKET_RETRY_DELAY} seconds..."
) )
time.sleep(SOCKET_RETRY_DELAY) time.sleep(SOCKET_RETRY_DELAY)
logging.error(f"Exceeded maximum retries ({MAX_RETRIES}). Ignoring the request.")
return False
class MyHandler(BaseHTTPRequestHandler): class MyHandler(BaseHTTPRequestHandler):
def do_GET(self): def do_GET(self):
@ -50,10 +47,7 @@ class MyHandler(BaseHTTPRequestHandler):
video_url = query_components.get("url", [None])[0] video_url = query_components.get("url", [None])[0]
if video_url: if video_url:
# Decode the URL to handle any special characters video_url = urllib.parse.unquote(video_url) # Decode the URL
video_url = urllib.parse.unquote(video_url)
# Log the received URL
logging.info(f"Received URL: {video_url}") logging.info(f"Received URL: {video_url}")
# Create the command to send to mpv # Create the command to send to mpv
@ -67,9 +61,8 @@ class MyHandler(BaseHTTPRequestHandler):
else: else:
self.send_response(500) self.send_response(500)
self.end_headers() self.end_headers()
self.wfile.write(b"Failed to add URL to mpv queue") self.wfile.write(b"Failed to add URL to mpv queue after max retries")
else: else:
# Log the error
logging.error("Missing 'url' parameter") logging.error("Missing 'url' parameter")
self.send_response(400) self.send_response(400)
self.end_headers() self.end_headers()
@ -81,7 +74,6 @@ class MyHandler(BaseHTTPRequestHandler):
if __name__ == "__main__": if __name__ == "__main__":
# Log server start
logging.info(f"Starting server on {HOST_NAME}:{PORT_NUMBER}...") logging.info(f"Starting server on {HOST_NAME}:{PORT_NUMBER}...")
try: try:
@ -89,10 +81,9 @@ if __name__ == "__main__":
logging.info(f"Server running on port {PORT_NUMBER}...") logging.info(f"Server running on port {PORT_NUMBER}...")
httpd.serve_forever() httpd.serve_forever()
except Exception as e: except Exception as e:
# Log any exceptions that occur during server operation
logging.exception(f"Error occurred: {e}") logging.exception(f"Error occurred: {e}")
except KeyboardInterrupt: except KeyboardInterrupt:
# Log server shutdown
logging.info("Server is shutting down...") logging.info("Server is shutting down...")
httpd.server_close() httpd.server_close()
logging.info("Server stopped.") logging.info("Server stopped.")