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
#![allow(non_snake_case)]

/**
* 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 std::collections::HashMap;
use std::str;
use std::str::FromStr;

use crate::error::{MetricsResult, StorageError};
use crate::ir::{TsPoint, TsValue};
use crate::IntoPoint;

use chrono::offset::Utc;
use chrono::DateTime;
use csv::Reader;
use log::{error, trace, warn};
use reqwest::header::ACCEPT;

pub struct Hitachi {
    client: reqwest::Client,
    config: HitachiConfig,
}

impl Hitachi {
    pub fn new(client: &reqwest::Client, config: HitachiConfig) -> Self {
        Hitachi {
            client: client.clone(),
            config,
        }
    }
}

#[derive(Deserialize, Debug)]
pub struct Collection {
    pub items: Vec<HashMap<String, serde_json::Value>>,
}

#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ConfigManagerStorage {
    pub storage_device_id: String,
    pub model: String,
    pub serial_number: u64,
    pub svp_ip: String,
}

#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LdevPort {
    pub port_id: String,
    pub host_group_number: u64,
    pub host_group_name: String,
    pub lun: u64,
}

impl IntoPoint for LdevPort {
    fn into_point(&self, name: Option<&str>, is_time_series: bool) -> Vec<TsPoint> {
        let mut p = TsPoint::new(name.unwrap_or_else(|| "hitachi_ldev_port"), is_time_series);
        p.add_tag("port_id", TsValue::String(self.port_id.clone()));
        p.add_field("host_group_number", TsValue::Long(self.host_group_number));
        p.add_tag(
            "host_group_name",
            TsValue::String(self.host_group_name.clone()),
        );
        p.add_field("lun", TsValue::String(convert_to_base16(self.lun)));

        vec![p]
    }
}

#[derive(Clone, Debug, Deserialize)]
pub struct ServerResult<T> {
    #[serde(bound(deserialize = "T: serde::de::Deserialize<'de>"))]
    pub data: Vec<T>,
}

#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StorageLdev {
    pub ldev_id: u64,
    pub clpr_id: u64,
    pub emulation_type: String,
    pub byte_format_capacity: String,
    pub block_capacity: u64,
    pub num_of_ports: u64,
    pub ports: Vec<LdevPort>,
    pub attributes: Vec<String>,
    pub status: String,
    pub mp_blade_id: u64,
    pub ssid: String,
    pub pool_id: u64,
    pub num_of_used_block: u64,
    pub is_relocation_enabled: bool,
    pub tier_level: String,
    pub used_capacity_per_tier_level1: u64,
    pub used_capacity_per_tier_level2: u64,
    pub used_capacity_per_tier_level3: Option<u64>,
    pub tier_level_for_new_page_allocation: String,
    pub resource_group_id: u64,
    pub data_reduction_status: String,
    pub data_reduction_mode: String,
    pub is_alua_enabled: bool,
}

impl IntoPoint for StorageLdev {
    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_else(|| "hitachi_ldev"), is_time_series);

        p.add_field("ldev_id", TsValue::String(convert_to_base16(self.ldev_id)));
        p.add_field("clpr_id", TsValue::Long(self.clpr_id));
        p.add_tag(
            "emulation_type",
            TsValue::String(self.emulation_type.clone()),
        );
        p.add_tag(
            "byte_format_capacity",
            TsValue::String(self.byte_format_capacity.clone()),
        );
        p.add_field(
            "block_capacity",
            TsValue::Long((self.block_capacity * 512) / 1024u64.pow(3)),
        );
        p.add_field("num_of_ports", TsValue::Long(self.num_of_ports));
        for port in &self.ports {
            let port_points: Vec<TsPoint> = port
                .into_point(Some("hitachi_ldev_port"), is_time_series)
                .into_iter()
                // Tag each port with ldev_id
                .map(|mut point| {
                    point.add_tag(
                        "ldev_id",
                        TsValue::String(convert_to_base16(self.ldev_id.clone())),
                    );
                    point
                })
                .collect();
            points.extend(port_points);
        }
        p.add_tag("attributes", TsValue::StringVec(self.attributes.clone()));
        p.add_tag("status", TsValue::String(self.status.clone()));
        p.add_field("mp_blade_id", TsValue::Long(self.mp_blade_id));
        p.add_tag("ssid", TsValue::String(self.ssid.clone()));
        p.add_field("pool_id", TsValue::Long(self.pool_id));
        p.add_field(
            "num_of_used_block",
            TsValue::Long((self.num_of_used_block * 512) / 1024u64.pow(3)),
        );
        p.add_field(
            "is_relocation_enabled",
            TsValue::Boolean(self.is_relocation_enabled),
        );
        p.add_tag("tier_level", TsValue::String(self.tier_level.clone()));
        p.add_field(
            "used_capacity_per_tier_level1",
            TsValue::Long(self.used_capacity_per_tier_level1),
        );
        p.add_field(
            "used_capacity_per_tier_level2",
            TsValue::Long(self.used_capacity_per_tier_level2),
        );
        if let Some(tier_level3) = self.used_capacity_per_tier_level3 {
            p.add_field("used_capacity_per_tier_level3", TsValue::Long(tier_level3));
        }
        p.add_tag(
            "tier_level_for_new_page_allocation",
            TsValue::String(self.tier_level_for_new_page_allocation.clone()),
        );
        p.add_field("resource_group_id", TsValue::Long(self.resource_group_id));
        p.add_tag(
            "data_reduction_status",
            TsValue::String(self.data_reduction_status.clone()),
        );
        p.add_tag(
            "data_reduction_mode",
            TsValue::String(self.data_reduction_mode.clone()),
        );
        p.add_field("is_alua_enabled", TsValue::Boolean(self.is_alua_enabled));

        points.push(p);

        points
    }
}

#[derive(Deserialize, Debug)]
pub struct Version {
    pub productName: String,
    pub productVersion: String,
    pub apiVersion: String,
    pub description: String,
}

/// Convert a comma separated value vec of ByteRecords into timescaledb Value's
/// The headers field is used to figure out which type to convert into
fn into_values(
    records: &csv::ByteRecord,
    types: &csv::ByteRecord,
    headers: &csv::StringRecord,
) -> Vec<(String, TsValue)> {
    let mut ret_vals: Vec<(String, TsValue)> = Vec::new();
    for (pos, val) in types.iter().enumerate() {
        let v = String::from_utf8_lossy(val);
        let record = match records.get(pos) {
            Some(r) => r,
            None => {
                error!(
                    "Unable to get csv record at position {} from {:?}. Skipping",
                    pos, records
                );
                continue;
            }
        };
        if record.is_empty() {
            //warn!("Skipping column {} because the value is blank.", v);
            continue;
        }
        let header = match headers.get(pos) {
            Some(r) => r,
            None => {
                error!(
                    "Unable to get csv header at position {} from {:?}. Skipping",
                    pos, records
                );
                continue;
            }
        };
        // Need to convert this record into a String first before we can convert it into a value
        let r = String::from_utf8_lossy(record);
        // Using verbose matching here to log errors so we're aware of parsing problems. Otherwise
        // I'd use an if let
        // Added checking for value "short" in parsing the csv to convert
        if v.contains("string") {
            ret_vals.push((header.into(), TsValue::String(r.into_owned())));
        } else if v.contains("double") {
            match f64::from_str(&r) {
                Ok(f) => {
                    ret_vals.push((header.into(), TsValue::Float(f)));
                }
                Err(_) => {
                    error!("unable to convert {} to f64. Skipping", r);
                }
            }
        } else if v.contains("float") {
            match f64::from_str(&r) {
                Ok(f) => {
                    ret_vals.push((header.into(), TsValue::Float(f)));
                }
                Err(_) => {
                    error!("unable to convert {} to f64. Skipping", r);
                }
            }
        } else if v.contains("time_t") {
            ret_vals.push((header.into(), TsValue::String(r.into_owned())));
        } else if v.contains("ulong") {
            match u64::from_str(&r) {
                Ok(f) => {
                    ret_vals.push((header.into(), TsValue::Long(f)));
                }
                Err(_) => {
                    error!("unable to convert {} to u64. Skipping", r);
                }
            };
        } else if v.contains("long") {
            match i64::from_str(&r) {
                Ok(f) => {
                    ret_vals.push((header.into(), TsValue::SignedLong(f)));
                }
                Err(_) => {
                    error!("unable to convert {} to i64. Skipping", r);
                }
            };
        } else if v.contains("short") {
            // Short is i16 but we're going to upsize it here to i32
            // since TsValue doesn't have an i16 variant
            match i32::from_str(&r) {
                Ok(f) => {
                    ret_vals.push((header.into(), TsValue::Integer(f)));
                }
                Err(_) => {
                    error!("unable to convert {} to i32. Skipping", r);
                }
            };
        } else if v.contains("unsigned char") {
            match u8::from_str(&r) {
                Ok(f) => {
                    ret_vals.push((header.into(), TsValue::Byte(f)));
                }
                Err(_) => {
                    error!("unable to convert {} to u8. Skipping", r);
                }
            };
        } else {
            warn!("Unknown type: {}, value: {}. Skipping", v, r);
            continue;
        }
    }

    ret_vals
}

#[test]
fn test_get_storage() {
    let json = include_str!("../tests/hitachi/config_manager.json");
    let s: ServerResult<ConfigManagerStorage> = serde_json::from_str(json).unwrap();
    println!("Result: {:?}", s);
}

#[test]
fn test_get_ldev() {
    let json = include_str!("../tests/hitachi/storage_ldev.json");
    let storage_id = "2038467351";
    let s: ServerResult<StorageLdev> = serde_json::from_str(json).unwrap();
    println!("Result: {:?}", s);
    let points: Vec<TsPoint> = s
        .data
        .iter()
        // Flatten all the Vec<TsPoint>'s
        .flat_map(|s| s.into_point(Some("hitachi_ldev"), false))
        .into_iter()
        // Tag each with storage_id
        .map(|mut point| {
            point.add_tag("storage_id", TsValue::String(storage_id.to_string()));
            point
        })
        .collect();
    println!("Result: {:#?}", points);
}

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

    let mut buff = String::new();
    let mut f = File::open("tests/hitachi/raid_pd_plc.csv").unwrap();
    f.read_to_string(&mut buff).unwrap();
    println!("buff: {}", buff);
    let result = csv_to_points(&buff, "test", None).unwrap();
    println!("Result: {:?}", result);
}

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

    let mut buff = String::new();
    let mut f = File::open("tests/hitachi/raid_pi_lda.csv").unwrap();
    f.read_to_string(&mut buff).unwrap();
    let result = csv_to_points(&buff, "test", None).unwrap();
    println!("Result: {:?}", result);
}

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

    let mut buff = String::new();
    let mut f = File::open("tests/hitachi/raid_pi_lds.csv").unwrap();
    f.read_to_string(&mut buff).unwrap();
    let result = csv_to_points(&buff, "test", None).unwrap();
    println!("Result: {:?}", result);
}

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

    let mut buff = String::new();
    let mut f = File::open("tests/hitachi/raid_pi.csv").unwrap();
    f.read_to_string(&mut buff).unwrap();
    let result = csv_to_points(&buff, "test", None).unwrap();
    println!("Result: {:?}", result);
}

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

    let mut buff = String::new();
    let mut f = File::open("tests/hitachi/raid_pi_prcs.csv").unwrap();
    f.read_to_string(&mut buff).unwrap();
    let result = csv_to_points(&buff, "test", None).unwrap();
    println!("Result: {:?}", result);
}

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

    let mut buff = String::new();
    let mut f = File::open("tests/hitachi/raid_pi_pts.csv").unwrap();
    f.read_to_string(&mut buff).unwrap();
    let result = csv_to_points(&buff, "test", None).unwrap();
    println!("Result: {:?}", result);
}

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

    let mut buff = String::new();
    let mut f = File::open("tests/hitachi/raid_pd_plts.csv").unwrap();
    f.read_to_string(&mut buff).unwrap();
    let result = csv_to_points(&buff, "test", None).unwrap();
    println!("Result: {:?}", result);
}

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

    let mut buff = String::new();
    let mut f = File::open("tests/hitachi/raid_pd_plc.csv").unwrap();
    f.read_to_string(&mut buff).unwrap();
    let result = csv_to_points(&buff, "test", None).unwrap();
    println!("Result: {:?}", result);
}

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

    let mut buff = String::new();
    let mut f = File::open("tests/hitachi/raid_pi_chs.csv").unwrap();
    f.read_to_string(&mut buff).unwrap();
    let result = csv_to_points(&buff, "test", None).unwrap();
    println!("Result: {:?}", result);
}

// This is the for the HDS HNAS since it is accessed in the same way as the HDS block arrays, different instancename
#[test]
fn test_nas_pd_hplc() {
    use std::fs::File;
    use std::io::Read;

    let mut buff = String::new();
    let mut f = File::open("tests/hitachi/nas_pd_hplc.csv").unwrap();
    f.read_to_string(&mut buff).unwrap();
    let result = csv_to_points(&buff, "test", None).unwrap();
    println!("Result: {:?}", result);
}

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

    let mut buff = String::new();
    let mut f = File::open("tests/hitachi/nas_pd_hsmu.csv").unwrap();
    f.read_to_string(&mut buff).unwrap();
    let result = csv_to_points(&buff, "test", None).unwrap();
    println!("Result: {:?}", result);
}

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

    let mut buff = String::new();
    let mut f = File::open("tests/hitachi/nas_pd_hnc.csv").unwrap();
    f.read_to_string(&mut buff).unwrap();
    let result = csv_to_points(&buff, "test", None).unwrap();
    println!("Result: {:?}", result);
}

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

    let mut buff = String::new();
    let mut f = File::open("tests/hitachi/nas_pd_hfsc.csv").unwrap();
    f.read_to_string(&mut buff).unwrap();
    let result = csv_to_points(&buff, "test", None).unwrap();
    println!("Result: {:?}", result);
}

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

    let mut buff = String::new();
    let mut f = File::open("tests/hitachi/nas_pi_hns.csv").unwrap();
    f.read_to_string(&mut buff).unwrap();
    let result = csv_to_points(&buff, "test", None).unwrap();
    println!("Result: {:?}", result);
}

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

    let mut buff = String::new();
    let mut f = File::open("tests/hitachi/nas_pi_hnhs.csv").unwrap();
    f.read_to_string(&mut buff).unwrap();
    let result = csv_to_points(&buff, "test", None).unwrap();
    println!("Result: {:?}", result);
}

#[derive(Clone, Deserialize, Debug)]
pub struct HitachiConfig {
    /// The hitachi endpoint to use
    pub endpoint: String,
    pub user: String,
    pub password: String,
    /// The region this cluster is located in
    pub region: String,
}
#[test]
fn test_convert_base() {
    let res = convert_to_base16(139);
    assert_eq!(res, "8B");
}

// Algorithm from: http://codeofthedamned.com/index.php/number-base-conversion
fn convert_to_base16(num: u64) -> String {
    let symbols: [char; 36] = [
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
        'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
    ];
    let mut remainder: [u64; 32] = [0; 32];
    let mut quotient: u64 = num;
    let mut place: u8 = 0;
    let mut output = String::new();

    while 0 != quotient {
        let value: u64 = quotient;
        remainder[place as usize] = value % 16;
        quotient = (value - remainder[place as usize]) / 16;
        place += 1;
    }
    for i in 1..=place {
        output.push(symbols[remainder[(place - i) as usize] as usize]);
    }
    output
}

impl Hitachi {
    /// This request obtains the detailed version of the API
    pub fn get_version(&self) -> MetricsResult<Version> {
        let version: Version = self
            .client
            .get(&format!(
                "http://@{endpoint}/TuningManager/v1/configuration/Version",
                endpoint = self.config.endpoint
            ))
            .basic_auth(&self.config.user, Some(&self.config.password))
            .header(ACCEPT, "application/json")
            .send()?
            .error_for_status()?
            .json()?;
        Ok(version)
    }

    pub fn get_agent_for_raid(&self) -> MetricsResult<Collection> {
        let agents: Collection = self
            .client
            .get(&format!(
                "http://{}/TuningManager/v1/objects/AgentForRAID",
                self.config.endpoint
            ))
            .basic_auth(&self.config.user, Some(&self.config.password))
            .header(ACCEPT, "application/json")
            .send()?
            .error_for_status()?
            .json()?;

        Ok(agents)
    }

    // HDS NAS have a specific search criteria for the instance_name than what AgentFroRaid is. Alternate is to use agentType=ALL and will see everything
    pub fn get_agent_for_nas(&self) -> MetricsResult<Collection> {
        let agentnas: Collection = self
            .client
            .get(&format!(
                "http://{}/TuningManager/v1/objects/Agents?agentType=NAS",
                self.config.endpoint
            ))
            .basic_auth(&self.config.user, Some(&self.config.password))
            .header(ACCEPT, "application/json")
            .send()?
            .error_for_status()?
            .json()?;

        Ok(agentnas)
    }

    fn get_server_response(
        &self,
        hostname: &str,
        agent_instance_name: &str,
        api_call: &str,
    ) -> MetricsResult<String> {
        let content = self
            .client
            .get(&format!(
                "http://{}/TuningManager/v1/objects/{}?hostName={}&agentInstanceName={}",
                self.config.endpoint, api_call, hostname, agent_instance_name,
            ))
            .basic_auth(&self.config.user, Some(&self.config.password))
            .send()?
            .error_for_status()?
            .text()?;
        trace!("server response: {}", content);
        Ok(content)
    }

    /// Note this only works with ConfigurationManager
    pub fn get_storage(&self) -> MetricsResult<ServerResult<ConfigManagerStorage>> {
        let endpoint = format!(
            "http://{}/ConfigurationManager/v1/objects/storages",
            self.config.endpoint
        );
        let s: ServerResult<ConfigManagerStorage> = super::get(
            &self.client,
            &endpoint,
            &self.config.user,
            Some(&self.config.password),
        )?;
        Ok(s)
    }

    /// Note this only works with ConfigurationManager
    pub fn get_ldev(&self, storage_id: &str) -> MetricsResult<Vec<TsPoint>> {
        let endpoint = format!(
            "http://{}/ConfigurationManager/v1/objects/storages/{}/ldevs?ldevOption=dpVolume",
            self.config.endpoint, storage_id
        );
        let s: ServerResult<StorageLdev> = super::get(
            &self.client,
            &endpoint,
            &self.config.user,
            Some(&self.config.password),
        )?;
        let points = s
            .data
            .iter()
            // Flatten all the Vec<TsPoint>'s
            .flat_map(|s| s.into_point(Some("hitachi_ldev"), false))
            .into_iter()
            // Tag each with storage_device_id
            .map(|mut point| {
                point.add_tag("storage_device_id", TsValue::String(storage_id.to_string()));
                point
            })
            .collect();

        Ok(points)
    }
}

pub fn csv_to_points(
    text: &str,
    point_name: &str,
    t: Option<DateTime<Utc>>,
) -> MetricsResult<Vec<TsPoint>> {
    let mut points: Vec<TsPoint> = Vec::new();
    let mut rdr = Reader::from_reader(text.as_bytes());
    let headers = {
        let headers = rdr.headers()?;
        headers.clone()
    };
    let mut iter = rdr.byte_records();
    let fields = iter.next();
    if fields.is_none() {
        // We cannot continue without the fields
        error!(
            "Unable to discover csv fields.  Cannot parse record: {}",
            text
        );
        return Err(StorageError::new("CSV Parsing failure".into()));
    }
    let fields = fields.unwrap()?;

    for result in iter {
        let record = result?;
        let values = into_values(&record, &fields, &headers);
        let mut p = TsPoint::new(point_name, true);
        p.timestamp = t;
        for (name, value) in values {
            match value {
                TsValue::String(_) => {
                    p.add_tag(name, value);
                }
                _ => {
                    p.add_field(name, value);
                }
            };
        }
        points.push(p);
    }

    Ok(points)
}

impl Hitachi {
    pub fn get_raid_pi_prcs(
        &self,
        hostname: &str,
        agent_instance_name: &str,
        t: DateTime<Utc>,
    ) -> MetricsResult<Vec<TsPoint>> {
        let result = self.get_server_response(hostname, agent_instance_name, "RAID_PI_PRCS")?;
        let points = csv_to_points(&result, "raid_pi_prcs", Some(t))?;
        Ok(points)
    }

    pub fn get_raid_pi_lda(
        &self,
        hostname: &str,
        agent_instance_name: &str,
        t: DateTime<Utc>,
    ) -> MetricsResult<Vec<TsPoint>> {
        let result = self.get_server_response(hostname, agent_instance_name, "RAID_PI_LDA")?;
        let points = csv_to_points(&result, "raid_pi_lda", Some(t))?;
        Ok(points)
    }

    pub fn get_raid_pi(
        &self,
        hostname: &str,
        agent_instance_name: &str,
        t: DateTime<Utc>,
    ) -> MetricsResult<Vec<TsPoint>> {
        let result = self.get_server_response(hostname, agent_instance_name, "RAID_PI")?;
        let points = csv_to_points(&result, "raid_pi", Some(t))?;
        Ok(points)
    }

    pub fn get_raid_pd_plc(
        &self,
        hostname: &str,
        agent_instance_name: &str,
        t: DateTime<Utc>,
    ) -> MetricsResult<Vec<TsPoint>> {
        let result = self.get_server_response(hostname, agent_instance_name, "RAID_PD_PLC")?;
        let points = csv_to_points(&result, "raid_pd_plc", Some(t))?;
        Ok(points)
    }

    pub fn get_raid_pi_chs(
        &self,
        hostname: &str,
        agent_instance_name: &str,
        t: DateTime<Utc>,
    ) -> MetricsResult<Vec<TsPoint>> {
        let result = self.get_server_response(hostname, agent_instance_name, "RAID_PI_CHS")?;
        let points = csv_to_points(&result, "raid_pi_chs", Some(t))?;
        Ok(points)
    }

    pub fn get_raid_pd_plts(
        &self,
        hostname: &str,
        agent_instance_name: &str,
        t: DateTime<Utc>,
    ) -> MetricsResult<Vec<TsPoint>> {
        let result = self.get_server_response(hostname, agent_instance_name, "RAID_PD_PLTS")?;
        let points = csv_to_points(&result, "raid_pd_plts", Some(t))?;
        Ok(points)
    }

    pub fn get_raid_pi_pts(
        &self,
        hostname: &str,
        agent_instance_name: &str,
        t: DateTime<Utc>,
    ) -> MetricsResult<Vec<TsPoint>> {
        let result = self.get_server_response(hostname, agent_instance_name, "RAID_PI_PTS")?;
        let points = csv_to_points(&result, "raid_pi_pts", Some(t))?;
        Ok(points)
    }

    pub fn get_nas_pd_hplc(
        &self,
        hostname: &str,
        agent_instance_name: &str,
        t: DateTime<Utc>,
    ) -> MetricsResult<Vec<TsPoint>> {
        let result = self.get_server_response(hostname, agent_instance_name, "NAS_PD_HPLC")?;
        let points = csv_to_points(&result, "nas_pd_hplc", Some(t))?;
        Ok(points)
    }

    pub fn get_nas_pd_hsmu(
        &self,
        hostname: &str,
        agent_instance_name: &str,
        t: DateTime<Utc>,
    ) -> MetricsResult<Vec<TsPoint>> {
        let result = self.get_server_response(hostname, agent_instance_name, "NAS_PD_HSMU")?;
        let points = csv_to_points(&result, "nas_pd_hsmu", Some(t))?;
        Ok(points)
    }

    pub fn get_nas_pd_hnc(
        &self,
        hostname: &str,
        agent_instance_name: &str,
        t: DateTime<Utc>,
    ) -> MetricsResult<Vec<TsPoint>> {
        let result = self.get_server_response(hostname, agent_instance_name, "NAS_PD_HNC")?;
        let points = csv_to_points(&result, "nas_pd_hnc", Some(t))?;
        Ok(points)
    }

    pub fn get_nas_pd_hfsc(
        &self,
        hostname: &str,
        agent_instance_name: &str,
        t: DateTime<Utc>,
    ) -> MetricsResult<Vec<TsPoint>> {
        let result = self.get_server_response(hostname, agent_instance_name, "NAS_PD_HFSC")?;
        let points = csv_to_points(&result, "nas_pd_hfsc", Some(t))?;
        Ok(points)
    }

    pub fn get_nas_pi_hns(
        &self,
        hostname: &str,
        agent_instance_name: &str,
        t: DateTime<Utc>,
    ) -> MetricsResult<Vec<TsPoint>> {
        let result = self.get_server_response(hostname, agent_instance_name, "NAS_PI_HNS")?;
        let points = csv_to_points(&result, "nas_pi_hns", Some(t))?;
        Ok(points)
    }

    pub fn get_nas_pi_hnhs(
        &self,
        hostname: &str,
        agent_instance_name: &str,
        t: DateTime<Utc>,
    ) -> MetricsResult<Vec<TsPoint>> {
        let result = self.get_server_response(hostname, agent_instance_name, "NAS_PI_HNHS")?;
        let points = csv_to_points(&result, "nas_pi_hnhs", Some(t))?;
        Ok(points)
    }
}