summaryrefslogtreecommitdiff
path: root/designate/backend/agent_backend/impl_djbdns.py
blob: f368fd488389dfb370058abf8419e0f6d45b802f (plain)
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
# Copyright 2016 Hewlett Packard Enterprise Development Company LP
#
# Author: Federico Ceratto <federico.ceratto@hpe.com>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

"""
backend.agent_backend.impl_djbdns
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Djbdns DNS agent backend

Create, update, delete zones locally on a Djbdns DNS resolver using the
axfr-get utility.

`Djbdns User documentation <../../admin/backends/djbdns_agent.html>`_

.. WARNING::

    Untested, do not use in production.


Configured in [service:agent:djbdns]

Requires rootwrap (or equivalent sudo privileges) to execute:
    - tcpclient
    - axfr-get
    - tinydns-data

"""

import errno
import glob
import os
import random
import tempfile

import dns
import dns.resolver
from oslo_concurrency import lockutils
from oslo_concurrency.processutils import ProcessExecutionError
from oslo_config import cfg
from oslo_log import log as logging

from designate.backend.agent_backend import base
from designate import exceptions
from designate import utils
from designate.utils import execute

LOG = logging.getLogger(__name__)
CFG_GROUP_NAME = 'backend:agent:djbdns'
# rootwrap requires a command name instead of full path
TCPCLIENT_DEFAULT_PATH = 'tcpclient'
AXFR_GET_DEFAULT_PATH = 'axfr-get'
TINYDNS_DATA_DEFAULT_PATH = 'tinydns-data'

TINYDNS_DATADIR_DEFAULT_PATH = '/var/lib/djbdns'
SOA_QUERY_TIMEOUT = 1


# TODO(Federico) on zone creation and update, agent.handler unnecessarily
# perfors AXFR from MiniDNS to the Agent to populate the `zone` argument
# (needed by the Bind backend)


def filter_exceptions(fn):
    # Let Backend() exceptions pass through, log out every other exception
    # and re-raise it as Backend()
    def wrapper(*a, **kw):
        try:
            return fn(*a, **kw)
        except exceptions.Backend:
            raise
        except Exception as e:
            LOG.error("Unhandled exception %s", e, exc_info=True)
            raise exceptions.Backend(str(e))

    return wrapper


