1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 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
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
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
144
145
146
147
148
149
150
151
152
153
154
155
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
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
// Copyright (C) 2013-2024 Internet Systems Consortium, Inc. ("ISC")
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include <config.h>

#include <d2/d2_update_mgr.h>
#include <d2/nc_add.h>
#include <d2/nc_remove.h>
#include <d2/simple_add.h>
#include <d2/simple_remove.h>
#include <d2/check_exists_add.h>
#include <d2/check_exists_remove.h>
#include <d2/simple_add_without_dhcid.h>
#include <d2/simple_remove_without_dhcid.h>

#include <sstream><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <iostream><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <vector><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.

namespace isc {
namespace d2 {

const size_t D2UpdateMgr::MAX_TRANSACTIONS_DEFAULT;

D2UpdateMgr::D2UpdateMgr(D2QueueMgrPtr& queue_mgr, D2CfgMgrPtr& cfg_mgr,
                         asiolink::IOServicePtr& io_service,
                         const size_t max_transactions)
    :queue_mgr_(queue_mgr), cfg_mgr_(cfg_mgr), io_service_(io_service) {
    if (!queue_mgr_) {
        isc_throw(D2UpdateMgrError, "D2UpdateMgr queue manager cannot be null");
    }

    if (!cfg_mgr_) {
        isc_throw(D2UpdateMgrError,
                  "D2UpdateMgr configuration manager cannot be null");
    }

    if (!io_service_) {
        isc_throw(D2UpdateMgrError, "IOServicePtr cannot be null");
    }

    // Use setter to do validation.
    setMaxTransactions(max_transactions);
}

D2UpdateMgr::~D2UpdateMgr() {
    transaction_list_.clear();
}

void D2UpdateMgr::sweep() {
    // cleanup finished transactions;
    checkFinishedTransactions();

    // if the queue isn't empty, find the next suitable job and
    // start a transaction for it.
    // @todo - Do we want to queue max transactions? The logic here will only
    // start one new transaction per invocation.  On the other hand a busy
    // system will generate many IO events and this method will be called
    // frequently.  It will likely achieve max transactions quickly on its own.
    if (getQueueCount() > 0) {
        if (getTransactionCount() >= max_transactions_) {
            LOG_DEBUG(dhcp_to_d2_logger, isc::log::DBGLVL_TRACE_DETAIL_DATA,
                      DHCP_DDNS_AT_MAX_TRANSACTIONS).arg(getQueueCount())
                      .arg(getMaxTransactions());

            return;
        }

        // We are not at maximum transactions, so pick and start the next job.
        pickNextJob();
    }
}

void
D2UpdateMgr::checkFinishedTransactions() {
    // Cycle through transaction list and do whatever needs to be done
    // for finished transactions.
    // At the moment all we do is remove them from the list. This is likely
    // to expand as DHCP_DDNS matures.
    // NOTE: One must use postfix increments of the iterator on the calls
    // to erase.  This replaces the old iterator which becomes invalid by the
    // erase with the next valid iterator.  Prefix incrementing will not
    // work.
    TransactionList::iterator it = transaction_list_.begin();
    while (it != transaction_list_.end()) {
        NameChangeTransactionPtr trans = (*it).second;
        if (trans->isModelDone()) {
            // @todo Additional actions based on NCR status could be
            // performed here.
            transaction_list_.erase(it++);
        } else {
            ++it;
        }
    }
}

void D2UpdateMgr::pickNextJob() {
    // Start at the front of the queue, looking for the first entry for
    // which no transaction is in progress.  If we find an eligible entry
    // remove it from the queue and make a transaction for it.  If the
    // transaction creation fails try the next entry in the queue.
    // Requests and transactions are associated by DHCID.  If a request has
    // the same DHCID as a transaction, they are presumed to be for the same
    // "end user".
    size_t queue_count = getQueueCount();
    for (size_t index = 0; index < queue_count; ) {
        dhcp_ddns::NameChangeRequestPtr found_ncr = queue_mgr_->peekAt(index);
        if (hasTransaction(found_ncr->getDhcid())) {
            // Leave it on the queue, move on to the next.
            ++index;
        } else {
            // Dequeue it and try to make transaction for it.
            queue_mgr_->dequeueAt(index);
            if (makeTransaction(found_ncr)) {
                return;
            }

            // One less in the queue.
            --queue_count;
        }
    }

    // There were no eligible jobs. All of the current DHCIDs already have
    // transactions pending.
    LOG_DEBUG(dhcp_to_d2_logger, isc::log::DBGLVL_TRACE_DETAIL_DATA,
              DHCP_DDNS_NO_ELIGIBLE_JOBS)
        .arg(getQueueCount()).arg(getTransactionCount());
}

bool
D2UpdateMgr::makeTransaction(dhcp_ddns::NameChangeRequestPtr& next_ncr) {
    // First lets ensure there is not a transaction in progress for this
    // DHCID. (pickNextJob should ensure this, as it is the only real caller
    // but for safety's sake we'll check).
    const TransactionKey& key = next_ncr->getDhcid();
    if (findTransaction(key) != transactionListEnd()) {
        // This is programmatic error.  Caller(s) should be checking this.
        isc_throw(D2UpdateMgrError, "Transaction already in progress for: "
            << key.toStr());
    }

    int direction_count = 0;
    // If forward change is enabled, match to forward servers.
    DdnsDomainPtr forward_domain;
    if (next_ncr->isForwardChange()) {
        if (!cfg_mgr_->forwardUpdatesEnabled()) {
            next_ncr->setForwardChange(false);
            LOG_DEBUG(dhcp_to_d2_logger, isc::log::DBGLVL_TRACE_DETAIL_DATA,
                      DHCP_DDNS_FWD_REQUEST_IGNORED)
                      .arg(next_ncr->getRequestId())
                      .arg(next_ncr->toText());
        } else {
            bool matched = cfg_mgr_->matchForward(next_ncr->getFqdn(),
                                                  forward_domain);
            // Could not find a match for forward DNS server. Log it and get
            // out. This has the net affect of dropping the request on the
            // floor.
            if (!matched) {
                LOG_ERROR(dhcp_to_d2_logger, DHCP_DDNS_NO_FWD_MATCH_ERROR)
                          .arg(next_ncr->getRequestId())
                          .arg(next_ncr->toText());
                return (false);
            }

            ++direction_count;
        }
    }

    // If reverse change is enabled, match to reverse servers.
    DdnsDomainPtr reverse_domain;
    if (next_ncr->isReverseChange()) {
        if (!cfg_mgr_->reverseUpdatesEnabled()) {
            next_ncr->setReverseChange(false);
            LOG_DEBUG(dhcp_to_d2_logger, isc::log::DBGLVL_TRACE_DETAIL_DATA,
                      DHCP_DDNS_REV_REQUEST_IGNORED)
                      .arg(next_ncr->getRequestId())
                      .arg(next_ncr->toText());
        } else {
            bool matched = cfg_mgr_->matchReverse(next_ncr->getIpAddress(),
                                                  reverse_domain);
            // Could not find a match for reverse DNS server. Log it and get
            // out. This has the net affect of dropping the request on the
            // floor.
            if (!matched) {
                LOG_ERROR(dhcp_to_d2_logger, DHCP_DDNS_NO_REV_MATCH_ERROR)
                          .arg(next_ncr->getRequestId())
                          .arg(next_ncr->toText());
                return (false);
            }

            ++direction_count;
        }
    }

    // If there is nothing to actually do, then the request falls on the floor.
    // Should we log this?
    if (!direction_count) {
        LOG_DEBUG(dhcp_to_d2_logger, isc::log::DBGLVL_TRACE_DETAIL_DATA,
                  DHCP_DDNS_REQUEST_DROPPED)
                  .arg(next_ncr->getRequestId())
                  .arg(next_ncr->toText());
        return (false);
    }

    // We matched to the required servers, so construct the transaction.
    // @todo If multi-threading is implemented, one would pass in an
    // empty IOServicePtr, rather than our instance value.  This would cause
    // the transaction to instantiate its own, separate IOService to handle
    // the transaction's IO.
    NameChangeTransactionPtr trans;
    if (next_ncr->getChangeType() == dhcp_ddns::CHG_ADD) {
        switch(next_ncr->getConflictResolutionMode()) {
        case dhcp_ddns::CHECK_WITH_DHCID:
            trans.reset(new NameAddTransaction(io_service_, next_ncr,
                                               forward_domain, reverse_domain,
                                               cfg_mgr_));
            break;
        case dhcp_ddns::CHECK_EXISTS_WITH_DHCID:
            trans.reset(new CheckExistsAddTransaction(io_service_, next_ncr,
                                                      forward_domain, reverse_domain,
                                                      cfg_mgr_));
            break;
        case dhcp_ddns::NO_CHECK_WITHOUT_DHCID:
            trans.reset(new SimpleAddWithoutDHCIDTransaction(io_service_, next_ncr,
                                                             forward_domain, reverse_domain,
                                                             cfg_mgr_));
            break;
        default:
            // dhcp_ddns::NO_CHECK_WITH_DHCID
            trans.reset(new SimpleAddTransaction(io_service_, next_ncr,
                                                 forward_domain, reverse_domain,
                                                 cfg_mgr_));
            break;
        }
    } else {
        switch(next_ncr->getConflictResolutionMode()) {
        case dhcp_ddns::CHECK_WITH_DHCID:
            trans.reset(new NameRemoveTransaction(io_service_, next_ncr,
                                                  forward_domain, reverse_domain,
                                                  cfg_mgr_));
            break;
        case dhcp_ddns::CHECK_EXISTS_WITH_DHCID:
            trans.reset(new CheckExistsRemoveTransaction(io_service_, next_ncr,
                                                         forward_domain, reverse_domain,
                                                         cfg_mgr_));
            break;
        case dhcp_ddns::NO_CHECK_WITHOUT_DHCID:
            trans.reset(new SimpleRemoveWithoutDHCIDTransaction(io_service_, next_ncr,
                                                                forward_domain, reverse_domain,
                                                                cfg_mgr_));
            break;
        default:
            // dhcp_ddns::NO_CHECK_WITH_DHCID
            trans.reset(new SimpleRemoveTransaction(io_service_, next_ncr,
                                                    forward_domain, reverse_domain,
                                                    cfg_mgr_));
            break;
        }
    }

    // Add the new transaction to the list.
    transaction_list_[key] = trans;

    // Start it.
    trans->startTransaction();
    return (true);
}

TransactionList::iterator
D2UpdateMgr::findTransaction(const TransactionKey& key) {
    return (transaction_list_.find(key));
}

bool
D2UpdateMgr::hasTransaction(const TransactionKey& key) {
   return (findTransaction(key) != transactionListEnd());
}

void
D2UpdateMgr::removeTransaction(const TransactionKey& key) {
    TransactionList::iterator pos = findTransaction(key);
    if (pos != transactionListEnd()) {
        transaction_list_.erase(pos);
    }
}

TransactionList::iterator
D2UpdateMgr::transactionListBegin() {
    return (transaction_list_.begin());
}

TransactionList::iterator
D2UpdateMgr::transactionListEnd() {
    return (transaction_list_.end());
}

void
D2UpdateMgr::clearTransactionList() {
    // @todo for now this just wipes them out. We might need something
    // more elegant, that allows a cancel first.
    transaction_list_.clear();
}

void
D2UpdateMgr::setMaxTransactions(const size_t new_trans_max) {
    // Obviously we need at room for at least one transaction.
    if (new_trans_max < 1) {
        isc_throw(D2UpdateMgrError, "D2UpdateMgr"
                  " maximum transactions limit must be greater than zero");
    }

    // Do not allow the list maximum to be set to less then current list size.
    if (new_trans_max < getTransactionCount()) {
        isc_throw(D2UpdateMgrError, "D2UpdateMgr maximum transaction limit "
                  "cannot be less than the current transaction count :"
                  << getTransactionCount());
    }

    max_transactions_ = new_trans_max;
}

size_t
D2UpdateMgr::getQueueCount() const {
    return (queue_mgr_->getQueueSize());
}

size_t
D2UpdateMgr::getTransactionCount() const {
    return (transaction_list_.size());
}


} // namespace isc::d2
} // namespace isc