lxc-fedora.in revision c28d2f446b1cfc3871a4e4303c7c7d459dde15e6
1152N/A# template script for generating fedora container for LXC 1152N/A# lxc: linux Container library 1152N/A# Daniel Lezcano <daniel.lezcano@free.fr> 1152N/A# Ramez Hanna <rhanna@informatiq.org> 1152N/A# Michael H. Warfield <mhw@WittsEnd.com> 1152N/A# This library is free software; you can redistribute it and/or 1152N/A# modify it under the terms of the GNU Lesser General Public 1152N/A# License as published by the Free Software Foundation; either 1152N/A# version 2.1 of the License, or (at your option) any later version. 1152N/A# This library is distributed in the hope that it will be useful, 1152N/A# but WITHOUT ANY WARRANTY; without even the implied warranty of 1152N/A # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 1152N/A# Lesser General Public License for more details. 1152N/A# You should have received a copy of the GNU Lesser General Public 1152N/A# License along with this library; if not, write to the Free Software 1204N/A# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 1204N/A# Some combinations of the tuning knobs below do not exactly make sense. # If the "root_password" is non-blank, use it, else set a default. # This can be passed to the script as an environment variable and is # set by a shell conditional assignment. Looks weird but it is what it is. # If the root password contains a ding ($) then try to expand it. # That will pick up things like ${name} and ${RANDOM}. # If the root password contains more than 3 consecutive X's, pass it as # a template to mktemp and take the result. # If root_display_password = yes, display the temporary root password at exit. # If root_store_password = yes, store it in the configuration directory # If root_prompt_password = yes, invoke "passwd" to force the user to change # the root password after the container is created. # If root_expire_password = yes, you will be prompted to change the root # password at the first login. # These are conditional assignments... The can be overridden from the # preexisting environment variables... # Make sure this is in single quotes to defer expansion to later! # :{root_password='Root-${name}-${RANDOM}'} # Now, it doesn't make much sense to display, store, and force change # together. But, we gotta test, right??? # Prompting for something interactive has potential for mayhem # with users running under the API... Don't default to "yes" # Expire root password? Default to yes, but can be overridden from # the environment variable # These are only going into comments in the resulting config... # Alow for weird remixes like the Raspberry Pi # Use the Mitre standard CPE identifier for the release ID if possible... # should be able to use EITHER. Give preference to /etc/os-release for now. # Detect use under userns (unsupported) [
"$arg" =
"--" ] &&
break if [
"$arg" =
"--mapped-uid" -o
"$arg" =
"--mapped-gid" ];
then echo "This template can't be used for unprivileged containers." 1>&
2 echo "You may want to try the \"download\" template instead." 1>&
2 # Make sure the usual locations are in PATH # This is a shell friendly configuration file. We can just source it. # What we're looking for in here is the ID, VERSION_ID and the CPE_NAME if [
"${CPE_URI}" !=
"cpe:/o" ]
# Probably a better way to do this but sill remain posix # compatible but this works, shrug... # Must be nice and not introduce convenient bashisms here. if [
"${CPE_NAME}" !=
"" -a
"${ID}" =
"fedora" -a
"${VERSION_ID}" !=
"" ]
# Only if all other methods fail, try to parse the redhat-release file. # disable selinux in fedora # Nice catch from Dwight Engen in the Oracle template. # Wantonly plagerized here with much appreciation. # This is a known problem and documented in RedHat bugzilla as relating # to a problem with auditing enabled. This prevents an error in # the container "Cannot make/remove an entry for the specified session" # In addition to disabling pam_loginuid in the above config files # we'll also disable it by linking it to pam_permit to catch any # we missed or any that get installed after the container is built. # Catch either or both 32 and 64 bit archs. # Set default localtime to the host localtime if not set... # Trim it and make it our own and link it in before the default # halt script so we can intercept it. This also preventions package # updates from interferring with our interferring with it. # There's generally not much in the halt script that useful but what's # in there from resetting the hardware clock down is generally very bad. # So we just eliminate the whole bottom half of that script in making # ourselves a copy. That way a major update to the init scripts won't # trash what we've set up. # This is mostly for legacy distros since any modern systemd Fedora # release will not have this script so we won't try to intercept it. # Link them into the rc directories... # configure the network using the dhcp cat <<EOF > ${rootfs_path}/etc/sysconfig/network-scripts/ifcfg-eth0 DHCP_HOSTNAME=\`hostname\` cat <<EOF > ${rootfs_path}/etc/sysconfig/network # set hostname on systemd Fedora systems cat <<EOF > $rootfs_path/etc/hosts 127.0.0.1 localhost.localdomain localhost $utsname ::1 localhost6.localdomain6 localhost6 # These mknod's really don't make any sense with modern releases of # Fedora with systemd, devtmpfs, and autodev enabled. They are left # here for legacy reasons and older releases with upstart and sysv init. # setup console and tty[1-4] for login. note that /dev/console and # /dev/lxc/tty[1-4] so that package updates can overwrite the symlinks. # lxc will maintain these links and bind mount ptys over /dev/lxc/* # allow root login on console, tty[1-4], and pts/0 for libvirt echo "Storing root password in '${config_path}/tmp_root_pass'" # Also set this password as expired to force the user to change it! # specifying this in the initial packages doesn't always work. # Even though it should have... echo "installing fedora-release package" # Rebuild the rpm database based on the target rpm version... # NetworkManager has not been installed. Use the # legacy chkconfig command to enable the network startup # scripts in the container. # silence some needless startup errors # don't mount devpts, for pete's sake # This is to make upstart honor SIGPWR. Should do no harm # on systemd systems and some systems may have both. cat <<EOF >${rootfs_path}/etc/init/power-status-changed.conf # power-status-changed - shutdown on SIGPWR start on power-status-changed exec /sbin/shutdown -h now "SIGPWR received" # Make systemd honor SIGPWR # if desired, prevent systemd from over-mounting /tmp with tmpfs #dependency on a device unit fails it specially that we disabled udev # Actually, the After=dev-%i.device line does not appear in the # Fedora 17 or Fedora 18 systemd getty\@.service file. It may be left # over from an earlier version and it's not doing any harm. We do need # to disable the "ConditionalPathExists=/dev/tty0" line or no gettys are # started on the ttys in the container. Lets do it in an override copy of # the service so it can still pass rpm verifies and not be automatically # updated by a new systemd version. -- mhw /\/\|=mhw=|\/\/ sed -e 's/^ConditionPathExists=/# ConditionPathExists=/' \ # Setup getty service on the 4 ttys we are going to allow in the # default config. Number should match lxc.tty ### BEGIN Bootstrap Environment Code... Michael H. Warfield /\/\|=mhw=|\/\/ # Ok... Heads up. If you're reading these comments, you're either a # template owner or someone wondering how the hell I did this (or, worse, # someone in the future trying to maintain it). This code is slightly # "evil coding bastard" code with one significant hack / dirty trick # that you would probably miss just reading the code below. I'll mark # Because of what this code does, it deserves a lot of comments so people # can understand WHY I did it this way... # Ultimate Objective - Build a Fedora container on a host system which does # not have a (complete compatible) version of rpm and/or yum. That basically # means damn near any distro other than Fedora and Ubuntu (which has rpm and # yum available). Only requirements for this function are rsync and # squashfs available to the kernel. If you don't have those, why are you # even attempting to build containers? # Challenge for this function - Bootstrap a Fedora install bootstrap # run time environment which has all the pieces to run rpm and yum and # from which we can build targets containers even where the host system # has no support for rpm, yum, or fedora. # Stage 0 - Download a Fedora LiveOS squashfs core (netinst core). # Stage 1 - Extract filesystem from Stage 0 and update to full rpm & yum # Stage 2 - Use Stage 1 to build a rootfs with python, rpm, and yum. # Stage 2 becomes our bootstrap file system which can be cached # and then used to build other arbitrary vesions of Fedora of a # given architecture. Note that this only has to run once for # Fedora on a given architecture since rpm and yum can build other # versions. We'll arbitrarily pick Fedora 22 to build this. This # will need to change as time goes on. # Programmers Note... A future fall back may be to download the netinst # iso image instead of the LiveOS squasfs image and work from that. # That may be more general but will introduce another substep # (mounting the iso) to the stage0 setup. # This system is designed to be as autonomous as possible so all whitelists # and controls are self-contained. # Initial testing - Whitelist nobody. Build for everybody... # Initial deployment - Whitelist Fedora. # Long term - Whitelist Fedora, Debian, Ubuntu, CentOs, Scientific, and NST. # List of distros which do not (should not) need a bootstrap (but we will test # for rpm and yum none the less... OS SHOULD be taken from CPE values but # Debian / Ubuntu doesn't support CPE yet. # BOOTSTRAP_WHITE_LIST="" # BOOTSTRAP_WHITE_LIST="fedora debian ubuntu centos scientific sl nst" echo "Bootstrap Environment testing..." # We need rpm. No rpm - not possible to white list... # We need yum No yum - not possible to white list... OS ${ID} is whitelisted. Installation Bootstrap Environment not required. Fedora Installation Bootstrap Build..." Unable to locate rsync. Cravely bailing out before even attempting to build an Installation Bootstrap Please install rsync and then rerun this process. # We know we don't have a cache directory of this version or we # would have never reached this code to begin with. But we may # have another Fedora cache directory from which we could run... # We'll give a preference for close matches preferring higher over # lower - which makes for really ugly code... # Is this a "bashism" that will need cleaning up???? Existing Bootstrap found. Testing..." Functional Installation Bootstrap exists and appears to be completed. Will use existing Bootstrap: ${BOOTSTRAP_DIR} Installation Bootstrap in ${BOOTSTRAP_DIR} exists but appears to be non-functional. Skipping... It should be removed. # Download the LiveOS squashfs image # mount image to "squashfs" # mount contained LiveOS to stage0 # We're going to use the kernel.org mirror for the initial stages... # 1 - It's generally up to date and comnplete # 2 - It's has high bandwidth access # 3 - It supports rsync and wildcarding (and we need both) # 4 - Not all the mirrors carry the LiveOS images Have a beer or a cup of coffee. This will take a bit (~300MB). sleep 3 # let him read it... # Right now, we are using Fedora 22 for the inial bootstrap. # We could make this the "current" Fedora rev (F > 15). echo "Download of squashfs image complete." Download of squashfs image failed. echo "Using cached stage 0 LiveOS squashfs file system." Mount of LiveOS squashfs image failed! You mush have squashfs support available to mount image. Unable to continue. Correct and retry process later! LiveOS image not removed. Process may be rerun without penalty of downloading LiveOS again. If LiveOS is corrupt, remove ${cache_base}/LiveOS before rerunning to redownload. Mount of LiveOS stage0 rootfs image failed! LiveOS download may be corrupt. Remove ${cache_base}/LiveOS to force a new download or troubleshoot cached image and then rerun process. # Copy stage0 (which is ro) to stage1 area (rw) for modification. # Unmount stage0 mounts - we're done with stage 0 at this point. # Download our rpm and yum rpm packages. # Force install of rpm and yum into stage1 image (dirty hack!) echo "Stage 0 complete, building Stage 1 image... This will take a couple of minutes. Patience..." echo "Creating Stage 1 r/w copy of r/o Stage 0 squashfs image from LiveOS." # Setup stage1 image with pieces to run installs... echo "Updating Stage 1 image with full rpm and yum packages" # Retrieve our 2 rpm packages we need to force down the throat # of this LiveOS image we're camped out on. This is the beginning # of the butt ugly hack. Look close or you may missing it... # The --nodeps is STUPID but F15 had a bogus dependency on RawHide?!?! # The LiveOS image contains rpm (but not rpmdb) and yum (but not # yummain.py - What the hell good does yum do with no # yummain.py?!?! - Sigh...). It contains all the supporting # pieces but the rpm database has not be initialized and it # doesn't know all the dependences (seem to) have been met. # So we do a "--nodeps" rpm install in the chrooted environment # to force the installation of the full rpm and yum packages. # For the purists - Yes, I know the rpm database is wildly out # of whack now. That's why this is a butt ugly hack / dirty trick. # But, this is just the stage1 image that we are going to discard as # soon as the stage2 image is built, so we don't care. All we care # is that the stage2 image ends up with all the pieces it need to # run yum and rpm and that the stage2 rpm database is coherent. # NOW we can really go to work! # Download our Fedora Release rpm packages. # Install fedora-release into bootstrap to initialize fs and databases. # Install rpm, and yum into bootstrap image using yum echo "Stage 1 creation complete. Building stage 2 Installation Bootstrap" # The --nodeps is STUPID but F15 had a bogus dependency on RawHide?!?! # yum will take $basearch from host, so force the arch we want # That's it! We should now have a viable installation BOOTSTRAP in # bootstrap We'll do a yum update in that to verify and then # move it to the cache location before cleaning up. # yum will take $basearch from host, so force the arch we want Build of Installation Bootstrap failed. Temp directory not removed so it can be investigated. # We know have a working run time environment in rootfs... Build of Installation Bootstrap complete! We now return you to your normally scheduled template creation. echo "Mounting Bootstrap mount points" # This is the code to create the initial roofs for Fedora. It may # require a run time environment by calling the routines above... # check the mini fedora was not already downloaded # download a mini fedora into a cache echo "Downloading fedora minimal ..." # These will get changed if it's decided that we need a # boostrap environment (can not build natively). These # are the defaults for the non-boostrap (native) mode. PKG_LIST="yum initscripts passwd rsyslog vim-minimal openssh-server openssh-clients dhclient chkconfig rootfiles policycoreutils fedora-release" # The reflects the move of db_dump and db_load from db4_utils to # libdb_utils in Fedora 17 and above and it's inclusion as a dep... # Prior to Fedora 11, we need to explicitly include it! # Since Fedora 21, a separate fedora-repos package is needed. # Before, the information was conained in fedora-release. # We're splitting the old loop into two loops plus a directory retrival. # First loop... Try and retrive a mirror list with retries and a slight # delay between attempts... # This code is mildly "brittle" in that it assumes a certain # page format and parsing HTML. I've done worse. :-P # This will fall through if we didn't get any URLS above # This code is mildly "brittle" in that it assumes a certain directory # page format and parsing HTML. I've done worse. :-P if [ $? -ne 0 -o "${RELEASE_RPM}" = "" ]; then echo "Failed to identify fedora release rpm." echo "Fetching fedora release rpm from ${RELEASE_URL}/${RELEASE_RPM}......" echo "Failed to download fedora release rpm ${RELEASE_RPM}." # F21 and newer need fedora-repos in addition to fedora-release. if [ $? -ne 0 -o "${REPOS_RPM}" = "" ]; then echo "Failed to identify fedora repos rpm." echo "Fetching fedora repos rpm from ${RELEASE_URL}/${REPOS_RPM}..." echo "Failed to download fedora repos rpm ${RELEASE_RPM}." echo "Fedora Bootstrap setup failed" # The --nodeps is STUPID but F15 had a bogus dependency on RawHide?!?! # F21 and newer need fedora-repos in addition to fedora-release... # Note that fedora-release and fedora-system have a mutual dependency. # So installing the reops package after the release package we can # yum will take $basearch from host, so force the arch we want # Here we have a bit of a sticky problem. We MIGHT have just installed # this template cache using versions of yum and rpm in the bootstrap # chroot that use a different database version than the target version. # That can be a very big problem. Solution is to rebuild the rpmdatabase # with the target database now that we are done building the cache. In the # vast majority of cases, this is a do-not-care with no harm done if we # didn't do it. But it catches several corner cases with older unsupported # releases and it really doesn't cost us a lot of time for a one shot # install that will never be done again for this rev. # Thanks and appreciation to Dwight Engen and the Oracle template for the echo "Fixing up rpm databases" # Change to our target install directory (if we're not already # there) just to simplify some of the logic to follow... # Programmers Note (warning): # Pay careful attention to the following commands! It # crosses TWO chroot boundaries linked by a bind mount! # In the bootstrap case, that's the bind mount of ${INSTALL_ROOT} # to the ${BOOTSTRAP_CHROOT}/run/install directory! This is # a deliberate hack across that bind mount to do a database # translation between two environments, neither of which may # be the host environment! It's ugly and hard to follow but, # if you don't understand it, don't mess with it! The pipe # is in host space between the two chrooted environments! # This is also why we cd'ed into the INSTALL_ROOT directory # in advance of this loop, so everything is relative to the # current working directory and congruent with the same working # space in both chrooted environments. The output into the new # db is also done in INSTALL_ROOT space but works in either host # space or INSTALL_ROOT space for the mv, so we don't care. It's # just not obvious what's happening in the db_dump and db_load # finish up by rebuilding the database... # This should be redundant but we do it for completeness and # any corner cases I may have missed... echo "Failed to download the rootfs, aborting." echo "Download complete." # make a local copy of the minifedora #cp -a $cache/rootfs-$basearch $rootfs_path || return 1 # i prefer rsync (no reason really) echo "Cache repository is busy." echo "Checking cache download in $cache/rootfs ... " if [ ! -e "$cache/rootfs" ]; then echo "Failed to download 'fedora base'" echo "Cache found. Updating..." echo "Failed to update 'fedora base', continuing with last known good cache" echo "Failed to copy rootfs" # Generate a random hardware (MAC) address composed of FE followed by # The following code is to create static MAC addresses for each # interface in the container. This code will work for multiple # interfaces in the default config. It will also strip any # hwaddr stanzas out of the default config since we can not share # MAC addresses between containers. # This should catch variable expansions from the default config... LINE=$(eval "echo \"${LINE}\"") # There is a tab and a space in the regex bracket below! # Seems that \s doesn't work in brackets. KEY=$(expr "${LINE}" : '\s*\([^ ]*\)\s*=') # Include common configuration # Append things which require expansion here... cat <<EOF >> $config_path/config # When using LXC with apparmor, uncomment the next line to run unconfined: #lxc.aa_profile = unconfined # example simple networking setup, uncomment to enable #lxc.network.type = $lxc_network_type #lxc.network.link = $lxc_network_link # Additional example for veth network type #lxc.network.hwaddr = 00:16:3e:77:52:20 # persistent veth device name on host side # Note: This may potentially collide with other containers of same name! #lxc.network.veth.pair = v-$name-e0 echo "Failed to add configuration" # lock, so we won't purge while someone is creating a repository echo "Cache repository is busy." echo -n "Purging the download cache for Fedora-$release..." $1 -n|--name=<container_name> [-p|--path=<path>] [-c|--clean] [-R|--release=<Fedora_release>] [--fqdn=<network name of container>] [-a|--arch=<arch of the container>] -n,--name container name, used to as an identifier for that container -p,--path path to where the container will be created, --rootfs path for actual rootfs. -c,--clean clean the cache -R,--release Fedora release for the new container. Defaults to host's release if the host is Fedora. --fqdn fully qualified domain name (FQDN) for DNS and system naming -a,--arch Define what arch the container will be [i686,x86_64] --mask-tmp Prevent systemd from over-mounting /tmp with tmpfs. -h,--help print this help # Map a few architectures to their generic Fedora repository archs. # The two ARM archs are a bit of a guesstimate for the v5 and v6 # archs. V6 should have hardware floating point (Rasberry Pi). # The "arm" arch is safer (no hardware floating point). So # there may be cases where we "get it wrong" for some v6 other # Somebody wants to specify an arch. This is very limited case. if [
"${newarch}" !=
"" -a
"${newarch}" !=
"${arch}" ]
if [
"${basearch}" =
"i386" -o
"${basearch}" =
"x86_64" ]
# Make the arch a generic x86 32 bit... if [
"${basearch}" =
"bad" ]
echo "You cannot build a ${newarch} Fedora container on a ${arch} host. Sorry!" # Allow the cache base to be set by environment variable # Let's do something better for the initial root password. # It's not perfect but it will defeat common scanning brute force # attacks in the case where ssh is exposed. It will also be set to # expired, forcing the user to change it at first login. if [
"${root_password}" =
"" ]
# If it's got a ding in it, try and expand it! if [
$(expr "${root_password}" : '.*$.') !=
0 ]
# If it has more than 3 consecutive X's in it, feed it # through mktemp as a template. if [
$(expr "${root_password}" : '.*XXXX') !=
0 ]
if [ -z
"${utsname}" ];
then # This follows a standard "resolver" convention that an FQDN must have # at least two dots or it is considered a local relative host name. # If it doesn't, append the dns domain name of the host system. # This changes one significant behavior when running # "lxc_create -n Container_Name" without using the # utsname and hostname = Container_Name echo "Please install these using \"sudo yum install $needed_pkgs\"" echo "This is not a fedora host and release missing, defaulting to 22 use -R|--release to specify release" if [
"$(id -u)" !=
"0" ];
then echo "This script should be run as 'root'" # check for 'lxc.rootfs' passed in through default config by lxc-create echo "Interrupted, so cleaning up" # maybe was interrupted before copy config echo "failed write configuration file" echo "failed to install fedora" echo "failed to configure fedora for a container" # If the systemd configuration directory exists - set it up for what we need. # This configuration (rc.sysinit) is not inconsistent with the systemd stuff # above and may actually coexist on some upgraded systems. Let's just make # sure that, if it exists, we update this file, even if it's not used... Container rootfs and config have been created. echo "You have successfully built a Fedora container and cache. This cache may be used to create future containers of various revisions. The directory ${cache_base}/bootstrap contains a bootstrap which may no longer needed and can be removed. echo "A LiveOS directory exists at ${cache_base}/LiveOS. This is only used in the creation of the bootstrap run-time-environment You may want to note that password down before starting the container. echo "The temporary root password is stored in: '${config_path}/tmp_root_pass' echo "Invoking the passwd command in the container to set the root password. chroot ${rootfs_path} passwd The root password is set up as "expired" and will require it to be changed at first login, which you should do as soon as possible. If you lose the root password or wish to change it without starting the container, you can change it from the host by running the following command (which will also reset the expired flag): chroot ${rootfs_path} passwd