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
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
// Copyright (C) 2012-2024 Internet Systems Consortium, Inc. ("ISC")
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include <config.h>

#include <asiolink/addr_utilities.h>
#include <dhcpsrv/cfg_consistency.h>
#include <dhcpsrv/cfgmgr.h>
#include <dhcpsrv/dhcpsrv_exceptions.h>
#include <dhcpsrv/dhcpsrv_log.h>
#include <dhcpsrv/lease_file_loader.h>
#include <dhcpsrv/memfile_lease_mgr.h>
#include <dhcpsrv/timer_mgr.h>
#include <exceptions/exceptions.h>
#include <stats/stats_mgr.h>
#include <util/multi_threading_mgr.h>
#include <util/pid_file.h>

#include <boost/foreach.hpp><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <cstdio><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <cstring><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <errno.h><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <iostream><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <limits><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <sstream><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.

namespace {

/// @brief A name of the environmental variable specifying the kea-lfc
/// program location.
///
/// This variable can be set by tests to point to the location of the
/// kea-lfc program within a build directory. If this variable is not
/// set, the backend will use the location of the kea-lfc in the
/// Kea installation directory.
const char* KEA_LFC_EXECUTABLE_ENV_NAME = "KEA_LFC_EXECUTABLE";

}  // namespace

using namespace isc::asiolink;
using namespace isc::data;
using namespace isc::db;
using namespace isc::util;
using namespace isc::stats;

namespace isc {
namespace dhcp {

/// @brief Represents a configuration for Lease File Cleanup.
///
/// This class is solely used by the @c Memfile_LeaseMgr as a configuration
/// information storage for %Lease File Cleanup. Internally, it creates
/// the interval timer and assigns a callback function (pointer to which is
/// passed in the constructor), which will be called at the specified
/// intervals to perform the cleanup. It is also responsible for creating
/// and maintaining the object which is used to spawn the new process which
/// executes the @c kea-lfc program.
///
/// This functionality is enclosed in a separate class so as the implementation
/// details are not exposed in the @c Memfile_LeaseMgr header file and
/// to maintain a single place with the LFC configuration, instead of multiple
/// members and functions scattered in the @c Memfile_LeaseMgr class.
class LFCSetup {
public:

    /// @brief Constructor.
    ///
    /// Assigns a pointer to the function triggered to perform the cleanup.
    /// This pointer should point to the appropriate method of the
    /// @c Memfile_LeaseMgr class.
    ///
    /// @param callback A pointer to the callback function.
    LFCSetup(asiolink::IntervalTimer::Callback callback);

    /// @brief Destructor.
    ///
    /// Unregisters LFC timer.
    ~LFCSetup();

    /// @brief Sets the new configuration for the %Lease File Cleanup.
    ///
    /// @param lfc_interval An interval in seconds at which the cleanup should
    /// be performed.
    /// @param lease_file4 A pointer to the DHCPv4 lease file to be cleaned up
    /// or null. If this is null, the @c lease_file6 must be non-null.
    /// @param lease_file6 A pointer to the DHCPv6 lease file to be cleaned up
    /// or null. If this is null, the @c lease_file4 must be non-null.
    /// @param run_once_now A flag that causes LFC to be invoked immediately,
    /// regardless of the value of lfc_interval.  This is primarily used to
    /// cause lease file schema upgrades upon startup.
    void setup(const uint32_t lfc_interval,
               const boost::shared_ptr<CSVLeaseFile4>& lease_file4,
               const boost::shared_ptr<CSVLeaseFile6>& lease_file6,
               bool run_once_now = false);

    /// @brief Spawns a new process.
    void execute();

    /// @brief Checks if the lease file cleanup is in progress.
    ///
    /// @return true if the lease file cleanup is being executed.
    bool isRunning() const;

    /// @brief Returns exit code of the last completed cleanup.
    int getExitStatus() const;

private:

    /// @brief A pointer to the @c ProcessSpawn object used to execute
    /// the LFC.
    boost::scoped_ptr<ProcessSpawn> process_;

    /// @brief A pointer to the callback function executed by the timer.
    asiolink::IntervalTimer::Callback callback_;

    /// @brief A PID of the last executed LFC process.
    pid_t pid_;

    /// @brief Pointer to the timer manager.
    ///
    /// We have to hold this pointer here to make sure that the timer
    /// manager is not destroyed before the lease manager.
    TimerMgrPtr timer_mgr_;
};

LFCSetup::LFCSetup(asiolink::IntervalTimer::Callback callback)
    : process_(), callback_(callback), pid_(0),
      timer_mgr_(TimerMgr::instance()) {
}

LFCSetup::~LFCSetup() {
    try {
        // Remove the timer. This will throw an exception if the timer does not
        // exist.  There are several possible reasons for this:
        // a) It hasn't been registered (although if the LFC Setup instance
        //    exists it means that the timer must have been registered or that
        //    such registration has been attempted).
        // b) The registration may fail if the duplicate timer exists or if the
        //    TimerMgr's worker thread is running but if this happens it is a
        //    programming error.
        // c) The program is shutting down and the timer has been removed by
        //    another component.
        timer_mgr_->unregisterTimer("memfile-lfc");

    } catch (const std::exception& ex) {
        // We don't want exceptions being thrown from the destructor so we just
        // log a message here.  The message is logged at debug severity as
        // we don't want an error message output during shutdown.
        LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE,
                  DHCPSRV_MEMFILE_LFC_UNREGISTER_TIMER_FAILED).arg(ex.what());
    }
}

void
LFCSetup::setup(const uint32_t lfc_interval,
                const boost::shared_ptr<CSVLeaseFile4>& lease_file4,
                const boost::shared_ptr<CSVLeaseFile6>& lease_file6,
                bool run_once_now) {

    // If to nothing to do, punt
    if (lfc_interval == 0 && !run_once_now) {
        return;
    }

    // Start preparing the command line for kea-lfc.
    std::string executable;
    char* c_executable = getenv(KEA_LFC_EXECUTABLE_ENV_NAME);
    if (!c_executable) {
        executable = KEA_LFC_EXECUTABLE;
    } else {
        executable = c_executable;
    }

    // Gather the base file name.
    std::string lease_file = lease_file4 ? lease_file4->getFilename() :
                                           lease_file6->getFilename();

    // Create the other names by appending suffixes to the base name.
    ProcessArgs args;
    // Universe: v4 or v6.
    args.push_back(lease_file4 ? "-4" : "-6");

    // Previous file.
    args.push_back("-x");
    args.push_back(Memfile_LeaseMgr::appendSuffix(lease_file,
                                                  Memfile_LeaseMgr::FILE_PREVIOUS));
    // Input file.
    args.push_back("-i");
    args.push_back(Memfile_LeaseMgr::appendSuffix(lease_file,
                                                  Memfile_LeaseMgr::FILE_INPUT));
    // Output file.
    args.push_back("-o");
    args.push_back(Memfile_LeaseMgr::appendSuffix(lease_file,
                                                  Memfile_LeaseMgr::FILE_OUTPUT));
    // Finish file.
    args.push_back("-f");
    args.push_back(Memfile_LeaseMgr::appendSuffix(lease_file,
                                                  Memfile_LeaseMgr::FILE_FINISH));
    // PID file.
    args.push_back("-p");
    args.push_back(Memfile_LeaseMgr::appendSuffix(lease_file,
                                                  Memfile_LeaseMgr::FILE_PID));

    // The configuration file is currently unused.
    args.push_back("-c");
    args.push_back("ignored-path");

    // Create the process (do not start it yet).
    process_.reset(new ProcessSpawn(ProcessSpawn::ASYNC, executable, args,
                                    ProcessEnvVars(), true));

    // If we've been told to run it once now, invoke the callback directly.
    if (run_once_now) {
        callback_();
    }

    // If it's supposed to run periodically, setup that now.
    if (lfc_interval > 0) {
        // Set the timer to call callback function periodically.
        LOG_INFO(dhcpsrv_logger, DHCPSRV_MEMFILE_LFC_SETUP).arg(lfc_interval);

        // Multiple the lfc_interval value by 1000 as this value specifies
        // a timeout in seconds, whereas the setup() method expects the
        // timeout in milliseconds.
        timer_mgr_->registerTimer("memfile-lfc", callback_, lfc_interval * 1000,
                                  asiolink::IntervalTimer::REPEATING);
        timer_mgr_->setup("memfile-lfc");
    }
}

void
LFCSetup::execute() {
    try {
        LOG_INFO(dhcpsrv_logger, DHCPSRV_MEMFILE_LFC_EXECUTE)
            .arg(process_->getCommandLine());
        pid_ = process_->spawn();

    } catch (const ProcessSpawnError&) {
        LOG_ERROR(dhcpsrv_logger, DHCPSRV_MEMFILE_LFC_SPAWN_FAIL);
    }
}

bool
LFCSetup::isRunning() const {
    return (process_ && process_->isRunning(pid_));
}

int
LFCSetup::getExitStatus() const {
    if (!process_) {
        isc_throw(InvalidOperation, "unable to obtain LFC process exit code: "
                  " the process is null");
    }
    return (process_->getExitStatus(pid_));
}


/// @brief Base Memfile derivation of the statistical lease data query
///
/// This class provides the functionality such as results storage and row
/// fetching common to fulfilling the statistical lease data query.
///
class MemfileLeaseStatsQuery : public LeaseStatsQuery {
public:
    /// @brief Constructor for all subnets query
    ///
    /// @param select_mode The selection criteria which is either ALL_SUBNETS or
    /// ALL_SUBNET_POOLS
    MemfileLeaseStatsQuery(const SelectMode& select_mode = ALL_SUBNETS)
        : LeaseStatsQuery(select_mode), rows_(0), next_pos_(rows_.end()) {
    };

    /// @brief Constructor for single subnet query
    ///
    /// @param subnet_id ID of the desired subnet
    MemfileLeaseStatsQuery(const SubnetID& subnet_id)
        : LeaseStatsQuery(subnet_id), rows_(0), next_pos_(rows_.end()) {
    };

    /// @brief Constructor for subnet range query
    ///
    /// @param first_subnet_id ID of the first subnet in the desired range
    /// @param last_subnet_id ID of the last subnet in the desired range
    MemfileLeaseStatsQuery(const SubnetID& first_subnet_id, const SubnetID& last_subnet_id)
        : LeaseStatsQuery(first_subnet_id, last_subnet_id), rows_(0), next_pos_(rows_.end()) {
    };

    /// @brief Destructor
    virtual ~MemfileLeaseStatsQuery() {};<--- Destructor in derived class<--- Virtual destructor in base class<--- Virtual destructor in base class

    /// @brief Fetches the next row in the result set
    ///
    /// Once the internal result set has been populated by invoking the
    /// the start() method, this method is used to iterate over the
    /// result set rows.  Once the last row has been fetched, subsequent
    /// calls will return false.
    /// @param row Storage for the fetched row
    ///
    /// @return True if the fetch succeeded, false if there are no more
    /// rows to fetch.
    virtual bool getNextRow(LeaseStatsRow& row) {<--- Function in derived class
        if (next_pos_ == rows_.end()) {
            return (false);
        }

        row = *next_pos_;
        ++next_pos_;
        return (true);
    }

    /// @brief Returns the number of rows in the result set
    int getRowCount() const {
        return (rows_.size());
    }

protected:
    /// @brief A vector containing the "result set"
    std::vector<LeaseStatsRow> rows_;

    /// @brief An iterator for accessing the next row within the result set
    std::vector<LeaseStatsRow>::iterator next_pos_;
};

/// @brief Memfile derivation of the IPv4 statistical lease data query
///
/// This class is used to recalculate IPv4 lease statistics for Memfile
/// lease storage.  It does so by iterating over the given storage,
/// accumulating counts of leases in each of the monitored lease states
/// for each subnet and storing these counts in an internal collection.
/// The populated result set will contain one entry per monitored state
/// per subnet.
///
class MemfileLeaseStatsQuery4 : public MemfileLeaseStatsQuery {
public:
    /// @brief Constructor for an all subnets query
    ///
    /// @param storage4 A pointer to the v4 lease storage to be counted
    /// @param select_mode The selection criteria which is either ALL_SUBNETS or
    /// ALL_SUBNET_POOLS
    MemfileLeaseStatsQuery4(Lease4Storage& storage4,
                            const SelectMode& select_mode = ALL_SUBNETS)
        : MemfileLeaseStatsQuery(select_mode), storage4_(storage4) {
    };

    /// @brief Constructor for a single subnet query
    ///
    /// @param storage4 A pointer to the v4 lease storage to be counted
    /// @param subnet_id ID of the desired subnet
    MemfileLeaseStatsQuery4(Lease4Storage& storage4, const SubnetID& subnet_id)
        : MemfileLeaseStatsQuery(subnet_id), storage4_(storage4) {
    };

    /// @brief Constructor for a subnet range query
    ///
    /// @param storage4 A pointer to the v4 lease storage to be counted
    /// @param first_subnet_id ID of the first subnet in the desired range
    /// @param last_subnet_id ID of the last subnet in the desired range
    MemfileLeaseStatsQuery4(Lease4Storage& storage4, const SubnetID& first_subnet_id,
                            const SubnetID& last_subnet_id)
        : MemfileLeaseStatsQuery(first_subnet_id, last_subnet_id), storage4_(storage4) {
    };

    /// @brief Destructor
    virtual ~MemfileLeaseStatsQuery4() {};<--- Destructor in derived class

