DataStoreImpl.hpp 21 KB
Newer Older
Matthieu Dorier's avatar
Matthieu Dorier committed
1 2 3 4 5
/*
 * (C) 2018 The University of Chicago
 * 
 * See COPYRIGHT in top-level directory.
 */
6 7 8
#ifndef __HEPNOS_PRIVATE_DATASTORE_IMPL
#define __HEPNOS_PRIVATE_DATASTORE_IMPL

9
#include <vector>
10
#include <unordered_set>
Matthieu Dorier's avatar
Matthieu Dorier committed
11
#include <unordered_map>
12 13 14 15 16 17 18
#include <functional>
#include <iostream>
#include <yaml-cpp/yaml.h>
#include <sdskv-client.h>
#include <bake-client.h>
#include <ch-placement.h>
#include "KeyTypes.hpp"
Matthieu Dorier's avatar
Matthieu Dorier committed
19
#include "ValueTypes.hpp"
20 21 22 23 24 25 26 27 28 29 30 31 32
#include "hepnos/Exception.hpp"
#include "hepnos/DataStore.hpp"
#include "hepnos/DataSet.hpp"

namespace hepnos {

////////////////////////////////////////////////////////////////////////////////////////////
// DataStore::Impl implementation
////////////////////////////////////////////////////////////////////////////////////////////

class DataStore::Impl {
    public:

Matthieu Dorier's avatar
Matthieu Dorier committed
33 34 35 36 37 38 39 40 41 42 43
    margo_instance_id                         m_mid;          // Margo instance
    std::unordered_map<std::string,hg_addr_t> m_addrs;        // Addresses used by the service
    sdskv_client_t                            m_sdskv_client; // SDSKV client
    bake_client_t                             m_bake_client;  // BAKE client
    std::vector<sdskv_provider_handle_t>      m_sdskv_ph;     // list of SDSKV provider handlers
    std::vector<sdskv_database_id_t>          m_sdskv_db;     // list of SDSKV database ids
    struct ch_placement_instance*             m_chi_sdskv;    // ch-placement instance for SDSKV
    std::vector<bake_provider_handle_t>       m_bake_ph;      // list of BAKE provider handlers
    std::vector<bake_target_id_t>             m_bake_targets; // list of BAKE target ids
    struct ch_placement_instance*             m_chi_bake;     // ch-placement instance for BAKE
    const DataStore::iterator                 m_end;          // iterator for the end() of the DataStore
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

    Impl(DataStore* parent)
    : m_mid(MARGO_INSTANCE_NULL)
    , m_sdskv_client(SDSKV_CLIENT_NULL)
    , m_chi_sdskv(nullptr)
    , m_bake_client(BAKE_CLIENT_NULL)
    , m_chi_bake(nullptr)
    , m_end() {}

