~maas-committers/maas/trunk

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
# Copyright 2014-2015 Canonical Ltd.  This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).

"""Tests for the edit_named_options command."""

from __future__ import (
    absolute_import,
    print_function,
    unicode_literals,
    )

str = None

__metaclass__ = type
__all__ = []

from codecs import getwriter
from collections import OrderedDict
from io import BytesIO
import os
import shutil
import textwrap

from django.core.management import call_command
from django.core.management.base import CommandError
from maasserver.management.commands.edit_named_options import (
    Command as command_module,
)
from maasserver.models import Config
from maasserver.testing.factory import factory
from maasserver.testing.testcase import MAASServerTestCase
from maasserver.utils import get_one
from provisioningserver.dns.config import MAAS_NAMED_CONF_OPTIONS_INSIDE_NAME
from provisioningserver.utils.isc import (
    make_isc_string,
    parse_isc_string,
    read_isc_file,
)
from testtools.matchers import (
    Contains,
    Equals,
    FileContains,
    Not,
)


OPTIONS_FILE = textwrap.dedent("""\
    options {
        directory "/var/cache/bind";
        auth-nxdomain no;    # conform to RFC1035
        listen-on-v6 { any; };
    };
""")

OPTIONS_FILE_WITH_DNSSEC = textwrap.dedent("""\
    options {
        directory "/var/cache/bind";
        dnssec-validation auto;
        auth-nxdomain no;    # conform to RFC1035
        listen-on-v6 { any; };
    };
""")

OPTIONS_FILE_WITH_FORWARDERS = textwrap.dedent("""\
    options {
        directory "/var/cache/bind";
        forwarders { 192.168.1.1; 192.168.1.2; };
        auth-nxdomain no;    # conform to RFC1035
        listen-on-v6 { any; };
    };
""")

OPTIONS_FILE_WITH_FORWARDERS_AND_DNSSEC = textwrap.dedent("""\
    options {
        directory "/var/cache/bind";
        forwarders { 192.168.1.1; 192.168.1.2; };
        dnssec-validation no;
        auth-nxdomain no;    # conform to RFC1035
        listen-on-v6 { any; };
    };
""")

OPTIONS_FILE_WITH_EXTRA_AND_DUP_FORWARDER = textwrap.dedent("""\
    options {
        directory "/var/cache/bind";
        forwarders { 192.168.1.2; 192.168.1.3; };
        dnssec-validation no;
        auth-nxdomain no;    # conform to RFC1035
        listen-on-v6 { any; };
    };
""")


