Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
#include <unistd.h>
 
#include "dgrid_config.h"
#include "dgrid_logger.h"
#include "dgrid_client.h"
#include "dgridd_node_arbiter.h"
 
namespace DGrid {
 
DGriddNodeArbiter::DGriddNodeArbiter() :DGriddThread() {}
DGriddNodeArbiter::~DGriddNodeArbiter() {}
 
bool DGriddNodeArbiter::start()
{
    std::string cluster_key = Config::instance()->get_cluster_key();
    if(Config::instance()->get("standalone", 0) > 0) {
        writeLog(LOG_WARNING, "Standalone mode: ignoring nodes, disabling arbiter");
        redundancy_level = 1;
        return false;
    }
    if(cluster_key.empty()) {
        writeLog(LOG_WARNING, "Cluster key not defined: ignoring nodes, disabling arbiter");
        redundancy_level = 1;
        return false;
    }
    reconnect_interval = Config::instance()->get("node_reconnect", 10);
    redundancy_level = Config::instance()->get("redundancy_level", 1);
 
    // creating node clients
    for(auto node: Config::instance()->getnodes()) {
        bool enabled = atoi(node.at("enabled").c_str());
        std::string node_name = node.at("name");
        std::string node_addr = node.at("addr");
        uint16_t    node_port = atoi(node.at("port").c_str());
        if(enabled && !node_addr.empty() && node_port) {
            writeLog(LOG_INFO, "Creating node client %s:%d for node '%s'", node_addr.c_str(), node_port, node_name.c_str());
            DGridNodeClient* node = new DGridNodeClient();
            node->setEventHandler([this] (std::shared_ptr<DGridEvent> e)->void { this->pushEvent(e); });
            node->setName(node_name);
            node->setAuthData(cluster_key);
            node->openConnection(node_addr, node_port);
            if(node->authState() == AUTH_STATE_FAILED) {
                writeLog(LOG_ERR, "Node '%s' auth failed - cluster key missmatch, disabling.", node_name.c_str());
            } else {
                node_clients.insert(node);
            }
        }
    }
    if(node_clients.size()) {
        return DGriddThread::start();
    } else {
        writeLog(LOG_WARNING, "No enabled nodes in config found, disabling arbiter");
        return false;
    }
}
 
void DGriddNodeArbiter::stop()
{
    DGriddThread::stop();
    for(DGridNodeClient* node: node_clients) {
        node->closeConnection_nowait();
    }
    for(DGridNodeClient* node: node_clients) {
        delete node;
    }
    node_clients.clear();
}
 
void DGriddNodeArbiter::pushEvent(std::shared_ptr<DGridEvent> e)
{
    std::lock_guard<std::mutex> lock(equeue_mutex);
    equeue.push(e);
}
 
std::shared_ptr<DGridEvent> DGriddNodeArbiter::popEvent()
{
    std::lock_guard<std::mutex> lock(equeue_mutex);
    if(equeue.size()) {
        std::shared_ptr<DGridEvent> e = equeue.front();
        equeue.pop();
        return e;
    }
    return nullptr;
}
 
void DGriddNodeArbiter::processEvents()
{
    std::shared_ptr<DGridEvent> e;
    while(e = popEvent()) {
        eventHandler(e);
    }
}
 
void DGriddNodeArbiter::eventHandler(std::shared_ptr<DGridEvent> e)
{
    writeLog(LOG_DEBUG, "event: %s (%s)", eventType2string(e->type).c_str(), e->message.c_str());
    DGridNodeClient* node = dynamic_cast<DGridNodeClient*>((DGridNodeClient*)e->sender);
    switch(e->type) {
        case ConnectionClosed: {
            NodeID id = node->getID();
            if(id.size()) {
                writeLog(LOG_NOTICE, "Node '%s' %s lost", node->name().c_str(), raw_to_hexstring(id).c_str());
                nodes_lost[node] = id;
                nodes_active.erase(id);
                node->resetID();
            }
            break;
        }
        case ConnectionEstablished: {
            NodeID id = node->getID();
            writeLog(LOG_NOTICE, "Node '%s' %s connected", node->name().c_str(), raw_to_hexstring(id).c_str());
            nodes_active.insert(std::pair<NodeID, DGridNodeClient*>(id, node));
            auto n = nodes_lost.find(node);
            if(n != nodes_lost.end()) {
                if(id == n->second) {
                    writeLog(LOG_NOTICE, "Node '%s' %s alive again", node->name().c_str(), raw_to_hexstring(n->second).c_str());
                } else if(id.size()) {
                    writeLog(LOG_NOTICE, "Node '%s' %s restarted, new id: %s",
                        node->name().c_str(),
                        raw_to_hexstring(n->second).c_str(),
                        raw_to_hexstring(id).c_str());
                    nodes_dead.insert(n->second);
                    nodes_lost.erase(node);
                } else {
                    writeLog(LOG_WARNING, "Node '%s' (was %s) reports empty ID", node->name().c_str(), raw_to_hexstring(n->second).c_str());
                }
            }
            break;
        }
        default:
            break;
    }
}
 
void DGriddNodeArbiter::checkConnections()
{
    // check all connections
    for(DGridNodeClient* node: node_clients) {
        if(!node->isRunning() && !node->isConnected()) {
            writeLog(LOG_DEBUG, "Reconnecting node '%s'...", node->name().c_str());
            node->reconnect();
        }
    }
}
 
void DGriddNodeArbiter::showStats()
{
    writeLog(LOG_INFO, "> Known nodes: %d", node_clients.size());
    writeLog(LOG_INFO, "       active: %d", nodes_active.size());
    writeLog(LOG_INFO, "         lost: %d", nodes_lost.size());
    writeLog(LOG_INFO, "         dead: %d", nodes_dead.size());
    for(DGridNodeClient* node: node_clients) {
        bool up = node->isConnected();
        writeLog(LOG_INFO, "  %s: %s", node->name().c_str(), up ? "UP" : "DOWN");
        if(up) {
            NodeLoadData d;
            if (DGRID_OK == node->get_load(d)) {
                writeLog(LOG_INFO, "    ID: %s", raw_to_hexstring(d.node_id).c_str());
                writeLog(LOG_INFO, "    keys: %d", d.keys_count);
            }
        }
    }
}
 
uint16_t DGriddNodeArbiter::activeNodesCount()
{
    int16_t cnt=0;
    for(DGridNodeClient* node: node_clients) {
        if(node->isConnected())
            cnt++;
    }
    return cnt;
}
 
uint16_t DGriddNodeArbiter::knownNodesCount()
{
    return node_clients.size();
}
 
DGridNodeClient* DGriddNodeArbiter::getNode(const NodeID& id)
{
    auto it = nodes_active.find(id);
    if(it != nodes_active.end())
        return it->second;
    return nullptr;
}
 
void DGriddNodeArbiter::run()
{
    writeLog(LOG_INFO, "DGriddNodeArbiter %d nodes, reconnect_interval = %d", node_clients.size(), reconnect_interval);
    int32_t check_interval_cur = reconnect_interval * 10;
    while(!hasStopReq()) {
        usleep(100000);
        check_interval_cur--;
        if(check_interval_cur < 0) {
            checkConnections();
            check_interval_cur = reconnect_interval * 10;
        }
        processEvents();
    }
    writeLog(LOG_INFO, "DGriddNodeArbiter finished");
}
 
// data requests
DGridResult DGriddNodeArbiter::get_theme_simple(const std::string& session, const std::string& theme_name, SimpleValueMap& data, const NodeID& old_source)
{
    // check old source first
    if(!old_source.empty() && old_source != Config::node_id()) {
        DGridNodeClient *node = getNode(old_source);
        if(nullptr != node && DGRID_OK == node->get_theme_simple(session, theme_name, data)) {
            return DGRID_OK;
        }
        writeLog(LOG_WARNING, "Owner (%s) unavailable now!", raw_to_hexstring(old_source).c_str());
    }
    // check other nodes
    for(DGridNodeClient* node: node_clients) {
        if(node->isConnected()) {
            if((old_source.empty() || old_source == node->getID())
                && DGRID_OK == node->get_theme_simple(session, theme_name, data))
                return DGRID_OK;
        }
    }
    return DGRID_NOT_FOUND;
}
 
DGridResult DGriddNodeArbiter::notify_old_source(const std::string& session, const std::string& theme_name, const SimpleValueMap& data, const NodeID& old_source)
{
    if(!old_source.empty() && old_source != Config::node_id()) {
        DGridNodeClient* node = getNode(old_source);
        if(node != nullptr) {
            DGridResult r = node->append_theme_simple(session, theme_name, data);
            if(DGRID_OK != r) {
                writeLog(LOG_DEBUG, "Error sending data to another owner: %s", DGridResultString(r).c_str());
            }
            return r;
        }
        writeLog(LOG_WARNING, "Owner (%s) unavailable now!", raw_to_hexstring(old_source).c_str());
        return DGRID_NOT_FOUND;
    }
    return DGRID_INVALID_ARGUMENT;
}
 
DGridResult DGriddNodeArbiter::append_theme_simple(const std::string& session, const std::string& theme_name, const SimpleValueMap& data, const NodeID& old_source)
{
    DGridResult r = DGRID_NOT_ENOUGH_NODES;
    // additional checks for data consistency
    uint16_t check_cnt_needed = old_source.empty() ? knownNodesCount() - redundancy_level : 0;
    // redundancy_level includes current node, so start from 1
    uint16_t checked_cnt(1);
    bool old_source_notified(false);
    NodeID another_source;
 
    // notify old source
    if (DGRID_OK == notify_old_source(session, theme_name, data, old_source))
        checked_cnt++;
 
    for(DGridNodeClient* node: node_clients) {
        if(node->isConnected()) {
            // skip old source, it should be already notified (if online)
            if(checked_cnt < redundancy_level) {
                if(old_source != node->getID()
                        && DGRID_OK == node->append_theme_simple(session, theme_name, data, another_source)) {
                    checked_cnt++;
                    if (!another_source.empty()) {
                        if(node->getID() == another_source) {
                            old_source_notified = true;
                        } else {
                            writeLog(LOG_DEBUG, "Another owner found (%s), have to notify it", raw_to_hexstring(another_source).c_str());
                            if(DGRID_OK == notify_old_source(session, theme_name, data, another_source)) {
                                old_source_notified = true;
                            }
                        }
                    }
                }
            } else if(checked_cnt < check_cnt_needed && old_source.empty()) {
                // search another source if key is new
                SimpleValueMap data_tmp = data;
                DGridResult r = node->get_theme_simple(session, theme_name, data_tmp);
                checked_cnt++;
                if(DGRID_OK == r && !data_tmp.empty()) {
                    // another instance found
                    another_source = data_tmp.begin()->second.source_node;
                    if(!another_source.empty() && another_source != Config::node_id()) {
                        writeLog(LOG_DEBUG, "Another owner found (%s), have to notify it", raw_to_hexstring(another_source).c_str());
                        if(DGRID_OK == notify_old_source(session, theme_name, data, another_source)) {
                            old_source_notified = true;
                        }
                    }
                }
            }
        }
    }
 
    if (checked_cnt < redundancy_level) {
        writeLog(LOG_WARNING, "Not enough active nodes for redundancy_level=%d", redundancy_level);
    } else {
        r = DGRID_OK;
    }
    return r;
}
 
DGridResult DGriddNodeArbiter::sync_theme_simple(const std::string& session, const std::string& theme_name, SimpleValueMap& data)
{
    SimpleValueMap tmp_data;
    SimpleValueMap ret_data;
    for(DGridNodeClient* node: node_clients) {
        if(node->isConnected()) {
            tmp_data = data;
            if(DGRID_OK == node->sync_theme_simple(session, theme_name, tmp_data)) {
                for(auto& it: tmp_data) {
                    ret_data[it.first] = it.second;
                }
            }
        }
    }
    data = ret_data;
    return DGRID_OK;
}
 
DGridResult DGriddNodeArbiter::table__get_master_node(const TableFullID& full_id, TableID& table_id, NodeID& master_id)
{
    for(DGridNodeClient* node: node_clients) {
        if(node->isConnected() && DGRID_OK == node->table_check_exists(full_id, table_id, master_id)) {
            if(full_id.id.empty()) {
                writeLog(LOG_DEBUG, "Table '%s/%s/%s' found as '%s' on node '%s', master '%s'",
                        full_id.session.c_str(), full_id.space.c_str(), full_id.name.c_str(),
                        raw_to_hexstring(table_id).c_str(), raw_to_hexstring(node->getID()).c_str(),
                        raw_to_hexstring(master_id).c_str());
            } else {
                writeLog(LOG_DEBUG, "Table '%s' found on node '%s', master '%s'",
                        raw_to_hexstring(table_id).c_str(), raw_to_hexstring(node->getID()).c_str(),
                        raw_to_hexstring(master_id).c_str());
            }
            return DGRID_OK;
        }
    }
    return DGRID_NOT_FOUND;  
}
 
DGridResult DGriddNodeArbiter::table__choose_fallback_nodes(std::vector<NodeID>& nodes)
{
    nodes.clear();
    // TODO: нужен более умный выбор нод для балансировки
    for(DGridNodeClient* node: node_clients) {
        if(node->isConnected())
            nodes.push_back(node->getID());
        if(nodes.size()+1 >= redundancy_level)
            return DGRID_OK;
    }
    return DGRID_NOT_ENOUGH_NODES;
}
 
DGridResult DGriddNodeArbiter::table__request_passthru(const NodeID& node_id,
        const RequestType type, const RequestSubType subtype, const std::vector<char>& payload,
        std::vector<char>& response)
{
    DGridNodeClient* node = getNode(node_id);
    if(nullptr == node) {
        writeLog(LOG_ERR, "Requested node ID invalid: %s", raw_to_hexstring(node_id).c_str());
        return DGRID_INVALID_ARGUMENT;
    }
    return node->table_request_passthru(type, subtype, payload, response);
}
 
} // namespace DGrid