sdskv-benchmark.cc 20.3 KB
Newer Older
Matthieu Dorier's avatar
Matthieu Dorier committed
1
#include <iostream>
2
#include <iomanip>
Matthieu Dorier's avatar
Matthieu Dorier committed
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
#include <cmath>
#include <algorithm>
#include <numeric>
#include <fstream>
#include <map>
#include <functional>
#include <memory>
#include <mpi.h>
#include <json/json.h>
#include <sdskv-client.hpp>
#include <sdskv-server.hpp>

using RemoteDatabase = sdskv::database;

/**
 * Helper function to generate random strings of a certain length.
 * These strings are readable.
 */
static std::string gen_random_string(size_t len) {
    static const char alphanum[] =
        "0123456789"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz";
    std::string s(len, ' ');
    for (unsigned i = 0; i < len; ++i) {
        s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
    }
    return s;
}

template<typename T>
class BenchmarkRegistration;

/**
 * The AbstractBenchmark class describes an interface that a benchmark object
 * needs to satisfy. This interface has a setup, execute, and teardown
 * methods. AbstractBenchmark also acts as a factory to create concrete instances.
 */
class AbstractBenchmark {

    MPI_Comm        m_comm;      // communicator gathering all clients
    RemoteDatabase& m_remote_db; // remote database

    template<typename T>
    friend class BenchmarkRegistration;

    using benchmark_factory_function = std::function<
        std::unique_ptr<AbstractBenchmark>(Json::Value&, MPI_Comm, RemoteDatabase&)>;
    static std::map<std::string, benchmark_factory_function> s_benchmark_factories;

    protected:

    RemoteDatabase& remoteDatabase() { return m_remote_db; }
    const RemoteDatabase& remoteDatabase() const { return m_remote_db; }
    MPI_Comm comm() const { return m_comm; }

    public:

    AbstractBenchmark(MPI_Comm c, RemoteDatabase& rdb)
    : m_comm(c)
    , m_remote_db(rdb) {}

    virtual ~AbstractBenchmark() = default;
    virtual void setup()    = 0;
    virtual void execute()  = 0;
    virtual void teardown() = 0;

    /**
     * @brief Factory function used to create benchmark instances.
     */
    template<typename ... T>
    static std::unique_ptr<AbstractBenchmark> create(const std::string& type, T&& ... args) {
        auto it = s_benchmark_factories.find(type);
        if(it == s_benchmark_factories.end())
            throw std::invalid_argument(type+" benchmark type unknown");
        return (it->second)(std::forward<T>(args)...);
    }
};

/**
 * @brief The mechanism bellow is used to provide the REGISTER_BENCHMARK macro,
 * which registers a child class of AbstractBenchmark and allows AbstractBenchmark::create("type", ...)
 * to return an instance of this concrete child class.
 */
template<typename T>
class BenchmarkRegistration {
    public:
    BenchmarkRegistration(const std::string& type) {
        AbstractBenchmark::s_benchmark_factories[type] = 
            [](Json::Value& config, MPI_Comm comm, RemoteDatabase& rdb) {
                return std::make_unique<T>(config, comm, rdb);
        };
    }
};

std::map<std::string, AbstractBenchmark::benchmark_factory_function> AbstractBenchmark::s_benchmark_factories;

#define REGISTER_BENCHMARK(__name, __class) \
    static BenchmarkRegistration<__class> __class##_registration(__name)

103 104
class AbstractAccessBenchmark : public AbstractBenchmark {
    
Matthieu Dorier's avatar
Matthieu Dorier committed
105 106 107 108 109 110 111 112 113 114
    protected:

    uint64_t                  m_num_entries = 0;
    std::pair<size_t, size_t> m_key_size_range;
    std::pair<size_t, size_t> m_val_size_range;
    bool                      m_erase_on_teardown;

    public:

