PageRenderTime 58ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 0ms

/rocketmq-broker/src/main/java/com/alibaba/rocketmq/broker/BrokerStartup.java

https://gitlab.com/xialeizhou/RocketMQ
Java | 288 lines | 208 code | 45 blank | 35 comment | 27 complexity | 421709a990b428c8d298bac2250c95ef MD5 | raw file
  1. /**
  2. * Copyright (C) 2010-2013 Alibaba Group Holding Limited
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.alibaba.rocketmq.broker;
  17. import java.io.BufferedInputStream;
  18. import java.io.FileInputStream;
  19. import java.io.InputStream;
  20. import java.util.Properties;
  21. import java.util.concurrent.atomic.AtomicInteger;
  22. import org.apache.commons.cli.CommandLine;
  23. import org.apache.commons.cli.Option;
  24. import org.apache.commons.cli.Options;
  25. import org.apache.commons.cli.PosixParser;
  26. import org.slf4j.Logger;
  27. import org.slf4j.LoggerFactory;
  28. import ch.qos.logback.classic.LoggerContext;
  29. import ch.qos.logback.classic.joran.JoranConfigurator;
  30. import com.alibaba.rocketmq.common.BrokerConfig;
  31. import com.alibaba.rocketmq.common.MQVersion;
  32. import com.alibaba.rocketmq.common.MixAll;
  33. import com.alibaba.rocketmq.common.conflict.PackageConflictDetect;
  34. import com.alibaba.rocketmq.common.constant.LoggerName;
  35. import com.alibaba.rocketmq.remoting.common.RemotingUtil;
  36. import com.alibaba.rocketmq.remoting.netty.NettyClientConfig;
  37. import com.alibaba.rocketmq.remoting.netty.NettyServerConfig;
  38. import com.alibaba.rocketmq.remoting.netty.NettySystemConfig;
  39. import com.alibaba.rocketmq.remoting.protocol.RemotingCommand;
  40. import com.alibaba.rocketmq.srvutil.ServerUtil;
  41. import com.alibaba.rocketmq.store.config.BrokerRole;
  42. import com.alibaba.rocketmq.store.config.MessageStoreConfig;
  43. /**
  44. * @author shijia.wxr<vintage.wang@gmail.com>
  45. * @since 2013-7-26
  46. */
  47. public class BrokerStartup {
  48. public static Properties properties = null;
  49. public static CommandLine commandLine = null;
  50. public static String configFile = null;
  51. public static Logger log;
  52. public static Options buildCommandlineOptions(final Options options) {
  53. Option opt = new Option("c", "configFile", true, "Broker config properties file");
  54. opt.setRequired(false);
  55. options.addOption(opt);
  56. opt = new Option("p", "printConfigItem", false, "Print all config item");
  57. opt.setRequired(false);
  58. options.addOption(opt);
  59. opt = new Option("m", "printImportantConfig", false, "Print important config item");
  60. opt.setRequired(false);
  61. options.addOption(opt);
  62. return options;
  63. }
  64. public static void main(String[] args) {
  65. start(createBrokerController(args));
  66. }
  67. public static BrokerController createBrokerController(String[] args) {
  68. System.setProperty(RemotingCommand.RemotingVersionKey, Integer.toString(MQVersion.CurrentVersion));
  69. // Socket发送缓冲区大小
  70. if (null == System.getProperty(NettySystemConfig.SystemPropertySocketSndbufSize)) {
  71. NettySystemConfig.SocketSndbufSize = 131072;
  72. }
  73. // Socket接收缓冲区大小
  74. if (null == System.getProperty(NettySystemConfig.SystemPropertySocketRcvbufSize)) {
  75. NettySystemConfig.SocketRcvbufSize = 131072;
  76. }
  77. try {
  78. // 检测包冲突
  79. PackageConflictDetect.detectFastjson();
  80. // 解析命令行
  81. Options options = ServerUtil.buildCommandlineOptions(new Options());
  82. commandLine =
  83. ServerUtil.parseCmdLine("mqbroker", args, buildCommandlineOptions(options),
  84. new PosixParser());
  85. if (null == commandLine) {
  86. System.exit(-1);
  87. return null;
  88. }
  89. // 初始化配置文件
  90. final BrokerConfig brokerConfig = new BrokerConfig();
  91. final NettyServerConfig nettyServerConfig = new NettyServerConfig();
  92. final NettyClientConfig nettyClientConfig = new NettyClientConfig();
  93. nettyServerConfig.setListenPort(10911);
  94. final MessageStoreConfig messageStoreConfig = new MessageStoreConfig();
  95. // 如果是slave,修改默认值
  96. if (BrokerRole.SLAVE == messageStoreConfig.getBrokerRole()) {
  97. int ratio = messageStoreConfig.getAccessMessageInMemoryMaxRatio() - 10;
  98. messageStoreConfig.setAccessMessageInMemoryMaxRatio(ratio);
  99. }
  100. // 打印默认配置
  101. if (commandLine.hasOption('p')) {
  102. MixAll.printObjectProperties(null, brokerConfig);
  103. MixAll.printObjectProperties(null, nettyServerConfig);
  104. MixAll.printObjectProperties(null, nettyClientConfig);
  105. MixAll.printObjectProperties(null, messageStoreConfig);
  106. System.exit(0);
  107. }
  108. else if (commandLine.hasOption('m')) {
  109. MixAll.printObjectProperties(null, brokerConfig, true);
  110. MixAll.printObjectProperties(null, nettyServerConfig, true);
  111. MixAll.printObjectProperties(null, nettyClientConfig, true);
  112. MixAll.printObjectProperties(null, messageStoreConfig, true);
  113. System.exit(0);
  114. }
  115. // 指定配置文件
  116. if (commandLine.hasOption('c')) {
  117. String file = commandLine.getOptionValue('c');
  118. if (file != null) {
  119. configFile = file;
  120. InputStream in = new BufferedInputStream(new FileInputStream(file));
  121. properties = new Properties();
  122. properties.load(in);
  123. MixAll.properties2Object(properties, brokerConfig);
  124. MixAll.properties2Object(properties, nettyServerConfig);
  125. MixAll.properties2Object(properties, nettyClientConfig);
  126. MixAll.properties2Object(properties, messageStoreConfig);
  127. BrokerPathConfigHelper.setBrokerConfigPath(file);
  128. System.out.println("load config properties file OK, " + file);
  129. in.close();
  130. }
  131. }
  132. MixAll.properties2Object(ServerUtil.commandLine2Properties(commandLine), brokerConfig);
  133. if (null == brokerConfig.getRocketmqHome()) {
  134. System.out.println("Please set the " + MixAll.ROCKETMQ_HOME_ENV
  135. + " variable in your environment to match the location of the RocketMQ installation");
  136. System.exit(-2);
  137. }
  138. // 检测Name Server地址设置是否正确 IP:PORT
  139. String namesrvAddr = brokerConfig.getNamesrvAddr();
  140. if (null != namesrvAddr) {
  141. try {
  142. String[] addrArray = namesrvAddr.split(";");
  143. if (addrArray != null) {
  144. for (String addr : addrArray) {
  145. RemotingUtil.string2SocketAddress(addr);
  146. }
  147. }
  148. }
  149. catch (Exception e) {
  150. System.out
  151. .printf(
  152. "The Name Server Address[%s] illegal, please set it as follows, \"127.0.0.1:9876;192.168.0.1:9876\"\n",
  153. namesrvAddr);
  154. System.exit(-3);
  155. }
  156. }
  157. // BrokerId的处理
  158. switch (messageStoreConfig.getBrokerRole()) {
  159. case ASYNC_MASTER:
  160. case SYNC_MASTER:
  161. // Master Id必须是0
  162. brokerConfig.setBrokerId(MixAll.MASTER_ID);
  163. break;
  164. case SLAVE:
  165. if (brokerConfig.getBrokerId() <= 0) {
  166. System.out.println("Slave's brokerId must be > 0");
  167. System.exit(-3);
  168. }
  169. break;
  170. default:
  171. break;
  172. }
  173. // Master监听Slave请求的端口,默认为服务端口+1
  174. messageStoreConfig.setHaListenPort(nettyServerConfig.getListenPort() + 1);
  175. // 初始化Logback
  176. LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
  177. JoranConfigurator configurator = new JoranConfigurator();
  178. configurator.setContext(lc);
  179. lc.reset();
  180. configurator.doConfigure(brokerConfig.getRocketmqHome() + "/conf/logback_broker.xml");
  181. log = LoggerFactory.getLogger(LoggerName.BrokerLoggerName);
  182. // 打印启动参数
  183. MixAll.printObjectProperties(log, brokerConfig);
  184. MixAll.printObjectProperties(log, nettyServerConfig);
  185. MixAll.printObjectProperties(log, nettyClientConfig);
  186. MixAll.printObjectProperties(log, messageStoreConfig);
  187. // 初始化服务控制对象
  188. final BrokerController controller = new BrokerController(//
  189. brokerConfig, //
  190. nettyServerConfig, //
  191. nettyClientConfig, //
  192. messageStoreConfig);
  193. boolean initResult = controller.initialize();
  194. if (!initResult) {
  195. controller.shutdown();
  196. System.exit(-3);
  197. }
  198. Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
  199. private volatile boolean hasShutdown = false;
  200. private AtomicInteger shutdownTimes = new AtomicInteger(0);
  201. @Override
  202. public void run() {
  203. synchronized (this) {
  204. log.info("shutdown hook was invoked, " + this.shutdownTimes.incrementAndGet());
  205. if (!this.hasShutdown) {
  206. this.hasShutdown = true;
  207. long begineTime = System.currentTimeMillis();
  208. controller.shutdown();
  209. long consumingTimeTotal = System.currentTimeMillis() - begineTime;
  210. log.info("shutdown hook over, consuming time total(ms): " + consumingTimeTotal);
  211. }
  212. }
  213. }
  214. }, "ShutdownHook"));
  215. return controller;
  216. }
  217. catch (Throwable e) {
  218. e.printStackTrace();
  219. System.exit(-1);
  220. }
  221. return null;
  222. }
  223. public static BrokerController start(BrokerController controller) {
  224. try {
  225. // 启动服务控制对象
  226. controller.start();
  227. String tip =
  228. "The broker[" + controller.getBrokerConfig().getBrokerName() + ", "
  229. + controller.getBrokerAddr() + "] boot success.";
  230. if (null != controller.getBrokerConfig().getNamesrvAddr()) {
  231. tip += " and name server is " + controller.getBrokerConfig().getNamesrvAddr();
  232. }
  233. log.info(tip);
  234. System.out.println(tip);
  235. return controller;
  236. }
  237. catch (Throwable e) {
  238. e.printStackTrace();
  239. System.exit(-1);
  240. }
  241. return null;
  242. }
  243. }