mysql_lease_mgr.cc 67 KB

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