database.h 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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 <datasrc/client.h>
  17. #include <dns/name.h>
  18. #include <exceptions/exceptions.h>
  19. namespace isc {
  20. namespace datasrc {
  21. /**
  22. * \brief Abstraction of lowlevel database with DNS data
  23. *
  24. * This class is defines interface to databases. Each supported database
  25. * will provide methods for accessing the data stored there in a generic
  26. * manner. The methods are meant to be low-level, without much or any knowledge
  27. * about DNS and should be possible to translate directly to queries.
  28. *
  29. * On the other hand, how the communication with database is done and in what
  30. * schema (in case of relational/SQL database) is up to the concrete classes.
  31. *
  32. * This class is non-copyable, as copying connections to database makes little
  33. * sense and will not be needed.
  34. *
  35. * \todo Is it true this does not need to be copied? For example the zone
  36. * iterator might need it's own copy. But a virtual clone() method might
  37. * be better for that than copy constructor.
  38. *
  39. * \note The same application may create multiple connections to the same
  40. * database, having multiple instances of this class. If the database
  41. * allows having multiple open queries at one connection, the connection
  42. * class may share it.
  43. */
  44. class DatabaseAccessor : boost::noncopyable {
  45. public:
  46. /**
  47. * \brief Destructor
  48. *
  49. * It is empty, but needs a virtual one, since we will use the derived
  50. * classes in polymorphic way.
  51. */
  52. virtual ~DatabaseAccessor() { }
  53. /**
  54. * \brief Retrieve a zone identifier
  55. *
  56. * This method looks up a zone for the given name in the database. It
  57. * should match only exact zone name (eg. name is equal to the zone's
  58. * apex), as the DatabaseClient will loop trough the labels itself and
  59. * find the most suitable zone.
  60. *
  61. * It is not specified if and what implementation of this method may throw,
  62. * so code should expect anything.
  63. *
  64. * \param name The name of the zone's apex to be looked up.
  65. * \return The first part of the result indicates if a matching zone
  66. * was found. In case it was, the second part is internal zone ID.
  67. * This one will be passed to methods finding data in the zone.
  68. * It is not required to keep them, in which case whatever might
  69. * be returned - the ID is only passed back to the database as
  70. * an opaque handle.
  71. */
  72. virtual std::pair<bool, int> getZone(const isc::dns::Name& name) const = 0;
  73. /**
  74. * \brief This holds the internal context of ZoneIterator for databases
  75. *
  76. * While the ZoneIterator implementation from DatabaseClient does all the
  77. * translation from strings to DNS classes and validation, this class
  78. * holds the pointer to where the database is at reading the data.
  79. *
  80. * It can either hold shared pointer to the connection which created it
  81. * and have some kind of statement inside (in case single database
  82. * connection can handle multiple concurrent SQL statements) or it can
  83. * create a new connection (or, if it is more convenient, the connection
  84. * itself can inherit both from DatabaseConnection and IteratorContext
  85. * and just clone itself).
  86. */
  87. class IteratorContext : public boost::noncopyable {
  88. public:
  89. /**
  90. * \brief Destructor
  91. *
  92. * Virtual destructor, so any descendand class is destroyed correctly.
  93. */
  94. virtual ~IteratorContext() { }
  95. /**
  96. * \brief Function to provide next resource record
  97. *
  98. * This function should provide data about the next resource record
  99. * from the iterated zone. The data are not converted yet.
  100. *
  101. * \note The order of RRs is not strictly set, but the RRs for single
  102. * RRset must not be interleaved with any other RRs (eg. RRsets must be
  103. * "together").
  104. *
  105. * \param columns The data will be returned through here. The order
  106. * is specified by the RecordColumns enum.
  107. * \param Size of the columns array. Must be equal to COLUMN_COUNT,
  108. * otherwise DataSourceError is thrown.
  109. * \todo Do we consider databases where it is stored in binary blob
  110. * format?
  111. * \throw DataSourceError if there's database-related error. If the
  112. * exception (or any other in case of derived class) is thrown,
  113. * the iterator can't be safely used any more.
  114. */
  115. virtual bool getNext(std::string columns[], size_t column_data) = 0;
  116. };
  117. typedef boost::shared_ptr<IteratorContext> IteratorContextPtr;
  118. /**
  119. * \brief Creates an iterator context for the whole zone.
  120. *
  121. * This should create a new iterator context to be used by
  122. * DatabaseConnection's ZoneIterator. It can be created based on the name
  123. * or the ID (returned from getZone()), what is more comfortable for the
  124. * database implementation. Both are provided (and are guaranteed to match,
  125. * the DatabaseClient first looks up the zone ID and then calls this).
  126. *
  127. * The default implementation throws isc::NotImplemented, to allow
  128. * "minimal" implementations of the connection not supporting optional
  129. * functionality.
  130. *
  131. * \param name The name of the zone.
  132. * \param id The ID of the zone, returned from getZone().
  133. * \return Newly created iterator context. Must not be NULL.
  134. */
  135. virtual IteratorContextPtr getAllRecords(const isc::dns::Name& name,
  136. int id) const
  137. {
  138. /*
  139. * This is a compromise. We need to document the parameters in doxygen,
  140. * so they need a name, but then it complains about unused parameter.
  141. * This is a NOP that "uses" the parameters.
  142. */
  143. static_cast<void>(name);
  144. static_cast<void>(id);
  145. isc_throw(isc::NotImplemented,
  146. "This database datasource can't be iterated");
  147. }
  148. /**
  149. * \brief Starts a new search for records of the given name in the given zone
  150. *
  151. * The data searched by this call can be retrieved with subsequent calls to
  152. * getNextRecord().
  153. *
  154. * \exception DataSourceError if there is a problem connecting to the
  155. * backend database
  156. *
  157. * \param zone_id The zone to search in, as returned by getZone()
  158. * \param name The name of the records to find
  159. */
  160. virtual void searchForRecords(int zone_id, const std::string& name) = 0;
  161. /**
  162. * \brief Retrieves the next record from the search started with searchForRecords()
  163. *
  164. * Returns a boolean specifying whether or not there was more data to read.
  165. * In the case of a database error, a DatasourceError is thrown.
  166. *
  167. * The columns passed is an array of std::strings consisting of
  168. * DatabaseConnection::COLUMN_COUNT elements, the elements of which
  169. * are defined in DatabaseConnection::RecordColumns, in their basic
  170. * string representation.
  171. *
  172. * If you are implementing a derived database connection class, you
  173. * should have this method check the column_count value, and fill the
  174. * array with strings conforming to their description in RecordColumn.
  175. *
  176. * \exception DatasourceError if there was an error reading from the database
  177. *
  178. * \param columns The elements of this array will be filled with the data
  179. * for one record as defined by RecordColumns
  180. * If there was no data, the array is untouched.
  181. * \return true if there was a next record, false if there was not
  182. */
  183. virtual bool getNextRecord(std::string columns[], size_t column_count) = 0;
  184. /**
  185. * \brief Resets the current search initiated with searchForRecords()
  186. *
  187. * This method will be called when the called of searchForRecords() and
  188. * getNextRecord() finds bad data, and aborts the current search.
  189. * It should clean up whatever handlers searchForRecords() created, and
  190. * any other state modified or needed by getNextRecord()
  191. *
  192. * Of course, the implementation of getNextRecord may also use it when
  193. * it is done with a search. If it does, the implementation of this
  194. * method should make sure it can handle being called multiple times.
  195. *
  196. * The implementation for this method should make sure it never throws.
  197. */
  198. virtual void resetSearch() = 0;
  199. /**
  200. * Definitions of the fields as they are required to be filled in
  201. * by getNextRecord()
  202. *
  203. * When implementing getNextRecord(), the columns array should
  204. * be filled with the values as described in this enumeration,
  205. * in this order, i.e. TYPE_COLUMN should be the first element
  206. * (index 0) of the array, TTL_COLUMN should be the second element
  207. * (index 1), etc.
  208. */
  209. enum RecordColumns {
  210. TYPE_COLUMN = 0, ///< The RRType of the record (A/NS/TXT etc.)
  211. TTL_COLUMN = 1, ///< The TTL of the record (a
  212. SIGTYPE_COLUMN = 2, ///< For RRSIG records, this contains the RRTYPE
  213. ///< the RRSIG covers. In the current implementation,
  214. ///< this field is ignored.
  215. RDATA_COLUMN = 3, ///< Full text representation of the record's RDATA
  216. NAME_COLUMN = 4 ///< The domain name of this RR
  217. };
  218. /// The number of fields the columns array passed to getNextRecord should have
  219. static const size_t COLUMN_COUNT = 5;
  220. /**
  221. * \brief Returns a string identifying this dabase backend
  222. *
  223. * The returned string is mainly intended to be used for
  224. * debugging/logging purposes.
  225. *
  226. * Any implementation is free to choose the exact string content,
  227. * but it is advisable to make it a name that is distinguishable
  228. * from the others.
  229. *
  230. * \return the name of the database
  231. */
  232. virtual const std::string& getDBName() const = 0;
  233. };
  234. /**
  235. * \brief Concrete data source client oriented at database backends.
  236. *
  237. * This class (together with corresponding versions of ZoneFinder,
  238. * ZoneIterator, etc.) translates high-level data source queries to
  239. * low-level calls on DatabaseAccessor. It calls multiple queries
  240. * if necessary and validates data from the database, allowing the
  241. * DatabaseAccessor to be just simple translation to SQL/other
  242. * queries to database.
  243. *
  244. * While it is possible to subclass it for specific database in case
  245. * of special needs, it is not expected to be needed. This should just
  246. * work as it is with whatever DatabaseAccessor.
  247. */
  248. class DatabaseClient : public DataSourceClient {
  249. public:
  250. /**
  251. * \brief Constructor
  252. *
  253. * It initializes the client with a database.
  254. *
  255. * \exception isc::InvalidParameter if database is NULL. It might throw
  256. * standard allocation exception as well, but doesn't throw anything else.
  257. *
  258. * \param database The database to use to get data. As the parameter
  259. * suggests, the client takes ownership of the database and will
  260. * delete it when itself deleted.
  261. */
  262. DatabaseClient(boost::shared_ptr<DatabaseAccessor> database);
  263. /**
  264. * \brief Corresponding ZoneFinder implementation
  265. *
  266. * The zone finder implementation for database data sources. Similarly
  267. * to the DatabaseClient, it translates the queries to methods of the
  268. * database.
  269. *
  270. * Application should not come directly in contact with this class
  271. * (it should handle it trough generic ZoneFinder pointer), therefore
  272. * it could be completely hidden in the .cc file. But it is provided
  273. * to allow testing and for rare cases when a database needs slightly
  274. * different handling, so it can be subclassed.
  275. *
  276. * Methods directly corresponds to the ones in ZoneFinder.
  277. */
  278. class Finder : public ZoneFinder {
  279. public:
  280. /**
  281. * \brief Constructor
  282. *
  283. * \param database The database (shared with DatabaseClient) to
  284. * be used for queries (the one asked for ID before).
  285. * \param zone_id The zone ID which was returned from
  286. * DatabaseAccessor::getZone and which will be passed to further
  287. * calls to the database.
  288. * \param origin The name of the origin of this zone. It could query
  289. * it from database, but as the DatabaseClient just searched for
  290. * the zone using the name, it should have it.
  291. */
  292. Finder(boost::shared_ptr<DatabaseAccessor> database, int zone_id,
  293. const isc::dns::Name& origin);
  294. // The following three methods are just implementations of inherited
  295. // ZoneFinder's pure virtual methods.
  296. virtual isc::dns::Name getOrigin() const;
  297. virtual isc::dns::RRClass getClass() const;
  298. /**
  299. * \brief Find an RRset in the datasource
  300. *
  301. * Searches the datasource for an RRset of the given name and
  302. * type. If there is a CNAME at the given name, the CNAME rrset
  303. * is returned.
  304. * (this implementation is not complete, and currently only
  305. * does full matches, CNAMES, and the signatures for matches and
  306. * CNAMEs)
  307. * \note target was used in the original design to handle ANY
  308. * queries. This is not implemented yet, and may use
  309. * target again for that, but it might also use something
  310. * different. It is left in for compatibility at the moment.
  311. * \note options are ignored at this moment
  312. *
  313. * \note Maybe counter intuitively, this method is not a const member
  314. * function. This is intentional; some of the underlying implementations
  315. * are expected to use a database backend, and would internally contain
  316. * some abstraction of "database connection". In the most strict sense
  317. * any (even read only) operation might change the internal state of
  318. * such a connection, and in that sense the operation cannot be considered
  319. * "const". In order to avoid giving a false sense of safety to the
  320. * caller, we indicate a call to this method may have a surprising
  321. * side effect. That said, this view may be too strict and it may
  322. * make sense to say the internal database connection doesn't affect
  323. * external behavior in terms of the interface of this method. As
  324. * we gain more experiences with various kinds of backends we may
  325. * revisit the constness.
  326. *
  327. * \exception DataSourceError when there is a problem reading
  328. * the data from the dabase backend.
  329. * This can be a connection, code, or
  330. * data (parse) error.
  331. *
  332. * \param name The name to find
  333. * \param type The RRType to find
  334. * \param target Unused at this moment
  335. * \param options Options about how to search.
  336. * See ZoneFinder::FindOptions.
  337. */
  338. virtual FindResult find(const isc::dns::Name& name,
  339. const isc::dns::RRType& type,
  340. isc::dns::RRsetList* target = NULL,
  341. const FindOptions options = FIND_DEFAULT);
  342. /**
  343. * \brief The zone ID
  344. *
  345. * This function provides the stored zone ID as passed to the
  346. * constructor. This is meant for testing purposes and normal
  347. * applications shouldn't need it.
  348. */
  349. int zone_id() const { return (zone_id_); }
  350. /**
  351. * \brief The database.
  352. *
  353. * This function provides the database stored inside as
  354. * passed to the constructor. This is meant for testing purposes and
  355. * normal applications shouldn't need it.
  356. */
  357. const DatabaseAccessor& database() const {
  358. return (*database_);
  359. }
  360. private:
  361. boost::shared_ptr<DatabaseAccessor> database_;
  362. const int zone_id_;
  363. const isc::dns::Name origin_;
  364. /**
  365. * \brief Searches database for an RRset
  366. *
  367. * This method scans RRs of single domain specified by name and finds
  368. * RRset with given type or any of redirection RRsets that are
  369. * requested.
  370. *
  371. * This function is used internally by find(), because this part is
  372. * called multiple times with slightly different parameters.
  373. *
  374. * \param name Which domain name should be scanned.
  375. * \param type The RRType which is requested. This can be NULL, in
  376. * which case the method will look for the redirections only.
  377. * \param want_cname If this is true, CNAME redirection may be returned
  378. * instead of the RRset with given type. If there's CNAME and
  379. * something else or the CNAME has multiple RRs, it throws
  380. * DataSourceError.
  381. * \param want_dname If this is true, DNAME redirection may be returned
  382. * instead. This is with type = NULL only and is not checked in
  383. * other circumstances. If the DNAME has multiple RRs, it throws
  384. * DataSourceError.
  385. * \param want_ns This allows redirection by NS to be returned. If
  386. * any other data is met as well, DataSourceError is thrown.
  387. * \note It may happen that some of the above error conditions are not
  388. * detected in some circumstances. The goal here is not to validate
  389. * the domain in DB, but to avoid bad behaviour resulting from
  390. * broken data.
  391. * \return First part of the result tells if the domain contains any
  392. * RRs. This can be used to decide between NXDOMAIN and NXRRSET.
  393. * The second part is the RRset found (if any) with any relevant
  394. * signatures attached to it.
  395. * \todo This interface doesn't look very elegant. Any better idea
  396. * would be nice.
  397. */
  398. std::pair<bool, isc::dns::RRsetPtr> getRRset(const isc::dns::Name&
  399. name,
  400. const isc::dns::RRType*
  401. type,
  402. bool want_cname,
  403. bool want_dname,
  404. bool want_ns);
  405. };
  406. /**
  407. * \brief Find a zone in the database
  408. *
  409. * This queries database's getZone to find the best matching zone.
  410. * It will propagate whatever exceptions are thrown from that method
  411. * (which is not restricted in any way).
  412. *
  413. * \param name Name of the zone or data contained there.
  414. * \return FindResult containing the code and an instance of Finder, if
  415. * anything is found. However, application should not rely on the
  416. * ZoneFinder being instance of Finder (possible subclass of this class
  417. * may return something else and it may change in future versions), it
  418. * should use it as a ZoneFinder only.
  419. */
  420. virtual FindResult findZone(const isc::dns::Name& name) const;
  421. /**
  422. * \brief Get the zone iterator
  423. *
  424. * The iterator allows going through the whole zone content. If the
  425. * underlying DatabaseConnection is implemented correctly, it should
  426. * be possible to have multiple ZoneIterators at once and query data
  427. * at the same time.
  428. *
  429. * \exception DataSourceError if the zone doesn't exist.
  430. * \exception isc::NotImplemented if the underlying DatabaseConnection
  431. * doesn't implement iteration. But in case it is not implemented
  432. * and the zone doesn't exist, DataSourceError is thrown.
  433. * \exception Anything else the underlying DatabaseConnection might
  434. * want to throw.
  435. * \param name The origin of the zone to iterate.
  436. * \return Shared pointer to the iterator (it will never be NULL)
  437. */
  438. virtual ZoneIteratorPtr getIterator(const isc::dns::Name& name) const;
  439. private:
  440. /// \brief Our database.
  441. const boost::shared_ptr<DatabaseAccessor> database_;
  442. };
  443. }
  444. }
  445. #endif