summaryrefslogtreecommitdiffstats
path: root/cron-jobs/check_archlinux/check_packages.py
blob: cb7eae4e138c836a1e6efdfdb3bc7a633b385e04 (plain)
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
#!/usr/bin/python
#
# check_archlinux.py
#
# Original script by Scott Horowitz <stonecrest@gmail.com>
# Rewritten by Xavier Chantry <shiningxc@gmail.com>
#
# This script currently checks for a number of issues in your ABS tree:
#   1. Directories with missing PKGBUILDS
#   2. Invalid PKGBUILDs (bash syntax error for instance)
#   3. PKGBUILD names that don't match their directory
#   4. Duplicate PKGBUILDs
#   5. Valid arch's in PKGBUILDS
#   6. Missing (make-)dependencies
#   7. Hierarchy of repos (e.g., that a core package doesn't depend on
#      a non-core package)
#   8. Circular dependencies

import os,re,commands,getopt,sys,tarfile,alpm
import pdb

DBEXT='.db.tar.gz'

packages = {} # pkgname : PacmanPackage
provisions = {} # provision : PacmanPackage
pkgdeps,makepkgdeps = {},{} # pkgname : list of the PacmanPackage dependencies
invalid_pkgbuilds = []
missing_pkgbuilds = []
dups = []

dbonly = []
absonly = []

mismatches = []
missing_deps = []
missing_makedeps = []
invalid_archs = []
dep_hierarchy = []
makedep_hierarchy = []
circular_deps = [] # pkgname>dep1>dep2>...>pkgname
checked_deps = []

class PacmanPackage:
	def __init__(self):
		self.name,self.version = "",""
		self.base = ""
		self.path,self.repo = "",""
		self.deps,self.makedeps = [],[]
		self.provides,self.conflicts = [],[]
		self.archs = []

class Depend:
	def __init__(self,name,version,mod):
		self.name = name
		self.version = version
		self.mod = mod

def parse_pkgbuilds(repos,arch):
	for absroot in absroots:
		for repo in repos:
			cmd = os.path.dirname(os.path.realpath(sys.argv[0])) + '/parse_pkgbuilds.sh '
			cmd += arch + ' ' + absroot + '/' + repo
			(status,output) = commands.getstatusoutput(cmd)
			if status != 0:
				print "Error : failed to run '%s'" % cmd
				sys.exit()
			parse_data(repo,output)

def parse_data(repo,data):
	attrname = None

	for line in data.split('\n'):
		if line.startswith('%'):
			attrname = line.strip('%').lower()
		elif line.strip() == '':
			attrname = None
		elif attrname == "invalid":
			if repo in repos:
				invalid_pkgbuilds.append(line)
		elif attrname == "missing":
			if repo in repos:
				missing_pkgbuilds.append(line)
		elif attrname == "name":
			pkg = PacmanPackage()
			pkg.name = line
			pkg.repo = repo
			dup = None
			if packages.has_key(pkg.name):
				dup = packages[pkg.name]
			packages[pkg.name] = pkg
		elif attrname == "base":
			pkg.base = line
		elif attrname == "version":
			pkg.version = line
		elif attrname == "path":
			pkg.path = line
			if dup != None and (pkg.repo in repos or dup.repo in repos):
				dups.append(pkg.path + " vs. " + dup.path)
		elif attrname == "arch":
			pkg.archs.append(line)
		elif attrname == "depends":
			pkg.deps.append(line)
		elif attrname == "makedepends":
			pkg.makedeps.append(line)
		elif attrname == "conflicts":
			pkg.conflicts.append(line)
		elif attrname == "provides":
			pkg.provides.append(line)
			provname=line.split("=")[0]
			if not provisions.has_key(provname):
				provisions[provname] = []
			provisions[provname].append(pkg)

def parse_dbs(repos,arch):
	dbpkgs = {}
	for repo in repos:
		pkgs = set([])
		db = tarfile.open(os.path.join(repodir,repo,'os',arch,repo + DBEXT))
		for line in db.getnames():
			if not '/' in line:
				pkgs.add(line.rsplit('-',2)[0])
		dbpkgs[repo] = pkgs
	return(dbpkgs)

