mysql_lease_mgr.h 17.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Copyright (C) 2012 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.

15
16
#ifndef MYSQL_LEASE_MGR_H
#define MYSQL_LEASE_MGR_H
17

18
#include <time.h>
19
#include <boost/scoped_ptr.hpp>
20
#include <mysql.h>
21
22
23
24
25
#include <dhcp/lease_mgr.h>

namespace isc {
namespace dhcp {

26
27
28
29
30
// Define the current database schema values

const uint32_t CURRENT_VERSION_VERSION = 0;
const uint32_t CURRENT_VERSION_MINOR = 1;

31
32
33
34
35
36

// Forward declaration of the Lease6 exchange object.  This class is defined
// in the .cc file.
class MySqlLease6Exchange;


37
/// @brief MySQL Lease Manager
38
39
40
41
42
43
44
45
///
/// This is a concrete API for the backend for the MySQL database.
class MySqlLeaseMgr : public LeaseMgr {
public:
    /// @brief Constructor
    ///
    /// Uses the following keywords in the parameters passed to it to
    /// connect to the database:
46
47
48
49
    /// - name - Name of the database to which to connect (mandatory)
    /// - host - Host to which to connect (optional, defaults to "localhost")
    /// - user - Username under which to connect (optional)
    /// - password - Password for "user" on the database (optional)
50
51
52
53
54
55
56
57
58
    ///
    /// If the database is successfully opened, the version number in the
    /// schema_version table will be checked against hard-coded value in
    /// the implementation file.
    ///
    /// Finally, all the SQL commands are pre-compiled.
    ///
    /// @param parameters A data structure relating keywords and values
    ///        concerned with the database.
59
    ///
60
61
62
63
    /// @throw isc::dhcp::NoDatabaseName Mandatory database name not given
    /// @throw isc::dhcp::DbOpenError Error opening the database
    /// @throw isc::dhcp::DbOperationError An operation on the open database has
    ///        failed.
64
65
66
67
68
69
70
71
    MySqlLeaseMgr(const ParameterMap& parameters);

    /// @brief Destructor (closes database)
    virtual ~MySqlLeaseMgr();

    /// @brief Adds an IPv4 lease.
    ///
    /// @param lease lease to be added
72
73
74
75
    ///
    /// @result true if the lease was added, false if not (because a lease
    ///         with the same address was already there).
    ///
76
77
    /// @throw isc::dhcp::DbOperationError An operation on the open database has
    ///        failed.
78
    virtual bool addLease(const Lease4Ptr& lease);
79
80
81
82

    /// @brief Adds an IPv6 lease.
    ///
    /// @param lease lease to be added
83
84
85
86
    ///
    /// @result true if the lease was added, false if not (because a lease
    ///         with the same address was already there).
    ///
87
88
    /// @throw isc::dhcp::DbOperationError An operation on the open database has
    ///        failed.
89
    virtual bool addLease(const Lease6Ptr& lease);
90

91
    /// @brief Return IPv4 lease for specified IPv4 address and subnet_id
92
93
94
95
96
    ///
    /// This method is used to get a lease for specific subnet_id. There can be
    /// at most one lease for any given subnet, so this method returns a single
    /// pointer.
    ///
97
    /// @param addr address of the sought lease
98
99
100
    /// @param subnet_id ID of the subnet the lease must belong to
    ///
    /// @return smart pointer to the lease (or NULL if a lease is not found)
101
    virtual Lease4Ptr getLease4(const isc::asiolink::IOAddress& addr,
102
                                SubnetID subnet_id) const;
103
104
105
106

    /// @brief Returns an IPv4 lease for specified IPv4 address
    ///
    /// This method return a lease that is associated with a given address.
107
    /// For other query types (by hardware addr, by DUID) there can be
108
109
110
111
112
113
114
115
116
    /// several leases in different subnets (e.g. for mobile clients that
    /// got address in different subnets). However, for a single address
    /// there can be only one lease, so this method returns a pointer to
    /// a single lease, not a container of leases.
    ///
    /// @param addr address of the searched lease
    /// @param subnet_id ID of the subnet the lease must belong to
    ///
    /// @return smart pointer to the lease (or NULL if a lease is not found)
117
    virtual Lease4Ptr getLease4(const isc::asiolink::IOAddress& addr) const;
118

119

120
121
122
123
124
125
126
127
128
129
    /// @brief Returns existing IPv4 leases for specified hardware address.
    ///
    /// Although in the usual case there will be only one lease, for mobile
    /// clients or clients with multiple static/fixed/reserved leases there
    /// can be more than one. Thus return type is a container, not a single
    /// pointer.
    ///
    /// @param hwaddr hardware address of the client
    ///
    /// @return lease collection
130
    virtual Lease4Collection getLease4(const HWAddr& hwaddr) const;
131
132
133
134
135
136
137
138
139
140
141
142