    template<typename ... T>
115
    AbstractAccessBenchmark(Json::Value& config, T&& ... args)
Matthieu Dorier's avatar
Matthieu Dorier committed
116 117 118 119 120
    : AbstractBenchmark(std::forward<T>(args)...) {
        // read the configuration
        m_num_entries = config["num-entries"].asUInt64();
        if(config["key-sizes"].isIntegral()) {
            auto x = config["key-sizes"].asUInt64();
121
            m_key_size_range = { x, x+1 };
Matthieu Dorier's avatar
Matthieu Dorier committed
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
        } else if(config["key-sizes"].isArray() && config["key-sizes"].size() == 2) {
            auto x = config["key-sizes"][0].asUInt64();
            auto y = config["key-sizes"][1].asUInt64();
            if(x > y) throw std::range_error("invalid key-sizes range");
            m_key_size_range = { x, y };
        } else {
            throw std::range_error("invalid key-sizes range or value");
        }
        if(config["val-sizes"].isIntegral()) {
            auto x = config["val-sizes"].asUInt64();
            m_val_size_range = { x, x+1 };
        } else if(config["val-sizes"].isArray() && config["val-sizes"].size() == 2) {
            auto x = config["val-sizes"][0].asUInt64();
            auto y = config["val-sizes"][1].asUInt64();
            if(x >= y) throw std::range_error("invalid val-sizes range");
            m_val_size_range = { x, y };
        } else {
            throw std::range_error("invalid val-sizes range or value");
        }
        m_erase_on_teardown = config["erase-on-teardown"].asBool();
    }
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
};

/**
 * PutBenchmark executes a series of PUT operations and measures their duration.
 */
class PutBenchmark : public AbstractAccessBenchmark {

    protected:

    std::vector<std::string>  m_keys;
    std::vector<std::string>  m_vals;

    public:

    template<typename ... T>
    PutBenchmark(T&& ... args)
    : AbstractAccessBenchmark(std::forward<T>(args)...) { }
Matthieu Dorier's avatar
Matthieu Dorier committed
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216

    virtual void setup() override {
        // generate key/value pairs and store them in the local
        m_keys.reserve(m_num_entries);
        m_vals.reserve(m_num_entries);
        for(unsigned i=0; i < m_num_entries; i++) {
            size_t ksize = m_key_size_range.first + (rand() % (m_key_size_range.second - m_key_size_range.first));
            m_keys.push_back(gen_random_string(ksize));
            size_t vsize = m_val_size_range.first + (rand() % (m_val_size_range.second - m_val_size_range.first));
            m_vals.push_back(gen_random_string(vsize));
        }
    }

    virtual void execute() override {
        // execute PUT operations
        auto& db = remoteDatabase();
        for(unsigned i=0; i < m_num_entries; i++) {
            auto& key = m_keys[i];
            auto& val = m_vals[i];
            db.put(key, val);
        }
    }

    virtual void teardown() override {
        if(m_erase_on_teardown) {
            // erase all the keys from the database
            auto& db = remoteDatabase();
            for(unsigned i=0; i < m_num_entries; i++) {
                db.erase(m_keys[i]);
            }
        }
        // erase keys and values from the local vectors
        m_keys.resize(0);
        m_vals.resize(0);
    }
};
REGISTER_BENCHMARK("put", PutBenchmark);

/**
 * PutMultiBenchmark inherites from PutBenchmark and does the same but
 * executes a PUT-MULTI instead of a PUT.
 */
class PutMultiBenchmark : public PutBenchmark {
    
    public:

    template<typename ... T>
    PutMultiBenchmark(T&& ... args)
    : PutBenchmark(std::forward<T>(args)...) {}

    virtual void execute() override {
        auto& db = remoteDatabase();
        db.put(m_keys, m_vals);
    }
};
REGISTER_BENCHMARK("put-multi", PutMultiBenchmark);

217 218 219
/**
 * GetBenchmark executes a series of GET operations and measures their duration.
 */
220
class GetBenchmark : public AbstractAccessBenchmark {
221 222 223 224 225 226 227 228 229

    protected:

    std::vector<std::string>  m_keys;
    std::vector<std::string>  m_vals;

    public:

    template<typename ... T>
230 231
    GetBenchmark(T&& ... args)
    : AbstractAccessBenchmark(std::forward<T>(args)...) {}
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297

    virtual void setup() override {
        // generate key/value pairs and store them in the local
        m_keys.reserve(m_num_entries);
        m_vals.reserve(m_num_entries);
        for(unsigned i=0; i < m_num_entries; i++) {
            size_t ksize = m_key_size_range.first + (rand() % (m_key_size_range.second - m_key_size_range.first));
            m_keys.push_back(gen_random_string(ksize));
            size_t vsize = m_val_size_range.first + (rand() % (m_val_size_range.second - m_val_size_range.first));
            m_vals.push_back(gen_random_string(vsize));
        }
        // execute PUT operations (not part of the measure)
        auto& db = remoteDatabase();
        for(unsigned i=0; i < m_num_entries; i++) {
            auto& key = m_keys[i];
            auto& val = m_vals[i];
            db.put(key, val);
        }
    }

