import-export 21.9 KB
Newer Older
1 2 3 4
#!/usr/bin/python
#

# Copyright (C) 2010 Google Inc.
Klaus Aehlig's avatar
Klaus Aehlig committed
5
# All rights reserved.
6
#
Klaus Aehlig's avatar
Klaus Aehlig committed
7 8 9
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
10
#
Klaus Aehlig's avatar
Klaus Aehlig committed
11 12
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
13
#
Klaus Aehlig's avatar
Klaus Aehlig committed
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 30 31 32 33 34


"""Import/export daemon.

"""

35
# pylint: disable=C0103
36 37 38 39 40 41 42 43 44 45 46
# C0103: Invalid name import-export

import errno
import logging
import optparse
import os
import select
import signal
import subprocess
import sys
import time
47
import math
48 49 50 51

from ganeti import constants
from ganeti import cli
from ganeti import utils
52
from ganeti import errors
53 54
from ganeti import serializer
from ganeti import objects
55
from ganeti import impexpd
56
from ganeti import netutils
57 58 59 60 61 62 63 64


#: How many lines to keep in the status file
MAX_RECENT_OUTPUT_LINES = 20

#: Don't update status file more than once every 5 seconds (unless forced)
MIN_UPDATE_INTERVAL = 5.0

65 66 67
#: How long to wait for a connection to be established
DEFAULT_CONNECT_TIMEOUT = 60

68 69 70 71 72 73 74 75 76 77
#: Get dd(1) statistics every few seconds
DD_STATISTICS_INTERVAL = 5.0

#: Seconds for throughput calculation
DD_THROUGHPUT_INTERVAL = 60.0

#: Number of samples for throughput calculation
DD_THROUGHPUT_SAMPLES = int(math.ceil(float(DD_THROUGHPUT_INTERVAL) /
                                      DD_STATISTICS_INTERVAL))

78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110

# Global variable for options
options = None


def SetupLogging():
  """Configures the logging module.

  """
  formatter = logging.Formatter("%(asctime)s: %(message)s")

  stderr_handler = logging.StreamHandler()
  stderr_handler.setFormatter(formatter)
  stderr_handler.setLevel(logging.NOTSET)

  root_logger = logging.getLogger("")
  root_logger.addHandler(stderr_handler)

  if options.debug:
    root_logger.setLevel(logging.NOTSET)
  elif options.verbose:
    root_logger.setLevel(logging.INFO)
  else:
    root_logger.setLevel(logging.ERROR)

  # Create special logger for child process output
  child_logger = logging.Logger("child output")
  child_logger.addHandler(stderr_handler)
  child_logger.setLevel(logging.NOTSET)

  return child_logger


111
class StatusFile(object):
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
  """Status file manager.

  """
  def __init__(self, path):
    """Initializes class.

    """
    self._path = path
    self._data = objects.ImportExportStatus(ctime=time.time(),
                                            mtime=None,
                                            recent_output=[])

  def AddRecentOutput(self, line):
    """Adds a new line of recent output.

    """
    self._data.recent_output.append(line)

    # Remove old lines
    del self._data.recent_output[:-MAX_RECENT_OUTPUT_LINES]

  def SetListenPort(self, port):
    """Sets the port the daemon is listening on.

    @type port: int
    @param port: TCP/UDP port

    """
Michael Hanselmann's avatar
Michael Hanselmann committed
140
    assert isinstance(port, (int, long)) and 0 < port < (2 ** 16)
141 142 143 144 145 146 147 148 149 150 151 152 153 154
    self._data.listen_port = port

  def GetListenPort(self):
    """Returns the port the daemon is listening on.

    """
    return self._data.listen_port

  def SetConnected(self):
    """Sets the connected flag.

    """
    self._data.connected = True

155 156 157 158 159 160
  def GetConnected(self):
    """Determines whether the daemon is connected.

    """
    return self._data.connected