    /// @brief Creates the IPv4 lease statistical data result set
    ///
    /// The result set is populated by iterating over the IPv4 leases in
    /// storage, in ascending order by subnet id or by subnet id and pool id,
    /// accumulating the lease state counts per subnet or per subnet and pool.
    /// At the completion of all entries for a given subnet or pool, the counts
    /// are used to create LeaseStatsRow instances which are appended to an
    /// internal vector.  The process results in a vector containing one entry
    /// per state per subnet or per subnet and pool.
    ///
    /// Currently the states counted are:
    ///
    /// - Lease::STATE_DEFAULT (i.e. assigned)
    /// - Lease::STATE_DECLINED
    void start() {<--- Function in derived class
        switch (getSelectMode()) {
        case ALL_SUBNETS:
        case SINGLE_SUBNET:
        case SUBNET_RANGE:
            startSubnets();
            break;

        case ALL_SUBNET_POOLS:
            startSubnetPools();
            break;
        }
    }

private:
    /// @brief Creates the IPv4 lease statistical data result set
    ///
    /// The result set is populated by iterating over the IPv4 leases in
    /// storage, in ascending order by subnet id, accumulating the lease state
    /// counts per subnet.
    /// At the completion of all entries for a given subnet, the counts are
    /// used to create LeaseStatsRow instances which are appended to an
    /// internal vector.  The process results in a vector containing one entry
    /// per state per subnet.
    ///
    /// Currently the states counted are:
    ///
    /// - Lease::STATE_DEFAULT (i.e. assigned)
    /// - Lease::STATE_DECLINED
    void startSubnets() {
        const Lease4StorageSubnetIdIndex& idx
            = storage4_.get<SubnetIdIndexTag>();

        // Set lower and upper bounds based on select mode
        Lease4StorageSubnetIdIndex::const_iterator lower;
        Lease4StorageSubnetIdIndex::const_iterator upper;

        switch (getSelectMode()) {
        case ALL_SUBNETS:
            lower = idx.begin();
            upper = idx.end();
            break;

        case SINGLE_SUBNET:
            lower = idx.lower_bound(getFirstSubnetID());
            upper = idx.upper_bound(getFirstSubnetID());
            break;

        case SUBNET_RANGE:
            lower = idx.lower_bound(getFirstSubnetID());
            upper = idx.upper_bound(getLastSubnetID());
            break;

        default:
            return;
        }

        // Return an empty set if there are no rows.
        if (lower == upper) {
            return;
        }

        // Iterate over the leases in order by subnet, accumulating per
        // subnet counts for each state of interest.  As we finish each
        // subnet, add the appropriate rows to our result set.
        SubnetID cur_id = 0;
        int64_t assigned = 0;
        int64_t declined = 0;
        for (Lease4StorageSubnetIdIndex::const_iterator lease = lower;
             lease != upper; ++lease) {
            // If we've hit the next subnet, add rows for the current subnet
            // and wipe the accumulators
            if ((*lease)->subnet_id_ != cur_id) {
                if (cur_id > 0) {
                    if (assigned > 0) {
                        rows_.push_back(LeaseStatsRow(cur_id,
                                                      Lease::STATE_DEFAULT,
                                                      assigned));
                        assigned = 0;
                    }

                    if (declined > 0) {
                        rows_.push_back(LeaseStatsRow(cur_id,
                                                      Lease::STATE_DECLINED,
                                                      declined));
                        declined = 0;
                    }
                }

                // Update current subnet id
                cur_id = (*lease)->subnet_id_;
            }

            // Bump the appropriate accumulator
            if ((*lease)->state_ == Lease::STATE_DEFAULT) {
                ++assigned;
            } else if ((*lease)->state_ == Lease::STATE_DECLINED) {
                ++declined;
            }
        }

        // Make the rows for last subnet
        if (assigned > 0) {
            rows_.push_back(LeaseStatsRow(cur_id, Lease::STATE_DEFAULT,
                                          assigned));
        }

        if (declined > 0) {
            rows_.push_back(LeaseStatsRow(cur_id, Lease::STATE_DECLINED,
                                          declined));
        }

        // Reset the next row position back to the beginning of the rows.
        next_pos_ = rows_.begin();
    }

    /// @brief Creates the IPv4 lease statistical data result set
    ///
    /// The result set is populated by iterating over the IPv4 leases in
    /// storage, in ascending order by subnet id and pool id, accumulating the
    /// lease state counts per subnet and pool.
    /// At the completion of all entries for a given subnet or pool, the counts
    /// are used to create LeaseStatsRow instances which are appended to an
    /// internal vector.  The process results in a vector containing one entry
    /// per state per subnet and pool.
    ///
    /// Currently the states counted are:
    ///
    /// - Lease::STATE_DEFAULT (i.e. assigned)
    /// - Lease::STATE_DECLINED
    void startSubnetPools() {
        const Lease4StorageSubnetIdPoolIdIndex& idx
            = storage4_.get<SubnetIdPoolIdIndexTag>();

        // Set lower and upper bounds based on select mode
        Lease4StorageSubnetIdPoolIdIndex::const_iterator lower;
        Lease4StorageSubnetIdPoolIdIndex::const_iterator upper;
        switch (getSelectMode()) {
        case ALL_SUBNET_POOLS:
            lower = idx.begin();
            upper = idx.end();
            break;

        default:
            return;
        }

        // Return an empty set if there are no rows.
        if (lower == upper) {
            return;
        }

        // Iterate over the leases in order by subnet and pool, accumulating per
        // subnet and pool counts for each state of interest.  As we finish each
        // subnet or pool, add the appropriate rows to our result set.
        SubnetID cur_id = 0;
        uint32_t cur_pool_id = 0;
        int64_t assigned = 0;
        int64_t declined = 0;
        for (Lease4StorageSubnetIdPoolIdIndex::const_iterator lease = lower;
             lease != upper; ++lease) {
            // If we've hit the next pool, add rows for the current subnet and
            // pool and wipe the accumulators
            if ((*lease)->pool_id_ != cur_pool_id) {
                if (assigned > 0) {
                    rows_.push_back(LeaseStatsRow(cur_id,
                                                  Lease::STATE_DEFAULT,
                                                  assigned, cur_pool_id));
                    assigned = 0;
                }

                if (declined > 0) {
                    rows_.push_back(LeaseStatsRow(cur_id,
                                                  Lease::STATE_DECLINED,
                                                  declined, cur_pool_id));
                    declined = 0;
                }

                // Update current pool id
                cur_pool_id = (*lease)->pool_id_;
            }

            // If we've hit the next subnet, add rows for the current subnet
            // and wipe the accumulators
            if ((*lease)->subnet_id_ != cur_id) {
                if (cur_id > 0) {
                    if (assigned > 0) {
                        rows_.push_back(LeaseStatsRow(cur_id,
                                                      Lease::STATE_DEFAULT,
                                                      assigned, cur_pool_id));
                        assigned = 0;
                    }

                    if (declined > 0) {
                        rows_.push_back(LeaseStatsRow(cur_id,
                                                      Lease::STATE_DECLINED,
                                                      declined, cur_pool_id));
                        declined = 0;
                    }
                }

                // Update current subnet id
                cur_id = (*lease)->subnet_id_;

                // Reset pool id
                cur_pool_id = 0;
            }

            // Bump the appropriate accumulator
            if ((*lease)->state_ == Lease::STATE_DEFAULT) {
                ++assigned;
            } else if ((*lease)->state_ == Lease::STATE_DECLINED) {
                ++declined;
            }
        }

        // Make the rows for last subnet
        if (assigned > 0) {
            rows_.push_back(LeaseStatsRow(cur_id, Lease::STATE_DEFAULT,
                                          assigned, cur_pool_id));
        }

        if (declined > 0) {
            rows_.push_back(LeaseStatsRow(cur_id, Lease::STATE_DECLINED,
                                          declined, cur_pool_id));
        }

        // Reset the next row position back to the beginning of the rows.
        next_pos_ = rows_.begin();
    }

    /// @brief The Memfile storage containing the IPv4 leases to analyze
    Lease4Storage& storage4_;
};


/// @brief Memfile derivation of the IPv6 statistical lease data query
///
/// This class is used to recalculate IPv6 lease statistics for Memfile
/// lease storage.  It does so by iterating over the given storage,
/// accumulating counts of leases in each of the monitored lease states
/// for each subnet and storing these counts in an internal collection.
/// The populated result set will contain one entry per monitored state
/// per subnet.
///
class MemfileLeaseStatsQuery6 : public MemfileLeaseStatsQuery {
public:
    /// @brief Constructor
    ///
    /// @param storage6 A pointer to the v6 lease storage to be counted
    /// @param select_mode The selection criteria which is either ALL_SUBNETS or
    /// ALL_SUBNET_POOLS
    MemfileLeaseStatsQuery6(Lease6Storage& storage6,
                            const SelectMode& select_mode = ALL_SUBNETS)
        : MemfileLeaseStatsQuery(select_mode), storage6_(storage6) {
    };

    /// @brief Constructor for a single subnet query
    ///
    /// @param storage6 A pointer to the v6 lease storage to be counted
    /// @param subnet_id ID of the desired subnet
    MemfileLeaseStatsQuery6(Lease6Storage& storage6, const SubnetID& subnet_id)
        : MemfileLeaseStatsQuery(subnet_id), storage6_(storage6) {
    };

    /// @brief Constructor for a subnet range query
    ///
    /// @param storage6 A pointer to the v6 lease storage to be counted
    /// @param first_subnet_id ID of the first subnet in the desired range
    /// @param last_subnet_id ID of the last subnet in the desired range
    MemfileLeaseStatsQuery6(Lease6Storage& storage6, const SubnetID& first_subnet_id,
                            const SubnetID& last_subnet_id)
        : MemfileLeaseStatsQuery(first_subnet_id, last_subnet_id), storage6_(storage6) {
    };

    /// @brief Destructor
    virtual ~MemfileLeaseStatsQuery6() {};<--- Destructor in derived class

    /// @brief Creates the IPv6 lease statistical data result set
    ///
    /// The result set is populated by iterating over the IPv6 leases in
    /// storage, in ascending order by subnet id or by subnet id and pool id,
    /// accumulating the lease state counts per subnet or per subnet and pool.
    /// At the completion of all entries for a given subnet or pool, the counts
    /// are used to create LeaseStatsRow instances which are appended to an
    /// internal vector.  The process results in a vector containing one entry
    /// per state per subnet or per subnet and pool.
    ///
    /// Currently the states counted are:
    ///
    /// - Lease::STATE_DEFAULT (i.e. assigned)
    /// - Lease::STATE_DECLINED
    void start() {<--- Function in derived class
        switch (getSelectMode()) {
        case ALL_SUBNETS:
        case SINGLE_SUBNET:
        case SUBNET_RANGE:
            startSubnets();
            break;

        case ALL_SUBNET_POOLS:
            startSubnetPools();
            break;
        }
    }

private:
    /// @brief Creates the IPv6 lease statistical data result set
    ///
    /// The result set is populated by iterating over the IPv6 leases in
    /// storage, in ascending order by subnet id, accumulating the lease state
    /// counts per subnet.
    /// At the completion of all entries for a given subnet, the counts are
    /// used to create LeaseStatsRow instances which are appended to an
    /// internal vector.  The process results in a vector containing one entry
    /// per state per subnet.
    ///
    /// Currently the states counted are:
    ///
    /// - Lease::STATE_DEFAULT (i.e. assigned)
    /// - Lease::STATE_DECLINED
    virtual void startSubnets() {
        const Lease6StorageSubnetIdIndex& idx
            = storage6_.get<SubnetIdIndexTag>();

        // Set lower and upper bounds based on select mode
        Lease6StorageSubnetIdIndex::const_iterator lower;
        Lease6StorageSubnetIdIndex::const_iterator upper;
        switch (getSelectMode()) {
        case ALL_SUBNETS:
            lower = idx.begin();
            upper = idx.end();
            break;

        case SINGLE_SUBNET:
            lower = idx.lower_bound(getFirstSubnetID());
            upper = idx.upper_bound(getFirstSubnetID());
            break;

        case SUBNET_RANGE:
            lower = idx.lower_bound(getFirstSubnetID());
            upper = idx.upper_bound(getLastSubnetID());
            break;

        default:
            return;
        }

        // Return an empty set if there are no rows.
        if (lower == upper) {
            return;
        }

        // Iterate over the leases in order by subnet, accumulating per
        // subnet counts for each state of interest.  As we finish each
        // subnet, add the appropriate rows to our result set.
        SubnetID cur_id = 0;
        int64_t assigned = 0;
        int64_t declined = 0;
        int64_t assigned_pds = 0;
        for (Lease6StorageSubnetIdIndex::const_iterator lease = lower;
             lease != upper; ++lease) {
            // If we've hit the next subnet, add rows for the current subnet
            // and wipe the accumulators
            if ((*lease)->subnet_id_ != cur_id) {
                if (cur_id > 0) {
                    if (assigned > 0) {
                        rows_.push_back(LeaseStatsRow(cur_id, Lease::TYPE_NA,
                                                      Lease::STATE_DEFAULT,
                                                      assigned));
                        assigned = 0;
                    }

                    if (declined > 0) {
                        rows_.push_back(LeaseStatsRow(cur_id, Lease::TYPE_NA,
                                                      Lease::STATE_DECLINED,
                                                      declined));
                        declined = 0;
                    }

                    if (assigned_pds > 0) {
                        rows_.push_back(LeaseStatsRow(cur_id, Lease::TYPE_PD,
                                                      Lease::STATE_DEFAULT,
                                                      assigned_pds));
                        assigned_pds = 0;
                    }
                }

                // Update current subnet id
                cur_id = (*lease)->subnet_id_;
            }

            // Bump the appropriate accumulator
            if ((*lease)->state_ == Lease::STATE_DEFAULT) {
                switch((*lease)->type_) {
                case Lease::TYPE_NA:
                    ++assigned;
                    break;
                case Lease::TYPE_PD:
                    ++assigned_pds;
                    break;
                default:
                    break;
                }
            } else if ((*lease)->state_ == Lease::STATE_DECLINED) {
                // In theory only NAs can be declined
                if (((*lease)->type_) == Lease::TYPE_NA) {
                    ++declined;
                }
            }
        }

        // Make the rows for last subnet, unless there were no rows
        if (assigned > 0) {
            rows_.push_back(LeaseStatsRow(cur_id, Lease::TYPE_NA,
                                          Lease::STATE_DEFAULT, assigned));
        }

        if (declined > 0) {
            rows_.push_back(LeaseStatsRow(cur_id, Lease::TYPE_NA,
                                          Lease::STATE_DECLINED, declined));
        }

        if (assigned_pds > 0) {
            rows_.push_back(LeaseStatsRow(cur_id, Lease::TYPE_PD,
                                          Lease::STATE_DEFAULT, assigned_pds));
        }

        // Set the next row position to the beginning of the rows.
        next_pos_ = rows_.begin();
    }

