[CalendarServer-changes] [12571] CalendarServer/trunk/txdav/dps

source_changes at macosforge.org source_changes at macosforge.org
Wed Mar 12 11:16:52 PDT 2014


Revision: 12571
          http://trac.calendarserver.org//changeset/12571
Author:   sagen at apple.com
Date:     2014-02-05 09:44:38 -0800 (Wed, 05 Feb 2014)
Log Message:
-----------
Break dps modules into client and server

Modified Paths:
--------------
    CalendarServer/trunk/txdav/dps/client.py
    CalendarServer/trunk/txdav/dps/service.py

Added Paths:
-----------
    CalendarServer/trunk/txdav/dps/commands.py
    CalendarServer/trunk/txdav/dps/server.py

Removed Paths:
-------------
    CalendarServer/trunk/txdav/dps/protocol.py

Modified: CalendarServer/trunk/txdav/dps/client.py
===================================================================
--- CalendarServer/trunk/txdav/dps/client.py	2014-02-05 01:04:49 UTC (rev 12570)
+++ CalendarServer/trunk/txdav/dps/client.py	2014-02-05 17:44:38 UTC (rev 12571)
@@ -14,19 +14,179 @@
 # limitations under the License.
 ##
 
-from txdav.dps.service import DirectoryService
 from twext.who.idirectory import RecordType
 from twext.python.log import Logger
 from twisted.internet import reactor
-from twisted.internet.defer import inlineCallbacks
+from twext.who.directory import DirectoryService as BaseDirectoryService
+from twext.who.directory import DirectoryRecord as BaseDirectoryRecord
+from twext.who.util import ConstantsContainer
+import twext.who.idirectory
+import txdav.who.idirectory
 
+from zope.interface import implementer
+
+from txdav.dps.commands import (
+    RecordWithShortNameCommand, RecordWithUIDCommand,
+    RecordWithGUIDCommand, RecordsWithRecordTypeCommand,
+    RecordsWithEmailAddressCommand
+)
+
+from twisted.internet.defer import inlineCallbacks, returnValue
+from twisted.internet.protocol import ClientCreator
+from twisted.protocols import amp
+import cPickle as pickle
+
 log = Logger()
 
 
