-
Notifications
You must be signed in to change notification settings - Fork 250
/
EndpointManager.cpp
1998 lines (1636 loc) · 57.7 KB
/
EndpointManager.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Tencent is pleased to support the open source community by making Tars available.
*
* Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
#include "util/tc_port.h"
#include "servant/EndpointManager.h"
#include "servant/ObjectProxy.h"
#include "servant/RemoteLogger.h"
#include "servant/AppCache.h"
#include "servant/Application.h"
#include "servant/StatReport.h"
namespace tars
{
/////////////////////////////////////////////////////////////////////////////
QueryEpBase::QueryEpBase(Communicator * pComm, bool bFirstNetThread,bool bInterfaceReq)
: _communicator(pComm)
, _firstNetThread(bFirstNetThread)
, _interfaceReq(bInterfaceReq)
, _direct(false)
, _objName("")
, _invokeSetId("")
, _locator("")
, _valid(false)
, _weightType(E_LOOP)
, _rootServant(true)
, _requestRegistry(false)
, _requestTimeout(0)
, _timeoutInterval(5*1000)
, _refreshTime(0)
, _refreshInterval(60*1000)
, _activeEmptyInterval(10*1000)
, _failInterval(2*1000)
, _manyFailInterval(30*1000)
, _failTimesLimit(3)
, _failTimes(0)
{
setNoDelete(true);
}
void QueryEpBase::callback_findObjectById4All(Int32 ret, const vector<EndpointF>& activeEp, const vector<EndpointF>& inactiveEp)
{
TLOGTARS("[callback_findObjectById4All _objName:" << _objName << "|ret:" << ret
<< ",active:" << activeEp.size()
<< ",inactive:" << inactiveEp.size() << "]" << endl);
doEndpoints(activeEp,inactiveEp,ret);
}
void QueryEpBase::callback_findObjectById4All_exception(Int32 ret)
{
TLOGERROR("[callback_findObjectById4All_exception _objName:" << _objName << "|ret:" << ret << "]" << endl);
doEndpointsExp(ret);
}
void QueryEpBase::callback_findObjectById4Any(Int32 ret, const vector<EndpointF>& activeEp, const vector<EndpointF>& inactiveEp)
{
TLOGTARS("[callback_findObjectById4Any _objName:" << _objName << "|ret:" << ret
<< ",active:" << activeEp.size()
<< ",inactive:" << inactiveEp.size() << "]" << endl);
doEndpoints(activeEp,inactiveEp,ret);
}
void QueryEpBase::callback_findObjectById4Any_exception(Int32 ret)
{
TLOGERROR("[callback_findObjectById4Any_exception _objName:" << _objName << "|ret:" << ret << "]" << endl);
doEndpointsExp(ret);
}
void QueryEpBase::callback_findObjectByIdInSameGroup(Int32 ret, const vector<EndpointF>& activeEp, const vector<EndpointF>& inactiveEp)
{
TLOGTARS("[callback_findObjectByIdInSameGroup _objName:" << _objName << "|ret:"<<ret
<< ",active:" << activeEp.size()
<< ",inactive:" << inactiveEp.size() << "]" << endl);
doEndpoints(activeEp,inactiveEp,ret);
}
void QueryEpBase::callback_findObjectByIdInSameGroup_exception(Int32 ret)
{
TLOGERROR("[callback_findObjectByIdInSameGroup_exception _objName:" << _objName << "|ret:" << ret << "]" << endl);
doEndpointsExp(ret);
}
void QueryEpBase::callback_findObjectByIdInSameSet( Int32 ret, const vector<EndpointF> &activeEp, const vector<EndpointF> & inactiveEp)
{
TLOGTARS("[callback_findObjectByIdInSameSet _objName:" << _objName << "|ret:" << ret
<< ",active:" << activeEp.size()
<< ",inactive:" << inactiveEp.size() << "]" << endl);
doEndpoints(activeEp,inactiveEp,ret);
}
void QueryEpBase::callback_findObjectByIdInSameSet_exception( Int32 ret)
{
TLOGERROR("[callback_findObjectByIdInSameSet_exception _objName:" << _objName << "|ret:" << ret << "]" << endl);
doEndpointsExp(ret);
}
void QueryEpBase::callback_findObjectByIdInSameStation( Int32 ret, const vector<EndpointF> &activeEp, const vector<EndpointF> &inactiveEp)
{
TLOGTARS("[callback_findObjectByIdInSameStation _objName:" << _objName << "|ret:" << ret
<< ",active:" << activeEp.size()
<< ",inactive:" << inactiveEp.size() << "]" << endl);
doEndpoints(activeEp,inactiveEp,ret);
}
void QueryEpBase::callback_findObjectByIdInSameStation_exception( Int32 ret)
{
TLOGERROR("[callback_findObjectByIdInSameStation_exception _objName:" << _objName << "|ret:" << ret << "]" << endl);
doEndpointsExp(ret);
}
int QueryEpBase::setLocatorPrx(QueryFPrx prx)
{
_queryFPrx = prx;
return 0;
}
bool QueryEpBase::init(const string & sObjName,const string & sLocator,const string& setName)
{
TLOGTARS("[QueryEpBase::init sObjName:" << sObjName << ",sLocator:" << sLocator << ",setName:" << setName << "]" << endl);
_locator = sLocator;
_invokeSetId = setName;
setObjName(sObjName);
return true;
}
void QueryEpBase::setObjName(const string & sObjName)
{
string::size_type pos = sObjName.find_first_of('@');
string sEndpoints;
string sInactiveEndpoints;
if (pos != string::npos)
{
//[直接连接]指定服务的IP和端口列表
_objName = sObjName.substr(0,pos);
sEndpoints = sObjName.substr(pos + 1);
pos = _objName.find_first_of("#");
if(pos != string::npos)
{
_rootServant = false;
_objName = _objName.substr(0, pos);
}
_direct = true;
_valid = true;
}
else
{
//[间接连接]通过registry查询服务端的IP和端口列表
_direct = false;
_valid = false;
_objName = sObjName;
if(_locator.find_first_not_of('@') == string::npos)
{
TLOGERROR("[QueryEpBase::setObjName locator is not valid,_locator:" << _locator << "]" << endl);
throw TarsRegistryException("locator is not valid,_locator:" + _locator);
}
pos = _objName.find_first_of("#");
if(pos != string::npos)
{
_objName = _objName.substr(0, pos);
}
_queryFPrx = _communicator->stringToProxy<QueryFPrx>(_locator);
string sLocatorKey = _locator;
//如果启用set,则获取按set分组的缓存
if(ClientConfig::SetOpen)
{
sLocatorKey += "_" + ClientConfig::SetDivision;
}
string objName = _objName + string(_invokeSetId.empty() ? "" : ":") + _invokeSetId;
//[间接连接]第一次使用cache,如果是接口级请求则不从缓存读取
if(!_interfaceReq)
{
sEndpoints = AppCache::getInstance()->get(objName,sLocatorKey);
sInactiveEndpoints = AppCache::getInstance()->get("inactive_"+objName,sLocatorKey);
}
}
setEndpoints(sEndpoints,_activeEndpoints);
setEndpoints(sInactiveEndpoints,_inactiveEndpoints);
if(_activeEndpoints.size()>0)
{
_valid = true;
}
if(_activeEndpoints.size()>0 || _inactiveEndpoints.size()>0)
{
notifyEndpoints(_activeEndpoints,_inactiveEndpoints,true);
}
}
vector<string> QueryEpBase::sepEndpoint(const string& sEndpoints)
{
vector<string> vEndpoints;
bool flag = false;
string::size_type startPos = 0;
string::size_type sepPos = 0;
for(string::size_type pos = 0; pos < sEndpoints.size(); pos++)
{
if(sEndpoints[pos] == ':' && !flag )
{
sepPos = pos;
flag = true;
}
else if(flag)
{
if(sEndpoints[pos] == ' ')
{
continue;
}
if(TC_Port::strncasecmp("tcp", (sEndpoints.c_str() + pos), 3) == 0 || TC_Port::strncasecmp("udp", (sEndpoints.c_str() + pos), 3) == 0 || TC_Port::strncasecmp("ssl", (sEndpoints.c_str() + pos), 3) == 0)
{
string ep = TC_Common::trim(string(sEndpoints.c_str() + startPos, sepPos - startPos));
if(!ep.empty()) {
vEndpoints.push_back(ep);
}
startPos = pos;
}
flag = false;
}
}
string ep = sEndpoints.substr(startPos);
if(!ep.empty()) {
vEndpoints.push_back(ep);
}
// vEndpoints.push_back(sEndpoints.substr(startPos));
return vEndpoints;
}
void QueryEpBase::setEndpoints(const string & sEndpoints, set<EndpointInfo> & setEndpoints)
{
if(sEndpoints == "")
{
return ;
}
bool bSameWeightType = true;
bool bFirstWeightType = true;
unsigned int iWeightType = 0;
vector<string> vEndpoints = sepEndpoint(sEndpoints);
for (size_t i = 0; i < vEndpoints.size(); ++i)
{
try
{
TC_Endpoint ep(vEndpoints[i]);
string sSetDivision;
//解析set分组信息
if (!_direct)
{
string sep = " -s ";
size_t pos = vEndpoints[i].rfind(sep);
if (pos != string::npos)
{
sSetDivision = TC_Common::trim(vEndpoints[i].substr(pos+sep.size()));
size_t endPos = sSetDivision.find(" ");
if (endPos != string::npos)
{
sSetDivision = sSetDivision.substr(0, endPos);
}
}
}
if(bFirstWeightType)
{
bFirstWeightType = false;
iWeightType = ep.getWeightType();
}
else
{
if(ep.getWeightType() != iWeightType)
{
bSameWeightType = false;
}
}
EndpointInfo epi(ep, sSetDivision);
// EndpointInfo epi(ep.getHost(), ep.getPort(), ep.getType(), ep.getGrid(), sSetDivision, ep.getQos(), ep.getWeight(), ep.getWeightType(), ep.getAuthType());
setEndpoints.insert(epi);
}
catch (...)
{
TLOGERROR("[QueryEpBase::setEndpoints parse error,objname:" << _objName << ",endpoint:" << vEndpoints[i] << "]" << endl);
}
}
if(bSameWeightType)
{
if(iWeightType == 1)
{
_weightType = E_STATIC_WEIGHT;
}
else
{
_weightType = E_LOOP;
}
}
else
{
_weightType = E_LOOP;
}
}
void QueryEpBase::refreshReg(GetEndpointType type, const string & sName)
{
if(_direct)
{
return;
}
int64_t iNow = TNOWMS;
//正在请求状态 而且请求超时了,或者第一次
if(_requestRegistry && _requestTimeout < iNow)
{
doEndpointsExp(0);
}
//如果是间接连接,通过registry定时查询服务列表
//正在请求状态 而且请求超时了
//非请求状态 到了下一个刷新时间了
if( (!_requestRegistry) && (_refreshTime <= iNow))
{
_requestRegistry = true;
//一定时间不回调就算超时了
_requestTimeout = iNow + _timeoutInterval;
TLOGTARS("[QueryEpBase::refresh,"<<_objName<<"]"<<endl);
//判断是同步调用还是异步调用
//内部请求主控都是异步请求
//接口请求主控第一次是同步请求
bool bSync = (!_valid && _interfaceReq);
//如果是异步且不是根servant(通过#1创建的servant, 不主动更新主控信息)
if(!bSync && !_rootServant)
return;
try
{
if(bSync)
{
vector<EndpointF> activeEp;
vector<EndpointF> inactiveEp;
int iRet = 0;
switch(type)
{
case E_ALL:
{
iRet = _queryFPrx->findObjectById4Any(_objName,activeEp,inactiveEp, ServerConfig::Context);
break;
}
case E_STATION:
{
iRet = _queryFPrx->findObjectByIdInSameStation(_objName,sName,activeEp,inactiveEp, ServerConfig::Context);
}
case E_SET:
{
iRet = _queryFPrx->findObjectByIdInSameSet(_objName,sName,activeEp,inactiveEp, ServerConfig::Context);
break;
}
case E_DEFAULT:
default:
{
if(ClientConfig::SetOpen || !_invokeSetId.empty())
{
//指定set调用时,指定set的优先级最高
string setId = _invokeSetId.empty()?ClientConfig::SetDivision:_invokeSetId;
iRet = _queryFPrx->findObjectByIdInSameSet(_objName,setId,activeEp,inactiveEp, ServerConfig::Context);
}
else
{
iRet = _queryFPrx->findObjectByIdInSameGroup(_objName,activeEp,inactiveEp, ServerConfig::Context);
}
break;
}
}
doEndpoints(activeEp, inactiveEp, iRet, true);
}
else
{
switch(type)
{
case E_ALL:
{
_queryFPrx->async_findObjectById4Any(this,_objName, ServerConfig::Context);
break;
}
case E_STATION:
{
_queryFPrx->async_findObjectByIdInSameStation(this,_objName,sName, ServerConfig::Context);
break;
}
case E_SET:
{
_queryFPrx->async_findObjectByIdInSameSet(this,_objName,sName, ServerConfig::Context);
break;
}
case E_DEFAULT:
default:
{
if(ClientConfig::SetOpen || !_invokeSetId.empty())
{
//指定set调用时,指定set的优先级最高
string setId = _invokeSetId.empty()?ClientConfig::SetDivision:_invokeSetId;
_queryFPrx->async_findObjectByIdInSameSet(this,_objName,setId, ServerConfig::Context);
}
else
{
_queryFPrx->async_findObjectByIdInSameGroup(this,_objName, ServerConfig::Context);
}
break;
}
}//end switch
}
}
catch(TC_Exception & ex)
{
TLOGERROR("[QueryEpBase::refreshReg obj:"<<_objName<<"exception:"<<ex.what() << "]"<<endl);
doEndpointsExp(TARSSERVERUNKNOWNERR);
}
catch(...)
{
TLOGERROR("[QueryEpBase::refreshReg obj:"<<_objName<<"unknown exception]" <<endl);
doEndpointsExp(TARSSERVERUNKNOWNERR);
}
}
}
void QueryEpBase::doEndpoints(const vector<EndpointF>& activeEp, const vector<EndpointF>& inactiveEp, int iRet, bool bSync)
{
if(iRet != 0)
{
doEndpointsExp(iRet);
return ;
}
_failTimes = 0;
_requestRegistry = false;
int64_t iNow = TNOWMS;
//有返回成功的结点,按照正常的频率
//如果返回空列表或者返回失败 2s去刷新一次
//接口请求主控的方式 不管是不是空都要去刷新
if(activeEp.empty() && (!_interfaceReq) )
{
_refreshTime = iNow + _activeEmptyInterval;
//如果registry返回Active服务列表为空,不做更新
TLOGERROR("[QueryEpBase::doEndpoints, callback activeEps is empty,objname:"<< _objName << "]" << endl);
return;
}
else
{
_refreshTime = iNow + _refreshInterval;
}
bool bNeedNotify = false;
bool bSameWeightType = true;
bool bFirstWeightType = true;
int iWeightType = 0;
set<string> sActiveEndpoints;
set<string> sInactiveEndpoints;
set<EndpointInfo> activeEps;
set<EndpointInfo> inactiveEps;
//生成active set 用于比较
for (uint32_t i = 0; i < activeEp.size(); ++i)
{
if(bFirstWeightType)
{
bFirstWeightType = false;
iWeightType = activeEp[i].weightType;
}
else
{
if(activeEp[i].weightType != iWeightType)
{
bSameWeightType = false;
}
}
// taf istcp意思和这里枚举值对应
// EndpointInfo::EType type = EndpointInfo::EType(activeEp[i].istcp);
// EndpointInfo ep(activeEp[i].host, activeEp[i].port, (TC_Endpoint::EType)activeEp[i].istcp, activeEp[i].grid, activeEp[i].setId, activeEp[i].qos, activeEp[i].weight, activeEp[i].weightType, activeEp[i].authType);
activeEps.insert(EndpointInfo(activeEp[i]));
}
//生成inactive set 用于比较
for (uint32_t i = 0; i < inactiveEp.size(); ++i)
{
// taf istcp意思和这里枚举值对应
// EndpointInfo::EType type = EndpointInfo::EType(inactiveEp[i].istcp);
// EndpointInfo ep(inactiveEp[i].host, inactiveEp[i].port, (TC_Endpoint::EType)activeEp[i].istcp, inactiveEp[i].grid, inactiveEp[i].setId, inactiveEp[i].qos, inactiveEp[i].weight, inactiveEp[i].weightType, inactiveEp[i].authType);
inactiveEps.insert(EndpointInfo(inactiveEp[i]));
}
if(bSameWeightType)
{
if(iWeightType == 1)
{
_weightType = E_STATIC_WEIGHT;
}
else
{
_weightType = E_LOOP;
}
}
else
{
_weightType = E_LOOP;
}
if(activeEps != _activeEndpoints)
{
bNeedNotify = true;
_activeEndpoints = activeEps;
if(_firstNetThread)
{
setEndPointToCache(false);
}
}
if(inactiveEps != _inactiveEndpoints)
{
bNeedNotify = true;
_inactiveEndpoints = inactiveEps;
if(_firstNetThread)
{
setEndPointToCache(true);
}
}
if(bNeedNotify)
{
notifyEndpoints(_activeEndpoints,_inactiveEndpoints,bSync);
}
if(!_valid)
{
_valid = true;
doNotify();
}
}
void QueryEpBase::doEndpointsExp(int iRet)
{
_failTimes++;
_requestRegistry = false;
int64_t iNow = TNOWMS;
//频率控制获取主控失败 2秒钟再更新
_refreshTime = iNow + _failInterval;
//获取主控连续失败3次就等30s再更新一次
//连续失败 强制设成数据是有效的
if(_failTimes > _failTimesLimit)
{
if(!_valid)
{
_valid = true;
doNotify();
}
_refreshTime = iNow + _manyFailInterval;
}
}
void QueryEpBase::setEndPointToCache(bool bInactive)
{
//如果是接口级请求则不缓存到文件
if(_interfaceReq)
{
return;
}
string sEndpoints;
set<EndpointInfo> doEndpoints;
if(!bInactive)
{
doEndpoints = _activeEndpoints;
}
else
{
doEndpoints = _inactiveEndpoints;
}
set<EndpointInfo>::iterator iter;
iter = doEndpoints.begin();
for (; iter != doEndpoints.end(); ++iter)
{
//这里的超时时间 只是对服务端有效。这里的值无效。所以默认用3000了
TC_Endpoint ep(iter->host(), iter->port(), 3000, iter->type(), iter->grid(), iter->qos(), iter->weight(), iter->getWeightType());
ep.setAuthType(iter->authType());
if (!sEndpoints.empty())
{
sEndpoints += ":";
}
sEndpoints += ep.toString();
if (!iter->setDivision().empty())
{
sEndpoints += " -s " + iter->setDivision();
}
}
//如果启用set,则按set分组保存
string sLocatorKey = _locator;
if(ClientConfig::SetOpen)
{
sLocatorKey += "_" + ClientConfig::SetDivision;
}
string objName = _objName + string(_invokeSetId.empty()?"":":") + _invokeSetId;
if(bInactive)
{
AppCache::getInstance()->set("inactive_"+objName,sEndpoints,sLocatorKey);
}
else
{
AppCache::getInstance()->set(objName,sEndpoints,sLocatorKey);
}
TLOGTARS("[setEndPointToCache,obj:" << _objName << ",invokeSetId:" << _invokeSetId << ",endpoint:" << sEndpoints << "]" << endl);
}
EndpointManager::EndpointManager(ObjectProxy * pObjectProxy, Communicator* pComm, const string & sObjName, bool bFirstNetThread,const string& setName)
: QueryEpBase(pComm, bFirstNetThread, false)
,_objectProxy(pObjectProxy)
,_lastRoundPosition(0)
,_update(true)
,_updateWeightInterval(60)
,_lastSWeightPosition(0)
,_consistentHashWeight(E_TC_CONHASH_KETAMAHASH)
,_consistentHash(E_TC_CONHASH_KETAMAHASH)
{
setNetThreadProcess(true);
init(sObjName, _communicator->getProperty("locator"), setName);
}
EndpointManager::~EndpointManager()
{
map<string,AdapterProxy*>::iterator iterAdapter;
for(iterAdapter = _allProxys.begin();iterAdapter != _allProxys.end();iterAdapter++)
{
if(iterAdapter->second)
{
delete iterAdapter->second;
iterAdapter->second = NULL;
}
}
}
void EndpointManager::updateEndpoints(const set<EndpointInfo> & active, const set<EndpointInfo> & inactive)
{
set<EndpointInfo>::const_iterator iter;
map<string,AdapterProxy*>::iterator iterAdapter;
pair<map<string,AdapterProxy*>::iterator,bool> result;
_activeProxys.clear();
_regProxys.clear();
//更新active
iter = active.begin();
for(;iter != active.end();++iter)
{
if(!_direct && _weightType == E_STATIC_WEIGHT && iter->weight() <= 0)
{
continue;
}
iterAdapter = _allProxys.find(iter->cmpDesc());
if(iterAdapter == _allProxys.end())
{
AdapterProxy* ap = new AdapterProxy(_objectProxy, *iter, _communicator);
result = _allProxys.insert(make_pair(iter->cmpDesc(),ap));
assert(result.second);
iterAdapter = result.first;
_vAllProxys.push_back(ap);
}
//该节点在主控的状态为active
iterAdapter->second->setActiveInReg(true);
_activeProxys.push_back(iterAdapter->second);
_regProxys.insert(make_pair(iter->cmpDesc(),iterAdapter->second));
//设置该节点的静态权重值
iterAdapter->second->setWeight(iter->weight());
}
//更新inactive
iter = inactive.begin();
for(;iter != inactive.end();++iter)
{
if(!_direct && _weightType == E_STATIC_WEIGHT && iter->weight() <= 0)
{
continue;
}
iterAdapter = _allProxys.find(iter->cmpDesc());
if(iterAdapter == _allProxys.end())
{
AdapterProxy* ap = new AdapterProxy(_objectProxy, *iter, _communicator);
result = _allProxys.insert(make_pair(iter->cmpDesc(),ap));
assert(result.second);
iterAdapter = result.first;
_vAllProxys.push_back(ap);
}
//该节点在主控的状态为inactive
iterAdapter->second->setActiveInReg(false);
_regProxys.insert(make_pair(iter->cmpDesc(),iterAdapter->second));
//设置该节点的静态权重值
iterAdapter->second->setWeight(iter->weight());
}
//_vRegProxys 需要按顺序来 重排
_vRegProxys.clear();
iterAdapter = _regProxys.begin();
for(;iterAdapter != _regProxys.end();++iterAdapter)
{
_vRegProxys.push_back(iterAdapter->second);
}
_update = true;
}
void EndpointManager::notifyEndpoints(const set<EndpointInfo> & active,const set<EndpointInfo> & inactive,bool bNotify)
{
updateEndpoints(active, inactive);
//丢给外层统一做
_objectProxy->onNotifyEndpoints(active, inactive);
}
void EndpointManager::doNotify()
{
_objectProxy->doInvoke();
}
bool EndpointManager::selectAdapterProxy(ReqMessage * msg,AdapterProxy * & pAdapterProxy)
{
pAdapterProxy = NULL;
//刷新主控
refreshReg(E_DEFAULT, "");
//无效的数据 返回true
if (!_valid)
{
return true;
}
//如果有hash,则先使用hash策略
if (msg->bHash)
{
pAdapterProxy = getHashProxy(msg->iHashCode, msg->bConHash);
return false;
}
if(_weightType == E_STATIC_WEIGHT)
{
//权重模式
bool bStaticWeighted = false;
if(_weightType == E_STATIC_WEIGHT || msg->eType == ReqMessage::ONE_WAY)
bStaticWeighted = true;
pAdapterProxy = getWeightedProxy(bStaticWeighted);
}
else
{
//普通轮询模式
pAdapterProxy = getNextValidProxy();
}
return false;
}
AdapterProxy * EndpointManager::getNextValidProxy()
{
if (_activeProxys.empty())
{
TLOGERROR("[TAF][EndpointManager::getNextValidProxy activeEndpoints is empty][obj:"<<_objName<<"]" << endl);
return NULL;
}
vector<AdapterProxy*> conn;
for(size_t i=0;i<_activeProxys.size();i++)
{
++_lastRoundPosition;
if(_lastRoundPosition >= _activeProxys.size())
_lastRoundPosition = 0;
if(_activeProxys[_lastRoundPosition]->checkActive(false))
{
return _activeProxys[_lastRoundPosition];
}
if(!_activeProxys[_lastRoundPosition]->isConnTimeout() && !_activeProxys[_lastRoundPosition]->isConnExc()) {
conn.push_back(_activeProxys[_lastRoundPosition]);
}
}
if(conn.size() > 0)
{
//都有问题, 随机选择一个没有connect超时或者链接异常的发送
AdapterProxy * adapterProxy = conn[((uint32_t)rand() % conn.size())];
//该proxy可能已经被屏蔽,需重新连一次
adapterProxy->checkActive(true);
return adapterProxy;
}
//所有adapter都有问题 选不到结点,随机找一个重试
AdapterProxy * adapterProxy = _activeProxys[((uint32_t)rand() % _activeProxys.size())];
//该proxy可能已经被屏蔽,需重新连一次
adapterProxy->checkActive(true);
return adapterProxy;
}
AdapterProxy* EndpointManager::getHashProxy(int64_t hashCode, bool bConsistentHash)
{
if(_weightType == E_STATIC_WEIGHT)
{
if(bConsistentHash)
{
return getConHashProxyForWeight(hashCode, true);
}
else
{
return getHashProxyForWeight(hashCode, true, _hashStaticRouterCache);
}
}
else
{
if(bConsistentHash)
{
return getConHashProxyForNormal(hashCode);
}
else
{
return getHashProxyForNormal(hashCode);
}
}
}
AdapterProxy* EndpointManager::getHashProxyForWeight(int64_t hashCode, bool bStatic, vector<size_t> &vRouterCache)
{
if(_vRegProxys.empty())
{
TLOGERROR("[EndpointManager::getHashProxyForWeight _vRegProxys is empty], bStatic:" << bStatic << endl);
return NULL;
}
if(checkHashStaticWeightChange(bStatic))
{
int64_t iBegin = TNOWMS;
updateHashProxyWeighted(bStatic);
int64_t iEnd = TNOWMS;
TLOGTARS("[EndpointManager::getHashProxyForWeight update bStatic:" << bStatic << "|_objName:" << _objName << "|timecost(ms):" << (iEnd - iBegin) << endl);
}
if(vRouterCache.size() > 0)
{
size_t hash = ((int64_t)hashCode) % vRouterCache.size();
//这里做判断的原因是:32位系统下,如果hashCode为负值,hash经过上面的计算会是一个超大值,导致越界
if(hash >= vRouterCache.size())
{
hash = hash % vRouterCache.size();
}
size_t iIndex = vRouterCache[hash];
if(iIndex >= _vRegProxys.size())
{
iIndex = iIndex % _vRegProxys.size();
}
//被hash到的节点在主控是active的才走在流程
if (_vRegProxys[iIndex]->isActiveInReg() && _vRegProxys[iIndex]->checkActive())
{
return _vRegProxys[iIndex];
}
else
{
if(_activeProxys.empty())
{
TLOGERROR("[EndpointManager::getHashProxyForWeight _activeEndpoints is empty], bStatic:" << bStatic << endl);
return NULL;
}
//在active节点中再次hash
vector<AdapterProxy*> thisHash = _activeProxys;
vector<AdapterProxy*> conn;
do
{
hash = ((int64_t)hashCode) % thisHash.size();
//这里做判断的原因是:32位系统下,如果hashCode为负值,hash经过上面的计算会是一个超大值,导致越界
if(hash >= thisHash.size())
{
hash = hash % thisHash.size();
}
if (thisHash[hash]->checkActive(false))
{
return thisHash[hash];
}
if(!thisHash[hash]->isConnTimeout() &&
!thisHash[hash]->isConnExc())
{
conn.push_back(thisHash[hash]);
}
thisHash.erase(thisHash.begin() + hash);
}
while(!thisHash.empty());
if(conn.size() > 0)
{
hash = ((int64_t)hashCode) % conn.size();
//这里做判断的原因是:32位系统下,如果hashCode为负值,hash经过上面的计算会是一个超大值,导致越界
if(hash >= conn.size())