    void init(const std::string& configFile) {
        int ret;
        hg_return_t hret;
        YAML::Node config = YAML::LoadFile(configFile);
        checkConfig(config);
        // get protocol
        std::string proto = config["hepnos"]["client"]["protocol"].as<std::string>();
        // initialize Margo
        m_mid = margo_init(proto.c_str(), MARGO_CLIENT_MODE, 0, 0);
        if(!m_mid) {
            cleanup();
            throw Exception("Could not initialized Margo");
        }
        // initialize SDSKV client
        ret = sdskv_client_init(m_mid, &m_sdskv_client);
        if(ret != SDSKV_SUCCESS) {
            cleanup();
            throw Exception("Could not create SDSKV client");
        }
        // initialize BAKE client
        ret = bake_client_init(m_mid, &m_bake_client);
        if(ret != 0) {
            cleanup();
            throw Exception("Could not create BAKE client");
        }
        // create list of sdskv provider handles
        YAML::Node sdskv = config["hepnos"]["providers"]["sdskv"];
        for(YAML::const_iterator it = sdskv.begin(); it != sdskv.end(); it++) {
            std::string str_addr = it->first.as<std::string>();
            hg_addr_t addr;
Matthieu Dorier's avatar
Matthieu Dorier committed
83 84 85 86 87 88 89 90 91 92
            if(m_addrs.count(str_addr) != 0) {
                addr = m_addrs[str_addr];
            } else {
                hret = margo_addr_lookup(m_mid, str_addr.c_str(), &addr);
                if(hret != HG_SUCCESS) {
                    margo_addr_free(m_mid,addr);
                    cleanup();
                    throw Exception("margo_addr_lookup failed");
                }
                m_addrs[str_addr] = addr;
93
            }
Matthieu Dorier's avatar
Matthieu Dorier committed
94
            // get the provider id(s)
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
            if(it->second.IsScalar()) {
                uint16_t provider_id = it->second.as<uint16_t>();
                sdskv_provider_handle_t ph;
                ret = sdskv_provider_handle_create(m_sdskv_client, addr, provider_id, &ph);
                if(ret != SDSKV_SUCCESS) {
                    cleanup();
                    throw Exception("sdskv_provider_handle_create failed");
                }
                m_sdskv_ph.push_back(ph);
            } else if(it->second.IsSequence()) {
                for(YAML::const_iterator pid = it->second.begin(); pid != it->second.end(); pid++) {
                    uint16_t provider_id = pid->second.as<uint16_t>();
                    sdskv_provider_handle_t ph;
                    ret = sdskv_provider_handle_create(m_sdskv_client, addr, provider_id, &ph);
                    if(ret != SDSKV_SUCCESS) {
                        cleanup();
                        throw Exception("sdskv_provider_handle_create failed");
                    }
                    m_sdskv_ph.push_back(ph);
                }
            }
        }
        // loop over sdskv providers and get the database id
        for(auto ph : m_sdskv_ph) {
            sdskv_database_id_t db_id;
            ret = sdskv_open(ph, "hepnosdb", &db_id);
            if(ret != SDSKV_SUCCESS) {
                cleanup();
                throw Exception("sdskv_open failed to open database");
            }
            m_sdskv_db.push_back(db_id);
        }
        // initialize ch-placement for the SDSKV providers
        m_chi_sdskv = ch_placement_initialize("hash_lookup3", m_sdskv_ph.size(), 4, 0);
Matthieu Dorier's avatar
Matthieu Dorier committed
129

130 131
        // get list of bake provider handles
        YAML::Node bake = config["hepnos"]["providers"]["bake"];
Matthieu Dorier's avatar
Matthieu Dorier committed
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
        if(bake) {
            for(YAML::const_iterator it = bake.begin(); it != bake.end(); it++) {
                // get the address of a bake provider
                std::string str_addr = it->first.as<std::string>();
                hg_addr_t addr;
                if(m_addrs.count(str_addr) != 0) {
                    addr = m_addrs[str_addr];
                } else {
                    // lookup the address
                    hret = margo_addr_lookup(m_mid, str_addr.c_str(), &addr);
                    if(hret != HG_SUCCESS) {
                        margo_addr_free(m_mid, addr);
                        cleanup();
                        throw Exception("margo_addr_lookup failed");
                    }
                    m_addrs[str_addr] = addr;
148
                }
Matthieu Dorier's avatar
Matthieu Dorier committed
149 150
                if(it->second.IsScalar()) {
                    uint16_t provider_id = it->second.as<uint16_t>();
151 152 153 154 155 156 157
                    bake_provider_handle_t ph;
                    ret = bake_provider_handle_create(m_bake_client, addr, provider_id, &ph);
                    if(ret != 0) {
                        cleanup();
                        throw Exception("bake_provider_handle_create failed");
                    }
                    m_bake_ph.push_back(ph);
Matthieu Dorier's avatar
Matthieu Dorier committed
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
                } else if(it->second.IsSequence()) {
                    for(YAML::const_iterator pid = it->second.begin(); pid != it->second.end(); pid++) {
                        uint16_t provider_id = pid->second.as<uint16_t>();
                        bake_provider_handle_t ph;
                        ret = bake_provider_handle_create(m_bake_client, addr, provider_id, &ph);
                        if(ret != 0) {
                            cleanup();
                            throw Exception("bake_provider_handle_create failed");
                        }
                        m_bake_ph.push_back(ph);
                    }
                } // if(it->second.IsSequence())
            } // for loop
            // find out the bake targets at each bake provider
            for(auto& bake_ph : m_bake_ph) {
                bake_target_id_t bti;
                uint64_t num_targets = 0;
                ret = bake_probe(bake_ph, 1, &bti, &num_targets);
                if(ret != BAKE_SUCCESS) {
                    throw Exception("bake_probe failed to retrieve targets");
                }
                if(num_targets != 1) {
                    throw Exception("bake_prove returned no target");
181
                }
Matthieu Dorier's avatar
Matthieu Dorier committed
182
                m_bake_targets.push_back(bti);
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
            }
        }
        // initialize ch-placement for the bake providers
        if(m_bake_ph.size()) {
            m_chi_bake = ch_placement_initialize("hash_lookup3", m_bake_ph.size(), 4, 0);
        }
    }

