コード例 #1
0
 def testComplete(self):
     self.assertEqual(
         utils.Retry(lambda: True,
                     0,
                     1,
                     wait_fn=self._wait_fn,
                     _time_fn=self._time_fn), True)
     self.assertEqual(
         utils.Retry(self._RetryAndSucceed,
                     0,
                     1,
                     args=[2],
                     wait_fn=self._wait_fn,
                     _time_fn=self._time_fn), True)
     self.assertEqual(self.retries, 2)
コード例 #2
0
  def _AssembleLocal(self, minor, backend, meta, size):
    """Configure the local part of a DRBD device.

    @type minor: int
    @param minor: the minor to assemble locally
    @type backend: string
    @param backend: path to the data device to use
    @type meta: string
    @param meta: path to the meta device to use
    @type size: int
    @param size: size in MiB

    """
    cmds = self._cmd_gen.GenLocalInitCmds(minor, backend, meta,
                                          size, self.params)

    for cmd in cmds:
      result = utils.RunCmd(cmd)
      if result.failed:
        base.ThrowError("drbd%d: can't attach local disk: %s",
                        minor, result.output)

    def _WaitForMinorSyncParams():
      """Call _SetMinorSyncParams and raise RetryAgain on errors.
      """
      if self._SetMinorSyncParams(minor, self.params):
        raise utils.RetryAgain()

    if self._NeedsLocalSyncerParams():
      # Retry because disk config for DRBD resource may be still uninitialized.
      try:
        utils.Retry(_WaitForMinorSyncParams, 1.0, 5.0)
      except utils.RetryTimeout as e:
        base.ThrowError("drbd%d: can't set the synchronization parameters: %s" %
                        (minor, utils.CommaJoin(e.args[0])))
コード例 #3
0
ファイル: hv_xen.py プロジェクト: badp/ganeti
  def RebootInstance(self, instance):
    """Reboot an instance.

    """
    ini_info = self.GetInstanceInfo(instance.name, hvparams=instance.hvparams)

    if ini_info is None:
      raise errors.HypervisorError("Failed to reboot instance %s,"
                                   " not running" % instance.name)

    result = self._RunXen(["reboot", instance.name], instance.hvparams)
    if result.failed:
      raise errors.HypervisorError("Failed to reboot instance %s: %s, %s" %
                                   (instance.name, result.fail_reason,
                                    result.output))

    def _CheckInstance():
      new_info = self.GetInstanceInfo(instance.name, hvparams=instance.hvparams)

      # check if the domain ID has changed or the run time has decreased
      if (new_info is not None and
          (new_info[1] != ini_info[1] or new_info[5] < ini_info[5])):
        return

      raise utils.RetryAgain()

    try:
      utils.Retry(_CheckInstance, self.REBOOT_RETRY_INTERVAL,
                  self.REBOOT_RETRY_INTERVAL * self.REBOOT_RETRY_COUNT)
    except utils.RetryTimeout:
      raise errors.HypervisorError("Failed to reboot instance %s: instance"
                                   " did not reboot in the expected interval" %
                                   (instance.name, ))
コード例 #4
0
 def testTimeoutArgument(self):
     retry_arg = "my_important_debugging_message"
     try:
         utils.Retry(self._RaiseRetryAgainWithArg,
                     0.01,
                     0.02,
                     args=[[retry_arg]],
                     wait_fn=self._wait_fn,
                     _time_fn=self._time_fn)
     except utils.RetryTimeout, err:
         self.failUnlessEqual(err.args, (retry_arg, ))
コード例 #5
0
 def testTimeout(self):
     self.time_for_time_fn = 0.01
     self.time_for_retry_and_succeed = 10
     try:
         utils.Retry(self._RetryAndSucceed,
                     1,
                     18,
                     args=[2],
                     wait_fn=self._wait_fn,
                     _time_fn=self._time_fn)
     except utils.RetryTimeout, err:
         self.failUnlessEqual(err.args, ())
コード例 #6
0
 def testRaiseInnerWithMsg(self):
     retry_arg = "my_important_debugging_message"
     try:
         try:
             utils.Retry(self._RaiseRetryAgainWithArg,
                         0.01,
                         0.02,
                         args=[[retry_arg, retry_arg]],
                         wait_fn=self._wait_fn,
                         _time_fn=self._time_fn)
         except utils.RetryTimeout, err:
             err.RaiseInner()
         else:
コード例 #7
0
ファイル: transport.py プロジェクト: sajalcody/ganeti
    def __init__(self, address, timeouts=None, allow_non_master=None):
        """Constructor for the Client class.

    There are two timeouts used since we might want to wait for a long
    time for a response, but the connect timeout should be lower.

    If not passed, we use the default luxi timeouts from the global
    constants file.

    Note that on reading data, since the timeout applies to an
    invidual receive, it might be that the total duration is longer
    than timeout value passed (we make a hard limit at twice the read
    timeout).

    @type address: socket address
    @param address: address the transport connects to
    @type timeouts: list of ints
    @param timeouts: timeouts to be used on connect and read/write
    @type allow_non_master: bool
    @param allow_non_master: skip checks for the master node on errors

    """
        self.address = address
        if timeouts is None:
            self._ctimeout, self._rwtimeout = DEF_CTMO, DEF_RWTO
        else:
            self._ctimeout, self._rwtimeout = timeouts

        self.socket = None
        self._buffer = ""
        self._msgs = collections.deque()

        try:
            self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)

            # Try to connect
            try:
                utils.Retry(self._Connect,
                            1.0,
                            self._ctimeout,
                            args=(self.socket, address, self._ctimeout,
                                  allow_non_master))
            except utils.RetryTimeout:
                raise errors.TimeoutError("Connect timed out")

            self.socket.settimeout(self._rwtimeout)
        except (socket.error, errors.NoMasterError):
            if self.socket is not None:
                self.socket.close()
            self.socket = None
            raise
コード例 #8
0
ファイル: transport.py プロジェクト: dimara/ganeti
    def __init__(self, address, timeouts=None):
        """Constructor for the Client class.

    Arguments:
      - address: a valid address the the used transport class
      - timeout: a list of timeouts, to be used on connect and read/write

    There are two timeouts used since we might want to wait for a long
    time for a response, but the connect timeout should be lower.

    If not passed, we use a default of 10 and respectively 60 seconds.

    Note that on reading data, since the timeout applies to an
    invidual receive, it might be that the total duration is longer
    than timeout value passed (we make a hard limit at twice the read
    timeout).

    """
        self.address = address
        if timeouts is None:
            self._ctimeout, self._rwtimeout = DEF_CTMO, DEF_RWTO
        else:
            self._ctimeout, self._rwtimeout = timeouts

        self.socket = None
        self._buffer = ""
        self._msgs = collections.deque()

        try:
            self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)

            # Try to connect
            try:
                utils.Retry(self._Connect,
                            1.0,
                            self._ctimeout,
                            args=(self.socket, address, self._ctimeout))
            except utils.RetryTimeout:
                raise errors.TimeoutError("Connect timed out")

            self.socket.settimeout(self._rwtimeout)
        except (socket.error, errors.NoMasterError):
            if self.socket is not None:
                self.socket.close()
            self.socket = None
            raise
コード例 #9
0
 def testRaiseInnerWithMsg(self):
     retry_arg = "my_important_debugging_message"
     try:
         try:
             utils.Retry(self._RaiseRetryAgainWithArg,
                         0.01,
                         0.02,
                         args=[[retry_arg, retry_arg]],
                         wait_fn=self._wait_fn,
                         _time_fn=self._time_fn)
         except utils.RetryTimeout as err:
             err.RaiseInner()
         else:
             self.fail("Expected timeout didn't happen")
     except utils.RetryTimeout as err:
         self.failUnlessEqual(err.args, (retry_arg, retry_arg))
     else:
         self.fail("Expected RetryTimeout didn't happen")
