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.
32 from imgcreate
.errors
import *
33 from imgcreate
.fs
import *
34 from imgcreate
.yuminst
import *
35 from imgcreate
import kickstart
38 """The maximum string length supported for LoopImageCreator.fslabel."""
40 class ImageCreator(object):
41 """Installs a system to a chroot directory.
43 ImageCreator is the simplest creator class available; it will install and
44 configure a system image according to the supplied kickstart file.
49 ks = imgcreate.read_kickstart("foo.ks")
50 imgcreate.ImageCreator(ks, "foo").create()
54 def __init__(self
, ks
, name
, releasever
=None):
55 """Initialize an ImageCreator instance.
57 ks -- a pykickstart.KickstartParser instance; this instance will be
58 used to drive the install by e.g. providing the list of packages
59 to be installed, the system configuration and %post scripts
61 name -- a name for the image; used for e.g. image filenames or
64 releasever -- Value to substitute for $releasever in repo urls
67 """A pykickstart.KickstartParser instance."""
70 """A name for the image."""
72 self
.releasever
= releasever
74 self
.tmpdir
= "/var/tmp"
75 """The directory in which all temporary files will be created."""
77 self
.__builddir
= None
78 self
.__bindmounts
= []
88 def __get_instroot(self
):
89 if self
.__builddir
is None:
90 raise CreatorError("_instroot is not valid before calling mount()")
91 return self
.__builddir
+ "/install_root"
92 _instroot
= property(__get_instroot
)
93 """The location of the install root directory.
95 This is the directory into which the system is installed. Subclasses may
96 mount a filesystem image here or copy files to/from here.
98 Note, this directory does not exist before ImageCreator.mount() is called.
100 Note also, this is a read-only attribute.
104 def __get_outdir(self
):
105 if self
.__builddir
is None:
106 raise CreatorError("_outdir is not valid before calling mount()")
107 return self
.__builddir
+ "/out"
108 _outdir
= property(__get_outdir
)
109 """The staging location for the final image.
111 This is where subclasses should stage any files that are part of the final
112 image. ImageCreator.package() will copy any files found here into the
113 requested destination directory.
115 Note, this directory does not exist before ImageCreator.mount() is called.
117 Note also, this is a read-only attribute.
122 # Hooks for subclasses
124 def _mount_instroot(self
, base_on
= None):
125 """Mount or prepare the install root directory.
127 This is the hook where subclasses may prepare the install root by e.g.
128 mounting creating and loopback mounting a filesystem image to
131 There is no default implementation.
133 base_on -- this is the value passed to mount() and can be interpreted
134 as the subclass wishes; it might e.g. be the location of
135 a previously created ISO containing a system image.
140 def _unmount_instroot(self
):
141 """Undo anything performed in _mount_instroot().
143 This is the hook where subclasses must undo anything which was done
144 in _mount_instroot(). For example, if a filesystem image was mounted
145 onto _instroot, it should be unmounted here.
147 There is no default implementation.
152 def _create_bootconfig(self
):
153 """Configure the image so that it's bootable.
155 This is the hook where subclasses may prepare the image for booting by
156 e.g. creating an initramfs and bootloader configuration.
158 This hook is called while the install root is still mounted, after the
159 packages have been installed and the kickstart configuration has been
160 applied, but before the %post scripts have been executed.
162 There is no default implementation.
167 def _stage_final_image(self
):
168 """Stage the final system image in _outdir.
170 This is the hook where subclasses should place the image in _outdir
171 so that package() can copy it to the requested destination directory.
173 By default, this moves the install root into _outdir.
176 shutil
.move(self
._instroot
, self
._outdir
+ "/" + self
.name
)
178 def _get_required_packages(self
):
179 """Return a list of required packages.
181 This is the hook where subclasses may specify a set of packages which
182 it requires to be installed.
184 This returns an empty list by default.
186 Note, subclasses should usually chain up to the base class
187 implementation of this hook.
192 def _get_excluded_packages(self
):
193 """Return a list of excluded packages.
195 This is the hook where subclasses may specify a set of packages which
196 it requires _not_ to be installed.
198 This returns an empty list by default.
200 Note, subclasses should usually chain up to the base class
201 implementation of this hook.
206 def _get_fstab(self
):
207 """Return the desired contents of /etc/fstab.
209 This is the hook where subclasses may specify the contents of
210 /etc/fstab by returning a string containing the desired contents.
212 A sensible default implementation is provided.
215 s
= "/dev/root / %s defaults,noatime 0 0\n" %(self
._fstype
)
216 s
+= self
._get
_fstab
_special
()
219 def _get_fstab_special(self
):
220 s
= "devpts /dev/pts devpts gid=5,mode=620 0 0\n"
221 s
+= "tmpfs /dev/shm tmpfs defaults 0 0\n"
222 s
+= "proc /proc proc defaults 0 0\n"
223 s
+= "sysfs /sys sysfs defaults 0 0\n"
226 def _get_post_scripts_env(self
, in_chroot
):
227 """Return an environment dict for %post scripts.
229 This is the hook where subclasses may specify some environment
230 variables for %post scripts by return a dict containing the desired
233 By default, this returns an empty dict.
235 in_chroot -- whether this %post script is to be executed chroot()ed
241 def _get_kernel_versions(self
):
242 """Return a dict detailing the available kernel types/versions.
244 This is the hook where subclasses may override what kernel types and
245 versions should be available for e.g. creating the booloader
248 A dict should be returned mapping the available kernel types to a list
249 of the available versions for those kernels.
251 The default implementation uses rpm to iterate over everything
252 providing 'kernel', finds /boot/vmlinuz-* and returns the version
253 obtained from the vmlinuz filename. (This can differ from the kernel
254 RPM's n-v-r in the case of e.g. xen)
257 def get_version(header
):
259 for f
in header
['filenames']:
260 if f
.startswith('/boot/vmlinuz-'):
264 ts
= rpm
.TransactionSet(self
._instroot
)
267 for header
in ts
.dbMatch('provides', 'kernel'):
268 version
= get_version(header
)
272 name
= header
['name']
274 ret
[name
] = [version
]
275 elif not version
in ret
[name
]:
276 ret
[name
].append(version
)
281 # Helpers for subclasses
283 def _do_bindmounts(self
):
284 """Mount various system directories onto _instroot.
286 This method is called by mount(), but may also be used by subclasses
287 in order to re-mount the bindmounts after modifying the underlying
291 for b
in self
.__bindmounts
:
294 def _undo_bindmounts(self
):
295 """Unmount the bind-mounted system directories from _instroot.
297 This method is usually only called by unmount(), but may also be used
298 by subclasses in order to gain access to the filesystem obscured by
299 the bindmounts - e.g. in order to create device nodes on the image
303 self
.__bindmounts
.reverse()
304 for b
in self
.__bindmounts
:
308 """Chroot into the install root.
310 This method may be used by subclasses when executing programs inside
311 the install root e.g.
313 subprocess.call(["/bin/ls"], preexec_fn = self.chroot)
316 os
.chroot(self
._instroot
)
319 def _mkdtemp(self
, prefix
= "tmp-"):
320 """Create a temporary directory.
322 This method may be used by subclasses to create a temporary directory
323 for use in building the final image - e.g. a subclass might create
324 a temporary directory in order to bundle a set of files into a package.
326 The subclass may delete this directory if it wishes, but it will be
327 automatically deleted by cleanup().
329 The absolute path to the temporary directory is returned.
331 Note, this method should only be called after mount() has been called.
333 prefix -- a prefix which should be used when creating the directory;
337 self
.__ensure
_builddir
()
338 return tempfile
.mkdtemp(dir = self
.__builddir
, prefix
= prefix
)
340 def _mkstemp(self
, prefix
= "tmp-"):
341 """Create a temporary file.
343 This method may be used by subclasses to create a temporary file
344 for use in building the final image - e.g. a subclass might need
345 a temporary location to unpack a compressed file.
347 The subclass may delete this file if it wishes, but it will be
348 automatically deleted by cleanup().
350 A tuple containing a file descriptor (returned from os.open() and the
351 absolute path to the temporary directory is returned.
353 Note, this method should only be called after mount() has been called.
355 prefix -- a prefix which should be used when creating the file;
359 self
.__ensure
_builddir
()
360 return tempfile
.mkstemp(dir = self
.__builddir
, prefix
= prefix
)
362 def _mktemp(self
, prefix
= "tmp-"):
363 """Create a temporary file.
365 This method simply calls _mkstemp() and closes the returned file
368 The absolute path to the temporary file is returned.
370 Note, this method should only be called after mount() has been called.
372 prefix -- a prefix which should be used when creating the file;
377 (f
, path
) = self
._mkstemp
(prefix
)
382 # Actual implementation
384 def __ensure_builddir(self
):
385 if not self
.__builddir
is None:
389 self
.__builddir
= tempfile
.mkdtemp(dir = os
.path
.abspath(self
.tmpdir
),
390 prefix
= "imgcreate-")
392 raise CreatorError("Failed create build directory in %s: %s" %
393 (self
.tmpdir
, e
.strerror
))
395 def __sanity_check(self
):
396 """Ensure that the config we've been given is sane."""
397 if not (kickstart
.get_packages(self
.ks
) or
398 kickstart
.get_groups(self
.ks
)):
399 raise CreatorError("No packages or groups specified")
401 kickstart
.convert_method_to_repo(self
.ks
)
403 if not kickstart
.get_repos(self
.ks
):
404 raise CreatorError("No repositories specified")
406 def __write_fstab(self
):
407 fstab
= open(self
._instroot
+ "/etc/fstab", "w")
408 fstab
.write(self
._get
_fstab
())
411 def __create_minimal_dev(self
):
412 """Create a minimal /dev so that we don't corrupt the host /dev"""
413 origumask
= os
.umask(0000)
414 devices
= (('null', 1, 3, 0666),
415 ('urandom',1, 9, 0666),
416 ('random', 1, 8, 0666),
417 ('full', 1, 7, 0666),
418 ('ptmx', 5, 2, 0666),
420 ('zero', 1, 5, 0666))
421 links
= (("/proc/self/fd", "/dev/fd"),
422 ("/proc/self/fd/0", "/dev/stdin"),
423 ("/proc/self/fd/1", "/dev/stdout"),
424 ("/proc/self/fd/2", "/dev/stderr"))
426 for (node
, major
, minor
, perm
) in devices
:
427 if not os
.path
.exists(self
._instroot
+ "/dev/" + node
):
428 os
.mknod(self
._instroot
+ "/dev/" + node
, perm | stat
.S_IFCHR
, os
.makedev(major
,minor
))
429 for (src
, dest
) in links
:
430 if not os
.path
.exists(self
._instroot
+ dest
):
431 os
.symlink(src
, self
._instroot
+ dest
)
434 def __getbooleans(self
):
436 if not kickstart
.selinux_enabled(self
.ks
) or not os
.path
.exists("/selinux/enforce"):
438 for i
in selinux
.security_get_boolean_names()[1]:
439 on
= selinux
.security_get_boolean_active(i
)
440 booleans
.append(("/booleans/%s" % i
, "%d %d" % (on
, on
)))
443 def __create_selinuxfs(self
):
444 # if selinux exists on the host we need to lie to the chroot
445 if os
.path
.exists("/selinux/enforce"):
446 selinux_dir
= self
._instroot
+ "/selinux"
448 # enforce=0 tells the chroot selinux is not enforcing
449 # policyvers=999 tell the chroot to make the highest version of policy it can
451 files
= [('/enforce', '0'),
452 ('/policyvers', '999'),
453 ('/commit_pending_bools', ''),
454 ('/mls', str(selinux
.is_selinux_mls_enabled()))]
456 for (file, value
) in files
+ self
.__getbooleans
():
457 fd
= os
.open(selinux_dir
+ file, os
.O_WRONLY | os
.O_TRUNC | os
.O_CREAT
)
461 # we steal mls from the host system for now, might be best to always set it to 1????
462 # make /load -> /dev/null so chroot policy loads don't hurt anything
463 os
.mknod(selinux_dir
+ "/load", 0666 | stat
.S_IFCHR
, os
.makedev(1, 3))
465 # selinux is on in the kickstart, so clean up as best we can to start
466 if kickstart
.selinux_enabled(self
.ks
):
467 # label the fs like it is a root before the bind mounting
468 arglist
= ["/sbin/setfiles", "-F", "-r", self
._instroot
, selinux
.selinux_file_context_path(), self
._instroot
]
469 subprocess
.call(arglist
, close_fds
= True)
471 def __destroy_selinuxfs(self
):
472 # if the system was running selinux clean up our lies
473 if os
.path
.exists("/selinux/enforce"):
474 for root
, dirs
, files
in os
.walk(self
._instroot
+ "/selinux"):
477 os
.remove(os
.path
.join(root
, name
))
481 if os
.path
.join(root
, name
) == self
._instroot
+ "/selinux":
484 os
.rmdir(os
.path
.join(root
, name
))
488 def mount(self
, base_on
= None, cachedir
= None):
489 """Setup the target filesystem in preparation for an install.
491 This function sets up the filesystem which the ImageCreator will
492 install into and configure. The ImageCreator class merely creates an
493 install root directory, bind mounts some system directories (e.g. /dev)
494 and writes out /etc/fstab. Other subclasses may also e.g. create a
495 sparse file, format it and loopback mount it to the install root.
497 base_on -- a previous install on which to base this install; defaults
498 to None, causing a new image to be created
500 cachedir -- a directory in which to store the Yum cache; defaults to
501 None, causing a new cache to be created; by setting this
502 to another directory, the same cache can be reused across
506 self
.__ensure
_builddir
()
508 makedirs(self
._instroot
)
509 makedirs(self
._outdir
)
511 self
._mount
_instroot
(base_on
)
513 for d
in ("/dev/pts", "/etc", "/boot", "/var/log", "/var/cache/yum", "/sys", "/proc", "/selinux/booleans"):
514 makedirs(self
._instroot
+ d
)
516 cachesrc
= cachedir
or (self
.__builddir
+ "/yum-cache")
519 # bind mount system directories into _instroot
520 for (f
, dest
) in [("/sys", None), ("/proc", None),
521 ("/dev/pts", None), ("/dev/shm", None),
522 (cachesrc
, "/var/cache/yum")]:
523 self
.__bindmounts
.append(BindChrootMount(f
, self
._instroot
, dest
))
525 self
.__create
_selinuxfs
()
527 self
._do
_bindmounts
()
529 self
.__create
_minimal
_dev
()
531 os
.symlink("../proc/mounts", self
._instroot
+ "/etc/mtab")
536 """Unmounts the target filesystem.
538 The ImageCreator class detaches the system from the install root, but
539 other subclasses may also detach the loopback mounted filesystem image
540 from the install root.
544 os
.unlink(self
._instroot
+ "/etc/mtab")
548 self
.__destroy
_selinuxfs
()
550 self
._undo
_bindmounts
()
552 self
._unmount
_instroot
()
555 """Unmounts the target filesystem and deletes temporary files.
557 This method calls unmount() and then deletes any temporary files and
558 directories that were created on the host system while building the
561 Note, make sure to call this method once finished with the creator
562 instance in order to ensure no stale files are left on the host e.g.:
564 creator = ImageCreator(ks, name)
571 if not self
.__builddir
:
576 shutil
.rmtree(self
.__builddir
, ignore_errors
= True)
577 self
.__builddir
= None
579 def __select_packages(self
, ayum
):
581 for pkg
in kickstart
.get_packages(self
.ks
,
582 self
._get
_required
_packages
()):
584 ayum
.selectPackage(pkg
)
585 except yum
.Errors
.InstallError
, e
:
586 if kickstart
.ignore_missing(self
.ks
):
587 skipped_pkgs
.append(pkg
)
589 raise CreatorError("Failed to find package '%s' : %s" %
592 for pkg
in skipped_pkgs
:
593 logging
.warn("Skipping missing package '%s'" % (pkg
,))
595 def __select_groups(self
, ayum
):
597 for group
in kickstart
.get_groups(self
.ks
):
599 ayum
.selectGroup(group
.name
, group
.include
)
600 except (yum
.Errors
.InstallError
, yum
.Errors
.GroupsError
), e
:
601 if kickstart
.ignore_missing(self
.ks
):
602 raise CreatorError("Failed to find group '%s' : %s" %
605 skipped_groups
.append(group
)
607 for group
in skipped_groups
:
608 logging
.warn("Skipping missing group '%s'" % (group
.name
,))
610 def __deselect_packages(self
, ayum
):
611 for pkg
in kickstart
.get_excluded(self
.ks
,
612 self
._get
_excluded
_packages
()):
613 ayum
.deselectPackage(pkg
)
615 # if the system is running selinux and the kickstart wants it disabled
616 # we need /usr/sbin/lokkit
617 def __can_handle_selinux(self
, ayum
):
618 file = "/usr/sbin/lokkit"
619 if not kickstart
.selinux_enabled(self
.ks
) and os
.path
.exists("/selinux/enforce") and not ayum
.installHasFile(file):
620 raise CreatorError("Unable to disable SELinux because the installed package set did not include the file %s" % (file))
622 def install(self
, repo_urls
= {}):
623 """Install packages into the install root.
625 This function installs the packages listed in the supplied kickstart
626 into the install root. By default, the packages are installed from the
627 repository URLs specified in the kickstart.
629 repo_urls -- a dict which maps a repository name to a repository URL;
630 if supplied, this causes any repository URLs specified in
631 the kickstart to be overridden.
634 yum_conf
= self
._mktemp
(prefix
= "yum.conf-")
636 ayum
= LiveCDYum(releasever
=self
.releasever
)
637 ayum
.setup(yum_conf
, self
._instroot
)
639 for repo
in kickstart
.get_repos(self
.ks
, repo_urls
):
640 (name
, baseurl
, mirrorlist
, inc
, exc
) = repo
642 yr
= ayum
.addRepository(name
, baseurl
, mirrorlist
)
648 if kickstart
.exclude_docs(self
.ks
):
649 rpm
.addMacro("_excludedocs", "1")
650 if not kickstart
.selinux_enabled(self
.ks
):
651 rpm
.addMacro("__file_context_path", "%{nil}")
652 if kickstart
.inst_langs(self
.ks
) != None:
653 rpm
.addMacro("_install_langs", kickstart
.inst_langs(self
.ks
))
656 self
.__select
_packages
(ayum
)
657 self
.__select
_groups
(ayum
)
658 self
.__deselect
_packages
(ayum
)
660 self
.__can
_handle
_selinux
(ayum
)
663 except yum
.Errors
.RepoError
, e
:
664 raise CreatorError("Unable to download from repo : %s" % (e
,))
665 except yum
.Errors
.YumBaseError
, e
:
666 raise CreatorError("Unable to install: %s" % (e
,))
672 # do some clean up to avoid lvm info leakage. this sucks.
673 for subdir
in ("cache", "backup", "archive"):
674 lvmdir
= self
._instroot
+ "/etc/lvm/" + subdir
676 for f
in os
.listdir(lvmdir
):
677 os
.unlink(lvmdir
+ "/" + f
)
681 def __run_post_scripts(self
):
682 for s
in kickstart
.get_post_scripts(self
.ks
):
683 (fd
, path
) = tempfile
.mkstemp(prefix
= "ks-script-",
684 dir = self
._instroot
+ "/tmp")
686 os
.write(fd
, s
.script
)
690 env
= self
._get
_post
_scripts
_env
(s
.inChroot
)
693 env
["INSTALL_ROOT"] = self
._instroot
697 preexec
= self
._chroot
698 script
= "/tmp/" + os
.path
.basename(path
)
701 subprocess
.check_call([s
.interp
, script
],
702 preexec_fn
= preexec
, env
= env
)
704 raise CreatorError("Failed to execute %%post script "
705 "with '%s' : %s" % (s
.interp
, e
.strerror
))
706 except subprocess
.CalledProcessError
, err
:
708 raise CreatorError("%%post script failed with code %d "
710 logging
.warning("ignoring %%post failure (code %d)"
716 """Configure the system image according to the kickstart.
718 This method applies the (e.g. keyboard or network) configuration
719 specified in the kickstart and executes the kickstart %post scripts.
721 If neccessary, it also prepares the image to be bootable by e.g.
722 creating an initrd and bootloader configuration.
725 ksh
= self
.ks
.handler
727 kickstart
.LanguageConfig(self
._instroot
).apply(ksh
.lang
)
728 kickstart
.KeyboardConfig(self
._instroot
).apply(ksh
.keyboard
)
729 kickstart
.TimezoneConfig(self
._instroot
).apply(ksh
.timezone
)
730 kickstart
.AuthConfig(self
._instroot
).apply(ksh
.authconfig
)
731 kickstart
.FirewallConfig(self
._instroot
).apply(ksh
.firewall
)
732 kickstart
.RootPasswordConfig(self
._instroot
).apply(ksh
.rootpw
)
733 kickstart
.ServicesConfig(self
._instroot
).apply(ksh
.services
)
734 kickstart
.XConfig(self
._instroot
).apply(ksh
.xconfig
)
735 kickstart
.NetworkConfig(self
._instroot
).apply(ksh
.network
)
736 kickstart
.RPMMacroConfig(self
._instroot
).apply(self
.ks
)
738 self
._create
_bootconfig
()
740 self
.__run
_post
_scripts
()
741 kickstart
.SelinuxConfig(self
._instroot
).apply(ksh
.selinux
)
743 def launch_shell(self
):
744 """Launch a shell in the install root.
746 This method is launches a bash shell chroot()ed in the install root;
747 this can be useful for debugging.
750 subprocess
.call(["/bin/bash"], preexec_fn
= self
._chroot
)
752 def package(self
, destdir
= "."):
753 """Prepares the created image for final delivery.
755 In its simplest form, this method merely copies the install root to the
756 supplied destination directory; other subclasses may choose to package
757 the image by e.g. creating a bootable ISO containing the image and
758 bootloader configuration.
760 destdir -- the directory into which the final image should be moved;
761 this defaults to the current directory.
764 self
._stage
_final
_image
()
766 for f
in os
.listdir(self
._outdir
):
767 shutil
.move(os
.path
.join(self
._outdir
, f
),
768 os
.path
.join(destdir
, f
))
771 """Install, configure and package an image.
773 This method is a utility method which creates and image by calling some
774 of the other methods in the following order - mount(), install(),
775 configure(), unmount and package().
784 class LoopImageCreator(ImageCreator
):
785 """Installs a system into a loopback-mountable filesystem image.
787 LoopImageCreator is a straightforward ImageCreator subclass; the system
788 is installed into an ext3 filesystem on a sparse file which can be
789 subsequently loopback-mounted.
793 def __init__(self
, ks
, name
, fslabel
=None, releasever
=None):
794 """Initialize a LoopImageCreator instance.
796 This method takes the same arguments as ImageCreator.__init__() with
799 fslabel -- A string used as a label for any filesystems created.
802 ImageCreator
.__init
__(self
, ks
, name
, releasever
=releasever
)
804 self
.__fslabel
= None
805 self
.fslabel
= fslabel
807 self
.__minsize
_KB
= 0
808 self
.__blocksize
= 4096
809 self
.__fstype
= kickstart
.get_image_fstype(self
.ks
, "ext3")
811 self
.__instloop
= None
814 self
.__image
_size
= kickstart
.get_image_size(self
.ks
,
820 def __get_fslabel(self
):
821 if self
.__fslabel
is None:
824 return self
.__fslabel
825 def __set_fslabel(self
, val
):
827 self
.__fslabel
= None
829 self
.__fslabel
= val
[:FSLABEL_MAXLEN
]
830 fslabel
= property(__get_fslabel
, __set_fslabel
)
831 """A string used to label any filesystems created.
833 Some filesystems impose a constraint on the maximum allowed size of the
834 filesystem label. In the case of ext3 it's 16 characters, but in the case
835 of ISO9660 it's 32 characters.
837 mke2fs silently truncates the label, but mkisofs aborts if the label is too
838 long. So, for convenience sake, any string assigned to this attribute is
839 silently truncated to FSLABEL_MAXLEN (32) characters.
843 def __get_image(self
):
844 if self
.__imgdir
is None:
845 raise CreatorError("_image is not valid before calling mount()")
846 return self
.__imgdir
+ "/ext3fs.img"
847 _image
= property(__get_image
)
848 """The location of the image file.
850 This is the path to the filesystem image. Subclasses may use this path
851 in order to package the image in _stage_final_image().
853 Note, this directory does not exist before ImageCreator.mount() is called.
855 Note also, this is a read-only attribute.
859 def __get_blocksize(self
):
860 return self
.__blocksize
861 def __set_blocksize(self
, val
):
863 raise CreatorError("_blocksize must be set before calling mount()")
865 self
.__blocksize
= int(val
)
867 raise CreatorError("'%s' is not a valid integer value "
868 "for _blocksize" % val
)
869 _blocksize
= property(__get_blocksize
, __set_blocksize
)
870 """The block size used by the image's filesystem.
872 This is the block size used when creating the filesystem image. Subclasses
873 may change this if they wish to use something other than a 4k block size.
875 Note, this attribute may only be set before calling mount().
879 def __get_fstype(self
):
881 def __set_fstype(self
, val
):
882 if val
not in ("ext2", "ext3", "ext4"):
883 raise CreatorError("Unknown _fstype '%s' supplied" % val
)
885 _fstype
= property(__get_fstype
, __set_fstype
)
886 """The type of filesystem used for the image.
888 This is the filesystem type used when creating the filesystem image.
889 Subclasses may change this if they wish to use something other ext3.
891 Note, only ext2, ext3, ext4 are currently supported.
893 Note also, this attribute may only be set before calling mount().
898 # Helpers for subclasses
900 def _resparse(self
, size
= None):
901 """Rebuild the filesystem image to be as sparse as possible.
903 This method should be used by subclasses when staging the final image
904 in order to reduce the actual space taken up by the sparse image file
905 to be as little as possible.
907 This is done by resizing the filesystem to the minimal size (thereby
908 eliminating any space taken up by deleted files) and then resizing it
909 back to the supplied size.
911 size -- the size in, in bytes, which the filesystem image should be
912 resized to after it has been minimized; this defaults to None,
913 causing the original size specified by the kickstart file to
914 be used (or 4GiB if not specified in the kickstart).
917 return self
.__instloop
.resparse(size
)
919 def _base_on(self
, base_on
):
920 shutil
.copyfile(base_on
, self
._image
)
923 # Actual implementation
925 def _mount_instroot(self
, base_on
= None):
926 self
.__imgdir
= self
._mkdtemp
()
928 if not base_on
is None:
929 self
._base
_on
(base_on
)
931 self
.__instloop
= ExtDiskMount(SparseLoopbackDisk(self
._image
, self
.__image
_size
),
938 self
.__instloop
.mount()
939 except MountError
, e
:
940 raise CreatorError("Failed to loopback mount '%s' : %s" %
943 def _unmount_instroot(self
):
944 if not self
.__instloop
is None:
945 self
.__instloop
.cleanup()
947 def _stage_final_image(self
):
949 shutil
.move(self
._image
, self
._outdir
+ "/" + self
.name
+ ".img")