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 14 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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. """Validate the profiler parameters."""
  16. import os
  17. import sys
  18. from mindinsight.datavisual.utils.tools import to_int
  19. from mindinsight.profiler.common.exceptions.exceptions import ProfilerParamTypeErrorException, \
  20. ProfilerDeviceIdException, ProfilerOpTypeException, \
  21. ProfilerSortConditionException, ProfilerFilterConditionException, \
  22. ProfilerGroupConditionException, ProfilerParamValueErrorException
  23. from mindinsight.profiler.common.log import logger as log
  24. AICORE_TYPE_COL = ["op_type", "execution_time", "execution_frequency", "precent"]
  25. AICORE_DETAIL_COL = ["op_name", "op_type", "avg_execution_time", "subgraph", "full_op_name"]
  26. AICPU_COL = ["serial_number", "op_type", "total_time", "dispatch_time", "run_start",
  27. "run_end"]
  28. GPU_TYPE_COL = ["op_type", "type_occurrences", "total_time", "proportion", "avg_time"]
  29. GPU_ACTIVITY_COL = ["name", "type", "op_full_name", "stream_id",
  30. "block_dim", "grid_dim", "occurrences", "total_duration",
  31. "avg_duration", "max_duration", "min_duration"]
  32. GPU_DETAIL_COL = ["op_side", "op_type", "op_name", "op_full_name",
  33. "op_occurrences", "op_total_time", "op_avg_time",
  34. "proportion", "cuda_activity_cost_time", "cuda_activity_call_count"]
  35. MINDDATA_PIPELINE_COL = [
  36. 'op_id', 'op_type', 'num_workers', 'output_queue_average_size',
  37. 'output_queue_length', 'output_queue_usage_rate', 'sample_interval',
  38. 'parent_id'
  39. ]
  40. def validate_condition(search_condition):
  41. """
  42. Verify the param in search_condition is valid or not.
  43. Args:
  44. search_condition (dict): The search condition.
  45. Raises:
  46. ProfilerParamTypeErrorException: If the type of the param in search_condition is invalid.
  47. ProfilerDeviceIdException: If the device_id param in search_condition is invalid.
  48. ProfilerOpTypeException: If the op_type param in search_condition is invalid.
  49. ProfilerGroupConditionException: If the group_condition param in search_condition is invalid.
  50. ProfilerSortConditionException: If the sort_condition param in search_condition is invalid.
  51. ProfilerFilterConditionException: If the filter_condition param in search_condition is invalid.
  52. """
  53. if not isinstance(search_condition, dict):
  54. log.error("Invalid search_condition type, it should be dict.")
  55. raise ProfilerParamTypeErrorException(
  56. "Invalid search_condition type, it should be dict.")
  57. if "device_id" in search_condition:
  58. device_id = search_condition.get("device_id")
  59. if not isinstance(device_id, str):
  60. raise ProfilerDeviceIdException("Invalid device_id type, it should be str.")
  61. if "op_type" in search_condition:
  62. op_type = search_condition.get("op_type")
  63. if op_type == "aicpu":
  64. search_scope = AICPU_COL
  65. elif op_type == "aicore_type":
  66. search_scope = AICORE_TYPE_COL
  67. elif op_type == "aicore_detail":
  68. search_scope = AICORE_DETAIL_COL
  69. elif op_type == "gpu_op_type":
  70. search_scope = GPU_TYPE_COL
  71. elif op_type == "gpu_op_info":
  72. search_scope = GPU_DETAIL_COL
  73. elif op_type == "gpu_cuda_activity":
  74. search_scope = GPU_ACTIVITY_COL
  75. else:
  76. raise ProfilerOpTypeException(
  77. "The op_type must in ['aicpu', 'aicore_type', 'aicore_detail', "
  78. "'gpu_op_type', 'gpu_op_info', 'gpu_cuda_activity']")
  79. else:
  80. raise ProfilerOpTypeException(
  81. "The op_type must in ['aicpu', 'aicore_type', 'aicore_detail', "
  82. "'gpu_op_type', 'gpu_op_info', 'gpu_cuda_activity']")
  83. if "group_condition" in search_condition:
  84. validate_group_condition(search_condition)
  85. if "sort_condition" in search_condition:
  86. validate_sort_condition(search_condition, search_scope)
  87. if "filter_condition" in search_condition:
  88. validate_filter_condition(search_condition)
  89. def validate_group_condition(search_condition):
  90. """
  91. Verify the group_condition in search_condition is valid or not.
  92. Args:
  93. search_condition (dict): The search condition.
  94. Raises:
  95. ProfilerGroupConditionException: If the group_condition param in search_condition is invalid.
  96. """
  97. group_condition = search_condition.get("group_condition")
  98. if not isinstance(group_condition, dict):
  99. raise ProfilerGroupConditionException("The group condition must be dict.")
  100. if "limit" in group_condition:
  101. limit = group_condition.get("limit", 10)
  102. if isinstance(limit, bool) \
  103. or not isinstance(group_condition.get("limit"), int):
  104. log.error("The limit must be int.")
  105. raise ProfilerGroupConditionException("The limit must be int.")
  106. if limit < 1 or limit > 100:
  107. raise ProfilerGroupConditionException("The limit must in [1, 100].")
  108. if "offset" in group_condition:
  109. offset = group_condition.get("offset", 0)
  110. if isinstance(offset, bool) \
  111. or not isinstance(group_condition.get("offset"), int):
  112. log.error("The offset must be int.")
  113. raise ProfilerGroupConditionException("The offset must be int.")
  114. if offset < 0:
  115. raise ProfilerGroupConditionException("The offset must ge 0.")
  116. if offset > 1000000:
  117. raise ProfilerGroupConditionException("The offset must le 1000000.")
  118. def validate_sort_condition(search_condition, search_scope):
  119. """
  120. Verify the sort_condition in search_condition is valid or not.
  121. Args:
  122. search_condition (dict): The search condition.
  123. search_scope (list): The search scope.
  124. Raises:
  125. ProfilerSortConditionException: If the sort_condition param in search_condition is invalid.
  126. """
  127. sort_condition = search_condition.get("sort_condition")
  128. if not isinstance(sort_condition, dict):
  129. raise ProfilerSortConditionException("The sort condition must be dict.")
  130. if "name" in sort_condition:
  131. sorted_name = sort_condition.get("name", "")
  132. err_msg = "The sorted_name must be in {}".format(search_scope)
  133. if not isinstance(sorted_name, str):
  134. log.error("Wrong sorted name type.")
  135. raise ProfilerSortConditionException("Wrong sorted name type.")
  136. if sorted_name not in search_scope:
  137. log.error(err_msg)
  138. raise ProfilerSortConditionException(err_msg)
  139. if "type" in sort_condition:
  140. sorted_type_param = ['ascending', 'descending']
  141. sorted_type = sort_condition.get("type")
  142. if sorted_type and sorted_type not in sorted_type_param:
  143. err_msg = "The sorted type must be ascending or descending."
  144. log.error(err_msg)
  145. raise ProfilerSortConditionException(err_msg)
  146. def validate_op_filter_condition(op_condition, value_type=str, value_type_msg='str'):
  147. """
  148. Verify the op_condition in filter_condition is valid or not.
  149. Args:
  150. op_condition (dict): The op_condition in search_condition.
  151. value_type (type): The value type. Default: str.
  152. value_type_msg (str): The value type message. Default: 'str'.
  153. Raises:
  154. ProfilerFilterConditionException: If the filter_condition param in search_condition is invalid.
  155. """
  156. filter_key = ["in", "not_in", "partial_match_str_in"]
  157. if not isinstance(op_condition, dict):
  158. raise ProfilerFilterConditionException("The filter condition value must be dict.")
  159. for key, value in op_condition.items():
  160. if not isinstance(key, str):
  161. raise ProfilerFilterConditionException("The filter key must be str")
  162. if not isinstance(value, list):
  163. raise ProfilerFilterConditionException("The filter value must be list")
  164. if key not in filter_key:
  165. raise ProfilerFilterConditionException("The filter key must in {}.".format(filter_key))
  166. for item in value:
  167. if not isinstance(item, value_type):
  168. raise ProfilerFilterConditionException(
  169. "The item in filter value must be {}.".format(value_type_msg)
  170. )
  171. def validate_filter_condition(search_condition):
  172. """
  173. Verify the filter_condition in search_condition is valid or not.
  174. Args:
  175. search_condition (dict): The search condition.
  176. Raises:
  177. ProfilerFilterConditionException: If the filter_condition param in search_condition is invalid.
  178. """
  179. filter_condition = search_condition.get("filter_condition")
  180. if not isinstance(filter_condition, dict):
  181. raise ProfilerFilterConditionException("The filter condition must be dict.")
  182. if filter_condition:
  183. if "op_type" in filter_condition:
  184. op_type_condition = filter_condition.get("op_type")
  185. validate_op_filter_condition(op_type_condition)
  186. if "op_name" in filter_condition:
  187. op_name_condition = filter_condition.get("op_name")
  188. validate_op_filter_condition(op_name_condition)
  189. def validate_and_set_job_id_env(job_id_env):
  190. """
  191. Validate the job id and set it in environment.
  192. Args:
  193. job_id_env (str): The id that to be set in environment parameter `JOB_ID`.
  194. Returns:
  195. int, the valid job id env.
  196. """
  197. if job_id_env is None:
  198. return job_id_env
  199. # get job_id_env in int type
  200. valid_id = to_int(job_id_env, 'job_id_env')
  201. # check the range of valid_id
  202. if valid_id and 255 < valid_id < sys.maxsize:
  203. os.environ['JOB_ID'] = job_id_env
  204. else:
  205. log.warning("Invalid job_id_env %s. The value should be int and between 255 and %s. Use"
  206. "default job id env instead.",
  207. job_id_env, sys.maxsize)
  208. return valid_id
  209. def validate_ui_proc(proc_name):
  210. """
  211. Validate proc name in restful request.
  212. Args:
  213. proc_name (str): The proc name to query. Acceptable value is in
  214. [`iteration_interval`, `fp_and_bp`, `tail`].
  215. Raises:
  216. ProfilerParamValueErrorException: If the proc_name is invalid.
  217. """
  218. accept_names = ['iteration_interval', 'fp_and_bp', 'tail']
  219. if proc_name not in accept_names:
  220. log.error("Invalid proc_name. The proc_name for restful api is in %s", accept_names)
  221. raise ProfilerParamValueErrorException(f'proc_name should be in {accept_names}.')
  222. def validate_minddata_pipeline_condition(condition):
  223. """
  224. Verify the minddata pipeline search condition is valid or not.
  225. Args:
  226. condition (dict): The minddata pipeline search condition.
  227. Raises:
  228. ProfilerParamTypeErrorException: If the type of the search condition is
  229. invalid.
  230. ProfilerDeviceIdException: If the device_id param in the search
  231. condition is invalid.
  232. ProfilerGroupConditionException: If the group_condition param in the
  233. search condition is invalid.
  234. ProfilerSortConditionException: If the sort_condition param in the
  235. search condition is invalid.
  236. ProfilerFilterConditionException: If the filter_condition param in the
  237. search condition is invalid.
  238. """
  239. if not isinstance(condition, dict):
  240. log.error("Invalid condition type, it should be dict.")
  241. raise ProfilerParamTypeErrorException(
  242. "Invalid condition type, it should be dict."
  243. )
  244. if "device_id" in condition:
  245. device_id = condition.get("device_id")
  246. if not isinstance(device_id, str):
  247. raise ProfilerDeviceIdException(
  248. "Invalid device_id type, it should be str."
  249. )
  250. if "group_condition" in condition:
  251. validate_group_condition(condition)
  252. if "sort_condition" in condition:
  253. validate_sort_condition(condition, MINDDATA_PIPELINE_COL)
  254. if "filter_condition" in condition:
  255. filter_condition = condition.get('filter_condition')
  256. if not isinstance(filter_condition, dict):
  257. raise ProfilerFilterConditionException(
  258. "The filter condition must be dict."
  259. )
  260. for key, value in filter_condition.items():
  261. if key == 'op_id':
  262. validate_op_filter_condition(
  263. value, value_type=int, value_type_msg='int'
  264. )
  265. elif key == 'op_type':
  266. validate_op_filter_condition(value)
  267. elif key == 'is_display_op_detail':
  268. if not isinstance(value, bool):
  269. raise ProfilerFilterConditionException(
  270. "The condition must be bool."
  271. )
  272. else:
  273. raise ProfilerFilterConditionException(
  274. "The key {} of filter_condition is not support.".format(key)
  275. )