Synced repos to: 64740
diff --git a/image_chromeos.py b/image_chromeos.py
index 380a94f..30b29a4 100755
--- a/image_chromeos.py
+++ b/image_chromeos.py
@@ -1,4 +1,4 @@
-#!/usr/bin/python2.6
+#!/usr/bin/python
 #
 # Copyright 2011 Google Inc. All Rights Reserved.
 
@@ -9,7 +9,6 @@
 
 __author__ = "asharif@google.com (Ahmad Sharif)"
 
-import fcntl
 import filecmp
 import glob
 import optparse
@@ -18,13 +17,15 @@
 import shutil
 import sys
 import tempfile
+import time
+
 from utils import command_executer
 from utils import logger
 from utils import misc
 from utils.file_utils import FileUtils
 
 checksum_file = "/usr/local/osimage_checksum_file"
-lock_file = "/tmp/lock_image_chromeos"
+lock_file = "/tmp/image_chromeos_lock/image_chromeos_lock"
 
 def Usage(parser, message):
   print "ERROR: " + message
@@ -32,17 +33,9 @@
   sys.exit(0)
 
 
-def Main(argv):
+def DoImage(argv):
   """Build ChromeOS."""
-  #Get lock for the host
-  f = open(lock_file, "w+a")
-  try:
-    fcntl.lockf(f, fcntl.LOCK_EX|fcntl.LOCK_NB)
-  except IOError:
-    f.close()
-    print ("You can not run two instances of image_chromes at the same time."
-           "\nTry again. Exiting ....")
-    exit(0)
+
   # Common initializations
   cmd_executer = command_executer.GetCommandExecuter()
   l = logger.GetLogger()
@@ -61,8 +54,8 @@
                     default=False,
                     help="Force an image even if it is non-test.")
   parser.add_option("-a",
-                    "--image_to_live_args",
-                    dest="image_to_live_args")
+                    "--image_args",
+                    dest="image_args")
 
 
   options = parser.parse_args(argv[1:])[0]
@@ -132,21 +125,40 @@
                                 chromeos_root=options.chromeos_root,
                                 machine=options.remote)
 
-    command = (options.chromeos_root +
-               "/src/scripts/image_to_live.sh --remote=" +
-               options.remote +
-               " --image=" + located_image)
-    if options.image_to_live_args:
-      command += " %s" % options.image_to_live_args
+    real_src_dir = os.path.join(os.path.realpath(options.chromeos_root),
+                                "src")
+    if located_image.find(real_src_dir) != 0:
+      raise Exception("Located image: %s not in chromeos_root: %s" %
+                      (located_image, options.chromeos_root))
+    chroot_image = os.path.join(
+        "..",
+        located_image[len(real_src_dir):].lstrip("/"))
+    cros_image_to_target_args = ["--remote=%s" % options.remote,
+                                 "--board=%s" % board,
+                                 "--from=%s" % os.path.dirname(chroot_image),
+                                 "--image-name=%s" %
+                                 os.path.basename(located_image)]
 
-    retval = cmd_executer.RunCommand(command)
+    command = ("./bin/cros_image_to_target.py %s" %
+               " ".join(cros_image_to_target_args))
+    if options.image_args:
+      command += " %s" % options.image_args
 
+    # Workaround for crosbug.com/35684.
+    os.chmod(misc.GetChromeOSKeyFile(options.chromeos_root), 0600)
+    retval = cmd_executer.ChrootRunCommand(options.chromeos_root,
+                                           command)
     if found == False:
       temp_dir = os.path.dirname(located_image)
       l.LogOutput("Deleting temp image dir: %s" % temp_dir)
       shutil.rmtree(temp_dir)
 
     logger.GetLogger().LogFatalIf(retval, "Image command failed")
+
+    # Unfortunately cros_image_to_target.py sometimes returns early when the
+    # machine isn't fully up yet.
+    retval = EnsureMachineUp(options.chromeos_root, options.remote)
+
     command = "echo %s > %s && chmod -w %s" % (image_checksum, checksum_file,
                                                checksum_file)
     retval = cmd_executer.CrosRunCommand(command,
@@ -161,9 +173,6 @@
                                   "Image verification failed!")
   else:
     l.LogOutput("Checksums match. Skipping reimage")
-
-  fcntl.lockf(f, fcntl.LOCK_UN)
-  f.close()
   return retval
 
 
@@ -260,6 +269,34 @@
     return False
 
 
+def EnsureMachineUp(chromeos_root, remote):
+  l = logger.GetLogger()
+  cmd_executer = command_executer.GetCommandExecuter()
+  timeout = 600
+  magic = "abcdefghijklmnopqrstuvwxyz"
+  command = "echo %s" % magic
+  start_time = time.time()
+  while True:
+    current_time = time.time()
+    if current_time - start_time > timeout:
+      l.LogError("Timeout of %ss reached. Machine still not up. Aborting." %
+                 timeout)
+      return False
+    retval = cmd_executer.CrosRunCommand(command,
+                                         chromeos_root=chromeos_root,
+                                         machine=remote)
+    if not retval:
+      return True
+
+
+def Main(argv):
+  misc.AcquireLock(lock_file)
+  try:
+    return DoImage(argv)
+  finally:
+    misc.ReleaseLock(lock_file)
+
+
 if __name__ == "__main__":
   retval = Main(sys.argv)
   sys.exit(retval)