161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
  def SetProgress(self, mbytes, throughput, percent, eta):
    """Sets how much data has been transferred so far.

    @type mbytes: number
    @param mbytes: Transferred amount of data in MiB.
    @type throughput: float
    @param throughput: MiB/second
    @type percent: number
    @param percent: Percent processed
    @type eta: number
    @param eta: Expected number of seconds until done

    """
    self._data.progress_mbytes = mbytes
    self._data.progress_throughput = throughput
    self._data.progress_percent = percent
    self._data.progress_eta = eta

179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
  def SetExitStatus(self, exit_status, error_message):
    """Sets the exit status and an error message.

    """
    # Require error message when status isn't 0
    assert exit_status == 0 or error_message

    self._data.exit_status = exit_status
    self._data.error_message = error_message

  def ExitStatusIsSuccess(self):
    """Returns whether the exit status means "success".

    """
    return not bool(self._data.error_message)

  def Update(self, force):
    """Updates the status file.

    @type force: bool
    @param force: Write status file in any case, not only when minimum interval
                  is expired

    """
    if not (force or
            self._data.mtime is None or
            time.time() > (self._data.mtime + MIN_UPDATE_INTERVAL)):
      return

    logging.debug("Updating status file %s", self._path)

    self._data.mtime = time.time()
    utils.WriteFile(self._path,
212
                    data=serializer.DumpJson(self._data.ToDict()),
213 214 215
                    mode=0400)


216
def ProcessChildIO(child, socat_stderr_read_fd, dd_stderr_read_fd,
217
                   dd_pid_read_fd, exp_size_read_fd, status_file, child_logger,
218
                   signal_notify, signal_handler, mode):
219 220 221
  """Handles the child processes' output.

  """
222 223 224 225 226 227 228
  assert not (signal_handler.signum - set([signal.SIGTERM, signal.SIGINT])), \
         "Other signals are not handled in this function"

  # Buffer size 0 is important, otherwise .read() with a specified length
  # might buffer data while poll(2) won't mark its file descriptor as
  # readable again.
  socat_stderr_read = os.fdopen(socat_stderr_read_fd, "r", 0)
229 230
  dd_stderr_read = os.fdopen(dd_stderr_read_fd, "r", 0)
  dd_pid_read = os.fdopen(dd_pid_read_fd, "r", 0)
231
  exp_size_read = os.fdopen(exp_size_read_fd, "r", 0)
232 233

  tp_samples = DD_THROUGHPUT_SAMPLES
234

235 236 237 238 239
  if options.exp_size == constants.IE_CUSTOM_SIZE:
    exp_size = None
  else:
    exp_size = options.exp_size

240
  child_io_proc = impexpd.ChildIOProcessor(options.debug, status_file,
241 242
                                           child_logger, tp_samples,
                                           exp_size)
243
  try:
244 245 246 247 248
    fdmap = {
      child.stderr.fileno():
        (child.stderr, child_io_proc.GetLineSplitter(impexpd.PROG_OTHER)),
      socat_stderr_read.fileno():
        (socat_stderr_read, child_io_proc.GetLineSplitter(impexpd.PROG_SOCAT)),
249 250 251 252
      dd_pid_read.fileno():
        (dd_pid_read, child_io_proc.GetLineSplitter(impexpd.PROG_DD_PID)),
      dd_stderr_read.fileno():
        (dd_stderr_read, child_io_proc.GetLineSplitter(impexpd.PROG_DD)),
253 254
      exp_size_read.fileno():
        (exp_size_read, child_io_proc.GetLineSplitter(impexpd.PROG_EXP_SIZE)),
255 256 257 258 259 260 261 262 263
      signal_notify.fileno(): (signal_notify, None),
      }

    poller = select.poll()
    for fd in fdmap:
      utils.SetNonblockFlag(fd, True)
      poller.register(fd, select.POLLIN)

    if options.connect_timeout and mode == constants.IEM_IMPORT:
