# The Evolution of Finger: pluggable backends

## Introduction

This is the fifth part of the Twisted tutorial Twisted from Scratch, or The Evolution of Finger.

In this part we will add new several new backends to our finger service using the component-based architecture developed in The Evolution of Finger: moving to a component based architecture. This will show just how convenient it is to implement new back-ends when we move to a component based architecture. Note that here we also use an interface we previously wrote, `FingerSetterFactory`, by supporting one single method. We manage to preserve the service's ignorance of the network.

## Another Back-end

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    from twisted.internet import protocol, reactor, defer, utils
    import pwd

    # Another back-end

    class LocalFingerService(service.Service):

        implements(IFingerService)

        def getUser(self, user):
        # need a local finger daemon running for this to work
            return utils.getProcessOutput("finger", [user])

        def getUsers(self):
            return defer.succeed([])

    f = LocalFingerService()

Source listing - listings/finger/finger19b_changes.py

Full source code here:

      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    # Do everything properly, and componentize
    from twisted.application import internet, service
    from twisted.internet import protocol, reactor, defer, utils
    from twisted.words.protocols import irc
    from twisted.protocols import basic
    from twisted.python import components
    from twisted.web import resource, server, static, xmlrpc
    from zope.interface import Interface, implements
    import cgi
    import pwd

    class IFingerService(Interface):

        def getUser(user):
            """
            Return a deferred returning a string.
            """

        def getUsers():
            """
            Return a deferred returning a list of strings.
            """

    class IFingerSetterService(Interface):

        def setUser(user, status):
            """
            Set the user's status to something.
            """

    class IFingerSetterService(Interface):

        def setUser(user, status):
            """
            Set the user's status to something.
            """

    def catchError(err):
        return "Internal error in server"

    class FingerProtocol(basic.LineReceiver):

        def lineReceived(self, user):
            d = self.factory.getUser(user)
            d.addErrback(catchError)
            def writeValue(value):
                self.transport.write(value+'\r\n')
                self.transport.loseConnection()
            d.addCallback(writeValue)

    class IFingerFactory(Interface):

        def getUser(user):
            """
            Return a deferred returning a string.
            """

        def buildProtocol(addr):
            """
            Return a protocol returning a string.
            """

    class FingerFactoryFromService(protocol.ServerFactory):

        implements(IFingerFactory)

        protocol = FingerProtocol

        def __init__(self, service):
            self.service = service

        def getUser(self, user):
            return self.service.getUser(user)

    components.registerAdapter(FingerFactoryFromService,
                               IFingerService,
                               IFingerFactory)

    class FingerSetterProtocol(basic.LineReceiver):

        def connectionMade(self):
            self.lines = []

        def lineReceived(self, line):
            self.lines.append(line)

        def connectionLost(self, reason):
            if len(self.lines) == 2:
                self.factory.setUser(*self.lines)

    class IFingerSetterFactory(Interface):

        def setUser(user, status):
            """
            Return a deferred returning a string.
            """

        def buildProtocol(addr):
            """
            Return a protocol returning a string.
            """

    class FingerSetterFactoryFromService(protocol.ServerFactory):

        implements(IFingerSetterFactory)

        protocol = FingerSetterProtocol

        def __init__(self, service):
            self.service = service

        def setUser(self, user, status):
            self.service.setUser(user, status)

    components.registerAdapter(FingerSetterFactoryFromService,
                               IFingerSetterService,
                               IFingerSetterFactory)

    class IRCReplyBot(irc.IRCClient):

        def connectionMade(self):
            self.nickname = self.factory.nickname
            irc.IRCClient.connectionMade(self)

        def privmsg(self, user, channel, msg):
            user = user.split('!')[0]
            if self.nickname.lower() == channel.lower():
                d = self.factory.getUser(msg)
                d.addErrback(catchError)
                d.addCallback(lambda m: "Status of %s: %s" % (msg, m))
                d.addCallback(lambda m: self.msg(user, m))

    class IIRCClientFactory(Interface):

        """
        @ivar nickname
        """

        def getUser(user):
            """
            Return a deferred returning a string.
            """

        def buildProtocol(addr):
            """
            Return a protocol.
            """

    class IRCClientFactoryFromService(protocol.ClientFactory):

        implements(IIRCClientFactory)

        protocol = IRCReplyBot
        nickname = None

        def __init__(self, service):
            self.service = service

        def getUser(self, user):
            return self.service.getUser(user)

    components.registerAdapter(IRCClientFactoryFromService,
                               IFingerService,
                               IIRCClientFactory)

    class UserStatusTree(resource.Resource):

        implements(resource.IResource)

        def __init__(self, service):
            resource.Resource.__init__(self)
            self.service = service
            self.putChild('RPC2', UserStatusXR(self.service))

        def render_GET(self, request):
            d = self.service.getUsers()
            def formatUsers(users):
                l = ['<li><a href="%s">%s</a></li>' % (user, user)
                     for user in users]
                return '<ul>'+''.join(l)+'</ul>'
            d.addCallback(formatUsers)
            d.addCallback(request.write)
            d.addCallback(lambda _: request.finish())
            return server.NOT_DONE_YET

        def getChild(self, path, request):
            if path=="":
                return UserStatusTree(self.service)
            else:
                return UserStatus(path, self.service)

    components.registerAdapter(UserStatusTree, IFingerService,
                               resource.IResource)

    class UserStatus(resource.Resource):

        def __init__(self, user, service):
            resource.Resource.__init__(self)
            self.user = user
            self.service = service

        def render_GET(self, request):
            d = self.service.getUser(self.user)
            d.addCallback(cgi.escape)
            d.addCallback(lambda m:
                          '<h1>%s</h1>'%self.user+'<p>%s</p>'%m)
            d.addCallback(request.write)
            d.addCallback(lambda _: request.finish())
            return server.NOT_DONE_YET

    class UserStatusXR(xmlrpc.XMLRPC):

        def __init__(self, service):
            xmlrpc.XMLRPC.__init__(self)
            self.service = service

        def xmlrpc_getUser(self, user):
            return self.service.getUser(user)

    class FingerService(service.Service):

        implements(IFingerService)

        def __init__(self, filename):
            self.filename = filename
            self.users = {}

        def _read(self):
            self.users.clear()
            for line in file(self.filename):
                user, status = line.split(':', 1)
                user = user.strip()
                status = status.strip()
                self.users[user] = status
            self.call = reactor.callLater(30, self._read)

        def getUser(self, user):
            return defer.succeed(self.users.get(user, "No such user"))

        def getUsers(self):
            return defer.succeed(self.users.keys())

        def startService(self):
            self._read()
            service.Service.startService(self)

        def stopService(self):
            service.Service.stopService(self)
            self.call.cancel()

    # Another back-end

    class LocalFingerService(service.Service):

        implements(IFingerService)

        def getUser(self, user):
        # need a local finger daemon running for this to work
            return utils.getProcessOutput("finger", [user])

        def getUsers(self):
            return defer.succeed([])

    application = service.Application('finger', uid=1, gid=1)
    f = LocalFingerService()
    serviceCollection = service.IServiceCollection(application)
    internet.TCPServer(79, IFingerFactory(f)
                       ).setServiceParent(serviceCollection)
    internet.TCPServer(8000, server.Site(resource.IResource(f))
                       ).setServiceParent(serviceCollection)
    i = IIRCClientFactory(f)
    i.nickname = 'fingerbot'
    internet.TCPClient('irc.freenode.org', 6667, i
                       ).setServiceParent(serviceCollection)

