-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
MetaClient.cpp
3898 lines (3625 loc) · 143 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.
*/
#include "clients/meta/MetaClient.h"
#include <folly/ScopeGuard.h>
#include <folly/executors/Async.h>
#include <folly/futures/Future.h>
#include <folly/hash/Hash.h>
#include <thrift/lib/cpp/util/EnumUtils.h>
#include <boost/filesystem.hpp>
#include <unordered_set>
#include "clients/meta/FileBasedClusterIdMan.h"
#include "clients/meta/stats/MetaClientStats.h"
#include "common/base/Base.h"
#include "common/base/MurmurHash2.h"
#include "common/conf/Configuration.h"
#include "common/http/HttpClient.h"
#include "common/meta/NebulaSchemaProvider.h"
#include "common/network/NetworkUtils.h"
#include "common/ssl/SSLConfig.h"
#include "common/stats/StatsManager.h"
#include "common/time/TimeUtils.h"
#include "version/Version.h"
#include "webservice/Common.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 in seconds");
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");
DEFINE_int32(check_plan_killed_frequency, 8, "check plan killed every 1<<n times");
DEFINE_uint32(failed_login_attempts,
0,
"how many consecutive incorrect passwords input to a SINGLE graph service node cause "
"the account to become locked.");
DEFINE_uint32(
password_lock_time_in_secs,
0,
"how long in seconds to lock the account after too many consecutive login attempts provide an "
"incorrect password.");
// Sanity-checking Flag Values
static bool ValidateFailedLoginAttempts(const char* flagname, uint32_t value) {
if (value <= 32767) // value is ok
return true;
FLOG_WARN("Invalid value for --%s: %d, the timeout should be an integer between 0 and 32767\n",
flagname,
(int)value);
return false;
}
DEFINE_validator(failed_login_attempts, &ValidateFailedLoginAttempts);
namespace nebula {
namespace meta {
Indexes buildIndexes(std::vector<cpp2::IndexItem> indexItemVec);
MetaClient::MetaClient(std::shared_ptr<folly::IOThreadPoolExecutor> ioThreadPool,
std::vector<HostAddr> addrs,
const MetaClientOptions& options)
: ioThreadPool_(ioThreadPool),
addrs_(std::move(addrs)),
options_(options),
metadata_(new MetaData()) {
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>>(
FLAGS_enable_ssl || FLAGS_enable_meta_ssl);
updateActive();
updateLeader();
bgThread_ = std::make_unique<thread::GenericWorker>();
LOG(INFO) << "Create meta client to " << active_;
LOG(INFO) << folly::sformat(
"root path: {}, data path size: {}", options_.rootPath_, options_.dataPaths_.size());
}
MetaClient::~MetaClient() {
notifyStop();
stop();
delete metadata_.load();
VLOG(3) << "~MetaClient";
}
#ifdef BUILD_STANDALONE
StatusOr<bool> MetaClient::checkLocalMachineRegistered() {
auto ret = heartbeat().get();
if (!ret.ok()) {
if (ret.status().toString() == "Machine not existed!") {
return false;
}
LOG(ERROR) << "Check register failed: " << ret.status();
return Status::Error("Check register failed!");
}
return true;
}
#endif
bool MetaClient::isMetadReady() {
// UNKNOWN is reserved for tools such as upgrader, in that case the ip/port is not set. We do
// not send heartbeat to meta to avoid writing error host info (e.g. Host("", 0))
if (options_.role_ != cpp2::HostRole::UNKNOWN) {
auto ret = heartbeat().get();
if (!ret.ok()) {
LOG(ERROR) << "Heartbeat failed, status:" << ret.status();
return ready_;
} else if (options_.role_ == cpp2::HostRole::STORAGE &&
metaServerVersion_ != EXPECT_META_VERSION) {
LOG(ERROR) << "Expect meta version is " << EXPECT_META_VERSION << ", but actual is "
<< metaServerVersion_;
return ready_;
}
}
// ready_ will be set in loadData
loadData();
loadCfg();
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;
}
// Verify the graph server version
auto status = verifyVersion();
if (!status.ok()) {
LOG(ERROR) << status;
return false;
}
// Save graph version to meta
status = saveVersionToMeta();
if (!status.ok()) {
LOG(ERROR) << status;
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::notifyStop() {
if (bgThread_ != nullptr) {
bgThread_->stop();
}
isRunning_ = false;
}
void MetaClient::stop() {
if (bgThread_ != nullptr) {
bgThread_->wait();
bgThread_.reset();
}
}
void MetaClient::heartBeatThreadFunc() {
SCOPE_EXIT {
bgThread_->addDelayTask(
FLAGS_heartbeat_interval_secs * 1000, &MetaClient::heartBeatThreadFunc, this);
};
// UNKNOWN is reserved for tools such as upgrader, in that case the ip/port is not set. We do
// not send heartbeat to meta to avoid writing error host info (e.g. Host("", 0))
if (options_.role_ != cpp2::HostRole::UNKNOWN) {
auto ret = heartbeat().get();
if (!ret.ok()) {
LOG(ERROR) << "Heartbeat failed, status:" << ret.status();
return;
}
}
// if MetaServer has some changes, refresh the localCache_
loadData();
loadCfg();
}
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;
// List of username
std::unordered_set<std::string> userNameList;
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;
userNameList.emplace(user.first);
}
userRolesMap_ = std::move(userRolesMap);
userPasswordMap_ = std::move(userPasswordMap);
// Remove expired users from cache
auto removeExpiredUser = [&](folly::ConcurrentHashMap<std::string, uint32>& userMap,
const std::unordered_set<std::string>& userList) {
for (auto iter = userMap.begin(); iter != userMap.end();) {
if (!userList.count(iter->first)) {
iter = userMap.erase(iter);
} else {
++iter;
}
}
};
removeExpiredUser(userPasswordAttemptsRemain_, userNameList);
removeExpiredUser(userLoginLockTime_, userNameList);
// This method is called periodically by the heartbeat thread, but we don't want to reset the
// failed login attempts every time.
for (const auto& user : userNameList) {
// If the user is not in the map, insert value with the default value
// Do nothing if the account is already in the map
if (userPasswordAttemptsRemain_.find(user) == userPasswordAttemptsRemain_.end()) {
userPasswordAttemptsRemain_.insert(user, FLAGS_failed_login_attempts);
}
if (userLoginLockTime_.find(user) == userLoginLockTime_.end()) {
userLoginLockTime_.insert(user, 0);
}
}
return true;
}
bool MetaClient::loadData() {
memory::MemoryCheckOffGuard g;
// UNKNOWN role will skip heartbeat
if (options_.role_ != cpp2::HostRole::UNKNOWN &&
localDataLastUpdateTime_ == metadLastUpdateTime_) {
return true;
}
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 (!loadGlobalServiceClients()) {
LOG(ERROR) << "Load global services Failed";
return false;
}
if (!loadFulltextIndexes()) {
LOG(ERROR) << "Load fulltext indexes Failed";
return false;
}
if (!loadSessions()) {
LOG(ERROR) << "Load sessions 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 (!hostsRet.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();
});
decltype(localCache_) oldCache;
{
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);
}
loadLeader(hostItems, spaceIndexByName_);
localDataLastUpdateTime_.store(metadLastUpdateTime_.load());
auto newMetaData = new MetaData();
for (auto& spaceInfo : localCache_) {
GraphSpaceID spaceId = spaceInfo.first;
std::shared_ptr<SpaceInfoCache> info = spaceInfo.second;
std::shared_ptr<SpaceInfoCache> infoDeepCopy = std::make_shared<SpaceInfoCache>(*info);
infoDeepCopy->tagSchemas_ = buildTagSchemas(infoDeepCopy->tagItemVec_);
infoDeepCopy->edgeSchemas_ = buildEdgeSchemas(infoDeepCopy->edgeItemVec_);
infoDeepCopy->tagIndexes_ = buildIndexes(infoDeepCopy->tagIndexItemVec_);
infoDeepCopy->edgeIndexes_ = buildIndexes(infoDeepCopy->edgeIndexItemVec_);
newMetaData->localCache_[spaceId] = infoDeepCopy;
}
newMetaData->spaceIndexByName_ = spaceIndexByName_;
newMetaData->spaceTagIndexByName_ = spaceTagIndexByName_;
newMetaData->spaceEdgeIndexByName_ = spaceEdgeIndexByName_;
newMetaData->spaceEdgeIndexByType_ = spaceEdgeIndexByType_;
newMetaData->spaceNewestTagVerMap_ = spaceNewestTagVerMap_;
newMetaData->spaceNewestEdgeVerMap_ = spaceNewestEdgeVerMap_;
newMetaData->spaceTagIndexById_ = spaceTagIndexById_;
newMetaData->spaceAllEdgeMap_ = spaceAllEdgeMap_;
newMetaData->userRolesMap_ = userRolesMap_;
newMetaData->storageHosts_ = storageHosts_;
newMetaData->fulltextIndexMap_ = fulltextIndexMap_;
newMetaData->userPasswordMap_ = userPasswordMap_;
newMetaData->sessionMap_ = std::move(sessionMap_);
newMetaData->killedPlans_ = std::move(killedPlans_);
newMetaData->serviceClientList_ = std::move(serviceClientList_);
auto oldMetaData = metadata_.load();
metadata_.store(newMetaData);
folly::rcu_retire(oldMetaData);
diff(oldCache, localCache_);
listenerDiff(oldCache, localCache_);
loadRemoteListeners();
ready_ = true;
return true;
}
TagSchemas MetaClient::buildTagSchemas(std::vector<cpp2::TagItem> tagItemVec) {
memory::MemoryCheckOffGuard g;
TagSchemas tagSchemas;
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());
auto& schemas = tagSchemas[tagIt.get_tag_id()];
// Because of the byte order of schema version in meta is not same as numerical order, we have
// to check schema version
if (schemas.size() <= static_cast<size_t>(schema->getVersion())) {
// since schema version is zero-based, need to add one
schemas.resize(schema->getVersion() + 1);
}
schemas[schema->getVersion()] = std::move(schema);
}
return tagSchemas;
}
EdgeSchemas MetaClient::buildEdgeSchemas(std::vector<cpp2::EdgeItem> edgeItemVec) {
memory::MemoryCheckOffGuard g;
EdgeSchemas edgeSchemas;
std::unordered_set<std::pair<GraphSpaceID, EdgeType>> edges;
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()) {
MetaClient::addSchemaField(schema.get(), col);
}
// handle shcem property
schema->setProp(edgeIt.get_schema().get_schema_prop());
auto& schemas = edgeSchemas[edgeIt.get_edge_type()];
// Because of the byte order of schema version in meta is not same as numerical order, we have
// to check schema version
if (schemas.size() <= static_cast<size_t>(schema->getVersion())) {
// since schema version is zero-based, need to add one
schemas.resize(schema->getVersion() + 1);
}
schemas[schema->getVersion()] = std::move(schema);
}
return edgeSchemas;
}
void MetaClient::addSchemaField(NebulaSchemaProvider* schema, const cpp2::ColumnDef& col) {
memory::MemoryCheckOffGuard g;
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;
cpp2::GeoShape geoShape =
colType.geo_shape_ref().has_value() ? *colType.get_geo_shape() : cpp2::GeoShape::ANY;
bool nullable = col.nullable_ref().has_value() ? *col.get_nullable() : false;
std::string encoded;
if (hasDef) {
encoded = *col.get_default_value();
}
schema->addField(col.get_name(), colType.get_type(), len, nullable, encoded, geoShape);
}
bool MetaClient::loadSchemas(GraphSpaceID spaceId,
std::shared_ptr<SpaceInfoCache> spaceInfoCache,
SpaceTagNameIdMap& tagNameIdMap,
SpaceTagIdNameMap& tagIdNameMap,
SpaceEdgeNameTypeMap& edgeNameTypeMap,
SpaceEdgeTypeNameMap& edgeTypeNameMap,
SpaceNewestTagVerMap& newestTagVerMap,
SpaceNewestEdgeVerMap& newestEdgeVerMap,
SpaceAllEdgeMap& allEdgeMap) {
memory::MemoryCheckOffGuard g;
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] = {};
spaceInfoCache->tagItemVec_ = tagItemVec;
spaceInfoCache->tagSchemas_ = buildTagSchemas(tagItemVec);
spaceInfoCache->edgeItemVec_ = edgeItemVec;
spaceInfoCache->edgeSchemas_ = buildEdgeSchemas(edgeItemVec);
for (auto& tagIt : tagItemVec) {
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;
for (auto& edgeIt : edgeItemVec) {
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!";
}
return true;
}
Indexes buildIndexes(std::vector<cpp2::IndexItem> indexItemVec) {
memory::MemoryCheckOffGuard g;
Indexes indexes;
for (auto index : indexItemVec) {
auto indexName = index.get_index_name();
auto indexID = index.get_index_id();
auto indexPtr = std::make_shared<cpp2::IndexItem>(index);
indexes.emplace(indexID, indexPtr);
}
return indexes;
}
bool MetaClient::loadIndexes(GraphSpaceID spaceId, std::shared_ptr<SpaceInfoCache> cache) {
memory::MemoryCheckOffGuard g;
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;
}
auto tagIndexItemVec = tagIndexesRet.value();
cache->tagIndexItemVec_ = tagIndexItemVec;
cache->tagIndexes_ = buildIndexes(tagIndexItemVec);
for (const auto& tagIndex : tagIndexItemVec) {
auto indexName = tagIndex.get_index_name();
auto indexID = tagIndex.get_index_id();
std::pair<GraphSpaceID, std::string> pair(spaceId, indexName);
tagNameIndexMap_[pair] = indexID;
}
auto edgeIndexItemVec = edgeIndexesRet.value();
cache->edgeIndexItemVec_ = edgeIndexItemVec;
cache->edgeIndexes_ = buildIndexes(edgeIndexItemVec);
for (auto& edgeIndex : edgeIndexItemVec) {
auto indexName = edgeIndex.get_index_name();
auto indexID = edgeIndex.get_index_id();
std::pair<GraphSpaceID, std::string> pair(spaceId, indexName);
edgeNameIndexMap_[pair] = indexID;
}
return true;
}
bool MetaClient::loadListeners(GraphSpaceID spaceId, std::shared_ptr<SpaceInfoCache> cache) {
memory::MemoryCheckOffGuard g;
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::loadGlobalServiceClients() {
memory::MemoryCheckOffGuard g;
auto ret = listServiceClients(cpp2::ExternalServiceType::ELASTICSEARCH).get();
if (!ret.ok()) {
LOG(ERROR) << "List services failed, status:" << ret.status();
return false;
}
serviceClientList_ = std::move(ret).value();
return true;
}
bool MetaClient::loadFulltextIndexes() {
memory::MemoryCheckOffGuard g;
auto ftRet = listFTIndexes().get();
if (!ftRet.ok()) {
LOG(ERROR) << "List fulltext indexes failed, status:" << ftRet.status();
return false;
}
fulltextIndexMap_ = std::move(ftRet).value();
return true;
}
Status MetaClient::checkTagIndexed(GraphSpaceID spaceId, IndexID indexID) {
memory::MemoryCheckOffGuard g;
folly::rcu_reader guard;
const auto& metadata = *metadata_.load();
auto it = metadata.localCache_.find(spaceId);
if (it != metadata.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) {
memory::MemoryCheckOffGuard g;
folly::rcu_reader guard;
const auto& metadata = *metadata_.load();
auto it = metadata.localCache_.find(space);
if (it != metadata.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) {
memory::MemoryCheckOffGuard g;
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) {
memory::MemoryCheckOffGuard g;
stats::StatsManager::addValue(kNumRpcSentToMetad);
auto* evb = ioThreadPool_->getEventBase();
HostAddr host;
{
folly::SharedMutex::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()) {
stats::StatsManager::addValue(kNumRpcSentToMetadFailed);
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";
LOG(ERROR) << "RpcResponse exception: " << t.exception().what().c_str();
pro.setValue(Status::Error("RPC failure in MetaClient: %s",
t.exception().what().c_str()));
}
return;
}
auto&& resp = t.value();
auto code = resp.get_code();
if (code == nebula::cpp2::ErrorCode::SUCCEEDED) {
// succeeded
pro.setValue(respGen(std::move(resp)));
return;
} else if (code == nebula::cpp2::ErrorCode::E_LEADER_CHANGED ||
code == nebula::cpp2::ErrorCode::E_MACHINE_NOT_FOUND) {
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;
}
} else if (code == nebula::cpp2::ErrorCode::E_CLIENT_SERVER_INCOMPATIBLE) {
pro.setValue(respGen(std::move(resp)));
return;
}
pro.setValue(this->handleResponse(resp));
}); // then
}); // via
}
std::vector<SpaceIdName> MetaClient::toSpaceIdName(const std::vector<cpp2::IdName>& tIdNames) {
memory::MemoryCheckOffGuard g;
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) {
memory::MemoryCheckOffGuard g;
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, probably timeout!");
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_HISTORY_CONFLICT:
return Status::Error("Schema exisited before!");
case nebula::cpp2::ErrorCode::E_SPACE_NOT_FOUND:
return Status::SpaceNotFound("Space not existed!");
case nebula::cpp2::ErrorCode::E_TAG_NOT_FOUND:
return Status::TagNotFound("Tag not existed!");
case nebula::cpp2::ErrorCode::E_EDGE_NOT_FOUND:
return Status::EdgeNotFound("Edge not existed!");
case nebula::cpp2::ErrorCode::E_INDEX_NOT_FOUND:
return Status::IndexNotFound("Index not existed!");
case nebula::cpp2::ErrorCode::E_STATS_NOT_FOUND:
return Status::Error(
"There is no any stats info to show, please execute "
"`submit job stats' firstly!");
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_MACHINE_NOT_FOUND:
return Status::Error("Machine 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_INVALID_PARM:
return Status::Error("Invalid param!");
case nebula::cpp2::ErrorCode::E_WRONGCLUSTER:
return Status::Error("Wrong cluster!");
case nebula::cpp2::ErrorCode::E_ZONE_NOT_ENOUGH:
return Status::Error("Host not enough!");
case nebula::cpp2::ErrorCode::E_ZONE_IS_EMPTY:
return Status::Error("Host not exist!");
case nebula::cpp2::ErrorCode::E_STORE_FAILURE:
return Status::Error("Store failure!");
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_CORRUPTED_BALANCE_PLAN:
return Status::Error("No corrupted balance 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_SNAPSHOT_RUNNING_JOBS:
return Status::Error("Snapshot failed encounter running jobs!");
case nebula::cpp2::ErrorCode::E_SNAPSHOT_NOT_FOUND:
return Status::Error("Snapshot not found!");
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_JOB_ALREADY_FINISH:
return Status::Error(
"Finished job or failed job can not be stopped, please start another job instead");
case nebula::cpp2::ErrorCode::E_JOB_NOT_STOPPABLE:
return Status::Error(
"The job type do not support stopping, either wait previous job done or restart the "
"cluster to start another job");
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_RUNNING_JOBS:
return Status::Error("Backup encounter running or queued jobs!");
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_LIST_CLUSTER_NO_AGENT_FAILURE:
return Status::Error("There is no agent!");
case nebula::cpp2::ErrorCode::E_INVALID_JOB:
return Status::Error("No valid job!");
case nebula::cpp2::ErrorCode::E_JOB_NOT_IN_SPACE:
return Status::Error("Job not existed in chosen space!");
case nebula::cpp2::ErrorCode::E_JOB_NEED_RECOVER:
return Status::Error("Need to recover or stop failed data balance job firstly!");
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!");
case nebula::cpp2::ErrorCode::E_SCHEMA_NAME_EXISTS:
return Status::Error("Schema with same name exists");
case nebula::cpp2::ErrorCode::E_RELATED_INDEX_EXISTS:
return Status::Error("Related index exists, please drop index first");
case nebula::cpp2::ErrorCode::E_RELATED_SPACE_EXISTS:
return Status::Error("There are still space on the host");
case nebula::cpp2::ErrorCode::E_RELATED_FULLTEXT_INDEX_EXISTS:
return Status::Error("Related fulltext index exists, please drop it first");
case nebula::cpp2::ErrorCode::E_HOST_CAN_NOT_BE_ADDED:
return Status::Error("Could not add a host, which is not a storage and not expired either");
case nebula::cpp2::ErrorCode::E_ACCESS_ES_FAILURE:
return Status::Error("Access elasticsearch failed");
default:
return Status::Error("Unknown error %d!", static_cast<int>(resp.get_code()));
}
}
PartsMap MetaClient::doGetPartsMap(const HostAddr& host, const LocalCache& localCache) {
memory::MemoryCheckOffGuard g;