264
      listen_timeout = utils.RunningTimeout(options.connect_timeout, True)
265 266 267 268
    else:
      listen_timeout = None

    exit_timeout = None
269
    dd_stats_timeout = None
270 271 272 273 274 275 276 277 278

    while True:
      # Break out of loop if only signal notify FD is left
      if len(fdmap) == 1 and signal_notify.fileno() in fdmap:
        break

      timeout = None

      if listen_timeout and not exit_timeout:
279
        assert mode == constants.IEM_IMPORT and options.connect_timeout
280 281 282
        if status_file.GetConnected():
          listen_timeout = None
        elif listen_timeout.Remaining() < 0:
283 284 285 286 287 288
          errmsg = ("Child process didn't establish connection in time"
                    " (%0.0fs), sending SIGTERM" % options.connect_timeout)
          logging.error(errmsg)
          status_file.AddRecentOutput(errmsg)
          status_file.Update(True)

289 290
          child.Kill(signal.SIGTERM)
          exit_timeout = \
René Nussbaumer's avatar
René Nussbaumer committed
291
            utils.RunningTimeout(constants.CHILD_LINGER_TIMEOUT, True)
292 293 294 295 296 297 298 299 300
          # Next block will calculate timeout
        else:
          # Not yet connected, check again in a second
          timeout = 1000

      if exit_timeout:
        timeout = exit_timeout.Remaining() * 1000
        if timeout < 0:
          logging.info("Child process didn't exit in time")
301 302
          break

303 304 305 306
      if (not dd_stats_timeout) or dd_stats_timeout.Remaining() < 0:
        notify_status = child_io_proc.NotifyDd()
        if notify_status:
          # Schedule next notification
307
          dd_stats_timeout = utils.RunningTimeout(DD_STATISTICS_INTERVAL, True)
308 309
        else:
          # Try again soon (dd isn't ready yet)
310
          dd_stats_timeout = utils.RunningTimeout(1.0, True)
311 312 313 314 315 316 317 318 319

      if dd_stats_timeout:
        dd_timeout = max(0, dd_stats_timeout.Remaining() * 1000)

        if timeout is None:
          timeout = dd_timeout
        else:
          timeout = min(timeout, dd_timeout)

320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
      for fd, event in utils.RetryOnSignal(poller.poll, timeout):
        if event & (select.POLLIN | event & select.POLLPRI):
          (from_, to) = fdmap[fd]

          # Read up to 1 KB of data
          data = from_.read(1024)
          if data:
            if to:
              to.write(data)
            elif fd == signal_notify.fileno():
              # Signal handling
              if signal_handler.called:
                signal_handler.Clear()
                if exit_timeout:
                  logging.info("Child process still has about %0.2f seconds"
                               " to exit", exit_timeout.Remaining())
                else:
                  logging.info("Giving child process %0.2f seconds to exit",
René Nussbaumer's avatar
René Nussbaumer committed
338
                               constants.CHILD_LINGER_TIMEOUT)
339
                  exit_timeout = \
René Nussbaumer's avatar
René Nussbaumer committed
340
                    utils.RunningTimeout(constants.CHILD_LINGER_TIMEOUT, True)
341
          else:
342 343 344
            poller.unregister(fd)
            del fdmap[fd]

345 346 347 348 349 350
        elif event & (select.POLLNVAL | select.POLLHUP |
                      select.POLLERR):
          poller.unregister(fd)
          del fdmap[fd]

      child_io_proc.FlushAll()
351

352 353 354
    # If there was a timeout calculator, we were waiting for the child to
    # finish, e.g. due to a signal
    return not bool(exit_timeout)
355
  finally:
356
    child_io_proc.CloseAll()
357 358 359 360 361 362 363 364


def ParseOptions():
  """Parses the options passed to the program.

  @return: Arguments to program

  """
365
  global options # pylint: disable=W0603
