database.h 18.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Copyright (C) 2011  Internet Systems Consortium, Inc. ("ISC")
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.

#ifndef __DATABASE_DATASRC_H
#define __DATABASE_DATASRC_H

#include <datasrc/client.h>

20
#include <dns/name.h>
21
#include <exceptions/exceptions.h>
22

23 24 25
namespace isc {
namespace datasrc {

26
/**
27
 * \brief Abstraction of lowlevel database with DNS data
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
 *
 * This class is defines interface to databases. Each supported database
 * will provide methods for accessing the data stored there in a generic
 * manner. The methods are meant to be low-level, without much or any knowledge
 * about DNS and should be possible to translate directly to queries.
 *
 * On the other hand, how the communication with database is done and in what
 * schema (in case of relational/SQL database) is up to the concrete classes.
 *
 * This class is non-copyable, as copying connections to database makes little
 * sense and will not be needed.
 *
 * \todo Is it true this does not need to be copied? For example the zone
 *     iterator might need it's own copy. But a virtual clone() method might
 *     be better for that than copy constructor.
 *
 * \note The same application may create multiple connections to the same
45 46 47
 *     database, having multiple instances of this class. If the database
 *     allows having multiple open queries at one connection, the connection
 *     class may share it.
48
 */
49
class DatabaseAccessor : boost::noncopyable {
50
public:
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
    /**
     * Definitions of the fields as they are required to be filled in
     * by IteratorContext::getNext()
     *
     * When implementing getNext(), the columns array should
     * be filled with the values as described in this enumeration,
     * in this order, i.e. TYPE_COLUMN should be the first element
     * (index 0) of the array, TTL_COLUMN should be the second element
     * (index 1), etc.
     */
    enum RecordColumns {
        TYPE_COLUMN = 0,    ///< The RRType of the record (A/NS/TXT etc.)
        TTL_COLUMN = 1,     ///< The TTL of the record (a
        SIGTYPE_COLUMN = 2, ///< For RRSIG records, this contains the RRTYPE
                            ///< the RRSIG covers. In the current implementation,
                            ///< this field is ignored.
        RDATA_COLUMN = 3,   ///< Full text representation of the record's RDATA
        NAME_COLUMN = 4,    ///< The domain name of this RR
        COLUMN_COUNT = 5    ///< The total number of columns, MUST be value of
                            ///< the largest other element in this enum plus 1.
    };
72

73 74 75 76 77 78
    /**
     * \brief Destructor
     *
     * It is empty, but needs a virtual one, since we will use the derived
     * classes in polymorphic way.
     */
79
    virtual ~DatabaseAccessor() { }
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
    /**
     * \brief Retrieve a zone identifier
     *
     * This method looks up a zone for the given name in the database. It
     * should match only exact zone name (eg. name is equal to the zone's
     * apex), as the DatabaseClient will loop trough the labels itself and
     * find the most suitable zone.
     *
     * It is not specified if and what implementation of this method may throw,
     * so code should expect anything.
     *
     * \param name The name of the zone's apex to be looked up.
     * \return The first part of the result indicates if a matching zone
     *     was found. In case it was, the second part is internal zone ID.
     *     This one will be passed to methods finding data in the zone.
     *     It is not required to keep them, in which case whatever might
96
     *     be returned - the ID is only passed back to the database as
97 98
     *     an opaque handle.
     */
99
    virtual std::pair<bool, int> getZone(const isc::dns::Name& name) const = 0;
100

101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
    /**
     * \brief This holds the internal context of ZoneIterator for databases
     *
     * While the ZoneIterator implementation from DatabaseClient does all the
     * translation from strings to DNS classes and validation, this class
     * holds the pointer to where the database is at reading the data.
     *
     * It can either hold shared pointer to the connection which created it
     * and have some kind of statement inside (in case single database
     * connection can handle multiple concurrent SQL statements) or it can
     * create a new connection (or, if it is more convenient, the connection
     * itself can inherit both from DatabaseConnection and IteratorContext
     * and just clone itself).
     */
    class IteratorContext : public boost::noncopyable {
    public:
        /**
         * \brief Destructor
         *
         * Virtual destructor, so any descendand class is destroyed correctly.
         */
        virtual ~IteratorContext() { }
Jelte Jansen's avatar
Jelte Jansen committed
123

124 125 126 127
        /**
         * \brief Function to provide next resource record
         *
         * This function should provide data about the next resource record
Jelte Jansen's avatar
Jelte Jansen committed
128
         * from the data that is searched. The data is not converted yet.
129
         *
Jelte Jansen's avatar
Jelte Jansen committed
130 131
         * Depending on how the iterator was constructed, there is a difference
         * in behaviour; for a 'full zone iterator', created with
132 133 134 135
         * getAllRecords(), all COLUMN_COUNT elements of the array are
         * overwritten.
         * For a 'name iterator', created with getRecords(), the column
         * NAME_COLUMN is untouched, since what would be added here is by
Jelte Jansen's avatar
Jelte Jansen committed
136 137
         * definition already known to the caller (it already passes it as
         * an argument to getRecords()).
138
         *
Jelte Jansen's avatar
Jelte Jansen committed
139 140
         * \note The order of RRs is not strictly set, but the RRs for single
         * RRset must not be interleaved with any other RRs (eg. RRsets must be
141 142
         * "together").
         *
143
         * \param columns The data will be returned through here. The order
Jelte Jansen's avatar
Jelte Jansen committed
144 145
         *     is specified by the RecordColumns enum, and the size must be
         *     COLUMN_COUNT
146 147
         * \todo Do we consider databases where it is stored in binary blob
         *     format?
148 149 150
         * \throw DataSourceError if there's database-related error. If the
         *     exception (or any other in case of derived class) is thrown,
         *     the iterator can't be safely used any more.
151
         */
152
        virtual bool getNext(std::string (&columns)[COLUMN_COUNT]) = 0;
153
    };
Jelte Jansen's avatar
Jelte Jansen committed
154

155
    typedef boost::shared_ptr<IteratorContext> IteratorContextPtr;
Jelte Jansen's avatar
Jelte Jansen committed
156

157 158 159
    /**
     * \brief Creates an iterator context for a specific name.
     *
160 161
     * Returns an IteratorContextPtr that contains all records of the
     * given name from the given zone.
162
     *
Jelte Jansen's avatar
Jelte Jansen committed
163
     * The implementation of the iterator that is returned may leave the
164
     * NAME_COLUMN column of the array passed to getNext() untouched, as that
Jelte Jansen's avatar
Jelte Jansen committed
165 166
     * data is already known (it is the same as the name argument here)
     *
167 168 169 170
     * \exception any Since any implementation can be used, the caller should
     *            expect any exception to be thrown.
     *
     * \param name The name to search for. This should be a FQDN.
171 172 173
     * \param id The ID of the zone, returned from getZone().
     * \return Newly created iterator context. Must not be NULL.
     */
174
    virtual IteratorContextPtr getRecords(const std::string& name,
175
                                          int id) const = 0;
176

177
    /**
178
     * \brief Creates an iterator context for the whole zone.
179
     *
180 181
     * Returns an IteratorContextPtr that contains all records of the
     * zone with the given zone id.
182
     *
183 184 185 186 187 188
     * Each call to getNext() on the returned iterator should copy all
     * column fields of the array that is passed, as defined in the
     * RecordColumns enum.
     *
     * \exception any Since any implementation can be used, the caller should
     *            expect any exception to be thrown.
189 190 191 192
     *
     * \param id The ID of the zone, returned from getZone().
     * \return Newly created iterator context. Must not be NULL.
     */
193
    virtual IteratorContextPtr getAllRecords(int id) const = 0;
194

195
    /**
Michal 'vorner' Vaner's avatar
Michal 'vorner' Vaner committed
196 197 198 199 200 201 202 203 204 205 206
     * \brief Returns a string identifying this dabase backend
     *
     * The returned string is mainly intended to be used for
     * debugging/logging purposes.
     *
     * Any implementation is free to choose the exact string content,
     * but it is advisable to make it a name that is distinguishable
     * from the others.
     *
     * \return the name of the database
     */
207
    virtual const std::string& getDBName() const = 0;
208 209
};

210 211 212 213 214
/**
 * \brief Concrete data source client oriented at database backends.
 *
 * This class (together with corresponding versions of ZoneFinder,
 * ZoneIterator, etc.) translates high-level data source queries to
215
 * low-level calls on DatabaseAccessor. It calls multiple queries
216
 * if necessary and validates data from the database, allowing the
217
 * DatabaseAccessor to be just simple translation to SQL/other
218 219 220 221
 * queries to database.
 *
 * While it is possible to subclass it for specific database in case
 * of special needs, it is not expected to be needed. This should just
222
 * work as it is with whatever DatabaseAccessor.
223
 */
224 225
class DatabaseClient : public DataSourceClient {
public:
226 227 228
    /**
     * \brief Constructor
     *
229
     * It initializes the client with a database.
230
     *
231
     * \exception isc::InvalidParameter if database is NULL. It might throw
232 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
     *     suggests, the client takes ownership of the database and will
236 237
     *     delete it when itself deleted.
     */
238
    DatabaseClient(boost::shared_ptr<DatabaseAccessor> database);
239 240 241 242 243
    /**
     * \brief Corresponding ZoneFinder implementation
     *
     * The zone finder implementation for database data sources. Similarly
     * to the DatabaseClient, it translates the queries to methods of the
244
     * database.
245 246 247 248 249 250 251 252 253 254 255 256 257 258
     *
     * Application should not come directly in contact with this class
     * (it should handle it trough generic ZoneFinder pointer), therefore
     * it could be completely hidden in the .cc file. But it is provided
     * to allow testing and for rare cases when a database needs slightly
     * different handling, so it can be subclassed.
     *
     * Methods directly corresponds to the ones in ZoneFinder.
     */
    class Finder : public ZoneFinder {
    public:
        /**
         * \brief Constructor
         *
259
         * \param database The database (shared with DatabaseClient) to
260 261
         *     be used for queries (the one asked for ID before).
         * \param zone_id The zone ID which was returned from
262
         *     DatabaseAccessor::getZone and which will be passed to further
263
         *     calls to the database.
264 265 266
         * \param origin The name of the origin of this zone. It could query
         *     it from database, but as the DatabaseClient just searched for
         *     the zone using the name, it should have it.
267
         */
268 269
        Finder(boost::shared_ptr<DatabaseAccessor> database, int zone_id,
               const isc::dns::Name& origin);
Michal 'vorner' Vaner's avatar
Michal 'vorner' Vaner committed
270 271
        // The following three methods are just implementations of inherited
        // ZoneFinder's pure virtual methods.
272 273
        virtual isc::dns::Name getOrigin() const;
        virtual isc::dns::RRClass getClass() const;
274 275 276

