Source

vinstall / vinstall / backend / bootloader.py

Full commit
  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
# coding: utf8


"""Bootloader setup

>>> lilo = Lilo("/dev/sda1") # pass main os root
>>> lilo.backup_config()
... for system in OperatingSystem.all():
...     lilo.add_os(system)
>>> lilo.write_config()
>>> lilo.install()

"""


__author__ = "M0E-lnx"


import os
import shutil
import tempfile
from StringIO import StringIO
from vinstall.backend import utils, media
from vinstall.backend import sp
import unittest


LILO = object()
GRUB = object()
GRUB2 = object()


class Lilo(object):
    """LiLo bootloader

    """
    def __init__(self, target, default_os=None, timeout=3,
            vga_mode="788"):

        self.target = target
        self.default_os = default_os
        self.vga_mode = vga_mode
        self.operating_systems = []
        self.timeout = None
        self.set_timeout(timeout)
        self.buffer = []
        self.lilo_root = utils.get_mounted("/")
        tamu = "/boot/tamu"
        if not os.path.exists(tamu):
            os.mkdir(tamu)

    def add_os(self, system):
        if system.type == "linux":
            self.add_unix_os(system)
        elif "microsoft" in system.type:
            self.add_ms_os(system)
        else:
            #XXX
            pass

    def add_unix_os(self, system):
        """Add an operating system to the boot menu

        """
        if system in self.operating_systems:
            raise RuntimeError("OS already added")
        if system.root != self.lilo_root:

            # mount os root partition if needed
            umount = False
            partition = media.Partition(system.root)
            if not partition.is_mounted():
                mountpoint = system.root.replace("/dev/", "/mnt/")
                if not os.path.exists(mountpoint):
                    os.mkdir(mountpoint)
                partition.mount(mountpoint)
                umount = True

            # copy kernel
            kernel_from = os.path.join(partition.mountpoint, "boot",
                    system.kernel_name)
            kernel_dest = os.path.join("/boot/tamu", system.kernel)
            shutil.copy2(kernel_from, kernel_dest)

            # copy initrd if needed
            if system.initrd:
                initrd_from = os.path.join(partition.mountpoint,
                        system.initrd)
                initrd_dest = os.path.join("/boot/tamu",
                        system.initrd)
                if os.path.exists(initrd_from) and \
                        not os.path.exists(initrd_dest):
                    shutil.copy2(initrd_from, initrd_dest)

            # umount if needed
            if umount:
                partition.umount()

            # write config lines
            tab = " " * 4
            self.buffer.append("# -- %s on %s --" % (system.label,
                system.root))
            self.buffer.append("image = %s" % system.kernel)
            self.buffer.append("%s label = %s" % (tab, system.label))
            if system.initrd:
                self.buffer.append("%s initrd = %s" % (tab,
                    system.initrd))
            if system.appendline:
                if "splash" not in system.appendline:
                    self.buffer.append('%s append = "%s splash=silent"' %
                            (tab, system.appendline))
                else:
                    self.buffer.append('s append = "%s"' % (tab,
                            system.appendline))
            self.buffer.append("%s read-only" % tab)
            self.buffer.append("# --")

            self.operating_systems.append(system)

    def add_ms_os(self, system):
        """Add MS os to boot menu

        """

    def set_default_os(self, system):
        """Set the default OS

        """
        self.default_os = system

    def set_timeout(self, seconds):
        """Wait for <timeout> seconds before booting the default OS

        """
        self.timeout = int(seconds) * 10

    def set_vga_mode(self, resolution, quality):
        """Set the VGA mode

        """
        values = {
                "640x480" : {
                    "low" : "769",
                    "med" : "784",
                    "high" : "785"},
                "800x600" : {
                    "low" : "771",
                    "med" : "787",
                    "high" : "788"},
                "1024x768" : {
                    "low" : "773",
                    "med" : "790",
                    "high" : "791"},
                "1280x1024": {
                    "high":"794",
                    "med":"793",
                    "low":"775"}}

        self.vga_mode = values[resolution][quality]

    def backup_config(self):
        """Backup existing lilo.conf

        """

    def write_config(self, config_path="/etc/lilo.conf"):
        """Write lilo.conf.

        """
        newline = "\n"
        header = (
            "# LILO configuration file.",
            "# ",
            "# Generated by VASM.",
            "# ",
            "boot = %s" % self.target,
            "compact",
            "prompt",
            "timeout = %s" % self.timeout,
            "change-rules",
            "reset",
            "bitmap = /boot/bitmap/boot.bmp",
            "vga = %s" % self.vga_mode,
            "# OS list")

        with open(config_path, "w") as liloconf:
            for i in header:
                liloconf.write(i + newline)
            for line in self.buffer:
                liloconf.write(line + newline)

    def install(self):
        """Install the bootloader

        """
        return sp.check_call(["/sbin/lilo"])

    def test_install(self, config_file, bootdev):
        """Install routine for testing

        """
        cmd = "/sbin/lilo -b %s -C %s" % (bootdev, config_file)
        return sp.check_call(cmd.split())


