#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Тестовый скрипт для проверки периодического обновления контейнеров LogBoard+ Автор: Сергей Антропов Сайт: https://devops.org.ru """ import requests import json import time from datetime import datetime def test_container_update(): """Тестирование периодического обновления контейнеров""" base_url = "http://localhost:9001" # 1. Вход в систему print("🔐 Вход в систему...") login_data = {"username": "admin", "password": "admin"} response = requests.post(f"{base_url}/api/auth/login", json=login_data) if response.status_code != 200: print(f"❌ Ошибка входа: {response.status_code}") return token = response.json()["access_token"] headers = {"Authorization": f"Bearer {token}"} print("✅ Вход выполнен успешно") # 2. Получение контейнеров print("\n🐳 Получение контейнеров...") response = requests.get(f"{base_url}/api/containers/services", headers=headers) if response.status_code != 200: print(f"❌ Ошибка получения контейнеров: {response.status_code}") return containers = response.json() print(f"✅ Контейнеров получено: {len(containers)}") # Анализируем контейнеры local_containers = [c for c in containers if not c.get('is_remote', False)] remote_containers = [c for c in containers if c.get('is_remote', False)] print(f"\n📊 Статистика контейнеров:") print(f" 📍 Локальные контейнеры: {len(local_containers)}") for container in local_containers: print(f" • {container['name']} ({container['status']})") print(f"\n 🌐 Удаленные контейнеры: {len(remote_containers)}") # Группируем удаленные контейнеры по хостам containers_by_host = {} for container in remote_containers: hostname = container.get('hostname', 'unknown') if hostname not in containers_by_host: containers_by_host[hostname] = [] containers_by_host[hostname].append(container) for hostname, host_containers in containers_by_host.items(): print(f" 🖥️ Хост: {hostname} ({len(host_containers)} контейнеров)") for container in host_containers: print(f" • {container['name']} ({container['status']})") # 3. Тестирование периодического обновления print(f"\n⏰ Тестирование периодического обновления...") print(f" Будем проверять каждые 10 секунд в течение 1 минуты") initial_count = len(containers) check_count = 0 for i in range(6): # 6 проверок по 10 секунд = 1 минута time.sleep(10) check_count += 1 print(f"\n 🔄 Проверка #{check_count} ({datetime.now().strftime('%H:%M:%S')})") try: response = requests.get(f"{base_url}/api/containers/services", headers=headers) if response.status_code == 200: current_containers = response.json() current_count = len(current_containers) print(f" Контейнеров сейчас: {current_count}") if current_count != initial_count: print(f" ⚠️ Количество контейнеров изменилось!") print(f" Было: {initial_count}, Стало: {current_count}") # Анализируем изменения current_local = [c for c in current_containers if not c.get('is_remote', False)] current_remote = [c for c in current_containers if c.get('is_remote', False)] print(f" 📍 Локальных: {len(current_local)}") print(f" 🌐 Удаленных: {len(current_remote)}") # Проверяем, какие контейнеры исчезли initial_ids = {c['id'] for c in containers} current_ids = {c['id'] for c in current_containers} disappeared = initial_ids - current_ids if disappeared: print(f" ❌ Исчезли контейнеры: {list(disappeared)}") # Проверяем, какие контейнеры появились appeared = current_ids - initial_ids if appeared: print(f" ✅ Появились контейнеры: {list(appeared)}") # Обновляем начальное состояние containers = current_containers initial_count = current_count else: print(f" ✅ Количество контейнеров не изменилось") else: print(f" ❌ Ошибка получения контейнеров: {response.status_code}") except Exception as e: print(f" ❌ Ошибка при проверке: {e}") print(f"\n🎉 Тестирование периодического обновления завершено!") print(f"🌐 Откройте http://localhost:9001 в браузере для просмотра интерфейса") if __name__ == "__main__": test_container_update()