mysql_lease_mgr.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. // Copyright (C) 2012 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #ifndef MYSQL_LEASE_MGR_H
  15. #define MYSQL_LEASE_MGR_H
  16. #include <dhcpsrv/lease_mgr.h>
  17. #include <boost/scoped_ptr.hpp>
  18. #include <mysql/mysql.h>
  19. #include <time.h>
  20. namespace isc {
  21. namespace dhcp {
  22. // Define the current database schema values
  23. const uint32_t CURRENT_VERSION_VERSION = 0;
  24. const uint32_t CURRENT_VERSION_MINOR = 1;
  25. // Forward declaration of the Lease exchange objects. This class is defined
  26. // in the .cc file.
  27. class MySqlLease4Exchange;
  28. class MySqlLease6Exchange;
  29. /// @brief MySQL Lease Manager
  30. ///
  31. /// This is a concrete API for the backend for the MySQL database.
  32. class MySqlLeaseMgr : public LeaseMgr {
  33. public:
  34. /// @brief Constructor
  35. ///
  36. /// Uses the following keywords in the parameters passed to it to
  37. /// connect to the database:
  38. /// - name - Name of the database to which to connect (mandatory)
  39. /// - host - Host to which to connect (optional, defaults to "localhost")
  40. /// - user - Username under which to connect (optional)
  41. /// - password - Password for "user" on the database (optional)
  42. ///
  43. /// If the database is successfully opened, the version number in the
  44. /// schema_version table will be checked against hard-coded value in
  45. /// the implementation file.
  46. ///
  47. /// Finally, all the SQL commands are pre-compiled.
  48. ///
  49. /// @param parameters A data structure relating keywords and values
  50. /// concerned with the database.
  51. ///
  52. /// @throw isc::dhcp::NoDatabaseName Mandatory database name not given
  53. /// @throw isc::dhcp::DbOpenError Error opening the database
  54. /// @throw isc::dhcp::DbOperationError An operation on the open database has
  55. /// failed.
  56. MySqlLeaseMgr(const ParameterMap& parameters);
  57. /// @brief Destructor (closes database)
  58. virtual ~MySqlLeaseMgr();
  59. /// @brief Adds an IPv4 lease.
  60. ///
  61. /// @param lease lease to be added
  62. ///
  63. /// @result true if the lease was added, false if not (because a lease
  64. /// with the same address was already there).
  65. ///
  66. /// @throw isc::dhcp::DbOperationError An operation on the open database has
  67. /// failed.
  68. virtual bool addLease(const Lease4Ptr& lease);
  69. /// @brief Adds an IPv6 lease.
  70. ///
  71. /// @param lease lease to be added
  72. ///
  73. /// @result true if the lease was added, false if not (because a lease
  74. /// with the same address was already there).
  75. ///
  76. /// @throw isc::dhcp::DbOperationError An operation on the open database has
  77. /// failed.
  78. virtual bool addLease(const Lease6Ptr& lease);
  79. /// @brief Return IPv4 lease for specified IPv4 address and subnet_id
  80. ///
  81. /// This method is used to get a lease for specific subnet_id. There can be
  82. /// at most one lease for any given subnet, so this method returns a single
  83. /// pointer.
  84. ///
  85. /// @param addr address of the sought lease
  86. /// @param subnet_id ID of the subnet the lease must belong to
  87. ///
  88. /// @return smart pointer to the lease (or NULL if a lease is not found)
  89. virtual Lease4Ptr getLease4(const isc::asiolink::IOAddress& addr,
  90. SubnetID subnet_id) const;
  91. /// @brief Returns an IPv4 lease for specified IPv4 address
  92. ///
  93. /// This method return a lease that is associated with a given address.
  94. /// For other query types (by hardware addr, by DUID) there can be
  95. /// several leases in different subnets (e.g. for mobile clients that
  96. /// got address in different subnets). However, for a single address
  97. /// there can be only one lease, so this method returns a pointer to
  98. /// a single lease, not a container of leases.
  99. ///
  100. /// @param addr address of the searched lease
  101. ///
  102. /// @return smart pointer to the lease (or NULL if a lease is not found)
  103. virtual Lease4Ptr getLease4(const isc::asiolink::IOAddress& addr) const;
  104. /// @brief Returns existing IPv4 leases for specified hardware address.
  105. ///
  106. /// Although in the usual case there will be only one lease, for mobile
  107. /// clients or clients with multiple static/fixed/reserved leases there
  108. /// can be more than one. Thus return type is a container, not a single
  109. /// pointer.
  110. ///
  111. /// @param hwaddr hardware address of the client
  112. ///
  113. /// @return lease collection
  114. virtual Lease4Collection getLease4(const HWAddr& hwaddr) const;
  115. /// @brief Returns existing IPv4 leases for specified hardware address
  116. /// and a subnet
  117. ///
  118. /// There can be at most one lease for a given HW address in a single
  119. /// pool, so this method with either return a single lease or NULL.
  120. ///
  121. /// @param hwaddr hardware address of the client
  122. /// @param subnet_id identifier of the subnet that lease must belong to
  123. ///
  124. /// @return a pointer to the lease (or NULL if a lease is not found)
  125. virtual Lease4Ptr getLease4(const HWAddr& hwaddr,
  126. SubnetID subnet_id) const;
  127. /// @brief Returns existing IPv4 lease for specified client-id
  128. ///
  129. /// Although in the usual case there will be only one lease, for mobile
  130. /// clients or clients with multiple static/fixed/reserved leases there
  131. /// can be more than one. Thus return type is a container, not a single
  132. /// pointer.
  133. ///
  134. /// @param clientid client identifier
  135. ///
  136. /// @return lease collection
  137. virtual Lease4Collection getLease4(const ClientId& clientid) const;
  138. /// @brief Returns existing IPv4 lease for specified client-id
  139. ///
  140. /// There can be at most one lease for a given HW address in a single
  141. /// pool, so this method with either return a single lease or NULL.
  142. ///
  143. /// @param clientid client identifier
  144. /// @param subnet_id identifier of the subnet that lease must belong to
  145. ///
  146. /// @return a pointer to the lease (or NULL if a lease is not found)
  147. virtual Lease4Ptr getLease4(const ClientId& clientid,
  148. SubnetID subnet_id) const;
  149. /// @brief Returns existing IPv6 lease for a given IPv6 address.
  150. ///
  151. /// For a given address, we assume that there will be only one lease.
  152. /// The assumtion here is that there will not be site or link-local
  153. /// addresses used, so there is no way of having address duplication.
  154. ///
  155. /// @param addr address of the searched lease
  156. ///
  157. /// @return smart pointer to the lease (or NULL if a lease is not found)
  158. ///
  159. /// @throw isc::BadValue record retrieved from database had an invalid
  160. /// lease type field.
  161. /// @throw isc::dhcp::DbOperationError An operation on the open database has
  162. /// failed.
  163. virtual Lease6Ptr getLease6(const isc::asiolink::IOAddress& addr) const;
  164. /// @brief Returns existing IPv6 leases for a given DUID+IA combination
  165. ///
  166. /// Although in the usual case there will be only one lease, for mobile
  167. /// clients or clients with multiple static/fixed/reserved leases there
  168. /// can be more than one. Thus return type is a container, not a single
  169. /// pointer.
  170. ///
  171. /// @param duid client DUID
  172. /// @param iaid IA identifier
  173. ///
  174. /// @return smart pointer to the lease (or NULL if a lease is not found)
  175. virtual Lease6Collection getLease6(const DUID& duid,
  176. uint32_t iaid) const;
  177. /// @brief Returns existing IPv6 lease for a given DUID+IA combination
  178. ///
  179. /// @param duid client DUID
  180. /// @param iaid IA identifier
  181. /// @param subnet_id subnet id of the subnet the lease belongs to
  182. ///
  183. /// @return smart pointer to the lease (or NULL if a lease is not found)
  184. virtual Lease6Ptr getLease6(const DUID& duid, uint32_t iaid,
  185. SubnetID subnet_id) const;
  186. /// @brief Updates IPv4 lease.
  187. ///
  188. /// @param lease4 The lease to be updated.
  189. ///
  190. /// If no such lease is present, an exception will be thrown.
  191. virtual void updateLease4(const Lease4Ptr& lease4);
  192. /// @brief Updates IPv6 lease.
  193. ///
  194. /// @param lease6 The lease to be updated.
  195. ///
  196. /// @throw isc::dhcp::NoSuchLease Attempt to update a lease that did not
  197. /// exist.
  198. /// @throw isc::dhcp::DbOperationError An operation on the open database has
  199. /// failed.
  200. virtual void updateLease6(const Lease6Ptr& lease6);
  201. /// @brief Deletes an IPv4 lease.
  202. ///
  203. /// @todo Merge with deleteLease6: it is possible to determine whether
  204. /// an address is V4 or V6 from the IOAddress argument, so there
  205. /// is no need for separate V4 or V6 methods.
  206. ///
  207. /// @param addr IPv4 address of the lease to be deleted.
  208. ///
  209. /// @return true if deletion was successful, false if no such lease exists
  210. virtual bool deleteLease4(const isc::asiolink::IOAddress& addr);
  211. /// @brief Deletes an IPv6 lease.
  212. ///
  213. /// @todo Merge with deleteLease4: it is possible to determine whether
  214. /// an address is V4 or V6 from the IOAddress argument, so there
  215. /// is no need for separate V4 or V6 methods.
  216. ///
  217. /// @param addr IPv6 address of the lease to be deleted.
  218. ///
  219. /// @return true if deletion was successful, false if no such lease exists
  220. ///
  221. /// @throw isc::dhcp::DbOperationError An operation on the open database has
  222. /// failed.
  223. virtual bool deleteLease6(const isc::asiolink::IOAddress& addr);
  224. /// @brief Return backend type
  225. ///
  226. /// Returns the type of the backend (e.g. "mysql", "memfile" etc.)
  227. ///
  228. /// @return Type of the backend.
  229. virtual std::string getType() const {
  230. return (std::string("mysql"));
  231. }
  232. /// @brief Returns backend name.
  233. ///
  234. /// Each backend have specific name, e.g. "mysql" or "sqlite".
  235. ///
  236. /// @return Name of the backend.
  237. virtual std::string getName() const;
  238. /// @brief Returns description of the backend.
  239. ///
  240. /// This description may be multiline text that describes the backend.
  241. ///
  242. /// @return Description of the backend.
  243. virtual std::string getDescription() const;
  244. /// @brief Returns backend version.
  245. ///
  246. /// @return Version number as a pair of unsigned integers. "first" is the
  247. /// major version number, "second" the minor number.
  248. ///
  249. /// @throw isc::dhcp::DbOperationError An operation on the open database has
  250. /// failed.
  251. virtual std::pair<uint32_t, uint32_t> getVersion() const;
  252. /// @brief Commit Transactions
  253. ///
  254. /// Commits all pending database operations. On databases that don't
  255. /// support transactions, this is a no-op.
  256. ///
  257. /// @throw DbOperationError Iif the commit failed.
  258. virtual void commit();
  259. /// @brief Rollback Transactions
  260. ///
  261. /// Rolls back all pending database operations. On databases that don't
  262. /// support transactions, this is a no-op.
  263. ///
  264. /// @throw DbOperationError If the rollback failed.
  265. virtual void rollback();
  266. ///@{
  267. /// The following methods are used to convert between times and time
  268. /// intervals stored in the Lease object, and the times stored in the
  269. /// database. The reason for the difference is because in the DHCP server,
  270. /// the cltt (Client Time Since Last Transmission) is the natural data; in
  271. /// the lease file - which may be read by the user - it is the expiry time
  272. /// of the lease.
  273. /// @brief Convert Lease Time to Database Times
  274. ///
  275. /// Within the DHCP servers, times are stored as client last transmit time
  276. /// and valid lifetime. In the database, the information is stored as
  277. /// valid lifetime and "expire" (time of expiry of the lease). They are
  278. /// related by the equation:
  279. ///
  280. /// - expire = client last transmit time + valid lifetime
  281. ///
  282. /// This method converts from the times in the lease object into times
  283. /// able to be added to the database.
  284. ///
  285. /// @param cltt Client last transmit time
  286. /// @param valid_lifetime Valid lifetime
  287. /// @param expire Reference to MYSQL_TIME object where the expiry time of
  288. /// the lease will be put.
  289. static
  290. void convertToDatabaseTime(time_t cltt, uint32_t valid_lifetime,
  291. MYSQL_TIME& expire);
  292. /// @brief Convert Database Time to Lease Times
  293. ///
  294. /// Within the database, time is stored as "expire" (time of expiry of the
  295. /// lease) and valid lifetime. In the DHCP server, the information is
  296. /// stored client last transmit time and valid lifetime. These are related
  297. /// by the equation:
  298. ///
  299. /// - client last transmit time = expire - valid_lifetime
  300. ///
  301. /// This method converts from the times in the database into times
  302. /// able to be inserted into the lease object.
  303. ///
  304. /// @param expire Reference to MYSQL_TIME object from where the expiry
  305. /// time of the lease is taken.
  306. /// @param valid_lifetime lifetime of the lease.
  307. /// @param cltt Reference to location where client last transmit time
  308. /// is put.
  309. static
  310. void convertFromDatabaseTime(const MYSQL_TIME& expire,
  311. uint32_t valid_lifetime, time_t& cltt);
  312. ///@}
  313. /// @brief Statement Tags
  314. ///
  315. /// The contents of the enum are indexes into the list of SQL statements
  316. enum StatementIndex {
  317. DELETE_LEASE4, // Delete from lease4 by address
  318. DELETE_LEASE6, // Delete from lease6 by address
  319. GET_LEASE4_ADDR, // Get lease4 by address
  320. GET_LEASE6_ADDR, // Get lease6 by address
  321. GET_LEASE6_DUID_IAID, // Get lease6 by DUID and IAID
  322. GET_LEASE6_DUID_IAID_SUBID, // Get lease6 by DUID, IAID and Subnet ID
  323. GET_VERSION, // Obtain version number
  324. INSERT_LEASE4, // Add entry to lease4 table
  325. INSERT_LEASE6, // Add entry to lease6 table
  326. UPDATE_LEASE6, // Update a Lease6 entry
  327. NUM_STATEMENTS // Number of statements
  328. };
  329. private:
  330. /// @brief Prepare Single Statement
  331. ///
  332. /// Creates a prepared statement from the text given and adds it to the
  333. /// statements_ vector at the given index.
  334. ///
  335. /// @param index Index into the statements_ vector into which the text
  336. /// should be placed. The vector must be big enough for the index
  337. /// to be valid, else an exception will be thrown.
  338. /// @param text Text of the SQL statement to be prepared.
  339. ///
  340. /// @throw isc::dhcp::DbOperationError An operation on the open database has
  341. /// failed.
  342. /// @throw isc::InvalidParameter 'index' is not valid for the vector.
  343. void prepareStatement(StatementIndex index, const char* text);
  344. /// @brief Prepare statements
  345. ///
  346. /// Creates the prepared statements for all of the SQL statements used
  347. /// by the MySQL backend.
  348. ///
  349. /// @throw isc::dhcp::DbOperationError An operation on the open database has
  350. /// failed.
  351. /// @throw isc::InvalidParameter 'index' is not valid for the vector. This
  352. /// represents an internal error within the code.
  353. void prepareStatements();
  354. /// @brief Open Database
  355. ///
  356. /// Opens the database using the information supplied in the parameters
  357. /// passed to the constructor.
  358. ///
  359. /// @throw NoDatabaseName Mandatory database name not given
  360. /// @throw DbOpenError Error opening the database
  361. void openDatabase();
  362. /// @brief Add Lease Common Code
  363. ///
  364. /// This method performs the common actions for both flavours of the
  365. /// addLease method.
  366. ///
  367. /// @param stindex Index of statemnent being executed
  368. /// @param bind MYSQL_BIND array that has been created for the type
  369. /// of lease in question.
  370. ///
  371. /// @return true if the lease was added, false if it was not added because
  372. /// a lease with that address already exists in the database.
  373. ///
  374. /// @throw isc::dhcp::DbOperationError An operation on the open database has
  375. /// failed.
  376. bool addLease(StatementIndex stindex, std::vector<MYSQL_BIND>& bind);
  377. /// @brief Get Lease Common Code
  378. ///
  379. /// This method performs the common actions for the getLease methods.
  380. ///
  381. /// @param stindex Index of statement being executed
  382. /// @param inbind MYSQL_BIND array for input parameters
  383. /// @param exchange Exchange object to use
  384. /// @param lease Lease object returned
  385. template <typename Exchange, typename LeasePtr>
  386. void getLease(StatementIndex stindex, MYSQL_BIND* inbind,
  387. Exchange& exchange, LeasePtr& result) const;
  388. /// @brief Binds Parameters and Executes
  389. ///
  390. /// This method abstracts a lot of common processing from the getXxxx()
  391. /// methods. It binds the parameters passed to it to the appropriate
  392. /// prepared statement, and binds the variables in the exchange6 object to
  393. /// the output parameters of the statement. It then executes the prepared
  394. /// statement.
  395. ///
  396. /// The data can be retrieved using mysql_stmt_fetch and the getLeaseData()
  397. /// method on the appropriate exchange object.
  398. ///
  399. /// @param stindex Index of prepared statement to be executed
  400. /// @param exchange Exchange object to use
  401. /// @param inbind Array of MYSQL_BIND objects representing the parameters.
  402. /// (Note that the number is determined by the number of parameters
  403. /// in the statement.)
  404. ///
  405. /// @throw isc::dhcp::DbOperationError An operation on the open database has
  406. /// failed.
  407. template <typename Exchange>
  408. void bindAndExecute(StatementIndex stindex, Exchange& exchange,
  409. MYSQL_BIND* inbind) const;
  410. /// @brief Check Error and Throw Exception
  411. ///
  412. /// Virtually all MySQL functions return a status which, if non-zero,
  413. /// indicates an error. This inline function conceals a lot of error
  414. /// checking/exception-throwing code.
  415. ///
  416. /// @param status Status code: non-zero implies an error
  417. /// @param index Index of statement that caused the error
  418. /// @param what High-level description of the error
  419. ///
  420. /// @throw isc::dhcp::DbOperationError An operation on the open database has
  421. /// failed.
  422. inline void checkError(int status, StatementIndex index,
  423. const char* what) const {
  424. if (status != 0) {
  425. isc_throw(DbOperationError, what << " for <" <<
  426. text_statements_[index] << ">, reason: " <<
  427. mysql_error(mysql_) << " (error code " <<
  428. mysql_errno(mysql_) << ")");
  429. }
  430. }
  431. // Members
  432. /// Used for transfer of data to/from the database. This is a pointed-to
  433. /// object as its contents may change in "const" calls, while the rest
  434. /// of this object does not. (At alternative would be to declare it as
  435. /// "mutable".)
  436. MYSQL* mysql_; ///< MySQL context object
  437. std::vector<std::string> text_statements_; ///< Raw text of statements
  438. std::vector<MYSQL_STMT*> statements_; ///< Prepared statements
  439. boost::scoped_ptr<MySqlLease4Exchange> exchange4_; ///< Exchange object
  440. boost::scoped_ptr<MySqlLease6Exchange> exchange6_; ///< Exchange object
  441. };
  442. }; // end of isc::dhcp namespace
  443. }; // end of isc namespace
  444. #endif // MYSQL_LEASE_MGR_H