class Grub2(object):
    """Grub2 bootloader

    """
    def __init__(self, target):
        self.config_path = "/etc/default/grub"
        self.type = GRUB2
        self.timeout = 3
        self.target = target
        self.vga_mode = None
        self.set_vga_mode()

    def set_vga_mode(self, resolution="800x600"):
        modes = {
                "640x480": "640x480x16",
                "800x600": "800x600x16",
                "1024x768": "1024x768x16",
                "1280x1024": "1280x1024x16"}
        self.vga_mode = modes.get(resolution, "800x600")

    def backup_config(self):
        pass

    def write_config(self, config_path="/etc/default/grub"):
        """The grub2 config file is automatically generated, so we use
        this method to save the values to /etc/default/grub which is
        parsed while the config file is generated

        """

        # set the correct vga_mode value
        if not self.vga_mode:
            self.set_vga_mode()

        ndata = ["export GRUB_GFXMODE=%s"% self.vga_mode,
                 "export GRUB_TERMINAL=gfxterm",
                 "export GRUB_DISABLE_LINUX_UUID=true",
                 "export GRUB_TIMEOUT=%s"% self.timeout,
                 "if [ \"$GRUB_GFXMODE\" = \"1024x768x16\" ]; then",
                 "    VGA=791 ",
                 "elif [ \"$GRUB_GFXMODE\" = \"800x600x16\" ]; then",
                 "    VGA=788 ",
                 "elif [ \"$GRUB_GFXMODE\" = \"1280x1024x16\" ]; then",
                 "    VGA=794 ",
                 "else",
                 "    VGA=normal",
                 "fi",
                 "# END OF /etc/default/grub",""]

        # save the new file
        with open(config_path, "w") as f:
            f.writelines("\n".join(ndata))

        # after these are set, we just need to run grub-mkconfig
        cfg = "/boot/grub/grub.cfg"
        new = cfg + ".new"
        sp.check_call(["grub-mkconfig", "-o", cfg])
        if os.path.exists(new):
            shutil.move(new, cfg)

    def install(self):
        """Install grub to the target

        """
        sp.check_call(["grub-mkdevicemap", "--no-floppy"])
        sp.check_call(["grub-install", "--no-floppy", self.target])

    def test_install(self, config_file, bootdev):
        sp.check_call(["grub-mkdevicemap", "--no-floppy"])
        sp.check_call(["grub-install", "--no-floppy", bootdev])


