summaryrefslogtreecommitdiff
path: root/cloudinit/net/dhcp.py
blob: 0db991db40fba2b7884134c8b435b9afd6ca9ff1 (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
# Copyright (C) 2017 Canonical Ltd.
#
# Author: Chad Smith <chad.smith@canonical.com>
#
# This file is part of cloud-init. See LICENSE file for license information.

import configobj
import logging
import os
import re
import signal

from cloudinit.net import (
    EphemeralIPv4Network, find_fallback_nic, get_devicelist,
    has_url_connectivity)
from cloudinit.net.network_state import mask_and_ipv4_to_bcast_addr as bcip
from cloudinit import temp_utils
from cloudinit import util
from six import StringIO

LOG = logging.getLogger(__name__)

NETWORKD_LEASES_DIR = '/run/systemd/netif/leases'


class InvalidDHCPLeaseFileError(Exception):
    """Raised when parsing an empty or invalid dhcp.leases file.

    Current uses are DataSourceAzure and DataSourceEc2 during ephemeral
    boot to scrape metadata.
    """
    pass


class NoDHCPLeaseError(Exception):
    """Raised when unable to get a DHCP lease."""
    pass


class EphemeralDHCPv4(object):
    def __init__(self, iface=None, connectivity_url=None):
        self.iface = iface
        self._ephipv4 = None
        self.lease = None
        self.connectivity_url = connectivity_url

    def __enter__(self):
        """Setup sandboxed dhcp context, unless connectivity_url can already be
        reached."""
        if self.connectivity_url:
            if has_url_connectivity(self.connectivity_url):
                LOG.debug(
                    'Skip ephemeral DHCP setup, instance has connectivity'
                    ' to %s', self.connectivity_url)
                return
        return self.obtain_lease()

    def __exit__(self, excp_type, excp_value, excp_traceback):
        """Teardown sandboxed dhcp context."""
        self.clean_network()

    def clean_network(self):
        """Exit _ephipv4 context to teardown of ip configuration performed."""
        if self.lease:
            self.lease = None
        if not self._ephipv4:
            return
        self._ephipv4.__exit__(None, None, None)

    def obtain_lease(self):
        """Perform dhcp discovery in a sandboxed environment if possible.

        @return: A dict representing dhcp options on the most recent lease
            obtained from the dhclient discovery if run, otherwise an error
            is raised.

        @raises: NoDHCPLeaseError if no leases could be obtained.
        """
        if self.lease:
            return self.lease
        try:
            leases = maybe_perform_dhcp_discovery(self.iface)
        except InvalidDHCPLeaseFileError:
            raise NoDHCPLeaseError()
        if not leases:
            raise NoDHCPLeaseError()
        self.lease = leases[-1]
        LOG.debug("Received dhcp lease on %s for %s/%s",
                  self.lease['interface'], self.lease['fixed-address'],
                  self.lease['subnet-mask'])
        nmap = {'interface': 'interface', 'ip': 'fixed-address',
                'prefix_or_mask': 'subnet-mask',
                'broadcast': 'broadcast-address',
                'router': 'routers'}
        kwargs = dict([(k, self.lease.get(v)) for k, v in nmap.items()])
        if not kwargs['broadcast']:
            kwargs['broadcast'] = bcip(kwargs['prefix_or_mask'], kwargs['ip'])
        if self.connectivity_url:
            kwargs['connectivity_url'] = self.connectivity_url
        ephipv4 = EphemeralIPv4Network(**kwargs)
        ephipv4.__enter__()
        self._ephipv4 = ephipv4
        return self.lease


def maybe_perform_dhcp_discovery(nic=None):
    """Perform dhcp discovery if nic valid and dhclient command exists.

    If the nic is invalid or undiscoverable or dhclient command is not found,
    skip dhcp_discovery and return an empty dict.

    @param nic: Name of the network interface we want to run dhclient on.
    @return: A list of dicts representing dhcp options for each lease obtained
        from the dhclient discovery if run, otherwise an empty list is
        returned.
    """
    if nic is None:
        nic = find_fallback_nic()
        if nic is None:
            LOG.debug('Skip dhcp_discovery: Unable to find fallback nic.')
            return []
    elif nic not in get_devicelist():
        LOG.debug(
            'Skip dhcp_discovery: nic %s not found in get_devicelist.', nic)
        return []
    dhclient_path = util.which('dhclient')
    if not dhclient_path:
        LOG.debug('Skip dhclient configuration: No dhclient command found.')
        return []
    with temp_utils.tempdir(prefix='cloud-init-dhcp-', needs_exe=True) as tdir:
        # Use /var/tmp because /run/cloud-init/tmp is mounted noexec
        return dhcp_discovery(dhclient_path, nic, tdir)


def parse_dhcp_lease_file(lease_file):
    """Parse the given dhcp lease file for the most recent lease.

    Return a list of dicts of dhcp options. Each dict contains key value pairs
    a specific lease in order from oldest to newest.

    @raises: InvalidDHCPLeaseFileError on empty of unparseable leasefile
        content.
    """
    lease_regex = re.compile(r"lease {(?P<lease>[^}]*)}\n")
    dhcp_leases = []
    lease_content = util.load_file(lease_file)
    if len(lease_content) == 0:
        raise InvalidDHCPLeaseFileError(
            'Cannot parse empty dhcp lease file {0}'.format(lease_file))
    for lease in lease_regex.findall(lease_content):
        lease_options = []
        for line in lease.split(';'):
            # Strip newlines, double-quotes and option prefix
            line = line.strip().replace('"', '').replace('option ', '')
            if not line:
                continue
            lease_options.append(line.split(' ', 1))
        dhcp_leases.append(dict(lease_options))
    if not dhcp_leases:
        raise InvalidDHCPLeaseFileError(
            'Cannot parse dhcp lease file {0}. No leases found'.format(
                lease_file))
    return dhcp_leases


def dhcp_discovery(dhclient_cmd_path, interface, cleandir):
    """Run dhclient on the interface without scripts or filesystem artifacts.

    @param dhclient_cmd_path: Full path to the dhclient used.
    @param interface: Name of the network inteface on which to dhclient.
    @param cleandir: The directory from which to run dhclient as well as store
        dhcp leases.

    @return: A list of dicts of representing the dhcp leases parsed from the
        dhcp.leases file or empty list.
    """
    LOG.debug('Performing a dhcp discovery on %s', interface)

    # XXX We copy dhclient out of /sbin/dhclient to avoid dealing with strict
    # app armor profiles which disallow running dhclient -sf <our-script-file>.
    # We want to avoid running /sbin/dhclient-script because of side-effects in
    # /etc/resolv.conf any any other vendor specific scripts in
    # /etc/dhcp/dhclient*hooks.d.
    sandbox_dhclient_cmd = os.path.join(cleandir, 'dhclient')
    util.copy(dhclient_cmd_path, sandbox_dhclient_cmd)
    pid_file = os.path.join(cleandir, 'dhclient.pid')
    lease_file = os.path.join(cleandir, 'dhcp.leases')

    # ISC dhclient needs the interface up to send initial discovery packets.
    # Generally dhclient relies on dhclient-script PREINIT action to bring the
    # link up before attempting discovery. Since we are using -sf /bin/true,
    # we need to do that "link up" ourselves first.
    util.subp(['ip', 'link', 'set', 'dev', interface, 'up'], capture=True)
    cmd = [sandbox_dhclient_cmd, '-1', '-v', '-lf', lease_file,
           '-pf', pid_file, interface, '-sf', '/bin/true']
    util.subp(cmd, capture=True)

    # dhclient doesn't write a pid file until after it forks when it gets a
    # proper lease response. Since cleandir is a temp directory that gets
    # removed, we need to wait for that pidfile creation before the
    # cleandir is removed, otherwise we get FileNotFound errors.
    missing = util.wait_for_files(
        [pid_file, lease_file], maxwait=5, naplen=0.01)
    if missing:
        LOG.warning("dhclient did not produce expected files: %s",
                    ', '.join(os.path.basename(f) for f in missing))
        return []
    pid_content = util.load_file(pid_file).strip()
    try:
        pid = int(pid_content)
    except ValueError:
        LOG.debug(
            "pid file contains non-integer content '%s'", pid_content)
    else:
        os.kill(pid, signal.SIGKILL)
    return parse_dhcp_lease_file(lease_file)


def networkd_parse_lease(content):
    """Parse a systemd lease file content as in /run/systemd/netif/leases/

    Parse this (almost) ini style file even though it says:
      # This is private data. Do not parse.

    Simply return a dictionary of key/values."""

    return dict(configobj.ConfigObj(StringIO(content), list_values=False))


def networkd_load_leases(leases_d=None):
    """Return a dictionary of dictionaries representing each lease
    found in lease_d.i

    The top level key will be the filename, which is typically the ifindex."""

    if leases_d is None:
        leases_d = NETWORKD_LEASES_DIR

    ret = {}
    if not os.path.isdir(leases_d):
        return ret
    for lfile in os.listdir(leases_d):
        ret[lfile] = networkd_parse_lease(
            util.load_file(os.path.join(leases_d, lfile)))
    return ret


def networkd_get_option_from_leases(keyname, leases_d=None):
    if leases_d is None:
        leases_d = NETWORKD_LEASES_DIR
    leases = networkd_load_leases(leases_d=leases_d)
    for _ifindex, data in sorted(leases.items()):
        if data.get(keyname):
            return data[keyname]
    return None

# vi: ts=4 expandtab