+##
+## Client implementation of Directory Proxy Service
+##
+
+
+ at implementer(twext.who.idirectory.IDirectoryService)
+class DirectoryService(BaseDirectoryService):
+    """
+    Client side of directory proxy
+    """
+
+    recordType = ConstantsContainer(
+        (twext.who.idirectory.RecordType,
+         txdav.who.idirectory.RecordType)
+    )
+
+
+    def _dictToRecord(self, serializedFields):
+        """
+        This to be replaced by something awesome
+        """
+        if not serializedFields:
+            return None
+
+        fields = {}
+        for fieldName, value in serializedFields.iteritems():
+            try:
+                field = self.fieldName.lookupByName(fieldName)
+            except ValueError:
+                # unknown field
+                pass
+            else:
+                fields[field] = value
+        fields[self.fieldName.recordType] = self.recordType.user
+        return DirectoryRecord(self, fields)
+
+
+    def _processSingleRecord(self, result):
+        serializedFields = pickle.loads(result['fields'])
+        return self._dictToRecord(serializedFields)
+
+
+    def _processMultipleRecords(self, result):
+        serializedFieldsList = pickle.loads(result['fieldsList'])
+        results = []
+        for serializedFields in serializedFieldsList:
+            record = self._dictToRecord(serializedFields)
+            if record is not None:
+                results.append(record)
+        return results
+
+
+    @inlineCallbacks
+    def _getConnection(self):
+        # path = config.DirectoryProxy.SocketPath
+        path = "data/Logs/state/directory-proxy.sock"
+        if getattr(self, "_connection", None) is None:
+            log.debug("Creating connection")
+            connection = (yield ClientCreator(reactor, amp.AMP).connectUNIX(path))
+            self._connection = connection
+        else:
+            log.debug("Already have connection")
+        returnValue(self._connection)
+
+
+    def recordWithShortName(self, recordType, shortName):
+
+        def _call(ampProto):
+            return ampProto.callRemote(
+                RecordWithShortNameCommand,
+                recordType=recordType.description.encode("utf-8"),
+                shortName=shortName.encode("utf-8")
+            )
+
+        d = self._getConnection()
+        d.addCallback(_call)
+        d.addCallback(self._processSingleRecord)
+        return d
+
+
+    def recordWithUID(self, uid):
+
+        def _call(ampProto):
+            return ampProto.callRemote(
+                RecordWithUIDCommand,
+                uid=uid.encode("utf-8")
+            )
+
+        d = self._getConnection()
+        d.addCallback(_call)
+        d.addCallback(self._processSingleRecord)
+        return d
+
+
+    def recordWithGUID(self, guid):
+
+        def _call(ampProto):
+            return ampProto.callRemote(
+                RecordWithGUIDCommand,
+                guid=guid.encode("utf-8")
+            )
+
+        d = self._getConnection()
+        d.addCallback(_call)
+        d.addCallback(self._processSingleRecord)
+        return d
+
+
+    def recordsWithRecordType(self, recordType):
+
+        def _call(ampProto):
+            return ampProto.callRemote(
+                RecordsWithRecordTypeCommand,
+                recordType=recordType.description.encode("utf-8")
+            )
+
+        d = self._getConnection()
+        d.addCallback(_call)
+        d.addCallback(self._processMultipleRecords)
+        return d
+
+
+    def recordsWithEmailAddress(self, emailAddress):
+
+        def _call(ampProto):
+            return ampProto.callRemote(
+                RecordsWithEmailAddressCommand,
+                emailAddress=emailAddress
+            )
+
+        d = self._getConnection()
+        d.addCallback(_call)
+        d.addCallback(self._processMultipleRecords)
+        return d
+
+
+class DirectoryRecord(BaseDirectoryRecord):
+    pass
+
+
+
+# Test client:
+
+
 @inlineCallbacks
 def makeEvenBetterRequest():
     ds = DirectoryService(None)
-    record = (yield ds.recordWithShortName(RecordType.user, "sagen"))
+    record = (yield ds.recordWithShortName(RecordType.user, "wsanchez"))
     print("short name: {r}".format(r=record))
     record = (yield ds.recordWithUID("__dre__"))
     print("uid: {r}".format(r=record))

Added: CalendarServer/trunk/txdav/dps/commands.py
===================================================================
--- CalendarServer/trunk/txdav/dps/commands.py	                        (rev 0)
+++ CalendarServer/trunk/txdav/dps/commands.py	2014-02-05 17:44:38 UTC (rev 12571)
@@ -0,0 +1,82 @@
+##
+# Copyright (c) 2014 Apple Inc. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##
+
+from twisted.protocols import amp
+
+
+class RecordWithShortNameCommand(amp.Command):
+    arguments = [
+        ('recordType', amp.String()),
+        ('shortName', amp.String()),
+    ]
+    response = [
+        ('fields', amp.String()),
+    ]
+
+
+class RecordWithUIDCommand(amp.Command):
+    arguments = [
+        ('uid', amp.String()),
+    ]
+    response = [
+        ('fields', amp.String()),
+    ]
+
+
+class RecordWithGUIDCommand(amp.Command):
+    arguments = [
+        ('guid', amp.String()),
+    ]
+    response = [
+        ('fields', amp.String()),
+    ]
+
+
+class RecordsWithRecordTypeCommand(amp.Command):
+    arguments = [
+        ('recordType', amp.String()),
+    ]
+    response = [
+        ('fieldsList', amp.String()),
+    ]
+
+
+class RecordsWithEmailAddressCommand(amp.Command):
+    arguments = [
+        ('emailAddress', amp.String()),
+    ]
+    response = [
+        ('fieldsList', amp.String()),
+    ]
+
+
+class UpdateRecordsCommand(amp.Command):
+    arguments = [
+        ('fieldsList', amp.String()),
+        ('create', amp.Boolean(optional=True)),
+    ]
+    response = [
+        ('success', amp.Boolean()),
+    ]
+
+
+class RemoveRecordsCommand(amp.Command):
+    arguments = [
+        ('uids', amp.ListOf(amp.String())),
+    ]
+    response = [
+        ('success', amp.Boolean()),
+    ]

