PipelineCache.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. import eventlet
  2. import datetime as dt
  3. from queue import Queue
  4. from threading import Lock
  5. from time import sleep
  6. # from time import time
  7. from collections import namedtuple
  8. from dataclasses import dataclass
  9. from eventlet import spawn_n
  10. from eventlet import tpool
  11. from pycs import app
  12. from pycs.database.Project import Project
  13. from pycs.interfaces.Pipeline import Pipeline
  14. from pycs.jobs.JobRunner import JobRunner
  15. from pycs.util.PipelineUtil import load_from_root_folder
  16. from pycs.util.green_worker import GreenWorker
  17. @dataclass
  18. class PipelineEntry(object):
  19. last_used: int = -1
  20. pipeline: Pipeline = None
  21. pipeline_name: str = None
  22. project_id: int = -1
  23. def __post_init__(self):
  24. if self.pipeline is not None:
  25. self.pipeline_name = self.pipeline.__class__.__name__
  26. self.poke()
  27. def poke(self):
  28. self.last_used = dt.datetime.now()
  29. def __str__(self):
  30. return f"<Pipeline '{self.pipeline_name}' for project #{self.project_id} (last_used: {self.last_used})>"
  31. class PipelineCache(GreenWorker):
  32. CLOSE_TIMER = dt.timedelta(seconds=120)
  33. def __init__(self, jobs: JobRunner):
  34. super().__init__()
  35. self.__jobs = jobs
  36. self.__pipelines: dict[PipelineEntry] = {}
  37. self.__lock = Lock()
  38. def load_from_root_folder(self, project: Project, root_folder: str, no_cache: bool = False) -> Pipeline:
  39. """
  40. load configuration.json and create an instance from the included code object
  41. :param projeventletect: associated project
  42. :param root_folder: path to model root folder
  43. :return: Pipeline instance
  44. """
  45. # check if instance is cached
  46. with self.__lock:
  47. if root_folder in self.__pipelines:
  48. entry: PipelineEntry = self.__pipelines[root_folder]
  49. entry.poke()
  50. self.info(f"Using {entry}")
  51. return entry.pipeline
  52. # load pipeline
  53. pipeline = load_from_root_folder(root_folder)
  54. if no_cache:
  55. return pipeline
  56. # save instance to cache
  57. with self.__lock:
  58. entry = PipelineEntry(pipeline=pipeline, project_id=project.id)
  59. self.info(f"Cached {entry}")
  60. self.__pipelines[root_folder] = entry
  61. self.queue.put((root_folder,))
  62. # return
  63. return pipeline
  64. def free_instance(self, root_folder: str):
  65. """
  66. Change an instance's status to unused and start the timer to call it's `close` function
  67. after `CLOSE_TIMER` seconds. The next call to `load_from_root_folder` in this interval
  68. will disable this timer.
  69. :param root_folder: path to model root folder
  70. """
  71. with self.__lock:
  72. if root_folder in self.__pipelines:
  73. # reset "last used" to now
  74. self.__pipelines[root_folder].poke()
  75. # abort if no pipeline with this root folder is loaded
  76. else:
  77. return
  78. # executed as coroutine in the main thread
  79. def __run__(self):
  80. while True:
  81. # get pipeline
  82. res = tpool.execute(self.work)
  83. if res is self.STOP_QUEUE:
  84. break
  85. pipeline, project_id = res
  86. if pipeline is None:
  87. # pipeline vanished from cache
  88. continue
  89. project = Project.query.get(project_id)
  90. # create job to close pipeline
  91. self.__jobs.run(project,
  92. 'Model Interaction',
  93. f'{project.name} (close pipeline)',
  94. f'{project.name}/model-interaction',
  95. pipeline.close
  96. )
  97. self._finish()
  98. # executed in a separate thread
  99. def work(self):
  100. while True:
  101. res = self.check_queue()
  102. if res is self.STOP_QUEUE:
  103. return res
  104. elif res is self.CONTINUE_QUEUE:
  105. continue
  106. # an entry was found in the queue
  107. return self._check_cache_entry(*res)
  108. def _check_cache_entry(self, key):
  109. with self.__lock:
  110. entry = self.__pipelines.get(key)
  111. if entry is None:
  112. self.info(f"Entry for {key} already gone")
  113. return None, None
  114. self.info(f"Starting checks for {entry}...")
  115. while True:
  116. now = dt.datetime.now()
  117. with self.__lock:
  118. entry = self.__pipelines.get(key)
  119. if entry is None:
  120. self.info(f"Entry for {key} already gone")
  121. return None, None
  122. delay = entry.last_used + self.CLOSE_TIMER - now
  123. if delay.seconds > 0:
  124. sleep(delay.seconds)
  125. continue
  126. with self.__lock:
  127. entry = self.__pipelines.pop(key, None)
  128. if entry is None:
  129. self.info(f"Entry for {key} already gone")
  130. return None, None
  131. self.info(f"Removed {entry} from cache")
  132. return entry.pipeline, entry.project_id
  133. # def __get(self):
  134. # while True:
  135. # # get element from queue
  136. # root_folder, timestamp = self.__queue.get()
  137. # # sleep if needed
  138. # delay = int(timestamp + self.CLOSE_TIMER - time())
  139. # if delay > 0:
  140. # eventlet.sleep(delay)
  141. # # lock and access __pipelines
  142. # with self.__lock:
  143. # instance = self.__pipelines[root_folder]
  144. # # reference counter greater than 1
  145. # if instance.counter > 1:
  146. # # decrease reference counter
  147. # instance.counter -= 1
  148. # # reference counter equals 1
  149. # else:
  150. # # delete instance from __pipelines and return to call `close` function
  151. # del self.__pipelines[root_folder]
  152. # return instance.pipeline, instance.project_id
  153. # def __run(self):
  154. # while True:
  155. # # get pipeline
  156. # pipeline, project_id = tpool.execute(self.__get)
  157. # project = Project.query.get(project_id)
  158. # # create job to close pipeline
  159. # self.__jobs.run(project,
  160. # 'Model Interaction',
  161. # f'{project.name} (close pipeline)',
  162. # f'{project.name}/model-interaction',
  163. # pipeline.close
  164. # )