blob: 06328e23fcf7a8c7384a465181914ab045bf4f53 [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.
50 keypath = os.path.join (os.path.realpath(chromeos_root),
cmtice13909242014-03-11 13:38:07 -070051 "src/scripts/mod_for_test_scripts/ssh_keys/"
52 "testing_rsa")
cmtice0cc4e772014-01-30 15:52:37 -080053
54 command = ("ssh -i %s -o StrictHostKeyChecking=no -o CheckHostIP=no "
55 "-o BatchMode=yes root@%s \"python -c 'import cherrypy'\" " %
56 (keypath,remote) )
57 retval = cmd_executer.RunCommand (command)
58 if retval == 0:
59 remote_has_cherrypy = True
60
61 return (chroot_has_cros_flash and remote_has_cherrypy)
62
Ahmad Sharif4467f002012-12-20 12:09:49 -080063def DoImage(argv):
Ahmad Sharif70de27b2011-06-15 17:51:24 -070064 """Build ChromeOS."""
Ahmad Sharif4467f002012-12-20 12:09:49 -080065
Ahmad Sharif70de27b2011-06-15 17:51:24 -070066 parser = optparse.OptionParser()
67 parser.add_option("-c", "--chromeos_root", dest="chromeos_root",
68 help="Target directory for ChromeOS installation.")
69 parser.add_option("-r", "--remote", dest="remote",
70 help="Target device.")
71 parser.add_option("-i", "--image", dest="image",
72 help="Image binary file.")
73 parser.add_option("-b", "--board", dest="board",
74 help="Target board override.")
75 parser.add_option("-f", "--force", dest="force",
76 action="store_true",
77 default=False,
78 help="Force an image even if it is non-test.")
cmtice13909242014-03-11 13:38:07 -070079 parser.add_option("-l", "--logging_level", dest="log_level",
80 default="verbose",
81 help="Amount of logging to be used. Valid levels are "
82 "'quiet', 'average', and 'verbose'.")
Ahmad Sharif0dcbc4b2012-02-02 16:37:18 -080083 parser.add_option("-a",
Ahmad Sharif4467f002012-12-20 12:09:49 -080084 "--image_args",
85 dest="image_args")
Ahmad Sharif0dcbc4b2012-02-02 16:37:18 -080086
Ahmad Sharif70de27b2011-06-15 17:51:24 -070087
88 options = parser.parse_args(argv[1:])[0]
89
cmtice13909242014-03-11 13:38:07 -070090 if not options.log_level in command_executer.LOG_LEVEL:
91 Usage(parser, "--logging_level must be 'quiet', 'average' or 'verbose'")
92 else:
93 log_level = options.log_level
94
95 # Common initializations
96 cmd_executer = command_executer.GetCommandExecuter(log_level=log_level)
97 l = logger.GetLogger()
98
Ahmad Sharif70de27b2011-06-15 17:51:24 -070099 if options.chromeos_root is None:
100 Usage(parser, "--chromeos_root must be set")
101
102 if options.remote is None:
103 Usage(parser, "--remote must be set")
104
105 options.chromeos_root = os.path.expanduser(options.chromeos_root)
106
107 if options.board is None:
108 board = cmd_executer.CrosLearnBoard(options.chromeos_root, options.remote)
109 else:
110 board = options.board
111
112 if options.image is None:
Ahmad Shariffd356fb2012-05-07 12:02:16 -0700113 images_dir = misc.GetImageDir(options.chromeos_root, board)
114 image = os.path.join(images_dir,
115 "latest",
116 "chromiumos_test_image.bin")
117 if not os.path.exists(image):
118 image = os.path.join(images_dir,
119 "latest",
120 "chromiumos_image.bin")
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700121 else:
122 image = options.image
cmtice0cc4e772014-01-30 15:52:37 -0800123 if image.find("xbuddy://") < 0:
124 image = os.path.expanduser(image)
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700125
cmtice0cc4e772014-01-30 15:52:37 -0800126 if image.find("xbuddy://") < 0:
127 image = os.path.realpath(image)
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700128
cmtice0cc4e772014-01-30 15:52:37 -0800129 if not os.path.exists(image) and image.find("xbuddy://") < 0:
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700130 Usage(parser, "Image file: " + image + " does not exist!")
131
cmtice0cc4e772014-01-30 15:52:37 -0800132 reimage = False
133 local_image = False
134 if image.find("xbuddy://") < 0:
135 local_image = True
cmtice13909242014-03-11 13:38:07 -0700136 image_checksum = FileUtils().Md5File(image, log_level=log_level)
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700137
cmtice0cc4e772014-01-30 15:52:37 -0800138 command = "cat " + checksum_file
139 retval, device_checksum, err = cmd_executer.CrosRunCommand(command,
140 return_output=True,
141 chromeos_root=options.chromeos_root,
142 machine=options.remote)
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700143
cmtice0cc4e772014-01-30 15:52:37 -0800144 device_checksum = device_checksum.strip()
145 image_checksum = str(image_checksum)
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700146
cmtice0cc4e772014-01-30 15:52:37 -0800147 l.LogOutput("Image checksum: " + image_checksum)
148 l.LogOutput("Device checksum: " + device_checksum)
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700149
cmtice0cc4e772014-01-30 15:52:37 -0800150 if image_checksum != device_checksum:
151 [found, located_image] = LocateOrCopyImage(options.chromeos_root,
152 image,
153 board=board)
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700154
cmtice0cc4e772014-01-30 15:52:37 -0800155 reimage = True
156 l.LogOutput("Checksums do not match. Re-imaging...")
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700157
cmtice0cc4e772014-01-30 15:52:37 -0800158 is_test_image = IsImageModdedForTest(options.chromeos_root,
cmtice13909242014-03-11 13:38:07 -0700159 located_image, log_level)
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700160
cmtice0cc4e772014-01-30 15:52:37 -0800161 if not is_test_image and not options.force:
162 logger.GetLogger().LogFatal("Have to pass --force to image a non-test "
163 "image!")
164 else:
165 reimage = True
166 found = True
167 l.LogOutput("Using non-local image; Re-imaging...")
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700168
cmtice0cc4e772014-01-30 15:52:37 -0800169
170 if reimage:
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700171 # If the device has /tmp mounted as noexec, image_to_live.sh can fail.
172 command = "mount -o remount,rw,exec /tmp"
173 cmd_executer.CrosRunCommand(command,
174 chromeos_root=options.chromeos_root,
175 machine=options.remote)
176
Ahmad Sharif4467f002012-12-20 12:09:49 -0800177 real_src_dir = os.path.join(os.path.realpath(options.chromeos_root),
178 "src")
cmtice0cc4e772014-01-30 15:52:37 -0800179 if local_image:
180 if located_image.find(real_src_dir) != 0:
181 raise Exception("Located image: %s not in chromeos_root: %s" %
182 (located_image, options.chromeos_root))
183 chroot_image = os.path.join(
184 "..",
185 located_image[len(real_src_dir):].lstrip("/"))
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700186
cmticefd06cca2014-01-29 14:21:44 -0800187 # Check to see if cros flash is in the chroot or not.
cmtice0cc4e772014-01-30 15:52:37 -0800188 use_cros_flash = CheckForCrosFlash (options.chromeos_root,
cmtice13909242014-03-11 13:38:07 -0700189 options.remote, log_level)
cmtice0cc4e772014-01-30 15:52:37 -0800190
191 if use_cros_flash:
cmticefd06cca2014-01-29 14:21:44 -0800192 # Use 'cros flash'
cmtice0cc4e772014-01-30 15:52:37 -0800193 if local_image:
194 cros_flash_args = ["--board=%s" % board,
195 "--clobber-stateful",
196 options.remote,
197 chroot_image]
198 else:
199
200 cros_flash_args = ["--board=%s" % board,
201 "--clobber-stateful",
202 options.remote,
203 image]
cmticefd06cca2014-01-29 14:21:44 -0800204
205 command = ("cros flash %s" % " ".join(cros_flash_args))
cmtice0cc4e772014-01-30 15:52:37 -0800206 elif local_image:
cmticefd06cca2014-01-29 14:21:44 -0800207 # Use 'cros_image_to_target.py'
cmticefd06cca2014-01-29 14:21:44 -0800208 cros_image_to_target_args = ["--remote=%s" % options.remote,
209 "--board=%s" % board,
210 "--from=%s" % os.path.dirname(chroot_image),
211 "--image-name=%s" %
212 os.path.basename(located_image)]
213
214 command = ("./bin/cros_image_to_target.py %s" %
215 " ".join(cros_image_to_target_args))
216 if options.image_args:
217 command += " %s" % options.image_args
cmtice0cc4e772014-01-30 15:52:37 -0800218 else:
219 raise Exception("Unable to find 'cros flash' in chroot; cannot use "
220 "non-local image (%s) with cros_image_to_target.py" %
221 image)
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700222
Ahmad Sharif4467f002012-12-20 12:09:49 -0800223 # Workaround for crosbug.com/35684.
224 os.chmod(misc.GetChromeOSKeyFile(options.chromeos_root), 0600)
cmtice13909242014-03-11 13:38:07 -0700225 if log_level == "quiet":
226 l.LogOutput("CMD : %s" % command)
227 elif log_level == "average":
228 cmd_executer.SetLogLevel("verbose");
Ahmad Sharif4467f002012-12-20 12:09:49 -0800229 retval = cmd_executer.ChrootRunCommand(options.chromeos_root,
cmticeb1340082014-01-13 13:22:37 -0800230 command, command_timeout=600)
231
232 retries = 0
233 while retval != 0 and retries < 2:
234 retries += 1
cmtice13909242014-03-11 13:38:07 -0700235 if log_level == "quiet":
236 l.LogOutput("Imaging failed. Retry # %d." % retries)
237 l.LogOutput("CMD : %s" % command)
cmticeb1340082014-01-13 13:22:37 -0800238 retval = cmd_executer.ChrootRunCommand(options.chromeos_root,
239 command, command_timeout=600)
240
cmtice13909242014-03-11 13:38:07 -0700241 if log_level == "average":
242 cmd_executer.SetLogLevel(log_level)
243
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700244 if found == False:
245 temp_dir = os.path.dirname(located_image)
246 l.LogOutput("Deleting temp image dir: %s" % temp_dir)
247 shutil.rmtree(temp_dir)
248
249 logger.GetLogger().LogFatalIf(retval, "Image command failed")
Ahmad Sharif4467f002012-12-20 12:09:49 -0800250
251 # Unfortunately cros_image_to_target.py sometimes returns early when the
252 # machine isn't fully up yet.
cmtice13909242014-03-11 13:38:07 -0700253 retval = EnsureMachineUp(options.chromeos_root, options.remote,
254 log_level)
Ahmad Sharif4467f002012-12-20 12:09:49 -0800255
cmtice0cc4e772014-01-30 15:52:37 -0800256 # If this is a non-local image, then the retval returned from
257 # EnsureMachineUp is the one that will be returned by this function;
258 # in that case, make sure the value in 'retval' is appropriate.
259 if not local_image and retval == True:
260 retval = 0
261 else:
262 retval = 1
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700263
cmtice0cc4e772014-01-30 15:52:37 -0800264 if local_image:
cmtice13909242014-03-11 13:38:07 -0700265 if log_level == "average":
266 l.LogOutput("Verifying image.")
cmtice0cc4e772014-01-30 15:52:37 -0800267 command = "echo %s > %s && chmod -w %s" % (image_checksum,
268 checksum_file,
269 checksum_file)
270 retval = cmd_executer.CrosRunCommand(command,
271 chromeos_root=options.chromeos_root,
272 machine=options.remote)
273 logger.GetLogger().LogFatalIf(retval, "Writing checksum failed.")
274
275 successfully_imaged = VerifyChromeChecksum(options.chromeos_root,
276 image,
cmtice13909242014-03-11 13:38:07 -0700277 options.remote, log_level)
cmtice0cc4e772014-01-30 15:52:37 -0800278 logger.GetLogger().LogFatalIf(not successfully_imaged,
279 "Image verification failed!")
cmtice13909242014-03-11 13:38:07 -0700280 TryRemountPartitionAsRW(options.chromeos_root, options.remote,
281 log_level)
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700282 else:
283 l.LogOutput("Checksums match. Skipping reimage")
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700284 return retval
285
286
287def LocateOrCopyImage(chromeos_root, image, board=None):
288 l = logger.GetLogger()
289 if board is None:
290 board_glob = "*"
291 else:
292 board_glob = board
293
294 chromeos_root_realpath = os.path.realpath(chromeos_root)
295 image = os.path.realpath(image)
Ahmad Sharif0dcbc4b2012-02-02 16:37:18 -0800296
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700297 if image.startswith("%s/" % chromeos_root_realpath):
298 return [True, image]
299
300 # First search within the existing build dirs for any matching files.
301 images_glob = ("%s/src/build/images/%s/*/*.bin" %
302 (chromeos_root_realpath,
303 board_glob))
304 images_list = glob.glob(images_glob)
305 for potential_image in images_list:
306 if filecmp.cmp(potential_image, image):
307 l.LogOutput("Found matching image %s in chromeos_root." % potential_image)
308 return [True, potential_image]
cmtice13909242014-03-11 13:38:07 -0700309 # We did not find an image. Copy it in the src dir and return the copied
310 # file.
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700311 if board is None:
312 board = ""
313 base_dir = ("%s/src/build/images/%s" %
314 (chromeos_root_realpath,
315 board))
316 if not os.path.isdir(base_dir):
317 os.makedirs(base_dir)
318 temp_dir = tempfile.mkdtemp(prefix="%s/tmp" % base_dir)
319 new_image = "%s/%s" % (temp_dir, os.path.basename(image))
320 l.LogOutput("No matching image found. Copying %s to %s" %
321 (image, new_image))
322 shutil.copyfile(image, new_image)
323 return [False, new_image]
324
325
Ahmad Sharif0dcbc4b2012-02-02 16:37:18 -0800326def GetImageMountCommand(chromeos_root, image, rootfs_mp, stateful_mp):
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700327 image_dir = os.path.dirname(image)
328 image_file = os.path.basename(image)
329 mount_command = ("cd %s/src/scripts &&"
330 "./mount_gpt_image.sh --from=%s --image=%s"
331 " --safe --read_only"
Ahmad Sharif0dcbc4b2012-02-02 16:37:18 -0800332 " --rootfs_mountpt=%s"
333 " --stateful_mountpt=%s" %
334 (chromeos_root, image_dir, image_file, rootfs_mp,
335 stateful_mp))
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700336 return mount_command
337
338
cmtice13909242014-03-11 13:38:07 -0700339def MountImage(chromeos_root, image, rootfs_mp, stateful_mp, log_level,
340 unmount=False):
341 cmd_executer = command_executer.GetCommandExecuter(log_level=log_level)
Ahmad Sharif0dcbc4b2012-02-02 16:37:18 -0800342 command = GetImageMountCommand(chromeos_root, image, rootfs_mp, stateful_mp)
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700343 if unmount:
344 command = "%s --unmount" % command
345 retval = cmd_executer.RunCommand(command)
346 logger.GetLogger().LogFatalIf(retval, "Mount/unmount command failed!")
347 return retval
348
349
cmtice13909242014-03-11 13:38:07 -0700350def IsImageModdedForTest(chromeos_root, image, log_level):
351 if log_level != "verbose":
352 log_level = "quiet"
Ahmad Sharif0dcbc4b2012-02-02 16:37:18 -0800353 rootfs_mp = tempfile.mkdtemp()
354 stateful_mp = tempfile.mkdtemp()
cmtice13909242014-03-11 13:38:07 -0700355 MountImage(chromeos_root, image, rootfs_mp, stateful_mp, log_level)
Ahmad Sharif0dcbc4b2012-02-02 16:37:18 -0800356 lsb_release_file = os.path.join(rootfs_mp, "etc/lsb-release")
Ahmad Shariff395c262012-10-09 17:48:09 -0700357 lsb_release_contents = open(lsb_release_file).read()
358 is_test_image = re.search("test", lsb_release_contents, re.IGNORECASE)
cmtice13909242014-03-11 13:38:07 -0700359 MountImage(chromeos_root, image, rootfs_mp, stateful_mp, log_level,
360 unmount=True)
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700361 return is_test_image
362
363
cmtice13909242014-03-11 13:38:07 -0700364def VerifyChromeChecksum(chromeos_root, image, remote, log_level):
365 cmd_executer = command_executer.GetCommandExecuter(log_level=log_level)
Ahmad Sharif0dcbc4b2012-02-02 16:37:18 -0800366 rootfs_mp = tempfile.mkdtemp()
367 stateful_mp = tempfile.mkdtemp()
cmtice13909242014-03-11 13:38:07 -0700368 MountImage(chromeos_root, image, rootfs_mp, stateful_mp, log_level)
Ahmad Sharif0dcbc4b2012-02-02 16:37:18 -0800369 image_chrome_checksum = FileUtils().Md5File("%s/opt/google/chrome/chrome" %
cmtice13909242014-03-11 13:38:07 -0700370 rootfs_mp,
371 log_level=log_level)
372 MountImage(chromeos_root, image, rootfs_mp, stateful_mp, log_level,
373 unmount=True)
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700374
375 command = "md5sum /opt/google/chrome/chrome"
376 [r, o, e] = cmd_executer.CrosRunCommand(command,
377 return_output=True,
378 chromeos_root=chromeos_root,
379 machine=remote)
380 device_chrome_checksum = o.split()[0]
381 if image_chrome_checksum.strip() == device_chrome_checksum.strip():
382 return True
383 else:
384 return False
385
Luis Lozanof81680c2013-03-15 14:44:13 -0700386# Remount partition as writable.
387# TODO: auto-detect if an image is built using --noenable_rootfs_verification.
cmtice13909242014-03-11 13:38:07 -0700388def TryRemountPartitionAsRW(chromeos_root, remote, log_level):
Luis Lozanof81680c2013-03-15 14:44:13 -0700389 l = logger.GetLogger()
cmtice13909242014-03-11 13:38:07 -0700390 cmd_executer = command_executer.GetCommandExecuter(log_level=log_level)
Luis Lozanof81680c2013-03-15 14:44:13 -0700391 command = "sudo mount -o remount,rw /"
392 retval = cmd_executer.CrosRunCommand(\
393 command, chromeos_root=chromeos_root, machine=remote, terminated_timeout=10)
394 if retval:
395 ## Safely ignore.
396 l.LogWarning("Failed to remount partition as rw, "
397 "probably the image was not built with "
398 "\"--noenable_rootfs_verification\", "
399 "you can safely ignore this.")
400 else:
401 l.LogOutput("Re-mounted partition as writable.")
402
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700403
cmtice13909242014-03-11 13:38:07 -0700404def EnsureMachineUp(chromeos_root, remote, log_level):
Ahmad Sharif4467f002012-12-20 12:09:49 -0800405 l = logger.GetLogger()
cmtice13909242014-03-11 13:38:07 -0700406 cmd_executer = command_executer.GetCommandExecuter(log_level=log_level)
Ahmad Sharif4467f002012-12-20 12:09:49 -0800407 timeout = 600
408 magic = "abcdefghijklmnopqrstuvwxyz"
409 command = "echo %s" % magic
410 start_time = time.time()
411 while True:
412 current_time = time.time()
413 if current_time - start_time > timeout:
414 l.LogError("Timeout of %ss reached. Machine still not up. Aborting." %
415 timeout)
416 return False
417 retval = cmd_executer.CrosRunCommand(command,
418 chromeos_root=chromeos_root,
419 machine=remote)
420 if not retval:
421 return True
422
423
424def Main(argv):
425 misc.AcquireLock(lock_file)
426 try:
427 return DoImage(argv)
428 finally:
429 misc.ReleaseLock(lock_file)
430
431
Ahmad Sharif70de27b2011-06-15 17:51:24 -0700432if __name__ == "__main__":
433 retval = Main(sys.argv)
434 sys.exit(retval)