    void cleanup() {
        for(auto ph : m_sdskv_ph) {
            sdskv_provider_handle_release(ph);
        }
        for(auto ph : m_bake_ph) {
            bake_provider_handle_release(ph);
        }
        sdskv_client_finalize(m_sdskv_client);
        bake_client_finalize(m_bake_client);
        if(m_chi_sdskv)
            ch_placement_finalize(m_chi_sdskv);
        if(m_chi_bake)
            ch_placement_finalize(m_chi_bake);
Matthieu Dorier's avatar
Matthieu Dorier committed
204 205 206
        for(auto& addr : m_addrs) {
            margo_addr_free(m_mid, addr.second);
        }
207 208 209 210 211 212
        if(m_mid) margo_finalize(m_mid);
    }

    private:

    static void checkConfig(YAML::Node& config) {
Matthieu Dorier's avatar
Matthieu Dorier committed
213
        // config file starts with hepnos entry
214 215 216 217
        auto hepnosNode = config["hepnos"];
        if(!hepnosNode) {
            throw Exception("\"hepnos\" entry not found in YAML file");
        }
Matthieu Dorier's avatar
Matthieu Dorier committed
218
        // hepnos entry has client entry
219 220 221 222
        auto clientNode = hepnosNode["client"];
        if(!clientNode) {
            throw Exception("\"client\" entry not found in \"hepnos\" section");
        }
Matthieu Dorier's avatar
Matthieu Dorier committed
223
        // client entry has protocol entry
224 225 226 227
        auto protoNode = clientNode["protocol"];
        if(!protoNode) {
            throw Exception("\"protocol\" entry not found in \"client\" section");
        }
Matthieu Dorier's avatar
Matthieu Dorier committed
228
        // hepnos entry has providers entry
229 230 231 232
        auto providersNode = hepnosNode["providers"];
        if(!providersNode) {
            throw Exception("\"providers\" entry not found in \"hepnos\" section");
        }
Matthieu Dorier's avatar
Matthieu Dorier committed
233
        // provider entry has sdskv entry
234 235 236 237
        auto sdskvNode = providersNode["sdskv"];
        if(!sdskvNode) {
            throw Exception("\"sdskv\" entry not found in \"providers\" section");
        }
Matthieu Dorier's avatar
Matthieu Dorier committed
238
        // sdskv entry is not empty
239 240 241
        if(sdskvNode.size() == 0) {
            throw Exception("No provider found in \"sdskv\" section");
        }
Matthieu Dorier's avatar
Matthieu Dorier committed
242
        // for each sdskv entry
243 244 245
        for(auto it = sdskvNode.begin(); it != sdskvNode.end(); it++) {
            if(it->second.IsScalar()) continue; // one provider id given
            if(it->second.IsSequence()) { // array of provider ids given
Matthieu Dorier's avatar
Matthieu Dorier committed
246
                // the sequence is not empty
247 248 249
                if(it->second.size() == 0) {
                    throw Exception("Empty array of provider ids encountered in \"sdskv\" section");
                }
Matthieu Dorier's avatar
Matthieu Dorier committed
250 251
                // all objects in the sequence are scalar and appear only once
                std::unordered_set<uint16_t> ids;
252 253 254 255
                for(auto pid = it->second.begin(); pid != it->second.end(); pid++) {
                    if(!pid->second.IsScalar()) {
                        throw Exception("Non-scalar provider id encountered in \"sdskv\" section");
                    }
Matthieu Dorier's avatar
Matthieu Dorier committed
256 257 258 259 260
                    uint16_t pid_int = pid->as<uint16_t>();
                    if(ids.count(pid_int) != 0) {
                        throw Exception("Provider id encountered twice in \"sdskv\" section");
                    }
                    ids.insert(pid_int);
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
                }
            } else {
                throw Exception("Invalid value type for provider in \"sdskv\" section");
            }
        }
        // bake providers are not mandatory. If they are not present,
        // objects will be stored in sdskv providers.
        auto bakeNode = providersNode["bake"];
        if(!bakeNode) return;
        if(bakeNode.size() == 0) return;
        for(auto it = bakeNode.begin(); it != bakeNode.end(); it++) {
            if(it->second.IsScalar()) continue; // one provider id given
            if(it->second.IsSequence()) { // array of provider ids given
                if(it->second.size() == 0) {
                    throw Exception("No provider found in \"bake\" section");
                }
Matthieu Dorier's avatar
Matthieu Dorier committed
277
                std::unordered_set<uint16_t> ids;
278 279 280 281
                for(auto pid = it->second.begin(); pid != it->second.end(); pid++) {
                    if(!pid->second.IsScalar()) {
                        throw Exception("Non-scalar provider id encountered in \"bake\" section");
                    }
Matthieu Dorier's avatar
Matthieu Dorier committed
282 283 284 285 286
                    uint16_t pid_int = pid->as<uint16_t>();
                    if(ids.count(pid_int) != 0) {
                        throw Exception("Provider id encountered twice in \"bake\" section");
                    }
                    ids.insert(pid_int);
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
                }
            } else {
                throw Exception("Invalid value type for provider in \"bake\" section");
            }
        }
    }

