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
62 # Minimum physical memory utilization to be considered the largest consumer
65 # System slices that should not be reset (regexps)
66 system_slices = ['root', PLC_SLICE_PREFIX + '_']
68 # Message sent after a critical reboot
69 rebooted_subject = "pl_mom rebooted %(hostname)s"
72 Sometime before %(date)s, swap space was
73 nearly exhausted on %(hostname)s, so pl_mom rebooted it.
75 Slices active prior to reboot are listed below. Memory usage
76 statistics are not entirely accurate due to threading.
80 %(date)s %(hostname)s reboot
83 # Message sent after a hog is reset
84 reset_subject = "pl_mom reset slice %(slice)s on %(hostname)s"
87 Sometime before %(date)s, swap space was
88 nearly exhausted on %(hostname)s.
90 Slice %(slice)s was reset since it was the largest consumer of
91 physical memory at %(rss)s (%(percent)4.1f%%).
93 Please reply to this message explaining the nature of your experiment,
94 and what you are doing to address the problem.
96 %(slice)s processes prior to reset:
100 %(date)s %(hostname)s reset %(slice)s
103 # Message sent to system slices that should not be reset
104 alarm_subject = "pl_mom alarm slice %(slice)s on %(hostname)s"
107 Sometime before %(date)s, swap space was
108 nearly exhausted on %(hostname)s.
110 System slice %(slice)s was the largest consumer of physical memory at
111 %(rss)s (%(percent)4.1f%%). It was not reset, but please verify its
114 %(slice)s processes prior to alarm:
118 %(date)s %(hostname)s alarm %(slice)s
121 # Message sent after a slice has been killed
122 kill_subject = "pl_mom killed slice %(slice)s on %(hostname)s"
125 Sometime before %(date)s, swap space was
126 nearly exhausted on %(hostname)s.
128 Slice %(slice)s was killed since it was the largest consumer of
129 physical memory at %(rss)s (%(percent)4.1f%%) after repeated restarts.
131 Please reply to this message explaining the nature of your experiment,
132 and what you are doing to address the problem.
134 %(slice)s processes prior to reset:
138 %(date)s %(hostname)s reset %(slice)s
145 Keeps track of state information for resets and kills
147 resettimeleft - timeout before checking for next reset
148 resetcount - number of strikes
149 killtimeleft - time out before removing from kill queue
152 def __init__(self,name):
154 self.resettimeleft = reset_timeout
156 self.killtimeleft = kill_timeout
162 # Count down for next check of reset slice.
163 if self.resettimeleft > 0:
164 self.resettimeleft -= 1
165 if debug and verbose:
166 print "%s has %s seconds to die and has been reset %s times" \
167 %(self.name, self.resettimeleft, self.resetcount)
168 print "%s has %s seconds in probation" \
169 %(self.name, self.killtimeleft)
170 if self.killtimeleft > 0:
171 # Count down kill probation timer (killtimeleft)
172 self.killtimeleft -= 1
174 # Once out of probation period (killtimeleft), remove strike
178 # Check to see if a slice needs to be killed. If it has rules more than kill_thresh in
179 # the probation period (kill_timeout) send an email, kill the slice.
180 def checkkill(self,params):
181 if self.killtimeleft > 0 and self.resetcount >= kill_thresh:
183 print kill_subject % params
184 print kill_body % params
188 print "Slice %s is being killed." % self.name
189 vserver = VServer(self.name)
193 except Exception, err:
194 print "Warning: Exception received while killing slice %s: %s" % self.name, err
195 slicemail(self.name, kill_subject % params, kill_body % params)
199 # Reset slice after checking to see if slice is out of timeout.
200 # Increment resetcount, check to see if larger than kill_thresh.
201 def reset(self, params):
202 # If its the first reset or if its been reset before
203 # and we are out of the reset timeout.
204 if self.resetcount == 0 or self.resettimeleft == 0:
205 # Do we need to kill this slice? Check history first.
206 if self.checkkill(params):
210 self.killtimeleft = kill_timeout
211 self.resettimeleft = reset_timeout
213 print reset_subject % params
214 print reset_body % params
218 print "Resetting slice " + self.name
219 vserver = VServer(self.name)
221 vserver.start(wait = False)
225 except Exception, err:
226 print "Warning: Exception received while resetting slice %s:" \
228 slicemail(self.name, reset_subject % params, reset_body % params)
234 Usage: %s [OPTIONS]...
237 -d, --debug Enable debugging (default: %s)
238 -v, --verbose Increase verbosity level (default: %d)
239 -f, --file=FILE Data file (default: %s)
240 -s, --slice=SLICE Constrain monitoring to these slices (default: all)
241 -p, --period=SECONDS Seconds between normal process analysis (default: %s)
242 --reset-thresh=PERCENT Swap utilization at which slice reset is attempted
243 --reboot-thresh=PERCENT Swap utilization at which the machine is rebooted
244 --min-thresh=PERCENT Minimum physical memory utilization to be considered a hog
245 --system-slice=SLICE System slice that should not be reset
246 --status Print memory usage statistics and exit
247 -h, --help This message
248 """.lstrip() % (sys.argv[0], debug, verbose, datafile, format_period(period))
250 def slicestat(names = None):
252 Get status of specified slices (if names is None or empty, all
253 slices). vsize and rss are in KiB. Returns
255 {xid: {'xid': slice_id,
257 'procs': [{'pid': pid, 'xid': slice_id, 'user', username, 'cmd': command,
258 'vsize': virtual_kib, 'rss': physical_kib,
259 'pcpu': cpu_percent, 'pmem': mem_percent}]
260 'vsize': total_virtual_kib,
261 'rss': total_physical_kib}}
264 # Mandatory fields. xid is a virtual field inserted by vps. Make
265 # sure cmd is last so that it does not get truncated
267 fields = ['pid', 'xid', 'user', 'vsize', 'rss', 'pcpu', 'pmem', 'cmd']
269 # vps inserts xid after pid in the output, but ps doesn't know
270 # what the field means.
271 ps_fields = list(fields)
272 ps_fields.remove('xid')
276 # Eat the header line. vps depends on the header to figure out
277 # which column is the PID column, so we can't just tell ps not to
279 for line in bwlimit.run("/usr/sbin/vps -e -o " + ",".join(ps_fields))[1:]:
283 # Replace "0 MAIN" and "1 ALL_PROC" (the special monikers that
284 # vps uses to denote the root context and the "all contexts"
285 # context) with "0" so that we can just split() on whitespace.
286 line = line.replace("0 MAIN", "0").replace("1 ALL_PROC", "0")
288 # Represent process as a dict of fields
289 values = line.split(None, len(fields) - 1)
290 if len(values) != len(fields):
292 proc = dict(zip(fields, values))
294 # Convert ints and floats
297 proc[field] = int(proc[field])
300 proc[field] = float(proc[field])
304 # vps sometimes prints ERR instead of a context ID if it
305 # cannot identify the context of an orphaned (usually dying)
306 # process. Skip these processes.
307 if type(proc['xid']) != int:
310 # Assign (pl_)sshd processes to slice instead of root
311 m = re.search(r"sshd: ([a-zA-Z_]+)", proc['cmd'])
313 xid = bwlimit.get_xid(m.group(1))
317 name = bwlimit.get_slice(proc['xid'])
319 # Orphaned (not associated with a slice) class
320 name = "%d?" % proc['xid']
322 # Monitor only the specified slices
323 if names and name not in names:
326 # Additional overhead calculations from slicestat
328 # Include 12 KiB of process overhead =
329 # 4 KiB top-level page table +
330 # 4 KiB kernel structure +
331 # 4 KiB basic page table
334 # Include additional page table overhead
335 if proc['vsize'] > 4096:
336 proc['rss'] += 4 * ((proc['vsize'] - 1) / 4096)
338 if slices.has_key(proc['xid']):
339 slice = slices[proc['xid']]
341 slice = {'xid': proc['xid'], 'name': name, 'procs': [], 'vsize': 0, 'rss': 0}
343 slice['procs'].append(proc)
344 slice['vsize'] += proc['vsize']
345 slice['rss'] += proc['rss']
347 slices[proc['xid']] = slice
353 Returns total physical memory on the system in KiB.
356 meminfo = open("/proc/meminfo", "r")
357 line = meminfo.readline()
359 if line[0:8] == "MemTotal":
360 # MemTotal: 255396 kB
361 (name, value, kb) = line.split()
368 Returns swap utilization on the system as a whole percentage (0-100).
375 swaps = open("/proc/swaps", "r")
377 lines = swaps.readlines()[1:]
380 # /dev/mapper/planetlab-swap partition 1048568 3740 -1
381 (filename, type, size, used, priority) = line.strip().split()
383 total_swap += int(size)
384 total_used += int(used)
385 except ValueEror, err:
387 except (IOError, KeyError), err:
390 return 100 * total_used / total_swap
392 def summary(names = None, total_rss = memtotal()):
394 Return a summary of memory usage by slice.
396 slicelist = slicestat(names).values()
397 slicelist.sort(lambda a, b: b['rss'] - a['rss'])
399 table = "%-20s%10s%24s\n\n" % ("Slice", "Processes", "Memory Usage")
400 for slice in slicelist:
401 table += "%-20s%10d%16s (%4.1f%%)\n" % \
402 (slice['name'], len(slice['procs']),
403 format_bytes(slice['rss'] * 1024, si = False),
404 100. * slice['rss'] / total_rss)
410 global debug, verbose, datafile
411 global period, change_thresh, reset_thresh, reboot_thresh, min_thresh, system_slices
416 longopts = ["debug", "verbose", "file=", "slice=", "status", "help"]
417 longopts += ["period=", "reset-thresh=", "reboot-thresh=", "min-thresh=", "system-slice="]
418 (opts, argv) = getopt.getopt(sys.argv[1:], "dvf:s:ph", longopts)
419 except getopt.GetoptError, err:
420 print "Error: " + err.msg
424 for (opt, optval) in opts:
425 if opt == "-d" or opt == "--debug":
427 elif opt == "-v" or opt == "--verbose":
429 elif opt == "-f" or opt == "--file":
431 elif opt == "-s" or opt == "--slice":
433 elif opt == "-p" or opt == "--period":
435 elif opt == "--change-thresh":
436 change_thresh = int(optval)
437 elif opt == "--reset-thresh":
438 reset_thresh = int(optval)
439 elif opt == "--reboot-thresh":
440 reboot_thresh = int(optval)
441 elif opt == "--min-thresh":
442 min_thresh = int(optval)
443 elif opt == "--system-slice":
444 system_slices.append(optval)
445 elif opt == "--status":
452 # Check if we are already running
459 # Redirect stdout and stderr to syslog
460 syslog.openlog("swapmon")
461 sys.stdout = sys.stderr = Logger()
463 # Get total physical memory
464 total_rss = memtotal()
467 f = open(datafile, "r+")
469 print "Loading %s" % datafile
470 (version, slices) = pickle.load(f)
472 # Check version of data file
473 if version != "$Id: swapmon.py,v 1.5 2006/05/09 03:23:57 mlhuang Exp $":
474 print "Not using old version '%s' data file %s" % (version, datafile)
477 params = {'hostname': socket.gethostname(),
478 'date': time.asctime(time.gmtime()) + " GMT",
479 'table': summary(total_rss)}
482 print rebooted_subject % params
483 print rebooted_body % params
485 slicemail(None, rebooted_subject % params, rebooted_body % params)
490 version = "$Id: swapmon.py,v 1.5 2006/05/09 03:23:57 mlhuang Exp $"
493 # Query process table every 30 seconds, or when a large change in
494 # swap utilization is detected.
499 # System slices that we have warned but could not reset
502 # Slices that were reset
508 for resetslice in resetlist.keys():
509 resetlist[resetslice].update()
511 if last_used is None:
514 print "%d%% swap consumed" % used
516 if used >= reboot_thresh:
517 # Dump slice state before rebooting
519 print "Saving %s" % datafile
520 f = open(datafile, "w")
521 pickle.dump((version, slices), f)
524 # Goodbye, cruel world
525 print "%d%% swap consumed, rebooting" % used
527 bwlimit.run("/bin/sync; /sbin/reboot -f")
529 elif used >= reset_thresh:
531 slicelist = slices.values()
532 slicelist.sort(lambda a, b: b['rss'] - a['rss'])
533 for slice in slicelist:
534 percent = 100. * slice['rss'] / total_rss
536 if percent < min_thresh:
539 print "%d%% swap consumed, slice %s is using %s (%d%%) of memory" % \
542 format_bytes(slice['rss'] * 1024, si = False),
545 slice['procs'].sort(lambda a, b: b['rss'] - a['rss'])
547 table = "%5s %10s %10s %4s %4s %s\n\n" % ("PID", "VIRT", "RES", '%CPU', '%MEM', 'COMMAND')
548 for proc in slice['procs']:
549 table += "%5s %10s %10s %4.1f %4.1f %s\n" % \
551 format_bytes(proc['vsize'] * 1024, si = False),
552 format_bytes(proc['rss'] * 1024, si = False),
553 proc['pcpu'], proc['pmem'], proc['cmd'])
555 params = {'hostname': socket.gethostname(),
556 'date': time.asctime(time.gmtime()) + " GMT",
558 'slice': slice['name'],
559 'rss': format_bytes(slice['rss'] * 1024, si = False),
562 # Match slice name against system slice patterns
563 is_system_slice = filter(None, [re.match(pattern, slice['name']) for pattern in system_slices])
566 # Do not reset system slices, just warn once
567 if slice['name'] not in warned:
568 warned.append(slice['name'])
570 print alarm_subject % params
571 print alarm_body % params
573 print "Warning slice " + slice['name']
574 slicemail(slice['name'], alarm_subject % params, alarm_body % params)
577 if not resetlist.has_key(slice['name']):
578 resetlist[slice['name']] = Reset(slice['name'])
579 resetlist[slice['name']].reset(params)
581 elif timer <= 0 or used >= (last_used + change_thresh):
582 if used >= (last_used + change_thresh):
583 print "%d%% swap consumed, %d%% in last %d seconds" % \
584 (used, used - last_used, period - timer)
586 slices = slicestat(names)
589 # Keep track of large changes in swap utilization
597 if __name__ == '__main__':