graph-depends 15 KB

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