Files
hostpanel/ssh_manager/utils.py
ilkeral 342f1314c7 yeni
2025-07-21 13:49:36 +03:00

146 lines
5.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from .models import SSHLog, Project
from django.utils import timezone
import logging
import os
import tempfile
import requests
from bs4 import BeautifulSoup
logger = logging.getLogger(__name__)
# Yardımcı fonksiyonlar buraya gelebilir
def check_site_status(project):
"""
Projenin web sitesinin aktif olup olmadığını kontrol eder
Aynı zamanda proje klasörünün disk kullanımını günceller
"""
from .ssh_client import SSHManager
result_messages = []
# 1. Disk kullanımını güncelle
try:
if project.ssh_credential:
ssh_manager = SSHManager(project.ssh_credential)
if ssh_manager.check_connection():
# Proje klasörünün tam yolu
base_path = project.ssh_credential.base_path.rstrip('/')
folder_name = project.folder_name.strip('/')
full_path = f"{base_path}/{folder_name}"
# Debug bilgisi ekle
result_messages.append(f"Kontrol edilen path: {full_path}")
# Önce base path'in var olup olmadığını kontrol et
base_check_command = f"test -d '{base_path}' && echo 'BASE_EXISTS' || echo 'BASE_NOT_EXISTS'"
stdout_base, stderr_base, success_base = ssh_manager.execute_command(base_check_command)
if success_base and stdout_base.strip() == 'BASE_EXISTS':
# Base path var, şimdi proje klasörünü kontrol et
# Önce base path içindeki klasörleri listele
list_command = f"ls -la '{base_path}' | grep '^d'"
stdout_list, stderr_list, success_list = ssh_manager.execute_command(list_command)
if success_list:
result_messages.append(f"Base path içindeki klasörler: {stdout_list.strip()[:200]}")
# Proje klasörünü kontrol et
check_command = f"test -d '{full_path}' && echo 'EXISTS' || echo 'NOT_EXISTS'"
stdout_check, stderr_check, success_check = ssh_manager.execute_command(check_command)
if success_check and stdout_check.strip() == 'EXISTS':
# Disk kullanımını al
command = f"du -sh '{full_path}' 2>/dev/null | cut -f1"
stdout, stderr, success = ssh_manager.execute_command(command)
if success and stdout.strip():
old_usage = project.disk_usage or "Bilinmiyor"
project.disk_usage = stdout.strip()
result_messages.append(f"Disk kullanımı güncellendi: {old_usage}{project.disk_usage}")
else:
result_messages.append("Disk kullanımı komutu başarısız")
else:
result_messages.append(f"Proje klasörü bulunamadı: {full_path}")
else:
result_messages.append(f"Base path bulunamadı: {base_path}")
ssh_manager.close()
else:
result_messages.append("SSH bağlantısı kurulamadı")
else:
result_messages.append("SSH bilgisi eksik")
except Exception as e:
result_messages.append(f"Disk kontrolü hatası: {str(e)}")
# 2. Site durumunu kontrol et
if not project.url:
project.last_site_check = timezone.now()
project.save()
return False, "; ".join(result_messages + ["URL eksik"])
try:
# URL'yi düzenle
url = project.url
if not url.startswith(('http://', 'https://')):
url = f'http://{url}'
# Site kontrolü
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
response = requests.get(url, headers=headers, timeout=10)
if response.status_code == 200:
# Site erişilebilir
project.is_site_active = True
project.last_site_check = timezone.now()
project.save()
result_messages.append(f"Site aktif (HTTP {response.status_code})")
return True, "; ".join(result_messages)
else:
# Site erişilemez
project.is_site_active = False
project.last_site_check = timezone.now()
project.save()
result_messages.append(f"Site erişilemez (HTTP {response.status_code})")
return False, "; ".join(result_messages)
except requests.exceptions.Timeout:
project.is_site_active = False
project.last_site_check = timezone.now()
project.save()
result_messages.append("Site zaman aşımı")
return False, "; ".join(result_messages)
except requests.exceptions.ConnectionError:
project.is_site_active = False
project.last_site_check = timezone.now()
project.save()
result_messages.append("Site bağlantı hatası")
return False, "; ".join(result_messages)
except Exception as e:
project.is_site_active = False
project.last_site_check = timezone.now()
project.save()
result_messages.append(f"Site hatası: {str(e)}")
return False, "; ".join(result_messages)
def check_all_sites():
"""Tüm projelerin site durumunu kontrol et"""
projects = Project.objects.filter(url__isnull=False).exclude(url='')
results = []
for project in projects:
status, message = check_site_status(project)
results.append({
'project': project,
'status': status,
'message': message
})
return results