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 3.8 kB

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