    /// @brief Returns existing IPv4 leases for specified hardware address
    ///        and a subnet
    ///
    /// There can be at most one lease for a given HW address in a single
    /// pool, so this method with either return a single lease or NULL.
    ///
    /// @param hwaddr hardware address of the client
    /// @param subnet_id identifier of the subnet that lease must belong to
    ///
    /// @return a pointer to the lease (or NULL if a lease is not found)
    virtual Lease4Ptr getLease4(const HWAddr& hwaddr,
143
                                SubnetID subnet_id) const;
144
145
146
147
148
149
150
151
152
153
154

    /// @brief Returns existing IPv4 lease for specified client-id
    ///
    /// Although in the usual case there will be only one lease, for mobile
    /// clients or clients with multiple static/fixed/reserved leases there
    /// can be more than one. Thus return type is a container, not a single
    /// pointer.
    ///
    /// @param clientid client identifier
    ///
    /// @return lease collection
155
    virtual Lease4Collection getLease4(const ClientId& clientid) const;
156
157
158
159
160
161
162
163
164
165
166

    /// @brief Returns existing IPv4 lease for specified client-id
    ///
    /// There can be at most one lease for a given HW address in a single
    /// pool, so this method with either return a single lease or NULL.
    ///
    /// @param clientid client identifier
    /// @param subnet_id identifier of the subnet that lease must belong to
    ///
    /// @return a pointer to the lease (or NULL if a lease is not found)
    virtual Lease4Ptr getLease4(const ClientId& clientid,
167
                                SubnetID subnet_id) const;
168
169
170
171
172
173
174
175
176
177

    /// @brief Returns existing IPv6 lease for a given IPv6 address.
    ///
    /// For a given address, we assume that there will be only one lease.
    /// The assumtion here is that there will not be site or link-local
    /// addresses used, so there is no way of having address duplication.
    ///
    /// @param addr address of the searched lease
    ///
    /// @return smart pointer to the lease (or NULL if a lease is not found)
178
    ///
179
180
181
182
    /// @throw isc::BadValue record retrieved from database had an invalid
    ///        lease type field.
    /// @throw isc::dhcp::DbOperationError An operation on the open database has
    ///        failed.
183
    virtual Lease6Ptr getLease6(const isc::asiolink::IOAddress& addr) const;
184
185
186
187
188
189
190
191
192
193
194
195
196

    /// @brief Returns existing IPv6 leases for a given DUID+IA combination
    ///
    /// Although in the usual case there will be only one lease, for mobile
    /// clients or clients with multiple static/fixed/reserved leases there
    /// can be more than one. Thus return type is a container, not a single
    /// pointer.
    ///
    /// @param duid client DUID
    /// @param iaid IA identifier
    ///
    /// @return smart pointer to the lease (or NULL if a lease is not found)
    virtual Lease6Collection getLease6(const DUID& duid,
197
                                       uint32_t iaid) const;
198
199
200
201
202
203
204
205
206

    /// @brief Returns existing IPv6 lease for a given DUID+IA combination
    ///
    /// @param duid client DUID
    /// @param iaid IA identifier
    /// @param subnet_id subnet id of the subnet the lease belongs to
    ///
    /// @return smart pointer to the lease (or NULL if a lease is not found)
    virtual Lease6Ptr getLease6(const DUID& duid, uint32_t iaid,
207
                                SubnetID subnet_id) const;
208
209
210
211
212
213

    /// @brief Updates IPv4 lease.
    ///
    /// @param lease4 The lease to be updated.
    ///
    /// If no such lease is present, an exception will be thrown.
214
    virtual void updateLease4(const Lease4Ptr& lease4);
215
216
217
218
219

    /// @brief Updates IPv4 lease.
    ///
    /// @param lease4 The lease to be updated.
    ///
220
221
222
223
    /// @throw isc::dhcp::NoSuchLease Attempt to update a lease that did not
    ///        exist.
    /// @throw isc::dhcp::DbOperationError An operation on the open database has
    ///        failed.
224
    virtual void updateLease6(const Lease6Ptr& lease6);
225
226
227
228
229
230

