forked from urvishpatelce/lxd-app
fix: update code
This commit is contained in:
@@ -8,7 +8,7 @@ use App\Services\LxdService;
|
||||
$lxdService = new LxdService();
|
||||
|
||||
// Define the directory containing access logs
|
||||
$logDir = realpath(__DIR__ . '/../../public/last-access-logs'); // Adjust if you're in /app/src/Cron or similar
|
||||
$logDir = $_ENV['STATEDIR'] ?? "/var/www/html/lxd-app/api/public/last-access-logs";
|
||||
|
||||
// Define the idle threshold in minutes
|
||||
$thresholdMinutes = 30;
|
||||
@@ -18,23 +18,15 @@ foreach (glob($logDir . '/*.txt') as $filePath) {
|
||||
// Extract the container name from the file name
|
||||
$containerName = basename($filePath, '.txt');
|
||||
|
||||
// Get the last line from the log file
|
||||
$lastLine = getLastLine($filePath);
|
||||
if (!$lastLine) {
|
||||
echo "No access logs found for $containerName.\n";
|
||||
// Get the last modified time of the file
|
||||
$lastModified = filemtime($filePath);
|
||||
if (!$lastModified) {
|
||||
echo "Failed to get modification time for $containerName.\n";
|
||||
continue;
|
||||
}
|
||||
|
||||
// Parse the timestamp from the last log entry
|
||||
$parts = explode(' : ', $lastLine);
|
||||
if (!isset($parts[0])) continue;
|
||||
|
||||
$lastAccess = DateTime::createFromFormat('Y-m-d H:i:s', trim($parts[0]));
|
||||
if (!$lastAccess) continue;
|
||||
|
||||
// Calculate the idle time in seconds
|
||||
$now = new DateTime();
|
||||
$interval = $now->getTimestamp() - $lastAccess->getTimestamp();
|
||||
$now = time();
|
||||
$interval = $now - $lastModified;
|
||||
|
||||
// Check if the container has been idle for longer than the threshold
|
||||
if ($interval > $thresholdMinutes * 60) {
|
||||
@@ -49,20 +41,7 @@ foreach (glob($logDir . '/*.txt') as $filePath) {
|
||||
echo "Container $containerName does not exist.\n";
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
// Handle any errors that occur while stopping the container
|
||||
echo "Error stopping $containerName: " . $e->getMessage() . "\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the last non-empty line from a file.
|
||||
*
|
||||
* @param string $filePath Path to the file.
|
||||
* @return string|null The last line, or null if the file is empty.
|
||||
*/
|
||||
function getLastLine(string $filePath): ?string
|
||||
{
|
||||
$lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
|
||||
return $lines ? end($lines) : null;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user