import concurrent.futures import time import socket from queue import Queue from…
- User
import concurrent.futures import time import socket from queue import Queue from threading import Thread
class TcpCheck(Thread): def init(self, hostname, wan_a, wan_b, timeout): super().init() self.hostname = hostname self.wan_a = wan_a self.wan_b = wan_b self.timeout = timeout self.queue = Queue()
def run(self): try: with socket.create_connection((self.hostname, 80), timeout=self.timeout): self.queue.put(("Server up", True)) elif self.hostname.startswith("PTH2", "PTH3"): ip = socket.gethostbyname(self.hostname) wan_ip = '.'.join(ip.split('.')[:-1] + ['10']) try: with socket.create_connection((wan_ip, 23), timeout=self.timeout): self.queue.put(("Server down", False) except (socket.timeout, ConnectionRefusedError, OSError): self.queue.put(("WAN down", False) elif self.hostname.startswith(("PTH11", "PTH15")) or self.hostname.startswith(("169", "s")): for ip, port in [(self.wan_a, 23), (self.wan_b, 23)]: if ip: try: with socket.create_connection((ip, port), timeout=self.timeout): self.queue.put(("Server down", False) except (socket.timeout, ConnectionRefusedError, OSError): pass self.queue.put(("WAN down", False) else: self.queue.put(("Server down", False) except (socket.timeout, ConnectionRefusedError, OSError): self.queue.put(("Connection error", False)def tcp_socket(hostname, wan_a=None, wan_b=None, timeout=2, max_retries=5): global prev_ping_time n = QTime.currentTime().toString("hh:mm:ss") inspect_status = "" if hostname.startswith("169.254.163.169"): current_time = time.time() time_diff = current_time - prev_ping_time if prev_ping_time != 0 else 0 print(f"{n} Ping Checked (Diff previous ping: {time_diff:.2f}s)") prev_ping_time = current_time
# Check most common ports first for port in [80, 443, 22, 23, 3389]: try: if socket.create_connection((hostname, port), timeout=timeout): inspect_status = "Server up" #print(f"{n} Ping {hostname}") #if hostname.startswith("169"): print(f"{n} Ping PTH15067") return True, inspect_status except (socket.timeout, ConnectionRefusedError, OSError): continue # Try the next port # Second Checking if hostname.startswith(("PTH2", "PTH3")): ip = socket.gethostbyname(hostname) wan_ip = '.'.join(ip.split('.')[:-1] + ['10']) try: with socket.create_connection((wan_ip, 23), timeout=timeout): inspect_status = "Server down" return False, inspect_status except (socket.timeout, ConnectionRefusedError, OSError): inspect_status = "WAN down" return False, inspect_status elif hostname.startswith(("PTH11", "PTH15")) or hostname.startswith(("169", "s")): for ip, port in [(wan_a, 23), (wan_b, 23)]: if ip: try: with socket.create_connection((ip, port), timeout=timeout): inspect_status = "Server down" return False, inspect_status except (socket.timeout, ConnectionRefusedError, OSError): pass inspect_status = "WAN down" return False, inspect_status else: inspect_status = "Server down" return False, inspect_status with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor: check_queue = Queue() for _ in range(max_retries): executor.submit(TcpCheck(hostname, wan_a, wan_b, timeout).start()) while not check_queue.empty(): result, success = check_queue.get() if success: return result, "TcpCheck Finished" inspect_status = "TcpCheck Retries Exhausted" return False, inspect_statusอธิบายโดยละเอียด
- Assistant
This script is designed to perform TCP checks on a hostname to determine if it's accessible over common ports, specifically ports 80, 443, 22, 23, and 3389. It employs multithreading and concurrent futures to manage the workload efficiently. Let's break down the code to understand its functionality better:
Key Components and Logic:
1. Classes and Functions:
-
TcpCheckClass:- Inherits from
Thread. - Takes a hostname, two WAN IPs, a timeout period, and initializes a queue to store results.
- Implements a
runmethod to create a socket connection to the specified hostname on port 80 (HTTP). If the connection is successful, it puts a "Server up" message in the queue. - Contains logic to handle specific patterns in hostnames (e.g., "PTH2", "PTH3", "PTH11", "PTH15", "169", "s") to attempt further checks on WAN IP addresses using port 23 (Telnet), with messages indicating either server or WAN down if these connections fail.
- Inherits from
-
tcp_socketFunction:- Takes a hostname, two WAN IPs, a timeout, and a maximum number of retries.
- Attempts to connect to the hostname on common ports (80, 443, 22, 23, 3389). If any connection is successful, it returns immediately with "Server up".
- Implements a second layer of checks for specific hostname patterns, similar to
TcpCheck, to identify WAN vs. server issues. - Utilizes a
ThreadPoolExecutorto concurrently executeTcpCheckthreads up tomax_retriestimes, attempting redundant checks for cases where initial connections might be unreliable or temporarily down.
2. Network and Threading Components:
-
Sockets:
- Used to create TCP connections to the specified IP address and port.
- Utilizes exception handling to manage connection timeouts, refusals, or other socket errors, proceeding with the logic based on these outcomes.
-
Queue:- Used for inter-thread communication between
TcpCheckthreads and the main thread managing retries.
- Used for inter-thread communication between
-
Thread Management:
ThreadPoolExecutoris used to manage multipleTcpCheckinstances, allowing asynchronous execution.- Each
TcpCheckinstance is a thread that attempts a network connection and puts the result in a queue.
Potential Issues:
-
Syntax Errors:
- There are several syntax errors in the
TcpCheck.runmethod such as missing colons afterelifstatements and incorrect method signatures likestartswith. - Missing closing parentheses in
queue.put.
- There are several syntax errors in the
-
Logical Problems:
- Multiple conditions and error handling should be encapsulated better to ensure clean processing.
- The handling of WAN IPs and hostname checks appears to be redundant across both
TcpCheckandtcp_socket, leading to potential inefficiency.
-
Concurrency Handling:
- The check queue is not properly utilized in the
tcp_socketfunction; it initializescheck_queuebut does not use it.
- The check queue is not properly utilized in the
Suggestions for Improvement:
- Fix syntax errors and ensure all logical branches are correctly formed.
- Simplify and consolidate similar logic across
TcpCheckandtcp_socket. - Improve queue management to ensure results are retrieved and interpreted properly from thread executions.
- Test the code in a controlled environment since network operations can be unpredictable and host-dependent.
-