blob: e69bd09e312b3f85657872e8c18efab976232c37 [file] [log] [blame]
sonu.kumarc8f7a702016-04-29 21:07:16 +09001"""
2Copyright 2015 Rackspace
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15"""
16
17
18class ZoneFile(object):
19
20 def __init__(self, origin, ttl, records):
21 self.origin = origin
22 self.ttl = ttl
23 self.records = records
24
25 def __str__(self):
26 return str(self.__dict__)
27
28 def __repr__(self):
29 return str(self)
30
31 def __eq__(self, other):
32 return self.__dict__ == other.__dict__
33
34 @classmethod
35 def from_text(cls, text):
36 """Return a ZoneFile from a string containing the zone file contents"""
37 # filter out empty lines and strip all leading/trailing whitespace.
38 # this assumes no multiline records
39 lines = [x.strip() for x in text.split('\n') if x.strip()]
40
41 assert lines[0].startswith('$ORIGIN')
42 assert lines[1].startswith('$TTL')
43
44 return ZoneFile(
45 origin=lines[0].split(' ')[1],
46 ttl=int(lines[1].split(' ')[1]),
47 records=[ZoneFileRecord.from_text(x) for x in lines[2:]],
48 )
49
50
51class ZoneFileRecord(object):
52
53 def __init__(self, name, type, data):
54 self.name = str(name)
55 self.type = str(type)
56 self.data = str(data)
57
58 def __str__(self):
59 return str(self.__dict__)
60
61 def __repr__(self):
62 return str(self)
63
64 def __eq__(self, other):
65 return self.__dict__ == other.__dict__
66
67 def __hash__(self):
68 return hash(tuple(sorted(self.__dict__.items())))
69
70 @classmethod
71 def from_text(cls, text):
72 """Create a ZoneFileRecord from a line of text of a zone file, like:
73
74 mydomain.com. IN NS ns1.example.com.
75 """
76 # assumes records don't have a TTL between the name and the class.
77 # assumes no parentheses in the record, all on a single line.
78 parts = [x for x in text.split(' ', 4) if x.strip()]
79 name, rclass, rtype, data = parts
80 assert rclass == 'IN'
81 return cls(name=name, type=rtype, data=data)