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 def _lookup(self, name, cls, type, timeout = None):
31 value = self._lookup_unsafe(name, cls, type, timeout = None)
32 except (psycopg2.OperationalError, sqlalchemy.exceptions.SQLError):
35 print "Reloading database"
41 def _lookup_unsafe(self, name, cls, type, timeout):
42 sipb_xen_database.clear_cache()
43 if name.lower() in self.domains:
46 for domain in self.domains:
47 if name.lower().endswith('.'+domain):
50 return defer.fail(failure.Failure(dns.DomainError(name)))
52 if cls == dns.IN and type in (dns.A, dns.ALL_RECORDS):
53 host = name[:-len(domain)-1]
56 record = dns.Record_CNAME('sipb-xen-dev.mit.edu', ttl)
57 results.append(dns.RRHeader(name, dns.CNAME, dns.IN,
58 ttl, record, auth=True))
60 value = sipb_xen_database.Machine.get_by(name=host)
61 if value is None or not value.nics:
62 return defer.fail(failure.Failure(dns.AuthoritativeDomainError(name)))
64 if ip is None: #Deactivated?
65 return defer.fail(failure.Failure(dns.AuthoritativeDomainError(name)))
67 record = dns.Record_A(ip, ttl)
68 results.append(dns.RRHeader(name, dns.A, dns.IN,
69 ttl, record, auth=True))
71 authority.append(dns.RRHeader(domain, dns.SOA, dns.IN, 3600,
73 return defer.succeed((results, authority, []))
75 return defer.fail(failure.Failure(dns.AuthoritativeDomainError(name)))
77 if '__main__' == __name__:
78 resolver = DatabaseAuthority(['servers.csail.mit.edu',
80 'postgres://sipb-xen@sipb-xen-dev/sipb_xen')
83 f = server.DNSServerFactory(authorities=[resolver], verbose=verbosity)
84 p = dns.DNSDatagramProtocol(f)
85 f.noisy = p.noisy = verbosity
87 reactor.listenUDP(53, p)
88 reactor.listenTCP(53, f)