    public:

    bool load(uint8_t level, const std::string& containerName,
            const std::string& objectName, std::vector<char>& data) const {
        int ret;
        // build full name
        std::stringstream ss;
        if(!containerName.empty())
            ss << containerName << "/";
        ss << objectName;
        // hash the name to get the provider id
Matthieu Dorier's avatar
Matthieu Dorier committed
305 306
        long unsigned sdskv_provider_idx = 0;
        uint64_t name_hash;
307
        if(level != 0) {
Matthieu Dorier's avatar
Matthieu Dorier committed
308
            name_hash = std::hash<std::string>()(containerName);
309
        } else {
310
            // use the complete name for final objects (level 0)
Matthieu Dorier's avatar
Matthieu Dorier committed
311
            name_hash = std::hash<std::string>()(ss.str());
312
        }
Matthieu Dorier's avatar
Matthieu Dorier committed
313
        ch_placement_find_closest(m_chi_sdskv, name_hash, 1, &sdskv_provider_idx);
314 315
        // make corresponding datastore entry
        DataStoreEntryPtr entry = make_datastore_entry(level, ss.str());
Matthieu Dorier's avatar
Matthieu Dorier committed
316 317
        auto sdskv_ph = m_sdskv_ph[sdskv_provider_idx];
        auto db_id = m_sdskv_db[sdskv_provider_idx];
318
        // read the value
Matthieu Dorier's avatar
Matthieu Dorier committed
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
        if(level != 0 || m_bake_ph.empty()) { // read directly from sdskv
            
            // find the size of the value, as a way to check if the key exists
            hg_size_t vsize;
            ret = sdskv_length(sdskv_ph, db_id, entry->raw(), entry->length(), &vsize);
            if(ret == SDSKV_ERR_UNKNOWN_KEY) {
                return false;
            }
            if(ret != SDSKV_SUCCESS) {
                throw Exception("Error occured when calling sdskv_length");
            }

            data.resize(vsize);
            ret = sdskv_get(sdskv_ph, db_id, entry->raw(), entry->length(), data.data(), &vsize);
            if(ret != SDSKV_SUCCESS) {
                throw Exception("Error occured when calling sdskv_get");
            }

        } else { // read from BAKE

            // first get the key/val from sdskv
            DataStoreValue rid_info;
            hg_size_t vsize = sizeof(rid_info);
            ret = sdskv_get(sdskv_ph, db_id, entry->raw(), entry->length(), (void*)(&rid_info), &vsize);
            if(ret == SDSKV_ERR_UNKNOWN_KEY) {
                return false;
            }
            if(ret != SDSKV_SUCCESS) {
                throw Exception("Error occured when calling sdskv_get");
            }
            if(vsize != sizeof(rid_info)) {
                throw Exception("Call to sdskv_get returned a value of unexpected size");
            }
            // now read the data from bake
            data.resize(rid_info.getDataSize());
            if(data.size() == 0) return true;
            long unsigned bake_provider_idx = 0;
            ch_placement_find_closest(m_chi_bake, name_hash, 1, &bake_provider_idx);
            auto bake_ph = m_bake_ph[bake_provider_idx];
            auto target = m_bake_targets[bake_provider_idx];
            uint64_t bytes_read = 0;
            ret = bake_read(bake_ph, rid_info.getBakeRegionID(), 0, data.data(), data.size(), &bytes_read);
            if(ret != BAKE_SUCCESS) {
                throw Exception("Couldn't read region from BAKE");
            }
            if(bytes_read != rid_info.getDataSize()) {
                throw Exception("Bytes read from BAKE did not match expected object size");
            }
367 368 369 370 371 372 373 374 375 376 377 378
        }
        return true;
    }

