[CalendarServer-changes] [15715] CalendarServer/trunk/txdav

source_changes at macosforge.org source_changes at macosforge.org
Tue Jun 28 10:04:59 PDT 2016


Revision: 15715
          http://trac.calendarserver.org//changeset/15715
Author:   cdaboo at apple.com
Date:     2016-06-28 10:04:59 -0700 (Tue, 28 Jun 2016)
Log Message:
-----------
When splitting events, make sure we uncache attendee homes as we go around the attendee loop to ensure we don't use too much memory.

Modified Paths:
--------------
    CalendarServer/trunk/txdav/caldav/datastore/sql.py
    CalendarServer/trunk/txdav/caldav/datastore/test/test_sql.py
    CalendarServer/trunk/txdav/common/datastore/sql.py

Modified: CalendarServer/trunk/txdav/caldav/datastore/sql.py
===================================================================
--- CalendarServer/trunk/txdav/caldav/datastore/sql.py	2016-06-28 16:16:43 UTC (rev 15714)
+++ CalendarServer/trunk/txdav/caldav/datastore/sql.py	2016-06-28 17:04:59 UTC (rev 15715)
@@ -339,11 +339,47 @@
 
 
     @inlineCallbacks
+    def calendarObjectDetailsWithUID(self, txn, uid):
+        """
+        Return details about all child object resources with the specified UID.
+        Only "owned" resources are returned, no shared resources.
+
+        @param txn: transaction to use
+        @type txn: L{CommonStoreTransaction}
+        @param uid: UID to query
+        @type uid: C{str}
+
+        @return: list of C{list} of home id, calendar id, and calendar object id
+        @rtype: C{list} of C{list}
+        """
+
+        # First find the resource-ids of the (home, parent, object) for each object matching the UID.
+        obj = CalendarHome._objectSchema
+        bind = CalendarHome._bindSchema
+        rows = (yield Select(
+            [bind.HOME_RESOURCE_ID, obj.PARENT_RESOURCE_ID, obj.RESOURCE_ID],
+            From=obj.join(bind, obj.PARENT_RESOURCE_ID == bind.RESOURCE_ID),
+            Where=(obj.UID == Parameter("uid")).And(bind.BIND_MODE == _BIND_MODE_OWN),
+        ).on(txn, uid=uid))
+
+        returnValue(rows)
+
+
+    @inlineCallbacks
     def calendarObjectsWithUID(self, txn, uid):
         """
         Return all child object resources with the specified UID. Only "owned" resources are returned,
         no shared resources.
 
+        WARNING: this method loads all the home, calendar, and calendar object
+        resources for the specified UID. This is potentially a memory hog for
+        the case of an event with a very large number of attendees. Please avoid
+        using this. Instead use L{calendarObjectDetailsWithUID}, which just
+        looks up the IDs, which can then be loaded one at a time when needed.
+        When doing that, make sure that all references to previously processed
+        objects are removed so that they don't hang around in memory and cause
+        problems.
+
         @param txn: transaction to use
         @type txn: L{CommonStoreTransaction}
         @param uid: UID to query
@@ -5350,7 +5386,7 @@
         if onlyThis:
             resources = ()
         else:
-            resources = (yield CalendarStoreFeatures(self._txn._store).calendarObjectsWithUID(self._txn, self._uid))
+            resources = (yield CalendarStoreFeatures(self._txn._store).calendarObjectDetailsWithUID(self._txn, self._uid))
 
         if splitter is None:
             splitter = iCalSplitter(config.Scheduling.Options.Splitting.Size, config.Scheduling.Options.Splitting.PastDays)
@@ -5395,15 +5431,40 @@
             )
 
         # Split each one - but not this resource
-        for resource in resources:
-            if resource is None or resource._resourceID == self._resourceID:
+        lastHome = None
+        for homeID, parentID, resourceID in sorted(resources):
+
+            # Each time the home changes, wipe it from the txn cache so that
+            # we do not accumulate them in memory whilst we go through this loop
+            if lastHome is not None:
+                if lastHome.id() != homeID:
+                    self._txn.cleanHomeCache(lastHome)
+
+            if resourceID == self._resourceID:
                 continue
+            lastHome = home = (yield self._txn.calendarHomeWithResourceID(homeID))
+            if home is None:
+                continue
+            parent = (yield home.childWithID(parentID))
+            if parent is None:
+                continue
+            resource = (yield parent.objectResourceWithID(resourceID))
+            if resource is None:
+                continue
             yield resource.splitForAttendee(
                 rid,
                 olderUID,
                 coercePartstatsInExistingResource=coercePartstatsInExistingResource
             )
+            resource = None
+            parent = None
+            home = None
 
+        # Clean up the last one
+        if lastHome is not None:
+            self._txn.cleanHomeCache(lastHome)
+            lastHome = None
+
         returnValue(olderObject)
 
 

Modified: CalendarServer/trunk/txdav/caldav/datastore/test/test_sql.py
===================================================================
--- CalendarServer/trunk/txdav/caldav/datastore/test/test_sql.py	2016-06-28 16:16:43 UTC (rev 15714)
+++ CalendarServer/trunk/txdav/caldav/datastore/test/test_sql.py	2016-06-28 17:04:59 UTC (rev 15715)
@@ -52,11 +52,12 @@
 from txdav.caldav.datastore.scheduling.itip import iTIPRequestStatus
 from txdav.caldav.datastore.scheduling.processing import ImplicitProcessor
 from txdav.caldav.datastore.scheduling.scheduler import ScheduleResponseQueue
-from txdav.caldav.datastore.sql import CalendarStoreFeatures, CalendarObject
+from txdav.caldav.datastore.sql import CalendarStoreFeatures, CalendarObject, \
+    CalendarHome
 from txdav.common.datastore.sql import ECALENDARTYPE, CommonObjectResource, \
     CommonStoreTransactionMonitor
 from txdav.common.datastore.sql_tables import schema, _BIND_MODE_DIRECT, \
-    _BIND_STATUS_ACCEPTED, _TRANSP_OPAQUE, _BIND_MODE_WRITE
+    _BIND_STATUS_ACCEPTED, _TRANSP_OPAQUE, _BIND_MODE_WRITE, _HOME_STATUS_NORMAL
 from txdav.caldav.datastore.test.common import CommonTests as CalendarCommonTests, \
     test_event_text, cal1Root, OTHER_HOME_UID
 from txdav.caldav.datastore.test.test_file import setUpCalendarStore
@@ -78,6 +79,7 @@
 from twext.enterprise.util import parseSQLTimestamp
 
 import datetime
+import gc
 import os
 
 
@@ -3544,6 +3546,7 @@
         for ctr in range(1, 5):
             home_uid = yield txn.homeWithUID(ECALENDARTYPE, "user%02d" % (ctr,), create=True)
             self.assertNotEqual(home_uid, None)
+        self.transactionUnderTest().resetHomeCache()
         yield self.commit()
 
         self.setupDateTimeValues()
@@ -7638,7 +7641,7 @@
         yield self.commit()
 
         # Patch resource lookup code so that it deletes the inbox resource after lookup is done
-        oldLookup = CalendarStoreFeatures.calendarObjectsWithUID
+        oldLookup = CalendarStoreFeatures.calendarObjectDetailsWithUID
         @inlineCallbacks
         def _lookup(csself, txn, uid):
             results = yield oldLookup(csself, txn, uid)
@@ -7650,19 +7653,19 @@
             yield cobjs[0].remove()
             yield newtxn.commit()
 
-            # Remove inbox item in another txn
+            # Remove inbox item in another txn by setting the resourceID to an invalid value
             newtxn = self.concurrentTransaction()
             cal = yield self.calendarUnderTest(name="inbox", home="user03")
             cobjs = yield cal.calendarObjects()
             for ctr in range(len(results)):
-                if results[ctr]._resourceID == cobjs[0]._resourceID:
-                    results[ctr] = None
+                if results[ctr][2] == cobjs[0]._resourceID:
+                    results[ctr][2] += 100000
                     break
             yield newtxn.commit()
 
             returnValue(results)
 
-        self.patch(CalendarStoreFeatures, "calendarObjectsWithUID", _lookup)
+        self.patch(CalendarStoreFeatures, "calendarObjectDetailsWithUID", _lookup)
 
         cobj = yield self.calendarObjectUnderTest(name="data1.ics", calendar_name="calendar", home="user01")
         yield cobj.split()
@@ -7713,6 +7716,125 @@
 
 
     @inlineCallbacks
+    def test_calendarObjectSplit_clean_cache(self):
+        """
+        Test that (manual) splitting of calendar objects works and does not use excessive memory
+        by caching store objects for each attendee.
+        """
+
+        self.patch(config.Scheduling.Options.Splitting, "Enabled", False)
+        self.patch(config.Scheduling.Options.Splitting, "Size", 100)
+        self.patch(config.Scheduling.Options.Splitting, "PastDays", 14)
+        self.patch(config, "MaxResourceSize", 10 * 1024 * 1024)
+
+        # Create one event that will split
+        calendar = yield self.calendarUnderTest(name="calendar", home="user01")
+
+        attendees = "\n".join(["ATTENDEE:mailto:user{:02d}@example.com".format(i + 2) for i in range(3)])
+        data = """BEGIN:VCALENDAR
+VERSION:2.0
+PRODID:-//CALENDARSERVER.ORG//NONSGML Version 1//EN
+BEGIN:VEVENT
+UID:12345-67890
+DTSTART:%(now_back30)s
+DURATION:PT2H
+ATTENDEE;PARTSTAT=ACCEPTED:mailto:user01 at example.com
+{attendees}
+DTSTAMP:20051222T210507Z
+ORGANIZER:mailto:user01 at example.com
+RRULE:FREQ=DAILY
+SUMMARY:1234567890123456789012345678901234567890
+ 1234567890123456789012345678901234567890
+ 1234567890123456789012345678901234567890
+ 1234567890123456789012345678901234567890
+DESCRIPTION:{description}
+END:VEVENT
+BEGIN:VEVENT
+UID:12345-67890
+RECURRENCE-ID:%(now_back25)s
+DTSTART:%(now_back25)s
+DURATION:PT1H
+ATTENDEE;PARTSTAT=ACCEPTED:mailto:user01 at example.com
+{attendees}
+DTSTAMP:20051222T210507Z
+ORGANIZER:mailto:user01 at example.com
+DESCRIPTION:{description}
+END:VEVENT
+BEGIN:VEVENT
+UID:12345-67890
+RECURRENCE-ID:%(now_back24)s
+DTSTART:%(now_back24)s
+DURATION:PT1H
+ATTENDEE;PARTSTAT=ACCEPTED:mailto:user01 at example.com
+{attendees}
+DTSTAMP:20051222T210507Z
+ORGANIZER:mailto:user01 at example.com
+DESCRIPTION:{description}
+END:VEVENT
+BEGIN:VEVENT
+UID:12345-67890
+RECURRENCE-ID:%(now_fwd10)s
+DTSTART:%(now_fwd10)s
+DURATION:PT1H
+{attendees}
+DTSTAMP:20051222T210507Z
+ORGANIZER:mailto:user01 at example.com
+DESCRIPTION:{description}
+END:VEVENT
+END:VCALENDAR
+""".format(description=" " * 1024 * 1024, attendees=attendees)
+
+        component = Component.fromString(data % self.dtsubs)
+        cobj = yield calendar.createCalendarObjectWithName("data1.ics", component)
+        self.assertFalse(hasattr(cobj, "_workItems"))
+        self.transactionUnderTest().resetHomeCache()
+        yield self.commit()
+        cobj = None
+        component = None
+        calendar = None
+
+        w = schema.CALENDAR_OBJECT_SPLITTER_WORK
+        rows = yield Select(
+            [w.RESOURCE_ID, ],
+            From=w
+        ).on(self.transactionUnderTest())
+        self.assertEqual(len(rows), 0)
+        self.transactionUnderTest().resetHomeCache()
+        yield self.abort()
+
+        # Do manual split
+        cobj = yield self.calendarObjectUnderTest(name="data1.ics", calendar_name="calendar", home="user01")
+        will = yield cobj.willSplit()
+        self.assertTrue(will)
+
+        yield cobj.split()
+
+        # Make sure caches are clean
+        txn = self.transactionUnderTest()
+        self.assertEqual(1, len(txn._cachedHomes[ECALENDARTYPE]["byUID"][_HOME_STATUS_NORMAL]))
+        self.assertEqual(1, len(txn._cachedHomes[ECALENDARTYPE]["byID"][None]))
+
+        # Make sure local objects are gone
+        cobj = None
+        txn = None
+        yield self.commit()
+
+        # Garbage collect then look for the number of home/resource objects and
+        # make sure only those for user01 still exist
+        gc.collect()
+        gcobjs = gc.get_objects()
+        hcount = 0
+        ocount = 0
+        for obj in gcobjs:
+            if isinstance(obj, CalendarHome):
+                hcount += 1
+            elif isinstance(obj, CalendarObject):
+                ocount += 1
+        self.assertTrue(hcount <= 2) # Just user01 home left (maybe user05 too)
+        self.assertTrue(ocount <= 4) # Old resource + new resource (and maybe user05 too)
+
+
+    @inlineCallbacks
     def _setupSplitAt(self):
         """
         Test that user triggered splitting of calendar objects works.

