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
366
367
368
369
370
371
372
373
374
375
376
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 | // Copyright (C) 2018-2024 Internet Systems Consortium, Inc. ("ISC")
//
// This Source Code Form is subject to the terms of the Kea Hooks Basic
// Commercial End User License Agreement v2.0. See COPYING file in the premium/
// directory.
#include <config.h>
#include <legal_log_db_log.h><--- Include file: not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <mysql_legal_log.h><--- Include file: not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <dhcpsrv/timer_mgr.h>
#include <util/multi_threading_mgr.h>
#include <boost/array.hpp><--- Include file: not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <boost/static_assert.hpp><--- Include file: not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <mysqld_error.h><--- Include file: not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <iomanip><--- Include file: not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <limits.h><--- Include file: not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <sstream><--- Include file: not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <string><--- Include file: not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <time.h><--- Include file: not found. Please note: Cppcheck does not need standard library headers to get proper results.
using namespace isc;
using namespace isc::db;
using namespace isc::dhcp;
using namespace isc::legal_log;
using namespace isc::util;
using namespace std;
namespace {
boost::array<TaggedStatement, MySqlStore::NUM_STATEMENTS>
tagged_statements = { {
{MySqlStore::INSERT_LOG,
"INSERT INTO logs(address, log) VALUES (?, ?)"},
}
};
};
namespace isc {
namespace legal_log {
/// @brief Supports exchanging log entries with MySQL.
class MySqlLegLExchange {
/// @brief Set number of database columns for this log structure
static const size_t LOG_COLUMNS = 2;
public:
/// @brief Constructor
///
/// The initialization of the variables here is only to satisfy cppcheck -
/// all variables are initialized/set in the methods before they are used.
MySqlLegLExchange() : addr_(""), log_(""),
addr_length_(0), addr_null_(MLM_FALSE) {
std::fill(&error_[0], &error_[LOG_COLUMNS], MLM_FALSE);
// Set the column names (for error messages)
columns_[0] = "address";
columns_[1] = "log";
BOOST_STATIC_ASSERT(1 < LOG_COLUMNS);
}
/// @brief Destructor
~MySqlLegLExchange() = default;
/// @brief Set error indicators
///
/// Sets the error indicator for each of the MYSQL_BIND elements. It points
/// the "error" field within an element of the input array to the
/// corresponding element of the passed error array.
///
/// @param bind Array of BIND elements
/// @param error Array of error elements. If there is an error in getting
/// data associated with one of the "bind" elements, the
/// corresponding element in the error array is set to MLM_TRUE.
/// @param count Size of each of the arrays.
static void setErrorIndicators(MYSQL_BIND* bind, my_bool* error,
size_t count) {
for (size_t i = 0; i < count; ++i) {
error[i] = MLM_FALSE;
bind[i].error = reinterpret_cast<my_bool*>(&error[i]);
}
}
/// @brief Return columns in error
///
/// If an error is returned from a fetch (in particular, a truncated
/// status), this method can be called to get the names of the fields in
/// error. It returns a string comprising the names of the fields
/// separated by commas. In the case of there being no error indicators
/// set, it returns the string "(None)".
///
/// @param error Array of error elements. An element is set to MLM_TRUE
/// if the corresponding column in the database is the source of
/// the error.
/// @param names Array of column names, the same size as the error array.
/// @param count Size of each of the arrays.
static string getColumnsInError(my_bool* error, std::string* names,<--- Parameter 'error' can be declared as pointer to const<--- Parameter 'names' can be declared as pointer to const
size_t count) {
string result = "";
// Accumulate list of column names
for (size_t i = 0; i < count; ++i) {
if (error[i] == MLM_TRUE) {
if (!result.empty()) {
result += ", ";
}
result += names[i];
}
}
if (result.empty()) {
result = "(None)";
}
return (result);
}
/// @brief Create MYSQL_BIND objects for log entry
///
/// Fills in the MYSQL_BIND array for sending data in the log entry to
/// the database.
///
/// @param addr address or prefix of the log entry
/// @param log log entry to be added to the database.
///
/// @return Vector of MySQL BIND objects representing the data to be added.
vector<MYSQL_BIND> createBindForSend(const string& addr,
const string& log) {
// Store arguments to ensure they remain valid.
addr_ = addr;
log_ = log;
// Initialize prior to constructing the array of MYSQL_BIND structures.
// It sets all fields, including is_null, to zero, so we need to set
// is_null only if it should be true. This gives up minor performance
// benefit while being safe approach. For improved readability, the
// code that explicitly sets is_null is there, but is commented out.
memset(bind_, 0, sizeof(bind_));
// Set up the structures for the various components of the log entry.
try {
// address : VARCHAR(43) NULL
// Note that previously we used MYSQL_TYPE_VARCHAR instead of
// MYSQL_TYPE_STRING. However, that caused 'buffer type not supported'
// errors on some systems running MariaDB.
if (!addr_.empty()) {
addr_length_ = addr_.size();
bind_[0].buffer_type = MYSQL_TYPE_STRING;
bind_[0].buffer = const_cast<char*>(addr_.c_str());
bind_[0].buffer_length = addr_length_;
bind_[0].length = &addr_length_;
// bind_[0].is_null = &MLM_FALSE; // commented out for performance
// reasons, see memset() above
} else {
bind_[0].buffer_type = MYSQL_TYPE_NULL;
// According to http://dev.mysql.com/doc/refman/5.5/en/
// c-api-prepared-statement-data-structures.html, the other
// fields doesn't matter if type is set to MYSQL_TYPE_NULL,
// but let's set them to some sane values in case earlier versions
// didn't have that assumption.
addr_null_ = MLM_TRUE;
bind_[0].buffer = NULL;
bind_[0].is_null = &addr_null_;
}
// log : TEXT NOT NULL
bind_[1].buffer_type = MYSQL_TYPE_STRING;
bind_[1].buffer = &log_[0];
bind_[1].buffer_length = log_.length();
// bind_[1].is_null = &MLM_FALSE; // commented out for performance
// reasons, see memset() above
// Add the error flags
setErrorIndicators(bind_, error_, LOG_COLUMNS);
// .. and check that we have the numbers correct at compile time.
BOOST_STATIC_ASSERT(1 < LOG_COLUMNS);
} catch (const std::exception& ex) {
isc_throw(DbOperationError,
"Could not create bind array from log: '"
<< log << "', reason: " << ex.what());
}
// Add the data to the vector. Note the end element is one after the
// end of the array.
return (vector<MYSQL_BIND>(&bind_[0], &bind_[LOG_COLUMNS]));
}
/// @brief Return columns in error
///
/// If an error is returned from a fetch (in particular, a truncated
/// status), this method can be called to get the names of the fields in
/// error. It returns a string comprising the names of the fields
/// separated by commas. In the case of there being no error indicators
/// set, it returns the string "(None)".
///
/// @return Comma-separated list of columns in error, or the string
/// "(None)".
string getErrorColumns() {
return (getColumnsInError(error_, columns_, LOG_COLUMNS));
}
private:
MYSQL_BIND bind_[LOG_COLUMNS]; ///< Bind array
string columns_[LOG_COLUMNS]; ///< Column names
my_bool error_[LOG_COLUMNS]; ///< Error array
string addr_; ///< Address or prefix
string log_; ///< Log entry
unsigned long addr_length_; ///< Address length
my_bool addr_null_; ///< Used when address is null
};
// MySqlStoreContext Constructor
MySqlStoreContext::MySqlStoreContext(const DatabaseConnection::ParameterMap& parameters,
IOServiceAccessorPtr io_service_accessor,
db::DbCallback db_reconnect_callback)
: conn_(parameters, io_service_accessor, db_reconnect_callback) {
}
// MySqlStoreContextAlloc Constructor and Destructor
MySqlStore::MySqlStoreContextAlloc::MySqlStoreContextAlloc(const MySqlStore& store)
: ctx_(), store_(store) {
if (MultiThreadingMgr::instance().getMode()) {
// multi-threaded
{
// we need to protect the whole pool_ operation, hence extra scope {}
lock_guard<mutex> lock(store_.pool_->mutex_);
if (!store_.pool_->pool_.empty()) {
ctx_ = store_.pool_->pool_.back();
store_.pool_->pool_.pop_back();
}
}
if (!ctx_) {
ctx_ = store_.createContext();
}
} else {
// single-threaded
if (store_.pool_->pool_.empty()) {
isc_throw(Unexpected, "No available MySQL store context?!");
}
ctx_ = store_.pool_->pool_.back();
}
}
MySqlStore::MySqlStoreContextAlloc::~MySqlStoreContextAlloc() {
if (MultiThreadingMgr::instance().getMode()) {
// multi-threaded
lock_guard<mutex> lock(store_.pool_->mutex_);
store_.pool_->pool_.push_back(ctx_);
}
// If running in single-threaded mode, there's nothing to do here.
}
// MySqlStore
MySqlStore::MySqlStore(const DatabaseConnection::ParameterMap& parameters)
: timer_name_("") {
// Store connection parameters.
BackendStore::setParameters(parameters);
// Create unique timer name per instance.
timer_name_ = "MySqlLegalStore[";
timer_name_ += boost::lexical_cast<std::string>(reinterpret_cast<uint64_t>(this));
timer_name_ += "]DbReconnectTimer";
}
void MySqlStore::open() {
LegalLogDbLogger pushed;
// Test schema version first.
std::pair<uint32_t, uint32_t> code_version(MYSQL_SCHEMA_VERSION_MAJOR,
MYSQL_SCHEMA_VERSION_MINOR);
BackendStorePtr store = BackendStore::instance();
BackendStore::instance().reset();
string timer_name;
bool retry = false;
if (BackendStore::getParameters().count("retry-on-startup")) {
if (BackendStore::getParameters().at("retry-on-startup") == "true") {
retry = true;
}
}
if (retry) {
timer_name = timer_name_;
}
std::pair<uint32_t, uint32_t> db_version = getVersion(timer_name);
if (code_version != db_version) {
isc_throw(DbOpenError,
"MySQL schema version mismatch: need version: "
<< code_version.first << "." << code_version.second
<< " found version: " << db_version.first << "."
<< db_version.second);
}
BackendStore::instance() = store;
// Create an initial context.
pool_.reset(new MySqlStoreContextPool());
pool_->pool_.push_back(createContext());
}
// Create context.
MySqlStoreContextPtr
MySqlStore::createContext() const {
MySqlStoreContextPtr ctx(new MySqlStoreContext(BackendStore::getParameters(),
IOServiceAccessorPtr(new IOServiceAccessor(&MySqlStore::getIOService)),
&MySqlStore::dbReconnect));
// Open the database.
ctx->conn_.openDatabase();
// Check if we have TLS when we required it.
if (ctx->conn_.getTls()) {
std::string cipher = ctx->conn_.getTlsCipher();
if (cipher.empty()) {
LOG_ERROR(legal_log_logger, LEGAL_LOG_MYSQL_NO_TLS);
} else {
LOG_DEBUG(legal_log_logger, DB_DBG_TRACE_DETAIL,
LEGAL_LOG_MYSQL_TLS_CIPHER)
.arg(cipher);
}
}
// Prepare all statements likely to be used.
ctx->conn_.prepareStatements(tagged_statements.begin(),
tagged_statements.end());
// Create the exchange objects for use in exchanging data between the
// program and the database.
ctx->exchange_.reset(new MySqlLegLExchange());
// Create ReconnectCtl for this connection.
ctx->conn_.makeReconnectCtl(timer_name_);
return (ctx);
}
MySqlStore::~MySqlStore() {
// There is no need to close the database in this destructor: it is
// closed in the destructor of the mysql_ member variable.
}
void
MySqlStore::close() {
}
void
MySqlStore::writeln(const string& text, const std::string& addr) {
if (text.empty()) {
return;
}
LOG_DEBUG(legal_log_logger, DB_DBG_TRACE_DETAIL,
LEGAL_LOG_MYSQL_INSERT_LOG).arg(text);
LegalLogDbLogger pushed;
// Get a context
MySqlStoreContextAlloc get_context(*this);
MySqlStoreContextPtr ctx = get_context.ctx_;
// Create the MYSQL_BIND array for the log entry
vector<MYSQL_BIND> bind = ctx->exchange_->createBindForSend(addr, text);
// Bind the parameters to the statement
int status = mysql_stmt_bind_param(ctx->conn_.getStatement(INSERT_LOG),
&bind[0]);
checkError(ctx, status, INSERT_LOG, "unable to bind parameters");
// Execute the statement
status = MysqlExecuteStatement(ctx->conn_.getStatement(INSERT_LOG));
if (status != 0) {
checkError(ctx, status, INSERT_LOG, "unable to execute");
}
// Insert succeeded
}
pair<uint32_t, uint32_t>
MySqlStore::getVersion(const std::string& timer_name) const {
LOG_DEBUG(legal_log_logger, DB_DBG_TRACE_DETAIL,
LEGAL_LOG_MYSQL_GET_VERSION);
LegalLogDbLogger pushed;
IOServiceAccessorPtr ac(new IOServiceAccessor(&DatabaseConnection::getIOService));
DbCallback cb(&MySqlStore::dbReconnect);
return (MySqlConnection::getVersion(BackendStore::getParameters(), ac, cb, timer_name));
}
void
MySqlStore::checkError(MySqlStoreContextPtr& ctx,
int status,
StatementIndex index,
const char* what) const {
ctx->conn_.checkError(status, index, what);
}
bool
MySqlStore::dbReconnect(ReconnectCtlPtr db_reconnect_ctl) {
MultiThreadingCriticalSection cs;
// Invoke application layer connection lost callback.
if (!DatabaseConnection::invokeDbLostCallback(db_reconnect_ctl)) {
return (false);
}
bool reopened = false;
const std::string timer_name = db_reconnect_ctl->timerName();
// At least one connection was lost.
try {
auto parameters = BackendStore::getParameters();
// Set legal store to NULL
BackendStore::instance().reset();
// Create temporary legal store
BackendStorePtr store(new MySqlStore(parameters));
store->open();
// If everything is fine, set the legal store
BackendStore::instance() = store;
BackendStore::parseExtraParameters(BackendStore::getConfig());
reopened = true;
} catch (const std::exception& ex) {
LOG_ERROR(legal_log_logger, LEGAL_LOG_MYSQL_DB_RECONNECT_ATTEMPT_FAILED)
.arg(ex.what());
}
if (reopened) {
// Cancel the timer.
if (TimerMgr::instance()->isTimerRegistered(timer_name)) {
TimerMgr::instance()->unregisterTimer(timer_name);
}
// Invoke application layer connection recovered callback.
if (!DatabaseConnection::invokeDbRecoveredCallback(db_reconnect_ctl)) {
return (false);
}
} else {
if (!db_reconnect_ctl->checkRetries()) {
// We're out of retries, log it and initiate shutdown.
LOG_ERROR(legal_log_logger, LEGAL_LOG_MYSQL_DB_RECONNECT_FAILED)
.arg(db_reconnect_ctl->maxRetries());
// Cancel the timer.
if (TimerMgr::instance()->isTimerRegistered(timer_name)) {
TimerMgr::instance()->unregisterTimer(timer_name);
}
// Invoke application layer connection failed callback.
DatabaseConnection::invokeDbFailedCallback(db_reconnect_ctl);
return (false);
}
LOG_INFO(legal_log_logger, LEGAL_LOG_MYSQL_DB_RECONNECT_ATTEMPT_SCHEDULE)
.arg(db_reconnect_ctl->maxRetries() - db_reconnect_ctl->retriesLeft() + 1)
.arg(db_reconnect_ctl->maxRetries())
.arg(db_reconnect_ctl->retryInterval());
// Start the timer.
if (!TimerMgr::instance()->isTimerRegistered(timer_name)) {
TimerMgr::instance()->registerTimer(timer_name,
std::bind(&MySqlStore::dbReconnect, db_reconnect_ctl),
db_reconnect_ctl->retryInterval(),
asiolink::IntervalTimer::ONE_SHOT);
}
TimerMgr::instance()->setup(timer_name);
}
return (true);
}
} // end of isc::legal_log namespace
} // end of isc namespace
|