database.h 16.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// 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

18 19
#include <string>

20 21
#include <boost/scoped_ptr.hpp>

22 23
#include <dns/rrclass.h>

24 25 26 27 28
#include <datasrc/client.h>

namespace isc {
namespace datasrc {

29
/**
30
 * \brief Abstraction of lowlevel database with DNS data
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
 *
 * 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
48 49 50
 *     database, having multiple instances of this class. If the database
 *     allows having multiple open queries at one connection, the connection
 *     class may share it.
51
 */
52
class DatabaseAccessor : boost::noncopyable {
53
public:
54 55 56 57 58 59
    /**
     * \brief Destructor
     *
     * It is empty, but needs a virtual one, since we will use the derived
     * classes in polymorphic way.
     */
60
    virtual ~DatabaseAccessor() { }
61

62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
    /**
     * \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
78
     *     be returned - the ID is only passed back to the database as
79 80
     *     an opaque handle.
     */
81
    virtual std::pair<bool, int> getZone(const isc::dns::Name& name) const = 0;
82 83 84 85

    /**
     * \brief Starts a new search for records of the given name in the given zone
     *
Jelte Jansen's avatar
Jelte Jansen committed
86 87 88 89 90 91
     * The data searched by this call can be retrieved with subsequent calls to
     * getNextRecord().
     *
     * \exception DataSourceError if there is a problem connecting to the
     *                            backend database
     *
92 93 94
     * \param zone_id The zone to search in, as returned by getZone()
     * \param name The name of the records to find
     */
95
    virtual void searchForRecords(int zone_id, const std::string& name) = 0;
96 97 98 99 100 101 102

    /**
     * \brief Retrieves the next record from the search started with searchForRecords()
     *
     * Returns a boolean specifying whether or not there was more data to read.
     * In the case of a database error, a DatasourceError is thrown.
     *
103
     * The columns passed is an array of std::strings consisting of
104
     * DatabaseConnection::COLUMN_COUNT elements, the elements of which
105 106
     * are defined in DatabaseConnection::RecordColumns, in their basic
     * string representation.
Jelte Jansen's avatar
Jelte Jansen committed
107
     *
108 109 110 111
     * If you are implementing a derived database connection class, you
     * should have this method check the column_count value, and fill the
     * array with strings conforming to their description in RecordColumn.
     *
112 113
     * \exception DatasourceError if there was an error reading from the database
     *
114 115 116
     * \param columns The elements of this array will be filled with the data
     *                for one record as defined by RecordColumns
     *                If there was no data, the array is untouched.
117 118
     * \return true if there was a next record, false if there was not
     */
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
    virtual bool getNextRecord(std::string columns[], size_t column_count) = 0;

    /**
     * \brief Resets the current search initiated with searchForRecords()
     *
     * This method will be called when the called of searchForRecords() and
     * getNextRecord() finds bad data, and aborts the current search.
     * It should clean up whatever handlers searchForRecords() created, and
     * any other state modified or needed by getNextRecord()
     *
     * Of course, the implementation of getNextRecord may also use it when
     * it is done with a search. If it does, the implementation of this
     * method should make sure it can handle being called multiple times.
     *
     * The implementation for this method should make sure it never throws.
     */
    virtual void resetSearch() = 0;

    /**
     * Definitions of the fields as they are required to be filled in
     * by getNextRecord()
Jelte Jansen's avatar
Jelte Jansen committed
140
     *
141 142
     * When implementing getNextRecord(), the columns array should
     * be filled with the values as described in this enumeration,
Jelte Jansen's avatar
Jelte Jansen committed
143 144 145
     * 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.
146 147 148 149 150 151 152 153 154 155
     */
    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
    };

156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
    /// TBD
    virtual std::pair<bool, int> startUpdateZone(const std::string& zone_name,
                                                 bool replace) = 0;

    /// TBD
    virtual void commitUpdateZone() = 0;

    /// TBD
    virtual void rollbackUpdateZone() = 0;

    /// TBD
    /// This is "dumb"; doesn't inspect the content of columns.
    /// The zone is the one specified in startUpdateZone().
    virtual void addRecordToZone(const std::vector<std::string>& columns) = 0;

    /// TBD
    ///
    /// note: in dynamic update or IXFR, TTL may also be specified, but
    /// we intentionally ignore that in this interface, because it's not
    /// guaranteed that all records have the same TTL (unlike the RRset
    /// assumption) and there can even be multiple records for the same name,
    /// type and rdata with different TTLs.  If we only delete one of them,
    /// subsequent lookup will still return a positive answer, which would
    /// be confusing.  It's a higher layer's responsibility to check if
    /// there is at least one record in the database that has the given
    /// TTL.
    virtual void deleteRecordInZone(
        const std::vector<std::string>& params) = 0;

    /// TBD
    /// Compliant database should support the following columns:
    /// name, rname, ttl, rdtype, sigtype, rdata
    /// (even though their internal representation may be different).
    static const size_t ADD_COLUMN_COUNT = 6;

