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}")
# Adjust group_size to avoid division by zero or overly small groups
group_size = max(1, GROUP_SIZE)
# Adjust the grouping logic ensuring each host is assigned to at least one group
grouped_host_info = [host_info[i:i + group_size] for i in range(0, len(host_info), group_size)]
# Reorder the groups to prevent consecutive repeats of the last hostname
reordered_host_info = []
max_group_length = max(len(group) for group in grouped_host_info)
for i in range(max_group_length):
for group in grouped_host_info:
if i < len(group):
reordered_host_info.append(group[i])
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
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 = 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:
store_name = offline_dict[normalized_hostname]['store_name']
# Log the host coming online
log_online(
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)
# Play sound when host comes back online
# hostname_lower = hostname.lower()
# if any(fnmatch.fnmatch(hostname_lower, pattern.lower()) for pattern in settings_widget.sound_alert_patterns):
# if hasattr(main_window, 'sound_manager'):
# message = f"Big C {store_name} return to Online"
# audio_filename = f"{message}.mp3"
# audio_path = os.path.join('sounds', audio_filename)
# fallback_sound_file = "returnonline.mp3"
# if os.path.exists(audio_path):
# main_window.sound_manager.play(audio_path)
# else:
# print(f"Sound file '{audio_filename}' does not exist. Attempting to download...")
# downloaded_file = download_audio(message)
# if downloaded_file and os.path.exists(downloaded_file):
# audio_path = downloaded_file
# main_window.sound_manager.play(downloaded_file)
# else:
# if os.path.exists(fallback_sound_file):
# print(f"Failed to download. Playing fallback sound file: {fallback_sound_file}")
# main_window.sound_manager.play(fallback_sound_file)
# return
# else:
# print("Failed to download sound file and no fallback sound available.")
# return
# # If audio_path exists (either original or downloaded), play it
# 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)
else:
print(f"Hostname {normalized_hostname} was not in offline_dict")
# Emit the update signal to refresh the GUI
update_signal.emit()
# Schedule the deletion after 5 seconds
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 {}
app = QApplication(sys.argv)
tab_widget = QTabWidget()
# Main widget and layout setup
main_widget = QWidget()
main_layout = QVBoxLayout(main_widget)
# Top-right layout for host label
top_right_layout = QHBoxLayout()
host_label = QLabel()
host_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
host_label.setStyleSheet("font-size: 12pt; color: black; padding-right: 10px;")
top_right_layout.addStretch()
top_right_layout.addWidget(host_label)
# Bottom-right layout for clock label
bottom_right_layout = QHBoxLayout()
clock_label = QLabel()
clock_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
clock_label.setStyleSheet("font-size: 12pt;")
bottom_right_layout.addStretch()
bottom_right_layout.addWidget(clock_label)
# Layout for the center widget
center_layout = QVBoxLayout()
center_layout.addWidget(tab_widget)
# Create a duplicate overlay layout
overlay_layout = QVBoxLayout() # or QHBoxLayout() depending on your needs
overlay_layout.addLayout(top_right_layout)
overlay_layout.addLayout(center_layout)
# Add the overlay layout to the main layout
main_layout.addLayout(overlay_layout)
main_layout.addLayout(bottom_right_layout)
main_widget.setLayout(main_layout)
main_widget.setWindowTitle("Server Monitor - Alert")
main_widget.setGeometry(300, 300, 1100, 600)
def update_labels():
current_time = english_locale.toString(QTime.currentTime(), "hh:mm:ss")
current_date = english_locale.toString(QDate.currentDate(), "dd MMM yyyy")
total_hosts = len(host_info_dict)
offline_hosts = 0
offline_hosts_wan = 0
offline_hosts_serv = 0
for row in range(main_window.table_widget.rowCount()):
item = main_window.table_widget.item(row, 0) # Assuming the hostname is in the first column
if item is not None:
inspect_status = main_window.table_widget.item(row, 6).text() # Assuming the inspect status is in the 7th column
if inspect_status != 'Server up':
offline_hosts += 1
if inspect_status == 'WAN down':
offline_hosts_wan += 1
elif inspect_status == 'Server down':
offline_hosts_serv += 1
online_hosts = total_hosts - (offline_hosts_wan + offline_hosts_serv)
host_label.setText(f"Total: {total_hosts} Online: {online_hosts} Offline: {offline_hosts} [ Server: {offline_hosts_serv} Wan: {offline_hosts_wan} ]")
clock_label.setText(f"{current_date} - {current_time} ")
timer = QTimer()
timer.timeout.connect(update_labels)
timer.start(1000) # Update every 1000ms (1 second)
# Create tabs
main_window = OfflineHostMonitor(None, None, None, None)
tab_widget.addTab(main_window, "Monitor")
return_online_widget = ReturnOnlineWidget()
tab_widget.addTab(return_online_widget, "Return Online")
settings_widget = SettingsWidget(None, None, None, None, None, tab_widget, main_window)
tab_widget.addTab(settings_widget, "Settings")
main_window.settings_widget = settings_widget
# Show main widget
main_widget.show()
# File handling and threading setup
file_path = 'hostname.txt'
offline_state_file = 'offline_state.json'
if not os.path.exists(file_path):
QMessageBox.critical(None, "File Not Found", "The file 'hostname.txt' was not found. Exiting the application.")
sys.exit()
host_info_list, hostname_count = read_host_list(file_path)
print(f"Number of hostnames in file: {hostname_count}")
if not host_info_list:
sys.exit()
offline_dict = load_offline_state(offline_state_file)
host_info_dict = {hostname.upper(): (hostname, store_name, telephone, wan_a, wan_b) for hostname, store_name, telephone, wan_a, wan_b in host_info_list}
offline_dict = {hostname: details for hostname, details in offline_dict.items() if hostname in host_info_dict}
queue = Queue()
stop_event = threading.Event()
cpu_count = psutil.cpu_count(logical=True)
memory = psutil.virtual_memory()
available_memory_gb = memory.available / (1024 ** 3)
max_pings_based_on_memory = int(available_memory_gb / 0.1)
MAX_PINGS = min(MAX_PINGS, max_pings_based_on_memory)
semaphore = threading.Semaphore(MAX_PINGS)
main_window.queue = queue
main_window.offline_dict = offline_dict
main_window.stop_event = stop_event
main_window.semaphore = semaphore
settings_widget.queue = queue
settings_widget.offline_dict = offline_dict
settings_widget.stop_event = stop_event
settings_widget.semaphore = semaphore
settings_widget.host_info_list = host_info_list
return_online_signal = return_online_widget.dataUpdated
for hostname, (host, store_name, telephone, wan_a, wan_b) in host_info_dict.items():
threading.Thread(
target=monitor_host,
args=((host, store_name, telephone, wan_a, wan_b), queue, offline_dict, stop_event, semaphore, settings_widget.main_window),
daemon=True
).start()
threading.Thread(
target=update_offline_list,
args=(queue, offline_dict, stop_event, return_online_signal, settings_widget, main_window),
daemon=True
).start()
app.aboutToQuit.connect(lambda: save_offline_state(offline_state_file, offline_dict))
app.aboutToQuit.connect(main_window.stop_all_threads)
sys.exit(app.exec_())
if name == "main":
main()
#สร้าง class ในการตรวจสอบสอบไฟล์ hostname.txt ด้วย watchdog หากพบการเปลี่ยนแปลงให้ update list ที่เกี่ยวข้องและลบ gui hostname ที่ถูกลบหรือถูกละเว้น #
#หากพบการเปลี่ยนแปลงเฉพาะส่วน เช่น storename, telephone, wan_a, wan_b ให้ทำการ update list ด้วยเช่นกัน
#ปัญหาที่พบคือหลังจาก update ส่วนต่าง ๆ แล้ว รายการใน tab offline list ไม่ถูกลบออกไป
To address your requirements, we'll add a HostFileWatcher class using the watchdog library to monitor changes in the hostname.txt file. This class will detect additions, deletions, and modifications of host entries and appropriately update the internal host list and the GUI.
Additionally, we'll ensure that the offline_dict and the GUI's offline tab are updated correctly when hosts are removed or modified. Here's how you can implement this:
Step 1: Install watchdog (If Not Already Installed)
Ensure that the watchdog library is installed. You can install it using pip:
pip install watchdog
Step 2: Create the HostFileWatcher Class
This class will monitor the hostname.txt file for any changes and update the host list accordingly.
import threading
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class HostFileWatcher(FileSystemEventHandler):
def __init__(self, file_path, on_modified_callback):
super().__init__()
self.file_path = os.path.abspath(file_path)
self.on_modified_callback = on_modified_callback
self.observer = Observer()
self.start()
def start(self):
directory = os.path.dirname(self.file_path)
self.observer.schedule(self, directory, recursive=False)
self.observer.start()
print(f"Started watching {self.file_path} for changes.")
def stop(self):
self.observer.stop()
self.observer.join()
print(f"Stopped watching {self.file_path}.")
def on_modified(self, event):
if os.path.abspath(event.src_path) == self.file_path:
print(f"Detected modification in {self.file_path}.")
self.on_modified_callback()
Step 3: Integrate HostFileWatcher into Your Application
We'll integrate the HostFileWatcher into your main application. This integration involves:
Initializing the Watcher: Start watching the hostname.txt file.
Handling File Changes: When a change is detected, reload the host list, determine additions, deletions, and modifications, and update the GUI and monitoring threads accordingly.
Updating the Offline Dictionary: Remove hosts that no longer exist and update details for modified hosts.
Here's how you can modify your main function and related components to incorporate the HostFileWatcher:
# ... [Your existing imports] ...
# Add the HostFileWatcher class here (as defined above)
def main():
global MAX_PINGS, MAX_WORKERS
app = QApplication(sys.argv)
tab_widget = QTabWidget()
# Main widget and layout setup
main_widget = QWidget()
main_layout = QVBoxLayout(main_widget)
# Top-right layout for host label
top_right_layout = QHBoxLayout()
host_label = QLabel()
host_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
host_label.setStyleSheet("font-size: 12pt; color: black; padding-right: 10px;")
top_right_layout.addStretch()
top_right_layout.addWidget(host_label)
# Bottom-right layout for clock label
bottom_right_layout = QHBoxLayout()
clock_label = QLabel()
clock_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
clock_label.setStyleSheet("font-size: 12pt;")
bottom_right_layout.addStretch()
bottom_right_layout.addWidget(clock_label)
# Layout for the center widget
center_layout = QVBoxLayout()
center_layout.addWidget(tab_widget)
# Create a duplicate overlay layout
overlay_layout = QVBoxLayout() # or QHBoxLayout() depending on your needs
overlay_layout.addLayout(top_right_layout)
overlay_layout.addLayout(center_layout)
# Add the overlay layout to the main layout
main_layout.addLayout(overlay_layout)
main_layout.addLayout(bottom_right_layout)
main_widget.setLayout(main_layout)
main_widget.setWindowTitle("Server Monitor - Alert")
main_widget.setGeometry(300, 300, 1100, 600)
def update_labels():
current_time = english_locale.toString(QTime.currentTime(), "hh:mm:ss")
current_date = english_locale.toString(QDate.currentDate(), "dd MMM yyyy")
total_hosts = len(host_info_dict)
offline_hosts = 0
offline_hosts_wan = 0
offline_hosts_serv = 0
for row in range(main_window.table_widget.rowCount()):
item = main_window.table_widget.item(row, 0) # Assuming the hostname is in the first column
if item is not None:
inspect_status = main_window.table_widget.item(row, 6).text() # Assuming the inspect status is in the 7th column
if inspect_status != 'Server up':
offline_hosts += 1
if inspect_status == 'WAN down':
offline_hosts_wan += 1
elif inspect_status == 'Server down':
offline_hosts_serv += 1
online_hosts = total_hosts - (offline_hosts_wan + offline_hosts_serv)
host_label.setText(f"Total: {total_hosts} Online: {online_hosts} Offline: {offline_hosts} [ Server: {offline_hosts_serv} Wan: {offline_hosts_wan} ]")
clock_label.setText(f"{current_date} - {current_time} ")
# Timer to update labels every second
timer = QTimer()
timer.timeout.connect(update_labels)
timer.start(1000) # Update every 1000ms (1 second)
# Create tabs
main_window = OfflineHostMonitor(None, None, None, None)
tab_widget.addTab(main_window, "Monitor")
return_online_widget = ReturnOnlineWidget()
tab_widget.addTab(return_online_widget, "Return Online")
settings_widget = SettingsWidget(None, None, None, None, None, tab_widget, main_window)
tab_widget.addTab(settings_widget, "Settings")
main_window.settings_widget = settings_widget
# Show main widget
main_widget.show()
# File handling and threading setup
file_path = 'hostname.txt'
offline_state_file = 'offline_state.json'
if not os.path.exists(file_path):
QMessageBox.critical(None, "File Not Found", "The file 'hostname.txt' was not found. Exiting the application.")
sys.exit()
host_info_list, hostname_count = read_host_list(file_path)
print(f"Number of hostnames in file: {hostname_count}")
if not host_info_list:
sys.exit()
offline_dict = load_offline_state(offline_state_file)
host_info_dict = {hostname.upper(): (hostname, store_name, telephone, wan_a, wan_b) for hostname, store_name, telephone, wan_a, wan_b in host_info_list}
# Remove any hosts from offline_dict that no longer exist in host_info_dict
offline_dict = {hostname: details for hostname, details in offline_dict.items() if hostname in host_info_dict}
queue = Queue()
stop_event = threading.Event()
cpu_count = psutil.cpu_count(logical=True)
memory = psutil.virtual_memory()
available_memory_gb = memory.available / (1024 ** 3)
max_pings_based_on_memory = int(available_memory_gb / 0.1)
MAX_PINGS = min(MAX_PINGS, max_pings_based_on_memory)
semaphore = threading.Semaphore(MAX_PINGS)
main_window.queue = queue
main_window.offline_dict = offline_dict
main_window.stop_event = stop_event
main_window.semaphore = semaphore
settings_widget.queue = queue
settings_widget.offline_dict = offline_dict
settings_widget.stop_event = stop_event
settings_widget.semaphore = semaphore
settings_widget.host_info_list = host_info_list
return_online_signal = return_online_widget.dataUpdated
# Start monitoring threads for each host
monitoring_threads = {}
for host_info in host_info_list:
threading.Thread(
target=monitor_host,
args=(host_info, queue, offline_dict, stop_event, semaphore, settings_widget.main_window),
daemon=True
).start()
# Start the offline list updater thread
threading.Thread(
target=update_offline_list,
args=(queue, offline_dict, stop_event, return_online_signal, settings_widget, main_window),
daemon=True
).start()
# Initialize the HostFileWatcher
def on_hostfile_modified():
"""Callback when the hostname.txt file is modified."""
print("Reloading host list due to file change...")
new_host_info_list, new_hostname_count = read_host_list(file_path)
print(f"Number of hostnames after reload: {new_hostname_count}")
new_host_info_dict = {hostname.upper(): (hostname, store_name, telephone, wan_a, wan_b) for hostname, store_name, telephone, wan_a, wan_b in new_host_info_list}
# Determine additions and deletions
added_hosts = set(new_host_info_dict.keys()) - set(host_info_dict.keys())
removed_hosts = set(host_info_dict.keys()) - set(new_host_info_dict.keys())
modified_hosts = {hostname for hostname in new_host_info_dict.keys() & host_info_dict.keys()
if new_host_info_dict[hostname] != host_info_dict[hostname]}
# Handle removed hosts
for hostname in removed_hosts:
print(f"Removing host: {hostname}")
# Remove from offline_dict
if hostname in offline_dict:
del offline_dict[hostname]
# Emit signal to update GUI
return_online_signal.emit()
# Optionally, signal the monitoring thread to stop if you have a reference to it
# Handle added hosts
for hostname in added_hosts:
print(f"Adding new host: {hostname}")
host_info = new_host_info_dict[hostname]
host_info_list.append(host_info)
# Start a new monitoring thread for the added host
threading.Thread(
target=monitor_host,
args=(host_info, queue, offline_dict, stop_event, semaphore, settings_widget.main_window),
daemon=True
).start()
# Handle modified hosts
for hostname in modified_hosts:
print(f"Modifying host: {hostname}")
old_info = host_info_dict[hostname]
new_info = new_host_info_dict[hostname]
# Update host_info_list
index = host_info_list.index(old_info)
host_info_list[index] = new_info
# Update host_info_dict
host_info_dict[hostname] = new_info
# If needed, update any GUI elements related to the host
# Update the host_info_dict
host_info_dict.clear()
host_info_dict.update(new_host_info_dict)
hostfile_watcher = HostFileWatcher(file_path, on_hostfile_modified)
# Connect the watchdog to the application lifecycle
def on_app_exit():
hostfile_watcher.stop()
save_offline_state(offline_state_file, offline_dict)
main_window.stop_all_threads()
app.aboutToQuit.connect(on_app_exit)
sys.exit(app.exec_())
Step 4: Update read_host_list Function
Ensure that the read_host_list function returns necessary details and handles updates correctly.
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}")
# Adjust group_size to avoid division by zero or overly small groups
group_size = max(1, GROUP_SIZE)
# No need to reorder_host_info here as the watcher will handle updates
return host_info, hostname_count
Step 5: Modify the OfflineHostMonitor Class to Handle Host Removals
Ensure that when hosts are removed from offline_dict, they are also removed from the GUI's table.
Add a method to handle host removals:
class OfflineHostMonitor(QWidget):
# ... [existing code] ...
def remove_host_from_table(self, hostname):
"""Remove a host from the table based on its hostname."""
for row in range(self.table_widget.rowCount()):
item = self.table_widget.item(row, 1) # Hostname is in the second column (index 1)
if item and item.text().upper() == hostname.upper():
self.table_widget.removeRow(row)
print(f"Removed host '{hostname}' from the table.")
break
# Modify the refresh_table method to handle removals
def refresh_table(self):
# ... [existing code up to sorted_offline] ...
# Collect current hostnames in table
current_table_hostnames = set()
for row in range(self.table_widget.rowCount()):
item = self.table_widget.item(row, 1) # Hostname is in the second column
if item:
current_table_hostnames.add(item.text().upper())
# Hosts that need to be removed from the table
hosts_to_remove = current_table_hostnames - set(sorted_offline.keys())
for hostname in hosts_to_remove:
self.remove_host_from_table(hostname)
# Now, proceed to add/update rows for sorted_offline
for hostname, details in sorted_offline.items():
existing_row = None
for row in range(self.table_widget.rowCount()):
item = self.table_widget.item(row, 1) # Hostname is in the second column
if item and item.text().upper() == hostname.upper():
existing_row = row
break
duration_seconds = int(current_time - details['start_time'])
duration_minutes = duration_seconds / 60
hours, remainder = divmod(duration_seconds, 3600)
minutes, seconds = divmod(remainder, 60)
duration = f"{hours:02}:{minutes:02}:{seconds:02}"
comment = details.get('comment', '')
inspect_status = details.get('inspect_status', 'Unknown')
if existing_row is not None:
# Update existing row
self.table_widget.setItem(existing_row, 4, QTableWidgetItem(details['offline_time']))
self.table_widget.setItem(existing_row, 5, QTableWidgetItem(duration))
self.table_widget.setItem(existing_row, 6, QTableWidgetItem(inspect_status))
self.table_widget.setItem(existing_row, 7, QTableWidgetItem(comment))
else:
# Add new row
row = self.table_widget.rowCount()
self.table_widget.insertRow(row)
item_no = QTableWidgetItem(str(row + 1))
item_hostname = QTableWidgetItem(hostname)
item_store_name = QTableWidgetItem(details['store_name'])
item_telephone = QTableWidgetItem(details['telephone'])
item_offline_time = QTableWidgetItem(details['offline_time'])
item_duration = QTableWidgetItem(duration)
item_inspect = QTableWidgetItem(inspect_status)
item_comment = QTableWidgetItem(comment)
item_no.setTextAlignment(Qt.AlignCenter)
item_hostname.setTextAlignment(Qt.AlignCenter)
item_offline_time.setTextAlignment(Qt.AlignCenter)
item_duration.setTextAlignment(Qt.AlignCenter)
item_inspect.setTextAlignment(Qt.AlignCenter)
self.table_widget.setItem(row, 0, item_no)
self.table_widget.setItem(row, 1, item_hostname)
self.table_widget.setItem(row, 2, item_store_name)
self.table_widget.setItem(row, 3, item_telephone)
self.table_widget.setItem(row, 4, item_offline_time)
self.table_widget.setItem(row, 5, item_duration)
self.table_widget.setItem(row, 6, item_inspect)
self.table_widget.setItem(row, 7, item_comment)
# Additional UI updates (colors, alerts) can be added here as needed
self.adjust_row_heights()
# ... [rest of the OfflineHostMonitor class] ...
Step 6: Ensure Thread Safety and GUI Updates
Since the HostFileWatcher runs in a separate thread, ensure that any updates to the GUI are performed in the main thread. Use signals and slots to achieve this safely.
Modify the HostFileWatcher integration in the main function to use signals:
from PyQt5.QtCore import pyqtSignal, QObject
class HostUpdateSignals(QObject):
hosts_added = pyqtSignal(list) # List of host_info tuples
hosts_removed = pyqtSignal(list) # List of hostnames
hosts_modified = pyqtSignal(list) # List of host_info tuples
# ... [Inside main function] ...
# Initialize HostUpdateSignals
host_update_signals = HostUpdateSignals()
# Define slots to handle host additions, removals, and modifications
def handle_hosts_added(hosts):
for host_info in hosts:
hostname, store_name, telephone, wan_a, wan_b = host_info
host_info_list.append(host_info)
host_info_dict[hostname.upper()] = host_info
# 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()
return_online_signal.emit()
print(f"Added {len(hosts)} new hosts.")
def handle_hosts_removed(hostnames):
for hostname in hostnames:
# Remove from host_info_list
host_info = host_info_dict.get(hostname.upper())
if host_info:
host_info_list.remove(host_info)
del host_info_dict[hostname.upper()]
# Remove from offline_dict if present
if hostname.upper() in offline_dict:
del offline_dict[hostname.upper()]
# Remove from GUI
main_window.remove_host_from_table(hostname)
return_online_signal.emit()
print(f"Removed {len(hostnames)} hosts.")
def handle_hosts_modified(hosts):
for host_info in hosts:
hostname, store_name, telephone, wan_a, wan_b = host_info
if hostname.upper() in host_info_dict:
# Update host_info_list and host_info_dict
index = host_info_list.index(host_info_dict[hostname.upper()])
host_info_list[index] = host_info
host_info_dict[hostname.upper()] = host_info
# Update GUI if the host is offline
if hostname.upper() in offline_dict:
main_window.refresh_table()
return_online_signal.emit()
print(f"Modified {len(hosts)} hosts.")
# Connect signals to slots
host_update_signals.hosts_added.connect(handle_hosts_added)
host_update_signals.hosts_removed.connect(handle_hosts_removed)
host_update_signals.hosts_modified.connect(handle_hosts_modified)
# Modify the on_hostfile_modified callback to emit signals
def on_hostfile_modified():
"""Callback when the hostname.txt file is modified."""
print("Reloading host list due to file change...")
new_host_info_list, new_hostname_count = read_host_list(file_path)
print(f"Number of hostnames after reload: {new_hostname_count}")
new_host_info_dict = {hostname.upper(): (hostname, store_name, telephone, wan_a, wan_b) for hostname, store_name, telephone, wan_a, wan_b in new_host_info_list}
# Determine additions and deletions
existing_hostnames = set(host_info_dict.keys())
new_hostnames = set(new_host_info_dict.keys())
added_hosts = [new_host_info_dict[hostname] for hostname in new_hostnames - existing_hostnames]
removed_hosts = list(existing_hostnames - new_hostnames)
# Determine modified hosts (fields other than hostname)
modified_hosts = [new_host_info_dict[hostname] for hostname in new_hostnames & existing_hostnames
if new_host_info_dict[hostname] != host_info_dict[hostname]]
# Emit signals
if added_hosts:
host_update_signals.hosts_added.emit(added_hosts)
if removed_hosts:
host_update_signals.hosts_removed.emit(removed_hosts)
if modified_hosts:
host_update_signals.hosts_modified.emit(modified_hosts)
# Initialize HostFileWatcher with the updated callback
hostfile_watcher = HostFileWatcher(file_path, on_hostfile_modified)
# Connect the watchdog to the application lifecycle
def on_app_exit():
hostfile_watcher.stop()
save_offline_state(offline_state_file, offline_dict)
main_window.stop_all_threads()
app.aboutToQuit.connect(on_app_exit)
sys.exit(app.exec_())
Step 7: Testing the Implementation
Add a Host: Add a new host entry to hostname.txt and observe if the GUI updates by adding the new host and starting its monitoring thread.
Remove a Host: Remove a host entry from hostname.txt and verify that it gets removed from both the monitoring threads and the GUI's offline tab.
Modify a Host: Change details like store_name, telephone, wan_a, or wan_b for an existing host and ensure that the changes reflect in the GUI.
Step 8: Ensuring Offline Tab Updates Correctly
The issue where the offline tab does not remove hosts after updates can be attributed to the refresh_table method not handling removals correctly. The modifications made in Step 5 ensure that removed hosts are deleted from the table. Additionally, by using signals and handling additions, removals, and modifications appropriately, the synchronization between the host list and the GUI is maintained.
Complete Revised Code Snippet
For clarity, here's how the main parts integrate:
# ... [All your existing imports, including PyQt5, threading, watchdog, etc.] ...
# Define HostUpdateSignals and HostFileWatcher as shown above
def main():
# ... [All previous setup code] ...
# Initialize HostUpdateSignals
host_update_signals = HostUpdateSignals()
# Define slots to handle host additions, removals, and modifications
# ... [Define handle_hosts_added, handle_hosts_removed, handle_hosts_modified as above] ...
# Connect signals to slots
host_update_signals.hosts_added.connect(handle_hosts_added)
host_update_signals.hosts_removed.connect(handle_hosts_removed)
host_update_signals.hosts_modified.connect(handle_hosts_modified)
# Modify the on_hostfile_modified callback to emit signals
# ... [Define on_hostfile_modified as above] ...
# Initialize HostFileWatcher with the updated callback
hostfile_watcher = HostFileWatcher(file_path, on_hostfile_modified)
# Connect the watchdog to the application lifecycle
# ... [Define on_app_exit and connect] ...
# Start the application event loop
sys.exit(app.exec_())
if __name__ == "__main__":
main()
Additional Recommendations
Handle Monitoring Threads Gracefully: In the current implementation, monitoring threads are daemon threads, which means they will terminate when the main program exits. Ensure that any necessary cleanup is performed if you plan to have more control over these threads.
Error Handling: Enhance error handling within the HostFileWatcher and monitoring threads to handle unexpected scenarios gracefully.
Logging: Implement a logging system instead of using print statements for better traceability and debugging.
Optimization: Depending on the number of hosts, consider optimizing how you manage threads and connections to improve performance.
User Feedback: Provide visual feedback in the GUI when hosts are added, removed, or modified for better user experience.
By following the above steps, your application should now dynamically respond to changes in the hostname.txt file, ensuring that the GUI remains in sync with the underlying host list.