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
//! 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,
}

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,
        })
    }
}

#[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 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)]
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 {
    InitialTest,
    InitialTestDone,
    Normal,
    NormalTesting,
    RemovePending,
}

impl ToString for DeviceState {
    fn to_string(&self) -> String {
        match *self {
            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);
}

#[serde(rename_all = "camelCase")]
#[derive(Deserialize, Debug)]
pub struct DeviceStatistics {
    avg_write_size_in_bytes: u64,
    active_moving_in_fwd_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_rebalance_jobs: u64,
    active_moving_in_norm_rebuild_jobs: u64,
    active_moving_in_bck_rebuild_jobs: u64,
    active_moving_out_norm_rebuild_jobs: u64,
    avg_read_latency_in_microsec: u64,
    avg_write_latency_in_microsec: u64,
    avg_read_size_in_bytes: u64,
    #[serde(rename = "BackgroundScanCompareCount")]
    background_scan_compare_count: u64,
    #[serde(rename = "BackgroundScannedInMB")]
    background_scanned_in_mb: u64,
    bck_rebuild_write_bwc: BWC,
    bck_rebuild_read_bwc: BWC,
    capacity_in_use_in_kb: u64,
    degraded_healthy_vac_in_kb: u64,
    degraded_failed_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,
    norm_rebuild_read_bwc: BWC,
    norm_rebuild_write_bwc: BWC,
    pending_moving_in_bck_rebuild_jobs: u64,
    pending_moving_out_bck_rebuild_jobs: u64,
    pending_moving_in_norm_rebuild_jobs: u64,
    pending_moving_rebalance_jobs: u64,
    pending_moving_out_normrebuild_jobs: u64,
    pending_moving_in_rebalance_jobs: u64,
    pending_moving_in_fwd_rebuild_jobs: u64,
    pending_moving_out_fwd_rebuild_jobs: u64,
    primary_read_from_rmcache_bwc: BWC,
    primary_read_from_dev_bwc: BWC,
    primary_read_bwc: BWC,
    primary_vac_in_kb: u64,
    protected_vac_in_kb: u64,
    primary_write_bwc: BWC,
    rebalance_read_bwc: BWC,
    rebalance_write_bwc: BWC,
    rfcache_avg_read_time: u64,
    rfcache_io_errors: u64,
    rfcache_reads_skipped_internal_error: u64,
    rfcache_source_device_writes: u64,
    rfcache_reads_skipped_low_resources: u64,
    rfcache_reads_skipped_max_io_size: u64,
    rfcache_reads_skipped_aligned_size_too_large: u64,
    rfcache_writes_skipped_internal_error: u64,
    rfcache_writes_skipped_stuck_io: u64,
    rfcache_writes_skipped_cache_miss: u64,
    rfcache_writes_skipped_heavy_load: u64,
    rfcache_write_miss: u64,
    rfcache_writes_skipped_low_resources: u64,
    rfcache_reads_from_cache: u64,
    rfcache_ios_outstanding: u64,
    rfcache_skipped_unlined_write: u64,
    rfcache_writes_received: u64,
    rfcache_write_pending: u64,
    rfcache_writes_skipped_max_io_size: u64,
    rfcache_reads_skipped_stuck_io: u64,
    rfcache_reads_skipped: u64,
    rfcache_reads_received: u64,
    rfcache_ios_skipped: u64,
    rfcache_read_miss: u64,
    rfcache_reads_skipped_lock_ios: u64,
    rfache_read_hit: u64,
    rfcache_avg_write_time: u64,
    rfcache_source_device_reads: u64,
    rfcache_reads_skipped_heavy_load: u64,
    rfcache_reads_pending: u64,
    rm_pending_allocated_in_kb: u64,
    secondary_read_from_dev_bwc: BWC,
    secondary_vac_in_kb: u64,
    secondary_read_bwc: BWC,
    secondary_read_from_rmcache_bwc: BWC,
    secondary_write_bwc: BWC,
    snap_capacity_in_use_occupied_in_kb: u64,
    snap_capacity_in_use_in_kb: u64,
    thick_capacity_in_use_in_kb: u64,
    thin_capacity_in_use_in_kb: u64,
    thin_capacity_allocated_in_km: u64,
    total_read_bwc: BWC,
    total_write_bwc: BWC,
    unused_capacity_in_kb: u64,
    unreachable_unused_capacity_in_kb: u64,
    semi_protected_vac_in_kb: u64,
}

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),
        );
        p.add_field(
            "primary_read_bwc",
            TsValue::Long(self.primary_read_bwc.average()),
        );
        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),
        );
        p.add_field(
            "primary_write_bwc",
            TsValue::Long(self.primary_write_bwc.average()),
        );
        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.average()),
        );
        p.add_field(
            "total_write_bwc",
            TsValue::Long(self.total_write_bwc.average()),
        );
        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),
        );
        p.add_field(
            "rebalance_read_bwc",
            TsValue::Long(self.rebalance_read_bwc.average()),
        );
        p.add_field(
            "rebalance_write_bwc",
            TsValue::Long(self.rebalance_write_bwc.average()),
        );

        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)]
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 {
    Custom,
    Default,
    HighPerformance,
}