class OperatingSystem(object):
    """An OS to be added to a bootloader

    """
    type = None         # str indicating OS type
    kernel = None       # Kernel image
    root = None         # path to OS root
    appendline = None   # append line for lilo.conf

    @property
    def kernel_name(self):
        return os.path.split(self.kernel)[-1]

    @classmethod
    def all(cls, include_running_os=False):
        """Return one OperatingSystem instance for each OS
        installed

        """
        os_prober = sp.check_output(["os-prober", "&>/dev/null"])
        found_os = os_prober.split("\n")

        if include_running_os and os.path.exists('/boot/vmlinuz'):
            running_os = cls()
            running_os.kernel = '/boot/vmlinuz'
            running_os.label = 'VectorLinux'
            running_os.type = "linux"
            if os.path.exists('/boot/initrd'):
                running_os.initrd = '/boot/initrd'
            running_os.root = utils.get_mounted("/")
            yield running_os

        for i in found_os:
            if ":" not in i:
                continue
            root, long_desc, short_desc, os_type = \
                    [ s.strip() for s in i.split(":") ]
            operating_system = cls()
            if short_desc.startswith("Vector"):
                short_desc = "VectorLinux - %s"% root.split("/")[-1]
            operating_system.label = short_desc
            if os_type.lower() == "linux":
                operating_system.type = "linux"
                bootinfo = get_linux_boot_info(root)
                if bootinfo is None:
                    continue
                operating_system.root = bootinfo["root"] or root
                operating_system.kernel = bootinfo["kernel"]
                operating_system.initrd = bootinfo["initrd"]
                operating_system.appendline = bootinfo["append"]
            elif "microsoft" in os.type.lower() or \
                    "windows" in os_type.lower():
                        operating_system.root = root
                        operating_system.label = root.split("/")[-1]
                        operating_system.type = "windows"
            #XXX what about bsd, osx, etc
            else:
                continue
            yield operating_system


class MasterBootRecord(object):
    """The MBR of a device

    """
    def __init__(self, device):
        self.device = device # path to the device as in /dev/sda

    def read(self, bytes=2):
        """Read n bytes

        """
        with open(self.device) as f:
            data = f.read(bytes)
        return data

    def bootloader(self):
        """Return the bootloader installed in the MBR if any

        """
        bytes = self.read()
        if bytes == "\xEB\x63":
            return GRUB2
        elif bytes == "\xEB\x48":
            return GRUB
        elif bytes == "\xFA\xEB":
            return LILO
        else:
            return None


def get_linux_boot_info(root_partition):
    """Use linux-boot-prober to find out how to boot this OS

    /dev/sdb1:/dev/sdb1::/boot/vmlinuz26:/boot/kernel26.img:root=/dev/sdb1

    """
    proc = sp.check_output(['linux-boot-prober', root_partition])
    hits = proc.split("\n")
    if not hits:
        return None
    line = hits[0]
    if ":" not in line:
        return None
    line = line.strip()
    root, boot, _, kernel, initrd, append = \
            [ i.strip() for i in line.split(":") ]
    return dict(root=root, kernel=kernel, initrd=initrd, append=append)


class FakeDeviceTestCase(unittest.TestCase):

    def setUp(self):
        (fd, self.path) = tempfile.mkstemp(prefix="fake-device-")
        f = os.fdopen(fd)
        f.seek(140000)
        os.write(fd, "0")

    def tearDown(self):
        os.unlink(self.path)


class LiloTestCase(FakeDeviceTestCase):

    def test_lilo(self):
        import os
        if not os.path.exists('/bin/lilo'):
            return True
        lilo = Lilo(self.path)
        for ops in OperatingSystem.all(include_running_os=True):
            lilo.add_os(ops)
        lilo.write_config(config_path="/tmp/lilo-test")
        lilo.test_install("/tmp/lilo-test", self.path)
        mbr = MasterBootRecord(self.path)
        self.assertEqual(mbr.bootloader(), LILO)


class Grub2TestCase(FakeDeviceTestCase):

    def test_grub2(self):
        return True
        grub2 = Grub2(self.path)
        grub2.write_config(config_path="/tmp/grub2-test")
        grub2.test_install("/tmp/grub2-test", self.path)
        mbr = MasterBootRecord(self.path)
        self.assertEqual(mbr.bootloader(), GRUB2)


if __name__ == "__main__":
    unittest.main()