mysql_lease_mgr.cc 66 KB

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