ServantProxy.cpp 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684
  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 "servant/ServantProxy.h"
  17. #include "servant/ServantHandle.h"
  18. #include "servant/StatReport.h"
  19. #include "servant/Application.h"
  20. #include "servant/BaseF.h"
  21. #include "servant/CommunicatorEpoll.h"
  22. #include "servant/EndpointManager.h"
  23. #include "servant/Message.h"
  24. #include "servant/ObjectProxy.h"
  25. #include "servant/RemoteLogger.h"
  26. namespace tars
  27. {
  28. shared_ptr<ServantProxyThreadData::Immortal> ServantProxyThreadData::g_immortal;
  29. thread_local shared_ptr<ServantProxyThreadData> ServantProxyThreadData::g_sp;
  30. unsigned int ServantProxyThreadData::_traceParamMaxLen = 1; // 默认1K
  31. ///////////////////////////////////////////////////////////////
  32. SeqManager::SeqManager(uint16_t iNum)
  33. {
  34. assert(iNum < MAX_UNSIGN_SHORT);
  35. assert(iNum > 0);
  36. _p = NULL;
  37. _p = new SeqInfo[iNum];
  38. assert(_p);
  39. //0xff表示结束
  40. _free = 0;
  41. _freeTail = iNum - 1;
  42. for (uint16_t i = 0; i < (uint16_t)iNum; i++)
  43. {
  44. _p[i].free = true;
  45. _p[i].next = i + 1;
  46. }
  47. _p[iNum - 1].next = MAX_UNSIGN_SHORT;
  48. _num = iNum;
  49. }
  50. SeqManager ::~SeqManager()
  51. {
  52. if (_p)
  53. {
  54. delete[] _p;
  55. _p = NULL;
  56. }
  57. }
  58. uint16_t SeqManager::get()
  59. {
  60. TC_LockT<TC_SpinLock> lock(_mutex);
  61. assert(_free != MAX_UNSIGN_SHORT);
  62. assert(_p[_free].free);
  63. uint16_t buf = _free;
  64. if (_free == _freeTail)
  65. {
  66. assert(_p[buf].next == MAX_UNSIGN_SHORT);
  67. _freeTail = MAX_UNSIGN_SHORT;
  68. }
  69. _free = _p[buf].next;
  70. _p[buf].free = false;
  71. return buf;
  72. }
  73. void SeqManager::del(uint16_t iSeq)
  74. {
  75. TC_LockT<TC_SpinLock> lock(_mutex);
  76. assert(iSeq < _num);
  77. assert(!_p[iSeq].free);
  78. _p[iSeq].next = MAX_UNSIGN_SHORT;
  79. if (MAX_UNSIGN_SHORT == _freeTail)
  80. {
  81. _free = iSeq;
  82. }
  83. else
  84. {
  85. _p[_freeTail].next = iSeq;
  86. }
  87. _p[iSeq].free = true;
  88. _freeTail = iSeq;
  89. }
  90. ///////////////////////////////////////////////////////////////
  91. ServantProxyThreadData::Immortal::Immortal()
  92. {
  93. _pSeq.reset(new SeqManager(MAX_CLIENT_NOTIFYEVENT_NUM));
  94. }
  95. ServantProxyThreadData::Immortal::~Immortal()
  96. {
  97. _pSeq.reset();
  98. }
  99. void ServantProxyThreadData::Immortal::add(ServantProxyThreadData* data)
  100. {
  101. TC_LockT<TC_ThreadMutex> lock(_mutex);
  102. _sp_list.insert(data);
  103. }
  104. void ServantProxyThreadData::Immortal::erase(ServantProxyThreadData* data)
  105. {
  106. TC_LockT<TC_ThreadMutex> lock(_mutex);
  107. _sp_list.erase(data);
  108. }
  109. unordered_set<ServantProxyThreadData *> ServantProxyThreadData::Immortal::getList()
  110. {
  111. TC_LockT<TC_ThreadMutex> lock(_mutex);
  112. return _sp_list;
  113. }
  114. void ServantProxyThreadData::Immortal::erase(Communicator *comm)
  115. {
  116. TC_LockT<TC_ThreadMutex> lock(_mutex);
  117. for(auto it : _sp_list)
  118. {
  119. (*it).erase(comm);
  120. }
  121. }
  122. ServantProxyThreadData::ServantProxyThreadData()
  123. : _reqQNo(0)
  124. {
  125. // LOG_CONSOLE_DEBUG << endl;
  126. _sp_immortal = g_immortal;
  127. _reqQNo = _sp_immortal->getSeqManager()->get();
  128. _sp_immortal->add(this);
  129. }
  130. ServantProxyThreadData::~ServantProxyThreadData()
  131. {
  132. // LOG_CONSOLE_DEBUG << endl;
  133. try
  134. {
  135. // TC_LockT<TC_SpinLock> lock(_mutex);
  136. //先释放公有的网络通信器的信息
  137. for(auto it = _communicatorEpollInfo.begin(); it != _communicatorEpollInfo.end(); ++it)
  138. {
  139. for (auto &e: it->second->_info)
  140. {
  141. shared_ptr<CommunicatorEpoll> ce = e._communicatorEpoll.lock();
  142. if(ce)
  143. {
  144. ce->notifyServantThreadQuit(_reqQNo);
  145. }
  146. }
  147. }
  148. for(auto it = _schedCommunicatorEpollInfo.begin(); it != _schedCommunicatorEpollInfo.end(); ++it)
  149. {
  150. it->second->_communicator->eraseSchedCommunicatorEpoll(_reqQNo);
  151. }
  152. }
  153. catch (...)
  154. {
  155. }
  156. _sp_immortal->erase(this);
  157. _sp_immortal->getSeqManager()->del(_reqQNo);
  158. _sched.reset();
  159. _sp_immortal.reset();
  160. }
  161. ServantProxyThreadData* ServantProxyThreadData::getData()
  162. {
  163. static std::once_flag flag;
  164. std::call_once(flag, []()
  165. { g_immortal = std::make_shared<Immortal>(); });
  166. if (!g_sp)
  167. {
  168. g_sp = std::make_shared<ServantProxyThreadData>();
  169. }
  170. return g_sp.get();
  171. }
  172. void ServantProxyThreadData::deconstructor(Communicator *communicator)
  173. {
  174. if(g_immortal.use_count() > 0)
  175. {
  176. g_immortal->erase(communicator);
  177. }
  178. }
  179. void ServantProxyThreadData::erase(Communicator *communicator)
  180. {
  181. TC_LockT<TC_ThreadMutex> lock(_mutex);
  182. _communicatorEpollInfo.erase(communicator);
  183. _schedCommunicatorEpollInfo.erase(communicator);
  184. }
  185. shared_ptr<ServantProxyThreadData::CommunicatorEpollInfo> ServantProxyThreadData::getCommunicatorEpollInfo(Communicator *communicator)
  186. {
  187. TC_LockT<TC_ThreadMutex> lock(_mutex);
  188. auto it = _communicatorEpollInfo.find(communicator);
  189. if(it != _communicatorEpollInfo.end())
  190. {
  191. return it->second;
  192. }
  193. auto info = std::make_shared<CommunicatorEpollInfo>();
  194. _communicatorEpollInfo.insert(std::make_pair(communicator, info));
  195. return info;
  196. }
  197. shared_ptr<ServantProxyThreadData::SchedCommunicatorEpollInfo> ServantProxyThreadData::getSchedCommunicatorEpollInfo(Communicator *communicator)
  198. {
  199. TC_LockT<TC_ThreadMutex> lock(_mutex);
  200. auto it = _schedCommunicatorEpollInfo.find(communicator);
  201. if(it != _schedCommunicatorEpollInfo.end())
  202. {
  203. return it->second;
  204. }
  205. auto info = std::make_shared<SchedCommunicatorEpollInfo>();
  206. _schedCommunicatorEpollInfo.insert(std::make_pair(communicator, info));
  207. return info;
  208. }
  209. ThreadPrivateData ServantProxyThreadData::move()
  210. {
  211. ThreadPrivateData data = _data;
  212. //hash每次调用完成都要清掉,不用透传
  213. _data._hash = false;
  214. _data._conHash = false;
  215. _data._timeout = 0;
  216. return data;
  217. }
  218. shared_ptr<ServantProxyThreadData::CommunicatorEpollInfo> ServantProxyThreadData::addCommunicatorEpoll(const shared_ptr<CommunicatorEpoll> &ce)
  219. {
  220. auto q = std::make_shared<ReqInfoQueue>(ce->getNoSendQueueLimit());
  221. ServantProxyThreadData::CommunicatorEpollReqQueueInfo epollReqQueueInfo;
  222. epollReqQueueInfo._reqQueue = q;
  223. epollReqQueueInfo._communicatorEpoll = ce;
  224. auto info = getCommunicatorEpollInfo(ce->getCommunicator());
  225. info->_info.push_back(epollReqQueueInfo);
  226. ce->initNotify(this->_reqQNo, q);
  227. return info;
  228. }
  229. ///////////////////////////////////////////////////////////////////////////////////////////
  230. ServantProxyCallback::ServantProxyCallback()
  231. : _bNetThreadProcess(false)
  232. {
  233. }
  234. int ServantProxyCallback::dispatch(ReqMessagePtr msg)
  235. {
  236. return onDispatch(msg);
  237. }
  238. ///////////////////////////////////////////////////////////////////////////////////////////
  239. int HttpServantProxyCallback::onDispatch(ReqMessagePtr msg)
  240. {
  241. if (msg->response->iRet != TARSSERVERSUCCESS)
  242. {
  243. return onDispatchException(msg->request, *msg->response);
  244. }
  245. return onDispatchResponse(msg->request, *msg->response);
  246. }
  247. HttpServantProxyCallback::HttpServantProxyCallback(const HttpCallbackPtr &cb)
  248. : _httpCb(cb)
  249. {
  250. }
  251. int HttpServantProxyCallback::onDispatchException(const RequestPacket &request, const ResponsePacket &response)
  252. {
  253. if (_httpCb)
  254. return _httpCb->onHttpResponseException(response.iRet);
  255. return 0;
  256. }
  257. int HttpServantProxyCallback::onDispatchResponse(const RequestPacket &request, const ResponsePacket &response)
  258. {
  259. assert(response.sBuffer.size() == sizeof(shared_ptr<TC_HttpResponse>));
  260. shared_ptr<TC_HttpResponse> rsp = *(shared_ptr<TC_HttpResponse> *)(response.sBuffer.data());
  261. if (_httpCb)
  262. return _httpCb->onHttpResponse(rsp);
  263. return 0;
  264. }
  265. ///////////////////////////////////////////////////////////////
  266. void coroWhenAll(const CoroParallelBasePtr &ptr)
  267. {
  268. if(!ptr->checkAllReqSend())
  269. {
  270. TLOGERROR("[coroWhenAll use coro invoke interface's num not equal ptr set value]"<<endl);
  271. throw TarsUseCoroException("use coro invoke interface's num not equal ptr set value");
  272. }
  273. //线程私有数据
  274. ServantProxyThreadData *pSptd = ServantProxyThreadData::getData();
  275. assert(pSptd != NULL);
  276. if (!pSptd->_sched)
  277. {
  278. TLOGERROR("[coroWhenAll no open coroutine mode]"<<endl);
  279. throw TarsUseCoroException("coroWhenAll not open coroutine mode");
  280. }
  281. pSptd->_sched->yield(false);
  282. vector<ReqMessage *> vMsg = ptr->getAllReqMessage();
  283. for (size_t i = 0; i < vMsg.size(); ++i)
  284. {
  285. ReqMessagePtr msgPtr = vMsg[i];
  286. vMsg[i]->callback->dispatch(msgPtr);
  287. }
  288. }
  289. ///////////////////////////////////////////////////////////////
  290. string ServantProxy::STATUS_DYED_KEY = "STATUS_DYED_KEY";
  291. string ServantProxy::STATUS_GRID_KEY = "STATUS_GRID_KEY";
  292. string ServantProxy::STATUS_RESULT_CODE = "STATUS_RESULT_CODE";
  293. string ServantProxy::STATUS_RESULT_DESC = "STATUS_RESULT_DESC";
  294. string ServantProxy::STATUS_SETNAME_VALUE = "STATUS_SETNAME_VALUE";
  295. string ServantProxy::STATUS_TRACE_KEY = "STATUS_TRACE_KEY";
  296. ////////////////////////////////////
  297. ServantProxy::ServantProxy(Communicator *pCommunicator, const string &name, const string &setName)
  298. : _communicator(pCommunicator), _syncTimeout(DEFAULT_SYNCTIMEOUT), _asyncTimeout(DEFAULT_ASYNCTIMEOUT), _id(0), _masterFlag(false), _minTimeout(100)
  299. {
  300. _proxyProtocol.requestFunc = ProxyProtocol::tarsRequest;
  301. _proxyProtocol.responseFunc = ProxyProtocol::tarsResponse;
  302. //在每个公有网络线程对象中创建ObjectProxy
  303. for (size_t i = 0; i < _communicator->getCommunicatorEpollNum(); ++i)
  304. {
  305. _communicator->getCommunicatorEpoll(i)->createObjectProxy(this, name, setName);
  306. }
  307. //用第一个ObjectProxy返回数据
  308. _objectProxy = this->getObjectProxy(0);
  309. _endpointInfo.reset(new EndpointManagerThread(_communicator, _objectProxy->name()));
  310. _minTimeout = pCommunicator->getMinTimeout();
  311. if (_minTimeout < 1)
  312. {
  313. _minTimeout = 1;
  314. }
  315. }
  316. void ServantProxy::tars_initialize(bool rootServant)
  317. {
  318. //等ServantProxy完全创建完以后, 再创建Object
  319. for (size_t i = 0; i < _communicator->getCommunicatorEpollNum(); ++i)
  320. {
  321. this->getObjectProxy(i)->initialize(rootServant);
  322. }
  323. }
  324. ServantProxy::~ServantProxy()
  325. {
  326. }
  327. const string &ServantProxy::tars_name() const
  328. {
  329. return _objectProxy->name();
  330. }
  331. string ServantProxy::tars_full_name() const
  332. {
  333. string name = _objectProxy->name();
  334. if(!_objectProxy->hash().empty())
  335. {
  336. name = name + "#" + _objectProxy->hash();
  337. }
  338. if(!_objectProxy->address().empty())
  339. {
  340. name = name + "@" + _objectProxy->address();
  341. }
  342. return name;
  343. }
  344. const string& ServantProxy::tars_setName() const
  345. {
  346. return _objectProxy->getInvokeSetName();
  347. }
  348. ObjectProxy *ServantProxy::getObjectProxy(size_t netThreadSeq)
  349. {
  350. return _communicator->getCommunicatorEpoll(netThreadSeq)->servantToObjectProxy(this);
  351. }
  352. void ServantProxy::forEachObject(std::function<void(ObjectProxy *)> func)
  353. {
  354. for (size_t i = 0; i < _communicator->getCommunicatorEpollNum(); ++i)
  355. {
  356. ObjectProxy *objectProxy = _communicator->getCommunicatorEpoll(i)->servantToObjectProxy(this);
  357. assert(objectProxy != NULL);
  358. try
  359. {
  360. func(objectProxy);
  361. }
  362. catch (...)
  363. {
  364. }
  365. }
  366. }
  367. void ServantProxy::tars_reconnect(int second)
  368. {
  369. forEachObject([=](ObjectProxy *o) { o->reconnect(second); });
  370. }
  371. void ServantProxy::tars_reconnect(int millisecond, bool onlyActiveInReg)
  372. {
  373. forEachObject([=](ObjectProxy *o) { o->reconnect(millisecond, onlyActiveInReg); });
  374. }
  375. TC_Endpoint ServantProxy::tars_invoke_endpoint()
  376. {
  377. ServantProxyThreadData *td = ServantProxyThreadData::getData();
  378. if (td)
  379. {
  380. return TC_Endpoint(td->_data._szHost);
  381. }
  382. return TC_Endpoint();
  383. }
  384. void ServantProxy::tars_set_proxy(ServantProxy::SERVANT_PROXY type, const TC_Endpoint &ep, const string &user, const string &pass)
  385. {
  386. _proxyBaseInfo = std::make_shared<TC_ProxyInfo::ProxyBaseInfo>();
  387. _proxyBaseInfo->ep = ep;
  388. _proxyBaseInfo->user = user;
  389. _proxyBaseInfo->pass = pass;
  390. switch (type)
  391. {
  392. case PROXY_SOCK4:
  393. _proxyBaseInfo->type = TC_ProxyInfo::eProxy_Type_Sock4;
  394. break;
  395. case PROXY_SOCK5:
  396. _proxyBaseInfo->type = TC_ProxyInfo::eProxy_Type_Sock5;
  397. break;
  398. case PROXY_HTTP:
  399. _proxyBaseInfo->type = TC_ProxyInfo::eProxy_Type_Http;
  400. break;
  401. default:
  402. assert(false);
  403. }
  404. }
  405. void ServantProxy::tars_timeout(int msecond)
  406. {
  407. //保护,超时时间不能小于_minTimeout毫秒
  408. _syncTimeout = (msecond < _minTimeout) ? _minTimeout : msecond;
  409. }
  410. int ServantProxy::tars_timeout() const
  411. {
  412. return _syncTimeout;
  413. }
  414. int ServantProxy::tars_connect_timeout() const
  415. {
  416. return _connTimeout;
  417. }
  418. void ServantProxy::tars_connect_timeout(int conTimeout)
  419. {
  420. if(conTimeout < 100)
  421. {
  422. conTimeout = 100;
  423. }
  424. _connTimeout = conTimeout;
  425. }
  426. void ServantProxy::tars_async_timeout(int msecond)
  427. {
  428. TC_LockT<TC_ThreadMutex> lock(*this);
  429. //保护,超时时间不能小于_minTimeout毫秒
  430. _asyncTimeout = (msecond < _minTimeout) ? _minTimeout : msecond;
  431. }
  432. int ServantProxy::tars_async_timeout() const
  433. {
  434. return _asyncTimeout;
  435. }
  436. void ServantProxy::tars_set_custom_callback(ServantProxy::custom_callback callback)
  437. {
  438. _callback = callback;
  439. }
  440. void ServantProxy::tars_enable_callback_hash()
  441. {
  442. _callbackHash = true;
  443. }
  444. void ServantProxy::tars_connection_serial(int connectionSerial)
  445. {
  446. assert(!_rootPrx);
  447. _connectionSerial = connectionSerial;
  448. }
  449. int ServantProxy::tars_connection_serial() const
  450. {
  451. if(_rootPrx) {
  452. return _rootPrx->tars_connection_serial();
  453. }
  454. return _connectionSerial;
  455. }
  456. void ServantProxy::tars_set_protocol(SERVANT_PROTOCOL protocol, int connectionSerial)
  457. {
  458. ProxyProtocol proto;
  459. switch(protocol)
  460. {
  461. case PROTOCOL_HTTP1:
  462. proto.requestFunc = ProxyProtocol::http1Request;
  463. proto.responseFunc = ProxyProtocol::http1Response;
  464. if(connectionSerial <= 0)
  465. connectionSerial = DEFAULT_CONNECTION_SERIAL;
  466. break;
  467. #if TARS_HTTP2
  468. case PROTOCOL_HTTP2:
  469. proto.requestFunc = ProxyProtocol::http2Request;
  470. proto.responseFunc = ProxyProtocol::http2Response;
  471. connectionSerial = 0;
  472. break;
  473. case PROTOCOL_GRPC:
  474. proto.requestFunc = ProxyProtocol::grpcRequest;
  475. proto.responseFunc = ProxyProtocol::grpcResponse;
  476. connectionSerial = 0;
  477. break;
  478. #endif
  479. case PROTOCOL_TARS:
  480. default:
  481. proto.requestFunc = ProxyProtocol::tarsRequest;
  482. proto.responseFunc = ProxyProtocol::tarsResponse;
  483. break;
  484. }
  485. tars_set_protocol(proto, connectionSerial);
  486. }
  487. void ServantProxy::tars_set_protocol(const ProxyProtocol& protocol, int connectionSerial)
  488. {
  489. TC_LockT<TC_ThreadMutex> lock(*this);
  490. _proxyProtocol = protocol;
  491. _connectionSerial = connectionSerial;
  492. }
  493. const ProxyProtocol &ServantProxy::tars_get_protocol() const
  494. {
  495. return _proxyProtocol;
  496. }
  497. vector<ServantProxy::SocketOpt> ServantProxy::tars_get_sockopt() const
  498. {
  499. TC_LockT<TC_ThreadMutex> lock(*this);
  500. return _socketOpts;
  501. }
  502. void ServantProxy::tars_set_sockopt(int level, int optname, const void *optval, SOCKET_LEN_TYPE optlen)
  503. {
  504. TC_LockT<TC_ThreadMutex> lock(*this);
  505. SocketOpt socketOpt;
  506. socketOpt.level = level;
  507. socketOpt.optname = optname;
  508. socketOpt.optval = optval;
  509. socketOpt.optlen = optlen;
  510. _socketOpts.push_back(socketOpt);
  511. }
  512. void ServantProxy::tars_set_check_timeout(const CheckTimeoutInfo& checkTimeoutInfo)
  513. {
  514. TC_LockT<TC_ThreadMutex> lock(*this);
  515. _checkTimeoutInfo = checkTimeoutInfo;
  516. }
  517. CheckTimeoutInfo ServantProxy::tars_get_check_timeout()
  518. {
  519. TC_LockT<TC_ThreadMutex> lock(*this);
  520. return _checkTimeoutInfo;
  521. }
  522. void ServantProxy::tars_ping()
  523. {
  524. map<string, string> m;
  525. map<string, string> s;
  526. TarsOutputStream<BufferWriterVector> os;
  527. tars_invoke(TARSNORMAL, "tars_ping", os, m, s);
  528. }
  529. void ServantProxy::tars_async_ping()
  530. {
  531. map<string, string> m;
  532. map<string, string> s;
  533. TarsOutputStream<BufferWriterVector> os;
  534. tars_invoke_async(TARSONEWAY, "tars_ping", os, m, s, NULL);
  535. }
  536. ServantProxy* ServantProxy::tars_hash(uint32_t key)
  537. {
  538. ServantProxyThreadData *pSptd = ServantProxyThreadData::getData();
  539. assert(pSptd != NULL);
  540. pSptd->_data._hash = true;
  541. pSptd->_data._hashCode = key;
  542. return this;
  543. }
  544. //ServantProxy* ServantProxy::tars_direct()
  545. //{
  546. // ServantProxyThreadData *pSptd = ServantProxyThreadData::getData();
  547. //
  548. // pSptd->_direct = true;
  549. // return this;
  550. //}
  551. ServantProxy* ServantProxy::tars_consistent_hash(uint32_t key)
  552. {
  553. ServantProxyThreadData *pSptd = ServantProxyThreadData::getData();
  554. assert(pSptd != NULL);
  555. pSptd->_data._hash = true;
  556. pSptd->_data._conHash = true;
  557. pSptd->_data._hashCode = key;
  558. return this;
  559. }
  560. ServantProxy* ServantProxy::tars_open_trace(bool traceParams)
  561. {
  562. ServantProxyThreadData *pSptd = ServantProxyThreadData::getData();
  563. assert(pSptd != NULL);
  564. if (traceParams)
  565. {
  566. pSptd->openTrace(15);
  567. }
  568. else
  569. {
  570. pSptd->openTrace();
  571. }
  572. return this;
  573. }
  574. void ServantProxy::tars_clear_hash()
  575. {
  576. }
  577. ServantProxy* ServantProxy::tars_set_timeout(int msecond)
  578. {
  579. ServantProxyThreadData *pSptd = ServantProxyThreadData::getData();
  580. assert(pSptd != NULL);
  581. // pSptd->_hasTimeout = true;
  582. pSptd->_data._timeout = msecond;
  583. return this;
  584. }
  585. uint32_t ServantProxy::tars_gen_requestid()
  586. {
  587. uint32_t i = ++_id;
  588. if (i == 0)
  589. {
  590. i = ++_id;
  591. }
  592. return i;
  593. }
  594. void ServantProxy::tars_set_push_callback(const ServantProxyCallbackPtr & cb)
  595. {
  596. _pushCallback = cb;
  597. }
  598. ServantProxyCallbackPtr ServantProxy::tars_get_push_callback()
  599. {
  600. return _pushCallback;
  601. }
  602. void ServantProxy::invoke(ReqMessage *msg, bool bCoroAsync)
  603. {
  604. //线程私有数据
  605. ServantProxyThreadData *pSptd = ServantProxyThreadData::getData();
  606. assert(pSptd != NULL);
  607. //协程调用方式, 启用协程
  608. if(bCoroAsync && TC_CoroutineScheduler::scheduler() && !pSptd->_sched)
  609. {
  610. pSptd->_sched = TC_CoroutineScheduler::scheduler();
  611. }
  612. msg->data = pSptd->move();
  613. // 调用链追踪透传
  614. msg->bTraceCall = pSptd->_traceCall;
  615. msg->sTraceKey = pSptd->getTraceKey(true);
  616. if (msg->data._dyeing)
  617. {
  618. TLOGTARS("[ServantProxy::invoke, set dyeing, key=" << pSptd->_data._dyeingKey << endl);
  619. }
  620. msg->data._cookie = pSptd->_data._cookie;
  621. // #ifdef TARS_OPENTRACKING
  622. // msg->trackInfoMap = pSptd->_trackInfoMap;
  623. // #endif
  624. //
  625. //设置超时时间
  626. msg->request.iTimeout = (ReqMessage::SYNC_CALL == msg->eType) ? _syncTimeout : _asyncTimeout;
  627. //判断是否针对接口级设置超时
  628. if (msg->data._timeout > 0)
  629. {
  630. msg->request.iTimeout = msg->data._timeout;
  631. }
  632. else
  633. {
  634. msg->request.iTimeout = (ReqMessage::SYNC_CALL == msg->eType) ? _syncTimeout : _asyncTimeout;
  635. }
  636. shared_ptr<ReqInfoQueue> pReqQ;
  637. //选择网络线程
  638. selectNetThreadInfo(pSptd, msg->pObjectProxy, pReqQ);
  639. //如果是按set规则调用
  640. if (msg->pObjectProxy && msg->pObjectProxy->isInvokeBySet())
  641. {
  642. SET_MSG_TYPE(msg->request.iMessageType, TARSMESSAGETYPESETNAME);
  643. msg->request.status[ServantProxy::STATUS_SETNAME_VALUE] = msg->pObjectProxy->getInvokeSetName();
  644. TLOGTARS("[ServantProxy::invoke, " << msg->request.sServantName << ", invoke with set," << msg->pObjectProxy->getInvokeSetName() << "]" << endl);
  645. }
  646. assert(msg->pMonitor == NULL);
  647. if (msg->eType == ReqMessage::SYNC_CALL)
  648. {
  649. if (pSptd->_sched)
  650. {
  651. msg->sched = pSptd->_sched;
  652. msg->iCoroId = pSptd->_sched->getCoroutineId();
  653. }
  654. else
  655. {
  656. //同步调用 new 一个ReqMonitor
  657. msg->pMonitor = new ReqMonitor(msg);
  658. }
  659. }
  660. else if (msg->eType == ReqMessage::ASYNC_CALL)
  661. {
  662. //是否是协程的并行请求
  663. if (bCoroAsync)
  664. {
  665. if (pSptd->_sched)
  666. {
  667. CoroParallelBasePtr coroPtr = msg->callback->getCoroParallelBasePtr();
  668. if (coroPtr)
  669. {
  670. coroPtr->incReqCount();
  671. msg->sched = pSptd->_sched;
  672. msg->iCoroId = pSptd->_sched->getCoroutineId();
  673. }
  674. else
  675. {
  676. TLOGERROR("[ServantProxy::invoke use coroutine's callback not set CoroParallelBasePtr]" << endl);
  677. delete msg;
  678. msg = NULL;
  679. throw TarsUseCoroException("use coroutine's callback not set CoroParallelBasePtr");
  680. }
  681. }
  682. else
  683. {
  684. TLOGERROR("[ServantProxy::invoke coroutine mode invoke not open]" << endl);
  685. delete msg;
  686. msg = NULL;
  687. throw TarsUseCoroException("coroutine mode invoke not open");
  688. }
  689. }
  690. }
  691. //通知网络线程
  692. bool bEmpty = false;
  693. bool bSync = (msg->eType == ReqMessage::SYNC_CALL);
  694. if (!pReqQ->push_back(msg, bEmpty))
  695. {
  696. TLOGERROR("[ServantProxy::invoke msgQueue push_back error thread seq:" << pSptd->_reqQNo << "]" << endl);
  697. delete msg;
  698. msg = NULL;
  699. throw TarsClientQueueException("client queue full");
  700. }
  701. if (msg->sched)
  702. {
  703. // LOG_CONSOLE_DEBUG << "in sched handle: " << this << ", " << msg->request.sServantName << endl;
  704. //协程中, 直接发包了
  705. msg->pObjectProxy->getCommunicatorEpoll()->handle(pSptd->_reqQNo);
  706. }
  707. else
  708. {
  709. msg->pObjectProxy->getCommunicatorEpoll()->notify(pSptd->_reqQNo);
  710. }
  711. if (bSync)
  712. {
  713. if (!msg->sched)
  714. {
  715. assert(msg->pMonitor);
  716. msg->pMonitor->wait();
  717. if(!msg->pMonitor->bMonitorFin)
  718. {
  719. TLOGERROR("[ServantProxy::invoke communicator terminate]" << endl);
  720. throw TarsCommunicatorException("communicator terminate");
  721. }
  722. }
  723. else
  724. {
  725. assert(!msg->sched->isMainCoroutine());
  726. msg->sched->yield(false);
  727. }
  728. //判断eStatus来判断状态
  729. // assert(msg->eStatus != ReqMessage::REQ_REQ);
  730. if(msg->adapter) {
  731. pSptd->_data._szHost = msg->adapter->endpoint().desc();
  732. }
  733. if(msg->eStatus == ReqMessage::REQ_RSP && msg->response->iRet == TARSSERVERSUCCESS)
  734. {
  735. //成功
  736. return;
  737. }
  738. ostringstream os;
  739. if (msg->eStatus == ReqMessage::REQ_TIME)
  740. {
  741. //超时
  742. os << "[ServantProxy::invoke timeout:" << msg->request.iTimeout;
  743. }
  744. else
  745. {
  746. os << "[ServantProxy::invoke errno:" << msg->response->iRet << ",info:" << msg->response->sResultDesc;
  747. }
  748. os << ",servant:" << msg->pObjectProxy->name() << ",func:" << msg->request.sFuncName;
  749. if (msg->adapter)
  750. os << ",adapter:" << msg->adapter->endpoint().desc();
  751. os << ",reqid:" << msg->request.iRequestId << "]";
  752. if (msg->eStatus == ReqMessage::REQ_TIME)
  753. {
  754. //超时
  755. delete msg;
  756. msg = NULL;
  757. throw TarsSyncCallTimeoutException(os.str());
  758. }
  759. //异常调用
  760. int ret = msg->response->iRet;
  761. delete msg;
  762. msg = NULL;
  763. TarsException::throwException(ret, os.str());
  764. }
  765. }
  766. //////////////////////////////////////////////////////////////////
  767. void ServantProxy::tars_invoke_async(char cPacketType,
  768. const string &sFuncName,
  769. TarsOutputStream<BufferWriterVector> &buf,
  770. const map<string, string>& context,
  771. const map<string, string>& status,
  772. const ServantProxyCallbackPtr& callback,
  773. bool bCoro)
  774. {
  775. ReqMessage *msg = new ReqMessage();
  776. msg->init(callback?ReqMessage::ASYNC_CALL:ReqMessage::ONE_WAY, this);
  777. msg->callback = callback;
  778. msg->request.iVersion = TARSVERSION;
  779. msg->request.cPacketType = (callback ? cPacketType : TARSONEWAY);
  780. msg->request.sFuncName = sFuncName;
  781. msg->request.sServantName = _objectProxy->name();
  782. buf.swap(msg->request.sBuffer);
  783. msg->request.context = context;
  784. msg->request.status = status;
  785. msg->request.iTimeout = _asyncTimeout;
  786. // // 在RequestPacket中的context设置主调信息
  787. // if(_masterFlag)
  788. // {
  789. // msg->request.context.insert(std::make_pair(TARS_MASTER_KEY,ClientConfig::ModuleName)); //TARS_MASTER_KEY clientConfig.ModuleName
  790. // }
  791. checkDye(msg->request);
  792. checkTrace(msg->request);
  793. checkCookie(msg->request);
  794. servant_invoke(msg, bCoro);
  795. }
  796. //////////////////////////////////////////////////////////////////
  797. void ServantProxy::tars_invoke_async(char cPacketType,
  798. const string &sFuncName,
  799. const vector<char> &buf,
  800. const map<string, string>& context,
  801. const map<string, string>& status,
  802. const ServantProxyCallbackPtr& callback,
  803. bool bCoro)
  804. {
  805. ReqMessage * msg = new ReqMessage();
  806. msg->init(callback?ReqMessage::ASYNC_CALL:ReqMessage::ONE_WAY, this);
  807. msg->callback = callback;
  808. msg->request.iVersion = TARSVERSION;
  809. msg->request.cPacketType = (callback ? cPacketType : TARSONEWAY);
  810. msg->request.sFuncName = sFuncName;
  811. msg->request.sServantName = _objectProxy->name();
  812. msg->request.sBuffer = buf;
  813. msg->request.context = context;
  814. msg->request.status = status;
  815. msg->request.iTimeout = _asyncTimeout;
  816. // // 在RequestPacket中的context设置主调信息
  817. // if(_masterFlag)
  818. // {
  819. // msg->request.context.insert(std::make_pair(TARS_MASTER_KEY,ClientConfig::ModuleName)); //TARS_MASTER_KEY clientConfig.ModuleName
  820. // }
  821. checkDye(msg->request);
  822. checkTrace(msg->request);
  823. checkCookie(msg->request);
  824. servant_invoke(msg, bCoro);
  825. }
  826. shared_ptr<ResponsePacket> ServantProxy::tars_invoke(char cPacketType,
  827. const string& sFuncName,
  828. const vector<char>& buf,
  829. const map<string, string>& context,
  830. const map<string, string>& status)
  831. // ResponsePacket& rsp)
  832. {
  833. ReqMessage *msg = new ReqMessage();
  834. msg->init(ReqMessage::SYNC_CALL, this);
  835. msg->request.iVersion = TARSVERSION;
  836. msg->request.cPacketType = cPacketType;
  837. msg->request.sFuncName = sFuncName;
  838. msg->request.sServantName = _objectProxy->name();
  839. msg->request.sBuffer = buf;
  840. msg->request.context = context;
  841. msg->request.status = status;
  842. msg->request.iTimeout = _syncTimeout;
  843. // // 在RequestPacket中的context设置主调信息
  844. // if(_masterFlag)
  845. // {
  846. // msg->request.context.insert(std::make_pair(TARS_MASTER_KEY,ClientConfig::ModuleName));
  847. // }
  848. checkDye(msg->request);
  849. checkTrace(msg->request);
  850. checkCookie(msg->request);
  851. servant_invoke(msg, false);
  852. shared_ptr<ResponsePacket> rsp = msg->response;
  853. // rsp = msg->response;
  854. delete msg;
  855. msg = NULL;
  856. return rsp;
  857. }
  858. shared_ptr<ResponsePacket> ServantProxy::tars_invoke(char cPacketType,
  859. const string& sFuncName,
  860. TarsOutputStream<BufferWriterVector>& buf,
  861. const map<string, string>& context,
  862. const map<string, string>& status)
  863. {
  864. ReqMessage * msg = new ReqMessage();
  865. msg->init(ReqMessage::SYNC_CALL, this);
  866. msg->request.iVersion = TARSVERSION;
  867. msg->request.cPacketType = cPacketType;
  868. msg->request.sFuncName = sFuncName;
  869. msg->request.sServantName = _objectProxy->name();
  870. buf.swap(msg->request.sBuffer);
  871. msg->request.context = context;
  872. msg->request.status = status;
  873. msg->request.iTimeout = _syncTimeout;
  874. checkDye(msg->request);
  875. checkTrace(msg->request);
  876. checkCookie(msg->request);
  877. servant_invoke(msg, false);
  878. shared_ptr<ResponsePacket> rsp = msg->response;
  879. delete msg;
  880. msg = NULL;
  881. return rsp;
  882. }
  883. //////////////////////////////////////////////////////////////////////////////
  884. //服务端是非tars协议,通过rpc_call调用
  885. void ServantProxy::rpc_call(uint32_t iRequestId,
  886. const string& sFuncName,
  887. const char* buff,
  888. uint32_t len,
  889. ResponsePacket& rsp)
  890. {
  891. ReqMessage *msg = new ReqMessage();
  892. msg->init(ReqMessage::SYNC_CALL, this);
  893. msg->bFromRpc = true;
  894. msg->request.sServantName = _objectProxy->name();
  895. msg->request.sFuncName = sFuncName;
  896. msg->request.iRequestId = iRequestId;
  897. msg->request.sBuffer.assign(buff, buff + len);
  898. servant_invoke(msg, false);
  899. rsp = *msg->response.get();
  900. delete msg;
  901. msg = NULL;
  902. }
  903. void ServantProxy::rpc_call_async(uint32_t iRequestId,
  904. const string& sFuncName,
  905. const char* buff,
  906. uint32_t len,
  907. const ServantProxyCallbackPtr& callback,
  908. bool bCoro)
  909. {
  910. ReqMessage *msg = new ReqMessage();
  911. msg->init(callback ? ReqMessage::ASYNC_CALL : ReqMessage::ONE_WAY, this);
  912. msg->bFromRpc = true;
  913. msg->callback = callback;
  914. msg->request.sServantName = _objectProxy->name();
  915. msg->request.sFuncName = sFuncName;
  916. msg->request.iRequestId = iRequestId;
  917. msg->request.sBuffer.assign(buff, buff + len);
  918. servant_invoke(msg, bCoro);
  919. }
  920. ServantPrx ServantProxy::getServantPrx(ReqMessage *msg)
  921. {
  922. if (_servantId == 0)
  923. {
  924. std::lock_guard<std::mutex> m(_servantMutex);
  925. if (_servantId == 0 && _servantList.empty())
  926. {
  927. for (int i = 1; i < _connectionSerial; ++i)
  928. {
  929. string obj = tars_name() + "#" + TC_Common::tostr(i);
  930. if (!_objectProxy->address().empty())
  931. {
  932. obj += "@" + _objectProxy->address();
  933. }
  934. ServantPrx prx = _communicator->stringToProxy<ServantPrx>(obj, this->tars_setName(), false);
  935. prx->tars_set_protocol(tars_get_protocol());
  936. prx->tars_connect_timeout(tars_connect_timeout());
  937. prx->tars_timeout(tars_timeout());
  938. prx->tars_async_timeout(tars_async_timeout());
  939. prx->_rootPrx = this;
  940. _servantList.push_back(prx);
  941. }
  942. }
  943. }
  944. if (_connectionSerial != 0)
  945. {
  946. assert(int(_servantList.size() + 1) == _connectionSerial);
  947. }
  948. int id = _servantId++ % (_servantList.size() + 1);
  949. if (id == 0)
  950. {
  951. return this;
  952. }
  953. return _servantList[(id - 1)];
  954. }
  955. void ServantProxy::travelObjectProxys(ServantProxy *prx, function<void(ObjectProxy*)> f)
  956. {
  957. vector<ObjectProxy*> objectProxys;
  958. size_t num = _communicator->getCommunicatorEpollNum();
  959. for (size_t i = 0; i < num; ++i)
  960. {
  961. auto ce = _communicator->getCommunicatorEpoll(i);
  962. ObjectProxy* objectProxy = ce->servantToObjectProxy(prx);
  963. if (objectProxy)
  964. {
  965. f(objectProxy);
  966. }
  967. }
  968. //协程通信器也需要
  969. _communicator->forEachSchedCommunicatorEpoll([&](const shared_ptr<CommunicatorEpoll>& ce)
  970. {
  971. ObjectProxy* objectProxy = ce->servantToObjectProxy(prx);
  972. if (objectProxy)
  973. {
  974. f(objectProxy);
  975. }
  976. });
  977. }
  978. vector<ObjectProxy*> ServantProxy::getObjectProxys()
  979. {
  980. vector<ObjectProxy*> objectProxys;
  981. //更新子servant proxy的地址
  982. for (size_t i = 0; i < _servantList.size(); i++)
  983. {
  984. ServantProxy* prx = _servantList[i].get();
  985. travelObjectProxys(prx, [&](ObjectProxy *op){
  986. objectProxys.push_back(op);
  987. });
  988. }
  989. travelObjectProxys(this, [&](ObjectProxy *op){
  990. objectProxys.push_back(op);
  991. });
  992. return objectProxys;
  993. }
  994. void ServantProxy::tars_update_endpoints(const set<EndpointInfo> &active, const set<EndpointInfo> &inactive)
  995. {
  996. onNotifyEndpoints(NULL, active, inactive);
  997. }
  998. void ServantProxy::onNotifyEndpoints(CommunicatorEpoll *communicatorEpoll, const set<EndpointInfo> &active, const set<EndpointInfo> &inactive)
  999. {
  1000. //更新子servant proxy的地址
  1001. for (size_t i = 0; i < _servantList.size(); i++)
  1002. {
  1003. ServantProxy* prx = _servantList[i].get();
  1004. travelObjectProxys(prx, [&](ObjectProxy *op){
  1005. if(op->getEndpointManager())
  1006. {
  1007. op->getEndpointManager()->updateEndpointsOutter(active, inactive);
  1008. }
  1009. });
  1010. }
  1011. travelObjectProxys(this, [&](ObjectProxy *op){
  1012. if(op->getEndpointManager())
  1013. {
  1014. op->getEndpointManager()->updateEndpointsOutter(active, inactive);
  1015. }
  1016. });
  1017. }
  1018. void ServantProxy::onSetInactive(const EndpointInfo &ep)
  1019. {
  1020. if (!_rootPrx)
  1021. return;
  1022. for (size_t i = 0; i < _rootPrx->_servantList.size(); i++)
  1023. {
  1024. ServantPrx &prx = _rootPrx->_servantList[i];
  1025. prx->forEachObject([&](ObjectProxy *o) { o->onSetInactive(ep); });
  1026. }
  1027. }
  1028. int ServantProxy::servant_invoke(ReqMessage *msg, bool bCoroAsync)
  1029. {
  1030. ServantPrx prx = getServantPrx(msg);
  1031. if (msg->callback)
  1032. {
  1033. msg->callback->setServantPrx(prx);
  1034. }
  1035. prx->invoke(msg, bCoroAsync);
  1036. return 0;
  1037. }
  1038. void ServantProxy::http_call(const string &funcName, shared_ptr<TC_HttpRequest> &request, shared_ptr<TC_HttpResponse> &response)
  1039. {
  1040. if (_connectionSerial <= 0)
  1041. {
  1042. _connectionSerial = DEFAULT_CONNECTION_SERIAL;
  1043. }
  1044. ReqMessage *msg = new ReqMessage();
  1045. msg->init(ReqMessage::SYNC_CALL, this);
  1046. msg->bFromRpc = true;
  1047. msg->request.sServantName = _objectProxy->name();
  1048. msg->request.sFuncName = funcName;
  1049. msg->request.sBuffer.resize(sizeof(shared_ptr<TC_HttpRequest>));
  1050. msg->deconstructor = [msg] {
  1051. shared_ptr<TC_HttpRequest> &data = *(shared_ptr<TC_HttpRequest> *)(msg->request.sBuffer.data());
  1052. data.reset();
  1053. if (!msg->response->sBuffer.empty())
  1054. {
  1055. shared_ptr<TC_HttpResponse> &rsp = *(shared_ptr<TC_HttpResponse> *)(msg->response->sBuffer.data());
  1056. //主动reset一次
  1057. rsp.reset();
  1058. msg->response->sBuffer.clear();
  1059. }
  1060. };
  1061. shared_ptr<TC_HttpRequest> &data = *(shared_ptr<TC_HttpRequest> *)(msg->request.sBuffer.data());
  1062. data = request;
  1063. servant_invoke(msg, false);
  1064. response = *(shared_ptr<TC_HttpResponse> *)(msg->response->sBuffer.data());
  1065. delete msg;
  1066. msg = NULL;
  1067. }
  1068. void ServantProxy::http_call_async(const string &funcName, shared_ptr<TC_HttpRequest> &request, const HttpCallbackPtr &cb, bool bCoro)
  1069. {
  1070. if (_connectionSerial <= 0)
  1071. {
  1072. _connectionSerial = DEFAULT_CONNECTION_SERIAL;
  1073. }
  1074. ReqMessage *msg = new ReqMessage();
  1075. msg->init(ReqMessage::ASYNC_CALL, this);
  1076. msg->bFromRpc = true;
  1077. msg->request.sServantName = _objectProxy->name();
  1078. msg->request.sFuncName = funcName;
  1079. msg->request.sBuffer.resize(sizeof(shared_ptr<TC_HttpRequest>));
  1080. msg->deconstructor = [msg] {
  1081. shared_ptr<TC_HttpRequest> &data = *(shared_ptr<TC_HttpRequest> *)(msg->request.sBuffer.data());
  1082. data.reset();
  1083. if (!msg->response->sBuffer.empty())
  1084. {
  1085. shared_ptr<TC_HttpResponse> &rsp = *(shared_ptr<TC_HttpResponse> *)(msg->response->sBuffer.data());
  1086. //主动reset一次
  1087. rsp.reset();
  1088. msg->response->sBuffer.clear();
  1089. }
  1090. };
  1091. *(shared_ptr<TC_HttpRequest> *)(msg->request.sBuffer.data()) = request;
  1092. ServantProxyCallbackPtr callback = new HttpServantProxyCallback(cb);
  1093. msg->callback = callback;
  1094. servant_invoke(msg, bCoro);
  1095. }
  1096. void ServantProxy::common_protocol_call(const string &funcName, shared_ptr<TC_CustomProtoReq> &request, shared_ptr<TC_CustomProtoRsp> &response)
  1097. {
  1098. if (_connectionSerial <= 0)
  1099. {
  1100. _connectionSerial = DEFAULT_CONNECTION_SERIAL;
  1101. }
  1102. ReqMessage *msg = new ReqMessage();
  1103. msg->init(ReqMessage::SYNC_CALL, this);
  1104. msg->bFromRpc = true;
  1105. msg->request.sFuncName = funcName;
  1106. msg->request.sBuffer.resize(sizeof(shared_ptr<TC_CustomProtoReq>));
  1107. msg->deconstructor = [msg] {
  1108. shared_ptr<TC_CustomProtoReq> &data = *(shared_ptr<TC_CustomProtoReq> *)(msg->request.sBuffer.data());
  1109. data.reset();
  1110. if (!msg->response->sBuffer.empty())
  1111. {
  1112. shared_ptr<TC_CustomProtoRsp> &rsp = *(shared_ptr<TC_CustomProtoRsp> *)(msg->response->sBuffer.data());
  1113. //主动reset一次
  1114. rsp.reset();
  1115. msg->response->sBuffer.clear();
  1116. }
  1117. };
  1118. shared_ptr<TC_CustomProtoReq> &data = *(shared_ptr<TC_CustomProtoReq> *)(msg->request.sBuffer.data());
  1119. data = request;
  1120. servant_invoke(msg, false);
  1121. response = *(shared_ptr<TC_CustomProtoRsp> *)(msg->response->sBuffer.data());
  1122. delete msg;
  1123. msg = NULL;
  1124. }
  1125. void ServantProxy::common_protocol_call_async(const string &funcName, shared_ptr<TC_CustomProtoReq> &request, const ServantProxyCallbackPtr &cb, bool bCoro)
  1126. {
  1127. if (_connectionSerial <= 0)
  1128. {
  1129. _connectionSerial = DEFAULT_CONNECTION_SERIAL;
  1130. }
  1131. ReqMessage *msg = new ReqMessage();
  1132. msg->init(ReqMessage::ASYNC_CALL, this);
  1133. msg->bFromRpc = true;
  1134. msg->request.sFuncName = funcName;
  1135. msg->request.sServantName = tars_name();
  1136. msg->request.sBuffer.resize(sizeof(shared_ptr<TC_CustomProtoReq>));
  1137. msg->deconstructor = [msg] {
  1138. shared_ptr<TC_CustomProtoReq> &data = *(shared_ptr<TC_CustomProtoReq> *)(msg->request.sBuffer.data());
  1139. data.reset();
  1140. if (!msg->response->sBuffer.empty())
  1141. {
  1142. shared_ptr<TC_CustomProtoRsp> &rsp = *(shared_ptr<TC_CustomProtoRsp> *)(msg->response->sBuffer.data());
  1143. //主动reset一次
  1144. rsp.reset();
  1145. msg->response->sBuffer.clear();
  1146. }
  1147. };
  1148. *(shared_ptr<TC_CustomProtoReq> *)(msg->request.sBuffer.data()) = request;
  1149. msg->callback = cb;
  1150. servant_invoke(msg, bCoro);
  1151. }
  1152. //
  1153. //选取一个网络线程对应的信息
  1154. void ServantProxy::selectNetThreadInfo(ServantProxyThreadData *pSptd, ObjectProxy *&pObjProxy, shared_ptr<ReqInfoQueue> &pReqQ)
  1155. {
  1156. if(pSptd->_sched && pSptd->_communicatorEpoll == NULL)
  1157. {
  1158. //处于业务线程中, 且当前业务线程是以协程模式启动;
  1159. auto schedCommunicatorEpollInfo = pSptd->getSchedCommunicatorEpollInfo(_communicator);
  1160. shared_ptr<CommunicatorEpoll> ce;
  1161. if (!schedCommunicatorEpollInfo->_communicator)
  1162. {
  1163. //当前协程没有关联过私有网络通信器, 需要新建!
  1164. pReqQ = std::make_shared<ReqInfoQueue>(_communicator->getCommunicatorEpoll(0)->getNoSendQueueLimit());
  1165. ce = _communicator->createSchedCommunicatorEpoll(pSptd->_reqQNo, pReqQ);
  1166. schedCommunicatorEpollInfo->_communicator = _communicator;
  1167. schedCommunicatorEpollInfo->_info._reqQueue = pReqQ;
  1168. schedCommunicatorEpollInfo->_info._communicatorEpoll = ce;
  1169. pObjProxy = ce->createObjectProxy(this, this->tars_full_name(), this->tars_setName());
  1170. pObjProxy->initialize(true);
  1171. }
  1172. else
  1173. {
  1174. //网络通信器已经初始化过, 直接获取对象
  1175. pReqQ = schedCommunicatorEpollInfo->_info._reqQueue.lock();
  1176. ce = schedCommunicatorEpollInfo->_info._communicatorEpoll.lock();
  1177. if(ce && pReqQ)
  1178. {
  1179. pObjProxy = ce->hasObjectProxy(this->tars_full_name(), this->tars_setName());
  1180. //创建对应的ObjectProxy
  1181. if(!pObjProxy)
  1182. {
  1183. pObjProxy = ce->createObjectProxy(this, this->tars_full_name(), this->tars_setName());
  1184. pObjProxy->initialize(true);
  1185. }
  1186. }
  1187. else
  1188. {
  1189. // assert(false);
  1190. throw TarsCommunicatorException("communicator may deconstruct");
  1191. }
  1192. }
  1193. }
  1194. else
  1195. {
  1196. if( pSptd->_communicatorEpoll )
  1197. {
  1198. //处于网咯线程中
  1199. auto communicatorEpollInfo = pSptd->getCommunicatorEpollInfo(_communicator);
  1200. assert(communicatorEpollInfo->_info.size() == 1);
  1201. assert(communicatorEpollInfo->_info[0]._communicatorEpoll.lock().get() == pSptd->_communicatorEpoll);
  1202. pObjProxy = pSptd->_communicatorEpoll->servantToObjectProxy(this);
  1203. pReqQ = communicatorEpollInfo->_info[0]._reqQueue.lock();
  1204. }
  1205. else
  1206. {
  1207. //处于普通线程中, 判断当前线程是否关联过网络通信器, 没关联, 则关联所有的公有通信器, 即创建和公有网络通信器的队列!
  1208. auto communicatorEpollInfo = pSptd->getCommunicatorEpollInfo(_communicator);
  1209. //当前线程没有关联业务通信器, 需要关联
  1210. if (!communicatorEpollInfo->_communicator)
  1211. {
  1212. communicatorEpollInfo->_communicator = _communicator;
  1213. //为每个网络线程都创建一个队列
  1214. for (size_t i = 0; i < _communicator->getCommunicatorEpollNum(); ++i)
  1215. {
  1216. shared_ptr<CommunicatorEpoll> ce = _communicator->getCommunicatorEpoll(i);
  1217. pSptd->addCommunicatorEpoll(ce);
  1218. }
  1219. }
  1220. if(communicatorEpollInfo->_communicator->isTerminating())
  1221. {
  1222. throw TarsCommunicatorException("communicator may deconstruct");
  1223. }
  1224. assert(!communicatorEpollInfo->_communicator->isTerminating());
  1225. assert(communicatorEpollInfo->_netSeq < _communicator->getCommunicatorEpollNum());
  1226. //循环使用下一个网络线程发送数据
  1227. auto ce = communicatorEpollInfo->_info[communicatorEpollInfo->_netSeq]._communicatorEpoll.lock();
  1228. if (ce)
  1229. {
  1230. pObjProxy = ce->servantToObjectProxy(this);
  1231. pReqQ = communicatorEpollInfo->_info[communicatorEpollInfo->_netSeq]._reqQueue.lock();
  1232. communicatorEpollInfo->_netSeq++;
  1233. if (communicatorEpollInfo->_netSeq == _communicator->getCommunicatorEpollNum())
  1234. communicatorEpollInfo->_netSeq = 0;
  1235. }
  1236. }
  1237. if(!pReqQ)
  1238. {
  1239. //队列已经析构, 说明通信器已经释放了!
  1240. throw TarsCommunicatorException("communicator has deconstructed");
  1241. }
  1242. }
  1243. }
  1244. void ServantProxy::checkDye(RequestPacket& req)
  1245. {
  1246. //线程私有数据
  1247. ServantProxyThreadData *pSptd = ServantProxyThreadData::getData();
  1248. assert(pSptd != NULL);
  1249. if (pSptd && pSptd->_data._dyeing)
  1250. {
  1251. SET_MSG_TYPE(req.iMessageType, TARSMESSAGETYPEDYED);
  1252. req.status[ServantProxy::STATUS_DYED_KEY] = pSptd->_data._dyeingKey;
  1253. }
  1254. }
  1255. void ServantProxy::checkTrace(RequestPacket &req)
  1256. {
  1257. //线程私有数据
  1258. ServantProxyThreadData *pSptd = ServantProxyThreadData::getData();
  1259. assert(pSptd != NULL);
  1260. if (pSptd && pSptd->_traceCall)
  1261. {
  1262. SET_MSG_TYPE(req.iMessageType, tars::TARSMESSAGETYPETRACE);
  1263. req.status[ServantProxy::STATUS_TRACE_KEY] = pSptd->getTraceKey();
  1264. }
  1265. }
  1266. void ServantProxy::checkCookie(RequestPacket &req)
  1267. {
  1268. //线程私有数据
  1269. ServantProxyThreadData *pSptd = ServantProxyThreadData::getData();
  1270. assert(pSptd != NULL);
  1271. std::for_each(pSptd->_data._cookie.begin(), pSptd->_data._cookie.end(), [&](map<string, string>::value_type &p) {
  1272. req.status.insert(make_pair(p.first, p.second));
  1273. });
  1274. }
  1275. void ServantProxy::tars_endpoints(vector<EndpointInfo> &activeEndPoint, vector<EndpointInfo> &inactiveEndPoint)
  1276. {
  1277. _endpointInfo->getEndpoint(activeEndPoint, inactiveEndPoint);
  1278. }
  1279. void ServantProxy::tars_endpointsAll(vector<EndpointInfo> &activeEndPoint, vector<EndpointInfo> &inactiveEndPoint)
  1280. {
  1281. _endpointInfo->getEndpointByAll(activeEndPoint, inactiveEndPoint);
  1282. }
  1283. void ServantProxy::tars_endpointsBySet(const string & sName,vector<EndpointInfo> &activeEndPoint, vector<EndpointInfo> &inactiveEndPoint)
  1284. {
  1285. _endpointInfo->getEndpointBySet(sName, activeEndPoint, inactiveEndPoint);
  1286. }
  1287. void ServantProxy::tars_endpointsByStation(const string & sName,vector<EndpointInfo> &activeEndPoint, vector<EndpointInfo> &inactiveEndPoint)
  1288. {
  1289. _endpointInfo->getEndpointByStation(sName, activeEndPoint, inactiveEndPoint);
  1290. }
  1291. vector<TC_Endpoint> ServantProxy::tars_endpoints(const std::string & sStation)
  1292. {
  1293. vector<TC_Endpoint> activeEndPoint;
  1294. vector<TC_Endpoint> inactiveEndPoint;
  1295. _endpointInfo->getTCEndpoint(activeEndPoint, inactiveEndPoint);
  1296. return activeEndPoint;
  1297. }
  1298. void ServantProxy::tars_endpoints(const std::string & sStation, vector<TC_Endpoint> & vecActive, vector<TC_Endpoint> & vecInactive)
  1299. {
  1300. _endpointInfo->getTCEndpointByStation(sStation, vecActive, vecInactive);
  1301. }
  1302. vector<TC_Endpoint> ServantProxy::getEndpoint()
  1303. {
  1304. vector<TC_Endpoint> activeEndPoint;
  1305. vector<TC_Endpoint> inactiveEndPoint;
  1306. _endpointInfo->getTCEndpoint(activeEndPoint, inactiveEndPoint);
  1307. return activeEndPoint;
  1308. }
  1309. vector<TC_Endpoint> ServantProxy::getEndpoint4All()
  1310. {
  1311. vector<TC_Endpoint> activeEndPoint;
  1312. vector<TC_Endpoint> inactiveEndPoint;
  1313. _endpointInfo->getTCEndpointByAll(activeEndPoint, inactiveEndPoint);
  1314. return activeEndPoint;
  1315. }
  1316. //////////////////////////////////////////////////////////////////////////////////////////////////
  1317. }