<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>[9895] CalendarServer/trunk</title>
</head>
<body>

<style type="text/css"><!--
#msg dl.meta { border: 1px #006 solid; background: #369; padding: 6px; color: #fff; }
#msg dl.meta dt { float: left; width: 6em; font-weight: bold; }
#msg dt:after { content:':';}
#msg dl, #msg dt, #msg ul, #msg li, #header, #footer, #logmsg { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt;  }
#msg dl a { font-weight: bold}
#msg dl a:link    { color:#fc3; }
#msg dl a:active  { color:#ff0; }
#msg dl a:visited { color:#cc6; }
h3 { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; font-weight: bold; }
#msg pre { overflow: auto; background: #ffc; border: 1px #fa0 solid; padding: 6px; }
#logmsg { background: #ffc; border: 1px #fa0 solid; padding: 1em 1em 0 1em; }
#logmsg p, #logmsg pre, #logmsg blockquote { margin: 0 0 1em 0; }
#logmsg p, #logmsg li, #logmsg dt, #logmsg dd { line-height: 14pt; }
#logmsg h1, #logmsg h2, #logmsg h3, #logmsg h4, #logmsg h5, #logmsg h6 { margin: .5em 0; }
#logmsg h1:first-child, #logmsg h2:first-child, #logmsg h3:first-child, #logmsg h4:first-child, #logmsg h5:first-child, #logmsg h6:first-child { margin-top: 0; }
#logmsg ul, #logmsg ol { padding: 0; list-style-position: inside; margin: 0 0 0 1em; }
#logmsg ul { text-indent: -1em; padding-left: 1em; }#logmsg ol { text-indent: -1.5em; padding-left: 1.5em; }
#logmsg > ul, #logmsg > ol { margin: 0 0 1em 0; }
#logmsg pre { background: #eee; padding: 1em; }
#logmsg blockquote { border: 1px solid #fa0; border-left-width: 10px; padding: 1em 1em 0 1em; background: white;}
#logmsg dl { margin: 0; }
#logmsg dt { font-weight: bold; }
#logmsg dd { margin: 0; padding: 0 0 0.5em 0; }
#logmsg dd:before { content:'\00bb';}
#logmsg table { border-spacing: 0px; border-collapse: collapse; border-top: 4px solid #fa0; border-bottom: 1px solid #fa0; background: #fff; }
#logmsg table th { text-align: left; font-weight: normal; padding: 0.2em 0.5em; border-top: 1px dotted #fa0; }
#logmsg table td { text-align: right; border-top: 1px dotted #fa0; padding: 0.2em 0.5em; }
#logmsg table thead th { text-align: center; border-bottom: 1px solid #fa0; }
#logmsg table th.Corner { text-align: left; }
#logmsg hr { border: none 0; border-top: 2px dashed #fa0; height: 1px; }
#header, #footer { color: #fff; background: #636; border: 1px #300 solid; padding: 6px; }
#patch { width: 100%; }
#patch h4 {font-family: verdana,arial,helvetica,sans-serif;font-size:10pt;padding:8px;background:#369;color:#fff;margin:0;}
#patch .propset h4, #patch .binary h4 {margin:0;}
#patch pre {padding:0;line-height:1.2em;margin:0;}
#patch .diff {width:100%;background:#eee;padding: 0 0 10px 0;overflow:auto;}
#patch .propset .diff, #patch .binary .diff  {padding:10px 0;}
#patch span {display:block;padding:0 10px;}
#patch .modfile, #patch .addfile, #patch .delfile, #patch .propset, #patch .binary, #patch .copfile {border:1px solid #ccc;margin:10px 0;}
#patch ins {background:#dfd;text-decoration:none;display:block;padding:0 10px;}
#patch del {background:#fdd;text-decoration:none;display:block;padding:0 10px;}
#patch .lines, .info {color:#888;background:#fff;}
--></style>
<div id="msg">
<dl class="meta">
<dt>Revision</dt> <dd><a href="http://trac.calendarserver.org//changeset/9895">9895</a></dd>
<dt>Author</dt> <dd>sagen@apple.com</dd>
<dt>Date</dt> <dd>2012-10-04 12:18:18 -0700 (Thu, 04 Oct 2012)</dd>
</dl>

<h3>Log Message</h3>
<pre>Watch for process memory growth and restart any exceeding configured limit</pre>

<h3>Modified Paths</h3>
<ul>
<li><a href="#CalendarServertrunkcalendarservertapcaldavpy">CalendarServer/trunk/calendarserver/tap/caldav.py</a></li>
<li><a href="#CalendarServertrunkcalendarservertaptesttest_utilpy">CalendarServer/trunk/calendarserver/tap/test/test_util.py</a></li>
<li><a href="#CalendarServertrunkcalendarservertaputilpy">CalendarServer/trunk/calendarserver/tap/util.py</a></li>
<li><a href="#CalendarServertrunktwistedcaldavstdconfigpy">CalendarServer/trunk/twistedcaldav/stdconfig.py</a></li>
</ul>

