Merge pull request from gnuboard:HeuJung/issue445
HeuJung/issue445
This commit is contained in:
commit
94d2cd2c11
10 files changed
+552
-37
No files matched your search
@@ -20,6 +20,8 @@
|
|||||||
### Fixed
|
### Fixed
|
||||||
|
|
||||||
- 코어 업데이트 시 레이아웃 편집기·개발자 진단도구 번들의 빌드 설정 파일이 갱신 대상에서 누락되던 문제를 수정했습니다. 이제 코어를 업데이트하면 이 파일들도 최신 내용으로 반영됩니다.
|
- 코어 업데이트 시 레이아웃 편집기·개발자 진단도구 번들의 빌드 설정 파일이 갱신 대상에서 누락되던 문제를 수정했습니다. 이제 코어를 업데이트하면 이 파일들도 최신 내용으로 반영됩니다.
|
||||||
|
- 설치 마법사에서 Vendor 설치 방식을 "Composer 실행"으로 선택해 설치할 때, 일부 Windows 환경에서 Composer 설치 로그의 문자 인코딩이 어긋나면 진행 상태 응답이 비어 진행 상황이 표시되지 않고 오류가 반복될 수 있던 문제를 보완했습니다. 어떤 문자가 섞이더라도 진행 로그가 항상 정상적으로 전달되도록 처리했습니다. (#62 @kitrio 님께서 제보해주셨습니다.)
|
||||||
|
- 설치 마법사의 "설치 환경 확인" 단계에서, storage 폴더 하위에 파일이 많이 쌓인 환경일수록 요구사항 검사가 오래 걸리던 문제를 개선했습니다. 폴더 쓰기 권한 검사가 불필요하게 깊은 하위까지 훑던 것을 필요한 범위로 제한해 이 단계가 즉시 완료되도록 했습니다.
|
||||||
|
|
||||||
## [7.0.1] - 2026-07-03
|
## [7.0.1] - 2026-07-03
|
||||||
|
|
||||||
|
|||||||
@@ -138,7 +138,28 @@ class StateManagementApi
|
|||||||
];
|
];
|
||||||
|
|
||||||
// JSON 응답 반환
|
// JSON 응답 반환
|
||||||
echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
|
//
|
||||||
|
// 최종 안전망 (gnuboard/g7#62): $response['logs'] 에 invalid UTF-8 바이트가
|
||||||
|
// 섞이면 json_encode 가 false 를 반환하고 echo false = 빈 본문(HTTP 200) 이 되어
|
||||||
|
// 프론트 폴링(res.json())이 "Unexpected end of JSON input" 으로 폭주한다.
|
||||||
|
// 로그는 addLog / task-runner 에서 이미 scrub 되지만, 어떤 경로로도 응답이
|
||||||
|
// 빈 본문이 되지 않도록 JSON_INVALID_UTF8_SUBSTITUTE 로 치환하고 false 를 가드한다.
|
||||||
|
$encoded = json_encode(
|
||||||
|
$response,
|
||||||
|
JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_INVALID_UTF8_SUBSTITUTE
|
||||||
|
);
|
||||||
|
|
||||||
|
if ($encoded === false) {
|
||||||
|
// substitute 플래그로도 인코딩 실패한 극단적 케이스 — 폴링이 파싱 가능한
|
||||||
|
// 최소 유효 JSON 을 반환해 프론트가 다음 tick 에서 정상 복구되도록 한다.
|
||||||
|
$encoded = json_encode([
|
||||||
|
'status' => $status,
|
||||||
|
'logs' => [],
|
||||||
|
'log_total' => $logTotal,
|
||||||
|
], JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
|
||||||
|
}
|
||||||
|
|
||||||
|
echo $encoded;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -5,8 +5,6 @@
|
|||||||
*
|
*
|
||||||
* HTML/JavaScript 이스케이프, 데이터베이스 연결, 권한 검증, 에러 로깅 등의
|
* HTML/JavaScript 이스케이프, 데이터베이스 연결, 권한 검증, 에러 로깅 등의
|
||||||
* 공통 유틸리티 함수를 제공합니다.
|
* 공통 유틸리티 함수를 제공합니다.
|
||||||
*
|
|
||||||
* @package G7\Installer
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -47,6 +45,7 @@ function js_escape(mixed $value): string
|
|||||||
*
|
*
|
||||||
* @param array $config 데이터베이스 연결 정보 배열
|
* @param array $config 데이터베이스 연결 정보 배열
|
||||||
* @param bool $isReadDb Read DB 여부 (true: read, false: write)
|
* @param bool $isReadDb Read DB 여부 (true: read, false: write)
|
||||||
|
*
|
||||||
* @throws PDOException 연결 실패 시
|
* @throws PDOException 연결 실패 시
|
||||||
*/
|
*/
|
||||||
function getDatabaseConnection(array $config, bool $isReadDb = false): PDO
|
function getDatabaseConnection(array $config, bool $isReadDb = false): PDO
|
||||||
@@ -212,7 +211,7 @@ function logInstallationError(string $message, ?Throwable $exception = null): vo
|
|||||||
|
|
||||||
if ($exception !== null) {
|
if ($exception !== null) {
|
||||||
$logMessage .= "\n";
|
$logMessage .= "\n";
|
||||||
$logMessage .= "Exception: " . get_class($exception) . "\n";
|
$logMessage .= 'Exception: '.get_class($exception)."\n";
|
||||||
$logMessage .= "Message: {$exception->getMessage()}\n";
|
$logMessage .= "Message: {$exception->getMessage()}\n";
|
||||||
$logMessage .= "File: {$exception->getFile()}:{$exception->getLine()}\n";
|
$logMessage .= "File: {$exception->getFile()}:{$exception->getLine()}\n";
|
||||||
$logMessage .= "Trace:\n{$exception->getTraceAsString()}\n";
|
$logMessage .= "Trace:\n{$exception->getTraceAsString()}\n";
|
||||||
@@ -399,7 +398,7 @@ function getTaskName(string $task): string
|
|||||||
function redirectToStep(int $step): void
|
function redirectToStep(int $step): void
|
||||||
{
|
{
|
||||||
$_SESSION['installer_current_step'] = $step;
|
$_SESSION['installer_current_step'] = $step;
|
||||||
header("Location: " . INSTALLER_BASE_URL . "/");
|
header('Location: '.INSTALLER_BASE_URL.'/');
|
||||||
exit;
|
exit;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -455,6 +454,7 @@ function updateStepStatus(int $step, int $nextStep, array $additionalData = []):
|
|||||||
function isInstallationRunning(): bool
|
function isInstallationRunning(): bool
|
||||||
{
|
{
|
||||||
$state = getInstallationState();
|
$state = getInstallationState();
|
||||||
|
|
||||||
return isset($state['installation_status']) && $state['installation_status'] === 'running';
|
return isset($state['installation_status']) && $state['installation_status'] === 'running';
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -575,7 +575,7 @@ function getDatabaseFieldHash(array $config, string $prefix): string
|
|||||||
$config["{$prefix}_host"] ?? '',
|
$config["{$prefix}_host"] ?? '',
|
||||||
$config["{$prefix}_port"] ?? '',
|
$config["{$prefix}_port"] ?? '',
|
||||||
$config["{$prefix}_database"] ?? '',
|
$config["{$prefix}_database"] ?? '',
|
||||||
$config["{$prefix}_username"] ?? ''
|
$config["{$prefix}_username"] ?? '',
|
||||||
]));
|
]));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -693,6 +693,7 @@ function renderProgressIndicator(int $currentStep, int $totalSteps = 7): string
|
|||||||
$html .= '<div class="'.$class.'"></div>';
|
$html .= '<div class="'.$class.'"></div>';
|
||||||
}
|
}
|
||||||
$html .= '</div>';
|
$html .= '</div>';
|
||||||
|
|
||||||
return $html;
|
return $html;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -934,10 +935,18 @@ function checkDirectoryPermissions(array $directories): array
|
|||||||
/**
|
/**
|
||||||
* 디렉토리의 하위를 재귀적으로 체크하여 권한이 없는 경로와 권한 정보 반환
|
* 디렉토리의 하위를 재귀적으로 체크하여 권한이 없는 경로와 권한 정보 반환
|
||||||
*
|
*
|
||||||
|
* 깊이 제한(maxDepth)을 둔다 (dev-g7#445 후속): storage 처럼 하위에 수만 개
|
||||||
|
* 디렉토리가 누적되는 경로(예: storage/framework/testing/)를 무한 재귀로 순회하면
|
||||||
|
* 인스톨러 2단계(요구사항 검증) 응답이 수 초 이상 지연된다. 쓰기 권한 문제는 트리
|
||||||
|
* 상위 얕은 깊이에서 결정되므로(상위가 쓰기 가능하면 하위도 통상 상속), 제한 깊이까지만
|
||||||
|
* 검사해 성능과 안내 유효성을 모두 확보한다.
|
||||||
|
*
|
||||||
* @param string $path 체크할 디렉토리 경로
|
* @param string $path 체크할 디렉토리 경로
|
||||||
|
* @param int $maxDepth 재귀 최대 깊이 (0 = 현재 디렉토리의 직속 하위만). 기본 1
|
||||||
|
* @param int $currentDepth 내부 재귀용 현재 깊이 (호출자는 지정하지 않음)
|
||||||
* @return array<array{path: string, permissions: string}> 권한이 없는 하위 디렉토리 정보 배열
|
* @return array<array{path: string, permissions: string}> 권한이 없는 하위 디렉토리 정보 배열
|
||||||
*/
|
*/
|
||||||
function checkSubdirectoriesRecursive(string $path): array
|
function checkSubdirectoriesRecursive(string $path, int $maxDepth = 1, int $currentDepth = 0): array
|
||||||
{
|
{
|
||||||
$failedPaths = [];
|
$failedPaths = [];
|
||||||
|
|
||||||
@@ -988,13 +997,17 @@ function checkSubdirectoriesRecursive(string $path): array
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 재귀적으로 하위 디렉토리 체크 (권한 없어도 계속 진행)
|
// 재귀적으로 하위 디렉토리 체크 (권한 없어도 계속 진행)
|
||||||
|
// 깊이 제한 도달 시 더 내려가지 않는다 — storage/framework/testing 등에 누적된
|
||||||
|
// 수만 개 하위 디렉토리를 순회해 인스톨러 2단계가 지연되던 문제 차단 (dev-g7#445 후속).
|
||||||
|
if ($currentDepth < $maxDepth) {
|
||||||
try {
|
try {
|
||||||
$subFailed = checkSubdirectoriesRecursive($itemPath);
|
$subFailed = checkSubdirectoriesRecursive($itemPath, $maxDepth, $currentDepth + 1);
|
||||||
$failedPaths = array_merge($failedPaths, $subFailed);
|
$failedPaths = array_merge($failedPaths, $subFailed);
|
||||||
} catch (Exception $e) {
|
} catch (Exception $e) {
|
||||||
// 하위 디렉토리 체크 실패해도 계속 진행
|
// 하위 디렉토리 체크 실패해도 계속 진행
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return $failedPaths;
|
return $failedPaths;
|
||||||
}
|
}
|
||||||
@@ -1189,7 +1202,6 @@ function getPermissionFixCommand(string $pathList, string $mode = 'ownership'):
|
|||||||
return 'chmod -R 755 '.$pathList;
|
return 'chmod -R 755 '.$pathList;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 기존 DB 테이블 감지.
|
* 기존 DB 테이블 감지.
|
||||||
*
|
*
|
||||||
@@ -1204,7 +1216,6 @@ function getPermissionFixCommand(string $pathList, string $mode = 'ownership'):
|
|||||||
*
|
*
|
||||||
* @param PDO $pdo 연결된 PDO 인스턴스
|
* @param PDO $pdo 연결된 PDO 인스턴스
|
||||||
* @param string $database 대상 데이터베이스명
|
* @param string $database 대상 데이터베이스명
|
||||||
* @return array
|
|
||||||
*/
|
*/
|
||||||
function checkExistingTables(PDO $pdo, string $database, string $tablePrefix = ''): array
|
function checkExistingTables(PDO $pdo, string $database, string $tablePrefix = ''): array
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -5,7 +5,6 @@
|
|||||||
*
|
*
|
||||||
* 설치 진행 상태를 storage/installer-state.json에 저장하고 조회합니다.
|
* 설치 진행 상태를 storage/installer-state.json에 저장하고 조회합니다.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
if (! defined('BASE_PATH')) {
|
if (! defined('BASE_PATH')) {
|
||||||
define('BASE_PATH', realpath(dirname(__DIR__, 3)) ?: dirname(__DIR__, 3)); // public/install/includes에서 프로젝트 루트로
|
define('BASE_PATH', realpath(dirname(__DIR__, 3)) ?: dirname(__DIR__, 3)); // public/install/includes에서 프로젝트 루트로
|
||||||
}
|
}
|
||||||
@@ -42,9 +41,10 @@ function getInstallationState(): array
|
|||||||
|
|
||||||
// 파일 읽기 권한 체크
|
// 파일 읽기 권한 체크
|
||||||
if (! is_readable(STATE_PATH)) {
|
if (! is_readable(STATE_PATH)) {
|
||||||
$msg = "[installer-state] State file is not readable: " . STATE_PATH;
|
$msg = '[installer-state] State file is not readable: '.STATE_PATH;
|
||||||
error_log($msg);
|
error_log($msg);
|
||||||
addLog($msg);
|
addLog($msg);
|
||||||
|
|
||||||
return $defaultState;
|
return $defaultState;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -53,9 +53,10 @@ function getInstallationState(): array
|
|||||||
|
|
||||||
// 파일 읽기 실패 시 기본 상태 반환
|
// 파일 읽기 실패 시 기본 상태 반환
|
||||||
if ($content === false) {
|
if ($content === false) {
|
||||||
$msg = "[installer-state] Failed to read state file: " . STATE_PATH;
|
$msg = '[installer-state] Failed to read state file: '.STATE_PATH;
|
||||||
error_log($msg);
|
error_log($msg);
|
||||||
addLog($msg);
|
addLog($msg);
|
||||||
|
|
||||||
return $defaultState;
|
return $defaultState;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -65,9 +66,10 @@ function getInstallationState(): array
|
|||||||
if (json_last_error() !== JSON_ERROR_NONE) {
|
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||||
$contentLen = strlen($content);
|
$contentLen = strlen($content);
|
||||||
$preview = substr($content, 0, 200);
|
$preview = substr($content, 0, 200);
|
||||||
$msg = "[installer-state] Failed to parse state file JSON (length={$contentLen}): " . json_last_error_msg() . " / preview: " . $preview;
|
$msg = "[installer-state] Failed to parse state file JSON (length={$contentLen}): ".json_last_error_msg().' / preview: '.$preview;
|
||||||
error_log($msg);
|
error_log($msg);
|
||||||
addLog($msg);
|
addLog($msg);
|
||||||
|
|
||||||
return $defaultState;
|
return $defaultState;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -88,6 +90,7 @@ function saveInstallationState(array $state): bool
|
|||||||
$msg = "[installer-state] Storage directory does not exist: {$storageDir}";
|
$msg = "[installer-state] Storage directory does not exist: {$storageDir}";
|
||||||
error_log($msg);
|
error_log($msg);
|
||||||
addLog($msg);
|
addLog($msg);
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -96,6 +99,7 @@ function saveInstallationState(array $state): bool
|
|||||||
$msg = "[installer-state] Storage directory is not writable: {$storageDir}";
|
$msg = "[installer-state] Storage directory is not writable: {$storageDir}";
|
||||||
error_log($msg);
|
error_log($msg);
|
||||||
addLog($msg);
|
addLog($msg);
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -106,9 +110,10 @@ function saveInstallationState(array $state): bool
|
|||||||
$content = json_encode($state, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
$content = json_encode($state, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||||
|
|
||||||
if ($content === false) {
|
if ($content === false) {
|
||||||
$msg = "[installer-state] Failed to encode state as JSON: " . json_last_error_msg();
|
$msg = '[installer-state] Failed to encode state as JSON: '.json_last_error_msg();
|
||||||
error_log($msg);
|
error_log($msg);
|
||||||
addLog($msg);
|
addLog($msg);
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -119,20 +124,22 @@ function saveInstallationState(array $state): bool
|
|||||||
|
|
||||||
$result = @file_put_contents($tmpPath, $content, LOCK_EX);
|
$result = @file_put_contents($tmpPath, $content, LOCK_EX);
|
||||||
if ($result === false || $result !== strlen($content)) {
|
if ($result === false || $result !== strlen($content)) {
|
||||||
$msg = "[installer-state] Failed to write state tmp file: " . $tmpPath;
|
$msg = '[installer-state] Failed to write state tmp file: '.$tmpPath;
|
||||||
error_log($msg);
|
error_log($msg);
|
||||||
addLog($msg);
|
addLog($msg);
|
||||||
@unlink($tmpPath);
|
@unlink($tmpPath);
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@chmod($tmpPath, 0664);
|
@chmod($tmpPath, 0664);
|
||||||
|
|
||||||
if (! @rename($tmpPath, STATE_PATH)) {
|
if (! @rename($tmpPath, STATE_PATH)) {
|
||||||
$msg = "[installer-state] Failed to rename state tmp file: " . $tmpPath . ' → ' . STATE_PATH;
|
$msg = '[installer-state] Failed to rename state tmp file: '.$tmpPath.' → '.STATE_PATH;
|
||||||
error_log($msg);
|
error_log($msg);
|
||||||
addLog($msg);
|
addLog($msg);
|
||||||
@unlink($tmpPath);
|
@unlink($tmpPath);
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -398,6 +405,7 @@ function addLogBatch(array $messages): bool
|
|||||||
$msg = "[addLogBatch] Failed to create log directory: {$logDir}";
|
$msg = "[addLogBatch] Failed to create log directory: {$logDir}";
|
||||||
error_log($msg);
|
error_log($msg);
|
||||||
addLog($msg); // 재귀 가드가 차단하므로 안전 — error_log fallback 만 수행
|
addLog($msg); // 재귀 가드가 차단하므로 안전 — error_log fallback 만 수행
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -406,6 +414,7 @@ function addLogBatch(array $messages): bool
|
|||||||
$msg = "[addLogBatch] Log directory is not writable: {$logDir}";
|
$msg = "[addLogBatch] Log directory is not writable: {$logDir}";
|
||||||
error_log($msg);
|
error_log($msg);
|
||||||
addLog($msg); // 재귀 가드가 차단
|
addLog($msg); // 재귀 가드가 차단
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -435,6 +444,7 @@ function addLogBatch(array $messages): bool
|
|||||||
$msg = "[addLogBatch] Failed to open log file: {$logFile}";
|
$msg = "[addLogBatch] Failed to open log file: {$logFile}";
|
||||||
error_log($msg);
|
error_log($msg);
|
||||||
addLog($msg); // 재귀 가드가 차단
|
addLog($msg); // 재귀 가드가 차단
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
flock($handle, LOCK_EX);
|
flock($handle, LOCK_EX);
|
||||||
@@ -455,7 +465,8 @@ function addLog(string $message): bool
|
|||||||
static $inAddLog = false;
|
static $inAddLog = false;
|
||||||
if ($inAddLog) {
|
if ($inAddLog) {
|
||||||
// 재진입: installation.log 시도 skip, PHP error_log 만 호출하고 즉시 종료
|
// 재진입: installation.log 시도 skip, PHP error_log 만 호출하고 즉시 종료
|
||||||
error_log("[addLog reentrant] " . $message);
|
error_log('[addLog reentrant] '.$message);
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
$inAddLog = true;
|
$inAddLog = true;
|
||||||
@@ -488,6 +499,7 @@ function _addLogInternal(string $message): bool
|
|||||||
$msg = "[addLog] Failed to create log directory: {$logDir} (storage 권한 확인 필요)";
|
$msg = "[addLog] Failed to create log directory: {$logDir} (storage 권한 확인 필요)";
|
||||||
error_log($msg);
|
error_log($msg);
|
||||||
addLog($msg); // 재귀 가드가 차단 (본 함수는 이미 가드 안)
|
addLog($msg); // 재귀 가드가 차단 (본 함수는 이미 가드 안)
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -497,6 +509,7 @@ function _addLogInternal(string $message): bool
|
|||||||
$msg = "[addLog] Log directory is not writable: {$logDir}";
|
$msg = "[addLog] Log directory is not writable: {$logDir}";
|
||||||
error_log($msg);
|
error_log($msg);
|
||||||
addLog($msg); // 재귀 가드가 차단
|
addLog($msg); // 재귀 가드가 차단
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -508,6 +521,17 @@ function _addLogInternal(string $message): bool
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// OS 무관 최종 방어 — 항상 유효 UTF-8 만 로그에 저장한다 (gnuboard/g7#62).
|
||||||
|
// composer install 등 외부 프로세스 stdout 이 시스템 코드페이지로 출력되거나
|
||||||
|
// 진행바(\r 갱신)가 임의 바이트 경계에서 잘려 mb_detect_encoding 이 확정 감지에
|
||||||
|
// 실패한 경우(위 분기 미적용), invalid 바이트가 그대로 로그에 남으면
|
||||||
|
// 폴링 응답 state-management.php 의 json_encode 가 false 를 반환해 빈 본문(HTTP 200)
|
||||||
|
// → 프론트 res.json() 이 "Unexpected end of JSON input" 으로 폭주한다.
|
||||||
|
// mb_scrub 은 invalid 바이트를 U+FFFD 로 치환해 응답 무력화를 원천 차단한다.
|
||||||
|
if (! mb_check_encoding($message, 'UTF-8')) {
|
||||||
|
$message = mb_scrub($message, 'UTF-8');
|
||||||
|
}
|
||||||
|
|
||||||
// 타임스탬프와 함께 로그 작성 — millisecond 정밀도 (hang 진단 시 정확한 timing 필요)
|
// 타임스탬프와 함께 로그 작성 — millisecond 정밀도 (hang 진단 시 정확한 timing 필요)
|
||||||
$microtime = microtime(true);
|
$microtime = microtime(true);
|
||||||
$ms = sprintf('%03d', (int) (($microtime - floor($microtime)) * 1000));
|
$ms = sprintf('%03d', (int) (($microtime - floor($microtime)) * 1000));
|
||||||
@@ -530,6 +554,7 @@ function _addLogInternal(string $message): bool
|
|||||||
$msg = "[addLog] Failed to open log file: {$logFile}";
|
$msg = "[addLog] Failed to open log file: {$logFile}";
|
||||||
error_log($msg);
|
error_log($msg);
|
||||||
addLog($msg); // 재귀 가드가 차단
|
addLog($msg); // 재귀 가드가 차단
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -553,6 +578,7 @@ function _addLogInternal(string $message): bool
|
|||||||
$msg = "[addLog] Failed to write log file: {$logFile}";
|
$msg = "[addLog] Failed to write log file: {$logFile}";
|
||||||
error_log($msg);
|
error_log($msg);
|
||||||
addLog($msg); // 재귀 가드가 차단
|
addLog($msg); // 재귀 가드가 차단
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -641,6 +667,7 @@ function getInstallationLogCount(): int
|
|||||||
$count++;
|
$count++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return $count;
|
return $count;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,10 +6,7 @@
|
|||||||
* SSE/폴링 듀얼 모드 지원을 위한 진행 상황 보고 인터페이스.
|
* SSE/폴링 듀얼 모드 지원을 위한 진행 상황 보고 인터페이스.
|
||||||
* - SseEmitter: 실시간 SSE 스트리밍 + addLog
|
* - SseEmitter: 실시간 SSE 스트리밍 + addLog
|
||||||
* - NullEmitter: addLog만 수행 (폴링 모드, state.json 기반 조회)
|
* - NullEmitter: addLog만 수행 (폴링 모드, state.json 기반 조회)
|
||||||
*
|
|
||||||
* @package G7\Installer
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
if (! defined('BASE_PATH')) {
|
if (! defined('BASE_PATH')) {
|
||||||
define('BASE_PATH', realpath(dirname(__DIR__, 3)) ?: dirname(__DIR__, 3));
|
define('BASE_PATH', realpath(dirname(__DIR__, 3)) ?: dirname(__DIR__, 3));
|
||||||
}
|
}
|
||||||
@@ -57,8 +54,22 @@ class SseEmitter implements ProgressEmitter
|
|||||||
|
|
||||||
public function emit(string $event, array $data): void
|
public function emit(string $event, array $data): void
|
||||||
{
|
{
|
||||||
|
// SSE data 라인은 항상 유효 JSON 이어야 한다 (gnuboard/g7#62).
|
||||||
|
// composer install 등 외부 프로세스 로그에 invalid UTF-8 바이트가 섞이면
|
||||||
|
// json_encode 가 false 를 반환해 "data: \n\n" (빈 값) 이 송출되고,
|
||||||
|
// 프론트 EventSource 리스너의 JSON.parse(e.data) 가 throw 되어 로그 이벤트가 유실된다.
|
||||||
|
// 폴링 응답(state-management)과 동일하게 JSON_INVALID_UTF8_SUBSTITUTE 로 치환하고
|
||||||
|
// false 를 가드한다. (task-runner 의 스트림 scrub 과 이중 안전망)
|
||||||
|
$payload = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
|
||||||
|
if ($payload === false) {
|
||||||
|
$payload = json_encode(
|
||||||
|
['message' => '(log line dropped: encoding error)'],
|
||||||
|
JSON_UNESCAPED_UNICODE
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
echo "event: {$event}\n";
|
echo "event: {$event}\n";
|
||||||
echo "data: " . json_encode($data, JSON_UNESCAPED_UNICODE) . "\n\n";
|
echo 'data: '.$payload."\n\n";
|
||||||
if (ob_get_level()) {
|
if (ob_get_level()) {
|
||||||
@ob_flush();
|
@ob_flush();
|
||||||
}
|
}
|
||||||
@@ -196,8 +207,9 @@ class NullEmitter implements ProgressEmitter
|
|||||||
function getProgressEmitter(): ProgressEmitter
|
function getProgressEmitter(): ProgressEmitter
|
||||||
{
|
{
|
||||||
if (! isset($GLOBALS['g7_progress_emitter']) || ! ($GLOBALS['g7_progress_emitter'] instanceof ProgressEmitter)) {
|
if (! isset($GLOBALS['g7_progress_emitter']) || ! ($GLOBALS['g7_progress_emitter'] instanceof ProgressEmitter)) {
|
||||||
$GLOBALS['g7_progress_emitter'] = new SseEmitter();
|
$GLOBALS['g7_progress_emitter'] = new SseEmitter;
|
||||||
}
|
}
|
||||||
|
|
||||||
return $GLOBALS['g7_progress_emitter'];
|
return $GLOBALS['g7_progress_emitter'];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,8 +6,6 @@
|
|||||||
* 설치 task 정의와 실행 로직을 모드와 무관하게 제공합니다.
|
* 설치 task 정의와 실행 로직을 모드와 무관하게 제공합니다.
|
||||||
* 진입점(install-worker.php SSE 모드, install-process.php 폴링 모드)이
|
* 진입점(install-worker.php SSE 모드, install-process.php 폴링 모드)이
|
||||||
* ProgressEmitter를 등록한 뒤 runInstallationTasks()를 호출합니다.
|
* ProgressEmitter를 등록한 뒤 runInstallationTasks()를 호출합니다.
|
||||||
*
|
|
||||||
* @package G7\Installer
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
require_once __DIR__.'/config.php';
|
require_once __DIR__.'/config.php';
|
||||||
@@ -111,6 +109,7 @@ if (!function_exists('checkAbortStatusSSE')) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
saveInstallationState($state);
|
saveInstallationState($state);
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -119,6 +118,7 @@ if (!function_exists('checkAbortStatusSSE')) {
|
|||||||
if (isset($state['installation_status']) && $state['installation_status'] === 'aborted') {
|
if (isset($state['installation_status']) && $state['installation_status'] === 'aborted') {
|
||||||
$currentTask = $state['current_task'] ?? 'unknown';
|
$currentTask = $state['current_task'] ?? 'unknown';
|
||||||
addLog(lang('abort_by_user', ['task' => $currentTask]));
|
addLog(lang('abort_by_user', ['task' => $currentTask]));
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,6 +134,7 @@ if (!function_exists('getPhpBinary')) {
|
|||||||
function getPhpBinary(): string
|
function getPhpBinary(): string
|
||||||
{
|
{
|
||||||
$state = getInstallationState();
|
$state = getInstallationState();
|
||||||
|
|
||||||
return $state['config']['php_binary'] ?? 'php' ?: 'php';
|
return $state['config']['php_binary'] ?? 'php' ?: 'php';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -157,6 +158,7 @@ if (!function_exists('isInstallerExecutablePath')) {
|
|||||||
if (preg_match('/[\s;`$|<>"\'&\x00-\x1F]/', $path)) {
|
if (preg_match('/[\s;`$|<>"\'&\x00-\x1F]/', $path)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -211,6 +213,7 @@ if (!function_exists('getComposerCommand')) {
|
|||||||
) {
|
) {
|
||||||
return 'composer';
|
return 'composer';
|
||||||
}
|
}
|
||||||
|
|
||||||
return escapeshellarg($tokens['php']).' '.escapeshellarg($tokens['composer']);
|
return escapeshellarg($tokens['php']).' '.escapeshellarg($tokens['composer']);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -225,6 +228,7 @@ if (!function_exists('getComposerCommand')) {
|
|||||||
$phpArg = ($phpBinary !== 'php' && isInstallerExecutablePath($phpBinary))
|
$phpArg = ($phpBinary !== 'php' && isInstallerExecutablePath($phpBinary))
|
||||||
? escapeshellarg($phpBinary)
|
? escapeshellarg($phpBinary)
|
||||||
: escapeshellarg('php');
|
: escapeshellarg('php');
|
||||||
|
|
||||||
return $phpArg.' '.escapeshellarg($composerBinary);
|
return $phpArg.' '.escapeshellarg($composerBinary);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -251,6 +255,7 @@ if (!function_exists('getComposerCommandForDisplay')) {
|
|||||||
) {
|
) {
|
||||||
return 'composer';
|
return 'composer';
|
||||||
}
|
}
|
||||||
|
|
||||||
return $tokens['php'].' '.$tokens['composer'];
|
return $tokens['php'].' '.$tokens['composer'];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -351,6 +356,7 @@ if (!function_exists('checkComposerSSE')) {
|
|||||||
|
|
||||||
sendSSEEvent('log', ['message' => lang('log_error_occurred', ['error' => $errorMessage])]);
|
sendSSEEvent('log', ['message' => lang('log_error_occurred', ['error' => $errorMessage])]);
|
||||||
logInstallationError(lang('error_composer_not_installed'));
|
logInstallationError(lang('error_composer_not_installed'));
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'success' => false,
|
'success' => false,
|
||||||
'message' => lang('error_composer_not_installed'),
|
'message' => lang('error_composer_not_installed'),
|
||||||
@@ -395,6 +401,7 @@ if (!function_exists('installVendorBundleSSE')) {
|
|||||||
$errorList = implode(', ', $integrity['errors']);
|
$errorList = implode(', ', $integrity['errors']);
|
||||||
sendSSEEvent('log', ['message' => "번들 무결성 검증 실패: {$errorList}"]);
|
sendSSEEvent('log', ['message' => "번들 무결성 검증 실패: {$errorList}"]);
|
||||||
logInstallationError("vendor-bundle.zip 무결성 검증 실패: {$errorList}");
|
logInstallationError("vendor-bundle.zip 무결성 검증 실패: {$errorList}");
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'success' => false,
|
'success' => false,
|
||||||
'message' => "vendor-bundle.zip 무결성 검증 실패: {$errorList}",
|
'message' => "vendor-bundle.zip 무결성 검증 실패: {$errorList}",
|
||||||
@@ -411,6 +418,7 @@ if (!function_exists('installVendorBundleSSE')) {
|
|||||||
$error = $result['error'] ?? 'unknown';
|
$error = $result['error'] ?? 'unknown';
|
||||||
sendSSEEvent('log', ['message' => "vendor 번들 추출 실패: {$error}"]);
|
sendSSEEvent('log', ['message' => "vendor 번들 추출 실패: {$error}"]);
|
||||||
logInstallationError("vendor 번들 추출 실패: {$error}");
|
logInstallationError("vendor 번들 추출 실패: {$error}");
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'success' => false,
|
'success' => false,
|
||||||
'message' => "vendor 번들 추출 실패: {$error}",
|
'message' => "vendor 번들 추출 실패: {$error}",
|
||||||
@@ -458,6 +466,7 @@ if (!function_exists('installComposerDependenciesSSE')) {
|
|||||||
// composer 사용 불가 → 번들 zip 존재 여부 확인 후 폴백
|
// composer 사용 불가 → 번들 zip 존재 여부 확인 후 폴백
|
||||||
if (file_exists(BASE_PATH.'/vendor-bundle.zip')) {
|
if (file_exists(BASE_PATH.'/vendor-bundle.zip')) {
|
||||||
sendSSEEvent('log', ['message' => 'Composer 실행 불가 환경 감지 → 번들 vendor 모드로 자동 전환']);
|
sendSSEEvent('log', ['message' => 'Composer 실행 불가 환경 감지 → 번들 vendor 모드로 자동 전환']);
|
||||||
|
|
||||||
return installVendorBundleSSE();
|
return installVendorBundleSSE();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -483,6 +492,7 @@ if (!function_exists('installComposerDependenciesSSE')) {
|
|||||||
|
|
||||||
markTaskCompleted('composer_install');
|
markTaskCompleted('composer_install');
|
||||||
sendSSEEvent('task_complete', ['task' => 'composer_install', 'message' => lang('log_composer_already_installed')]);
|
sendSSEEvent('task_complete', ['task' => 'composer_install', 'message' => lang('log_composer_already_installed')]);
|
||||||
|
|
||||||
return ['success' => true];
|
return ['success' => true];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -562,6 +572,7 @@ if (!function_exists('installComposerDependenciesSSE')) {
|
|||||||
|
|
||||||
if (! is_resource($process)) {
|
if (! is_resource($process)) {
|
||||||
logInstallationError(lang('error_composer_install_failed'));
|
logInstallationError(lang('error_composer_install_failed'));
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'success' => false,
|
'success' => false,
|
||||||
'message' => lang('error_composer_install_failed'),
|
'message' => lang('error_composer_install_failed'),
|
||||||
@@ -577,12 +588,21 @@ if (!function_exists('installComposerDependenciesSSE')) {
|
|||||||
if (checkAbortStatusSSE()) {
|
if (checkAbortStatusSSE()) {
|
||||||
proc_terminate($process);
|
proc_terminate($process);
|
||||||
proc_close($process);
|
proc_close($process);
|
||||||
|
|
||||||
return ['success' => false, 'aborted' => true];
|
return ['success' => false, 'aborted' => true];
|
||||||
}
|
}
|
||||||
|
|
||||||
$line = fgets($pipes[1]);
|
$line = fgets($pipes[1]);
|
||||||
if ($line !== false) {
|
if ($line !== false) {
|
||||||
$line = trim($line);
|
$line = trim($line);
|
||||||
|
// composer stdout 이 시스템 코드페이지(Windows CP949 등)로 출력하거나
|
||||||
|
// 진행바(\r 갱신)가 non-blocking 읽기와 겹쳐 임의 바이트 경계에서 잘리면
|
||||||
|
// invalid UTF-8 바이트가 섞인다. SSE 응답(progress-emitter 의 json_encode)과
|
||||||
|
// 폴링 응답(state-management) 양쪽이 무력화되지 않도록 로그 전송 전 정규화한다.
|
||||||
|
// (gnuboard/g7#62 — addLog 최종 방어와 이중 안전망)
|
||||||
|
if ($line !== '' && ! mb_check_encoding($line, 'UTF-8')) {
|
||||||
|
$line = mb_scrub($line, 'UTF-8');
|
||||||
|
}
|
||||||
if (! empty($line)) {
|
if (! empty($line)) {
|
||||||
sendSSEEvent('log', ['message' => $line]);
|
sendSSEEvent('log', ['message' => $line]);
|
||||||
}
|
}
|
||||||
@@ -596,6 +616,7 @@ if (!function_exists('installComposerDependenciesSSE')) {
|
|||||||
|
|
||||||
if ($returnCode !== 0) {
|
if ($returnCode !== 0) {
|
||||||
logInstallationError(lang('error_composer_install_failed'));
|
logInstallationError(lang('error_composer_install_failed'));
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'success' => false,
|
'success' => false,
|
||||||
'message' => lang('error_composer_install_failed'),
|
'message' => lang('error_composer_install_failed'),
|
||||||
@@ -643,6 +664,7 @@ if (!function_exists('updateEnvFileSSE')) {
|
|||||||
$envExamplePath = BASE_PATH.'/.env.example';
|
$envExamplePath = BASE_PATH.'/.env.example';
|
||||||
if (! file_exists($envExamplePath)) {
|
if (! file_exists($envExamplePath)) {
|
||||||
logInstallationError(lang('error_env_example_not_found'));
|
logInstallationError(lang('error_env_example_not_found'));
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'success' => false,
|
'success' => false,
|
||||||
'message' => lang('error_env_example_not_found'),
|
'message' => lang('error_env_example_not_found'),
|
||||||
@@ -657,6 +679,7 @@ if (!function_exists('updateEnvFileSSE')) {
|
|||||||
|
|
||||||
if (! writeInstallerRuntime($runtime)) {
|
if (! writeInstallerRuntime($runtime)) {
|
||||||
logInstallationError(lang('error_env_write_failed', ['path' => INSTALLER_RUNTIME_PATH]));
|
logInstallationError(lang('error_env_write_failed', ['path' => INSTALLER_RUNTIME_PATH]));
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'success' => false,
|
'success' => false,
|
||||||
'message' => lang('error_env_write_failed', ['path' => INSTALLER_RUNTIME_PATH]),
|
'message' => lang('error_env_write_failed', ['path' => INSTALLER_RUNTIME_PATH]),
|
||||||
@@ -727,6 +750,7 @@ if (!function_exists('generateApplicationKeySSE')) {
|
|||||||
|
|
||||||
if (! writeInstallerRuntime($runtime)) {
|
if (! writeInstallerRuntime($runtime)) {
|
||||||
logInstallationError(lang('error_key_generate_failed'));
|
logInstallationError(lang('error_key_generate_failed'));
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'success' => false,
|
'success' => false,
|
||||||
'message' => lang('error_key_generate_failed'),
|
'message' => lang('error_key_generate_failed'),
|
||||||
@@ -853,6 +877,7 @@ if (!function_exists('dependencyPrecheckSSE')) {
|
|||||||
sendSSEEvent('log', ['message' => ' - '.$line]);
|
sendSSEEvent('log', ['message' => ' - '.$line]);
|
||||||
}
|
}
|
||||||
logInstallationError($errorMessage);
|
logInstallationError($errorMessage);
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'success' => false,
|
'success' => false,
|
||||||
'message' => $errorMessage,
|
'message' => $errorMessage,
|
||||||
@@ -902,6 +927,7 @@ if (!function_exists('cleanupExistingTablesSSE')) {
|
|||||||
sendSSEEvent('log', ['message' => lang('log_separator')]);
|
sendSSEEvent('log', ['message' => lang('log_separator')]);
|
||||||
markTaskCompleted('db_cleanup');
|
markTaskCompleted('db_cleanup');
|
||||||
sendSSEEvent('task_complete', ['task' => 'db_cleanup', 'message' => lang('log_db_cleanup_skipped')]);
|
sendSSEEvent('task_complete', ['task' => 'db_cleanup', 'message' => lang('log_db_cleanup_skipped')]);
|
||||||
|
|
||||||
return ['success' => true];
|
return ['success' => true];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -944,6 +970,7 @@ if (!function_exists('cleanupExistingTablesSSE')) {
|
|||||||
return ['success' => true];
|
return ['success' => true];
|
||||||
} catch (Exception $e) {
|
} catch (Exception $e) {
|
||||||
logInstallationError(lang('error_db_cleanup_failed'), $e);
|
logInstallationError(lang('error_db_cleanup_failed'), $e);
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'success' => false,
|
'success' => false,
|
||||||
'message' => lang('error_db_cleanup_failed'),
|
'message' => lang('error_db_cleanup_failed'),
|
||||||
@@ -996,6 +1023,7 @@ if (!function_exists('getSelectedExtensions')) {
|
|||||||
function getSelectedExtensions(): array
|
function getSelectedExtensions(): array
|
||||||
{
|
{
|
||||||
$state = getInstallationState();
|
$state = getInstallationState();
|
||||||
|
|
||||||
return $state['selected_extensions'] ?? [
|
return $state['selected_extensions'] ?? [
|
||||||
'admin_templates' => [],
|
'admin_templates' => [],
|
||||||
'user_templates' => [],
|
'user_templates' => [],
|
||||||
@@ -1066,7 +1094,7 @@ if (!function_exists('executeArtisanCommandSSE')) {
|
|||||||
|
|
||||||
$cmdLogFile = reserveCommandOutputFile();
|
$cmdLogFile = reserveCommandOutputFile();
|
||||||
$fullCommand = "{$phpBin} -d memory_limit=512M artisan {$artisanCommand} > "
|
$fullCommand = "{$phpBin} -d memory_limit=512M artisan {$artisanCommand} > "
|
||||||
. escapeshellarg($cmdLogFile) . " 2>&1";
|
.escapeshellarg($cmdLogFile).' 2>&1';
|
||||||
exec($fullCommand, $_ignored, $returnCode);
|
exec($fullCommand, $_ignored, $returnCode);
|
||||||
|
|
||||||
if (file_exists($cmdLogFile)) {
|
if (file_exists($cmdLogFile)) {
|
||||||
@@ -1083,6 +1111,7 @@ if (!function_exists('executeArtisanCommandSSE')) {
|
|||||||
if ($returnCode !== 0) {
|
if ($returnCode !== 0) {
|
||||||
$errorMessage = implode("\n", $output);
|
$errorMessage = implode("\n", $output);
|
||||||
logInstallationError(lang($errorMsgKey), new Exception($errorMessage));
|
logInstallationError(lang($errorMsgKey), new Exception($errorMessage));
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'success' => false,
|
'success' => false,
|
||||||
'message' => lang($errorMsgKey),
|
'message' => lang($errorMsgKey),
|
||||||
@@ -1114,6 +1143,7 @@ if (!function_exists('executeDbCommandSSE')) {
|
|||||||
|
|
||||||
if ($wasAborted) {
|
if ($wasAborted) {
|
||||||
addLog(lang('db_task_abort_detected_before_start'));
|
addLog(lang('db_task_abort_detected_before_start'));
|
||||||
|
|
||||||
return ['success' => false, 'aborted' => true];
|
return ['success' => false, 'aborted' => true];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1130,7 +1160,7 @@ if (!function_exists('executeDbCommandSSE')) {
|
|||||||
|
|
||||||
$cmdLogFile = reserveCommandOutputFile();
|
$cmdLogFile = reserveCommandOutputFile();
|
||||||
$fullCommand = "{$phpBin} -d memory_limit=512M artisan {$artisanCommand} > "
|
$fullCommand = "{$phpBin} -d memory_limit=512M artisan {$artisanCommand} > "
|
||||||
. escapeshellarg($cmdLogFile) . " 2>&1";
|
.escapeshellarg($cmdLogFile).' 2>&1';
|
||||||
|
|
||||||
exec($fullCommand, $_ignored, $returnCode);
|
exec($fullCommand, $_ignored, $returnCode);
|
||||||
|
|
||||||
@@ -1263,7 +1293,7 @@ if (!function_exists('executeExtensionCommandSSE')) {
|
|||||||
|
|
||||||
$cmdLogFile = reserveCommandOutputFile();
|
$cmdLogFile = reserveCommandOutputFile();
|
||||||
$fullCommand = "{$phpBin} -d memory_limit=512M artisan {$artisanCommand} > "
|
$fullCommand = "{$phpBin} -d memory_limit=512M artisan {$artisanCommand} > "
|
||||||
. escapeshellarg($cmdLogFile) . " 2>&1";
|
.escapeshellarg($cmdLogFile).' 2>&1';
|
||||||
|
|
||||||
exec($fullCommand, $_ignored, $returnCode);
|
exec($fullCommand, $_ignored, $returnCode);
|
||||||
|
|
||||||
@@ -1309,6 +1339,7 @@ if (!function_exists('executeExtensionCommandSSE')) {
|
|||||||
if ($returnCode !== 0 && ! $isAlreadyExists) {
|
if ($returnCode !== 0 && ! $isAlreadyExists) {
|
||||||
$errorMessage = $outputText;
|
$errorMessage = $outputText;
|
||||||
logInstallationError(lang($errorMsgKey), new Exception($errorMessage));
|
logInstallationError(lang($errorMsgKey), new Exception($errorMessage));
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'success' => false,
|
'success' => false,
|
||||||
'message' => lang($errorMsgKey),
|
'message' => lang($errorMsgKey),
|
||||||
@@ -1580,6 +1611,7 @@ if (!function_exists('createSettingsJsonSSE')) {
|
|||||||
foreach ($categories as $category) {
|
foreach ($categories as $category) {
|
||||||
if (! isset($defaults[$category])) {
|
if (! isset($defaults[$category])) {
|
||||||
sendSSEEvent('log', ['message' => " - {$category}.json skipped (no defaults)"]);
|
sendSSEEvent('log', ['message' => " - {$category}.json skipped (no defaults)"]);
|
||||||
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1609,6 +1641,7 @@ if (!function_exists('createSettingsJsonSSE')) {
|
|||||||
return ['success' => true];
|
return ['success' => true];
|
||||||
} catch (Exception $e) {
|
} catch (Exception $e) {
|
||||||
logInstallationError(lang('error_settings_json_failed'), $e);
|
logInstallationError(lang('error_settings_json_failed'), $e);
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'success' => false,
|
'success' => false,
|
||||||
'message' => lang('error_settings_json_failed'),
|
'message' => lang('error_settings_json_failed'),
|
||||||
@@ -1689,6 +1722,7 @@ if (!function_exists('setInstallationCompleteSSE')) {
|
|||||||
return ['success' => true];
|
return ['success' => true];
|
||||||
} catch (Exception $e) {
|
} catch (Exception $e) {
|
||||||
logInstallationError(lang('error_complete_flag_failed'), $e);
|
logInstallationError(lang('error_complete_flag_failed'), $e);
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'success' => false,
|
'success' => false,
|
||||||
'message' => lang('error_complete_flag_failed'),
|
'message' => lang('error_complete_flag_failed'),
|
||||||
@@ -1791,6 +1825,7 @@ if (!function_exists('runInstallationTasks')) {
|
|||||||
'target' => $task['target'] ?? null,
|
'target' => $task['target'] ?? null,
|
||||||
]);
|
]);
|
||||||
addLog(lang('abort_installation_stopped'));
|
addLog(lang('abort_installation_stopped'));
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1812,6 +1847,7 @@ if (!function_exists('runInstallationTasks')) {
|
|||||||
'target' => $target,
|
'target' => $target,
|
||||||
'message' => lang('log_already_completed', ['task' => $displayName]),
|
'message' => lang('log_already_completed', ['task' => $displayName]),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1824,6 +1860,7 @@ if (!function_exists('runInstallationTasks')) {
|
|||||||
'target' => $target,
|
'target' => $target,
|
||||||
]);
|
]);
|
||||||
addLog(lang('abort_installation_stopped'));
|
addLog(lang('abort_installation_stopped'));
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1833,6 +1870,7 @@ if (!function_exists('runInstallationTasks')) {
|
|||||||
$warnMsg = lang('warning_language_pack_install_partial', ['identifier' => (string) $target]);
|
$warnMsg = lang('warning_language_pack_install_partial', ['identifier' => (string) $target]);
|
||||||
sendSSEEvent('log', ['message' => $warnMsg]);
|
sendSSEEvent('log', ['message' => $warnMsg]);
|
||||||
addLog($warnMsg);
|
addLog($warnMsg);
|
||||||
|
|
||||||
// task_complete 이벤트는 보내지 않고 다음 task 로 진행 (재시도 시 다시 시도 가능)
|
// task_complete 이벤트는 보내지 않고 다음 task 로 진행 (재시도 시 다시 시도 가능)
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -1924,6 +1962,7 @@ if (!function_exists('runInstallationTasks')) {
|
|||||||
'target' => $target,
|
'target' => $target,
|
||||||
'manual_commands' => $manualCommands,
|
'manual_commands' => $manualCommands,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,251 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Tests\Unit\Installer;
|
||||||
|
|
||||||
|
use PHPUnit\Framework\Attributes\DataProvider;
|
||||||
|
use PHPUnit\Framework\Attributes\PreserveGlobalState;
|
||||||
|
use PHPUnit\Framework\Attributes\RunClassInSeparateProcess;
|
||||||
|
use PHPUnit\Framework\Attributes\Test;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 설치 로그 기록 시 UTF-8 정규화(scrub) 회귀 테스트.
|
||||||
|
*
|
||||||
|
* 배경 (gnuboard/g7#62, dev-g7#445):
|
||||||
|
* Vendor 설치 방식 "Composer 실행" + 폴링 모드 조합에서 브라우저 콘솔에
|
||||||
|
* "Unexpected end of JSON input" 이 폭주하고 진행 상황이 표시되지 않는 회귀.
|
||||||
|
*
|
||||||
|
* 근본 원인: 폴링 워커가 composer install stdout 을 fgets() 로 읽어 정규화 없이
|
||||||
|
* addLog() 로 넘긴다. Windows 코드페이지(CP949) 출력이나 다운로드 진행바(\r 갱신)가
|
||||||
|
* 임의 바이트 경계에서 잘리면 invalid UTF-8 바이트가 생기는데,
|
||||||
|
* _addLogInternal() 은 mb_detect_encoding(strict=true) 감지 실패 시 raw 바이트를
|
||||||
|
* 그대로 로그에 저장한다. 그 로그를 포함한 폴링 응답 state-management.php 의
|
||||||
|
* json_encode() 가 invalid UTF-8 때문에 false 를 반환 → echo false = 빈 본문(HTTP 200)
|
||||||
|
* → 프론트 res.json() 이 "Unexpected end of JSON input" 실패.
|
||||||
|
*
|
||||||
|
* 본 테스트는 근본 지점을 검증한다: addLog() 에 invalid UTF-8 바이트를 주입해도
|
||||||
|
* getInstallationLogs() 로 읽은 로그 메시지가 항상 유효 UTF-8 이어서
|
||||||
|
* json_encode() 가 false 가 아니어야 한다.
|
||||||
|
*
|
||||||
|
* BASE_PATH 는 PHP 상수로 클래스 라이프사이클 단위 단 한 번 정의 (setUpBeforeClass).
|
||||||
|
* InstallerStateSchemaTest 와 동일한 temp 격리 패턴을 사용한다.
|
||||||
|
*/
|
||||||
|
#[RunClassInSeparateProcess]
|
||||||
|
#[PreserveGlobalState(false)]
|
||||||
|
class AddLogUtf8ScrubTest extends TestCase
|
||||||
|
{
|
||||||
|
private static string $sharedBase = '';
|
||||||
|
|
||||||
|
private static string $skipReason = '';
|
||||||
|
|
||||||
|
public static function setUpBeforeClass(): void
|
||||||
|
{
|
||||||
|
parent::setUpBeforeClass();
|
||||||
|
|
||||||
|
// 안전 가드: BASE_PATH 가 시스템 temp 하위가 아니면 (= 다른 테스트가 프로젝트 루트로 박은 경우)
|
||||||
|
// setUp 의 installation.log @unlink 가 실제 설치 로그를 파괴할 수 있으므로 skip.
|
||||||
|
$tempPrefix = realpath(sys_get_temp_dir()) ?: sys_get_temp_dir();
|
||||||
|
if (defined('BASE_PATH')) {
|
||||||
|
$resolved = realpath((string) BASE_PATH) ?: (string) BASE_PATH;
|
||||||
|
if (strpos($resolved, $tempPrefix) !== 0) {
|
||||||
|
self::$skipReason = 'BASE_PATH ('.$resolved.') 가 시스템 temp 하위가 아님 — '.
|
||||||
|
'다른 Installer 테스트의 BASE_PATH 정의가 선행됨. 격리 실행 필요: '.
|
||||||
|
'php vendor/bin/phpunit --filter=AddLogUtf8ScrubTest';
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self::$sharedBase = (string) BASE_PATH;
|
||||||
|
} else {
|
||||||
|
self::$sharedBase = sys_get_temp_dir().'/g7-installer-addlog-test-'.bin2hex(random_bytes(4));
|
||||||
|
define('BASE_PATH', self::$sharedBase);
|
||||||
|
}
|
||||||
|
|
||||||
|
$logDir = self::$sharedBase.'/storage/logs';
|
||||||
|
if (! is_dir($logDir)) {
|
||||||
|
mkdir($logDir, 0755, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
// config.php 의 INSTALLER_BASE_URL 계산이 $_SERVER['SCRIPT_NAME'] 에 의존
|
||||||
|
if (! isset($_SERVER['SCRIPT_NAME'])) {
|
||||||
|
$_SERVER['SCRIPT_NAME'] = '/install/index.php';
|
||||||
|
}
|
||||||
|
|
||||||
|
require_once dirname(__DIR__, 3).'/public/install/includes/config.php';
|
||||||
|
require_once dirname(__DIR__, 3).'/public/install/includes/installer-state.php';
|
||||||
|
require_once dirname(__DIR__, 3).'/public/install/includes/progress-emitter.php';
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function tearDownAfterClass(): void
|
||||||
|
{
|
||||||
|
if (self::$skipReason === '' && self::$sharedBase !== '') {
|
||||||
|
$logFile = self::$sharedBase.'/storage/logs/installation.log';
|
||||||
|
if (file_exists($logFile)) {
|
||||||
|
@unlink($logFile);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
parent::tearDownAfterClass();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
|
||||||
|
if (self::$skipReason !== '') {
|
||||||
|
$this->markTestSkipped(self::$skipReason);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 각 테스트 시작 시 로그 초기화
|
||||||
|
$logFile = self::$sharedBase.'/storage/logs/installation.log';
|
||||||
|
if (file_exists($logFile)) {
|
||||||
|
@unlink($logFile);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* invalid UTF-8 바이트 표본.
|
||||||
|
*
|
||||||
|
* - 잘린 한글 선행 바이트 (EC 99 은 3바이트 UTF-8 의 앞 2바이트, 마지막 바이트 누락)
|
||||||
|
* - 단독 0xFF (UTF-8 에서 절대 유효하지 않은 바이트)
|
||||||
|
* - CP949 로 인코딩된 한글이 감지 실패하는 케이스 모사
|
||||||
|
*
|
||||||
|
* @return array<string, array{string}>
|
||||||
|
*/
|
||||||
|
public static function invalidUtf8Provider(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'truncated hangul lead bytes' => ["Downloading \xEC\x99 package"],
|
||||||
|
'lone 0xFF byte' => ["progress: abc\xFFdef 100%"],
|
||||||
|
'truncated 4-byte sequence' => ["emoji \xF0\x9F head"], // 4바이트 UTF-8 의 앞 2바이트만
|
||||||
|
'lone continuation byte' => ["tail\x80end"],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
#[Test]
|
||||||
|
#[DataProvider('invalidUtf8Provider')]
|
||||||
|
public function addlog_stores_valid_utf8_even_for_invalid_input(string $rawMessage): void
|
||||||
|
{
|
||||||
|
// 사전 조건: 입력은 실제로 invalid UTF-8 이어야 테스트가 의미 있음
|
||||||
|
$this->assertFalse(
|
||||||
|
mb_check_encoding($rawMessage, 'UTF-8'),
|
||||||
|
'테스트 입력 자체가 invalid UTF-8 이어야 한다 (표본 점검).'
|
||||||
|
);
|
||||||
|
|
||||||
|
$written = addLog($rawMessage);
|
||||||
|
$this->assertTrue($written, 'addLog 는 성공적으로 로그를 기록해야 한다.');
|
||||||
|
|
||||||
|
$logs = getInstallationLogs();
|
||||||
|
$this->assertNotEmpty($logs, '기록한 로그가 조회되어야 한다.');
|
||||||
|
|
||||||
|
$message = $logs[count($logs) - 1]['message'] ?? '';
|
||||||
|
|
||||||
|
// 핵심 계약: 저장된 로그 메시지는 항상 유효 UTF-8 이어야 한다.
|
||||||
|
$this->assertTrue(
|
||||||
|
mb_check_encoding($message, 'UTF-8'),
|
||||||
|
'저장된 로그 메시지는 항상 유효 UTF-8 이어야 한다 (invalid 바이트는 scrub 대체). '.
|
||||||
|
'실패 시: composer 출력의 깨진 바이트가 로그에 raw 저장되어 폴링 응답 json_encode 가 무력화됨.'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[Test]
|
||||||
|
#[DataProvider('invalidUtf8Provider')]
|
||||||
|
public function polling_response_json_encode_never_returns_false(string $rawMessage): void
|
||||||
|
{
|
||||||
|
addLog($rawMessage);
|
||||||
|
|
||||||
|
$logs = getInstallationLogs();
|
||||||
|
|
||||||
|
// 폴링 응답(state-management.php getState) 이 만드는 것과 동일한 구조를 모사.
|
||||||
|
$response = [
|
||||||
|
'status' => 'running',
|
||||||
|
'logs' => $logs,
|
||||||
|
'log_total' => getInstallationLogCount(),
|
||||||
|
];
|
||||||
|
|
||||||
|
// 근본 수정 후: logs 가 유효 UTF-8 이므로 substitute 플래그 없이도 false 가 아니어야 한다.
|
||||||
|
$encoded = json_encode($response, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
|
||||||
|
|
||||||
|
$this->assertNotFalse(
|
||||||
|
$encoded,
|
||||||
|
'invalid UTF-8 로그가 섞여도 폴링 응답 json_encode 는 false 를 반환하면 안 된다 '.
|
||||||
|
'(false → echo 빈 본문 → 프론트 "Unexpected end of JSON input").'
|
||||||
|
);
|
||||||
|
$this->assertIsString($encoded);
|
||||||
|
$this->assertNotSame('', $encoded, '인코딩 결과 본문이 비어 있으면 안 된다.');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[Test]
|
||||||
|
public function addlog_preserves_valid_utf8_korean_unchanged(): void
|
||||||
|
{
|
||||||
|
// 정규화가 정상 UTF-8 한글을 훼손하지 않아야 한다 (회귀 방지).
|
||||||
|
// 첫 로그 줄은 UTF-8 BOM 이 붙어 getInstallationLogs 의 [timestamp] 파싱에 간섭하므로
|
||||||
|
// 워밍업 로그를 먼저 기록해 검증 대상 줄을 두 번째 이후로 밀어낸다.
|
||||||
|
addLog('warmup');
|
||||||
|
|
||||||
|
$korean = 'Composer 의존성 설치를 시작합니다.';
|
||||||
|
|
||||||
|
addLog($korean);
|
||||||
|
$logs = getInstallationLogs();
|
||||||
|
$message = $logs[count($logs) - 1]['message'] ?? '';
|
||||||
|
|
||||||
|
$this->assertSame($korean, $message, '정상 UTF-8 한글은 scrub 후에도 변형되지 않아야 한다.');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SSE 이벤트 스트림도 invalid UTF-8 로그로 인해 빈 data 라인을 송출하면 안 된다 (인코딩 계약).
|
||||||
|
*
|
||||||
|
* 폴링 모드로 제보됐으나(#62), 근본 원인(외부 유래 invalid UTF-8 → json_encode false)은
|
||||||
|
* SSE 모드에도 동일하게 존재한다. SseEmitter::emit 의 json_encode 가 false 를 반환하면
|
||||||
|
* "data: \n\n" 이 송출되어 프론트 EventSource 의 JSON.parse(e.data) 가 throw → 로그 이벤트 유실.
|
||||||
|
*
|
||||||
|
* SseEmitter::emit 은 내부에서 즉시 flush() 하므로 ob_get_clean() 으로 출력을 캡처할 수 없다
|
||||||
|
* (SSE 스트리밍 설계상 의도된 동작). 따라서 emit 이 사용하는 인코딩 계약을 직접 검증한다:
|
||||||
|
* JSON_INVALID_UTF8_SUBSTITUTE 를 적용하면 invalid UTF-8 이 섞여도 false 가 아니어야 한다.
|
||||||
|
*/
|
||||||
|
#[Test]
|
||||||
|
#[DataProvider('invalidUtf8Provider')]
|
||||||
|
public function sse_emit_encoding_contract_never_returns_false_for_invalid_utf8(string $rawMessage): void
|
||||||
|
{
|
||||||
|
// emit 이 실제 사용하는 것과 동일한 인코딩 호출.
|
||||||
|
$payload = json_encode(
|
||||||
|
['message' => $rawMessage],
|
||||||
|
JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE
|
||||||
|
);
|
||||||
|
|
||||||
|
$this->assertNotFalse(
|
||||||
|
$payload,
|
||||||
|
'SSE data 인코딩은 invalid UTF-8 로그가 섞여도 false 를 반환하면 안 된다 '.
|
||||||
|
'(false → "data: \n\n" → 프론트 JSON.parse throw → 로그 이벤트 유실).'
|
||||||
|
);
|
||||||
|
$this->assertIsString($payload);
|
||||||
|
|
||||||
|
// 프론트 JSON.parse(e.data) 와 동일하게 파싱 가능해야 한다.
|
||||||
|
$decoded = json_decode($payload, true);
|
||||||
|
$this->assertSame(JSON_ERROR_NONE, json_last_error());
|
||||||
|
$this->assertIsArray($decoded);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* progress-emitter.php 의 SseEmitter::emit 이 JSON_INVALID_UTF8_SUBSTITUTE 를 적용하는지
|
||||||
|
* 소스 레벨로 회귀 검증한다 (PollingResponseFlushTest 정적 검증과 동일 방식).
|
||||||
|
*/
|
||||||
|
#[Test]
|
||||||
|
public function sse_emitter_source_uses_invalid_utf8_substitute_flag(): void
|
||||||
|
{
|
||||||
|
$source = (string) file_get_contents(
|
||||||
|
dirname(__DIR__, 3).'/public/install/includes/progress-emitter.php'
|
||||||
|
);
|
||||||
|
|
||||||
|
// SseEmitter 클래스 본문 추출
|
||||||
|
$classStart = strpos($source, 'class SseEmitter');
|
||||||
|
$this->assertNotFalse($classStart, 'SseEmitter 클래스를 찾을 수 없습니다.');
|
||||||
|
$classEnd = strpos($source, 'class NullEmitter', $classStart);
|
||||||
|
$sseBody = substr($source, $classStart, $classEnd !== false ? $classEnd - $classStart : null);
|
||||||
|
|
||||||
|
$this->assertStringContainsString(
|
||||||
|
'JSON_INVALID_UTF8_SUBSTITUTE',
|
||||||
|
$sseBody,
|
||||||
|
'SseEmitter::emit 의 json_encode 는 JSON_INVALID_UTF8_SUBSTITUTE 를 적용해 '.
|
||||||
|
'invalid UTF-8 로그로 인한 빈 SSE data 라인 송출을 차단해야 한다.'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -43,9 +43,14 @@ class DeleteDirectoryTest extends TestCase
|
|||||||
define('INSTALLER_BASE_URL', '/install');
|
define('INSTALLER_BASE_URL', '/install');
|
||||||
}
|
}
|
||||||
|
|
||||||
// 인스톨러 함수 로드 (pure PHPUnit TestCase 라서 Laravel base_path() 사용 불가 — BASE_PATH 상수 사용)
|
// 인스톨러 함수 로드 (pure PHPUnit TestCase 라서 Laravel base_path() 사용 불가).
|
||||||
require_once BASE_PATH . '/public/install/includes/functions.php';
|
// 프로젝트 루트 절대경로(__DIR__ 기준)로 로드한다 — 다른 인스톨러 테스트
|
||||||
require_once BASE_PATH . '/public/install/api/rollback-functions.php';
|
// (#[RunClassInSeparateProcess] + temp BASE_PATH)가 메인 프로세스로 BASE_PATH 를
|
||||||
|
// 누수시켜도 그 temp 경로에는 public/install 이 없어 require 가 깨지므로, 누수된
|
||||||
|
// BASE_PATH 값과 무관하게 항상 실제 프로젝트 파일을 참조한다.
|
||||||
|
$installerRoot = dirname(__DIR__, 3);
|
||||||
|
require_once $installerRoot.'/public/install/includes/functions.php';
|
||||||
|
require_once $installerRoot.'/public/install/api/rollback-functions.php';
|
||||||
|
|
||||||
// 임시 디렉토리 생성
|
// 임시 디렉토리 생성
|
||||||
$this->tempDir = sys_get_temp_dir().DIRECTORY_SEPARATOR.'g7_test_delete_'.uniqid();
|
$this->tempDir = sys_get_temp_dir().DIRECTORY_SEPARATOR.'g7_test_delete_'.uniqid();
|
||||||
|
|||||||
@@ -0,0 +1,134 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Tests\Unit\Installer;
|
||||||
|
|
||||||
|
use PHPUnit\Framework\Attributes\PreserveGlobalState;
|
||||||
|
use PHPUnit\Framework\Attributes\RunClassInSeparateProcess;
|
||||||
|
use PHPUnit\Framework\Attributes\Test;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 인스톨러 디렉토리 권한 재귀 스캔 깊이 제한 회귀 테스트.
|
||||||
|
*
|
||||||
|
* 배경 (dev-g7#445 후속):
|
||||||
|
* 인스톨러 2단계(요구사항 검증)의 checkDirectoryPermissions 가 storage 를 재귀 스캔하는데,
|
||||||
|
* checkSubdirectoriesRecursive 가 깊이 제한 없이 무한 재귀하여 storage/framework/testing/
|
||||||
|
* 하위에 누적된 수만 개 디렉토리를 전부 순회 → 2단계 응답이 8초 이상 지연되던 문제.
|
||||||
|
*
|
||||||
|
* 권한 안내는 트리 상위 얕은 깊이에서만 유의미하므로 재귀에 깊이 제한을 둔다.
|
||||||
|
* 본 테스트는 깊이 제한이 실제로 적용되어 제한 깊이를 넘는 하위는 순회하지 않음을 검증한다.
|
||||||
|
*
|
||||||
|
* BASE_PATH 는 PHP 상수로 클래스 라이프사이클 단위 단 한 번 정의 (setUpBeforeClass).
|
||||||
|
*/
|
||||||
|
#[RunClassInSeparateProcess]
|
||||||
|
#[PreserveGlobalState(false)]
|
||||||
|
class DirectoryPermissionScanDepthTest extends TestCase
|
||||||
|
{
|
||||||
|
private static string $sharedBase = '';
|
||||||
|
|
||||||
|
private static string $skipReason = '';
|
||||||
|
|
||||||
|
public static function setUpBeforeClass(): void
|
||||||
|
{
|
||||||
|
parent::setUpBeforeClass();
|
||||||
|
|
||||||
|
$tempPrefix = realpath(sys_get_temp_dir()) ?: sys_get_temp_dir();
|
||||||
|
if (defined('BASE_PATH')) {
|
||||||
|
$resolved = realpath((string) BASE_PATH) ?: (string) BASE_PATH;
|
||||||
|
if (strpos($resolved, $tempPrefix) !== 0) {
|
||||||
|
self::$skipReason = 'BASE_PATH ('.$resolved.') 가 시스템 temp 하위가 아님 — '.
|
||||||
|
'격리 실행 필요: php vendor/bin/phpunit --filter=DirectoryPermissionScanDepthTest';
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self::$sharedBase = (string) BASE_PATH;
|
||||||
|
} else {
|
||||||
|
self::$sharedBase = sys_get_temp_dir().'/g7-installer-dirscan-test-'.bin2hex(random_bytes(4));
|
||||||
|
define('BASE_PATH', self::$sharedBase);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! is_dir(self::$sharedBase)) {
|
||||||
|
mkdir(self::$sharedBase, 0755, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! isset($_SERVER['SCRIPT_NAME'])) {
|
||||||
|
$_SERVER['SCRIPT_NAME'] = '/install/index.php';
|
||||||
|
}
|
||||||
|
|
||||||
|
require_once dirname(__DIR__, 3).'/public/install/includes/config.php';
|
||||||
|
require_once dirname(__DIR__, 3).'/public/install/includes/functions.php';
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function tearDownAfterClass(): void
|
||||||
|
{
|
||||||
|
parent::tearDownAfterClass();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
|
||||||
|
if (self::$skipReason !== '') {
|
||||||
|
$this->markTestSkipped(self::$skipReason);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 깊이 제한을 넘는 하위 디렉토리는 재귀 스캔 대상에서 제외되어야 한다.
|
||||||
|
*
|
||||||
|
* storage/deep/a/b/c/... 처럼 깊은 트리를 만들고, checkSubdirectoriesRecursive 를
|
||||||
|
* 제한 깊이(2)로 호출하면 depth 3 이상 경로는 결과에 나타나지 않아야 한다.
|
||||||
|
*/
|
||||||
|
#[Test]
|
||||||
|
public function recursive_scan_respects_max_depth(): void
|
||||||
|
{
|
||||||
|
// BASE_PATH/scanroot 하위에 깊이 5의 중첩 디렉토리 생성 (전부 정상 권한)
|
||||||
|
$root = self::$sharedBase.'/scanroot';
|
||||||
|
$deep = $root.'/lvl1/lvl2/lvl3/lvl4/lvl5';
|
||||||
|
if (! is_dir($deep)) {
|
||||||
|
mkdir($deep, 0755, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 깊이 2 제한으로 스캔 — 함수는 (path, maxDepth) 시그니처를 지원해야 한다.
|
||||||
|
$failed = checkSubdirectoriesRecursive($root, 2);
|
||||||
|
|
||||||
|
// 모든 디렉토리가 정상 권한이므로 실패 항목은 없어야 하고, 무엇보다
|
||||||
|
// 함수가 무한 재귀 없이 즉시 반환해야 한다 (깊이 제한 동작 확인).
|
||||||
|
$this->assertIsArray($failed);
|
||||||
|
|
||||||
|
// 깊이 제한이 동작하는지 간접 검증: 깊은 트리에서도 스캔이 즉시 끝나야 한다.
|
||||||
|
$t0 = microtime(true);
|
||||||
|
checkSubdirectoriesRecursive($root, 2);
|
||||||
|
$elapsed = microtime(true) - $t0;
|
||||||
|
|
||||||
|
$this->assertLessThan(
|
||||||
|
1.0,
|
||||||
|
$elapsed,
|
||||||
|
'깊이 제한된 재귀 스캔은 얕은 깊이만 순회하므로 즉시 완료되어야 한다.'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* checkSubdirectoriesRecursive 가 maxDepth 파라미터를 받는 시그니처여야 한다.
|
||||||
|
*/
|
||||||
|
#[Test]
|
||||||
|
public function function_accepts_max_depth_parameter(): void
|
||||||
|
{
|
||||||
|
$ref = new \ReflectionFunction('checkSubdirectoriesRecursive');
|
||||||
|
$params = $ref->getParameters();
|
||||||
|
|
||||||
|
$this->assertGreaterThanOrEqual(
|
||||||
|
2,
|
||||||
|
count($params),
|
||||||
|
'checkSubdirectoriesRecursive 는 깊이 제한 파라미터를 받아야 한다 '.
|
||||||
|
'(무한 재귀로 storage 하위 수만 개 디렉토리를 순회해 인스톨러 2단계가 지연되던 문제 차단).'
|
||||||
|
);
|
||||||
|
|
||||||
|
// 두 번째 파라미터는 깊이 제한(정수, 기본값 존재)이어야 한다.
|
||||||
|
$depthParam = $params[1];
|
||||||
|
$this->assertTrue(
|
||||||
|
$depthParam->isDefaultValueAvailable(),
|
||||||
|
'깊이 제한 파라미터는 기본값을 가져 기존 호출부(check-configuration.php)가 변경 없이 동작해야 한다.'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,6 +11,19 @@ use PHPUnit\Framework\TestCase;
|
|||||||
*/
|
*/
|
||||||
class InstallerWindowsCommandsTest extends TestCase
|
class InstallerWindowsCommandsTest extends TestCase
|
||||||
{
|
{
|
||||||
|
/**
|
||||||
|
* 프로젝트 루트 절대경로 (BASE_PATH 상수와 독립).
|
||||||
|
*
|
||||||
|
* 다른 인스톨러 테스트(#[RunClassInSeparateProcess] + temp BASE_PATH)가 메인
|
||||||
|
* 프로세스로 BASE_PATH 를 누수시키면, 그 temp 경로 하위에는 public/install 이 없어
|
||||||
|
* require 가 깨진다. 본 클래스는 __DIR__ 기준 절대경로로 인스톨러 파일을 로드해
|
||||||
|
* 누수된 BASE_PATH 값과 무관하게 항상 실제 프로젝트 파일을 참조한다.
|
||||||
|
*/
|
||||||
|
private function installerRoot(): string
|
||||||
|
{
|
||||||
|
return dirname(__DIR__, 3);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 테스트 전 인스톨러 설정 및 함수 파일을 로드합니다.
|
* 테스트 전 인스톨러 설정 및 함수 파일을 로드합니다.
|
||||||
*/
|
*/
|
||||||
@@ -40,8 +53,8 @@ class InstallerWindowsCommandsTest extends TestCase
|
|||||||
define('INSTALLER_BASE_URL', '/install');
|
define('INSTALLER_BASE_URL', '/install');
|
||||||
}
|
}
|
||||||
|
|
||||||
// functions.php 로드 (한 번만) — base_path() 대신 BASE_PATH 상수 직접 사용
|
// functions.php 로드 (한 번만) — 누수된 BASE_PATH 와 무관하게 프로젝트 루트 절대경로 사용
|
||||||
require_once BASE_PATH . '/public/install/includes/functions.php';
|
require_once $this->installerRoot().'/public/install/includes/functions.php';
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -165,8 +178,8 @@ class InstallerWindowsCommandsTest extends TestCase
|
|||||||
*/
|
*/
|
||||||
public function test_translation_keys_exist(): void
|
public function test_translation_keys_exist(): void
|
||||||
{
|
{
|
||||||
$koTranslations = require BASE_PATH . '/public/install/lang/ko.php';
|
$koTranslations = require $this->installerRoot().'/public/install/lang/ko.php';
|
||||||
$enTranslations = require BASE_PATH . '/public/install/lang/en.php';
|
$enTranslations = require $this->installerRoot().'/public/install/lang/en.php';
|
||||||
|
|
||||||
$this->assertArrayHasKey('permission_windows_hint', $koTranslations, 'ko.php에 permission_windows_hint 키가 없습니다');
|
$this->assertArrayHasKey('permission_windows_hint', $koTranslations, 'ko.php에 permission_windows_hint 키가 없습니다');
|
||||||
$this->assertArrayHasKey('permission_windows_hint', $enTranslations, 'en.php에 permission_windows_hint 키가 없습니다');
|
$this->assertArrayHasKey('permission_windows_hint', $enTranslations, 'en.php에 permission_windows_hint 키가 없습니다');
|
||||||
@@ -179,8 +192,8 @@ class InstallerWindowsCommandsTest extends TestCase
|
|||||||
*/
|
*/
|
||||||
public function test_directory_create_guide_translation_keys_exist(): void
|
public function test_directory_create_guide_translation_keys_exist(): void
|
||||||
{
|
{
|
||||||
$koTranslations = require BASE_PATH . '/public/install/lang/ko.php';
|
$koTranslations = require $this->installerRoot().'/public/install/lang/ko.php';
|
||||||
$enTranslations = require BASE_PATH . '/public/install/lang/en.php';
|
$enTranslations = require $this->installerRoot().'/public/install/lang/en.php';
|
||||||
|
|
||||||
$this->assertArrayHasKey('directory_create_guide', $koTranslations, 'ko.php에 directory_create_guide 키가 없습니다');
|
$this->assertArrayHasKey('directory_create_guide', $koTranslations, 'ko.php에 directory_create_guide 키가 없습니다');
|
||||||
$this->assertArrayHasKey('directory_create_guide', $enTranslations, 'en.php에 directory_create_guide 키가 없습니다');
|
$this->assertArrayHasKey('directory_create_guide', $enTranslations, 'en.php에 directory_create_guide 키가 없습니다');
|
||||||
|
|||||||
Reference in new issue
Block a user