6
0

PipelineCache.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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 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. """
  33. Store initialized pipelines and call `close` after `CLOSE_TIMER` if they are not requested
  34. another time.
  35. """
  36. CLOSE_TIMER = dt.timedelta(seconds=120)
  37. def __init__(self):
  38. super().__init__()
  39. self.__pipelines: dict[PipelineEntry] = {}
  40. self.__lock = Lock()
  41. def load_from_root_folder(self, project: Project, no_cache: bool = False) -> Pipeline:
  42. """
  43. load configuration.json and create an instance from the included code object
  44. :param projeventletect: associated project
  45. :param root_folder: path to model root folder
  46. :return: Pipeline instance
  47. """
  48. root_folder = project.model.root_folder
  49. # check if instance is cached
  50. with self.__lock:
  51. if root_folder in self.__pipelines:
  52. entry: PipelineEntry = self.__pipelines[root_folder]
  53. entry.poke()
  54. self.info(f"Using {entry}")
  55. return entry.pipeline
  56. # load pipeline
  57. pipeline = load_from_root_folder(root_folder)
  58. if no_cache:
  59. return pipeline
  60. # save instance to cache
  61. with self.__lock:
  62. entry = PipelineEntry(pipeline=pipeline, project_id=project.id)
  63. self.info(f"Cached {entry}")
  64. self.__pipelines[root_folder] = entry
  65. self.queue.put((root_folder,))
  66. # return
  67. return pipeline
  68. def free_instance(self, project: Project):
  69. """
  70. Change an instance's status to unused and start the timer to call it's `close` function
  71. after `CLOSE_TIMER` seconds. The next call to `load_from_root_folder` in this interval
  72. will disable this timer.
  73. :param root_folder: path to model root folder
  74. """
  75. root_folder = project.model.root_folder
  76. with self.__lock:
  77. if root_folder in self.__pipelines:
  78. # reset "last used" to now
  79. self.__pipelines[root_folder].poke()
  80. # abort if no pipeline with this root folder is loaded
  81. else:
  82. return
  83. # executed as coroutine in the main thread
  84. def __run__(self):
  85. while True:
  86. # get pipeline
  87. res = tpool.execute(self.work)
  88. if res is self.STOP_QUEUE:
  89. break
  90. pipeline, project_id = res
  91. if pipeline is None:
  92. # pipeline vanished from cache
  93. continue
  94. project = Project.query.get(project_id)
  95. if project is None:
  96. # project does not exist anymore
  97. continue
  98. # create job to close pipeline
  99. JobRunner.Run(project,
  100. 'Model Interaction',
  101. f'{project.name} (close pipeline)',
  102. f'{project.name}/model-interaction',
  103. pipeline.close
  104. )
  105. self._finish()
  106. # executed in a separate thread
  107. def work(self):
  108. while True:
  109. res = self.check_queue()
  110. if res is self.STOP_QUEUE:
  111. return res
  112. elif res is self.CONTINUE_QUEUE:
  113. continue
  114. # an entry was found in the queue
  115. return self._check_cache_entry(*res)
  116. def _check_cache_entry(self, key):
  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. self.info(f"Starting checks for {entry}...")
  123. while True:
  124. now = dt.datetime.now()
  125. with self.__lock:
  126. entry = self.__pipelines.get(key)
  127. if entry is None:
  128. self.info(f"Entry for {key} already gone")
  129. return None, None
  130. delay = entry.last_used + self.CLOSE_TIMER - now
  131. if delay.seconds > 0:
  132. sleep(delay.seconds)
  133. continue
  134. with self.__lock:
  135. entry = self.__pipelines.pop(key, None)
  136. if entry is None:
  137. self.info(f"Entry for {key} already gone")
  138. return None, None
  139. self.info(f"Removed {entry} from cache")
  140. return entry.pipeline, entry.project_id
  141. # def __get(self):
  142. # while True:
  143. # # get element from queue
  144. # root_folder, timestamp = self.__queue.get()
  145. # # sleep if needed
  146. # delay = int(timestamp + self.CLOSE_TIMER - time())
  147. # if delay > 0:
  148. # eventlet.sleep(delay)
  149. # # lock and access __pipelines
  150. # with self.__lock:
  151. # instance = self.__pipelines[root_folder]
  152. # # reference counter greater than 1
  153. # if instance.counter > 1:
  154. # # decrease reference counter
  155. # instance.counter -= 1
  156. # # reference counter equals 1
  157. # else:
  158. # # delete instance from __pipelines and return to call `close` function
  159. # del self.__pipelines[root_folder]
  160. # return instance.pipeline, instance.project_id
  161. # def __run(self):
  162. # while True:
  163. # # get pipeline
  164. # pipeline, project_id = tpool.execute(self.__get)
  165. # project = Project.query.get(project_id)
  166. # # create job to close pipeline
  167. # self.__jobs.run(project,
  168. # 'Model Interaction',
  169. # f'{project.name} (close pipeline)',
  170. # f'{project.name}/model-interaction',
  171. # pipeline.close
  172. # )