-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdpkg.py
290 lines (261 loc) · 9.3 KB
/
dpkg.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
import json
import sys
import subprocess
import os
from os import listdir
from os.path import isfile, join
from pprint import pprint
from collections import Counter
def load_json(filename):
with open(filename) as data_file:
data = json.load(data_file)
return data
def aptcache_show(name):
FNULL = open(os.devnull, 'w')
res = subprocess.Popen("apt-cache show %s" % name, shell=True,
stdout=subprocess.PIPE, stderr=FNULL).stdout.read()
new_l = []
for u in res.split("\n"):
if u.find(":")>0:
new_l.append(u.split(":",1))
new_d = dict(new_l)
return new_d
def show_depends(name, option=None):
res = apt_rdepends(name, "depends")
if option == "flat":
d_name_only = []
for k, v in res.iteritems():
d_name_only += [ x[0] for x in v['depends'] ]
return Counter(d_name_only)
else:
return res
def show_rdepends(name):
return apt_rdepends(name, "reverse")
def apt_rdepends(name, q):
""" Sample:
build-essential
Reverse Depends: abi-compliance-checker (1.99.9-2)
Reverse Depends: blends-dev (0.6.92.3ubuntu1)
Reverse Depends: critcl (3.1.9-1)
...
dkms
Reverse Depends: acpi-call-dkms (>= 1.1.0-2)
Reverse Depends: asic0x-dkms (>= 1.0.1-1)
Return: dict
e.g.
{ 'abc': { 'rdepends': [[ 'xyz', '(>= 1.0.0)' ],
[ '...', '(ubuntu1.0.1)' ]]
}
}
"""
if q == "reverse":
option = "-r"
keyname = "rdepends"
search_keyword = " Reverse Depends: "
else:
option = "depends"
keyname = "depends"
search_keyword = " Depends: "
FNULL = open(os.devnull, 'w')
res = subprocess.Popen("apt-rdepends %s %s" % (option, name), shell=True,
stdout=subprocess.PIPE, stderr=FNULL).stdout.read()
new_d = {}
p_node = ''
for u in res.split("\n"):
if u[:2] != " ":
p_node = u
continue
if u[:len(search_keyword)] == search_keyword:
#pprint("-"+u[0:19]+"-")
if u.find(":")>0:
tmp = u.split(":",1)
name_and_version = tmp[1].strip().split(' ',1)
if not p_node in new_d:
new_d[p_node] = { keyname: [] }
new_d[p_node][keyname].append(name_and_version)
return new_d
def get_names(depends):
depends = list(set([ x.split()[0] for x in depends.split(",")]))
return depends
def stats_in_csv(file_or_path, option, file4comparison=None):
a = Counter()
if os.path.isdir(file_or_path):
onlyfiles = [f for f in listdir(file_or_path) if isfile(join(file_or_path, f))]
mypath = file_or_path
else:
onlyfiles = [file_or_path]
mypath = ''
# TEMPORAL CODE FOR DEPENDENCIES
tmp_depends = []
for filename in onlyfiles:
full_path = mypath + filename
res = load_json(full_path)
name = filename.split(".")[0]
if option:
packages = res['result'][option]
c = Counter()
t_l = []
for df_fullpath, dps in packages.iteritems():
tmp = Counter(dps)
c += tmp
lib_names = list(set(list(tmp.elements())))
t_l += lib_names
#for i in lib_names:
# tmp_depends.append([df_fullpath, i, tmp[i]])
frequent_c = Counter(t_l)
#pprint(c.most_common())
#print "==================="
#pprint(frequent_c.most_common())
#print (len(packages))
dockerfile_cnt = len(packages)
package_info = {}
for k in set(frequent_c.elements()):
if k in ['debconf', 'libc6','libcomerr2','libgcc1','libx11-6','zlib1g']:
continue
info = aptcache_show(k)
package_info[k] = info
try:
size= info['Size']
except KeyError as e:
# 'virtual packages'
# https://www.debian.org/doc/packaging-manuals/virtual-package-names-list.txt
size= ''
tmp_depends.append([name, k , size, c[k],frequent_c[k],
dockerfile_cnt])
package_stat = {}
for x in frequent_c.most_common():
perc = round(x[1]/(dockerfile_cnt*1.0),1)
try:
package_stat[perc].append(x[0])
except:
package_stat[perc] = [x[0]]
# temp code for validation.
import csv
fcsv = csv.reader(open(file4comparison, "r"))
dependency = {}
dependency_stat = {}
for i in fcsv:
category = i[0]
name = i[1]
size = int(i[2] or 0)
internal_frequency = i[3]
frequency = i[4]
dependency[name] = { 'size': size,
'frequency': frequency }
perc = round(eval(frequency), 1)
while perc > 0.0:
try:
dependency_stat[perc] += size
except KeyError:
dependency_stat[perc] = size
perc -= 0.1
perc = round(perc, 1)
image_stat = []
for df_fullpath, dps in packages.iteritems():
total_lib_size_in_image = 0
ddd = {}
for x in range(1,11):
do = round(x * 0.1,1)
ddd[do] = 0
#print (ddd)
print df_fullpath, dps
for p in dps:
#print p
try:
psize = int(package_info[p]['Size'])
except:
psize = 0
if psize == 0:
continue
total_lib_size_in_image += psize
#print psize, total_lib_size_in_image
if p in dependency:
perc = round(eval(dependency[p]['frequency']),1)
print ("%s found, %.2f, %d" % (p, perc, psize))
else:
perc = 0
print ("%s not found, %.2f, %d" % (p, perc, psize))
#m = frequent_c[p]
#perc = round(m/(dockerfile_cnt*1.0),1)
while perc > 0.0:
ddd[perc] += -1 * psize
perc-=0.1
perc = round(perc,1)
#pprint(ddd)
#sys.exit()
for x in ddd:
image_stat.append([df_fullpath, x, ddd[x], total_lib_size_in_image])
for k,v in package_stat.iteritems():
asize = 0
for k1 in v:
try:
psize = int(package_info[k1]['Size'])
except:
psize = 0
asize+=psize
print "%s, %s, %d" % (k, asize, len(v))
pprint(dependency_stat)
return (image_stat)
continue
else:
packages = res['result']['dockerfiles']['packages']
c = Counter(packages)
a += c
if len(tmp_depends) > 0:
return tmp_depends
li = a.most_common(50)
for i in li:
package_name = i[0]
info = aptcache_show(package_name)
rinfo = show_rdepends(package_name)
depends_cnt = rdepends_cnt = 0
depends_names = ""
size = 0
size_all = 0
priority = ""
try:
desc = info['Description-en'] # dpkg has 'Description'
if 'Depends' in info:
depends = info['Depends']
depends_names = get_names(depends)
depends_cnt = len(depends_names)
rdepends_cnt = len(rinfo[package_name]['rdepends'])
size = info['Size'] # Not Installed-Size
priority = info['Priority']
section = info['Section']
except KeyError as e:
continue
for j in depends_names:
info_d = aptcache_show(j)
try:
#print info_d['Package'], info_d['Installed-Size']
size_all += int(info_d['Size'])
except KeyError as e:
continue
# in latex table
print ("%s & %s & %s & %s & %s & %s & %s (%s) & %s \\\\ \\hline" %
(package_name, desc, section, depends_cnt, rdepends_cnt,
", ".join(depends_names), size, size_all, priority))
return a
if __name__ == "__main__":
mypath=sys.argv[1]
opt = None
if len(sys.argv) == 3:
opt = sys.argv[2]
elif len(sys.argv) == 4:
opt = sys.argv[2]
comp_file = sys.argv[3]
a = stats_in_csv(mypath, opt, comp_file)
for i in a:
ddd=",".join(str(x) for x in i)
print (ddd)
total_count = sum(a.values())
re = a.most_common()
top_count = 0
for i,b in re:
if b == 1:
continue
top_count += b
print ("total number of packages: %s" % total_count)
print ("Percentage of 1+ used packages: %s" % (top_count * 1.0 /
total_count))