netconf.cc 19.8 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 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
// 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_;

    /// @brief Module change callback.
    ///
    /// @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*/) {
        if (NetconfProcess::global_shut_down_flag) {
            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");
        if (NetconfProcess::global_shut_down_flag) {
            return (SR_ERR_DISCONNECT);
        }
        NetconfAgent::logChanges(sess, xpath + "logging");
        if (NetconfProcess::global_shut_down_flag) {
            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) {
109
    if (NetconfProcess::global_shut_down_flag || !cfg_mgr) {
110 111
        return;
    }
112 113 114 115 116 117 118
    const CfgServersMapPtr& servers =
        cfg_mgr->getNetconfConfig()->getCfgServersMap();
    for (auto pair : *servers) {
        if (NetconfProcess::global_shut_down_flag) {
            return;
        }
        keaConfig(pair);
119 120 121
        if (NetconfProcess::global_shut_down_flag) {
            return;
        }
122 123 124 125 126
    }
    if (NetconfProcess::global_shut_down_flag) {
        return;
    }
    initSysrepo();
127 128 129
    if (NetconfProcess::global_shut_down_flag) {
        return;
    }
130 131 132 133 134 135 136 137 138
    for (auto pair : *servers) {
        if (NetconfProcess::global_shut_down_flag) {
            return;
        }
        yangConfig(pair);
        if (NetconfProcess::global_shut_down_flag) {
            return;
        }
        subscribe(pair);
139 140 141
        if (NetconfProcess::global_shut_down_flag) {
            return;
        }
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 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
    }
}

void
NetconfAgent::clear() {
    // Should be already set to true but in case...
    NetconfProcess::global_shut_down_flag = true;
    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;
        msg << "configGet failed with " << ex.what();
        LOG_ERROR(netconf_logger, NETCONF_GET_CONFIG_FAILED)
            .arg(service_pair.first)
            .arg(msg.str());
        return;
    }
    if (NetconfProcess::global_shut_down_flag) {
        return;
    }
    if (rcode != CONTROL_RESULT_SUCCESS) {
        ostringstream msg;
        msg << "configGet returned " << answerToText(answer);
        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)
            .arg("configGet returned an empty configuration");
        return;
    }
    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) {
    if (NetconfProcess::global_shut_down_flag ||
        !service_pair.second->getBootUpdate() ||
        service_pair.second->getModel().empty()) {
        return;
    }
    CfgControlSocketPtr ctrl_sock = service_pair.second->getCfgControlSocket();
    if (!ctrl_sock) {
        return;
    }
    LOG_DEBUG(netconf_logger, NETCONF_DBG_TRACE, NETCONF_SET_CONFIG)
        .arg(service_pair.first);
    ConstElementPtr config;
    try {
        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;
        msg << "YANG getConfig for " << service_pair.first
            << " failed with " << ex.what();
        LOG_ERROR(netconf_logger, NETCONF_SET_CONFIG_FAILED)
            .arg(service_pair.first)
            .arg(msg.str());
        return;
    }
    if (NetconfProcess::global_shut_down_flag) {
        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;
    }
    if (NetconfProcess::global_shut_down_flag) {
        return;
    }
    ConstElementPtr answer;
    int rcode;
    try {
        answer = comm->configSet(config, service_pair.first);
        parseAnswer(rcode, answer);
    } catch (const std::exception& ex) {
        ostringstream msg;
        msg << "configSet failed with " << ex.what();
        LOG_ERROR(netconf_logger, NETCONF_SET_CONFIG_FAILED)
            .arg(service_pair.first)
            .arg(msg.str());
        return;
    }
    if (rcode != CONTROL_RESULT_SUCCESS) {
        ostringstream msg;
        msg << "configSet returned " << answerToText(answer);
        LOG_ERROR(netconf_logger, NETCONF_SET_CONFIG_FAILED)
            .arg(service_pair.first)
            .arg(msg.str());
    }
}

void
NetconfAgent::subscribe(const CfgServersMapPair& service_pair) {
    if (NetconfProcess::global_shut_down_flag ||
        !service_pair.second->getSubscribeChanges() ||
        service_pair.second->getModel().empty()) {
        return;
    }
    LOG_DEBUG(netconf_logger, NETCONF_DBG_TRACE, NETCONF_SUBSCRIBE)
        .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();
        LOG_ERROR(netconf_logger, NETCONF_SUBSCRIBE_FAILED)
            .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) {
    if (NetconfProcess::global_shut_down_flag ||
        !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);
    }
    LOG_DEBUG(netconf_logger, NETCONF_DBG_TRACE, NETCONF_VALIDATE_CONFIG)
        .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,
                      NETCONF_VALIDATE_CONFIG_CONFIG)
                .arg(service_pair.first)
                .arg(prettyPrint(config));
        }
    } catch (const std::exception& ex) {
        ostringstream msg;
        msg << "YANG getConfig for " << service_pair.first
            << " 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 (NetconfProcess::global_shut_down_flag) {
        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);
        LOG_ERROR(netconf_logger, NETCONF_VALIDATE_CONFIG_FAILED)
            .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) {
    if (NetconfProcess::global_shut_down_flag ||
        !service_pair.second->getSubscribeChanges()) {
        return (SR_ERR_OK);
    }
    CfgControlSocketPtr ctrl_sock = service_pair.second->getCfgControlSocket();
    if (!ctrl_sock) {
        return (SR_ERR_OK);
    }
    LOG_DEBUG(netconf_logger, NETCONF_DBG_TRACE, NETCONF_UPDATE_CONFIG)
        .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_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,
                      NETCONF_UPDATE_CONFIG_CONFIG)
                .arg(service_pair.first)
                .arg(prettyPrint(config));
        }
    } catch (const std::exception& ex) {
        ostringstream msg;
        msg << "YANG getConfig for " << service_pair.first
            << " failed with " << ex.what();
        LOG_ERROR(netconf_logger, NETCONF_UPDATE_CONFIG_FAILED)
            .arg(service_pair.first)
            .arg(msg.str());
        return (SR_ERR_VALIDATION_FAILED);
    }
    if (NetconfProcess::global_shut_down_flag) {
        return (SR_ERR_OK);
    }
    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);
    }
    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);
    }
    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) {
    if (NetconfProcess::global_shut_down_flag) {
        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 (;;) {
        if (NetconfProcess::global_shut_down_flag) {
            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;
        }
        if (NetconfProcess::global_shut_down_flag) {
            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();
589
            if (!old_val) {
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
                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