Modified: CalendarServer/trunk/txdav/common/datastore/sql.py
===================================================================
--- CalendarServer/trunk/txdav/common/datastore/sql.py	2016-06-28 16:16:43 UTC (rev 15714)
+++ CalendarServer/trunk/txdav/common/datastore/sql.py	2016-06-28 17:04:59 UTC (rev 15715)
@@ -754,11 +754,19 @@
         if storeType not in (ECALENDARTYPE, EADDRESSBOOKTYPE):
             raise RuntimeError("Unknown home type.")
 
-        result = self._determineMemo(storeType, "byUID", status).get(uid)
+        if status is None:
+            # Look for any that match possible status and return the first one.
+            # The order of status here matches that in L{CommonHome.homeWith}.
+            for possible_status in (_HOME_STATUS_NORMAL, _HOME_STATUS_DISABLED, _HOME_STATUS_EXTERNAL,):
+                result = self._determineMemo(storeType, "byUID", possible_status).get(uid)
+                if result is not None:
+                    break
+        else:
+            result = self._determineMemo(storeType, "byUID", status).get(uid)
         if result is None:
             result = yield self._homeClass[storeType].homeWithUID(self, uid, status, create, authzUID)
             if result:
-                self._determineMemo(storeType, "byUID", status)[uid] = result
+                self._determineMemo(storeType, "byUID", result.status())[uid] = result
                 self._determineMemo(storeType, "byID", None)[result.id()] = result
         returnValue(result)
 