366 367 368 369 370 371 372 373 374 375 376 377 378 379

  parser = optparse.OptionParser(usage=("%%prog <status-file> {%s|%s}" %
                                        (constants.IEM_IMPORT,
                                         constants.IEM_EXPORT)))
  parser.add_option(cli.DEBUG_OPT)
  parser.add_option(cli.VERBOSE_OPT)
  parser.add_option("--key", dest="key", action="store", type="string",
                    help="RSA key file")
  parser.add_option("--cert", dest="cert", action="store", type="string",
                    help="X509 certificate file")
  parser.add_option("--ca", dest="ca", action="store", type="string",
                    help="X509 CA file")
  parser.add_option("--bind", dest="bind", action="store", type="string",
                    help="Bind address")
380 381 382 383
  parser.add_option("--ipv4", dest="ipv4", action="store_true",
                    help="Use IPv4 only")
  parser.add_option("--ipv6", dest="ipv6", action="store_true",
                    help="Use IPv6 only")
384 385 386 387
  parser.add_option("--host", dest="host", action="store", type="string",
                    help="Remote hostname")
  parser.add_option("--port", dest="port", action="store", type="int",
                    help="Remote port")
388 389 390 391 392 393 394
  parser.add_option("--connect-retries", dest="connect_retries", action="store",
                    type="int", default=0,
                    help=("How many times the connection should be retried"
                          " (export only)"))
  parser.add_option("--connect-timeout", dest="connect_timeout", action="store",
                    type="int", default=DEFAULT_CONNECT_TIMEOUT,
                    help="Timeout for connection to be established (seconds)")
395
  parser.add_option("--compress", dest="compress", action="store",
396 397
                    type="string", help="Compression method",
                    default=constants.IEC_GZIP)
398 399 400
  parser.add_option("--expected-size", dest="exp_size", action="store",
                    type="string", default=None,
                    help="Expected import/export size (MiB)")
401 402
  parser.add_option("--magic", dest="magic", action="store",
                    type="string", default=None, help="Magic string")
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
  parser.add_option("--cmd-prefix", dest="cmd_prefix", action="store",
                    type="string", help="Command prefix")
  parser.add_option("--cmd-suffix", dest="cmd_suffix", action="store",
                    type="string", help="Command suffix")

  (options, args) = parser.parse_args()

  if len(args) != 2:
    # Won't return
    parser.error("Expected exactly two arguments")

  (status_file_path, mode) = args

  if mode not in (constants.IEM_IMPORT,
                  constants.IEM_EXPORT):
    # Won't return
    parser.error("Invalid mode: %s" % mode)

421
  # Normalize and check parameters
422
  if options.host is not None and not netutils.IPAddress.IsValid(options.host):
423
    try:
424
      options.host = netutils.Hostname.GetNormalizedName(options.host)
425 426 427 428 429 430
    except errors.OpPrereqError, err:
      parser.error("Invalid hostname '%s': %s" % (options.host, err))

  if options.port is not None:
    options.port = utils.ValidateServiceName(options.port)

431 432 433 434 435 436 437 438 439
  if (options.exp_size is not None and
      options.exp_size != constants.IE_CUSTOM_SIZE):
    try:
      options.exp_size = int(options.exp_size)
    except (ValueError, TypeError), err:
      # Won't return
      parser.error("Invalid value for --expected-size: %s (%s)" %
                   (options.exp_size, err))

440 441 442 443
  if not (options.magic is None or constants.IE_MAGIC_RE.match(options.magic)):
    parser.error("Magic must match regular expression %s" %
                 constants.IE_MAGIC_RE.pattern)

444 445 446
  if options.ipv4 and options.ipv6:
    parser.error("Can only use one of --ipv4 and --ipv6")

447 448 449
  return (status_file_path, mode)


450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
# Return code signifying that no program was found
PROGRAM_NOT_FOUND_RCODE = 127


