Application.cpp 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461
  1. /**
  2. * Tencent is pleased to support the open source community by making Tars available.
  3. *
  4. * Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved.
  5. *
  6. * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
  7. * in compliance with the License. You may obtain a copy of the License at
  8. *
  9. * https://opensource.org/licenses/BSD-3-Clause
  10. *
  11. * Unless required by applicable law or agreed to in writing, software distributed
  12. * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  13. * CONDITIONS OF ANY KIND, either express or implied. See the License for the
  14. * specific language governing permissions and limitations under the License.
  15. */
  16. #include <sstream>
  17. #include "util/tc_option.h"
  18. #include "util/tc_common.h"
  19. #include "servant/KeepAliveNodeF.h"
  20. #include "servant/Application.h"
  21. #include "servant/AppProtocol.h"
  22. #include "servant/AdminServant.h"
  23. #include "servant/ServantHandle.h"
  24. #include "servant/BaseF.h"
  25. #include "servant/AppCache.h"
  26. #include "servant/NotifyObserver.h"
  27. #include "servant/AuthLogic.h"
  28. #include "servant/CommunicatorFactory.h"
  29. #include <signal.h>
  30. #if TARGET_PLATFORM_LINUX
  31. #include <sys/resource.h>
  32. #endif
  33. #if TARGET_PLATFORM_LINUX || TARGET_PLATFORM_IOS
  34. #include <fcntl.h>
  35. #endif
  36. #if TARS_SSL
  37. #include "util/tc_openssl.h"
  38. #endif
  39. static TC_RollLogger __out__;
  40. #define NOTIFY_AND_WAIT(msg) { \
  41. RemoteNotify::getInstance()->report(msg); \
  42. std::this_thread::sleep_for(std::chrono::milliseconds(20)); \
  43. }
  44. namespace tars
  45. {
  46. std::string ServerConfig::TarsPath; //服务路径
  47. std::string ServerConfig::Application; //应用名称
  48. std::string ServerConfig::ServerName; //服务名称,一个服务名称含一个或多个服务标识
  49. std::string ServerConfig::LocalIp; //本机IP
  50. std::string ServerConfig::BasePath; //应用程序路径,用于保存远程系统配置的本地目录
  51. std::string ServerConfig::DataPath; //应用程序路径,用于本地数据
  52. std::string ServerConfig::Local; //本地套接字
  53. std::string ServerConfig::Node; //本机node地址
  54. std::string ServerConfig::Log; //日志中心地址
  55. std::string ServerConfig::Config; //配置中心地址
  56. std::string ServerConfig::Notify; //信息通知中心
  57. std::string ServerConfig::LogPath; //logpath
  58. int ServerConfig::LogSize; //log大小(字节)
  59. int ServerConfig::LogNum; //log个数()
  60. std::string ServerConfig::LogLevel; //log日志级别
  61. std::string ServerConfig::ConfigFile; //框架配置文件路径
  62. int ServerConfig::ReportFlow = 1; //是否服务端上报所有接口stat流量 0不上报 1上报 (用于非tars协议服务流量统计)
  63. int ServerConfig::IsCheckSet = 1; //是否对按照set规则调用进行合法性检查 0,不检查,1检查
  64. int ServerConfig::OpenCoroutine = 0; //是否启用协程处理方式
  65. size_t ServerConfig::CoroutineMemSize; //协程占用内存空间的最大大小
  66. uint32_t ServerConfig::CoroutineStackSize; //每个协程的栈大小(默认128k)
  67. bool ServerConfig::ManualListen = false; //手工启动监听端口
  68. //bool ServerConfig::MergeNetImp = false; //合并网络和处理线程
  69. int ServerConfig::NetThread = 1; //servernet thread
  70. bool ServerConfig::CloseCout = true;
  71. int ServerConfig::BackPacketLimit = 0;
  72. int ServerConfig::BackPacketMin = 1024;
  73. //int ServerConfig::Pattern = 0;
  74. #if TARS_SSL
  75. std::string ServerConfig::CA;
  76. std::string ServerConfig::Cert;
  77. std::string ServerConfig::Key;
  78. bool ServerConfig::VerifyClient = false;
  79. std::string ServerConfig::Ciphers;
  80. #endif
  81. map<string, string> ServerConfig::Context;
  82. ///////////////////////////////////////////////////////////////////////////////////////////
  83. //TC_Config Application::_conf;
  84. //TC_EpollServerPtr Application::_epollServer = NULL;
  85. CommunicatorPtr Application::_communicator = NULL;
  86. PropertyReportPtr g_pReportRspQueue;
  87. /**上报服务端发送队列大小的间隔时间**/
  88. #define REPORT_SEND_QUEUE_INTERVAL 10
  89. ///////////////////////////////////////////////////////////////////////////////////////////
  90. Application::Application()
  91. {
  92. _servantHelper = std::make_shared<ServantHelperManager>();
  93. _notifyObserver = std::make_shared<NotifyObserver>();
  94. setNotifyObserver(_notifyObserver);
  95. #if TARGET_PLATFORM_WINDOWS
  96. WSADATA wsadata;
  97. WSAStartup(MAKEWORD(2, 2), &wsadata);
  98. #endif
  99. }
  100. Application::~Application()
  101. {
  102. if(_epollServer)
  103. {
  104. _epollServer->terminate();
  105. _epollServer = NULL;
  106. }
  107. #if TARGET_PLATFORM_WINDOWS
  108. WSACleanup();
  109. #endif
  110. }
  111. string Application::getTarsVersion()
  112. {
  113. return TARS_VERSION;
  114. }
  115. CommunicatorPtr& Application::getCommunicator()
  116. {
  117. return _communicator;
  118. }
  119. void reportRspQueue(TC_EpollServer *epollServer)
  120. {
  121. if (!g_pReportRspQueue)
  122. return;
  123. static time_t iLastCheckTime = TNOW;
  124. time_t iNow = TNOW;
  125. if (iNow - iLastCheckTime > REPORT_SEND_QUEUE_INTERVAL)
  126. {
  127. iLastCheckTime = iNow;
  128. const vector<TC_EpollServer::BindAdapterPtr> &adapters = epollServer->getBindAdapters();
  129. size_t n = 0;
  130. for (size_t i = 0; i < adapters.size(); ++i)
  131. {
  132. n = n + adapters[i]->getSendBufferSize();
  133. }
  134. g_pReportRspQueue->report((int)n);
  135. }
  136. }
  137. void heartBeatFunc(const string& adapterName)
  138. {
  139. TARS_KEEPALIVE(adapterName);
  140. }
  141. void Application::manualListen()
  142. {
  143. vector<TC_EpollServer::BindAdapterPtr> v = getEpollServer()->getBindAdapters();
  144. for(auto &b : v)
  145. {
  146. b->manualListen();
  147. }
  148. }
  149. void Application::waitForShutdown()
  150. {
  151. assert(_epollServer);
  152. _epollServer->setCallbackFunctor(reportRspQueue);
  153. _epollServer->setHeartBeatFunctor(heartBeatFunc);
  154. _epollServer->setDestroyAppFunctor([&](TC_EpollServer *epollServer){
  155. this->destroyApp();
  156. NOTIFY_AND_WAIT("stop");
  157. });
  158. _epollServer->waitForShutdown();
  159. TC_Port::unregisterCtrlC(_ctrlCId);
  160. TC_Port::unregisterTerm(_termId);
  161. _epollServer = NULL;
  162. }
  163. void Application::waitForReady()
  164. {
  165. if(_epollServer)
  166. {
  167. _epollServer->waitForReady();
  168. }
  169. }
  170. void Application::terminate()
  171. {
  172. if (_epollServer && !_epollServer->isTerminate())
  173. {
  174. std::this_thread::sleep_for(std::chrono::milliseconds(100)); //稍微休息一下, 让当前处理包能够回复
  175. _epollServer->terminate();
  176. }
  177. }
  178. bool Application::cmdViewStatus(const string& command, const string& params, string& result)
  179. {
  180. TLOGTARS("Application::cmdViewStatus:" << command << " " << params << endl);
  181. ostringstream os;
  182. os << OUT_LINE_LONG << endl;
  183. os << TC_Common::outfill("[proxy config]:") << endl;
  184. outClient(os);
  185. os << OUT_LINE << "\n" << TC_Common::outfill("[server config]:") << endl;
  186. outServer(os);
  187. os << OUT_LINE << endl;
  188. outAllAdapter(os);
  189. result = os.str();
  190. return true;
  191. }
  192. bool Application::cmdCloseCoreDump(const string& command, const string& params, string& result)
  193. {
  194. #if TARGET_PLATFORM_LINUX || TARGET_PLATFORM_IOS
  195. struct rlimit tlimit;
  196. int ret = 0;
  197. ostringstream os;
  198. ret = getrlimit(RLIMIT_CORE, &tlimit);
  199. if (ret != 0)
  200. {
  201. TLOGERROR("error: "<<strerror(errno)<<endl);
  202. return false;
  203. }
  204. TLOGDEBUG("before :cur:" << tlimit.rlim_cur << ";max: " << tlimit.rlim_max << endl);
  205. os << (ServerConfig::Application + "." + ServerConfig::ServerName);
  206. os << "|before set:cur:" << tlimit.rlim_cur << ";max: " << tlimit.rlim_max;
  207. string param = TC_Common::lower(TC_Common::trim(params));
  208. bool bClose = (param == "yes") ? true : false;
  209. if (bClose)
  210. {
  211. tlimit.rlim_cur = 0;
  212. }
  213. else
  214. {
  215. tlimit.rlim_cur = tlimit.rlim_max;
  216. }
  217. ret = setrlimit(RLIMIT_CORE, &tlimit);
  218. if (ret != 0)
  219. {
  220. TLOGERROR("error: "<<strerror(errno)<<endl);
  221. return false;
  222. }
  223. ret = getrlimit(RLIMIT_CORE, &tlimit);
  224. if (ret != 0)
  225. {
  226. TLOGERROR("error: "<<strerror(errno)<<endl);
  227. return false;
  228. }
  229. TLOGDEBUG("after cur:" << tlimit.rlim_cur << ";max: " << tlimit.rlim_max << endl);
  230. os << "|after set cur:" << tlimit.rlim_cur << ";max: " << tlimit.rlim_max << endl;
  231. result = os.str();
  232. #else
  233. TLOGDEBUG("windows not support!");
  234. #endif
  235. return true;
  236. }
  237. bool Application::cmdSetLogLevel(const string& command, const string& params, string& result)
  238. {
  239. TLOGTARS("Application::cmdSetLogLevel:" << command << " " << params << endl);
  240. string level = TC_Common::trim(params);
  241. int ret = LocalRollLogger::getInstance()->logger()->setLogLevel(level);
  242. if (ret == 0)
  243. {
  244. ServerConfig::LogLevel = TC_Common::upper(level);
  245. result = "set log level [" + level + "] ok";
  246. AppCache::getInstance()->set("logLevel", level);
  247. }
  248. else
  249. {
  250. result = "set log level [" + level + "] error";
  251. }
  252. return true;
  253. }
  254. bool Application::cmdEnableDayLog(const string& command, const string& params, string& result)
  255. {
  256. TLOGTARS("Application::cmdEnableDayLog:" << command << " " << params << endl);
  257. vector<string> vParams = TC_Common::sepstr<string>(TC_Common::trim(params), "|");
  258. size_t nNum = vParams.size();
  259. if (!(nNum == 2 || nNum == 3))
  260. {
  261. result = "usage: tars.enabledaylog {remote|local}|[logname]|{true|false}";
  262. return false;
  263. }
  264. if((vParams[0] != "local" && vParams[0] != "remote"))
  265. {
  266. result = "usage: tars.enabledaylog {remote|local}|[logname]|{true|false}";
  267. return false;
  268. }
  269. if(nNum == 2 && (vParams[1] != "true" && vParams[1] != "false"))
  270. {
  271. result = "usage: tars.enabledaylog {remote|local}|[logname]|{true|false}";
  272. return false;
  273. }
  274. if(nNum == 3 && (vParams[2] != "true" && vParams[2] != "false"))
  275. {
  276. result = "usage: tars.enabledaylog {remote|local}|[logname]|{true|false}";
  277. return false;
  278. }
  279. bool bEnable = true;
  280. string sFile;
  281. if (nNum == 2)
  282. {
  283. bEnable = (vParams[1] == "true") ? true : false;
  284. sFile = "";
  285. result = "set " + vParams[0] + " " + vParams[1] + " ok";
  286. }
  287. else if (nNum == 3)
  288. {
  289. bEnable = (vParams[2] == "true") ? true : false;
  290. sFile = vParams[1];
  291. result = "set " + vParams[0] + " " + vParams[1] + " " + vParams[2] + " ok";
  292. }
  293. if (vParams[0] == "local")
  294. {
  295. RemoteTimeLogger::getInstance()->enableLocal(sFile, bEnable);
  296. return true;
  297. }
  298. if (vParams[0] == "remote")
  299. {
  300. RemoteTimeLogger::getInstance()->enableRemote(sFile, bEnable);
  301. return true;
  302. }
  303. result = "usage: tars.enabledaylog {remote|local}|[logname]|{true|false}";
  304. return false;
  305. }
  306. bool Application::cmdLoadConfig(const string& command, const string& params, string& result)
  307. {
  308. TLOGTARS("Application::cmdLoadConfig:" << command << " " << params << endl);
  309. string filename = TC_Common::trim(params);
  310. if (RemoteConfig::getInstance()->addConfig(filename, result, false))
  311. {
  312. RemoteNotify::getInstance()->report(result);
  313. return true;
  314. }
  315. RemoteNotify::getInstance()->report(result);
  316. return true;
  317. }
  318. bool Application::cmdConnections(const string& command, const string& params, string& result)
  319. {
  320. TLOGTARS("Application::cmdConnections:" << command << " " << params << endl);
  321. ostringstream os;
  322. os << OUT_LINE_LONG << endl;
  323. auto m = _epollServer->getListenSocketInfo();
  324. for (auto it = m.begin(); it != m.end(); ++it)
  325. {
  326. vector<TC_EpollServer::ConnStatus> v = it->second->getConnStatus();
  327. os << OUT_LINE << "\n" << TC_Common::outfill("[adater:" + it->second->getName() + "] [connections:" + TC_Common::tostr(v.size()) + "]") << endl;
  328. os << TC_Common::outfill("conn-uid", ' ', 15)
  329. << TC_Common::outfill("ip:port", ' ', 25)
  330. << TC_Common::outfill("last-time", ' ', 25)
  331. << TC_Common::outfill("timeout", ' ', 10)
  332. << TC_Common::outfill("recvBufferSize", ' ', 30)
  333. << TC_Common::outfill("sendBufferSize", ' ', 30)
  334. << endl;
  335. for (size_t i = 0; i < v.size(); i++)
  336. {
  337. os << TC_Common::outfill(TC_Common::tostr<uint32_t>(v[i].uid), ' ', 15)
  338. << TC_Common::outfill(v[i].ip + ":" + TC_Common::tostr(v[i].port), ' ', 25)
  339. << TC_Common::outfill(TC_Common::tm2str(v[i].iLastRefreshTime, "%Y-%m-%d %H:%M:%S"), ' ', 25)
  340. << TC_Common::outfill(TC_Common::tostr(v[i].timeout), ' ', 10)
  341. << TC_Common::outfill(TC_Common::tostr(v[i].recvBufferSize), ' ', 30)
  342. << TC_Common::outfill(TC_Common::tostr(v[i].sendBufferSize), ' ', 30)
  343. << endl;
  344. }
  345. }
  346. os << OUT_LINE_LONG << endl;
  347. result = os.str();
  348. return true;
  349. }
  350. bool Application::cmdViewVersion(const string& command, const string& params, string& result)
  351. {
  352. result = "$" + string(TARS_VERSION) + "$";
  353. return true;
  354. }
  355. bool Application::cmdViewBuildID(const string& command, const string& params, string& result)
  356. {
  357. #define YEARSUF ((__DATE__ [9] - '0') * 10 + (__DATE__ [10] - '0'))
  358. #define MONTH (__DATE__ [2] == 'n' ? (__DATE__ [1] == 'a' ? 0 : 5) \
  359. : __DATE__ [2] == 'b' ? 1 \
  360. : __DATE__ [2] == 'r' ? (__DATE__ [0] == 'M' ? 2 : 3) \
  361. : __DATE__ [2] == 'y' ? 4 \
  362. : __DATE__ [2] == 'l' ? 6 \
  363. : __DATE__ [2] == 'g' ? 7 \
  364. : __DATE__ [2] == 'p' ? 8 \
  365. : __DATE__ [2] == 't' ? 9 \
  366. : __DATE__ [2] == 'v' ? 10 : 11)
  367. #define DAY ((__DATE__ [4] == ' ' ? 0 : __DATE__ [4] - '0') * 10 \
  368. + (__DATE__ [5] - '0'))
  369. #define TIMEINT ((((((__TIME__[0] - '0') * 10 + (__TIME__[1] - '0')) * 10 \
  370. + (__TIME__[3] - '0')) * 10 + (__TIME__[4] - '0')) * 10 \
  371. + (__TIME__[6] - '0')) * 10 + (__TIME__[7] - '0'))
  372. char buildTime[50] = {0};
  373. sprintf(buildTime, "%d.%02d%02d.%06d", YEARSUF, MONTH + 1, DAY, TIMEINT);
  374. result = "$" + ServerConfig::Application + "." + ServerConfig::ServerName + "-" + string(buildTime) + "$";
  375. return true;
  376. }
  377. bool Application::cmdLoadProperty(const string& command, const string& params, string& result)
  378. {
  379. try
  380. {
  381. TLOGTARS("Application::cmdLoadProperty:" << command << " " << params << endl);
  382. //重新解析配置文件
  383. _conf.parseFile(ServerConfig::ConfigFile);
  384. string sResult = "";
  385. //加载通讯器属性
  386. _communicator->setProperty(_conf);
  387. _communicator->reloadProperty(sResult);
  388. //加载远程对象
  389. ServerConfig::Log = _conf.get("/tars/application/server<log>");
  390. RemoteTimeLogger::getInstance()->setLogInfo(_communicator, ServerConfig::Log, ServerConfig::Application, ServerConfig::ServerName, ServerConfig::LogPath,setDivision());
  391. ServerConfig::Config = _conf.get("/tars/application/server<config>");
  392. RemoteConfig::getInstance()->setConfigInfo(_communicator, ServerConfig::Config, ServerConfig::Application, ServerConfig::ServerName, ServerConfig::BasePath,setDivision(), 5);
  393. ServerConfig::Notify = _conf.get("/tars/application/server<notify>");
  394. RemoteNotify::getInstance()->setNotifyInfo(_communicator, ServerConfig::Notify, ServerConfig::Application, ServerConfig::ServerName, setDivision(), ServerConfig::LocalIp);
  395. result = "loaded config items:\r\n" + sResult +
  396. "log=" + ServerConfig::Log + "\r\n" +
  397. "config=" + ServerConfig::Config + "\r\n" +
  398. "notify=" + ServerConfig::Notify + "\r\n";
  399. }
  400. catch (TC_Config_Exception & ex)
  401. {
  402. result = "load config " + ServerConfig::ConfigFile + " error:" + ex.what();
  403. }
  404. catch (exception &ex)
  405. {
  406. result = ex.what();
  407. }
  408. return true;
  409. }
  410. bool Application::cmdViewAdminCommands(const string& command, const string& params, string& result)
  411. {
  412. TLOGTARS("Application::cmdViewAdminCommands:" << command << " " << params << endl);
  413. result = result + _notifyObserver->viewRegisterCommand();
  414. return true;
  415. }
  416. bool Application::cmdSetDyeing(const string& command, const string& params, string& result)
  417. {
  418. vector<string> vDyeingParams = TC_Common::sepstr<string>(params, " ");
  419. if (vDyeingParams.size() == 2 || vDyeingParams.size() == 3)
  420. {
  421. _servantHelper->setDyeing(vDyeingParams[0], vDyeingParams[1], vDyeingParams.size() == 3 ? vDyeingParams[2] : "");
  422. result = "DyeingKey=" + vDyeingParams[0] + "\r\n" +
  423. "DyeingServant=" + vDyeingParams[1] + "\r\n" +
  424. "DyeingInterface=" + (vDyeingParams.size() == 3 ? vDyeingParams[2] : "") + "\r\n";
  425. }
  426. else
  427. {
  428. result = "Invalid parameters.Should be: dyeingKey dyeingServant [dyeingInterface]";
  429. }
  430. return true;
  431. }
  432. bool Application::cmdCloseCout(const string& command, const string& params, string& result)
  433. {
  434. TLOGTARS("Application::cmdCloseCout:" << command << " " << params << endl);
  435. string s = TC_Common::lower(TC_Common::trim(params));
  436. if (s == "yes")
  437. {
  438. AppCache::getInstance()->set("closeCout", "1");
  439. }
  440. else
  441. {
  442. AppCache::getInstance()->set("closeCout", "0");
  443. }
  444. result = "set closeCout [" + s + "] ok";
  445. return true;
  446. }
  447. bool Application::cmdReloadLocator(const string& command, const string& params, string& result)
  448. {
  449. TLOGDEBUG("Application::cmdReloadLocator:" << command << " " << params << endl);
  450. string sPara = TC_Common::lower(TC_Common::trim(params));
  451. bool bSucc(true);
  452. if (sPara == "reload")
  453. {
  454. TLOGDEBUG(__FUNCTION__ << "|" << __LINE__ << "|conf file:" << ServerConfig::ConfigFile << endl);
  455. TC_Config reloadConf;
  456. reloadConf.parseFile(ServerConfig::ConfigFile);
  457. string sLocator = reloadConf.get("/tars/application/client/<locator>", "");
  458. TLOGDEBUG(__FUNCTION__ << "|" << __LINE__ << "|conf file:" << ServerConfig::ConfigFile << "\n"
  459. << "|sLocator:" << sLocator << endl);
  460. if (sLocator.empty())
  461. {
  462. bSucc = false;
  463. result = "locator info is null.";
  464. }
  465. else
  466. {
  467. _communicator->setProperty("locator", sLocator);
  468. _communicator->reloadLocator();
  469. result = sLocator + " set succ.";
  470. }
  471. }
  472. else
  473. {
  474. result = "please input right paras.";
  475. bSucc = false;
  476. }
  477. return bSucc;
  478. }
  479. bool Application::cmdViewResource(const string& command, const string& params, string& result)
  480. {
  481. TLOGDEBUG("Application::cmdViewResource:" << command << " " << params << endl);
  482. ostringstream os;
  483. os << _communicator->getResourcesInfo() << endl;
  484. os << OUT_LINE << endl;
  485. vector<TC_EpollServer::BindAdapterPtr> adapters = _epollServer->getBindAdapters();
  486. for(auto adapter : adapters)
  487. {
  488. outAdapter(os, _servantHelper->getAdapterServant(adapter->getName()), adapter);
  489. os << TC_Common::outfill("recv-buffer-count") << adapter->getRecvBufferSize() << endl;
  490. os << TC_Common::outfill("send-buffer-count") << adapter->getSendBufferSize() << endl;
  491. }
  492. result += os.str();
  493. TLOGDEBUG("Application::cmdViewResource result:" << result << endl);
  494. return true;
  495. }
  496. void Application::outAllAdapter(ostream &os)
  497. {
  498. auto m = _epollServer->getListenSocketInfo();
  499. for (auto it = m.begin(); it != m.end(); ++it)
  500. {
  501. outAdapter(os, _servantHelper->getAdapterServant(it->second->getName()), it->second);
  502. os << OUT_LINE << endl;
  503. }
  504. }
  505. bool Application::addConfig(const string &filename)
  506. {
  507. string result;
  508. if (RemoteConfig::getInstance()->addConfig(filename, result, false))
  509. {
  510. RemoteNotify::getInstance()->report(result);
  511. return true;
  512. }
  513. RemoteNotify::getInstance()->report(result);
  514. return true;
  515. }
  516. bool Application::addAppConfig(const string &filename)
  517. {
  518. string result = "";
  519. // true-只获取应用级别配置
  520. if (RemoteConfig::getInstance()->addConfig(filename, result, true))
  521. {
  522. RemoteNotify::getInstance()->report(result);
  523. return true;
  524. }
  525. RemoteNotify::getInstance()->report(result);
  526. return true;
  527. }
  528. void Application::main(int argc, char *argv[])
  529. {
  530. TC_Option op;
  531. op.decode(argc, argv);
  532. main(op);
  533. }
  534. void Application::main(const TC_Option &option)
  535. {
  536. //直接输出编译的TARS版本
  537. if(option.hasParam("version"))
  538. {
  539. __out__.debug() << "TARS:" << TARS_VERSION << endl;
  540. exit(0);
  541. }
  542. //加载配置文件
  543. ServerConfig::ConfigFile = option.getValue("config");
  544. if (ServerConfig::ConfigFile == "")
  545. {
  546. cerr << "start server with config, for example: exe --config=config.conf" << endl;
  547. exit(-1);
  548. }
  549. string config = TC_File::load2str(ServerConfig::ConfigFile);
  550. main(config);
  551. }
  552. void Application::main(const string &config)
  553. {
  554. try
  555. {
  556. #if TARGET_PLATFORM_LINUX || TARGET_PLATFORM_IOS
  557. TC_Common::ignorePipe();
  558. #endif
  559. //解析配置文件
  560. parseConfig(config);
  561. //初始化Proxy部分
  562. initializeClient();
  563. //初始化Server部分
  564. initializeServer();
  565. vector <TC_EpollServer::BindAdapterPtr> adapters;
  566. //绑定对象和端口
  567. bindAdapter(adapters);
  568. stringstream os;
  569. //输出所有adapter
  570. outAllAdapter(os);
  571. __out__.info() << os.str();
  572. __out__.info() << "\n" << TC_Common::outfill("[initialize server] ", '.') << " [Done]" << endl;
  573. __out__.info() << OUT_LINE_LONG << endl;
  574. {
  575. bool initing = true;
  576. std::mutex mtx;
  577. std::condition_variable cond;
  578. std::thread keepActiving([&]
  579. {
  580. do
  581. {
  582. //发送心跳给node, 表示正在启动
  583. TARS_KEEPACTIVING;
  584. //等待initialize初始化完毕
  585. std::unique_lock<std::mutex> lock(mtx);
  586. cond.wait_for(lock, std::chrono::seconds(5), [&](){
  587. return !initing;
  588. });
  589. }while(initing);
  590. });
  591. try
  592. {
  593. //业务应用的初始化
  594. initialize();
  595. {
  596. std::unique_lock<std::mutex> lock(mtx);
  597. initing = false;
  598. cond.notify_all();
  599. }
  600. keepActiving.join();
  601. }
  602. catch (exception & ex)
  603. {
  604. keepActiving.detach();
  605. NOTIFY_AND_WAIT("exit: " + string(ex.what()));
  606. __out__.error() << "[init exception]:" << ex.what() << endl;
  607. exit(-1);
  608. }
  609. }
  610. //动态加载配置文件
  611. TARS_ADD_ADMIN_CMD_PREFIX(TARS_CMD_LOAD_CONFIG, Application::cmdLoadConfig);
  612. //动态设置滚动日志等级
  613. TARS_ADD_ADMIN_CMD_PREFIX(TARS_CMD_SET_LOG_LEVEL, Application::cmdSetLogLevel);
  614. //动态设置按天日志等级
  615. TARS_ADD_ADMIN_CMD_PREFIX(TARS_CMD_SET_DAYLOG_LEVEL, Application::cmdEnableDayLog);
  616. //查看服务状态
  617. TARS_ADD_ADMIN_CMD_PREFIX(TARS_CMD_VIEW_STATUS, Application::cmdViewStatus);
  618. //查看当前链接状态
  619. TARS_ADD_ADMIN_CMD_PREFIX(TARS_CMD_CONNECTIONS, Application::cmdConnections);
  620. //查看编译的TARS版本
  621. TARS_ADD_ADMIN_CMD_PREFIX(TARS_CMD_VIEW_VERSION, Application::cmdViewVersion);
  622. //查看服务buildid(编译时间)
  623. TARS_ADD_ADMIN_CMD_PREFIX(TARS_CMD_VIEW_BID, Application::cmdViewBuildID);
  624. //加载配置文件中的属性信息
  625. TARS_ADD_ADMIN_CMD_PREFIX(TARS_CMD_LOAD_PROPERTY, Application::cmdLoadProperty);
  626. //查看服务支持的管理命令
  627. TARS_ADD_ADMIN_CMD_PREFIX(TARS_CMD_VIEW_ADMIN_COMMANDS, Application::cmdViewAdminCommands);
  628. //设置染色信息
  629. TARS_ADD_ADMIN_CMD_PREFIX(TARS_CMD_SET_DYEING, Application::cmdSetDyeing);
  630. //设置服务的core limit
  631. TARS_ADD_ADMIN_CMD_PREFIX(TARS_CMD_CLOSE_CORE, Application::cmdCloseCoreDump);
  632. //设置是否标准输出
  633. TARS_ADD_ADMIN_CMD_PREFIX(TARS_CMD_CLOSE_COUT, Application::cmdCloseCout);
  634. //设置是否标准输出
  635. TARS_ADD_ADMIN_CMD_PREFIX(TARS_CMD_RELOAD_LOCATOR, Application::cmdReloadLocator);
  636. //设置是否标准输出
  637. TARS_ADD_ADMIN_CMD_PREFIX(TARS_CMD_RESOURCE, Application::cmdViewResource);
  638. //上报版本
  639. TARS_REPORTVERSION(TARS_VERSION);
  640. //发送心跳给node, 表示启动了
  641. TARS_KEEPALIVE("");
  642. //发送给notify表示服务启动了
  643. RemoteNotify::getInstance()->report("restart");
  644. //ctrl + c能够完美结束服务
  645. _ctrlCId = TC_Port::registerCtrlC([=]{
  646. this->terminate();
  647. #if TARGET_PLATFORM_WINDOWS
  648. ExitProcess(0);
  649. #endif
  650. });
  651. _termId = TC_Port::registerTerm([=]{
  652. this->terminate();
  653. #if TARGET_PLATFORM_WINDOWS
  654. ExitProcess(0);
  655. #endif
  656. });
  657. #if TARGET_PLATFORM_LINUX || TARGET_PLATFORM_IOS
  658. if(_conf.get("/tars/application/server<closecout>",AppCache::getInstance()->get("closeCout")) != "0")
  659. {
  660. // 重定向stdin、stdout、stderr
  661. int fd = open("/dev/null", O_RDWR );
  662. if (fd != -1)
  663. {
  664. dup2(fd, 0);
  665. dup2(fd, 1);
  666. dup2(fd, 2);
  667. }
  668. else
  669. {
  670. close(0);
  671. close(1);
  672. close(2);
  673. }
  674. }
  675. #endif
  676. }
  677. catch (exception &ex)
  678. {
  679. __out__.error() << "[main exception]:" << ex.what() << endl;
  680. NOTIFY_AND_WAIT("exit: " + string(ex.what()));
  681. exit(-1);
  682. }
  683. //初始化完毕后, 日志再修改为异步
  684. LocalRollLogger::getInstance()->sync(false);
  685. }
  686. void Application::parseConfig(const string &config)
  687. {
  688. _conf.parseString(config);
  689. __out__.setLogLevel(_conf.get("/tars/application/server<start_output>", "DEBUG"));
  690. onParseConfig(_conf);
  691. }
  692. TC_EpollServer::BindAdapter::EOrder Application::parseOrder(const string &s)
  693. {
  694. vector<string> vtOrder = TC_Common::sepstr<string>(s, ";, \t", false);
  695. if (vtOrder.size() != 2)
  696. {
  697. cerr << "invalid order '" << TC_Common::tostr(vtOrder) << "'." << endl;
  698. exit(0);
  699. }
  700. if ((TC_Common::lower(vtOrder[0]) == "allow") && (TC_Common::lower(vtOrder[1]) == "deny"))
  701. {
  702. return TC_EpollServer::BindAdapter::ALLOW_DENY;
  703. }
  704. if ((TC_Common::lower(vtOrder[0]) == "deny") && (TC_Common::lower(vtOrder[1]) == "allow"))
  705. {
  706. return TC_EpollServer::BindAdapter::DENY_ALLOW;
  707. }
  708. cerr << "invalid order '" << TC_Common::tostr(vtOrder) << "'." << endl;
  709. exit(0);
  710. }
  711. void Application::initializeClient()
  712. {
  713. __out__.info() << "\n" << OUT_LINE_LONG << endl;
  714. //初始化通信器
  715. _communicator = CommunicatorFactory::getInstance()->getCommunicator(_conf);
  716. __out__.info() << TC_Common::outfill("[proxy config]:") << endl;
  717. //输出
  718. stringstream os;
  719. outClient(os);
  720. __out__.info() << os.str();
  721. }
  722. void Application::outClient(ostream &os)
  723. {
  724. os << OUT_LINE << "\n" << TC_Common::outfill("[load client]:") << endl;
  725. os << TC_Common::outfill("locator") << _communicator->getProperty("locator") << endl;
  726. os << TC_Common::outfill("sync-invoke-timeout") << _communicator->getProperty("sync-invoke-timeout") << endl;
  727. os << TC_Common::outfill("async-invoke-timeout") << _communicator->getProperty("async-invoke-timeout") << endl;
  728. os << TC_Common::outfill("refresh-endpoint-interval") << _communicator->getProperty("refresh-endpoint-interval") << endl;
  729. os << TC_Common::outfill("stat") << _communicator->getProperty("stat") << endl;
  730. os << TC_Common::outfill("property") << _communicator->getProperty("property") << endl;
  731. os << TC_Common::outfill("report-interval") << _communicator->getProperty("report-interval") << endl;
  732. // os << TC_Common::outfill("sample-rate") << _communicator->getProperty("sample-rate") << endl;
  733. // os << TC_Common::outfill("max-sample-count") << _communicator->getProperty("max-sample-count") << endl;
  734. os << TC_Common::outfill("netthread") << _communicator->getProperty("netthread") << endl;
  735. os << TC_Common::outfill("asyncthread") << _communicator->getProperty("asyncthread") << endl;
  736. os << TC_Common::outfill("modulename") << _communicator->getProperty("modulename") << endl;
  737. os << TC_Common::outfill("enableset") << _communicator->getProperty("enableset") << endl;
  738. os << TC_Common::outfill("setdivision") << _communicator->getProperty("setdivision") << endl;
  739. }
  740. string Application::toDefault(const string &s, const string &sDefault)
  741. {
  742. if (s.empty())
  743. {
  744. return sDefault;
  745. }
  746. return s;
  747. }
  748. string Application::setDivision()
  749. {
  750. bool bEnableSet = TC_Common::lower(_conf.get("/tars/application<enableset>", "n"))=="y"?true:false;;
  751. string sSetDevision = bEnableSet?_conf.get("/tars/application<setdivision>", ""):"";
  752. return sSetDevision;
  753. }
  754. void Application::addServantProtocol(const string& servant, const TC_NetWorkBuffer::protocol_functor& protocol)
  755. {
  756. string adapterName = _servantHelper->getServantAdapter(servant);
  757. if (adapterName == "")
  758. {
  759. throw runtime_error("addServantProtocol fail, no found adapter for servant:" + servant);
  760. }
  761. getEpollServer()->getBindAdapter(adapterName)->setProtocol(protocol);
  762. }
  763. void Application::addAcceptCallback(const TC_EpollServer::accept_callback_functor& cb)
  764. {
  765. _acceptFuncs.push_back(cb);
  766. }
  767. void Application::onAccept(TC_EpollServer::Connection* cPtr)
  768. {
  769. for (size_t i = 0; i < _acceptFuncs.size(); ++i)
  770. {
  771. _acceptFuncs[i](cPtr);
  772. }
  773. }
  774. //void Application::addServantOnClose(const string& servant, const TC_EpollServer::close_functor& cf)
  775. //{
  776. // string adapterName = _servantHelper->getServantAdapter(servant);
  777. //
  778. // if (adapterName.empty())
  779. // {
  780. // throw runtime_error("setServantOnClose fail, no found adapter for servant:" + servant);
  781. // }
  782. //
  783. // getEpollServer()->getBindAdapter(adapterName)->setOnClose(cf);
  784. //}
  785. void Application::outServer(ostream &os)
  786. {
  787. os << TC_Common::outfill("Application(app)") << ServerConfig::Application << endl;
  788. os << TC_Common::outfill("ServerName(server)") << ServerConfig::ServerName << endl;
  789. os << TC_Common::outfill("BasePath(basepath)") << ServerConfig::BasePath << endl;
  790. os << TC_Common::outfill("DataPath(datapath)") << ServerConfig::DataPath << endl;
  791. os << TC_Common::outfill("LocalIp(localip)") << ServerConfig::LocalIp << endl;
  792. os << TC_Common::outfill("Local(local)") << ServerConfig::Local << endl;
  793. os << TC_Common::outfill("LogPath(logpath)") << ServerConfig::LogPath << endl;
  794. os << TC_Common::outfill("LogSize(logsize)") << ServerConfig::LogSize << endl;
  795. os << TC_Common::outfill("LogNum(lognum)") << ServerConfig::LogNum << endl;
  796. os << TC_Common::outfill("LogLevel(loglevel)") << ServerConfig::LogLevel << endl;
  797. os << TC_Common::outfill("Log(log)") << ServerConfig::Log << endl;
  798. os << TC_Common::outfill("Node(node)") << ServerConfig::Node << endl;
  799. os << TC_Common::outfill("Config(config)") << ServerConfig::Config << endl;
  800. os << TC_Common::outfill("Notify(notify)") << ServerConfig::Notify << endl;
  801. os << TC_Common::outfill("OpenCoroutine(opencoroutine)") << ServerConfig::OpenCoroutine << endl;
  802. os << TC_Common::outfill("CoroutineMemSize(coroutinememsize)") << ServerConfig::CoroutineMemSize << endl;
  803. os << TC_Common::outfill("CoroutineStackSize(coroutinestack)") << ServerConfig::CoroutineStackSize << endl;
  804. os << TC_Common::outfill("CloseCout(closecout)") << ServerConfig::CloseCout << endl;
  805. os << TC_Common::outfill("NetThread(netthread)") << ServerConfig::NetThread << endl;
  806. os << TC_Common::outfill("ManualListen(manuallisten)") << ServerConfig::ManualListen << endl;
  807. // os << TC_Common::outfill("MergeNetImp(mergenetimp)") << ServerConfig::MergeNetImp << endl;
  808. os << TC_Common::outfill("ReportFlow(reportflow)") << ServerConfig::ReportFlow<< endl;
  809. os << TC_Common::outfill("BackPacketLimit(backpacketlimit)") << ServerConfig::BackPacketLimit<< endl;
  810. os << TC_Common::outfill("BackPacketMin(backpacketmin)") << ServerConfig::BackPacketMin<< endl;
  811. #if TARS_SSL
  812. os << TC_Common::outfill("Ca(ca)") << ServerConfig::CA << endl;
  813. os << TC_Common::outfill("Cert(cert)") << ServerConfig::Cert << endl;
  814. os << TC_Common::outfill("Key(key)") << ServerConfig::Key << endl;
  815. os << TC_Common::outfill("VerifyClient(verifyclient)") << ServerConfig::VerifyClient << endl;
  816. os << TC_Common::outfill("Ciphers(ciphers)") << ServerConfig::Ciphers << endl;
  817. #endif
  818. }
  819. void Application::initializeServer()
  820. {
  821. __out__.info() << OUT_LINE << "\n" << TC_Common::outfill("[server config]:") << endl;
  822. ServerConfig::Application = toDefault(_conf.get("/tars/application/server<app>"), "UNKNOWN");
  823. //缺省采用进程名称
  824. string exe = "";
  825. try
  826. {
  827. exe = TC_File::extractFileName(TC_File::getExePath());
  828. }
  829. catch (TC_File_Exception & ex)
  830. {
  831. //取失败则使用ip代替进程名
  832. exe = _conf.get("/tars/application/server<localip>");
  833. }
  834. ServerConfig::ServerName = toDefault(_conf.get("/tars/application/server<server>"), exe);
  835. #if TARGET_PLATFORM_WINDOWS
  836. ServerConfig::BasePath = TC_File::simplifyDirectory(_conf.get("/tars/application/server<basepath.win>")) + FILE_SEP;
  837. if (ServerConfig::BasePath == FILE_SEP)
  838. {
  839. ServerConfig::BasePath = TC_File::simplifyDirectory(toDefault(_conf.get("/tars/application/server<basepath>"), ".")) + FILE_SEP;
  840. }
  841. ServerConfig::DataPath = TC_File::simplifyDirectory(_conf.get("/tars/application/server<datapath.win>")) + FILE_SEP;
  842. if(ServerConfig::DataPath == FILE_SEP)
  843. {
  844. ServerConfig::DataPath = TC_File::simplifyDirectory(toDefault(_conf.get("/tars/application/server<datapath>"), ".")) + FILE_SEP;
  845. }
  846. ServerConfig::LogPath = TC_File::simplifyDirectory(_conf.get("/tars/application/server<logpath.win>")) + FILE_SEP;
  847. if(ServerConfig::LogPath == FILE_SEP)
  848. {
  849. ServerConfig::LogPath = TC_File::simplifyDirectory(toDefault(_conf.get("/tars/application/server<logpath>"), ".")) + FILE_SEP;
  850. }
  851. #else
  852. ServerConfig::BasePath = TC_File::simplifyDirectory(toDefault(_conf.get("/tars/application/server<basepath>"), ".")) + FILE_SEP;
  853. ServerConfig::DataPath = TC_File::simplifyDirectory(toDefault(_conf.get("/tars/application/server<datapath>"), ".")) + FILE_SEP;
  854. ServerConfig::LogPath = TC_File::simplifyDirectory(toDefault(_conf.get("/tars/application/server<logpath>"), ".")) + FILE_SEP;
  855. #endif
  856. ServerConfig::TarsPath = TC_File::simplifyDirectory(ServerConfig::LogPath + FILE_SEP + ".." + FILE_SEP) + FILE_SEP;
  857. ServerConfig::LogSize = TC_Common::toSize(toDefault(_conf.get("/tars/application/server<logsize>"), "52428800"), 52428800);
  858. ServerConfig::LogNum = TC_Common::strto<int>(toDefault(_conf.get("/tars/application/server<lognum>"), "10"));
  859. ServerConfig::LocalIp = _conf.get("/tars/application/server<localip>");
  860. ServerConfig::Local = _conf.get("/tars/application/server<local>");
  861. ServerConfig::Node = _conf.get("/tars/application/server<node>");
  862. ServerConfig::Log = _conf.get("/tars/application/server<log>");
  863. ServerConfig::Config = _conf.get("/tars/application/server<config>");
  864. ServerConfig::Notify = _conf.get("/tars/application/server<notify>");
  865. ServerConfig::ReportFlow = _conf.get("/tars/application/server<reportflow>")=="0"?0:1;
  866. ServerConfig::IsCheckSet = _conf.get("/tars/application/server<checkset>","1")=="0"?0:1;
  867. ServerConfig::OpenCoroutine = TC_Common::strto<int>(toDefault(_conf.get("/tars/application/server<opencoroutine>"), "0"));
  868. ServerConfig::CoroutineMemSize = TC_Common::toSize(toDefault(_conf.get("/tars/application/server<coroutinememsize>"), "1G"), 1024*1024*1024);
  869. ServerConfig::CoroutineStackSize= (uint32_t)TC_Common::toSize(toDefault(_conf.get("/tars/application/server<coroutinestack>"), "128K"), 1024*128);
  870. ServerConfig::ManualListen = _conf.get("/tars/application/server<manuallisten>", "0") == "0" ? false : true;
  871. // ServerConfig::MergeNetImp = _conf.get("/tars/application/server<mergenetimp>", "0") == "0" ? false : true;
  872. ServerConfig::NetThread = TC_Common::strto<int>(toDefault(_conf.get("/tars/application/server<netthread>"), "1"));
  873. ServerConfig::CloseCout = _conf.get("/tars/application/server<closecout>","1")=="0"?0:1;
  874. ServerConfig::BackPacketLimit = TC_Common::strto<int>(_conf.get("/tars/application/server<backpacketlimit>", "100*1024*1024"));
  875. ServerConfig::BackPacketMin = TC_Common::strto<int>(_conf.get("/tars/application/server<backpacketmin>", "1024"));
  876. ServerConfig::Context["node_name"] = ServerConfig::LocalIp;
  877. #if TARS_SSL
  878. ServerConfig::CA = _conf.get("/tars/application/server<ca>");
  879. ServerConfig::Cert = _conf.get("/tars/application/server<cert>");
  880. ServerConfig::Key = _conf.get("/tars/application/server<key>");
  881. ServerConfig::VerifyClient = _conf.get("/tars/application/server<verifyclient>","0")=="0"?false:true;
  882. ServerConfig::Ciphers = _conf.get("/tars/application/server<ciphers>");
  883. if(!ServerConfig::Cert.empty()) {
  884. _ctx = TC_OpenSSL::newCtx(ServerConfig::CA, ServerConfig::Cert, ServerConfig::Key, ServerConfig::VerifyClient, ServerConfig::Ciphers);
  885. if (!_ctx) {
  886. TLOGERROR("[load server ssl error, ca:" << ServerConfig::CA << endl);
  887. exit(-1);
  888. }
  889. }
  890. #endif
  891. if (ServerConfig::LocalIp.empty())
  892. {
  893. // ServerConfig::LocalIp = "127.0.0.1";
  894. vector<string> v = TC_Socket::getLocalHosts();
  895. ServerConfig::LocalIp = "127.0.0.1";
  896. //获取第一个非127.0.0.1的IP
  897. for(size_t i = 0; i < v.size(); i++)
  898. {
  899. if(v[i] != "127.0.0.1")
  900. {
  901. ServerConfig::LocalIp = v[i];
  902. break;
  903. }
  904. }
  905. }
  906. onServerConfig();
  907. ostringstream os;
  908. //输出信息
  909. outServer(os);
  910. __out__.info() << os.str();
  911. if (ServerConfig::NetThread < 1)
  912. {
  913. ServerConfig::NetThread = 1;
  914. __out__.info() << OUT_LINE << "\nwarning:netThreadNum < 1." << endl;
  915. }
  916. //网络线程的配置数目不能15个
  917. if (ServerConfig::NetThread > 15)
  918. {
  919. ServerConfig::NetThread = 15;
  920. __out__.info() << OUT_LINE << "\nwarning:netThreadNum > 15." << endl;
  921. }
  922. if(ServerConfig::CoroutineMemSize/ServerConfig::CoroutineStackSize <= 0)
  923. {
  924. __out__.error() << OUT_LINE << "\nerror:coroutine paramter error: coroutinememsize/coroutinestack <= 0!." << endl;
  925. exit(-1);
  926. }
  927. _epollServer = new TC_EpollServer();
  928. _epollServer->setThreadNum(ServerConfig::NetThread);
  929. _epollServer->setOpenCoroutine((TC_EpollServer::SERVER_OPEN_COROUTINE)ServerConfig::OpenCoroutine);
  930. _epollServer->setCoroutineStack(ServerConfig::CoroutineMemSize/ServerConfig::CoroutineStackSize, ServerConfig::CoroutineStackSize);
  931. _epollServer->setOnAccept(std::bind(&Application::onAccept, this, std::placeholders::_1));
  932. //初始化服务是否对空链接进行超时检查
  933. // bool bEnable = (_conf.get("/tars/application/server<emptyconcheck>","0")=="1")?true:false;
  934. // _epollServer->enAntiEmptyConnAttack(bEnable);
  935. _epollServer->setEmptyConnTimeout(TC_Common::strto<int>(toDefault(_conf.get("/tars/application/server<emptyconntimeout>"), "0")));
  936. ///////////////////////////////////////////////////////////////////////////////////////////////////
  937. //初始化本地文件cache
  938. __out__.info() << OUT_LINE << "\n" << TC_Common::outfill("[set file cache ]") << "OK" << endl;
  939. AppCache::getInstance()->setCacheInfo(ServerConfig::DataPath + ServerConfig::ServerName + ".tarsdat", 0);
  940. ///////////////////////////////////////////////////////////////////////////////////////////////////
  941. //初始化本地Log
  942. __out__.info() << OUT_LINE << "\n" << TC_Common::outfill("[set roll logger] ") << "OK" << endl;
  943. LocalRollLogger::getInstance()->setLogInfo(ServerConfig::Application, ServerConfig::ServerName, ServerConfig::LogPath, ServerConfig::LogSize, ServerConfig::LogNum, _communicator, ServerConfig::Log);
  944. _epollServer->setLocalLogger(LocalRollLogger::getInstance()->logger());
  945. //初始化是日志为同步
  946. LocalRollLogger::getInstance()->sync(true);
  947. //设置日志级别
  948. string level = AppCache::getInstance()->get("logLevel");
  949. if(level.empty())
  950. {
  951. level = _conf.get("/tars/application/server<logLevel>","DEBUG");
  952. }
  953. ServerConfig::LogLevel = TC_Common::upper(level);
  954. LocalRollLogger::getInstance()->logger()->setLogLevel(ServerConfig::LogLevel);
  955. ///////////////////////////////////////////////////////////////////////////////////////////////////
  956. //初始化到LogServer代理
  957. __out__.info() << OUT_LINE << "\n" << TC_Common::outfill("[set time logger] ") << "OK" << endl;
  958. bool bLogStatReport = (_conf.get("/tars/application/server<logstatreport>", "0") == "1") ? true : false;
  959. RemoteTimeLogger::getInstance()->setLogInfo(_communicator, ServerConfig::Log, ServerConfig::Application, ServerConfig::ServerName, ServerConfig::LogPath, setDivision(), bLogStatReport);
  960. ///////////////////////////////////////////////////////////////////////////////////////////////////
  961. //初始化到配置中心代理
  962. __out__.info() << OUT_LINE << "\n" << TC_Common::outfill("[set remote config] ") << "OK" << endl;
  963. RemoteConfig::getInstance()->setConfigInfo(_communicator, ServerConfig::Config, ServerConfig::Application, ServerConfig::ServerName, ServerConfig::BasePath,setDivision());
  964. ///////////////////////////////////////////////////////////////////////////////////////////////////
  965. //初始化到信息中心代理
  966. __out__.info() << OUT_LINE << "\n" << TC_Common::outfill("[set remote notify] ") << "OK" << endl;
  967. RemoteNotify::getInstance()->setNotifyInfo(_communicator, ServerConfig::Notify, ServerConfig::Application, ServerConfig::ServerName, setDivision(), ServerConfig::LocalIp);
  968. ///////////////////////////////////////////////////////////////////////////////////////////////////
  969. //初始化到Node的代理
  970. __out__.info() << OUT_LINE << "\n" << TC_Common::outfill("[set node proxy]") << "OK" << endl;
  971. KeepAliveNodeFHelper::getInstance()->setNodeInfo(_communicator, ServerConfig::Node, ServerConfig::Application, ServerConfig::ServerName);
  972. ///////////////////////////////////////////////////////////////////////////////////////////////////
  973. //初始化管理对象
  974. __out__.info() << OUT_LINE << "\n" << TC_Common::outfill("[set admin adapter]") << "OK" << endl;
  975. if (!ServerConfig::Local.empty())
  976. {
  977. _servantHelper->addServant<AdminServant>("AdminObj", this);
  978. string adminAdapter = "AdminAdapter";
  979. _servantHelper->setAdapterServant(adminAdapter, "AdminObj");
  980. TC_EpollServer::BindAdapterPtr lsPtr = _epollServer->createBindAdapter<ServantHandle>(adminAdapter, ServerConfig::Local, 1, this);
  981. setAdapter(lsPtr, adminAdapter);
  982. lsPtr->setMaxConns(TC_EpollServer::BindAdapter::DEFAULT_MAX_CONN);
  983. lsPtr->setQueueCapacity(TC_EpollServer::BindAdapter::DEFAULT_QUEUE_CAP);
  984. lsPtr->setQueueTimeout(TC_EpollServer::BindAdapter::DEFAULT_QUEUE_TIMEOUT);
  985. lsPtr->setProtocolName("tars");
  986. lsPtr->setProtocol(AppProtocol::parse);
  987. _epollServer->bind(lsPtr);
  988. }
  989. //队列取平均值
  990. if(!_communicator->getProperty("property").empty())
  991. {
  992. string sRspQueue("");
  993. sRspQueue += ServerConfig::Application;
  994. sRspQueue += ".";
  995. sRspQueue += ServerConfig::ServerName;
  996. sRspQueue += ".sendrspqueue";
  997. g_pReportRspQueue = _communicator->getStatReport()->createPropertyReport(sRspQueue, PropertyReport::avg());
  998. }
  999. }
  1000. void Application::setAdapter(TC_EpollServer::BindAdapterPtr& adapter, const string &name)
  1001. {
  1002. // 设置该obj的鉴权账号密码,只要一组就够了
  1003. {
  1004. std::string accKey = _conf.get("/tars/application/server/" + name + "<accesskey>");
  1005. std::string secretKey = _conf.get("/tars/application/server/" + name + "<secretkey>");
  1006. //注意这里必须用weak, 否则adapter最终释放不了!
  1007. weak_ptr<TC_EpollServer::BindAdapter> a = adapter;
  1008. adapter->setAkSkCallback(accKey, secretKey, std::bind(&tars::serverVerifyAuthCallback, std::placeholders::_1, std::placeholders::_2, a, _servantHelper->getAdapterServant(name)));
  1009. }
  1010. #if TARS_SSL
  1011. string cert = _conf.get("/tars/application/server/" + name + "<cert>");
  1012. if (!cert.empty())
  1013. {
  1014. string ca = _conf.get("/tars/application/server/" + name + "<ca>");
  1015. string key = _conf.get("/tars/application/server/" + name + "<key>");
  1016. bool verifyClient =
  1017. _conf.get("/tars/application/server/" + name + "<verifyclient>", "0") == "0" ? false : true;
  1018. string ciphers = _conf.get("/tars/application/server/" + name + "<ciphers>");
  1019. shared_ptr<TC_OpenSSL::CTX> ctx = TC_OpenSSL::newCtx(ca, cert, key, verifyClient, ciphers);
  1020. if (!ctx) {
  1021. TLOGERROR("load server ssl error, cert:" << cert << endl);
  1022. exit(-1);
  1023. }
  1024. adapter->setSSLCtx(ctx);
  1025. }
  1026. else
  1027. {
  1028. adapter->setSSLCtx(_ctx);
  1029. }
  1030. #endif
  1031. }
  1032. void Application::bindAdapter(vector<TC_EpollServer::BindAdapterPtr>& adapters)
  1033. {
  1034. string sPrefix = ServerConfig::Application + "." + ServerConfig::ServerName + ".";
  1035. vector<string> adapterName;
  1036. map<string, ServantHandle*> servantHandles;
  1037. if (_conf.getDomainVector("/tars/application/server", adapterName))
  1038. {
  1039. for (size_t i = 0; i < adapterName.size(); i++)
  1040. {
  1041. string servant = _conf.get("/tars/application/server/" + adapterName[i] + "<servant>");
  1042. checkServantNameValid(servant, sPrefix);
  1043. _servantHelper->setAdapterServant(adapterName[i], servant);
  1044. string sLastPath = "/tars/application/server/" + adapterName[i];
  1045. TC_Endpoint ep;
  1046. ep.parse(_conf[sLastPath + "<endpoint>"]);
  1047. if (ep.getHost() == "localip")
  1048. {
  1049. ep.setHost(ServerConfig::LocalIp);
  1050. }
  1051. TC_EpollServer::BindAdapterPtr bindAdapter = _epollServer->createBindAdapter<ServantHandle>(adapterName[i], _conf[sLastPath + "<endpoint>"], TC_Common::strto<int>(_conf.get(sLastPath + "<threads>", "1")), this);
  1052. //init auth & ssl
  1053. setAdapter(bindAdapter, adapterName[i]);
  1054. bindAdapter->setMaxConns(TC_Common::strto<int>(_conf.get(sLastPath + "<maxconns>", "128")));
  1055. bindAdapter->setOrder(parseOrder(_conf.get(sLastPath + "<order>", "allow,deny")));
  1056. bindAdapter->setAllow(TC_Common::sepstr<string>(_conf[sLastPath + "<allow>"], ";,", false));
  1057. bindAdapter->setDeny(TC_Common::sepstr<string>(_conf.get(sLastPath + "<deny>", ""), ";,", false));
  1058. bindAdapter->setQueueCapacity(TC_Common::strto<int>(_conf.get(sLastPath + "<queuecap>", "1024")));
  1059. bindAdapter->setQueueTimeout(TC_Common::strto<int>(_conf.get(sLastPath + "<queuetimeout>", "10000")));
  1060. bindAdapter->setProtocolName(_conf.get(sLastPath + "<protocol>", "tars"));
  1061. bindAdapter->setBackPacketBuffLimit(ServerConfig::BackPacketLimit);
  1062. bindAdapter->setBackPacketBuffMin(ServerConfig::BackPacketMin);
  1063. if (bindAdapter->isTarsProtocol())
  1064. {
  1065. bindAdapter->setProtocol(AppProtocol::parse);
  1066. }
  1067. //校验ssl正常初始化
  1068. #if TARS_SSL
  1069. if (bindAdapter->getEndpoint().isSSL() && (!(bindAdapter->getSSLCtx())))
  1070. {
  1071. __out__.error() << "load server ssl error, no cert config!" << bindAdapter->getEndpoint().toString() << endl;
  1072. exit(-1);
  1073. }
  1074. #endif
  1075. if(ServerConfig::ManualListen) {
  1076. //手工监听
  1077. bindAdapter->enableManualListen();
  1078. }
  1079. _epollServer->bind(bindAdapter);
  1080. adapters.push_back(bindAdapter);
  1081. //队列取平均值
  1082. if(!_communicator->getProperty("property").empty())
  1083. {
  1084. PropertyReportPtr p;
  1085. p = _communicator->getStatReport()->createPropertyReport(bindAdapter->getName() + ".queue", PropertyReport::avg());
  1086. bindAdapter->_pReportQueue = p.get();
  1087. p = _communicator->getStatReport()->createPropertyReport(bindAdapter->getName() + ".connectRate", PropertyReport::avg());
  1088. bindAdapter->_pReportConRate = p.get();
  1089. p = _communicator->getStatReport()->createPropertyReport(bindAdapter->getName() + ".timeoutNum", PropertyReport::sum());
  1090. bindAdapter->_pReportTimeoutNum = p.get();
  1091. }
  1092. }
  1093. }
  1094. }
  1095. void Application::checkServantNameValid(const string& servant, const string& sPrefix)
  1096. {
  1097. if ((servant.length() <= sPrefix.length()) || (servant.substr(0, sPrefix.length()) != sPrefix))
  1098. {
  1099. ostringstream os;
  1100. os << "Servant '" << servant << "' error: must be start with '" << sPrefix << "'";
  1101. NOTIFY_AND_WAIT("exit: " + string(os.str()));
  1102. __out__.error() << os.str() << endl;
  1103. exit(-1);
  1104. }
  1105. }
  1106. void Application::outAdapter(ostream &os, const string &v, TC_EpollServer::BindAdapterPtr lsPtr)
  1107. {
  1108. os << TC_Common::outfill("name") << lsPtr->getName() << endl;
  1109. os << TC_Common::outfill("servant") << v << endl;
  1110. os << TC_Common::outfill("endpoint") << lsPtr->getEndpoint().toString() << endl;
  1111. os << TC_Common::outfill("maxconns") << lsPtr->getMaxConns() << endl;
  1112. os << TC_Common::outfill("queuecap") << lsPtr->getQueueCapacity() << endl;
  1113. os << TC_Common::outfill("queuetimeout") << lsPtr->getQueueTimeout() << "ms" << endl;
  1114. os << TC_Common::outfill("order") << (lsPtr->getOrder() == TC_EpollServer::BindAdapter::ALLOW_DENY ? "allow,deny" : "deny,allow") << endl;
  1115. os << TC_Common::outfill("allow") << TC_Common::tostr(lsPtr->getAllow()) << endl;
  1116. os << TC_Common::outfill("deny") << TC_Common::tostr(lsPtr->getDeny()) << endl;
  1117. // os << outfill("queuesize") << lsPtr->getRecvBufferSize() << endl;
  1118. os << TC_Common::outfill("connections") << lsPtr->getNowConnection() << endl;
  1119. os << TC_Common::outfill("protocol") << lsPtr->getProtocolName() << endl;
  1120. os << TC_Common::outfill("handlethread") << lsPtr->getHandleNum() << endl;
  1121. }
  1122. //////////////////////////////////////////////////////////////////////////////////////////////////
  1123. }