api.py 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249
  1. #
  2. # Metrix++, Copyright 2009-2013, Metrix++ Project
  3. # Link: http://metrixplusplus.sourceforge.net
  4. #
  5. # This file is a part of Metrix++ Tool.
  6. #
  7. # Metrix++ is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, version 3 of the License.
  10. #
  11. # Metrix++ is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with Metrix++. If not, see <http://www.gnu.org/licenses/>.
  18. #
  19. import os.path
  20. import sys
  21. import mpp.internal.dbwrap
  22. import mpp.internal.api_impl
  23. class InterfaceNotImplemented(Exception):
  24. def __init__(self, obj):
  25. Exception.__init__(self, "Method '"
  26. + sys._getframe(1).f_code.co_name
  27. + "' has not been implemented for "
  28. + str(obj.__class__))
  29. class IConfigurable(object):
  30. def configure(self, options):
  31. raise InterfaceNotImplemented(self)
  32. def declare_configuration(self, optparser):
  33. raise InterfaceNotImplemented(self)
  34. class IRunable(object):
  35. def run(self, args):
  36. raise InterfaceNotImplemented(self)
  37. class IParser(object):
  38. def process(self, parent, data, is_updated):
  39. raise InterfaceNotImplemented(self)
  40. class ICode(object):
  41. pass
  42. class CallbackNotImplemented(Exception):
  43. def __init__(self, obj, callback_name):
  44. Exception.__init__(self, "Callback '"
  45. + callback_name
  46. + "' has not been implemented for "
  47. + str(obj.__class__))
  48. class Child(object):
  49. def notify(self, parent, callback_name, *args):
  50. if hasattr(self, callback_name) == False:
  51. raise CallbackNotImplemented(self, callback_name)
  52. self.__getattribute__(callback_name)(parent, *args)
  53. def subscribe_by_parents_name(self, parent_name, callback_name='callback'):
  54. self.get_plugin(parent_name).subscribe(self, callback_name)
  55. def subscribe_by_parents_names(self, parent_names, callback_name='callback'):
  56. for parent_name in parent_names:
  57. self.get_plugin(parent_name).subscribe(self, callback_name)
  58. def subscribe_by_parents_interface(self, interface, callback_name='callback'):
  59. for plugin in self._get_plugin_loader().iterate_plugins():
  60. if isinstance(plugin, interface):
  61. plugin.subscribe(self, callback_name)
  62. class Parent(object):
  63. def init_Parent(self):
  64. if hasattr(self, 'children') == False:
  65. self.children = []
  66. def subscribe(self, obj, callback_name):
  67. self.init_Parent()
  68. if (isinstance(obj, Child) == False):
  69. raise TypeError()
  70. self.children.append((obj,callback_name))
  71. def unsubscribe(self, obj, callback_name):
  72. self.init_Parent()
  73. self.children.remove((obj, callback_name))
  74. def notify_children(self, *args):
  75. self.init_Parent()
  76. for child in self.children:
  77. child[0].notify(self, child[1], *args)
  78. def iterate_children(self):
  79. self.init_Parent()
  80. for child in self.children:
  81. yield child
  82. ##############################################################################
  83. #
  84. #
  85. #
  86. ##############################################################################
  87. class Data(object):
  88. def __init__(self):
  89. self.data = {}
  90. def get_data(self, namespace, field):
  91. if namespace not in self.data.keys():
  92. return None
  93. if field not in self.data[namespace].keys():
  94. return None
  95. return self.data[namespace][field]
  96. def set_data(self, namespace, field, value):
  97. if namespace not in self.data:
  98. self.data[namespace] = {}
  99. self.data[namespace][field] = value
  100. def iterate_namespaces(self):
  101. for namespace in self.data.keys():
  102. yield namespace
  103. def iterate_fields(self, namespace):
  104. for field in self.data[namespace].keys():
  105. yield (field, self.data[namespace][field])
  106. def get_data_tree(self, namespaces=None):
  107. return self.data
  108. def __repr__(self):
  109. return object.__repr__(self) + " with data " + self.data.__repr__()
  110. class LoadableData(Data):
  111. def __init__(self, loader, file_id, region_id):
  112. Data.__init__(self)
  113. self.loader = loader
  114. self.file_id = file_id
  115. self.region_id = region_id
  116. self.loaded_namespaces = []
  117. self.changed_namespaces = []
  118. def load_namespace(self, namespace):
  119. namespace_obj = self.loader.get_namespace(namespace)
  120. if namespace_obj == None:
  121. return
  122. regions_supported = namespace_obj.are_regions_supported()
  123. if ((self.region_id == None and regions_supported == True) or
  124. (self.region_id != None and regions_supported == False)):
  125. return
  126. row = self.loader.db.get_row(namespace, self.file_id, self.region_id)
  127. if row == None:
  128. return
  129. for column_name in row.keys():
  130. try:
  131. packager = namespace_obj._get_field_packager(column_name)
  132. except mpp.internal.api_impl.PackagerError:
  133. continue
  134. if row[column_name] == None:
  135. continue
  136. Data.set_data(self, namespace, column_name, packager.unpack(row[column_name]))
  137. def set_data(self, namespace, field, value):
  138. if namespace not in self.changed_namespaces:
  139. self.changed_namespaces.append(namespace)
  140. return Data.set_data(self, namespace, field, value)
  141. def get_data(self, namespace, field):
  142. if namespace not in self.loaded_namespaces:
  143. self.loaded_namespaces.append(namespace)
  144. self.load_namespace(namespace)
  145. return Data.get_data(self, namespace, field)
  146. def is_namespace_updated(self, namespace):
  147. return namespace in self.changed_namespaces
  148. def is_namespace_loaded(self, namespace):
  149. return namespace in self.loaded_namespaces
  150. def get_data_tree(self, namespaces=None):
  151. if namespaces == None:
  152. namespaces = self.loader.iterate_namespace_names()
  153. for each in namespaces:
  154. self.load_namespace(each)
  155. return Data.get_data_tree(self)
  156. class Region(LoadableData):
  157. class T(object):
  158. NONE = 0x00
  159. GLOBAL = 0x01
  160. CLASS = 0x02
  161. STRUCT = 0x04
  162. NAMESPACE = 0x08
  163. FUNCTION = 0x10
  164. INTERFACE = 0x20
  165. ANY = 0xFF
  166. def to_str(self, group):
  167. if group == self.NONE:
  168. return "none"
  169. elif group == self.GLOBAL:
  170. return "global"
  171. elif group == self.CLASS:
  172. return "class"
  173. elif group == self.STRUCT:
  174. return "struct"
  175. elif group == self.NAMESPACE:
  176. return "namespace"
  177. elif group == self.FUNCTION:
  178. return "function"
  179. elif group == self.INTERFACE:
  180. return "interface"
  181. else:
  182. assert(False)
  183. def __init__(self, loader, file_id, region_id, region_name, offset_begin, offset_end, line_begin, line_end, cursor_line, group, checksum):
  184. LoadableData.__init__(self, loader, file_id, region_id)
  185. self.name = region_name
  186. self.begin = offset_begin
  187. self.end = offset_end
  188. self.line_begin = line_begin
  189. self.line_end = line_end
  190. self.cursor = cursor_line
  191. self.group = group
  192. self.checksum = checksum
  193. self.children = []
  194. def get_id(self):
  195. return self.region_id
  196. def get_name(self):
  197. return self.name
  198. def get_offset_begin(self):
  199. return self.begin
  200. def get_offset_end(self):
  201. return self.end
  202. def get_line_begin(self):
  203. return self.line_begin
  204. def get_line_end(self):
  205. return self.line_end
  206. def get_cursor(self):
  207. return self.cursor
  208. def get_type(self):
  209. return self.group
  210. def get_checksum(self):
  211. return self.checksum
  212. def iterate_subregion_ids(self):
  213. return self.children
  214. def _register_subregion_id(self, child_id):
  215. self.children.append(child_id)
  216. class Marker(object):
  217. class T(object):
  218. NONE = 0x00
  219. COMMENT = 0x01
  220. STRING = 0x02
  221. PREPROCESSOR = 0x04
  222. CODE = 0x08
  223. ANY = 0xFF
  224. def to_str(self, group):
  225. if group == self.NONE:
  226. return "none"
  227. elif group == self.COMMENT:
  228. return "comment"
  229. elif group == self.STRING:
  230. return "string"
  231. elif group == self.PREPROCESSOR:
  232. return "preprocessor"
  233. elif group == self.CODE:
  234. return "code"
  235. else:
  236. assert(False)
  237. def __init__(self, offset_begin, offset_end, group):
  238. self.begin = offset_begin
  239. self.end = offset_end
  240. self.group = group
  241. def get_offset_begin(self):
  242. return self.begin
  243. def get_offset_end(self):
  244. return self.end
  245. def get_type(self):
  246. return self.group
  247. class FileData(LoadableData):
  248. def __init__(self, loader, path, file_id, checksum, content):
  249. LoadableData.__init__(self, loader, file_id, None)
  250. self.path = path
  251. self.checksum = checksum
  252. self.content = content
  253. self.regions = None
  254. self.markers = None
  255. self.loader = loader
  256. self.loading_tmp = []
  257. def get_id(self):
  258. return self.file_id
  259. def get_path(self):
  260. return self.path
  261. def get_checksum(self):
  262. return self.checksum
  263. def get_content(self):
  264. return self.content
  265. def _internal_append_region(self, region):
  266. # here we apply some magic - we rely on special ordering of coming regions,
  267. # which is supported by code parsers
  268. prev_id = None
  269. while True:
  270. if len(self.loading_tmp) == 0:
  271. break
  272. prev_id = self.loading_tmp.pop()
  273. if self.get_region(prev_id).get_offset_end() > region.get_offset_begin():
  274. self.loading_tmp.append(prev_id) # return back
  275. break
  276. self.loading_tmp.append(region.get_id())
  277. if prev_id != None:
  278. self.get_region(prev_id)._register_subregion_id(region.get_id())
  279. self.regions.append(region)
  280. def load_regions(self):
  281. if self.regions == None:
  282. self.regions = []
  283. for each in self.loader.db.iterate_regions(self.get_id()):
  284. self._internal_append_region(Region(self.loader,
  285. self.get_id(),
  286. each.region_id,
  287. each.name,
  288. each.begin,
  289. each.end,
  290. each.line_begin,
  291. each.line_end,
  292. each.cursor,
  293. each.group,
  294. each.checksum))
  295. assert(len(self.regions) == each.region_id)
  296. def add_region(self, region_name, offset_begin, offset_end, line_begin, line_end, cursor_line, group, checksum):
  297. if self.regions == None:
  298. # # do not load regions and markers in time of collection
  299. # if region is added first by parser, set markers to empty list as well
  300. # because if there are no markers in a file, it forces loading of markers
  301. # during iterate_markers call
  302. self.regions = []
  303. self.markers = []
  304. new_id = len(self.regions) + 1
  305. self._internal_append_region(Region(self.loader, self.get_id(), new_id, region_name, offset_begin, offset_end, line_begin, line_end, cursor_line, group, checksum))
  306. self.loader.db.create_region(self.file_id, new_id, region_name, offset_begin, offset_end, line_begin, line_end, cursor_line, group, checksum)
  307. return new_id
  308. def get_region(self, region_id):
  309. self.load_regions()
  310. return self.regions[region_id - 1]
  311. def iterate_regions(self, filter_group = Region.T.ANY, region_id = None):
  312. self.load_regions()
  313. if region_id == None:
  314. for each in self.regions:
  315. if each.group & filter_group:
  316. yield each
  317. else:
  318. for sub_id in self.get_region(region_id).iterate_subregion_ids():
  319. each = self.get_region(sub_id)
  320. if each.group & filter_group:
  321. yield each
  322. def are_regions_loaded(self):
  323. return self.regions != None
  324. def load_markers(self):
  325. if self.markers == None:
  326. # TODO add assert in case of an attempt to load data during collection
  327. assert(False) # TODO not used in post-processing tools for while, need to be fixed
  328. self.markers = []
  329. for each in self.loader.db.iterate_markers(self.get_id()):
  330. self.markers.append(Marker(each.begin, each.end, each.group))
  331. def add_marker(self, offset_begin, offset_end, group):
  332. if self.markers == None:
  333. # # do not load regions and markers in time of collection
  334. # if marker is added first by parser, set regions to empty list as well
  335. # because if there are no regions in a file, it forces loading of regions
  336. # during iterate_regions call
  337. self.regions = []
  338. self.markers = []
  339. self.markers.append(Marker(offset_begin, offset_end, group))
  340. # TODO drop collecting markers, it is faster to double parse
  341. # it is not the same with regions, it is faster to load regions
  342. # on iterative re-run
  343. #self.loader.db.create_marker(self.file_id, offset_begin, offset_end, group)
  344. def iterate_markers(self, filter_group = Marker.T.ANY,
  345. region_id = None, exclude_children = True, merge = False):
  346. self.load_markers()
  347. # merged markers
  348. if merge == True:
  349. next_marker = None
  350. for marker in self.iterate_markers(filter_group, region_id, exclude_children, merge = False):
  351. if next_marker != None:
  352. if next_marker.get_offset_end() == marker.get_offset_begin():
  353. # sequential markers
  354. next_marker = Marker(next_marker.get_offset_begin(),
  355. marker.get_offset_end(),
  356. next_marker.get_type() | marker.get_type())
  357. else:
  358. yield next_marker
  359. next_marker = None
  360. if next_marker == None:
  361. next_marker = Marker(marker.get_offset_begin(),
  362. marker.get_offset_end(),
  363. marker.get_type())
  364. if next_marker != None:
  365. yield next_marker
  366. # all markers per file
  367. elif region_id == None:
  368. next_code_marker_start = 0
  369. for marker in self.markers:
  370. if Marker.T.CODE & filter_group and next_code_marker_start < marker.get_offset_begin():
  371. yield Marker(next_code_marker_start, marker.get_offset_begin(), Marker.T.CODE)
  372. if marker.group & filter_group:
  373. yield marker
  374. next_code_marker_start = marker.get_offset_end()
  375. if Marker.T.CODE & filter_group and next_code_marker_start < len(self.get_content()):
  376. yield Marker(next_code_marker_start, len(self.get_content()), Marker.T.CODE)
  377. # markers per region
  378. else:
  379. region = self.get_region(region_id)
  380. if region != None:
  381. # code parsers and database know about non-code markers
  382. # clients want to iterate code as markers as well
  383. # so, we embed code markers in run-time
  384. class CodeMarker(Marker):
  385. pass
  386. # cache markers for all regions if it does not exist
  387. if hasattr(region, '_markers_list') == False:
  388. # subroutine to populate _markers_list attribute
  389. # _markers_list does include code markers
  390. def cache_markers_list_rec(data, region_id, marker_start_ind, next_code_marker_start):
  391. region = data.get_region(region_id)
  392. region._markers_list = []
  393. region._first_marker_ind = marker_start_ind
  394. #next_code_marker_start = region.get_offset_begin()
  395. for sub_id in region.iterate_subregion_ids():
  396. subregion = data.get_region(sub_id)
  397. # cache all markers before the subregion
  398. while len(data.markers) > marker_start_ind and \
  399. subregion.get_offset_begin() > data.markers[marker_start_ind].get_offset_begin():
  400. if next_code_marker_start < data.markers[marker_start_ind].get_offset_begin():
  401. # append code markers coming before non-code marker
  402. region._markers_list.append(CodeMarker(next_code_marker_start,
  403. data.markers[marker_start_ind].get_offset_begin(),
  404. Marker.T.CODE))
  405. next_code_marker_start = data.markers[marker_start_ind].get_offset_end()
  406. region._markers_list.append(marker_start_ind)
  407. marker_start_ind += 1
  408. # cache all code markers before the subregion but after the last marker
  409. if next_code_marker_start < subregion.get_offset_begin():
  410. region._markers_list.append(CodeMarker(next_code_marker_start,
  411. subregion.get_offset_begin(),
  412. Marker.T.CODE))
  413. next_code_marker_start = subregion.get_offset_begin()
  414. # here is the recursive call for all sub-regions
  415. (marker_start_ind, next_code_marker_start) = cache_markers_list_rec(data,
  416. sub_id,
  417. marker_start_ind,
  418. next_code_marker_start)
  419. # cache all markers after the last subregion
  420. while len(data.markers) > marker_start_ind and \
  421. region.get_offset_end() > data.markers[marker_start_ind].get_offset_begin():
  422. # append code markers coming before non-code marker
  423. if next_code_marker_start < data.markers[marker_start_ind].get_offset_begin():
  424. region._markers_list.append(CodeMarker(next_code_marker_start,
  425. data.markers[marker_start_ind].get_offset_begin(),
  426. Marker.T.CODE))
  427. next_code_marker_start = data.markers[marker_start_ind].get_offset_end()
  428. region._markers_list.append(marker_start_ind)
  429. marker_start_ind += 1
  430. # cache the last code segment after the last marker
  431. if next_code_marker_start < region.get_offset_end():
  432. region._markers_list.append(CodeMarker(next_code_marker_start,
  433. region.get_offset_end(),
  434. Marker.T.CODE))
  435. next_code_marker_start = region.get_offset_end()
  436. # return the starting point for the next call of this function
  437. return (marker_start_ind, next_code_marker_start)
  438. # append markers list to all regions recursively
  439. (next_marker_pos, next_code_marker_start) = cache_markers_list_rec(self, 1, 0, 0)
  440. assert(next_marker_pos == len(self.markers))
  441. # excluding subregions
  442. if exclude_children == True:
  443. for marker_ind in region._markers_list:
  444. if isinstance(marker_ind, int):
  445. marker = self.markers[marker_ind]
  446. else:
  447. marker = marker_ind # CodeMarker
  448. if marker.group & filter_group:
  449. yield marker
  450. # including subregions
  451. else:
  452. next_code_marker_start = region.get_offset_begin()
  453. for marker in self.markers[region._first_marker_ind:]:
  454. if marker.get_offset_begin() >= region.get_offset_end():
  455. break
  456. if region.get_offset_begin() > marker.get_offset_begin():
  457. continue
  458. if Marker.T.CODE & filter_group and next_code_marker_start < marker.get_offset_begin():
  459. yield Marker(next_code_marker_start, marker.get_offset_begin(), Marker.T.CODE)
  460. if marker.group & filter_group:
  461. yield marker
  462. next_code_marker_start = marker.get_offset_end()
  463. if Marker.T.CODE & filter_group and next_code_marker_start < region.get_offset_end():
  464. yield Marker(next_code_marker_start, region.get_offset_end(), Marker.T.CODE)
  465. def are_markers_loaded(self):
  466. return self.markers != None
  467. def __repr__(self):
  468. return Data.__repr__(self) + " and regions " + self.regions.__repr__()
  469. class AggregatedData(Data):
  470. def __init__(self, loader, path):
  471. Data.__init__(self)
  472. self.path = path
  473. self.loader = loader
  474. self.subdirs = None
  475. self.subfiles = None
  476. def get_subdirs(self):
  477. if self.subdirs != None:
  478. return self.subdirs
  479. self.subdirs = []
  480. if self.path != None:
  481. for subdir in self.loader.db.iterate_dircontent(self.path, include_subdirs = True, include_subfiles = False):
  482. self.subdirs.append(subdir)
  483. return self.subdirs
  484. def get_subfiles(self):
  485. if self.subfiles != None:
  486. return self.subfiles
  487. self.subfiles = []
  488. if self.path != None:
  489. for subfile in self.loader.db.iterate_dircontent(self.path, include_subdirs = False, include_subfiles = True):
  490. self.subfiles.append(subfile)
  491. return self.subfiles
  492. class SelectData(Data):
  493. def __init__(self, loader, path, file_id, region_id):
  494. Data.__init__(self)
  495. self.loader = loader
  496. self.path = path
  497. self.file_id = file_id
  498. self.region_id = region_id
  499. self.region = None
  500. def get_path(self):
  501. return self.path
  502. def get_region(self):
  503. if self.region == None and self.region_id != None:
  504. row = self.loader.db.get_region(self.file_id, self.region_id)
  505. if row != None:
  506. self.region = Region(self.loader,
  507. self.file_id,
  508. self.region_id,
  509. row.name,
  510. row.begin,
  511. row.end,
  512. row.line_begin,
  513. row.line_end,
  514. row.cursor,
  515. row.group,
  516. row.checksum)
  517. return self.region
  518. class DiffData(Data):
  519. def __init__(self, new_data, old_data):
  520. Data.__init__(self)
  521. self.new_data = new_data
  522. self.old_data = old_data
  523. def get_data(self, namespace, field):
  524. new_data = self.new_data.get_data(namespace, field)
  525. old_data = self.old_data.get_data(namespace, field)
  526. if new_data == None:
  527. return None
  528. if old_data == None:
  529. # non_zero fields has got zero value by default if missed
  530. # the data can be also unavailable,
  531. # because previous collection does not include that
  532. # but external tools (like limit.py) should warn about this,
  533. # using list of registered database properties
  534. old_data = 0
  535. return new_data - old_data
  536. ####################################
  537. # Loader
  538. ####################################
  539. class Namespace(object):
  540. class NamespaceError(Exception):
  541. def __init__(self, namespace, reason):
  542. Exception.__init__(self, "Namespace '"
  543. + namespace
  544. + "': '"
  545. + reason
  546. + "'")
  547. class FieldError(Exception):
  548. def __init__(self, field, reason):
  549. Exception.__init__(self, "Field '"
  550. + field
  551. + "': '"
  552. + reason
  553. + "'")
  554. def __init__(self, db_handle, name, support_regions = False, version='1.0'):
  555. if not isinstance(name, str):
  556. raise Namespace.NamespaceError(name, "name not a string")
  557. self.name = name
  558. self.support_regions = support_regions
  559. self.fields = {}
  560. self.db = db_handle
  561. if self.db.check_table(name) == False:
  562. self.db.create_table(name, support_regions, version)
  563. else:
  564. for column in self.db.iterate_columns(name):
  565. self.add_field(column.name,
  566. mpp.internal.api_impl.PackagerFactory().get_python_type(column.sql_type),
  567. non_zero=column.non_zero)
  568. def get_name(self):
  569. return self.name
  570. def are_regions_supported(self):
  571. return self.support_regions
  572. def add_field(self, field_name, python_type, non_zero=False):
  573. if not isinstance(field_name, str):
  574. raise Namespace.FieldError(field_name, "field_name not a string")
  575. packager = mpp.internal.api_impl.PackagerFactory().create(python_type, non_zero)
  576. if field_name in self.fields.keys():
  577. raise Namespace.FieldError(field_name, "double used")
  578. self.fields[field_name] = packager
  579. if self.db.check_column(self.get_name(), field_name) == False:
  580. # - False if cloned
  581. # - True if created
  582. return self.db.create_column(self.name, field_name, packager.get_sql_type(), non_zero=non_zero)
  583. return None # if double request
  584. def iterate_field_names(self):
  585. for name in self.fields.keys():
  586. yield name
  587. def check_field(self, field_name):
  588. try:
  589. self._get_field_packager(field_name)
  590. except mpp.internal.api_impl.PackagerError:
  591. return False
  592. return True
  593. def get_field_sql_type(self, field_name):
  594. try:
  595. return self._get_field_packager(field_name).get_sql_type()
  596. except mpp.internal.api_impl.PackagerError:
  597. raise Namespace.FieldError(field_name, 'does not exist')
  598. def get_field_python_type(self, field_name):
  599. try:
  600. return self._get_field_packager(field_name).get_python_type()
  601. except mpp.internal.api_impl.PackagerError:
  602. raise Namespace.FieldError(field_name, 'does not exist')
  603. def is_field_non_zero(self, field_name):
  604. try:
  605. return self._get_field_packager(field_name).is_non_zero()
  606. except mpp.internal.api_impl.PackagerError:
  607. raise Namespace.FieldError(field_name, 'does not exist')
  608. def _get_field_packager(self, field_name):
  609. if field_name in self.fields.keys():
  610. return self.fields[field_name]
  611. else:
  612. raise mpp.internal.api_impl.PackagerError("unknown field " + field_name + " requested")
  613. class Loader(object):
  614. def __init__(self):
  615. self.namespaces = {}
  616. self.db = None
  617. self.last_file_data = None # for performance boost reasons
  618. def create_database(self, dbfile, previous_db = None):
  619. self.db = mpp.internal.dbwrap.Database()
  620. try:
  621. self.db.create(dbfile, clone_from=previous_db)
  622. except:
  623. return False
  624. return True
  625. def open_database(self, dbfile, read_only = True):
  626. self.db = mpp.internal.dbwrap.Database()
  627. if os.path.exists(dbfile) == False:
  628. return False
  629. try:
  630. self.db.connect(dbfile, read_only=read_only)
  631. except:
  632. return False
  633. for table in self.db.iterate_tables():
  634. self.create_namespace(table.name, table.support_regions)
  635. return True
  636. def set_property(self, property_name, value):
  637. if self.db == None:
  638. return None
  639. return self.db.set_property(property_name, str(value))
  640. def get_property(self, property_name):
  641. if self.db == None:
  642. return None
  643. return self.db.get_property(property_name)
  644. def iterate_properties(self):
  645. if self.db == None:
  646. return None
  647. return self.db.iterate_properties()
  648. def create_namespace(self, name, support_regions = False, version='1.0'):
  649. if self.db == None:
  650. return None
  651. if name in self.namespaces.keys():
  652. raise Namespace.NamespaceError(name, "double used")
  653. new_namespace = Namespace(self.db, name, support_regions, version)
  654. self.namespaces[name] = new_namespace
  655. return new_namespace
  656. def iterate_namespace_names(self):
  657. for name in self.namespaces.keys():
  658. yield name
  659. def get_namespace(self, name):
  660. if name in self.namespaces.keys():
  661. return self.namespaces[name]
  662. else:
  663. return None
  664. def create_file_data(self, path, checksum, content):
  665. if self.db == None:
  666. return None
  667. (new_id, is_updated) = self.db.create_file(path, checksum)
  668. result = FileData(self, path, new_id, checksum, content)
  669. self.last_file_data = result
  670. return (result, is_updated)
  671. def load_file_data(self, path):
  672. if self.db == None:
  673. return None
  674. if self.last_file_data != None and self.last_file_data.get_path() == path:
  675. return self.last_file_data
  676. data = self.db.get_file(path)
  677. if data == None:
  678. return None
  679. result = FileData(self, data.path, data.id, data.checksum, None)
  680. self.last_file_data = result
  681. return result
  682. class DataNotPackable(Exception):
  683. def __init__(self, namespace, field, value, packager, extra_message):
  684. Exception.__init__(self, "Data '"
  685. + str(value)
  686. + "' of type "
  687. + str(value.__class__)
  688. + " referred by '"
  689. + namespace
  690. + "=>"
  691. + field
  692. + "' is not packable by registered packager '"
  693. + str(packager.__class__)
  694. + "': " + extra_message)
  695. def save_file_data(self, file_data):
  696. if self.db == None:
  697. return None
  698. class DataIterator(object):
  699. def iterate_packed_values(self, data, namespace, support_regions = False):
  700. for each in data.iterate_fields(namespace):
  701. space = self.loader.get_namespace(namespace)
  702. if space == None:
  703. raise Loader.DataNotPackable(namespace, each[0], each[1], None, "The namespace has not been found")
  704. try:
  705. packager = space._get_field_packager(each[0])
  706. except mpp.internal.api_impl.PackagerError:
  707. raise Loader.DataNotPackable(namespace, each[0], each[1], None, "The field has not been found")
  708. if space.support_regions != support_regions:
  709. raise Loader.DataNotPackable(namespace, each[0], each[1], packager, "Incompatible support for regions")
  710. try:
  711. packed_data = packager.pack(each[1])
  712. if packed_data == None:
  713. continue
  714. except mpp.internal.api_impl.PackagerError:
  715. raise Loader.DataNotPackable(namespace, each[0], each[1], packager, "Packager raised exception")
  716. yield (each[0], packed_data)
  717. def __init__(self, loader, data, namespace, support_regions = False):
  718. self.loader = loader
  719. self.iterator = self.iterate_packed_values(data, namespace, support_regions)
  720. def __iter__(self):
  721. return self.iterator
  722. # TODO can construct to add multiple rows at one sql query
  723. # to improve the performance
  724. for namespace in file_data.iterate_namespaces():
  725. if file_data.is_namespace_updated(namespace) == False:
  726. continue
  727. self.db.add_row(namespace,
  728. file_data.get_id(),
  729. None,
  730. DataIterator(self, file_data, namespace))
  731. if file_data.are_regions_loaded():
  732. for region in file_data.iterate_regions():
  733. for namespace in region.iterate_namespaces():
  734. if region.is_namespace_updated(namespace) == False:
  735. continue
  736. self.db.add_row(namespace,
  737. file_data.get_id(),
  738. region.get_id(),
  739. DataIterator(self, region, namespace, support_regions = True))
  740. def iterate_file_data(self, path = None, path_like_filter = "%"):
  741. if self.db == None:
  742. return None
  743. final_path_like = path_like_filter
  744. if path != None:
  745. if self.db.check_dir(path) == False and self.db.check_file(path) == False:
  746. return None
  747. final_path_like = path + path_like_filter
  748. class FileDataIterator(object):
  749. def iterate_file_data(self, loader, final_path_like):
  750. for data in loader.db.iterate_files(path_like=final_path_like):
  751. yield FileData(loader, data.path, data.id, data.checksum, None)
  752. def __init__(self, loader, final_path_like):
  753. self.iterator = self.iterate_file_data(loader, final_path_like)
  754. def __iter__(self):
  755. return self.iterator
  756. if self.db == None:
  757. return None
  758. return FileDataIterator(self, final_path_like)
  759. def load_aggregated_data(self, path = None, path_like_filter = "%", namespaces = None):
  760. if self.db == None:
  761. return None
  762. final_path_like = path_like_filter
  763. if path != None:
  764. if self.db.check_dir(path) == False and self.db.check_file(path) == False:
  765. return None
  766. final_path_like = path + path_like_filter
  767. if namespaces == None:
  768. namespaces = self.namespaces.keys()
  769. result = AggregatedData(self, path)
  770. for name in namespaces:
  771. namespace = self.get_namespace(name)
  772. data = self.db.aggregate_rows(name, path_like = final_path_like)
  773. for field in data.keys():
  774. if namespace.get_field_python_type(field) == str:
  775. continue
  776. data[field]['nonzero'] = namespace.is_field_non_zero(field)
  777. distribution = self.db.count_rows(name, path_like = final_path_like, group_by_column = field)
  778. data[field]['distribution-bars'] = []
  779. for each in distribution:
  780. if each[0] == None:
  781. continue
  782. assert(float(data[field]['count'] != 0))
  783. data[field]['distribution-bars'].append({'metric': each[0],
  784. 'count': each[1],
  785. 'ratio': (float(each[1]) / float(data[field]['count']))})
  786. result.set_data(name, field, data[field])
  787. return result
  788. def load_selected_data(self, namespace, fields = None, path = None, path_like_filter = "%", filters = [],
  789. sort_by = None, limit_by = None):
  790. if self.db == None:
  791. return None
  792. final_path_like = path_like_filter
  793. if path != None:
  794. if self.db.check_dir(path) == False and self.db.check_file(path) == False:
  795. return None
  796. final_path_like = path + path_like_filter
  797. namespace_obj = self.get_namespace(namespace)
  798. if namespace_obj == None:
  799. return None
  800. class SelectDataIterator(object):
  801. def iterate_selected_values(self, loader, namespace_obj, final_path_like, fields, filters, sort_by, limit_by):
  802. for row in loader.db.select_rows(namespace_obj.get_name(), path_like=final_path_like, filters=filters,
  803. order_by=sort_by, limit_by=limit_by):
  804. region_id = None
  805. if namespace_obj.are_regions_supported() == True:
  806. region_id = row['region_id']
  807. data = SelectData(loader, row['path'], row['id'], region_id)
  808. field_names = fields
  809. if fields == None:
  810. field_names = namespace_obj.iterate_field_names()
  811. for field in field_names:
  812. data.set_data(namespace, field, row[field])
  813. yield data
  814. def __init__(self, loader, namespace_obj, final_path_like, fields, filters, sort_by, limit_by):
  815. self.iterator = self.iterate_selected_values(loader, namespace_obj, final_path_like, fields, filters, sort_by, limit_by)
  816. def __iter__(self):
  817. return self.iterator
  818. return SelectDataIterator(self, namespace_obj, final_path_like, fields, filters, sort_by, limit_by)
  819. class BasePlugin(object):
  820. def initialize(self):
  821. pass
  822. def terminate(self):
  823. pass
  824. def set_name(self, name):
  825. self.name = name
  826. def get_name(self):
  827. if hasattr(self, 'name') == False:
  828. return None
  829. return self.name
  830. def get_namespace(self):
  831. return self.get_name()
  832. def set_version(self, version):
  833. self.version = version
  834. def get_version(self):
  835. if hasattr(self, 'version') == False:
  836. return None
  837. return self.version
  838. def _set_plugin_loader(self, loader):
  839. self.plugin_loader = loader
  840. def _get_plugin_loader(self):
  841. if hasattr(self, 'plugin_loader') == False:
  842. return None
  843. return self.plugin_loader
  844. def get_plugin(self, plugin_name):
  845. return self._get_plugin_loader().get_plugin(plugin_name)
  846. def get_action(self):
  847. return self._get_plugin_loader().get_action()
  848. class Plugin(BasePlugin):
  849. class Field(object):
  850. def __init__(self, name, ftype, non_zero=False):
  851. self.name = name
  852. self.type = ftype
  853. self.non_zero = non_zero
  854. self._regions_supported = True
  855. class Property(object):
  856. def __init__(self, name, value):
  857. self.name = name
  858. self.value = value
  859. def initialize(self, namespace=None, support_regions=True, fields=[], properties=[]):
  860. super(Plugin, self).initialize()
  861. if hasattr(self, 'is_updated') == False:
  862. self.is_updated = False # original initialization
  863. db_loader = self.get_plugin('mpp.dbf').get_loader()
  864. if namespace == None:
  865. namespace = self.get_name()
  866. if (len(fields) != 0 or len(properties) != 0):
  867. prev_version = db_loader.set_property(self.get_name() + ":version", self.get_version())
  868. if str(prev_version) != str(self.get_version()):
  869. self.is_updated = True
  870. for prop in properties:
  871. assert(prop.name != 'version')
  872. prev_prop = db_loader.set_property(self.get_name() + ":" + prop.name, prop.value)
  873. if str(prev_prop) != str(prop.value):
  874. self.is_updated = True
  875. if len(fields) != 0:
  876. namespace_obj = db_loader.create_namespace(namespace,
  877. support_regions=support_regions,
  878. version=self.get_version())
  879. for field in fields:
  880. is_created = namespace_obj.add_field(field.name, field.type, non_zero=field.non_zero)
  881. field._regions_supported = support_regions
  882. assert(is_created != None)
  883. # if field is created (not cloned from the previous db),
  884. # mark the plug-in as updated in order to trigger full rescan
  885. self.is_updated = self.is_updated or is_created
  886. class MetricPluginMixin(Parent):
  887. class AliasError(Exception):
  888. def __init__(self, alias):
  889. Exception.__init__(self, "Unknown pattern alias: " + str(alias))
  890. class PlainCounter(object):
  891. def __init__(self, namespace, field, plugin, alias, data, region):
  892. self.namespace = namespace
  893. self.field = field
  894. self.plugin = plugin
  895. self.alias = alias
  896. self.data = data
  897. self.region = region
  898. self.result = 0
  899. def count(self, marker, pattern_to_search):
  900. self.result += len(pattern_to_search.findall(self.data.get_content(),
  901. marker.get_offset_begin(),
  902. marker.get_offset_end()))
  903. def get_result(self):
  904. return self.result
  905. class IterIncrementCounter(PlainCounter):
  906. def count(self, marker, pattern_to_search):
  907. self.marker = marker
  908. self.pattern_to_search = pattern_to_search
  909. for match in pattern_to_search.finditer(self.data.get_content(),
  910. marker.get_offset_begin(),
  911. marker.get_offset_end()):
  912. self.result += self.increment(match)
  913. def increment(self, match):
  914. return 1
  915. class IterAssignCounter(PlainCounter):
  916. def count(self, marker, pattern_to_search):
  917. self.marker = marker
  918. self.pattern_to_search = pattern_to_search
  919. for match in pattern_to_search.finditer(self.data.get_content(),
  920. marker.get_offset_begin(),
  921. marker.get_offset_end()):
  922. self.result = self.assign(match)
  923. def assign(self, match):
  924. return self.result
  925. class RankedCounter(PlainCounter):
  926. def __init__(self, *args, **kwargs):
  927. super(MetricPluginMixin.RankedCounter, self).__init__(*args, **kwargs)
  928. self.result = self.region.get_data(self.namespace, self.field)
  929. if self.result == None:
  930. self.result = 1
  931. def get_result(self):
  932. sourced_metric = self.region.get_data(self.rank_source[0], self.rank_source[1])
  933. for (ind, range_pair) in enumerate(self.rank_ranges):
  934. if ((range_pair[0] == None or sourced_metric >= range_pair[0])
  935. and
  936. (range_pair[1] == None or sourced_metric <= range_pair[1])):
  937. self.result = self.result * (ind + 1)
  938. break
  939. return self.result
  940. def declare_metric(self, is_active, field,
  941. pattern_to_search_or_map_of_patterns,
  942. marker_type_mask=Marker.T.ANY,
  943. region_type_mask=Region.T.ANY,
  944. exclude_subregions=True,
  945. merge_markers=False):
  946. if hasattr(self, '_fields') == False:
  947. self._fields = {}
  948. if isinstance(pattern_to_search_or_map_of_patterns, dict):
  949. map_of_patterns = pattern_to_search_or_map_of_patterns
  950. else:
  951. map_of_patterns = {'*': pattern_to_search_or_map_of_patterns}
  952. # client may suply with pattern or pair of pattern + counter class
  953. for key in map_of_patterns.keys():
  954. if isinstance(map_of_patterns[key], tuple) == False:
  955. # if it is not a pair, create a pair using default counter class
  956. map_of_patterns[key] = (map_of_patterns[key],
  957. MetricPluginMixin.PlainCounter)
  958. if is_active == True:
  959. self._fields[field.name] = (field,
  960. marker_type_mask,
  961. exclude_subregions,
  962. merge_markers,
  963. map_of_patterns,
  964. region_type_mask)
  965. def is_active(self, metric_name = None):
  966. if metric_name == None:
  967. return (len(self._fields.keys()) > 0)
  968. return (metric_name in self._fields.keys())
  969. def get_fields(self):
  970. result = []
  971. for key in self._fields.keys():
  972. result.append(self._fields[key][0])
  973. return result
  974. def callback(self, parent, data, is_updated):
  975. # count if metric is enabled,
  976. # and (optimization for the case of iterative rescan:)
  977. # if file is updated or this plugin's settings are updated
  978. is_updated = is_updated or self.is_updated
  979. if is_updated == True:
  980. for field in self.get_fields():
  981. self.count_if_active(self.get_namespace(),
  982. field.name,
  983. data,
  984. alias=parent.get_name())
  985. # this mixin implements parent interface
  986. self.notify_children(data, is_updated)
  987. def count_if_active(self, namespace, field, data, alias='*'):
  988. if self.is_active(field) == False:
  989. return
  990. field_data = self._fields[field]
  991. if alias not in field_data[4].keys():
  992. if '*' not in field_data[4].keys():
  993. raise self.AliasError(alias)
  994. else:
  995. alias = '*'
  996. (pattern_to_search, counter_class) = field_data[4][alias]
  997. if field_data[0]._regions_supported == True:
  998. for region in data.iterate_regions(filter_group=field_data[5]):
  999. counter = counter_class(namespace, field, self, alias, data, region)
  1000. if field_data[1] != Marker.T.NONE:
  1001. for marker in data.iterate_markers(
  1002. filter_group = field_data[1],
  1003. region_id = region.get_id(),
  1004. exclude_children = field_data[2],
  1005. merge=field_data[3]):
  1006. counter.count(marker, pattern_to_search)
  1007. count = counter.get_result()
  1008. if count != 0 or field_data[0].non_zero == False:
  1009. region.set_data(namespace, field, count)
  1010. else:
  1011. counter = counter_class(namespace, field, self, alias, data, None)
  1012. if field_data[1] != Marker.T.NONE:
  1013. for marker in data.iterate_markers(
  1014. filter_group = field_data[1],
  1015. region_id = None,
  1016. exclude_children = field_data[2],
  1017. merge=field_data[3]):
  1018. counter.count(marker, pattern_to_search)
  1019. count = counter.get_result()
  1020. if count != 0 or field_data[0].non_zero == False:
  1021. data.set_data(namespace, field, count)