3 # Swap monitoring daemon. Every 30 seconds, checks process memory
4 # usage. At 90% utilization, resets the slice that is consuming the
5 # most physical memory. At 95% utilization, reboots the machine to
8 # Mark Huang <mlhuang@cs.princeton.edu>
9 # Andy Bavier <acb@cs.princeton.edu>
10 # Faiyaz Ahmed <faiyaza@cs.princeton.edu>
11 # Copyright (C) 2004-2006 The Trustees of Princeton University
13 # $Id: swapmon.py,v 1.5 2006/05/09 03:23:57 mlhuang Exp $
25 # util-vserver/python/vserver.py allows us to control slices directly
27 from vserver import VServer
29 # bwlimit exports a few useful functions like run(), get_xid(), and get_slice()
38 datafile = "/var/lib/misc/swapmon.dat"
40 # Seconds between process analysis
43 # Minimum change in swap utilization over 30 seconds that will trigger
44 # early process analysis.
47 # Swap utilization at which the largest consumer of physical memory is reset
50 # Swap utilization at which the machine is rebooted
53 # Time to wait before checking slice again after reset
56 # Number of strikes before killing (strike, strike, kill)
59 # Time to wait before removing slice from kill queue (probation)
62 # Don't email the same message more than once in the same emailtimeout interval
65 # Minimum physical memory utilization to be considered the largest consumer
68 # System slices that should not be reset (regexps)
69 system_slices = ['root', PLC_SLICE_PREFIX + '_']
71 # Message sent after a critical reboot
72 rebooted_subject = "pl_mom rebooted %(hostname)s"
75 Sometime before %(date)s, swap space was
76 nearly exhausted on %(hostname)s, so pl_mom rebooted it.
78 Slices active prior to reboot are listed below. Memory usage
79 statistics are not entirely accurate due to threading.
83 %(date)s %(hostname)s reboot
86 # Message sent after a hog is reset
87 reset_subject = "pl_mom reset slice %(slice)s on %(hostname)s"
90 Sometime before %(date)s, swap space was
91 nearly exhausted on %(hostname)s.
93 Slice %(slice)s was reset since it was the largest consumer of
94 physical memory at %(rss)s (%(percent)4.1f%%).
96 Please reply to this message explaining the nature of your experiment,
97 and what you are doing to address the problem.
99 %(slice)s processes prior to reset:
103 %(date)s %(hostname)s reset %(slice)s
106 # Message sent to system slices that should not be reset
107 alarm_subject = "pl_mom alarm slice %(slice)s on %(hostname)s"
110 Sometime before %(date)s, swap space was
111 nearly exhausted on %(hostname)s.
113 System slice %(slice)s was the largest consumer of physical memory at
114 %(rss)s (%(percent)4.1f%%). It was not reset, but please verify its
117 %(slice)s processes prior to alarm:
121 %(date)s %(hostname)s alarm %(slice)s
124 # Message sent after a slice has been killed
125 kill_subject = "pl_mom killed slice %(slice)s on %(hostname)s"
128 Sometime before %(date)s, swap space was
129 nearly exhausted on %(hostname)s.
131 Slice %(slice)s was killed since it was the largest consumer of
132 physical memory at %(rss)s (%(percent)4.1f%%) after repeated restarts.
134 Please reply to this message explaining the nature of your experiment,
135 and what you are doing to address the problem.
137 %(slice)s processes prior to reset:
141 %(date)s %(hostname)s reset %(slice)s
148 Keeps track of state information for resets and kills
150 resettimeleft - timeout before checking for next reset
151 resetcount - number of strikes
152 killtimeleft - time out before removing from kill queue
153 {kill,reset}mail - Time of last email
154 kill - State of kill. If slice is already being killed, wait before retry.
157 def __init__(self,name):
159 self.resettimeleft = reset_timeout
163 self.killtimeleft = kill_timeout
170 # Count down for next check of reset slice.
171 if self.resettimeleft > 0:
172 self.resettimeleft -= 1
173 if debug and verbose:
174 print "%s has %s seconds in probation" \
175 %(self.name, self.killtimeleft)
176 if self.killtimeleft > 0:
177 # Count down kill probation timer (killtimeleft)
178 self.killtimeleft -= 1
179 if self.killtimeleft == 1:
180 print "%s is out of probation" % self.name
182 # Once out of probation period (killtimeleft), remove strikes
187 # Check to see if a slice needs to be killed. If it has rules more than kill_thresh in
188 # the probation period (kill_timeout) send an email, kill the slice.
189 def checkkill(self,params):
190 if self.killtimeleft > 0 and self.resetcount >= kill_thresh and \
194 print kill_subject % params
195 print kill_body % params
199 print "Slice %s is being killed." % self.name
200 vserver = VServer(self.name)
203 except Exception, err:
204 print "Warning: Exception received while killing slice %s: %s" % self.name, err
205 if (time.time() - self.killmail) > email_timeout:
206 slicemail(self.name, kill_subject % params, kill_body % params)
207 print "Sending KILL email for slice %s" % self.name
208 self.killmail = time.time()
212 # Reset slice after checking to see if slice is out of timeout.
213 # Increment resetcount, check to see if larger than kill_thresh.
214 def reset(self, params):
215 # If its the first reset or if its been reset before
216 # and we are out of the reset timeout.
217 if self.resetcount == 0 or self.resettimeleft == 0:
218 # Do we need to kill this slice? Check history first.
219 if self.checkkill(params):
223 self.killtimeleft = kill_timeout
224 self.resettimeleft = reset_timeout
225 print "%s has %s seconds to die and has been reset %s times" \
226 %(self.name, self.resettimeleft, self.resetcount)
228 print reset_subject % params
229 print reset_body % params
233 print "Resetting slice " + self.name
234 vserver = VServer(self.name)
236 vserver.start(wait = False)
238 except Exception, err:
239 print "Warning: Exception received while resetting slice %s:" \
241 if (time.time() - self.resetmail) > email_timeout:
242 slicemail(self.name, reset_subject % params, reset_body % params)
243 print "Sending Reset email for slice %s" % self.name
244 self.resetmail = time.time()
249 Usage: %s [OPTIONS]...
252 -d, --debug Enable debugging (default: %s)
253 -v, --verbose Increase verbosity level (default: %d)
254 -f, --file=FILE Data file (default: %s)
255 -s, --slice=SLICE Constrain monitoring to these slices (default: all)
256 -p, --period=SECONDS Seconds between normal process analysis (default: %s)
257 --reset-thresh=PERCENT Swap utilization at which slice reset is attempted
258 --reboot-thresh=PERCENT Swap utilization at which the machine is rebooted
259 --min-thresh=PERCENT Minimum physical memory utilization to be considered a hog
260 --system-slice=SLICE System slice that should not be reset
261 --status Print memory usage statistics and exit
262 -h, --help This message
263 """.lstrip() % (sys.argv[0], debug, verbose, datafile, format_period(period))
265 def slicestat(names = None):
267 Get status of specified slices (if names is None or empty, all
268 slices). vsize and rss are in KiB. Returns
270 {xid: {'xid': slice_id,
272 'procs': [{'pid': pid, 'xid': slice_id, 'user', username, 'cmd': command,
273 'vsize': virtual_kib, 'rss': physical_kib,
274 'pcpu': cpu_percent, 'pmem': mem_percent}]
275 'vsize': total_virtual_kib,
276 'rss': total_physical_kib}}
279 # Mandatory fields. xid is a virtual field inserted by vps. Make
280 # sure cmd is last so that it does not get truncated
282 fields = ['pid', 'xid', 'user', 'vsize', 'rss', 'pcpu', 'pmem', 'cmd']
284 # vps inserts xid after pid in the output, but ps doesn't know
285 # what the field means.
286 ps_fields = list(fields)
287 ps_fields.remove('xid')
291 # Eat the header line. vps depends on the header to figure out
292 # which column is the PID column, so we can't just tell ps not to
294 for line in bwlimit.run("/usr/sbin/vps -e -o " + ",".join(ps_fields))[1:]:
298 # Replace "0 MAIN" and "1 ALL_PROC" (the special monikers that
299 # vps uses to denote the root context and the "all contexts"
300 # context) with "0" so that we can just split() on whitespace.
301 line = line.replace("0 MAIN", "0").replace("1 ALL_PROC", "0")
303 # Represent process as a dict of fields
304 values = line.split(None, len(fields) - 1)
305 if len(values) != len(fields):
307 proc = dict(zip(fields, values))
309 # Convert ints and floats
312 proc[field] = int(proc[field])
315 proc[field] = float(proc[field])
319 # vps sometimes prints ERR instead of a context ID if it
320 # cannot identify the context of an orphaned (usually dying)
321 # process. Skip these processes.
322 if type(proc['xid']) != int:
325 # Assign (pl_)sshd processes to slice instead of root
326 m = re.search(r"sshd: ([a-zA-Z_]+)", proc['cmd'])
328 xid = bwlimit.get_xid(m.group(1))
332 name = bwlimit.get_slice(proc['xid'])
334 # Orphaned (not associated with a slice) class
335 name = "%d?" % proc['xid']
337 # Monitor only the specified slices
338 if names and name not in names:
341 # Additional overhead calculations from slicestat
343 # Include 12 KiB of process overhead =
344 # 4 KiB top-level page table +
345 # 4 KiB kernel structure +
346 # 4 KiB basic page table
349 # Include additional page table overhead
350 if proc['vsize'] > 4096:
351 proc['rss'] += 4 * ((proc['vsize'] - 1) / 4096)
353 if slices.has_key(proc['xid']):
354 slice = slices[proc['xid']]
356 slice = {'xid': proc['xid'], 'name': name, 'procs': [], 'vsize': 0, 'rss': 0}
358 slice['procs'].append(proc)
359 slice['vsize'] += proc['vsize']
360 slice['rss'] += proc['rss']
362 slices[proc['xid']] = slice
368 Returns total physical memory on the system in KiB.
371 meminfo = open("/proc/meminfo", "r")
372 line = meminfo.readline()
374 if line[0:8] == "MemTotal":
375 # MemTotal: 255396 kB
376 (name, value, kb) = line.split()
383 Returns swap utilization on the system as a whole percentage (0-100).
390 swaps = open("/proc/swaps", "r")
392 lines = swaps.readlines()[1:]
395 # /dev/mapper/planetlab-swap partition 1048568 3740 -1
396 (filename, type, size, used, priority) = line.strip().split()
398 total_swap += int(size)
399 total_used += int(used)
400 except ValueEror, err:
402 except (IOError, KeyError), err:
405 return 100 * total_used / total_swap
407 def summary(names = None, total_rss = memtotal()):
409 Return a summary of memory usage by slice.
411 slicelist = slicestat(names).values()
412 slicelist.sort(lambda a, b: b['rss'] - a['rss'])
414 table = "%-20s%10s%24s\n\n" % ("Slice", "Processes", "Memory Usage")
415 for slice in slicelist:
416 table += "%-20s%10d%16s (%4.1f%%)\n" % \
417 (slice['name'], len(slice['procs']),
418 format_bytes(slice['rss'] * 1024, si = False),
419 100. * slice['rss'] / total_rss)
425 global debug, verbose, datafile
426 global period, change_thresh, reset_thresh, reboot_thresh, min_thresh, system_slices
431 longopts = ["debug", "verbose", "file=", "slice=", "status", "help"]
432 longopts += ["period=", "reset-thresh=", "reboot-thresh=", "min-thresh=", "system-slice="]
433 (opts, argv) = getopt.getopt(sys.argv[1:], "dvf:s:ph", longopts)
434 except getopt.GetoptError, err:
435 print "Error: " + err.msg
439 for (opt, optval) in opts:
440 if opt == "-d" or opt == "--debug":
442 elif opt == "-v" or opt == "--verbose":
444 elif opt == "-f" or opt == "--file":
446 elif opt == "-s" or opt == "--slice":
448 elif opt == "-p" or opt == "--period":
450 elif opt == "--change-thresh":
451 change_thresh = int(optval)
452 elif opt == "--reset-thresh":
453 reset_thresh = int(optval)
454 elif opt == "--reboot-thresh":
455 reboot_thresh = int(optval)
456 elif opt == "--min-thresh":
457 min_thresh = int(optval)
458 elif opt == "--system-slice":
459 system_slices.append(optval)
460 elif opt == "--status":
467 # Check if we are already running
474 # Redirect stdout and stderr to syslog
475 syslog.openlog("swapmon")
476 sys.stdout = sys.stderr = Logger()
478 # Get total physical memory
479 total_rss = memtotal()
482 f = open(datafile, "r+")
484 print "Loading %s" % datafile
485 (version, slices) = pickle.load(f)
487 # Check version of data file
488 if version != "$Id: swapmon.py,v 1.5 2006/05/09 03:23:57 mlhuang Exp $":
489 print "Not using old version '%s' data file %s" % (version, datafile)
492 params = {'hostname': socket.gethostname(),
493 'date': time.asctime(time.gmtime()) + " GMT",
494 'table': summary(total_rss)}
497 print rebooted_subject % params
498 print rebooted_body % params
500 slicemail(None, rebooted_subject % params, rebooted_body % params)
505 version = "$Id: swapmon.py,v 1.5 2006/05/09 03:23:57 mlhuang Exp $"
508 # Query process table every 30 seconds, or when a large change in
509 # swap utilization is detected.
514 # System slices that we have warned but could not reset
517 # Slices that were reset
523 for resetslice in resetlist.keys():
524 resetlist[resetslice].update()
526 if last_used is None:
529 print "%d%% swap consumed" % used
531 if used >= reboot_thresh:
532 # Dump slice state before rebooting
534 print "Saving %s" % datafile
535 f = open(datafile, "w")
536 pickle.dump((version, slices), f)
539 # Goodbye, cruel world
540 print "%d%% swap consumed, rebooting" % used
542 bwlimit.run("/bin/sync; /sbin/reboot -f")
544 elif used >= reset_thresh:
546 slicelist = slices.values()
547 slicelist.sort(lambda a, b: b['rss'] - a['rss'])
548 for slice in slicelist:
549 percent = 100. * slice['rss'] / total_rss
551 if percent < min_thresh:
554 print "%d%% swap consumed, slice %s is using %s (%d%%) of memory" % \
557 format_bytes(slice['rss'] * 1024, si = False),
560 slice['procs'].sort(lambda a, b: b['rss'] - a['rss'])
562 table = "%5s %10s %10s %4s %4s %s\n\n" % ("PID", "VIRT", "RES", '%CPU', '%MEM', 'COMMAND')
563 for proc in slice['procs']:
564 table += "%5s %10s %10s %4.1f %4.1f %s\n" % \
566 format_bytes(proc['vsize'] * 1024, si = False),
567 format_bytes(proc['rss'] * 1024, si = False),
568 proc['pcpu'], proc['pmem'], proc['cmd'])
570 params = {'hostname': socket.gethostname(),
571 'date': time.asctime(time.gmtime()) + " GMT",
573 'slice': slice['name'],
574 'rss': format_bytes(slice['rss'] * 1024, si = False),
577 # Match slice name against system slice patterns
578 is_system_slice = filter(None, [re.match(pattern, slice['name']) for pattern in system_slices])
580 if is_system_slice and params['rss'] > 100:
581 # Do not reset system slices, just warn once
582 if slice['name'] not in warned:
583 warned.append(slice['name'])
585 print alarm_subject % params
586 print alarm_body % params
588 print "Warning slice " + slice['name']
589 slicemail(slice['name'], alarm_subject % params, alarm_body % params)
592 if not resetlist.has_key(slice['name']):
593 resetlist[slice['name']] = Reset(slice['name'])
594 resetlist[slice['name']].reset(params)
596 elif timer <= 0 or used >= (last_used + change_thresh):
597 if used >= (last_used + change_thresh):
598 print "%d%% swap consumed, %d%% in last %d seconds" % \
599 (used, used - last_used, period - timer)
601 slices = slicestat(names)
604 # Keep track of large changes in swap utilization
612 if __name__ == '__main__':