[CalendarServer-changes] [1271] CalendarServer/trunk/twistedcaldav

source_changes at macosforge.org source_changes at macosforge.org
Mon Feb 26 12:04:23 PST 2007


Revision: 1271
          http://trac.macosforge.org/projects/calendarserver/changeset/1271
Author:   dreid at apple.com
Date:     2007-02-26 12:04:22 -0800 (Mon, 26 Feb 2007)

Log Message:
-----------
DirectoryService now subclasses Service, so Directory Services that need to perform initialization on server startup should override startService

Modified Paths:
--------------
    CalendarServer/trunk/twistedcaldav/directory/aggregate.py
    CalendarServer/trunk/twistedcaldav/directory/appleopendirectory.py
    CalendarServer/trunk/twistedcaldav/directory/directory.py
    CalendarServer/trunk/twistedcaldav/directory/sqldb.py
    CalendarServer/trunk/twistedcaldav/directory/sudo.py
    CalendarServer/trunk/twistedcaldav/directory/test/test_aggregate.py
    CalendarServer/trunk/twistedcaldav/directory/test/test_opendirectory.py
    CalendarServer/trunk/twistedcaldav/directory/test/test_opendirectoryschema.py
    CalendarServer/trunk/twistedcaldav/directory/test/test_sqldb.py
    CalendarServer/trunk/twistedcaldav/directory/test/test_xmlfile.py
    CalendarServer/trunk/twistedcaldav/directory/xmlfile.py
    CalendarServer/trunk/twistedcaldav/tap.py

Modified: CalendarServer/trunk/twistedcaldav/directory/aggregate.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/directory/aggregate.py	2007-02-26 17:29:17 UTC (rev 1270)
+++ CalendarServer/trunk/twistedcaldav/directory/aggregate.py	2007-02-26 20:04:22 UTC (rev 1271)
@@ -27,12 +27,13 @@
 ]
 
 from twisted.cred.error import UnauthorizedLogin
+from twisted.application.service import MultiService, IService
 
 from twistedcaldav.directory.idirectory import IDirectoryService
 from twistedcaldav.directory.directory import DirectoryService, DirectoryError
 from twistedcaldav.directory.directory import UnknownRecordTypeError
 
-class AggregateDirectoryService(DirectoryService):
+class AggregateDirectoryService(DirectoryService, MultiService):
     """
     L{IDirectoryService} implementation which aggregates multiple directory services.
     """
@@ -40,35 +41,39 @@
 
     def __init__(self, services):
         DirectoryService.__init__(self)
+        MultiService.__init__(self)
 
-        realmName = None
-        recordTypes = {}
+        self.realmName = None
+        self._recordTypes = {}
 
         for service in services:
+            IService(service).setServiceParent(self)
+
+    def startService(self):
+        super(AggregateDirectoryService, self).startService()
+
+        for service in self.services:
             service = IDirectoryService(service)
 