def _RunWithTimeout(cmd, timeout, silent=False):
  """Runs a command, killing it if a timeout was reached.

  Uses the alarm signal, not thread-safe. Waits regardless of whether the
  command exited early.

  @type timeout: number
  @param timeout: Timeout, in seconds
  @type silent: Boolean
  @param silent: Whether command output should be suppressed
  @rtype: tuple of (bool, int)
  @return: Whether the command timed out, and the return code

  """
  try:
    if silent:
      with open(os.devnull, 'wb') as null_fd:
        p = subprocess.Popen(cmd, stdout=null_fd, stderr=null_fd)
    else:
      p = subprocess.Popen(cmd)

  except OSError:
    return False, PROGRAM_NOT_FOUND_RCODE

  time.sleep(timeout)

  timed_out = False
  status = p.poll()
  if status is None:
    timed_out = True
    p.kill()

  return timed_out, p.wait()


CHECK_SWITCH = "-h"


def VerifyOptions():
  """Performs various runtime checks to make sure the options are valid.

  """
  if options.compress != constants.IEC_NONE:
497 498
    utility_name = constants.IEC_COMPRESSION_UTILITIES.get(options.compress,
                                                           options.compress)
499 500 501 502 503 504 505 506 507 508 509 510 511 512
    timed_out, rcode = \
      _RunWithTimeout([utility_name, CHECK_SWITCH], 2, silent=True)

    if timed_out:
      raise Exception("The invoked utility has timed out - the %s switch to"
                      " check for presence must be supported" % CHECK_SWITCH)

    if rcode != 0:
      raise Exception("Verification attempt of selected compression method %s"
                      " failed - check that %s is present and can be invoked"
                      " safely with the %s switch" %
                      (options.compress, utility_name, CHECK_SWITCH))


513
class ChildProcess(subprocess.Popen):
514
  def __init__(self, env, cmd, noclose_fds):
515 516 517 518 519 520 521
    """Initializes this class.

    """
    self._noclose_fds = noclose_fds

    # Not using close_fds because doing so would also close the socat stderr
    # pipe, which we still need.
522
    subprocess.Popen.__init__(self, cmd, env=env, shell=False, close_fds=False,
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
                              stderr=subprocess.PIPE, stdout=None, stdin=None,
                              preexec_fn=self._ChildPreexec)
    self._SetProcessGroup()

  def _ChildPreexec(self):
    """Called before child executable is execve'd.

    """
    # Move to separate process group. By sending a signal to its process group
    # we can kill the child process and all grandchildren.
    os.setpgid(0, 0)

    # Close almost all file descriptors
    utils.CloseFDs(noclose_fds=self._noclose_fds)

  def _SetProcessGroup(self):
    """Sets the child's process group.

    """
    assert self.pid, "Can't be called in child process"

    # Avoid race condition by setting child's process group (as good as
    # possible in Python) before sending signals to child. For an
    # explanation, see preexec function for child.
    try:
      os.setpgid(self.pid, self.pid)
    except EnvironmentError, err:
      # If the child process was faster we receive EPERM or EACCES
      if err.errno not in (errno.EPERM, errno.EACCES):
        raise

  def Kill(self, signum):
    """Sends signal to child process.

    """
    logging.info("Sending signal %s to child process", signum)
559
    utils.IgnoreProcessNotFound(os.killpg, self.pid, signum)
560 561 562 563 564 565 566 567 568 569 570 571

  def ForceQuit(self):
    """Ensure child process is no longer running.

    """
    # Final check if child process is still alive
    if utils.RetryOnSignal(self.poll) is None:
      logging.error("Child process still alive, sending SIGKILL")
      self.Kill(signal.SIGKILL)
      utils.RetryOnSignal(self.wait)


572 573 574 575 576 577 578 579 580 581 582 583 584
def main():
  """Main function.

  """
  # Option parsing
  (status_file_path, mode) = ParseOptions()

  # Configure logging
  child_logger = SetupLogging()

  status_file = StatusFile(status_file_path)
  try:
    try:
