6
0

PipelineCache.py 6.7 KB

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