scaling.go 6.9 KB

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