585 586 587
      # Option verification
      VerifyOptions()

588 589 590
      # Pipe to receive socat's stderr output
      (socat_stderr_read_fd, socat_stderr_write_fd) = os.pipe()

591 592 593 594 595 596
      # Pipe to receive dd's stderr output
      (dd_stderr_read_fd, dd_stderr_write_fd) = os.pipe()

      # Pipe to receive dd's PID
      (dd_pid_read_fd, dd_pid_write_fd) = os.pipe()

597 598 599
      # Pipe to receive size predicted by export script
      (exp_size_read_fd, exp_size_write_fd) = os.pipe()

600
      # Get child process command
601 602
      cmd_builder = impexpd.CommandBuilder(mode, options, socat_stderr_write_fd,
                                           dd_stderr_write_fd, dd_pid_write_fd)
603
      cmd = cmd_builder.GetCommand()
604

605 606 607 608 609 610
      # Prepare command environment
      cmd_env = os.environ.copy()

      if options.exp_size == constants.IE_CUSTOM_SIZE:
        cmd_env["EXP_SIZE_FD"] = str(exp_size_write_fd)

611 612
      logging.debug("Starting command %r", cmd)

613
      # Start child process
614 615 616
      child = ChildProcess(cmd_env, cmd,
                           [socat_stderr_write_fd, dd_stderr_write_fd,
                            dd_pid_write_fd, exp_size_write_fd])
617
      try:
618

619
        def _ForwardSignal(signum, _):
620
          """Forwards signals to child process.
621

622
          """
623
          child.Kill(signum)
624

625
        signal_wakeup = utils.SignalWakeupFd()
626
        try:
627 628 629 630 631 632 633 634 635 636 637
          # TODO: There is a race condition between starting the child and
          # handling the signals here. While there might be a way to work around
          # it by registering the handlers before starting the child and
          # deferring sent signals until the child is available, doing so can be
          # complicated.
          signal_handler = utils.SignalHandler([signal.SIGTERM, signal.SIGINT],
                                               handler_fn=_ForwardSignal,
                                               wakeup=signal_wakeup)
          try:
            # Close child's side
            utils.RetryOnSignal(os.close, socat_stderr_write_fd)
638 639
            utils.RetryOnSignal(os.close, dd_stderr_write_fd)
            utils.RetryOnSignal(os.close, dd_pid_write_fd)
640
            utils.RetryOnSignal(os.close, exp_size_write_fd)
641

642
            if ProcessChildIO(child, socat_stderr_read_fd, dd_stderr_read_fd,
643 644
                              dd_pid_read_fd, exp_size_read_fd,
                              status_file, child_logger,
645
                              signal_wakeup, signal_handler, mode):
646 647 648 649 650 651
              # The child closed all its file descriptors and there was no
              # signal
              # TODO: Implement timeout instead of waiting indefinitely
              utils.RetryOnSignal(child.wait)
          finally:
            signal_handler.Reset()
652
        finally:
653
          signal_wakeup.Reset()
654
      finally:
655
        child.ForceQuit()
656 657 658 659 660 661 662 663 664

      if child.returncode == 0:
        errmsg = None
      elif child.returncode < 0:
        errmsg = "Exited due to signal %s" % (-child.returncode, )
      else:
        errmsg = "Exited with status %s" % (child.returncode, )

      status_file.SetExitStatus(child.returncode, errmsg)
665
    except Exception, err: # pylint: disable=W0703
666 667 668 669 670 671 672 673 674 675 676 677 678 679
      logging.exception("Unhandled error occurred")
      status_file.SetExitStatus(constants.EXIT_FAILURE,
                                "Unhandled error occurred: %s" % (err, ))

    if status_file.ExitStatusIsSuccess():
      sys.exit(constants.EXIT_SUCCESS)

    sys.exit(constants.EXIT_FAILURE)
  finally:
    status_file.Update(True)


if __name__ == "__main__":
  main()