    /// @brief Creates the IPv6 lease statistical data result set
    ///
    /// The result set is populated by iterating over the IPv6 leases in
    /// storage, in ascending order by subnet id and pool id, accumulating the
    /// lease state counts per subnet and pool.
    /// At the completion of all entries for a given subnet or pool, the counts
    /// are used to create LeaseStatsRow instances which are appended to an
    /// internal vector.  The process results in a vector containing one entry
    /// per state per subnet and pool.
    ///
    /// Currently the states counted are:
    ///
    /// - Lease::STATE_DEFAULT (i.e. assigned)
    /// - Lease::STATE_DECLINED
    virtual void startSubnetPools() {
        const Lease6StorageSubnetIdPoolIdIndex& idx
            = storage6_.get<SubnetIdPoolIdIndexTag>();

        // Set lower and upper bounds based on select mode
        Lease6StorageSubnetIdPoolIdIndex::const_iterator lower;
        Lease6StorageSubnetIdPoolIdIndex::const_iterator upper;
        switch (getSelectMode()) {
        case ALL_SUBNET_POOLS:
            lower = idx.begin();
            upper = idx.end();
            break;

        default:
            return;
        }

        // Return an empty set if there are no rows.
        if (lower == upper) {
            return;
        }

        // Iterate over the leases in order by subnet, accumulating per
        // subnet counts for each state of interest.  As we finish each
        // subnet, add the appropriate rows to our result set.
        SubnetID cur_id = 0;
        uint32_t cur_pool_id = 0;
        int64_t assigned = 0;
        int64_t declined = 0;
        int64_t assigned_pds = 0;
        for (Lease6StorageSubnetIdPoolIdIndex::const_iterator lease = lower;
             lease != upper; ++lease) {
            // If we've hit the next pool, add rows for the current subnet and
            // pool and wipe the accumulators
            if ((*lease)->pool_id_ != cur_pool_id) {
                if (assigned > 0) {
                    rows_.push_back(LeaseStatsRow(cur_id, Lease::TYPE_NA,
                                                  Lease::STATE_DEFAULT,
                                                  assigned, cur_pool_id));
                    assigned = 0;
                }

                if (declined > 0) {
                    rows_.push_back(LeaseStatsRow(cur_id, Lease::TYPE_NA,
                                                  Lease::STATE_DECLINED,
                                                  declined, cur_pool_id));
                    declined = 0;
                }

                if (assigned_pds > 0) {
                    rows_.push_back(LeaseStatsRow(cur_id, Lease::TYPE_PD,
                                                  Lease::STATE_DEFAULT,
                                                  assigned_pds, cur_pool_id));
                    assigned_pds = 0;
                }

                // Update current pool id
                cur_pool_id = (*lease)->pool_id_;
            }

            // If we've hit the next subnet, add rows for the current subnet
            // and wipe the accumulators
            if ((*lease)->subnet_id_ != cur_id) {
                if (cur_id > 0) {
                    if (assigned > 0) {
                        rows_.push_back(LeaseStatsRow(cur_id, Lease::TYPE_NA,
                                                      Lease::STATE_DEFAULT,
                                                      assigned, cur_pool_id));
                        assigned = 0;
                    }

                    if (declined > 0) {
                        rows_.push_back(LeaseStatsRow(cur_id, Lease::TYPE_NA,
                                                      Lease::STATE_DECLINED,
                                                      declined, cur_pool_id));
                        declined = 0;
                    }

                    if (assigned_pds > 0) {
                        rows_.push_back(LeaseStatsRow(cur_id, Lease::TYPE_PD,
                                                      Lease::STATE_DEFAULT,
                                                      assigned_pds, cur_pool_id));
                        assigned_pds = 0;
                    }
                }

                // Update current subnet id
                cur_id = (*lease)->subnet_id_;

                // Reset pool id
                cur_pool_id = 0;
            }

            // Bump the appropriate accumulator
            if ((*lease)->state_ == Lease::STATE_DEFAULT) {
                switch((*lease)->type_) {
                case Lease::TYPE_NA:
                    ++assigned;
                    break;
                case Lease::TYPE_PD:
                    ++assigned_pds;
                    break;
                default:
                    break;
                }
            } else if ((*lease)->state_ == Lease::STATE_DECLINED) {
                // In theory only NAs can be declined
                if (((*lease)->type_) == Lease::TYPE_NA) {
                    ++declined;
                }
            }
        }

        // Make the rows for last subnet, unless there were no rows
        if (assigned > 0) {
            rows_.push_back(LeaseStatsRow(cur_id, Lease::TYPE_NA,
                                          Lease::STATE_DEFAULT, assigned,
                                          cur_pool_id));
        }

        if (declined > 0) {
            rows_.push_back(LeaseStatsRow(cur_id, Lease::TYPE_NA,
                                          Lease::STATE_DECLINED, declined,
                                          cur_pool_id));
        }

        if (assigned_pds > 0) {
            rows_.push_back(LeaseStatsRow(cur_id, Lease::TYPE_PD,
                                          Lease::STATE_DEFAULT, assigned_pds,
                                          cur_pool_id));
        }

        // Set the next row position to the beginning of the rows.
        next_pos_ = rows_.begin();
    }

    /// @brief The Memfile storage containing the IPv6 leases to analyze
    Lease6Storage& storage6_;
};

// Explicit definition of class static constants.  Values are given in the
// declaration so they're not needed here.
const int Memfile_LeaseMgr::MAJOR_VERSION_V4;
const int Memfile_LeaseMgr::MINOR_VERSION_V4;
const int Memfile_LeaseMgr::MAJOR_VERSION_V6;
const int Memfile_LeaseMgr::MINOR_VERSION_V6;

Memfile_LeaseMgr::Memfile_LeaseMgr(const DatabaseConnection::ParameterMap& parameters)
    : TrackingLeaseMgr(), lfc_setup_(), conn_(parameters), mutex_(new std::mutex) {
    bool conversion_needed = false;

    // Check if the extended info tables are enabled.
    setExtendedInfoTablesEnabled(parameters);

    // Check the universe and use v4 file or v6 file.
    std::string universe = conn_.getParameter("universe");
    if (universe == "4") {
        std::string file4 = initLeaseFilePath(V4);
        if (!file4.empty()) {
            conversion_needed = loadLeasesFromFiles<Lease4,
                                                 CSVLeaseFile4>(file4,
                                                                lease_file4_,
                                                                storage4_);
            static_cast<void>(extractExtendedInfo4(false, false));
        }
    } else {
        std::string file6 = initLeaseFilePath(V6);
        if (!file6.empty()) {
            conversion_needed = loadLeasesFromFiles<Lease6,
                                                 CSVLeaseFile6>(file6,
                                                                lease_file6_,
                                                                storage6_);
            buildExtendedInfoTables6();
        }
    }

    // If lease persistence have been disabled for both v4 and v6,
    // issue a warning. It is ok not to write leases to disk when
    // doing testing, but it should not be done in normal server
    // operation.
    if (!persistLeases(V4) && !persistLeases(V6)) {
        LOG_WARN(dhcpsrv_logger, DHCPSRV_MEMFILE_NO_STORAGE);
    } else {
        if (conversion_needed) {
            auto const& version(getVersion());
            LOG_WARN(dhcpsrv_logger, DHCPSRV_MEMFILE_CONVERTING_LEASE_FILES)
                    .arg(version.first).arg(version.second);
        }
        lfcSetup(conversion_needed);
    }
}

Memfile_LeaseMgr::~Memfile_LeaseMgr() {
    if (lease_file4_) {
        lease_file4_->close();
        lease_file4_.reset();
    }
    if (lease_file6_) {
        lease_file6_->close();
        lease_file6_.reset();
    }
}

std::string
Memfile_LeaseMgr::getDBVersionInternal(Universe const& u) {
    std::stringstream tmp;
    tmp << "Memfile backend ";
    if (u == V4) {
        tmp << MAJOR_VERSION_V4 << "." << MINOR_VERSION_V4;
    } else if (u == V6) {
        tmp << MAJOR_VERSION_V6 << "." << MINOR_VERSION_V6;
    }
    return tmp.str();
}

std::string
Memfile_LeaseMgr::getDBVersion() {<--- Derived function 'Memfile_LeaseMgr::getDBVersion'
    uint16_t family = CfgMgr::instance().getFamily();
    if (family == AF_INET6) {
        return (Memfile_LeaseMgr::getDBVersionInternal(Memfile_LeaseMgr::V6));
    } else {
        return (Memfile_LeaseMgr::getDBVersionInternal(Memfile_LeaseMgr::V4));
    }
}

bool
Memfile_LeaseMgr::addLeaseInternal(const Lease4Ptr& lease) {
    if (getLease4Internal(lease->addr_)) {
        // there is a lease with specified address already
        return (false);
    }

    // Try to write a lease to disk first. If this fails, the lease will
    // not be inserted to the memory and the disk and in-memory data will
    // remain consistent.
    if (persistLeases(V4)) {
        lease_file4_->append(*lease);
    }

    storage4_.insert(lease);

    // Update lease current expiration time (allows update between the creation
    // of the Lease up to the point of insertion in the database).
    lease->updateCurrentExpirationTime();

    // Increment class lease counters.
    class_lease_counter_.addLease(lease);

    // Run installed callbacks.
    if (hasCallbacks()) {
        trackAddLease(lease);
    }

    return (true);
}

bool
Memfile_LeaseMgr::addLease(const Lease4Ptr& lease) {
    LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
              DHCPSRV_MEMFILE_ADD_ADDR4).arg(lease->addr_.toText());

    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        return (addLeaseInternal(lease));
    } else {
        return (addLeaseInternal(lease));
    }
}

bool
Memfile_LeaseMgr::addLeaseInternal(const Lease6Ptr& lease) {
    if (getLease6Internal(lease->type_, lease->addr_)) {
        // there is a lease with specified address already
        return (false);
    }

    // Try to write a lease to disk first. If this fails, the lease will
    // not be inserted to the memory and the disk and in-memory data will
    // remain consistent.
    if (persistLeases(V6)) {
        lease_file6_->append(*lease);
    }

    lease->extended_info_action_ = Lease6::ACTION_IGNORE;
    storage6_.insert(lease);

    // Update lease current expiration time (allows update between the creation
    // of the Lease up to the point of insertion in the database).
    lease->updateCurrentExpirationTime();

    // Increment class lease counters.
    class_lease_counter_.addLease(lease);

    if (getExtendedInfoTablesEnabled()) {
        static_cast<void>(addExtendedInfo6(lease));
    }

    // Run installed callbacks.
    if (hasCallbacks()) {
        trackAddLease(lease);
    }

    return (true);
}

bool
Memfile_LeaseMgr::addLease(const Lease6Ptr& lease) {
    LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
              DHCPSRV_MEMFILE_ADD_ADDR6).arg(lease->addr_.toText());

    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        return (addLeaseInternal(lease));
    } else {
        return (addLeaseInternal(lease));
    }
}

Lease4Ptr
Memfile_LeaseMgr::getLease4Internal(const isc::asiolink::IOAddress& addr) const {
    const Lease4StorageAddressIndex& idx = storage4_.get<AddressIndexTag>();
    Lease4StorageAddressIndex::iterator l = idx.find(addr);
    if (l == idx.end()) {
        return (Lease4Ptr());
    } else {
        return (Lease4Ptr(new Lease4(**l)));
    }
}

Lease4Ptr
Memfile_LeaseMgr::getLease4(const isc::asiolink::IOAddress& addr) const {
    LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
              DHCPSRV_MEMFILE_GET_ADDR4).arg(addr.toText());

    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        return (getLease4Internal(addr));
    } else {
        return (getLease4Internal(addr));
    }
}

void
Memfile_LeaseMgr::getLease4Internal(const HWAddr& hwaddr,
                                    Lease4Collection& collection) const {
    // Using composite index by 'hw address' and 'subnet id'. It is
    // ok to use it for searching by the 'hw address' only.
    const Lease4StorageHWAddressSubnetIdIndex& idx =
        storage4_.get<HWAddressSubnetIdIndexTag>();
    std::pair<Lease4StorageHWAddressSubnetIdIndex::const_iterator,
              Lease4StorageHWAddressSubnetIdIndex::const_iterator> l
        = idx.equal_range(boost::make_tuple(hwaddr.hwaddr_));

    BOOST_FOREACH(auto const& lease, l) {
        collection.push_back(Lease4Ptr(new Lease4(*lease)));
    }
}

Lease4Collection
Memfile_LeaseMgr::getLease4(const HWAddr& hwaddr) const {
    LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
              DHCPSRV_MEMFILE_GET_HWADDR).arg(hwaddr.toText());

    Lease4Collection collection;
    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        getLease4Internal(hwaddr, collection);
    } else {
        getLease4Internal(hwaddr, collection);
    }

    return (collection);
}

Lease4Ptr
Memfile_LeaseMgr::getLease4Internal(const HWAddr& hwaddr,
                                    SubnetID subnet_id) const {
    // Get the index by HW Address and Subnet Identifier.
    const Lease4StorageHWAddressSubnetIdIndex& idx =
        storage4_.get<HWAddressSubnetIdIndexTag>();
    // Try to find the lease using HWAddr and subnet id.
    Lease4StorageHWAddressSubnetIdIndex::const_iterator lease =
        idx.find(boost::make_tuple(hwaddr.hwaddr_, subnet_id));
    // Lease was not found. Return empty pointer to the caller.
    if (lease == idx.end()) {
        return (Lease4Ptr());
    }

    // Lease was found. Return it to the caller.
    return (Lease4Ptr(new Lease4(**lease)));
}

Lease4Ptr
Memfile_LeaseMgr::getLease4(const HWAddr& hwaddr,
                            SubnetID subnet_id) const {
    LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
              DHCPSRV_MEMFILE_GET_SUBID_HWADDR).arg(subnet_id)
        .arg(hwaddr.toText());

    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        return (getLease4Internal(hwaddr, subnet_id));
    } else {
        return (getLease4Internal(hwaddr, subnet_id));
    }
}

void
Memfile_LeaseMgr::getLease4Internal(const ClientId& client_id,
                                    Lease4Collection& collection) const {
    // Using composite index by 'client id' and 'subnet id'. It is ok
    // to use it to search by 'client id' only.
    const Lease4StorageClientIdSubnetIdIndex& idx =
        storage4_.get<ClientIdSubnetIdIndexTag>();
    std::pair<Lease4StorageClientIdSubnetIdIndex::const_iterator,
              Lease4StorageClientIdSubnetIdIndex::const_iterator> l
        = idx.equal_range(boost::make_tuple(client_id.getClientId()));

    BOOST_FOREACH(auto const& lease, l) {
        collection.push_back(Lease4Ptr(new Lease4(*lease)));
    }
}

