From e94e3bcb97c3803a00ae00fd1408e556ffa4177c Mon Sep 17 00:00:00 2001 From: Alliballibaba Date: Sun, 14 Dec 2025 23:14:19 +0100 Subject: [PATCH 01/19] Tests. --- caddy/caddy_test.go | 69 ++++++++++++++++++++++++++++++++++++++ frankenphp.c | 19 +++++++++++ frankenphp.go | 64 +++++++++++++++++++++++++++++++++-- phpmainthread_test.go | 2 +- testdata/opcache_reset.php | 9 +++++ testdata/require.php | 6 ++++ threadregular.go | 6 ++++ watcher.go | 2 +- worker.go | 2 ++ 9 files changed, 175 insertions(+), 4 deletions(-) create mode 100644 testdata/opcache_reset.php create mode 100644 testdata/require.php diff --git a/caddy/caddy_test.go b/caddy/caddy_test.go index 5f95c0ab31..bd10ff7791 100644 --- a/caddy/caddy_test.go +++ b/caddy/caddy_test.go @@ -3,6 +3,7 @@ package caddy_test import ( "bytes" "fmt" + "math/rand/v2" "net/http" "os" "path/filepath" @@ -11,6 +12,7 @@ import ( "sync" "sync/atomic" "testing" + "time" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddytest" @@ -1472,3 +1474,70 @@ func TestDd(t *testing.T) { "dump123", ) } + +// test to force the opcache segfault race condition under concurrency (~1.7s) +func TestOpcacheReset(t *testing.T) { + tester := caddytest.NewTester(t) + tester.InitServer(` + { + skip_install_trust + admin localhost:2999 + http_port `+testPort+` + metrics + + frankenphp { + num_threads 40 + php_ini { + opcache.enable 1 + zend_extension opcache.so + opcache.log_verbosity_level 4 + } + } + } + + localhost:`+testPort+` { + php { + root ../testdata + worker { + file sleep.php + match /sleep* + num 20 + } + } + } + `, "caddyfile") + + wg := sync.WaitGroup{} + numRequests := 100 + wg.Add(numRequests) + for i := 0; i < numRequests; i++ { + + // introduce some random delay + if rand.IntN(10) > 8 { + time.Sleep(time.Millisecond * 10) + } + + go func() { + // randomly call opcache_reset + if rand.IntN(10) > 5 { + tester.AssertGetResponse( + "http://localhost:"+testPort+"/opcache_reset.php", + http.StatusOK, + "opcache reset done", + ) + wg.Done() + return + } + + // otherwise call sleep.php with random sleep and work values + tester.AssertGetResponse( + fmt.Sprintf("http://localhost:%s/sleep.php?sleep=%d&work=%d", testPort, i, i), + http.StatusOK, + fmt.Sprintf("slept for %d ms and worked for %d iterations", i, i), + ) + wg.Done() + }() + } + + wg.Wait() +} diff --git a/frankenphp.c b/frankenphp.c index 04782a9b65..7b59d24faa 100644 --- a/frankenphp.c +++ b/frankenphp.c @@ -73,6 +73,7 @@ bool should_filter_var = 0; __thread uintptr_t thread_index; __thread bool is_worker_thread = false; __thread zval *os_environment = NULL; +zif_handler orig_opcache_reset; void frankenphp_update_local_thread_context(bool is_worker) { is_worker_thread = is_worker; @@ -340,6 +341,15 @@ PHP_FUNCTION(frankenphp_getenv) { } } /* }}} */ +/* {{{ thread-safe opcache reset */ +PHP_FUNCTION(frankenphp_opcache_reset) { + if (go_schedule_opcache_reset(thread_index)) { + orig_opcache_reset(INTERNAL_FUNCTION_PARAM_PASSTHRU); + } + + RETVAL_FALSE; +} /* }}} */ + /* {{{ Fetch all HTTP request headers */ PHP_FUNCTION(frankenphp_request_headers) { ZEND_PARSE_PARAMETERS_NONE(); @@ -570,6 +580,15 @@ PHP_MINIT_FUNCTION(frankenphp) { php_error(E_WARNING, "Failed to find built-in getenv function"); } + // Override opcache_reset + func = zend_hash_str_find_ptr(CG(function_table), "opcache_reset", + sizeof("opcache_reset") - 1); + if (func != NULL && func->type == ZEND_INTERNAL_FUNCTION) { + orig_opcache_reset = ((zend_internal_function *)func)->handler; + ((zend_internal_function *)func)->handler = + ZEND_FN(frankenphp_opcache_reset); + } + return SUCCESS; } diff --git a/frankenphp.go b/frankenphp.go index da0bdead3c..09b87cf537 100644 --- a/frankenphp.go +++ b/frankenphp.go @@ -32,11 +32,14 @@ import ( "runtime" "strings" "sync" + "sync/atomic" "syscall" "time" "unsafe" // debug on Linux //_ "github.com/ianlancetaylor/cgosymbolizer" + + "github.com/dunglas/frankenphp/internal/state" ) type contextKeyStruct struct{} @@ -56,8 +59,10 @@ var ( contextKey = contextKeyStruct{} serverHeader = []string{"FrankenPHP"} - isRunning bool - onServerShutdown []func() + isRunning bool + isOpcacheResetting atomic.Bool + threadsAreRestarting atomic.Bool + onServerShutdown []func() // Set default values to make Shutdown() idempotent globalMu sync.Mutex @@ -698,6 +703,61 @@ func go_is_context_done(threadIndex C.uintptr_t) C.bool { return C.bool(phpThreads[threadIndex].frankenPHPContext().isDone) } +//export go_schedule_opcache_reset +func go_schedule_opcache_reset(threadIndex C.uintptr_t) C.bool { + if isOpcacheResetting.CompareAndSwap(false, true) { + restartThreadsForOpcacheReset(nil) + return C.bool(true) + } + + return C.bool(phpThreads[threadIndex].state.Is(state.Restarting)) +} + +// restart all threads for an opcache_reset +func restartThreadsForOpcacheReset(exceptThisThread *phpThread) { + if threadsAreRestarting.Load() { + // ignore reloads while a restart is already ongoing + return + } + + // disallow scaling threads while restarting workers + scalingMu.Lock() + defer scalingMu.Unlock() + + // drain workers + globalLogger.Info("Restarting all PHP threads for opcache_reset") + threadsToRestart := drainWorkerThreads() + + // drain regular threads + globalLogger.Info("Draining regular PHP threads for opcache_reset") + wg := sync.WaitGroup{} + for _, thread := range regularThreads { + if thread.state.Is(state.Ready) { + threadsToRestart = append(threadsToRestart, thread) + thread.state.Set(state.Restarting) + close(thread.drainChan) + + wg.Go(func() { + thread.state.WaitFor(state.Yielding) + }) + } + } + + // other threads may not parse new scripts while this thread is scheduling an opcache_reset + // sleeping a bit here makes this much less likely to happen + // waiting for all other threads to drain first can potentially deadlock + time.Sleep(100 * time.Millisecond) + + go func() { + wg.Wait() + for _, thread := range threadsToRestart { + thread.drainChan = make(chan struct{}) + thread.state.Set(state.Ready) + isOpcacheResetting.Store(false) + } + }() +} + // ExecuteScriptCLI executes the PHP script passed as parameter. // It returns the exit status code of the script. func ExecuteScriptCLI(script string, args []string) int { diff --git a/phpmainthread_test.go b/phpmainthread_test.go index b777c33942..a570215115 100644 --- a/phpmainthread_test.go +++ b/phpmainthread_test.go @@ -97,7 +97,7 @@ func TestTransitionThreadsWhileDoingRequests(t *testing.T) { var ( isDone atomic.Bool - wg sync.WaitGroup + wg sync.WaitGroup ) numThreads := 10 diff --git a/testdata/opcache_reset.php b/testdata/opcache_reset.php new file mode 100644 index 0000000000..b19a80bf43 --- /dev/null +++ b/testdata/opcache_reset.php @@ -0,0 +1,9 @@ + Date: Sun, 28 Dec 2025 22:42:54 +0100 Subject: [PATCH 02/19] Wait 1s for deadlocks. --- frankenphp.go | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/frankenphp.go b/frankenphp.go index 09b87cf537..dea7d6da98 100644 --- a/frankenphp.go +++ b/frankenphp.go @@ -706,7 +706,7 @@ func go_is_context_done(threadIndex C.uintptr_t) C.bool { //export go_schedule_opcache_reset func go_schedule_opcache_reset(threadIndex C.uintptr_t) C.bool { if isOpcacheResetting.CompareAndSwap(false, true) { - restartThreadsForOpcacheReset(nil) + restartThreadsForOpcacheReset(phpThreads[threadIndex]) return C.bool(true) } @@ -737,19 +737,31 @@ func restartThreadsForOpcacheReset(exceptThisThread *phpThread) { thread.state.Set(state.Restarting) close(thread.drainChan) + if thread == exceptThisThread { + continue + } + wg.Go(func() { thread.state.WaitFor(state.Yielding) }) } } - // other threads may not parse new scripts while this thread is scheduling an opcache_reset - // sleeping a bit here makes this much less likely to happen - // waiting for all other threads to drain first can potentially deadlock - time.Sleep(100 * time.Millisecond) - + done := make(chan struct{}) go func() { wg.Wait() + close(done) + }() + + select { + case <-done: + // all other threads are drained + case <-time.After(time.Second): + // probably a deadlock, continue anyway and hope for the best + } + + go func() { + exceptThisThread.state.WaitFor(state.Yielding) for _, thread := range threadsToRestart { thread.drainChan = make(chan struct{}) thread.state.Set(state.Ready) From d1e28d5df55a0d2ad527d5018ca8929c2210e95d Mon Sep 17 00:00:00 2001 From: Alliballibaba Date: Sun, 28 Dec 2025 22:54:57 +0100 Subject: [PATCH 03/19] Adjusts waitgroup logic. --- frankenphp.go | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/frankenphp.go b/frankenphp.go index f91528058e..090d0fd6c1 100644 --- a/frankenphp.go +++ b/frankenphp.go @@ -765,11 +765,12 @@ func go_schedule_opcache_reset(threadIndex C.uintptr_t) C.bool { return C.bool(true) } + // always call the original opcache_reset if already restarting return C.bool(phpThreads[threadIndex].state.Is(state.Restarting)) } // restart all threads for an opcache_reset -func restartThreadsForOpcacheReset(exceptThisThread *phpThread) { +func restartThreadsForOpcacheReset(callingThread *phpThread) { if threadsAreRestarting.Load() { // ignore reloads while a restart is already ongoing return @@ -792,16 +793,13 @@ func restartThreadsForOpcacheReset(exceptThisThread *phpThread) { thread.state.Set(state.Restarting) close(thread.drainChan) - if thread == exceptThisThread { - continue - } - wg.Go(func() { thread.state.WaitFor(state.Yielding) }) } } + wg.Done() // ignore the calling thread done := make(chan struct{}) go func() { wg.Wait() @@ -816,7 +814,7 @@ func restartThreadsForOpcacheReset(exceptThisThread *phpThread) { } go func() { - exceptThisThread.state.WaitFor(state.Yielding) + callingThread.state.WaitFor(state.Yielding) for _, thread := range threadsToRestart { thread.drainChan = make(chan struct{}) thread.state.Set(state.Ready) From 8e87d00829a9de9fc3b85a86590c3168dc3ff2e6 Mon Sep 17 00:00:00 2001 From: Alliballibaba Date: Mon, 29 Dec 2025 23:16:03 +0100 Subject: [PATCH 04/19] Starts separate opcache_reset request flow once all threads are stopped. --- frankenphp.c | 10 +++--- frankenphp.go | 86 +++++++++++++++++++----------------------------- threadregular.go | 1 + threadworker.go | 7 +--- worker.go | 38 +++++++++++++++++---- 5 files changed, 73 insertions(+), 69 deletions(-) diff --git a/frankenphp.c b/frankenphp.c index 669f7d6c28..23b221753f 100644 --- a/frankenphp.c +++ b/frankenphp.c @@ -343,11 +343,9 @@ PHP_FUNCTION(frankenphp_getenv) { /* {{{ thread-safe opcache reset */ PHP_FUNCTION(frankenphp_opcache_reset) { - if (go_schedule_opcache_reset(thread_index)) { - orig_opcache_reset(INTERNAL_FUNCTION_PARAM_PASSTHRU); - } + go_schedule_opcache_reset(thread_index); - RETVAL_FALSE; + RETVAL_TRUE; } /* }}} */ /* {{{ Fetch all HTTP request headers */ @@ -1270,11 +1268,15 @@ int frankenphp_execute_script_cli(char *script, int argc, char **argv, } int frankenphp_reset_opcache(void) { + php_request_startup(); zend_function *opcache_reset = zend_hash_str_find_ptr(CG(function_table), ZEND_STRL("opcache_reset")); if (opcache_reset) { + ((zend_internal_function *)opcache_reset)->handler = orig_opcache_reset; zend_call_known_function(opcache_reset, NULL, NULL, NULL, 0, NULL, NULL); + ((zend_internal_function *)opcache_reset)->handler = ZEND_FN(frankenphp_opcache_reset); } + php_request_shutdown((void *)0); return 0; } diff --git a/frankenphp.go b/frankenphp.go index 090d0fd6c1..bd304789f1 100644 --- a/frankenphp.go +++ b/frankenphp.go @@ -59,10 +59,9 @@ var ( contextKey = contextKeyStruct{} serverHeader = []string{"FrankenPHP"} - isRunning bool - isOpcacheResetting atomic.Bool - threadsAreRestarting atomic.Bool - onServerShutdown []func() + isRunning bool + restartCounter atomic.Int32 + onServerShutdown []func() // Set default values to make Shutdown() idempotent globalMu sync.Mutex @@ -759,68 +758,49 @@ func go_is_context_done(threadIndex C.uintptr_t) C.bool { } //export go_schedule_opcache_reset -func go_schedule_opcache_reset(threadIndex C.uintptr_t) C.bool { - if isOpcacheResetting.CompareAndSwap(false, true) { - restartThreadsForOpcacheReset(phpThreads[threadIndex]) - return C.bool(true) +func go_schedule_opcache_reset(threadIndex C.uintptr_t) { + if restartCounter.CompareAndSwap(0, 1) { + go restartThreadsForOpcacheReset() } - - // always call the original opcache_reset if already restarting - return C.bool(phpThreads[threadIndex].state.Is(state.Restarting)) } // restart all threads for an opcache_reset -func restartThreadsForOpcacheReset(callingThread *phpThread) { - if threadsAreRestarting.Load() { - // ignore reloads while a restart is already ongoing - return - } - +func restartThreadsForOpcacheReset() { // disallow scaling threads while restarting workers scalingMu.Lock() defer scalingMu.Unlock() - // drain workers - globalLogger.Info("Restarting all PHP threads for opcache_reset") - threadsToRestart := drainWorkerThreads() - - // drain regular threads - globalLogger.Info("Draining regular PHP threads for opcache_reset") - wg := sync.WaitGroup{} - for _, thread := range regularThreads { - if thread.state.Is(state.Ready) { - threadsToRestart = append(threadsToRestart, thread) - thread.state.Set(state.Restarting) - close(thread.drainChan) - - wg.Go(func() { - thread.state.WaitFor(state.Yielding) - }) - } + threadsToRestart := drainWorkerThreads(true) + + for _, thread := range threadsToRestart { + thread.drainChan = make(chan struct{}) + thread.state.Set(state.Ready) } +} - wg.Done() // ignore the calling thread - done := make(chan struct{}) - go func() { - wg.Wait() - close(done) - }() +func scheduleOpcacheReset(thread *phpThread) { + restartCounter.Add(-1) + if restartCounter.Load() != 1 { + return // only the last restarting thread will trigger an actual opcache_reset + } + workerThread, ok := thread.handler.(*workerThread) + fc, _ := newDummyContext("/opcache_reset") + if ok && workerThread.worker != nil { + workerThread.dummyFrankenPHPContext = fc + defer func() { workerThread.dummyFrankenPHPContext = nil }() + } - select { - case <-done: - // all other threads are drained - case <-time.After(time.Second): - // probably a deadlock, continue anyway and hope for the best + regularThread, ok := thread.handler.(*regularThread) + if ok { + regularThread.contextHolder.frankenPHPContext = fc + defer func() { regularThread.contextHolder.frankenPHPContext = nil }() } - go func() { - callingThread.state.WaitFor(state.Yielding) - for _, thread := range threadsToRestart { - thread.drainChan = make(chan struct{}) - thread.state.Set(state.Ready) - isOpcacheResetting.Store(false) - } - }() + globalLogger.Info("resetting opcache in all threads") + C.frankenphp_reset_opcache() + + // all threads should have restarted now + restartCounter.Store(0) } // ExecuteScriptCLI executes the PHP script passed as parameter. diff --git a/threadregular.go b/threadregular.go index 801116822d..86dade86c8 100644 --- a/threadregular.go +++ b/threadregular.go @@ -50,6 +50,7 @@ func (handler *regularThread) beforeScriptExecution() string { return handler.waitForRequest() case state.Restarting: handler.state.Set(state.Yielding) + scheduleOpcacheReset(handler.thread) handler.state.WaitFor(state.Ready, state.ShuttingDown) return handler.beforeScriptExecution() diff --git a/threadworker.go b/threadworker.go index ae7e4545f2..ba544e24c2 100644 --- a/threadworker.go +++ b/threadworker.go @@ -51,6 +51,7 @@ func (handler *workerThread) beforeScriptExecution() string { handler.worker.onThreadShutdown(handler.thread.threadIndex) } handler.state.Set(state.Yielding) + scheduleOpcacheReset(handler.thread) handler.state.WaitFor(state.Ready, state.ShuttingDown) return handler.beforeScriptExecution() case state.Ready, state.TransitionComplete: @@ -226,12 +227,6 @@ func (handler *workerThread) waitForWorkerRequest() (bool, any) { globalLogger.LogAttrs(globalCtx, slog.LevelDebug, "shutting down", slog.String("worker", handler.worker.name), slog.Int("thread", handler.thread.threadIndex)) } - // flush the opcache when restarting due to watcher or admin api - // note: this is done right before frankenphp_handle_request() returns 'false' - if handler.state.Is(state.Restarting) { - C.frankenphp_reset_opcache() - } - return false, nil case requestCH = <-handler.thread.requestChan: case requestCH = <-handler.worker.requestChan: diff --git a/worker.go b/worker.go index 58680ea178..73ed5855c4 100644 --- a/worker.go +++ b/worker.go @@ -171,10 +171,10 @@ func newWorker(o workerOpt) (*worker, error) { // EXPERIMENTAL: DrainWorkers finishes all worker scripts before a graceful shutdown func DrainWorkers() { - _ = drainWorkerThreads() + _ = drainWorkerThreads(false) } -func drainWorkerThreads() []*phpThread { +func drainWorkerThreads(withRegularThreads bool) []*phpThread { var ( ready sync.WaitGroup drainedThreads []*phpThread @@ -192,7 +192,7 @@ func drainWorkerThreads() []*phpThread { // we'll proceed to restart all other threads anyway continue } - + restartCounter.Add(1) close(thread.drainChan) drainedThreads = append(drainedThreads, thread) @@ -205,6 +205,31 @@ func drainWorkerThreads() []*phpThread { worker.threadMutex.RUnlock() } + if withRegularThreads { + regularThreadMu.RLock() + ready.Add(len(regularThreads)) + + for _, thread := range regularThreads { + if !thread.state.RequestSafeStateChange(state.Restarting) { + ready.Done() + + // no state change allowed == thread is shutting down + // we'll proceed to restart all other threads anyway + continue + } + restartCounter.Add(1) + close(thread.drainChan) + drainedThreads = append(drainedThreads, thread) + + go func(thread *phpThread) { + thread.state.WaitFor(state.Yielding) + ready.Done() + }(thread) + } + + regularThreadMu.RUnlock() + } + ready.Wait() return drainedThreads @@ -213,13 +238,14 @@ func drainWorkerThreads() []*phpThread { // RestartWorkers attempts to restart all workers gracefully // All workers must be restarted at the same time to prevent issues with opcache resetting. func RestartWorkers() { - threadsAreRestarting.Store(true) - defer threadsAreRestarting.Store(false) + if !restartCounter.CompareAndSwap(0, 1) { + return // another restart is already in progress + } // disallow scaling threads while restarting workers scalingMu.Lock() defer scalingMu.Unlock() - threadsToRestart := drainWorkerThreads() + threadsToRestart := drainWorkerThreads(false) for _, thread := range threadsToRestart { thread.drainChan = make(chan struct{}) From acf2a1c84dcbe8a4fc9a374b500775b9103e635d Mon Sep 17 00:00:00 2001 From: Alliballibaba Date: Mon, 29 Dec 2025 23:28:11 +0100 Subject: [PATCH 05/19] Test with grace period (again) --- caddy/caddy_test.go | 1 - frankenphp.c | 4 ++-- frankenphp.go | 1 + 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/caddy/caddy_test.go b/caddy/caddy_test.go index 12ac84e675..aaa600d642 100644 --- a/caddy/caddy_test.go +++ b/caddy/caddy_test.go @@ -1489,7 +1489,6 @@ func TestOpcacheReset(t *testing.T) { num_threads 40 php_ini { opcache.enable 1 - zend_extension opcache.so opcache.log_verbosity_level 4 } } diff --git a/frankenphp.c b/frankenphp.c index 23b221753f..d586cb5362 100644 --- a/frankenphp.c +++ b/frankenphp.c @@ -1268,15 +1268,15 @@ int frankenphp_execute_script_cli(char *script, int argc, char **argv, } int frankenphp_reset_opcache(void) { - php_request_startup(); zend_function *opcache_reset = zend_hash_str_find_ptr(CG(function_table), ZEND_STRL("opcache_reset")); if (opcache_reset) { + php_request_startup(); ((zend_internal_function *)opcache_reset)->handler = orig_opcache_reset; zend_call_known_function(opcache_reset, NULL, NULL, NULL, 0, NULL, NULL); ((zend_internal_function *)opcache_reset)->handler = ZEND_FN(frankenphp_opcache_reset); + php_request_shutdown((void *)0); } - php_request_shutdown((void *)0); return 0; } diff --git a/frankenphp.go b/frankenphp.go index bd304789f1..227991aabb 100644 --- a/frankenphp.go +++ b/frankenphp.go @@ -798,6 +798,7 @@ func scheduleOpcacheReset(thread *phpThread) { globalLogger.Info("resetting opcache in all threads") C.frankenphp_reset_opcache() + time.Sleep(200 * time.Millisecond) // opcache_reset grace period // all threads should have restarted now restartCounter.Store(0) From d8c185ccff6c68d40cb090a74dc72769948bceb3 Mon Sep 17 00:00:00 2001 From: Alliballibaba Date: Fri, 2 Jan 2026 20:09:27 +0100 Subject: [PATCH 06/19] Force all threads to call opcache_reset(). --- frankenphp.go | 100 ++++++++++++++++++++++++++++++++-------- internal/state/state.go | 2 + threadregular.go | 2 + threadworker.go | 2 + worker.go | 77 +------------------------------ 5 files changed, 89 insertions(+), 94 deletions(-) diff --git a/frankenphp.go b/frankenphp.go index 227991aabb..d6c1a72154 100644 --- a/frankenphp.go +++ b/frankenphp.go @@ -59,9 +59,9 @@ var ( contextKey = contextKeyStruct{} serverHeader = []string{"FrankenPHP"} - isRunning bool - restartCounter atomic.Int32 - onServerShutdown []func() + isRunning bool + threadsAreRestarting atomic.Bool + onServerShutdown []func() // Set default values to make Shutdown() idempotent globalMu sync.Mutex @@ -759,49 +759,111 @@ func go_is_context_done(threadIndex C.uintptr_t) C.bool { //export go_schedule_opcache_reset func go_schedule_opcache_reset(threadIndex C.uintptr_t) { - if restartCounter.CompareAndSwap(0, 1) { - go restartThreadsForOpcacheReset() + if threadsAreRestarting.CompareAndSwap(false, true) { + go restartThreadsAndOpcacheReset(true) } } // restart all threads for an opcache_reset -func restartThreadsForOpcacheReset() { +func restartThreadsAndOpcacheReset(withRegularThreads bool) { // disallow scaling threads while restarting workers scalingMu.Lock() defer scalingMu.Unlock() - threadsToRestart := drainWorkerThreads(true) + threadsToRestart := drainThreads(withRegularThreads) + + opcacheResetWg := sync.WaitGroup{} + for _, thread := range threadsToRestart { + thread.state.Set(state.OpcacheResetting) + opcacheResetWg.Go(func() { + thread.state.WaitFor(state.OpcacheResettingDone) + }) + } + + opcacheResetWg.Wait() for _, thread := range threadsToRestart { thread.drainChan = make(chan struct{}) thread.state.Set(state.Ready) } + + threadsAreRestarting.Store(false) } -func scheduleOpcacheReset(thread *phpThread) { - restartCounter.Add(-1) - if restartCounter.Load() != 1 { - return // only the last restarting thread will trigger an actual opcache_reset +func drainThreads(withRegularThreads bool) []*phpThread { + var ( + ready sync.WaitGroup + drainedThreads []*phpThread + ) + + for _, worker := range workers { + worker.threadMutex.RLock() + ready.Add(len(worker.threads)) + + for _, thread := range worker.threads { + if !thread.state.RequestSafeStateChange(state.Restarting) { + ready.Done() + + // no state change allowed == thread is shutting down + // we'll proceed to restart all other threads anyway + continue + } + close(thread.drainChan) + drainedThreads = append(drainedThreads, thread) + + go func(thread *phpThread) { + thread.state.WaitFor(state.Yielding) + ready.Done() + }(thread) + } + + worker.threadMutex.RUnlock() + } + + if withRegularThreads { + regularThreadMu.RLock() + ready.Add(len(regularThreads)) + + for _, thread := range regularThreads { + if !thread.state.RequestSafeStateChange(state.Restarting) { + ready.Done() + + // no state change allowed == thread is shutting down + // we'll proceed to restart all other threads anyway + continue + } + close(thread.drainChan) + drainedThreads = append(drainedThreads, thread) + + go func(thread *phpThread) { + thread.state.WaitFor(state.Yielding) + ready.Done() + }(thread) + } + + regularThreadMu.RUnlock() } - workerThread, ok := thread.handler.(*workerThread) + + ready.Wait() + + return drainedThreads +} + +func scheduleOpcacheReset(thread *phpThread) { fc, _ := newDummyContext("/opcache_reset") - if ok && workerThread.worker != nil { + + if workerThread, ok := thread.handler.(*workerThread); ok { workerThread.dummyFrankenPHPContext = fc defer func() { workerThread.dummyFrankenPHPContext = nil }() } - regularThread, ok := thread.handler.(*regularThread) - if ok { + if regularThread, ok := thread.handler.(*regularThread); ok { regularThread.contextHolder.frankenPHPContext = fc defer func() { regularThread.contextHolder.frankenPHPContext = nil }() } globalLogger.Info("resetting opcache in all threads") C.frankenphp_reset_opcache() - time.Sleep(200 * time.Millisecond) // opcache_reset grace period - - // all threads should have restarted now - restartCounter.Store(0) } // ExecuteScriptCLI executes the PHP script passed as parameter. diff --git a/internal/state/state.go b/internal/state/state.go index b15c008bce..3eba4dc47e 100644 --- a/internal/state/state.go +++ b/internal/state/state.go @@ -24,6 +24,8 @@ const ( // States necessary for restarting workers Restarting State = "restarting" Yielding State = "yielding" + OpcacheResetting State = "opcache resetting" + OpcacheResettingDone State = "opcache reset done" // States necessary for transitioning between different handlers TransitionRequested State = "transition requested" diff --git a/threadregular.go b/threadregular.go index 86dade86c8..ebca0b72ad 100644 --- a/threadregular.go +++ b/threadregular.go @@ -50,7 +50,9 @@ func (handler *regularThread) beforeScriptExecution() string { return handler.waitForRequest() case state.Restarting: handler.state.Set(state.Yielding) + handler.state.WaitFor(state.OpcacheResetting) scheduleOpcacheReset(handler.thread) + handler.state.Set(state.OpcacheResettingDone) handler.state.WaitFor(state.Ready, state.ShuttingDown) return handler.beforeScriptExecution() diff --git a/threadworker.go b/threadworker.go index ba544e24c2..f0a2237e4c 100644 --- a/threadworker.go +++ b/threadworker.go @@ -51,7 +51,9 @@ func (handler *workerThread) beforeScriptExecution() string { handler.worker.onThreadShutdown(handler.thread.threadIndex) } handler.state.Set(state.Yielding) + handler.state.WaitFor(state.OpcacheResetting) scheduleOpcacheReset(handler.thread) + handler.state.Set(state.OpcacheResettingDone) handler.state.WaitFor(state.Ready, state.ShuttingDown) return handler.beforeScriptExecution() case state.Ready, state.TransitionComplete: diff --git a/worker.go b/worker.go index 73ed5855c4..c965661ea8 100644 --- a/worker.go +++ b/worker.go @@ -171,86 +171,13 @@ func newWorker(o workerOpt) (*worker, error) { // EXPERIMENTAL: DrainWorkers finishes all worker scripts before a graceful shutdown func DrainWorkers() { - _ = drainWorkerThreads(false) -} - -func drainWorkerThreads(withRegularThreads bool) []*phpThread { - var ( - ready sync.WaitGroup - drainedThreads []*phpThread - ) - - for _, worker := range workers { - worker.threadMutex.RLock() - ready.Add(len(worker.threads)) - - for _, thread := range worker.threads { - if !thread.state.RequestSafeStateChange(state.Restarting) { - ready.Done() - - // no state change allowed == thread is shutting down - // we'll proceed to restart all other threads anyway - continue - } - restartCounter.Add(1) - close(thread.drainChan) - drainedThreads = append(drainedThreads, thread) - - go func(thread *phpThread) { - thread.state.WaitFor(state.Yielding) - ready.Done() - }(thread) - } - - worker.threadMutex.RUnlock() - } - - if withRegularThreads { - regularThreadMu.RLock() - ready.Add(len(regularThreads)) - - for _, thread := range regularThreads { - if !thread.state.RequestSafeStateChange(state.Restarting) { - ready.Done() - - // no state change allowed == thread is shutting down - // we'll proceed to restart all other threads anyway - continue - } - restartCounter.Add(1) - close(thread.drainChan) - drainedThreads = append(drainedThreads, thread) - - go func(thread *phpThread) { - thread.state.WaitFor(state.Yielding) - ready.Done() - }(thread) - } - - regularThreadMu.RUnlock() - } - - ready.Wait() - - return drainedThreads + _ = drainThreads(false) } // RestartWorkers attempts to restart all workers gracefully // All workers must be restarted at the same time to prevent issues with opcache resetting. func RestartWorkers() { - if !restartCounter.CompareAndSwap(0, 1) { - return // another restart is already in progress - } - // disallow scaling threads while restarting workers - scalingMu.Lock() - defer scalingMu.Unlock() - - threadsToRestart := drainWorkerThreads(false) - - for _, thread := range threadsToRestart { - thread.drainChan = make(chan struct{}) - thread.state.Set(state.Ready) - } + restartThreadsAndOpcacheReset(false) } func (worker *worker) attachThread(thread *phpThread) { From 3e7cdd023b39d00cff97117577031b9070f55a72 Mon Sep 17 00:00:00 2001 From: Alliballibaba Date: Sat, 3 Jan 2026 21:56:54 +0100 Subject: [PATCH 07/19] test --- frankenphp.go | 3 ++- worker.go | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/frankenphp.go b/frankenphp.go index d6c1a72154..2d6a6511a1 100644 --- a/frankenphp.go +++ b/frankenphp.go @@ -862,8 +862,9 @@ func scheduleOpcacheReset(thread *phpThread) { defer func() { regularThread.contextHolder.frankenPHPContext = nil }() } - globalLogger.Info("resetting opcache in all threads") + globalLogger.Info("resetting opcache", "thread", thread.name()) C.frankenphp_reset_opcache() + globalLogger.Info("opcache reset completed", "thread", thread.name()) } // ExecuteScriptCLI executes the PHP script passed as parameter. diff --git a/worker.go b/worker.go index c965661ea8..4a3ae7cedf 100644 --- a/worker.go +++ b/worker.go @@ -177,7 +177,7 @@ func DrainWorkers() { // RestartWorkers attempts to restart all workers gracefully // All workers must be restarted at the same time to prevent issues with opcache resetting. func RestartWorkers() { - restartThreadsAndOpcacheReset(false) + restartThreadsAndOpcacheReset(true) } func (worker *worker) attachThread(thread *phpThread) { From df82e814dfbd2286c2f0555dad8185b2066db3e0 Mon Sep 17 00:00:00 2001 From: henderkes Date: Fri, 13 Mar 2026 21:00:01 +0700 Subject: [PATCH 08/19] fix clang format --- frankenphp.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/frankenphp.c b/frankenphp.c index c36c4fbf11..5e43cf74ab 100644 --- a/frankenphp.c +++ b/frankenphp.c @@ -1418,7 +1418,8 @@ int frankenphp_reset_opcache(void) { php_request_startup(); ((zend_internal_function *)opcache_reset)->handler = orig_opcache_reset; zend_call_known_function(opcache_reset, NULL, NULL, NULL, 0, NULL, NULL); - ((zend_internal_function *)opcache_reset)->handler = ZEND_FN(frankenphp_opcache_reset); + ((zend_internal_function *)opcache_reset)->handler = + ZEND_FN(frankenphp_opcache_reset); php_request_shutdown((void *)0); } From 0d87765fb8b84608df29dfc3d067f34984aacb06 Mon Sep 17 00:00:00 2001 From: henderkes Date: Fri, 13 Mar 2026 22:37:31 +0700 Subject: [PATCH 09/19] call into cgo for reset directly, no fake dummy --- frankenphp.c | 55 ++++++++++++++++++++++++++++++++------------------- frankenphp.go | 23 ++++++++------------- 2 files changed, 43 insertions(+), 35 deletions(-) diff --git a/frankenphp.c b/frankenphp.c index 5e43cf74ab..bd24b9bdc7 100644 --- a/frankenphp.c +++ b/frankenphp.c @@ -89,6 +89,25 @@ __thread HashTable *sandboxed_env = NULL; __thread zval *os_environment = NULL; zif_handler orig_opcache_reset; +/* Forward declaration */ +PHP_FUNCTION(frankenphp_opcache_reset); + +/* Try to override opcache_reset if opcache is loaded. + * Safe to call multiple times - skips if already overridden in this function + * table. Uses handler comparison instead of orig_opcache_reset check so that + * a fresh function table after PHP module restart is always re-overridden. */ +static void frankenphp_override_opcache_reset(void) { + zend_function *func = zend_hash_str_find_ptr(CG(function_table), "opcache_reset", + sizeof("opcache_reset") - 1); + if (func != NULL && func->type == ZEND_INTERNAL_FUNCTION && + ((zend_internal_function *)func)->handler != + ZEND_FN(frankenphp_opcache_reset)) { + orig_opcache_reset = ((zend_internal_function *)func)->handler; + ((zend_internal_function *)func)->handler = + ZEND_FN(frankenphp_opcache_reset); + } +} + void frankenphp_update_local_thread_context(bool is_worker) { is_worker_thread = is_worker; @@ -724,14 +743,8 @@ PHP_MINIT_FUNCTION(frankenphp) { php_error(E_WARNING, "Failed to find built-in getenv function"); } - // Override opcache_reset - func = zend_hash_str_find_ptr(CG(function_table), "opcache_reset", - sizeof("opcache_reset") - 1); - if (func != NULL && func->type == ZEND_INTERNAL_FUNCTION) { - orig_opcache_reset = ((zend_internal_function *)func)->handler; - ((zend_internal_function *)func)->handler = - ZEND_FN(frankenphp_opcache_reset); - } + // Override opcache_reset (may not be available yet if opcache loads after us) + frankenphp_override_opcache_reset(); return SUCCESS; } @@ -751,7 +764,14 @@ static zend_module_entry frankenphp_module = { static int frankenphp_startup(sapi_module_struct *sapi_module) { php_import_environment_variables = get_full_env; - return php_module_startup(sapi_module, &frankenphp_module); + int result = php_module_startup(sapi_module, &frankenphp_module); + if (result == SUCCESS) { + /* All extensions are now loaded. Override opcache_reset if opcache + * was not yet available during our MINIT (shared extension load order). */ + frankenphp_override_opcache_reset(); + } + + return result; } static int frankenphp_deactivate(void) { return SUCCESS; } @@ -1412,17 +1432,12 @@ int frankenphp_execute_script_cli(char *script, int argc, char **argv, } int frankenphp_reset_opcache(void) { - zend_function *opcache_reset = - zend_hash_str_find_ptr(CG(function_table), ZEND_STRL("opcache_reset")); - if (opcache_reset) { - php_request_startup(); - ((zend_internal_function *)opcache_reset)->handler = orig_opcache_reset; - zend_call_known_function(opcache_reset, NULL, NULL, NULL, 0, NULL, NULL); - ((zend_internal_function *)opcache_reset)->handler = - ZEND_FN(frankenphp_opcache_reset); - php_request_shutdown((void *)0); - } - + zend_execute_data execute_data; + zval retval; + memset(&execute_data, 0, sizeof(execute_data)); + ZVAL_UNDEF(&retval); + orig_opcache_reset(&execute_data, &retval); + zval_ptr_dtor(&retval); return 0; } diff --git a/frankenphp.go b/frankenphp.go index 9149226315..81aec1372e 100644 --- a/frankenphp.go +++ b/frankenphp.go @@ -765,6 +765,10 @@ func go_schedule_opcache_reset(threadIndex C.uintptr_t) { } } +// opcacheResetOnce ensures only one thread calls the actual opcache_reset. +// Multiple threads calling it concurrently can race on shared memory. +var opcacheResetOnce sync.Once + // restart all threads for an opcache_reset func restartThreadsAndOpcacheReset(withRegularThreads bool) { // disallow scaling threads while restarting workers @@ -773,6 +777,7 @@ func restartThreadsAndOpcacheReset(withRegularThreads bool) { threadsToRestart := drainThreads(withRegularThreads) + opcacheResetOnce = sync.Once{} opcacheResetWg := sync.WaitGroup{} for _, thread := range threadsToRestart { thread.state.Set(state.OpcacheResetting) @@ -851,21 +856,9 @@ func drainThreads(withRegularThreads bool) []*phpThread { } func scheduleOpcacheReset(thread *phpThread) { - fc, _ := newDummyContext("/opcache_reset") - - if workerThread, ok := thread.handler.(*workerThread); ok { - workerThread.dummyFrankenPHPContext = fc - defer func() { workerThread.dummyFrankenPHPContext = nil }() - } - - if regularThread, ok := thread.handler.(*regularThread); ok { - regularThread.contextHolder.frankenPHPContext = fc - defer func() { regularThread.contextHolder.frankenPHPContext = nil }() - } - - globalLogger.Info("resetting opcache", "thread", thread.name()) - C.frankenphp_reset_opcache() - globalLogger.Info("opcache reset completed", "thread", thread.name()) + opcacheResetOnce.Do(func() { + C.frankenphp_reset_opcache() + }) } func convertArgs(args []string) (C.int, []*C.char) { From 0564eaf1505c36521b869e87c9150a3f826b5277 Mon Sep 17 00:00:00 2001 From: henderkes Date: Fri, 13 Mar 2026 22:52:08 +0700 Subject: [PATCH 10/19] clang fmt --- frankenphp.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/frankenphp.c b/frankenphp.c index bd24b9bdc7..3f0e540adb 100644 --- a/frankenphp.c +++ b/frankenphp.c @@ -97,8 +97,8 @@ PHP_FUNCTION(frankenphp_opcache_reset); * table. Uses handler comparison instead of orig_opcache_reset check so that * a fresh function table after PHP module restart is always re-overridden. */ static void frankenphp_override_opcache_reset(void) { - zend_function *func = zend_hash_str_find_ptr(CG(function_table), "opcache_reset", - sizeof("opcache_reset") - 1); + zend_function *func = zend_hash_str_find_ptr( + CG(function_table), "opcache_reset", sizeof("opcache_reset") - 1); if (func != NULL && func->type == ZEND_INTERNAL_FUNCTION && ((zend_internal_function *)func)->handler != ZEND_FN(frankenphp_opcache_reset)) { From 49fc8784f5276d8b703447b25a111414bb356bd7 Mon Sep 17 00:00:00 2001 From: henderkes Date: Sat, 14 Mar 2026 10:37:00 +0700 Subject: [PATCH 11/19] override opcache reset handler for every php thread in php 8.2 --- frankenphp.c | 1 + 1 file changed, 1 insertion(+) diff --git a/frankenphp.c b/frankenphp.c index 3f0e540adb..3c81d072d5 100644 --- a/frankenphp.c +++ b/frankenphp.c @@ -1232,6 +1232,7 @@ bool frankenphp_new_php_thread(uintptr_t thread_index) { static int frankenphp_request_startup() { frankenphp_update_request_context(); + frankenphp_override_opcache_reset(); if (php_request_startup() == SUCCESS) { return SUCCESS; } From 22c6ba60f7c31761a069d33af824b2ac3bad720c Mon Sep 17 00:00:00 2001 From: henderkes Date: Sat, 14 Mar 2026 11:03:57 +0700 Subject: [PATCH 12/19] maybe after request startup? --- frankenphp.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frankenphp.c b/frankenphp.c index 3c81d072d5..a07cba86a1 100644 --- a/frankenphp.c +++ b/frankenphp.c @@ -1232,8 +1232,8 @@ bool frankenphp_new_php_thread(uintptr_t thread_index) { static int frankenphp_request_startup() { frankenphp_update_request_context(); - frankenphp_override_opcache_reset(); if (php_request_startup() == SUCCESS) { + frankenphp_override_opcache_reset(); return SUCCESS; } From 66702fe0d828e3c0b311cda0bbb11671ead67019 Mon Sep 17 00:00:00 2001 From: henderkes Date: Sat, 14 Mar 2026 18:39:46 +0700 Subject: [PATCH 13/19] try not resetting opcache? --- frankenphp.c | 1 - frankenphp.go | 21 ++++++++++++--------- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/frankenphp.c b/frankenphp.c index a07cba86a1..cc420aeb5d 100644 --- a/frankenphp.c +++ b/frankenphp.c @@ -86,7 +86,6 @@ HashTable *main_thread_env = NULL; __thread uintptr_t thread_index; __thread bool is_worker_thread = false; __thread HashTable *sandboxed_env = NULL; -__thread zval *os_environment = NULL; zif_handler orig_opcache_reset; /* Forward declaration */ diff --git a/frankenphp.go b/frankenphp.go index 81aec1372e..25effdc704 100644 --- a/frankenphp.go +++ b/frankenphp.go @@ -777,16 +777,19 @@ func restartThreadsAndOpcacheReset(withRegularThreads bool) { threadsToRestart := drainThreads(withRegularThreads) - opcacheResetOnce = sync.Once{} - opcacheResetWg := sync.WaitGroup{} - for _, thread := range threadsToRestart { - thread.state.Set(state.OpcacheResetting) - opcacheResetWg.Go(func() { - thread.state.WaitFor(state.OpcacheResettingDone) - }) - } + // on 8.2 debian it segfaults, skip opcache reset + if Version().VersionID >= 80300 { + opcacheResetOnce = sync.Once{} + opcacheResetWg := sync.WaitGroup{} + for _, thread := range threadsToRestart { + thread.state.Set(state.OpcacheResetting) + opcacheResetWg.Go(func() { + thread.state.WaitFor(state.OpcacheResettingDone) + }) + } - opcacheResetWg.Wait() + opcacheResetWg.Wait() + } for _, thread := range threadsToRestart { thread.drainChan = make(chan struct{}) From 7cb94e6d31e7ae25143ea8ba42b1d21d7049c116 Mon Sep 17 00:00:00 2001 From: henderkes Date: Sat, 14 Mar 2026 19:06:49 +0700 Subject: [PATCH 14/19] don't overrride opcache_reset at all in php 8.2 --- frankenphp.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/frankenphp.c b/frankenphp.c index cc420aeb5d..57c037fea6 100644 --- a/frankenphp.c +++ b/frankenphp.c @@ -742,8 +742,10 @@ PHP_MINIT_FUNCTION(frankenphp) { php_error(E_WARNING, "Failed to find built-in getenv function"); } +#if PHP_VERSION_ID >= 80300 // Override opcache_reset (may not be available yet if opcache loads after us) frankenphp_override_opcache_reset(); +#endif return SUCCESS; } @@ -765,9 +767,11 @@ static int frankenphp_startup(sapi_module_struct *sapi_module) { int result = php_module_startup(sapi_module, &frankenphp_module); if (result == SUCCESS) { +#if PHP_VERSION_ID >= 80300 /* All extensions are now loaded. Override opcache_reset if opcache * was not yet available during our MINIT (shared extension load order). */ frankenphp_override_opcache_reset(); +#endif } return result; @@ -1232,7 +1236,9 @@ bool frankenphp_new_php_thread(uintptr_t thread_index) { static int frankenphp_request_startup() { frankenphp_update_request_context(); if (php_request_startup() == SUCCESS) { +#if PHP_VERSION_ID >= 80300 frankenphp_override_opcache_reset(); +#endif return SUCCESS; } From e9533b8f216e102573860987c697534566ad1630 Mon Sep 17 00:00:00 2001 From: henderkes Date: Sat, 14 Mar 2026 19:34:18 +0700 Subject: [PATCH 15/19] dont even run the test --- caddy/caddy_test.go | 4 ++++ frankenphp.c | 2 ++ 2 files changed, 6 insertions(+) diff --git a/caddy/caddy_test.go b/caddy/caddy_test.go index ebed000925..adba4c7d21 100644 --- a/caddy/caddy_test.go +++ b/caddy/caddy_test.go @@ -16,6 +16,7 @@ import ( "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddytest" + "github.com/dunglas/frankenphp" "github.com/dunglas/frankenphp/internal/fastabs" "github.com/prometheus/client_golang/prometheus/testutil" "github.com/stretchr/testify/require" @@ -1544,6 +1545,9 @@ func TestDd(t *testing.T) { // test to force the opcache segfault race condition under concurrency (~1.7s) func TestOpcacheReset(t *testing.T) { + if frankenphp.Version().VersionID < 80300 { + t.Skip("opcache reset test requires PHP 8.3+") + } tester := caddytest.NewTester(t) tester.InitServer(` { diff --git a/frankenphp.c b/frankenphp.c index 57c037fea6..0c4da675a1 100644 --- a/frankenphp.c +++ b/frankenphp.c @@ -91,6 +91,7 @@ zif_handler orig_opcache_reset; /* Forward declaration */ PHP_FUNCTION(frankenphp_opcache_reset); +#if PHP_VERSION_ID >= 80300 /* Try to override opcache_reset if opcache is loaded. * Safe to call multiple times - skips if already overridden in this function * table. Uses handler comparison instead of orig_opcache_reset check so that @@ -106,6 +107,7 @@ static void frankenphp_override_opcache_reset(void) { ZEND_FN(frankenphp_opcache_reset); } } +#endif void frankenphp_update_local_thread_context(bool is_worker) { is_worker_thread = is_worker; From 7c28f3d4526e26542b75fe1c35925d137d1faed4 Mon Sep 17 00:00:00 2001 From: henderkes Date: Sat, 14 Mar 2026 20:18:24 +0700 Subject: [PATCH 16/19] don't wait for resetting in php 8.2 --- frankenphp.go | 3 +-- threadregular.go | 8 +++++--- threadworker.go | 8 +++++--- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/frankenphp.go b/frankenphp.go index 25effdc704..2f9b4277b0 100644 --- a/frankenphp.go +++ b/frankenphp.go @@ -777,7 +777,7 @@ func restartThreadsAndOpcacheReset(withRegularThreads bool) { threadsToRestart := drainThreads(withRegularThreads) - // on 8.2 debian it segfaults, skip opcache reset + // on 8.2 opcache_reset() segfaults, skip it entirely if Version().VersionID >= 80300 { opcacheResetOnce = sync.Once{} opcacheResetWg := sync.WaitGroup{} @@ -787,7 +787,6 @@ func restartThreadsAndOpcacheReset(withRegularThreads bool) { thread.state.WaitFor(state.OpcacheResettingDone) }) } - opcacheResetWg.Wait() } diff --git a/threadregular.go b/threadregular.go index 8b7bbd2347..5041f6f067 100644 --- a/threadregular.go +++ b/threadregular.go @@ -50,9 +50,11 @@ func (handler *regularThread) beforeScriptExecution() string { return handler.waitForRequest() case state.Restarting: handler.state.Set(state.Yielding) - handler.state.WaitFor(state.OpcacheResetting) - scheduleOpcacheReset(handler.thread) - handler.state.Set(state.OpcacheResettingDone) + if Version().VersionID >= 80300 { + handler.state.WaitFor(state.OpcacheResetting) + scheduleOpcacheReset(handler.thread) + handler.state.Set(state.OpcacheResettingDone) + } handler.state.WaitFor(state.Ready, state.ShuttingDown) return handler.beforeScriptExecution() diff --git a/threadworker.go b/threadworker.go index 68e0605a4b..61f0c5a4ef 100644 --- a/threadworker.go +++ b/threadworker.go @@ -51,9 +51,11 @@ func (handler *workerThread) beforeScriptExecution() string { handler.worker.onThreadShutdown(handler.thread.threadIndex) } handler.state.Set(state.Yielding) - handler.state.WaitFor(state.OpcacheResetting) - scheduleOpcacheReset(handler.thread) - handler.state.Set(state.OpcacheResettingDone) + if Version().VersionID >= 80300 { + handler.state.WaitFor(state.OpcacheResetting) + scheduleOpcacheReset(handler.thread) + handler.state.Set(state.OpcacheResettingDone) + } handler.state.WaitFor(state.Ready, state.ShuttingDown) return handler.beforeScriptExecution() case state.Ready, state.TransitionComplete: From d88821a8d03d95a1af5fae4e14cb152c78480659 Mon Sep 17 00:00:00 2001 From: henderkes Date: Sat, 14 Mar 2026 21:56:48 +0700 Subject: [PATCH 17/19] original opcache reset in 8.2 --- frankenphp.c | 22 +++++++++++++++++----- threadregular.go | 1 - threadworker.go | 8 ++++++++ worker.go | 2 +- 4 files changed, 26 insertions(+), 7 deletions(-) diff --git a/frankenphp.c b/frankenphp.c index 0c4da675a1..b249c6a43b 100644 --- a/frankenphp.c +++ b/frankenphp.c @@ -86,12 +86,12 @@ HashTable *main_thread_env = NULL; __thread uintptr_t thread_index; __thread bool is_worker_thread = false; __thread HashTable *sandboxed_env = NULL; -zif_handler orig_opcache_reset; +#if PHP_VERSION_ID >= 80300 /* Forward declaration */ PHP_FUNCTION(frankenphp_opcache_reset); +zif_handler orig_opcache_reset; -#if PHP_VERSION_ID >= 80300 /* Try to override opcache_reset if opcache is loaded. * Safe to call multiple times - skips if already overridden in this function * table. Uses handler comparison instead of orig_opcache_reset check so that @@ -479,12 +479,14 @@ PHP_FUNCTION(frankenphp_getenv) { } } /* }}} */ +#if PHP_VERSION_ID >= 80300 /* {{{ thread-safe opcache reset */ PHP_FUNCTION(frankenphp_opcache_reset) { go_schedule_opcache_reset(thread_index); RETVAL_TRUE; } /* }}} */ +#endif /* {{{ Fetch all HTTP request headers */ PHP_FUNCTION(frankenphp_request_headers) { @@ -768,13 +770,13 @@ static int frankenphp_startup(sapi_module_struct *sapi_module) { php_import_environment_variables = get_full_env; int result = php_module_startup(sapi_module, &frankenphp_module); +#if PHP_VERSION_ID >= 80300 && PHP_VERSION_ID < 80500 if (result == SUCCESS) { -#if PHP_VERSION_ID >= 80300 /* All extensions are now loaded. Override opcache_reset if opcache * was not yet available during our MINIT (shared extension load order). */ frankenphp_override_opcache_reset(); -#endif } +#endif return result; } @@ -1238,7 +1240,9 @@ bool frankenphp_new_php_thread(uintptr_t thread_index) { static int frankenphp_request_startup() { frankenphp_update_request_context(); if (php_request_startup() == SUCCESS) { -#if PHP_VERSION_ID >= 80300 +#if PHP_VERSION_ID >= 80300 && PHP_VERSION_ID < 80500 + /* for php 8.5+ opcache is always compiled statically, so it's already + * hooked in main request startup */ frankenphp_override_opcache_reset(); #endif return SUCCESS; @@ -1440,12 +1444,20 @@ int frankenphp_execute_script_cli(char *script, int argc, char **argv, } int frankenphp_reset_opcache(void) { +#if PHP_VERSION_ID >= 80300 zend_execute_data execute_data; zval retval; memset(&execute_data, 0, sizeof(execute_data)); ZVAL_UNDEF(&retval); orig_opcache_reset(&execute_data, &retval); zval_ptr_dtor(&retval); +#else + zend_function *opcache_reset = + zend_hash_str_find_ptr(CG(function_table), ZEND_STRL("opcache_reset")); + if (opcache_reset) { + zend_call_known_function(opcache_reset, NULL, NULL, NULL, 0, NULL, NULL); + } +#endif return 0; } diff --git a/threadregular.go b/threadregular.go index 5041f6f067..08f70463d8 100644 --- a/threadregular.go +++ b/threadregular.go @@ -57,7 +57,6 @@ func (handler *regularThread) beforeScriptExecution() string { } handler.state.WaitFor(state.Ready, state.ShuttingDown) return handler.beforeScriptExecution() - case state.Ready: return handler.waitForRequest() diff --git a/threadworker.go b/threadworker.go index 61f0c5a4ef..dba7b78254 100644 --- a/threadworker.go +++ b/threadworker.go @@ -229,6 +229,14 @@ func (handler *workerThread) waitForWorkerRequest() (bool, any) { globalLogger.LogAttrs(globalCtx, slog.LevelDebug, "shutting down", slog.String("worker", handler.worker.name), slog.Int("thread", handler.thread.threadIndex)) } + if Version().VersionID < 80300 { + // flush the opcache when restarting due to watcher or admin api + // note: this is done right before frankenphp_handle_request() returns 'false' + if handler.state.Is(state.Restarting) { + C.frankenphp_reset_opcache() + } + } + return false, nil case requestCH = <-handler.thread.requestChan: case requestCH = <-handler.worker.requestChan: diff --git a/worker.go b/worker.go index ef624c3724..5f9c228abd 100644 --- a/worker.go +++ b/worker.go @@ -173,7 +173,7 @@ func DrainWorkers() { // RestartWorkers attempts to restart all workers gracefully // All workers must be restarted at the same time to prevent issues with opcache resetting. func RestartWorkers() { - restartThreadsAndOpcacheReset(true) + restartThreadsAndOpcacheReset(false) } func (worker *worker) attachThread(thread *phpThread) { From 45d49c1a6504a9e3de0f86a7e8c4267ce0c0d82d Mon Sep 17 00:00:00 2001 From: henderkes Date: Sun, 15 Mar 2026 09:35:15 +0700 Subject: [PATCH 18/19] make it run on 8.2 again --- caddy/caddy_test.go | 4 ---- frankenphp.c | 29 ++++++++--------------------- frankenphp.go | 19 ++++++++----------- threadregular.go | 8 +++----- threadworker.go | 20 +++++--------------- 5 files changed, 24 insertions(+), 56 deletions(-) diff --git a/caddy/caddy_test.go b/caddy/caddy_test.go index adba4c7d21..ebed000925 100644 --- a/caddy/caddy_test.go +++ b/caddy/caddy_test.go @@ -16,7 +16,6 @@ import ( "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddytest" - "github.com/dunglas/frankenphp" "github.com/dunglas/frankenphp/internal/fastabs" "github.com/prometheus/client_golang/prometheus/testutil" "github.com/stretchr/testify/require" @@ -1545,9 +1544,6 @@ func TestDd(t *testing.T) { // test to force the opcache segfault race condition under concurrency (~1.7s) func TestOpcacheReset(t *testing.T) { - if frankenphp.Version().VersionID < 80300 { - t.Skip("opcache reset test requires PHP 8.3+") - } tester := caddytest.NewTester(t) tester.InitServer(` { diff --git a/frankenphp.c b/frankenphp.c index b249c6a43b..821dd8f3c1 100644 --- a/frankenphp.c +++ b/frankenphp.c @@ -87,7 +87,6 @@ __thread uintptr_t thread_index; __thread bool is_worker_thread = false; __thread HashTable *sandboxed_env = NULL; -#if PHP_VERSION_ID >= 80300 /* Forward declaration */ PHP_FUNCTION(frankenphp_opcache_reset); zif_handler orig_opcache_reset; @@ -107,7 +106,6 @@ static void frankenphp_override_opcache_reset(void) { ZEND_FN(frankenphp_opcache_reset); } } -#endif void frankenphp_update_local_thread_context(bool is_worker) { is_worker_thread = is_worker; @@ -479,14 +477,12 @@ PHP_FUNCTION(frankenphp_getenv) { } } /* }}} */ -#if PHP_VERSION_ID >= 80300 /* {{{ thread-safe opcache reset */ PHP_FUNCTION(frankenphp_opcache_reset) { go_schedule_opcache_reset(thread_index); RETVAL_TRUE; } /* }}} */ -#endif /* {{{ Fetch all HTTP request headers */ PHP_FUNCTION(frankenphp_request_headers) { @@ -746,10 +742,9 @@ PHP_MINIT_FUNCTION(frankenphp) { php_error(E_WARNING, "Failed to find built-in getenv function"); } -#if PHP_VERSION_ID >= 80300 - // Override opcache_reset (may not be available yet if opcache loads after us) + // Override opcache_reset (may not be available yet if opcache loads as a + // shared extension in PHP 8.4 and below) frankenphp_override_opcache_reset(); -#endif return SUCCESS; } @@ -770,10 +765,10 @@ static int frankenphp_startup(sapi_module_struct *sapi_module) { php_import_environment_variables = get_full_env; int result = php_module_startup(sapi_module, &frankenphp_module); -#if PHP_VERSION_ID >= 80300 && PHP_VERSION_ID < 80500 +#if PHP_VERSION_ID < 80500 if (result == SUCCESS) { - /* All extensions are now loaded. Override opcache_reset if opcache - * was not yet available during our MINIT (shared extension load order). */ + /* Override opcache here again if loaded as a shared extension + * (php 8.4 and under) */ frankenphp_override_opcache_reset(); } #endif @@ -1240,9 +1235,9 @@ bool frankenphp_new_php_thread(uintptr_t thread_index) { static int frankenphp_request_startup() { frankenphp_update_request_context(); if (php_request_startup() == SUCCESS) { -#if PHP_VERSION_ID >= 80300 && PHP_VERSION_ID < 80500 - /* for php 8.5+ opcache is always compiled statically, so it's already - * hooked in main request startup */ +#if PHP_VERSION_ID < 80500 + /* Override opcache here again if loaded as a shared extension + * (php 8.4 and under) */ frankenphp_override_opcache_reset(); #endif return SUCCESS; @@ -1444,20 +1439,12 @@ int frankenphp_execute_script_cli(char *script, int argc, char **argv, } int frankenphp_reset_opcache(void) { -#if PHP_VERSION_ID >= 80300 zend_execute_data execute_data; zval retval; memset(&execute_data, 0, sizeof(execute_data)); ZVAL_UNDEF(&retval); orig_opcache_reset(&execute_data, &retval); zval_ptr_dtor(&retval); -#else - zend_function *opcache_reset = - zend_hash_str_find_ptr(CG(function_table), ZEND_STRL("opcache_reset")); - if (opcache_reset) { - zend_call_known_function(opcache_reset, NULL, NULL, NULL, 0, NULL, NULL); - } -#endif return 0; } diff --git a/frankenphp.go b/frankenphp.go index 2f9b4277b0..e82570400a 100644 --- a/frankenphp.go +++ b/frankenphp.go @@ -777,18 +777,15 @@ func restartThreadsAndOpcacheReset(withRegularThreads bool) { threadsToRestart := drainThreads(withRegularThreads) - // on 8.2 opcache_reset() segfaults, skip it entirely - if Version().VersionID >= 80300 { - opcacheResetOnce = sync.Once{} - opcacheResetWg := sync.WaitGroup{} - for _, thread := range threadsToRestart { - thread.state.Set(state.OpcacheResetting) - opcacheResetWg.Go(func() { - thread.state.WaitFor(state.OpcacheResettingDone) - }) - } - opcacheResetWg.Wait() + opcacheResetOnce = sync.Once{} + opcacheResetWg := sync.WaitGroup{} + for _, thread := range threadsToRestart { + thread.state.Set(state.OpcacheResetting) + opcacheResetWg.Go(func() { + thread.state.WaitFor(state.OpcacheResettingDone) + }) } + opcacheResetWg.Wait() for _, thread := range threadsToRestart { thread.drainChan = make(chan struct{}) diff --git a/threadregular.go b/threadregular.go index 08f70463d8..74bce3eff4 100644 --- a/threadregular.go +++ b/threadregular.go @@ -50,11 +50,9 @@ func (handler *regularThread) beforeScriptExecution() string { return handler.waitForRequest() case state.Restarting: handler.state.Set(state.Yielding) - if Version().VersionID >= 80300 { - handler.state.WaitFor(state.OpcacheResetting) - scheduleOpcacheReset(handler.thread) - handler.state.Set(state.OpcacheResettingDone) - } + handler.state.WaitFor(state.OpcacheResetting) + scheduleOpcacheReset(handler.thread) + handler.state.Set(state.OpcacheResettingDone) handler.state.WaitFor(state.Ready, state.ShuttingDown) return handler.beforeScriptExecution() case state.Ready: diff --git a/threadworker.go b/threadworker.go index dba7b78254..d715c8d18f 100644 --- a/threadworker.go +++ b/threadworker.go @@ -51,11 +51,9 @@ func (handler *workerThread) beforeScriptExecution() string { handler.worker.onThreadShutdown(handler.thread.threadIndex) } handler.state.Set(state.Yielding) - if Version().VersionID >= 80300 { - handler.state.WaitFor(state.OpcacheResetting) - scheduleOpcacheReset(handler.thread) - handler.state.Set(state.OpcacheResettingDone) - } + handler.state.WaitFor(state.OpcacheResetting) + scheduleOpcacheReset(handler.thread) + handler.state.Set(state.OpcacheResettingDone) handler.state.WaitFor(state.Ready, state.ShuttingDown) return handler.beforeScriptExecution() case state.Ready, state.TransitionComplete: @@ -75,9 +73,9 @@ func (handler *workerThread) beforeScriptExecution() string { // signal to stop return "" + default: + panic("unexpected state: " + handler.state.Name()) } - - panic("unexpected state: " + handler.state.Name()) } func (handler *workerThread) afterScriptExecution(exitStatus int) { @@ -229,14 +227,6 @@ func (handler *workerThread) waitForWorkerRequest() (bool, any) { globalLogger.LogAttrs(globalCtx, slog.LevelDebug, "shutting down", slog.String("worker", handler.worker.name), slog.Int("thread", handler.thread.threadIndex)) } - if Version().VersionID < 80300 { - // flush the opcache when restarting due to watcher or admin api - // note: this is done right before frankenphp_handle_request() returns 'false' - if handler.state.Is(state.Restarting) { - C.frankenphp_reset_opcache() - } - } - return false, nil case requestCH = <-handler.thread.requestChan: case requestCH = <-handler.worker.requestChan: From d189770cc7c273a68a92968d4780be9ae2a07494 Mon Sep 17 00:00:00 2001 From: Marc Date: Mon, 16 Mar 2026 09:32:47 +0700 Subject: [PATCH 19/19] Update worker.go Signed-off-by: Marc --- worker.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/worker.go b/worker.go index 5f9c228abd..ef624c3724 100644 --- a/worker.go +++ b/worker.go @@ -173,7 +173,7 @@ func DrainWorkers() { // RestartWorkers attempts to restart all workers gracefully // All workers must be restarted at the same time to prevent issues with opcache resetting. func RestartWorkers() { - restartThreadsAndOpcacheReset(false) + restartThreadsAndOpcacheReset(true) } func (worker *worker) attachThread(thread *phpThread) {