This repository has been archived by the owner on Dec 1, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 37
/
MetaClient.cpp
3800 lines (3443 loc) · 139 KB
/
MetaClient.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
/* Copyright (c) 2018 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License,
* attached with Common Clause Condition 1.0, found in the LICENSES directory.
*/
#include "common/base/Base.h"
#include "common/base/MurmurHash2.h"
#include "common/http/HttpClient.h"
#include "common/clients/meta/MetaClient.h"
#include "common/network/NetworkUtils.h"
#include "common/meta/NebulaSchemaProvider.h"
#include "common/conf/Configuration.h"
#include "common/stats/StatsManager.h"
#include "common/clients/meta/FileBasedClusterIdMan.h"
#include "common/webservice/Common.h"
#include "common/version/Version.h"
#include <folly/hash/Hash.h>
#include <folly/ScopeGuard.h>
#include <folly/executors/Async.h>
#include <folly/futures/Future.h>
#include <thrift/lib/cpp/util/EnumUtils.h>
DEFINE_uint32(expired_time_factor, 5, "The factor of expired time based on heart beat interval");
DEFINE_int32(heartbeat_interval_secs, 10, "Heartbeat interval");
DEFINE_int32(meta_client_retry_times, 3, "meta client retry times, 0 means no retry");
DEFINE_int32(meta_client_retry_interval_secs, 1,
"meta client sleep interval between retry");
DEFINE_int32(meta_client_timeout_ms, 60 * 1000,
"meta client timeout");
DEFINE_string(cluster_id_path, "cluster.id",
"file path saved clusterId");
namespace nebula {
namespace meta {
MetaClient::MetaClient(std::shared_ptr<folly::IOThreadPoolExecutor> ioThreadPool,
std::vector<HostAddr> addrs,
const MetaClientOptions& options)
: ioThreadPool_(ioThreadPool)
, addrs_(std::move(addrs))
, options_(options) {
CHECK(ioThreadPool_ != nullptr) << "IOThreadPool is required";
CHECK(!addrs_.empty())
<< "No meta server address is specified or can be solved. Meta server is required";
clientsMan_ = std::make_shared<
thrift::ThriftClientManager<cpp2::MetaServiceAsyncClient>
>();
updateActive();
updateLeader();
bgThread_ = std::make_unique<thread::GenericWorker>();
LOG(INFO) << "Create meta client to " << active_;
}
MetaClient::~MetaClient() {
stop();
VLOG(3) << "~MetaClient";
}
bool MetaClient::isMetadReady() {
auto ret = heartbeat().get();
if (!ret.ok() && ret.status() != Status::LeaderChanged()) {
LOG(ERROR) << "Heartbeat failed, status:" << ret.status();
ready_ = false;
return ready_;
}
bool ldRet = loadData();
bool lcRet = true;
if (!options_.skipConfig_) {
lcRet = loadCfg();
}
if (ldRet && lcRet) {
localLastUpdateTime_ = metadLastUpdateTime_;
}
return ready_;
}
bool MetaClient::waitForMetadReady(int count, int retryIntervalSecs) {
if (!options_.skipConfig_) {
std::string gflagsJsonPath;
GflagsManager::getGflagsModule(gflagsModule_);
gflagsDeclared_ = GflagsManager::declareGflags(gflagsModule_);
}
isRunning_ = true;
int tryCount = count;
while (!isMetadReady() && ((count == -1) || (tryCount > 0)) && isRunning_) {
LOG(INFO) << "Waiting for the metad to be ready!";
--tryCount;
::sleep(retryIntervalSecs);
} // end while
if (!isRunning_) {
LOG(ERROR) << "Connect to the MetaServer Failed";
return false;
}
CHECK(bgThread_->start());
LOG(INFO) << "Register time task for heartbeat!";
size_t delayMS = FLAGS_heartbeat_interval_secs * 1000 + folly::Random::rand32(900);
bgThread_->addDelayTask(delayMS, &MetaClient::heartBeatThreadFunc, this);
return ready_;
}
void MetaClient::stop() {
if (bgThread_ != nullptr) {
bgThread_->stop();
bgThread_->wait();
bgThread_.reset();
}
isRunning_ = false;
}
void MetaClient::heartBeatThreadFunc() {
SCOPE_EXIT {
bgThread_->addDelayTask(FLAGS_heartbeat_interval_secs * 1000,
&MetaClient::heartBeatThreadFunc,
this);
};
auto ret = heartbeat().get();
if (!ret.ok()) {
LOG(ERROR) << "Heartbeat failed, status:" << ret.status();
return;
}
// if MetaServer has some changes, refesh the localCache_
if (localLastUpdateTime_ < metadLastUpdateTime_) {
bool ldRet = loadData();
bool lcRet = true;
if (!options_.skipConfig_) {
lcRet = loadCfg();
}
if (ldRet && lcRet) {
localLastUpdateTime_ = metadLastUpdateTime_;
}
}
}
bool MetaClient::loadUsersAndRoles() {
auto userRoleRet = listUsers().get();
if (!userRoleRet.ok()) {
LOG(ERROR) << "List users failed, status:" << userRoleRet.status();
return false;
}
decltype(userRolesMap_) userRolesMap;
decltype(userPasswordMap_) userPasswordMap;
for (auto& user : userRoleRet.value()) {
auto rolesRet = getUserRoles(user.first).get();
if (!rolesRet.ok()) {
LOG(ERROR) << "List role by user failed, user : " << user.first;
return false;
}
userRolesMap[user.first] = rolesRet.value();
userPasswordMap[user.first] = user.second;
}
{
folly::RWSpinLock::WriteHolder holder(localCacheLock_);
userRolesMap_ = std::move(userRolesMap);
userPasswordMap_ = std::move(userPasswordMap);
}
return true;
}
bool MetaClient::loadData() {
if (ioThreadPool_->numThreads() <= 0) {
LOG(ERROR) << "The threads number in ioThreadPool should be greater than 0";
return false;
}
if (!loadUsersAndRoles()) {
LOG(ERROR) << "Load roles Failed";
return false;
}
if (!loadFulltextClients()) {
LOG(ERROR) << "Load fulltext services Failed";
return false;
}
if (!loadFulltextIndexes()) {
LOG(ERROR) << "Load fulltext indexes Failed";
return false;
}
auto ret = listSpaces().get();
if (!ret.ok()) {
LOG(ERROR) << "List space failed, status:" << ret.status();
return false;
}
decltype(localCache_) cache;
decltype(spaceIndexByName_) spaceIndexByName;
decltype(spaceTagIndexByName_) spaceTagIndexByName;
decltype(spaceEdgeIndexByName_) spaceEdgeIndexByName;
decltype(spaceNewestTagVerMap_) spaceNewestTagVerMap;
decltype(spaceNewestEdgeVerMap_) spaceNewestEdgeVerMap;
decltype(spaceEdgeIndexByType_) spaceEdgeIndexByType;
decltype(spaceTagIndexById_) spaceTagIndexById;
decltype(spaceAllEdgeMap_) spaceAllEdgeMap;
for (auto space : ret.value()) {
auto spaceId = space.first;
MetaClient::PartTerms partTerms;
auto r = getPartsAlloc(spaceId, &partTerms).get();
if (!r.ok()) {
LOG(ERROR) << "Get parts allocation failed for spaceId " << spaceId
<< ", status " << r.status();
return false;
}
auto spaceCache = std::make_shared<SpaceInfoCache>();
auto partsAlloc = r.value();
auto& spaceName = space.second;
spaceCache->partsOnHost_ = reverse(partsAlloc);
spaceCache->partsAlloc_ = std::move(partsAlloc);
spaceCache->termOfPartition_ = std::move(partTerms);
VLOG(2) << "Load space " << spaceId
<< ", parts num:" << spaceCache->partsAlloc_.size();
// loadSchemas
if (!loadSchemas(spaceId,
spaceCache,
spaceTagIndexByName,
spaceTagIndexById,
spaceEdgeIndexByName,
spaceEdgeIndexByType,
spaceNewestTagVerMap,
spaceNewestEdgeVerMap,
spaceAllEdgeMap)) {
LOG(ERROR) << "Load Schemas Failed";
return false;
}
if (!loadIndexes(spaceId, spaceCache)) {
LOG(ERROR) << "Load Indexes Failed";
return false;
}
if (!loadListeners(spaceId, spaceCache)) {
LOG(ERROR) << "Load Listeners Failed";
return false;
}
// get space properties
auto resp = getSpace(spaceName).get();
if (!resp.ok()) {
LOG(ERROR) << "Get space properties failed for space " << spaceId;
return false;
}
auto properties = resp.value().get_properties();
spaceCache->spaceDesc_ = std::move(properties);
cache.emplace(spaceId, spaceCache);
spaceIndexByName.emplace(space.second, spaceId);
}
auto hostsRet = listHosts().get();
if (!ret.ok()) {
LOG(ERROR) << "List hosts failed, status:" << hostsRet.status();
return false;
}
auto &hostItems = hostsRet.value();
std::vector<HostAddr> hosts(hostItems.size());
std::transform(hostItems.begin(), hostItems.end(), hosts.begin(),
[] (auto &hostItem) -> HostAddr {
return *hostItem.hostAddr_ref();
});
loadLeader(hostItems, spaceIndexByName_);
decltype(localCache_) oldCache;
{
folly::RWSpinLock::WriteHolder holder(localCacheLock_);
oldCache = std::move(localCache_);
localCache_ = std::move(cache);
spaceIndexByName_ = std::move(spaceIndexByName);
spaceTagIndexByName_ = std::move(spaceTagIndexByName);
spaceEdgeIndexByName_ = std::move(spaceEdgeIndexByName);
spaceNewestTagVerMap_ = std::move(spaceNewestTagVerMap);
spaceNewestEdgeVerMap_ = std::move(spaceNewestEdgeVerMap);
spaceEdgeIndexByType_ = std::move(spaceEdgeIndexByType);
spaceTagIndexById_ = std::move(spaceTagIndexById);
spaceAllEdgeMap_ = std::move(spaceAllEdgeMap);
storageHosts_ = std::move(hosts);
}
diff(oldCache, localCache_);
listenerDiff(oldCache, localCache_);
loadRemoteListeners();
ready_ = true;
return true;
}
bool MetaClient::loadSchemas(GraphSpaceID spaceId,
std::shared_ptr<SpaceInfoCache> spaceInfoCache,
SpaceTagNameIdMap &tagNameIdMap,
SpaceTagIdNameMap &tagIdNameMap,
SpaceEdgeNameTypeMap &edgeNameTypeMap,
SpaceEdgeTypeNameMap &edgeTypeNameMap,
SpaceNewestTagVerMap &newestTagVerMap,
SpaceNewestEdgeVerMap &newestEdgeVerMap,
SpaceAllEdgeMap &allEdgeMap) {
auto tagRet = listTagSchemas(spaceId).get();
if (!tagRet.ok()) {
LOG(ERROR) << "Get tag schemas failed for spaceId " << spaceId
<< ", " << tagRet.status();
return false;
}
auto edgeRet = listEdgeSchemas(spaceId).get();
if (!edgeRet.ok()) {
LOG(ERROR) << "Get edge schemas failed for spaceId " << spaceId
<< ", " << edgeRet.status();
return false;
}
auto tagItemVec = tagRet.value();
auto edgeItemVec = edgeRet.value();
allEdgeMap[spaceId] = {};
TagSchemas tagSchemas;
EdgeSchemas edgeSchemas;
TagID lastTagId = -1;
auto addSchemaField = [&spaceInfoCache](NebulaSchemaProvider* schema,
const cpp2::ColumnDef& col) {
bool hasDef = col.default_value_ref().has_value();
auto& colType = col.get_type();
size_t len = colType.type_length_ref().has_value() ? *colType.get_type_length() : 0;
bool nullable = col.nullable_ref().has_value() ? *col.get_nullable() : false;
Expression* defaultValueExpr = nullptr;
if (hasDef) {
auto encoded = *col.get_default_value();
defaultValueExpr = Expression::decode(
&(spaceInfoCache->pool_), folly::StringPiece(encoded.data(), encoded.size()));
if (defaultValueExpr == nullptr) {
LOG(ERROR) << "Wrong expr default value for column name: " << col.get_name();
hasDef = false;
}
}
schema->addField(col.get_name(),
colType.get_type(),
len,
nullable,
hasDef ? defaultValueExpr : nullptr);
};
for (auto& tagIt : tagItemVec) {
// meta will return the different version from new to old
auto schema = std::make_shared<NebulaSchemaProvider>(tagIt.get_version());
for (const auto& colIt : tagIt.get_schema().get_columns()) {
addSchemaField(schema.get(), colIt);
}
// handle schema property
schema->setProp(tagIt.get_schema().get_schema_prop());
if (tagIt.get_tag_id() != lastTagId) {
// init schema vector, since schema version is zero-based, need to add one
tagSchemas[tagIt.get_tag_id()].resize(schema->getVersion() + 1);
lastTagId = tagIt.get_tag_id();
}
tagSchemas[tagIt.get_tag_id()][schema->getVersion()] = std::move(schema);
tagNameIdMap.emplace(std::make_pair(spaceId, tagIt.get_tag_name()), tagIt.get_tag_id());
tagIdNameMap.emplace(std::make_pair(spaceId, tagIt.get_tag_id()), tagIt.get_tag_name());
// get the latest tag version
auto it = newestTagVerMap.find(std::make_pair(spaceId, tagIt.get_tag_id()));
if (it != newestTagVerMap.end()) {
if (it->second < tagIt.get_version()) {
it->second = tagIt.get_version();
}
} else {
newestTagVerMap.emplace(
std::make_pair(spaceId, tagIt.get_tag_id()), tagIt.get_version());
}
VLOG(3) << "Load Tag Schema Space " << spaceId
<< ", ID " << tagIt.get_tag_id()
<< ", Name " << tagIt.get_tag_name()
<< ", Version " << tagIt.get_version() << " Successfully!";
}
std::unordered_set<std::pair<GraphSpaceID, EdgeType>> edges;
EdgeType lastEdgeType = -1;
for (auto& edgeIt : edgeItemVec) {
// meta will return the different version from new to old
auto schema = std::make_shared<NebulaSchemaProvider>(edgeIt.get_version());
for (const auto& col : edgeIt.get_schema().get_columns()) {
addSchemaField(schema.get(), col);
}
// handle shcem property
schema->setProp(edgeIt.get_schema().get_schema_prop());
if (edgeIt.get_edge_type() != lastEdgeType) {
// init schema vector, since schema version is zero-based, need to add one
edgeSchemas[edgeIt.get_edge_type()].resize(schema->getVersion() + 1);
lastEdgeType = edgeIt.get_edge_type();
}
edgeSchemas[edgeIt.get_edge_type()][schema->getVersion()] = std::move(schema);
edgeNameTypeMap.emplace(
std::make_pair(spaceId, edgeIt.get_edge_name()), edgeIt.get_edge_type());
edgeTypeNameMap.emplace(
std::make_pair(spaceId, edgeIt.get_edge_type()), edgeIt.get_edge_name());
if (edges.find({spaceId, edgeIt.get_edge_type()}) != edges.cend()) {
continue;
}
edges.emplace(spaceId, edgeIt.get_edge_type());
allEdgeMap[spaceId].emplace_back(edgeIt.get_edge_name());
// get the latest edge version
auto it2 = newestEdgeVerMap.find(std::make_pair(spaceId, edgeIt.get_edge_type()));
if (it2 != newestEdgeVerMap.end()) {
if (it2->second < edgeIt.get_version()) {
it2->second = edgeIt.get_version();
}
} else {
newestEdgeVerMap.emplace(std::make_pair(spaceId, edgeIt.get_edge_type()),
edgeIt.get_version());
}
VLOG(3) << "Load Edge Schema Space " << spaceId
<< ", Type " << edgeIt.get_edge_type()
<< ", Name " << edgeIt.get_edge_name()
<< ", Version " << edgeIt.get_version()
<< " Successfully!";
}
spaceInfoCache->tagSchemas_ = std::move(tagSchemas);
spaceInfoCache->edgeSchemas_ = std::move(edgeSchemas);
return true;
}
bool MetaClient::loadIndexes(GraphSpaceID spaceId,
std::shared_ptr<SpaceInfoCache> cache) {
auto tagIndexesRet = listTagIndexes(spaceId).get();
if (!tagIndexesRet.ok()) {
LOG(ERROR) << "Get tag indexes failed for spaceId " << spaceId
<< ", " << tagIndexesRet.status();
return false;
}
auto edgeIndexesRet = listEdgeIndexes(spaceId).get();
if (!edgeIndexesRet.ok()) {
LOG(ERROR) << "Get edge indexes failed for spaceId " << spaceId
<< ", " << edgeIndexesRet.status();
return false;
}
Indexes tagIndexes;
for (auto tagIndex : tagIndexesRet.value()) {
auto indexName = tagIndex.get_index_name();
auto indexID = tagIndex.get_index_id();
std::pair<GraphSpaceID, std::string> pair(spaceId, indexName);
tagNameIndexMap_[pair] = indexID;
auto tagIndexPtr = std::make_shared<cpp2::IndexItem>(tagIndex);
tagIndexes.emplace(indexID, tagIndexPtr);
}
cache->tagIndexes_ = std::move(tagIndexes);
Indexes edgeIndexes;
for (auto& edgeIndex : edgeIndexesRet.value()) {
auto indexName = edgeIndex.get_index_name();
auto indexID = edgeIndex.get_index_id();
std::pair<GraphSpaceID, std::string> pair(spaceId, indexName);
edgeNameIndexMap_[pair] = indexID;
auto edgeIndexPtr = std::make_shared<cpp2::IndexItem>(edgeIndex);
edgeIndexes.emplace(indexID, edgeIndexPtr);
}
cache->edgeIndexes_ = std::move(edgeIndexes);
return true;
}
bool MetaClient::loadListeners(GraphSpaceID spaceId, std::shared_ptr<SpaceInfoCache> cache) {
auto listenerRet = listListener(spaceId).get();
if (!listenerRet.ok()) {
LOG(ERROR) << "Get listeners failed for spaceId " << spaceId
<< ", " << listenerRet.status();
return false;
}
Listeners listeners;
for (auto& listener : listenerRet.value()) {
listeners[listener.get_host()].emplace_back(
std::make_pair(listener.get_part_id(), listener.get_type()));
}
cache->listeners_ = std::move(listeners);
return true;
}
bool MetaClient::loadFulltextClients() {
auto ftRet = listFTClients().get();
if (!ftRet.ok()) {
LOG(ERROR) << "List fulltext services failed, status:" << ftRet.status();
return false;
}
{
folly::RWSpinLock::WriteHolder holder(localCacheLock_);
fulltextClientList_ = std::move(ftRet).value();
}
return true;
}
bool MetaClient::loadFulltextIndexes() {
auto ftRet = listFTIndexes().get();
if (!ftRet.ok()) {
LOG(ERROR) << "List fulltext indexes failed, status:" << ftRet.status();
return false;
}
{
folly::RWSpinLock::WriteHolder holder(localCacheLock_);
fulltextIndexMap_ = std::move(ftRet).value();
}
return true;
}
Status MetaClient::checkTagIndexed(GraphSpaceID space, IndexID indexID) {
folly::RWSpinLock::ReadHolder holder(localCacheLock_);
auto it = localCache_.find(space);
if (it != localCache_.end()) {
auto indexIt = it->second->tagIndexes_.find(indexID);
if (indexIt != it->second->tagIndexes_.end()) {
return Status::OK();
} else {
return Status::IndexNotFound();
}
}
return Status::SpaceNotFound();
}
Status MetaClient::checkEdgeIndexed(GraphSpaceID space, IndexID indexID) {
folly::RWSpinLock::ReadHolder holder(localCacheLock_);
auto it = localCache_.find(space);
if (it != localCache_.end()) {
auto indexIt = it->second->edgeIndexes_.find(indexID);
if (indexIt != it->second->edgeIndexes_.end()) {
return Status::OK();
} else {
return Status::IndexNotFound();
}
}
return Status::SpaceNotFound();
}
std::unordered_map<HostAddr, std::vector<PartitionID>>
MetaClient::reverse(const PartsAlloc& parts) {
std::unordered_map<HostAddr, std::vector<PartitionID>> hosts;
for (auto& partHost : parts) {
for (auto& h : partHost.second) {
hosts[h].emplace_back(partHost.first);
}
}
return hosts;
}
template<typename Request,
typename RemoteFunc,
typename RespGenerator,
typename RpcResponse,
typename Response>
void MetaClient::getResponse(Request req,
RemoteFunc remoteFunc,
RespGenerator respGen,
folly::Promise<StatusOr<Response>> pro,
bool toLeader,
int32_t retry,
int32_t retryLimit) {
auto* evb = ioThreadPool_->getEventBase();
HostAddr host;
{
folly::RWSpinLock::ReadHolder holder(&hostLock_);
host = toLeader ? leader_ : active_;
}
folly::via(evb, [host,
evb,
req = std::move(req),
remoteFunc = std::move(remoteFunc),
respGen = std::move(respGen),
pro = std::move(pro),
toLeader,
retry,
retryLimit,
this] () mutable {
auto client = clientsMan_->client(host, evb, false, FLAGS_meta_client_timeout_ms);
VLOG(1) << "Send request to meta " << host;
remoteFunc(client, req)
.via(evb)
.then([host,
req = std::move(req),
remoteFunc = std::move(remoteFunc),
respGen = std::move(respGen),
pro = std::move(pro),
toLeader,
retry,
retryLimit,
evb,
this] (folly::Try<RpcResponse>&& t) mutable {
// exception occurred during RPC
if (t.hasException()) {
if (toLeader) {
updateLeader();
} else {
updateActive();
}
if (retry < retryLimit) {
evb->runAfterDelay([req = std::move(req),
remoteFunc = std::move(remoteFunc),
respGen = std::move(respGen),
pro = std::move(pro),
toLeader,
retry,
retryLimit,
this] () mutable {
getResponse(std::move(req),
std::move(remoteFunc),
std::move(respGen),
std::move(pro),
toLeader,
retry + 1,
retryLimit);
}, FLAGS_meta_client_retry_interval_secs * 1000);
return;
} else {
LOG(ERROR) << "Send request to " << host << ", exceed retry limit";
pro.setValue(Status::Error("RPC failure in MetaClient: %s",
t.exception().what().c_str()));
}
return;
}
auto&& resp = t.value();
if (resp.get_code() == nebula::cpp2::ErrorCode::SUCCEEDED) {
// succeeded
pro.setValue(respGen(std::move(resp)));
return;
} else if (resp.get_code() == nebula::cpp2::ErrorCode::E_LEADER_CHANGED) {
updateLeader(resp.get_leader());
if (retry < retryLimit) {
evb->runAfterDelay([req = std::move(req),
remoteFunc = std::move(remoteFunc),
respGen = std::move(respGen),
pro = std::move(pro),
toLeader,
retry,
retryLimit,
this] () mutable {
getResponse(std::move(req),
std::move(remoteFunc),
std::move(respGen),
std::move(pro),
toLeader,
retry + 1,
retryLimit);
}, FLAGS_meta_client_retry_interval_secs * 1000);
return;
}
}
pro.setValue(this->handleResponse(resp));
}); // then
}); // via
}
std::vector<SpaceIdName>
MetaClient::toSpaceIdName(const std::vector<cpp2::IdName>& tIdNames) {
std::vector<SpaceIdName> idNames;
idNames.resize(tIdNames.size());
std::transform(tIdNames.begin(), tIdNames.end(), idNames.begin(), [](const auto& tin) {
return SpaceIdName(tin.get_id().get_space_id(), tin.get_name());
});
return idNames;
}
template<typename RESP>
Status MetaClient::handleResponse(const RESP& resp) {
switch (resp.get_code()) {
case nebula::cpp2::ErrorCode::SUCCEEDED:
return Status::OK();
case nebula::cpp2::ErrorCode::E_DISCONNECTED:
return Status::Error("Disconnected!");
case nebula::cpp2::ErrorCode::E_FAIL_TO_CONNECT:
return Status::Error("Fail to connect!");
case nebula::cpp2::ErrorCode::E_RPC_FAILURE:
return Status::Error("Rpc failure!");
case nebula::cpp2::ErrorCode::E_LEADER_CHANGED:
return Status::LeaderChanged("Leader changed!");
case nebula::cpp2::ErrorCode::E_NO_HOSTS:
return Status::Error("No hosts!");
case nebula::cpp2::ErrorCode::E_EXISTED:
return Status::Error("Existed!");
case nebula::cpp2::ErrorCode::E_SPACE_NOT_FOUND:
return Status::Error("Space not existed!");
case nebula::cpp2::ErrorCode::E_TAG_NOT_FOUND:
return Status::Error("Tag not existed!");
case nebula::cpp2::ErrorCode::E_EDGE_NOT_FOUND:
return Status::Error("Edge not existed!");
case nebula::cpp2::ErrorCode::E_INDEX_NOT_FOUND:
return Status::Error("Index not existed!");
case nebula::cpp2::ErrorCode::E_EDGE_PROP_NOT_FOUND:
return Status::Error("Edge prop not existed!");
case nebula::cpp2::ErrorCode::E_TAG_PROP_NOT_FOUND:
return Status::Error("Tag prop not existed!");
case nebula::cpp2::ErrorCode::E_ROLE_NOT_FOUND:
return Status::Error("Role not existed!");
case nebula::cpp2::ErrorCode::E_CONFIG_NOT_FOUND:
return Status::Error("Conf not existed!");
case nebula::cpp2::ErrorCode::E_PART_NOT_FOUND:
return Status::Error("Part not existed!");
case nebula::cpp2::ErrorCode::E_USER_NOT_FOUND:
return Status::Error("User not existed!");
case nebula::cpp2::ErrorCode::E_GROUP_NOT_FOUND:
return Status::Error("Group not existed!");
case nebula::cpp2::ErrorCode::E_ZONE_NOT_FOUND:
return Status::Error("Zone not existed!");
case nebula::cpp2::ErrorCode::E_KEY_NOT_FOUND:
return Status::Error("Key not existed!");
case nebula::cpp2::ErrorCode::E_INVALID_HOST:
return Status::Error("Invalid host!");
case nebula::cpp2::ErrorCode::E_UNSUPPORTED:
return Status::Error("Unsupported!");
case nebula::cpp2::ErrorCode::E_NOT_DROP:
return Status::Error("Not allowed to drop!");
case nebula::cpp2::ErrorCode::E_BALANCER_RUNNING:
return Status::Error("The balancer is running!");
case nebula::cpp2::ErrorCode::E_CONFIG_IMMUTABLE:
return Status::Error("Config immutable!");
case nebula::cpp2::ErrorCode::E_CONFLICT:
return Status::Error("Conflict!");
case nebula::cpp2::ErrorCode::E_INVALID_PARM:
return Status::Error("Invalid parm!");
case nebula::cpp2::ErrorCode::E_WRONGCLUSTER:
return Status::Error("Wrong cluster!");
case nebula::cpp2::ErrorCode::E_STORE_FAILURE:
return Status::Error("Store failure!");
case nebula::cpp2::ErrorCode::E_STORE_SEGMENT_ILLEGAL:
return Status::Error("Store segment illegal!");
case nebula::cpp2::ErrorCode::E_BAD_BALANCE_PLAN:
return Status::Error("Bad balance plan!");
case nebula::cpp2::ErrorCode::E_BALANCED:
return Status::Error("The cluster is balanced!");
case nebula::cpp2::ErrorCode::E_NO_RUNNING_BALANCE_PLAN:
return Status::Error("No running balance plan!");
case nebula::cpp2::ErrorCode::E_NO_VALID_HOST:
return Status::Error("No valid host hold the partition!");
case nebula::cpp2::ErrorCode::E_CORRUPTTED_BALANCE_PLAN:
return Status::Error("No corrupted blance plan!");
case nebula::cpp2::ErrorCode::E_INVALID_PASSWORD:
return Status::Error("Invalid password!");
case nebula::cpp2::ErrorCode::E_IMPROPER_ROLE:
return Status::Error("Improper role!");
case nebula::cpp2::ErrorCode::E_INVALID_PARTITION_NUM:
return Status::Error("No valid partition_num!");
case nebula::cpp2::ErrorCode::E_INVALID_REPLICA_FACTOR:
return Status::Error("No valid replica_factor!");
case nebula::cpp2::ErrorCode::E_INVALID_CHARSET:
return Status::Error("No valid charset!");
case nebula::cpp2::ErrorCode::E_INVALID_COLLATE:
return Status::Error("No valid collate!");
case nebula::cpp2::ErrorCode::E_CHARSET_COLLATE_NOT_MATCH:
return Status::Error("Charset and collate not match!");
case nebula::cpp2::ErrorCode::E_SNAPSHOT_FAILURE:
return Status::Error("Snapshot failure!");
case nebula::cpp2::ErrorCode::E_BLOCK_WRITE_FAILURE:
return Status::Error("Block write failure!");
case nebula::cpp2::ErrorCode::E_REBUILD_INDEX_FAILED:
return Status::Error("Rebuild index failed!");
case nebula::cpp2::ErrorCode::E_INDEX_WITH_TTL:
return Status::Error("Index with ttl!");
case nebula::cpp2::ErrorCode::E_ADD_JOB_FAILURE:
return Status::Error("Add job failure!");
case nebula::cpp2::ErrorCode::E_STOP_JOB_FAILURE:
return Status::Error("Stop job failure!");
case nebula::cpp2::ErrorCode::E_SAVE_JOB_FAILURE:
return Status::Error("Save job failure!");
case nebula::cpp2::ErrorCode::E_BALANCER_FAILURE:
return Status::Error("Balance failure!");
case nebula::cpp2::ErrorCode::E_NO_INVALID_BALANCE_PLAN:
return Status::Error("No invalid balance plan!");
case nebula::cpp2::ErrorCode::E_JOB_NOT_FINISHED:
return Status::Error("Job is not finished!");
case nebula::cpp2::ErrorCode::E_TASK_REPORT_OUT_DATE:
return Status::Error("Task report is out of date!");
case nebula::cpp2::ErrorCode::E_BACKUP_FAILED:
return Status::Error("Backup failure!");
case nebula::cpp2::ErrorCode::E_BACKUP_BUILDING_INDEX:
return Status::Error("Backup building indexes!");
case nebula::cpp2::ErrorCode::E_BACKUP_SPACE_NOT_FOUND:
return Status::Error("The space is not found when backup!");
case nebula::cpp2::ErrorCode::E_RESTORE_FAILURE:
return Status::Error("Restore failure!");
case nebula::cpp2::ErrorCode::E_LIST_CLUSTER_FAILURE:
return Status::Error("list cluster failure!");
case nebula::cpp2::ErrorCode::E_LIST_CLUSTER_GET_ABS_PATH_FAILURE:
return Status::Error("Failed to get the absolute path!");
case nebula::cpp2::ErrorCode::E_GET_META_DIR_FAILURE:
return Status::Error("Failed to get meta dir!");
case nebula::cpp2::ErrorCode::E_INVALID_JOB:
return Status::Error("No valid job!");
case nebula::cpp2::ErrorCode::E_BACKUP_EMPTY_TABLE:
return Status::Error("Backup empty table!");
case nebula::cpp2::ErrorCode::E_BACKUP_TABLE_FAILED:
return Status::Error("Backup table failure!");
case nebula::cpp2::ErrorCode::E_SESSION_NOT_FOUND:
return Status::Error("Session not existed!");
default:
return Status::Error("Unknown error!");
}
}
PartsMap MetaClient::doGetPartsMap(const HostAddr& host,
const LocalCache& localCache) {
PartsMap partMap;
for (auto it = localCache.begin(); it != localCache.end(); it++) {
auto spaceId = it->first;
auto& cache = it->second;
auto partsIt = cache->partsOnHost_.find(host);
if (partsIt != cache->partsOnHost_.end()) {
for (auto& partId : partsIt->second) {
auto partAllocIter = cache->partsAlloc_.find(partId);
CHECK(partAllocIter != cache->partsAlloc_.end());
auto& partM = partMap[spaceId][partId];
partM.spaceId_ = spaceId;
partM.partId_ = partId;
partM.hosts_ = partAllocIter->second;
}
}
}
return partMap;
}
void MetaClient::diff(const LocalCache& oldCache, const LocalCache& newCache) {
folly::RWSpinLock::WriteHolder holder(listenerLock_);
if (listener_ == nullptr) {
VLOG(3) << "Listener is null!";
return;
}
auto newPartsMap = doGetPartsMap(options_.localHost_, newCache);
auto oldPartsMap = doGetPartsMap(options_.localHost_, oldCache);
VLOG(1) << "Let's check if any new parts added/updated for " << options_.localHost_;
for (auto it = newPartsMap.begin(); it != newPartsMap.end(); it++) {
auto spaceId = it->first;
const auto& newParts = it->second;
auto oldIt = oldPartsMap.find(spaceId);
if (oldIt == oldPartsMap.end()) {
VLOG(1) << "SpaceId " << spaceId << " was added!";
listener_->onSpaceAdded(spaceId);
for (auto partIt = newParts.begin(); partIt != newParts.end(); partIt++) {
listener_->onPartAdded(partIt->second);
}
} else {
const auto& oldParts = oldIt->second;
for (auto partIt = newParts.begin(); partIt != newParts.end(); partIt++) {
auto oldPartIt = oldParts.find(partIt->first);
if (oldPartIt == oldParts.end()) {
VLOG(1) << "SpaceId " << spaceId << ", partId "
<< partIt->first << " was added!";
listener_->onPartAdded(partIt->second);
} else {
const auto& oldPartHosts = oldPartIt->second;
const auto& newPartHosts = partIt->second;
if (oldPartHosts != newPartHosts) {
VLOG(1) << "SpaceId " << spaceId
<< ", partId " << partIt->first << " was updated!";
listener_->onPartUpdated(newPartHosts);
}
}
}
}
}
VLOG(1) << "Let's check if any old parts removed....";
for (auto it = oldPartsMap.begin(); it != oldPartsMap.end(); it++) {
auto spaceId = it->first;
const auto& oldParts = it->second;
auto newIt = newPartsMap.find(spaceId);
if (newIt == newPartsMap.end()) {
VLOG(1) << "SpaceId " << spaceId << " was removed!";
for (auto partIt = oldParts.begin(); partIt != oldParts.end(); partIt++) {
listener_->onPartRemoved(spaceId, partIt->first);
}
listener_->onSpaceRemoved(spaceId);
} else {
const auto& newParts = newIt->second;
for (auto partIt = oldParts.begin(); partIt != oldParts.end(); partIt++) {
auto newPartIt = newParts.find(partIt->first);
if (newPartIt == newParts.end()) {
VLOG(1) << "SpaceId " << spaceId
<< ", partId " << partIt->first << " was removed!";
listener_->onPartRemoved(spaceId, partIt->first);
}
}
}
}
}
void MetaClient::listenerDiff(const LocalCache& oldCache, const LocalCache& newCache) {
folly::RWSpinLock::WriteHolder holder(listenerLock_);
if (listener_ == nullptr) {
VLOG(3) << "Listener is null!";
return;
}
auto newMap = doGetListenersMap(options_.localHost_, newCache);
auto oldMap = doGetListenersMap(options_.localHost_, oldCache);
if (newMap == oldMap) {
return;
}
VLOG(1) << "Let's check if any listeners parts added for " << options_.localHost_;
for (auto& spaceEntry : newMap) {
auto spaceId = spaceEntry.first;
auto oldSpaceIter = oldMap.find(spaceId);
if (oldSpaceIter == oldMap.end()) {
// new space is added
VLOG(1) << "[Listener] SpaceId " << spaceId << " was added!";
listener_->onSpaceAdded(spaceId, true);
for (const auto& partEntry : spaceEntry.second) {
auto partId = partEntry.first;
for (const auto& info : partEntry.second) {
VLOG(1) << "[Listener] SpaceId " << spaceId << ", partId " << partId
<< " was added!";
listener_->onListenerAdded(spaceId, partId, info);
}
}
} else {
// check if new part listener is added
for (auto& partEntry : spaceEntry.second) {
auto partId = partEntry.first;
auto oldPartIter = oldSpaceIter->second.find(partId);
if (oldPartIter == oldSpaceIter->second.end()) {
for (const auto& info : partEntry.second) {
VLOG(1) << "[Listener] SpaceId " << spaceId << ", partId " << partId
<< " was added!";
listener_->onListenerAdded(spaceId, partId, info);
}
} else {
std::sort(partEntry.second.begin(), partEntry.second.end());
std::sort(oldPartIter->second.begin(), oldPartIter->second.end());
std::vector<ListenerHosts> diff;
std::set_difference(partEntry.second.begin(),
partEntry.second.end(),
oldPartIter->second.begin(),
oldPartIter->second.end(),
std::back_inserter(diff));
for (const auto& info : diff) {
VLOG(1) << "[Listener] SpaceId " << spaceId << ", partId " << partId
<< " was added!";
listener_->onListenerAdded(spaceId, partId, info);
}
}
}
}
}
VLOG(1) << "Let's check if any old listeners removed....";
for (auto& spaceEntry : oldMap) {
auto spaceId = spaceEntry.first;
auto newSpaceIter = newMap.find(spaceId);
if (newSpaceIter == newMap.end()) {
// remove old space
for (const auto& partEntry : spaceEntry.second) {
auto partId = partEntry.first;
for (const auto& info : partEntry.second) {
VLOG(1) << "SpaceId " << spaceId << ", partId " << partId << " was removed!";
listener_->onListenerRemoved(spaceId, partId, info.type_);
}
}
listener_->onSpaceRemoved(spaceId, true);
VLOG(1) << "[Listener] SpaceId " << spaceId << " was removed!";
} else {
// check if part listener is removed
for (auto& partEntry : spaceEntry.second) {
auto partId = partEntry.first;
auto newPartIter = newSpaceIter->second.find(partId);
if (newPartIter == newSpaceIter->second.end()) {
for (const auto& info : partEntry.second) {
VLOG(1) << "[Listener] SpaceId " << spaceId << ", partId " << partId
<< " was removed!";
listener_->onListenerRemoved(spaceId, partId, info.type_);
}
} else {
std::sort(partEntry.second.begin(), partEntry.second.end());
std::sort(newPartIter->second.begin(), newPartIter->second.end());
std::vector<ListenerHosts> diff;
std::set_difference(partEntry.second.begin(),
partEntry.second.end(),
newPartIter->second.begin(),
newPartIter->second.end(),
std::back_inserter(diff));
for (const auto& info : diff) {
VLOG(1) << "[Listener] SpaceId " << spaceId << ", partId " << partId
<< " was removed!";
listener_->onListenerRemoved(spaceId, partId, info.type_);