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.

summary_watcher.py 22 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. # Copyright 2020 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. """Summary watcher module."""
  16. import json
  17. import os
  18. import re
  19. import datetime
  20. from pathlib import Path
  21. from mindinsight.datavisual.common.log import logger
  22. from mindinsight.datavisual.common.validation import Validation
  23. from mindinsight.datavisual.utils.tools import Counter
  24. from mindinsight.datavisual.utils.utils import contains_null_byte
  25. from mindinsight.datavisual.common.exceptions import MaxCountExceededError
  26. from mindinsight.utils.exceptions import FileSystemPermissionError
  27. LINEAGE_SUMMARY_SUFFIX = '_lineage'
  28. EXPLAIN_SUMMARY_SUFFIX = '_explain'
  29. class SummaryWatcher:
  30. """SummaryWatcher class."""
  31. SUMMARY_FILENAME_REGEX = r'summary\.(?P<timestamp>\d+)'
  32. PB_FILENAME_REGEX = r'\.pb$'
  33. PROFILER_DIRECTORY_REGEX = r'^profiler'
  34. MAX_SUMMARY_DIR_COUNT = 999
  35. # scan at most 20000 files/directories (approximately 1 seconds)
  36. # if overall is False in SummaryWatcher.list_summary_directories
  37. # to avoid long-time blocking
  38. MAX_SCAN_COUNT = 20000
  39. def list_summary_directories(self, summary_base_dir, overall=True, list_explain=False):
  40. """
  41. List summary directories within base directory.
  42. Args:
  43. summary_base_dir (str): Path of summary base directory.
  44. overall (bool): Limit the total num of scanning if overall is False.
  45. list_explain (bool): Indicates whether to list only the mindexplain folder.
  46. Default is False, means not to list mindexplain folder.
  47. Returns:
  48. list, list of summary directory info, each of which including the following attributes.
  49. - relative_path (str): Relative path of summary directory, referring to settings.SUMMARY_BASE_DIR,
  50. starting with "./".
  51. - create_time (datetime): Creation time of summary file.
  52. - update_time (datetime): Modification time of summary file.
  53. - profiler (dict): profiler info, including profiler subdirectory path, profiler creation time and
  54. profiler modification time.
  55. Examples:
  56. >>> from mindinsight.datavisual.data_transform.summary_watcher import SummaryWatcher
  57. >>> summary_watcher = SummaryWatcher()
  58. >>> directories = summary_watcher.list_summary_directories('/summary/base/dir')
  59. """
  60. if contains_null_byte(summary_base_dir=summary_base_dir):
  61. return []
  62. relative_path = os.path.join('.', '')
  63. if not self._is_valid_summary_directory(summary_base_dir, relative_path):
  64. return []
  65. summary_dict = {}
  66. counter = Counter(max_count=None if overall else self.MAX_SCAN_COUNT)
  67. try:
  68. entries = os.scandir(summary_base_dir)
  69. except PermissionError:
  70. logger.error('Path of summary base directory is not accessible.')
  71. raise FileSystemPermissionError('Path of summary base directory is not accessible.')
  72. for entry in entries:
  73. if len(summary_dict) == self.MAX_SUMMARY_DIR_COUNT:
  74. break
  75. try:
  76. counter.add()
  77. except MaxCountExceededError:
  78. logger.info('Stop further scanning due to overall is False and '
  79. 'number of scanned files exceeds upper limit.')
  80. break
  81. if entry.is_symlink():
  82. pass
  83. elif entry.is_file():
  84. self._update_summary_dict(summary_dict, summary_base_dir, relative_path, entry, list_explain)
  85. elif entry.is_dir():
  86. entry_path = os.path.realpath(os.path.join(summary_base_dir, entry.name))
  87. self._scan_subdir_entries(summary_dict, summary_base_dir, entry_path, entry.name, counter, list_explain)
  88. directories = []
  89. for key, value in summary_dict.items():
  90. directory = {
  91. 'relative_path': key,
  92. **value
  93. }
  94. directories.append(directory)
  95. # sort by update time in descending order and relative path in ascending order
  96. directories.sort(key=lambda x: (-int(x['update_time'].timestamp()), x['relative_path']))
  97. return directories
  98. def _scan_subdir_entries(self, summary_dict, summary_base_dir, entry_path, entry_name, counter, list_explain):
  99. """
  100. Scan subdir entries.
  101. Args:
  102. summary_dict (dict): Temporary data structure to hold summary directory info.
  103. summary_base_dir (str): Path of summary base directory.
  104. entry_path(str): Path entry.
  105. entry_name (str): Name of entry.
  106. counter (Counter): An instance of CountLimiter.
  107. list_explain (bool): Indicates whether to list only the mindexplain folder.
  108. """
  109. try:
  110. subdir_entries = os.scandir(entry_path)
  111. except PermissionError:
  112. logger.warning('Path of %s under summary base directory is not accessible.', entry_name)
  113. return
  114. for subdir_entry in subdir_entries:
  115. if len(summary_dict) == self.MAX_SUMMARY_DIR_COUNT:
  116. break
  117. try:
  118. counter.add()
  119. except MaxCountExceededError:
  120. logger.info('Stop further scanning due to overall is False and '
  121. 'number of scanned files exceeds upper limit.')
  122. break
  123. subdir_relative_path = os.path.join('.', entry_name)
  124. if subdir_entry.is_symlink():
  125. pass
  126. self._update_summary_dict(summary_dict, summary_base_dir, subdir_relative_path, subdir_entry, list_explain)
  127. def _is_valid_summary_directory(self, summary_base_dir, relative_path):
  128. """
  129. Check if the given summary directory is valid.
  130. Args:
  131. summary_base_dir (str): Path of summary base directory.
  132. relative_path (str): Relative path of summary directory, referring to summary base directory,
  133. starting with "./" .
  134. Returns:
  135. bool, indicates if summary directory is valid.
  136. """
  137. summary_base_dir = os.path.realpath(summary_base_dir)
  138. summary_directory = os.path.realpath(os.path.join(summary_base_dir, relative_path))
  139. if not os.path.exists(summary_directory):
  140. logger.info('Path of summary directory not exists.')
  141. return False
  142. if not os.path.isdir(summary_directory):
  143. logger.warning('Path of summary directory is not a valid directory.')
  144. return False
  145. try:
  146. Path(summary_directory).relative_to(Path(summary_base_dir))
  147. except ValueError:
  148. logger.warning('Relative path %s is not subdirectory of summary_base_dir', relative_path)
  149. return False
  150. return True
  151. def _update_summary_dict(self, summary_dict, summary_base_dir, relative_path, entry, list_explain):
  152. """
  153. Update summary_dict with ctime and mtime.
  154. Args:
  155. summary_dict (dict): Temporary data structure to hold summary directory info.
  156. summary_base_dir (str): Path of summary base directory.
  157. relative_path (str): Relative path of summary directory, referring to summary base directory,
  158. starting with "./" .
  159. entry (DirEntry): Directory entry instance needed to check with regular expression.
  160. list_explain (bool): Indicates whether to list only the mindexplain folder.
  161. """
  162. try:
  163. stat = entry.stat()
  164. except FileNotFoundError:
  165. logger.warning('File %s not found', entry.name)
  166. return
  167. ctime = datetime.datetime.fromtimestamp(stat.st_ctime).astimezone()
  168. mtime = datetime.datetime.fromtimestamp(stat.st_mtime).astimezone()
  169. if entry.is_file():
  170. summary_pattern = re.search(self.SUMMARY_FILENAME_REGEX, entry.name)
  171. pb_pattern = re.search(self.PB_FILENAME_REGEX, entry.name)
  172. if not self._is_valid_pattern_result(summary_pattern, pb_pattern, list_explain, entry):
  173. return
  174. if summary_pattern is not None:
  175. timestamp = int(summary_pattern.groupdict().get('timestamp'))
  176. try:
  177. # extract created time from filename
  178. ctime = datetime.datetime.fromtimestamp(timestamp).astimezone()
  179. except OverflowError:
  180. return
  181. if relative_path not in summary_dict:
  182. summary_dict[relative_path] = _new_entry(ctime, mtime)
  183. job_dict = _get_explain_job_info(summary_base_dir, relative_path, timestamp)
  184. summary_dict[relative_path].update(job_dict)
  185. if summary_dict[relative_path]['create_time'] < ctime:
  186. summary_dict[relative_path].update({
  187. 'create_time': ctime,
  188. 'update_time': mtime,
  189. })
  190. job_dict = _get_explain_job_info(summary_base_dir, relative_path, timestamp)
  191. summary_dict[relative_path].update(job_dict)
  192. if not summary_pattern:
  193. summary_dict[relative_path]['graph_files'] += 1
  194. elif entry.name.endswith(LINEAGE_SUMMARY_SUFFIX):
  195. summary_dict[relative_path]['lineage_files'] += 1
  196. elif entry.name.endswith(EXPLAIN_SUMMARY_SUFFIX):
  197. summary_dict[relative_path]['explain_files'] += 1
  198. else:
  199. summary_dict[relative_path]['summary_files'] += 1
  200. elif entry.is_dir():
  201. if list_explain:
  202. return
  203. profiler_type, is_find = self._find_profiler_dir(entry, summary_base_dir, relative_path)
  204. if not is_find:
  205. return
  206. profiler = {
  207. 'directory': os.path.join('.', entry.name),
  208. 'create_time': ctime,
  209. 'update_time': mtime,
  210. "profiler_type": profiler_type
  211. }
  212. if relative_path in summary_dict:
  213. summary_dict[relative_path]['profiler'] = profiler
  214. else:
  215. summary_dict[relative_path] = _new_entry(ctime, mtime, profiler)
  216. def _find_profiler_dir(self, entry, summary_base_dir, relative_path):
  217. """Find profiler dir by the given relative path."""
  218. profiler_pattern = re.search(self.PROFILER_DIRECTORY_REGEX, entry.name)
  219. full_dir_path = os.path.join(summary_base_dir, relative_path, entry.name)
  220. is_valid_profiler_dir, profiler_type = self._is_valid_profiler_directory(full_dir_path)
  221. if profiler_pattern is None or not is_valid_profiler_dir:
  222. return profiler_type, False
  223. return profiler_type, True
  224. def _is_valid_pattern_result(self, summary_pattern, pb_pattern, list_explain, entry):
  225. """Check the pattern result is valid."""
  226. if summary_pattern is None and pb_pattern is None:
  227. return False
  228. if list_explain and not entry.name.endswith(EXPLAIN_SUMMARY_SUFFIX):
  229. return False
  230. if not list_explain and entry.name.endswith(EXPLAIN_SUMMARY_SUFFIX):
  231. return False
  232. return True
  233. def is_summary_directory(self, summary_base_dir, relative_path):
  234. """
  235. Check if the given summary directory is valid.
  236. Args:
  237. summary_base_dir (str): Path of summary base directory.
  238. relative_path (str): Relative path of summary directory, referring to summary base directory,
  239. starting with "./" .
  240. Returns:
  241. bool, indicates if the given summary directory is valid.
  242. Examples:
  243. >>> from mindinsight.datavisual.data_transform.summary_watcher import SummaryWatcher
  244. >>> summary_watcher = SummaryWatcher()
  245. >>> summaries = summary_watcher.is_summary_directory('/summary/base/dir', './job-01')
  246. """
  247. if contains_null_byte(summary_base_dir=summary_base_dir, relative_path=relative_path):
  248. return False
  249. if not self._is_valid_summary_directory(summary_base_dir, relative_path):
  250. return False
  251. summary_directory = os.path.realpath(os.path.join(summary_base_dir, relative_path))
  252. try:
  253. entries = os.scandir(summary_directory)
  254. except PermissionError:
  255. logger.error('Path of summary base directory is not accessible.')
  256. raise FileSystemPermissionError('Path of summary base directory is not accessible.')
  257. for entry in entries:
  258. if entry.is_symlink():
  259. continue
  260. summary_pattern = re.search(self.SUMMARY_FILENAME_REGEX, entry.name)
  261. if summary_pattern is not None and entry.is_file():
  262. return True
  263. pb_pattern = re.search(self.PB_FILENAME_REGEX, entry.name)
  264. if pb_pattern is not None and entry.is_file():
  265. return True
  266. profiler_pattern = re.search(self.PROFILER_DIRECTORY_REGEX, entry.name)
  267. if profiler_pattern is not None and entry.is_dir():
  268. full_path = os.path.realpath(os.path.join(summary_directory, entry.name))
  269. if self._is_valid_profiler_directory(full_path)[0]:
  270. return True
  271. return False
  272. def _is_valid_profiler_directory(self, directory):
  273. profiler_type = ""
  274. try:
  275. from mindinsight.profiler.common.util import analyse_device_list_from_profiler_dir
  276. device_list, profiler_type = analyse_device_list_from_profiler_dir(directory)
  277. except ImportError:
  278. device_list = []
  279. return bool(device_list), profiler_type
  280. def list_summary_directories_by_pagination(self, summary_base_dir, offset=0, limit=10):
  281. """
  282. List summary directories within base directory.
  283. Args:
  284. summary_base_dir (str): Path of summary base directory.
  285. offset (int): An offset for page. Ex, offset is 0, mean current page is 1. Default value is 0.
  286. limit (int): The max data items for per page. Default value is 10.
  287. Returns:
  288. tuple[total, directories], total indicates the overall number of summary directories and directories
  289. indicate list of summary directory info including the following attributes.
  290. - relative_path (str): Relative path of summary directory, referring to settings.SUMMARY_BASE_DIR,
  291. starting with "./".
  292. - create_time (datetime): Creation time of summary file.
  293. - update_time (datetime): Modification time of summary file.
  294. Raises:
  295. ParamValueError, if offset < 0 or limit is out of valid value range.
  296. ParamTypeError, if offset or limit is not valid integer.
  297. Examples:
  298. >>> from mindinsight.datavisual.data_transform.summary_watcher import SummaryWatcher
  299. >>> summary_watcher = SummaryWatcher()
  300. >>> total, directories = summary_watcher.list_summary_directories_by_pagination(
  301. '/summary/base/dir', offset=0, limit=10)
  302. """
  303. offset = Validation.check_offset(offset=offset)
  304. limit = Validation.check_limit(limit, min_value=1, max_value=999)
  305. directories = self.list_summary_directories(summary_base_dir, overall=False)
  306. return len(directories), directories[offset * limit:(offset + 1) * limit]
  307. def list_summaries(self, summary_base_dir, relative_path='./'):
  308. """
  309. Get info of latest summary file within the given summary directory.
  310. Args:
  311. summary_base_dir (str): Path of summary base directory.
  312. relative_path (str): Relative path of summary directory, referring to summary base directory,
  313. starting with "./" .
  314. Returns:
  315. list, list of summary file including the following attributes.
  316. - file_name (str): Summary file name.
  317. - create_time (datetime): Creation time of summary file.
  318. - update_time (datetime): Modification time of summary file.
  319. Examples:
  320. >>> from mindinsight.datavisual.data_transform.summary_watcher import SummaryWatcher
  321. >>> summary_watcher = SummaryWatcher()
  322. >>> summaries = summary_watcher.list_summaries('/summary/base/dir', './job-01')
  323. """
  324. if contains_null_byte(summary_base_dir=summary_base_dir, relative_path=relative_path):
  325. return []
  326. if not self._is_valid_summary_directory(summary_base_dir, relative_path):
  327. return []
  328. summaries = []
  329. summary_directory = os.path.realpath(os.path.join(summary_base_dir, relative_path))
  330. try:
  331. entries = os.scandir(summary_directory)
  332. except PermissionError:
  333. logger.error('Path of summary directory is not accessible.')
  334. raise FileSystemPermissionError('Path of summary directory is not accessible.')
  335. for entry in entries:
  336. if entry.is_symlink() or not entry.is_file():
  337. continue
  338. pattern = re.search(self.SUMMARY_FILENAME_REGEX, entry.name)
  339. if pattern is None:
  340. continue
  341. timestamp = int(pattern.groupdict().get('timestamp'))
  342. try:
  343. # extract created time from filename
  344. ctime = datetime.datetime.fromtimestamp(timestamp).astimezone()
  345. except OverflowError:
  346. continue
  347. try:
  348. stat = entry.stat()
  349. except FileNotFoundError:
  350. logger.warning('File %s not found.', entry.name)
  351. continue
  352. mtime = datetime.datetime.fromtimestamp(stat.st_mtime).astimezone()
  353. summaries.append({
  354. 'file_name': entry.name,
  355. 'create_time': ctime,
  356. 'update_time': mtime,
  357. })
  358. # sort by update time in descending order and filename in ascending order
  359. summaries.sort(key=lambda x: (-int(x['update_time'].timestamp()), x['file_name']))
  360. return summaries
  361. def list_explain_directories(self, summary_base_dir, offset=0, limit=None):
  362. """
  363. List explain directories within base directory.
  364. Args:
  365. summary_base_dir (str): Path of summary base directory.
  366. offset (int): An offset for page. Ex, offset is 0, mean current page is 1. Default value is 0.
  367. limit (int): The max data items for per page. Default value is 10.
  368. Returns:
  369. tuple[total, directories], total indicates the overall number of explain directories and directories
  370. indicate list of summary directory info including the following attributes.
  371. - relative_path (str): Relative path of summary directory, referring to settings.SUMMARY_BASE_DIR,
  372. starting with "./".
  373. - create_time (datetime): Creation time of summary file.
  374. - update_time (datetime): Modification time of summary file.
  375. Raises:
  376. ParamValueError, if offset < 0 or limit is out of valid value range.
  377. ParamTypeError, if offset or limit is not valid integer.
  378. Examples:
  379. >>> from mindinsight.datavisual.data_transform.summary_watcher import SummaryWatcher
  380. >>> summary_watcher = SummaryWatcher()
  381. >>> total, directories = summary_watcher.list_explain_directories('/summary/base/dir', offset=0, limit=10)
  382. """
  383. offset = Validation.check_offset(offset=offset)
  384. limit = Validation.check_limit(limit, min_value=1, max_value=999, default_value=None)
  385. directories = self.list_summary_directories(summary_base_dir, overall=False, list_explain=True)
  386. if limit is None:
  387. return len(directories), directories
  388. return len(directories), directories[offset * limit:(offset + 1) * limit]
  389. def _new_entry(ctime, mtime, profiler=None):
  390. """Create a new entry."""
  391. return {
  392. 'create_time': ctime,
  393. 'update_time': mtime,
  394. 'summary_files': 0,
  395. 'lineage_files': 0,
  396. 'explain_files': 0,
  397. 'graph_files': 0,
  398. 'profiler': profiler
  399. }
  400. def _get_explain_job_info(summary_base_dir, relative_path, timestamp):
  401. """Get explain job info."""
  402. json_path = os.path.join(summary_base_dir, relative_path.lstrip("./"), f"_explain_{timestamp}",
  403. "manifest.json")
  404. if os.path.exists(json_path):
  405. with open(json_path, "r") as f:
  406. job_dict = json.load(f)
  407. return job_dict
  408. # Set default value to make it compatible with previous version
  409. job_dict = {"saliency_map": True, "hierarchical_occlusion": False}
  410. return job_dict