Lease4Collection
Memfile_LeaseMgr::getLease4(const ClientId& client_id) const {
    LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
              DHCPSRV_MEMFILE_GET_CLIENTID).arg(client_id.toText());

    Lease4Collection collection;
    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        getLease4Internal(client_id, collection);
    } else {
        getLease4Internal(client_id, collection);
    }

    return (collection);
}

Lease4Ptr
Memfile_LeaseMgr::getLease4Internal(const ClientId& client_id,
                                    SubnetID subnet_id) const {
    // Get the index by client and subnet id.
    const Lease4StorageClientIdSubnetIdIndex& idx =
        storage4_.get<ClientIdSubnetIdIndexTag>();
    // Try to get the lease using client id and subnet id.
    Lease4StorageClientIdSubnetIdIndex::const_iterator lease =
        idx.find(boost::make_tuple(client_id.getClientId(), subnet_id));
    // Lease was not found. Return empty pointer to the caller.
    if (lease == idx.end()) {
        return (Lease4Ptr());
    }
    // Lease was found. Return it to the caller.
    return (Lease4Ptr(new Lease4(**lease)));
}

Lease4Ptr
Memfile_LeaseMgr::getLease4(const ClientId& client_id,
                            SubnetID subnet_id) const {
    LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
              DHCPSRV_MEMFILE_GET_SUBID_CLIENTID).arg(subnet_id)
              .arg(client_id.toText());

    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        return (getLease4Internal(client_id, subnet_id));
    } else {
        return (getLease4Internal(client_id, subnet_id));
    }
}

void
Memfile_LeaseMgr::getLeases4Internal(SubnetID subnet_id,
                                     Lease4Collection& collection) const {
    const Lease4StorageSubnetIdIndex& idx = storage4_.get<SubnetIdIndexTag>();
    std::pair<Lease4StorageSubnetIdIndex::const_iterator,
              Lease4StorageSubnetIdIndex::const_iterator> l =
        idx.equal_range(subnet_id);

    BOOST_FOREACH(auto const& lease, l) {
        collection.push_back(Lease4Ptr(new Lease4(*lease)));
    }
}

Lease4Collection
Memfile_LeaseMgr::getLeases4(SubnetID subnet_id) const {
    LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL, DHCPSRV_MEMFILE_GET_SUBID4)
        .arg(subnet_id);

    Lease4Collection collection;
    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        getLeases4Internal(subnet_id, collection);
    } else {
        getLeases4Internal(subnet_id, collection);
    }

    return (collection);
}

void
Memfile_LeaseMgr::getLeases4Internal(const std::string& hostname,
                                     Lease4Collection& collection) const {
    const Lease4StorageHostnameIndex& idx = storage4_.get<HostnameIndexTag>();
    std::pair<Lease4StorageHostnameIndex::const_iterator,
              Lease4StorageHostnameIndex::const_iterator> l =
        idx.equal_range(hostname);

    BOOST_FOREACH(auto const& lease, l) {
        collection.push_back(Lease4Ptr(new Lease4(*lease)));
    }
}

Lease4Collection
Memfile_LeaseMgr::getLeases4(const std::string& hostname) const {
    LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL, DHCPSRV_MEMFILE_GET_HOSTNAME4)
        .arg(hostname);

    Lease4Collection collection;
    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        getLeases4Internal(hostname, collection);
    } else {
        getLeases4Internal(hostname, collection);
    }

    return (collection);
}

void
Memfile_LeaseMgr::getLeases4Internal(Lease4Collection& collection) const {
   for (auto const& lease : storage4_) {
       collection.push_back(Lease4Ptr(new Lease4(*lease)));<--- Consider using std::transform algorithm instead of a raw loop.
   }
}

Lease4Collection
Memfile_LeaseMgr::getLeases4() const {
   LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL, DHCPSRV_MEMFILE_GET4);

   Lease4Collection collection;
   if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        getLeases4Internal(collection);
   } else {
        getLeases4Internal(collection);
   }

   return (collection);
}

void
Memfile_LeaseMgr::getLeases4Internal(const asiolink::IOAddress& lower_bound_address,
                                     const LeasePageSize& page_size,
                                     Lease4Collection& collection) const {
    const Lease4StorageAddressIndex& idx = storage4_.get<AddressIndexTag>();
    Lease4StorageAddressIndex::const_iterator lb = idx.lower_bound(lower_bound_address);

    // Exclude the lower bound address specified by the caller.
    if ((lb != idx.end()) && ((*lb)->addr_ == lower_bound_address)) {
        ++lb;
    }

    // Return all other leases being within the page size.
    for (auto lease = lb;
         (lease != idx.end()) && (std::distance(lb, lease) < page_size.page_size_);
         ++lease) {
        collection.push_back(Lease4Ptr(new Lease4(**lease)));
    }
}

Lease4Collection
Memfile_LeaseMgr::getLeases4(const asiolink::IOAddress& lower_bound_address,
                             const LeasePageSize& page_size) const {
    // Expecting IPv4 address.
    if (!lower_bound_address.isV4()) {
        isc_throw(InvalidAddressFamily, "expected IPv4 address while "
                  "retrieving leases from the lease database, got "
                  << lower_bound_address);
    }

    LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL, DHCPSRV_MEMFILE_GET_PAGE4)
        .arg(page_size.page_size_)
        .arg(lower_bound_address.toText());

    Lease4Collection collection;
    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        getLeases4Internal(lower_bound_address, page_size, collection);
    } else {
        getLeases4Internal(lower_bound_address, page_size, collection);
    }

    return (collection);
}

Lease6Ptr
Memfile_LeaseMgr::getLease6Internal(Lease::Type type,
                                    const isc::asiolink::IOAddress& addr) const {
    Lease6Storage::iterator l = storage6_.find(addr);
    if (l == storage6_.end() || !(*l) || ((*l)->type_ != type)) {
        return (Lease6Ptr());
    } else {
        return (Lease6Ptr(new Lease6(**l)));
    }
}

Lease6Ptr
Memfile_LeaseMgr::getAnyLease6Internal(const isc::asiolink::IOAddress& addr) const {
    Lease6Storage::iterator l = storage6_.find(addr);
    if (l == storage6_.end() || !(*l)) {
        return (Lease6Ptr());
    } else {
        return (Lease6Ptr(new Lease6(**l)));
    }
}

Lease6Ptr
Memfile_LeaseMgr::getLease6(Lease::Type type,
                            const isc::asiolink::IOAddress& addr) const {
    LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
              DHCPSRV_MEMFILE_GET_ADDR6)
        .arg(addr.toText())
        .arg(Lease::typeToText(type));

    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        return (getLease6Internal(type, addr));
    } else {
        return (getLease6Internal(type, addr));
    }
}

void
Memfile_LeaseMgr::getLeases6Internal(Lease::Type type,
                                     const DUID& duid,
                                     uint32_t iaid,
                                     Lease6Collection& collection) const {
    // Get the index by DUID, IAID, lease type.
    const Lease6StorageDuidIaidTypeIndex& idx = storage6_.get<DuidIaidTypeIndexTag>();
    // Try to get the lease using the DUID, IAID and lease type.
    std::pair<Lease6StorageDuidIaidTypeIndex::const_iterator,
              Lease6StorageDuidIaidTypeIndex::const_iterator> l =
        idx.equal_range(boost::make_tuple(duid.getDuid(), iaid, type));

    for (Lease6StorageDuidIaidTypeIndex::const_iterator lease =
         l.first; lease != l.second; ++lease) {
        collection.push_back(Lease6Ptr(new Lease6(**lease)));
    }
}

Lease6Collection
Memfile_LeaseMgr::getLeases6(Lease::Type type,
                             const DUID& duid,
                             uint32_t iaid) const {
    LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
              DHCPSRV_MEMFILE_GET_IAID_DUID)
        .arg(iaid)
        .arg(duid.toText())
        .arg(Lease::typeToText(type));

    Lease6Collection collection;
    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        getLeases6Internal(type, duid, iaid, collection);
    } else {
        getLeases6Internal(type, duid, iaid, collection);
    }

    return (collection);
}

void
Memfile_LeaseMgr::getLeases6Internal(Lease::Type type,
                                     const DUID& duid,
                                     uint32_t iaid,
                                     SubnetID subnet_id,
                                     Lease6Collection& collection) const {
    // Get the index by DUID, IAID, lease type.
    const Lease6StorageDuidIaidTypeIndex& idx = storage6_.get<DuidIaidTypeIndexTag>();
    // Try to get the lease using the DUID, IAID and lease type.
    std::pair<Lease6StorageDuidIaidTypeIndex::const_iterator,
              Lease6StorageDuidIaidTypeIndex::const_iterator> l =
        idx.equal_range(boost::make_tuple(duid.getDuid(), iaid, type));

    for (Lease6StorageDuidIaidTypeIndex::const_iterator lease =
         l.first; lease != l.second; ++lease) {
        // Filter out the leases which subnet id doesn't match.
        if ((*lease)->subnet_id_ == subnet_id) {
            collection.push_back(Lease6Ptr(new Lease6(**lease)));
        }
    }
}

Lease6Collection
Memfile_LeaseMgr::getLeases6(Lease::Type type,
                             const DUID& duid,
                             uint32_t iaid,
                             SubnetID subnet_id) const {
    LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
              DHCPSRV_MEMFILE_GET_IAID_SUBID_DUID)
        .arg(iaid)
        .arg(subnet_id)
        .arg(duid.toText())
        .arg(Lease::typeToText(type));

    Lease6Collection collection;
    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        getLeases6Internal(type, duid, iaid, subnet_id, collection);
    } else {
        getLeases6Internal(type, duid, iaid, subnet_id, collection);
    }

    return (collection);
}

void
Memfile_LeaseMgr::getLeases6Internal(SubnetID subnet_id,
                                     Lease6Collection& collection) const {
    const Lease6StorageSubnetIdIndex& idx = storage6_.get<SubnetIdIndexTag>();
    std::pair<Lease6StorageSubnetIdIndex::const_iterator,
              Lease6StorageSubnetIdIndex::const_iterator> l =
        idx.equal_range(subnet_id);

    BOOST_FOREACH(auto const& lease, l) {
        collection.push_back(Lease6Ptr(new Lease6(*lease)));
    }
}

Lease6Collection
Memfile_LeaseMgr::getLeases6(SubnetID subnet_id) const {
    LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL, DHCPSRV_MEMFILE_GET_SUBID6)
        .arg(subnet_id);

    Lease6Collection collection;
    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        getLeases6Internal(subnet_id, collection);
    } else {
        getLeases6Internal(subnet_id, collection);
    }

    return (collection);
}

void
Memfile_LeaseMgr::getLeases6Internal(const std::string& hostname,
                                     Lease6Collection& collection) const {
    const Lease6StorageHostnameIndex& idx = storage6_.get<HostnameIndexTag>();
    std::pair<Lease6StorageHostnameIndex::const_iterator,
              Lease6StorageHostnameIndex::const_iterator> l =
        idx.equal_range(hostname);

    BOOST_FOREACH(auto const& lease, l) {
        collection.push_back(Lease6Ptr(new Lease6(*lease)));
    }
}

Lease6Collection
Memfile_LeaseMgr::getLeases6(const std::string& hostname) const {
    LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL, DHCPSRV_MEMFILE_GET_HOSTNAME6)
        .arg(hostname);

    Lease6Collection collection;
    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        getLeases6Internal(hostname, collection);
    } else {
        getLeases6Internal(hostname, collection);
    }

    return (collection);
}

void
Memfile_LeaseMgr::getLeases6Internal(Lease6Collection& collection) const {
   for (auto const& lease : storage6_) {
       collection.push_back(Lease6Ptr(new Lease6(*lease)));<--- Consider using std::transform algorithm instead of a raw loop.
   }
}

Lease6Collection
Memfile_LeaseMgr::getLeases6() const {
   LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL, DHCPSRV_MEMFILE_GET6);

   Lease6Collection collection;
   if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        getLeases6Internal(collection);
   } else {
        getLeases6Internal(collection);
   }

   return (collection);
}

void
Memfile_LeaseMgr::getLeases6Internal(const DUID& duid,
                                     Lease6Collection& collection) const {
    const Lease6StorageDuidIndex& idx = storage6_.get<DuidIndexTag>();
    std::pair<Lease6StorageDuidIndex::const_iterator,
              Lease6StorageDuidIndex::const_iterator> l =
        idx.equal_range(duid.getDuid());

    BOOST_FOREACH(auto const& lease, l) {
        collection.push_back(Lease6Ptr(new Lease6(*lease)));
    }
}

Lease6Collection
Memfile_LeaseMgr::getLeases6(const DUID& duid) const {
   LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL, DHCPSRV_MEMFILE_GET6_DUID)
       .arg(duid.toText());

    Lease6Collection collection;
    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        getLeases6Internal(duid, collection);
    } else {
        getLeases6Internal(duid, collection);
    }

    return (collection);
}

void
Memfile_LeaseMgr::getLeases6Internal(const asiolink::IOAddress& lower_bound_address,
                                     const LeasePageSize& page_size,
                                     Lease6Collection& collection) const {
    const Lease6StorageAddressIndex& idx = storage6_.get<AddressIndexTag>();
    Lease6StorageAddressIndex::const_iterator lb = idx.lower_bound(lower_bound_address);

    // Exclude the lower bound address specified by the caller.
    if ((lb != idx.end()) && ((*lb)->addr_ == lower_bound_address)) {
        ++lb;
    }

    // Return all other leases being within the page size.
    for (auto lease = lb;
         (lease != idx.end()) && (std::distance(lb, lease) < page_size.page_size_);
         ++lease) {
        collection.push_back(Lease6Ptr(new Lease6(**lease)));
    }
}

Lease6Collection
Memfile_LeaseMgr::getLeases6(const asiolink::IOAddress& lower_bound_address,
                             const LeasePageSize& page_size) const {
    // Expecting IPv6 address.
    if (!lower_bound_address.isV6()) {
        isc_throw(InvalidAddressFamily, "expected IPv6 address while "
                  "retrieving leases from the lease database, got "
                  << lower_bound_address);
    }

    LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL, DHCPSRV_MEMFILE_GET_PAGE6)
        .arg(page_size.page_size_)
        .arg(lower_bound_address.toText());

    Lease6Collection collection;
    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        getLeases6Internal(lower_bound_address, page_size, collection);
    } else {
        getLeases6Internal(lower_bound_address, page_size, collection);
    }

    return (collection);
}

