size-stats 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. #!/usr/bin/env python
  2. # Copyright (C) 2014 by Thomas Petazzoni <thomas.petazzoni@free-electrons.com>
  3. # This program is free software; you can redistribute it and/or modify
  4. # it under the terms of the GNU General Public License as published by
  5. # the Free Software Foundation; either version 2 of the License, or
  6. # (at your option) any later version.
  7. #
  8. # This program is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. # General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with this program; if not, write to the Free Software
  15. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. import sys
  17. import os
  18. import os.path
  19. import argparse
  20. import csv
  21. import collections
  22. import math
  23. try:
  24. import matplotlib
  25. matplotlib.use('Agg')
  26. import matplotlib.font_manager as fm
  27. import matplotlib.pyplot as plt
  28. except ImportError:
  29. sys.stderr.write("You need python-matplotlib to generate the size graph\n")
  30. exit(1)
  31. class Config:
  32. iec = False
  33. size_limit = 0.01
  34. colors = ['#e60004', '#009836', '#2e1d86', '#ffed00',
  35. '#0068b5', '#f28e00', '#940084', '#97c000']
  36. #
  37. # This function adds a new file to 'filesdict', after checking its
  38. # size. The 'filesdict' contain the relative path of the file as the
  39. # key, and as the value a tuple containing the name of the package to
  40. # which the file belongs and the size of the file.
  41. #
  42. # filesdict: the dict to which the file is added
  43. # relpath: relative path of the file
  44. # fullpath: absolute path to the file
  45. # pkg: package to which the file belongs
  46. #
  47. def add_file(filesdict, relpath, abspath, pkg):
  48. if not os.path.exists(abspath):
  49. return
  50. if os.path.islink(abspath):
  51. return
  52. sz = os.stat(abspath).st_size
  53. filesdict[relpath] = (pkg, sz)
  54. #
  55. # This function returns a dict where each key is the path of a file in
  56. # the root filesystem, and the value is a tuple containing two
  57. # elements: the name of the package to which this file belongs and the
  58. # size of the file.
  59. #
  60. # builddir: path to the Buildroot output directory
  61. #
  62. def build_package_dict(builddir):
  63. filesdict = {}
  64. with open(os.path.join(builddir, "build", "packages-file-list.txt")) as f:
  65. for l in f.readlines():
  66. pkg, fpath = l.split(",", 1)
  67. # remove the initial './' in each file path
  68. fpath = fpath.strip()[2:]
  69. fullpath = os.path.join(builddir, "target", fpath)
  70. add_file(filesdict, fpath, fullpath, pkg)
  71. return filesdict
  72. #
  73. # This function builds a dictionary that contains the name of a
  74. # package as key, and the size of the files installed by this package
  75. # as the value.
  76. #
  77. # filesdict: dictionary with the name of the files as key, and as
  78. # value a tuple containing the name of the package to which the files
  79. # belongs, and the size of the file. As returned by
  80. # build_package_dict.
  81. #
  82. # builddir: path to the Buildroot output directory
  83. #
  84. def build_package_size(filesdict, builddir):
  85. pkgsize = collections.defaultdict(int)
  86. seeninodes = set()
  87. for root, _, files in os.walk(os.path.join(builddir, "target")):
  88. for f in files:
  89. fpath = os.path.join(root, f)
  90. if os.path.islink(fpath):
  91. continue
  92. st = os.stat(fpath)
  93. if st.st_ino in seeninodes:
  94. # hard link
  95. continue
  96. else:
  97. seeninodes.add(st.st_ino)
  98. frelpath = os.path.relpath(fpath, os.path.join(builddir, "target"))
  99. if frelpath not in filesdict:
  100. print("WARNING: %s is not part of any package" % frelpath)
  101. pkg = "unknown"
  102. else:
  103. pkg = filesdict[frelpath][0]
  104. pkgsize[pkg] += st.st_size
  105. return pkgsize
  106. #
  107. # Given a dict returned by build_package_size(), this function
  108. # generates a pie chart of the size installed by each package.
  109. #
  110. # pkgsize: dictionary with the name of the package as a key, and the
  111. # size as the value, as returned by build_package_size.
  112. #
  113. # outputf: output file for the graph
  114. #
  115. def draw_graph(pkgsize, outputf):
  116. def size2string(sz):
  117. if Config.iec:
  118. divider = 1024.0
  119. prefixes = ['', 'Ki', 'Mi', 'Gi', 'Ti']
  120. else:
  121. divider = 1000.0
  122. prefixes = ['', 'k', 'M', 'G', 'T']
  123. while sz > divider and len(prefixes) > 1:
  124. prefixes = prefixes[1:]
  125. sz = sz/divider
  126. # precision is made so that there are always at least three meaningful
  127. # digits displayed (e.g. '3.14' and '10.4', not just '3' and '10')
  128. precision = int(2-math.floor(math.log10(sz))) if sz < 1000 else 0
  129. return '{:.{prec}f} {}B'.format(sz, prefixes[0], prec=precision)
  130. total = sum(pkgsize.values())
  131. labels = []
  132. values = []
  133. other_value = 0
  134. unknown_value = 0
  135. for (p, sz) in sorted(pkgsize.items(), key=lambda x: x[1]):
  136. if sz < (total * Config.size_limit):
  137. other_value += sz
  138. elif p == "unknown":
  139. unknown_value = sz
  140. else:
  141. labels.append("%s (%s)" % (p, size2string(sz)))
  142. values.append(sz)
  143. if unknown_value != 0:
  144. labels.append("Unknown (%s)" % (size2string(unknown_value)))
  145. values.append(unknown_value)
  146. if other_value != 0:
  147. labels.append("Other (%s)" % (size2string(other_value)))
  148. values.append(other_value)
  149. plt.figure()
  150. patches, texts, autotexts = plt.pie(values, labels=labels,
  151. autopct='%1.1f%%', shadow=True,
  152. colors=Config.colors)
  153. # Reduce text size
  154. proptease = fm.FontProperties()
  155. proptease.set_size('xx-small')
  156. plt.setp(autotexts, fontproperties=proptease)
  157. plt.setp(texts, fontproperties=proptease)
  158. plt.suptitle("Filesystem size per package", fontsize=18, y=.97)
  159. plt.title("Total filesystem size: %s" % (size2string(total)), fontsize=10,
  160. y=.96)
  161. plt.savefig(outputf)
  162. #
  163. # Generate a CSV file with statistics about the size of each file, its
  164. # size contribution to the package and to the overall system.
  165. #
  166. # filesdict: dictionary with the name of the files as key, and as
  167. # value a tuple containing the name of the package to which the files
  168. # belongs, and the size of the file. As returned by
  169. # build_package_dict.
  170. #
  171. # pkgsize: dictionary with the name of the package as a key, and the
  172. # size as the value, as returned by build_package_size.
  173. #
  174. # outputf: output CSV file
  175. #
  176. def gen_files_csv(filesdict, pkgsizes, outputf):
  177. total = 0
  178. for (p, sz) in pkgsizes.items():
  179. total += sz
  180. with open(outputf, 'w') as csvfile:
  181. wr = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
  182. wr.writerow(["File name",
  183. "Package name",
  184. "File size",
  185. "Package size",
  186. "File size in package (%)",
  187. "File size in system (%)"])
  188. for f, (pkgname, filesize) in filesdict.items():
  189. pkgsize = pkgsizes[pkgname]
  190. if pkgsize == 0:
  191. percent_pkg = 0
  192. else:
  193. percent_pkg = float(filesize) / pkgsize * 100
  194. percent_total = float(filesize) / total * 100
  195. wr.writerow([f, pkgname, filesize, pkgsize,
  196. "%.1f" % percent_pkg,
  197. "%.1f" % percent_total])
  198. #
  199. # Generate a CSV file with statistics about the size of each package,
  200. # and their size contribution to the overall system.
  201. #
  202. # pkgsize: dictionary with the name of the package as a key, and the
  203. # size as the value, as returned by build_package_size.
  204. #
  205. # outputf: output CSV file
  206. #
  207. def gen_packages_csv(pkgsizes, outputf):
  208. total = sum(pkgsizes.values())
  209. with open(outputf, 'w') as csvfile:
  210. wr = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
  211. wr.writerow(["Package name", "Package size",
  212. "Package size in system (%)"])
  213. for (pkg, size) in pkgsizes.items():
  214. wr.writerow([pkg, size, "%.1f" % (float(size) / total * 100)])
  215. #
  216. # Our special action for --iec, --binary, --si, --decimal
  217. #
  218. class PrefixAction(argparse.Action):
  219. def __init__(self, option_strings, dest, **kwargs):
  220. for key in ["type", "nargs"]:
  221. if key in kwargs:
  222. raise ValueError('"{}" not allowed'.format(key))
  223. super(PrefixAction, self).__init__(option_strings, dest, nargs=0,
  224. type=bool, **kwargs)
  225. def __call__(self, parser, namespace, values, option_string=None):
  226. setattr(namespace, self.dest, option_string in ["--iec", "--binary"])
  227. def main():
  228. parser = argparse.ArgumentParser(description='Draw size statistics graphs')
  229. parser.add_argument("--builddir", '-i', metavar="BUILDDIR", required=True,
  230. help="Buildroot output directory")
  231. parser.add_argument("--graph", '-g', metavar="GRAPH",
  232. help="Graph output file (.pdf or .png extension)")
  233. parser.add_argument("--file-size-csv", '-f', metavar="FILE_SIZE_CSV",
  234. help="CSV output file with file size statistics")
  235. parser.add_argument("--package-size-csv", '-p', metavar="PKG_SIZE_CSV",
  236. help="CSV output file with package size statistics")
  237. parser.add_argument("--iec", "--binary", "--si", "--decimal",
  238. action=PrefixAction,
  239. help="Use IEC (binary, powers of 1024) or SI (decimal, "
  240. "powers of 1000, the default) prefixes")
  241. parser.add_argument("--size-limit", "-l", type=float,
  242. help='Under this size ratio, files are accounted to ' +
  243. 'the generic "Other" package. Default: 0.01 (1%%)')
  244. args = parser.parse_args()
  245. Config.iec = args.iec
  246. if args.size_limit is not None:
  247. if args.size_limit < 0.0 or args.size_limit > 1.0:
  248. parser.error("--size-limit must be in [0.0..1.0]")
  249. Config.size_limit = args.size_limit
  250. # Find out which package installed what files
  251. pkgdict = build_package_dict(args.builddir)
  252. # Collect the size installed by each package
  253. pkgsize = build_package_size(pkgdict, args.builddir)
  254. if args.graph:
  255. draw_graph(pkgsize, args.graph)
  256. if args.file_size_csv:
  257. gen_files_csv(pkgdict, pkgsize, args.file_size_csv)
  258. if args.package_size_csv:
  259. gen_packages_csv(pkgsize, args.package_size_csv)
  260. if __name__ == "__main__":
  261. main()