def splitdep(dep):
	name = dep
	version = ""
	mod = ""
	for char in (">=", "<=", "=", ">", "<"):
		pos = dep.find(char)
		if pos > -1:
			name = dep[:pos]
			version = dep[pos:].replace(char, "")
			mod = char
			break
	return Depend(name,version,mod)

def splitprov(prov):
	name = prov
	version = ""
	pos = prov.find("=")
	if pos > -1:
		name = prov[:pos]
		version = prov[pos:].replace("=", "")
	return (name,version)

def vercmp(v1,mod,v2):
	res = alpm.vercmp(v1,v2)
	if res == 0:
		return (mod.find("=") > -1)
	elif res < 0:
		return (mod.find("<") > -1)
	elif res > 0:
		return (mod.find(">") > -1)
	return False


def depcmp(name,version,dep):
	if name != dep.name:
		return False
	if dep.version == "" or dep.mod == "":
		return True
	if version == "":
		return False
	return vercmp(version,dep.mod,dep.version)

def provcmp(pkg,dep):
	for prov in pkg.provides:
		(provname,provver) = splitprov(prov)
		if depcmp(provname,provver,dep):
			return True
	return False

def verify_dep(dep):
	dep = splitdep(dep)
	if packages.has_key(dep.name):
		pkg = packages[dep.name]
		if depcmp(pkg.name,pkg.version,dep):
			return [pkg]
	if provisions.has_key(dep.name):
		provlist = provisions[dep.name]
		results = []
		for prov in provlist:
			if provcmp(prov,dep):
				results.append(prov)
		return results
	return []

def verify_deps(name,repo,deps):
	pkg_deps = []
	missdeps = []
	hierarchy = []
	for dep in deps:
		pkglist = verify_dep(dep)
		if pkglist == []:
			missdeps.append(repo + "/" + name + " --> '" + dep + "'")
		else:
			valid_repos = get_repo_hierarchy(repo)
			pkgdep = None
			for pkg in pkglist:
				if pkg.repo in valid_repos:
					pkgdep = pkg
					break
			if not pkgdep:
				pkgdep = pkglist[0]
				hierarchy.append((repo,name,pkgdep))

			pkg_deps.append(pkgdep)

	return (pkg_deps,missdeps,hierarchy)

def compute_deplist(pkg):
	list = []
	stack = [pkg]
	while stack != []:
		dep = stack.pop()
		if pkgdeps.has_key(dep):
			for dep2 in pkgdeps[dep]:
				if dep2 not in list:
					list.append(dep2)
					stack.append(dep2)
		if makepkgdeps.has_key(dep):
			for dep2 in makepkgdeps[dep]:
				if dep2 not in list:
					list.append(dep2)
					stack.append(dep2)
	return list

def check_hierarchy(deph):
	hierarchy = []
	for (repo,name,pkgdep) in deph:
		deplist = compute_deplist(pkgdep)
		valid_repos = get_repo_hierarchy(repo)
		extdeps = []
		for dep in deplist:
			if dep.repo not in valid_repos:
				extdeps.append(dep.name)
		string = repo + "/" + name + " depends on " + pkgdep.repo + "/" + pkgdep.name + " ("
		string += "%s extra (make)deps to pull" % len(extdeps)
		if 0 < len(extdeps) < 10:
			string += " : " +  ' '.join(extdeps)
		string += ")"
		hierarchy.append(string)
	return hierarchy

def get_repo_hierarchy(repo):
	repo_hierarchy = {'core': ['core'], \
		'extra': ['core', 'extra'], \
		'community': ['core', 'extra', 'community']}
	if repo_hierarchy.has_key(repo):
		return repo_hierarchy[repo]
	else:
		return ['core','extra','community']

def verify_archs(name,repo,archs):
	valid_archs = ['any', 'i686', 'x86_64']
	invalid_archs = []
	for arch in archs:
		if arch not in valid_archs:
			invalid_archs.append(repo + "/" + name + " --> " + arch)
	return invalid_archs

def find_scc(packages):
	# reset all variables
	global index,S,pkgindex,pkglowlink
	index = 0
	S = []
	pkgindex = {}
	pkglowlink = {}
	cycles = []
	for pkg in packages:
		tarjan(pkg)

