Source

vinstall / vinstall / controller / automatic.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
#-*- coding: utf-8 -*-

"""Automatic install first screen

"""


from vinstall.core import Render, Controller, model
from vinstall.backend import media,  utils,  partitioning
from vinstall.backend import fstab
from vinstall.backend import users
from vinstall.backend import service
from vinstall.backend import bootloader
import vinstall.controller.intro as intro
import os, subprocess
import glob
import shutil

class AutomaticMode(Controller):
    """Automatic install mode. We will look for devices suitable for
    installation and let the user pick one.

    """
    # Controller interface
    ROOT_FS="ext3"

    def init(self):
        """Initialize some objects

        """
        self.disks = self.find_disks()

    def render(self):
        """Show available disks for user selection

        """
        title = "Target location"
        intro = "Select a disk for Vector. Data in the disk will be overwritten"
        options = [ {"name": str(i)} for i in self.disks ]
        options = model.ExclusiveOptionList(*options)
        return Render(title, intro, options)

    def process(self, *_):
        """Mount source media so we can read available packages

        """
        self.mount_source()

    def command(self, diskindex):
        """Schedule all the necessary steps for installation.
        Use yield to return a function and a tuple with the arguments needed
        for calling it.

        """
        disk = self.get_disk(diskindex)

        yield self.partitioning, (disk,), "Partitioning %s" % disk
        yield self.format_partitions, (disk,), "Formating partitions"
        yield self.mount_target, (disk,), "Mounting target"

        yield self.preinstall, tuple(), "Preparing package install"
        for package in self.packages():
            yield self.installpkg, (package, disk), "Installing %s" % package.split("/")[-1]
        yield self.postinstall, tuple(), "Installing setup routines"
        yield self.install_kernel, tuple(), "Installing Linux kernel"

        yield self.set_bind_mounts, tuple(), "Mounting pseudo filesystems"
        yield self.fstab, (disk,), "Creating fstab"
        yield self.setup_services, tuple(), "Setting up services"
        yield self.vector_version, tuple(), "Writting /etc/vector-version"
        yield self.bootloader, (disk,), "Installing bootloader"
        yield self.clear_bind_mounts, tuple(), "Clearing bind mounts"

    def previous(self):
        """Go back to the first screen

        """
        return intro.Introduction

    def next(self):
        """Jump to the basic Setup

        """
        return Setup

    # utility methods

    def find_disks(self):
        """Find the disks available in the system.

        """
        return [ i for i in media.Disk.all() ]

    def get_disk(self, index):
        """Return a disk object from index

        """
        return self.disks[index]

    def partitioning(self, disk):
        """Do automatic partitioning in disk

        """
        print "Partitioning", disk

        if not self._check_continue():
            return

        available_ram = int(utils.get_mem_size())

        if available_ram <= 512:
            swap_size = 2 * available_ram
        elif available_ram < 1024:
            swap_size = 1024
        else:
            swap_size = int(available_ram / 2)

        disk_size = disk.size(unit="MiB")
        partitioner = partitioning.DiskPartitioner(disk)
        if not disk.has_partition_table:
            print "Creating partition table"
            partitioner.create_partition_table()
        else:
            partitioner.delete_all_partitions()
        
        root_size = disk_size - swap_size
        partitioner.add_partition(size=root_size, units='MiB')
        partitioner.add_partition(size=swap_size-1, units='MiB')
        partitioner.write_changes()


    def format_partitions(self, disk):
        """Format partitions in disk with the default filesystem

        """
        print "Formatting partitions in", disk

        if not self._check_continue():
            return

        proot = "%s%s" % (disk.path(), 1)
        pswap = "%s%s" % (disk.path(), 2)
        # make sure our partitions are not mounted before we attempt to
        # format them.  Especially the target's /
        utils.umount('/mnt/TARGET')
        utils.format_partition(proot, self.ROOT_FS)
        utils.format_partition(pswap, 'swap')
        utils.activate_swap(pswap)

    def mount_source(self):
        """Mount the install media

        """
        mountpoint = "/mnt/SOURCE"
        if not os.path.exists(mountpoint):
            os.mkdir(mountpoint)
        install_media = self.config["install_media"]
        if install_media.is_iso():
            utils.mountiso(install_media.path, mountpoint)
        else:
            utils.mount(install_media.path, mountpoint, filesystem="auto")

    def mount_target(self, disk):
        """Mount target partitions

        """
        mountpoint = "/mnt/TARGET"
        if not os.path.exists(mountpoint):
            os.mkdir(mountpoint)
        partition = "%s%s" % (disk.path(), 1)
        utils.mount(partition, mountpoint, filesystem="auto")

    def packages(self):
        """Return a sequence of package objects for installing.
        In automatic mode this should be every package in the iso.

        """
        print "Looking for packages"
        excluded =("vlconfig2", "vlsetup", "aaa_base")
        for root, dirs, files in os.walk("/mnt/SOURCE/packages"):
            for file in files:
                fname, fext = os.path.splitext(file)
                if fext in (".txz",".tlz",".tgz"):
                    name = file.rsplit("-", 3)[0]
                    if name not in excluded:
                        yield os.path.join(root, file)

    def installpkg(self, package, disk):
        """Install package in the disk root partition

        """
        print "Installing %s in %s" % (package, disk)
        command = "/usr/sbin/installpkg %s --root=%s" % (package, "/mnt/TARGET")
        if self._check_continue():
            subprocess.check_call(command.split())

    def preinstall(self):
        """Run before installing packages, used for installing required
        packages first.

        """
        if not self._check_continue():
            return

        aaa = glob.glob("/mnt/SOURCE/packages/a/aaa_base-*.t?z")[0]
        self.installpkg(aaa, "/mnt/TARGET")

    def postinstall(self):
        """Run after installing packages, use for packages needing to be
        installed at last, or for post install required tasks.

        """
        if not self._check_continue():
            return

        vlconfig = glob.glob("/mnt/SOURCE/packages/a/vlconfig2-*.t?z")[0]
        self.installpkg(vlconfig, "/mnt/TARGET")

    def install_kernel(self):
        """Copy the kernel from the initrd to the target

        kernel is in the ISO as 'sata' in isolinux/kernel/
        Represented in VINSTALL.INI as "sata=version"

        """
        if not self._check_continue():
            return

        install_media = self.config["install_media"]
        kernel_version = install_media.config.get("kernels", "sata")
        kernel_version = kernel_version.replace("\"", "")
        source = os.path.join('/mnt', 'SOURCE', 'isolinux', 'kernel',
                'sata')
        target = os.path.join('/mnt', 'TARGET', 'boot', 'vmlinuz-%s' %
            kernel_version)
        shutil.copyfile(source, target)

    def fstab(self, disk):
        """Create and install a fstab file in disk

        """
        print "Installing fstab in", disk
        if not self._check_continue():
            return

        fstab_obj = fstab.Fstab("/mnt/TARGET/etc/fstab")
        root_entry = fstab.FstabEntry(device = "%s1" % disk.path(),
                mountpoint = "/", filesystem = self.ROOT_FS)
        swap_entry = fstab.FstabEntry(device = "%s2" % disk.path(),
                mountpoint = "none", filesystem="swap")
        for entry in (root_entry, swap_entry):
            fstab_obj.add_entry(entry)

    def setup_services(self):
        """Setup default system services

        """
        #XXX:  Define the default set of services for each runlevel
        # At some other location so they can be used by advanced.py too

        if not self._check_continue():
            return

        svcbasic = [ "cron", "portmap", "lm_sensors", "gpm", "inetd" ]
        svc2 = svcbasic[:]
        svc3 = svcbasic[:]
        svc3.extend(["samba", "cups", "sshd"])
        svc4 = svcbasic[:]
        svc4.extend(["bluetooth", "fuse", "cups"])
        svc5 = svc3[:]
        svc5.extend(["bluetooth", "fuse"])

        for svc in service.Service.all("/mnt/TARGET"):
            for s, runlevel in ((svc2, 2), (svc3, 3), (svc4, 4), (svc5, 5)):
                if svc.name in s:
                    svc.enable(runlevel)

    def bootloader(self, disk):
        """Install the default bootloader in disk

        """
        print "Installing bootloader in", disk

        if not self._check_continue():
            return

        vga_size = "800x600"
        vga_quality = "16"
        timeout = 5
        grub = bootloader.Grub2(target=disk.path(), vga_size=vga_size,
                vga_quality=vga_quality, timeout=timeout)
        with utils.Chroot("/mnt/TARGET"):
            grub.write_config("/etc/default/grub")
            grub.install()

    def vector_version(self):
        """write /etc/vector-version based on the information
        in VINSTALL.INI

        """
        print "Writing vector-version"

        if not self._check_continue():
            return

        install_media = self.config["install_media"]
        distro = install_media.config.get("general", "distro").replace("\"", "")
        version = install_media.config.get("general", "version").replace("\"", "")
        build_date = install_media.config.get("general",
                "build_date").replace("\"", "")
        vector_version =  "%s built on %s\n" % (version, build_date)
        with open("/mnt/TARGET/etc/vector-version", 'w') as f:
            f.write(vector_version)

    def set_bind_mounts(self):
        """Bind mount some paths into the target.
        Later steps will need this when we chroot there

        """
        if not self._check_continue():
            return

        for point in ("sys","proc","dev"):
            cmd = "mount -o bind /%s /mnt/TARGET/%s" % (point, point)
            subprocess.check_call(cmd.split())

    def clear_bind_mounts(self):
        """Clear the mountpoints that were mounted for the configuration

        """
        if not self._check_continue():
            return

        for point in ("sys","proc","dev"):
            cmd = "umount -f /mnt/TARGET/%s" % point
            subprocess.check_call(cmd.split())

    def _check_continue(self):
        return 'I_MEAN_IT' in os.environ



