database.h 18 KB

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