graph-depends 14 KB

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