graph-depends 14 KB

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