1
0

ServantProxy.cpp 43 KB

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