def tarjan(pkg):
	global index,S,pkgindex,pkglowlink,cycles
	pkgindex[pkg] = index
	pkglowlink[pkg] = index
	index += 1
	checked_deps.append(pkg)
	S.append(pkg)
	if pkgdeps.has_key(pkg):
		deps = pkgdeps[pkg]
	else:
		print pkg.name
		deps = []
	for dep in deps:
		if not pkgindex.has_key(dep):
			tarjan(dep)
			pkglowlink[pkg] = min(pkglowlink[pkg],pkglowlink[dep])
		elif dep in S:
			pkglowlink[pkg] = min(pkglowlink[pkg],pkgindex[dep])
	if pkglowlink[pkg] == pkgindex[pkg]:
		dep = S.pop()
		if pkg == dep:
			return
		path = pkg.name
		while pkg != dep:
			path = dep.repo + "/" + dep.name + ">" + path
			dep = S.pop()
		path = dep.name + ">" + path
		if pkg.repo in repos:
			circular_deps.append(path)

def print_heading(heading):
	print ""
	print "=" * (len(heading) + 4)
	print "= " + heading + " ="
	print "=" * (len(heading) + 4)

def print_subheading(subheading):
	print ""
	print subheading
	print "-" * (len(subheading) + 2)

def print_missdeps(pkgname,missdeps) :
	for d in missdeps:
		print pkgname + " : " + d

def print_result(list, subheading):
	if len(list) > 0:
		list.sort()
		print_subheading(subheading)
		for item in list:
			print item

def print_results():
	print_result(missing_pkgbuilds, "Missing PKGBUILDs")
	print_result(invalid_pkgbuilds, "Invalid PKGBUILDs")
	print_result(mismatches, "Mismatched Pkgnames")
	print_result(dups, "Duplicate PKGBUILDs")
	print_result(invalid_archs, "Invalid Archs")
	print_result(missing_deps, "Missing Dependencies")
	print_result(missing_makedeps, "Missing Makedepends")
	print_result(dep_hierarchy, "Repo Hierarchy for Dependencies")
	print_result(makedep_hierarchy, "Repo Hierarchy for Makedepends")
	print_result(circular_deps, "Circular Dependencies")
	print_result(dbonly, "Packages found in db, but not in tree")
	print_result(absonly,"Packages found in tree, but not in db")
	print_subheading("Summary")
	print "Missing PKGBUILDs:                    ", len(missing_pkgbuilds)
	print "Invalid PKGBUILDs:                    ", len(invalid_pkgbuilds)
	print "Mismatching PKGBUILD names:           ", len(mismatches)
	print "Duplicate PKGBUILDs:                  ", len(dups)
	print "Invalid archs:                        ", len(invalid_archs)
	print "Missing (make)dependencies:           ", len(missing_deps)+len(missing_makedeps)
	print "Repo hierarchy problems:              ", len(dep_hierarchy)+len(makedep_hierarchy)
	print "Circular dependencies:                ", len(circular_deps)
	print "In db, but not in tree:               ", len(dbonly)
	print "In tree, but not in db:               ", len(absonly)
	print ""

def print_usage():
	print ""
	print "Usage: ./check_packages.py [OPTION]"
	print ""
	print "Options:"
	print "  --abs-tree=<path[,path]>      Check the specified tree(s) (default : /var/abs)"
	print "  --repos=<r1,r2,...>           Check the specified repos (default : core,extra)"
	print "  --arch=<i686|x86_64>          Check the specified arch (default : i686)"
	print "  --repo-dir=<path>             Check the dbs at the specified path (default : /srv/ftp)"
	print "  -h, --help                    Show this help and exit"
	print ""
	print "Examples:"
	print "\n  Check core and extra in existing abs tree:"
	print "    ./check_packages.py --abs-tree=/var/abs --repos=core,extra --arch=i686"
	print "\n  Check community:"
	print "    ./check_packages.py --abs-tree=/var/abs --repos=community --arch=i686"
	print ""

## Default path to the abs root directory
absroots = ["/var/abs"]
## Default list of repos to check
repos = ['core', 'extra']
## Default arch
arch = "i686"
## Default repodir
repodir = "/srv/ftp"

try:
	opts, args = getopt.getopt(sys.argv[1:], "", ["abs-tree=", "repos=",
	"arch=", "repo-dir="])
