database.h 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971
  1. // Copyright (C) 2011 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 __DATABASE_DATASRC_H
  15. #define __DATABASE_DATASRC_H
  16. #include <string>
  17. #include <boost/scoped_ptr.hpp>
  18. #include <dns/rrclass.h>
  19. #include <dns/rrclass.h>
  20. #include <dns/rrset.h>
  21. #include <datasrc/data_source.h>
  22. #include <datasrc/client.h>
  23. #include <datasrc/client.h>
  24. #include <dns/name.h>
  25. #include <exceptions/exceptions.h>
  26. #include <map>
  27. #include <set>
  28. namespace isc {
  29. namespace datasrc {
  30. /**
  31. * \brief No such serial number when obtaining difference iterator
  32. *
  33. * This exception can be thrown from \c DatabaseAccessor::getDiffs().
  34. * It's thrown if either the zone/start version or zone/end version
  35. * combination does not exist in the differences table.
  36. */
  37. class NoSuchSerial : public DataSourceError {
  38. public:
  39. NoSuchSerial(const char* file, size_t line, const char* what) :
  40. DataSourceError(file, line, what) {}
  41. };
  42. /**
  43. * \brief Abstraction of lowlevel database with DNS data
  44. *
  45. * This class is defines interface to databases. Each supported database
  46. * will provide methods for accessing the data stored there in a generic
  47. * manner. The methods are meant to be low-level, without much or any knowledge
  48. * about DNS and should be possible to translate directly to queries.
  49. *
  50. * On the other hand, how the communication with database is done and in what
  51. * schema (in case of relational/SQL database) is up to the concrete classes.
  52. *
  53. * This class is non-copyable, as copying connections to database makes little
  54. * sense and will not be needed.
  55. *
  56. * \todo Is it true this does not need to be copied? For example the zone
  57. * iterator might need it's own copy. But a virtual clone() method might
  58. * be better for that than copy constructor.
  59. *
  60. * \note The same application may create multiple connections to the same
  61. * database, having multiple instances of this class. If the database
  62. * allows having multiple open queries at one connection, the connection
  63. * class may share it.
  64. */
  65. class DatabaseAccessor : boost::noncopyable {
  66. public:
  67. /**
  68. * Definitions of the fields as they are required to be filled in
  69. * by IteratorContext::getNext()
  70. *
  71. * When implementing getNext(), the columns array should
  72. * be filled with the values as described in this enumeration,
  73. * in this order, i.e. TYPE_COLUMN should be the first element
  74. * (index 0) of the array, TTL_COLUMN should be the second element
  75. * (index 1), etc.
  76. */
  77. enum RecordColumns {
  78. TYPE_COLUMN = 0, ///< The RRType of the record (A/NS/TXT etc.)
  79. TTL_COLUMN = 1, ///< The TTL of the record (a
  80. SIGTYPE_COLUMN = 2, ///< For RRSIG records, this contains the RRTYPE
  81. ///< the RRSIG covers. In the current implementation,
  82. ///< this field is ignored.
  83. RDATA_COLUMN = 3, ///< Full text representation of the record's RDATA
  84. NAME_COLUMN = 4, ///< The domain name of this RR
  85. COLUMN_COUNT = 5 ///< The total number of columns, MUST be value of
  86. ///< the largest other element in this enum plus 1.
  87. };
  88. /**
  89. * Definitions of the fields to be passed to addRecordToZone().
  90. *
  91. * Each derived implementation of addRecordToZone() should expect
  92. * the "columns" array to be filled with the values as described in this
  93. * enumeration, in this order.
  94. */
  95. enum AddRecordColumns {
  96. ADD_NAME = 0, ///< The owner name of the record (a domain name)
  97. ADD_REV_NAME = 1, ///< Reversed name of NAME (used for DNSSEC)
  98. ADD_TTL = 2, ///< The TTL of the record (in numeric form)
  99. ADD_TYPE = 3, ///< The RRType of the record (A/NS/TXT etc.)
  100. ADD_SIGTYPE = 4, ///< For RRSIG records, this contains the RRTYPE
  101. ///< the RRSIG covers.
  102. ADD_RDATA = 5, ///< Full text representation of the record's RDATA
  103. ADD_COLUMN_COUNT = 6 ///< Number of columns
  104. };
  105. /**
  106. * Definitions of the fields to be passed to deleteRecordInZone().
  107. *
  108. * Each derived implementation of deleteRecordInZone() should expect
  109. * the "params" array to be filled with the values as described in this
  110. * enumeration, in this order.
  111. */
  112. enum DeleteRecordParams {
  113. DEL_NAME = 0, ///< The owner name of the record (a domain name)
  114. DEL_TYPE = 1, ///< The RRType of the record (A/NS/TXT etc.)
  115. DEL_RDATA = 2, ///< Full text representation of the record's RDATA
  116. DEL_PARAM_COUNT = 3 ///< Number of parameters
  117. };
  118. /**
  119. * Operation mode when adding a record diff.
  120. *
  121. * This is used as the "operation" parameter value of addRecordDiff().
  122. */
  123. enum DiffOperation {
  124. DIFF_ADD = 0, ///< This diff is for adding an RR
  125. DIFF_DELETE = 1 ///< This diff is for deleting an RR
  126. };
  127. /**
  128. * Definitions of the fields to be passed to addRecordDiff().
  129. *
  130. * Each derived implementation of addRecordDiff() should expect
  131. * the "params" array to be filled with the values as described in this
  132. * enumeration, in this order.
  133. */
  134. enum DiffRecordParams {
  135. DIFF_NAME = 0, ///< The owner name of the record (a domain name)
  136. DIFF_TYPE = 1, ///< The RRType of the record (A/NS/TXT etc.)
  137. DIFF_TTL = 2, ///< The TTL of the record (in numeric form)
  138. DIFF_RDATA = 3, ///< Full text representation of the record's RDATA
  139. DIFF_PARAM_COUNT = 4 ///< Number of parameters
  140. };
  141. /**
  142. * \brief Destructor
  143. *
  144. * It is empty, but needs a virtual one, since we will use the derived
  145. * classes in polymorphic way.
  146. */
  147. virtual ~DatabaseAccessor() { }
  148. /**
  149. * \brief Retrieve a zone identifier
  150. *
  151. * This method looks up a zone for the given name in the database. It
  152. * should match only exact zone name (eg. name is equal to the zone's
  153. * apex), as the DatabaseClient will loop trough the labels itself and
  154. * find the most suitable zone.
  155. *
  156. * It is not specified if and what implementation of this method may throw,
  157. * so code should expect anything.
  158. *
  159. * \param name The (fully qualified) domain name of the zone's apex to be
  160. * looked up.
  161. * \return The first part of the result indicates if a matching zone
  162. * was found. In case it was, the second part is internal zone ID.
  163. * This one will be passed to methods finding data in the zone.
  164. * It is not required to keep them, in which case whatever might
  165. * be returned - the ID is only passed back to the database as
  166. * an opaque handle.
  167. */
  168. virtual std::pair<bool, int> getZone(const std::string& name) const = 0;
  169. /**
  170. * \brief This holds the internal context of ZoneIterator for databases
  171. *
  172. * While the ZoneIterator implementation from DatabaseClient does all the
  173. * translation from strings to DNS classes and validation, this class
  174. * holds the pointer to where the database is at reading the data.
  175. *
  176. * It can either hold shared pointer to the connection which created it
  177. * and have some kind of statement inside (in case single database
  178. * connection can handle multiple concurrent SQL statements) or it can
  179. * create a new connection (or, if it is more convenient, the connection
  180. * itself can inherit both from DatabaseConnection and IteratorContext
  181. * and just clone itself).
  182. */
  183. class IteratorContext : public boost::noncopyable {
  184. public:
  185. /**
  186. * \brief Destructor
  187. *
  188. * Virtual destructor, so any descendand class is destroyed correctly.
  189. */
  190. virtual ~IteratorContext() { }
  191. /**
  192. * \brief Function to provide next resource record
  193. *
  194. * This function should provide data about the next resource record
  195. * from the data that is searched. The data is not converted yet.
  196. *
  197. * Depending on how the iterator was constructed, there is a difference
  198. * in behaviour; for a 'full zone iterator', created with
  199. * getAllRecords(), all COLUMN_COUNT elements of the array are
  200. * overwritten.
  201. * For a 'name iterator', created with getRecords(), the column
  202. * NAME_COLUMN is untouched, since what would be added here is by
  203. * definition already known to the caller (it already passes it as
  204. * an argument to getRecords()).
  205. *
  206. * Once this function returns false, any subsequent call to it should
  207. * result in false. The implementation of a derived class must ensure
  208. * it doesn't cause any disruption due to that such as a crash or
  209. * exception.
  210. *
  211. * \note The order of RRs is not strictly set, but the RRs for single
  212. * RRset must not be interleaved with any other RRs (eg. RRsets must be
  213. * "together").
  214. *
  215. * \param columns The data will be returned through here. The order
  216. * is specified by the RecordColumns enum, and the size must be
  217. * COLUMN_COUNT
  218. * \todo Do we consider databases where it is stored in binary blob
  219. * format?
  220. * \throw DataSourceError if there's database-related error. If the
  221. * exception (or any other in case of derived class) is thrown,
  222. * the iterator can't be safely used any more.
  223. * \return true if a record was found, and the columns array was
  224. * updated. false if there was no more data, in which case
  225. * the columns array is untouched.
  226. */
  227. virtual bool getNext(std::string (&columns)[COLUMN_COUNT]) = 0;
  228. };
  229. typedef boost::shared_ptr<IteratorContext> IteratorContextPtr;
  230. /**
  231. * \brief Creates an iterator context for a specific name.
  232. *
  233. * Returns an IteratorContextPtr that contains all records of the
  234. * given name from the given zone.
  235. *
  236. * The implementation of the iterator that is returned may leave the
  237. * NAME_COLUMN column of the array passed to getNext() untouched, as that
  238. * data is already known (it is the same as the name argument here)
  239. *
  240. * \exception any Since any implementation can be used, the caller should
  241. * expect any exception to be thrown.
  242. *
  243. * \param name The name to search for. This should be a FQDN.
  244. * \param id The ID of the zone, returned from getZone().
  245. * \param subdomains If set to true, match subdomains of name instead
  246. * of name itself. It is used to find empty domains and match
  247. * wildcards.
  248. * \return Newly created iterator context. Must not be NULL.
  249. */
  250. virtual IteratorContextPtr getRecords(const std::string& name,
  251. int id,
  252. bool subdomains = false) const = 0;
  253. /**
  254. * \brief Creates an iterator context for the whole zone.
  255. *
  256. * Returns an IteratorContextPtr that contains all records of the
  257. * zone with the given zone id.
  258. *
  259. * Each call to getNext() on the returned iterator should copy all
  260. * column fields of the array that is passed, as defined in the
  261. * RecordColumns enum.
  262. *
  263. * \exception any Since any implementation can be used, the caller should
  264. * expect any exception to be thrown.
  265. *
  266. * \param id The ID of the zone, returned from getZone().
  267. * \return Newly created iterator context. Must not be NULL.
  268. */
  269. virtual IteratorContextPtr getAllRecords(int id) const = 0;
  270. /**
  271. * \brief Creates an iterator context for a set of differences.
  272. *
  273. * Returns an IteratorContextPtr that contains all difference records for
  274. * the given zone between two versions of a zone.
  275. *
  276. * The difference records are the set of records that would appear in an
  277. * IXFR serving a request for the difference between two versions of a zone.
  278. * The records are returned in the same order as they would be in the IXFR.
  279. * This means that if the the difference between versions of a zone with SOA
  280. * serial numbers of "start" and "end" is required, and the zone contains
  281. * the differences between serial number "start" to serial number
  282. * "intermediate" and from serial number "intermediate" to serial number
  283. * "end", the returned records will be (in order):
  284. *
  285. * \li SOA for serial "start"
  286. * \li Records removed from the zone between versions "start" and
  287. * "intermediate" of the zone. The order of these is not guaranteed.
  288. * \li SOA for serial "intermediate"
  289. * \li Records added to the zone between versions "start" and
  290. * "intermediate" of the zone. The order of these is not guaranteed.
  291. * \li SOA for serial "intermediate"
  292. * \li Records removed from the zone between versions "intermediate" and
  293. * "end" of the zone. The order of these is not guaranteed.
  294. * \li SOA for serial "end"
  295. * \li Records added to the zone between versions "intermediate" and "end"
  296. * of the zone. The order of these is not guaranteed.
  297. *
  298. * Note that there is no requirement that "start" be less than "end". Owing
  299. * to serial number arithmetic, it is entirely possible that a later version
  300. * of a zone will have a smaller SOA serial number than an earlier version.
  301. *
  302. * Each call to getNext() on the returned iterator should copy all
  303. * column fields of the array that is passed, as defined in the
  304. * RecordColumns enum.
  305. *
  306. * \exception any Since any implementation can be used, the caller should
  307. * expect any exception to be thrown.
  308. *
  309. * \param id The ID of the zone, returned from getZone().
  310. * \param start The SOA serial number of the version of the zone from
  311. * which the difference sequence should start.
  312. * \param end The SOA serial number of the version of the zone at which
  313. * the difference sequence should end.
  314. *
  315. * \return Newly created iterator context. Must not be NULL.
  316. */
  317. virtual IteratorContextPtr
  318. getDiffs(int id, uint32_t start, uint32_t end) const = 0;
  319. /// Start a transaction for updating a zone.
  320. ///
  321. /// Each derived class version of this method starts a database
  322. /// transaction to make updates to the given name of zone (whose class was
  323. /// specified at the construction of the class).
  324. ///
  325. /// If \c replace is true, any existing records of the zone will be
  326. /// deleted on successful completion of updates (after
  327. /// \c commitUpdateZone()); if it's false, the existing records will be
  328. /// intact unless explicitly deleted by \c deleteRecordInZone().
  329. ///
  330. /// A single \c DatabaseAccessor instance can perform at most one
  331. /// transaction; a duplicate call to this method before
  332. /// \c commitUpdateZone() or \c rollbackUpdateZone(), or a call to this
  333. /// method within another transaction started by \c startTransaction()
  334. /// will result in a \c DataSourceError exception.
  335. /// If multiple update attempts need to be performed concurrently (and
  336. /// if the underlying database allows such operation), separate
  337. /// \c DatabaseAccessor instance must be created.
  338. ///
  339. /// \note The underlying database may not allow concurrent updates to
  340. /// the same database instance even if different "connections" (or
  341. /// something similar specific to the database implementation) are used
  342. /// for different sets of updates. For example, it doesn't seem to be
  343. /// possible for SQLite3 unless different databases are used. MySQL
  344. /// allows concurrent updates to different tables of the same database,
  345. /// but a specific operation may block others. As such, this interface
  346. /// doesn't require derived classes to allow concurrent updates with
  347. /// multiple \c DatabaseAccessor instances; however, the implementation
  348. /// is encouraged to do the best for making it more likely to succeed
  349. /// as long as the underlying database system allows concurrent updates.
  350. ///
  351. /// This method returns a pair of \c bool and \c int. Its first element
  352. /// indicates whether the given name of zone is found. If it's false,
  353. /// the transaction isn't considered to be started; a subsequent call to
  354. /// this method with an existing zone name should succeed. Likewise,
  355. /// if a call to this method results in an exception, the transaction
  356. /// isn't considered to be started. Note also that if the zone is not
  357. /// found this method doesn't try to create a new one in the database.
  358. /// It must have been created by some other means beforehand.
  359. ///
  360. /// The second element is the internal zone ID used for subsequent
  361. /// updates. Depending on implementation details of the actual derived
  362. /// class method, it may be different from the one returned by
  363. /// \c getZone(); for example, a specific implementation may use a
  364. /// completely new zone ID when \c replace is true.
  365. ///
  366. /// \exception DataSourceError Duplicate call to this method, call to
  367. /// this method within another transaction, or some internal database
  368. /// related error.
  369. ///
  370. /// \param zone_name A string representation of the zone name to be updated
  371. /// \param replace Whether to replace the entire zone (see above)
  372. ///
  373. /// \return A pair of bool and int, indicating whether the specified zone
  374. /// exists and (if so) the zone ID to be used for the update, respectively.
  375. virtual std::pair<bool, int> startUpdateZone(const std::string& zone_name,
  376. bool replace) = 0;
  377. /// Add a single record to the zone to be updated.
  378. ///
  379. /// This method provides a simple interface to insert a new record
  380. /// (a database "row") to the zone in the update context started by
  381. /// \c startUpdateZone(). The zone to which the record to be added
  382. /// is the one specified at the time of the \c startUpdateZone() call.
  383. ///
  384. /// A successful call to \c startUpdateZone() must have preceded to
  385. /// this call; otherwise a \c DataSourceError exception will be thrown.
  386. ///
  387. /// The row is defined as a vector of strings that has exactly
  388. /// ADD_COLUMN_COUNT number of elements. See AddRecordColumns for
  389. /// the semantics of each element.
  390. ///
  391. /// Derived class methods are not required to check whether the given
  392. /// values in \c columns are valid in terms of the expected semantics;
  393. /// in general, it's the caller's responsibility.
  394. /// For example, TTLs would normally be expected to be a textual
  395. /// representation of decimal numbers, but this interface doesn't require
  396. /// the implementation to perform this level of validation. It may check
  397. /// the values, however, and in that case if it detects an error it
  398. /// should throw a \c DataSourceError exception.
  399. ///
  400. /// Likewise, derived class methods are not required to detect any
  401. /// duplicate record that is already in the zone.
  402. ///
  403. /// \note The underlying database schema may not have a trivial mapping
  404. /// from this style of definition of rows to actual database records.
  405. /// It's the implementation's responsibility to implement the mapping
  406. /// in the actual derived method.
  407. ///
  408. /// \exception DataSourceError Invalid call without starting a transaction,
  409. /// or other internal database error.
  410. ///
  411. /// \param columns An array of strings that defines a record to be added
  412. /// to the zone.
  413. virtual void addRecordToZone(
  414. const std::string (&columns)[ADD_COLUMN_COUNT]) = 0;
  415. /// Delete a single record from the zone to be updated.
  416. ///
  417. /// This method provides a simple interface to delete a record
  418. /// (a database "row") from the zone in the update context started by
  419. /// \c startUpdateZone(). The zone from which the record to be deleted
  420. /// is the one specified at the time of the \c startUpdateZone() call.
  421. ///
  422. /// A successful call to \c startUpdateZone() must have preceded to
  423. /// this call; otherwise a \c DataSourceError exception will be thrown.
  424. ///
  425. /// The record to be deleted is specified by a vector of strings that has
  426. /// exactly DEL_PARAM_COUNT number of elements. See DeleteRecordParams
  427. /// for the semantics of each element.
  428. ///
  429. /// \note In IXFR, TTL may also be specified, but we intentionally
  430. /// ignore that in this interface, because it's not guaranteed
  431. /// that all records have the same TTL (unlike the RRset
  432. /// assumption) and there can even be multiple records for the
  433. /// same name, type and rdata with different TTLs. If we only
  434. /// delete one of them, subsequent lookup will still return a
  435. /// positive answer, which would be confusing. It's a higher
  436. /// layer's responsibility to check if there is at least one
  437. /// record in the database that has the given TTL.
  438. ///
  439. /// Like \c addRecordToZone, derived class methods are not required to
  440. /// validate the semantics of the given parameters or to check if there
  441. /// is a record that matches the specified parameter; if there isn't
  442. /// it simply ignores the result.
  443. ///
  444. /// \exception DataSourceError Invalid call without starting a transaction,
  445. /// or other internal database error.
  446. ///
  447. /// \param params An array of strings that defines a record to be deleted
  448. /// from the zone.
  449. virtual void deleteRecordInZone(
  450. const std::string (&params)[DEL_PARAM_COUNT]) = 0;
  451. /// Start a general transaction.
  452. ///
  453. /// Each derived class version of this method starts a database
  454. /// transaction in a way specific to the database details. Any subsequent
  455. /// operations on the accessor are guaranteed to be not susceptible to
  456. /// any update attempts made during the transaction. The transaction
  457. /// must be terminated by either \c commit() or \c rollback().
  458. ///
  459. /// In practice, this transaction is intended to be used to perform
  460. /// a set of atomic reads and work as a read-only lock. So, in many
  461. /// cases \c commit() and \c rollback() will have the same effect.
  462. ///
  463. /// This transaction cannot coexist with an update transaction started
  464. /// by \c startUpdateZone(). Such an attempt will result in
  465. /// \c DataSourceError.
  466. ///
  467. /// \exception DataSourceError An attempt of nested transaction, or some
  468. /// internal database related error.
  469. virtual void startTransaction() = 0;
  470. /// Commit a transaction.
  471. ///
  472. /// This method completes a transaction started by \c startTransaction
  473. /// or \c startUpdateZone.
  474. ///
  475. /// A successful call to one of the "start" methods must have preceded to
  476. /// this call; otherwise a \c DataSourceError exception will be thrown.
  477. /// Once this method successfully completes, the transaction isn't
  478. /// considered to exist any more. So a new transaction can now be
  479. /// started. On the other hand, a duplicate call to this method after
  480. /// a successful completion of it is invalid and should result in
  481. /// a \c DataSourceError exception.
  482. ///
  483. /// If some internal database error happens, a \c DataSourceError
  484. /// exception must be thrown. In that case the transaction is still
  485. /// considered to be valid; the caller must explicitly rollback it
  486. /// or (if it's confident that the error is temporary) try to commit it
  487. /// again.
  488. ///
  489. /// \exception DataSourceError Call without a transaction, duplicate call
  490. /// to the method or internal database error.
  491. virtual void commit() = 0;
  492. /// Rollback any changes in a transaction made so far.
  493. ///
  494. /// This method rollbacks a transaction started by \c startTransaction or
  495. /// \c startUpdateZone. When it succeeds (it normally should, but see
  496. /// below), the underlying database should be reverted to the point
  497. /// before performing the corresponding "start" method.
  498. ///
  499. /// A successful call to one of the "start" method must have preceded to
  500. /// this call; otherwise a \c DataSourceError exception will be thrown.
  501. /// Once this method successfully completes, the transaction isn't
  502. /// considered to exist any more. So a new transaction can now be
  503. /// started. On the other hand, a duplicate call to this method after
  504. /// a successful completion of it is invalid and should result in
  505. /// a \c DataSourceError exception.
  506. ///
  507. /// Normally this method should not fail. But it may not always be
  508. /// possible to guarantee it depending on the characteristics of the
  509. /// underlying database system. So this interface doesn't require the
  510. /// actual implementation for the error free property. But if a specific
  511. /// implementation of this method can fail, it is encouraged to document
  512. /// when that can happen with its implication.
  513. ///
  514. /// \exception DataSourceError Call without a transaction, duplicate call
  515. /// to the method or internal database error.
  516. virtual void rollback() = 0;
  517. /// Install a single RR diff in difference sequences for zone update.
  518. ///
  519. /// This method inserts parameters of an update operation for a single RR
  520. /// (either adding or deleting one) in the underlying database.
  521. /// (These parameters would normally be a separate database table, but
  522. /// actual realization can differ in specific implementations).
  523. /// The information given via this method generally corresponds to either
  524. /// a single call to \c addRecordToZone() or \c deleteRecordInZone(),
  525. /// and this method is expected to be called immediately after (or before)
  526. /// a call to either of those methods.
  527. ///
  528. /// Note, however, that this method passes more detailed information
  529. /// than those update methods: it passes "serial", even if the diff
  530. /// is not for the SOA RR; it passes TTL for a diff that deletes an RR
  531. /// while in \c deleteRecordInZone() it's omitted. This is because
  532. /// the stored diffs are expected to be retrieved in the form that
  533. /// \c getDiffs() is expected to meet. This means if the caller
  534. /// wants to use this method with other update operations, it must
  535. /// ensure the additional information is ready when this method is called.
  536. ///
  537. /// The caller of this method must ensure that the added diffs via
  538. /// this method in a single transaction form an IXFR-style difference
  539. /// sequences: Each difference sequence is a sequence of RRs:
  540. /// an older version of SOA (to be deleted), zero or more other deleted
  541. /// RRs, the post-transaction SOA (to be added), and zero or more other
  542. /// added RRs. So, for example, the first call to this method in a
  543. /// transaction must always be deleting an SOA. Also, the \c serial
  544. /// parameter must be equal to the value of the serial field of the
  545. /// SOA that was last added or deleted (if the call is to add or delete
  546. /// an SOA RR, \c serial must be identical to the serial of that SOA).
  547. /// The underlying derived class implementation may or may not check
  548. /// this condition, but if the caller doesn't meet the condition
  549. /// a subsequent call to \c getDiffs() will not work as expected.
  550. ///
  551. /// Any call to this method must be in a transaction, and, for now,
  552. /// it must be a transaction triggered by \c startUpdateZone() (that is,
  553. /// it cannot be a transaction started by \c startTransaction()).
  554. /// All calls to this method are considered to be part of an atomic
  555. /// transaction: Until \c commit() is performed, the added diffs are
  556. /// not visible outside the transaction; if \c rollback() is performed,
  557. /// all added diffs are canceled; and the added sequences are not
  558. /// affected by any concurrent attempt of adding diffs (conflict resolution
  559. /// is up to the database implementation).
  560. ///
  561. /// Also for now, all diffs are assumed to be for the zone that is
  562. /// being updated in the context of \c startUpdateZone(). So the
  563. /// \c zone_id parameter must be identical to the zone ID returned by
  564. /// \c startUpdateZone().
  565. ///
  566. /// In a future version we may loosen this condition so that diffs can be
  567. /// added in a generic transaction and may not even have to belong to
  568. /// a single zone. For this possible extension \c zone_id parameter is
  569. /// included even if it's redundant under the current restriction.
  570. ///
  571. /// The support for adding (or retrieving) diffs is optional; if it's
  572. /// not supported in a specific data source, this method for the
  573. /// corresponding derived class will throw an \c NotImplemented exception.
  574. ///
  575. /// \exception DataSourceError Invalid call without starting a transaction,
  576. /// zone ID doesn't match the zone being updated, or other internal
  577. /// database error.
  578. /// \exception NotImplemented Adding diffs is not supported in the
  579. /// data source.
  580. /// \exception Other The concrete derived method may throw other
  581. /// data source specific exceptions.
  582. ///
  583. /// \param zone_id The zone for the diff to be added.
  584. /// \param serial The SOA serial to which the diff belongs.
  585. /// \param operation Either \c DIFF_ADD or \c DIFF_DELETE.
  586. /// \param params An array of strings that defines a record for the diff.
  587. virtual void addRecordDiff(
  588. int zone_id, uint32_t serial, DiffOperation operation,
  589. const std::string (&params)[DIFF_PARAM_COUNT]) = 0;
  590. /// Clone the accessor with the same configuration.
  591. ///
  592. /// Each derived class implementation of this method will create a new
  593. /// accessor of the same derived class with the same configuration
  594. /// (such as the database server address) as that of the caller object
  595. /// and return it.
  596. ///
  597. /// Note that other internal states won't be copied to the new accessor
  598. /// even though the name of "clone" may indicate so. For example, even
  599. /// if the calling accessor is in the middle of a update transaction,
  600. /// the new accessor will not start a transaction to trace the same
  601. /// updates.
  602. ///
  603. /// The intended use case of cloning is to create a separate context
  604. /// where a specific set of database operations can be performed
  605. /// independently from the original accessor. The updater will use it
  606. /// so that multiple updaters can be created concurrently even if the
  607. /// underlying database system doesn't allow running multiple transactions
  608. /// in a single database connection.
  609. ///
  610. /// The underlying database system may not support the functionality
  611. /// that would be needed to implement this method. For example, it
  612. /// may not allow a single thread (or process) to have more than one
  613. /// database connections. In such a case the derived class implementation
  614. /// should throw a \c DataSourceError exception.
  615. ///
  616. /// \return A shared pointer to the cloned accessor.
  617. virtual boost::shared_ptr<DatabaseAccessor> clone() = 0;
  618. /**
  619. * \brief Returns a string identifying this dabase backend
  620. *
  621. * The returned string is mainly intended to be used for
  622. * debugging/logging purposes.
  623. *
  624. * Any implementation is free to choose the exact string content,
  625. * but it is advisable to make it a name that is distinguishable
  626. * from the others.
  627. *
  628. * \return the name of the database
  629. */
  630. virtual const std::string& getDBName() const = 0;
  631. /**
  632. * \brief It returns the previous name in DNSSEC order.
  633. *
  634. * This is used in DatabaseClient::findPreviousName and does more
  635. * or less the real work, except for working on strings.
  636. *
  637. * \param rname The name to ask for previous of, in reversed form.
  638. * We use the reversed form (see isc::dns::Name::reverse),
  639. * because then the case insensitive order of string representation
  640. * and the DNSSEC order correspond (eg. org.example.a is followed
  641. * by org.example.a.b which is followed by org.example.b, etc).
  642. * \param zone_id The zone to look through.
  643. * \return The previous name.
  644. * \note This function must return previous name even in case
  645. * the queried rname does not exist in the zone.
  646. * \note This method must skip under-the-zone-cut data (glue data).
  647. * This might be implemented by looking for NSEC records (as glue
  648. * data don't have them) in the zone or in some other way.
  649. *
  650. * \throw DataSourceError if there's a problem with the database.
  651. * \throw NotImplemented if this database doesn't support DNSSEC
  652. * or there's no previous name for the queried one (the NSECs
  653. * might be missing or the queried name is less or equal the
  654. * apex of the zone).
  655. */
  656. virtual std::string findPreviousName(int zone_id,
  657. const std::string& rname) const = 0;
  658. };
  659. /**
  660. * \brief Concrete data source client oriented at database backends.
  661. *
  662. * This class (together with corresponding versions of ZoneFinder,
  663. * ZoneIterator, etc.) translates high-level data source queries to
  664. * low-level calls on DatabaseAccessor. It calls multiple queries
  665. * if necessary and validates data from the database, allowing the
  666. * DatabaseAccessor to be just simple translation to SQL/other
  667. * queries to database.
  668. *
  669. * While it is possible to subclass it for specific database in case
  670. * of special needs, it is not expected to be needed. This should just
  671. * work as it is with whatever DatabaseAccessor.
  672. */
  673. class DatabaseClient : public DataSourceClient {
  674. public:
  675. /**
  676. * \brief Constructor
  677. *
  678. * It initializes the client with a database via the given accessor.
  679. *
  680. * \exception isc::InvalidParameter if accessor is NULL. It might throw
  681. * standard allocation exception as well, but doesn't throw anything else.
  682. *
  683. * \param rrclass The RR class of the zones that this client will handle.
  684. * \param accessor The accessor to the database to use to get data.
  685. * As the parameter suggests, the client takes ownership of the accessor
  686. * and will delete it when itself deleted.
  687. */
  688. DatabaseClient(isc::dns::RRClass rrclass,
  689. boost::shared_ptr<DatabaseAccessor> accessor);
  690. /**
  691. * \brief Corresponding ZoneFinder implementation
  692. *
  693. * The zone finder implementation for database data sources. Similarly
  694. * to the DatabaseClient, it translates the queries to methods of the
  695. * database.
  696. *
  697. * Application should not come directly in contact with this class
  698. * (it should handle it trough generic ZoneFinder pointer), therefore
  699. * it could be completely hidden in the .cc file. But it is provided
  700. * to allow testing and for rare cases when a database needs slightly
  701. * different handling, so it can be subclassed.
  702. *
  703. * Methods directly corresponds to the ones in ZoneFinder.
  704. */
  705. class Finder : public ZoneFinder {
  706. public:
  707. /**
  708. * \brief Constructor
  709. *
  710. * \param database The database (shared with DatabaseClient) to
  711. * be used for queries (the one asked for ID before).
  712. * \param zone_id The zone ID which was returned from
  713. * DatabaseAccessor::getZone and which will be passed to further
  714. * calls to the database.
  715. * \param origin The name of the origin of this zone. It could query
  716. * it from database, but as the DatabaseClient just searched for
  717. * the zone using the name, it should have it.
  718. */
  719. Finder(boost::shared_ptr<DatabaseAccessor> database, int zone_id,
  720. const isc::dns::Name& origin);
  721. // The following three methods are just implementations of inherited
  722. // ZoneFinder's pure virtual methods.
  723. virtual isc::dns::Name getOrigin() const;
  724. virtual isc::dns::RRClass getClass() const;
  725. /**
  726. * \brief Find an RRset in the datasource
  727. *
  728. * Searches the datasource for an RRset of the given name and
  729. * type. If there is a CNAME at the given name, the CNAME rrset
  730. * is returned.
  731. * (this implementation is not complete, and currently only
  732. * does full matches, CNAMES, and the signatures for matches and
  733. * CNAMEs)
  734. * \note target was used in the original design to handle ANY
  735. * queries. This is not implemented yet, and may use
  736. * target again for that, but it might also use something
  737. * different. It is left in for compatibility at the moment.
  738. * \note options are ignored at this moment
  739. *
  740. * \note Maybe counter intuitively, this method is not a const member
  741. * function. This is intentional; some of the underlying implementations
  742. * are expected to use a database backend, and would internally contain
  743. * some abstraction of "database connection". In the most strict sense
  744. * any (even read only) operation might change the internal state of
  745. * such a connection, and in that sense the operation cannot be considered
  746. * "const". In order to avoid giving a false sense of safety to the
  747. * caller, we indicate a call to this method may have a surprising
  748. * side effect. That said, this view may be too strict and it may
  749. * make sense to say the internal database connection doesn't affect
  750. * external behavior in terms of the interface of this method. As
  751. * we gain more experiences with various kinds of backends we may
  752. * revisit the constness.
  753. *
  754. * \exception DataSourceError when there is a problem reading
  755. * the data from the dabase backend.
  756. * This can be a connection, code, or
  757. * data (parse) error.
  758. *
  759. * \param name The name to find
  760. * \param type The RRType to find
  761. * \param target Unused at this moment
  762. * \param options Options about how to search.
  763. * See ZoneFinder::FindOptions.
  764. */
  765. virtual FindResult find(const isc::dns::Name& name,
  766. const isc::dns::RRType& type,
  767. isc::dns::RRsetList* target = NULL,
  768. const FindOptions options = FIND_DEFAULT);
  769. /**
  770. * \brief Implementation of ZoneFinder::findPreviousName method.
  771. */
  772. virtual isc::dns::Name findPreviousName(const isc::dns::Name& query)
  773. const;
  774. /**
  775. * \brief The zone ID
  776. *
  777. * This function provides the stored zone ID as passed to the
  778. * constructor. This is meant for testing purposes and normal
  779. * applications shouldn't need it.
  780. */
  781. int zone_id() const { return (zone_id_); }
  782. /**
  783. * \brief The database accessor.
  784. *
  785. * This function provides the database accessor stored inside as
  786. * passed to the constructor. This is meant for testing purposes and
  787. * normal applications shouldn't need it.
  788. */
  789. const DatabaseAccessor& getAccessor() const {
  790. return (*accessor_);
  791. }
  792. private:
  793. boost::shared_ptr<DatabaseAccessor> accessor_;
  794. const int zone_id_;
  795. const isc::dns::Name origin_;
  796. //
  797. /// \brief Shortcut name for the result of getRRsets
  798. typedef std::pair<bool, std::map<dns::RRType, dns::RRsetPtr> >
  799. FoundRRsets;
  800. /// \brief Just shortcut for set of types
  801. typedef std::set<dns::RRType> WantedTypes;
  802. /**
  803. * \brief Searches database for RRsets of one domain.
  804. *
  805. * This method scans RRs of single domain specified by name and
  806. * extracts any RRsets found and requested by parameters.
  807. *
  808. * It is used internally by find(), because it is called multiple
  809. * times (usually with different domains).
  810. *
  811. * \param name Which domain name should be scanned.
  812. * \param types List of types the caller is interested in.
  813. * \param check_ns If this is set to true, it checks nothing lives
  814. * together with NS record (with few little exceptions, like RRSIG
  815. * or NSEC). This check is meant for non-apex NS records.
  816. * \param construct_name If this is NULL, the resulting RRsets have
  817. * their name set to name. If it is not NULL, it overrides the name
  818. * and uses this one (this can be used for wildcard synthesized
  819. * records).
  820. * \return A pair, where the first element indicates if the domain
  821. * contains any RRs at all (not only the requested, it may happen
  822. * this is set to true, but the second part is empty). The second
  823. * part is map from RRtypes to RRsets of the corresponding types.
  824. * If the RRset is not present in DB, the RRtype is not there at
  825. * all (so you'll not find NULL pointer in the result).
  826. * \throw DataSourceError If there's a low-level error with the
  827. * database or the database contains bad data.
  828. */
  829. FoundRRsets getRRsets(const std::string& name,
  830. const WantedTypes& types, bool check_ns,
  831. const std::string* construct_name = NULL);
  832. /**
  833. * \brief Checks if something lives below this domain.
  834. *
  835. * This looks if there's any subdomain of the given name. It can be
  836. * used to test if domain is empty non-terminal.
  837. *
  838. * \param name The domain to check.
  839. */
  840. bool hasSubdomains(const std::string& name);
  841. /**
  842. * \brief Get the NSEC covering a name.
  843. *
  844. * This one calls findPreviousName on the given name and extracts an NSEC
  845. * record on the result. It handles various error cases. The method exists
  846. * to share code present at more than one location.
  847. */
  848. dns::RRsetPtr findNSECCover(const dns::Name& name);
  849. /**
  850. * \brief Convenience type shortcut.
  851. *
  852. * To find stuff in the result of getRRsets.
  853. */
  854. typedef std::map<dns::RRType, dns::RRsetPtr>::const_iterator
  855. FoundIterator;
  856. };
  857. /**
  858. * \brief Find a zone in the database
  859. *
  860. * This queries database's getZone to find the best matching zone.
  861. * It will propagate whatever exceptions are thrown from that method
  862. * (which is not restricted in any way).
  863. *
  864. * \param name Name of the zone or data contained there.
  865. * \return FindResult containing the code and an instance of Finder, if
  866. * anything is found. However, application should not rely on the
  867. * ZoneFinder being instance of Finder (possible subclass of this class
  868. * may return something else and it may change in future versions), it
  869. * should use it as a ZoneFinder only.
  870. */
  871. virtual FindResult findZone(const isc::dns::Name& name) const;
  872. /**
  873. * \brief Get the zone iterator
  874. *
  875. * The iterator allows going through the whole zone content. If the
  876. * underlying DatabaseConnection is implemented correctly, it should
  877. * be possible to have multiple ZoneIterators at once and query data
  878. * at the same time.
  879. *
  880. * \exception DataSourceError if the zone doesn't exist.
  881. * \exception isc::NotImplemented if the underlying DatabaseConnection
  882. * doesn't implement iteration. But in case it is not implemented
  883. * and the zone doesn't exist, DataSourceError is thrown.
  884. * \exception Anything else the underlying DatabaseConnection might
  885. * want to throw.
  886. * \param name The origin of the zone to iterate.
  887. * \param adjust_ttl If true, the iterator will treat RRs with the same
  888. * name and type but different TTL values to be of the
  889. * same RRset, and will adjust the TTL to the lowest
  890. * value found. If false, it will consider the RR to
  891. * belong to a different RRset.
  892. * \return Shared pointer to the iterator (it will never be NULL)
  893. */
  894. virtual ZoneIteratorPtr getIterator(const isc::dns::Name& name,
  895. bool adjust_ttl = true) const;
  896. /// This implementation internally clones the accessor from the one
  897. /// used in the client and starts a separate transaction using the cloned
  898. /// accessor. The returned updater will be able to work separately from
  899. /// the original client.
  900. virtual ZoneUpdaterPtr getUpdater(const isc::dns::Name& name,
  901. bool replace,
  902. bool journaling = false) const;
  903. /// This implementation internally clones the accessor from the one
  904. /// used in the client for retrieving diffs and iterating over them.
  905. /// The returned reader object will be able to work separately from
  906. /// the original client.
  907. virtual std::pair<ZoneJournalReader::Result, ZoneJournalReaderPtr>
  908. getJournalReader(const isc::dns::Name& zone, uint32_t begin_serial,
  909. uint32_t end_serial) const;
  910. private:
  911. /// \brief The RR class that this client handles.
  912. const isc::dns::RRClass rrclass_;
  913. /// \brief The accessor to our database.
  914. const boost::shared_ptr<DatabaseAccessor> accessor_;
  915. };
  916. }
  917. }
  918. #endif // __DATABASE_DATASRC_H
  919. // Local Variables:
  920. // mode: c++
  921. // End: