scaling.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. package frankenphp
  2. //#include "frankenphp.h"
  3. //#include <sys/resource.h>
  4. import "C"
  5. import (
  6. "errors"
  7. "sync"
  8. "sync/atomic"
  9. "time"
  10. "github.com/dunglas/frankenphp/internal/cpu"
  11. "go.uber.org/zap"
  12. )
  13. // TODO: these constants need some real-world trial
  14. const (
  15. // requests have to be stalled for at least this amount of time before scaling
  16. minStallTime = 5 * time.Millisecond
  17. // time to check for CPU usage before scaling a single thread
  18. cpuProbeTime = 120 * time.Millisecond
  19. // do not scale over this amount of CPU usage
  20. maxCpuUsageForScaling = 0.8
  21. // upscale stalled threads every x milliseconds
  22. upscaleCheckTime = 100 * time.Millisecond
  23. // downscale idle threads every x seconds
  24. downScaleCheckTime = 5 * time.Second
  25. // max amount of threads stopped in one iteration of downScaleCheckTime
  26. maxTerminationCount = 10
  27. // autoscaled threads waiting for longer than this time are downscaled
  28. maxThreadIdleTime = 5 * time.Second
  29. )
  30. var (
  31. autoScaledThreads = []*phpThread{}
  32. scaleChan = make(chan *FrankenPHPContext)
  33. scalingMu = new(sync.RWMutex)
  34. disallowScaling = atomic.Bool{}
  35. MaxThreadsReachedError = errors.New("max amount of overall threads reached")
  36. CannotRemoveLastThreadError = errors.New("cannot remove last thread")
  37. WorkerNotFoundError = errors.New("worker not found for given filename")
  38. )
  39. func initAutoScaling(mainThread *phpMainThread) {
  40. if mainThread.maxThreads <= mainThread.numThreads {
  41. return
  42. }
  43. maxScaledThreads := mainThread.maxThreads - mainThread.numThreads
  44. scalingMu.Lock()
  45. autoScaledThreads = make([]*phpThread, 0, maxScaledThreads)
  46. scalingMu.Unlock()
  47. go startUpscalingThreads(mainThread.done, maxScaledThreads)
  48. go startDownScalingThreads(mainThread.done)
  49. }
  50. func drainAutoScaling() {
  51. scalingMu.Lock()
  52. logger.Debug("shutting down autoscaling", zap.Int("autoScaledThreads", len(autoScaledThreads)))
  53. scalingMu.Unlock()
  54. }
  55. func addRegularThread() (*phpThread, error) {
  56. thread := getInactivePHPThread()
  57. if thread == nil {
  58. return nil, MaxThreadsReachedError
  59. }
  60. convertToRegularThread(thread)
  61. thread.state.waitFor(stateReady, stateShuttingDown, stateReserved)
  62. return thread, nil
  63. }
  64. func removeRegularThread() error {
  65. regularThreadMu.RLock()
  66. if len(regularThreads) <= 1 {
  67. regularThreadMu.RUnlock()
  68. return CannotRemoveLastThreadError
  69. }
  70. thread := regularThreads[len(regularThreads)-1]
  71. regularThreadMu.RUnlock()
  72. thread.shutdown()
  73. return nil
  74. }
  75. func addWorkerThread(worker *worker) (*phpThread, error) {
  76. thread := getInactivePHPThread()
  77. if thread == nil {
  78. return nil, MaxThreadsReachedError
  79. }
  80. convertToWorkerThread(thread, worker)
  81. thread.state.waitFor(stateReady, stateShuttingDown, stateReserved)
  82. return thread, nil
  83. }
  84. func removeWorkerThread(worker *worker) error {
  85. worker.threadMutex.RLock()
  86. if len(worker.threads) <= 1 {
  87. worker.threadMutex.RUnlock()
  88. return CannotRemoveLastThreadError
  89. }
  90. thread := worker.threads[len(worker.threads)-1]
  91. worker.threadMutex.RUnlock()
  92. thread.shutdown()
  93. return nil
  94. }
  95. // Add a worker PHP threads automatically
  96. func scaleWorkerThread(worker *worker) {
  97. scalingMu.Lock()
  98. defer scalingMu.Unlock()
  99. if !mainThread.state.is(stateReady) {
  100. return
  101. }
  102. // probe CPU usage before scaling
  103. if !cpu.ProbeCPUs(cpuProbeTime, maxCpuUsageForScaling, mainThread.done) {
  104. return
  105. }
  106. thread, err := addWorkerThread(worker)
  107. if err != nil {
  108. logger.Warn("could not increase max_threads, consider raising this limit", zap.String("worker", worker.fileName), zap.Error(err))
  109. return
  110. }
  111. autoScaledThreads = append(autoScaledThreads, thread)
  112. }
  113. // Add a regular PHP thread automatically
  114. func scaleRegularThread() {
  115. scalingMu.Lock()
  116. defer scalingMu.Unlock()
  117. if !mainThread.state.is(stateReady) {
  118. return
  119. }
  120. // probe CPU usage before scaling
  121. if !cpu.ProbeCPUs(cpuProbeTime, maxCpuUsageForScaling, mainThread.done) {
  122. return
  123. }
  124. thread, err := addRegularThread()
  125. if err != nil {
  126. logger.Warn("could not increase max_threads, consider raising this limit", zap.Error(err))
  127. return
  128. }
  129. autoScaledThreads = append(autoScaledThreads, thread)
  130. }
  131. func startUpscalingThreads(done chan struct{}, maxScaledThreads int) {
  132. for {
  133. scalingMu.Lock()
  134. scaledThreadCount := len(autoScaledThreads)
  135. scalingMu.Unlock()
  136. if scaledThreadCount >= maxScaledThreads {
  137. // we have reached max_threads, check again later
  138. select {
  139. case <-done:
  140. return
  141. case <-time.After(downScaleCheckTime):
  142. continue
  143. }
  144. }
  145. select {
  146. case fc := <-scaleChan:
  147. timeSinceStalled := time.Since(fc.startedAt)
  148. // if the request has not been stalled long enough, wait and repeat
  149. if timeSinceStalled < minStallTime {
  150. select {
  151. case <-done:
  152. return
  153. case <-time.After(minStallTime - timeSinceStalled):
  154. continue
  155. }
  156. }
  157. // if the request has been stalled long enough, scale
  158. if worker, ok := workers[fc.scriptFilename]; ok {
  159. scaleWorkerThread(worker)
  160. } else {
  161. scaleRegularThread()
  162. }
  163. case <-done:
  164. return
  165. }
  166. }
  167. }
  168. func startDownScalingThreads(done chan struct{}) {
  169. for {
  170. select {
  171. case <-done:
  172. return
  173. case <-time.After(downScaleCheckTime):
  174. deactivateThreads()
  175. }
  176. }
  177. }
  178. // Check all threads and remove those that have been inactive for too long
  179. func deactivateThreads() {
  180. stoppedThreadCount := 0
  181. scalingMu.Lock()
  182. defer scalingMu.Unlock()
  183. for i := len(autoScaledThreads) - 1; i >= 0; i-- {
  184. thread := autoScaledThreads[i]
  185. // the thread might have been stopped otherwise, remove it
  186. if thread.state.is(stateReserved) {
  187. autoScaledThreads = append(autoScaledThreads[:i], autoScaledThreads[i+1:]...)
  188. continue
  189. }
  190. waitTime := thread.state.waitTime()
  191. if stoppedThreadCount > maxTerminationCount || waitTime == 0 {
  192. continue
  193. }
  194. // convert threads to inactive if they have been idle for too long
  195. if thread.state.is(stateReady) && waitTime > maxThreadIdleTime.Milliseconds() {
  196. logger.Debug("auto-converting thread to inactive", zap.Int("threadIndex", thread.threadIndex))
  197. convertToInactiveThread(thread)
  198. stoppedThreadCount++
  199. continue
  200. }
  201. // TODO: Completely stopping threads is more memory efficient
  202. // Some PECL extensions like #1296 will prevent threads from fully stopping (they leak memory)
  203. // Reactivate this if there is a better solution or workaround
  204. //if thread.state.is(stateInactive) && waitTime > maxThreadIdleTime.Milliseconds() {
  205. // logger.Debug("auto-stopping thread", zap.Int("threadIndex", thread.threadIndex))
  206. // thread.shutdown()
  207. // stoppedThreadCount++
  208. // autoScaledThreads = append(autoScaledThreads[:i], autoScaledThreads[i+1:]...)
  209. // continue
  210. //}
  211. }
  212. }