Source

vasm / modules / bootloaders.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
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
#!/usr/bin/env python

#    This file is part of VASM.
#
#    VASM is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License v3 as published by
#    the Free Software Foundation.
#
#    VASM 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 VASM.  If not, see <http://www.gnu.org/licenses/>.

__author__ = "Moises Henriquez"
__author_email__ = "moc.liamg@xnl.E0M"[::-1]

import gtk
import gobject
import os
from support import widgets
from support import dialogs
from support.vectorlinux import BOOTLOADERS, FSTAB
from support.vectorlinux.utils import _, get_popen, logger
import threading
import time


# some constans for the actions to be performed here
bootloader_install = -1
bootloader_refresh = -2

class WideLabel(gtk.Label):
    def __init__(self, markup, wide=0):
        gtk.Label.__init__(self)
        self.set_markup(markup)
        self.set_property('xalign', 0.0)
        if wide > 0:
            self.set_property('width-chars', wide)

class FlaggedThread(threading.Thread):
    def __init__(self, flag, target):
        self.flag = flag
        self.target = target
        threading.Thread.__init__(self)
    
    def run(self):
        self.target()
        self.flag.set()

class BootloaderInstallProgress(gtk.Dialog):
    """ Pop-up dialog window to be displayed when the bootloader is being
    installed or the menu is being refreshed.
    
    Arguments:
        blobject = one of BOOTLOADERS.GRUB2 or BOOTLOADERS.LILO object
            this is the model object that is to be used to interact with the 
            system.  This object's properties should be setup before calling 
            this class.
        action = one of (bootloader_install or bootloader_refresh)"""
    def __init__(self, parent=None, blobject=None, action=None):
        self._errors = False
        gtk.Dialog.__init__(self, parent=parent, buttons=None)
        self.blobject = blobject
        self.action = action
        self.flag = threading.Event()
        self.connect('close', self.do_exit)
        self.connect('response', self.do_response)
        self.set_size_request(350, 150)
        self.set_title(parent.get_title())
        if action == bootloader_install:
            self.message = (
            _("Installing"), blobject.type, _("on"),
            blobject.target +  ". ", _("Please wait."))
        else:
            self.message = (
            _("Refreshing"),blobject.type, _("boot menu") + ". ",
            _("Please wait ..."))
        self.body = self.get_content_area()
        self.set_has_separator(True)
        self.label = widgets.DLabel(" ".join(self.message))
        msgbox = gtk.HBox()
        msgbox.pack_start(self.label, True, True, 4)
        self.body.pack_start(msgbox, False, True, 8)
        
        # the progressbar
        self.progressbox = gtk.HBox()
        self.progressbar = gtk.ProgressBar()
        self.progressbar.set_text(_("Bootloader update in progress"))
        self.progressbox.pack_start(self.progressbar, True, True, 4)
        self.body.pack_start(self.progressbox, False, True, 8)
        self.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE)
        self.button = self.get_action_area().get_children()[0]
        self.body.show_all()
        self.do_apply()
    
    def do_exit(self, widget=None):
        """ stop all threads and then close """
        self.cleanup()
        return super(BootloaderInstallProgress).close()
    
    def do_response(self, widget=None, id=None):
        """ stop all threads before we exit """
        return self.cleanup()
    
    def cleanup(self):
        """ signal all running threads to stop """
        self.flag.set()
    
    def do_apply(self):
        """ Create and launch threads to perform actions """
        # thread to pulse the progressbar 
        self.pthread = threading.Thread(target=self.pulse_pb, args=())
        self.pthread.start()
        
        # worker thread
        self.wthread = FlaggedThread(flag=self.flag, target=self.act)
        self.wthread.start()
    
    def act(self):
        """ Action to be performed """
        # Decide what to do based on the type of bootloader and the
        # chosen action
        methods = []
        if self.blobject.type == "GRUB2":
            if self.action == bootloader_install:
                # do the install
                methods.append(self.blobject.install)
                methods.append(self.blobject.refresh_menu)                
            elif self.action == bootloader_refresh:
                # do the refresh
                methods.append(self.blobject.refresh_menu)
        elif self.blobject.type == "LiLO":
            # for lilo, it's all the same, you still have to re-write the target.
            methods.append(self.blobject.install)
        
        # execute the methods
        for f in methods:                
            logger.debug("Executing %s"% f)
            try:
                f()
            except AssertionError, e:
                self._errors = True
                self.flag.set()
                logger.fatal("%s"%e)
            time.sleep(1)
    
    def pulse_pb(self):
        """ pulse the progress bar """
        while not self.flag.is_set():
            self.progressbar.pulse()
            self.button.set_property('sensitive', False)
            time.sleep(0.1)
        
        self.button.set_property('sensitive', True)
        return self.indicate_done()
        # change the text of the message
        #self.progressbar.set_text(_("All operations complete."))
        #self.message = (_("All operations were performed."),
        #    _("Reboot your system to see your changes."))
        #self.label.set_markup(" ".join(self.message))
        
        
    def indicate_done(self):
        """ Change the dialog's contents according to the results """
        self.progressbox.set_property('visible', False)
        if self._errors:
            msg = (_("Some errors were reported while saving changes."),
            " ", _("Please try again before you restart your system."),
            " ", _("See /var/log/vasm.log for details."))
        else:
            msg = (_("Changes were applied successfully."))
        
        self.label.set_markup("".join(msg))
        
        
        

