blob: 8d60c55ffcac44503e34be849b1febee4fb931d7 [file] [log] [blame]
Brian Harringf539bc32012-02-06 00:18:37 -08001#!/bin/bash
2
3# Copyright (c) 2010 The Chromium OS Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
7# This script sets up a Gentoo chroot environment. The script is passed the
8# path to an empty folder, which will be populated with a Gentoo stage3 and
9# setup for development. Once created, the password is set to PASSWORD (below).
10# One can enter the chrooted environment for work by running enter_chroot.sh.
11
12SCRIPT_ROOT=$(readlink -f $(dirname "$0")/..)
13. "${SCRIPT_ROOT}/common.sh" || exit 1
14
15# Check if the host machine architecture is supported.
16ARCHITECTURE="$(uname -m)"
17if [[ "$ARCHITECTURE" != "x86_64" ]]; then
18 echo "$SCRIPT_NAME: $ARCHITECTURE is not supported as a host machine architecture."
19 exit 1
20fi
21
22# Script must be run outside the chroot
23assert_outside_chroot
24
25# Define command line flags
26# See http://code.google.com/p/shflags/wiki/Documentation10x
27
28DEFINE_string chroot "$DEFAULT_CHROOT_DIR" \
29 "Destination dir for the chroot environment."
30DEFINE_boolean usepkg $FLAGS_TRUE "Use binary packages to bootstrap."
31DEFINE_boolean delete $FLAGS_FALSE "Delete an existing chroot."
32DEFINE_boolean replace $FLAGS_FALSE "Overwrite existing chroot, if any."
33DEFINE_integer jobs -1 "How many packages to build in parallel at maximum."
34DEFINE_boolean fast ${DEFAULT_FAST} "Call many emerges in parallel"
35DEFINE_string stage3_date "2010.03.09" \
36 "Use the stage3 with the given date."
37DEFINE_string stage3_path "" \
38 "Use the stage3 located on this path."
39DEFINE_boolean cros_sdk $FLAGS_FALSE "Internal: we're called from cros_sdk"
40
41# Parse command line flags
42FLAGS_HELP="usage: $SCRIPT_NAME [flags]"
43FLAGS "$@" || exit 1
44eval set -- "${FLAGS_ARGV}"
45check_flags_only_and_allow_null_arg "$@" && set --
46
47if [ "${FLAGS_cros_sdk}" == "${FLAGS_TRUE}" ]; then
48 # HACK: If we're being called by cros_sdk, change the messages.
49 SCRIPT_NAME=cros_sdk
50fi
51
52assert_not_root_user
53# Set the right umask for chroot creation.
54umask 022
55
56# Only now can we die on error. shflags functions leak non-zero error codes,
57# so will die prematurely if 'set -e' is specified before now.
58# TODO: replace shflags with something less error-prone, or contribute a fix.
59set -e
60
61FULLNAME="ChromeOS Developer"
62DEFGROUPS="eng,adm,cdrom,floppy,audio,video,portage"
63PASSWORD=chronos
64CRYPTED_PASSWD=$(perl -e 'print crypt($ARGV[0], "foo")', $PASSWORD)
65
66USEPKG=""
67if [[ $FLAGS_usepkg -eq $FLAGS_TRUE ]]; then
68 # Use binary packages. Include all build-time dependencies,
69 # so as to avoid unnecessary differences between source
70 # and binary builds.
71 USEPKG="--getbinpkg --usepkg --with-bdeps y"
72fi
73
74# Support faster build if necessary.
75EMERGE_CMD="emerge"
76if [ "$FLAGS_fast" -eq "${FLAGS_TRUE}" ]; then
77 CHROOT_CHROMITE_DIR="/home/${USER}/trunk/chromite"
78 EMERGE_CMD="${CHROOT_CHROMITE_DIR}/bin/parallel_emerge"
79fi
80
81function in_chroot {
82 sudo "${CHROOT_PASSTHRU[@]}" chroot "$FLAGS_chroot" "$@"
83}
84
85function bash_chroot {
86 # Use $* not $@ since 'bash -c' needs a single arg
87 # Use -l to force source of /etc/profile (login shell)
88 sudo "${CHROOT_PASSTHRU[@]}" chroot "$FLAGS_chroot" bash -l -c "$*"
89}
90
91function sudo_chroot {
92 # The same as bash_chroot, except ran as the normal user.
93 sudo chroot "$FLAGS_chroot" sudo -i -u ${USER} "${CHROOT_PASSTHRU[@]}" -- "$@"
94}
95
96function cleanup {
97 # Clean up mounts
98 safe_umount_tree "${FLAGS_chroot}"
99}
100
101function delete_existing {
102 # Delete old chroot dir
103 if [[ -e "$FLAGS_chroot" ]]; then
104 echo "$SCRIPT_NAME: Cleaning up old mount points..."
105 cleanup
106 echo "$SCRIPT_NAME: Deleting $FLAGS_chroot..."
107 sudo rm -rf "$FLAGS_chroot"
108 echo "$SCRIPT_NAME: Done."
109 fi
110}
111
112function init_users () {
113 echo "$SCRIPT_NAME: Set timezone..."
114 # date +%Z has trouble with daylight time, so use host's info
115 in_chroot rm -f /etc/localtime
116 if [ -f /etc/localtime ] ; then
117 sudo cp /etc/localtime "${FLAGS_chroot}/etc"
118 else
119 in_chroot ln -sf /usr/share/zoneinfo/PST8PDT /etc/localtime
120 fi
121 echo "$SCRIPT_NAME: Adding user/group..."
122 # Add ourselves as a user inside the chroot.
123 in_chroot groupadd -g 5000 eng
124 # We need the UID to match the host user's. This can conflict with
125 # a particular chroot UID. At the same time, the added user has to
126 # be a primary user for the given UID for sudo to work, which is
127 # determined by the order in /etc/passwd. Let's put ourselves on top
128 # of the file.
129 in_chroot useradd -o -G ${DEFGROUPS} -g eng -u `id -u` -s \
130 /bin/bash -m -c "${FULLNAME}" -p ${CRYPTED_PASSWD} ${USER}
131 # Because passwd generally isn't sorted and the entry ended up at the
132 # bottom, it is safe to just take it and move it to top instead.
133 in_chroot sed -e '1{h;d};$!{H;d};$G' -i /etc/passwd
134}
135
136function init_setup () {
137 echo "$SCRIPT_NAME: Running init_setup()..."
138 sudo mkdir -p "${FLAGS_chroot}/usr"
139 sudo ln -sf "${CHROOT_TRUNK}/src/third_party/portage" \
140 "${FLAGS_chroot}/usr/portage"
141 sudo mkdir -p "${FLAGS_chroot}/usr/local/portage"
142 sudo chmod 755 "${FLAGS_chroot}/usr/local/portage"
143 sudo ln -sf "${CHROOT_TRUNK}/src/third_party/chromiumos-overlay" \
144 "${FLAGS_chroot}"/"${CHROOT_OVERLAY}"
145 sudo ln -sf "${CHROOT_TRUNK}/src/third_party/portage-stable" \
146 "${FLAGS_chroot}"/"${PORTAGE_STABLE_OVERLAY}"
147 sudo mkdir -p "${FLAGS_chroot}"/"${CROSSDEV_OVERLAY}"
148 sudo chmod 755 "${FLAGS_chroot}"/"${CROSSDEV_OVERLAY}"
149
150 # Some operations need an mtab
151 in_chroot ln -s /proc/mounts /etc/mtab
152
153 # Set up sudoers. Inside the chroot, the user can sudo without a password.
154 # (Safe enough, since the only way into the chroot is to 'sudo chroot', so
155 # the user's already typed in one sudo password...)
156 # Make sure the sudoers.d subdir exists as older stage3 base images lack it.
157 sudo mkdir -p "${FLAGS_chroot}/etc/sudoers.d"
158 sudo_clobber "${FLAGS_chroot}/etc/sudoers.d/90_cros" <<EOF
159Defaults env_keep += CROS_WORKON_SRCROOT
160Defaults env_keep += CHROMEOS_OFFICIAL
161Defaults env_keep += PORTAGE_USERNAME
162Defaults env_keep += http_proxy
163Defaults env_keep += ftp_proxy
164Defaults env_keep += all_proxy
165%adm ALL=(ALL) ALL
166root ALL=(ALL) ALL
167$USER ALL=NOPASSWD: ALL
168EOF
169 bash_chroot "find /etc/sudoers* -type f -exec chmod 0440 {} +"
170 bash_chroot "chown -R root:root /etc/sudoers*" # Fix bad group for some.
171
172 echo "$SCRIPT_NAME: Setting up hosts/resolv..."
173 # Copy config from outside chroot into chroot
174 sudo cp /etc/hosts "$FLAGS_chroot/etc/hosts"
175 sudo chmod 0644 "$FLAGS_chroot/etc/hosts"
176 sudo cp /etc/resolv.conf "$FLAGS_chroot/etc/resolv.conf"
177 sudo chmod 0644 "$FLAGS_chroot/etc/resolv.conf"
178
179 # Setup host make.conf. This includes any overlay that we may be using
180 # and a pointer to pre-built packages.
181 # TODO: This should really be part of a profile in the portage
182 echo "$SCRIPT_NAME: Setting up /etc/make.*..."
183 sudo mv "${FLAGS_chroot}"/etc/make.conf{,.orig}
184 sudo ln -sf "${CHROOT_CONFIG}/make.conf.amd64-host" \
185 "${FLAGS_chroot}/etc/make.conf"
186 sudo mv "${FLAGS_chroot}"/etc/make.profile{,.orig}
187 sudo ln -sf "${CHROOT_OVERLAY}/profiles/default/linux/amd64/10.0" \
188 "${FLAGS_chroot}/etc/make.profile"
189
190 # Create make.conf.user
191 sudo touch "${FLAGS_chroot}"/etc/make.conf.user
192 sudo chmod 0644 "${FLAGS_chroot}"/etc/make.conf.user
193
194 # Create directories referred to by our conf files.
195 sudo mkdir -p -m 775 "${FLAGS_chroot}/var/lib/portage/distfiles"
196 sudo mkdir -p -m 775 "${FLAGS_chroot}/var/lib/portage/distfiles-target"
197 sudo mkdir -p -m 775 "${FLAGS_chroot}/var/lib/portage/pkgs"
198
199 if [[ $FLAGS_jobs -ne -1 ]]; then
200 EMERGE_JOBS="--jobs=$FLAGS_jobs"
201 fi
202
203 # Add chromite/bin and depot_tools into the path globally; note that the
204 # chromite wrapper itself might also be found in depot_tools.
205 # We rely on 'env-update' getting called below.
206 target="${FLAGS_chroot}/etc/env.d/99chromiumos"
207 sudo_clobber "${target}" <<EOF
208PATH=/home/$USER/trunk/chromite/bin:/home/$USER/depot_tools
209CROS_WORKON_SRCROOT="${CHROOT_TRUNK}"
210PORTAGE_USERNAME=$USER
211EOF
212
213 # TODO(zbehan): Configure stuff that is usually configured in postinst's,
214 # but wasn't. Fix the postinst's. crosbug.com/18036
215 echo "Running post-inst configuration hacks"
216 in_chroot env-update
217 if [ -f ${FLAGS_chroot}/usr/bin/build-docbook-catalog ]; then
218 # For too ancient chroots that didn't have build-docbook-catalog, this
219 # is not relevant, and will get installed during update.
220 in_chroot build-docbook-catalog
221 fi
222
223 # Configure basic stuff needed
224 in_chroot env-update
225 bash_chroot ls -l /etc/make.conf
226 bash_chroot ls -l /etc/make.profile
227 bash_chroot ls -l /usr/local/portage/chromiumos/profiles/default/linux/amd64/10.0
228
229 target="${FLAGS_chroot}/etc/profile.d"
230 sudo mkdir -p "${target}"
231 sudo_clobber "${target}/chromiumos-niceties.sh" << EOF
232# Niceties for interactive logins. (cr) denotes this is a chroot, the
233# __git_branch_ps1 prints current git branch in ./ . The $r behavior is to
234# make sure we don't reset the previous $? value which later formats in
235# $PS1 might rely on.
236PS1='\$(r=\$?; __git_branch_ps1 "(%s) "; exit \$r)'"\${PS1}"
237PS1="(cr) \${PS1}"
238EOF
239
240 # Select a small set of locales for the user if they haven't done so
241 # already. This makes glibc upgrades cheap by only generating a small
242 # set of locales. The ones listed here are basically for the buildbots
243 # which always assume these are available. This works in conjunction
244 # with `cros_sdk --enter`.
245 # http://crosbug.com/20378
246 local localegen="$FLAGS_chroot/etc/locale.gen"
247 if ! grep -q -v -e '^#' -e '^$' "${localegen}" ; then
248 sudo_append "${localegen}" <<EOF
249en_US ISO-8859-1
250en_US.UTF-8 UTF-8
251EOF
252 fi
253
254 # Add chromite as a local site-package.
255 mkdir -p "${FLAGS_chroot}/home/$USER/.local/lib/python2.6/site-packages"
256 ln -s ../../../../trunk/chromite \
257 "${FLAGS_chroot}/home/$USER/.local/lib/python2.6/site-packages/"
258
259 chmod a+x "$FLAGS_chroot/home/$USER/.bashrc"
260 # Automatically change to scripts directory
261 echo 'cd ${CHROOT_CWD:-~/trunk/src/scripts}' \
262 >> "$FLAGS_chroot/home/$USER/.bash_profile"
263
264 # Enable bash completion for build scripts
265 echo ". ~/trunk/src/scripts/bash_completion" \
266 >> "$FLAGS_chroot/home/$USER/.bashrc"
267
268 # Warn if attempting to use source control commands inside the chroot
269 for NOUSE in svn gcl gclient
270 do
271 echo "alias $NOUSE='echo In the chroot, it is a bad idea to run $NOUSE'" \
272 >> "$FLAGS_chroot/home/$USER/.bash_profile"
273 done
274
275 if [[ "$USER" = "chrome-bot" ]]; then
276 # Copy ssh keys, so chroot'd chrome-bot can scp files from chrome-web.
277 cp -r ~/.ssh "$FLAGS_chroot/home/$USER/"
278 fi
279
280 if [[ -f $HOME/.gitconfig ]]; then
281 # Copy .gitconfig into chroot so repo and git can be used from inside
282 # This is required for repo to work since it validates the email address
283 echo "Copying ~/.gitconfig into chroot"
284 cp $HOME/.gitconfig "$FLAGS_chroot/home/$USER/"
285 fi
286}
287
288# Handle deleting an existing environment
289if [[ $FLAGS_delete -eq $FLAGS_TRUE || \
290 $FLAGS_replace -eq $FLAGS_TRUE ]]; then
291 delete_existing
292 [[ $FLAGS_delete -eq $FLAGS_TRUE ]] && exit 0
293fi
294
295CHROOT_TRUNK="${CHROOT_TRUNK_DIR}"
296PORTAGE="${SRC_ROOT}/third_party/portage"
297OVERLAY="${SRC_ROOT}/third_party/chromiumos-overlay"
298CONFIG_DIR="${OVERLAY}/chromeos/config"
299CHROOT_CONFIG="${CHROOT_TRUNK}/src/third_party/chromiumos-overlay/chromeos/config"
300PORTAGE_STABLE_OVERLAY="/usr/local/portage/stable"
301CROSSDEV_OVERLAY="/usr/local/portage/crossdev"
302CHROOT_OVERLAY="/usr/local/portage/chromiumos"
303CHROOT_STATE="${FLAGS_chroot}/etc/debian_chroot"
304CHROOT_PASSTHRU=(CROS_WORKON_SRCROOT="$CHROOT_TRUNK" PORTAGE_USERNAME="$USER"
305 IGNORE_PREFLIGHT_BINHOST="$IGNORE_PREFLIGHT_BINHOST")
306
307# Pass proxy variables into the environment.
308for type in http ftp all; do
309 value=$(env | grep ${type}_proxy || true)
310 if [ -n "${value}" ]; then
311 CHROOT_PASSTHRU+=("$value")
312 fi
313done
314
315# Create the base Gentoo stage3 based on last version put in chroot
316STAGE3="${OVERLAY}/chromeos/stage3/stage3-amd64-${FLAGS_stage3_date}.tar.bz2"
317if [ -f $CHROOT_STATE ] && \
318 ! sudo egrep -q "^STAGE3=$STAGE3" $CHROOT_STATE >/dev/null 2>&1
319then
320 echo "$SCRIPT_NAME: STAGE3 version has changed."
321 delete_existing
322fi
323
324if [ -n "${FLAGS_stage3_path}" ]; then
325 if [ -f "${FLAGS_stage3_path}" ]; then
326 STAGE3="${FLAGS_stage3_path}"
327 else
328 error "Invalid stage3!"
329 exit 1;
330 fi
331fi
332
333# Create the destination directory
334mkdir -p "$FLAGS_chroot"
335
336echo
337if [ -f $CHROOT_STATE ]
338then
339 echo "$SCRIPT_NAME: STAGE3 already set up. Skipping..."
340else
341 echo "$SCRIPT_NAME: Unpacking STAGE3..."
342 sudo tar -xp -I $(type -p pbzip2 || echo bzip2) \
343 -C "${FLAGS_chroot}" -f "${STAGE3}"
344 sudo rm -f $FLAGS_chroot/etc/make.globals
345 sudo rm -f $FLAGS_chroot/etc/make.conf.user
346fi
347
348# Set up users, if needed, before mkdir/mounts below
349[ -f $CHROOT_STATE ] || init_users
350
351echo
352echo "$SCRIPT_NAME: Setting up mounts..."
353# Set up necessary mounts and make sure we clean them up on exit
354trap cleanup EXIT
355sudo mkdir -p "${FLAGS_chroot}/${CHROOT_TRUNK}"
356sudo mount --bind /dev "${FLAGS_chroot}/dev"
357sudo mount --bind "${GCLIENT_ROOT}" "${FLAGS_chroot}/${CHROOT_TRUNK}"
358sudo mount none -t proc "$FLAGS_chroot/proc"
359sudo mount none -t devpts "$FLAGS_chroot/dev/pts"
360sudo mkdir -p "${FLAGS_chroot}/run"
361if [ -d /run ]; then
362 sudo mount --bind /run "$FLAGS_chroot/run"
363 if [ -d /run/shm ]; then
364 sudo mount --bind /run/shm "$FLAGS_chroot/run/shm"
365 fi
366fi
367PREBUILT_SETUP="$FLAGS_chroot/etc/make.conf.prebuilt_setup"
368if [[ -z "$IGNORE_PREFLIGHT_BINHOST" ]]; then
369 echo 'PORTAGE_BINHOST="$FULL_BINHOST"' | sudo_clobber "$PREBUILT_SETUP"
370else
371 sudo_clobber "$PREBUILT_SETUP" < /dev/null
372fi
373sudo chmod 0644 "$PREBUILT_SETUP"
374
375# For bootstrapping from old wget, disable certificate checking. Once we've
376# upgraded to new curl (below), certificate checking is re-enabled. See
377# http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=409938
378bash_chroot 'cat > /etc/make.conf.fetchcommand_setup' <<'EOF'
379FETCHCOMMAND="/usr/bin/wget -t 5 -T 60 --no-check-certificate --passive-ftp -O \"\${DISTDIR}/\${FILE}\" \"\${URI}\""
380RESUMECOMMAND="/usr/bin/wget -c -t 5 -T 60 --no-check-certificate --passive-ftp -O \"\${DISTDIR}/\${FILE}\" \"\${URI}\""
381EOF
382sudo chmod 0644 "${FLAGS_chroot}"/etc/make.conf.fetchcommand_setup
383bash_chroot 'cat > /etc/make.conf.host_setup' <<EOF
384# Created by make_chroot
385source make.conf.prebuilt_setup
386source make.conf.fetchcommand_setup
387MAKEOPTS="-j${NUM_JOBS}"
388EOF
389sudo chmod 0644 "${FLAGS_chroot}"/etc/make.conf.host_setup
390
391if ! [ -f "$CHROOT_STATE" ];then
392 INITIALIZE_CHROOT=1
393fi
394
395
396if [ -z "${INITIALIZE_CHROOT}" ];then
397 echo "$SCRIPT_NAME: chroot already initialized. Skipping..."
398else
399 # run all the init stuff to setup the env
400 init_setup
401fi
402
403# Add file to indicate that it is a chroot
404# Add version of $STAGE3 for update checks
405sudo sh -c "echo STAGE3=$STAGE3 > $CHROOT_STATE"
406
407echo "$SCRIPT_NAME: Updating portage"
408in_chroot emerge -uNv portage
409
410echo "$SCRIPT_NAME: Updating toolchain"
411in_chroot emerge -uNv $USEPKG '>=sys-devel/gcc-4.4' sys-libs/glibc \
412 sys-devel/binutils sys-kernel/linux-headers
413
414# HACK: Select the latest toolchain. We're assuming that when this is
415# ran, the chroot has no experimental versions of new toolchains, just
416# one that is very old, and one that was just emerged.
417CHOST="$(in_chroot portageq envvar CHOST)"
418LATEST="$(in_chroot gcc-config -l | grep "${CHOST}" | tail -n1 | \
419 cut -f3 -d' ')"
420in_chroot gcc-config "${LATEST}"
421in_chroot emerge --unmerge "<sys-devel/gcc-${LATEST/${CHOST}-/}"
422
423# dhcpcd is included in 'world' by the stage3 that we pull in for some reason.
424# We have no need to install it in our host environment, so pull it out here.
425echo "$SCRIPT_NAME: Deselecting dhcpcd"
426in_chroot $EMERGE_CMD --deselect dhcpcd
427
428echo "$SCRIPT_NAME: Running emerge ccache curl sudo ..."
429in_chroot $EMERGE_CMD -uNv $USEPKG ccache net-misc/curl sudo $EMERGE_JOBS
430
431# Curl is now installed, so we can depend on it now.
432bash_chroot 'cat > /etc/make.conf.fetchcommand_setup' <<'EOF'
433FETCHCOMMAND='curl -f -y 30 --retry 9 -L --output \${DISTDIR}/\${FILE} \${URI}'
434RESUMECOMMAND='curl -f -y 30 -C - --retry 9 -L --output \${DISTDIR}/\${FILE} \${URI}'
435EOF
436sudo chmod 0644 "${FLAGS_chroot}"/etc/make.conf.fetchcommand_setup
437
438if [ -n "${INITIALIZE_CHROOT}" ]; then
439 # If we're creating a new chroot, we also want to set it to the latest
440 # version.
441 sudo_chroot \
442 "${CHROOT_TRUNK}/src/scripts/run_chroot_version_hooks" --force_latest
443fi
444
445# Update chroot
446UPDATE_ARGS=""
447if [[ $FLAGS_usepkg -eq $FLAGS_TRUE ]]; then
448 UPDATE_ARGS+=" --usepkg"
449else
450 UPDATE_ARGS+=" --nousepkg"
451fi
452if [[ ${FLAGS_fast} -eq ${FLAGS_TRUE} ]]; then
453 UPDATE_ARGS+=" --fast"
454else
455 UPDATE_ARGS+=" --nofast"
456fi
457sudo_chroot "${CHROOT_TRUNK}/src/scripts/update_chroot" ${UPDATE_ARGS}
458
459# Unmount trunk
460sudo umount "${FLAGS_chroot}/${CHROOT_TRUNK}"
461
462# Clean up the chroot mounts
463trap - EXIT
464cleanup
465
466if [[ "$FLAGS_chroot" = "$DEFAULT_CHROOT_DIR" ]]; then
467 CHROOT_EXAMPLE_OPT=""
468else
469 CHROOT_EXAMPLE_OPT="--chroot=$FLAGS_chroot"
470fi
471
472print_time_elapsed
473
474echo
475echo "$SCRIPT_NAME: All set up. To enter the chroot, run:"
476echo "$SCRIPT_NAME: $ cros_sdk --enter $CHROOT_EXAMPLE_OPT"
477echo ""
478echo "CAUTION: Do *NOT* rm -rf the chroot directory; if there are stale bind"
479echo "mounts you may end up deleting your source tree too. To unmount and"
480echo "delete the chroot cleanly, use:"
481echo "$ $SCRIPT_NAME --delete $CHROOT_EXAMPLE_OPT"