6
0

PipelineCache.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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. if project is None:
  91. # project does not exist anymore
  92. continue
  93. # create job to close pipeline
  94. self.__jobs.run(project,
  95. 'Model Interaction',
  96. f'{project.name} (close pipeline)',
  97. f'{project.name}/model-interaction',
  98. pipeline.close
  99. )
  100. self._finish()
  101. # executed in a separate thread
  102. def work(self):
  103. while True:
  104. res = self.check_queue()
  105. if res is self.STOP_QUEUE:
  106. return res
  107. elif res is self.CONTINUE_QUEUE:
  108. continue
  109. # an entry was found in the queue
  110. return self._check_cache_entry(*res)
  111. def _check_cache_entry(self, key):
  112. with self.__lock:
  113. entry = self.__pipelines.get(key)
  114. if entry is None:
  115. self.info(f"Entry for {key} already gone")
  116. return None, None
  117. self.info(f"Starting checks for {entry}...")
  118. while True:
  119. now = dt.datetime.now()
  120. with self.__lock:
  121. entry = self.__pipelines.get(key)
  122. if entry is None:
  123. self.info(f"Entry for {key} already gone")
  124. return None, None
  125. delay = entry.last_used + self.CLOSE_TIMER - now
  126. if delay.seconds > 0:
  127. sleep(delay.seconds)
  128. continue
  129. with self.__lock:
  130. entry = self.__pipelines.pop(key, None)
  131. if entry is None:
  132. self.info(f"Entry for {key} already gone")
  133. return None, None
  134. self.info(f"Removed {entry} from cache")
  135. return entry.pipeline, entry.project_id
  136. # def __get(self):
  137. # while True:
  138. # # get element from queue
  139. # root_folder, timestamp = self.__queue.get()
  140. # # sleep if needed
  141. # delay = int(timestamp + self.CLOSE_TIMER - time())
  142. # if delay > 0:
  143. # eventlet.sleep(delay)
  144. # # lock and access __pipelines
  145. # with self.__lock:
  146. # instance = self.__pipelines[root_folder]
  147. # # reference counter greater than 1
  148. # if instance.counter > 1:
  149. # # decrease reference counter
  150. # instance.counter -= 1
  151. # # reference counter equals 1
  152. # else:
  153. # # delete instance from __pipelines and return to call `close` function
  154. # del self.__pipelines[root_folder]
  155. # return instance.pipeline, instance.project_id
  156. # def __run(self):
  157. # while True:
  158. # # get pipeline
  159. # pipeline, project_id = tpool.execute(self.__get)
  160. # project = Project.query.get(project_id)
  161. # # create job to close pipeline
  162. # self.__jobs.run(project,
  163. # 'Model Interaction',
  164. # f'{project.name} (close pipeline)',
  165. # f'{project.name}/model-interaction',
  166. # pipeline.close
  167. # )