class Setup(Controller):
    """Minimal configuration - Ask for username and passwords

    """
    def render(self):
        """Ask for username and passwords

        """
        username = model.TextOption("Username")
        password = model.TextOption("Password")
        rootpassword = model.TextOption("Admin password")
        title = "Passwords"
        intro = "Setup your user account and administrator password"
        return Render(title, intro, username, password, rootpassword)

    def next(self):
        """This is the last stage in automatic mode, return None

        """
        return None

    def previous(self):
        """Return the previous step

        """
        return AutomaticMode

    def command(self, username, password, rootpassword):
        """Create a user and setup passwords

        """
        yield self.set_root_password, (rootpassword,), "Creating users"
        yield self.create_user_account, (username, password), "Setting passwords"

    def set_root_password(self, rootpassword):
        """Set the root password

        """
        if not self._check_continue():
            return

        admin = users.User()
        admin.root = "/mnt/TARGET"
        admin.login = "root"
        with utils.Chroot("/mnt/TARGET"):
            admin.change_password(rootpassword)

    def create_user_account(self, username, userpassword):
        """Create a user account and set its password

        """
        if not self._check_continue():
            return

        account = users.User()
        account.root = "/mnt/TARGET"
        account.login = username
        account.password = userpassword
        with utils.Chroot("/mnt/TARGET"):
            account.create()

    def _check_continue(self):
        return 'I_MEAN_IT' in os.environ