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