To implement the keep_online_host functionality as you've described, we'll enhance your existing code to ensure that hosts marked in keep_online_host remain displayed in the offline list until they stay online for more than TIME_BEFORE_ONLINE seconds. This helps prevent transient network glitches from rapidly toggling host statuses between online and offline.
Here's a comprehensive guide along with the necessary code modifications to achieve this:
Overview of Changes
-
Define keep_online_host: Introduce a new data structure to keep track of hosts that have recently come back online but should still be displayed as offline until TIME_BEFORE_ONLINE seconds have elapsed.
-
Modify Host Monitoring Logic: Update the logic to handle the transition of hosts from offline to the keep_online_host and eventually to the online list after the specified timeout.
-
Update the Offline List Display: Ensure that hosts in both offline_dict and keep_online_host are displayed appropriately in the offline list.
-
Ensure Accurate Time Calculations: Correctly calculate the elapsed time to determine when a host should be moved from keep_online_host to the online list.
Let's go through each of these steps in detail.
1. Define keep_online_host
We'll add a new set named keep_online_host to track hostnames that should remain in the offline list temporarily after coming back online.
Modifications:
Add the keep_online_host set to your OfflineHostMonitor class.
class OfflineHostMonitor(QWidget):
update_inspect_status = pyqtSignal(str, str)
def __init__(self, queue, offline_dict, stop_event, semaphore, remote_alert=''):
super().__init__()
self.queue = queue
self.offline_dict = offline_dict
self.stop_event = stop_event
self.semaphore = semaphore
self.remote_alert = remote_alert
self.settings_widget = None
self.attempts_dict = {}
self.update_inspect_status.connect(self.on_update_inspect_status)
self.red_alert_time = 15 # default value in minutes
self.red_alert_color = QColor() # default alert color
# Initialize keep_online_host as a dictionary with hostname as key and timestamp as value
self.keep_online_host = {}
self.TIME_BEFORE_ONLINE = TIME_BEFORE_ONLINE # ensure TIME_BEFORE_ONLINE is defined globally
self.initUI()
self.update_signal = pyqtSignal()
threading.Thread(target=update_offline_list, args=(self.queue, self.offline_dict, self.keep_online_host, self.stop_event, self.update_signal, self.settings_widget, self), daemon=True).start()
self.timer = QTimer(self)
self.timer.timeout.connect(self.refresh_table)
self.timer.start(1000) # Refresh every second
self.inspect_filter_state = 0 # 0: All, 1: WAN down & Server up, 2: Server down & Server up
self.sound_manager = SoundManager()
Note: Ensure that TIME_BEFORE_ONLINE is defined globally at the beginning of your script:
TIME_BEFORE_ONLINE = 60 # seconds (Adjust as needed)
2. Modify Host Monitoring Logic
Update the schedule_host_deletion and related functions to handle the transition of hosts into the keep_online_host and their eventual removal from the offline list.
Modifications:
a. Update the schedule_host_deletion Function
Adjust this function to add hosts to keep_online_host instead of immediately removing them from offline_dict.
def schedule_host_deletion(hostname, offline_dict, keep_online_host, 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_online(
hostname,
store_name,
offline_dict,
normalized_hostname,
offline_dict[normalized_hostname]['inspect_status']
)
offline_duration = time.time() - offline_dict[normalized_hostname]['start_time']
# Add to keep_online_host with the current timestamp
keep_online_host[normalized_hostname] = time.time()
# Play sound alert if conditions are met
if settings_widget.sound_alert_enabled and offline_duration > OFFLINE_DURATION and len(main_window.sound_manager.sound_queue) < main_window.sound_manager.max_sounds:
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"
def play_sound():
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):
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)
else:
print("Failed to download sound file and no fallback sound available.")
sound_thread = threading.Thread(target=play_sound)
sound_thread.start()
# Do not delete from offline_dict yet
# Instead, add to keep_online_host and schedule removal after TIME_BEFORE_ONLINE
#else:
#print(f"Hostname {normalized_hostname} was not in offline_dict")
update_signal.emit()
# Schedule the host to be moved to keep_online_host after TIME_BEFORE_ONLINE
timer = threading.Timer(TIME_BEFORE_ONLINE, delete_host)
timer.start()
b. Update update_offline_list Function
Modify the update_offline_list function to handle the keep_online_host and remove hosts from it after TIME_BEFORE_ONLINE seconds.
def update_offline_list(queue, offline_dict, keep_online_host, 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():
current_time = time.time()
try:
# Handle hosts returning online
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 deletion after TIME_BEFORE_ONLINE
schedule_host_deletion(hostname, offline_dict, keep_online_host, update_signal, settings_widget, offline_dict_lock, main_window)
else:
if 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,
'comment': ''
}
else:
offline_dict[normalized_hostname]['inspect_status'] = inspect_status
queue.task_done()
except Empty:
pass # No host update, continue
except Exception as e:
print(f"Error in update_offline_list: {e}")
# Check if any hosts in keep_online_host have exceeded TIME_BEFORE_ONLINE
hosts_to_remove = []
for hostname in keep_online_host:
if current_time - keep_online_host[hostname] >= TIME_BEFORE_ONLINE:
# Host has been online long enough, remove from keep_online_host
hosts_to_remove.append(hostname)
# Optionally, update online list here if you have one
for hostname in hosts_to_remove:
del keep_online_host[hostname]
# Optionally, emit a signal to update UI or perform other actions
update_signal.emit()
time.sleep(0.1) # Slight delay to prevent high CPU usage
Explanation:
-
Adding to keep_online_host: When a host comes back online, instead of immediately removing it from offline_dict, we add it to keep_online_host with the current timestamp.
-
Scheduled Removal: A threading.Timer is set up to move the host to keep_online_host after TIME_BEFORE_ONLINE seconds. This ensures that the host remains in the offline list for the specified duration before being removed.
-
Periodic Check: In the update_offline_list function, we periodically check if any hosts in keep_online_host have surpassed the TIME_BEFORE_ONLINE duration. If they have, we remove them from keep_online_host, effectively moving them to the online list.
3. Update the Offline List Display
Ensure that the hosts in both offline_dict and keep_online_host are displayed in the offline list. Hosts in keep_online_host should be visually identifiable (e.g., with a different color or annotation).
Modifications:
Update the refresh_table method in the OfflineHostMonitor class.
def refresh_table(self):
current_time = time.time()
self.table_widget.setRowCount(0)
# Combine offline_dict and keep_online_host for display
combined_offline = self.offline_dict.copy()
for hostname in self.keep_online_host:
if hostname in combined_offline:
combined_offline[hostname]['keep_online_since'] = self.keep_online_host[hostname]
filtered_offline = {
hostname: details for hostname, details in combined_offline.items()
if (current_time - details['start_time']) > OFFLINE_DURATION
}
if self.inspect_filter_state == 1:
filtered_offline = {hostname: details for hostname, details in filtered_offline.items() if details.get('inspect_status') in ['WAN down', 'Server up']}
elif self.inspect_filter_state == 2:
filtered_offline = {hostname: details for hostname, details in filtered_offline.items() if details.get('inspect_status') in ['Server down', 'Server up']}
sorted_offline = sorted(filtered_offline.items(), key=lambda item: current_time - item[1]['start_time'], reverse=True)
if self.settings_widget:
exception_hosts = self.settings_widget.exception_hosts
for row, (hostname, details) in enumerate(sorted_offline):
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')
# Check if host is in keep_online_host
is_keeping = 'keep_online_since' in details
keep_duration = current_time - details['keep_online_since'] if is_keeping else 0
if is_keeping and keep_duration < TIME_BEFORE_ONLINE:
# Optionally, modify display to indicate the host is in keep_online_host
duration += f" (Reappeared {int(keep_duration)}s ago)"
# You can also set a different color or style
row_color = QColor('lightblue')
else:
row_color = None
if duration_seconds > ALERT_TIME and current_time - details['last_alert_time'] > ALERT_REPEAT:
if self.settings_widget:
normalized_hostname = hostname.upper()
exception_hosts_upper = {h.upper() for h in self.settings_widget.exception_hosts}
if normalized_hostname not in exception_hosts_upper:
if self.settings_widget.pop_up_alert_enabled:
threading.Thread(target=self.trigger_pop_up_alert, args=(hostname, details, duration), daemon=True).start()
if self.settings_widget.sound_alert_enabled and row < 10: # check if hostname is less than 10
threading.Thread(target=self.trigger_sound_alert, args=(hostname, details, duration), daemon=True).start()
details['last_alert_time'] = current_time
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)
# Color coding
hostname_lower = hostname.lower()
if any(fnmatch.fnmatch(hostname_lower, pattern.lower()) for pattern in self.settings_widget.sound_alert_patterns):
self.set_row_color(row, QColor('lightyellow'))
if is_keeping and row_color:
self.set_row_color(row, row_color)
elif duration_minutes >= self.red_alert_time and self.red_alert_color.isValid():
self.set_row_color(row, self.red_alert_color)
if inspect_status == "Server up":
self.set_row_color(row, QColor('palegreen'))
# Update the comment
details['comment'] = self.table_widget.item(row, 7).text()
self.adjust_row_heights()
Explanation:
-
Combined Offline List: We create a combined dictionary that includes both offline hosts and those in keep_online_host with an additional timestamp.
-
Display Formatting: For hosts in keep_online_host, we append a note indicating how long they've been online recently and optionally change their row color to lightblue for better visibility.
-
Row Coloring: Differentiates between regular offline hosts, those in keep_online_host, and alerts.
4. Ensure Accurate Time Calculations
Make sure the time calculations accurately reflect the time elapsed for each host, especially when determining whether to move a host out of keep_online_host.
Modifications:
a. Update monitor_host Function
Ensure that when a host's status changes to online, it interacts correctly with keep_online_host.
def monitor_host(host_info, queue, offline_dict, keep_online_host, 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)
if not is_online:
if 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,
'comment': ''
}
else:
offline_dict[normalized_hostname]['inspect_status'] = inspect_status
else:
if normalized_hostname in offline_dict and normalized_hostname not in keep_online_host:
# Only schedule deletion if not already in keep_online_host
schedule_host_deletion(hostname, offline_dict, keep_online_host, queue, main_window.settings_widget, offline_dict_lock, main_window)
queue.put((hostname, store_name, telephone, is_online, inspect_status))
time.sleep(3)
Explanation:
-
Check Existing in keep_online_host: Only schedule deletion (i.e., add to keep_online_host) if the host is not already there. This prevents rescheduling if the host is already in the temporary list.
-
Pass Required Arguments: Ensure that all necessary arguments, including keep_online_host, are passed to update_offline_list.
5. Integrate keep_online_host in the Main Thread
Ensure that keep_online_host is correctly managed within the main application context.
Modifications:
a. Update Update_offline_list Thread Invocation
When initializing the update_offline_list thread, include keep_online_host.
# Start thread to handle offline list updates
update_thread = threading.Thread(
target=update_offline_list,
args=(queue, offline_dict, main_window.keep_online_host, stop_event, return_online_signal, settings_widget, main_window),
daemon=True
)
update_thread.start()
active_threads.append(update_thread)
Explanation:
- Pass
keep_online_host: Ensure that the keep_online_host is correctly passed to the update_offline_list function so it can manage host entries appropriately.
6. Optional: Visual Indicators for keep_online_host
To improve user experience, you can add visual indicators (like different colors or icons) for hosts that are in keep_online_host. This helps users distinguish between fully offline hosts and those temporarily kept offline.
Modifications:
As shown in the refresh_table method above, we change the row color for hosts in keep_online_host. You can further enhance this by adding icons or tooltips.
if is_keeping and row_color:
self.set_row_color(row, row_color)
# Optionally, add a tooltip
item_hostname.setToolTip("Recently went online. Will be removed from offline list shortly.")
Complete Code Integration
For clarity, here's how the key components fit together. Please integrate these changes into your existing codebase accordingly.
a. Define Global Variables
ALERT_TIME = 60 # seconds
ALERT_REPEAT = 300 # seconds
ALERT_TIMEOUT = 5 # seconds
OFFLINE_DURATION = 60 # seconds
TIME_BEFORE_ONLINE = 60 # seconds (You can adjust this as needed)
MAX_WORKERS = 10 # Maximum number of threads
MAX_PINGS = 50 # Maximum number of concurrent pings
GROUP_SIZE = 30 # Make groups of hostname
LOG_NORMAL = 60 # Write host return online after 60 seconds
FONT_SIZE = 14
english_locale = QLocale(QLocale.English, QLocale.UnitedStates)
b. Update OfflineHostMonitor Class
Ensure the OfflineHostMonitor class includes the keep_online_host set and integrates it within existing methods.
class OfflineHostMonitor(QWidget):
update_inspect_status = pyqtSignal(str, str)
def __init__(self, queue, offline_dict, keep_online_host, stop_event, semaphore, remote_alert=''):
super().__init__()
self.queue = queue
self.offline_dict = offline_dict
self.keep_online_host = keep_online_host
self.stop_event = stop_event
self.semaphore = semaphore
self.remote_alert = remote_alert
self.settings_widget = None
self.attempts_dict = {}
self.update_inspect_status.connect(self.on_update_inspect_status)
self.red_alert_time = 15 # default value in minutes
self.red_alert_color = QColor() # default alert color
self.TIME_BEFORE_ONLINE = TIME_BEFORE_ONLINE # seconds
self.initUI()
self.update_signal = pyqtSignal()
threading.Thread(target=update_offline_list, args=(self.queue, self.offline_dict, self.keep_online_host, self.stop_event, self.update_signal, self.settings_widget, self), daemon=True).start()
self.timer = QTimer(self)
self.timer.timeout.connect(self.refresh_table)
self.timer.start(1000) # Refresh every second
self.inspect_filter_state = 0 # 0: All, 1: WAN down & Server up, 2: Server down & Server up
self.sound_manager = SoundManager()
# ... (rest of the class methods)
c. Update main Function
Ensure that keep_online_host is correctly initialized and passed to relevant components.
def main():
# Initialize PyQt5 application
app = QApplication(sys.argv)
lock_manager = LockManager(LOCK_FILE)
try:
lock_manager.acquire()
except (IOError, OSError):
QMessageBox.warning(None, "", "The program is already running.")
if lock_manager.file:
lock_manager.file.close()
sys.exit()
atexit.register(lock_manager.release)
# Your main program logic here
print("Program is running...")
global MAX_PINGS, MAX_WORKERS
tab_widget = QTabWidget()
# Initialize SoundManager (assuming this is defined elsewhere in your code)
sound_manager = SoundManager()
# Main widget and layout setup
main_widget = QWidget()
main_layout = QVBoxLayout(main_widget)
# UI setup (e.g., labels for status information)
host_label = QLabel()
host_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
host_label.setStyleSheet("font-size: 12pt; color: black; padding-right: 10px;")
clock_label = QLabel()
clock_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
clock_label.setStyleSheet("font-size: 12pt;")
# Arrange layout
main_layout.addWidget(host_label)
main_layout.addWidget(tab_widget)
main_layout.addWidget(clock_label)
main_widget.setLayout(main_layout)
main_widget.setWindowTitle("Server Monitor - Alert by IT Servicedesk 2024")
main_widget.setGeometry(300, 300, 1100, 600)
# Function to update status labels
def update_labels():
current_time = QTime.currentTime().toString("hh:mm:ss")
current_date = QDate.currentDate().toString("dd MMM yyyy")
# Assuming host_info_dict is defined/available
total_hosts = len(host_info_dict)
offline_hosts = 0 # Implement logic to determine online/offline hosts
offline_hosts_wan = 0 # Implement logic to specifically track WAN status
offline_hosts_serv = 0 # Implement logic for Server status
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)
# Example label updates
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 for updating labels
timer = QTimer()
timer.timeout.connect(update_labels)
timer.start(1000) # Update every second
# Create main UI components
keep_online_host = {}
main_window = OfflineHostMonitor(queue=None, offline_dict=None, keep_online_host=keep_online_host, stop_event=None, semaphore=None)
tab_widget.addTab(main_window, "Monitor")
return_online_widget = ReturnOnlineWidget()
tab_widget.addTab(return_online_widget, "Return Online")
main_window.sound_manager = sound_manager # Attach the sound manager to the main window
settings_widget = SettingsWidget(None, None, None, None, None, tab_widget, main_window)
tab_widget.addTab(settings_widget, "Settings")
update_log_widget = UpdateLogWidget()
tab_widget.addTab(update_log_widget, "Update Log")
main_window.settings_widget = settings_widget
# Prepare application exit cleanup
def cleanup():
# Display the closing dialog
closing_dialog = ClosingDialog()
closing_dialog.show()
app.processEvents() # Process remaining GUI events
stop_event.set() # Signal all threads to stop
for thread in active_threads:
thread.join() # Wait for threads to finish
# Close the dialog after threads are done
closing_dialog.accept()
# Connect cleanup on application exit
app.aboutToQuit.connect(cleanup)
# File path setup and initial checks
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()
# Load offline state
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 and threading setup
queue = Queue()
stop_event = threading.Event()
active_threads = []
cpu_count = psutil.cpu_count(logical=True)
memory = psutil.virtual_memory()
available_memory_gb = memory.available / (1024 ** 3) # Corrected to gigabytes
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)
# Assign globals to widgets
main_window.queue = queue
main_window.offline_dict = offline_dict
main_window.keep_online_host = keep_online_host
main_window.stop_event = stop_event
main_window.semaphore = semaphore
settings_widget.queue = queue
settings_widget.offline_dict = offline_dict
settings_widget.keep_online_host = keep_online_host
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
for host_info in host_info_list:
thread = threading.Thread(
target=monitor_host,
args=(host_info, queue, offline_dict, keep_online_host, stop_event, semaphore, main_window)
)
thread.start()
active_threads.append(thread)
# Start thread to handle offline list updates
update_thread = threading.Thread(
target=update_offline_list,
args=(queue, offline_dict, keep_online_host, stop_event, return_online_signal, settings_widget, main_window),
daemon=True
)
update_thread.start()
active_threads.append(update_thread)
# Show main widget
main_widget.show()
# Ensure state is saved on app quit
app.aboutToQuit.connect(lambda: save_offline_state(offline_state_file, offline_dict))
sys.exit(app.exec_())
Key Points:
-
Initialization: keep_online_host is initialized as an empty dictionary and passed to the OfflineHostMonitor instance.
-
Thread Arguments: Ensure that all necessary arguments, including keep_online_host, are correctly passed to monitoring and updating threads.
-
Memory Calculation Correction: Adjusted the memory calculation from megabytes to gigabytes for max_pings_based_on_memory.
7. Final Touches and Testing
After integrating all the above changes:
-
Test the Functionality:
- Simulate Hosts Going Offline and Online: Ensure that when hosts come back online, they are correctly added to
keep_online_host and removed after TIME_BEFORE_ONLINE seconds.
- Visual Indicators: Verify that hosts in
keep_online_host are visually distinct in the offline list.
- Alerts: Confirm that alerts behave as expected for both offline and transitioning hosts.
-
Handle Edge Cases:
- Program Restart: Ensure that
keep_online_host does not persist across program restarts unless desired.
- Concurrent Updates: Make sure that thread synchronization is correctly handled to prevent race conditions.
-
Logging: Optionally, add logging statements to help debug and monitor the behavior of keep_online_host.
Complete Enhanced Code Snippets
For convenience, here are the complete enhanced code snippets integrating the keep_online_host functionality.
a. Global Definitions
import sys, os, time, subprocess, threading, psutil, socket, requests, platform, base64, json, ipaddress
import csv, io, winsound, tempfile, ffmpeg, pyexpat, shutil, ast, operator, re, msvcrt, atexit
from queue import Queue, Empty
from PyQt5.QtWidgets import (QApplication, QWidget, QVBoxLayout, QLineEdit, QLabel,
QTabWidget, QPushButton, QMessageBox, QTableWidget, QTableWidgetItem,
QFormLayout, QCheckBox, QTextEdit, QComboBox, QInputDialog, QHBoxLayout,
QAbstractItemView, QHeaderView, QDialog, QTableView, QStatusBar,
QDateEdit, QFileDialog, QMenu, QAction, QStyledItemDelegate, QStackedWidget,
QColorDialog, QSizePolicy, QDateTimeEdit, QTimeEdit, QMenu, QDesktopWidget)
from PyQt5.QtCore import QTimer, Qt, QByteArray, QThread, pyqtSignal, QObject, QDate, QTime, QRect, QLocale
from PyQt5 import QtGui
from PyQt5.QtGui import QIcon, QPixmap, QClipboard, QColor, QBrush, QFont, QIntValidator, QPainter
from io import BytesIO
from datetime import datetime, timedelta
from filelock import FileLock, Timeout
from playsound import playsound
from threading import Thread, Lock
import pygame, fnmatch
import urllib.parse
import urllib.request
from collections import deque
from concurrent.futures import ThreadPoolExecutor, as_completed
ALERT_TIME = 60 # seconds
ALERT_REPEAT = 300 # seconds
ALERT_TIMEOUT = 5 # seconds
OFFLINE_DURATION = 60 # seconds
TIME_BEFORE_ONLINE = 60 # seconds
MAX_WORKERS = 10 # Maximum number of threads
MAX_PINGS = 50 # Maximum number of concurrent pings
GROUP_SIZE = 30 # Make groups of hostname
LOG_NORMAL = 60 # Write host return online after 60 seconds
FONT_SIZE = 14
english_locale = QLocale(QLocale.English, QLocale.UnitedStates)
b. OfflineHostMonitor Class with keep_online_host
class OfflineHostMonitor(QWidget):
update_inspect_status = pyqtSignal(str, str)
def __init__(self, queue, offline_dict, keep_online_host, stop_event, semaphore, remote_alert=''):
super().__init__()
self.queue = queue
self.offline_dict = offline_dict
self.keep_online_host = keep_online_host
self.stop_event = stop_event
self.semaphore = semaphore
self.remote_alert = remote_alert
self.settings_widget = None
self.attempts_dict = {}
self.update_inspect_status.connect(self.on_update_inspect_status)
self.red_alert_time = 15 # default value in minutes
self.red_alert_color = QColor() # default alert color
self.TIME_BEFORE_ONLINE = TIME_BEFORE_ONLINE # seconds
self.initUI()
self.update_signal = pyqtSignal()
threading.Thread(target=update_offline_list, args=(self.queue, self.offline_dict, self.keep_online_host, self.stop_event, self.update_signal, self.settings_widget, self), daemon=True).start()
self.timer = QTimer(self)
self.timer.timeout.connect(self.refresh_table)
self.timer.start(1000) # Refresh every second
self.inspect_filter_state = 0 # 0: All, 1: WAN down & Server up, 2: Server down & Server up
self.sound_manager = SoundManager()
def refresh_table(self):
current_time = time.time()
self.table_widget.setRowCount(0)
# Combine offline_dict and keep_online_host for display
combined_offline = self.offline_dict.copy()
for hostname in self.keep_online_host:
if hostname in combined_offline:
combined_offline[hostname]['keep_online_since'] = self.keep_online_host[hostname]
filtered_offline = {
hostname: details for hostname, details in combined_offline.items()
if (current_time - details['start_time']) > OFFLINE_DURATION
}
if self.inspect_filter_state == 1:
filtered_offline = {hostname: details for hostname, details in filtered_offline.items() if details.get('inspect_status') in ['WAN down', 'Server up']}
elif self.inspect_filter_state == 2:
filtered_offline = {hostname: details for hostname, details in filtered_offline.items() if details.get('inspect_status') in ['Server down', 'Server up']}
sorted_offline = sorted(filtered_offline.items(), key=lambda item: current_time - item[1]['start_time'], reverse=True)
if self.settings_widget:
exception_hosts = self.settings_widget.exception_hosts
for row, (hostname, details) in enumerate(sorted_offline):
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')
# Check if host is in keep_online_host
is_keeping = 'keep_online_since' in details
keep_duration = current_time - details['keep_online_since'] if is_keeping else 0
if is_keeping and keep_duration < TIME_BEFORE_ONLINE:
# Optionally, modify display to indicate the host is in keep_online_host
duration += f" (Reappeared {int(keep_duration)}s ago)"
# You can also set a different color or style
row_color = QColor('lightblue')
else:
row_color = None
if duration_seconds > ALERT_TIME and current_time - details['last_alert_time'] > ALERT_REPEAT:
if self.settings_widget:
normalized_hostname = hostname.upper()
exception_hosts_upper = {h.upper() for h in self.settings_widget.exception_hosts}
if normalized_hostname not in exception_hosts_upper:
if self.settings_widget.pop_up_alert_enabled:
threading.Thread(target=self.trigger_pop_up_alert, args=(hostname, details, duration), daemon=True).start()
if self.settings_widget.sound_alert_enabled and row < 10: # check if hostname is less than 10
threading.Thread(target=self.trigger_sound_alert, args=(hostname, details, duration), daemon=True).start()
details['last_alert_time'] = current_time
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)
# Color coding
hostname_lower = hostname.lower()
if any(fnmatch.fnmatch(hostname_lower, pattern.lower()) for pattern in self.settings_widget.sound_alert_patterns):
self.set_row_color(row, QColor('lightyellow'))
if is_keeping and row_color:
self.set_row_color(row, row_color)
# Optionally, add a tooltip
item_hostname.setToolTip("Recently went online. Will be removed from offline list shortly.")
elif duration_minutes >= self.red_alert_time and self.red_alert_color.isValid():
self.set_row_color(row, self.red_alert_color)
if inspect_status == "Server up":
self.set_row_color(row, QColor('palegreen'))
# Update the comment
details['comment'] = self.table_widget.item(row, 7).text()
self.adjust_row_heights()
c. Update schedule_host_deletion Function
def schedule_host_deletion(hostname, offline_dict, keep_online_host, 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_online(
hostname,
store_name,
offline_dict,
normalized_hostname,
offline_dict[normalized_hostname]['inspect_status']
)
offline_duration = time.time() - offline_dict[normalized_hostname]['start_time']
# Add to keep_online_host with the current timestamp
keep_online_host[normalized_hostname] = time.time()
# Play sound alert if conditions are met
if settings_widget.sound_alert_enabled and offline_duration > OFFLINE_DURATION and len(main_window.sound_manager.sound_queue) < main_window.sound_manager.max_sounds:
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"
def play_sound():
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):
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)
else:
print("Failed to download sound file and no fallback sound available.")
sound_thread = threading.Thread(target=play_sound)
sound_thread.start()
update_signal.emit()
# Schedule the host to be moved to keep_online_host after TIME_BEFORE_ONLINE
timer = threading.Timer(TIME_BEFORE_ONLINE, delete_host)
timer.start()
d. Update update_offline_list Function
def update_offline_list(queue, offline_dict, keep_online_host, 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():
current_time = time.time()
try:
# Handle hosts returning online
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 deletion after TIME_BEFORE_ONLINE
schedule_host_deletion(hostname, offline_dict, keep_online_host, update_signal, settings_widget, offline_dict_lock, main_window)
else:
if 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,
'comment': ''
}
else:
offline_dict[normalized_hostname]['inspect_status'] = inspect_status
queue.task_done()
except Empty:
pass # No host update, continue
except Exception as e:
print(f"Error in update_offline_list: {e}")
# Check if any hosts in keep_online_host have exceeded TIME_BEFORE_ONLINE
hosts_to_remove = []
for hostname in keep_online_host:
if current_time - keep_online_host[hostname] >= TIME_BEFORE_ONLINE:
# Host has been online long enough, remove from keep_online_host
hosts_to_remove.append(hostname)
# Optionally, add to online list or perform other actions
for hostname in hosts_to_remove:
del keep_online_host[hostname]
# Optionally, emit a signal to update UI or perform other actions
update_signal.emit()
time.sleep(0.1) # Slight delay to prevent high CPU usage
Conclusion
By following the above steps, you will have successfully implemented the keep_online_host functionality in your server monitoring application. This enhancement ensures that transient host status changes don't lead to rapid toggling in the UI, providing a more stable and user-friendly experience.
Key Benefits:
-
Stability: Prevents flapping by keeping recently online hosts in the offline list temporarily.
-
User Clarity: Visual indicators help users distinguish between fully offline hosts and those recently returned online.
-
Configurability: The TIME_BEFORE_ONLINE parameter allows flexibility in how long hosts remain in the keep_online_host list.
Final Recommendations:
-
Testing: Rigorously test the new functionality in various scenarios to ensure reliability.
-
Logging: Consider adding more detailed logging around the keep_online_host management for easier debugging.
-
UI Enhancements: Further improve the UI to provide more intuitive indicators or options related to keep_online_host.
Feel free to reach out if you encounter any issues or need further assistance with this implementation!