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