graph-depends 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. #!/usr/bin/env python
  2. # Usage (the graphviz package must be installed in your distribution)
  3. # ./support/scripts/graph-depends [-p package-name] > test.dot
  4. # dot -Tpdf test.dot -o test.pdf
  5. #
  6. # With no arguments, graph-depends will draw a complete graph of
  7. # dependencies for the current configuration.
  8. # If '-p <package-name>' is specified, graph-depends will draw a graph
  9. # of dependencies for the given package name.
  10. # If '-d <depth>' is specified, graph-depends will limit the depth of
  11. # the dependency graph to 'depth' levels.
  12. #
  13. # Limitations
  14. #
  15. # * Some packages have dependencies that depend on the Buildroot
  16. # configuration. For example, many packages have a dependency on
  17. # openssl if openssl has been enabled. This tool will graph the
  18. # dependencies as they are with the current Buildroot
  19. # configuration.
  20. #
  21. # Copyright (C) 2010-2013 Thomas Petazzoni <thomas.petazzoni@free-electrons.com>
  22. import logging
  23. import sys
  24. import subprocess
  25. import argparse
  26. from fnmatch import fnmatch
  27. import brpkgutil
  28. # Modes of operation:
  29. MODE_FULL = 1 # draw full dependency graph for all selected packages
  30. MODE_PKG = 2 # draw dependency graph for a given package
  31. allpkgs = []
  32. # Execute the "make show-targets" command to get the list of the main
  33. # Buildroot PACKAGES and return it formatted as a Python list. This
  34. # list is used as the starting point for full dependency graphs
  35. def get_targets():
  36. logging.info("Getting targets")
  37. cmd = ["make", "-s", "--no-print-directory", "show-targets"]
  38. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, universal_newlines=True)
  39. output = p.communicate()[0].strip()
  40. if p.returncode != 0:
  41. return None
  42. if output == '':
  43. return []
  44. return output.split(' ')
  45. # Recursive function that builds the tree of dependencies for a given
  46. # list of packages. The dependencies are built in a list called
  47. # 'dependencies', which contains tuples of the form (pkg1 ->
  48. # pkg2_on_which_pkg1_depends, pkg3 -> pkg4_on_which_pkg3_depends) and
  49. # the function finally returns this list.
  50. def get_all_depends(pkgs, get_depends_func):
  51. dependencies = []
  52. # Filter the packages for which we already have the dependencies
  53. filtered_pkgs = []
  54. for pkg in pkgs:
  55. if pkg in allpkgs:
  56. continue
  57. filtered_pkgs.append(pkg)
  58. allpkgs.append(pkg)
  59. if len(filtered_pkgs) == 0:
  60. return []
  61. depends = get_depends_func(filtered_pkgs)
  62. deps = set()
  63. for pkg in filtered_pkgs:
  64. pkg_deps = depends[pkg]
  65. # This package has no dependency.
  66. if pkg_deps == []:
  67. continue
  68. # Add dependencies to the list of dependencies
  69. for dep in pkg_deps:
  70. dependencies.append((pkg, dep))
  71. deps.add(dep)
  72. if len(deps) != 0:
  73. newdeps = get_all_depends(deps, get_depends_func)
  74. if newdeps is not None:
  75. dependencies += newdeps
  76. return dependencies
  77. # The Graphviz "dot" utility doesn't like dashes in node names. So for
  78. # node names, we strip all dashes.
  79. def pkg_node_name(pkg):
  80. return pkg.replace("-", "")
  81. TARGET_EXCEPTIONS = [
  82. "target-finalize",
  83. "target-post-image",
  84. ]
  85. # Basic cache for the results of the is_dep() function, in order to
  86. # optimize the execution time. The cache is a dict of dict of boolean
  87. # values. The key to the primary dict is "pkg", and the key of the
  88. # sub-dicts is "pkg2".
  89. is_dep_cache = {}
  90. def is_dep_cache_insert(pkg, pkg2, val):
  91. try:
  92. is_dep_cache[pkg].update({pkg2: val})
  93. except KeyError:
  94. is_dep_cache[pkg] = {pkg2: val}
  95. # Retrieves from the cache whether pkg2 is a transitive dependency
  96. # of pkg.
  97. # Note: raises a KeyError exception if the dependency is not known.
  98. def is_dep_cache_lookup(pkg, pkg2):
  99. return is_dep_cache[pkg][pkg2]
  100. # This function return True if pkg is a dependency (direct or
  101. # transitive) of pkg2, dependencies being listed in the deps
  102. # dictionary. Returns False otherwise.
  103. # This is the un-cached version.
  104. def is_dep_uncached(pkg, pkg2, deps):
  105. try:
  106. for p in deps[pkg2]:
  107. if pkg == p:
  108. return True
  109. if is_dep(pkg, p, deps):
  110. return True
  111. except KeyError:
  112. pass
  113. return False
  114. # See is_dep_uncached() above; this is the cached version.
  115. def is_dep(pkg, pkg2, deps):
  116. try:
  117. return is_dep_cache_lookup(pkg, pkg2)
  118. except KeyError:
  119. val = is_dep_uncached(pkg, pkg2, deps)
  120. is_dep_cache_insert(pkg, pkg2, val)
  121. return val
  122. # This function eliminates transitive dependencies; for example, given
  123. # these dependency chain: A->{B,C} and B->{C}, the A->{C} dependency is
  124. # already covered by B->{C}, so C is a transitive dependency of A, via B.
  125. # The functions does:
  126. # - for each dependency d[i] of the package pkg
  127. # - if d[i] is a dependency of any of the other dependencies d[j]
  128. # - do not keep d[i]
  129. # - otherwise keep d[i]
  130. def remove_transitive_deps(pkg, deps):
  131. d = deps[pkg]
  132. new_d = []
  133. for i in range(len(d)):
  134. keep_me = True
  135. for j in range(len(d)):
  136. if j == i:
  137. continue
  138. if is_dep(d[i], d[j], deps):
  139. keep_me = False
  140. if keep_me:
  141. new_d.append(d[i])
  142. return new_d
  143. # This function removes the dependency on some 'mandatory' package, like the
  144. # 'toolchain' package, or the 'skeleton' package
  145. def remove_mandatory_deps(pkg, deps):
  146. return [p for p in deps[pkg] if p not in ['toolchain', 'skeleton']]
  147. # This function will check that there is no loop in the dependency chain
  148. # As a side effect, it builds up the dependency cache.
  149. def check_circular_deps(deps):
  150. def recurse(pkg):
  151. if pkg not in list(deps.keys()):
  152. return
  153. if pkg in not_loop:
  154. return
  155. not_loop.append(pkg)
  156. chain.append(pkg)
  157. for p in deps[pkg]:
  158. if p in chain:
  159. logging.warning("\nRecursion detected for : %s" % (p))
  160. while True:
  161. _p = chain.pop()
  162. logging.warning("which is a dependency of: %s" % (_p))
  163. if p == _p:
  164. sys.exit(1)
  165. recurse(p)
  166. chain.pop()
  167. not_loop = []
  168. chain = []
  169. for pkg in list(deps.keys()):
  170. recurse(pkg)
  171. # This functions trims down the dependency list of all packages.
  172. # It applies in sequence all the dependency-elimination methods.
  173. def remove_extra_deps(deps, transitive):
  174. for pkg in list(deps.keys()):
  175. if not pkg == 'all':
  176. deps[pkg] = remove_mandatory_deps(pkg, deps)
  177. for pkg in list(deps.keys()):
  178. if not transitive or pkg == 'all':
  179. deps[pkg] = remove_transitive_deps(pkg, deps)
  180. return deps
  181. # Print the attributes of a node: label and fill-color
  182. def print_attrs(outfile, pkg, version, depth, colors):
  183. name = pkg_node_name(pkg)
  184. if pkg == 'all':
  185. label = 'ALL'
  186. else:
  187. label = pkg
  188. if depth == 0:
  189. color = colors[0]
  190. else:
  191. if pkg.startswith('host') \
  192. or pkg.startswith('toolchain') \
  193. or pkg.startswith('rootfs'):
  194. color = colors[2]
  195. else:
  196. color = colors[1]
  197. if version == "virtual":
  198. outfile.write("%s [label = <<I>%s</I>>]\n" % (name, label))
  199. else:
  200. outfile.write("%s [label = \"%s\"]\n" % (name, label))
  201. outfile.write("%s [color=%s,style=filled]\n" % (name, color))
  202. done_deps = []
  203. # Print the dependency graph of a package
  204. def print_pkg_deps(outfile, dict_deps, dict_version, stop_list, exclude_list,
  205. arrow_dir, draw_graph, depth, max_depth, pkg, colors):
  206. if pkg in done_deps:
  207. return
  208. done_deps.append(pkg)
  209. if draw_graph:
  210. print_attrs(outfile, pkg, dict_version.get(pkg), depth, colors)
  211. elif depth != 0:
  212. outfile.write("%s " % pkg)
  213. if pkg not in dict_deps:
  214. return
  215. for p in stop_list:
  216. if fnmatch(pkg, p):
  217. return
  218. if dict_version.get(pkg) == "virtual" and "virtual" in stop_list:
  219. return
  220. if pkg.startswith("host-") and "host" in stop_list:
  221. return
  222. if max_depth == 0 or depth < max_depth:
  223. for d in dict_deps[pkg]:
  224. if dict_version.get(d) == "virtual" \
  225. and "virtual" in exclude_list:
  226. continue
  227. if d.startswith("host-") \
  228. and "host" in exclude_list:
  229. continue
  230. add = True
  231. for p in exclude_list:
  232. if fnmatch(d, p):
  233. add = False
  234. break
  235. if add:
  236. if draw_graph:
  237. outfile.write("%s -> %s [dir=%s]\n" % (pkg_node_name(pkg), pkg_node_name(d), arrow_dir))
  238. print_pkg_deps(outfile, dict_deps, dict_version, stop_list, exclude_list,
  239. arrow_dir, draw_graph, depth + 1, max_depth, d, colors)
  240. def parse_args():
  241. parser = argparse.ArgumentParser(description="Graph packages dependencies")
  242. parser.add_argument("--check-only", "-C", dest="check_only", action="store_true", default=False,
  243. help="Only do the dependency checks (circular deps...)")
  244. parser.add_argument("--outfile", "-o", metavar="OUT_FILE", dest="outfile",
  245. help="File in which to generate the dot representation")
  246. parser.add_argument("--package", '-p', metavar="PACKAGE",
  247. help="Graph the dependencies of PACKAGE")
  248. parser.add_argument("--depth", '-d', metavar="DEPTH", dest="depth", type=int, default=0,
  249. help="Limit the dependency graph to DEPTH levels; 0 means no limit.")
  250. parser.add_argument("--stop-on", "-s", metavar="PACKAGE", dest="stop_list", action="append",
  251. help="Do not graph past this package (can be given multiple times)." +
  252. " Can be a package name or a glob, " +
  253. " 'virtual' to stop on virtual packages, or " +
  254. "'host' to stop on host packages.")
  255. parser.add_argument("--exclude", "-x", metavar="PACKAGE", dest="exclude_list", action="append",
  256. help="Like --stop-on, but do not add PACKAGE to the graph.")
  257. parser.add_argument("--colors", "-c", metavar="COLOR_LIST", dest="colors",
  258. default="lightblue,grey,gainsboro",
  259. help="Comma-separated list of the three colors to use" +
  260. " to draw the top-level package, the target" +
  261. " packages, and the host packages, in this order." +
  262. " Defaults to: 'lightblue,grey,gainsboro'")
  263. parser.add_argument("--transitive", dest="transitive", action='store_true',
  264. default=False)
  265. parser.add_argument("--no-transitive", dest="transitive", action='store_false',
  266. help="Draw (do not draw) transitive dependencies")
  267. parser.add_argument("--direct", dest="direct", action='store_true', default=True,
  268. help="Draw direct dependencies (the default)")
  269. parser.add_argument("--reverse", dest="direct", action='store_false',
  270. help="Draw reverse dependencies")
  271. parser.add_argument("--quiet", '-q', dest="quiet", action='store_true',
  272. help="Quiet")
  273. parser.add_argument("--flat-list", '-f', dest="flat_list", action='store_true', default=False,
  274. help="Do not draw graph, just print a flat list")
  275. return parser.parse_args()
  276. def main():
  277. args = parse_args()
  278. check_only = args.check_only
  279. logging.basicConfig(stream=sys.stderr, format='%(message)s',
  280. level=logging.WARNING if args.quiet else logging.INFO)
  281. if args.outfile is None:
  282. outfile = sys.stdout
  283. else:
  284. if check_only:
  285. logging.error("don't specify outfile and check-only at the same time")
  286. sys.exit(1)
  287. outfile = open(args.outfile, "w")
  288. if args.package is None:
  289. mode = MODE_FULL
  290. else:
  291. mode = MODE_PKG
  292. rootpkg = args.package
  293. if args.stop_list is None:
  294. stop_list = []
  295. else:
  296. stop_list = args.stop_list
  297. if args.exclude_list is None:
  298. exclude_list = []
  299. else:
  300. exclude_list = args.exclude_list
  301. if args.direct:
  302. get_depends_func = brpkgutil.get_depends
  303. arrow_dir = "forward"
  304. else:
  305. if mode == MODE_FULL:
  306. logging.error("--reverse needs a package")
  307. sys.exit(1)
  308. get_depends_func = brpkgutil.get_rdepends
  309. arrow_dir = "back"
  310. draw_graph = not args.flat_list
  311. # Get the colors: we need exactly three colors,
  312. # so no need not split more than 4
  313. # We'll let 'dot' validate the colors...
  314. colors = args.colors.split(',', 4)
  315. if len(colors) != 3:
  316. logging.error("Error: incorrect color list '%s'" % args.colors)
  317. sys.exit(1)
  318. # In full mode, start with the result of get_targets() to get the main
  319. # targets and then use get_all_depends() for all targets
  320. if mode == MODE_FULL:
  321. targets = get_targets()
  322. dependencies = []
  323. allpkgs.append('all')
  324. filtered_targets = []
  325. for tg in targets:
  326. # Skip uninteresting targets
  327. if tg in TARGET_EXCEPTIONS:
  328. continue
  329. dependencies.append(('all', tg))
  330. filtered_targets.append(tg)
  331. deps = get_all_depends(filtered_targets, get_depends_func)
  332. if deps is not None:
  333. dependencies += deps
  334. rootpkg = 'all'
  335. # In pkg mode, start directly with get_all_depends() on the requested
  336. # package
  337. elif mode == MODE_PKG:
  338. dependencies = get_all_depends([rootpkg], get_depends_func)
  339. # Make the dependencies a dictionnary { 'pkg':[dep1, dep2, ...] }
  340. dict_deps = {}
  341. for dep in dependencies:
  342. if dep[0] not in dict_deps:
  343. dict_deps[dep[0]] = []
  344. dict_deps[dep[0]].append(dep[1])
  345. check_circular_deps(dict_deps)
  346. if check_only:
  347. sys.exit(0)
  348. dict_deps = remove_extra_deps(dict_deps, args.transitive)
  349. dict_version = brpkgutil.get_version([pkg for pkg in allpkgs
  350. if pkg != "all" and not pkg.startswith("root")])
  351. # Start printing the graph data
  352. if draw_graph:
  353. outfile.write("digraph G {\n")
  354. print_pkg_deps(outfile, dict_deps, dict_version, stop_list, exclude_list,
  355. arrow_dir, draw_graph, 0, args.depth, rootpkg, colors)
  356. if draw_graph:
  357. outfile.write("}\n")
  358. else:
  359. outfile.write("\n")
  360. if __name__ == "__main__":
  361. sys.exit(main())