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.

validate.py 21 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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. """Validate the parameters."""
  16. import os
  17. import re
  18. from marshmallow import ValidationError
  19. from mindinsight.lineagemgr.common.exceptions.error_code import LineageErrors, LineageErrorMsg
  20. from mindinsight.lineagemgr.common.exceptions.exceptions import LineageParamMissingError, \
  21. LineageParamTypeError, LineageParamValueError, LineageDirNotExistError
  22. from mindinsight.lineagemgr.common.log import logger as log
  23. from mindinsight.lineagemgr.common.validator.validate_path import safe_normalize_path
  24. from mindinsight.lineagemgr.querier.query_model import FIELD_MAPPING
  25. from mindinsight.utils.exceptions import MindInsightException, ParamValueError
  26. try:
  27. from mindspore.nn import Cell
  28. from mindspore.train.summary import SummaryRecord
  29. except (ImportError, ModuleNotFoundError):
  30. log.warning('MindSpore Not Found!')
  31. # Named string regular expression
  32. _name_re = r"^\w+[0-9a-zA-Z\_\.]*$"
  33. TRAIN_RUN_CONTEXT_ERROR_MAPPING = {
  34. 'optimizer': LineageErrors.PARAM_OPTIMIZER_ERROR,
  35. 'loss_fn': LineageErrors.PARAM_LOSS_FN_ERROR,
  36. 'net_outputs': LineageErrors.PARAM_NET_OUTPUTS_ERROR,
  37. 'train_network': LineageErrors.PARAM_TRAIN_NETWORK_ERROR,
  38. 'train_dataset': LineageErrors.PARAM_DATASET_ERROR,
  39. 'epoch_num': LineageErrors.PARAM_EPOCH_NUM_ERROR,
  40. 'batch_num': LineageErrors.PARAM_BATCH_NUM_ERROR,
  41. 'parallel_mode': LineageErrors.PARAM_TRAIN_PARALLEL_ERROR,
  42. 'device_number': LineageErrors.PARAM_DEVICE_NUMBER_ERROR,
  43. 'list_callback': LineageErrors.PARAM_CALLBACK_LIST_ERROR,
  44. 'train_dataset_size': LineageErrors.PARAM_DATASET_SIZE_ERROR,
  45. }
  46. SEARCH_MODEL_ERROR_MAPPING = {
  47. 'summary_dir': LineageErrors.LINEAGE_PARAM_SUMMARY_DIR_ERROR,
  48. 'loss_function': LineageErrors.LINEAGE_PARAM_LOSS_FUNCTION_ERROR,
  49. 'train_dataset_path': LineageErrors.LINEAGE_PARAM_TRAIN_DATASET_PATH_ERROR,
  50. 'train_dataset_count': LineageErrors.LINEAGE_PARAM_TRAIN_DATASET_COUNT_ERROR,
  51. 'test_dataset_path': LineageErrors.LINEAGE_PARAM_TEST_DATASET_PATH_ERROR,
  52. 'test_dataset_count': LineageErrors.LINEAGE_PARAM_TEST_DATASET_COUNT_ERROR,
  53. 'network': LineageErrors.LINEAGE_PARAM_NETWORK_ERROR,
  54. 'optimizer': LineageErrors.LINEAGE_PARAM_OPTIMIZER_ERROR,
  55. 'learning_rate': LineageErrors.LINEAGE_PARAM_LEARNING_RATE_ERROR,
  56. 'epoch': LineageErrors.LINEAGE_PARAM_EPOCH_ERROR,
  57. 'batch_size': LineageErrors.LINEAGE_PARAM_BATCH_SIZE_ERROR,
  58. 'device_num': LineageErrors.LINEAGE_PARAM_DEVICE_NUM_ERROR,
  59. 'limit': LineageErrors.PARAM_VALUE_ERROR,
  60. 'offset': LineageErrors.PARAM_VALUE_ERROR,
  61. 'loss': LineageErrors.LINEAGE_PARAM_LOSS_ERROR,
  62. 'model_size': LineageErrors.LINEAGE_PARAM_MODEL_SIZE_ERROR,
  63. 'sorted_name': LineageErrors.LINEAGE_PARAM_SORTED_NAME_ERROR,
  64. 'sorted_type': LineageErrors.LINEAGE_PARAM_SORTED_TYPE_ERROR,
  65. 'dataset_mark': LineageErrors.LINEAGE_PARAM_DATASET_MARK_ERROR,
  66. 'lineage_type': LineageErrors.LINEAGE_PARAM_LINEAGE_TYPE_ERROR
  67. }
  68. TRAIN_RUN_CONTEXT_ERROR_MSG_MAPPING = {
  69. 'optimizer': LineageErrorMsg.PARAM_OPTIMIZER_ERROR.value,
  70. 'loss_fn': LineageErrorMsg.PARAM_LOSS_FN_ERROR.value,
  71. 'net_outputs': LineageErrorMsg.PARAM_NET_OUTPUTS_ERROR.value,
  72. 'train_network': LineageErrorMsg.PARAM_TRAIN_NETWORK_ERROR.value,
  73. 'epoch_num': LineageErrorMsg.PARAM_EPOCH_NUM_ERROR.value,
  74. 'batch_num': LineageErrorMsg.PARAM_BATCH_NUM_ERROR.value,
  75. 'parallel_mode': LineageErrorMsg.PARAM_TRAIN_PARALLEL_ERROR.value,
  76. 'device_number': LineageErrorMsg.PARAM_DEVICE_NUMBER_ERROR.value,
  77. 'list_callback': LineageErrorMsg.PARAM_CALLBACK_LIST_ERROR.value
  78. }
  79. SEARCH_MODEL_ERROR_MSG_MAPPING = {
  80. 'summary_dir': LineageErrorMsg.LINEAGE_PARAM_SUMMARY_DIR_ERROR.value,
  81. 'loss_function': LineageErrorMsg.LINEAGE_LOSS_FUNCTION_ERROR.value,
  82. 'train_dataset_path': LineageErrorMsg.LINEAGE_TRAIN_DATASET_PATH_ERROR.value,
  83. 'train_dataset_count': LineageErrorMsg.LINEAGE_TRAIN_DATASET_COUNT_ERROR.value,
  84. 'test_dataset_path': LineageErrorMsg.LINEAGE_TEST_DATASET_PATH_ERROR.value,
  85. 'test_dataset_count': LineageErrorMsg.LINEAGE_TEST_DATASET_COUNT_ERROR.value,
  86. 'network': LineageErrorMsg.LINEAGE_NETWORK_ERROR.value,
  87. 'optimizer': LineageErrorMsg.LINEAGE_OPTIMIZER_ERROR.value,
  88. 'learning_rate': LineageErrorMsg.LINEAGE_LEARNING_RATE_ERROR.value,
  89. 'epoch': LineageErrorMsg.PARAM_EPOCH_NUM_ERROR.value,
  90. 'batch_size': LineageErrorMsg.PARAM_BATCH_SIZE_ERROR.value,
  91. 'device_num': LineageErrorMsg.PARAM_DEVICE_NUM_ERROR.value,
  92. 'limit': LineageErrorMsg.PARAM_LIMIT_ERROR.value,
  93. 'offset': LineageErrorMsg.PARAM_OFFSET_ERROR.value,
  94. 'loss': LineageErrorMsg.LINEAGE_LOSS_ERROR.value,
  95. 'model_size': LineageErrorMsg.LINEAGE_MODEL_SIZE_ERROR.value,
  96. 'sorted_name': LineageErrorMsg.LINEAGE_PARAM_SORTED_NAME_ERROR.value,
  97. 'sorted_type': LineageErrorMsg.LINEAGE_PARAM_SORTED_TYPE_ERROR.value,
  98. 'dataset_mark': LineageErrorMsg.LINEAGE_PARAM_DATASET_MARK_ERROR.value,
  99. 'lineage_type': LineageErrorMsg.LINEAGE_PARAM_LINEAGE_TYPE_ERROR.value
  100. }
  101. EVAL_RUN_CONTEXT_ERROR_MAPPING = {
  102. 'valid_dataset': LineageErrors.PARAM_DATASET_ERROR,
  103. 'metrics': LineageErrors.PARAM_EVAL_METRICS_ERROR
  104. }
  105. EVAL_RUN_CONTEXT_ERROR_MSG_MAPPING = {
  106. 'metrics': LineageErrorMsg.PARAM_EVAL_METRICS_ERROR.value,
  107. }
  108. def validate_int_params(int_param, param_name):
  109. """
  110. Verify the parameter which type is integer valid or not.
  111. Args:
  112. int_param (int): parameter that is integer,
  113. including epoch, dataset_batch_size, step_num
  114. param_name (str): the name of parameter,
  115. including epoch, dataset_batch_size, step_num
  116. Raises:
  117. MindInsightException: If the parameters are invalid.
  118. """
  119. if not isinstance(int_param, int) or int_param <= 0 or int_param > pow(2, 63) - 1:
  120. if param_name == 'step_num':
  121. log.error('Invalid step_num. The step number should be a positive integer.')
  122. raise MindInsightException(error=LineageErrors.PARAM_STEP_NUM_ERROR,
  123. message=LineageErrorMsg.PARAM_STEP_NUM_ERROR.value)
  124. if param_name == 'dataset_batch_size':
  125. log.error('Invalid dataset_batch_size. '
  126. 'The batch size should be a positive integer.')
  127. raise MindInsightException(error=LineageErrors.PARAM_BATCH_SIZE_ERROR,
  128. message=LineageErrorMsg.PARAM_BATCH_SIZE_ERROR.value)
  129. def validate_network(network):
  130. """
  131. Verify if the network is valid.
  132. Args:
  133. network (Cell): See mindspore.nn.Cell.
  134. Raises:
  135. LineageParamMissingError: If the network is None.
  136. MindInsightException: If the network is invalid.
  137. """
  138. if not network:
  139. error_msg = "The input network for TrainLineage should not be None."
  140. log.error(error_msg)
  141. raise LineageParamMissingError(error_msg)
  142. if not isinstance(network, Cell):
  143. log.error("Invalid network. Network should be an instance"
  144. "of mindspore.nn.Cell.")
  145. raise MindInsightException(
  146. error=LineageErrors.PARAM_TRAIN_NETWORK_ERROR,
  147. message=LineageErrorMsg.PARAM_TRAIN_NETWORK_ERROR.value
  148. )
  149. def validate_file_path(file_path, allow_empty=False):
  150. """
  151. Verify that the file_path is valid.
  152. Args:
  153. file_path (str): Input file path.
  154. allow_empty (bool): Whether file_path can be empty.
  155. Raises:
  156. MindInsightException: If the parameters are invalid.
  157. """
  158. try:
  159. if allow_empty and not file_path:
  160. return file_path
  161. return safe_normalize_path(file_path, raise_key='dataset_path', safe_prefixes=None)
  162. except ValidationError as error:
  163. log.error(str(error))
  164. raise MindInsightException(error=LineageErrors.PARAM_FILE_PATH_ERROR,
  165. message=str(error))
  166. def validate_train_run_context(schema, data):
  167. """
  168. Validate mindspore train run_context data according to schema.
  169. Args:
  170. schema (Schema): data schema.
  171. data (dict): data to check schema.
  172. Raises:
  173. MindInsightException: If the parameters are invalid.
  174. """
  175. errors = schema().validate(data)
  176. for error_key, error_msg in errors.items():
  177. if error_key in TRAIN_RUN_CONTEXT_ERROR_MAPPING.keys():
  178. error_code = TRAIN_RUN_CONTEXT_ERROR_MAPPING.get(error_key)
  179. if TRAIN_RUN_CONTEXT_ERROR_MSG_MAPPING.get(error_key):
  180. error_msg = TRAIN_RUN_CONTEXT_ERROR_MSG_MAPPING.get(error_key)
  181. log.error(error_msg)
  182. raise MindInsightException(error=error_code, message=error_msg)
  183. def validate_eval_run_context(schema, data):
  184. """
  185. Validate mindspore evaluation job run_context data according to schema.
  186. Args:
  187. schema (Schema): data schema.
  188. data (dict): data to check schema.
  189. Raises:
  190. MindInsightException: If the parameters are invalid.
  191. """
  192. errors = schema().validate(data)
  193. for error_key, error_msg in errors.items():
  194. if error_key in EVAL_RUN_CONTEXT_ERROR_MAPPING.keys():
  195. error_code = EVAL_RUN_CONTEXT_ERROR_MAPPING.get(error_key)
  196. if EVAL_RUN_CONTEXT_ERROR_MSG_MAPPING.get(error_key):
  197. error_msg = EVAL_RUN_CONTEXT_ERROR_MSG_MAPPING.get(error_key)
  198. log.error(error_msg)
  199. raise MindInsightException(error=error_code, message=error_msg)
  200. def validate_search_model_condition(schema, data):
  201. """
  202. Validate search model condition.
  203. Args:
  204. schema (Schema): Data schema.
  205. data (dict): Data to check schema.
  206. Raises:
  207. MindInsightException: If the parameters are invalid.
  208. """
  209. error = schema().validate(data)
  210. for (error_key, error_msgs) in error.items():
  211. if error_key in SEARCH_MODEL_ERROR_MAPPING.keys():
  212. error_code = SEARCH_MODEL_ERROR_MAPPING.get(error_key)
  213. error_msg = SEARCH_MODEL_ERROR_MSG_MAPPING.get(error_key)
  214. for err_msg in error_msgs:
  215. if 'operation' in err_msg.lower():
  216. error_msg = f'The parameter {error_key} is invalid. {err_msg}'
  217. break
  218. log.error(error_msg)
  219. raise MindInsightException(error=error_code, message=error_msg)
  220. def validate_summary_record(summary_record):
  221. """
  222. Validate summary_record.
  223. Args:
  224. summary_record (SummaryRecord): SummaryRecord is used to record
  225. the summary value, and summary_record is an instance of SummaryRecord,
  226. see mindspore.train.summary.SummaryRecord
  227. Raises:
  228. MindInsightException: If the parameters are invalid.
  229. """
  230. if not isinstance(summary_record, SummaryRecord):
  231. log.error("Invalid summary_record. It should be an instance "
  232. "of mindspore.train.summary.SummaryRecord.")
  233. raise MindInsightException(
  234. error=LineageErrors.PARAM_SUMMARY_RECORD_ERROR,
  235. message=LineageErrorMsg.PARAM_SUMMARY_RECORD_ERROR.value
  236. )
  237. def validate_raise_exception(raise_exception):
  238. """
  239. Validate raise_exception.
  240. Args:
  241. raise_exception (bool): decide raise exception or not,
  242. if True, raise exception; else, catch exception and continue.
  243. Raises:
  244. MindInsightException: If the parameters are invalid.
  245. """
  246. if not isinstance(raise_exception, bool):
  247. log.error("Invalid raise_exception. It should be True or False.")
  248. raise MindInsightException(
  249. error=LineageErrors.PARAM_RAISE_EXCEPTION_ERROR,
  250. message=LineageErrorMsg.PARAM_RAISE_EXCEPTION_ERROR.value
  251. )
  252. def validate_filter_key(keys):
  253. """
  254. Verify the keys of filtering is valid or not.
  255. Args:
  256. keys (list): The keys to get the relative lineage info.
  257. Raises:
  258. LineageParamTypeError: If keys is not list.
  259. LineageParamValueError: If the value of keys is invalid.
  260. """
  261. filter_keys = [
  262. 'metric', 'hyper_parameters', 'algorithm',
  263. 'train_dataset', 'model', 'valid_dataset',
  264. 'dataset_graph'
  265. ]
  266. if not isinstance(keys, list):
  267. log.error("Keys must be list.")
  268. raise LineageParamTypeError("Keys must be list.")
  269. for element in keys:
  270. if not isinstance(element, str):
  271. log.error("Element of keys must be str.")
  272. raise LineageParamTypeError("Element of keys must be str.")
  273. if not set(keys).issubset(filter_keys):
  274. err_msg = "Keys must be in {}.".format(filter_keys)
  275. log.error(err_msg)
  276. raise LineageParamValueError(err_msg)
  277. def validate_condition(search_condition):
  278. """
  279. Verify the param in search_condition is valid or not.
  280. Args:
  281. search_condition (dict): The search condition.
  282. Raises:
  283. LineageParamTypeError: If the type of the param in search_condition is invalid.
  284. LineageParamValueError: If the value of the param in search_condition is invalid.
  285. """
  286. if not isinstance(search_condition, dict):
  287. log.error("Invalid search_condition type, it should be dict.")
  288. raise LineageParamTypeError("Invalid search_condition type, "
  289. "it should be dict.")
  290. if "limit" in search_condition:
  291. if isinstance(search_condition.get("limit"), bool) \
  292. or not isinstance(search_condition.get("limit"), int):
  293. log.error("The limit must be int.")
  294. raise LineageParamTypeError("The limit must be int.")
  295. if "offset" in search_condition:
  296. if isinstance(search_condition.get("offset"), bool) \
  297. or not isinstance(search_condition.get("offset"), int):
  298. log.error("The offset must be int.")
  299. raise LineageParamTypeError("The offset must be int.")
  300. if "sorted_name" in search_condition:
  301. sorted_name = search_condition.get("sorted_name")
  302. err_msg = "The sorted_name must be in {} or start with " \
  303. "`metric/` or `user_defined/`.".format(list(FIELD_MAPPING.keys()))
  304. if not isinstance(sorted_name, str):
  305. log.error(err_msg)
  306. raise LineageParamValueError(err_msg)
  307. if not (sorted_name in FIELD_MAPPING
  308. or (sorted_name.startswith('metric/') and len(sorted_name) > len('metric/'))
  309. or (sorted_name.startswith('user_defined/') and len(sorted_name) > len('user_defined/'))
  310. or sorted_name in ['tag']):
  311. log.error(err_msg)
  312. raise LineageParamValueError(err_msg)
  313. sorted_type_param = ['ascending', 'descending', None]
  314. if "sorted_type" in search_condition:
  315. if "sorted_name" not in search_condition:
  316. log.error("The sorted_name have to exist when sorted_type exists.")
  317. raise LineageParamValueError("The sorted_name have to exist when sorted_type exists.")
  318. if search_condition.get("sorted_type") not in sorted_type_param:
  319. err_msg = "The sorted_type must be ascending or descending."
  320. log.error(err_msg)
  321. raise LineageParamValueError(err_msg)
  322. def validate_path(summary_path):
  323. """
  324. Verify the summary path is valid or not.
  325. Args:
  326. summary_path (str): The summary path which is a dir.
  327. Raises:
  328. LineageParamValueError: If the input param value is invalid.
  329. LineageDirNotExistError: If the summary path is invalid.
  330. """
  331. try:
  332. summary_path = safe_normalize_path(
  333. summary_path, "summary_path", None, check_absolute_path=True
  334. )
  335. except ValidationError:
  336. log.error("The summary path is invalid.")
  337. raise LineageParamValueError("The summary path is invalid.")
  338. if not os.path.isdir(summary_path):
  339. log.error("The summary path does not exist or is not a dir.")
  340. raise LineageDirNotExistError("The summary path does not exist or is not a dir.")
  341. return summary_path
  342. def validate_user_defined_info(user_defined_info):
  343. """
  344. Validate user defined info, delete the item if its key is in lineage.
  345. Args:
  346. user_defined_info (dict): The user defined info.
  347. Raises:
  348. LineageParamTypeError: If the type of parameters is invalid.
  349. LineageParamValueError: If user defined keys have been defined in lineage.
  350. """
  351. if not isinstance(user_defined_info, dict):
  352. log.error("Invalid user defined info. It should be a dict.")
  353. raise LineageParamTypeError("Invalid user defined info. It should be dict.")
  354. for key, value in user_defined_info.items():
  355. if not isinstance(key, str):
  356. error_msg = "Dict key type {} is not supported in user defined info." \
  357. "Only str is permitted now.".format(type(key))
  358. log.error(error_msg)
  359. raise LineageParamTypeError(error_msg)
  360. if not isinstance(value, (int, str, float)):
  361. error_msg = "Dict value type {} is not supported in user defined info." \
  362. "Only str, int and float are permitted now.".format(type(value))
  363. log.error(error_msg)
  364. raise LineageParamTypeError(error_msg)
  365. field_map = set(FIELD_MAPPING.keys())
  366. user_defined_keys = set(user_defined_info.keys())
  367. insertion = list(field_map & user_defined_keys)
  368. if insertion:
  369. for key in insertion:
  370. user_defined_info.pop(key)
  371. raise LineageParamValueError("There are some keys have defined in lineage. "
  372. "Duplicated key(s): %s. " % insertion)
  373. def validate_train_id(relative_path):
  374. """
  375. Check if train_id is valid.
  376. Args:
  377. relative_path (str): Train ID of a summary directory, e.g. './log1'.
  378. Returns:
  379. bool, if train id is valid, return True.
  380. """
  381. if not relative_path.startswith('./'):
  382. log.warning("The relative_path does not start with './'.")
  383. raise ParamValueError(
  384. "Summary dir should be relative path starting with './'."
  385. )
  386. if len(relative_path.split("/")) > 2:
  387. log.warning("The relative_path contains multiple '/'.")
  388. raise ParamValueError(
  389. "Summary dir should be relative path starting with './'."
  390. )
  391. def validate_range(name, value, min_value, max_value):
  392. """
  393. Check if value is in [min_value, max_value].
  394. Args:
  395. name (str): Value name.
  396. value (Union[int, float]): Value to be check.
  397. min_value (Union[int, float]): Min value.
  398. max_value (Union[int, float]): Max value.
  399. Raises:
  400. LineageParamValueError, if value type is invalid or value is out of [min_value, max_value].
  401. """
  402. if not isinstance(value, (int, float)):
  403. raise LineageParamValueError("Value should be int or float.")
  404. if value < min_value or value > max_value:
  405. raise LineageParamValueError("The %s should in [%d, %d]." % (name, min_value, max_value))
  406. def validate_added_info(added_info: dict):
  407. """
  408. Check if added_info is valid.
  409. Args:
  410. added_info (dict): The added info.
  411. Raises:
  412. bool, if added_info is valid, return True.
  413. """
  414. added_info_keys = ["tag", "remark"]
  415. if not set(added_info.keys()).issubset(added_info_keys):
  416. err_msg = "Keys of added_info must be in {}.".format(added_info_keys)
  417. raise LineageParamValueError(err_msg)
  418. for key, value in added_info.items():
  419. if key == "tag":
  420. if not isinstance(value, int):
  421. raise LineageParamValueError("'tag' must be int.")
  422. # tag should be in [0, 10].
  423. validate_range("tag", value, min_value=0, max_value=10)
  424. elif key == "remark":
  425. if not isinstance(value, str):
  426. raise LineageParamValueError("'remark' must be str.")
  427. # length of remark should be in [0, 128].
  428. validate_range("length of remark", len(value), min_value=0, max_value=128)
  429. def validate_str_by_regular(target, reg=None, flag=re.ASCII):
  430. """
  431. Validate string by given regular.
  432. Args:
  433. target: target string.
  434. reg: pattern.
  435. flag: pattern mode.
  436. Raises:
  437. LineageParamValueError, if string not match given pattern.
  438. Returns:
  439. bool, if target matches pattern, return True.
  440. """
  441. if reg is None:
  442. reg = _name_re
  443. if re.match(reg, target, flag) is None:
  444. raise LineageParamValueError("'{}' is illegal, it should be match "
  445. "regular'{}' by flags'{}'".format(target, reg, flag))
  446. return True