class VectorBootLoaders(widgets.VasmModule):
    def __init__(self, parent):
        self.vga_quality = "high"
        self._partitions = FSTAB.list_all_system_partitions()
        self._drives = FSTAB.list_all_system_drives()
        # indicate which one is the bootsector (lilo tradition)
        sector = BOOTLOADERS.get_current_bootsector()
        i = self._partitions.index(sector)
        self._warning = (
        "<b>%s</b>"% _("WARNING:"),
        _("You are about to over-write your system bootloader."),
        " ", "<b>%s</b>"% _("DO NOT INTERRUPT THIS PROCESS."),
        " ", _("Interrupting this process will render your system unbootable."),
        _("Are you sure you want to continue?"))
        self._partitions[i] = "Bootsector"
        tx = (
            _("Select which bootloader you would like to use from the options below."),
            "\n\n"
            "<b>%s</b>"% _("WARNING:"),
            _("This tool will over-write the target you select below."),
            " <b>%s</b>"% _("Selecting the wrong options here could render your system unbootable.")
            )
        widgets.VasmModule.__init__(self, parent,
                                    _("System Boot Menu"), ' '.join(tx))
        topsep = gtk.HSeparator()
        self.pack_start(topsep, False, True, 0)
        choicesbox = gtk.HBox()
        lb = WideLabel("<b>%s</b>"%_("Bootloader:"))
        
        choicesbox.pack_start(lb, False, False, 4)
        active = BOOTLOADERS.get_active_bootloader() or BOOTLOADERS.DEFAULT_BOOTLOADER
        self.bootloader = active.lower()
        self._lilorb = gtk.RadioButton(label="LILO")
        self._grubrb = gtk.RadioButton(group=self._lilorb,
                                       label = "GRUB2")
        for opt in (self._lilorb, self._grubrb):
            choicesbox.pack_start(opt, False, False, 8)
        self.pack_start(choicesbox, False, True, 4)
        # target box
        targetbox = gtk.HBox()
        tgtlb = WideLabel("<b>%s</b>"%_("Installation Target: "))
        targetbox.pack_start(tgtlb, False, False, 4)
        
        # add a dropdown box to select the target.
        model = gtk.ListStore(str)
        self.targetselector = gtk.ComboBox(model)
        cr = gtk.CellRendererText()
        self.targetselector.pack_start(cr, True)
        self.targetselector.add_attribute(cr, 'text', 0)
        self.targetselector.connect('changed', self.target_change_event)
        # populate partitions list
        targetbox.pack_start(self.targetselector, False, False, 4)
        self.pack_start(targetbox, False, True, 4)
        
        # Add the timeout option
        tbox = gtk.HBox()
        tadj = gtk.Adjustment(0.0, 0.0, 60.0, 1.0, 5.0, 0.0)
        lb = WideLabel("<b>%s</b>"%_("Timeout"))
        timer = gtk.SpinButton(tadj)
        timer.set_numeric(True)
        timer.connect('value-changed', self.timeout_change_event)
        timer.set_value(5.0)
        tbox.pack_start(lb, False, False, 4)
        tbox.pack_start(timer, False, False, 4)
        tbox.pack_start(gtk.Label(_("seconds")), False, False, 2)
        targetbox.pack_start(tbox, True, True, 4)
        #self.pack_start(tbox, False, True, 4)
        
        # Add a dropdown box for the vga selection mode.
        model = gtk.ListStore(str)
        model.append(["1280x1024"])
        model.append(["1024x768"])
        model.append(["800x600"])
        model.append(["648x480"])        
        cr = gtk.CellRendererText()
        self.vgaselector = gtk.ComboBox(model)
        self.vgaselector.pack_start(cr, True)
        self.vgaselector.add_attribute(cr, 'text', 0)
        self.vgaselector.set_active(0)
        self.vgaselector.connect('changed', self.vgamode_change_event)
        vgabox = gtk.HBox()
        lb = WideLabel("<b>%s</b>"% _("Video Resolution"))
        vgabox.pack_start(lb, False, False, 4)
        vgabox.pack_start(self.vgaselector, False, False, 4)
        self.pack_start(vgabox, False, True, 4)
        
        # action to perform
        optionsbox = gtk.VBox()
        tx = _("Select one of the following actions to be performed.")
        lb = widgets.DLabel(tx)
        optionsbox.pack_start(lb, False, True, 4)
        rb0 = gtk.RadioButton(None,
            label = _("Install bootloader and (re)create boot menu."))
        rb0.data = bootloader_install
        rb1 = gtk.RadioButton(rb0,
            label = _("Refresh boot menu only."))
        rb1.data = bootloader_refresh
        for rb in rb0, rb1:
            optionsbox.pack_start(rb, False, True, 4)
            rb.connect('toggled', self.action_toggle)
        rb1.set_active(True)
        hoptionsbox = gtk.HBox()
        hoptionsbox.pack_start(optionsbox, True, True, 4)
        self.pack_start(hoptionsbox, False, True, 12)
    
        for opt in (self._lilorb, self._grubrb):
            opt.connect('toggled', self.bootloader_toggle)
        
        # module action buttons.
        self.add_button((gtk.Button(stock=gtk.STOCK_CANCEL), self.close_module))
        self.apply_button = gtk.Button(stock=gtk.STOCK_APPLY)
        self._apply_id = self.apply_button.connect('clicked', self.fake_apply)
        self.add_button(self.apply_button)

        # set the current value.
        # This will trigger video resolution and modes to be populated correctly.
        for loader in self._grubrb, self._lilorb:
            if loader.get_label() == active:
                loader.set_active(True)
                self.populate_targets(self.targetselector, active.upper() == "LILO")
                self.populate_video_modes(active.upper() == "GRUB2")
                self.vgaselector.set_active(1)
                break
    
    def fake_apply(self, button=None):
        """ Just a place holder for the apply button.
        setup """
        if self._lilorb.get_active():
            return self.apply_lilo_event()
        elif self._grubrb.get_active():
            return self.apply_grub2_event()
    
    def apply_lilo_event(self, button=None):
        """ Apply event for when lilo is the selected bootloader """
        res = dialogs.question(" ".join(self._warning), parent = self._parent)
        if res == gtk.RESPONSE_NO:
            return
        # create the model class
        loader = BOOTLOADERS.LILO(
            target = self.target,
            timeout = self.timeout,
            vga_size = self.vga_size,
            vga_quality = self.vga_quality or self.vidqualityselector.get_active_text(),
            include_running_os=True)
        # Pop a progress
        progress = BootloaderInstallProgress(self._parent,loader, self.todo)
        logger.debug("Saving changes to LiLO setup.")
        response = progress.run()
        progress.hide()
        _errors = progress._errors
        progress.destroy()
        if _errors is True:
            # something wen wrong.
            msg = (
                _("Something went wrong during the lilo setup."),
                " ", _("See /var/log/vasm.log for details"))
            return dialogs.error(" ".join(msg), parent=self._parent)
        #return dialogs.info(
        #    _("All operations succeeded.  Reboot to see your changes."),
        #    parent = self._parent)
    
    def apply_grub2_event(self, button=None):
        """ Apply event for when grub2 is the selected bootloader """
        res = dialogs.question(" ".join(self._warning), parent = self._parent)
        if res == gtk.RESPONSE_NO:
            return
        
        # create the grub2 model object
        loader = BOOTLOADERS.GRUB2(
            target = self.target,
            timeout = self.timeout,
            vga_size = self.vga_size,
            vga_quality = self.vga_quality)        
        logger.debug("Saving changes to Grub2 setup.")
        # pop a progress dialog because this will take a long time to complete.
        progress = BootloaderInstallProgress(
            self._parent, loader, self.todo)
        response = progress.run()
        progress.hide()
        _errors = progress._errors
        progress.destroy()
        if _errors is True:
            msg = (
                _("Something went wrong during the grub2 setup."),
                " ", _("See /var/log/vasm.log for details"))
            return dialogs.error("".join(msg), parent = self._parent)
        #return dialogs.info(
        #    _("No errors where reported.  Reboot to see your changes."),
        #    parent = self._parent)
    
    def vgaquality_toggle(self, combobox):
        """ Set the vga quality to the selected value """
        self.vga_quality = combobox.get_active_text()
    
    def vgamode_change_event(self, combo):
        """ Set the vga resolution size to the selected value """
        self.vga_size = combo.get_active_text()
    
    def populate_targets(self, combo, include_partitions=False):
        """ Disable targets that are unavailable for each bootloader"""
        model = combo.get_model()
        model.clear()
        targets = []
        bootsector = BOOTLOADERS.get_current_bootsector()
        targets.extend(self._drives)
        if include_partitions is True:
            targets.extend(self._partitions)
        targets.sort()
        for target in targets:
            model.append([target])
        return combo.set_active(0)

    def display_valid_video_quality_values(self, grub2=False):
        """ Hide invalid resolution sizes for the selected bootloader """
        model = self.vidqualityselector.get_model()
        model.clear()
        if grub2 is True:
            model.append(["med"])
            return self.vidqualityselector.set_active(0)
        else:
            for value in ("low", "med", "high"):
                model.append([value])
        return self.vidqualityselector.set_active(1)
    
    def populate_video_modes(self, grub2=False):
        """ Remove the unfitter video modes for the different bootloaders """
        model = self.vgaselector.get_model()
        model.clear()
        for mode in ("640x480","800x600","1024x768","1280x1024"):
            model.append([mode])
        self.vgaselector.set_active(1)
        return
    
    def timeout_change_event(self, spinner):
        """ Update the timeout value """
        self.timeout = spinner.get_value()
    
    def target_change_event(self, cb):
        """ Update the installation target """
        self.target = cb.get_active_text()
    
    def bootloader_toggle(self, radiobutton):
        """ Update video values depending on which bootloader is selected """
        if radiobutton.get_active() is True:
            self.bootloader = radiobutton.get_label().lower()
        if self.bootloader.lower() == "lilo":
            self.populate_video_modes(False)
            # connect the correct method for the apply button
            self.apply_button.disconnect(self._apply_id)
            self._apply_id = self.apply_button.connect('clicked',
                self.apply_lilo_event)
            return self.populate_targets(self.targetselector, True)
        self.populate_video_modes(True)
        # connect the grub2 apply event to the apply button
        self.apply_button.disconnect(self._apply_id)
        self._apply_id = self.apply_button.connect('clicked',
            self.apply_grub2_event)
        return self.populate_targets(self.targetselector)
    
    def action_toggle(self, radiobutton):
        """ Update the todo variable.  The variable is contained in
        radiobutton.data and is either "install" or "refresh".
        This defines what the apply button does when clicked """
        if radiobutton.get_active() is True:
            self.todo = radiobutton.data

def __vasm_test__():
    return os.geteuid() == 0

def __run__(parent=None):
    w = VectorBootLoaders(parent)
    return w.launch()

VASM_CATEGORY = "%s/%s"% (_("System"), _("Startup Options"))
VASM_LABEL=_("System Boot Menu")
VASM_ICON=os.path.join(os.getcwd(), "modules/support/data/icons/bootmenu.png")