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