database.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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 a specific name.
  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 to search for.
  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 getRecords(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 Creates an iterator context for the whole zone.
  150. *
  151. * This should create a new iterator context to be used by
  152. * DatabaseConnection's ZoneIterator. It can be created based on the name
  153. * or the ID (returned from getZone()), what is more comfortable for the
  154. * database implementation. Both are provided (and are guaranteed to match,
  155. * the DatabaseClient first looks up the zone ID and then calls this).
  156. *
  157. * The default implementation throws isc::NotImplemented, to allow
  158. * "minimal" implementations of the connection not supporting optional
  159. * functionality.
  160. *
  161. * \param name The name of the zone.
  162. * \param id The ID of the zone, returned from getZone().
  163. * \return Newly created iterator context. Must not be NULL.
  164. */
  165. virtual IteratorContextPtr getAllRecords(int id) const
  166. {
  167. /*
  168. * This is a compromise. We need to document the parameters in doxygen,
  169. * so they need a name, but then it complains about unused parameter.
  170. * This is a NOP that "uses" the parameters.
  171. */
  172. static_cast<void>(id);
  173. isc_throw(isc::NotImplemented,
  174. "This database datasource can't be iterated");
  175. }
  176. /**
  177. * Definitions of the fields as they are required to be filled in
  178. * by getNextRecord()
  179. *
  180. * When implementing getNextRecord(), the columns array should
  181. * be filled with the values as described in this enumeration,
  182. * in this order, i.e. TYPE_COLUMN should be the first element
  183. * (index 0) of the array, TTL_COLUMN should be the second element
  184. * (index 1), etc.
  185. */
  186. enum RecordColumns {
  187. TYPE_COLUMN = 0, ///< The RRType of the record (A/NS/TXT etc.)
  188. TTL_COLUMN = 1, ///< The TTL of the record (a
  189. SIGTYPE_COLUMN = 2, ///< For RRSIG records, this contains the RRTYPE
  190. ///< the RRSIG covers. In the current implementation,
  191. ///< this field is ignored.
  192. RDATA_COLUMN = 3, ///< Full text representation of the record's RDATA
  193. NAME_COLUMN = 4 ///< The domain name of this RR
  194. };
  195. /// The number of fields the columns array passed to getNextRecord should have
  196. static const size_t COLUMN_COUNT = 5;
  197. /**
  198. * \brief Returns a string identifying this dabase backend
  199. *
  200. * The returned string is mainly intended to be used for
  201. * debugging/logging purposes.
  202. *
  203. * Any implementation is free to choose the exact string content,
  204. * but it is advisable to make it a name that is distinguishable
  205. * from the others.
  206. *
  207. * \return the name of the database
  208. */
  209. virtual const std::string& getDBName() const = 0;
  210. };
  211. /**
  212. * \brief Concrete data source client oriented at database backends.
  213. *
  214. * This class (together with corresponding versions of ZoneFinder,
  215. * ZoneIterator, etc.) translates high-level data source queries to
  216. * low-level calls on DatabaseAccessor. It calls multiple queries
  217. * if necessary and validates data from the database, allowing the
  218. * DatabaseAccessor to be just simple translation to SQL/other
  219. * queries to database.
  220. *
  221. * While it is possible to subclass it for specific database in case
  222. * of special needs, it is not expected to be needed. This should just
  223. * work as it is with whatever DatabaseAccessor.
  224. */
  225. class DatabaseClient : public DataSourceClient {
  226. public:
  227. /**
  228. * \brief Constructor
  229. *
  230. * It initializes the client with a database.
  231. *
  232. * \exception isc::InvalidParameter if database is NULL. It might throw
  233. * standard allocation exception as well, but doesn't throw anything else.
  234. *
  235. * \param database The database to use to get data. As the parameter
  236. * suggests, the client takes ownership of the database and will
  237. * delete it when itself deleted.
  238. */
  239. DatabaseClient(boost::shared_ptr<DatabaseAccessor> database);
  240. /**
  241. * \brief Corresponding ZoneFinder implementation
  242. *
  243. * The zone finder implementation for database data sources. Similarly
  244. * to the DatabaseClient, it translates the queries to methods of the
  245. * database.
  246. *
  247. * Application should not come directly in contact with this class
  248. * (it should handle it trough generic ZoneFinder pointer), therefore
  249. * it could be completely hidden in the .cc file. But it is provided
  250. * to allow testing and for rare cases when a database needs slightly
  251. * different handling, so it can be subclassed.
  252. *
  253. * Methods directly corresponds to the ones in ZoneFinder.
  254. */
  255. class Finder : public ZoneFinder {
  256. public:
  257. /**
  258. * \brief Constructor
  259. *
  260. * \param database The database (shared with DatabaseClient) to
  261. * be used for queries (the one asked for ID before).
  262. * \param zone_id The zone ID which was returned from
  263. * DatabaseAccessor::getZone and which will be passed to further
  264. * calls to the database.
  265. * \param origin The name of the origin of this zone. It could query
  266. * it from database, but as the DatabaseClient just searched for
  267. * the zone using the name, it should have it.
  268. */
  269. Finder(boost::shared_ptr<DatabaseAccessor> database, int zone_id,
  270. const isc::dns::Name& origin);
  271. // The following three methods are just implementations of inherited
  272. // ZoneFinder's pure virtual methods.
  273. virtual isc::dns::Name getOrigin() const;
  274. virtual isc::dns::RRClass getClass() const;
  275. /**
  276. * \brief Find an RRset in the datasource
  277. *
  278. * Searches the datasource for an RRset of the given name and
  279. * type. If there is a CNAME at the given name, the CNAME rrset
  280. * is returned.
  281. * (this implementation is not complete, and currently only
  282. * does full matches, CNAMES, and the signatures for matches and
  283. * CNAMEs)
  284. * \note target was used in the original design to handle ANY
  285. * queries. This is not implemented yet, and may use
  286. * target again for that, but it might also use something
  287. * different. It is left in for compatibility at the moment.
  288. * \note options are ignored at this moment
  289. *
  290. * \note Maybe counter intuitively, this method is not a const member
  291. * function. This is intentional; some of the underlying implementations
  292. * are expected to use a database backend, and would internally contain
  293. * some abstraction of "database connection". In the most strict sense
  294. * any (even read only) operation might change the internal state of
  295. * such a connection, and in that sense the operation cannot be considered
  296. * "const". In order to avoid giving a false sense of safety to the
  297. * caller, we indicate a call to this method may have a surprising
  298. * side effect. That said, this view may be too strict and it may
  299. * make sense to say the internal database connection doesn't affect
  300. * external behavior in terms of the interface of this method. As
  301. * we gain more experiences with various kinds of backends we may
  302. * revisit the constness.
  303. *
  304. * \exception DataSourceError when there is a problem reading
  305. * the data from the dabase backend.
  306. * This can be a connection, code, or
  307. * data (parse) error.
  308. *
  309. * \param name The name to find
  310. * \param type The RRType to find
  311. * \param target Unused at this moment
  312. * \param options Options about how to search.
  313. * See ZoneFinder::FindOptions.
  314. */
  315. virtual FindResult find(const isc::dns::Name& name,
  316. const isc::dns::RRType& type,
  317. isc::dns::RRsetList* target = NULL,
  318. const FindOptions options = FIND_DEFAULT);
  319. /**
  320. * \brief The zone ID
  321. *
  322. * This function provides the stored zone ID as passed to the
  323. * constructor. This is meant for testing purposes and normal
  324. * applications shouldn't need it.
  325. */
  326. int zone_id() const { return (zone_id_); }
  327. /**
  328. * \brief The database.
  329. *
  330. * This function provides the database stored inside as
  331. * passed to the constructor. This is meant for testing purposes and
  332. * normal applications shouldn't need it.
  333. */
  334. const DatabaseAccessor& database() const {
  335. return (*database_);
  336. }
  337. private:
  338. boost::shared_ptr<DatabaseAccessor> database_;
  339. const int zone_id_;
  340. const isc::dns::Name origin_;
  341. /**
  342. * \brief Searches database for an RRset
  343. *
  344. * This method scans RRs of single domain specified by name and finds
  345. * RRset with given type or any of redirection RRsets that are
  346. * requested.
  347. *
  348. * This function is used internally by find(), because this part is
  349. * called multiple times with slightly different parameters.
  350. *
  351. * \param name Which domain name should be scanned.
  352. * \param type The RRType which is requested. This can be NULL, in
  353. * which case the method will look for the redirections only.
  354. * \param want_cname If this is true, CNAME redirection may be returned
  355. * instead of the RRset with given type. If there's CNAME and
  356. * something else or the CNAME has multiple RRs, it throws
  357. * DataSourceError.
  358. * \param want_dname If this is true, DNAME redirection may be returned
  359. * instead. This is with type = NULL only and is not checked in
  360. * other circumstances. If the DNAME has multiple RRs, it throws
  361. * DataSourceError.
  362. * \param want_ns This allows redirection by NS to be returned. If
  363. * any other data is met as well, DataSourceError is thrown.
  364. * \note It may happen that some of the above error conditions are not
  365. * detected in some circumstances. The goal here is not to validate
  366. * the domain in DB, but to avoid bad behaviour resulting from
  367. * broken data.
  368. * \return First part of the result tells if the domain contains any
  369. * RRs. This can be used to decide between NXDOMAIN and NXRRSET.
  370. * The second part is the RRset found (if any) with any relevant
  371. * signatures attached to it.
  372. * \todo This interface doesn't look very elegant. Any better idea
  373. * would be nice.
  374. */
  375. std::pair<bool, isc::dns::RRsetPtr> getRRset(const isc::dns::Name&
  376. name,
  377. const isc::dns::RRType*
  378. type,
  379. bool want_cname,
  380. bool want_dname,
  381. bool want_ns);
  382. };
  383. /**
  384. * \brief Find a zone in the database
  385. *
  386. * This queries database's getZone to find the best matching zone.
  387. * It will propagate whatever exceptions are thrown from that method
  388. * (which is not restricted in any way).
  389. *
  390. * \param name Name of the zone or data contained there.
  391. * \return FindResult containing the code and an instance of Finder, if
  392. * anything is found. However, application should not rely on the
  393. * ZoneFinder being instance of Finder (possible subclass of this class
  394. * may return something else and it may change in future versions), it
  395. * should use it as a ZoneFinder only.
  396. */
  397. virtual FindResult findZone(const isc::dns::Name& name) const;
  398. /**
  399. * \brief Get the zone iterator
  400. *
  401. * The iterator allows going through the whole zone content. If the
  402. * underlying DatabaseConnection is implemented correctly, it should
  403. * be possible to have multiple ZoneIterators at once and query data
  404. * at the same time.
  405. *
  406. * \exception DataSourceError if the zone doesn't exist.
  407. * \exception isc::NotImplemented if the underlying DatabaseConnection
  408. * doesn't implement iteration. But in case it is not implemented
  409. * and the zone doesn't exist, DataSourceError is thrown.
  410. * \exception Anything else the underlying DatabaseConnection might
  411. * want to throw.
  412. * \param name The origin of the zone to iterate.
  413. * \return Shared pointer to the iterator (it will never be NULL)
  414. */
  415. virtual ZoneIteratorPtr getIterator(const isc::dns::Name& name) const;
  416. private:
  417. /// \brief Our database.
  418. const boost::shared_ptr<DatabaseAccessor> database_;
  419. };
  420. }
  421. }
  422. #endif