Deleted: CalendarServer/trunk/txdav/dps/protocol.py
===================================================================
--- CalendarServer/trunk/txdav/dps/protocol.py	2014-02-05 01:04:49 UTC (rev 12570)
+++ CalendarServer/trunk/txdav/dps/protocol.py	2014-02-05 17:44:38 UTC (rev 12571)
@@ -1,195 +0,0 @@
-##
-# Copyright (c) 2014 Apple Inc. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-##
-
-from twext.who.idirectory import RecordType
-from twisted.protocols import amp
-from twisted.internet.defer import inlineCallbacks, returnValue
-from twext.python.log import Logger
-import uuid
-import cPickle as pickle
-
-log = Logger()
-
-
-
-class RecordWithShortNameCommand(amp.Command):
-    arguments = [
-        ('recordType', amp.String()),
-        ('shortName', amp.String()),
-    ]
-    response = [
-        ('fields', amp.String()),
-    ]
-
-
-class RecordWithUIDCommand(amp.Command):
-    arguments = [
-        ('uid', amp.String()),
-    ]
-    response = [
-        ('fields', amp.String()),
-    ]
-
-
-class RecordWithGUIDCommand(amp.Command):
-    arguments = [
-        ('guid', amp.String()),
-    ]
-    response = [
-        ('fields', amp.String()),
-    ]
-
-
-class RecordsWithRecordTypeCommand(amp.Command):
-    arguments = [
-        ('recordType', amp.String()),
-    ]
-    response = [
-        ('fieldsList', amp.String()),
-    ]
-
-
-class RecordsWithEmailAddressCommand(amp.Command):
-    arguments = [
-        ('emailAddress', amp.String()),
-    ]
-    response = [
-        ('fieldsList', amp.String()),
-    ]
-
-
-class UpdateRecordsCommand(amp.Command):
-    arguments = [
-        ('fieldsList', amp.String()),
-        ('create', amp.Boolean(optional=True)),
-    ]
-    response = [
-        ('success', amp.Boolean()),
-    ]
-
-
-class RemoveRecordsCommand(amp.Command):
-    arguments = [
-        ('uids', amp.ListOf(amp.String())),
-    ]
-    response = [
-        ('success', amp.Boolean()),
-    ]
-
-
-class DirectoryProxyAMPProtocol(amp.AMP):
-    """
-    Server side of directory proxy
-    """
-
-    def __init__(self, directory):
-        """
-        """
-        amp.AMP.__init__(self)
-        self._directory = directory
-
-
-    def recordToDict(self, record):
-        """
-        This to be replaced by something awesome
-        """
-        fields = {}
-        if record is not None:
-            for field, value in record.fields.iteritems():
-                # print("%s: %s" % (field.name, value))
-                valueType = self._directory.fieldName.valueType(field)
-                if valueType is unicode:
-                    fields[field.name] = value
-        return fields
-
-
-    @RecordWithShortNameCommand.responder
-    @inlineCallbacks
-    def recordWithShortName(self, recordType, shortName):
-        recordType = recordType  # keep as bytes
-        shortName = shortName.decode("utf-8")
-        log.debug("RecordWithShortName: {r} {n}", r=recordType, n=shortName)
-        record = (yield self._directory.recordWithShortName(
-            RecordType.lookupByName(recordType), shortName)
-        )
-        fields = self.recordToDict(record)
-        response = {
-            "fields": pickle.dumps(fields),
-        }
-        log.debug("Responding with: {response}", response=response)
-        returnValue(response)
-
-
-    @RecordWithUIDCommand.responder
-    @inlineCallbacks
-    def recordWithUID(self, uid):
-        uid = uid.decode("utf-8")
-        log.debug("RecordWithUID: {u}", u=uid)
-        record = (yield self._directory.recordWithUID(uid))
-        fields = self.recordToDict(record)
-        response = {
-            "fields": pickle.dumps(fields),
-        }
-        log.debug("Responding with: {response}", response=response)
-        returnValue(response)
-
-
-    @RecordWithGUIDCommand.responder
-    @inlineCallbacks
-    def recordWithGUID(self, guid):
-        guid = uuid.UUID(guid)
-        log.debug("RecordWithGUID: {g}", g=guid)
-        record = (yield self._directory.recordWithGUID(guid))
-        fields = self.recordToDict(record)
-        response = {
-            "fields": pickle.dumps(fields),
-        }
-        log.debug("Responding with: {response}", response=response)
-        returnValue(response)
-
-
-    @RecordsWithRecordTypeCommand.responder
-    @inlineCallbacks
-    def recordsWithRecordType(self, recordType):
-        recordType = recordType  # as bytes
-        log.debug("RecordsWithRecordType: {r}", r=recordType)
-        records = (yield self._directory.recordsWithRecordType(
-            RecordType.lookupByName(recordType))
-        )
-        fieldsList = []
-        for record in records:
-            fieldsList.append(self.recordToDict(record))
-        response = {
-            "fieldsList": pickle.dumps(fieldsList),
-        }
-        log.debug("Responding with: {response}", response=response)
-        returnValue(response)
-
-
-    @RecordsWithEmailAddressCommand.responder
-    @inlineCallbacks
-    def recordsWithEmailAddress(self, emailAddress):
-        emailAddress = emailAddress.decode("utf-8")
-        log.debug("RecordsWithEmailAddress: {e}", e=emailAddress)
-        records = (yield self._directory.recordsWithEmailAddress(emailAddress))
-        fieldsList = []
-        for record in records:
-            fieldsList.append(self.recordToDict(record))
-        response = {
-            "fieldsList": pickle.dumps(fieldsList),
-        }
-        log.debug("Responding with: {response}", response=response)
-        returnValue(response)