    virtual void execute() override {
        // execute GET operations
        auto& db = remoteDatabase();
        std::string val(m_val_size_range.second-1, 0);
        for(unsigned i=0; i < m_num_entries; i++) {
            auto& key = m_keys[i];
            db.get(key, val);
            val.resize(m_val_size_range.second-1, 0);
        }
    }

    virtual void teardown() override {
        if(m_erase_on_teardown) {
            // erase all the keys from the database
            auto& db = remoteDatabase();
            for(unsigned i=0; i < m_num_entries; i++) {
                db.erase(m_keys[i]);
            }
        }
        // erase keys and values from the local vectors
        m_keys.resize(0);
        m_vals.resize(0);
    }
};
REGISTER_BENCHMARK("get", GetBenchmark);

/**
 * GetMultiBenchmark inherites from GetBenchmark and does the same but
 * executes a GET-MULTI instead of a GET.
 */
class GetMultiBenchmark : public GetBenchmark {
    
    public:

    template<typename ... T>
    GetMultiBenchmark(T&& ... args)
    : GetBenchmark(std::forward<T>(args)...) {}

    virtual void execute() override {
        auto& db = remoteDatabase();
        std::vector<std::string> vals(m_num_entries, std::string(m_val_size_range.second-1, 0));
        db.get(m_keys, vals);
    }
};
REGISTER_BENCHMARK("get-multi", GetMultiBenchmark);

298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
/**
 * LengthBenchmark executes a series of LENGTH operations and measures their duration.
 */
class LengthBenchmark : public AbstractAccessBenchmark {

    protected:

    std::vector<std::string>  m_keys;
    std::vector<std::string>  m_vals;

    public:

    template<typename ... T>
    LengthBenchmark(T&& ... args)
    : AbstractAccessBenchmark(std::forward<T>(args)...) {}

    virtual void setup() override {
        // generate key/value pairs and store them in the local
        m_keys.reserve(m_num_entries);
        m_vals.reserve(m_num_entries);
        for(unsigned i=0; i < m_num_entries; i++) {
            size_t ksize = m_key_size_range.first + (rand() % (m_key_size_range.second - m_key_size_range.first));
            m_keys.push_back(gen_random_string(ksize));
            size_t vsize = m_val_size_range.first + (rand() % (m_val_size_range.second - m_val_size_range.first));
            m_vals.push_back(gen_random_string(vsize));
        }
        // execute PUT operations (not part of the measure)
        auto& db = remoteDatabase();
        for(unsigned i=0; i < m_num_entries; i++) {
            auto& key = m_keys[i];
            auto& val = m_vals[i];
            db.put(key, val);
        }
    }

    virtual void execute() override {
        // execute LENGTH operations
        auto& db = remoteDatabase();
        for(unsigned i=0; i < m_num_entries; i++) {
            auto& key = m_keys[i];
            db.length(key);
        }
    }

    virtual void teardown() override {
        if(m_erase_on_teardown) {
            // erase all the keys from the database
            auto& db = remoteDatabase();
            for(unsigned i=0; i < m_num_entries; i++) {
                db.erase(m_keys[i]);
            }
        }
        // erase keys and values from the local vectors
        m_keys.resize(0);
        m_vals.resize(0);
    }
};
REGISTER_BENCHMARK("length", LengthBenchmark);

/**
 * LengthMultiBenchmark inherites from LengthBenchmark and does the same but
 * executes a LENGTH-MULTI instead of a LENGTH.
 */
class LengthMultiBenchmark : public LengthBenchmark {
    
    public:

    template<typename ... T>
    LengthMultiBenchmark(T&& ... args)
    : LengthBenchmark(std::forward<T>(args)...) {}

    virtual void execute() override {
        auto& db = remoteDatabase();
        std::vector<hg_size_t> sizes(m_num_entries); 
        db.length(m_keys, sizes);
    }
};
REGISTER_BENCHMARK("length-multi", LengthMultiBenchmark);

Matthieu Dorier's avatar
Matthieu Dorier committed
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
static void run_server(MPI_Comm comm, Json::Value& config);
static void run_client(MPI_Comm comm, Json::Value& config);
static sdskv_db_type_t database_type_from_string(const std::string& type);

