forked from 4paradigm/OpenMLDB
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtablet_impl.cc
More file actions
6023 lines (5781 loc) · 261 KB
/
Copy pathtablet_impl.cc
File metadata and controls
6023 lines (5781 loc) · 261 KB
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 2021 4Paradigm
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 "tablet/tablet_impl.h"
#include <stdio.h>
#include <stdlib.h>
#include <filesystem>
#include <memory>
#include "vm/sql_compiler.h"
#ifdef DISALLOW_COPY_AND_ASSIGN
#undef DISALLOW_COPY_AND_ASSIGN
#endif
#include <snappy.h>
#include <algorithm>
#include <thread> // NOLINT
#include <unordered_map>
#include <utility>
#include <vector>
#include "absl/cleanup/cleanup.h"
#include "absl/strings/match.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "base/file_util.h"
#include "base/glog_wrapper.h"
#include "base/hash.h"
#include "base/memory_stat.h"
#include "base/proto_util.h"
#include "base/status.h"
#include "base/strings.h"
#include "base/sys_info.h"
#include "boost/bind.hpp"
#include "boost/container/deque.hpp"
#include "brpc/controller.h"
#include "butil/iobuf.h"
#include "codec/codec.h"
#include "codec/row_codec.h"
#include "codec/sql_rpc_row_codec.h"
#include "common/timer.h"
#include "config.h" // NOLINT
#include "gflags/gflags.h"
#include "glog/logging.h"
#ifdef TCMALLOC_ENABLE
#include "gperftools/malloc_extension.h"
#endif
#include "google/protobuf/io/zero_copy_stream_impl.h"
#include "google/protobuf/text_format.h"
#include "nameserver/task.h"
#include "schema/schema_adapter.h"
#include "storage/binlog.h"
#include "storage/disk_table_snapshot.h"
#include "storage/index_organized_table.h"
#include "storage/segment.h"
#include "storage/table.h"
#include "tablet/file_sender.h"
#include "tablet_impl.h"
using ::openmldb::base::ReturnCode;
using ::openmldb::storage::DiskTable;
using ::openmldb::storage::Table;
DECLARE_int32(gc_interval);
DECLARE_int32(gc_pool_size);
DECLARE_int32(disk_gc_interval);
DECLARE_int32(statdb_ttl);
DECLARE_uint32(scan_max_bytes_size);
DECLARE_uint32(scan_reserve_size);
DECLARE_uint32(max_memory_mb);
DECLARE_double(mem_release_rate);
DECLARE_int32(get_sys_mem_interval);
DECLARE_string(db_root_path);
DECLARE_string(ssd_root_path);
DECLARE_string(hdd_root_path);
DECLARE_bool(binlog_notify_on_put);
DECLARE_int32(task_pool_size);
DECLARE_int32(io_pool_size);
DECLARE_int32(make_snapshot_time);
DECLARE_int32(make_snapshot_check_interval);
DECLARE_uint32(make_snapshot_offline_interval);
DECLARE_bool(recycle_bin_enabled);
DECLARE_uint32(recycle_ttl);
DECLARE_string(recycle_bin_root_path);
DECLARE_string(recycle_bin_ssd_root_path);
DECLARE_string(recycle_bin_hdd_root_path);
DECLARE_int32(make_snapshot_threshold_offset);
DECLARE_uint32(get_table_diskused_interval);
DECLARE_uint32(get_memory_stat_interval);
DECLARE_uint32(task_check_interval);
DECLARE_uint32(load_index_max_wait_time);
DECLARE_bool(use_name);
DECLARE_bool(enable_distsql);
DECLARE_string(snapshot_compression);
DECLARE_string(file_compression);
DECLARE_int32(request_timeout_ms);
// cluster config
DECLARE_string(endpoint);
DECLARE_string(zk_cluster);
DECLARE_string(zk_root_path);
DECLARE_int32(zk_session_timeout);
DECLARE_int32(zk_keep_alive_check_interval);
DECLARE_string(zk_auth_schema);
DECLARE_string(zk_cert);
DECLARE_int32(binlog_sync_to_disk_interval);
DECLARE_int32(binlog_delete_interval);
DECLARE_uint32(absolute_ttl_max);
DECLARE_uint32(latest_ttl_max);
DECLARE_uint32(max_traverse_cnt);
DECLARE_uint32(snapshot_ttl_time);
DECLARE_uint32(snapshot_ttl_check_interval);
DECLARE_uint32(put_slow_log_threshold);
DECLARE_uint32(query_slow_log_threshold);
DECLARE_int32(snapshot_pool_size);
namespace openmldb {
namespace tablet {
static const uint32_t SEED = 0xe17a1465;
static constexpr const char DEPLOY_STATS[] = "deploy_stats";
TabletImpl::TabletImpl()
: tables_(),
mu_(),
gc_pool_(FLAGS_gc_pool_size),
replicators_(),
snapshots_(),
zk_client_(nullptr),
trivial_task_pool_(1),
task_pool_(FLAGS_task_pool_size),
io_pool_(FLAGS_io_pool_size),
snapshot_pool_(FLAGS_snapshot_pool_size),
mode_root_paths_(),
mode_recycle_root_paths_(),
follower_(false),
catalog_(new ::openmldb::catalog::TabletCatalog()),
engine_(),
zk_cluster_(),
zk_path_(),
endpoint_(),
sp_cache_(std::shared_ptr<SpCache>(new SpCache())),
notify_path_(),
globalvar_changed_notify_path_(),
startup_mode_(::openmldb::type::StartupMode::kStandalone),
user_access_manager_(GetSystemTableIterator()) {}
TabletImpl::~TabletImpl() {
task_pool_.Stop(true);
trivial_task_pool_.Stop(true);
gc_pool_.Stop(true);
io_pool_.Stop(true);
snapshot_pool_.Stop(true);
if (zk_client_) {
delete zk_client_;
}
}
bool TabletImpl::Init(const std::string& real_endpoint) {
return Init(FLAGS_zk_cluster, FLAGS_zk_root_path, FLAGS_endpoint, real_endpoint);
}
bool TabletImpl::Init(const std::string& zk_cluster, const std::string& zk_path, const std::string& endpoint,
const std::string& real_endpoint) {
zk_cluster_ = zk_cluster;
zk_path_ = zk_path;
endpoint_ = endpoint;
notify_path_ = zk_path + "/table/notify";
sp_root_path_ = zk_path + "/store_procedure/db_sp_data";
globalvar_changed_notify_path_ = zk_path + "/notify/global_variable";
global_variables_ = std::make_shared<std::map<std::string, std::string>>();
global_variables_->emplace("execute_mode", "online");
global_variables_->emplace("enable_trace", "false");
::openmldb::base::SplitString(FLAGS_db_root_path, ",", mode_root_paths_[::openmldb::common::kMemory]);
::openmldb::base::SplitString(FLAGS_ssd_root_path, ",", mode_root_paths_[::openmldb::common::kSSD]);
::openmldb::base::SplitString(FLAGS_hdd_root_path, ",", mode_root_paths_[::openmldb::common::kHDD]);
::openmldb::base::SplitString(FLAGS_recycle_bin_root_path, ",",
mode_recycle_root_paths_[::openmldb::common::kMemory]);
::openmldb::base::SplitString(FLAGS_recycle_bin_ssd_root_path, ",",
mode_recycle_root_paths_[::openmldb::common::kSSD]);
::openmldb::base::SplitString(FLAGS_recycle_bin_hdd_root_path, ",",
mode_recycle_root_paths_[::openmldb::common::kHDD]);
// if want /brpc_metrics, prefix should be g_server_info_prefix+<port>(when no server_info_name), means
// rpc_server_<port> if standalone, diy
deploy_collector_ = std::make_unique<::openmldb::statistics::DeploymentMetricCollector>(
"rpc_server_" + endpoint.substr(endpoint.find(":") + 1));
if (!zk_cluster.empty()) {
zk_client_ = new ZkClient(zk_cluster, real_endpoint, FLAGS_zk_session_timeout, endpoint, zk_path,
FLAGS_zk_auth_schema, FLAGS_zk_cert);
bool ok = zk_client_->Init();
if (!ok) {
PDLOG(ERROR, "fail to init zookeeper with cluster %s", zk_cluster.c_str());
return false;
}
startup_mode_ = ::openmldb::type::StartupMode::kCluster;
} else {
PDLOG(INFO, "start with standalone mode");
startup_mode_ = ::openmldb::type::StartupMode::kStandalone;
}
::hybridse::vm::EngineOptions options;
if (IsClusterMode()) {
options.SetClusterOptimized(FLAGS_enable_distsql);
} else {
options.SetClusterOptimized(false);
}
engine_ = std::make_unique<::hybridse::vm::Engine>(catalog_, options);
catalog_->SetLocalTablet(std::make_shared<::hybridse::vm::LocalTablet>(engine_.get(), sp_cache_));
std::set<std::string> snapshot_compression_set{"off", "zlib", "snappy"};
if (snapshot_compression_set.find(FLAGS_snapshot_compression) == snapshot_compression_set.end()) {
LOG(ERROR) << "wrong snapshot_compression: " << FLAGS_snapshot_compression;
return false;
}
std::set<std::string> file_compression_set{"off", "zlib", "lz4"};
if (file_compression_set.find(FLAGS_file_compression) == file_compression_set.end()) {
LOG(ERROR) << "wrong FLAGS_file_compression: " << FLAGS_file_compression;
return false;
}
if (FLAGS_make_snapshot_time < 0 || FLAGS_make_snapshot_time > 23) {
PDLOG(ERROR, "make_snapshot_time[%d] is illegal.", FLAGS_make_snapshot_time);
return false;
}
if (FLAGS_db_root_path != "") {
if (!CreateMultiDir(mode_root_paths_[::openmldb::common::kMemory])) {
PDLOG(ERROR, "fail to create db root path %s", FLAGS_db_root_path.c_str());
return false;
}
} else {
PDLOG(ERROR, "db_root_path is required");
return false;
}
if (FLAGS_ssd_root_path != "") {
if (!CreateMultiDir(mode_root_paths_[::openmldb::common::kSSD])) {
PDLOG(ERROR, "fail to create ssd root path %s", FLAGS_ssd_root_path.c_str());
return false;
}
} else {
PDLOG(WARNING, "ssd_root_path is not set");
}
if (FLAGS_hdd_root_path != "") {
if (!CreateMultiDir(mode_root_paths_[::openmldb::common::kHDD])) {
PDLOG(ERROR, "fail to create hdd root path %s", FLAGS_hdd_root_path.c_str());
return false;
}
} else {
PDLOG(WARNING, "hdd_root_path is not set");
}
if (FLAGS_recycle_bin_enabled) {
// FLAGS_db_root_path is guaranteed to be not empty
if (FLAGS_recycle_bin_root_path != "") {
if (!CreateMultiDir(mode_recycle_root_paths_[::openmldb::common::kMemory])) {
PDLOG(ERROR, "fail to create recycle bin root path %s", FLAGS_recycle_bin_root_path.c_str());
return false;
}
} else {
PDLOG(ERROR, "recycle_bin_root_path is not configured. Deleted table is not recycled");
}
if (FLAGS_ssd_root_path != "") {
if (FLAGS_recycle_bin_ssd_root_path != "") {
if (!CreateMultiDir(mode_recycle_root_paths_[::openmldb::common::kSSD])) {
PDLOG(ERROR, "fail to create recycle bin root path %s", FLAGS_recycle_bin_ssd_root_path.c_str());
return false;
}
} else {
PDLOG(ERROR, "recycle_bin_ssd_root_path is not configured. Deleted table is not recycled.");
}
}
if (FLAGS_hdd_root_path != "") {
if (FLAGS_recycle_bin_hdd_root_path != "") {
if (!CreateMultiDir(mode_recycle_root_paths_[::openmldb::common::kHDD])) {
PDLOG(WARNING, "fail to create recycle bin root path %s", FLAGS_recycle_bin_hdd_root_path.c_str());
return false;
}
} else {
PDLOG(ERROR, "recycle_bin_hdd_root_path is not configured. Deleted table is not recycled.");
}
}
}
std::map<std::string, std::string> real_endpoint_map = {{endpoint, real_endpoint}};
if (!catalog_->UpdateClient(real_endpoint_map)) {
PDLOG(ERROR, "update client failed");
return false;
}
if (IsClusterMode()) {
RecoverExternalFunction();
}
snapshot_pool_.DelayTask(FLAGS_make_snapshot_check_interval, boost::bind(&TabletImpl::SchedMakeSnapshot, this));
task_pool_.AddTask(boost::bind(&TabletImpl::GetDiskused, this));
if (FLAGS_max_memory_mb > 0) {
LOG(INFO) << "max memory is " << FLAGS_max_memory_mb << " MB";
task_pool_.AddTask(boost::bind(&TabletImpl::GetMemoryStat, this));
}
if (FLAGS_recycle_ttl != 0) {
task_pool_.DelayTask(FLAGS_recycle_ttl * 60 * 1000, boost::bind(&TabletImpl::SchedDelRecycle, this));
}
#ifdef TCMALLOC_ENABLE
MallocExtension* tcmalloc = MallocExtension::instance();
tcmalloc->SetMemoryReleaseRate(FLAGS_mem_release_rate);
#endif
#if defined(__linux__)
trivial_task_pool_.DelayTask(FLAGS_get_sys_mem_interval, boost::bind(&TabletImpl::UpdateMemoryUsage, this));
#endif
return true;
}
void TabletImpl::UpdateTTL(RpcController* ctrl, const ::openmldb::api::UpdateTTLRequest* request,
::openmldb::api::UpdateTTLResponse* response, Closure* done) {
brpc::ClosureGuard done_guard(done);
uint32_t tid = request->tid();
uint32_t pid = request->pid();
std::shared_ptr<Table> table = GetTable(tid, pid);
if (!table) {
PDLOG(WARNING, "table does not exist. tid %u, pid %u", tid, pid);
response->set_code(::openmldb::base::ReturnCode::kTableIsNotExist);
response->set_msg("table does not exist");
return;
}
::openmldb::common::TTLSt ttl(request->ttl());
uint64_t abs_ttl = ttl.abs_ttl();
uint64_t lat_ttl = ttl.lat_ttl();
const auto& index_name = request->index_name();
if (!index_name.empty()) {
auto index = table->GetIndex(request->index_name());
if (!index) {
PDLOG(WARNING, "idx name %s not found in table tid %u, pid %u", index_name.c_str(), tid, pid);
response->set_code(::openmldb::base::ReturnCode::kIdxNameNotFound);
response->set_msg("idx name not found");
return;
}
}
// different ttl type is ok
// no ttl value limit check in tablet, do it in nameserver before send request
::openmldb::storage::TTLSt ttl_st(ttl);
table->SetTTL(::openmldb::storage::UpdateTTLMeta(ttl_st, request->index_name()));
std::string db_root_path;
if (!ChooseDBRootPath(tid, pid, table->GetStorageMode(), db_root_path)) {
base::SetResponseStatus(base::ReturnCode::kFailToGetDbRootPath, "fail to get db root path", response);
PDLOG(WARNING, "fail to get table db root path for tid %u, pid %u", tid, pid);
return;
}
std::string db_path = GetDBPath(db_root_path, tid, pid);
if (!::openmldb::base::IsExists(db_path)) {
PDLOG(WARNING, "table db path doesn't exist. tid %u, pid %u", tid, pid);
base::SetResponseStatus(base::ReturnCode::kTableDbPathIsNotExist, "table db path does not exist", response);
return;
}
if (WriteTableMeta(db_path, table->GetTableMeta().get()) < 0) {
PDLOG(WARNING, "write table_meta failed. tid[%u] pid[%u]", tid, pid);
base::SetResponseStatus(base::ReturnCode::kWriteDataFailed, "write meta data failed", response);
return;
}
PDLOG(INFO, "update table tid %u pid %u ttl meta to abs_ttl %lu lat_ttl %lu index_name %s", tid, pid, abs_ttl,
lat_ttl, index_name.c_str());
response->set_code(::openmldb::base::ReturnCode::kOk);
response->set_msg("ok");
}
bool TabletImpl::RegisterZK() {
if (IsClusterMode()) {
if (zk_client_ == nullptr) {
return false;
}
if (FLAGS_use_name) {
if (!zk_client_->RegisterName()) {
return false;
}
}
if (!zk_client_->Register(true)) {
PDLOG(WARNING, "fail to register tablet with endpoint %s", endpoint_.c_str());
return false;
}
PDLOG(INFO, "tablet with endpoint %s register to zk cluster %s ok", endpoint_.c_str(), zk_cluster_.c_str());
if (zk_client_->IsExistNode(notify_path_) != 0) {
zk_client_->CreateNode(notify_path_, "1");
}
if (zk_client_->IsExistNode(globalvar_changed_notify_path_) != 0) {
zk_client_->CreateNode(globalvar_changed_notify_path_, "1");
}
if (!zk_client_->WatchItem(globalvar_changed_notify_path_,
[this]() { this->UpdateGlobalVarTable(); })) {
LOG(WARNING) << "add global var changed watcher failed";
return false;
}
if (!zk_client_->WatchItem(notify_path_, [this]() { this->RefreshTableInfo(); })) {
LOG(WARNING) << "add notify watcher failed";
return false;
}
trivial_task_pool_.DelayTask(FLAGS_zk_keep_alive_check_interval, boost::bind(&TabletImpl::CheckZkClient, this));
}
return true;
}
bool TabletImpl::CheckGetDone(::openmldb::api::GetType type, uint64_t ts, uint64_t target_ts) {
switch (type) {
case openmldb::api::GetType::kSubKeyEq:
if (ts == target_ts) {
return true;
}
break;
case openmldb::api::GetType::kSubKeyLe:
if (ts <= target_ts) {
return true;
}
break;
case openmldb::api::GetType::kSubKeyLt:
if (ts < target_ts) {
return true;
}
break;
case openmldb::api::GetType::kSubKeyGe:
if (ts >= target_ts) {
return true;
}
break;
case openmldb::api::GetType::kSubKeyGt:
if (ts > target_ts) {
return true;
}
}
return false;
}
void TabletImpl::UpdateMemoryUsage() {
base::SysInfo info;
if (auto status = base::GetSysMem(&info); status.OK()) {
if (info.mem_total > 0) {
system_memory_usage_rate_.store(info.mem_used * 100 / info.mem_total, std::memory_order_relaxed);
DEBUGLOG("system_memory_usage_rate is %u", system_memory_usage_rate_.load(std::memory_order_relaxed));
} else {
PDLOG(WARNING, "total memory is zero");
}
} else {
PDLOG(WARNING, "GetSysMem run failed. error message %s", status.GetMsg().c_str());
}
trivial_task_pool_.DelayTask(FLAGS_get_sys_mem_interval, boost::bind(&TabletImpl::UpdateMemoryUsage, this));
}
int32_t TabletImpl::GetIndex(const ::openmldb::api::GetRequest* request, const ::openmldb::api::TableMeta& meta,
const std::map<int32_t, std::shared_ptr<Schema>>& vers_schema, CombineIterator* it,
std::string* value, uint64_t* ts) {
if (it == nullptr || value == nullptr || ts == nullptr) {
LOG(WARNING) << "invalid args";
return -1;
}
uint64_t st = request->ts();
openmldb::api::GetType st_type = request->type();
uint64_t et = request->et();
const openmldb::api::GetType& et_type = request->et_type();
if (st_type == ::openmldb::api::kSubKeyEq && et_type == ::openmldb::api::kSubKeyEq && st != et) {
LOG(WARNING) << "invalid args for st " << st << " not equal to et " << et;
return -1;
}
::openmldb::api::GetType real_et_type = et_type;
::openmldb::storage::TTLType ttl_type = it->GetTTLType();
uint64_t expire_time = it->GetExpireTime();
if (ttl_type == ::openmldb::storage::TTLType::kAbsoluteTime ||
ttl_type == ::openmldb::storage::TTLType::kAbsOrLat) {
et = std::max(et, expire_time);
}
if (et < expire_time && et_type == ::openmldb::api::GetType::kSubKeyGt) {
real_et_type = ::openmldb::api::GetType::kSubKeyGe;
}
DLOG(INFO) << "expire time " << expire_time << ", after adjust: et " << et << " real_et_type " << real_et_type;
bool enable_project = false;
openmldb::codec::RowProject row_project(vers_schema, request->projection());
if (request->projection().size() > 0) {
bool ok = row_project.Init();
if (!ok) {
LOG(WARNING) << "invalid project list";
return -1;
}
enable_project = true;
}
// it's ok when st < et(after adjust), we should return 0 rows cuz no valid data for this range
// but we have set the code -1, don't change the return code, accept it.
if (st > 0 && st < et) {
DLOG(WARNING) << "invalid args for st " << st << " less than et " << et;
return -1;
}
DLOG(INFO) << "it valid " << it->Valid();
if (it->Valid()) {
*ts = it->GetTs();
DLOG(INFO) << "check " << *ts << " " << st << " " << et << " " << st_type << " " << real_et_type;
if (st_type == ::openmldb::api::GetType::kSubKeyEq && st > 0 && *ts != st) {
return 1;
}
bool jump_out = false;
if (st_type == ::openmldb::api::GetType::kSubKeyGe || st_type == ::openmldb::api::GetType::kSubKeyGt) {
::openmldb::base::Slice it_value = it->GetValue();
if (enable_project) {
int8_t* ptr = nullptr;
uint32_t size = 0;
openmldb::base::Slice data = it->GetValue();
const int8_t* row_ptr = reinterpret_cast<const int8_t*>(data.data());
bool ok = row_project.Project(row_ptr, data.size(), &ptr, &size);
if (!ok) {
LOG(WARNING) << "fail to make a projection";
return -4;
}
value->assign(reinterpret_cast<char*>(ptr), size);
delete[] ptr;
} else {
value->assign(it_value.data(), it_value.size());
}
return 0;
}
switch (real_et_type) {
case ::openmldb::api::GetType::kSubKeyEq:
if (*ts != et) {
jump_out = true;
}
break;
case ::openmldb::api::GetType::kSubKeyGt:
if (*ts <= et) {
jump_out = true;
}
break;
case ::openmldb::api::GetType::kSubKeyGe:
if (*ts < et) {
jump_out = true;
}
break;
default:
LOG(WARNING) << "invalid et type " << ::openmldb::api::GetType_Name(et_type).c_str();
return -2;
}
if (jump_out) {
return 1;
}
if (enable_project) {
int8_t* ptr = nullptr;
uint32_t size = 0;
openmldb::base::Slice data = it->GetValue();
const int8_t* row_ptr = reinterpret_cast<const int8_t*>(data.data());
bool ok = row_project.Project(row_ptr, data.size(), &ptr, &size);
if (!ok) {
LOG(WARNING) << "fail to make a projection";
return -4;
}
value->assign(reinterpret_cast<char*>(ptr), size);
delete[] ptr;
} else {
value->assign(it->GetValue().data(), it->GetValue().size());
}
return 0;
}
// not found
return 1;
}
void TabletImpl::Refresh(RpcController* controller, const ::openmldb::api::RefreshRequest* request,
::openmldb::api::GeneralResponse* response, Closure* done) {
brpc::ClosureGuard done_guard(done);
if (IsClusterMode()) {
if (RefreshSingleTable(request->tid())) {
PDLOG(INFO, "refresh success. tid %u", request->tid());
}
}
}
void TabletImpl::RecoverExternalFunction() {
std::string external_function_path = zk_path_ + "/data/function";
std::vector<std::string> functions;
if (zk_client_->IsExistNode(external_function_path) == 0) {
if (!zk_client_->GetChildren(external_function_path, functions)) {
LOG(WARNING) << "fail to get function list with path " << external_function_path;
return;
}
}
if (functions.empty()) {
LOG(INFO) << "no external functions to recover";
return;
}
for (const auto& name : functions) {
std::string value;
if (!zk_client_->GetNodeValue(external_function_path + "/" + name, value)) {
LOG(WARNING) << "fail to get function data. function: " << name;
continue;
}
::openmldb::common::ExternalFun fun;
if (!fun.ParseFromString(value)) {
LOG(WARNING) << "fail to parse external function. function: " << name << " value: " << value;
continue;
}
if (CreateFunctionInternal(fun).OK()) {
LOG(INFO) << "recover " << name << " function success";
}
}
}
void TabletImpl::Get(RpcController* controller, const ::openmldb::api::GetRequest* request,
::openmldb::api::GetResponse* response, Closure* done) {
brpc::ClosureGuard done_guard(done);
uint64_t start_time = ::baidu::common::timer::get_micros();
uint32_t tid = request->tid();
uint32_t pid_num = 1;
if (request->pid_group_size() > 0) {
pid_num = request->pid_group_size();
}
std::vector<QueryIt> query_its(pid_num);
std::shared_ptr<::openmldb::storage::TTLSt> ttl;
::openmldb::storage::TTLSt expired_value;
for (uint32_t idx = 0; idx < pid_num; idx++) {
uint32_t pid = 0;
if (request->pid_group_size() > 0) {
pid = request->pid_group(idx);
} else {
pid = request->pid();
}
auto table = GetTable(tid, pid);
if (auto status = CheckTable(tid, pid, false, table); !status.OK()) {
SetResponseStatus(status, response);
return;
}
std::string index_name;
if (request->has_idx_name() && request->idx_name().size() > 0) {
index_name = request->idx_name();
} else {
index_name = table->GetPkIndex()->GetName();
}
auto index_def = table->GetIndex(index_name);
if (!index_def || !index_def->IsReady()) {
PDLOG(WARNING, "idx name %s not found in table tid %u, pid %u", index_name.c_str(), tid, pid);
response->set_code(::openmldb::base::ReturnCode::kIdxNameNotFound);
response->set_msg("idx name not found");
return;
}
uint32_t index = index_def->GetId();
if (!ttl) {
ttl = index_def->GetTTL();
expired_value = *ttl;
expired_value.abs_ttl = table->GetExpireTime(expired_value);
}
GetIterator(table, request->key(), index, &query_its[idx].it, &query_its[idx].ticket);
if (!query_its[idx].it) {
response->set_code(::openmldb::base::ReturnCode::kTsNameNotFound);
response->set_msg("ts name not found");
return;
}
query_its[idx].table = table;
}
auto table_meta = query_its.begin()->table->GetTableMeta();
const std::map<int32_t, std::shared_ptr<Schema>> vers_schema = query_its.begin()->table->GetAllVersionSchema();
CombineIterator combine_it(std::move(query_its), request->ts(), request->type(), expired_value);
combine_it.SeekToFirst();
std::string* value = response->mutable_value();
uint64_t ts = 0;
int32_t code = GetIndex(request, *table_meta, vers_schema, &combine_it, value, &ts);
response->set_ts(ts);
response->set_code(code);
DLOG(WARNING) << "get key " << request->key() << " ts " << ts << " code " << code;
uint64_t end_time = ::baidu::common::timer::get_micros();
if (start_time + FLAGS_query_slow_log_threshold < end_time) {
std::string index_name;
if (request->has_idx_name() && request->idx_name().size() > 0) {
index_name = request->idx_name();
}
PDLOG(INFO, "slow log[get]. key %s index_name %s time %lu. tid %u, pid %u", request->key().c_str(),
index_name.c_str(), end_time - start_time, request->tid(), request->pid());
}
switch (code) {
case 1:
response->set_code(::openmldb::base::ReturnCode::kKeyNotFound);
response->set_msg("key not found");
return;
case 0:
return;
case -1:
response->set_msg("invalid args");
response->set_code(::openmldb::base::ReturnCode::kInvalidParameter);
return;
case -2:
response->set_code(::openmldb::base::ReturnCode::kInvalidParameter);
response->set_msg("st/et sub key type is invalid");
return;
default:
return;
}
}
void TabletImpl::Put(RpcController* controller, const ::openmldb::api::PutRequest* request,
::openmldb::api::PutResponse* response, Closure* done) {
brpc::ClosureGuard done_guard(done);
if (follower_.load(std::memory_order_relaxed)) {
response->set_code(::openmldb::base::ReturnCode::kIsFollowerCluster);
response->set_msg("is follower cluster");
return;
}
uint32_t tid = request->tid();
uint32_t pid = request->pid();
auto table = GetTable(tid, pid);
if (auto status = CheckTable(tid, pid, true, table); !status.OK()) {
SetResponseStatus(status, response);
return;
}
uint64_t start_time = ::baidu::common::timer::get_micros();
DLOG(INFO) << "request dimension size " << request->dimensions_size() << " request time " << request->time();
if (table->GetStorageMode() == ::openmldb::common::StorageMode::kMemory &&
memory_used_.load(std::memory_order_relaxed) > FLAGS_max_memory_mb) {
PDLOG(WARNING, "current memory %lu MB exceed max memory limit %lu MB. tid %u, pid %u",
memory_used_.load(std::memory_order_relaxed), FLAGS_max_memory_mb, tid, pid);
response->set_code(::openmldb::base::ReturnCode::kExceedMaxMemory);
response->set_msg("exceed max memory");
return;
}
::openmldb::api::LogEntry entry;
entry.set_pk(request->pk());
entry.set_ts(request->time());
if (table->GetCompressType() == openmldb::type::CompressType::kSnappy) {
const auto& raw_val = request->value();
std::string* val = entry.mutable_value();
::snappy::Compress(raw_val.c_str(), raw_val.length(), val);
} else {
entry.set_value(request->value());
}
if (request->dimensions_size() > 0) {
entry.mutable_dimensions()->CopyFrom(request->dimensions());
}
if (request->ts_dimensions_size() > 0) {
entry.mutable_ts_dimensions()->CopyFrom(request->ts_dimensions());
}
absl::Status st;
if (request->dimensions_size() > 0) {
int32_t ret_code = CheckDimessionPut(request, table->GetIdxCnt());
if (ret_code != 0) {
response->set_code(::openmldb::base::ReturnCode::kInvalidDimensionParameter);
response->set_msg("invalid dimension parameter");
return;
}
if (request->check_exists()) {
// table should be iot
auto iot = std::dynamic_pointer_cast<storage::IndexOrganizedTable>(table);
if (!iot) {
response->set_code(::openmldb::base::ReturnCode::kTableMetaIsIllegal);
response->set_msg("table type is not iot");
return;
}
DLOG(INFO) << "check data exists in tid " << tid << " pid " << pid << " with key "
<< entry.dimensions(0).key() << " ts " << entry.ts();
// ts is ts value when check exists
st = iot->CheckDataExists(entry.ts(), entry.dimensions());
} else {
DLOG(INFO) << "put data to tid " << tid << " pid " << pid << " with key " << request->dimensions(0).key();
// 1. normal put: ok, invalid data
// 2. put if absent: ok, exists but ignore, invalid data
st = table->Put(entry.ts(), entry.value(), entry.dimensions(), request->put_if_absent());
}
}
// when check exists, we won't do log
if (request->check_exists()) {
DLOG_ASSERT(request->check_exists()) << "check_exists should be true";
DLOG_ASSERT(!request->put_if_absent()) << "put_if_absent should be false";
DLOG(INFO) << "result " << st.ToString();
// return ok if exists
if (absl::IsAlreadyExists(st)) {
response->set_code(base::ReturnCode::kOk);
response->set_msg("exists");
} else if (absl::IsNotFound(st)) {
response->set_code(base::ReturnCode::kKeyNotFound);
response->set_msg(st.ToString());
} else {
// other errors
response->set_code(base::ReturnCode::kError);
response->set_msg(st.ToString());
}
return;
}
if (!st.ok()) {
if (request->put_if_absent() && absl::IsAlreadyExists(st)) {
// not a failure but shounld't write log entry
response->set_code(::openmldb::base::ReturnCode::kOk);
response->set_msg("exists but ignore");
return;
}
LOG(WARNING) << st.ToString();
response->set_code(::openmldb::base::ReturnCode::kPutFailed);
response->set_msg(st.ToString());
return;
}
response->set_code(::openmldb::base::ReturnCode::kOk);
std::shared_ptr<LogReplicator> replicator;
bool ok = false;
do {
replicator = GetReplicator(request->tid(), request->pid());
if (!replicator) {
PDLOG(WARNING, "fail to find table tid %u pid %u leader's log replicator", tid, pid);
break;
}
entry.set_term(replicator->GetLeaderTerm());
// Aggregator update assumes that binlog_offset is strictly increasing
// so the update should be protected within the replicator lock
// in case there will be other Put jump into the middle
auto update_aggr = [this, &request, &ok, &entry]() {
ok =
UpdateAggrs(request->tid(), request->pid(), request->value(), request->dimensions(), entry.log_index());
};
UpdateAggrClosure closure(update_aggr);
replicator->AppendEntry(entry, &closure);
if (!ok) {
response->set_code(::openmldb::base::ReturnCode::kError);
response->set_msg("update aggr failed");
return;
}
} while (false);
uint64_t end_time = ::baidu::common::timer::get_micros();
if (start_time + FLAGS_put_slow_log_threshold < end_time) {
std::string key;
if (request->dimensions_size() > 0) {
for (int idx = 0; idx < request->dimensions_size(); idx++) {
if (!key.empty()) {
key.append(", ");
}
key.append(std::to_string(request->dimensions(idx).idx()));
key.append(":");
key.append(request->dimensions(idx).key());
}
} else {
key = request->pk();
}
PDLOG(INFO, "slow log[put]. key %s time %lu. tid %u, pid %u", key.c_str(), end_time - start_time, tid, pid);
}
if (replicator) {
if (FLAGS_binlog_notify_on_put) {
replicator->Notify();
}
}
// update global var in standalone mode
if (!IsClusterMode() && table->GetDB() == openmldb::nameserver::INFORMATION_SCHEMA_DB &&
table->GetName() == openmldb::nameserver::GLOBAL_VARIABLES) {
UpdateGlobalVarTable();
}
}
int32_t TabletImpl::ScanIndex(const ::openmldb::api::ScanRequest* request, const ::openmldb::api::TableMeta& meta,
const std::map<int32_t, std::shared_ptr<Schema>>& vers_schema, bool use_attachment,
CombineIterator* combine_it, butil::IOBuf* io_buf, uint32_t* count, bool* is_finish) {
uint32_t limit = request->limit();
if (combine_it == nullptr || io_buf == nullptr || count == nullptr || is_finish == nullptr) {
PDLOG(WARNING, "invalid args");
return -1;
}
uint64_t st = request->st();
uint64_t et = request->et();
::openmldb::storage::TTLType ttl_type = combine_it->GetTTLType();
uint64_t expire_time = combine_it->GetExpireTime();
if (ttl_type == ::openmldb::storage::TTLType::kAbsoluteTime ||
ttl_type == ::openmldb::storage::TTLType::kAbsOrLat) {
et = std::max(et, expire_time);
}
if (st > 0 && st < et) {
PDLOG(WARNING, "invalid args for st %lu less than et %lu or expire time %lu", st, et, expire_time);
return -1;
}
bool enable_project = false;
::openmldb::codec::RowProject row_project(vers_schema, request->projection());
if (request->projection().size() > 0) {
if (!row_project.Init()) {
PDLOG(WARNING, "invalid project list");
return -1;
}
enable_project = true;
}
bool remove_duplicated_record = request->enable_remove_duplicated_record();
uint64_t last_time = 0;
uint32_t total_block_size = 0;
uint32_t record_count = 0;
uint32_t skip_record_num = request->skip_record_num();
combine_it->SeekToFirst();
while (combine_it->Valid()) {
if (limit > 0 && record_count >= limit) {
*is_finish = false;
break;
}
if (remove_duplicated_record && record_count > 0 && last_time == combine_it->GetTs()) {
combine_it->Next();
continue;
}
if (combine_it->GetTs() == st && skip_record_num > 0) {
skip_record_num--;
combine_it->Next();
continue;
}
uint64_t ts = combine_it->GetTs();
if (ts <= et) {
break;
}
last_time = ts;
if (enable_project) {
int8_t* ptr = nullptr;
uint32_t size = 0;
openmldb::base::Slice data = combine_it->GetValue();
const int8_t* row_ptr = reinterpret_cast<const int8_t*>(data.data());
bool ok = row_project.Project(row_ptr, data.size(), &ptr, &size);
if (!ok) {
PDLOG(WARNING, "fail to make a projection");
return -4;
}
if (use_attachment) {
io_buf->append(reinterpret_cast<void*>(ptr), size);
} else {
::openmldb::codec::Encode(ts, reinterpret_cast<char*>(ptr), size, io_buf);
}
total_block_size += size;
} else {
openmldb::base::Slice data = combine_it->GetValue();
if (use_attachment) {
io_buf->append(reinterpret_cast<const void*>(data.data()), data.size());
} else {
::openmldb::codec::Encode(ts, data.data(), data.size(), io_buf);
}
total_block_size += data.size();
}
record_count++;
if (FLAGS_scan_max_bytes_size > 0 && total_block_size > FLAGS_scan_max_bytes_size) {
*is_finish = false;
break;
}
combine_it->Next();
}
*count = record_count;
return 0;
}
int32_t TabletImpl::CountIndex(uint64_t expire_time, uint64_t expire_cnt, ::openmldb::storage::TTLType ttl_type,
::openmldb::storage::TableIterator* it, const ::openmldb::api::CountRequest* request,
uint32_t* count) {
uint64_t st = request->st();
const openmldb::api::GetType& st_type = request->st_type();
uint64_t et = request->et();
const openmldb::api::GetType& et_type = request->et_type();
bool remove_duplicated_record =
request->has_enable_remove_duplicated_record() && request->enable_remove_duplicated_record();
if (it == nullptr || count == nullptr) {
PDLOG(WARNING, "invalid args");
return -1;
}
openmldb::api::GetType real_st_type = st_type;
openmldb::api::GetType real_et_type = et_type;
if (et < expire_time && et_type == ::openmldb::api::GetType::kSubKeyGt) {
real_et_type = ::openmldb::api::GetType::kSubKeyGe;
}
if (ttl_type == ::openmldb::storage::TTLType::kAbsoluteTime ||
ttl_type == ::openmldb::storage::TTLType::kAbsOrLat) {
et = std::max(et, expire_time);
}
if (st_type == ::openmldb::api::GetType::kSubKeyEq) {
real_st_type = ::openmldb::api::GetType::kSubKeyLe;
}
if (st_type != ::openmldb::api::GetType::kSubKeyEq && st_type != ::openmldb::api::GetType::kSubKeyLe &&
st_type != ::openmldb::api::GetType::kSubKeyLt) {
PDLOG(WARNING, "invalid st type %s", ::openmldb::api::GetType_Name(st_type).c_str());
return -2;
}
uint32_t cnt = 0;
if (st > 0) {
if (st < et) {
return -1;
}