        /**
         * \brief Find an RRset in the datasource
277
         *
Jelte Jansen's avatar
Jelte Jansen committed
278 279 280 281 282 283 284 285 286 287 288
         * Searches the datasource for an RRset of the given name and
         * type. If there is a CNAME at the given name, the CNAME rrset
         * is returned.
         * (this implementation is not complete, and currently only
         * does full matches, CNAMES, and the signatures for matches and
         * CNAMEs)
         * \note target was used in the original design to handle ANY
         *       queries. This is not implemented yet, and may use
         *       target again for that, but it might also use something
         *       different. It is left in for compatibility at the moment.
         * \note options are ignored at this moment
Jelte Jansen's avatar
Jelte Jansen committed
289
         *
290 291 292 293 294 295 296 297 298 299 300 301 302 303
         * \note Maybe counter intuitively, this method is not a const member
         * function.  This is intentional; some of the underlying implementations
         * are expected to use a database backend, and would internally contain
         * some abstraction of "database connection".  In the most strict sense
         * any (even read only) operation might change the internal state of
         * such a connection, and in that sense the operation cannot be considered
         * "const".  In order to avoid giving a false sense of safety to the
         * caller, we indicate a call to this method may have a surprising
         * side effect.  That said, this view may be too strict and it may
         * make sense to say the internal database connection doesn't affect
         * external behavior in terms of the interface of this method.  As
         * we gain more experiences with various kinds of backends we may
         * revisit the constness.
         *
Jelte Jansen's avatar
Jelte Jansen committed
304 305 306 307 308 309 310 311
         * \exception DataSourceError when there is a problem reading
         *                            the data from the dabase backend.
         *                            This can be a connection, code, or
         *                            data (parse) error.
         *
         * \param name The name to find
         * \param type The RRType to find
         * \param target Unused at this moment
312 313
         * \param options Options about how to search.
         *     See ZoneFinder::FindOptions.
314
         */
315 316 317
        virtual FindResult find(const isc::dns::Name& name,
                                const isc::dns::RRType& type,
                                isc::dns::RRsetList* target = NULL,
Jelte Jansen's avatar
Jelte Jansen committed
318
                                const FindOptions options = FIND_DEFAULT);
Jelte Jansen's avatar
Jelte Jansen committed
319

320 321 322 323 324 325 326 327 328
        /**
         * \brief The zone ID
         *
         * This function provides the stored zone ID as passed to the
         * constructor. This is meant for testing purposes and normal
         * applications shouldn't need it.
         */
        int zone_id() const { return (zone_id_); }
        /**
329
         * \brief The database.
330
         *
331
         * This function provides the database stored inside as
332 333 334
         * passed to the constructor. This is meant for testing purposes and
         * normal applications shouldn't need it.
         */
335
        const DatabaseAccessor& database() const {
336
            return (*database_);
337
        }
338
    private:
339
        boost::shared_ptr<DatabaseAccessor> database_;
340
        const int zone_id_;
341
        const isc::dns::Name origin_;
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
        /**
         * \brief Searches database for an RRset
         *
         * This method scans RRs of single domain specified by name and finds
         * RRset with given type or any of redirection RRsets that are
         * requested.
         *
         * This function is used internally by find(), because this part is
         * called multiple times with slightly different parameters.
         *
         * \param name Which domain name should be scanned.
         * \param type The RRType which is requested. This can be NULL, in
         *     which case the method will look for the redirections only.
         * \param want_cname If this is true, CNAME redirection may be returned
         *     instead of the RRset with given type. If there's CNAME and
         *     something else or the CNAME has multiple RRs, it throws
         *     DataSourceError.
         * \param want_dname If this is true, DNAME redirection may be returned
         *     instead. This is with type = NULL only and is not checked in
         *     other circumstances. If the DNAME has multiple RRs, it throws
         *     DataSourceError.
363 364 365 366 367 368
         * \param want_ns This allows redirection by NS to be returned. If
         *     any other data is met as well, DataSourceError is thrown.
         * \note It may happen that some of the above error conditions are not
         *     detected in some circumstances. The goal here is not to validate
         *     the domain in DB, but to avoid bad behaviour resulting from
         *     broken data.
369 370 371 372 373 374 375
         * \return First part of the result tells if the domain contains any
         *     RRs. This can be used to decide between NXDOMAIN and NXRRSET.
         *     The second part is the RRset found (if any) with any relevant
         *     signatures attached to it.
         * \todo This interface doesn't look very elegant. Any better idea
         *     would be nice.
         */
376 377
        std::pair<bool, isc::dns::RRsetPtr> getRRset(const isc::dns::Name&
                                                     name,
378 379 380 381 382
                                                     const isc::dns::RRType*
                                                     type,
                                                     bool want_cname,
                                                     bool want_dname,
                                                     bool want_ns);
383 384 385 386
    };
    /**
     * \brief Find a zone in the database
     *
387
     * This queries database's getZone to find the best matching zone.
388 389 390 391
     * It will propagate whatever exceptions are thrown from that method
     * (which is not restricted in any way).
     *
     * \param name Name of the zone or data contained there.
Michal 'vorner' Vaner's avatar
Michal 'vorner' Vaner committed
392 393 394 395 396
     * \return FindResult containing the code and an instance of Finder, if
     *     anything is found. However, application should not rely on the
     *     ZoneFinder being instance of Finder (possible subclass of this class
     *     may return something else and it may change in future versions), it
     *     should use it as a ZoneFinder only.
397
     */
398
    virtual FindResult findZone(const isc::dns::Name& name) const;
399

400 401 402 403 404 405 406 407 408 409
    /**
     * \brief Get the zone iterator
     *
     * The iterator allows going through the whole zone content. If the
     * underlying DatabaseConnection is implemented correctly, it should
     * be possible to have multiple ZoneIterators at once and query data
     * at the same time.
     *
     * \exception DataSourceError if the zone doesn't exist.
     * \exception isc::NotImplemented if the underlying DatabaseConnection
410 411
     *     doesn't implement iteration. But in case it is not implemented
     *     and the zone doesn't exist, DataSourceError is thrown.
412 413 414 415 416 417
     * \exception Anything else the underlying DatabaseConnection might
     *     want to throw.
     * \param name The origin of the zone to iterate.
     * \return Shared pointer to the iterator (it will never be NULL)
     */
    virtual ZoneIteratorPtr getIterator(const isc::dns::Name& name) const;
Jelte Jansen's avatar
Jelte Jansen committed
418

419
private:
420
    /// \brief Our database.
421
    const boost::shared_ptr<DatabaseAccessor> database_;
422 423 424 425 426 427
};

}
}

#endif