Source

vinstall / vinstall / backend / bootloader.py

  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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
# 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
from vinstall.core import log

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

LOG = log.get_logger("bootloader_backend")

class LiloDotConfEntry(object):
    """Dummy wrapper for reading a lilo.conf.  Has absolutely no use at all.
    The only reason it exists is to do some unittesting"""
    root = None
    label = None

    @classmethod
    def all(cls, fpath):
	entries = []
	with open(fpath) as data:
	    for line in data:
		line = line.strip()
		if line.startswith("root") or \
		  line.startswith("other"):
		    entry = cls()
		    entry.root = line.split("=")[-1].strip()
		    yield entry

class Lilo(object):
    """LiLo bootloader

    """
    def __init__(self, target, default_os=None, timeout=3,
            vga_mode="788", bootloader_root=None):
	"""
	arguments:
		target: target device or partition where lilo will be installed
		default_os: default os to be booted after the timeout value if the user does not take action
		timeout: N in seconds the boot menu should be displayed
		vga_mode: vga mode used for boot menu and while booting
		bootloader_root: Path to root partition containing the bootloader config
		
	"""

        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 = []
	if not bootloader_root:
            self.lilo_root = utils.get_mounted("/")
	else:
	    self.lilo_root = bootloader_root
	self.bootloader_root = bootloader_root
        self.tamu = "/boot/tamu"
        if not os.path.exists(self.tamu):
            os.mkdir(self.tamu)


    def add_os(self, system):
	"""Add the information about this operating system to the
	class"""
        if system.type == "linux":
            self.add_unix_os(system)
        elif "chain" in system.type:
            self.add_ms_os(system)
        else:
            #XXX
            pass

    def copy_unix_bootdata(self, system):
	"""Copy the kernel and initrd to our partition
	if necessary"""
	
	umount = False
        if system.type != "linux":
	    return
	if system.os_root != self.bootloader_root:
	    # Mount the os root partition if needed
	    partition = media.Partition(system.root)
	    if not partition.is_mounted():
		umount = True
		if not os.path.exists(partition.mountpoint):
		    os.mkdir(partition.mountpoint)
		mountpoint = partition.mount(partition.mountpoint)
	    else:
		mountpoint = partition.mountpoint

	    # Copy the kernel to the local tamu path
	    kernel_from = mountpoint + system.kernel #XX: os.path.join wont work here!!
	    kernel_to = system.tamu_kernel_path

	    if not os.path.exists(os.path.split(kernel_to)[0]):
	        os.mkdir(os.path.split(kernel_to)[0])
	    shutil.copy2(kernel_from, kernel_to)

	    # Copy the initrd to the local tamu path
	    if system.initrd:
	        initrd_from = mountpoint + system.initrd #XX: os.path.join wont work here !!
	    	shutil.copy2(initrd_from, system.tamu_initrd_path)

        # un-mount the partition if necessary
	if umount:
	    partition.umount()

    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")

        # write config lines
        tab = " " * 4
        self.buffer.append("# -- %s on %s --" % (system.label,
            system.root))
	
	if system.root != self.bootloader_root:
	    self.buffer.append("image = %s"% system.tamu_kernel_path)
	    self.buffer.append("%s label = %s"% (tab, system.tamu_lilo_label))
	    if system.initrd:
	        self.buffer.append("%s initrd = %s"% (tab, system.tamu_initrd_path))
	else:
	    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))
	self.buffer.append("%s root = %s" % (tab, system.root))
