Kea 2.7.6
database_connection.cc
Go to the documentation of this file.
1// Copyright (C) 2015-2024 Internet Systems Consortium, Inc. ("ISC")
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4// License, v. 2.0. If a copy of the MPL was not distributed with this
5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7#include <config.h>
8
9#include <cc/cfg_to_element.h>
12#include <database/db_log.h>
15#include <util/str.h>
16
17#include <boost/algorithm/string.hpp>
18#include <vector>
19
20using namespace isc::asiolink;
21using namespace isc::util;
22using namespace std;
23
24namespace isc {
25namespace db {
26
27const time_t DatabaseConnection::MAX_DB_TIME = 2147483647;
28
29std::string
30DatabaseConnection::getParameter(const std::string& name) const {
31 ParameterMap::const_iterator param = parameters_.find(name);
32 if (param == parameters_.end()) {
33 isc_throw(BadValue, "Parameter " << name << " not found");
34 }
35 return (param->second);
36}
37
39DatabaseConnection::parse(const std::string& dbaccess) {
41 std::string dba = dbaccess;
42
43 if (!dba.empty()) {
44 try {
45 vector<string> tokens;
46
47 // Handle the special case of a password which is enclosed in apostrophes.
48 // Such password may include whitespace.
49 std::string password_prefix = "password='";
50 auto password_pos = dba.find(password_prefix);
51 if (password_pos != string::npos) {
52 // Password starts with apostrophe, so let's find ending apostrophe.
53 auto password_end_pos = dba.find('\'', password_pos + password_prefix.length());
54 if (password_end_pos == string::npos) {
55 // No ending apostrophe. This is wrong.
56 isc_throw(InvalidParameter, "Apostrophe (') expected at the end of password");
57 }
58 // Extract the password value. It starts after the password=' prefix and ends
59 // at the position of ending apostrophe.
60 auto password = dba.substr(password_pos + password_prefix.length(),
61 password_end_pos - password_pos - password_prefix.length());
62 mapped_tokens.insert(make_pair("password", password));
63
64 // We need to erase the password from the access string because the generic
65 // algorithm parsing other parameters requires that there are no whitespaces
66 // within the parameter values.
67 dba.erase(password_pos, password_prefix.length() + password.length() + 2);
68 // Leading or trailing whitespace may remain after the password removal.
69 dba = util::str::trim(dba);
70 // If the password was the only parameter in the access string, there is
71 // nothing more to do.
72 if (dba.empty()) {
73 return (mapped_tokens);
74 }
75 }
76
77 // We need to pass a string to is_any_of, not just char*. Otherwise
78 // there are cryptic warnings on Debian6 running g++ 4.4 in
79 // /usr/include/c++/4.4/bits/stl_algo.h:2178 "array subscript is above
80 // array bounds"
81 boost::split(tokens, dba, boost::is_any_of(string("\t ")));
82 for (auto const& token : tokens) {
83 size_t pos = token.find("=");
84 if (pos != string::npos) {
85 string name = token.substr(0, pos);
86 string value = token.substr(pos + 1);
87 mapped_tokens.insert(make_pair(name, value));
88 } else {
89 isc_throw(InvalidParameter, "Cannot parse " << token
90 << ", expected format is name=value");
91 }
92 }
93 } catch (const std::exception& ex) {
94 // We'd obscure the password if we could parse the access string.
96 throw;
97 }
98 }
99
100 return (mapped_tokens);
101}
102
103std::string
105 // Reconstruct the access string: start of with an empty string, then
106 // work through all the parameters in the original string and add them.
107 std::string access;
108 for (auto const& i : parameters) {
109
110 // Separate second and subsequent tokens are preceded by a space.
111 if (!access.empty()) {
112 access += " ";
113 }
114
115 // Append name of parameter...
116 access += i.first;
117 access += "=";
118
119 // ... and the value, except in the case of the password, where a
120 // redacted value is appended.
121 if (i.first == std::string("password")) {
122 access += "*****";
123 } else {
124 access += i.second;
125 }
126 }
127
128 return (access);
129}
130
131bool
133 std::string readonly_value = "false";
134 try {
135 readonly_value = getParameter("readonly");
136 boost::algorithm::to_lower(readonly_value);
137 } catch (...) {
138 // Parameter "readonly" hasn't been specified so we simply use
139 // the default value of "false".
140 }
141
142 if ((readonly_value != "false") && (readonly_value != "true")) {
143 isc_throw(DbInvalidReadOnly, "invalid value '" << readonly_value
144 << "' specified for boolean parameter 'readonly'");
145 }
146
147 return (readonly_value == "true");
148}
149
150void
151DatabaseConnection::makeReconnectCtl(const std::string& timer_name) {
152 string type = "unknown";
153 unsigned int retries = 0;
154 unsigned int interval = 0;
155
156 // Assumes that parsing ensures only valid values are present
157 try {
158 type = getParameter("type");
159 } catch (...) {
160 // Wasn't specified so we'll use default of "unknown".
161 }
162
163 std::string parm_str;
164 try {
165 parm_str = getParameter("max-reconnect-tries");
166 retries = boost::lexical_cast<unsigned int>(parm_str);
167 } catch (...) {
168 // Wasn't specified so we'll use default of 0;
169 }
170
171 try {
172 parm_str = getParameter("reconnect-wait-time");
173 interval = boost::lexical_cast<unsigned int>(parm_str);
174 } catch (...) {
175 // Wasn't specified so we'll use default of 0;
176 }
177
178 OnFailAction action = OnFailAction::STOP_RETRY_EXIT;
179 try {
180 parm_str = getParameter("on-fail");
181 action = ReconnectCtl::onFailActionFromText(parm_str);
182 } catch (...) {
183 // Wasn't specified so we'll use default of "stop-retry-exit";
184 }
185
186 reconnect_ctl_ = boost::make_shared<ReconnectCtl>(type, timer_name, retries,
187 interval, action);
188}
189
190bool
193 return (DatabaseConnection::db_lost_callback_(db_reconnect_ctl));
194 }
195
196 return (false);
197}
198
199bool
202 return (DatabaseConnection::db_recovered_callback_(db_reconnect_ctl));
203 }
204
205 return (false);
206}
207
208bool
211 return (DatabaseConnection::db_failed_callback_(db_reconnect_ctl));
212 }
213
214 return (false);
215}
216
220
221 for (auto const& param : params) {
222 std::string keyword = param.first;
223 std::string value = param.second;
224
225 if ((keyword == "lfc-interval") ||
226 (keyword == "connect-timeout") ||
227 (keyword == "read-timeout") ||
228 (keyword == "write-timeout") ||
229 (keyword == "tcp-user-timeout") ||
230 (keyword == "reconnect-wait-time") ||
231 (keyword == "max-reconnect-tries") ||
232 (keyword == "port") ||
233 (keyword == "max-row-errors")) {
234 // integer parameters
235 int64_t int_value;
236 try {
237 int_value = boost::lexical_cast<int64_t>(value);
238 result->set(keyword, isc::data::Element::create(int_value));
239 } catch (...) {
241 .arg(keyword).arg(value);
242 }
243 } else if ((keyword == "persist") ||
244 (keyword == "readonly") ||
245 (keyword == "retry-on-startup")) {
246 if (value == "true") {
247 result->set(keyword, isc::data::Element::create(true));
248 } else if (value == "false") {
249 result->set(keyword, isc::data::Element::create(false));
250 } else {
252 .arg(keyword).arg(value);
253 }
254 } else if ((keyword == "type") ||
255 (keyword == "user") ||
256 (keyword == "password") ||
257 (keyword == "host") ||
258 (keyword == "name") ||
259 (keyword == "on-fail") ||
260 (keyword == "trust-anchor") ||
261 (keyword == "cert-file") ||
262 (keyword == "key-file") ||
263 (keyword == "cipher-list")) {
264 result->set(keyword, isc::data::Element::create(value));
265 } else {
267 .arg(keyword).arg(value);
268 }
269 }
270
271 return (result);
272}
273
276 ParameterMap params = parse(dbaccess);
277 return (toElement(params));
278}
279
283bool DatabaseConnection::retry_ = false;
284IOServicePtr DatabaseConnection::io_service_ = IOServicePtr();
285
287
288} // namespace db
289} // namespace isc
A generic exception that is thrown if a parameter given to a method is considered invalid in that con...
A generic exception that is thrown if a parameter given to a method or function is considered invalid...
static ElementPtr create(const Position &pos=ZERO_POSITION())
Definition data.cc:249
static ElementPtr createMap(const Position &pos=ZERO_POSITION())
Creates an empty MapElement type ElementPtr.
Definition data.cc:304
bool configuredReadOnly() const
Convenience method checking if database should be opened with read only access.
std::string getParameter(const std::string &name) const
Returns value of a connection parameter.
static bool invokeDbLostCallback(const util::ReconnectCtlPtr &db_reconnect_ctl)
Invokes the connection's lost connectivity callback.
static std::string redactedAccessString(const ParameterMap &parameters)
Redact database access string.
static bool invokeDbFailedCallback(const util::ReconnectCtlPtr &db_reconnect_ctl)
Invokes the connection's restore failed connectivity callback.
std::map< std::string, std::string > ParameterMap
Database configuration parameter map.
static isc::data::ElementPtr toElement(const ParameterMap &params)
Unparse a parameter map.
static isc::data::ElementPtr toElementDbAccessString(const std::string &dbaccess)
Unparse an access string.
static DbCallback db_recovered_callback_
Optional callback function to invoke if an opened connection recovery succeeded.
virtual void makeReconnectCtl(const std::string &timer_name)
Instantiates a ReconnectCtl based on the connection's reconnect parameters.
static ParameterMap parse(const std::string &dbaccess)
Parse database access string.
static bool test_mode_
Test mode flag (default false).
static bool retry_
Flag which indicates if the database connection should be retried on fail.
static bool invokeDbRecoveredCallback(const util::ReconnectCtlPtr &db_reconnect_ctl)
Invokes the connection's restored connectivity callback.
static DbCallback db_failed_callback_
Optional callback function to invoke if an opened connection recovery failed.
static DbCallback db_lost_callback_
Optional callback function to invoke if an opened connection is lost.
static const time_t MAX_DB_TIME
Defines maximum value for time that can be reliably stored.
Invalid 'readonly' value specification.
static OnFailAction onFailActionFromText(const std::string &text)
Convert string to action.
We want to reuse the database backend connection and exchange code for other uses,...
#define isc_throw(type, stream)
A shortcut macro to insert known values into exception arguments.
#define LOG_ERROR(LOGGER, MESSAGE)
Macro to conveniently test error output and log it.
Definition macros.h:32
boost::shared_ptr< Element > ElementPtr
Definition data.h:28
isc::log::Logger database_logger("database")
Common database library logger.
Definition db_log.h:46
@ DB_INVALID_ACCESS
Definition db_log.h:52
const isc::log::MessageID DATABASE_TO_JSON_UNKNOWN_TYPE_ERROR
Definition db_messages.h:28
const isc::log::MessageID DATABASE_TO_JSON_INTEGER_ERROR
Definition db_messages.h:27
std::function< bool(util::ReconnectCtlPtr db_reconnect_ctl)> DbCallback
Defines a callback prototype for propagating events upward.
const isc::log::MessageID DATABASE_TO_JSON_BOOLEAN_ERROR
Definition db_messages.h:26
string trim(const string &input)
Trim leading and trailing spaces.
Definition str.cc:32
OnFailAction
Type of action to take on connection loss.
boost::shared_ptr< ReconnectCtl > ReconnectCtlPtr
Pointer to an instance of ReconnectCtl.
Defines the logger used by the top-level component of kea-lfc.
DB_LOG & arg(T first, Args... args)
Pass parameters to replace logger placeholders.
Definition db_log.h:144