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
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 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
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 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
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
// Copyright (C) 2018-2025 Internet Systems Consortium, Inc. ("ISC")
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include <config.h>

#include <ha_config_parser.h><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <ha_impl.h><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <ha_log.h><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <asiolink/io_service.h>
#include <cc/data.h>
#include <cc/command_interpreter.h>
#include <dhcp/pkt4.h>
#include <dhcp/pkt6.h>
#include <dhcpsrv/cfgmgr.h>
#include <dhcpsrv/lease.h>
#include <dhcpsrv/shared_network.h>
#include <dhcpsrv/subnet.h>
#include <stats/stats_mgr.h>

using namespace isc::asiolink;
using namespace isc::config;
using namespace isc::data;
using namespace isc::dhcp;
using namespace isc::hooks;
using namespace isc::log;
using namespace isc::stats;

namespace isc {
namespace ha {

HAImpl::HAImpl()
    : io_service_(new IOService()), config_(), services_(new HAServiceMapper()) {
}

void
HAImpl::configure(const ConstElementPtr& input_config) {
    config_ = HAConfigParser::parse(input_config);
}

void
HAImpl::startServices(const NetworkStatePtr& network_state,
                      const HAServerType& server_type) {
    auto configs = config_->getAll();
    for (auto id = 0; id < configs.size(); ++id) {
        // Create the HA service and crank up the state machine.
        auto service = boost::make_shared<HAService>(id, io_service_, network_state,
                                                     configs[id], server_type);
        for (auto const& peer_config : configs[id]->getAllServersConfig()) {
            services_->map(peer_config.first, service);
        }
    }
    // Schedule a start of the services. This ensures we begin after
    // the dust has settled and Kea MT mode has been firmly established.
    io_service_->post([&]() {
        for (auto const& service : services_->getAll()) {
            service->startClientAndListener();
        }
    });
}

HAImpl::~HAImpl() {
    for (auto const& service : services_->getAll()) {
        // Shut down the services explicitly, we need finer control
        // than relying on destruction order.
        service->stopClientAndListener();
    }
    config_.reset();
    services_.reset(new HAServiceMapper());
    io_service_->stopAndPoll();
}

void
HAImpl::buffer4Receive(hooks::CalloutHandle& callout_handle) {
    // If there are multiple relationships, the HA-specific processing is
    // in the subnet4_select hook point.
    if (services_->hasMultiple()) {
        return;
    }

    Pkt4Ptr query4;
    callout_handle.getArgument("query4", query4);

    /// @todo Add unit tests to verify the behavior for different
    /// malformed packets.
    try {
        // We have to unpack the query to get access into HW address which is
        // used to load balance the packet.
        if (callout_handle.getStatus() != CalloutHandle::NEXT_STEP_SKIP) {
            query4->unpack();
        }

    } catch (const SkipRemainingOptionsError& ex) {
        // An option failed to unpack but we are to attempt to process it
        // anyway.  Log it and let's hope for the best.
        LOG_DEBUG(ha_logger, DBGLVL_TRACE_BASIC,
                  HA_BUFFER4_RECEIVE_PACKET_OPTIONS_SKIPPED)
            .arg(ex.what());

    } catch (const std::exception& ex) {
        // Packet parsing failed. Drop the packet.
        LOG_DEBUG(ha_logger, DBGLVL_TRACE_BASIC, HA_BUFFER4_RECEIVE_UNPACK_FAILED)
            .arg(query4->getRemoteAddr().toText())
            .arg(query4->getLocalAddr().toText())
            .arg(query4->getIface())
            .arg(ex.what());

        // Increase the statistics of parse failures and dropped packets.
        StatsMgr::instance().addValue("pkt4-parse-failed", static_cast<int64_t>(1));
        StatsMgr::instance().addValue("pkt4-receive-drop", static_cast<int64_t>(1));


        callout_handle.setStatus(CalloutHandle::NEXT_STEP_DROP);
        return;
    }

    // Check if we should process this query. If not, drop it.
    if (!services_->get()->inScope(query4)) {
        LOG_DEBUG(ha_logger, DBGLVL_TRACE_BASIC, HA_BUFFER4_RECEIVE_NOT_FOR_US)
            .arg(query4->getLabel());
        callout_handle.setStatus(CalloutHandle::NEXT_STEP_DROP);

    } else {
        // We have successfully parsed the query so we have to signal
        // to the server that it must not parse it.
        callout_handle.setStatus(CalloutHandle::NEXT_STEP_SKIP);
    }
}

void
HAImpl::subnet4Select(hooks::CalloutHandle& callout_handle) {
    // This callout only applies in the case of multiple relationships.
    // When there is only one relationship it has no effect because
    // the decision if we should process the packet has been made
    // in the buffer4_receive callout.
    if (!services_->hasMultiple()) {
        // Return silently. It is not an error.
        return;
    }

    Pkt4Ptr query4;
    callout_handle.getArgument("query4", query4);

    ConstSubnet4Ptr subnet4;
    callout_handle.getArgument("subnet4", subnet4);

    // If the server failed to select the subnet this pointer is null.
    // There is nothing we can do with this packet because we don't know
    // which relationship it belongs to. We're even unable to check if the
    // server is responsible for this packet.
    if (!subnet4) {
        // Log at debug level because that's the level at which the server
        // logs the subnet selection failure.
        LOG_DEBUG(ha_logger, DBGLVL_TRACE_BASIC, HA_SUBNET4_SELECT_NO_SUBNET_SELECTED)
            .arg(query4->getLabel());
        callout_handle.setStatus(CalloutHandle::NEXT_STEP_DROP);
        StatsMgr::instance().addValue("pkt4-receive-drop", static_cast<int64_t>(1));
        return;
    }

    // The subnet configuration should contain a user context
    // and this context should contain a mapping of the subnet to a
    // relationship. If the context doesn't exist there is no way
    // to determine which relationship the packet belongs to.
    std::string server_name;
    try {
        server_name = HAConfig::getSubnetServerName(subnet4);
        if (server_name.empty()) {
            LOG_ERROR(ha_logger, HA_SUBNET4_SELECT_NO_RELATIONSHIP_SELECTOR_FOR_SUBNET)
                .arg(query4->getLabel())
                .arg(subnet4->toText());
            callout_handle.setStatus(CalloutHandle::NEXT_STEP_DROP);
            StatsMgr::instance().addValue("pkt4-receive-drop", static_cast<int64_t>(1));
            return;
        }

    } catch (...) {
        LOG_ERROR(ha_logger, HA_SUBNET4_SELECT_INVALID_HA_SERVER_NAME)
            .arg(query4->getLabel())
            .arg(subnet4->toText());
        callout_handle.setStatus(CalloutHandle::NEXT_STEP_DROP);
        StatsMgr::instance().addValue("pkt4-receive-drop", static_cast<int64_t>(1));
        return;
    }

    // Try to find a relationship matching this server name.
    auto service = services_->get(server_name);
    if (!service) {
        LOG_ERROR(ha_logger, HA_SUBNET4_SELECT_NO_RELATIONSHIP_FOR_SUBNET)
            .arg(query4->getLabel())
            .arg(server_name);
        callout_handle.setStatus(CalloutHandle::NEXT_STEP_DROP);
        StatsMgr::instance().addValue("pkt4-receive-drop", static_cast<int64_t>(1));
        return;
    }

    // We have found appropriate relationship. Let's see if we should
    // process the packet. We'll drop the packet if our partner is
    // operational and is responsible for this packet.
    if (!service->inScope(query4)) {
        LOG_DEBUG(ha_logger, DBGLVL_TRACE_BASIC, HA_SUBNET4_SELECT_NOT_FOR_US)
            .arg(query4->getLabel())
            .arg(server_name);
        callout_handle.setStatus(CalloutHandle::NEXT_STEP_DROP);
        return;
    }

    // Remember the server name we retrieved from the subnet. We will
    // need it in a leases4_committed callout that doesn't have access
    // to the subnet object.
    callout_handle.setContext("ha-server-name", server_name);
}

void
HAImpl::leases4Committed(CalloutHandle& callout_handle) {
    Pkt4Ptr query4;
    Lease4CollectionPtr leases4;
    Lease4CollectionPtr deleted_leases4;

    // Get all arguments available for the leases4_committed hook point.
    // If any of these arguments is not available this is a programmatic
    // error. An exception will be thrown which will be caught by the
    // caller and logged.
    callout_handle.getArgument("query4", query4);

    callout_handle.getArgument("leases4", leases4);
    callout_handle.getArgument("deleted_leases4", deleted_leases4);

    // In some cases we may have no leases, e.g. DHCPNAK.
    if (leases4->empty() && deleted_leases4->empty()) {
        LOG_DEBUG(ha_logger, DBGLVL_TRACE_BASIC, HA_LEASES4_COMMITTED_NOTHING_TO_UPDATE)
            .arg(query4->getLabel());
        return;
    }

    // Get default config and service instances.
    HAConfigPtr config = config_->get();
    HAServicePtr service = services_->get();

    // If we have multiple relationships we need to find the one that
    // matches our subnet.
    if (services_->hasMultiple()) {
        try {
            // Retrieve the server name from the context and the respective
            // config and service instances.
            std::string server_name;
            callout_handle.getContext("ha-server-name", server_name);
            config = config_->get(server_name);
            service = services_->get(server_name);

            // This is rather impossible but let's be safe.
            if (!config || !service) {
                isc_throw(Unexpected, "relationship not configured for server '" << server_name << "'");
            }

        } catch (const std::exception& ex) {
            LOG_ERROR(ha_logger, HA_LEASES4_COMMITTED_NO_RELATIONSHIP)
                .arg(query4->getLabel())
                .arg(ex.what());
            callout_handle.setStatus(CalloutHandle::NEXT_STEP_DROP);
            return;
        }
    }

    // If the hook library is configured to not send lease updates to the
    // partner, there is nothing to do because this whole callout is
    // currently about sending lease updates.
    if (!config->amSendingLeaseUpdates()) {
        // No need to log it, because it was already logged when configuration
        // was applied.
        return;
    }

    // Get the parking lot for this hook point. We're going to remember this
    // pointer until we unpark the packet.
    ParkingLotHandlePtr parking_lot = callout_handle.getParkingLotHandlePtr();

    // Create a reference to the parked packet. This signals that we have a
    // stake in unparking it.
    parking_lot->reference(query4);

    // Asynchronously send lease updates. In some cases no updates will be sent,
    // e.g. when this server is in the partner-down state and there are no backup
    // servers. In those cases we simply return without parking the DHCP query.
    // The response will be sent to the client immediately.
    try {
        if (service->asyncSendLeaseUpdates(query4, leases4, deleted_leases4, parking_lot) == 0) {
            // Dereference the parked packet.  This releases our stake in it.
            parking_lot->dereference(query4);
            return;
        }
    } catch (...) {
        // Make sure we dereference.
        parking_lot->dereference(query4);
        throw;
    }

    // The callout returns this status code to indicate to the server that it
    // should leave the packet parked.  It will be parked until each hook
    // library with a reference, unparks the packet.
    callout_handle.setStatus(CalloutHandle::NEXT_STEP_PARK);
}

void
HAImpl::lease4ServerDecline(CalloutHandle& callout_handle) {
    // Always return CONTINUE.
    callout_handle.setStatus(CalloutHandle::NEXT_STEP_CONTINUE);
    size_t peers_to_update = 0;

    // If the hook library is configured to not send lease updates to the
    // partner, there is nothing to do because this whole callout is
    // currently about sending lease updates.
    if (!config_->get()->amSendingLeaseUpdates()) {
        // No need to log it, because it was already logged when configuration
        // was applied.
        callout_handle.setArgument("peers_to_update", peers_to_update);
        return;
    }

    // Get all arguments available for the lease4_server_decline hook point.
    // If any of these arguments is not available this is a programmatic
    // error. An exception will be thrown which will be caught by the
    // caller and logged.
    Pkt4Ptr query4;
    callout_handle.getArgument("query4", query4);

    Lease4Ptr lease4;
    callout_handle.getArgument("lease4", lease4);

    // Asynchronously send the lease update. In some cases no updates will be sent,
    // e.g. when this server is in the partner-down state and there are no backup
    // servers.
    peers_to_update = services_->get()->asyncSendSingleLeaseUpdate(query4, lease4, 0);
    callout_handle.setArgument("peers_to_update", peers_to_update);
}

void
HAImpl::lease4Expire(CalloutHandle& callout_handle) {
    Lease4Ptr lease4;
    callout_handle.getArgument("lease4", lease4);

    // If there are multiple relationships we need to take a detour and find
    // a subnet the lease belongs to. The subnet will contain the information
    // required to select appropriate HA service.
    HAServicePtr service;
    if (services_->hasMultiple()) {
        auto subnet4 = CfgMgr::instance().getCurrentCfg()->getCfgSubnets4()->getBySubnetId(lease4->subnet_id_);
        if (!subnet4) {
            // No subnet means that we possibly have some stale leases that don't
            // really belong to us. Therefore, there we return early and rely on the
            // DHCP server to reclaim them. The HA hook has no jurisdiction here.
            return;
        }

        std::string server_name;
        try {
            server_name = HAConfig::getSubnetServerName(subnet4);
            if (server_name.empty()) {
                // Again, this subnet has no hint for HA where our lease belongs.
                // We have to rely on the server to run reclamation of this lease.
                return;
            }
        } catch (...) {
            // Someone has tried to configure the hint for HA in the subnet but
            // it was poorly specified. We will log an error and leave again.
            LOG_ERROR(ha_logger, HA_LEASE4_EXPIRE_INVALID_HA_SERVER_NAME)
                .arg(lease4->addr_.toText())
                .arg(subnet4->toText());
            return;
        }
        service = services_->get(server_name);

    } else {
        service = services_->get();
    }

    if (!service) {
        // This is highly unlikely but better handle null pointers.
        return;
    }

    if (!shouldReclaim(service, lease4)) {
        // While the server is in the terminated state it has to be careful about
        // reclaiming the leases to avoid conflicting DNS updates with a server that
        // owns the lease. This lease apparently belongs to another server, so we
        // should not reclaim it.
        LOG_DEBUG(ha_logger, DBGLVL_TRACE_BASIC, HA_LEASE4_EXPIRE_RECLAMATION_SKIP)
            .arg(lease4->addr_.toText());
        callout_handle.setStatus(CalloutHandle::NEXT_STEP_SKIP);
        return;
    }
}

void
HAImpl::buffer6Receive(hooks::CalloutHandle& callout_handle) {
    // If there are multiple relationships, the HA-specific processing is
    // in the subnet6_select hook point.
    if (services_->hasMultiple()) {
        return;
    }

    Pkt6Ptr query6;
    callout_handle.getArgument("query6", query6);

    /// @todo Add unit tests to verify the behavior for different
    /// malformed packets.
    try {
        // We have to unpack the query to get access into DUID which is
        // used to load balance the packet.
        if (callout_handle.getStatus() != CalloutHandle::NEXT_STEP_SKIP) {
            query6->unpack();
        }

    } catch (const SkipRemainingOptionsError& ex) {
        // An option failed to unpack but we are to attempt to process it
        // anyway.  Log it and let's hope for the best.
        LOG_DEBUG(ha_logger, DBGLVL_TRACE_BASIC,
                  HA_BUFFER6_RECEIVE_PACKET_OPTIONS_SKIPPED)
            .arg(ex.what());

    } catch (const std::exception& ex) {
        // Packet parsing failed. Drop the packet.
        LOG_DEBUG(ha_logger, DBGLVL_TRACE_BASIC, HA_BUFFER6_RECEIVE_UNPACK_FAILED)
            .arg(query6->getRemoteAddr().toText())
            .arg(query6->getLocalAddr().toText())
            .arg(query6->getIface())
            .arg(ex.what());

        // Increase the statistics of parse failures and dropped packets.
        StatsMgr::instance().addValue("pkt6-parse-failed", static_cast<int64_t>(1));
        StatsMgr::instance().addValue("pkt6-receive-drop", static_cast<int64_t>(1));


        callout_handle.setStatus(CalloutHandle::NEXT_STEP_DROP);
        return;
    }

    // Check if we should process this query. If not, drop it.
    if (!services_->get()->inScope(query6)) {
        LOG_DEBUG(ha_logger, DBGLVL_TRACE_BASIC, HA_BUFFER6_RECEIVE_NOT_FOR_US)
            .arg(query6->getLabel());
        callout_handle.setStatus(CalloutHandle::NEXT_STEP_DROP);

    } else {
        // We have successfully parsed the query so we have to signal
        // to the server that it must not parse it.
        callout_handle.setStatus(CalloutHandle::NEXT_STEP_SKIP);
    }
}

void
HAImpl::subnet6Select(hooks::CalloutHandle& callout_handle) {
    // This callout only applies in the case of multiple relationships.
    // When there is only one relationship it has no effect because
    // the decision if we should process the packet has been made
    // in the buffer6_receive callout.
    if (!services_->hasMultiple()) {
        // Return silently. It is not an error.
        return;
    }

    Pkt6Ptr query6;
    callout_handle.getArgument("query6", query6);

    ConstSubnet6Ptr subnet6;
    callout_handle.getArgument("subnet6", subnet6);

    // If the server failed to select the subnet this pointer is null.
    // There is nothing we can do with this packet because we don't know
    // which relationship it belongs to. We're even unable to check if the
    // server is responsible for this packet.
    if (!subnet6) {
        // Log at debug level because that's the level at which the server
        // logs the subnet selection failure.
        LOG_DEBUG(ha_logger, DBGLVL_TRACE_BASIC, HA_SUBNET6_SELECT_NO_SUBNET_SELECTED)
            .arg(query6->getLabel());
        callout_handle.setStatus(CalloutHandle::NEXT_STEP_DROP);
        StatsMgr::instance().addValue("pkt6-receive-drop", static_cast<int64_t>(1));
        return;
    }

    // The subnet configuration should contain a user context
    // and this context should contain a mapping of the subnet to a
    // relationship. If the context doesn't exist there is no way
    // to determine which relationship the packet belongs to.
    std::string server_name;
    try {
        server_name = HAConfig::getSubnetServerName(subnet6);
        if (server_name.empty()) {
            LOG_ERROR(ha_logger, HA_SUBNET6_SELECT_NO_RELATIONSHIP_SELECTOR_FOR_SUBNET)
                .arg(query6->getLabel())
                .arg(subnet6->toText());
            callout_handle.setStatus(CalloutHandle::NEXT_STEP_DROP);
            StatsMgr::instance().addValue("pkt6-receive-drop", static_cast<int64_t>(1));
            return;
        }

    } catch (...) {
        LOG_ERROR(ha_logger, HA_SUBNET6_SELECT_INVALID_HA_SERVER_NAME)
            .arg(query6->getLabel())
            .arg(subnet6->toText());
        callout_handle.setStatus(CalloutHandle::NEXT_STEP_DROP);
        StatsMgr::instance().addValue("pkt6-receive-drop", static_cast<int64_t>(1));
        return;
    }

    // Try to find a relationship matching this server name.
    auto service = services_->get(server_name);
    if (!service) {
        LOG_ERROR(ha_logger, HA_SUBNET6_SELECT_NO_RELATIONSHIP_FOR_SUBNET)
            .arg(query6->getLabel())
            .arg(server_name);
        callout_handle.setStatus(CalloutHandle::NEXT_STEP_DROP);
        StatsMgr::instance().addValue("pkt6-receive-drop", static_cast<int64_t>(1));
        return;
    }

    // We have found appropriate relationship. Let's see if we should
    // process the packet. We'll drop the packet if our partner is
    // operational and is responsible for this packet.
    if (!service->inScope(query6)) {
        LOG_DEBUG(ha_logger, DBGLVL_TRACE_BASIC, HA_SUBNET6_SELECT_NOT_FOR_US)
            .arg(query6->getLabel())
            .arg(server_name);
        callout_handle.setStatus(CalloutHandle::NEXT_STEP_DROP);
        return;
    }

    // Remember the server name we retrieved from the subnet. We will
    // need it in a leases4_committed callout that doesn't have access
    // to the subnet object.
    callout_handle.setContext("ha-server-name", server_name);
}

void
HAImpl::leases6Committed(CalloutHandle& callout_handle) {
    Pkt6Ptr query6;
    Lease6CollectionPtr leases6;
    Lease6CollectionPtr deleted_leases6;

    // Get all arguments available for the leases6_committed hook point.
    // If any of these arguments is not available this is a programmatic
    // error. An exception will be thrown which will be caught by the
    // caller and logged.
    callout_handle.getArgument("query6", query6);

    callout_handle.getArgument("leases6", leases6);
    callout_handle.getArgument("deleted_leases6", deleted_leases6);

    // In some cases we may have no leases.
    if (leases6->empty() && deleted_leases6->empty()) {
        LOG_DEBUG(ha_logger, DBGLVL_TRACE_BASIC, HA_LEASES6_COMMITTED_NOTHING_TO_UPDATE)
            .arg(query6->getLabel());
        return;
    }

    HAConfigPtr config = config_->get();
    HAServicePtr service = services_->get();
    if (services_->hasMultiple()) {
        try {
            std::string server_name;
            callout_handle.getContext("ha-server-name", server_name);
            config = config_->get(server_name);
            service = services_->get(server_name);

            if (!config || !service) {
                isc_throw(Unexpected, "relationship not found for the ha-server-name='" << server_name << "'");
            }

        } catch (const std::exception& ex) {
            LOG_ERROR(ha_logger, HA_LEASES6_COMMITTED_NO_RELATIONSHIP)
                .arg(query6->getLabel())
                .arg(ex.what());
            callout_handle.setStatus(CalloutHandle::NEXT_STEP_DROP);
            return;
        }
    }

    // If the hook library is configured to not send lease updates to the
    // partner, there is nothing to do because this whole callout is
    // currently about sending lease updates.
    if (!config->amSendingLeaseUpdates()) {
        // No need to log it, because it was already logged when configuration
        // was applied.
        return;
    }

    // Get the parking lot for this hook point. We're going to remember this
    // pointer until we unpark the packet.
    ParkingLotHandlePtr parking_lot = callout_handle.getParkingLotHandlePtr();

    // Create a reference to the parked packet. This signals that we have a
    // stake in unparking it.
    parking_lot->reference(query6);

    // Asynchronously send lease updates. In some cases no updates will be sent,
    // e.g. when this server is in the partner-down state and there are no backup
    // servers. In those cases we simply return without parking the DHCP query.
    // The response will be sent to the client immediately.
    try {
        if (service->asyncSendLeaseUpdates(query6, leases6, deleted_leases6, parking_lot) == 0) {
            // Dereference the parked packet.  This releases our stake in it.
            parking_lot->dereference(query6);
            return;
        }
    } catch (...) {
        // Make sure we dereference.
        parking_lot->dereference(query6);
        throw;
    }

    // The callout returns this status code to indicate to the server that it
    // should leave the packet parked.  It will be unparked until each hook
    // library with a reference, unparks the packet.
    callout_handle.setStatus(CalloutHandle::NEXT_STEP_PARK);
}

void
HAImpl::lease6Expire(CalloutHandle& callout_handle) {
    Lease6Ptr lease6;
    callout_handle.getArgument("lease6", lease6);

    // If there are multiple relationships we need to take a detour and find
    // a subnet the lease belongs to. The subnet will contain the information
    // required to select appropriate HA service.
    HAServicePtr service;
    if (services_->hasMultiple()) {
        auto subnet6 = CfgMgr::instance().getCurrentCfg()->getCfgSubnets6()->getBySubnetId(lease6->subnet_id_);
        if (!subnet6) {
            // No subnet means that we possibly have some stale leases that don't
            // really belong to us. Therefore, there we return early and rely on the
            // DHCP server to reclaim them. The HA hook has no jurisdiction here.
            return;
        }

        std::string server_name;
        try {
            server_name = HAConfig::getSubnetServerName(subnet6);
            if (server_name.empty()) {
                // Again, this subnet has no hint for HA where our lease belongs.
                // We have to rely on the server to run reclamation of this lease.
                return;
            }
        } catch (...) {
            // Someone has tried to configure the hint for HA in the subnet but
            // it was poorly specified. We will log an error and leave again.
            LOG_ERROR(ha_logger, HA_LEASE6_EXPIRE_INVALID_HA_SERVER_NAME)
                .arg(lease6->addr_.toText())
                .arg(subnet6->toText());
            return;
        }
        service = services_->get(server_name);

    } else {
        service = services_->get();
    }

    if (!service) {
        // This is highly unlikely but better handle null pointers.
        return;
    }

    if (!shouldReclaim(service, lease6)) {
        // While the server is in the terminated state it has to be careful about
        // reclaiming the leases to avoid conflicting DNS updates with a server that
        // owns the lease. This lease apparently belongs to another server, so we
        // should not reclaim it.
        LOG_DEBUG(ha_logger, DBGLVL_TRACE_BASIC, HA_LEASE6_EXPIRE_RECLAMATION_SKIP)
            .arg(lease6->addr_.toText());
        callout_handle.setStatus(CalloutHandle::NEXT_STEP_SKIP);
        return;
    }
}

void
HAImpl::commandProcessed(hooks::CalloutHandle& callout_handle) {
    std::string command_name;
    callout_handle.getArgument("name", command_name);
    if (command_name == "status-get") {
        // Get the response.
        ConstElementPtr response;
        callout_handle.getArgument("response", response);
        if (!response || (response->getType() != Element::map)) {
            return;
        }
        // Get the arguments item from the response.
        ConstElementPtr resp_args = response->get("arguments");
        if (!resp_args || (resp_args->getType() != Element::map)) {
            return;
        }
        // Add the ha servers info to arguments.
        ElementPtr mutable_resp_args =
            boost::const_pointer_cast<Element>(resp_args);

        // Process the status get command for each HA service.
        auto ha_relationships = Element::createList();
        for (auto const& service : services_->getAll()) {
            auto ha_relationship = Element::createMap();
            ConstElementPtr ha_servers = service->processStatusGet();
            ha_relationship->set("ha-servers", ha_servers);
            ha_relationship->set("ha-mode", Element::create(HAConfig::HAModeToString(config_->get()->getHAMode())));
            ha_relationships->add(ha_relationship);
            mutable_resp_args->set("high-availability", ha_relationships);
        }
    }
}

void
HAImpl::heartbeatHandler(CalloutHandle& callout_handle) {
    // Command must always be provided.
    ConstElementPtr command;
    callout_handle.getArgument("command", command);

    // Retrieve arguments.
    ConstElementPtr args;
    static_cast<void>(parseCommand(args, command));

    HAServicePtr service;
    try {
        service = getHAServiceByServerName("ha-heartbeat", args);

    } catch (const std::exception& ex) {
        // There was an error while parsing command arguments. Return an error status
        // code to notify the user.
        ConstElementPtr response = createAnswer(CONTROL_RESULT_ERROR, ex.what());
        callout_handle.setArgument("response", response);
        return;
    }

    // Command parsing was successful, so let's process the command.
    ConstElementPtr response = service->processHeartbeat();
    callout_handle.setArgument("response", response);
}

void
HAImpl::synchronizeHandler(hooks::CalloutHandle& callout_handle) {
    // Command must always be provided.
    ConstElementPtr command;
    callout_handle.getArgument("command", command);

    // Retrieve arguments.
    ConstElementPtr args;
    static_cast<void>(parseCommand(args, command));

    ConstElementPtr server_name;
    unsigned int max_period_value = 0;

    HAServicePtr service;
    try {
        // Arguments are required for the ha-sync command.
        if (!args) {
            isc_throw(BadValue, "arguments not found in the 'ha-sync' command");
        }

        // Arguments must be a map.
        if (args->getType() != Element::map) {
            isc_throw(BadValue, "arguments in the 'ha-sync' command are not a map");
        }

        // server-name is mandatory. Otherwise how can we know the server to
        // communicate with.
        server_name = args->get("server-name");
        if (!server_name) {
            isc_throw(BadValue, "'server-name' is mandatory for the 'ha-sync' command");
        }

        // server-name must obviously be a string.
        if (server_name->getType() != Element::string) {
            isc_throw(BadValue, "'server-name' must be a string in the 'ha-sync' command");
        }

        // max-period is optional. In fact it is optional for dhcp-disable command too.
        ConstElementPtr max_period = args->get("max-period");
        if (max_period) {
            // If it is specified, it must be a positive integer.
            if ((max_period->getType() != Element::integer) ||
                (max_period->intValue() <= 0)) {
                isc_throw(BadValue, "'max-period' must be a positive integer in the 'ha-sync' command");
            }

            max_period_value = static_cast<unsigned int>(max_period->intValue());
        }

        service = getHAServiceByServerName("ha-sync", args);

    } catch (const std::exception& ex) {
        // There was an error while parsing command arguments. Return an error status
        // code to notify the user.
        ConstElementPtr response = createAnswer(CONTROL_RESULT_ERROR, ex.what());
        callout_handle.setArgument("response", response);
        return;
    }

    // Command parsing was successful, so let's process the command.
    ConstElementPtr response = service->processSynchronize(server_name->stringValue(),
                                                           max_period_value);
    callout_handle.setArgument("response", response);
}

void
HAImpl::scopesHandler(hooks::CalloutHandle& callout_handle) {
    // Command must always be provided.
    ConstElementPtr command;
    callout_handle.getArgument("command", command);

    // Retrieve arguments.
    ConstElementPtr args;
    static_cast<void>(parseCommand(args, command));

    HAServicePtr service;
    std::vector<std::string> scopes_vector;
    try {
        // Arguments must be present.
        if (!args) {
            isc_throw(BadValue, "arguments not found in the 'ha-scopes' command");
        }

        // Arguments must be a map.
        if (args->getType() != Element::map) {
            isc_throw(BadValue, "arguments in the 'ha-scopes' command are not a map");
        }

        // scopes argument is mandatory.
        ConstElementPtr scopes = args->get("scopes");
        if (!scopes) {
            isc_throw(BadValue, "'scopes' is mandatory for the 'ha-scopes' command");
        }

        // It contains a list of scope names.
        if (scopes->getType() != Element::list) {
            isc_throw(BadValue, "'scopes' must be a list in the 'ha-scopes' command");
        }

        // Retrieve scope names from this list. The list may be empty to clear the
        // scopes.
        for (size_t i = 0; i < scopes->size(); ++i) {
            ConstElementPtr scope = scopes->get(i);
            if (!scope || scope->getType() != Element::string) {
                isc_throw(BadValue, "scope name must be a string in the 'scopes' argument");
            }
            scopes_vector.push_back(scope->stringValue());
        }

        service = getHAServiceByServerName("ha-scopes", args);

    } catch (const std::exception& ex) {
        // There was an error while parsing command arguments. Return an error status
        // code to notify the user.
        ConstElementPtr response = createAnswer(CONTROL_RESULT_ERROR, ex.what());
        callout_handle.setArgument("response", response);
        return;
    }

    // Command parsing was successful, so let's process the command.
    ConstElementPtr response = service->processScopes(scopes_vector);
    callout_handle.setArgument("response", response);
}

void
HAImpl::continueHandler(hooks::CalloutHandle& callout_handle) {
    // Command must always be provided.
    ConstElementPtr command;
    callout_handle.getArgument("command", command);

    // Retrieve arguments.
    ConstElementPtr args;
    static_cast<void>(parseCommand(args, command));

    HAServicePtr service;
    try {
        service = getHAServiceByServerName("ha-continue", args);

    } catch (const std::exception& ex) {
        // There was an error while parsing command arguments. Return an error status
        // code to notify the user.
        ConstElementPtr response = createAnswer(CONTROL_RESULT_ERROR, ex.what());
        callout_handle.setArgument("response", response);
        return;
    }
    ConstElementPtr response = service->processContinue();
    callout_handle.setArgument("response", response);
}

void
HAImpl::maintenanceNotifyHandler(hooks::CalloutHandle& callout_handle) {
    // Command must always be provided.
    ConstElementPtr command;
    callout_handle.getArgument("command", command);

    HAServicePtr service;
    try {
        // Retrieve arguments.
        ConstElementPtr args;
        static_cast<void>(parseCommandWithArgs(args, command));

        ConstElementPtr cancel_op = args->get("cancel");
        if (!cancel_op) {
            isc_throw(BadValue, "'cancel' is mandatory for the 'ha-maintenance-notify' command");
        }

        if (cancel_op->getType() != Element::boolean) {
            isc_throw(BadValue, "'cancel' must be a boolean in the 'ha-maintenance-notify' command");
        }

        ConstElementPtr state = args->get("state");
        if (state && state->getType() != Element::string) {
            isc_throw(BadValue, "'state' must be a string in the 'ha-maintenance-notify' command");
        }

        service = getHAServiceByServerName("ha-maintenance-notify", args);

        ConstElementPtr response = service->processMaintenanceNotify(cancel_op->boolValue(),
                                                                     state ? state->stringValue() : "unavailable");
        callout_handle.setArgument("response", response);

    } catch (const std::exception& ex) {
        // There was an error while parsing command arguments. Return an error status
        // code to notify the user.
        ConstElementPtr response = createAnswer(CONTROL_RESULT_ERROR, ex.what());
        callout_handle.setArgument("response", response);
    }
}

void
HAImpl::maintenanceStartHandler(hooks::CalloutHandle& callout_handle) {
    ConstElementPtr response;
    for (auto const& service : services_->getAll()) {
        response = service->processMaintenanceStart();
        int rcode = CONTROL_RESULT_SUCCESS;
        static_cast<void>(parseAnswer(rcode, response));
        if (rcode != CONTROL_RESULT_SUCCESS) {
            break;
        }
    }
    callout_handle.setArgument("response", response);
}

void
HAImpl::maintenanceCancelHandler(hooks::CalloutHandle& callout_handle) {
    ConstElementPtr response;
    for (auto const& service : services_->getAll()) {
        response = service->processMaintenanceCancel();
    }
    callout_handle.setArgument("response", response);
}

void
HAImpl::haResetHandler(hooks::CalloutHandle& callout_handle) {
    // Command must always be provided.
    ConstElementPtr command;
    callout_handle.getArgument("command", command);

    // Retrieve arguments.
    ConstElementPtr args;
    static_cast<void>(parseCommand(args, command));

    HAServicePtr service;
    try {
        service = getHAServiceByServerName("ha-reset", args);

    } catch (const std::exception& ex) {
        // There was an error while parsing command arguments. Return an error status
        // code to notify the user.
        ConstElementPtr response = createAnswer(CONTROL_RESULT_ERROR, ex.what());
        callout_handle.setArgument("response", response);
        return;
    }

    ConstElementPtr response = service->processHAReset();
    callout_handle.setArgument("response", response);
}

void
HAImpl::syncCompleteNotifyHandler(hooks::CalloutHandle& callout_handle) {
    // Command must always be provided.
    ConstElementPtr command;
    callout_handle.getArgument("command", command);

    // Retrieve arguments.
    ConstElementPtr args;
    static_cast<void>(parseCommand(args, command));

    HAServicePtr service;
    auto origin_id_value = NetworkState::HA_REMOTE_COMMAND+1;
    try {
        if (args) {
            auto origin_id = args->get("origin-id");
            auto origin = args->get("origin");
            // The origin-id is a new parameter replacing the origin. However, some versions
            // of Kea may still send the origin parameter instead.
            if (origin_id) {
                if (origin_id->getType() != Element::integer) {
                    isc_throw(BadValue, "'origin-id' must be an integer in the 'ha-sync-complete-notify' command");
                }
                origin_id_value = origin_id->intValue();

            } else if (origin) {
                if (origin->getType() != Element::integer) {
                    isc_throw(BadValue, "'origin' must be an integer in the 'ha-sync-complete-notify' command");
                }
                origin_id_value = origin->intValue();
            }
        }

        service = getHAServiceByServerName("ha-sync-complete-notify", args);

    } catch (const std::exception& ex) {
        // There was an error while parsing command arguments. Return an error status
        // code to notify the user.
        ConstElementPtr response = createAnswer(CONTROL_RESULT_ERROR, ex.what());
        callout_handle.setArgument("response", response);
        return;
    }

    ConstElementPtr response = service->processSyncCompleteNotify(origin_id_value);
    callout_handle.setArgument("response", response);
}

HAServicePtr
HAImpl::getHAServiceByServerName(const std::string& command_name, ConstElementPtr args) const {
    HAServicePtr service;
    if (args) {
        // Arguments must be a map.
        if (args->getType() != Element::map) {
            isc_throw(BadValue, "arguments in the '" << command_name << "' command are not a map");
        }

        auto server_name = args->get("server-name");

        if (server_name) {
            if (server_name->getType() != Element::string) {
                isc_throw(BadValue, "'server-name' must be a string in the '" << command_name << "' command");
            }
            service = services_->get(server_name->stringValue());
            if (!service) {
                isc_throw(BadValue, server_name->stringValue() << " matches no configured"
                          << " 'server-name'");
            }
        }
    }

    if (!service) {
        service = services_->get();
    }

    return (service);
}

bool
HAImpl::shouldReclaim(const HAServicePtr& service, const dhcp::Lease4Ptr& lease4) const {
    return (service->shouldReclaim(lease4));
}

bool
HAImpl::shouldReclaim(const HAServicePtr& service, const dhcp::Lease6Ptr& lease6) const {
    return (service->shouldReclaim(lease6));
}


} // end of namespace isc::ha
} // end of namespace isc