Source listing - listings/finger/finger19b.tac

We've already written this, but now we get more for less work: the network code is completely separate from the back-end.

## Yet Another Back-end: Doing the Standard Thing

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    from twisted.internet import protocol, reactor, defer, utils
    import pwd
    import os

    # Yet another back-end

    class LocalFingerService(service.Service):

        implements(IFingerService)

        def getUser(self, user):
            user = user.strip()
            try:
                entry = pwd.getpwnam(user)
            except KeyError:
                return defer.succeed("No such user")
            try:
                f = file(os.path.join(entry[5],'.plan'))
            except (IOError, OSError):
                return defer.succeed("No such user")
            data = f.read()
            data = data.strip()
            f.close()
            return defer.succeed(data)

        def getUsers(self):
            return defer.succeed([])

    f = LocalFingerService()

Source listing - listings/finger/finger19c_changes.py

Full source code here:

      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    # Do everything properly, and componentize
    from twisted.application import internet, service
    from twisted.internet import protocol, reactor, defer, utils
    from twisted.words.protocols import irc
    from twisted.protocols import basic
    from twisted.python import components
    from twisted.web import resource, server, static, xmlrpc
    from zope.interface import Interface, implements
    import cgi
    import pwd
    import os

    class IFingerService(Interface):

        def getUser(user):
            """
            Return a deferred returning a string.
            """

        def getUsers():
            """
            Return a deferred returning a list of strings.
            """

    class IFingerSetterService(Interface):

        def setUser(user, status):
            """
            Set the user's status to something.
            """

    class IFingerSetterService(Interface):

        def setUser(user, status):
            """
            Set the user's status to something.
            """

    def catchError(err):
        return "Internal error in server"

    class FingerProtocol(basic.LineReceiver):

        def lineReceived(self, user):
            d = self.factory.getUser(user)
            d.addErrback(catchError)
            def writeValue(value):
                self.transport.write(value+'\r\n')
                self.transport.loseConnection()
            d.addCallback(writeValue)

    class IFingerFactory(Interface):

        def getUser(user):
            """
            Return a deferred returning a string.
            """

        def buildProtocol(addr):
            """
            Return a protocol returning a string.
            """

    class FingerFactoryFromService(protocol.ServerFactory):

        implements(IFingerFactory)

        protocol = FingerProtocol

        def __init__(self, service):
            self.service = service

        def getUser(self, user):
            return self.service.getUser(user)

    components.registerAdapter(FingerFactoryFromService,
                               IFingerService,
                               IFingerFactory)

    class FingerSetterProtocol(basic.LineReceiver):

        def connectionMade(self):
            self.lines = []

        def lineReceived(self, line):
            self.lines.append(line)

        def connectionLost(self, reason):
            if len(self.lines) == 2:
                self.factory.setUser(*self.lines)

    class IFingerSetterFactory(Interface):

        def setUser(user, status):
            """
            Return a deferred returning a string.
            """

        def buildProtocol(addr):
            """
            Return a protocol returning a string.
            """

    class FingerSetterFactoryFromService(protocol.ServerFactory):

        implements(IFingerSetterFactory)

        protocol = FingerSetterProtocol

        def __init__(self, service):
            self.service = service

        def setUser(self, user, status):
            self.service.setUser(user, status)

    components.registerAdapter(FingerSetterFactoryFromService,
                               IFingerSetterService,
                               IFingerSetterFactory)

    class IRCReplyBot(irc.IRCClient):

        def connectionMade():
            self.nickname = self.factory.nickname
            irc.IRCClient.connectionMade(self)

        def privmsg(self, user, channel, msg):
            user = user.split('!')[0]
            if self.nickname.lower() == channel.lower():
                d = self.factory.getUser(msg)
                d.addErrback(catchError)
                d.addCallback(lambda m: "Status of %s: %s" % (msg, m))
                d.addCallback(lambda m: self.msg(user, m))

    class IIRCClientFactory(Interface):

        """
        @ivar nickname
        """

        def getUser(user):
            """
            Return a deferred returning a string.
            """

        def buildProtocol(addr):
            """
            Return a protocol.
            """

    class IRCClientFactoryFromService(protocol.ClientFactory):

        implements(IIRCClientFactory)

        protocol = IRCReplyBot
        nickname = None

        def __init__(self, service):
            self.service = service

        def getUser(self, user):
            return self.service.getUser(user)

    components.registerAdapter(IRCClientFactoryFromService,
                               IFingerService,
                               IIRCClientFactory)

    class UserStatusTree(resource.Resource):

        implements(resource.IResource)

        def __init__(self, service):
            resource.Resource.__init__(self)
            self.service = service
            self.putChild('RPC2', UserStatusXR(self.service))

        def render_GET(self, request):
            d = self.service.getUsers()
            def formatUsers(users):
                l = ['<li><a href="%s">%s</a></li>' % (user, user)
                     for user in users]
                return '<ul>'+''.join(l)+'</ul>'
            d.addCallback(formatUsers)
            d.addCallback(request.write)
            d.addCallback(lambda _: request.finish())
            return server.NOT_DONE_YET

        def getChild(self, path, request):
            if path=="":
                return UserStatusTree(self.service)
            else:
                return UserStatus(path, self.service)

    components.registerAdapter(UserStatusTree, IFingerService,
                               resource.IResource)

    class UserStatus(resource.Resource):

        def __init__(self, user, service):
            resource.Resource.__init__(self)
            self.user = user
            self.service = service

        def render_GET(self, request):
            d = self.service.getUser(self.user)
            d.addCallback(cgi.escape)
            d.addCallback(lambda m:
                          '<h1>%s</h1>'%self.user+'<p>%s</p>'%m)
            d.addCallback(request.write)
            d.addCallback(lambda _: request.finish())
            return server.NOT_DONE_YET

    class UserStatusXR(xmlrpc.XMLRPC):

        def __init__(self, service):
            xmlrpc.XMLRPC.__init__(self)
            self.service = service

        def xmlrpc_getUser(self, user):
            return self.service.getUser(user)

    class FingerService(service.Service):

        implements(IFingerService)

        def __init__(self, filename):
            self.filename = filename
            self.users = {}

        def _read(self):
            self.users.clear()
            for line in file(self.filename):
                user, status = line.split(':', 1)
                user = user.strip()
                status = status.strip()
                self.users[user] = status
            self.call = reactor.callLater(30, self._read)

        def getUser(self, user):
            return defer.succeed(self.users.get(user, "No such user"))

        def getUsers(self):
            return defer.succeed(self.users.keys())

        def startService(self):
            self._read()
            service.Service.startService(self)

        def stopService(self):
            service.Service.stopService(self)
            self.call.cancel()

    # Yet another back-end

    class LocalFingerService(service.Service):

        implements(IFingerService)

        def getUser(self, user):
            user = user.strip()
            try:
                entry = pwd.getpwnam(user)
            except KeyError:
                return defer.succeed("No such user")
            try:
                f = file(os.path.join(entry[5],'.plan'))
            except (IOError, OSError):
                return defer.succeed("No such user")
            data = f.read()
            data = data.strip()
            f.close()
            return defer.succeed(data)

        def getUsers(self):
            return defer.succeed([])

    application = service.Application('finger', uid=1, gid=1)
    f = LocalFingerService()
    serviceCollection = service.IServiceCollection(application)
    internet.TCPServer(79, IFingerFactory(f)
                       ).setServiceParent(serviceCollection)
    internet.TCPServer(8000, server.Site(resource.IResource(f))
                       ).setServiceParent(serviceCollection)
    i = IIRCClientFactory(f)
    i.nickname = 'fingerbot'
    internet.TCPClient('irc.freenode.org', 6667, i
                       ).setServiceParent(serviceCollection)

Source listing - listings/finger/finger19c.tac

Not much to say except that now we can be churn out backends like crazy. Feel like doing a back-end for Advogato, for example? Dig out the XML-RPC client support Twisted has, and get to work!

Index

Version: 11.0.0