Codebase list debian-goodies / f06492b
port to Python3 Alexandre Detiste authored 8 years ago Axel Beckert committed 7 years ago
4 changed file(s) with 89 addition(s) and 90 deletion(s). Raw diff Collapse all Expand all
0 #!/usr/bin/python
0 #!/usr/bin/python3
11
22 # Copyright (C) 2001 Matt Zimmerman <mdz@debian.org>
33 # Copyright (C) 2007,2010-2015 Javier Fernandez-Sanguino <jfs@debian.org>
8585 # Process options
8686 try:
8787 opts, args = getopt.getopt(sys.argv[1:], "hvpab:i:ne:", ["help", "verbose", "packages", "all", "blacklist", "ignore", "nolsof", "excludepid"])
88 except getopt.GetoptError, err:
88 except getopt.GetoptError as err:
8989 # print help information and exit:
90 print str(err) # will print something like "option -x not recognized"
90 print(err) # will print something like "option -x not recognized"
9191 usage()
9292 sys.exit(2)
9393
142142 # Check if we have lsof, if not, use an alternative mechanism
143143 if not find_cmd('lsof') or not useLsof:
144144 if verbose and not find_cmd('lsof'):
145 print "[DEBUG] Lsof is not available in the system. Using alternative mechanism."
145 print("[DEBUG] Lsof is not available in the system. Using alternative mechanism.")
146146 toRestart = procfilescheck(blacklist = blacklist, excludepidlist = excludepidlist)
147147 else:
148148 toRestart = lsoffilescheck(blacklist = blacklist)
149149
150150
151 print "Found %d processes using old versions of upgraded files" % len(toRestart)
151 print("Found %d processes using old versions of upgraded files" % len(toRestart))
152152
153153 if len(toRestart) == 0:
154154 sys.exit(0)
159159 programs[process.program].append(process)
160160
161161 if len(programs) == 1:
162 print "(%d distinct program)" % len(programs)
162 print("(%d distinct program)" % len(programs))
163163 else:
164 print "(%d distinct programs)" % len(programs)
164 print("(%d distinct programs)" % len(programs))
165165
166166 #services Verbose information
167167 if verbose:
168168 for process in toRestart:
169 print "[DEBUG] Process %s (PID: %d) " % (process.program, process.pid)
169 print("[DEBUG] Process %s (PID: %d) " % (process.program, process.pid))
170170 process.listDeleted()
171171
172172 packages = {}
173173 diverted = None
174174
175 dpkgQuery = ["dpkg-query", "--search"] + programs.keys()
175 dpkgQuery = ["dpkg-query", "--search"] + list(programs.keys())
176176 if verbose:
177 print "[DEBUG] Running:%s" % dpkgQuery
177 print("[DEBUG] Running:%s" % dpkgQuery)
178178 dpkgProc = subprocess.Popen(dpkgQuery, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
179179 env = lc_all_c_env)
180180 while True:
182182 if not line:
183183 break
184184 if verbose:
185 print "[DEBUG] Reading line from dpkg-query: %s" % line
185 print("[DEBUG] Reading line from dpkg-query: %s" % line)
186186 if line.startswith('local diversion'):
187187 continue
188188 if not ':' in line:
207207 try:
208208 packages[packagename].processes.extend(programs[program])
209209 if verbose:
210 print "[DEBUG] Found package %s for program %s" % (packagename, program)
210 print("[DEBUG] Found package %s for program %s" % (packagename, program))
211211 except KeyError:
212212 sys.stderr.write ('checkrestart (program not found): %s: %s\n' % (packagename, program))
213213 sys.stdout.flush()
220220 for i in ignorelist:
221221 if i in packages:
222222 if verbose:
223 print "[DEBUG] Removing %s from the package list (ignored)" % (i)
223 print("[DEBUG] Removing %s from the package list (ignored)" % (i))
224224 try:
225225 del packages[i]
226226 except KeyError:
227227 continue
228228
229 print "(%d distinct packages)" % len(packages)
229 print("(%d distinct packages)" % len(packages))
230230
231231 if len(packages) == 0:
232 print "No packages seem to need to be restarted."
233 print "(please read checkrestart(1))"
232 print("No packages seem to need to be restarted.")
233 print("(please read checkrestart(1))")
234234 sys.exit(0)
235235
236 for package in packages.values():
236 for package in list(packages.values()):
237237 dpkgQuery = ["dpkg-query", "--listfiles", package.name]
238238 if verbose:
239 print "[DEBUG] Running:%s" % dpkgQuery
239 print("[DEBUG] Running:%s" % dpkgQuery)
240240 dpkgProc = subprocess.Popen(dpkgQuery, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
241241 env = lc_all_c_env)
242242 while True:
251251 # If running on a systemd system, extract the systemd's service files from the package
252252 if is_systemd and path.startswith('/lib/systemd/system/') and path.endswith('.service') and path.find('.wants') == -1:
253253 # Read the service file and make sure it is not of type 'oneshot'
254 servicefile = open (path)
254 servicefile = open (path)
255255 is_oneshot = False
256 for line in servicefile.readlines ():
257 if line.find ('Type=oneshot') > 0:
258 is_oneshot = True
259 continue
260 servicefile.close ()
256 for line in servicefile.readlines():
257 if line.find ('Type=oneshot') > 0:
258 is_oneshot = True
259 continue
260 servicefile.close ()
261261 if not is_oneshot:
262262 package.systemdservice.add(path[20:])
263263 sys.stdout.flush()
274274 nonrestartable = []
275275 restartInitCommands = []
276276 restartServiceCommands = []
277 for package in packages.values():
277 for package in list(packages.values()):
278278 if len(package.initscripts) > 0:
279279 restartable.append(package)
280 restartInitCommands.extend(map(lambda s: 'service ' + s + ' restart', package.initscripts))
280 restartInitCommands.extend(['service ' + s + ' restart' for s in package.initscripts])
281281 elif len(package.systemdservice) > 0:
282282 restartable.append(package)
283 restartServiceCommands.extend(map(lambda s: 'systemctl restart ' + s, package.systemdservice))
283 restartServiceCommands.extend(['systemctl restart ' + s for s in package.systemdservice])
284284 else:
285285 nonrestartable.append(package)
286286
287287 if len(restartable) > 0:
288 print
289 print "Of these, %d seem to contain systemd service definitions or init scripts which can be used to restart them." % len(restartable)
288 print()
289 print("Of these, %d seem to contain systemd service definitions or init scripts which can be used to restart them." % len(restartable))
290290 # TODO - consider putting this in a --verbose option
291 print "The following packages seem to have definitions that could be used\nto restart their services:"
291 print("The following packages seem to have definitions that could be used\nto restart their services:")
292292 for package in restartable:
293 print package.name + ':'
293 print(package.name + ':')
294294 for process in package.processes:
295 print "\t%s\t%s" % (process.pid,process.program)
295 print("\t%s\t%s" % (process.pid,process.program))
296296
297297 if len(restartServiceCommands)>0:
298 print
299 print "These are the systemd services:"
300 print '\n'.join(restartServiceCommands)
301 print
298 print()
299 print("These are the systemd services:")
300 print('\n'.join(restartServiceCommands))
301 print()
302302
303303 if len(restartInitCommands)>0:
304 print "These are the initd scripts:"
305 print '\n'.join(restartInitCommands)
306 print
304 print("These are the initd scripts:")
305 print('\n'.join(restartInitCommands))
306 print()
307307
308308 if len(nonrestartable) == 0:
309309 sys.exit(0)
310310
311311 # TODO - consider putting this in a --verbose option
312 print "These processes (%d) do not seem to have an associated init script to restart them:" %len(nonrestartable)
312 print("These processes (%d) do not seem to have an associated init script to restart them:" %len(nonrestartable))
313313 for package in nonrestartable:
314 print package.name + ':'
314 print(package.name + ':')
315315 for process in package.processes:
316 print "\t%s\t%s" % (process.pid,process.program)
316 print("\t%s\t%s" % (process.pid,process.program))
317317
318318 def lsoffilescheck(blacklist = None):
319319 # Use LSOF to extract the list of deleted files
354354 # Save the descriptor for later comparison
355355 process.descriptors.append(data)
356356
357 toRestart = filter(lambda process: process.needsRestart(blacklist),
358 processes.values())
357 toRestart = [process for process in list(processes.values()) if process.needsRestart(blacklist)]
359358 return toRestart
360359
361360 def procfilescheck(blacklist = None, excludepidlist = None):
395394 # print pid + ': ' + ', '.join(foundfiles)
396395 process.files = foundfiles
397396
398 toRestart = filter(lambda process: process.needsRestart(blacklist),
399 processes.values())
397 toRestart = [process for process in list(processes.values()) if process.needsRestart(blacklist)]
400398 return toRestart
401399
402400
409407 file_in_package = False
410408 file_regexp = False
411409 if verbose:
412 print "[DEBUG] Checking if file %s belongs to any package" % f
410 print("[DEBUG] Checking if file %s belongs to any package" % f)
413411 # First check if the file exists
414412 if not os.path.exists(f):
415413 if ( f.startswith('/lib/') or f.startswith('/usr/lib/') ) and re.compile("\.so[\d.]+$"):
428426 # If it exists, run dpkg-query
429427 dpkgQuery = ["dpkg-query", "--search", f ]
430428 if verbose:
431 print "[DEBUG] Running:%s" % dpkgQuery
429 print("[DEBUG] Running:%s" % dpkgQuery)
432430 dpkgProc = subprocess.Popen(dpkgQuery, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
433431 env = lc_all_c_env, close_fds=True)
434432 dpkgProc.wait()
435433 if verbose:
436 print "[DEBUG] Running:%s" % dpkgQuery
434 print("[DEBUG] Running:%s" % dpkgQuery)
437435 for line in dpkgProc.stdout.readlines():
438436 line = line.strip()
439437 if line.find('no path found matching pattern ' + f) > 0:
445443 break
446444
447445 if file_in_package and verbose:
448 print "[DEBUG] YES: File belongs to package %s" % package
446 print("[DEBUG] YES: File belongs to package %s" % package)
449447 if not file_in_package and verbose:
450 print "[DEBUG] NO: File does not belongs to any package"
448 print("[DEBUG] NO: File does not belongs to any package")
451449 return file_in_package
452450
453451 # Tells if a file has to be considered a deleted file
503501 return 0
504502 # Skip nagios spool files
505503 if f.startswith('/var/lib/nagios3/spool/checkresults/'):
506 return 0
504 return 0
507505 # Skip Postgresql files
508506 if f.startswith('/var/lib/postgresql/'):
509507 return 0
546544 # <http://bugs.debian.org/264985> for more information.
547545
548546 numeric = re.compile(r'\d+')
549 toRestart = map (delmaps, map (string.atoi, filter (numeric.match, os.listdir('/proc'))))
547 toRestart = list(map (delmaps, list(map (string.atoi, list(filter (numeric.match, os.listdir('/proc')))))))
550548 return toRestart
551549
552550 def delmaps (pid):
575573 try:
576574 if os.stat (file)[stat.ST_INO] != inode:
577575 process = processes.setdefault(pid,Process(int(pid)))
578 except OSError, (e, strerror):
576 except OSError as e_tuple:
577 (e, strerror) = e_tuple.args
579578 if e == errno.ENOENT:
580579 process = processes.setdefault(pid,Process(int(pid)))
581580 else:
582581 sys.stderr.write ('checkrestart (psdel): %s %s: %s\n' % (SysProcess.get(pid).info (), file, os.strerror (e)))
583582 else:
584 print 'checkrestart (psdel): Error parsing "%s"' % (line [0:-1])
583 print('checkrestart (psdel): Error parsing "%s"' % (line [0:-1]))
585584 maps.close ()
586585
587586 return process
663662 if m:
664663 # store the real full path of script as the program
665664 self.program = m.group(1)
666 except OSError, e:
665 except OSError as e:
667666 if e.errno != errno.ENOENT:
668667 if self.pid == 1:
669668 sys.stderr.write("Found unreadable pid 1. Assuming we're under vserver and continuing.\n")
711710 if isdeletedFile(f):
712711 listfiles.append(f)
713712 if listfiles != []:
714 print "List of deleted files in use:"
713 print("List of deleted files in use:")
715714 for file in listfiles:
716 print "\t" + file
715 print("\t" + file)
717716
718717 # Check if a process needs to be restarted, previously we would
719718 # just check if it used libraries named '.dpkg-new' since that's
724723 def needsRestart(self, blacklist = None):
725724 for f in self.files:
726725 if isdeletedFile(f, blacklist):
727 return 1
728 for f in self.links:
729 if f == 0:
730 return 1
726 return 1
727 for f in self.links:
728 if f == 0:
729 return 1
731730 return 0
732731
733732 class Package:
1313 Depends: curl,
1414 dctrl-tools | grep-dctrl,
1515 perl,
16 python (>= 2.4),
16 python3,
1717 whiptail | dialog,
1818 ${misc:Depends}
1919 Recommends: lsof
0 #!/usr/bin/python
0 #!/usr/bin/python3
11
22 # popbugs - Find RC bugs in packages you commonly use
33 # Copyright (C) 2001-2004 Matt Zimmerman <mdz@debian.org>
2222 import sys
2323 import re
2424 import os
25 import urllib2
25 import urllib.request, urllib.error, urllib.parse
2626 import tempfile
2727 import getopt
2828
5353 if len(args) >= 1:
5454 popconfile = args[0]
5555 if not os.path.exists(popconfile):
56 sys.stderr.write('''
56 sys.stderr.write('''
5757 I cannot find the popularity-contest data you pointed me to.
5858 This program requires the data collected from popularity-contest
5959 in order to work.
9696 class Package:
9797 def __init__(self, name, atime):
9898 self.name = name
99 self.atime = atime
99 self.atime = int(atime)
100100
101101 packages = {}
102102 pkglist = []
117117 # continue
118118
119119 if debug:
120 print "POPCON: Adding package " + package
120 print("POPCON: Adding package " + package)
121121 packages[package] = Package(package,atime)
122122 pkglist.append(packages[package])
123123
124124 popcon.close()
125125
126 page = urllib2.urlopen(bugurl).readlines()
126 page = urllib.request.urlopen(bugurl).readlines()
127127
128128 while page:
129 line = page.pop(0)
129 line = page.pop(0).decode('utf-8')
130130 if line.startswith('<div'):
131131 break
132132 output.write(line)
133133
134134 packagere = re.compile('.*<a name="([^"]+)"><strong>Package:.*')
135135 while page:
136 m = packagere.match(page[0])
136 m = packagere.match(page[0].decode('utf-8'))
137137 if m:
138138 html = ''
139139 while page:
140 line = page.pop(0)
140 line = page.pop(0).decode('utf-8')
141141 html += line
142142
143143 if line == '\n' or (page and packagere.match(page[0])):
146146
147147 pkgname = m.group(1)
148148 if debug:
149 print "REGEX: Parsing package " + pkgname
149 print("REGEX: Parsing package " + pkgname)
150150
151151 if pkgname in packages:
152152 if debug:
153 print "REGEX: Package " + pkgname + "is in packages"
153 print("REGEX: Package " + pkgname + "is in packages")
154154 packages[pkgname].html = html
155155 else:
156 if page[0].startswith('<hr>'):
156 if page[0].startswith(bytes('<hr>', 'ascii')):
157157 break
158158 page.pop(0)
159159
160 pkglist.sort(lambda a,b: -cmp(a.atime,b.atime))
160 pkglist.sort(key=lambda k: -k.atime)
161161 for package in pkglist:
162162 if hasattr(package,'html'):
163163 output.write(package.html)
164164 output.write('\n')
165165
166 output.writelines(page)
166 while page:
167 line = page.pop(0).decode('utf-8')
168 output.write(line)
167169
168170 output.flush()
169171
0 #! /usr/bin/python
0 #!/usr/bin/python3
11 # which-pkg-broke: help find offending packages when something breaks
22 # Placed in the public domain by Bill Gribble <grib@billgribble.com>
33
1212 apt_cache = subprocess.Popen(
1313 ['apt-cache', 'depends', pkg],
1414 stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
15 universal_newlines=True,
1516 env={} # force POSIX locale
1617 )
1718 deps = []
18 myline = apt_cache.stdout.readline()
19 while(myline != ''):
20 elts = map(strip, myline.split(':'))
19 for myline in apt_cache.stdout:
20 elts = list(s.strip() for s in myline.split(':'))
2121 if len(elts) == 2:
2222 how, pkg = elts
2323 how = how.replace('|', '')
2424 if how in ('Depends', 'PreDepends'):
2525 deps.append(pkg)
26 myline = apt_cache.stdout.readline()
2726 apt_cache.wait()
2827 return deps
2928
3938 deps[c] = 1
4039 ignore[i] = 1
4140
42 dlist = deps.keys()
41 dlist = list(deps.keys())
4342 return dlist
4443
4544
4847 dpkg_arch = subprocess.Popen(
4948 ['dpkg', '--print-architecture'],
5049 stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
50 universal_newlines=True,
5151 env={} # force POSIX locale
5252 )
5353 for arch in dpkg_arch.stdout.readlines():
5757 dpkg_archs = subprocess.Popen(
5858 ['dpkg', '--print-foreign-architecture'],
5959 stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
60 universal_newlines=True,
6061 env={} # force POSIX locale
6162 )
6263 for arch in dpkg_archs.stdout.readlines():
8182 try:
8283 times.append([pkg, os.stat(listfile)[ST_MTIME]])
8384 except OSError:
84 print "Package", pkg, "has no install time info"
85 print("Package", pkg, "has no install time info")
8586
8687 return times
8788
8889 def what_broke(pname):
89 def sortfun(a, b):
90 return cmp(a[1], b[1])
91
9290 pkgs = [ pname ]
9391 pkgs.extend(alldeps(sys.argv[1], {}))
9492
9795 itimes = []
9896 for p in pkgs:
9997 itimes.extend(pkginstalltime(p, architectures))
100 itimes.sort(sortfun)
98 itimes.sort(key=lambda k: k[1])
10199 for i in itimes:
102100 p, t = i
103101 if t is not None:
104 print ljust(p, 54), time.asctime(time.localtime(float(t)))
102 print(p.ljust(54), time.asctime(time.localtime(float(t))))
105103
106104 if (len(sys.argv) != 2 or sys.argv[1][0] == '-'):
107 print "Usage: which-pkg-broke <pkg-name>"
105 print("Usage: which-pkg-broke <pkg-name>")
108106 sys.exit(-1)
109107 else:
110108 what_broke(sys.argv[1])