scaling.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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. scaleChan chan *FrankenPHPContext
  32. autoScaledThreads = []*phpThread{}
  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. scaleChan = nil
  42. return
  43. }
  44. scalingMu.Lock()
  45. scaleChan = make(chan *FrankenPHPContext)
  46. maxScaledThreads := mainThread.maxThreads - mainThread.numThreads
  47. autoScaledThreads = make([]*phpThread, 0, maxScaledThreads)
  48. scalingMu.Unlock()
  49. go startUpscalingThreads(maxScaledThreads, scaleChan, mainThread.done)
  50. go startDownScalingThreads(mainThread.done)
  51. }
  52. func drainAutoScaling() {
  53. scalingMu.Lock()
  54. logger.Debug("shutting down autoscaling", zap.Int("autoScaledThreads", len(autoScaledThreads)))
  55. scalingMu.Unlock()
  56. }
  57. func addRegularThread() (*phpThread, error) {
  58. thread := getInactivePHPThread()
  59. if thread == nil {
  60. return nil, MaxThreadsReachedError
  61. }
  62. convertToRegularThread(thread)
  63. thread.state.waitFor(stateReady, stateShuttingDown, stateReserved)
  64. return thread, nil
  65. }
  66. func removeRegularThread() error {
  67. regularThreadMu.RLock()
  68. if len(regularThreads) <= 1 {
  69. regularThreadMu.RUnlock()
  70. return CannotRemoveLastThreadError
  71. }
  72. thread := regularThreads[len(regularThreads)-1]
  73. regularThreadMu.RUnlock()
  74. thread.shutdown()
  75. return nil
  76. }
  77. func addWorkerThread(worker *worker) (*phpThread, error) {
  78. thread := getInactivePHPThread()
  79. if thread == nil {
  80. return nil, MaxThreadsReachedError
  81. }
  82. convertToWorkerThread(thread, worker)
  83. thread.state.waitFor(stateReady, stateShuttingDown, stateReserved)
  84. return thread, nil
  85. }
  86. func removeWorkerThread(worker *worker) error {
  87. worker.threadMutex.RLock()
  88. if len(worker.threads) <= 1 {
  89. worker.threadMutex.RUnlock()
  90. return CannotRemoveLastThreadError
  91. }
  92. thread := worker.threads[len(worker.threads)-1]
  93. worker.threadMutex.RUnlock()
  94. thread.shutdown()
  95. return nil
  96. }
  97. // Add a worker PHP threads automatically
  98. func scaleWorkerThread(worker *worker) {
  99. scalingMu.Lock()
  100. defer scalingMu.Unlock()
  101. if !mainThread.state.is(stateReady) {
  102. return
  103. }
  104. // probe CPU usage before scaling
  105. if !cpu.ProbeCPUs(cpuProbeTime, maxCpuUsageForScaling, mainThread.done) {
  106. return
  107. }
  108. thread, err := addWorkerThread(worker)
  109. if err != nil {
  110. logger.Warn("could not increase max_threads, consider raising this limit", zap.String("worker", worker.fileName), zap.Error(err))
  111. return
  112. }
  113. autoScaledThreads = append(autoScaledThreads, thread)
  114. }
  115. // Add a regular PHP thread automatically
  116. func scaleRegularThread() {
  117. scalingMu.Lock()
  118. defer scalingMu.Unlock()
  119. if !mainThread.state.is(stateReady) {
  120. return
  121. }
  122. // probe CPU usage before scaling
  123. if !cpu.ProbeCPUs(cpuProbeTime, maxCpuUsageForScaling, mainThread.done) {
  124. return
  125. }
  126. thread, err := addRegularThread()
  127. if err != nil {
  128. logger.Warn("could not increase max_threads, consider raising this limit", zap.Error(err))
  129. return
  130. }
  131. autoScaledThreads = append(autoScaledThreads, thread)
  132. }
  133. func startUpscalingThreads(maxScaledThreads int, scale chan *FrankenPHPContext, done chan struct{}) {
  134. for {
  135. scalingMu.Lock()
  136. scaledThreadCount := len(autoScaledThreads)
  137. scalingMu.Unlock()
  138. if scaledThreadCount >= maxScaledThreads {
  139. // we have reached max_threads, check again later
  140. select {
  141. case <-done:
  142. return
  143. case <-time.After(downScaleCheckTime):
  144. continue
  145. }
  146. }
  147. select {
  148. case fc := <-scale:
  149. timeSinceStalled := time.Since(fc.startedAt)
  150. // if the request has not been stalled long enough, wait and repeat
  151. if timeSinceStalled < minStallTime {
  152. select {
  153. case <-done:
  154. return
  155. case <-time.After(minStallTime - timeSinceStalled):
  156. continue
  157. }
  158. }
  159. // if the request has been stalled long enough, scale
  160. if worker, ok := workers[fc.scriptFilename]; ok {
  161. scaleWorkerThread(worker)
  162. } else {
  163. scaleRegularThread()
  164. }
  165. case <-done:
  166. return
  167. }
  168. }
  169. }
  170. func startDownScalingThreads(done chan struct{}) {
  171. for {
  172. select {
  173. case <-done:
  174. return
  175. case <-time.After(downScaleCheckTime):
  176. deactivateThreads()
  177. }
  178. }
  179. }
  180. // Check all threads and remove those that have been inactive for too long
  181. func deactivateThreads() {
  182. stoppedThreadCount := 0
  183. scalingMu.Lock()
  184. defer scalingMu.Unlock()
  185. for i := len(autoScaledThreads) - 1; i >= 0; i-- {
  186. thread := autoScaledThreads[i]
  187. // the thread might have been stopped otherwise, remove it
  188. if thread.state.is(stateReserved) {
  189. autoScaledThreads = append(autoScaledThreads[:i], autoScaledThreads[i+1:]...)
  190. continue
  191. }
  192. waitTime := thread.state.waitTime()
  193. if stoppedThreadCount > maxTerminationCount || waitTime == 0 {
  194. continue
  195. }
  196. // convert threads to inactive if they have been idle for too long
  197. if thread.state.is(stateReady) && waitTime > maxThreadIdleTime.Milliseconds() {
  198. logger.Debug("auto-converting thread to inactive", zap.Int("threadIndex", thread.threadIndex))
  199. convertToInactiveThread(thread)
  200. stoppedThreadCount++
  201. autoScaledThreads = append(autoScaledThreads[:i], autoScaledThreads[i+1:]...)
  202. continue
  203. }
  204. // TODO: Completely stopping threads is more memory efficient
  205. // Some PECL extensions like #1296 will prevent threads from fully stopping (they leak memory)
  206. // Reactivate this if there is a better solution or workaround
  207. //if thread.state.is(stateInactive) && waitTime > maxThreadIdleTime.Milliseconds() {
  208. // logger.Debug("auto-stopping thread", zap.Int("threadIndex", thread.threadIndex))
  209. // thread.shutdown()
  210. // stoppedThreadCount++
  211. // autoScaledThreads = append(autoScaledThreads[:i], autoScaledThreads[i+1:]...)
  212. // continue
  213. //}
  214. }
  215. }