org.apache.zookeeper.server.quorum.QuorumPeerMain

打印 上一主题 下一主题

主题 797|帖子 797|积分 2391

QuorumPeerMain源代码

  1. package org.apache.zookeeper.server.quorum;
  2. import java.io.IOException;
  3. import javax.management.JMException;
  4. import javax.security.sasl.SaslException;
  5. import org.apache.yetus.audience.InterfaceAudience;
  6. import org.apache.zookeeper.audit.ZKAuditProvider;
  7. import org.apache.zookeeper.jmx.ManagedUtil;
  8. import org.apache.zookeeper.metrics.MetricsProvider;
  9. import org.apache.zookeeper.metrics.MetricsProviderLifeCycleException;
  10. import org.apache.zookeeper.metrics.impl.MetricsProviderBootstrap;
  11. import org.apache.zookeeper.server.DatadirCleanupManager;
  12. import org.apache.zookeeper.server.ExitCode;
  13. import org.apache.zookeeper.server.ServerCnxnFactory;
  14. import org.apache.zookeeper.server.ServerMetrics;
  15. import org.apache.zookeeper.server.ZKDatabase;
  16. import org.apache.zookeeper.server.ZooKeeperServerMain;
  17. import org.apache.zookeeper.server.admin.AdminServer.AdminServerException;
  18. import org.apache.zookeeper.server.auth.ProviderRegistry;
  19. import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
  20. import org.apache.zookeeper.server.persistence.FileTxnSnapLog.DatadirException;
  21. import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException;
  22. import org.apache.zookeeper.server.util.JvmPauseMonitor;
  23. import org.apache.zookeeper.util.ServiceUtils;
  24. import org.slf4j.Logger;
  25. import org.slf4j.LoggerFactory;
  26. /**
  27. *
  28. * <h2>Configuration file</h2>
  29. *
  30. * When the main() method of this class is used to start the program, the first
  31. * argument is used as a path to the config file, which will be used to obtain
  32. * configuration information. This file is a Properties file, so keys and
  33. * values are separated by equals (=) and the key/value pairs are separated
  34. * by new lines. The following is a general summary of keys used in the
  35. * configuration file. For full details on this see the documentation in
  36. * docs/index.html
  37. * <ol>
  38. * <li>dataDir - The directory where the ZooKeeper data is stored.</li>
  39. * <li>dataLogDir - The directory where the ZooKeeper transaction log is stored.</li>
  40. * <li>clientPort - The port used to communicate with clients.</li>
  41. * <li>tickTime - The duration of a tick in milliseconds. This is the basic
  42. * unit of time in ZooKeeper.</li>
  43. * <li>initLimit - The maximum number of ticks that a follower will wait to
  44. * initially synchronize with a leader.</li>
  45. * <li>syncLimit - The maximum number of ticks that a follower will wait for a
  46. * message (including heartbeats) from the leader.</li>
  47. * <li>server.<i>id</i> - This is the host:port[:port] that the server with the
  48. * given id will use for the quorum protocol.</li>
  49. * </ol>
  50. * In addition to the config file. There is a file in the data directory called
  51. * "myid" that contains the server id as an ASCII decimal value.
  52. *
  53. */
  54. @InterfaceAudience.Public
  55. public class QuorumPeerMain {
  56.     private static final Logger LOG = LoggerFactory.getLogger(QuorumPeerMain.class);
  57.     private static final String USAGE = "Usage: QuorumPeerMain configfile";
  58.     protected QuorumPeer quorumPeer;
  59.     /**
  60.      * To start the replicated server specify the configuration file name on
  61.      * the command line.
  62.      * @param args path to the configfile
  63.      */
  64.     public static void main(String[] args) {
  65.         QuorumPeerMain main = new QuorumPeerMain();
  66.         try {
  67.             main.initializeAndRun(args);
  68.         } catch (IllegalArgumentException e) {
  69.             LOG.error("Invalid arguments, exiting abnormally", e);
  70.             LOG.info(USAGE);
  71.             System.err.println(USAGE);
  72.             ZKAuditProvider.addServerStartFailureAuditLog();
  73.             ServiceUtils.requestSystemExit(ExitCode.INVALID_INVOCATION.getValue());
  74.         } catch (ConfigException e) {
  75.             LOG.error("Invalid config, exiting abnormally", e);
  76.             System.err.println("Invalid config, exiting abnormally");
  77.             ZKAuditProvider.addServerStartFailureAuditLog();
  78.             ServiceUtils.requestSystemExit(ExitCode.INVALID_INVOCATION.getValue());
  79.         } catch (DatadirException e) {
  80.             LOG.error("Unable to access datadir, exiting abnormally", e);
  81.             System.err.println("Unable to access datadir, exiting abnormally");
  82.             ZKAuditProvider.addServerStartFailureAuditLog();
  83.             ServiceUtils.requestSystemExit(ExitCode.UNABLE_TO_ACCESS_DATADIR.getValue());
  84.         } catch (AdminServerException e) {
  85.             LOG.error("Unable to start AdminServer, exiting abnormally", e);
  86.             System.err.println("Unable to start AdminServer, exiting abnormally");
  87.             ZKAuditProvider.addServerStartFailureAuditLog();
  88.             ServiceUtils.requestSystemExit(ExitCode.ERROR_STARTING_ADMIN_SERVER.getValue());
  89.         } catch (Exception e) {
  90.             LOG.error("Unexpected exception, exiting abnormally", e);
  91.             ZKAuditProvider.addServerStartFailureAuditLog();
  92.             ServiceUtils.requestSystemExit(ExitCode.UNEXPECTED_ERROR.getValue());
  93.         }
  94.         LOG.info("Exiting normally");
  95.         ServiceUtils.requestSystemExit(ExitCode.EXECUTION_FINISHED.getValue());
  96.     }
  97.     protected void initializeAndRun(String[] args) throws ConfigException, IOException, AdminServerException {
  98.         QuorumPeerConfig config = new QuorumPeerConfig();
  99.         if (args.length == 1) {
  100.             config.parse(args[0]);
  101.         }
  102.         // Start and schedule the the purge task
  103.         DatadirCleanupManager purgeMgr = new DatadirCleanupManager(
  104.             config.getDataDir(),
  105.             config.getDataLogDir(),
  106.             config.getSnapRetainCount(),
  107.             config.getPurgeInterval());
  108.         purgeMgr.start();
  109.         if (args.length == 1 && config.isDistributed()) {
  110.             runFromConfig(config);
  111.         } else {
  112.             LOG.warn("Either no config or no quorum defined in config, running in standalone mode");
  113.             // there is only server in the quorum -- run as standalone
  114.             ZooKeeperServerMain.main(args);
  115.         }
  116.     }
  117.     public void runFromConfig(QuorumPeerConfig config) throws IOException, AdminServerException {
  118.         try {
  119.             ManagedUtil.registerLog4jMBeans();
  120.         } catch (JMException e) {
  121.             LOG.warn("Unable to register log4j JMX control", e);
  122.         }
  123.         LOG.info("Starting quorum peer, myid=" + config.getServerId());
  124.         final MetricsProvider metricsProvider;
  125.         try {
  126.             metricsProvider = MetricsProviderBootstrap.startMetricsProvider(
  127.                 config.getMetricsProviderClassName(),
  128.                 config.getMetricsProviderConfiguration());
  129.         } catch (MetricsProviderLifeCycleException error) {
  130.             throw new IOException("Cannot boot MetricsProvider " + config.getMetricsProviderClassName(), error);
  131.         }
  132.         try {
  133.             ServerMetrics.metricsProviderInitialized(metricsProvider);
  134.             ProviderRegistry.initialize();
  135.             ServerCnxnFactory cnxnFactory = null;
  136.             ServerCnxnFactory secureCnxnFactory = null;
  137.             if (config.getClientPortAddress() != null) {
  138.                 cnxnFactory = ServerCnxnFactory.createFactory();
  139.                 cnxnFactory.configure(config.getClientPortAddress(), config.getMaxClientCnxns(), config.getClientPortListenBacklog(), false);
  140.             }
  141.             if (config.getSecureClientPortAddress() != null) {
  142.                 secureCnxnFactory = ServerCnxnFactory.createFactory();
  143.                 secureCnxnFactory.configure(config.getSecureClientPortAddress(), config.getMaxClientCnxns(), config.getClientPortListenBacklog(), true);
  144.             }
  145.             quorumPeer = getQuorumPeer();
  146.             quorumPeer.setTxnFactory(new FileTxnSnapLog(config.getDataLogDir(), config.getDataDir()));
  147.             quorumPeer.enableLocalSessions(config.areLocalSessionsEnabled());
  148.             quorumPeer.enableLocalSessionsUpgrading(config.isLocalSessionsUpgradingEnabled());
  149.             //quorumPeer.setQuorumPeers(config.getAllMembers());
  150.             quorumPeer.setElectionType(config.getElectionAlg());
  151.             quorumPeer.setMyid(config.getServerId());
  152.             quorumPeer.setTickTime(config.getTickTime());
  153.             quorumPeer.setMinSessionTimeout(config.getMinSessionTimeout());
  154.             quorumPeer.setMaxSessionTimeout(config.getMaxSessionTimeout());
  155.             quorumPeer.setInitLimit(config.getInitLimit());
  156.             quorumPeer.setSyncLimit(config.getSyncLimit());
  157.             quorumPeer.setConnectToLearnerMasterLimit(config.getConnectToLearnerMasterLimit());
  158.             quorumPeer.setObserverMasterPort(config.getObserverMasterPort());
  159.             quorumPeer.setConfigFileName(config.getConfigFilename());
  160.             quorumPeer.setClientPortListenBacklog(config.getClientPortListenBacklog());
  161.             quorumPeer.setZKDatabase(new ZKDatabase(quorumPeer.getTxnFactory()));
  162.             quorumPeer.setQuorumVerifier(config.getQuorumVerifier(), false);
  163.             if (config.getLastSeenQuorumVerifier() != null) {
  164.                 quorumPeer.setLastSeenQuorumVerifier(config.getLastSeenQuorumVerifier(), false);
  165.             }
  166.             quorumPeer.initConfigInZKDatabase();
  167.             quorumPeer.setCnxnFactory(cnxnFactory);
  168.             quorumPeer.setSecureCnxnFactory(secureCnxnFactory);
  169.             quorumPeer.setSslQuorum(config.isSslQuorum());
  170.             quorumPeer.setUsePortUnification(config.shouldUsePortUnification());
  171.             quorumPeer.setLearnerType(config.getPeerType());
  172.             quorumPeer.setSyncEnabled(config.getSyncEnabled());
  173.             quorumPeer.setQuorumListenOnAllIPs(config.getQuorumListenOnAllIPs());
  174.             if (config.sslQuorumReloadCertFiles) {
  175.                 quorumPeer.getX509Util().enableCertFileReloading();
  176.             }
  177.             quorumPeer.setMultiAddressEnabled(config.isMultiAddressEnabled());
  178.             quorumPeer.setMultiAddressReachabilityCheckEnabled(config.isMultiAddressReachabilityCheckEnabled());
  179.             quorumPeer.setMultiAddressReachabilityCheckTimeoutMs(config.getMultiAddressReachabilityCheckTimeoutMs());
  180.             // sets quorum sasl authentication configurations
  181.             quorumPeer.setQuorumSaslEnabled(config.quorumEnableSasl);
  182.             if (quorumPeer.isQuorumSaslAuthEnabled()) {
  183.                 quorumPeer.setQuorumServerSaslRequired(config.quorumServerRequireSasl);
  184.                 quorumPeer.setQuorumLearnerSaslRequired(config.quorumLearnerRequireSasl);
  185.                 quorumPeer.setQuorumServicePrincipal(config.quorumServicePrincipal);
  186.                 quorumPeer.setQuorumServerLoginContext(config.quorumServerLoginContext);
  187.                 quorumPeer.setQuorumLearnerLoginContext(config.quorumLearnerLoginContext);
  188.             }
  189.             org.apache.zookeeper.server.quorum.QuorumPeerMain.setQuorumCnxnThreadsSize(config.quorumCnxnThreadsSize);
  190.             quorumPeer.initialize();
  191.             if (config.jvmPauseMonitorToRun) {
  192.                 quorumPeer.setJvmPauseMonitor(new JvmPauseMonitor(config));
  193.             }
  194.             quorumPeer.start();
  195.             ZKAuditProvider.addZKStartStopAuditLog();
  196.             quorumPeer.join();
  197.         } catch (InterruptedException e) {
  198.             // warn, but generally this is ok
  199.             LOG.warn("Quorum Peer interrupted", e);
  200.         } finally {
  201.             try {
  202.                 metricsProvider.stop();
  203.             } catch (Throwable error) {
  204.                 LOG.warn("Error while stopping metrics", error);
  205.             }
  206.         }
  207.     }
  208.     // @VisibleForTesting
  209.     protected QuorumPeer getQuorumPeer() throws SaslException {
  210.         return new QuorumPeer();
  211.     }
  212.     /**
  213.      * Shutdowns properly the service, this method is not a public API.
  214.      */
  215.     public void close() {
  216.         if (quorumPeer != null) {
  217.             try {
  218.                 quorumPeer.shutdown();
  219.             } finally {
  220.                 quorumPeer = null;
  221.             }
  222.         }
  223.     }
  224.     @Override
  225.     public String toString() {
  226.         QuorumPeer peer = quorumPeer;
  227.         return peer == null ? "" : peer.toString();
  228.     }
  229. }
复制代码
org.apache.zookeeper.server.quorum.QuorumPeerMain 是 Apache ZooKeeper 项目中的一个类,它负责启动和管理 ZooKeeper 的 Quorum 服务器。
ZooKeeper 是一个为分布式体系提供服务的开源项目,它为分布式应用提供了一致的、可靠的、高性能的调和服务。Quorum 服务器是 ZooKeeper 集群的核心组件之一,它负责处理客户端的请求,维护集群的状态,以及在集群中复制和同步数据。
QuorumPeerMain 类是 ZooKeeper Quorum 服务器的入口点。当你在下令行中运行 ZooKeeper 时,这个类会被 JVM 加载并执行。它负责剖析下令行参数,配置 ZooKeeper 服务器,然后启动服务器并进入监听状态。
这个类包罗了启动和管理 ZooKeeper Quorum 服务器的逻辑。它读取配置文件(通常是 zoo.cfg),设置须要的体系属性,创建和配置 QuorumPeer 对象,然后启动服务器。一旦服务器启动并运行,它将开始担当客户端的毗连请求并处理这些请求。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

忿忿的泥巴坨

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表