mysql_lease_mgr.cc 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034
  1. // Copyright (C) 2012 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #include <iostream>
  15. #include <iomanip>
  16. #include <string>
  17. #include <config.h>
  18. #include <time.h>
  19. #include <mysql/mysqld_error.h>
  20. #include <dhcp/mysql_lease_mgr.h>
  21. #include <asiolink/io_address.h>
  22. using namespace isc;
  23. using namespace std;
  24. namespace {
  25. ///@{
  26. /// @brief Maximum Size of Database Fields
  27. ///
  28. /// The following constants define buffer sizes for variable length database
  29. /// fields. The values should be greater than or equal to the length set in
  30. /// the schema definition.
  31. ///
  32. /// The exception is the length of any VARCHAR fields: these should be set
  33. /// greater than or equal to the length of the field plus 2: this allows for
  34. /// the insertion of a trailing null regardless of whether the data returned
  35. /// contains a trailing null (the documentation is not clear on this point).
  36. const size_t ADDRESS6_TEXT_MAX_LEN = 42; // Max size of a IPv6 text buffer
  37. const size_t DUID_MAX_LEN = 128; // Max size of a DUID
  38. ///@}
  39. };
  40. namespace isc {
  41. namespace dhcp {
  42. /// @brief Exchange MySQL and Lease6 Data
  43. ///
  44. /// On any MySQL operation, arrays of MYSQL_BIND structures must be built to
  45. /// describe the parameters in the prepared statements. Where information is
  46. /// inserted or retrieved - INSERT, UPDATE, SELECT - a large amount of that
  47. /// structure is identical - it defines data values in the Lease6 structure.
  48. ///
  49. /// This class handles the creation of that array. For maximum flexibility,
  50. /// the data is appended to an array of MYSQL_BIND elemements, so allowing
  51. /// additional elements to be prepended/appended to it.
  52. ///
  53. /// Owing to the MySQL API, the process requires some intermediate variables
  54. /// to hold things like length etc. This object holds the intermediate
  55. /// variables as well.
  56. class MySqlLease6Exchange {
  57. public:
  58. /// @brief Constructor
  59. ///
  60. /// Apart from the initialization of false_ and true_, the other
  61. /// initializations are to satisfy cppcheck: none are really needed, as all
  62. /// variables are initialized/set in the methods.
  63. MySqlLease6Exchange() : addr6_length_(0), duid_length_(0), false_(0), true_(1) {
  64. memset(addr6_buffer_, 0, sizeof(addr6_buffer_));
  65. memset(duid_buffer_, 0, sizeof(duid_buffer_));
  66. }
  67. /// @brief Create MYSQL_BIND objects for Lease6 Pointer
  68. ///
  69. /// Fills in the MYSQL_BIND objects for the Lease6 passed to it.
  70. ///
  71. /// @param lease Lease object to be added to the database
  72. /// @param bindvec Vector of MySQL BIND objects: the elements describing the
  73. /// lease are appended to this vector. The data added to the vector
  74. /// only remain valid while both the lease and this object are valid.
  75. void
  76. createBindForSend(const Lease6Ptr& lease, std::vector<MYSQL_BIND>& bindvec) {
  77. // Store lease object to ensure it remains valid.
  78. lease_ = lease;
  79. // Ensure bind_ array clear for constructing the MYSQL_BIND structures
  80. // for this lease.
  81. memset(bind_, 0, sizeof(bind_));
  82. // address: varchar(40)
  83. addr6_ = lease_->addr_.toText();
  84. addr6_length_ = addr6_.size();
  85. bind_[0].buffer_type = MYSQL_TYPE_STRING;
  86. bind_[0].buffer = const_cast<char*>(addr6_.c_str());
  87. bind_[0].buffer_length = addr6_length_;
  88. bind_[0].length = &addr6_length_;
  89. // duid: varchar(128)
  90. duid_ = lease_->duid_->getDuid();
  91. duid_length_ = duid_.size();
  92. bind_[1].buffer_type = MYSQL_TYPE_BLOB;
  93. bind_[1].buffer = reinterpret_cast<char*>(&(duid_[0]));
  94. bind_[1].buffer_length = duid_length_;
  95. bind_[1].length = &duid_length_;
  96. // valid lifetime: unsigned int
  97. bind_[2].buffer_type = MYSQL_TYPE_LONG;
  98. bind_[2].buffer = reinterpret_cast<char*>(&lease->valid_lft_);
  99. bind_[2].is_unsigned = true_;
  100. // expire: timestamp
  101. // The lease structure holds the client last transmission time (cltt_)
  102. // For convenience for external tools, this is converted to lease
  103. /// expiry time (expire). The relationship is given by:
  104. //
  105. // expire = cltt_ + valid_lft_
  106. //
  107. // @TODO Handle overflows
  108. MySqlLeaseMgr::convertToDatabaseTime(lease_->cltt_, lease_->valid_lft_,
  109. expire_);
  110. bind_[3].buffer_type = MYSQL_TYPE_TIMESTAMP;
  111. bind_[3].buffer = reinterpret_cast<char*>(&expire_);
  112. bind_[3].buffer_length = sizeof(expire_);
  113. // subnet_id: unsigned int
  114. // Can use lease_->subnet_id_ directly as it is of type uint32_t.
  115. bind_[4].buffer_type = MYSQL_TYPE_LONG;
  116. bind_[4].buffer = reinterpret_cast<char*>(&lease_->subnet_id_);
  117. bind_[4].is_unsigned = true_;
  118. // pref_lifetime: unsigned int
  119. // Can use lease_->preferred_lft_ directly as it is of type uint32_t.
  120. bind_[5].buffer_type = MYSQL_TYPE_LONG;
  121. bind_[5].buffer = reinterpret_cast<char*>(&lease_->preferred_lft_);
  122. bind_[5].is_unsigned = true_;
  123. // lease_type: tinyint
  124. // Must convert to uint8_t as lease_->type_ is a LeaseType variable
  125. lease_type_ = lease_->type_;
  126. bind_[6].buffer_type = MYSQL_TYPE_TINY;
  127. bind_[6].buffer = reinterpret_cast<char*>(&lease_type_);
  128. bind_[6].is_unsigned = true_;
  129. // iaid: unsigned int
  130. // Can use lease_->iaid_ directly as it is of type uint32_t.
  131. bind_[7].buffer_type = MYSQL_TYPE_LONG;
  132. bind_[7].buffer = reinterpret_cast<char*>(&lease_->iaid_);
  133. bind_[7].is_unsigned = true_;
  134. // prefix_len: unsigned tinyint
  135. // Can use lease_->prefixlen_ directly as it is uint32_t.
  136. bind_[8].buffer_type = MYSQL_TYPE_TINY;
  137. bind_[8].buffer = reinterpret_cast<char*>(&lease_->prefixlen_);
  138. bind_[8].is_unsigned = true_;
  139. // Add the data to the vector. Note the end element is one after the
  140. // end of the array.
  141. bindvec.insert(bindvec.end(), &bind_[0], &bind_[9]);
  142. }
  143. /// @brief Create BIND array to receive data
  144. ///
  145. /// Creates a MYSQL_BIND array to receive Lease6 data from the database.
  146. /// After data is successfully received, getLeaseData() is used to copy
  147. /// it to a Lease6 object.
  148. ///
  149. /// @param bindvec Vector of MySQL BIND objects: the elements describing the
  150. /// lease are appended to this vector. The data added to the vector
  151. /// only remain valid while both the lease and this object are valid.
  152. void createBindForReceive(std::vector<MYSQL_BIND>& bindvec) {
  153. // Ensure both the array of MYSQL_BIND structures and the error array
  154. // are clear.
  155. memset(bind_, 0, sizeof(bind_));
  156. memset(error_, 0, sizeof(error_));
  157. // address: varchar
  158. // A Lease6_ address has a maximum of 39 characters. The array is
  159. // a few bites longer than this to guarantee that we can always null
  160. // terminate it.
  161. addr6_length_ = sizeof(addr6_buffer_) - 1;
  162. bind_[0].buffer_type = MYSQL_TYPE_STRING;
  163. bind_[0].buffer = addr6_buffer_;
  164. bind_[0].buffer_length = addr6_length_;
  165. bind_[0].length = &addr6_length_;
  166. bind_[0].error = &error_[0];
  167. // client_id: varbinary(128)
  168. duid_length_ = sizeof(duid_buffer_);
  169. bind_[1].buffer_type = MYSQL_TYPE_BLOB;
  170. bind_[1].buffer = reinterpret_cast<char*>(duid_buffer_);
  171. bind_[1].buffer_length = duid_length_;
  172. bind_[1].length = &duid_length_;
  173. bind_[1].error = &error_[1];
  174. // lease_time: unsigned int
  175. bind_[2].buffer_type = MYSQL_TYPE_LONG;
  176. bind_[2].buffer = reinterpret_cast<char*>(&valid_lifetime_);
  177. bind_[2].is_unsigned = true_;
  178. bind_[2].error = &error_[2];
  179. // expire: timestamp
  180. bind_[3].buffer_type = MYSQL_TYPE_TIMESTAMP;
  181. bind_[3].buffer = reinterpret_cast<char*>(&expire_);
  182. bind_[3].buffer_length = sizeof(expire_);
  183. bind_[3].error = &error_[3];
  184. // subnet_id: unsigned int
  185. bind_[4].buffer_type = MYSQL_TYPE_LONG;
  186. bind_[4].buffer = reinterpret_cast<char*>(&subnet_id_);
  187. bind_[4].is_unsigned = true_;
  188. bind_[4].error = &error_[4];
  189. // pref_lifetime: unsigned int
  190. bind_[5].buffer_type = MYSQL_TYPE_LONG;
  191. bind_[5].buffer = reinterpret_cast<char*>(&pref_lifetime_);
  192. bind_[5].is_unsigned = true_;
  193. bind_[5].error = &error_[5];
  194. // lease_type: tinyint
  195. bind_[6].buffer_type = MYSQL_TYPE_TINY;
  196. bind_[6].buffer = reinterpret_cast<char*>(&lease_type_);
  197. bind_[6].is_unsigned = true_;
  198. bind_[6].error = &error_[6];
  199. // iaid: unsigned int
  200. bind_[7].buffer_type = MYSQL_TYPE_LONG;
  201. bind_[7].buffer = reinterpret_cast<char*>(&iaid_);
  202. bind_[7].is_unsigned = true_;
  203. bind_[7].error = &error_[7];
  204. // prefix_len: unsigned tinyint
  205. bind_[8].buffer_type = MYSQL_TYPE_TINY;
  206. bind_[8].buffer = reinterpret_cast<char*>(&prefixlen_);
  207. bind_[8].is_unsigned = true_;
  208. bind_[8].error = &error_[8];
  209. // Add the data to the vector. Note the end element is one after the
  210. // end of the array.
  211. bindvec.insert(bindvec.end(), &bind_[0], &bind_[9]);
  212. }
  213. /// @brief Copy Received Data into Lease6 Object
  214. ///
  215. /// Called after the MYSQL_BIND array created by createBindForReceive()
  216. /// has been used, this copies data from the internal member vairables
  217. /// into a Lease6 object.
  218. ///
  219. /// @return Lease6Ptr Pointer to a Lease6 object holding the relevant
  220. /// data.
  221. ///
  222. /// @exception BadValue Unable to convert Lease Type value in database
  223. Lease6Ptr getLeaseData() {
  224. // Create the object to be returned.
  225. Lease6Ptr result(new Lease6());
  226. // Put the data in the lease object
  227. // The address buffer is declared larger than the buffer size passed
  228. // to the access function so that we can always append a null byte.
  229. addr6_buffer_[addr6_length_] = '\0';
  230. std::string address = addr6_buffer_;
  231. // Set the other data, converting time as needed.
  232. result->addr_ = isc::asiolink::IOAddress(address);
  233. result->duid_.reset(new DUID(duid_buffer_, duid_length_));
  234. MySqlLeaseMgr::convertFromDatabaseTime(expire_, valid_lifetime_,
  235. result->cltt_);
  236. result->valid_lft_ = valid_lifetime_;
  237. result->subnet_id_ = subnet_id_;
  238. result->preferred_lft_ = pref_lifetime_;
  239. // We can't convert from a numeric value to an enum, hence:
  240. switch (lease_type_) {
  241. case Lease6::LEASE_IA_NA:
  242. result->type_ = Lease6::LEASE_IA_NA;
  243. break;
  244. case Lease6::LEASE_IA_TA:
  245. result->type_ = Lease6::LEASE_IA_TA;
  246. break;
  247. case Lease6::LEASE_IA_PD:
  248. result->type_ = Lease6::LEASE_IA_PD;
  249. break;
  250. default:
  251. isc_throw(BadValue, "invalid lease type returned (" <<
  252. lease_type_ << ") for lease with address " <<
  253. result->addr_.toText() << ". Only 0, 1, or 2 "
  254. "are allowed.");
  255. }
  256. result->iaid_ = iaid_;
  257. result->prefixlen_ = prefixlen_;
  258. return (result);
  259. }
  260. private:
  261. // Note: All array legths are equal to the corresponding variable in the
  262. // schema.
  263. std::string addr6_; ///< String form of address
  264. char addr6_buffer_[ADDRESS6_TEXT_MAX_LEN]; ///< Character
  265. ///< array form of V6 address
  266. unsigned long addr6_length_; ///< Length of the address
  267. MYSQL_BIND bind_[9]; ///< Static array for speed of access
  268. std::vector<uint8_t> duid_; ///< Client identification
  269. uint8_t duid_buffer_[DUID_MAX_LEN]; ///< Buffer form of DUID
  270. unsigned long duid_length_; ///< Length of the DUID
  271. my_bool error_[9]; ///< For error reporting
  272. MYSQL_TIME expire_; ///< Lease expiry time
  273. const my_bool false_; ///< "false" for MySql
  274. uint32_t iaid_; ///< Identity association ID
  275. Lease6Ptr lease_; ///< Pointer to lease object
  276. uint32_t valid_lifetime_; ///< Lease time
  277. uint8_t lease_type_; ///< Lease type
  278. uint8_t prefixlen_; ///< Prefix length
  279. uint32_t pref_lifetime_; ///< Preferred lifetime
  280. uint32_t subnet_id_; ///< Subnet identification
  281. const my_bool true_; ///< "true_" for MySql
  282. };
  283. MySqlLeaseMgr::MySqlLeaseMgr(const LeaseMgr::ParameterMap& parameters)
  284. : LeaseMgr(parameters), mysql_(NULL) {
  285. // Allocate context for MySQL - it is destroyed in the destructor.
  286. mysql_ = mysql_init(NULL);
  287. if (mysql_ == NULL) {
  288. isc_throw(DbOpenError, "unable to initialize MySQL");
  289. }
  290. // Open the database
  291. openDatabase();
  292. // Disable autocommit
  293. my_bool result = mysql_autocommit(mysql_, 0);
  294. if (result != 0) {
  295. isc_throw(DbOperationError, mysql_error(mysql_));
  296. }
  297. // Prepare all statements likely to be used.
  298. prepareStatements();
  299. }
  300. MySqlLeaseMgr::~MySqlLeaseMgr() {
  301. // Free up the prepared statements, ignoring errors. (What would we do
  302. // about them - we're destroying this object and are not really concerned
  303. // with errors on a database connection that it about to go away.)
  304. for (int i = 0; i < statements_.size(); ++i) {
  305. if (statements_[i] != NULL) {
  306. (void) mysql_stmt_close(statements_[i]);
  307. statements_[i] = NULL;
  308. }
  309. }
  310. // Close the database
  311. mysql_close(mysql_);
  312. mysql_ = NULL;
  313. }
  314. // Time conversion methods.
  315. //
  316. // Note that the MySQL TIMESTAMP data type (used for "expire") converts data
  317. // from the current timezone to UTC for storage, and from UTC to the current
  318. // timezone for retrieval.
  319. //
  320. // This causes no problems providing that:
  321. // a) cltt is given in local time
  322. // b) We let the system take care of timezone conversion when converting
  323. // from a time read from the database into a local time.
  324. void
  325. MySqlLeaseMgr::convertToDatabaseTime(time_t cltt, uint32_t valid_lifetime,
  326. MYSQL_TIME& expire) {
  327. // Calculate expiry time and convert to various date/time fields.
  328. // @TODO: handle overflows
  329. time_t expire_time = cltt + valid_lifetime;
  330. // Convert to broken-out time
  331. struct tm expire_tm;
  332. (void) localtime_r(&expire_time, &expire_tm);
  333. // Place in output expire structure.
  334. expire.year = expire_tm.tm_year + 1900;
  335. expire.month = expire_tm.tm_mon + 1; // Note different base
  336. expire.day = expire_tm.tm_mday;
  337. expire.hour = expire_tm.tm_hour;
  338. expire.minute = expire_tm.tm_min;
  339. expire.second = expire_tm.tm_sec;
  340. expire.second_part = 0; // No fractional seconds
  341. expire.neg = static_cast<my_bool>(0); // Not negative
  342. }
  343. void
  344. MySqlLeaseMgr::convertFromDatabaseTime(const MYSQL_TIME& expire,
  345. uint32_t valid_lifetime, time_t& cltt) {
  346. // Copy across fields from MYSQL_TIME structure.
  347. struct tm expire_tm;
  348. memset(&expire_tm, 0, sizeof(expire_tm));
  349. expire_tm.tm_year = expire.year - 1900;
  350. expire_tm.tm_mon = expire.month - 1;
  351. expire_tm.tm_mday = expire.day;
  352. expire_tm.tm_hour = expire.hour;
  353. expire_tm.tm_min = expire.minute;
  354. expire_tm.tm_sec = expire.second;
  355. expire_tm.tm_isdst = -1; // Let the system work out about DST
  356. // Convert to local time
  357. cltt = mktime(&expire_tm) - valid_lifetime;
  358. }
  359. void
  360. MySqlLeaseMgr::openDatabase() {
  361. // Set up the values of the parameters
  362. const char* host = "localhost";
  363. string shost;
  364. try {
  365. shost = getParameter("host");
  366. host = shost.c_str();
  367. } catch (...) {
  368. // No host. Fine, we'll use "localhost"
  369. }
  370. const char* user = NULL;
  371. string suser;
  372. try {
  373. suser = getParameter("user");
  374. user = suser.c_str();
  375. } catch (...) {
  376. // No user. Fine, we'll use NULL
  377. ;
  378. }
  379. const char* password = NULL;
  380. string spassword;
  381. try {
  382. spassword = getParameter("password");
  383. password = spassword.c_str();
  384. } catch (...) {
  385. // No password. Fine, we'll use NULL
  386. ;
  387. }
  388. const char* name = NULL;
  389. string sname;
  390. try {
  391. sname = getParameter("name");
  392. name = sname.c_str();
  393. } catch (...) {
  394. // No database name. Throw a "NoName" exception
  395. isc_throw(NoDatabaseName, "must specified a name for the database");
  396. }
  397. // Set options for the connection:
  398. // - automatic reconnection
  399. my_bool auto_reconnect = 1;
  400. int result = mysql_options(mysql_, MYSQL_OPT_RECONNECT, &auto_reconnect);
  401. if (result != 0) {
  402. isc_throw(DbOpenError, "unable to set auto-reconnect option: " <<
  403. mysql_error(mysql_));
  404. }
  405. // Open the database.
  406. //
  407. // The option CLIENT_FOUND_ROWS is specified so that in an UPDATE,
  408. // the affected rows are the number of rows found that match the
  409. // WHERE clause of the SQL statement, not the rows changed. The reason
  410. // here is that MySQL apparently does not update a row if data has not
  411. // changed and so the "affected rows" (retrievable from MySQL) is zero.
  412. // This makes it hard to distinguish whether the UPDATE changed no rows
  413. // because no row matching the WHERE clause was found, or because a
  414. // row was found by no data was altered.
  415. MYSQL* status = mysql_real_connect(mysql_, host, user, password, name,
  416. 0, NULL, CLIENT_FOUND_ROWS);
  417. if (status != mysql_) {
  418. isc_throw(DbOpenError, mysql_error(mysql_));
  419. }
  420. }
  421. void
  422. MySqlLeaseMgr::prepareStatement(StatementIndex index, const char* text) {
  423. // Validate that there is space for the statement in the statements array
  424. // and that nothing has been placed there before.
  425. if ((index >= statements_.size()) || (statements_[index] != NULL)) {
  426. isc_throw(InvalidParameter, "invalid prepared statement index (" <<
  427. static_cast<int>(index) << ") or indexed prepared " <<
  428. "statement is not null");
  429. }
  430. // All OK, so prepare the statement
  431. text_statements_[index] = std::string(text);
  432. statements_[index] = mysql_stmt_init(mysql_);
  433. if (statements_[index] == NULL) {
  434. isc_throw(DbOperationError, "unable to allocate MySQL prepared "
  435. "statement structure" << mysql_error(mysql_));
  436. }
  437. int status = mysql_stmt_prepare(statements_[index], text, strlen(text));
  438. if (status != 0) {
  439. isc_throw(DbOperationError, "unable to prepare MySQL statement <" <<
  440. text << ">, reason: " << mysql_error(mysql_));
  441. }
  442. }
  443. void
  444. MySqlLeaseMgr::prepareStatements() {
  445. // Allocate space for all statements
  446. statements_.clear();
  447. statements_.resize(NUM_STATEMENTS, NULL);
  448. text_statements_.clear();
  449. text_statements_.resize(NUM_STATEMENTS, std::string(""));
  450. // Now allocate the statements
  451. prepareStatement(DELETE_LEASE6,
  452. "DELETE FROM lease6 WHERE address = ?");
  453. prepareStatement(GET_LEASE6_ADDR,
  454. "SELECT address, duid, valid_lifetime, "
  455. "expire, subnet_id, pref_lifetime, "
  456. "lease_type, iaid, prefix_len "
  457. "FROM lease6 "
  458. "WHERE address = ?");
  459. prepareStatement(GET_LEASE6_DUID_IAID,
  460. "SELECT address, duid, valid_lifetime, "
  461. "expire, subnet_id, pref_lifetime, "
  462. "lease_type, iaid, prefix_len "
  463. "FROM lease6 "
  464. "WHERE duid = ? AND iaid = ?");
  465. prepareStatement(GET_LEASE6_DUID_IAID_SUBID,
  466. "SELECT address, duid, valid_lifetime, "
  467. "expire, subnet_id, pref_lifetime, "
  468. "lease_type, iaid, prefix_len "
  469. "FROM lease6 "
  470. "WHERE duid = ? AND iaid = ? AND subnet_id = ?");
  471. prepareStatement(GET_VERSION,
  472. "SELECT version, minor FROM schema_version");
  473. prepareStatement(INSERT_LEASE6,
  474. "INSERT INTO lease6(address, duid, valid_lifetime, "
  475. "expire, subnet_id, pref_lifetime, "
  476. "lease_type, iaid, prefix_len) "
  477. "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
  478. prepareStatement(UPDATE_LEASE6,
  479. "UPDATE lease6 SET address = ?, duid = ?, "
  480. "valid_lifetime = ?, expire = ?, subnet_id = ?, "
  481. "pref_lifetime = ?, lease_type = ?, iaid = ?, "
  482. "prefix_len = ? "
  483. "WHERE address = ?");
  484. }
  485. bool
  486. MySqlLeaseMgr::addLease(const Lease4Ptr& /* lease */) {
  487. isc_throw(NotImplemented, "MySqlLeaseMgr::addLease(const Lease4Ptr&) "
  488. "not implemented yet");
  489. return (false);
  490. }
  491. bool
  492. MySqlLeaseMgr::addLease(const Lease6Ptr& lease) {
  493. // Create the MYSQL_BIND array for the lease
  494. MySqlLease6Exchange exchange;
  495. std::vector<MYSQL_BIND> bind;
  496. exchange.createBindForSend(lease, bind);
  497. // Bind the parameters to the statement
  498. int status = mysql_stmt_bind_param(statements_[INSERT_LEASE6], &bind[0]);
  499. checkError(status, INSERT_LEASE6, "unable to bind parameters");
  500. // Execute the statement
  501. status = mysql_stmt_execute(statements_[INSERT_LEASE6]);
  502. if (status != 0) {
  503. // Failure: check for the special case of duplicate entry. If this is
  504. // the case, we return false to indicate that the row was not added.
  505. // Otherwise we throw an exception.
  506. if (mysql_errno(mysql_) == ER_DUP_ENTRY) {
  507. return (false);
  508. }
  509. checkError(status, INSERT_LEASE6, "unable to execute");
  510. }
  511. // Insert succeeded
  512. return (true);
  513. }
  514. Lease4Ptr
  515. MySqlLeaseMgr::getLease4(const isc::asiolink::IOAddress& /* addr */,
  516. SubnetID /* subnet_id */) const {
  517. isc_throw(NotImplemented, "MySqlLeaseMgr::getLease4(const IOAddress&, SubnetID) "
  518. "not implemented yet");
  519. return (Lease4Ptr());
  520. }
  521. Lease4Ptr
  522. MySqlLeaseMgr::getLease4(const isc::asiolink::IOAddress& /* addr */) const {
  523. isc_throw(NotImplemented, "MySqlLeaseMgr::getLease4(const IOAddress&) "
  524. "not implemented yet");
  525. return (Lease4Ptr());
  526. }
  527. Lease4Collection
  528. MySqlLeaseMgr::getLease4(const HWAddr& /* hwaddr */) const {
  529. isc_throw(NotImplemented, "MySqlLeaseMgr::getLease4(const HWAddr&) "
  530. "not implemented yet");
  531. return (Lease4Collection());
  532. }
  533. Lease4Ptr
  534. MySqlLeaseMgr::getLease4(const HWAddr& /* hwaddr */,
  535. SubnetID /* subnet_id */) const {
  536. isc_throw(NotImplemented, "MySqlLeaseMgr::getLease4(const HWAddr&, SubnetID) "
  537. "not implemented yet");
  538. return (Lease4Ptr());
  539. }
  540. Lease4Collection
  541. MySqlLeaseMgr::getLease4(const ClientId& /* clientid */) const {
  542. isc_throw(NotImplemented, "MySqlLeaseMgr::getLease4(const ClientID&) "
  543. "not implemented yet");
  544. return (Lease4Collection());
  545. }
  546. Lease4Ptr
  547. MySqlLeaseMgr::getLease4(const ClientId& /* clientid */,
  548. SubnetID /* subnet_id */) const {
  549. isc_throw(NotImplemented, "MySqlLeaseMgr::getLease4(const ClientID&, SubnetID) "
  550. "not implemented yet");
  551. return (Lease4Ptr());
  552. }
  553. Lease6Ptr
  554. MySqlLeaseMgr::getLease6(const isc::asiolink::IOAddress& addr) const {
  555. // Set up the WHERE clause value
  556. MYSQL_BIND inbind[1];
  557. memset(inbind, 0, sizeof(inbind));
  558. std::string addr6 = addr.toText();
  559. unsigned long addr6_length = addr6.size();
  560. inbind[0].buffer_type = MYSQL_TYPE_STRING;
  561. inbind[0].buffer = const_cast<char*>(addr6.c_str());
  562. inbind[0].buffer_length = addr6_length;
  563. inbind[0].length = &addr6_length;
  564. // Bind the input parameters to the statement
  565. int status = mysql_stmt_bind_param(statements_[GET_LEASE6_ADDR], inbind);
  566. checkError(status, GET_LEASE6_ADDR, "unable to bind WHERE clause parameter");
  567. // Set up the SELECT clause
  568. MySqlLease6Exchange exchange;
  569. std::vector<MYSQL_BIND> outbind;
  570. exchange.createBindForReceive(outbind);
  571. // Bind the output parameters to the statement
  572. status = mysql_stmt_bind_result(statements_[GET_LEASE6_ADDR], &outbind[0]);
  573. checkError(status, GET_LEASE6_ADDR, "unable to bind SELECT caluse parameters");
  574. // Execute the statement
  575. status = mysql_stmt_execute(statements_[GET_LEASE6_ADDR]);
  576. checkError(status, GET_LEASE6_ADDR, "unable to execute");
  577. // Fetch the data.
  578. status = mysql_stmt_fetch(statements_[GET_LEASE6_ADDR]);
  579. Lease6Ptr result;
  580. if (status == 0) {
  581. try {
  582. result = exchange.getLeaseData();
  583. } catch (const isc::BadValue& ex) {
  584. // Free up result set.
  585. (void) mysql_stmt_free_result(statements_[GET_LEASE6_ADDR]);
  586. // Lease type is returned, to rethrow the exception with a bit
  587. // more data.
  588. isc_throw(BadValue, ex.what() << ". Statement is <" <<
  589. text_statements_[GET_LEASE6_ADDR] << ">");
  590. }
  591. // As the address is the primary key in the table, we can't return
  592. // two rows, so we don't bother checking whether multiple rows have
  593. // been returned.
  594. } else if (status == 1) {
  595. checkError(status, GET_LEASE6_ADDR, "unable to fetch results");
  596. } else {
  597. // @TODO Handle truncation
  598. // We are ignoring truncation for now, so the only other result is
  599. // no data was found. In that case, we return a null Lease6 structure.
  600. // This has already been set, so the action is a no-op.
  601. }
  602. // Free data structures associated with information returned.
  603. (void) mysql_stmt_free_result(statements_[GET_LEASE6_ADDR]);
  604. return (result);
  605. }
  606. Lease6Collection
  607. MySqlLeaseMgr::getLease6(const DUID& duid, uint32_t iaid) const {
  608. // Set up the WHERE clause value
  609. MYSQL_BIND inbind[2];
  610. memset(inbind, 0, sizeof(inbind));
  611. // DUID. The complex casting is needed to obtain the "const" vector of
  612. // uint8_t from the DUID, point to the start of it (discarding the
  613. // "const"ness) and finally casing it to "char*" for the MySQL buffer
  614. // element.
  615. const vector<uint8_t>& duid_vector = duid.getDuid();
  616. unsigned long duid_length = duid_vector.size();
  617. inbind[0].buffer_type = MYSQL_TYPE_BLOB;
  618. inbind[0].buffer = reinterpret_cast<char*>(
  619. const_cast<uint8_t*>(&duid_vector[0]));
  620. inbind[0].buffer_length = duid_length;
  621. inbind[0].length = &duid_length;
  622. // IAID
  623. inbind[1].buffer_type = MYSQL_TYPE_LONG;
  624. inbind[1].buffer = reinterpret_cast<char*>(&iaid);
  625. inbind[1].is_unsigned = static_cast<my_bool>(1);
  626. // Bind the input parameters to the statement
  627. int status = mysql_stmt_bind_param(statements_[GET_LEASE6_DUID_IAID], inbind);
  628. checkError(status, GET_LEASE6_DUID_IAID, "unable to bind WHERE clause parameter");
  629. // Set up the SELECT clause
  630. MySqlLease6Exchange exchange;
  631. std::vector<MYSQL_BIND> outbind;
  632. exchange.createBindForReceive(outbind);
  633. // Bind the output parameters to the statement
  634. status = mysql_stmt_bind_result(statements_[GET_LEASE6_DUID_IAID], &outbind[0]);
  635. checkError(status, GET_LEASE6_DUID_IAID, "unable to bind SELECT clause parameters");
  636. // Execute the query.
  637. status = mysql_stmt_execute(statements_[GET_LEASE6_DUID_IAID]);
  638. checkError(status, GET_LEASE6_DUID_IAID, "unable to execute");
  639. // Ensure that all the lease information is retrieved in one go to avoid overhead
  640. // of going back and forth between client and server.
  641. status = mysql_stmt_store_result(statements_[GET_LEASE6_DUID_IAID]);
  642. checkError(status, GET_LEASE6_DUID_IAID, "unable to set up for storing all results");
  643. // Fetch the data. There could be multiple rows, so we need to iterate
  644. // until all data has been retrieved.
  645. Lease6Collection result;
  646. while ((status = mysql_stmt_fetch(statements_[GET_LEASE6_DUID_IAID])) == 0) {
  647. try {
  648. Lease6Ptr lease = exchange.getLeaseData();
  649. result.push_back(lease);
  650. } catch (const isc::BadValue& ex) {
  651. // Free up result set.
  652. (void) mysql_stmt_free_result(statements_[GET_LEASE6_DUID_IAID]);
  653. // Rethrow the exception with a bit more data.
  654. isc_throw(BadValue, ex.what() << ". Statement is <" <<
  655. text_statements_[GET_LEASE6_DUID_IAID] << ">");
  656. }
  657. }
  658. // How did the fetch end?
  659. if (status == 1) {
  660. // Error - unable to fecth results
  661. checkError(status, GET_LEASE6_DUID_IAID, "unable to fetch results");
  662. } else if (status == MYSQL_DATA_TRUNCATED) {
  663. // @TODO Handle truncation
  664. ;
  665. }
  666. // Free up resources assoicated with the fetched data.
  667. (void) mysql_stmt_free_result(statements_[GET_LEASE6_DUID_IAID]);
  668. return (result);
  669. }
  670. Lease6Ptr
  671. MySqlLeaseMgr::getLease6(const DUID& duid, uint32_t iaid,
  672. SubnetID subnet_id) const {
  673. // Set up the WHERE clause value
  674. MYSQL_BIND inbind[3];
  675. memset(inbind, 0, sizeof(inbind));
  676. // DUID. The complex casting is needed to obtain the "const" vector of
  677. // uint8_t from the DUID, point to the start of it (discarding the
  678. // "const"ness) and finally casing it to "char*" for the MySQL buffer
  679. // element.
  680. const vector<uint8_t>& duid_vector = duid.getDuid();
  681. unsigned long duid_length = duid_vector.size();
  682. inbind[0].buffer_type = MYSQL_TYPE_BLOB;
  683. inbind[0].buffer = reinterpret_cast<char*>(
  684. const_cast<uint8_t*>(&duid_vector[0]));
  685. inbind[0].buffer_length = duid_length;
  686. inbind[0].length = &duid_length;
  687. // IAID
  688. inbind[1].buffer_type = MYSQL_TYPE_LONG;
  689. inbind[1].buffer = reinterpret_cast<char*>(&iaid);
  690. inbind[1].is_unsigned = static_cast<my_bool>(1);
  691. // Subnet ID
  692. inbind[2].buffer_type = MYSQL_TYPE_LONG;
  693. inbind[2].buffer = reinterpret_cast<char*>(&subnet_id);
  694. inbind[2].is_unsigned = static_cast<my_bool>(1);
  695. // Bind the input parameters to the statement
  696. int status = mysql_stmt_bind_param(statements_[GET_LEASE6_DUID_IAID_SUBID], inbind);
  697. checkError(status, GET_LEASE6_DUID_IAID_SUBID, "unable to bind WHERE clause parameter");
  698. // Set up the SELECT clause
  699. MySqlLease6Exchange exchange;
  700. std::vector<MYSQL_BIND> outbind;
  701. exchange.createBindForReceive(outbind);
  702. // Bind the output parameters to the statement
  703. status = mysql_stmt_bind_result(statements_[GET_LEASE6_DUID_IAID_SUBID], &outbind[0]);
  704. checkError(status, GET_LEASE6_DUID_IAID_SUBID, "unable to bind SELECT clause parameters");
  705. // Execute the query.
  706. status = mysql_stmt_execute(statements_[GET_LEASE6_DUID_IAID_SUBID]);
  707. checkError(status, GET_LEASE6_DUID_IAID_SUBID, "unable to execute");
  708. Lease6Ptr result;
  709. status = mysql_stmt_fetch(statements_[GET_LEASE6_DUID_IAID_SUBID]);
  710. if (status == 0) {
  711. try {
  712. result = exchange.getLeaseData();
  713. // TODO: check for more than one row returned. At present, just ignore
  714. // the excess and take the first.
  715. } catch (const isc::BadValue& ex) {
  716. // Free up result set.
  717. (void) mysql_stmt_free_result(statements_[GET_LEASE6_DUID_IAID_SUBID]);
  718. // Lease type is returned, to rethrow the exception with a bit
  719. // more data.
  720. isc_throw(BadValue, ex.what() << ". Statement is <" <<
  721. text_statements_[GET_LEASE6_DUID_IAID_SUBID] << ">");
  722. }
  723. // As the address is the primary key in the table, we can't return
  724. // two rows, so we don't bother checking whether multiple rows have
  725. // been returned.
  726. } else if (status == 1) {
  727. checkError(status, GET_LEASE6_DUID_IAID_SUBID, "unable to fetch results");
  728. } else {
  729. // @TODO Handle truncation
  730. // We are ignoring truncation for now, so the only other result is
  731. // no data was found. In that case, we return a null Lease6 structure.
  732. // This has already been set, so the action is a no-op.
  733. }
  734. // Free data structures associated with information returned.
  735. (void) mysql_stmt_free_result(statements_[GET_LEASE6_DUID_IAID_SUBID]);
  736. return (result);
  737. }
  738. void
  739. MySqlLeaseMgr::updateLease4(const Lease4Ptr& /* lease4 */) {
  740. isc_throw(NotImplemented, "MySqlLeaseMgr::updateLease4(const Lease4Ptr&) "
  741. "not implemented yet");
  742. }
  743. void
  744. MySqlLeaseMgr::updateLease6(const Lease6Ptr& lease) {
  745. // Create the MYSQL_BIND array for the data being updated
  746. MySqlLease6Exchange exchange;
  747. std::vector<MYSQL_BIND> bind;
  748. exchange.createBindForSend(lease, bind);
  749. // Set up the WHERE clause value
  750. MYSQL_BIND where;
  751. memset(&where, 0, sizeof(where));
  752. std::string addr6 = lease->addr_.toText();
  753. unsigned long addr6_length = addr6.size();
  754. where.buffer_type = MYSQL_TYPE_STRING;
  755. where.buffer = const_cast<char*>(addr6.c_str());
  756. where.buffer_length = addr6_length;
  757. where.length = &addr6_length;
  758. bind.push_back(where);
  759. // Bind the parameters to the statement
  760. int status = mysql_stmt_bind_param(statements_[UPDATE_LEASE6], &bind[0]);
  761. checkError(status, UPDATE_LEASE6, "unable to bind parameters");
  762. // Execute
  763. status = mysql_stmt_execute(statements_[UPDATE_LEASE6]);
  764. checkError(status, UPDATE_LEASE6, "unable to execute");
  765. // See how many rows were affected. The statement should only delete a
  766. // single row.
  767. int affected_rows = mysql_stmt_affected_rows(statements_[UPDATE_LEASE6]);
  768. if (affected_rows == 0) {
  769. isc_throw(NoSuchLease, "unable to update lease for address " <<
  770. addr6 << " as it does not exist");
  771. } else if (affected_rows > 1) {
  772. // Should not happen - primary key constraint should only have selected
  773. // one row.
  774. isc_throw(DbOperationError, "apparently updated more than one lease "
  775. "that had the address " << addr6);
  776. }
  777. }
  778. bool
  779. MySqlLeaseMgr::deleteLease4(const isc::asiolink::IOAddress& /* addr */) {
  780. isc_throw(NotImplemented, "MySqlLeaseMgr::deleteLease4(const IOAddress&) "
  781. "not implemented yet");
  782. return (false);
  783. }
  784. bool
  785. MySqlLeaseMgr::deleteLease6(const isc::asiolink::IOAddress& addr) {
  786. // Set up the WHERE clause value
  787. MYSQL_BIND inbind[1];
  788. memset(inbind, 0, sizeof(inbind));
  789. std::string addr6 = addr.toText();
  790. unsigned long addr6_length = addr6.size();
  791. inbind[0].buffer_type = MYSQL_TYPE_STRING;
  792. inbind[0].buffer = const_cast<char*>(addr6.c_str());
  793. inbind[0].buffer_length = addr6_length;
  794. inbind[0].length = &addr6_length;
  795. // Bind the input parameters to the statement
  796. int status = mysql_stmt_bind_param(statements_[DELETE_LEASE6], inbind);
  797. checkError(status, DELETE_LEASE6, "unable to bind WHERE clause parameter");
  798. // Execute
  799. status = mysql_stmt_execute(statements_[DELETE_LEASE6]);
  800. checkError(status, DELETE_LEASE6, "unable to execute");
  801. // See how many rows were affected. Note that the statement may delete
  802. // multiple rows.
  803. return (mysql_stmt_affected_rows(statements_[DELETE_LEASE6]) > 0);
  804. return false;
  805. }
  806. std::string
  807. MySqlLeaseMgr::getName() const {
  808. std::string name = "";
  809. try {
  810. name = getParameter("name");
  811. } catch (...) {
  812. ;
  813. }
  814. return (name);
  815. }
  816. std::string
  817. MySqlLeaseMgr::getDescription() const {
  818. return (std::string(""));
  819. }
  820. std::pair<uint32_t, uint32_t>
  821. MySqlLeaseMgr::getVersion() const {
  822. uint32_t major; // Major version number
  823. uint32_t minor; // Minor version number
  824. // Execute the prepared statement
  825. int status = mysql_stmt_execute(statements_[GET_VERSION]);
  826. if (status != 0) {
  827. isc_throw(DbOperationError, "unable to execute <"
  828. << text_statements_[GET_VERSION] << "> - reason: " <<
  829. mysql_error(mysql_));
  830. }
  831. // Bind the output of the statement to the appropriate variables.
  832. MYSQL_BIND bind[2];
  833. memset(bind, 0, sizeof(bind));
  834. bind[0].buffer_type = MYSQL_TYPE_LONG;
  835. bind[0].is_unsigned = 1;
  836. bind[0].buffer = &major;
  837. bind[0].buffer_length = sizeof(major);
  838. bind[1].buffer_type = MYSQL_TYPE_LONG;
  839. bind[1].is_unsigned = 1;
  840. bind[1].buffer = &minor;
  841. bind[1].buffer_length = sizeof(minor);
  842. status = mysql_stmt_bind_result(statements_[GET_VERSION], bind);
  843. if (status != 0) {
  844. isc_throw(DbOperationError, "unable to bind result set: " <<
  845. mysql_error(mysql_));
  846. }
  847. // Get the result
  848. status = mysql_stmt_fetch(statements_[GET_VERSION]);
  849. if (status != 0) {
  850. (void) mysql_stmt_free_result(statements_[GET_VERSION]);
  851. isc_throw(DbOperationError, "unable to obtain result set: " <<
  852. mysql_error(mysql_));
  853. }
  854. (void) mysql_stmt_free_result(statements_[GET_VERSION]);
  855. return (std::make_pair(major, minor));
  856. }
  857. void
  858. MySqlLeaseMgr::commit() {
  859. if (mysql_commit(mysql_) != 0) {
  860. isc_throw(DbOperationError, "commit failed: " << mysql_error(mysql_));
  861. }
  862. }
  863. void
  864. MySqlLeaseMgr::rollback() {
  865. if (mysql_rollback(mysql_) != 0) {
  866. isc_throw(DbOperationError, "rollback failed: " << mysql_error(mysql_));
  867. }
  868. }
  869. }; // end of isc::dhcp namespace
  870. }; // end of isc namespace