* Added hard limit of 200MB to be considered a hog.
[mom.git] / swapmon.py
1 #!/usr/bin/python
2 #
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
6 # avoid a crash.
7 #
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
12 #
13 # $Id: swapmon.py,v 1.9 2006/07/19 19:40:55 faiyaza Exp $
14 #
15
16 import syslog
17 import os
18 import sys
19 import getopt
20 import re
21 import pickle
22 import socket
23 import time
24
25 # util-vserver/python/vserver.py allows us to control slices directly
26 # from Python
27 from vserver import VServer
28
29 # bwlimit exports a few useful functions like run(), get_xid(), and get_slice()
30 import bwlimit
31
32 # Utility functions
33 from pl_mom import *
34
35 # Defaults
36 debug = False
37 verbose = 0
38 datafile = "/var/lib/misc/swapmon.dat"
39
40 # Seconds between process analysis
41 period = 30
42
43 # Minimum change in swap utilization over 30 seconds that will trigger
44 # early process analysis.
45 change_thresh = 5
46
47 # Swap utilization at which the largest consumer of physical memory is reset
48 reset_thresh = 80
49
50 # Swap utilization at which the machine is rebooted
51 reboot_thresh = 95
52
53 # Time to wait before checking slice again after reset
54 reset_timeout = 15
55
56 # Number of strikes before killing (strike, strike, kill)
57 kill_thresh = 2
58
59 # Time to wait before removing slice from kill queue (probation) 
60 kill_timeout = 120 
61
62 # Don't email the same message more than once in the same emailtimeout interval
63 email_timeout = 1800
64
65 # Physical size threshold to be considered a consumer.  Rationale is if there are no procs
66 # with a size at least as large as this, then there is a slow leaker;  better to just reboot.
67 rss_min = 150 * 1024 
68
69 # System slices that should not be reset (regexps)
70 system_slices = ['root', PLC_SLICE_PREFIX + '_']
71
72 # Message sent after a critical reboot
73 rebooted_subject = "pl_mom rebooted %(hostname)s"
74 rebooted_body = \
75 """
76 Sometime before %(date)s, swap space was
77 nearly exhausted on %(hostname)s, so pl_mom rebooted it.
78
79 Slices active prior to reboot are listed below. Memory usage
80 statistics are not entirely accurate due to threading.
81
82 %(table)s
83
84 %(date)s %(hostname)s reboot
85 """.lstrip()
86
87 # Message sent after a hog is reset
88 reset_subject = "pl_mom reset slice %(slice)s on %(hostname)s"
89 reset_body = \
90 """
91 Sometime before %(date)s, swap space was
92 nearly exhausted on %(hostname)s.
93
94 Slice %(slice)s was reset since it was the largest consumer of
95 physical memory at %(rss)s (%(percent)4.1f%%).
96
97 Please reply to this message explaining the nature of your experiment,
98 and what you are doing to address the problem.
99
100 %(slice)s processes prior to reset:
101
102 %(table)s
103
104 %(date)s %(hostname)s reset %(slice)s
105 """.lstrip()
106
107 # Message sent to system slices that should not be reset
108 alarm_subject = "pl_mom alarm slice %(slice)s on %(hostname)s"
109 alarm_body = \
110 """           
111 Sometime before %(date)s, swap space was
112 nearly exhausted on %(hostname)s.
113
114 System slice %(slice)s was the largest consumer of physical memory at
115 %(rss)s (%(percent)4.1f%%). It was not reset, but please verify its
116 behavior.
117
118 %(slice)s processes prior to alarm:
119
120 %(table)s
121
122 %(date)s %(hostname)s alarm %(slice)s
123 """.lstrip()
124
125 # Message sent after a slice has been killed
126 kill_subject = "pl_mom killed slice %(slice)s on %(hostname)s"
127 kill_body = \
128 """
129 Sometime before %(date)s, swap space was
130 nearly exhausted on %(hostname)s.
131
132 Slice %(slice)s was killed since it was the largest consumer of
133 physical memory at %(rss)s (%(percent)4.1f%%) after repeated restarts.
134
135 Please reply to this message explaining the nature of your experiment,
136 and what you are doing to address the problem.
137
138 %(slice)s processes prior to reset:
139
140 %(table)s
141
142 %(date)s %(hostname)s reset %(slice)s
143 """.lstrip()
144
145
146
147 class Reset:
148         """
149         Keeps track of state information for resets and kills
150
151         resettimeleft - timeout before checking for next reset
152         resetcount - number of strikes 
153         killtimeleft - time out before removing from kill queue
154         {kill,reset}mail - Time of last email
155         kill - State of kill.  If slice is already being killed, wait before retry.
156         """
157
158         def __init__(self,name):
159                 self.name = name
160                 self.resettimeleft = reset_timeout
161                 self.resetcount = 0 
162                 self.resetmail = 0
163                 self.killtimeleft = kill_timeout
164                 self.killmail = 0
165
166         def __repr__(self):
167                 return self.name
168         
169         def update(self):
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
181                 else:
182                         # Once out of probation period (killtimeleft), remove strikes
183                         self.resetcount = 0
184
185
186         # Check to see if a slice needs to be killed.  If it has been killed more 
187         # than kill_thresh in the probation period (kill_timeout) send an email, kill the slice.
188         def checkkill(self,params):
189                 if self.killtimeleft > 0 and self.resetcount >= kill_thresh:
190                         if debug:
191                                 print kill_subject % params
192                                 print kill_body % params
193                         try:
194                                 pid = os.fork()
195                                 if pid == 0:
196                                         print "Slice %s is being killed." % self.name   
197                                         vserver = VServer(self.name)
198                                         vserver.stop()
199                                         os._exit(0)
200                                 else:
201                                         os.waitpid(pid,0)
202                         except Exception, err:
203                                 print "Warning: Exception received while killing slice %s: %s" \
204                                         % 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() 
209                         return True
210                 return False 
211
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 (came back after kill)
216                 # or if its been reset before
217                 # and we are out of the reset timeout.
218                 if self.resetcount == 0 or self.resettimeleft == 0:
219                         # Do we need to kill this slice?  Check history first.
220                         if self.checkkill(params):
221                                 return
222                         # Update counters
223                         self.resetcount += 1
224                         self.killtimeleft = kill_timeout
225                         self.resettimeleft = reset_timeout
226                         print "%s has %s seconds to die and has been reset %s times" \
227                                 %(self.name, self.resettimeleft, self.resetcount)
228                         if debug:
229                                 print reset_subject % params
230                                 print reset_body % params
231                         try:
232                                 pid = os.fork()
233                                 if pid == 0:
234                                         print "Resetting slice " + self.name 
235                                         vserver = VServer(self.name)
236                                         vserver.stop()
237                                         vserver.start(wait = False)
238                                         os._exit(0)
239                                 else:
240                                         os.waitpid(pid,0)
241                         except Exception, err:
242                                 print "Warning: Exception received while resetting slice %s:" \
243                                         % self.name, err
244                         if (time.time() - self.resetmail) > email_timeout:
245                                 slicemail(self.name, reset_subject % params, reset_body % params)
246                                 print "Sending Reset email for slice %s" % self.name
247                                 self.resetmail = time.time() 
248
249
250 def usage():
251     print """
252 Usage: %s [OPTIONS]...
253
254 Options:
255         -d, --debug             Enable debugging (default: %s)
256         -v, --verbose           Increase verbosity level (default: %d)
257         -f, --file=FILE         Data file (default: %s)
258         -s, --slice=SLICE       Constrain monitoring to these slices (default: all)
259         -p, --period=SECONDS    Seconds between normal process analysis (default: %s)
260         --reset-thresh=PERCENT  Swap utilization at which slice reset is attempted
261         --reboot-thresh=PERCENT Swap utilization at which the machine is rebooted
262         --min-thresh=PERCENT    Minimum physical memory utilization to be considered a hog
263         --system-slice=SLICE    System slice that should not be reset
264         --status                Print memory usage statistics and exit
265         -h, --help              This message
266 """.lstrip() % (sys.argv[0], debug, verbose, datafile, format_period(period))
267
268 def slicestat(names = None):
269     """
270     Get status of specified slices (if names is None or empty, all
271     slices). vsize and rss are in KiB. Returns
272
273     {xid: {'xid': slice_id,
274            'name': slice_name,
275            'procs': [{'pid': pid, 'xid': slice_id, 'user', username, 'cmd': command,
276                       'vsize': virtual_kib, 'rss': physical_kib,
277                       'pcpu': cpu_percent, 'pmem': mem_percent}]
278            'vsize': total_virtual_kib,
279            'rss': total_physical_kib}}
280     """
281     
282     # Mandatory fields. xid is a virtual field inserted by vps. Make
283     # sure cmd is last so that it does not get truncated
284     # automatically.
285     fields = ['pid', 'xid', 'user', 'vsize', 'rss', 'pcpu', 'pmem', 'cmd']
286
287     # vps inserts xid after pid in the output, but ps doesn't know
288     # what the field means.
289     ps_fields = list(fields)
290     ps_fields.remove('xid')
291
292     slices = {}
293
294     # Eat the header line. vps depends on the header to figure out
295     # which column is the PID column, so we can't just tell ps not to
296     # print it.
297     for line in bwlimit.run("/usr/sbin/vps -e -o " + ",".join(ps_fields))[1:]:
298         # Chomp newline
299         line = line.strip()
300
301         # Replace "0 MAIN" and "1 ALL_PROC" (the special monikers that
302         # vps uses to denote the root context and the "all contexts"
303         # context) with "0" so that we can just split() on whitespace.
304         line = line.replace("0 MAIN", "0").replace("1 ALL_PROC", "0")
305
306         # Represent process as a dict of fields
307         values = line.split(None, len(fields) - 1)
308         if len(values) != len(fields):
309             continue
310         proc = dict(zip(fields, values))
311
312         # Convert ints and floats
313         for field in proc:
314             try:
315                 proc[field] = int(proc[field])
316             except ValueError:
317                 try:
318                     proc[field] = float(proc[field])
319                 except ValueError:
320                     pass
321
322         # vps sometimes prints ERR instead of a context ID if it
323         # cannot identify the context of an orphaned (usually dying)
324         # process. Skip these processes.
325         if type(proc['xid']) != int:
326             continue
327
328         # Assign (pl_)sshd processes to slice instead of root
329         m = re.search(r"sshd: ([a-zA-Z_]+)", proc['cmd'])
330         if m is not None:
331             xid = bwlimit.get_xid(m.group(1))
332             if xid is not None:
333                 proc['xid'] = xid
334
335         name = bwlimit.get_slice(proc['xid'])
336         if name is None:
337             # Orphaned (not associated with a slice) class
338             name = "%d?" % proc['xid']
339
340         # Monitor only the specified slices
341         if names and name not in names:
342             continue
343
344         # Additional overhead calculations from slicestat
345
346         # Include 12 KiB of process overhead =
347         # 4 KiB top-level page table +
348         # 4 KiB kernel structure +
349         # 4 KiB basic page table
350         proc['rss'] += 12
351
352         # Include additional page table overhead
353         if proc['vsize'] > 4096:
354             proc['rss'] += 4 * ((proc['vsize'] - 1) / 4096)
355
356         if slices.has_key(proc['xid']):
357             slice = slices[proc['xid']]
358         else:
359             slice = {'xid': proc['xid'], 'name': name, 'procs': [], 'vsize': 0, 'rss': 0}
360
361         slice['procs'].append(proc)
362         slice['vsize'] += proc['vsize']
363         slice['rss'] += proc['rss']
364
365         slices[proc['xid']] = slice
366
367     return slices
368
369 def memtotal():
370     """
371     Returns total physical memory on the system in KiB.
372     """
373
374     meminfo = open("/proc/meminfo", "r")
375     line = meminfo.readline()
376     meminfo.close()
377     if line[0:8] == "MemTotal":
378         # MemTotal: 255396 kB
379         (name, value, kb) = line.split()
380         return int(value)
381
382     return 0
383
384 def swap_used():
385     """
386     Returns swap utilization on the system as a whole percentage (0-100).
387     """
388
389     total_swap = 0
390     total_used = 0
391
392     try:
393         swaps = open("/proc/swaps", "r")
394         # Eat header line
395         lines = swaps.readlines()[1:]
396         swaps.close()
397         for line in lines:
398             # /dev/mapper/planetlab-swap partition 1048568 3740 -1
399             (filename, type, size, used, priority) = line.strip().split()
400             try:
401                 total_swap += int(size)
402                 total_used += int(used)
403             except ValueEror, err:
404                 pass
405     except (IOError, KeyError), err:
406         pass
407
408     return 100 * total_used / total_swap
409
410 def summary(names = None, total_rss = memtotal()):
411     """
412     Return a summary of memory usage by slice.
413     """
414     slicelist = slicestat(names).values()
415     slicelist.sort(lambda a, b: b['rss'] - a['rss'])
416
417     table = "%-20s%10s%24s\n\n" % ("Slice", "Processes", "Memory Usage")
418     for slice in slicelist:
419         table += "%-20s%10d%16s (%4.1f%%)\n" % \
420                  (slice['name'], len(slice['procs']),
421                   format_bytes(slice['rss'] * 1024, si = False),
422                   100. * slice['rss'] / total_rss)
423
424     return table
425
426 def main():
427     # Defaults
428     global debug, verbose, datafile
429     global period, change_thresh, reset_thresh, reboot_thresh, rss_min, system_slices
430     # All slices
431     names = []
432
433     try:
434         longopts = ["debug", "verbose", "file=", "slice=", "status", "help"]
435         longopts += ["period=", "reset-thresh=", "reboot-thresh=", "min-thresh=", "system-slice="]
436         (opts, argv) = getopt.getopt(sys.argv[1:], "dvf:s:ph", longopts)
437     except getopt.GetoptError, err:
438         print "Error: " + err.msg
439         usage()
440         sys.exit(1)
441
442     for (opt, optval) in opts:
443         if opt == "-d" or opt == "--debug":
444             debug = True
445         elif opt == "-v" or opt == "--verbose":
446             verbose += 1
447         elif opt == "-f" or opt == "--file":
448             datafile = optval
449         elif opt == "-s" or opt == "--slice":
450             names.append(optval)
451         elif opt == "-p" or opt == "--period":
452             period = int(optval)
453         elif opt == "--change-thresh":
454             change_thresh = int(optval)
455         elif opt == "--reset-thresh":
456             reset_thresh = int(optval)
457         elif opt == "--reboot-thresh":
458             reboot_thresh = int(optval)
459         elif opt == "--system-slice":
460             system_slices.append(optval)
461         elif opt == "--status":
462             print summary(names)
463             sys.exit(0)
464         else:
465             usage()
466             sys.exit(0)
467
468     # Check if we are already running
469     writepid("swapmon")
470
471     if not debug:
472         daemonize()
473         # Rewrite PID file
474         writepid("swapmon")
475         # Redirect stdout and stderr to syslog
476         syslog.openlog("swapmon")
477         sys.stdout = sys.stderr = Logger()
478
479     # Get total physical memory
480     total_rss = memtotal()
481
482     try:
483         f = open(datafile, "r+")
484         if verbose:
485             print "Loading %s" % datafile
486         (version, slices) = pickle.load(f)
487         f.close()
488         # Check version of data file
489         if version != "$Id: swapmon.py,v 1.9 2006/07/19 19:40:55 faiyaza Exp $":
490             print "Not using old version '%s' data file %s" % (version, datafile)
491             raise Exception
492
493         params = {'hostname': socket.gethostname(),
494                   'date': time.asctime(time.gmtime()) + " GMT",
495                   'table': summary(total_rss)}
496
497         if debug:
498             print rebooted_subject % params
499             print rebooted_body % params
500         else:
501             slicemail(None, rebooted_subject % params, rebooted_body % params)
502
503         # Delete data file
504         os.unlink(datafile)
505     except Exception:
506         version = "$Id: swapmon.py,v 1.9 2006/07/19 19:40:55 faiyaza Exp $"
507         slices = {}
508
509     # Query process table every 30 seconds, or when a large change in
510     # swap utilization is detected.
511     timer = period
512     last_used = None
513     used = None
514
515     # System slices that we have warned but could not reset
516     warned = []
517
518     # Slices that were reset
519     resetlist = {}
520
521     while True:
522         used = swap_used()
523
524         for resetslice in resetlist.keys():
525                 resetlist[resetslice].update()
526         
527         if last_used is None:
528             last_used = used
529
530         if verbose:
531             print "%d%% swap consumed" % used
532
533         if used >= reboot_thresh:
534             # Dump slice state before rebooting
535             if verbose:
536                 print "Saving %s" % datafile
537             f = open(datafile, "w")
538             pickle.dump((version, slices), f)
539             f.close()
540
541             # Goodbye, cruel world
542             print "%d%% swap consumed, rebooting" % used
543             if not debug:
544                 bwlimit.run("/bin/sync; /sbin/reboot -f")
545
546         elif used >= reset_thresh:
547             if debug:
548                 print "Memory used = %s" %(used)
549             # Try and find a hog
550             slicelist = slices.values()
551             slicelist.sort(lambda a, b: b['rss'] - a['rss'])
552             for slice in slicelist:
553                 percent = 100. * slice['rss'] / total_rss
554
555                 if slice['rss'] < rss_min:
556                     continue
557                 
558                 print "%d%% swap consumed, slice %s is using %s (%d%%) of memory" % \
559                       (used,
560                        slice['name'],
561                        format_bytes(slice['rss'] * 1024, si = False),
562                        percent)
563
564                 slice['procs'].sort(lambda a, b: b['rss'] - a['rss'])
565
566                 table = "%5s %10s %10s %4s %4s %s\n\n" % ("PID", "VIRT", "RES", '%CPU', '%MEM', 'COMMAND')
567                 for proc in slice['procs']:
568                     table += "%5s %10s %10s %4.1f %4.1f %s\n" % \
569                              (proc['pid'],
570                               format_bytes(proc['vsize'] * 1024, si = False),
571                               format_bytes(proc['rss'] * 1024, si = False),
572                               proc['pcpu'], proc['pmem'], proc['cmd'])
573
574                 params = {'hostname': socket.gethostname(),
575                           'date': time.asctime(time.gmtime()) + " GMT",
576                           'table': table,
577                           'slice': slice['name'],
578                           'rss': format_bytes(slice['rss'] * 1024, si = False),
579                           'percent': percent}
580
581                 # Match slice name against system slice patterns
582                 is_system_slice = filter(None, [re.match(pattern, slice['name']) for pattern in system_slices])
583
584                 if is_system_slice: 
585                         if slice['name'] not in warned:
586                                 warned.append(slice['name'])
587                                 if debug:
588                                         print alarm_subject % params
589                                         print alarm_body % params
590                         else:
591                                 print "Warning slice " + slice['name']
592                                 slicemail(slice['name'], alarm_subject % params, 
593                                         alarm_body % params)
594                 else:
595                         # Reset slice
596                         if not resetlist.has_key(slice['name']):
597                                 resetlist[slice['name']] = Reset(slice['name'])
598                         resetlist[slice['name']].reset(params)
599                         slices = slicestat(names)
600
601         if timer <= 0 or used >= (last_used + change_thresh):
602             if used >= (last_used + change_thresh):
603                 print "%d%% swap consumed, %d%% in last %d seconds" % \
604                       (used, used - last_used, period - timer)
605             # Get slice state
606             slices = slicestat(names)
607             # Reset timer
608             timer = period
609             # Keep track of large changes in swap utilization
610             last_used = used
611
612         timer -= 1
613         time.sleep(1)
614
615     removepid("swapmon")
616
617 if __name__ == '__main__':
618     main()