Added: CalendarServer/trunk/txdav/dps/server.py
===================================================================
--- CalendarServer/trunk/txdav/dps/server.py	                        (rev 0)
+++ CalendarServer/trunk/txdav/dps/server.py	2014-02-05 17:44:38 UTC (rev 12571)
@@ -0,0 +1,296 @@
+##
+# Copyright (c) 2014 Apple Inc. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##
+
+from twext.who.idirectory import RecordType
+from twisted.protocols import amp
+from twisted.internet.defer import inlineCallbacks, returnValue
+from twext.python.log import Logger
+import uuid
+import cPickle as pickle
+from txdav.dps.commands import (
+    RecordWithShortNameCommand, RecordWithUIDCommand, RecordWithGUIDCommand,
+    RecordsWithRecordTypeCommand, RecordsWithEmailAddressCommand,
+    # UpdateRecordsCommand, RemoveRecordsCommand
+)
+from twisted.internet.protocol import Factory
+from twisted.python.usage import Options, UsageError
+from twistedcaldav.config import config
+from twistedcaldav.stdconfig import DEFAULT_CONFIG, DEFAULT_CONFIG_FILE
+from zope.interface import implementer
+from twisted.plugin import IPlugin
+from twisted.application import service
+from twext.who.opendirectory import DirectoryService as ODDirectoryService
+from txdav.who.xml import DirectoryService as XMLDirectoryService
+from twisted.python.filepath import FilePath
+from twisted.application.strports import service as strPortsService
+
+log = Logger()
+
+
+##
+## Server implementation of Directory Proxy Service
+##
+
+
+class DirectoryProxyAMPProtocol(amp.AMP):
+    """
+    Server side of directory proxy
+    """
+
+    def __init__(self, directory):
+        """
+        """
+        amp.AMP.__init__(self)
+        self._directory = directory
+
+
+    def recordToDict(self, record):
+        """
+        This to be replaced by something awesome
+        """
+        fields = {}
+        if record is not None:
+            for field, value in record.fields.iteritems():
+                # print("%s: %s" % (field.name, value))
+                valueType = self._directory.fieldName.valueType(field)
+                if valueType is unicode:
+                    fields[field.name] = value
+        return fields
+
+
+    @RecordWithShortNameCommand.responder
+    @inlineCallbacks
+    def recordWithShortName(self, recordType, shortName):
+        recordType = recordType  # keep as bytes
+        shortName = shortName.decode("utf-8")
+        log.debug("RecordWithShortName: {r} {n}", r=recordType, n=shortName)
+        record = (yield self._directory.recordWithShortName(
+            RecordType.lookupByName(recordType), shortName)
+        )
+        fields = self.recordToDict(record)
+        response = {
+            "fields": pickle.dumps(fields),
+        }
+        log.debug("Responding with: {response}", response=response)
+        returnValue(response)
+
+
+    @RecordWithUIDCommand.responder
+    @inlineCallbacks
+    def recordWithUID(self, uid):
+        uid = uid.decode("utf-8")
+        log.debug("RecordWithUID: {u}", u=uid)
+        try:
+            record = (yield self._directory.recordWithUID(uid))
+        except Exception as e:
+            log.error("Failed in recordWithUID", error=e)
+            record = None
+        fields = self.recordToDict(record)
+        response = {
+            "fields": pickle.dumps(fields),
+        }
+        log.debug("Responding with: {response}", response=response)
+        returnValue(response)
+
+
+    @RecordWithGUIDCommand.responder
+    @inlineCallbacks
+    def recordWithGUID(self, guid):
+        guid = uuid.UUID(guid)
+        log.debug("RecordWithGUID: {g}", g=guid)
+        record = (yield self._directory.recordWithGUID(guid))
+        fields = self.recordToDict(record)
+        response = {
+            "fields": pickle.dumps(fields),
+        }
+        log.debug("Responding with: {response}", response=response)
+        returnValue(response)
+
+
+    @RecordsWithRecordTypeCommand.responder
+    @inlineCallbacks
+    def recordsWithRecordType(self, recordType):
+        recordType = recordType  # as bytes
+        log.debug("RecordsWithRecordType: {r}", r=recordType)
+        records = (yield self._directory.recordsWithRecordType(
+            RecordType.lookupByName(recordType))
+        )
+        fieldsList = []
+        for record in records:
+            fieldsList.append(self.recordToDict(record))
+        response = {
+            "fieldsList": pickle.dumps(fieldsList),
+        }
+        log.debug("Responding with: {response}", response=response)
+        returnValue(response)
+
+
+    @RecordsWithEmailAddressCommand.responder
+    @inlineCallbacks
+    def recordsWithEmailAddress(self, emailAddress):
+        emailAddress = emailAddress.decode("utf-8")
+        log.debug("RecordsWithEmailAddress: {e}", e=emailAddress)
+        records = (yield self._directory.recordsWithEmailAddress(emailAddress))
+        fieldsList = []
+        for record in records:
+            fieldsList.append(self.recordToDict(record))
+        response = {
+            "fieldsList": pickle.dumps(fieldsList),
+        }
+        log.debug("Responding with: {response}", response=response)
+        returnValue(response)
+
+
+
+
+class DirectoryProxyAMPFactory(Factory):
+    """
+    """
+    protocol = DirectoryProxyAMPProtocol
+
+
+    def __init__(self, directory):
+        self._directory = directory
+
+    def buildProtocol(self, addr):
+        return DirectoryProxyAMPProtocol(self._directory)
+
+
+
+
+
+class DirectoryProxyOptions(Options):
+    optParameters = [[
+        "config", "f", DEFAULT_CONFIG_FILE, "Path to configuration file."
+    ]]
+
+
+    def __init__(self, *args, **kwargs):
+        super(DirectoryProxyOptions, self).__init__(*args, **kwargs)
+
+        self.overrides = {}
+
+
+    def _coerceOption(self, configDict, key, value):
+        """
+        Coerce the given C{val} to type of C{configDict[key]}
+        """
+        if key in configDict:
+            if isinstance(configDict[key], bool):
+                value = value == "True"
+
+            elif isinstance(configDict[key], (int, float, long)):
+                value = type(configDict[key])(value)
+
+            elif isinstance(configDict[key], (list, tuple)):
+                value = value.split(',')
+
+            elif isinstance(configDict[key], dict):
+                raise UsageError(
+                    "Dict options not supported on the command line"
+                )
+
+            elif value == 'None':
+                value = None
+
+        return value
+
+
+    def _setOverride(self, configDict, path, value, overrideDict):
+        """
+        Set the value at path in configDict
+        """
+        key = path[0]
+
+        if len(path) == 1:
+            overrideDict[key] = self._coerceOption(configDict, key, value)
+            return
+
+        if key in configDict:
+            if not isinstance(configDict[key], dict):
+                raise UsageError(
+                    "Found intermediate path element that is not a dictionary"
+                )
+
+            if key not in overrideDict:
+                overrideDict[key] = {}
+
+            self._setOverride(
+                configDict[key], path[1:],
+                value, overrideDict[key]
+            )
+
+
+    def opt_option(self, option):
+        """
+        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
+        --option flags may be specified.
+        """
+
+        if "=" in option:
+            path, value = option.split('=')
+            self._setOverride(
+                DEFAULT_CONFIG,
+                path.split('/'),
+                value,
+                self.overrides
+            )
+        else:
+            self.opt_option('%s=True' % (option,))
+
+    opt_o = opt_option
+
+    def postOptions(self):
+        config.load(self['config'])
+        config.updateDefaults(self.overrides)
+        self.parent['pidfile'] = None
+
+
+ at implementer(IPlugin, service.IServiceMaker)
+class DirectoryProxyServiceMaker(object):
+
+    tapname = "caldav_directoryproxy"
+    description = "Directory Proxy Service"
+    options = DirectoryProxyOptions
+
+    def makeService(self, options):
+        """
+        Return a service
+        """
+        try:
+            from setproctitle import setproctitle
+        except ImportError:
+            pass
+        else:
+            setproctitle("CalendarServer Directory Proxy Service")
+
+        directoryType = config.DirectoryProxy.DirectoryType
+        if directoryType == "OD":
+            directory = ODDirectoryService()
+        elif directoryType == "LDAP":
+            pass
+        elif directoryType == "XML":
+            directory = XMLDirectoryService(FilePath("foo.xml"))
+        else:
+            log.error("Invalid DirectoryType: {dt}", dt=directoryType)
+
+
+        desc = "unix:{path}:mode=660".format(
+            path=config.DirectoryProxy.SocketPath
+        )
+        return strPortsService(desc, DirectoryProxyAMPFactory(directory))