Lease6Collection
Memfile_LeaseMgr::getLeases6Internal(SubnetID subnet_id,
                                     const IOAddress& lower_bound_address,
                                     const LeasePageSize& page_size) const {
    Lease6Collection collection;
    const Lease6StorageSubnetIdIndex& idx = storage6_.get<SubnetIdIndexTag>();
    Lease6StorageSubnetIdIndex::const_iterator lb =
        idx.lower_bound(boost::make_tuple(subnet_id, lower_bound_address));

    // Exclude the lower bound address specified by the caller.
    if ((lb != idx.end()) && ((*lb)->addr_ == lower_bound_address)) {
        ++lb;
    }

    // Return all leases being within the page size.
    for (auto it = lb; it != idx.end(); ++it) {
        if ((*it)->subnet_id_ != subnet_id) {
            // Gone after the subnet id index.
            break;
        }
        collection.push_back(Lease6Ptr(new Lease6(**it)));
        if (collection.size() >= page_size.page_size_) {
            break;
        }
    }
    return (collection);
}

Lease6Collection
Memfile_LeaseMgr::getLeases6(SubnetID subnet_id,
                             const IOAddress& lower_bound_address,
                             const LeasePageSize& page_size) const {
    LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
              DHCPSRV_MEMFILE_GET_SUBID_PAGE6)
        .arg(page_size.page_size_)
        .arg(lower_bound_address.toText())
        .arg(subnet_id);

    // Expecting IPv6 valid address.
    if (!lower_bound_address.isV6()) {
        isc_throw(InvalidAddressFamily, "expected IPv6 address while "
                  "retrieving leases from the lease database, got "
                  << lower_bound_address);
    }

    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        return (getLeases6Internal(subnet_id,
                                   lower_bound_address,
                                   page_size));
    } else {
        return (getLeases6Internal(subnet_id,
                                   lower_bound_address,
                                    page_size));
    }
}

void
Memfile_LeaseMgr::getExpiredLeases4Internal(Lease4Collection& expired_leases,
                                            const size_t max_leases) const {
    // Obtain the index which segragates leases by state and time.
    const Lease4StorageExpirationIndex& index = storage4_.get<ExpirationIndexTag>();

    // Retrieve leases which are not reclaimed and which haven't expired. The
    // 'less-than' operator will be used for both components of the index. So,
    // for the 'state' 'false' is less than 'true'. Also the leases with
    // expiration time lower than current time will be returned.
    Lease4StorageExpirationIndex::const_iterator ub =
        index.upper_bound(boost::make_tuple(false, time(0)));

    // Copy only the number of leases indicated by the max_leases parameter.
    for (Lease4StorageExpirationIndex::const_iterator lease = index.begin();
         (lease != ub) && ((max_leases == 0) || (std::distance(index.begin(), lease) <
                                                 max_leases));
         ++lease) {
        expired_leases.push_back(Lease4Ptr(new Lease4(**lease)));
    }
}

void
Memfile_LeaseMgr::getExpiredLeases4(Lease4Collection& expired_leases,
                                    const size_t max_leases) const {
    LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL, DHCPSRV_MEMFILE_GET_EXPIRED4)
        .arg(max_leases);

    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        getExpiredLeases4Internal(expired_leases, max_leases);
    } else {
        getExpiredLeases4Internal(expired_leases, max_leases);
    }
}

void
Memfile_LeaseMgr::getExpiredLeases6Internal(Lease6Collection& expired_leases,
                                            const size_t max_leases) const {
    // Obtain the index which segragates leases by state and time.
    const Lease6StorageExpirationIndex& index = storage6_.get<ExpirationIndexTag>();

    // Retrieve leases which are not reclaimed and which haven't expired. The
    // 'less-than' operator will be used for both components of the index. So,
    // for the 'state' 'false' is less than 'true'. Also the leases with
    // expiration time lower than current time will be returned.
    Lease6StorageExpirationIndex::const_iterator ub =
        index.upper_bound(boost::make_tuple(false, time(0)));

    // Copy only the number of leases indicated by the max_leases parameter.
    for (Lease6StorageExpirationIndex::const_iterator lease = index.begin();
         (lease != ub) && ((max_leases == 0) || (std::distance(index.begin(), lease) <
                                                 max_leases));
         ++lease) {
        expired_leases.push_back(Lease6Ptr(new Lease6(**lease)));
    }
}

void
Memfile_LeaseMgr::getExpiredLeases6(Lease6Collection& expired_leases,
                                    const size_t max_leases) const {
    LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL, DHCPSRV_MEMFILE_GET_EXPIRED6)
        .arg(max_leases);

    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        getExpiredLeases6Internal(expired_leases, max_leases);
    } else {
        getExpiredLeases6Internal(expired_leases, max_leases);
    }
}

void
Memfile_LeaseMgr::updateLease4Internal(const Lease4Ptr& lease) {
    // Obtain 'by address' index.
    Lease4StorageAddressIndex& index = storage4_.get<AddressIndexTag>();

    bool persist = persistLeases(V4);

    // Lease must exist if it is to be updated.
    Lease4StorageAddressIndex::const_iterator lease_it = index.find(lease->addr_);
    if (lease_it == index.end()) {
        isc_throw(NoSuchLease, "failed to update the lease with address "
                  << lease->addr_ << " - no such lease");
    } else if ((!persist) && (((*lease_it)->cltt_ != lease->current_cltt_) ||
        ((*lease_it)->valid_lft_ != lease->current_valid_lft_))) {
        // For test purpose only: check that the lease has not changed in
        // the database.
        isc_throw(NoSuchLease, "failed to update the lease with address "
                  << lease->addr_ << " - lease has changed in database");
    }

    // Try to write a lease to disk first. If this fails, the lease will
    // not be inserted to the memory and the disk and in-memory data will
    // remain consistent.
    if (persist) {
        lease_file4_->append(*lease);
    }

    // Update lease current expiration time.
    lease->updateCurrentExpirationTime();

    // Save a copy of the old lease as lease_it will point to the new
    // one after the replacement.
    Lease4Ptr old_lease = *lease_it;

    // Use replace() to re-index leases.
    index.replace(lease_it, Lease4Ptr(new Lease4(*lease)));

    // Adjust class lease counters.
    class_lease_counter_.updateLease(lease, old_lease);

    // Run installed callbacks.
    if (hasCallbacks()) {
        trackUpdateLease(lease);
    }
}

void
Memfile_LeaseMgr::updateLease4(const Lease4Ptr& lease) {
    LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
              DHCPSRV_MEMFILE_UPDATE_ADDR4).arg(lease->addr_.toText());

    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        updateLease4Internal(lease);
    } else {
        updateLease4Internal(lease);
    }
}

void
Memfile_LeaseMgr::updateLease6Internal(const Lease6Ptr& lease) {
    // Obtain 'by address' index.
    Lease6StorageAddressIndex& index = storage6_.get<AddressIndexTag>();

    bool persist = persistLeases(V6);

    // Get the recorded action and reset it.
    Lease6::ExtendedInfoAction recorded_action = lease->extended_info_action_;
    lease->extended_info_action_ = Lease6::ACTION_IGNORE;

    // Lease must exist if it is to be updated.
    Lease6StorageAddressIndex::const_iterator lease_it = index.find(lease->addr_);
    if (lease_it == index.end()) {
        isc_throw(NoSuchLease, "failed to update the lease with address "
                  << lease->addr_ << " - no such lease");
    } else if ((!persist) && (((*lease_it)->cltt_ != lease->current_cltt_) ||
        ((*lease_it)->valid_lft_ != lease->current_valid_lft_))) {
        // For test purpose only: check that the lease has not changed in
        // the database.
        isc_throw(NoSuchLease, "failed to update the lease with address "
                  << lease->addr_ << " - lease has changed in database");
    }

    // Try to write a lease to disk first. If this fails, the lease will
    // not be inserted to the memory and the disk and in-memory data will
    // remain consistent.
    if (persist) {
        lease_file6_->append(*lease);
    }

    // Update lease current expiration time.
    lease->updateCurrentExpirationTime();

    // Save a copy of the old lease as lease_it will point to the new
    // one after the replacement.
    Lease6Ptr old_lease = *lease_it;

    // Use replace() to re-index leases.
    index.replace(lease_it, Lease6Ptr(new Lease6(*lease)));

    // Adjust class lease counters.
    class_lease_counter_.updateLease(lease, old_lease);

    // Update extended info tables.
    if (getExtendedInfoTablesEnabled()) {
        switch (recorded_action) {
        case Lease6::ACTION_IGNORE:
            break;

        case Lease6::ACTION_DELETE:
            deleteExtendedInfo6(lease->addr_);
            break;

        case Lease6::ACTION_UPDATE:
            deleteExtendedInfo6(lease->addr_);
            static_cast<void>(addExtendedInfo6(lease));
            break;
        }
    }

    // Run installed callbacks.
    if (hasCallbacks()) {
        trackUpdateLease(lease);
    }
}

void
Memfile_LeaseMgr::updateLease6(const Lease6Ptr& lease) {
    LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
              DHCPSRV_MEMFILE_UPDATE_ADDR6).arg(lease->addr_.toText());

    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        updateLease6Internal(lease);
    } else {
        updateLease6Internal(lease);
    }
}

bool
Memfile_LeaseMgr::deleteLeaseInternal(const Lease4Ptr& lease) {
    const isc::asiolink::IOAddress& addr = lease->addr_;
    Lease4Storage::iterator l = storage4_.find(addr);
    if (l == storage4_.end()) {
        // No such lease
        return (false);
    } else {
        if (persistLeases(V4)) {
            // Copy the lease. The valid lifetime needs to be modified and
            // we don't modify the original lease.
            Lease4 lease_copy = **l;
            // Setting valid lifetime to 0 means that lease is being
            // removed.
            lease_copy.valid_lft_ = 0;
            lease_file4_->append(lease_copy);
        } else {
            // For test purpose only: check that the lease has not changed in
            // the database.
            if (((*l)->cltt_ != lease->current_cltt_) ||
                ((*l)->valid_lft_ != lease->current_valid_lft_)) {
                return false;
            }
        }

        storage4_.erase(l);

        // Decrement class lease counters.
        class_lease_counter_.removeLease(lease);

        // Run installed callbacks.
        if (hasCallbacks()) {
            trackDeleteLease(lease);
        }

        return (true);
    }
}

bool
Memfile_LeaseMgr::deleteLease(const Lease4Ptr& lease) {
    LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
              DHCPSRV_MEMFILE_DELETE_ADDR4).arg(lease->addr_.toText());

    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        return (deleteLeaseInternal(lease));
    } else {
        return (deleteLeaseInternal(lease));
    }
}

bool
Memfile_LeaseMgr::deleteLeaseInternal(const Lease6Ptr& lease) {
    lease->extended_info_action_ = Lease6::ACTION_IGNORE;

    const isc::asiolink::IOAddress& addr = lease->addr_;
    Lease6Storage::iterator l = storage6_.find(addr);
    if (l == storage6_.end()) {
        // No such lease
        return (false);
    } else {
        if (persistLeases(V6)) {
            // Copy the lease. The lifetimes need to be modified and we
            // don't modify the original lease.
            Lease6 lease_copy = **l;
            // Setting lifetimes to 0 means that lease is being removed.
            lease_copy.valid_lft_ = 0;
            lease_copy.preferred_lft_ = 0;
            lease_file6_->append(lease_copy);
        } else {
            // For test purpose only: check that the lease has not changed in
            // the database.
            if (((*l)->cltt_ != lease->current_cltt_) ||
                ((*l)->valid_lft_ != lease->current_valid_lft_)) {
                return false;
            }
        }

        storage6_.erase(l);

        // Decrement class lease counters.
        class_lease_counter_.removeLease(lease);

        // Delete references from extended info tables.
        if (getExtendedInfoTablesEnabled()) {
            deleteExtendedInfo6(lease->addr_);
        }

        // Run installed callbacks.
        if (hasCallbacks()) {
            trackDeleteLease(lease);
        }

        return (true);
    }
}

bool
Memfile_LeaseMgr::deleteLease(const Lease6Ptr& lease) {
    LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
              DHCPSRV_MEMFILE_DELETE_ADDR6).arg(lease->addr_.toText());

    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        return (deleteLeaseInternal(lease));
    } else {
        return (deleteLeaseInternal(lease));
    }
}

uint64_t
Memfile_LeaseMgr::deleteExpiredReclaimedLeases4(const uint32_t secs) {
    LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
              DHCPSRV_MEMFILE_DELETE_EXPIRED_RECLAIMED4)
        .arg(secs);

    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        return (deleteExpiredReclaimedLeases<
                Lease4StorageExpirationIndex, Lease4
                >(secs, V4, storage4_, lease_file4_));
    } else {
        return (deleteExpiredReclaimedLeases<
                Lease4StorageExpirationIndex, Lease4
                >(secs, V4, storage4_, lease_file4_));
    }
}

uint64_t
Memfile_LeaseMgr::deleteExpiredReclaimedLeases6(const uint32_t secs) {
    LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
              DHCPSRV_MEMFILE_DELETE_EXPIRED_RECLAIMED6)
        .arg(secs);

    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        return (deleteExpiredReclaimedLeases<
                Lease6StorageExpirationIndex, Lease6
                >(secs, V6, storage6_, lease_file6_));
    } else {
        return (deleteExpiredReclaimedLeases<
                Lease6StorageExpirationIndex, Lease6
                >(secs, V6, storage6_, lease_file6_));
    }
}

template<typename IndexType, typename LeaseType, typename StorageType,
         typename LeaseFileType>