class TestEditNamedOptionsCommand(MAASServerTestCase):

    def setUp(self):
        super(TestEditNamedOptionsCommand, self).setUp()
        out = BytesIO()
        self.stdout = getwriter("UTF-8")(out)

    def assertFailsWithMessage(self, config_path, message):
        e = self.assertRaises(
            CommandError,
            call_command, "edit_named_options", config_path=config_path,
            stdout=self.stdout)
        self.assertIn(message, e.message)

    def assertContentFailsWithMessage(self, content, message):
        options_file = self.make_file(contents=content)
        self.assertFailsWithMessage(options_file, message)
        # The original file must be untouched.
        self.assertThat(options_file, FileContains(content))

    def test_exits_when_no_file_to_edit(self):
        dir = self.make_dir()
        absent_file = os.path.join(dir, "foo")
        self.assertFailsWithMessage(absent_file, "does not exist")

    def test_exits_when_file_has_no_options_block(self):
        content = factory.make_string()
        self.assertContentFailsWithMessage(
            content, "Can't find options {} block")

    def test_exits_when_cant_parse_config(self):
        content = "options { forwarders {1.1.1.1} "
        # (missing a closing brace)
        self.assertContentFailsWithMessage(content, "Failed to parse")

    def test_exits_when_fails_to_make_backup(self):
        self.patch(shutil, "copyfile").side_effect = IOError("whatever")
        self.assertContentFailsWithMessage(
            OPTIONS_FILE, "Failed to make a backup")

    def test_does_not_remove_existing_forwarders_config(self):
        options_file = self.make_file(contents=OPTIONS_FILE_WITH_FORWARDERS)
        call_command(
            "edit_named_options", config_path=options_file,
            stdout=self.stdout)

        options = read_isc_file(options_file)
        self.assertThat(make_isc_string(options), Contains('forwarders'))

    def test_removes_existing_forwarders_config_if_migrate_set(self):
        options_file = self.make_file(contents=OPTIONS_FILE_WITH_FORWARDERS)
        call_command(
            "edit_named_options", config_path=options_file,
            migrate_conflicting_options=True, stdout=self.stdout)

        # Check that the file was re-written without forwarders (since
        # that's now in the included file).
        options = read_isc_file(options_file)
        self.assertThat(
            make_isc_string(options),
            Not(Contains('forwarders')))

    def test_removes_existing_dnssec_validation_config(self):
        options_file = self.make_file(contents=OPTIONS_FILE_WITH_DNSSEC)
        call_command(
            "edit_named_options", config_path=options_file,
            stdout=self.stdout)

        # Check that the file was re-written without dnssec-validation (since
        # that's now in the included file).
        options = read_isc_file(options_file)
        self.assertThat(
            make_isc_string(options), Contains('dnssec-validation'))

    def test_removes_existing_dnssec_validation_config_if_migration_set(self):
        options_file = self.make_file(contents=OPTIONS_FILE_WITH_DNSSEC)
        call_command(
            "edit_named_options", config_path=options_file,
            migrate_conflicting_options=True, stdout=self.stdout)

        # Check that the file was re-written without dnssec-validation (since
        # that's now in the included file).
        options = read_isc_file(options_file)
        self.assertThat(
            make_isc_string(options), Not(Contains('dnssec-validation')))

    def test_normal_operation(self):
        options_file = self.make_file(contents=OPTIONS_FILE)
        call_command(
            "edit_named_options", config_path=options_file,
            stdout=self.stdout)
        expected_path = os.path.join(
            os.path.dirname(options_file),
            "maas",
            MAAS_NAMED_CONF_OPTIONS_INSIDE_NAME)

        # Check that the file was re-written with the include statement.
        options = read_isc_file(options_file)
        self.assertThat(
            make_isc_string(options),
            Contains('include "%s";' % expected_path))

        # Check that the backup was made.
        options_file_base = os.path.dirname(options_file)
        files = os.listdir(options_file_base)
        self.assertEqual(2, len(files))
        files.remove(os.path.basename(options_file))
        [backup_file] = files
        backup_file = os.path.join(options_file_base, backup_file)
        self.assertThat(backup_file, FileContains(OPTIONS_FILE))

    def test_migrates_bind_config_to_database(self):
        options_file = self.make_file(
            contents=OPTIONS_FILE_WITH_FORWARDERS_AND_DNSSEC)
        call_command(
            "edit_named_options", config_path=options_file,
            migrate_conflicting_options=True, stdout=self.stdout)

        upstream_dns = get_one(Config.objects.filter(name="upstream_dns"))
        self.assertThat({'192.168.1.1', '192.168.1.2'},
                        Equals(set(upstream_dns.value.split())))

        dnssec_validation = get_one(Config.objects.filter(
            name="dnssec_validation"))
        self.assertThat('no', Equals(dnssec_validation.value))

    def test_migrate_combines_with_existing_forwarders(self):
        options_file = self.make_file(
            contents=OPTIONS_FILE_WITH_FORWARDERS_AND_DNSSEC)
        call_command(
            "edit_named_options", config_path=options_file,
            migrate_conflicting_options=True, stdout=self.stdout)

        upstream_dns = get_one(Config.objects.filter(name="upstream_dns"))
        self.assertThat(OrderedDict.fromkeys(['192.168.1.1', '192.168.1.2']),
                        Equals(OrderedDict.fromkeys(
                            upstream_dns.value.split())))

        dnssec_validation = get_one(Config.objects.filter(
            name="dnssec_validation"))
        self.assertThat('no', Equals(dnssec_validation.value))

        options_file = self.make_file(
            contents=OPTIONS_FILE_WITH_EXTRA_AND_DUP_FORWARDER)

        call_command(
            "edit_named_options", config_path=options_file,
            migrate_conflicting_options=True, stdout=self.stdout)

        upstream_dns = get_one(Config.objects.filter(name="upstream_dns"))
        self.assertThat(
            OrderedDict.fromkeys(
                ['192.168.1.1', '192.168.1.2', '192.168.1.3']),
            Equals(OrderedDict.fromkeys(upstream_dns.value.split())))

    def test_dry_run_migrates_nothing_and_prints_config(self):
        options_file = self.make_file(
            contents=OPTIONS_FILE_WITH_FORWARDERS_AND_DNSSEC)
        call_command(
            "edit_named_options", config_path=options_file,
            migrate_conflicting_options=True, dry_run=True, stdout=self.stdout)

        upstream_dns = get_one(Config.objects.filter(name="upstream_dns"))
        self.assertIsNone(upstream_dns)
        dnssec_validation = get_one(Config.objects.filter(
            name="dnssec_validation"))
        self.assertIsNone(dnssec_validation)

        # Check that a proper configuration was written to stdout.
        config = parse_isc_string(self.stdout.getvalue())
        self.assertIsNotNone(config)

    def test_repeat_migrations_migrate_nothing(self):
        options_file = self.make_file(
            contents=OPTIONS_FILE_WITH_FORWARDERS_AND_DNSSEC)
        backup_mock = self.patch(command_module, "back_up_existing_file")

        call_command(
            "edit_named_options", config_path=options_file,
            migrate_conflicting_options=True, stdout=self.stdout)

        self.assertTrue(backup_mock.called)
        backup_mock.reset_mock()

        write_mock = self.patch(command_module, "write_new_named_conf_options")

        call_command(
            "edit_named_options", config_path=options_file,
            migrate_conflicting_options=True, stdout=self.stdout)

        self.assertFalse(backup_mock.called)
        self.assertFalse(write_mock.called)

    def test_repeat_forced_migrations_write_file_anyway(self):
        options_file = self.make_file(
            contents=OPTIONS_FILE_WITH_FORWARDERS_AND_DNSSEC)
        backup_mock = self.patch(command_module, "back_up_existing_file")

        call_command(
            "edit_named_options", config_path=options_file,
            migrate_conflicting_options=True, stdout=self.stdout)

        self.assertTrue(backup_mock.called)
        backup_mock.reset_mock()

        write_mock = self.patch(command_module, "write_new_named_conf_options")

        call_command(
            "edit_named_options", config_path=options_file,
            migrate_conflicting_options=True, force=True, stdout=self.stdout)

        self.assertTrue(backup_mock.called)
        self.assertTrue(write_mock.called)