libstorage 0.4.8

Storage helper functions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
//! Scaleio Definitions:
//! SDS: the SDS is defined as the ScaleIO Data Server. The SDS is
//! the software component that contributes local storage space to an
//! aggregated pool of storage within the ScaleIO virtual SAN.
//! SDC: ScaleIO Data Client. A  lightweight device driver that exposes ScaleIO
//! shared block volumes to applications.
//! MDM: ScaleIO Meta Data Manager.  Manages, configures and monitors the ScaleIO system

/**
* Copyright 2019 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
use crate::deserialize_string_or_int;
use crate::error::{MetricsResult, StorageError};
use crate::ir::{TsPoint, TsValue};
use crate::IntoPoint;

use std::collections::HashMap;
use std::fmt::Debug;
use std::net::IpAddr;
use std::str;

use chrono::offset::Utc;
use chrono::DateTime;
use log::{debug, trace};
use nom::IResult;
use reqwest::header::CONTENT_TYPE;
use serde::de::DeserializeOwned;

#[derive(Clone, Deserialize, Debug)]
pub struct ScaleioConfig {
    /// The scaleio endpoint to use
    pub endpoint: String,
    pub user: String,
    /// This gets replaced with the token at runtime
    pub password: String,
    /// Optional certificate file to use against the server
    /// der encoded
    pub certificate: Option<String>,
    /// The region this cluster is located in
    pub region: String,
    /// bandwidth limits for new volumes in this cluster
    pub bandwidth_limit: Option<u64>,
    /// iops limit for new volumes in this cluster
    pub iops_limit: Option<u64>,
}

pub struct Scaleio {
    client: reqwest::Client,
    config: ScaleioConfig,
}

#[test]
fn test_get_system_config() {
    use std::fs::File;
    use std::io::Read;

    let mut f = File::open("tests/scaleio/system_config.json").unwrap();
    let mut buff = String::new();
    f.read_to_string(&mut buff).unwrap();

    let i: SystemConfig = serde_json::from_str(&buff).unwrap();
    println!("result: {:#?}", i);
}

#[serde(rename_all = "camelCase")]
#[derive(Deserialize, Debug)]
pub struct SystemConfig {
    pub system_id: String,
    pub mdm_port: String,
    pub snmp_resend_frequency: String,
    pub snmp_sampling_frequency: String,
    pub features_enable_snmp: String,
    pub cipher_suites: Option<String>,
    #[serde(rename = "featuresEnableIM")]
    pub features_enable_im: String,
    pub snmp_port: String,
    pub bypass_certificate_check: String,
    pub mdm_username: String,
    pub mdm_addresses: Vec<String>,
    pub snmp_traps_receiver_ips: Option<Vec<String>>,
    pub allow_non_secure_communication: String,
}

// BWC=Bandwidth Calculation
#[serde(rename_all = "camelCase")]
#[derive(Clone, Deserialize, Debug)]
pub struct BWC {
    pub total_weight_in_kb: u64,
    pub num_occured: u64,
    pub num_seconds: u64,
}

impl BWC {
    // Calculate IOPS
    fn iops(self) -> u64 {
        self.num_occured.checked_div(self.num_occured).unwrap_or(0)
    }
    // Calculate Bandwidth
    fn bandwidth(self) -> u64 {
        self.total_weight_in_kb
            .checked_div(self.num_seconds)
            .unwrap_or(0)
    }
    // Calculate IO Size or Latency: totalWeightIn* / numOccured
    fn iosize_or_latency(self) -> u64 {
        self.total_weight_in_kb
            .checked_div(self.num_occured)
            .unwrap_or(0)
    }
    // Calculate the average kb/s from the fields
    fn average(&self) -> u64 {
        let avg = self
            .total_weight_in_kb
            .checked_div(self.num_occured)
            .unwrap_or(0);
        avg.checked_div(self.num_seconds).unwrap_or(0)
    }
}

#[serde(rename_all = "camelCase")]
#[derive(Clone, Deserialize, Debug)]
pub struct CertificateInfo {
    subject: String,
    issuer: String,
    valid_from: String,
    valid_to: String,
    thumbprint: String,
    valid_from_asn1_format: String,
    valid_to_asn1_format: String,
}

#[serde(rename_all = "camelCase")]
#[derive(Clone, Deserialize, Debug, IntoPoint)]
pub struct OscillatingCounterWindow {
    pub threshold: Option<i64>,
    pub window_size_in_sec: Option<i64>,
    pub last_oscillation_count: Option<i64>,
    pub last_oscillationi_time: Option<u64>,
    pub max_failures_count: Option<i64>,
    pub max_failures_time: Option<u64>,
    pub fixed_read_error_count: Option<u64>,
    pub avg_read_size_in_bytes: Option<u64>,
    pub avg_write_size_in_bytes: Option<u64>,
    pub avg_read_latency_in_microsec: Option<u64>,
    pub avg_write_latency_in_microsec: Option<u64>,
    pub capacity_in_use_in_kb: Option<u64>,
    pub thick_capacity_in_use_in_kb: Option<u64>,
    pub thin_capacity_in_use_in_kb: Option<u64>,
    pub snap_capacity_in_use_in_kb: Option<u64>,
    pub snap_capacity_in_use_occupied_in_kb: Option<u64>,
    pub unreachable_unused_capacity_in_kb: Option<u64>,
    pub protected_vac_in_kb: Option<u64>,
    pub degraded_healthy_vac_in_kb: Option<u64>,
    pub degraded_failed_vac_in_kb: Option<u64>,
    pub failed_vac_in_kb: Option<u64>,
    pub in_use_vac_in_kb: Option<u64>,
    pub active_moving_in_fwd_rebuild_jobs: Option<u64>,
    pub pending_moving_in_fwd_rebuild_jobs: Option<u64>,
    pub active_moving_out_fwd_rebuild_jobs: Option<u64>,
    pub pending_moving_out_fwd_rebuild_jobs: Option<u64>,
    pub active_moving_in_bck_rebuild_jobs: Option<u64>,
    pub pending_moving_in_bck_rebuild_jobs: Option<u64>,
    pub active_moving_out_bck_rebuild_jobs: Option<u64>,
    pub pending_moving_out_bck_rebuild_jobs: Option<u64>,
    pub active_moving_in_rebalance_jobs: Option<u64>,
    pub pending_moving_in_rebalance_jobs: Option<u64>,
    pub active_moving_rebalance_jobs: Option<u64>,
    pub pending_moving_rebalance_jobs: Option<u64>,
    pub primary_vac_in_kb: Option<u64>,
    pub secondary_vac_in_kb: Option<u64>,
    pub primary_read_bwc: Option<BWC>,
    pub primary_read_from_dev_bwc: Option<BWC>,
    pub primary_write_bwc: Option<BWC>,
    pub secondary_read_bwc: Option<BWC>,
    pub secondary_read_from_dev_bwc: Option<BWC>,
    pub secondary_write_bwc: Option<BWC>,
    pub total_read_bwc: Option<BWC>,
    pub total_write_bwc: Option<BWC>,
    pub fwd_rebuild_read_bwc: Option<BWC>,
    pub fwd_rebuild_write_bwc: Option<BWC>,
    pub bck_rebuild_read_bwc: Option<BWC>,
    pub bck_rebuild_write_bwc: Option<BWC>,
    pub rebalance_read_bwc: Option<BWC>,
    pub rebalance_write_bwc: Option<BWC>,
    pub background_scan_compare_count: Option<u64>,
    pub background_scanned_in_mb: Option<u64>,
    pub thin_capacity_allocated_in_km: Option<u64>,
    pub rm_pending_allocated_in_kb: Option<u64>,
    pub semi_protected_vac_in_kb: Option<u64>,
    pub in_maintenance_vac_in_kb: Option<u64>,
    pub active_moving_in_norm_rebuild_jobs: Option<u64>,
    pub active_moving_out_norm_rebuild_jobs: Option<u64>,
    pub pending_moving_in_norm_rebuild_jobs: Option<u64>,
    pub pending_moving_out_normrebuild_jobs: Option<u64>,
    pub primary_read_from_rmcache_bwc: Option<BWC>,
    pub secondary_read_from_rmcache_bwc: Option<BWC>,
    pub norm_rebuild_read_bwc: Option<BWC>,
    pub norm_rebuild_write_bwc: Option<BWC>,
    pub rfcache_reads_received: Option<u64>,
    pub rfcache_writes_received: Option<u64>,
    pub rfcache_avg_read_time: Option<u64>,
    pub rfcache_avg_write_time: Option<u64>,
    pub rfcache_source_device_reads: Option<u64>,
    pub rfcache_source_device_writes: Option<u64>,
    pub rfache_read_hit: Option<u64>,
    pub rfcache_read_miss: Option<u64>,
    pub rfcache_write_miss: Option<u64>,
    pub rfcache_ios_skipped: Option<u64>,
    pub rfcache_reads_skipped: Option<u64>,
    pub rfcache_reads_skipped_aligned_size_too_large: Option<u64>,
    pub rfcache_reads_skipped_max_io_size: Option<u64>,
    pub rfcache_reads_skipped_heavy_load: Option<u64>,
    pub rfcache_reads_skipped_stuck_io: Option<u64>,
    pub rfcache_reads_skipped_low_resources: Option<u64>,
    pub rfcache_reads_skipped_internal_error: Option<u64>,
    pub rfcache_reads_skipped_lock_ios: Option<u64>,
    pub rfcache_writes_skipped_max_io_size: Option<u64>,
    pub rfcache_writes_skipped_heavy_load: Option<u64>,
    pub rfcache_writes_skipped_stuck_io: Option<u64>,
    pub rfcache_writes_skipped_low_resources: Option<u64>,
    pub rfcache_writes_skipped_internal_error: Option<u64>,
    pub rfcache_writes_skipped_cache_miss: Option<u64>,
    pub rfcache_skipped_unlined_write: Option<u64>,
    pub rfcache_io_errors: Option<u64>,
    pub rfcache_reads_from_cache: Option<u64>,
    pub rfcache_ios_outstanding: Option<u64>,
    pub rfcache_reads_pending: Option<u64>,
    pub rfcache_write_pending: Option<u64>,
}

#[serde(rename_all = "camelCase")]
#[derive(Clone, Deserialize, Debug)] 
pub struct FailureCounter {
    pub short_window: Window,
    pub medium_window: Option<Window>,
    pub long_window: Option<Window>,
}

#[serde(rename_all = "camelCase")]
#[derive(Clone, Deserialize, Debug)] // v3 look for OscillatingCounter
pub struct Successfulio {
    pub short_window: Option<OscillatingCounterWindow>,
    pub medium_window: Option<OscillatingCounterWindow>,
    pub long_window: Option<OscillatingCounterWindow>,
}

#[derive(Clone, Deserialize, Debug)]
pub struct Link {
    pub rel: String,
    pub href: String,
}

#[derive(Deserialize, Debug)]
pub enum AuthenticationError {
    None,
    General,
    ErrorLoadingOpenssl,
    ErrorLoadingCertificate,
    VerificationError,
    ErrorLoadingAuthenticationInMdm,
    Open,
    #[serde(rename = "sslVerionTooLong")]
    SslVerionTooLong,
}

impl ToString for AuthenticationError {
    fn to_string(&self) -> String {
        match *self {
            AuthenticationError::None => "None".into(),
            AuthenticationError::General => "General".into(),
            AuthenticationError::ErrorLoadingOpenssl => "ErrorLoadingOpenssl".into(),
            AuthenticationError::ErrorLoadingCertificate => "ErrorLoadingCertificiate".into(),
            AuthenticationError::VerificationError => "VerificationError".into(),
            AuthenticationError::ErrorLoadingAuthenticationInMdm => {
                "ErrorLoadingAuthenticationInMdm".into()
            }
            AuthenticationError::Open => "Open".into(),
            AuthenticationError::SslVerionTooLong => "SslVersionTooLong".into(),
        }
    }
}

#[derive(Clone, Deserialize, Debug)]
pub enum DeviceState {
    DeviceInit,
    DeviceRecovery,
    InitialTest,
    InitialTestDone,
    Normal,
    NormalTesting,
    RemovePending,
}

impl ToString for DeviceState {
    fn to_string(&self) -> String {
        match *self {
            DeviceState::DeviceInit => "DeviceInit".into(),
            DeviceState::DeviceRecovery => "DeviceRecovery".into(),
            DeviceState::InitialTest => "InitialTest".into(),
            DeviceState::InitialTestDone => "InitialTestDone".into(),
            DeviceState::Normal => "Normal".into(),
            DeviceState::NormalTesting => "NormalTesting".into(),
            DeviceState::RemovePending => "RemovePending".into(),
        }
    }
}

#[test]
fn test_scaleio_drive_stats() {
    use std::fs::File;
    use std::io::Read;

    let mut f = File::open("tests/scaleio/device_statistics.json").unwrap();
    let mut buff = String::new();
    f.read_to_string(&mut buff).unwrap();

    let i: DeviceStatistics = serde_json::from_str(&buff).unwrap();
    let points = i.into_point(Some("scaleio_device"), true);
    println!("result: {:#?}", i);
    println!("points: {:?}", points);
}

#[derive(Debug, Clone)]
// Not an API structure, this struct exists for mapping purposes
pub struct DriveId {
    id: String,              //device id
    sds_id: String,          // sds id
    storage_pool_id: String, // storage pool id
}

#[serde(rename_all = "camelCase")]
#[derive(Deserialize, Debug)]
pub struct DeviceStatistics {
    avg_write_size_in_bytes: u64,             // in v3
    active_moving_in_fwd_rebuild_jobs: u64,   // in v3
    active_moving_in_rebalance_jobs: u64,     // in v3
    active_moving_out_bck_rebuild_jobs: u64,  // in v3
    active_moving_out_fwd_rebuild_jobs: u64,  // in v3
    active_moving_rebalance_jobs: u64,        // in v3
    active_moving_in_norm_rebuild_jobs: u64,  // in v3
    active_moving_in_bck_rebuild_jobs: u64,   // in v3
    active_moving_out_norm_rebuild_jobs: u64, // in v3
    avg_read_latency_in_microsec: u64,        // in v3
    avg_write_latency_in_microsec: u64,       // in v3
    avg_read_size_in_bytes: u64,              // in v3
    #[serde(rename = "BackgroundScanCompareCount")]
    background_scan_compare_count: u64, // in v3
    #[serde(rename = "BackgroundScannedInMB")]
    background_scanned_in_mb: u64, // in v3
    bck_rebuild_write_bwc: BWC,               // in v3
    bck_rebuild_read_bwc: BWC,                // in v3
    capacity_in_use_in_kb: u64,               // in v3
    capacity_in_use_no_overhead_in_kb: Option<u64>, // NEW V3
    capacity_limit_in_kb: Option<u64>,        // NEW V3
    changelog_destage_completion_percent: Option<u64>, // NEW V3
    checksum_calculation_completion_percent: Option<u64>, // NEW V3
    checksum_capacity_in_kb: Option<u64>,     // NEW v3
    checksum_migration_completion_percent: Option<u64>, // NEW V3
    compressed_data_compression_ratio: Option<f64>, // NEW V3
    compression_ratio: Option<f64>,           // NEW V3
    #[serde(rename = "currentChecksumMigrationSizeInKB")]
    current_checksum_migration_size_in_kb: Option<u64>, // NEW V3
    current_checksum_protected_combs_num: Option<u64>, // NEW V3
    current_fgl_migration_size_in_kb: Option<u64>, // NEW V3
    degraded_healthy_vac_in_kb: u64,          // in v3
    degraded_failed_vac_in_kb: u64,           // in v3
    failed_vac_in_kb: u64,                    // in v3
    fgl_uncompressed_data_size_in_kb: Option<u64>, // NEW V3
    fgl_compressed_data_size_in_kb: Option<u64>, // NEW V3
    fgl_spares_in_kb: Option<u64>,            // NEW V3
    fgl_migration_completion_percent: Option<u64>, // NEW V3
    fgl_user_data_capacity_in_kb: Option<u64>, // NEW V3
    fixed_read_error_count: u64,              //in v3
    fwd_rebuild_read_bwc: BWC,                // in v3
    fwd_rebuild_write_bwc: BWC,               // in v3
    in_maintenance_vac_in_kb: u64,            // in v3
    in_use_vac_in_kb: u64,                    // in v3
    log_written_blocks_in_kb: Option<u64>,    // NEW v3
    max_capacity_in_kb: Option<u64>,          // NEW v3
    max_user_data_capacity_in_kb: Option<u64>, // NEW V3
    metadata_overhead_in_kb: Option<u64>,     // NEW V3
    mg_user_ddata_ccapacity_in_kb: Option<u64>, // NEW V3
    net_capacity_in_use_in_kb: Option<u64>,   // NEW V3
    net_capacity_in_use_no_overhead_in_kb: Option<u64>, // NEW V3
    net_fgl_compressed_data_size_in_kb: Option<u64>, // NEW V3
    net_fgl_spares_in_kb: Option<u64>,        // NEW V3
    net_fgl_uncompressed_data_size_in_kb: Option<u64>, // NEW V3
    net_fgl_user_data_capacity_in_kb: Option<u64>, // NEW V3
    net_max_user_data_capacity_in_kb: Option<u64>, // NEW V3
    net_metadata_overhead_in_kb: Option<u64>, // NEW V3
    net_mg_user_data_capacity_in_kb: Option<u64>, // NEW V3
    net_provisioned_addresses_in_kb: Option<u64>, // NEW V3
    net_snapshot_capacity_in_kb: Option<u64>, // NEW V3
    net_trimmed_user_data_capacity_in_kb: Option<u64>, // NEW V3
    net_unused_capacity_in_kb: Option<u64>,   // NEW V3
    net_user_data_capacity_in_kb: Option<u64>, // NEW V3
    net_user_data_capacity_no_trim_in_kb: Option<u64>, // NEW V3
    norm_rebuild_read_bwc: BWC,               // in v3
    norm_rebuild_write_bwc: BWC,              // in v3
    num_changelog_records_left_to_destage: Option<u64>, // NEW V3
    pending_moving_in_bck_rebuild_jobs: u64,  // in v3
    pending_moving_out_bck_rebuild_jobs: u64, // in v3
    pending_moving_in_norm_rebuild_jobs: u64, // in v3
    pending_moving_rebalance_jobs: u64,       // in v3
    pending_moving_out_normrebuild_jobs: u64, // in v3
    pending_moving_in_rebalance_jobs: u64,    // in v3
    pending_moving_in_fwd_rebuild_jobs: u64,  // in v3
    pending_moving_out_fwd_rebuild_jobs: u64, // in v3
    primary_read_from_rmcache_bwc: BWC,       // in v3
    primary_read_from_dev_bwc: BWC,           // in v3
    primary_read_bwc: BWC,                    // in v3
    primary_vac_in_kb: u64,                   // in v3
    protected_vac_in_kb: u64,                 // in v3
    primary_write_bwc: BWC,                   // in v3
    rebalance_read_bwc: BWC,                  // in v3
    rebalance_write_bwc: BWC,                 // in v3
    rfcache_avg_read_time: u64,               // in v3
    rfcache_io_errors: u64,                   // in v3
    rfcache_reads_skipped_internal_error: u64, // in v3
    rfcache_source_device_writes: u64,        // in v3
    rfcache_reads_skipped_low_resources: u64, // in v3
    rfcache_reads_skipped_max_io_size: u64,   // in v3
    rfcache_reads_skipped_aligned_size_too_large: u64, // in v3
    rfcache_writes_skipped_internal_error: u64, // in v3
    rfcache_writes_skipped_stuck_io: u64,     // in v3
    rfcache_writes_skipped_cache_miss: u64,   // in v3
    rfcache_writes_skipped_heavy_load: u64,   // in v3
    rfcache_write_miss: u64,                  // in v3
    rfcache_writes_skipped_low_resources: u64, // in v3
    rfcache_reads_from_cache: u64,            // in v3
    rfcache_ios_outstanding: u64,             // in v3
    rfcache_skipped_unlined_write: u64,       // in v3
    rfcache_writes_received: u64,             // in v3
    rfcache_write_pending: u64,               // in v3
    rfcache_writes_skipped_max_io_size: u64,  // in v3
    rfcache_reads_skipped_stuck_io: u64,      // in v3
    rfcache_reads_skipped: u64,               // in v3
    rfcache_reads_received: u64,              // in v3
    rfcache_ios_skipped: u64,                 // in v3
    rfcache_read_miss: u64,                   // in v3
    rfcache_reads_skipped_lock_ios: u64,      // in v3
    rfache_read_hit: u64,                     // in v3
    rfcache_avg_write_time: u64,              // in v3
    rfcache_source_device_reads: u64,         // in v3
    rfcache_reads_skipped_heavy_load: u64,    // in v3
    rfcache_reads_pending: u64,               // in v3
    rfcache_fd_reads_recieved: Option<u64>,   // NEW V3
    rfcache_fd_writes_recieved: Option<u64>,  // NEW V3
    rfcache_fd_inlight_reads: Option<u64>,    // NEW V3
    rfcache_fd_inlight_writes: Option<u64>,   // NEW V3
    rfcache_fd_read_time_greater500_millis: Option<u64>, // NEW V3
    rfcache_fd_read_time_greater1_sec: Option<u64>, // NEW V3
    rfcache_fd_read_time_greater5_sec: Option<u64>, // NEW V3
    rfcache_fd_read_time_greater1_min: Option<u64>, // NEW V3
    rfcache_fd_write_time_greater500_millis: Option<u64>, // NEW V3
    rfcache_fd_write_time_greater1_sec: Option<u64>, // NEW V3
    rfcache_fd_write_time_greater5_sec: Option<u64>, // NEW V3
    rfcache_fd_write_time_greater1_min: Option<u64>, // NEW V3
    rfcache_fd_avg_read_time: Option<u64>,    // NEW V3
    rfcache_fd_avg_write_time: Option<u64>,   // NEW V3
    rfcache_fd_io_errors: Option<u64>,        // NEW V3
    rfcache_fd_cache_overloaded: Option<u64>, // NEW V3
    rfcache_fd_monitor_error_stuck_io: Option<u64>, // NEW V3
    rm_pending_allocated_in_kb: u64,          // in v3
    rm_pending_thick_in_kb: Option<u64>,      // NEW v3
    secondary_read_from_dev_bwc: BWC,         // in v3
    secondary_vac_in_kb: u64,                 // in v3
    secondary_read_bwc: BWC,                  // in v3
    secondary_read_from_rmcache_bwc: BWC,     // in v3
    secondary_write_bwc: BWC,                 // in v3
    semi_protected_vac_in_kb: u64,            // in v3
    snap_capacity_in_use_occupied_in_kb: u64, // in v3
    snap_capacity_in_use_in_kb: u64,          //in v3
    snapshot_capacity_in_kb: Option<u64>,     // NEW V3
    temp_capacity_vac_in_kb: Option<u64>,     // NEW v3
    thick_capacity_in_use_in_kb: u64,         // in v3
    thin_capacity_in_use_in_kb: u64,          // in v3
    thin_capacity_allocated_in_km: u64,       // in v3
    total_changelog_records_to_destage: Option<u64>, // NEW V3
    #[serde(rename = "totalChecksumMigrationSizeInKB")]
    total_checksum_migration_size_in_kb: Option<u64>, // NEW V3
    total_checksum_protected_combs_num: Option<u64>, // NEW V3
    total_fgl_migration_size_in_kb: Option<u64>, // NEW V3
    total_read_bwc: BWC,                      // in v3
    total_write_bwc: BWC,                     // in v3
    trimmed_user_data_capacity_in_kb: Option<u64>, // NEW V3
    unused_capacity_in_kb: u64,
    unreachable_unused_capacity_in_kb: u64,        // in v3
    user_data_capacity_in_kb: Option<u64>,         // NEW V3
    user_data_capacity_no_trim_in_kb: Option<u64>, // NEW V3
    vol_migration_read_bwc: Option<BWC>,           // NEW V3
    vol_migration_write_bwc: Option<BWC>,          // NEW V3
}

impl IntoPoint for DeviceStatistics {
    fn into_point(&self, name: Option<&str>, is_time_series: bool) -> Vec<TsPoint> {
        let mut p = TsPoint::new(name.unwrap_or("scaleio_drive_stat"), is_time_series);
        p.add_field(
            "avg_write_size_in_bytes",
            TsValue::Long(self.avg_write_size_in_bytes),
        );
        p.add_field(
            "avg_read_latency_in_microsec",
            TsValue::Long(self.avg_read_latency_in_microsec),
        );
        p.add_field(
            "avg_write_latency_in_microsec",
            TsValue::Long(self.avg_write_latency_in_microsec),
        );
        p.add_field(
            "avg_read_size_in_bytes",
            TsValue::Long(self.avg_read_size_in_bytes),
        );
        p.add_field(
            "capacity_in_use_in_kb",
            TsValue::Long(self.capacity_in_use_in_kb),
        );
        p.add_field(
            "degraded_healthy_vac_in_kb",
            TsValue::Long(self.degraded_healthy_vac_in_kb),
        );
        p.add_field(
            "degraded_failed_vac_in_kb",
            TsValue::Long(self.degraded_failed_vac_in_kb),
        );
        // not in use
        p.add_field(
            "primary_read_bwc",
            TsValue::Long(self.primary_read_bwc.total_weight_in_kb),
        );
        p.add_field(
            "primary_read_bwc_total_weight_in_kb",
            TsValue::Long(self.primary_read_bwc.total_weight_in_kb),
        );
        p.add_field(
            "primary_read_bwc_num_seconds",
            TsValue::Long(self.primary_read_bwc.num_seconds),
        );
        p.add_field(
            "primary_read_bwc_num_occured",
            TsValue::Long(self.primary_read_bwc.num_occured),
        );
        p.add_field("primary_vac_in_kb", TsValue::Long(self.primary_vac_in_kb));
        p.add_field(
            "protected_vac_in_kb",
            TsValue::Long(self.protected_vac_in_kb),
        );
        //Not in use
        p.add_field(
            "primary_write_bwc",
            TsValue::Long(self.primary_write_bwc.total_weight_in_kb),
        );
        p.add_field(
            "primary_write_bwc_total_weight_in_kb",
            TsValue::Long(self.primary_write_bwc.total_weight_in_kb),
        );
        p.add_field(
            "primary_write_bwc_num_seconds",
            TsValue::Long(self.primary_write_bwc.num_seconds),
        );
        p.add_field(
            "primary_write_bwc_num_occured",
            TsValue::Long(self.primary_write_bwc.num_occured),
        );

        p.add_field(
            "thick_capacity_in_use_in_kb",
            TsValue::Long(self.thick_capacity_in_use_in_kb),
        );
        p.add_field(
            "thin_capacity_in_use_in_kb",
            TsValue::Long(self.thin_capacity_in_use_in_kb),
        );
        p.add_field(
            "thin_capacity_allocated_in_km",
            TsValue::Long(self.thin_capacity_allocated_in_km),
        );
        p.add_field(
            "total_read_bwc",
            TsValue::Long(self.total_read_bwc.total_weight_in_kb),
        );
        p.add_field(
            "total_read_bwc_total_weight_in_kb",
            TsValue::Long(self.total_read_bwc.total_weight_in_kb),
        );
        p.add_field(
            "total_read_bwc_num_seconds",
            TsValue::Long(self.total_read_bwc.num_seconds),
        );
        p.add_field(
            "total_read_bwc_num_occured",
            TsValue::Long(self.total_read_bwc.num_occured),
        );

        //not used
        p.add_field(
            "total_write_bwc",
            TsValue::Long(self.total_write_bwc.total_weight_in_kb),
        );
        p.add_field(
            "total_write_bwc_total_weight_in_kb",
            TsValue::Long(self.total_write_bwc.total_weight_in_kb),
        );
        p.add_field(
            "total_write_bwc_num_seconds",
            TsValue::Long(self.total_write_bwc.num_seconds),
        );
        p.add_field(
            "total_write_bwc_num_occured",
            TsValue::Long(self.total_write_bwc.num_occured),
        );

        p.add_field(
            "unused_capacity_in_kb",
            TsValue::Long(self.unused_capacity_in_kb),
        );
        p.add_field(
            "unreachable_unused_capacity_in_kb",
            TsValue::Long(self.unreachable_unused_capacity_in_kb),
        );
        //not used
        p.add_field(
            "rebalance_read_bwc",
            TsValue::Long(self.rebalance_read_bwc.total_weight_in_kb),
        );
        p.add_field(
            "rebalance_read_bwc_total_weight_in_kb",
            TsValue::Long(self.rebalance_read_bwc.total_weight_in_kb),
        );
        p.add_field(
            "rebalance_read_bwc_num_seconds",
            TsValue::Long(self.rebalance_read_bwc.num_seconds),
        );
        p.add_field(
            "rebalance_read_bwc_num_occured",
            TsValue::Long(self.rebalance_read_bwc.num_occured),
        );
        // not used
        p.add_field(
            "rebalance_write_bwc",
            TsValue::Long(self.rebalance_write_bwc.total_weight_in_kb),
        );
        p.add_field(
            "rebalance_write_bwc_total_weight_in_kb",
            TsValue::Long(self.rebalance_write_bwc.total_weight_in_kb),
        );
        p.add_field(
            "rebalance_write_bwc_num_seconds",
            TsValue::Long(self.rebalance_write_bwc.num_seconds),
        );
        p.add_field(
            "rebalance_write_bwc_num_occured",
            TsValue::Long(self.rebalance_write_bwc.num_occured),
        );

        // not used
        p.add_field(
            "secondary_read_from_dev_bwc",
            TsValue::Long(self.secondary_read_from_dev_bwc.total_weight_in_kb),
        );
        p.add_field(
            "secondary_read_from_dev_bwc_total_weight_in_kb",
            TsValue::Long(self.secondary_read_from_dev_bwc.total_weight_in_kb),
        );
        p.add_field(
            "secondary_read_from_dev_bwc_num_seconds",
            TsValue::Long(self.secondary_read_from_dev_bwc.num_seconds),
        );
        p.add_field(
            "secondary_read_from_dev_bwc_num_occured",
            TsValue::Long(self.secondary_read_from_dev_bwc.num_occured),
        );

        p.add_field(
            "secondary_vac_in_kb",
            TsValue::Long(self.secondary_vac_in_kb),
        );
        //not used
        p.add_field(
            "secondary_read_bwc",
            TsValue::Long(self.secondary_read_bwc.total_weight_in_kb),
        );
        p.add_field(
            "secondary_read_bwc_total_weight_in_kb",
            TsValue::Long(self.secondary_read_bwc.total_weight_in_kb),
        );
        p.add_field(
            "secondary_read_bwc_num_seconds",
            TsValue::Long(self.secondary_read_bwc.num_seconds),
        );
        p.add_field(
            "secondary_read_bwc_num_occured",
            TsValue::Long(self.secondary_read_bwc.num_occured),
        );

        //not used
        p.add_field(
            "secondary_read_from_rmcache_bwc",
            TsValue::Long(self.secondary_read_from_rmcache_bwc.total_weight_in_kb),
        );
        p.add_field(
            "secondary_read_from_rmcache_bwc_total_weight_in_kb",
            TsValue::Long(self.secondary_read_from_rmcache_bwc.total_weight_in_kb),
        );
        p.add_field(
            "secondary_read_from_rmcache_bwc_num_seconds",
            TsValue::Long(self.secondary_read_from_rmcache_bwc.num_seconds),
        );
        p.add_field(
            "secondary_read_from_rmcache_bwc_num_occured",
            TsValue::Long(self.secondary_read_from_rmcache_bwc.num_occured),
        );
        //not used
        p.add_field(
            "secondary_write_bwc",
            TsValue::Long(self.secondary_write_bwc.total_weight_in_kb),
        );
        p.add_field(
            "secondary_write_bwc_total_weight_in_kb",
            TsValue::Long(self.secondary_write_bwc.total_weight_in_kb),
        );
        p.add_field(
            "secondary_write_bwc_num_seconds",
            TsValue::Long(self.secondary_write_bwc.num_seconds),
        );
        p.add_field(
            "secondary_write_bwc_num_occured",
            TsValue::Long(self.secondary_write_bwc.num_occured),
        );

        vec![p]
    }
}

#[derive(Deserialize, Debug)]
pub enum DrlMode {
    Volatile,
    NonVolatile,
}

impl ToString for DrlMode {
    fn to_string(&self) -> String {
        match *self {
            DrlMode::Volatile => "Volatile".into(),
            DrlMode::NonVolatile => "NonVolatile".into(),
        }
    }
}

#[derive(Deserialize, Debug)]
pub enum IpRole {
    #[serde(rename = "sdsOnly")]
    SdsOnly,
    #[serde(rename = "sdcOnly")]
    SdcOnly,
    #[serde(rename = "all")]
    All,
}

#[derive(Deserialize, Debug)]
pub enum MembershipState {
    JoinPending,
    Joined,
    Decoupled,
}

impl ToString for MembershipState {
    fn to_string(&self) -> String {
        match *self {
            MembershipState::JoinPending => "JoinPending".into(),
            MembershipState::Joined => "Joined".into(),
            MembershipState::Decoupled => "Decoupled".into(),
        }
    }
}

#[derive(Deserialize, Debug)]
pub enum MaintenanceState {
    NoMaintenance,
    SetMaintenanceInProgress,
    InMaintenance,
    ExitMaintenanceInProgress,
}

impl ToString for MaintenanceState {
    fn to_string(&self) -> String {
        match *self {
            MaintenanceState::NoMaintenance => "NoMaintenance".into(),
            MaintenanceState::SetMaintenanceInProgress => "SetMaintenanceInProgress".into(),
            MaintenanceState::InMaintenance => "Inmaintenance".into(),
            MaintenanceState::ExitMaintenanceInProgress => "ExitMaintenanceInProgress".into(),
        }
    }
}

#[derive(Deserialize, Debug)]
pub enum MdmConnectionState {
    Connected,
    Disconnected,
}

impl ToString for MdmConnectionState {
    fn to_string(&self) -> String {
        match *self {
            MdmConnectionState::Connected => "Connected".into(),
            MdmConnectionState::Disconnected => "Disconnected".into(),
        }
    }
}

#[derive(Deserialize, Debug)]
// This is the RmcacheMemoryAllocationState in V3
pub enum MemoryAllocationState {
    RmcacheMemoryAllocationStateInvalid,
    AllocationPending,
    AllocationSuccessful,
    AllocationFailed,
    RmcacheDisabled,
}

impl ToString for MemoryAllocationState {
    fn to_string(&self) -> String {
        match *self {
            MemoryAllocationState::RmcacheMemoryAllocationStateInvalid => {
                "RmcacheMemoryAllocationStateInvalid".into()
            }
            MemoryAllocationState::AllocationPending => "AllocationPending".into(),
            MemoryAllocationState::AllocationSuccessful => "AllocationSuccessful".into(),
            MemoryAllocationState::AllocationFailed => "AllocationFailed".into(),
            MemoryAllocationState::RmcacheDisabled => "RmcacheDisabled".into(),
        }
    }
}

#[derive(Deserialize, Debug)]
pub enum PerfProfile {
    Compact, // new to V3
    Custom,
    Default,
    HighPerformance,
}

impl ToString for PerfProfile {
    fn to_string(&self) -> String {
        match *self {
            PerfProfile::Compact => "Compact".into(),
            PerfProfile::Custom => "Custom".into(),
            PerfProfile::Default => "Default".into(),
            PerfProfile::HighPerformance => "HighPerformance".into(),
        }
    }
}

#[test]
fn test_instances() {
    use std::fs::File;
    use std::io::Read;

    let mut f = File::open("tests/scaleio/instances.json").unwrap();
    let mut buff = String::new();
    f.read_to_string(&mut buff).unwrap();

    let i: Vec<Instance> = serde_json::from_str(&buff).unwrap();
    println!("result: {:#?}", i);
}

#[test]
fn test_selected_stats() {
    use std::fs::File;
    use std::io::Read;

    // Test drive stats response
    let mut f = File::open("tests/scaleio/querySelectedStatistics.json").unwrap();
    let mut buff = String::new();
    f.read_to_string(&mut buff).unwrap();

    let i: DeviceSelectedStatisticsResponse = serde_json::from_str(&buff).unwrap();
    println!("result: {:#?}", i);

    // Test cluster stats response
    let mut f = File::open("tests/scaleio/clusterSelectedStatisticsResponse.json").unwrap();
    let mut buff = String::new();
    f.read_to_string(&mut buff).unwrap();

    let i: ClusterSelectedStatisticsResponse = serde_json::from_str(&buff).unwrap();
    println!("result: {:#?}", i);

    // Test sdcstats response
    let mut f = File::open("tests/scaleio/sdcSelectedStatisticsResponse.json").unwrap();
    let mut buff = String::new();
    f.read_to_string(&mut buff).unwrap();

    let i: SdcSelectedStatisticsResponse = serde_json::from_str(&buff).unwrap();
    println!("result: {:#?}", i);
    let all_sdc_stats = i.into_point(Some("scaleio_sdc_stats"), true);
    println!("points: {:#?}", all_sdc_stats);
}

#[derive(Deserialize, Debug)]
pub struct DeviceSelectedStatisticsResponse {
    #[serde(rename = "Device")]
    pub device: HashMap<String, HashMap<String, u64>>,
}

#[derive(Deserialize, Debug)]
pub struct ClusterSelectedStatisticsResponse {
    #[serde(rename = "StoragePool")]
    pub storage_pool: HashMap<String, StoragePoolInfo>,
}

#[serde(rename_all = "camelCase")]
#[derive(Deserialize, Debug, IntoPoint)]
pub struct StoragePoolInfo {
    // StoragePoolStatistics (selected ones)
    pub num_of_devices: u64,
    pub num_of_volumes: u64,
    pub primary_read_bwc: BWC,
    pub primary_write_bwc: BWC,
    pub secondary_write_bwc: BWC,
    pub secondary_read_bwc: BWC,
    pub capacity_limit_in_kb: u64,
    pub thick_capacity_in_use_in_kb: u64,
    pub thin_capacity_in_use_in_kb: u64,
    pub thin_capacity_allocated_in_km: u64,
    pub total_write_bwc: BWC,
    pub total_read_bwc: BWC,
}

#[derive(Deserialize, Debug)]
pub struct SdcSelectedStatisticsResponse {
    #[serde(rename = "Sdc")]
    pub sdc: HashMap<String, SdcStatsInfo>,
}

impl IntoPoint for SdcSelectedStatisticsResponse {
    fn into_point(&self, name: Option<&str>, is_time_series: bool) -> Vec<TsPoint> {
        let mut all_sdc_stats: Vec<TsPoint> = Vec::new();
        for (key, value) in self.sdc.iter() {
            let point: Vec<TsPoint> = value
                .into_point(name, is_time_series)
                .iter_mut()
                .map(|p| {
                    p.add_tag("sdc_id", TsValue::String(key.to_string()));
                    p.clone()
                })
                .collect();
            all_sdc_stats.extend(point);
        }
        all_sdc_stats
    }
}

#[serde(rename_all = "camelCase")]
#[derive(Deserialize, Debug, IntoPoint)]
pub struct SdcStatsInfo {
    pub user_data_read_bwc: BWC,
    pub user_data_write_bwc: BWC,
    pub user_data_trim_bwc: Option<BWC>,          // in v2 and v3
    pub user_data_sdc_read_latency: Option<BWC>,  // NEW V3
    pub user_data_sdc_write_latency: Option<BWC>, // NEW V3
    pub user_data_sdc_trim_latency: Option<BWC>,  // NEW V3
    pub volume_ids: Vec<String>,
    pub num_of_mapped_volumes: u64,
}

#[serde(rename_all = "camelCase")]
#[derive(Clone, Deserialize, Debug, IntoPoint)]
pub struct Instance {
    // Device Object
    pub device_current_path_name: String,  // in v3
    pub device_original_path_name: String, // in v3
    pub rfcache_error_device_does_not_exist: bool,
    pub sds_id: String,
    pub device_state: DeviceState,         // in v3
    pub capacity_limit_in_kb: Option<u64>, // in v3
    pub max_capacity_in_kb: u64,           // in v3
    pub storage_pool_id: String,           // in v3 ** required
    pub long_successful_ios: Option<Successfulio>,
    pub error_state: String,  // in v3 (note this could be an enum)
    pub name: Option<String>, // in v3
    pub id: String,           // in v3
    pub links: Vec<Link>,
    pub update_configuration: Option<bool>,
    pub vendor_name: Option<String>,      // NEW V3
    pub firmware_version: Option<String>, //NEW V3
    pub raid_controller_serial_number: Option<String>, // NEW V3
                                          // SDS object....
}

#[serde(rename_all = "camelCase")]
#[derive(Debug, Deserialize)]
pub struct MdmCluster {
    pub master: TieBreaker,            //
    pub slaves: Vec<TieBreaker>,       //
    pub cluster_mode: String,          //
    pub tie_breakers: Vec<TieBreaker>, //
    #[serde(rename = "standbyMDMs")]
    pub standby_mdms: Option<Vec<TieBreaker>>, // NEW V3
    pub good_nodes_num: u16,           //
    pub good_replicas_num: u16,        //
    pub cluster_state: String,         //
    pub name: String,                  //
    pub id: String,                    //
    pub virtual_ip: Option<Vec<String>>, // NEW V3
}

#[serde(rename_all = "camelCase")]
#[derive(Serialize, Debug)]
pub struct SelectedStatisticsRequest {
    pub selected_statistics_list: Vec<StatsRequest>,
}

#[derive(Serialize, Debug)]
pub enum StatsRequestType {
    System,
    ProtectionDomain,
    Sds,
    StoragePool,
    Device,
    Volume,
    VTree,
    Sdc,
    FaultSet,
    RfcacheDevice,
}

#[derive(Debug, Deserialize)]
pub enum RebuildIoPriority {
    #[serde(rename = "unlimited")]
    Unlimited,
    #[serde(rename = "limitNumOfConcurrentIos")]
    LimitNumOfConcurrentIos,
    #[serde(rename = "favorAppIos")]
    FavorAppIos,
    #[serde(rename = "dynamicBwThrottling")]
    DynamicBwThrottling,
}

#[derive(Debug, Deserialize)]
pub enum BackgroundScannerMode {
    Disabled,
    DeviceOnly,
    DataComparison,
}

#[derive(Debug, Deserialize)]
pub enum CacheWriteHandlingMode {
    Passthrough,
    Cached,
}

#[serde(rename_all = "camelCase")]
#[derive(Serialize, Debug)]
pub struct StatsRequest {
    #[serde(rename = "type")]
    pub req_type: StatsRequestType,
    // This can be left blank for all ids
    pub all_ids: Vec<String>,
    // "fixedReadErrorCount", "avgReadSizeInBytes", "avgWriteSizeInBytes",
    //
    pub properties: Vec<String>,
}

#[derive(Debug, Deserialize)]
pub struct IpObject {
    pub ip: IpAddr,
    pub role: IpRole,
}

#[serde(rename_all = "camelCase")]
#[derive(Debug, Deserialize, IntoPoint)]
pub struct ScsiInitiatorMappingInfo {
    pub scsi_initiator_id: String,
    pub scsi_initiator_name: String,
    pub scsi_initiator_iqn: String,
    pub lun: String,
}

#[serde(rename_all = "camelCase")]
#[derive(Debug, Deserialize)]
pub struct SdcMappingInfo {
    pub sdc_id: String,
    pub sdc_ip: String,
    pub limit_iops: u64,
    pub limit_bw_in_mbps: u64,
}

impl IntoPoint for SdcMappingInfo {
    fn into_point(&self, name: Option<&str>, is_time_series: bool) -> Vec<TsPoint> {
        let mut p = TsPoint::new(name.unwrap_or("scaleio_volume_sdc"), is_time_series);
        p.add_tag("sdc_id", TsValue::String(self.sdc_id.clone()));
        p.add_tag("sdc_ip", TsValue::String(self.sdc_ip.clone()));
        p.add_field("limit_iops", TsValue::Long(self.limit_iops));
        p.add_field("limit_bw_in_mbps", TsValue::Long(self.limit_bw_in_mbps));

        vec![p]
    }
}

#[serde(rename_all = "camelCase")]
#[derive(Debug, Deserialize)]
pub struct SdsVolume {
    // Volume Object
    pub id: String,
    pub name: Option<String>,
    pub size_in_kb: u64,
    pub is_obfuscated: bool,
    pub creation_time: u64,
    pub volume_type: String,
    pub consistency_group_id: Option<String>,
    pub mapping_to_all_sdcs_enabled: bool,
    pub mapped_sdc_info: Option<Vec<SdcMappingInfo>>,
    pub mapped_scsi_initiator_info_list: Option<Vec<ScsiInitiatorMappingInfo>>,
    pub ancestor_volume_id: Option<String>,
    pub vtree_id: String,
    pub storage_pool_id: String,
    pub use_rmcache: Option<bool>,
}

impl IntoPoint for SdsVolume {
    fn into_point(&self, name: Option<&str>, is_time_series: bool) -> Vec<TsPoint> {
        let mut points: Vec<TsPoint> = Vec::new();
        let mut p = TsPoint::new(name.unwrap_or("scaleio_volume"), is_time_series);
        p.add_tag("id", TsValue::String(self.id.clone()));
        if let Some(ref name) = self.name {
            p.add_tag("name", TsValue::String(name.clone()));
        }
        p.add_field("size_in_kb", TsValue::Long(self.size_in_kb));
        p.add_field("is_obfuscated", TsValue::Boolean(self.is_obfuscated));
        p.add_field("creation_time", TsValue::Long(self.creation_time));
        p.add_tag("volume_type", TsValue::String(self.volume_type.clone()));
        if let Some(ref group_id) = self.consistency_group_id {
            p.add_tag("consistency_group_id", TsValue::String(group_id.clone()));
        }
        p.add_field(
            "mapping_to_all_sdcs_enabled",
            TsValue::Boolean(self.mapping_to_all_sdcs_enabled),
        );

        // This is a 1:Many relationship so we're going to denormalize that here
        // and store the sdc_info is a separate table with the volume id so we can
        // find it later
        if let Some(ref mapped_sdc_info) = self.mapped_sdc_info {
            for sdc_map in mapped_sdc_info {
                sdc_map
                    .into_point(Some("scaleio_volume_sdc"), is_time_series)
                    .into_iter()
                    .for_each(|mut point| {
                        // Add the volume id so we can look this up later
                        point.add_tag("volume", TsValue::String(self.id.clone()));
                        points.push(point);
                    });
            }
        }

        if let Some(ref mapped_scsi_list) = self.mapped_scsi_initiator_info_list {
            for scsi_map in mapped_scsi_list {
                scsi_map
                    .into_point(Some("scaleio_volume_scsi"), is_time_series)
                    .into_iter()
                    .for_each(|mut point| {
                        point.add_tag("volume", TsValue::String(self.id.clone()));
                        points.push(point);
                    });
            }
        }

        if let Some(ref ancestor) = self.ancestor_volume_id {
            p.add_field("ancestor_volume_id", TsValue::String(ancestor.clone()));
        }
        p.add_tag("vtree_id", TsValue::String(self.vtree_id.clone()));
        p.add_tag(
            "storage_pool_id",
            TsValue::String(self.storage_pool_id.clone()),
        );
        if let Some(use_rmcache) = self.use_rmcache {
            p.add_field("use_rmcache", TsValue::Boolean(use_rmcache));
        }
        points.push(p);

        points
    }
}

#[test]
fn test_sds_object() {
    use std::fs::File;
    use std::io::Read;

    let mut f = File::open("tests/scaleio/sdsObject.json").unwrap();
    let mut buff = String::new();
    f.read_to_string(&mut buff).unwrap();

    let i: SdsObject = serde_json::from_str(&buff).unwrap();
    println!("result: {:#?}", i);
}

#[test]
fn test_sds_statistics() {
    use std::fs::File;
    use std::io::Read;

    let mut f = File::open("tests/scaleio/sds_statistics.json").unwrap();
    let mut buff = String::new();
    f.read_to_string(&mut buff).unwrap();

    let i: SdsStatistics = serde_json::from_str(&buff).unwrap();
    println!("result: {:#?}", i);
}

#[serde(rename_all = "camelCase")]
#[derive(Debug, Deserialize, IntoPoint)]
pub struct SdsStatistics {
    active_moving_in_bck_rebuild_jobs: u64,
    active_moving_in_fwd_rebuild_jobs: u64,
    active_moving_in_norm_rebuild_jobs: u64,
    active_moving_in_rebalance_jobs: u64,
    active_moving_out_bck_rebuild_jobs: u64,
    active_moving_out_fwd_rebuild_jobs: u64,
    active_moving_out_norm_rebuild_jobs: u64,
    active_moving_rebalance_jobs: u64,
    #[serde(rename = "BackgroundScanCompareCount")]
    background_scan_compare_count: u64,
    #[serde(rename = "BackgroundScannedInMB")]
    background_scanned_in_mb: u64,
    bck_rebuild_read_bwc: BWC,
    bck_rebuild_write_bwc: BWC,
    capacity_in_use_in_kb: u64,
    capacity_limit_in_kb: u64,
    degraded_failed_vac_in_kb: u64,
    degraded_healthy_vac_in_kb: u64,
    failed_vac_in_kb: u64,
    fixed_read_error_count: u64,
    fwd_rebuild_read_bwc: BWC,
    fwd_rebuild_write_bwc: BWC,
    in_maintenance_vac_in_kb: u64,
    in_use_vac_in_kb: u64,
    maintenance_mode_state: Option<u64>,
    max_capacity_in_kb: u64,
    norm_rebuild_read_bwc: BWC,
    norm_rebuild_write_bwc: BWC,
    num_of_devices: u64,
    num_of_rfcache_devices: u64,
    pending_moving_in_bck_rebuild_jobs: u64,
    pending_moving_in_fwd_rebuild_jobs: u64,
    pending_moving_in_norm_rebuild_jobs: u64,
    pending_moving_in_rebalance_jobs: u64,
    pending_moving_out_bck_rebuild_jobs: u64,
    pending_moving_out_fwd_rebuild_jobs: u64,
    pending_moving_out_normrebuild_jobs: u64,
    pending_moving_rebalance_jobs: u64,
    primary_read_bwc: BWC,
    primary_read_from_dev_bwc: BWC,
    primary_read_from_rmcache_bwc: BWC,
    primary_vac_in_kb: u64,
    primary_write_bwc: BWC,
    protected_vac_in_kb: u64,
    rebalance_per_receive_job_net_throttling_in_kbps: u64,
    rebalance_read_bwc: BWC,
    rebalance_wait_send_q_length: u64,
    rebalance_write_bwc: BWC,
    rebuild_per_receive_job_net_throttling_in_kbps: u64,
    rebuild_wait_send_q_length: u64,
    rfache_read_hit: u64,
    rfcache_avg_read_time: u64,
    rfcache_avg_write_time: u64,
    rfcache_fd_avg_read_time: u64,
    rfcache_fd_avg_write_time: u64,
    rfcache_fd_cache_overloaded: u64,
    rfcache_fd_inlight_reads: u64,
    rfcache_fd_inlight_writes: u64,
    rfcache_fd_io_errors: u64,
    rfcache_fd_monitor_error_stuck_io: u64,
    rfcache_fd_reads_received: u64,
    rfcache_fd_read_time_greater1_min: u64,
    rfcache_fd_read_time_greater1_sec: u64,
    rfcache_fd_read_time_greater500_millis: u64,
    rfcache_fd_read_time_greater5_sec: u64,
    rfcache_fd_writes_received: u64,
    rfcache_fd_write_time_greater1_min: u64,
    rfcache_fd_write_time_greater1_sec: u64,
    rfcache_fd_write_time_greater500_millis: u64,
    rfcache_fd_write_time_greater5_sec: u64,
    rfcache_io_errors: u64,
    rfcache_ios_outstanding: u64,
    rfcache_ios_skipped: u64,
    rfcache_poo_ios_outstanding: u64,
    rfcache_pool_continuos_mem: u64,
    rfcache_pool_evictions: u64,
    rfcache_pool_in_low_memory_condition: u64,
    rfcache_pool_io_time_greater1_min: u64,
    rfcache_pool_lock_time_greater1_sec: u64,
    rfcache_pool_low_resources_initiated_passthrough_mode: u64,
    rfcache_pool_max_io_size: u64,
    rfcache_pool_num_cache_devs: u64,
    rfcache_pool_num_of_driver_theads: u64,
    rfcache_pool_num_src_devs: u64,
    rfcache_pool_opmode: u64,
    rfcache_pool_pages_inuse: u64,
    rfcache_pool_page_size: u64,
    rfcache_pool_read_hit: u64,
    rfcache_pool_read_miss: u64,
    rfcache_pool_read_pending_g10_millis: u64,
    rfcache_pool_read_pending_g1_millis: u64,
    rfcache_pool_read_pending_g1_sec: u64,
    rfcache_pool_read_pending_g500_micro: u64,
    rfcache_pool_reads_pending: u64,
    rfcache_pool_size: u64,
    rfcache_pool_source_id_mismatch: u64,
    rfcache_pool_suspended_ios: u64,
    rfcache_pool_suspended_ios_max: u64,
    rfcache_pool_suspended_pequests_redundant_searchs: u64,
    rfcache_pool_write_hit: u64,
    rfcache_pool_write_miss: u64,
    rfcache_pool_write_pending: u64,
    rfcache_pool_write_pending_g10_millis: u64,
    rfcache_pool_write_pending_g1_millis: u64,
    rfcache_pool_write_pending_g1_sec: u64,
    rfcache_pool_write_pending_g500_micro: u64,
    rfcache_read_miss: u64,
    rfcache_reads_from_cache: u64,
    rfcache_reads_pending: u64,
    rfcache_reads_received: u64,
    rfcache_reads_skipped: u64,
    rfcache_reads_skipped_aligned_size_too_large: u64,
    rfcache_reads_skipped_heavy_load: u64,
    rfcache_reads_skipped_internal_error: u64,
    rfcache_reads_skipped_lock_ios: u64,
    rfcache_reads_skipped_low_resources: u64,
    rfcache_reads_skipped_max_io_size: u64,
    rfcache_reads_skipped_stuck_io: u64,
    rfcache_skipped_unlined_write: u64,
    rfcache_source_device_reads: u64,
    rfcache_source_device_writes: u64,
    rfcache_write_miss: u64,
    rfcache_write_pending: u64,
    rfcache_writes_received: u64,
    rfcache_writes_skipped_cache_miss: u64,
    rfcache_writes_skipped_heavy_load: u64,
    rfcache_writes_skipped_internal_error: u64,
    rfcache_writes_skipped_low_resources: u64,
    rfcache_writes_skipped_max_io_size: u64,
    rfcache_writes_skipped_stuck_io: u64,
    rmcache128kb_entry_count: u64,
    rmcache16kb_entry_count: u64,
    rmcache32kb_entry_count: u64,
    rmcache4kb_entry_count: u64,
    rmcache64kb_entry_count: u64,
    rmcache8kb_entry_count: u64,
    rmcache_big_block_eviction_count: u64,
    rmcache_big_block_eviction_size_count_in_kb: u64,
    rmcache_curr_num_of128kb_entries: u64,
    rmcache_curr_num_of16kb_entries: u64,
    rmcache_curr_num_of32kb_entries: u64,
    rmcache_curr_num_of4kb_entries: u64,
    rmcache_curr_num_of64kb_entries: u64,
    rmcache_curr_num_of8kb_entries: u64,
    rmcache_entry_eviction_count: u64,
    rmcache_entry_eviction_size_count_in_kb: u64,
    rmcache_no_eviction_count: u64,
    rmcache_size_in_use_in_kb: u64,
    rmcache_skip_count_cache_all_busy: u64,
    rmcache_skip_count_large_io: u64,
    rmcache_skip_count_unaligned4kb_io: u64,
    rm_pending_allocated_in_kb: u64,
    secondary_read_bwc: BWC,
    secondary_read_from_dev_bwc: BWC,
    secondary_read_from_rmcache_bwc: BWC,
    secondary_vac_in_kb: u64,
    secondary_write_bwc: BWC,
    semi_protected_vac_in_kb: u64,
    snap_capacity_in_use_in_kb: u64,
    snap_capacity_in_use_occupied_in_kb: u64,
    thick_capacity_in_use_in_kb: u64,
    thin_capacity_allocated_in_km: u64,
    thin_capacity_in_use_in_kb: u64,
    total_read_bwc: BWC,
    total_write_bwc: BWC,
    unreachable_unused_capacity_in_kb: u64,
    unused_capacity_in_kb: u64,
}

#[serde(rename_all = "camelCase")]
#[derive(Debug, Deserialize)]
pub struct SdsObject {
    pub ip_list: Vec<IpObject>,
    pub on_vm_ware: bool,
    pub protection_domain_id: String,
    pub num_of_io_buffers: Option<u64>,
    pub fault_set_id: String,
    pub software_version_info: String,
    pub sds_state: DeviceState,
    pub membership_state: MembershipState,
    pub mdm_connection_state: MdmConnectionState,
    pub drl_mode: DrlMode,
    pub rmcache_enabled: bool,
    pub rmcache_size_in_kb: u64,
    pub rmcache_frozen: bool,
    pub rmcache_memory_allocation_state: MemoryAllocationState,
    pub rfcache_enabled: bool,
    pub maintenance_state: MaintenanceState,
    pub sds_decoupled: Option<OscillatingCounterWindow>,
    pub sds_configuration_failure: Option<OscillatingCounterWindow>,
    pub sds_receive_buffer_allocation_failures: Option<OscillatingCounterWindow>,
    pub rfcache_error_device_does_not_exist: bool,
    pub rfcache_error_low_resources: bool,
    pub rfcache_error_api_version_mismatch: bool,
    pub rfcache_error_inconsistent_cache_configuration: bool,
    pub rfcache_error_inconsistent_source_configuration: bool,
    pub rfcache_error_invalid_driver_path: bool,
    pub certificate_info: Option<CertificateInfo>,
    pub authentication_error: Option<AuthenticationError>,
    pub perf_profile: PerfProfile,
    pub name: String,
    pub port: u16,
    pub id: String,
    pub links: Vec<HashMap<String, String>>,
}

impl IntoPoint for SdsObject {
    fn into_point(&self, name: Option<&str>, is_time_series: bool) -> Vec<TsPoint> {
        let mut p = TsPoint::new(name.unwrap_or("scaleio_sds"), is_time_series);
        p.add_field(
            "ip_list",
            TsValue::StringVec(
                self.ip_list
                    .iter()
                    .map(|i| format!("{}", i.ip))
                    .collect::<Vec<String>>(),
            ),
        );
        p.add_field("on_vm_ware", TsValue::Boolean(self.on_vm_ware));
        p.add_tag(
            "protection_domain_id",
            TsValue::String(self.protection_domain_id.clone()),
        );
        if let Some(buffers) = self.num_of_io_buffers {
            p.add_field("num_of_io_buffers", TsValue::Long(buffers));
        }
        p.add_tag("fault_set_id", TsValue::String(self.fault_set_id.clone()));
        p.add_tag(
            "software_version_info",
            TsValue::String(self.software_version_info.clone()),
        );
        p.add_field("sds_state", TsValue::String(self.sds_state.to_string()));
        p.add_field(
            "membership_state",
            TsValue::String(self.membership_state.to_string()),
        );
        p.add_field(
            "mdm_connection_state",
            TsValue::String(self.mdm_connection_state.to_string()),
        );
        p.add_field("drl_mode", TsValue::String(self.drl_mode.to_string()));
        p.add_field("rmcache_enabled", TsValue::Boolean(self.rmcache_enabled));
        p.add_field("rmcache_size_in_kb", TsValue::Long(self.rmcache_size_in_kb));
        p.add_field("rmcache_frozen", TsValue::Boolean(self.rmcache_frozen));
        p.add_field(
            "rmcache_memory_allocation_state",
            TsValue::String(self.rmcache_memory_allocation_state.to_string()),
        );
        p.add_field("rfcache_enabled", TsValue::Boolean(self.rfcache_enabled));
        p.add_field(
            "maintenance_state",
            TsValue::String(self.maintenance_state.to_string()),
        );
        //if let Some(counter) = self.sds_decoupled {
        //p.add_field("sds_decoupled", self.sds_decoupled: Option<OscillatingCounterWindow>);
        //}
        //if let Some(counter) = self.sds_configuration_failure {
        //p.add_field("sds_configuration_failure", self.sds_configuration_failure: Option<OscillatingCounterWindow>);
        //}
        //if let Some(counter) = self.sds_receive_buffer_allocation_failures {
        //counter.add_fields(&mut p);
        //p.add_field("sds_receive_buffer_allocation_failures", self.sds_receive_buffer_allocation_failures,
        //}
        p.add_field(
            "rfcache_error_device_does_not_exist",
            TsValue::Boolean(self.rfcache_error_device_does_not_exist),
        );
        p.add_field(
            "rfcache_error_low_resources",
            TsValue::Boolean(self.rfcache_error_low_resources),
        );
        p.add_field(
            "rfcache_error_api_version_mismatch",
            TsValue::Boolean(self.rfcache_error_api_version_mismatch),
        );
        p.add_field(
            "rfcache_error_inconsistent_cache_configuration",
            TsValue::Boolean(self.rfcache_error_inconsistent_cache_configuration),
        );
        p.add_field(
            "rfcache_error_inconsistent_source_configuration",
            TsValue::Boolean(self.rfcache_error_inconsistent_source_configuration),
        );
        p.add_field(
            "rfcache_error_invalid_driver_path",
            TsValue::Boolean(self.rfcache_error_invalid_driver_path),
        );

        if let Some(ref info) = self.certificate_info {
            p.add_field("certificate_subject", TsValue::String(info.subject.clone()));
            p.add_field("certificate_issuer", TsValue::String(info.issuer.clone()));
            p.add_field(
                "certificate_validfrom",
                TsValue::String(info.valid_from.clone()),
            );
            p.add_field(
                "certificate_validto",
                TsValue::String(info.valid_to.clone()),
            );
            p.add_field(
                "certificate_thumbprint",
                TsValue::String(info.thumbprint.clone()),
            );
            p.add_field(
                "certificate_validfrom_asn",
                TsValue::String(info.valid_from_asn1_format.clone()),
            );
            p.add_field(
                "certificate_validto_asn",
                TsValue::String(info.valid_to_asn1_format.clone()),
            );
        }

        if let Some(ref err) = self.authentication_error {
            p.add_field("authentication_error", TsValue::String(err.to_string()));
        }

        p.add_field(
            "perf_profile",
            TsValue::String(self.perf_profile.to_string()),
        );
        p.add_tag("name", TsValue::String(self.name.clone()));
        p.add_field("port", TsValue::Short(self.port));
        p.add_tag("id", TsValue::String(self.id.clone()));

        vec![p]
    }
}

#[test]
fn test_pool_response() {
    use std::fs::File;
    use std::io::Read;

    let mut f = File::open("tests/scaleio/poolInstance.json").unwrap();
    let mut buff = String::new();
    f.read_to_string(&mut buff).unwrap();
    println!("buff: {}", buff);

    let i: PoolInstanceResponse = serde_json::from_str(&buff).unwrap();
    println!("result: {:#?}", i);
}

#[serde(rename_all = "camelCase")]
#[derive(Debug, Deserialize)]
pub struct PoolInstanceResponse {
    pub rebuild_io_priority_policy: RebuildIoPriority,
    pub rebalance_io_priority_policy: RebuildIoPriority,
    pub rebuild_io_priority_num_of_concurrent_ios_per_device: Option<u64>,
    pub rebalance_io_priority_num_of_concurrent_ios_per_device: Option<u64>,
    pub rebuild_io_priority_bw_limit_per_device_in_kbps: Option<u64>,
    pub rebalance_io_priority_bw_limit_per_device_in_kbps: Option<u64>,
    pub rebuild_io_priority_app_iops_per_device_threshold: Option<u64>,
    pub rebalance_io_priority_app_iops_per_device_threshold: Option<u64>,
    pub rebuild_io_priority_app_bw_per_device_threshold_in_kbps: Option<u64>,
    pub rebalance_io_priority_app_bw_per_device_threshold_in_kbps: Option<u64>,
    pub rebuild_io_priority_quiet_period_in_msec: Option<u64>,
    pub rebalance_io_priority_quiet_period_in_msec: Option<u64>,
    pub zero_padding_enabled: bool,
    pub use_rmcache: bool,
    pub background_scanner_mode: BackgroundScannerMode,
    #[serde(rename = "backgroundScannerBWLimitKBps")]
    pub background_scanner_bw_limit_kbps: u64,
    pub protection_domain_id: String,
    pub spare_percentage: u8,
    pub rmcache_write_handling_mode: CacheWriteHandlingMode,
    pub checksum_enabled: bool,
    pub use_rfcache: bool,
    pub rebuild_enabled: bool,
    pub rebalance_enabled: bool,
    pub num_of_parallel_rebuild_rebalance_jobs_per_device: u16,
    pub capacity_alert_high_threshold: u8,
    pub capacity_alert_critical_threshold: u8,
    pub name: String,
    pub id: String,
    pub links: Vec<HashMap<String, String>>,
}

#[test]
fn test_sdc_objects() {
    use std::fs::File;
    use std::io::Read;

    let mut f = File::open("tests/scaleio/sdc_info.json").unwrap();
    let mut buff = String::new();
    f.read_to_string(&mut buff).unwrap();

    let i: Vec<Sdc> = serde_json::from_str(&buff).unwrap();
    println!("result: {:#?}", i);
}

#[serde(rename_all = "camelCase")]
#[derive(Clone, Deserialize, Debug, IntoPoint)]
pub struct Sdc {
    pub sdc_approved: bool,
    pub mdm_connection_state: String,
    pub memory_allocation_failure: Option<OscillatingCounterWindow>,
    pub socket_allocation_failure: Option<OscillatingCounterWindow>,
    pub sdc_guid: String,
    pub sdc_ip: String,
    pub perf_profile: String,
    pub version_info: Option<String>,
    pub system_id: String,
    pub name: Option<String>,
    pub id: String,
    pub links: Vec<HashMap<String, String>>,
}

#[test]
fn test_system_response() {
    use std::fs::File;
    use std::io::Read;

    let mut f = File::open("tests/scaleio/systems.json").unwrap();
    let mut buff = String::new();
    f.read_to_string(&mut buff).unwrap();
    println!("buff: {}", buff);

    let i: Vec<System> = serde_json::from_str(&buff).unwrap();
    println!("result: {:#?}", i);
}

#[serde(rename_all = "camelCase")]
#[derive(Debug, Deserialize, IntoPoint)]
pub struct System {
    pub system_version_name: String,                    // in v3
    pub capacity_alert_high_threshold_percent: u16,     // in V3
    pub capacity_alert_critical_threshold_percent: u16, // in v3
    pub remote_read_only_limit_state: bool,             // in v3
    pub upgrade_state: String,                          // in v3
    pub mdm_management_port: u16,                       // in v3
    pub sdc_mdm_network_disconnections_counter_parameters: FailureCounter, // in v3
    pub sdc_sds_network_disconnections_counter_parameters: FailureCounter, // in v3
    pub sdc_memory_allocation_failures_counter_parameters: FailureCounter, // in v3
    pub sdc_socket_allocation_failures_counter_parameters: FailureCounter, // in v3
    pub sdc_long_operations_counter_parameters: FailureCounter, // in v3
    pub cli_password_allowed: bool,                     // in v3
    pub management_client_secure_communication_enabled: bool, // in v3
    pub tls_version: String,                            // in v3
    pub show_guid: bool,                                // in v3
    pub authentication_method: String,                  // in v3
    pub mdm_to_sds_policy: String,                      // in v3
    pub mdm_cluster: MdmCluster,                        // in v3
    pub perf_profile: PerfProfile,                      // in v3
    pub install_id: String,                             // in v3
    pub days_installed: u64,                            // in V3
    #[serde(deserialize_with = "deserialize_string_or_int")]
    pub max_capacity_in_gb: i64, // in v3
    pub capacity_time_left_in_days: String,             // in v3
    pub enterprise_features_enabled: bool,              // in v3
    pub is_initial_license: bool,                       // in v3
    pub default_is_volume_obfuscated: Option<bool>,     // not in V3
    pub restricted_sdc_mode_enabled: bool,              // in v3
    pub swid: String,                                   // in v3
    pub name: String,                                   // in V3
    pub id: String,                                     // in V3
    pub links: Vec<HashMap<String, String>>,
}

#[serde(rename_all = "camelCase")]
#[derive(Debug, Deserialize)]
pub struct SystemStatistics {
    pub capacity_limit_in_kb: u64,
    pub max_capacity_in_kb: u64,
    pub capacity_in_use_in_kb: u64,
    pub thick_capacity_in_use_in_kb: u64,
    pub thin_capacity_in_use_in_kb: u64,
    pub snap_capacity_in_use_in_kb: u64,
    pub unreachable_unused_capacity_in_kb: u64,
    pub unused_capacity_in_kb: u64,
    pub snap_capacity_in_use_occupied_in_kb: u64,
    pub thin_capacity_allocated_in_kb: u64,
    pub rm_pending_allocated_in_kb: u64,
    pub rm_pending_thick_in_kb: Option<u64>,
    pub checksum_capacity_in_kb: Option<u64>,
    pub spare_capacity_in_kb: u64,
    pub capacity_available_for_volume_allocation_in_kb: u64,
    pub volume_allocation_limit_in_kb: Option<u64>,
    pub protected_capacity_in_kb: u64,
    pub degraded_healthy_capacity_in_kb: u64,
    pub degraded_failed_capacity_in_kb: u64,
    pub failed_capacity_in_kb: u64,
    pub semi_protected_capacity_in_kb: u64,
    pub in_maintenance_capacity_in_kb: u64,
    pub temp_capacity_in_kb: Option<u64>,
    pub protected_vac_in_kb: u64,
    pub degraded_healthy_vac_in_kb: u64,
    pub degraded_failed_vac_in_kb: u64,
    pub failed_vac_in_kb: u64,
    pub semi_protected_vac_in_kb: u64,
    pub in_maintenance_vac_in_kb: u64,
    pub temp_capacity_vac_in_kb: Option<u64>,
    pub moving_capacity_in_kb: u64,
    pub active_moving_capacity_in_kb: u64,
    pub pending_moving_capacity_in_kb: u64,
    pub fwd_rebuild_capacity_in_kb: u64,
    pub active_fwd_rebuild_capacity_in_kb: u64,
    pub pending_fwd_rebuild_capacity_in_kb: u64,
    pub bck_rebuild_capacity_in_kb: u64,
    pub active_bck_rebuild_capacity_in_kb: u64,
    pub pending_bck_rebuild_capacity_in_kb: u64,
    pub rebalance_capacity_in_kb: u64,
    pub active_rebalance_capacity_in_kb: u64,
    pub pending_rebalance_capacity_in_kb: u64,
    pub at_rest_capacity_in_kb: u64,
    pub norm_rebuild_capacity_in_kb: u64,
    pub active_norm_rebuild_capacity_in_kb: u64,
    pub pending_norm_rebuild_capacity_in_kb: u64,
    pub active_moving_in_fwd_rebuild_jobs: u64,
    pub active_moving_in_bck_rebuild_jobs: u64,
    pub active_moving_in_rebalance_jobs: u64,
    pub active_moving_out_fwd_rebuild_jobs: u64,
    pub active_moving_out_bck_rebuild_jobs: u64,
    pub active_moving_rebalance_jobs: u64,
    pub pending_moving_in_fwd_rebuild_jobs: u64,
    pub pending_moving_in_bck_rebuild_jobs: u64,
    pub pending_moving_in_rebalance_jobs: u64,
    pub pending_moving_out_fwd_rebuild_jobs: u64,
    pub pending_moving_out_bck_rebuild_jobs: u64,
    pub pending_moving_rebalance_jobs: u64,
    pub active_moving_in_norm_rebuild_jobs: u64,
    pub active_moving_out_norm_rebuild_jobs: u64,
    pub pending_moving_in_norm_rebuild_jobs: u64,
    pub pending_moving_out_normrebuild_jobs: u64,
    pub in_use_vac_in_kb: u64,
    pub primary_vac_in_kb: u64,
    pub secondary_vac_in_kb: u64,
    pub rebuild_wait_send_q_length: u64,
    pub rebalance_wait_send_q_length: u64,
    pub rebuild_per_receive_job_net_throttling_in_kbps: u64,
    pub rebalance_per_receive_job_net_throttling_in_kbps: u64,
    pub fixed_read_error_count: u64,
    #[serde(rename = "BackgroundScanCompareCount")]
    pub background_scan_compare_count: u64,
    #[serde(rename = "BackgroundScannedInMB")]
    pub background_scanned_in_mb: u64,
    pub primary_read_bwc: BWC,
    pub primary_read_from_dev_bwc: BWC,
    pub primary_write_bwc: BWC,
    pub secondary_read_bwc: BWC,
    pub secondary_read_from_dev_bwc: BWC,
    pub secondary_write_bwc: BWC,
    pub fwd_rebuild_read_bwc: BWC,
    pub fwd_rebuild_write_bwc: BWC,
    pub bck_rebuild_read_bwc: BWC,
    pub bck_rebuild_write_bwc: BWC,
    pub rebalance_read_bwc: BWC,
    pub rebalance_write_bwc: BWC,
    pub total_read_bwc: BWC,
    pub total_write_bwc: BWC,
    pub primary_read_from_rmcache_bwc: BWC,
    pub secondary_read_from_rmcache_bwc: BWC,
    pub norm_rebuild_read_bwc: BWC,
    pub norm_rebuild_write_bwc: BWC,
    pub vol_migration_read_bwc: Option<BWC>,
    pub vol_migration_write_bwc: Option<BWC>,
    pub user_data_read_bwc: BWC,
    pub user_data_write_bwc: BWC,
    pub user_data_trim_bwc: Option<BWC>,
    pub user_data_sdc_read_latency: Option<BWC>, // THIS IS A BWC
    pub user_data_sdc_write_latency: Option<BWC>,
    pub user_data_sdc_trim_latency: Option<BWC>,
    pub rmcache_size_in_kb: u64,
    pub rmcache_size_in_use_in_kb: u64,
    pub rmcache_entry_eviction_size_count_in_kb: u64,
    pub rmcache_big_block_eviction_size_count_in_kb: u64,
    pub rmcache_curr_num_of4kb_entries: u64,
    pub rmcache_curr_num_of8kb_entries: u64,
    pub rmcache_curr_num_of16kb_entries: u64,
    pub rmcache_curr_num_of32kb_entries: u64,
    pub rmcache_curr_num_of64kb_entries: u64,
    pub rmcache_curr_num_of128kb_entries: u64,
    pub rmcache_entry_eviction_count: u64,
    pub rmcache_big_block_eviction_count: u64,
    pub rmcache_no_eviction_count: u64,
    pub rmcache_skip_count_large_io: u64,
    pub rmcache_skip_count_unaligned4kb_io: u64,
    pub rmcache_skip_count_cache_all_busy: u64,
    pub num_of_unmapped_volumes: u64,
    pub num_of_mapped_to_all_volumes: u64,
    pub num_of_thick_base_volumes: u64,
    pub num_of_thin_base_volumes: u64,
    pub num_of_snapshots: u64,
    pub num_of_volumes_in_deletion: u64,
    pub num_of_devices: u64,
    pub num_of_sds: u64,
    pub num_of_storage_pools: u64,
    pub num_of_volumes: u64,
    pub num_of_vtrees: u64,
    pub protection_domain_ids: Vec<String>,
    pub num_of_protection_domains: u64,
    pub sdc_ids: Vec<String>,
    pub num_of_sdc: u64,
    pub num_of_fault_sets: u64,
    pub num_of_rfcache_devices: u64,
    pub num_of_acceleration_pools: Option<u64>,
    pub sp_sds_ids: Option<Vec<String>>,
    pub num_of_vtree_migrations_in_system: Option<u64>,
    pub compression_ratio: Option<f64>,
    pub snap_policy_ids: Option<Vec<String>>,
    pub num_of_snap_policies: Option<u64>,
    pub rfcache_reads_received: u64,
    pub rfcache_writes_received: u64,
    pub rfcache_avg_read_time: u64,
    pub rfcache_avg_write_time: u64,
    pub rfcache_source_device_reads: u64,
    pub rfcache_source_device_writes: u64,
    pub rfache_read_hit: u64,
    pub rfcache_read_miss: u64,
    pub rfache_write_hit: u64,
    pub rfcache_write_miss: u64,
    pub rfcache_ios_skipped: u64,
    pub rfcache_reads_skipped: u64,
    pub rfcache_reads_skipped_aligned_size_too_large: u64,
    pub rfcache_reads_skipped_max_io_size: u64,
    pub rfcache_reads_skipped_heavy_load: u64,
    pub rfcache_reads_skipped_stuck_io: u64,
    pub rfcache_reads_skipped_low_resources: u64,
    pub rfcache_reads_skipped_internal_error: u64,
    pub rfcache_reads_skipped_lock_ios: u64,
    pub rfcache_writes_skipped_max_io_size: u64,
    pub rfcache_writes_skipped_heavy_load: u64,
    pub rfcache_writes_skipped_stuck_io: u64,
    pub rfcache_writes_skipped_low_resources: u64,
    pub rfcache_writes_skipped_internal_error: u64,
    pub rfcache_writes_skipped_cache_miss: u64,
    pub rfcache_io_errors: u64,
    pub rfcache_reads_from_cache: u64,
    pub rfcache_ios_outstanding: u64,
    pub rfcache_reads_pending: u64,
    pub rfcache_write_pending: u64,
    pub rfcache_fd_reads_received: u64,
    pub rfcache_fd_writes_received: u64,
    pub rfcache_fd_inlight_reads: u64,
    pub rfcache_fd_inlight_writes: u64,
    pub rfcache_fd_read_time_greater500_millis: u64,
    pub rfcache_fd_read_time_greater1_sec: u64,
    pub rfcache_fd_read_time_greater5_sec: u64,
    pub rfcache_fd_read_time_greater1_min: u64,
    pub rfcache_fd_write_time_greater500_millis: u64,
    pub rfcache_fd_write_time_greater1_sec: u64,
    pub rfcache_fd_write_time_greater5_sec: u64,
    pub rfcache_fd_write_time_greater1_min: u64,
    pub rfcache_fd_avg_read_time: u64,
    pub rfcache_fd_avg_write_time: u64,
    pub rfcache_fd_io_errors: u64,
    pub rfcache_fd_cache_overloaded: u64,
    pub rfcache_fd_monitor_error_stuck_io: u64,
    pub rfcache_pool_num_src_devs: u64,
    pub rfcache_pool_num_cache_devs: u64,
    pub rfcache_pool_size: u64,
    pub rfcache_pool_read_hit: u64,
    pub rfcache_pool_read_miss: u64,
    pub rfcache_pool_write_hit: u64,
    pub rfcache_pool_write_miss: u64,
    pub rfcache_pool_cache_pages: u64,
    pub rfcache_pool_pages_inuse: u64,
    pub rfcache_pool_evictions: u64,
    pub rfcache_pool_in_low_memory_condition: u64,
    pub rfcache_pool_io_time_greater1_min: u64,
    pub rfcache_pool_lock_time_greater1_sec: u64,
    pub rfcache_pool_suspended_ios: u64,
    pub rfcache_pool_low_resources_initiated_passthrough_mode: u64,
    pub rfcache_poo_ios_outstanding: u64,
    pub rfcache_pool_reads_pending: u64,
    pub rfcache_pool_write_pending: u64,
    pub rfcache_pool_suspended_pequests_redundant_searchs: u64,
    pub rfcache_pool_read_pending_g1_sec: u64,
    pub rfcache_pool_read_pending_g10_millis: u64,
    pub rfcache_pool_read_pending_g1_millis: u64,
    pub rfcache_pool_read_pending_g500_micro: u64,
    pub rfcache_pool_write_pending_g1_sec: u64,
    pub rfcache_pool_write_pending_g10_millis: u64,
    pub rfcache_pool_write_pending_g1_millis: u64,
    pub rfcache_pool_write_pending_g500_micro: u64,
    pub rfcache_pool_source_id_mismatch: u64,
    pub vtree_migration_wait_send_q_length: Option<u64>,
    pub vtree_migration_per_receive_job_net_throttling_in_kbps: Option<u64>,
    pub log_written_blocks_in_kb: Option<u64>,
    pub fgl_uncompressed_data_size_in_kb: Option<u64>,
    pub fgl_compressed_data_size_in_kb: Option<u64>,
    pub user_data_capacity_in_kb: Option<u64>,
    pub snapshot_capacity_in_kb: Option<u64>,
    pub trimmed_user_data_capacity_in_kb: Option<u64>,
    pub provisioned_addresses_in_kb: Option<u64>,
    pub volume_address_space_in_kb: Option<u64>,
    pub vtree_addres_space_in_kb: Option<u64>,
    pub fgl_spares_in_kb: Option<u64>,
    pub metadata_overhead_in_kb: Option<u64>,
    pub net_fgl_spares_in_kb: Option<u64>,
    pub net_metadata_overhead_in_kb: Option<u64>,
    pub net_capacity_in_use_no_overhead_in_kb: Option<u64>,
    pub net_user_data_capacity_in_kb: Option<u64>,
    pub net_snapshot_capacity_in_kb: Option<u64>,
    pub net_trimmed_user_data_capacity_in_kb: Option<u64>,
    pub net_provisioned_addresses_in_kb: Option<u64>,
    pub net_unused_capacity_in_kb: Option<u64>,
    pub thin_and_snapshot_ratio: Option<u64>,
    pub overall_usage_ratio: Option<f64>,
    pub net_capacity_in_use_in_kb: Option<u64>,
    pub aggregate_compression_level: Option<u64>,
    pub fgl_user_data_capacity_in_kb: Option<u64>,
    pub mg_user_ddata_ccapacity_in_kb: Option<u64>,
    pub max_user_data_capacity_in_kb: Option<u64>,
    pub capacity_in_use_no_overhead_in_kb: Option<u64>,
    pub net_fgl_uncompressed_data_size_in_kb: Option<u64>,
    pub net_fgl_compressed_data_size_in_kb: Option<u64>,
    pub net_fgl_user_data_capacity_in_kb: Option<u64>,
    pub compressed_data_compression_ratio: Option<u64>,
    pub net_mg_user_data_capacity_in_kb: Option<u64>,
    pub net_max_user_data_capacity_in_kb: Option<u64>,
    pub net_user_data_capacity_no_trim_in_kb: Option<u64>,
    pub num_volume_migrations_performed: Option<u64>,
    pub num_snapshots_taken: Option<u64>,
    pub num_dev_errors: Option<u64>,
    pub num_sds_reconnections: Option<u64>,
    pub num_sd_sdc_disconnections: Option<u64>,
    pub num_oscillation_counters_passed_threshold: Option<u64>,
    pub num_smart_attributes_passed_threshold: Option<u64>,
    pub num_cmatrix_policy_changes: Option<u64>,
}

impl IntoPoint for SystemStatistics {
    fn into_point(&self, name: Option<&str>, is_time_series: bool) -> Vec<TsPoint> {
        let mut points = Vec::new();
        let mut p = TsPoint::new(name.unwrap_or("scaleio_sys_stat"), is_time_series);
        p.add_field(
            "capacity_limit_in_kb",
            TsValue::Long(self.capacity_limit_in_kb),
        );
        p.add_field("max_capacity_in_kb", TsValue::Long(self.max_capacity_in_kb));
        p.add_field(
            "capacity_in_use_in_kb",
            TsValue::Long(self.capacity_in_use_in_kb),
        );
        p.add_field(
            "thick capacity_in_use_in_kb",
            TsValue::Long(self.thick_capacity_in_use_in_kb),
        );
        p.add_field(
            "thin_capacity_in_use_in_kb",
            TsValue::Long(self.thin_capacity_in_use_in_kb),
        );
        p.add_field(
            "snap_capacity_in_use_in_kb",
            TsValue::Long(self.snap_capacity_in_use_in_kb),
        );
        p.add_field(
            "unreachable_unused_capacity_in_kb",
            TsValue::Long(self.unreachable_unused_capacity_in_kb),
        );
        p.add_field(
            "unused_capacity_in_kb",
            TsValue::Long(self.unused_capacity_in_kb),
        );
        p.add_field(
            "snap_capacity_in_use_occupied_in_kb",
            TsValue::Long(self.snap_capacity_in_use_occupied_in_kb),
        );
        p.add_field(
            "thin_capacity_allocated_in_kb",
            TsValue::Long(self.thin_capacity_allocated_in_kb),
        );
        p.add_field(
            "spare_capacity_in_kb",
            TsValue::Long(self.spare_capacity_in_kb),
        );
        p.add_field(
            "fixed_read_error_count",
            TsValue::Long(self.fixed_read_error_count),
        );
        p.add_field(
            "num_of_unmapped_volumes",
            TsValue::Long(self.num_of_unmapped_volumes),
        );
        p.add_field(
            "num_of_mapped_to_all_volumes",
            TsValue::Long(self.num_of_mapped_to_all_volumes),
        );
        p.add_field(
            "num_of_thick_base_volumes",
            TsValue::Long(self.num_of_thick_base_volumes),
        );
        p.add_field(
            "num_of_thin_base_volumes",
            TsValue::Long(self.num_of_thin_base_volumes),
        );
        p.add_field("num_of_snapshots", TsValue::Long(self.num_of_snapshots));
        p.add_field(
            "num_of_volumes_in_deletion",
            TsValue::Long(self.num_of_volumes_in_deletion),
        );
        p.add_field("num_of_devices", TsValue::Long(self.num_of_devices));
        p.add_field("num_of_sds", TsValue::Long(self.num_of_sds));
        p.add_field(
            "num_of_storage_pools",
            TsValue::Long(self.num_of_storage_pools),
        );
        p.add_field("num_of_volumes", TsValue::Long(self.num_of_volumes));
        p.add_field("num_of_sdc", TsValue::Long(self.num_of_sdc));
        if let Some(compression_ratio) = self.compression_ratio {
            p.add_field("compression_ratio", TsValue::Float(compression_ratio));
        }
        if let Some(user_data_capacity_in_kb) = self.user_data_capacity_in_kb {
            p.add_field(
                "user_data_capacity_in_kb",
                TsValue::Long(user_data_capacity_in_kb),
            );
        }
        if let Some(snapshot_capacity_in_kb) = self.snapshot_capacity_in_kb {
            p.add_field(
                "snapshot_capacity_in_kb",
                TsValue::Long(snapshot_capacity_in_kb),
            );
        }
        if let Some(overall_usage_ratio) = self.overall_usage_ratio {
            p.add_field("overall_usage_ratio", TsValue::Float(overall_usage_ratio));
        }
        if let Some(num_sds_reconnections) = self.num_sds_reconnections {
            p.add_field(
                "num_sds_reconnections",
                TsValue::Long(num_sds_reconnections),
            );
        }
        if let Some(num_sd_sdc_disconnections) = self.num_sd_sdc_disconnections {
            p.add_field(
                "num_sd_sdc_disconnections",
                TsValue::Long(num_sd_sdc_disconnections),
            );
        }
        p.add_field(
            "primary_read_bwc_total_weight_in_kb",
            TsValue::Long(self.primary_read_bwc.total_weight_in_kb),
        );
        p.add_field(
            "primary_read_bwc_num_seconds",
            TsValue::Long(self.primary_read_bwc.num_seconds),
        );
        p.add_field(
            "primary_read_bwc_num_occured",
            TsValue::Long(self.primary_read_bwc.num_occured),
        );

        p.add_field(
            "primary_read_from_dev_bwc_total_weight_in_kb",
            TsValue::Long(self.primary_read_from_dev_bwc.total_weight_in_kb),
        );
        p.add_field(
            "primary_read_from_dev_bwc_num_seconds",
            TsValue::Long(self.primary_read_from_dev_bwc.num_seconds),
        );
        p.add_field(
            "primary_read_from_dev_bwc_num_occured",
            TsValue::Long(self.primary_read_from_dev_bwc.num_occured),
        );

        p.add_field(
            "primary_write_bwc_total_weight_in_kb",
            TsValue::Long(self.primary_write_bwc.total_weight_in_kb),
        );
        p.add_field(
            "primary_write_bwc_num_seconds",
            TsValue::Long(self.primary_write_bwc.num_seconds),
        );
        p.add_field(
            "primary_write_bwc_num_occured",
            TsValue::Long(self.primary_write_bwc.num_occured),
        );

        p.add_field(
            "secondary_read_bwc_total_weight_in_kb",
            TsValue::Long(self.secondary_read_bwc.total_weight_in_kb),
        );
        p.add_field(
            "secondary_read_bwc_num_seconds",
            TsValue::Long(self.secondary_read_bwc.num_seconds),
        );
        p.add_field(
            "secondary_read_bwc_num_occured",
            TsValue::Long(self.secondary_read_bwc.num_occured),
        );

        p.add_field(
            "secondary_read_from_dev_bwc_total_weight_in_kb",
            TsValue::Long(self.secondary_read_from_dev_bwc.total_weight_in_kb),
        );
        p.add_field(
            "secondary_read_from_dev_bwc_num_seconds",
            TsValue::Long(self.secondary_read_from_dev_bwc.num_seconds),
        );
        p.add_field(
            "secondary_read_from_dev_bwc_num_occured",
            TsValue::Long(self.secondary_read_from_dev_bwc.num_occured),
        );

        p.add_field(
            "secondary_write_bwc_total_weight_in_kb",
            TsValue::Long(self.secondary_write_bwc.total_weight_in_kb),
        );
        p.add_field(
            "secondary_write_bwc_num_seconds",
            TsValue::Long(self.secondary_write_bwc.num_seconds),
        );
        p.add_field(
            "secondary_write_bwc_num_occured",
            TsValue::Long(self.secondary_write_bwc.num_occured),
        );

        p.add_field(
            "fwd_rebuild_read_bwc_total_weight_in_kb",
            TsValue::Long(self.fwd_rebuild_read_bwc.total_weight_in_kb),
        );
        p.add_field(
            "fwd_rebuild_read_bwc_num_seconds",
            TsValue::Long(self.fwd_rebuild_read_bwc.num_seconds),
        );
        p.add_field(
            "fwd_rebuild_read_bwc_num_occured",
            TsValue::Long(self.fwd_rebuild_read_bwc.num_occured),
        );

        p.add_field(
            "fwd_rebuild_write_bwc_total_weight_in_kb",
            TsValue::Long(self.fwd_rebuild_write_bwc.total_weight_in_kb),
        );
        p.add_field(
            "fwd_rebuild_write_bwc_num_seconds",
            TsValue::Long(self.fwd_rebuild_write_bwc.num_seconds),
        );
        p.add_field(
            "fwd_rebuild_write_bwc_num_occured",
            TsValue::Long(self.fwd_rebuild_write_bwc.num_occured),
        );

        p.add_field(
            "bck_rebuild_read_bwc_total_weight_in_kb",
            TsValue::Long(self.bck_rebuild_read_bwc.total_weight_in_kb),
        );
        p.add_field(
            "bck_rebuild_read_bwc_num_seconds",
            TsValue::Long(self.bck_rebuild_read_bwc.num_seconds),
        );
        p.add_field(
            "bck_rebuild_read_bwc_num_occured",
            TsValue::Long(self.bck_rebuild_read_bwc.num_occured),
        );

        p.add_field(
            "bck_rebuild_write_bwc_total_weight_in_kb",
            TsValue::Long(self.bck_rebuild_write_bwc.total_weight_in_kb),
        );
        p.add_field(
            "bck_rebuild_write_bwc_num_seconds",
            TsValue::Long(self.bck_rebuild_write_bwc.num_seconds),
        );
        p.add_field(
            "bck_rebuild_write_bwc_num_occured",
            TsValue::Long(self.bck_rebuild_write_bwc.num_occured),
        );

        p.add_field(
            "rebalance_read_bwc_total_weight_in_kb",
            TsValue::Long(self.rebalance_read_bwc.total_weight_in_kb),
        );
        p.add_field(
            "rebalance_read_bwc_num_seconds",
            TsValue::Long(self.rebalance_read_bwc.num_seconds),
        );
        p.add_field(
            "rebalance_read_bwc_num_occured",
            TsValue::Long(self.rebalance_read_bwc.num_occured),
        );

        p.add_field(
            "rebalance_write_bwc_total_weight_in_kb",
            TsValue::Long(self.rebalance_write_bwc.total_weight_in_kb),
        );
        p.add_field(
            "rebalance_write_bwc_num_seconds",
            TsValue::Long(self.rebalance_write_bwc.num_seconds),
        );
        p.add_field(
            "rebalance_write_bwc_num_occured",
            TsValue::Long(self.rebalance_write_bwc.num_occured),
        );

        p.add_field(
            "total_read_bwc_total_weight_in_kb",
            TsValue::Long(self.total_read_bwc.total_weight_in_kb),
        );
        p.add_field(
            "total_read_bwc_num_seconds",
            TsValue::Long(self.total_read_bwc.num_seconds),
        );
        p.add_field(
            "total_read_bwc_num_occured",
            TsValue::Long(self.total_read_bwc.num_occured),
        );

        p.add_field(
            "total_write_bwc_total_weight_in_kb",
            TsValue::Long(self.total_write_bwc.total_weight_in_kb),
        );
        p.add_field(
            "total_write_bwc_num_seconds",
            TsValue::Long(self.total_write_bwc.num_seconds),
        );
        p.add_field(
            "total_write_bwc_num_occured",
            TsValue::Long(self.total_write_bwc.num_occured),
        );

        p.add_field(
            "primary_read_from_rmcache_bwc_total_weight_in_kb",
            TsValue::Long(self.primary_read_from_rmcache_bwc.total_weight_in_kb),
        );
        p.add_field(
            "primary_read_from_rmcache_bwc_num_seconds",
            TsValue::Long(self.primary_read_from_rmcache_bwc.num_seconds),
        );
        p.add_field(
            "primary_read_from_rmcache_bwc_num_occured",
            TsValue::Long(self.primary_read_from_rmcache_bwc.num_occured),
        );

        p.add_field(
            "secondary_read_from_rmcache_bwc_total_weight_in_kb",
            TsValue::Long(self.secondary_read_from_rmcache_bwc.total_weight_in_kb),
        );
        p.add_field(
            "secondary_read_from_rmcache_bwc_num_seconds",
            TsValue::Long(self.secondary_read_from_rmcache_bwc.num_seconds),
        );
        p.add_field(
            "secondary_read_from_rmcache_bwc_num_seconds",
            TsValue::Long(self.secondary_read_from_rmcache_bwc.num_occured),
        );

        p.add_field(
            "norm_rebuild_read_bwc_total_weight_in_kb",
            TsValue::Long(self.norm_rebuild_read_bwc.total_weight_in_kb),
        );
        p.add_field(
            "norm_rebuild_read_bwc_num_seconds",
            TsValue::Long(self.norm_rebuild_read_bwc.num_seconds),
        );
        p.add_field(
            "norm_rebuild_read_bwc_num_occured",
            TsValue::Long(self.norm_rebuild_read_bwc.num_occured),
        );

        p.add_field(
            "norm_rebuild_write_bwc_total_weight_in_kb",
            TsValue::Long(self.norm_rebuild_write_bwc.total_weight_in_kb),
        );
        p.add_field(
            "norm_rebuild_write_bwc_num_seconds",
            TsValue::Long(self.norm_rebuild_write_bwc.num_seconds),
        );
        p.add_field(
            "norm_rebuild_write_bwc_num_occured",
            TsValue::Long(self.norm_rebuild_write_bwc.num_occured),
        );

        if let Some(vol_migration_read_bwc) = &self.vol_migration_read_bwc {
            p.add_field(
                "vol_migration_read_bwc_total_weight_in_kb",
                TsValue::Long(vol_migration_read_bwc.total_weight_in_kb),
            );
            p.add_field(
                "vol_migration_read_bwc_num_seconds",
                TsValue::Long(vol_migration_read_bwc.num_seconds),
            );
            p.add_field(
                "vol_migration_read_bwc_num_occured",
                TsValue::Long(vol_migration_read_bwc.num_occured),
            );
        }

        if let Some(vol_migration_write_bwc) = &self.vol_migration_write_bwc {
            p.add_field(
                "vol_migration_write_bwc_total_weight_in_kb",
                TsValue::Long(vol_migration_write_bwc.total_weight_in_kb),
            );
            p.add_field(
                "vol_migration_write_bwc_num_seconds",
                TsValue::Long(vol_migration_write_bwc.num_seconds),
            );
            p.add_field(
                "vol_migration_write_bwc_num_occured",
                TsValue::Long(vol_migration_write_bwc.num_occured),
            );
        }

        p.add_field(
            "user_data_read_bwc_total_weight_in_kb",
            TsValue::Long(self.user_data_read_bwc.total_weight_in_kb),
        );
        p.add_field(
            "user_data_read_bwc_num_seconds",
            TsValue::Long(self.user_data_read_bwc.num_seconds),
        );
        p.add_field(
            "user_data_read_bwc_num_occured",
            TsValue::Long(self.user_data_read_bwc.num_occured),
        );

        p.add_field(
            "user_data_write_bwc_total_weight_in_kb",
            TsValue::Long(self.user_data_write_bwc.total_weight_in_kb),
        );
        p.add_field(
            "user_data_write_bwc_num_seconds",
            TsValue::Long(self.user_data_write_bwc.num_seconds),
        );
        p.add_field(
            "user_data_write_bwc_num_occured",
            TsValue::Long(self.user_data_write_bwc.num_occured),
        );

        if let Some(user_data_trim_bwc) = &self.user_data_trim_bwc {
            p.add_field(
                "user_data_trim_bwc_total_weight_in_kb",
                TsValue::Long(user_data_trim_bwc.total_weight_in_kb),
            );
            p.add_field(
                "user_data_trim_bwc_num_seconds",
                TsValue::Long(user_data_trim_bwc.num_seconds),
            );
            p.add_field(
                "user_data_trim_bwc_num_occured",
                TsValue::Long(user_data_trim_bwc.num_occured),
            );
        }

        if let Some(user_data_sdc_read_latency) = &self.user_data_sdc_read_latency {
            p.add_field(
                "user_data_sdc_read_latency_total_weight_in_kb",
                TsValue::Long(user_data_sdc_read_latency.total_weight_in_kb),
            );
            p.add_field(
                "user_data_sdc_read_latency_num_seconds",
                TsValue::Long(user_data_sdc_read_latency.num_seconds),
            );
            p.add_field(
                "user_data_sdc_read_latency_num_occured",
                TsValue::Long(user_data_sdc_read_latency.num_occured),
            );
        }

        if let Some(user_data_sdc_write_latency) = &self.user_data_sdc_write_latency {
            p.add_field(
                "user_data_sdc_write_latency_total_weight_in_kb",
                TsValue::Long(user_data_sdc_write_latency.total_weight_in_kb),
            );
            p.add_field(
                "user_data_sdc_write_latency_num_seconds",
                TsValue::Long(user_data_sdc_write_latency.num_seconds),
            );
            p.add_field(
                "user_data_sdc_write_latency_num_occured",
                TsValue::Long(user_data_sdc_write_latency.num_occured),
            );
        }

        if let Some(user_data_sdc_trim_latency) = &self.user_data_sdc_trim_latency {
            p.add_field(
                "user_data_sdc_trim_latency_total_weight_in_kb",
                TsValue::Long(user_data_sdc_trim_latency.total_weight_in_kb),
            );
            p.add_field(
                "user_data_sdc_trim_latency_num_seconds",
                TsValue::Long(user_data_sdc_trim_latency.num_seconds),
            );
            p.add_field(
                "user_data_sdc_trim_latency_num_occured",
                TsValue::Long(user_data_sdc_trim_latency.num_occured),
            );
        }

        points.push(p);
        points
    }
}

#[test]
fn test_system_stats() {
    use std::fs::File;
    use std::io::Read;

    let mut f = File::open("tests/scaleio/system_statistics.json").unwrap();
    let mut buff = String::new();
    f.read_to_string(&mut buff).unwrap();
    println!("buff: {}", buff);

    let i: SystemStatistics = serde_json::from_str(&buff).unwrap();
    println!("result: {:#?}", i);

    let points = i.into_point(None, true);
}

#[serde(rename_all = "camelCase")]
#[derive(Clone, Deserialize, Debug)]
pub struct TieBreaker {
    pub openssl_version: String,
    #[serde(rename = "managementIPs")]
    pub management_ips: Vec<String>,
    pub ips: Vec<String>,
    pub version_info: String,
    pub role: String,
    pub status: Option<String>,
    pub name: String,
    pub id: String,
    pub port: u16,
}

#[serde(rename_all = "camelCase")]
#[derive(Clone, Deserialize, Debug)] 
pub struct Window {
    threshold: u64,
    window_size_in_sec: u64,
}

fn get<T>(client: &reqwest::Client, config: &ScaleioConfig, api: &str) -> MetricsResult<T>
where
    T: DeserializeOwned + Debug,
{
    let res: Result<T, reqwest::Error> = client
        .get(&format!("https://{}/api/{}", config.endpoint, api))
        .basic_auth(config.user.clone(), Some(config.password.clone()))
        .send()?
        .error_for_status()?
        .json();
    debug!("deserialized: {:?}", res);
    Ok(res?)
}

// Connect to the metadata server and request a new api token
pub fn get_api_token(client: &reqwest::Client, config: &ScaleioConfig) -> MetricsResult<String> {
    let mut token = client
        .get(&format!("https://{}/api/login", config.endpoint))
        .basic_auth(config.user.clone(), Some(config.password.clone()))
        .send()?
        .error_for_status()?;
    let t = token.text()?;
    trace!("api token: {}", t);

    match api_token(t.as_bytes()) {
        IResult::Done(_, o) => Ok(o.into()),
        IResult::Incomplete(_) => Err(StorageError::new(format!(
            "Unable to parse api token {} from server",
            t
        ))),
        IResult::Error(e) => Err(StorageError::new(e.to_string())),
    }
}

#[test]
fn test_api_token_parser() {
    let raw_token = "\"YXV0b21hdGlvbjoxNTE1MTk4NjYzNDg0OjJiOWFhODhiYzliY2Y5O\
                     WU3OTc1OGVjMmM0MzgyZGE0\"";
    let expected = "YXV0b21hdGlvbjoxNTE1MTk4NjYzNDg0OjJiOWFhODhi\
                    YzliY2Y5OWU3OTc1OGVjMmM0MzgyZGE0";
    let res = api_token(raw_token.as_bytes());
    println!("parsed api_token: {:?}", res);
    assert_eq!(
        api_token(raw_token.as_bytes()),
        IResult::Done(&b""[..], expected)
    );
}

// We parse any value surrounded by quotes, ignoring all whitespaces around those
named!(
    api_token<&str>,
    ws!(delimited!(
        tag!("\""),
        map_res!(take_until!("\""), str::from_utf8),
        tag!("\"")
    ))
);

impl Scaleio {
    pub fn new(client: &reqwest::Client, mut config: ScaleioConfig) -> MetricsResult<Self> {
        let token = get_api_token(client, &config)?;
        config.password = token;
        Ok(Scaleio {
            client: client.clone(),
            config,
        })
    }
    // Get the basic cluster configuration
    pub fn get_configuration(&self) -> MetricsResult<SystemConfig> {
        // Ask scaleio for the system configuration information
        let sys_config = get::<SystemConfig>(&self.client, &self.config, "Configuration")?;
        Ok(sys_config)
    }

    // Dump all drive information.  Call get_sds_object afterwards to turn the sdsId into
    // more useful information
    pub fn get_drive_instances(&self, t: DateTime<Utc>) -> MetricsResult<Vec<TsPoint>> {
        let instances = get::<Vec<Instance>>(&self.client, &self.config, "types/Device/instances")
            .map(|instance| {
                let points: Vec<TsPoint> = instance
                    .iter()
                    .flat_map(|instance| instance.into_point(Some("scaleio_drive"), true))
                    .map(|mut point| {
                        point.timestamp = Some(t);
                        point
                    })
                    .collect();
                points
            })?;
        Ok(instances)
    }

    pub fn get_drive_ids(&self) -> MetricsResult<Vec<DriveId>> {
        let instance_ids =
            get::<Vec<Instance>>(&self.client, &self.config, "types/Device/instances").map(
                |instances| {
                    let ids = instances
                        .iter()
                        .map(|instance| DriveId {
                            id: instance.id.clone(),
                            sds_id: instance.sds_id.clone(),
                            storage_pool_id: instance.storage_pool_id.clone(),
                        })
                        .collect::<Vec<DriveId>>();
                    ids
                },
            )?;
        Ok(instance_ids)
    }

    pub fn get_sds_ids(&self) -> MetricsResult<Vec<String>> {
        let sds_ids = get::<Vec<SdsObject>>(&self.client, &self.config, "types/Sds/instances")
            .map(|sds_objects| {
                let ids = sds_objects
                    .iter()
                    .map(|sds| sds.id.clone())
                    .collect::<Vec<String>>();
                ids
            })?;

        Ok(sds_ids)
    }

    pub fn get_sds_statistics(
        &self,
        t: DateTime<Utc>,
        sds_id: &str,
    ) -> MetricsResult<Vec<TsPoint>> {
        let instance_statistics = get::<SdsStatistics>(
            &self.client,
            &self.config,
            &format!("instances/Sds::{}/relationships/Statistics", sds_id),
        )
        .map(|instance| {
            let points: Vec<TsPoint> = instance
                .into_point(Some("scaleio_sds_stat"), true)
                .iter_mut()
                .map(|point| {
                    point.timestamp = Some(t);
                    point.add_tag("sds_id", TsValue::String(sds_id.to_string()));
                    point.clone()
                })
                .collect();
            points
        })?;

        Ok(instance_statistics)
    }

    //ids is (device_id, sds_id, storage_pool_id)
    pub fn get_drive_statistics(
        &self,
        t: DateTime<Utc>,
        ids: &DriveId,
    ) -> MetricsResult<Vec<TsPoint>> {
        let instance_statistics = get::<DeviceStatistics>(
            &self.client,
            &self.config,
            &format!("instances/Device::{}/relationships/Statistics", ids.id),
        )
        .map(|instance| {
            let points: Vec<TsPoint> = instance
                .into_point(Some("scaleio_drive_stat"), true)
                .into_iter()
                .map(|mut point| {
                    point.timestamp = Some(t);
                    point.add_tag("device_id", TsValue::String(ids.id.to_string()));
                    point.add_tag("sds_id", TsValue::String(ids.sds_id.to_string()));
                    point.add_tag(
                        "storage_pool_id",
                        TsValue::String(ids.storage_pool_id.to_string()),
                    );
                    point
                })
                .collect();
            points
        })?;

        Ok(instance_statistics)
    }

    // Get all the drive stats.  This hashmap is referenced by sdsId.
    pub fn get_drive_stats(&self) -> MetricsResult<DeviceSelectedStatisticsResponse> {
        let stats_req = SelectedStatisticsRequest {
            selected_statistics_list: vec![StatsRequest {
                req_type: StatsRequestType::Device,
                all_ids: vec![],
                properties: vec![
                    // TODO: Change this into an enum
                    "fixedReadErrorCount".into(),
                    "avgReadSizeInBytes".into(),
                    "avgWriteSizeInBytes".into(),
                    "avgReadLatencyInMicrosec".into(),
                    "avgWriteLatencyInMicrosec".into(),
                ],
            }],
        };

        // Contact scaleio metadata server and parse the results
        // back into json.  If the call isn't an http success result
        // then return an error
        let mut resp = self
            .client
            .post(&format!(
                "https://{}/api/instances/querySelectedStatistics",
                self.config.endpoint
            ))
            .header(CONTENT_TYPE, "application/json")
            .basic_auth(&self.config.user, Some(&self.config.password))
            .json(&stats_req)
            .send()?
            .error_for_status()?;
        let json_resp: DeviceSelectedStatisticsResponse = resp.json()?;
        Ok(json_resp)
    }

    /// Gets all instances
    pub fn get_instances(&self) -> MetricsResult<()> {
        let instances = self
            .client
            .get(&format!("https://{}/api/instances", self.config.endpoint,))
            .basic_auth(&self.config.user, Some(&self.config.password))
            .send()?
            .error_for_status()?
            .text()?;
        println!("instances: {}", instances);

        Ok(())
    }

    pub fn get_pool_info(&self, pool_id: &str) -> MetricsResult<PoolInstanceResponse> {
        let pool_info = get::<PoolInstanceResponse>(
            &self.client,
            &self.config,
            &format!("instances/StoragePool::{}", pool_id),
        )?;
        Ok(pool_info)
    }

    pub fn get_pool_stats(&self) -> MetricsResult<ClusterSelectedStatisticsResponse> {
        let stats_req = SelectedStatisticsRequest {
            selected_statistics_list: vec![StatsRequest {
                req_type: StatsRequestType::StoragePool,
                all_ids: vec![],
                properties: vec![
                    "numOfDevices".into(),
                    "numOfVolumes".into(),
                    "capacityLimitInKb".into(),
                    "thickCapacityInUseInKb".into(),
                    "thinCapacityInUseInKb".into(),
                    "primaryReadBwc".into(),
                    "primaryWriteBwc".into(),
                    "secondaryReadBwc".into(),
                    "secondaryWriteBwc".into(),
                    "totalReadBwc".into(),
                    "totalWriteBwc".into(),
                    "thinCapacityAllocatedInKm".into(),
                ],
            }],
        };

        // Contact scaleio metadata server and parse the results
        // back into json.  If the call isn't an http success result
        // then return an error
        let mut resp = self
            .client
            .post(&format!(
                "https://{}/api/instances/querySelectedStatistics",
                self.config.endpoint
            ))
            .header(CONTENT_TYPE, "application/json")
            .basic_auth(&self.config.user, Some(&self.config.password))
            .json(&stats_req)
            .send()?
            .error_for_status()?;
        let json_resp: ClusterSelectedStatisticsResponse = resp.json()?;
        Ok(json_resp)
    }

    pub fn get_sdc_stats(&self) -> MetricsResult<Vec<TsPoint>> {
        let stats_req = SelectedStatisticsRequest {
            selected_statistics_list: vec![StatsRequest {
                req_type: StatsRequestType::Sdc,
                all_ids: vec![],
                properties: vec![
                    "userDataReadBwc".into(),
                    "userDataWriteBwc".into(),
                    "volumeIds".into(),
                    "numOfMappedVolumes".into(),
                ],
            }],
        };
        let mut resp = self
            .client
            .post(&format!(
                "https://{}/api/instances/querySelectedStatistics",
                self.config.endpoint
            ))
            .header(CONTENT_TYPE, "application/json")
            .basic_auth(&self.config.user, Some(&self.config.password))
            .json(&stats_req)
            .send()?
            .error_for_status()?;
        debug!("deserialized: {:?}", resp);
        let json_resp: SdcSelectedStatisticsResponse = resp.json()?;
        Ok(json_resp.into_point(Some("scaleio_sdc_stats"), true))
    }

    pub fn get_sdc_objects(
        &self,
        system_id: &str,
        t: DateTime<Utc>,
    ) -> MetricsResult<Vec<TsPoint>> {
        let sdc_info = get::<Vec<Sdc>>(
            &self.client,
            &self.config,
            &format!("instances/System::{}/relationships/Sdc", system_id),
        )
        .map(|sdc_objects| {
            let points: Vec<TsPoint> = sdc_objects
                .iter()
                .flat_map(|sdc| sdc.into_point(Some("scaleio_sdc"), true))
                .map(|mut point| {
                    point.timestamp = Some(t);
                    point
                })
                .collect();
            points
        })?;
        Ok(sdc_info)
    }

    // Use this to gather more information about the sds device like
    // ip address, state, storage server attached to, etc
    pub fn get_sds_object(&self, sds_id: &str) -> MetricsResult<SdsObject> {
        let sds_object = get::<SdsObject>(
            &self.client,
            &self.config,
            &format!("instances/Sds::{}", sds_id),
        )?;
        Ok(sds_object)
    }

    pub fn get_sds_objects(&self, t: DateTime<Utc>) -> MetricsResult<Vec<TsPoint>> {
        let sds_info = get::<Vec<SdsObject>>(&self.client, &self.config, "types/Sds/instances")
            .map(|sds_objects| {
                let points: Vec<TsPoint> = sds_objects
                    .iter()
                    .flat_map(|sds| sds.into_point(Some("scaleio_sds"), true))
                    .map(|mut point| {
                        point.timestamp = Some(t);
                        point
                    })
                    .collect();
                points
            })?;
        Ok(sds_info)
    }

    pub fn get_system_stats(
        &self,
        system_id: &str,
        t: DateTime<Utc>,
    ) -> MetricsResult<Vec<TsPoint>> {
        let systemstats = get::<SystemStatistics>(
            &self.client,
            &self.config,
            &format!("instances/System::{}/relationships/Statistics", system_id),
        )
        .map(|system_stats| {
            let points: Vec<TsPoint> = system_stats
                .into_point(Some("scaleio_sys_stats"), true)
                .into_iter()
                .map(|mut point| {
                    point.timestamp = Some(t);
                    point.add_tag("sys_id", TsValue::String(system_id.to_string()));
                    point
                })
                .collect();
            points
        })?;
        Ok(systemstats)
    }

    pub fn get_system(&self, system_id: &str) -> MetricsResult<System> {
        let system = get::<System>(
            &self.client,
            &self.config,
            &format!("instances/System::{}", system_id),
        )?;
        Ok(system)
    }

    pub fn get_systems(&self) -> MetricsResult<Vec<System>> {
        let systems = get::<Vec<System>>(&self.client, &self.config, "types/System/instances")?;
        Ok(systems)
    }

    pub fn get_version(&self) -> MetricsResult<String> {
        let version = self
            .client
            .get(&format!("https://{}/api/version", self.config.endpoint))
            .basic_auth(&self.config.user, Some(&self.config.password))
            .send()?
            .error_for_status()?
            .text()?;
        Ok(version)
    }

    pub fn get_volumes(&self, t: DateTime<Utc>) -> MetricsResult<Vec<TsPoint>> {
        let sds_vols = get::<Vec<SdsVolume>>(&self.client, &self.config, "types/Volume/instances")
            .map(|sds_vols| {
                let points: Vec<TsPoint> = sds_vols
                    .iter()
                    .flat_map(|vol| vol.into_point(Some("scaleio_volume"), true))
                    .map(|mut point| {
                        point.timestamp = Some(t);
                        point
                    })
                    .collect();
                points
            })?;
        Ok(sds_vols)
    }

    /// Creates a volume on the given endpoint using the credentials specified
    /// in the config file. Automatically selects a storage pool
    /// vol_name_prefix refers to the tracking ID/ticket ID of the request
    pub fn create_volume(
        &self,
        vol_name_prefix: &str,
        requested_size_in_kb: u64,
        num_of_luns: usize,
        mut spare_cutoff: u8,
    ) -> MetricsResult<Vec<String>> {
        // Set minimum cut off
        if spare_cutoff <= 10 {
            spare_cutoff = 10
        }

        // First, get a list of available pools
        let storage_pools = get::<Vec<PoolInstanceResponse>>(
            &self.client,
            &self.config,
            "types/StoragePool/instances",
        )?;

        // don't need storage_pools later on, OK to move
        let pool_ids: Vec<String> = identify_ideal_pools(storage_pools, num_of_luns, spare_cutoff)?;

        // Could be more defensive and check if pool_ids is empty.
        // identify_ideal_pools() should ideally return an error in that case.
        // So, skip that check.
        if pool_ids.len() < num_of_luns {
            debug!(
                "Cannot create volumes in {} pools, creating in {} instead",
                num_of_luns,
                pool_ids.len()
            );
        }
        // Create each volume with sizes balanced over pools
        let each_vol_size_in_kb = requested_size_in_kb / (pool_ids.len() as u64);

        let mut volume_ids: Vec<String> = Vec::new();

        for (vol_num, pool_id) in pool_ids.iter().enumerate() {
            debug!(
                "Creating volume of size {} in pool with ID {}",
                each_vol_size_in_kb,
                pool_id.to_string()
            );
            let vol_creation_req = VolumeRequest::new(
                each_vol_size_in_kb,
                pool_id.to_string(),
                format!("{}_{}", vol_name_prefix, vol_num),
            );
            // post a request to endpoint to create a volume. If call isn't
            // an http success result, return an error. Return is newly created volume ID
            let mut vol_creation_resp = self
                .client
                .post(&format!(
                    "https://{}/api/types/Volume/instances",
                    self.config.endpoint
                ))
                .header(CONTENT_TYPE, "application/json")
                .basic_auth(&self.config.user, Some(&self.config.password))
                .json(&vol_creation_req)
                .send()?
                .error_for_status()?;
            let json_resp: String = vol_creation_resp.json()?;
            volume_ids.push(json_resp);
        }

        // Did we succeed in creating as many as intended?
        if volume_ids.len() != pool_ids.len() {
            debug!(
                "Created only {} volumes. {} intended",
                volume_ids.len(),
                pool_ids.len()
            );
            debug!("Request is not met in full");
            // TODO: Rollback/delete these volumes without mapping?
        }
        Ok(volume_ids)
    }

    /// Returns the sdcId corresponding to the given name
    fn get_sdc_id_from_name(&self, sdc_name: &str) -> MetricsResult<String> {
        // get a list of all sdc's, filter entry that matches sdc_name
        // and return corresponding sdc_id

        debug!("Retrieving SDC ID for {}", sdc_name);
        let sdc_info = get::<Vec<Sdc>>(&self.client, &self.config, "api/types/Sdc/instances").map(
            |sdc_objects| {
                let ids: Vec<String> = sdc_objects
                    .iter()
                    .filter(|sdc| match sdc.name {
                        Some(ref name) => name == sdc_name,
                        None => false,
                    })
                    .map(|sdc| sdc.id.clone())
                    .collect::<Vec<String>>();
                ids
            },
        )?;

        if !sdc_info.is_empty() {
            if let Some(id) = sdc_info.get(0) {
                Ok(id.to_string())
            } else {
                Err(StorageError::new(format!(
                    "SDC ID not found for {}",
                    sdc_name
                )))
            }
        } else {
            Err(StorageError::new(format!(
                "SDC ID not found for {}",
                sdc_name
            )))
        }
    }

    /// Maps all the volumes in the list to the given sdc
    /// Also sets iops and bandwidth limits
    pub fn map_volumes(&self, volume_ids: &[String], sdc_name: &str) -> MetricsResult<bool> {
        // Get sdc_id from sdc_name
        let sdc_id = self.get_sdc_id_from_name(sdc_name)?;
        debug!("SDC ID for {} is {}", sdc_name, sdc_id);

        for vol_id in volume_ids {
            debug!("Mapping {} to {}", vol_id, sdc_id);

            let mut sdc_map = HashMap::new();
            sdc_map.insert("sdcId", sdc_id.clone());

            // TODO: allow multiple mappings?

            // Returns only http status of success or failure
            let mut _resp = self
                .client
                .post(&format!(
                    "https://{}/api/instances/Volume::{}/action/addMappedSdc",
                    self.config.endpoint, vol_id
                ))
                .header(CONTENT_TYPE, "application/json")
                .basic_auth(&self.config.user, Some(&self.config.password))
                .json(&sdc_map)
                .send()?
                .error_for_status()?;

            let mut sdc_limits = HashMap::new();
            sdc_limits.insert("sdcId", sdc_id.clone());

            if let Some(limit) = &self.config.bandwidth_limit {
                sdc_limits.insert("bandwidthLimitInKbps", limit.to_string());
            } else {
                sdc_limits.insert("bandwidthLimitInKbps", "0".to_string());
            }
            if let Some(limit) = &self.config.iops_limit {
                sdc_limits.insert("iopsLimit", limit.to_string());
            } else {
                sdc_limits.insert("iopsLimit", "0".to_string());
            }

            debug!("Adding bandwidth limits to volume with ID {}", vol_id);
            let mut _resp = self
                .client
                .post(&format!(
                    "https://{}/api/instances/Volume::{}/action/setMappedSdcLimits",
                    self.config.endpoint, vol_id
                ))
                .header(CONTENT_TYPE, "application/json")
                .basic_auth(&self.config.user, Some(&self.config.password))
                .json(&sdc_limits)
                .send()?
                .error_for_status()?;
        }
        Ok(true)
    }
}

#[derive(Serialize, Debug)]
pub enum VolumeRequestType {
    ThinProvisioned,
    ThickProvisioned,
}

#[serde(rename_all = "camelCase")]
#[derive(Serialize, Debug)]
pub struct VolumeRequest {
    pub volume_size_in_kb: String,
    pub storage_pool_id: String,
    pub name: String,
    pub volume_type: VolumeRequestType,
    pub use_rmcache: bool,
}

impl VolumeRequest {
    fn new(volume_size_int: u64, storage_pool_id: String, name: String) -> VolumeRequest {
        VolumeRequest {
            volume_size_in_kb: volume_size_int.to_string(),
            storage_pool_id,
            name,
            volume_type: VolumeRequestType::ThinProvisioned,
            use_rmcache: true,
        }
    }
}
/// Finds the ideal pools where volumes need to be created.
/// Returns a vector of pool_ids, will never return an empty list
/// Available space and percent provisioned are considered
/// when identifying the pools.
fn identify_ideal_pools(
    mut storage_pools: Vec<PoolInstanceResponse>,
    num_of_pools: usize,
    spare_cutoff: u8,
) -> MetricsResult<Vec<String>> {
    if !storage_pools.is_empty() {
        let mut ids: Vec<String> = Vec::new();

        // Retain only those pools which pass the cutoff
        storage_pools.retain(|each| each.spare_percentage > spare_cutoff);
        if storage_pools.is_empty() {
            // None have enough spare space
            return Err(StorageError::new(format!(
                "All storage pools are above
                                    cutoff of {}%",
                spare_cutoff
            )));
        }
        // Now reverse sort storage_pools based on the 'spare_percentage' field
        storage_pools.sort_unstable_by(|a, b| b.spare_percentage.cmp(&a.spare_percentage));

        let available_pools: usize = if storage_pools.len() < num_of_pools {
            storage_pools.len()
        } else {
            num_of_pools
        };

        for i in 0..available_pools {
            if let Some(element) = storage_pools.get(i) {
                let pool_id = &element.id;
                ids.push(pool_id.to_string());
            }
        }
        if !ids.is_empty() {
            Ok(ids)
        } else {
            // storage_pools is not empty, but did not find any elements?
            Err(StorageError::new(
                "Failed to identify ideal pool to create volume".to_string(),
            ))
        }
    } else {
        Err(StorageError::new("No storage pools found".to_string()))
    }
}

/* Uncomment this when this test should run
#[test]
fn test_create_and_map_volume() {
    use self::serde_json;
    use self::simplelog::{Config, TermLogger};
    use std::fs::File;
    use std::io::{Error as ioError, ErrorKind};

    // read config file
    TermLogger::new(log::LevelFilter::Debug, Config::default()).unwrap();
    let config_file = "/newDevice/tests/scaleio_wc.json".to_string();
    let config_file_fd = File::open(&config_file).unwrap();

    let config: serde_json::Value = serde_json::from_reader(config_file_fd)
        .map_err(|e| ioError::new(ErrorKind::InvalidData, e.to_string()))
        .unwrap();

    debug!("Read file");
    let mut scaleio_config = ScaleioConfig {
        user: config["username"]
            .as_str()
            .expect("User name is missing")
            .to_string(),
        password: config["password"]
            .as_str()
            .expect("password is missing")
            .to_string(),
        endpoint: config["endpoint"]
            .as_str()
            .expect("endpoint is missing")
            .to_string(),
        region: config["region"]
            .as_str()
            .expect("region is missing")
            .to_string(),
        bandwidth_limit: {
            if let Some(b) = config["bandwidth"].as_u64() {
                Some(b)
            } else {
                // unspecified, set unlimited
                Some(0)
            }
        },
        iops_limit: {
            if let Some(c) = config["iops"].as_u64() {
                Some(c)
            } else {
                // unspecified, set unlimited
                Some(0)
            }
        },
        certificate: None,
    };

    debug!("Config is {:#?}", scaleio_config);
    let vol_size: u64 = config["total_size"].as_u64().unwrap();
    let luns = config["no_of_luns"].as_u64().unwrap();
    let sdc_hostname = config["sdc_hostname"]
        .as_str()
        .expect("SDC hostname is missing");
    let spare_cutoff: u8 = config["spare_cutoff"].as_u8().unwrap();

    let web_client = reqwest::Client::builder().build().unwrap();

    let token = get_api_token(&web_client, &scaleio_config).unwrap();
    // valid 10 mins
    scaleio_config.password = token;

    let vols = create_volume(
        &web_client,
        &scaleio_config,
        "LIBTEST",
        vol_size,
        luns as usize,
        spare_cutoff,
    ).unwrap();
    println!("{:#?}", vols);

    map_volumes(&web_client, &scaleio_config, vols, &sdc_hostname).unwrap();
} */