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