    bool store(uint8_t level, const std::string& containerName,
            const std::string& objectName, const std::vector<char>& data) {
        // build full name
        std::stringstream ss;
        if(!containerName.empty())
            ss << containerName << "/";
        ss << objectName;
        // hash the name to get the provider id
Matthieu Dorier's avatar
Matthieu Dorier committed
379 380
        long unsigned sdskv_provider_idx = 0;
        uint64_t name_hash;
381
        if(level != 0) {
Matthieu Dorier's avatar
Matthieu Dorier committed
382
            name_hash = std::hash<std::string>()(containerName);
383 384
        } else {
            // use the complete name for final objects (level 0)
Matthieu Dorier's avatar
Matthieu Dorier committed
385
            name_hash = std::hash<std::string>()(ss.str());
386
        }
Matthieu Dorier's avatar
Matthieu Dorier committed
387 388
        ch_placement_find_closest(m_chi_sdskv, name_hash, 1, &sdskv_provider_idx);
        // make corresponding datastore entry key
389
        DataStoreEntryPtr entry = make_datastore_entry(level, ss.str());
Matthieu Dorier's avatar
Matthieu Dorier committed
390 391
        auto sdskv_ph = m_sdskv_ph[sdskv_provider_idx];
        auto db_id = m_sdskv_db[sdskv_provider_idx];
392 393
        // check if the key exists
        hg_size_t vsize;
Matthieu Dorier's avatar
Matthieu Dorier committed
394
        int ret = sdskv_length(sdskv_ph, db_id, entry->raw(), entry->length(), &vsize);
395 396 397 398
        if(ret == HG_SUCCESS) return false; // key already exists
        if(ret != SDSKV_ERR_UNKNOWN_KEY) { // there was a problem with sdskv
            throw Exception("Could not check if key exists in SDSKV (sdskv_length error)");
        }
Matthieu Dorier's avatar
Matthieu Dorier committed
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
        // if it's not a last-level data entry (data product), store in sdskeyval
        if(level != 0 || m_bake_ph.empty()) {
            ret = sdskv_put(sdskv_ph, db_id, entry->raw(), entry->length(), data.data(), data.size());
            if(ret != SDSKV_SUCCESS) {
                throw Exception("Could not put key/value pair in SDSKV (sdskv_put error)");
            }
        } else { // store data in bake
            long unsigned bake_provider_idx = 0;
            ch_placement_find_closest(m_chi_bake, name_hash, 1, &bake_provider_idx);
            auto bake_ph = m_bake_ph[bake_provider_idx];
            auto target = m_bake_targets[bake_provider_idx];
            bake_region_id_t rid;
            ret = bake_create_write_persist(bake_ph, target, data.data(), data.size(), &rid);
            if(ret != BAKE_SUCCESS) {
                throw Exception("Could not create bake region (bake_create_write_persist error)");
            }
            // create Value to put in SDSKV
            DataStoreValue value(data.size(), bake_provider_idx, rid);
            ret = sdskv_put(sdskv_ph, db_id, entry->raw(), entry->length(), (void*)(&value), sizeof(value));
            if(ret != SDSKV_SUCCESS) {
                ret = bake_remove(bake_ph, rid);
                if(ret != BAKE_SUCCESS) {
                    throw Exception("Dude, not only did SDSKV fail to put the key, but I couldn't cleanup BAKE. Is it Friday 13?");
                }
                throw Exception("Could not put key/value pair in SDSKV (sdskv_put error)");
            }
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
        }
        return true;
    }

