]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/introducer/server.py
new introducer: signed extensible dictionary-based messages! refs #466
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / introducer / server.py
1
2 import time, os.path
3 from zope.interface import implements
4 from twisted.application import service
5 from foolscap.api import Referenceable
6 import allmydata
7 from allmydata import node
8 from allmydata.util import log
9 from allmydata.introducer.interfaces import \
10      RIIntroducerPublisherAndSubscriberService_v2
11 from allmydata.introducer.common import convert_announcement_v1_to_v2, \
12      convert_announcement_v2_to_v1, unsign_from_foolscap, make_index, \
13      get_tubid_string_from_ann
14
15 class IntroducerNode(node.Node):
16     PORTNUMFILE = "introducer.port"
17     NODETYPE = "introducer"
18     GENERATED_FILES = ['introducer.furl']
19
20     def __init__(self, basedir="."):
21         node.Node.__init__(self, basedir)
22         self.read_config()
23         self.init_introducer()
24         webport = self.get_config("node", "web.port", None)
25         if webport:
26             self.init_web(webport) # strports string
27
28     def init_introducer(self):
29         introducerservice = IntroducerService(self.basedir)
30         self.add_service(introducerservice)
31
32         d = self.when_tub_ready()
33         def _publish(res):
34             self.introducer_url = self.tub.registerReference(introducerservice,
35                                                              "introducer")
36             self.log(" introducer is at %s" % self.introducer_url,
37                      umid="qF2L9A")
38             self.write_config("introducer.furl", self.introducer_url + "\n")
39         d.addCallback(_publish)
40         d.addErrback(log.err, facility="tahoe.init",
41                      level=log.BAD, umid="UaNs9A")
42
43     def init_web(self, webport):
44         self.log("init_web(webport=%s)", args=(webport,), umid="2bUygA")
45
46         from allmydata.webish import IntroducerWebishServer
47         nodeurl_path = os.path.join(self.basedir, "node.url")
48         staticdir = self.get_config("node", "web.static", "public_html")
49         staticdir = os.path.expanduser(staticdir)
50         ws = IntroducerWebishServer(self, webport, nodeurl_path, staticdir)
51         self.add_service(ws)
52
53 class WrapV1SubscriberInV2Interface: # for_v1
54     """I wrap a RemoteReference that points at an old v1 subscriber, enabling
55     it to be treated like a v2 subscriber.
56     """
57
58     def __init__(self, original):
59         self.original = original
60     def __eq__(self, them):
61         return self.original == them
62     def __ne__(self, them):
63         return self.original != them
64     def __hash__(self):
65         return hash(self.original)
66     def getRemoteTubID(self):
67         return self.original.getRemoteTubID()
68     def getSturdyRef(self):
69         return self.original.getSturdyRef()
70     def getPeer(self):
71         return self.original.getPeer()
72     def callRemote(self, methname, *args, **kwargs):
73         m = getattr(self, "wrap_" + methname)
74         return m(*args, **kwargs)
75     def wrap_announce_v2(self, announcements):
76         anns_v1 = [convert_announcement_v2_to_v1(ann) for ann in announcements]
77         return self.original.callRemote("announce", set(anns_v1))
78     def wrap_set_encoding_parameters(self, parameters):
79         # note: unused
80         return self.original.callRemote("set_encoding_parameters", parameters)
81     def notifyOnDisconnect(self, *args, **kwargs):
82         return self.original.notifyOnDisconnect(*args, **kwargs)
83
84 class IntroducerService(service.MultiService, Referenceable):
85     implements(RIIntroducerPublisherAndSubscriberService_v2)
86     name = "introducer"
87     # v1 is the original protocol, supported since 1.0 (but only advertised
88     # starting in 1.3). v2 is the new signed protocol, supported after 1.9
89     VERSION = { "http://allmydata.org/tahoe/protocols/introducer/v1": { },
90                 "http://allmydata.org/tahoe/protocols/introducer/v2": { },
91                 "application-version": str(allmydata.__full_version__),
92                 }
93
94     def __init__(self, basedir="."):
95         service.MultiService.__init__(self)
96         self.introducer_url = None
97         # 'index' is (service_name, key_s, tubid), where key_s or tubid is
98         # None
99         self._announcements = {} # dict of index ->
100                                  # (ann_t, canary, ann, timestamp)
101
102         # ann (the announcement dictionary) is cleaned up: nickname is always
103         # unicode, servicename is always ascii, etc, even though
104         # simplejson.loads sometimes returns either
105
106         # self._subscribers is a dict mapping servicename to subscriptions
107         # 'subscriptions' is a dict mapping rref to a subscription
108         # 'subscription' is a tuple of (subscriber_info, timestamp)
109         # 'subscriber_info' is a dict, provided directly for v2 clients, or
110         # synthesized for v1 clients. The expected keys are:
111         #  version, nickname, app-versions, my-version, oldest-supported
112         self._subscribers = {}
113
114         # self._stub_client_announcements contains the information provided
115         # by v1 clients. We stash this so we can match it up with their
116         # subscriptions.
117         self._stub_client_announcements = {} # maps tubid to sinfo # for_v1
118
119         self._debug_counts = {"inbound_message": 0,
120                               "inbound_duplicate": 0,
121                               "inbound_update": 0,
122                               "outbound_message": 0,
123                               "outbound_announcements": 0,
124                               "inbound_subscribe": 0}
125         self._debug_outstanding = 0 # also covers WrapV1SubscriberInV2Interface
126
127     def _debug_retired(self, res):
128         self._debug_outstanding -= 1
129         return res
130
131     def log(self, *args, **kwargs):
132         if "facility" not in kwargs:
133             kwargs["facility"] = "tahoe.introducer.server"
134         return log.msg(*args, **kwargs)
135
136     def get_announcements(self):
137         return self._announcements
138     def get_subscribers(self):
139         """Return a list of (service_name, when, subscriber_info, rref) for
140         all subscribers. subscriber_info is a dict with the following keys:
141         version, nickname, app-versions, my-version, oldest-supported"""
142         s = []
143         for service_name, subscriptions in self._subscribers.items():
144             for rref,(subscriber_info,when) in subscriptions.items():
145                 s.append( (service_name, when, subscriber_info, rref) )
146         return s
147
148     def remote_get_version(self):
149         return self.VERSION
150
151     def remote_publish(self, ann_t): # for_v1
152         lp = self.log("introducer: old (v1) announcement published: %s"
153                       % (ann_t,), umid="6zGOIw")
154         ann_v2 = convert_announcement_v1_to_v2(ann_t)
155         return self.publish(ann_v2, None, lp)
156
157     def remote_publish_v2(self, ann_t, canary):
158         lp = self.log("introducer: announcement (v2) published", umid="L2QXkQ")
159         return self.publish(ann_t, canary, lp)
160
161     def publish(self, ann_t, canary, lp):
162         try:
163             self._publish(ann_t, canary, lp)
164         except:
165             log.err(format="Introducer.remote_publish failed on %(ann)s",
166                     ann=ann_t,
167                     level=log.UNUSUAL, parent=lp, umid="620rWA")
168             raise
169
170     def _publish(self, ann_t, canary, lp):
171         self._debug_counts["inbound_message"] += 1
172         self.log("introducer: announcement published: %s" % (ann_t,),
173                  umid="wKHgCw")
174         ann, key = unsign_from_foolscap(ann_t) # might raise BadSignatureError
175         index = make_index(ann, key)
176
177         service_name = str(ann["service-name"])
178         if service_name == "stub_client": # for_v1
179             self._attach_stub_client(ann, lp)
180             return
181
182         old = self._announcements.get(index)
183         if old:
184             (old_ann_t, canary, old_ann, timestamp) = old
185             if old_ann == ann:
186                 self.log("but we already knew it, ignoring", level=log.NOISY,
187                          umid="myxzLw")
188                 self._debug_counts["inbound_duplicate"] += 1
189                 return
190             else:
191                 self.log("old announcement being updated", level=log.NOISY,
192                          umid="304r9g")
193                 self._debug_counts["inbound_update"] += 1
194         self._announcements[index] = (ann_t, canary, ann, time.time())
195         #if canary:
196         #    canary.notifyOnDisconnect ...
197         # use a CanaryWatcher? with cw.is_connected()?
198         # actually we just want foolscap to give rref.is_connected(), since
199         # this is only for the status display
200
201         for s in self._subscribers.get(service_name, []):
202             self._debug_counts["outbound_message"] += 1
203             self._debug_counts["outbound_announcements"] += 1
204             self._debug_outstanding += 1
205             d = s.callRemote("announce_v2", set([ann_t]))
206             d.addBoth(self._debug_retired)
207             d.addErrback(log.err,
208                          format="subscriber errored on announcement %(ann)s",
209                          ann=ann_t, facility="tahoe.introducer",
210                          level=log.UNUSUAL, umid="jfGMXQ")
211
212     def _attach_stub_client(self, ann, lp):
213         # There might be a v1 subscriber for whom this is a stub_client.
214         # We might have received the subscription before the stub_client
215         # announcement, in which case we now need to fix up the record in
216         # self._subscriptions .
217
218         # record it for later, in case the stub_client arrived before the
219         # subscription
220         subscriber_info = self._get_subscriber_info_from_ann(ann)
221         ann_tubid = get_tubid_string_from_ann(ann)
222         self._stub_client_announcements[ann_tubid] = subscriber_info
223
224         lp2 = self.log("stub_client announcement, "
225                        "looking for matching subscriber",
226                        parent=lp, level=log.NOISY, umid="BTywDg")
227
228         for sn in self._subscribers:
229             s = self._subscribers[sn]
230             for (subscriber, info) in s.items():
231                 # we correlate these by looking for a subscriber whose tubid
232                 # matches this announcement
233                 sub_tubid = subscriber.getRemoteTubID()
234                 if sub_tubid == ann_tubid:
235                     self.log(format="found a match, nodeid=%(nodeid)s",
236                              nodeid=sub_tubid,
237                              level=log.NOISY, parent=lp2, umid="xsWs1A")
238                     # found a match. Does it need info?
239                     if not info[0]:
240                         self.log(format="replacing info",
241                                  level=log.NOISY, parent=lp2, umid="m5kxwA")
242                         # yup
243                         s[subscriber] = (subscriber_info, info[1])
244             # and we don't remember or announce stub_clients beyond what we
245             # need to get the subscriber_info set up
246
247     def _get_subscriber_info_from_ann(self, ann): # for_v1
248         sinfo = { "version": ann["version"],
249                   "nickname": ann["nickname"],
250                   "app-versions": ann["app-versions"],
251                   "my-version": ann["my-version"],
252                   "oldest-supported": ann["oldest-supported"],
253                   }
254         return sinfo
255
256     def remote_subscribe(self, subscriber, service_name): # for_v1
257         self.log("introducer: old (v1) subscription[%s] request at %s"
258                  % (service_name, subscriber), umid="hJlGUg")
259         return self.add_subscriber(WrapV1SubscriberInV2Interface(subscriber),
260                                    service_name, None)
261
262     def remote_subscribe_v2(self, subscriber, service_name, subscriber_info):
263         self.log("introducer: subscription[%s] request at %s"
264                  % (service_name, subscriber), umid="U3uzLg")
265         return self.add_subscriber(subscriber, service_name, subscriber_info)
266
267     def add_subscriber(self, subscriber, service_name, subscriber_info):
268         self._debug_counts["inbound_subscribe"] += 1
269         if service_name not in self._subscribers:
270             self._subscribers[service_name] = {}
271         subscribers = self._subscribers[service_name]
272         if subscriber in subscribers:
273             self.log("but they're already subscribed, ignoring",
274                      level=log.UNUSUAL, umid="Sy9EfA")
275             return
276
277         if not subscriber_info: # for_v1
278             # v1 clients don't provide subscriber_info, but they should
279             # publish a 'stub client' record which contains the same
280             # information. If we've already received this, it will be in
281             # self._stub_client_announcements
282             tubid = subscriber.getRemoteTubID()
283             if tubid in self._stub_client_announcements:
284                 subscriber_info = self._stub_client_announcements[tubid]
285
286         subscribers[subscriber] = (subscriber_info, time.time())
287         def _remove():
288             self.log("introducer: unsubscribing[%s] %s" % (service_name,
289                                                            subscriber),
290                      umid="vYGcJg")
291             subscribers.pop(subscriber, None)
292         subscriber.notifyOnDisconnect(_remove)
293
294         # now tell them about any announcements they're interested in
295         announcements = set( [ ann_t
296                                for idx,(ann_t,canary,ann,when)
297                                in self._announcements.items()
298                                if idx[0] == service_name] )
299         if announcements:
300             self._debug_counts["outbound_message"] += 1
301             self._debug_counts["outbound_announcements"] += len(announcements)
302             self._debug_outstanding += 1
303             d = subscriber.callRemote("announce_v2", announcements)
304             d.addBoth(self._debug_retired)
305             d.addErrback(log.err,
306                          format="subscriber errored during subscribe %(anns)s",
307                          anns=announcements, facility="tahoe.introducer",
308                          level=log.UNUSUAL, umid="mtZepQ")
309             return d