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.

exceptions.py 16 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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. """Define custom exception."""
  16. import abc
  17. import sys
  18. from enum import unique, Enum
  19. from importlib import import_module
  20. from lib2to3.pgen2 import parse
  21. from treelib.exceptions import DuplicatedNodeIdError, MultipleRootError, NodeIDAbsentError
  22. from mindinsight.mindconverter.common.log import logger as log, logger_console as log_console
  23. from mindinsight.utils.constant import ScriptConverterErrors
  24. from mindinsight.utils.exceptions import MindInsightException
  25. @unique
  26. class ConverterErrors(ScriptConverterErrors):
  27. """Converter error codes."""
  28. SCRIPT_NOT_SUPPORT = 1
  29. NODE_TYPE_NOT_SUPPORT = 2
  30. CODE_SYNTAX_ERROR = 3
  31. BASE_CONVERTER_FAIL = 000
  32. GRAPH_INIT_FAIL = 100
  33. TREE_CREATE_FAIL = 200
  34. SOURCE_FILES_SAVE_FAIL = 300
  35. GENERATOR_FAIL = 400
  36. SUB_GRAPH_SEARCHING_FAIL = 500
  37. class ScriptNotSupport(MindInsightException):
  38. """The script can not support to process."""
  39. def __init__(self, msg):
  40. super(ScriptNotSupport, self).__init__(ConverterErrors.SCRIPT_NOT_SUPPORT,
  41. msg,
  42. http_code=400)
  43. class NodeTypeNotSupport(MindInsightException):
  44. """The astNode can not support to process."""
  45. def __init__(self, msg):
  46. super(NodeTypeNotSupport, self).__init__(ConverterErrors.NODE_TYPE_NOT_SUPPORT,
  47. msg,
  48. http_code=400)
  49. class CodeSyntaxError(MindInsightException):
  50. """The CodeSyntaxError class definition."""
  51. def __init__(self, msg):
  52. super(CodeSyntaxError, self).__init__(ConverterErrors.CODE_SYNTAX_ERROR,
  53. msg,
  54. http_code=400)
  55. class MindConverterException(Exception):
  56. """MindConverter exception."""
  57. BASE_ERROR_CODE = None # ConverterErrors.BASE_CONVERTER_FAIL.value
  58. # ERROR_CODE should be declared in child exception.
  59. ERROR_CODE = None
  60. def __init__(self, **kwargs):
  61. """Initialization of MindInsightException."""
  62. user_msg = kwargs.get('user_msg', '')
  63. if isinstance(user_msg, str):
  64. user_msg = ' '.join(user_msg.split())
  65. super(MindConverterException, self).__init__()
  66. self.user_msg = user_msg
  67. self.root_exception_error_code = None
  68. def __str__(self):
  69. return '[{}] code: {}, msg: {}'.format(self.__class__.__name__, self.error_code(), self.user_msg)
  70. def __repr__(self):
  71. return self.__str__()
  72. def error_code(self):
  73. """"
  74. Calculate error code.
  75. code compose(2bytes)
  76. error: 16bits.
  77. num = 0xFFFF & error
  78. error_cods
  79. Returns:
  80. str, Hex string representing the composed MindConverter error code.
  81. """
  82. if self.root_exception_error_code:
  83. return self.root_exception_error_code
  84. if self.BASE_ERROR_CODE is None or self.ERROR_CODE is None:
  85. raise ValueError("MindConverterException has not been initialized.")
  86. num = 0xFFFF & self.ERROR_CODE # 0xFFFF & self.error.value
  87. error_code = f"{str(self.BASE_ERROR_CODE).zfill(3)}{hex(num)[2:].zfill(4).upper()}"
  88. return error_code
  89. @classmethod
  90. @abc.abstractmethod
  91. def raise_from(cls):
  92. """Raise from below exceptions."""
  93. @classmethod
  94. def normalize_error_msg(cls, error_msg):
  95. """Normalize error msg for common python exception."""
  96. if cls.BASE_ERROR_CODE is None or cls.ERROR_CODE is None:
  97. raise ValueError("MindConverterException has not been initialized.")
  98. num = 0xFFFF & cls.ERROR_CODE # 0xFFFF & self.error.value
  99. error_code = f"{str(cls.BASE_ERROR_CODE).zfill(3)}{hex(num)[2:].zfill(4).upper()}"
  100. return f"[{cls.__name__}] code: {error_code}, msg: {error_msg}"
  101. @classmethod
  102. def uniform_catcher(cls, msg: str = ""):
  103. """Uniform exception catcher."""
  104. def decorator(func):
  105. def _f(*args, **kwargs):
  106. try:
  107. res = func(*args, **kwargs)
  108. except cls.raise_from() as e:
  109. error = cls() if not msg else cls(msg=msg)
  110. detail_info = str(e)
  111. if not isinstance(e, MindConverterException):
  112. detail_info = cls.normalize_error_msg(str(e))
  113. log.error(error)
  114. log_console.error("\n")
  115. log_console.error(detail_info)
  116. log_console.error("\n")
  117. log.exception(e)
  118. sys.exit(0)
  119. except ModuleNotFoundError as e:
  120. detail_info = "Error detail: Required package not found, please check the runtime environment."
  121. log_console.error("\n")
  122. log_console.error(str(e))
  123. log_console.error(detail_info)
  124. log_console.error("\n")
  125. log.exception(e)
  126. sys.exit(0)
  127. return res
  128. return _f
  129. return decorator
  130. @classmethod
  131. def check_except(cls, msg):
  132. """Check except."""
  133. def decorator(func):
  134. def _f(*args, **kwargs):
  135. try:
  136. output = func(*args, **kwargs)
  137. except cls.raise_from() as e:
  138. error = cls(msg=msg)
  139. error_code = e.error_code() if isinstance(e, MindConverterException) else None
  140. error.root_exception_error_code = error_code
  141. log.error(msg)
  142. log.exception(e)
  143. raise error
  144. except Exception as e:
  145. log.error(msg)
  146. log.exception(e)
  147. raise e
  148. return output
  149. return _f
  150. return decorator
  151. class BaseConverterError(MindConverterException):
  152. """Base converter failed."""
  153. @unique
  154. class ErrCode(Enum):
  155. """Define error code of BaseConverterError."""
  156. UNKNOWN_ERROR = 0
  157. UNKNOWN_MODEL = 1
  158. PARAM_MISSING = 2
  159. BASE_ERROR_CODE = ConverterErrors.BASE_CONVERTER_FAIL.value
  160. ERROR_CODE = ErrCode.UNKNOWN_ERROR.value
  161. DEFAULT_MSG = "Failed to start base converter."
  162. def __init__(self, msg=DEFAULT_MSG):
  163. super(BaseConverterError, self).__init__(user_msg=msg)
  164. @classmethod
  165. def raise_from(cls):
  166. """Raise from exceptions below."""
  167. except_source = Exception, UnknownModelError, ParamMissingError, cls
  168. return except_source
  169. class UnknownModelError(BaseConverterError):
  170. """The unknown model error."""
  171. ERROR_CODE = BaseConverterError.ErrCode.UNKNOWN_MODEL.value
  172. def __init__(self, msg):
  173. super(UnknownModelError, self).__init__(msg=msg)
  174. @classmethod
  175. def raise_from(cls):
  176. return cls
  177. class ParamMissingError(BaseConverterError):
  178. """Define cli params missing error."""
  179. ERROR_CODE = BaseConverterError.ErrCode.PARAM_MISSING.value
  180. def __init__(self, msg):
  181. super(ParamMissingError, self).__init__(msg=msg)
  182. @classmethod
  183. def raise_from(cls):
  184. return cls
  185. class GraphInitError(MindConverterException):
  186. """The graph init fail error."""
  187. @unique
  188. class ErrCode(Enum):
  189. """Define error code of GraphInitError."""
  190. UNKNOWN_ERROR = 0
  191. MODEL_NOT_SUPPORT = 1
  192. TF_RUNTIME_ERROR = 2
  193. INPUT_SHAPE_ERROR = 3
  194. MI_RUNTIME_ERROR = 4
  195. BASE_ERROR_CODE = ConverterErrors.GRAPH_INIT_FAIL.value
  196. ERROR_CODE = ErrCode.UNKNOWN_ERROR.value
  197. DEFAULT_MSG = "Error occurred when init graph object."
  198. def __init__(self, msg=DEFAULT_MSG):
  199. super(GraphInitError, self).__init__(user_msg=msg)
  200. @classmethod
  201. def raise_from(cls):
  202. """Raise from exceptions below."""
  203. except_source = (FileNotFoundError,
  204. ModuleNotFoundError,
  205. ModelNotSupportError,
  206. ModelLoadingError,
  207. RuntimeIntegrityError,
  208. TypeError,
  209. ZeroDivisionError,
  210. RuntimeError,
  211. cls)
  212. return except_source
  213. class TreeCreationError(MindConverterException):
  214. """The tree create fail."""
  215. @unique
  216. class ErrCode(Enum):
  217. """Define error code of TreeCreationError."""
  218. UNKNOWN_ERROR = 0
  219. NODE_INPUT_MISSING = 1
  220. TREE_NODE_INSERT_FAIL = 2
  221. BASE_ERROR_CODE = ConverterErrors.TREE_CREATE_FAIL.value
  222. ERROR_CODE = ErrCode.UNKNOWN_ERROR.value
  223. DEFAULT_MSG = "Error occurred when create hierarchical tree."
  224. def __init__(self, msg=DEFAULT_MSG):
  225. super(TreeCreationError, self).__init__(user_msg=msg)
  226. @classmethod
  227. def raise_from(cls):
  228. """Raise from exceptions below."""
  229. except_source = NodeInputMissingError, TreeNodeInsertError, cls
  230. return except_source
  231. class SourceFilesSaveError(MindConverterException):
  232. """The source files save fail error."""
  233. @unique
  234. class ErrCode(Enum):
  235. """Define error code of SourceFilesSaveError."""
  236. UNKNOWN_ERROR = 0
  237. NODE_INPUT_TYPE_NOT_SUPPORT = 1
  238. SCRIPT_GENERATE_FAIL = 2
  239. REPORT_GENERATE_FAIL = 3
  240. BASE_ERROR_CODE = ConverterErrors.SOURCE_FILES_SAVE_FAIL.value
  241. ERROR_CODE = ErrCode.UNKNOWN_ERROR.value
  242. DEFAULT_MSG = "Error occurred when save source files."
  243. def __init__(self, msg=DEFAULT_MSG):
  244. super(SourceFilesSaveError, self).__init__(user_msg=msg)
  245. @classmethod
  246. def raise_from(cls):
  247. """Raise from exceptions below."""
  248. except_source = (NodeInputTypeNotSupportError,
  249. ScriptGenerationError,
  250. ReportGenerationError,
  251. IOError, cls)
  252. return except_source
  253. class ModelNotSupportError(GraphInitError):
  254. """The model not support error."""
  255. ERROR_CODE = GraphInitError.ErrCode.MODEL_NOT_SUPPORT.value
  256. def __init__(self, msg):
  257. super(ModelNotSupportError, self).__init__(msg=msg)
  258. @classmethod
  259. def raise_from(cls):
  260. """Raise from exceptions below."""
  261. except_source = (RuntimeError,
  262. ModuleNotFoundError,
  263. ValueError,
  264. AssertionError,
  265. TypeError,
  266. OSError,
  267. ZeroDivisionError, cls)
  268. return except_source
  269. class TfRuntimeError(GraphInitError):
  270. """Catch tf runtime error."""
  271. ERROR_CODE = GraphInitError.ErrCode.TF_RUNTIME_ERROR.value
  272. DEFAULT_MSG = "Error occurred when init graph, TensorFlow runtime error."
  273. def __init__(self, msg=DEFAULT_MSG):
  274. super(TfRuntimeError, self).__init__(msg=msg)
  275. @classmethod
  276. def raise_from(cls):
  277. tf_error_module = import_module('tensorflow.python.framework.errors_impl')
  278. tf_error = getattr(tf_error_module, 'OpError')
  279. return tf_error, ValueError, RuntimeError, cls
  280. class RuntimeIntegrityError(GraphInitError):
  281. """Catch runtime error."""
  282. ERROR_CODE = GraphInitError.ErrCode.MI_RUNTIME_ERROR.value
  283. def __init__(self, msg):
  284. super(RuntimeIntegrityError, self).__init__(msg=msg)
  285. @classmethod
  286. def raise_from(cls):
  287. return RuntimeError, AttributeError, ImportError, ModuleNotFoundError, cls
  288. class NodeInputMissingError(TreeCreationError):
  289. """The node input missing error."""
  290. ERROR_CODE = TreeCreationError.ErrCode.NODE_INPUT_MISSING.value
  291. def __init__(self, msg):
  292. super(NodeInputMissingError, self).__init__(msg=msg)
  293. @classmethod
  294. def raise_from(cls):
  295. return ValueError, IndexError, KeyError, AttributeError, cls
  296. class TreeNodeInsertError(TreeCreationError):
  297. """The tree node create fail error."""
  298. ERROR_CODE = TreeCreationError.ErrCode.TREE_NODE_INSERT_FAIL.value
  299. def __init__(self, msg):
  300. super(TreeNodeInsertError, self).__init__(msg=msg)
  301. @classmethod
  302. def raise_from(cls):
  303. """Raise from exceptions below."""
  304. except_source = (OSError,
  305. DuplicatedNodeIdError,
  306. MultipleRootError,
  307. NodeIDAbsentError, cls)
  308. return except_source
  309. class NodeInputTypeNotSupportError(SourceFilesSaveError):
  310. """The node input type NOT support error."""
  311. ERROR_CODE = SourceFilesSaveError.ErrCode.NODE_INPUT_TYPE_NOT_SUPPORT.value
  312. def __init__(self, msg):
  313. super(NodeInputTypeNotSupportError, self).__init__(msg=msg)
  314. @classmethod
  315. def raise_from(cls):
  316. return ValueError, TypeError, IndexError, cls
  317. class ScriptGenerationError(SourceFilesSaveError):
  318. """The script generate fail error."""
  319. ERROR_CODE = SourceFilesSaveError.ErrCode.SCRIPT_GENERATE_FAIL.value
  320. def __init__(self, msg):
  321. super(ScriptGenerationError, self).__init__(msg=msg)
  322. @classmethod
  323. def raise_from(cls):
  324. """Raise from exceptions below."""
  325. except_source = (RuntimeError,
  326. parse.ParseError,
  327. AttributeError, cls)
  328. return except_source
  329. class ReportGenerationError(SourceFilesSaveError):
  330. """The report generate fail error."""
  331. ERROR_CODE = SourceFilesSaveError.ErrCode.REPORT_GENERATE_FAIL.value
  332. def __init__(self, msg):
  333. super(ReportGenerationError, self).__init__(msg=msg)
  334. @classmethod
  335. def raise_from(cls):
  336. """Raise from exceptions below."""
  337. return ZeroDivisionError, cls
  338. class SubGraphSearchingError(MindConverterException):
  339. """Sub-graph searching exception."""
  340. @unique
  341. class ErrCode(Enum):
  342. """Define error code of SourceFilesSaveError."""
  343. BASE_ERROR = 0
  344. CANNOT_FIND_VALID_PATTERN = 1
  345. MODEL_NOT_SUPPORT = 2
  346. BASE_ERROR_CODE = ConverterErrors.SUB_GRAPH_SEARCHING_FAIL.value
  347. ERROR_CODE = ErrCode.BASE_ERROR.value
  348. DEFAULT_MSG = "Sub-Graph pattern searching fail."
  349. def __init__(self, msg=DEFAULT_MSG):
  350. super(SubGraphSearchingError, self).__init__(user_msg=msg)
  351. @classmethod
  352. def raise_from(cls):
  353. """Define exception in sub-graph searching module."""
  354. return IndexError, KeyError, ValueError, AttributeError, ZeroDivisionError, cls
  355. class GeneratorError(MindConverterException):
  356. """The Generator fail error."""
  357. @unique
  358. class ErrCode(Enum):
  359. """Define error code of SourceFilesSaveError."""
  360. BASE_ERROR = 0
  361. STATEMENT_GENERATION_ERROR = 1
  362. CONVERTED_OPERATOR_LOADING_ERROR = 2
  363. BASE_ERROR_CODE = ConverterErrors.GENERATOR_FAIL.value
  364. ERROR_CODE = ErrCode.BASE_ERROR.value
  365. DEFAULT_MSG = "Error occurred when generate code."
  366. def __init__(self, msg=DEFAULT_MSG):
  367. super(GeneratorError, self).__init__(user_msg=msg)
  368. @classmethod
  369. def raise_from(cls):
  370. """Raise from exceptions below."""
  371. except_source = (ValueError, TypeError, cls)
  372. return except_source
  373. class ModelLoadingError(GraphInitError):
  374. """Model loading fail."""
  375. ERROR_CODE = GraphInitError.ErrCode.INPUT_SHAPE_ERROR.value
  376. def __init__(self, msg):
  377. super(ModelLoadingError, self).__init__(msg=msg)
  378. @classmethod
  379. def raise_from(cls):
  380. """Define exception when model loading fail."""
  381. return ValueError, cls