1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
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
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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
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
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
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
751
752
753
754
755
756
757
758
759
760
761
762
763
// Copyright (C) 2018-2024 Internet Systems Consortium, Inc. ("ISC")
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

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

#include <config.h>

#include <cc/command_interpreter.h>
#include <netconf/netconf.h>
#include <netconf/netconf_controller.h>
#include <netconf/netconf_log.h>
#include <yang/translator_config.h>
#include <yang/yang_revisions.h>

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

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

namespace {

/// @brief Module change subscription callback.
class NetconfAgentCallback {
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 const service_pair_;

    /// @brief Module configuration change callback.
    ///
    /// This callback is called by sysrepo when there is a change to
    /// module configuration.
    ///
    /// @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.
    sysrepo::ErrorCode moduleChange(Session sess,
                                    uint32_t /* subscription_id */,
                                    string_view module_name,
                                    optional<string_view> /* sub_xpath */,
                                    Event event,
                                    uint32_t /* request_id */) {
        ostringstream event_type;
        switch (event) {
        case Event::Update:
            // This could potentially be a hook point for mid-flight
            // configuration changes.
            event_type << "Event::Update";
            break;
        case Event::Change:
            event_type << "Event::Change";
            break;
        case Event::Done:
            event_type << "Event::Done";
            break;
        case Event::Abort:
            event_type << "Event::Abort";
            break;
        case Event::Enabled:
            event_type << "Event::Enabled";
            break;
        case Event::RPC:
            event_type << "Event::RPC";
            break;
        default:
            event_type << "UNKNOWN (" << event << ")";
            break;
        }
        LOG_INFO(netconf_logger, NETCONF_CONFIG_CHANGE_EVENT)
            .arg(event_type.str());
        NetconfAgent::logChanges(sess, module_name);
        switch (event) {
        case Event::Change:
            return (NetconfAgent::change(sess, service_pair_));
        case Event::Done:
            return (NetconfAgent::done(sess, service_pair_));
        default:
            return (sysrepo::ErrorCode::Ok);
        }
    }

    void eventNotif(Session /* session */,
                    uint32_t /* subscription_id */,
                    NotificationType const notification_type,
                    optional<DataNode> const notification_tree,
                    NotificationTimeStamp const /* timestamp */) {
        string n;
        switch (notification_type) {
        case NotificationType::Realtime:
            n = "NotificationType::Realtime";
            break;
        case NotificationType::Replay:
            n = "NotificationType::Replay";
            break;
        case NotificationType::ReplayComplete:
            n = "NotificationType::ReplayComplete";
            break;
        case NotificationType::Terminated:
            n = "NotificationType::Terminated";
            break;
        case NotificationType::Modified:
            n = "NotificationType::Modified";
            break;
        case NotificationType::Suspended:
            n = "NotificationType::Suspended";
            break;
        case NotificationType::Resumed:
            n = "NotificationType::Resumed";
            break;
        }

        string tree;
        if (notification_tree) {
            optional<string> const str(
                notification_tree->printStr(DataFormat::JSON, PrintFlags::WithDefaultsExplicit));
            if (str) {
                tree = *str;
            }
        }
        LOG_INFO(netconf_logger, NETCONF_NOTIFICATION_RECEIVED)
            .arg(n)
            .arg(service_pair_.first)
            .arg(tree);
    }
};  // NetconfAgentCallback

}  // anonymous namespace