</div>
<div id="patch">
<h3>Diff</h3>
<a id="CalendarServertrunkcalendarservertapcaldavpy"></a>
<div class="modfile"><h4>Modified: CalendarServer/trunk/calendarserver/tap/caldav.py (9894 => 9895)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/trunk/calendarserver/tap/caldav.py        2012-10-04 17:29:39 UTC (rev 9894)
+++ CalendarServer/trunk/calendarserver/tap/caldav.py        2012-10-04 19:18:18 UTC (rev 9895)
</span><span class="lines">@@ -75,7 +75,7 @@
</span><span class="cx"> from twistedcaldav.stdconfig import DEFAULT_CONFIG, DEFAULT_CONFIG_FILE
</span><span class="cx"> from twistedcaldav.upgrade import UpgradeFileSystemFormatService, PostDBImportService
</span><span class="cx"> 
</span><del>-from calendarserver.tap.util import pgServiceFromConfig, getDBPool
</del><ins>+from calendarserver.tap.util import pgServiceFromConfig, getDBPool, MemoryLimitService
</ins><span class="cx"> 
</span><span class="cx"> from twext.enterprise.ienterprise import POSTGRES_DIALECT
</span><span class="cx"> from twext.enterprise.ienterprise import ORACLE_DIALECT
</span><span class="lines">@@ -1194,6 +1194,11 @@
</span><span class="cx">         s.processMonitor = monitor
</span><span class="cx">         monitor.setServiceParent(s)
</span><span class="cx"> 
</span><ins>+        if config.MemoryLimiter.Enabled:
+            memoryLimiter = MemoryLimitService(monitor, config.MemoryLimiter.Seconds,
+                config.MemoryLimiter.Bytes, config.MemoryLimiter.ResidentOnly)
+            memoryLimiter.setServiceParent(s)
+
</ins><span class="cx">         for name, pool in config.Memcached.Pools.items():
</span><span class="cx">             if pool.ServerEnabled:
</span><span class="cx">                 self.log_info(
</span><span class="lines">@@ -1635,7 +1640,6 @@
</span><span class="cx">         for name in self.processes:
</span><span class="cx">             self.startProcess(name)
</span><span class="cx"> 
</span><del>-
</del><span class="cx">     def stopService(self):
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx">         Return a deferred that fires when all child processes have ended.
</span></span></pre></div>
<a id="CalendarServertrunkcalendarservertaptesttest_utilpy"></a>
<div class="modfile"><h4>Modified: CalendarServer/trunk/calendarserver/tap/test/test_util.py (9894 => 9895)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/trunk/calendarserver/tap/test/test_util.py        2012-10-04 17:29:39 UTC (rev 9894)
+++ CalendarServer/trunk/calendarserver/tap/test/test_util.py        2012-10-04 19:18:18 UTC (rev 9895)
</span><span class="lines">@@ -14,10 +14,11 @@
</span><span class="cx"> # limitations under the License.
</span><span class="cx"> ##
</span><span class="cx"> 
</span><del>-from calendarserver.tap.util import computeProcessCount, directoryFromConfig
</del><ins>+from calendarserver.tap.util import computeProcessCount, directoryFromConfig, MemoryLimitService
</ins><span class="cx"> from twistedcaldav.test.util import TestCase
</span><span class="cx"> from twistedcaldav.config import config
</span><span class="cx"> from twistedcaldav.directory.augment import AugmentXMLDB
</span><ins>+from twisted.internet.task import Clock
</ins><span class="cx"> 
</span><span class="cx"> class ProcessCountTestCase(TestCase):
</span><span class="cx"> 
</span><span class="lines">@@ -62,3 +63,72 @@
</span><span class="cx">             # augmentService set to AugmentXMLDB
</span><span class="cx">             if hasattr(service, &quot;augmentService&quot;):
</span><span class="cx">                 self.assertTrue(isinstance(service.augmentService, AugmentXMLDB))
</span><ins>+
+
+
+# Stub classes for MemoryLimitServiceTestCase
+
+class StubProtocol(object):
+    def __init__(self, transport):
+        self.transport = transport
+
+class StubProcess(object):
+    def __init__(self, pid):
+        self.pid = pid
+
+class StubProcessMonitor(object):
+    def __init__(self, processes, protocols):
+        self.processes = processes
+        self.protocols = protocols
+        self.history = []
+
+    def stopProcess(self, name):
+        self.history.append(name)
+
+
+class MemoryLimitServiceTestCase(TestCase):
+
+    def test_checkMemory(self):
+        &quot;&quot;&quot;
+        Set up stub objects to verify MemoryLimitService.checkMemory( )
+        only stops the processes whose memory usage exceeds the configured
+        limit, and skips memcached
+        &quot;&quot;&quot;
+        data = {
+            # PID : (name, resident memory-in-bytes, virtual memory-in-bytes)
+            101 : (&quot;process #1&quot;, 10, 1010),
+            102 : (&quot;process #2&quot;, 30, 1030),
+            103 : (&quot;process #3&quot;, 50, 1050),
+            99  : (&quot;memcached-Default&quot;, 10, 1010),
+        }
+
+        processes = []
+        protocols = {}
+        for pid, (name, resident, virtual) in data.iteritems():
+            protocols[name] = StubProtocol(StubProcess(pid))
+            processes.append(name)
+        processMonitor = StubProcessMonitor(processes, protocols)
+        clock = Clock()
+        service = MemoryLimitService(processMonitor, 10, 15, True, reactor=clock)
+
+        # For testing, use a stub implementation of memory-usage lookup
+        def testMemoryForPID(pid, residentOnly):
+            return data[pid][1 if residentOnly else 2]
+        service._memoryForPID = testMemoryForPID
+
+        # After 5 seconds, nothing should have happened, since the interval is 10 seconds
+        service.startService()
+        clock.advance(5)
+        self.assertEquals(processMonitor.history, [])
+
+        # After 7 more seconds, processes 2 and 3 should have been stopped since their
+        # memory usage exceeds 10 bytes
+        clock.advance(7)
+        self.assertEquals(processMonitor.history, ['process #2', 'process #3'])
+
+        # Now switch to looking at virtual memory, in which case all 3 processes
+        # should be stopped
+        service._residentOnly = False
+        processMonitor.history = []
+        clock.advance(10)
+        self.assertEquals(processMonitor.history, ['process #1', 'process #2', 'process #3'])
</ins></span></pre></div>
<a id="CalendarServertrunkcalendarservertaputilpy"></a>
<div class="modfile"><h4>Modified: CalendarServer/trunk/calendarserver/tap/util.py (9894 => 9895)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/trunk/calendarserver/tap/util.py        2012-10-04 17:29:39 UTC (rev 9894)
+++ CalendarServer/trunk/calendarserver/tap/util.py        2012-10-04 19:18:18 UTC (rev 9895)
</span><span class="lines">@@ -23,12 +23,14 @@
</span><span class="cx">     &quot;getRootResource&quot;,
</span><span class="cx">     &quot;getDBPool&quot;,
</span><span class="cx">     &quot;FakeRequest&quot;,
</span><ins>+    &quot;MemoryLimitService&quot;,
</ins><span class="cx"> ]
</span><span class="cx"> 
</span><span class="cx"> import errno
</span><span class="cx"> import os
</span><span class="cx"> from time import sleep
</span><span class="cx"> from socket import fromfd, AF_UNIX, SOCK_STREAM, socketpair
</span><ins>+import psutil
</ins><span class="cx"> 
</span><span class="cx"> from twext.python.filepath import CachingFilePath as FilePath
</span><span class="cx"> from twext.python.log import Logger
</span><span class="lines">@@ -37,6 +39,7 @@
</span><span class="cx"> from twext.web2.http_headers import Headers
</span><span class="cx"> from twext.web2.static import File as FileResource
</span><span class="cx"> 
</span><ins>+from twisted.application.service import Service
</ins><span class="cx"> from twisted.cred.portal import Portal
</span><span class="cx"> from twisted.internet.defer import inlineCallbacks, returnValue
</span><span class="cx"> from twisted.internet import reactor as _reactor
</span><span class="lines">@@ -68,6 +71,7 @@
</span><span class="cx"> from twext.enterprise.ienterprise import ORACLE_DIALECT
</span><span class="cx"> from twext.enterprise.adbapi2 import ConnectionPool, ConnectionPoolConnection
</span><span class="cx"> 
</span><ins>+
</ins><span class="cx"> try:
</span><span class="cx">     from twistedcaldav.authkerb import NegotiateCredentialFactory
</span><span class="cx">     NegotiateCredentialFactory  # pacify pyflakes
</span><span class="lines">@@ -821,3 +825,90 @@
</span><span class="cx">     def addResponseFilter(*args, **kwds):
</span><span class="cx">         pass
</span><span class="cx"> 
</span><ins>+
+def memoryForPID(pid, residentOnly=True):
+    &quot;&quot;&quot;
+    Return the amount of memory in use for the given process.  If residentOnly is True,
+        then RSS is returned; if False, then virtual memory is returned.
+    @param pid: process id
+    @type pid: C{int}
+    @param residentOnly: Whether only resident memory should be included
+    @type residentOnly: C{boolean}
+    @return: Memory used by process in bytes
+    @rtype: C{int}
+    &quot;&quot;&quot;
+    memoryInfo = psutil.Process(pid).get_memory_info()
+    return memoryInfo.rss if residentOnly else memoryInfo.vms
+
+
+class MemoryLimitService(Service, object):
+    &quot;&quot;&quot;
+    A service which when paired with a DelayedStartupProcessMonitor will periodically
+    examine the memory usage of the monitored processes and stop any which exceed
+    a configured limit.  Memcached processes are ignored.
+    &quot;&quot;&quot;
+
+    def __init__(self, processMonitor, intervalSeconds, limitBytes, residentOnly, reactor=None):
+        &quot;&quot;&quot;
+        @param processMonitor: the DelayedStartupProcessMonitor
+        @param intervalSeconds: how often to check
+        @type intervalSeconds: C{int}
+        @param limitBytes: any monitored process over this limit is stopped
+        @type limitBytes: C{int}
+        @param residentOnly: whether only resident memory should be included
+        @type residentOnly: C{boolean}
+        @param reactor: for testing
+        &quot;&quot;&quot;
+        self._processMonitor = processMonitor
+        self._seconds = intervalSeconds
+        self._bytes = limitBytes
+        self._residentOnly = residentOnly
+        self._delayedCall = None
+        if reactor is None:
+            from twisted.internet import reactor
+        self._reactor = reactor
+
+        # Unit tests can swap out _memoryForPID
+        self._memoryForPID = memoryForPID
+
+    def startService(self):
+        &quot;&quot;&quot;
+        Start scheduling the memory checks
+        &quot;&quot;&quot;
+        super(MemoryLimitService, self).startService()
+        self._delayedCall = self._reactor.callLater(self._seconds, self.checkMemory)
+
+    def stopService(self):
+        &quot;&quot;&quot;
+        Stop checking memory
+        &quot;&quot;&quot;
+        super(MemoryLimitService, self).stopService()
+        if self._delayedCall is not None and self._delayedCall.active():
+            self._delayedCall.cancel()
+            self._delayedCall = None
+
+    def checkMemory(self):
+        &quot;&quot;&quot;
+        Stop any processes monitored by our paired processMonitor whose resident
+        memory exceeds our configured limitBytes.  Reschedule intervalSeconds in
+        the future.
+        &quot;&quot;&quot;
+        try:
+            for name in self._processMonitor.processes:
+                if name.startswith(&quot;memcached&quot;):
+                    continue
+                proto = self._processMonitor.protocols.get(name, None)
+                if proto is not None:
+                    proc = proto.transport
+                    pid = proc.pid
+                    try:
+                        memory = self._memoryForPID(pid, self._residentOnly)
+                    except Exception, e:
+                        log.error(&quot;Unable to determine memory usage of PID: %d (%s)&quot; % (pid, e))
+                        continue
+                    if memory &gt; self._bytes:
+                        log.warn(&quot;Killing large process: %s PID:%d %s:%d&quot; %
+                            (name, pid, &quot;Resident&quot; if self._residentOnly else &quot;Virtual&quot;, memory))
+                        self._processMonitor.stopProcess(name)
+        finally:
+            self._delayedCall = self._reactor.callLater(self._seconds, self.checkMemory)
</ins></span></pre></div>
<a id="CalendarServertrunktwistedcaldavstdconfigpy"></a>
<div class="modfile"><h4>Modified: CalendarServer/trunk/twistedcaldav/stdconfig.py (9894 => 9895)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/trunk/twistedcaldav/stdconfig.py        2012-10-04 17:29:39 UTC (rev 9894)
+++ CalendarServer/trunk/twistedcaldav/stdconfig.py        2012-10-04 19:18:18 UTC (rev 9895)
</span><span class="lines">@@ -491,6 +491,15 @@
</span><span class="cx">         },
</span><span class="cx">     },
</span><span class="cx"> 
</span><ins>+    # How large a spawned process is allowed to get before it's stopped
+    &quot;MemoryLimiter&quot; : {
+        &quot;Enabled&quot; : True,
+        &quot;Seconds&quot; : 60, # How often to check memory sizes (in seconds)
+        &quot;Bytes&quot;   : 2 * 1024 * 1024 * 1024, # Memory limit (RSS in bytes)
+        &quot;ResidentOnly&quot; : True,  # True: only take into account resident memory;
+                                # False: include virtual memory
+    },
+
</ins><span class="cx">     #
</span><span class="cx">     # Service ACLs
</span><span class="cx">     #
</span></span></pre>
</div>
</div>

</body>
</html>