- add SZ ("potential" memory usage) to e-mails to see if this can be
[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.10 2006/08/16 16:18:45 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%%) (%(sz)s writable).
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%%) (%(sz)s writable). It was not reset,
116 but please verify its 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%%) (%(sz)s writable)
134 after repeated restarts.
135
136 Please reply to this message explaining the nature of your experiment,
137 and what you are doing to address the problem.
138
139 %(slice)s processes prior to reset:
140
141 %(table)s
142
143 %(date)s %(hostname)s reset %(slice)s
144 """.lstrip()
145
146
147
148 class Reset:
149         """
150         Keeps track of state information for resets and kills
151
152         resettimeleft - timeout before checking for next reset
153         resetcount - number of strikes 
154         killtimeleft - time out before removing from kill queue
155         {kill,reset}mail - Time of last email
156         kill - State of kill.  If slice is already being killed, wait before retry.
157         """
158
159         def __init__(self,name):
160                 self.name = name
161                 self.resettimeleft = reset_timeout
162                 self.resetcount = 0 
163                 self.resetmail = 0
164                 self.killtimeleft = kill_timeout
165                 self.killmail = 0
166
167         def __repr__(self):
168                 return self.name
169         
170         def update(self):
171                 # Count down for next check of reset slice.
172                 if self.resettimeleft > 0:
173                         self.resettimeleft -= 1
174                         if debug and verbose:
175                                 print "%s has %s seconds in probation" \
176                                         %(self.name, self.killtimeleft)
177                 if self.killtimeleft > 0:
178                         # Count down kill probation timer (killtimeleft)
179                         self.killtimeleft -= 1
180                         if self.killtimeleft == 1:
181                                 print "%s is out of probation" % self.name
182                 else:
183                         # Once out of probation period (killtimeleft), remove strikes
184                         self.resetcount = 0
185
186
187         # Check to see if a slice needs to be killed.  If it has been killed more 
188         # than kill_thresh in 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:
191                         if debug:
192                                 print kill_subject % params
193                                 print kill_body % params
194                         try:
195                                 pid = os.fork()
196                                 if pid == 0:
197                                         print "Slice %s is being killed." % self.name   
198                                         vserver = VServer(self.name)
199                                         vserver.stop()
200                                         os._exit(0)
201                                 else:
202                                         os.waitpid(pid,0)
203                         except Exception, err:
204                                 print "Warning: Exception received while killing slice %s: %s" \
205                                         % self.name, err
206                         if (time.time() - self.killmail) > email_timeout:
207                                 slicemail(self.name, kill_subject % params, kill_body % params)
208                                 print "Sending KILL email for slice %s" % self.name
209                                 self.killmail = time.time() 
210                         return True
211                 return False 
212
213         # Reset slice after checking to see if slice is out of timeout.
214         # Increment resetcount, check to see if larger than kill_thresh.
215         def reset(self, params):
216                 # If its the first reset (came back after kill)
217                 # or if its been reset before
218                 # and we are out of the reset timeout.
219                 if self.resetcount == 0 or self.resettimeleft == 0:
220                         # Do we need to kill this slice?  Check history first.
221                         if self.checkkill(params):
222                                 return
223                         # Update counters
224                         self.resetcount += 1
225                         self.killtimeleft = kill_timeout
226                         self.resettimeleft = reset_timeout
227                         print "%s has %s seconds to die and has been reset %s times" \
228                                 %(self.name, self.resettimeleft, self.resetcount)
229                         if debug:
230                                 print reset_subject % params
231                                 print reset_body % params
232                         try:
233                                 pid = os.fork()
234                                 if pid == 0:
235                                         print "Resetting slice " + self.name 
236                                         vserver = VServer(self.name)
237                                         vserver.stop()
238                                         vserver.start(wait = False)
239                                         os._exit(0)
240                                 else:
241                                         os.waitpid(pid,0)
242                         except Exception, err:
243                                 print "Warning: Exception received while resetting slice %s:" \
244                                         % self.name, err
245                         if (time.time() - self.resetmail) > email_timeout:
246                                 slicemail(self.name, reset_subject % params, reset_body % params)
247                                 print "Sending Reset email for slice %s" % self.name
248                                 self.resetmail = time.time() 
249
250
251 def usage():
252     print """
253 Usage: %s [OPTIONS]...
254
255 Options:
256         -d, --debug             Enable debugging (default: %s)
257         -v, --verbose           Increase verbosity level (default: %d)
258         -f, --file=FILE         Data file (default: %s)
259         -s, --slice=SLICE       Constrain monitoring to these slices (default: all)
260         -p, --period=SECONDS    Seconds between normal process analysis (default: %s)
261         --reset-thresh=PERCENT  Swap utilization at which slice reset is attempted
262         --reboot-thresh=PERCENT Swap utilization at which the machine is rebooted
263         --min-thresh=PERCENT    Minimum physical memory utilization to be considered a hog
264         --system-slice=SLICE    System slice that should not be reset
265         --status                Print memory usage statistics and exit
266         -h, --help              This message
267 """.lstrip() % (sys.argv[0], debug, verbose, datafile, format_period(period))
268
269 def slicestat(names = None):
270     """
271     Get status of specified slices (if names is None or empty, all
272     slices). vsize, sz, and rss are in KiB. Returns
273
274     {xid: {'xid': slice_id,
275            'name': slice_name,
276            'procs': [{'pid': pid, 'xid': slice_id, 'user', username, 'cmd': command,
277                       'vsize': virtual_kib, 'sz': potential_kib, 'rss': physical_kib,
278                       'pcpu': cpu_percent, 'pmem': mem_percent}]
279            'vsize': total_virtual_kib,
280            'sz': total_potential_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', 'sz', '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, 'sz': 0, 'rss': 0}
362
363         slice['procs'].append(proc)
364         slice['vsize'] += proc['vsize']
365         slice['sz'] += proc['sz']
366         slice['rss'] += proc['rss']
367
368         slices[proc['xid']] = slice
369
370     return slices
371
372 def memtotal():
373     """
374     Returns total physical and swap memory on the system in KiB.
375     """
376
377     mem = 0
378     swap = 0
379
380     meminfo = open("/proc/meminfo", "r")
381     for line in meminfo.readlines():
382         try:
383             (name, value, kb) = line.split()
384         except:
385             continue
386         if name == "MemTotal:": 
387             mem = int(value)
388         elif name == "SwapTotal:":
389             swap = int(value)
390     meminfo.close()
391
392     return (mem, swap)
393
394 def swap_used():
395     """
396     Returns swap utilization on the system as a whole percentage (0-100).
397     """
398
399     total_swap = 0
400     total_used = 0
401
402     try:
403         swaps = open("/proc/swaps", "r")
404         # Eat header line
405         lines = swaps.readlines()[1:]
406         swaps.close()
407         for line in lines:
408             # /dev/mapper/planetlab-swap partition 1048568 3740 -1
409             (filename, type, size, used, priority) = line.strip().split()
410             try:
411                 total_swap += int(size)
412                 total_used += int(used)
413             except ValueEror, err:
414                 pass
415     except (IOError, KeyError), err:
416         pass
417
418     return 100 * total_used / total_swap
419
420 def summary(slices = None, total_mem = None, total_swap = None):
421     """
422     Return a summary of memory usage by slice.
423     """
424     if not slices:
425         slices = slicestat()
426     slicelist = slices.values()
427     slicelist.sort(lambda a, b: b['sz'] - a['sz'])
428     if total_mem is None or total_swap is None:
429         (total_mem, total_swap) = memtotal()
430
431     table = "%-20s%10s%24s%24s\n\n" % ("Slice", "Processes", "Memory Usage", "Potential Usage")
432     for slice in slicelist:
433         table += "%-20s%10d%16s (%4.1f%%)%16s (%4.1f%%)\n" % \
434                  (slice['name'], len(slice['procs']),
435                   format_bytes(slice['rss'] * 1024, si = False),
436                   100. * slice['rss'] / total_mem,
437                   format_bytes(slice['sz'] * 1024, si = False),
438                   100. * slice['sz'] / (total_mem + total_swap))
439                   
440
441     return table
442
443 def main():
444     # Defaults
445     global debug, verbose, datafile
446     global period, change_thresh, reset_thresh, reboot_thresh, rss_min, system_slices
447     # All slices
448     names = []
449
450     try:
451         longopts = ["debug", "verbose", "file=", "slice=", "status", "help"]
452         longopts += ["period=", "reset-thresh=", "reboot-thresh=", "min-thresh=", "system-slice="]
453         (opts, argv) = getopt.getopt(sys.argv[1:], "dvf:s:ph", longopts)
454     except getopt.GetoptError, err:
455         print "Error: " + err.msg
456         usage()
457         sys.exit(1)
458
459     for (opt, optval) in opts:
460         if opt == "-d" or opt == "--debug":
461             debug = True
462         elif opt == "-v" or opt == "--verbose":
463             verbose += 1
464         elif opt == "-f" or opt == "--file":
465             datafile = optval
466         elif opt == "-s" or opt == "--slice":
467             names.append(optval)
468         elif opt == "-p" or opt == "--period":
469             period = int(optval)
470         elif opt == "--change-thresh":
471             change_thresh = int(optval)
472         elif opt == "--reset-thresh":
473             reset_thresh = int(optval)
474         elif opt == "--reboot-thresh":
475             reboot_thresh = int(optval)
476         elif opt == "--min-thresh":
477             rss_min = int(optval)
478         elif opt == "--system-slice":
479             system_slices.append(optval)
480         elif opt == "--status":
481             print summary(slicestat(names))
482             sys.exit(0)
483         else:
484             usage()
485             sys.exit(0)
486
487     # Check if we are already running
488     writepid("swapmon")
489
490     if not debug:
491         daemonize()
492         # Rewrite PID file
493         writepid("swapmon")
494         # Redirect stdout and stderr to syslog
495         syslog.openlog("swapmon")
496         sys.stdout = sys.stderr = Logger()
497
498     # Get total memory
499     (total_mem, total_swap) = memtotal()
500
501     try:
502         f = open(datafile, "r+")
503         if verbose:
504             print "Loading %s" % datafile
505         (version, slices) = pickle.load(f)
506         f.close()
507         # Check version of data file
508         if version != "$Id: swapmon.py,v 1.10 2006/08/16 16:18:45 faiyaza Exp $":
509             print "Not using old version '%s' data file %s" % (version, datafile)
510             raise Exception
511
512         params = {'hostname': socket.gethostname(),
513                   'date': time.asctime(time.gmtime()) + " GMT",
514                   'table': summary(slices, total_mem, total_swap)}
515
516         if debug:
517             print rebooted_subject % params
518             print rebooted_body % params
519         else:
520             slicemail(None, rebooted_subject % params, rebooted_body % params)
521
522         # Delete data file
523         os.unlink(datafile)
524     except Exception:
525         version = "$Id: swapmon.py,v 1.10 2006/08/16 16:18:45 faiyaza Exp $"
526         slices = {}
527
528     # Query process table every 30 seconds, or when a large change in
529     # swap utilization is detected.
530     timer = period
531     last_used = None
532     used = None
533
534     # System slices that we have warned but could not reset
535     warned = []
536
537     # Slices that were reset
538     resetlist = {}
539
540     while True:
541         used = swap_used()
542
543         for resetslice in resetlist.keys():
544             resetlist[resetslice].update()
545         
546         if last_used is None:
547             last_used = used
548
549         if verbose:
550             print "%d%% swap consumed" % used
551
552         if used >= reboot_thresh:
553             # Dump slice state before rebooting
554             if verbose:
555                 print "Saving %s" % datafile
556             f = open(datafile, "w")
557             pickle.dump((version, slices), f)
558             f.close()
559
560             # Goodbye, cruel world
561             print "%d%% swap consumed, rebooting" % used
562             if not debug:
563                 bwlimit.run("/bin/sync; /sbin/reboot -f")
564
565         elif used >= reset_thresh:
566             if debug:
567                 print "Memory used = %s" %(used)
568             # Try and find a hog
569             slicelist = slices.values()
570             slicelist.sort(lambda a, b: b['rss'] - a['rss'])
571             for slice in slicelist:
572                 percent = 100. * slice['rss'] / total_mem
573
574                 if slice['rss'] < rss_min:
575                     continue
576                 
577                 print "%d%% swap consumed, slice %s is using %s (%d%%) of memory" % \
578                       (used,
579                        slice['name'],
580                        format_bytes(slice['rss'] * 1024, si = False),
581                        percent)
582
583                 slice['procs'].sort(lambda a, b: b['rss'] - a['rss'])
584
585                 table = "%5s %10s %10s %10s %4s %4s %s\n\n" % ("PID", "VIRT", "SZ", "RES", '%CPU', '%MEM', 'COMMAND')
586                 for proc in slice['procs']:
587                     table += "%5s %10s %10s %10s %4.1f %4.1f %s\n" % \
588                              (proc['pid'],
589                               format_bytes(proc['vsize'] * 1024, si = False),
590                               format_bytes(proc['sz'] * 1024, si = False),
591                               format_bytes(proc['rss'] * 1024, si = False),
592                               proc['pcpu'], proc['pmem'], proc['cmd'])
593
594                 params = {'hostname': socket.gethostname(),
595                           'date': time.asctime(time.gmtime()) + " GMT",
596                           'table': table,
597                           'slice': slice['name'],
598                           'rss': format_bytes(slice['rss'] * 1024, si = False),
599                           'sz': format_bytes(slice['sz'] * 1024, si = False),
600                           'percent': percent}
601
602                 # Match slice name against system slice patterns
603                 is_system_slice = filter(None, [re.match(pattern, slice['name']) for pattern in system_slices])
604
605                 if is_system_slice: 
606                     # Do not reset system slices, just warn once
607                     if slice['name'] not in warned:
608                         warned.append(slice['name'])
609                         if debug:
610                             print alarm_subject % params
611                             print alarm_body % params
612                         else:
613                             print "Warning slice " + slice['name']
614                             slicemail(slice['name'], alarm_subject % params, 
615                                       alarm_body % params)
616                 else:
617                     # Reset slice
618                     if not resetlist.has_key(slice['name']):
619                         resetlist[slice['name']] = Reset(slice['name'])
620                     resetlist[slice['name']].reset(params)
621                     slices = slicestat(names)
622
623         if timer <= 0 or used >= (last_used + change_thresh):
624             if used >= (last_used + change_thresh):
625                 print "%d%% swap consumed, %d%% in last %d seconds" % \
626                       (used, used - last_used, period - timer)
627             # Get slice state
628             slices = slicestat(names)
629             # Reset timer
630             timer = period
631             # Keep track of large changes in swap utilization
632             last_used = used
633
634         timer -= 1
635         time.sleep(1)
636
637     removepid("swapmon")
638
639 if __name__ == '__main__':
640     main()