namespace isc {
namespace netconf {

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

void
NetconfAgent::init(NetconfCfgMgrPtr cfg_mgr) {
    // Check for a configuration manager.
    if (!cfg_mgr) {
        isc_throw(Unexpected, "missing configuration manager");
        return;
    }

    // Retrieve configuration from existing running DHCP daemons.
    const CfgServersMapPtr& servers =
        cfg_mgr->getNetconfConfig()->getCfgServersMap();
    for (auto const& pair : *servers) {
        keaConfig(pair);
    }

    // Initialize sysrepo.
    initSysrepo();

    // Check modules / revisions.
    checkModules(servers);

    for (auto const& pair : *servers) {
        yangConfig(pair);
        subscribeToDataChanges(pair);
        subscribeToNotifications(pair);
    }
}

void
NetconfAgent::clear() {
    subscriptions_.clear();
    running_sess_.reset();
    startup_sess_.reset();
}

void
NetconfAgent::keaConfig(const CfgServersMapPair& service_pair) {
    string const& server(service_pair.first);
    CfgServerPtr const& configuration(service_pair.second);

    // If the boot-update flag is not set.
    if (!configuration->getBootUpdate()) {
        return;
    }
    CfgControlSocketPtr ctrl_sock = configuration->getCfgControlSocket();
    if (!ctrl_sock) {
        return;
    }
    ControlSocketBasePtr comm;
    try {
        comm = controlSocketFactory(ctrl_sock);
    } catch (exception const& ex) {
        ostringstream msg;
        msg << "createControlSocket failed with " << ex.what();
        LOG_ERROR(netconf_logger, NETCONF_GET_CONFIG_FAILED)
            .arg(server)
            .arg(msg.str());
        return;
    }
    ConstElementPtr answer;
    int rcode;
    ConstElementPtr config;
    LOG_INFO(netconf_logger, NETCONF_GET_CONFIG_STARTED)
        .arg(server);
    try {
        answer = comm->configGet(server);
        config = parseAnswer(rcode, answer);
    } catch (exception const& ex) {
        ostringstream msg;
        msg << "config-get command failed with " << ex.what();
        LOG_ERROR(netconf_logger, NETCONF_GET_CONFIG_FAILED)
            .arg(server)
            .arg(msg.str());
        return;
    }
    if (rcode != CONTROL_RESULT_SUCCESS) {
        ostringstream msg;
        msg << "config-get command returned " << answerToText(answer);
        LOG_ERROR(netconf_logger, NETCONF_GET_CONFIG_FAILED)
            .arg(server)
            .arg(msg.str());
        return;
    }
    if (!config) {
        LOG_ERROR(netconf_logger, NETCONF_GET_CONFIG_FAILED)
            .arg(server)
            .arg("config-get command returned an empty configuration");
        return;
    }
    LOG_DEBUG(netconf_logger, NETCONF_DBG_TRACE_DETAIL_DATA,
              NETCONF_GET_CONFIG)
        .arg(server)
        .arg(prettyPrint(config));
}

void
NetconfAgent::initSysrepo() {
    try {
        running_sess_ = Connection{}.sessionStart();
        running_sess_->switchDatastore(Datastore::Running);
        startup_sess_ = Connection{}.sessionStart();
        startup_sess_->switchDatastore(Datastore::Startup);
    } catch (exception const& ex) {
        isc_throw(Unexpected, "Can't establish a sysrepo session: " << ex.what());
    }

    // Retrieve names and revisions of installed modules from sysrepo.
    getModules();
}

void
NetconfAgent::getModules() {
    vector<Module> modules;
    try {
        Context context(running_sess_->getContext());
        modules = context.modules();
    } catch (Error const& ex) {
        isc_throw(Unexpected, "can't retrieve available modules: " << ex.what());
    }

    for (Module const& module : modules) {
        string const name(module.name());
        if (!module.revision()) {
            isc_throw(Unexpected, "could not retrieve module revision for module " << name);
        }
        string const revision(*module.revision());
        modules_.emplace(name, revision);
    }
}

bool
NetconfAgent::checkModule(const string& module_name) const {
    auto module = modules_.find(module_name);
    if (module == modules_.end()) {
        LOG_ERROR(netconf_logger, NETCONF_MODULE_MISSING_ERR)
            .arg(module_name);
        return (false);
    }
    auto modrev = YANG_REVISIONS.find(module_name);
    if (modrev == YANG_REVISIONS.end()) {
        // Can't check revision?!
        // It can happen only with a module which is not in
        // YANG_REVISIONS but installed so likely on purpose.
        return (true);
    }
    if (modrev->second != module->second) {
        LOG_ERROR(netconf_logger, NETCONF_MODULE_REVISION_ERR)
            .arg(module_name)
            .arg(modrev->second)
            .arg(module->second);
        return (false);
    }
    return (true);
}

void
NetconfAgent::checkModules(CfgServersMapPtr const& servers /* = {} */) const {
    bool faulty_model(false);
    if (servers) {
        for (auto const& pair : *servers) {
            if (!checkModule(pair.second->getModel())) {
                faulty_model = true;
            }
        }
    }

    if (faulty_model) {
        isc_throw(Unexpected, "YANG module is missing or its revision is not "
                              "supported. Check logs for details.");
    }

    for (auto const& modrev : YANG_REVISIONS) {
        auto module = modules_.find(modrev.first);
        if (module == modules_.end()) {
            LOG_WARN(netconf_logger, NETCONF_MODULE_MISSING_WARN)
                .arg(modrev.first);
            continue;
        }
        if (modrev.second != module->second) {
            LOG_WARN(netconf_logger, NETCONF_MODULE_REVISION_WARN)
                .arg(modrev.first)
                .arg(modrev.second)
                .arg(module->second);
        }
    }
}

void
NetconfAgent::yangConfig(const CfgServersMapPair& service_pair) {
    string const& server(service_pair.first);
    CfgServerPtr const& configuration(service_pair.second);

    // If we're shutting down, or the boot-update flag is not set or the model
    // associated with it is not specified.
    if (!configuration->getBootUpdate() ||
        configuration->getModel().empty()) {
        return;
    }

    // First we need a way to reach the actual servers.
    CfgControlSocketPtr ctrl_sock = configuration->getCfgControlSocket();
    if (!ctrl_sock) {
        return;
    }

    LOG_INFO(netconf_logger, NETCONF_SET_CONFIG_STARTED)
        .arg(server);
    ElementPtr config;
    try {
        // Retrieve configuration from Sysrepo.
        TranslatorConfig tc(*startup_sess_, configuration->getModel());
        config = tc.getConfig();
        if (!config) {
            ostringstream msg;
            msg << "YANG configuration for "
                << configuration->getModel()
                << " is empty";
            LOG_ERROR(netconf_logger, NETCONF_SET_CONFIG_FAILED)
                .arg(server)
                .arg(msg.str());
            return;
        } else {
            LOG_DEBUG(netconf_logger, NETCONF_DBG_TRACE_DETAIL_DATA,
                      NETCONF_SET_CONFIG)
                .arg(server)
                .arg(prettyPrint(config));
        }
    } catch (exception const& ex) {
        ostringstream msg;
        msg << "get YANG configuration for " << server
            << " failed with " << ex.what();
        LOG_ERROR(netconf_logger, NETCONF_SET_CONFIG_FAILED)
            .arg(server)
            .arg(msg.str());
        return;
    }
    ControlSocketBasePtr comm;
    try {
        comm = controlSocketFactory(ctrl_sock);
    } catch (exception const& ex) {
        ostringstream msg;
        msg << "control socket creation failed with " << ex.what();
        LOG_ERROR(netconf_logger, NETCONF_SET_CONFIG_FAILED)
            .arg(server)
            .arg(msg.str());
        return;
    }
    ConstElementPtr answer;
    int rcode;
    try {
        answer = comm->configSet(config, server);
        parseAnswer(rcode, answer);
    } catch (exception const& ex) {
        ostringstream msg;
        msg << "config-set command failed with " << ex.what();
        LOG_ERROR(netconf_logger, NETCONF_SET_CONFIG_FAILED)
            .arg(server)
            .arg(msg.str());
        return;
    }
    if (rcode != CONTROL_RESULT_SUCCESS) {
        ostringstream msg;
        msg << "config-set command returned " << answerToText(answer);
        LOG_ERROR(netconf_logger, NETCONF_SET_CONFIG_FAILED)
            .arg(server)
            .arg(msg.str());
        return;
    }
    LOG_INFO(netconf_logger, NETCONF_BOOT_UPDATE_COMPLETED)
        .arg(server);
}

void
NetconfAgent::subscribeToDataChanges(const CfgServersMapPair& service_pair) {
    string const& server(service_pair.first);
    CfgServerPtr const& configuration(service_pair.second);
    string const& model(configuration->getModel());

    // If we're shutting down, or the subscribe-changes flag is not set or
    // the model is not specified, give up on subscribing.
    if (!configuration->getSubscribeChanges() || model.empty()) {
        return;
    }
    LOG_INFO(netconf_logger, NETCONF_SUBSCRIBE_CONFIG)
        .arg(server)
        .arg(model);
    auto callback = [=](Session session,
                        uint32_t subscription_id,
                        string_view module_name,
                        optional<string_view> sub_xpath,
                        Event event,
                        uint32_t request_id) {
        NetconfAgentCallback agent(service_pair);
        return agent.moduleChange(session, subscription_id, module_name, sub_xpath, event,
                                  request_id);
    };
    try {
        SubscribeOptions options(SubscribeOptions::Default);
        if (!configuration->getValidateChanges()) {
            options = options | SubscribeOptions::DoneOnly;
        }
        auto exception_handler = [model](std::exception& ex) {
            LOG_ERROR(netconf_logger, NETCONF_MODULE_CHANGE_INTERNAL_ERROR)
                .arg(model)
                .arg(ex.what());
        };
        Subscription subscription(
            running_sess_->onModuleChange(model, callback, nullopt, 0, options, exception_handler));
        subscriptions_.emplace(server, std::forward<Subscription>(subscription));
    } catch (exception const& ex) {
        ostringstream msg;
        msg << "module change subscribe failed with " << ex.what();
        msg << "change subscription for model " << model << " failed with: " << ex.what();
        LOG_ERROR(netconf_logger, NETCONF_SUBSCRIBE_CONFIG_FAILED)
            .arg(server)
            .arg(configuration->getModel())
            .arg(msg.str());
        return;
    }
}

void
NetconfAgent::subscribeToNotifications(const CfgServersMapPair& service_pair) {
    string const& server(service_pair.first);
    CfgServerPtr const& configuration(service_pair.second);
    string const& model(configuration->getModel());

    // If we're shutting down, or the subscribe-changes flag is not set or
    // the model is not specified, give up on subscribing.
    if (!configuration->getSubscribeNotifications() || model.empty()) {
        return;
    }
    LOG_INFO(netconf_logger, NETCONF_SUBSCRIBE_NOTIFICATIONS)
        .arg(server)
        .arg(model);

    auto callback = [=](Session session,
                        uint32_t subscription_id,
                        NotificationType const notification_type,
                        optional<DataNode> const notification_tree,
                        NotificationTimeStamp const timestamp) {
        NetconfAgentCallback agent(service_pair);
        return agent.eventNotif(session, subscription_id, notification_type, notification_tree,
                                timestamp);
    };
    try {
        auto exception_handler = [model](std::exception& ex) {
            LOG_ERROR(netconf_logger, NETCONF_NOTIFICATION_INTERNAL_ERROR)
                .arg(model)
                .arg(ex.what());
        };
        Subscription subscription(running_sess_->onNotification(model, callback, nullopt, nullopt,
                                                                nullopt, SubscribeOptions::Default,
                                                                exception_handler));
        subscriptions_.emplace(server, std::forward<Subscription>(subscription));
    } catch (exception const& ex) {
        ostringstream msg;
        msg << "event notification subscription for model " << model <<
            " failed with: " << ex.what();
        LOG_WARN(netconf_logger, NETCONF_NOT_SUBSCRIBED_TO_NOTIFICATIONS)
            .arg(server)
            .arg(configuration->getModel())
            .arg(msg.str());
        return;
    }
}

sysrepo::ErrorCode
NetconfAgent::change(Session sess, const CfgServersMapPair& service_pair) {
    string const& server(service_pair.first);
    CfgServerPtr const& configuration(service_pair.second);

    // If we're shutting down, or the subscribe-changes or the
    // validate-changes flag is not set or the model associated with
    // it is not specified.
    if (!configuration->getSubscribeChanges() ||
        !configuration->getValidateChanges() ||
        configuration->getModel().empty()) {
        return (sysrepo::ErrorCode::Ok);
    }
    CfgControlSocketPtr ctrl_sock = configuration->getCfgControlSocket();
    if (!ctrl_sock) {
        return (sysrepo::ErrorCode::Ok);
    }
    LOG_INFO(netconf_logger, NETCONF_VALIDATE_CONFIG_STARTED)
        .arg(server);
    ElementPtr config;
    try {
        TranslatorConfig tc(sess, configuration->getModel());
        config = tc.getConfig();
        if (!config) {
            ostringstream msg;
            msg << "YANG configuration for "
                << configuration->getModel()
                << " is empty";
            LOG_ERROR(netconf_logger, NETCONF_VALIDATE_CONFIG_FAILED)
                .arg(server)
                .arg(msg.str());
            return (sysrepo::ErrorCode::OperationFailed);
        } else {
            LOG_DEBUG(netconf_logger, NETCONF_DBG_TRACE_DETAIL_DATA,
                      NETCONF_VALIDATE_CONFIG)
                .arg(server)
                .arg(prettyPrint(config));
        }
    } catch (exception const& ex) {
        ostringstream msg;
        msg << "get YANG configuration for " << server
            << " failed with " << ex.what();
        LOG_ERROR(netconf_logger, NETCONF_VALIDATE_CONFIG_FAILED)
            .arg(server)
            .arg(msg.str());
        return (sysrepo::ErrorCode::ValidationFailed);
    }
    ControlSocketBasePtr comm;
    try {
        comm = controlSocketFactory(ctrl_sock);
    } catch (exception const& ex) {
        ostringstream msg;
        msg << "createControlSocket failed with " << ex.what();
        LOG_ERROR(netconf_logger, NETCONF_VALIDATE_CONFIG_FAILED)
            .arg(server)
            .arg(msg.str());
        return (sysrepo::ErrorCode::Ok);
    }
    ConstElementPtr answer;
    int rcode;
    try {
        answer = comm->configTest(config, server);
        parseAnswer(rcode, answer);
    } catch (exception const& ex) {
        stringstream msg;
        msg << "configTest failed with " << ex.what();
        LOG_ERROR(netconf_logger, NETCONF_VALIDATE_CONFIG_FAILED)
            .arg(server)
            .arg(msg.str());
        return (sysrepo::ErrorCode::ValidationFailed);
    }
    if (rcode != CONTROL_RESULT_SUCCESS) {
        stringstream msg;
        msg << "configTest returned " << answerToText(answer);
        LOG_ERROR(netconf_logger, NETCONF_VALIDATE_CONFIG_REJECTED)
            .arg(server)
            .arg(msg.str());
        return (sysrepo::ErrorCode::ValidationFailed);
    }
    LOG_INFO(netconf_logger, NETCONF_VALIDATE_CONFIG_COMPLETED)
        .arg(server);
    return (sysrepo::ErrorCode::Ok);
}

sysrepo::ErrorCode
NetconfAgent::done(Session sess, const CfgServersMapPair& service_pair) {
    string const& server(service_pair.first);
    CfgServerPtr const& configuration(service_pair.second);

    // Check if we should and can process this update.
    if (!configuration->getSubscribeChanges() ||
        configuration->getModel().empty()) {
        return (sysrepo::ErrorCode::Ok);
    }
    CfgControlSocketPtr ctrl_sock = configuration->getCfgControlSocket();
    if (!ctrl_sock) {
        return (sysrepo::ErrorCode::Ok);
    }

    // All looks good, let's get started. Print an info that we're about
    // to update the configuration.
    LOG_INFO(netconf_logger, NETCONF_UPDATE_CONFIG_STARTED)
        .arg(server);

    // Retrieve the configuration from SYSREPO first.
    ElementPtr config;
    try {
        TranslatorConfig tc(sess, configuration->getModel());
        config = tc.getConfig();
        if (!config) {
            ostringstream msg;
            msg << "YANG configuration for "
                << configuration->getModel()
                << " is empty";
            LOG_ERROR(netconf_logger, NETCONF_UPDATE_CONFIG_FAILED)
                .arg(server)
                .arg(msg.str());
            return (sysrepo::ErrorCode::ValidationFailed);
        } else {
            LOG_DEBUG(netconf_logger, NETCONF_DBG_TRACE_DETAIL_DATA,
                      NETCONF_UPDATE_CONFIG)
                .arg(server)
                .arg(prettyPrint(config));
        }
    } catch (exception const& ex) {
        ostringstream msg;
        msg << "get YANG configuration for " << server
            << " failed with " << ex.what();
        LOG_ERROR(netconf_logger, NETCONF_UPDATE_CONFIG_FAILED)
            .arg(server)
            .arg(msg.str());
        return (sysrepo::ErrorCode::ValidationFailed);
    }

    // Ok, now open the control socket. We need this to send the config to
    // the server.
    ControlSocketBasePtr comm;
    try {
        comm = controlSocketFactory(ctrl_sock);
    } catch (exception const& ex) {
        ostringstream msg;
        msg << "createControlSocket failed with " << ex.what();
        LOG_ERROR(netconf_logger, NETCONF_UPDATE_CONFIG_FAILED)
            .arg(server)
            .arg(msg.str());
        return (sysrepo::ErrorCode::Ok);
    }

    // Now apply the config using config-set command.
    ConstElementPtr answer;
    int rcode;
    try {
        answer = comm->configSet(config, server);
        parseAnswer(rcode, answer);
    } catch (exception const& ex) {
        stringstream msg;
        msg << "configSet failed with " << ex.what();
        LOG_ERROR(netconf_logger, NETCONF_UPDATE_CONFIG_FAILED)
            .arg(server)
            .arg(msg.str());
        return (sysrepo::ErrorCode::ValidationFailed);
    }

    // rcode == CONTROL_RESULT_SUCCESS, unless the docs say otherwise :).
    if (rcode != CONTROL_RESULT_SUCCESS) {
        stringstream msg;
        msg << "configSet returned " << answerToText(answer);
        LOG_ERROR(netconf_logger, NETCONF_UPDATE_CONFIG_FAILED)
            .arg(server)
            .arg(msg.str());
        return (sysrepo::ErrorCode::ValidationFailed);
    }
    LOG_INFO(netconf_logger, NETCONF_UPDATE_CONFIG_COMPLETED)
        .arg(server);
    return (sysrepo::ErrorCode::Ok);
}

void
NetconfAgent::logChanges(Session sess, string_view const& model) {
    ostringstream stream;
    stream << "/" << model << ":*//.";
    string const xpath(stream.str());
    ChangeCollection const changes(sess.getChanges(xpath));
    for (Change const& change : changes) {<--- Shadow variable
        ostringstream msg;
        switch (change.operation) {
        case sysrepo::ChangeOperation::Created:
            msg << "created: ";
            break;
        case sysrepo::ChangeOperation::Deleted:
            msg << "deleted: ";
            break;
        case sysrepo::ChangeOperation::Modified:
            msg << "modified: ";
            break;
        case sysrepo::ChangeOperation::Moved:
            msg << "moved: ";
            break;
        default:
            msg << "unknown operation (" << change.operation << "): ";
        }
        string const path(change.node.path());
        msg << path;
        SchemaNode const& schema(change.node.schema());
        NodeType const node_type(schema.nodeType());
        if (node_type == NodeType::Container) {
            msg << " (container)";
        } else if (node_type == NodeType::List) {
            msg << " (list)";
        } else {
            optional<string> const str(
                Translator::translateToYang(Translator::translateFromYang(change.node),
                                            LeafBaseType::Unknown));
            if (str) {
                msg << " = " << *str;
            }
        }

        LOG_DEBUG(netconf_logger, NETCONF_DBG_TRACE_DETAIL_DATA,
                  NETCONF_CONFIG_CHANGED_DETAIL)
            .arg(msg.str());
    }
}

void
NetconfAgent::announceShutdown() const {
    isc::process::DControllerBasePtr& controller(NetconfController::instance());
    if (controller) {
        boost::dynamic_pointer_cast<NetconfController>(controller)
            ->getNetconfProcess()
            ->setShutdownFlag(true);
    }
}

bool
NetconfAgent::shouldShutdown() const {
    return boost::dynamic_pointer_cast<NetconfController>(NetconfController::instance())
        ->getNetconfProcess()
        ->shouldShutdown();
}

}  // namespace netconf
}  // namespace isc