ServantProxy.cpp 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594
  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. TC_Endpoint ServantProxy::tars_invoke_endpoint()
  372. {
  373. ServantProxyThreadData *td = ServantProxyThreadData::getData();
  374. if (td)
  375. {
  376. return TC_Endpoint(td->_data._szHost);
  377. }
  378. return TC_Endpoint();
  379. }
  380. void ServantProxy::tars_set_proxy(ServantProxy::SERVANT_PROXY type, const TC_Endpoint &ep, const string &user, const string &pass)
  381. {
  382. _proxyBaseInfo = std::make_shared<TC_ProxyInfo::ProxyBaseInfo>();
  383. _proxyBaseInfo->ep = ep;
  384. _proxyBaseInfo->user = user;
  385. _proxyBaseInfo->pass = pass;
  386. switch (type)
  387. {
  388. case PROXY_SOCK4:
  389. _proxyBaseInfo->type = TC_ProxyInfo::eProxy_Type_Sock4;
  390. break;
  391. case PROXY_SOCK5:
  392. _proxyBaseInfo->type = TC_ProxyInfo::eProxy_Type_Sock5;
  393. break;
  394. case PROXY_HTTP:
  395. _proxyBaseInfo->type = TC_ProxyInfo::eProxy_Type_Http;
  396. break;
  397. default:
  398. assert(false);
  399. }
  400. }
  401. void ServantProxy::tars_timeout(int msecond)
  402. {
  403. //保护,超时时间不能小于_minTimeout毫秒
  404. _syncTimeout = (msecond < _minTimeout) ? _minTimeout : msecond;
  405. }
  406. int ServantProxy::tars_timeout() const
  407. {
  408. return _syncTimeout;
  409. }
  410. int ServantProxy::tars_connect_timeout() const
  411. {
  412. return _connTimeout;
  413. }
  414. void ServantProxy::tars_connect_timeout(int conTimeout)
  415. {
  416. if(conTimeout < 100)
  417. {
  418. conTimeout = 100;
  419. }
  420. _connTimeout = conTimeout;
  421. }
  422. void ServantProxy::tars_async_timeout(int msecond)
  423. {
  424. TC_LockT<TC_ThreadMutex> lock(*this);
  425. //保护,超时时间不能小于_minTimeout毫秒
  426. _asyncTimeout = (msecond < _minTimeout) ? _minTimeout : msecond;
  427. }
  428. int ServantProxy::tars_async_timeout() const
  429. {
  430. return _asyncTimeout;
  431. }
  432. void ServantProxy::tars_set_custom_callback(ServantProxy::custom_callback callback)
  433. {
  434. _callback = callback;
  435. }
  436. void ServantProxy::tars_enable_callback_hash()
  437. {
  438. _callbackHash = true;
  439. }
  440. void ServantProxy::tars_connection_serial(int connectionSerial)
  441. {
  442. assert(!_rootPrx);
  443. _connectionSerial = connectionSerial;
  444. }
  445. int ServantProxy::tars_connection_serial() const
  446. {
  447. if(_rootPrx) {
  448. return _rootPrx->tars_connection_serial();
  449. }
  450. return _connectionSerial;
  451. }
  452. void ServantProxy::tars_set_protocol(SERVANT_PROTOCOL protocol, int connectionSerial)
  453. {
  454. ProxyProtocol proto;
  455. switch(protocol)
  456. {
  457. case PROTOCOL_HTTP1:
  458. proto.requestFunc = ProxyProtocol::http1Request;
  459. proto.responseFunc = ProxyProtocol::http1Response;
  460. if(connectionSerial <= 0)
  461. connectionSerial = DEFAULT_CONNECTION_SERIAL;
  462. break;
  463. #if TARS_HTTP2
  464. case PROTOCOL_HTTP2:
  465. proto.requestFunc = ProxyProtocol::http2Request;
  466. proto.responseFunc = ProxyProtocol::http2Response;
  467. connectionSerial = 0;
  468. break;
  469. case PROTOCOL_GRPC:
  470. proto.requestFunc = ProxyProtocol::grpcRequest;
  471. proto.responseFunc = ProxyProtocol::grpcResponse;
  472. connectionSerial = 0;
  473. break;
  474. #endif
  475. case PROTOCOL_TARS:
  476. default:
  477. proto.requestFunc = ProxyProtocol::tarsRequest;
  478. proto.responseFunc = ProxyProtocol::tarsResponse;
  479. break;
  480. }
  481. tars_set_protocol(proto, connectionSerial);
  482. }
  483. void ServantProxy::tars_set_protocol(const ProxyProtocol& protocol, int connectionSerial)
  484. {
  485. TC_LockT<TC_ThreadMutex> lock(*this);
  486. _proxyProtocol = protocol;
  487. _connectionSerial = connectionSerial;
  488. }
  489. const ProxyProtocol &ServantProxy::tars_get_protocol() const
  490. {
  491. return _proxyProtocol;
  492. }
  493. vector<ServantProxy::SocketOpt> ServantProxy::tars_get_sockopt() const
  494. {
  495. TC_LockT<TC_ThreadMutex> lock(*this);
  496. return _socketOpts;
  497. }
  498. void ServantProxy::tars_set_sockopt(int level, int optname, const void *optval, SOCKET_LEN_TYPE optlen)
  499. {
  500. TC_LockT<TC_ThreadMutex> lock(*this);
  501. SocketOpt socketOpt;
  502. socketOpt.level = level;
  503. socketOpt.optname = optname;
  504. socketOpt.optval = optval;
  505. socketOpt.optlen = optlen;
  506. _socketOpts.push_back(socketOpt);
  507. }
  508. void ServantProxy::tars_set_check_timeout(const CheckTimeoutInfo& checkTimeoutInfo)
  509. {
  510. TC_LockT<TC_ThreadMutex> lock(*this);
  511. _checkTimeoutInfo = checkTimeoutInfo;
  512. }
  513. CheckTimeoutInfo ServantProxy::tars_get_check_timeout()
  514. {
  515. TC_LockT<TC_ThreadMutex> lock(*this);
  516. return _checkTimeoutInfo;
  517. }
  518. void ServantProxy::tars_ping()
  519. {
  520. map<string, string> m;
  521. map<string, string> s;
  522. TarsOutputStream<BufferWriterVector> os;
  523. tars_invoke(TARSNORMAL, "tars_ping", os, m, s);
  524. }
  525. void ServantProxy::tars_async_ping()
  526. {
  527. map<string, string> m;
  528. map<string, string> s;
  529. TarsOutputStream<BufferWriterVector> os;
  530. tars_invoke_async(TARSONEWAY, "tars_ping", os, m, s, NULL);
  531. }
  532. ServantProxy* ServantProxy::tars_hash(uint32_t key)
  533. {
  534. ServantProxyThreadData *pSptd = ServantProxyThreadData::getData();
  535. assert(pSptd != NULL);
  536. pSptd->_data._hash = true;
  537. pSptd->_data._hashCode = key;
  538. return this;
  539. }
  540. //ServantProxy* ServantProxy::tars_direct()
  541. //{
  542. // ServantProxyThreadData *pSptd = ServantProxyThreadData::getData();
  543. //
  544. // pSptd->_direct = true;
  545. // return this;
  546. //}
  547. ServantProxy* ServantProxy::tars_consistent_hash(uint32_t key)
  548. {
  549. ServantProxyThreadData *pSptd = ServantProxyThreadData::getData();
  550. assert(pSptd != NULL);
  551. pSptd->_data._hash = true;
  552. pSptd->_data._conHash = true;
  553. pSptd->_data._hashCode = key;
  554. return this;
  555. }
  556. ServantProxy* ServantProxy::tars_open_trace(bool traceParams)
  557. {
  558. ServantProxyThreadData *pSptd = ServantProxyThreadData::getData();
  559. assert(pSptd != NULL);
  560. if (traceParams)
  561. {
  562. pSptd->openTrace(15);
  563. }
  564. else
  565. {
  566. pSptd->openTrace();
  567. }
  568. return this;
  569. }
  570. void ServantProxy::tars_clear_hash()
  571. {
  572. }
  573. ServantProxy* ServantProxy::tars_set_timeout(int msecond)
  574. {
  575. ServantProxyThreadData *pSptd = ServantProxyThreadData::getData();
  576. assert(pSptd != NULL);
  577. // pSptd->_hasTimeout = true;
  578. pSptd->_data._timeout = msecond;
  579. return this;
  580. }
  581. uint32_t ServantProxy::tars_gen_requestid()
  582. {
  583. uint32_t i = ++_id;
  584. if (i == 0)
  585. {
  586. i = ++_id;
  587. }
  588. return i;
  589. }
  590. void ServantProxy::tars_set_push_callback(const ServantProxyCallbackPtr & cb)
  591. {
  592. _pushCallback = cb;
  593. }
  594. ServantProxyCallbackPtr ServantProxy::tars_get_push_callback()
  595. {
  596. return _pushCallback;
  597. }
  598. void ServantProxy::invoke(ReqMessage *msg, bool bCoroAsync)
  599. {
  600. //线程私有数据
  601. ServantProxyThreadData *pSptd = ServantProxyThreadData::getData();
  602. assert(pSptd != NULL);
  603. //协程调用方式, 启用协程
  604. if(bCoroAsync && TC_CoroutineScheduler::scheduler() && !pSptd->_sched)
  605. {
  606. pSptd->_sched = TC_CoroutineScheduler::scheduler();
  607. }
  608. msg->data = pSptd->move();
  609. // 调用链追踪透传
  610. msg->bTraceCall = pSptd->_traceCall;
  611. msg->sTraceKey = pSptd->getTraceKey(true);
  612. if (msg->data._dyeing)
  613. {
  614. TLOGTARS("[ServantProxy::invoke, set dyeing, key=" << pSptd->_data._dyeingKey << endl);
  615. }
  616. msg->data._cookie = pSptd->_data._cookie;
  617. // #ifdef TARS_OPENTRACKING
  618. // msg->trackInfoMap = pSptd->_trackInfoMap;
  619. // #endif
  620. //
  621. //设置超时时间
  622. msg->request.iTimeout = (ReqMessage::SYNC_CALL == msg->eType) ? _syncTimeout : _asyncTimeout;
  623. //判断是否针对接口级设置超时
  624. if (msg->data._timeout > 0)
  625. {
  626. msg->request.iTimeout = msg->data._timeout;
  627. }
  628. else
  629. {
  630. msg->request.iTimeout = (ReqMessage::SYNC_CALL == msg->eType) ? _syncTimeout : _asyncTimeout;
  631. }
  632. shared_ptr<ReqInfoQueue> pReqQ;
  633. //选择网络线程
  634. selectNetThreadInfo(pSptd, msg->pObjectProxy, pReqQ);
  635. //如果是按set规则调用
  636. if (msg->pObjectProxy && msg->pObjectProxy->isInvokeBySet())
  637. {
  638. SET_MSG_TYPE(msg->request.iMessageType, TARSMESSAGETYPESETNAME);
  639. msg->request.status[ServantProxy::STATUS_SETNAME_VALUE] = msg->pObjectProxy->getInvokeSetName();
  640. TLOGTARS("[ServantProxy::invoke, " << msg->request.sServantName << ", invoke with set," << msg->pObjectProxy->getInvokeSetName() << "]" << endl);
  641. }
  642. assert(msg->pMonitor == NULL);
  643. if (msg->eType == ReqMessage::SYNC_CALL)
  644. {
  645. if (pSptd->_sched)
  646. {
  647. msg->sched = pSptd->_sched;
  648. msg->iCoroId = pSptd->_sched->getCoroutineId();
  649. }
  650. else
  651. {
  652. //同步调用 new 一个ReqMonitor
  653. msg->pMonitor = new ReqMonitor(msg);
  654. }
  655. }
  656. else if (msg->eType == ReqMessage::ASYNC_CALL)
  657. {
  658. //是否是协程的并行请求
  659. if (bCoroAsync)
  660. {
  661. if (pSptd->_sched)
  662. {
  663. CoroParallelBasePtr coroPtr = msg->callback->getCoroParallelBasePtr();
  664. if (coroPtr)
  665. {
  666. coroPtr->incReqCount();
  667. msg->sched = pSptd->_sched;
  668. msg->iCoroId = pSptd->_sched->getCoroutineId();
  669. }
  670. else
  671. {
  672. TLOGERROR("[ServantProxy::invoke use coroutine's callback not set CoroParallelBasePtr]" << endl);
  673. delete msg;
  674. msg = NULL;
  675. throw TarsUseCoroException("use coroutine's callback not set CoroParallelBasePtr");
  676. }
  677. }
  678. else
  679. {
  680. TLOGERROR("[ServantProxy::invoke coroutine mode invoke not open]" << endl);
  681. delete msg;
  682. msg = NULL;
  683. throw TarsUseCoroException("coroutine mode invoke not open");
  684. }
  685. }
  686. }
  687. //通知网络线程
  688. bool bEmpty = false;
  689. bool bSync = (msg->eType == ReqMessage::SYNC_CALL);
  690. if (!pReqQ->push_back(msg, bEmpty))
  691. {
  692. TLOGERROR("[ServantProxy::invoke msgQueue push_back error thread seq:" << pSptd->_reqQNo << "]" << endl);
  693. delete msg;
  694. msg = NULL;
  695. throw TarsClientQueueException("client queue full");
  696. }
  697. if (msg->sched)
  698. {
  699. // LOG_CONSOLE_DEBUG << "in sched handle: " << this << ", " << msg->request.sServantName << endl;
  700. //协程中, 直接发包了
  701. msg->pObjectProxy->getCommunicatorEpoll()->handle(pSptd->_reqQNo);
  702. }
  703. else
  704. {
  705. msg->pObjectProxy->getCommunicatorEpoll()->notify(pSptd->_reqQNo);
  706. }
  707. if (bSync)
  708. {
  709. if (!msg->sched)
  710. {
  711. assert(msg->pMonitor);
  712. msg->pMonitor->wait();
  713. if(!msg->pMonitor->bMonitorFin)
  714. {
  715. TLOGERROR("[ServantProxy::invoke communicator terminate]" << endl);
  716. throw TarsCommunicatorException("communicator terminate");
  717. }
  718. }
  719. else
  720. {
  721. assert(!msg->sched->isMainCoroutine());
  722. msg->sched->yield(false);
  723. }
  724. //判断eStatus来判断状态
  725. // assert(msg->eStatus != ReqMessage::REQ_REQ);
  726. if(msg->adapter) {
  727. pSptd->_data._szHost = msg->adapter->endpoint().desc();
  728. }
  729. if(msg->eStatus == ReqMessage::REQ_RSP && msg->response->iRet == TARSSERVERSUCCESS)
  730. {
  731. //成功
  732. return;
  733. }
  734. ostringstream os;
  735. if (msg->eStatus == ReqMessage::REQ_TIME)
  736. {
  737. //超时
  738. os << "[ServantProxy::invoke timeout:" << msg->request.iTimeout;
  739. }
  740. else
  741. {
  742. os << "[ServantProxy::invoke errno:" << msg->response->iRet << ",info:" << msg->response->sResultDesc;
  743. }
  744. os << ",servant:" << msg->pObjectProxy->name() << ",func:" << msg->request.sFuncName;
  745. if (msg->adapter)
  746. os << ",adapter:" << msg->adapter->endpoint().desc();
  747. os << ",reqid:" << msg->request.iRequestId << "]";
  748. if (msg->eStatus == ReqMessage::REQ_TIME)
  749. {
  750. //超时
  751. delete msg;
  752. msg = NULL;
  753. throw TarsSyncCallTimeoutException(os.str());
  754. }
  755. //异常调用
  756. int ret = msg->response->iRet;
  757. delete msg;
  758. msg = NULL;
  759. TarsException::throwException(ret, os.str());
  760. }
  761. }
  762. //////////////////////////////////////////////////////////////////
  763. void ServantProxy::tars_invoke_async(char cPacketType,
  764. const string &sFuncName,
  765. TarsOutputStream<BufferWriterVector> &buf,
  766. const map<string, string>& context,
  767. const map<string, string>& status,
  768. const ServantProxyCallbackPtr& callback,
  769. bool bCoro)
  770. {
  771. ReqMessage *msg = new ReqMessage();
  772. msg->init(callback?ReqMessage::ASYNC_CALL:ReqMessage::ONE_WAY, this);
  773. msg->callback = callback;
  774. msg->request.iVersion = TARSVERSION;
  775. msg->request.cPacketType = (callback ? cPacketType : TARSONEWAY);
  776. msg->request.sFuncName = sFuncName;
  777. msg->request.sServantName = _objectProxy->name();
  778. buf.swap(msg->request.sBuffer);
  779. msg->request.context = context;
  780. msg->request.status = status;
  781. msg->request.iTimeout = _asyncTimeout;
  782. // // 在RequestPacket中的context设置主调信息
  783. // if(_masterFlag)
  784. // {
  785. // msg->request.context.insert(std::make_pair(TARS_MASTER_KEY,ClientConfig::ModuleName)); //TARS_MASTER_KEY clientConfig.ModuleName
  786. // }
  787. checkDye(msg->request);
  788. checkTrace(msg->request);
  789. checkCookie(msg->request);
  790. servant_invoke(msg, bCoro);
  791. }
  792. //////////////////////////////////////////////////////////////////
  793. void ServantProxy::tars_invoke_async(char cPacketType,
  794. const string &sFuncName,
  795. const vector<char> &buf,
  796. const map<string, string>& context,
  797. const map<string, string>& status,
  798. const ServantProxyCallbackPtr& callback,
  799. bool bCoro)
  800. {
  801. ReqMessage * msg = new ReqMessage();
  802. msg->init(callback?ReqMessage::ASYNC_CALL:ReqMessage::ONE_WAY, this);
  803. msg->callback = callback;
  804. msg->request.iVersion = TARSVERSION;
  805. msg->request.cPacketType = (callback ? cPacketType : TARSONEWAY);
  806. msg->request.sFuncName = sFuncName;
  807. msg->request.sServantName = _objectProxy->name();
  808. msg->request.sBuffer = buf;
  809. msg->request.context = context;
  810. msg->request.status = status;
  811. msg->request.iTimeout = _asyncTimeout;
  812. // // 在RequestPacket中的context设置主调信息
  813. // if(_masterFlag)
  814. // {
  815. // msg->request.context.insert(std::make_pair(TARS_MASTER_KEY,ClientConfig::ModuleName)); //TARS_MASTER_KEY clientConfig.ModuleName
  816. // }
  817. checkDye(msg->request);
  818. checkTrace(msg->request);
  819. checkCookie(msg->request);
  820. servant_invoke(msg, bCoro);
  821. }
  822. shared_ptr<ResponsePacket> ServantProxy::tars_invoke(char cPacketType,
  823. const string& sFuncName,
  824. const vector<char>& buf,
  825. const map<string, string>& context,
  826. const map<string, string>& status)
  827. // ResponsePacket& rsp)
  828. {
  829. ReqMessage *msg = new ReqMessage();
  830. msg->init(ReqMessage::SYNC_CALL, this);
  831. msg->request.iVersion = TARSVERSION;
  832. msg->request.cPacketType = cPacketType;
  833. msg->request.sFuncName = sFuncName;
  834. msg->request.sServantName = _objectProxy->name();
  835. msg->request.sBuffer = buf;
  836. msg->request.context = context;
  837. msg->request.status = status;
  838. msg->request.iTimeout = _syncTimeout;
  839. // // 在RequestPacket中的context设置主调信息
  840. // if(_masterFlag)
  841. // {
  842. // msg->request.context.insert(std::make_pair(TARS_MASTER_KEY,ClientConfig::ModuleName));
  843. // }
  844. checkDye(msg->request);
  845. checkTrace(msg->request);
  846. checkCookie(msg->request);
  847. servant_invoke(msg, false);
  848. shared_ptr<ResponsePacket> rsp = msg->response;
  849. // rsp = msg->response;
  850. delete msg;
  851. msg = NULL;
  852. return rsp;
  853. }
  854. shared_ptr<ResponsePacket> ServantProxy::tars_invoke(char cPacketType,
  855. const string& sFuncName,
  856. TarsOutputStream<BufferWriterVector>& buf,
  857. const map<string, string>& context,
  858. const map<string, string>& status)
  859. {
  860. ReqMessage * msg = new ReqMessage();
  861. msg->init(ReqMessage::SYNC_CALL, this);
  862. msg->request.iVersion = TARSVERSION;
  863. msg->request.cPacketType = cPacketType;
  864. msg->request.sFuncName = sFuncName;
  865. msg->request.sServantName = _objectProxy->name();
  866. buf.swap(msg->request.sBuffer);
  867. msg->request.context = context;
  868. msg->request.status = status;
  869. msg->request.iTimeout = _syncTimeout;
  870. checkDye(msg->request);
  871. checkTrace(msg->request);
  872. checkCookie(msg->request);
  873. servant_invoke(msg, false);
  874. shared_ptr<ResponsePacket> rsp = msg->response;
  875. delete msg;
  876. msg = NULL;
  877. return rsp;
  878. }
  879. //////////////////////////////////////////////////////////////////////////////
  880. //服务端是非tars协议,通过rpc_call调用
  881. void ServantProxy::rpc_call(uint32_t iRequestId,
  882. const string& sFuncName,
  883. const char* buff,
  884. uint32_t len,
  885. ResponsePacket& rsp)
  886. {
  887. ReqMessage *msg = new ReqMessage();
  888. msg->init(ReqMessage::SYNC_CALL, this);
  889. msg->bFromRpc = true;
  890. msg->request.sServantName = _objectProxy->name();
  891. msg->request.sFuncName = sFuncName;
  892. msg->request.iRequestId = iRequestId;
  893. msg->request.sBuffer.assign(buff, buff + len);
  894. servant_invoke(msg, false);
  895. rsp = *msg->response.get();
  896. delete msg;
  897. msg = NULL;
  898. }
  899. void ServantProxy::rpc_call_async(uint32_t iRequestId,
  900. const string& sFuncName,
  901. const char* buff,
  902. uint32_t len,
  903. const ServantProxyCallbackPtr& callback,
  904. bool bCoro)
  905. {
  906. ReqMessage *msg = new ReqMessage();
  907. msg->init(callback ? ReqMessage::ASYNC_CALL : ReqMessage::ONE_WAY, this);
  908. msg->bFromRpc = true;
  909. msg->callback = callback;
  910. msg->request.sServantName = _objectProxy->name();
  911. msg->request.sFuncName = sFuncName;
  912. msg->request.iRequestId = iRequestId;
  913. msg->request.sBuffer.assign(buff, buff + len);
  914. servant_invoke(msg, bCoro);
  915. }
  916. ServantPrx ServantProxy::getServantPrx(ReqMessage *msg)
  917. {
  918. if (_servantId == 0)
  919. {
  920. std::lock_guard<std::mutex> m(_servantMutex);
  921. if (_servantId == 0 && _servantList.empty())
  922. {
  923. for (int i = 1; i < _connectionSerial; ++i)
  924. {
  925. string obj = tars_name() + "#" + TC_Common::tostr(i);
  926. if (!_objectProxy->address().empty())
  927. {
  928. obj += "@" + _objectProxy->address();
  929. }
  930. ServantPrx prx = _communicator->stringToProxy<ServantPrx>(obj, this->tars_setName(), false);
  931. prx->tars_set_protocol(tars_get_protocol());
  932. prx->tars_connect_timeout(tars_connect_timeout());
  933. prx->tars_timeout(tars_timeout());
  934. prx->tars_async_timeout(tars_async_timeout());
  935. prx->_rootPrx = this;
  936. _servantList.push_back(prx);
  937. }
  938. }
  939. }
  940. if (_connectionSerial != 0)
  941. {
  942. assert(int(_servantList.size() + 1) == _connectionSerial);
  943. }
  944. int id = _servantId++ % (_servantList.size() + 1);
  945. if (id == 0)
  946. {
  947. return this;
  948. }
  949. return _servantList[(id - 1)];
  950. }
  951. void ServantProxy::travelObjectProxys(ServantProxy *prx, function<void(ObjectProxy*)> f)
  952. {
  953. vector<ObjectProxy*> objectProxys;
  954. size_t num = _communicator->getCommunicatorEpollNum();
  955. for (size_t i = 0; i < num; ++i)
  956. {
  957. auto ce = _communicator->getCommunicatorEpoll(i);
  958. ObjectProxy* objectProxy = ce->servantToObjectProxy(prx);
  959. if (objectProxy)
  960. {
  961. f(objectProxy);
  962. }
  963. }
  964. //协程通信器也需要
  965. _communicator->forEachSchedCommunicatorEpoll([&](const shared_ptr<CommunicatorEpoll>& ce)
  966. {
  967. ObjectProxy* objectProxy = ce->servantToObjectProxy(prx);
  968. if (objectProxy)
  969. {
  970. f(objectProxy);
  971. }
  972. });
  973. }
  974. vector<ObjectProxy*> ServantProxy::getObjectProxys()
  975. {
  976. vector<ObjectProxy*> objectProxys;
  977. //更新子servant proxy的地址
  978. for (size_t i = 0; i < _servantList.size(); i++)
  979. {
  980. ServantProxy* prx = _servantList[i].get();
  981. travelObjectProxys(prx, [&](ObjectProxy *op){
  982. objectProxys.push_back(op);
  983. });
  984. }
  985. travelObjectProxys(this, [&](ObjectProxy *op){
  986. objectProxys.push_back(op);
  987. });
  988. return objectProxys;
  989. }
  990. void ServantProxy::tars_update_endpoints(const set<EndpointInfo> &active, const set<EndpointInfo> &inactive)
  991. {
  992. onNotifyEndpoints(NULL, active, inactive);
  993. }
  994. void ServantProxy::onNotifyEndpoints(CommunicatorEpoll *communicatorEpoll, const set<EndpointInfo> &active, const set<EndpointInfo> &inactive)
  995. {
  996. //更新子servant proxy的地址
  997. for (size_t i = 0; i < _servantList.size(); i++)
  998. {
  999. ServantProxy* prx = _servantList[i].get();
  1000. travelObjectProxys(prx, [&](ObjectProxy *op){
  1001. if(op->getEndpointManager())
  1002. {
  1003. op->getEndpointManager()->updateEndpointsOutter(active, inactive);
  1004. }
  1005. });
  1006. }
  1007. travelObjectProxys(this, [&](ObjectProxy *op){
  1008. if(op->getEndpointManager())
  1009. {
  1010. op->getEndpointManager()->updateEndpointsOutter(active, inactive);
  1011. }
  1012. });
  1013. }
  1014. void ServantProxy::onSetInactive(const EndpointInfo &ep)
  1015. {
  1016. if (!_rootPrx)
  1017. return;
  1018. for (size_t i = 0; i < _rootPrx->_servantList.size(); i++)
  1019. {
  1020. ServantPrx &prx = _rootPrx->_servantList[i];
  1021. prx->forEachObject([&](ObjectProxy *o) { o->onSetInactive(ep); });
  1022. }
  1023. }
  1024. int ServantProxy::servant_invoke(ReqMessage *msg, bool bCoroAsync)
  1025. {
  1026. ServantPrx prx = getServantPrx(msg);
  1027. if (msg->callback)
  1028. {
  1029. msg->callback->setServantPrx(prx);
  1030. }
  1031. prx->invoke(msg, bCoroAsync);
  1032. return 0;
  1033. }
  1034. void ServantProxy::http_call(const string &funcName, shared_ptr<TC_HttpRequest> &request, shared_ptr<TC_HttpResponse> &response)
  1035. {
  1036. if (_connectionSerial <= 0)
  1037. {
  1038. _connectionSerial = DEFAULT_CONNECTION_SERIAL;
  1039. }
  1040. ReqMessage *msg = new ReqMessage();
  1041. msg->init(ReqMessage::SYNC_CALL, this);
  1042. msg->bFromRpc = true;
  1043. msg->request.sServantName = _objectProxy->name();
  1044. msg->request.sFuncName = funcName;
  1045. msg->request.sBuffer.resize(sizeof(shared_ptr<TC_HttpRequest>));
  1046. msg->deconstructor = [msg] {
  1047. shared_ptr<TC_HttpRequest> &data = *(shared_ptr<TC_HttpRequest> *)(msg->request.sBuffer.data());
  1048. data.reset();
  1049. if (!msg->response->sBuffer.empty())
  1050. {
  1051. shared_ptr<TC_HttpResponse> &rsp = *(shared_ptr<TC_HttpResponse> *)(msg->response->sBuffer.data());
  1052. //主动reset一次
  1053. rsp.reset();
  1054. msg->response->sBuffer.clear();
  1055. }
  1056. };
  1057. shared_ptr<TC_HttpRequest> &data = *(shared_ptr<TC_HttpRequest> *)(msg->request.sBuffer.data());
  1058. data = request;
  1059. servant_invoke(msg, false);
  1060. response = *(shared_ptr<TC_HttpResponse> *)(msg->response->sBuffer.data());
  1061. delete msg;
  1062. msg = NULL;
  1063. }
  1064. void ServantProxy::http_call_async(const string &funcName, shared_ptr<TC_HttpRequest> &request, const HttpCallbackPtr &cb, bool bCoro)
  1065. {
  1066. if (_connectionSerial <= 0)
  1067. {
  1068. _connectionSerial = DEFAULT_CONNECTION_SERIAL;
  1069. }
  1070. ReqMessage *msg = new ReqMessage();
  1071. msg->init(ReqMessage::ASYNC_CALL, this);
  1072. msg->bFromRpc = true;
  1073. msg->request.sServantName = _objectProxy->name();
  1074. msg->request.sFuncName = funcName;
  1075. msg->request.sBuffer.resize(sizeof(shared_ptr<TC_HttpRequest>));
  1076. msg->deconstructor = [msg] {
  1077. shared_ptr<TC_HttpRequest> &data = *(shared_ptr<TC_HttpRequest> *)(msg->request.sBuffer.data());
  1078. data.reset();
  1079. if (!msg->response->sBuffer.empty())
  1080. {
  1081. shared_ptr<TC_HttpResponse> &rsp = *(shared_ptr<TC_HttpResponse> *)(msg->response->sBuffer.data());
  1082. //主动reset一次
  1083. rsp.reset();
  1084. msg->response->sBuffer.clear();
  1085. }
  1086. };
  1087. *(shared_ptr<TC_HttpRequest> *)(msg->request.sBuffer.data()) = request;
  1088. ServantProxyCallbackPtr callback = new HttpServantProxyCallback(cb);
  1089. msg->callback = callback;
  1090. servant_invoke(msg, bCoro);
  1091. }
  1092. //
  1093. //选取一个网络线程对应的信息
  1094. void ServantProxy::selectNetThreadInfo(ServantProxyThreadData *pSptd, ObjectProxy *&pObjProxy, shared_ptr<ReqInfoQueue> &pReqQ)
  1095. {
  1096. if(pSptd->_sched && pSptd->_communicatorEpoll == NULL)
  1097. {
  1098. //处于业务线程中, 且当前业务线程是以协程模式启动;
  1099. auto schedCommunicatorEpollInfo = pSptd->getSchedCommunicatorEpollInfo(_communicator);
  1100. shared_ptr<CommunicatorEpoll> ce;
  1101. if (!schedCommunicatorEpollInfo->_communicator)
  1102. {
  1103. //当前协程没有关联过私有网络通信器, 需要新建!
  1104. pReqQ = std::make_shared<ReqInfoQueue>(_communicator->getCommunicatorEpoll(0)->getNoSendQueueLimit());
  1105. ce = _communicator->createSchedCommunicatorEpoll(pSptd->_reqQNo, pReqQ);
  1106. schedCommunicatorEpollInfo->_communicator = _communicator;
  1107. schedCommunicatorEpollInfo->_info._reqQueue = pReqQ;
  1108. schedCommunicatorEpollInfo->_info._communicatorEpoll = ce;
  1109. pObjProxy = ce->createObjectProxy(this, this->tars_full_name(), this->tars_setName());
  1110. pObjProxy->initialize(true);
  1111. }
  1112. else
  1113. {
  1114. //网络通信器已经初始化过, 直接获取对象
  1115. pReqQ = schedCommunicatorEpollInfo->_info._reqQueue.lock();
  1116. ce = schedCommunicatorEpollInfo->_info._communicatorEpoll.lock();
  1117. if(ce && pReqQ)
  1118. {
  1119. pObjProxy = ce->hasObjectProxy(this->tars_full_name(), this->tars_setName());
  1120. //创建对应的ObjectProxy
  1121. if(!pObjProxy)
  1122. {
  1123. pObjProxy = ce->createObjectProxy(this, this->tars_full_name(), this->tars_setName());
  1124. pObjProxy->initialize(true);
  1125. }
  1126. }
  1127. else
  1128. {
  1129. // assert(false);
  1130. throw TarsCommunicatorException("communicator may deconstruct");
  1131. }
  1132. }
  1133. }
  1134. else
  1135. {
  1136. if( pSptd->_communicatorEpoll )
  1137. {
  1138. auto info = pSptd->getCommunicatorEpollInfo(_communicator);
  1139. assert(info->_info.size() == 1);
  1140. assert(info->_info[0]._communicatorEpoll.lock().get() == pSptd->_communicatorEpoll);
  1141. pObjProxy = pSptd->_communicatorEpoll->servantToObjectProxy(this);
  1142. pReqQ = info->_info[0]._reqQueue.lock();
  1143. }
  1144. else
  1145. {
  1146. //处于普通线程中, 判断当前线程是否关联过网络通信器, 没关联, 则关联所有的公有通信器, 即创建和公有网络通信器的队列!
  1147. auto communicatorEpollInfo = pSptd->getCommunicatorEpollInfo(_communicator);
  1148. //当前线程没有关联业务通信器, 需要关联
  1149. if (!communicatorEpollInfo->_communicator)
  1150. {
  1151. communicatorEpollInfo->_communicator = _communicator;
  1152. //为每个网络线程都创建一个队列
  1153. for (size_t i = 0; i < _communicator->getCommunicatorEpollNum(); ++i)
  1154. {
  1155. shared_ptr<CommunicatorEpoll> ce = _communicator->getCommunicatorEpoll(i);
  1156. pSptd->addCommunicatorEpoll(ce);
  1157. }
  1158. }
  1159. assert(communicatorEpollInfo->_netSeq < _communicator->getCommunicatorEpollNum());
  1160. //循环使用下一个网络线程发送数据
  1161. auto ce = communicatorEpollInfo->_info[communicatorEpollInfo->_netSeq]._communicatorEpoll.lock();
  1162. if (ce)
  1163. {
  1164. pObjProxy = ce->servantToObjectProxy(this);
  1165. pReqQ = communicatorEpollInfo->_info[communicatorEpollInfo->_netSeq]._reqQueue.lock();
  1166. communicatorEpollInfo->_netSeq++;
  1167. if (communicatorEpollInfo->_netSeq == _communicator->getCommunicatorEpollNum())
  1168. communicatorEpollInfo->_netSeq = 0;
  1169. }
  1170. }
  1171. if(!pReqQ)
  1172. {
  1173. //队列已经析构, 说明通信器已经释放了!
  1174. throw TarsCommunicatorException("communicator has deconstructed");
  1175. }
  1176. }
  1177. }
  1178. void ServantProxy::checkDye(RequestPacket& req)
  1179. {
  1180. //线程私有数据
  1181. ServantProxyThreadData *pSptd = ServantProxyThreadData::getData();
  1182. assert(pSptd != NULL);
  1183. if (pSptd && pSptd->_data._dyeing)
  1184. {
  1185. SET_MSG_TYPE(req.iMessageType, TARSMESSAGETYPEDYED);
  1186. req.status[ServantProxy::STATUS_DYED_KEY] = pSptd->_data._dyeingKey;
  1187. }
  1188. }
  1189. void ServantProxy::checkTrace(RequestPacket &req)
  1190. {
  1191. //线程私有数据
  1192. ServantProxyThreadData *pSptd = ServantProxyThreadData::getData();
  1193. assert(pSptd != NULL);
  1194. if (pSptd && pSptd->_traceCall)
  1195. {
  1196. SET_MSG_TYPE(req.iMessageType, tars::TARSMESSAGETYPETRACE);
  1197. req.status[ServantProxy::STATUS_TRACE_KEY] = pSptd->getTraceKey();
  1198. }
  1199. }
  1200. void ServantProxy::checkCookie(RequestPacket &req)
  1201. {
  1202. //线程私有数据
  1203. ServantProxyThreadData *pSptd = ServantProxyThreadData::getData();
  1204. assert(pSptd != NULL);
  1205. std::for_each(pSptd->_data._cookie.begin(), pSptd->_data._cookie.end(), [&](map<string, string>::value_type &p) {
  1206. req.status.insert(make_pair(p.first, p.second));
  1207. });
  1208. }
  1209. void ServantProxy::tars_endpoints(vector<EndpointInfo> &activeEndPoint, vector<EndpointInfo> &inactiveEndPoint)
  1210. {
  1211. _endpointInfo->getEndpoint(activeEndPoint, inactiveEndPoint);
  1212. }
  1213. void ServantProxy::tars_endpointsAll(vector<EndpointInfo> &activeEndPoint, vector<EndpointInfo> &inactiveEndPoint)
  1214. {
  1215. _endpointInfo->getEndpointByAll(activeEndPoint, inactiveEndPoint);
  1216. }
  1217. void ServantProxy::tars_endpointsBySet(const string & sName,vector<EndpointInfo> &activeEndPoint, vector<EndpointInfo> &inactiveEndPoint)
  1218. {
  1219. _endpointInfo->getEndpointBySet(sName, activeEndPoint, inactiveEndPoint);
  1220. }
  1221. void ServantProxy::tars_endpointsByStation(const string & sName,vector<EndpointInfo> &activeEndPoint, vector<EndpointInfo> &inactiveEndPoint)
  1222. {
  1223. _endpointInfo->getEndpointByStation(sName, activeEndPoint, inactiveEndPoint);
  1224. }
  1225. vector<TC_Endpoint> ServantProxy::tars_endpoints(const std::string & sStation)
  1226. {
  1227. vector<TC_Endpoint> activeEndPoint;
  1228. vector<TC_Endpoint> inactiveEndPoint;
  1229. _endpointInfo->getTCEndpoint(activeEndPoint, inactiveEndPoint);
  1230. return activeEndPoint;
  1231. }
  1232. void ServantProxy::tars_endpoints(const std::string & sStation, vector<TC_Endpoint> & vecActive, vector<TC_Endpoint> & vecInactive)
  1233. {
  1234. _endpointInfo->getTCEndpointByStation(sStation, vecActive, vecInactive);
  1235. }
  1236. vector<TC_Endpoint> ServantProxy::getEndpoint()
  1237. {
  1238. vector<TC_Endpoint> activeEndPoint;
  1239. vector<TC_Endpoint> inactiveEndPoint;
  1240. _endpointInfo->getTCEndpoint(activeEndPoint, inactiveEndPoint);
  1241. return activeEndPoint;
  1242. }
  1243. vector<TC_Endpoint> ServantProxy::getEndpoint4All()
  1244. {
  1245. vector<TC_Endpoint> activeEndPoint;
  1246. vector<TC_Endpoint> inactiveEndPoint;
  1247. _endpointInfo->getTCEndpointByAll(activeEndPoint, inactiveEndPoint);
  1248. return activeEndPoint;
  1249. }
  1250. //////////////////////////////////////////////////////////////////////////////////////////////////
  1251. }