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