kemidocs.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. # tool to generate the modules.md content
  2. #
  3. import os, json, sys, time, fnmatch, re, importlib
  4. class ModuleDocGenerator(object):
  5. PATH_GENERATED_MARKDOWN = "../docs/modules.md"
  6. PATH_MODULES_DOCS = "../docs/modules/"
  7. # Contains the output until it should be written to disk
  8. markdown_string = ""
  9. def execute(self, data):
  10. # Validate that we got some methods back. 155 is an arbitrary large number.
  11. if len(data) < 1:
  12. print("ERR: Invalid data")
  13. exit()
  14. functions_parsed = self.parse_function_list(data)
  15. self.output_markdown(functions_parsed)
  16. print ("Markdown doc created successfully at " + self.PATH_GENERATED_MARKDOWN)
  17. def parse_function_list(self, functions):
  18. data = {}
  19. for elem in functions:
  20. module = elem["module"]
  21. # TODO: What about the hdr, pv, x sub-module?
  22. if module == "":
  23. module = "core"
  24. if module not in data:
  25. data[module] = []
  26. data[module].append({"name": elem["name"], "return": elem["ret"], "params": elem["params"]})
  27. return data
  28. def output_markdown(self, data):
  29. self.markdown_header()
  30. for key in sorted(data):
  31. methods = data[key]
  32. # Sort the functions by name alphabetically
  33. methods = sorted(methods, key = lambda k: k['name'])
  34. self.markdown_section_heading(key)
  35. self.markdown_section_content(key, methods)
  36. self.markdown_write()
  37. return True
  38. def markdown_header(self):
  39. self.markdown_string += self.read_file_to_string("header.md")
  40. return True
  41. def markdown_section_heading(self, heading):
  42. self.markdown_string += "## " + heading + " ##\n\n"
  43. self.markdown_string += self.read_file_to_string(heading + "/" + heading + ".header.md")
  44. return True
  45. def markdown_section_content(self, module, methods):
  46. if module == "core":
  47. module_prefix = ""
  48. else:
  49. module_prefix = module + "."
  50. for value in methods:
  51. self.markdown_string += "#### KSR." + module_prefix + value["name"] + "() ####\n\n"
  52. # Sanitize the return values
  53. if value["return"] == "none":
  54. return_value = "void"
  55. else:
  56. return_value = value["return"]
  57. # Sanitize the parameter values
  58. if value["params"] == "none":
  59. params_value = ""
  60. else:
  61. params_value = value["params"]
  62. # Generate the output string for the markdown page
  63. self.markdown_string += "<a target='_blank' href='/docs/modules/devel/modules/" + module + ".html#" \
  64. + module + ".f." + value["name"] + "'> `" + return_value + " " + value["name"] \
  65. + "(" + params_value + ")` </a>\n\n"
  66. func_doc = self.read_file_to_string(module + "/" + module + "." + value["name"] + ".md").strip()
  67. if len(func_doc)>0:
  68. self.markdown_string += func_doc + "\n\n"
  69. return True
  70. def markdown_write(self):
  71. f = open(self.PATH_GENERATED_MARKDOWN, "w")
  72. f.write(self.markdown_string)
  73. f.close()
  74. return True
  75. def read_file_to_string(self, filename):
  76. path = self.PATH_MODULES_DOCS + filename
  77. if os.path.isfile(path):
  78. with open(path, 'r') as myfile:
  79. return myfile.read() + "\n"
  80. return ""
  81. class KemiFileExportParser(object):
  82. # These functions are created by a macro so makes the parsing somewhat tricky,
  83. # for now they are statically defined
  84. macro_functions = {
  85. "t_set_auto_inv_100": "int state",
  86. "t_set_disable_6xx": "int state",
  87. "t_set_disable_failover": "int state",
  88. "t_set_no_e2e_cancel_reason": "int state",
  89. "t_set_disable_internal_reply": "int state"
  90. }
  91. # These files export the KEMI functions in a special way so we map them manually
  92. # TODO: Discuss with @miconda if core/HDR/pv/x should be added as well or not
  93. special_exports = [
  94. #{"filename": "kemi.c", "export": "_sr_kemi_core", "folder": "/core/"},
  95. #{"filename": "kemi.c", "export": "_sr_kemi_hdr", "folder": "/core/"},
  96. #{"filename": "app_lua_mod.c", "export": "sr_kemi_app_lua_rpc_exports", "folder": "/modules/app_lua/"}
  97. ]
  98. def generate_kemi_export_list(self, source_path):
  99. files = self.list_c_files_in_directory(source_path)
  100. lists = []
  101. for file in files:
  102. with open(file, 'r', encoding='utf-8', errors='ignore') as f:
  103. lines = f.readlines()
  104. export_name = self.find_c_file_kemi_export(file, lines)
  105. if export_name:
  106. export_functions = self.extract_c_file_kemi_export_lines(file, lines, export_name)
  107. lists = lists + export_functions
  108. print ("Found ", len(export_functions), "functions", "Total:", len(lists))
  109. # Handle some special files separately
  110. for elem in self.special_exports:
  111. file = source_path + elem["folder"] + elem["filename"]
  112. with open(file) as f:
  113. lines = f.readlines()
  114. lists = lists + self.extract_c_file_kemi_export_lines(file, lines, elem["export"])
  115. return lists
  116. def find_c_file_kemi_export(self, filename, lines):
  117. param = None
  118. for line in lines:
  119. if line.find("sr_kemi_modules_add") >= 0:
  120. line = line.lstrip(" ")
  121. line = line.lstrip("\t")
  122. if line.find("sr_kemi_modules_add") == 0:
  123. param = line[line.find("(") + 1:line.find(")")]
  124. print ("INFO: ---- Found export", filename, param)
  125. break
  126. else:
  127. if line != "int sr_kemi_modules_add(sr_kemi_t *klist)\n":
  128. print ("ERR: Possible error at line: ", filename, line)
  129. exit()
  130. return param
  131. def extract_c_file_kemi_export_lines(self, filename, lines, export_name):
  132. list_functions = []
  133. find_start = True
  134. for line in lines:
  135. if find_start and line.find("static sr_kemi_t " + export_name + "[]") >= 0:
  136. find_start = False
  137. elif not find_start:
  138. if line.find("};") >= 0:
  139. break
  140. line = line.lstrip(" \t")
  141. line = line.rstrip()
  142. list_functions.append(line)
  143. if len(list_functions) < 1:
  144. print ("ERR: Couldn't parse file for exported functions: ", export_name)
  145. exit()
  146. parsed_list = self.parse_kemi_export_c_lines(filename, list_functions)
  147. return parsed_list
  148. def parse_kemi_export_c_lines(self, filename, lines):
  149. elements = []
  150. function_lines = []
  151. temp_function = ""
  152. # We look for str_init which would be the start of each exported function
  153. for line in lines:
  154. if line.find("str_init") >= 0:
  155. if temp_function != "":
  156. function_lines.append(temp_function)
  157. temp_function = ""
  158. temp_function += line
  159. if temp_function != "":
  160. function_lines.append(temp_function)
  161. # Now we parse each exported function to extract its declaration
  162. for func in function_lines:
  163. function_lines_split = func.split(",{")
  164. if len(function_lines_split) < 2:
  165. print ("ERR: Incorrect function line", func)
  166. exit()
  167. declarations = function_lines_split[0].split(",")
  168. params = function_lines_split[1]
  169. # Extract the content from the definitions
  170. val_module = declarations[0]
  171. val_module = val_module[val_module.find('("') + 2:val_module.find('")')]
  172. val_function = declarations[1]
  173. val_function = val_function[val_function.find('("') + 2:val_function.find('")')]
  174. if declarations[2] == "SR_KEMIP_INT":
  175. val_return = "int"
  176. elif declarations[2] == "SR_KEMIP_STR":
  177. val_return = "string"
  178. elif declarations[2] == "SR_KEMIP_NONE":
  179. val_return = "void"
  180. elif declarations[2] == "SR_KEMIP_BOOL":
  181. val_return = "bool"
  182. elif declarations[2] == "SR_KEMIP_XVAL":
  183. val_return = "xval"
  184. else:
  185. print("ERR: Invalid return value", declarations[2], func)
  186. exit()
  187. val_c_function = declarations[3].strip()
  188. # Count how many parameters the KEMI C function expects
  189. val_params = []
  190. itr = 0
  191. for val in params.rstrip("},").split(","):
  192. itr += 1
  193. # KEMI function has a maximum of 6 params
  194. if itr > 6:
  195. break
  196. pm = val.strip()
  197. if pm == "SR_KEMIP_INT":
  198. val_params.append("int")
  199. elif pm == "SR_KEMIP_STR":
  200. val_params.append("str")
  201. elif pm == "SR_KEMIP_NONE":
  202. continue
  203. else:
  204. print("Invalid return value", declarations[2], func)
  205. exit()
  206. if itr != 6:
  207. print("ERR: Couldn't iterate the params: ", params)
  208. exit()
  209. param_string = self.find_c_function_params(filename, val_c_function, val_return)
  210. param_string = self.prettify_params_list(val_function, param_string, val_params)
  211. elements.append({"module": val_module, "name": val_function, "ret": val_return, "params": param_string})
  212. return elements
  213. def prettify_params_list(self, function_name, function_declaration, kemi_types):
  214. # Validate the quantity and types of declaration vs export
  215. if function_declaration == "" and len(kemi_types) == 0:
  216. return ""
  217. params = function_declaration.split(",")
  218. if params[0].find("sip_msg_t") >= 0 or params[0].find("struct sip_msg") >= 0:
  219. params.pop(0)
  220. if len(params) != len(kemi_types):
  221. print("ERR: Mismatching quantity of params. Declaration for", function_name, ":", function_declaration, "KEMI:", kemi_types)
  222. exit()
  223. for declared, type in zip(params, kemi_types):
  224. declared = declared.replace("*", "")
  225. declared = declared.strip().split(" ")[0]
  226. if declared != type:
  227. print("ERR: Mismatching type of params for", function_name, ":", function_declaration, " | ", kemi_types, " | Declared: ", declared, " Type: ", type)
  228. exit()
  229. param_string = ""
  230. for param in params:
  231. param = param.strip()
  232. param = param.replace("*", "")
  233. if param[:3] == "str":
  234. temp = param.split(" ")
  235. param = "str" + ' "' + temp[1] + '"'
  236. param_string += param + ", "
  237. # Clean up the presentation of the params
  238. param_string = param_string.rstrip(", ")
  239. return param_string
  240. def find_c_function_params(self, filename, function_name, return_type):
  241. # First we try with the same file to find the declaration
  242. param_string = self.search_file_for_function_declaration(filename, function_name, return_type)
  243. # If we couldn't find it, let's try all files in the same folder as the first file
  244. if param_string:
  245. return param_string
  246. else:
  247. files = self.list_c_files_in_directory(os.path.dirname(filename))
  248. for file in files:
  249. param_string = self.search_file_for_function_declaration(file, function_name, return_type)
  250. if param_string:
  251. return param_string
  252. if function_name in self.macro_functions:
  253. return self.macro_functions[function_name]
  254. print("ERR: Couldn't find the function declaration", filename, function_name, return_type)
  255. exit()
  256. def search_file_for_function_declaration(self, filename, function_name, return_type):
  257. # print "Searching file", filename, "for", function_name
  258. with open(filename, 'r', encoding='utf-8', errors='ignore') as f:
  259. lines = f.readlines()
  260. param_string = None
  261. found = False
  262. temp_string = ""
  263. return_match = return_type
  264. # KEMI has some magic where most functions actually return INTs but KEMI maps them to void/bool
  265. if return_type == "void" or return_type == "bool":
  266. return_match = "int"
  267. if return_type == "xval":
  268. return_match = "sr_kemi_xval_t([ \t])*\*"
  269. # Look for declarations in format: static? return_type function_name(
  270. r = re.compile("^(?:static )?" + return_match + "[ \t]*(" + function_name + ")[ \t]*\(")
  271. for line in lines:
  272. m = r.match(line)
  273. if m:
  274. found = True
  275. if found:
  276. temp_string += line
  277. if line.find("{") >= 0:
  278. param_string = temp_string[temp_string.find('(') + 1:temp_string.find(')')]
  279. break
  280. return param_string
  281. def list_c_files_in_directory(self, path):
  282. matches = []
  283. for root, dirnames, filenames in os.walk(path):
  284. for filename in fnmatch.filter(filenames, '*.c'):
  285. matches.append(os.path.join(root, filename))
  286. return matches
  287. if __name__ == "__main__":
  288. try:
  289. if not os.path.isdir(sys.argv[1]):
  290. raise Exception('Not a valid directory')
  291. except:
  292. print("Please provide the path to the Kamailio src folder as the first argument")
  293. exit()
  294. print("Parsing the source")
  295. parser = KemiFileExportParser()
  296. data = parser.generate_kemi_export_list(sys.argv[1].rstrip("/"))
  297. fgen = ModuleDocGenerator()
  298. fgen.execute(data)
  299. print("Done")