blob: b2a1687ed4b041218202b677fc6f8a4e86018442 [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
gecong19734f173f32016-10-16 09:27:14 +080034 def __ne__(self, other):
35 return not self.__eq__(other)
36
sonu.kumarc8f7a702016-04-29 21:07:16 +090037 @classmethod
38 def from_text(cls, text):
39 """Return a ZoneFile from a string containing the zone file contents"""
40 # filter out empty lines and strip all leading/trailing whitespace.
41 # this assumes no multiline records
42 lines = [x.strip() for x in text.split('\n') if x.strip()]
43
44 assert lines[0].startswith('$ORIGIN')
45 assert lines[1].startswith('$TTL')
46
47 return ZoneFile(
48 origin=lines[0].split(' ')[1],
49 ttl=int(lines[1].split(' ')[1]),
50 records=[ZoneFileRecord.from_text(x) for x in lines[2:]],
51 )
52
53
54class ZoneFileRecord(object):
55
56 def __init__(self, name, type, data):
57 self.name = str(name)
58 self.type = str(type)
59 self.data = str(data)
60
61 def __str__(self):
62 return str(self.__dict__)
63
64 def __repr__(self):
65 return str(self)
66
67 def __eq__(self, other):
68 return self.__dict__ == other.__dict__
69
gecong19734f173f32016-10-16 09:27:14 +080070 def __ne__(self, other):
71 return not self.__eq__(other)
72
sonu.kumarc8f7a702016-04-29 21:07:16 +090073 def __hash__(self):
74 return hash(tuple(sorted(self.__dict__.items())))
75
76 @classmethod
77 def from_text(cls, text):
78 """Create a ZoneFileRecord from a line of text of a zone file, like:
79
80 mydomain.com. IN NS ns1.example.com.
81 """
82 # assumes records don't have a TTL between the name and the class.
83 # assumes no parentheses in the record, all on a single line.
84 parts = [x for x in text.split(' ', 4) if x.strip()]
85 name, rclass, rtype, data = parts
86 assert rclass == 'IN'
87 return cls(name=name, type=rtype, data=data)