graph-depends 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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, depth, max_depth, pkg, colors):
  206. if pkg in done_deps:
  207. return
  208. done_deps.append(pkg)
  209. print_attrs(outfile, pkg, dict_version.get(pkg), depth, colors)
  210. if pkg not in dict_deps:
  211. return
  212. for p in stop_list:
  213. if fnmatch(pkg, p):
  214. return
  215. if dict_version.get(pkg) == "virtual" and "virtual" in stop_list:
  216. return
  217. if pkg.startswith("host-") and "host" in stop_list:
  218. return
  219. if max_depth == 0 or depth < max_depth:
  220. for d in dict_deps[pkg]:
  221. if dict_version.get(d) == "virtual" \
  222. and "virtual" in exclude_list:
  223. continue
  224. if d.startswith("host-") \
  225. and "host" in exclude_list:
  226. continue
  227. add = True
  228. for p in exclude_list:
  229. if fnmatch(d, p):
  230. add = False
  231. break
  232. if add:
  233. outfile.write("%s -> %s [dir=%s]\n" % (pkg_node_name(pkg), pkg_node_name(d), arrow_dir))
  234. print_pkg_deps(outfile, dict_deps, dict_version, stop_list, exclude_list,
  235. arrow_dir, depth + 1, max_depth, d, colors)
  236. def parse_args():
  237. parser = argparse.ArgumentParser(description="Graph packages dependencies")
  238. parser.add_argument("--check-only", "-C", dest="check_only", action="store_true", default=False,
  239. help="Only do the dependency checks (circular deps...)")
  240. parser.add_argument("--outfile", "-o", metavar="OUT_FILE", dest="outfile",
  241. help="File in which to generate the dot representation")
  242. parser.add_argument("--package", '-p', metavar="PACKAGE",
  243. help="Graph the dependencies of PACKAGE")
  244. parser.add_argument("--depth", '-d', metavar="DEPTH", dest="depth", type=int, default=0,
  245. help="Limit the dependency graph to DEPTH levels; 0 means no limit.")
  246. parser.add_argument("--stop-on", "-s", metavar="PACKAGE", dest="stop_list", action="append",
  247. help="Do not graph past this package (can be given multiple times)." +
  248. " Can be a package name or a glob, " +
  249. " 'virtual' to stop on virtual packages, or " +
  250. "'host' to stop on host packages.")
  251. parser.add_argument("--exclude", "-x", metavar="PACKAGE", dest="exclude_list", action="append",
  252. help="Like --stop-on, but do not add PACKAGE to the graph.")
  253. parser.add_argument("--colors", "-c", metavar="COLOR_LIST", dest="colors",
  254. default="lightblue,grey,gainsboro",
  255. help="Comma-separated list of the three colors to use" +
  256. " to draw the top-level package, the target" +
  257. " packages, and the host packages, in this order." +
  258. " Defaults to: 'lightblue,grey,gainsboro'")
  259. parser.add_argument("--transitive", dest="transitive", action='store_true',
  260. default=False)
  261. parser.add_argument("--no-transitive", dest="transitive", action='store_false',
  262. help="Draw (do not draw) transitive dependencies")
  263. parser.add_argument("--direct", dest="direct", action='store_true', default=True,
  264. help="Draw direct dependencies (the default)")
  265. parser.add_argument("--reverse", dest="direct", action='store_false',
  266. help="Draw reverse dependencies")
  267. return parser.parse_args()
  268. def main():
  269. args = parse_args()
  270. check_only = args.check_only
  271. logging.basicConfig(stream=sys.stderr, format='%(message)s',
  272. level=logging.INFO)
  273. if args.outfile is None:
  274. outfile = sys.stdout
  275. else:
  276. if check_only:
  277. logging.error("don't specify outfile and check-only at the same time")
  278. sys.exit(1)
  279. outfile = open(args.outfile, "w")
  280. if args.package is None:
  281. mode = MODE_FULL
  282. else:
  283. mode = MODE_PKG
  284. rootpkg = args.package
  285. if args.stop_list is None:
  286. stop_list = []
  287. else:
  288. stop_list = args.stop_list
  289. if args.exclude_list is None:
  290. exclude_list = []
  291. else:
  292. exclude_list = args.exclude_list
  293. if args.direct:
  294. get_depends_func = brpkgutil.get_depends
  295. arrow_dir = "forward"
  296. else:
  297. if mode == MODE_FULL:
  298. logging.error("--reverse needs a package")
  299. sys.exit(1)
  300. get_depends_func = brpkgutil.get_rdepends
  301. arrow_dir = "back"
  302. # Get the colors: we need exactly three colors,
  303. # so no need not split more than 4
  304. # We'll let 'dot' validate the colors...
  305. colors = args.colors.split(',', 4)
  306. if len(colors) != 3:
  307. logging.error("Error: incorrect color list '%s'" % args.colors)
  308. sys.exit(1)
  309. # In full mode, start with the result of get_targets() to get the main
  310. # targets and then use get_all_depends() for all targets
  311. if mode == MODE_FULL:
  312. targets = get_targets()
  313. dependencies = []
  314. allpkgs.append('all')
  315. filtered_targets = []
  316. for tg in targets:
  317. # Skip uninteresting targets
  318. if tg in TARGET_EXCEPTIONS:
  319. continue
  320. dependencies.append(('all', tg))
  321. filtered_targets.append(tg)
  322. deps = get_all_depends(filtered_targets, get_depends_func)
  323. if deps is not None:
  324. dependencies += deps
  325. rootpkg = 'all'
  326. # In pkg mode, start directly with get_all_depends() on the requested
  327. # package
  328. elif mode == MODE_PKG:
  329. dependencies = get_all_depends([rootpkg], get_depends_func)
  330. # Make the dependencies a dictionnary { 'pkg':[dep1, dep2, ...] }
  331. dict_deps = {}
  332. for dep in dependencies:
  333. if dep[0] not in dict_deps:
  334. dict_deps[dep[0]] = []
  335. dict_deps[dep[0]].append(dep[1])
  336. check_circular_deps(dict_deps)
  337. if check_only:
  338. sys.exit(0)
  339. dict_deps = remove_extra_deps(dict_deps, args.transitive)
  340. dict_version = brpkgutil.get_version([pkg for pkg in allpkgs
  341. if pkg != "all" and not pkg.startswith("root")])
  342. # Start printing the graph data
  343. outfile.write("digraph G {\n")
  344. print_pkg_deps(outfile, dict_deps, dict_version, stop_list, exclude_list,
  345. arrow_dir, 0, args.depth, rootpkg, colors)
  346. outfile.write("}\n")
  347. if __name__ == "__main__":
  348. sys.exit(main())