graph-depends 15 KB

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