rem: более понятные переменные

This commit is contained in:
Sergei Erjemin 2024-11-11 18:41:18 +03:00
parent 9ac1c120a7
commit c3eb4e2ded

35
main.py
View File

@ -5,8 +5,10 @@ import sys
import signal import signal
import toml import toml
import os import os
import subprocess
from watchdog.observers import Observer from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler from watchdog.events import FileSystemEventHandler
from singleton import SingleInstance, SingleInstanceException
from pathlib import Path from pathlib import Path
@ -38,11 +40,14 @@ def read_toml(file_path):
class LogFileHandler(FileSystemEventHandler): class LogFileHandler(FileSystemEventHandler):
def __init__(self, log_filename): def __init__(self, log_filename):
self.log_filename = log_filename self.log_filename = log_filename
self.last_line_log = None
def on_modified(self, event): def on_modified(self, event):
if event.is_directory: if event.is_directory:
return return
print(event) print(self.log_filename, event)
# определяем какие изменения произошли в файле
# elif event.event_type == 'modified' and event.src_path == self.log_filename: # elif event.event_type == 'modified' and event.src_path == self.log_filename:
# # Обработка изменений в лог-файле # # Обработка изменений в лог-файле
# with open(event.src_path, 'r') as file: # with open(event.src_path, 'r') as file:
@ -54,9 +59,15 @@ class LogFileHandler(FileSystemEventHandler):
# Press the green button in the gutter to run the script. # Press the green button in the gutter to run the script.
if __name__ == '__main__': if __name__ == '__main__':
# Получение информации о системе # Проверка на запуск второго экземпляра
# system_info = platform.system() try:
# print(f"System: {system_info}") me = SingleInstance(flavor_id="tacacs_watcher")
except SingleInstanceException:
print("Another instance is already running, quitting.")
sys.exit(1)
print(sys.platform, me.lockfile)
# Установка обработчика сигнала # Установка обработчика сигнала
signal.signal(signal.SIGTERM, handler_stop) signal.signal(signal.SIGTERM, handler_stop)
# Считывание имени config-файла их аргументов командной строки # Считывание имени config-файла их аргументов командной строки
@ -70,10 +81,9 @@ if __name__ == '__main__':
print(config['hello']) print(config['hello'])
interval = config['interval'] if 'interval' in config else 1 interval = config['interval'] if 'interval' in config else 1
# получаем все группы в конфиге # получаем все группы в конфиге
group_keys = [key for key, value in config.items() if isinstance(value, dict)] groups = [key for key, value in config.items() if isinstance(value, dict)]
count_valid_groups = 0
observers = [] observers = []
for group in group_keys: for group in groups:
if 'log_in' not in config[group]: if 'log_in' not in config[group]:
print(f"Config '{config_file}' not have key 'log_in' in group '{group}' (see config '{config_file}').") print(f"Config '{config_file}' not have key 'log_in' in group '{group}' (see config '{config_file}').")
continue continue
@ -87,17 +97,16 @@ if __name__ == '__main__':
print(f"Directory '{config[group]['outdir']}' not exist (see config '{config_file}').") print(f"Directory '{config[group]['outdir']}' not exist (see config '{config_file}').")
continue continue
observers.append(Observer()) observers.append(Observer())
observers[count_valid_groups].schedule(LogFileHandler(config[group]['log_in']), observers[-1].schedule(LogFileHandler(config[group]['log_in']),
path=os.path.dirname(config[group]['log_in']), path=os.path.dirname(config[group]['log_in']),
recursive=False) recursive=False)
observers[count_valid_groups].start() observers[-1].start()
count_valid_groups += 1
# observer = Observer() # observer = Observer()
# event_handler = LogFileHandler(config[group]['log_in']) # event_handler = LogFileHandler(config[group]['log_in'])
# observer.schedule(event_handler, path=os.path.dirname(config[group]['log_in']), recursive=False) # observer.schedule(event_handler, path=os.path.dirname(config[group]['log_in']), recursive=False)
if count_valid_groups == 0: if len(observers) == 0:
# если нет ни одной валидной группы, то выходим # если нет ни одной валидной группы, то выходим
print(f"Config '{config_file}' not have valid groups (see config '{config_file}').") print(f"Config '{config_file}' not have valid groups (see config '{config_file}').")
sys.exit(1) sys.exit(1)