-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnovnc_cleanup.php
More file actions
84 lines (67 loc) · 2.79 KB
/
Copy pathnovnc_cleanup.php
File metadata and controls
84 lines (67 loc) · 2.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
// novnc_cleanup.php
class NoVNCCleanup {
private $session_timeout = 3600; // 1 час
public function cleanupOldSessions() {
$temp_dir = sys_get_temp_dir();
$pattern = $temp_dir . "/novnc_*.json";
$files = glob($pattern);
$cleaned = 0;
foreach ($files as $file) {
$data = json_decode(file_get_contents($file), true);
if (json_last_error() !== JSON_ERROR_NONE) {
unlink($file);
$cleaned++;
continue;
}
// Проверяем время создания сессии
if (time() - $data['started'] > $this->session_timeout) {
// Останавливаем процесс
if (isset($data['pid'])) {
exec("kill {$data['pid']} 2>/dev/null");
}
// Удаляем файл сессии
unlink($file);
$cleaned++;
}
}
return $cleaned;
}
public function cleanupByProcesses() {
echo "Поиск процессов noVNC/websockify старше 1 часа\n";
$cleaned = 0;
$timeout = 3600; // 1 час в секундах
// Получаем список процессов с временем запуска
exec("ps -eo pid,etimes,cmd | grep -E 'websockify|novnc' | grep -v grep", $processes);
foreach ($processes as $proc) {
$parts = preg_split('/\s+/', trim($proc), 3);
$pid = $parts[0] ?? 0;
$elapsed = $parts[1] ?? 0; // время работы в секундах
if ($pid && $elapsed > $timeout) {
echo "Процесс $pid работает {$elapsed}сек (>3600), завершаем\n";
// Мягкое завершение
exec("kill $pid 2>/dev/null");
sleep(1);
// Принудительно, если не завершился
exec("ps -p $pid 2>/dev/null", $check);
if (!empty($check)) {
exec("kill -9 $pid 2>/dev/null");
echo "Процесс $pid принудительно завершен\n";
} else {
echo "Процесс $pid завершен\n";
}
$cleaned++;
}
}
echo "Завершено процессов: $cleaned\n";
return $cleaned;
}
}
// Запуск очистки через cron
if (php_sapi_name() === 'cli') {
$cleanup = new NoVNCCleanup();
$cleaned = $cleanup->cleanupOldSessions();
$cleanedProcess = $cleanup->cleanupByProcesses();
echo "Cleaned $cleaned old noVNC sessions and $cleanedProcess processes\n";
}
?>