mysql_lease_mgr.cc 64 KB

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