database.h 42 KB

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