-            if service.realmName != realmName:
-                assert realmName is None, (
+            if service.realmName != self.realmName:
+                assert self.realmName is None, (
                     "Aggregated directory services must have the same realm name: %r != %r"
-                    % (service.realmName, realmName)
+                    % (service.realmName, self.realmName)
                 )
-                realmName = service.realmName
+                self.realmName = service.realmName
 
             if not hasattr(service, "recordTypePrefix"):
                 service.recordTypePrefix = ""
             prefix = service.recordTypePrefix
 
             for recordType in (prefix + r for r in service.recordTypes()):
-                if recordType in recordTypes:
+                if recordType in self._recordTypes:
                     raise DuplicateRecordTypeError(
                         "%r is in multiple services: %s, %s"
-                        % (recordType, recordTypes[recordType], service)
+                        % (recordType, self._recordTypes[recordType], service)
                     )
-                recordTypes[recordType] = service
+                self._recordTypes[recordType] = service
 
-        self.realmName = realmName
-        self._recordTypes = recordTypes
-
     def __repr__(self):
         return "<%s (%s): %r>" % (self.__class__.__name__, self.realmName, self._recordTypes)
 
@@ -133,7 +138,7 @@
             if user:
                 return self.serviceForRecordType(
                     type).requestAvatarId(credentials)
-        
+
         raise UnauthorizedLogin("No such user: %s" % (
                 credentials.credentials.username,))
 

Modified: CalendarServer/trunk/twistedcaldav/directory/appleopendirectory.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/directory/appleopendirectory.py	2007-02-26 17:29:17 UTC (rev 1270)
+++ CalendarServer/trunk/twistedcaldav/directory/appleopendirectory.py	2007-02-26 20:04:22 UTC (rev 1271)
@@ -53,14 +53,11 @@
     def __repr__(self):
         return "<%s %r: %r>" % (self.__class__.__name__, self.realmName, self.node)
 
-    def __init__(self, node="/Search", requireComputerRecord=True, dosetup=True):
+    def __init__(self, node="/Search", requireComputerRecord=True):
         """
         @param node: an OpenDirectory node name to bind to.
         @param requireComputerRecord: C{True} if the directory schema is to be used to determine
             which calendar users are enabled.
-        @param dosetup: if C{True} then the directory records are initialized,
-                        if C{False} they are not.
-                        This should only be set to C{False} when doing unit tests.
         """
         try:
             directory = opendirectory.odInit(node)
@@ -76,16 +73,16 @@
         self._records = {}
         self._delayedCalls = set()
 
-        if dosetup:
-            if self.requireComputerRecord:
-                try:
-                    self._lookupVHostRecord()
-                except Exception, e:
-                    log.err("Unable to locate virtual host record: %s" % (e,))
-                    raise
+    def startService(self):
+        if self.requireComputerRecord:
+            try:
+                self._lookupVHostRecord()
+            except Exception, e:
+                log.err("Unable to locate virtual host record: %s" % (e,))
+                raise
 
-            for recordType in self.recordTypes():
-                self.recordsForType(recordType)
+        for recordType in self.recordTypes():
+            self.recordsForType(recordType)
 
     def __cmp__(self, other):
         if not isinstance(other, DirectoryRecord):
@@ -115,7 +112,7 @@
                 "There is no virtual hostname configured for the server for use with Open Directory (node=%s)"
                 % (self.realmName,)
             )
-         
+
         # Find a record in /Computers with an ENetAddress attribute value equal to the MAC address
         # and return some useful attributes.
         attrs = [
@@ -136,7 +133,7 @@
         self._parseComputersRecords(records, vhostname)
 
     def _parseComputersRecords(self, records, vhostname):
-        
+
         # Must have some results
         if len(records) == 0:
             raise OpenDirectoryInitError(
@@ -147,12 +144,12 @@
         # Now find a single record that actually matches the hostname
         found = False
         for recordname, record in records.iteritems():
-            
+
             # Must have XMLPlist value
             plist = record.get(dsattributes.kDS1AttrXMLPlist, None)
             if not plist:
                 continue
-            
+
             if not self._parseXMLPlist(vhostname, recordname, plist, record[dsattributes.kDS1AttrGeneratedUID]):
                 continue
             elif found:
@@ -162,13 +159,13 @@
                 )
             else:
                 found = True
-                
+
         if not found:
             raise OpenDirectoryInitError(
                 "Open Directory (node=%s) no /Computers records with an enabled and valid calendar service were found matching virtual hostname: %s"
                 % (self.realmName, vhostname,)
             )
-    
+
     def _parseXMLPlist(self, vhostname, recordname, plist, recordguid):
         # Parse the plist and look for our special entry
         plist = readPlistFromString(plist)
@@ -180,7 +177,7 @@
                 % (self.realmName, recordname)
             )
             return False
-        
+
         # Iterate over each vhost and find one that is a calendar service
         hostguid = None
         for key, value in vhosts.iteritems():
@@ -190,7 +187,7 @@
                     if type == "calendar":
                         hostguid = key
                         break
-                    
+
         if not hostguid:
             log.msg(
                 "Open Directory (node=%s) /Computers/%s record does not have a "
@@ -198,7 +195,7 @@
                 % (self.realmName, recordname)
             )
             return False
-            
+
         # Get host name
         hostname = vhosts[hostguid].get("hostname", None)
         if not hostname:
@@ -215,7 +212,7 @@
                 % (self.realmName, recordname, hostname, vhostname)
             )
             return False
-        
+
         # Get host details and create host templates
         hostdetails = vhosts[hostguid].get("hostDetails", None)
         if not hostdetails:
@@ -229,7 +226,7 @@
         for key, value in hostdetails.iteritems():
             if key in ("http", "https"):
                 hostvariants.append((key, hostname, value["port"]))
