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.

utils.py 4.3 kB

5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. # Copyright 2019 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. """Lineage utils."""
  16. import os
  17. import re
  18. from functools import wraps
  19. from pathlib import Path
  20. from mindinsight.datavisual.data_transform.summary_watcher import SummaryWatcher
  21. from mindinsight.lineagemgr.common.exceptions.exceptions import LineageParamRunContextError, \
  22. LineageGetModelFileError, LineageLogError, LineageParamValueError, LineageParamTypeError, \
  23. LineageDirNotExistError, LineageParamSummaryPathError
  24. from mindinsight.lineagemgr.common.log import logger as log
  25. from mindinsight.lineagemgr.common.validator.validate import validate_path
  26. from mindinsight.utils.exceptions import MindInsightException
  27. def enum_to_list(enum):
  28. return [enum_ele.value for enum_ele in enum]
  29. def try_except(logger):
  30. """
  31. Catch or raise exceptions while collecting lineage.
  32. Args:
  33. logger (logger): The logger instance which logs the warning info.
  34. Returns:
  35. function, the decorator which we use to retry the decorated function.
  36. """
  37. def try_except_decorate(func):
  38. @wraps(func)
  39. def wrapper(self, *args, **kwargs):
  40. try:
  41. func(self, *args, **kwargs)
  42. except (AttributeError, MindInsightException,
  43. LineageParamRunContextError, LineageLogError,
  44. LineageGetModelFileError, IOError) as err:
  45. logger.error(err)
  46. try:
  47. raise_except = self.raise_exception
  48. except AttributeError:
  49. raise_except = False
  50. if raise_except is True:
  51. raise
  52. return wrapper
  53. return try_except_decorate
  54. def normalize_summary_dir(summary_dir):
  55. """Normalize summary dir."""
  56. try:
  57. summary_dir = validate_path(summary_dir)
  58. except (LineageParamValueError, LineageDirNotExistError) as error:
  59. log.error(str(error))
  60. log.exception(error)
  61. raise LineageParamSummaryPathError(str(error.message))
  62. return summary_dir
  63. def get_timestamp(filename):
  64. """Get timestamp from filename."""
  65. timestamp = int(re.search(SummaryWatcher().SUMMARY_FILENAME_REGEX, filename)[1])
  66. return timestamp
  67. def make_directory(path):
  68. """Make directory."""
  69. real_path = None
  70. if path is None or not isinstance(path, str) or not path.strip():
  71. log.error("Invalid input path: %r.", path)
  72. raise LineageParamTypeError("Invalid path type")
  73. # convert relative path to abs path
  74. path = os.path.realpath(path)
  75. log.debug("The abs path is %r", path)
  76. # check path exist and its write permissions]
  77. if os.path.exists(path):
  78. real_path = path
  79. else:
  80. # All exceptions need to be caught because create directory maybe have some limit(permissions)
  81. log.debug("The directory(%s) doesn't exist, will create it", path)
  82. try:
  83. os.makedirs(path, exist_ok=True)
  84. real_path = path
  85. except PermissionError as err:
  86. log.error("No write permission on the directory(%r), error = %r", path, err)
  87. raise LineageParamTypeError("No write permission on the directory.")
  88. return real_path
  89. def get_relative_path(path, base_path):
  90. """
  91. Get relative path based on base_path.
  92. Args:
  93. path (str): absolute path.
  94. base_path: absolute base path.
  95. Returns:
  96. str, relative path based on base_path.
  97. """
  98. try:
  99. r_path = str(Path(path).relative_to(Path(base_path)))
  100. except ValueError:
  101. raise LineageParamValueError("The path %r does not start with %r." % (path, base_path))
  102. if r_path == ".":
  103. r_path = ""
  104. return os.path.join("./", r_path)