2 from twisted.internet import reactor
3 from twisted.names import server
4 from twisted.names import dns
5 from twisted.names import common
6 from twisted.internet import defer
7 from twisted.python import failure
9 import sipb_xen_database
14 class DatabaseAuthority(common.ResolverBase):
15 """An Authority that is loaded from a file."""
19 def __init__(self, domains, database=None):
20 common.ResolverBase.__init__(self)
21 if database is not None:
22 sipb_xen_database.connect(database)
23 self.domains = domains
24 self.soa = dns.Record_SOA(mname='sipb-xen-dev.mit.edu',
25 rname='sipb-xen.mit.edu',
26 serial=1, refresh=3600, retry=900,
27 expire=3600000, minimum=21600, ttl=3600)
28 self.ns = dns.Record_NS(name='ns1.xvm.mit.edu', ttl=3600)
29 record = dns.Record_A(address='18.181.0.62', ttl=3600)
30 self.ns1 = dns.RRHeader('ns1.xvm.mit.edu', dns.A, dns.IN,
31 3600, record, auth=True)
34 def _lookup(self, name, cls, type, timeout = None):
37 value = self._lookup_unsafe(name, cls, type, timeout = None)
38 except (psycopg2.OperationalError, sqlalchemy.exceptions.SQLError):
41 print "Reloading database"
47 def _lookup_unsafe(self, name, cls, type, timeout):
48 sipb_xen_database.clear_cache()
51 if name.lower() in self.domains:
54 # This works because domain will remain bound after breaking out of the loop
55 for domain in self.domains:
56 if name.lower().endswith('.'+domain):
59 return defer.fail(failure.Failure(dns.DomainError(name)))
62 additional = [self.ns1]
63 authority.append(dns.RRHeader(domain, dns.NS, dns.IN,
64 3600, self.ns, auth=True))
66 if type in (dns.A, dns.ALL_RECORDS):
67 host = name[:-len(domain)-1]
69 record = dns.Record_A('18.181.0.62', ttl)
70 results.append(dns.RRHeader(name, dns.A, dns.IN,
71 ttl, record, auth=True))
73 value = sipb_xen_database.Machine.get_by(name=host)
74 if value is None or not value.nics:
75 return defer.fail(failure.Failure(dns.AuthoritativeDomainError(name)))
77 if ip is None: #Deactivated?
78 return defer.fail(failure.Failure(dns.AuthoritativeDomainError(name)))
79 record = dns.Record_A(ip, ttl)
80 results.append(dns.RRHeader(name, dns.A, dns.IN,
81 ttl, record, auth=True))
83 results.append(dns.RRHeader(domain, dns.NS, dns.IN,
84 ttl, self.ns, auth=True))
87 results.append(dns.RRHeader(domain, dns.SOA, dns.IN,
88 ttl, self.soa, auth=True))
89 return defer.succeed((results, authority, additional))
92 return defer.fail(failure.Failure(dns.AuthoritativeDomainError(name)))
94 if '__main__' == __name__:
95 resolver = DatabaseAuthority(['servers.csail.mit.edu',
97 'postgres://sipb-xen@sipb-xen-dev/sipb_xen')
100 f = server.DNSServerFactory(authorities=[resolver], verbose=verbosity)
101 p = dns.DNSDatagramProtocol(f)
102 f.noisy = p.noisy = verbosity
104 reactor.listenUDP(53, p)
105 reactor.listenTCP(53, f)