You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

data_manager.py 34 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013
  1. # Copyright 2019 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """
  16. Management of all events data.
  17. This module exists to all loaders.
  18. It can read events data through the DataLoader.
  19. This module also acts as a thread pool manager.
  20. """
  21. import abc
  22. import datetime
  23. import threading
  24. import time
  25. import os
  26. from typing import Iterable, Optional
  27. from mindinsight.datavisual.data_transform.summary_watcher import SummaryWatcher
  28. from mindinsight.conf import settings
  29. from mindinsight.datavisual.common import exceptions
  30. from mindinsight.datavisual.common.enums import CacheStatus
  31. from mindinsight.datavisual.common.log import logger
  32. from mindinsight.datavisual.common.enums import DataManagerStatus
  33. from mindinsight.datavisual.common.enums import PluginNameEnum
  34. from mindinsight.datavisual.common.exceptions import TrainJobNotExistError
  35. from mindinsight.datavisual.data_transform.loader_generators.loader_generator import MAX_DATA_LOADER_SIZE
  36. from mindinsight.datavisual.data_transform.loader_generators.data_loader_generator import DataLoaderGenerator
  37. from mindinsight.utils.computing_resource_mgr import ComputingResourceManager
  38. from mindinsight.utils.exceptions import MindInsightException
  39. from mindinsight.utils.exceptions import ParamValueError
  40. from mindinsight.utils.exceptions import UnknownError
  41. from mindinsight.datavisual.utils.tools import exception_wrapper
  42. class _BasicTrainJob:
  43. """
  44. Basic info about train job.
  45. Args:
  46. train_id (str): Id of the train job.
  47. abs_summary_base_dir (str): The canonical path of summary base directory. It should be the return value of
  48. realpath().
  49. abs_summary_dir (str): The canonical path of summary directory. It should be the return value of realpath().
  50. create_time (DateTime): The create time of summary directory.
  51. update_time (DateTime): The latest modify time of summary files directly in the summary directory.
  52. profiler_dir (str): The relative path of profiler directory.
  53. profiler_type (str): The profiler device type.
  54. """
  55. def __init__(self, train_id, abs_summary_base_dir, abs_summary_dir, create_time, update_time, profiler_dir,
  56. profiler_type=""):
  57. self._train_id = train_id
  58. self._abs_summary_base_dir = abs_summary_base_dir
  59. self._abs_summary_dir = abs_summary_dir
  60. self._create_time = create_time
  61. self._update_time = update_time
  62. self._profiler_dir = profiler_dir
  63. self._profiler_type = profiler_type
  64. @property
  65. def abs_summary_dir(self):
  66. """Get summary directory path."""
  67. return self._abs_summary_dir
  68. @property
  69. def summary_base_dir(self):
  70. """Get summary base directory path."""
  71. return self._abs_summary_base_dir
  72. @property
  73. def train_id(self):
  74. """Get train id."""
  75. return self._train_id
  76. @property
  77. def profiler_dir(self):
  78. """Get profiler directory path."""
  79. return self._profiler_dir
  80. @property
  81. def create_time(self):
  82. """Get create time."""
  83. return self._create_time
  84. @property
  85. def update_time(self):
  86. """Get update time."""
  87. return self._update_time
  88. @property
  89. def profiler_type(self):
  90. """Get profiler type"""
  91. return self._profiler_type
  92. class CachedTrainJob:
  93. """
  94. Cache item for BriefCacheManager.
  95. DetailCacheManager will also wrap it's return value with this class.
  96. Args:
  97. basic_info (_BasicTrainJob): Basic info about the train job.
  98. """
  99. def __init__(self, basic_info: _BasicTrainJob):
  100. self._basic_info = basic_info
  101. self._last_access_time = datetime.datetime.utcnow()
  102. # Other cached content is stored here.
  103. self._content = {}
  104. self._cache_status = CacheStatus.NOT_IN_CACHE
  105. self._key_locks = {}
  106. @property
  107. def cache_status(self):
  108. """Get cache status."""
  109. return self._cache_status
  110. @cache_status.setter
  111. def cache_status(self, value):
  112. """Set cache status."""
  113. self._cache_status = value
  114. def update_access_time(self):
  115. """Update last access time of this cache item."""
  116. self._last_access_time = datetime.datetime.utcnow()
  117. @property
  118. def last_access_time(self):
  119. """Get last access time for purposes such as LRU."""
  120. return self._last_access_time
  121. @property
  122. def abs_summary_dir(self):
  123. """Get summary directory path."""
  124. return self._basic_info.abs_summary_dir
  125. @property
  126. def summary_base_dir(self):
  127. """Get summary base directory path."""
  128. return self._basic_info.summary_base_dir
  129. def set(self, key, value):
  130. """Set value to cache."""
  131. self._content[key] = value
  132. def delete(self, key, raise_exception=True):
  133. """Delete key in cache."""
  134. try:
  135. self._content.pop(key)
  136. except KeyError:
  137. if raise_exception:
  138. raise ParamValueError("Delete failed. Invalid cache key({}).".format(key))
  139. def get(self, key, raise_exception=True):
  140. """
  141. Get value from cache.
  142. Args:
  143. key (str): Key of content.
  144. raise_exception (bool): If the key does not exist and
  145. raise_exception is True, it will raise an Exception.
  146. Returns:
  147. Union[Object, None], Return value if key in content,
  148. return False else if raise_exception is False.
  149. Raises:
  150. ParamValueError, if the key does not exist and raise_exception is True.
  151. """
  152. try:
  153. return self._content[key]
  154. except KeyError:
  155. if raise_exception:
  156. raise ParamValueError("Invalid cache key({}).".format(key))
  157. return None
  158. @property
  159. def basic_info(self):
  160. """Get basic train job info."""
  161. return self._basic_info
  162. @basic_info.setter
  163. def basic_info(self, value):
  164. """Set basic train job info."""
  165. self._basic_info = value
  166. def lock_key(self, key):
  167. """Threading lock with given key."""
  168. return self._key_locks.setdefault(key, threading.Lock())
  169. class TrainJob:
  170. """
  171. Train job object.
  172. You must not create TrainJob objects manually. You should always get TrainJob objects from DataManager.
  173. Args:
  174. brief_train_job (CachedTrainJob): Brief info about train job.
  175. detail_train_job (Optional[CachedTrainJob]): Detailed info about train job. Default: None.
  176. """
  177. def __init__(self,
  178. brief_train_job: CachedTrainJob,
  179. detail_train_job: Optional[CachedTrainJob] = None):
  180. self._brief = brief_train_job
  181. self._detail = detail_train_job
  182. if self._detail is None:
  183. self._cache_status = CacheStatus.NOT_IN_CACHE
  184. else:
  185. self._cache_status = self._detail.cache_status
  186. def has_detail(self):
  187. """Whether this train job has detailed info in cache."""
  188. return bool(self._detail is not None)
  189. def get_detail(self, key):
  190. """
  191. Get detail content.
  192. Args:
  193. key (Any): Cache key.
  194. Returns:
  195. Any, cache content.
  196. Raises:
  197. TrainJobDetailNotInCacheError: when this train job has no detail cache.
  198. """
  199. if not self.has_detail():
  200. raise exceptions.TrainJobDetailNotInCacheError()
  201. return self._detail.get(key)
  202. def get_brief(self, key):
  203. """
  204. Get brief content.
  205. Args:
  206. key (Any): Cache key.
  207. Returns:
  208. Any, cache content.
  209. """
  210. return self._brief.get(key)
  211. def get_basic_info(self):
  212. """
  213. Get basic info.
  214. Returns:
  215. basic_info (_BasicTrainJob): Basic info about the train job.
  216. """
  217. return self._brief.basic_info
  218. @property
  219. def cache_status(self):
  220. """Get cache status."""
  221. return self._cache_status
  222. @cache_status.setter
  223. def cache_status(self, cache_status):
  224. """Set cache status."""
  225. self._cache_status = cache_status
  226. class BaseCacheItemUpdater(abc.ABC):
  227. """Abstract base class for other modules to update cache content."""
  228. def update_item(self, cache_item: CachedTrainJob):
  229. """
  230. Update cache item in place.
  231. Args:
  232. cache_item (CachedTrainJob): The cache item to be processed.
  233. """
  234. raise NotImplementedError()
  235. class _BaseCacheManager:
  236. """Base class for cache manager."""
  237. def __init__(self, summary_base_dir):
  238. self._summary_base_dir = summary_base_dir
  239. # Use dict to remove duplicate updaters.
  240. self._updaters = {}
  241. # key is train_id
  242. self._lock = threading.Lock()
  243. self._cache_items = {}
  244. def size(self):
  245. """Gets used cache slots."""
  246. return len(self._cache_items)
  247. def register_cache_item_updater(self, updater: BaseCacheItemUpdater):
  248. """Register cache item updater."""
  249. self._updaters[updater.__class__.__qualname__] = updater
  250. def get_train_jobs(self):
  251. """Get cached train jobs."""
  252. copied_train_jobs = dict(self._cache_items)
  253. return copied_train_jobs
  254. def get_train_job(self, train_id):
  255. """Get cached train job."""
  256. try:
  257. return self._cache_items[train_id]
  258. except KeyError:
  259. raise TrainJobNotExistError(train_id)
  260. def cache_train_job(self, train_id) -> bool:
  261. """
  262. Cache given train job and update train job's last access time.
  263. This method should return true if reload actions should be taken to cache the train job.
  264. Args:
  265. train_id (str): Train Id.
  266. """
  267. raise NotImplementedError()
  268. def delete_train_job(self, train_id):
  269. """Delete train job from cache."""
  270. if train_id in self._cache_items:
  271. del self._cache_items[train_id]
  272. def has_content(self):
  273. """Whether this cache manager has train jobs."""
  274. return bool(self._cache_items)
  275. def update_cache(self, executor):
  276. """
  277. Update cache according to given train jobs on disk.
  278. Different cache manager should implement different cache update policies in this method.
  279. Args:
  280. executor (Executor): The Executor instance.
  281. """
  282. raise NotImplementedError()
  283. class _BriefCacheManager(_BaseCacheManager):
  284. """A cache manager that holds all disk train jobs on disk."""
  285. def cache_train_job(self, train_id):
  286. """
  287. Cache given train job.
  288. All disk train jobs are cached on every reload, so this method always return false.
  289. Args:
  290. train_id (str): Train Id.
  291. """
  292. if train_id in self._cache_items:
  293. self._cache_items[train_id].update_access_time()
  294. return False
  295. def update_cache(self, executor):
  296. """Update cache."""
  297. logger.info('Start to update BriefCacheManager.')
  298. summaries_info = SummaryWatcher().list_summary_directories(self._summary_base_dir)
  299. basic_train_jobs = []
  300. for info in summaries_info:
  301. profiler = info['profiler']
  302. basic_train_jobs.append(_BasicTrainJob(
  303. train_id=info['relative_path'],
  304. abs_summary_base_dir=self._summary_base_dir,
  305. abs_summary_dir=os.path.realpath(os.path.join(
  306. self._summary_base_dir,
  307. info['relative_path']
  308. )),
  309. create_time=info['create_time'],
  310. update_time=info['update_time'],
  311. profiler_dir=None if profiler is None else profiler['directory'],
  312. profiler_type="" if profiler is None else profiler['profiler_type'],
  313. ))
  314. with self._lock:
  315. new_cache_items = self._merge_with_disk(basic_train_jobs)
  316. self._cache_items = new_cache_items
  317. for updater in self._updaters.values():
  318. for cache_item in self._cache_items.values():
  319. updater.update_item(cache_item)
  320. def _merge_with_disk(self, disk_train_jobs: Iterable[_BasicTrainJob]):
  321. """
  322. Merge train jobs in cache with train jobs from disk
  323. This method will remove train jobs not on disk. Call this function with lock for thread safety.
  324. Args:
  325. disk_train_jobs (Iterable[_BasicTrainJob]): Basic train jobs info from disk.
  326. Returns:
  327. dict, a dict containing train jobs to be cached.
  328. """
  329. new_cache_items = {}
  330. for train_job in disk_train_jobs:
  331. if train_job.train_id not in self._cache_items:
  332. new_cache_items[train_job.train_id] = CachedTrainJob(train_job)
  333. else:
  334. reused_train_job = self._cache_items[train_job.train_id]
  335. reused_train_job.basic_info = train_job
  336. new_cache_items[train_job.train_id] = reused_train_job
  337. return new_cache_items
  338. @property
  339. def cache_items(self):
  340. """Get cache items."""
  341. return self._cache_items
  342. # Key for plugin tags.
  343. DATAVISUAL_PLUGIN_KEY = "tag_mapping"
  344. # Detail train job cache key for datavisual content.
  345. DATAVISUAL_CACHE_KEY = "datavisual"
  346. class _DetailCacheManager(_BaseCacheManager):
  347. """A cache manager that holds detailed info for most recently used train jobs."""
  348. def __init__(self, summary_base_dir):
  349. super().__init__(summary_base_dir)
  350. self._loader_pool = {}
  351. self._deleted_id_list = []
  352. self._loader_pool_mutex = threading.Lock()
  353. self._loader_generators = [DataLoaderGenerator(summary_base_dir)]
  354. self._loading_mutex = threading.Lock()
  355. def has_content(self):
  356. """Whether this cache manager has train jobs."""
  357. return bool(self._loader_pool)
  358. def size(self):
  359. """
  360. Get the number of items in this cache manager.
  361. To be implemented.
  362. Returns:
  363. int, the number of items in this cache manager.
  364. """
  365. raise NotImplementedError()
  366. def loader_pool_size(self):
  367. """Get loader pool size."""
  368. return len(self._loader_pool)
  369. def update_cache(self, executor):
  370. """
  371. Update cache.
  372. Will switch to using disk_train_jobs in the future.
  373. Args:
  374. executor (Executor): The Executor instance.
  375. """
  376. with self._loading_mutex:
  377. load_in_cache = exception_wrapper(self._execute_load_data)
  378. try:
  379. while not load_in_cache(executor):
  380. yield
  381. except UnknownError as ex:
  382. logger.warning("Load event data failed. Detail: %s.", str(ex))
  383. def cache_train_job(self, train_id):
  384. """Cache given train job."""
  385. loader = None
  386. need_reload = False
  387. with self._loader_pool_mutex:
  388. if self._is_loader_in_loader_pool(train_id, self._loader_pool):
  389. loader = self._loader_pool.get(train_id)
  390. if loader is None:
  391. for generator in self._loader_generators:
  392. tmp_loader = generator.generate_loader_by_train_id(train_id)
  393. if loader and loader.latest_update_time > tmp_loader.latest_update_time:
  394. continue
  395. loader = tmp_loader
  396. if loader is None:
  397. raise TrainJobNotExistError(train_id)
  398. self._add_loader(loader)
  399. need_reload = True
  400. self._update_loader_latest_update_time(loader.loader_id)
  401. return need_reload
  402. def get_train_jobs(self):
  403. """
  404. Get train jobs
  405. To be implemented.
  406. """
  407. def _add_loader(self, loader):
  408. """
  409. Add a loader to load data.
  410. Args:
  411. loader (LoaderStruct): A object of `Loader`.
  412. """
  413. if len(self._loader_pool) >= MAX_DATA_LOADER_SIZE:
  414. delete_number = len(self._loader_pool) - MAX_DATA_LOADER_SIZE + 1
  415. sorted_loaders = sorted(self._loader_pool.items(),
  416. key=lambda loader: loader[1].latest_update_time)
  417. for index in range(delete_number):
  418. delete_loader_id = sorted_loaders[index][0]
  419. self._delete_loader(delete_loader_id)
  420. self._loader_pool.update({loader.loader_id: loader})
  421. def _delete_loader(self, loader_id):
  422. """
  423. Delete loader from loader pool by loader id.
  424. Args:
  425. loader_id (str): ID of loader.
  426. """
  427. if self._loader_pool.get(loader_id) is not None:
  428. logger.debug("delete loader %s", loader_id)
  429. self._loader_pool.pop(loader_id)
  430. def _execute_loader(self, loader_id, executor):
  431. """
  432. Load data form data_loader.
  433. If there is something wrong by loading, add logs and delete the loader.
  434. Args:
  435. loader_id (str): An ID for `Loader`.
  436. executor (Executor): The Executor instance.
  437. Returns:
  438. bool, True if the loader is finished loading.
  439. """
  440. try:
  441. with self._loader_pool_mutex:
  442. loader = self._loader_pool.get(loader_id, None)
  443. if loader is None:
  444. logger.debug("Loader %r has been deleted, will not load data.", loader_id)
  445. return True
  446. loader.cache_status = CacheStatus.CACHING
  447. if loader.data_loader.load(executor):
  448. # Update loader cache status to CACHED.
  449. # Loader with cache status CACHED should remain the same cache status.
  450. loader.cache_status = CacheStatus.CACHED
  451. return True
  452. return False
  453. except MindInsightException as ex:
  454. logger.warning("Data loader %r load data failed. "
  455. "Delete data_loader. Detail: %s", loader_id, ex)
  456. with self._loader_pool_mutex:
  457. self._delete_loader(loader_id)
  458. return True
  459. def _generate_loaders(self):
  460. """This function generates the loader from given path."""
  461. loader_dict = {}
  462. for generator in self._loader_generators:
  463. loader_dict.update(generator.generate_loaders(self._loader_pool))
  464. sorted_loaders = sorted(loader_dict.items(), key=lambda loader: loader[1].latest_update_time)
  465. latest_loaders = sorted_loaders[-MAX_DATA_LOADER_SIZE:]
  466. self._deal_loaders(latest_loaders)
  467. def _deal_loaders(self, latest_loaders):
  468. """
  469. This function determines which loaders to keep or remove or added.
  470. It is based on the given dict of loaders.
  471. Args:
  472. latest_loaders (list[dict]): A list of <loader_id: LoaderStruct>.
  473. """
  474. with self._loader_pool_mutex:
  475. for loader_id, loader in latest_loaders:
  476. if self._loader_pool.get(loader_id, None) is None:
  477. self._add_loader(loader)
  478. continue
  479. # If this loader was updated manually before,
  480. # its latest_update_time may bigger than update_time in summary.
  481. if self._loader_pool[loader_id].latest_update_time < loader.latest_update_time:
  482. self._update_loader_latest_update_time(loader_id, loader.latest_update_time)
  483. def _execute_load_data(self, executor):
  484. """Load data through multiple threads."""
  485. self._generate_loaders()
  486. loader_pool = self._get_snapshot_loader_pool()
  487. loaded = True
  488. for loader_id in loader_pool:
  489. loaded = self._execute_loader(loader_id, executor) and loaded
  490. return loaded
  491. def delete_train_job(self, train_id):
  492. """
  493. Delete train job with a train id.
  494. Args:
  495. train_id (str): ID for train job.
  496. """
  497. with self._loader_pool_mutex:
  498. self._delete_loader(train_id)
  499. def list_tensors(self, train_id, tag):
  500. """
  501. List tensors of the given train job and tag.
  502. If the tensor can not find by the given tag, will raise exception.
  503. Args:
  504. train_id (str): ID for train job.
  505. tag (str): The tag name.
  506. Returns:
  507. list, the NameTuple format is `collections.namedtuple('_Tensor', ['wall_time', 'event_step', 'value'])`.
  508. the value will contain the given tag data.
  509. """
  510. loader_pool = self._get_snapshot_loader_pool()
  511. if not self._is_loader_in_loader_pool(train_id, loader_pool):
  512. raise TrainJobNotExistError("Can not find the given train job in cache.")
  513. data_loader = loader_pool[train_id].data_loader
  514. tensors = []
  515. try:
  516. events_data = data_loader.get_events_data()
  517. tensors = events_data.tensors(tag)
  518. except KeyError:
  519. error_msg = "Can not find any data in this train job by given tag."
  520. raise ParamValueError(error_msg)
  521. except AttributeError:
  522. logger.debug("Train job %r has been deleted or it has not loaded data, "
  523. "and set tags to empty list.", train_id)
  524. return tensors
  525. def _check_train_job_exist(self, train_id, loader_pool):
  526. """
  527. Check train job exist, if not exist, will raise exception.
  528. Args:
  529. train_id (str): The given train job id.
  530. loader_pool (dict[str, LoaderStruct]): Refer to self._loader_pool.
  531. Raises:
  532. TrainJobNotExistError: Can not find train job in data manager.
  533. """
  534. is_exist = False
  535. if train_id in loader_pool:
  536. return
  537. for generator in self._loader_generators:
  538. if generator.check_train_job_exist(train_id):
  539. is_exist = True
  540. break
  541. if not is_exist:
  542. raise TrainJobNotExistError("Can not find the train job in data manager.")
  543. def _is_loader_in_loader_pool(self, train_id, loader_pool):
  544. """
  545. Check train job exist, if not exist, return False. Else, return True.
  546. Args:
  547. train_id (str): The given train job id.
  548. loader_pool (dict): See self._loader_pool.
  549. Returns:
  550. bool, if loader in loader pool, return True.
  551. """
  552. if train_id in loader_pool:
  553. return True
  554. return False
  555. def _get_snapshot_loader_pool(self):
  556. """
  557. Create a snapshot of data loader pool to avoid concurrent mutation and iteration issues.
  558. Returns:
  559. dict, a copy of `self._loader_pool`.
  560. """
  561. with self._loader_pool_mutex:
  562. return dict(self._loader_pool)
  563. def get_train_job(self, train_id):
  564. """
  565. Get train job by train ID.
  566. This method overrides parent method.
  567. Args:
  568. train_id (str): Train ID for train job.
  569. Returns:
  570. dict, single train job, if can not find any data, will return None.
  571. """
  572. self._check_train_job_exist(train_id, self._loader_pool)
  573. loader = self._get_loader(train_id)
  574. if loader is None:
  575. logger.info("No valid summary log in train job %s, or it is not in the cache.", train_id)
  576. return None
  577. train_job = loader.to_dict()
  578. train_job.pop('data_loader')
  579. plugin_data = {}
  580. for plugin_name in PluginNameEnum.list_members():
  581. job = self.get_train_job_by_plugin(train_id, plugin_name=plugin_name)
  582. if job is None:
  583. plugin_data[plugin_name] = []
  584. else:
  585. plugin_data[plugin_name] = job['tags']
  586. train_job.update({DATAVISUAL_PLUGIN_KEY: plugin_data})
  587. # Will fill basic_info value in future.
  588. train_job_obj = CachedTrainJob(basic_info=None)
  589. train_job_obj.set(DATAVISUAL_CACHE_KEY, train_job)
  590. train_job_obj.cache_status = loader.cache_status
  591. return train_job_obj
  592. def _get_loader(self, train_id):
  593. """
  594. Get loader by train id.
  595. Args:
  596. train_id (str): Train Id.
  597. Returns:
  598. LoaderStruct, the loader.
  599. """
  600. loader = None
  601. with self._loader_pool_mutex:
  602. if self._is_loader_in_loader_pool(train_id, self._loader_pool):
  603. loader = self._loader_pool.get(train_id)
  604. return loader
  605. def _update_loader_latest_update_time(self, loader_id, latest_update_time=None):
  606. """
  607. Update loader with latest_update_time.
  608. Args:
  609. loader_id (str): ID of loader.
  610. latest_update_time (float): Timestamp.
  611. """
  612. if latest_update_time is None:
  613. latest_update_time = time.time()
  614. self._loader_pool[loader_id].latest_update_time = latest_update_time
  615. def get_train_job_by_plugin(self, train_id, plugin_name):
  616. """
  617. Get a train job by train job id.
  618. If the given train job does not has the given plugin data, the tag list will be empty.
  619. Args:
  620. train_id (str): Get train job info by the given id.
  621. plugin_name (str): Get tags by given plugin.
  622. Returns:
  623. TypedDict('TrainJobEntity', {'id': str, 'name': str, 'tags': List[str]}),
  624. a train job object.
  625. """
  626. self._check_train_job_exist(train_id, self._loader_pool)
  627. loader = self._get_loader(train_id)
  628. if loader is None:
  629. logger.warning("No valid summary log in train job %s, "
  630. "or it is not in the cache.", train_id)
  631. return None
  632. name = loader.name
  633. data_loader = loader.data_loader
  634. tags = []
  635. try:
  636. events_data = data_loader.get_events_data()
  637. tags = events_data.list_tags_by_plugin(plugin_name)
  638. except KeyError:
  639. logger.debug("Plugin name %r does not exist "
  640. "in train job %r, and set tags to empty list.", plugin_name, name)
  641. except AttributeError:
  642. logger.debug("Train job %r has been deleted or it has not loaded data, "
  643. "and set tags to empty list.", name)
  644. result = dict(id=train_id, name=name, tags=tags)
  645. return result
  646. class DataManager:
  647. """
  648. DataManager manages a pool of loader which help access events data.
  649. Each loader helps deal the data of the events.
  650. A loader corresponds to an events_data.
  651. The DataManager build a pool including all the data_loader.
  652. The data_loader provides extracting
  653. method to get the information of events.
  654. """
  655. def __init__(self, summary_base_dir):
  656. """
  657. Initialize the pool of loader and the dict of name-to-path.
  658. Args:
  659. summary_base_dir (str): Base summary directory.
  660. self._status: Refer `datavisual.common.enums.DataManagerStatus`.
  661. """
  662. self._summary_base_dir = os.path.realpath(summary_base_dir)
  663. self._status = DataManagerStatus.INIT.value
  664. self._status_mutex = threading.Lock()
  665. self._detail_cache = _DetailCacheManager(self._summary_base_dir)
  666. self._brief_cache = _BriefCacheManager(self._summary_base_dir)
  667. # This lock is used to make sure that only one self._load_data_in_thread() is running.
  668. # Because self._load_data_in_thread() will create process pool when loading files, we can not
  669. # afford to run multiple self._load_data_in_thread() simultaneously (will create too many processes).
  670. self._load_data_lock = threading.Lock()
  671. @property
  672. def summary_base_dir(self):
  673. """Get summary base dir."""
  674. return self._summary_base_dir
  675. def start_load_data(self, auto_reload=False):
  676. """
  677. Start threads for loading data.
  678. Returns:
  679. Thread, the background Thread instance.
  680. """
  681. logger.info("Start to load data")
  682. thread = threading.Thread(target=self._load_data_in_thread_wrapper,
  683. name='start_load_data_thread',
  684. args=(auto_reload,),
  685. daemon=True)
  686. thread.daemon = True
  687. thread.start()
  688. return thread
  689. def _load_data_in_thread_wrapper(self, auto_reload):
  690. """Wrapper for load data in thread."""
  691. if self._load_data_lock.locked():
  692. return
  693. try:
  694. with self._load_data_lock:
  695. while True:
  696. exception_wrapper(self._load_data)()
  697. if not auto_reload:
  698. break
  699. except UnknownError as exc:
  700. # Not raising the exception here to ensure that data reloading does not crash.
  701. logger.warning(exc.message)
  702. def _load_data(self):
  703. """This function will load data once and ignore it if the status is loading."""
  704. with self._status_mutex:
  705. if self.status == DataManagerStatus.LOADING.value:
  706. logger.debug("Current status is %s , will ignore to load data.", self.status)
  707. return
  708. self.status = DataManagerStatus.LOADING.value
  709. with ComputingResourceManager(executors_cnt=1,
  710. max_processes_cnt=settings.MAX_PROCESSES_COUNT) as computing_resource_mgr:
  711. with computing_resource_mgr.get_executor() as executor:
  712. self._brief_cache.update_cache(executor)
  713. for _ in self._detail_cache.update_cache(executor):
  714. self._brief_cache.update_cache(executor)
  715. executor.wait_all_tasks_finish()
  716. with self._status_mutex:
  717. if not self._brief_cache.has_content() and not self._detail_cache.has_content():
  718. self.status = DataManagerStatus.INVALID.value
  719. else:
  720. self.status = DataManagerStatus.DONE.value
  721. logger.info("Load brief data end, and loader pool size is %r.", self._detail_cache.loader_pool_size())
  722. def get_train_job_by_plugin(self, train_id, plugin_name):
  723. """
  724. Get a train job by train job id.
  725. If the given train job does not has the given plugin data, the tag list will be empty.
  726. Args:
  727. train_id (str): Get train job info by the given id.
  728. plugin_name (str): Get tags by given plugin.
  729. Returns:
  730. TypedDict('TrainJobEntity', {'id': str, 'name': str, 'tags': List[str]}),
  731. a train job object.
  732. """
  733. self._check_status_valid()
  734. return self._detail_cache.get_train_job_by_plugin(train_id, plugin_name)
  735. def delete_train_job(self, train_id, only_delete_from_cache=True):
  736. """
  737. Delete train job with a train id.
  738. Args:
  739. train_id (str): ID for train job.
  740. """
  741. if not only_delete_from_cache:
  742. raise NotImplementedError("Delete from both cache and disk is not supported.")
  743. self._brief_cache.delete_train_job(train_id)
  744. self._detail_cache.delete_train_job(train_id)
  745. def list_tensors(self, train_id, tag):
  746. """
  747. List tensors of the given train job and tag.
  748. If the tensor can not find by the given tag, will raise exception.
  749. Args:
  750. train_id (str): ID for train job.
  751. tag (str): The tag name.
  752. Returns:
  753. NamedTuple, the tuple format is `collections.namedtuple('_Tensor', ['wall_time', 'event_step', 'value'])`.
  754. the value will contain the given tag data.
  755. """
  756. self._check_status_valid()
  757. return self._detail_cache.list_tensors(train_id, tag)
  758. def _check_status_valid(self):
  759. """Check if the status is valid to load data."""
  760. if self.status == DataManagerStatus.INIT.value:
  761. raise exceptions.SummaryLogIsLoading("Data is being loaded, current status: %s." % self._status)
  762. def get_train_job(self, train_id):
  763. """
  764. Get train job by train ID.
  765. Args:
  766. train_id (str): Train ID for train job.
  767. Returns:
  768. dict, single train job, if can not find any data, will return None.
  769. """
  770. self._check_status_valid()
  771. detail_train_job = self._detail_cache.get_train_job(train_id)
  772. brief_train_job = self._brief_cache.get_train_job(train_id)
  773. return TrainJob(brief_train_job, detail_train_job)
  774. @property
  775. def status(self):
  776. """
  777. Get the status of data manager.
  778. Returns:
  779. DataManagerStatus, the status of data manager.
  780. """
  781. return self._status
  782. @status.setter
  783. def status(self, status):
  784. """Set data manger status."""
  785. self._status = status
  786. def cache_train_job(self, train_id):
  787. """Cache given train job (async)."""
  788. brief_need_reload = self._brief_cache.cache_train_job(train_id)
  789. detail_need_reload = self._detail_cache.cache_train_job(train_id)
  790. if brief_need_reload or detail_need_reload:
  791. self.start_load_data()
  792. def register_brief_cache_item_updater(self, updater: BaseCacheItemUpdater):
  793. """Register brief cache item updater for brief cache manager."""
  794. self._brief_cache.register_cache_item_updater(updater)
  795. def get_brief_cache(self):
  796. """Get brief cache."""
  797. return self._brief_cache
  798. def get_brief_train_job(self, train_id):
  799. """Get brief train job."""
  800. return self._brief_cache.get_train_job(train_id)
  801. DATA_MANAGER = DataManager(settings.SUMMARY_BASE_DIR)