database.h 44 KB

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