uint64_t
Memfile_LeaseMgr::deleteExpiredReclaimedLeases(const uint32_t secs,
                                               const Universe& universe,
                                               StorageType& storage,
                                               LeaseFileType& lease_file) {
    // Obtain the index which segragates leases by state and time.
    IndexType& index = storage.template get<ExpirationIndexTag>();

    // This returns the first element which is greater than the specified
    // tuple (true, time(0) - secs). However, the range between the
    // beginning of the index and returned element also includes all the
    // elements for which the first value is false (lease state is NOT
    // reclaimed), because false < true. All elements between the
    // beginning of the index and the element returned, for which the
    // first value is true, represent the reclaimed leases which should
    // be deleted, because their expiration time + secs has occurred earlier
    // than current time.
    typename IndexType::const_iterator upper_limit =
        index.upper_bound(boost::make_tuple(true, time(0) - secs));

    // Now, we have to exclude all elements of the index which represent
    // leases in the state other than reclaimed - with the first value
    // in the index equal to false. Note that elements in the index are
    // ordered from the lower to the higher ones. So, all elements with
    // the first value of false are placed before the elements with the
    // value of true. Hence, we have to find the first element which
    // contains value of true. The time value is the lowest possible.
    typename IndexType::const_iterator lower_limit =
        index.upper_bound(boost::make_tuple(true, std::numeric_limits<int64_t>::min()));

    // If there are some elements in this range, delete them.
    uint64_t num_leases = static_cast<uint64_t>(std::distance(lower_limit, upper_limit));
    if (num_leases > 0) {

        LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
                  DHCPSRV_MEMFILE_DELETE_EXPIRED_RECLAIMED_START)
            .arg(num_leases);

        // If lease persistence is enabled, we also have to mark leases
        // as deleted in the lease file. We do this by setting the
        // lifetime to 0.
        if (persistLeases(universe)) {
            for (typename IndexType::const_iterator lease = lower_limit;
                 lease != upper_limit; ++lease) {
                // Copy lease to not affect the lease in the container.
                LeaseType lease_copy(**lease);
                // Set the valid lifetime to 0 to indicate the removal
                // of the lease.
                lease_copy.valid_lft_ = 0;
                lease_file->append(lease_copy);
            }
        }

        // Erase leases from memory.
        index.erase(lower_limit, upper_limit);

    }
    // Return number of leases deleted.
    return (num_leases);
}

std::string
Memfile_LeaseMgr::getDescription() const {
    return (std::string("In memory database with leases stored in a CSV file."));
}

std::pair<uint32_t, uint32_t>
Memfile_LeaseMgr::getVersion(const std::string& /* timer_name */) const {
    std::string const& universe(conn_.getParameter("universe"));
    if (universe == "4") {
        return std::make_pair(MAJOR_VERSION_V4, MINOR_VERSION_V4);
    } else if (universe == "6") {
        return std::make_pair(MAJOR_VERSION_V6, MINOR_VERSION_V6);
    }
    isc_throw(BadValue, "cannot determine version for universe " << universe);
}

void
Memfile_LeaseMgr::commit() {
    LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL, DHCPSRV_MEMFILE_COMMIT);
}

void
Memfile_LeaseMgr::rollback() {
    LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
              DHCPSRV_MEMFILE_ROLLBACK);
}

std::string
Memfile_LeaseMgr::appendSuffix(const std::string& file_name,
                               const LFCFileType& file_type) {
    std::string name(file_name);
    switch (file_type) {
    case FILE_INPUT:
        name += ".1";
        break;
    case FILE_PREVIOUS:
        name += ".2";
        break;
    case FILE_OUTPUT:
        name += ".output";
        break;
    case FILE_FINISH:
        name += ".completed";
        break;
    case FILE_PID:
        name += ".pid";
        break;
    default:
        // Do not append any suffix for the FILE_CURRENT.
        ;
    }

    return (name);
}

std::string
Memfile_LeaseMgr::getDefaultLeaseFilePath(Universe u) const {
    std::ostringstream s;
    s << CfgMgr::instance().getDataDir() << "/kea-leases";
    s << (u == V4 ? "4" : "6");
    s << ".csv";
    return (s.str());
}

std::string
Memfile_LeaseMgr::getLeaseFilePath(Universe u) const {
    if (u == V4) {
        return (lease_file4_ ? lease_file4_->getFilename() : "");
    }

    return (lease_file6_ ? lease_file6_->getFilename() : "");
}

bool
Memfile_LeaseMgr::persistLeases(Universe u) const {
    // Currently, if the lease file IO is not created, it means that writes to
    // disk have been explicitly disabled by the administrator. At some point,
    // there may be a dedicated ON/OFF flag implemented to control this.
    if (u == V4 && lease_file4_) {
        return (true);
    }

    return (u == V6 && lease_file6_);
}

std::string
Memfile_LeaseMgr::initLeaseFilePath(Universe u) {
    std::string persist_val;
    try {
        persist_val = conn_.getParameter("persist");
    } catch (const Exception&) {
        // If parameter persist hasn't been specified, we use a default value
        // 'yes'.
        persist_val = "true";
    }
    // If persist_val is 'false' we will not store leases to disk, so let's
    // return empty file name.
    if (persist_val == "false") {
        return ("");

    } else if (persist_val != "true") {
        isc_throw(isc::BadValue, "invalid value 'persist="
                  << persist_val << "'");
    }

    std::string lease_file;
    try {
        lease_file = conn_.getParameter("name");
    } catch (const Exception&) {
        lease_file = getDefaultLeaseFilePath(u);
    }
    return (lease_file);
}

template<typename LeaseObjectType, typename LeaseFileType, typename StorageType>
bool
Memfile_LeaseMgr::loadLeasesFromFiles(const std::string& filename,
                                      boost::shared_ptr<LeaseFileType>& lease_file,
                                      StorageType& storage) {
    // Check if the instance of the LFC is running right now. If it is
    // running, we refuse to load leases as the LFC may be writing to the
    // lease files right now. When the user retries server configuration
    // it should go through.
    /// @todo Consider applying a timeout for an LFC and retry when this
    /// timeout elapses.
    PIDFile pid_file(appendSuffix(filename, FILE_PID));
    if (pid_file.check()) {
        isc_throw(DbOpenError, "unable to load leases from files while the "
                  "lease file cleanup is in progress");
    }

    storage.clear();

    std::string max_row_errors_str = "0";
    try {
        max_row_errors_str = conn_.getParameter("max-row-errors");
    } catch (const std::exception&) {
        // Ignore and default to 0.
    }

    int64_t max_row_errors64;
    try {
        max_row_errors64 = boost::lexical_cast<int64_t>(max_row_errors_str);
    } catch (const boost::bad_lexical_cast&) {
        isc_throw(isc::BadValue, "invalid value of the max-row-errors "
                  << max_row_errors_str << " specified");
    }
    if ((max_row_errors64 < 0) ||
        (max_row_errors64 > std::numeric_limits<uint32_t>::max())) {
        isc_throw(isc::BadValue, "invalid value of the max-row-errors "
                  << max_row_errors_str << " specified");
    }
    uint32_t max_row_errors = static_cast<uint32_t>(max_row_errors64);

    // Load the leasefile.completed, if exists.
    bool conversion_needed = false;
    lease_file.reset(new LeaseFileType(std::string(filename + ".completed")));
    if (lease_file->exists()) {
        LeaseFileLoader::load<LeaseObjectType>(*lease_file, storage,
                                               max_row_errors);
        conversion_needed = conversion_needed || lease_file->needsConversion();
    } else {
        // If the leasefile.completed doesn't exist, let's load the leases
        // from leasefile.2 and leasefile.1, if they exist.
        lease_file.reset(new LeaseFileType(appendSuffix(filename, FILE_PREVIOUS)));
        if (lease_file->exists()) {
            LeaseFileLoader::load<LeaseObjectType>(*lease_file, storage,
                                                   max_row_errors);
            conversion_needed = conversion_needed || lease_file->needsConversion();
        }

        lease_file.reset(new LeaseFileType(appendSuffix(filename, FILE_INPUT)));
        if (lease_file->exists()) {
            LeaseFileLoader::load<LeaseObjectType>(*lease_file, storage,
                                                   max_row_errors);
            conversion_needed = conversion_needed || lease_file->needsConversion();
        }
    }

    // Always load leases from the primary lease file. If the lease file
    // doesn't exist it will be created by the LeaseFileLoader. Note
    // that the false value passed as the last parameter to load
    // function causes the function to leave the file open after
    // it is parsed. This file will be used by the backend to record
    // future lease updates.
    lease_file.reset(new LeaseFileType(filename));
    LeaseFileLoader::load<LeaseObjectType>(*lease_file, storage,
                                           max_row_errors, false);
    conversion_needed = conversion_needed || lease_file->needsConversion();

    return (conversion_needed);
}


bool
Memfile_LeaseMgr::isLFCRunning() const {
    return (lfc_setup_->isRunning());
}

int
Memfile_LeaseMgr::getLFCExitStatus() const {
    return (lfc_setup_->getExitStatus());
}

void
Memfile_LeaseMgr::lfcCallback() {
    LOG_INFO(dhcpsrv_logger, DHCPSRV_MEMFILE_LFC_START);

    // Check if we're in the v4 or v6 space and use the appropriate file.
    if (lease_file4_) {
        MultiThreadingCriticalSection cs;
        lfcExecute(lease_file4_);
    } else if (lease_file6_) {
        MultiThreadingCriticalSection cs;
        lfcExecute(lease_file6_);
    }
}

void
Memfile_LeaseMgr::lfcSetup(bool conversion_needed) {
    std::string lfc_interval_str = "3600";
    try {
        lfc_interval_str = conn_.getParameter("lfc-interval");
    } catch (const std::exception&) {
        // Ignore and default to 3600.
    }

    uint32_t lfc_interval = 0;
    try {
        lfc_interval = boost::lexical_cast<uint32_t>(lfc_interval_str);
    } catch (const boost::bad_lexical_cast&) {
        isc_throw(isc::BadValue, "invalid value of the lfc-interval "
                  << lfc_interval_str << " specified");
    }

    if (lfc_interval > 0 || conversion_needed) {
        lfc_setup_.reset(new LFCSetup(std::bind(&Memfile_LeaseMgr::lfcCallback, this)));
        lfc_setup_->setup(lfc_interval, lease_file4_, lease_file6_, conversion_needed);
    }
}

template<typename LeaseFileType>
void
Memfile_LeaseMgr::lfcExecute(boost::shared_ptr<LeaseFileType>& lease_file) {
    bool do_lfc = true;

    // Check the status of the LFC instance.
    // If the finish file exists or the copy of the lease file exists it
    // is an indication that another LFC instance may be in progress or
    // may be stalled. In that case we don't want to rotate the current
    // lease file to avoid overriding the contents of the existing file.
    CSVFile lease_file_finish(appendSuffix(lease_file->getFilename(), FILE_FINISH));
    CSVFile lease_file_copy(appendSuffix(lease_file->getFilename(), FILE_INPUT));
    if (!lease_file_finish.exists() && !lease_file_copy.exists()) {
        // Close the current file so as we can move it to the copy file.
        lease_file->close();
        // Move the current file to the copy file. Remember the result
        // because we don't want to run LFC if the rename failed.
        do_lfc = (rename(lease_file->getFilename().c_str(),
                         lease_file_copy.getFilename().c_str()) == 0);

        if (!do_lfc) {
            LOG_ERROR(dhcpsrv_logger, DHCPSRV_MEMFILE_LFC_LEASE_FILE_RENAME_FAIL)
                .arg(lease_file->getFilename())
                .arg(lease_file_copy.getFilename())
                .arg(strerror(errno));
        }

        // Regardless if we successfully moved the current file or not,
        // we need to re-open the current file for the server to write
        // new lease updates. If the file has been successfully moved,
        // this will result in creation of the new file. Otherwise,
        // an existing file will be opened.
        try {
            lease_file->open(true);

        } catch (const CSVFileError& ex) {
            // If we're unable to open the lease file this is a serious
            // error because the server will not be able to persist
            // leases.
            /// @todo We need to better address this error. It should
            /// trigger an alarm (once we have a monitoring system in
            /// place) so as an administrator can correct it. In
            /// practice it should be very rare that this happens and
            /// is most likely related to a human error, e.g. changing
            /// file permissions.
            LOG_ERROR(dhcpsrv_logger, DHCPSRV_MEMFILE_LFC_LEASE_FILE_REOPEN_FAIL)
                .arg(lease_file->getFilename())
                .arg(ex.what());
            // Reset the pointer to the file so as the backend doesn't
            // try to write leases to disk.
            lease_file.reset();
            do_lfc = false;
        }
    }
    // Once the files have been rotated, or untouched if another LFC had
    // not finished, a new process is started.
    if (do_lfc) {
        lfc_setup_->execute();
    }
}

LeaseStatsQueryPtr
Memfile_LeaseMgr::startLeaseStatsQuery4() {
    LeaseStatsQueryPtr query(new MemfileLeaseStatsQuery4(storage4_));
    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        query->start();
    } else {
        query->start();
    }

    return(query);
}

LeaseStatsQueryPtr
Memfile_LeaseMgr::startPoolLeaseStatsQuery4() {
    LeaseStatsQueryPtr query(new MemfileLeaseStatsQuery4(storage4_, LeaseStatsQuery::ALL_SUBNET_POOLS));
    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        query->start();
    } else {
        query->start();
    }

    return(query);
}

LeaseStatsQueryPtr
Memfile_LeaseMgr::startSubnetLeaseStatsQuery4(const SubnetID& subnet_id) {
    LeaseStatsQueryPtr query(new MemfileLeaseStatsQuery4(storage4_, subnet_id));
    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        query->start();
    } else {
        query->start();
    }

    return(query);
}

LeaseStatsQueryPtr
Memfile_LeaseMgr::startSubnetRangeLeaseStatsQuery4(const SubnetID& first_subnet_id,
                                                   const SubnetID& last_subnet_id) {
    LeaseStatsQueryPtr query(new MemfileLeaseStatsQuery4(storage4_, first_subnet_id,
                                                         last_subnet_id));
    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        query->start();
    } else {
        query->start();
    }

    return(query);
}

LeaseStatsQueryPtr
Memfile_LeaseMgr::startLeaseStatsQuery6() {
    LeaseStatsQueryPtr query(new MemfileLeaseStatsQuery6(storage6_));
    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        query->start();
    } else {
        query->start();
    }

    return(query);
}

LeaseStatsQueryPtr
Memfile_LeaseMgr::startPoolLeaseStatsQuery6() {
    LeaseStatsQueryPtr query(new MemfileLeaseStatsQuery6(storage6_, LeaseStatsQuery::ALL_SUBNET_POOLS));
    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        query->start();
    } else {
        query->start();
    }

    return(query);
}

LeaseStatsQueryPtr
Memfile_LeaseMgr::startSubnetLeaseStatsQuery6(const SubnetID& subnet_id) {
    LeaseStatsQueryPtr query(new MemfileLeaseStatsQuery6(storage6_, subnet_id));
    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        query->start();
    } else {
        query->start();
    }

    return(query);
}

