#include <fstream>
|
#include <uuid/uuid.h>
|
|
#include "dgrid_logger.h"
|
#include "dgrid_config.h"
|
|
namespace DGrid {
|
|
Config* Config::_instance = nullptr;
|
NodeID Config::_node_id;
|
|
Config::Config() {}
|
Config::~Config() {}
|
|
Config* Config::instance()
|
{
|
if (nullptr == _instance) {
|
_instance = new Config();
|
}
|
return _instance;
|
}
|
|
void Config::destroy_instance()
|
{
|
if(nullptr != _instance) {
|
delete _instance;
|
_instance = nullptr;
|
}
|
}
|
|
NodeID Config::node_id()
|
{
|
if(_node_id.empty()) {
|
_node_id.resize(16);
|
uuid_generate(reinterpret_cast<unsigned char*>(_node_id.data()));
|
writeLog(LOG_INFO, "Current node ID: %s", raw_to_hexstring(_node_id).c_str() );
|
}
|
return _node_id;
|
}
|
|
bool Config::load(const std::string& fname)
|
{
|
int line_num(0);
|
int node_idx(-1);
|
std::ifstream cfile(fname);
|
std::string group;
|
std::string::size_type pos, first, last;
|
std::string key, val;
|
|
if(!cfile.is_open()) {
|
writeLog(LOG_WARNING, "Can't open config file '%s'", fname.c_str());
|
return false;
|
}
|
writeLog(LOG_INFO, "Reading config '%s'", fname.c_str());
|
|
for(std::string line; std::getline(cfile, line); line_num++) {
|
if(std::string::npos != (pos = line.find("#"))) {
|
line = line.substr(0, pos);
|
}
|
line = strtrim(line);
|
if(line.empty())
|
continue;
|
// writeLog(LOG_DEBUG, "%s", line.c_str());
|
|
if(std::string::npos != (first = line.find_first_of("[")) &&
|
std::string::npos != (last = line.find_last_of("]"))) {
|
group = to_lower_case(strtrim(line.substr(first+1, last - first - 1)));
|
if("node" == group) {
|
node_idx++;
|
nodes.resize(node_idx+1);
|
}
|
}
|
|
if(std::string::npos != (pos = line.find("="))) {
|
key = strtrim(line.substr(0, pos));
|
val = strtrim(line.substr(pos + 1));
|
|
if(key.empty()) {
|
writeLog(LOG_WARNING, "Error in config file at line %d", line_num);
|
continue;
|
}
|
|
if("common" == group) {
|
common[key] = val;
|
} else if("node" == group) {
|
nodes[node_idx][key] = val;
|
}
|
}
|
}
|
|
writeLog(LOG_DEBUG, "Local settings:");
|
for(auto p: common) {
|
writeLog(LOG_DEBUG, "\t'%s' = '%s'", p.first.c_str(), p.second.c_str());
|
}
|
writeLog(LOG_DEBUG, "Known nodes:");
|
for(auto p: nodes) {
|
writeLog(LOG_DEBUG, "\t'%s'@%s:%d", p["name"].c_str(), p["addr"].c_str(), std::stoi(p["port"]));
|
}
|
cfile.close();
|
return true;
|
}
|
|
std::string Config::get_cluster_key() const
|
{
|
return get("cluster_key");
|
}
|
|
std::string Config::get(const std::string& key, const std::string& default_value) const
|
{
|
auto it = common.find(key);
|
if(it == common.end())
|
return default_value;
|
return it->second;
|
}
|
|
uint16_t Config::get(const std::string& key, const uint16_t value) const
|
{
|
return atoi(get(key, std::to_string(value)).c_str());
|
}
|
|
const std::vector<stringmap>& Config::getnodes() const
|
{
|
return nodes;
|
}
|
|
void Config::clear() {
|
common.clear();
|
nodes.clear();
|
}
|
|
} // namespace DGrid
|