-        
+
         # Look at the service data
         serviceInfos = vhosts[hostguid].get("serviceInfo", None)
         if not serviceInfos or not serviceInfos.has_key("calendar"):
@@ -240,7 +237,7 @@
             )
             return False
         serviceInfo = serviceInfos["calendar"]
-        
+
         # Check that this service is enabled
         enabled = serviceInfo.get("enabled", True)
         if not enabled:
@@ -253,23 +250,23 @@
 
         # Create the string we will use to match users with accounts on this server
         self.servicetag = "%s:%s:calendar" % (recordguid, hostguid)
-        
+
         self.computerRecordName = recordname
-        
+
         return True
-    
+
     def _getCalendarUserAddresses(self, recordType, recordName, record):
         """
         Extract specific attributes from the directory record for use as calendar user address.
-        
+
         @param recordName: a C{str} containing the record name being operated on.
         @param record: a C{dict} containing the attributes retrieved from the directory.
         @return: a C{set} of C{str} for each expanded calendar user address.
         """
-        
+
         # Now get the addresses
         result = set()
-        
+
         # Add each email address as a mailto URI
         emails = record.get(dsattributes.kDSNAttrEMailAddress)
         if emails is not None:
@@ -277,7 +274,7 @@
                 emails = [emails]
             for email in emails:
                 result.add("mailto:%s" % (email,))
-                
+
         return result
 
     def recordTypes(self):
@@ -316,7 +313,7 @@
             elif recordType == DirectoryService.recordType_locations:
                 listRecordType = dsattributes.kDSStdRecordTypeResources
                 query = dsquery.match(dsattributes.kDSNAttrResourceType, "1", dsattributes.eDSExact)
-            
+
             elif recordType == DirectoryService.recordType_resources:
                 listRecordType = dsattributes.kDSStdRecordTypeResources
                 query = dsquery.expression(dsquery.expression.OR, (
@@ -326,7 +323,7 @@
                     dsquery.match(dsattributes.kDSNAttrResourceType, "4", dsattributes.eDSExact),
                     dsquery.match(dsattributes.kDSNAttrResourceType, "5", dsattributes.eDSExact),
                 ))
-            
+
             else:
                 raise UnknownRecordTypeError("Unknown Open Directory record type: %s"
                                              % (recordType,))
@@ -337,7 +334,7 @@
                     query = dsquery.expression(dsquery.expression.AND, (cprecord, query))
                 else:
                     query = cprecord
-                
+
             records = {}
 
             try:

Modified: CalendarServer/trunk/twistedcaldav/directory/directory.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/directory/directory.py	2007-02-26 17:29:17 UTC (rev 1270)
+++ CalendarServer/trunk/twistedcaldav/directory/directory.py	2007-02-26 20:04:22 UTC (rev 1271)
@@ -33,6 +33,7 @@
 from zope.interface import implements
 
 from twisted.python import log
+from twisted.application.service import Service
 from twisted.cred.error import UnauthorizedLogin
 from twisted.cred.checkers import ICredentialsChecker
 from twisted.web2.dav.auth import IPrincipalCredentials
@@ -45,7 +46,7 @@
 from twistedcaldav.directory.idirectory import IDirectoryService, IDirectoryRecord
 from twistedcaldav.directory.util import uuidFromName
 
-class DirectoryService(object):
+class DirectoryService(object, Service):
     implements(IDirectoryService, ICredentialsChecker)
 
     ##
@@ -58,7 +59,7 @@
     recordType_groups = "groups"
     recordType_locations = "locations"
     recordType_resources = "resources"
-    
+
     def _generatedGUID(self):
         if not hasattr(self, "_guid"):
             realmName = self.realmName
@@ -98,7 +99,7 @@
             raise UnauthorizedLogin("No such user: %s" % (user,))
 
         # Handle Kerberos as a separate behavior
