#
# Mark Huang <mlhuang@cs.princeton.edu>
# Andy Bavier <acb@cs.princeton.edu>
+# Faiyaz Ahmed <faiyaza@cs.princeton.edu>
# Copyright (C) 2004-2006 The Trustees of Princeton University
#
-# $Id: BandwidthMonitor.py,v 1.1 2006/04/25 14:40:28 mlhuang Exp $
+# $Id: swapmon.py,v 1.5 2006/05/09 03:23:57 mlhuang Exp $
#
import syslog
import socket
import time
-import textwrap
-wrap = textwrap.TextWrapper()
-
# util-vserver/python/vserver.py allows us to control slices directly
# from Python
from vserver import VServer
change_thresh = 5
# Swap utilization at which the largest consumer of physical memory is reset
-reset_thresh = 85
+reset_thresh = 80
# Swap utilization at which the machine is rebooted
reboot_thresh = 95
+# Time to wait before checking slice again after reset
+reset_timeout = 15
+
+# Number of strikes before killing (strike, strike, kill)
+kill_thresh = 2
+
+# Time to wait before removing slice from kill queue (probation)
+kill_timeout = 120
+
+# Don't email the same message more than once in the same emailtimeout interval
+email_timeout = 1800
+
# Minimum physical memory utilization to be considered the largest consumer
min_thresh = 10
%(date)s %(hostname)s alarm %(slice)s
""".lstrip()
+# Message sent after a slice has been killed
+kill_subject = "pl_mom killed slice %(slice)s on %(hostname)s"
+kill_body = \
+"""
+Sometime before %(date)s, swap space was
+nearly exhausted on %(hostname)s.
+
+Slice %(slice)s was killed since it was the largest consumer of
+physical memory at %(rss)s (%(percent)4.1f%%) after repeated restarts.
+
+Please reply to this message explaining the nature of your experiment,
+and what you are doing to address the problem.
+
+%(slice)s processes prior to reset:
+
+%(table)s
+
+%(date)s %(hostname)s reset %(slice)s
+""".lstrip()
+
+
+
+class Reset:
+ """
+ Keeps track of state information for resets and kills
+
+ resettimeleft - timeout before checking for next reset
+ resetcount - number of strikes
+ killtimeleft - time out before removing from kill queue
+ {kill,reset}mail - Time of last email
+ kill - State of kill. If slice is already being killed, wait before retry.
+ """
+
+ def __init__(self,name):
+ self.name = name
+ self.resettimeleft = reset_timeout
+ self.resetcount = 0
+ self.resetmail = 0
+ self.kill = False
+ self.killtimeleft = kill_timeout
+ self.killmail = 0
+
+ def __repr__(self):
+ return self.name
+
+ def update(self):
+ # Count down for next check of reset slice.
+ if self.resettimeleft > 0:
+ self.resettimeleft -= 1
+ if debug and verbose:
+ print "%s has %s seconds in probation" \
+ %(self.name, self.killtimeleft)
+ if self.killtimeleft > 0:
+ # Count down kill probation timer (killtimeleft)
+ self.killtimeleft -= 1
+ if self.killtimeleft == 1:
+ print "%s is out of probation" % self.name
+ else:
+ # Once out of probation period (killtimeleft), remove strikes
+ self.resetcount = 0
+ self.kill = False
+
+
+ # Check to see if a slice needs to be killed. If it has rules more than kill_thresh in
+ # the probation period (kill_timeout) send an email, kill the slice.
+ def checkkill(self,params):
+ if self.killtimeleft > 0 and self.resetcount >= kill_thresh and \
+ self.kill == False:
+ self.kill = True
+ if debug:
+ print kill_subject % params
+ print kill_body % params
+ try:
+ pid = os.fork()
+ if pid == 0:
+ print "Slice %s is being killed." % self.name
+ vserver = VServer(self.name)
+ vserver.stop()
+ os._exit(0)
+ else:
+ os.waitpid(pid,0)
+ except Exception, err:
+ print "Warning: Exception received while killing slice %s: %s" \
+ % self.name, err
+ if (time.time() - self.killmail) > email_timeout:
+ slicemail(self.name, kill_subject % params, kill_body % params)
+ print "Sending KILL email for slice %s" % self.name
+ self.killmail = time.time()
+ return True
+ return False
+
+ # Reset slice after checking to see if slice is out of timeout.
+ # Increment resetcount, check to see if larger than kill_thresh.
+ def reset(self, params):
+ # If its the first reset or if its been reset before
+ # and we are out of the reset timeout.
+ if self.resetcount == 0 or self.resettimeleft == 0:
+ # Do we need to kill this slice? Check history first.
+ if self.checkkill(params):
+ return
+ # Update counters
+ self.resetcount += 1
+ self.killtimeleft = kill_timeout
+ self.resettimeleft = reset_timeout
+ print "%s has %s seconds to die and has been reset %s times" \
+ %(self.name, self.resettimeleft, self.resetcount)
+ if debug:
+ print reset_subject % params
+ print reset_body % params
+ try:
+ pid = os.fork()
+ if pid == 0:
+ print "Resetting slice " + self.name
+ vserver = VServer(self.name)
+ vserver.stop()
+ vserver.start(wait = False)
+ os._exit(0)
+ else:
+ os.waitpid(pid,0)
+ except Exception, err:
+ print "Warning: Exception received while resetting slice %s:" \
+ % self.name, err
+ if (time.time() - self.resetmail) > email_timeout:
+ slicemail(self.name, reset_subject % params, reset_body % params)
+ print "Sending Reset email for slice %s" % self.name
+ self.resetmail = time.time()
+
+
def usage():
print """
Usage: %s [OPTIONS]...
--reboot-thresh=PERCENT Swap utilization at which the machine is rebooted
--min-thresh=PERCENT Minimum physical memory utilization to be considered a hog
--system-slice=SLICE System slice that should not be reset
+ --status Print memory usage statistics and exit
-h, --help This message
""".lstrip() % (sys.argv[0], debug, verbose, datafile, format_period(period))
except ValueError:
pass
+ # vps sometimes prints ERR instead of a context ID if it
+ # cannot identify the context of an orphaned (usually dying)
+ # process. Skip these processes.
+ if type(proc['xid']) != int:
+ continue
+
# Assign (pl_)sshd processes to slice instead of root
m = re.search(r"sshd: ([a-zA-Z_]+)", proc['cmd'])
if m is not None:
return 100 * total_used / total_swap
+def summary(names = None, total_rss = memtotal()):
+ """
+ Return a summary of memory usage by slice.
+ """
+ slicelist = slicestat(names).values()
+ slicelist.sort(lambda a, b: b['rss'] - a['rss'])
+
+ table = "%-20s%10s%24s\n\n" % ("Slice", "Processes", "Memory Usage")
+ for slice in slicelist:
+ table += "%-20s%10d%16s (%4.1f%%)\n" % \
+ (slice['name'], len(slice['procs']),
+ format_bytes(slice['rss'] * 1024, si = False),
+ 100. * slice['rss'] / total_rss)
+
+ return table
+
def main():
# Defaults
global debug, verbose, datafile
names = []
try:
- longopts = ["debug", "verbose", "file=", "slice=", "help"]
+ longopts = ["debug", "verbose", "file=", "slice=", "status", "help"]
longopts += ["period=", "reset-thresh=", "reboot-thresh=", "min-thresh=", "system-slice="]
(opts, argv) = getopt.getopt(sys.argv[1:], "dvf:s:ph", longopts)
except getopt.GetoptError, err:
min_thresh = int(optval)
elif opt == "--system-slice":
system_slices.append(optval)
+ elif opt == "--status":
+ print summary(names)
+ sys.exit(0)
else:
usage()
sys.exit(0)
(version, slices) = pickle.load(f)
f.close()
# Check version of data file
- if version != "$Id: bwmon.py,v 1.1 2006/04/25 14:40:28 mlhuang Exp $":
+ if version != "$Id: swapmon.py,v 1.5 2006/05/09 03:23:57 mlhuang Exp $":
print "Not using old version '%s' data file %s" % (version, datafile)
raise Exception
- # Send notification if we rebooted the node because of swap exhaustion
- slicelist = slices.values()
- slicelist.sort(lambda a, b: b['rss'] - a['rss'])
-
- table = "%-20s%10s%24s\n\n" % ("Slice", "Processes", "Memory Usage")
- for slice in slicelist:
- table += "%-20s%10d%16s (%4.1f%%)\n" % \
- (slice['name'], len(slice['procs']),
- format_bytes(slice['rss'] * 1024, si = False),
- 100. * slice['rss'] / total_rss)
-
params = {'hostname': socket.gethostname(),
'date': time.asctime(time.gmtime()) + " GMT",
- 'table': table}
+ 'table': summary(total_rss)}
if debug:
print rebooted_subject % params
# Delete data file
os.unlink(datafile)
except Exception:
- version = "$Id: bwmon.py,v 1.1 2006/04/25 14:40:28 mlhuang Exp $"
+ version = "$Id: swapmon.py,v 1.5 2006/05/09 03:23:57 mlhuang Exp $"
slices = {}
# Query process table every 30 seconds, or when a large change in
# System slices that we have warned but could not reset
warned = []
+ # Slices that were reset
+ resetlist = {}
+
while True:
used = swap_used()
+
+ for resetslice in resetlist.keys():
+ resetlist[resetslice].update()
+
if last_used is None:
last_used = used
- if verbose:
+ if verbose:
print "%d%% swap consumed" % used
if used >= reboot_thresh:
slicelist.sort(lambda a, b: b['rss'] - a['rss'])
for slice in slicelist:
percent = 100. * slice['rss'] / total_rss
+
if percent < min_thresh:
continue
-
+
print "%d%% swap consumed, slice %s is using %s (%d%%) of memory" % \
(used,
slice['name'],
# Match slice name against system slice patterns
is_system_slice = filter(None, [re.match(pattern, slice['name']) for pattern in system_slices])
- if is_system_slice:
- # Do not reset system slices, just warn once
- if slice['name'] not in warned:
- warned.append(slice['name'])
- if debug:
- print alarm_subject % params
- print alarm_body % params
- else:
- print "Warning slice " + slice['name']
- slicemail(slice['name'], alarm_subject % params, alarm_body % params)
+ if is_system_slice:
+ if slice['name'] not in warned:
+ warned.append(slice['name'])
+ if debug:
+ print alarm_subject % params
+ print alarm_body % params
+ else:
+ print "Warning slice " + slice['name']
+ slicemail(slice['name'], alarm_subject % params,
+ alarm_body % params)
else:
- # Otherwise, reset
- if debug:
- print reset_subject % params
- print reset_body % params
- else:
- try:
- pid = os.fork()
- if pid == 0:
- print "Resetting slice " + slice['name']
- vserver = VServer(slice['name'])
- vserver.stop()
- vserver.start(wait = False)
- os._exit(0)
- else:
- os.waitpid(pid, 0)
- except Exception, err:
- print "Warning: Exception received while resetting slice %s:" % slice['name'], err
- slicemail(slice['name'], reset_subject % params, reset_body % params)
- break
+ # Reset slice
+ if not resetlist.has_key(slice['name']):
+ resetlist[slice['name']] = Reset(slice['name'])
+ resetlist[slice['name']].reset(params)
elif timer <= 0 or used >= (last_used + change_thresh):
if used >= (last_used + change_thresh):