ServantProxy.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602
  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(int64_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(int64_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. // ResponsePacket& rsp)
  860. {
  861. ReqMessage * msg = new ReqMessage();
  862. msg->init(ReqMessage::SYNC_CALL, this);
  863. msg->request.iVersion = TARSVERSION;
  864. msg->request.cPacketType = cPacketType;
  865. msg->request.sFuncName = sFuncName;
  866. msg->request.sServantName = _objectProxy->name();
  867. buf.swap(msg->request.sBuffer);
  868. msg->request.context = context;
  869. msg->request.status = status;
  870. msg->request.iTimeout = _syncTimeout;
  871. // // 在RequestPacket中的context设置主调信息
  872. // if(_masterFlag)
  873. // {
  874. // msg->request.context.insert(std::make_pair(TARS_MASTER_KEY,ClientConfig::ModuleName));
  875. // }
  876. checkDye(msg->request);
  877. checkTrace(msg->request);
  878. checkCookie(msg->request);
  879. servant_invoke(msg, false);
  880. shared_ptr<ResponsePacket> rsp = msg->response;
  881. // rsp = msg->response;
  882. delete msg;
  883. msg = NULL;
  884. return rsp;
  885. }
  886. //////////////////////////////////////////////////////////////////////////////
  887. //服务端是非tars协议,通过rpc_call调用
  888. void ServantProxy::rpc_call(uint32_t iRequestId,
  889. const string& sFuncName,
  890. const char* buff,
  891. uint32_t len,
  892. ResponsePacket& rsp)
  893. {
  894. ReqMessage *msg = new ReqMessage();
  895. msg->init(ReqMessage::SYNC_CALL, this);
  896. msg->bFromRpc = true;
  897. msg->request.sServantName = _objectProxy->name();
  898. msg->request.sFuncName = sFuncName;
  899. msg->request.iRequestId = iRequestId;
  900. msg->request.sBuffer.assign(buff, buff + len);
  901. servant_invoke(msg, false);
  902. rsp = *msg->response.get();
  903. delete msg;
  904. msg = NULL;
  905. }
  906. void ServantProxy::rpc_call_async(uint32_t iRequestId,
  907. const string& sFuncName,
  908. const char* buff,
  909. uint32_t len,
  910. const ServantProxyCallbackPtr& callback,
  911. bool bCoro)
  912. {
  913. ReqMessage *msg = new ReqMessage();
  914. msg->init(callback ? ReqMessage::ASYNC_CALL : ReqMessage::ONE_WAY, this);
  915. msg->bFromRpc = true;
  916. msg->callback = callback;
  917. msg->request.sServantName = _objectProxy->name();
  918. msg->request.sFuncName = sFuncName;
  919. msg->request.iRequestId = iRequestId;
  920. msg->request.sBuffer.assign(buff, buff + len);
  921. servant_invoke(msg, bCoro);
  922. }
  923. ServantPrx ServantProxy::getServantPrx(ReqMessage *msg)
  924. {
  925. if (_servantId == 0)
  926. {
  927. std::lock_guard<std::mutex> m(_servantMutex);
  928. if (_servantId == 0 && _servantList.empty())
  929. {
  930. for (int i = 1; i < _connectionSerial; ++i)
  931. {
  932. string obj = tars_name() + "#" + TC_Common::tostr(i);
  933. if (!_objectProxy->address().empty())
  934. {
  935. obj += "@" + _objectProxy->address();
  936. }
  937. ServantPrx prx = _communicator->stringToProxy<ServantPrx>(obj, this->tars_setName(), false);
  938. prx->tars_set_protocol(tars_get_protocol());
  939. prx->tars_connect_timeout(tars_connect_timeout());
  940. prx->tars_timeout(tars_timeout());
  941. prx->tars_async_timeout(tars_async_timeout());
  942. prx->_rootPrx = this;
  943. _servantList.push_back(prx);
  944. }
  945. }
  946. }
  947. if (_connectionSerial != 0)
  948. {
  949. assert(int(_servantList.size() + 1) == _connectionSerial);
  950. }
  951. int id = _servantId++ % (_servantList.size() + 1);
  952. if (id == 0)
  953. {
  954. return this;
  955. }
  956. return _servantList[(id - 1)];
  957. }
  958. void ServantProxy::travelObjectProxys(ServantProxy *prx, function<void(ObjectProxy*)> f)
  959. {
  960. vector<ObjectProxy*> objectProxys;
  961. size_t num = _communicator->getCommunicatorEpollNum();
  962. for (size_t i = 0; i < num; ++i)
  963. {
  964. auto ce = _communicator->getCommunicatorEpoll(i);
  965. ObjectProxy* objectProxy = ce->servantToObjectProxy(prx);
  966. if (objectProxy)
  967. {
  968. f(objectProxy);
  969. }
  970. }
  971. //协程通信器也需要
  972. _communicator->forEachSchedCommunicatorEpoll([&](const shared_ptr<CommunicatorEpoll>& ce)
  973. {
  974. ObjectProxy* objectProxy = ce->servantToObjectProxy(prx);
  975. if (objectProxy)
  976. {
  977. f(objectProxy);
  978. }
  979. });
  980. }
  981. vector<ObjectProxy*> ServantProxy::getObjectProxys()
  982. {
  983. vector<ObjectProxy*> objectProxys;
  984. //更新子servant proxy的地址
  985. for (size_t i = 0; i < _servantList.size(); i++)
  986. {
  987. ServantProxy* prx = _servantList[i].get();
  988. travelObjectProxys(prx, [&](ObjectProxy *op){
  989. objectProxys.push_back(op);
  990. });
  991. }
  992. travelObjectProxys(this, [&](ObjectProxy *op){
  993. objectProxys.push_back(op);
  994. });
  995. return objectProxys;
  996. }
  997. void ServantProxy::tars_update_endpoints(const set<EndpointInfo> &active, const set<EndpointInfo> &inactive)
  998. {
  999. onNotifyEndpoints(NULL, active, inactive);
  1000. }
  1001. void ServantProxy::onNotifyEndpoints(CommunicatorEpoll *communicatorEpoll, const set<EndpointInfo> &active, const set<EndpointInfo> &inactive)
  1002. {
  1003. //更新子servant proxy的地址
  1004. for (size_t i = 0; i < _servantList.size(); i++)
  1005. {
  1006. ServantProxy* prx = _servantList[i].get();
  1007. travelObjectProxys(prx, [&](ObjectProxy *op){
  1008. if(op->getEndpointManager())
  1009. {
  1010. op->getEndpointManager()->updateEndpointsOutter(active, inactive);
  1011. }
  1012. });
  1013. }
  1014. travelObjectProxys(this, [&](ObjectProxy *op){
  1015. if(op->getEndpointManager())
  1016. {
  1017. op->getEndpointManager()->updateEndpointsOutter(active, inactive);
  1018. }
  1019. });
  1020. }
  1021. void ServantProxy::onSetInactive(const EndpointInfo &ep)
  1022. {
  1023. if (!_rootPrx)
  1024. return;
  1025. for (size_t i = 0; i < _rootPrx->_servantList.size(); i++)
  1026. {
  1027. ServantPrx &prx = _rootPrx->_servantList[i];
  1028. prx->forEachObject([&](ObjectProxy *o) { o->onSetInactive(ep); });
  1029. }
  1030. }
  1031. int ServantProxy::servant_invoke(ReqMessage *msg, bool bCoroAsync)
  1032. {
  1033. ServantPrx prx = getServantPrx(msg);
  1034. if (msg->callback)
  1035. {
  1036. msg->callback->setServantPrx(prx);
  1037. }
  1038. prx->invoke(msg, bCoroAsync);
  1039. return 0;
  1040. }
  1041. void ServantProxy::http_call(const string &funcName, shared_ptr<TC_HttpRequest> &request, shared_ptr<TC_HttpResponse> &response)
  1042. {
  1043. if (_connectionSerial <= 0)
  1044. {
  1045. _connectionSerial = DEFAULT_CONNECTION_SERIAL;
  1046. }
  1047. ReqMessage *msg = new ReqMessage();
  1048. msg->init(ReqMessage::SYNC_CALL, this);
  1049. msg->bFromRpc = true;
  1050. msg->request.sServantName = _objectProxy->name();
  1051. msg->request.sFuncName = funcName;
  1052. msg->request.sBuffer.resize(sizeof(shared_ptr<TC_HttpRequest>));
  1053. msg->deconstructor = [msg] {
  1054. shared_ptr<TC_HttpRequest> &data = *(shared_ptr<TC_HttpRequest> *)(msg->request.sBuffer.data());
  1055. data.reset();
  1056. if (!msg->response->sBuffer.empty())
  1057. {
  1058. shared_ptr<TC_HttpResponse> &rsp = *(shared_ptr<TC_HttpResponse> *)(msg->response->sBuffer.data());
  1059. //主动reset一次
  1060. rsp.reset();
  1061. msg->response->sBuffer.clear();
  1062. }
  1063. };
  1064. shared_ptr<TC_HttpRequest> &data = *(shared_ptr<TC_HttpRequest> *)(msg->request.sBuffer.data());
  1065. data = request;
  1066. servant_invoke(msg, false);
  1067. response = *(shared_ptr<TC_HttpResponse> *)(msg->response->sBuffer.data());
  1068. delete msg;
  1069. msg = NULL;
  1070. }
  1071. void ServantProxy::http_call_async(const string &funcName, shared_ptr<TC_HttpRequest> &request, const HttpCallbackPtr &cb, bool bCoro)
  1072. {
  1073. if (_connectionSerial <= 0)
  1074. {
  1075. _connectionSerial = DEFAULT_CONNECTION_SERIAL;
  1076. }
  1077. ReqMessage *msg = new ReqMessage();
  1078. msg->init(ReqMessage::ASYNC_CALL, this);
  1079. msg->bFromRpc = true;
  1080. msg->request.sServantName = _objectProxy->name();
  1081. msg->request.sFuncName = funcName;
  1082. msg->request.sBuffer.resize(sizeof(shared_ptr<TC_HttpRequest>));
  1083. msg->deconstructor = [msg] {
  1084. shared_ptr<TC_HttpRequest> &data = *(shared_ptr<TC_HttpRequest> *)(msg->request.sBuffer.data());
  1085. data.reset();
  1086. if (!msg->response->sBuffer.empty())
  1087. {
  1088. shared_ptr<TC_HttpResponse> &rsp = *(shared_ptr<TC_HttpResponse> *)(msg->response->sBuffer.data());
  1089. //主动reset一次
  1090. rsp.reset();
  1091. msg->response->sBuffer.clear();
  1092. }
  1093. };
  1094. *(shared_ptr<TC_HttpRequest> *)(msg->request.sBuffer.data()) = request;
  1095. ServantProxyCallbackPtr callback = new HttpServantProxyCallback(cb);
  1096. msg->callback = callback;
  1097. servant_invoke(msg, bCoro);
  1098. }
  1099. //
  1100. //选取一个网络线程对应的信息
  1101. void ServantProxy::selectNetThreadInfo(ServantProxyThreadData *pSptd, ObjectProxy *&pObjProxy, shared_ptr<ReqInfoQueue> &pReqQ)
  1102. {
  1103. if(pSptd->_sched && pSptd->_communicatorEpoll == NULL)
  1104. {
  1105. //处于业务线程中, 且当前业务线程是以协程模式启动;
  1106. auto schedCommunicatorEpollInfo = pSptd->getSchedCommunicatorEpollInfo(_communicator);
  1107. shared_ptr<CommunicatorEpoll> ce;
  1108. if (!schedCommunicatorEpollInfo->_communicator)
  1109. {
  1110. //当前协程没有关联过私有网络通信器, 需要新建!
  1111. pReqQ = std::make_shared<ReqInfoQueue>(_communicator->getCommunicatorEpoll(0)->getNoSendQueueLimit());
  1112. ce = _communicator->createSchedCommunicatorEpoll(pSptd->_reqQNo, pReqQ);
  1113. schedCommunicatorEpollInfo->_communicator = _communicator;
  1114. schedCommunicatorEpollInfo->_info._reqQueue = pReqQ;
  1115. schedCommunicatorEpollInfo->_info._communicatorEpoll = ce;
  1116. pObjProxy = ce->createObjectProxy(this, this->tars_full_name(), this->tars_setName());
  1117. pObjProxy->initialize(true);
  1118. }
  1119. else
  1120. {
  1121. //网络通信器已经初始化过, 直接获取对象
  1122. pReqQ = schedCommunicatorEpollInfo->_info._reqQueue.lock();
  1123. ce = schedCommunicatorEpollInfo->_info._communicatorEpoll.lock();
  1124. if(ce && pReqQ)
  1125. {
  1126. pObjProxy = ce->hasObjectProxy(this->tars_full_name(), this->tars_setName());
  1127. //创建对应的ObjectProxy
  1128. if(!pObjProxy)
  1129. {
  1130. pObjProxy = ce->createObjectProxy(this, this->tars_full_name(), this->tars_setName());
  1131. pObjProxy->initialize(true);
  1132. }
  1133. }
  1134. else
  1135. {
  1136. // assert(false);
  1137. throw TarsCommunicatorException("communicator may deconstruct");
  1138. }
  1139. }
  1140. }
  1141. else
  1142. {
  1143. if( pSptd->_communicatorEpoll )
  1144. {
  1145. auto info = pSptd->getCommunicatorEpollInfo(_communicator);
  1146. assert(info->_info.size() == 1);
  1147. assert(info->_info[0]._communicatorEpoll.lock().get() == pSptd->_communicatorEpoll);
  1148. pObjProxy = pSptd->_communicatorEpoll->servantToObjectProxy(this);
  1149. pReqQ = info->_info[0]._reqQueue.lock();
  1150. }
  1151. else
  1152. {
  1153. //处于普通线程中, 判断当前线程是否关联过网络通信器, 没关联, 则关联所有的公有通信器, 即创建和公有网络通信器的队列!
  1154. auto communicatorEpollInfo = pSptd->getCommunicatorEpollInfo(_communicator);
  1155. //当前线程没有关联业务通信器, 需要关联
  1156. if (!communicatorEpollInfo->_communicator)
  1157. {
  1158. communicatorEpollInfo->_communicator = _communicator;
  1159. //为每个网络线程都创建一个队列
  1160. for (size_t i = 0; i < _communicator->getCommunicatorEpollNum(); ++i)
  1161. {
  1162. shared_ptr<CommunicatorEpoll> ce = _communicator->getCommunicatorEpoll(i);
  1163. pSptd->addCommunicatorEpoll(ce);
  1164. }
  1165. }
  1166. assert(communicatorEpollInfo->_netSeq < _communicator->getCommunicatorEpollNum());
  1167. //循环使用下一个网络线程发送数据
  1168. auto ce = communicatorEpollInfo->_info[communicatorEpollInfo->_netSeq]._communicatorEpoll.lock();
  1169. if (ce)
  1170. {
  1171. pObjProxy = ce->servantToObjectProxy(this);
  1172. pReqQ = communicatorEpollInfo->_info[communicatorEpollInfo->_netSeq]._reqQueue.lock();
  1173. communicatorEpollInfo->_netSeq++;
  1174. if (communicatorEpollInfo->_netSeq == _communicator->getCommunicatorEpollNum())
  1175. communicatorEpollInfo->_netSeq = 0;
  1176. }
  1177. }
  1178. if(!pReqQ)
  1179. {
  1180. //队列已经析构, 说明通信器已经释放了!
  1181. throw TarsCommunicatorException("communicator has deconstructed");
  1182. }
  1183. }
  1184. }
  1185. void ServantProxy::checkDye(RequestPacket& req)
  1186. {
  1187. //线程私有数据
  1188. ServantProxyThreadData *pSptd = ServantProxyThreadData::getData();
  1189. assert(pSptd != NULL);
  1190. if (pSptd && pSptd->_data._dyeing)
  1191. {
  1192. SET_MSG_TYPE(req.iMessageType, TARSMESSAGETYPEDYED);
  1193. req.status[ServantProxy::STATUS_DYED_KEY] = pSptd->_data._dyeingKey;
  1194. }
  1195. }
  1196. void ServantProxy::checkTrace(RequestPacket &req)
  1197. {
  1198. //线程私有数据
  1199. ServantProxyThreadData *pSptd = ServantProxyThreadData::getData();
  1200. assert(pSptd != NULL);
  1201. if (pSptd && pSptd->_traceCall)
  1202. {
  1203. SET_MSG_TYPE(req.iMessageType, tars::TARSMESSAGETYPETRACE);
  1204. req.status[ServantProxy::STATUS_TRACE_KEY] = pSptd->getTraceKey();
  1205. }
  1206. }
  1207. void ServantProxy::checkCookie(RequestPacket &req)
  1208. {
  1209. //线程私有数据
  1210. ServantProxyThreadData *pSptd = ServantProxyThreadData::getData();
  1211. assert(pSptd != NULL);
  1212. std::for_each(pSptd->_data._cookie.begin(), pSptd->_data._cookie.end(), [&](map<string, string>::value_type &p) {
  1213. req.status.insert(make_pair(p.first, p.second));
  1214. });
  1215. }
  1216. void ServantProxy::tars_endpoints(vector<EndpointInfo> &activeEndPoint, vector<EndpointInfo> &inactiveEndPoint)
  1217. {
  1218. _endpointInfo->getEndpoint(activeEndPoint, inactiveEndPoint);
  1219. }
  1220. void ServantProxy::tars_endpointsAll(vector<EndpointInfo> &activeEndPoint, vector<EndpointInfo> &inactiveEndPoint)
  1221. {
  1222. _endpointInfo->getEndpointByAll(activeEndPoint, inactiveEndPoint);
  1223. }
  1224. void ServantProxy::tars_endpointsBySet(const string & sName,vector<EndpointInfo> &activeEndPoint, vector<EndpointInfo> &inactiveEndPoint)
  1225. {
  1226. _endpointInfo->getEndpointBySet(sName, activeEndPoint, inactiveEndPoint);
  1227. }
  1228. void ServantProxy::tars_endpointsByStation(const string & sName,vector<EndpointInfo> &activeEndPoint, vector<EndpointInfo> &inactiveEndPoint)
  1229. {
  1230. _endpointInfo->getEndpointByStation(sName, activeEndPoint, inactiveEndPoint);
  1231. }
  1232. vector<TC_Endpoint> ServantProxy::tars_endpoints(const std::string & sStation)
  1233. {
  1234. vector<TC_Endpoint> activeEndPoint;
  1235. vector<TC_Endpoint> inactiveEndPoint;
  1236. _endpointInfo->getTCEndpoint(activeEndPoint, inactiveEndPoint);
  1237. return activeEndPoint;
  1238. }
  1239. void ServantProxy::tars_endpoints(const std::string & sStation, vector<TC_Endpoint> & vecActive, vector<TC_Endpoint> & vecInactive)
  1240. {
  1241. _endpointInfo->getTCEndpointByStation(sStation, vecActive, vecInactive);
  1242. }
  1243. vector<TC_Endpoint> ServantProxy::getEndpoint()
  1244. {
  1245. vector<TC_Endpoint> activeEndPoint;
  1246. vector<TC_Endpoint> inactiveEndPoint;
  1247. _endpointInfo->getTCEndpoint(activeEndPoint, inactiveEndPoint);
  1248. return activeEndPoint;
  1249. }
  1250. vector<TC_Endpoint> ServantProxy::getEndpoint4All()
  1251. {
  1252. vector<TC_Endpoint> activeEndPoint;
  1253. vector<TC_Endpoint> inactiveEndPoint;
  1254. _endpointInfo->getTCEndpointByAll(activeEndPoint, inactiveEndPoint);
  1255. return activeEndPoint;
  1256. }
  1257. //////////////////////////////////////////////////////////////////////////////////////////////////
  1258. }