scaling.go 6.3 KB

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