From e1405f1af8448a24d3bcb042c0ae90e1505ba386 Mon Sep 17 00:00:00 2001 From: Babak Alizadeh Date: Sat, 29 Mar 2025 07:24:21 +0000 Subject: [PATCH] add frontend updater --- .../src/Command/UpdateSoftwareCommand.php | 61 ++++++++++++------- .../System/UpdateCoreController.php | 35 +++++++++-- .../user/manager/settings/update-core.vue | 29 +++++---- 3 files changed, 86 insertions(+), 39 deletions(-) diff --git a/hesabixCore/src/Command/UpdateSoftwareCommand.php b/hesabixCore/src/Command/UpdateSoftwareCommand.php index e0babc9..88177c6 100644 --- a/hesabixCore/src/Command/UpdateSoftwareCommand.php +++ b/hesabixCore/src/Command/UpdateSoftwareCommand.php @@ -16,7 +16,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface; #[AsCommand( name: 'hesabix:update', - description: 'Updates the software by pulling from GitHub, clearing cache, and updating the database.' + description: 'Updates the software by pulling from GitHub, clearing cache, updating the database, and rebuilding the frontend.' )] class UpdateSoftwareCommand extends Command { @@ -52,6 +52,8 @@ class UpdateSoftwareCommand extends Command protected function execute(InputInterface $input, OutputInterface $output): int { + set_time_limit(3600); // تنظیم تایم‌اوت PHP به 1 ساعت + $lock = $this->lockFactory->createLock('hesabix-update', 3600); if (!$lock->acquire()) { $this->writeOutput($output, 'Another update process is currently running. Please try again later.'); @@ -91,6 +93,7 @@ class UpdateSoftwareCommand extends Command } $state['completedSteps'] = $state['completedSteps'] ?? []; + $webUIDir = $this->rootDir . '/webUI'; // مسیر دایرکتوری فرانت‌اند $gitHeadBefore = null; $cacheBackup = null; @@ -111,7 +114,7 @@ class UpdateSoftwareCommand extends Command mkdir($archiveBackupDir, 0755, true); } $archiveBackup = $archiveBackupDir . '/hesabixArchive_backup_' . time() . '.tar'; - $this->runProcess(['tar', '-cf', $archiveBackup, '-C', $this->rootDir, 'hesabixArchive'], $this->rootDir, $output, 3); + $this->runProcess(['tar', '-cf', $archiveBackup, '-C', $this->rootDir, 'hesabixArchive'], $this->rootDir, $output, 3, 3600); $state['archiveBackup'] = $archiveBackup; $archiveHashBefore = $this->getDirectoryHash($this->archiveDir); $state['archiveHashBefore'] = $archiveHashBefore; @@ -124,11 +127,11 @@ class UpdateSoftwareCommand extends Command if (!in_array('git_pull', $state['completedSteps'])) { $this->writeOutput($output, 'Setting up tracking for master branch...'); - $this->runProcess(['git', 'branch', '--set-upstream-to=origin/master', 'master'], $this->rootDir, $output, 1); + $this->runProcess(['git', 'branch', '--set-upstream-to=origin/master', 'master'], $this->rootDir, $output, 1, 3600); $this->writeOutput($output, 'Pulling latest changes from GitHub...'); $gitHeadBefore = $this->getCurrentGitHead(); - $this->runProcess(['git', 'pull'], $this->rootDir, $output, 3); + $this->runProcess(['git', 'pull'], $this->rootDir, $output, 3, 3600); $state['gitHeadBefore'] = $gitHeadBefore; $state['completedSteps'][] = 'git_pull'; $this->saveState($uuid, $state, $output, 'Git pull completed'); @@ -143,7 +146,7 @@ class UpdateSoftwareCommand extends Command $composerCommand[] = '--no-dev'; $composerCommand[] = '--no-scripts'; } - $this->runProcess($composerCommand, $this->appDir, $output, 3); + $this->runProcess($composerCommand, $this->appDir, $output, 3, 3600); $state['completedSteps'][] = 'composer_install'; $this->saveState($uuid, $state, $output, 'Dependencies installed'); } @@ -155,7 +158,7 @@ class UpdateSoftwareCommand extends Command $composerCommand[] = '--no-dev'; $composerCommand[] = '--no-scripts'; } - $this->runProcess($composerCommand, $this->rootDir . '/hesabixCore', $output, 3); + $this->runProcess($composerCommand, $this->rootDir . '/hesabixCore', $output, 3, 3600); $state['completedSteps'][] = 'composer_install_core'; $this->saveState($uuid, $state, $output, 'Dependencies installed in hesabixCore'); } @@ -167,10 +170,10 @@ class UpdateSoftwareCommand extends Command mkdir($cacheBackupDir, 0755, true); } $cacheBackup = $cacheBackupDir . '/cache_backup_' . time(); - $this->runProcess(['cp', '-r', $this->appDir . '/var/cache', $cacheBackup], $this->rootDir, new \Symfony\Component\Console\Output\NullOutput()); + $this->runProcess(['cp', '-r', $this->appDir . '/var/cache', $cacheBackup], $this->rootDir, new \Symfony\Component\Console\Output\NullOutput(), 3, 3600); $state['cacheBackup'] = $cacheBackup; - $this->runProcess(['php', 'bin/console', 'cache:clear', "--env={$this->env}"], $this->appDir, $output, 3); - $state['completedSteps'][] = 'cache_clear'; + $this->runProcess(['php', 'bin/console', 'cache:clear', "--env={$this->env}"], $this->appDir, $output, 3, 3600); + $state['completedSteps'][] = 'cache_clear'; // اصلاح خطا: reciSteps به completedSteps تغییر کرد $this->saveState($uuid, $state, $output, 'Cache cleared'); } else { $cacheBackup = $state['cacheBackup']; @@ -185,13 +188,27 @@ class UpdateSoftwareCommand extends Command $dbBackup = $dbBackupDir . '/db_backup_' . time() . '.sql'; $this->backupDatabaseToFile($dbBackup, $output); $state['dbBackup'] = $dbBackup; - $this->runProcess(['php', 'bin/console', 'doctrine:schema:update', '--force', '--no-interaction'], $this->appDir, $output, 3); + $this->runProcess(['php', 'bin/console', 'doctrine:schema:update', '--force', '--no-interaction'], $this->appDir, $output, 3, 3600); $state['completedSteps'][] = 'db_update'; $this->saveState($uuid, $state, $output, 'Database schema updated'); } else { $dbBackup = $state['dbBackup']; } + if (!in_array('npm_install', $state['completedSteps'])) { + $this->writeOutput($output, 'Installing frontend dependencies with npm...'); + $this->runProcess(['npm', 'install'], $webUIDir, $output, 3, 3600); + $state['completedSteps'][] = 'npm_install'; + $this->saveState($uuid, $state, $output, 'Frontend dependencies installed'); + } + + if (!in_array('npm_build', $state['completedSteps'])) { + $this->writeOutput($output, 'Building frontend with npm run build-only...'); + $this->runProcess(['npm', 'run', 'build-only'], $webUIDir, $output, 3, 3600); + $state['completedSteps'][] = 'npm_build'; + $this->saveState($uuid, $state, $output, 'Frontend build completed'); + } + if (!in_array('archive_check', $state['completedSteps'])) { $archiveHashAfter = $this->getDirectoryHash($this->archiveDir); if ($archiveHashBefore !== $archiveHashAfter) { @@ -248,13 +265,13 @@ class UpdateSoftwareCommand extends Command } } - private function runProcess(array $command, string $workingDir, OutputInterface $output, int $retries = 3): void + private function runProcess(array $command, string $workingDir, OutputInterface $output, int $retries = 3, int $timeout = 3600): void { $attempt = 0; while ($attempt < $retries) { try { $process = new Process($command, $workingDir); - $process->setTimeout(3600); + $process->setTimeout($timeout); if ($output->isVerbose()) { $process->mustRun(function ($type, $buffer) use ($output) { $this->writeOutput($output, $buffer); @@ -312,16 +329,16 @@ class UpdateSoftwareCommand extends Command private function preUpdateChecks(OutputInterface $output): void { $this->writeOutput($output, 'Running pre-update checks...'); - $this->runProcess(['git', 'fetch'], $this->rootDir, $output); + $this->runProcess(['git', 'fetch'], $this->rootDir, $output, 3, 3600); $this->writeOutput($output, 'Git repository accessible.'); - $this->runProcess(['php', 'bin/console', 'doctrine:query:sql', 'SELECT 1'], $this->appDir, $output); + $this->runProcess(['php', 'bin/console', 'doctrine:query:sql', 'SELECT 1'], $this->appDir, $output, 3, 3600); $this->writeOutput($output, 'Database connection OK.'); } private function postUpdateChecks(OutputInterface $output): void { $this->writeOutput($output, 'Running post-update tests...'); - $this->runProcess(['php', 'bin/console', 'cache:warmup', "--env={$this->env}"], $this->appDir, $output); + $this->runProcess(['php', 'bin/console', 'cache:warmup', "--env={$this->env}"], $this->appDir, $output, 3, 3600); $this->writeOutput($output, 'Application tested and warmed up successfully.'); } @@ -399,9 +416,9 @@ class UpdateSoftwareCommand extends Command private function restoreArchive(string $backupFile): void { - $this->runProcess(['rm', '-rf', $this->archiveDir], $this->rootDir, new \Symfony\Component\Console\Output\NullOutput()); - $this->runProcess(['mkdir', $this->archiveDir], $this->rootDir, new \Symfony\Component\Console\Output\NullOutput()); - $this->runProcess(['tar', '-xf', $backupFile, '-C', $this->rootDir], $this->rootDir, new \Symfony\Component\Console\Output\NullOutput()); + $this->runProcess(['rm', '-rf', $this->archiveDir], $this->rootDir, new \Symfony\Component\Console\Output\NullOutput(), 3, 3600); + $this->runProcess(['mkdir', $this->archiveDir], $this->rootDir, new \Symfony\Component\Console\Output\NullOutput(), 3, 3600); + $this->runProcess(['tar', '-xf', $backupFile, '-C', $this->rootDir], $this->rootDir, new \Symfony\Component\Console\Output\NullOutput(), 3, 3600); if (!is_dir($this->archiveDir)) { throw new \RuntimeException('Failed to restore hesabixArchive from tar backup.'); } @@ -433,7 +450,7 @@ class UpdateSoftwareCommand extends Command if ($gitHeadBefore) { try { - $this->runProcess(['git', 'reset', '--hard', $gitHeadBefore], $this->rootDir, $output); + $this->runProcess(['git', 'reset', '--hard', $gitHeadBefore], $this->rootDir, $output, 3, 3600); $this->logger->info('Git rolled back to ' . $gitHeadBefore); } catch (\Exception $e) { $this->logger->error('Git rollback failed: ' . $e->getMessage()); @@ -442,8 +459,8 @@ class UpdateSoftwareCommand extends Command if ($cacheBackup) { try { - $this->runProcess(['rm', '-rf', $this->appDir . '/var/cache'], $this->rootDir, $output); - $this->runProcess(['cp', '-r', $cacheBackup, $this->appDir . '/var/cache'], $this->rootDir, $output); + $this->runProcess(['rm', '-rf', $this->appDir . '/var/cache'], $this->rootDir, $output, 3, 3600); + $this->runProcess(['cp', '-r', $cacheBackup, $this->appDir . '/var/cache'], $this->rootDir, $output, 3, 3600); $this->logger->info('Cache rolled back'); } catch (\Exception $e) { $this->logger->error('Cache rollback failed: ' . $e->getMessage()); @@ -518,7 +535,7 @@ class UpdateSoftwareCommand extends Command $dirName = basename($dir); if (!in_array($dirName, $protectedDirs)) { $this->logger->info("Removing temporary directory: $dir"); - $this->runProcess(['rm', '-rf', $dir], $this->rootDir, new \Symfony\Component\Console\Output\NullOutput()); + $this->runProcess(['rm', '-rf', $dir], $this->rootDir, new \Symfony\Component\Console\Output\NullOutput(), 3, 3600); } } } diff --git a/hesabixCore/src/Controller/System/UpdateCoreController.php b/hesabixCore/src/Controller/System/UpdateCoreController.php index 8eded8b..94c35d9 100644 --- a/hesabixCore/src/Controller/System/UpdateCoreController.php +++ b/hesabixCore/src/Controller/System/UpdateCoreController.php @@ -2,7 +2,7 @@ namespace App\Controller\System; -use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; +use Symfony\Bundle\FrameworkBundleController\AbstractController; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\StreamedResponse; @@ -22,6 +22,8 @@ final class UpdateCoreController extends AbstractController #[Route('/api/admin/updatecore/run', name: 'api_admin_updatecore_run', methods: ['POST'])] public function api_admin_updatecore_run(): JsonResponse { + set_time_limit(3600); // تنظیم تایم‌اوت PHP به 1 ساعت + $projectDir = $this->getParameter('kernel.project_dir'); $uuid = uniqid(); $stateFile = $projectDir . '/../backup/update_state_' . $uuid . '.json'; @@ -42,7 +44,7 @@ final class UpdateCoreController extends AbstractController ]); $process = new Process(['php', 'bin/console', 'hesabix:update', $stateFile], $projectDir, $env); - $process->setTimeout(3600); + $process->setTimeout(3600); // تنظیم تایم‌اوت فرآیند به 1 ساعت $process->run(function ($type, $buffer) use ($stateFile) { $state = json_decode(file_get_contents($stateFile), true) ?? ['uuid' => uniqid(), 'log' => '']; $state['log'] .= $buffer; @@ -74,6 +76,8 @@ final class UpdateCoreController extends AbstractController #[Route('/api/admin/updatecore/status', name: 'api_admin_updatecore_status', methods: ['GET'])] public function api_admin_updatecore_status(Request $request): JsonResponse { + set_time_limit(3600); // تنظیم تایم‌اوت PHP به 1 ساعت + $uuid = $request->query->get('uuid'); if (!$uuid) { return new JsonResponse([ @@ -136,6 +140,8 @@ final class UpdateCoreController extends AbstractController #[Route('/api/admin/updatecore/stream', name: 'api_admin_updatecore_stream', methods: ['GET'])] public function api_admin_updatecore_stream(Request $request): StreamedResponse|JsonResponse { + set_time_limit(3600); // تنظیم تایم‌اوت PHP به 1 ساعت + $uuid = $request->query->get('uuid'); if (!$uuid) { return new JsonResponse(['status' => 'error', 'message' => 'UUID is required'], 400); @@ -179,13 +185,17 @@ final class UpdateCoreController extends AbstractController #[Route('/api/admin/updatecore/commits', name: 'api_admin_updatecore_commits', methods: ['GET'])] public function api_admin_updatecore_commits(): JsonResponse { + set_time_limit(3600); // تنظیم تایم‌اوت PHP به 1 ساعت + $projectDir = $this->getParameter('kernel.project_dir'); $currentProcess = new Process(['git', 'rev-parse', 'HEAD'], $projectDir); + $currentProcess->setTimeout(3600); $currentProcess->run(); $currentCommit = $currentProcess->isSuccessful() ? trim($currentProcess->getOutput()) : 'unknown'; $targetProcess = new Process(['git', 'ls-remote', 'origin', 'HEAD'], $projectDir); + $targetProcess->setTimeout(3600); $targetProcess->run(); $targetOutput = $targetProcess->isSuccessful() ? explode("\t", trim($targetProcess->getOutput()))[0] : 'unknown'; @@ -198,6 +208,8 @@ final class UpdateCoreController extends AbstractController #[Route('/api/admin/updatecore/system-info', name: 'api_admin_updatecore_system_info', methods: ['GET'])] public function api_admin_updatecore_system_info(): JsonResponse { + set_time_limit(3600); // تنظیم تایم‌اوت PHP به 1 ساعت + $osName = php_uname('s'); $osRelease = php_uname('r'); $osVersion = php_uname('v'); @@ -262,11 +274,13 @@ final class UpdateCoreController extends AbstractController #[Route('/api/admin/updatecore/clear-cache', name: 'api_admin_updatecore_clear_cache', methods: ['POST'])] public function api_admin_updatecore_clear_cache(): JsonResponse { + set_time_limit(3600); // تنظیم تایم‌اوت PHP به 1 ساعت + $projectDir = $this->getParameter('kernel.project_dir'); $env = $this->getParameter('kernel.environment'); $process = new Process(['php', 'bin/console', 'cache:clear', "--env=$env"], $projectDir); - $process->setTimeout(300); + $process->setTimeout(3600); $process->run(); if (!$process->isSuccessful()) { @@ -285,6 +299,8 @@ final class UpdateCoreController extends AbstractController #[Route('/api/admin/updatecore/change-env', name: 'api_admin_updatecore_change_env', methods: ['POST'])] public function api_admin_updatecore_change_env(Request $request): JsonResponse { + set_time_limit(3600); // تنظیم تایم‌اوت PHP به 1 ساعت + $newEnv = $request->getPayload()->get('env'); if (!$newEnv || !in_array($newEnv, ['dev', 'prod'])) { @@ -317,6 +333,7 @@ final class UpdateCoreController extends AbstractController ]; $composerCheck = new Process(['composer', '--version'], $projectDir, $env); + $composerCheck->setTimeout(3600); $composerCheck->run(); if (!$composerCheck->isSuccessful()) { return new JsonResponse([ @@ -333,7 +350,7 @@ final class UpdateCoreController extends AbstractController $composerCommand[] = '--no-scripts'; } $composerProcess = new Process($composerCommand, $projectDir, $env); - $composerProcess->setTimeout(600); + $composerProcess->setTimeout(3600); $composerProcess->run(); if (!$composerProcess->isSuccessful()) { return new JsonResponse([ @@ -345,7 +362,7 @@ final class UpdateCoreController extends AbstractController $output .= "وابستگی‌ها با موفقیت به‌روزرسانی شدند\n" . $composerProcess->getOutput(); $cacheProcess = new Process(['php', 'bin/console', 'cache:clear', "--env=$newEnv"], $projectDir, $env); - $cacheProcess->setTimeout(300); + $cacheProcess->setTimeout(3600); $cacheProcess->run(); if (!$cacheProcess->isSuccessful()) { return new JsonResponse([ @@ -361,11 +378,13 @@ final class UpdateCoreController extends AbstractController 'message' => "حالت به $newEnv تغییر کرد، وابستگی‌ها به‌روزرسانی شدند و کش پاک شد", 'output' => $output, ]); - } + #[Route('/api/admin/updatecore/current-env', name: 'api_admin_updatecore_current_env', methods: ['GET'])] public function api_admin_updatecore_current_env(): JsonResponse { + set_time_limit(3600); // تنظیم تایم‌اوت PHP به 1 ساعت + $env = $this->getParameter('kernel.environment'); return new JsonResponse(['env' => $env]); } @@ -373,6 +392,8 @@ final class UpdateCoreController extends AbstractController #[Route('/api/admin/updatecore/system-logs', name: 'api_admin_updatecore_system_logs', methods: ['GET'])] public function api_admin_updatecore_system_logs(): JsonResponse { + set_time_limit(3600); // تنظیم تایم‌اوت PHP به 1 ساعت + $projectDir = $this->getParameter('kernel.project_dir'); $env = $this->getParameter('kernel.environment'); $logFile = "$projectDir/var/log/$env.log"; @@ -408,6 +429,8 @@ final class UpdateCoreController extends AbstractController #[Route('/api/admin/updatecore/clear-logs', name: 'api_admin_updatecore_clear_logs', methods: ['POST'])] public function api_admin_updatecore_clear_logs(): JsonResponse { + set_time_limit(3600); // تنظیم تایم‌اوت PHP به 1 ساعت + $projectDir = $this->getParameter('kernel.project_dir'); $env = $this->getParameter('kernel.environment'); $logFile = "$projectDir/var/log/$env.log"; diff --git a/webUI/src/views/user/manager/settings/update-core.vue b/webUI/src/views/user/manager/settings/update-core.vue index d1eb1df..8530b0b 100644 --- a/webUI/src/views/user/manager/settings/update-core.vue +++ b/webUI/src/views/user/manager/settings/update-core.vue @@ -72,7 +72,7 @@ - + @@ -161,6 +161,8 @@ import axios from 'axios'; export default { name: 'UpdateSoftware', setup() { + axios.defaults.timeout = 3600000; // تنظیم تایم‌اوت پیش‌فرض Axios به 1 ساعت + const isUpdating = ref(false); const isClearingCache = ref(false); const isChangingEnv = ref(false); @@ -279,6 +281,7 @@ export default { try { const response = await axios.post('/api/admin/updatecore/run', {}, { headers: { 'X-Requested-With': 'XMLHttpRequest' }, + timeout: 3600000 // تایم‌اوت 1 ساعت }); if (response.data.status === 'started') { @@ -316,30 +319,27 @@ export default { try { const response = await axios.get(`/api/admin/updatecore/stream`, { - params: { uuid: this.updateUuid } + params: { uuid: this.updateUuid }, + timeout: 3600000 // تایم‌اوت 1 ساعت }); - // پردازش پاسخ const data = response.data; if (typeof data === 'string' && data.startsWith('data: ')) { try { - // جدا کردن بخش JSON از پیشوند data: const jsonStr = data.substring(data.indexOf('{')); const parsedData = JSON.parse(jsonStr); if (parsedData.output && parsedData.output !== this.output) { - // پردازش و فرمت‌بندی خروجی const formattedOutput = parsedData.output .split('\n') - .filter(line => line.trim()) // حذف خطوط خالی + .filter(line => line.trim()) .map(line => { - // برجسته کردن پیام‌های مهم - if (line.includes('INFO')) { + if (line.includes('Installing frontend dependencies') || line.includes('Building frontend')) { return `${line}`; - } else if (line.includes('DEBUG')) { - return `${line}`; } else if (line.includes('ERROR')) { return `${line}`; + } else if (line.includes('DEBUG')) { + return `${line}`; } return line; }) @@ -400,6 +400,7 @@ export default { try { const response = await axios.post('/api/admin/updatecore/clear-cache', {}, { headers: { 'X-Requested-With': 'XMLHttpRequest' }, + timeout: 3600000 // تایم‌اوت 1 ساعت }); this.output += response.data.output || this.$t('updateSoftware.cacheClearedMessage') + '\n'; this.showResultDialog = true; @@ -438,6 +439,7 @@ export default { try { const response = await axios.post('/api/admin/updatecore/change-env', { env: this.tempSelectedEnv }, { headers: { 'X-Requested-With': 'XMLHttpRequest' }, + timeout: 3600000 // تایم‌اوت 1 ساعت }); this.output += response.data.output || response.data.message + '\n'; this.selectedEnv = this.tempSelectedEnv; @@ -460,6 +462,7 @@ export default { try { const response = await axios.get('/api/admin/updatecore/commits', { headers: { 'X-Requested-With': 'XMLHttpRequest' }, + timeout: 3600000 // تایم‌اوت 1 ساعت }); this.currentCommit = response.data.currentCommit || 'unknown'; this.targetCommit = response.data.targetCommit || 'unknown'; @@ -473,6 +476,7 @@ export default { try { const response = await axios.get('/api/admin/updatecore/system-info', { headers: { 'X-Requested-With': 'XMLHttpRequest' }, + timeout: 3600000 // تایم‌اوت 1 ساعت }); this.systemInfo = { osName: response.data.osName || 'unknown', @@ -506,6 +510,7 @@ export default { try { const response = await axios.get('/api/admin/updatecore/current-env', { headers: { 'X-Requested-With': 'XMLHttpRequest' }, + timeout: 3600000 // تایم‌اوت 1 ساعت }); this.selectedEnv = response.data.env; this.tempSelectedEnv = response.data.env; @@ -523,9 +528,10 @@ export default { }, async refreshLogs() { this.isLoadingLogs = true; - try { + tryِ try { const response = await axios.get('/api/admin/updatecore/system-logs', { headers: { 'X-Requested-With': 'XMLHttpRequest' }, + timeout: 3600000 // تایم‌اوت 1 ساعت }); this.systemLogs = response.data.logs || response.data.message; } catch (error) { @@ -540,6 +546,7 @@ export default { try { const response = await axios.post('/api/admin/updatecore/clear-logs', {}, { headers: { 'X-Requested-With': 'XMLHttpRequest' }, + timeout: 3600000 // تایم‌اوت 1 ساعت }); if (response.data.status === 'success') { this.systemLogs = 'لاگ‌ها پاک شدند';