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