forked from urvishpatelce/lxd-app
feat: change structure
This commit is contained in:
Executable
+68
@@ -0,0 +1,68 @@
|
||||
<?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 = realpath(__DIR__ . '/../../public/last-access-logs'); // Adjust if you're in /app/src/Cron or similar
|
||||
|
||||
// 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 line from the log file
|
||||
$lastLine = getLastLine($filePath);
|
||||
if (!$lastLine) {
|
||||
echo "No access logs found 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();
|
||||
|
||||
// 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) {
|
||||
// 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