| Conditions | 45 |
| Paths | > 20000 |
| Total Lines | 368 |
| Code Lines | 211 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
| 1 | <?php |
||
| 170 | public function restart(): void |
||
| 171 | { |
||
| 172 | // Get all workers that need to be restarted |
||
| 173 | $arrWorkers = $this->prepareWorkersList(); |
||
| 174 | |||
| 175 | // Collect all running workers and their forks |
||
| 176 | $runningWorkers = []; |
||
| 177 | $workerPools = []; |
||
| 178 | |||
| 179 | // Create tasks for collecting PIDs |
||
| 180 | $pidCollectionTasks = []; |
||
| 181 | foreach ($arrWorkers as $workerType => $workersWithCurrentType) { |
||
| 182 | foreach ($workersWithCurrentType as $worker) { |
||
| 183 | $pidCollectionTasks[] = function() use ($worker, &$runningWorkers, &$workerPools) { |
||
| 184 | // Check if worker uses pool |
||
| 185 | $maxProc = $this->getWorkerInstanceCount($worker); |
||
| 186 | |||
| 187 | if ($maxProc > 1) { |
||
| 188 | // This is a pool worker - collect all instances |
||
| 189 | $pattern = "$worker"; |
||
| 190 | $poolPids = Processes::getPidOfProcess($pattern); |
||
| 191 | if (!empty($poolPids)) { |
||
| 192 | $workerPools[$worker] = [ |
||
| 193 | 'maxProc' => $maxProc, |
||
| 194 | 'pids' => array_filter(explode(' ', $poolPids)) |
||
| 195 | ]; |
||
| 196 | } |
||
| 197 | } else { |
||
| 198 | // Regular single worker |
||
| 199 | $mainPid = Processes::getPidOfProcess($worker); |
||
| 200 | if (!empty($mainPid)) { |
||
| 201 | $runningWorkers[$worker] = $mainPid; |
||
| 202 | } |
||
| 203 | } |
||
| 204 | Fiber::suspend(); |
||
| 205 | }; |
||
| 206 | } |
||
| 207 | } |
||
| 208 | |||
| 209 | // Execute PID collection in parallel |
||
| 210 | $this->executeParallel($pidCollectionTasks); |
||
| 211 | |||
| 212 | // Count total workers to restart |
||
| 213 | $totalWorkers = count($runningWorkers) + array_sum(array_map(function($pool) { |
||
| 214 | return count($pool['pids']); |
||
| 215 | }, $workerPools)); |
||
| 216 | |||
| 217 | // Log the start of restart process with detailed information |
||
| 218 | SystemMessages::sysLogMsg( |
||
| 219 | static::class, |
||
| 220 | sprintf( |
||
| 221 | "Starting restart process for %d worker instances. Regular workers: %d, Pool workers: %d", |
||
| 222 | $totalWorkers, |
||
| 223 | count($runningWorkers), |
||
| 224 | count($workerPools) |
||
| 225 | ), |
||
| 226 | LOG_NOTICE |
||
| 227 | ); |
||
| 228 | |||
| 229 | // Детально логируем обнаруженные пулы воркеров |
||
| 230 | foreach ($workerPools as $worker => $poolInfo) { |
||
| 231 | SystemMessages::sysLogMsg( |
||
| 232 | static::class, |
||
| 233 | sprintf( |
||
| 234 | "Detected worker pool: %s, maxProc: %d, running PIDs: %s", |
||
| 235 | $worker, |
||
| 236 | $poolInfo['maxProc'], |
||
| 237 | implode(',', $poolInfo['pids']) |
||
| 238 | ), |
||
| 239 | LOG_NOTICE |
||
| 240 | ); |
||
| 241 | } |
||
| 242 | |||
| 243 | // STEP 1: Start new worker instances first |
||
| 244 | // This ensures new workers are ready to take jobs before old ones exit |
||
| 245 | $startTasks = []; |
||
| 246 | $startedWorkers = []; |
||
| 247 | |||
| 248 | // Приоритизируем запуск WorkerApiCommands - они самые критичные для UI |
||
| 249 | foreach ($arrWorkers as $workerType => $workersWithCurrentType) { |
||
| 250 | // Сортируем воркеры так, чтобы API-воркеры запускались первыми |
||
| 251 | $sortedWorkers = $workersWithCurrentType; |
||
| 252 | usort($sortedWorkers, function($a, $b) { |
||
| 253 | $isApiWorkerA = strpos($a, 'WorkerApiCommands') !== false; |
||
| 254 | $isApiWorkerB = strpos($b, 'WorkerApiCommands') !== false; |
||
| 255 | |||
| 256 | if ($isApiWorkerA && !$isApiWorkerB) { |
||
| 257 | return -1; // A должен быть раньше B |
||
| 258 | } elseif (!$isApiWorkerA && $isApiWorkerB) { |
||
| 259 | return 1; // B должен быть раньше A |
||
| 260 | } |
||
| 261 | return 0; // Порядок не важен |
||
| 262 | }); |
||
| 263 | |||
| 264 | foreach ($sortedWorkers as $worker) { |
||
| 265 | $maxProc = $this->getWorkerInstanceCount($worker); |
||
| 266 | |||
| 267 | // Если это API-воркер, создаем все экземпляры сразу (не в фоновом режиме) |
||
| 268 | // и дожидаемся полной их инициализации перед продолжением |
||
| 269 | if (strpos($worker, 'WorkerApiCommands') !== false) { |
||
| 270 | SystemMessages::sysLogMsg( |
||
| 271 | static::class, |
||
| 272 | "Starting ALL instances of critical worker {$worker} synchronously", |
||
| 273 | LOG_NOTICE |
||
| 274 | ); |
||
| 275 | |||
| 276 | // Для WorkerApiCommands создаем все инстансы сразу, но используем стандартный механизм |
||
| 277 | for ($i = 1; $i <= $maxProc; $i++) { |
||
| 278 | SystemMessages::sysLogMsg( |
||
| 279 | static::class, |
||
| 280 | "Starting critical worker instance {$i}/{$maxProc}: {$worker}", |
||
| 281 | LOG_NOTICE |
||
| 282 | ); |
||
| 283 | |||
| 284 | // Используем стандартный механизм запуска, но с правильными параметрами instanceId |
||
| 285 | // Это гарантирует, что процесс будет корректно запущен и залогирован |
||
| 286 | Processes::processPHPWorker($worker, 'start'); |
||
| 287 | |||
| 288 | // Дополнительно проверим, что воркер действительно запущен |
||
| 289 | sleep(1); |
||
| 290 | $pidFile = Processes::getPidFilePath($worker, $i); |
||
| 291 | if (file_exists($pidFile)) { |
||
| 292 | $pid = trim(file_get_contents($pidFile)); |
||
| 293 | SystemMessages::sysLogMsg( |
||
| 294 | static::class, |
||
| 295 | sprintf("Worker %s instance %d started with PID %s", $worker, $i, $pid), |
||
| 296 | LOG_NOTICE |
||
| 297 | ); |
||
| 298 | } else { |
||
| 299 | SystemMessages::sysLogMsg( |
||
| 300 | static::class, |
||
| 301 | sprintf("WARNING: PID file not found for %s instance %d", $worker, $i), |
||
| 302 | LOG_WARNING |
||
| 303 | ); |
||
| 304 | } |
||
| 305 | } |
||
| 306 | |||
| 307 | // Ждем дополнительное время, чтобы воркеры полностью инициализировались |
||
| 308 | sleep(3); |
||
| 309 | $startedWorkers[$worker] = true; |
||
| 310 | |||
| 311 | // Проверяем, что все воркеры действительно запустились |
||
| 312 | $allWorkersRunning = true; |
||
| 313 | for ($i = 1; $i <= $maxProc; $i++) { |
||
| 314 | $pidFile = Processes::getPidFilePath($worker, $i); |
||
| 315 | if (!file_exists($pidFile)) { |
||
| 316 | $allWorkersRunning = false; |
||
| 317 | SystemMessages::sysLogMsg( |
||
| 318 | static::class, |
||
| 319 | "WARNING: PID file not found for {$worker} instance {$i}", |
||
| 320 | LOG_WARNING |
||
| 321 | ); |
||
| 322 | } |
||
| 323 | } |
||
| 324 | |||
| 325 | if (!$allWorkersRunning) { |
||
| 326 | SystemMessages::sysLogMsg( |
||
| 327 | static::class, |
||
| 328 | "ERROR: Not all instances of {$worker} started correctly!", |
||
| 329 | LOG_ERR |
||
| 330 | ); |
||
| 331 | } else { |
||
| 332 | SystemMessages::sysLogMsg( |
||
| 333 | static::class, |
||
| 334 | "All {$maxProc} instances of {$worker} started successfully", |
||
| 335 | LOG_NOTICE |
||
| 336 | ); |
||
| 337 | } |
||
| 338 | } else if ($maxProc > 1) { |
||
| 339 | // Это пул воркеров, но не API-воркеры |
||
| 340 | // Добавляем их в список задач для запуска |
||
| 341 | for ($i = 1; $i <= $maxProc; $i++) { |
||
| 342 | $startTasks[] = function() use ($worker, $i, &$startedWorkers) { |
||
| 343 | SystemMessages::sysLogMsg( |
||
| 344 | static::class, |
||
| 345 | "Starting new instance {$i} of pool worker {$worker}", |
||
| 346 | LOG_NOTICE |
||
| 347 | ); |
||
| 348 | Processes::processPHPWorker($worker, 'start'); |
||
| 349 | $startedWorkers[$worker] = true; |
||
| 350 | Fiber::suspend(); |
||
| 351 | }; |
||
| 352 | } |
||
| 353 | } else { |
||
| 354 | // Обычный одиночный воркер |
||
| 355 | $startTasks[] = function() use ($worker, &$startedWorkers) { |
||
| 356 | SystemMessages::sysLogMsg( |
||
| 357 | static::class, |
||
| 358 | "Starting new instance of {$worker}", |
||
| 359 | LOG_NOTICE |
||
| 360 | ); |
||
| 361 | Processes::processPHPWorker($worker, 'start'); |
||
| 362 | $startedWorkers[$worker] = true; |
||
| 363 | Fiber::suspend(); |
||
| 364 | }; |
||
| 365 | } |
||
| 366 | } |
||
| 367 | } |
||
| 368 | |||
| 369 | // Start remaining new instances in parallel |
||
| 370 | if (!empty($startTasks)) { |
||
| 371 | $this->executeParallel($startTasks); |
||
| 372 | } |
||
| 373 | |||
| 374 | // Wait for new instances to initialize and become ready to process jobs |
||
| 375 | SystemMessages::sysLogMsg( |
||
| 376 | static::class, |
||
| 377 | "Started new worker instances, waiting for them to initialize", |
||
| 378 | LOG_NOTICE |
||
| 379 | ); |
||
| 380 | sleep(5); // Give more time for proper initialization |
||
| 381 | |||
| 382 | // STEP 2: Signal old workers to gracefully shutdown |
||
| 383 | // They will finish current jobs and then exit |
||
| 384 | $shutdownTasks = []; |
||
| 385 | |||
| 386 | // Handle regular workers |
||
| 387 | foreach ($runningWorkers as $worker => $pid) { |
||
| 388 | $shutdownTasks[] = function() use ($pid, $worker) { |
||
| 389 | if (posix_kill((int)$pid, SIGUSR1)) { |
||
| 390 | SystemMessages::sysLogMsg( |
||
| 391 | static::class, |
||
| 392 | "Sent SIGUSR1 to {$worker} (PID: {$pid})", |
||
| 393 | LOG_DEBUG |
||
| 394 | ); |
||
| 395 | } |
||
| 396 | Fiber::suspend(); |
||
| 397 | }; |
||
| 398 | } |
||
| 399 | |||
| 400 | // Handle worker pools |
||
| 401 | foreach ($workerPools as $worker => $poolInfo) { |
||
| 402 | foreach ($poolInfo['pids'] as $pid) { |
||
| 403 | $shutdownTasks[] = function() use ($pid, $worker) { |
||
| 404 | if (posix_kill((int)$pid, SIGUSR1)) { |
||
| 405 | SystemMessages::sysLogMsg( |
||
| 406 | static::class, |
||
| 407 | "Sent SIGUSR1 to {$worker} pool instance (PID: {$pid})", |
||
| 408 | LOG_DEBUG |
||
| 409 | ); |
||
| 410 | } |
||
| 411 | Fiber::suspend(); |
||
| 412 | }; |
||
| 413 | } |
||
| 414 | } |
||
| 415 | |||
| 416 | // Execute graceful shutdown signals in parallel |
||
| 417 | $this->executeParallel($shutdownTasks); |
||
| 418 | |||
| 419 | // STEP 3: Wait for graceful shutdown with sufficient timeout |
||
| 420 | SystemMessages::sysLogMsg( |
||
| 421 | static::class, |
||
| 422 | "Waiting for workers to complete active tasks (graceful shutdown)", |
||
| 423 | LOG_NOTICE |
||
| 424 | ); |
||
| 425 | |||
| 426 | $gracefulShutdownStart = time(); |
||
| 427 | $gracefulShutdownTimeout = 30; // Increased timeout to allow job completion |
||
| 428 | |||
| 429 | while (time() - $gracefulShutdownStart < $gracefulShutdownTimeout) { |
||
| 430 | $allShutdown = true; |
||
| 431 | |||
| 432 | // Check regular workers |
||
| 433 | foreach ($runningWorkers as $worker => $pid) { |
||
| 434 | if (posix_kill((int)$pid, 0)) { |
||
| 435 | // Process still exists |
||
| 436 | $allShutdown = false; |
||
| 437 | break; |
||
| 438 | } |
||
| 439 | } |
||
| 440 | |||
| 441 | // Check pool workers |
||
| 442 | foreach ($workerPools as $worker => $poolInfo) { |
||
| 443 | foreach ($poolInfo['pids'] as $pid) { |
||
| 444 | if (posix_kill((int)$pid, 0)) { |
||
| 445 | // Process still exists |
||
| 446 | $allShutdown = false; |
||
| 447 | break 2; |
||
| 448 | } |
||
| 449 | } |
||
| 450 | } |
||
| 451 | |||
| 452 | if ($allShutdown) { |
||
| 453 | SystemMessages::sysLogMsg( |
||
| 454 | static::class, |
||
| 455 | "All workers have gracefully shutdown", |
||
| 456 | LOG_NOTICE |
||
| 457 | ); |
||
| 458 | break; |
||
| 459 | } |
||
| 460 | |||
| 461 | sleep(1); |
||
| 462 | } |
||
| 463 | |||
| 464 | // STEP 4: Force terminate any remaining processes |
||
| 465 | $terminateTasks = []; |
||
| 466 | |||
| 467 | // Regular workers |
||
| 468 | foreach ($runningWorkers as $worker => $pid) { |
||
| 469 | if (posix_kill((int)$pid, 0)) { |
||
| 470 | SystemMessages::sysLogMsg( |
||
| 471 | static::class, |
||
| 472 | "Worker {$worker} (PID: {$pid}) didn't shut down gracefully, sending SIGTERM", |
||
| 473 | LOG_WARNING |
||
| 474 | ); |
||
| 475 | |||
| 476 | $terminateTasks[] = function() use ($pid) { |
||
| 477 | posix_kill((int)$pid, SIGTERM); |
||
| 478 | Fiber::suspend(); |
||
| 479 | }; |
||
| 480 | } |
||
| 481 | } |
||
| 482 | |||
| 483 | // Pool worker instances |
||
| 484 | foreach ($workerPools as $worker => $poolInfo) { |
||
| 485 | foreach ($poolInfo['pids'] as $pid) { |
||
| 486 | if (posix_kill((int)$pid, 0)) { |
||
| 487 | SystemMessages::sysLogMsg( |
||
| 488 | static::class, |
||
| 489 | "Worker {$worker} pool instance (PID: {$pid}) didn't shut down gracefully, sending SIGTERM", |
||
| 490 | LOG_WARNING |
||
| 491 | ); |
||
| 492 | |||
| 493 | $terminateTasks[] = function() use ($pid) { |
||
| 494 | posix_kill((int)$pid, SIGTERM); |
||
| 495 | Fiber::suspend(); |
||
| 496 | }; |
||
| 497 | } |
||
| 498 | } |
||
| 499 | } |
||
| 500 | |||
| 501 | // Execute termination in parallel if needed |
||
| 502 | if (!empty($terminateTasks)) { |
||
| 503 | $this->executeParallel($terminateTasks); |
||
| 504 | // Give processes time to terminate |
||
| 505 | sleep(2); |
||
| 506 | |||
| 507 | // Final check and SIGKILL if necessary for regular workers |
||
| 508 | foreach ($runningWorkers as $worker => $pid) { |
||
| 509 | if (posix_kill((int)$pid, 0)) { |
||
| 510 | SystemMessages::sysLogMsg( |
||
| 511 | static::class, |
||
| 512 | "Worker {$worker} (PID: {$pid}) still alive, sending SIGKILL", |
||
| 513 | LOG_WARNING |
||
| 514 | ); |
||
| 515 | posix_kill((int)$pid, SIGKILL); |
||
| 516 | } |
||
| 517 | } |
||
| 518 | |||
| 519 | // Final check and SIGKILL if necessary for pool workers |
||
| 520 | foreach ($workerPools as $worker => $poolInfo) { |
||
| 521 | foreach ($poolInfo['pids'] as $pid) { |
||
| 522 | if (posix_kill((int)$pid, 0)) { |
||
| 523 | SystemMessages::sysLogMsg( |
||
| 524 | static::class, |
||
| 525 | "Worker {$worker} pool instance (PID: {$pid}) still alive, sending SIGKILL", |
||
| 526 | LOG_WARNING |
||
| 527 | ); |
||
| 528 | posix_kill((int)$pid, SIGKILL); |
||
| 529 | } |
||
| 530 | } |
||
| 531 | } |
||
| 532 | } |
||
| 533 | |||
| 534 | SystemMessages::sysLogMsg( |
||
| 535 | static::class, |
||
| 536 | "Worker restart completed - new instances are running with updated code", |
||
| 537 | LOG_NOTICE |
||
| 538 | ); |
||
| 1029 | } |
This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.
This is most likely a typographical error or the method has been renamed.