Always return an additional section
[invirt/packages/invirt-dns.git] / code / dnsserver.py
1 #!/usr/bin/python
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
8
9 import sipb_xen_database
10 import psycopg2
11 import sqlalchemy
12 import time
13
14 class DatabaseAuthority(common.ResolverBase):
15     """An Authority that is loaded from a file."""
16
17     soa = None
18
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)
32
33     
34     def _lookup(self, name, cls, type, timeout = None):
35         for i in range(3):
36             try:
37                 value = self._lookup_unsafe(name, cls, type, timeout = None)
38             except (psycopg2.OperationalError, sqlalchemy.exceptions.SQLError):
39                 if i == 2:
40                     raise
41                 print "Reloading database"
42                 time.sleep(0.5)
43                 continue
44             else:
45                 return value
46
47     def _lookup_unsafe(self, name, cls, type, timeout):
48         sipb_xen_database.clear_cache()
49         
50         ttl = 900
51         if name.lower() in self.domains:
52             domain = name.lower()
53         else:
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):
57                     break
58             else: #Not us
59                 return defer.fail(failure.Failure(dns.DomainError(name)))
60         results = []
61         authority = []
62         additional = [self.ns1]
63         authority.append(dns.RRHeader(domain, dns.NS, dns.IN,
64                                       3600, self.ns, auth=True))
65         if cls == dns.IN:
66             if type in (dns.A, dns.ALL_RECORDS):
67                 host = name[:-len(domain)-1]
68                 if not host:
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))
72                 else:
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)))
76                     ip = value.nics[0].ip
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))
82             elif type == dns.NS:
83                 results.append(dns.RRHeader(domain, dns.NS, dns.IN,
84                                             ttl, self.ns, auth=True))
85                 authority = []
86             elif type == dns.SOA:
87                 results.append(dns.RRHeader(domain, dns.SOA, dns.IN,
88                                             ttl, self.soa, auth=True))
89             return defer.succeed((results, authority, additional))
90         else:
91             #Doesn't exist
92             return defer.fail(failure.Failure(dns.AuthoritativeDomainError(name)))
93
94 if '__main__' == __name__:
95     resolver = DatabaseAuthority(['servers.csail.mit.edu',
96                                   'xvm.mit.edu'],
97                                  'postgres://sipb-xen@sipb-xen-dev/sipb_xen')
98
99     verbosity = 0
100     f = server.DNSServerFactory(authorities=[resolver], verbose=verbosity)
101     p = dns.DNSDatagramProtocol(f)
102     f.noisy = p.noisy = verbosity
103     
104     reactor.listenUDP(53, p)
105     reactor.listenTCP(53, f)
106     reactor.run()