Modified: CalendarServer/trunk/txdav/dps/service.py
===================================================================
--- CalendarServer/trunk/txdav/dps/service.py	2014-02-05 01:04:49 UTC (rev 12570)
+++ CalendarServer/trunk/txdav/dps/service.py	2014-02-05 17:44:38 UTC (rev 12571)
@@ -14,29 +14,18 @@
 # limitations under the License.
 ##
 
-# Temporary:
-from txdav.who.xml import DirectoryService as XMLDirectoryService
 
-
 from twext.who.directory import DirectoryService as BaseDirectoryService
 from twext.who.directory import DirectoryRecord as BaseDirectoryRecord
 from twext.who.util import ConstantsContainer
 import twext.who.idirectory
 import txdav.who.idirectory
 
-from twisted.python.usage import Options, UsageError
-from twisted.plugin import IPlugin
-from twisted.application import service
 from zope.interface import implementer
-from twistedcaldav.config import config
-from twistedcaldav.stdconfig import DEFAULT_CONFIG, DEFAULT_CONFIG_FILE
-from twisted.application.strports import service as strPortsService
-from twisted.internet.protocol import Factory
 from twext.python.log import Logger
-from twisted.python.filepath import FilePath
 
-from .protocol import (
-    DirectoryProxyAMPProtocol, RecordWithShortNameCommand, RecordWithUIDCommand,
+from .commands import (
+    RecordWithShortNameCommand, RecordWithUIDCommand,
     RecordWithGUIDCommand, RecordsWithRecordTypeCommand,
     RecordsWithEmailAddressCommand
 )
@@ -50,6 +39,7 @@
 log = Logger()
 
 
+ at implementer(twext.who.idirectory.IDirectoryService)
 class DirectoryService(BaseDirectoryService):
     """
     Client side of directory proxy
@@ -70,8 +60,13 @@
 
         fields = {}
         for fieldName, value in serializedFields.iteritems():
-            field = self.fieldName.lookupByName(fieldName)
-            fields[field] = value
+            try:
+                field = self.fieldName.lookupByName(fieldName)
+            except ValueError:
+                # unknown field
+                pass
+            else:
+                fields[field] = value
         fields[self.fieldName.recordType] = self.recordType.user
         return DirectoryRecord(self, fields)
 
@@ -177,136 +172,3 @@
 
 class DirectoryRecord(BaseDirectoryRecord):
     pass
-
-
-
-
-class DirectoryProxyAMPFactory(Factory):
-    """
-    """
-    protocol = DirectoryProxyAMPProtocol
-
-
-    def __init__(self, directory):
-        self._directory = directory
-
-    def buildProtocol(self, addr):
-        return DirectoryProxyAMPProtocol(self._directory)
-
-
-
-
-
-class DirectoryProxyOptions(Options):
-    optParameters = [[
-        "config", "f", DEFAULT_CONFIG_FILE, "Path to configuration file."
-    ]]
-
-
-    def __init__(self, *args, **kwargs):
-        super(DirectoryProxyOptions, self).__init__(*args, **kwargs)
-
-        self.overrides = {}
-
-
-    def _coerceOption(self, configDict, key, value):
-        """
-        Coerce the given C{val} to type of C{configDict[key]}
-        """
-        if key in configDict:
-            if isinstance(configDict[key], bool):
-                value = value == "True"
-
-            elif isinstance(configDict[key], (int, float, long)):
-                value = type(configDict[key])(value)
-
-            elif isinstance(configDict[key], (list, tuple)):
-                value = value.split(',')
-
-            elif isinstance(configDict[key], dict):
-                raise UsageError(
-                    "Dict options not supported on the command line"
-                )
-
-            elif value == 'None':
-                value = None
-
-        return value
-
-
-    def _setOverride(self, configDict, path, value, overrideDict):
-        """
-        Set the value at path in configDict
-        """
-        key = path[0]
-
-        if len(path) == 1:
-            overrideDict[key] = self._coerceOption(configDict, key, value)
-            return
-
-        if key in configDict:
-            if not isinstance(configDict[key], dict):
-                raise UsageError(
-                    "Found intermediate path element that is not a dictionary"
-                )
-
-            if key not in overrideDict:
-                overrideDict[key] = {}
-
-            self._setOverride(
-                configDict[key], path[1:],
-                value, overrideDict[key]
-            )
-
-
-    def opt_option(self, option):
-        """
-        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
-        --option flags may be specified.
-        """
-
-        if "=" in option:
-            path, value = option.split('=')
-            self._setOverride(
-                DEFAULT_CONFIG,
-                path.split('/'),
-                value,
-                self.overrides
-            )
-        else:
-            self.opt_option('%s=True' % (option,))
-
-    opt_o = opt_option
-
-    def postOptions(self):
-        config.load(self['config'])
-        config.updateDefaults(self.overrides)
-        self.parent['pidfile'] = None
-
-
- at implementer(IPlugin, service.IServiceMaker)
-class DirectoryProxyServiceMaker(object):
-
-    tapname = "caldav_directoryproxy"
-    description = "Directory Proxy Service"
-    options = DirectoryProxyOptions
-
-    def makeService(self, options):
-        """
-        Return a service
-        """
-        try:
-            from setproctitle import setproctitle
-        except ImportError:
-            pass
-        else:
-            setproctitle("CalendarServer Directory Proxy Service")
-
-        directory = XMLDirectoryService(FilePath("foo.xml"))
-
-        desc = "unix:{path}:mode=660".format(
-            path=config.DirectoryProxy.SocketPath
-        )
-        return strPortsService(desc, DirectoryProxyAMPFactory(directory))
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.macosforge.org/pipermail/calendarserver-changes/attachments/20140312/27024190/attachment.html>


More information about the calendarserver-changes mailing list