Permalink
Browse files

Fixes to manhole script for multiple manhole files/cleanup of dead ones

  • Loading branch information...
1 parent a6f138a commit 375f2295e8c850f67bc5ab5f052e46e13a02d897 @daf daf committed Jan 4, 2013
Showing with 48 additions and 2 deletions.
  1. +48 −2 scripts/manhole.py
View
@@ -6,7 +6,7 @@
__license__ = 'Apache 2.0'
def main():
- import sys, os, re
+ import sys, os, re, errno, json, socket
from pkg_resources import load_entry_point
r = re.compile('manhole-(\d+).json')
@@ -20,7 +20,53 @@ def main():
print >>sys.stderr, "No manhole files detected, specify it manually"
sys.exit(1)
elif len(mh_files) > 1:
- print >>sys.stderr, "Multiple manhole files detected, specify it manually"
+
+ def legal_manhole_file(f):
+ """
+ Helper method to check if a process exists and is likely a manhole-able container.
+
+ @return True/False if is a likely container.
+ """
+ mh_pid = int(r.search(f).group(1))
+ try:
+ os.getpgid(mh_pid)
+ except OSError as e:
+ if e.errno == errno.ESRCH:
+ return False
+ raise # unexpected, just re-raise
+
+ # the pid seems legal, now check status of sockets - the pid may be reused
+ with open(f) as ff:
+ mh_doc = json.load(ff)
+
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ try:
+ s.bind((mh_doc['ip'], mh_doc['shell_port']))
+ except socket.error as e:
+ if e.errno == errno.EADDRINUSE:
+ return True
+ raise # unexpected, re-raise
+ finally:
+ s.close()
+
+ return False
+
+ # try to see if these are active processes
+ legal_mh_files = filter(legal_manhole_file, mh_files)
+
+ if len(legal_mh_files) > 1:
+ print >>sys.stderr, "Multiple legal manhole files detected, specify it manually:", legal_mh_files
+ sys.exit(1)
+
+ # we found a single legal file, use it
+ mh_file = legal_mh_files[0]
+
+ # perform cleanup of stale files
+ dead_mh_files = [x for x in mh_files if x not in legal_mh_files]
+ for df in dead_mh_files:
+ print >>sys.stderr, "Cleaning up stale manhole file", df
+ os.unlink(df)
+
else:
mh_file = mh_files[0]

0 comments on commit 375f229

Please sign in to comment.