    size_t nextKeys(uint8_t level, const std::string& containerName,
            const std::string& lower,
            std::vector<std::string>& keys, size_t maxKeys) const {
        int ret;
        if(level == 0) return 0; // cannot iterate at object level
        // build full name from lower bound key
        std::stringstream ss;
        if(!containerName.empty())
            ss << containerName << "/";
        ss << lower;
        // hash the name to get the provider id
        long unsigned provider_idx = 0;
        uint64_t h = std::hash<std::string>()(containerName);
        ch_placement_find_closest(m_chi_sdskv, h, 1, &provider_idx);
        // make an entry for the lower bound
        DataStoreEntryPtr lb_entry = make_datastore_entry(level, ss.str());
        // create data structures to receive keys
        std::vector<DataStoreEntryPtr> keys_ent;
        std::vector<void*>             keys_ptr(maxKeys);
        std::vector<hg_size_t>         keys_len(maxKeys);
        for(unsigned i=0; i < maxKeys; i++) {
            keys_ent.push_back(make_datastore_entry(level, 1024));
            keys_ptr[i] = keys_ent[i]->raw();
            keys_len[i] = sizeof(DataStoreEntry) + 1024;
        }
        // get provider and database
        auto ph = m_sdskv_ph[provider_idx];
        auto db_id = m_sdskv_db[provider_idx];
        // issue an sdskv_list_keys
        hg_size_t max_keys = maxKeys;
        ret = sdskv_list_keys(ph, db_id, lb_entry->raw(), lb_entry->length(),
                keys_ptr.data(), keys_len.data(), &max_keys);
        if(ret != HG_SUCCESS) {
            throw Exception("Error occured when calling sdskv_list_keys");
        }
        unsigned i = max_keys - 1;
        if(max_keys == 0) return 0;
        // remove keys that don't have the same level or the same prefix
        std::string prefix = containerName + "/";
        keys.resize(0);
        for(unsigned i = 0; i < max_keys; i++) {
            if(keys_ent[i]->m_level != level) {
                max_keys = i;
                break;
            }
            if(!containerName.empty()) {
                size_t lenpre = prefix.size();
                size_t lenstr = strlen(keys_ent[i]->m_fullname);
                if(lenstr < lenpre) {
                    max_keys = i;
                    break;
                }
                if(strncmp(prefix.c_str(), keys_ent[i]->m_fullname, lenpre) != 0) {
                    max_keys = i;
                    break;
                }
            }
            keys.push_back(keys_ent[i]->m_fullname);
        }
        // set the resulting keys
        return max_keys;
    }
};

}
494 495

#endif