summaryrefslogtreecommitdiff
path: root/tests/unittests/sources/test_vultr.py
blob: 488df4f34e7d39896a0951b24765967e35ce17c2 (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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
# Author: Eric Benner <ebenner@vultr.com>
#
# This file is part of cloud-init. See LICENSE file for license information.

# Vultr Metadata API:
# https://www.vultr.com/metadata/

import json

from cloudinit import helpers, settings
from cloudinit.net.dhcp import NoDHCPLeaseError
from cloudinit.sources import DataSourceVultr
from cloudinit.sources.helpers import vultr
from tests.unittests.helpers import CiTestCase, mock

# Vultr metadata test data
VULTR_V1_1 = {
    "bgp": {
        "ipv4": {
            "my-address": "",
            "my-asn": "",
            "peer-address": "",
            "peer-asn": "",
        },
        "ipv6": {
            "my-address": "",
            "my-asn": "",
            "peer-address": "",
            "peer-asn": "",
        },
    },
    "hostname": "CLOUDINIT_1",
    "local-hostname": "CLOUDINIT_1",
    "instance-v2-id": "29bea708-2e6e-480a-90ad-0e6b5d5ad62f",
    "instance-id": "29bea708-2e6e-480a-90ad-0e6b5d5ad62f",
    "instanceid": "42506325",
    "interfaces": [
        {
            "ipv4": {
                "additional": [],
                "address": "108.61.89.242",
                "gateway": "108.61.89.1",
                "netmask": "255.255.255.0",
            },
            "ipv6": {
                "additional": [],
                "address": "2001:19f0:5:56c2:5400:03ff:fe15:c465",
                "network": "2001:19f0:5:56c2::",
                "prefix": "64",
            },
            "mac": "56:00:03:15:c4:65",
            "network-type": "public",
        }
    ],
    "public-keys": ["ssh-rsa AAAAB3NzaC1y...IQQhv5PAOKaIl+mM3c= test3@key"],
    "region": "us",
    "user-defined": [],
    "startup-script": "echo No configured startup script",
    "raid1-script": "",
    "user-data": [],
    "vendor-data": [
        {
            "package_upgrade": "true",
            "disable_root": 0,
            "ssh_pwauth": 1,
            "chpasswd": {
                "expire": False,
                "list": ["root:$6$S2Smuj.../VqxmIR9Urw0jPZ88i4yvB/"],
            },
            "system_info": {"default_user": {"name": "root"}},
        }
    ],
}

VULTR_V1_2 = {
    "bgp": {
        "ipv4": {
            "my-address": "",
            "my-asn": "",
            "peer-address": "",
            "peer-asn": "",
        },
        "ipv6": {
            "my-address": "",
            "my-asn": "",
            "peer-address": "",
            "peer-asn": "",
        },
    },
    "hostname": "CLOUDINIT_2",
    "local-hostname": "CLOUDINIT_2",
    "instance-v2-id": "29bea708-2e6e-480a-90ad-0e6b5d5ad62f",
    "instance-id": "29bea708-2e6e-480a-90ad-0e6b5d5ad62f",
    "instanceid": "42872224",
    "interfaces": [
        {
            "ipv4": {
                "additional": [],
                "address": "45.76.7.171",
                "gateway": "45.76.6.1",
                "netmask": "255.255.254.0",
            },
            "ipv6": {
                "additional": [
                    {"network": "2002:19f0:5:28a7::", "prefix": "64"}
                ],
                "address": "2001:19f0:5:28a7:5400:03ff:fe1b:4eca",
                "network": "2001:19f0:5:28a7::",
                "prefix": "64",
            },
            "mac": "56:00:03:1b:4e:ca",
            "network-type": "public",
        },
        {
            "ipv4": {
                "additional": [],
                "address": "10.1.112.3",
                "gateway": "",
                "netmask": "255.255.240.0",
            },
            "ipv6": {"additional": [], "network": "", "prefix": ""},
            "mac": "5a:00:03:1b:4e:ca",
            "network-type": "private",
            "network-v2-id": "fbbe2b5b-b986-4396-87f5-7246660ccb64",
            "networkid": "net5e7155329d730",
        },
    ],
    "public-keys": ["ssh-rsa AAAAB3NzaC1y...IQQhv5PAOKaIl+mM3c= test3@key"],
    "region": "us",
    "user-defined": [],
    "startup-script": "echo No configured startup script",
    "user-data": [],
    "vendor-data": [
        {
            "package_upgrade": "true",
            "disable_root": 0,
            "ssh_pwauth": 1,
            "chpasswd": {
                "expire": False,
                "list": ["root:$6$SxXx...k2mJNIzZB5vMCDBlYT1"],
            },
            "system_info": {"default_user": {"name": "root"}},
        }
    ],
}

VULTR_V1_3 = None

SSH_KEYS_1 = ["ssh-rsa AAAAB3NzaC1y...IQQhv5PAOKaIl+mM3c= test3@key"]

CLOUD_INTERFACES = {
    "version": 1,
    "config": [
        {
            "type": "nameserver",
            "address": ["108.61.10.10", "2001:19f0:300:1704::6"],
        },
        {
            "type": "physical",
            "mac_address": "56:00:03:1b:4e:ca",
            "accept-ra": 1,
            "subnets": [
                {"type": "dhcp", "control": "auto"},
                {"type": "ipv6_slaac", "control": "auto"},
                {
                    "type": "static6",
                    "control": "auto",
                    "address": "2002:19f0:5:28a7::/64",
                },
            ],
        },
        {
            "type": "physical",
            "mac_address": "5a:00:03:1b:4e:ca",
            "subnets": [
                {
                    "type": "static",
                    "control": "auto",
                    "address": "10.1.112.3",
                    "netmask": "255.255.240.0",
                }
            ],
        },
    ],
}

INTERFACES = ["lo", "dummy0", "eth1", "eth0", "eth2"]

ORDERED_INTERFACES = ["eth0", "eth1", "eth2"]

FILTERED_INTERFACES = ["eth1", "eth2", "eth0"]

# Expected generated objects

# Expected config
EXPECTED_VULTR_CONFIG = {
    "package_upgrade": "true",
    "disable_root": 0,
    "ssh_pwauth": 1,
    "chpasswd": {
        "expire": False,
        "list": ["root:$6$SxXx...k2mJNIzZB5vMCDBlYT1"],
    },
    "system_info": {"default_user": {"name": "root"}},
}

# Expected network config object from generator
EXPECTED_VULTR_NETWORK_1 = {
    "version": 1,
    "config": [
        {
            "type": "nameserver",
            "address": ["108.61.10.10", "2001:19f0:300:1704::6"],
        },
        {
            "name": "eth0",
            "type": "physical",
            "mac_address": "56:00:03:15:c4:65",
            "accept-ra": 1,
            "subnets": [
                {"type": "dhcp", "control": "auto"},
                {"type": "ipv6_slaac", "control": "auto"},
            ],
        },
    ],
}

EXPECTED_VULTR_NETWORK_2 = {
    "version": 1,
    "config": [
        {
            "type": "nameserver",
            "address": ["108.61.10.10", "2001:19f0:300:1704::6"],
        },
        {
            "name": "eth0",
            "type": "physical",
            "mac_address": "56:00:03:1b:4e:ca",
            "accept-ra": 1,
            "subnets": [
                {"type": "dhcp", "control": "auto"},
                {"type": "ipv6_slaac", "control": "auto"},
                {
                    "type": "static6",
                    "control": "auto",
                    "address": "2002:19f0:5:28a7::/64",
                },
            ],
        },
        {
            "name": "eth1",
            "type": "physical",
            "mac_address": "5a:00:03:1b:4e:ca",
            "subnets": [
                {
                    "type": "static",
                    "control": "auto",
                    "address": "10.1.112.3",
                    "netmask": "255.255.240.0",
                }
            ],
        },
    ],
}


INTERFACE_MAP = {
    "56:00:03:15:c4:65": "eth0",
    "56:00:03:1b:4e:ca": "eth0",
    "5a:00:03:1b:4e:ca": "eth1",
}


FINAL_INTERFACE_USED = ""


# Static override, pylint doesnt like this in
# classes without self
def check_route(url):
    if FINAL_INTERFACE_USED == "eth0":
        return True
    return False


class TestDataSourceVultr(CiTestCase):
    def setUp(self):
        global VULTR_V1_3
        super(TestDataSourceVultr, self).setUp()

        # Create v3
        VULTR_V1_3 = VULTR_V1_2.copy()
        VULTR_V1_3["cloud_interfaces"] = CLOUD_INTERFACES.copy()
        VULTR_V1_3["interfaces"] = []

        # Stored as a dict to make it easier to maintain
        raw1 = json.dumps(VULTR_V1_1["vendor-data"][0])
        raw2 = json.dumps(VULTR_V1_2["vendor-data"][0])

        # Make expected format
        VULTR_V1_1["vendor-data"] = [raw1]
        VULTR_V1_2["vendor-data"] = [raw2]
        VULTR_V1_3["vendor-data"] = [raw2]

        self.tmp = self.tmp_dir()

    # Test the datasource itself
    @mock.patch("cloudinit.net.get_interfaces_by_mac")
    @mock.patch("cloudinit.sources.helpers.vultr.is_vultr")
    @mock.patch("cloudinit.sources.helpers.vultr.get_metadata")
    def test_datasource(self, mock_getmeta, mock_isvultr, mock_netmap):
        mock_getmeta.return_value = VULTR_V1_2
        mock_isvultr.return_value = True
        mock_netmap.return_value = INTERFACE_MAP

        distro = mock.MagicMock()
        distro.get_tmp_exec_path = self.tmp_dir
        source = DataSourceVultr.DataSourceVultr(
            settings.CFG_BUILTIN, distro, helpers.Paths({"run_dir": self.tmp})
        )

        # Test for failure
        self.assertEqual(True, source._get_data())

        # Test instance id
        self.assertEqual("42872224", source.metadata["instanceid"])

        # Test hostname
        self.assertEqual("CLOUDINIT_2", source.metadata["local-hostname"])

        # Test ssh keys
        self.assertEqual(SSH_KEYS_1, source.metadata["public-keys"])

        # Test vendor data generation
        orig_val = self.maxDiff
        self.maxDiff = None

        vendordata = source.vendordata_raw

        # Test vendor config
        self.assertEqual(
            EXPECTED_VULTR_CONFIG,
            json.loads(vendordata[0].replace("#cloud-config", "")),
        )

        self.maxDiff = orig_val

        # Test network config generation
        self.assertEqual(EXPECTED_VULTR_NETWORK_2, source.network_config)

    # Test the datasource with new network config type
    @mock.patch("cloudinit.net.get_interfaces_by_mac")
    @mock.patch("cloudinit.sources.helpers.vultr.is_vultr")
    @mock.patch("cloudinit.sources.helpers.vultr.get_metadata")
    def test_datasource_cloud_interfaces(
        self, mock_getmeta, mock_isvultr, mock_netmap
    ):
        mock_getmeta.return_value = VULTR_V1_3
        mock_isvultr.return_value = True
        mock_netmap.return_value = INTERFACE_MAP

        distro = mock.MagicMock()
        distro.get_tmp_exec_path = self.tmp_dir
        source = DataSourceVultr.DataSourceVultr(
            settings.CFG_BUILTIN, distro, helpers.Paths({"run_dir": self.tmp})
        )

        source._get_data()

        # Test network config generation
        self.assertEqual(EXPECTED_VULTR_NETWORK_2, source.network_config)

    # Test network config generation
    @mock.patch("cloudinit.net.get_interfaces_by_mac")
    def test_network_config(self, mock_netmap):
        mock_netmap.return_value = INTERFACE_MAP
        interf = VULTR_V1_1["interfaces"]

        self.assertEqual(
            EXPECTED_VULTR_NETWORK_1, vultr.generate_network_config(interf)
        )

    # Test Private Networking config generation
    @mock.patch("cloudinit.net.get_interfaces_by_mac")
    def test_private_network_config(self, mock_netmap):
        mock_netmap.return_value = INTERFACE_MAP
        interf = VULTR_V1_2["interfaces"].copy()

        # Test configuring
        self.assertEqual(
            EXPECTED_VULTR_NETWORK_2, vultr.generate_network_config(interf)
        )

        # Test unconfigured
        interf[1]["unconfigured"] = True
        expected = EXPECTED_VULTR_NETWORK_2.copy()
        expected["config"].pop(2)
        self.assertEqual(expected, vultr.generate_network_config(interf))

    # Override ephemeral for proper unit testing
    def ephemeral_init(
        self, iface="", connectivity_url_data=None, tmp_dir=None
    ):
        global FINAL_INTERFACE_USED
        FINAL_INTERFACE_USED = iface
        if iface == "eth0":
            return
        raise NoDHCPLeaseError("Generic for testing")

    # Override ephemeral for proper unit testing
    def ephemeral_init_always(
        self, iface="", connectivity_url_data=None, tmp_dir=None
    ):
        global FINAL_INTERFACE_USED
        FINAL_INTERFACE_USED = iface

    # Override ephemeral for proper unit testing
    def override_enter(self):
        return

    # Override ephemeral for proper unit testing
    def override_exit(self, excp_type, excp_value, excp_traceback):
        return

    # Test interface seeking to ensure we are able to find the correct one
    @mock.patch(
        "cloudinit.net.ephemeral.EphemeralDHCPv4.__init__", ephemeral_init
    )
    @mock.patch(
        "cloudinit.net.ephemeral.EphemeralDHCPv4.__enter__", override_enter
    )
    @mock.patch(
        "cloudinit.net.ephemeral.EphemeralDHCPv4.__exit__", override_exit
    )
    @mock.patch("cloudinit.sources.helpers.vultr.check_route")
    @mock.patch("cloudinit.sources.helpers.vultr.is_vultr")
    @mock.patch("cloudinit.sources.helpers.vultr.read_metadata")
    @mock.patch("cloudinit.sources.helpers.vultr.get_interface_list")
    def test_interface_seek(
        self,
        mock_interface_list,
        mock_read_metadata,
        mock_isvultr,
        mock_check_route,
    ):
        mock_read_metadata.return_value = {}
        mock_isvultr.return_value = True
        mock_interface_list.return_value = FILTERED_INTERFACES
        mock_check_route.return_value = True

        distro = mock.MagicMock()
        distro.get_tmp_exec_path = self.tmp_dir
        source = DataSourceVultr.DataSourceVultr(
            settings.CFG_BUILTIN, distro, helpers.Paths({"run_dir": self.tmp})
        )

        try:
            source._get_data()
        except Exception:
            pass

        self.assertEqual(FINAL_INTERFACE_USED, INTERFACES[3])

    # Test route checking sucessful DHCPs
    @mock.patch("cloudinit.sources.helpers.vultr.check_route", check_route)
    @mock.patch(
        "cloudinit.net.ephemeral.EphemeralDHCPv4.__init__",
        ephemeral_init_always,
    )
    @mock.patch(
        "cloudinit.net.ephemeral.EphemeralDHCPv4.__enter__", override_enter
    )
    @mock.patch(
        "cloudinit.net.ephemeral.EphemeralDHCPv4.__exit__", override_exit
    )
    @mock.patch("cloudinit.sources.helpers.vultr.get_interface_list")
    @mock.patch("cloudinit.sources.helpers.vultr.is_vultr")
    @mock.patch("cloudinit.sources.helpers.vultr.read_metadata")
    def test_interface_seek_route_check(
        self, mock_read_metadata, mock_isvultr, mock_interface_list
    ):
        mock_read_metadata.return_value = {}
        mock_interface_list.return_value = FILTERED_INTERFACES
        mock_isvultr.return_value = True

        source = DataSourceVultr.DataSourceVultr(
            settings.CFG_BUILTIN, None, helpers.Paths({"run_dir": self.tmp})
        )

        try:
            source._get_data()
        except Exception:
            pass

        self.assertEqual(FINAL_INTERFACE_USED, INTERFACES[3])


# vi: ts=4 expandtab