graph-depends 13 KB

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