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