LeaseStatsQueryPtr
Memfile_LeaseMgr::startSubnetRangeLeaseStatsQuery6(const SubnetID& first_subnet_id,
                                                   const SubnetID& last_subnet_id) {
    LeaseStatsQueryPtr query(new MemfileLeaseStatsQuery6(storage6_, first_subnet_id,
                                                         last_subnet_id));
    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        query->start();
    } else {
        query->start();
    }

    return(query);
}

size_t
Memfile_LeaseMgr::wipeLeases4(const SubnetID& subnet_id) {
    LOG_INFO(dhcpsrv_logger, DHCPSRV_MEMFILE_WIPE_LEASES4)
        .arg(subnet_id);

    // Get the index by DUID, IAID, lease type.
    const Lease4StorageSubnetIdIndex& idx = storage4_.get<SubnetIdIndexTag>();

    // Try to get the lease using the DUID, IAID and lease type.
    std::pair<Lease4StorageSubnetIdIndex::const_iterator,
              Lease4StorageSubnetIdIndex::const_iterator> r =
        idx.equal_range(subnet_id);

    // Let's collect all leases.
    Lease4Collection leases;
    BOOST_FOREACH(auto const& lease, r) {
        leases.push_back(lease);
    }

    size_t num = leases.size();
    for (auto const& l : leases) {
        deleteLease(l);
    }
    LOG_INFO(dhcpsrv_logger, DHCPSRV_MEMFILE_WIPE_LEASES4_FINISHED)
        .arg(subnet_id).arg(num);

    return (num);
}

size_t
Memfile_LeaseMgr::wipeLeases6(const SubnetID& subnet_id) {
    LOG_INFO(dhcpsrv_logger, DHCPSRV_MEMFILE_WIPE_LEASES6)
        .arg(subnet_id);

    // Get the index by DUID, IAID, lease type.
    const Lease6StorageSubnetIdIndex& idx = storage6_.get<SubnetIdIndexTag>();

    // Try to get the lease using the DUID, IAID and lease type.
    std::pair<Lease6StorageSubnetIdIndex::const_iterator,
              Lease6StorageSubnetIdIndex::const_iterator> r =
        idx.equal_range(subnet_id);

    // Let's collect all leases.
    Lease6Collection leases;
    BOOST_FOREACH(auto const& lease, r) {
        leases.push_back(lease);
    }

    size_t num = leases.size();
    for (auto const& l : leases) {
        deleteLease(l);
    }
    LOG_INFO(dhcpsrv_logger, DHCPSRV_MEMFILE_WIPE_LEASES6_FINISHED)
        .arg(subnet_id).arg(num);

    return (num);
}

void
Memfile_LeaseMgr::recountClassLeases4() {
    class_lease_counter_.clear();
    for (auto const& lease : storage4_) {
        // Bump the appropriate accumulator
        if (lease->state_ == Lease::STATE_DEFAULT) {
            class_lease_counter_.addLease(lease);
        }
    }
}

void
Memfile_LeaseMgr::recountClassLeases6() {
    class_lease_counter_.clear();
    for (auto const& lease : storage6_) {
        // Bump the appropriate accumulator
        if (lease->state_ == Lease::STATE_DEFAULT) {
            class_lease_counter_.addLease(lease);
        }
    }
}

size_t
Memfile_LeaseMgr::getClassLeaseCount(const ClientClass& client_class,
                                     const Lease::Type& ltype /* = Lease::TYPE_V4*/) const {
    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        return(class_lease_counter_.getClassCount(client_class, ltype));
    } else {
        return(class_lease_counter_.getClassCount(client_class, ltype));
    }
}

void
Memfile_LeaseMgr::clearClassLeaseCounts() {
    return(class_lease_counter_.clear());
}

std::string
Memfile_LeaseMgr::checkLimits4(isc::data::ConstElementPtr const& user_context) const {
    if (!user_context) {
        return ("");
    }

    ConstElementPtr limits = user_context->find("ISC/limits");
    if (!limits) {
        return ("");
    }

    // Iterate of the 'client-classes' list in 'limits'. For each class that specifies
    // an "address-limit", check its value against the class's lease count.
    ConstElementPtr classes = limits->get("client-classes");
    if (classes) {
        for (int i = 0; i < classes->size(); ++i) {
            ConstElementPtr class_elem = classes->get(i);
            // Get class name.
            ConstElementPtr name_elem = class_elem->get("name");
            if (!name_elem) {
                isc_throw(BadValue, "checkLimits4 - client-class.name is missing: "
                          << prettyPrint(limits));
            }

            std::string name = name_elem->stringValue();

            // Now look for an address-limit
            size_t limit;
            if (!getLeaseLimit(class_elem, Lease::TYPE_V4, limit)) {
                // No limit, go to the next class.
                continue;
            }

            // If the limit is > 0 look up the class lease count.  Limit of 0 always
            // denies the lease.
            size_t lease_count = 0;
            if (limit) {
                lease_count = getClassLeaseCount(name);
            }

            // If we're over the limit, return the error, no need to evaluate any others.
            if (lease_count >= limit) {
                std::ostringstream ss;
                ss << "address limit " << limit << " for client class \""
                   << name << "\", current lease count " << lease_count;
                return (ss.str());
            }
        }
    }

    // If there were class limits we passed them, now look for a subnet limit.
    ConstElementPtr subnet_elem = limits->get("subnet");
    if (subnet_elem) {
        // Get the subnet id.
        ConstElementPtr id_elem = subnet_elem->get("id");
        if (!id_elem) {
            isc_throw(BadValue, "checkLimits4 - subnet.id is missing: "
                      << prettyPrint(limits));
        }

        SubnetID subnet_id = id_elem->intValue();

        // Now look for an address-limit.
        size_t limit;
        if (getLeaseLimit(subnet_elem, Lease::TYPE_V4, limit)) {
            // If the limit is > 0 look up the subnet lease count. Limit of 0 always
            // denies the lease.
            int64_t lease_count = 0;
            if (limit) {
                lease_count = getSubnetStat(subnet_id, "assigned-addresses");
            }

            // If we're over the limit, return the error.
            if (lease_count >= limit) {
                std::ostringstream ss;
                ss << "address limit " << limit << " for subnet ID " << subnet_id
                   << ", current lease count " << lease_count;
                return (ss.str());
            }
        }
    }

    // No limits exceeded!
    return ("");
}

std::string
Memfile_LeaseMgr::checkLimits6(isc::data::ConstElementPtr const& user_context) const {
    if (!user_context) {
        return ("");
    }

    ConstElementPtr limits = user_context->find("ISC/limits");
    if (!limits) {
        return ("");
    }

    // Iterate over the 'client-classes' list in 'limits'. For each class that specifies
    // limit (either "address-limit" or "prefix-limit", check its value against the appropriate
    // class lease count.
    ConstElementPtr classes = limits->get("client-classes");
    if (classes) {
        for (int i = 0; i < classes->size(); ++i) {
            ConstElementPtr class_elem = classes->get(i);
            // Get class name.
            ConstElementPtr name_elem = class_elem->get("name");
            if (!name_elem) {
                isc_throw(BadValue, "checkLimits6 - client-class.name is missing: "
                          << prettyPrint(limits));
            }

            std::string name = name_elem->stringValue();

            // Now look for either address-limit or a prefix=limit.
            size_t limit = 0;
            Lease::Type ltype = Lease::TYPE_NA;
            if (!getLeaseLimit(class_elem, ltype, limit)) {
                ltype = Lease::TYPE_PD;
                if (!getLeaseLimit(class_elem, ltype, limit)) {
                    // No limits for this class, skip to the next.
                    continue;
                }
            }

            // If the limit is > 0 look up the class lease count.  Limit of 0 always
            // denies the lease.
            size_t lease_count = 0;
            if (limit) {
                lease_count = getClassLeaseCount(name, ltype);
            }

            // If we're over the limit, return the error, no need to evaluate any others.
            if (lease_count >= limit) {
                std::ostringstream ss;
                ss << (ltype == Lease::TYPE_NA ? "address" : "prefix")
                   << " limit " << limit << " for client class \""
                   << name << "\", current lease count " << lease_count;
                return (ss.str());
            }
        }
    }

    // If there were class limits we passed them, now look for a subnet limit.
    ConstElementPtr subnet_elem = limits->get("subnet");
    if (subnet_elem) {
        // Get the subnet id.
        ConstElementPtr id_elem = subnet_elem->get("id");
        if (!id_elem) {
            isc_throw(BadValue, "checkLimits6 - subnet.id is missing: "
                      << prettyPrint(limits));
        }

        SubnetID subnet_id = id_elem->intValue();

        // Now look for either address-limit or a prefix=limit.
        size_t limit = 0;
        Lease::Type ltype = Lease::TYPE_NA;
        if (!getLeaseLimit(subnet_elem, ltype, limit)) {
            ltype = Lease::TYPE_PD;
            if (!getLeaseLimit(subnet_elem, ltype, limit)) {
                // No limits for the subnet so none exceeded!
                return ("");
            }
        }

        // If the limit is > 0 look up the class lease count.  Limit of 0 always
        // denies the lease.
        int64_t lease_count = 0;
        if (limit) {
            lease_count = getSubnetStat(subnet_id, (ltype == Lease::TYPE_NA ?
                                                    "assigned-nas" : "assigned-pds"));
        }

        // If we're over the limit, return the error.
        if (lease_count >= limit) {
            std::ostringstream ss;
            ss << (ltype == Lease::TYPE_NA ? "address" : "prefix")
               << " limit " << limit << " for subnet ID " << subnet_id
               << ", current lease count " << lease_count;
            return (ss.str());
        }
    }

    // No limits exceeded!
    return ("");
}

bool
Memfile_LeaseMgr::isJsonSupported() const {
    return true;
}

int64_t
Memfile_LeaseMgr::getSubnetStat(const SubnetID& subnet_id, const std::string& stat_label) const {
    /// @todo This could be simplified if StatsMgr provided a mechanism to
    /// return the most recent sample as an InterSample.
    std::string stat_name = StatsMgr::generateName("subnet", subnet_id, stat_label);
    ConstElementPtr stat = StatsMgr::instance().get(stat_name);
    ConstElementPtr samples = stat->get(stat_name);
    if (samples && samples->size()) {
        auto sample = samples->get(0);
        if (sample->size()) {
            auto count_elem = sample->get(0);
            return (count_elem->intValue());
        }
    }

    return (0);
}

bool
Memfile_LeaseMgr::getLeaseLimit(ConstElementPtr parent, Lease::Type ltype, size_t& limit) const {
    ConstElementPtr limit_elem = parent->get(ltype == Lease::TYPE_PD ?
                                             "prefix-limit" : "address-limit");
    if (limit_elem) {
        limit = limit_elem->intValue();
        return (true);
    }

    return (false);
}

namespace {

std::string
idToText(const OptionBuffer& id) {
    std::stringstream tmp;
    tmp << std::hex;
    bool delim = false;
    for (auto const& it : id) {
        if (delim) {
            tmp << ":";
        }
        tmp << std::setw(2) << std::setfill('0')
            << static_cast<unsigned int>(it);
        delim = true;
    }
    return (tmp.str());
}

} // anonymous namespace

Lease4Collection
Memfile_LeaseMgr::getLeases4ByRelayId(const OptionBuffer& relay_id,
                                      const IOAddress& lower_bound_address,
                                      const LeasePageSize& page_size,
                                      const time_t& qry_start_time /* = 0 */,
                                      const time_t& qry_end_time /* = 0 */) {
    LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
              DHCPSRV_MEMFILE_GET_RELAYID4)
        .arg(page_size.page_size_)
        .arg(lower_bound_address.toText())
        .arg(idToText(relay_id))
        .arg(qry_start_time)
        .arg(qry_end_time);

    // Expecting IPv4 address.
    if (!lower_bound_address.isV4()) {
        isc_throw(InvalidAddressFamily, "expected IPv4 address while "
                  "retrieving leases from the lease database, got "
                  << lower_bound_address);
    }

    // Catch 2038 bug with 32 bit time_t.
    if ((qry_start_time < 0) || (qry_end_time < 0)) {
        isc_throw(BadValue, "negative time value");
    }

    // Start time must be before end time.
    if ((qry_start_time > 0) && (qry_end_time > 0) &&
        (qry_start_time > qry_end_time)) {
        isc_throw(BadValue, "start time must be before end time");
    }

    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        return (getLeases4ByRelayIdInternal(relay_id,
                                            lower_bound_address,
                                            page_size,
                                            qry_start_time,
                                            qry_end_time));
    } else {
        return (getLeases4ByRelayIdInternal(relay_id,
                                            lower_bound_address,
                                            page_size,
                                            qry_start_time,
                                            qry_end_time));
    }
}

Lease4Collection
Memfile_LeaseMgr::getLeases4ByRelayIdInternal(const OptionBuffer& relay_id,
                                              const IOAddress& lower_bound_address,
                                              const LeasePageSize& page_size,
                                              const time_t& qry_start_time,
                                              const time_t& qry_end_time) {
    Lease4Collection collection;
    const Lease4StorageRelayIdIndex& idx = storage4_.get<RelayIdIndexTag>();
    Lease4StorageRelayIdIndex::const_iterator lb =
        idx.lower_bound(boost::make_tuple(relay_id, lower_bound_address));
    // Return all convenient leases being within the page size.
    IOAddress last_addr = lower_bound_address;
    for (; lb != idx.end(); ++lb) {
        if ((*lb)->addr_ == last_addr) {
            // Already seen: skip it.
            continue;
        }
        if ((*lb)->relay_id_ != relay_id) {
            // Gone after the relay id index.
            break;
        }
        last_addr = (*lb)->addr_;
        if ((qry_start_time > 0) && ((*lb)->cltt_ < qry_start_time)) {
            // Too old.
            continue;
        }
        if ((qry_end_time > 0) && ((*lb)->cltt_ > qry_end_time)) {
            // Too young.
            continue;
        }
        collection.push_back(Lease4Ptr(new Lease4(**lb)));
        if (collection.size() >= page_size.page_size_) {
            break;
        }
    }
    return (collection);
}

