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 | // 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/io_address.h>
#include <cc/command_interpreter.h>
#include <config/command_mgr.h>
#include <config/timeouts.h>
#include <config/unix_command_mgr.h>
#include <dhcp/libdhcp++.h>
#include <dhcp/testutils/iface_mgr_test_config.h>
#include <dhcpsrv/cfgmgr.h>
#include <dhcpsrv/host_mgr.h>
#include <dhcpsrv/lease.h>
#include <dhcpsrv/lease_mgr_factory.h>
#include <dhcp6/ctrl_dhcp6_srv.h>
#include <dhcp6/tests/dhcp6_test_utils.h>
#include <hooks/hooks_manager.h>
#include <log/logger_support.h>
#include <stats/stats_mgr.h>
#include <util/multi_threading_mgr.h>
#include <util/chrono_time_utils.h>
#include <testutils/io_utils.h>
#include <testutils/unix_control_client.h>
#include <testutils/sandbox.h>
#include "marker_file.h"
#include "test_libraries.h"
#include <boost/scoped_ptr.hpp><--- Include file: not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <gtest/gtest.h><--- Include file: not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <fstream><--- Include file: not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <iomanip><--- 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.
#include <thread><--- Include file: not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <sys/select.h><--- Include file: not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <sys/stat.h><--- Include file: not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <sys/ioctl.h><--- Include file: not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <cstdlib><--- Include file: not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <unistd.h><--- Include file: not found. Please note: Cppcheck does not need standard library headers to get proper results.
using namespace std;
using namespace isc;
using namespace isc::asiolink;
using namespace isc::config;
using namespace isc::data;
using namespace isc::dhcp;
using namespace isc::dhcp::test;
using namespace isc::hooks;
using namespace isc::stats;
using namespace isc::test;
using namespace isc::util;
namespace ph = std::placeholders;
namespace {
/// @brief Simple RAII class which stops IO service upon destruction
/// of the object.
class IOServiceWork {
public:
/// @brief Constructor.
///
/// @param io_service Pointer to the IO service to be stopped.
explicit IOServiceWork(const IOServicePtr& io_service)
: io_service_(io_service) {
}
/// @brief Destructor.
///
/// Stops IO service.
~IOServiceWork() {
io_service_->stop();
}
private:
/// @brief Pointer to the IO service to be stopped upon destruction.
IOServicePtr io_service_;
};
class NakedControlledDhcpv6Srv: public ControlledDhcpv6Srv {
// "Naked" DHCPv6 server, exposes internal fields
public:
NakedControlledDhcpv6Srv() : ControlledDhcpv6Srv(DHCP6_SERVER_PORT + 10000) {
CfgMgr::instance().setFamily(AF_INET6);
}
/// Expose internal methods for the sake of testing
using Dhcpv6Srv::receivePacket;
using Dhcpv6Srv::network_state_;
};
/// @brief Default control connection timeout.
const size_t DEFAULT_CONNECTION_TIMEOUT = 10000;
class CtrlDhcpv6SrvTest : public BaseServerTest {
public:
CtrlDhcpv6SrvTest()
: BaseServerTest() {
reset();
}
virtual ~CtrlDhcpv6SrvTest() {
LeaseMgrFactory::destroy();
StatsMgr::instance().removeAll();
CommandMgr::instance().deregisterAll();
UnixCommandMgr::instance().setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT);
reset();
}
/// @brief Reset hooks data
///
/// Resets the data for the hooks-related portion of the test by ensuring
/// that no libraries are loaded and that any marker files are deleted.
virtual void reset() {
// Unload any previously-loaded libraries.
EXPECT_TRUE(HooksManager::unloadLibraries());
// Get rid of any marker files.
static_cast<void>(remove(LOAD_MARKER_FILE));
static_cast<void>(remove(UNLOAD_MARKER_FILE));
IfaceMgr::instance().deleteAllExternalSockets();
CfgMgr::instance().clear();
}
};
class CtrlChannelDhcpv6SrvTest : public CtrlDhcpv6SrvTest {
public:
isc::test::Sandbox sandbox;
/// @brief Path to the UNIX socket being used to communicate with the server
std::string socket_path_;
/// @brief List of interfaces (defaults to "*").
std::string interfaces_;
/// @brief Pointer to the tested server object
boost::shared_ptr<NakedControlledDhcpv6Srv> server_;
/// @brief Default constructor
///
/// Sets socket path to its default value.
CtrlChannelDhcpv6SrvTest() : interfaces_("\"*\"") {
const char* env = getenv("KEA_SOCKET_TEST_DIR");
if (env) {
socket_path_ = string(env) + "/kea6.sock";
} else {
socket_path_ = sandbox.join("/kea6.sock");
}
reset();
IfaceMgr::instance().setTestMode(false);
IfaceMgr::instance().setDetectCallback(std::bind(&IfaceMgr::checkDetectIfaces,
IfaceMgr::instancePtr().get(), ph::_1));
}
/// @brief Destructor
~CtrlChannelDhcpv6SrvTest() {
LeaseMgrFactory::destroy();
StatsMgr::instance().removeAll();
CommandMgr::instance().deregisterAll();
UnixCommandMgr::instance().setConnectionTimeout(TIMEOUT_DHCP_SERVER_RECEIVE_COMMAND);
server_.reset();
reset();
IfaceMgr::instance().setTestMode(false);
IfaceMgr::instance().setDetectCallback(std::bind(&IfaceMgr::checkDetectIfaces,
IfaceMgr::instancePtr().get(), ph::_1));
IfaceMgr::instance().clearIfaces();
IfaceMgr::instance().closeSockets();
IfaceMgr::instance().detectIfaces();
}
/// @brief Returns pointer to the server's IO service.
///
/// @return Pointer to the server's IO service or null pointer if the server
/// hasn't been created.
IOServicePtr getIOService() {
return (server_ ? server_->getIOService() : IOServicePtr());
}
void createUnixChannelServer() {
static_cast<void>(::remove(socket_path_.c_str()));
// Just a simple config. The important part here is the socket
// location information.
std::string header =
"{"
" \"interfaces-config\": {"
" \"interfaces\": [";
std::string body = "]"
" },"
" \"expired-leases-processing\": {"
" \"reclaim-timer-wait-time\": 60,"
" \"hold-reclaimed-time\": 500,"
" \"flush-reclaimed-timer-wait-time\": 60"
" },"
" \"rebind-timer\": 2000, "
" \"renew-timer\": 1000, "
" \"subnet6\": [ ],"
" \"valid-lifetime\": 4000,"
" \"control-socket\": {"
" \"socket-type\": \"unix\","
" \"socket-name\": \"";
std::string footer =
"\" },"
" \"lease-database\": {"
" \"type\": \"memfile\", \"persist\": false },"
" \"loggers\": [ {"
" \"name\": \"kea-dhcp6\","
" \"severity\": \"INFO\","
" \"debuglevel\": 0"
" } ]"
"}";
// Fill in the socket-name value with socket_path_ to
// make the actual configuration text.
std::string config_txt = header + interfaces_ + body + socket_path_ + footer;
ASSERT_NO_THROW(server_.reset(new NakedControlledDhcpv6Srv()));
ConstElementPtr config;
ASSERT_NO_THROW(config = parseDHCP6(config_txt));
// Parse the logger configuration explicitly into the staging config.
// Note this does not alter the current loggers, they remain in
// effect until we apply the logging config below. If no logging
// is supplied logging will revert to default logging.
server_->configureLogger(config, CfgMgr::instance().getStagingCfg());
// Let's apply the new logging. We do it early, so we'll be able to print
// out what exactly is wrong with the new config in case of problems.
CfgMgr::instance().getStagingCfg()->applyLoggingCfg();
ConstElementPtr answer = server_->processConfig(config);
// Commit the configuration so any subsequent reconfigurations
// will only close the command channel if its configuration has
// changed.
CfgMgr::instance().commit();
ASSERT_TRUE(answer);
int status = 0;
ConstElementPtr txt = isc::config::parseAnswer(status, answer);
// This should succeed. If not, print the error message.
ASSERT_EQ(0, status) << txt->str();
// Now check that the socket was indeed open.
ASSERT_GT(isc::config::UnixCommandMgr::instance().getControlSocketFD(), -1);
}
/// @brief Reset
void reset() override {
CtrlDhcpv6SrvTest::reset();
// Remove unix socket file
static_cast<void>(::remove(socket_path_.c_str()));
}
/// @brief Conducts a command/response exchange via UnixCommandSocket
///
/// This method connects to the given server over the given socket path.
/// If successful, it then sends the given command and retrieves the
/// server's response. Note that it polls the server's I/O service
/// where needed to cause the server to process IO events on
/// the control channel sockets.
///
/// @param command the command text to execute in JSON form
/// @param response variable into which the received response should be
/// placed.
void sendUnixCommand(const std::string& command, std::string& response) {
response = "";
boost::scoped_ptr<UnixControlClient> client;
client.reset(new UnixControlClient());
ASSERT_TRUE(client);
// Connect to the server. This is expected to trigger server's acceptor
// handler when IOService::poll() is run.
ASSERT_TRUE(client->connectToServer(socket_path_));
ASSERT_NO_THROW(getIOService()->poll());
// Send the command. This will trigger server's handler which receives
// data over the unix domain socket. The server will start sending
// response to the client.
ASSERT_TRUE(client->sendCommand(command));
ASSERT_NO_THROW(getIOService()->poll());
// Read the response generated by the server. Note that getResponse
// only fails if there an IO error or no response data was present.
// It is not based on the response content.
ASSERT_TRUE(client->getResponse(response));
// Now disconnect and process the close event
client->disconnectFromServer();
ASSERT_NO_THROW(getIOService()->poll());
}
/// @brief Checks response for list-commands
///
/// This method checks if the list-commands response is generally sane
/// and whether specified command is mentioned in the response.
///
/// @param rsp response sent back by the server
/// @param command command expected to be on the list.
void checkListCommands(const ConstElementPtr& rsp, const std::string& command) {
ConstElementPtr params;
int status_code = -1;
EXPECT_NO_THROW(params = parseAnswer(status_code, rsp));
EXPECT_EQ(CONTROL_RESULT_SUCCESS, status_code);
ASSERT_TRUE(params);
ASSERT_EQ(Element::list, params->getType());
int cnt = 0;
for (size_t i = 0; i < params->size(); ++i) {
string tmp = params->get(i)->stringValue();
if (tmp == command) {
// Command found, but that's not enough. Need to continue working
// through the list to see if there are no duplicates.
cnt++;
}
}
// Exactly one command on the list is expected.
EXPECT_EQ(1, cnt) << "Command " << command << " not found";
}
/// @brief Check if the answer for config-write command is correct.
///
/// @param response_txt response in text form (as read from
/// the control socket)
/// @param exp_status expected status (0 success, 1 failure)
/// @param exp_txt for success cases this defines the expected filename,
/// for failure cases this defines the expected error message.
void checkConfigWrite(const std::string& response_txt, int exp_status,
const std::string& exp_txt = "") {
ConstElementPtr rsp;
EXPECT_NO_THROW(rsp = Element::fromJSON(response_txt));
ASSERT_TRUE(rsp);
int status;
ConstElementPtr params = parseAnswer(status, rsp);
EXPECT_EQ(exp_status, status);
if (exp_status == CONTROL_RESULT_SUCCESS) {
// Let's check couple things...
// The parameters must include filename
ASSERT_TRUE(params);
ASSERT_TRUE(params->get("filename"));
ASSERT_EQ(Element::string, params->get("filename")->getType());
EXPECT_EQ(exp_txt, params->get("filename")->stringValue());
// The parameters must include size. And the size
// must indicate some content.
ASSERT_TRUE(params->get("size"));
ASSERT_EQ(Element::integer, params->get("size")->getType());
int64_t size = params->get("size")->intValue();
EXPECT_LE(1, size);
// Now check if the file is really there and suitable for
// opening.
ifstream f(exp_txt, ios::binary | ios::ate);
ASSERT_TRUE(f.good());
// Now check that it is the correct size as reported.
EXPECT_EQ(size, static_cast<int64_t>(f.tellg()));
// Finally, check that it's really a JSON.
ElementPtr from_file = Element::fromJSONFile(exp_txt);
ASSERT_TRUE(from_file);
} else if (exp_status == CONTROL_RESULT_ERROR) {
// Let's check if the reason for failure was given.
ConstElementPtr text = rsp->get("text");
ASSERT_TRUE(text);
ASSERT_EQ(Element::string, text->getType());
EXPECT_EQ(exp_txt, text->stringValue());
} else {
ADD_FAILURE() << "Invalid expected status: " << exp_status;
}
}
/// @brief Handler for long command.
///
/// It checks whether the received command is equal to the one specified
/// as an argument.
///
/// @param expected_command String representing an expected command.
/// @param command_name Command name received by the handler.
/// @param arguments Command arguments received by the handler.
///
/// @returns Success answer.
static ConstElementPtr
longCommandHandler(const std::string& expected_command,
const std::string& command_name,
const ConstElementPtr& arguments) {
// The handler is called with a command name and the structure holding
// command arguments. We have to rebuild the command from those
// two arguments so as it can be compared against expected_command.
ElementPtr entire_command = Element::createMap();
entire_command->set("command", Element::create(command_name));
entire_command->set("arguments", (arguments));
// The rebuilt command will have a different order of parameters so
// let's parse expected_command back to JSON to guarantee that
// both structures are built using the same order.
EXPECT_EQ(Element::fromJSON(expected_command)->str(),
entire_command->str());
return (createAnswer(CONTROL_RESULT_SUCCESS, "long command received ok"));
}
/// @brief Command handler which generates long response
///
/// This handler generates a large response (over 400kB). It includes
/// a list of randomly generated strings to make sure that the test
/// can catch out of order delivery.
static ConstElementPtr longResponseHandler(const std::string&,
const ConstElementPtr&) {
ElementPtr arguments = Element::createList();
for (unsigned i = 0; i < 80000; ++i) {
std::ostringstream s;
s << std::setw(5) << i;
arguments->add(Element::create(s.str()));
}
return (createAnswer(CONTROL_RESULT_SUCCESS, arguments));
}
};
TEST_F(CtrlDhcpv6SrvTest, commands) {
boost::scoped_ptr<ControlledDhcpv6Srv> srv;
ASSERT_NO_THROW(
srv.reset(new ControlledDhcpv6Srv(DHCP6_SERVER_PORT + 10000))
);
// Use empty parameters list
ElementPtr params(new isc::data::MapElement());
int rcode = -1;
// Case 1: send bogus command
ConstElementPtr result = CommandMgr::instance().processCommand(createCommand("blah", params));
ConstElementPtr comment = parseAnswer(rcode, result);
EXPECT_EQ(2, rcode); // expect failure (no such command as blah)
// Case 2: send shutdown command without any parameters
result = CommandMgr::instance().processCommand(createCommand("shutdown", params));
comment = parseAnswer(rcode, result);
EXPECT_EQ(0, rcode); // expect success
// Exit value should default to 0.
EXPECT_EQ(0, srv->getExitValue());
// Case 3: send shutdown command with exit-value parameter.
ConstElementPtr x(new isc::data::IntElement(77));
params->set("exit-value", x);
result = CommandMgr::instance().processCommand(createCommand("shutdown", params));
comment = parseAnswer(rcode, result);
EXPECT_EQ(0, rcode); // expect success
// Exit value should match.
EXPECT_EQ(77, srv->getExitValue());
}
// This test checks which commands are registered by the DHCPv6 server.
TEST_F(CtrlDhcpv6SrvTest, commandsRegistration) {
ConstElementPtr list_cmds = createCommand("list-commands");
ConstElementPtr answer;
// By default the list should be empty (except the standard list-commands
// supported by the CommandMgr itself)
EXPECT_NO_THROW(answer = CommandMgr::instance().processCommand(list_cmds));
ASSERT_TRUE(answer);
ASSERT_TRUE(answer->get("arguments"));
EXPECT_EQ("[ \"list-commands\" ]", answer->get("arguments")->str());
// Created server should register several additional commands.
boost::scoped_ptr<ControlledDhcpv6Srv> srv;
ASSERT_NO_THROW(<--- There is an unknown macro here somewhere. Configuration is required. If ASSERT_NO_THROW is a macro then please configure it.
srv.reset(new ControlledDhcpv6Srv(0));
);
EXPECT_NO_THROW(answer = CommandMgr::instance().processCommand(list_cmds));
ASSERT_TRUE(answer);
ASSERT_TRUE(answer->get("arguments"));
std::string command_list = answer->get("arguments")->str();
EXPECT_TRUE(command_list.find("\"list-commands\"") != string::npos);
EXPECT_TRUE(command_list.find("\"build-report\"") != string::npos);
EXPECT_TRUE(command_list.find("\"config-backend-pull\"") != string::npos);
EXPECT_TRUE(command_list.find("\"config-get\"") != string::npos);
EXPECT_TRUE(command_list.find("\"config-hash-get\"") != string::npos);
EXPECT_TRUE(command_list.find("\"config-set\"") != string::npos);
EXPECT_TRUE(command_list.find("\"config-write\"") != string::npos);
EXPECT_TRUE(command_list.find("\"leases-reclaim\"") != string::npos);
EXPECT_TRUE(command_list.find("\"subnet6-select-test\"") != string::npos);
EXPECT_TRUE(command_list.find("\"server-tag-get\"") != string::npos);
EXPECT_TRUE(command_list.find("\"shutdown\"") != string::npos);
EXPECT_TRUE(command_list.find("\"statistic-get\"") != string::npos);
EXPECT_TRUE(command_list.find("\"statistic-get-all\"") != string::npos);
EXPECT_TRUE(command_list.find("\"statistic-remove\"") != string::npos);
EXPECT_TRUE(command_list.find("\"statistic-remove-all\"") != string::npos);
EXPECT_TRUE(command_list.find("\"statistic-reset\"") != string::npos);
EXPECT_TRUE(command_list.find("\"statistic-reset-all\"") != string::npos);
EXPECT_TRUE(command_list.find("\"statistic-sample-age-set\"") != string::npos);
EXPECT_TRUE(command_list.find("\"statistic-sample-age-set-all\"") != string::npos);
EXPECT_TRUE(command_list.find("\"statistic-sample-count-set\"") != string::npos);
EXPECT_TRUE(command_list.find("\"statistic-sample-count-set-all\"") != string::npos);
EXPECT_TRUE(command_list.find("\"status-get\"") != string::npos);
EXPECT_TRUE(command_list.find("\"version-get\"") != string::npos);
// Ok, and now delete the server. It should deregister its commands.
srv.reset();
// The list should be (almost) empty again.
EXPECT_NO_THROW(answer = CommandMgr::instance().processCommand(list_cmds));
ASSERT_TRUE(answer);
ASSERT_TRUE(answer->get("arguments"));
EXPECT_EQ("[ \"list-commands\" ]", answer->get("arguments")->str());
}
// Tests that the server properly responds to invalid commands sent
// via ControlChannel
TEST_F(CtrlChannelDhcpv6SrvTest, controlChannelNegative) {
createUnixChannelServer();
std::string response;
sendUnixCommand("{ \"command\": \"bogus\" }", response);
EXPECT_EQ("{ \"result\": 2,"
" \"text\": \"'bogus' command not supported.\" }", response);
sendUnixCommand("utter nonsense", response);
EXPECT_EQ("{ \"result\": 1, "
"\"text\": \"invalid first character u\" }",
response);
}
// Tests that the server properly responds to shutdown command sent
// via ControlChannel
TEST_F(CtrlChannelDhcpv6SrvTest, controlChannelShutdown) {
createUnixChannelServer();
std::string response;
sendUnixCommand("{ \"command\": \"shutdown\" }", response);
EXPECT_EQ("{ \"result\": 0, \"text\": \"Shutting down.\" }", response);
}
// Tests that the server properly responds to statistics commands. Note this
// is really only intended to verify that the appropriate Statistics handler
// is called based on the command. It is not intended to be an exhaustive
// test of Dhcpv6 statistics.
TEST_F(CtrlChannelDhcpv6SrvTest, controlChannelStats) {
createUnixChannelServer();
std::string response;
// Check statistic-get
sendUnixCommand("{ \"command\" : \"statistic-get\", "
" \"arguments\": {"
" \"name\":\"bogus\" }}", response);
EXPECT_EQ("{ \"arguments\": { }, \"result\": 0 }", response);
// Check statistic-get-all
sendUnixCommand("{ \"command\" : \"statistic-get-all\", "
" \"arguments\": {}}", response);
std::set<std::string> initial_stats = {
"pkt6-received",
"pkt6-solicit-received",
"pkt6-advertise-received",
"pkt6-request-received",
"pkt6-reply-received",
"pkt6-renew-received",
"pkt6-rebind-received",
"pkt6-decline-received",
"pkt6-release-received",
"pkt6-infrequest-received",
"pkt6-dhcpv4-query-received",
"pkt6-dhcpv4-response-received",
"pkt6-unknown-received",
"pkt6-sent",
"pkt6-advertise-sent",
"pkt6-reply-sent",
"pkt6-dhcpv4-response-sent",
"pkt6-parse-failed",
"pkt6-receive-drop",
"v6-allocation-fail",
"v6-allocation-fail-shared-network",
"v6-allocation-fail-subnet",
"v6-allocation-fail-no-pools",
"v6-allocation-fail-classes",
"v6-ia-na-lease-reuses",
"v6-ia-pd-lease-reuses",
};
std::ostringstream s;
s << "{ \"arguments\": { ";
bool first = true;
for (auto const& st : initial_stats) {
if (!first) {
s << ", ";
} else {
first = false;
}
s << "\"" << st << "\": [ [ 0, \"";
s << isc::util::clockToText(StatsMgr::instance().getObservation(st)->getInteger().second);
s << "\" ] ]";
}
s << " }, \"result\": 0 }";
auto stats_get_all = s.str();
EXPECT_EQ(stats_get_all, response);
// Check statistic-reset
sendUnixCommand("{ \"command\" : \"statistic-reset\", "
" \"arguments\": {"
" \"name\":\"bogus\" }}", response);
EXPECT_EQ("{ \"result\": 1, \"text\": \"No 'bogus' statistic found\" }",
response);
// Check statistic-reset-all
sendUnixCommand("{ \"command\" : \"statistic-reset-all\", "
" \"arguments\": {}}", response);
EXPECT_EQ("{ \"result\": 0, \"text\": "
"\"All statistics reset to neutral values.\" }", response);
// Check statistic-remove
sendUnixCommand("{ \"command\" : \"statistic-remove\", "
" \"arguments\": {"
" \"name\":\"bogus\" }}", response);
EXPECT_EQ("{ \"result\": 1, \"text\": \"No 'bogus' statistic found\" }",
response);
// Check statistic-remove-all (deprecated)
// Check statistic-sample-age-set
sendUnixCommand("{ \"command\" : \"statistic-sample-age-set\", "
" \"arguments\": {"
" \"name\":\"bogus\", \"duration\": 1245 }}", response);
EXPECT_EQ("{ \"result\": 1, \"text\": \"No 'bogus' statistic found\" }",
response);
// Check statistic-sample-age-set-all
sendUnixCommand("{ \"command\" : \"statistic-sample-age-set-all\", "
" \"arguments\": {"
" \"duration\": 1245 }}", response);
EXPECT_EQ("{ \"result\": 0, \"text\": \"All statistics duration limit are set.\" }",
response);
// Check statistic-sample-count-set
sendUnixCommand("{ \"command\" : \"statistic-sample-count-set\", "
" \"arguments\": {"
" \"name\":\"bogus\", \"max-samples\": 100 }}", response);
EXPECT_EQ("{ \"result\": 1, \"text\": \"No 'bogus' statistic found\" }",
response);
// Check statistic-sample-count-set-all
sendUnixCommand("{ \"command\" : \"statistic-sample-count-set-all\", "
" \"arguments\": {"
" \"max-samples\": 100 }}", response);
EXPECT_EQ("{ \"result\": 0, \"text\": \"All statistics count limit are set.\" }",
response);
}
// Check that the "config-set" command will replace current configuration
TEST_F(CtrlChannelDhcpv6SrvTest, configSet) {
createUnixChannelServer();
// Define strings to permutate the config arguments
// (Note the line feeds makes errors easy to find)
string set_config_txt = "{ \"command\": \"config-set\" \n";
string args_txt = " \"arguments\": { \n";
string dhcp6_cfg_txt =
" \"Dhcp6\": { \n"
" \"interfaces-config\": { \n"
" \"interfaces\": [\"*\"] \n"
" }, \n"
" \"preferred-lifetime\": 3000, \n"
" \"valid-lifetime\": 4000, \n"
" \"renew-timer\": 1000, \n"
" \"rebind-timer\": 2000, \n"
" \"lease-database\": { \n"
" \"type\": \"memfile\", \n"
" \"persist\":false, \n"
" \"lfc-interval\": 0 \n"
" }, \n"
" \"expired-leases-processing\": { \n"
" \"reclaim-timer-wait-time\": 0, \n"
" \"hold-reclaimed-time\": 0, \n"
" \"flush-reclaimed-timer-wait-time\": 0 \n"
" },"
" \"subnet6\": [ \n";
string subnet1 =
" {\"subnet\": \"3002::/64\", \"id\": 1, \n"
" \"pools\": [{ \"pool\": \"3002::100-3002::200\" }]}\n";
string subnet2 =
" {\"subnet\": \"3003::/64\", \"id\": 2, \n"
" \"pools\": [{ \"pool\": \"3003::100-3003::200\" }]}\n";
string bad_subnet =
" {\"comment\": \"3005::/64\", \"id\": 10, \n"
" \"pools\": [{ \"pool\": \"3005::100-3005::200\" }]}\n";
string subnet_footer =
" ] \n";
string option_def =
" ,\"option-def\": [\n"
" {\n"
" \"name\": \"foo\",\n"
" \"code\": 163,\n"
" \"type\": \"uint32\",\n"
" \"array\": false,\n"
" \"record-types\": \"\",\n"
" \"space\": \"dhcp6\",\n"
" \"encapsulate\": \"\"\n"
" }\n"
"]\n";
string option_data =
" ,\"option-data\": [\n"
" {\n"
" \"name\": \"foo\",\n"
" \"code\": 163,\n"
" \"space\": \"dhcp6\",\n"
" \"csv-format\": true,\n"
" \"data\": \"12345\"\n"
" }\n"
"]\n";
string control_socket_header =
" ,\"control-socket\": { \n"
" \"socket-type\": \"unix\", \n"
" \"socket-name\": \"";
string control_socket_footer =
"\" \n} \n";
string logger_txt =
" ,\"loggers\": [ { \n"
" \"name\": \"kea\", \n"
" \"severity\": \"FATAL\", \n"
" \"output-options\": [{ \n"
" \"output\": \"/dev/null\", \n"
" \"maxsize\": 0"
" }] \n"
" }] \n";
std::ostringstream os;
// Create a valid config with all the parts should parse
os << set_config_txt << ","
<< args_txt
<< dhcp6_cfg_txt
<< subnet1
<< subnet_footer
<< option_def
<< option_data
<< control_socket_header
<< socket_path_
<< control_socket_footer
<< logger_txt
<< "}\n" // close dhcp6
<< "}}";
// Send the config-set command
std::string response;
sendUnixCommand(os.str(), response);
// Verify the configuration was successful. The config contains random
// socket name (/tmp/kea-<value-changing-each-time>/kea6.sock), so the
// hash will be different each time. As such, we can do simplified checks:
// - verify the "result": 0 is there
// - verify the "text": "Configuration successful." is there
EXPECT_NE(response.find("\"result\": 0"), std::string::npos);
EXPECT_NE(response.find("\"text\": \"Configuration successful.\""), std::string::npos);
// Check that the config was indeed applied.
const Subnet6Collection* subnets =
CfgMgr::instance().getCurrentCfg()->getCfgSubnets6()->getAll();
EXPECT_EQ(1, subnets->size());
OptionDefinitionPtr def =
LibDHCP::getRuntimeOptionDef(DHCP6_OPTION_SPACE, 163);
ASSERT_TRUE(def);
// Create a config with malformed subnet that should fail to parse.
os.str("");
os << set_config_txt << ","
<< args_txt
<< dhcp6_cfg_txt
<< bad_subnet
<< subnet_footer
<< control_socket_header
<< socket_path_
<< control_socket_footer
<< "}\n" // close dhcp6
<< "}}";
// Send the config-set command
sendUnixCommand(os.str(), response);
// Should fail with a syntax error
EXPECT_EQ("{ \"result\": 1, "
"\"text\": \"subnet configuration failed: mandatory 'subnet' "
"parameter is missing for a subnet being configured (<wire>:20:17)\" }",
response);
// Check that the config was not lost
subnets = CfgMgr::instance().getCurrentCfg()->getCfgSubnets6()->getAll();
EXPECT_EQ(1, subnets->size());
def = LibDHCP::getRuntimeOptionDef(DHCP6_OPTION_SPACE, 163);
ASSERT_TRUE(def);
// Create a valid config with two subnets and no command channel.
// It should succeed, client should still receive the response
os.str("");
os << set_config_txt << ","
<< args_txt
<< dhcp6_cfg_txt
<< subnet1
<< ",\n"
<< subnet2
<< subnet_footer
<< "}\n" // close dhcp6
<< "}}";
// Verify the control channel socket exists.
ASSERT_TRUE(fileExists(socket_path_));
// Send the config-set command.
sendUnixCommand(os.str(), response);
// Verify the control channel socket no longer exists.
EXPECT_FALSE(fileExists(socket_path_));
// With no command channel, should still receive the response.
// The config contains random socket name
// (/tmp/kea-<value-changing-each-time>/kea6.sock), so the hash will
// be different each time. As such, we can do simplified checks:
// - verify the "result": 0 is there
// - verify the "text": "Configuration successful." is there
EXPECT_NE(response.find("\"result\": 0"), std::string::npos);
EXPECT_NE(response.find("\"text\": \"Configuration successful.\""), std::string::npos);
// Check that the config was not lost
subnets = CfgMgr::instance().getCurrentCfg()->getCfgSubnets6()->getAll();
EXPECT_EQ(2, subnets->size());
// Clean up after the test.
CfgMgr::instance().clear();
}
// Tests if the server returns its configuration using config-get.
// Note there are separate tests that verify if toElement() called by the
// config-get handler are actually converting the configuration correctly.
TEST_F(CtrlChannelDhcpv6SrvTest, configGet) {
createUnixChannelServer();
std::string response;
sendUnixCommand("{ \"command\": \"config-get\" }", response);
ConstElementPtr rsp;
// The response should be a valid JSON.
EXPECT_NO_THROW(rsp = Element::fromJSON(response));
ASSERT_TRUE(rsp);
int status;
ConstElementPtr cfg = parseAnswer(status, rsp);
EXPECT_EQ(CONTROL_RESULT_SUCCESS, status);
// Ok, now roughly check if the response seems legit.
ASSERT_TRUE(cfg);
ASSERT_EQ(Element::map, cfg->getType());
EXPECT_TRUE(cfg->get("Dhcp6"));
EXPECT_TRUE(cfg->get("Dhcp6")->get("loggers"));
}
// Tests if the server returns the hash of its configuration using
// config-hash-get.
TEST_F(CtrlChannelDhcpv6SrvTest, configHashGet) {
createUnixChannelServer();
std::string response;
sendUnixCommand("{ \"command\": \"config-hash-get\" }", response);
ConstElementPtr rsp;
// The response should be a valid JSON.
EXPECT_NO_THROW(rsp = Element::fromJSON(response));
ASSERT_TRUE(rsp);
int status;
ConstElementPtr args = parseAnswer(status, rsp);
EXPECT_EQ(CONTROL_RESULT_SUCCESS, status);
// The parseAnswer is trying to be smart with ignoring hash.
// But this time we really want to see the hash, so we'll retrieve
// the arguments manually.
args = rsp->get(CONTROL_ARGUMENTS);
// Ok, now roughly check if the response seems legit.
ASSERT_TRUE(args);
ASSERT_EQ(Element::map, args->getType());
ConstElementPtr hash = args->get("hash");
ASSERT_TRUE(hash);
ASSERT_EQ(Element::string, hash->getType());
// SHA-256 -> 64 hex digits.
EXPECT_EQ(64, hash->stringValue().size());
}
// Verify that the "config-test" command will do what we expect.
TEST_F(CtrlChannelDhcpv6SrvTest, configTest) {
createUnixChannelServer();
// Define strings to permutate the config arguments
// (Note the line feeds makes errors easy to find)
string set_config_txt = "{ \"command\": \"config-set\" \n";
string config_test_txt = "{ \"command\": \"config-test\" \n";
string args_txt = " \"arguments\": { \n";
string dhcp6_cfg_txt =
" \"Dhcp6\": { \n"
" \"interfaces-config\": { \n"
" \"interfaces\": [\"*\"] \n"
" }, \n"
" \"preferred-lifetime\": 3000, \n"
" \"valid-lifetime\": 4000, \n"
" \"renew-timer\": 1000, \n"
" \"rebind-timer\": 2000, \n"
" \"lease-database\": { \n"
" \"type\": \"memfile\", \n"
" \"persist\":false, \n"
" \"lfc-interval\": 0 \n"
" }, \n"
" \"expired-leases-processing\": { \n"
" \"reclaim-timer-wait-time\": 0, \n"
" \"hold-reclaimed-time\": 0, \n"
" \"flush-reclaimed-timer-wait-time\": 0 \n"
" },"
" \"subnet6\": [ \n";
string subnet1 =
" {\"subnet\": \"3002::/64\", \"id\": 1, \n"
" \"pools\": [{ \"pool\": \"3002::100-3002::200\" }]}\n";
string subnet2 =
" {\"subnet\": \"3003::/64\", \"id\": 2, \n"
" \"pools\": [{ \"pool\": \"3003::100-3003::200\" }]}\n";
string bad_subnet =
" {\"comment\": \"3005::/64\", \"id\": 10, \n"
" \"pools\": [{ \"pool\": \"3005::100-3005::200\" }]}\n";
string subnet_footer =
" ] \n";
string control_socket_header =
" ,\"control-socket\": { \n"
" \"socket-type\": \"unix\", \n"
" \"socket-name\": \"";
string control_socket_footer =
"\" \n} \n";
string logger_txt =
" ,\"loggers\": [ { \n"
" \"name\": \"kea\", \n"
" \"severity\": \"FATAL\", \n"
" \"output-options\": [{ \n"
" \"output\": \"/dev/null\", \n"
" \"maxsize\": 0"
" }] \n"
" }] \n";
std::ostringstream os;
// Create a valid config with all the parts should parse
os << set_config_txt << ","
<< args_txt
<< dhcp6_cfg_txt
<< subnet1
<< subnet_footer
<< control_socket_header
<< socket_path_
<< control_socket_footer
<< logger_txt
<< "}\n" // close dhcp6
<< "}}";
// Send the config-set command
std::string response;
sendUnixCommand(os.str(), response);
// Verify the configuration was successful. The config contains random
// socket name (/tmp/kea-<value-changing-each-time>/kea6.sock), so the
// hash will be different each time. As such, we can do simplified checks:
// - verify the "result": 0 is there
// - verify the "text": "Configuration successful." is there
EXPECT_NE(response.find("\"result\": 0"), std::string::npos);
EXPECT_NE(response.find("\"text\": \"Configuration successful.\""), std::string::npos);
// Check that the config was indeed applied.
const Subnet6Collection* subnets =
CfgMgr::instance().getCurrentCfg()->getCfgSubnets6()->getAll();
EXPECT_EQ(1, subnets->size());
// Create a config with malformed subnet that should fail to parse.
os.str("");
os << config_test_txt << ","
<< args_txt
<< dhcp6_cfg_txt
<< bad_subnet
<< subnet_footer
<< control_socket_header
<< socket_path_
<< control_socket_footer
<< "}\n" // close dhcp6
<< "}}";
// Send the config-test command
sendUnixCommand(os.str(), response);
// Should fail with a syntax error
EXPECT_EQ("{ \"result\": 1, "
"\"text\": \"subnet configuration failed: mandatory 'subnet' parameter "
"is missing for a subnet being configured (<wire>:20:17)\" }",
response);
// Check that the config was not lost
subnets = CfgMgr::instance().getCurrentCfg()->getCfgSubnets6()->getAll();
EXPECT_EQ(1, subnets->size());
// Create a valid config with two subnets and no command channel.
os.str("");
os << config_test_txt << ","
<< args_txt
<< dhcp6_cfg_txt
<< subnet1
<< ",\n"
<< subnet2
<< subnet_footer
<< "}\n" // close dhcp6
<< "}}";
// Verify the control channel socket exists.
ASSERT_TRUE(fileExists(socket_path_));
// Send the config-test command.
sendUnixCommand(os.str(), response);
// Verify the control channel socket still exists.
EXPECT_TRUE(fileExists(socket_path_));
// Verify the configuration was successful.
EXPECT_EQ("{ \"result\": 0, \"text\": \"Configuration seems sane. "
"Control-socket, hook-libraries, and D2 configuration were "
"sanity checked, but not applied.\" }",
response);
// Check that the config was not applied.
subnets = CfgMgr::instance().getCurrentCfg()->getCfgSubnets6()->getAll();
EXPECT_EQ(1, subnets->size());
// Clean up after the test.
CfgMgr::instance().clear();
}
// Verify that the "subnet6-select-test" command will do what we expect.
TEST_F(CtrlChannelDhcpv6SrvTest, subnetSelectTest) {
createUnixChannelServer();
string command_txt = "{ \"command\": \"subnet6-select-test\", \"arguments\": { \"classes\": [ \"foo\" ] } }";
// Send the subnet6-select-test command
std::string response;
sendUnixCommand(command_txt, response);
EXPECT_EQ("{ \"result\": 3, \"text\": \"no subnet selected\" }",
response);
}
// This test verifies that the DHCP server handles version-get commands
TEST_F(CtrlChannelDhcpv6SrvTest, getVersion) {
createUnixChannelServer();
std::string response;
// Send the version-get command
sendUnixCommand("{ \"command\": \"version-get\" }", response);
EXPECT_TRUE(response.find("\"result\": 0") != string::npos);
EXPECT_TRUE(response.find("log4cplus") != string::npos);
EXPECT_FALSE(response.find("GTEST_VERSION") != string::npos);
// Send the build-report command
sendUnixCommand("{ \"command\": \"build-report\" }", response);
EXPECT_TRUE(response.find("\"result\": 0") != string::npos);
EXPECT_TRUE(response.find("GTEST_VERSION") != string::npos);
}
// This test verifies that the DHCP server handles server-tag-get command
TEST_F(CtrlChannelDhcpv6SrvTest, serverTagGet) {
createUnixChannelServer();
std::string response;
std::string expected;
// Send the server-tag-get command
sendUnixCommand("{ \"command\": \"server-tag-get\" }", response);
expected = "{ \"arguments\": { \"server-tag\": \"\" }, \"result\": 0 }";
EXPECT_EQ(expected, response);
// Set a value to the server tag
CfgMgr::instance().getCurrentCfg()->setServerTag("foobar");
// Retry...
sendUnixCommand("{ \"command\": \"server-tag-get\" }", response);
expected = "{ \"arguments\": { \"server-tag\": \"foobar\" }, \"result\": 0 }";
EXPECT_EQ(expected, response);
}
// This test verifies that the DHCP server handles status-get commands
TEST_F(CtrlChannelDhcpv6SrvTest, statusGet) {
createUnixChannelServer();
// start_ is initialized by init.
ASSERT_THROW(server_->init("/no/such/file"), BadValue);
std::string response_txt;
// Send the status-get command.
sendUnixCommand("{ \"command\": \"status-get\" }", response_txt);
ConstElementPtr response;
ASSERT_NO_THROW(response = Element::fromJSON(response_txt));
ASSERT_TRUE(response);
ASSERT_EQ(Element::map, response->getType());
EXPECT_EQ(2, response->size());
ConstElementPtr result = response->get("result");
ASSERT_TRUE(result);
ASSERT_EQ(Element::integer, result->getType());
EXPECT_EQ(0, result->intValue());
ConstElementPtr arguments = response->get("arguments");
ASSERT_EQ(Element::map, arguments->getType());
// The returned pid should be the pid of our process.
auto found_pid = arguments->get("pid");
ASSERT_TRUE(found_pid);
EXPECT_EQ(static_cast<int64_t>(getpid()), found_pid->intValue());
// It is hard to check the actual uptime (and reload) as it is based
// on current time. Let's just make sure it is within a reasonable
// range.
auto found_uptime = arguments->get("uptime");
ASSERT_TRUE(found_uptime);
EXPECT_LE(found_uptime->intValue(), 5);
EXPECT_GE(found_uptime->intValue(), 0);
auto found_reload = arguments->get("reload");
ASSERT_TRUE(found_reload);
EXPECT_LE(found_reload->intValue(), 5);
EXPECT_GE(found_reload->intValue(), 0);
auto found_multi_threading = arguments->get("multi-threading-enabled");
ASSERT_TRUE(found_multi_threading);
EXPECT_TRUE(found_multi_threading->boolValue());
auto found_thread_count = arguments->get("thread-pool-size");
ASSERT_TRUE(found_thread_count);
// The default value varies between systems.
// Let's just make sure it's a positive value.
EXPECT_LE(0, found_thread_count->intValue());
auto found_queue_size = arguments->get("packet-queue-size");
ASSERT_TRUE(found_queue_size);
EXPECT_EQ(64, found_queue_size->intValue());
auto found_queue_stats = arguments->get("packet-queue-statistics");
ASSERT_TRUE(found_queue_stats);
EXPECT_FALSE(found_queue_stats->str().empty());
auto found_extended_info_tables = arguments->get("extended-info-tables");
ASSERT_TRUE(found_extended_info_tables);
EXPECT_FALSE(found_extended_info_tables->boolValue());
MultiThreadingMgr::instance().setMode(true);
MultiThreadingMgr::instance().setThreadPoolSize(4);
MultiThreadingMgr::instance().setPacketQueueSize(64);
sendUnixCommand("{ \"command\": \"status-get\" }", response_txt);
ASSERT_NO_THROW(response = Element::fromJSON(response_txt));
ASSERT_TRUE(response);
ASSERT_EQ(Element::map, response->getType());
EXPECT_EQ(2, response->size());
result = response->get("result");
ASSERT_TRUE(result);
ASSERT_EQ(Element::integer, result->getType());
EXPECT_EQ(0, result->intValue());
arguments = response->get("arguments");
ASSERT_EQ(Element::map, arguments->getType());
// The returned pid should be the pid of our process.
found_pid = arguments->get("pid");
ASSERT_TRUE(found_pid);
EXPECT_EQ(static_cast<int64_t>(getpid()), found_pid->intValue());
// It is hard to check the actual uptime (and reload) as it is based
// on current time. Let's just make sure it is within a reasonable
// range.
found_uptime = arguments->get("uptime");
ASSERT_TRUE(found_uptime);
EXPECT_LE(found_uptime->intValue(), 5);
EXPECT_GE(found_uptime->intValue(), 0);
found_reload = arguments->get("reload");
ASSERT_TRUE(found_reload);
EXPECT_LE(found_reload->intValue(), 5);
EXPECT_GE(found_reload->intValue(), 0);
found_multi_threading = arguments->get("multi-threading-enabled");
ASSERT_TRUE(found_multi_threading);
EXPECT_TRUE(found_multi_threading->boolValue());
found_thread_count = arguments->get("thread-pool-size");
ASSERT_TRUE(found_thread_count);
EXPECT_EQ(found_thread_count->intValue(), 4);
found_queue_size = arguments->get("packet-queue-size");
ASSERT_TRUE(found_queue_size);
EXPECT_EQ(found_queue_size->intValue(), 64);
found_queue_stats = arguments->get("packet-queue-statistics");
ASSERT_TRUE(found_queue_stats);
ASSERT_EQ(Element::list, found_queue_stats->getType());
EXPECT_EQ(3, found_queue_stats->size());
}
// Check that status is returned even if LeaseMgr and HostMgr are not created.
TEST_F(CtrlChannelDhcpv6SrvTest, noManagers) {
// Send the status-get command.
createUnixChannelServer();
LeaseMgrFactory::destroy();
HostMgr::create();
string response_text;
sendUnixCommand(R"({ "command": "status-get" })", response_text);
ConstElementPtr response;
ASSERT_NO_THROW(response = Element::fromJSON(response_text));
ASSERT_TRUE(response);
ASSERT_EQ(Element::map, response->getType());
ConstElementPtr result(response->get("result"));
ASSERT_TRUE(result);
ASSERT_EQ(Element::integer, result->getType());
EXPECT_EQ(0, result->intValue());
ConstElementPtr arguments(response->get("arguments"));
ASSERT_TRUE(arguments);
ASSERT_EQ(Element::map, arguments->getType());
}
// Checks that socket status exists in status-get responses.
TEST_F(CtrlChannelDhcpv6SrvTest, statusGetSockets) {
// Create dummy interfaces to test socket status.
isc::dhcp::test::IfaceMgrTestConfig test_config(true);
// Send the status-get command.
createUnixChannelServer();
string response_text;
sendUnixCommand(R"({ "command": "status-get" })", response_text);
ConstElementPtr response;
ASSERT_NO_THROW(response = Element::fromJSON(response_text));
ASSERT_TRUE(response);
ASSERT_EQ(Element::map, response->getType());
ConstElementPtr result(response->get("result"));
ASSERT_TRUE(result);
ASSERT_EQ(Element::integer, result->getType());
EXPECT_EQ(0, result->intValue());
ConstElementPtr arguments(response->get("arguments"));
ASSERT_TRUE(arguments);
ASSERT_EQ(Element::map, arguments->getType());
ConstElementPtr sockets(arguments->get("sockets"));
ASSERT_TRUE(sockets);
ASSERT_EQ(Element::map, sockets->getType());
ConstElementPtr status(sockets->get("status"));
ASSERT_TRUE(status);
ASSERT_EQ(Element::string, status->getType());
EXPECT_EQ("ready", status->stringValue());
ConstElementPtr errors(sockets->get("errors"));
ASSERT_FALSE(errors);
}
// Checks that socket status includes errors in status-get responses.
TEST_F(CtrlChannelDhcpv6SrvTest, statusGetSocketsErrors) {
// Create dummy interfaces to test socket status and add a custom down interface.
isc::dhcp::test::IfaceMgrTestConfig test_config(true);
test_config.addIface("down_interface", 4);
test_config.setIfaceFlags("down_interface", FlagLoopback(false), FlagUp(false),
FlagRunning(true), FlagInactive4(false),
FlagInactive6(false));
// Send the status-get command.
createUnixChannelServer();
string response_text;
sendUnixCommand(R"({ "command": "status-get" })", response_text);
ConstElementPtr response;
ASSERT_NO_THROW(response = Element::fromJSON(response_text));
ASSERT_TRUE(response);
ASSERT_EQ(Element::map, response->getType());
ConstElementPtr result(response->get("result"));
ASSERT_TRUE(result);
ASSERT_EQ(Element::integer, result->getType());
EXPECT_EQ(0, result->intValue());
ConstElementPtr arguments(response->get("arguments"));
ASSERT_TRUE(arguments);
ASSERT_EQ(Element::map, arguments->getType());
ConstElementPtr sockets(arguments->get("sockets"));
ASSERT_TRUE(sockets);
ASSERT_EQ(Element::map, sockets->getType());
ConstElementPtr status(sockets->get("status"));
ASSERT_TRUE(status);
ASSERT_EQ(Element::string, status->getType());
EXPECT_EQ("failed", status->stringValue());
ConstElementPtr errors(sockets->get("errors"));
ASSERT_TRUE(errors);
ASSERT_EQ(Element::list, errors->getType());
ASSERT_EQ(1, errors->size());
ConstElementPtr error(errors->get(0));
ASSERT_TRUE(error);
ASSERT_EQ(Element::string, error->getType());
ASSERT_EQ("the interface down_interface is down", error->stringValue());
}
// This test verifies that the DHCP server handles config-backend-pull command
TEST_F(CtrlChannelDhcpv6SrvTest, configBackendPull) {
createUnixChannelServer();
std::string response;
std::string expected;
// Send the config-backend-pull command. Note there is no configured backed.
sendUnixCommand("{ \"command\": \"config-backend-pull\" }", response);
expected = "{ \"result\": 3, \"text\": \"No config backend.\" }";
EXPECT_EQ(expected, response);
}
// This test verifies that the DHCP server immediately reclaims expired
// leases on leases-reclaim command
TEST_F(CtrlChannelDhcpv6SrvTest, controlLeasesReclaim) {
createUnixChannelServer();
// Create expired leases. Leases are expired by 40 seconds ago
// (valid lifetime = 60, cltt = now - 100).
DuidPtr duid0(new DUID(DUID::fromText("00:01:02:03:04:05:06").getDuid()));
Lease6Ptr lease0(new Lease6(Lease::TYPE_NA, IOAddress("3000::1"),
duid0, 1, 50, 60, SubnetID(1)));
lease0->cltt_ = time(NULL) - 100;
DuidPtr duid1(new DUID(DUID::fromText("01:02:03:04:05:06:07").getDuid()));
Lease6Ptr lease1(new Lease6(Lease::TYPE_NA, IOAddress("3000::2"),
duid1, 1, 50, 60, SubnetID(1)));
lease1->cltt_ = time(NULL) - 100;
// Add leases to the database.
LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
ASSERT_NO_THROW(lease_mgr.addLease(lease0));
ASSERT_NO_THROW(lease_mgr.addLease(lease1));
// Make sure they have been added.
ASSERT_TRUE(lease_mgr.getLease6(Lease::TYPE_NA, IOAddress("3000::1")));
ASSERT_TRUE(lease_mgr.getLease6(Lease::TYPE_NA, IOAddress("3000::2")));
// No arguments
std::string response;
sendUnixCommand("{ \"command\": \"leases-reclaim\" }", response);
EXPECT_EQ("{ \"result\": 1, \"text\": "
"\"Missing mandatory 'remove' parameter.\" }", response);
// Bad argument name
sendUnixCommand("{ \"command\": \"leases-reclaim\", "
"\"arguments\": { \"reclaim\": true } }", response);
EXPECT_EQ("{ \"result\": 1, \"text\": "
"\"Missing mandatory 'remove' parameter.\" }", response);
// Bad remove argument type
sendUnixCommand("{ \"command\": \"leases-reclaim\", "
"\"arguments\": { \"remove\": \"bogus\" } }", response);
EXPECT_EQ("{ \"result\": 1, \"text\": "
"\"'remove' parameter expected to be a boolean.\" }", response);
// Send the command
sendUnixCommand("{ \"command\": \"leases-reclaim\", "
"\"arguments\": { \"remove\": false } }", response);
EXPECT_EQ("{ \"result\": 0, \"text\": "
"\"Reclamation of expired leases is complete.\" }", response);
// Leases should be reclaimed, but not removed
ASSERT_NO_THROW(
lease0 = lease_mgr.getLease6(Lease::TYPE_NA, IOAddress("3000::1"))
);
ASSERT_NO_THROW(
lease1 = lease_mgr.getLease6(Lease::TYPE_NA, IOAddress("3000::2"))
);
ASSERT_TRUE(lease0);
ASSERT_TRUE(lease1);
EXPECT_TRUE(lease0->stateExpiredReclaimed());
EXPECT_TRUE(lease1->stateExpiredReclaimed());
}
// This test verifies that the DHCP server immediately reclaims expired
// leases on leases-reclaim command with remove = true
TEST_F(CtrlChannelDhcpv6SrvTest, controlLeasesReclaimRemove) {
createUnixChannelServer();
// Create expired leases. Leases are expired by 40 seconds ago
// (valid lifetime = 60, cltt = now - 100).
DuidPtr duid0(new DUID(DUID::fromText("00:01:02:03:04:05:06").getDuid()));
Lease6Ptr lease0(new Lease6(Lease::TYPE_NA, IOAddress("3000::1"),
duid0, 1, 50, 60, SubnetID(1)));
lease0->cltt_ = time(NULL) - 100;
DuidPtr duid1(new DUID(DUID::fromText("01:02:03:04:05:06:07").getDuid()));
Lease6Ptr lease1(new Lease6(Lease::TYPE_NA, IOAddress("3000::2"),
duid1, 1, 50, 60, SubnetID(1)));
lease1->cltt_ = time(NULL) - 100;
// Add leases to the database.
LeaseMgr& lease_mgr = LeaseMgrFactory::instance();
ASSERT_NO_THROW(lease_mgr.addLease(lease0));
ASSERT_NO_THROW(lease_mgr.addLease(lease1));
// Make sure they have been added.
ASSERT_TRUE(lease_mgr.getLease6(Lease::TYPE_NA, IOAddress("3000::1")));
ASSERT_TRUE(lease_mgr.getLease6(Lease::TYPE_NA, IOAddress("3000::2")));
// Send the command
std::string response;
sendUnixCommand("{ \"command\": \"leases-reclaim\", "
"\"arguments\": { \"remove\": true } }", response);
EXPECT_EQ("{ \"result\": 0, \"text\": "
"\"Reclamation of expired leases is complete.\" }", response);
// Leases should have been removed.
ASSERT_NO_THROW(
lease0 = lease_mgr.getLease6(Lease::TYPE_NA, IOAddress("3000::1"))
);
ASSERT_NO_THROW(
lease1 = lease_mgr.getLease6(Lease::TYPE_NA, IOAddress("3000::2"))
);
ASSERT_FALSE(lease0);
ASSERT_FALSE(lease1);
}
// Tests that the server properly responds to list-commands command sent
// via ControlChannel
TEST_F(CtrlChannelDhcpv6SrvTest, listCommands) {
createUnixChannelServer();
std::string response;
sendUnixCommand("{ \"command\": \"list-commands\" }", response);
ConstElementPtr rsp;
EXPECT_NO_THROW(rsp = Element::fromJSON(response));
// We expect the server to report at least the following commands:
checkListCommands(rsp, "build-report");
checkListCommands(rsp, "config-backend-pull");
checkListCommands(rsp, "config-get");
checkListCommands(rsp, "config-hash-get");
checkListCommands(rsp, "config-reload");
checkListCommands(rsp, "config-set");
checkListCommands(rsp, "config-test");
checkListCommands(rsp, "config-write");
checkListCommands(rsp, "list-commands");
checkListCommands(rsp, "leases-reclaim");
checkListCommands(rsp, "version-get");
checkListCommands(rsp, "server-tag-get");
checkListCommands(rsp, "shutdown");
checkListCommands(rsp, "statistic-get");
checkListCommands(rsp, "statistic-get-all");
checkListCommands(rsp, "statistic-remove");
checkListCommands(rsp, "statistic-remove-all");
checkListCommands(rsp, "statistic-reset");
checkListCommands(rsp, "statistic-reset-all");
checkListCommands(rsp, "statistic-sample-age-set");
checkListCommands(rsp, "statistic-sample-age-set-all");
checkListCommands(rsp, "statistic-sample-count-set");
checkListCommands(rsp, "statistic-sample-count-set-all");
}
// Tests if config-write can be called without any parameters.
TEST_F(CtrlChannelDhcpv6SrvTest, configWriteNoFilename) {
createUnixChannelServer();
std::string response;
// This is normally set by the command line -c parameter.
server_->setConfigFile("test1.json");
// If the filename is not explicitly specified, the name used
// in -c command line switch is used.
sendUnixCommand("{ \"command\": \"config-write\" }", response);
checkConfigWrite(response, CONTROL_RESULT_SUCCESS, "test1.json");
::remove("test1.json");
}
// Tests if config-write can be called with a valid filename as parameter.
TEST_F(CtrlChannelDhcpv6SrvTest, configWriteFilename) {
createUnixChannelServer();
std::string response;
sendUnixCommand("{ \"command\": \"config-write\", "
"\"arguments\": { \"filename\": \"test2.json\" } }", response);
checkConfigWrite(response, CONTROL_RESULT_SUCCESS, "test2.json");
::remove("test2.json");
}
// Tests if config-reload attempts to reload a file and reports that the
// file is missing.
TEST_F(CtrlChannelDhcpv6SrvTest, configReloadMissingFile) {
createUnixChannelServer();
std::string response;
// This is normally set to whatever value is passed to -c when the server is
// started, but we're not starting it that way, so need to set it by hand.
server_->setConfigFile("test6.json");
// Tell the server to reload its configuration. It should attempt to load
// test6.json (and fail, because the file is not there).
sendUnixCommand("{ \"command\": \"config-reload\" }", response);
// Verify the reload was rejected.
EXPECT_EQ("{ \"result\": 1, \"text\": \"Config reload failed: "
"configuration error using file 'test6.json': Unable to open file "
"test6.json\" }",
response);
}
// Tests if config-reload attempts to reload a file and reports that the
// file is not a valid JSON.
TEST_F(CtrlChannelDhcpv6SrvTest, configReloadBrokenFile) {
createUnixChannelServer();
std::string response;
// This is normally set to whatever value is passed to -c when the server is
// started, but we're not starting it that way, so need to set it by hand.
server_->setConfigFile("test7.json");
// Although Kea is smart, its AI routines are not smart enough to handle
// this one... at least not yet.
ofstream f("test7.json", ios::trunc);
f << "gimme some addrs, bro!";
f.close();
// Now tell Kea to reload its config.
sendUnixCommand("{ \"command\": \"config-reload\" }", response);
// Verify the reload will fail.
EXPECT_EQ("{ \"result\": 1, \"text\": \"Config reload failed: "
"configuration error using file 'test7.json': "
"test7.json:1.1: Invalid character: g\" }",
response);
::remove("test7.json");
}
// Tests if config-reload attempts to reload a file and reports that the
// file is loaded correctly.
TEST_F(CtrlChannelDhcpv6SrvTest, configReloadValid) {
createUnixChannelServer();
std::string response;
// This is normally set to whatever value is passed to -c when the server is
// started, but we're not starting it that way, so need to set it by hand.
server_->setConfigFile("test8.json");
// Ok, enough fooling around. Let's create a valid config.
const std::string cfg_txt =
"{ \"Dhcp6\": {"
" \"interfaces-config\": {"
" \"interfaces\": [ \"*\" ]"
" },"
" \"subnet6\": ["
" { \"subnet\": \"2001:db8:1::/64\", \"id\": 1 },"
" { \"subnet\": \"2001:db8:2::/64\", \"id\": 2 }"
" ],"
" \"lease-database\": {"
" \"type\": \"memfile\", \"persist\": false }"
"} }";
ofstream f("test8.json", ios::trunc);
f << cfg_txt;
f.close();
// This command should reload test8.json config.
sendUnixCommand("{ \"command\": \"config-reload\" }", response);
// Verify the configuration was successful. The config contains random
// socket name (/tmp/kea-<value-changing-each-time>/kea6.sock), so the
// hash will be different each time. As such, we can do simplified checks:
// - verify the "result": 0 is there
// - verify the "text": "Configuration successful." is there
EXPECT_NE(response.find("\"result\": 0"), std::string::npos);
EXPECT_NE(response.find("\"text\": \"Configuration successful.\""), std::string::npos);
// Check that the config was indeed applied.
const Subnet6Collection* subnets =
CfgMgr::instance().getCurrentCfg()->getCfgSubnets6()->getAll();
EXPECT_EQ(2, subnets->size());
::remove("test8.json");
}
// Tests if config-reload attempts to reload a file and reports that the
// file is loaded correctly.
TEST_F(CtrlChannelDhcpv6SrvTest, configReloadDetectInterfaces) {
interfaces_ = "\"eth0\"";
IfacePtr eth0 = IfaceMgrTestConfig::createIface("eth0", ETH0_INDEX,
"11:22:33:44:55:66");
auto detectIfaces = [&](bool update_only) {
if (!update_only) {
eth0->addAddress(IOAddress("10.0.0.1"));
eth0->addAddress(IOAddress("fe80::3a60:77ff:fed5:cdef"));
eth0->addAddress(IOAddress("2001:db8:1::1"));
IfaceMgr::instance().addInterface(eth0);
}
return (false);
};
IfaceMgr::instance().setDetectCallback(detectIfaces);
IfaceMgr::instance().clearIfaces();
IfaceMgr::instance().closeSockets();
IfaceMgr::instance().detectIfaces();
createUnixChannelServer();
std::string response;
// This is normally set to whatever value is passed to -c when the server is
// started, but we're not starting it that way, so need to set it by hand.
server_->setConfigFile("test8.json");
// Ok, enough fooling around. Let's create a valid config.
const std::string cfg_txt =
"{ \"Dhcp6\": {"
" \"interfaces-config\": {"
" \"interfaces\": [ \"eth1\" ]"
" },"
" \"subnet6\": ["
" { \"subnet\": \"2001:db8:1::/64\", \"id\": 1 },"
" { \"subnet\": \"2001:db8:2::/64\", \"id\": 2 }"
" ],"
" \"lease-database\": {"
" \"type\": \"memfile\", \"persist\": false }"
"} }";
ofstream f("test8.json", ios::trunc);
f << cfg_txt;
f.close();
IfacePtr eth1 = IfaceMgrTestConfig::createIface("eth1", ETH1_INDEX,
"AA:BB:CC:DD:EE:FF");
auto detectUpdateIfaces = [&](bool update_only) {
if (!update_only) {
eth1->addAddress(IOAddress("192.0.2.3"));
eth1->addAddress(IOAddress("fe80::3a60:77ff:fed5:abcd"));
eth1->addAddress(IOAddress("3001:db8:100::1"));
IfaceMgr::instance().addInterface(eth1);
}
return (false);
};
IfaceMgr::instance().setDetectCallback(detectUpdateIfaces);
// This command should reload test8.json config.
sendUnixCommand("{ \"command\": \"config-reload\" }", response);
// Verify the configuration was successful. The config contains random
// socket name (/tmp/kea-<value-changing-each-time>/kea6.sock), so the
// hash will be different each time. As such, we can do simplified checks:
// - verify the "result": 0 is there
// - verify the "text": "Configuration successful." is there
EXPECT_NE(response.find("\"result\": 0"), std::string::npos);
EXPECT_NE(response.find("\"text\": \"Configuration successful.\""), std::string::npos);
// Check that the config was indeed applied.
const Subnet6Collection* subnets =
CfgMgr::instance().getCurrentCfg()->getCfgSubnets6()->getAll();
EXPECT_EQ(2, subnets->size());
::remove("test8.json");
}
// This test verifies that disable DHCP service command performs sanity check on
// parameters.
TEST_F(CtrlChannelDhcpv6SrvTest, dhcpDisableBadParam) {
createUnixChannelServer();
std::string response;
sendUnixCommand("{"
" \"command\": \"dhcp-disable\","
" \"arguments\": {"
" \"max-period\": -3"
" }"
"}", response);
ConstElementPtr rsp;
// The response should be a valid JSON.
EXPECT_NO_THROW(rsp = Element::fromJSON(response));
ASSERT_TRUE(rsp);
EXPECT_EQ("{ \"result\": 1, \"text\": \"'max-period' must be positive "
"integer\" }", response);
sendUnixCommand("{"
" \"command\": \"dhcp-disable\","
" \"arguments\": {"
" \"origin-id\": \"\""
" }"
"}", response);
// The response should be a valid JSON.
EXPECT_NO_THROW(rsp = Element::fromJSON(response));
ASSERT_TRUE(rsp);
EXPECT_EQ("{ \"result\": 1, \"text\": \"'origin-id' argument must be a number\" }", response);
sendUnixCommand("{"
" \"command\": \"dhcp-disable\","
" \"arguments\": {"
" \"origin-id\": \"foo\""
" }"
"}", response);
// The response should be a valid JSON.
EXPECT_NO_THROW(rsp = Element::fromJSON(response));
ASSERT_TRUE(rsp);
EXPECT_EQ("{ \"result\": 1, \"text\": \"'origin-id' argument must be a number\" }", response);
sendUnixCommand("{"
" \"command\": \"dhcp-disable\","
" \"arguments\": {"
" \"origin\": \"\""
" }"
"}", response);
// The response should be a valid JSON.
EXPECT_NO_THROW(rsp = Element::fromJSON(response));
ASSERT_TRUE(rsp);
EXPECT_EQ("{ \"result\": 1, \"text\": \"invalid value used for 'origin' "
"parameter: (empty string)\" }", response);
sendUnixCommand("{"
" \"command\": \"dhcp-disable\","
" \"arguments\": {"
" \"origin\": \"test\""
" }"
"}", response);
// The response should be a valid JSON.
EXPECT_NO_THROW(rsp = Element::fromJSON(response));
ASSERT_TRUE(rsp);
EXPECT_EQ("{ \"result\": 1, \"text\": \"invalid value used for 'origin' "
"parameter: test\" }", response);
}
// This test verifies if it is possible to disable DHCP service via command.
TEST_F(CtrlChannelDhcpv6SrvTest, dhcpDisable) {
createUnixChannelServer();
std::string response;
sendUnixCommand("{ \"command\": \"dhcp-disable\" }", response);
ConstElementPtr rsp;
// The response should be a valid JSON.
EXPECT_NO_THROW(rsp = Element::fromJSON(response));
ASSERT_TRUE(rsp);
int status;
ConstElementPtr cfg = parseAnswer(status, rsp);
EXPECT_EQ(CONTROL_RESULT_SUCCESS, status);
EXPECT_FALSE(server_->network_state_->isServiceEnabled());
server_->network_state_->enableService(NetworkState::USER_COMMAND);
EXPECT_TRUE(server_->network_state_->isServiceEnabled());
sendUnixCommand("{"
" \"command\": \"dhcp-disable\","
" \"arguments\": {"
" \"origin\": \"user\""
" }"
"}", response);
// The response should be a valid JSON.
EXPECT_NO_THROW(rsp = Element::fromJSON(response));
ASSERT_TRUE(rsp);
cfg = parseAnswer(status, rsp);
EXPECT_EQ(CONTROL_RESULT_SUCCESS, status);
EXPECT_FALSE(server_->network_state_->isServiceEnabled());
server_->network_state_->enableService(NetworkState::USER_COMMAND);
EXPECT_TRUE(server_->network_state_->isServiceEnabled());
sendUnixCommand("{"
" \"command\": \"dhcp-disable\","
" \"arguments\": {"
" \"origin\": \"ha-partner\""
" }"
"}", response);
// The response should be a valid JSON.
EXPECT_NO_THROW(rsp = Element::fromJSON(response));
ASSERT_TRUE(rsp);
cfg = parseAnswer(status, rsp);
EXPECT_EQ(CONTROL_RESULT_SUCCESS, status);
EXPECT_FALSE(server_->network_state_->isServiceEnabled());
server_->network_state_->enableService(NetworkState::HA_REMOTE_COMMAND);
EXPECT_TRUE(server_->network_state_->isServiceEnabled());
sendUnixCommand("{"
" \"command\": \"dhcp-disable\","
" \"arguments\": {"
" \"origin\": 2001"
" }"
"}", response);
// The response should be a valid JSON.
EXPECT_NO_THROW(rsp = Element::fromJSON(response));
ASSERT_TRUE(rsp);
cfg = parseAnswer(status, rsp);
EXPECT_EQ(CONTROL_RESULT_SUCCESS, status);
EXPECT_FALSE(server_->network_state_->isServiceEnabled());
server_->network_state_->enableService(NetworkState::HA_REMOTE_COMMAND+1);
EXPECT_TRUE(server_->network_state_->isServiceEnabled());
}
// This test verifies if it is possible to disable DHCP service using
// the origin-id.
TEST_F(CtrlChannelDhcpv6SrvTest, dhcpDisableOriginId) {
createUnixChannelServer();
std::string response;
EXPECT_TRUE(server_->network_state_->isServiceEnabled());
sendUnixCommand("{"
" \"command\": \"dhcp-disable\","
" \"arguments\": {"
" \"origin-id\": 2002,"
" \"origin\": \"user\""
" }"
"}", response);
ConstElementPtr rsp;
// The response should be a valid JSON.
EXPECT_NO_THROW(rsp = Element::fromJSON(response));
ASSERT_TRUE(rsp);
int status;
ConstElementPtr cfg = parseAnswer(status, rsp);
EXPECT_EQ(CONTROL_RESULT_SUCCESS, status);
EXPECT_FALSE(server_->network_state_->isServiceEnabled());
server_->network_state_->enableService(NetworkState::HA_REMOTE_COMMAND+2);
EXPECT_TRUE(server_->network_state_->isServiceEnabled());
}
// This test verifies that it is possible to disable DHCP service for a short
// period of time, after which the service is automatically enabled.
TEST_F(CtrlChannelDhcpv6SrvTest, dhcpDisableTemporarily) {
createUnixChannelServer();
std::string response;
// Send a command to disable DHCP service for 3 seconds.
sendUnixCommand("{"
" \"command\": \"dhcp-disable\","
" \"arguments\": {"
" \"max-period\": 3"
" }"
"}", response);
ConstElementPtr rsp;
// The response should be a valid JSON.
EXPECT_NO_THROW(rsp = Element::fromJSON(response));
ASSERT_TRUE(rsp);
int status;
ConstElementPtr cfg = parseAnswer(status, rsp);
EXPECT_EQ(CONTROL_RESULT_SUCCESS, status);
// The service should be disabled.
EXPECT_FALSE(server_->network_state_->isServiceEnabled());
// And the timer should be scheduled which counts the time to automatic
// enabling of the service.
EXPECT_TRUE(server_->network_state_->isDelayedEnableService());
}
// This test verifies that enable DHCP service command performs sanity check on
// parameters.
TEST_F(CtrlChannelDhcpv6SrvTest, dhcpEnableBadParam) {
createUnixChannelServer();
std::string response;
ConstElementPtr rsp;
sendUnixCommand("{"
" \"command\": \"dhcp-enable\","
" \"arguments\": {"
" \"origin-id\": \"\""
" }"
"}", response);
// The response should be a valid JSON.
EXPECT_NO_THROW(rsp = Element::fromJSON(response));
ASSERT_TRUE(rsp);
EXPECT_EQ("{ \"result\": 1, \"text\": \"'origin-id' argument must be a number\" }", response);
sendUnixCommand("{"
" \"command\": \"dhcp-enable\","
" \"arguments\": {"
" \"origin-id\": \"foo\""
" }"
"}", response);
// The response should be a valid JSON.
EXPECT_NO_THROW(rsp = Element::fromJSON(response));
ASSERT_TRUE(rsp);
EXPECT_EQ("{ \"result\": 1, \"text\": \"'origin-id' argument must be a number\" }", response);
sendUnixCommand("{"
" \"command\": \"dhcp-enable\","
" \"arguments\": {"
" \"origin\": \"\""
" }"
"}", response);
// The response should be a valid JSON.
EXPECT_NO_THROW(rsp = Element::fromJSON(response));
ASSERT_TRUE(rsp);
EXPECT_EQ("{ \"result\": 1, \"text\": \"invalid value used for 'origin' "
"parameter: (empty string)\" }", response);
sendUnixCommand("{"
" \"command\": \"dhcp-enable\","
" \"arguments\": {"
" \"origin\": \"test\""
" }"
"}", response);
// The response should be a valid JSON.
EXPECT_NO_THROW(rsp = Element::fromJSON(response));
ASSERT_TRUE(rsp);
EXPECT_EQ("{ \"result\": 1, \"text\": \"invalid value used for 'origin' "
"parameter: test\" }", response);
}
// This test verifies if it is possible to enable DHCP service via command.
TEST_F(CtrlChannelDhcpv6SrvTest, dhcpEnable) {
createUnixChannelServer();
std::string response;
sendUnixCommand("{ \"command\": \"dhcp-enable\" }", response);
ConstElementPtr rsp;
// The response should be a valid JSON.
EXPECT_NO_THROW(rsp = Element::fromJSON(response));
ASSERT_TRUE(rsp);
int status;
ConstElementPtr cfg = parseAnswer(status, rsp);
EXPECT_EQ(CONTROL_RESULT_SUCCESS, status);
EXPECT_TRUE(server_->network_state_->isServiceEnabled());
server_->network_state_->disableService(NetworkState::USER_COMMAND);
EXPECT_FALSE(server_->network_state_->isServiceEnabled());
sendUnixCommand("{"
" \"command\": \"dhcp-enable\","
" \"arguments\": {"
" \"origin\": \"user\""
" }"
"}", response);
// The response should be a valid JSON.
EXPECT_NO_THROW(rsp = Element::fromJSON(response));
ASSERT_TRUE(rsp);
cfg = parseAnswer(status, rsp);
EXPECT_EQ(CONTROL_RESULT_SUCCESS, status);
EXPECT_TRUE(server_->network_state_->isServiceEnabled());
server_->network_state_->disableService(NetworkState::HA_REMOTE_COMMAND);
EXPECT_FALSE(server_->network_state_->isServiceEnabled());
sendUnixCommand("{"
" \"command\": \"dhcp-enable\","
" \"arguments\": {"
" \"origin\": \"ha-partner\""
" }"
"}", response);
// The response should be a valid JSON.
EXPECT_NO_THROW(rsp = Element::fromJSON(response));
ASSERT_TRUE(rsp);
cfg = parseAnswer(status, rsp);
EXPECT_EQ(CONTROL_RESULT_SUCCESS, status);
EXPECT_TRUE(server_->network_state_->isServiceEnabled());
server_->network_state_->disableService(NetworkState::HA_REMOTE_COMMAND+2);
EXPECT_FALSE(server_->network_state_->isServiceEnabled());
sendUnixCommand("{"
" \"command\": \"dhcp-enable\","
" \"arguments\": {"
" \"origin\": 2002"
" }"
"}", response);
// The response should be a valid JSON.
EXPECT_NO_THROW(rsp = Element::fromJSON(response));
ASSERT_TRUE(rsp);
cfg = parseAnswer(status, rsp);
EXPECT_EQ(CONTROL_RESULT_SUCCESS, status);
EXPECT_TRUE(server_->network_state_->isServiceEnabled());
}
// This test verifies if it is possible to enable DHCP service using
// the origin-id.
TEST_F(CtrlChannelDhcpv6SrvTest, dhcpEnableOriginId) {
createUnixChannelServer();
std::string response;
ConstElementPtr rsp;
int status;
// Disable the service using two distinct origins.
server_->network_state_->disableService(NetworkState::HA_REMOTE_COMMAND+1);
server_->network_state_->disableService(NetworkState::USER_COMMAND);
EXPECT_FALSE(server_->network_state_->isServiceEnabled());
// Enable the service for the 'origin-id' of 2001. The 'origin' should
// be ignored.
sendUnixCommand("{"
" \"command\": \"dhcp-enable\","
" \"arguments\": {"
" \"origin-id\": 2001,"
" \"origin\": \"user\""
" }"
"}", response);
// The response should be a valid JSON.
EXPECT_NO_THROW(rsp = Element::fromJSON(response));
ASSERT_TRUE(rsp);
ConstElementPtr cfg = parseAnswer(status, rsp);
EXPECT_EQ(CONTROL_RESULT_SUCCESS, status);
// The service should still be disabled.
EXPECT_FALSE(server_->network_state_->isServiceEnabled());
// Enable the service for the user command.
sendUnixCommand("{"
" \"command\": \"dhcp-enable\","
" \"arguments\": {"
" \"origin-id\": 1"
" }"
"}", response);
// The response should be a valid JSON.
EXPECT_NO_THROW(rsp = Element::fromJSON(response));
ASSERT_TRUE(rsp);
cfg = parseAnswer(status, rsp);
EXPECT_EQ(CONTROL_RESULT_SUCCESS, status);
// The service should be enabled.
EXPECT_TRUE(server_->network_state_->isServiceEnabled());
}
// This test verifies that subnet6-select-test command performs sanity check parameters.
TEST_F(CtrlChannelDhcpv6SrvTest, subnet6SelectTestBadParam) {
createUnixChannelServer();
std::string response;
ConstElementPtr rsp;
sendUnixCommand("{"
" \"command\": \"subnet6-select-test\""
"}", response);
// The response should be a valid JSON.
EXPECT_NO_THROW(rsp = Element::fromJSON(response));
ASSERT_TRUE(rsp);
EXPECT_EQ("{ \"result\": 1, \"text\": \"empty arguments\" }",
response);
sendUnixCommand("{"
" \"command\": \"subnet6-select-test\","
" \"arguments\": [ ]"
" }"
"}", response);
EXPECT_EQ("{ \"result\": 1, \"text\": \"arguments must be a map\" }",
response);
sendUnixCommand("{"
" \"command\": \"subnet6-select-test\","
" \"arguments\": {"
" \"foo\": \"bar\""
" }"
"}", response);
EXPECT_EQ("{ \"result\": 1, \"text\": \"unknown entry 'foo'\" }",
response);
sendUnixCommand("{"
" \"command\": \"subnet6-select-test\","
" \"arguments\": {"
" \"interface\": 1"
" }"
"}", response);
string expected = "{ \"result\": 1, \"text\": \"";
expected += "'interface' entry must be a string";
expected += "\" }";
EXPECT_EQ(expected, response);
sendUnixCommand("{"
" \"command\": \"subnet6-select-test\","
" \"arguments\": {"
" \"interface-id\": 1"
" }"
"}", response);
expected = "{ \"result\": 1, \"text\": \"";
expected += "'interface-id' entry must be a string";
expected += "\" }";
EXPECT_EQ(expected, response);
sendUnixCommand("{"
" \"command\": \"subnet6-select-test\","
" \"arguments\": {"
" \"interface-id\": \"\""
" }"
"}", response);
expected = "{ \"result\": 1, \"text\": \"";
expected += "'interface-id' must be not empty";
expected += "\" }";
EXPECT_EQ(expected, response);
sendUnixCommand("{"
" \"command\": \"subnet6-select-test\","
" \"arguments\": {"
" \"interface-id\": \"foo\""
" }"
"}", response);
expected = "{ \"result\": 1, \"text\": \"";
expected += "value of 'interface-id' was not recognized";
expected += "\" }";
EXPECT_EQ(expected, response);
sendUnixCommand("{"
" \"command\": \"subnet6-select-test\","
" \"arguments\": {"
" \"remote\": 1"
" }"
"}", response);
expected = "{ \"result\": 1, \"text\": \"";
expected += "'remote' entry must be a string";
expected += "\" }";
EXPECT_EQ(expected, response);
sendUnixCommand("{"
" \"command\": \"subnet6-select-test\","
" \"arguments\": {"
" \"remote\": \"192.2.1.2\""
" }"
"}", response);
expected = "{ \"result\": 1, \"text\": \"";
expected += "bad 'remote' entry: not IPv6";
expected += "\" }";
EXPECT_EQ(expected, response);
sendUnixCommand("{"
" \"command\": \"subnet6-select-test\","
" \"arguments\": {"
" \"remote\": \"foobar\""
" }"
"}", response);
expected = "{ \"result\": 1, \"text\": \"";
expected += "bad 'remote' entry: Failed to convert string to address ";
expected += "'foobar': Invalid argument";
expected += "\" }";
EXPECT_EQ(expected, response);
sendUnixCommand("{"
" \"command\": \"subnet6-select-test\","
" \"arguments\": {"
" \"link\": 1"
" }"
"}", response);
expected = "{ \"result\": 1, \"text\": \"";
expected += "'link' entry must be a string";
expected += "\" }";
EXPECT_EQ(expected, response);
sendUnixCommand("{"
" \"command\": \"subnet6-select-test\","
" \"arguments\": {"
" \"link\": \"192.2.1.2\""
" }"
"}", response);
expected = "{ \"result\": 1, \"text\": \"";
expected += "bad 'link' entry: not IPv6";
expected += "\" }";
EXPECT_EQ(expected, response);
sendUnixCommand("{"
" \"command\": \"subnet6-select-test\","
" \"arguments\": {"
" \"link\": \"foobar\""
" }"
"}", response);
expected = "{ \"result\": 1, \"text\": \"";
expected += "bad 'link' entry: Failed to convert string to address ";
expected += "'foobar': Invalid argument";
expected += "\" }";
EXPECT_EQ(expected, response);
sendUnixCommand("{"
" \"command\": \"subnet6-select-test\","
" \"arguments\": {"
" \"classes\": \"foo\""
" }"
"}", response);
expected = "{ \"result\": 1, \"text\": \"";
expected += "'classes' entry must be a list";
expected += "\" }";
EXPECT_EQ(expected, response);
sendUnixCommand("{"
" \"command\": \"subnet6-select-test\","
" \"arguments\": {"
" \"classes\": [ 1 ]"
" }"
"}", response);
expected = "{ \"result\": 1, \"text\": \"";
expected += "'classes' entry must be a list of strings";
expected += "\" }";
EXPECT_EQ(expected, response);
}
// This test verifies if subnet6-select-test command returns proper subnet for a given
// remote/source address.
TEST_F(CtrlChannelDhcpv6SrvTest, subnet6SelectTestAddr) {
createUnixChannelServer();
std::string response;
auto subnet = Subnet6::create(IOAddress("2001:db8:1::"),
64, 1, 2, 3, 4, SubnetID(1));
SharedNetwork6Ptr network(new SharedNetwork6("foo"));
CfgMgr::instance().clear();
CfgMgr::instance().getStagingCfg()->getCfgSubnets6()->add(subnet);
CfgMgr::instance().getStagingCfg()->getCfgSharedNetworks6()->add(network);
CfgMgr::instance().commit();
// Address not in range: nothing can be selected.
sendUnixCommand("{"
" \"command\": \"subnet6-select-test\","
" \"arguments\": {"
" \"remote\": \"fe80::abcd\""
" }"
"}", response);
EXPECT_EQ("{ \"result\": 3, \"text\": \"no subnet selected\" }",
response);
// Address in range: the subnet is selected.
sendUnixCommand("{"
" \"command\": \"subnet6-select-test\","
" \"arguments\": {"
" \"remote\": \"2001:db8:1::1\""
" }"
"}", response);
string expected = "{ \"result\": 0, \"text\": \"";
expected += "selected subnet '2001:db8:1::/64' id 1";
expected += "\" }";
EXPECT_EQ(expected, response);
// Add the subnet to the shared network.
subnet->setSharedNetwork(network);
sendUnixCommand("{"
" \"command\": \"subnet6-select-test\","
" \"arguments\": {"
" \"remote\": \"2001:db8:1::1\""
" }"
"}", response);
expected = "{ \"result\": 0, \"text\": \"";
expected += "selected shared network 'foo' ";
expected += "starting with subnet '2001:db8:1::/64' id 1";
expected += "\" }";
EXPECT_EQ(expected, response);
}
// This test verifies if subnet6-select-test command returns proper subnet for a given
// incoming interface.
TEST_F(CtrlChannelDhcpv6SrvTest, subnet6SelectTestIface) {
createUnixChannelServer();
std::string response;
auto subnet = Subnet6::create(IOAddress("2001:db8:1::"),
64, 1, 2, 3, 4, SubnetID(1));
subnet->setIface("eth0");
SharedNetwork6Ptr network(new SharedNetwork6("foo"));
CfgMgr::instance().clear();
CfgMgr::instance().getStagingCfg()->getCfgSubnets6()->add(subnet);
CfgMgr::instance().getStagingCfg()->getCfgSharedNetworks6()->add(network);
CfgMgr::instance().commit();
// Different interface: nothing can be selected.
sendUnixCommand("{"
" \"command\": \"subnet6-select-test\","
" \"arguments\": {"
" \"interface\": \"bar\""
" }"
"}", response);
EXPECT_EQ("{ \"result\": 3, \"text\": \"no subnet selected\" }",
response);
// Same interface: the subnet is selected.
sendUnixCommand("{"
" \"command\": \"subnet6-select-test\","
" \"arguments\": {"
" \"interface\": \"eth0\""
" }"
"}", response);
string expected = "{ \"result\": 0, \"text\": \"";
expected += "selected subnet '2001:db8:1::/64' id 1";
expected += "\" }";
EXPECT_EQ(expected, response);
// Add the subnet to the shared network.
subnet->setSharedNetwork(network);
sendUnixCommand("{"
" \"command\": \"subnet6-select-test\","
" \"arguments\": {"
" \"interface\": \"eth0\""
" }"
"}", response);
expected = "{ \"result\": 0, \"text\": \"";
expected += "selected shared network 'foo' ";
expected += "starting with subnet '2001:db8:1::/64' id 1";
expected += "\" }";
EXPECT_EQ(expected, response);
}
// This test verifies if subnet6-select-test command returns proper subnet for a given
// relay link address.
TEST_F(CtrlChannelDhcpv6SrvTest, subnet6SelectTestRelayLinkaddr) {
createUnixChannelServer();
std::string response;
auto subnet = Subnet6::create(IOAddress("2001:db8:1::"),
64, 1, 2, 3, 4, SubnetID(1));
SharedNetwork6Ptr network(new SharedNetwork6("foo"));
CfgMgr::instance().clear();
CfgMgr::instance().getStagingCfg()->getCfgSubnets6()->add(subnet);
CfgMgr::instance().getStagingCfg()->getCfgSharedNetworks6()->add(network);
CfgMgr::instance().commit();
// Address not in range: nothing can be selected.
sendUnixCommand("{"
" \"command\": \"subnet6-select-test\","
" \"arguments\": {"
" \"link\": \"2001:db8:2::2\""
" }"
"}", response);
EXPECT_EQ("{ \"result\": 3, \"text\": \"no subnet selected\" }",
response);
// Address in range: the subnet is selected.
sendUnixCommand("{"
" \"command\": \"subnet6-select-test\","
" \"arguments\": {"
" \"link\": \"2001:db8:1::1\""
" }"
"}", response);
string expected = "{ \"result\": 0, \"text\": \"";
expected += "selected subnet '2001:db8:1::/64' id 1";
expected += "\" }";
EXPECT_EQ(expected, response);
// Add the subnet to the shared network.
subnet->setSharedNetwork(network);
sendUnixCommand("{"
" \"command\": \"subnet6-select-test\","
" \"arguments\": {"
" \"link\": \"2001:db8:1::1\""
" }"
"}", response);
expected = "{ \"result\": 0, \"text\": \"";
expected += "selected shared network 'foo' ";
expected += "starting with subnet '2001:db8:1::/64' id 1";
expected += "\" }";
EXPECT_EQ(expected, response);
}
// This test verifies if subnet6-select-test command returns proper subnet for a given
// relay interface id.
TEST_F(CtrlChannelDhcpv6SrvTest, subnet6SelectTestRelayInterfaceId) {
createUnixChannelServer();
std::string response;
auto subnet = Subnet6::create(IOAddress("2001:db8:1::"),
64, 1, 2, 3, 4, SubnetID(1));
string iface_id("relay");
vector<uint8_t> bin(iface_id.cbegin(), iface_id.cend());
OptionPtr id(new Option(Option::V6, D6O_INTERFACE_ID, bin));
subnet->setInterfaceId(id);
SharedNetwork6Ptr network(new SharedNetwork6("foo"));
CfgMgr::instance().clear();
CfgMgr::instance().getStagingCfg()->getCfgSubnets6()->add(subnet);
CfgMgr::instance().getStagingCfg()->getCfgSharedNetworks6()->add(network);
CfgMgr::instance().commit();
// Note that below a relay link address is required: it says the client
// is behind a relay.
// Different interface id: nothing can be selected.
sendUnixCommand("{"
" \"command\": \"subnet6-select-test\","
" \"arguments\": {"
" \"link\": \"2001:db8:2::2\","
" \"interface-id\": \"'foobar'\""
" }"
"}", response);
EXPECT_EQ("{ \"result\": 3, \"text\": \"no subnet selected\" }",
response);
// Same interface id: the subnet is selected.
sendUnixCommand("{"
" \"command\": \"subnet6-select-test\","
" \"arguments\": {"
" \"link\": \"2001:db8:2::2\","
" \"interface-id\": \"'relay'\""
" }"
"}", response);
string expected = "{ \"result\": 0, \"text\": \"";
expected += "selected subnet '2001:db8:1::/64' id 1";
expected += "\" }";
EXPECT_EQ(expected, response);
// Add the subnet to the shared network.
subnet->setSharedNetwork(network);
sendUnixCommand("{"
" \"command\": \"subnet6-select-test\","
" \"arguments\": {"
" \"link\": \"2001:db8:2::2\","
" \"interface-id\": \"'relay'\""
" }"
"}", response);
expected = "{ \"result\": 0, \"text\": \"";
expected += "selected shared network 'foo' ";
expected += "starting with subnet '2001:db8:1::/64' id 1";
expected += "\" }";
EXPECT_EQ(expected, response);
}
// This test verifies if subnet6-select-test command returns proper guarded subnet.
TEST_F(CtrlChannelDhcpv6SrvTest, subnet6SelectTestClass) {
createUnixChannelServer();
std::string response;
auto subnet = Subnet6::create(IOAddress("2001:db8:1::"),
64, 1, 2, 3, 4, SubnetID(1));
subnet->allowClientClass("foobar");
SharedNetwork6Ptr network(new SharedNetwork6("foo"));
CfgMgr::instance().clear();
CfgMgr::instance().getStagingCfg()->getCfgSubnets6()->add(subnet);
CfgMgr::instance().getStagingCfg()->getCfgSharedNetworks6()->add(network);
CfgMgr::instance().commit();
// Address in range but not in guard: nothing can be selected.
sendUnixCommand("{"
" \"command\": \"subnet6-select-test\","
" \"arguments\": {"
" \"remote\": \"2001:db8:1::1\""
" }"
"}", response);
EXPECT_EQ("{ \"result\": 3, \"text\": \"no subnet selected\" }",
response);
// Address in range and in guard: the subnet is selected.
sendUnixCommand("{"
" \"command\": \"subnet6-select-test\","
" \"arguments\": {"
" \"remote\": \"2001:db8:1::1\","
" \"classes\": [ \"foobar\" ]"
" }"
"}", response);
string expected = "{ \"result\": 0, \"text\": \"";
expected += "selected subnet '2001:db8:1::/64' id 1";
expected += "\" }";
EXPECT_EQ(expected, response);
// Add the subnet to the shared network.
subnet->setSharedNetwork(network);
sendUnixCommand("{"
" \"command\": \"subnet6-select-test\","
" \"arguments\": {"
" \"remote\": \"2001:db8:1::1\","
" \"classes\": [ \"foobar\" ]"
" }"
"}", response);
expected = "{ \"result\": 0, \"text\": \"";
expected += "selected shared network 'foo' ";
expected += "starting with subnet '2001:db8:1::/64' id 1";
expected += "\" }";
EXPECT_EQ(expected, response);
}
/// Verify that concurrent connections over the control channel can be
/// established.
/// @todo Future Kea 1.3 tickets will modify the behavior of the CommandMgr
/// such that the server will be able to send response in multiple chunks.
/// This test will need to be extended. For now, the receive and write
/// operations are atomic and there is no conflict between concurrent
/// connections.
TEST_F(CtrlChannelDhcpv6SrvTest, concurrentConnections) {
createUnixChannelServer();
boost::scoped_ptr<UnixControlClient> client1(new UnixControlClient());
ASSERT_TRUE(client1);
boost::scoped_ptr<UnixControlClient> client2(new UnixControlClient());
ASSERT_TRUE(client2);
// Client 1 connects.
ASSERT_TRUE(client1->connectToServer(socket_path_));
ASSERT_NO_THROW(getIOService()->poll());
// Client 2 connects.
ASSERT_TRUE(client2->connectToServer(socket_path_));
ASSERT_NO_THROW(getIOService()->poll());
// Send the command while another client is connected.
ASSERT_TRUE(client2->sendCommand("{ \"command\": \"list-commands\" }"));
ASSERT_NO_THROW(getIOService()->poll());
std::string response;
// The server should respond ok.
ASSERT_TRUE(client2->getResponse(response));
EXPECT_TRUE(response.find("\"result\": 0") != std::string::npos);
// Disconnect the servers.
client1->disconnectFromServer();
client2->disconnectFromServer();
ASSERT_NO_THROW(getIOService()->poll());
}
// This test verifies that the server can receive and process a large command.
TEST_F(CtrlChannelDhcpv6SrvTest, longCommand) {
std::ostringstream command;
// This is the desired size of the command sent to the server (1MB). The
// actual size sent will be slightly greater than that.
const ssize_t command_size = 1024 * 1000;
while (command.tellp() < command_size) {
// We're sending command 'foo' with arguments being a list of
// strings. If this is the first transmission, send command name
// and open the arguments list. Also insert the first argument
// so as all subsequent arguments can be prefixed with a comma.
if (command.tellp() == 0) {
command << "{ \"command\": \"foo\", \"arguments\": [ \"begin\"";
} else {
// Generate a random number and insert it into the stream as
// 10 digits long string.
std::ostringstream arg;
arg << setw(10) << std::rand();
// Append the argument in the command.
command << ", \"" << arg.str() << "\"\n";
// If we have hit the limit of the command size, close braces to
// get appropriate JSON.
if (command.tellp() > command_size) {
command << "] }";
}
}
}
ASSERT_NO_THROW(
CommandMgr::instance().registerCommand("foo",
std::bind(&CtrlChannelDhcpv6SrvTest::longCommandHandler,
command.str(), ph::_1, ph::_2));
);
createUnixChannelServer();
std::string response;
std::thread th([this, &response, &command]() {
// IO service will be stopped automatically when this object goes
// out of scope and is destroyed. This is useful because we use
// asserts which may break the thread in various exit points.
IOServiceWork work(getIOService());
// Create client which we will use to send command to the server.
boost::scoped_ptr<UnixControlClient> client(new UnixControlClient());
ASSERT_TRUE(client);
// Connect to the server. This will trigger acceptor handler on the
// server side and create a new connection.
ASSERT_TRUE(client->connectToServer(socket_path_));
// Initially the remaining_string holds the entire command and we
// will be erasing the portions that we have sent.
std::string remaining_data = command.str();
while (!remaining_data.empty()) {
// Send the command in chunks of 1024 bytes.
const size_t l = remaining_data.size() < 1024 ? remaining_data.size() : 1024;
ASSERT_TRUE(client->sendCommand(remaining_data.substr(0, l)));
remaining_data.erase(0, l);
}
// Set timeout to 5 seconds to allow the time for the server to send
// a response.
const unsigned int timeout = 5;
ASSERT_TRUE(client->getResponse(response, timeout));
// We're done. Close the connection to the server.
client->disconnectFromServer();
});
// Run the server until the command has been processed and response
// received.
getIOService()->run();
// Wait for the thread to complete.
th.join();
EXPECT_EQ("{ \"result\": 0, \"text\": \"long command received ok\" }",
response);
}
// This test verifies that the server can send long response to the client.
TEST_F(CtrlChannelDhcpv6SrvTest, longResponse) {
// We need to generate large response. The simplest way is to create
// a command and a handler which will generate some static response
// of a desired size.
ASSERT_NO_THROW(
CommandMgr::instance().registerCommand("foo",
std::bind(&CtrlChannelDhcpv6SrvTest::longResponseHandler, ph::_1, ph::_2));
);
createUnixChannelServer();
// The UnixControlClient doesn't have any means to check that the entire
// response has been received. What we want to do is to generate a
// reference response using our command handler and then compare
// what we have received over the unix domain socket with this reference
// response to figure out when to stop receiving.
std::string reference_response = longResponseHandler("foo", ConstElementPtr())->str();
// In this stream we're going to collect out partial responses.
std::ostringstream response;
// The client is synchronous so it is useful to run it in a thread.
std::thread th([this, &response, reference_response]() {
// IO service will be stopped automatically when this object goes
// out of scope and is destroyed. This is useful because we use
// asserts which may break the thread in various exit points.
IOServiceWork work(getIOService());
// Remember the response size so as we know when we should stop
// receiving.
const ssize_t long_response_size = reference_response.size();
// Create the client and connect it to the server.
boost::scoped_ptr<UnixControlClient> client(new UnixControlClient());
ASSERT_TRUE(client);
ASSERT_TRUE(client->connectToServer(socket_path_));
// Send the stub command.
std::string command = "{ \"command\": \"foo\", \"arguments\": { } }";
ASSERT_TRUE(client->sendCommand(command));
// Keep receiving response data until we have received the full answer.
while (response.tellp() < long_response_size) {
std::string partial;
const unsigned int timeout = 5;
ASSERT_TRUE(client->getResponse(partial, timeout));
response << partial;
}
// We have received the entire response, so close the connection and
// stop the IO service.
client->disconnectFromServer();
});
// Run the server until the entire response has been received.
getIOService()->run();
// Wait for the thread to complete.
th.join();
// Make sure we have received correct response.
EXPECT_EQ(reference_response, response.str());
}
// This test verifies that the server signals timeout if the transmission
// takes too long, having received a partial command.
TEST_F(CtrlChannelDhcpv6SrvTest, connectionTimeoutPartialCommand) {
createUnixChannelServer();
// Set connection timeout to 2s to prevent long waiting time for the
// timeout during this test.
const unsigned short timeout = 2000;
UnixCommandMgr::instance().setConnectionTimeout(timeout);
// Server's response will be assigned to this variable.
std::string response;
// It is useful to create a thread and run the server and the client
// at the same time and independently.
std::thread th([this, &response]() {
// IO service will be stopped automatically when this object goes
// out of scope and is destroyed. This is useful because we use
// asserts which may break the thread in various exit points.
IOServiceWork work(getIOService());
// Create the client and connect it to the server.
boost::scoped_ptr<UnixControlClient> client(new UnixControlClient());
ASSERT_TRUE(client);
ASSERT_TRUE(client->connectToServer(socket_path_));
// Send partial command. The server will be waiting for the remaining
// part to be sent and will eventually signal a timeout.
std::string command = "{ \"command\": \"foo\" ";
ASSERT_TRUE(client->sendCommand(command));
// Let's wait up to 15s for the server's response. The response
// should arrive sooner assuming that the timeout mechanism for
// the server is working properly.
const unsigned int response_timeout = 15;
ASSERT_TRUE(client->getResponse(response, response_timeout));
// Explicitly close the client's connection.
client->disconnectFromServer();
});
// Run the server until stopped.
getIOService()->run();
// Wait for the thread to return.
th.join();
// Check that the server has signalled a timeout.
EXPECT_EQ("{ \"result\": 1, \"text\": "
"\"Connection over control channel timed out, "
"discarded partial command of 19 bytes\" }", response);
}
// This test verifies that the server signals timeout if the transmission
// takes too long, having received no data from the client.
TEST_F(CtrlChannelDhcpv6SrvTest, connectionTimeoutNoData) {
createUnixChannelServer();
// Set connection timeout to 2s to prevent long waiting time for the
// timeout during this test.
const unsigned short timeout = 2000;
UnixCommandMgr::instance().setConnectionTimeout(timeout);
// Server's response will be assigned to this variable.
std::string response;
// It is useful to create a thread and run the server and the client
// at the same time and independently.
std::thread th([this, &response]() {
// IO service will be stopped automatically when this object goes
// out of scope and is destroyed. This is useful because we use
// asserts which may break the thread in various exit points.
IOServiceWork work(getIOService());
// Create the client and connect it to the server.
boost::scoped_ptr<UnixControlClient> client(new UnixControlClient());
ASSERT_TRUE(client);
ASSERT_TRUE(client->connectToServer(socket_path_));
// Having sent nothing let's just wait and see if Server times us out.
// Let's wait up to 15s for the server's response. The response
// should arrive sooner assuming that the timeout mechanism for
// the server is working properly.
const unsigned int response_timeout = 15;
ASSERT_TRUE(client->getResponse(response, response_timeout));
// Explicitly close the client's connection.
client->disconnectFromServer();
});
// Run the server until stopped.
getIOService()->run();
// Wait for the thread to return.
th.join();
// Check that the server has signalled a timeout.
EXPECT_EQ("{ \"result\": 1, \"text\": "
"\"Connection over control channel timed out\" }", response);
}
} // End of anonymous namespace
|