/**
 * @brief Main function.
 */
int main(int argc, char** argv) {

    MPI_Init(&argc, &argv);
    int rank, size;
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);

    if(argc != 2) {
        if(rank == 0) {
            std::cerr << "Usage: " << argv[0] << " <config.json>" << std::endl;
            MPI_Abort(MPI_COMM_WORLD, -1);
        }
    }

    std::ifstream config_file(argv[1]);
    if(!config_file.good() && rank == 0) {
        std::cerr << "Could not read configuration file " << argv[1] << std::endl;
        MPI_Abort(MPI_COMM_WORLD, -1);
    }

    Json::Reader reader;
    Json::Value config;
    reader.parse(config_file, config);

    MPI_Comm comm;
    MPI_Comm_split(MPI_COMM_WORLD, rank == 0 ? 0 : 1, rank, &comm);

    if(rank == 0) {
        run_server(comm, config);
    } else {
        run_client(comm, config);
    }

    MPI_Finalize();
    return 0;
}

static void run_server(MPI_Comm comm, Json::Value& config) {
    // initialize Margo
    margo_instance_id mid = MARGO_INSTANCE_NULL;
    std::string protocol = config["protocol"].asString();
    auto& server_config = config["server"];
    bool use_progress_thread = server_config["use-progress-thread"].asBool();
    int  rpc_thread_count = server_config["rpc-thread-count"].asInt();
    mid = margo_init(protocol.c_str(), MARGO_SERVER_MODE, use_progress_thread, rpc_thread_count);
    margo_enable_remote_shutdown(mid);
    // serialize server address
    std::vector<char> server_addr_str(256,0);
    hg_size_t buf_size = 256;
    hg_addr_t server_addr = HG_ADDR_NULL;
    margo_addr_self(mid, &server_addr);
    margo_addr_to_string(mid, server_addr_str.data(), &buf_size, server_addr);
    margo_addr_free(mid, server_addr);
    // send server address to client
    MPI_Bcast(&buf_size, sizeof(hg_size_t), MPI_BYTE, 0, MPI_COMM_WORLD);
    MPI_Bcast(server_addr_str.data(), buf_size, MPI_BYTE, 0, MPI_COMM_WORLD);
    // initialize sdskv provider
    auto provider = sdskv::provider::create(mid);
    // initialize database
    auto& database_config = server_config["database"];
    std::string db_name = database_config["name"].asString();
    std::string db_path = database_config["path"].asString();
    sdskv_db_type_t db_type = database_type_from_string(database_config["type"].asString());
    sdskv_config_t db_config = {
        .db_name = db_name.c_str(),
        .db_path = db_path.c_str(),
        .db_type = db_type,
        .db_comp_fn_name = nullptr,
        .db_no_overwrite = 0
    };
    provider->attach_database(db_config);
    // notify clients that the database is ready
    MPI_Barrier(MPI_COMM_WORLD);
    // wait for finalize
    margo_wait_for_finalize(mid);
}

