forked from octodns/octodns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcloudflare.py
300 lines (252 loc) · 9.59 KB
/
cloudflare.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
#
#
#
from __future__ import absolute_import, division, print_function, \
unicode_literals
from collections import defaultdict
from logging import getLogger
from requests import Session
from ..record import Record, Update
from .base import BaseProvider
class CloudflareAuthenticationError(Exception):
def __init__(self, data):
try:
message = data['errors'][0]['message']
except (IndexError, KeyError):
message = 'Authentication error'
super(CloudflareAuthenticationError, self).__init__(message)
class CloudflareProvider(BaseProvider):
'''
Cloudflare DNS provider
cloudflare:
class: octodns.provider.cloudflare.CloudflareProvider
# Your Cloudflare account email address (required)
email: [email protected]
# The api key (required)
token: foo
'''
SUPPORTS_GEO = False
SUPPORTS_PROXY = True
# TODO: support SRV
SUPPORTS = set(('A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'SPF', 'TXT'))
MIN_TTL = 120
TIMEOUT = 15
def __init__(self, id, email, token, *args, **kwargs):
self.log = getLogger('CloudflareProvider[{}]'.format(id))
self.log.debug('__init__: id=%s, email=%s, token=***', id, email)
super(CloudflareProvider, self).__init__(id, *args, **kwargs)
sess = Session()
sess.headers.update({
'X-Auth-Email': email,
'X-Auth-Key': token,
})
self._sess = sess
self._zones = None
self._zone_records = {}
def _request(self, method, path, params=None, data=None):
self.log.debug('_request: method=%s, path=%s', method, path)
url = 'https://api.cloudflare.com/client/v4{}'.format(path)
resp = self._sess.request(method, url, params=params, json=data,
timeout=self.TIMEOUT)
self.log.debug('_request: status=%d', resp.status_code)
if resp.status_code == 403:
raise CloudflareAuthenticationError(resp.json())
elif resp.status_code == 400 and resp.json()['errors'][0]['code'] == 81057:
self.log.debug('_request: message=%s', 'the record already exists')
else:
resp.raise_for_status()
return resp.json()
@property
def zones(self):
if self._zones is None:
page = 1
zones = []
while page:
resp = self._request('GET', '/zones', params={'page': page})
zones += resp['result']
info = resp['result_info']
if info['count'] > 0 and info['count'] == info['per_page']:
page += 1
else:
page = None
self._zones = {'{}.'.format(z['name']): z['id'] for z in zones}
return self._zones
def _data_for_multiple(self, _type, records):
return {
'ttl': records[0]['ttl'],
'type': _type,
'values': [r['content'] for r in records],
}
def _data_for_A(self, _type, records):
return {
'ttl': records[0]['ttl'],
'type': _type,
'proxied': records[0].get('proxied', False),
'values': [r['content'] for r in records],
}
_data_for_AAAA = _data_for_A
_data_for_SPF = _data_for_multiple
def _data_for_TXT(self, _type, records):
return {
'ttl': records[0]['ttl'],
'type': _type,
'values': [r['content'].replace(';', '\;') for r in records],
}
def _data_for_CAA(self, _type, records):
values = []
for r in records:
data = r['data']
values.append(data)
return {
'ttl': records[0]['ttl'],
'type': _type,
'values': values,
}
def _data_for_CNAME(self, _type, records):
only = records[0]
return {
'ttl': only['ttl'],
'type': _type,
'proxied': only.get('proxied', False),
'value': '{}.'.format(only['content'])
}
def _data_for_MX(self, _type, records):
values = []
for r in records:
values.append({
'preference': r['priority'],
'exchange': '{}.'.format(r['content']),
})
return {
'ttl': records[0]['ttl'],
'type': _type,
'values': values,
}
def _data_for_NS(self, _type, records):
return {
'ttl': records[0]['ttl'],
'type': _type,
'values': ['{}.'.format(r['content']) for r in records],
}
def zone_records(self, zone):
if zone.name not in self._zone_records:
zone_id = self.zones.get(zone.name, False)
if not zone_id:
return []
records = []
path = '/zones/{}/dns_records'.format(zone_id)
page = 1
while page:
resp = self._request('GET', path, params={'page': page})
records += resp['result']
info = resp['result_info']
if info['count'] > 0 and info['count'] == info['per_page']:
page += 1
else:
page = None
self._zone_records[zone.name] = records
return self._zone_records[zone.name]
def populate(self, zone, target=False, lenient=False):
self.log.debug('populate: name=%s, target=%s, lenient=%s', zone.name,
target, lenient)
before = len(zone.records)
records = self.zone_records(zone)
if records:
values = defaultdict(lambda: defaultdict(list))
for record in records:
name = zone.hostname_from_fqdn(record['name'])
_type = record['type']
if _type in self.SUPPORTS:
values[name][record['type']].append(record)
for name, types in values.items():
for _type, records in types.items():
data_for = getattr(self, '_data_for_{}'.format(_type))
data = data_for(_type, records)
record = Record.new(zone, name, data, source=self,
lenient=lenient)
zone.add_record(record)
self.log.info('populate: found %s records',
len(zone.records) - before)
def _include_change(self, change):
if isinstance(change, Update):
existing = change.existing.data
new = change.new.data
new['ttl'] = max(1, new['ttl'])
if new == existing:
return False
return True
def _contents_for_multiple(self, record):
for value in record.values:
yield {'content': value}
_contents_for_A = _contents_for_multiple
_contents_for_AAAA = _contents_for_multiple
_contents_for_NS = _contents_for_multiple
_contents_for_SPF = _contents_for_multiple
def _contents_for_CAA(self, record):
for value in record.values:
yield {
'data': {
'flags': value.flags,
'tag': value.tag,
'value': value.value,
}
}
def _contents_for_TXT(self, record):
for value in record.values:
yield {'content': value.replace('\;', ';')}
def _contents_for_CNAME(self, record):
yield {'content': record.value}
def _contents_for_MX(self, record):
for value in record.values:
yield {
'priority': value.preference,
'content': value.exchange
}
def _apply_Create(self, change):
new = change.new
zone_id = self.zones[new.zone.name]
contents_for = getattr(self, '_contents_for_{}'.format(new._type))
path = '/zones/{}/dns_records'.format(zone_id)
name = new.fqdn[:-1]
for content in contents_for(change.new):
content.update({
'name': name,
'type': new._type,
'ttl': max(1, new.ttl),
'proxied': getattr(new, 'proxied', False),
})
self._request('POST', path, data=content)
def _apply_Update(self, change):
# Create the new and delete the old
self._apply_Create(change)
self._apply_Delete(change)
def _apply_Delete(self, change):
existing = change.existing
existing_name = existing.fqdn[:-1]
for record in self.zone_records(existing.zone):
if existing_name == record['name'] and \
existing._type == record['type']:
path = '/zones/{}/dns_records/{}'.format(record['zone_id'],
record['id'])
self._request('DELETE', path)
def _apply(self, plan):
desired = plan.desired
changes = plan.changes
self.log.debug('_apply: zone=%s, len(changes)=%d', desired.name,
len(changes))
name = desired.name
if name not in self.zones:
self.log.debug('_apply: no matching zone, creating')
data = {
'name': name[:-1],
'jump_start': False,
}
resp = self._request('POST', '/zones', data=data)
zone_id = resp['result']['id']
self.zones[name] = zone_id
self._zone_records[name] = {}
for change in changes:
class_name = change.__class__.__name__
getattr(self, '_apply_{}'.format(class_name))(change)
# clear the cache
self._zone_records.pop(name, None)