pegasus_server_impl.cpp 95.3 KB
Newer Older
Q
qinzuoyan 已提交
1 2 3 4 5
// Copyright (c) 2017, Xiaomi, Inc.  All rights reserved.
// This source code is licensed under the Apache License Version 2.0, which
// can be found in the LICENSE file in the root directory of this source tree.

#include "pegasus_server_impl.h"
6 7 8

#include <algorithm>
#include <boost/lexical_cast.hpp>
9
#include <rocksdb/convenience.h>
10 11
#include <rocksdb/table.h>
#include <rocksdb/utilities/checkpoint.h>
12
#include <rocksdb/filter_policy.h>
Q
qinzuoyan 已提交
13
#include <dsn/utility/utils.h>
14
#include <dsn/utility/filesystem.h>
15 16 17 18 19
#include <dsn/dist/fmt_logging.h>

#include "base/pegasus_key_schema.h"
#include "base/pegasus_value_schema.h"
#include "base/pegasus_utils.h"
20
#include "pegasus_event_listener.h"
21
#include "pegasus_server_write.h"
Q
qinzuoyan 已提交
22 23 24 25 26 27 28 29 30 31

namespace pegasus {
namespace server {

// Although we have removed the INCR operator, but we need reserve the code for compatibility
// reason,
// because there may be some mutation log entries which include the code. Even if these entries need
// not to be applied to rocksdb, they may be deserialized.
DEFINE_TASK_CODE_RPC(RPC_RRDB_RRDB_INCR, TASK_PRIORITY_COMMON, ::dsn::THREAD_POOL_DEFAULT)

32 33 34 35
DEFINE_TASK_CODE(LPC_PEGASUS_SERVER_DELAY, TASK_PRIORITY_COMMON, ::dsn::THREAD_POOL_DEFAULT)

DEFINE_TASK_CODE(LPC_UPDATING_ROCKSDB_SSTSIZE, TASK_PRIORITY_COMMON, THREAD_POOL_REPLICATION_LONG)

Q
qinzuoyan 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48
static std::string chkpt_get_dir_name(int64_t decree)
{
    char buffer[256];
    sprintf(buffer, "checkpoint.%" PRId64 "", decree);
    return std::string(buffer);
}

static bool chkpt_init_from_dir(const char *name, int64_t &decree)
{
    return 1 == sscanf(name, "checkpoint.%" PRId64 "", &decree) &&
           std::string(name) == chkpt_get_dir_name(decree);
}

49 50
pegasus_server_impl::pegasus_server_impl(dsn::replication::replica *r)
    : dsn::apps::rrdb_service(r),
51
      _usage_scenario(ROCKSDB_ENV_USAGE_SCENARIO_NORMAL),
Q
qinzuoyan 已提交
52 53 54
      _db(nullptr),
      _is_open(false),
      _value_schema_version(0),
C
cailiuyang 已提交
55
      _last_durable_decree(0),
56 57
      _is_checkpointing(false),
      _manual_compact_svc(this)
Q
qinzuoyan 已提交
58
{
59 60
    _primary_address = dsn::rpc_address(dsn_primary_address()).to_string();
    _gpid = get_gpid();
Q
qinzuoyan 已提交
61 62 63 64
    _verbose_log = dsn_config_get_value_bool("pegasus.server",
                                             "rocksdb_verbose_log",
                                             false,
                                             "print verbose log for debugging, default is false");
65 66 67 68 69 70 71 72 73 74
    _abnormal_get_time_threshold_ns = dsn_config_get_value_uint64(
        "pegasus.server",
        "rocksdb_abnormal_get_time_threshold_ns",
        0,
        "rocksdb_abnormal_get_time_threshold_ns, default is 0, means no check");
    _abnormal_get_size_threshold = dsn_config_get_value_uint64(
        "pegasus.server",
        "rocksdb_abnormal_get_size_threshold",
        0,
        "rocksdb_abnormal_get_size_threshold, default is 0, means no check");
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
    _abnormal_multi_get_time_threshold_ns = dsn_config_get_value_uint64(
        "pegasus.server",
        "rocksdb_abnormal_multi_get_time_threshold_ns",
        0,
        "rocksdb_abnormal_multi_get_time_threshold_ns, default is 0, means no check");
    _abnormal_multi_get_size_threshold = dsn_config_get_value_uint64(
        "pegasus.server",
        "rocksdb_abnormal_multi_get_size_threshold",
        0,
        "rocksdb_abnormal_multi_get_size_threshold, default is 0, means no check");
    _abnormal_multi_get_iterate_count_threshold = dsn_config_get_value_uint64(
        "pegasus.server",
        "rocksdb_abnormal_multi_get_iterate_count_threshold",
        0,
        "rocksdb_abnormal_multi_get_iterate_count_threshold, default is 0, means no check");
Q
qinzuoyan 已提交
90 91 92

    // init db options

93
    // read rocksdb::Options configurations
Q
qinzuoyan 已提交
94 95 96 97
    // rocksdb default: 4MB
    _db_opts.write_buffer_size =
        (size_t)dsn_config_get_value_uint64("pegasus.server",
                                            "rocksdb_write_buffer_size",
98 99
                                            64 * 1024 * 1024,
                                            "rocksdb options.write_buffer_size, default 64MB");
Q
qinzuoyan 已提交
100 101 102

    // rocksdb default: 2
    _db_opts.max_write_buffer_number =
103 104 105 106
        (int)dsn_config_get_value_int64("pegasus.server",
                                        "rocksdb_max_write_buffer_number",
                                        6,
                                        "rocksdb options.max_write_buffer_number, default 6");
107

108 109 110
    // rocksdb default: -1
    // flush threads are shared among all rocksdb instances in one process.
    _db_opts.max_background_flushes =
111
        (int)dsn_config_get_value_int64("pegasus.server",
112
                                        "rocksdb_max_background_flushes",
113
                                        4,
114 115 116 117 118 119 120 121 122
                                        "rocksdb options.max_background_flushes, default 4");

    // rocksdb default: -1
    // compaction threads are shared among all rocksdb instances in one process.
    _db_opts.max_background_compactions =
        (int)dsn_config_get_value_int64("pegasus.server",
                                        "rocksdb_max_background_compactions",
                                        12,
                                        "rocksdb options.max_background_compactions, default 12");
Q
qinzuoyan 已提交
123 124

    // rocksdb default: 7
125
    _db_opts.num_levels = (int)dsn_config_get_value_int64(
Q
qinzuoyan 已提交
126 127 128 129 130 131
        "pegasus.server", "rocksdb_num_levels", 6, "rocksdb options.num_levels, default 6");

    // rocksdb default: 2MB
    _db_opts.target_file_size_base =
        dsn_config_get_value_uint64("pegasus.server",
                                    "rocksdb_target_file_size_base",
132 133
                                    64 * 1024 * 1024,
                                    "rocksdb options.target_file_size_base, default 64MB");
Q
qinzuoyan 已提交
134

135 136 137 138 139 140 141
    // rocksdb default: 1
    _db_opts.target_file_size_multiplier =
        (int)dsn_config_get_value_int64("pegasus.server",
                                        "rocksdb_target_file_size_multiplier",
                                        1,
                                        "rocksdb options.target_file_size_multiplier, default 1");

Q
qinzuoyan 已提交
142 143 144 145
    // rocksdb default: 10MB
    _db_opts.max_bytes_for_level_base =
        dsn_config_get_value_uint64("pegasus.server",
                                    "rocksdb_max_bytes_for_level_base",
146 147
                                    10 * 64 * 1024 * 1024,
                                    "rocksdb options.max_bytes_for_level_base, default 640MB");
Q
qinzuoyan 已提交
148

149 150 151 152 153 154
    // rocksdb default: 10
    _db_opts.max_bytes_for_level_multiplier = dsn_config_get_value_double(
        "pegasus.server",
        "rocksdb_max_bytes_for_level_multiplier",
        10,
        "rocksdb options.rocksdb_max_bytes_for_level_multiplier, default 10");
Q
qinzuoyan 已提交
155

156 157 158
    // we need set max_compaction_bytes definitely because set_usage_scenario() depends on it.
    _db_opts.max_compaction_bytes = _db_opts.target_file_size_base * 25;

Q
qinzuoyan 已提交
159 160
    // rocksdb default: 4
    _db_opts.level0_file_num_compaction_trigger =
161 162 163 164
        (int)dsn_config_get_value_int64("pegasus.server",
                                        "rocksdb_level0_file_num_compaction_trigger",
                                        4,
                                        "rocksdb options.level0_file_num_compaction_trigger, 4");
Q
qinzuoyan 已提交
165 166

    // rocksdb default: 20
167
    _db_opts.level0_slowdown_writes_trigger = (int)dsn_config_get_value_int64(
Q
qinzuoyan 已提交
168 169
        "pegasus.server",
        "rocksdb_level0_slowdown_writes_trigger",
170 171
        30,
        "rocksdb options.level0_slowdown_writes_trigger, default 30");
Q
qinzuoyan 已提交
172 173 174

    // rocksdb default: 24
    _db_opts.level0_stop_writes_trigger =
175 176 177 178
        (int)dsn_config_get_value_int64("pegasus.server",
                                        "rocksdb_level0_stop_writes_trigger",
                                        60,
                                        "rocksdb options.level0_stop_writes_trigger, default 60");
Q
qinzuoyan 已提交
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
    // rocksdb default: snappy
    std::string compression_str = dsn_config_get_value_string(
        "pegasus.server",
        "rocksdb_compression_type",
        "snappy",
        "rocksdb options.compression, default snappy. Supported: none, snappy.");
    if (compression_str == "none") {
        _db_opts.compression = rocksdb::kNoCompression;
    } else if (compression_str == "snappy") {
        _db_opts.compression = rocksdb::kSnappyCompression;
    } else {
        dassert("unsupported compression type: %s", compression_str.c_str());
    }

    if (_db_opts.compression != rocksdb::kNoCompression) {
        // only compress levels >= 2
        // refer to ColumnFamilyOptions::OptimizeLevelStyleCompaction()
        _db_opts.compression_per_level.resize(_db_opts.num_levels);
        for (int i = 0; i < _db_opts.num_levels; ++i) {
            if (i < 2) {
                _db_opts.compression_per_level[i] = rocksdb::kNoCompression;
            } else {
                _db_opts.compression_per_level[i] = _db_opts.compression;
            }
        }
    }

207 208 209 210 211 212 213 214 215
    // read rocksdb::BlockBasedTableOptions configurations
    rocksdb::BlockBasedTableOptions tbl_opts;
    // disable table block cache, default: false
    if (dsn_config_get_value_bool("pegasus.server",
                                  "rocksdb_disable_table_block_cache",
                                  false,
                                  "rocksdb tbl_opts.no_block_cache, default false")) {
        tbl_opts.no_block_cache = true;
        tbl_opts.block_restart_interval = 4;
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
    } else {
        // block cache capacity, default 10G
        static uint64_t capacity = dsn_config_get_value_uint64(
            "pegasus.server",
            "rocksdb_block_cache_capacity",
            10 * 1024 * 1024 * 1024ULL,
            "block cache capacity for one pegasus server, shared by all rocksdb instances");

        // block cache num shard bits, default -1(auto)
        static int num_shard_bits = (int)dsn_config_get_value_int64(
            "pegasus.server",
            "rocksdb_block_cache_num_shard_bits",
            -1,
            "block cache will be sharded into 2^num_shard_bits shards");

        // init block cache
        static std::shared_ptr<rocksdb::Cache> cache =
            rocksdb::NewLRUCache(capacity, num_shard_bits);
        tbl_opts.block_cache = cache;
235 236 237 238 239 240 241 242 243 244 245 246
    }

    // disable bloom filter, default: false
    if (!dsn_config_get_value_bool("pegasus.server",
                                   "rocksdb_disable_bloom_filter",
                                   false,
                                   "rocksdb tbl_opts.filter_policy, default nullptr")) {
        tbl_opts.filter_policy.reset(rocksdb::NewBloomFilterPolicy(10, false));
    }

    _db_opts.table_factory.reset(NewBlockBasedTableFactory(tbl_opts));

247 248
    _db_opts.listeners.emplace_back(new pegasus_event_listener());

Q
qinzuoyan 已提交
249 250 251 252 253 254 255 256 257
    // disable write ahead logging as replication handles logging instead now
    _wt_opts.disableWAL = true;

    // get the checkpoint reserve options.
    _checkpoint_reserve_min_count = (uint32_t)dsn_config_get_value_uint64(
        "pegasus.server", "checkpoint_reserve_min_count", 3, "checkpoint_reserve_min_count");
    _checkpoint_reserve_time_seconds =
        (uint32_t)dsn_config_get_value_uint64("pegasus.server",
                                              "checkpoint_reserve_time_seconds",
258 259
                                              0,
                                              "checkpoint_reserve_time_seconds, 0 means no check");
Q
qinzuoyan 已提交
260 261 262 263 264 265 266 267

    // get the _updating_sstsize_inteval_seconds.
    _updating_rocksdb_sstsize_interval_seconds =
        (uint32_t)dsn_config_get_value_uint64("pegasus.server",
                                              "updating_rocksdb_sstsize_interval_seconds",
                                              600,
                                              "updating_rocksdb_sstsize_interval_seconds");

268 269 270 271
    // TODO: move the qps/latency counters and it's statistics to replication_app_base layer
    char str_gpid[128], buf[256];
    snprintf(str_gpid, 128, "%d.%d", _gpid.get_app_id(), _gpid.get_partition_index());

Q
qinzuoyan 已提交
272
    // register the perf counters
273
    snprintf(buf, 255, "get_qps@%s", str_gpid);
274 275
    _pfc_get_qps.init_app_counter(
        "app.pegasus", buf, COUNTER_TYPE_RATE, "statistic the qps of GET request");
Q
qinzuoyan 已提交
276

277
    snprintf(buf, 255, "multi_get_qps@%s", str_gpid);
278
    _pfc_multi_get_qps.init_app_counter(
Q
qinzuoyan 已提交
279 280
        "app.pegasus", buf, COUNTER_TYPE_RATE, "statistic the qps of MULTI_GET request");

281
    snprintf(buf, 255, "scan_qps@%s", str_gpid);
282 283
    _pfc_scan_qps.init_app_counter(
        "app.pegasus", buf, COUNTER_TYPE_RATE, "statistic the qps of SCAN request");
Q
qinzuoyan 已提交
284

285
    snprintf(buf, 255, "get_latency@%s", str_gpid);
286 287 288 289
    _pfc_get_latency.init_app_counter("app.pegasus",
                                      buf,
                                      COUNTER_TYPE_NUMBER_PERCENTILES,
                                      "statistic the latency of GET request");
Q
qinzuoyan 已提交
290

291
    snprintf(buf, 255, "multi_get_latency@%s", str_gpid);
292 293 294 295
    _pfc_multi_get_latency.init_app_counter("app.pegasus",
                                            buf,
                                            COUNTER_TYPE_NUMBER_PERCENTILES,
                                            "statistic the latency of MULTI_GET request");
Q
qinzuoyan 已提交
296

297
    snprintf(buf, 255, "scan_latency@%s", str_gpid);
298 299 300 301
    _pfc_scan_latency.init_app_counter("app.pegasus",
                                       buf,
                                       COUNTER_TYPE_NUMBER_PERCENTILES,
                                       "statistic the latency of SCAN request");
Q
qinzuoyan 已提交
302

303
    snprintf(buf, 255, "recent.expire.count@%s", str_gpid);
304 305 306 307
    _pfc_recent_expire_count.init_app_counter("app.pegasus",
                                              buf,
                                              COUNTER_TYPE_VOLATILE_NUMBER,
                                              "statistic the recent expired value read count");
308

309
    snprintf(buf, 255, "recent.filter.count@%s", str_gpid);
310 311 312 313
    _pfc_recent_filter_count.init_app_counter("app.pegasus",
                                              buf,
                                              COUNTER_TYPE_VOLATILE_NUMBER,
                                              "statistic the recent filtered value read count");
314

315 316 317 318 319 320
    snprintf(buf, 255, "recent.abnormal.count@%s", str_gpid);
    _pfc_recent_abnormal_count.init_app_counter("app.pegasus",
                                                buf,
                                                COUNTER_TYPE_VOLATILE_NUMBER,
                                                "statistic the recent abnormal read count");

321
    snprintf(buf, 255, "disk.storage.sst.count@%s", str_gpid);
322
    _pfc_sst_count.init_app_counter(
Q
qinzuoyan 已提交
323
        "app.pegasus", buf, COUNTER_TYPE_NUMBER, "statistic the count of sstable files");
324

325
    snprintf(buf, 255, "disk.storage.sst(MB)@%s", str_gpid);
326
    _pfc_sst_size.init_app_counter(
Q
qinzuoyan 已提交
327
        "app.pegasus", buf, COUNTER_TYPE_NUMBER, "statistic the size of sstable files");
328

Q
qinzuoyan 已提交
329 330 331 332 333 334
    updating_rocksdb_sstsize();
}

void pegasus_server_impl::parse_checkpoints()
{
    std::vector<std::string> dirs;
335
    ::dsn::utils::filesystem::get_subdirectories(data_dir(), dirs, false);
Q
qinzuoyan 已提交
336 337 338 339 340 341

    ::dsn::utils::auto_lock<::dsn::utils::ex_lock_nr> l(_checkpoints_lock);

    _checkpoints.clear();
    for (auto &d : dirs) {
        int64_t ci;
342
        std::string d1 = d.substr(data_dir().size() + 1);
Q
qinzuoyan 已提交
343 344 345
        if (chkpt_init_from_dir(d1.c_str(), ci)) {
            _checkpoints.push_back(ci);
        } else if (d1.find("checkpoint") != std::string::npos) {
346
            ddebug("%s: invalid checkpoint directory %s, remove it", replica_name(), d.c_str());
Q
qinzuoyan 已提交
347 348
            ::dsn::utils::filesystem::remove_path(d);
            if (!::dsn::utils::filesystem::remove_path(d)) {
349 350
                derror(
                    "%s: remove invalid checkpoint directory %s failed", replica_name(), d.c_str());
Q
qinzuoyan 已提交
351 352 353 354 355 356 357 358 359 360 361 362
            }
        }
    }

    if (!_checkpoints.empty()) {
        std::sort(_checkpoints.begin(), _checkpoints.end());
        set_last_durable_decree(_checkpoints.back());
    } else {
        set_last_durable_decree(0);
    }
}

363 364
pegasus_server_impl::~pegasus_server_impl() = default;

Q
qinzuoyan 已提交
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
void pegasus_server_impl::gc_checkpoints()
{
    std::deque<int64_t> temp_list;
    {
        ::dsn::utils::auto_lock<::dsn::utils::ex_lock_nr> l(_checkpoints_lock);
        if (_checkpoints.size() <= _checkpoint_reserve_min_count)
            return;
        temp_list = _checkpoints;
    }

    // find the max checkpoint which can be deleted
    int64_t max_del_d = -1;
    uint64_t current_time = dsn_now_ms() / 1000;
    for (int i = 0; i < temp_list.size(); ++i) {
        if (i + _checkpoint_reserve_min_count >= temp_list.size())
            break;
        int64_t d = temp_list[i];
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
        if (_checkpoint_reserve_time_seconds > 0) {
            // we check last write time of "CURRENT" instead of directory, because the directory's
            // last write time may be updated by previous incompleted garbage collection.
            auto cpt_dir =
                ::dsn::utils::filesystem::path_combine(data_dir(), chkpt_get_dir_name(d));
            auto current_file = ::dsn::utils::filesystem::path_combine(cpt_dir, "CURRENT");
            if (!::dsn::utils::filesystem::file_exists(current_file)) {
                max_del_d = d;
                continue;
            }
            time_t tm;
            if (!dsn::utils::filesystem::last_write_time(current_file, tm)) {
                dwarn("get last write time of file %s failed", current_file.c_str());
                break;
            }
            uint64_t last_write_time = (uint64_t)tm;
            if (last_write_time + _checkpoint_reserve_time_seconds >= current_time) {
                // not expired
                break;
            }
Q
qinzuoyan 已提交
402 403 404 405 406 407
        }
        max_del_d = d;
    }
    if (max_del_d == -1) {
        // no checkpoint to delete
        ddebug("%s: no checkpoint to garbage collection, checkpoints_count = %d",
408
               replica_name(),
Q
qinzuoyan 已提交
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
               (int)temp_list.size());
        return;
    }
    std::list<int64_t> to_delete_list;
    int64_t min_d = 0;
    int64_t max_d = 0;
    int checkpoints_count = 0;
    {
        ::dsn::utils::auto_lock<::dsn::utils::ex_lock_nr> l(_checkpoints_lock);
        int delete_max_index = -1;
        for (int i = 0; i < _checkpoints.size(); ++i) {
            int64_t del_d = _checkpoints[i];
            if (i + _checkpoint_reserve_min_count >= _checkpoints.size() || del_d > max_del_d)
                break;
            to_delete_list.push_back(del_d);
            delete_max_index = i;
        }
426
        if (delete_max_index >= 0) {
Q
qinzuoyan 已提交
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
            _checkpoints.erase(_checkpoints.begin(), _checkpoints.begin() + delete_max_index + 1);
        }

        if (!_checkpoints.empty()) {
            min_d = _checkpoints.front();
            max_d = _checkpoints.back();
            checkpoints_count = _checkpoints.size();
        } else {
            min_d = 0;
            max_d = 0;
            checkpoints_count = 0;
        }
    }

    // do delete
    std::list<int64_t> put_back_list;
    for (auto &del_d : to_delete_list) {
444 445
        auto cpt_dir =
            ::dsn::utils::filesystem::path_combine(data_dir(), chkpt_get_dir_name(del_d));
Q
qinzuoyan 已提交
446 447 448
        if (::dsn::utils::filesystem::directory_exists(cpt_dir)) {
            if (::dsn::utils::filesystem::remove_path(cpt_dir)) {
                ddebug("%s: checkpoint directory %s removed by garbage collection",
449
                       replica_name(),
Q
qinzuoyan 已提交
450 451 452
                       cpt_dir.c_str());
            } else {
                derror("%s: checkpoint directory %s remove failed by garbage collection",
453
                       replica_name(),
Q
qinzuoyan 已提交
454 455 456 457 458
                       cpt_dir.c_str());
                put_back_list.push_back(del_d);
            }
        } else {
            ddebug("%s: checkpoint directory %s does not exist, ignored by garbage collection",
459
                   replica_name(),
Q
qinzuoyan 已提交
460 461 462 463
                   cpt_dir.c_str());
        }
    }

464 465 466
    // put back checkpoints which is not deleted, to make it delete again in the next gc time.
    // ATTENTION: the put back checkpoint may be incomplete, which will cause failure on load. But
    // it would not cause data lost, because incomplete checkpoint can not be loaded successfully.
Q
qinzuoyan 已提交
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
    if (!put_back_list.empty()) {
        ::dsn::utils::auto_lock<::dsn::utils::ex_lock_nr> l(_checkpoints_lock);
        if (_checkpoints.empty() || put_back_list.back() < _checkpoints.front()) {
            // just insert to front will hold the order
            _checkpoints.insert(_checkpoints.begin(), put_back_list.begin(), put_back_list.end());
        } else {
            // need to re-sort
            _checkpoints.insert(_checkpoints.begin(), put_back_list.begin(), put_back_list.end());
            std::sort(_checkpoints.begin(), _checkpoints.end());
        }

        if (!_checkpoints.empty()) {
            min_d = _checkpoints.front();
            max_d = _checkpoints.back();
            checkpoints_count = _checkpoints.size();
        } else {
            min_d = 0;
            max_d = 0;
            checkpoints_count = 0;
        }
    }

    ddebug("%s: after checkpoint garbage collection, checkpoints_count = %d, "
           "min_checkpoint = %" PRId64 ", max_checkpoint = %" PRId64,
491
           replica_name(),
Q
qinzuoyan 已提交
492 493 494 495 496
           checkpoints_count,
           min_d,
           max_d);
}

497
int pegasus_server_impl::on_batched_write_requests(int64_t decree,
W
Wu Tao 已提交
498
                                                   uint64_t timestamp,
499 500
                                                   dsn_message_t *requests,
                                                   int count)
Q
qinzuoyan 已提交
501 502 503 504
{
    dassert(_is_open, "");
    dassert(requests != nullptr, "");

505
    return _server_write->on_batched_write_requests(requests, count, decree, timestamp);
Q
qinzuoyan 已提交
506 507 508 509 510 511
}

void pegasus_server_impl::on_get(const ::dsn::blob &key,
                                 ::dsn::rpc_replier<::dsn::apps::read_response> &reply)
{
    dassert(_is_open, "");
512
    _pfc_get_qps->increment();
Q
qinzuoyan 已提交
513 514 515
    uint64_t start_time = dsn_now_ns();

    ::dsn::apps::read_response resp;
516 517
    resp.app_id = _gpid.get_app_id();
    resp.partition_index = _gpid.get_partition_index();
Q
qinzuoyan 已提交
518 519 520
    resp.server = _primary_address;

    rocksdb::Slice skey(key.data(), key.length());
521 522
    std::string value;
    rocksdb::Status status = _db->Get(_rd_opts, skey, &value);
Q
qinzuoyan 已提交
523 524

    if (status.ok()) {
525
        if (check_if_record_expired(utils::epoch_now(), value)) {
526
            _pfc_recent_expire_count->increment();
Q
qinzuoyan 已提交
527
            if (_verbose_log) {
528 529 530
                derror("%s: rocksdb data expired for get from %s",
                       replica_name(),
                       reply.to_address().to_string());
Q
qinzuoyan 已提交
531 532 533 534 535 536 537 538 539
            }
            status = rocksdb::Status::NotFound();
        }
    }

    if (!status.ok()) {
        if (_verbose_log) {
            ::dsn::blob hash_key, sort_key;
            pegasus_restore_key(key, hash_key, sort_key);
540
            derror("%s: rocksdb get failed for get from %s: "
541
                   "hash_key = \"%s\", sort_key = \"%s\", error = %s",
542
                   replica_name(),
543
                   reply.to_address().to_string(),
544 545
                   ::pegasus::utils::c_escape_string(hash_key).c_str(),
                   ::pegasus::utils::c_escape_string(sort_key).c_str(),
Q
qinzuoyan 已提交
546 547
                   status.ToString().c_str());
        } else if (!status.IsNotFound()) {
548
            derror("%s: rocksdb get failed for get from %s: error = %s",
549
                   replica_name(),
550
                   reply.to_address().to_string(),
Q
qinzuoyan 已提交
551 552 553 554
                   status.ToString().c_str());
        }
    }

555 556 557
    if (_abnormal_get_time_threshold_ns || _abnormal_get_size_threshold) {
        uint64_t time_used = dsn_now_ns() - start_time;
        if ((_abnormal_get_time_threshold_ns && time_used >= _abnormal_get_time_threshold_ns) ||
558
            (_abnormal_get_size_threshold && value.size() >= _abnormal_get_size_threshold)) {
559 560
            ::dsn::blob hash_key, sort_key;
            pegasus_restore_key(key, hash_key, sort_key);
561
            dwarn("%s: rocksdb abnormal get from %s: "
562 563 564
                  "hash_key = \"%s\", sort_key = \"%s\", return = %s, "
                  "value_size = %d, time_used = %" PRIu64 " ns",
                  replica_name(),
565
                  reply.to_address().to_string(),
566 567 568
                  ::pegasus::utils::c_escape_string(hash_key).c_str(),
                  ::pegasus::utils::c_escape_string(sort_key).c_str(),
                  status.ToString().c_str(),
569
                  (int)value.size(),
570
                  time_used);
571
            _pfc_recent_abnormal_count->increment();
572
        }
573 574
    }

Q
qinzuoyan 已提交
575 576 577 578 579
    resp.error = status.code();
    if (status.ok()) {
        pegasus_extract_user_data(_value_schema_version, std::move(value), resp.value);
    }

580
    _pfc_get_latency->set(dsn_now_ns() - start_time);
581

Q
qinzuoyan 已提交
582 583 584 585 586 587 588
    reply(resp);
}

void pegasus_server_impl::on_multi_get(const ::dsn::apps::multi_get_request &request,
                                       ::dsn::rpc_replier<::dsn::apps::multi_get_response> &reply)
{
    dassert(_is_open, "");
589
    _pfc_multi_get_qps->increment();
Q
qinzuoyan 已提交
590 591 592
    uint64_t start_time = dsn_now_ns();

    ::dsn::apps::multi_get_response resp;
593 594
    resp.app_id = _gpid.get_app_id();
    resp.partition_index = _gpid.get_partition_index();
Q
qinzuoyan 已提交
595 596
    resp.server = _primary_address;

597
    if (!is_filter_type_supported(request.sort_key_filter_type)) {
598 599
        derror("%s: invalid argument for multi_get from %s: "
               "sort key filter type %d not supported",
600
               replica_name(),
601
               reply.to_address().to_string(),
602 603
               request.sort_key_filter_type);
        resp.error = rocksdb::Status::kInvalidArgument;
604
        _pfc_multi_get_latency->set(dsn_now_ns() - start_time);
605 606 607 608
        reply(resp);
        return;
    }

Q
qinzuoyan 已提交
609 610 611
    int32_t max_kv_count = request.max_kv_count > 0 ? request.max_kv_count : INT_MAX;
    int32_t max_kv_size = request.max_kv_size > 0 ? request.max_kv_size : INT_MAX;
    uint32_t epoch_now = ::pegasus::utils::epoch_now();
612 613 614 615 616
    int32_t count = 0;
    int64_t size = 0;
    int32_t iterate_count = 0;
    int32_t expire_count = 0;
    int32_t filter_count = 0;
Q
qinzuoyan 已提交
617 618

    if (request.sort_keys.empty()) {
619 620 621
        ::dsn::blob range_start_key, range_stop_key;
        pegasus_generate_key(range_start_key, request.hash_key, request.start_sortkey);
        bool start_inclusive = request.start_inclusive;
622 623
        bool stop_inclusive;
        if (request.stop_sortkey.length() == 0) {
624
            pegasus_generate_next_blob(range_stop_key, request.hash_key);
625 626
            stop_inclusive = false;
        } else {
627
            pegasus_generate_key(range_stop_key, request.hash_key, request.stop_sortkey);
628 629 630
            stop_inclusive = request.stop_inclusive;
        }

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
        rocksdb::Slice start(range_start_key.data(), range_start_key.length());
        rocksdb::Slice stop(range_stop_key.data(), range_stop_key.length());

        // limit key range by prefix filter
        ::dsn::blob prefix_start_key, prefix_stop_key;
        if (request.sort_key_filter_type == ::dsn::apps::filter_type::FT_MATCH_PREFIX &&
            request.sort_key_filter_pattern.length() > 0) {
            pegasus_generate_key(
                prefix_start_key, request.hash_key, request.sort_key_filter_pattern);
            pegasus_generate_next_blob(
                prefix_stop_key, request.hash_key, request.sort_key_filter_pattern);

            rocksdb::Slice prefix_start(prefix_start_key.data(), prefix_start_key.length());
            if (prefix_start.compare(start) > 0) {
                start = prefix_start;
                start_inclusive = true;
            }

            rocksdb::Slice prefix_stop(prefix_stop_key.data(), prefix_stop_key.length());
            if (prefix_stop.compare(stop) <= 0) {
                stop = prefix_stop;
                stop_inclusive = false;
            }
        }

        // check if range is empty
        int c = start.compare(stop);
        if (c > 0 || (c == 0 && (!start_inclusive || !stop_inclusive))) {
            // empty sort key range
            if (_verbose_log) {
661
                dwarn("%s: empty sort key range for multi_get from %s: hash_key = \"%s\", "
662 663 664
                      "start_sort_key = \"%s\" (%s), stop_sort_key = \"%s\" (%s), "
                      "sort_key_filter_type = %s, sort_key_filter_pattern = \"%s\", "
                      "final_start = \"%s\" (%s), final_stop = \"%s\" (%s)",
665
                      replica_name(),
666
                      reply.to_address().to_string(),
667 668 669 670 671 672 673 674 675 676 677 678 679 680
                      ::pegasus::utils::c_escape_string(request.hash_key).c_str(),
                      ::pegasus::utils::c_escape_string(request.start_sortkey).c_str(),
                      request.start_inclusive ? "inclusive" : "exclusive",
                      ::pegasus::utils::c_escape_string(request.stop_sortkey).c_str(),
                      request.stop_inclusive ? "inclusive" : "exclusive",
                      ::dsn::apps::_filter_type_VALUES_TO_NAMES.find(request.sort_key_filter_type)
                          ->second,
                      ::pegasus::utils::c_escape_string(request.sort_key_filter_pattern).c_str(),
                      ::pegasus::utils::c_escape_string(start).c_str(),
                      start_inclusive ? "inclusive" : "exclusive",
                      ::pegasus::utils::c_escape_string(stop).c_str(),
                      stop_inclusive ? "inclusive" : "exclusive");
            }
            resp.error = rocksdb::Status::kOk;
681
            _pfc_multi_get_latency->set(dsn_now_ns() - start_time);
682 683 684 685
            reply(resp);
            return;
        }

686 687
        std::unique_ptr<rocksdb::Iterator> it(_db->NewIterator(_rd_opts));
        bool complete = false;
688 689 690 691
        if (!request.reverse) {
            it->Seek(start);
            bool first_exclusive = !start_inclusive;
            while (count < max_kv_count && size < max_kv_size && it->Valid()) {
692 693
                iterate_count++;

694 695 696 697 698 699 700
                // check stop sort key
                int c = it->key().compare(stop);
                if (c > 0 || (c == 0 && !stop_inclusive)) {
                    // out of range
                    complete = true;
                    break;
                }
701

702 703 704 705 706 707 708 709
                // check start sort key
                if (first_exclusive) {
                    first_exclusive = false;
                    if (it->key().compare(start) == 0) {
                        // discard start_sortkey
                        it->Next();
                        continue;
                    }
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
                // extract value
                int r = append_key_value_for_multi_get(resp.kvs,
                                                       it->key(),
                                                       it->value(),
                                                       request.sort_key_filter_type,
                                                       request.sort_key_filter_pattern,
                                                       epoch_now,
                                                       request.no_value);
                if (r == 1) {
                    count++;
                    auto &kv = resp.kvs.back();
                    size += kv.key.length() + kv.value.length();
                } else if (r == 2) {
                    expire_count++;
                } else { // r == 3
                    filter_count++;
                }

                if (c == 0) {
                    // if arrived to the last position
                    complete = true;
                    break;
                }

                it->Next();
Q
qinzuoyan 已提交
737
            }
738 739 740 741 742
        } else { // reverse
            it->SeekForPrev(stop);
            bool first_exclusive = !stop_inclusive;
            std::vector<::dsn::apps::key_value> reverse_kvs;
            while (count < max_kv_count && size < max_kv_size && it->Valid()) {
743 744
                iterate_count++;

745 746 747 748 749 750 751
                // check start sort key
                int c = it->key().compare(start);
                if (c < 0 || (c == 0 && !start_inclusive)) {
                    // out of range
                    complete = true;
                    break;
                }
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
                // check stop sort key
                if (first_exclusive) {
                    first_exclusive = false;
                    if (it->key().compare(stop) == 0) {
                        // discard stop_sortkey
                        it->Prev();
                        continue;
                    }
                }

                // extract value
                int r = append_key_value_for_multi_get(reverse_kvs,
                                                       it->key(),
                                                       it->value(),
                                                       request.sort_key_filter_type,
                                                       request.sort_key_filter_pattern,
                                                       epoch_now,
                                                       request.no_value);
                if (r == 1) {
                    count++;
                    auto &kv = reverse_kvs.back();
                    size += kv.key.length() + kv.value.length();
                } else if (r == 2) {
                    expire_count++;
                } else { // r == 3
                    filter_count++;
                }

                if (c == 0) {
                    // if arrived to the last position
                    complete = true;
                    break;
                }

                it->Prev();
788 789
            }

790 791 792 793 794 795 796
            if (it->status().ok() && !reverse_kvs.empty()) {
                // revert order to make resp.kvs ordered in sort_key
                resp.kvs.reserve(reverse_kvs.size());
                for (int i = reverse_kvs.size() - 1; i >= 0; i--) {
                    resp.kvs.emplace_back(std::move(reverse_kvs[i]));
                }
            }
Q
qinzuoyan 已提交
797 798 799 800 801 802
        }

        resp.error = it->status().code();
        if (!it->status().ok()) {
            // error occur
            if (_verbose_log) {
803 804
                derror("%s: rocksdb scan failed for multi_get from %s: "
                       "hash_key = \"%s\", reverse = %s, error = %s",
805
                       replica_name(),
806
                       reply.to_address().to_string(),
807
                       ::pegasus::utils::c_escape_string(request.hash_key).c_str(),
808
                       request.reverse ? "true" : "false",
Q
qinzuoyan 已提交
809 810
                       it->status().ToString().c_str());
            } else {
811 812
                derror("%s: rocksdb scan failed for multi_get from %s: "
                       "reverse = %s, error = %s",
813
                       replica_name(),
814
                       reply.to_address().to_string(),
815
                       request.reverse ? "true" : "false",
Q
qinzuoyan 已提交
816 817 818
                       it->status().ToString().c_str());
            }
            resp.kvs.clear();
819
        } else if (it->Valid() && !complete) {
Q
qinzuoyan 已提交
820 821 822 823
            // scan not completed
            resp.error = rocksdb::Status::kIncomplete;
        }
    } else {
824 825
        bool error_occurred = false;
        rocksdb::Status final_status;
Q
qinzuoyan 已提交
826
        bool exceed_limit = false;
827 828 829 830 831
        std::vector<::dsn::blob> keys_holder;
        std::vector<rocksdb::Slice> keys;
        std::vector<std::string> values;
        keys_holder.reserve(request.sort_keys.size());
        keys.reserve(request.sort_keys.size());
Q
qinzuoyan 已提交
832 833 834
        for (auto &sort_key : request.sort_keys) {
            ::dsn::blob raw_key;
            pegasus_generate_key(raw_key, request.hash_key, sort_key);
835 836 837
            keys.emplace_back(raw_key.data(), raw_key.length());
            keys_holder.emplace_back(std::move(raw_key));
        }
Q
qinzuoyan 已提交
838

839 840
        std::vector<rocksdb::Status> statuses = _db->MultiGet(_rd_opts, keys, &values);
        for (int i = 0; i < keys.size(); i++) {
841 842
            rocksdb::Status &status = statuses[i];
            std::string &value = values[i];
Q
qinzuoyan 已提交
843 844 845
            // print log
            if (!status.ok()) {
                if (_verbose_log) {
846
                    derror("%s: rocksdb get failed for multi_get from %s: "
847
                           "hash_key = \"%s\", sort_key = \"%s\", error = %s",
848
                           replica_name(),
849
                           reply.to_address().to_string(),
850
                           ::pegasus::utils::c_escape_string(request.hash_key).c_str(),
851
                           ::pegasus::utils::c_escape_string(request.sort_keys[i]).c_str(),
Q
qinzuoyan 已提交
852 853
                           status.ToString().c_str());
                } else if (!status.IsNotFound()) {
854
                    derror("%s: rocksdb get failed for multi_get from %s: error = %s",
855
                           replica_name(),
856
                           reply.to_address().to_string(),
Q
qinzuoyan 已提交
857 858 859
                           status.ToString().c_str());
                }
            }
860 861 862 863 864 865
            // check ttl
            if (status.ok()) {
                uint32_t expire_ts = pegasus_extract_expire_ts(_value_schema_version, value);
                if (expire_ts > 0 && expire_ts <= epoch_now) {
                    expire_count++;
                    if (_verbose_log) {
866 867 868
                        derror("%s: rocksdb data expired for multi_get from %s",
                               replica_name(),
                               reply.to_address().to_string());
869 870 871 872
                    }
                    status = rocksdb::Status::NotFound();
                }
            }
Q
qinzuoyan 已提交
873 874
            // extract value
            if (status.ok()) {
875 876 877 878 879
                // check if exceed limit
                if (count >= max_kv_count || size >= max_kv_size) {
                    exceed_limit = true;
                    break;
                }
Q
qinzuoyan 已提交
880
                ::dsn::apps::key_value kv;
881
                kv.key = request.sort_keys[i];
Q
qinzuoyan 已提交
882
                if (!request.no_value) {
883
                    pegasus_extract_user_data(_value_schema_version, std::move(value), kv.value);
Q
qinzuoyan 已提交
884 885 886
                }
                count++;
                size += kv.key.length() + kv.value.length();
887
                resp.kvs.emplace_back(std::move(kv));
Q
qinzuoyan 已提交
888 889 890 891
            }
            // if error occurred
            if (!status.ok() && !status.IsNotFound()) {
                error_occurred = true;
892
                final_status = status;
Q
qinzuoyan 已提交
893 894 895 896 897
                break;
            }
        }

        if (error_occurred) {
898
            resp.error = final_status.code();
Q
qinzuoyan 已提交
899 900 901 902 903 904 905 906
            resp.kvs.clear();
        } else if (exceed_limit) {
            resp.error = rocksdb::Status::kIncomplete;
        } else {
            resp.error = rocksdb::Status::kOk;
        }
    }

907 908 909 910 911 912 913 914 915
    if (_abnormal_multi_get_time_threshold_ns || _abnormal_multi_get_size_threshold ||
        _abnormal_multi_get_iterate_count_threshold) {
        uint64_t time_used = dsn_now_ns() - start_time;
        if ((_abnormal_multi_get_time_threshold_ns &&
             time_used >= _abnormal_multi_get_time_threshold_ns) ||
            (_abnormal_multi_get_size_threshold &&
             (uint64_t)size >= _abnormal_multi_get_size_threshold) ||
            (_abnormal_multi_get_iterate_count_threshold &&
             (uint64_t)iterate_count >= _abnormal_multi_get_iterate_count_threshold)) {
916 917 918
            dwarn("%s: rocksdb abnormal multi_get from %s: hash_key = \"%s\", "
                  "start_sort_key = \"%s\" (%s), stop_sort_key = \"%s\" (%s), "
                  "sort_key_filter_type = %s, sort_key_filter_pattern = \"%s\", "
919 920 921
                  "result_count = %d, result_size = %" PRId64 ", iterate_count = %d, "
                  "expire_count = %d, filter_count = %d, time_used = %" PRIu64 " ns",
                  replica_name(),
922
                  reply.to_address().to_string(),
923
                  ::pegasus::utils::c_escape_string(request.hash_key).c_str(),
924 925 926 927 928 929 930
                  ::pegasus::utils::c_escape_string(request.start_sortkey).c_str(),
                  request.start_inclusive ? "inclusive" : "exclusive",
                  ::pegasus::utils::c_escape_string(request.stop_sortkey).c_str(),
                  request.stop_inclusive ? "inclusive" : "exclusive",
                  ::dsn::apps::_filter_type_VALUES_TO_NAMES.find(request.sort_key_filter_type)
                      ->second,
                  ::pegasus::utils::c_escape_string(request.sort_key_filter_pattern).c_str(),
931 932 933 934 935 936
                  count,
                  size,
                  iterate_count,
                  expire_count,
                  filter_count,
                  time_used);
937
            _pfc_recent_abnormal_count->increment();
938 939 940
        }
    }

941
    if (expire_count > 0) {
942
        _pfc_recent_expire_count->add(expire_count);
943
    }
944
    if (filter_count > 0) {
945
        _pfc_recent_filter_count->add(filter_count);
946
    }
947
    _pfc_multi_get_latency->set(dsn_now_ns() - start_time);
948

Q
qinzuoyan 已提交
949 950 951 952 953 954 955 956 957
    reply(resp);
}

void pegasus_server_impl::on_sortkey_count(const ::dsn::blob &hash_key,
                                           ::dsn::rpc_replier<::dsn::apps::count_response> &reply)
{
    dassert(_is_open, "");

    ::dsn::apps::count_response resp;
958 959
    resp.app_id = _gpid.get_app_id();
    resp.partition_index = _gpid.get_partition_index();
Q
qinzuoyan 已提交
960 961 962 963 964 965 966 967 968 969 970 971 972
    resp.server = _primary_address;

    // scan
    ::dsn::blob start_key, stop_key;
    pegasus_generate_key(start_key, hash_key, ::dsn::blob());
    pegasus_generate_next_blob(stop_key, hash_key);
    rocksdb::Slice start(start_key.data(), start_key.length());
    rocksdb::Slice stop(stop_key.data(), stop_key.length());
    rocksdb::ReadOptions options = _rd_opts;
    options.iterate_upper_bound = &stop;
    std::unique_ptr<rocksdb::Iterator> it(_db->NewIterator(options));
    it->Seek(start);
    resp.count = 0;
973 974
    uint32_t epoch_now = ::pegasus::utils::epoch_now();
    uint64_t expire_count = 0;
Q
qinzuoyan 已提交
975
    while (it->Valid()) {
976
        if (check_if_record_expired(epoch_now, it->value())) {
977 978
            expire_count++;
            if (_verbose_log) {
979 980 981
                derror("%s: rocksdb data expired for sortkey_count from %s",
                       replica_name(),
                       reply.to_address().to_string());
982 983 984 985
            }
        } else {
            resp.count++;
        }
Q
qinzuoyan 已提交
986 987
        it->Next();
    }
988
    if (expire_count > 0) {
989
        _pfc_recent_expire_count->add(expire_count);
990
    }
Q
qinzuoyan 已提交
991 992 993 994 995

    resp.error = it->status().code();
    if (!it->status().ok()) {
        // error occur
        if (_verbose_log) {
996 997
            derror("%s: rocksdb scan failed for sortkey_count from %s: "
                   "hash_key = \"%s\", error = %s",
998
                   replica_name(),
999
                   reply.to_address().to_string(),
1000
                   ::pegasus::utils::c_escape_string(hash_key).c_str(),
Q
qinzuoyan 已提交
1001 1002
                   it->status().ToString().c_str());
        } else {
1003
            derror("%s: rocksdb scan failed for sortkey_count from %s: error = %s",
1004
                   replica_name(),
1005
                   reply.to_address().to_string(),
Q
qinzuoyan 已提交
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
                   it->status().ToString().c_str());
        }
        resp.count = 0;
    }

    reply(resp);
}

void pegasus_server_impl::on_ttl(const ::dsn::blob &key,
                                 ::dsn::rpc_replier<::dsn::apps::ttl_response> &reply)
{
    dassert(_is_open, "");

    ::dsn::apps::ttl_response resp;
1020 1021
    resp.app_id = _gpid.get_app_id();
    resp.partition_index = _gpid.get_partition_index();
Q
qinzuoyan 已提交
1022 1023 1024 1025 1026 1027 1028 1029 1030
    resp.server = _primary_address;

    rocksdb::Slice skey(key.data(), key.length());
    std::string value;
    rocksdb::Status status = _db->Get(_rd_opts, skey, &value);

    uint32_t expire_ts;
    uint32_t now_ts = ::pegasus::utils::epoch_now();
    if (status.ok()) {
1031
        if (check_if_record_expired(now_ts, value)) {
1032
            _pfc_recent_expire_count->increment();
Q
qinzuoyan 已提交
1033
            if (_verbose_log) {
1034 1035 1036
                derror("%s: rocksdb data expired for ttl from %s",
                       replica_name(),
                       reply.to_address().to_string());
Q
qinzuoyan 已提交
1037 1038 1039 1040 1041 1042 1043 1044 1045
            }
            status = rocksdb::Status::NotFound();
        }
    }

    if (!status.ok()) {
        if (_verbose_log) {
            ::dsn::blob hash_key, sort_key;
            pegasus_restore_key(key, hash_key, sort_key);
1046
            derror("%s: rocksdb get failed for ttl from %s: "
1047
                   "hash_key = \"%s\", sort_key = \"%s\", error = %s",
1048
                   replica_name(),
1049
                   reply.to_address().to_string(),
1050 1051
                   ::pegasus::utils::c_escape_string(hash_key).c_str(),
                   ::pegasus::utils::c_escape_string(sort_key).c_str(),
Q
qinzuoyan 已提交
1052 1053
                   status.ToString().c_str());
        } else if (!status.IsNotFound()) {
1054
            derror("%s: rocksdb get failed for ttl from %s: error = %s",
1055
                   replica_name(),
1056
                   reply.to_address().to_string(),
Q
qinzuoyan 已提交
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
                   status.ToString().c_str());
        }
    }

    resp.error = status.code();
    if (status.ok()) {
        if (expire_ts > 0) {
            resp.ttl_seconds = expire_ts - now_ts;
        } else {
            // no ttl
            resp.ttl_seconds = -1;
        }
    }

    reply(resp);
}

1074
void pegasus_server_impl::on_get_scanner(const ::dsn::apps::get_scanner_request &request,
Q
qinzuoyan 已提交
1075 1076 1077
                                         ::dsn::rpc_replier<::dsn::apps::scan_response> &reply)
{
    dassert(_is_open, "");
1078
    _pfc_scan_qps->increment();
1079
    uint64_t start_time = dsn_now_ns();
Q
qinzuoyan 已提交
1080 1081

    ::dsn::apps::scan_response resp;
1082 1083
    resp.app_id = _gpid.get_app_id();
    resp.partition_index = _gpid.get_partition_index();
Q
qinzuoyan 已提交
1084 1085
    resp.server = _primary_address;

1086
    if (!is_filter_type_supported(request.hash_key_filter_type)) {
1087 1088
        derror("%s: invalid argument for get_scanner from %s: "
               "hash key filter type %d not supported",
1089
               replica_name(),
1090
               reply.to_address().to_string(),
1091 1092 1093 1094 1095 1096
               request.hash_key_filter_type);
        resp.error = rocksdb::Status::kInvalidArgument;
        reply(resp);
        return;
    }
    if (!is_filter_type_supported(request.sort_key_filter_type)) {
1097 1098
        derror("%s: invalid argument for get_scanner from %s: "
               "sort key filter type %d not supported",
1099
               replica_name(),
1100
               reply.to_address().to_string(),
1101 1102 1103 1104 1105 1106
               request.sort_key_filter_type);
        resp.error = rocksdb::Status::kInvalidArgument;
        reply(resp);
        return;
    }

1107 1108
    bool start_inclusive = request.start_inclusive;
    bool stop_inclusive = request.stop_inclusive;
1109 1110
    rocksdb::Slice start(request.start_key.data(), request.start_key.length());
    rocksdb::Slice stop(request.stop_key.data(), request.stop_key.length());
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130

    // limit key range by prefix filter
    // because data is not ordered by hash key (hash key "aa" is greater than "b"),
    // so we can only limit the start range by hash key filter.
    ::dsn::blob prefix_start_key;
    if (request.hash_key_filter_type == ::dsn::apps::filter_type::FT_MATCH_PREFIX &&
        request.hash_key_filter_pattern.length() > 0) {
        pegasus_generate_key(prefix_start_key, request.hash_key_filter_pattern, ::dsn::blob());
        rocksdb::Slice prefix_start(prefix_start_key.data(), prefix_start_key.length());
        if (prefix_start.compare(start) > 0) {
            start = prefix_start;
            start_inclusive = true;
        }
    }

    // check if range is empty
    int c = start.compare(stop);
    if (c > 0 || (c == 0 && (!start_inclusive || !stop_inclusive))) {
        // empty key range
        if (_verbose_log) {
1131
            dwarn("%s: empty key range for get_scanner from %s: "
1132
                  "start_key = \"%s\" (%s), stop_key = \"%s\" (%s)",
1133
                  replica_name(),
1134
                  reply.to_address().to_string(),
1135 1136 1137 1138 1139 1140
                  ::pegasus::utils::c_escape_string(request.start_key).c_str(),
                  request.start_inclusive ? "inclusive" : "exclusive",
                  ::pegasus::utils::c_escape_string(request.stop_key).c_str(),
                  request.stop_inclusive ? "inclusive" : "exclusive");
        }
        resp.error = rocksdb::Status::kOk;
1141
        _pfc_multi_get_latency->set(dsn_now_ns() - start_time);
1142 1143 1144
        reply(resp);
        return;
    }
Q
qinzuoyan 已提交
1145

1146
    std::unique_ptr<rocksdb::Iterator> it(_db->NewIterator(_rd_opts));
Q
qinzuoyan 已提交
1147 1148
    it->Seek(start);
    bool complete = false;
1149
    bool first_exclusive = !start_inclusive;
Q
qinzuoyan 已提交
1150
    uint32_t epoch_now = ::pegasus::utils::epoch_now();
1151
    uint64_t expire_count = 0;
1152 1153
    uint64_t filter_count = 0;
    int32_t count = 0;
1154
    resp.kvs.reserve(request.batch_size);
1155 1156
    while (count < request.batch_size && it->Valid()) {
        int c = it->key().compare(stop);
1157
        if (c > 0 || (c == 0 && !stop_inclusive)) {
1158
            // out of range
Q
qinzuoyan 已提交
1159 1160
            complete = true;
            break;
1161 1162 1163 1164 1165 1166 1167
        }

        if (first_exclusive) {
            first_exclusive = false;
            if (it->key().compare(start) == 0) {
                // discard start_sortkey
                it->Next();
Q
qinzuoyan 已提交
1168 1169 1170 1171
                continue;
            }
        }

1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
        int r = append_key_value_for_scan(resp.kvs,
                                          it->key(),
                                          it->value(),
                                          request.hash_key_filter_type,
                                          request.hash_key_filter_pattern,
                                          request.sort_key_filter_type,
                                          request.sort_key_filter_pattern,
                                          epoch_now,
                                          request.no_value);
        if (r == 1) {
            count++;
        } else if (r == 2) {
1184
            expire_count++;
1185 1186
        } else { // r == 3
            filter_count++;
1187
        }
1188 1189 1190 1191 1192 1193 1194 1195

        if (c == 0) {
            // seek to the last position
            complete = true;
            break;
        }

        it->Next();
1196
    }
Q
qinzuoyan 已提交
1197

1198 1199 1200 1201
    resp.error = it->status().code();
    if (!it->status().ok()) {
        // error occur
        if (_verbose_log) {
1202
            derror("%s: rocksdb scan failed for get_scanner from %s: "
1203
                   "start_key = \"%s\" (%s), stop_key = \"%s\" (%s), "
1204
                   "batch_size = %d, read_count = %d, error = %s",
1205
                   replica_name(),
1206
                   reply.to_address().to_string(),
1207
                   ::pegasus::utils::c_escape_string(start).c_str(),
1208
                   request.start_inclusive ? "inclusive" : "exclusive",
1209
                   ::pegasus::utils::c_escape_string(stop).c_str(),
1210 1211 1212 1213 1214
                   request.stop_inclusive ? "inclusive" : "exclusive",
                   request.batch_size,
                   count,
                   it->status().ToString().c_str());
        } else {
1215
            derror("%s: rocksdb scan failed for get_scanner from %s: error = %s",
1216
                   replica_name(),
1217
                   reply.to_address().to_string(),
1218 1219 1220 1221 1222
                   it->status().ToString().c_str());
        }
        resp.kvs.clear();
    } else if (it->Valid() && !complete) {
        // scan not completed
Q
qinzuoyan 已提交
1223 1224 1225
        std::unique_ptr<pegasus_scan_context> context(
            new pegasus_scan_context(std::move(it),
                                     std::string(stop.data(), stop.size()),
1226 1227 1228 1229 1230 1231 1232 1233 1234
                                     request.stop_inclusive,
                                     request.hash_key_filter_type,
                                     std::string(request.hash_key_filter_pattern.data(),
                                                 request.hash_key_filter_pattern.length()),
                                     request.sort_key_filter_type,
                                     std::string(request.sort_key_filter_pattern.data(),
                                                 request.sort_key_filter_pattern.length()),
                                     request.batch_size,
                                     request.no_value));
Q
qinzuoyan 已提交
1235 1236
        int64_t handle = _context_cache.put(std::move(context));
        resp.context_id = handle;
1237 1238
        // if the context is used, it will be fetched and re-put into cache,
        // which will change the handle,
Q
qinzuoyan 已提交
1239
        // then the delayed task will fetch null context by old handle, and do nothing.
1240 1241
        ::dsn::tasking::enqueue(LPC_PEGASUS_SERVER_DELAY,
                                &_tracker,
Q
qinzuoyan 已提交
1242 1243 1244
                                [this, handle]() { _context_cache.fetch(handle); },
                                0,
                                std::chrono::minutes(5));
1245 1246 1247
    } else {
        // scan completed
        resp.context_id = pegasus::SCAN_CONTEXT_ID_COMPLETED;
Q
qinzuoyan 已提交
1248 1249
    }

1250
    if (expire_count > 0) {
1251
        _pfc_recent_expire_count->add(expire_count);
1252 1253
    }
    if (filter_count > 0) {
1254
        _pfc_recent_filter_count->add(filter_count);
1255 1256
    }

1257
    _pfc_scan_latency->set(dsn_now_ns() - start_time);
Q
qinzuoyan 已提交
1258 1259 1260
    reply(resp);
}

1261
void pegasus_server_impl::on_scan(const ::dsn::apps::scan_request &request,
Q
qinzuoyan 已提交
1262 1263 1264
                                  ::dsn::rpc_replier<::dsn::apps::scan_response> &reply)
{
    dassert(_is_open, "");
1265
    _pfc_scan_qps->increment();
Q
qinzuoyan 已提交
1266 1267 1268
    uint64_t start_time = dsn_now_ns();

    ::dsn::apps::scan_response resp;
1269 1270
    resp.app_id = _gpid.get_app_id();
    resp.partition_index = _gpid.get_partition_index();
Q
qinzuoyan 已提交
1271 1272
    resp.server = _primary_address;

1273
    std::unique_ptr<pegasus_scan_context> context = _context_cache.fetch(request.context_id);
Q
qinzuoyan 已提交
1274 1275 1276 1277
    if (context) {
        rocksdb::Iterator *it = context->iterator.get();
        int32_t batch_size = context->batch_size;
        const rocksdb::Slice &stop = context->stop;
1278 1279 1280 1281 1282 1283
        bool stop_inclusive = context->stop_inclusive;
        ::dsn::apps::filter_type::type hash_key_filter_type = context->hash_key_filter_type;
        const ::dsn::blob &hash_key_filter_pattern = context->hash_key_filter_pattern;
        ::dsn::apps::filter_type::type sort_key_filter_type = context->hash_key_filter_type;
        const ::dsn::blob &sort_key_filter_pattern = context->hash_key_filter_pattern;
        bool no_value = context->no_value;
Q
qinzuoyan 已提交
1284 1285
        bool complete = false;
        uint32_t epoch_now = ::pegasus::utils::epoch_now();
1286
        uint64_t expire_count = 0;
1287 1288 1289 1290 1291 1292 1293
        uint64_t filter_count = 0;
        int32_t count = 0;

        while (count < batch_size && it->Valid()) {
            int c = it->key().compare(stop);
            if (c > 0 || (c == 0 && !stop_inclusive)) {
                // out of range
Q
qinzuoyan 已提交
1294 1295 1296
                complete = true;
                break;
            }
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309

            int r = append_key_value_for_scan(resp.kvs,
                                              it->key(),
                                              it->value(),
                                              hash_key_filter_type,
                                              hash_key_filter_pattern,
                                              sort_key_filter_type,
                                              sort_key_filter_pattern,
                                              epoch_now,
                                              no_value);
            if (r == 1) {
                count++;
            } else if (r == 2) {
1310
                expire_count++;
1311 1312
            } else { // r == 3
                filter_count++;
1313
            }
1314 1315 1316 1317 1318 1319 1320 1321

            if (c == 0) {
                // seek to the last position
                complete = true;
                break;
            }

            it->Next();
1322
        }
1323 1324 1325 1326 1327

        resp.error = it->status().code();
        if (!it->status().ok()) {
            // error occur
            if (_verbose_log) {
1328
                derror("%s: rocksdb scan failed for scan from %s: "
1329
                       "context_id= %" PRId64 ", stop_key = \"%s\" (%s), "
1330
                       "batch_size = %d, read_count = %d, error = %s",
1331
                       replica_name(),
1332
                       reply.to_address().to_string(),
1333
                       request.context_id,
1334 1335
                       ::pegasus::utils::c_escape_string(stop).c_str(),
                       stop_inclusive ? "inclusive" : "exclusive",
1336 1337 1338 1339
                       batch_size,
                       count,
                       it->status().ToString().c_str());
            } else {
1340
                derror("%s: rocksdb scan failed for scan from %s: error = %s",
1341
                       replica_name(),
1342
                       reply.to_address().to_string(),
1343 1344 1345 1346 1347
                       it->status().ToString().c_str());
            }
            resp.kvs.clear();
        } else if (it->Valid() && !complete) {
            // scan not completed
Q
qinzuoyan 已提交
1348 1349
            int64_t handle = _context_cache.put(std::move(context));
            resp.context_id = handle;
1350 1351
            ::dsn::tasking::enqueue(LPC_PEGASUS_SERVER_DELAY,
                                    &_tracker,
Q
qinzuoyan 已提交
1352 1353 1354
                                    [this, handle]() { _context_cache.fetch(handle); },
                                    0,
                                    std::chrono::minutes(5));
1355 1356 1357 1358 1359 1360
        } else {
            // scan completed
            resp.context_id = pegasus::SCAN_CONTEXT_ID_COMPLETED;
        }

        if (expire_count > 0) {
1361
            _pfc_recent_expire_count->add(expire_count);
1362 1363
        }
        if (filter_count > 0) {
1364
            _pfc_recent_filter_count->add(filter_count);
Q
qinzuoyan 已提交
1365 1366 1367 1368 1369
        }
    } else {
        resp.error = rocksdb::Status::Code::kNotFound;
    }

1370
    _pfc_scan_latency->set(dsn_now_ns() - start_time);
Q
qinzuoyan 已提交
1371 1372 1373 1374 1375 1376 1377 1378
    reply(resp);
}

void pegasus_server_impl::on_clear_scanner(const int64_t &args) { _context_cache.fetch(args); }

::dsn::error_code pegasus_server_impl::start(int argc, char **argv)
{
    dassert(!_is_open, "");
1379
    ddebug("%s: start to open app %s", replica_name(), data_dir().c_str());
Q
qinzuoyan 已提交
1380 1381 1382 1383 1384 1385 1386

    rocksdb::Options opts = _db_opts;
    opts.create_if_missing = true;
    opts.error_if_exists = false;
    opts.compaction_filter = &_key_ttl_compaction_filter;
    opts.default_value_schema_version = PEGASUS_VALUE_SCHEMA_MAX_VERSION;

1387 1388 1389
    // parse envs for parameters
    // envs is compounded in replication_app_base::open() function
    std::map<std::string, std::string> envs;
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
    if (argc > 0) {
        if (((argc - 1) % 2 != 0) || argv == nullptr) {
            derror("%s: parse envs failed, because invalid argc = %d or argv = nullptr",
                   replica_name(),
                   argc);
            return ::dsn::ERR_INVALID_PARAMETERS;
        }
        int idx = 1;
        while (idx < argc) {
            const char *key = argv[idx++];
            const char *value = argv[idx++];
            envs.emplace(key, value);
        }
1403
    }
C
cailiuyang 已提交
1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417

    //
    // here, we must distinguish three cases, such as:
    //  case 1: we open the db that already exist
    //  case 2: we open a new db
    //  case 3: we restore the db base on old data
    //
    // if we want to restore the db base on old data, only all of the restore preconditions are
    // satisfied
    //      restore preconditions:
    //          1, rdb isn't exist
    //          2, we can parse restore info from app env, which is stored in argv
    //          3, restore_dir is exist
    //
1418
    auto path = ::dsn::utils::filesystem::path_combine(data_dir(), "rdb");
C
cailiuyang 已提交
1419 1420
    if (::dsn::utils::filesystem::path_exists(path)) {
        // only case 1
1421
        ddebug("%s: rdb is already exist, path = %s", replica_name(), path.c_str());
C
cailiuyang 已提交
1422
    } else {
1423
        std::pair<std::string, bool> restore_info = get_restore_dir_from_env(envs);
C
cailiuyang 已提交
1424 1425 1426 1427
        const std::string &restore_dir = restore_info.first;
        bool force_restore = restore_info.second;
        if (restore_dir.empty()) {
            // case 2
1428 1429
            if (force_restore) {
                derror("%s: try to restore, but we can't combine restore_dir from envs",
1430
                       replica_name());
1431 1432
                return ::dsn::ERR_FILE_OPERATION_FAILED;
            } else {
1433
                dinfo("%s: open a new db, path = %s", replica_name(), path.c_str());
1434
            }
C
cailiuyang 已提交
1435 1436
        } else {
            // case 3
1437
            ddebug("%s: try to restore from restore_dir = %s", replica_name(), restore_dir.c_str());
C
cailiuyang 已提交
1438 1439 1440 1441
            if (::dsn::utils::filesystem::directory_exists(restore_dir)) {
                // here, we just rename restore_dir to rdb, then continue the normal process
                if (::dsn::utils::filesystem::rename_path(restore_dir.c_str(), path.c_str())) {
                    ddebug("%s: rename restore_dir(%s) to rdb(%s) succeed",
1442
                           replica_name(),
C
cailiuyang 已提交
1443 1444 1445 1446
                           restore_dir.c_str(),
                           path.c_str());
                } else {
                    derror("%s: rename restore_dir(%s) to rdb(%s) failed",
1447
                           replica_name(),
C
cailiuyang 已提交
1448 1449 1450 1451 1452 1453 1454
                           restore_dir.c_str(),
                           path.c_str());
                    return ::dsn::ERR_FILE_OPERATION_FAILED;
                }
            } else {
                if (force_restore) {
                    derror("%s: try to restore, but restore_dir isn't exist, restore_dir = %s",
1455
                           replica_name(),
C
cailiuyang 已提交
1456 1457 1458 1459 1460 1461 1462
                           restore_dir.c_str());
                    return ::dsn::ERR_FILE_OPERATION_FAILED;
                } else {
                    dwarn(
                        "%s: try to restore and restore_dir(%s) isn't exist, but we don't force "
                        "it, the role of this replica must not primary, so we open a new db on the "
                        "path(%s)",
1463
                        replica_name(),
C
cailiuyang 已提交
1464 1465 1466 1467 1468 1469 1470
                        restore_dir.c_str(),
                        path.c_str());
                }
            }
        }
    }

1471
    ddebug("%s: start to open rocksDB's rdb(%s)", replica_name(), path.c_str());
C
cailiuyang 已提交
1472

Q
qinzuoyan 已提交
1473 1474
    auto status = rocksdb::DB::Open(opts, path, &_db);
    if (status.ok()) {
1475
        _last_committed_decree = _db->GetLastFlushedDecree();
Q
qinzuoyan 已提交
1476 1477 1478
        _value_schema_version = _db->GetValueSchemaVersion();
        if (_value_schema_version > PEGASUS_VALUE_SCHEMA_MAX_VERSION) {
            derror("%s: open app failed, unsupported value schema version %" PRIu32,
1479
                   replica_name(),
Q
qinzuoyan 已提交
1480 1481 1482 1483 1484 1485
                   _value_schema_version);
            delete _db;
            _db = nullptr;
            return ::dsn::ERR_LOCAL_APP_FAILURE;
        }

1486 1487
        _manual_compact_svc.init_last_finish_time_ms(_db->GetLastManualCompactFinishTime());

Q
qinzuoyan 已提交
1488 1489 1490 1491
        // only enable filter after correct value_schema_version set
        _key_ttl_compaction_filter.SetValueSchemaVersion(_value_schema_version);
        _key_ttl_compaction_filter.EnableFilter();

1492 1493
        update_app_envs(envs);

Q
qinzuoyan 已提交
1494 1495
        parse_checkpoints();

1496 1497 1498 1499
        // checkpoint if necessary to make last_durable_decree() fresh.
        // only need async checkpoint because we sure that memtable is empty now.
        int64_t last_flushed = _db->GetLastFlushedDecree();
        if (last_flushed != last_durable_decree()) {
Q
qinzuoyan 已提交
1500 1501
            ddebug("%s: start to do async checkpoint, last_durable_decree = %" PRId64
                   ", last_flushed_decree = %" PRId64,
1502
                   replica_name(),
Q
qinzuoyan 已提交
1503
                   last_durable_decree(),
1504
                   last_flushed);
1505
            auto err = async_checkpoint(false);
Q
qinzuoyan 已提交
1506
            if (err != ::dsn::ERR_OK) {
1507 1508 1509 1510
                derror("%s: create checkpoint failed, error = %s", replica_name(), err.to_string());
                delete _db;
                _db = nullptr;
                return err;
Q
qinzuoyan 已提交
1511
            }
1512
            dassert(last_flushed == last_durable_decree(),
Q
qinzuoyan 已提交
1513
                    "last durable decree mismatch after checkpoint: %" PRId64 " vs %" PRId64,
1514
                    last_flushed,
Q
qinzuoyan 已提交
1515 1516 1517 1518 1519
                    last_durable_decree());
        }

        ddebug("%s: open app succeed, value_schema_version = %" PRIu32
               ", last_durable_decree = %" PRId64 "",
1520
               replica_name(),
Q
qinzuoyan 已提交
1521 1522 1523 1524 1525
               _value_schema_version,
               last_durable_decree());

        _is_open = true;

1526
        dinfo("%s: start the updating sstsize timer task", replica_name());
1527
        _updating_rocksdb_sstsize_timer_task = ::dsn::tasking::enqueue_timer(
1528 1529
            LPC_UPDATING_ROCKSDB_SSTSIZE,
            &_tracker,
Q
qinzuoyan 已提交
1530 1531 1532 1533 1534
            [this]() { this->updating_rocksdb_sstsize(); },
            std::chrono::seconds(_updating_rocksdb_sstsize_interval_seconds),
            0,
            std::chrono::seconds(30));

1535 1536 1537
        // initialize write service after server being initialized.
        _server_write = dsn::make_unique<pegasus_server_write>(this, _verbose_log);

Q
qinzuoyan 已提交
1538 1539
        return ::dsn::ERR_OK;
    } else {
1540
        derror("%s: open app failed, error = %s", replica_name(), status.ToString().c_str());
Q
qinzuoyan 已提交
1541 1542 1543 1544
        return ::dsn::ERR_LOCAL_APP_FAILURE;
    }
}

1545 1546 1547 1548 1549 1550
void pegasus_server_impl::cancel_background_work(bool wait)
{
    dassert(_db != nullptr, "");
    rocksdb::CancelAllBackgroundWork(_db, wait);
}

Q
qinzuoyan 已提交
1551 1552 1553 1554 1555 1556 1557 1558
::dsn::error_code pegasus_server_impl::stop(bool clear_state)
{
    if (!_is_open) {
        dassert(_db == nullptr, "");
        dassert(!clear_state, "should not be here if do clear");
        return ::dsn::ERR_OK;
    }

1559
    if (!clear_state) {
1560 1561
        auto status = _db->Flush(rocksdb::FlushOptions());
        if (!status.ok()) {
1562
            derror("%s: flush memtable on close failed: %s",
1563 1564
                   replica_name(),
                   status.ToString().c_str());
1565 1566 1567
        }
    }

1568
    // stop all tracked tasks when pegasus server is stopped.
1569 1570 1571 1572
    if (_updating_rocksdb_sstsize_timer_task != nullptr) {
        _updating_rocksdb_sstsize_timer_task->cancel(true);
        _updating_rocksdb_sstsize_timer_task = nullptr;
    }
1573
    _tracker.cancel_outstanding_tasks();
Q
qinzuoyan 已提交
1574

1575 1576
    _context_cache.clear();

Q
qinzuoyan 已提交
1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587
    _is_open = false;
    delete _db;
    _db = nullptr;

    {
        ::dsn::utils::auto_lock<::dsn::utils::ex_lock_nr> l(_checkpoints_lock);
        _checkpoints.clear();
        set_last_durable_decree(0);
    }

    if (clear_state) {
1588 1589 1590
        if (!::dsn::utils::filesystem::remove_path(data_dir())) {
            derror(
                "%s: clear directory %s failed when stop app", replica_name(), data_dir().c_str());
Q
qinzuoyan 已提交
1591 1592
            return ::dsn::ERR_FILE_OPERATION_FAILED;
        }
1593 1594
        _pfc_sst_count->set(0);
        _pfc_sst_size->set(0);
Q
qinzuoyan 已提交
1595 1596
    }

1597 1598
    ddebug(
        "%s: close app succeed, clear_state = %s", replica_name(), clear_state ? "true" : "false");
Q
qinzuoyan 已提交
1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620
    return ::dsn::ERR_OK;
}

class CheckpointingTokenHelper
{
public:
    CheckpointingTokenHelper(std::atomic_bool &flag) : _flag(flag)
    {
        bool expected = false;
        _token_got = _flag.compare_exchange_strong(expected, true);
    }
    ~CheckpointingTokenHelper()
    {
        if (_token_got)
            _flag.store(false);
    }
    bool token_got() const { return _token_got; }
private:
    std::atomic_bool &_flag;
    bool _token_got;
};

1621
::dsn::error_code pegasus_server_impl::sync_checkpoint()
Q
qinzuoyan 已提交
1622 1623 1624 1625 1626
{
    CheckpointingTokenHelper token_helper(_is_checkpointing);
    if (!token_helper.token_got())
        return ::dsn::ERR_WRONG_TIMING;

1627
    int64_t last_durable = last_durable_decree();
1628
    int64_t last_commit = last_committed_decree();
1629 1630 1631 1632 1633 1634 1635 1636 1637
    dassert(last_durable <= last_commit, "%" PRId64 " VS %" PRId64, last_durable, last_commit);

    if (last_durable == last_commit) {
        ddebug("%s: no need to checkpoint because "
               "last_durable_decree = last_committed_decree = %" PRId64,
               replica_name(),
               last_durable);
        return ::dsn::ERR_OK;
    }
Q
qinzuoyan 已提交
1638 1639 1640 1641 1642

    rocksdb::Checkpoint *chkpt = nullptr;
    auto status = rocksdb::Checkpoint::Create(_db, &chkpt);
    if (!status.ok()) {
        derror("%s: create Checkpoint object failed, error = %s",
1643
               replica_name(),
Q
qinzuoyan 已提交
1644 1645 1646 1647 1648
               status.ToString().c_str());
        return ::dsn::ERR_LOCAL_APP_FAILURE;
    }

    auto dir = chkpt_get_dir_name(last_commit);
1649
    auto chkpt_dir = ::dsn::utils::filesystem::path_combine(data_dir(), dir);
Q
qinzuoyan 已提交
1650 1651
    if (::dsn::utils::filesystem::directory_exists(chkpt_dir)) {
        ddebug("%s: checkpoint directory %s already exist, remove it first",
1652
               replica_name(),
Q
qinzuoyan 已提交
1653 1654
               chkpt_dir.c_str());
        if (!::dsn::utils::filesystem::remove_path(chkpt_dir)) {
1655 1656
            derror(
                "%s: remove old checkpoint directory %s failed", replica_name(), chkpt_dir.c_str());
Q
qinzuoyan 已提交
1657 1658 1659 1660 1661 1662
            delete chkpt;
            chkpt = nullptr;
            return ::dsn::ERR_FILE_OPERATION_FAILED;
        }
    }

1663 1664
    // CreateCheckpoint() will always flush memtable firstly.
    status = chkpt->CreateCheckpoint(chkpt_dir, 0);
Q
qinzuoyan 已提交
1665 1666 1667
    if (!status.ok()) {
        // sometimes checkpoint may fail, and try again will succeed
        derror("%s: create checkpoint failed, error = %s, try again",
1668
               replica_name(),
Q
qinzuoyan 已提交
1669
               status.ToString().c_str());
1670
        status = chkpt->CreateCheckpoint(chkpt_dir, 0);
Q
qinzuoyan 已提交
1671 1672 1673 1674 1675 1676 1677
    }

    // destroy Checkpoint object
    delete chkpt;
    chkpt = nullptr;

    if (!status.ok()) {
1678 1679
        derror(
            "%s: create checkpoint failed, error = %s", replica_name(), status.ToString().c_str());
Q
qinzuoyan 已提交
1680 1681 1682
        ::dsn::utils::filesystem::remove_path(chkpt_dir);
        if (!::dsn::utils::filesystem::remove_path(chkpt_dir)) {
            derror("%s: remove damaged checkpoint directory %s failed",
1683
                   replica_name(),
Q
qinzuoyan 已提交
1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694
                   chkpt_dir.c_str());
        }
        return ::dsn::ERR_LOCAL_APP_FAILURE;
    }

    {
        ::dsn::utils::auto_lock<::dsn::utils::ex_lock_nr> l(_checkpoints_lock);
        dassert(last_commit > last_durable_decree(),
                "%" PRId64 " VS %" PRId64 "",
                last_commit,
                last_durable_decree());
1695 1696 1697 1698
        dassert(last_commit == _db->GetLastFlushedDecree(),
                "%" PRId64 " VS %" PRId64 "",
                last_commit,
                _db->GetLastFlushedDecree());
Q
qinzuoyan 已提交
1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709
        if (!_checkpoints.empty()) {
            dassert(last_commit > _checkpoints.back(),
                    "%" PRId64 " VS %" PRId64 "",
                    last_commit,
                    _checkpoints.back());
        }
        _checkpoints.push_back(last_commit);
        set_last_durable_decree(_checkpoints.back());
    }

    ddebug("%s: sync create checkpoint succeed, last_durable_decree = %" PRId64 "",
1710
           replica_name(),
Q
qinzuoyan 已提交
1711 1712 1713 1714 1715 1716 1717 1718
           last_durable_decree());

    gc_checkpoints();

    return ::dsn::ERR_OK;
}

// Must be thread safe.
1719
::dsn::error_code pegasus_server_impl::async_checkpoint(bool flush_memtable)
Q
qinzuoyan 已提交
1720 1721 1722 1723 1724
{
    CheckpointingTokenHelper token_helper(_is_checkpointing);
    if (!token_helper.token_got())
        return ::dsn::ERR_WRONG_TIMING;

1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741
    int64_t last_durable = last_durable_decree();
    int64_t last_flushed = static_cast<int64_t>(_db->GetLastFlushedDecree());
    int64_t last_commit = last_committed_decree();

    dassert(last_durable <= last_flushed, "%" PRId64 " VS %" PRId64, last_durable, last_flushed);
    dassert(last_flushed <= last_commit, "%" PRId64 " VS %" PRId64, last_flushed, last_commit);

    if (last_durable == last_commit) {
        ddebug("%s: no need to checkpoint because "
               "last_durable_decree = last_committed_decree = %" PRId64,
               replica_name(),
               last_durable);
        return ::dsn::ERR_OK;
    }

    if (last_durable == last_flushed) {
        if (flush_memtable) {
Q
qinzuoyan 已提交
1742 1743 1744 1745 1746
            // trigger flushing memtable, but not wait
            rocksdb::FlushOptions options;
            options.wait = false;
            auto status = _db->Flush(options);
            if (status.ok()) {
1747
                ddebug("%s: trigger flushing memtable succeed", replica_name());
Q
qinzuoyan 已提交
1748 1749 1750
                return ::dsn::ERR_TRY_AGAIN;
            } else {
                derror("%s: trigger flushing memtable failed, error = %s",
1751
                       replica_name(),
Q
qinzuoyan 已提交
1752 1753 1754 1755
                       status.ToString().c_str());
                return ::dsn::ERR_LOCAL_APP_FAILURE;
            }
        } else {
1756
            return ::dsn::ERR_OK;
Q
qinzuoyan 已提交
1757 1758 1759
        }
    }

1760
    dassert(last_durable < last_flushed, "%" PRId64 " VS %" PRId64, last_durable, last_flushed);
Q
qinzuoyan 已提交
1761 1762 1763

    char buf[256];
    sprintf(buf, "checkpoint.tmp.%" PRIu64 "", dsn_now_us());
1764
    std::string tmp_dir = ::dsn::utils::filesystem::path_combine(data_dir(), buf);
Q
qinzuoyan 已提交
1765 1766
    if (::dsn::utils::filesystem::directory_exists(tmp_dir)) {
        ddebug("%s: temporary checkpoint directory %s already exist, remove it first",
1767
               replica_name(),
Q
qinzuoyan 已提交
1768 1769 1770
               tmp_dir.c_str());
        if (!::dsn::utils::filesystem::remove_path(tmp_dir)) {
            derror("%s: remove temporary checkpoint directory %s failed",
1771
                   replica_name(),
Q
qinzuoyan 已提交
1772 1773 1774 1775
                   tmp_dir.c_str());
            return ::dsn::ERR_FILE_OPERATION_FAILED;
        }
    }
1776

1777 1778 1779 1780
    int64_t checkpoint_decree = 0;
    ::dsn::error_code err = copy_checkpoint_to_dir_unsafe(tmp_dir.c_str(), &checkpoint_decree);
    if (err != ::dsn::ERR_OK) {
        derror("%s: call copy_checkpoint_to_dir_unsafe failed with err = %s",
1781
               replica_name(),
1782 1783
               err.to_string());
        return ::dsn::ERR_LOCAL_APP_FAILURE;
Q
qinzuoyan 已提交
1784 1785
    }

1786
    auto chkpt_dir =
1787
        ::dsn::utils::filesystem::path_combine(data_dir(), chkpt_get_dir_name(checkpoint_decree));
Q
qinzuoyan 已提交
1788 1789
    if (::dsn::utils::filesystem::directory_exists(chkpt_dir)) {
        ddebug("%s: checkpoint directory %s already exist, remove it first",
1790
               replica_name(),
Q
qinzuoyan 已提交
1791 1792
               chkpt_dir.c_str());
        if (!::dsn::utils::filesystem::remove_path(chkpt_dir)) {
1793 1794
            derror(
                "%s: remove old checkpoint directory %s failed", replica_name(), chkpt_dir.c_str());
Q
qinzuoyan 已提交
1795 1796
            if (!::dsn::utils::filesystem::remove_path(tmp_dir)) {
                derror("%s: remove temporary checkpoint directory %s failed",
1797
                       replica_name(),
Q
qinzuoyan 已提交
1798 1799 1800 1801 1802 1803 1804 1805
                       tmp_dir.c_str());
            }
            return ::dsn::ERR_FILE_OPERATION_FAILED;
        }
    }

    if (!::dsn::utils::filesystem::rename_path(tmp_dir, chkpt_dir)) {
        derror("%s: rename checkpoint directory from %s to %s failed",
1806
               replica_name(),
Q
qinzuoyan 已提交
1807 1808 1809 1810
               tmp_dir.c_str(),
               chkpt_dir.c_str());
        if (!::dsn::utils::filesystem::remove_path(tmp_dir)) {
            derror("%s: remove temporary checkpoint directory %s failed",
1811
                   replica_name(),
Q
qinzuoyan 已提交
1812 1813 1814 1815 1816 1817 1818
                   tmp_dir.c_str());
        }
        return ::dsn::ERR_FILE_OPERATION_FAILED;
    }

    {
        ::dsn::utils::auto_lock<::dsn::utils::ex_lock_nr> l(_checkpoints_lock);
1819 1820 1821 1822
        dassert(checkpoint_decree > last_durable_decree(),
                "%" PRId64 " VS %" PRId64 "",
                checkpoint_decree,
                last_durable_decree());
Q
qinzuoyan 已提交
1823
        if (!_checkpoints.empty()) {
1824 1825 1826 1827
            dassert(checkpoint_decree > _checkpoints.back(),
                    "%" PRId64 " VS %" PRId64 "",
                    checkpoint_decree,
                    _checkpoints.back());
Q
qinzuoyan 已提交
1828
        }
1829
        _checkpoints.push_back(checkpoint_decree);
Q
qinzuoyan 已提交
1830 1831 1832 1833
        set_last_durable_decree(_checkpoints.back());
    }

    ddebug("%s: async create checkpoint succeed, last_durable_decree = %" PRId64 "",
1834
           replica_name(),
Q
qinzuoyan 已提交
1835 1836 1837 1838 1839 1840 1841
           last_durable_decree());

    gc_checkpoints();

    return ::dsn::ERR_OK;
}

1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863
// Must be thread safe.
::dsn::error_code pegasus_server_impl::copy_checkpoint_to_dir(const char *checkpoint_dir,
                                                              /*output*/ int64_t *last_decree)
{
    CheckpointingTokenHelper token_helper(_is_checkpointing);
    if (!token_helper.token_got()) {
        return ::dsn::ERR_WRONG_TIMING;
    }

    return copy_checkpoint_to_dir_unsafe(checkpoint_dir, last_decree);
}

// not thread safe, should be protected by caller
::dsn::error_code pegasus_server_impl::copy_checkpoint_to_dir_unsafe(const char *checkpoint_dir,
                                                                     int64_t *checkpoint_decree)
{
    rocksdb::Checkpoint *chkpt = nullptr;
    rocksdb::Status status = rocksdb::Checkpoint::Create(_db, &chkpt);
    if (!status.ok()) {
        if (chkpt != nullptr)
            delete chkpt, chkpt = nullptr;
        derror("%s: create Checkpoint object failed, error = %s",
1864
               replica_name(),
1865 1866 1867 1868 1869 1870
               status.ToString().c_str());
        return ::dsn::ERR_LOCAL_APP_FAILURE;
    }

    if (::dsn::utils::filesystem::directory_exists(checkpoint_dir)) {
        ddebug("%s: checkpoint directory %s is already exist, remove it first",
1871
               replica_name(),
1872 1873
               checkpoint_dir);
        if (!::dsn::utils::filesystem::remove_path(checkpoint_dir)) {
1874
            derror("%s: remove checkpoint directory %s failed", replica_name(), checkpoint_dir);
1875 1876 1877 1878 1879 1880 1881 1882 1883 1884
            return ::dsn::ERR_FILE_OPERATION_FAILED;
        }
    }

    uint64_t ci = 0;
    status = chkpt->CreateCheckpointQuick(checkpoint_dir, &ci);
    delete chkpt, chkpt = nullptr;

    if (!status.ok()) {
        derror("%s: async create checkpoint failed, error = %s",
1885
               replica_name(),
1886 1887
               status.ToString().c_str());
        if (!::dsn::utils::filesystem::remove_path(checkpoint_dir)) {
1888
            derror("%s: remove checkpoint directory %s failed", replica_name(), checkpoint_dir);
1889 1890 1891 1892 1893
        }
        return ::dsn::ERR_LOCAL_APP_FAILURE;
    }

    ddebug("%s: copy checkpoint to dir(%s) succeed, last_decree = %" PRId64 "",
1894
           replica_name(),
1895 1896 1897 1898 1899 1900 1901 1902 1903
           checkpoint_dir,
           ci);
    if (checkpoint_decree != nullptr) {
        *checkpoint_decree = static_cast<int64_t>(ci);
    }

    return ::dsn::ERR_OK;
}

Q
qinzuoyan 已提交
1904
::dsn::error_code pegasus_server_impl::get_checkpoint(int64_t learn_start,
1905 1906
                                                      const dsn::blob &learn_request,
                                                      dsn::replication::learn_state &state)
Q
qinzuoyan 已提交
1907 1908 1909 1910 1911
{
    dassert(_is_open, "");

    int64_t ci = last_durable_decree();
    if (ci == 0) {
1912
        derror("%s: no checkpoint found", replica_name());
Q
qinzuoyan 已提交
1913 1914 1915
        return ::dsn::ERR_OBJECT_NOT_FOUND;
    }

1916
    auto chkpt_dir = ::dsn::utils::filesystem::path_combine(data_dir(), chkpt_get_dir_name(ci));
Q
qinzuoyan 已提交
1917 1918
    state.files.clear();
    if (!::dsn::utils::filesystem::get_subfiles(chkpt_dir, state.files, true)) {
1919
        derror("%s: list files in checkpoint dir %s failed", replica_name(), chkpt_dir.c_str());
Q
qinzuoyan 已提交
1920 1921 1922 1923 1924 1925 1926
        return ::dsn::ERR_FILE_OPERATION_FAILED;
    }

    state.from_decree_excluded = 0;
    state.to_decree_included = ci;

    ddebug("%s: get checkpoint succeed, from_decree_excluded = 0, to_decree_included = %" PRId64 "",
1927
           replica_name(),
Q
qinzuoyan 已提交
1928 1929 1930 1931
           state.to_decree_included);
    return ::dsn::ERR_OK;
}

1932 1933 1934
::dsn::error_code
pegasus_server_impl::storage_apply_checkpoint(chkpt_apply_mode mode,
                                              const dsn::replication::learn_state &state)
Q
qinzuoyan 已提交
1935 1936 1937 1938
{
    ::dsn::error_code err;
    int64_t ci = state.to_decree_included;

1939
    if (mode == chkpt_apply_mode::copy) {
Q
qinzuoyan 已提交
1940 1941 1942 1943 1944 1945
        dassert(ci > last_durable_decree(),
                "state.to_decree_included(%" PRId64 ") <= last_durable_decree(%" PRId64 ")",
                ci,
                last_durable_decree());

        auto learn_dir = ::dsn::utils::filesystem::remove_file_name(state.files[0]);
1946
        auto chkpt_dir = ::dsn::utils::filesystem::path_combine(data_dir(), chkpt_get_dir_name(ci));
Q
qinzuoyan 已提交
1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963
        if (::dsn::utils::filesystem::rename_path(learn_dir, chkpt_dir)) {
            ::dsn::utils::auto_lock<::dsn::utils::ex_lock_nr> l(_checkpoints_lock);
            dassert(ci > last_durable_decree(),
                    "%" PRId64 " VS %" PRId64 "",
                    ci,
                    last_durable_decree());
            _checkpoints.push_back(ci);
            if (!_checkpoints.empty()) {
                dassert(ci > _checkpoints.back(),
                        "%" PRId64 " VS %" PRId64 "",
                        ci,
                        _checkpoints.back());
            }
            set_last_durable_decree(ci);
            err = ::dsn::ERR_OK;
        } else {
            derror("%s: rename directory %s to %s failed",
1964
                   replica_name(),
Q
qinzuoyan 已提交
1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975
                   learn_dir.c_str(),
                   chkpt_dir.c_str());
            err = ::dsn::ERR_FILE_OPERATION_FAILED;
        }

        return err;
    }

    if (_is_open) {
        err = stop(true);
        if (err != ::dsn::ERR_OK) {
1976
            derror("%s: close rocksdb %s failed, error = %s", replica_name(), err.to_string());
Q
qinzuoyan 已提交
1977 1978 1979 1980 1981
            return err;
        }
    }

    // clear data dir
1982 1983
    if (!::dsn::utils::filesystem::remove_path(data_dir())) {
        derror("%s: clear data directory %s failed", replica_name(), data_dir().c_str());
Q
qinzuoyan 已提交
1984 1985 1986 1987
        return ::dsn::ERR_FILE_OPERATION_FAILED;
    }

    // reopen the db with the new checkpoint files
1988
    if (state.files.size() > 0) {
Q
qinzuoyan 已提交
1989
        // create data dir
1990 1991
        if (!::dsn::utils::filesystem::create_directory(data_dir())) {
            derror("%s: create data directory %s failed", replica_name(), data_dir().c_str());
Q
qinzuoyan 已提交
1992 1993 1994 1995 1996
            return ::dsn::ERR_FILE_OPERATION_FAILED;
        }

        // move learned files from learn_dir to data_dir/rdb
        std::string learn_dir = ::dsn::utils::filesystem::remove_file_name(state.files[0]);
1997
        std::string new_dir = ::dsn::utils::filesystem::path_combine(data_dir(), "rdb");
Q
qinzuoyan 已提交
1998 1999
        if (!::dsn::utils::filesystem::rename_path(learn_dir, new_dir)) {
            derror("%s: rename directory %s to %s failed",
2000
                   replica_name(),
Q
qinzuoyan 已提交
2001 2002 2003 2004 2005 2006 2007
                   learn_dir.c_str(),
                   new_dir.c_str());
            return ::dsn::ERR_FILE_OPERATION_FAILED;
        }

        err = start(0, nullptr);
    } else {
2008
        ddebug("%s: apply empty checkpoint, create new rocksdb", replica_name());
Q
qinzuoyan 已提交
2009 2010 2011 2012
        err = start(0, nullptr);
    }

    if (err != ::dsn::ERR_OK) {
2013
        derror("%s: open rocksdb failed, error = %s", replica_name(), err.to_string());
Q
qinzuoyan 已提交
2014 2015 2016 2017 2018 2019 2020
        return err;
    }

    dassert(_is_open, "");
    dassert(ci == last_durable_decree(), "%" PRId64 " VS %" PRId64 "", ci, last_durable_decree());

    ddebug("%s: apply checkpoint succeed, last_durable_decree = %" PRId64,
2021
           replica_name(),
Q
qinzuoyan 已提交
2022 2023 2024 2025
           last_durable_decree());
    return ::dsn::ERR_OK;
}

2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079
bool pegasus_server_impl::is_filter_type_supported(::dsn::apps::filter_type::type filter_type)
{
    return filter_type >= ::dsn::apps::filter_type::FT_NO_FILTER &&
           filter_type <= ::dsn::apps::filter_type::FT_MATCH_POSTFIX;
}

bool pegasus_server_impl::validate_filter(::dsn::apps::filter_type::type filter_type,
                                          const ::dsn::blob &filter_pattern,
                                          const ::dsn::blob &value)
{
    if (filter_type == ::dsn::apps::filter_type::FT_NO_FILTER || filter_pattern.length() == 0)
        return true;
    if (value.length() < filter_pattern.length())
        return false;
    switch (filter_type) {
    case ::dsn::apps::filter_type::FT_MATCH_ANYWHERE: {
        // brute force search
        // TODO: improve it according to
        //   http://old.blog.phusion.nl/2010/12/06/efficient-substring-searching/
        const char *a1 = value.data();
        int l1 = value.length();
        const char *a2 = filter_pattern.data();
        int l2 = filter_pattern.length();
        for (int i = 0; i <= l1 - l2; ++i) {
            int j = 0;
            while (j < l2 && a1[i + j] == a2[j])
                ++j;
            if (j == l2)
                return true;
        }
        return false;
    }
    case ::dsn::apps::filter_type::FT_MATCH_PREFIX:
        return (memcmp(value.data(), filter_pattern.data(), filter_pattern.length()) == 0);
    case ::dsn::apps::filter_type::FT_MATCH_POSTFIX:
        return (memcmp(value.data() + value.length() - filter_pattern.length(),
                       filter_pattern.data(),
                       filter_pattern.length()) == 0);
    default:
        dassert(false, "unsupported filter type: %d", filter_type);
    }
    return false;
}

int pegasus_server_impl::append_key_value_for_scan(
    std::vector<::dsn::apps::key_value> &kvs,
    const rocksdb::Slice &key,
    const rocksdb::Slice &value,
    ::dsn::apps::filter_type::type hash_key_filter_type,
    const ::dsn::blob &hash_key_filter_pattern,
    ::dsn::apps::filter_type::type sort_key_filter_type,
    const ::dsn::blob &sort_key_filter_pattern,
    uint32_t epoch_now,
    bool no_value)
Q
qinzuoyan 已提交
2080
{
2081
    if (check_if_record_expired(epoch_now, value)) {
Q
qinzuoyan 已提交
2082
        if (_verbose_log) {
2083
            derror("%s: rocksdb data expired for scan", replica_name());
Q
qinzuoyan 已提交
2084
        }
2085
        return 2;
Q
qinzuoyan 已提交
2086 2087 2088 2089 2090
    }

    ::dsn::apps::key_value kv;

    // extract raw key
2091 2092 2093 2094 2095 2096 2097 2098
    ::dsn::blob raw_key(key.data(), 0, key.size());
    if (hash_key_filter_type != ::dsn::apps::filter_type::FT_NO_FILTER ||
        sort_key_filter_type != ::dsn::apps::filter_type::FT_NO_FILTER) {
        ::dsn::blob hash_key, sort_key;
        pegasus_restore_key(raw_key, hash_key, sort_key);
        if (hash_key_filter_type != ::dsn::apps::filter_type::FT_NO_FILTER &&
            !validate_filter(hash_key_filter_type, hash_key_filter_pattern, hash_key)) {
            if (_verbose_log) {
2099
                derror("%s: hash key filtered for scan", replica_name());
2100 2101 2102 2103 2104 2105
            }
            return 3;
        }
        if (sort_key_filter_type != ::dsn::apps::filter_type::FT_NO_FILTER &&
            !validate_filter(sort_key_filter_type, sort_key_filter_pattern, sort_key)) {
            if (_verbose_log) {
2106
                derror("%s: sort key filtered for scan", replica_name());
2107 2108 2109 2110
            }
            return 3;
        }
    }
2111
    std::shared_ptr<char> key_buf(::dsn::utils::make_shared_array<char>(raw_key.length()));
2112 2113
    ::memcpy(key_buf.get(), raw_key.data(), raw_key.length());
    kv.key.assign(std::move(key_buf), 0, raw_key.length());
Q
qinzuoyan 已提交
2114 2115

    // extract value
2116
    if (!no_value) {
2117
        std::string value_buf(value.data(), value.size());
2118 2119
        pegasus_extract_user_data(_value_schema_version, std::move(value_buf), kv.value);
    }
Q
qinzuoyan 已提交
2120

2121
    kvs.emplace_back(std::move(kv));
2122
    return 1;
Q
qinzuoyan 已提交
2123 2124
}

2125 2126 2127 2128 2129 2130 2131 2132
int pegasus_server_impl::append_key_value_for_multi_get(
    std::vector<::dsn::apps::key_value> &kvs,
    const rocksdb::Slice &key,
    const rocksdb::Slice &value,
    ::dsn::apps::filter_type::type sort_key_filter_type,
    const ::dsn::blob &sort_key_filter_pattern,
    uint32_t epoch_now,
    bool no_value)
Q
qinzuoyan 已提交
2133
{
2134
    if (check_if_record_expired(epoch_now, value)) {
Q
qinzuoyan 已提交
2135
        if (_verbose_log) {
2136
            derror("%s: rocksdb data expired for multi get", replica_name());
Q
qinzuoyan 已提交
2137
        }
2138
        return 2;
Q
qinzuoyan 已提交
2139 2140 2141 2142 2143 2144 2145 2146
    }

    ::dsn::apps::key_value kv;

    // extract sort_key
    ::dsn::blob raw_key(key.data(), 0, key.size());
    ::dsn::blob hash_key, sort_key;
    pegasus_restore_key(raw_key, hash_key, sort_key);
2147 2148 2149
    if (sort_key_filter_type != ::dsn::apps::filter_type::FT_NO_FILTER &&
        !validate_filter(sort_key_filter_type, sort_key_filter_pattern, sort_key)) {
        if (_verbose_log) {
2150
            derror("%s: sort key filtered for multi get", replica_name());
2151 2152 2153
        }
        return 3;
    }
2154
    std::shared_ptr<char> sort_key_buf(::dsn::utils::make_shared_array<char>(sort_key.length()));
Q
qinzuoyan 已提交
2155 2156 2157 2158 2159
    ::memcpy(sort_key_buf.get(), sort_key.data(), sort_key.length());
    kv.key.assign(std::move(sort_key_buf), 0, sort_key.length());

    // extract value
    if (!no_value) {
2160
        std::string value_buf(value.data(), value.size());
Q
qinzuoyan 已提交
2161 2162 2163
        pegasus_extract_user_data(_value_schema_version, std::move(value_buf), kv.value);
    }

2164
    kvs.emplace_back(std::move(kv));
2165
    return 1;
Q
qinzuoyan 已提交
2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195
}

// statistic the count and size of files of this type. return (-1,-1) if failed.
static std::pair<int64_t, int64_t> get_type_file_size(const std::string &path,
                                                      const std::string &type)
{
    std::vector<std::string> files;
    if (!::dsn::utils::filesystem::get_subfiles(path, files, false)) {
        dwarn("get subfiles of dir %s failed", path.c_str());
        return std::pair<int64_t, int64_t>(-1, -1);
    }
    int64_t res = 0;
    int64_t cnt = 0;
    for (auto &f : files) {
        if (f.length() > type.length() && f.substr(f.length() - type.length()) == type) {
            int64_t tsize = 0;
            if (::dsn::utils::filesystem::file_size(f, tsize)) {
                res += tsize;
                cnt++;
            } else {
                dwarn("get size of file %s failed", f.c_str());
                return std::pair<int64_t, int64_t>(-1, -1);
            }
        }
    }
    return std::pair<int64_t, int64_t>(cnt, res);
}

std::pair<int64_t, int64_t> pegasus_server_impl::statistic_sst_size()
{
2196 2197
    // dir = data_dir()/rdb
    return get_type_file_size(::dsn::utils::filesystem::path_combine(data_dir(), "rdb"), ".sst");
Q
qinzuoyan 已提交
2198 2199 2200 2201 2202 2203
}

void pegasus_server_impl::updating_rocksdb_sstsize()
{
    std::pair<int64_t, int64_t> sst_size = statistic_sst_size();
    if (sst_size.first == -1) {
2204
        dwarn("%s: statistic sst file size failed", replica_name());
Q
qinzuoyan 已提交
2205 2206 2207 2208
    } else {
        int64_t sst_size_mb = sst_size.second / 1048576;
        ddebug("%s: statistic sst file size succeed, sst_count = %" PRId64 ", sst_size = %" PRId64
               "(%" PRId64 "MB)",
2209
               replica_name(),
Q
qinzuoyan 已提交
2210 2211 2212
               sst_size.first,
               sst_size.second,
               sst_size_mb);
2213 2214
        _pfc_sst_count->set(sst_size.first);
        _pfc_sst_size->set(sst_size_mb);
Q
qinzuoyan 已提交
2215 2216
    }
}
C
cailiuyang 已提交
2217

2218 2219
std::pair<std::string, bool>
pegasus_server_impl::get_restore_dir_from_env(const std::map<std::string, std::string> &env_kvs)
C
cailiuyang 已提交
2220 2221
{
    std::pair<std::string, bool> res;
2222 2223 2224
    std::stringstream os;
    os << "restore.";

2225
    auto it = env_kvs.find(ROCKSDB_ENV_RESTORE_FORCE_RESTORE);
C
cailiuyang 已提交
2226
    if (it != env_kvs.end()) {
2227
        ddebug("%s: found %s in envs", replica_name(), ROCKSDB_ENV_RESTORE_FORCE_RESTORE.c_str());
C
cailiuyang 已提交
2228 2229 2230
        res.second = true;
    }

2231
    it = env_kvs.find(ROCKSDB_ENV_RESTORE_POLICY_NAME);
C
cailiuyang 已提交
2232
    if (it != env_kvs.end()) {
2233 2234 2235 2236
        ddebug("%s: found %s in envs: %s",
               replica_name(),
               ROCKSDB_ENV_RESTORE_POLICY_NAME.c_str(),
               it->second.c_str());
C
cailiuyang 已提交
2237 2238 2239 2240
        os << it->second << ".";
    } else {
        return res;
    }
2241

2242
    it = env_kvs.find(ROCKSDB_ENV_RESTORE_BACKUP_ID);
C
cailiuyang 已提交
2243
    if (it != env_kvs.end()) {
2244 2245 2246 2247
        ddebug("%s: found %s in envs: %s",
               replica_name(),
               ROCKSDB_ENV_RESTORE_BACKUP_ID.c_str(),
               it->second.c_str());
C
cailiuyang 已提交
2248 2249 2250 2251
        os << it->second;
    } else {
        return res;
    }
2252

2253
    std::string parent_dir = ::dsn::utils::filesystem::remove_file_name(data_dir());
C
cailiuyang 已提交
2254 2255 2256
    res.first = ::dsn::utils::filesystem::path_combine(parent_dir, os.str());
    return res;
}
A
acelyc111 已提交
2257

2258
void pegasus_server_impl::update_app_envs(const std::map<std::string, std::string> &envs)
A
acelyc111 已提交
2259
{
2260 2261 2262
    update_usage_scenario(envs);
    _manual_compact_svc.start_manual_compact_if_needed(envs);
}
2263

2264 2265 2266
void pegasus_server_impl::query_app_envs(/*out*/ std::map<std::string, std::string> &envs)
{
    envs[ROCKSDB_ENV_USAGE_SCENARIO_KEY] = _usage_scenario;
2267 2268
}

2269
void pegasus_server_impl::update_usage_scenario(const std::map<std::string, std::string> &envs)
2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380
{
    // update usage scenario
    // if not specified, default is normal
    auto find = envs.find(ROCKSDB_ENV_USAGE_SCENARIO_KEY);
    std::string new_usage_scenario =
        (find != envs.end() ? find->second : ROCKSDB_ENV_USAGE_SCENARIO_NORMAL);
    if (new_usage_scenario != _usage_scenario) {
        std::string old_usage_scenario = _usage_scenario;
        if (set_usage_scenario(new_usage_scenario)) {
            ddebug("%s: update app env[%s] from %s to %s succeed",
                   replica_name(),
                   ROCKSDB_ENV_USAGE_SCENARIO_KEY.c_str(),
                   old_usage_scenario.c_str(),
                   new_usage_scenario.c_str());
        } else {
            derror("%s: update app env[%s] from %s to %s failed",
                   replica_name(),
                   ROCKSDB_ENV_USAGE_SCENARIO_KEY.c_str(),
                   old_usage_scenario.c_str(),
                   new_usage_scenario.c_str());
        }
    }
}

bool pegasus_server_impl::set_usage_scenario(const std::string &usage_scenario)
{
    if (usage_scenario == _usage_scenario)
        return false;
    std::unordered_map<std::string, std::string> new_options;
    if (usage_scenario == ROCKSDB_ENV_USAGE_SCENARIO_NORMAL ||
        usage_scenario == ROCKSDB_ENV_USAGE_SCENARIO_PREFER_WRITE) {
        if (_usage_scenario == ROCKSDB_ENV_USAGE_SCENARIO_BULK_LOAD) {
            // old usage scenario is bulk load, reset first
            new_options["level0_file_num_compaction_trigger"] =
                boost::lexical_cast<std::string>(_db_opts.level0_file_num_compaction_trigger);
            new_options["level0_slowdown_writes_trigger"] =
                boost::lexical_cast<std::string>(_db_opts.level0_slowdown_writes_trigger);
            new_options["level0_stop_writes_trigger"] =
                boost::lexical_cast<std::string>(_db_opts.level0_stop_writes_trigger);
            new_options["soft_pending_compaction_bytes_limit"] =
                boost::lexical_cast<std::string>(_db_opts.soft_pending_compaction_bytes_limit);
            new_options["hard_pending_compaction_bytes_limit"] =
                boost::lexical_cast<std::string>(_db_opts.hard_pending_compaction_bytes_limit);
            new_options["disable_auto_compactions"] = "false";
            new_options["max_compaction_bytes"] =
                boost::lexical_cast<std::string>(_db_opts.max_compaction_bytes);
            new_options["write_buffer_size"] =
                boost::lexical_cast<std::string>(_db_opts.write_buffer_size);
            new_options["max_write_buffer_number"] =
                boost::lexical_cast<std::string>(_db_opts.max_write_buffer_number);
        }
        if (usage_scenario == ROCKSDB_ENV_USAGE_SCENARIO_NORMAL) {
            new_options["level0_file_num_compaction_trigger"] =
                boost::lexical_cast<std::string>(_db_opts.level0_file_num_compaction_trigger);
        } else {
            new_options["level0_file_num_compaction_trigger"] =
                boost::lexical_cast<std::string>(_db_opts.level0_file_num_compaction_trigger * 2);
        }
    } else if (usage_scenario == ROCKSDB_ENV_USAGE_SCENARIO_BULK_LOAD) {
        // refer to Options::PrepareForBulkLoad()
        new_options["level0_file_num_compaction_trigger"] = "1000000000";
        new_options["level0_slowdown_writes_trigger"] = "1000000000";
        new_options["level0_stop_writes_trigger"] = "1000000000";
        new_options["soft_pending_compaction_bytes_limit"] = "0";
        new_options["hard_pending_compaction_bytes_limit"] = "0";
        new_options["disable_auto_compactions"] = "true";
        new_options["max_compaction_bytes"] =
            boost::lexical_cast<std::string>(static_cast<uint64_t>(1) << 60);
        new_options["write_buffer_size"] = boost::lexical_cast<std::string>(
            std::max(_db_opts.write_buffer_size, (size_t)(256 * 1024 * 1024)));
        new_options["max_write_buffer_number"] =
            boost::lexical_cast<std::string>(std::max(_db_opts.max_write_buffer_number, 6));
    } else {
        derror("%s: invalid usage scenario: %s", replica_name(), usage_scenario.c_str());
        return false;
    }
    if (set_options(new_options)) {
        _usage_scenario = usage_scenario;
        ddebug("%s: set usage scenario to %s succeed", replica_name(), usage_scenario.c_str());
        return true;
    } else {
        derror("%s: set usage scenario to %s failed", replica_name(), usage_scenario.c_str());
        return false;
    }
}

bool pegasus_server_impl::set_options(
    const std::unordered_map<std::string, std::string> &new_options)
{
    std::ostringstream oss;
    int i = 0;
    for (auto &kv : new_options) {
        if (i > 0)
            oss << ",";
        oss << kv.first << "=" << kv.second;
        i++;
    }
    rocksdb::Status status = _db->SetOptions(new_options);
    if (status == rocksdb::Status::OK()) {
        ddebug("%s: rocksdb set options returns %s: {%s}",
               replica_name(),
               status.ToString().c_str(),
               oss.str().c_str());
        return true;
    } else {
        derror("%s: rocksdb set options returns %s: {%s}",
               replica_name(),
               status.ToString().c_str(),
               oss.str().c_str());
        return false;
    }
A
acelyc111 已提交
2381
}
2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413

uint64_t pegasus_server_impl::do_manual_compact(const rocksdb::CompactRangeOptions &options)
{
    uint64_t start_time;
    rocksdb::Status status;

    // wait flush before compact to make all data compacted.
    ddebug_replica("start to Flush");
    start_time = dsn_now_ms();
    status = _db->Flush(rocksdb::FlushOptions());
    ddebug_replica("Flush finished, status = {}, time_used = {}ms",
                   status.ToString().c_str(),
                   dsn_now_ms() - start_time);

    ddebug_replica("start to CompactRange, target_level = {}, bottommost_level_compaction = {}",
                   options.target_level,
                   options.bottommost_level_compaction == rocksdb::BottommostLevelCompaction::kForce
                       ? "force"
                       : "skip");
    start_time = dsn_now_ms();
    status = _db->CompactRange(options, nullptr, nullptr);
    ddebug_replica("CompactRange finished, status = {}, time_used = {}ms",
                   status.ToString().c_str(),
                   dsn_now_ms() - start_time);

    return _db->GetLastManualCompactFinishTime();
}

std::string pegasus_server_impl::query_compact_state() const
{
    return _manual_compact_svc.query_compact_state();
}
2414 2415 2416

} // namespace server
} // namespace pegasus