database.h 45 KB

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