Пример #1
0
def Main():
    """Main routine.

  """
    opts = ParseOptions()

    utils.SetupToolLogging(opts.debug, opts.verbose)

    try:
        data = common.LoadData(sys.stdin.read(), _DATA_CHECK)

        # Check if input data is correct
        common.VerifyClusterName(data, SshUpdateError,
                                 constants.SSHS_CLUSTER_NAME)
        common.VerifyCertificateSoft(data, SshUpdateError)

        # Update / Generate SSH files
        UpdateAuthorizedKeys(data, opts.dry_run)
        UpdatePubKeyFile(data, opts.dry_run)
        GenerateRootSshKeys(data, opts.dry_run)

        logging.info("Setup finished successfully")
    except Exception, err:  # pylint: disable=W0703
        logging.debug("Caught unhandled exception", exc_info=True)

        (retcode, message) = cli.FormatError(err)
        logging.error(message)

        return retcode
Пример #2
0
def Main():
    """Main routine.

  """
    (opts, args) = ParseOptions()

    utils.SetupToolLogging(opts.debug, opts.verbose)

    if args:
        logging.error("No arguments are expected")
        return constants.EXIT_FAILURE

    if opts.full_run:
        logging.info("Running in full mode")

    getent = runtime.GetEnts()

    try:
        for path in GetPaths():
            ProcessPath(path)

        if opts.full_run:
            RecursiveEnsure(pathutils.JOB_QUEUE_ARCHIVE_DIR,
                            getent.masterd_uid, getent.daemons_gid, 0750,
                            constants.JOB_QUEUE_FILES_PERMS)
    except errors.GenericError, err:
        logging.error("An error occurred while setting permissions: %s", err)
        return constants.EXIT_FAILURE
Пример #3
0
def Main():
    """Main routine.

  """
    opts = ParseOptions()

    utils.SetupToolLogging(opts.debug, opts.verbose)

    try:
        getent = runtime.GetEnts()

        data = common.LoadData(sys.stdin.read(), SetupError)

        cluster_name = common.VerifyClusterName(data, SetupError,
                                                constants.NDS_CLUSTER_NAME)
        cert_pem = common.VerifyCertificateStrong(data, SetupError)
        ssdata = VerifySsconf(data, cluster_name)

        logging.info("Writing ssconf files ...")
        ssconf.WriteSsconfFiles(ssdata, dry_run=opts.dry_run)

        logging.info("Writing node daemon certificate ...")
        utils.WriteFile(pathutils.NODED_CERT_FILE,
                        data=cert_pem,
                        mode=pathutils.NODED_CERT_MODE,
                        uid=getent.masterd_uid,
                        gid=getent.masterd_gid,
                        dry_run=opts.dry_run)
        common.GenerateClientCertificate(data, SetupError)

        if (data.get(constants.NDS_START_NODE_DAEMON) and  # pylint: disable=E1103
                not opts.dry_run):
            logging.info("Restarting node daemon ...")

            stop_cmd = "%s stop-all" % pathutils.DAEMON_UTIL
            noded_cmd = "%s start %s" % (pathutils.DAEMON_UTIL,
                                         constants.NODED)
            mond_cmd = ""
            if constants.ENABLE_MOND:
                mond_cmd = "%s start %s" % (pathutils.DAEMON_UTIL,
                                            constants.MOND)

            cmd = "; ".join([stop_cmd, noded_cmd, mond_cmd])

            result = utils.RunCmd(cmd, interactive=True)
            if result.failed:
                raise SetupError(
                    "Could not start the node daemons, command '%s'"
                    " failed: %s" % (result.cmd, result.fail_reason))

        logging.info("Node daemon successfully configured")
    except Exception as err:  # pylint: disable=W0703
        logging.debug("Caught unhandled exception", exc_info=True)

        (retcode, message) = cli.FormatError(err)
        logging.error(message)

        return retcode
    else:
        return constants.EXIT_SUCCESS
Пример #4
0
def Main():
    """Main routine.

  """
    opts = ParseOptions()

    utils.SetupToolLogging(opts.debug,
                           opts.verbose,
                           toolname=os.path.splitext(
                               os.path.basename(__file__))[0])

    try:
        data = common.LoadData(sys.stdin.read(), _DATA_CHECK)

        # Check if input data is correct
        common.VerifyClusterName(data, JoinError, constants.SSHS_CLUSTER_NAME)
        common.VerifyCertificateSoft(data, JoinError)

        # Update SSH files
        UpdateSshDaemon(data, opts.dry_run)
        UpdateSshRoot(data, opts.dry_run)

        logging.info("Setup finished successfully")
    except Exception, err:  # pylint: disable=W0703
        logging.debug("Caught unhandled exception", exc_info=True)

        (retcode, message) = cli.FormatError(err)
        logging.error(message)

        return retcode
Пример #5
0
def Main():
    """Main routine.

  """
    opts = ParseOptions()

    utils.SetupToolLogging(opts.debug, opts.verbose)

    try:
        data = LoadData(sys.stdin.read())

        # Check if input data is correct
        VerifyClusterName(data)
        VerifyCertificate(data)

        # Update SSH files
        UpdateSshDaemon(data, opts.dry_run)
        UpdateSshRoot(data, opts.dry_run)

        logging.info("Setup finished successfully")
    except Exception, err:  # pylint: disable=W0703
        logging.debug("Caught unhandled exception", exc_info=True)

        (retcode, message) = cli.FormatError(err)
        logging.error(message)

        return retcode
Пример #6
0
def Main():
    """Main routine.

  """
    opts = ParseOptions()

    utils.SetupToolLogging(opts.debug,
                           opts.verbose,
                           toolname=os.path.splitext(
                               os.path.basename(__file__))[0])

    try:
        # List of files to delete. Contains tuples consisting of the absolute path
        # and a boolean denoting whether a backup copy should be created before
        # deleting.
        clean_files = [
            (pathutils.CONFD_HMAC_KEY, True),
            (pathutils.CLUSTER_CONF_FILE, True),
            (pathutils.CLUSTER_DOMAIN_SECRET_FILE, True),
        ]
        clean_files.extend(map(lambda s: (s, True), pathutils.ALL_CERT_FILES))
        clean_files.extend(
            map(lambda s: (s, False),
                ssconf.SimpleStore().GetFileList()))

        if not opts.yes_do_it:
            cli.ToStderr(
                "Cleaning a node is irreversible. If you really want to"
                " clean this node, supply the --yes-do-it option.")
            return constants.EXIT_FAILURE

        logging.info("Stopping daemons")
        result = utils.RunCmd([pathutils.DAEMON_UTIL, "stop-all"],
                              interactive=True)
        if result.failed:
            raise Exception("Could not stop daemons, command '%s' failed: %s" %
                            (result.cmd, result.fail_reason))

        for (filename, backup) in clean_files:
            if os.path.exists(filename):
                if opts.backup and backup:
                    logging.info("Backing up %s", filename)
                    utils.CreateBackup(filename)

                logging.info("Removing %s", filename)
                utils.RemoveFile(filename)

        logging.info("Node successfully cleaned")
    except Exception, err:  # pylint: disable=W0703
        logging.debug("Caught unhandled exception", exc_info=True)

        (retcode, message) = cli.FormatError(err)
        logging.error(message)

        return retcode
Пример #7
0
    def test(self):
        error_name = logging.getLevelName(logging.ERROR)
        warn_name = logging.getLevelName(logging.WARNING)
        info_name = logging.getLevelName(logging.INFO)
        debug_name = logging.getLevelName(logging.DEBUG)

        for debug in [False, True]:
            for verbose in [False, True]:
                logger = logging.Logger("TestLogger")
                buf = StringIO()

                utils.SetupToolLogging(debug,
                                       verbose,
                                       _root_logger=logger,
                                       _stream=buf)

                logger.error("level=error")
                logger.warning("level=warning")
                logger.info("level=info")
                logger.debug("level=debug")

                lines = buf.getvalue().splitlines()

                self.assertTrue(
                    compat.all(line.count(":") == 3 for line in lines))

                messages = [line.split(":", 3)[-1].strip() for line in lines]

                if debug:
                    self.assertEqual(messages, [
                        "%s level=error" % error_name,
                        "%s level=warning" % warn_name,
                        "%s level=info" % info_name,
                        "%s level=debug" % debug_name,
                    ])
                elif verbose:
                    self.assertEqual(messages, [
                        "%s level=error" % error_name,
                        "%s level=warning" % warn_name,
                        "%s level=info" % info_name,
                    ])
                else:
                    self.assertEqual(messages, [
                        "level=error",
                        "level=warning",
                    ])
  def testThreadName(self):
    thread_name = threading.currentThread().getName()

    for enable_threadname in [False, True]:
      logger = logging.Logger("TestLogger")
      buf = StringIO()

      utils.SetupToolLogging(True, True, threadname=enable_threadname,
                             _root_logger=logger, _stream=buf)

      logger.debug("test134042376")

      lines = buf.getvalue().splitlines()
      self.assertEqual(len(lines), 1)

      if enable_threadname:
        self.assertTrue((" %s " % thread_name) in lines[0])
      else:
        self.assertTrue(thread_name not in lines[0])
Пример #9
0
def Main():
    """Main routine.

  """
    opts = ParseOptions()

    utils.SetupToolLogging(opts.debug, opts.verbose)

    try:
        data = common.LoadData(sys.stdin.read(), _DATA_CHECK)

        common.VerifyClusterName(data, SslSetupError,
                                 constants.NDS_CLUSTER_NAME)

        # Verifies whether the server certificate of the caller
        # is the same as on this node.
        common.VerifyCertificateStrong(data, SslSetupError)

        action = data.get(constants.NDS_ACTION)
        if not action:
            raise SslSetupError("No Action specified.")

        if action == constants.CRYPTO_ACTION_CREATE:
            common.GenerateClientCertificate(data, SslSetupError)
        elif action == constants.CRYPTO_ACTION_DELETE:
            DeleteClientCertificate()
            ClearMasterCandidateSsconfList()
        else:
            raise SslSetupError("Unsupported action: %s." % action)

    except Exception as err:  # pylint: disable=W0703
        logging.debug("Caught unhandled exception", exc_info=True)

        (retcode, message) = cli.FormatError(err)
        logging.error(message)

        return retcode
    else:
        return constants.EXIT_SUCCESS