-        if NegotiateCredentials and isinstance(credentials.credentials, 
+        if NegotiateCredentials and isinstance(credentials.credentials,
                                                NegotiateCredentials):
             # If we get here with Kerberos, then authentication has already succeeded
             return (
@@ -112,7 +113,7 @@
                     credentials.authzPrincipal.principalURL(),
                 )
             else:
-                raise UnauthorizedLogin("Incorrect credentials for %s" % (user,)) 
+                raise UnauthorizedLogin("Incorrect credentials for %s" % (user,))
 
     def recordTypes(self):
         raise NotImplementedError("Subclass must implement recordTypes()")

Modified: CalendarServer/trunk/twistedcaldav/directory/sqldb.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/directory/sqldb.py	2007-02-26 17:29:17 UTC (rev 1270)
+++ CalendarServer/trunk/twistedcaldav/directory/sqldb.py	2007-02-26 20:04:22 UTC (rev 1271)
@@ -65,7 +65,7 @@
 
     def loadFromXML(self, xmlFile):
         parser = XMLAccountsParser(xmlFile)
-       
+
         # Totally wipe existing DB and start from scratch
         if os.path.exists(self.dbpath):
             os.remove(self.dbpath)
@@ -95,13 +95,13 @@
         ):
             # See if we have members
             members = self.members(shortName)
-                
+
             # See if we are a member of any groups
             groups = self.groups(shortName)
-                
+
             # Get calendar user addresses
             calendarUserAddresses = self.calendarUserAddresses(shortName)
-                
+
             yield shortName, guid, password, name, members, groups, calendarUserAddresses
 
     def getRecord(self, recordType, shortName):
@@ -117,18 +117,18 @@
             break
         else:
             return None
-        
+
         # See if we have members
         members = self.members(shortName)
-            
+
         # See if we are a member of any groups
         groups = self.groups(shortName)
-            
+
         # Get calendar user addresses
         calendarUserAddresses = self.calendarUserAddresses(shortName)
-            
+
         return shortName, guid, password, name, members, groups, calendarUserAddresses
-            
+
     def members(self, shortName):
         members = set()
         for member in self._db_execute(
@@ -179,7 +179,7 @@
             values (:1, :2, :3, :4, :5)
             """, recordType, shortName, guid, password, name
         )
-        
+
         # Check for members
         for memberRecordType, memberShortName in record.members:
             self._db_execute(
@@ -188,7 +188,7 @@
                 values (:1, :2, :3)
                 """, shortName, memberRecordType, memberShortName
             )
