2
1

graph-depends 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. #!/usr/bin/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.
  156. def pkg_node_name(pkg):
  157. return pkg.replace("-","")
  158. TARGET_EXCEPTIONS = [
  159. "target-finalize",
  160. "target-post-image",
  161. ]
  162. # In full mode, start with the result of get_targets() to get the main
  163. # targets and then use get_all_depends() for all targets
  164. if mode == MODE_FULL:
  165. targets = get_targets()
  166. dependencies = []
  167. allpkgs.append('all')
  168. filtered_targets = []
  169. for tg in targets:
  170. # Skip uninteresting targets
  171. if tg in TARGET_EXCEPTIONS:
  172. continue
  173. dependencies.append(('all', tg))
  174. filtered_targets.append(tg)
  175. deps = get_all_depends(filtered_targets)
  176. if deps is not None:
  177. dependencies += deps
  178. rootpkg = 'all'
  179. # In pkg mode, start directly with get_all_depends() on the requested
  180. # package
  181. elif mode == MODE_PKG:
  182. dependencies = get_all_depends([rootpkg])
  183. # Make the dependencies a dictionnary { 'pkg':[dep1, dep2, ...] }
  184. dict_deps = {}
  185. for dep in dependencies:
  186. if dep[0] not in dict_deps:
  187. dict_deps[dep[0]] = []
  188. dict_deps[dep[0]].append(dep[1])
  189. # Basic cache for the results of the is_dep() function, in order to
  190. # optimize the execution time. The cache is a dict of dict of boolean
  191. # values. The key to the primary dict is "pkg", and the key of the
  192. # sub-dicts is "pkg2".
  193. is_dep_cache = {}
  194. def is_dep_cache_insert(pkg, pkg2, val):
  195. try:
  196. is_dep_cache[pkg].update({pkg2: val})
  197. except KeyError:
  198. is_dep_cache[pkg] = {pkg2: val}
  199. # Retrieves from the cache whether pkg2 is a transitive dependency
  200. # of pkg.
  201. # Note: raises a KeyError exception if the dependency is not known.
  202. def is_dep_cache_lookup(pkg, pkg2):
  203. return is_dep_cache[pkg][pkg2]
  204. # This function return True if pkg is a dependency (direct or
  205. # transitive) of pkg2, dependencies being listed in the deps
  206. # dictionary. Returns False otherwise.
  207. # This is the un-cached version.
  208. def is_dep_uncached(pkg,pkg2,deps):
  209. try:
  210. for p in deps[pkg2]:
  211. if pkg == p:
  212. return True
  213. if is_dep(pkg,p,deps):
  214. return True
  215. except KeyError:
  216. pass
  217. return False
  218. # See is_dep_uncached() above; this is the cached version.
  219. def is_dep(pkg,pkg2,deps):
  220. try:
  221. return is_dep_cache_lookup(pkg, pkg2)
  222. except KeyError:
  223. val = is_dep_uncached(pkg, pkg2, deps)
  224. is_dep_cache_insert(pkg, pkg2, val)
  225. return val
  226. # This function eliminates transitive dependencies; for example, given
  227. # these dependency chain: A->{B,C} and B->{C}, the A->{C} dependency is
  228. # already covered by B->{C}, so C is a transitive dependency of A, via B.
  229. # The functions does:
  230. # - for each dependency d[i] of the package pkg
  231. # - if d[i] is a dependency of any of the other dependencies d[j]
  232. # - do not keep d[i]
  233. # - otherwise keep d[i]
  234. def remove_transitive_deps(pkg,deps):
  235. d = deps[pkg]
  236. new_d = []
  237. for i in range(len(d)):
  238. keep_me = True
  239. for j in range(len(d)):
  240. if j==i:
  241. continue
  242. if is_dep(d[i],d[j],deps):
  243. keep_me = False
  244. if keep_me:
  245. new_d.append(d[i])
  246. return new_d
  247. # This function removes the dependency on some 'mandatory' package, like the
  248. # 'toolchain' package, or the 'skeleton' package
  249. def remove_mandatory_deps(pkg,deps):
  250. return [p for p in deps[pkg] if p not in ['toolchain', 'skeleton']]
  251. # This function will check that there is no loop in the dependency chain
  252. # As a side effect, it builds up the dependency cache.
  253. def check_circular_deps(deps):
  254. def recurse(pkg):
  255. if not pkg in list(deps.keys()):
  256. return
  257. if pkg in not_loop:
  258. return
  259. not_loop.append(pkg)
  260. chain.append(pkg)
  261. for p in deps[pkg]:
  262. if p in chain:
  263. sys.stderr.write("\nRecursion detected for : %s\n" % (p))
  264. while True:
  265. _p = chain.pop()
  266. sys.stderr.write("which is a dependency of: %s\n" % (_p))
  267. if p == _p:
  268. sys.exit(1)
  269. recurse(p)
  270. chain.pop()
  271. not_loop = []
  272. chain = []
  273. for pkg in list(deps.keys()):
  274. recurse(pkg)
  275. # This functions trims down the dependency list of all packages.
  276. # It applies in sequence all the dependency-elimination methods.
  277. def remove_extra_deps(deps):
  278. for pkg in list(deps.keys()):
  279. if not pkg == 'all':
  280. deps[pkg] = remove_mandatory_deps(pkg,deps)
  281. for pkg in list(deps.keys()):
  282. if not transitive or pkg == 'all':
  283. deps[pkg] = remove_transitive_deps(pkg,deps)
  284. return deps
  285. check_circular_deps(dict_deps)
  286. if check_only:
  287. sys.exit(0)
  288. dict_deps = remove_extra_deps(dict_deps)
  289. dict_version = brpkgutil.get_version([pkg for pkg in allpkgs
  290. if pkg != "all" and not pkg.startswith("root")])
  291. # Print the attributes of a node: label and fill-color
  292. def print_attrs(pkg):
  293. name = pkg_node_name(pkg)
  294. if pkg == 'all':
  295. label = 'ALL'
  296. else:
  297. label = pkg
  298. if pkg == 'all' or (mode == MODE_PKG and pkg == rootpkg):
  299. color = root_colour
  300. else:
  301. if pkg.startswith('host') \
  302. or pkg.startswith('toolchain') \
  303. or pkg.startswith('rootfs'):
  304. color = host_colour
  305. else:
  306. color = target_colour
  307. version = dict_version.get(pkg)
  308. if version == "virtual":
  309. outfile.write("%s [label = <<I>%s</I>>]\n" % (name, label))
  310. else:
  311. outfile.write("%s [label = \"%s\"]\n" % (name, label))
  312. outfile.write("%s [color=%s,style=filled]\n" % (name, color))
  313. # Print the dependency graph of a package
  314. def print_pkg_deps(depth, pkg):
  315. if pkg in done_deps:
  316. return
  317. done_deps.append(pkg)
  318. print_attrs(pkg)
  319. if pkg not in dict_deps:
  320. return
  321. for p in stop_list:
  322. if fnmatch(pkg, p):
  323. return
  324. if dict_version.get(pkg) == "virtual" and "virtual" in stop_list:
  325. return
  326. if pkg.startswith("host-") and "host" in stop_list:
  327. return
  328. if max_depth == 0 or depth < max_depth:
  329. for d in dict_deps[pkg]:
  330. if dict_version.get(d) == "virtual" \
  331. and "virtual" in exclude_list:
  332. continue
  333. if d.startswith("host-") \
  334. and "host" in exclude_list:
  335. continue
  336. add = True
  337. for p in exclude_list:
  338. if fnmatch(d,p):
  339. add = False
  340. break
  341. if add:
  342. outfile.write("%s -> %s [dir=%s]\n" % (pkg_node_name(pkg), pkg_node_name(d), arrow_dir))
  343. print_pkg_deps(depth+1, d)
  344. # Start printing the graph data
  345. outfile.write("digraph G {\n")
  346. done_deps = []
  347. print_pkg_deps(0, rootpkg)
  348. outfile.write("}\n")