mysql_lease_mgr.cc 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225
  1. // Copyright (C) 2012-2017 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this
  5. // file, You can obtain one at http://mozilla.org/MPL/2.0/.
  6. #include <config.h>
  7. #include <asiolink/io_address.h>
  8. #include <dhcp/duid.h>
  9. #include <dhcp/hwaddr.h>
  10. #include <dhcpsrv/dhcpsrv_log.h>
  11. #include <dhcpsrv/mysql_lease_mgr.h>
  12. #include <dhcpsrv/mysql_connection.h>
  13. #include <boost/array.hpp>
  14. #include <boost/static_assert.hpp>
  15. #include <mysqld_error.h>
  16. #include <iostream>
  17. #include <iomanip>
  18. #include <limits.h>
  19. #include <sstream>
  20. #include <string>
  21. #include <time.h>
  22. using namespace isc;
  23. using namespace isc::dhcp;
  24. using namespace std;
  25. /// @file
  26. ///
  27. /// This file holds the implementation of the Lease Manager using MySQL. The
  28. /// implementation uses MySQL's C API, as it comes as standard with the MySQL
  29. /// client libraries.
  30. ///
  31. /// In general, each of the database access methods corresponds to one SQL
  32. /// statement. To avoid the overhead of parsing a statement every time it is
  33. /// used, when the database is opened "prepared statements" are created -
  34. /// essentially doing the SQL parsing up front. Every time a method is used
  35. /// to access data, the corresponding prepared statement is referenced. Each
  36. /// prepared statement contains a set of placeholders for data, each
  37. /// placeholder being for:
  38. ///
  39. /// - data being added to the database (as in adding or updating a lease)
  40. /// - data being retrieved from the database (as in getting lease information)
  41. /// - selection criteria used to determine which records to update/retrieve.
  42. ///
  43. /// All such data is associated with the prepared statement using an array of
  44. /// MYSQL_BIND structures. Each element in the array corresponds to one
  45. /// parameter in the prepared statement - the first element in the array is
  46. /// associated with the first parameter, the second element with the second
  47. /// parameter etc.
  48. ///
  49. /// Within this file, the setting up of the MYSQL_BIND arrays for data being
  50. /// passed to and retrieved from the database is handled in the
  51. /// isc::dhcp::MySqlLease4Exchange and isc::dhcp::MySqlLease6Exchange classes.
  52. /// The classes also hold intermediate variables required for exchanging some
  53. /// of the data.
  54. ///
  55. /// With these exchange objects in place, many of the methods follow similar
  56. /// logic:
  57. /// - Set up the MYSQL_BIND array for data being transferred to/from the
  58. /// database. For data being transferred to the database, some of the
  59. /// data is extracted from the lease to intermediate variables, whilst
  60. /// in other cases the MYSQL_BIND arrays point to the data in the lease.
  61. /// - Set up the MYSQL_BIND array for the data selection parameters.
  62. /// - Bind these arrays to the prepared statement.
  63. /// - Execute the statement.
  64. /// - If there is output, copy the data from the bound variables to the output
  65. /// lease object.
  66. namespace {
  67. /// @brief Maximum length of the hostname stored in DNS.
  68. ///
  69. /// This length is restricted by the length of the domain-name carried
  70. /// in the Client FQDN %Option (see RFC4702 and RFC4704).
  71. const size_t HOSTNAME_MAX_LEN = 255;
  72. /// @brief Maximum size of an IPv6 address represented as a text string.
  73. ///
  74. /// This is 32 hexadecimal characters written in 8 groups of four, plus seven
  75. /// colon separators.
  76. const size_t ADDRESS6_TEXT_MAX_LEN = 39;
  77. boost::array<TaggedStatement, MySqlLeaseMgr::NUM_STATEMENTS>
  78. tagged_statements = { {
  79. {MySqlLeaseMgr::DELETE_LEASE4,
  80. "DELETE FROM lease4 WHERE address = ?"},
  81. {MySqlLeaseMgr::DELETE_LEASE4_STATE_EXPIRED,
  82. "DELETE FROM lease4 "
  83. "WHERE state = ? AND expire < ?"},
  84. {MySqlLeaseMgr::DELETE_LEASE6,
  85. "DELETE FROM lease6 WHERE address = ?"},
  86. {MySqlLeaseMgr::DELETE_LEASE6_STATE_EXPIRED,
  87. "DELETE FROM lease6 "
  88. "WHERE state = ? AND expire < ?"},
  89. {MySqlLeaseMgr::GET_LEASE4_ADDR,
  90. "SELECT address, hwaddr, client_id, "
  91. "valid_lifetime, expire, subnet_id, "
  92. "fqdn_fwd, fqdn_rev, hostname, "
  93. "state "
  94. "FROM lease4 "
  95. "WHERE address = ?"},
  96. {MySqlLeaseMgr::GET_LEASE4_CLIENTID,
  97. "SELECT address, hwaddr, client_id, "
  98. "valid_lifetime, expire, subnet_id, "
  99. "fqdn_fwd, fqdn_rev, hostname, "
  100. "state "
  101. "FROM lease4 "
  102. "WHERE client_id = ?"},
  103. {MySqlLeaseMgr::GET_LEASE4_CLIENTID_SUBID,
  104. "SELECT address, hwaddr, client_id, "
  105. "valid_lifetime, expire, subnet_id, "
  106. "fqdn_fwd, fqdn_rev, hostname, "
  107. "state "
  108. "FROM lease4 "
  109. "WHERE client_id = ? AND subnet_id = ?"},
  110. {MySqlLeaseMgr::GET_LEASE4_HWADDR,
  111. "SELECT address, hwaddr, client_id, "
  112. "valid_lifetime, expire, subnet_id, "
  113. "fqdn_fwd, fqdn_rev, hostname, "
  114. "state "
  115. "FROM lease4 "
  116. "WHERE hwaddr = ?"},
  117. {MySqlLeaseMgr::GET_LEASE4_HWADDR_SUBID,
  118. "SELECT address, hwaddr, client_id, "
  119. "valid_lifetime, expire, subnet_id, "
  120. "fqdn_fwd, fqdn_rev, hostname, "
  121. "state "
  122. "FROM lease4 "
  123. "WHERE hwaddr = ? AND subnet_id = ?"},
  124. {MySqlLeaseMgr::GET_LEASE4_EXPIRE,
  125. "SELECT address, hwaddr, client_id, "
  126. "valid_lifetime, expire, subnet_id, "
  127. "fqdn_fwd, fqdn_rev, hostname, "
  128. "state "
  129. "FROM lease4 "
  130. "WHERE state != ? AND expire < ? "
  131. "ORDER BY expire ASC "
  132. "LIMIT ?"},
  133. {MySqlLeaseMgr::GET_LEASE6_ADDR,
  134. "SELECT address, duid, valid_lifetime, "
  135. "expire, subnet_id, pref_lifetime, "
  136. "lease_type, iaid, prefix_len, "
  137. "fqdn_fwd, fqdn_rev, hostname, "
  138. "hwaddr, hwtype, hwaddr_source, "
  139. "state "
  140. "FROM lease6 "
  141. "WHERE address = ? AND lease_type = ?"},
  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. "fqdn_fwd, fqdn_rev, hostname, "
  147. "hwaddr, hwtype, hwaddr_source, "
  148. "state "
  149. "FROM lease6 "
  150. "WHERE duid = ? AND iaid = ? AND lease_type = ?"},
  151. {MySqlLeaseMgr::GET_LEASE6_DUID_IAID_SUBID,
  152. "SELECT address, duid, valid_lifetime, "
  153. "expire, subnet_id, pref_lifetime, "
  154. "lease_type, iaid, prefix_len, "
  155. "fqdn_fwd, fqdn_rev, hostname, "
  156. "hwaddr, hwtype, hwaddr_source, "
  157. "state "
  158. "FROM lease6 "
  159. "WHERE duid = ? AND iaid = ? AND subnet_id = ? "
  160. "AND lease_type = ?"},
  161. {MySqlLeaseMgr::GET_LEASE6_EXPIRE,
  162. "SELECT address, duid, valid_lifetime, "
  163. "expire, subnet_id, pref_lifetime, "
  164. "lease_type, iaid, prefix_len, "
  165. "fqdn_fwd, fqdn_rev, hostname, "
  166. "hwaddr, hwtype, hwaddr_source, "
  167. "state "
  168. "FROM lease6 "
  169. "WHERE state != ? AND expire < ? "
  170. "ORDER BY expire ASC "
  171. "LIMIT ?"},
  172. {MySqlLeaseMgr::GET_VERSION,
  173. "SELECT version, minor FROM schema_version"},
  174. {MySqlLeaseMgr::INSERT_LEASE4,
  175. "INSERT INTO lease4(address, hwaddr, client_id, "
  176. "valid_lifetime, expire, subnet_id, "
  177. "fqdn_fwd, fqdn_rev, hostname, state) "
  178. "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"},
  179. {MySqlLeaseMgr::INSERT_LEASE6,
  180. "INSERT INTO lease6(address, duid, valid_lifetime, "
  181. "expire, subnet_id, pref_lifetime, "
  182. "lease_type, iaid, prefix_len, "
  183. "fqdn_fwd, fqdn_rev, hostname, "
  184. "hwaddr, hwtype, hwaddr_source, "
  185. "state) "
  186. "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"},
  187. {MySqlLeaseMgr::UPDATE_LEASE4,
  188. "UPDATE lease4 SET address = ?, hwaddr = ?, "
  189. "client_id = ?, valid_lifetime = ?, expire = ?, "
  190. "subnet_id = ?, fqdn_fwd = ?, fqdn_rev = ?, "
  191. "hostname = ?, state = ? "
  192. "WHERE address = ?"},
  193. {MySqlLeaseMgr::UPDATE_LEASE6,
  194. "UPDATE lease6 SET address = ?, duid = ?, "
  195. "valid_lifetime = ?, expire = ?, subnet_id = ?, "
  196. "pref_lifetime = ?, lease_type = ?, iaid = ?, "
  197. "prefix_len = ?, fqdn_fwd = ?, fqdn_rev = ?, "
  198. "hostname = ?, hwaddr = ?, hwtype = ?, hwaddr_source = ?, "
  199. "state = ? "
  200. "WHERE address = ?"},
  201. {MySqlLeaseMgr::RECOUNT_LEASE4_STATS,
  202. "SELECT subnet_id, state, count(state) as state_count "
  203. " FROM lease4 GROUP BY subnet_id, state ORDER BY subnet_id"},
  204. {MySqlLeaseMgr::RECOUNT_LEASE6_STATS,
  205. "SELECT subnet_id, lease_type, state, count(state) as state_count"
  206. " FROM lease6 GROUP BY subnet_id, lease_type, state "
  207. " ORDER BY subnet_id" }
  208. }
  209. };
  210. };
  211. namespace isc {
  212. namespace dhcp {
  213. /// @brief Common MySQL and Lease Data Methods
  214. ///
  215. /// The MySqlLease4Exchange and MySqlLease6Exchange classes provide the
  216. /// functionality to set up binding information between variables in the
  217. /// program and data extracted from the database. This class is the common
  218. /// base to both of them, containing some common methods.
  219. class MySqlLeaseExchange {
  220. public:
  221. /// @brief Set error indicators
  222. ///
  223. /// Sets the error indicator for each of the MYSQL_BIND elements. It points
  224. /// the "error" field within an element of the input array to the
  225. /// corresponding element of the passed error array.
  226. ///
  227. /// @param bind Array of BIND elements
  228. /// @param error Array of error elements. If there is an error in getting
  229. /// data associated with one of the "bind" elements, the
  230. /// corresponding element in the error array is set to MLM_TRUE.
  231. /// @param count Size of each of the arrays.
  232. static void setErrorIndicators(MYSQL_BIND* bind, my_bool* error,
  233. size_t count) {
  234. for (size_t i = 0; i < count; ++i) {
  235. error[i] = MLM_FALSE;
  236. bind[i].error = reinterpret_cast<char*>(&error[i]);
  237. }
  238. }
  239. /// @brief Return columns in error
  240. ///
  241. /// If an error is returned from a fetch (in particular, a truncated
  242. /// status), this method can be called to get the names of the fields in
  243. /// error. It returns a string comprising the names of the fields
  244. /// separated by commas. In the case of there being no error indicators
  245. /// set, it returns the string "(None)".
  246. ///
  247. /// @param error Array of error elements. An element is set to MLM_TRUE
  248. /// if the corresponding column in the database is the source of
  249. /// the error.
  250. /// @param names Array of column names, the same size as the error array.
  251. /// @param count Size of each of the arrays.
  252. static std::string getColumnsInError(my_bool* error, std::string* names,
  253. size_t count) {
  254. std::string result = "";
  255. // Accumulate list of column names
  256. for (size_t i = 0; i < count; ++i) {
  257. if (error[i] == MLM_TRUE) {
  258. if (!result.empty()) {
  259. result += ", ";
  260. }
  261. result += names[i];
  262. }
  263. }
  264. if (result.empty()) {
  265. result = "(None)";
  266. }
  267. return (result);
  268. }
  269. };
  270. /// @brief Exchange MySQL and Lease4 Data
  271. ///
  272. /// On any MySQL operation, arrays of MYSQL_BIND structures must be built to
  273. /// describe the parameters in the prepared statements. Where information is
  274. /// inserted or retrieved - INSERT, UPDATE, SELECT - a large amount of that
  275. /// structure is identical. This class handles the creation of that array.
  276. ///
  277. /// Owing to the MySQL API, the process requires some intermediate variables
  278. /// to hold things like data length etc. This object holds those variables.
  279. ///
  280. /// @note There are no unit tests for this class. It is tested indirectly
  281. /// in all MySqlLeaseMgr::xxx4() calls where it is used.
  282. class MySqlLease4Exchange : public MySqlLeaseExchange {
  283. /// @brief Set number of database columns for this lease structure
  284. static const size_t LEASE_COLUMNS = 10;
  285. public:
  286. /// @brief Constructor
  287. ///
  288. /// The initialization of the variables here is only to satisfy cppcheck -
  289. /// all variables are initialized/set in the methods before they are used.
  290. MySqlLease4Exchange() : addr4_(0), hwaddr_length_(0), client_id_length_(0),
  291. client_id_null_(MLM_FALSE),
  292. subnet_id_(0), valid_lifetime_(0),
  293. fqdn_fwd_(false), fqdn_rev_(false), hostname_length_(0),
  294. state_(0) {
  295. memset(hwaddr_buffer_, 0, sizeof(hwaddr_buffer_));
  296. memset(client_id_buffer_, 0, sizeof(client_id_buffer_));
  297. memset(hostname_buffer_, 0, sizeof(hostname_buffer_));
  298. std::fill(&error_[0], &error_[LEASE_COLUMNS], MLM_FALSE);
  299. // Set the column names (for error messages)
  300. columns_[0] = "address";
  301. columns_[1] = "hwaddr";
  302. columns_[2] = "client_id";
  303. columns_[3] = "valid_lifetime";
  304. columns_[4] = "expire";
  305. columns_[5] = "subnet_id";
  306. columns_[6] = "fqdn_fwd";
  307. columns_[7] = "fqdn_rev";
  308. columns_[8] = "hostname";
  309. columns_[9] = "state";
  310. BOOST_STATIC_ASSERT(9 < LEASE_COLUMNS);
  311. }
  312. /// @brief Create MYSQL_BIND objects for Lease4 Pointer
  313. ///
  314. /// Fills in the MYSQL_BIND array for sending data in the Lease4 object to
  315. /// the database.
  316. ///
  317. /// @param lease Lease object to be added to the database. None of the
  318. /// fields in the lease are modified - the lease data is only read.
  319. ///
  320. /// @return Vector of MySQL BIND objects representing the data to be added.
  321. std::vector<MYSQL_BIND> createBindForSend(const Lease4Ptr& lease) {
  322. // Store lease object to ensure it remains valid.
  323. lease_ = lease;
  324. // Initialize prior to constructing the array of MYSQL_BIND structures.
  325. // It sets all fields, including is_null, to zero, so we need to set
  326. // is_null only if it should be true. This gives up minor performance
  327. // benefit while being safe approach. For improved readability, the
  328. // code that explicitly sets is_null is there, but is commented out.
  329. memset(bind_, 0, sizeof(bind_));
  330. // Set up the structures for the various components of the lease4
  331. // structure.
  332. try {
  333. // Address: uint32_t
  334. // The address in the Lease structure is an IOAddress object. Convert
  335. // this to an integer for storage.
  336. addr4_ = lease_->addr_.toUint32();
  337. bind_[0].buffer_type = MYSQL_TYPE_LONG;
  338. bind_[0].buffer = reinterpret_cast<char*>(&addr4_);
  339. bind_[0].is_unsigned = MLM_TRUE;
  340. // bind_[0].is_null = &MLM_FALSE; // commented out for performance
  341. // reasons, see memset() above
  342. // hwaddr: varbinary(128)
  343. // For speed, we avoid copying the data into temporary storage and
  344. // instead extract it from the lease structure directly.
  345. hwaddr_length_ = lease_->hwaddr_->hwaddr_.size();
  346. bind_[1].buffer_type = MYSQL_TYPE_BLOB;
  347. bind_[1].buffer = reinterpret_cast<char*>(&(lease_->hwaddr_->hwaddr_[0]));
  348. bind_[1].buffer_length = hwaddr_length_;
  349. bind_[1].length = &hwaddr_length_;
  350. // bind_[1].is_null = &MLM_FALSE; // commented out for performance
  351. // reasons, see memset() above
  352. // client_id: varbinary(128)
  353. if (lease_->client_id_) {
  354. client_id_ = lease_->client_id_->getClientId();
  355. client_id_length_ = client_id_.size();
  356. bind_[2].buffer_type = MYSQL_TYPE_BLOB;
  357. bind_[2].buffer = reinterpret_cast<char*>(&client_id_[0]);
  358. bind_[2].buffer_length = client_id_length_;
  359. bind_[2].length = &client_id_length_;
  360. // bind_[2].is_null = &MLM_FALSE; // commented out for performance
  361. // reasons, see memset() above
  362. } else {
  363. bind_[2].buffer_type = MYSQL_TYPE_NULL;
  364. // According to http://dev.mysql.com/doc/refman/5.5/en/
  365. // c-api-prepared-statement-data-structures.html, the other
  366. // fields doesn't matter if type is set to MYSQL_TYPE_NULL,
  367. // but let's set them to some sane values in case earlier versions
  368. // didn't have that assumption.
  369. client_id_null_ = MLM_TRUE;
  370. bind_[2].buffer = NULL;
  371. bind_[2].is_null = &client_id_null_;
  372. }
  373. // valid lifetime: unsigned int
  374. bind_[3].buffer_type = MYSQL_TYPE_LONG;
  375. bind_[3].buffer = reinterpret_cast<char*>(&lease_->valid_lft_);
  376. bind_[3].is_unsigned = MLM_TRUE;
  377. // bind_[3].is_null = &MLM_FALSE; // commented out for performance
  378. // reasons, see memset() above
  379. // expire: timestamp
  380. // The lease structure holds the client last transmission time (cltt_)
  381. // For convenience for external tools, this is converted to lease
  382. // expiry time (expire). The relationship is given by:
  383. //
  384. // expire = cltt_ + valid_lft_
  385. MySqlConnection::convertToDatabaseTime(lease_->cltt_, lease_->valid_lft_,
  386. expire_);
  387. bind_[4].buffer_type = MYSQL_TYPE_TIMESTAMP;
  388. bind_[4].buffer = reinterpret_cast<char*>(&expire_);
  389. bind_[4].buffer_length = sizeof(expire_);
  390. // bind_[4].is_null = &MLM_FALSE; // commented out for performance
  391. // reasons, see memset() above
  392. // subnet_id: unsigned int
  393. // Can use lease_->subnet_id_ directly as it is of type uint32_t.
  394. bind_[5].buffer_type = MYSQL_TYPE_LONG;
  395. bind_[5].buffer = reinterpret_cast<char*>(&lease_->subnet_id_);
  396. bind_[5].is_unsigned = MLM_TRUE;
  397. // bind_[5].is_null = &MLM_FALSE; // commented out for performance
  398. // reasons, see memset() above
  399. // fqdn_fwd: boolean
  400. bind_[6].buffer_type = MYSQL_TYPE_TINY;
  401. bind_[6].buffer = reinterpret_cast<char*>(&lease_->fqdn_fwd_);
  402. bind_[6].is_unsigned = MLM_TRUE;
  403. // bind_[6].is_null = &MLM_FALSE; // commented out for performance
  404. // reasons, see memset() above
  405. // fqdn_rev: boolean
  406. bind_[7].buffer_type = MYSQL_TYPE_TINY;
  407. bind_[7].buffer = reinterpret_cast<char*>(&lease_->fqdn_rev_);
  408. bind_[7].is_unsigned = MLM_TRUE;
  409. // bind_[7].is_null = &MLM_FALSE; // commented out for performance
  410. // reasons, see memset() above
  411. // hostname: varchar(255)
  412. bind_[8].buffer_type = MYSQL_TYPE_VARCHAR;
  413. bind_[8].buffer = const_cast<char*>(lease_->hostname_.c_str());
  414. bind_[8].buffer_length = lease_->hostname_.length();
  415. // bind_[8].is_null = &MLM_FALSE; // commented out for performance
  416. // reasons, see memset() above
  417. // state: uint32_t.
  418. bind_[9].buffer_type = MYSQL_TYPE_LONG;
  419. bind_[9].buffer = reinterpret_cast<char*>(&lease_->state_);
  420. bind_[9].is_unsigned = MLM_TRUE;
  421. // bind_[9].is_null = &MLM_FALSE; // commented out for performance
  422. // reasons, see memset() above
  423. // Add the error flags
  424. setErrorIndicators(bind_, error_, LEASE_COLUMNS);
  425. // .. and check that we have the numbers correct at compile time.
  426. BOOST_STATIC_ASSERT(9 < LEASE_COLUMNS);
  427. } catch (const std::exception& ex) {
  428. isc_throw(DbOperationError,
  429. "Could not create bind array from Lease4: "
  430. << lease_->addr_.toText() << ", reason: " << ex.what());
  431. }
  432. // Add the data to the vector. Note the end element is one after the
  433. // end of the array.
  434. return (std::vector<MYSQL_BIND>(&bind_[0], &bind_[LEASE_COLUMNS]));
  435. }
  436. /// @brief Create BIND array to receive data
  437. ///
  438. /// Creates a MYSQL_BIND array to receive Lease4 data from the database.
  439. /// After data is successfully received, getLeaseData() can be used to copy
  440. /// it to a Lease6 object.
  441. ///
  442. std::vector<MYSQL_BIND> createBindForReceive() {
  443. // Initialize MYSQL_BIND array.
  444. // It sets all fields, including is_null, to zero, so we need to set
  445. // is_null only if it should be true. This gives up minor performance
  446. // benefit while being safe approach. For improved readability, the
  447. // code that explicitly sets is_null is there, but is commented out.
  448. memset(bind_, 0, sizeof(bind_));
  449. // address: uint32_t
  450. bind_[0].buffer_type = MYSQL_TYPE_LONG;
  451. bind_[0].buffer = reinterpret_cast<char*>(&addr4_);
  452. bind_[0].is_unsigned = MLM_TRUE;
  453. // bind_[0].is_null = &MLM_FALSE; // commented out for performance
  454. // reasons, see memset() above
  455. // hwaddr: varbinary(20)
  456. hwaddr_length_ = sizeof(hwaddr_buffer_);
  457. bind_[1].buffer_type = MYSQL_TYPE_BLOB;
  458. bind_[1].buffer = reinterpret_cast<char*>(hwaddr_buffer_);
  459. bind_[1].buffer_length = hwaddr_length_;
  460. bind_[1].length = &hwaddr_length_;
  461. // bind_[1].is_null = &MLM_FALSE; // commented out for performance
  462. // reasons, see memset() above
  463. // client_id: varbinary(128)
  464. client_id_length_ = sizeof(client_id_buffer_);
  465. bind_[2].buffer_type = MYSQL_TYPE_BLOB;
  466. bind_[2].buffer = reinterpret_cast<char*>(client_id_buffer_);
  467. bind_[2].buffer_length = client_id_length_;
  468. bind_[2].length = &client_id_length_;
  469. bind_[2].is_null = &client_id_null_;
  470. // bind_[2].is_null = &MLM_FALSE; // commented out for performance
  471. // reasons, see memset() above
  472. // lease_time: unsigned int
  473. bind_[3].buffer_type = MYSQL_TYPE_LONG;
  474. bind_[3].buffer = reinterpret_cast<char*>(&valid_lifetime_);
  475. bind_[3].is_unsigned = MLM_TRUE;
  476. // bind_[3].is_null = &MLM_FALSE; // commented out for performance
  477. // reasons, see memset() above
  478. // expire: timestamp
  479. bind_[4].buffer_type = MYSQL_TYPE_TIMESTAMP;
  480. bind_[4].buffer = reinterpret_cast<char*>(&expire_);
  481. bind_[4].buffer_length = sizeof(expire_);
  482. // bind_[4].is_null = &MLM_FALSE; // commented out for performance
  483. // reasons, see memset() above
  484. // subnet_id: unsigned int
  485. bind_[5].buffer_type = MYSQL_TYPE_LONG;
  486. bind_[5].buffer = reinterpret_cast<char*>(&subnet_id_);
  487. bind_[5].is_unsigned = MLM_TRUE;
  488. // bind_[5].is_null = &MLM_FALSE; // commented out for performance
  489. // reasons, see memset() above
  490. // fqdn_fwd: boolean
  491. bind_[6].buffer_type = MYSQL_TYPE_TINY;
  492. bind_[6].buffer = reinterpret_cast<char*>(&fqdn_fwd_);
  493. bind_[6].is_unsigned = MLM_TRUE;
  494. // bind_[6].is_null = &MLM_FALSE; // commented out for performance
  495. // reasons, see memset() above
  496. // fqdn_rev: boolean
  497. bind_[7].buffer_type = MYSQL_TYPE_TINY;
  498. bind_[7].buffer = reinterpret_cast<char*>(&fqdn_rev_);
  499. bind_[7].is_unsigned = MLM_TRUE;
  500. // bind_[7].is_null = &MLM_FALSE; // commented out for performance
  501. // reasons, see memset() above
  502. // hostname: varchar(255)
  503. hostname_length_ = sizeof(hostname_buffer_);
  504. bind_[8].buffer_type = MYSQL_TYPE_STRING;
  505. bind_[8].buffer = reinterpret_cast<char*>(hostname_buffer_);
  506. bind_[8].buffer_length = hostname_length_;
  507. bind_[8].length = &hostname_length_;
  508. // bind_[8].is_null = &MLM_FALSE; // commented out for performance
  509. // reasons, see memset() above
  510. // state: uint32_t
  511. bind_[9].buffer_type = MYSQL_TYPE_LONG;
  512. bind_[9].buffer = reinterpret_cast<char*>(&state_);
  513. bind_[9].is_unsigned = MLM_TRUE;
  514. // bind_[9].is_null = &MLM_FALSE; // commented out for performance
  515. // reasons, see memset() above
  516. // Add the error flags
  517. setErrorIndicators(bind_, error_, LEASE_COLUMNS);
  518. // .. and check that we have the numbers correct at compile time.
  519. BOOST_STATIC_ASSERT(9 < LEASE_COLUMNS);
  520. // Add the data to the vector. Note the end element is one after the
  521. // end of the array.
  522. return(std::vector<MYSQL_BIND>(&bind_[0], &bind_[LEASE_COLUMNS]));
  523. }
  524. /// @brief Copy Received Data into Lease4 Object
  525. ///
  526. /// Called after the MYSQL_BIND array created by createBindForReceive()
  527. /// has been used, this copies data from the internal member variables
  528. /// into a Lease4 object.
  529. ///
  530. /// @return Lease4Ptr Pointer to a Lease6 object holding the relevant
  531. /// data.
  532. Lease4Ptr getLeaseData() {
  533. // Convert times received from the database to times for the lease
  534. // structure
  535. time_t cltt = 0;
  536. MySqlConnection::convertFromDatabaseTime(expire_, valid_lifetime_, cltt);
  537. if (client_id_null_==MLM_TRUE) {
  538. // There's no client-id, so we pass client-id_length_ set to 0
  539. client_id_length_ = 0;
  540. }
  541. // Hostname is passed to Lease4 as a string object. We have to create
  542. // it from the buffer holding hostname and the buffer length.
  543. std::string hostname(hostname_buffer_,
  544. hostname_buffer_ + hostname_length_);
  545. // Recreate the hardware address.
  546. HWAddrPtr hwaddr(new HWAddr(hwaddr_buffer_, hwaddr_length_, HTYPE_ETHER));
  547. // note that T1 and T2 are not stored
  548. Lease4Ptr lease(new Lease4(addr4_, hwaddr,
  549. client_id_buffer_, client_id_length_,
  550. valid_lifetime_, 0, 0, cltt, subnet_id_,
  551. fqdn_fwd_, fqdn_rev_, hostname));
  552. lease->state_ = state_;
  553. return (lease);
  554. }
  555. /// @brief Return columns in error
  556. ///
  557. /// If an error is returned from a fetch (in particular, a truncated
  558. /// status), this method can be called to get the names of the fields in
  559. /// error. It returns a string comprising the names of the fields
  560. /// separated by commas. In the case of there being no error indicators
  561. /// set, it returns the string "(None)".
  562. ///
  563. /// @return Comma-separated list of columns in error, or the string
  564. /// "(None)".
  565. std::string getErrorColumns() {
  566. return (getColumnsInError(error_, columns_, LEASE_COLUMNS));
  567. }
  568. private:
  569. // Note: All array lengths are equal to the corresponding variable in the
  570. // schema.
  571. // Note: Arrays are declared fixed length for speed of creation
  572. uint32_t addr4_; ///< IPv4 address
  573. MYSQL_BIND bind_[LEASE_COLUMNS]; ///< Bind array
  574. std::string columns_[LEASE_COLUMNS];///< Column names
  575. my_bool error_[LEASE_COLUMNS]; ///< Error array
  576. std::vector<uint8_t> hwaddr_; ///< Hardware address
  577. uint8_t hwaddr_buffer_[HWAddr::MAX_HWADDR_LEN];
  578. ///< Hardware address buffer
  579. unsigned long hwaddr_length_; ///< Hardware address length
  580. std::vector<uint8_t> client_id_; ///< Client identification
  581. uint8_t client_id_buffer_[ClientId::MAX_CLIENT_ID_LEN];
  582. ///< Client ID buffer
  583. unsigned long client_id_length_; ///< Client ID address length
  584. my_bool client_id_null_; ///< Is Client ID null?
  585. MYSQL_TIME expire_; ///< Lease expiry time
  586. Lease4Ptr lease_; ///< Pointer to lease object
  587. uint32_t subnet_id_; ///< Subnet identification
  588. uint32_t valid_lifetime_; ///< Lease time
  589. my_bool fqdn_fwd_; ///< Has forward DNS update been
  590. ///< performed
  591. my_bool fqdn_rev_; ///< Has reverse DNS update been
  592. ///< performed
  593. char hostname_buffer_[HOSTNAME_MAX_LEN];
  594. ///< Client hostname
  595. unsigned long hostname_length_; ///< Client hostname length
  596. uint32_t state_; ///< Lease state
  597. };
  598. /// @brief Exchange MySQL and Lease6 Data
  599. ///
  600. /// On any MySQL operation, arrays of MYSQL_BIND structures must be built to
  601. /// describe the parameters in the prepared statements. Where information is
  602. /// inserted or retrieved - INSERT, UPDATE, SELECT - a large amount of that
  603. /// structure is identical. This class handles the creation of that array.
  604. ///
  605. /// Owing to the MySQL API, the process requires some intermediate variables
  606. /// to hold things like data length etc. This object holds those variables.
  607. ///
  608. /// @note There are no unit tests for this class. It is tested indirectly
  609. /// in all MySqlLeaseMgr::xxx6() calls where it is used.
  610. class MySqlLease6Exchange : public MySqlLeaseExchange {
  611. /// @brief Set number of database columns for this lease structure
  612. static const size_t LEASE_COLUMNS = 16;
  613. public:
  614. /// @brief Constructor
  615. ///
  616. /// The initialization of the variables here is nonly to satisfy cppcheck -
  617. /// all variables are initialized/set in the methods before they are used.
  618. MySqlLease6Exchange() : addr6_length_(0), duid_length_(0),
  619. iaid_(0), lease_type_(0), prefixlen_(0),
  620. pref_lifetime_(0), subnet_id_(0), valid_lifetime_(0),
  621. fqdn_fwd_(false), fqdn_rev_(false),
  622. hostname_length_(0), hwaddr_length_(0),
  623. hwaddr_null_(MLM_FALSE), hwtype_(0), hwaddr_source_(0),
  624. state_(0) {
  625. memset(addr6_buffer_, 0, sizeof(addr6_buffer_));
  626. memset(duid_buffer_, 0, sizeof(duid_buffer_));
  627. memset(hostname_buffer_, 0, sizeof(hostname_buffer_));
  628. memset(hwaddr_buffer_, 0, sizeof(hwaddr_buffer_));
  629. std::fill(&error_[0], &error_[LEASE_COLUMNS], MLM_FALSE);
  630. // Set the column names (for error messages)
  631. columns_[0] = "address";
  632. columns_[1] = "duid";
  633. columns_[2] = "valid_lifetime";
  634. columns_[3] = "expire";
  635. columns_[4] = "subnet_id";
  636. columns_[5] = "pref_lifetime";
  637. columns_[6] = "lease_type";
  638. columns_[7] = "iaid";
  639. columns_[8] = "prefix_len";
  640. columns_[9] = "fqdn_fwd";
  641. columns_[10] = "fqdn_rev";
  642. columns_[11] = "hostname";
  643. columns_[12] = "hwaddr";
  644. columns_[13] = "hwtype";
  645. columns_[14] = "hwaddr_source";
  646. columns_[15] = "state";
  647. BOOST_STATIC_ASSERT(15 < LEASE_COLUMNS);
  648. }
  649. /// @brief Create MYSQL_BIND objects for Lease6 Pointer
  650. ///
  651. /// Fills in the MYSQL_BIND array for sending data in the Lease4 object to
  652. /// the database.
  653. ///
  654. /// @param lease Lease object to be added to the database.
  655. ///
  656. /// @return Vector of MySQL BIND objects representing the data to be added.
  657. std::vector<MYSQL_BIND> createBindForSend(const Lease6Ptr& lease) {
  658. // Store lease object to ensure it remains valid.
  659. lease_ = lease;
  660. // Ensure bind_ array clear for constructing the MYSQL_BIND structures
  661. // for this lease.
  662. // It sets all fields, including is_null, to zero, so we need to set
  663. // is_null only if it should be true. This gives up minor performance
  664. // benefit while being safe approach. For improved readability, the
  665. // code that explicitly sets is_null is there, but is commented out.
  666. memset(bind_, 0, sizeof(bind_));
  667. try {
  668. // address: varchar(39)
  669. addr6_ = lease_->addr_.toText();
  670. addr6_length_ = addr6_.size();
  671. // In the following statement, the string is being read. However, the
  672. // MySQL C interface does not use "const", so the "buffer" element
  673. // is declared as "char*" instead of "const char*". To resolve this,
  674. // the "const" is discarded. (Note that the address of addr6_.c_str()
  675. // is guaranteed to be valid until the next non-const operation on
  676. // addr6_.)
  677. //
  678. // The const_cast could be avoided by copying the string to a writable
  679. // buffer and storing the address of that in the "buffer" element.
  680. // However, this introduces a copy operation (with additional overhead)
  681. // purely to get round the structures introduced by design of the
  682. // MySQL interface (which uses the area pointed to by "buffer" as input
  683. // when specifying query parameters and as output when retrieving data).
  684. // For that reason, "const_cast" has been used.
  685. bind_[0].buffer_type = MYSQL_TYPE_STRING;
  686. bind_[0].buffer = const_cast<char*>(addr6_.c_str());
  687. bind_[0].buffer_length = addr6_length_;
  688. bind_[0].length = &addr6_length_;
  689. // bind_[0].is_null = &MLM_FALSE; // commented out for performance
  690. // reasons, see memset() above
  691. // duid: varchar(128)
  692. if (!lease_->duid_) {
  693. isc_throw(DbOperationError, "lease6 for address " << addr6_
  694. << " is missing mandatory client-id.");
  695. }
  696. duid_ = lease_->duid_->getDuid();
  697. duid_length_ = duid_.size();
  698. bind_[1].buffer_type = MYSQL_TYPE_BLOB;
  699. bind_[1].buffer = reinterpret_cast<char*>(&(duid_[0]));
  700. bind_[1].buffer_length = duid_length_;
  701. bind_[1].length = &duid_length_;
  702. // bind_[1].is_null = &MLM_FALSE; // commented out for performance
  703. // reasons, see memset() above
  704. // valid lifetime: unsigned int
  705. bind_[2].buffer_type = MYSQL_TYPE_LONG;
  706. bind_[2].buffer = reinterpret_cast<char*>(&lease_->valid_lft_);
  707. bind_[2].is_unsigned = MLM_TRUE;
  708. // bind_[2].is_null = &MLM_FALSE; // commented out for performance
  709. // reasons, see memset() above
  710. // expire: timestamp
  711. // The lease structure holds the client last transmission time (cltt_)
  712. // For convenience for external tools, this is converted to lease
  713. /// expiry time (expire). The relationship is given by:
  714. //
  715. // expire = cltt_ + valid_lft_
  716. //
  717. MySqlConnection::convertToDatabaseTime(lease_->cltt_, lease_->valid_lft_,
  718. expire_);
  719. bind_[3].buffer_type = MYSQL_TYPE_TIMESTAMP;
  720. bind_[3].buffer = reinterpret_cast<char*>(&expire_);
  721. bind_[3].buffer_length = sizeof(expire_);
  722. // bind_[3].is_null = &MLM_FALSE; // commented out for performance
  723. // reasons, see memset() above
  724. // subnet_id: unsigned int
  725. // Can use lease_->subnet_id_ directly as it is of type uint32_t.
  726. bind_[4].buffer_type = MYSQL_TYPE_LONG;
  727. bind_[4].buffer = reinterpret_cast<char*>(&lease_->subnet_id_);
  728. bind_[4].is_unsigned = MLM_TRUE;
  729. // bind_[4].is_null = &MLM_FALSE; // commented out for performance
  730. // reasons, see memset() above
  731. // pref_lifetime: unsigned int
  732. // Can use lease_->preferred_lft_ directly as it is of type uint32_t.
  733. bind_[5].buffer_type = MYSQL_TYPE_LONG;
  734. bind_[5].buffer = reinterpret_cast<char*>(&lease_->preferred_lft_);
  735. bind_[5].is_unsigned = MLM_TRUE;
  736. // bind_[5].is_null = &MLM_FALSE; // commented out for performance
  737. // reasons, see memset() above
  738. // lease_type: tinyint
  739. // Must convert to uint8_t as lease_->type_ is a LeaseType variable.
  740. lease_type_ = lease_->type_;
  741. bind_[6].buffer_type = MYSQL_TYPE_TINY;
  742. bind_[6].buffer = reinterpret_cast<char*>(&lease_type_);
  743. bind_[6].is_unsigned = MLM_TRUE;
  744. // bind_[6].is_null = &MLM_FALSE; // commented out for performance
  745. // reasons, see memset() above
  746. // iaid: unsigned int
  747. // Can use lease_->iaid_ directly as it is of type uint32_t.
  748. bind_[7].buffer_type = MYSQL_TYPE_LONG;
  749. bind_[7].buffer = reinterpret_cast<char*>(&lease_->iaid_);
  750. bind_[7].is_unsigned = MLM_TRUE;
  751. // bind_[7].is_null = &MLM_FALSE; // commented out for performance
  752. // reasons, see memset() above
  753. // prefix_len: unsigned tinyint
  754. // Can use lease_->prefixlen_ directly as it is uint32_t.
  755. bind_[8].buffer_type = MYSQL_TYPE_TINY;
  756. bind_[8].buffer = reinterpret_cast<char*>(&lease_->prefixlen_);
  757. bind_[8].is_unsigned = MLM_TRUE;
  758. // bind_[8].is_null = &MLM_FALSE; // commented out for performance
  759. // reasons, see memset() above
  760. // fqdn_fwd: boolean
  761. bind_[9].buffer_type = MYSQL_TYPE_TINY;
  762. bind_[9].buffer = reinterpret_cast<char*>(&lease_->fqdn_fwd_);
  763. bind_[9].is_unsigned = MLM_TRUE;
  764. // bind_[7].is_null = &MLM_FALSE; // commented out for performance
  765. // reasons, see memset() above
  766. // fqdn_rev: boolean
  767. bind_[10].buffer_type = MYSQL_TYPE_TINY;
  768. bind_[10].buffer = reinterpret_cast<char*>(&lease_->fqdn_rev_);
  769. bind_[10].is_unsigned = MLM_TRUE;
  770. // bind_[10].is_null = &MLM_FALSE; // commented out for performance
  771. // reasons, see memset() above
  772. // hostname: varchar(255)
  773. bind_[11].buffer_type = MYSQL_TYPE_VARCHAR;
  774. bind_[11].buffer = const_cast<char*>(lease_->hostname_.c_str());
  775. bind_[11].buffer_length = lease_->hostname_.length();
  776. // bind_[11].is_null = &MLM_FALSE; // commented out for performance
  777. // reasons, see memset() above
  778. // hwaddr: varbinary(20) - hardware/MAC address
  779. HWAddrPtr hwaddr = lease_->hwaddr_;
  780. if (hwaddr) {
  781. hwaddr_ = hwaddr->hwaddr_;
  782. hwaddr_length_ = hwaddr->hwaddr_.size();
  783. bind_[12].buffer_type = MYSQL_TYPE_BLOB;
  784. bind_[12].buffer = reinterpret_cast<char*>(&(hwaddr_[0]));
  785. bind_[12].buffer_length = hwaddr_length_;
  786. bind_[12].length = &hwaddr_length_;
  787. } else {
  788. bind_[12].buffer_type = MYSQL_TYPE_NULL;
  789. // According to http://dev.mysql.com/doc/refman/5.5/en/
  790. // c-api-prepared-statement-data-structures.html, the other
  791. // fields doesn't matter if type is set to MYSQL_TYPE_NULL,
  792. // but let's set them to some sane values in case earlier versions
  793. // didn't have that assumption.
  794. hwaddr_null_ = MLM_TRUE;
  795. bind_[12].buffer = NULL;
  796. bind_[12].is_null = &hwaddr_null_;
  797. }
  798. // hwtype
  799. if (hwaddr) {
  800. hwtype_ = lease->hwaddr_->htype_;
  801. bind_[13].buffer_type = MYSQL_TYPE_SHORT;
  802. bind_[13].buffer = reinterpret_cast<char*>(&hwtype_);
  803. bind_[13].is_unsigned = MLM_TRUE;
  804. } else {
  805. hwtype_ = 0;
  806. bind_[13].buffer_type = MYSQL_TYPE_NULL;
  807. // According to http://dev.mysql.com/doc/refman/5.5/en/
  808. // c-api-prepared-statement-data-structures.html, the other
  809. // fields doesn't matter if type is set to MYSQL_TYPE_NULL,
  810. // but let's set them to some sane values in case earlier versions
  811. // didn't have that assumption.
  812. hwaddr_null_ = MLM_TRUE;
  813. bind_[13].buffer = NULL;
  814. bind_[13].is_null = &hwaddr_null_;
  815. }
  816. /// Hardware source
  817. if (hwaddr) {
  818. hwaddr_source_ = lease->hwaddr_->source_;
  819. bind_[14].buffer_type = MYSQL_TYPE_LONG;
  820. bind_[14].buffer = reinterpret_cast<char*>(&hwaddr_source_);
  821. bind_[14].is_unsigned = MLM_TRUE;
  822. } else {
  823. hwaddr_source_ = 0;
  824. bind_[14].buffer_type = MYSQL_TYPE_NULL;
  825. // According to http://dev.mysql.com/doc/refman/5.5/en/
  826. // c-api-prepared-statement-data-structures.html, the other
  827. // fields doesn't matter if type is set to MYSQL_TYPE_NULL,
  828. // but let's set them to some sane values in case earlier versions
  829. // didn't have that assumption.
  830. hwaddr_null_ = MLM_TRUE;
  831. bind_[14].buffer = NULL;
  832. bind_[14].is_null = &hwaddr_null_;
  833. }
  834. // state: uint32_t
  835. bind_[15].buffer_type = MYSQL_TYPE_LONG;
  836. bind_[15].buffer = reinterpret_cast<char*>(&lease_->state_);
  837. bind_[15].is_unsigned = MLM_TRUE;
  838. // bind_[15].is_null = &MLM_FALSE; // commented out for performance
  839. // reasons, see memset() above
  840. // Add the error flags
  841. setErrorIndicators(bind_, error_, LEASE_COLUMNS);
  842. // .. and check that we have the numbers correct at compile time.
  843. BOOST_STATIC_ASSERT(14 < LEASE_COLUMNS);
  844. } catch (const std::exception& ex) {
  845. isc_throw(DbOperationError,
  846. "Could not create bind array from Lease6: "
  847. << lease_->addr_.toText() << ", reason: " << ex.what());
  848. }
  849. // Add the data to the vector. Note the end element is one after the
  850. // end of the array.
  851. return (std::vector<MYSQL_BIND>(&bind_[0], &bind_[LEASE_COLUMNS]));
  852. }
  853. /// @brief Create BIND array to receive data
  854. ///
  855. /// Creates a MYSQL_BIND array to receive Lease6 data from the database.
  856. /// After data is successfully received, getLeaseData() is used to copy
  857. /// it to a Lease6 object.
  858. ///
  859. /// @return Vector of MySQL BIND objects passed to the MySQL data retrieval
  860. /// functions.
  861. std::vector<MYSQL_BIND> createBindForReceive() {
  862. // Initialize MYSQL_BIND array.
  863. // It sets all fields, including is_null, to zero, so we need to set
  864. // is_null only if it should be true. This gives up minor performance
  865. // benefit while being safe approach. For improved readability, the
  866. // code that explicitly sets is_null is there, but is commented out.
  867. memset(bind_, 0, sizeof(bind_));
  868. // address: varchar(39)
  869. // A Lease6_ address has a maximum of 39 characters. The array is
  870. // one byte longer than this to guarantee that we can always null
  871. // terminate it whatever is returned.
  872. addr6_length_ = sizeof(addr6_buffer_) - 1;
  873. bind_[0].buffer_type = MYSQL_TYPE_STRING;
  874. bind_[0].buffer = addr6_buffer_;
  875. bind_[0].buffer_length = addr6_length_;
  876. bind_[0].length = &addr6_length_;
  877. // bind_[0].is_null = &MLM_FALSE; // commented out for performance
  878. // reasons, see memset() above
  879. // client_id: varbinary(128)
  880. duid_length_ = sizeof(duid_buffer_);
  881. bind_[1].buffer_type = MYSQL_TYPE_BLOB;
  882. bind_[1].buffer = reinterpret_cast<char*>(duid_buffer_);
  883. bind_[1].buffer_length = duid_length_;
  884. bind_[1].length = &duid_length_;
  885. // bind_[1].is_null = &MLM_FALSE; // commented out for performance
  886. // reasons, see memset() above
  887. // lease_time: unsigned int
  888. bind_[2].buffer_type = MYSQL_TYPE_LONG;
  889. bind_[2].buffer = reinterpret_cast<char*>(&valid_lifetime_);
  890. bind_[2].is_unsigned = MLM_TRUE;
  891. // bind_[2].is_null = &MLM_FALSE; // commented out for performance
  892. // reasons, see memset() above
  893. // expire: timestamp
  894. bind_[3].buffer_type = MYSQL_TYPE_TIMESTAMP;
  895. bind_[3].buffer = reinterpret_cast<char*>(&expire_);
  896. bind_[3].buffer_length = sizeof(expire_);
  897. // bind_[3].is_null = &MLM_FALSE; // commented out for performance
  898. // reasons, see memset() above
  899. // subnet_id: unsigned int
  900. bind_[4].buffer_type = MYSQL_TYPE_LONG;
  901. bind_[4].buffer = reinterpret_cast<char*>(&subnet_id_);
  902. bind_[4].is_unsigned = MLM_TRUE;
  903. // bind_[4].is_null = &MLM_FALSE; // commented out for performance
  904. // reasons, see memset() above
  905. // pref_lifetime: unsigned int
  906. bind_[5].buffer_type = MYSQL_TYPE_LONG;
  907. bind_[5].buffer = reinterpret_cast<char*>(&pref_lifetime_);
  908. bind_[5].is_unsigned = MLM_TRUE;
  909. // bind_[5].is_null = &MLM_FALSE; // commented out for performance
  910. // reasons, see memset() above
  911. // lease_type: tinyint
  912. bind_[6].buffer_type = MYSQL_TYPE_TINY;
  913. bind_[6].buffer = reinterpret_cast<char*>(&lease_type_);
  914. bind_[6].is_unsigned = MLM_TRUE;
  915. // bind_[6].is_null = &MLM_FALSE; // commented out for performance
  916. // reasons, see memset() above
  917. // iaid: unsigned int
  918. bind_[7].buffer_type = MYSQL_TYPE_LONG;
  919. bind_[7].buffer = reinterpret_cast<char*>(&iaid_);
  920. bind_[7].is_unsigned = MLM_TRUE;
  921. // bind_[7].is_null = &MLM_FALSE; // commented out for performance
  922. // reasons, see memset() above
  923. // prefix_len: unsigned tinyint
  924. bind_[8].buffer_type = MYSQL_TYPE_TINY;
  925. bind_[8].buffer = reinterpret_cast<char*>(&prefixlen_);
  926. bind_[8].is_unsigned = MLM_TRUE;
  927. // bind_[8].is_null = &MLM_FALSE; // commented out for performance
  928. // reasons, see memset() above
  929. // fqdn_fwd: boolean
  930. bind_[9].buffer_type = MYSQL_TYPE_TINY;
  931. bind_[9].buffer = reinterpret_cast<char*>(&fqdn_fwd_);
  932. bind_[9].is_unsigned = MLM_TRUE;
  933. // bind_[9].is_null = &MLM_FALSE; // commented out for performance
  934. // reasons, see memset() above
  935. // fqdn_rev: boolean
  936. bind_[10].buffer_type = MYSQL_TYPE_TINY;
  937. bind_[10].buffer = reinterpret_cast<char*>(&fqdn_rev_);
  938. bind_[10].is_unsigned = MLM_TRUE;
  939. // bind_[10].is_null = &MLM_FALSE; // commented out for performance
  940. // reasons, see memset() above
  941. // hostname: varchar(255)
  942. hostname_length_ = sizeof(hostname_buffer_);
  943. bind_[11].buffer_type = MYSQL_TYPE_STRING;
  944. bind_[11].buffer = reinterpret_cast<char*>(hostname_buffer_);
  945. bind_[11].buffer_length = hostname_length_;
  946. bind_[11].length = &hostname_length_;
  947. // bind_[11].is_null = &MLM_FALSE; // commented out for performance
  948. // reasons, see memset() above
  949. // hardware address
  950. // hwaddr: varbinary(20)
  951. hwaddr_null_ = MLM_FALSE;
  952. hwaddr_length_ = sizeof(hwaddr_buffer_);
  953. bind_[12].buffer_type = MYSQL_TYPE_BLOB;
  954. bind_[12].buffer = reinterpret_cast<char*>(hwaddr_buffer_);
  955. bind_[12].buffer_length = hwaddr_length_;
  956. bind_[12].length = &hwaddr_length_;
  957. bind_[12].is_null = &hwaddr_null_;
  958. // hardware type: unsigned short int (16 bits)
  959. bind_[13].buffer_type = MYSQL_TYPE_SHORT;
  960. bind_[13].buffer = reinterpret_cast<char*>(&hwtype_);
  961. bind_[13].is_unsigned = MLM_TRUE;
  962. // hardware source: unsigned int (32 bits)
  963. bind_[14].buffer_type = MYSQL_TYPE_LONG;
  964. bind_[14].buffer = reinterpret_cast<char*>(&hwaddr_source_);
  965. bind_[14].is_unsigned = MLM_TRUE;
  966. // state: uint32_t
  967. bind_[15].buffer_type = MYSQL_TYPE_LONG;
  968. bind_[15].buffer = reinterpret_cast<char*>(&state_);
  969. bind_[15].is_unsigned = MLM_TRUE;
  970. // bind_[15].is_null = &MLM_FALSE; // commented out for performance
  971. // reasons, see memset() above
  972. // Add the error flags
  973. setErrorIndicators(bind_, error_, LEASE_COLUMNS);
  974. // .. and check that we have the numbers correct at compile time.
  975. BOOST_STATIC_ASSERT(15 < LEASE_COLUMNS);
  976. // Add the data to the vector. Note the end element is one after the
  977. // end of the array.
  978. return(std::vector<MYSQL_BIND>(&bind_[0], &bind_[LEASE_COLUMNS]));
  979. }
  980. /// @brief Copy Received Data into Lease6 Object
  981. ///
  982. /// Called after the MYSQL_BIND array created by createBindForReceive()
  983. /// has been used, this copies data from the internal member variables
  984. /// into a Lease6 object.
  985. ///
  986. /// @return Lease6Ptr Pointer to a Lease6 object holding the relevant
  987. /// data.
  988. ///
  989. /// @throw isc::BadValue Unable to convert Lease Type value in database
  990. Lease6Ptr getLeaseData() {
  991. // The address buffer is declared larger than the buffer size passed
  992. // to the access function so that we can always append a null byte.
  993. // Create the IOAddress object corresponding to the received data.
  994. addr6_buffer_[addr6_length_] = '\0';
  995. std::string address = addr6_buffer_;
  996. isc::asiolink::IOAddress addr(address);
  997. // Set the lease type in a variable of the appropriate data type, which
  998. // has been initialized with an arbitrary (but valid) value.
  999. Lease::Type type = Lease::TYPE_NA;
  1000. switch (lease_type_) {
  1001. case Lease::TYPE_NA:
  1002. type = Lease::TYPE_NA;
  1003. break;
  1004. case Lease::TYPE_TA:
  1005. type = Lease::TYPE_TA;
  1006. break;
  1007. case Lease::TYPE_PD:
  1008. type = Lease::TYPE_PD;
  1009. break;
  1010. default:
  1011. isc_throw(BadValue, "invalid lease type returned (" <<
  1012. static_cast<int>(lease_type_) << ") for lease with "
  1013. << "address " << address << ". Only 0, 1, or 2 are "
  1014. << "allowed.");
  1015. }
  1016. // Set up DUID,
  1017. DuidPtr duid_ptr(new DUID(duid_buffer_, duid_length_));
  1018. // Hostname is passed to Lease6 as a string object, so we have to
  1019. // create it from the hostname buffer and length.
  1020. std::string hostname(hostname_buffer_,
  1021. hostname_buffer_ + hostname_length_);
  1022. /// Set hardware address if it was set
  1023. HWAddrPtr hwaddr;
  1024. if (hwaddr_null_ == MLM_FALSE) {
  1025. hwaddr.reset(new HWAddr(hwaddr_buffer_, hwaddr_length_, hwtype_));
  1026. hwaddr->source_ = hwaddr_source_;
  1027. }
  1028. // Create the lease and set the cltt (after converting from the
  1029. // expire time retrieved from the database).
  1030. Lease6Ptr result(new Lease6(type, addr, duid_ptr, iaid_,
  1031. pref_lifetime_, valid_lifetime_, 0, 0,
  1032. subnet_id_, fqdn_fwd_, fqdn_rev_,
  1033. hostname, hwaddr, prefixlen_));
  1034. time_t cltt = 0;
  1035. MySqlConnection::convertFromDatabaseTime(expire_, valid_lifetime_, cltt);
  1036. result->cltt_ = cltt;
  1037. // Set state.
  1038. result->state_ = state_;
  1039. return (result);
  1040. }
  1041. /// @brief Return columns in error
  1042. ///
  1043. /// If an error is returned from a fetch (in particular, a truncated
  1044. /// status), this method can be called to get the names of the fields in
  1045. /// error. It returns a string comprising the names of the fields
  1046. /// separated by commas. In the case of there being no error indicators
  1047. /// set, it returns the string "(None)".
  1048. ///
  1049. /// @return Comma-separated list of columns in error, or the string
  1050. /// "(None)".
  1051. std::string getErrorColumns() {
  1052. return (getColumnsInError(error_, columns_, LEASE_COLUMNS));
  1053. }
  1054. private:
  1055. // Note: All array lengths are equal to the corresponding variable in the
  1056. // schema.
  1057. // Note: arrays are declared fixed length for speed of creation
  1058. std::string addr6_; ///< String form of address
  1059. char addr6_buffer_[ADDRESS6_TEXT_MAX_LEN + 1]; ///< Character
  1060. ///< array form of V6 address
  1061. unsigned long addr6_length_; ///< Length of the address
  1062. MYSQL_BIND bind_[LEASE_COLUMNS]; ///< Bind array
  1063. std::string columns_[LEASE_COLUMNS];///< Column names
  1064. std::vector<uint8_t> duid_; ///< Client identification
  1065. uint8_t duid_buffer_[DUID::MAX_DUID_LEN]; ///< Buffer form of DUID
  1066. unsigned long duid_length_; ///< Length of the DUID
  1067. my_bool error_[LEASE_COLUMNS]; ///< Error indicators
  1068. MYSQL_TIME expire_; ///< Lease expiry time
  1069. uint32_t iaid_; ///< Identity association ID
  1070. Lease6Ptr lease_; ///< Pointer to lease object
  1071. uint8_t lease_type_; ///< Lease type
  1072. uint8_t prefixlen_; ///< Prefix length
  1073. uint32_t pref_lifetime_; ///< Preferred lifetime
  1074. uint32_t subnet_id_; ///< Subnet identification
  1075. uint32_t valid_lifetime_; ///< Lease time
  1076. my_bool fqdn_fwd_; ///< Has forward DNS update been
  1077. ///< performed
  1078. my_bool fqdn_rev_; ///< Has reverse DNS update been
  1079. ///< performed
  1080. char hostname_buffer_[HOSTNAME_MAX_LEN];
  1081. ///< Client hostname
  1082. unsigned long hostname_length_; ///< Client hostname length
  1083. uint8_t hwaddr_buffer_[HWAddr::MAX_HWADDR_LEN];
  1084. ///< Buffer for Hardware address
  1085. std::vector<uint8_t> hwaddr_; ///< Hardware address (optional)
  1086. unsigned long hwaddr_length_; ///< Aux. variable denoting hwaddr_ size()
  1087. my_bool hwaddr_null_; ///< Used when HWAddr is null
  1088. uint16_t hwtype_; ///< Hardware type
  1089. uint32_t hwaddr_source_; ///< Source of the hardware address
  1090. uint32_t state_; ///< Lease state.
  1091. };
  1092. /// @brief MySql derivation of the statistical lease data query
  1093. ///
  1094. /// This class is used to recalculate lease statistics for MySQL
  1095. /// lease storage. It does so by executing a query which returns a result
  1096. /// containing one row per monitored state per lease type per
  1097. /// subnet, ordered by subnet id in ascending order.
  1098. ///
  1099. class MySqlLeaseStatsQuery : public LeaseStatsQuery {
  1100. public:
  1101. /// @brief Constructor
  1102. ///
  1103. /// @param conn A open connection to the database housing the lease data
  1104. /// @param statement_index Index of the query's prepared statement
  1105. /// @param fetch_type Indicates if query supplies lease type
  1106. MySqlLeaseStatsQuery(MySqlConnection& conn, const size_t statement_index,
  1107. const bool fetch_type)
  1108. : conn_(conn), statement_index_(statement_index), statement_(NULL),
  1109. fetch_type_(fetch_type),
  1110. // Set the number of columns in the bind array based on fetch_type
  1111. // This is the number of columns expected in the result set
  1112. bind_(fetch_type_ ? 4 : 3),
  1113. subnet_id_(0), lease_type_(0), lease_state_(0), state_count_(0) {
  1114. if (statement_index_ >= MySqlLeaseMgr::NUM_STATEMENTS) {
  1115. isc_throw(BadValue, "MySqlLeaseStatsQuery"
  1116. " - invalid statement index" << statement_index_);
  1117. }
  1118. statement_ = conn.statements_[statement_index_];
  1119. }
  1120. /// @brief Destructor
  1121. virtual ~MySqlLeaseStatsQuery() {
  1122. (void) mysql_stmt_free_result(statement_);
  1123. }
  1124. /// @brief Creates the IPv4 lease statistical data result set
  1125. ///
  1126. /// The result set is populated by executing a SQL query against the
  1127. /// lease(4/6) table which sums the leases per lease state per lease
  1128. /// type (v6 only) per subnet id. This method binds the statement to
  1129. /// the output bind array and then executes the statement, and fetches
  1130. /// entire result set.
  1131. void start() {
  1132. int col = 0;
  1133. // subnet_id: unsigned int
  1134. bind_[col].buffer_type = MYSQL_TYPE_LONG;
  1135. bind_[col].buffer = reinterpret_cast<char*>(&subnet_id_);
  1136. bind_[col].is_unsigned = MLM_TRUE;
  1137. ++col;
  1138. // Fetch the lease type if we were told to do so.
  1139. if (fetch_type_) {
  1140. // lease type: uint32_t
  1141. bind_[col].buffer_type = MYSQL_TYPE_LONG;
  1142. bind_[col].buffer = reinterpret_cast<char*>(&lease_type_);
  1143. bind_[col].is_unsigned = MLM_TRUE;
  1144. ++col;
  1145. } else {
  1146. fetch_type_ = Lease::TYPE_NA;
  1147. }
  1148. // state: uint32_t
  1149. bind_[col].buffer_type = MYSQL_TYPE_LONG;
  1150. bind_[col].buffer = reinterpret_cast<char*>(&lease_state_);
  1151. bind_[col].is_unsigned = MLM_TRUE;
  1152. ++col;
  1153. // state_count_: uint32_t
  1154. bind_[col].buffer_type = MYSQL_TYPE_LONG;
  1155. bind_[col].buffer = reinterpret_cast<char*>(&state_count_);
  1156. bind_[col].is_unsigned = MLM_TRUE;
  1157. // Set up the MYSQL_BIND array for the data being returned
  1158. // and bind it to the statement.
  1159. int status = mysql_stmt_bind_result(statement_, &bind_[0]);
  1160. conn_.checkError(status, statement_index_, "outbound binding failed");
  1161. // Execute the statement
  1162. status = mysql_stmt_execute(statement_);
  1163. conn_.checkError(status, statement_index_, "unable to execute");
  1164. // Ensure that all the lease information is retrieved in one go to avoid
  1165. // overhead of going back and forth between client and server.
  1166. status = mysql_stmt_store_result(statement_);
  1167. conn_.checkError(status, statement_index_, "results storage failed");
  1168. }
  1169. /// @brief Fetches the next row in the result set
  1170. ///
  1171. /// Once the internal result set has been populated by invoking the
  1172. /// the start() method, this method is used to iterate over the
  1173. /// result set rows. Once the last row has been fetched, subsequent
  1174. /// calls will return false.
  1175. ///
  1176. /// @param row Storage for the fetched row
  1177. ///
  1178. /// @return True if the fetch succeeded, false if there are no more
  1179. /// rows to fetch.
  1180. bool getNextRow(LeaseStatsRow& row) {
  1181. bool have_row = false;
  1182. int status = mysql_stmt_fetch(statement_);
  1183. if (status == MLM_MYSQL_FETCH_SUCCESS) {
  1184. row.subnet_id_ = static_cast<SubnetID>(subnet_id_);
  1185. row.lease_type_ = static_cast<Lease::Type>(lease_type_);
  1186. row.lease_state_ = lease_state_;
  1187. row.state_count_ = state_count_;
  1188. have_row = true;
  1189. } else if (status != MYSQL_NO_DATA) {
  1190. conn_.checkError(status, statement_index_, "getNextRow failed");
  1191. }
  1192. return (have_row);
  1193. }
  1194. private:
  1195. /// @brief Database connection to use to execute the query
  1196. MySqlConnection& conn_;
  1197. /// @brief Index of the query's prepared statement
  1198. size_t statement_index_;
  1199. /// @brief The query's prepared statement
  1200. MYSQL_STMT *statement_;
  1201. /// @brief Indicates if query supplies lease type
  1202. bool fetch_type_;
  1203. /// @brief Bind array used to store the query result set;
  1204. std::vector<MYSQL_BIND> bind_;
  1205. /// @brief Receives subnet ID when fetching a row
  1206. uint32_t subnet_id_;
  1207. /// @brief Receives the lease type when fetching a row
  1208. uint32_t lease_type_;
  1209. /// @brief Receives the lease state when fetching a row
  1210. uint32_t lease_state_;
  1211. /// @brief Receives the state count when fetching a row
  1212. uint32_t state_count_;
  1213. };
  1214. // MySqlLeaseMgr Constructor and Destructor
  1215. MySqlLeaseMgr::MySqlLeaseMgr(const MySqlConnection::ParameterMap& parameters)
  1216. : conn_(parameters) {
  1217. // Open the database.
  1218. conn_.openDatabase();
  1219. // Enable autocommit. To avoid a flush to disk on every commit, the global
  1220. // parameter innodb_flush_log_at_trx_commit should be set to 2. This will
  1221. // cause the changes to be written to the log, but flushed to disk in the
  1222. // background every second. Setting the parameter to that value will speed
  1223. // up the system, but at the risk of losing data if the system crashes.
  1224. my_bool result = mysql_autocommit(conn_.mysql_, 1);
  1225. if (result != 0) {
  1226. isc_throw(DbOperationError, mysql_error(conn_.mysql_));
  1227. }
  1228. // Prepare all statements likely to be used.
  1229. conn_.prepareStatements(tagged_statements.begin(), tagged_statements.end());
  1230. // Create the exchange objects for use in exchanging data between the
  1231. // program and the database.
  1232. exchange4_.reset(new MySqlLease4Exchange());
  1233. exchange6_.reset(new MySqlLease6Exchange());
  1234. }
  1235. MySqlLeaseMgr::~MySqlLeaseMgr() {
  1236. // There is no need to close the database in this destructor: it is
  1237. // closed in the destructor of the mysql_ member variable.
  1238. }
  1239. std::string
  1240. MySqlLeaseMgr::getDBVersion() {
  1241. std::stringstream tmp;
  1242. tmp << "MySQL backend " << MYSQL_SCHEMA_VERSION_MAJOR;
  1243. tmp << "." << MYSQL_SCHEMA_VERSION_MINOR;
  1244. tmp << ", library " << mysql_get_client_info();
  1245. return (tmp.str());
  1246. }
  1247. // Add leases to the database. The two public methods accept a lease object
  1248. // (either V4 of V6), bind the contents to the appropriate prepared
  1249. // statement, then call common code to execute the statement.
  1250. bool
  1251. MySqlLeaseMgr::addLeaseCommon(StatementIndex stindex,
  1252. std::vector<MYSQL_BIND>& bind) {
  1253. // Bind the parameters to the statement
  1254. int status = mysql_stmt_bind_param(conn_.statements_[stindex], &bind[0]);
  1255. checkError(status, stindex, "unable to bind parameters");
  1256. // Execute the statement
  1257. status = mysql_stmt_execute(conn_.statements_[stindex]);
  1258. if (status != 0) {
  1259. // Failure: check for the special case of duplicate entry. If this is
  1260. // the case, we return false to indicate that the row was not added.
  1261. // Otherwise we throw an exception.
  1262. if (mysql_errno(conn_.mysql_) == ER_DUP_ENTRY) {
  1263. return (false);
  1264. }
  1265. checkError(status, stindex, "unable to execute");
  1266. }
  1267. // Insert succeeded
  1268. return (true);
  1269. }
  1270. bool
  1271. MySqlLeaseMgr::addLease(const Lease4Ptr& lease) {
  1272. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1273. DHCPSRV_MYSQL_ADD_ADDR4).arg(lease->addr_.toText());
  1274. // Create the MYSQL_BIND array for the lease
  1275. std::vector<MYSQL_BIND> bind = exchange4_->createBindForSend(lease);
  1276. // ... and drop to common code.
  1277. return (addLeaseCommon(INSERT_LEASE4, bind));
  1278. }
  1279. bool
  1280. MySqlLeaseMgr::addLease(const Lease6Ptr& lease) {
  1281. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1282. DHCPSRV_MYSQL_ADD_ADDR6).arg(lease->addr_.toText())
  1283. .arg(lease->type_);
  1284. // Create the MYSQL_BIND array for the lease
  1285. std::vector<MYSQL_BIND> bind = exchange6_->createBindForSend(lease);
  1286. // ... and drop to common code.
  1287. return (addLeaseCommon(INSERT_LEASE6, bind));
  1288. }
  1289. // Extraction of leases from the database.
  1290. //
  1291. // All getLease() methods ultimately call getLeaseCollection(). This
  1292. // binds the input parameters passed to it with the appropriate prepared
  1293. // statement and executes the statement. It then gets the results from the
  1294. // database. getlease() methods that expect a single result back call it
  1295. // with the "single" parameter set true: this causes an exception to be
  1296. // generated if multiple records can be retrieved from the result set. (Such
  1297. // an occurrence either indicates corruption in the database, or that an
  1298. // assumption that a query can only return a single record is incorrect.)
  1299. // Methods that require a collection of records have "single" set to the
  1300. // default value of false. The logic is the same for both Lease4 and Lease6
  1301. // objects, so the code is templated.
  1302. //
  1303. // Methods that require a collection of objects access this method through
  1304. // two interface methods (also called getLeaseCollection()). These are
  1305. // short enough as to be defined in the header file: all they do is to supply
  1306. // the appropriate MySqlLeaseXExchange object depending on the type of the
  1307. // LeaseCollection objects passed to them.
  1308. //
  1309. // Methods that require a single object to be returned access the method
  1310. // through two interface methods (called getLease()). As well as supplying
  1311. // the appropriate exchange object, they convert between lease collection
  1312. // holding zero or one leases into an appropriate Lease object.
  1313. template <typename Exchange, typename LeaseCollection>
  1314. void MySqlLeaseMgr::getLeaseCollection(StatementIndex stindex,
  1315. MYSQL_BIND* bind,
  1316. Exchange& exchange,
  1317. LeaseCollection& result,
  1318. bool single) const {
  1319. // Bind the selection parameters to the statement
  1320. int status = mysql_stmt_bind_param(conn_.statements_[stindex], bind);
  1321. checkError(status, stindex, "unable to bind WHERE clause parameter");
  1322. // Set up the MYSQL_BIND array for the data being returned and bind it to
  1323. // the statement.
  1324. std::vector<MYSQL_BIND> outbind = exchange->createBindForReceive();
  1325. status = mysql_stmt_bind_result(conn_.statements_[stindex], &outbind[0]);
  1326. checkError(status, stindex, "unable to bind SELECT clause parameters");
  1327. // Execute the statement
  1328. status = mysql_stmt_execute(conn_.statements_[stindex]);
  1329. checkError(status, stindex, "unable to execute");
  1330. // Ensure that all the lease information is retrieved in one go to avoid
  1331. // overhead of going back and forth between client and server.
  1332. status = mysql_stmt_store_result(conn_.statements_[stindex]);
  1333. checkError(status, stindex, "unable to set up for storing all results");
  1334. // Set up the fetch "release" object to release resources associated
  1335. // with the call to mysql_stmt_fetch when this method exits, then
  1336. // retrieve the data.
  1337. MySqlFreeResult fetch_release(conn_.statements_[stindex]);
  1338. int count = 0;
  1339. while ((status = mysql_stmt_fetch(conn_.statements_[stindex])) == 0) {
  1340. try {
  1341. result.push_back(exchange->getLeaseData());
  1342. } catch (const isc::BadValue& ex) {
  1343. // Rethrow the exception with a bit more data.
  1344. isc_throw(BadValue, ex.what() << ". Statement is <" <<
  1345. conn_.text_statements_[stindex] << ">");
  1346. }
  1347. if (single && (++count > 1)) {
  1348. isc_throw(MultipleRecords, "multiple records were found in the "
  1349. "database where only one was expected for query "
  1350. << conn_.text_statements_[stindex]);
  1351. }
  1352. }
  1353. // How did the fetch end?
  1354. if (status == 1) {
  1355. // Error - unable to fetch results
  1356. checkError(status, stindex, "unable to fetch results");
  1357. } else if (status == MYSQL_DATA_TRUNCATED) {
  1358. // Data truncated - throw an exception indicating what was at fault
  1359. isc_throw(DataTruncated, conn_.text_statements_[stindex]
  1360. << " returned truncated data: columns affected are "
  1361. << exchange->getErrorColumns());
  1362. }
  1363. }
  1364. void MySqlLeaseMgr::getLease(StatementIndex stindex, MYSQL_BIND* bind,
  1365. Lease4Ptr& result) const {
  1366. // Create appropriate collection object and get all leases matching
  1367. // the selection criteria. The "single" parameter is true to indicate
  1368. // that the called method should throw an exception if multiple
  1369. // matching records are found: this particular method is called when only
  1370. // one or zero matches is expected.
  1371. Lease4Collection collection;
  1372. getLeaseCollection(stindex, bind, exchange4_, collection, true);
  1373. // Return single record if present, else clear the lease.
  1374. if (collection.empty()) {
  1375. result.reset();
  1376. } else {
  1377. result = *collection.begin();
  1378. }
  1379. }
  1380. void MySqlLeaseMgr::getLease(StatementIndex stindex, MYSQL_BIND* bind,
  1381. Lease6Ptr& result) const {
  1382. // Create appropriate collection object and get all leases matching
  1383. // the selection criteria. The "single" parameter is true to indicate
  1384. // that the called method should throw an exception if multiple
  1385. // matching records are found: this particular method is called when only
  1386. // one or zero matches is expected.
  1387. Lease6Collection collection;
  1388. getLeaseCollection(stindex, bind, exchange6_, collection, true);
  1389. // Return single record if present, else clear the lease.
  1390. if (collection.empty()) {
  1391. result.reset();
  1392. } else {
  1393. result = *collection.begin();
  1394. }
  1395. }
  1396. // Basic lease access methods. Obtain leases from the database using various
  1397. // criteria.
  1398. Lease4Ptr
  1399. MySqlLeaseMgr::getLease4(const isc::asiolink::IOAddress& addr) const {
  1400. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1401. DHCPSRV_MYSQL_GET_ADDR4).arg(addr.toText());
  1402. // Set up the WHERE clause value
  1403. MYSQL_BIND inbind[1];
  1404. memset(inbind, 0, sizeof(inbind));
  1405. uint32_t addr4 = addr.toUint32();
  1406. inbind[0].buffer_type = MYSQL_TYPE_LONG;
  1407. inbind[0].buffer = reinterpret_cast<char*>(&addr4);
  1408. inbind[0].is_unsigned = MLM_TRUE;
  1409. // Get the data
  1410. Lease4Ptr result;
  1411. getLease(GET_LEASE4_ADDR, inbind, result);
  1412. return (result);
  1413. }
  1414. Lease4Collection
  1415. MySqlLeaseMgr::getLease4(const HWAddr& hwaddr) const {
  1416. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1417. DHCPSRV_MYSQL_GET_HWADDR).arg(hwaddr.toText());
  1418. // Set up the WHERE clause value
  1419. MYSQL_BIND inbind[1];
  1420. memset(inbind, 0, sizeof(inbind));
  1421. // As "buffer" is "char*" - even though the data is being read - we need
  1422. // to cast away the "const"ness as well as reinterpreting the data as
  1423. // a "char*". (We could avoid the "const_cast" by copying the data to a
  1424. // local variable, but as the data is only being read, this introduces
  1425. // an unnecessary copy).
  1426. unsigned long hwaddr_length = hwaddr.hwaddr_.size();
  1427. uint8_t* data = const_cast<uint8_t*>(&hwaddr.hwaddr_[0]);
  1428. inbind[0].buffer_type = MYSQL_TYPE_BLOB;
  1429. inbind[0].buffer = reinterpret_cast<char*>(data);
  1430. inbind[0].buffer_length = hwaddr_length;
  1431. inbind[0].length = &hwaddr_length;
  1432. // Get the data
  1433. Lease4Collection result;
  1434. getLeaseCollection(GET_LEASE4_HWADDR, inbind, result);
  1435. return (result);
  1436. }
  1437. Lease4Ptr
  1438. MySqlLeaseMgr::getLease4(const HWAddr& hwaddr, SubnetID subnet_id) const {
  1439. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1440. DHCPSRV_MYSQL_GET_SUBID_HWADDR)
  1441. .arg(subnet_id).arg(hwaddr.toText());
  1442. // Set up the WHERE clause value
  1443. MYSQL_BIND inbind[2];
  1444. memset(inbind, 0, sizeof(inbind));
  1445. // As "buffer" is "char*" - even though the data is being read - we need
  1446. // to cast away the "const"ness as well as reinterpreting the data as
  1447. // a "char*". (We could avoid the "const_cast" by copying the data to a
  1448. // local variable, but as the data is only being read, this introduces
  1449. // an unnecessary copy).
  1450. unsigned long hwaddr_length = hwaddr.hwaddr_.size();
  1451. uint8_t* data = const_cast<uint8_t*>(&hwaddr.hwaddr_[0]);
  1452. inbind[0].buffer_type = MYSQL_TYPE_BLOB;
  1453. inbind[0].buffer = reinterpret_cast<char*>(data);
  1454. inbind[0].buffer_length = hwaddr_length;
  1455. inbind[0].length = &hwaddr_length;
  1456. inbind[1].buffer_type = MYSQL_TYPE_LONG;
  1457. inbind[1].buffer = reinterpret_cast<char*>(&subnet_id);
  1458. inbind[1].is_unsigned = MLM_TRUE;
  1459. // Get the data
  1460. Lease4Ptr result;
  1461. getLease(GET_LEASE4_HWADDR_SUBID, inbind, result);
  1462. return (result);
  1463. }
  1464. Lease4Collection
  1465. MySqlLeaseMgr::getLease4(const ClientId& clientid) const {
  1466. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1467. DHCPSRV_MYSQL_GET_CLIENTID).arg(clientid.toText());
  1468. // Set up the WHERE clause value
  1469. MYSQL_BIND inbind[1];
  1470. memset(inbind, 0, sizeof(inbind));
  1471. std::vector<uint8_t> client_data = clientid.getClientId();
  1472. unsigned long client_data_length = client_data.size();
  1473. inbind[0].buffer_type = MYSQL_TYPE_BLOB;
  1474. inbind[0].buffer = reinterpret_cast<char*>(&client_data[0]);
  1475. inbind[0].buffer_length = client_data_length;
  1476. inbind[0].length = &client_data_length;
  1477. // Get the data
  1478. Lease4Collection result;
  1479. getLeaseCollection(GET_LEASE4_CLIENTID, inbind, result);
  1480. return (result);
  1481. }
  1482. Lease4Ptr
  1483. MySqlLeaseMgr::getLease4(const ClientId&, const HWAddr&, SubnetID) const {
  1484. /// This function is currently not implemented because allocation engine
  1485. /// searches for the lease using HW address or client identifier.
  1486. /// It never uses both parameters in the same time. We need to
  1487. /// consider if this function is needed at all.
  1488. isc_throw(NotImplemented, "The MySqlLeaseMgr::getLease4 function was"
  1489. " called, but it is not implemented");
  1490. }
  1491. Lease4Ptr
  1492. MySqlLeaseMgr::getLease4(const ClientId& clientid, SubnetID subnet_id) const {
  1493. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1494. DHCPSRV_MYSQL_GET_SUBID_CLIENTID)
  1495. .arg(subnet_id).arg(clientid.toText());
  1496. // Set up the WHERE clause value
  1497. MYSQL_BIND inbind[2];
  1498. memset(inbind, 0, sizeof(inbind));
  1499. std::vector<uint8_t> client_data = clientid.getClientId();
  1500. unsigned long client_data_length = client_data.size();
  1501. inbind[0].buffer_type = MYSQL_TYPE_BLOB;
  1502. inbind[0].buffer = reinterpret_cast<char*>(&client_data[0]);
  1503. inbind[0].buffer_length = client_data_length;
  1504. inbind[0].length = &client_data_length;
  1505. inbind[1].buffer_type = MYSQL_TYPE_LONG;
  1506. inbind[1].buffer = reinterpret_cast<char*>(&subnet_id);
  1507. inbind[1].is_unsigned = MLM_TRUE;
  1508. // Get the data
  1509. Lease4Ptr result;
  1510. getLease(GET_LEASE4_CLIENTID_SUBID, inbind, result);
  1511. return (result);
  1512. }
  1513. Lease6Ptr
  1514. MySqlLeaseMgr::getLease6(Lease::Type lease_type,
  1515. const isc::asiolink::IOAddress& addr) const {
  1516. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1517. DHCPSRV_MYSQL_GET_ADDR6).arg(addr.toText())
  1518. .arg(lease_type);
  1519. // Set up the WHERE clause value
  1520. MYSQL_BIND inbind[2];
  1521. memset(inbind, 0, sizeof(inbind));
  1522. std::string addr6 = addr.toText();
  1523. unsigned long addr6_length = addr6.size();
  1524. // See the earlier description of the use of "const_cast" when accessing
  1525. // the address for an explanation of the reason.
  1526. inbind[0].buffer_type = MYSQL_TYPE_STRING;
  1527. inbind[0].buffer = const_cast<char*>(addr6.c_str());
  1528. inbind[0].buffer_length = addr6_length;
  1529. inbind[0].length = &addr6_length;
  1530. // LEASE_TYPE
  1531. inbind[1].buffer_type = MYSQL_TYPE_TINY;
  1532. inbind[1].buffer = reinterpret_cast<char*>(&lease_type);
  1533. inbind[1].is_unsigned = MLM_TRUE;
  1534. Lease6Ptr result;
  1535. getLease(GET_LEASE6_ADDR, inbind, result);
  1536. return (result);
  1537. }
  1538. Lease6Collection
  1539. MySqlLeaseMgr::getLeases6(Lease::Type lease_type,
  1540. const DUID& duid, uint32_t iaid) const {
  1541. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1542. DHCPSRV_MYSQL_GET_IAID_DUID).arg(iaid).arg(duid.toText())
  1543. .arg(lease_type);
  1544. // Set up the WHERE clause value
  1545. MYSQL_BIND inbind[3];
  1546. memset(inbind, 0, sizeof(inbind));
  1547. // In the following statement, the DUID is being read. However, the
  1548. // MySQL C interface does not use "const", so the "buffer" element
  1549. // is declared as "char*" instead of "const char*". To resolve this,
  1550. // the "const" is discarded before the uint8_t* is cast to char*.
  1551. //
  1552. // Note that the const_cast could be avoided by copying the DUID to
  1553. // a writable buffer and storing the address of that in the "buffer"
  1554. // element. However, this introduces a copy operation (with additional
  1555. // overhead) purely to get round the structures introduced by design of
  1556. // the MySQL interface (which uses the area pointed to by "buffer" as
  1557. // input when specifying query parameters and as output when retrieving
  1558. // data). For that reason, "const_cast" has been used.
  1559. const vector<uint8_t>& duid_vector = duid.getDuid();
  1560. unsigned long duid_length = duid_vector.size();
  1561. inbind[0].buffer_type = MYSQL_TYPE_BLOB;
  1562. inbind[0].buffer = reinterpret_cast<char*>(
  1563. const_cast<uint8_t*>(&duid_vector[0]));
  1564. inbind[0].buffer_length = duid_length;
  1565. inbind[0].length = &duid_length;
  1566. // IAID
  1567. inbind[1].buffer_type = MYSQL_TYPE_LONG;
  1568. inbind[1].buffer = reinterpret_cast<char*>(&iaid);
  1569. inbind[1].is_unsigned = MLM_TRUE;
  1570. // LEASE_TYPE
  1571. inbind[2].buffer_type = MYSQL_TYPE_TINY;
  1572. inbind[2].buffer = reinterpret_cast<char*>(&lease_type);
  1573. inbind[2].is_unsigned = MLM_TRUE;
  1574. // ... and get the data
  1575. Lease6Collection result;
  1576. getLeaseCollection(GET_LEASE6_DUID_IAID, inbind, result);
  1577. return (result);
  1578. }
  1579. Lease6Collection
  1580. MySqlLeaseMgr::getLeases6(Lease::Type lease_type,
  1581. const DUID& duid, uint32_t iaid,
  1582. SubnetID subnet_id) const {
  1583. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1584. DHCPSRV_MYSQL_GET_IAID_SUBID_DUID)
  1585. .arg(iaid).arg(subnet_id).arg(duid.toText())
  1586. .arg(lease_type);
  1587. // Set up the WHERE clause value
  1588. MYSQL_BIND inbind[4];
  1589. memset(inbind, 0, sizeof(inbind));
  1590. // See the earlier description of the use of "const_cast" when accessing
  1591. // the DUID for an explanation of the reason.
  1592. const vector<uint8_t>& duid_vector = duid.getDuid();
  1593. unsigned long duid_length = duid_vector.size();
  1594. inbind[0].buffer_type = MYSQL_TYPE_BLOB;
  1595. inbind[0].buffer = reinterpret_cast<char*>(
  1596. const_cast<uint8_t*>(&duid_vector[0]));
  1597. inbind[0].buffer_length = duid_length;
  1598. inbind[0].length = &duid_length;
  1599. // IAID
  1600. inbind[1].buffer_type = MYSQL_TYPE_LONG;
  1601. inbind[1].buffer = reinterpret_cast<char*>(&iaid);
  1602. inbind[1].is_unsigned = MLM_TRUE;
  1603. // Subnet ID
  1604. inbind[2].buffer_type = MYSQL_TYPE_LONG;
  1605. inbind[2].buffer = reinterpret_cast<char*>(&subnet_id);
  1606. inbind[2].is_unsigned = MLM_TRUE;
  1607. // LEASE_TYPE
  1608. inbind[3].buffer_type = MYSQL_TYPE_TINY;
  1609. inbind[3].buffer = reinterpret_cast<char*>(&lease_type);
  1610. inbind[3].is_unsigned = MLM_TRUE;
  1611. // ... and get the data
  1612. Lease6Collection result;
  1613. getLeaseCollection(GET_LEASE6_DUID_IAID_SUBID, inbind, result);
  1614. return (result);
  1615. }
  1616. void
  1617. MySqlLeaseMgr::getExpiredLeases6(Lease6Collection& expired_leases,
  1618. const size_t max_leases) const {
  1619. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL, DHCPSRV_MYSQL_GET_EXPIRED6)
  1620. .arg(max_leases);
  1621. getExpiredLeasesCommon(expired_leases, max_leases, GET_LEASE6_EXPIRE);
  1622. }
  1623. void
  1624. MySqlLeaseMgr::getExpiredLeases4(Lease4Collection& expired_leases,
  1625. const size_t max_leases) const {
  1626. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL, DHCPSRV_MYSQL_GET_EXPIRED4)
  1627. .arg(max_leases);
  1628. getExpiredLeasesCommon(expired_leases, max_leases, GET_LEASE4_EXPIRE);
  1629. }
  1630. template<typename LeaseCollection>
  1631. void
  1632. MySqlLeaseMgr::getExpiredLeasesCommon(LeaseCollection& expired_leases,
  1633. const size_t max_leases,
  1634. StatementIndex statement_index) const {
  1635. // Set up the WHERE clause value
  1636. MYSQL_BIND inbind[3];
  1637. memset(inbind, 0, sizeof(inbind));
  1638. // Exclude reclaimed leases.
  1639. uint32_t state = static_cast<uint32_t>(Lease::STATE_EXPIRED_RECLAIMED);
  1640. inbind[0].buffer_type = MYSQL_TYPE_LONG;
  1641. inbind[0].buffer = reinterpret_cast<char*>(&state);
  1642. inbind[0].is_unsigned = MLM_TRUE;
  1643. // Expiration timestamp.
  1644. MYSQL_TIME expire_time;
  1645. conn_.convertToDatabaseTime(time(NULL), expire_time);
  1646. inbind[1].buffer_type = MYSQL_TYPE_TIMESTAMP;
  1647. inbind[1].buffer = reinterpret_cast<char*>(&expire_time);
  1648. inbind[1].buffer_length = sizeof(expire_time);
  1649. // If the number of leases is 0, we will return all leases. This is
  1650. // achieved by setting the limit to a very high value.
  1651. uint32_t limit = max_leases > 0 ? static_cast<uint32_t>(max_leases) :
  1652. std::numeric_limits<uint32_t>::max();
  1653. inbind[2].buffer_type = MYSQL_TYPE_LONG;
  1654. inbind[2].buffer = reinterpret_cast<char*>(&limit);
  1655. inbind[2].is_unsigned = MLM_TRUE;
  1656. // Get the data
  1657. getLeaseCollection(statement_index, inbind, expired_leases);
  1658. }
  1659. // Update lease methods. These comprise common code that handles the actual
  1660. // update, and type-specific methods that set up the parameters for the prepared
  1661. // statement depending on the type of lease.
  1662. template <typename LeasePtr>
  1663. void
  1664. MySqlLeaseMgr::updateLeaseCommon(StatementIndex stindex, MYSQL_BIND* bind,
  1665. const LeasePtr& lease) {
  1666. // Bind the parameters to the statement
  1667. int status = mysql_stmt_bind_param(conn_.statements_[stindex], bind);
  1668. checkError(status, stindex, "unable to bind parameters");
  1669. // Execute
  1670. status = mysql_stmt_execute(conn_.statements_[stindex]);
  1671. checkError(status, stindex, "unable to execute");
  1672. // See how many rows were affected. The statement should only update a
  1673. // single row.
  1674. int affected_rows = mysql_stmt_affected_rows(conn_.statements_[stindex]);
  1675. if (affected_rows == 0) {
  1676. isc_throw(NoSuchLease, "unable to update lease for address " <<
  1677. lease->addr_ << " as it does not exist");
  1678. } else if (affected_rows > 1) {
  1679. // Should not happen - primary key constraint should only have selected
  1680. // one row.
  1681. isc_throw(DbOperationError, "apparently updated more than one lease "
  1682. "that had the address " << lease->addr_);
  1683. }
  1684. }
  1685. void
  1686. MySqlLeaseMgr::updateLease4(const Lease4Ptr& lease) {
  1687. const StatementIndex stindex = UPDATE_LEASE4;
  1688. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1689. DHCPSRV_MYSQL_UPDATE_ADDR4).arg(lease->addr_.toText());
  1690. // Create the MYSQL_BIND array for the data being updated
  1691. std::vector<MYSQL_BIND> bind = exchange4_->createBindForSend(lease);
  1692. // Set up the WHERE clause and append it to the MYSQL_BIND array
  1693. MYSQL_BIND where;
  1694. memset(&where, 0, sizeof(where));
  1695. uint32_t addr4 = lease->addr_.toUint32();
  1696. where.buffer_type = MYSQL_TYPE_LONG;
  1697. where.buffer = reinterpret_cast<char*>(&addr4);
  1698. where.is_unsigned = MLM_TRUE;
  1699. bind.push_back(where);
  1700. // Drop to common update code
  1701. updateLeaseCommon(stindex, &bind[0], lease);
  1702. }
  1703. void
  1704. MySqlLeaseMgr::updateLease6(const Lease6Ptr& lease) {
  1705. const StatementIndex stindex = UPDATE_LEASE6;
  1706. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1707. DHCPSRV_MYSQL_UPDATE_ADDR6).arg(lease->addr_.toText())
  1708. .arg(lease->type_);
  1709. // Create the MYSQL_BIND array for the data being updated
  1710. std::vector<MYSQL_BIND> bind = exchange6_->createBindForSend(lease);
  1711. // Set up the WHERE clause value
  1712. MYSQL_BIND where;
  1713. memset(&where, 0, sizeof(where));
  1714. std::string addr6 = lease->addr_.toText();
  1715. unsigned long addr6_length = addr6.size();
  1716. // See the earlier description of the use of "const_cast" when accessing
  1717. // the address for an explanation of the reason.
  1718. where.buffer_type = MYSQL_TYPE_STRING;
  1719. where.buffer = const_cast<char*>(addr6.c_str());
  1720. where.buffer_length = addr6_length;
  1721. where.length = &addr6_length;
  1722. bind.push_back(where);
  1723. // Drop to common update code
  1724. updateLeaseCommon(stindex, &bind[0], lease);
  1725. }
  1726. // Delete lease methods. Similar to other groups of methods, these comprise
  1727. // a per-type method that sets up the relevant MYSQL_BIND array (in this
  1728. // case, a single method for both V4 and V6 addresses) and a common method that
  1729. // handles the common processing.
  1730. uint64_t
  1731. MySqlLeaseMgr::deleteLeaseCommon(StatementIndex stindex, MYSQL_BIND* bind) {
  1732. // Bind the input parameters to the statement
  1733. int status = mysql_stmt_bind_param(conn_.statements_[stindex], bind);
  1734. checkError(status, stindex, "unable to bind WHERE clause parameter");
  1735. // Execute
  1736. status = mysql_stmt_execute(conn_.statements_[stindex]);
  1737. checkError(status, stindex, "unable to execute");
  1738. // See how many rows were affected. Note that the statement may delete
  1739. // multiple rows.
  1740. return (static_cast<uint64_t>(mysql_stmt_affected_rows(conn_.statements_[stindex])));
  1741. }
  1742. bool
  1743. MySqlLeaseMgr::deleteLease(const isc::asiolink::IOAddress& addr) {
  1744. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1745. DHCPSRV_MYSQL_DELETE_ADDR).arg(addr.toText());
  1746. // Set up the WHERE clause value
  1747. MYSQL_BIND inbind[1];
  1748. memset(inbind, 0, sizeof(inbind));
  1749. if (addr.isV4()) {
  1750. uint32_t addr4 = addr.toUint32();
  1751. inbind[0].buffer_type = MYSQL_TYPE_LONG;
  1752. inbind[0].buffer = reinterpret_cast<char*>(&addr4);
  1753. inbind[0].is_unsigned = MLM_TRUE;
  1754. return (deleteLeaseCommon(DELETE_LEASE4, inbind) > 0);
  1755. } else {
  1756. std::string addr6 = addr.toText();
  1757. unsigned long addr6_length = addr6.size();
  1758. // See the earlier description of the use of "const_cast" when accessing
  1759. // the address for an explanation of the reason.
  1760. inbind[0].buffer_type = MYSQL_TYPE_STRING;
  1761. inbind[0].buffer = const_cast<char*>(addr6.c_str());
  1762. inbind[0].buffer_length = addr6_length;
  1763. inbind[0].length = &addr6_length;
  1764. return (deleteLeaseCommon(DELETE_LEASE6, inbind) > 0);
  1765. }
  1766. }
  1767. uint64_t
  1768. MySqlLeaseMgr::deleteExpiredReclaimedLeases4(const uint32_t secs) {
  1769. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1770. DHCPSRV_MYSQL_DELETE_EXPIRED_RECLAIMED4)
  1771. .arg(secs);
  1772. return (deleteExpiredReclaimedLeasesCommon(secs, DELETE_LEASE4_STATE_EXPIRED));
  1773. }
  1774. uint64_t
  1775. MySqlLeaseMgr::deleteExpiredReclaimedLeases6(const uint32_t secs) {
  1776. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1777. DHCPSRV_MYSQL_DELETE_EXPIRED_RECLAIMED6)
  1778. .arg(secs);
  1779. return (deleteExpiredReclaimedLeasesCommon(secs, DELETE_LEASE6_STATE_EXPIRED));
  1780. }
  1781. uint64_t
  1782. MySqlLeaseMgr::deleteExpiredReclaimedLeasesCommon(const uint32_t secs,
  1783. StatementIndex statement_index) {
  1784. // Set up the WHERE clause value
  1785. MYSQL_BIND inbind[2];
  1786. memset(inbind, 0, sizeof(inbind));
  1787. // State is reclaimed.
  1788. uint32_t state = static_cast<uint32_t>(Lease::STATE_EXPIRED_RECLAIMED);
  1789. inbind[0].buffer_type = MYSQL_TYPE_LONG;
  1790. inbind[0].buffer = reinterpret_cast<char*>(&state);
  1791. inbind[0].is_unsigned = MLM_TRUE;
  1792. // Expiration timestamp.
  1793. MYSQL_TIME expire_time;
  1794. conn_.convertToDatabaseTime(time(NULL) - static_cast<time_t>(secs), expire_time);
  1795. inbind[1].buffer_type = MYSQL_TYPE_TIMESTAMP;
  1796. inbind[1].buffer = reinterpret_cast<char*>(&expire_time);
  1797. inbind[1].buffer_length = sizeof(expire_time);
  1798. // Get the number of deleted leases and log it.
  1799. uint64_t deleted_leases = deleteLeaseCommon(statement_index, inbind);
  1800. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1801. DHCPSRV_MYSQL_DELETED_EXPIRED_RECLAIMED)
  1802. .arg(deleted_leases);
  1803. return (deleted_leases);
  1804. }
  1805. size_t
  1806. MySqlLeaseMgr::wipeLeases4(const SubnetID& /*subnet_id*/) {
  1807. isc_throw(NotImplemented, "wipeLeases4 is not implemented for MySQL backend");
  1808. }
  1809. size_t
  1810. MySqlLeaseMgr::wipeLeases6(const SubnetID& /*subnet_id*/) {
  1811. isc_throw(NotImplemented, "wipeLeases6 is not implemented for MySQL backend");
  1812. }
  1813. // Miscellaneous database methods.
  1814. std::string
  1815. MySqlLeaseMgr::getName() const {
  1816. std::string name = "";
  1817. try {
  1818. name = conn_.getParameter("name");
  1819. } catch (...) {
  1820. // Return an empty name
  1821. }
  1822. return (name);
  1823. }
  1824. std::string
  1825. MySqlLeaseMgr::getDescription() const {
  1826. return (std::string("MySQL Database"));
  1827. }
  1828. std::pair<uint32_t, uint32_t>
  1829. MySqlLeaseMgr::getVersion() const {
  1830. const StatementIndex stindex = GET_VERSION;
  1831. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1832. DHCPSRV_MYSQL_GET_VERSION);
  1833. uint32_t major; // Major version number
  1834. uint32_t minor; // Minor version number
  1835. // Execute the prepared statement
  1836. int status = mysql_stmt_execute(conn_.statements_[stindex]);
  1837. if (status != 0) {
  1838. isc_throw(DbOperationError, "unable to execute <"
  1839. << conn_.text_statements_[stindex] << "> - reason: " <<
  1840. mysql_error(conn_.mysql_));
  1841. }
  1842. // Bind the output of the statement to the appropriate variables.
  1843. MYSQL_BIND bind[2];
  1844. memset(bind, 0, sizeof(bind));
  1845. bind[0].buffer_type = MYSQL_TYPE_LONG;
  1846. bind[0].is_unsigned = 1;
  1847. bind[0].buffer = &major;
  1848. bind[0].buffer_length = sizeof(major);
  1849. bind[1].buffer_type = MYSQL_TYPE_LONG;
  1850. bind[1].is_unsigned = 1;
  1851. bind[1].buffer = &minor;
  1852. bind[1].buffer_length = sizeof(minor);
  1853. status = mysql_stmt_bind_result(conn_.statements_[stindex], bind);
  1854. if (status != 0) {
  1855. isc_throw(DbOperationError, "unable to bind result set: " <<
  1856. mysql_error(conn_.mysql_));
  1857. }
  1858. // Fetch the data and set up the "release" object to release associated
  1859. // resources when this method exits then retrieve the data.
  1860. MySqlFreeResult fetch_release(conn_.statements_[stindex]);
  1861. status = mysql_stmt_fetch(conn_.statements_[stindex]);
  1862. if (status != 0) {
  1863. isc_throw(DbOperationError, "unable to obtain result set: " <<
  1864. mysql_error(conn_.mysql_));
  1865. }
  1866. return (std::make_pair(major, minor));
  1867. }
  1868. LeaseStatsQueryPtr
  1869. MySqlLeaseMgr::startLeaseStatsQuery4() {
  1870. LeaseStatsQueryPtr query(new MySqlLeaseStatsQuery(conn_,
  1871. RECOUNT_LEASE4_STATS,
  1872. false));
  1873. query->start();
  1874. return(query);
  1875. }
  1876. LeaseStatsQueryPtr
  1877. MySqlLeaseMgr::startLeaseStatsQuery6() {
  1878. LeaseStatsQueryPtr query(new MySqlLeaseStatsQuery(conn_,
  1879. RECOUNT_LEASE6_STATS,
  1880. true));
  1881. query->start();
  1882. return(query);
  1883. }
  1884. void
  1885. MySqlLeaseMgr::commit() {
  1886. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL, DHCPSRV_MYSQL_COMMIT);
  1887. if (mysql_commit(conn_.mysql_) != 0) {
  1888. isc_throw(DbOperationError, "commit failed: " << mysql_error(conn_.mysql_));
  1889. }
  1890. }
  1891. void
  1892. MySqlLeaseMgr::rollback() {
  1893. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL, DHCPSRV_MYSQL_ROLLBACK);
  1894. if (mysql_rollback(conn_.mysql_) != 0) {
  1895. isc_throw(DbOperationError, "rollback failed: " << mysql_error(conn_.mysql_));
  1896. }
  1897. }
  1898. void
  1899. MySqlLeaseMgr::checkError(int status, StatementIndex index,
  1900. const char* what) const {
  1901. conn_.checkError(status, index, what);
  1902. }
  1903. }; // end of isc::dhcp namespace
  1904. }; // end of isc namespace