mysql_cb_impl.cc 44.3 KB
Newer Older
1
// Copyright (C) 2018-2020 Internet Systems Consortium, Inc. ("ISC")
2 3 4 5 6
//
// 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/.

7
#include <config.h>
8 9
#include <mysql_cb_impl.h>
#include <asiolink/io_address.h>
10
#include <config_backend/constants.h>
11 12
#include <dhcp/option_space.h>
#include <util/buffer.h>
13 14 15 16 17
#include <mysql.h>
#include <mysqld_error.h>
#include <cstdint>
#include <utility>

18
using namespace isc::cb;
19 20
using namespace isc::data;
using namespace isc::db;
21
using namespace isc::util;
22 23 24 25

namespace isc {
namespace dhcp {

26 27 28
MySqlConfigBackendImpl::
ScopedAuditRevision::ScopedAuditRevision(MySqlConfigBackendImpl* impl,
                                         const int index,
29
                                         const ServerSelector& server_selector,
30 31 32
                                         const std::string& log_message,
                                         bool cascade_transaction)
    : impl_(impl) {
33 34 35
    impl_->createAuditRevision(index, server_selector,
                               boost::posix_time::microsec_clock::local_time(),
                               log_message,
36
                               cascade_transaction);
37 38 39 40 41 42 43
}

MySqlConfigBackendImpl::
ScopedAuditRevision::~ScopedAuditRevision() {
    impl_->clearAuditRevision();
}

44 45
MySqlConfigBackendImpl::
MySqlConfigBackendImpl(const DatabaseConnection::ParameterMap& parameters)
46
    : conn_(parameters), audit_revision_created_(false) {
47
    // Test schema version first.
48 49
    std::pair<uint32_t, uint32_t> code_version(MYSQL_SCHEMA_VERSION_MAJOR,
                                               MYSQL_SCHEMA_VERSION_MINOR);
50 51
    std::pair<uint32_t, uint32_t> db_version =
        MySqlConnection::getVersion(parameters);
52 53 54 55 56
    if (code_version != db_version) {
        isc_throw(DbOpenError, "MySQL schema version mismatch: need version: "
                  << code_version.first << "." << code_version.second
                  << " found version:  " << db_version.first << "."
                  << db_version.second);
57 58 59 60
    }

    // Open the database.
    conn_.openDatabase();
61 62 63 64 65 66 67 68 69

    // Enable autocommit. In case transaction is explicitly used, this
    // setting will be overwritten for the transaction. However, there are
    // cases when lack of autocommit could cause transactions to hang
    // until commit or rollback is explicitly called. This already
    // caused issues for some unit tests which were unable to cleanup
    // the database after the test because of pending transactions.
    // Use of autocommit will eliminate this problem.
    my_bool result = mysql_autocommit(conn_.mysql_, 1);
70
    if (result != MLM_FALSE) {
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
        isc_throw(DbOperationError, mysql_error(conn_.mysql_));
    }
}

MySqlConfigBackendImpl::~MySqlConfigBackendImpl() {
    // Free up the prepared statements, ignoring errors. (What would we do
    // about them? We're destroying this object and are not really concerned
    // with errors on a database connection that is about to go away.)
    for (int i = 0; i < conn_.statements_.size(); ++i) {
        if (conn_.statements_[i] != NULL) {
            (void) mysql_stmt_close(conn_.statements_[i]);
            conn_.statements_[i] = NULL;
        }
    }
}

87
MySqlBindingPtr
88
MySqlConfigBackendImpl::createBinding(const Triplet<uint32_t>& triplet) {
89 90 91 92 93 94
    if (triplet.unspecified()) {
        return (MySqlBinding::createNull());
    }
    return (MySqlBinding::createInteger<uint32_t>(triplet.get()));
}

95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
MySqlBindingPtr
MySqlConfigBackendImpl::createMinBinding(const Triplet<uint32_t>& triplet) {
    if (triplet.unspecified() || (triplet.getMin() == triplet.get())) {
        return (MySqlBinding::createNull());
    }
    return (MySqlBinding::createInteger<uint32_t>(triplet.getMin()));
}

MySqlBindingPtr
MySqlConfigBackendImpl::createMaxBinding(const Triplet<uint32_t>& triplet) {
    if (triplet.unspecified() || (triplet.getMax() == triplet.get())) {
        return (MySqlBinding::createNull());
    }
    return (MySqlBinding::createInteger<uint32_t>(triplet.getMax()));
}

111
Triplet<uint32_t>
112
MySqlConfigBackendImpl::createTriplet(const MySqlBindingPtr& binding) {
113 114
    if (!binding) {
        isc_throw(Unexpected, "MySQL configuration backend internal error: "
115
                  "binding pointer is NULL when creating a triplet value");
116 117 118 119 120 121 122 123 124
    }

    if (binding->amNull()) {
        return (Triplet<uint32_t>());
    }

    return (Triplet<uint32_t>(binding->getInteger<uint32_t>()));
}

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
Triplet<uint32_t>
MySqlConfigBackendImpl::createTriplet(const MySqlBindingPtr& def_binding,
                                      const MySqlBindingPtr& min_binding,
                                      const MySqlBindingPtr& max_binding) {
    if (!def_binding || !min_binding || !max_binding) {
        isc_throw(Unexpected, "MySQL configuration backend internal error: "
                  "binding pointer is NULL when creating a triplet value");
    }

    // This code assumes the database was filled using the API, e.g. it
    // is not possible (so not handled) to have only the min_binding not NULL.
    if (def_binding->amNull()) {
        return (Triplet<uint32_t>());
    }

    uint32_t value = def_binding->getInteger<uint32_t>();
    uint32_t min_value = value;
    if (!min_binding->amNull()) {
        min_value = min_binding->getInteger<uint32_t>();
    }
    uint32_t max_value = value;
    if (!max_binding->amNull()) {
        max_value = max_binding->getInteger<uint32_t>();
    }

    return (Triplet<uint32_t>(min_value, value, max_value));
}

153
void
154 155
MySqlConfigBackendImpl::createAuditRevision(const int index,
                                            const ServerSelector& server_selector,
156
                                            const boost::posix_time::ptime& audit_ts,
157 158
                                            const std::string& log_message,
                                            const bool cascade_transaction) {
159 160 161 162 163
    // Do not touch existing audit revision in case of the cascade update.
    if (audit_revision_created_) {
        return;
    }

164 165 166 167 168 169 170 171 172 173 174
    /// @todo The audit trail is not really well prepared to handle multiple server
    /// tags or no server tags. Therefore, if the server selector appears to be
    /// pointing to multiple servers, no servers or any server we simply associate the
    /// audit revision with all servers. The only case when we create a dedicated
    /// audit entry is when there is a single server tag, i.e. "all" or explicit
    /// server name. In fact, these are the most common two cases.
    std::string tag = ServerTag::ALL;
    auto tags = server_selector.getTags();
    if (tags.size() == 1) {
        tag = tags.begin()->get();
    }
175

176
    MySqlBindingCollection in_bindings = {
177
        MySqlBinding::createTimestamp(audit_ts),
178
        MySqlBinding::createString(tag),
179
        MySqlBinding::createString(log_message),
180
        MySqlBinding::createInteger<uint8_t>(static_cast<uint8_t>(cascade_transaction))
181 182
    };
    conn_.insertQuery(index, in_bindings);
183 184 185 186 187 188
    audit_revision_created_ = true;
}

void
MySqlConfigBackendImpl::clearAuditRevision() {
    audit_revision_created_ = false;
189 190
}

191 192
void
MySqlConfigBackendImpl::getRecentAuditEntries(const int index,
193
                                              const db::ServerSelector& server_selector,
194
                                              const boost::posix_time::ptime& modification_time,
195
                                              const uint64_t& modification_id,
196 197 198
                                              AuditEntryCollection& audit_entries) {
    // Create the output bindings for receiving the data.
    MySqlBindingCollection out_bindings = {
199 200 201 202 203
        MySqlBinding::createInteger<uint64_t>(), // id
        MySqlBinding::createString(AUDIT_ENTRY_OBJECT_TYPE_BUF_LENGTH), // object_type
        MySqlBinding::createInteger<uint64_t>(), // object_id
        MySqlBinding::createInteger<uint8_t>(), // modification_type
        MySqlBinding::createTimestamp(), // modification_time
204
        MySqlBinding::createInteger<uint64_t>(), // revision_id
205
        MySqlBinding::createString(AUDIT_ENTRY_LOG_MESSAGE_BUF_LENGTH) // log_message
206 207
    };

208
    auto tags = server_selector.getTags();
209 210 211

    for (auto tag : tags) {

212
        // There are only a few input bindings
213
        MySqlBindingCollection in_bindings = {
214
            MySqlBinding::createString(tag.get()),
215 216
            MySqlBinding::createTimestamp(modification_time),
            MySqlBinding::createInteger<uint64_t>(modification_id)
217 218 219 220 221 222 223 224 225 226 227
        };

        // Execute select.
        conn_.selectQuery(index, in_bindings, out_bindings,
                          [&audit_entries] (MySqlBindingCollection& out_bindings) {
             // Convert the numeric modification type into modification type enum.
            AuditEntry::ModificationType mod_type =
                static_cast<AuditEntry::ModificationType>(out_bindings[3]->getInteger<uint8_t>());

            // Create new audit entry and add it to the collection of received
            // entries.
228 229 230 231 232
            AuditEntryPtr audit_entry =
                AuditEntry::create(out_bindings[1]->getString(),
                                   out_bindings[2]->getInteger<uint64_t>(),
                                   mod_type,
                                   out_bindings[4]->getTimestamp(),
233 234
                                   out_bindings[5]->getInteger<uint64_t>(),
                                   out_bindings[6]->getStringOrDefault(""));
235 236 237
            audit_entries.insert(audit_entry);
        });
    }
238 239
}

240 241
uint64_t
MySqlConfigBackendImpl::deleteFromTable(const int index,
242 243
                                        const ServerSelector& server_selector,
                                        const std::string& operation) {
244 245 246 247 248 249
    // When deleting multiple objects we must not use ANY server.
    if (server_selector.amAny()) {
        isc_throw(InvalidOperation, "deleting multiple objects for ANY server is not"
                  " supported");
    }

250 251
    MySqlBindingCollection in_bindings;
    return (deleteFromTable(index, server_selector, operation, in_bindings));
252 253
}

254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
void
MySqlConfigBackendImpl::getGlobalParameters(const int index,
                                            const MySqlBindingCollection& in_bindings,
                                            StampedValueCollection& parameters) {
    // The following parameters from the dhcp[46]_global_parameter table are
    // returned:
    // - id
    // - name - parameter name
    // - value - parameter value
    // - modification_ts - modification timestamp.
    MySqlBindingCollection out_bindings = {
        MySqlBinding::createInteger<uint64_t>(), // id
        MySqlBinding::createString(GLOBAL_PARAMETER_NAME_BUF_LENGTH), // name
        MySqlBinding::createString(GLOBAL_PARAMETER_VALUE_BUF_LENGTH), // value
        MySqlBinding::createInteger<uint8_t>(), // parameter_type
269 270
        MySqlBinding::createTimestamp(), // modification_ts
        MySqlBinding::createString(SERVER_TAG_BUF_LENGTH) // server_tag
271 272
    };

273 274 275
    StampedValuePtr last_param;

    StampedValueCollection local_parameters;
276

277
    conn_.selectQuery(index, in_bindings, out_bindings,
278 279
                      [&last_param, &local_parameters]
                      (MySqlBindingCollection& out_bindings) {
280 281 282 283

        uint64_t id = out_bindings[0]->getInteger<uint64_t>();

        // If we're starting or if this is new parameter being processed...
284
        if (!last_param || (last_param->getId() != id)) {
285 286 287 288 289

            // parameter name
            std::string name = out_bindings[1]->getString();

            if (!name.empty()) {
290
                last_param = StampedValue::create(name,
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
                                                  out_bindings[2]->getString(),
                                                  static_cast<Element::types>
                                                  (out_bindings[3]->getInteger<uint8_t>()));

                // id
                last_param->setId(id);

                // modification_ts
                last_param->setModificationTime(out_bindings[4]->getTimestamp());

                // server_tag
                ServerTag last_param_server_tag(out_bindings[5]->getString());
                last_param->setServerTag(last_param_server_tag.get());
                // If we're fetching parameters for a given server (explicit server
                // tag is provided), it takes precedence over the same parameter
                // specified for all servers. Therefore, we check if the given
                // parameter already exists and belongs to 'all'.
                auto& index = local_parameters.get<StampedValueNameIndexTag>();
309
                auto existing = index.find(name);
310
                if (existing != index.end()) {
311 312 313 314 315 316
                    // This parameter was already fetched. Let's check if we should
                    // replace it or not.
                    if (!last_param_server_tag.amAll() && (*existing)->hasAllServerTag()) {
                        // Replace parameter specified for 'all' with the one associated
                        // with the particular server tag.
                        local_parameters.replace(existing, last_param);
317 318
                        return;
                    }
319

320 321
                }

322 323 324
                // If there is no such parameter yet or the existing parameter
                // belongs to a different server and the inserted parameter is
                // not for all servers.
325
                if ((existing == index.end()) ||
326 327 328
                    (!(*existing)->hasServerTag(last_param_server_tag) &&
                     !last_param_server_tag.amAll())) {
                    local_parameters.insert(last_param);
329 330
                }
            }
331 332
        }
    });
333 334

    parameters.insert(local_parameters.begin(), local_parameters.end());
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
OptionDefinitionPtr
MySqlConfigBackendImpl::getOptionDef(const int index,
                                     const ServerSelector& server_selector,
                                     const uint16_t code,
                                     const std::string& space) {

    if (server_selector.amUnassigned()) {
        isc_throw(NotImplemented, "managing configuration for no particular server"
                  " (unassigned) is unsupported at the moment");
    }

    auto tag = getServerTag(server_selector, "fetching option definition");

    OptionDefContainer option_defs;
    MySqlBindingCollection in_bindings = {
        MySqlBinding::createString(tag),
        MySqlBinding::createInteger<uint16_t>(code),
        MySqlBinding::createString(space)
    };
    getOptionDefs(index, in_bindings, option_defs);
    return (option_defs.empty() ? OptionDefinitionPtr() : *option_defs.begin());
}

void
MySqlConfigBackendImpl::getAllOptionDefs(const int index,
                     const ServerSelector& server_selector,
                     OptionDefContainer& option_defs) {
364
    auto tags = server_selector.getTags();
365 366
    for (auto tag : tags) {
        MySqlBindingCollection in_bindings = {
367
            MySqlBinding::createString(tag.get())
368 369 370 371 372 373 374 375 376 377
        };
        getOptionDefs(index, in_bindings, option_defs);
    }
}

void
MySqlConfigBackendImpl::getModifiedOptionDefs(const int index,
                                              const ServerSelector& server_selector,
                                              const boost::posix_time::ptime& modification_time,
                                              OptionDefContainer& option_defs) {
378
    auto tags = server_selector.getTags();
379 380
    for (auto tag : tags) {
        MySqlBindingCollection in_bindings = {
381
            MySqlBinding::createString(tag.get()),
382 383 384 385 386 387
            MySqlBinding::createTimestamp(modification_time)
        };
        getOptionDefs(index, in_bindings, option_defs);
    }
}

388 389 390 391 392 393 394 395
void
MySqlConfigBackendImpl::getOptionDefs(const int index,
                                      const MySqlBindingCollection& in_bindings,
                                      OptionDefContainer& option_defs) {
    // Create output bindings. The order must match that in the prepared
    // statement.
    MySqlBindingCollection out_bindings = {
        MySqlBinding::createInteger<uint64_t>(), // id
396
        MySqlBinding::createInteger<uint16_t>(), // code
397 398
        MySqlBinding::createString(OPTION_NAME_BUF_LENGTH), // name
        MySqlBinding::createString(OPTION_SPACE_BUF_LENGTH), // space
399 400 401
        MySqlBinding::createInteger<uint8_t>(), // type
        MySqlBinding::createTimestamp(), // modification_ts
        MySqlBinding::createInteger<uint8_t>(), // array
402 403
        MySqlBinding::createString(OPTION_ENCAPSULATE_BUF_LENGTH), // encapsulate
        MySqlBinding::createString(OPTION_RECORD_TYPES_BUF_LENGTH), // record_types
404 405
        MySqlBinding::createString(USER_CONTEXT_BUF_LENGTH), // user_context
        MySqlBinding::createString(SERVER_TAG_BUF_LENGTH) // server_tag
406 407 408 409
    };

    uint64_t last_def_id = 0;

410 411
    OptionDefContainer local_option_defs;

412 413
    // Run select query.
    conn_.selectQuery(index, in_bindings, out_bindings,
414
                      [&local_option_defs, &last_def_id]
415 416 417
                      (MySqlBindingCollection& out_bindings) {
        // Get pointer to last fetched option definition.
        OptionDefinitionPtr last_def;
418 419
        if (!local_option_defs.empty()) {
            last_def = *local_option_defs.rbegin();
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
        }

        // See if the last fetched definition is the one for which we now got
        // the row of data. If not, it means that we need to create new option
        // definition.
        if ((last_def_id == 0) ||
            (last_def_id != out_bindings[0]->getInteger<uint64_t>())) {

            last_def_id = out_bindings[0]->getInteger<uint64_t>();

            // Check array type, because depending on this value we have to use
            // different constructor.
            bool array_type = static_cast<bool>(out_bindings[6]->getInteger<uint8_t>());
            if (array_type) {
                // Create array option.
435
                last_def = OptionDefinition::create(out_bindings[2]->getString(),
436
                                                    out_bindings[1]->getInteger<uint16_t>(),
437 438
                                                    static_cast<OptionDataType>
                                                    (out_bindings[4]->getInteger<uint8_t>()),
439
                                                    array_type);
440 441
            } else {
                // Create non-array option.
442
                last_def = OptionDefinition::create(out_bindings[2]->getString(),
443
                                                    out_bindings[1]->getInteger<uint16_t>(),
444 445
                                                    static_cast<OptionDataType>
                                                    (out_bindings[4]->getInteger<uint8_t>()),
446
                                                    out_bindings[7]->getStringOrDefault("").c_str());
447 448 449 450 451
            }

            // space
            last_def->setOptionSpaceName(out_bindings[3]->getStringOrDefault(""));

452 453 454
            // id
            last_def->setId(last_def_id);

455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
            // record_types
            ElementPtr record_types_element = out_bindings[8]->getJSON();
            if (record_types_element) {
                if (record_types_element->getType() != Element::list) {
                    isc_throw(BadValue, "invalid record_types value "
                              << out_bindings[8]->getString());
                }
                // This element must contain a list of integers specifying
                // types of the record fields.
                for (auto i = 0; i < record_types_element->size(); ++i) {
                    auto type_element = record_types_element->get(i);
                    if (type_element->getType() != Element::integer) {
                        isc_throw(BadValue, "record type values must be integers");
                    }
                    last_def->addRecordField(static_cast<OptionDataType>
                                             (type_element->intValue()));
                }
            }

            // Update modification time.
            last_def->setModificationTime(out_bindings[5]->getTimestamp());

477
            // server_tag
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
            ServerTag last_def_server_tag(out_bindings[10]->getString());
            last_def->setServerTag(last_def_server_tag.get());

            // If we're fetching option definitions for a given server
            // (explicit server tag is provided), it takes precedence over
            // the same option definition specified for all servers.
            // Therefore, we check if the given option already exists and
            // belongs to 'all'.
            auto& index = local_option_defs.get<1>();
            auto existing_it_pair = index.equal_range(last_def->getCode());
            auto existing_it = existing_it_pair.first;
            bool found = false;
            for ( ; existing_it != existing_it_pair.second; ++existing_it) {
                if ((*existing_it)->getOptionSpaceName() == last_def->getOptionSpaceName()) {
                    found = true;
                    // This option definition was already fetched. Let's check
                    // if we should replace it or not.
                    if (!last_def_server_tag.amAll() && (*existing_it)->hasAllServerTag()) {
                        index.replace(existing_it, last_def);
                        return;
                    }
                    break;
                }
            }
502

503 504 505 506 507 508 509 510
            // If there is no such option definition yet or the existing option
            // definition belongs to a different server and the inserted option
            // definition is not for all servers.
            if (!found ||
                (!(*existing_it)->hasServerTag(last_def_server_tag) &&
                 !last_def_server_tag.amAll())) {
                static_cast<void>(local_option_defs.push_back(last_def));
            }
511 512
        }
    });
513 514 515 516 517 518

    // Append the option definition fetched by this function into the container
    // supplied by the caller. The container supplied by the caller may already
    // hold some option definitions fetched for other server tags.
    option_defs.insert(option_defs.end(), local_option_defs.begin(),
                       local_option_defs.end());
519 520
}

521 522 523 524
void
MySqlConfigBackendImpl::createUpdateOptionDef(const db::ServerSelector& server_selector,
                                              const OptionDefinitionPtr& option_def,
                                              const std::string& space,
525
                                              const int& /*get_option_def_code_space*/,
526 527 528 529
                                              const int& insert_option_def,
                                              const int& update_option_def,
                                              const int& create_audit_revision,
                                              const int& insert_option_def_server) {
530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554

    if (server_selector.amUnassigned()) {
        isc_throw(NotImplemented, "managing configuration for no particular server"
                  " (unassigned) is unsupported at the moment");
    }

    auto tag = getServerTag(server_selector, "creating or updating option definition");

    ElementPtr record_types = Element::createList();
    for (auto field : option_def->getRecordFields()) {
        record_types->add(Element::create(static_cast<int>(field)));
    }
    MySqlBindingPtr record_types_binding = record_types->empty() ?
        MySqlBinding::createNull() : MySqlBinding::createString(record_types->str());

    MySqlBindingCollection in_bindings = {
        MySqlBinding::createInteger<uint16_t>(option_def->getCode()),
        MySqlBinding::createString(option_def->getName()),
        MySqlBinding::createString(option_def->getOptionSpaceName().empty() ?
                                   space : option_def->getOptionSpaceName()),
        MySqlBinding::createInteger<uint8_t>(static_cast<uint8_t>(option_def->getType())),
        MySqlBinding::createTimestamp(option_def->getModificationTime()),
        MySqlBinding::createBool(option_def->getArrayType()),
        MySqlBinding::createString(option_def->getEncapsulatedSpace()),
        record_types_binding,
555 556 557 558
        createInputContextBinding(option_def),
        MySqlBinding::createString(tag),
        MySqlBinding::createInteger<uint16_t>(option_def->getCode()),
        MySqlBinding::createString(option_def->getOptionSpaceName())
559 560 561 562 563 564 565 566 567 568 569 570
    };

    MySqlTransaction transaction(conn_);

    // Create scoped audit revision. As long as this instance exists
    // no new audit revisions are created in any subsequent calls.
    ScopedAuditRevision audit_revision(this,
                                       create_audit_revision,
                                       server_selector,
                                       "option definition set",
                                       true);

571 572 573
    if (conn_.updateDeleteQuery(update_option_def, in_bindings) == 0) {
        // Remove the bindings used only during the update.
        in_bindings.resize(in_bindings.size() - 3);
574 575 576 577 578 579
        conn_.insertQuery(insert_option_def, in_bindings);

        // Fetch unique identifier of the inserted option definition and use it
        // as input to the next query.
        uint64_t id = mysql_insert_id(conn_.mysql_);

580 581 582 583 584
        // Insert associations of the option definition with servers.
        attachElementToServers(insert_option_def_server,
                               server_selector,
                               MySqlBinding::createInteger<uint64_t>(id),
                               MySqlBinding::createTimestamp(option_def->getModificationTime()));
585 586 587 588 589
    }

    transaction.commit();
}

590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
OptionDescriptorPtr
MySqlConfigBackendImpl::getOption(const int index,
                                  const Option::Universe& universe,
                                  const ServerSelector& server_selector,
                                  const uint16_t code,
                                  const std::string& space) {

    if (server_selector.amUnassigned()) {
        isc_throw(NotImplemented, "managing configuration for no particular server"
                  " (unassigned) is unsupported at the moment");
    }

    auto tag = getServerTag(server_selector, "fetching global option");

    OptionContainer options;
    MySqlBindingCollection in_bindings;
    in_bindings.push_back(MySqlBinding::createString(tag));
    if (universe == Option::V4) {
        in_bindings.push_back(MySqlBinding::createInteger<uint8_t>(static_cast<uint8_t>(code)));
    } else {
        in_bindings.push_back(MySqlBinding::createInteger<uint16_t>(code));
    }
    in_bindings.push_back(MySqlBinding::createString(space));
    getOptions(index, in_bindings, universe, options);
    return (options.empty() ? OptionDescriptorPtr() :
615
            OptionDescriptor::create(*options.begin()));
616 617 618 619 620 621 622 623
}

OptionContainer
MySqlConfigBackendImpl::getAllOptions(const int index,
                                      const Option::Universe& universe,
                                      const ServerSelector& server_selector) {
    OptionContainer options;

624
    auto tags = server_selector.getTags();
625 626
    for (auto tag : tags) {
        MySqlBindingCollection in_bindings = {
627
            MySqlBinding::createString(tag.get())
628 629 630 631 632 633 634 635 636 637 638 639 640 641
        };
        getOptions(index, in_bindings, universe, options);
    }

    return (options);
}

OptionContainer
MySqlConfigBackendImpl::getModifiedOptions(const int index,
                                           const Option::Universe& universe,
                                           const ServerSelector& server_selector,
                                           const boost::posix_time::ptime& modification_time) {
    OptionContainer options;

642
    auto tags = server_selector.getTags();
643 644
    for (auto tag : tags) {
        MySqlBindingCollection in_bindings = {
645
            MySqlBinding::createString(tag.get()),
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
            MySqlBinding::createTimestamp(modification_time)
        };
        getOptions(index, in_bindings, universe, options);
    }

    return (options);
}

OptionDescriptorPtr
MySqlConfigBackendImpl::getOption(const int index,
                                  const Option::Universe& universe,
                                  const ServerSelector& server_selector,
                                  const SubnetID& subnet_id,
                                  const uint16_t code,
                                  const std::string& space) {

    if (server_selector.amUnassigned()) {
        isc_throw(NotImplemented, "managing configuration for no particular server"
                  " (unassigned) is unsupported at the moment");
    }

    auto tag = getServerTag(server_selector, "fetching subnet level option");

    OptionContainer options;
    MySqlBindingCollection in_bindings;
    in_bindings.push_back(MySqlBinding::createString(tag));
    uint32_t id = static_cast<uint32_t>(subnet_id);
    in_bindings.push_back(MySqlBinding::createInteger<uint32_t>(id));
    if (universe == Option::V4) {
        in_bindings.push_back(MySqlBinding::createInteger<uint8_t>(static_cast<uint8_t>(code)));
    } else {
        in_bindings.push_back(MySqlBinding::createInteger<uint16_t>(code));
    }
    in_bindings.push_back(MySqlBinding::createString(space));
    getOptions(index, in_bindings, universe, options);
    return (options.empty() ? OptionDescriptorPtr() :
682
            OptionDescriptor::create(*options.begin()));
683 684 685 686 687
}

OptionDescriptorPtr
MySqlConfigBackendImpl::getOption(const int index,
                                  const ServerSelector& server_selector,
688
                                  const Lease::Type& pool_type,
689 690 691 692 693 694 695 696 697
                                  const uint64_t pool_id,
                                  const uint16_t code,
                                  const std::string& space) {

    if (server_selector.amUnassigned()) {
        isc_throw(NotImplemented, "managing configuration for no particular server"
                  " (unassigned) is unsupported at the moment");
    }

698 699 700 701 702 703 704 705
    std::string msg = "fetching ";
    if (pool_type == Lease::TYPE_PD) {
        msg += "prefix delegation";
    } else {
        msg += "address";
    }
    msg += " pool level option";
    auto tag = getServerTag(server_selector, msg);
706

707
    Option::Universe universe = Option::V4;
708 709 710 711
    OptionContainer options;
    MySqlBindingCollection in_bindings;
    in_bindings.push_back(MySqlBinding::createString(tag));
    in_bindings.push_back(MySqlBinding::createInteger<uint64_t>(pool_id));
712
    if (pool_type == Lease::TYPE_V4) {
713 714 715
        in_bindings.push_back(MySqlBinding::createInteger<uint8_t>(static_cast<uint8_t>(code)));
    } else {
        in_bindings.push_back(MySqlBinding::createInteger<uint16_t>(code));
716
        universe = Option::V6;
717 718 719 720
    }
    in_bindings.push_back(MySqlBinding::createString(space));
    getOptions(index, in_bindings, universe, options);
    return (options.empty() ? OptionDescriptorPtr() :
721
            OptionDescriptor::create(*options.begin()));
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
}

OptionDescriptorPtr
MySqlConfigBackendImpl::getOption(const int index,
                                  const Option::Universe& universe,
                                  const ServerSelector& server_selector,
                                  const std::string& shared_network_name,
                                  const uint16_t code,
                                  const std::string& space) {

    if (server_selector.amUnassigned()) {
        isc_throw(NotImplemented, "managing configuration for no particular server"
                  " (unassigned) is unsupported at the moment");
    }

    auto tag = getServerTag(server_selector, "fetching shared network level option");

    OptionContainer options;
    MySqlBindingCollection in_bindings;
    in_bindings.push_back(MySqlBinding::createString(tag));
    in_bindings.push_back(MySqlBinding::createString(shared_network_name));
    if (universe == Option::V4) {
        in_bindings.push_back(MySqlBinding::createInteger<uint8_t>(static_cast<uint8_t>(code)));
    } else {
        in_bindings.push_back(MySqlBinding::createInteger<uint16_t>(code));
    }
    in_bindings.push_back(MySqlBinding::createString(space));
    getOptions(index, in_bindings, universe, options);
    return (options.empty() ? OptionDescriptorPtr() :
751
            OptionDescriptor::create(*options.begin()));
752 753
}

754 755 756 757 758 759 760
void
MySqlConfigBackendImpl::getOptions(const int index,
                                   const db::MySqlBindingCollection& in_bindings,
                                   const Option::Universe& universe,
                                   OptionContainer& options) {
    // Create output bindings. The order must match that in the prepared
    // statement.
761 762 763 764
    MySqlBindingCollection out_bindings;
    // option_id
    out_bindings.push_back(MySqlBinding::createInteger<uint64_t>());
    // code
765
    if (universe == Option::V4) {
766
        out_bindings.push_back(MySqlBinding::createInteger<uint8_t>());
767
    } else {
768
        out_bindings.push_back(MySqlBinding::createInteger<uint16_t>());
769
    }
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
    // value
    out_bindings.push_back(MySqlBinding::createBlob(OPTION_VALUE_BUF_LENGTH));
    // forma\tted_value
    out_bindings.push_back(MySqlBinding::createString(FORMATTED_OPTION_VALUE_BUF_LENGTH));
    // space
    out_bindings.push_back(MySqlBinding::createString(OPTION_SPACE_BUF_LENGTH));
    // persistent
    out_bindings.push_back(MySqlBinding::createInteger<uint8_t>());
    // dhcp[46]_subnet_id
    out_bindings.push_back(MySqlBinding::createInteger<uint32_t>());
    // scope_id
    out_bindings.push_back(MySqlBinding::createInteger<uint8_t>());
    // user_context
    out_bindings.push_back(MySqlBinding::createString(USER_CONTEXT_BUF_LENGTH));
    // shared_network_name
    out_bindings.push_back(MySqlBinding::createString(SHARED_NETWORK_NAME_BUF_LENGTH));
    // pool_id
    out_bindings.push_back(MySqlBinding::createInteger<uint64_t>());
788 789
    // modification_ts
    out_bindings.push_back(MySqlBinding::createTimestamp());
790 791
    // server_tag
    out_bindings.push_back(MySqlBinding::createString(SERVER_TAG_BUF_LENGTH));
792
    // pd_pool_id
793
    if (universe == Option::V6) {
794
        out_bindings.push_back(MySqlBinding::createInteger<uint64_t>());
795 796
    }

797 798
    uint64_t last_option_id = 0;

799 800
    OptionContainer local_options;

801
    conn_.selectQuery(index, in_bindings, out_bindings,
802
                      [this, universe, &local_options, &last_option_id]
803 804 805 806 807 808 809 810 811
                      (MySqlBindingCollection& out_bindings) {
        // Parse option.
        if (!out_bindings[0]->amNull() &&
            ((last_option_id == 0) ||
             (last_option_id < out_bindings[0]->getInteger<uint64_t>()))) {
            last_option_id = out_bindings[0]->getInteger<uint64_t>();

            OptionDescriptorPtr desc = processOptionRow(universe, out_bindings.begin());
            if (desc) {
812
                // server_tag for the global option
813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
                ServerTag last_option_server_tag(out_bindings[12]->getString());
                desc->setServerTag(last_option_server_tag.get());

                // If we're fetching options for a given server (explicit server
                // tag is provided), it takes precedence over the same option
                // specified for all servers. Therefore, we check if the given
                // option already exists and belongs to 'all'.
                auto& index = local_options.get<1>();
                auto existing_it_pair = index.equal_range(desc->option_->getType());
                auto existing_it = existing_it_pair.first;
                bool found = false;
                for ( ; existing_it != existing_it_pair.second; ++existing_it) {
                    if (existing_it->space_name_ == desc->space_name_) {
                        found = true;
                        // This option was already fetched. Let's check if we should
                        // replace it or not.
                        if (!last_option_server_tag.amAll() && existing_it->hasAllServerTag()) {
                            index.replace(existing_it, *desc);
                            return;
                        }
                        break;
                    }
                }

                // If there is no such global option yet or the existing option
                // belongs to a different server and the inserted option is not
                // for all servers.
                if (!found ||
                    (!existing_it->hasServerTag(last_option_server_tag) &&
                     !last_option_server_tag.amAll())) {
                    static_cast<void>(local_options.push_back(*desc));
                }
845 846 847
            }
        }
    });
848 849 850 851 852

    // Append the options fetched by this function into the container supplied
    // by the caller. The container supplied by the caller may already hold
    // some options fetched for other server tags.
    options.insert(options.end(), local_options.begin(), local_options.end());
853 854 855 856 857
}

OptionDescriptorPtr
MySqlConfigBackendImpl::processOptionRow(const Option::Universe& universe,
                                         MySqlBindingCollection::iterator first_binding) {
858 859 860 861 862 863
    // Some of the options have standard or custom definitions.
    // Depending whether the option has a definition or not a different
    // C++ class may be used to represent the option. Therefore, the
    // first thing to do is to see if there is a definition for our
    // parsed option. The option code and space is needed for it.
    std::string space = (*(first_binding + 4))->getString();
864 865 866 867 868 869
    uint16_t code;
    if (universe == Option::V4) {
        code = (*(first_binding + 1))->getInteger<uint8_t>();
    } else {
        code = (*(first_binding + 1))->getInteger<uint16_t>();
    }
870 871


872
    // Get formatted value if available.
873 874
    std::string formatted_value = (*(first_binding + 3))->getStringOrDefault("");

875
    OptionPtr option = Option::create(universe, code);
876 877 878 879 880 881 882 883 884 885

    // If we don't have a formatted value, check for a blob. Add it to the
    // option if it exists.
    if (formatted_value.empty()) {
        std::vector<uint8_t> blob;
        if (!(*(first_binding + 2))->amNull()) {
            blob = (*(first_binding + 2))->getBlob();
        }
        option->setData(blob.begin(), blob.end());
    }
886

887
    // Check if the option is persistent.
888 889
    bool persistent = static_cast<bool>((*(first_binding + 5))->getIntegerOrDefault<uint8_t>(0));

890 891 892
    // Create option descriptor which encapsulates our option and adds
    // additional information, i.e. whether the option is persistent,
    // its option space and timestamp.
893
    OptionDescriptorPtr desc = OptionDescriptor::create(option, persistent, formatted_value);
894
    desc->space_name_ = space;
895
    desc->setModificationTime((*(first_binding + 11))->getTimestamp());
896

897 898 899 900 901
    // Set database id for the option.
    if (!(*first_binding)->amNull()) {
        desc->setId((*first_binding)->getInteger<uint64_t>());
    }

902 903 904
    return (desc);
}

905 906 907 908 909 910 911 912 913
void
MySqlConfigBackendImpl::attachElementToServers(const int index,
                                               const ServerSelector& server_selector,
                                               const MySqlBindingPtr& first_binding,
                                               const MySqlBindingPtr& in_bindings...) {
    // Create the vector from the parameter pack.
    MySqlBindingCollection in_server_bindings = { first_binding, in_bindings };
    for (auto tag : server_selector.getTags()) {
        in_server_bindings.push_back(MySqlBinding::createString(tag.get()));
914 915 916 917 918 919 920 921
        // Handles the case where the server does not exists.
        try {
            conn_.insertQuery(index, in_server_bindings);
        } catch (const NullKeyError&) {
            // The message should give the tag value.
            isc_throw(NullKeyError,
                      "server '" << tag.get() << "' does not exist");
        }
922 923 924 925
        in_server_bindings.pop_back();
    }
}

926 927 928 929 930 931 932 933 934 935 936 937 938 939
MySqlBindingPtr
MySqlConfigBackendImpl::createInputRelayBinding(const NetworkPtr& network) {
    ElementPtr relay_element = Element::createList();
    const auto& addresses = network->getRelayAddresses();
    if (!addresses.empty()) {
        for (const auto& address : addresses) {
            relay_element->add(Element::create(address.toText()));
        }
    }

    return (relay_element->empty() ? MySqlBinding::createNull() :
            MySqlBinding::condCreateString(relay_element->str()));
}

940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955
MySqlBindingPtr
MySqlConfigBackendImpl::createOptionValueBinding(const OptionDescriptorPtr& option) {
    OptionPtr opt = option->option_;
    if (option->formatted_value_.empty() && (opt->len() > opt->getHeaderLen())) {
        OutputBuffer buf(opt->len());
        opt->pack(buf);
        const char* buf_ptr = static_cast<const char*>(buf.getData());
        std::vector<uint8_t> blob(buf_ptr + opt->getHeaderLen(),
                                  buf_ptr + buf.getLength());
        return (MySqlBinding::createBlob(blob.begin(), blob.end()));

    }

    return (MySqlBinding::createNull());
}

956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
ServerPtr
MySqlConfigBackendImpl::getServer(const int index, const ServerTag& server_tag) {
    ServerCollection servers;
    MySqlBindingCollection in_bindings = {
        MySqlBinding::createString(server_tag.get())
    };
    getServers(index, in_bindings, servers);

    return (servers.empty() ? ServerPtr() : *servers.begin());
}

void
MySqlConfigBackendImpl::getAllServers(const int index, db::ServerCollection& servers) {
    MySqlBindingCollection in_bindings;
    getServers(index, in_bindings, servers);
}

void
MySqlConfigBackendImpl::getServers(const int index,
                                   const MySqlBindingCollection& in_bindings,
                                   ServerCollection& servers) {
    MySqlBindingCollection out_bindings = {
        MySqlBinding::createInteger<uint64_t>(),
        MySqlBinding::createString(SERVER_TAG_BUF_LENGTH),
        MySqlBinding::createString(SERVER_DESCRIPTION_BUF_LENGTH),
        MySqlBinding::createTimestamp()
    };

    conn_.selectQuery(index, in_bindings, out_bindings,
                      [&servers](MySqlBindingCollection& out_bindings) {

        ServerPtr last_server;
        uint64_t id = out_bindings[0]->getInteger<uint64_t>();
        if (!last_server || (last_server->getId() != id)) {

            // Set description if it is non-null.
            auto desc = (out_bindings[2]->amNull() ? "" : out_bindings[2]->getString());
            last_server = Server::create(ServerTag(out_bindings[1]->getString()),
                                         desc);

            // id
            last_server->setId(id);

            // modification_ts
            last_server->setModificationTime(out_bindings[3]->getTimestamp());

            // New server fetched. Let's store it.
            servers.insert(last_server);
        }
    });
}

void
1009 1010 1011
MySqlConfigBackendImpl::createUpdateServer(const int& create_audit_revision,
                                           const int& create_index,
                                           const int& update_index,
1012
                                           const ServerPtr& server) {
1013 1014 1015 1016
    // The server tag 'all' is reserved.
    if (server->getServerTag().amAll()) {
        isc_throw(InvalidOperation, "'all' is a name reserved for the server tag which"
                  " associates the configuration elements with all servers connecting"
1017
                  " to the database and a server with this name may not be created");
1018 1019
    }

1020 1021 1022
    // Create scoped audit revision. As long as this instance exists
    // no new audit revisions are created in any subsequent calls.
    ScopedAuditRevision audit_revision(this,
1023
                                       create_audit_revision,
1024 1025 1026 1027 1028 1029 1030
                                       ServerSelector::ALL(),
                                       "server set",
                                       true);

    MySqlTransaction transaction(conn_);

    MySqlBindingCollection in_bindings = {
1031
        MySqlBinding::createString(server->getServerTagAsText()),
1032 1033 1034 1035 1036 1037 1038 1039
        MySqlBinding::createString(server->getDescription()),
        MySqlBinding::createTimestamp(server->getModificationTime())
    };

    try {
        conn_.insertQuery(create_index, in_bindings);

    } catch (const DuplicateEntry&) {
1040
        in_bindings.push_back(MySqlBinding::createString(server->getServerTagAsText()));
1041 1042 1043 1044 1045 1046
        conn_.updateDeleteQuery(update_index, in_bindings);
    }

    transaction.commit();
}

1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
std::string
MySqlConfigBackendImpl::getType() const {
    return ("mysql");
}

std::string
MySqlConfigBackendImpl::getHost() const {
    std::string host = "localhost";
    try {
        host = conn_.getParameter("host");
    } catch (...) {
        // No host parameter. Return localhost as a default.
    }
    return (host);
}

uint16_t
MySqlConfigBackendImpl::getPort() const {
    try {
        std::string sport = conn_.getParameter("port");
        return (boost::lexical_cast<uint16_t>(sport));

    } catch (...) {
        // No port parameter or parameter invalid.
    }
    return (0);
}

1075 1076
} // end of namespace isc::dhcp
} // end of namespace isc