mysql_lease_mgr.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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 <time.h>
  17. #include <mysql.h>
  18. #include <dhcp/lease_mgr.h>
  19. namespace isc {
  20. namespace dhcp {
  21. // Define the current database schema values
  22. const uint32_t CURRENT_VERSION_VERSION = 0;
  23. const uint32_t CURRENT_VERSION_MINOR = 1;
  24. /// @brief MySQL Lease Manager
  25. ///
  26. /// This is a concrete API for the backend for the MySQL database.
  27. class MySqlLeaseMgr : public LeaseMgr {
  28. public:
  29. /// @brief Constructor
  30. ///
  31. /// Uses the following keywords in the parameters passed to it to
  32. /// connect to the database:
  33. /// - name - Name of the database to which to connect (mandatory)
  34. /// - host - Host to which to connect (optional, defaults to "localhost")
  35. /// - user - Username under which to connect (optional)
  36. /// - password - Password for "user" on the database (optional)
  37. ///
  38. /// If the database is successfully opened, the version number in the
  39. /// schema_version table will be checked against hard-coded value in
  40. /// the implementation file.
  41. ///
  42. /// Finally, all the SQL commands are pre-compiled.
  43. ///
  44. /// @param parameters A data structure relating keywords and values
  45. /// concerned with the database.
  46. ///
  47. /// @exception NoDatabaseName Mandatory database name not given
  48. /// @exception DbOpenError Error opening the database
  49. /// @exception DbOperationError An operation on the open database has
  50. /// failed.
  51. MySqlLeaseMgr(const ParameterMap& parameters);
  52. /// @brief Destructor (closes database)
  53. virtual ~MySqlLeaseMgr();
  54. /// @brief Adds an IPv4 lease.
  55. ///
  56. /// @param lease lease to be added
  57. ///
  58. /// @result true if the lease was added, false if not (because a lease
  59. /// with the same address was already there).
  60. ///
  61. /// @exception DbOperationError Database function failed
  62. virtual bool addLease(const Lease4Ptr& lease);
  63. /// @brief Adds an IPv6 lease.
  64. ///
  65. /// @param lease lease to be added
  66. ///
  67. /// @result true if the lease was added, false if not (because a lease
  68. /// with the same address was already there).
  69. ///
  70. /// @exception DbOperationError Database function failed
  71. virtual bool addLease(const Lease6Ptr& lease);
  72. /// @brief Return IPv4 lease for specified IPv4 address and subnet_id
  73. ///
  74. /// This method is used to get a lease for specific subnet_id. There can be
  75. /// at most one lease for any given subnet, so this method returns a single
  76. /// pointer.
  77. ///
  78. /// @param addr address of the sought lease
  79. /// @param subnet_id ID of the subnet the lease must belong to
  80. ///
  81. /// @return smart pointer to the lease (or NULL if a lease is not found)
  82. virtual Lease4Ptr getLease4(const isc::asiolink::IOAddress& addr,
  83. SubnetID subnet_id) const;
  84. /// @brief Returns an IPv4 lease for specified IPv4 address
  85. ///
  86. /// This method return a lease that is associated with a given address.
  87. /// For other query types (by hardware addr, by DUID) there can be
  88. /// several leases in different subnets (e.g. for mobile clients that
  89. /// got address in different subnets). However, for a single address
  90. /// there can be only one lease, so this method returns a pointer to
  91. /// a single lease, not a container of leases.
  92. ///
  93. /// @param addr address of the searched lease
  94. /// @param subnet_id ID of the subnet the lease must belong to
  95. ///
  96. /// @return smart pointer to the lease (or NULL if a lease is not found)
  97. virtual Lease4Ptr getLease4(const isc::asiolink::IOAddress& addr) const;
  98. /// @brief Returns existing IPv4 leases for specified hardware address.
  99. ///
  100. /// Although in the usual case there will be only one lease, for mobile
  101. /// clients or clients with multiple static/fixed/reserved leases there
  102. /// can be more than one. Thus return type is a container, not a single
  103. /// pointer.
  104. ///
  105. /// @param hwaddr hardware address of the client
  106. ///
  107. /// @return lease collection
  108. virtual Lease4Collection getLease4(const HWAddr& hwaddr) const;
  109. /// @brief Returns existing IPv4 leases for specified hardware address
  110. /// and a subnet
  111. ///
  112. /// There can be at most one lease for a given HW address in a single
  113. /// pool, so this method with either return a single lease or NULL.
  114. ///
  115. /// @param hwaddr hardware address of the client
  116. /// @param subnet_id identifier of the subnet that lease must belong to
  117. ///
  118. /// @return a pointer to the lease (or NULL if a lease is not found)
  119. virtual Lease4Ptr getLease4(const HWAddr& hwaddr,
  120. SubnetID subnet_id) const;
  121. /// @brief Returns existing IPv4 lease for specified client-id
  122. ///
  123. /// Although in the usual case there will be only one lease, for mobile
  124. /// clients or clients with multiple static/fixed/reserved leases there
  125. /// can be more than one. Thus return type is a container, not a single
  126. /// pointer.
  127. ///
  128. /// @param clientid client identifier
  129. ///
  130. /// @return lease collection
  131. virtual Lease4Collection getLease4(const ClientId& clientid) const;
  132. /// @brief Returns existing IPv4 lease for specified client-id
  133. ///
  134. /// There can be at most one lease for a given HW address in a single
  135. /// pool, so this method with either return a single lease or NULL.
  136. ///
  137. /// @param clientid client identifier
  138. /// @param subnet_id identifier of the subnet that lease must belong to
  139. ///
  140. /// @return a pointer to the lease (or NULL if a lease is not found)
  141. virtual Lease4Ptr getLease4(const ClientId& clientid,
  142. SubnetID subnet_id) const;
  143. /// @brief Returns existing IPv6 lease for a given IPv6 address.
  144. ///
  145. /// For a given address, we assume that there will be only one lease.
  146. /// The assumtion here is that there will not be site or link-local
  147. /// addresses used, so there is no way of having address duplication.
  148. ///
  149. /// @param addr address of the searched lease
  150. ///
  151. /// @return smart pointer to the lease (or NULL if a lease is not found)
  152. ///
  153. /// @exception BadValue record retrieved from database had an invalid
  154. /// lease type field.
  155. /// @exception DbOperationError MySQL operation failed, exception will give
  156. /// text indicating the reason.
  157. virtual Lease6Ptr getLease6(const isc::asiolink::IOAddress& addr) const;
  158. /// @brief Returns existing IPv6 leases for a given DUID+IA combination
  159. ///
  160. /// Although in the usual case there will be only one lease, for mobile
  161. /// clients or clients with multiple static/fixed/reserved leases there
  162. /// can be more than one. Thus return type is a container, not a single
  163. /// pointer.
  164. ///
  165. /// @param duid client DUID
  166. /// @param iaid IA identifier
  167. ///
  168. /// @return smart pointer to the lease (or NULL if a lease is not found)
  169. virtual Lease6Collection getLease6(const DUID& duid,
  170. uint32_t iaid) const;
  171. /// @brief Returns existing IPv6 lease for a given DUID+IA combination
  172. ///
  173. /// @param duid client DUID
  174. /// @param iaid IA identifier
  175. /// @param subnet_id subnet id of the subnet the lease belongs to
  176. ///
  177. /// @return smart pointer to the lease (or NULL if a lease is not found)
  178. virtual Lease6Ptr getLease6(const DUID& duid, uint32_t iaid,
  179. SubnetID subnet_id) const;
  180. /// @brief Updates IPv4 lease.
  181. ///
  182. /// @param lease4 The lease to be updated.
  183. ///
  184. /// If no such lease is present, an exception will be thrown.
  185. virtual void updateLease4(const Lease4Ptr& lease4);
  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 updateLease6(const Lease6Ptr& lease6);
  192. /// @brief Deletes a lease.
  193. ///
  194. /// @param addr IPv4 address of the lease to be deleted.
  195. ///
  196. /// @return true if deletion was successful, false if no such lease exists
  197. virtual bool deleteLease4(const isc::asiolink::IOAddress& addr);
  198. /// @brief Deletes a lease.
  199. ///
  200. /// @param addr IPv4 address of the lease to be deleted.
  201. ///
  202. /// @return true if deletion was successful, false if no such lease exists
  203. ///
  204. /// @exception DbOperationError MySQL operation failed, exception will give
  205. /// text indicating the reason.
  206. virtual bool deleteLease6(const isc::asiolink::IOAddress& addr);
  207. /// @brief Returns backend name.
  208. ///
  209. /// Each backend have specific name, e.g. "mysql" or "sqlite".
  210. virtual std::string getName() const;
  211. /// @brief Returns description of the backend.
  212. ///
  213. /// This description may be multiline text that describes the backend.
  214. virtual std::string getDescription() const;
  215. /// @brief Returns backend version.
  216. ///
  217. /// @return Version number as a pair of unsigned integers. "first" is the
  218. /// major version number, "second" the minor number.
  219. ///
  220. /// @todo: We will need to implement 3 version functions eventually:
  221. /// A. abstract API version
  222. /// B. backend version
  223. /// C. database version (stored in the database scheme)
  224. ///
  225. /// and then check that:
  226. /// B>=A and B=C (it is ok to have newer backend, as it should be backward
  227. /// compatible)
  228. /// Also if B>C, some database upgrade procedure may be triggered
  229. ///
  230. /// @exception DbOperationError MySQL operation failed, exception will give
  231. /// text indicating the reason.
  232. virtual std::pair<uint32_t, uint32_t> getVersion() const;
  233. /// @brief Commit Transactions
  234. ///
  235. /// Commits all pending database operations. On databases that don't
  236. /// support transactions, this is a no-op.
  237. ///
  238. /// @exception DbOperationError if the commit failed.
  239. virtual void commit();
  240. /// @brief Rollback Transactions
  241. ///
  242. /// Rolls back all pending database operations. On databases that don't
  243. /// support transactions, this is a no-op.
  244. ///
  245. /// @exception DbOperationError if the rollback failed.
  246. virtual void rollback();
  247. ///@{
  248. /// The following methods are used to convert between times and time
  249. /// intervals stored in the Lease object, and the times stored in the
  250. /// database. The reason for the difference is because in the DHCP server,
  251. /// the cltt (Client Time Since Last Transmission) is the natural data; in
  252. /// the lease file - which may be read by the user - it is the expiry time
  253. /// of the lease.
  254. /// @brief Convert Lease Time to Database Times
  255. ///
  256. /// Within the DHCP servers, times are stored as client last transmit time
  257. /// and valid lifetime. In the database, the information is stored as
  258. /// valid lifetime and "expire" (time of expiry of the lease). They are
  259. /// related by the equation:
  260. ///
  261. /// - expire = client last transmit time + valid lifetime
  262. ///
  263. /// This method converts from the times in the lease object into times
  264. /// able to be added to the database.
  265. ///
  266. /// @param cltt Client last transmit time
  267. /// @param valid_lifetime Valid lifetime
  268. /// @param expire Reference to MYSQL_TIME object where the expiry time of
  269. /// the lease will be put.
  270. static
  271. void convertToDatabaseTime(time_t cltt, uint32_t valid_lifetime,
  272. MYSQL_TIME& expire);
  273. /// @brief Convert Database Time to Lease Times
  274. ///
  275. /// Within the database, time is stored as "expire" (time of expiry of the
  276. /// lease) and valid lifetime. In the DHCP server, the information is
  277. /// stored client last transmit time and valid lifetime. These are related
  278. /// by the equation:
  279. ///
  280. /// - client last transmit time = expire - valid_lifetime
  281. ///
  282. /// This method converts from the times in the database into times
  283. /// able to be inserted into the lease object.
  284. ///
  285. /// @param expire Reference to MYSQL_TIME object from where the expiry
  286. /// time of the lease is taken.
  287. /// @param lease_time lifetime of the lease.
  288. /// @param cltt Reference to location where client last transmit time
  289. /// is put.
  290. static
  291. void convertFromDatabaseTime(const MYSQL_TIME& expire,
  292. uint32_t valid_lifetime, time_t& cltt);
  293. ///@}
  294. private:
  295. /// @brief Statement Tags
  296. ///
  297. /// The contents of the enum are indexes into the list of SQL statements
  298. enum StatementIndex {
  299. DELETE_LEASE6, // Delete from lease6 by address
  300. GET_LEASE6, // Get lease 6 by address
  301. GET_VERSION, // Obtain version number
  302. INSERT_LEASE6, // Add entry to lease6 table
  303. NUM_STATEMENTS // Number of statements
  304. };
  305. /// @brief Prepare Single Statement
  306. ///
  307. /// Creates a prepared statement from the text given and adds it to the
  308. /// statements_ vector at the given index.
  309. ///
  310. /// @param index Index into the statements_ vector into which the text
  311. /// should be placed. The vector must be big enough for the index
  312. /// to be valid, else an exception will be thrown.
  313. /// @param text Text of the SQL statement to be prepared.
  314. ///
  315. /// @exception DbOperationError MySQL operation failed, exception will give
  316. /// text indicating the reason.
  317. /// @exception InvalidParameter 'index' is not valid for the vector.
  318. void prepareStatement(StatementIndex index, const char* text);
  319. /// @brief Prepare statements
  320. ///
  321. /// Creates the prepared statements for all of the SQL statements used
  322. /// by the MySQL backend.
  323. ///
  324. /// @exception DbOperationError MySQL operation failed, exception will give
  325. /// text indicating the reason.
  326. /// @exception InvalidParameter 'index' is not valid for the vector. This
  327. /// represents an internal error within the code.
  328. void prepareStatements();
  329. /// @brief Open Database
  330. ///
  331. /// Opens the database using the information supplied in the parameters
  332. /// passed to the constructor.
  333. ///
  334. /// @exception NoDatabaseName Mandatory database name not given
  335. /// @exception DbOpenError Error opening the database
  336. void openDatabase();
  337. /// @brief Check Error and Throw Exception
  338. ///
  339. /// Virtually all MySQL functions return a status which, if non-zero,
  340. /// indicates an error. This inline function conceals a lot of error
  341. /// checking/exception-throwing code.
  342. ///
  343. /// @param status Status code: non-zero implies an error
  344. /// @param index Index of statement that caused the error
  345. /// @param what High-level description of the error
  346. ///
  347. /// @exception DbOperationError Error doing a database operation
  348. inline void checkError(int status, StatementIndex index,
  349. const char* what) const {
  350. if (status != 0) {
  351. isc_throw(DbOperationError, what << " for <" <<
  352. text_statements_[index] << ">, reason: " <<
  353. mysql_error(mysql_) << " (error code " <<
  354. mysql_errno(mysql_) << ")");
  355. }
  356. }
  357. // Members
  358. MYSQL* mysql_; ///< MySQL context object
  359. std::vector<std::string> text_statements_; ///< Raw text of statements
  360. std::vector<MYSQL_STMT*> statements_; ///< Prepared statements
  361. };
  362. }; // end of isc::dhcp namespace
  363. }; // end of isc namespace
  364. #endif // MYSQL_LEASE_MGR_H