@@ -796,6 +804,42 @@
         return self.homeWithResourceID(EADDRESSBOOKTYPE, rid)
 
 
+    def resetHomeCache(self):
+        """
+        Initialize the home caches, wiping any that existed before. This is only
+        used in testing when we want to be sure all cached objects have been
+        removed.
+        """
+        self._cachedHomes = {
+            ECALENDARTYPE: {
+                "byUID": defaultdict(dict),
+                "byID": defaultdict(dict),
+            },
+            EADDRESSBOOKTYPE: {
+                "byUID": defaultdict(dict),
+                "byID": defaultdict(dict),
+            },
+        }
+        self._notificationHomes = {
+            "byUID": defaultdict(dict),
+            "byID": defaultdict(dict),
+        }
+
+
+    def cleanHomeCache(self, home):
+        """
+        Remove the specified home from the home cache.
+        @param home: home to remove
+        @type home: L{CommonHome}
+        """
+        rid_memo = self._determineMemo(home._homeType, "byID", None)
+        if home.id() in rid_memo:
+            del rid_memo[home.id()]
+        uid_memo = self._determineMemo(home._homeType, "byUID", home.status())
+        if home.uid() in uid_memo:
+            del uid_memo[home.uid()]
+
+
     @inlineCallbacks
     def notificationsWithUID(self, uid, status=None, create=False):
         """
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.macosforge.org/pipermail/calendarserver-changes/attachments/20160628/2586c511/attachment-0001.html>


More information about the calendarserver-changes mailing list