graph-depends 14 KB

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