コード例 #10
0
ファイル: hv_xen.py プロジェクト: badp/ganeti
def _GetAllInstanceList(fn, include_node, _timeout=5):
  """Return the list of instances including running and shutdown.

  See L{_RunInstanceList} and L{_ParseInstanceList} for parameter details.

  """
  instance_list_errors = []
  try:
    lines = utils.Retry(_RunInstanceList, (0.3, 1.5, 1.0), _timeout,
                        args=(fn, instance_list_errors))
  except utils.RetryTimeout:
    if instance_list_errors:
      instance_list_result = instance_list_errors.pop()

      errmsg = ("listing instances failed, timeout exceeded (%s): %s" %
                (instance_list_result.fail_reason, instance_list_result.output))
    else:
      errmsg = "listing instances failed"

    raise errors.HypervisorError(errmsg)

  return _ParseInstanceList(lines, include_node)
コード例 #11
0
ファイル: bootstrap.py プロジェクト: vali-um/ganeti
def MasterFailover(no_voting=False):
    """Failover the master node.

  This checks that we are not already the master, and will cause the
  current master to cease being master, and the non-master to become
  new master.

  Note: The call to MasterFailover from lib/client/gnt_cluster.py checks that
  a majority of nodes are healthy and responding before calling this. If this
  function is called from somewhere else, the caller should also verify that a
  majority of nodes are healthy.

  @type no_voting: boolean
  @param no_voting: force the operation without remote nodes agreement
                      (dangerous)

  @returns: the pair of an exit code and warnings to display
  """
    sstore = ssconf.SimpleStore()

    old_master, new_master = ssconf.GetMasterAndMyself(sstore)
    node_names = sstore.GetNodeList()
    mc_list = sstore.GetMasterCandidates()

    if old_master == new_master:
        raise errors.OpPrereqError(
            "This commands must be run on the node"
            " where you want the new master to be."
            " %s is already the master" % old_master, errors.ECODE_INVAL)

    if new_master not in mc_list:
        mc_no_master = [name for name in mc_list if name != old_master]
        raise errors.OpPrereqError(
            "This node is not among the nodes marked"
            " as master candidates. Only these nodes"
            " can become masters. Current list of"
            " master candidates is:\n"
            "%s" % ("\n".join(mc_no_master)), errors.ECODE_STATE)

    if not no_voting:
        vote_list = _GatherMasterVotes(node_names)
        if vote_list:
            voted_master = vote_list[0][0]
            if voted_master != old_master:
                raise errors.OpPrereqError(
                    "I have a wrong configuration, I believe"
                    " the master is %s but the other nodes"
                    " voted %s. Please resync the configuration"
                    " of this node." % (old_master, voted_master),
                    errors.ECODE_STATE)
    # end checks

    rcode = 0
    warnings = []

    logging.info("Setting master to %s, old master: %s", new_master,
                 old_master)

    try:
        # Forcefully start WConfd so that we can access the configuration
        result = utils.RunCmd([
            pathutils.DAEMON_UTIL, "start", constants.WCONFD, "--force-node",
            "--no-voting", "--yes-do-it"
        ])
        if result.failed:
            raise errors.OpPrereqError(
                "Could not start the configuration daemon,"
                " command %s had exitcode %s and error %s" %
                (result.cmd, result.exit_code, result.output),
                errors.ECODE_NOENT)

        # instantiate a real config writer, as we now know we have the
        # configuration data
        livelock = utils.livelock.LiveLock("bootstrap_failover")
        cfg = config.GetConfig(None, livelock, accept_foreign=True)

        old_master_node = cfg.GetNodeInfoByName(old_master)
        if old_master_node is None:
            raise errors.OpPrereqError(
                "Could not find old master node '%s' in"
                " cluster configuration." % old_master, errors.ECODE_NOENT)

        cluster_info = cfg.GetClusterInfo()
        new_master_node = cfg.GetNodeInfoByName(new_master)
        if new_master_node is None:
            raise errors.OpPrereqError(
                "Could not find new master node '%s' in"
                " cluster configuration." % new_master, errors.ECODE_NOENT)

        cluster_info.master_node = new_master_node.uuid
        # this will also regenerate the ssconf files, since we updated the
        # cluster info
        cfg.Update(cluster_info, logging.error)

        # if cfg.Update worked, then it means the old master daemon won't be
        # able now to write its own config file (we rely on locking in both
        # backend.UploadFile() and ConfigWriter._Write(); hence the next
        # step is to kill the old master

        logging.info("Stopping the master daemon on node %s", old_master)

        runner = rpc.BootstrapRunner()
        master_params = cfg.GetMasterNetworkParameters()
        master_params.uuid = old_master_node.uuid
        ems = cfg.GetUseExternalMipScript()
        result = runner.call_node_deactivate_master_ip(old_master,
                                                       master_params, ems)

        msg = result.fail_msg
        if msg:
            warning = "Could not disable the master IP: %s" % (msg, )
            logging.warning("%s", warning)
            warnings.append(warning)

        result = runner.call_node_stop_master(old_master)
        msg = result.fail_msg
        if msg:
            warning = ("Could not disable the master role on the old master"
                       " %s, please disable manually: %s" % (old_master, msg))
            logging.error("%s", warning)
            warnings.append(warning)
    except errors.ConfigurationError as err:
        logging.error("Error while trying to set the new master: %s", str(err))
        return 1, warnings
    finally:
        # stop WConfd again:
        result = utils.RunCmd(
            [pathutils.DAEMON_UTIL, "stop", constants.WCONFD])
        if result.failed:
            warning = ("Could not stop the configuration daemon,"
                       " command %s had exitcode %s and error %s" %
                       (result.cmd, result.exit_code, result.output))
            logging.error("%s", warning)
            rcode = 1

    logging.info("Checking master IP non-reachability...")

    master_ip = sstore.GetMasterIP()
    total_timeout = 30

    # Here we have a phase where no master should be running
    def _check_ip(expected):
        if netutils.TcpPing(master_ip,
                            constants.DEFAULT_NODED_PORT) != expected:
            raise utils.RetryAgain()

    try:
        utils.Retry(_check_ip, (1, 1.5, 5), total_timeout, args=[False])
    except utils.RetryTimeout:
        warning = ("The master IP is still reachable after %s seconds,"
                   " continuing but activating the master IP on the current"
                   " node will probably fail" % total_timeout)
        logging.warning("%s", warning)
        warnings.append(warning)
        rcode = 1

    if jstore.CheckDrainFlag():
        logging.info("Undraining job queue")
        jstore.SetDrainFlag(False)

    logging.info("Starting the master daemons on the new master")

    result = rpc.BootstrapRunner().call_node_start_master_daemons(
        new_master, no_voting)
    msg = result.fail_msg
    if msg:
        logging.error(
            "Could not start the master role on the new master"
            " %s, please check: %s", new_master, msg)
        rcode = 1

    # Finally verify that the new master managed to set up the master IP
    # and warn if it didn't.
    try:
        utils.Retry(_check_ip, (1, 1.5, 5), total_timeout, args=[True])
    except utils.RetryTimeout:
        warning = ("The master IP did not come up within %s seconds; the"
                   " cluster should still be working and reachable via %s,"
                   " but not via the master IP address" %
                   (total_timeout, new_master))
        logging.warning("%s", warning)
        warnings.append(warning)
        rcode = 1

    logging.info("Master failed over from %s to %s", old_master, new_master)
    return rcode, warnings