File: test_main.py

package info (click to toggle)
cloud-init 25.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 12,412 kB
  • sloc: python: 135,894; sh: 3,883; makefile: 141; javascript: 30; xml: 22
file content (413 lines) | stat: -rw-r--r-- 13,656 bytes parent folder | download
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
# This file is part of cloud-init. See LICENSE file for license information.

import copy
import getpass
import os
import textwrap
from collections import namedtuple
from unittest import mock

import pytest

from cloudinit import features, safeyaml, util
from cloudinit.cmd import main
from cloudinit.util import ensure_dir, load_text_file, write_file

MyArgs = namedtuple(
    "MyArgs", "debug files force local reporter subcommand skip_log_setup"
)


CLOUD_CONFIG_ARCHIVE = """\
#cloud-config-archive
- type: "text/cloud-boothook"
  content: |
    #!/bin/sh
    echo "this is from a boothook." > /var/tmp/boothook.txt
- type: "text/cloud-config"
  content: |
    bootcmd:
    - echo "this is from a cloud-config." > /var/tmp/bootcmd.txt
"""


EXTRA_CLOUD_CONFIG = """\
#cloud-config
write_files
- path: {tmpdir}/etc/blah.ini
  content: override
"""


class TestMain:
    @pytest.fixture(autouse=True)
    def common_mocks(self, mocker):
        mocker.patch("cloudinit.cmd.main.os.getppid", return_value=42)
        mocker.patch("cloudinit.cmd.main.close_stdin")
        mocker.patch(
            "cloudinit.cmd.main.netinfo.debug_info",
            return_value="my net debug info",
        )
        mocker.patch(
            "cloudinit.cmd.main.util.fixup_output",
            return_value=("outfmt", "errfmt"),
        )
        mocker.patch("cloudinit.cmd.main.util.get_cmdline", return_value="")
        mocker.patch("cloudinit.cmd.main.util.uptime", return_value="12345")
        os.environ["_CLOUD_INIT_SAVE_STDOUT"] = "true"
        yield
        os.environ.pop("_CLOUD_INIT_SAVE_STDOUT")

    @pytest.fixture
    def cloud_cfg(self, mocker, tmpdir, fake_filesystem):
        cloud_dir = os.path.join(tmpdir, "var/lib/cloud/")
        log_dir = os.path.join(tmpdir, "var/log/")
        ensure_dir(cloud_dir)
        ensure_dir(os.path.join(tmpdir, "etc/cloud"))
        ensure_dir(log_dir)
        cloud_cfg_file = os.path.join(tmpdir, "etc/cloud/cloud.cfg")

        cfg = {
            "datasource_list": ["None"],
            # "def_log_file": os.path.join(log_dir, "cloud-init.log"),
            "def_log_file": "",
            "runcmd": ["ls /etc"],  # test ALL_DISTROS
            "system_info": {
                "paths": {
                    "cloud_dir": cloud_dir,
                    "run_dir": str(tmpdir),
                }
            },
            "write_files": [
                {
                    "path": os.path.join(tmpdir, "etc/blah.ini"),
                    "content": "blah",
                    "permissions": 0o755,
                    "owner": getpass.getuser(),
                },
            ],
            "cloud_init_modules": ["write_files", "runcmd"],
        }
        write_file(cloud_cfg_file, safeyaml.dumps(cfg))
        yield copy.deepcopy(cfg), cloud_cfg_file

    @pytest.mark.parametrize(
        "provide_file_arg,expected_file_content",
        (
            pytest.param(False, "blah", id="write_files_from_base_config"),
            pytest.param(
                True,
                "override",
                id="write_files_from_supplemental_file_arg",
            ),
        ),
    )
    def test_main_init_run_net_runs_modules(
        self,
        provide_file_arg,
        expected_file_content,
        cloud_cfg,
        capsys,
        tmpdir,
    ):
        """Modules like write_files are run in 'net' mode."""
        if provide_file_arg:
            supplemental_config_file = tmpdir.join("custom.yaml")
            supplemental_config_file.write(
                EXTRA_CLOUD_CONFIG.format(tmpdir=tmpdir)
            )
            files = [open(supplemental_config_file)]
        else:
            files = None
        cmdargs = MyArgs(
            debug=False,
            files=files,
            force=False,
            local=False,
            reporter=None,
            subcommand="init",
            skip_log_setup=False,
        )
        _ds, msg = main.main_init("init", cmdargs)
        assert msg == []
        # Instancify is called
        instance_id_path = "var/lib/cloud/data/instance-id"
        assert "iid-datasource-none\n" == os.path.join(
            load_text_file(os.path.join(tmpdir, instance_id_path))
        )
        # modules are run (including write_files)
        assert "blah" == load_text_file(os.path.join(tmpdir, "etc/blah.ini"))
        expected_logs = [
            "network config is disabled by fallback",  # apply_network_config
            "my net debug info",  # netinfo.debug_info
            "PID [42] started cloud-init 'init'",
        ]
        stderr = capsys.readouterr().err
        for log in expected_logs:
            assert log in stderr

    def test_main_init_run_net_calls_set_hostname_when_metadata_present(
        self, cloud_cfg, mocker
    ):
        """When local-hostname metadata is present, call cc_set_hostname."""
        cfg, cloud_cfg_file = cloud_cfg
        cfg["datasource"] = {
            "None": {"metadata": {"local-hostname": "md-hostname"}}
        }
        write_file(cloud_cfg_file, safeyaml.dumps(cfg))
        cmdargs = MyArgs(
            debug=False,
            files=None,
            force=False,
            local=False,
            reporter=None,
            subcommand="init",
            skip_log_setup=False,
        )

        def set_hostname(name, cfg, cloud, args):
            assert "set_hostname" == name

        m_hostname = mocker.patch(
            "cloudinit.cmd.main.cc_set_hostname.handle",
            side_effect=set_hostname,
        )
        main.main_init("init", cmdargs)

        m_hostname.assert_called_once()

    @mock.patch("cloudinit.cmd.clean.get_parser")
    @mock.patch("cloudinit.cmd.clean.handle_clean_args")
    @mock.patch("cloudinit.log.loggers.configure_root_logger")
    def test_main_sys_argv(
        self,
        _m_configure_root_logger,
        _m_handle_clean_args,
        m_clean_get_parser,
    ):
        with mock.patch("sys.argv", ["cloudinit", "--debug", "clean"]):
            main.main()
        m_clean_get_parser.assert_called_once()

    @mock.patch("cloudinit.cmd.clean.get_parser")
    @mock.patch("cloudinit.cmd.clean.handle_clean_args")
    @mock.patch("cloudinit.log.loggers.configure_root_logger")
    def test_main_sys_argv_missing_subcommand(
        self,
        _m_configure_root_logger,
        _m_handle_clean_args,
        m_clean_get_parser,
        capsys,
    ):
        with mock.patch("sys.argv", ["cloudinit", "--debug"]):
            with pytest.raises(SystemExit):
                main.main()
        stderr = capsys.readouterr().err
        assert "No Subcommand specified." in stderr
        m_clean_get_parser.assert_not_called()

    @pytest.mark.parametrize(
        "ds,userdata,expected",
        [
            # If we have no datasource, wait regardless
            (None, None, True),
            (None, "#!/bin/bash\n  - echo hello", True),
            # Empty user data shouldn't wait
            (mock.Mock(), "", False),
            # Bootcmd always wait
            (mock.Mock(), "#cloud-config\nbootcmd:\n  - echo hello", True),
            # Bytes are valid too
            (mock.Mock(), b"#cloud-config\nbootcmd:\n  - echo hello", True),
            # write_files with source uri wait
            (
                mock.Mock(),
                textwrap.dedent(
                    """\
                    #cloud-config
                    write_files:
                    - source:
                        uri: http://example.com
                        headers:
                          Authorization: Basic stuff
                          User-Agent: me
                    """
                ),
                True,
            ),
            # write_files with source file don't wait
            (
                mock.Mock(),
                textwrap.dedent(
                    """\
                    #cloud-config
                    write_files:
                    - source:
                        uri: /tmp/hi
                        headers:
                          Authorization: Basic stuff
                          User-Agent: me
                    """
                ),
                False,
            ),
            # write_files without 'source' don't wait
            (
                mock.Mock(),
                textwrap.dedent(
                    """\
                    #cloud-config
                    write_files:
                    - content: hello
                      encoding: b64
                      owner: root:root
                      path: /etc/sysconfig/selinux
                      permissions: '0644'
                    """
                ),
                False,
            ),
            # random_seed with 'command' wait
            (
                mock.Mock(),
                "#cloud-config\nrandom_seed:\n  command: true",
                True,
            ),
            # random_seed without 'command' no wait
            (
                mock.Mock(),
                textwrap.dedent(
                    """\
                    #cloud-config
                    random_seed:
                      data: 4
                      encoding: raw
                      file: /dev/urandom
                    """
                ),
                False,
            ),
            # mounts always wait
            (
                mock.Mock(),
                "#cloud-config\nmounts:\n  - [ /dev/sdb, /mnt, ext4 ]",
                True,
            ),
            # Not parseable as yaml
            (mock.Mock(), "#cloud-config\nbootcmd:\necho hello", True),
            # Yaml that parses to list
            (mock.Mock(), CLOUD_CONFIG_ARCHIVE, True),
            # Non-cloud-config
            (mock.Mock(), "#!/bin/bash\n  - echo hello", True),
            # Something that after processing won't decode to utf-8
            (mock.Mock(), "RANDOM100", True),
            # Something small that  after processing won't decode to utf-8
            (mock.Mock(), "RANDOM5", True),
        ],
    )
    def test_should_wait_on_network(self, ds, userdata, expected):
        # pytest-xdist doesn't like randomness
        # https://github.com/pytest-dev/pytest-xdist/issues/432
        # So work around it with a super stupid hack
        if userdata == "RANDOM100":
            userdata = os.urandom(100)
        elif userdata == "RANDOM5":
            userdata = os.urandom(5)

        if ds:
            ds.get_userdata_raw = mock.Mock(return_value=userdata)
            ds.get_vendordata_raw = mock.Mock(return_value=None)
            ds.get_vendordata2_raw = mock.Mock(return_value=None)
        assert main._should_wait_on_network(ds)[0] is expected

        # Here we rotate our configs to ensure that any of userdata,
        # vendordata, or vendordata2 can be the one that causes us to wait.
        for _ in range(2):
            if ds:
                (
                    ds.get_userdata_raw,
                    ds.get_vendordata_raw,
                    ds.get_vendordata2_raw,
                ) = (
                    ds.get_vendordata_raw,
                    ds.get_vendordata2_raw,
                    ds.get_userdata_raw,
                )
            assert main._should_wait_on_network(ds)[0] is expected

    @pytest.mark.parametrize(
        "distro,should_wait,expected_add_wait",
        [
            ("ubuntu", True, True),
            ("ubuntu", False, False),
            ("debian", True, False),
            ("debian", False, False),
            ("centos", True, False),
            ("rhel", False, False),
            ("fedora", True, False),
            ("suse", False, False),
            ("gentoo", True, False),
            ("arch", False, False),
            ("alpine", False, False),
        ],
    )
    def test_distro_wait_for_network(
        self,
        distro,
        should_wait,
        expected_add_wait,
        cloud_cfg,
        mocker,
        fake_filesystem,
    ):
        mocker.patch("cloudinit.net.netplan.available", return_value=True)
        m_nm = mocker.patch(
            "cloudinit.net.network_manager.available", return_value=False
        )
        m_subp = mocker.patch("cloudinit.subp.subp", return_value=("", ""))
        if not should_wait:
            util.write_file(".skip-network", "")

        cfg, cloud_cfg_file = cloud_cfg
        cfg["system_info"]["distro"] = distro
        write_file(cloud_cfg_file, safeyaml.dumps(cfg))
        cmdargs = MyArgs(
            debug=False,
            files=None,
            force=False,
            local=False,
            reporter=None,
            subcommand="init",
            skip_log_setup=False,
        )
        main.main_init("init", cmdargs)
        if features.MANUAL_NETWORK_WAIT and expected_add_wait:
            m_nm.assert_called_once()
            m_subp.assert_called_with(
                ["systemctl", "start", "systemd-networkd-wait-online.service"]
            )
        else:
            m_nm.assert_not_called()
            m_subp.assert_not_called()


class TestShouldBringUpInterfaces:
    @pytest.mark.parametrize(
        "cfg_disable,args_local,expected",
        [
            (True, True, False),
            (True, False, False),
            (False, True, False),
            (False, False, True),
        ],
    )
    def test_should_bring_up_interfaces(
        self, cfg_disable, args_local, expected
    ):
        init = mock.Mock()
        init.cfg = {"disable_network_activation": cfg_disable}

        args = mock.Mock()
        args.local = args_local

        result = main._should_bring_up_interfaces(init, args)
        assert result == expected