summaryrefslogtreecommitdiff
path: root/cloudinit/config/cc_lxd.py
blob: 13ddcbe930a6a834d7c43a2d8a442dc88a0bebee (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
# Copyright (C) 2016 Canonical Ltd.
#
# Author: Wesley Wiedenmeier <wesley.wiedenmeier@canonical.com>
#
# This file is part of cloud-init. See LICENSE file for license information.

"""
LXD
---
**Summary:** configure lxd with ``lxd init`` and optionally lxd-bridge

This module configures lxd with user specified options using ``lxd init``.
If lxd is not present on the system but lxd configuration is provided, then
lxd will be installed. If the selected storage backend is zfs, then zfs will
be installed if missing. If network bridge configuration is provided, then
lxd-bridge will be configured accordingly.

**Internal name:** ``cc_lxd``

**Module frequency:** per instance

**Supported distros:** ubuntu

**Config keys**::

    lxd:
        init:
            network_address: <ip addr>
            network_port: <port>
            storage_backend: <zfs/dir>
            storage_create_device: <dev>
            storage_create_loop: <size>
            storage_pool: <name>
            trust_password: <password>
        bridge:
            mode: <new, existing or none>
            name: <name>
            ipv4_address: <ip addr>
            ipv4_netmask: <cidr>
            ipv4_dhcp_first: <ip addr>
            ipv4_dhcp_last: <ip addr>
            ipv4_dhcp_leases: <size>
            ipv4_nat: <bool>
            ipv6_address: <ip addr>
            ipv6_netmask: <cidr>
            ipv6_nat: <bool>
            domain: <domain>
"""

import os

from cloudinit import log as logging
from cloudinit import subp, util

distros = ["ubuntu"]

LOG = logging.getLogger(__name__)

_DEFAULT_NETWORK_NAME = "lxdbr0"


def handle(name, cfg, cloud, log, args):
    # Get config
    lxd_cfg = cfg.get("lxd")
    if not lxd_cfg:
        log.debug(
            "Skipping module named %s, not present or disabled by cfg", name
        )
        return
    if not isinstance(lxd_cfg, dict):
        log.warning(
            "lxd config must be a dictionary. found a '%s'", type(lxd_cfg)
        )
        return

    # Grab the configuration
    init_cfg = lxd_cfg.get("init")
    if not isinstance(init_cfg, dict):
        log.warning(
            "lxd/init config must be a dictionary. found a '%s'",
            type(init_cfg),
        )
        init_cfg = {}

    bridge_cfg = lxd_cfg.get("bridge", {})
    if not isinstance(bridge_cfg, dict):
        log.warning(
            "lxd/bridge config must be a dictionary. found a '%s'",
            type(bridge_cfg),
        )
        bridge_cfg = {}

    # Install the needed packages
    packages = []
    if not subp.which("lxd"):
        packages.append("lxd")

    if init_cfg.get("storage_backend") == "zfs" and not subp.which("zfs"):
        packages.append("zfsutils-linux")

    if len(packages):
        try:
            cloud.distro.install_packages(packages)
        except subp.ProcessExecutionError as exc:
            log.warning("failed to install packages %s: %s", packages, exc)
            return

    # Set up lxd if init config is given
    if init_cfg:
        init_keys = (
            "network_address",
            "network_port",
            "storage_backend",
            "storage_create_device",
            "storage_create_loop",
            "storage_pool",
            "trust_password",
        )
        subp.subp(["lxd", "waitready", "--timeout=300"])
        cmd = ["lxd", "init", "--auto"]
        for k in init_keys:
            if init_cfg.get(k):
                cmd.extend(
                    ["--%s=%s" % (k.replace("_", "-"), str(init_cfg[k]))]
                )
        subp.subp(cmd)

    # Set up lxd-bridge if bridge config is given
    dconf_comm = "debconf-communicate"
    if bridge_cfg:
        net_name = bridge_cfg.get("name", _DEFAULT_NETWORK_NAME)
        if os.path.exists("/etc/default/lxd-bridge") and subp.which(
            dconf_comm
        ):
            # Bridge configured through packaging

            debconf = bridge_to_debconf(bridge_cfg)

            # Update debconf database
            try:
                log.debug("Setting lxd debconf via " + dconf_comm)
                data = (
                    "\n".join(
                        ["set %s %s" % (k, v) for k, v in debconf.items()]
                    )
                    + "\n"
                )
                subp.subp(["debconf-communicate"], data)
            except Exception:
                util.logexc(
                    log, "Failed to run '%s' for lxd with" % dconf_comm
                )

            # Remove the existing configuration file (forces re-generation)
            util.del_file("/etc/default/lxd-bridge")

            # Run reconfigure
            log.debug("Running dpkg-reconfigure for lxd")
            subp.subp(["dpkg-reconfigure", "lxd", "--frontend=noninteractive"])
        else:
            # Built-in LXD bridge support
            cmd_create, cmd_attach = bridge_to_cmd(bridge_cfg)
            maybe_cleanup_default(
                net_name=net_name,
                did_init=bool(init_cfg),
                create=bool(cmd_create),
                attach=bool(cmd_attach),
            )
            if cmd_create:
                log.debug("Creating lxd bridge: %s" % " ".join(cmd_create))
                _lxc(cmd_create)

            if cmd_attach:
                log.debug(
                    "Setting up default lxd bridge: %s" % " ".join(cmd_attach)
                )
                _lxc(cmd_attach)

    elif bridge_cfg:
        raise RuntimeError(
            "Unable to configure lxd bridge without %s." + dconf_comm
        )


def bridge_to_debconf(bridge_cfg):
    debconf = {}

    if bridge_cfg.get("mode") == "none":
        debconf["lxd/setup-bridge"] = "false"
        debconf["lxd/bridge-name"] = ""

    elif bridge_cfg.get("mode") == "existing":
        debconf["lxd/setup-bridge"] = "false"
        debconf["lxd/use-existing-bridge"] = "true"
        debconf["lxd/bridge-name"] = bridge_cfg.get("name")

    elif bridge_cfg.get("mode") == "new":
        debconf["lxd/setup-bridge"] = "true"
        if bridge_cfg.get("name"):
            debconf["lxd/bridge-name"] = bridge_cfg.get("name")

        if bridge_cfg.get("ipv4_address"):
            debconf["lxd/bridge-ipv4"] = "true"
            debconf["lxd/bridge-ipv4-address"] = bridge_cfg.get("ipv4_address")
            debconf["lxd/bridge-ipv4-netmask"] = bridge_cfg.get("ipv4_netmask")
            debconf["lxd/bridge-ipv4-dhcp-first"] = bridge_cfg.get(
                "ipv4_dhcp_first"
            )
            debconf["lxd/bridge-ipv4-dhcp-last"] = bridge_cfg.get(
                "ipv4_dhcp_last"
            )
            debconf["lxd/bridge-ipv4-dhcp-leases"] = bridge_cfg.get(
                "ipv4_dhcp_leases"
            )
            debconf["lxd/bridge-ipv4-nat"] = bridge_cfg.get("ipv4_nat", "true")

        if bridge_cfg.get("ipv6_address"):
            debconf["lxd/bridge-ipv6"] = "true"
            debconf["lxd/bridge-ipv6-address"] = bridge_cfg.get("ipv6_address")
            debconf["lxd/bridge-ipv6-netmask"] = bridge_cfg.get("ipv6_netmask")
            debconf["lxd/bridge-ipv6-nat"] = bridge_cfg.get(
                "ipv6_nat", "false"
            )

        if bridge_cfg.get("domain"):
            debconf["lxd/bridge-domain"] = bridge_cfg.get("domain")

    else:
        raise Exception('invalid bridge mode "%s"' % bridge_cfg.get("mode"))

    return debconf


def bridge_to_cmd(bridge_cfg):
    if bridge_cfg.get("mode") == "none":
        return None, None

    bridge_name = bridge_cfg.get("name", _DEFAULT_NETWORK_NAME)
    cmd_create = []
    cmd_attach = ["network", "attach-profile", bridge_name, "default", "eth0"]

    if bridge_cfg.get("mode") == "existing":
        return None, cmd_attach

    if bridge_cfg.get("mode") != "new":
        raise Exception('invalid bridge mode "%s"' % bridge_cfg.get("mode"))

    cmd_create = ["network", "create", bridge_name]

    if bridge_cfg.get("ipv4_address") and bridge_cfg.get("ipv4_netmask"):
        cmd_create.append(
            "ipv4.address=%s/%s"
            % (bridge_cfg.get("ipv4_address"), bridge_cfg.get("ipv4_netmask"))
        )

        if bridge_cfg.get("ipv4_nat", "true") == "true":
            cmd_create.append("ipv4.nat=true")

        if bridge_cfg.get("ipv4_dhcp_first") and bridge_cfg.get(
            "ipv4_dhcp_last"
        ):
            dhcp_range = "%s-%s" % (
                bridge_cfg.get("ipv4_dhcp_first"),
                bridge_cfg.get("ipv4_dhcp_last"),
            )
            cmd_create.append("ipv4.dhcp.ranges=%s" % dhcp_range)
    else:
        cmd_create.append("ipv4.address=none")

    if bridge_cfg.get("ipv6_address") and bridge_cfg.get("ipv6_netmask"):
        cmd_create.append(
            "ipv6.address=%s/%s"
            % (bridge_cfg.get("ipv6_address"), bridge_cfg.get("ipv6_netmask"))
        )

        if bridge_cfg.get("ipv6_nat", "false") == "true":
            cmd_create.append("ipv6.nat=true")

    else:
        cmd_create.append("ipv6.address=none")

    if bridge_cfg.get("domain"):
        cmd_create.append("dns.domain=%s" % bridge_cfg.get("domain"))

    return cmd_create, cmd_attach


def _lxc(cmd):
    env = {
        "LC_ALL": "C",
        "HOME": os.environ.get("HOME", "/root"),
        "USER": os.environ.get("USER", "root"),
    }
    subp.subp(["lxc"] + list(cmd) + ["--force-local"], update_env=env)


def maybe_cleanup_default(
    net_name, did_init, create, attach, profile="default", nic_name="eth0"
):
    """Newer versions of lxc (3.0.1+) create a lxdbr0 network when
    'lxd init --auto' is run.  Older versions did not.

    By removing ay that lxd-init created, we simply leave the add/attach
    code in-tact.

    https://github.com/lxc/lxd/issues/4649"""
    if net_name != _DEFAULT_NETWORK_NAME or not did_init:
        return

    fail_assume_enoent = "failed. Assuming it did not exist."
    succeeded = "succeeded."
    if create:
        msg = "Detach of lxd network '%s' from profile '%s' %s"
        try:
            _lxc(["network", "detach-profile", net_name, profile])
            LOG.debug(msg, net_name, profile, succeeded)
        except subp.ProcessExecutionError as e:
            if e.exit_code != 1:
                raise e
            LOG.debug(msg, net_name, profile, fail_assume_enoent)
        else:
            msg = "Deletion of lxd network '%s' %s"
            _lxc(["network", "delete", net_name])
            LOG.debug(msg, net_name, succeeded)

    if attach:
        msg = "Removal of device '%s' from profile '%s' %s"
        try:
            _lxc(["profile", "device", "remove", profile, nic_name])
            LOG.debug(msg, nic_name, profile, succeeded)
        except subp.ProcessExecutionError as e:
            if e.exit_code != 1:
                raise e
            LOG.debug(msg, nic_name, profile, fail_assume_enoent)


# vi: ts=4 expandtab