alloc_engine.cc 9.42 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

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
33
34
isc::asiolink::IOAddress
AllocEngine::IterativeAllocator::increaseAddress(const isc::asiolink::IOAddress& addr) {
    uint8_t packed[V6ADDRESS_LEN];
    int len;
35
36

    // First we copy the whole address as 16 bytes.
37
38
    if (addr.getFamily()==AF_INET) {
        // IPv4
39
        std::memcpy(packed, addr.getAddress().to_v4().to_bytes().data(), 4);
40
41
42
        len = 4;
    } else {
        // IPv6
43
        std::memcpy(packed, addr.getAddress().to_v6().to_bytes().data(), 16);
44
45
46
        len = 16;
    }

47
    for (int i = len - 1; i >= 0; --i) {
Tomek Mrugalski's avatar
Tomek Mrugalski committed
48
        ++packed[i];
49
50
51
52
53
        if (packed[i] != 0) {
            break;
        }
    }

54
    return (IOAddress::fromBytes(addr.getFamily(), packed));
55
56
57
}


58
59
isc::asiolink::IOAddress
AllocEngine::IterativeAllocator::pickAddress(const Subnet6Ptr& subnet,
60
61
                                             const DuidPtr&,
                                             const IOAddress&) {
62

63
    // Let's get the last allocated address. It is usually set correctly,
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
    // but there are times when it won't be (like after removing a pool or
    // perhaps restaring the server).
    IOAddress last = subnet->getLastAllocated();

    const Pool6Collection& pools = subnet->getPools();

    if (pools.size() == 0) {
        isc_throw(AllocFailed, "No pools defined in selected subnet");
    }

    // first we need to find a pool the last address belongs to.
    Pool6Collection::const_iterator it;
    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)) {
97
        // the next one is in the pool as well, so we haven't hit pool boundary yet
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
        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);
}

118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
AllocEngine::HashedAllocator::HashedAllocator()
    :Allocator() {
    isc_throw(NotImplemented, "Hashed allocator is not implemented");
}


isc::asiolink::IOAddress
AllocEngine::HashedAllocator::pickAddress(const Subnet6Ptr&,
                                             const DuidPtr&,
                                             const IOAddress&) {
    isc_throw(NotImplemented, "Hashed allocator is not implemented");
}

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


isc::asiolink::IOAddress
AllocEngine::RandomAllocator::pickAddress(const Subnet6Ptr&,
                                             const DuidPtr&,
                                             const IOAddress&) {
    isc_throw(NotImplemented, "Random allocator is not implemented");
}

144
145
146
147
148

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

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

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

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

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

184
185
    // check if the hint is in pool and is available
    if (subnet->inPool(hint)) {
186
        existing = LeaseMgrFactory::instance().getLease6(hint);
187
188
189
190
191
        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
Tomek Mrugalski's avatar
Tomek Mrugalski committed
192
            Lease6Ptr lease = createLease(subnet, duid, iaid, hint, fake_allocation);
193
194
195
196
197
198
199
200

            // 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);
            }
        }
201
202
    }

203
204
205
206
207
208
209
    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

210
        Lease6Ptr existing = LeaseMgrFactory::instance().getLease6(candidate);
211
212
213
        // there's no existing lease for selected candidate, so it is
        // free. Let's allocate it.
        if (!existing) {
Tomek Mrugalski's avatar
Tomek Mrugalski committed
214
215
            Lease6Ptr lease = createLease(subnet, duid, iaid, candidate,
                                          fake_allocation);
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
            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.
        }

        // 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");
}

Lease6Ptr AllocEngine::createLease(const Subnet6Ptr& subnet,
                                   const DuidPtr& duid,
                                   uint32_t iaid,
237
                                   const IOAddress& addr,
Tomek Mrugalski's avatar
Tomek Mrugalski committed
238
                                   bool fake_allocation /*= false */ ) {
239

240
241
242
    Lease6Ptr lease(new Lease6(Lease6::LEASE_IA_NA, addr, duid, iaid,
                               subnet->getPreferred(), subnet->getValid(),
                               subnet->getT1(), subnet->getT2(), subnet->getID()));
243

Tomek Mrugalski's avatar
Tomek Mrugalski committed
244
    if (!fake_allocation) {
245
        // That is a real (REQUEST) allocation
246
        bool status = LeaseMgrFactory::instance().addLease(lease);
247

248
249
250
251
252
253
254
255
256
257
        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());
        }
258
    } else {
259
260
261
262
        // 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.
263
        Lease6Ptr existing = LeaseMgrFactory::instance().getLease6(addr);
264
265
266
267
268
        if (!existing) {
            return (lease);
        } else {
            return (Lease6Ptr());
        }
269
270
271
272
    }
}

AllocEngine::~AllocEngine() {
Tomek Mrugalski's avatar
Tomek Mrugalski committed
273
    // no need to delete allocator. smart_ptr will do the trick for us
274
275
276
277
}

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