2
1

graph-depends 14 KB

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