mysql_lease_mgr.cc 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787
  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 <config.h>
  15. #include <asiolink/io_address.h>
  16. #include <dhcp/duid.h>
  17. #include <dhcp/hwaddr.h>
  18. #include <dhcpsrv/dhcpsrv_log.h>
  19. #include <dhcpsrv/mysql_lease_mgr.h>
  20. #include <boost/static_assert.hpp>
  21. #include <mysql/mysqld_error.h>
  22. #include <iostream>
  23. #include <iomanip>
  24. #include <sstream>
  25. #include <string>
  26. #include <time.h>
  27. using namespace isc;
  28. using namespace isc::dhcp;
  29. using namespace std;
  30. /// @file
  31. ///
  32. /// This file holds the implementation of the Lease Manager using MySQL. The
  33. /// implementation uses MySQL's C API, as it comes as standard with the MySQL
  34. /// client libraries.
  35. ///
  36. /// In general, each of the database access methods corresponds to one SQL
  37. /// statement. To avoid the overhead of parsing a statement every time it is
  38. /// used, when the database is opened "prepared statements" are created -
  39. /// essentially doing the SQL parsing up front. Every time a method is used
  40. /// to access data, the corresponding prepared statement is referenced. Each
  41. /// prepared statement contains a set of placeholders for data, each
  42. /// placeholder being for:
  43. ///
  44. /// - data being added to the database (as in adding or updating a lease)
  45. /// - data being retrieved from the database (as in getting lease information)
  46. /// - selection criteria used to determine which records to update/retrieve.
  47. ///
  48. /// All such data is associated with the prepared statment using an array of
  49. /// MYSQL_BIND structures. Each element in the array corresponds to one
  50. /// parameter in the prepared statement - the first element in the array is
  51. /// associated with the first parameter, the second element with the second
  52. /// parameter etc.
  53. ///
  54. /// Within this file, the setting up of the MYSQL_BIND arrays for data being
  55. /// passed to and retrieved from the database is handled in the
  56. /// isc::dhcp::MySqlLease4Exchange and isc::dhcp::MySqlLease6Exchange classes.
  57. /// The classes also hold intermediate variables required for exchanging some
  58. /// of the data.
  59. ///
  60. /// With these exchange objects in place, many of the methods follow similar
  61. /// logic:
  62. /// - Set up the MYSQL_BIND array for data being transferred to/from the
  63. /// database. For data being transferred to the database, some of the
  64. /// data is extracted from the lease to intermediate variables, whilst
  65. /// in other cases the MYSQL_BIND arrays point to the data in the lease.
  66. /// - Set up the MYSQL_BIND array for the data selection parameters.
  67. /// - Bind these arrays to the prepared statement.
  68. /// - Execute the statement.
  69. /// - If there is output, copy the data from the bound variables to the output
  70. /// lease object.
  71. namespace {
  72. ///@{
  73. /// @brief Maximum size of database fields
  74. ///
  75. /// The following constants define buffer sizes for variable length database
  76. /// fields. The values should be greater than or equal to the length set in
  77. /// the schema definition.
  78. ///
  79. /// The exception is the length of any VARCHAR fields: buffers for these should
  80. /// be set greater than or equal to the length of the field plus 1: this allows
  81. /// for the insertion of a trailing null whatever data is returned.
  82. /// @brief Maximum size of an IPv6 address represented as a text string.
  83. ///
  84. /// This is 32 hexadecimal characters written in 8 groups of four, plus seven
  85. /// colon separators.
  86. const size_t ADDRESS6_TEXT_MAX_LEN = 39;
  87. /// @brief Maximum size of a hardware address.
  88. const size_t HWADDR_MAX_LEN = 20;
  89. /// @brief MySQL True/False constants
  90. ///
  91. /// Declare typed values so as to avoid problems of data conversion. These
  92. /// are local to the file but are given the prefix MLM (MySql Lease Manager) to
  93. /// avoid any likely conflicts with variables in header files named TRUE or
  94. /// FALSE.
  95. const my_bool MLM_FALSE = 0; ///< False value
  96. const my_bool MLM_TRUE = 1; ///< True value
  97. ///@}
  98. /// @brief MySQL Selection Statements
  99. ///
  100. /// Each statement is associated with an index, which is used to reference the
  101. /// associated prepared statement.
  102. struct TaggedStatement {
  103. MySqlLeaseMgr::StatementIndex index;
  104. const char* text;
  105. };
  106. TaggedStatement tagged_statements[] = {
  107. {MySqlLeaseMgr::DELETE_LEASE4,
  108. "DELETE FROM lease4 WHERE address = ?"},
  109. {MySqlLeaseMgr::DELETE_LEASE6,
  110. "DELETE FROM lease6 WHERE address = ?"},
  111. {MySqlLeaseMgr::GET_LEASE4_ADDR,
  112. "SELECT address, hwaddr, client_id, "
  113. "valid_lifetime, expire, subnet_id "
  114. "FROM lease4 "
  115. "WHERE address = ?"},
  116. {MySqlLeaseMgr::GET_LEASE4_CLIENTID,
  117. "SELECT address, hwaddr, client_id, "
  118. "valid_lifetime, expire, subnet_id "
  119. "FROM lease4 "
  120. "WHERE client_id = ?"},
  121. {MySqlLeaseMgr::GET_LEASE4_CLIENTID_SUBID,
  122. "SELECT address, hwaddr, client_id, "
  123. "valid_lifetime, expire, subnet_id "
  124. "FROM lease4 "
  125. "WHERE client_id = ? AND subnet_id = ?"},
  126. {MySqlLeaseMgr::GET_LEASE4_HWADDR,
  127. "SELECT address, hwaddr, client_id, "
  128. "valid_lifetime, expire, subnet_id "
  129. "FROM lease4 "
  130. "WHERE hwaddr = ?"},
  131. {MySqlLeaseMgr::GET_LEASE4_HWADDR_SUBID,
  132. "SELECT address, hwaddr, client_id, "
  133. "valid_lifetime, expire, subnet_id "
  134. "FROM lease4 "
  135. "WHERE hwaddr = ? AND subnet_id = ?"},
  136. {MySqlLeaseMgr::GET_LEASE6_ADDR,
  137. "SELECT address, duid, valid_lifetime, "
  138. "expire, subnet_id, pref_lifetime, "
  139. "lease_type, iaid, prefix_len "
  140. "FROM lease6 "
  141. "WHERE address = ?"},
  142. {MySqlLeaseMgr::GET_LEASE6_DUID_IAID,
  143. "SELECT address, duid, valid_lifetime, "
  144. "expire, subnet_id, pref_lifetime, "
  145. "lease_type, iaid, prefix_len "
  146. "FROM lease6 "
  147. "WHERE duid = ? AND iaid = ?"},
  148. {MySqlLeaseMgr::GET_LEASE6_DUID_IAID_SUBID,
  149. "SELECT address, duid, valid_lifetime, "
  150. "expire, subnet_id, pref_lifetime, "
  151. "lease_type, iaid, prefix_len "
  152. "FROM lease6 "
  153. "WHERE duid = ? AND iaid = ? AND subnet_id = ?"},
  154. {MySqlLeaseMgr::GET_VERSION,
  155. "SELECT version, minor FROM schema_version"},
  156. {MySqlLeaseMgr::INSERT_LEASE4,
  157. "INSERT INTO lease4(address, hwaddr, client_id, "
  158. "valid_lifetime, expire, subnet_id) "
  159. "VALUES (?, ?, ?, ?, ?, ?)"},
  160. {MySqlLeaseMgr::INSERT_LEASE6,
  161. "INSERT INTO lease6(address, duid, valid_lifetime, "
  162. "expire, subnet_id, pref_lifetime, "
  163. "lease_type, iaid, prefix_len) "
  164. "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"},
  165. {MySqlLeaseMgr::UPDATE_LEASE4,
  166. "UPDATE lease4 SET address = ?, hwaddr = ?, "
  167. "client_id = ?, valid_lifetime = ?, expire = ?, "
  168. "subnet_id = ? "
  169. "WHERE address = ?"},
  170. {MySqlLeaseMgr::UPDATE_LEASE6,
  171. "UPDATE lease6 SET address = ?, duid = ?, "
  172. "valid_lifetime = ?, expire = ?, subnet_id = ?, "
  173. "pref_lifetime = ?, lease_type = ?, iaid = ?, "
  174. "prefix_len = ? "
  175. "WHERE address = ?"},
  176. // End of list sentinel
  177. {MySqlLeaseMgr::NUM_STATEMENTS, NULL}
  178. };
  179. // Small RAII object for safer initialization, will close the database
  180. // connection upon destruction, unless release() has been called.
  181. class MySQLHolder {
  182. public:
  183. MySQLHolder(MYSQL* mysql) : mysql_(mysql) {}
  184. ~MySQLHolder() {
  185. if (mysql_) {
  186. mysql_close(mysql_);
  187. }
  188. }
  189. MYSQL* get_ptr() {
  190. return (mysql_);
  191. }
  192. MYSQL* release() {
  193. MYSQL* ptr = mysql_;
  194. mysql_ = NULL;
  195. return (ptr);
  196. }
  197. private:
  198. MYSQL* mysql_;
  199. };
  200. }; // Anonymous namespace
  201. namespace isc {
  202. namespace dhcp {
  203. /// @brief Common MySQL and Lease Data Methods
  204. ///
  205. /// The MySqlLease4Exchange and MySqlLease6Exchange classes provide the
  206. /// functionaility to set up binding information between variables in the
  207. /// program and data extracted from the database. This class is the common
  208. /// base to both of them, containing some common methods.
  209. class MySqlLeaseExchange {
  210. public:
  211. /// @brief Set error indicators
  212. ///
  213. /// Sets the error indicator for each of the MYSQL_BIND elements. It points
  214. /// the "error" field within an element of the input array to the
  215. /// corresponding element of the passed error array.
  216. ///
  217. /// @param bind Array of BIND elements
  218. /// @param error Array of error elements. If there is an error in getting
  219. /// data associated with one of the "bind" elements, the
  220. /// corresponding element in the error array is set to MLM_TRUE.
  221. /// @param count Size of each of the arrays.
  222. void setErrorIndicators(MYSQL_BIND* bind, my_bool* error, size_t count) {
  223. for (size_t i = 0; i < count; ++i) {
  224. error[i] = MLM_FALSE;
  225. bind[i].error = reinterpret_cast<char*>(&error[i]);
  226. }
  227. }
  228. /// @brief Return columns in error
  229. ///
  230. /// If an error is returned from a fetch (in particular, a truncated
  231. /// status), this method can be called to get the names of the fields in
  232. /// error. It returns a string comprising the names of the fields
  233. /// separated by commas. In the case of there being no error indicators
  234. /// set, it returns the string "(None)".
  235. ///
  236. /// @param error Array of error elements. An element is set to MLM_TRUE
  237. /// if the corresponding column in the database is the source of
  238. /// the error.
  239. /// @param names Array of column names, the same size as the error array.
  240. /// @param count Size of each of the arrays.
  241. std::string getColumnsInError(my_bool* error, std::string* names,
  242. size_t count) {
  243. std::string result = "";
  244. // Accumulate list of column names
  245. for (size_t i = 0; i < count; ++i) {
  246. if (error[i] == MLM_TRUE) {
  247. if (!result.empty()) {
  248. result += ", ";
  249. }
  250. result += names[i];
  251. }
  252. }
  253. if (result.empty()) {
  254. result = "(None)";
  255. }
  256. return (result);
  257. }
  258. };
  259. /// @brief Exchange MySQL and Lease4 Data
  260. ///
  261. /// On any MySQL operation, arrays of MYSQL_BIND structures must be built to
  262. /// describe the parameters in the prepared statements. Where information is
  263. /// inserted or retrieved - INSERT, UPDATE, SELECT - a large amount of that
  264. /// structure is identical. This class handles the creation of that array.
  265. ///
  266. /// Owing to the MySQL API, the process requires some intermediate variables
  267. /// to hold things like data length etc. This object holds those variables.
  268. ///
  269. /// @note There are no unit tests for this class. It is tested indirectly
  270. /// in all MySqlLeaseMgr::xxx4() calls where it is used.
  271. class MySqlLease4Exchange : public MySqlLeaseExchange {
  272. /// @brief Set number of database columns for this lease structure
  273. static const size_t LEASE_COLUMNS = 6;
  274. public:
  275. /// @brief Constructor
  276. ///
  277. /// The initialization of the variables here is only to satisfy cppcheck -
  278. /// all variables are initialized/set in the methods before they are used.
  279. MySqlLease4Exchange() : addr4_(0), hwaddr_length_(0), client_id_length_(0) {
  280. memset(hwaddr_buffer_, 0, sizeof(hwaddr_buffer_));
  281. memset(client_id_buffer_, 0, sizeof(client_id_buffer_));
  282. std::fill(&error_[0], &error_[LEASE_COLUMNS], MLM_FALSE);
  283. // Set the column names (for error messages)
  284. columns_[0] = "address";
  285. columns_[1] = "hwaddr";
  286. columns_[2] = "client_id";
  287. columns_[3] = "valid_lifetime";
  288. columns_[4] = "expire";
  289. columns_[5] = "subnet_id";
  290. BOOST_STATIC_ASSERT(5 < LEASE_COLUMNS);
  291. }
  292. /// @brief Create MYSQL_BIND objects for Lease4 Pointer
  293. ///
  294. /// Fills in the MYSQL_BIND array for sending data in the Lease4 object to
  295. /// the database.
  296. ///
  297. /// @param lease Lease object to be added to the database. None of the
  298. /// fields in the lease are modified - the lease data is only read.
  299. ///
  300. /// @return Vector of MySQL BIND objects representing the data to be added.
  301. std::vector<MYSQL_BIND> createBindForSend(const Lease4Ptr& lease) {
  302. // Store lease object to ensure it remains valid.
  303. lease_ = lease;
  304. // Initialize prior to constructing the array of MYSQL_BIND structures.
  305. memset(bind_, 0, sizeof(bind_));
  306. // Set up the structures for the various components of the lease4
  307. // structure.
  308. // Address: uint32_t
  309. // The address in the Lease structure is an IOAddress object. Convert
  310. // this to an integer for storage.
  311. addr4_ = static_cast<uint32_t>(lease_->addr_);
  312. bind_[0].buffer_type = MYSQL_TYPE_LONG;
  313. bind_[0].buffer = reinterpret_cast<char*>(&addr4_);
  314. bind_[0].is_unsigned = MLM_TRUE;
  315. // hwaddr: varbinary(128)
  316. // For speed, we avoid copying the data into temporary storage and
  317. // instead extract it from the lease structure directly.
  318. hwaddr_length_ = lease_->hwaddr_.size();
  319. bind_[1].buffer_type = MYSQL_TYPE_BLOB;
  320. bind_[1].buffer = reinterpret_cast<char*>(&(lease_->hwaddr_[0]));
  321. bind_[1].buffer_length = hwaddr_length_;
  322. bind_[1].length = &hwaddr_length_;
  323. // client_id: varbinary(128)
  324. if (lease_->client_id_) {
  325. client_id_ = lease_->client_id_->getClientId();
  326. client_id_length_ = client_id_.size();
  327. bind_[2].buffer_type = MYSQL_TYPE_BLOB;
  328. bind_[2].buffer = reinterpret_cast<char*>(&client_id_[0]);
  329. bind_[2].buffer_length = client_id_length_;
  330. bind_[2].length = &client_id_length_;
  331. } else {
  332. bind_[2].buffer_type = MYSQL_TYPE_NULL;
  333. // According to http://dev.mysql.com/doc/refman/5.5/en/
  334. // c-api-prepared-statement-data-structures.html, the other
  335. // fields doesn't matter if type is set to MYSQL_TYPE_NULL,
  336. // but let's set them to some sane values in case earlier versions
  337. // didn't have that assumption.
  338. static my_bool no_clientid = MLM_TRUE;
  339. bind_[2].buffer = NULL;
  340. bind_[2].is_null = &no_clientid;
  341. }
  342. // valid lifetime: unsigned int
  343. bind_[3].buffer_type = MYSQL_TYPE_LONG;
  344. bind_[3].buffer = reinterpret_cast<char*>(&lease_->valid_lft_);
  345. bind_[3].is_unsigned = MLM_TRUE;
  346. // expire: timestamp
  347. // The lease structure holds the client last transmission time (cltt_)
  348. // For convenience for external tools, this is converted to lease
  349. // expiry time (expire). The relationship is given by:
  350. //
  351. // expire = cltt_ + valid_lft_
  352. //
  353. // @todo Handle overflows - a large enough valid_lft_ could cause
  354. // an overflow on a 32-bit system.
  355. MySqlLeaseMgr::convertToDatabaseTime(lease_->cltt_, lease_->valid_lft_,
  356. expire_);
  357. bind_[4].buffer_type = MYSQL_TYPE_TIMESTAMP;
  358. bind_[4].buffer = reinterpret_cast<char*>(&expire_);
  359. bind_[4].buffer_length = sizeof(expire_);
  360. // subnet_id: unsigned int
  361. // Can use lease_->subnet_id_ directly as it is of type uint32_t.
  362. bind_[5].buffer_type = MYSQL_TYPE_LONG;
  363. bind_[5].buffer = reinterpret_cast<char*>(&lease_->subnet_id_);
  364. bind_[5].is_unsigned = MLM_TRUE;
  365. // Add the error flags
  366. setErrorIndicators(bind_, error_, LEASE_COLUMNS);
  367. // .. and check that we have the numbers correct at compile time.
  368. BOOST_STATIC_ASSERT(5 < LEASE_COLUMNS);
  369. // Add the data to the vector. Note the end element is one after the
  370. // end of the array.
  371. return (std::vector<MYSQL_BIND>(&bind_[0], &bind_[LEASE_COLUMNS]));
  372. }
  373. /// @brief Create BIND array to receive data
  374. ///
  375. /// Creates a MYSQL_BIND array to receive Lease4 data from the database.
  376. /// After data is successfully received, getLeaseData() can be used to copy
  377. /// it to a Lease6 object.
  378. ///
  379. std::vector<MYSQL_BIND> createBindForReceive() {
  380. // Initialize MYSQL_BIND array.
  381. memset(bind_, 0, sizeof(bind_));
  382. // address: uint32_t
  383. bind_[0].buffer_type = MYSQL_TYPE_LONG;
  384. bind_[0].buffer = reinterpret_cast<char*>(&addr4_);
  385. bind_[0].is_unsigned = MLM_TRUE;
  386. // hwaddr: varbinary(20)
  387. hwaddr_length_ = sizeof(hwaddr_buffer_);
  388. bind_[1].buffer_type = MYSQL_TYPE_BLOB;
  389. bind_[1].buffer = reinterpret_cast<char*>(hwaddr_buffer_);
  390. bind_[1].buffer_length = hwaddr_length_;
  391. bind_[1].length = &hwaddr_length_;
  392. // client_id: varbinary(128)
  393. client_id_length_ = sizeof(client_id_buffer_);
  394. bind_[2].buffer_type = MYSQL_TYPE_BLOB;
  395. bind_[2].buffer = reinterpret_cast<char*>(client_id_buffer_);
  396. bind_[2].buffer_length = client_id_length_;
  397. bind_[2].length = &client_id_length_;
  398. // lease_time: unsigned int
  399. bind_[3].buffer_type = MYSQL_TYPE_LONG;
  400. bind_[3].buffer = reinterpret_cast<char*>(&valid_lifetime_);
  401. bind_[3].is_unsigned = MLM_TRUE;
  402. // expire: timestamp
  403. bind_[4].buffer_type = MYSQL_TYPE_TIMESTAMP;
  404. bind_[4].buffer = reinterpret_cast<char*>(&expire_);
  405. bind_[4].buffer_length = sizeof(expire_);
  406. // subnet_id: unsigned int
  407. bind_[5].buffer_type = MYSQL_TYPE_LONG;
  408. bind_[5].buffer = reinterpret_cast<char*>(&subnet_id_);
  409. bind_[5].is_unsigned = MLM_TRUE;
  410. // Add the error flags
  411. setErrorIndicators(bind_, error_, LEASE_COLUMNS);
  412. // .. and check that we have the numbers correct at compile time.
  413. BOOST_STATIC_ASSERT(5 < LEASE_COLUMNS);
  414. // Add the data to the vector. Note the end element is one after the
  415. // end of the array.
  416. return(std::vector<MYSQL_BIND>(&bind_[0], &bind_[LEASE_COLUMNS]));
  417. }
  418. /// @brief Copy Received Data into Lease6 Object
  419. ///
  420. /// Called after the MYSQL_BIND array created by createBindForReceive()
  421. /// has been used, this copies data from the internal member variables
  422. /// into a Lease4 objec.
  423. ///
  424. /// @return Lease4Ptr Pointer to a Lease6 object holding the relevant
  425. /// data.
  426. Lease4Ptr getLeaseData() {
  427. // Convert times received from the database to times for the lease
  428. // structure
  429. time_t cltt = 0;
  430. MySqlLeaseMgr::convertFromDatabaseTime(expire_, valid_lifetime_, cltt);
  431. // note that T1 and T2 are not stored
  432. return (Lease4Ptr(new Lease4(addr4_, hwaddr_buffer_, hwaddr_length_,
  433. client_id_buffer_, client_id_length_,
  434. valid_lifetime_, 0, 0, cltt, subnet_id_)));
  435. }
  436. /// @brief Return columns in error
  437. ///
  438. /// If an error is returned from a fetch (in particular, a truncated
  439. /// status), this method can be called to get the names of the fields in
  440. /// error. It returns a string comprising the names of the fields
  441. /// separated by commas. In the case of there being no error indicators
  442. /// set, it returns the string "(None)".
  443. ///
  444. /// @return Comma-separated list of columns in error, or the string
  445. /// "(None)".
  446. std::string getErrorColumns() {
  447. return (getColumnsInError(error_, columns_, LEASE_COLUMNS));
  448. }
  449. private:
  450. // Note: All array lengths are equal to the corresponding variable in the
  451. // schema.
  452. // Note: Arrays are declared fixed length for speed of creation
  453. uint32_t addr4_; ///< IPv4 address
  454. MYSQL_BIND bind_[LEASE_COLUMNS]; ///< Bind array
  455. std::string columns_[LEASE_COLUMNS];///< Column names
  456. my_bool error_[LEASE_COLUMNS]; ///< Error array
  457. std::vector<uint8_t> hwaddr_; ///< Hardware address
  458. uint8_t hwaddr_buffer_[HWADDR_MAX_LEN];
  459. ///< Hardware address buffer
  460. unsigned long hwaddr_length_; ///< Hardware address length
  461. std::vector<uint8_t> client_id_; ///< Client identification
  462. uint8_t client_id_buffer_[ClientId::MAX_CLIENT_ID_LEN];
  463. ///< Client ID buffer
  464. unsigned long client_id_length_; ///< Client ID address length
  465. MYSQL_TIME expire_; ///< Lease expiry time
  466. Lease4Ptr lease_; ///< Pointer to lease object
  467. uint32_t subnet_id_; ///< Subnet identification
  468. uint32_t valid_lifetime_; ///< Lease time
  469. };
  470. /// @brief Exchange MySQL and Lease6 Data
  471. ///
  472. /// On any MySQL operation, arrays of MYSQL_BIND structures must be built to
  473. /// describe the parameters in the prepared statements. Where information is
  474. /// inserted or retrieved - INSERT, UPDATE, SELECT - a large amount of that
  475. /// structure is identical. This class handles the creation of that array.
  476. ///
  477. /// Owing to the MySQL API, the process requires some intermediate variables
  478. /// to hold things like data length etc. This object holds those variables.
  479. ///
  480. /// @note There are no unit tests for this class. It is tested indirectly
  481. /// in all MySqlLeaseMgr::xxx6() calls where it is used.
  482. class MySqlLease6Exchange : public MySqlLeaseExchange {
  483. /// @brief Set number of database columns for this lease structure
  484. static const size_t LEASE_COLUMNS = 9;
  485. public:
  486. /// @brief Constructor
  487. ///
  488. /// The initialization of the variables here is nonly to satisfy cppcheck -
  489. /// all variables are initialized/set in the methods before they are used.
  490. MySqlLease6Exchange() : addr6_length_(0), duid_length_(0) {
  491. memset(addr6_buffer_, 0, sizeof(addr6_buffer_));
  492. memset(duid_buffer_, 0, sizeof(duid_buffer_));
  493. std::fill(&error_[0], &error_[LEASE_COLUMNS], MLM_FALSE);
  494. // Set the column names (for error messages)
  495. columns_[0] = "address";
  496. columns_[1] = "duid";
  497. columns_[2] = "valid_lifetime";
  498. columns_[3] = "expire";
  499. columns_[4] = "subnet_id";
  500. columns_[5] = "pref_lifetime";
  501. columns_[6] = "lease_type";
  502. columns_[7] = "iaid";
  503. columns_[8] = "prefix_len";
  504. BOOST_STATIC_ASSERT(8 < LEASE_COLUMNS);
  505. }
  506. /// @brief Create MYSQL_BIND objects for Lease6 Pointer
  507. ///
  508. /// Fills in the MYSQL_BIND array for sending data in the Lease4 object to
  509. /// the database.
  510. ///
  511. /// @param lease Lease object to be added to the database.
  512. ///
  513. /// @return Vector of MySQL BIND objects representing the data to be added.
  514. std::vector<MYSQL_BIND> createBindForSend(const Lease6Ptr& lease) {
  515. // Store lease object to ensure it remains valid.
  516. lease_ = lease;
  517. // Ensure bind_ array clear for constructing the MYSQL_BIND structures
  518. // for this lease.
  519. memset(bind_, 0, sizeof(bind_));
  520. // address: varchar(39)
  521. addr6_ = lease_->addr_.toText();
  522. addr6_length_ = addr6_.size();
  523. // In the following statement, the string is being read. However, the
  524. // MySQL C interface does not use "const", so the "buffer" element
  525. // is declared as "char*" instead of "const char*". To resolve this,
  526. // the "const" is discarded. (Note that the address of addr6_.c_str()
  527. // is guaranteed to be valid until the next non-const operation on
  528. // addr6_.)
  529. //
  530. // The const_cast could be avoided by copying the string to a writeable
  531. // buffer and storing the address of that in the "buffer" element.
  532. // However, this introduces a copy operation (with additional overhead)
  533. // purely to get round the structures introduced by design of the
  534. // MySQL interface (which uses the area pointed to by "buffer" as input
  535. // when specifying query parameters and as output when retrieving data).
  536. // For that reason, "const_cast" has been used.
  537. bind_[0].buffer_type = MYSQL_TYPE_STRING;
  538. bind_[0].buffer = const_cast<char*>(addr6_.c_str());
  539. bind_[0].buffer_length = addr6_length_;
  540. bind_[0].length = &addr6_length_;
  541. // duid: varchar(128)
  542. duid_ = lease_->duid_->getDuid();
  543. duid_length_ = duid_.size();
  544. bind_[1].buffer_type = MYSQL_TYPE_BLOB;
  545. bind_[1].buffer = reinterpret_cast<char*>(&(duid_[0]));
  546. bind_[1].buffer_length = duid_length_;
  547. bind_[1].length = &duid_length_;
  548. // valid lifetime: unsigned int
  549. bind_[2].buffer_type = MYSQL_TYPE_LONG;
  550. bind_[2].buffer = reinterpret_cast<char*>(&lease_->valid_lft_);
  551. bind_[2].is_unsigned = MLM_TRUE;
  552. // expire: timestamp
  553. // The lease structure holds the client last transmission time (cltt_)
  554. // For convenience for external tools, this is converted to lease
  555. /// expiry time (expire). The relationship is given by:
  556. //
  557. // expire = cltt_ + valid_lft_
  558. //
  559. // @todo Handle overflows
  560. MySqlLeaseMgr::convertToDatabaseTime(lease_->cltt_, lease_->valid_lft_,
  561. expire_);
  562. bind_[3].buffer_type = MYSQL_TYPE_TIMESTAMP;
  563. bind_[3].buffer = reinterpret_cast<char*>(&expire_);
  564. bind_[3].buffer_length = sizeof(expire_);
  565. // subnet_id: unsigned int
  566. // Can use lease_->subnet_id_ directly as it is of type uint32_t.
  567. bind_[4].buffer_type = MYSQL_TYPE_LONG;
  568. bind_[4].buffer = reinterpret_cast<char*>(&lease_->subnet_id_);
  569. bind_[4].is_unsigned = MLM_TRUE;
  570. // pref_lifetime: unsigned int
  571. // Can use lease_->preferred_lft_ directly as it is of type uint32_t.
  572. bind_[5].buffer_type = MYSQL_TYPE_LONG;
  573. bind_[5].buffer = reinterpret_cast<char*>(&lease_->preferred_lft_);
  574. bind_[5].is_unsigned = MLM_TRUE;
  575. // lease_type: tinyint
  576. // Must convert to uint8_t as lease_->type_ is a LeaseType variable.
  577. lease_type_ = lease_->type_;
  578. bind_[6].buffer_type = MYSQL_TYPE_TINY;
  579. bind_[6].buffer = reinterpret_cast<char*>(&lease_type_);
  580. bind_[6].is_unsigned = MLM_TRUE;
  581. // iaid: unsigned int
  582. // Can use lease_->iaid_ directly as it is of type uint32_t.
  583. bind_[7].buffer_type = MYSQL_TYPE_LONG;
  584. bind_[7].buffer = reinterpret_cast<char*>(&lease_->iaid_);
  585. bind_[7].is_unsigned = MLM_TRUE;
  586. // prefix_len: unsigned tinyint
  587. // Can use lease_->prefixlen_ directly as it is uint32_t.
  588. bind_[8].buffer_type = MYSQL_TYPE_TINY;
  589. bind_[8].buffer = reinterpret_cast<char*>(&lease_->prefixlen_);
  590. bind_[8].is_unsigned = MLM_TRUE;
  591. // Add the error flags
  592. setErrorIndicators(bind_, error_, LEASE_COLUMNS);
  593. // .. and check that we have the numbers correct at compile time.
  594. BOOST_STATIC_ASSERT(8 < LEASE_COLUMNS);
  595. // Add the data to the vector. Note the end element is one after the
  596. // end of the array.
  597. return (std::vector<MYSQL_BIND>(&bind_[0], &bind_[LEASE_COLUMNS]));
  598. }
  599. /// @brief Create BIND array to receive data
  600. ///
  601. /// Creates a MYSQL_BIND array to receive Lease6 data from the database.
  602. /// After data is successfully received, getLeaseData() is used to copy
  603. /// it to a Lease6 object.
  604. ///
  605. /// @return Vector of MySQL BIND objects passed to the MySQL data retrieval
  606. /// functions.
  607. std::vector<MYSQL_BIND> createBindForReceive() {
  608. // Initialize MYSQL_BIND array.
  609. memset(bind_, 0, sizeof(bind_));
  610. // address: varchar(39)
  611. // A Lease6_ address has a maximum of 39 characters. The array is
  612. // one byte longer than this to guarantee that we can always null
  613. // terminate it whatever is returned.
  614. addr6_length_ = sizeof(addr6_buffer_) - 1;
  615. bind_[0].buffer_type = MYSQL_TYPE_STRING;
  616. bind_[0].buffer = addr6_buffer_;
  617. bind_[0].buffer_length = addr6_length_;
  618. bind_[0].length = &addr6_length_;
  619. // client_id: varbinary(128)
  620. duid_length_ = sizeof(duid_buffer_);
  621. bind_[1].buffer_type = MYSQL_TYPE_BLOB;
  622. bind_[1].buffer = reinterpret_cast<char*>(duid_buffer_);
  623. bind_[1].buffer_length = duid_length_;
  624. bind_[1].length = &duid_length_;
  625. // lease_time: unsigned int
  626. bind_[2].buffer_type = MYSQL_TYPE_LONG;
  627. bind_[2].buffer = reinterpret_cast<char*>(&valid_lifetime_);
  628. bind_[2].is_unsigned = MLM_TRUE;
  629. // expire: timestamp
  630. bind_[3].buffer_type = MYSQL_TYPE_TIMESTAMP;
  631. bind_[3].buffer = reinterpret_cast<char*>(&expire_);
  632. bind_[3].buffer_length = sizeof(expire_);
  633. // subnet_id: unsigned int
  634. bind_[4].buffer_type = MYSQL_TYPE_LONG;
  635. bind_[4].buffer = reinterpret_cast<char*>(&subnet_id_);
  636. bind_[4].is_unsigned = MLM_TRUE;
  637. // pref_lifetime: unsigned int
  638. bind_[5].buffer_type = MYSQL_TYPE_LONG;
  639. bind_[5].buffer = reinterpret_cast<char*>(&pref_lifetime_);
  640. bind_[5].is_unsigned = MLM_TRUE;
  641. // lease_type: tinyint
  642. bind_[6].buffer_type = MYSQL_TYPE_TINY;
  643. bind_[6].buffer = reinterpret_cast<char*>(&lease_type_);
  644. bind_[6].is_unsigned = MLM_TRUE;
  645. // iaid: unsigned int
  646. bind_[7].buffer_type = MYSQL_TYPE_LONG;
  647. bind_[7].buffer = reinterpret_cast<char*>(&iaid_);
  648. bind_[7].is_unsigned = MLM_TRUE;
  649. // prefix_len: unsigned tinyint
  650. bind_[8].buffer_type = MYSQL_TYPE_TINY;
  651. bind_[8].buffer = reinterpret_cast<char*>(&prefixlen_);
  652. bind_[8].is_unsigned = MLM_TRUE;
  653. // Add the error flags
  654. setErrorIndicators(bind_, error_, LEASE_COLUMNS);
  655. // .. and check that we have the numbers correct at compile time.
  656. BOOST_STATIC_ASSERT(8 < LEASE_COLUMNS);
  657. // Add the data to the vector. Note the end element is one after the
  658. // end of the array.
  659. return(std::vector<MYSQL_BIND>(&bind_[0], &bind_[LEASE_COLUMNS]));
  660. }
  661. /// @brief Copy Received Data into Lease6 Object
  662. ///
  663. /// Called after the MYSQL_BIND array created by createBindForReceive()
  664. /// has been used, this copies data from the internal member variables
  665. /// into a Lease6 object.
  666. ///
  667. /// @return Lease6Ptr Pointer to a Lease6 object holding the relevant
  668. /// data.
  669. ///
  670. /// @throw isc::BadValue Unable to convert Lease Type value in database
  671. Lease6Ptr getLeaseData() {
  672. // The address buffer is declared larger than the buffer size passed
  673. // to the access function so that we can always append a null byte.
  674. // Create the IOAddress object corresponding to the received data.
  675. addr6_buffer_[addr6_length_] = '\0';
  676. std::string address = addr6_buffer_;
  677. isc::asiolink::IOAddress addr(address);
  678. // Set the lease type in a variable of the appropriate data type, which
  679. // has been initialized with an arbitrary (but valid) value.
  680. Lease6::LeaseType type = Lease6::LEASE_IA_NA;
  681. switch (lease_type_) {
  682. case Lease6::LEASE_IA_NA:
  683. type = Lease6::LEASE_IA_NA;
  684. break;
  685. case Lease6::LEASE_IA_TA:
  686. type = Lease6::LEASE_IA_TA;
  687. break;
  688. case Lease6::LEASE_IA_PD:
  689. type = Lease6::LEASE_IA_PD;
  690. break;
  691. default:
  692. isc_throw(BadValue, "invalid lease type returned (" <<
  693. lease_type_ << ") for lease with address " <<
  694. address << ". Only 0, 1, or 2 are allowed.");
  695. }
  696. // Set up DUID,
  697. DuidPtr duid_ptr(new DUID(duid_buffer_, duid_length_));
  698. // Create the lease and set the cltt (after converting from the
  699. // expire time retrieved from the database).
  700. Lease6Ptr result(new Lease6(type, addr, duid_ptr, iaid_,
  701. pref_lifetime_, valid_lifetime_, 0, 0,
  702. subnet_id_, prefixlen_));
  703. time_t cltt = 0;
  704. MySqlLeaseMgr::convertFromDatabaseTime(expire_, valid_lifetime_, cltt);
  705. result->cltt_ = cltt;
  706. return (result);
  707. }
  708. /// @brief Return columns in error
  709. ///
  710. /// If an error is returned from a fetch (in particular, a truncated
  711. /// status), this method can be called to get the names of the fields in
  712. /// error. It returns a string comprising the names of the fields
  713. /// separated by commas. In the case of there being no error indicators
  714. /// set, it returns the string "(None)".
  715. ///
  716. /// @return Comma-separated list of columns in error, or the string
  717. /// "(None)".
  718. std::string getErrorColumns() {
  719. return (getColumnsInError(error_, columns_, LEASE_COLUMNS));
  720. }
  721. private:
  722. // Note: All array lengths are equal to the corresponding variable in the
  723. // schema.
  724. // Note: arrays are declared fixed length for speed of creation
  725. std::string addr6_; ///< String form of address
  726. char addr6_buffer_[ADDRESS6_TEXT_MAX_LEN + 1]; ///< Character
  727. ///< array form of V6 address
  728. unsigned long addr6_length_; ///< Length of the address
  729. MYSQL_BIND bind_[LEASE_COLUMNS]; ///< Bind array
  730. std::string columns_[LEASE_COLUMNS];///< Column names
  731. std::vector<uint8_t> duid_; ///< Client identification
  732. uint8_t duid_buffer_[DUID::MAX_DUID_LEN]; ///< Buffer form of DUID
  733. unsigned long duid_length_; ///< Length of the DUID
  734. my_bool error_[LEASE_COLUMNS]; ///< Error indicators
  735. MYSQL_TIME expire_; ///< Lease expiry time
  736. uint32_t iaid_; ///< Identity association ID
  737. Lease6Ptr lease_; ///< Pointer to lease object
  738. uint8_t lease_type_; ///< Lease type
  739. uint8_t prefixlen_; ///< Prefix length
  740. uint32_t pref_lifetime_; ///< Preferred lifetime
  741. uint32_t subnet_id_; ///< Subnet identification
  742. uint32_t valid_lifetime_; ///< Lease time
  743. };
  744. /// @brief Fetch and Release MySQL Results
  745. ///
  746. /// When a MySQL statement is exected, to fetch the results the function
  747. /// mysql_stmt_fetch() must be called. As well as getting data, this
  748. /// allocates internal state. Subsequent calls to mysql_stmt_fetch can be
  749. /// made, but when all the data is retrieved, mysql_stmt_free_result must be
  750. /// called to free up the resources allocated.
  751. ///
  752. /// Created prior to the first fetch, this class's destructor calls
  753. /// mysql_stmt_free_result, so eliminating the need for an explicit release
  754. /// in the method calling mysql_stmt_free_result. In this way, it guarantees
  755. /// that the resources are released even if the MySqlLeaseMgr method concerned
  756. /// exits via an exception.
  757. class MySqlFreeResult {
  758. public:
  759. /// @brief Constructor
  760. ///
  761. /// Store the pointer to the statement for which data is being fetched.
  762. ///
  763. /// Note that according to the MySQL documentation, mysql_stmt_free_result
  764. /// only releases resources if a cursor has been allocated for the
  765. /// statement. This implies that it is a no-op if none have been. Either
  766. /// way, any error from mysql_stmt_free_result is ignored. (Generating
  767. /// an exception is not much help, as it will only confuse things if the
  768. /// method calling mysql_stmt_fetch is exiting via an exception.)
  769. MySqlFreeResult(MYSQL_STMT* statement) : statement_(statement)
  770. {}
  771. /// @brief Destructor
  772. ///
  773. /// Frees up fetch context if a fetch has been successfully executed.
  774. ~MySqlFreeResult() {
  775. (void) mysql_stmt_free_result(statement_);
  776. }
  777. private:
  778. MYSQL_STMT* statement_; ///< Statement for which results are freed
  779. };
  780. // MySqlLeaseMgr Constructor and Destructor
  781. MySqlLeaseMgr::MySqlLeaseMgr(const LeaseMgr::ParameterMap& parameters)
  782. : LeaseMgr(parameters), mysql_(NULL) {
  783. // Allocate context for MySQL
  784. MySQLHolder mysql_holder(mysql_init(NULL));
  785. mysql_ = mysql_holder.get_ptr();
  786. if (mysql_ == NULL) {
  787. isc_throw(DbOpenError, "unable to initialize MySQL");
  788. }
  789. // Open the database.
  790. openDatabase();
  791. // Enable autocommit. To avoid a flush to disk on every commit, the global
  792. // parameter innodb_flush_log_at_trx_commit should be set to 2. This will
  793. // cause the changes to be written to the log, but flushed to disk in the
  794. // background every second. Setting the parameter to that value will speed
  795. // up the system, but at the risk of losing data if the system crashes.
  796. my_bool result = mysql_autocommit(mysql_, 1);
  797. if (result != 0) {
  798. isc_throw(DbOperationError, mysql_error(mysql_));
  799. }
  800. // Prepare all statements likely to be used.
  801. prepareStatements();
  802. // Create the exchange objects for use in exchanging data between the
  803. // program and the database.
  804. exchange4_.reset(new MySqlLease4Exchange());
  805. exchange6_.reset(new MySqlLease6Exchange());
  806. // Let the real destructor take care of cleaning up now
  807. mysql_holder.release();
  808. }
  809. MySqlLeaseMgr::~MySqlLeaseMgr() {
  810. // Free up the prepared statements, ignoring errors. (What would we do
  811. // about them? We're destroying this object and are not really concerned
  812. // with errors on a database connection that is about to go away.)
  813. for (int i = 0; i < statements_.size(); ++i) {
  814. if (statements_[i] != NULL) {
  815. (void) mysql_stmt_close(statements_[i]);
  816. statements_[i] = NULL;
  817. }
  818. }
  819. // Close the database
  820. mysql_close(mysql_);
  821. mysql_ = NULL;
  822. }
  823. // Time conversion methods.
  824. //
  825. // Note that the MySQL TIMESTAMP data type (used for "expire") converts data
  826. // from the current timezone to UTC for storage, and from UTC to the current
  827. // timezone for retrieval.
  828. //
  829. // This causes no problems providing that:
  830. // a) cltt is given in local time
  831. // b) We let the system take care of timezone conversion when converting
  832. // from a time read from the database into a local time.
  833. void
  834. MySqlLeaseMgr::convertToDatabaseTime(time_t cltt, uint32_t valid_lifetime,
  835. MYSQL_TIME& expire) {
  836. // Calculate expiry time.
  837. // @TODO: handle overflows
  838. time_t expire_time = cltt + valid_lifetime;
  839. // Convert to broken-out time
  840. struct tm expire_tm;
  841. (void) localtime_r(&expire_time, &expire_tm);
  842. // Place in output expire structure.
  843. expire.year = expire_tm.tm_year + 1900;
  844. expire.month = expire_tm.tm_mon + 1; // Note different base
  845. expire.day = expire_tm.tm_mday;
  846. expire.hour = expire_tm.tm_hour;
  847. expire.minute = expire_tm.tm_min;
  848. expire.second = expire_tm.tm_sec;
  849. expire.second_part = 0; // No fractional seconds
  850. expire.neg = my_bool(0); // Not negative
  851. }
  852. void
  853. MySqlLeaseMgr::convertFromDatabaseTime(const MYSQL_TIME& expire,
  854. uint32_t valid_lifetime, time_t& cltt) {
  855. // Copy across fields from MYSQL_TIME structure.
  856. struct tm expire_tm;
  857. memset(&expire_tm, 0, sizeof(expire_tm));
  858. expire_tm.tm_year = expire.year - 1900;
  859. expire_tm.tm_mon = expire.month - 1;
  860. expire_tm.tm_mday = expire.day;
  861. expire_tm.tm_hour = expire.hour;
  862. expire_tm.tm_min = expire.minute;
  863. expire_tm.tm_sec = expire.second;
  864. expire_tm.tm_isdst = -1; // Let the system work out about DST
  865. // Convert to local time
  866. cltt = mktime(&expire_tm) - valid_lifetime;
  867. }
  868. // Open the database using the parameters passed to the constructor.
  869. void
  870. MySqlLeaseMgr::openDatabase() {
  871. // Set up the values of the parameters
  872. const char* host = "localhost";
  873. string shost;
  874. try {
  875. shost = getParameter("host");
  876. host = shost.c_str();
  877. } catch (...) {
  878. // No host. Fine, we'll use "localhost"
  879. }
  880. const char* user = NULL;
  881. string suser;
  882. try {
  883. suser = getParameter("user");
  884. user = suser.c_str();
  885. } catch (...) {
  886. // No user. Fine, we'll use NULL
  887. }
  888. const char* password = NULL;
  889. string spassword;
  890. try {
  891. spassword = getParameter("password");
  892. password = spassword.c_str();
  893. } catch (...) {
  894. // No password. Fine, we'll use NULL
  895. }
  896. const char* name = NULL;
  897. string sname;
  898. try {
  899. sname = getParameter("name");
  900. name = sname.c_str();
  901. } catch (...) {
  902. // No database name. Throw a "NoName" exception
  903. isc_throw(NoDatabaseName, "must specified a name for the database");
  904. }
  905. // Set options for the connection:
  906. //
  907. // Automatic reconnection: after a period of inactivity, the client will
  908. // disconnect from the database. This option causes it to automatically
  909. // reconnect when another operation is about to be done.
  910. my_bool auto_reconnect = MLM_TRUE;
  911. int result = mysql_options(mysql_, MYSQL_OPT_RECONNECT, &auto_reconnect);
  912. if (result != 0) {
  913. isc_throw(DbOpenError, "unable to set auto-reconnect option: " <<
  914. mysql_error(mysql_));
  915. }
  916. // Open the database.
  917. //
  918. // The option CLIENT_FOUND_ROWS is specified so that in an UPDATE,
  919. // the affected rows are the number of rows found that match the
  920. // WHERE clause of the SQL statement, not the rows changed. The reason
  921. // here is that MySQL apparently does not update a row if data has not
  922. // changed and so the "affected rows" (retrievable from MySQL) is zero.
  923. // This makes it hard to distinguish whether the UPDATE changed no rows
  924. // because no row matching the WHERE clause was found, or because a
  925. // row was found but no data was altered.
  926. MYSQL* status = mysql_real_connect(mysql_, host, user, password, name,
  927. 0, NULL, CLIENT_FOUND_ROWS);
  928. if (status != mysql_) {
  929. isc_throw(DbOpenError, mysql_error(mysql_));
  930. }
  931. }
  932. // Prepared statement setup. The textual form of an SQL statement is stored
  933. // in a vector of strings (text_statements_) and is used in the output of
  934. // error messages. The SQL statement is also compiled into a "prepared
  935. // statement" (stored in statements_), which avoids the overhead of compilation
  936. // during use. As prepared statements have resources allocated to them, the
  937. // class destructor explicitly destroys them.
  938. void
  939. MySqlLeaseMgr::prepareStatement(StatementIndex index, const char* text) {
  940. // Validate that there is space for the statement in the statements array
  941. // and that nothing has been placed there before.
  942. if ((index >= statements_.size()) || (statements_[index] != NULL)) {
  943. isc_throw(InvalidParameter, "invalid prepared statement index (" <<
  944. static_cast<int>(index) << ") or indexed prepared " <<
  945. "statement is not null");
  946. }
  947. // All OK, so prepare the statement
  948. text_statements_[index] = std::string(text);
  949. statements_[index] = mysql_stmt_init(mysql_);
  950. if (statements_[index] == NULL) {
  951. isc_throw(DbOperationError, "unable to allocate MySQL prepared "
  952. "statement structure, reason: " << mysql_error(mysql_));
  953. }
  954. int status = mysql_stmt_prepare(statements_[index], text, strlen(text));
  955. if (status != 0) {
  956. isc_throw(DbOperationError, "unable to prepare MySQL statement <" <<
  957. text << ">, reason: " << mysql_error(mysql_));
  958. }
  959. }
  960. void
  961. MySqlLeaseMgr::prepareStatements() {
  962. // Allocate space for all statements
  963. statements_.clear();
  964. statements_.resize(NUM_STATEMENTS, NULL);
  965. text_statements_.clear();
  966. text_statements_.resize(NUM_STATEMENTS, std::string(""));
  967. // Created the MySQL prepared statements for each DML statement.
  968. for (int i = 0; tagged_statements[i].text != NULL; ++i) {
  969. prepareStatement(tagged_statements[i].index,
  970. tagged_statements[i].text);
  971. }
  972. }
  973. // Add leases to the database. The two public methods accept a lease object
  974. // (either V4 of V6), bind the contents to the appropriate prepared
  975. // statement, then call common code to execute the statement.
  976. bool
  977. MySqlLeaseMgr::addLeaseCommon(StatementIndex stindex,
  978. std::vector<MYSQL_BIND>& bind) {
  979. // Bind the parameters to the statement
  980. int status = mysql_stmt_bind_param(statements_[stindex], &bind[0]);
  981. checkError(status, stindex, "unable to bind parameters");
  982. // Execute the statement
  983. status = mysql_stmt_execute(statements_[stindex]);
  984. if (status != 0) {
  985. // Failure: check for the special case of duplicate entry. If this is
  986. // the case, we return false to indicate that the row was not added.
  987. // Otherwise we throw an exception.
  988. if (mysql_errno(mysql_) == ER_DUP_ENTRY) {
  989. return (false);
  990. }
  991. checkError(status, stindex, "unable to execute");
  992. }
  993. // Insert succeeded
  994. return (true);
  995. }
  996. bool
  997. MySqlLeaseMgr::addLease(const Lease4Ptr& lease) {
  998. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  999. DHCPSRV_MYSQL_ADD_ADDR4).arg(lease->addr_.toText());
  1000. // Create the MYSQL_BIND array for the lease
  1001. std::vector<MYSQL_BIND> bind = exchange4_->createBindForSend(lease);
  1002. // ... and drop to common code.
  1003. return (addLeaseCommon(INSERT_LEASE4, bind));
  1004. }
  1005. bool
  1006. MySqlLeaseMgr::addLease(const Lease6Ptr& lease) {
  1007. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1008. DHCPSRV_MYSQL_ADD_ADDR6).arg(lease->addr_.toText());
  1009. // Create the MYSQL_BIND array for the lease
  1010. std::vector<MYSQL_BIND> bind = exchange6_->createBindForSend(lease);
  1011. // ... and drop to common code.
  1012. return (addLeaseCommon(INSERT_LEASE6, bind));
  1013. }
  1014. // Extraction of leases from the database.
  1015. //
  1016. // All getLease() methods ultimately call getLeaseCollection(). This
  1017. // binds the input parameters passed to it with the appropriate prepared
  1018. // statement and executes the statement. It then gets the results from the
  1019. // database. getlease() methods that expect a single result back call it
  1020. // with the "single" parameter set true: this causes an exception to be
  1021. // generated if multiple records can be retrieved from the result set. (Such
  1022. // an occurrence either indicates corruption in the database, or that an
  1023. // assumption that a query can only return a single record is incorrect.)
  1024. // Methods that require a collection of records have "single" set to the
  1025. // default value of false. The logic is the same for both Lease4 and Lease6
  1026. // objects, so the code is templated.
  1027. //
  1028. // Methods that require a collection of objects access this method through
  1029. // two interface methods (also called getLeaseCollection()). These are
  1030. // short enough as to be defined in the header file: all they do is to supply
  1031. // the appropriate MySqlLeaseXExchange object depending on the type of the
  1032. // LeaseCollection objects passed to them.
  1033. //
  1034. // Methods that require a single object to be returned access the method
  1035. // through two interface methods (called getLease()). As well as supplying
  1036. // the appropriate exchange object, they convert between lease collection
  1037. // holding zero or one leases into an appropriate Lease object.
  1038. template <typename Exchange, typename LeaseCollection>
  1039. void MySqlLeaseMgr::getLeaseCollection(StatementIndex stindex,
  1040. MYSQL_BIND* bind,
  1041. Exchange& exchange,
  1042. LeaseCollection& result,
  1043. bool single) const {
  1044. // Bind the selection parameters to the statement
  1045. int status = mysql_stmt_bind_param(statements_[stindex], bind);
  1046. checkError(status, stindex, "unable to bind WHERE clause parameter");
  1047. // Set up the MYSQL_BIND array for the data being returned and bind it to
  1048. // the statement.
  1049. std::vector<MYSQL_BIND> outbind = exchange->createBindForReceive();
  1050. status = mysql_stmt_bind_result(statements_[stindex], &outbind[0]);
  1051. checkError(status, stindex, "unable to bind SELECT clause parameters");
  1052. // Execute the statement
  1053. status = mysql_stmt_execute(statements_[stindex]);
  1054. checkError(status, stindex, "unable to execute");
  1055. // Ensure that all the lease information is retrieved in one go to avoid
  1056. // overhead of going back and forth between client and server.
  1057. status = mysql_stmt_store_result(statements_[stindex]);
  1058. checkError(status, stindex, "unable to set up for storing all results");
  1059. // Set up the fetch "release" object to release resources associated
  1060. // with the call to mysql_stmt_fetch when this method exits, then
  1061. // retrieve the data.
  1062. MySqlFreeResult fetch_release(statements_[stindex]);
  1063. int count = 0;
  1064. while ((status = mysql_stmt_fetch(statements_[stindex])) == 0) {
  1065. try {
  1066. result.push_back(exchange->getLeaseData());
  1067. } catch (const isc::BadValue& ex) {
  1068. // Rethrow the exception with a bit more data.
  1069. isc_throw(BadValue, ex.what() << ". Statement is <" <<
  1070. text_statements_[stindex] << ">");
  1071. }
  1072. if (single && (++count > 1)) {
  1073. isc_throw(MultipleRecords, "multiple records were found in the "
  1074. "database where only one was expected for query "
  1075. << text_statements_[stindex]);
  1076. }
  1077. }
  1078. // How did the fetch end?
  1079. if (status == 1) {
  1080. // Error - unable to fetch results
  1081. checkError(status, stindex, "unable to fetch results");
  1082. } else if (status == MYSQL_DATA_TRUNCATED) {
  1083. // Data truncated - throw an exception indicating what was at fault
  1084. isc_throw(DataTruncated, text_statements_[stindex]
  1085. << " returned truncated data: columns affected are "
  1086. << exchange->getErrorColumns());
  1087. }
  1088. }
  1089. void MySqlLeaseMgr::getLease(StatementIndex stindex, MYSQL_BIND* bind,
  1090. Lease4Ptr& result) const {
  1091. // Create appropriate collection object and get all leases matching
  1092. // the selection criteria. The "single" paraeter is true to indicate
  1093. // that the called method should throw an exception if multiple
  1094. // matching records are found: this particular method is called when only
  1095. // one or zero matches is expected.
  1096. Lease4Collection collection;
  1097. getLeaseCollection(stindex, bind, exchange4_, collection, true);
  1098. // Return single record if present, else clear the lease.
  1099. if (collection.empty()) {
  1100. result.reset();
  1101. } else {
  1102. result = *collection.begin();
  1103. }
  1104. }
  1105. void MySqlLeaseMgr::getLease(StatementIndex stindex, MYSQL_BIND* bind,
  1106. Lease6Ptr& result) const {
  1107. // Create appropriate collection object and get all leases matching
  1108. // the selection criteria. The "single" paraeter is true to indicate
  1109. // that the called method should throw an exception if multiple
  1110. // matching records are found: this particular method is called when only
  1111. // one or zero matches is expected.
  1112. Lease6Collection collection;
  1113. getLeaseCollection(stindex, bind, exchange6_, collection, true);
  1114. // Return single record if present, else clear the lease.
  1115. if (collection.empty()) {
  1116. result.reset();
  1117. } else {
  1118. result = *collection.begin();
  1119. }
  1120. }
  1121. // Basic lease access methods. Obtain leases from the database using various
  1122. // criteria.
  1123. Lease4Ptr
  1124. MySqlLeaseMgr::getLease4(const isc::asiolink::IOAddress& addr) const {
  1125. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1126. DHCPSRV_MYSQL_GET_ADDR4).arg(addr.toText());
  1127. // Set up the WHERE clause value
  1128. MYSQL_BIND inbind[1];
  1129. memset(inbind, 0, sizeof(inbind));
  1130. uint32_t addr4 = static_cast<uint32_t>(addr);
  1131. inbind[0].buffer_type = MYSQL_TYPE_LONG;
  1132. inbind[0].buffer = reinterpret_cast<char*>(&addr4);
  1133. inbind[0].is_unsigned = MLM_TRUE;
  1134. // Get the data
  1135. Lease4Ptr result;
  1136. getLease(GET_LEASE4_ADDR, inbind, result);
  1137. return (result);
  1138. }
  1139. Lease4Collection
  1140. MySqlLeaseMgr::getLease4(const HWAddr& hwaddr) const {
  1141. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1142. DHCPSRV_MYSQL_GET_HWADDR).arg(hwaddr.toText());
  1143. // Set up the WHERE clause value
  1144. MYSQL_BIND inbind[1];
  1145. memset(inbind, 0, sizeof(inbind));
  1146. // As "buffer" is "char*" - even though the data is being read - we need
  1147. // to cast away the "const"ness as well as reinterpreting the data as
  1148. // a "char*". (We could avoid the "const_cast" by copying the data to a
  1149. // local variable, but as the data is only being read, this introduces
  1150. // an unnecessary copy).
  1151. unsigned long hwaddr_length = hwaddr.hwaddr_.size();
  1152. uint8_t* data = const_cast<uint8_t*>(&hwaddr.hwaddr_[0]);
  1153. inbind[0].buffer_type = MYSQL_TYPE_BLOB;
  1154. inbind[0].buffer = reinterpret_cast<char*>(data);
  1155. inbind[0].buffer_length = hwaddr_length;
  1156. inbind[0].length = &hwaddr_length;
  1157. // Get the data
  1158. Lease4Collection result;
  1159. getLeaseCollection(GET_LEASE4_HWADDR, inbind, result);
  1160. return (result);
  1161. }
  1162. Lease4Ptr
  1163. MySqlLeaseMgr::getLease4(const HWAddr& hwaddr, SubnetID subnet_id) const {
  1164. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1165. DHCPSRV_MYSQL_GET_SUBID_HWADDR)
  1166. .arg(subnet_id).arg(hwaddr.toText());
  1167. // Set up the WHERE clause value
  1168. MYSQL_BIND inbind[2];
  1169. memset(inbind, 0, sizeof(inbind));
  1170. // As "buffer" is "char*" - even though the data is being read - we need
  1171. // to cast away the "const"ness as well as reinterpreting the data as
  1172. // a "char*". (We could avoid the "const_cast" by copying the data to a
  1173. // local variable, but as the data is only being read, this introduces
  1174. // an unnecessary copy).
  1175. unsigned long hwaddr_length = hwaddr.hwaddr_.size();
  1176. uint8_t* data = const_cast<uint8_t*>(&hwaddr.hwaddr_[0]);
  1177. inbind[0].buffer_type = MYSQL_TYPE_BLOB;
  1178. inbind[0].buffer = reinterpret_cast<char*>(data);
  1179. inbind[0].buffer_length = hwaddr_length;
  1180. inbind[0].length = &hwaddr_length;
  1181. inbind[1].buffer_type = MYSQL_TYPE_LONG;
  1182. inbind[1].buffer = reinterpret_cast<char*>(&subnet_id);
  1183. inbind[1].is_unsigned = MLM_TRUE;
  1184. // Get the data
  1185. Lease4Ptr result;
  1186. getLease(GET_LEASE4_HWADDR_SUBID, inbind, result);
  1187. return (result);
  1188. }
  1189. Lease4Collection
  1190. MySqlLeaseMgr::getLease4(const ClientId& clientid) const {
  1191. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1192. DHCPSRV_MYSQL_GET_CLIENTID).arg(clientid.toText());
  1193. // Set up the WHERE clause value
  1194. MYSQL_BIND inbind[1];
  1195. memset(inbind, 0, sizeof(inbind));
  1196. std::vector<uint8_t> client_data = clientid.getClientId();
  1197. unsigned long client_data_length = client_data.size();
  1198. inbind[0].buffer_type = MYSQL_TYPE_BLOB;
  1199. inbind[0].buffer = reinterpret_cast<char*>(&client_data[0]);
  1200. inbind[0].buffer_length = client_data_length;
  1201. inbind[0].length = &client_data_length;
  1202. // Get the data
  1203. Lease4Collection result;
  1204. getLeaseCollection(GET_LEASE4_CLIENTID, inbind, result);
  1205. return (result);
  1206. }
  1207. Lease4Ptr
  1208. MySqlLeaseMgr::getLease4(const ClientId& clientid, SubnetID subnet_id) const {
  1209. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1210. DHCPSRV_MYSQL_GET_SUBID_CLIENTID)
  1211. .arg(subnet_id).arg(clientid.toText());
  1212. // Set up the WHERE clause value
  1213. MYSQL_BIND inbind[2];
  1214. memset(inbind, 0, sizeof(inbind));
  1215. std::vector<uint8_t> client_data = clientid.getClientId();
  1216. unsigned long client_data_length = client_data.size();
  1217. inbind[0].buffer_type = MYSQL_TYPE_BLOB;
  1218. inbind[0].buffer = reinterpret_cast<char*>(&client_data[0]);
  1219. inbind[0].buffer_length = client_data_length;
  1220. inbind[0].length = &client_data_length;
  1221. inbind[1].buffer_type = MYSQL_TYPE_LONG;
  1222. inbind[1].buffer = reinterpret_cast<char*>(&subnet_id);
  1223. inbind[1].is_unsigned = MLM_TRUE;
  1224. // Get the data
  1225. Lease4Ptr result;
  1226. getLease(GET_LEASE4_CLIENTID_SUBID, inbind, result);
  1227. return (result);
  1228. }
  1229. Lease6Ptr
  1230. MySqlLeaseMgr::getLease6(const isc::asiolink::IOAddress& addr) const {
  1231. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1232. DHCPSRV_MYSQL_GET_ADDR6).arg(addr.toText());
  1233. // Set up the WHERE clause value
  1234. MYSQL_BIND inbind[1];
  1235. memset(inbind, 0, sizeof(inbind));
  1236. std::string addr6 = addr.toText();
  1237. unsigned long addr6_length = addr6.size();
  1238. // See the earlier description of the use of "const_cast" when accessing
  1239. // the address for an explanation of the reason.
  1240. inbind[0].buffer_type = MYSQL_TYPE_STRING;
  1241. inbind[0].buffer = const_cast<char*>(addr6.c_str());
  1242. inbind[0].buffer_length = addr6_length;
  1243. inbind[0].length = &addr6_length;
  1244. Lease6Ptr result;
  1245. getLease(GET_LEASE6_ADDR, inbind, result);
  1246. return (result);
  1247. }
  1248. Lease6Collection
  1249. MySqlLeaseMgr::getLease6(const DUID& duid, uint32_t iaid) const {
  1250. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1251. DHCPSRV_MYSQL_GET_IAID_DUID).arg(iaid).arg(duid.toText());
  1252. // Set up the WHERE clause value
  1253. MYSQL_BIND inbind[2];
  1254. memset(inbind, 0, sizeof(inbind));
  1255. // In the following statement, the DUID is being read. However, the
  1256. // MySQL C interface does not use "const", so the "buffer" element
  1257. // is declared as "char*" instead of "const char*". To resolve this,
  1258. // the "const" is discarded before the uint8_t* is cast to char*.
  1259. //
  1260. // Note that the const_cast could be avoided by copying the DUID to
  1261. // a writeable buffer and storing the address of that in the "buffer"
  1262. // element. However, this introduces a copy operation (with additional
  1263. // overhead) purely to get round the structures introduced by design of
  1264. // the MySQL interface (which uses the area pointed to by "buffer" as
  1265. // input when specifying query parameters and as output when retrieving
  1266. // data). For that reason, "const_cast" has been used.
  1267. const vector<uint8_t>& duid_vector = duid.getDuid();
  1268. unsigned long duid_length = duid_vector.size();
  1269. inbind[0].buffer_type = MYSQL_TYPE_BLOB;
  1270. inbind[0].buffer = reinterpret_cast<char*>(
  1271. const_cast<uint8_t*>(&duid_vector[0]));
  1272. inbind[0].buffer_length = duid_length;
  1273. inbind[0].length = &duid_length;
  1274. // IAID
  1275. inbind[1].buffer_type = MYSQL_TYPE_LONG;
  1276. inbind[1].buffer = reinterpret_cast<char*>(&iaid);
  1277. inbind[1].is_unsigned = MLM_TRUE;
  1278. // ... and get the data
  1279. Lease6Collection result;
  1280. getLeaseCollection(GET_LEASE6_DUID_IAID, inbind, result);
  1281. return (result);
  1282. }
  1283. Lease6Ptr
  1284. MySqlLeaseMgr::getLease6(const DUID& duid, uint32_t iaid,
  1285. SubnetID subnet_id) const {
  1286. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1287. DHCPSRV_MYSQL_GET_IAID_SUBID_DUID)
  1288. .arg(iaid).arg(subnet_id).arg(duid.toText());
  1289. // Set up the WHERE clause value
  1290. MYSQL_BIND inbind[3];
  1291. memset(inbind, 0, sizeof(inbind));
  1292. // See the earlier description of the use of "const_cast" when accessing
  1293. // the DUID for an explanation of the reason.
  1294. const vector<uint8_t>& duid_vector = duid.getDuid();
  1295. unsigned long duid_length = duid_vector.size();
  1296. inbind[0].buffer_type = MYSQL_TYPE_BLOB;
  1297. inbind[0].buffer = reinterpret_cast<char*>(
  1298. const_cast<uint8_t*>(&duid_vector[0]));
  1299. inbind[0].buffer_length = duid_length;
  1300. inbind[0].length = &duid_length;
  1301. // IAID
  1302. inbind[1].buffer_type = MYSQL_TYPE_LONG;
  1303. inbind[1].buffer = reinterpret_cast<char*>(&iaid);
  1304. inbind[1].is_unsigned = MLM_TRUE;
  1305. // Subnet ID
  1306. inbind[2].buffer_type = MYSQL_TYPE_LONG;
  1307. inbind[2].buffer = reinterpret_cast<char*>(&subnet_id);
  1308. inbind[2].is_unsigned = MLM_TRUE;
  1309. Lease6Ptr result;
  1310. getLease(GET_LEASE6_DUID_IAID_SUBID, inbind, result);
  1311. return (result);
  1312. }
  1313. // Update lease methods. These comprise common code that handles the actual
  1314. // update, and type-specific methods that set up the parameters for the prepared
  1315. // statement depending on the type of lease.
  1316. template <typename LeasePtr>
  1317. void
  1318. MySqlLeaseMgr::updateLeaseCommon(StatementIndex stindex, MYSQL_BIND* bind,
  1319. const LeasePtr& lease) {
  1320. // Bind the parameters to the statement
  1321. int status = mysql_stmt_bind_param(statements_[stindex], bind);
  1322. checkError(status, stindex, "unable to bind parameters");
  1323. // Execute
  1324. status = mysql_stmt_execute(statements_[stindex]);
  1325. checkError(status, stindex, "unable to execute");
  1326. // See how many rows were affected. The statement should only update a
  1327. // single row.
  1328. int affected_rows = mysql_stmt_affected_rows(statements_[stindex]);
  1329. if (affected_rows == 0) {
  1330. isc_throw(NoSuchLease, "unable to update lease for address " <<
  1331. lease->addr_.toText() << " as it does not exist");
  1332. } else if (affected_rows > 1) {
  1333. // Should not happen - primary key constraint should only have selected
  1334. // one row.
  1335. isc_throw(DbOperationError, "apparently updated more than one lease "
  1336. "that had the address " << lease->addr_.toText());
  1337. }
  1338. }
  1339. void
  1340. MySqlLeaseMgr::updateLease4(const Lease4Ptr& lease) {
  1341. const StatementIndex stindex = UPDATE_LEASE4;
  1342. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1343. DHCPSRV_MYSQL_UPDATE_ADDR4).arg(lease->addr_.toText());
  1344. // Create the MYSQL_BIND array for the data being updated
  1345. std::vector<MYSQL_BIND> bind = exchange4_->createBindForSend(lease);
  1346. // Set up the WHERE clause and append it to the MYSQL_BIND array
  1347. MYSQL_BIND where;
  1348. memset(&where, 0, sizeof(where));
  1349. uint32_t addr4 = static_cast<uint32_t>(lease->addr_);
  1350. where.buffer_type = MYSQL_TYPE_LONG;
  1351. where.buffer = reinterpret_cast<char*>(&addr4);
  1352. where.is_unsigned = MLM_TRUE;
  1353. bind.push_back(where);
  1354. // Drop to common update code
  1355. updateLeaseCommon(stindex, &bind[0], lease);
  1356. }
  1357. void
  1358. MySqlLeaseMgr::updateLease6(const Lease6Ptr& lease) {
  1359. const StatementIndex stindex = UPDATE_LEASE6;
  1360. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1361. DHCPSRV_MYSQL_UPDATE_ADDR6).arg(lease->addr_.toText());
  1362. // Create the MYSQL_BIND array for the data being updated
  1363. std::vector<MYSQL_BIND> bind = exchange6_->createBindForSend(lease);
  1364. // Set up the WHERE clause value
  1365. MYSQL_BIND where;
  1366. memset(&where, 0, sizeof(where));
  1367. std::string addr6 = lease->addr_.toText();
  1368. unsigned long addr6_length = addr6.size();
  1369. // See the earlier description of the use of "const_cast" when accessing
  1370. // the address for an explanation of the reason.
  1371. where.buffer_type = MYSQL_TYPE_STRING;
  1372. where.buffer = const_cast<char*>(addr6.c_str());
  1373. where.buffer_length = addr6_length;
  1374. where.length = &addr6_length;
  1375. bind.push_back(where);
  1376. // Drop to common update code
  1377. updateLeaseCommon(stindex, &bind[0], lease);
  1378. }
  1379. // Delete lease methods. Similar to other groups of methods, these comprise
  1380. // a per-type method that sets up the relevant MYSQL_BIND array (in this
  1381. // case, a single method for both V4 and V6 addresses) and a common method that
  1382. // handles the common processing.
  1383. bool
  1384. MySqlLeaseMgr::deleteLeaseCommon(StatementIndex stindex, MYSQL_BIND* bind) {
  1385. // Bind the input parameters to the statement
  1386. int status = mysql_stmt_bind_param(statements_[stindex], bind);
  1387. checkError(status, stindex, "unable to bind WHERE clause parameter");
  1388. // Execute
  1389. status = mysql_stmt_execute(statements_[stindex]);
  1390. checkError(status, stindex, "unable to execute");
  1391. // See how many rows were affected. Note that the statement may delete
  1392. // multiple rows.
  1393. return (mysql_stmt_affected_rows(statements_[stindex]) > 0);
  1394. }
  1395. bool
  1396. MySqlLeaseMgr::deleteLease(const isc::asiolink::IOAddress& addr) {
  1397. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1398. DHCPSRV_MYSQL_DELETE_ADDR).arg(addr.toText());
  1399. // Set up the WHERE clause value
  1400. MYSQL_BIND inbind[1];
  1401. memset(inbind, 0, sizeof(inbind));
  1402. if (addr.isV4()) {
  1403. uint32_t addr4 = static_cast<uint32_t>(addr);
  1404. inbind[0].buffer_type = MYSQL_TYPE_LONG;
  1405. inbind[0].buffer = reinterpret_cast<char*>(&addr4);
  1406. inbind[0].is_unsigned = MLM_TRUE;
  1407. return (deleteLeaseCommon(DELETE_LEASE4, inbind));
  1408. } else {
  1409. std::string addr6 = addr.toText();
  1410. unsigned long addr6_length = addr6.size();
  1411. // See the earlier description of the use of "const_cast" when accessing
  1412. // the address for an explanation of the reason.
  1413. inbind[0].buffer_type = MYSQL_TYPE_STRING;
  1414. inbind[0].buffer = const_cast<char*>(addr6.c_str());
  1415. inbind[0].buffer_length = addr6_length;
  1416. inbind[0].length = &addr6_length;
  1417. return (deleteLeaseCommon(DELETE_LEASE6, inbind));
  1418. }
  1419. }
  1420. // Miscellaneous database methods.
  1421. std::string
  1422. MySqlLeaseMgr::getName() const {
  1423. std::string name = "";
  1424. try {
  1425. name = getParameter("name");
  1426. } catch (...) {
  1427. // Return an empty name
  1428. }
  1429. return (name);
  1430. }
  1431. std::string
  1432. MySqlLeaseMgr::getDescription() const {
  1433. return (std::string("MySQL Database"));
  1434. }
  1435. std::pair<uint32_t, uint32_t>
  1436. MySqlLeaseMgr::getVersion() const {
  1437. const StatementIndex stindex = GET_VERSION;
  1438. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1439. DHCPSRV_MYSQL_GET_VERSION);
  1440. uint32_t major; // Major version number
  1441. uint32_t minor; // Minor version number
  1442. // Execute the prepared statement
  1443. int status = mysql_stmt_execute(statements_[stindex]);
  1444. if (status != 0) {
  1445. isc_throw(DbOperationError, "unable to execute <"
  1446. << text_statements_[stindex] << "> - reason: " <<
  1447. mysql_error(mysql_));
  1448. }
  1449. // Bind the output of the statement to the appropriate variables.
  1450. MYSQL_BIND bind[2];
  1451. memset(bind, 0, sizeof(bind));
  1452. bind[0].buffer_type = MYSQL_TYPE_LONG;
  1453. bind[0].is_unsigned = 1;
  1454. bind[0].buffer = &major;
  1455. bind[0].buffer_length = sizeof(major);
  1456. bind[1].buffer_type = MYSQL_TYPE_LONG;
  1457. bind[1].is_unsigned = 1;
  1458. bind[1].buffer = &minor;
  1459. bind[1].buffer_length = sizeof(minor);
  1460. status = mysql_stmt_bind_result(statements_[stindex], bind);
  1461. if (status != 0) {
  1462. isc_throw(DbOperationError, "unable to bind result set: " <<
  1463. mysql_error(mysql_));
  1464. }
  1465. // Fetch the data and set up the "release" object to release associated
  1466. // resources when this method exits then retrieve the data.
  1467. MySqlFreeResult fetch_release(statements_[stindex]);
  1468. status = mysql_stmt_fetch(statements_[stindex]);
  1469. if (status != 0) {
  1470. isc_throw(DbOperationError, "unable to obtain result set: " <<
  1471. mysql_error(mysql_));
  1472. }
  1473. return (std::make_pair(major, minor));
  1474. }
  1475. void
  1476. MySqlLeaseMgr::commit() {
  1477. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL, DHCPSRV_MYSQL_COMMIT);
  1478. if (mysql_commit(mysql_) != 0) {
  1479. isc_throw(DbOperationError, "commit failed: " << mysql_error(mysql_));
  1480. }
  1481. }
  1482. void
  1483. MySqlLeaseMgr::rollback() {
  1484. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL, DHCPSRV_MYSQL_ROLLBACK);
  1485. if (mysql_rollback(mysql_) != 0) {
  1486. isc_throw(DbOperationError, "rollback failed: " << mysql_error(mysql_));
  1487. }
  1488. }
  1489. }; // end of isc::dhcp namespace
  1490. }; // end of isc namespace