Lease4Collection
Memfile_LeaseMgr::getLeases4ByRemoteId(const OptionBuffer& remote_id,
                                       const IOAddress& lower_bound_address,
                                       const LeasePageSize& page_size,
                                       const time_t& qry_start_time /* = 0 */,
                                       const time_t& qry_end_time /* = 0 */) {
    LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
              DHCPSRV_MEMFILE_GET_REMOTEID4)
        .arg(page_size.page_size_)
        .arg(lower_bound_address.toText())
        .arg(idToText(remote_id))
        .arg(qry_start_time)
        .arg(qry_end_time);

    // Expecting IPv4 address.
    if (!lower_bound_address.isV4()) {
        isc_throw(InvalidAddressFamily, "expected IPv4 address while "
                  "retrieving leases from the lease database, got "
                  << lower_bound_address);
    }

    // Catch 2038 bug with 32 bit time_t.
    if ((qry_start_time < 0) || (qry_end_time < 0)) {
        isc_throw(BadValue, "negative time value");
    }

    // Start time must be before end time.
    if ((qry_start_time > 0) && (qry_end_time > 0) &&
        (qry_start_time > qry_end_time)) {
        isc_throw(BadValue, "start time must be before end time");
    }

    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        return (getLeases4ByRemoteIdInternal(remote_id,
                                             lower_bound_address,
                                             page_size,
                                             qry_start_time,
                                             qry_end_time));
    } else {
        return (getLeases4ByRemoteIdInternal(remote_id,
                                             lower_bound_address,
                                             page_size,
                                             qry_start_time,
                                             qry_end_time));
    }
}

Lease4Collection
Memfile_LeaseMgr::getLeases4ByRemoteIdInternal(const OptionBuffer& remote_id,
                                               const IOAddress& lower_bound_address,
                                               const LeasePageSize& page_size,
                                               const time_t& qry_start_time,
                                               const time_t& qry_end_time) {
    Lease4Collection collection;
    std::map<IOAddress, Lease4Ptr> sorted;
    const Lease4StorageRemoteIdIndex& idx = storage4_.get<RemoteIdIndexTag>();
    Lease4StorageRemoteIdRange er = idx.equal_range(remote_id);
    // Store all convenient leases being within the page size.
    BOOST_FOREACH(auto const& it, er) {
        const IOAddress& addr = it->addr_;
        if (addr <= lower_bound_address) {
            // Not greater than lower_bound_address.
            continue;
        }
        if ((qry_start_time > 0) && (it->cltt_ < qry_start_time)) {
            // Too old.
            continue;
        }
        if ((qry_end_time > 0) && (it->cltt_ > qry_end_time)) {
            // Too young.
            continue;
        }
        sorted[addr] = it;
    }

    // Return all leases being within the page size.
    for (auto const& it : sorted) {
        collection.push_back(Lease4Ptr(new Lease4(*it.second)));
        if (collection.size() >= page_size.page_size_) {
            break;
        }
    }
    return (collection);
}

void
Memfile_LeaseMgr::wipeExtendedInfoTables6() {
    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        relay_id6_.clear();
        remote_id6_.clear();
    } else {
        relay_id6_.clear();
        remote_id6_.clear();
    }
}

size_t
Memfile_LeaseMgr::byRelayId6size() const {
    return (relay_id6_.size());
}

size_t
Memfile_LeaseMgr::byRemoteId6size() const {
    return (remote_id6_.size());
}

Lease6Collection
Memfile_LeaseMgr::getLeases6ByRelayId(const DUID& relay_id,
                                      const IOAddress& lower_bound_address,
                                      const LeasePageSize& page_size) {
    LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
              DHCPSRV_MEMFILE_GET_RELAYID6)
        .arg(page_size.page_size_)
        .arg(lower_bound_address.toText())
        .arg(relay_id.toText());

    // Expecting IPv6 valid address.
    if (!lower_bound_address.isV6()) {
        isc_throw(InvalidAddressFamily, "expected IPv6 address while "
                  "retrieving leases from the lease database, got "
                  << lower_bound_address);
    }

    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        return (getLeases6ByRelayIdInternal(relay_id,
                                            lower_bound_address,
                                            page_size));
    } else {
        return (getLeases6ByRelayIdInternal(relay_id,
                                            lower_bound_address,
                                            page_size));
    }
}

Lease6Collection
Memfile_LeaseMgr::getLeases6ByRelayIdInternal(const DUID& relay_id,
                                              const IOAddress& lower_bound_address,
                                              const LeasePageSize& page_size) {
    const std::vector<uint8_t>& relay_id_data = relay_id.getDuid();
    Lease6Collection collection;
    const RelayIdIndex& idx = relay_id6_.get<RelayIdIndexTag>();
    RelayIdIndex::const_iterator lb =
        idx.lower_bound(boost::make_tuple(relay_id_data, lower_bound_address));

    // Return all leases being within the page size.
    IOAddress last_addr = lower_bound_address;
    for (; lb != idx.end(); ++lb) {
        if ((*lb)->lease_addr_ == last_addr) {
            // Already seen: skip it.
            continue;
        }
        if ((*lb)->id_ != relay_id_data) {
            // Gone after the relay id index.
            break;
        }
        last_addr = (*lb)->lease_addr_;
        Lease6Ptr lease = getAnyLease6Internal(last_addr);
        if (lease) {
            collection.push_back(lease);
            if (collection.size() >= page_size.page_size_) {
                break;
            }
        }
    }
    return (collection);
}

Lease6Collection
Memfile_LeaseMgr::getLeases6ByRemoteId(const OptionBuffer& remote_id,
                                       const IOAddress& lower_bound_address,
                                       const LeasePageSize& page_size) {
    LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE_DETAIL,
              DHCPSRV_MEMFILE_GET_REMOTEID6)
        .arg(page_size.page_size_)
        .arg(lower_bound_address.toText())
        .arg(idToText(remote_id));

    // Expecting IPv6 valid address.
    if (!lower_bound_address.isV6()) {
        isc_throw(InvalidAddressFamily, "expected IPv6 address while "
                  "retrieving leases from the lease database, got "
                  << lower_bound_address);
    }

    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        return (getLeases6ByRemoteIdInternal(remote_id,
                                             lower_bound_address,
                                             page_size));
    } else {
        return (getLeases6ByRemoteIdInternal(remote_id,
                                             lower_bound_address,
                                             page_size));
    }
}

Lease6Collection
Memfile_LeaseMgr::getLeases6ByRemoteIdInternal(const OptionBuffer& remote_id,
                                               const IOAddress& lower_bound_address,
                                               const LeasePageSize& page_size) {
    Lease6Collection collection;
    std::set<IOAddress> sorted;
    const RemoteIdIndex& idx = remote_id6_.get<RemoteIdIndexTag>();
    RemoteIdIndexRange er = idx.equal_range(remote_id);
    // Store all addresses greater than lower_bound_address.
    BOOST_FOREACH(auto const& it, er) {
        const IOAddress& addr = it->lease_addr_;
        if (addr <= lower_bound_address) {
            continue;
        }
        static_cast<void>(sorted.insert(addr));
    }

    // Return all leases being within the page size.
    for (const IOAddress& addr : sorted) {
        Lease6Ptr lease = getAnyLease6Internal(addr);
        if (lease) {
            collection.push_back(lease);
            if (collection.size() >= page_size.page_size_) {
                break;
            }
        }
    }
    return (collection);
}

size_t
Memfile_LeaseMgr::extractExtendedInfo4(bool update, bool current) {
    CfgConsistencyPtr cfg;
    if (current) {
        cfg = CfgMgr::instance().getCurrentCfg()->getConsistency();
    } else {
        cfg = CfgMgr::instance().getStagingCfg()->getConsistency();
    }
    if (!cfg) {
        isc_throw(Unexpected, "the " << (current ? "current" : "staging")
                  << " consistency configuration is null");
    }
    auto check = cfg->getExtendedInfoSanityCheck();

    LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE,
              DHCPSRV_MEMFILE_BEGIN_EXTRACT_EXTENDED_INFO4)
        .arg(CfgConsistency::sanityCheckToText(check))
        .arg(update ? " updating in file" : "");

    size_t leases = 0;
    size_t modified = 0;
    size_t updated = 0;
    size_t processed = 0;
    auto& index = storage4_.get<AddressIndexTag>();
    auto lease_it = index.begin();
    auto next_it = index.end();

    for (; lease_it != index.end(); lease_it = next_it) {
        next_it = std::next(lease_it);
        Lease4Ptr lease = *lease_it;
        ++leases;
        try {
            if (upgradeLease4ExtendedInfo(lease, check)) {
                ++modified;
                if (update && persistLeases(V4)) {
                    lease_file4_->append(*lease);
                    ++updated;
                }
            }
            // Work on a copy as the multi-index requires fields used
            // as indexes to be read-only.
            Lease4Ptr copy(new Lease4(*lease));
            extractLease4ExtendedInfo(copy, false);
            if (!copy->relay_id_.empty() || !copy->remote_id_.empty()) {
                index.replace(lease_it, copy);
                ++processed;
            }
        } catch (const std::exception& ex) {
            LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE,
                      DHCPSRV_MEMFILE_EXTRACT_EXTENDED_INFO4_ERROR)
                .arg(lease->addr_.toText())
                .arg(ex.what());
        }
    }

    LOG_INFO(dhcpsrv_logger, DHCPSRV_MEMFILE_EXTRACT_EXTENDED_INFO4)
        .arg(leases)
        .arg(modified)
        .arg(updated)
        .arg(processed);

    return (updated);
}

size_t
Memfile_LeaseMgr::upgradeExtendedInfo4(const LeasePageSize& /* page_size */) {
    return (0);
}

void
Memfile_LeaseMgr::buildExtendedInfoTables6() {
    CfgConsistencyPtr cfg = CfgMgr::instance().getStagingCfg()->getConsistency();
    if (!cfg) {
        isc_throw(Unexpected, "the staging consistency configuration is null");
    }
    auto check = cfg->getExtendedInfoSanityCheck();
    bool enabled = getExtendedInfoTablesEnabled();

    LOG_DEBUG(dhcpsrv_logger, DHCPSRV_DBG_TRACE,
              DHCPSRV_MEMFILE_BEGIN_BUILD_EXTENDED_INFO_TABLES6)
        .arg(CfgConsistency::sanityCheckToText(check))
        .arg(enabled ? "enabled" : "disabled");

    // Clear tables when enabled.
    if (enabled) {
        relay_id6_.clear();
        remote_id6_.clear();
    }

    size_t leases = 0;
    size_t modified = 0;
    size_t processed = 0;

    for (auto const& lease : storage6_) {
        ++leases;
        try {
            if (upgradeLease6ExtendedInfo(lease, check)) {
                ++modified;
            }
            if (enabled && addExtendedInfo6(lease)) {
                ++processed;
            }
        } catch (const std::exception& ex) {
            LOG_ERROR(dhcpsrv_logger,
                      DHCPSRV_MEMFILE_BUILD_EXTENDED_INFO_TABLES6_ERROR)
                .arg(lease->addr_.toText())
                .arg(ex.what());
        }
    }

    LOG_INFO(dhcpsrv_logger, DHCPSRV_MEMFILE_BUILD_EXTENDED_INFO_TABLES6)
        .arg(leases)
        .arg(modified)
        .arg(processed);
}

size_t
Memfile_LeaseMgr::upgradeExtendedInfo6(const LeasePageSize& /* page_size */) {
    return (0);
}

void
Memfile_LeaseMgr::deleteExtendedInfo6(const IOAddress& addr) {
    LeaseAddressRelayIdIndex& relay_id_idx =
        relay_id6_.get<LeaseAddressIndexTag>();
    static_cast<void>(relay_id_idx.erase(addr));
    LeaseAddressRemoteIdIndex& remote_id_idx =
        remote_id6_.get<LeaseAddressIndexTag>();
    static_cast<void>(remote_id_idx.erase(addr));
}

void
Memfile_LeaseMgr::addRelayId6(const IOAddress& lease_addr,
                              const std::vector<uint8_t>& relay_id) {
    Lease6ExtendedInfoPtr ex_info;
    ex_info.reset(new Lease6ExtendedInfo(lease_addr, relay_id));
    relay_id6_.insert(ex_info);
}

void
Memfile_LeaseMgr::addRemoteId6(const IOAddress& lease_addr,
                               const std::vector<uint8_t>& remote_id) {
    Lease6ExtendedInfoPtr ex_info;
    ex_info.reset(new Lease6ExtendedInfo(lease_addr, remote_id));
    remote_id6_.insert(ex_info);
}

void
Memfile_LeaseMgr::writeLeases4(const std::string& filename) {
    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        writeLeases4Internal(filename);
    } else {
        writeLeases4Internal(filename);
    }
}

void
Memfile_LeaseMgr::writeLeases4Internal(const std::string& filename) {
    bool overwrite = (lease_file4_ && lease_file4_->getFilename() == filename);
    try {
        if (overwrite) {
            lease_file4_->close();
        }
        std::ostringstream old;
        old << filename << ".bak" << getpid();
        ::rename(filename.c_str(), old.str().c_str());
        CSVLeaseFile4 backup(filename);
        backup.open();
        for (auto const& lease : storage4_) {
            backup.append(*lease);
        }
        backup.close();
        if (overwrite) {
            lease_file4_->open(true);
        }
    } catch (const std::exception&) {
        if (overwrite) {
            lease_file4_->open(true);
        }
        throw;
    }
}

void
Memfile_LeaseMgr::writeLeases6(const std::string& filename) {
    if (MultiThreadingMgr::instance().getMode()) {
        std::lock_guard<std::mutex> lock(*mutex_);
        writeLeases6Internal(filename);
    } else {
        writeLeases6Internal(filename);
    }
}

void
Memfile_LeaseMgr::writeLeases6Internal(const std::string& filename) {
    bool overwrite = (lease_file6_ && lease_file6_->getFilename() == filename);
    try {
        if (overwrite) {
            lease_file6_->close();
        }
        std::ostringstream old;
        old << filename << ".bak" << getpid();
        ::rename(filename.c_str(), old.str().c_str());
        CSVLeaseFile6 backup(filename);
        backup.open();
        for (auto const& lease : storage6_) {
            backup.append(*lease);
        }
        backup.close();
        if (overwrite) {
            lease_file6_->open(true);
        }
    } catch (const std::exception&) {
        if (overwrite) {
            lease_file6_->open(true);
        }
        throw;
    }
}

TrackingLeaseMgrPtr
Memfile_LeaseMgr::factory(const isc::db::DatabaseConnection::ParameterMap& parameters) {
    LOG_INFO(dhcpsrv_logger, DHCPSRV_MEMFILE_DB)
        .arg(DatabaseConnection::redactedAccessString(parameters));
    return (TrackingLeaseMgrPtr(new Memfile_LeaseMgr(parameters)));
}

}  // namespace dhcp
}  // namespace isc