    /// TBD
    static const size_t DEL_PARAM_COUNT = 3;

    /// The number of fields the columns array passed to getNextRecord should
    /// have.
196
    static const size_t COLUMN_COUNT = 4;
197 198

    /**
Michal 'vorner' Vaner's avatar
Michal 'vorner' Vaner committed
199 200 201 202 203 204 205 206 207 208 209
     * \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
     */
210
    virtual const std::string& getDBName() const = 0;
211 212
};

213 214 215 216 217
/**
 * \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
218
 * low-level calls on DatabaseAccessor. It calls multiple queries
219
 * if necessary and validates data from the database, allowing the
220
 * DatabaseAccessor to be just simple translation to SQL/other
221 222 223 224
 * 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
225
 * work as it is with whatever DatabaseAccessor.
226
 */
227 228
class DatabaseClient : public DataSourceClient {
public:
229 230 231
    /**
     * \brief Constructor
     *
232
     * It initializes the client with a database.
233
     *
234
     * \exception isc::InvalidParameter if database is NULL. It might throw
235 236
     * standard allocation exception as well, but doesn't throw anything else.
     *
237
     * \param rrclass The RR class of the zones that this client will handle.
238 239
     * \param database The database to use to get data. As the parameter
     *     suggests, the client takes ownership of the database and will
240 241
     *     delete it when itself deleted.
     */
242 243 244
    DatabaseClient(isc::dns::RRClass rrclass,
                   boost::shared_ptr<DatabaseAccessor> database);

245 246 247 248 249
    /**
     * \brief Corresponding ZoneFinder implementation
     *
     * The zone finder implementation for database data sources. Similarly
     * to the DatabaseClient, it translates the queries to methods of the
250
     * database.
251 252 253 254 255 256 257 258 259 260 261 262 263 264
     *
     * 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
         *
265
         * \param database The database (shared with DatabaseClient) to
266 267
         *     be used for queries (the one asked for ID before).
         * \param zone_id The zone ID which was returned from
268
         *     DatabaseAccessor::getZone and which will be passed to further
269
         *     calls to the database.
270
         */
271
        Finder(boost::shared_ptr<DatabaseAccessor> database, int zone_id);
Michal 'vorner' Vaner's avatar
Michal 'vorner' Vaner committed
272 273
        // The following three methods are just implementations of inherited
        // ZoneFinder's pure virtual methods.
274 275
        virtual isc::dns::Name getOrigin() const;
        virtual isc::dns::RRClass getClass() const;
276 277 278

        /**
         * \brief Find an RRset in the datasource
279
         *
Jelte Jansen's avatar
Jelte Jansen committed
280 281 282 283 284 285 286 287 288 289 290
         * 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
291
         *
292 293 294 295 296 297 298 299 300 301 302 303 304 305
         * \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
306 307 308 309 310 311 312 313 314
         * \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
         * \param options Unused at this moment
315
         */
316 317 318
        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
319
                                const FindOptions options = FIND_DEFAULT);
Jelte Jansen's avatar
Jelte Jansen committed
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

330
        /**
331
         * \brief The database accessor.
332
         *
333
         * This function provides the database accessor stored inside as
334 335 336
         * passed to the constructor. This is meant for testing purposes and
         * normal applications shouldn't need it.
         */
337 338
        const DatabaseAccessor& getAccessor() const {
            return (*accessor_);
339
        }
340
    private:
341
        boost::shared_ptr<DatabaseAccessor> accessor_;
342 343
        const int zone_id_;
    };
344 345 346

    class Updater : public ZoneUpdater {
    public:
347 348 349
        Updater(boost::shared_ptr<DatabaseAccessor> database, int zone_id,
                const std::string& zone_name, const std::string& class_name);
        ~Updater();
350
        virtual ZoneFinder& getFinder();
351
        virtual void commit();
352 353

    private:
354
        bool committed_;
355
        boost::shared_ptr<DatabaseAccessor> accessor_;
356
        const int zone_id_;
357 358 359
        std::string db_name_;
        std::string zone_name_;
        std::string class_name_;
360 361 362
        boost::scoped_ptr<Finder::Finder> finder_;
    };

363 364 365
    /**
     * \brief Find a zone in the database
     *
366
     * This queries database's getZone to find the best matching zone.
367 368 369 370
     * 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
371 372 373 374 375
     * \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.
376
     */
377
    virtual FindResult findZone(const isc::dns::Name& name) const;
378

379 380 381 382
    /// TBD
    virtual ZoneUpdaterPtr startUpdateZone(const isc::dns::Name& name,
                                           bool replace) const;

383
private:
384 385 386
    /// \brief The RR class that this client handles.
    const isc::dns::RRClass rrclass_;

387 388
    /// \brief The accessor to our database.
    const boost::shared_ptr<DatabaseAccessor> accessor_;
389 390 391 392 393
};

}
}

394 395 396 397 398
#endif  // __DATABASE_DATASRC_H

// Local Variables:
// mode: c++
// End: