summaryrefslogtreecommitdiff
path: root/designate/backend/impl_bind9.py
blob: 060c8f9c8f4f6504123f541c1dd54065657d77bc (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
# Copyright 2014 eBay Inc.
#
# Author: Ron Rickard <rrickard@ebay.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.

"""
Bind 9 backend. Create and delete zones by executing rndc
"""

import random

import subprocess

from oslo_log import log as logging
from oslo_utils import strutils

from designate import exceptions
from designate import utils
from designate.backend import base
from designate.conf.mdns import DEFAULT_MDNS_PORT

LOG = logging.getLogger(__name__)
DEFAULT_MASTER_PORT = DEFAULT_MDNS_PORT


class Bind9Backend(base.Backend):
    __plugin_name__ = 'bind9'

    __backend_status__ = 'integrated'

    def __init__(self, target):
        super(Bind9Backend, self).__init__(target)

        self._host = self.options.get('host', '127.0.0.1')
        self._port = int(self.options.get('port', 53))
        self._view = self.options.get('view')

        # Removes zone files when a zone is deleted.
        # This option will take effect on bind>=9.10.0.
        self._clean_zonefile = strutils.bool_from_string(
                                  self.options.get('clean_zonefile', 'false'))

        self._rndc_call_base = self._generate_rndc_base_call()
        self._rndc_timeout = self.options.get('rndc_timeout', None)
        if self._rndc_timeout == 0:
            self._rndc_timeout = None

    def _generate_rndc_base_call(self):
        """Generate argument list to execute rndc"""
        rndc_host = self.options.get('rndc_host', '127.0.0.1')
        rndc_port = int(self.options.get('rndc_port', 953))
        rndc_bin_path = self.options.get('rndc_bin_path', 'rndc')
        rndc_config_file = self.options.get('rndc_config_file')
        rndc_key_file = self.options.get('rndc_key_file')
        rndc_call = [rndc_bin_path, '-s', rndc_host, '-p', str(rndc_port)]

        if rndc_config_file:
            rndc_call.extend(['-c', rndc_config_file])

        if rndc_key_file:
            rndc_call.extend(['-k', rndc_key_file])

        return rndc_call

    def create_zone(self, context, zone):
        """Create a new Zone by executin rndc, then notify mDNS
        Do not raise exceptions if the zone already exists.
        """
        LOG.debug('Create Zone')
        masters = []
        for master in self.masters:
            host = master['host']
            port = master['port']
            masters.append('%s port %s' % (host, port))

        # Ensure different MiniDNS instances are targeted for AXFRs
        random.shuffle(masters)

        view = 'in %s' % self._view if self._view else ''

        rndc_op = [
            'addzone',
            '%s %s { type slave; masters { %s;}; file "slave.%s%s"; };' %
            (zone['name'].rstrip('.'), view, '; '.join(masters), zone['name'],
             zone['id']),
        ]

        try:
            self._execute_rndc(rndc_op)
        except exceptions.Backend as e:
            # If create fails because the zone exists, don't reraise
            if "already exists" not in str(e):
                LOG.warning('RNDC call failure: %s', e)
                raise

        self.mdns_api.notify_zone_changed(
            context, zone, self._host, self._port, self.timeout,
            self.retry_interval, self.max_retries, self.delay)

    def get_zone(self, context, zone):
        """Returns True if zone exists and False if not"""
        LOG.debug('Get Zone')

        view = 'in %s' % self._view if self._view else ''

        rndc_op = [
            'showzone',
            '%s %s' % (zone['name'].rstrip('.'), view),
        ]
        try:
            self._execute_rndc(rndc_op)
        except exceptions.Backend as e:
            if "not found" in str(e):
                LOG.debug('Zone %s not found on the backend', zone['name'])
                return False
            else:
                LOG.warning('RNDC call failure: %s', e)
                raise e

        return True

    def delete_zone(self, context, zone):
        """Delete a new Zone by executin rndc
        Do not raise exceptions if the zone does not exist.
        """
        LOG.debug('Delete Zone')

        view = 'in %s' % self._view if self._view else ''

        rndc_op = [
            'delzone',
            '%s %s' % (zone['name'].rstrip('.'), view),
        ]
        if self._clean_zonefile:
            rndc_op.insert(1, '-clean')

        try:
            self._execute_rndc(rndc_op)
        except exceptions.Backend as e:
            # If zone is already deleted, don't reraise
            if "not found" not in str(e):
                LOG.warning('RNDC call failure: %s', e)
                raise

    def update_zone(self, context, zone):
        """
        Update a DNS zone.

        This will execute a rndc modzone if the zone
        already exists but masters might need to be refreshed.
        Or, will create the zone if it does not exist.

        :param context: Security context information.
        :param zone: the DNS zone.
        """
        LOG.debug('Update Zone')

        if not self.get_zone(context, zone):
            # If zone does not exist yet, create it
            self.create_zone(context, zone)
            # Newly created zone won't require an update
            return

        masters = []
        for master in self.masters:
            host = master['host']
            port = master['port']
            masters.append('%s port %s' % (host, port))

        # Ensure different MiniDNS instances are targeted for AXFRs
        random.shuffle(masters)

        view = 'in %s' % self._view if self._view else ''

        rndc_op = [
            'modzone',
            '%s %s { type slave; masters { %s;}; file "slave.%s%s"; };' %
            (zone['name'].rstrip('.'), view, '; '.join(masters), zone['name'],
             zone['id']),
        ]

        try:
            self._execute_rndc(rndc_op)
        except exceptions.Backend as e:
            LOG.warning("Error updating zone: %s", e)
            pass
        super().update_zone(context, zone)

    def _execute_rndc(self, rndc_op):
        """Execute rndc

        :param rndc_op: rndc arguments
        :type rndc_op: list
        :returns: None
        :raises: exceptions.Backend
        """
        try:
            rndc_call = self._rndc_call_base + rndc_op
            LOG.debug('Executing RNDC call: %r with timeout %s',
                rndc_call, self._rndc_timeout)
            utils.execute(*rndc_call, timeout=self._rndc_timeout)
        except (utils.processutils.ProcessExecutionError,
                subprocess.TimeoutExpired) as e:
            raise exceptions.Backend(e)