summaryrefslogtreecommitdiffstats
path: root/src/hooks/dhcp/lease_cmds/lease_cmds.cc
blob: f4e8935587a674d54ac3d00e6ad8cdada007696f (plain)
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
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
// Copyright (C) 2017-2021 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 <config/command_mgr.h>
#include <config/cmds_impl.h>
#include <cc/command_interpreter.h>
#include <cc/data.h>
#include <asiolink/io_address.h>
#include <database/db_exceptions.h>
#include <dhcpsrv/cfgmgr.h>
#include <dhcpsrv/dhcpsrv_exceptions.h>
#include <dhcpsrv/lease_mgr.h>
#include <dhcpsrv/lease_mgr_factory.h>
#include <dhcpsrv/ncr_generator.h>
#include <dhcpsrv/resource_handler.h>
#include <dhcpsrv/subnet_id.h>
#include <dhcpsrv/sanity_checker.h>
#include <dhcp/duid.h>
#include <hooks/hooks.h>
#include <exceptions/exceptions.h>
#include <lease_cmds.h>
#include <lease_parser.h>
#include <lease_cmds_log.h>
#include <stats/stats_mgr.h>
#include <util/encode/hex.h>
#include <util/multi_threading_mgr.h>
#include <util/strutil.h>

#include <boost/scoped_ptr.hpp>
#include <boost/algorithm/string.hpp>
#include <string>
#include <sstream>

using namespace isc::dhcp;
using namespace isc::data;
using namespace isc::dhcp_ddns;
using namespace isc::config;
using namespace isc::asiolink;
using namespace isc::hooks;
using namespace isc::stats;
using namespace isc::util;
using namespace std;

namespace isc {
namespace lease_cmds {

/// @brief Wrapper class around reservation command handlers.
class LeaseCmdsImpl : private CmdsImpl {
public:

    /// @brief Parameters specified for lease commands.
    class Parameters {
    public:

        /// @brief specifies type of query (by IP addr, by hwaddr, by DUID)
        typedef enum {
            TYPE_ADDR,      ///< query by IP address (either v4 or v6)
            TYPE_HWADDR,    ///< query by hardware address (v4 only)
            TYPE_DUID,      ///< query by DUID (v6 only)
            TYPE_CLIENT_ID  ///< query by client identifier (v4 only).
        } Type;

        /// @brief Specifies subnet-id (always used)
        SubnetID subnet_id;

        /// @brief Specifies IPv4/v6 address (used when query_type is TYPE_ADDR)
        IOAddress addr;

        /// @brief Specifies hardware address (used when query_type is TYPE_HWADDR)
        HWAddrPtr hwaddr;

        /// @brief Specifies identifier value (used when query_type is TYPE_DUID)
        isc::dhcp::DuidPtr duid;

        /// @brief Specifies identifier value (used when query_type is TYPE_CLIENT_ID)
        isc::dhcp::ClientIdPtr client_id;

        /// @brief Attempts to covert text to one of specified types
        ///
        /// Supported values are: "address", hw-address and duid.
        ///
        /// @param txt text to be converted
        ///
        /// @return value converted to Parameters::Type
        ///
        /// @throw BadValue if unsupported type is specified
        static Type txtToType(const std::string& txt) {
            if (txt == "address") {
                return (Parameters::TYPE_ADDR);
            } else if (txt == "hw-address") {
                return (Parameters::TYPE_HWADDR);
            } else if (txt == "duid") {
                return (Parameters::TYPE_DUID);
            } else if (txt == "client-id") {
                return (Parameters::TYPE_CLIENT_ID);
            } else {
                isc_throw(BadValue, "Incorrect identifier type: "
                          << txt << ", the only supported values are: "
                          "address, hw-address, duid");
            }
        }

        /// @brief specifies parameter types
        Type query_type;

        /// @brief Lease type (NA,TA or PD) used for v6 leases
        Lease::Type lease_type;

        /// @brief IAID identifier used for v6 leases
        uint32_t iaid;

        /// @brief Indicates whether or not DNS should be updated.
        bool updateDDNS;

        /// @brief Default constructor.
        Parameters()
            : subnet_id(0), addr("::"), query_type(TYPE_ADDR),
              lease_type(Lease::TYPE_NA), iaid(0), updateDDNS(false) {
        }
    };

public:

    /// @brief lease4-add, lease6-add command handler
    ///
    /// Provides the implementation for @ref isc::lease_cmds::LeaseCmds::leaseAddHandler
    ///
    /// @param handle Callout context - which is expected to contain the
    /// add command JSON text in the "command" argument
    ///
    /// @return 0 upon success, non-zero otherwise
    int
    leaseAddHandler(CalloutHandle& handle);

    /// @brief lease6-bulk-apply command handler
    ///
    /// Provides the implementation for the
    /// @ref isc::lease_cmds::LeaseCmds::lease6BulkApplyHandler.
    ///
    /// @param handle Callout context - which is expected to contain the
    /// add command JSON text in the "command" argument
    ///
    /// @return 0 upon success, non-zero otherwise
    int
    lease6BulkApplyHandler(CalloutHandle& handle);

    /// @brief lease4-get, lease6-get command handler
    ///
    /// Provides the implementation for @ref isc::lease_cmds::LeaseCmds::leaseGetHandler
    ///
    /// @param handle Callout context - which is expected to contain the
    /// get command JSON text in the "command" argument
    ///
    /// @return 0 upon success, non-zero otherwise
    int
    leaseGetHandler(CalloutHandle& handle);

    /// @brief lease4-get-all, lease6-get-all commands handler
    ///
    /// These commands attempt to retrieve all IPv4 or IPv6 leases,
    /// or all IPv4 or all IPv6 leases belonging to the particular
    /// subnets. If no subnet identifiers are provided, it returns all
    /// IPv4 or IPv6 leases from the database.
    ///
    /// @param handle Callout context - which is expected to contain the
    /// get command JSON text in the "command" argument
    ///
    /// @return 0 upon success, non-zero otherwise.
    int
    leaseGetAllHandler(CalloutHandle& handle);

    /// @brief lease4-get-page, lease6-get-page commands handler
    ///
    /// These commands attempt to retrieve 1 page of leases. The maximum size
    /// of the page is specified by the caller. The caller also specifies
    /// the last address returned in the previous page. The new page
    /// starts from the first address following the address specified by
    /// the caller. If the first page should be returned the IPv4
    /// zero address, IPv6 zero address or the keyword "start" should
    /// be provided instead of the last address.
    ///
    /// @param handle Callout context - which is expected to contain the
    /// get commands JSON text in the "command" argument.
    ///
    /// @return 0 if the handler has been invoked successfully, 1 if an
    /// error occurs, 3 if no leases are returned.
    int
    leaseGetPageHandler(hooks::CalloutHandle& handle);

    /// @brief lease4-get-by-hw-address command handler
    ///
    /// Provides the implementation for @ref isc::lease_cmds::LeaseCmds::leaseGetByHwAddressHandler
    ///
    /// @param handle Callout context - which is expected to contain the
    /// get command JSON text in the "command" argument
    ///
    /// @return 0 if the handler has been invoked successfully, 1 if an
    /// error occurs, 3 if no leases are returned.
    int
    leaseGetByHwAddressHandler(hooks::CalloutHandle& handle);

    /// @brief lease4-get-by-client-id command handler
    ///
    /// Provides the implementation for @ref isc::lease_cmds::LeaseCmds::leaseGetByClientIdHandler
    ///
    /// @param handle Callout context - which is expected to contain the
    /// get command JSON text in the "command" argument
    ///
    /// @return 0 if the handler has been invoked successfully, 1 if an
    /// error occurs, 3 if no leases are returned.
    int
    leaseGetByClientIdHandler(hooks::CalloutHandle& handle);

    /// @brief lease6-get-by-duid command handler
    ///
    /// Provides the implementation for @ref isc::lease_cmds::LeaseCmds::leaseGetByDuidHandler
    ///
    /// @param handle Callout context - which is expected to contain the
    /// get command JSON text in the "command" argument
    ///
    /// @return 0 if the handler has been invoked successfully, 1 if an
    /// error occurs, 3 if no leases are returned.
    int
    leaseGetByDuidHandler(hooks::CalloutHandle& handle);

    /// @brief lease4-get-by-hostname and lease6-get-by-hostname commands
    /// handler
    ///
    /// Provides the implementation for @ref isc::lease_cmds::LeaseCmds::leaseGetByHostnameHandler
    ///
    /// @param handle Callout context - which is expected to contain the
    /// get command JSON text in the "command" argument
    ///
    /// @return 0 if the handler has been invoked successfully, 1 if an
    /// error occurs, 3 if no leases are returned.
    int
    leaseGetByHostnameHandler(hooks::CalloutHandle& handle);

    /// @brief lease4-del command handler
    ///
    /// Provides the implementation for @ref isc::lease_cmds::LeaseCmds::lease4DelHandler
    ///
    /// @param handle Callout context - which is expected to contain the
    /// delete command JSON text in the "command" argument
    ///
    /// @return 0 upon success, non-zero otherwise
    int
    lease4DelHandler(CalloutHandle& handle);

    /// @brief lease6-del command handler
    ///
    /// Provides the implementation for @ref isc::lease_cmds::LeaseCmds::lease6DelHandler
    ///
    /// @param handle Callout context - which is expected to contain the
    /// delete command JSON text in the "command" argument
    ///
    /// @return 0 upon success, non-zero otherwise
    int
    lease6DelHandler(CalloutHandle& handle);

    /// @brief lease4-update handler
    ///
    /// Provides the implementation for @ref isc::lease_cmds::LeaseCmds::lease4UpdateHandler
    ///
    /// @param handle Callout context - which is expected to contain the
    /// update command JSON text in the "command" argument
    ///
    /// @return 0 upon success, non-zero otherwise
    int
    lease4UpdateHandler(CalloutHandle& handle);

