blob: 460215aeed91f3d8147f623ee34e8edbafb9aaaf [file] [log] [blame]
Ahmad Sharif4467f002012-12-20 12:09:49 -08001#!/usr/bin/python
Ahmad Sharif70de27b2011-06-15 17:51:24 -07002#
3# Copyright 2011 Google Inc. All Rights Reserved.
4
5"""Script to image a ChromeOS device.
6
7This script images a remote ChromeOS device with a specific image."
8"""
9
10__author__ = "asharif@google.com (Ahmad Sharif)"
11
12import filecmp
13import glob
14import optparse
15import os
Ahmad Shariff395c262012-10-09 17:48:09 -070016import re
Ahmad Sharif70de27b2011-06-15 17:51:24 -070017import shutil
18import sys
19import tempfile
Ahmad Sharif4467f002012-12-20 12:09:49 -080020import time
21
Ahmad Sharif70de27b2011-06-15 17:51:24 -070022from utils import command_executer
23from utils import logger
Ahmad Shariffd356fb2012-05-07 12:02:16 -070024from utils import misc
Ahmad Sharif0dcbc4b2012-02-02 16:37:18 -080025from utils.file_utils import FileUtils
Ahmad Sharif70de27b2011-06-15 17:51:24 -070026
Ahmad Sharif0dcbc4b2012-02-02 16:37:18 -080027checksum_file = "/usr/local/osimage_checksum_file"
Ahmad Sharif4467f002012-12-20 12:09:49 -080028lock_file = "/tmp/image_chromeos_lock/image_chromeos_lock"
Ahmad Sharif70de27b2011-06-15 17:51:24 -070029
30def Usage(parser, message):
31 print "ERROR: " + message
32 parser.print_help()
33 sys.exit(0)
34
Ahmad Shariff395c262012-10-09 17:48:09 -070035
cmtice13909242014-03-11 13:38:07 -070036def CheckForCrosFlash(chromeos_root, remote, log_level):
37 cmd_executer = command_executer.GetCommandExecuter(log_level=log_level)
cmtice0cc4e772014-01-30 15:52:37 -080038
39 chroot_has_cros_flash = False
40 remote_has_cherrypy = False
41
42 # Check to see if chroot contains cros flash.
43 cros_flash_path = os.path.join(os.path.realpath(chromeos_root),
44 "chromite/cros/commands/cros_flash.py")
45
46 if os.path.exists(cros_flash_path):
47 chroot_has_cros_flash = True
48
49 # Check to see if remote machine has cherrypy.
Luis Lozanodd75bad2014-04-21 13:58:16 -070050 command = "python -c 'import cherrypy'"
51 retval = cmd_executer.CrosRunCommand (command,
52 chromeos_root=chromeos_root,
53 machine=remote)
Luis Lozano1e462d92014-04-18 17:49:29 -070054 logger.GetLogger().LogFatalIf(retval == 255, "Failed ssh to %s" % remote)
cmtice0cc4e772014-01-30 15:52:37 -080055 if retval == 0:
56 remote_has_cherrypy = True
57
58 return (chroot_has_cros_flash and remote_has_cherrypy)
59
Ahmad Sharif4467f002012-12-20 12:09:49 -080060def DoImage(argv):
Ahmad Sharif70de27b2011-06-15 17:51:24 -070061 """Build ChromeOS."""
Ahmad Sharif4467f002012-12-20 12:09:49 -080062
Ahmad Sharif70de27b2011-06-15 17:51:24 -070063 parser = optparse.OptionParser()
64 parser.add_option("-c", "--chromeos_root", dest="chromeos_root",
65 help="Target directory for ChromeOS installation.")
66 parser.add_option("-r", "--remote", dest="remote",
67 help="Target device.")
68 parser.add_option("-i", "--image", dest="image",
69 help="Image binary file.")
70 parser.add_option("-b", "--board", dest="board",
71 help="Target board override.")
72 parser.add_option("-f", "--force", dest="force",
73 action="store_true",
74 default=False,
75 help="Force an image even if it is non-test.")
cmtice13909242014-03-11 13:38:07 -070076 parser.add_option("-l", "--logging_level", dest="log_level",
77 default="verbose",
78 help="Amount of logging to be used. Valid levels are "
79 "'quiet', 'average', and 'verbose'.")
Ahmad Sharif0dcbc4b2012-02-02 16:37:18 -080080 parser.add_option("-a",
Ahmad Sharif4467f002012-12-20 12:09:49 -080081 "--image_args",
82 dest="image_args")
Ahmad Sharif0dcbc4b2012-02-02 16:37:18 -080083
Ahmad Sharif70de27b2011-06-15 17:51:24 -070084
85 options = parser.parse_args(argv[1:])[0]
86
cmtice13909242014-03-11 13:38:07 -070087 if not options.log_level in command_executer.LOG_LEVEL:
88 Usage(parser, "--logging_level must be 'quiet', 'average' or 'verbose'")
89 else:
90 log_level = options.log_level
91
92 # Common initializations
93 cmd_executer = command_executer.GetCommandExecuter(log_level=log_level)
94 l = logger.GetLogger()
95
Ahmad Sharif70de27b2011-06-15 17:51:24 -070096 if options.chromeos_root is None:
97 Usage(parser, "--chromeos_root must be set")
98
99 if options.remote is None:
100 Usage(parser, "--remote must be set")
101
102 options.chromeos_root = os.path.expanduser(options.chromeos_root)
103
104 if options.board is None:
105 board = cmd_executer.CrosLearnBoard(options.chromeos_root, options.remote)
106 else:
107 board = options.board
108
109 if options.image is None:
Ahmad Shariffd356fb2012-05-07 12:02:16 -0700110 images_dir = misc.GetImageDir(options.chromeos_root, board)
111 image = os.path.join(images_dir,
112 "latest",
113 "chromiumos_test_image.bin")
114 if not os.path.exists(image):
115 image = os.path.join(images_dir,
116 "latest",
117 "chromiumos_image.bin")
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700118 else:
119 image = options.image
cmtice0cc4e772014-01-30 15:52:37 -0800120 if image.find("xbuddy://") < 0:
121 image = os.path.expanduser(image)
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700122
cmtice0cc4e772014-01-30 15:52:37 -0800123 if image.find("xbuddy://") < 0:
124 image = os.path.realpath(image)
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700125
cmtice0cc4e772014-01-30 15:52:37 -0800126 if not os.path.exists(image) and image.find("xbuddy://") < 0:
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700127 Usage(parser, "Image file: " + image + " does not exist!")
128
cmtice0cc4e772014-01-30 15:52:37 -0800129 reimage = False
130 local_image = False
131 if image.find("xbuddy://") < 0:
132 local_image = True
cmtice13909242014-03-11 13:38:07 -0700133 image_checksum = FileUtils().Md5File(image, log_level=log_level)
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700134
cmtice0cc4e772014-01-30 15:52:37 -0800135 command = "cat " + checksum_file
136 retval, device_checksum, err = cmd_executer.CrosRunCommand(command,
137 return_output=True,
138 chromeos_root=options.chromeos_root,
139 machine=options.remote)
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700140
cmtice0cc4e772014-01-30 15:52:37 -0800141 device_checksum = device_checksum.strip()
142 image_checksum = str(image_checksum)
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700143
cmtice0cc4e772014-01-30 15:52:37 -0800144 l.LogOutput("Image checksum: " + image_checksum)
145 l.LogOutput("Device checksum: " + device_checksum)
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700146
cmtice0cc4e772014-01-30 15:52:37 -0800147 if image_checksum != device_checksum:
148 [found, located_image] = LocateOrCopyImage(options.chromeos_root,
149 image,
150 board=board)
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700151
cmtice0cc4e772014-01-30 15:52:37 -0800152 reimage = True
153 l.LogOutput("Checksums do not match. Re-imaging...")
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700154
cmtice0cc4e772014-01-30 15:52:37 -0800155 is_test_image = IsImageModdedForTest(options.chromeos_root,
cmtice13909242014-03-11 13:38:07 -0700156 located_image, log_level)
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700157
cmtice0cc4e772014-01-30 15:52:37 -0800158 if not is_test_image and not options.force:
159 logger.GetLogger().LogFatal("Have to pass --force to image a non-test "
160 "image!")
161 else:
162 reimage = True
163 found = True
164 l.LogOutput("Using non-local image; Re-imaging...")
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700165
cmtice0cc4e772014-01-30 15:52:37 -0800166
167 if reimage:
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700168 # If the device has /tmp mounted as noexec, image_to_live.sh can fail.
169 command = "mount -o remount,rw,exec /tmp"
170 cmd_executer.CrosRunCommand(command,
171 chromeos_root=options.chromeos_root,
172 machine=options.remote)
173
Ahmad Sharif4467f002012-12-20 12:09:49 -0800174 real_src_dir = os.path.join(os.path.realpath(options.chromeos_root),
175 "src")
cmtice43f1a452014-04-04 13:15:06 -0700176 real_chroot_dir = os.path.join(os.path.realpath(options.chromeos_root),
177 "chroot")
cmtice0cc4e772014-01-30 15:52:37 -0800178 if local_image:
179 if located_image.find(real_src_dir) != 0:
cmtice43f1a452014-04-04 13:15:06 -0700180 if located_image.find(real_chroot_dir) != 0:
181 raise Exception("Located image: %s not in chromeos_root: %s" %
182 (located_image, options.chromeos_root))
183 else:
184 chroot_image = located_image[len(real_chroot_dir):]
185 else:
186 chroot_image = os.path.join(
187 "..",
188 located_image[len(real_src_dir):].lstrip("/"))
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700189
cmticefd06cca2014-01-29 14:21:44 -0800190 # Check to see if cros flash is in the chroot or not.
cmtice0cc4e772014-01-30 15:52:37 -0800191 use_cros_flash = CheckForCrosFlash (options.chromeos_root,
cmtice13909242014-03-11 13:38:07 -0700192 options.remote, log_level)
cmtice0cc4e772014-01-30 15:52:37 -0800193
194 if use_cros_flash:
cmticefd06cca2014-01-29 14:21:44 -0800195 # Use 'cros flash'
cmtice0cc4e772014-01-30 15:52:37 -0800196 if local_image:
197 cros_flash_args = ["--board=%s" % board,
198 "--clobber-stateful",
199 options.remote,
200 chroot_image]
201 else:
202
203 cros_flash_args = ["--board=%s" % board,
204 "--clobber-stateful",
205 options.remote,
206 image]
cmticefd06cca2014-01-29 14:21:44 -0800207
208 command = ("cros flash %s" % " ".join(cros_flash_args))
cmtice0cc4e772014-01-30 15:52:37 -0800209 elif local_image:
cmticefd06cca2014-01-29 14:21:44 -0800210 # Use 'cros_image_to_target.py'
cmticefd06cca2014-01-29 14:21:44 -0800211 cros_image_to_target_args = ["--remote=%s" % options.remote,
212 "--board=%s" % board,
213 "--from=%s" % os.path.dirname(chroot_image),
214 "--image-name=%s" %
215 os.path.basename(located_image)]
216
217 command = ("./bin/cros_image_to_target.py %s" %
218 " ".join(cros_image_to_target_args))
219 if options.image_args:
220 command += " %s" % options.image_args
cmtice0cc4e772014-01-30 15:52:37 -0800221 else:
222 raise Exception("Unable to find 'cros flash' in chroot; cannot use "
223 "non-local image (%s) with cros_image_to_target.py" %
224 image)
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700225
Ahmad Sharif4467f002012-12-20 12:09:49 -0800226 # Workaround for crosbug.com/35684.
227 os.chmod(misc.GetChromeOSKeyFile(options.chromeos_root), 0600)
cmtice13909242014-03-11 13:38:07 -0700228 if log_level == "quiet":
229 l.LogOutput("CMD : %s" % command)
230 elif log_level == "average":
231 cmd_executer.SetLogLevel("verbose");
Ahmad Sharif4467f002012-12-20 12:09:49 -0800232 retval = cmd_executer.ChrootRunCommand(options.chromeos_root,
cmtice6de7f8f2014-03-14 14:08:21 -0700233 command, command_timeout=1800)
cmticeb1340082014-01-13 13:22:37 -0800234
235 retries = 0
236 while retval != 0 and retries < 2:
237 retries += 1
cmtice13909242014-03-11 13:38:07 -0700238 if log_level == "quiet":
239 l.LogOutput("Imaging failed. Retry # %d." % retries)
240 l.LogOutput("CMD : %s" % command)
cmticeb1340082014-01-13 13:22:37 -0800241 retval = cmd_executer.ChrootRunCommand(options.chromeos_root,
cmtice6de7f8f2014-03-14 14:08:21 -0700242 command, command_timeout=1800)
cmticeb1340082014-01-13 13:22:37 -0800243
cmtice13909242014-03-11 13:38:07 -0700244 if log_level == "average":
245 cmd_executer.SetLogLevel(log_level)
246
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700247 if found == False:
248 temp_dir = os.path.dirname(located_image)
249 l.LogOutput("Deleting temp image dir: %s" % temp_dir)
250 shutil.rmtree(temp_dir)
251
252 logger.GetLogger().LogFatalIf(retval, "Image command failed")
Ahmad Sharif4467f002012-12-20 12:09:49 -0800253
254 # Unfortunately cros_image_to_target.py sometimes returns early when the
255 # machine isn't fully up yet.
cmtice13909242014-03-11 13:38:07 -0700256 retval = EnsureMachineUp(options.chromeos_root, options.remote,
257 log_level)
Ahmad Sharif4467f002012-12-20 12:09:49 -0800258
cmtice0cc4e772014-01-30 15:52:37 -0800259 # If this is a non-local image, then the retval returned from
260 # EnsureMachineUp is the one that will be returned by this function;
261 # in that case, make sure the value in 'retval' is appropriate.
262 if not local_image and retval == True:
263 retval = 0
264 else:
265 retval = 1
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700266
cmtice0cc4e772014-01-30 15:52:37 -0800267 if local_image:
cmtice13909242014-03-11 13:38:07 -0700268 if log_level == "average":
269 l.LogOutput("Verifying image.")
cmtice0cc4e772014-01-30 15:52:37 -0800270 command = "echo %s > %s && chmod -w %s" % (image_checksum,
271 checksum_file,
272 checksum_file)
273 retval = cmd_executer.CrosRunCommand(command,
274 chromeos_root=options.chromeos_root,
275 machine=options.remote)
276 logger.GetLogger().LogFatalIf(retval, "Writing checksum failed.")
277
278 successfully_imaged = VerifyChromeChecksum(options.chromeos_root,
279 image,
cmtice13909242014-03-11 13:38:07 -0700280 options.remote, log_level)
cmtice0cc4e772014-01-30 15:52:37 -0800281 logger.GetLogger().LogFatalIf(not successfully_imaged,
282 "Image verification failed!")
cmtice13909242014-03-11 13:38:07 -0700283 TryRemountPartitionAsRW(options.chromeos_root, options.remote,
284 log_level)
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700285 else:
286 l.LogOutput("Checksums match. Skipping reimage")
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700287 return retval
288
289
290def LocateOrCopyImage(chromeos_root, image, board=None):
291 l = logger.GetLogger()
292 if board is None:
293 board_glob = "*"
294 else:
295 board_glob = board
296
297 chromeos_root_realpath = os.path.realpath(chromeos_root)
298 image = os.path.realpath(image)
Ahmad Sharif0dcbc4b2012-02-02 16:37:18 -0800299
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700300 if image.startswith("%s/" % chromeos_root_realpath):
301 return [True, image]
302
303 # First search within the existing build dirs for any matching files.
304 images_glob = ("%s/src/build/images/%s/*/*.bin" %
305 (chromeos_root_realpath,
306 board_glob))
307 images_list = glob.glob(images_glob)
308 for potential_image in images_list:
309 if filecmp.cmp(potential_image, image):
310 l.LogOutput("Found matching image %s in chromeos_root." % potential_image)
311 return [True, potential_image]
cmtice13909242014-03-11 13:38:07 -0700312 # We did not find an image. Copy it in the src dir and return the copied
313 # file.
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700314 if board is None:
315 board = ""
316 base_dir = ("%s/src/build/images/%s" %
317 (chromeos_root_realpath,
318 board))
319 if not os.path.isdir(base_dir):
320 os.makedirs(base_dir)
321 temp_dir = tempfile.mkdtemp(prefix="%s/tmp" % base_dir)
322 new_image = "%s/%s" % (temp_dir, os.path.basename(image))
323 l.LogOutput("No matching image found. Copying %s to %s" %
324 (image, new_image))
325 shutil.copyfile(image, new_image)
326 return [False, new_image]
327
328
Ahmad Sharif0dcbc4b2012-02-02 16:37:18 -0800329def GetImageMountCommand(chromeos_root, image, rootfs_mp, stateful_mp):
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700330 image_dir = os.path.dirname(image)
331 image_file = os.path.basename(image)
332 mount_command = ("cd %s/src/scripts &&"
333 "./mount_gpt_image.sh --from=%s --image=%s"
334 " --safe --read_only"
Ahmad Sharif0dcbc4b2012-02-02 16:37:18 -0800335 " --rootfs_mountpt=%s"
336 " --stateful_mountpt=%s" %
337 (chromeos_root, image_dir, image_file, rootfs_mp,
338 stateful_mp))
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700339 return mount_command
340
341
cmtice13909242014-03-11 13:38:07 -0700342def MountImage(chromeos_root, image, rootfs_mp, stateful_mp, log_level,
343 unmount=False):
344 cmd_executer = command_executer.GetCommandExecuter(log_level=log_level)
Ahmad Sharif0dcbc4b2012-02-02 16:37:18 -0800345 command = GetImageMountCommand(chromeos_root, image, rootfs_mp, stateful_mp)
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700346 if unmount:
347 command = "%s --unmount" % command
348 retval = cmd_executer.RunCommand(command)
349 logger.GetLogger().LogFatalIf(retval, "Mount/unmount command failed!")
350 return retval
351
352
cmtice13909242014-03-11 13:38:07 -0700353def IsImageModdedForTest(chromeos_root, image, log_level):
354 if log_level != "verbose":
355 log_level = "quiet"
Ahmad Sharif0dcbc4b2012-02-02 16:37:18 -0800356 rootfs_mp = tempfile.mkdtemp()
357 stateful_mp = tempfile.mkdtemp()
cmtice13909242014-03-11 13:38:07 -0700358 MountImage(chromeos_root, image, rootfs_mp, stateful_mp, log_level)
Ahmad Sharif0dcbc4b2012-02-02 16:37:18 -0800359 lsb_release_file = os.path.join(rootfs_mp, "etc/lsb-release")
Ahmad Shariff395c262012-10-09 17:48:09 -0700360 lsb_release_contents = open(lsb_release_file).read()
361 is_test_image = re.search("test", lsb_release_contents, re.IGNORECASE)
cmtice13909242014-03-11 13:38:07 -0700362 MountImage(chromeos_root, image, rootfs_mp, stateful_mp, log_level,
363 unmount=True)
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700364 return is_test_image
365
366
cmtice13909242014-03-11 13:38:07 -0700367def VerifyChromeChecksum(chromeos_root, image, remote, log_level):
368 cmd_executer = command_executer.GetCommandExecuter(log_level=log_level)
Ahmad Sharif0dcbc4b2012-02-02 16:37:18 -0800369 rootfs_mp = tempfile.mkdtemp()
370 stateful_mp = tempfile.mkdtemp()
cmtice13909242014-03-11 13:38:07 -0700371 MountImage(chromeos_root, image, rootfs_mp, stateful_mp, log_level)
Ahmad Sharif0dcbc4b2012-02-02 16:37:18 -0800372 image_chrome_checksum = FileUtils().Md5File("%s/opt/google/chrome/chrome" %
cmtice13909242014-03-11 13:38:07 -0700373 rootfs_mp,
374 log_level=log_level)
375 MountImage(chromeos_root, image, rootfs_mp, stateful_mp, log_level,
376 unmount=True)
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700377
378 command = "md5sum /opt/google/chrome/chrome"
379 [r, o, e] = cmd_executer.CrosRunCommand(command,
380 return_output=True,
381 chromeos_root=chromeos_root,
382 machine=remote)
383 device_chrome_checksum = o.split()[0]
384 if image_chrome_checksum.strip() == device_chrome_checksum.strip():
385 return True
386 else:
387 return False
388
Luis Lozanof81680c2013-03-15 14:44:13 -0700389# Remount partition as writable.
390# TODO: auto-detect if an image is built using --noenable_rootfs_verification.
cmtice13909242014-03-11 13:38:07 -0700391def TryRemountPartitionAsRW(chromeos_root, remote, log_level):
Luis Lozanof81680c2013-03-15 14:44:13 -0700392 l = logger.GetLogger()
cmtice13909242014-03-11 13:38:07 -0700393 cmd_executer = command_executer.GetCommandExecuter(log_level=log_level)
Luis Lozanof81680c2013-03-15 14:44:13 -0700394 command = "sudo mount -o remount,rw /"
395 retval = cmd_executer.CrosRunCommand(\
396 command, chromeos_root=chromeos_root, machine=remote, terminated_timeout=10)
397 if retval:
398 ## Safely ignore.
399 l.LogWarning("Failed to remount partition as rw, "
400 "probably the image was not built with "
401 "\"--noenable_rootfs_verification\", "
402 "you can safely ignore this.")
403 else:
404 l.LogOutput("Re-mounted partition as writable.")
405
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700406
cmtice13909242014-03-11 13:38:07 -0700407def EnsureMachineUp(chromeos_root, remote, log_level):
Ahmad Sharif4467f002012-12-20 12:09:49 -0800408 l = logger.GetLogger()
cmtice13909242014-03-11 13:38:07 -0700409 cmd_executer = command_executer.GetCommandExecuter(log_level=log_level)
Ahmad Sharif4467f002012-12-20 12:09:49 -0800410 timeout = 600
411 magic = "abcdefghijklmnopqrstuvwxyz"
412 command = "echo %s" % magic
413 start_time = time.time()
414 while True:
415 current_time = time.time()
416 if current_time - start_time > timeout:
417 l.LogError("Timeout of %ss reached. Machine still not up. Aborting." %
418 timeout)
419 return False
420 retval = cmd_executer.CrosRunCommand(command,
421 chromeos_root=chromeos_root,
422 machine=remote)
423 if not retval:
424 return True
425
426
427def Main(argv):
428 misc.AcquireLock(lock_file)
429 try:
430 return DoImage(argv)
431 finally:
432 misc.ReleaseLock(lock_file)
433
434
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700435if __name__ == "__main__":
436 retval = Main(sys.argv)
437 sys.exit(retval)