2 # creator.py : ImageCreator and LoopImageCreator base classes
4 # Copyright 2007, Red Hat Inc.
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; version 2 of the License.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU Library General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
31 from imgcreate
.errors
import *
32 from imgcreate
.fs
import *
33 from imgcreate
.yuminst
import *
34 from imgcreate
import kickstart
37 """The maximum string length supported for LoopImageCreator.fslabel."""
39 class ImageCreator(object):
40 """Installs a system to a chroot directory.
42 ImageCreator is the simplest creator class available; it will install and
43 configure a system image according to the supplied kickstart file.
48 ks = imgcreate.read_kickstart("foo.ks")
49 imgcreate.ImageCreator(ks, "foo").create()
53 def __init__(self
, ks
, name
):
54 """Initialize an ImageCreator instance.
56 ks -- a pykickstart.KickstartParser instance; this instance will be
57 used to drive the install by e.g. providing the list of packages
58 to be installed, the system configuration and %post scripts
60 name -- a name for the image; used for e.g. image filenames or
65 """A pykickstart.KickstartParser instance."""
68 """A name for the image."""
70 self
.tmpdir
= "/var/tmp"
71 """The directory in which all temporary files will be created."""
73 self
.__builddir
= None
74 self
.__bindmounts
= []
84 def __get_instroot(self
):
85 if self
.__builddir
is None:
86 raise CreatorError("_instroot is not valid before calling mount()")
87 return self
.__builddir
+ "/install_root"
88 _instroot
= property(__get_instroot
)
89 """The location of the install root directory.
91 This is the directory into which the system is installed. Subclasses may
92 mount a filesystem image here or copy files to/from here.
94 Note, this directory does not exist before ImageCreator.mount() is called.
96 Note also, this is a read-only attribute.
100 def __get_outdir(self
):
101 if self
.__builddir
is None:
102 raise CreatorError("_outdir is not valid before calling mount()")
103 return self
.__builddir
+ "/out"
104 _outdir
= property(__get_outdir
)
105 """The staging location for the final image.
107 This is where subclasses should stage any files that are part of the final
108 image. ImageCreator.package() will copy any files found here into the
109 requested destination directory.
111 Note, this directory does not exist before ImageCreator.mount() is called.
113 Note also, this is a read-only attribute.
118 # Hooks for subclasses
120 def _mount_instroot(self
, base_on
= None):
121 """Mount or prepare the install root directory.
123 This is the hook where subclasses may prepare the install root by e.g.
124 mounting creating and loopback mounting a filesystem image to
127 There is no default implementation.
129 base_on -- this is the value passed to mount() and can be interpreted
130 as the subclass wishes; it might e.g. be the location of
131 a previously created ISO containing a system image.
136 def _unmount_instroot(self
):
137 """Undo anything performed in _mount_instroot().
139 This is the hook where subclasses must undo anything which was done
140 in _mount_instroot(). For example, if a filesystem image was mounted
141 onto _instroot, it should be unmounted here.
143 There is no default implementation.
148 def _create_bootconfig(self
):
149 """Configure the image so that it's bootable.
151 This is the hook where subclasses may prepare the image for booting by
152 e.g. creating an initramfs and bootloader configuration.
154 This hook is called while the install root is still mounted, after the
155 packages have been installed and the kickstart configuration has been
156 applied, but before the %post scripts have been executed.
158 There is no default implementation.
163 def _stage_final_image(self
):
164 """Stage the final system image in _outdir.
166 This is the hook where subclasses should place the image in _outdir
167 so that package() can copy it to the requested destination directory.
169 By default, this moves the install root into _outdir.
172 shutil
.move(self
._instroot
, self
._outdir
+ "/" + self
.name
)
174 def _get_required_packages(self
):
175 """Return a list of required packages.
177 This is the hook where subclasses may specify a set of packages which
178 it requires to be installed.
180 This returns an empty list by default.
182 Note, subclasses should usually chain up to the base class
183 implementation of this hook.
188 def _get_excluded_packages(self
):
189 """Return a list of excluded packages.
191 This is the hook where subclasses may specify a set of packages which
192 it requires _not_ to be installed.
194 This returns an empty list by default.
196 Note, subclasses should usually chain up to the base class
197 implementation of this hook.
202 def _get_fstab(self
):
203 """Return the desired contents of /etc/fstab.
205 This is the hook where subclasses may specify the contents of
206 /etc/fstab by returning a string containing the desired contents.
208 A sensible default implementation is provided.
211 s
= "/dev/root / %s defaults,noatime 0 0\n" %(self
._fstype
)
212 s
+= self
._get
_fstab
_special
()
215 def _get_fstab_special(self
):
216 s
= "devpts /dev/pts devpts gid=5,mode=620 0 0\n"
217 s
+= "tmpfs /dev/shm tmpfs defaults 0 0\n"
218 s
+= "proc /proc proc defaults 0 0\n"
219 s
+= "sysfs /sys sysfs defaults 0 0\n"
222 def _get_post_scripts_env(self
, in_chroot
):
223 """Return an environment dict for %post scripts.
225 This is the hook where subclasses may specify some environment
226 variables for %post scripts by return a dict containing the desired
229 By default, this returns an empty dict.
231 in_chroot -- whether this %post script is to be executed chroot()ed
237 def _get_kernel_versions(self
):
238 """Return a dict detailing the available kernel types/versions.
240 This is the hook where subclasses may override what kernel types and
241 versions should be available for e.g. creating the booloader
244 A dict should be returned mapping the available kernel types to a list
245 of the available versions for those kernels.
247 The default implementation uses rpm to iterate over everything
248 providing 'kernel', finds /boot/vmlinuz-* and returns the version
249 obtained from the vmlinuz filename. (This can differ from the kernel
250 RPM's n-v-r in the case of e.g. xen)
253 def get_version(header
):
255 for f
in header
['filenames']:
256 if f
.startswith('/boot/vmlinuz-'):
260 ts
= rpm
.TransactionSet(self
._instroot
)
263 for header
in ts
.dbMatch('provides', 'kernel'):
264 version
= get_version(header
)
268 name
= header
['name']
270 ret
[name
] = [version
]
271 elif not version
in ret
[name
]:
272 ret
[name
].append(version
)
277 # Helpers for subclasses
279 def _do_bindmounts(self
):
280 """Mount various system directories onto _instroot.
282 This method is called by mount(), but may also be used by subclasses
283 in order to re-mount the bindmounts after modifying the underlying
287 for b
in self
.__bindmounts
:
290 def _undo_bindmounts(self
):
291 """Unmount the bind-mounted system directories from _instroot.
293 This method is usually only called by unmount(), but may also be used
294 by subclasses in order to gain access to the filesystem obscured by
295 the bindmounts - e.g. in order to create device nodes on the image
299 self
.__bindmounts
.reverse()
300 for b
in self
.__bindmounts
:
304 """Chroot into the install root.
306 This method may be used by subclasses when executing programs inside
307 the install root e.g.
309 subprocess.call(["/bin/ls"], preexec_fn = self.chroot)
312 os
.chroot(self
._instroot
)
315 def _mkdtemp(self
, prefix
= "tmp-"):
316 """Create a temporary directory.
318 This method may be used by subclasses to create a temporary directory
319 for use in building the final image - e.g. a subclass might create
320 a temporary directory in order to bundle a set of files into a package.
322 The subclass may delete this directory if it wishes, but it will be
323 automatically deleted by cleanup().
325 The absolute path to the temporary directory is returned.
327 Note, this method should only be called after mount() has been called.
329 prefix -- a prefix which should be used when creating the directory;
333 self
.__ensure
_builddir
()
334 return tempfile
.mkdtemp(dir = self
.__builddir
, prefix
= prefix
)
336 def _mkstemp(self
, prefix
= "tmp-"):
337 """Create a temporary file.
339 This method may be used by subclasses to create a temporary file
340 for use in building the final image - e.g. a subclass might need
341 a temporary location to unpack a compressed file.
343 The subclass may delete this file if it wishes, but it will be
344 automatically deleted by cleanup().
346 A tuple containing a file descriptor (returned from os.open() and the
347 absolute path to the temporary directory is returned.
349 Note, this method should only be called after mount() has been called.
351 prefix -- a prefix which should be used when creating the file;
355 self
.__ensure
_builddir
()
356 return tempfile
.mkstemp(dir = self
.__builddir
, prefix
= prefix
)
358 def _mktemp(self
, prefix
= "tmp-"):
359 """Create a temporary file.
361 This method simply calls _mkstemp() and closes the returned file
364 The absolute path to the temporary file is returned.
366 Note, this method should only be called after mount() has been called.
368 prefix -- a prefix which should be used when creating the file;
373 (f
, path
) = self
._mkstemp
(prefix
)
378 # Actual implementation
380 def __ensure_builddir(self
):
381 if not self
.__builddir
is None:
385 self
.__builddir
= tempfile
.mkdtemp(dir = os
.path
.abspath(self
.tmpdir
),
386 prefix
= "imgcreate-")
387 except OSError, (err
, msg
):
388 raise CreatorError("Failed create build directory in %s: %s" %
391 def __sanity_check(self
):
392 """Ensure that the config we've been given is sane."""
393 if not (kickstart
.get_packages(self
.ks
) or
394 kickstart
.get_groups(self
.ks
)):
395 raise CreatorError("No packages or groups specified")
397 kickstart
.convert_method_to_repo(self
.ks
)
399 if not kickstart
.get_repos(self
.ks
):
400 raise CreatorError("No repositories specified")
402 def __write_fstab(self
):
403 fstab
= open(self
._instroot
+ "/etc/fstab", "w")
404 fstab
.write(self
._get
_fstab
())
407 def __create_minimal_dev(self
):
408 """Create a minimal /dev so that we don't corrupt the host /dev"""
409 origumask
= os
.umask(0000)
410 devices
= (('null', 1, 3, 0666),
411 ('urandom',1, 9, 0666),
412 ('random', 1, 8, 0666),
413 ('full', 1, 7, 0666),
414 ('ptmx', 5, 2, 0666),
416 ('zero', 1, 5, 0666))
417 links
= (("/proc/self/fd", "/dev/fd"),
418 ("/proc/self/fd/0", "/dev/stdin"),
419 ("/proc/self/fd/1", "/dev/stdout"),
420 ("/proc/self/fd/2", "/dev/stderr"))
422 for (node
, major
, minor
, perm
) in devices
:
423 if not os
.path
.exists(self
._instroot
+ "/dev/" + node
):
424 os
.mknod(self
._instroot
+ "/dev/" + node
, perm | stat
.S_IFCHR
, os
.makedev(major
,minor
))
425 for (src
, dest
) in links
:
426 if not os
.path
.exists(self
._instroot
+ dest
):
427 os
.symlink(src
, self
._instroot
+ dest
)
430 def __create_selinuxfs(self
):
431 # if selinux exists on the host we need to lie to the chroot
432 if os
.path
.exists("/selinux/enforce"):
433 selinux_dir
= self
._instroot
+ "/selinux"
435 # enforce=0 tells the chroot selinux is not enforcing
436 # policyvers=999 tell the chroot to make the highest version of policy it can
437 files
= (('/enforce', '0'),
438 ('/policyvers', '999'))
439 for (file, value
) in files
:
440 fd
= os
.open(selinux_dir
+ file, os
.O_WRONLY | os
.O_TRUNC | os
.O_CREAT
)
444 # we steal mls from the host system for now, might be best to always set it to 1????
447 shutil
.copyfile("/selinux" + file, selinux_dir
+ file)
449 # make /load -> /dev/null so chroot policy loads don't hurt anything
450 os
.mknod(selinux_dir
+ "/load", 0666 | stat
.S_IFCHR
, os
.makedev(1, 3))
452 # selinux is on in the kickstart, so clean up as best we can to start
453 if kickstart
.selinux_enabled(self
.ks
):
454 # label the fs like it is a root before the bind mounting
455 arglist
= ["/sbin/setfiles", "-F", "-r", self
._instroot
, selinux
.selinux_file_context_path(), self
._instroot
]
456 subprocess
.call(arglist
, close_fds
= True)
458 def __destroy_selinuxfs(self
):
459 # if the system was running selinux clean up our lies
460 if os
.path
.exists("/selinux/enforce"):
467 os
.unlink(self
._instroot
+ "/selinux" + file)
472 def mount(self
, base_on
= None, cachedir
= None):
473 """Setup the target filesystem in preparation for an install.
475 This function sets up the filesystem which the ImageCreator will
476 install into and configure. The ImageCreator class merely creates an
477 install root directory, bind mounts some system directories (e.g. /dev)
478 and writes out /etc/fstab. Other subclasses may also e.g. create a
479 sparse file, format it and loopback mount it to the install root.
481 base_on -- a previous install on which to base this install; defaults
482 to None, causing a new image to be created
484 cachedir -- a directory in which to store the Yum cache; defaults to
485 None, causing a new cache to be created; by setting this
486 to another directory, the same cache can be reused across
490 self
.__ensure
_builddir
()
492 makedirs(self
._instroot
)
493 makedirs(self
._outdir
)
495 self
._mount
_instroot
(base_on
)
497 for d
in ("/dev/pts", "/etc", "/boot", "/var/log", "/var/cache/yum", "/sys", "/proc", "/selinux"):
498 makedirs(self
._instroot
+ d
)
500 cachesrc
= cachedir
or (self
.__builddir
+ "/yum-cache")
503 # bind mount system directories into _instroot
504 for (f
, dest
) in [("/sys", None), ("/proc", None),
506 (cachesrc
, "/var/cache/yum")]:
507 self
.__bindmounts
.append(BindChrootMount(f
, self
._instroot
, dest
))
509 #self.__create_selinuxfs()
510 # revert to bindmounting /selinux
511 # fake selinuxfs does not work for EL-5
513 # /selinux should only be mounted if selinux is enabled (enforcing or permissive)
514 if kickstart
.selinux_enabled(self
.ks
):
515 self
.__bindmounts
.append(BindChrootMount("/selinux", self
._instroot
, None))
517 self
._do
_bindmounts
()
519 self
.__create
_minimal
_dev
()
521 os
.symlink("../proc/mounts", self
._instroot
+ "/etc/mtab")
526 """Unmounts the target filesystem.
528 The ImageCreator class detaches the system from the install root, but
529 other subclasses may also detach the loopback mounted filesystem image
530 from the install root.
534 os
.unlink(self
._instroot
+ "/etc/mtab")
538 #self.__destroy_selinuxfs()
540 self
._undo
_bindmounts
()
542 self
._unmount
_instroot
()
545 """Unmounts the target filesystem and deletes temporary files.
547 This method calls unmount() and then deletes any temporary files and
548 directories that were created on the host system while building the
551 Note, make sure to call this method once finished with the creator
552 instance in order to ensure no stale files are left on the host e.g.:
554 creator = ImageCreator(ks, name)
561 if not self
.__builddir
:
566 shutil
.rmtree(self
.__builddir
, ignore_errors
= True)
567 self
.__builddir
= None
569 def __select_packages(self
, ayum
):
571 for pkg
in kickstart
.get_packages(self
.ks
,
572 self
._get
_required
_packages
()):
574 ayum
.selectPackage(pkg
)
575 except yum
.Errors
.InstallError
, e
:
576 if kickstart
.ignore_missing(self
.ks
):
577 skipped_pkgs
.append(pkg
)
579 raise CreatorError("Failed to find package '%s' : %s" %
582 for pkg
in skipped_pkgs
:
583 logging
.warn("Skipping missing package '%s'" % (pkg
,))
585 def __select_groups(self
, ayum
):
587 for group
in kickstart
.get_groups(self
.ks
):
589 ayum
.selectGroup(group
.name
, group
.include
)
590 except (yum
.Errors
.InstallError
, yum
.Errors
.GroupsError
), e
:
591 if kickstart
.ignore_missing(self
.ks
):
592 raise CreatorError("Failed to find group '%s' : %s" %
595 skipped_groups
.append(group
)
597 for group
in skipped_groups
:
598 logging
.warn("Skipping missing group '%s'" % (group
.name
,))
600 def __deselect_packages(self
, ayum
):
601 for pkg
in kickstart
.get_excluded(self
.ks
,
602 self
._get
_excluded
_packages
()):
603 ayum
.deselectPackage(pkg
)
605 # if the system is running selinux and the kickstart wants it disabled
606 # we need /usr/sbin/lokkit
607 def __can_handle_selinux(self
, ayum
):
608 file = "/usr/sbin/lokkit"
609 if not kickstart
.selinux_enabled(self
.ks
) and os
.path
.exists("/selinux/enforce") and not ayum
.installHasFile(file):
610 raise CreatorError("Unable to disable SELinux because the installed package set did not include the file %s" % (file))
612 def install(self
, repo_urls
= {}):
613 """Install packages into the install root.
615 This function installs the packages listed in the supplied kickstart
616 into the install root. By default, the packages are installed from the
617 repository URLs specified in the kickstart.
619 repo_urls -- a dict which maps a repository name to a repository URL;
620 if supplied, this causes any repository URLs specified in
621 the kickstart to be overridden.
624 yum_conf
= self
._mktemp
(prefix
= "yum.conf-")
627 ayum
.setup(yum_conf
, self
._instroot
)
629 for repo
in kickstart
.get_repos(self
.ks
, repo_urls
):
630 (name
, baseurl
, mirrorlist
, inc
, exc
) = repo
632 yr
= ayum
.addRepository(name
, baseurl
, mirrorlist
)
638 if kickstart
.exclude_docs(self
.ks
):
639 rpm
.addMacro("_excludedocs", "1")
640 if not kickstart
.selinux_enabled(self
.ks
):
641 rpm
.addMacro("__file_context_path", "%{nil}")
642 if kickstart
.inst_langs(self
.ks
) != None:
643 rpm
.addMacro("_install_langs", kickstart
.inst_langs(self
.ks
))
647 self
.__select
_packages
(ayum
)
648 self
.__select
_groups
(ayum
)
649 self
.__deselect
_packages
(ayum
)
651 self
.__can
_handle
_selinux
(ayum
)
654 except yum
.Errors
.RepoError
, e
:
655 raise CreatorError("Unable to download from repo : %s" % (e
,))
656 except yum
.Errors
.YumBaseError
, e
:
657 raise CreatorError("Unable to install: %s" % (e
,))
663 # do some clean up to avoid lvm info leakage. this sucks.
664 for subdir
in ("cache", "backup", "archive"):
665 lvmdir
= self
._instroot
+ "/etc/lvm/" + subdir
667 for f
in os
.listdir(lvmdir
):
668 os
.unlink(lvmdir
+ "/" + f
)
672 def __run_post_scripts(self
):
673 for s
in kickstart
.get_post_scripts(self
.ks
):
674 (fd
, path
) = tempfile
.mkstemp(prefix
= "ks-script-",
675 dir = self
._instroot
+ "/tmp")
677 os
.write(fd
, s
.script
)
681 env
= self
._get
_post
_scripts
_env
(s
.inChroot
)
684 env
["INSTALL_ROOT"] = self
._instroot
688 preexec
= self
._chroot
689 script
= "/tmp/" + os
.path
.basename(path
)
693 subprocess
.call([s
.interp
, script
],
694 preexec_fn
= preexec
, env
= env
)
695 except OSError, (err
, msg
):
696 raise CreatorError("Failed to execute %%post script "
697 "with '%s' : %s" % (s
.interp
, msg
))
702 """Configure the system image according to the kickstart.
704 This method applies the (e.g. keyboard or network) configuration
705 specified in the kickstart and executes the kickstart %post scripts.
707 If neccessary, it also prepares the image to be bootable by e.g.
708 creating an initrd and bootloader configuration.
711 ksh
= self
.ks
.handler
713 kickstart
.LanguageConfig(self
._instroot
).apply(ksh
.lang
)
714 kickstart
.KeyboardConfig(self
._instroot
).apply(ksh
.keyboard
)
715 kickstart
.TimezoneConfig(self
._instroot
).apply(ksh
.timezone
)
716 kickstart
.AuthConfig(self
._instroot
).apply(ksh
.authconfig
)
717 kickstart
.FirewallConfig(self
._instroot
).apply(ksh
.firewall
)
718 kickstart
.RootPasswordConfig(self
._instroot
).apply(ksh
.rootpw
)
719 kickstart
.ServicesConfig(self
._instroot
).apply(ksh
.services
)
720 kickstart
.XConfig(self
._instroot
).apply(ksh
.xconfig
)
721 kickstart
.NetworkConfig(self
._instroot
).apply(ksh
.network
)
722 kickstart
.RPMMacroConfig(self
._instroot
).apply(self
.ks
)
724 self
._create
_bootconfig
()
726 self
.__run
_post
_scripts
()
728 # selinux should always come last
729 kickstart
.SelinuxConfig(self
._instroot
).apply(ksh
.selinux
)
731 def launch_shell(self
):
732 """Launch a shell in the install root.
734 This method is launches a bash shell chroot()ed in the install root;
735 this can be useful for debugging.
738 subprocess
.call(["/bin/bash"], preexec_fn
= self
._chroot
)
740 def package(self
, destdir
= "."):
741 """Prepares the created image for final delivery.
743 In its simplest form, this method merely copies the install root to the
744 supplied destination directory; other subclasses may choose to package
745 the image by e.g. creating a bootable ISO containing the image and
746 bootloader configuration.
748 destdir -- the directory into which the final image should be moved;
749 this defaults to the current directory.
752 self
._stage
_final
_image
()
754 for f
in os
.listdir(self
._outdir
):
755 shutil
.move(os
.path
.join(self
._outdir
, f
),
756 os
.path
.join(destdir
, f
))
759 """Install, configure and package an image.
761 This method is a utility method which creates and image by calling some
762 of the other methods in the following order - mount(), install(),
763 configure(), unmount and package().
772 class LoopImageCreator(ImageCreator
):
773 """Installs a system into a loopback-mountable filesystem image.
775 LoopImageCreator is a straightforward ImageCreator subclass; the system
776 is installed into an ext3 filesystem on a sparse file which can be
777 subsequently loopback-mounted.
781 def __init__(self
, ks
, name
, fslabel
= None):
782 """Initialize a LoopImageCreator instance.
784 This method takes the same arguments as ImageCreator.__init__() with
787 fslabel -- A string used as a label for any filesystems created.
790 ImageCreator
.__init
__(self
, ks
, name
)
792 self
.__fslabel
= None
793 self
.fslabel
= fslabel
795 self
.__minsize
_KB
= 0
796 self
.__blocksize
= 4096
797 self
.__fstype
= kickstart
.get_image_fstype(self
.ks
, "ext3")
799 self
.__instloop
= None
802 self
.__image
_size
= kickstart
.get_image_size(self
.ks
,
808 def __get_fslabel(self
):
809 if self
.__fslabel
is None:
812 return self
.__fslabel
813 def __set_fslabel(self
, val
):
815 self
.__fslabel
= None
817 self
.__fslabel
= val
[:FSLABEL_MAXLEN
]
818 fslabel
= property(__get_fslabel
, __set_fslabel
)
819 """A string used to label any filesystems created.
821 Some filesystems impose a constraint on the maximum allowed size of the
822 filesystem label. In the case of ext3 it's 16 characters, but in the case
823 of ISO9660 it's 32 characters.
825 mke2fs silently truncates the label, but mkisofs aborts if the label is too
826 long. So, for convenience sake, any string assigned to this attribute is
827 silently truncated to FSLABEL_MAXLEN (32) characters.
831 def __get_image(self
):
832 if self
.__imgdir
is None:
833 raise CreatorError("_image is not valid before calling mount()")
834 return self
.__imgdir
+ "/ext3fs.img"
835 _image
= property(__get_image
)
836 """The location of the image file.
838 This is the path to the filesystem image. Subclasses may use this path
839 in order to package the image in _stage_final_image().
841 Note, this directory does not exist before ImageCreator.mount() is called.
843 Note also, this is a read-only attribute.
847 def __get_blocksize(self
):
848 return self
.__blocksize
849 def __set_blocksize(self
, val
):
851 raise CreatorError("_blocksize must be set before calling mount()")
853 self
.__blocksize
= int(val
)
855 raise CreatorError("'%s' is not a valid integer value "
856 "for _blocksize" % val
)
857 _blocksize
= property(__get_blocksize
, __set_blocksize
)
858 """The block size used by the image's filesystem.
860 This is the block size used when creating the filesystem image. Subclasses
861 may change this if they wish to use something other than a 4k block size.
863 Note, this attribute may only be set before calling mount().
867 def __get_fstype(self
):
869 def __set_fstype(self
, val
):
870 if val
not in ("ext2", "ext3", "ext4"):
871 raise CreatorError("Unknown _fstype '%s' supplied" % val
)
873 _fstype
= property(__get_fstype
, __set_fstype
)
874 """The type of filesystem used for the image.
876 This is the filesystem type used when creating the filesystem image.
877 Subclasses may change this if they wish to use something other ext3.
879 Note, only ext2, ext3, ext4 are currently supported.
881 Note also, this attribute may only be set before calling mount().
886 # Helpers for subclasses
888 def _resparse(self
, size
= None):
889 """Rebuild the filesystem image to be as sparse as possible.
891 This method should be used by subclasses when staging the final image
892 in order to reduce the actual space taken up by the sparse image file
893 to be as little as possible.
895 This is done by resizing the filesystem to the minimal size (thereby
896 eliminating any space taken up by deleted files) and then resizing it
897 back to the supplied size.
899 size -- the size in, in bytes, which the filesystem image should be
900 resized to after it has been minimized; this defaults to None,
901 causing the original size specified by the kickstart file to
902 be used (or 4GiB if not specified in the kickstart).
905 return self
.__instloop
.resparse(size
)
907 def _base_on(self
, base_on
):
908 shutil
.copyfile(base_on
, self
._image
)
911 # Actual implementation
913 def _mount_instroot(self
, base_on
= None):
914 self
.__imgdir
= self
._mkdtemp
()
916 if not base_on
is None:
917 self
._base
_on
(base_on
)
919 self
.__instloop
= ExtDiskMount(SparseLoopbackDisk(self
._image
, self
.__image
_size
),
926 self
.__instloop
.mount()
927 except MountError
, e
:
928 raise CreatorError("Failed to loopback mount '%s' : %s" %
931 def _unmount_instroot(self
):
932 if not self
.__instloop
is None:
933 self
.__instloop
.cleanup()
935 def _stage_final_image(self
):
937 shutil
.move(self
._image
, self
._outdir
+ "/" + self
.name
+ ".img")