alloc_engine.cc 21 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
#include <dhcpsrv/alloc_engine.h>
#include <dhcpsrv/lease_mgr_factory.h>
17

18
#include <cstring>
19
#include <vector>
20
#include <string.h>
21

22
23
24
25
26
27
28
29
30
using namespace isc::asiolink;

namespace isc {
namespace dhcp {

AllocEngine::IterativeAllocator::IterativeAllocator()
    :Allocator() {
}

31
32
isc::asiolink::IOAddress
AllocEngine::IterativeAllocator::increaseAddress(const isc::asiolink::IOAddress& addr) {
33
34
35
36
37
38
39
40
41
    // Get a buffer holding an address.
    const std::vector<uint8_t>& vec = addr.toBytes();
    // Get the address length.
    const int len = vec.size();

    // Since the same array will be used to hold the IPv4 and IPv6
    // address we have to make sure that the size of the array
    // we allocate will work for both types of address.
    BOOST_STATIC_ASSERT(V4ADDRESS_LEN <= V6ADDRESS_LEN);
42
43
    uint8_t packed[V6ADDRESS_LEN];

44
45
46
    // Copy the address. It can be either V4 or V6.
    std::memcpy(packed, &vec[0], len);

47
    // Start increasing the least significant byte
48
    for (int i = len - 1; i >= 0; --i) {
Tomek Mrugalski's avatar
Tomek Mrugalski committed
49
        ++packed[i];
50
        // if we haven't overflowed (0xff -> 0x0), than we are done
51
52
53
54
55
        if (packed[i] != 0) {
            break;
        }
    }

56
    return (IOAddress::fromBytes(addr.getFamily(), packed));
57
58
59
}


60
isc::asiolink::IOAddress
61
AllocEngine::IterativeAllocator::pickAddress(const SubnetPtr& subnet,
62
63
                                             const DuidPtr&,
                                             const IOAddress&) {
64

65
    // Let's get the last allocated address. It is usually set correctly,
66
67
68
69
    // but there are times when it won't be (like after removing a pool or
    // perhaps restaring the server).
    IOAddress last = subnet->getLastAllocated();

70
    const PoolCollection& pools = subnet->getPools();
71

72
    if (pools.empty()) {
73
74
75
76
        isc_throw(AllocFailed, "No pools defined in selected subnet");
    }

    // first we need to find a pool the last address belongs to.
77
    PoolCollection::const_iterator it;
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
    for (it = pools.begin(); it != pools.end(); ++it) {
        if ((*it)->inRange(last)) {
            break;
        }
    }

    // last one was bogus for one of several reasons:
    // - we just booted up and that's the first address we're allocating
    // - a subnet was removed or other reconfiguration just completed
    // - perhaps allocation algorithm was changed
    if (it == pools.end()) {
        // ok to access first element directly. We checked that pools is non-empty
        IOAddress next = pools[0]->getFirstAddress();
        subnet->setLastAllocated(next);
        return (next);
    }

    // Ok, we have a pool that the last address belonged to, let's use it.

    IOAddress next = increaseAddress(last); // basically addr++
    if ((*it)->inRange(next)) {
99
        // the next one is in the pool as well, so we haven't hit pool boundary yet
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
        subnet->setLastAllocated(next);
        return (next);
    }

    // We hit pool boundary, let's try to jump to the next pool and try again
    ++it;
    if (it == pools.end()) {
        // Really out of luck today. That was the last pool. Let's rewind
        // to the beginning.
        next = pools[0]->getFirstAddress();
        subnet->setLastAllocated(next);
        return (next);
    }

    // there is a next pool, let's try first adddress from it
    next = (*it)->getFirstAddress();
    subnet->setLastAllocated(next);
    return (next);
}

120
121
122
123
124
125
126
AllocEngine::HashedAllocator::HashedAllocator()
    :Allocator() {
    isc_throw(NotImplemented, "Hashed allocator is not implemented");
}


isc::asiolink::IOAddress
127
128
129
AllocEngine::HashedAllocator::pickAddress(const SubnetPtr&,
                                          const DuidPtr&,
                                          const IOAddress&) {
130
131
132
133
134
135
136
137
138
139
    isc_throw(NotImplemented, "Hashed allocator is not implemented");
}

AllocEngine::RandomAllocator::RandomAllocator()
    :Allocator() {
    isc_throw(NotImplemented, "Random allocator is not implemented");
}


isc::asiolink::IOAddress
140
141
142
AllocEngine::RandomAllocator::pickAddress(const SubnetPtr&,
                                          const DuidPtr&,
                                          const IOAddress&) {
143
144
145
    isc_throw(NotImplemented, "Random allocator is not implemented");
}

146
147
148
149
150

AllocEngine::AllocEngine(AllocType engine_type, unsigned int attempts)
    :attempts_(attempts) {
    switch (engine_type) {
    case ALLOC_ITERATIVE:
Tomek Mrugalski's avatar
Tomek Mrugalski committed
151
        allocator_ = boost::shared_ptr<Allocator>(new IterativeAllocator());
152
153
        break;
    case ALLOC_HASHED:
Tomek Mrugalski's avatar
Tomek Mrugalski committed
154
        allocator_ = boost::shared_ptr<Allocator>(new HashedAllocator());
155
156
        break;
    case ALLOC_RANDOM:
Tomek Mrugalski's avatar
Tomek Mrugalski committed
157
        allocator_ = boost::shared_ptr<Allocator>(new RandomAllocator());
158
159
160
161
162
163
164
165
166
167
168
        break;

    default:
        isc_throw(BadValue, "Invalid/unsupported allocation algorithm");
    }
}

Lease6Ptr
AllocEngine::allocateAddress6(const Subnet6Ptr& subnet,
                              const DuidPtr& duid,
                              uint32_t iaid,
169
                              const IOAddress& hint,
Tomek Mrugalski's avatar
Tomek Mrugalski committed
170
171
                              bool fake_allocation /* = false */ ) {

172
173
174
175
176
177
    // That check is not necessary. We create allocator in AllocEngine
    // constructor
    if (!allocator_) {
        isc_throw(InvalidOperation, "No allocator selected");
    }

178
    // check if there's existing lease for that subnet/duid/iaid combination.
179
    Lease6Ptr existing = LeaseMgrFactory::instance().getLease6(*duid, iaid, subnet->getID());
180
181
182
183
184
185
    if (existing) {
        // we have a lease already. This is a returning client, probably after
        // his reboot.
        return (existing);
    }

186
187
    // check if the hint is in pool and is available
    if (subnet->inPool(hint)) {
188
        existing = LeaseMgrFactory::instance().getLease6(hint);
189
190
191
192
193
        if (!existing) {
            /// @todo: check if the hint is reserved once we have host support
            /// implemented

            // the hint is valid and not currently used, let's create a lease for it
194
            Lease6Ptr lease = createLease6(subnet, duid, iaid, hint, fake_allocation);
195
196
197
198
199
200
201

            // It can happen that the lease allocation failed (we could have lost
            // the race condition. That means that the hint is lo longer usable and
            // we need to continue the regular allocation path.
            if (lease) {
                return (lease);
            }
202
203
204
205
206
207
        } else {
            if (existing->expired()) {
                return (reuseExpiredLease(existing, subnet, duid, iaid,
                                          fake_allocation));
            }

208
        }
209
210
    }

Tomek Mrugalski's avatar
Tomek Mrugalski committed
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
    // Hint is in the pool but is not available. Search the pool until first of
    // the following occurs:
    // - we find a free address
    // - we find an address for which the lease has expired
    // - we exhaust number of tries
    //
    // @todo: Current code does not handle pool exhaustion well. It will be
    // improved. Current problems:
    // 1. with attempts set to too large value (e.g. 1000) and a small pool (e.g.
    // 10 addresses), we will iterate over it 100 times before giving up
    // 2. attempts 0 mean unlimited (this is really UINT_MAX, not infinite)
    // 3. the whole concept of infinite attempts is just asking for infinite loop
    // We may consider some form or reference counting (this pool has X addresses
    // left), but this has one major problem. We exactly control allocation
    // moment, but we currently do not control expiration time at all

227
228
229
230
231
232
233
    unsigned int i = attempts_;
    do {
        IOAddress candidate = allocator_->pickAddress(subnet, duid, hint);

        /// @todo: check if the address is reserved once we have host support
        /// implemented

234
        Lease6Ptr existing = LeaseMgrFactory::instance().getLease6(candidate);
235
        if (!existing) {
Tomek Mrugalski's avatar
Tomek Mrugalski committed
236
237
            // there's no existing lease for selected candidate, so it is
            // free. Let's allocate it.
238
            Lease6Ptr lease = createLease6(subnet, duid, iaid, candidate,
Tomek Mrugalski's avatar
Tomek Mrugalski committed
239
                                          fake_allocation);
240
241
242
243
244
245
246
            if (lease) {
                return (lease);
            }

            // Although the address was free just microseconds ago, it may have
            // been taken just now. If the lease insertion fails, we continue
            // allocation attempts.
247
248
249
250
251
        } else {
            if (existing->expired()) {
                return (reuseExpiredLease(existing, subnet, duid, iaid,
                                          fake_allocation));
            }
252
253
254
255
256
257
258
259
260
261
262
        }

        // continue trying allocation until we run out of attempts
        // (or attempts are set to 0, which means infinite)
        --i;
    } while ( i || !attempts_);

    isc_throw(AllocFailed, "Failed to allocate address after " << attempts_
              << " tries");
}

263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
Lease4Ptr
AllocEngine::allocateAddress4(const SubnetPtr& subnet,
                              const ClientIdPtr& clientid,
                              const HWAddrPtr& hwaddr,
                              const IOAddress& hint,
                              bool fake_allocation /* = false */ ) {

    // That check is not necessary. We create allocator in AllocEngine
    // constructor
    if (!allocator_) {
        isc_throw(InvalidOperation, "No allocator selected");
    }

    // check if there's existing lease for that subnet/clientid/hwaddr combination.
    Lease4Ptr existing = LeaseMgrFactory::instance().getLease4(hwaddr->hwaddr_, subnet->getID());
    if (existing) {
        // we have a lease already. This is a returning client, probably after
        // his reboot.
281
282
283
284
285
286
287
288
289

        existing = renewLease4(subnet, clientid, hwaddr, existing, fake_allocation);

        if (existing) {
            return (existing);
        }

        // If renewal failed (e.g. the lease no longer matches current configuration)
        // let's continue allocation process
290
291
    }

292
293
294
295
296
    if (clientid) {
        existing = LeaseMgrFactory::instance().getLease4(*clientid, subnet->getID());
        if (existing) {
            // we have a lease already. This is a returning client, probably after
            // his reboot.
297

298
299
300
301
302
303
304
305
            existing = renewLease4(subnet, clientid, hwaddr, existing, fake_allocation);

            // @todo: produce a warning. We haven't found him using MAC address, but
            // we found him using client-id
            if (existing) {
                return (existing);
            }
        }
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
    }

    // check if the hint is in pool and is available
    if (subnet->inPool(hint)) {
        existing = LeaseMgrFactory::instance().getLease4(hint);
        if (!existing) {
            /// @todo: check if the hint is reserved once we have host support
            /// implemented

            // the hint is valid and not currently used, let's create a lease for it
            Lease4Ptr lease = createLease4(subnet, clientid, hwaddr, hint, fake_allocation);

            // It can happen that the lease allocation failed (we could have lost
            // the race condition. That means that the hint is lo longer usable and
            // we need to continue the regular allocation path.
            if (lease) {
                return (lease);
            }
        } else {
            if (existing->expired()) {
                return (reuseExpiredLease(existing, subnet, clientid, hwaddr,
                                          fake_allocation));
            }

        }
    }

    // Hint is in the pool but is not available. Search the pool until first of
    // the following occurs:
    // - we find a free address
    // - we find an address for which the lease has expired
    // - we exhaust number of tries
    //
    // @todo: Current code does not handle pool exhaustion well. It will be
    // improved. Current problems:
    // 1. with attempts set to too large value (e.g. 1000) and a small pool (e.g.
    // 10 addresses), we will iterate over it 100 times before giving up
    // 2. attempts 0 mean unlimited (this is really UINT_MAX, not infinite)
    // 3. the whole concept of infinite attempts is just asking for infinite loop
    // We may consider some form or reference counting (this pool has X addresses
    // left), but this has one major problem. We exactly control allocation
    // moment, but we currently do not control expiration time at all

    unsigned int i = attempts_;
    do {
        IOAddress candidate = allocator_->pickAddress(subnet, clientid, hint);

        /// @todo: check if the address is reserved once we have host support
        /// implemented

        Lease4Ptr existing = LeaseMgrFactory::instance().getLease4(candidate);
        if (!existing) {
            // there's no existing lease for selected candidate, so it is
            // free. Let's allocate it.
            Lease4Ptr lease = createLease4(subnet, clientid, hwaddr, candidate,
                                          fake_allocation);
            if (lease) {
                return (lease);
            }

            // Although the address was free just microseconds ago, it may have
            // been taken just now. If the lease insertion fails, we continue
            // allocation attempts.
        } else {
            if (existing->expired()) {
                return (reuseExpiredLease(existing, subnet, clientid, hwaddr,
                                          fake_allocation));
            }
        }

        // continue trying allocation until we run out of attempts
        // (or attempts are set to 0, which means infinite)
        --i;
    } while ( i || !attempts_);

    isc_throw(AllocFailed, "Failed to allocate address after " << attempts_
              << " tries");
}

385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
Lease4Ptr AllocEngine::renewLease4(const SubnetPtr& subnet,
                                   const ClientIdPtr& clientid,
                                   const HWAddrPtr& hwaddr,
                                   const Lease4Ptr& lease,
                                   bool fake_allocation /* = false */) {

    lease->subnet_id_ = subnet->getID();
    lease->hwaddr_ = hwaddr->hwaddr_;
    lease->client_id_ = clientid;
    lease->cltt_ = time(NULL);
    lease->t1_ = subnet->getT1();
    lease->t2_ = subnet->getT2();
    lease->valid_lft_ = subnet->getValid();

    if (!fake_allocation) {
        // for REQUEST we do update the lease
        LeaseMgrFactory::instance().updateLease4(lease);
    }

    return (lease);
}

407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
Lease6Ptr AllocEngine::reuseExpiredLease(Lease6Ptr& expired,
                                         const Subnet6Ptr& subnet,
                                         const DuidPtr& duid,
                                         uint32_t iaid,
                                         bool fake_allocation /*= false */ ) {

    if (!expired->expired()) {
        isc_throw(BadValue, "Attempt to recycle lease that is still valid");
    }

    // address, lease type and prefixlen (0) stay the same
    expired->iaid_ = iaid;
    expired->duid_ = duid;
    expired->preferred_lft_ = subnet->getPreferred();
    expired->valid_lft_ = subnet->getValid();
    expired->t1_ = subnet->getT1();
    expired->t2_ = subnet->getT2();
    expired->cltt_ = time(NULL);
    expired->subnet_id_ = subnet->getID();
    expired->fixed_ = false;
    expired->hostname_ = std::string("");
    expired->fqdn_fwd_ = false;
    expired->fqdn_rev_ = false;

    /// @todo: log here that the lease was reused (there's ticket #2524 for
    /// logging in libdhcpsrv)

    if (!fake_allocation) {
        // for REQUEST we do update the lease
        LeaseMgrFactory::instance().updateLease6(expired);
Tomek Mrugalski's avatar
Tomek Mrugalski committed
437
    }
438
439
440
441
442
443
444
445
446

    // We do nothing for SOLICIT. We'll just update database when
    // the client gets back to us with REQUEST message.

    // it's not really expired at this stage anymore - let's return it as
    // an updated lease
    return (expired);
}

447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
Lease4Ptr AllocEngine::reuseExpiredLease(Lease4Ptr& expired,
                                         const SubnetPtr& subnet,
                                         const ClientIdPtr& clientid,
                                         const HWAddrPtr& hwaddr,
                                         bool fake_allocation /*= false */ ) {

    if (!expired->expired()) {
        isc_throw(BadValue, "Attempt to recycle lease that is still valid");
    }

    // address, lease type and prefixlen (0) stay the same
    expired->client_id_ = clientid;
    expired->hwaddr_ = hwaddr->hwaddr_;
    expired->valid_lft_ = subnet->getValid();
    expired->t1_ = subnet->getT1();
    expired->t2_ = subnet->getT2();
    expired->cltt_ = time(NULL);
    expired->subnet_id_ = subnet->getID();
    expired->fixed_ = false;
    expired->hostname_ = std::string("");
    expired->fqdn_fwd_ = false;
    expired->fqdn_rev_ = false;

    /// @todo: log here that the lease was reused (there's ticket #2524 for
    /// logging in libdhcpsrv)

    if (!fake_allocation) {
        // for REQUEST we do update the lease
        LeaseMgrFactory::instance().updateLease4(expired);
    }

    // We do nothing for SOLICIT. We'll just update database when
    // the client gets back to us with REQUEST message.

    // it's not really expired at this stage anymore - let's return it as
    // an updated lease
    return (expired);
}

486
487
488
489
490
Lease6Ptr AllocEngine::createLease6(const Subnet6Ptr& subnet,
                                    const DuidPtr& duid,
                                    uint32_t iaid,
                                    const IOAddress& addr,
                                    bool fake_allocation /*= false */ ) {
491

492
493
494
    Lease6Ptr lease(new Lease6(Lease6::LEASE_IA_NA, addr, duid, iaid,
                               subnet->getPreferred(), subnet->getValid(),
                               subnet->getT1(), subnet->getT2(), subnet->getID()));
495

Tomek Mrugalski's avatar
Tomek Mrugalski committed
496
    if (!fake_allocation) {
497
        // That is a real (REQUEST) allocation
498
        bool status = LeaseMgrFactory::instance().addLease(lease);
499

500
501
502
503
504
505
506
507
508
509
        if (status) {

            return (lease);
        } else {
            // One of many failures with LeaseMgr (e.g. lost connection to the
            // database, database failed etc.). One notable case for that
            // is that we are working in multi-process mode and we lost a race
            // (some other process got that address first)
            return (Lease6Ptr());
        }
510
    } else {
511
512
513
514
        // That is only fake (SOLICIT without rapid-commit) allocation

        // It is for advertise only. We should not insert the lease into LeaseMgr,
        // but rather check that we could have inserted it.
515
        Lease6Ptr existing = LeaseMgrFactory::instance().getLease6(addr);
516
517
518
519
520
        if (!existing) {
            return (lease);
        } else {
            return (Lease6Ptr());
        }
521
522
523
    }
}

524
525
526
527
528
529
530
531
532
Lease4Ptr AllocEngine::createLease4(const SubnetPtr& subnet,
                                    const DuidPtr& clientid,
                                    const HWAddrPtr& hwaddr,
                                    const IOAddress& addr,
                                    bool fake_allocation /*= false */ ) {
    if (!hwaddr) {
        isc_throw(BadValue, "Can't create a lease with NULL HW address");
    }
    time_t now = time(NULL);
533
534
535
536
537
538
539

    // @todo: remove this kludge after ticket #2590 is implemented
    std::vector<uint8_t> local_copy;
    if (clientid) {
        local_copy = clientid->getDuid();
    }

540
    Lease4Ptr lease(new Lease4(addr, &hwaddr->hwaddr_[0], hwaddr->hwaddr_.size(),
541
542
543
                               &local_copy[0], local_copy.size(), subnet->getValid(),
                               subnet->getT1(), subnet->getT2(), now,
                               subnet->getID()));
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572

    if (!fake_allocation) {
        // That is a real (REQUEST) allocation
        bool status = LeaseMgrFactory::instance().addLease(lease);

        if (status) {
            return (lease);
        } else {
            // One of many failures with LeaseMgr (e.g. lost connection to the
            // database, database failed etc.). One notable case for that
            // is that we are working in multi-process mode and we lost a race
            // (some other process got that address first)
            return (Lease4Ptr());
        }
    } else {
        // That is only fake (DISCOVER) allocation

        // It is for OFFER only. We should not insert the lease into LeaseMgr,
        // but rather check that we could have inserted it.
        Lease4Ptr existing = LeaseMgrFactory::instance().getLease4(addr);
        if (!existing) {
            return (lease);
        } else {
            return (Lease4Ptr());
        }
    }
}


573
AllocEngine::~AllocEngine() {
Tomek Mrugalski's avatar
Tomek Mrugalski committed
574
    // no need to delete allocator. smart_ptr will do the trick for us
575
576
577
578
}

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