summaryrefslogtreecommitdiff
path: root/cloudinit/sources/DataSourceConfigDrive.py
blob: 677483d0686d3a3dcb7dc5970d1ef4e294cbf99a (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
# vi: ts=4 expandtab
#
#    Copyright (C) 2012 Canonical Ltd.
#    Copyright (C) 2012 Yahoo! Inc.
#
#    Author: Scott Moser <scott.moser@canonical.com>
#    Author: Joshua Harlow <harlowja@yahoo-inc.com>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License version 3, as
#    published by the Free Software Foundation.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

import json
import os

from cloudinit import log as logging
from cloudinit import sources
from cloudinit import util

LOG = logging.getLogger(__name__)

# Various defaults/constants...
DEFAULT_IID = "iid-dsconfigdrive"
DEFAULT_MODE = 'pass'
CFG_DRIVE_FILES_V1 = [
    "etc/network/interfaces",
    "root/.ssh/authorized_keys",
    "meta.js",
]
DEFAULT_METADATA = {
    "instance-id": DEFAULT_IID,
    "dsmode": DEFAULT_MODE,
}
CFG_DRIVE_DEV_ENV = 'CLOUD_INIT_CONFIG_DRIVE_DEVICE'


class DataSourceConfigDrive(sources.DataSource):
    def __init__(self, sys_cfg, distro, paths):
        sources.DataSource.__init__(self, sys_cfg, distro, paths)
        self.seed = None
        self.cfg = {}
        self.dsmode = 'local'
        self.seed_dir = os.path.join(paths.seed_dir, 'config_drive')
        self.version = None

    def __str__(self):
        mstr = "%s [%s,ver=%s]" % (util.obj_name(self), self.dsmode,
                                   self.version)
        mstr += "[seed=%s]" % (self.seed)
        return mstr

    def get_data(self):
        found = None
        md = {}
        ud = ""

        if os.path.isdir(self.seed_dir):
            try:
                (md, ud, files, ver) = read_config_drive_dir(self.seed_dir)
                found = self.seed_dir
            except NonConfigDriveDir:
                util.logexc(LOG, "Failed reading config drive from %s",
                            self.seed_dir)
        if not found:
            fslist = util.find_devs_with("TYPE=vfat")
            fslist.extend(util.find_devs_with("TYPE=iso9660"))

            label_list = util.find_devs_with("LABEL=config-2")
            devlist = list(set(fslist) & set(label_list))

            dev = find_cfg_drive_device()
            if dev not in devlist:
                devlist.append(dev)

            devlist.sort(reverse=True)

            for dev in devlist:
                try:
                    (md, ud, files, ver) = util.mount_cb(dev, read_config_drive_dir)
                    found = dev
                    break
                except (NonConfigDriveDir, util.MountFailedError):
                    pass

        if not found:
            return False

        if 'dsconfig' in md:
            self.cfg = md['dscfg']

        md = util.mergedict(md, DEFAULT_METADATA)

        # Update interfaces and ifup only on the local datasource
        # this way the DataSourceConfigDriveNet doesn't do it also.
        if 'network-interfaces' in md and self.dsmode == "local":
            LOG.debug("Updating network interfaces from config drive (%s)",
                     md['dsmode'])
            self.distro.apply_network(md['network-interfaces'])

        self.seed = found
        self.metadata = md
        self.userdata_raw = ud
        self.version = ver

        if md['dsmode'] == self.dsmode:
            return True

        LOG.debug("%s: not claiming datasource, dsmode=%s", self, md['dsmode'])
        return False

    def get_public_ssh_keys(self):
        if not 'public-keys' in self.metadata:
            return []
        return self.metadata['public-keys']

    # The data sources' config_obj is a cloud-config formated
    # object that came to it from ways other than cloud-config
    # because cloud-config content would be handled elsewhere
    def get_config_obj(self):
        return self.cfg


class DataSourceConfigDriveNet(DataSourceConfigDrive):
    def __init__(self, sys_cfg, distro, paths):
        DataSourceConfigDrive.__init__(self, sys_cfg, distro, paths)
        self.dsmode = 'net'


class NonConfigDriveDir(Exception):
    pass

class BrokenConfigDriveDir(Exception):
    pass


def find_cfg_drive_device():
    """Get the config drive device.  Return a string like '/dev/vdb'
       or None (if there is no non-root device attached). This does not
       check the contents, only reports that if there *were* a config_drive
       attached, it would be this device.
       Note: per config_drive documentation, this is
       "associated as the last available disk on the instance"
    """

    # This seems to be for debugging??
    if CFG_DRIVE_DEV_ENV in os.environ:
        return os.environ[CFG_DRIVE_DEV_ENV]

    # We are looking for a raw block device (sda, not sda1) with a vfat
    # filesystem on it....
    letters = "abcdefghijklmnopqrstuvwxyz"
    devs = util.find_devs_with("TYPE=vfat")

    # Filter out anything not ending in a letter (ignore partitions)
    devs = [f for f in devs if f[-1] in letters]

    # Sort them in reverse so "last" device is first
    devs.sort(reverse=True)

    if devs:
        return devs[0]

    return None


def read_config_drive_dir(source_dir):
    last_e = NonConfigDriveDir("Not found")
    for finder in (read_config_drive_dir_v2, read_config_drive_dir_v1):
        try:
            data = finder(source_dir)
            return data
        except NonConfigDriveDir as exc:
            last_e = exc
    raise last_e

def read_config_drive_dir_v2(source_dir, version="latest"):
    datafiles = (
        ('metadata',
         "openstack/%s/meta_data.json" % version, True, json.loads),
        ('userdata', "openstack/%s/user_data" % version, False, None),
        ('ec2-metadata', "ec2/latest/metadata.json", False, json.loads),
    )

    results = {}
    for (name, path, required, process) in datafiles:
        fpath = os.path.join(source_dir, path)
        data = None
        found = False
        if os.path.isfile(fpath):
            try:
                with open(fpath) as fp:
                    data = fp.read()
            except Exception as exc:
                raise BrokenConfigDriveDir("failed to read: %s" % fpath)
            found = True
        elif required:
            raise BrokenConfigDriveDir("missing mandatory %s" % fpath)

        if found and process:
            try:
                data = process(data)
            except Exception as exc:
                raise BrokenConfigDriveDir("failed to process: %s" % fpath)

        if found:
            results[name] = data

    def read_content_path(item):
        # do not use os.path.join here, as content_path starts with /
        cpath = os.path.sep.join((source_dir, "openstack",
                                  "./%s" % item['content_path']))
        with open(cpath) as fp:
            return(fp.read())

    files = {}
    try:
        for item in results['metadata'].get('files',{}):
            files[item['path']] = read_content_path(item)

        item = results['metadata'].get("network_config", None)
        if item:
            results['network_config'] = read_content_path(item)
    except Exception as exc:
        raise BrokenConfigDriveDir("failed to read file %s: %s" % (item, exc))

    results['files'] = files
    results['cfgdrive_ver'] = 2
    return results

def read_config_drive_dir_v1(source_dir):
    """
    read source_dir, and return a tuple with metadata dict, user-data,
    files and version (1).  If not a valid dir, raise a NonConfigDriveDir
    """

    # TODO(harlowja): fix this for other operating systems...
    # Ie: this is where https://fedorahosted.org/netcf/ or similar should
    # be hooked in... (or could be)
    found = {}
    for af in CFG_DRIVE_FILES_V1:
        fn = os.path.join(source_dir, af)
        if os.path.isfile(fn):
            found[af] = fn

    if len(found) == 0:
        raise NonConfigDriveDir("%s: %s" % (source_dir, "no files found"))

    md = {}
    ud = ""
    keydata = ""
    if "etc/network/interfaces" in found:
        fn = found["etc/network/interfaces"]
        md['network-interfaces'] = util.load_file(fn)

    if "root/.ssh/authorized_keys" in found:
        fn = found["root/.ssh/authorized_keys"]
        keydata = util.load_file(fn)

    meta_js = {}
    if "meta.js" in found:
        fn = found['meta.js']
        content = util.load_file(fn)
        try:
            # Just check if its really json...
            meta_js = json.loads(content)
            if not isinstance(meta_js, (dict)):
                raise TypeError("Dict expected for meta.js root node")
        except (ValueError, TypeError) as e:
            raise NonConfigDriveDir("%s: %s, %s" %
                (source_dir, "invalid json in meta.js", e))
        md['meta_js'] = content

    # Key data override??
    keydata = meta_js.get('public-keys', keydata)
    if keydata:
        lines = keydata.splitlines()
        md['public-keys'] = [l for l in lines
            if len(l) and not l.startswith("#")]

    for copy in ('dsmode', 'instance-id', 'dscfg'):
        if copy in meta_js:
            md[copy] = meta_js[copy]

    if 'user-data' in meta_js:
        ud = meta_js['user-data']

    # metadata, user-data, 'files', 1
    return {'metadata': md, 'userdata': ud, 'files': [], 'cfgdrive_ver': 1}


# Used to match classes to dependencies
datasources = [
  (DataSourceConfigDrive, (sources.DEP_FILESYSTEM, )),
  (DataSourceConfigDriveNet, (sources.DEP_FILESYSTEM, sources.DEP_NETWORK)),
]


# Return a list of data sources that match this set of dependencies
def get_datasource_list(depends):
    return sources.list_from_depends(depends, datasources)