thread-worker.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. package frankenphp
  2. // #include "frankenphp.h"
  3. import "C"
  4. import (
  5. "net/http"
  6. "path/filepath"
  7. "time"
  8. "go.uber.org/zap"
  9. "go.uber.org/zap/zapcore"
  10. )
  11. // representation of a thread assigned to a worker script
  12. // executes the PHP worker script in a loop
  13. // implements the threadHandler interface
  14. type workerThread struct {
  15. state *threadState
  16. thread *phpThread
  17. worker *worker
  18. fakeRequest *http.Request
  19. workerRequest *http.Request
  20. backoff *exponentialBackoff
  21. inRequest bool // true if the worker is currently handling a request
  22. }
  23. func convertToWorkerThread(thread *phpThread, worker *worker) {
  24. thread.setHandler(&workerThread{
  25. state: thread.state,
  26. thread: thread,
  27. worker: worker,
  28. backoff: &exponentialBackoff{
  29. maxBackoff: 1 * time.Second,
  30. minBackoff: 100 * time.Millisecond,
  31. maxConsecutiveFailures: 6,
  32. },
  33. })
  34. worker.attachThread(thread)
  35. }
  36. // beforeScriptExecution returns the name of the script or an empty string on shutdown
  37. func (handler *workerThread) beforeScriptExecution() string {
  38. switch handler.state.get() {
  39. case stateTransitionRequested:
  40. handler.worker.detachThread(handler.thread)
  41. return handler.thread.transitionToNewHandler()
  42. case stateRestarting:
  43. handler.state.set(stateYielding)
  44. handler.state.waitFor(stateReady, stateShuttingDown)
  45. return handler.beforeScriptExecution()
  46. case stateReady, stateTransitionComplete:
  47. setupWorkerScript(handler, handler.worker)
  48. return handler.worker.fileName
  49. case stateShuttingDown:
  50. // signal to stop
  51. return ""
  52. }
  53. panic("unexpected state: " + handler.state.name())
  54. }
  55. func (handler *workerThread) afterScriptExecution(exitStatus int) {
  56. tearDownWorkerScript(handler, exitStatus)
  57. }
  58. func (handler *workerThread) getActiveRequest() *http.Request {
  59. if handler.workerRequest != nil {
  60. return handler.workerRequest
  61. }
  62. return handler.fakeRequest
  63. }
  64. func setupWorkerScript(handler *workerThread, worker *worker) {
  65. handler.backoff.wait()
  66. metrics.StartWorker(worker.fileName)
  67. // Create a dummy request to set up the worker
  68. r, err := http.NewRequest(http.MethodGet, filepath.Base(worker.fileName), nil)
  69. if err != nil {
  70. panic(err)
  71. }
  72. r, err = NewRequestWithContext(
  73. r,
  74. WithRequestDocumentRoot(filepath.Dir(worker.fileName), false),
  75. WithRequestPreparedEnv(worker.env),
  76. )
  77. if err != nil {
  78. panic(err)
  79. }
  80. if err := updateServerContext(handler.thread, r, true, false); err != nil {
  81. panic(err)
  82. }
  83. handler.fakeRequest = r
  84. if c := logger.Check(zapcore.DebugLevel, "starting"); c != nil {
  85. c.Write(zap.String("worker", worker.fileName), zap.Int("thread", handler.thread.threadIndex))
  86. }
  87. }
  88. func tearDownWorkerScript(handler *workerThread, exitStatus int) {
  89. // if the worker request is not nil, the script might have crashed
  90. // make sure to close the worker request context
  91. if handler.workerRequest != nil {
  92. fc := handler.workerRequest.Context().Value(contextKey).(*FrankenPHPContext)
  93. maybeCloseContext(fc)
  94. handler.workerRequest = nil
  95. }
  96. fc := handler.fakeRequest.Context().Value(contextKey).(*FrankenPHPContext)
  97. fc.exitStatus = exitStatus
  98. defer func() {
  99. handler.fakeRequest = nil
  100. }()
  101. // on exit status 0 we just run the worker script again
  102. worker := handler.worker
  103. if fc.exitStatus == 0 {
  104. // TODO: make the max restart configurable
  105. metrics.StopWorker(worker.fileName, StopReasonRestart)
  106. handler.backoff.recordSuccess()
  107. if c := logger.Check(zapcore.DebugLevel, "restarting"); c != nil {
  108. c.Write(zap.String("worker", worker.fileName))
  109. }
  110. return
  111. }
  112. // TODO: error status
  113. // on exit status 1 we apply an exponential backoff when restarting
  114. metrics.StopWorker(worker.fileName, StopReasonCrash)
  115. if !handler.inRequest && handler.backoff.recordFailure() {
  116. if !watcherIsEnabled {
  117. logger.Panic("too many consecutive worker failures", zap.String("worker", worker.fileName), zap.Int("failures", handler.backoff.failureCount))
  118. }
  119. logger.Warn("many consecutive worker failures", zap.String("worker", worker.fileName), zap.Int("failures", handler.backoff.failureCount))
  120. }
  121. }
  122. // waitForWorkerRequest is called during frankenphp_handle_request in the php worker script.
  123. func (handler *workerThread) waitForWorkerRequest() bool {
  124. // unpin any memory left over from previous requests
  125. handler.thread.Unpin()
  126. if c := logger.Check(zapcore.DebugLevel, "waiting for request"); c != nil {
  127. c.Write(zap.String("worker", handler.worker.fileName))
  128. }
  129. if handler.state.compareAndSwap(stateTransitionComplete, stateReady) {
  130. metrics.ReadyWorker(handler.worker.fileName)
  131. }
  132. var r *http.Request
  133. select {
  134. case <-handler.thread.drainChan:
  135. if c := logger.Check(zapcore.DebugLevel, "shutting down"); c != nil {
  136. c.Write(zap.String("worker", handler.worker.fileName))
  137. }
  138. // execute opcache_reset if the restart was triggered by the watcher
  139. if watcherIsEnabled && handler.state.is(stateRestarting) {
  140. C.frankenphp_reset_opcache()
  141. }
  142. return false
  143. case r = <-handler.thread.requestChan:
  144. case r = <-handler.worker.requestChan:
  145. }
  146. handler.workerRequest = r
  147. if c := logger.Check(zapcore.DebugLevel, "request handling started"); c != nil {
  148. c.Write(zap.String("worker", handler.worker.fileName), zap.String("url", r.RequestURI))
  149. }
  150. handler.inRequest = true
  151. if err := updateServerContext(handler.thread, r, false, true); err != nil {
  152. // Unexpected error or invalid request
  153. if c := logger.Check(zapcore.DebugLevel, "unexpected error"); c != nil {
  154. c.Write(zap.String("worker", handler.worker.fileName), zap.String("url", r.RequestURI), zap.Error(err))
  155. }
  156. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  157. rejectRequest(fc.responseWriter, err.Error())
  158. maybeCloseContext(fc)
  159. handler.workerRequest = nil
  160. return handler.waitForWorkerRequest()
  161. }
  162. return true
  163. }
  164. // go_frankenphp_worker_handle_request_start is called at the start of every php request served.
  165. //
  166. //export go_frankenphp_worker_handle_request_start
  167. func go_frankenphp_worker_handle_request_start(threadIndex C.uintptr_t) C.bool {
  168. handler := phpThreads[threadIndex].handler.(*workerThread)
  169. return C.bool(handler.waitForWorkerRequest())
  170. }
  171. // go_frankenphp_finish_worker_request is called at the end of every php request served.
  172. //
  173. //export go_frankenphp_finish_worker_request
  174. func go_frankenphp_finish_worker_request(threadIndex C.uintptr_t) {
  175. thread := phpThreads[threadIndex]
  176. r := thread.getActiveRequest()
  177. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  178. maybeCloseContext(fc)
  179. thread.handler.(*workerThread).workerRequest = nil
  180. thread.handler.(*workerThread).inRequest = false
  181. if c := fc.logger.Check(zapcore.DebugLevel, "request handling finished"); c != nil {
  182. c.Write(zap.String("worker", fc.scriptFilename), zap.String("url", r.RequestURI))
  183. }
  184. }
  185. // when frankenphp_finish_request() is directly called from PHP
  186. //
  187. //export go_frankenphp_finish_php_request
  188. func go_frankenphp_finish_php_request(threadIndex C.uintptr_t) {
  189. r := phpThreads[threadIndex].getActiveRequest()
  190. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  191. maybeCloseContext(fc)
  192. if c := fc.logger.Check(zapcore.DebugLevel, "request handling finished"); c != nil {
  193. c.Write(zap.String("url", r.RequestURI))
  194. }
  195. }