#        if system.appendline:
#	    self.buffer.append('%s append = "%s"'% (tab, system.appendline))
# XX : ^^ The append line is very delicate and needs some processing.
# XX :
        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

        """
	tab = " " * 4
        self.buffer.append("# -- %s on %s --" % (system.long_desc, system.root))
        self.buffer.append("other = %s" % system.root)
        self.buffer.append("%s label = %s" % (tab, system.label))
        self.buffer.append("%s table = %s" % (tab, system.root[:-1]))
	self.operating_systems.append(system)
        
    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"
	if self.default_os:
	    default_os_line = "default = %s"% self.default_os.label
	else:
	    default_os_line = "#"
        header = (
            "# LILO configuration file.",
            "# ",
            "# Generated by VASM.",
            "# ",
            "boot = %s" % self.target,
	    default_os_line,
            "compact",
            "prompt",
            "timeout = %s" % self.timeout,
            "change-rules",
            "reset",
            "bitmap = /boot/bitmap/boot.bmp",
            "vga = 788",
            "# 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

        """
	for ops in self.operating_systems:
            self.copy_unix_bootdata(ops)
        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 GTUB_TERMINAL_OUTPUT=gfxterm",
                 "export GRUB_DISABLE_LINUX_UUID=true",
		 "export GRUB_FONT=/usr/share/grub/unifont.pf2",
                 "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",""]

        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

        """
        if os.path.exists("/usr/sbin/grub-mkdevicemap"):
            sp.check_call(["grub-mkdevicemap", "--no-floppy"])
        sp.check_call(["grub-install", "--no-floppy", self.target])

    def test_install(self, config_file, bootdev):
        if os.path.exists("/usr/sbin/grub-mkdevicemap"):
            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
    initrd = None	# Initial Ram Disk
    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]

    @property
    def initrd_name(self):
	if self.initrd:
	    return os.path.split(self.initrd)[-1]
	return None

    @property
    def os_root(self):
	return self.root

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

    @property 
    def tamu_kernel_path(self):
	return os.path.join("/boot/tamu/", "%s-%s"% (self.kernel_name, self._short_root))

    @property
    def tamu_initrd_path(self):
	rootpart = os.path.split(self.os_root)[-1]
	return os.path.join("/boot/tamu/","%s-%s"% ( self.initrd_name, self._short_root))

    @property
    def tamu_lilo_label(self):
	"""Return a lilo-friendly label for an OS on a foreign partition
	"""
	return "%s-%s"% (self.label, self._short_root)

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

        """
	if not op_data:
            op_data = sp.check_output(["os-prober", "&>/dev/null"])
        found_os = op_data.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()
	    LOG.debug("Found %s on %s"% (os_type, root))
            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, bp_data)
                if bootinfo is None:
                    continue
                operating_system.root = bootinfo["root"] #XX 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() or \
		    "chain" in os_type.lower():
		        operating_system.long_desc = long_desc
			operating_system.short_desc = short_desc
                        operating_system.root = root
			if "microsoft" in short_desc.lower() or \
			   "windows" in short_desc.lower():
			    operating_system.label = "Windows-%s"% os.path.split(root)[-1]
			else:
			    operating_system.label = "Other_OS-%s"% os.path.split(root)[-1] 
                        operating_system.type = "chain"
            #XXX what about bsd, osx, etc.  Will 'chain' cover them?
            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, data = None):
    """Use linux-boot-prober to find out how to boot this OS

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

    """
    if not data:
        data = sp.check_output(['linux-boot-prober', root_partition])
    else:
	data = "\n".join(
	    [ x for x in data.split("\n") if root_partition in x])
    hits = data.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")
	self.op_data = "\n".join(
		("/dev/sda1:Windows 7 (loader):Windows:chain",
		"/dev/sda2:VLocity 7.1 B2:Linux:linux",
		"/dev/sdb1:VectorLinux 7.1 B1.1:Linux:linux",
		"/dev/sdb2:Slackware Linux 14.1:Linux:linux"))
	self.bp_data = "\n".join(
	    ("/dev/sda2:/dev/sda2::/boot/vmlinuz:/boot/initrd:root=/dev/sda2",
		"/dev/sdb1:/dev/sdb1::/boot/vmlinuz:/boot/initrd:root=/dev/sdb1",
		"/dev/sdb2:/dev/sdb2::/boot/vmlinuz:/boot/initrd:root=/dev/sdb2"))

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


class LiloTestCase(FakeDeviceTestCase):

    def test_lilo(self):
        if not os.path.exists('/sbin/lilo'):
            return #XXX 
        lilo = Lilo(self.path)
        for ops in OperatingSystem.all(include_running_os=True,
	    op_data = self.op_data, bp_data = self.bp_data):
            lilo.add_os(ops)
        lilo.write_config(config_path="/tmp/lilo-test")
	# Test to make sure the entries got written to the config file
	found = [ entry.root for entry in LiloDotConfEntry.all('/tmp/lilo-test')]
	written = [ x.split(':')[0] for x in self.op_data.split("\n")]
	for i in written:
	    self.assertIn(i, found)
#        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 #XXX
        grub2 = Grub2(self.path, data = self.testdata)
        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()