Files
lxd-app/api/src/Scripts/auto-stop-containers.php
T
2025-09-02 20:38:58 +02:00

48 lines
1.5 KiB
PHP
Executable File

<?php
require __DIR__ . '/../../vendor/autoload.php'; // Adjust path as needed
use App\Services\LxdService;
// Initialize LXD service
$lxdService = new LxdService();
// Define the directory containing access logs
$logDir = $_ENV['STATEDIR'] ?? "/var/www/html/lxd-app/api/public/last-access-logs";
// Define the idle threshold in minutes
$thresholdMinutes = 30;
// Iterate over all log files in the specified directory
foreach (glob($logDir . '/*.txt') as $filePath) {
// Extract the container name from the file name
$containerName = basename($filePath, '.txt');
// Get the last modified time of the file
$lastModified = filemtime($filePath);
if (!$lastModified) {
echo "Failed to get modification time for $containerName.\n";
continue;
}
$now = time();
$interval = $now - $lastModified;
// Check if the container has been idle for longer than the threshold
if ($interval > $thresholdMinutes * 60) {
echo "$containerName has been idle for over $thresholdMinutes minutes. Stopping...\n";
try {
// Check if the container exists and stop it if it does
if ($lxdService->containerExists($containerName)) {
$lxdService->stopContainer($containerName);
echo "Stopped container: $containerName\n";
} else {
echo "Container $containerName does not exist.\n";
}
} catch (Throwable $e) {
echo "Error stopping $containerName: " . $e->getMessage() . "\n";
}
}
}