impl ToString for PerfProfile {
    fn to_string(&self) -> String {
        match *self {
            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: SelectedStatisticsResponse = 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);
}

#[derive(Deserialize, Debug)]
pub struct SelectedStatisticsResponse {
    #[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 {
    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,
}

#[serde(rename_all = "camelCase")]
#[derive(Clone, Deserialize, Debug, IntoPoint)]
pub struct Instance {
    pub device_current_path_name: String,
    pub device_original_path_name: String,
    pub rfcache_error_device_does_not_exist: bool,
    pub sds_id: String,
    pub device_state: DeviceState,
    pub capacity_limit_in_kb: Option<u64>,
    pub max_capacity_in_kb: u64,
    pub storage_pool_id: String,
    pub long_successful_ios: Option<Successfulio>,
    pub error_state: String,
    pub name: Option<String>,
    pub id: String,
    pub links: Vec<Link>,
    pub update_configuration: Option<bool>,
}

#[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>,
    pub good_nodes_num: u16,
    pub good_replicas_num: u16,
    pub cluster_state: String,
    pub name: String,
    pub id: String,
}

#[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 {
    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,
    pub capacity_alert_high_threshold_percent: u16,
    pub capacity_alert_critical_threshold_percent: u16,
    pub remote_read_only_limit_state: bool,
    pub upgrade_state: String,
    pub mdm_management_port: u16,
    pub sdc_mdm_network_disconnections_counter_parameters: FailureCounter,
    pub sdc_sds_network_disconnections_counter_parameters: FailureCounter,
    pub sdc_memory_allocation_failures_counter_parameters: FailureCounter,
    pub sdc_socket_allocation_failures_counter_parameters: FailureCounter,
    pub sdc_long_operations_counter_parameters: FailureCounter,
    pub cli_password_allowed: bool,
    pub management_client_secure_communication_enabled: bool,
    pub tls_version: String,
    pub show_guid: bool,
    pub authentication_method: String,
    pub mdm_to_sds_policy: String,
    pub mdm_cluster: MdmCluster,
    pub perf_profile: PerfProfile,
    pub install_id: String,
    pub days_installed: u64,
    #[serde(deserialize_with = "deserialize_string_or_int")]
    pub max_capacity_in_gb: i64,
    pub capacity_time_left_in_days: String,
    pub enterprise_features_enabled: bool,
    pub is_initial_license: bool,
    pub default_is_volume_obfuscated: bool,
    pub restricted_sdc_mode_enabled: bool,
    pub swid: String,
    pub name: String,
    pub id: String,
    pub links: Vec<HashMap<String, String>>,
}

#[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())),
    }
}

impl Scaleio {
    // 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")
            .and_then(|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();
                Ok(points)
            })?;
        Ok(instances)
    }

    pub fn get_drive_ids(&self) -> MetricsResult<Vec<String>> {
        let instance_ids =
            get::<Vec<Instance>>(&self.client, &self.config, "types/Device/instances").and_then(
                |instances| {
                    let ids = instances
                        .iter()
                        .map(|instance| instance.id.clone())
                        .collect::<Vec<String>>();
                    Ok(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")
            .and_then(|sds_objects| {
                let ids = sds_objects
                    .iter()
                    .map(|sds| sds.id.clone())
                    .collect::<Vec<String>>();
                Ok(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),
        )
        .and_then(|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();
            Ok(points)
        })?;

        Ok(instance_statistics)
    }

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

        Ok(instance_statistics)
    }

    // Get all the drive stats.  This hashmap is referenced by sdsId.
    pub fn get_drive_stats(&self) -> MetricsResult<SelectedStatisticsResponse> {
        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: SelectedStatisticsResponse = 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(())
    }
}

#[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 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_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),
        )
        .and_then(|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();
            Ok(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")
            .and_then(|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();
                Ok(points)
            })?;
        Ok(sds_info)
    }

    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")
            .and_then(|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();
                Ok(points)
            })?;
        Ok(sds_vols)
    }
}

#[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(|ref 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()))
    }
}

impl Scaleio {
    /// 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")
            .and_then(|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>>();
                Ok(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)
    }
}
/* 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();
} */