]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/util/rrefutil.py
a14d15f13fcb835f3afd09fd46030668c77eb871
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / util / rrefutil.py
1
2 from twisted.internet import address
3 from foolscap.api import Violation, RemoteException, DeadReferenceError, \
4      SturdyRef
5
6 def add_version_to_remote_reference(rref, default):
7     """I try to add a .version attribute to the given RemoteReference. I call
8     the remote get_version() method to learn its version. I'll add the
9     default value if the remote side doesn't appear to have a get_version()
10     method."""
11     d = rref.callRemote("get_version")
12     def _got_version(version):
13         rref.version = version
14         return rref
15     def _no_get_version(f):
16         f.trap(Violation, RemoteException)
17         rref.version = default
18         return rref
19     d.addCallbacks(_got_version, _no_get_version)
20     return d
21
22 def trap_and_discard(f, *errorTypes):
23     f.trap(*errorTypes)
24     pass
25
26 def trap_deadref(f):
27     return trap_and_discard(f, DeadReferenceError)
28
29
30 def hosts_for_rref(rref, ignore_localhost=True):
31     # actually, this only returns hostnames
32     advertised = []
33     for hint in rref.getLocationHints():
34         # Foolscap-0.2.5 and earlier used strings in .locationHints, but we
35         # require a newer version that uses tuples of ("ipv4", host, port)
36         assert not isinstance(hint, str), hint
37         if hint[0] == "ipv4":
38             host = hint[1]
39             if ignore_localhost and host == "127.0.0.1":
40                 continue
41             advertised.append(host)
42     return advertised
43
44 def hosts_for_furl(furl, ignore_localhost=True):
45     advertised = []
46     for hint in SturdyRef(furl).locationHints:
47         assert not isinstance(hint, str), hint
48         if hint[0] == "ipv4":
49             host = hint[1]
50             if ignore_localhost and host == "127.0.0.1":
51                 continue
52             advertised.append(host)
53     return advertised
54
55 def stringify_remote_address(rref):
56     remote = rref.getPeer()
57     if isinstance(remote, address.IPv4Address):
58         return "%s:%d" % (remote.host, remote.port)
59     # loopback is a non-IPv4Address
60     return str(remote)