This website requires JavaScript.
87c1c5dce97a5f255b3936530ba69a58ffda1077
swift /bin /swift-orphans
106 lines
3.9 KiB
Plaintext
2011年12月03日 07:42:08 +00:00
#!/usr/bin/env python
if __name__ == '__main__':
parser = optparse.OptionParser(usage='''%prog [options]
Lists and optionally kills orphaned Swift processes. This is done by scanning
/var/run/swift for .pid files and listing any processes that look like Swift
processes but aren't associated with the pids in those .pid files. Any Swift
processes running with the 'once' parameter are ignored, as those are usually
for full-speed audit scans and such.
Example (sends SIGTERM to all orphaned Swift processes older than two hours):
parser.add_option('-a', '--age', dest='hours', type='int', default=24,
help='look for processes at least HOURS old; default: 24')
parser.add_option('-k', '--kill', dest='signal',
help='send SIGNAL to matched processes; default: just list process '
parser.add_option('-w', '--wide', dest='wide', default=False,
action='store_true', help="don't clip the listing at 80 characters")
(options, args) = parser.parse_args()
for root, directories, files in os.walk('/var/run/swift'):
if name.endswith('.pid'):
pids.append(open(os.path.join(root, name)).read().strip())
pids.extend(subprocess.Popen(
['ps', '--ppid', pids[-1], '-o', 'pid', '--no-headers'],
stdout=subprocess.PIPE).communicate()[0].split())
for line in subprocess.Popen(
['ps', '-eo', 'etime,pid,args', '--no-headers'],
stdout=subprocess.PIPE).communicate()[0].split('\n'):
etime, pid, args = line.split(None, 2)
sys.exit('Could not process ps line %r' % line)
if (not args.startswith('/usr/bin/python /usr/bin/swift-') and
not args.startswith('/usr/bin/python /usr/local/bin/swift-')) or \
'swift-orphans' in args or \
args = args.split('-', 1)[1]
hours = int(etime[0]) * 24
sys.exit('Could not process etime value from %r' % line)
sys.exit('Could not process etime value from %r' % line)
if hours >= options.hours:
listing.append((str(hours), pid, args))
args_len = len('Command')
for hours, pid, args in listing:
hours_len = max(hours_len, len(hours))
pid_len = max(pid_len, len(pid))
args_len = max(args_len, len(args))
args_len = min(args_len, 78 - hours_len - pid_len)
print ('%%%ds %%%ds %%s' % (hours_len, pid_len)) % \
('Hours', 'PID', 'Command')
for hours, pid, args in listing:
print ('%%%ds %%%ds %%s' % (hours_len, pid_len)) % \
(hours, pid, args[:args_len])
signum = int(options.signal)
signum = getattr(signal, options.signal.upper(),
getattr(signal, 'SIG' + options.signal.upper(), None))
sys.exit('Could not translate %r to a signal number.' %
print 'Sending processes %s (%d) signal...' % (options.signal, signum),
for hours, pid, args in listing:
os.kill(int(pid), signum)