worker.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. package frankenphp
  2. // #include <stdlib.h>
  3. // #include "frankenphp.h"
  4. import "C"
  5. import (
  6. "errors"
  7. "fmt"
  8. "net/http"
  9. "path/filepath"
  10. "runtime/cgo"
  11. "sync"
  12. "go.uber.org/zap"
  13. "go.uber.org/zap/zapcore"
  14. )
  15. var (
  16. workersRequestChans sync.Map // map[fileName]chan *http.Request
  17. workersReadyWG sync.WaitGroup
  18. )
  19. // TODO: start all the worker in parallell to reduce the boot time
  20. func initWorkers(opt []workerOpt) error {
  21. for _, w := range opt {
  22. if err := startWorkers(w.fileName, w.num, w.env); err != nil {
  23. return err
  24. }
  25. }
  26. return nil
  27. }
  28. func startWorkers(fileName string, nbWorkers int, env PreparedEnv) error {
  29. absFileName, err := filepath.Abs(fileName)
  30. if err != nil {
  31. return fmt.Errorf("workers %q: %w", fileName, err)
  32. }
  33. if _, ok := workersRequestChans.Load(absFileName); ok {
  34. return fmt.Errorf("workers %q: already started", absFileName)
  35. }
  36. workersRequestChans.Store(absFileName, make(chan *http.Request))
  37. shutdownWG.Add(nbWorkers)
  38. workersReadyWG.Add(nbWorkers)
  39. var (
  40. m sync.RWMutex
  41. errs []error
  42. )
  43. if env == nil {
  44. env = make(PreparedEnv, 1)
  45. }
  46. env["FRANKENPHP_WORKER\x00"] = "1"
  47. l := getLogger()
  48. for i := 0; i < nbWorkers; i++ {
  49. go func() {
  50. defer shutdownWG.Done()
  51. for {
  52. // Create main dummy request
  53. r, err := http.NewRequest(http.MethodGet, filepath.Base(absFileName), nil)
  54. if err != nil {
  55. panic(err)
  56. }
  57. r, err = NewRequestWithContext(
  58. r,
  59. WithRequestDocumentRoot(filepath.Dir(absFileName), false),
  60. WithRequestPreparedEnv(env),
  61. )
  62. if err != nil {
  63. panic(err)
  64. }
  65. if c := l.Check(zapcore.DebugLevel, "starting"); c != nil {
  66. c.Write(zap.String("worker", absFileName), zap.Int("num", nbWorkers))
  67. }
  68. if err := ServeHTTP(nil, r); err != nil {
  69. panic(err)
  70. }
  71. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  72. if fc.currentWorkerRequest != 0 {
  73. // Terminate the pending HTTP request handled by the worker
  74. maybeCloseContext(fc.currentWorkerRequest.Value().(*http.Request).Context().Value(contextKey).(*FrankenPHPContext))
  75. fc.currentWorkerRequest.Delete()
  76. fc.currentWorkerRequest = 0
  77. }
  78. // TODO: make the max restart configurable
  79. if _, ok := workersRequestChans.Load(absFileName); ok {
  80. workersReadyWG.Add(1)
  81. if fc.exitStatus == 0 {
  82. if c := l.Check(zapcore.InfoLevel, "restarting"); c != nil {
  83. c.Write(zap.String("worker", absFileName))
  84. }
  85. } else {
  86. if c := l.Check(zapcore.ErrorLevel, "unexpected termination, restarting"); c != nil {
  87. c.Write(zap.String("worker", absFileName), zap.Int("exit_status", int(fc.exitStatus)))
  88. }
  89. }
  90. } else {
  91. break
  92. }
  93. }
  94. // TODO: check if the termination is expected
  95. if c := l.Check(zapcore.DebugLevel, "terminated"); c != nil {
  96. c.Write(zap.String("worker", absFileName))
  97. }
  98. }()
  99. }
  100. workersReadyWG.Wait()
  101. m.Lock()
  102. defer m.Unlock()
  103. if len(errs) == 0 {
  104. return nil
  105. }
  106. return fmt.Errorf("workers %q: error while starting: %w", fileName, errors.Join(errs...))
  107. }
  108. func stopWorkers() {
  109. workersRequestChans.Range(func(k, v any) bool {
  110. workersRequestChans.Delete(k)
  111. return true
  112. })
  113. }
  114. //export go_frankenphp_worker_ready
  115. func go_frankenphp_worker_ready() {
  116. workersReadyWG.Done()
  117. }
  118. //export go_frankenphp_worker_handle_request_start
  119. func go_frankenphp_worker_handle_request_start(mrh C.uintptr_t) C.uintptr_t {
  120. mainRequest := cgo.Handle(mrh).Value().(*http.Request)
  121. fc := mainRequest.Context().Value(contextKey).(*FrankenPHPContext)
  122. v, ok := workersRequestChans.Load(fc.scriptFilename)
  123. if !ok {
  124. // Probably shutting down
  125. return 0
  126. }
  127. rc := v.(chan *http.Request)
  128. l := getLogger()
  129. if c := l.Check(zapcore.DebugLevel, "waiting for request"); c != nil {
  130. c.Write(zap.String("worker", fc.scriptFilename))
  131. }
  132. var r *http.Request
  133. select {
  134. case <-done:
  135. if c := l.Check(zapcore.DebugLevel, "shutting down"); c != nil {
  136. c.Write(zap.String("worker", fc.scriptFilename))
  137. }
  138. return 0
  139. case r = <-rc:
  140. }
  141. fc.currentWorkerRequest = cgo.NewHandle(r)
  142. r.Context().Value(handleKey).(*handleList).AddHandle(fc.currentWorkerRequest)
  143. if c := l.Check(zapcore.DebugLevel, "request handling started"); c != nil {
  144. c.Write(zap.String("worker", fc.scriptFilename), zap.String("url", r.RequestURI))
  145. }
  146. if err := updateServerContext(r, false, mrh); err != nil {
  147. // Unexpected error
  148. if c := l.Check(zapcore.DebugLevel, "unexpected error"); c != nil {
  149. c.Write(zap.String("worker", fc.scriptFilename), zap.String("url", r.RequestURI), zap.Error(err))
  150. }
  151. return 0
  152. }
  153. return C.uintptr_t(fc.currentWorkerRequest)
  154. }
  155. //export go_frankenphp_finish_request
  156. func go_frankenphp_finish_request(mrh, rh C.uintptr_t, deleteHandle bool) {
  157. rHandle := cgo.Handle(rh)
  158. r := rHandle.Value().(*http.Request)
  159. fc := r.Context().Value(contextKey).(*FrankenPHPContext)
  160. if deleteHandle {
  161. r.Context().Value(handleKey).(*handleList).FreeAll()
  162. cgo.Handle(mrh).Value().(*http.Request).Context().Value(contextKey).(*FrankenPHPContext).currentWorkerRequest = 0
  163. }
  164. maybeCloseContext(fc)
  165. if c := fc.logger.Check(zapcore.DebugLevel, "request handling finished"); c != nil {
  166. var fields []zap.Field
  167. if mrh == 0 {
  168. fields = append(fields, zap.String("worker", fc.scriptFilename), zap.String("url", r.RequestURI))
  169. } else {
  170. fields = append(fields, zap.String("url", r.RequestURI))
  171. }
  172. c.Write(fields...)
  173. }
  174. }