    /// @brief lease6-update handler
    ///
    /// Provides the implementation for @ref isc::lease_cmds::LeaseCmds::lease6UpdateHandler
    ///
    /// @param handle Callout context - which is expected to contain the
    /// update command JSON text in the "command" argument
    ///
    /// @return 0 upon success, non-zero otherwise
    int
    lease6UpdateHandler(CalloutHandle& handle);

    /// @brief lease4-wipe handler
    ///
    /// Provides the implementation for @ref isc::lease_cmds::LeaseCmds::lease4WipeHandler
    ///
    /// @param handle Callout context - which is expected to contain the
    /// wipe command JSON text in the "command" argument
    ///
    /// @return 0 upon success, non-zero otherwise
    int
    lease4WipeHandler(CalloutHandle& handle);

    /// @brief lease6-wipe handler
    ///
    /// Provides the implementation for @ref isc::lease_cmds::LeaseCmds::lease6WipeHandler
    ///
    /// @param handle Callout context - which is expected to contain the
    /// wipe command JSON text in the "command" argument
    ///
    /// @return 0 upon success, non-zero otherwise
    int
    lease6WipeHandler(CalloutHandle& handle);

    /// @brief lease4-resend-ddns handler
    ///
    /// Provides the implementation for @ref isc::lease_cmds::LeaseCmds::lease4ResendDdnsHandler
    ///
    /// @param handle Callout context - which is expected to contain the
    /// lease4-resend-ddns command JSON text in the "command" argument
    ///
    /// @return 0 upon success, non-zero otherwise
    int lease4ResendDdnsHandler(CalloutHandle& handle);

    /// @brief lease6-resend-ddns handler
    ///
    /// Provides the implementation for @ref isc::lease_cmds::LeaseCmds::lease6ResendDdnsHandler
    ///
    /// @param handle Callout context - which is expected to contain the
    /// lease6-resend-ddns command JSON text in the "command" argument
    ///
    /// @return 0 upon success, non-zero otherwise
    int lease6ResendDdnsHandler(CalloutHandle& handle);

    /// @brief Extracts parameters required for reservation-get and reservation-del
    ///
    /// See @ref Parameters class for detailed description of what is expected
    /// in the args structure.
    ///
    /// @param v6 whether addresses allowed are v4 (false) or v6 (true)
    /// @param args arguments passed to command
    ///
    /// @return parsed parameters
    ///
    /// @throw BadValue if input arguments don't make sense.
    Parameters getParameters(bool v6, const ConstElementPtr& args);

    /// @brief Convenience function fetching IPv6 address to be used to
    /// delete a lease.
    ///
    /// The returned parameter depends on the @c query_type value stored
    /// in the passed object. Note that the HW address is not allowed and
    /// this query type results in an exception. If the query type is of
    /// the address type, the address is returned. If the type is set to
    /// DUID, this function will try to find the lease for this DUID
    /// and return the corresponding address.
    ///
    /// @param parameters parameters extracted from the command.
    ///
    /// @return Lease of the lease to be deleted.
    ///
    /// @throw InvalidParameter if the DUID is not found when needed to
    /// find the lease or if the query type is by HW address.
    /// @throw InvalidOperation if the query type is unknown.
    Lease6Ptr getIPv6LeaseForDelete(const Parameters& parameters) const;

    /// @brief Returns a map holding brief information about a lease which
    /// failed to be deleted, updated or added.
    ///
    /// The DUID is only included if it is non-null. The address is only
    /// included if it is non-zero.
    ///
    /// @param lease_type lease type.
    /// @param lease_address lease address.
    /// @param duid DUID of the client.
    /// @param control_result Control result: "empty" of the lease was
    /// not found, "error" otherwise.
    /// @param error_message Error message.
    ///
    /// @return The JSON map of the failed leases.
    ElementPtr createFailedLeaseMap(const Lease::Type& lease_type,
                                    const IOAddress& lease_address,
                                    const DuidPtr& duid,
                                    const int control_result,
                                    const std::string& error_message) const;

    /// @brief Fetches an IP address parameter from a map of parameters
    ///
    /// @param map of parameters in which to look
    /// @name name of the parameter desired
    /// @param family expected protocol family of the address parameter,
    /// AF_INET or AF_INET6
    ///
    /// @return IOAddress containing the value of the parameter.
    ///
    /// @throw BadValue if the parameter is missing or invalid
    IOAddress getAddressParam(ConstElementPtr params, const std::string name,
                              short family = AF_INET) const;

    /// @brief Update stats when adding lease.
    ///
    /// @param lease Added lease.
    static void updateStatsOnAdd(const Lease4Ptr& lease);

    /// @brief Update stats when adding lease.
    ///
    /// @param lease Added lease.
    static void updateStatsOnAdd(const Lease6Ptr& lease);

    /// @brief Update stats when updating lease.
    ///
    /// @param existing Lease data before update.
    /// @param lease Lease data after update.
    static void updateStatsOnUpdate(const Lease4Ptr& existing,
                                    const Lease4Ptr& lease);

    /// @brief Update stats when updating lease.
    ///
    /// @param existing Lease data before update.
    /// @param lease Lease data after update.
    static void updateStatsOnUpdate(const Lease6Ptr& existing,
                                    const Lease6Ptr& lease);

    /// @brief Update stats when deleting lease.
    ///
    /// @param lease Deleted lease.
    static void updateStatsOnDelete(const Lease4Ptr& lease);

    /// @brief Update stats when deleting lease.
    ///
    /// @param lease Deleted lease.
    static void updateStatsOnDelete(const Lease6Ptr& lease);

    /// @brief Add or update lease.
    ///
    /// @param lease The lease to be added or updated (if exists).
    /// @param force_create Flag to indicate if the function should try to
    /// create the lease if it does not exists, or simply update and fail in
    /// such case.
    ///
    /// @return true if lease has been successfully added, false otherwise.
    static bool addOrUpdate4(Lease4Ptr lease, bool force_create);

