def _play_sounds(self):
while True:
sound_file = self.sound_queue.get()
if sound_file is None:
break
with self.playing_lock:
try:
pygame.mixer.music.load(sound_file)
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
pygame.time.Clock().tick(10) # Wait until the sound finishes playing
except Exception as e:
print(f"Error playing sound {sound_file}: {e}")
self.sound_queue.task_done()
def play(self, sound_file):
self.sound_queue.put(sound_file)
def stop(self):
self.sound_queue.put(None)
self.thread.join()
pygame.quit()
class ReturnOnlineWidget(QWidget):
dataUpdated = pyqtSignal() # Define a signal to notify when data is updated
def __init__(self, parent=None):
super().__init__(parent)
self.initUI()
def set_font_size(self, font_size):
font = self.table_widget.font()
font.setPointSize(font_size)
self.table_widget.setFont(font)
header_font = self.table_widget.horizontalHeader().font()
header_font.setPointSize(font_size)
self.table_widget.horizontalHeader().setFont(header_font)
def initUI(self):
layout = QVBoxLayout(self)
# Create filter controls
self.start_date_edit = QDateEdit(self)
self.start_date_edit.setDate(QDate.currentDate())
self.start_date_edit.setCalendarPopup(True)
self.start_date_edit.setDisplayFormat("yyyy-MM-dd")
self.start_date_edit.dateChanged.connect(self.load_data)
self.start_date_edit.setFixedWidth(120) # Set fixed width
self.start_date_edit.setLocale(english_locale)
self.end_date_edit = QDateEdit(self)
self.end_date_edit.setDate(QDate.currentDate())
self.end_date_edit.setCalendarPopup(True)
self.end_date_edit.setDisplayFormat("yyyy-MM-dd")
self.end_date_edit.dateChanged.connect(self.load_data)
self.end_date_edit.setFixedWidth(120) # Set fixed width
self.end_date_edit.setLocale(english_locale)
self.status_filter = QComboBox(self)
self.status_filter.addItems(['All', 'WAN down', 'Server down'])
self.status_filter.currentTextChanged.connect(self.load_data)
self.duration_edit = QLineEdit(self)
self.duration_edit.setPlaceholderText(">= Minutes")
self.duration_edit.textChanged.connect(self.load_data)
self.duration_edit.setValidator(QIntValidator(0, 999999, self))
self.hostname_edit = QLineEdit(self)
self.hostname_edit.setPlaceholderText("Hostname (All)")
self.hostname_edit.textChanged.connect(self.load_data)
self.export_button = QPushButton("Export to CSV", self)
self.export_button.clicked.connect(self.export_to_csv)
self.export_button.setFixedWidth(120) # Set fixed width
# Layout for filter controls
filter_layout = QHBoxLayout()
filter_layout.addWidget(QLabel("Start Date:", self))
filter_layout.addWidget(self.start_date_edit)
filter_layout.addWidget(QLabel("End Date:", self))
filter_layout.addWidget(self.end_date_edit)
filter_layout.addWidget(QLabel("Status:", self))
filter_layout.addWidget(self.status_filter)
filter_layout.addWidget(QLabel("Duration:", self))
filter_layout.addWidget(self.duration_edit)
filter_layout.addWidget(QLabel("Hostname:", self))
filter_layout.addWidget(self.hostname_edit)
filter_layout.addWidget(self.export_button)
layout.addLayout(filter_layout)
# Status bar
self.status_bar = QStatusBar(self)
layout.addWidget(self.status_bar)
# Create the table widget
self.table_widget = QTableWidget(self)
self.table_widget.setEditTriggers(QAbstractItemView.NoEditTriggers)
# Set up table columns and headers
self.table_widget.setColumnCount(7)
self.table_widget.setHorizontalHeaderLabels(['Hostname', 'Storename', 'Start Offline', 'End Offline', 'Duration', 'Status', 'Comment'])
# Set resize modes for the table columns
header = self.table_widget.horizontalHeader()
#header.setSectionResizeMode(QHeaderView.ResizeToContents)
header.setStretchLastSection(True) # Makes the 'Comment' column stretch
# Optionally, adjust resize modes for specific columns
# header.setSectionResizeMode(0, QHeaderView.ResizeToContents) # 'Hostname'
# header.setSectionResizeMode(1, QHeaderView.ResizeToContents) # 'Storename'
# header.setSectionResizeMode(2, QHeaderView.Stretch) # 'Start Offline'
# header.setSectionResizeMode(3, QHeaderView.Stretch) # 'End Offline'
# header.setSectionResizeMode(4, QHeaderView.ResizeToContents) # 'Duration'
# header.setSectionResizeMode(5, QHeaderView.ResizeToContents) # 'Status'
# header.setSectionResizeMode(6, QHeaderView.Stretch) # 'Comment'
# Adjust fonts
font = QFont()
font.setPointSize(12)
self.table_widget.setFont(font)
header.setFont(font)
# Add table to layout
layout.addWidget(self.table_widget)
self.setLayout(layout)
# Connect data updated signal
self.dataUpdated.connect(self.load_data)
# Initial data load
self.load_data()
def convert_to_seconds(self, duration):
try:
if duration.isdigit():
return int(duration) * 60 # Convert minutes to seconds
parts = duration.split(':')
if len(parts) == 3:
hours, minutes, seconds = map(int, parts)
return hours * 3600 + minutes * 60 + seconds
elif len(parts) == 2: # Handle mm:ss format if needed
minutes, seconds = map(int, parts)
return minutes * 60 + seconds
elif len(parts) == 1: # Handle ss format if needed
return int(parts[0])
except ValueError:
return None
def load_data(self):
file_path = 'history_online.txt'
lock_path = 'history_online.lock'
temp_file_path = 'history_online_temp.txt'
lock = FileLock(lock_path)
def is_older_than_180_days(date_str):
date_format = "%Y-%m-%d"
try:
date_obj = datetime.strptime(date_str, date_format)
return date_obj < datetime.now() - timedelta(days=180)
except ValueError:
return True
try:
with lock.acquire(timeout=5): # Wait up to 5 seconds for the lock
if not os.path.exists(file_path):
return
with open(file_path, 'r', encoding='utf-8') as file:
lines = file.readlines()
lines_before_cleanup = len(lines)
lines_after_cleanup = 0
removed_dates = set()
with open(temp_file_path, 'w', encoding='utf-8') as temp_file:
for line in lines:
parts = line.strip().split('|')
if len(parts) >= 11:
end_offline_date_str = parts[6] # parts[6] is online_date in 'YYYY-MM-DD' format
if is_older_than_180_days(end_offline_date_str):
removed_dates.add(end_offline_date_str)
else:
temp_file.write(line)
lines_after_cleanup += 1
del lines # Remove reference to lines
if os.path.exists(temp_file_path):
try:
os.replace(temp_file_path, file_path)
except Exception as e:
print(f"Error during file replacement: {e}")
return
else:
print(f"Temporary file {temp_file_path} does not exist.")
return
# Retrieve user inputs for filtering
start_date = self.start_date_edit.date().toPyDate() # Returns a datetime.date object
end_date = self.end_date_edit.date().toPyDate() # Returns a datetime.date object
status_filter = self.status_filter.currentText()
hostname_filter = self.hostname_edit.text().strip().lower()
# Parse the duration filter
user_input_duration = self.duration_edit.text().strip()
if user_input_duration.isdigit():
duration_filter = self.convert_to_seconds(user_input_duration)
else:
duration_filter = None # If invalid, don't filter on duration
rows = []
with open(file_path, 'r', encoding='utf-8') as file:
for line in file:
parts = line.strip().split('|')
if len(parts) >= 11:
# Parse end_offline_date_str into a datetime.date object
try:
end_offline_date_str = parts[6] # online_date
end_offline_date = datetime.strptime(end_offline_date_str, '%Y-%m-%d').date()
except ValueError:
continue # Skip this line if date can't be parsed
# Check if the end_offline_date is within the selected date range
if start_date <= end_offline_date <= end_date:
# Apply status filter
if status_filter == 'All' or parts[9] == status_filter:
# Apply hostname filter
hostname = parts[2]
if hostname_filter == "" or hostname_filter.lower() in hostname.lower():
# Convert duration from the file to seconds for comparison
duration_str = parts[8]
duration = self.convert_to_seconds(duration_str)
if duration_filter is None or (duration is not None and duration >= duration_filter):
start_offline = f"{parts[4]} {parts[5]}" # start_date and start_time_str
end_offline = f"{parts[6]} {parts[7]}" # online_date and online_time_str
rows.append([hostname, parts[3], start_offline, end_offline, duration_str, parts[9], parts[10]])
rows.reverse() # To show latest entries first
# Set up table widget
self.table_widget.setRowCount(len(rows))
self.table_widget.setColumnCount(7)
self.table_widget.setHorizontalHeaderLabels(['Hostname', 'Storename', 'Start Offline', 'End Offline', 'Duration', 'Status', 'Comment'])
for row_idx, (hostname, storename, start_offline, end_offline, duration, status, comment) in enumerate(rows):
self.table_widget.setItem(row_idx, 0, QTableWidgetItem(hostname))
self.table_widget.setItem(row_idx, 1, QTableWidgetItem(storename))
self.table_widget.setItem(row_idx, 2, QTableWidgetItem(start_offline))
self.table_widget.setItem(row_idx, 3, QTableWidgetItem(end_offline))
self.table_widget.setItem(row_idx, 4, QTableWidgetItem(duration))
self.table_widget.setItem(row_idx, 5, QTableWidgetItem(status))
self.table_widget.setItem(row_idx, 6, QTableWidgetItem(comment))
self.table_widget.verticalHeader().setVisible(False)
# Update status bar
total_count = len(rows)
wan_down_count = sum(1 for row in rows if row[5] == 'WAN down')
server_down_count = sum(1 for row in rows if row[5] == 'Server down')
self.status_bar.showMessage(f"Total: {total_count} | WAN down: {wan_down_count} | Server down: {server_down_count}")
except Timeout:
print("Failed to acquire file lock")
except Exception as e:
print(f"An error occurred: {e}")
def resizeEvent(self, event):
super().resizeEvent(event)
table_width = self.table_widget.width()
scrollbar_width = 20
col_percentages = [0.13, 0.31, 0.20, 0.20, 0.10, 0.13, 0.13]
column_widths = [table_width * p for p in col_percentages]
total_column_width = sum(column_widths)
if total_column_width > table_width:
scale_factor = (table_width - scrollbar_width) / total_column_width
column_widths = [width * scale_factor for width in column_widths]
min_last_col_width = 40
column_widths[-1] = max(column_widths[-1], min_last_col_width)
for i, width in enumerate(column_widths):
self.table_widget.setColumnWidth(i, int(width))
#self.adjust_row_heights()
def adjust_row_heights(self):
num_rows = self.table_widget.rowCount()
self.table_widget.resizeRowsToContents()
for row in range(num_rows):
current_height = self.table_widget.rowHeight(row)
new_height = int(current_height * 1.1)
self.table_widget.setRowHeight(row, new_height)
def export_to_csv(self):
start_date_str = self.start_date_edit.date().toString("yyyy-MM-dd")
end_date_str = self.end_date_edit.date().toString("yyyy-MM-dd")
default_filename = f"history_online_{start_date_str}-{end_date_str}.csv"
file_path, _ = QFileDialog.getSaveFileName(self, "Save CSV File", default_filename, "CSV Files (*.csv)")
if not file_path:
return
if not file_path.endswith(".csv"):
file_path += ".csv"
lock_path = 'history_online.lock'
lock = FileLock(lock_path)
try:
with lock.acquire(timeout=10): # Wait up to 10 seconds for the lock
with open(file_path, 'w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow(['Hostname', 'Storename', 'Start Offline', 'End Offline', 'Duration', 'Status', 'Comment'])
for row_idx in range(self.table_widget.rowCount()):
row_data = [self.table_widget.item(row_idx, col_idx).text() for col_idx in range(self.table_widget.columnCount())]
writer.writerow(row_data)
print(f"Data exported to {file_path}")
except Timeout:
print("Failed to acquire file lock")
def read_host_list(file_path):
host_info = []
hostname_count = 0
try:
with open(file_path, 'r', encoding='utf-8-sig') as file:
for line in file:
line = line.strip()
if line:
normalized_line = line.upper()
if normalized_line.startswith("#"):
print(f"Skipping line: {line}")
continue
parts = line.split('|') # Change delimiter to |
if len(parts) > 5:
print(f"Warning: Line has too many parts, using only the first 5: {line}")
parts = parts[:5] # Truncate to the first 5 parts
parts = parts + [''] * (5 - len(parts))
hostname = parts[0]
store_name = parts[1]
telephone = parts[2]
wan_a = parts[3]
wan_b = parts[4]
host_info.append((hostname, store_name, telephone, wan_a, wan_b))
hostname_count += 1
except Exception as e:
print(f"Error reading file '{file_path}': {e}")
group_size = (hostname_count + 19) // GROUP_SIZE
grouped_host_info = [host_info[i:i + group_size] for i in range(0, hostname_count, group_size)]
# Reorder the groups to prevent consecutive repeats of the last hostname
host_info = []
for i in range(group_size):
for group in grouped_host_info:
if i < len(group):
host_info.append(group[i])
# Rotate the groups to prevent consecutive repeats
grouped_host_info = grouped_host_info[1:] + [grouped_host_info[0]]
#return reordered_host_info, hostname_count
return host_info, hostname_count
def count_hostnames(file_path):
try:
with open(file_path, 'r', encoding='utf-8') as file:
return sum(1 for line in file if line.strip())
except Exception as e:
print(f"Error reading file '{file_path}': {e}")
return 0
def tcp_socket(hostname, wan_a=None, wan_b=None, timeout=2):
n = QTime.currentTime().toString("hh:mm:ss")
inspect_status = ""
if hostname.startswith("PTH15067"): print(f"{n} Ping PTH15067")
# First Checking: Try port 80 and then port 8080
for port in [80, 8080, 22, 23, 3389]:
try:
with 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")):
try:
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
except (socket.gaierror, 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
#print(f"Second checking result for {hostname}: {inspect_status}")
return False, inspect_status
else:
#print(f"No specific prefix match for {hostname}, setting status as Server down")
inspect_status = "Server down"
return False, inspect_status
def get_google_translate_tts_url(text, lang='th'):
"""Get the URL for Google Translate TTS."""
url = 'https://translate.google.com/translate_tts'
params = {
'ie': 'UTF-8',
'q': text,
'tl': lang,
'client': 'gtx'
}
return url, params
def download_audio(text, lang='th'):
try:
url, params = get_google_translate_tts_url(text, lang)
response = requests.get(url, params=params, headers={'User-Agent': 'Mozilla/5.0'})
response.raise_for_status()
sounds_folder = 'sounds'
if not os.path.exists(sounds_folder):
os.mkdir(sounds_folder)
audio_filename = f'{text}.mp3'
audio_path = os.path.join(sounds_folder, audio_filename)
with open(audio_path, 'wb') as audio_file:
audio_file.write(response.content)
print(f"Audio saved to {audio_path}")
return audio_path
except requests.RequestException as e:
print(f"Failed to download audio: {e}")
return None
offline_dict_lock = threading.Lock()
def schedule_host_deletion(hostname, offline_dict, update_signal, settings_widget, lock, main_window):
def delete_host():
normalized_hostname = hostname.upper()
with lock:
if normalized_hostname in offline_dict:
# Log the host coming online
log_online(
hostname,
offline_dict[normalized_hostname]['store_name'],
offline_dict,
normalized_hostname,
offline_dict[normalized_hostname]['inspect_status']
)
# Remove the host from the offline_dict
del offline_dict[normalized_hostname]
# Save the offline state
save_offline_state('offline_state.json', offline_dict)
# Remove from exception hosts if necessary
if normalized_hostname in settings_widget.exception_hosts:
settings_widget.exception_hosts.remove(normalized_hostname)
settings_widget.update_exception_hosts_signal.emit(settings_widget.exception_hosts)
# Emit the update signal to refresh the GUI
update_signal.emit()
# Schedule the deletion after 1 second
timer = threading.Timer(5.0, delete_host)
timer.start()
def update_offline_list(queue, offline_dict, stop_event, update_signal, settings_widget, main_window):
if stop_event is None:
print("Stop event is None")
return
while not stop_event.is_set():
try:
hostname, store_name, telephone, is_online, inspect_status = queue.get(timeout=1)
normalized_hostname = hostname.upper()
if is_online:
if normalized_hostname in offline_dict:
# Schedule the deletion after 1 second without blocking the loop
schedule_host_deletion(hostname, offline_dict, update_signal, settings_widget, offline_dict_lock, main_window)
elif not is_online and normalized_hostname not in offline_dict:
with offline_dict_lock:
offline_dict[normalized_hostname] = {
'store_name': store_name,
'telephone': telephone,
'start_time': time.time(),
'offline_time': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()),
'last_alert_time': 0,
'inspect_status': inspect_status
}
update_signal.emit()
queue.task_done()
except Empty:
time.sleep(1)
except Exception as e:
print(f"Error in update_offline_list: {e}")
def monitor_host(host_info, queue, offline_dict, stop_event, semaphore, main_window):
global previous_status
previous_status = {}
hostname, store_name, telephone, wan_a, wan_b = host_info
normalized_hostname = hostname.upper()
while not stop_event.is_set():
with semaphore:
is_online, inspect_status = tcp_socket(hostname, wan_a, wan_b)
if main_window is not None and hasattr(main_window, 'update_inspect_status'):
main_window.update_inspect_status.emit(hostname, inspect_status)
#main_window.update_inspect_status.emit(hostname, inspect_status)
if not is_online:
if normalized_hostname not in offline_dict:
offline_dict[normalized_hostname] = {
'store_name': store_name,
'telephone': telephone,
'start_time': time.time(),
'offline_time': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()),
'last_alert_time': 0,
'inspect_status': inspect_status
}
else:
offline_dict[normalized_hostname]['inspect_status'] = inspect_status
previous_status[normalized_hostname] = inspect_status # store previous status
else:
if normalized_hostname in offline_dict:
offline_dict[normalized_hostname]['inspect_status'] = inspect_status
queue.put((hostname, store_name, telephone, is_online, inspect_status))
time.sleep(5)
file_lock = threading.Lock()
previous_status = {}
def log_online(hostname, store_name, offline_dict, normalized_hostname, inspect_status):
global previous_status
start_time = offline_dict[normalized_hostname]['start_time']
online_time = time.time()
offline_duration = online_time - start_time
duration_time = time.strftime('%H:%M:%S', time.gmtime(offline_duration))
start_date = time.strftime('%Y-%m-%d', time.localtime(start_time))
start_time_str = time.strftime('%H:%M:%S', time.localtime(start_time))
online_date = time.strftime('%Y-%m-%d', time.localtime(online_time))
online_time_str = time.strftime('%H:%M:%S', time.localtime(online_time))
previous_status_str = previous_status.get(normalized_hostname, "Server down") # get previous status
comment = offline_dict[normalized_hostname].get('comment', '')
if offline_duration > LOG_NORMAL: # only write to file if offline duration is over 1 minute
with open('history_online.txt', 'a', encoding='utf-8') as file:
file.write(f"{online_date}|{online_time_str}|{hostname}|{store_name}|{start_date}|{start_time_str}|{online_date}|{online_time_str}|{duration_time}|{previous_status_str}|{comment}\n")
save_lock = threading.Lock()
def save_offline_state(file_path, offline_dict):
temp_file_path = file_path + '.tmp'
with save_lock:
try:
with open(temp_file_path, 'w', encoding='utf-8') as temp_file:
json.dump(offline_dict, temp_file, ensure_ascii=False, indent=4)
os.replace(temp_file_path, file_path)
#print(f"Offline state saved to '{file_path}'")
except Exception as e:
#print(f"Error saving offline state to '{file_path}': {e}")
if os.path.exists(temp_file_path):
os.remove(temp_file_path)
def load_offline_state(file_path):
current_time = time.time()
if os.path.exists(file_path):
try:
with open(file_path, 'r', encoding='utf-8') as file:
offline_dict = json.load(file)
offline_dict = {hostname.upper(): details for hostname, details in offline_dict.items()}
for details in offline_dict.values():
details['last_alert_time'] = current_time
print(f"Offline state loaded from '{file_path}'")
return offline_dict
except Exception as e:
print(f"Error loading offline state from '{file_path}': {e}")
return {}
else:
print(f"File '{file_path}' does not exist.")
return {}
def monitor_hostname_file(file_path, host_info_list, host_info_dict, queue, offline_dict, stop_event, semaphore, settings_widget, main_window):
last_modified_time = os.path.getmtime(file_path)
while not stop_event.is_set():
time.sleep(5) # Check every 5 seconds (adjust as needed)
try:
current_modified_time = os.path.getmtime(file_path)
if current_modified_time != last_modified_time:
print("hostname.txt has changed. Updating host list...")
last_modified_time = current_modified_time
# Re-read the host list
new_host_info_list, _ = read_host_list(file_path)
update_host_list(new_host_info_list, host_info_list, host_info_dict, queue, offline_dict, stop_event, semaphore, settings_widget, main_window)
except Exception as e:
print(f"Error monitoring hostname.txt: {e}")
def update_host_list(new_host_info_list, host_info_list, host_info_dict, queue, offline_dict, stop_event, semaphore, settings_widget, main_window):
# Convert host lists to dictionaries for easy comparison
global offline_dict_lock
new_host_info_dict = {hostname.upper(): info for (hostname, *info) in new_host_info_list}
existing_hostnames = set(host_info_dict.keys())
new_hostnames = set(new_host_info_dict.keys())
# Hosts to remove
hosts_to_remove = existing_hostnames - new_hostnames
# Hosts to add
hosts_to_add = new_hostnames - existing_hostnames
# Hosts to update (if needed)
hosts_to_update = existing_hostnames & new_hostnames
with offline_dict_lock:
for hostname in hosts_to_remove:
# Remove from host_info_dict
del host_info_dict[hostname]
# Remove from offline_dict if present
if hostname in offline_dict:
del offline_dict[hostname]
print(f"Hosts to remove: {hosts_to_remove}")
print(f"Hosts to add: {hosts_to_add}")
# Remove hosts that are no longer in hostname.txt
for hostname in hosts_to_remove:
# Stop monitoring thread (you may need to implement thread management to stop threads gracefully)
# Remove from host_info_dict
del host_info_dict[hostname]
# Remove from offline_dict if present
if hostname in offline_dict:
del offline_dict[hostname]
# Optionally, update GUI or logs to reflect the removal
# Add new hosts to monitor
for hostname in hosts_to_add:
info = new_host_info_dict[hostname]
host_info = (hostname,) + tuple(info)
host_info_list.append(host_info)
host_info_dict[hostname] = host_info[1:]
# Start monitoring thread for the new host
threading.Thread(
target=monitor_host,
args=(host_info, queue, offline_dict, stop_event, semaphore, settings_widget.main_window),
daemon=True
).start()
# Update existing hosts if their information has changed (optional)
# For simplicity, this example assumes that hosts with the same hostname have the same information
# Update the original host_info_list
# Remove old hosts
host_info_list[:] = [host_info for host_info in host_info_list if host_info[0].upper() in new_hostnames]
# Add new hosts
for hostname in hosts_to_add:
host_info = (hostname,) + tuple(new_host_info_dict[hostname])
host_info_list.append(host_info)
main_window.update_signal.emit()
- save offline state ป้องกันการ damage จากการเขียนไฟล์หรือโปรแกรมขัดข้องด้วยการสร้าง temp
Your application is a comprehensive server monitoring tool built using PyQt5, threading, and various other Python libraries. It incorporates features such as real-time monitoring, alerting (both pop-up and sound-based), settings management, and historical data tracking. Below is a detailed analysis of your code, highlighting potential issues, suggestions for improvements, and best practices to enhance the overall functionality, maintainability, and performance of your application.
The application is monolithic, containing multiple classes and functions within a single script.
There are several interconnected components such as SettingsWidget, OfflineHostMonitor, ReturnOnlineWidget, and SoundManager.
Global variables are used extensively, which can lead to code that is harder to maintain and debug.
Suggestions:
Modularization: Break down the code into multiple modules or files. For example:
gui.py for all GUI-related classes.
monitoring.py for host monitoring logic.
alerts.py for alerting mechanisms.
utils.py for utility functions like safe_eval, file operations, etc.
This separation enhances readability and maintainability.
Use of Packages: Organize related modules into packages. For instance, a modules package containing sub-packages like gui, monitoring, alerts, etc.
Avoid Global Variables: Encapsulate configurations and state within classes or use configuration objects to pass necessary data between components. This reduces dependencies and side effects.
2. Threading and Concurrency
Observations:
Multiple threads are spawned for monitoring hosts, updating the offline list, and handling file changes.
Shared resources like offline_dict are accessed by multiple threads without sufficient synchronization, relying on locks like offline_dict_lock.
The SoundManager uses a queue and a dedicated thread to play sounds, which is a good approach.
Issues:
Potential Race Conditions: Although locks are used, ensuring every access to shared resources is properly synchronized is crucial.
Thread Management: Threads are started as daemon threads, which will terminate when the main program exits. However, graceful shutdown procedures might be necessary to ensure data integrity.
Suggestions:
Use Thread Pools: Instead of manually managing threads, consider using concurrent.futures.ThreadPoolExecutor. It simplifies thread management and can handle scaling better.
from concurrent.futures import ThreadPoolExecutor
executor = ThreadPoolExecutor(max_workers=MAX_WORKERS)
executor.submit(monitor_host, args...)
Event-Driven Concurrency: Utilize PyQt's QThread or QtConcurrent for better integration with the GUI event loop.
Graceful Shutdown: Implement mechanisms to ensure all threads complete their tasks before the application exits. This can involve setting events and joining threads appropriately.
Avoid Blocking Calls: Ensure that long-running operations do not block the main thread, preserving GUI responsiveness.
3. GUI Responsiveness and Design
Observations:
The application uses PyQt5's QTimer to update labels and refresh the GUI periodically.
Signals and slots are used for inter-component communication, which is appropriate for PyQt applications.
Long-running operations are offloaded to separate threads to keep the GUI responsive.
Issues:
Manual Thread Management: Combining PyQt's event-driven programming with manual threading can lead to complexity and potential issues.
Suggestions:
Leverage PyQt's Threading Capabilities: Use QThread and pyqtSignal to handle threading in a way that is more integrated with the PyQt event system.
from PyQt5.QtCore import QThread, pyqtSignal
class WorkerThread(QThread):
result_ready = pyqtSignal(object)
def run(self):
# Long-running task
result = perform_task()
self.result_ready.emit(result)
Use MVC Pattern: Implement the Model-View-Controller (MVC) or Model-View-ViewModel (MVVM) patterns to separate data handling from the GUI, enhancing testability and maintainability.
Optimize UI Updates: Ensure that the GUI updates (like refresh_table) are optimized to handle large datasets without significant lag. Virtualizing table views or implementing pagination can help.
4. Error Handling and Logging
Observations:
print statements are used extensively for debugging and logging purposes.
Some operations have basic try-except blocks but might not log errors comprehensively.
Issues:
Lack of Comprehensive Logging: Relying on print statements can make it harder to trace and debug issues, especially in production environments.
Unhandled Exceptions: Some potential exceptions might not be caught, leading to application crashes.
Suggestions:
Implement a Logging System: Use Python's built-in logging module to provide configurable and scalable logging.
Consistent Error Handling: Ensure that all possible exceptions are caught and handled appropriately. Provide user-friendly error messages and log the technical details for developers.
Use Specific Exceptions: Instead of using broad except Exception as e, catch specific exceptions to handle different error scenarios more effectively.
5. Code Quality and Best Practices
Observations:
The code is functional but can be improved in terms of readability and adherence to Python best practices.
Variable naming is mostly clear, but some inconsistencies exist.
Suggestions:
PEP 8 Compliance: Follow PEP 8 guidelines for Python code style to enhance readability.
Use snake_case for variables and functions.
Use CamelCase for classes.
Limit line lengths to 79 characters.
Tools like flake8, pylint, or integrated development environments (IDEs) like PyCharm can help enforce these standards.
Docstrings and Comments: Provide docstrings for modules, classes, and functions to describe their purpose and usage.
class SoundManager:
"""Manages the playback of sound alerts using pygame."""
def __init__(self):
"""Initializes the SoundManager and starts the playback thread."""
...
Removing Dead Code: There are commented-out sections (e.g., alternative implementations of tcp_socket) that should be removed or properly documented if they serve a purpose.
Consistent Naming: Ensure that variable and function names consistently use the same casing and are descriptive.
Avoid Hardcoding Paths: Use configurable paths or environment variables for file locations like 'hostname.txt', 'history_online.txt', and the sounds directory.
6. Performance Considerations
Observations:
The application creates multiple threads, which can lead to high resource consumption if not managed properly.
Limit Thread Count: Use a thread pool to limit the number of concurrent threads, avoiding excessive resource usage.
Efficient File Handling:
Batch Operations: Instead of reading and writing files frequently, consider batching updates or using a database for better performance and scalability.
Asynchronous I/O: Utilize asynchronous file operations to prevent blocking threads.
Optimize GUI Updates: Minimize the frequency and scope of GUI refreshes. For instance, only update parts of the table that have changed rather than refreshing the entire table every second.
7. Security Considerations
Observations:
The application evaluates user inputs in the settings using safe_eval, which is a good practice.
There are functionalities that download audio from external sources (Google Translate TTS), which could introduce security risks.
Issues:
External Downloads: Downloading audio files from external sources without validation can expose the application to malicious content.
Suggestions:
Validate Downloads: Ensure that downloaded content is safe and verified before use. Consider implementing checksum verification or restricting downloads to trusted sources.
Secure Communication: If the application communicates with remote servers, ensure that the communication channels are secure (e.g., using HTTPS).
Input Sanitization: Continue using safe_eval and ensure that all user inputs are properly sanitized to prevent injection attacks or unintended behavior.
8. Suggestions for Enhancements
Feature Enhancements:
User Authentication: Implement user authentication for accessing settings or sensitive information, enhancing security.
Notifications: Integrate system notifications or email alerts for better alerting mechanisms beyond pop-ups and sounds.
Dashboard Metrics: Provide more detailed metrics and visualizations (e.g., charts showing uptime/downtime trends).
Configuration Profiles: Allow users to create and switch between different monitoring profiles or configurations.
Internationalization: Support multiple languages beyond English and Thai, making the application more versatile.
Code Enhancements:
Dependency Management: Use a requirements.txt or Pipfile to manage dependencies, facilitating easier deployment and installation.
Packaging: Consider packaging the application using tools like PyInstaller to distribute it as a standalone executable.
Unit Testing: Implement unit tests for critical components to ensure reliability and catch regressions during future changes.
Conclusion
Your application demonstrates a solid foundation for a server monitoring tool with real-time capabilities and a user-friendly interface. By addressing the suggestions outlined above, you can enhance its robustness, performance, security, and maintainability. Adopting best practices in coding, error handling, and modularization will not only improve the current functionality but also make future developments and feature additions more manageable.
If you have specific questions or encounter particular issues within your code, feel free to provide more details, and I can offer targeted assistance.