Application.cpp 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463
  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("[adapter:" + 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. __out__.modFlag(0xFFFF, false);
  560. //解析配置文件
  561. parseConfig(config);
  562. //初始化Proxy部分
  563. initializeClient();
  564. //初始化Server部分
  565. initializeServer();
  566. vector <TC_EpollServer::BindAdapterPtr> adapters;
  567. //绑定对象和端口
  568. bindAdapter(adapters);
  569. stringstream os;
  570. //输出所有adapter
  571. outAllAdapter(os);
  572. __out__.info() << os.str();
  573. __out__.info() << "\n" << TC_Common::outfill("[initialize server] ", '.') << " [Done]" << endl;
  574. __out__.info() << OUT_LINE_LONG << endl;
  575. {
  576. bool initing = true;
  577. std::mutex mtx;
  578. std::condition_variable cond;
  579. std::thread keepActiving([&]
  580. {
  581. do
  582. {
  583. //发送心跳给node, 表示正在启动
  584. TARS_KEEPACTIVING;
  585. //等待initialize初始化完毕
  586. std::unique_lock<std::mutex> lock(mtx);
  587. cond.wait_for(lock, std::chrono::seconds(5), [&](){
  588. return !initing;
  589. });
  590. }while(initing);
  591. });
  592. try
  593. {
  594. //业务应用的初始化
  595. initialize();
  596. {
  597. std::unique_lock<std::mutex> lock(mtx);
  598. initing = false;
  599. cond.notify_all();
  600. }
  601. keepActiving.join();
  602. }
  603. catch (exception & ex)
  604. {
  605. keepActiving.detach();
  606. NOTIFY_AND_WAIT("exit: " + string(ex.what()));
  607. __out__.error() << "[init exception]:" << ex.what() << endl;
  608. exit(-1);
  609. }
  610. }
  611. //动态加载配置文件
  612. TARS_ADD_ADMIN_CMD_PREFIX(TARS_CMD_LOAD_CONFIG, Application::cmdLoadConfig);
  613. //动态设置滚动日志等级
  614. TARS_ADD_ADMIN_CMD_PREFIX(TARS_CMD_SET_LOG_LEVEL, Application::cmdSetLogLevel);
  615. //动态设置按天日志等级
  616. TARS_ADD_ADMIN_CMD_PREFIX(TARS_CMD_SET_DAYLOG_LEVEL, Application::cmdEnableDayLog);
  617. //查看服务状态
  618. TARS_ADD_ADMIN_CMD_PREFIX(TARS_CMD_VIEW_STATUS, Application::cmdViewStatus);
  619. //查看当前链接状态
  620. TARS_ADD_ADMIN_CMD_PREFIX(TARS_CMD_CONNECTIONS, Application::cmdConnections);
  621. //查看编译的TARS版本
  622. TARS_ADD_ADMIN_CMD_PREFIX(TARS_CMD_VIEW_VERSION, Application::cmdViewVersion);
  623. //查看服务buildid(编译时间)
  624. TARS_ADD_ADMIN_CMD_PREFIX(TARS_CMD_VIEW_BID, Application::cmdViewBuildID);
  625. //加载配置文件中的属性信息
  626. TARS_ADD_ADMIN_CMD_PREFIX(TARS_CMD_LOAD_PROPERTY, Application::cmdLoadProperty);
  627. //查看服务支持的管理命令
  628. TARS_ADD_ADMIN_CMD_PREFIX(TARS_CMD_VIEW_ADMIN_COMMANDS, Application::cmdViewAdminCommands);
  629. //设置染色信息
  630. TARS_ADD_ADMIN_CMD_PREFIX(TARS_CMD_SET_DYEING, Application::cmdSetDyeing);
  631. //设置服务的core limit
  632. TARS_ADD_ADMIN_CMD_PREFIX(TARS_CMD_CLOSE_CORE, Application::cmdCloseCoreDump);
  633. //设置是否标准输出
  634. TARS_ADD_ADMIN_CMD_PREFIX(TARS_CMD_CLOSE_COUT, Application::cmdCloseCout);
  635. //设置是否标准输出
  636. TARS_ADD_ADMIN_CMD_PREFIX(TARS_CMD_RELOAD_LOCATOR, Application::cmdReloadLocator);
  637. //设置是否标准输出
  638. TARS_ADD_ADMIN_CMD_PREFIX(TARS_CMD_RESOURCE, Application::cmdViewResource);
  639. //上报版本
  640. TARS_REPORTVERSION(TARS_VERSION);
  641. //发送心跳给node, 表示启动了
  642. TARS_KEEPALIVE("");
  643. //发送给notify表示服务启动了
  644. RemoteNotify::getInstance()->report("restart");
  645. //ctrl + c能够完美结束服务
  646. _ctrlCId = TC_Port::registerCtrlC([=]{
  647. this->terminate();
  648. #if TARGET_PLATFORM_WINDOWS
  649. ExitProcess(0);
  650. #endif
  651. });
  652. _termId = TC_Port::registerTerm([=]{
  653. this->terminate();
  654. #if TARGET_PLATFORM_WINDOWS
  655. ExitProcess(0);
  656. #endif
  657. });
  658. #if TARGET_PLATFORM_LINUX || TARGET_PLATFORM_IOS
  659. if(_conf.get("/tars/application/server<closecout>",AppCache::getInstance()->get("closeCout")) != "0")
  660. {
  661. // 重定向stdin、stdout、stderr
  662. int fd = open("/dev/null", O_RDWR );
  663. if (fd != -1)
  664. {
  665. dup2(fd, 0);
  666. dup2(fd, 1);
  667. dup2(fd, 2);
  668. }
  669. else
  670. {
  671. close(0);
  672. close(1);
  673. close(2);
  674. }
  675. }
  676. #endif
  677. }
  678. catch (exception &ex)
  679. {
  680. __out__.error() << "[Application]:" << ex.what() << endl;
  681. terminate();
  682. NOTIFY_AND_WAIT("exit: " + string(ex.what()));
  683. exit(-1);
  684. }
  685. //初始化完毕后, 日志再修改为异步
  686. LocalRollLogger::getInstance()->sync(false);
  687. }
  688. void Application::parseConfig(const string &config)
  689. {
  690. _conf.parseString(config);
  691. __out__.setLogLevel(_conf.get("/tars/application/server<start_output>", "DEBUG"));
  692. onParseConfig(_conf);
  693. }
  694. TC_EpollServer::BindAdapter::EOrder Application::parseOrder(const string &s)
  695. {
  696. vector<string> vtOrder = TC_Common::sepstr<string>(s, ";, \t", false);
  697. if (vtOrder.size() != 2)
  698. {
  699. cerr << "invalid order '" << TC_Common::tostr(vtOrder) << "'." << endl;
  700. exit(0);
  701. }
  702. if ((TC_Common::lower(vtOrder[0]) == "allow") && (TC_Common::lower(vtOrder[1]) == "deny"))
  703. {
  704. return TC_EpollServer::BindAdapter::ALLOW_DENY;
  705. }
  706. if ((TC_Common::lower(vtOrder[0]) == "deny") && (TC_Common::lower(vtOrder[1]) == "allow"))
  707. {
  708. return TC_EpollServer::BindAdapter::DENY_ALLOW;
  709. }
  710. cerr << "invalid order '" << TC_Common::tostr(vtOrder) << "'." << endl;
  711. exit(0);
  712. }
  713. void Application::initializeClient()
  714. {
  715. __out__.info() << "\n" << OUT_LINE_LONG << endl;
  716. //初始化通信器
  717. _communicator = CommunicatorFactory::getInstance()->getCommunicator(_conf);
  718. __out__.info() << TC_Common::outfill("[proxy config]:") << endl;
  719. //输出
  720. stringstream os;
  721. outClient(os);
  722. __out__.info() << os.str();
  723. }
  724. void Application::outClient(ostream &os)
  725. {
  726. os << OUT_LINE << "\n" << TC_Common::outfill("[load client]:") << endl;
  727. os << TC_Common::outfill("locator") << _communicator->getProperty("locator") << endl;
  728. os << TC_Common::outfill("sync-invoke-timeout") << _communicator->getProperty("sync-invoke-timeout") << endl;
  729. os << TC_Common::outfill("async-invoke-timeout") << _communicator->getProperty("async-invoke-timeout") << endl;
  730. os << TC_Common::outfill("refresh-endpoint-interval") << _communicator->getProperty("refresh-endpoint-interval") << endl;
  731. os << TC_Common::outfill("stat") << _communicator->getProperty("stat") << endl;
  732. os << TC_Common::outfill("property") << _communicator->getProperty("property") << endl;
  733. os << TC_Common::outfill("report-interval") << _communicator->getProperty("report-interval") << endl;
  734. // os << TC_Common::outfill("sample-rate") << _communicator->getProperty("sample-rate") << endl;
  735. // os << TC_Common::outfill("max-sample-count") << _communicator->getProperty("max-sample-count") << endl;
  736. os << TC_Common::outfill("netthread") << _communicator->getProperty("netthread") << endl;
  737. os << TC_Common::outfill("asyncthread") << _communicator->getProperty("asyncthread") << endl;
  738. os << TC_Common::outfill("modulename") << _communicator->getProperty("modulename") << endl;
  739. os << TC_Common::outfill("enableset") << _communicator->getProperty("enableset") << endl;
  740. os << TC_Common::outfill("setdivision") << _communicator->getProperty("setdivision") << endl;
  741. }
  742. string Application::toDefault(const string &s, const string &sDefault)
  743. {
  744. if (s.empty())
  745. {
  746. return sDefault;
  747. }
  748. return s;
  749. }
  750. string Application::setDivision()
  751. {
  752. bool bEnableSet = TC_Common::lower(_conf.get("/tars/application<enableset>", "n"))=="y"?true:false;;
  753. string sSetDevision = bEnableSet?_conf.get("/tars/application<setdivision>", ""):"";
  754. return sSetDevision;
  755. }
  756. void Application::addServantProtocol(const string& servant, const TC_NetWorkBuffer::protocol_functor& protocol)
  757. {
  758. string adapterName = _servantHelper->getServantAdapter(servant);
  759. if (adapterName == "")
  760. {
  761. throw runtime_error("addServantProtocol fail, no found adapter for servant:" + servant);
  762. }
  763. getEpollServer()->getBindAdapter(adapterName)->setProtocol(protocol);
  764. }
  765. void Application::addAcceptCallback(const TC_EpollServer::accept_callback_functor& cb)
  766. {
  767. _acceptFuncs.push_back(cb);
  768. }
  769. void Application::onAccept(TC_EpollServer::Connection* cPtr)
  770. {
  771. for (size_t i = 0; i < _acceptFuncs.size(); ++i)
  772. {
  773. _acceptFuncs[i](cPtr);
  774. }
  775. }
  776. //void Application::addServantOnClose(const string& servant, const TC_EpollServer::close_functor& cf)
  777. //{
  778. // string adapterName = _servantHelper->getServantAdapter(servant);
  779. //
  780. // if (adapterName.empty())
  781. // {
  782. // throw runtime_error("setServantOnClose fail, no found adapter for servant:" + servant);
  783. // }
  784. //
  785. // getEpollServer()->getBindAdapter(adapterName)->setOnClose(cf);
  786. //}
  787. void Application::outServer(ostream &os)
  788. {
  789. os << TC_Common::outfill("Application(app)") << ServerConfig::Application << endl;
  790. os << TC_Common::outfill("ServerName(server)") << ServerConfig::ServerName << endl;
  791. os << TC_Common::outfill("BasePath(basepath)") << ServerConfig::BasePath << endl;
  792. os << TC_Common::outfill("DataPath(datapath)") << ServerConfig::DataPath << endl;
  793. os << TC_Common::outfill("LocalIp(localip)") << ServerConfig::LocalIp << endl;
  794. os << TC_Common::outfill("Local(local)") << ServerConfig::Local << endl;
  795. os << TC_Common::outfill("LogPath(logpath)") << ServerConfig::LogPath << endl;
  796. os << TC_Common::outfill("LogSize(logsize)") << ServerConfig::LogSize << endl;
  797. os << TC_Common::outfill("LogNum(lognum)") << ServerConfig::LogNum << endl;
  798. os << TC_Common::outfill("LogLevel(loglevel)") << ServerConfig::LogLevel << endl;
  799. os << TC_Common::outfill("Log(log)") << ServerConfig::Log << endl;
  800. os << TC_Common::outfill("Node(node)") << ServerConfig::Node << endl;
  801. os << TC_Common::outfill("Config(config)") << ServerConfig::Config << endl;
  802. os << TC_Common::outfill("Notify(notify)") << ServerConfig::Notify << endl;
  803. os << TC_Common::outfill("OpenCoroutine(opencoroutine)") << ServerConfig::OpenCoroutine << endl;
  804. os << TC_Common::outfill("CoroutineMemSize(coroutinememsize)") << ServerConfig::CoroutineMemSize << endl;
  805. os << TC_Common::outfill("CoroutineStackSize(coroutinestack)") << ServerConfig::CoroutineStackSize << endl;
  806. os << TC_Common::outfill("CloseCout(closecout)") << ServerConfig::CloseCout << endl;
  807. os << TC_Common::outfill("NetThread(netthread)") << ServerConfig::NetThread << endl;
  808. os << TC_Common::outfill("ManualListen(manuallisten)") << ServerConfig::ManualListen << endl;
  809. // os << TC_Common::outfill("MergeNetImp(mergenetimp)") << ServerConfig::MergeNetImp << endl;
  810. os << TC_Common::outfill("ReportFlow(reportflow)") << ServerConfig::ReportFlow<< endl;
  811. os << TC_Common::outfill("BackPacketLimit(backpacketlimit)") << ServerConfig::BackPacketLimit<< endl;
  812. os << TC_Common::outfill("BackPacketMin(backpacketmin)") << ServerConfig::BackPacketMin<< endl;
  813. #if TARS_SSL
  814. os << TC_Common::outfill("Ca(ca)") << ServerConfig::CA << endl;
  815. os << TC_Common::outfill("Cert(cert)") << ServerConfig::Cert << endl;
  816. os << TC_Common::outfill("Key(key)") << ServerConfig::Key << endl;
  817. os << TC_Common::outfill("VerifyClient(verifyclient)") << ServerConfig::VerifyClient << endl;
  818. os << TC_Common::outfill("Ciphers(ciphers)") << ServerConfig::Ciphers << endl;
  819. #endif
  820. }
  821. void Application::initializeServer()
  822. {
  823. __out__.info() << OUT_LINE << "\n" << TC_Common::outfill("[server config]:") << endl;
  824. ServerConfig::Application = toDefault(_conf.get("/tars/application/server<app>"), "UNKNOWN");
  825. //缺省采用进程名称
  826. string exe = "";
  827. try
  828. {
  829. exe = TC_File::extractFileName(TC_File::getExePath());
  830. }
  831. catch (TC_File_Exception & ex)
  832. {
  833. //取失败则使用ip代替进程名
  834. exe = _conf.get("/tars/application/server<localip>");
  835. }
  836. ServerConfig::ServerName = toDefault(_conf.get("/tars/application/server<server>"), exe);
  837. #if TARGET_PLATFORM_WINDOWS
  838. ServerConfig::BasePath = TC_File::simplifyDirectory(_conf.get("/tars/application/server<basepath.win>")) + FILE_SEP;
  839. if (ServerConfig::BasePath == FILE_SEP)
  840. {
  841. ServerConfig::BasePath = TC_File::simplifyDirectory(toDefault(_conf.get("/tars/application/server<basepath>"), ".")) + FILE_SEP;
  842. }
  843. ServerConfig::DataPath = TC_File::simplifyDirectory(_conf.get("/tars/application/server<datapath.win>")) + FILE_SEP;
  844. if(ServerConfig::DataPath == FILE_SEP)
  845. {
  846. ServerConfig::DataPath = TC_File::simplifyDirectory(toDefault(_conf.get("/tars/application/server<datapath>"), ".")) + FILE_SEP;
  847. }
  848. ServerConfig::LogPath = TC_File::simplifyDirectory(_conf.get("/tars/application/server<logpath.win>")) + FILE_SEP;
  849. if(ServerConfig::LogPath == FILE_SEP)
  850. {
  851. ServerConfig::LogPath = TC_File::simplifyDirectory(toDefault(_conf.get("/tars/application/server<logpath>"), ".")) + FILE_SEP;
  852. }
  853. #else
  854. ServerConfig::BasePath = TC_File::simplifyDirectory(toDefault(_conf.get("/tars/application/server<basepath>"), ".")) + FILE_SEP;
  855. ServerConfig::DataPath = TC_File::simplifyDirectory(toDefault(_conf.get("/tars/application/server<datapath>"), ".")) + FILE_SEP;
  856. ServerConfig::LogPath = TC_File::simplifyDirectory(toDefault(_conf.get("/tars/application/server<logpath>"), ".")) + FILE_SEP;
  857. #endif
  858. ServerConfig::TarsPath = TC_File::simplifyDirectory(ServerConfig::LogPath + FILE_SEP + ".." + FILE_SEP) + FILE_SEP;
  859. ServerConfig::LogSize = TC_Common::toSize(toDefault(_conf.get("/tars/application/server<logsize>"), "52428800"), 52428800);
  860. ServerConfig::LogNum = TC_Common::strto<int>(toDefault(_conf.get("/tars/application/server<lognum>"), "10"));
  861. ServerConfig::LocalIp = _conf.get("/tars/application/server<localip>");
  862. ServerConfig::Local = _conf.get("/tars/application/server<local>");
  863. ServerConfig::Node = _conf.get("/tars/application/server<node>");
  864. ServerConfig::Log = _conf.get("/tars/application/server<log>");
  865. ServerConfig::Config = _conf.get("/tars/application/server<config>");
  866. ServerConfig::Notify = _conf.get("/tars/application/server<notify>");
  867. ServerConfig::ReportFlow = _conf.get("/tars/application/server<reportflow>")=="0"?0:1;
  868. ServerConfig::IsCheckSet = _conf.get("/tars/application/server<checkset>","1")=="0"?0:1;
  869. ServerConfig::OpenCoroutine = TC_Common::strto<int>(toDefault(_conf.get("/tars/application/server<opencoroutine>"), "0"));
  870. ServerConfig::CoroutineMemSize = TC_Common::toSize(toDefault(_conf.get("/tars/application/server<coroutinememsize>"), "1G"), 1024*1024*1024);
  871. ServerConfig::CoroutineStackSize= (uint32_t)TC_Common::toSize(toDefault(_conf.get("/tars/application/server<coroutinestack>"), "128K"), 1024*128);
  872. ServerConfig::ManualListen = _conf.get("/tars/application/server<manuallisten>", "0") == "0" ? false : true;
  873. // ServerConfig::MergeNetImp = _conf.get("/tars/application/server<mergenetimp>", "0") == "0" ? false : true;
  874. ServerConfig::NetThread = TC_Common::strto<int>(toDefault(_conf.get("/tars/application/server<netthread>"), "1"));
  875. ServerConfig::CloseCout = _conf.get("/tars/application/server<closecout>","1")=="0"?0:1;
  876. ServerConfig::BackPacketLimit = TC_Common::strto<int>(_conf.get("/tars/application/server<backpacketlimit>", "100*1024*1024"));
  877. ServerConfig::BackPacketMin = TC_Common::strto<int>(_conf.get("/tars/application/server<backpacketmin>", "1024"));
  878. ServerConfig::Context["node_name"] = ServerConfig::LocalIp;
  879. #if TARS_SSL
  880. ServerConfig::CA = _conf.get("/tars/application/server<ca>");
  881. ServerConfig::Cert = _conf.get("/tars/application/server<cert>");
  882. ServerConfig::Key = _conf.get("/tars/application/server<key>");
  883. ServerConfig::VerifyClient = _conf.get("/tars/application/server<verifyclient>","0")=="0"?false:true;
  884. ServerConfig::Ciphers = _conf.get("/tars/application/server<ciphers>");
  885. if(!ServerConfig::Cert.empty()) {
  886. _ctx = TC_OpenSSL::newCtx(ServerConfig::CA, ServerConfig::Cert, ServerConfig::Key, ServerConfig::VerifyClient, ServerConfig::Ciphers);
  887. if (!_ctx) {
  888. TLOGERROR("[load server ssl error, ca:" << ServerConfig::CA << endl);
  889. exit(-1);
  890. }
  891. }
  892. #endif
  893. if (ServerConfig::LocalIp.empty())
  894. {
  895. // ServerConfig::LocalIp = "127.0.0.1";
  896. vector<string> v = TC_Socket::getLocalHosts();
  897. ServerConfig::LocalIp = "127.0.0.1";
  898. //获取第一个非127.0.0.1的IP
  899. for(size_t i = 0; i < v.size(); i++)
  900. {
  901. if(v[i] != "127.0.0.1")
  902. {
  903. ServerConfig::LocalIp = v[i];
  904. break;
  905. }
  906. }
  907. }
  908. onServerConfig();
  909. ostringstream os;
  910. //输出信息
  911. outServer(os);
  912. __out__.info() << os.str();
  913. if (ServerConfig::NetThread < 1)
  914. {
  915. ServerConfig::NetThread = 1;
  916. __out__.info() << OUT_LINE << "\nwarning:netThreadNum < 1." << endl;
  917. }
  918. //网络线程的配置数目不能15个
  919. if (ServerConfig::NetThread > 15)
  920. {
  921. ServerConfig::NetThread = 15;
  922. __out__.info() << OUT_LINE << "\nwarning:netThreadNum > 15." << endl;
  923. }
  924. if(ServerConfig::CoroutineMemSize/ServerConfig::CoroutineStackSize <= 0)
  925. {
  926. __out__.error() << OUT_LINE << "\nerror:coroutine paramter error: coroutinememsize/coroutinestack <= 0!." << endl;
  927. exit(-1);
  928. }
  929. _epollServer = new TC_EpollServer();
  930. _epollServer->setThreadNum(ServerConfig::NetThread);
  931. _epollServer->setOpenCoroutine((TC_EpollServer::SERVER_OPEN_COROUTINE)ServerConfig::OpenCoroutine);
  932. _epollServer->setCoroutineStack(ServerConfig::CoroutineMemSize/ServerConfig::CoroutineStackSize, ServerConfig::CoroutineStackSize);
  933. _epollServer->setOnAccept(std::bind(&Application::onAccept, this, std::placeholders::_1));
  934. //初始化服务是否对空链接进行超时检查
  935. // bool bEnable = (_conf.get("/tars/application/server<emptyconcheck>","0")=="1")?true:false;
  936. // _epollServer->enAntiEmptyConnAttack(bEnable);
  937. _epollServer->setEmptyConnTimeout(TC_Common::strto<int>(toDefault(_conf.get("/tars/application/server<emptyconntimeout>"), "0")));
  938. ///////////////////////////////////////////////////////////////////////////////////////////////////
  939. //初始化本地文件cache
  940. __out__.info() << OUT_LINE << "\n" << TC_Common::outfill("[set file cache ]") << "OK" << endl;
  941. AppCache::getInstance()->setCacheInfo(ServerConfig::DataPath + ServerConfig::ServerName + ".tarsdat", 0);
  942. ///////////////////////////////////////////////////////////////////////////////////////////////////
  943. //初始化本地Log
  944. __out__.info() << OUT_LINE << "\n" << TC_Common::outfill("[set roll logger] ") << "OK" << endl;
  945. LocalRollLogger::getInstance()->setLogInfo(ServerConfig::Application, ServerConfig::ServerName, ServerConfig::LogPath, ServerConfig::LogSize, ServerConfig::LogNum, _communicator, ServerConfig::Log);
  946. _epollServer->setLocalLogger(LocalRollLogger::getInstance()->logger());
  947. //初始化是日志为同步
  948. LocalRollLogger::getInstance()->sync(true);
  949. //设置日志级别
  950. string level = AppCache::getInstance()->get("logLevel");
  951. if(level.empty())
  952. {
  953. level = _conf.get("/tars/application/server<logLevel>","DEBUG");
  954. }
  955. ServerConfig::LogLevel = TC_Common::upper(level);
  956. LocalRollLogger::getInstance()->logger()->setLogLevel(ServerConfig::LogLevel);
  957. ///////////////////////////////////////////////////////////////////////////////////////////////////
  958. //初始化到LogServer代理
  959. __out__.info() << OUT_LINE << "\n" << TC_Common::outfill("[set time logger] ") << "OK" << endl;
  960. bool bLogStatReport = (_conf.get("/tars/application/server<logstatreport>", "0") == "1") ? true : false;
  961. RemoteTimeLogger::getInstance()->setLogInfo(_communicator, ServerConfig::Log, ServerConfig::Application, ServerConfig::ServerName, ServerConfig::LogPath, setDivision(), bLogStatReport);
  962. ///////////////////////////////////////////////////////////////////////////////////////////////////
  963. //初始化到配置中心代理
  964. __out__.info() << OUT_LINE << "\n" << TC_Common::outfill("[set remote config] ") << "OK" << endl;
  965. RemoteConfig::getInstance()->setConfigInfo(_communicator, ServerConfig::Config, ServerConfig::Application, ServerConfig::ServerName, ServerConfig::BasePath,setDivision());
  966. ///////////////////////////////////////////////////////////////////////////////////////////////////
  967. //初始化到信息中心代理
  968. __out__.info() << OUT_LINE << "\n" << TC_Common::outfill("[set remote notify] ") << "OK" << endl;
  969. RemoteNotify::getInstance()->setNotifyInfo(_communicator, ServerConfig::Notify, ServerConfig::Application, ServerConfig::ServerName, setDivision(), ServerConfig::LocalIp);
  970. ///////////////////////////////////////////////////////////////////////////////////////////////////
  971. //初始化到Node的代理
  972. __out__.info() << OUT_LINE << "\n" << TC_Common::outfill("[set node proxy]") << "OK" << endl;
  973. KeepAliveNodeFHelper::getInstance()->setNodeInfo(_communicator, ServerConfig::Node, ServerConfig::Application, ServerConfig::ServerName);
  974. ///////////////////////////////////////////////////////////////////////////////////////////////////
  975. //初始化管理对象
  976. __out__.info() << OUT_LINE << "\n" << TC_Common::outfill("[set admin adapter]") << "OK" << endl;
  977. if (!ServerConfig::Local.empty())
  978. {
  979. _servantHelper->addServant<AdminServant>("AdminObj", this);
  980. string adminAdapter = "AdminAdapter";
  981. _servantHelper->setAdapterServant(adminAdapter, "AdminObj");
  982. TC_EpollServer::BindAdapterPtr lsPtr = _epollServer->createBindAdapter<ServantHandle>(adminAdapter, ServerConfig::Local, 1, this);
  983. setAdapter(lsPtr, adminAdapter);
  984. lsPtr->setMaxConns(TC_EpollServer::BindAdapter::DEFAULT_MAX_CONN);
  985. lsPtr->setQueueCapacity(TC_EpollServer::BindAdapter::DEFAULT_QUEUE_CAP);
  986. lsPtr->setQueueTimeout(TC_EpollServer::BindAdapter::DEFAULT_QUEUE_TIMEOUT);
  987. lsPtr->setProtocolName("tars");
  988. lsPtr->setProtocol(AppProtocol::parse);
  989. _epollServer->bind(lsPtr);
  990. }
  991. //队列取平均值
  992. if(!_communicator->getProperty("property").empty())
  993. {
  994. string sRspQueue("");
  995. sRspQueue += ServerConfig::Application;
  996. sRspQueue += ".";
  997. sRspQueue += ServerConfig::ServerName;
  998. sRspQueue += ".sendrspqueue";
  999. g_pReportRspQueue = _communicator->getStatReport()->createPropertyReport(sRspQueue, PropertyReport::avg());
  1000. }
  1001. TarsTimeLogger::getInstance()->enableLocal(TRACE_LOG_FILENAME, false);
  1002. }
  1003. void Application::setAdapter(TC_EpollServer::BindAdapterPtr& adapter, const string &name)
  1004. {
  1005. // 设置该obj的鉴权账号密码,只要一组就够了
  1006. {
  1007. std::string accKey = _conf.get("/tars/application/server/" + name + "<accesskey>");
  1008. std::string secretKey = _conf.get("/tars/application/server/" + name + "<secretkey>");
  1009. //注意这里必须用weak, 否则adapter最终释放不了!
  1010. weak_ptr<TC_EpollServer::BindAdapter> a = adapter;
  1011. adapter->setAkSkCallback(accKey, secretKey, std::bind(&tars::serverVerifyAuthCallback, std::placeholders::_1, std::placeholders::_2, a, _servantHelper->getAdapterServant(name)));
  1012. }
  1013. #if TARS_SSL
  1014. string cert = _conf.get("/tars/application/server/" + name + "<cert>");
  1015. if (!cert.empty())
  1016. {
  1017. string ca = _conf.get("/tars/application/server/" + name + "<ca>");
  1018. string key = _conf.get("/tars/application/server/" + name + "<key>");
  1019. bool verifyClient =
  1020. _conf.get("/tars/application/server/" + name + "<verifyclient>", "0") == "0" ? false : true;
  1021. string ciphers = _conf.get("/tars/application/server/" + name + "<ciphers>");
  1022. shared_ptr<TC_OpenSSL::CTX> ctx = TC_OpenSSL::newCtx(ca, cert, key, verifyClient, ciphers);
  1023. if (!ctx) {
  1024. TLOGERROR("load server ssl error, cert:" << cert << endl);
  1025. exit(-1);
  1026. }
  1027. adapter->setSSLCtx(ctx);
  1028. }
  1029. else
  1030. {
  1031. adapter->setSSLCtx(_ctx);
  1032. }
  1033. #endif
  1034. }
  1035. void Application::bindAdapter(vector<TC_EpollServer::BindAdapterPtr>& adapters)
  1036. {
  1037. string sPrefix = ServerConfig::Application + "." + ServerConfig::ServerName + ".";
  1038. vector<string> adapterName;
  1039. map<string, ServantHandle*> servantHandles;
  1040. if (_conf.getDomainVector("/tars/application/server", adapterName))
  1041. {
  1042. for (size_t i = 0; i < adapterName.size(); i++)
  1043. {
  1044. string servant = _conf.get("/tars/application/server/" + adapterName[i] + "<servant>");
  1045. checkServantNameValid(servant, sPrefix);
  1046. _servantHelper->setAdapterServant(adapterName[i], servant);
  1047. string sLastPath = "/tars/application/server/" + adapterName[i];
  1048. TC_Endpoint ep;
  1049. ep.parse(_conf[sLastPath + "<endpoint>"]);
  1050. if (ep.getHost() == "localip")
  1051. {
  1052. ep.setHost(ServerConfig::LocalIp);
  1053. }
  1054. TC_EpollServer::BindAdapterPtr bindAdapter = _epollServer->createBindAdapter<ServantHandle>(adapterName[i], _conf[sLastPath + "<endpoint>"], TC_Common::strto<int>(_conf.get(sLastPath + "<threads>", "1")), this);
  1055. //init auth & ssl
  1056. setAdapter(bindAdapter, adapterName[i]);
  1057. bindAdapter->setMaxConns(TC_Common::strto<int>(_conf.get(sLastPath + "<maxconns>", "128")));
  1058. bindAdapter->setOrder(parseOrder(_conf.get(sLastPath + "<order>", "allow,deny")));
  1059. bindAdapter->setAllow(TC_Common::sepstr<string>(_conf[sLastPath + "<allow>"], ";,", false));
  1060. bindAdapter->setDeny(TC_Common::sepstr<string>(_conf.get(sLastPath + "<deny>", ""), ";,", false));
  1061. bindAdapter->setQueueCapacity(TC_Common::strto<int>(_conf.get(sLastPath + "<queuecap>", "1024")));
  1062. bindAdapter->setQueueTimeout(TC_Common::strto<int>(_conf.get(sLastPath + "<queuetimeout>", "10000")));
  1063. bindAdapter->setProtocolName(_conf.get(sLastPath + "<protocol>", "tars"));
  1064. bindAdapter->setBackPacketBuffLimit(ServerConfig::BackPacketLimit);
  1065. bindAdapter->setBackPacketBuffMin(ServerConfig::BackPacketMin);
  1066. if (bindAdapter->isTarsProtocol())
  1067. {
  1068. bindAdapter->setProtocol(AppProtocol::parse);
  1069. }
  1070. //校验ssl正常初始化
  1071. #if TARS_SSL
  1072. if (bindAdapter->getEndpoint().isSSL() && (!(bindAdapter->getSSLCtx())))
  1073. {
  1074. __out__.error() << "load server ssl error, no cert config!" << bindAdapter->getEndpoint().toString() << endl;
  1075. exit(-1);
  1076. }
  1077. #endif
  1078. if(ServerConfig::ManualListen) {
  1079. //手工监听
  1080. bindAdapter->enableManualListen();
  1081. }
  1082. _epollServer->bind(bindAdapter);
  1083. adapters.push_back(bindAdapter);
  1084. //队列取平均值
  1085. if(!_communicator->getProperty("property").empty())
  1086. {
  1087. PropertyReportPtr p;
  1088. p = _communicator->getStatReport()->createPropertyReport(bindAdapter->getName() + ".queue", PropertyReport::avg());
  1089. bindAdapter->_pReportQueue = p.get();
  1090. p = _communicator->getStatReport()->createPropertyReport(bindAdapter->getName() + ".connectRate", PropertyReport::avg());
  1091. bindAdapter->_pReportConRate = p.get();
  1092. p = _communicator->getStatReport()->createPropertyReport(bindAdapter->getName() + ".timeoutNum", PropertyReport::sum());
  1093. bindAdapter->_pReportTimeoutNum = p.get();
  1094. }
  1095. }
  1096. }
  1097. }
  1098. void Application::checkServantNameValid(const string& servant, const string& sPrefix)
  1099. {
  1100. if ((servant.length() <= sPrefix.length()) || (servant.substr(0, sPrefix.length()) != sPrefix))
  1101. {
  1102. ostringstream os;
  1103. os << "Servant '" << servant << "' error: must be start with '" << sPrefix << "'";
  1104. NOTIFY_AND_WAIT("exit: " + string(os.str()));
  1105. __out__.error() << os.str() << endl;
  1106. exit(-1);
  1107. }
  1108. }
  1109. void Application::outAdapter(ostream &os, const string &v, TC_EpollServer::BindAdapterPtr lsPtr)
  1110. {
  1111. os << TC_Common::outfill("name") << lsPtr->getName() << endl;
  1112. os << TC_Common::outfill("servant") << v << endl;
  1113. os << TC_Common::outfill("endpoint") << lsPtr->getEndpoint().toString() << endl;
  1114. os << TC_Common::outfill("maxconns") << lsPtr->getMaxConns() << endl;
  1115. os << TC_Common::outfill("queuecap") << lsPtr->getQueueCapacity() << endl;
  1116. os << TC_Common::outfill("queuetimeout") << lsPtr->getQueueTimeout() << "ms" << endl;
  1117. os << TC_Common::outfill("order") << (lsPtr->getOrder() == TC_EpollServer::BindAdapter::ALLOW_DENY ? "allow,deny" : "deny,allow") << endl;
  1118. os << TC_Common::outfill("allow") << TC_Common::tostr(lsPtr->getAllow()) << endl;
  1119. os << TC_Common::outfill("deny") << TC_Common::tostr(lsPtr->getDeny()) << endl;
  1120. // os << outfill("queuesize") << lsPtr->getRecvBufferSize() << endl;
  1121. os << TC_Common::outfill("connections") << lsPtr->getNowConnection() << endl;
  1122. os << TC_Common::outfill("protocol") << lsPtr->getProtocolName() << endl;
  1123. os << TC_Common::outfill("handlethread") << lsPtr->getHandleNum() << endl;
  1124. }
  1125. //////////////////////////////////////////////////////////////////////////////////////////////////
  1126. }