pgsql_lease_mgr.cc 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582
  1. // Copyright (C) 2014-2016 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/pgsql_lease_mgr.h>
  12. #include <boost/static_assert.hpp>
  13. #include <iostream>
  14. #include <iomanip>
  15. #include <limits>
  16. #include <sstream>
  17. #include <string>
  18. #include <time.h>
  19. using namespace isc;
  20. using namespace isc::dhcp;
  21. using namespace std;
  22. namespace {
  23. /// @brief Catalog of all the SQL statements currently supported. Note
  24. /// that the order columns appear in statement body must match the order they
  25. /// that the occur in the table. This does not apply to the where clause.
  26. PgSqlTaggedStatement tagged_statements[] = {
  27. // DELETE_LEASE4
  28. { 1, { OID_INT8 },
  29. "delete_lease4",
  30. "DELETE FROM lease4 WHERE address = $1"},
  31. // DELETE_LEASE4_STATE_EXPIRED
  32. { 2, { OID_INT8, OID_TIMESTAMP },
  33. "delete_lease4_state_expired",
  34. "DELETE FROM lease4 "
  35. "WHERE state = $1 AND expire < $2"},
  36. // DELETE_LEASE6
  37. { 1, { OID_VARCHAR },
  38. "delete_lease6",
  39. "DELETE FROM lease6 WHERE address = $1"},
  40. // DELETE_LEASE6_STATE_EXPIRED
  41. { 2, { OID_INT8, OID_TIMESTAMP },
  42. "delete_lease6_state_expired",
  43. "DELETE FROM lease6 "
  44. "WHERE state = $1 AND expire < $2"},
  45. // GET_LEASE4_ADDR
  46. { 1, { OID_INT8 },
  47. "get_lease4_addr",
  48. "SELECT address, hwaddr, client_id, "
  49. "valid_lifetime, extract(epoch from expire)::bigint, subnet_id, "
  50. "fqdn_fwd, fqdn_rev, hostname, state "
  51. "FROM lease4 "
  52. "WHERE address = $1"},
  53. // GET_LEASE4_CLIENTID
  54. { 1, { OID_BYTEA },
  55. "get_lease4_clientid",
  56. "SELECT address, hwaddr, client_id, "
  57. "valid_lifetime, extract(epoch from expire)::bigint, subnet_id, "
  58. "fqdn_fwd, fqdn_rev, hostname, state "
  59. "FROM lease4 "
  60. "WHERE client_id = $1"},
  61. // GET_LEASE4_CLIENTID_SUBID
  62. { 2, { OID_BYTEA, OID_INT8 },
  63. "get_lease4_clientid_subid",
  64. "SELECT address, hwaddr, client_id, "
  65. "valid_lifetime, extract(epoch from expire)::bigint, subnet_id, "
  66. "fqdn_fwd, fqdn_rev, hostname, state "
  67. "FROM lease4 "
  68. "WHERE client_id = $1 AND subnet_id = $2"},
  69. // GET_LEASE4_HWADDR
  70. { 1, { OID_BYTEA },
  71. "get_lease4_hwaddr",
  72. "SELECT address, hwaddr, client_id, "
  73. "valid_lifetime, extract(epoch from expire)::bigint, subnet_id, "
  74. "fqdn_fwd, fqdn_rev, hostname, state "
  75. "FROM lease4 "
  76. "WHERE hwaddr = $1"},
  77. // GET_LEASE4_HWADDR_SUBID
  78. { 2, { OID_BYTEA, OID_INT8 },
  79. "get_lease4_hwaddr_subid",
  80. "SELECT address, hwaddr, client_id, "
  81. "valid_lifetime, extract(epoch from expire)::bigint, subnet_id, "
  82. "fqdn_fwd, fqdn_rev, hostname, state "
  83. "FROM lease4 "
  84. "WHERE hwaddr = $1 AND subnet_id = $2"},
  85. // GET_LEASE4_EXPIRE
  86. { 3, { OID_INT8, OID_TIMESTAMP, OID_INT8 },
  87. "get_lease4_expire",
  88. "SELECT address, hwaddr, client_id, "
  89. "valid_lifetime, extract(epoch from expire)::bigint, subnet_id, "
  90. "fqdn_fwd, fqdn_rev, hostname, state "
  91. "FROM lease4 "
  92. "WHERE state != $1 AND expire < $2 "
  93. "ORDER BY expire "
  94. "LIMIT $3"},
  95. // GET_LEASE6_ADDR
  96. { 2, { OID_VARCHAR, OID_INT2 },
  97. "get_lease6_addr",
  98. "SELECT address, duid, valid_lifetime, "
  99. "extract(epoch from expire)::bigint, subnet_id, pref_lifetime, "
  100. "lease_type, iaid, prefix_len, fqdn_fwd, fqdn_rev, hostname, "
  101. "state "
  102. "FROM lease6 "
  103. "WHERE address = $1 AND lease_type = $2"},
  104. // GET_LEASE6_DUID_IAID
  105. { 3, { OID_BYTEA, OID_INT8, OID_INT2 },
  106. "get_lease6_duid_iaid",
  107. "SELECT address, duid, valid_lifetime, "
  108. "extract(epoch from expire)::bigint, subnet_id, pref_lifetime, "
  109. "lease_type, iaid, prefix_len, fqdn_fwd, fqdn_rev, hostname, "
  110. "state "
  111. "FROM lease6 "
  112. "WHERE duid = $1 AND iaid = $2 AND lease_type = $3"},
  113. // GET_LEASE6_DUID_IAID_SUBID
  114. { 4, { OID_INT2, OID_BYTEA, OID_INT8, OID_INT8 },
  115. "get_lease6_duid_iaid_subid",
  116. "SELECT address, duid, valid_lifetime, "
  117. "extract(epoch from expire)::bigint, subnet_id, pref_lifetime, "
  118. "lease_type, iaid, prefix_len, fqdn_fwd, fqdn_rev, hostname, "
  119. "state "
  120. "FROM lease6 "
  121. "WHERE lease_type = $1 "
  122. "AND duid = $2 AND iaid = $3 AND subnet_id = $4"},
  123. // GET_LEASE6_EXPIRE
  124. { 3, { OID_INT8, OID_TIMESTAMP, OID_INT8 },
  125. "get_lease6_expire",
  126. "SELECT address, duid, valid_lifetime, "
  127. "extract(epoch from expire)::bigint, subnet_id, pref_lifetime, "
  128. "lease_type, iaid, prefix_len, "
  129. "fqdn_fwd, fqdn_rev, hostname, state "
  130. "state "
  131. "FROM lease6 "
  132. "WHERE state != $1 AND expire < $2 "
  133. "ORDER BY expire "
  134. "LIMIT $3"},
  135. // GET_VERSION
  136. { 0, { OID_NONE },
  137. "get_version",
  138. "SELECT version, minor FROM schema_version"},
  139. // INSERT_LEASE4
  140. { 10, { OID_INT8, OID_BYTEA, OID_BYTEA, OID_INT8, OID_TIMESTAMP, OID_INT8,
  141. OID_BOOL, OID_BOOL, OID_VARCHAR, OID_INT8, OID_INT8 },
  142. "insert_lease4",
  143. "INSERT INTO lease4(address, hwaddr, client_id, "
  144. "valid_lifetime, expire, subnet_id, fqdn_fwd, fqdn_rev, hostname, "
  145. "state) "
  146. "VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)"},
  147. // INSERT_LEASE6
  148. { 13, { OID_VARCHAR, OID_BYTEA, OID_INT8, OID_TIMESTAMP, OID_INT8,
  149. OID_INT8, OID_INT2, OID_INT8, OID_INT2, OID_BOOL, OID_BOOL,
  150. OID_VARCHAR, OID_INT8 },
  151. "insert_lease6",
  152. "INSERT INTO lease6(address, duid, valid_lifetime, "
  153. "expire, subnet_id, pref_lifetime, "
  154. "lease_type, iaid, prefix_len, fqdn_fwd, fqdn_rev, hostname, state) "
  155. "VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)"},
  156. // UPDATE_LEASE4
  157. { 11, { OID_INT8, OID_BYTEA, OID_BYTEA, OID_INT8, OID_TIMESTAMP, OID_INT8,
  158. OID_BOOL, OID_BOOL, OID_VARCHAR, OID_INT8, OID_INT8 },
  159. "update_lease4",
  160. "UPDATE lease4 SET address = $1, hwaddr = $2, "
  161. "client_id = $3, valid_lifetime = $4, expire = $5, "
  162. "subnet_id = $6, fqdn_fwd = $7, fqdn_rev = $8, hostname = $9, "
  163. "state = $10"
  164. "WHERE address = $11"},
  165. // UPDATE_LEASE6
  166. { 14, { OID_VARCHAR, OID_BYTEA, OID_INT8, OID_TIMESTAMP, OID_INT8, OID_INT8,
  167. OID_INT2, OID_INT8, OID_INT2, OID_BOOL, OID_BOOL, OID_VARCHAR,
  168. OID_INT8, OID_VARCHAR },
  169. "update_lease6",
  170. "UPDATE lease6 SET address = $1, duid = $2, "
  171. "valid_lifetime = $3, expire = $4, subnet_id = $5, "
  172. "pref_lifetime = $6, lease_type = $7, iaid = $8, "
  173. "prefix_len = $9, fqdn_fwd = $10, fqdn_rev = $11, hostname = $12, "
  174. "state = $13 "
  175. "WHERE address = $14"},
  176. // End of list sentinel
  177. { 0, { 0 }, NULL, NULL}
  178. };
  179. };
  180. namespace isc {
  181. namespace dhcp {
  182. const int PsqlBindArray::TEXT_FMT = 0;
  183. const int PsqlBindArray::BINARY_FMT = 1;
  184. const char* PsqlBindArray::TRUE_STR = "TRUE";
  185. const char* PsqlBindArray::FALSE_STR = "FALSE";
  186. void PsqlBindArray::add(const char* value) {
  187. values_.push_back(value);
  188. lengths_.push_back(strlen(value));
  189. formats_.push_back(TEXT_FMT);
  190. }
  191. void PsqlBindArray::add(const std::string& value) {
  192. values_.push_back(value.c_str());
  193. lengths_.push_back(value.size());
  194. formats_.push_back(TEXT_FMT);
  195. }
  196. void PsqlBindArray::add(const std::vector<uint8_t>& data) {
  197. values_.push_back(reinterpret_cast<const char*>(&(data[0])));
  198. lengths_.push_back(data.size());
  199. formats_.push_back(BINARY_FMT);
  200. }
  201. void PsqlBindArray::add(const bool& value) {
  202. add(value ? TRUE_STR : FALSE_STR);
  203. }
  204. std::string PsqlBindArray::toText() {
  205. std::ostringstream stream;
  206. for (int i = 0; i < values_.size(); ++i) {
  207. stream << i << " : ";
  208. if (formats_[i] == TEXT_FMT) {
  209. stream << "\"" << values_[i] << "\"" << std::endl;
  210. } else {
  211. const char *data = values_[i];
  212. if (lengths_[i] == 0) {
  213. stream << "empty" << std::endl;
  214. } else {
  215. stream << "0x";
  216. for (int i = 0; i < lengths_[i]; ++i) {
  217. stream << setfill('0') << setw(2) << setbase(16)
  218. << static_cast<unsigned int>(data[i]);
  219. }
  220. stream << std::endl;
  221. }
  222. }
  223. }
  224. return (stream.str());
  225. }
  226. /// @brief Base class for marshalling leases to and from PostgreSQL.
  227. ///
  228. /// Provides the common functionality to set up binding information between
  229. /// lease objects in the program and their database representation in the
  230. /// database.
  231. class PgSqlLeaseExchange {
  232. public:
  233. PgSqlLeaseExchange()
  234. : addr_str_(""), valid_lifetime_(0), valid_lft_str_(""),
  235. expire_(0), expire_str_(""), subnet_id_(0), subnet_id_str_(""),
  236. cltt_(0), fqdn_fwd_(false), fqdn_rev_(false), hostname_(""),
  237. state_str_("") {
  238. }
  239. virtual ~PgSqlLeaseExchange(){}
  240. /// @brief Converts time_t value to a text representation in local time.
  241. ///
  242. /// @param input_time A time_t value representing time.
  243. /// @return std::string containing stringified time.
  244. static std::string
  245. convertToDatabaseTime(const time_t input_time) {
  246. struct tm tinfo;
  247. char buffer[20];
  248. localtime_r(&input_time, &tinfo);
  249. strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", &tinfo);
  250. return (std::string(buffer));
  251. }
  252. /// @brief Converts lease expiration time to a text representation in
  253. /// local time.
  254. ///
  255. /// The expiration time is calculated as a sum of the cltt (client last
  256. /// transmit time) and the valid lifetime.
  257. ///
  258. /// The format of the output string is "%Y-%m-%d %H:%M:%S". Database
  259. /// table columns using this value should be typed as TIMESTAMP WITH
  260. /// TIME ZONE. For such columns PostgreSQL assumes input strings without
  261. /// timezones should be treated as in local time and are converted to UTC
  262. /// when stored. Likewise, these columns are automatically adjusted
  263. /// upon retrieval unless fetched via "extract(epoch from <column>))".
  264. ///
  265. /// @param cltt Client last transmit time
  266. /// @param valid_lifetime Valid lifetime
  267. ///
  268. /// @return std::string containing the stringified time
  269. /// @throw isc::BadValue if the sum of the calculated expiration time is
  270. /// greater than the value of @c DataSource::MAX_DB_TIME.
  271. static std::string
  272. convertToDatabaseTime(const time_t cltt, const uint32_t valid_lifetime) {
  273. // Calculate expiry time. Store it in the 64-bit value so as we can detect
  274. // overflows.
  275. int64_t expire_time_64 = static_cast<int64_t>(cltt) +
  276. static_cast<int64_t>(valid_lifetime);
  277. // It has been observed that the PostgreSQL doesn't deal well with the
  278. // timestamp values beyond the DataSource::MAX_DB_TIME seconds since the
  279. // beginning of the epoch (around year 2038). The value is often
  280. // stored in the database but it is invalid when read back (overflow?).
  281. // Hence, the maximum timestamp value is restricted here.
  282. if (expire_time_64 > DatabaseConnection::MAX_DB_TIME) {
  283. isc_throw(isc::BadValue, "Time value is too large: " << expire_time_64);
  284. }
  285. return (convertToDatabaseTime(static_cast<time_t>(expire_time_64)));
  286. }
  287. /// @brief Converts time stamp from the database to a time_t
  288. ///
  289. /// @param db_time_val timestamp to be converted. This value
  290. /// is expected to be the number of seconds since the epoch
  291. /// expressed as base-10 integer string.
  292. /// @return Converted timestamp as time_t value.
  293. static time_t convertFromDatabaseTime(const std::string& db_time_val) {
  294. // Convert string time value to time_t
  295. try {
  296. return (boost::lexical_cast<time_t>(db_time_val));
  297. } catch (const std::exception& ex) {
  298. isc_throw(BadValue, "Database time value is invalid: "
  299. << db_time_val);
  300. }
  301. }
  302. /// @brief Gets a pointer to the raw column value in a result set row
  303. ///
  304. /// Given a result set, row, and column return a const char* pointer to
  305. /// the data value in the result set. The pointer is valid as long as
  306. /// the result set has not been freed. It may point to text or binary
  307. /// data depending on how query was structured. You should not attempt
  308. /// to free this pointer.
  309. ///
  310. /// @param r the result set containing the query results
  311. /// @param row the row number within the result set
  312. /// @param col the column number within the row
  313. ///
  314. /// @return a const char* pointer to the column's raw data
  315. /// @throw DbOperationError if the value cannot be fetched.
  316. const char* getRawColumnValue(PGresult*& r, const int row,
  317. const size_t col) const {
  318. const char* value = PQgetvalue(r, row, col);
  319. if (!value) {
  320. isc_throw(DbOperationError, "getRawColumnValue no data for :"
  321. << getColumnLabel(col) << " row:" << row);
  322. }
  323. return (value);
  324. }
  325. /// @brief Fetches boolean text ('t' or 'f') as a bool.
  326. ///
  327. /// @param r the result set containing the query results
  328. /// @param row the row number within the result set
  329. /// @param col the column number within the row
  330. /// @param[out] value parameter to receive the converted value
  331. ///
  332. /// @throw DbOperationError if the value cannot be fetched or is
  333. /// invalid.
  334. void getColumnValue(PGresult*& r, const int row, const size_t col,
  335. bool &value) const {
  336. const char* data = getRawColumnValue(r, row, col);
  337. if (!strlen(data) || *data == 'f') {
  338. value = false;
  339. } else if (*data == 't') {
  340. value = true;
  341. } else {
  342. isc_throw(DbOperationError, "Invalid boolean data: " << data
  343. << " for: " << getColumnLabel(col) << " row:" << row
  344. << " : must be 't' or 'f'");
  345. }
  346. }
  347. /// @brief Fetches an integer text column as a uint32_t.
  348. ///
  349. /// @param r the result set containing the query results
  350. /// @param row the row number within the result set
  351. /// @param col the column number within the row
  352. /// @param[out] value parameter to receive the converted value
  353. ///
  354. /// @throw DbOperationError if the value cannot be fetched or is
  355. /// invalid.
  356. void getColumnValue(PGresult*& r, const int row, const size_t col,
  357. uint32_t &value) const {
  358. const char* data = getRawColumnValue(r, row, col);
  359. try {
  360. value = boost::lexical_cast<uint32_t>(data);
  361. } catch (const std::exception& ex) {
  362. isc_throw(DbOperationError, "Invalid uint32_t data: " << data
  363. << " for: " << getColumnLabel(col) << " row:" << row
  364. << " : " << ex.what());
  365. }
  366. }
  367. /// @brief Fetches an integer text column as a int32_t.
  368. ///
  369. /// @param r the result set containing the query results
  370. /// @param row the row number within the result set
  371. /// @param col the column number within the row
  372. /// @param[out] value parameter to receive the converted value
  373. ///
  374. /// @throw DbOperationError if the value cannot be fetched or is
  375. /// invalid.
  376. void getColumnValue(PGresult*& r, const int row, const size_t col,
  377. int32_t &value) const {
  378. const char* data = getRawColumnValue(r, row, col);
  379. try {
  380. value = boost::lexical_cast<int32_t>(data);
  381. } catch (const std::exception& ex) {
  382. isc_throw(DbOperationError, "Invalid int32_t data: " << data
  383. << " for: " << getColumnLabel(col) << " row:" << row
  384. << " : " << ex.what());
  385. }
  386. }
  387. /// @brief Fetches an integer text column as a uint8_t.
  388. ///
  389. /// @param r the result set containing the query results
  390. /// @param row the row number within the result set
  391. /// @param col the column number within the row
  392. /// @param[out] value parameter to receive the converted value
  393. ///
  394. /// @throw DbOperationError if the value cannot be fetched or is
  395. /// invalid.
  396. void getColumnValue(PGresult*& r, const int row, const size_t col,
  397. uint8_t &value) const {
  398. const char* data = getRawColumnValue(r, row, col);
  399. try {
  400. // lexically casting as uint8_t doesn't convert from char
  401. // so we use uint16_t and implicitly convert.
  402. value = boost::lexical_cast<uint16_t>(data);
  403. } catch (const std::exception& ex) {
  404. isc_throw(DbOperationError, "Invalid uint8_t data: " << data
  405. << " for: " << getColumnLabel(col) << " row:" << row
  406. << " : " << ex.what());
  407. }
  408. }
  409. /// @brief Fetches an integer text column as a Lease6::Type
  410. ///
  411. /// @param r the result set containing the query results
  412. /// @param row the row number within the result set
  413. /// @param col the column number within the row
  414. /// @param[out] value parameter to receive the converted value
  415. ///
  416. /// @throw DbOperationError if the value cannot be fetched or is
  417. /// invalid.
  418. void getColumnValue(PGresult*& r, const int row, const size_t col,
  419. Lease6::Type& value) const {
  420. uint32_t raw_value = 0;
  421. getColumnValue(r, row , col, raw_value);
  422. switch (raw_value) {
  423. case Lease6::TYPE_NA:
  424. value = Lease6::TYPE_NA;
  425. break;
  426. case Lease6::TYPE_TA:
  427. value = Lease6::TYPE_TA;
  428. break;
  429. case Lease6::TYPE_PD:
  430. value = Lease6::TYPE_PD;
  431. break;
  432. default:
  433. isc_throw(DbOperationError, "Invalid lease type: " << raw_value
  434. << " for: " << getColumnLabel(col) << " row:" << row);
  435. }
  436. }
  437. /// @brief Converts a column in a row in a result set to a binary bytes
  438. ///
  439. /// Method is used to convert columns stored as BYTEA into a buffer of
  440. /// binary bytes, (uint8_t). It uses PQunescapeBytea to do the conversion.
  441. ///
  442. /// @param r the result set containing the query results
  443. /// @param row the row number within the result set
  444. /// @param col the column number within the row
  445. /// @param[out] buffer pre-allocated buffer to which the converted bytes
  446. /// will be stored.
  447. /// @param buffer_size size of the output buffer
  448. /// @param[out] bytes_converted number of bytes converted
  449. /// value
  450. ///
  451. /// @throw DbOperationError if the value cannot be fetched or is
  452. /// invalid.
  453. void convertFromBytea(PGresult*& r, const int row, const size_t col,
  454. uint8_t* buffer,
  455. const size_t buffer_size,
  456. size_t &bytes_converted) const {
  457. // Returns converted bytes in a dynamically allocated buffer, and
  458. // sets bytes_converted.
  459. unsigned char* bytes = PQunescapeBytea((const unsigned char*)
  460. (getRawColumnValue(r, row, col)),
  461. &bytes_converted);
  462. // Unlikely it couldn't allocate it but you never know.
  463. if (!bytes) {
  464. isc_throw (DbOperationError, "PQunescapeBytea failed for:"
  465. << getColumnLabel(col) << " row:" << row);
  466. }
  467. // Make sure it's not larger than expected.
  468. if (bytes_converted > buffer_size) {
  469. // Free the allocated buffer first!
  470. PQfreemem(bytes);
  471. isc_throw (DbOperationError, "Converted data size: "
  472. << bytes_converted << " is too large for: "
  473. << getColumnLabel(col) << " row:" << row);
  474. }
  475. // Copy from the allocated buffer to caller's buffer the free up
  476. // the allocated buffer.
  477. memcpy(buffer, bytes, bytes_converted);
  478. PQfreemem(bytes);
  479. }
  480. /// @brief Returns column label given a column number
  481. std::string getColumnLabel(const size_t column) const {
  482. if (column > column_labels_.size()) {
  483. ostringstream os;
  484. os << "Unknown column:" << column;
  485. return (os.str());
  486. }
  487. return (column_labels_[column]);
  488. }
  489. protected:
  490. /// @brief Stores text labels for columns, currently only used for
  491. /// logging and errors.
  492. std::vector<std::string>column_labels_;
  493. /// @brief Common Instance members used for binding and conversion
  494. //@{
  495. std::string addr_str_;
  496. uint32_t valid_lifetime_;
  497. std::string valid_lft_str_;
  498. time_t expire_;
  499. std::string expire_str_;
  500. uint32_t subnet_id_;
  501. std::string subnet_id_str_;
  502. time_t cltt_;
  503. bool fqdn_fwd_;
  504. bool fqdn_rev_;
  505. std::string hostname_;
  506. std::string state_str_;
  507. //@}
  508. };
  509. /// @brief Supports exchanging IPv4 leases with PostgreSQL.
  510. class PgSqlLease4Exchange : public PgSqlLeaseExchange {
  511. private:
  512. /// @brief Column numbers for each column in the Lease4 table.
  513. /// These are used for both retrieving data and for looking up
  514. /// column labels for logging. Note that their numeric order
  515. /// MUST match that of the column order in the Lease4 table.
  516. static const size_t ADDRESS_COL = 0;
  517. static const size_t HWADDR_COL = 1;
  518. static const size_t CLIENT_ID_COL = 2;
  519. static const size_t VALID_LIFETIME_COL = 3;
  520. static const size_t EXPIRE_COL = 4;
  521. static const size_t SUBNET_ID_COL = 5;
  522. static const size_t FQDN_FWD_COL = 6;
  523. static const size_t FQDN_REV_COL = 7;
  524. static const size_t HOSTNAME_COL = 8;
  525. static const size_t STATE_COL = 9;
  526. /// @brief Number of columns in the table holding DHCPv4 leases.
  527. static const size_t LEASE_COLUMNS = 10;
  528. public:
  529. /// @brief Default constructor
  530. PgSqlLease4Exchange()
  531. : lease_(), addr4_(0), hwaddr_length_(0), hwaddr_(hwaddr_length_),
  532. client_id_length_(0) {
  533. BOOST_STATIC_ASSERT(9 < LEASE_COLUMNS);
  534. memset(hwaddr_buffer_, 0, sizeof(hwaddr_buffer_));
  535. memset(client_id_buffer_, 0, sizeof(client_id_buffer_));
  536. // Set the column names (for error messages)
  537. column_labels_.push_back("address");
  538. column_labels_.push_back("hwaddr");
  539. column_labels_.push_back("client_id");
  540. column_labels_.push_back("valid_lifetime");
  541. column_labels_.push_back("expire");
  542. column_labels_.push_back("subnet_id");
  543. column_labels_.push_back("fqdn_fwd");
  544. column_labels_.push_back("fqdn_rev");
  545. column_labels_.push_back("hostname");
  546. column_labels_.push_back("state");
  547. }
  548. /// @brief Creates the bind array for sending Lease4 data to the database.
  549. ///
  550. /// Converts each Lease4 member into the appropriate form and adds it
  551. /// to the bind array. Note that the array additions must occur in the
  552. /// order the columns are specified in the SQL statement. By convention
  553. /// all columns in the table are explicitly listed in the SQL statement(s)
  554. /// in the same order as they occur in the table.
  555. ///
  556. /// @param lease Lease4 object that is to be written to the database
  557. /// @param[out] bind_array array to populate with the lease data values
  558. ///
  559. /// @throw DbOperationError if bind_array cannot be populated.
  560. void createBindForSend(const Lease4Ptr& lease, PsqlBindArray& bind_array) {
  561. if (!lease) {
  562. isc_throw(BadValue, "createBindForSend:: Lease4 object is NULL");
  563. }
  564. // Store lease object to ensure it remains valid.
  565. lease_ = lease;
  566. try {
  567. addr_str_ = boost::lexical_cast<std::string>
  568. (static_cast<uint32_t>(lease->addr_));
  569. bind_array.add(addr_str_);
  570. if (lease->hwaddr_ && !lease->hwaddr_->hwaddr_.empty()) {
  571. // PostgreSql does not provide MAX on variable length types
  572. // so we have to enforce it ourselves.
  573. if (lease->hwaddr_->hwaddr_.size() > HWAddr::MAX_HWADDR_LEN) {
  574. isc_throw(DbOperationError, "Hardware address length : "
  575. << lease_->hwaddr_->hwaddr_.size()
  576. << " exceeds maximum allowed of: "
  577. << HWAddr::MAX_HWADDR_LEN);
  578. }
  579. bind_array.add(lease->hwaddr_->hwaddr_);
  580. } else {
  581. bind_array.add("");
  582. }
  583. if (lease->client_id_) {
  584. bind_array.add(lease->client_id_->getClientId());
  585. } else {
  586. bind_array.add("");
  587. }
  588. valid_lft_str_ = boost::lexical_cast<std::string>
  589. (lease->valid_lft_);
  590. bind_array.add(valid_lft_str_);
  591. expire_str_ = convertToDatabaseTime(lease->cltt_, lease_->valid_lft_);
  592. bind_array.add(expire_str_);
  593. subnet_id_str_ = boost::lexical_cast<std::string>
  594. (lease->subnet_id_);
  595. bind_array.add(subnet_id_str_);
  596. bind_array.add(lease->fqdn_fwd_);
  597. bind_array.add(lease->fqdn_rev_);
  598. bind_array.add(lease->hostname_);
  599. state_str_ = boost::lexical_cast<std::string>(lease->state_);
  600. bind_array.add(state_str_);
  601. } catch (const std::exception& ex) {
  602. isc_throw(DbOperationError,
  603. "Could not create bind array from Lease4: "
  604. << lease_->addr_.toText() << ", reason: " << ex.what());
  605. }
  606. }
  607. /// @brief Creates a Lease4 object from a given row in a result set.
  608. ///
  609. /// @param r result set containing one or rows from the Lease4 table
  610. /// @param row row number within the result set from to create the Lease4
  611. /// object.
  612. ///
  613. /// @return Lease4Ptr to the newly created Lease4 object
  614. /// @throw DbOperationError if the lease cannot be created.
  615. Lease4Ptr convertFromDatabase(PGresult*& r, int row) {
  616. try {
  617. getColumnValue(r, row, ADDRESS_COL, addr4_);
  618. convertFromBytea(r, row, HWADDR_COL, hwaddr_buffer_,
  619. sizeof(hwaddr_buffer_), hwaddr_length_);
  620. convertFromBytea(r, row, CLIENT_ID_COL, client_id_buffer_,
  621. sizeof(client_id_buffer_), client_id_length_);
  622. getColumnValue(r, row, VALID_LIFETIME_COL, valid_lifetime_);
  623. expire_ = convertFromDatabaseTime(getRawColumnValue(r, row,
  624. EXPIRE_COL));
  625. getColumnValue(r, row , SUBNET_ID_COL, subnet_id_);
  626. cltt_ = expire_ - valid_lifetime_;
  627. getColumnValue(r, row, FQDN_FWD_COL, fqdn_fwd_);
  628. getColumnValue(r, row, FQDN_REV_COL, fqdn_rev_);
  629. hostname_ = getRawColumnValue(r, row, HOSTNAME_COL);
  630. HWAddrPtr hwaddr(new HWAddr(hwaddr_buffer_, hwaddr_length_,
  631. HTYPE_ETHER));
  632. return (Lease4Ptr(new Lease4(addr4_, hwaddr,
  633. client_id_buffer_, client_id_length_,
  634. valid_lifetime_, 0, 0, cltt_,
  635. subnet_id_, fqdn_fwd_, fqdn_rev_,
  636. hostname_)));
  637. } catch (const std::exception& ex) {
  638. isc_throw(DbOperationError,
  639. "Could not convert data to Lease4, reason: "
  640. << ex.what());
  641. }
  642. }
  643. private:
  644. /// @brief Lease4 object currently being sent to the database.
  645. /// Storing this value ensures that it remains in scope while any bindings
  646. /// that refer to its contents are in use.
  647. Lease4Ptr lease_;
  648. /// @Brief Lease4 specific members used for binding and conversion.
  649. uint32_t addr4_;
  650. size_t hwaddr_length_;
  651. std::vector<uint8_t> hwaddr_;
  652. uint8_t hwaddr_buffer_[HWAddr::MAX_HWADDR_LEN];
  653. size_t client_id_length_;
  654. uint8_t client_id_buffer_[ClientId::MAX_CLIENT_ID_LEN];
  655. };
  656. /// @brief Supports exchanging IPv6 leases with PostgreSQL.
  657. class PgSqlLease6Exchange : public PgSqlLeaseExchange {
  658. private:
  659. /// @brief Column numbers for each column in the Lease6 table.
  660. /// These are used for both retrieving data and for looking up
  661. /// column labels for logging. Note that their numeric order
  662. /// MUST match that of the column order in the Lease6 table.
  663. //@{
  664. static const int ADDRESS_COL = 0;
  665. static const int DUID_COL = 1;
  666. static const int VALID_LIFETIME_COL = 2;
  667. static const int EXPIRE_COL = 3;
  668. static const int SUBNET_ID_COL = 4;
  669. static const int PREF_LIFETIME_COL = 5;
  670. static const int LEASE_TYPE_COL = 6;
  671. static const int IAID_COL = 7;
  672. static const int PREFIX_LEN_COL = 8;
  673. static const int FQDN_FWD_COL = 9;
  674. static const int FQDN_REV_COL = 10;
  675. static const int HOSTNAME_COL = 11;
  676. static const int STATE_COL = 12;
  677. //@}
  678. /// @brief Number of columns in the table holding DHCPv6 leases.
  679. static const size_t LEASE_COLUMNS = 13;
  680. public:
  681. PgSqlLease6Exchange()
  682. : lease_(), duid_length_(0), duid_(), iaid_u_(0), iaid_str_(""),
  683. lease_type_(Lease6::TYPE_NA), lease_type_str_(""), prefix_len_(0),
  684. prefix_len_str_(""), pref_lifetime_(0), preferred_lft_str_("") {
  685. BOOST_STATIC_ASSERT(12 < LEASE_COLUMNS);
  686. memset(duid_buffer_, 0, sizeof(duid_buffer_));
  687. // Set the column names (for error messages)
  688. column_labels_.push_back("address");
  689. column_labels_.push_back("duid");
  690. column_labels_.push_back("valid_lifetime");
  691. column_labels_.push_back("expire");
  692. column_labels_.push_back("subnet_id");
  693. column_labels_.push_back("pref_lifetime");
  694. column_labels_.push_back("lease_type");
  695. column_labels_.push_back("iaid");
  696. column_labels_.push_back("prefix_len");
  697. column_labels_.push_back("fqdn_fwd");
  698. column_labels_.push_back("fqdn_rev");
  699. column_labels_.push_back("hostname");
  700. column_labels_.push_back("state");
  701. }
  702. /// @brief Creates the bind array for sending Lease6 data to the database.
  703. ///
  704. /// Converts each Lease6 member into the appropriate form and adds it
  705. /// to the bind array. Note that the array additions must occur in the
  706. /// order the columns are specified in the SQL statement. By convention
  707. /// all columns in the table are explicitly listed in the SQL statement(s)
  708. /// in the same order as they occur in the table.
  709. ///
  710. /// @param lease Lease6 object that is to be written to the database
  711. /// @param[out] bind_array array to populate with the lease data values
  712. ///
  713. /// @throw DbOperationError if bind_array cannot be populated.
  714. void createBindForSend(const Lease6Ptr& lease, PsqlBindArray& bind_array) {
  715. if (!lease) {
  716. isc_throw(BadValue, "createBindForSend:: Lease6 object is NULL");
  717. }
  718. // Store lease object to ensure it remains valid.
  719. lease_ = lease;
  720. try {
  721. addr_str_ = lease_->addr_.toText();
  722. bind_array.add(addr_str_);
  723. if (lease_->duid_) {
  724. bind_array.add(lease_->duid_->getDuid());
  725. } else {
  726. isc_throw (BadValue, "IPv6 Lease cannot have a null DUID");
  727. }
  728. valid_lft_str_ = boost::lexical_cast<std::string>
  729. (lease->valid_lft_);
  730. bind_array.add(valid_lft_str_);
  731. expire_str_ = convertToDatabaseTime(lease->cltt_, lease_->valid_lft_);
  732. bind_array.add(expire_str_);
  733. subnet_id_str_ = boost::lexical_cast<std::string>
  734. (lease->subnet_id_);
  735. bind_array.add(subnet_id_str_);
  736. preferred_lft_str_ = boost::lexical_cast<std::string>
  737. (lease_->preferred_lft_);
  738. bind_array.add(preferred_lft_str_);
  739. lease_type_str_ = boost::lexical_cast<std::string>(lease_->type_);
  740. bind_array.add(lease_type_str_);
  741. // The iaid is stored as an INT in lease6 table, so we must
  742. // lexically cast from an integer version to avoid out of range
  743. // exception failure upon insert.
  744. iaid_u_.uval_ = lease_->iaid_;
  745. iaid_str_ = boost::lexical_cast<std::string>(iaid_u_.ival_);
  746. bind_array.add(iaid_str_);
  747. prefix_len_str_ = boost::lexical_cast<std::string>
  748. (static_cast<unsigned int>(lease_->prefixlen_));
  749. bind_array.add(prefix_len_str_);
  750. bind_array.add(lease->fqdn_fwd_);
  751. bind_array.add(lease->fqdn_rev_);
  752. bind_array.add(lease->hostname_);
  753. state_str_ = boost::lexical_cast<std::string>(lease->state_);
  754. bind_array.add(state_str_);
  755. } catch (const std::exception& ex) {
  756. isc_throw(DbOperationError,
  757. "Could not create bind array from Lease6: "
  758. << lease_->addr_.toText() << ", reason: " << ex.what());
  759. }
  760. }
  761. /// @brief Creates a Lease6 object from a given row in a result set.
  762. ///
  763. /// @param r result set containing one or rows from the Lease6 table
  764. /// @param row row number within the result set from to create the Lease6
  765. /// object.
  766. ///
  767. /// @return Lease6Ptr to the newly created Lease4 object
  768. /// @throw DbOperationError if the lease cannot be created.
  769. Lease6Ptr convertFromDatabase(PGresult*& r, int row) {
  770. try {
  771. isc::asiolink::IOAddress addr(getIPv6Value(r, row, ADDRESS_COL));
  772. convertFromBytea(r, row, DUID_COL, duid_buffer_,
  773. sizeof(duid_buffer_), duid_length_);
  774. DuidPtr duid_ptr(new DUID(duid_buffer_, duid_length_));
  775. getColumnValue(r, row, VALID_LIFETIME_COL, valid_lifetime_);
  776. expire_ = convertFromDatabaseTime(getRawColumnValue(r, row,
  777. EXPIRE_COL));
  778. cltt_ = expire_ - valid_lifetime_;
  779. getColumnValue(r, row , SUBNET_ID_COL, subnet_id_);
  780. getColumnValue(r, row , PREF_LIFETIME_COL, pref_lifetime_);
  781. getColumnValue(r, row, LEASE_TYPE_COL, lease_type_);
  782. getColumnValue(r, row , IAID_COL, iaid_u_.ival_);
  783. getColumnValue(r, row , PREFIX_LEN_COL, prefix_len_);
  784. getColumnValue(r, row, FQDN_FWD_COL, fqdn_fwd_);
  785. getColumnValue(r, row, FQDN_REV_COL, fqdn_rev_);
  786. hostname_ = getRawColumnValue(r, row, HOSTNAME_COL);
  787. /// @todo: implement this in #3557.
  788. HWAddrPtr hwaddr;
  789. Lease6Ptr result(new Lease6(lease_type_, addr, duid_ptr,
  790. iaid_u_.uval_, pref_lifetime_,
  791. valid_lifetime_, 0, 0,
  792. subnet_id_, fqdn_fwd_, fqdn_rev_,
  793. hostname_, hwaddr, prefix_len_));
  794. result->cltt_ = cltt_;
  795. return (result);
  796. } catch (const std::exception& ex) {
  797. isc_throw(DbOperationError,
  798. "Could not convert data to Lease6, reason: "
  799. << ex.what());
  800. }
  801. }
  802. /// @brief Converts a column in a row in a result set into IPv6 address.
  803. ///
  804. /// @param r the result set containing the query results
  805. /// @param row the row number within the result set
  806. /// @param col the column number within the row
  807. ///
  808. /// @return isc::asiolink::IOAddress containing the IPv6 address.
  809. /// @throw DbOperationError if the value cannot be fetched or is
  810. /// invalid.
  811. isc::asiolink::IOAddress getIPv6Value(PGresult*& r, const int row,
  812. const size_t col) const {
  813. const char* data = getRawColumnValue(r, row, col);
  814. try {
  815. return (isc::asiolink::IOAddress(data));
  816. } catch (const std::exception& ex) {
  817. isc_throw(DbOperationError, "Cannot convert data: " << data
  818. << " for: " << getColumnLabel(col) << " row:" << row
  819. << " : " << ex.what());
  820. }
  821. }
  822. private:
  823. /// @brief Lease6 object currently being sent to the database.
  824. /// Storing this value ensures that it remains in scope while any bindings
  825. /// that refer to its contents are in use.
  826. Lease6Ptr lease_;
  827. /// @brief Lease6 specific members for binding and conversion.
  828. //@{
  829. size_t duid_length_;
  830. vector<uint8_t> duid_;
  831. uint8_t duid_buffer_[DUID::MAX_DUID_LEN];
  832. /// @brief Union for marshalling IAID into and out of the database
  833. /// IAID is defined in the RFC as 4 octets, which Kea code handles as
  834. /// a uint32_t. Postgresql however, offers only signed integer types
  835. /// of sizes 2, 4, and 8 bytes (SMALLINT, INT, and BIGINT respectively).
  836. /// IAID is used in several indexes so rather than use the BIGINT, we
  837. /// use this union to safely move the value into and out of an INT column.
  838. union Uiaid {
  839. Uiaid(uint32_t val) : uval_(val){};
  840. Uiaid(int32_t val) : ival_(val){};
  841. uint32_t uval_;
  842. int32_t ival_;
  843. } iaid_u_;
  844. std::string iaid_str_;
  845. Lease6::Type lease_type_;
  846. std::string lease_type_str_;
  847. uint8_t prefix_len_;
  848. std::string prefix_len_str_;
  849. uint32_t pref_lifetime_;
  850. std::string preferred_lft_str_;
  851. //@}
  852. };
  853. PgSqlLeaseMgr::PgSqlLeaseMgr(const DatabaseConnection::ParameterMap& parameters)
  854. : LeaseMgr(), exchange4_(new PgSqlLease4Exchange()),
  855. exchange6_(new PgSqlLease6Exchange()), conn_(parameters) {
  856. conn_.openDatabase();
  857. prepareStatements();
  858. }
  859. PgSqlLeaseMgr::~PgSqlLeaseMgr() {
  860. }
  861. std::string
  862. PgSqlLeaseMgr::getDBVersion() {
  863. std::stringstream tmp;
  864. tmp << "PostgreSQL backend " << PG_CURRENT_VERSION;
  865. tmp << "." << PG_CURRENT_MINOR;
  866. tmp << ", library " << PQlibVersion();
  867. return (tmp.str());
  868. }
  869. void
  870. PgSqlLeaseMgr::prepareStatements() {
  871. for(int i = 0; tagged_statements[i].text != NULL; ++ i) {
  872. conn_.prepareStatement(tagged_statements[i]);
  873. }
  874. }
  875. bool
  876. PgSqlLeaseMgr::addLeaseCommon(StatementIndex stindex,
  877. PsqlBindArray& bind_array) {
  878. PGresult* r = PQexecPrepared(conn_, tagged_statements[stindex].name,
  879. tagged_statements[stindex].nbparams,
  880. &bind_array.values_[0],
  881. &bind_array.lengths_[0],
  882. &bind_array.formats_[0], 0);
  883. int s = PQresultStatus(r);
  884. if (s != PGRES_COMMAND_OK) {
  885. // Failure: check for the special case of duplicate entry. If this is
  886. // the case, we return false to indicate that the row was not added.
  887. // Otherwise we throw an exception.
  888. if (conn_.compareError(r, PgSqlConnection::DUPLICATE_KEY)) {
  889. PQclear(r);
  890. return (false);
  891. }
  892. conn_.checkStatementError(r, tagged_statements[stindex]);
  893. }
  894. PQclear(r);
  895. return (true);
  896. }
  897. bool
  898. PgSqlLeaseMgr::addLease(const Lease4Ptr& lease) {
  899. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  900. DHCPSRV_PGSQL_ADD_ADDR4).arg(lease->addr_.toText());
  901. PsqlBindArray bind_array;
  902. exchange4_->createBindForSend(lease, bind_array);
  903. return (addLeaseCommon(INSERT_LEASE4, bind_array));
  904. }
  905. bool
  906. PgSqlLeaseMgr::addLease(const Lease6Ptr& lease) {
  907. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  908. DHCPSRV_PGSQL_ADD_ADDR6).arg(lease->addr_.toText());
  909. PsqlBindArray bind_array;
  910. exchange6_->createBindForSend(lease, bind_array);
  911. return (addLeaseCommon(INSERT_LEASE6, bind_array));
  912. }
  913. template <typename Exchange, typename LeaseCollection>
  914. void PgSqlLeaseMgr::getLeaseCollection(StatementIndex stindex,
  915. PsqlBindArray& bind_array,
  916. Exchange& exchange,
  917. LeaseCollection& result,
  918. bool single) const {
  919. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  920. DHCPSRV_PGSQL_GET_ADDR4).arg(tagged_statements[stindex].name);
  921. PGresult* r = PQexecPrepared(conn_, tagged_statements[stindex].name,
  922. tagged_statements[stindex].nbparams,
  923. &bind_array.values_[0],
  924. &bind_array.lengths_[0],
  925. &bind_array.formats_[0], 0);
  926. conn_.checkStatementError(r, tagged_statements[stindex]);
  927. int rows = PQntuples(r);
  928. if (single && rows > 1) {
  929. PQclear(r);
  930. isc_throw(MultipleRecords, "multiple records were found in the "
  931. "database where only one was expected for query "
  932. << tagged_statements[stindex].name);
  933. }
  934. for(int i = 0; i < rows; ++ i) {
  935. result.push_back(exchange->convertFromDatabase(r, i));
  936. }
  937. PQclear(r);
  938. }
  939. void
  940. PgSqlLeaseMgr::getLease(StatementIndex stindex, PsqlBindArray& bind_array,
  941. Lease4Ptr& result) const {
  942. // Create appropriate collection object and get all leases matching
  943. // the selection criteria. The "single" parameter is true to indicate
  944. // that the called method should throw an exception if multiple
  945. // matching records are found: this particular method is called when only
  946. // one or zero matches is expected.
  947. Lease4Collection collection;
  948. getLeaseCollection(stindex, bind_array, exchange4_, collection, true);
  949. // Return single record if present, else clear the lease.
  950. if (collection.empty()) {
  951. result.reset();
  952. } else {
  953. result = *collection.begin();
  954. }
  955. }
  956. void
  957. PgSqlLeaseMgr::getLease(StatementIndex stindex, PsqlBindArray& bind_array,
  958. Lease6Ptr& result) const {
  959. // Create appropriate collection object and get all leases matching
  960. // the selection criteria. The "single" parameter is true to indicate
  961. // that the called method should throw an exception if multiple
  962. // matching records are found: this particular method is called when only
  963. // one or zero matches is expected.
  964. Lease6Collection collection;
  965. getLeaseCollection(stindex, bind_array, exchange6_, collection, true);
  966. // Return single record if present, else clear the lease.
  967. if (collection.empty()) {
  968. result.reset();
  969. } else {
  970. result = *collection.begin();
  971. }
  972. }
  973. Lease4Ptr
  974. PgSqlLeaseMgr::getLease4(const isc::asiolink::IOAddress& addr) const {
  975. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  976. DHCPSRV_PGSQL_GET_ADDR4).arg(addr.toText());
  977. // Set up the WHERE clause value
  978. PsqlBindArray bind_array;
  979. // LEASE ADDRESS
  980. std::string addr_str = boost::lexical_cast<std::string>
  981. (static_cast<uint32_t>(addr));
  982. bind_array.add(addr_str);
  983. // Get the data
  984. Lease4Ptr result;
  985. getLease(GET_LEASE4_ADDR, bind_array, result);
  986. return (result);
  987. }
  988. Lease4Collection
  989. PgSqlLeaseMgr::getLease4(const HWAddr& hwaddr) const {
  990. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  991. DHCPSRV_PGSQL_GET_HWADDR).arg(hwaddr.toText());
  992. // Set up the WHERE clause value
  993. PsqlBindArray bind_array;
  994. // HWADDR
  995. if (!hwaddr.hwaddr_.empty()) {
  996. bind_array.add(hwaddr.hwaddr_);
  997. } else {
  998. bind_array.add("");
  999. }
  1000. // Get the data
  1001. Lease4Collection result;
  1002. getLeaseCollection(GET_LEASE4_HWADDR, bind_array, result);
  1003. return (result);
  1004. }
  1005. Lease4Ptr
  1006. PgSqlLeaseMgr::getLease4(const HWAddr& hwaddr, SubnetID subnet_id) const {
  1007. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1008. DHCPSRV_PGSQL_GET_SUBID_HWADDR)
  1009. .arg(subnet_id).arg(hwaddr.toText());
  1010. // Set up the WHERE clause value
  1011. PsqlBindArray bind_array;
  1012. // HWADDR
  1013. if (!hwaddr.hwaddr_.empty()) {
  1014. bind_array.add(hwaddr.hwaddr_);
  1015. } else {
  1016. bind_array.add("");
  1017. }
  1018. // SUBNET_ID
  1019. std::string subnet_id_str = boost::lexical_cast<std::string>(subnet_id);
  1020. bind_array.add(subnet_id_str);
  1021. // Get the data
  1022. Lease4Ptr result;
  1023. getLease(GET_LEASE4_HWADDR_SUBID, bind_array, result);
  1024. return (result);
  1025. }
  1026. Lease4Collection
  1027. PgSqlLeaseMgr::getLease4(const ClientId& clientid) const {
  1028. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1029. DHCPSRV_PGSQL_GET_CLIENTID).arg(clientid.toText());
  1030. // Set up the WHERE clause value
  1031. PsqlBindArray bind_array;
  1032. // CLIENT_ID
  1033. bind_array.add(clientid.getClientId());
  1034. // Get the data
  1035. Lease4Collection result;
  1036. getLeaseCollection(GET_LEASE4_CLIENTID, bind_array, result);
  1037. return (result);
  1038. }
  1039. Lease4Ptr
  1040. PgSqlLeaseMgr::getLease4(const ClientId& clientid, SubnetID subnet_id) const {
  1041. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1042. DHCPSRV_PGSQL_GET_SUBID_CLIENTID)
  1043. .arg(subnet_id).arg(clientid.toText());
  1044. // Set up the WHERE clause value
  1045. PsqlBindArray bind_array;
  1046. // CLIENT_ID
  1047. bind_array.add(clientid.getClientId());
  1048. // SUBNET_ID
  1049. std::string subnet_id_str = boost::lexical_cast<std::string>(subnet_id);
  1050. bind_array.add(subnet_id_str);
  1051. // Get the data
  1052. Lease4Ptr result;
  1053. getLease(GET_LEASE4_CLIENTID_SUBID, bind_array, result);
  1054. return (result);
  1055. }
  1056. Lease4Ptr
  1057. PgSqlLeaseMgr::getLease4(const ClientId&, const HWAddr&, SubnetID) const {
  1058. /// This function is currently not implemented because allocation engine
  1059. /// searches for the lease using HW address or client identifier.
  1060. /// It never uses both parameters in the same time. We need to
  1061. /// consider if this function is needed at all.
  1062. isc_throw(NotImplemented, "The PgSqlLeaseMgr::getLease4 function was"
  1063. " called, but it is not implemented");
  1064. }
  1065. Lease6Ptr
  1066. PgSqlLeaseMgr::getLease6(Lease::Type lease_type,
  1067. const isc::asiolink::IOAddress& addr) const {
  1068. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL, DHCPSRV_PGSQL_GET_ADDR6)
  1069. .arg(addr.toText()).arg(lease_type);
  1070. // Set up the WHERE clause value
  1071. PsqlBindArray bind_array;
  1072. // LEASE ADDRESS
  1073. std::string addr_str = addr.toText();
  1074. bind_array.add(addr_str);
  1075. // LEASE_TYPE
  1076. std::string type_str_ = boost::lexical_cast<std::string>(lease_type);
  1077. bind_array.add(type_str_);
  1078. // ... and get the data
  1079. Lease6Ptr result;
  1080. getLease(GET_LEASE6_ADDR, bind_array, result);
  1081. return (result);
  1082. }
  1083. Lease6Collection
  1084. PgSqlLeaseMgr::getLeases6(Lease::Type lease_type, const DUID& duid,
  1085. uint32_t iaid) const {
  1086. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1087. DHCPSRV_PGSQL_GET_IAID_DUID)
  1088. .arg(iaid).arg(duid.toText()).arg(lease_type);
  1089. // Set up the WHERE clause value
  1090. PsqlBindArray bind_array;
  1091. // DUID
  1092. bind_array.add(duid.getDuid());
  1093. // IAID
  1094. std::string iaid_str = boost::lexical_cast<std::string>(iaid);
  1095. bind_array.add(iaid_str);
  1096. // LEASE_TYPE
  1097. std::string lease_type_str = boost::lexical_cast<std::string>(lease_type);
  1098. bind_array.add(lease_type_str);
  1099. // ... and get the data
  1100. Lease6Collection result;
  1101. getLeaseCollection(GET_LEASE6_DUID_IAID, bind_array, result);
  1102. return (result);
  1103. }
  1104. Lease6Collection
  1105. PgSqlLeaseMgr::getLeases6(Lease::Type lease_type, const DUID& duid,
  1106. uint32_t iaid, SubnetID subnet_id) const {
  1107. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1108. DHCPSRV_PGSQL_GET_IAID_SUBID_DUID)
  1109. .arg(iaid).arg(subnet_id).arg(duid.toText()).arg(lease_type);
  1110. // Set up the WHERE clause value
  1111. PsqlBindArray bind_array;
  1112. // LEASE_TYPE
  1113. std::string lease_type_str = boost::lexical_cast<std::string>(lease_type);
  1114. bind_array.add(lease_type_str);
  1115. // DUID
  1116. bind_array.add(duid.getDuid());
  1117. // IAID
  1118. std::string iaid_str = boost::lexical_cast<std::string>(iaid);
  1119. bind_array.add(iaid_str);
  1120. // SUBNET ID
  1121. std::string subnet_id_str = boost::lexical_cast<std::string>(subnet_id);
  1122. bind_array.add(subnet_id_str);
  1123. // ... and get the data
  1124. Lease6Collection result;
  1125. getLeaseCollection(GET_LEASE6_DUID_IAID_SUBID, bind_array, result);
  1126. return (result);
  1127. }
  1128. void
  1129. PgSqlLeaseMgr::getExpiredLeases6(Lease6Collection& expired_leases,
  1130. const size_t max_leases) const {
  1131. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL, DHCPSRV_PGSQL_GET_EXPIRED6)
  1132. .arg(max_leases);
  1133. getExpiredLeasesCommon(expired_leases, max_leases, GET_LEASE6_EXPIRE);
  1134. }
  1135. void
  1136. PgSqlLeaseMgr::getExpiredLeases4(Lease4Collection& expired_leases,
  1137. const size_t max_leases) const {
  1138. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL, DHCPSRV_PGSQL_GET_EXPIRED4)
  1139. .arg(max_leases);
  1140. getExpiredLeasesCommon(expired_leases, max_leases, GET_LEASE4_EXPIRE);
  1141. }
  1142. template<typename LeaseCollection>
  1143. void
  1144. PgSqlLeaseMgr::getExpiredLeasesCommon(LeaseCollection& expired_leases,
  1145. const size_t max_leases,
  1146. StatementIndex statement_index) const {
  1147. PsqlBindArray bind_array;
  1148. // Exclude reclaimed leases.
  1149. std::string state_str = boost::lexical_cast<std::string>(Lease::STATE_EXPIRED_RECLAIMED);
  1150. bind_array.add(state_str);
  1151. // Expiration timestamp.
  1152. std::string timestamp_str = PgSqlLeaseExchange::convertToDatabaseTime(time(NULL));
  1153. bind_array.add(timestamp_str);
  1154. // If the number of leases is 0, we will return all leases. This is
  1155. // achieved by setting the limit to a very high value.
  1156. uint32_t limit = max_leases > 0 ? static_cast<uint32_t>(max_leases) :
  1157. std::numeric_limits<uint32_t>::max();
  1158. std::string limit_str = boost::lexical_cast<std::string>(limit);
  1159. bind_array.add(limit_str);
  1160. // Retrieve leases from the database.
  1161. getLeaseCollection(statement_index, bind_array, expired_leases);
  1162. }
  1163. template<typename LeasePtr>
  1164. void
  1165. PgSqlLeaseMgr::updateLeaseCommon(StatementIndex stindex,
  1166. PsqlBindArray& bind_array,
  1167. const LeasePtr& lease) {
  1168. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1169. DHCPSRV_PGSQL_ADD_ADDR4).arg(tagged_statements[stindex].name);
  1170. PGresult* r = PQexecPrepared(conn_, tagged_statements[stindex].name,
  1171. tagged_statements[stindex].nbparams,
  1172. &bind_array.values_[0],
  1173. &bind_array.lengths_[0],
  1174. &bind_array.formats_[0], 0);
  1175. conn_.checkStatementError(r, tagged_statements[stindex]);
  1176. int affected_rows = boost::lexical_cast<int>(PQcmdTuples(r));
  1177. PQclear(r);
  1178. // Check success case first as it is the most likely outcome.
  1179. if (affected_rows == 1) {
  1180. return;
  1181. }
  1182. // If no rows affected, lease doesn't exist.
  1183. if (affected_rows == 0) {
  1184. isc_throw(NoSuchLease, "unable to update lease for address " <<
  1185. lease->addr_.toText() << " as it does not exist");
  1186. }
  1187. // Should not happen - primary key constraint should only have selected
  1188. // one row.
  1189. isc_throw(DbOperationError, "apparently updated more than one lease "
  1190. "that had the address " << lease->addr_.toText());
  1191. }
  1192. void
  1193. PgSqlLeaseMgr::updateLease4(const Lease4Ptr& lease) {
  1194. const StatementIndex stindex = UPDATE_LEASE4;
  1195. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1196. DHCPSRV_PGSQL_UPDATE_ADDR4).arg(lease->addr_.toText());
  1197. // Create the BIND array for the data being updated
  1198. PsqlBindArray bind_array;
  1199. exchange4_->createBindForSend(lease, bind_array);
  1200. // Set up the WHERE clause and append it to the SQL_BIND array
  1201. std::string addr4_ = boost::lexical_cast<std::string>
  1202. (static_cast<uint32_t>(lease->addr_));
  1203. bind_array.add(addr4_);
  1204. // Drop to common update code
  1205. updateLeaseCommon(stindex, bind_array, lease);
  1206. }
  1207. void
  1208. PgSqlLeaseMgr::updateLease6(const Lease6Ptr& lease) {
  1209. const StatementIndex stindex = UPDATE_LEASE6;
  1210. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1211. DHCPSRV_PGSQL_UPDATE_ADDR6).arg(lease->addr_.toText());
  1212. // Create the BIND array for the data being updated
  1213. PsqlBindArray bind_array;
  1214. exchange6_->createBindForSend(lease, bind_array);
  1215. // Set up the WHERE clause and append it to the BIND array
  1216. std::string addr_str = lease->addr_.toText();
  1217. bind_array.add(addr_str);
  1218. // Drop to common update code
  1219. updateLeaseCommon(stindex, bind_array, lease);
  1220. }
  1221. uint64_t
  1222. PgSqlLeaseMgr::deleteLeaseCommon(StatementIndex stindex,
  1223. PsqlBindArray& bind_array) {
  1224. PGresult* r = PQexecPrepared(conn_, tagged_statements[stindex].name,
  1225. tagged_statements[stindex].nbparams,
  1226. &bind_array.values_[0],
  1227. &bind_array.lengths_[0],
  1228. &bind_array.formats_[0], 0);
  1229. conn_.checkStatementError(r, tagged_statements[stindex]);
  1230. int affected_rows = boost::lexical_cast<int>(PQcmdTuples(r));
  1231. PQclear(r);
  1232. return (affected_rows);
  1233. }
  1234. bool
  1235. PgSqlLeaseMgr::deleteLease(const isc::asiolink::IOAddress& addr) {
  1236. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1237. DHCPSRV_PGSQL_DELETE_ADDR).arg(addr.toText());
  1238. // Set up the WHERE clause value
  1239. PsqlBindArray bind_array;
  1240. if (addr.isV4()) {
  1241. std::string addr4_str = boost::lexical_cast<std::string>
  1242. (static_cast<uint32_t>(addr));
  1243. bind_array.add(addr4_str);
  1244. return (deleteLeaseCommon(DELETE_LEASE4, bind_array) > 0);
  1245. }
  1246. std::string addr6_str = addr.toText();
  1247. bind_array.add(addr6_str);
  1248. return (deleteLeaseCommon(DELETE_LEASE6, bind_array) > 0);
  1249. }
  1250. uint64_t
  1251. PgSqlLeaseMgr::deleteExpiredReclaimedLeases4(const uint32_t secs) {
  1252. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1253. DHCPSRV_PGSQL_DELETE_EXPIRED_RECLAIMED4)
  1254. .arg(secs);
  1255. return (deleteExpiredReclaimedLeasesCommon(secs, DELETE_LEASE4_STATE_EXPIRED));
  1256. }
  1257. uint64_t
  1258. PgSqlLeaseMgr::deleteExpiredReclaimedLeases6(const uint32_t secs) {
  1259. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1260. DHCPSRV_PGSQL_DELETE_EXPIRED_RECLAIMED6)
  1261. .arg(secs);
  1262. return (deleteExpiredReclaimedLeasesCommon(secs, DELETE_LEASE6_STATE_EXPIRED));
  1263. }
  1264. uint64_t
  1265. PgSqlLeaseMgr::deleteExpiredReclaimedLeasesCommon(const uint32_t secs,
  1266. StatementIndex statement_index) {
  1267. PsqlBindArray bind_array;
  1268. // State is reclaimed.
  1269. std::string state_str = boost::lexical_cast<std::string>(Lease::STATE_EXPIRED_RECLAIMED);
  1270. bind_array.add(state_str);
  1271. // Expiration timestamp.
  1272. std::string expiration_str =
  1273. PgSqlLeaseExchange::convertToDatabaseTime(time(NULL) - static_cast<time_t>(secs));
  1274. bind_array.add(expiration_str);
  1275. // Delete leases.
  1276. return (deleteLeaseCommon(statement_index, bind_array));
  1277. }
  1278. string
  1279. PgSqlLeaseMgr::getName() const {
  1280. string name = "";
  1281. try {
  1282. name = conn_.getParameter("name");
  1283. } catch (...) {
  1284. // Return an empty name
  1285. }
  1286. return (name);
  1287. }
  1288. string
  1289. PgSqlLeaseMgr::getDescription() const {
  1290. return (string("PostgreSQL Database"));
  1291. }
  1292. pair<uint32_t, uint32_t>
  1293. PgSqlLeaseMgr::getVersion() const {
  1294. LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
  1295. DHCPSRV_PGSQL_GET_VERSION);
  1296. PGresult* r = PQexecPrepared(conn_, "get_version", 0, NULL, NULL, NULL, 0);
  1297. conn_.checkStatementError(r, tagged_statements[GET_VERSION]);
  1298. istringstream tmp;
  1299. uint32_t version;
  1300. tmp.str(PQgetvalue(r, 0, 0));
  1301. tmp >> version;
  1302. tmp.str("");
  1303. tmp.clear();
  1304. uint32_t minor;
  1305. tmp.str(PQgetvalue(r, 0, 1));
  1306. tmp >> minor;
  1307. PQclear(r);
  1308. return make_pair<uint32_t, uint32_t>(version, minor);
  1309. }
  1310. void
  1311. PgSqlLeaseMgr::commit() {
  1312. conn_.commit();
  1313. }
  1314. void
  1315. PgSqlLeaseMgr::rollback() {
  1316. conn_.rollback();
  1317. }
  1318. }; // end of isc::dhcp namespace
  1319. }; // end of isc namespace