file change on agent

This commit is contained in:
pika 2025-03-30 14:05:09 +02:00
parent 6217874cb0
commit eb99a1718b
3 changed files with 182 additions and 45 deletions

108
agent.py
View file

@ -20,6 +20,7 @@ load_dotenv()
# Fixed configuration
CADDYFILE_PATH = "/app/Caddyfile" # Fixed internal path
NGINX_CONFIG_PATH = "/app/nginx" # Fixed internal path for nginx configs
DASHBOARD_URL = os.getenv('DASHBOARD_URL', 'http://caddydb-server:5000/api/update')
SERVER_NAME = os.getenv('SERVER_NAME', socket.gethostname())
API_KEY = os.getenv('API_KEY')
@ -64,6 +65,9 @@ if not API_KEY:
last_data_sent = None
last_send_time = datetime.min
# Flag to determine what type of config to monitor
IS_NGINX = SERVER_TYPE.lower() == 'nginx'
def parse_caddyfile():
"""Parse the Caddyfile to extract domains and their proxy targets"""
entries = {}
@ -120,12 +124,68 @@ def create_auth_token():
logger.error(f"Error creating JWT token: {e}")
return None
def parse_nginx_configs():
"""Parse Nginx config files to extract domains and their proxy targets"""
entries = {}
if not os.path.exists(NGINX_CONFIG_PATH) or not os.path.isdir(NGINX_CONFIG_PATH):
logger.error(f"Nginx config directory not found at {NGINX_CONFIG_PATH}")
return entries
try:
# Find all .conf files in the directory and subdirectories
conf_files = []
for root, _, files in os.walk(NGINX_CONFIG_PATH):
for file in files:
if file.endswith('.conf'):
conf_files.append(os.path.join(root, file))
logger.info(f"Found {len(conf_files)} Nginx config files")
# Pattern to match server_name and proxy_pass directives
server_name_pattern = re.compile(r'server_name\s+([^;]+);', re.IGNORECASE)
proxy_pass_pattern = re.compile(r'proxy_pass\s+([^;]+);', re.IGNORECASE)
for conf_file in conf_files:
try:
with open(conf_file, 'r') as file:
content = file.read()
# Extract server blocks
server_blocks = re.findall(r'server\s*{([^}]+)}', content, re.DOTALL)
for block in server_blocks:
server_names = server_name_pattern.search(block)
proxy_pass = proxy_pass_pattern.search(block)
if server_names and proxy_pass:
server_names = server_names.group(1).strip().split()
target = proxy_pass.group(1).strip()
for name in server_names:
# Skip default names like "_" or localhost
if name != "_" and name != "localhost" and name != "localhost.localdomain":
entries[name] = target
except Exception as e:
logger.error(f"Error parsing Nginx config file {conf_file}: {e}")
return entries
except Exception as e:
logger.error(f"Error parsing Nginx configs: {e}")
return entries
def send_update(force=False):
"""Send Caddyfile data to the dashboard server"""
"""Send configuration data to the dashboard server"""
global last_data_sent, last_send_time
# Parse the Caddyfile
current_data = parse_caddyfile()
# Parse the appropriate configuration
if IS_NGINX:
current_data = parse_nginx_configs()
else:
current_data = parse_caddyfile()
current_time = datetime.now()
# Only send if data changed or enough time passed since last update
@ -134,9 +194,9 @@ def send_update(force=False):
(current_time - last_send_time).total_seconds() < CHECK_INTERVAL):
return
# Always include the server name in data payload
# Create the data payload
data = {
"server": SERVER_NAME, # Always include this
"server": SERVER_NAME,
"entries": current_data,
"timestamp": current_time.isoformat(),
"type": SERVER_TYPE
@ -171,12 +231,19 @@ def send_update(force=False):
except requests.exceptions.RequestException as e:
logger.error(f"Connection error sending update: {e}")
class CaddyFileHandler(FileSystemEventHandler):
"""Watch for changes to the Caddyfile and send updates"""
class ConfigFileHandler(FileSystemEventHandler):
"""Watch for changes to configuration files and send updates"""
def on_modified(self, event):
if event.src_path == CADDYFILE_PATH:
logger.info(f"Caddyfile changed, sending update")
send_update()
if IS_NGINX:
# For Nginx, check if it's a .conf file in the watched directory
if event.src_path.endswith('.conf'):
logger.info(f"Nginx config changed: {event.src_path}, sending update")
send_update()
else:
# For Caddy, check if it's the Caddyfile
if event.src_path == CADDYFILE_PATH:
logger.info(f"Caddyfile changed, sending update")
send_update()
def main():
"""Main function to start the agent"""
@ -184,13 +251,28 @@ def main():
send_update(force=True)
# Set up file watching
event_handler = CaddyFileHandler()
event_handler = ConfigFileHandler()
observer = Observer()
observer.schedule(event_handler, path=os.path.dirname(CADDYFILE_PATH), recursive=False)
if IS_NGINX:
# Watch the Nginx config directory
if not os.path.exists(NGINX_CONFIG_PATH):
logger.error(f"Nginx config path not found: {NGINX_CONFIG_PATH}")
sys.exit(1)
observer.schedule(event_handler, path=NGINX_CONFIG_PATH, recursive=True)
logger.info(f"Watching Nginx configs in {NGINX_CONFIG_PATH} for changes")
else:
# Watch the Caddyfile
if not os.path.exists(CADDYFILE_PATH):
logger.error(f"Caddyfile not found: {CADDYFILE_PATH}")
sys.exit(1)
observer.schedule(event_handler, path=os.path.dirname(CADDYFILE_PATH), recursive=False)
logger.info(f"Watching {CADDYFILE_PATH} for changes")
observer.start()
try:
logger.info(f"Agent started. Watching {CADDYFILE_PATH} for changes")
logger.info(f"{SERVER_TYPE.capitalize()} agent started successfully")
while True:
# Send periodic updates
send_update()