2
1

graph-depends 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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. Also, nodes can't start with a number,
  79. # so we prepend an underscore.
  80. def pkg_node_name(pkg):
  81. return "_" + pkg.replace("-", "")
  82. TARGET_EXCEPTIONS = [
  83. "target-finalize",
  84. "target-post-image",
  85. ]
  86. # Basic cache for the results of the is_dep() function, in order to
  87. # optimize the execution time. The cache is a dict of dict of boolean
  88. # values. The key to the primary dict is "pkg", and the key of the
  89. # sub-dicts is "pkg2".
  90. is_dep_cache = {}
  91. def is_dep_cache_insert(pkg, pkg2, val):
  92. try:
  93. is_dep_cache[pkg].update({pkg2: val})
  94. except KeyError:
  95. is_dep_cache[pkg] = {pkg2: val}
  96. # Retrieves from the cache whether pkg2 is a transitive dependency
  97. # of pkg.
  98. # Note: raises a KeyError exception if the dependency is not known.
  99. def is_dep_cache_lookup(pkg, pkg2):
  100. return is_dep_cache[pkg][pkg2]
  101. # This function return True if pkg is a dependency (direct or
  102. # transitive) of pkg2, dependencies being listed in the deps
  103. # dictionary. Returns False otherwise.
  104. # This is the un-cached version.
  105. def is_dep_uncached(pkg, pkg2, deps):
  106. try:
  107. for p in deps[pkg2]:
  108. if pkg == p:
  109. return True
  110. if is_dep(pkg, p, deps):
  111. return True
  112. except KeyError:
  113. pass
  114. return False
  115. # See is_dep_uncached() above; this is the cached version.
  116. def is_dep(pkg, pkg2, deps):
  117. try:
  118. return is_dep_cache_lookup(pkg, pkg2)
  119. except KeyError:
  120. val = is_dep_uncached(pkg, pkg2, deps)
  121. is_dep_cache_insert(pkg, pkg2, val)
  122. return val
  123. # This function eliminates transitive dependencies; for example, given
  124. # these dependency chain: A->{B,C} and B->{C}, the A->{C} dependency is
  125. # already covered by B->{C}, so C is a transitive dependency of A, via B.
  126. # The functions does:
  127. # - for each dependency d[i] of the package pkg
  128. # - if d[i] is a dependency of any of the other dependencies d[j]
  129. # - do not keep d[i]
  130. # - otherwise keep d[i]
  131. def remove_transitive_deps(pkg, deps):
  132. d = deps[pkg]
  133. new_d = []
  134. for i in range(len(d)):
  135. keep_me = True
  136. for j in range(len(d)):
  137. if j == i:
  138. continue
  139. if is_dep(d[i], d[j], deps):
  140. keep_me = False
  141. if keep_me:
  142. new_d.append(d[i])
  143. return new_d
  144. # This function removes the dependency on some 'mandatory' package, like the
  145. # 'toolchain' package, or the 'skeleton' package
  146. def remove_mandatory_deps(pkg, deps):
  147. return [p for p in deps[pkg] if p not in ['toolchain', 'skeleton']]
  148. # This function will check that there is no loop in the dependency chain
  149. # As a side effect, it builds up the dependency cache.
  150. def check_circular_deps(deps):
  151. def recurse(pkg):
  152. if pkg not in list(deps.keys()):
  153. return
  154. if pkg in not_loop:
  155. return
  156. not_loop.append(pkg)
  157. chain.append(pkg)
  158. for p in deps[pkg]:
  159. if p in chain:
  160. logging.warning("\nRecursion detected for : %s" % (p))
  161. while True:
  162. _p = chain.pop()
  163. logging.warning("which is a dependency of: %s" % (_p))
  164. if p == _p:
  165. sys.exit(1)
  166. recurse(p)
  167. chain.pop()
  168. not_loop = []
  169. chain = []
  170. for pkg in list(deps.keys()):
  171. recurse(pkg)
  172. # This functions trims down the dependency list of all packages.
  173. # It applies in sequence all the dependency-elimination methods.
  174. def remove_extra_deps(deps, transitive):
  175. for pkg in list(deps.keys()):
  176. if not pkg == 'all':
  177. deps[pkg] = remove_mandatory_deps(pkg, deps)
  178. for pkg in list(deps.keys()):
  179. if not transitive or pkg == 'all':
  180. deps[pkg] = remove_transitive_deps(pkg, deps)
  181. return deps
  182. # Print the attributes of a node: label and fill-color
  183. def print_attrs(outfile, pkg, version, depth, colors):
  184. name = pkg_node_name(pkg)
  185. if pkg == 'all':
  186. label = 'ALL'
  187. else:
  188. label = pkg
  189. if depth == 0:
  190. color = colors[0]
  191. else:
  192. if pkg.startswith('host') \
  193. or pkg.startswith('toolchain') \
  194. or pkg.startswith('rootfs'):
  195. color = colors[2]
  196. else:
  197. color = colors[1]
  198. if version == "virtual":
  199. outfile.write("%s [label = <<I>%s</I>>]\n" % (name, label))
  200. else:
  201. outfile.write("%s [label = \"%s\"]\n" % (name, label))
  202. outfile.write("%s [color=%s,style=filled]\n" % (name, color))
  203. done_deps = []
  204. # Print the dependency graph of a package
  205. def print_pkg_deps(outfile, dict_deps, dict_version, stop_list, exclude_list,
  206. arrow_dir, draw_graph, depth, max_depth, pkg, colors):
  207. if pkg in done_deps:
  208. return
  209. done_deps.append(pkg)
  210. if draw_graph:
  211. print_attrs(outfile, pkg, dict_version.get(pkg), depth, colors)
  212. elif depth != 0:
  213. outfile.write("%s " % pkg)
  214. if pkg not in dict_deps:
  215. return
  216. for p in stop_list:
  217. if fnmatch(pkg, p):
  218. return
  219. if dict_version.get(pkg) == "virtual" and "virtual" in stop_list:
  220. return
  221. if pkg.startswith("host-") and "host" in stop_list:
  222. return
  223. if max_depth == 0 or depth < max_depth:
  224. for d in dict_deps[pkg]:
  225. if dict_version.get(d) == "virtual" \
  226. and "virtual" in exclude_list:
  227. continue
  228. if d.startswith("host-") \
  229. and "host" in exclude_list:
  230. continue
  231. add = True
  232. for p in exclude_list:
  233. if fnmatch(d, p):
  234. add = False
  235. break
  236. if add:
  237. if draw_graph:
  238. outfile.write("%s -> %s [dir=%s]\n" % (pkg_node_name(pkg), pkg_node_name(d), arrow_dir))
  239. print_pkg_deps(outfile, dict_deps, dict_version, stop_list, exclude_list,
  240. arrow_dir, draw_graph, depth + 1, max_depth, d, colors)
  241. def parse_args():
  242. parser = argparse.ArgumentParser(description="Graph packages dependencies")
  243. parser.add_argument("--check-only", "-C", dest="check_only", action="store_true", default=False,
  244. help="Only do the dependency checks (circular deps...)")
  245. parser.add_argument("--outfile", "-o", metavar="OUT_FILE", dest="outfile",
  246. help="File in which to generate the dot representation")
  247. parser.add_argument("--package", '-p', metavar="PACKAGE",
  248. help="Graph the dependencies of PACKAGE")
  249. parser.add_argument("--depth", '-d', metavar="DEPTH", dest="depth", type=int, default=0,
  250. help="Limit the dependency graph to DEPTH levels; 0 means no limit.")
  251. parser.add_argument("--stop-on", "-s", metavar="PACKAGE", dest="stop_list", action="append",
  252. help="Do not graph past this package (can be given multiple times)." +
  253. " Can be a package name or a glob, " +
  254. " 'virtual' to stop on virtual packages, or " +
  255. "'host' to stop on host packages.")
  256. parser.add_argument("--exclude", "-x", metavar="PACKAGE", dest="exclude_list", action="append",
  257. help="Like --stop-on, but do not add PACKAGE to the graph.")
  258. parser.add_argument("--colors", "-c", metavar="COLOR_LIST", dest="colors",
  259. default="lightblue,grey,gainsboro",
  260. help="Comma-separated list of the three colors to use" +
  261. " to draw the top-level package, the target" +
  262. " packages, and the host packages, in this order." +
  263. " Defaults to: 'lightblue,grey,gainsboro'")
  264. parser.add_argument("--transitive", dest="transitive", action='store_true',
  265. default=False)
  266. parser.add_argument("--no-transitive", dest="transitive", action='store_false',
  267. help="Draw (do not draw) transitive dependencies")
  268. parser.add_argument("--direct", dest="direct", action='store_true', default=True,
  269. help="Draw direct dependencies (the default)")
  270. parser.add_argument("--reverse", dest="direct", action='store_false',
  271. help="Draw reverse dependencies")
  272. parser.add_argument("--quiet", '-q', dest="quiet", action='store_true',
  273. help="Quiet")
  274. parser.add_argument("--flat-list", '-f', dest="flat_list", action='store_true', default=False,
  275. help="Do not draw graph, just print a flat list")
  276. return parser.parse_args()
  277. def main():
  278. args = parse_args()
  279. check_only = args.check_only
  280. logging.basicConfig(stream=sys.stderr, format='%(message)s',
  281. level=logging.WARNING if args.quiet else logging.INFO)
  282. if args.outfile is None:
  283. outfile = sys.stdout
  284. else:
  285. if check_only:
  286. logging.error("don't specify outfile and check-only at the same time")
  287. sys.exit(1)
  288. outfile = open(args.outfile, "w")
  289. if args.package is None:
  290. mode = MODE_FULL
  291. else:
  292. mode = MODE_PKG
  293. rootpkg = args.package
  294. if args.stop_list is None:
  295. stop_list = []
  296. else:
  297. stop_list = args.stop_list
  298. if args.exclude_list is None:
  299. exclude_list = []
  300. else:
  301. exclude_list = args.exclude_list
  302. if args.direct:
  303. get_depends_func = brpkgutil.get_depends
  304. arrow_dir = "forward"
  305. else:
  306. if mode == MODE_FULL:
  307. logging.error("--reverse needs a package")
  308. sys.exit(1)
  309. get_depends_func = brpkgutil.get_rdepends
  310. arrow_dir = "back"
  311. draw_graph = not args.flat_list
  312. # Get the colors: we need exactly three colors,
  313. # so no need not split more than 4
  314. # We'll let 'dot' validate the colors...
  315. colors = args.colors.split(',', 4)
  316. if len(colors) != 3:
  317. logging.error("Error: incorrect color list '%s'" % args.colors)
  318. sys.exit(1)
  319. # In full mode, start with the result of get_targets() to get the main
  320. # targets and then use get_all_depends() for all targets
  321. if mode == MODE_FULL:
  322. targets = get_targets()
  323. dependencies = []
  324. allpkgs.append('all')
  325. filtered_targets = []
  326. for tg in targets:
  327. # Skip uninteresting targets
  328. if tg in TARGET_EXCEPTIONS:
  329. continue
  330. dependencies.append(('all', tg))
  331. filtered_targets.append(tg)
  332. deps = get_all_depends(filtered_targets, get_depends_func)
  333. if deps is not None:
  334. dependencies += deps
  335. rootpkg = 'all'
  336. # In pkg mode, start directly with get_all_depends() on the requested
  337. # package
  338. elif mode == MODE_PKG:
  339. dependencies = get_all_depends([rootpkg], get_depends_func)
  340. # Make the dependencies a dictionnary { 'pkg':[dep1, dep2, ...] }
  341. dict_deps = {}
  342. for dep in dependencies:
  343. if dep[0] not in dict_deps:
  344. dict_deps[dep[0]] = []
  345. dict_deps[dep[0]].append(dep[1])
  346. check_circular_deps(dict_deps)
  347. if check_only:
  348. sys.exit(0)
  349. dict_deps = remove_extra_deps(dict_deps, args.transitive)
  350. dict_version = brpkgutil.get_version([pkg for pkg in allpkgs
  351. if pkg != "all" and not pkg.startswith("root")])
  352. # Start printing the graph data
  353. if draw_graph:
  354. outfile.write("digraph G {\n")
  355. print_pkg_deps(outfile, dict_deps, dict_version, stop_list, exclude_list,
  356. arrow_dir, draw_graph, 0, args.depth, rootpkg, colors)
  357. if draw_graph:
  358. outfile.write("}\n")
  359. else:
  360. outfile.write("\n")
  361. if __name__ == "__main__":
  362. sys.exit(main())