except getopt.GetoptError:
	print_usage()
	sys.exit()
if opts != []:
	for o, a in opts:
		if o in ("--abs-tree"):
			absroot = a.split(',')
		elif o in ("--repos"):
			repos = a.split(",")
		elif o in ("--arch"):
			arch = a
		elif o in ("--repo-dir"):
			repodir = a
		else:
			print_usage()
			sys.exit()
		if args != []:
			print_usage()
			sys.exit()

for absroot in absroots:
	if not os.path.isdir(absroot):
		print "Error : the abs tree " + absroot + " does not exist"
		sys.exit()
	for repo in repos:
		repopath = absroot + "/" + repo
		if not os.path.isdir(repopath):
			print "Error : the repository " + repo + " does not exist in " + absroot
			sys.exit()
if not os.path.isdir(repodir):
	print "Error: the repository directory %s does not exist" % repodir
	sys.exit()
for repo in repos:
	path = os.path.join(repodir,repo,'os',arch,repo + DBEXT)
	if not os.path.isfile(path):
		print "Error : repo DB %s : File not found" % path
		sys.exit()
	if not tarfile.is_tarfile(path):
		print "Error : Cant open repo DB %s, not a valid tar file" % path
		sys.exit()
# repos which need to be loaded
loadrepos = set([])
for repo in repos:
	loadrepos = loadrepos | set(get_repo_hierarchy(repo))

print_heading("Integrity Check " + arch + " of " + ",".join(repos))
print "\nPerforming integrity checks..."

print "==> parsing pkgbuilds"
parse_pkgbuilds(loadrepos,arch)

repopkgs = {}
for name,pkg in packages.iteritems():
	if pkg.repo in repos:
		repopkgs[name] = pkg

print "==> parsing db files"
dbpkgs = parse_dbs(repos,arch)

print "==> checking mismatches"
for name,pkg in repopkgs.iteritems():
	pkgdirname = pkg.path.split("/")[-1]
	if name != pkgdirname and pkg.base != pkgdirname:
		mismatches.append(name + " vs. " + pkg.path)

print "==> checking archs"
for name,pkg in repopkgs.iteritems():
	archs = verify_archs(name,pkg.repo,pkg.archs)
	invalid_archs.extend(archs)

# ugly hack to strip the weird kblic- deps
for name,pkg in packages.iteritems():
	p = re.compile('klibc-[\w\-]{27}|klibc-\*')
	pkg.deps = [dep for dep in pkg.deps if not p.match(dep)]
	pkg.makedeps = [dep for dep in pkg.makedeps if not p.match(dep)]

deph,makedeph = [],[]

print "==> checking dependencies"
for name,pkg in repopkgs.iteritems():
	(deps,missdeps,hierarchy) = verify_deps(name,pkg.repo,pkg.deps)
	pkgdeps[pkg] = deps
	missing_deps.extend(missdeps)
	deph.extend(hierarchy)

print "==> checking makedepends"
for name,pkg in repopkgs.iteritems():
	(makedeps,missdeps,hierarchy) = verify_deps(name,pkg.repo,pkg.makedeps)
	makepkgdeps[pkg] = makedeps
	missing_makedeps.extend(missdeps)
	makedeph.extend(hierarchy)

print "==> checking hierarchy"
dep_hierarchy = check_hierarchy(deph)
makedep_hierarchy = check_hierarchy(makedeph)

print "==> checking for circular dependencies"
# make sure pkgdeps is filled for every package
for name,pkg in packages.iteritems():
	if not pkgdeps.has_key(pkg):
		(deps,missdeps,_) = verify_deps(name,pkg.repo,pkg.deps)
		pkgdeps[pkg] = deps
find_scc(repopkgs.values())

print "==> checking for differences between db files and pkgbuilds"
for repo in repos:
	for pkg in dbpkgs[repo]:
		if not (pkg in repopkgs.keys() and repopkgs[pkg].repo == repo):
			dbonly.append("%s/%s" % (repo,pkg))
for name,pkg in repopkgs.iteritems():
	if not name in dbpkgs[pkg.repo]:
		absonly.append("%s/%s" % (pkg.repo,name))

print_results()