netconf.cc 20.6 KB
Newer Older
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
// Copyright (C) 2018 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/.

/// @file netconf.cc
/// Contains the Netconf agent methods.

#include <config.h>

#include <netconf/netconf.h>
#include <netconf/netconf_controller.h>
#include <netconf/netconf_log.h>
#include <cc/command_interpreter.h>
#include <yang/translator_config.h>
#include <boost/algorithm/string.hpp>
#include <sstream>

using namespace std;
using namespace isc::config;
using namespace isc::data;
using namespace isc::netconf;
using namespace isc::yang;

namespace {

/// @brief Subscription callback.
class NetconfAgentCallback : public Callback {
public:
    /// @brief Constructor.
    ///
    /// @param service_pair The service name and configuration pair.
    NetconfAgentCallback(const CfgServersMapPair& service_pair)
        : service_pair_(service_pair) {
    }

    /// @brief Server name and configuration pair.
    CfgServersMapPair service_pair_;

41
    /// @brief Module configuration change callback.
42
    ///
43
    /// This callback is called by sysrepo when there is a change to
44
    /// module configuration.
45
    ///
46 47 48 49 50 51 52 53 54
    /// @param sess The running datastore session.
    /// @param module_name The module name.
    /// @param event The event.
    /// @param private_ctx The private context.
    /// @return the sysrepo return code.
    int module_change(S_Session sess,
                      const char* /*module_name*/,
                      sr_notif_event_t event,
                      void* /*private_ctx*/) {
55
        if (NetconfProcess::shut_down) {
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
            return (SR_ERR_DISCONNECT);
        }
        ostringstream event_type;
        switch (event) {
        case SR_EV_VERIFY:
            event_type << "VERIFY";
            break;
        case SR_EV_APPLY:
            event_type << "APPLY";
            break;
        case SR_EV_ABORT:
            event_type << "ABORT";
            break;
        case SR_EV_ENABLED:
            event_type << "ENABLED";
            break;
        default:
            event_type << "UNKNOWN (" << event << ")";
            break;
        }
        LOG_INFO(netconf_logger, NETCONF_CONFIG_CHANGE_EVENT)
            .arg(event_type.str());
        string xpath = "/" + service_pair_.second->getModel() + ":";
        NetconfAgent::logChanges(sess, xpath + "config");
80
        if (NetconfProcess::shut_down) {
81 82 83
            return (SR_ERR_DISCONNECT);
        }
        NetconfAgent::logChanges(sess, xpath + "logging");
84
        if (NetconfProcess::shut_down) {
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
            return (SR_ERR_DISCONNECT);
        }
        switch (event) {
        case SR_EV_VERIFY:
            return (NetconfAgent::validate(sess, service_pair_));
        case SR_EV_APPLY:
            return (NetconfAgent::update(sess, service_pair_));
        default:
            return (SR_ERR_OK);
        }
    }
};

} // end of anonymous namespace

