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)
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.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.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
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)
self.status_bar = QStatusBar(self)
layout.addWidget(self.status_bar)
self.table_widget = QTableWidget(self)
self.table_widget.setEditTriggers(QAbstractItemView.NoEditTriggers)
layout.addWidget(self.table_widget)
self.setLayout(layout)
font = QFont()
font.setPointSize(12)
self.table_widget.setFont(font)
self.dataUpdated.connect(self.load_data)
self.load_data()
self.resizeEvent(None)
def convert_to_seconds(self, duration):
""" Convert duration from various formats to seconds. """
try:
# If the input is purely numeric, assume it's in minutes and convert to seconds
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 = datetime.strptime(date_str, date_format)
return date < 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
# Clean up old data
lines_before_cleanup = 0
lines_after_cleanup = 0
removed_dates = set()
with open(file_path, 'r', encoding='utf-8') as file:
lines_before_cleanup = sum(1 for _ in file)
with open(file_path, 'r', encoding='utf-8') as file, open(temp_file_path, 'w', encoding='utf-8') as temp_file:
for line in file:
parts = line.strip().split('|')
if len(parts) >= 11:
end_offline_str = f"{parts[6]} {parts[7]}"
end_offline_date = end_offline_str.split()[0] # Extract just the date part (YYYY-MM-DD)
if is_older_than_180_days(end_offline_date):
removed_dates.add(end_offline_date)
else:
temp_file.write(line)
lines_after_cleanup += 1
# Replace old file with cleaned file
os.replace(temp_file_path, file_path)
if lines_before_cleanup != lines_after_cleanup:
removed_dates = sorted(removed_dates) # Sort dates for clarity
for date in removed_dates:
print(f"Removed date {date} : {lines_before_cleanup - lines_after_cleanup} lines of data older than 180 days.")
start_date = self.start_date_edit.date().toString("yyyy-MM-dd")
end_date = self.end_date_edit.date().toString("yyyy-MM-dd")
status_filter = self.status_filter.currentText()
hostname_filter = self.hostname_edit.text().strip()
# 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) # Assume user input is in minutes
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:
end_offline_str = f"{parts[6]} {parts[7]}"
end_offline_date = end_offline_str.split()[0] # Extract just the date part (YYYY-MM-DD)
# 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
if hostname_filter == "" or hostname_filter.lower() in parts[2].lower():
# Convert duration from the file to seconds for comparison
try:
duration = self.convert_to_seconds(parts[8]) # Extract duration from the line
except ValueError:
duration = None
if duration_filter is None or (duration is not None and duration >= duration_filter):
rows.append([parts[2], parts[3], f"{parts[4]} {parts[5]}", end_offline_str, parts[8], 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")
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}")
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
print(f"Error saving offline state to '{file_path}': {e}")
def save_offline_state(file_path, offline_dict):
try:
print("Saving offline state:")
#print(offline_dict) # Inspect the data being saved
normalized_dict = {k.upper(): v for k, v in offline_dict.items()}
with open(file_path, 'w', encoding='utf-8') as file:
try:
json.dump(normalized_dict, file, ensure_ascii=False, indent=4)
except TypeError as e:
print(f"Error serializing data to JSON: {e}")
print(f"Offline state saved to '{file_path}'")
except Exception as e:
print(f"Error saving offline state to '{file_path}': {e}")
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)
# Function to update labels
def update_labels():
current_time = QTime.currentTime().toString("hh:mm:ss")
current_date = QDate.currentDate().toString("dd MMM yyyy")
total_hosts = len(host_info_dict)
#offline_hosts = len(offline_dict)
offline_hosts = len([hostname for hostname, details in offline_dict.items() if details['inspect_status'] != 'Server up'])
online_hosts = total_hosts - offline_hosts
host_label.setText(f"Total: {total_hosts} Offline: {offline_hosts} Online: {online_hosts}")
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),
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()
make check hostname
It seems you're interested in adding functionality to check hostnames within your monitoring application. Based on your last line "make check hostname", you might be looking to ensure that the hostnames are valid or reachable before starting the monitoring process.
Your current code is designed to monitor a list of hostnames, attempting TCP connections to them, and performing various actions based on their online status. However, if you'd like to add an initial check to validate the hostnames before the monitoring begins, you can implement a function that checks whether each hostname can be resolved to an IP address or is reachable.
Below, I'll guide you through enhancing your application to check the hostnames before starting the monitoring:
1. Add a Function to Check Hostname Validity
You can use Python's socket module to attempt to resolve a hostname. If it raises an exception, the hostname is invalid or unreachable.
This function attempts to resolve the hostname to an IP address. If it fails, it catches a socket.gaierror exception and returns False, indicating an invalid hostname.
2. Incorporate the Hostname Check into Your read_host_list Function
Modify the read_host_list function to check each hostname as you read it:
def read_host_list(file_path):
host_info = []
hostname_count = 0
invalid_hostnames = []
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('|') # Assumes '|' as the delimiter
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)) # Ensure there are 5 elements
hostname = parts[0]
store_name = parts[1]
telephone = parts[2]
wan_a = parts[3]
wan_b = parts[4]
# Check if the hostname is valid
if check_hostname(hostname):
host_info.append((hostname, store_name, telephone, wan_a, wan_b))
hostname_count += 1
else:
invalid_hostnames.append(hostname)
print(f"Invalid hostname '{hostname}' - skipping.")
if invalid_hostnames:
print(f"Invalid hostnames: {', '.join(invalid_hostnames)}")
except Exception as e:
print(f"Error reading file '{file_path}': {e}")
return host_info, hostname_count
Explanation:
Invalid Hostnames List: A list to collect invalid hostnames.
Hostname Check: Before adding the hostname to host_info, the code calls check_hostname(hostname).
If the hostname is valid, it's added to the list.
If not, it's added to invalid_hostnames and skipped.
Reporting Invalid Hostnames: After processing the file, if there are any invalid hostnames, they are printed out.
3. Handle Invalid Hostnames Gracefully
In your application, ensure that any functions or threads that use the hostnames are only dealing with valid hostnames. This prevents unnecessary errors or exceptions during runtime.
Adjust the main Function:
Make sure your main function uses the updated host_info_list that only includes valid hostnames.
def main():
# ... existing setup code ...
# Read the host list with hostname checks
host_info_list, hostname_count = read_host_list(file_path)
# Proceed only with valid hostnames
if not host_info_list:
print("No valid hostnames found. Exiting.")
sys.exit()
# ... rest of your code ...
4. Optionally, Provide Feedback to the User
If you're running this application in an environment where user feedback is important, consider displaying a message box or UI element listing the invalid hostnames.
Example Using PyQt5 Message Box:
from PyQt5.QtWidgets import QMessageBox
def read_host_list(file_path):
# ... existing code ...
if invalid_hostnames:
invalid_hosts_str = ', '.join(invalid_hostnames)
QMessageBox.warning(None, "Invalid Hostnames", f"The following hostnames are invalid and were skipped:\n{invalid_hosts_str}")
return host_info, hostname_count
Note: Ensure that the PyQt5 event loop is running before showing message boxes.
5. Additional Considerations
Asynchronous DNS Resolution: If you have a large number of hostnames and the hostname resolution takes too long, consider using asynchronous DNS resolution libraries like aiohttp or asyncio.
Logging: Implement logging to a file for both valid and invalid hostnames for auditing purposes.
User Input Validation: If hostnames come from user input, validate them immediately upon entry.
6. Putting It All Together
Your updated main function should now initialize the host list with valid hostnames and proceed with the monitoring:
def main():
global MAX_PINGS, MAX_WORKERS
app = QApplication(sys.argv)
tab_widget = QTabWidget()
# ... existing UI setup ...
# Read the host list with hostname checks
host_info_list, hostname_count = read_host_list(file_path)
print(f"Number of valid hostnames: {hostname_count}")
if not host_info_list:
QMessageBox.critical(None, "No Valid Hostnames", "No valid hostnames were found in the host list. Exiting.")
sys.exit()
# ... existing code to initialize monitoring ...
sys.exit(app.exec_())
7. Testing the Changes
Ensure that your hostname.txt file contains both valid and invalid hostnames for testing purposes.
Run your application and observe the console output or UI messages.
The invalid hostnames should be reported and not included in the monitoring process.
Verify that the monitoring works correctly with the valid hostnames.
8. Conclusion
By adding a hostname check during the initialization phase, you enhance the robustness of your application. Users are immediately informed about any invalid hostnames, and the monitoring process proceeds smoothly without unnecessary errors.
I hope this helps you implement hostname checking in your server monitoring application. If you have any questions or need further assistance, feel free to ask!