Commit 49a09f69 authored by jan.koester's avatar jan.koester
Browse files

windows: stop endless worker respawn loop on startup failure

HttpConD swallowed startup exceptions on Windows, so a worker that
failed to bind exited with 0 and the supervisor restarted it at once,
forever. Now the exception reaches the caller: ServiceMain reports
SERVICE_STOPPED, workers exit with 1. The supervisor restarts with
growing delay (2s..60s) and gives up on a worker after 5 quick
failures in a row; exits when no worker is left.

Co-Authored-By: default avatarClaude Opus 5.5 <noreply@anthropic.com>
parent a17d62be
Loading
Loading
Loading
Loading
+140 −16
Changes for src/blogi.cpp: 140 added lines, 16 removed lines.
Original line number Diff line number Diff line
@@ -4316,6 +4316,11 @@ public:
        }
        catch (std::exception &e)
        {
#ifdef _WIN32
            // the caller reports it: ServiceMain sets SERVICE_STOPPED, a worker exits non-zero
            // so the supervisor sees a failed start instead of a clean exit
            throw;
#endif
            std::cerr << e.what() << std::endl;
#ifndef _WIN32
            // a start that fails here must not look like a clean exit to the config helper
@@ -5103,8 +5108,16 @@ int _tmain(int argc, TCHAR *argv[])
            {
                // Running as a per-domain worker spawned by the supervisor.
                blogi::Blogi::Cfg->filterDomains((size_t)workerDomainIdx);
                try
                {
                    HttpConD blogiD(debug);
                }
                catch (const std::exception &e)
                {
                    std::cerr << "[blogi] worker " << workerDomainIdx << " failed: " << e.what() << std::endl;
                    return 1;
                }
            }
            else
            {
                size_t domainCount = blogi::Blogi::Cfg->getDomainCount();
@@ -5114,10 +5127,24 @@ int _tmain(int argc, TCHAR *argv[])
                    wchar_t exePath[MAX_PATH];
                    GetModuleFileNameW(NULL, exePath, MAX_PATH);

                    std::vector<HANDLE> workerHandles(domainCount, INVALID_HANDLE_VALUE);
                    std::vector<DWORD>  workerDomains(domainCount);
                    // A worker that dies soon after its start (port taken, bad config, ...)
                    // would fail the same way again: restart it with a growing delay and
                    // give up on it after kMaxQuickFailures starts in a row.
                    const ULONGLONG kQuickExitMs = 30000;
                    const ULONGLONG kMaxDelayMs = 60000;
                    const int kMaxQuickFailures = 5;

                    struct Worker
                    {
                        HANDLE proc = NULL;
                        ULONGLONG startedAt = 0;
                        ULONGLONG respawnAt = 0;   // 0: no restart pending
                        int quickFailures = 0;
                        bool givenUp = false;
                    };
                    std::vector<Worker> workers(domainCount);

                    auto spawnWorker = [&](size_t d) -> HANDLE
                    auto spawnWorker = [&](size_t d) -> bool
                    {
                        std::wstring cmdLine = L"\"";
                        cmdLine += exePath;
@@ -5131,37 +5158,134 @@ int _tmain(int argc, TCHAR *argv[])
                        std::vector<wchar_t> cmdBuf(cmdLine.begin(), cmdLine.end());
                        cmdBuf.push_back(L'\0');

                        workers[d].startedAt = GetTickCount64();
                        workers[d].respawnAt = 0;
                        if (!CreateProcessW(NULL, cmdBuf.data(), NULL, NULL,
                                            FALSE, 0, NULL, NULL, &si, &pi))
                            return INVALID_HANDLE_VALUE;
                        {
                            std::cerr << "[blogi] could not start worker " << d
                                      << ": CreateProcess error " << GetLastError() << std::endl;
                            workers[d].proc = NULL;
                            return false;
                        }
                        CloseHandle(pi.hThread);
                        return pi.hProcess;
                        workers[d].proc = pi.hProcess;
                        return true;
                    };

                    // a worker is gone (exited, or could not be started): plan its restart
                    auto workerDown = [&](size_t d, DWORD exitCode)
                    {
                        Worker &w = workers[d];
                        ULONGLONG ranMs = GetTickCount64() - w.startedAt;
                        if (ranMs < kQuickExitMs)
                            ++w.quickFailures;
                        else
                            w.quickFailures = 0;

                        if (w.quickFailures >= kMaxQuickFailures)
                        {
                            w.givenUp = true;
                            std::cerr << "[blogi] worker " << d << " failed " << w.quickFailures
                                      << " times in a row (last exit code " << exitCode
                                      << "), not restarting it" << std::endl;
                            return;
                        }
                        ULONGLONG delay = w.quickFailures == 0
                                              ? 1000
                                              : std::min<ULONGLONG>(kMaxDelayMs, 1000ULL << w.quickFailures);
                        std::cerr << "[blogi] worker " << d << " exited (code " << exitCode
                                  << "), restarting in " << delay / 1000 << "s" << std::endl;
                        w.respawnAt = GetTickCount64() + delay;
                    };

                    for (size_t d = 0; d < domainCount; ++d)
                    {
                        workerDomains[d] = (DWORD)d;
                        workerHandles[d] = spawnWorker(d);
                        if (!spawnWorker(d))
                            workerDown(d, (DWORD)-1);
                    }

                    // Supervisor watchdog: restart crashed workers.
                    // Supervisor watchdog: restart workers that exit, with backoff.
                    while (true)
                    {
                        DWORD n = (DWORD)workerHandles.size();
                        DWORD idx = WaitForMultipleObjects(n, workerHandles.data(), FALSE, INFINITE);
                        std::vector<HANDLE> live;
                        std::vector<size_t> liveIdx;
                        ULONGLONG nextRespawn = 0;
                        bool anyAlive = false;
                        for (size_t d = 0; d < domainCount; ++d)
                        {
                            Worker &w = workers[d];
                            if (w.proc)
                            {
                                live.push_back(w.proc);
                                liveIdx.push_back(d);
                                anyAlive = true;
                            }
                            else if (!w.givenUp && w.respawnAt)
                            {
                                anyAlive = true;
                                if (!nextRespawn || w.respawnAt < nextRespawn)
                                    nextRespawn = w.respawnAt;
                            }
                        }
                        if (!anyAlive)
                        {
                            std::cerr << "[blogi] no worker left running, exiting" << std::endl;
                            return 1;
                        }

                        DWORD timeout = INFINITE;
                        if (nextRespawn)
                        {
                            ULONGLONG nowMs = GetTickCount64();
                            timeout = nextRespawn > nowMs ? (DWORD)(nextRespawn - nowMs) : 0;
                        }

                        DWORD idx = WAIT_TIMEOUT;
                        if (!live.empty())
                            idx = WaitForMultipleObjects((DWORD)live.size(), live.data(), FALSE, timeout);
                        else
                            Sleep(timeout);

                        if (idx == WAIT_FAILED)
                            break;
                        size_t d = (size_t)(idx - WAIT_OBJECT_0);
                        if (d >= domainCount)
                            break;
                        CloseHandle(workerHandles[d]);
                        workerHandles[d] = spawnWorker(d);
                        {
                            std::cerr << "[blogi] WaitForMultipleObjects failed: " << GetLastError() << std::endl;
                            return 1;
                        }
                        if (idx >= WAIT_OBJECT_0 && idx < WAIT_OBJECT_0 + live.size())
                        {
                            size_t d = liveIdx[idx - WAIT_OBJECT_0];
                            DWORD exitCode = 0;
                            GetExitCodeProcess(workers[d].proc, &exitCode);
                            CloseHandle(workers[d].proc);
                            workers[d].proc = NULL;
                            workerDown(d, exitCode);
                        }

                        ULONGLONG nowMs = GetTickCount64();
                        for (size_t d = 0; d < domainCount; ++d)
                        {
                            Worker &w = workers[d];
                            if (!w.proc && !w.givenUp && w.respawnAt && nowMs >= w.respawnAt)
                            {
                                if (!spawnWorker(d))
                                    workerDown(d, (DWORD)-1);
                            }
                        }
                    }
                }
                else
                {
                    try
                    {
                        HttpConD blogiD(debug);
                    }
                    catch (const std::exception &e)
                    {
                        std::cerr << "[blogi] fatal: " << e.what() << std::endl;
                        return 1;
                    }
                }
            }
        }
        else