    /// @brief Deletes a lease.
    ///
    /// @param addr IPv4 address of the lease to be deleted.
    ///
    /// @return true if deletion was successful, false if no such lease exists
231
    virtual bool deleteLease4(const isc::asiolink::IOAddress& addr);
232
233
234
235
236
237

    /// @brief Deletes a lease.
    ///
    /// @param addr IPv4 address of the lease to be deleted.
    ///
    /// @return true if deletion was successful, false if no such lease exists
238
    ///
239
240
    /// @throw isc::dhcp::DbOperationError An operation on the open database has
    ///        failed.
241
    virtual bool deleteLease6(const isc::asiolink::IOAddress& addr);
242
243
244
245

    /// @brief Returns backend name.
    ///
    /// Each backend have specific name, e.g. "mysql" or "sqlite".
246
    virtual std::string getName() const;
247
248
249
250

    /// @brief Returns description of the backend.
    ///
    /// This description may be multiline text that describes the backend.
251
    virtual std::string getDescription() const;
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266

    /// @brief Returns backend version.
    ///
    /// @return Version number as a pair of unsigned integers.  "first" is the
    ///         major version number, "second" the minor number.
    ///
    /// @todo: We will need to implement 3 version functions eventually:
    /// A. abstract API version
    /// B. backend version
    /// C. database version (stored in the database scheme)
    ///
    /// and then check that:
    /// B>=A and B=C (it is ok to have newer backend, as it should be backward
    /// compatible)
    /// Also if B>C, some database upgrade procedure may be triggered
267
    ///
268
269
    /// @throw isc::dhcp::DbOperationError An operation on the open database has
    ///        failed.
270
271
    virtual std::pair<uint32_t, uint32_t> getVersion() const;

272
273
274
275
276
    /// @brief Commit Transactions
    ///
    /// Commits all pending database operations.  On databases that don't
    /// support transactions, this is a no-op.
    ///
277
    /// @throw DbOperationError Iif the commit failed.
278
279
280
281
282
283
284
    virtual void commit();

    /// @brief Rollback Transactions
    ///
    /// Rolls back all pending database operations.  On databases that don't
    /// support transactions, this is a no-op.
    ///
285
    /// @throw DbOperationError If the rollback failed.
286
287
288
289
    virtual void rollback();

    ///@{
    /// The following methods are used to convert between times and time
290
291
292
293
294
    /// intervals stored in the Lease object, and the times stored in the
    /// database.  The reason for the difference is because in the DHCP server,
    /// the cltt (Client Time Since Last Transmission) is the natural data; in
    /// the lease file - which may be read by the user - it is the expiry time
    /// of the lease.
295
296
297

    /// @brief Convert Lease Time to Database Times
    ///
298
299
300
301
    /// Within the DHCP servers, times are stored as client last transmit time
    /// and valid lifetime.  In the database, the information is stored as
    /// valid lifetime and "expire" (time of expiry of the lease).  They are
    /// related by the equation:
302
    ///
303
    /// - expire = client last transmit time + valid lifetime
304
305
306
307
308
    ///
    /// This method converts from the times in the lease object into times
    /// able to be added to the database.
    ///
    /// @param cltt Client last transmit time
309
    /// @param valid_lifetime Valid lifetime
310
311
312
    /// @param expire Reference to MYSQL_TIME object where the expiry time of
    ///        the lease will be put.
    static
313
314
    void convertToDatabaseTime(time_t cltt, uint32_t valid_lifetime,
                               MYSQL_TIME& expire);
315
316
317