class DjbdnsBackend(base.AgentBackend):
    __plugin_name__ = 'djbdns'
    __backend_status__ = 'experimental'

    def __init__(self, *a, **kw):
        """Configure the backend"""
        super(DjbdnsBackend, self).__init__(*a, **kw)
        conf = cfg.CONF[CFG_GROUP_NAME]

        self._resolver = dns.resolver.Resolver(configure=False)
        self._resolver.timeout = SOA_QUERY_TIMEOUT
        self._resolver.lifetime = SOA_QUERY_TIMEOUT
        self._resolver.nameservers = [conf.query_destination]
        self._masters = [utils.split_host_port(ns)
                         for ns in cfg.CONF['service:agent'].masters]
        LOG.info("Resolvers: %r", self._resolver.nameservers)
        LOG.info("AXFR masters: %r", self._masters)
        if not self._masters:
            raise exceptions.Backend("Missing agent AXFR masters")

        self._tcpclient_cmd_name = conf.tcpclient_cmd_name
        self._axfr_get_cmd_name = conf.axfr_get_cmd_name

        # Directory where data.cdb lives, usually /var/lib/djbdns/root
        tinydns_root_dir = os.path.join(conf.tinydns_datadir, 'root')

        # Usually /var/lib/djbdns/root/data.cdb
        self._tinydns_cdb_filename = os.path.join(tinydns_root_dir, 'data.cdb')
        LOG.info("data.cdb path: %r", self._tinydns_cdb_filename)

        # Where the agent puts the zone datafiles,
        # usually /var/lib/djbdns/datafiles
        self._datafiles_dir = datafiles_dir = os.path.join(
            conf.tinydns_datadir,
            'datafiles')
        self._datafiles_tmp_path_tpl = os.path.join(datafiles_dir, "%s.ztmp")
        self._datafiles_path_tpl = os.path.join(datafiles_dir, "%s.zonedata")
        self._datafiles_path_glob = self._datafiles_path_tpl % '*'

        self._check_dirs(tinydns_root_dir, datafiles_dir)

    @staticmethod
    def _check_dirs(*dirnames):
        """Check if directories are writable
        """
        for dn in dirnames:
            if not os.path.isdir(dn):
                raise exceptions.Backend("Missing directory %s" % dn)
            if not os.access(dn, os.W_OK):
                raise exceptions.Backend("Directory not writable: %s" % dn)

    def start(self):
        """Start the backend"""
        LOG.info("Started djbdns backend")

    def find_zone_serial(self, zone_name):
        """Query the local resolver for a zone
        Times out after SOA_QUERY_TIMEOUT
        """
        LOG.debug("Finding %s", zone_name)
        try:
            rdata = self._resolver.query(
                zone_name, rdtype=dns.rdatatype.SOA)[0]
            return rdata.serial
        except Exception:
            return None

    @staticmethod
    def _concatenate_zone_datafiles(data_fn, path_glob):
        """Concatenate all zone datafiles into 'data'
        """
        with open(data_fn, 'w') as data_f:
            zone_cnt = 0
            for zone_fn in glob.glob(path_glob):
                zone_cnt += 1
                with open(zone_fn) as zf:
                    data_f.write(zf.read())

        LOG.info("Loaded %d zone datafiles.", zone_cnt)

    def _rebuild_data_cdb(self):
        """Rebuild data.cdb file from zone datafiles
        Requires global lock

        On zone creation, axfr-get creates datafiles atomically by doing
        rename. On zone deletion, os.remove deletes the file atomically
        Globbing and reading the datafiles can be done without locking on
        them.
        The data and data.cdb files are written into a unique temp directory
        """

        tmpdir = tempfile.mkdtemp(dir=self._datafiles_dir)
        data_fn = os.path.join(tmpdir, 'data')
        tmp_cdb_fn = os.path.join(tmpdir, 'data.cdb')

        try:
            self._concatenate_zone_datafiles(data_fn,
                                             self._datafiles_path_glob)
            # Generate the data.cdb file
            LOG.info("Updating data.cdb")
            LOG.debug("Convert %s to %s", data_fn, tmp_cdb_fn)
            try:
                out, err = execute(
                    cfg.CONF[CFG_GROUP_NAME].tinydns_data_cmd_name,
                    cwd=tmpdir
                )
            except ProcessExecutionError as e:
                LOG.error("Failed to generate data.cdb")
                LOG.error("Command output: %(out)r Stderr: %(err)r",
                          {
                              'out': e.stdout,
                              'err': e.stderr
                          })
                raise exceptions.Backend("Failed to generate data.cdb")

            LOG.debug("Move %s to %s", tmp_cdb_fn, self._tinydns_cdb_filename)
            try:
                os.rename(tmp_cdb_fn, self._tinydns_cdb_filename)
            except OSError:
                os.remove(tmp_cdb_fn)
                LOG.error("Unable to move data.cdb to %s",
                          self._tinydns_cdb_filename)
                raise exceptions.Backend("Unable to move data.cdb")

        finally:
            try:
                os.remove(data_fn)
            except OSError:
                pass
            try:
                os.removedirs(tmpdir)
            except OSError:
                pass

    def _perform_axfr_from_minidns(self, zone_name):
        """Instruct axfr-get to request an AXFR from MiniDNS.

        :raises: exceptions.Backend on error
        """
        zone_fn = self._datafiles_path_tpl % zone_name
        zone_tmp_fn = self._datafiles_tmp_path_tpl % zone_name

        # Perform AXFR, create or update a zone datafile
        # No need to lock globally here.
        # Axfr-get creates the datafile atomically by doing rename
        mdns_hostname, mdns_port = random.choice(self._masters)
        with lockutils.lock("%s.lock" % zone_name):
            LOG.debug("writing to %s", zone_fn)
            cmd = (
                self._tcpclient_cmd_name,
                mdns_hostname,
                "%d" % mdns_port,
                self._axfr_get_cmd_name,
                zone_name,
                zone_fn,
                zone_tmp_fn
            )

            LOG.debug("Executing AXFR as %r", ' '.join(cmd))
            try:
                out, err = execute(*cmd)
            except ProcessExecutionError as e:
                LOG.error("Error executing AXFR as %r", ' '.join(cmd))
                LOG.error("Command output: %(out)r Stderr: %(err)r",
                          {
                              'out': e.stdout,
                              'err': e.stderr
                          })
                raise exceptions.Backend(str(e))

            finally:
                try:
                    os.remove(zone_tmp_fn)
                except OSError:
                    pass

    @filter_exceptions
    def create_zone(self, zone):
        """Create a new Zone
        Do not raise exceptions if the zone already exists.

        :param zone: zone to be  created
        :type zone: raw pythondns Zone
        :raises: exceptions.Backend on error
        """
        zone_name = zone.origin.to_text(omit_final_dot=True)
        if isinstance(zone_name, bytes):
            zone_name = zone_name.decode('utf-8')
        LOG.debug("Creating %s", zone_name)
        # The zone might be already in place due to a race condition between
        # checking if the zone is there and creating it across different
        # greenlets

        LOG.debug("Triggering initial AXFR from MiniDNS to Djbdns for %s",
                  zone_name)
        self._perform_axfr_from_minidns(zone_name)
        self._rebuild_data_cdb()

    @filter_exceptions
    def update_zone(self, zone):
        """Instruct Djbdns DNS to perform AXFR from MiniDNS

        :param zone: zone to be  created
        :type zone: raw pythondns Zone
        :raises: exceptions.Backend on error
        """
        zone_name = zone.origin.to_text(omit_final_dot=True)
        if isinstance(zone_name, bytes):
            zone_name = zone_name.decode('utf-8')
        LOG.debug("Triggering AXFR from MiniDNS to Djbdns for %s", zone_name)
        self._perform_axfr_from_minidns(zone_name)
        self._rebuild_data_cdb()

    @filter_exceptions
    def delete_zone(self, zone_name):
        """Delete a new Zone
        Do not raise exceptions if the zone does not exist.

        :param zone_name: zone name
        :type zone_name: str
        :raises: exceptions.Backend on error
        """
        zone_name = zone_name.rstrip('.')
        LOG.debug('Deleting Zone: %s', zone_name)
        zone_fn = self._datafiles_path_tpl % zone_name
        try:
            os.remove(zone_fn)
            LOG.debug('Deleted Zone: %s', zone_name)
        except OSError as e:
            if errno.ENOENT == e.errno:
                LOG.info("Zone datafile %s was already deleted", zone_fn)
                return

            raise

        self._rebuild_data_cdb()