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