    /// @brief Convert Database Time to Lease Times
    ///
318
319
320
321
    /// Within the database, time is stored as "expire" (time of expiry of the
    /// lease) and valid lifetime.  In the DHCP server, the information is
    /// stored client last transmit time and valid lifetime.  These are related
    /// by the equation:
322
    ///
323
    /// - client last transmit time = expire - valid_lifetime
324
325
326
327
328
329
330
331
332
333
    ///
    /// This method converts from the times in the database into times
    /// able to be inserted into the lease object.
    ///
    /// @param expire Reference to MYSQL_TIME object from where the expiry
    ///        time of the lease is taken.
    /// @param lease_time lifetime of the lease.
    /// @param cltt Reference to location where client last transmit time
    ///        is put.
    static
334
335
    void convertFromDatabaseTime(const MYSQL_TIME& expire, 
                                 uint32_t valid_lifetime, time_t& cltt);
336
337
    ///@}

338
    /// @brief Statement Tags
339
    ///
340
    /// The contents of the enum are indexes into the list of SQL statements
341
    enum StatementIndex {
342
343
344
        DELETE_LEASE6,              // Delete from lease6 by address
        GET_LEASE6_ADDR,            // Get lease6 by address
        GET_LEASE6_DUID_IAID,       // Get lease6 by DUID and IAID
345
        GET_LEASE6_DUID_IAID_SUBID, // Get lease6 by DUID, IAID and Subnet ID
346
347
348
349
        GET_VERSION,                // Obtain version number
        INSERT_LEASE6,              // Add entry to lease6 table
        UPDATE_LEASE6,              // Update a Lease6 entry
        NUM_STATEMENTS              // Number of statements
350
351
    };

352
private:
353
354
355
356
357
358
359
360
361
362
    /// @brief Prepare Single Statement
    ///
    /// Creates a prepared statement from the text given and adds it to the
    /// statements_ vector at the given index.
    ///
    /// @param index Index into the statements_ vector into which the text
    ///        should be placed.  The vector must be big enough for the index
    ///        to be valid, else an exception will be thrown.
    /// @param text Text of the SQL statement to be prepared.
    ///
363
364
365
    /// @throw isc::dhcp::DbOperationError An operation on the open database has
    ///        failed.
    /// @throw isc::InvalidParameter 'index' is not valid for the vector.
366
367
368
369
370
371
    void prepareStatement(StatementIndex index, const char* text);

    /// @brief Prepare statements
    ///
    /// Creates the prepared statements for all of the SQL statements used
    /// by the MySQL backend.
372
    ///
373
374
375
376
    /// @throw isc::dhcp::DbOperationError An operation on the open database has
    ///        failed.
    /// @throw isc::InvalidParameter 'index' is not valid for the vector.  This
    ///        represents an internal error within the code.
377
378
    void prepareStatements();

379
380
381
382
383
    /// @brief Open Database
    ///
    /// Opens the database using the information supplied in the parameters
    /// passed to the constructor.
    ///
384
385
    /// @throw NoDatabaseName Mandatory database name not given
    /// @throw DbOpenError Error opening the database
386
387
    void openDatabase();

388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
    /// @brief Binds Parameters and Executes
    ///
    /// This method abstracts a lot of common processing from the getXxxx()
    /// methods.  It binds the parameters passed to it to the appropriate
    /// prepared statement, and binds the variables in the exchange6 object to
    /// the output parameters of the statement.  It then executes the prepared
    /// statement.
    ///
    /// The data can be retrieved using mysql_stmt_fetch and the getLeaseData()
    /// method on the exchange6 object.
    ///
    /// @param stindex Index of prepared statement to be executed
    /// @param inbind Array of MYSQL_BIND objects representing the parameters.
    ///        (Note that the number is determined by the number of parameters
    ///        in the statement.)
    ///
404
405
    /// @throw isc::dhcp::DbOperationError An operation on the open database has
    ///        failed.
406
407
    void bind6AndExecute(StatementIndex stindex, MYSQL_BIND* inbind) const;

408
409
410
411
412
413
414
415
416
417
    /// @brief Check Error and Throw Exception
    ///
    /// Virtually all MySQL functions return a status which, if non-zero,
    /// indicates an error.  This inline function conceals a lot of error
    /// checking/exception-throwing code.
    ///
    /// @param status Status code: non-zero implies an error
    /// @param index Index of statement that caused the error
    /// @param what High-level description of the error
    ///
418
419
    /// @throw isc::dhcp::DbOperationError An operation on the open database has
    ///        failed.
420
    inline void checkError(int status, StatementIndex index,
421
422
423
                           const char* what) const {
        if (status != 0) {
            isc_throw(DbOperationError, what << " for <" <<
424
                      text_statements_[index] << ">, reason: " <<
425
426
                      mysql_error(mysql_) << " (error code " <<
                      mysql_errno(mysql_) << ")");
427
428
429
        }
    }

430
    // Members
431
432
433
434
435
436

    /// Used for transfer of data to/from the database. This is a pointed-to
    /// object as its contents may change in "const" calls, while the rest
    /// of this object does not.  (At alternative would be to declare it as
    /// "mutable".)
    boost::scoped_ptr<MySqlLease6Exchange> exchange6_;
437
    MYSQL*              mysql_;                 ///< MySQL context object
438
    std::vector<std::string> text_statements_;  ///< Raw text of statements
439
    std::vector<MYSQL_STMT*> statements_;       ///< Prepared statements
440
441
442
443
444
};

}; // end of isc::dhcp namespace
}; // end of isc namespace

445
#endif // MYSQL_LEASE_MGR_H