summaryrefslogtreecommitdiffstats
path: root/livecd.py
blob: 77133448d7507f3ed6cd44083fe90c236e654517 (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
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
#
# An anaconda backend to do an install from a live CD image
#
# The basic idea is that with a live CD, we already have an install
# and should be able to just copy those bits over to the disk.  So we dd
# the image, move things to the "right" filesystem as needed, and then
# resize the rootfs to the size of its container.
#
# Copyright 2007  Red Hat, Inc.
# Jeremy Katz <katzj@redhat.com>
#
# This software may be freely redistributed under the terms of the GNU
# general public license.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#

import os, sys
import stat
import shutil
import time
import subprocess

from rhpl.translate import _, N_

from flags import flags
from constants import *

import backend
import installmethod
import isys
import iutil

import packages

import logging
log = logging.getLogger("anaconda")

def copytree(src, dst, symlinks=False):
    # copy of shutil.copytree which doesn't require dst to not exist
    names = os.listdir(src)
    if not os.path.isdir(dst):
        os.makedirs(dst)
    errors = []
    for name in names:
        srcname = os.path.join(src, name)
        dstname = os.path.join(dst, name)
        try:
            if symlinks and os.path.islink(srcname):
                linkto = os.readlink(srcname)
                os.symlink(linkto, dstname)
            elif os.path.isdir(srcname):
                copytree(srcname, dstname, symlinks)
            else:
                shutil.copy2(srcname, dstname)
            # XXX What about devices, sockets etc.?
        except (IOError, os.error), why:
            errors.append((srcname, dstname, str(why)))
        # catch the Error from the recursive copytree so that we can
        # continue with other files
        except Error, err:
            errors.extend(err.args[0])
    try:
        shutil.copystat(src, dst)
    except OSError, why:
        errors.extend((src, dst, str(why)))
    if errors:
        raise Error, errors

class LiveCDImageMethod(installmethod.InstallMethod):
    def __init__(self, method, rootpath, intf):
        """@param method livecd://live-block-device"""
        installmethod.InstallMethod.__init__(self, method, rootpath, intf)

        self.osimg = method[8:]
        if not stat.S_ISBLK(os.stat(self.osimg)[stat.ST_MODE]):
            intf.messageWindow(_("Unable to find image"),
                               _("The given location isn't a valid %s "
                                 "live CD to use as an installation source.")
                               %(productName,), type = "custom",
                               custom_icon="error",
                               custom_buttons=[_("Exit installer")])
            sys.exit(0)

    def postAction(self, anaconda):
        # unmount things that aren't listed in /etc/fstab.  *sigh*
        for dir in ("/selinux", "/dev"):
            try:
                isys.umount("%s/%s" %(anaconda.rootPath,dir), removeDir = 0)
            except Exception, e:
                log.error("unable to unmount %s: %s" %(d, e))

        try:
            anaconda.id.fsset.umountFilesystems(anaconda.rootPath,
                                                swapoff = False)
            os.rmdir(anaconda.rootPath)
        except Exception, e:
            log.error("Unable to unmount filesystems.") 

    def protectedPartitions(self):
        if os.path.exists("/dev/live") and \
           stat.S_ISBLK(os.stat("/dev/live")[stat.ST_MODE]):
            target = os.readlink("/dev/live")
            return [target]
        return []

    def getFilename(self, filename, callback=None, destdir=None, retry=1):
        if filename.startswith("RELEASE-NOTES"):
            return "/usr/share/doc/HTML/" + filename

    def getLiveBlockDevice(self):
        return self.osimg

    def getLiveSizeMB(self):
        lnk = os.readlink(self.osimg)
        if lnk[0] != "/":
            lnk = os.path.join(os.path.dirname(self.osimg), lnk)
        blk = os.path.basename(lnk)

        if not os.path.exists("/sys/block/%s/size" %(blk,)):
            log.debug("Unable to determine the actual size of the live image")
            return 0

        size = open("/sys/block/%s/size" %(blk,), "r").read()
        try:
            size = int(size)
        except ValueError:
            log.debug("Unable to handle live size conversion: %s" %(size,))
            return 0

        return (size * 512) / 1024 / 1024
        

class LiveCDCopyBackend(backend.AnacondaBackend):
    def __init__(self, method, instPath):
        backend.AnacondaBackend.__init__(self, method, instPath)
        self.supportsUpgrades = False
        self.supportsPackageSelection = False

    def doPreInstall(self, anaconda):
        if anaconda.dir == DISPATCH_BACK:
            for d in ("/selinux", "/dev"):
                try:
                    isys.umount(anaconda.rootPath + d, removeDir = 0)
                except Exception, e:
                    log.error("unable to unmount %s: %s" %(d, e))
            return

        anaconda.id.fsset.umountFilesystems(anaconda.rootPath, swapoff = False)

    def doInstall(self, anaconda):
        log.info("Preparing to install packages")
        if flags.test:
            log.info("Test mode - not performing install")
            return

        progress = anaconda.id.instProgress
        progress.set_label(_("Copying live image to hard drive."))
        progress.processEvents()

        osimg = anaconda.method.getLiveBlockDevice() # the real image
        osfd = os.open(osimg, os.O_RDONLY)

        r = anaconda.id.fsset.getEntryByMountPoint("/")
        rootfs = r.device.getDevice()
        rootfd = os.open("/dev/" + rootfs, os.O_WRONLY)

        readamt = 1024 * 1024 * 8 # 8 megs at a time
        size = float(anaconda.method.getLiveSizeMB() * 1024 * 1024)
        copied = 0
        while copied < size:
            buf = os.read(osfd, readamt)
            written = os.write(rootfd, buf)
            if (written < readamt) and (written < len(buf)):
                raise RuntimeError, "error copying filesystem!"
            copied += written
            progress.set_fraction(pct = copied / size)
            progress.processEvents()

        os.close(osfd)
        os.close(rootfd)

        anaconda.id.instProgress = None

    def _doFilesystemMangling(self, anaconda):
        log.info("doing post-install fs mangling")
        wait = anaconda.intf.waitWindow(_("Doing post-installation"),
                                        _("Performing post-installation filesystem changes.  This may take several minutes..."))

        # remount filesystems
        anaconda.id.fsset.mountFilesystems(anaconda)

        # restore the label of / to what we think it is (XXX: UUID?)
        r = anaconda.id.fsset.getEntryByMountPoint("/")        
        r.fsystem.labelDevice(r, anaconda.rootPath)

        # for any filesystem that's _not_ on the root, we need to handle
        # moving the bits from the livecd -> the real filesystems.
        # this could be more clever by starting at the deepest part of
        # the fsys tree, but this will do for now
        for entry in anaconda.id.fsset.entries:
            if entry.fsystem.isKernelFS():
                continue

            tocopy = entry.getMountPoint()

            if tocopy is None or tocopy == "/" or tocopy.startswith("/mnt") or tocopy == "swap":
                continue

            # FIXME: all calls to wait.refresh() are kind of a hack... we
            # should do better about not doing blocking things in the
            # main thread.  but threading anaconda is a job for another
            # time.
            wait.refresh()

            log.info("doing the copy for %s" %(tocopy,))
            entry.umount(anaconda.rootPath)
            entry.mount(anaconda.rootPath + "/mnt")
            # XXX: should use something with selinux knowledge...
            copytree("%s/%s" %(anaconda.rootPath, tocopy),
                     "%s/mnt/%s" %(anaconda.rootPath, tocopy))
            shutil.rmtree("%s/%s" %(anaconda.rootPath, tocopy))
            wait.refresh()            
            entry.umount(anaconda.rootPath + "/mnt")
            entry.mount(anaconda.rootPath)
            try:
                os.rmdir("%s/mnt/%s" %(anaconda.rootPath, tocopy))
            except OSError, e:
                log.debug("error removing %s" %(tocopy,))
                pass

            wait.refresh()
            # XXX: we should be preserving contexts on our copy, but
            # this will do for now
            for dir, subdirs, files in os.walk(os.path.normpath("%s/%s" %(anaconda.rootPath, tocopy))):
                dir = dir[len(anaconda.rootPath):]
                for f in map(lambda x: "%s/%s" %(dir, x), files) + [dir]:
                    if not os.access("%s/%s" %(anaconda.rootPath, f), os.R_OK):
                        continue
                    ret = isys.resetFileContext(os.path.normpath(f),
                                                anaconda.rootPath)
                    log.info("set fc of %s to %s" %(f, ret))
            wait.refresh()                    

        # ensure that non-fstab filesystems are mounted in the chroot
        if flags.selinux:
            try:
                isys.mount("/selinux", anaconda.rootPath + "/selinux", "selinuxfs")
            except Exception, e:
                log.error("error mounting selinuxfs: %s" %(e,))
        isys.mount("/dev", "%s/dev" %(anaconda.rootPath,), bindMount = 1)

        self._resizeRootfs(anaconda, wait)
        wait.pop()

    def _resizeRootfs(self, anaconda, win = None):
        log.info("going to do resize")
        r = anaconda.id.fsset.getEntryByMountPoint("/")        
        rootdev = r.device.getDevice()

        # FIXME: we'd like to have progress here to give an idea of
        # how long it will take.  or at least, to give an indefinite
        # progress window.  but, not for this time
        cmd = ["resize2fs", "/dev/%s" %(rootdev,), "-p"]
        out = open("/dev/tty5", "w")
        proc = subprocess.Popen(cmd, stdout=out, stderr=out)
        rc = proc.poll()
        while rc is None:
            win and win.refresh()
            time.sleep(0.5)
            rc = proc.poll()

        if rc:
            log.error("error running resize2fs; leaving filesystem as is")

    def doPostInstall(self, anaconda):
        self._doFilesystemMangling(anaconda)

        # maybe heavy handed, but it'll do
        anaconda.id.bootloader.args.append("rhgb quiet")
        anaconda.id.desktop.setDefaultRunLevel(5)

        # now write out the "real" fstab and mtab
        anaconda.id.fsset.write(anaconda.rootPath)
        f = open(anaconda.rootPath + "/etc/mtab", "w+")
        f.write(anaconda.id.fsset.mtab())
        f.close()        

        # rebuild the initrd(s)
        vers = self.kernelVersionList()
        for (n, arch, tag) in vers:
            packages.recreateInitrd(n, anaconda.rootPath)

    def writeConfiguration(self):
        pass

    def kernelVersionList(self):
        versions = []
        
        # FIXME: we should understand more types of kernel versions and not
        # be tied to rpm...  
        import rpm
        ts = rpm.TransactionSet()
        mi = ts.dbMatch('name', 'kernel')
        for h in mi:
            v = "%s-%s" %(h['version'], h['release'])
            versions.append( (v, h['arch'], "base") )

        return versions

    def doInitialSetup(self, anaconda):
        pass
    def doRepoSetup(self, anaconda):
        # ensure there's enough space on the rootfs
        # FIXME: really, this should be in the general sanity checking, but
        # trying to weave that in is a little tricky at present.
        ossize = anaconda.method.getLiveSizeMB()
        slash = anaconda.id.partitions.getRequestByMountPoint("/")
        if slash and \
           slash.getActualSize(anaconda.id.partitions, anaconda.id.diskset) < ossize:
            rc = anaconda.intf.messageWindow(_("Error"),
                                        ("The root filesystem you created is "
                                         "not large enough for this live "
                                         "image."), type = "custom",
                                        custom_icon = "error",
                                        custom_buttons=[_("Back"),
                                                        _("Exit installer")])
            if rc == 0:
                return DISPATCH_BACK
            else:
                sys.exit(1)
        

    # package/group selection doesn't apply for this backend
    def groupExists(self, group):
        pass
    def selectGroup(self, group, *args):
        pass
    def deselectGroup(self, group, *args):
        pass
    def selectPackage(self, pkg, *args):
        pass
    def deselectPackage(self, pkg, *args):
        pass
    def packageExists(self, pkg):
        return True
    def getDefaultGroups(self, anaconda):
        return []
    def writePackagesKS(self, f):
        pass