-                
+
         # CUAddress
         for cuaddr in record.calendarUserAddresses:
             self._db_execute(
@@ -197,7 +197,7 @@
                 values (:1, :2)
                 """, cuaddr, shortName
             )
-       
+
     def _delete_from_db(self, shortName):
         """
         Deletes the specified entry from all dbs.
@@ -208,13 +208,13 @@
         self._db_execute("delete from GROUPS    where SHORT_NAME        = :1", shortName)
         self._db_execute("delete from GROUPS    where MEMBER_SHORT_NAME = :1", shortName)
         self._db_execute("delete from ADDRESSES where SHORT_NAME        = :1", shortName)
-    
+
     def _db_type(self):
         """
         @return: the collection type assigned to this index.
         """
         return SQLDirectoryManager.dbType
-        
+
     def _db_init_data_tables(self, q):
         """
         Initialise the underlying database tables.
@@ -280,10 +280,14 @@
 
         if type(dbParentPath) is str:
             dbParentPath = FilePath(dbParentPath)
-            
+
+        self.xmlFile = xmlFile
+
         self.manager = SQLDirectoryManager(dbParentPath.path)
-        if xmlFile:
-            self.manager.loadFromXML(xmlFile)
+
+    def startService(self):
+        if self.xmlFile:
+            self.manager.loadFromXML(self.xmlFile)
         self.realmName = self.manager.getRealm()
 
     def recordTypes(self):

Modified: CalendarServer/trunk/twistedcaldav/directory/sudo.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/directory/sudo.py	2007-02-26 17:29:17 UTC (rev 1270)
+++ CalendarServer/trunk/twistedcaldav/directory/sudo.py	2007-02-26 20:04:22 UTC (rev 1271)
@@ -27,13 +27,13 @@
 
 from twisted.python.filepath import FilePath
 
-from twisted.cred.credentials import (IUsernamePassword, 
+from twisted.cred.credentials import (IUsernamePassword,
                                       IUsernameHashedPassword)
 
 from twisted.cred.error import UnauthorizedLogin
 
 from twistedcaldav.py.plistlib import readPlist
-from twistedcaldav.directory.directory import (DirectoryService, 
+from twistedcaldav.directory.directory import (DirectoryService,
                                                DirectoryRecord,
                                                UnknownRecordTypeError)
 
@@ -58,9 +58,11 @@
 
         if isinstance(plistFile, (unicode, str)):
             plistFile = FilePath(plistFile)
-            
+
         self.plistFile = plistFile
         self._fileInfo = None
+
+    def startService(self):
         self._accounts()
 
     def _accounts(self):
@@ -102,12 +104,12 @@
         # implementation because you shouldn't have a principal object for a
         # disabled directory principal.
         sudouser = self.recordWithShortName(
-            SudoDirectoryService.recordType_sudoers, 
+            SudoDirectoryService.recordType_sudoers,
             credentials.credentials.username)
 
         if sudouser is None:
             raise UnauthorizedLogin("No such user: %s" % (sudouser,))
-        
+
         if sudouser.verifyCredentials(credentials.credentials):
             return (
                 credentials.authnPrincipal.principalURL(),
@@ -115,7 +117,7 @@
                 )
         else:
             raise UnauthorizedLogin(
-                "Incorrect credentials for %s" % (sudouser,)) 
+                "Incorrect credentials for %s" % (sudouser,))
 
 
 class SudoDirectoryRecord(DirectoryRecord):
@@ -139,5 +141,5 @@
             return credentials.checkPassword(self.password)
         elif IUsernameHashedPassword.providedBy(credentials):
             return credentials.checkPassword(self.password)
-        
+
         return super(SudoDirectoryRecord, self).verifyCredentials(credentials)

Modified: CalendarServer/trunk/twistedcaldav/directory/test/test_aggregate.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/directory/test/test_aggregate.py	2007-02-26 17:29:17 UTC (rev 1270)
+++ CalendarServer/trunk/twistedcaldav/directory/test/test_aggregate.py	2007-02-26 20:04:22 UTC (rev 1271)
@@ -73,4 +73,7 @@
         xmlService = XMLDirectoryService(xmlFile)
         xmlService.recordTypePrefix = xml_prefix
 
-        return AggregateDirectoryService((apacheService, xmlService))
+        aggregate = AggregateDirectoryService((apacheService, xmlService))
+        aggregate.startService()
+
+        return aggregate

Modified: CalendarServer/trunk/twistedcaldav/directory/test/test_opendirectory.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/directory/test/test_opendirectory.py	2007-02-26 17:29:17 UTC (rev 1270)
+++ CalendarServer/trunk/twistedcaldav/directory/test/test_opendirectory.py	2007-02-26 20:04:22 UTC (rev 1271)
@@ -21,6 +21,7 @@
 except ImportError:
     pass
 else:
+    from twisted.internet.task import Clock
     from twistedcaldav.directory.directory import DirectoryService
     import twistedcaldav.directory.test.util
 
@@ -50,7 +51,7 @@
 
         def setUp(self):
             super(OpenDirectory, self).setUp()
-            self._service = OpenDirectoryService(node="/Search", dosetup=False)
+            self._service = OpenDirectoryService(node="/Search")
 
         def tearDown(self):
             for call in self._service._delayedCalls:

Modified: CalendarServer/trunk/twistedcaldav/directory/test/test_opendirectoryschema.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/directory/test/test_opendirectoryschema.py	2007-02-26 17:29:17 UTC (rev 1270)
+++ CalendarServer/trunk/twistedcaldav/directory/test/test_opendirectoryschema.py	2007-02-26 20:04:22 UTC (rev 1271)
@@ -30,7 +30,7 @@
         """
         Test Open Directory service schema.
         """
-        
+
         plist_nomacosxserver_key = """<?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
 <plist version="1.0">
@@ -186,7 +186,7 @@
                     </dict>
                 </dict>
             </dict>
-            
+
             <key>C18C34AC-3D9E-403C-8A33-BFC303F3840E</key>
             <dict>
                 <key>hostname</key>
@@ -301,7 +301,7 @@
                     </dict>
                 </dict>
             </dict>
-            
+
             <key>C18C34AC-3D9E-403C-8A33-BFC303F3840E</key>
             <dict>
                 <key>hostname</key>
@@ -425,7 +425,7 @@
                     </dict>
                 </dict>
             </dict>
-            
+
             <key>C18C34AC-3D9E-403C-8A33-BFC303F3840E</key>
             <dict>
                 <key>hostDetails</key>
@@ -544,7 +544,7 @@
                     </dict>
                 </dict>
             </dict>
-            
+
             <key>C18C34AC-3D9E-403C-8A33-BFC303F3840E</key>
             <dict>
                 <key>hostname</key>
@@ -647,7 +647,7 @@
                     </dict>
                 </dict>
             </dict>
-            
+
             <key>C18C34AC-3D9E-403C-8A33-BFC303F3840E</key>
             <dict>
                 <key>hostname</key>
@@ -769,7 +769,7 @@
                     </dict>
                 </dict>
             </dict>
-            
+
             <key>C18C34AC-3D9E-403C-8A33-BFC303F3840E</key>
             <dict>
                 <key>hostname</key>
@@ -825,10 +825,10 @@
 
         def test_plist_errors(self):
             def _doParse(plist, title):
-                service = OpenDirectoryService(node="/Search", dosetup=False)
+                service = OpenDirectoryService(node="/Search")
                 if service._parseXMLPlist("calendar.apple.com", "recordit", plist, "GUIDIFY"):
                     self.fail(msg="Plist parse should have failed: %s" % (title,))
-                
+
             plists = (
                 (PlistParse.plist_nomacosxserver_key, "nomacosxserver_key"),
                 (PlistParse.plist_nocalendarservice,  "nocalendarservice"),
@@ -841,7 +841,7 @@
                 _doParse(plist, title)
 
         def test_goodplist(self):
-            service = OpenDirectoryService(node="/Search", dosetup=False)
+            service = OpenDirectoryService(node="/Search")
             if not service._parseXMLPlist("calendar.apple.com", "recordit", PlistParse.plist_good, "GUIDIFY"):
                 self.fail(msg="Plist parse should not have failed")
             else:
@@ -850,15 +850,15 @@
 
         def test_expandcuaddrs(self):
             def _doTest(recordName, record, result, title):
-                service = OpenDirectoryService(node="/Search", dosetup=False)
+                service = OpenDirectoryService(node="/Search")
                 if not service._parseXMLPlist("calendar.apple.com", recordName, PlistParse.plist_good, "GUIDIFY"):
                     self.fail(msg="Plist parse should not have failed: %s" % (recordName,))
                 else:
                     expanded = service._getCalendarUserAddresses(DirectoryService.recordType_users, recordName, record)
-        
+
                     # Verify that we extracted the proper items
                     self.assertEqual(expanded, result, msg=title % (expanded, result,))
-            
+
             data = (
                 (
                  "user01",
@@ -892,7 +892,7 @@
                  "User with no email addresses, %s != %s",
                 ),
             )
-            
+
             for recordName, record, result, title in data:
                 _doTest(recordName, record, result, title)
 
@@ -916,13 +916,13 @@
 
         def test_odrecords_error(self):
             def _doParseRecords(recordlist, title):
-                service = OpenDirectoryService(node="/Search", dosetup=False)
+                service = OpenDirectoryService(node="/Search")
                 try:
                     service._parseComputersRecords(recordlist, "calendar.apple.com")
                     self.fail(msg="Record parse should have failed: %s" % (title,))
                 except OpenDirectoryInitError:
                     pass
-                
+
             records = (
                 ({}, "no records found"),
                 ({
@@ -939,12 +939,12 @@
 
         def test_odrecords_good(self):
             def _doParseRecords(recordlist, title):
-                service = OpenDirectoryService(node="/Search", dosetup=False)
+                service = OpenDirectoryService(node="/Search")
                 try:
                     service._parseComputersRecords(recordlist, "calendar.apple.com")
                 except OpenDirectoryInitError, ex:
                     self.fail(msg="Record parse should not have failed: \"%s\" with error: %s" % (title, ex))
-                
+
             records = (
                 ({
                       ODRecordsParse.record_good[0]        : ODRecordsParse.record_good[1],

Modified: CalendarServer/trunk/twistedcaldav/directory/test/test_sqldb.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/directory/test/test_sqldb.py	2007-02-26 17:29:17 UTC (rev 1270)
+++ CalendarServer/trunk/twistedcaldav/directory/test/test_sqldb.py	2007-02-26 20:04:22 UTC (rev 1271)
@@ -37,7 +37,9 @@
     Test SQL directory implementation.
     """
     def service(self):
-        return SQLDirectoryService(os.getcwd(), self.xmlFile())
+        service = SQLDirectoryService(os.getcwd(), self.xmlFile())
+        service.startService()
+        return service
 
     def test_verifyCredentials_digest(self):
         super(SQLDB, self).test_verifyCredentials_digest()
@@ -49,5 +51,6 @@
 
         # Then get an instance without using the XML file
         service = SQLDirectoryService(os.getcwd(), None)
+        service.startService()
 
         self.assertEquals(service.realmName, "Test")

Modified: CalendarServer/trunk/twistedcaldav/directory/test/test_xmlfile.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/directory/test/test_xmlfile.py	2007-02-26 17:29:17 UTC (rev 1270)
+++ CalendarServer/trunk/twistedcaldav/directory/test/test_xmlfile.py	2007-02-26 20:04:22 UTC (rev 1271)
@@ -86,7 +86,9 @@
     Test XML file based directory implementation.
     """
     def service(self):
-        return XMLDirectoryService(self.xmlFile())
+        service = XMLDirectoryService(self.xmlFile())
+        service.startService()
+        return service
 
     def test_changedXML(self):
         self.xmlFile().open("w").write(

Modified: CalendarServer/trunk/twistedcaldav/directory/xmlfile.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/directory/xmlfile.py	2007-02-26 17:29:17 UTC (rev 1270)
+++ CalendarServer/trunk/twistedcaldav/directory/xmlfile.py	2007-02-26 20:04:22 UTC (rev 1271)
@@ -50,6 +50,8 @@
 
         self.xmlFile = xmlFile
         self._fileInfo = None
+
+    def startService(self):
         self._accounts()
 
     def recordTypes(self):

Modified: CalendarServer/trunk/twistedcaldav/tap.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/tap.py	2007-02-26 17:29:17 UTC (rev 1270)
+++ CalendarServer/trunk/twistedcaldav/tap.py	2007-02-26 20:04:22 UTC (rev 1271)
@@ -88,9 +88,9 @@
 
     def opt_option(self, option):
         """
-        Set an option to override a value in the config file. True, False, int, 
+        Set an option to override a value in the config file. True, False, int,
         and float options are supported, as well as comma seperated lists. Only
-        one option may be given for each --option flag, however multiple 
+        one option may be given for each --option flag, however multiple
         --option flags may be specified.
         """
 
@@ -103,13 +103,13 @@
 
                 elif isinstance(defaultConfig[key], (int, float, long)):
                     value = type(defaultConfig[key])(value)
-                
+
                 elif isinstance(defaultConfig[key], (list, tuple)):
                     value = value.split(',')
 
                 elif isinstance(defaultConfig[key], dict):
                     raise UsageError("Dict options not supported on the command line")
-                        
+
                 elif value == 'None':
                     value = None
 
@@ -130,7 +130,7 @@
         uid, gid = None, None
 
         if self.parent['uid'] or self.parent['gid']:
-            uid, gid = getid(self.parent['uid'], 
+            uid, gid = getid(self.parent['uid'],
                              self.parent['gid'])
 
         if uid:
@@ -159,7 +159,7 @@
             uname=config.UserName,
             gname=config.GroupName
         )
-            
+
         # Verify that ssl certs exist if needed
         if config.SSLPort:
             self.checkFile(
@@ -181,12 +181,12 @@
 
         if not config.ErrorLogFile and config.ProcessType == 'Slave':
             log.FileLogObserver.timeFormat = ''
-        
+
         # Check current umask and warn if changed
         oldmask = os.umask(0027)
         if oldmask != 0027:
             print "WARNING: changing umask from: 0%03o to 0%03o" % (oldmask, 0027,)
-        
+
     def checkDirectory(self, dirpath, description, access=None, fail=False, permissions=None, uname=None, gname=None):
         if not os.path.exists(dirpath):
             raise ConfigurationError("%s does not exist: %s" % (description, dirpath,))
@@ -195,7 +195,7 @@
         elif access and not os.access(dirpath, access):
             raise ConfigurationError("Insufficient permissions for server on %s directory: %s" % (description, dirpath,))
         self.securityCheck(dirpath, description, fail=fail, permissions=permissions, uname=uname, gname=gname)
-    
+
     def checkFile(self, filepath, description, access=None, fail=False, permissions=None, uname=None, gname=None):
         if not os.path.exists(filepath):
             raise ConfigurationError("%s does not exist: %s" % (description, filepath,))
@@ -227,7 +227,7 @@
             except KeyError:
                 raiseOrPrint("The owner of %s directory %s is unknown (%s) and does not match the expected owner: %s"
                              % (description, path, pathstat[stat.ST_UID], uname))
-                    
+
         if gname:
             import grp
             try:
@@ -238,8 +238,8 @@
             except KeyError:
                 raiseOrPrint("The group of %s directory %s is unknown (%s) and does not match the expected group: %s"
                              % (description, path, pathstat[stat.ST_GID], gname))
-                    
 
+
 class CalDAVServiceMaker(object):
     implements(IPlugin, service.IServiceMaker)
 
@@ -262,12 +262,12 @@
         # Setup the Directory
         #
         directories = []
-        
+
         directoryClass = namedClass(config.DirectoryService['type'])
-        
+
         log.msg("Configuring directory service of type: %s"
                 % (config.DirectoryService['type'],))
-        
+
         baseDirectory = directoryClass(**config.DirectoryService['params'])
 
         directories.append(baseDirectory)
@@ -277,7 +277,7 @@
         if config.SudoersFile and os.path.exists(config.SudoersFile):
             log.msg("Configuring SudoDirectoryService with file: %s"
                     % (config.SudoersFile,))
-                
+
             sudoDirectory = SudoDirectoryService(config.SudoersFile)
             sudoDirectory.realmName = baseDirectory.realmName
 
@@ -298,7 +298,7 @@
         #
 
         log.msg("Setting up document root at: %s" % (config.DocumentRoot,))
-        
+
         log.msg("Setting up principal collection: %r" % (self.principalResourceClass,))
 
         principalCollection = self.principalResourceClass(
@@ -314,11 +314,11 @@
             directory,
             '/calendars/'
         )
-        
+
         log.msg("Setting up root resource: %r" % (self.rootResourceClass,))
-        
+
         root = self.rootResourceClass(
-            config.DocumentRoot, 
+            config.DocumentRoot,
             principalCollections=(principalCollection,)
         )
 
@@ -335,12 +335,12 @@
                 davxml.Grant(davxml.Privilege(davxml.Read())),
             ),
         ]
-        
+
         log.msg("Setting up AdminPrincipals")
 
         for principal in config.AdminPrincipals:
             log.msg("Added %s as admin principal" % (principal,))
-            
+
             rootACEs.append(
                 davxml.ACE(
                     davxml.Principal(davxml.HRef(principal)),
@@ -372,10 +372,10 @@
             scheme = scheme.lower()
 
             credFactory = None
-            
+
             if schemeConfig['Enabled']:
                 log.msg("Setting up scheme: %s" % (scheme,))
-                
+
                 if scheme == 'kerberos':
                     if not NegotiateCredentialFactory:
                         log.msg("Kerberos support not available")
@@ -414,7 +414,7 @@
 
         #
         # Configure the service
-        # 
+        #
 
         log.msg("Setting up service")
 
@@ -424,9 +424,11 @@
             config.AccessLogFile,))
 
         logObserver = RotatingFileAccessLoggingObserver(config.AccessLogFile)
-        
+
         service = CalDAVService(logObserver)
 
+        directory.setServiceParent(service)
+
         if not config.BindAddresses:
             config.BindAddresses = [""]
 
@@ -448,20 +450,20 @@
 
             for port in config.BindHTTPPorts:
                 log.msg("Adding server at %s:%s" % (bindAddress, port))
-                
+
                 httpService = internet.TCPServer(int(port), channel, interface=bindAddress)
                 httpService.setServiceParent(service)
 
             for port in config.BindSSLPorts:
                 log.msg("Adding SSL server at %s:%s" % (bindAddress, port))
-            
+
                 httpsService = internet.SSLServer(
                     int(port), channel,
                     DefaultOpenSSLContextFactory(config.SSLPrivateKey, config.SSLCertificate),
                     interface=bindAddress
                 )
                 httpsService.setServiceParent(service)
-            
+
         return service
 
     makeService_Combined = makeService_Combined

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.macosforge.org/pipermail/calendarserver-changes/attachments/20070226/d4c10ac2/attachment.html


More information about the calendarserver-changes mailing list