namespace isc {
namespace netconf {

NetconfAgent::NetconfAgent() {
}

NetconfAgent::~NetconfAgent() {
    clear();
}

void
NetconfAgent::init(NetconfCfgMgrPtr cfg_mgr) {
112
    if (NetconfProcess::shut_down || !cfg_mgr) {
113 114
        return;
    }
115 116 117
    const CfgServersMapPtr& servers =
        cfg_mgr->getNetconfConfig()->getCfgServersMap();
    for (auto pair : *servers) {
118
        if (NetconfProcess::shut_down) {
119 120
            return;
        }
121 122

        // Retrieve configuration from existing running DHCP daemons.
123
        keaConfig(pair);
124
        if (NetconfProcess::shut_down) {
125 126
            return;
        }
127
    }
128
    if (NetconfProcess::shut_down) {
129 130
        return;
    }
131 132

    // Initialize sysrepo interface.
133
    initSysrepo();
134
    if (NetconfProcess::shut_down) {
135 136
        return;
    }
137

138
    for (auto pair : *servers) {
139
        if (NetconfProcess::shut_down) {
140 141 142
            return;
        }
        yangConfig(pair);
143
        if (NetconfProcess::shut_down) {
144 145
            return;
        }
146 147
        subscribeConfig(pair);
        if (NetconfProcess::shut_down) {
148 149
            return;
        }
150 151 152 153 154 155
    }
}

void
NetconfAgent::clear() {
    // Should be already set to true but in case...
156
    NetconfProcess::shut_down = true;
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
    for (auto subs : subscriptions_) {
        subs.second.reset();
    }
    subscriptions_.clear();
    running_sess_.reset();
    startup_sess_.reset();
    conn_.reset();
}

void
NetconfAgent::keaConfig(const CfgServersMapPair& service_pair) {
    if (!service_pair.second->getBootUpdate()) {
        return;
    }
    CfgControlSocketPtr ctrl_sock = service_pair.second->getCfgControlSocket();
    if (!ctrl_sock) {
        return;
    }
    ControlSocketBasePtr comm;
    try {
        comm = createControlSocket(ctrl_sock);
    } catch (const std::exception& ex) {
        ostringstream msg;
        msg << "createControlSocket failed with " << ex.what();
        LOG_ERROR(netconf_logger, NETCONF_GET_CONFIG_FAILED)
            .arg(service_pair.first)
            .arg(msg.str());
        return;
    }
    ConstElementPtr answer;
    int rcode;
    ConstElementPtr config;
    LOG_DEBUG(netconf_logger, NETCONF_DBG_TRACE, NETCONF_GET_CONFIG)
        .arg(service_pair.first);
    try {
        answer = comm->configGet(service_pair.first);
        config = parseAnswer(rcode, answer);
    } catch (const std::exception& ex) {
        ostringstream msg;
196
        msg << "config-get command failed with " << ex.what();
197 198 199 200 201
        LOG_ERROR(netconf_logger, NETCONF_GET_CONFIG_FAILED)
            .arg(service_pair.first)
            .arg(msg.str());
        return;
    }
202
    if (NetconfProcess::shut_down) {
203 204 205 206
        return;
    }
    if (rcode != CONTROL_RESULT_SUCCESS) {
        ostringstream msg;
207
        msg << "config-get command returned " << answerToText(answer);
208 209 210 211 212 213 214 215
        LOG_ERROR(netconf_logger, NETCONF_GET_CONFIG_FAILED)
            .arg(service_pair.first)
            .arg(msg.str());
        return;
    }
    if (!config) {
        LOG_ERROR(netconf_logger, NETCONF_GET_CONFIG_FAILED)
            .arg(service_pair.first)
216
            .arg("config-get command returned an empty configuration");
217 218
        return;
    }
219 220 221
    LOG_INFO(netconf_logger, NETCONF_BOOT_UPDATE_COMPLETE)
        .arg(service_pair.first);

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
    LOG_DEBUG(netconf_logger, NETCONF_DBG_TRACE_DETAIL_DATA,
              NETCONF_GET_CONFIG_CONFIG)
        .arg(service_pair.first)
        .arg(prettyPrint(config));
}

void
NetconfAgent::initSysrepo() {
    try {
        conn_.reset(new Connection(NetconfController::netconf_app_name_,
                                   SR_CONN_DAEMON_REQUIRED));
    } catch (const std::exception& ex) {
        isc_throw(Unexpected, "Can't connect to sysrepo: " << ex.what());
    }

    try {
        startup_sess_.reset(new Session(conn_, SR_DS_STARTUP));
        running_sess_.reset(new Session(conn_, SR_DS_RUNNING));
    } catch (const std::exception& ex) {
        isc_throw(Unexpected,  "Can't establish a sysrepo session: "
                  << ex.what());
    }
}

void
NetconfAgent::yangConfig(const CfgServersMapPair& service_pair) {
248 249
    // If we're shutting down, or the boot-update flag is not set or the model
    // associated with it is not specified.
250
    if (NetconfProcess::shut_down ||
251 252 253 254
        !service_pair.second->getBootUpdate() ||
        service_pair.second->getModel().empty()) {
        return;
    }
255 256

    // First we need a way to reach the actual servers.
257 258 259 260
    CfgControlSocketPtr ctrl_sock = service_pair.second->getCfgControlSocket();
    if (!ctrl_sock) {
        return;
    }
261

262 263 264 265
    LOG_DEBUG(netconf_logger, NETCONF_DBG_TRACE, NETCONF_SET_CONFIG)
        .arg(service_pair.first);
    ConstElementPtr config;
    try {
266
        // Retrieve configuration from Sysrepo.
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
        TranslatorConfig tc(startup_sess_, service_pair.second->getModel());
        config = tc.getConfig();
        if (!config) {
            ostringstream msg;
            msg << "YANG configuration for "
                << service_pair.second->getModel()
                << " is empty";
            LOG_ERROR(netconf_logger, NETCONF_SET_CONFIG_FAILED)
                .arg(service_pair.first)
                .arg(msg.str());
            return;
        } else {
            LOG_DEBUG(netconf_logger, NETCONF_DBG_TRACE_DETAIL_DATA,
                      NETCONF_SET_CONFIG_CONFIG)
                .arg(service_pair.first)
                .arg(prettyPrint(config));
        }
    } catch (const std::exception& ex) {
        ostringstream msg;
286
        msg << "get YANG configuration for " << service_pair.first
287 288 289 290 291 292
            << " failed with " << ex.what();
        LOG_ERROR(netconf_logger, NETCONF_SET_CONFIG_FAILED)
            .arg(service_pair.first)
            .arg(msg.str());
        return;
    }
293
    if (NetconfProcess::shut_down) {
294 295 296 297 298 299 300 301 302 303 304 305 306
        return;
    }
    ControlSocketBasePtr comm;
    try {
        comm = createControlSocket(ctrl_sock);
    } catch (const std::exception& ex) {
        ostringstream msg;
        msg << "control socket creation failed with " << ex.what();
        LOG_ERROR(netconf_logger, NETCONF_SET_CONFIG_FAILED)
            .arg(service_pair.first)
            .arg(msg.str());
        return;
    }
307
    if (NetconfProcess::shut_down) {
308 309 310 311 312 313 314 315 316
        return;
    }
    ConstElementPtr answer;
    int rcode;
    try {
        answer = comm->configSet(config, service_pair.first);
        parseAnswer(rcode, answer);
    } catch (const std::exception& ex) {
        ostringstream msg;
317
        msg << "config-set command failed with " << ex.what();
318 319 320 321 322 323 324
        LOG_ERROR(netconf_logger, NETCONF_SET_CONFIG_FAILED)
            .arg(service_pair.first)
            .arg(msg.str());
        return;
    }
    if (rcode != CONTROL_RESULT_SUCCESS) {
        ostringstream msg;
325
        msg << "config-set command returned " << answerToText(answer);
326 327 328 329 330 331 332
        LOG_ERROR(netconf_logger, NETCONF_SET_CONFIG_FAILED)
            .arg(service_pair.first)
            .arg(msg.str());
    }
}

void
333 334
NetconfAgent::subscribeConfig(const CfgServersMapPair& service_pair) {
    if (NetconfProcess::shut_down ||
335 336 337 338
        !service_pair.second->getSubscribeChanges() ||
        service_pair.second->getModel().empty()) {
        return;
    }
339
    LOG_INFO(netconf_logger, NETCONF_SUBSCRIBE_CONFIG)
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
        .arg(service_pair.first)
        .arg(service_pair.second->getModel());
    S_Subscribe subs(new Subscribe(running_sess_));
    S_Callback cb(new NetconfAgentCallback(service_pair));
    try {
        sr_subscr_options_t options = SR_SUBSCR_DEFAULT;
        if (!service_pair.second->getValidateChanges()) {
            options |= SR_SUBSCR_APPLY_ONLY;
        }
        // Note the API stores the module name so do not put it
        // in a short lifetime variable!
        subs->module_change_subscribe(service_pair.second->getModel().c_str(),
                                      cb, 0, 0, options);
    } catch (const std::exception& ex) {
        ostringstream msg;
        msg << "module change subscribe failed with " << ex.what();
356
        LOG_ERROR(netconf_logger, NETCONF_SUBSCRIBE_CONFIG_FAILED)
357 358 359 360 361 362 363 364 365 366 367
            .arg(service_pair.first)
            .arg(service_pair.second->getModel())
            .arg(msg.str());
        subs.reset();
        return;
    }
    subscriptions_.insert(make_pair(service_pair.first, subs));
}

int
NetconfAgent::validate(S_Session sess, const CfgServersMapPair& service_pair) {
368
    if (NetconfProcess::shut_down ||
369 370 371 372 373 374 375 376
        !service_pair.second->getSubscribeChanges() ||
        !service_pair.second->getValidateChanges()) {
        return (SR_ERR_OK);
    }
    CfgControlSocketPtr ctrl_sock = service_pair.second->getCfgControlSocket();
    if (!ctrl_sock) {
        return (SR_ERR_OK);
    }
377 378
    LOG_DEBUG(netconf_logger, NETCONF_DBG_TRACE,
              NETCONF_VALIDATE_CONFIG_STARTED)
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
        .arg(service_pair.first);
    ConstElementPtr config;
    try {
        TranslatorConfig tc(sess, service_pair.second->getModel());
        config = tc.getConfig();
        if (!config) {
            ostringstream msg;
            msg << "YANG configuration for "
                << service_pair.second->getModel()
                << " is empty";
            LOG_ERROR(netconf_logger, NETCONF_VALIDATE_CONFIG_FAILED)
                .arg(service_pair.first)
                .arg(msg.str());
            return (SR_ERR_DISCONNECT);
        } else {
            LOG_DEBUG(netconf_logger, NETCONF_DBG_TRACE_DETAIL_DATA,
395
                      NETCONF_VALIDATE_CONFIG)
396 397 398 399 400
                .arg(service_pair.first)
                .arg(prettyPrint(config));
        }
    } catch (const std::exception& ex) {
        ostringstream msg;
401
        msg << "get YANG configuration for " << service_pair.first
402 403 404 405 406 407
            << " failed with " << ex.what();
        LOG_ERROR(netconf_logger, NETCONF_VALIDATE_CONFIG_FAILED)
            .arg(service_pair.first)
            .arg(msg.str());
        return (SR_ERR_VALIDATION_FAILED);;
    }
408
    if (NetconfProcess::shut_down) {
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 437
        return (SR_ERR_DISCONNECT);
    }
    ControlSocketBasePtr comm;
    try {
        comm = createControlSocket(ctrl_sock);
    } catch (const std::exception& ex) {
        ostringstream msg;
        msg << "createControlSocket failed with " << ex.what();
        LOG_ERROR(netconf_logger, NETCONF_VALIDATE_CONFIG_FAILED)
            .arg(service_pair.first)
            .arg(msg.str());
        return (SR_ERR_OK);
    }
    ConstElementPtr answer;
    int rcode;
    try {
        answer = comm->configTest(config, service_pair.first);
        parseAnswer(rcode, answer);
    } catch (const std::exception& ex) {
        stringstream msg;
        msg << "configTest failed with " << ex.what();
        LOG_ERROR(netconf_logger, NETCONF_VALIDATE_CONFIG_FAILED)
            .arg(service_pair.first)
            .arg(msg.str());
        return (SR_ERR_VALIDATION_FAILED);
    }
    if (rcode != CONTROL_RESULT_SUCCESS) {
        stringstream msg;
        msg << "configTest returned " << answerToText(answer);
438
        LOG_ERROR(netconf_logger, NETCONF_VALIDATE_CONFIG_REJECTED)
439 440 441 442 443 444 445 446 447
            .arg(service_pair.first)
            .arg(msg.str());
        return (SR_ERR_VALIDATION_FAILED);
    }
    return (SR_ERR_OK);
}

int
NetconfAgent::update(S_Session sess, const CfgServersMapPair& service_pair) {
448
    // Check if we should and can process this update.
449
    if (NetconfProcess::shut_down ||
450 451 452 453 454 455 456
        !service_pair.second->getSubscribeChanges()) {
        return (SR_ERR_OK);
    }
    CfgControlSocketPtr ctrl_sock = service_pair.second->getCfgControlSocket();
    if (!ctrl_sock) {
        return (SR_ERR_OK);
    }
457 458 459

    // All looks good, let's get started. Print an info that we're about
    // to update the configuration.
460
    LOG_DEBUG(netconf_logger, NETCONF_DBG_TRACE, NETCONF_UPDATE_CONFIG_STARTED)
461
        .arg(service_pair.first);
462 463

    // Retrieve the configuration from SYSREPO first.
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
    ConstElementPtr config;
    try {
        TranslatorConfig tc(sess, service_pair.second->getModel());
        config = tc.getConfig();
        if (!config) {
            ostringstream msg;
            msg << "YANG configuration for "
                << service_pair.second->getModel()
                << " is empty";
            LOG_ERROR(netconf_logger, NETCONF_UPDATE_CONFIG_FAILED)
                .arg(service_pair.first)
                .arg(msg.str());
            return (SR_ERR_VALIDATION_FAILED);
        } else {
            LOG_DEBUG(netconf_logger, NETCONF_DBG_TRACE_DETAIL_DATA,
479
                      NETCONF_UPDATE_CONFIG)
480 481 482 483 484
                .arg(service_pair.first)
                .arg(prettyPrint(config));
        }
    } catch (const std::exception& ex) {
        ostringstream msg;
485
        msg << "get YANG configuration for " << service_pair.first
486 487 488 489 490 491
            << " failed with " << ex.what();
        LOG_ERROR(netconf_logger, NETCONF_UPDATE_CONFIG_FAILED)
            .arg(service_pair.first)
            .arg(msg.str());
        return (SR_ERR_VALIDATION_FAILED);
    }
492
    if (NetconfProcess::shut_down) {
493 494
        return (SR_ERR_OK);
    }
495 496 497

    // Ok, now open the control socket. We need this to send the config to
    // the server.
498 499 500 501 502 503 504 505 506 507 508
    ControlSocketBasePtr comm;
    try {
        comm = createControlSocket(ctrl_sock);
    } catch (const std::exception& ex) {
        ostringstream msg;
        msg << "createControlSocket failed with " << ex.what();
        LOG_ERROR(netconf_logger, NETCONF_UPDATE_CONFIG_FAILED)
            .arg(service_pair.first)
            .arg(msg.str());
        return (SR_ERR_OK);
    }
509 510

    // Now apply the config using config-set command.
511 512 513 514 515 516 517 518 519 520 521 522 523
    ConstElementPtr answer;
    int rcode;
    try {
        answer = comm->configSet(config, service_pair.first);
        parseAnswer(rcode, answer);
    } catch (const std::exception& ex) {
        stringstream msg;
        msg << "configSet failed with " << ex.what();
        LOG_ERROR(netconf_logger, NETCONF_UPDATE_CONFIG_FAILED)
            .arg(service_pair.first)
            .arg(msg.str());
        return (SR_ERR_VALIDATION_FAILED);
    }
524

525
    // rcode == CONTROL_RESULT_SUCCESS, unless the docs say otherwise :).
526 527 528 529 530 531 532 533 534 535 536 537 538
    if (rcode != CONTROL_RESULT_SUCCESS) {
        stringstream msg;
        msg << "configSet returned " << answerToText(answer);
        LOG_ERROR(netconf_logger, NETCONF_UPDATE_CONFIG_FAILED)
            .arg(service_pair.first)
            .arg(msg.str());
        return (SR_ERR_VALIDATION_FAILED);
    }
    return (SR_ERR_OK);
}

void
NetconfAgent::logChanges(S_Session sess, const string& model) {
539
    if (NetconfProcess::shut_down) {
540 541 542 543 544 545 546 547 548
        return;
    }
    S_Iter_Change iter = sess->get_changes_iter(model.c_str());
    if (!iter) {
        LOG_WARN(netconf_logger, NETCONF_LOG_CHANGE_FAIL)
            .arg("no iterator");
        return;
    }
    for (;;) {
549
        if (NetconfProcess::shut_down) {
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
            return;
        }
        S_Change change;
        ostringstream msg;
        try {
            change = sess->get_change_next(iter);
        } catch (const sysrepo_exception& ex) {
            msg << "get change iterator next failed: " << ex.what();
            LOG_WARN(netconf_logger, NETCONF_LOG_CHANGE_FAIL)
                .arg(msg.str());
            return;
        }
        if (!change) {
            // End of changes, not an error.
            return;
        }
566
        if (NetconfProcess::shut_down) {
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 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 615 616 617 618 619
            return;
        }
        S_Val new_val = change->new_val();
        S_Val old_val = change->old_val();
        string report;
        switch (change->oper()) {
        case SR_OP_CREATED:
            if (!new_val) {
                LOG_WARN(netconf_logger, NETCONF_LOG_CHANGE_FAIL)
                    .arg("created but without a new value");
                break;
            }
            msg << "created: " << new_val->to_string();
            report = msg.str();
            boost::erase_all(report, "\n");
            LOG_DEBUG(netconf_logger, NETCONF_DBG_TRACE_DETAIL_DATA,
                      NETCONF_CONFIG_CHANGED_DETAIL)
                .arg(report);
            break;
        case SR_OP_MODIFIED:
            if (!old_val || !new_val) {
                LOG_WARN(netconf_logger, NETCONF_LOG_CHANGE_FAIL)
                    .arg("modified but without an old or new value");
                break;
            }
            msg << "modified: " << old_val->to_string()
                << " => " << new_val->to_string();
            report = msg.str();
            boost::erase_all(report, "\n");
            LOG_DEBUG(netconf_logger, NETCONF_DBG_TRACE_DETAIL_DATA,
                      NETCONF_CONFIG_CHANGED_DETAIL)
                .arg(report);
            break;
        case SR_OP_DELETED:
            if (!old_val) {
                LOG_WARN(netconf_logger, NETCONF_LOG_CHANGE_FAIL)
                    .arg("deleted but without an old value");
                break;
            }
            msg << "deleted: " << old_val->to_string();
            report = msg.str();
            boost::erase_all(report, "\n");
            LOG_DEBUG(netconf_logger, NETCONF_DBG_TRACE_DETAIL_DATA,
                      NETCONF_CONFIG_CHANGED_DETAIL)
                .arg(report);
            break;
        case SR_OP_MOVED:
            if (!new_val) {
                LOG_WARN(netconf_logger, NETCONF_LOG_CHANGE_FAIL)
                    .arg("moved but without a new value");
                break;
            }
            msg << "moved: " << new_val->xpath();
620
            if (!old_val) {
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
                msg << " first";
            } else {
                msg << " after " << old_val->xpath();
            }
            report = msg.str();
            boost::erase_all(report, "\n");
            LOG_DEBUG(netconf_logger, NETCONF_DBG_TRACE_DETAIL_DATA,
                      NETCONF_CONFIG_CHANGED_DETAIL)
                .arg(report);
            break;
        default:
            msg << "unknown operation (" << change->oper() << ")";
            LOG_WARN(netconf_logger, NETCONF_LOG_CHANGE_FAIL)
                .arg(msg.str());
        }
    }
}

} // namespace netconf
} // namespace isc