static void run_client(MPI_Comm comm, Json::Value& config) {
    // get info from communicator
    int rank, num_clients;
    MPI_Comm_rank(comm, &rank);
    MPI_Comm_size(comm, &num_clients);
    Json::StyledStreamWriter styledStream;
    // initialize Margo
    margo_instance_id mid = MARGO_INSTANCE_NULL;
    std::string protocol = config["protocol"].asString();
    mid = margo_init(protocol.c_str(), MARGO_SERVER_MODE, 0, 0);
    // receive server address
    std::vector<char> server_addr_str;
    hg_size_t buf_size;
    hg_addr_t server_addr = HG_ADDR_NULL;
    MPI_Bcast(&buf_size, sizeof(hg_size_t), MPI_BYTE, 0, MPI_COMM_WORLD);
    server_addr_str.resize(buf_size, 0);
    MPI_Bcast(server_addr_str.data(), buf_size, MPI_BYTE, 0, MPI_COMM_WORLD);
    margo_addr_lookup(mid, server_addr_str.data(), &server_addr);
    // wait for server to have initialize the database
    MPI_Barrier(MPI_COMM_WORLD);
    {
        // open remote database
        sdskv::client client(mid);
        sdskv::provider_handle ph(client, server_addr);
        std::string db_name = config["server"]["database"]["name"].asString();
        RemoteDatabase db = client.open(ph, db_name);
        // initialize the RNG seed
        int seed = config["seed"].asInt();
        // initialize benchmark instances
        std::vector<std::unique_ptr<AbstractBenchmark>> benchmarks;
        std::vector<unsigned> repetitions;
        std::vector<std::string> types;
        benchmarks.reserve(config["benchmarks"].size());
        repetitions.reserve(config["benchmarks"].size());
        types.reserve(config["benchmarks"].size());
        for(auto& bench_config : config["benchmarks"]) {
            std::string type = bench_config["type"].asString();
            types.push_back(type);
            benchmarks.push_back(AbstractBenchmark::create(type, bench_config, comm, db));
            repetitions.push_back(bench_config["repetitions"].asUInt());
        }
        // main execution loop
        for(unsigned i = 0; i < benchmarks.size(); i++) {
            auto& bench  = benchmarks[i];
            unsigned rep = repetitions[i];
            // reset the RNG
            srand(seed + rank);
            std::vector<double> local_timings(rep);
            for(unsigned j = 0; j < rep; j++) {
                MPI_Barrier(comm);
                // benchmark setup
                bench->setup();
                MPI_Barrier(comm);
                // benchmark execution
                double t_start = MPI_Wtime();
                bench->execute();
                double t_end = MPI_Wtime();
                local_timings[j] = t_end - t_start;
                MPI_Barrier(comm);
                // teardown
                bench->teardown();
            }
            // exchange timings
            std::vector<double> global_timings(rep*num_clients);
            if(num_clients != 1) {
                MPI_Gather(local_timings.data(), local_timings.size(), MPI_DOUBLE,
                       global_timings.data(), local_timings.size(), MPI_DOUBLE, 0, comm);
            } else {
                std::copy(local_timings.begin(), local_timings.end(), global_timings.begin());
            }
            // print report
            if(rank == 0) {
                size_t n = global_timings.size();
                std::cout << "================ " << types[i] << " ================" << std::endl;
                styledStream.write(std::cout, config["benchmarks"][i]);
                std::cout << "-----------------" << std::string(types[i].size(),'-') << "-----------------" << std::endl;
                double average  = std::accumulate(global_timings.begin(), global_timings.end(), 0.0) / n;
                double variance = std::accumulate(global_timings.begin(), global_timings.end(), 0.0, [average](double acc, double x) {
                        return acc + std::pow((x - average),2);
                    });
                variance /= n;
                double stddev = std::sqrt(variance);
                std::sort(global_timings.begin(), global_timings.end());
                double min = global_timings[0];
                double max = global_timings[global_timings.size()-1];
                double median = (n % 2) ? global_timings[n/2] : ((global_timings[n/2] + global_timings[n/2 + 1])/2.0);
                double q1 = global_timings[n/4];
                double q3 = global_timings[(3*n)/4];
549
                std::cout << std::setprecision(9) << std::fixed;
Matthieu Dorier's avatar
Matthieu Dorier committed
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
                std::cout << "Repetitions     : " << n << std::endl;
                std::cout << "Average(sec)    : " << average << std::endl;
                std::cout << "Variance(sec^2) : " << variance << std::endl;
                std::cout << "StdDev(sec)     : " << stddev << std::endl;
                std::cout << "Minimum(sec)    : " << min << std::endl;
                std::cout << "Q1(sec)         : " << q1 << std::endl;
                std::cout << "Median(sec)     : " << median << std::endl;
                std::cout << "Q3(sec)         : " << q3 << std::endl;
                std::cout << "Maximum(sec)    : " << max << std::endl;
            }
        }
        // wait for all the clients to be done with their tasks
        MPI_Barrier(comm);
        // shutdown server and finalize margo
        if(rank == 0)
            margo_shutdown_remote_instance(mid, server_addr);
    }
    margo_addr_free(mid, server_addr);
    margo_finalize(mid);
}

static sdskv_db_type_t database_type_from_string(const std::string& type) {
    if(type == "map") {
        return KVDB_MAP;
    } else if(type == "leveldb" || type == "ldb") {
        return KVDB_LEVELDB;
    } else if(type == "berkeleydb" || type == "bdb") {
        return KVDB_BERKELEYDB;
    }
    throw std::runtime_error(std::string("Unknown database type \"") + type + "\"");
}