    /// @brief Add or update lease.
    ///
    /// @param lease The lease to be added or updated (if exists).
    /// @param force_create Flag to indicate if the function should try to
    /// create the lease if it does not exists, or simply update and fail in
    /// such case.
    ///
    /// @return true if lease has been successfully added, false otherwise.
    static bool addOrUpdate6(Lease6Ptr lease, bool force_create);
};

void
LeaseCmdsImpl::updateStatsOnAdd(const Lease4Ptr& lease) {
    if (!lease->stateExpiredReclaimed()) {
        StatsMgr::instance().addValue(
            StatsMgr::generateName("subnet", lease->subnet_id_,
                                   "assigned-addresses"),
            int64_t(1));
        if (lease->stateDeclined()) {
            StatsMgr::instance().addValue("declined-addresses", int64_t(1));

            StatsMgr::instance().addValue(
                StatsMgr::generateName("subnet", lease->subnet_id_,
                                       "declined-addresses"),
                int64_t(1));
        }
    }
}

void
LeaseCmdsImpl::updateStatsOnAdd(const Lease6Ptr& lease) {
    if (!lease->stateExpiredReclaimed()) {
        StatsMgr::instance().addValue(
            StatsMgr::generateName("subnet", lease->subnet_id_,
                                   lease->type_ == Lease::TYPE_NA ?
                                   "assigned-nas" : "assigned-pds"),
            int64_t(1));
        if (lease->stateDeclined()) {
            StatsMgr::instance().addValue("declined-addresses", int64_t(1));

            StatsMgr::instance().addValue(
                StatsMgr::generateName("subnet", lease->subnet_id_,
                                       "declined-addresses"),
                int64_t(1));
        }
    }
}

void
LeaseCmdsImpl::updateStatsOnUpdate(const Lease4Ptr& existing,
                                   const Lease4Ptr& lease) {
    if (!existing->stateExpiredReclaimed()) {
        // old lease is non expired-reclaimed
        if (existing->subnet_id_ != lease->subnet_id_) {
            StatsMgr::instance().addValue(
                StatsMgr::generateName("subnet", existing->subnet_id_,
                                       "assigned-addresses"),
                int64_t(-1));
        }
        if (existing->stateDeclined()) {
            // old lease is declined
            StatsMgr::instance().addValue("declined-addresses", int64_t(-1));

            StatsMgr::instance().addValue(
                StatsMgr::generateName("subnet", existing->subnet_id_,
                                       "declined-addresses"),
                int64_t(-1));
        }
        if (!lease->stateExpiredReclaimed()) {
            // new lease is non expired-reclaimed
            if (existing->subnet_id_ != lease->subnet_id_) {
                StatsMgr::instance().addValue(
                    StatsMgr::generateName("subnet", lease->subnet_id_,
                                           "assigned-addresses"),
                    int64_t(1));
            }
            if (lease->stateDeclined()) {
                // new lease is declined
                StatsMgr::instance().addValue("declined-addresses", int64_t(1));

                StatsMgr::instance().addValue(
                    StatsMgr::generateName("subnet", lease->subnet_id_,
                                           "declined-addresses"),
                    int64_t(1));
            }
        }
    } else {
        // old lease is expired-reclaimed
        if (!lease->stateExpiredReclaimed()) {
            // new lease is non expired-reclaimed
            StatsMgr::instance().addValue(
                StatsMgr::generateName("subnet", lease->subnet_id_,
                                       "assigned-addresses"),
                int64_t(1));
            if (lease->stateDeclined()) {
                // new lease is declined
                StatsMgr::instance().addValue("declined-addresses", int64_t(1));

                StatsMgr::instance().addValue(
                    StatsMgr::generateName("subnet", lease->subnet_id_,
                                           "declined-addresses"),
                    int64_t(1));
            }
        }
    }
}

void
LeaseCmdsImpl::updateStatsOnUpdate(const Lease6Ptr& existing,
                                   const Lease6Ptr& lease) {
    if (!existing->stateExpiredReclaimed()) {
        // old lease is non expired-reclaimed
        if (existing->subnet_id_ != lease->subnet_id_) {
            StatsMgr::instance().addValue(
                StatsMgr::generateName("subnet", existing->subnet_id_,
                                       lease->type_ == Lease::TYPE_NA ?
                                       "assigned-nas" : "assigned-pds"),
                int64_t(-1));
        }
        if (existing->stateDeclined()) {
            // old lease is declined
            StatsMgr::instance().addValue("declined-addresses", int64_t(-1));

            StatsMgr::instance().addValue(
                StatsMgr::generateName("subnet", existing->subnet_id_,
                                       "declined-addresses"),
                int64_t(-1));
        }
        if (!lease->stateExpiredReclaimed()) {
            // new lease is non expired-reclaimed
            if (existing->subnet_id_ != lease->subnet_id_) {
                StatsMgr::instance().addValue(
                    StatsMgr::generateName("subnet", lease->subnet_id_,
                                           lease->type_ == Lease::TYPE_NA ?
                                           "assigned-nas" : "assigned-pds"),
                    int64_t(1));
            }
            if (lease->stateDeclined()) {
                // new lease is declined
                StatsMgr::instance().addValue("declined-addresses", int64_t(1));

                StatsMgr::instance().addValue(
                    StatsMgr::generateName("subnet", lease->subnet_id_,
                                           "declined-addresses"),
                    int64_t(1));
            }
        }
    } else {
        // old lease is expired-reclaimed
        if (!lease->stateExpiredReclaimed()) {
            // new lease is non expired-reclaimed
            StatsMgr::instance().addValue(
                StatsMgr::generateName("subnet", lease->subnet_id_,
                                       lease->type_ == Lease::TYPE_NA ?
                                       "assigned-nas" : "assigned-pds"),
                int64_t(1));
            if (lease->stateDeclined()) {
                // new lease is declined
                StatsMgr::instance().addValue("declined-addresses", int64_t(1));

                StatsMgr::instance().addValue(
                    StatsMgr::generateName("subnet", lease->subnet_id_,
                                           "declined-addresses"),
                    int64_t(1));
            }
        }
    }
}

void
LeaseCmdsImpl::updateStatsOnDelete(const Lease4Ptr& lease) {
    if (!lease->stateExpiredReclaimed()) {
        StatsMgr::instance().addValue(
            StatsMgr::generateName("subnet", lease->subnet_id_,
                                   "assigned-addresses"),
            int64_t(-1));
        if (lease->stateDeclined()) {
            StatsMgr::instance().addValue("declined-addresses", int64_t(-1));

            StatsMgr::instance().addValue(
                StatsMgr::generateName("subnet", lease->subnet_id_,
                                       "declined-addresses"),
                int64_t(-1));
        }
    }
}

void
LeaseCmdsImpl::updateStatsOnDelete(const Lease6Ptr& lease) {
    if (!lease->stateExpiredReclaimed()) {
        StatsMgr::instance().addValue(
            StatsMgr::generateName("subnet", lease->subnet_id_,
                                   lease->type_ == Lease::TYPE_NA ?
                                   "assigned-nas" : "assigned-pds"),
            int64_t(-1));
        if (lease->stateDeclined()) {
            StatsMgr::instance().addValue("declined-addresses", int64_t(-1));

            StatsMgr::instance().addValue(
                StatsMgr::generateName("subnet", lease->subnet_id_,
                                       "declined-addresses"),
                int64_t(-1));
        }
    }
}

bool
LeaseCmdsImpl::addOrUpdate4(Lease4Ptr lease, bool force_create) {
    Lease4Ptr existing = LeaseMgrFactory::instance().getLease4(lease->addr_);
    if (force_create && !existing) {
        // lease does not exist
        if (!LeaseMgrFactory::instance().addLease(lease)) {
            isc_throw(db::DuplicateEntry,
                      "lost race between calls to get and add");
        }
        LeaseCmdsImpl::updateStatsOnAdd(lease);
        return (true);
    }
    if (existing) {
        // Update lease current expiration time with value received from the
        // database. Some database backends reject operations on the lease if
        // the current expiration time value does not match what is stored.
        Lease::syncCurrentExpirationTime(*existing, *lease);
    }
    try {
        LeaseMgrFactory::instance().updateLease4(lease);
    } catch (const NoSuchLease&) {
        isc_throw(InvalidOperation, "failed to update the lease with address "
                  << lease->addr_ << " either because the lease has been "
                  "deleted or it has changed in the database, in both cases a "
                  "retry might succeed");
    }

    LeaseCmdsImpl::updateStatsOnUpdate(existing, lease);
    return (false);
}

bool
LeaseCmdsImpl::addOrUpdate6(Lease6Ptr lease, bool force_create) {
    Lease6Ptr existing =
        LeaseMgrFactory::instance().getLease6(lease->type_, lease->addr_);
    if (force_create && !existing) {
        // lease does not exist
        if (!LeaseMgrFactory::instance().addLease(lease)) {
            isc_throw(db::DuplicateEntry,
                      "lost race between calls to get and add");
        }
        LeaseCmdsImpl::updateStatsOnAdd(lease);
        return (true);
    }
    if (existing) {
        // Update lease current expiration time with value received from the
        // database. Some database backends reject operations on the lease if
        // the current expiration time value does not match what is stored.
        Lease::syncCurrentExpirationTime(*existing, *lease);
    }
    try {
        LeaseMgrFactory::instance().updateLease6(lease);
    } catch (const NoSuchLease&) {
        isc_throw(InvalidOperation, "failed to update the lease with address "
                  << lease->addr_ << " either because the lease has been "
                  "deleted or it has changed in the database, in both cases a "
                  "retry might succeed");
    }

    LeaseCmdsImpl::updateStatsOnUpdate(existing, lease);
    return (false);
}

int
LeaseCmdsImpl::leaseAddHandler(CalloutHandle& handle) {
    // Arbitrary defaulting to DHCPv4 or with other words extractCommand
    // below is not expected to throw...
    bool v4 = true;
    string txt = "malformed command";

    stringstream resp;
    try {
        extractCommand(handle);
        v4 = (cmd_name_ == "lease4-add");

        txt = "(missing parameters)";
        if (!cmd_args_) {
            isc_throw(isc::BadValue, "no parameters specified for the command");
        }

        txt = cmd_args_->str();

        ConstSrvConfigPtr config = CfgMgr::instance().getCurrentCfg();

        Lease4Ptr lease4;
        Lease6Ptr lease6;
        // This parameter is ignored for the commands adding the lease.
        bool force_create = false;
        if (v4) {
            Lease4Parser parser;
            lease4 = parser.parse(config, cmd_args_, force_create);
            if (lease4) {
                bool success;
                if (!MultiThreadingMgr::instance().getMode()) {
                    // Not multi-threading.
                    success = LeaseMgrFactory::instance().addLease(lease4);
                } else {
                    // Multi-threading, try to lock first to avoid a race.
                    ResourceHandler4 resource_handler;
                    if (resource_handler.tryLock4(lease4->addr_)) {
                        success = LeaseMgrFactory::instance().addLease(lease4);
                    } else {
                        isc_throw(ResourceBusy,
                                  "ResourceBusy: IP address:" << lease4->addr_
                                  << " could not be added.");
                    }
                }

                if (!success) {
                    isc_throw(db::DuplicateEntry, "IPv4 lease already exists.");
                }

                LeaseCmdsImpl::updateStatsOnAdd(lease4);
                resp << "Lease for address " << lease4->addr_.toText()
                     << ", subnet-id " << lease4->subnet_id_ << " added.";
            }
        } else {
            Lease6Parser parser;
            lease6 = parser.parse(config, cmd_args_, force_create);
            if (lease6) {
                bool success;
                if (!MultiThreadingMgr::instance().getMode()) {
                    // Not multi-threading.
                    success = LeaseMgrFactory::instance().addLease(lease6);
                } else {
                    // Multi-threading, try to lock first to avoid a race.
                    ResourceHandler resource_handler;
                    if (resource_handler.tryLock(lease6->type_, lease6->addr_)) {
                        success = LeaseMgrFactory::instance().addLease(lease6);
                    } else {
                        isc_throw(ResourceBusy,
                                  "ResourceBusy: IP address:" << lease6->addr_
                                  << " could not be added.");
                    }
                }

                if (!success) {
                    isc_throw(db::DuplicateEntry, "IPv6 lease already exists.");
                }

                LeaseCmdsImpl::updateStatsOnAdd(lease6);
                if (lease6->type_ == Lease::TYPE_NA) {
                    resp << "Lease for address " << lease6->addr_.toText()
                         << ", subnet-id " << lease6->subnet_id_ << " added.";
                } else {
                    resp << "Lease for prefix " << lease6->addr_.toText()
                         << "/" << static_cast<int>(lease6->prefixlen_)
                         << ", subnet-id " << lease6->subnet_id_ << " added.";
                }
            }
        }

    } catch (const std::exception& ex) {
        LOG_ERROR(lease_cmds_logger, v4 ? LEASE_CMDS_ADD4_FAILED : LEASE_CMDS_ADD6_FAILED)
            .arg(txt)
            .arg(ex.what());
        setErrorResponse(handle, ex.what());
        return (1);
    }

    LOG_INFO(lease_cmds_logger,
             v4 ? LEASE_CMDS_ADD4 : LEASE_CMDS_ADD6).arg(txt);
    setSuccessResponse(handle, resp.str());
    return (0);
}

LeaseCmdsImpl::Parameters
LeaseCmdsImpl::getParameters(bool v6, const ConstElementPtr& params) {
    Parameters x;

    if (!params || params->getType() != Element::map) {
        isc_throw(BadValue, "Parameters missing or are not a map.");
    }

    if (params->contains("update-ddns")) {
        ConstElementPtr tmp = params->get("update-ddns");
        if (tmp->getType() != Element::boolean) {
            isc_throw(BadValue, "'update-ddns' is not a boolean");
        } else {
            x.updateDDNS = tmp->boolValue();
        }
    }

    // We support several sets of parameters for leaseX-get/lease-del:
    // lease-get(type, address)
    // lease-get(type, subnet-id, identifier-type, identifier)

    if (params->contains("type")) {
        string t = params->get("type")->stringValue();
        if (t == "IA_NA" || t == "0") {
            x.lease_type = Lease::TYPE_NA;
        } else if (t == "IA_TA" || t == "1") {
            x.lease_type = Lease::TYPE_TA;
        } else if (t == "IA_PD" || t == "2") {
            x.lease_type = Lease::TYPE_PD;
        } else if (t == "V4" || t == "3") {
            x.lease_type = Lease::TYPE_V4;
        } else {
            isc_throw(BadValue, "Invalid lease type specified: "
                      << t << ", only supported values are: IA_NA, IA_TA,"
                      << " IA_PD and V4");
        }
    }

    ConstElementPtr tmp = params->get("ip-address");
    if (tmp) {
        if (tmp->getType() != Element::string) {
            isc_throw(BadValue, "'ip-address' is not a string.");
        }

        x.addr = IOAddress(tmp->stringValue());

        if ((v6 && !x.addr.isV6()) || (!v6 && !x.addr.isV4())) {
            stringstream txt;
            txt << "Invalid " << (v6 ? "IPv6" : "IPv4")
                << " address specified: " << tmp->stringValue();
            isc_throw(BadValue, txt.str());
        }

        x.query_type = Parameters::TYPE_ADDR;
        return (x);
    }

    tmp = params->get("subnet-id");
    if (!tmp) {
        isc_throw(BadValue, "Mandatory 'subnet-id' parameter missing.");
    }
    if (tmp->getType() != Element::integer) {
        isc_throw(BadValue, "'subnet-id' parameter is not integer.");
    }
    x.subnet_id = tmp->intValue();

    if (params->contains("iaid")) {
        x.iaid = params->get("iaid")->intValue();
    }

    // No address specified. Ok, so it must be identifier based query.
    // "identifier-type": "duid",
    // "identifier": "aa:bb:cc:dd:ee:..."

    ConstElementPtr type = params->get("identifier-type");
    ConstElementPtr ident = params->get("identifier");
    if (!type || type->getType() != Element::string) {
        isc_throw(BadValue, "No 'ip-address' provided"
                  " and 'identifier-type' is either missing or not a string.");
    }
    if (!ident || ident->getType() != Element::string) {
        isc_throw(BadValue, "No 'ip-address' provided"
                  " and 'identifier' is either missing or not a string.");
    }

    // Got the parameters. Let's see if their values make sense.
    // Try to convert identifier-type
    x.query_type = Parameters::txtToType(type->stringValue());

    switch (x.query_type) {
    case Parameters::TYPE_HWADDR: {
        HWAddr hw = HWAddr::fromText(ident->stringValue());
        x.hwaddr = HWAddrPtr(new HWAddr(hw));
        break;
    }
    case Parameters::TYPE_CLIENT_ID: {
        x.client_id = ClientId::fromText(ident->stringValue());
        break;
    }
    case Parameters::TYPE_DUID: {
        DUID duid = DUID::fromText(ident->stringValue());
        x.duid = DuidPtr(new DUID(duid));
        break;
    }
    case Parameters::TYPE_ADDR: {
        // We should never get here. The address clause should have been caught
        // earlier.
        return (x);
    }
    default: {
        isc_throw(BadValue, "Identifier type " << type->stringValue() <<
                  " is not supported.");
    }
    }

    return (x);
}

int
LeaseCmdsImpl::leaseGetHandler(CalloutHandle& handle) {
    Parameters p;
    Lease4Ptr lease4;
    Lease6Ptr lease6;
    bool v4;
    try {
        extractCommand(handle);
        v4 = (cmd_name_ == "lease4-get");

        p = getParameters(!v4, cmd_args_);
        switch (p.query_type) {
        case Parameters::TYPE_ADDR: {
            // Query by address
            if (v4) {
                lease4 = LeaseMgrFactory::instance().getLease4(p.addr);
            } else {
                lease6 = LeaseMgrFactory::instance().getLease6(p.lease_type, p.addr);
            }
            break;
        }
        case Parameters::TYPE_HWADDR:
            if (v4) {
                if (!p.hwaddr) {
                    isc_throw(InvalidParameter, "Program error: Query by hw-address "
                                                "requires hwaddr to be specified");
                }

                lease4 = LeaseMgrFactory::instance().getLease4(*p.hwaddr, p.subnet_id);
            } else {
                isc_throw(isc::InvalidParameter, "Query by hw-address is not allowed in v6.");
            }
            break;

        case Parameters::TYPE_DUID:
            if (!v4) {
                if (!p.duid) {
                    isc_throw(InvalidParameter, "Program error: Query by duid "
                                                "requires duid to be specified");
                }

                lease6 = LeaseMgrFactory::instance().getLease6(p.lease_type, *p.duid,
                                                               p.iaid, p.subnet_id);
            } else {
                isc_throw(InvalidParameter, "Query by duid is not allowed in v4.");
            }
            break;

        case Parameters::TYPE_CLIENT_ID:
            if (v4) {
                if (!p.client_id) {
                    isc_throw(InvalidParameter, "Program error: Query by client-id "
                                                "requires client-id to be specified");
                }

                lease4 = LeaseMgrFactory::instance().getLease4(*p.client_id, p.subnet_id);
            } else {
                isc_throw(isc::InvalidParameter, "Query by client-id is not allowed in v6.");
            }
            break;

        default: {
            isc_throw(InvalidOperation, "Unknown query type: " << static_cast<int>(p.query_type));
            break;
        }
        }
    } catch (const std::exception& ex) {
        setErrorResponse(handle, ex.what());
        return (1);
    }

    ElementPtr lease_json;
    if (v4 && lease4) {
        lease_json = lease4->toElement();
        ConstElementPtr response = createAnswer(CONTROL_RESULT_SUCCESS,
                                                "IPv4 lease found.", lease_json);
        setResponse(handle, response);
    } else if (!v4 && lease6) {
        lease_json = lease6->toElement();
        ConstElementPtr response = createAnswer(CONTROL_RESULT_SUCCESS,
                                                "IPv6 lease found.", lease_json);
        setResponse(handle, response);
    } else {
        // If we got here, the lease has not been found.
        setErrorResponse(handle, "Lease not found.", CONTROL_RESULT_EMPTY);
    }

    return (0);
}

int
LeaseCmdsImpl::leaseGetAllHandler(CalloutHandle& handle) {
    bool v4 = true;
    try {
        extractCommand(handle);
        v4 = (cmd_name_ == "lease4-get-all");

        ElementPtr leases_json = Element::createList();

        // The argument may contain a list of subnets for which leases should
        // be returned.
        if (cmd_args_) {
            ConstElementPtr subnets = cmd_args_->get("subnets");
            if (!subnets) {
                isc_throw(BadValue, "'subnets' parameter not specified");
            }
            if (subnets->getType() != Element::list) {
                isc_throw(BadValue, "'subnets' parameter must be a list");
            }

            const std::vector<ElementPtr>& subnet_ids = subnets->listValue();
            for (auto subnet_id = subnet_ids.begin();
                 subnet_id != subnet_ids.end();
                 ++subnet_id) {
                if ((*subnet_id)->getType() != Element::integer) {
                    isc_throw(BadValue, "listed subnet identifiers must be numbers");
                }

                if (v4) {
                    Lease4Collection leases =
                        LeaseMgrFactory::instance().getLeases4((*subnet_id)->intValue());
                    for (auto lease : leases) {
                        ElementPtr lease_json = lease->toElement();
                        leases_json->add(lease_json);
                    }
                } else {
                    Lease6Collection leases =
                        LeaseMgrFactory::instance().getLeases6((*subnet_id)->intValue());
                    for (auto lease : leases) {
                        ElementPtr lease_json = lease->toElement();
                        leases_json->add(lease_json);
                    }
                }
            }

        } else {
            // There is no 'subnets' argument so let's return all leases.
            if (v4) {
                Lease4Collection leases = LeaseMgrFactory::instance().getLeases4();
                for (auto lease : leases) {
                    ElementPtr lease_json = lease->toElement();
                    leases_json->add(lease_json);
                }
            } else {
                Lease6Collection leases = LeaseMgrFactory::instance().getLeases6();
                for (auto lease : leases) {
                    ElementPtr lease_json = lease->toElement();
                    leases_json->add(lease_json);
                }
            }
        }

        std::ostringstream s;
        s << leases_json->size()
          << " IPv" << (v4 ? "4" : "6")
          << " lease(s) found.";
        ElementPtr args = Element::createMap();
        args->set("leases", leases_json);
        ConstElementPtr response =
            createAnswer(leases_json->size() > 0 ?
                         CONTROL_RESULT_SUCCESS :
                         CONTROL_RESULT_EMPTY,
                         s.str(), args);
        setResponse(handle, response);

    } catch (const std::exception& ex) {
        setErrorResponse(handle, ex.what());
        return (CONTROL_RESULT_ERROR);
    }

    return (0);
}

int
LeaseCmdsImpl::leaseGetPageHandler(CalloutHandle& handle) {
    bool v4 = true;
    try {
        extractCommand(handle);
        v4 = (cmd_name_ == "lease4-get-page");

        // arguments must always be present
        if (!cmd_args_) {
            isc_throw(BadValue, "no parameters specified for the " << cmd_name_
                      << " command");
        }

        // The 'from' argument denotes from which lease we should start the
        // results page. The results page excludes this lease.
        ConstElementPtr from = cmd_args_->get("from");
        if (!from) {
            isc_throw(BadValue, "'from' parameter not specified");
        }

        // The 'from' argument is a string. It may contain a 'start' keyword or
        // an IP address.
        if (from->getType() != Element::string) {
            isc_throw(BadValue, "'from' parameter must be a string");
        }

        boost::scoped_ptr<IOAddress> from_address;
        try {
            if (from->stringValue() == "start") {
                from_address.reset(new IOAddress(v4 ? "0.0.0.0" : "::"));

            } else {
                // Conversion of a string to an IP address may throw.
                from_address.reset(new IOAddress(from->stringValue()));
            }

        } catch (...) {
            isc_throw(BadValue, "'from' parameter value is neither 'start' keyword nor "
                      "a valid IPv" << (v4 ? "4" : "6") << " address");
        }

        // It must be either IPv4 address for lease4-get-page or IPv6 address for
        // lease6-get-page.
        if (v4 && (!from_address->isV4())) {
            isc_throw(BadValue, "'from' parameter value " << from_address->toText()
                      << " is not an IPv4 address");

        } else if (!v4 && from_address->isV4()) {
            isc_throw(BadValue, "'from' parameter value " << from_address->toText()
                      << " is not an IPv6 address");
        }

        // The 'limit' is a desired page size. It must always be present.
        ConstElementPtr page_limit = cmd_args_->get("limit");
        if (!page_limit) {
            isc_throw(BadValue, "'limit' parameter not specified");
        }

        // The 'limit' must be a number.
        if (page_limit->getType() != Element::integer) {
            isc_throw(BadValue, "'limit' parameter must be a number");
        }

        // Retrieve the desired page size.
        size_t page_limit_value = static_cast<size_t>(page_limit->intValue());

        ElementPtr leases_json = Element::createList();

        if (v4) {
            // Get page of IPv4 leases.
            Lease4Collection leases =
                LeaseMgrFactory::instance().getLeases4(*from_address,
                                                       LeasePageSize(page_limit_value));

            // Convert leases into JSON list.
            for (auto lease : leases) {
                ElementPtr lease_json = lease->toElement();
                leases_json->add(lease_json);
            }

        } else {
            // Get page of IPv6 leases.
            Lease6Collection leases =
                LeaseMgrFactory::instance().getLeases6(*from_address,
                                                       LeasePageSize(page_limit_value));
            // Convert leases into JSON list.
            for (auto lease : leases) {
                ElementPtr lease_json = lease->toElement();
                leases_json->add(lease_json);
            }
        }

        // Prepare textual status.
        std::ostringstream s;
        s << leases_json->size()
          << " IPv" << (v4 ? "4" : "6")
          << " lease(s) found.";
        ElementPtr args = Element::createMap();

        // Put gathered data into arguments map.
        args->set("leases", leases_json);
        args->set("count", Element::create(static_cast<int64_t>(leases_json->size())));

        // Create the response.
        ConstElementPtr response =
            createAnswer(leases_json->size() > 0 ?
                         CONTROL_RESULT_SUCCESS :
                         CONTROL_RESULT_EMPTY,
                         s.str(), args);
        setResponse(handle, response);

    } catch (const std::exception& ex) {
        setErrorResponse(handle, ex.what());
        return (CONTROL_RESULT_ERROR);
    }

    return (CONTROL_RESULT_SUCCESS);
}

int
LeaseCmdsImpl::leaseGetByHwAddressHandler(CalloutHandle& handle) {
    try {
        extractCommand(handle);

        // arguments must always be present
        if (!cmd_args_ || (cmd_args_->getType() != Element::map)) {
            isc_throw(BadValue, "Command arguments missing or a not a map.");
        }

        // the hw-address parameter is mandatory.
        ConstElementPtr hw_address = cmd_args_->get("hw-address");
        if (!hw_address) {
            isc_throw(BadValue, "'hw-address' parameter not specified");
        }

        // The 'hw-address' argument is a string.
        if (hw_address->getType() != Element::string) {
            isc_throw(BadValue, "'hw-address' parameter must be a string");
        }

        HWAddr hwaddr = HWAddr::fromText(hw_address->stringValue());

        Lease4Collection leases =
            LeaseMgrFactory::instance().getLease4(hwaddr);
        ElementPtr leases_json = Element::createList();
        for (auto lease : leases) {
            ElementPtr lease_json = lease->toElement();
            leases_json->add(lease_json);
        }

        std::ostringstream s;
        s << leases_json->size() << " IPv4 lease(s) found.";
        ElementPtr args = Element::createMap();
        args->set("leases", leases_json);
        ConstElementPtr response =
            createAnswer(leases_json->size() > 0 ?
                         CONTROL_RESULT_SUCCESS :
                         CONTROL_RESULT_EMPTY,
                         s.str(), args);
        setResponse(handle, response);

    } catch (const std::exception& ex) {
        setErrorResponse(handle, ex.what());
        return (CONTROL_RESULT_ERROR);
    }

    return (0);
}

int
LeaseCmdsImpl::leaseGetByClientIdHandler(CalloutHandle& handle) {
    try {
        extractCommand(handle);

        // arguments must always be present
        if (!cmd_args_ || (cmd_args_->getType() != Element::map)) {
            isc_throw(BadValue, "Command arguments missing or a not a map.");
        }

        // the client-id parameter is mandatory.
        ConstElementPtr client_id = cmd_args_->get("client-id");
        if (!client_id) {
            isc_throw(BadValue, "'client-id' parameter not specified");
        }

        // The 'client-id' argument is a string.
        if (client_id->getType() != Element::string) {
            isc_throw(BadValue, "'client-id' parameter must be a string");
        }

        ClientIdPtr clientid = ClientId::fromText(client_id->stringValue());

        Lease4Collection leases =
            LeaseMgrFactory::instance().getLease4(*clientid);
        ElementPtr leases_json = Element::createList();
        for (auto lease : leases) {
            ElementPtr lease_json = lease->toElement();
            leases_json->add(lease_json);
        }

        std::ostringstream s;
        s << leases_json->size() << " IPv4 lease(s) found.";
        ElementPtr args = Element::createMap();
        args->set("leases", leases_json);
        ConstElementPtr response =
            createAnswer(leases_json->size() > 0 ?
                         CONTROL_RESULT_SUCCESS :
                         CONTROL_RESULT_EMPTY,
                         s.str(), args);
        setResponse(handle, response);

    } catch (const std::exception& ex) {
        setErrorResponse(handle, ex.what());
        return (CONTROL_RESULT_ERROR);
    }

    return (0);
}

int
LeaseCmdsImpl::leaseGetByDuidHandler(CalloutHandle& handle) {
    try {
        extractCommand(handle);

        // arguments must always be present
        if (!cmd_args_ || (cmd_args_->getType() != Element::map)) {
            isc_throw(BadValue, "Command arguments missing or a not a map.");
        }

        // the duid parameter is mandatory.
        ConstElementPtr duid = cmd_args_->get("duid");
        if (!duid) {
            isc_throw(BadValue, "'duid' parameter not specified");
        }

        // The 'duid' argument is a string.
        if (duid->getType() != Element::string) {
            isc_throw(BadValue, "'duid' parameter must be a string");
        }

        DUID duid_ = DUID::fromText(duid->stringValue());

        Lease6Collection leases =
            LeaseMgrFactory::instance().getLeases6(duid_);
        ElementPtr leases_json = Element::createList();
        for (auto lease : leases) {
            ElementPtr lease_json = lease->toElement();
            leases_json->add(lease_json);
        }

        std::ostringstream s;
        s << leases_json->size() << " IPv6 lease(s) found.";
        ElementPtr args = Element::createMap();
        args->set("leases", leases_json);
        ConstElementPtr response =
            createAnswer(leases_json->size() > 0 ?
                         CONTROL_RESULT_SUCCESS :
                         CONTROL_RESULT_EMPTY,
                         s.str(), args);
        setResponse(handle, response);

    } catch (const std::exception& ex) {
        setErrorResponse(handle, ex.what());
        return (CONTROL_RESULT_ERROR);
    }

    return (0);
}

int
LeaseCmdsImpl::leaseGetByHostnameHandler(CalloutHandle& handle) {
    bool v4;
    try {
        extractCommand(handle);
        v4 = (cmd_name_ == "lease4-get-by-hostname");

        // arguments must always be present
        if (!cmd_args_ || (cmd_args_->getType() != Element::map)) {
            isc_throw(BadValue, "Command arguments missing or a not a map.");
        }

        // the hostname parameter is mandatory.
        ConstElementPtr hostname = cmd_args_->get("hostname");
        if (!hostname) {
            isc_throw(BadValue, "'hostname' parameter not specified");
        }

        // The 'hostname' argument is a string.
        if (hostname->getType() != Element::string) {
            isc_throw(BadValue, "'hostname' parameter must be a string");
        }

        std::string hostname_ = hostname->stringValue();
        /// The 'hostname' argument should not be empty.
        if (hostname_.empty()) {
            isc_throw(BadValue, "'hostname' parameter is empty");
        }
        boost::algorithm::to_lower(hostname_);

        ElementPtr leases_json = Element::createList();
        if (v4) {
            Lease4Collection leases =
                LeaseMgrFactory::instance().getLeases4(hostname_);

            for (auto lease : leases) {
                ElementPtr lease_json = lease->toElement();
                leases_json->add(lease_json);
            }
        } else {
            Lease6Collection leases =
                LeaseMgrFactory::instance().getLeases6(hostname_);

            for (auto lease : leases) {
                ElementPtr lease_json = lease->toElement();
                leases_json->add(lease_json);
            }
        }

        std::ostringstream s;
        s << leases_json->size()
          << " IPv" << (v4 ? "4" : "6")
          << " lease(s) found.";
        ElementPtr args = Element::createMap();
        args->set("leases", leases_json);
        ConstElementPtr response =
            createAnswer(leases_json->size() > 0 ?
                         CONTROL_RESULT_SUCCESS :
                         CONTROL_RESULT_EMPTY,
                         s.str(), args);
        setResponse(handle, response);

    } catch (const std::exception& ex) {
        setErrorResponse(handle, ex.what());
        return (CONTROL_RESULT_ERROR);
    }

    return (0);
}

int
LeaseCmdsImpl::lease4DelHandler(CalloutHandle& handle) {
    Parameters p;
    Lease4Ptr lease4;
    try {
        extractCommand(handle);
        p = getParameters(false, cmd_args_);

        switch (p.query_type) {
        case Parameters::TYPE_ADDR: {
            // If address was specified explicitly, let's use it as is.
            lease4 = LeaseMgrFactory::instance().getLease4(p.addr);
            if (!lease4) {
                setErrorResponse(handle, "IPv4 lease not found.", CONTROL_RESULT_EMPTY);
                return (0);
            }
            break;
        }
        case Parameters::TYPE_HWADDR: {
            if (!p.hwaddr) {
                isc_throw(InvalidParameter, "Program error: Query by hw-address "
                                            "requires hwaddr to be specified");
            }

            // Let's see if there's such a lease at all.
            lease4 = LeaseMgrFactory::instance().getLease4(*p.hwaddr, p.subnet_id);
            if (!lease4) {
                setErrorResponse(handle, "IPv4 lease not found.", CONTROL_RESULT_EMPTY);
                return (0);
            }
            break;
        }
        case Parameters::TYPE_CLIENT_ID: {
            if (!p.client_id) {
                isc_throw(InvalidParameter, "Program error: Query by client-id "
                                            "requires client-id to be specified");
            }

            // Let's see if there's such a lease at all.
            lease4 = LeaseMgrFactory::instance().getLease4(*p.client_id, p.subnet_id);
            if (!lease4) {
                setErrorResponse(handle, "IPv4 lease not found.", CONTROL_RESULT_EMPTY);
                return (0);
            }
            break;
        }
        case Parameters::TYPE_DUID: {
            isc_throw(InvalidParameter, "Delete by duid is not allowed in v4.");
            break;
        }
        default: {
            isc_throw(InvalidOperation, "Unknown query type: " << static_cast<int>(p.query_type));
            break;
        }
        }

        if (LeaseMgrFactory::instance().deleteLease(lease4)) {
            setSuccessResponse(handle, "IPv4 lease deleted.");
            LeaseCmdsImpl::updateStatsOnDelete(lease4);
        } else {
            setErrorResponse (handle, "IPv4 lease not found.", CONTROL_RESULT_EMPTY);
        }

        // Queue an NCR to remove DNS if configured and the lease has it.
        if (p.updateDDNS) {
            queueNCR(CHG_REMOVE, lease4);
        }

    } catch (const std::exception& ex) {
        setErrorResponse(handle, ex.what());
        return (1);
    }

    return (0);
}

int
LeaseCmdsImpl::lease6BulkApplyHandler(CalloutHandle& handle) {
    try {
        extractCommand(handle);

        // Arguments are mandatory.
        if (!cmd_args_ || (cmd_args_->getType() != Element::map)) {
            isc_throw(BadValue, "Command arguments missing or a not a map.");
        }

        // At least one of the 'deleted-leases' or 'leases' must be present.
        auto deleted_leases = cmd_args_->get("deleted-leases");
        auto leases = cmd_args_->get("leases");

        if (!deleted_leases && !leases) {
            isc_throw(BadValue, "neither 'deleted-leases' nor 'leases' parameter"
                      " specified");
        }

        // Make sure that 'deleted-leases' is a list, if present.
        if (deleted_leases && (deleted_leases->getType() != Element::list)) {
            isc_throw(BadValue, "the 'deleted-leases' parameter must be a list");
        }

        // Make sure that 'leases' is a list, if present.
        if (leases && (leases->getType() != Element::list)) {
            isc_throw(BadValue, "the 'leases' parameter must be a list");
        }

        // Parse deleted leases without deleting them from the database
        // yet. If any of the deleted leases or new leases appears to be
        // malformed we can easily rollback.
        std::list<std::pair<Parameters, Lease6Ptr> > parsed_deleted_list;
        if (deleted_leases) {
            auto leases_list = deleted_leases->listValue();

            // Iterate over leases to be deleted.
            for (auto lease_params : leases_list) {
                // Parsing the lease may throw and it means that the lease
                // information is malformed.
                Parameters p = getParameters(true, lease_params);
                auto lease = getIPv6LeaseForDelete(p);
                parsed_deleted_list.push_back(std::make_pair(p, lease));
            }
        }

        // Parse new/updated leases without affecting the database to detect
        // any errors that should cause an error response.
        std::list<Lease6Ptr> parsed_leases_list;
        if (leases) {
            ConstSrvConfigPtr config = CfgMgr::instance().getCurrentCfg();

            // Iterate over all leases.
            auto leases_list = leases->listValue();
            for (auto lease_params : leases_list) {

                Lease6Parser parser;
                bool force_update;

                // If parsing the lease fails we throw, as it indicates that the
                // command is malformed.
                Lease6Ptr lease6 = parser.parse(config, lease_params, force_update);
                parsed_leases_list.push_back(lease6);
            }
        }

        // Count successful deletions and updates.
        size_t success_count = 0;

        ElementPtr failed_deleted_list;
        if (!parsed_deleted_list.empty()) {

            // Iterate over leases to be deleted.
            for (auto lease_params_pair : parsed_deleted_list) {

                // This part is outside of the try-catch because an exception
                // indicates that the command is malformed.
                Parameters p = lease_params_pair.first;
                auto lease = lease_params_pair.second;

                try {
                    if (lease) {
                        // This may throw if the lease couldn't be deleted for
                        // any reason, but we still want to proceed with other
                        // leases.
                        if (LeaseMgrFactory::instance().deleteLease(lease)) {
                            ++success_count;
                            LeaseCmdsImpl::updateStatsOnDelete(lease);

                        } else {
                            // Lazy creation of the list of leases which failed to delete.
                            if (!failed_deleted_list) {
                                failed_deleted_list = Element::createList();
                            }

                            // If the lease doesn't exist we also want to put it
                            // on the list of leases which failed to delete. That
                            // corresponds to the lease6-del command which returns
                            // an error when the lease doesn't exist.
                            failed_deleted_list->add(createFailedLeaseMap(p.lease_type,
                                                                          p.addr, p.duid,
                                                                          CONTROL_RESULT_EMPTY,
                                                                          "lease not found"));
                        }
                    }

                } catch (const std::exception& ex) {
                    // Lazy creation of the list of leases which failed to delete.
                    if (!failed_deleted_list) {
                         failed_deleted_list = Element::createList();
                    }
                    failed_deleted_list->add(createFailedLeaseMap(p.lease_type,
                                                                  p.addr, p.duid,
                                                                  CONTROL_RESULT_ERROR,
                                                                  ex.what()));
                }
            }
        }

        // Process leases to be added or/and updated.
        ElementPtr failed_leases_list;
        if (!parsed_leases_list.empty()) {
            ConstSrvConfigPtr config = CfgMgr::instance().getCurrentCfg();

            // Iterate over all leases.
            for (auto lease : parsed_leases_list) {

                try {
                    if (!MultiThreadingMgr::instance().getMode()) {
                        // Not multi-threading.
                        addOrUpdate6(lease, true);
                    } else {
                        // Multi-threading, try to lock first to avoid a race.
                        ResourceHandler resource_handler;
                        if (resource_handler.tryLock(lease->type_, lease->addr_)) {
                            addOrUpdate6(lease, true);
                        } else {
                            isc_throw(ResourceBusy,
                                      "ResourceBusy: IP address:" << lease->addr_
                                      << " could not be updated.");
                        }
                    }

                    ++success_count;
                } catch (const std::exception& ex) {
                    // Lazy creation of the list of leases which failed to add/update.
                    if (!failed_leases_list) {
                         failed_leases_list = Element::createList();
                    }
                    failed_leases_list->add(createFailedLeaseMap(lease->type_,
                                                                 lease->addr_,
                                                                 lease->duid_,
                                                                 CONTROL_RESULT_ERROR,
                                                                 ex.what()));
                }
            }
        }

        // Start preparing the response.
        ElementPtr args;

        if (failed_deleted_list || failed_leases_list) {
            // If there are any failed leases, let's include them in the response.
            args = Element::createMap();

            // failed-deleted-leases
            if (failed_deleted_list) {
                args->set("failed-deleted-leases", failed_deleted_list);
            }

            // failed-leases
            if (failed_leases_list) {
                args->set("failed-leases", failed_leases_list);
            }
        }

        // Send the success response and include failed leases.
        std::ostringstream resp_text;
        resp_text << "Bulk apply of " << success_count << " IPv6 leases completed.";
        auto answer = createAnswer(success_count > 0 ? CONTROL_RESULT_SUCCESS :
                                   CONTROL_RESULT_EMPTY, resp_text.str(), args);
        setResponse(handle, answer);

    } catch (const std::exception& ex) {
        // Unable to parse the command and similar issues.
        setErrorResponse(handle, ex.what());
        return (CONTROL_RESULT_ERROR);
    }

    return (CONTROL_RESULT_SUCCESS);
}

int
LeaseCmdsImpl::lease6DelHandler(CalloutHandle& handle) {
    Parameters p;
    Lease6Ptr lease6;
    IOAddress addr(IOAddress::IPV6_ZERO_ADDRESS());
    try {
        extractCommand(handle);
        p = getParameters(true, cmd_args_);

        switch (p.query_type) {
        case Parameters::TYPE_ADDR: {
            // If address was specified explicitly, let's use it as is.

            // Let's see if there's such a lease at all.
            lease6 = LeaseMgrFactory::instance().getLease6(p.lease_type, p.addr);
            if (!lease6) {
                setErrorResponse(handle, "IPv6 lease not found.", CONTROL_RESULT_EMPTY);
                return (0);
            }
            break;
        }
        case Parameters::TYPE_HWADDR: {
            isc_throw(InvalidParameter, "Delete by hw-address is not allowed in v6.");
            break;
        }
        case Parameters::TYPE_DUID: {
            if (!p.duid) {
                isc_throw(InvalidParameter, "Program error: Query by duid "
                                            "requires duid to be specified");
            }

            // Let's see if there's such a lease at all.
            lease6 = LeaseMgrFactory::instance().getLease6(p.lease_type, *p.duid,
                                                           p.iaid, p.subnet_id);
            if (!lease6) {
                setErrorResponse(handle, "IPv6 lease not found.", CONTROL_RESULT_EMPTY);
                return (0);
            }
            break;
        }
        default: {
            isc_throw(InvalidOperation, "Unknown query type: " << static_cast<int>(p.query_type));
            break;
        }
        }

        if (LeaseMgrFactory::instance().deleteLease(lease6)) {
            setSuccessResponse(handle, "IPv6 lease deleted.");
            LeaseCmdsImpl::updateStatsOnDelete(lease6);
        } else {
            setErrorResponse (handle, "IPv6 lease not found.", CONTROL_RESULT_EMPTY);
        }

        // Queue an NCR to remove DNS if configured and the lease has it.
        if (p.updateDDNS) {
            queueNCR(CHG_REMOVE, lease6);
        }

    } catch (const std::exception& ex) {
        setErrorResponse(handle, ex.what());
        return (1);
    }

    return (0);
}

int
LeaseCmdsImpl::lease4UpdateHandler(CalloutHandle& handle) {
    try {
        extractCommand(handle);

        // We need the lease to be specified.
        if (!cmd_args_) {
            isc_throw(isc::BadValue, "no parameters specified for lease4-update command");
        }

        // Get the parameters specified by the user first.
        ConstSrvConfigPtr config = CfgMgr::instance().getCurrentCfg();
        Lease4Ptr lease4;
        Lease4Parser parser;
        bool force_create = false;

        // The parser does sanity checks (if the address is in scope, if
        // subnet-id is valid, etc)
        lease4 = parser.parse(config, cmd_args_, force_create);
        bool added = false;
        if (!MultiThreadingMgr::instance().getMode()) {
            // Not multi-threading.
            added = addOrUpdate4(lease4, force_create);
        } else {
            // Multi-threading, try to lock first to avoid a race.
            ResourceHandler4 resource_handler;
            if (resource_handler.tryLock4(lease4->addr_)) {
                added = addOrUpdate4(lease4, force_create);
            } else {
                isc_throw(ResourceBusy,
                          "ResourceBusy: IP address:" << lease4->addr_
                          << " could not be updated.");
            }
        }

        if (added) {
            setSuccessResponse(handle, "IPv4 lease added.");
        } else {
            setSuccessResponse(handle, "IPv4 lease updated.");
        }
    } catch (const std::exception& ex) {
        setErrorResponse(handle, ex.what());
        return (1);
    }

    return (0);
}

int
LeaseCmdsImpl::lease6UpdateHandler(CalloutHandle& handle) {
    try {
        extractCommand(handle);

        // We need the lease to be specified.
        if (!cmd_args_) {
            isc_throw(isc::BadValue, "no parameters specified for lease6-update command");
        }

        // Get the parameters specified by the user first.
        ConstSrvConfigPtr config = CfgMgr::instance().getCurrentCfg();
        Lease6Ptr lease6;
        Lease6Parser parser;
        bool force_create = false;

        // The parser does sanity checks (if the address is in scope, if
        // subnet-id is valid, etc)
        lease6 = parser.parse(config, cmd_args_, force_create);
        bool added = false;
        if (!MultiThreadingMgr::instance().getMode()) {
            // Not multi-threading.
            added = addOrUpdate6(lease6, force_create);
        } else {
            // Multi-threading, try to lock first to avoid a race.
            ResourceHandler resource_handler;
            if (resource_handler.tryLock(lease6->type_, lease6->addr_)) {
                added = addOrUpdate6(lease6, force_create);
            } else {
                isc_throw(ResourceBusy,
                          "ResourceBusy: IP address:" << lease6->addr_
                          << " could not be updated.");
            }
        }

        if (added) {
            setSuccessResponse(handle, "IPv6 lease added.");
        } else {
            setSuccessResponse(handle, "IPv6 lease updated.");
        }
    } catch (const std::exception& ex) {
        setErrorResponse(handle, ex.what());
        return (1);
    }

    return (0);
}

int
LeaseCmdsImpl::lease4WipeHandler(CalloutHandle& handle) {
    try {
        extractCommand(handle);

        SimpleParser parser;
        SubnetID id = 0;

        size_t num = 0; // number of leases deleted
        stringstream ids; // a text with subnet-ids being wiped

        // The subnet-id parameter is now optional.
        if (cmd_args_ && cmd_args_->contains("subnet-id")) {
            id = parser.getUint32(cmd_args_, "subnet-id");
        }

        if (id) {
            // Wipe a single subnet.
            num = LeaseMgrFactory::instance().wipeLeases4(id);
            ids << " " << id;

            auto observation = StatsMgr::instance().getObservation(
                StatsMgr::generateName("subnet", id, "declined-addresses"));

            int64_t previous_declined = 0;

            if (observation) {
                previous_declined = observation->getInteger().first;
            }

            StatsMgr::instance().setValue(
                StatsMgr::generateName("subnet", id, "assigned-addresses"),
                int64_t(0));

            StatsMgr::instance().setValue(
                StatsMgr::generateName("subnet", id, "declined-addresses"),
                int64_t(0));

            StatsMgr::instance().addValue("declined-addresses", -previous_declined);
        } else {
            // Wipe them all!
            ConstSrvConfigPtr config = CfgMgr::instance().getCurrentCfg();
            ConstCfgSubnets4Ptr subnets = config->getCfgSubnets4();
            const Subnet4Collection * subs = subnets->getAll();

            // Go over all subnets and wipe leases in each of them.
            for (auto sub : *subs) {
                num += LeaseMgrFactory::instance().wipeLeases4(sub->getID());
                ids << " " << sub->getID();
                StatsMgr::instance().setValue(
                    StatsMgr::generateName("subnet", sub->getID(), "assigned-addresses"),
                    int64_t(0));

                StatsMgr::instance().setValue(
                    StatsMgr::generateName("subnet", sub->getID(), "declined-addresses"),
                    int64_t(0));
            }

            StatsMgr::instance().setValue("declined-addresses", int64_t(0));
        }

        stringstream tmp;
        tmp << "Deleted " << num << " IPv4 lease(s) from subnet(s)" << ids.str();
        ConstElementPtr response = createAnswer(num ? CONTROL_RESULT_SUCCESS
                                                    : CONTROL_RESULT_EMPTY, tmp.str());
        setResponse(handle, response);
    } catch (const std::exception& ex) {
        setErrorResponse(handle, ex.what());
        return (1);
    }

    return (0);
}

int
LeaseCmdsImpl::lease6WipeHandler(CalloutHandle& handle) {
    try {
        extractCommand(handle);

        SimpleParser parser;
        SubnetID id = 0;

        size_t num = 0; // number of leases deleted
        stringstream ids; // a text with subnet-ids being wiped

        /// @todo: consider extending the code with wipe-leases:
        /// - of specific type (v6)
        /// - from specific shared network
        /// - from specific pool
        /// see https://oldkea.isc.org/ticket/5543#comment:6 for background.

        // The subnet-id parameter is now optional.
        if (cmd_args_ && cmd_args_->contains("subnet-id")) {
            id = parser.getUint32(cmd_args_, "subnet-id");
        }

        if (id) {
            // Wipe a single subnet.
            num = LeaseMgrFactory::instance().wipeLeases6(id);
            ids << " " << id;

            auto observation = StatsMgr::instance().getObservation(
                StatsMgr::generateName("subnet", id, "declined-addresses"));

            int64_t previous_declined = 0;

            if (observation) {
                previous_declined = observation->getInteger().first;
            }

            StatsMgr::instance().setValue(
                StatsMgr::generateName("subnet", id, "assigned-nas" ),
                int64_t(0));

            StatsMgr::instance().setValue(
                StatsMgr::generateName("subnet", id, "assigned-pds"),
                int64_t(0));

            StatsMgr::instance().setValue(
                StatsMgr::generateName("subnet", id, "declined-addresses"),
                int64_t(0));

            StatsMgr::instance().addValue("declined-addresses", -previous_declined);
       } else {
            // Wipe them all!
            ConstSrvConfigPtr config = CfgMgr::instance().getCurrentCfg();
            ConstCfgSubnets6Ptr subnets = config->getCfgSubnets6();
            const Subnet6Collection * subs = subnets->getAll();

            // Go over all subnets and wipe leases in each of them.
            for (auto sub : *subs) {
                num += LeaseMgrFactory::instance().wipeLeases6(sub->getID());
                ids << " " << sub->getID();
                StatsMgr::instance().setValue(
                    StatsMgr::generateName("subnet", sub->getID(), "assigned-nas" ),
                    int64_t(0));

                StatsMgr::instance().setValue(
                    StatsMgr::generateName("subnet", sub->getID(), "assigned-pds"),
                    int64_t(0));

                StatsMgr::instance().setValue(
                    StatsMgr::generateName("subnet", sub->getID(), "declined-addresses"),
                    int64_t(0));
            }

            StatsMgr::instance().setValue("declined-addresses", int64_t(0));
        }

        stringstream tmp;
        tmp << "Deleted " << num << " IPv6 lease(s) from subnet(s)" << ids.str();
        ConstElementPtr response = createAnswer(num ? CONTROL_RESULT_SUCCESS
                                                    : CONTROL_RESULT_EMPTY, tmp.str());
        setResponse(handle, response);
    } catch (const std::exception& ex) {
        setErrorResponse(handle, ex.what());
        return (1);
    }

    return (0);
}

Lease6Ptr
LeaseCmdsImpl::getIPv6LeaseForDelete(const Parameters& parameters) const {
    Lease6Ptr lease6;

    switch (parameters.query_type) {
    case Parameters::TYPE_ADDR: {
        // If address was specified explicitly, let's use it as is.

        // Let's see if there's such a lease at all.
        lease6 = LeaseMgrFactory::instance().getLease6(parameters.lease_type,
                                                       parameters.addr);
        if (!lease6) {
            lease6.reset(new Lease6());
            lease6->addr_ = parameters.addr;
        }
        break;
    }
    case Parameters::TYPE_HWADDR: {
        isc_throw(InvalidParameter, "Delete by hw-address is not allowed in v6.");
        break;
    }
    case Parameters::TYPE_DUID: {
        if (!parameters.duid) {
            isc_throw(InvalidParameter, "Program error: Query by duid "
                      "requires duid to be specified");
        }

        // Let's see if there's such a lease at all.
        lease6 = LeaseMgrFactory::instance().getLease6(parameters.lease_type,
                                                       *parameters.duid,
                                                       parameters.iaid,
                                                       parameters.subnet_id);
        break;
    }
    default:
        isc_throw(InvalidOperation, "Unknown query type: "
                  << static_cast<int>(parameters.query_type));
    }

    return (lease6);
}

IOAddress
LeaseCmdsImpl::getAddressParam(ConstElementPtr params, const std::string name,
                               short family) const {
    ConstElementPtr param = params->get(name);
    if (!param) {
        isc_throw(BadValue, "'" << name << "' parameter is missing.");
    }

    if (param->getType() != Element::string) {
        isc_throw(BadValue, "'" << name << "' is not a string.");
    }

    IOAddress addr(0);
    try {
        addr = IOAddress(param->stringValue());
    } catch (const std::exception& ex) {
        isc_throw(BadValue, "'" << param->stringValue()
                                << "' is not a valid IP address.");
    }

    if (addr.getFamily() != family) {
        isc_throw(BadValue, "Invalid "
                  << (family == AF_INET6 ? "IPv6" : "IPv4")
                  << " address specified: " << param->stringValue());
    }

    return (addr);
}

int
LeaseCmdsImpl::lease4ResendDdnsHandler(CalloutHandle& handle) {
    std::stringstream ss;
    int resp_code = CONTROL_RESULT_ERROR;

    try {
        extractCommand(handle);

        // Get the target lease address. Invalid value will throw.
        IOAddress addr = getAddressParam(cmd_args_, "ip-address", AF_INET);

        if (!CfgMgr::instance().getD2ClientMgr().ddnsEnabled()) {
            ss << "DDNS updating is not enabled";
        } else {
            // Find the lease.
            Lease4Ptr lease = LeaseMgrFactory::instance().getLease4(addr);
            if (!lease) {
                ss << "No lease found for: " << addr.toText();
                resp_code = CONTROL_RESULT_EMPTY;
            } else if (lease->hostname_.empty()) {
                ss << "Lease for: " << addr.toText()
                   << ", has no hostname, nothing to update";
            } else if (!lease->fqdn_fwd_ && !lease->fqdn_rev_) {
                ss << "Neither forward nor reverse updates enabled for lease for: "
                   << addr.toText();
            } else {
                // We have a lease with a hostname and updates in at least
                // one direction enabled.  Queue an NCR for it.
                queueNCR(CHG_ADD, lease);
                ss << "NCR generated for: " << addr.toText()
                   << ", hostname: " << lease->hostname_;
                setSuccessResponse(handle, ss.str());
                LOG_INFO(lease_cmds_logger, LEASE_CMDS_RESEND_DDNS4).arg(ss.str());
                return (0);
            }
        }
    } catch (const std::exception& ex) {
        ss << ex.what();
    }

    LOG_ERROR(lease_cmds_logger, LEASE_CMDS_RESEND_DDNS4_FAILED).arg(ss.str());
    setErrorResponse(handle, ss.str(), resp_code);
    return (resp_code == CONTROL_RESULT_EMPTY ? 0 : 1);
}

int
LeaseCmdsImpl::lease6ResendDdnsHandler(CalloutHandle& handle) {
    std::stringstream ss;
    int resp_code = CONTROL_RESULT_ERROR;

    try {
        extractCommand(handle);

        // Get the target lease address. Invalid value will throw.
        IOAddress addr = getAddressParam(cmd_args_, "ip-address", AF_INET6);

        if (!CfgMgr::instance().getD2ClientMgr().ddnsEnabled()) {
            ss << "DDNS updating is not enabled";
        } else {
            // Find the lease.
            Lease6Ptr lease = LeaseMgrFactory::instance().getLease6(Lease::TYPE_NA, addr);
            if (!lease) {
                ss << "No lease found for: " << addr.toText();
                resp_code = CONTROL_RESULT_EMPTY;
            } else if (lease->hostname_.empty()) {
                ss << "Lease for: " << addr.toText()
                   << ", has no hostname, nothing to update";
            } else if (!lease->fqdn_fwd_ && !lease->fqdn_rev_) {
                ss << "Neither forward nor reverse updates enabled for lease for: "
                   << addr.toText();
            } else {
                // We have a lease with a hostname and updates in at least
                // one direction enabled.  Queue an NCR for it.
                queueNCR(CHG_ADD, lease);
                ss << "NCR generated for: " << addr.toText()
                   << ", hostname: " << lease->hostname_;
                setSuccessResponse(handle, ss.str());
                LOG_INFO(lease_cmds_logger, LEASE_CMDS_RESEND_DDNS6).arg(ss.str());
                return (0);
            }
        }
    } catch (const std::exception& ex) {
        ss << ex.what();
    }

    LOG_ERROR(lease_cmds_logger, LEASE_CMDS_RESEND_DDNS6_FAILED).arg(ss.str());
    setErrorResponse(handle, ss.str(), resp_code);
    return (resp_code == CONTROL_RESULT_EMPTY ? 0 : 1);
}

ElementPtr
LeaseCmdsImpl::createFailedLeaseMap(const Lease::Type& lease_type,
                                    const IOAddress& lease_address,
                                    const DuidPtr& duid,
                                    const int control_result,
                                    const std::string& error_message) const {
    auto failed_lease_map = Element::createMap();
    failed_lease_map->set("type", Element::create(Lease::typeToText(lease_type)));

    if (!lease_address.isV6Zero()) {
        failed_lease_map->set("ip-address", Element::create(lease_address.toText()));

    } else if (duid) {
        failed_lease_map->set("duid", Element::create(duid->toText()));
    }

    // Associate the result with the lease.
    failed_lease_map->set("result", Element::create(control_result));
    failed_lease_map->set("error-message", Element::create(error_message));

    return (failed_lease_map);
}

int
LeaseCmds::leaseAddHandler(CalloutHandle& handle) {
    return (impl_->leaseAddHandler(handle));
}

int
LeaseCmds::lease6BulkApplyHandler(CalloutHandle& handle) {
    return (impl_->lease6BulkApplyHandler(handle));
}

int
LeaseCmds::leaseGetHandler(CalloutHandle& handle) {
    return (impl_->leaseGetHandler(handle));
}

int
LeaseCmds::leaseGetAllHandler(hooks::CalloutHandle& handle) {
    return (impl_->leaseGetAllHandler(handle));
}

int
LeaseCmds::leaseGetPageHandler(hooks::CalloutHandle& handle) {
    return (impl_->leaseGetPageHandler(handle));
}

int
LeaseCmds::leaseGetByHwAddressHandler(hooks::CalloutHandle& handle) {
    return (impl_->leaseGetByHwAddressHandler(handle));
}

int
LeaseCmds::leaseGetByClientIdHandler(hooks::CalloutHandle& handle) {
    return (impl_->leaseGetByClientIdHandler(handle));
}

int
LeaseCmds::leaseGetByDuidHandler(hooks::CalloutHandle& handle) {
    return (impl_->leaseGetByDuidHandler(handle));
}

int
LeaseCmds::leaseGetByHostnameHandler(hooks::CalloutHandle& handle) {
    return (impl_->leaseGetByHostnameHandler(handle));
}

int
LeaseCmds::lease4DelHandler(CalloutHandle& handle) {
    return (impl_->lease4DelHandler(handle));
}

int
LeaseCmds::lease6DelHandler(CalloutHandle& handle) {
    return (impl_->lease6DelHandler(handle));
}

int
LeaseCmds::lease4UpdateHandler(CalloutHandle& handle) {
    return (impl_->lease4UpdateHandler(handle));
}

int
LeaseCmds::lease6UpdateHandler(CalloutHandle& handle) {
    return (impl_->lease6UpdateHandler(handle));
}

int
LeaseCmds::lease4WipeHandler(CalloutHandle& handle) {
    MultiThreadingCriticalSection cs;
    return (impl_->lease4WipeHandler(handle));
}

int
LeaseCmds::lease6WipeHandler(CalloutHandle& handle) {
    MultiThreadingCriticalSection cs;
    return (impl_->lease6WipeHandler(handle));
}

int
LeaseCmds::lease4ResendDdnsHandler(CalloutHandle& handle) {
    return (impl_->lease4ResendDdnsHandler(handle));
}

int
LeaseCmds::lease6ResendDdnsHandler(CalloutHandle& handle) {
    return (impl_->lease6ResendDdnsHandler(handle));
}

LeaseCmds::LeaseCmds()
    :impl_(new LeaseCmdsImpl()) {
}

} // end of namespace lease_cmds
} // end of namespace isc