worker.go 4.6 KB

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