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
// Copyright (C) 2017-2018 Red Hat, Inc.
//
// Permission is hereby granted, free of charge, to any
// person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the
// Software without restriction, including without
// limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software
// is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice
// shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Author: Gris Ge <fge@redhat.com>

use serde_json;
use serde_json::{Map, Value};
use std::fs::read_dir;
use std::thread::sleep;
use std::time::Duration;
use url;

use super::data::*;
use super::error::*;
use super::ipc::{uds_path, TransPort};
use super::misc::verify_init_id_str;

const DEFAULT_TIMEOUT: u32 = 30_000;
const JOB_RETRY_INTERVAL: u64 = 1;

/// Represent the connection to plugin.
pub struct Client {
    tp: TransPort,
    plugin_name: String,
}

#[derive(Deserialize, Debug)]
struct Job {
    status: u32,
    percent: u8,
    data: Option<Value>,
}

const JOB_STATUS_INPROGRESS: u32 = 1;
const JOB_STATUS_COMPLETE: u32 = 2;
const JOB_STATUS_ERROR: u32 = 3;
const VOLUME_THINP_YES: u32 = 1;
const VOLUME_THINP_NO: u32 = 2;
const VOLUME_THINP_DEFAULT: u32 = 3;
const POOL_MEMBER_TYPE_DISK: u32 = 2;
const POOL_MEMBER_TYPE_POOL: u32 = 3;

const WRITE_CACHE_POLICY_WRITE_BACK: u8 = 2;
const WRITE_CACHE_POLICY_AUTO: u8 = 3;
const WRITE_CACHE_POLICY_WRITE_THROUGH: u8 = 4;

const WRITE_CACHE_STATUS_WRITE_BACK: u8 = 2;
const WRITE_CACHE_STATUS_WRITE_THROUGH: u8 = 3;

const READ_CACHE_POLICY_ENABLED: u8 = 2;
const READ_CACHE_POLICY_DISABLED: u8 = 3;

const READ_CACHE_STATUS_ENABLED: u8 = 2;
const READ_CACHE_STATUS_DISABLED: u8 = 3;

const PHYSICAL_DISK_CACHE_ENABLED: u8 = 2;
const PHYSICAL_DISK_CACHE_DISABLED: u8 = 3;
const PHYSICAL_DISK_CACHE_USE_DISK_SETTING: u8 = 4;

trait OkOrPlugBug<T> {
    fn ok_or_plugin_bug(self, val: &Value) -> Result<T>;
}

impl<T> OkOrPlugBug<T> for Option<T> {
    fn ok_or_plugin_bug(self, val: &Value) -> Result<T> {
        match self {
            Some(i) => Ok(i),
            None => Err(LsmError::PluginBug(format!(
                "Plugin return unexpected data: {:?}",
                val
            ))),
        }
    }
}

/// Represent a plugin information
#[derive(Debug)]
pub struct PluginInfo {
    /// Plugin version string.
    pub version: String,
    /// Plugin description.
    pub description: String,
    /// Plugin name.
    pub name: String,
}

/// Query all available plugins from libStorageMgmt daemon (lsmd).
///
/// # Errors
///
///  * [`LsmError::DaemonNotRunning`][1]
///
/// [1]: enum.LsmError.html#variant.DaemonNotRunning
pub fn available_plugins() -> Result<Vec<PluginInfo>> {
    let mut ret = Vec::new();
    let uds_path = uds_path();
    match read_dir(&uds_path) {
        Err(_) => {
            return Err(LsmError::DaemonNotRunning(format!(
                "LibStorageMgmt daemon is not running for \
                 socket folder: '{}'",
                uds_path
            )))
        }
        Ok(paths) => {
            for path in paths {
                match path {
                    // Got error when iterate, it might happen when
                    // daemon is starting.
                    //
                    Err(_) => continue,
                    Ok(dir_entry) => {
                        let plugin_name = match dir_entry.file_name().into_string() {
                            Ok(i) => i,
                            Err(_) => continue,
                        };
                        let plugin_ipc_path = get_plugin_ipc_path(&plugin_name);
                        // We cannot use self.plugin_info() here, as we need
                        // to bypass the plugin_register() and
                        // plugin_unregister()
                        //
                        let mut tp = TransPort::new(&plugin_ipc_path)?;
                        let val = tp.invoke("plugin_info", None)?;
                        let data: Vec<String> = serde_json::from_value(val.clone())?;
                        let desc = data.get(0).ok_or_plugin_bug(&val)?;
                        let version = data.get(1).ok_or_plugin_bug(&val)?;
                        ret.push(PluginInfo {
                            version: version.to_string(),
                            description: desc.to_string(),
                            name: plugin_name,
                        });
                    }
                };
            }
        }
    };

    Ok(ret)
}

fn get_plugin_ipc_path(plugin_name: &str) -> String {
    format!("{}/{}", uds_path(), plugin_name)
}

impl Client {
    /// Create a connection to plugin.
    /// Please refer to [libstoragemgmt user guide][1] for how to choose the
    /// URI and password.
    ///
    /// The `timeout` argument is in milliseconds.
    ///
    /// [1]: https://libstorage.github.io/libstoragemgmt-doc/doc/user_guide.html
    pub fn new(uri: &str, password: Option<&str>, timeout: Option<u32>) -> Result<Client> {
        let p = match url::Url::parse(uri) {
            Ok(p) => p,
            Err(e) => {
                return Err(LsmError::InvalidArgument(format!(
                    "Failed to parse URI: {}",
                    e
                )))
            }
        };
        let plugin_name = p.scheme().to_string();
        let plugin_ipc_path = get_plugin_ipc_path(&plugin_name);
        let mut tp = TransPort::new(&plugin_ipc_path)?;
        let mut args = Map::new();
        let timeout = timeout.unwrap_or(DEFAULT_TIMEOUT);
        args.insert("password".to_string(), serde_json::to_value(password)?);
        args.insert("uri".to_string(), serde_json::to_value(uri)?);
        args.insert("timeout".to_string(), serde_json::to_value(timeout)?);
        tp.invoke("plugin_register", Some(args))?;

        Ok(Client { tp, plugin_name })
    }

    /// Gets a list of systems on this connection.
    pub fn systems(&mut self) -> Result<Vec<System>> {
        Ok(serde_json::from_value(self.tp.invoke("systems", None)?)?)
    }

    /// Gets a list of volumes on this connection.
    pub fn volumes(&mut self) -> Result<Vec<Volume>> {
        Ok(serde_json::from_value(self.tp.invoke("volumes", None)?)?)
    }

    /// Gets a list of pools on this connection.
    pub fn pools(&mut self) -> Result<Vec<Pool>> {
        Ok(serde_json::from_value(self.tp.invoke("pools", None)?)?)
    }

    /// Gets a list of disks on this connection.
    pub fn disks(&mut self) -> Result<Vec<Disk>> {
        Ok(serde_json::from_value(self.tp.invoke("disks", None)?)?)
    }

    /// Gets a list of file systems on this connection.
    pub fn fs(&mut self) -> Result<Vec<FileSystem>> {
        Ok(serde_json::from_value(self.tp.invoke("fs", None)?)?)
    }

    /// Gets a list of NFS exports on this connection.
    pub fn nfs_exports(&mut self) -> Result<Vec<NfsExport>> {
        Ok(serde_json::from_value(self.tp.invoke("exports", None)?)?)
    }

    /// Gets a list of access group on this connection.
    pub fn access_groups(&mut self) -> Result<Vec<AccessGroup>> {
        Ok(serde_json::from_value(
            self.tp.invoke("access_groups", None)?,
        )?)
    }

    /// Gets a list of target ports on this connection.
    pub fn target_ports(&mut self) -> Result<Vec<TargetPort>> {
        Ok(serde_json::from_value(
            self.tp.invoke("target_ports", None)?,
        )?)
    }

    /// Gets a list of batteries on this connection.
    pub fn batteries(&mut self) -> Result<Vec<Battery>> {
        Ok(serde_json::from_value(self.tp.invoke("batteries", None)?)?)
    }

    fn _job_free(&mut self, job_id: &str) -> Result<()> {
        let mut args = Map::new();
        args.insert("job_id".to_string(), serde_json::to_value(job_id)?);
        self.tp.invoke("job_free", Some(args))?;
        Ok(())
    }

    fn _wait_job(&mut self, job_id: &str) -> Result<Value> {
        loop {
            let mut args = Map::new();
            args.insert("job_id".to_string(), serde_json::to_value(job_id)?);
            let j: Job = serde_json::from_value(self.tp.invoke("job_status", Some(args))?)?;

            match j.status {
                JOB_STATUS_INPROGRESS => {
                    sleep(Duration::new(JOB_RETRY_INTERVAL, 0));
                    continue;
                }
                JOB_STATUS_COMPLETE => match j.data {
                    Some(v) => {
                        self._job_free(job_id)?;
                        return Ok(v);
                    }
                    None => break,
                },
                JOB_STATUS_ERROR =>
                // The invoke command should already got error detail
                // and returned. If not, got buggy plugin.
                {
                    return Err(LsmError::PluginBug(
                        "Got no error detail for failed job".to_string(),
                    ))
                }
                _ => {
                    return Err(LsmError::PluginBug(format!(
                        "Got invalid job status {}",
                        j.status
                    )))
                }
            };
        }
        Ok(Value::Null)
    }

    fn wait_job_none(&mut self, job_id: &str) -> Result<()> {
        self._wait_job(job_id)?;
        Ok(())
    }

    fn wait_job_volume(&mut self, job_id: &str) -> Result<Volume> {
        match self._wait_job(job_id) {
            Ok(j) => {
                if j.is_null() {
                    Err(LsmError::PluginBug(
                        "Expecting a volume, but got None".to_string(),
                    ))
                } else {
                    let v: Volume = serde_json::from_value(j)?;
                    Ok(v)
                }
            }
            Err(e) => Err(e),
        }
    }

    fn wait_job_fs(&mut self, job_id: &str) -> Result<FileSystem> {
        match self._wait_job(job_id) {
            Ok(j) => {
                if j.is_null() {
                    Err(LsmError::PluginBug(
                        "Expecting a file system, but got None".to_string(),
                    ))
                } else {
                    let f: FileSystem = serde_json::from_value(j)?;
                    Ok(f)
                }
            }
            Err(e) => Err(e),
        }
    }

    fn wait_job_fs_snap(&mut self, job_id: &str) -> Result<FileSystemSnapShot> {
        match self._wait_job(job_id) {
            Ok(j) => {
                if j.is_null() {
                    Err(LsmError::PluginBug(
                        "Expecting a file system snapshot, but got None".to_string(),
                    ))
                } else {
                    let f: FileSystemSnapShot = serde_json::from_value(j)?;
                    Ok(f)
                }
            }
            Err(e) => Err(e),
        }
    }

    /// Create new volume.
    ///
    ///  * `pool` -- The pool where new volume should allocated from.
    ///  * `name` -- The name of new volume. It might be altered or
    ///    ignored.
    ///  * `size_bytes` -- Size in bytes of new volume. You may use function
    ///    [`size_human_2_size_bytes()`][1] to convert string like '1.1 GiB'
    ///    to integer size bytes.
    ///  * `thinp` -- Whether to create thin provisioning volume.
    ///    Check [VolumeCreateArgThinP][2]
    ///
    /// [1]: fn.size_human_2_size_bytes.html
    /// [2]: enum.VolumeCreateArgThinP.html
    pub fn volume_create(
        &mut self,
        pool: &Pool,
        name: &str,
        size_bytes: u64,
        thinp: &VolumeCreateArgThinP,
    ) -> Result<Volume> {
        let mut args = Map::new();
        let thinp_val = match *thinp {
            VolumeCreateArgThinP::Full => serde_json::to_value(VOLUME_THINP_YES)?,
            VolumeCreateArgThinP::Thin => serde_json::to_value(VOLUME_THINP_NO)?,
            VolumeCreateArgThinP::Default => serde_json::to_value(VOLUME_THINP_DEFAULT)?,
        };
        args.insert("provisioning".to_string(), thinp_val);
        args.insert("size_bytes".to_string(), serde_json::to_value(size_bytes)?);
        args.insert("volume_name".to_string(), serde_json::to_value(name)?);
        args.insert("pool".to_string(), serde_json::to_value(pool)?);

        let ret = self.tp.invoke("volume_create", Some(args))?;
        self.get_vol_from_async(&ret)
    }

    /// Delete a volume
    ///
    ///
    /// # Errors
    ///
    ///  * [`LsmError::VolHasChildDep`][1] volume has child dependency. e.g.
    ///    specified volume is a replication source. Please use
    ///    [`Client::vol_child_dep_rm()`] to eliminate child dependency.
    ///
    /// [1]: enum.LsmError.html#variant.VolHasChildDep
    pub fn volume_delete(&mut self, vol: &Volume) -> Result<()> {
        let mut args = Map::new();
        args.insert("volume".to_string(), serde_json::to_value(vol)?);
        let ret = self.tp.invoke("volume_delete", Some(args))?;
        self.wait_if_async(&ret)
    }

    /// Set connection timeout value in milliseconds.
    pub fn time_out_set(&mut self, ms: u32) -> Result<()> {
        let mut args = Map::new();
        args.insert("ms".to_string(), serde_json::to_value(ms)?);
        self.tp.invoke("time_out_set", Some(args))?;
        Ok(())
    }

    /// Get connection timeout value.
    pub fn time_out_get(&mut self) -> Result<u32> {
        Ok(serde_json::from_value(
            self.tp.invoke("time_out_get", None)?,
        )?)
    }

    /// Get system's capabilities.
    ///
    /// Capability is used to indicate whether certain functionality is
    /// supported by specified storage system. Please check desired function
    /// for required capability. To verify capability is supported, use
    /// [`Capabilities::is_supported()`][1]. If the functionality is not
    /// listed in the enumerated [`Capability`][2] type then that functionality
    /// is mandatory and required to exist.
    ///
    /// [1]: struct.Capabilities.html#method.is_supported
    /// [2]: enum.capability.html
    pub fn capabilities(&mut self, sys: &System) -> Result<Capabilities> {
        let mut args = Map::new();
        args.insert("system".to_string(), serde_json::to_value(sys)?);
        Ok(serde_json::from_value(
            self.tp.invoke("capabilities", Some(args))?,
        )?)
    }

    /// Get plugin information.
    pub fn plugin_info(&mut self) -> Result<PluginInfo> {
        let val = self.tp.invoke("plugin_info", None)?;
        let data: Vec<String> = serde_json::from_value(val.clone())?;
        let desc = data.get(0).ok_or_plugin_bug(&val)?;
        let version = data.get(1).ok_or_plugin_bug(&val)?;
        Ok(PluginInfo {
            version: version.to_string(),
            description: desc.to_string(),
            name: self.plugin_name.clone(),
        })
    }

    /// Changes the read cache percentage for the specified system.
    ///
    /// # Errors
    ///
    ///  * [`LsmError::InvalidArgument`][1]: `read_pct` is larger than 100.
    ///
    /// [1]: enum.LsmError.html#variant.InvalidArgument
    pub fn sys_read_cache_pct_set(&mut self, sys: &System, read_pct: u32) -> Result<()> {
        if read_pct > 100 {
            return Err(LsmError::InvalidArgument(
                "Invalid read_pct, should be in range 0 - 100".to_string(),
            ));
        }
        let mut args = Map::new();
        args.insert("system".to_string(), serde_json::to_value(sys)?);
        args.insert("read_pct".to_string(), serde_json::to_value(read_pct)?);
        Ok(serde_json::from_value(
            self.tp.invoke("system_read_cache_pct_update", Some(args))?,
        )?)
    }

    /// Set(override) iSCSI CHAP authentication.
    ///
    ///  * `init_id` -- Initiator ID.
    ///  * `in_user` -- The inbound authentication username. The inbound
    ///    authentication means the iSCSI initiator authenticates the iSCSI
    ///    target using CHAP.
    ///  * `in_pass` -- The inbound authentication password.
    ///  * `out_user` -- The outbound authentication username. The outbound
    ///    authentication means the iSCSI target authenticates the iSCSI
    ///    initiator using CHAP.
    ///  * `out_pass` -- The outbound authentication password.
    pub fn iscsi_chap_auth_set(
        &mut self,
        init_id: &str,
        in_user: Option<&str>,
        in_pass: Option<&str>,
        out_user: Option<&str>,
        out_pass: Option<&str>,
    ) -> Result<()> {
        let mut args = Map::new();
        args.insert("init_id".to_string(), serde_json::to_value(init_id)?);
        args.insert(
            "in_user".to_string(),
            serde_json::to_value(in_user.unwrap_or(&String::new()))?,
        );
        args.insert(
            "in_password".to_string(),
            serde_json::to_value(in_pass.unwrap_or(&String::new()))?,
        );
        args.insert(
            "out_user".to_string(),
            serde_json::to_value(out_user.unwrap_or(&String::new()))?,
        );
        args.insert(
            "out_password".to_string(),
            serde_json::to_value(out_pass.unwrap_or(&String::new()))?,
        );
        self.tp.invoke("iscsi_chap_auth", Some(args))?;
        Ok(())
    }

    /// Resize a volume.
    ///
    /// Please check whether pool allows volume resize via
    /// [`Pool.unsupported_actions`][1].
    ///
    /// [1]: struct.Pool.html#structfield.unsupported_actions
    pub fn volume_resize(&mut self, vol: &Volume, new_size_bytes: u64) -> Result<Volume> {
        let mut args = Map::new();
        args.insert("volume".to_string(), serde_json::to_value(vol)?);
        args.insert(
            "new_size_bytes".to_string(),
            serde_json::to_value(new_size_bytes)?,
        );
        let ret = self.tp.invoke("volume_resize", Some(args))?;
        self.get_vol_from_async(&ret)
    }

    fn wait_if_async(&mut self, ret: &Value) -> Result<()> {
        if ret.is_null() {
            return Ok(());
        }
        self.wait_job_none(ret.as_str().ok_or_plugin_bug(ret)?)
    }

    //TODO(Gris Ge): Merge get_fs_from_async() and get_vol_from_asyn().
    fn get_fs_from_async(&mut self, ret: &Value) -> Result<FileSystem> {
        let ret_array = ret.as_array().ok_or_plugin_bug(ret)?;
        if ret_array.len() != 2 {
            return Err(LsmError::PluginBug(format!(
                "Plugin return unexpected data: {:?}",
                ret
            )));
        }
        let job_id = ret_array.get(0).ok_or_plugin_bug(ret)?;
        if job_id.is_null() {
            Ok(serde_json::from_value(
                ret_array.get(1).ok_or_plugin_bug(ret)?.clone(),
            )?)
        } else {
            self.wait_job_fs(job_id.as_str().ok_or_plugin_bug(ret)?)
        }
    }

    fn get_vol_from_async(&mut self, ret: &Value) -> Result<Volume> {
        let ret_array = ret.as_array().ok_or_plugin_bug(ret)?;
        if ret_array.len() != 2 {
            return Err(LsmError::PluginBug(format!(
                "Plugin return unexpected data: {:?}",
                ret
            )));
        }
        let job_id = ret_array.get(0).ok_or_plugin_bug(ret)?;
        if job_id.is_null() {
            Ok(serde_json::from_value(
                ret_array.get(1).ok_or_plugin_bug(ret)?.clone(),
            )?)
        } else {
            self.wait_job_volume(job_id.as_str().ok_or_plugin_bug(ret)?)
        }
    }

    fn get_fs_snap_from_asyn(&mut self, ret: &Value) -> Result<FileSystemSnapShot> {
        let ret_array = ret.as_array().ok_or_plugin_bug(ret)?;
        if ret_array.len() != 2 {
            return Err(LsmError::PluginBug(format!(
                "Plugin return unexpected data: {:?}",
                ret
            )));
        }
        let job_id = ret_array.get(0).ok_or_plugin_bug(ret)?;
        if job_id.is_null() {
            Ok(serde_json::from_value(
                ret_array.get(1).ok_or_plugin_bug(ret)?.clone(),
            )?)
        } else {
            self.wait_job_fs_snap(job_id.as_str().ok_or_plugin_bug(ret)?)
        }
    }

    /// Replicate a volume.
    ///
    ///  * `pool` -- The pool where new replication target volume should be
    ///    allocated from. For `None`, will use the same pool of source volume.
    ///  * `rep_type` -- Replication type.
    ///  * `src_vol` -- Replication source volume.
    ///  * `name` -- Name for replication target volume. Might be altered or
    ///    ignored.
    pub fn volume_replicate(
        &mut self,
        pool: Option<Pool>,
        rep_type: VolumeReplicateType,
        src_vol: &Volume,
        name: &str,
    ) -> Result<Volume> {
        let mut args = Map::new();
        args.insert("pool".to_string(), serde_json::to_value(pool)?);
        args.insert("volume_src".to_string(), serde_json::to_value(src_vol)?);
        args.insert(
            "rep_type".to_string(),
            serde_json::to_value(rep_type as i32)?,
        );
        args.insert("name".to_string(), serde_json::to_value(name)?);
        let ret = self.tp.invoke("volume_replicate", Some(args))?;
        self.get_vol_from_async(&ret)
    }

    /// Block size for the [`Client::volume_replicate_range()`][1].
    ///
    /// [1]: #method.volume_replicate_range
    pub fn volume_rep_range_blk_size(&mut self, sys: &System) -> Result<i32> {
        let mut args = Map::new();
        args.insert("system".to_string(), serde_json::to_value(sys)?);
        Ok(serde_json::from_value(self.tp.invoke(
            "volume_replicate_range_block_size",
            Some(args),
        )?)?)
    }

    /// Replicates a portion of a volume to a volume.
    ///
    /// * `rep_type` -- Replication type.
    /// * `src_vol` -- Replication source volume.
    /// * `dst_vol` -- Replication target volume.
    /// * `ranges` -- Replication block ranges.
    pub fn volume_replicate_range(
        &mut self,
        rep_type: VolumeReplicateType,
        src_vol: &Volume,
        dst_vol: &Volume,
        ranges: &[BlockRange],
    ) -> Result<()> {
        let mut args = Map::new();
        args.insert(
            "rep_type".to_string(),
            serde_json::to_value(rep_type as i32)?,
        );
        args.insert("ranges".to_string(), serde_json::to_value(ranges)?);
        args.insert("volume_src".to_string(), serde_json::to_value(src_vol)?);
        args.insert("volume_dest".to_string(), serde_json::to_value(dst_vol)?);
        let ret = self.tp.invoke("volume_replicate_range", Some(args))?;
        self.wait_if_async(&ret)
    }

    /// Set a Volume to online.
    ///
    /// Enable the specified volume when that volume is disabled by
    /// administrator or via [`Client::volume_disable()`][1]
    ///
    /// [1]: #method.volume_disable
    pub fn volume_enable(&mut self, vol: &Volume) -> Result<()> {
        let mut args = Map::new();
        args.insert("volume".to_string(), serde_json::to_value(vol)?);
        self.tp.invoke("volume_enable", Some(args))?;
        Ok(())
    }

    /// Disable the read and write access to the specified volume.
    pub fn volume_disable(&mut self, vol: &Volume) -> Result<()> {
        let mut args = Map::new();
        args.insert("volume".to_string(), serde_json::to_value(vol)?);
        self.tp.invoke("volume_disable", Some(args))?;
        Ok(())
    }

    /// Grant access to a volume for the specified group, also known as LUN
    /// masking or mapping.
    ///
    /// # Errors
    ///
    ///  * [`LsmError::EmptyAccessGroup`][1]: Cannot mask volume to empty
    ///    access group.
    ///
    /// [1]: enum.LsmError.html#variant.EmptyAccessGroup
    pub fn volume_mask(&mut self, vol: &Volume, ag: &AccessGroup) -> Result<()> {
        let mut args = Map::new();
        args.insert("volume".to_string(), serde_json::to_value(vol)?);
        args.insert("access_group".to_string(), serde_json::to_value(ag)?);
        self.tp.invoke("volume_mask", Some(args))?;
        Ok(())
    }

    /// Revokes access to a volume for the specified group
    pub fn volume_unmask(&mut self, vol: &Volume, ag: &AccessGroup) -> Result<()> {
        let mut args = Map::new();
        args.insert("volume".to_string(), serde_json::to_value(vol)?);
        args.insert("access_group".to_string(), serde_json::to_value(ag)?);
        self.tp.invoke("volume_unmask", Some(args))?;
        Ok(())
    }

    /// Create a access group.
    ///
    /// Creates a new access group with one initiator in it. You may expand
    /// the access group by adding more initiators via
    /// [`Client::access_group_init_add()`][1]
    ///
    /// # Errors
    ///
    ///  * [`LsmError::ExistsInitiator`][2]: Specified initiator is used by
    ///    other access group.
    ///
    /// [1]: #method.access_group_init_add
    /// [2]: enum.LsmError.html#variant.ExistsInitiator
    pub fn access_group_create(
        &mut self,
        name: &str,
        init_id: &str,
        init_type: InitiatorType,
        sys: &System,
    ) -> Result<AccessGroup> {
        verify_init_id_str(init_id, init_type)?;
        let mut args = Map::new();
        args.insert("name".to_string(), serde_json::to_value(name)?);
        args.insert("init_id".to_string(), serde_json::to_value(init_id)?);
        args.insert(
            "init_type".to_string(),
            serde_json::to_value(init_type as i32)?,
        );
        args.insert("system".to_string(), serde_json::to_value(sys)?);
        Ok(serde_json::from_value(
            self.tp.invoke("access_group_create", Some(args))?,
        )?)
    }

    /// Delete an access group. Only access group with no volume masked can
    /// be deleted.
    ///
    /// # Errors
    ///
    ///  * [`LsmError::IsMasked`][1]: Access group has volume masked to.
    ///
    /// [1]: enum.LsmError.html#variant.IsMasked
    pub fn access_group_delete(&mut self, ag: &AccessGroup) -> Result<()> {
        let mut args = Map::new();
        args.insert("access_group".to_string(), serde_json::to_value(ag)?);
        self.tp.invoke("access_group_delete", Some(args))?;
        Ok(())
    }

    /// Add an initiator to the access group.
    ///
    /// # Errors
    ///
    ///  * [`LsmError::ExistsInitiator`][1]: Specified initiator is used by
    ///    other access group.
    ///
    /// [1]: enum.LsmError.html#variant.ExistsInitiator
    pub fn access_group_init_add(
        &mut self,
        ag: &AccessGroup,
        init_id: &str,
        init_type: InitiatorType,
    ) -> Result<AccessGroup> {
        verify_init_id_str(init_id, init_type)?;
        let mut args = Map::new();
        args.insert("access_group".to_string(), serde_json::to_value(ag)?);
        args.insert("init_id".to_string(), serde_json::to_value(init_id)?);
        args.insert(
            "init_type".to_string(),
            serde_json::to_value(init_type as i32)?,
        );
        Ok(serde_json::from_value(
            self.tp.invoke("access_group_initiator_add", Some(args))?,
        )?)
    }

    /// Delete an initiator from an access group.
    ///
    /// # Errors
    ///
    ///  * [`LsmError::LastInitInAccessGroup`][1]: Specified initiator is the
    ///  last initiator of access group. Use
    ///  [`Client::access_group_delete()`][2] instead.
    ///
    /// [1]: enum.LsmError.html#variant.LastInitInAccessGroup
    /// [2]: #method.access_group_delete
    pub fn access_group_init_del(
        &mut self,
        ag: &AccessGroup,
        init_id: &str,
        init_type: InitiatorType,
    ) -> Result<AccessGroup> {
        verify_init_id_str(init_id, init_type)?;
        let mut args = Map::new();
        args.insert("access_group".to_string(), serde_json::to_value(ag)?);
        args.insert("init_id".to_string(), serde_json::to_value(init_id)?);
        args.insert(
            "init_type".to_string(),
            serde_json::to_value(init_type as i32)?,
        );
        Ok(serde_json::from_value(
            self.tp
                .invoke("access_group_initiator_delete", Some(args))?,
        )?)
    }

    /// Query volumes that the specified access group has access to.
    pub fn vols_masked_to_ag(&mut self, ag: &AccessGroup) -> Result<Vec<Volume>> {
        let mut args = Map::new();
        args.insert("access_group".to_string(), serde_json::to_value(ag)?);
        Ok(serde_json::from_value(self.tp.invoke(
            "volumes_accessible_by_access_group",
            Some(args),
        )?)?)
    }

    /// Retrieves the access groups that have access to the specified volume.
    pub fn ags_granted_to_vol(&mut self, vol: &Volume) -> Result<Vec<AccessGroup>> {
        let mut args = Map::new();
        args.insert("volume".to_string(), serde_json::to_value(vol)?);
        Ok(serde_json::from_value(
            self.tp
                .invoke("access_groups_granted_to_volume", Some(args))?,
        )?)
    }

    /// Check whether volume has child dependencies.
    pub fn vol_has_child_dep(&mut self, vol: &Volume) -> Result<bool> {
        let mut args = Map::new();
        args.insert("volume".to_string(), serde_json::to_value(vol)?);
        Ok(serde_json::from_value(
            self.tp.invoke("volume_child_dependency", Some(args))?,
        )?)
    }

    /// Delete all child dependencies of the specified volume.
    ///
    /// Instruct storage system to remove all child dependencies of the
    /// specified volume by duplicating the required storage before breaking
    /// replication relationship. This function might take a long time(days or
    /// even weeks), you might want to invoke it in a thread.
    pub fn vol_child_dep_rm(&mut self, vol: &Volume) -> Result<()> {
        let mut args = Map::new();
        args.insert("volume".to_string(), serde_json::to_value(vol)?);
        let ret = self.tp.invoke("volume_child_dependency_rm", Some(args))?;
        self.wait_if_async(&ret)
    }

    /// Create a new file system.
    ///
    ///  * `pool` -- The pool where new file system should allocated from.
    ///  * `name` -- The name of new file system. It might be altered or
    ///    ignored.
    ///  * `size_bytes` -- Size in bytes of new file system. You may use
    ///    function [`size_human_2_size_bytes()`][1] to convert string like
    ///    '1.1 GiB' to integer size bytes.
    ///
    /// [1]: fn.size_human_2_size_bytes.html
    pub fn fs_create(&mut self, pool: &Pool, name: &str, size_bytes: u64) -> Result<FileSystem> {
        let mut args = Map::new();
        args.insert("size_bytes".to_string(), serde_json::to_value(size_bytes)?);
        args.insert("name".to_string(), serde_json::to_value(name)?);
        args.insert("pool".to_string(), serde_json::to_value(pool)?);

        let ret = self.tp.invoke("fs_create", Some(args))?;
        self.get_fs_from_async(&ret)
    }

    /// Resize of file system.
    pub fn fs_resize(&mut self, fs: &FileSystem, new_size_bytes: u64) -> Result<FileSystem> {
        let mut args = Map::new();
        args.insert("fs".to_string(), serde_json::to_value(fs)?);
        args.insert(
            "new_size_bytes".to_string(),
            serde_json::to_value(new_size_bytes)?,
        );
        let ret = self.tp.invoke("fs_resize", Some(args))?;
        self.get_fs_from_async(&ret)
    }

    /// Delete a file system.
    ///
    /// When file system has snapshot attached, all its snapshot will be
    /// deleted also. When file system is exported, all its exports will be
    /// deleted also. If specified file system is has child dependency, it
    /// cannot be deleted, please use [`Client::fs_has_child_dep()`][1] and
    /// [`Client::fs_child_dep_rm()`][2].
    ///
    /// [1]: #method.fs_has_child_dep()
    /// [2]: #method.fs_child_dep_rm()
    pub fn fs_delete(&mut self, fs: &FileSystem) -> Result<()> {
        let mut args = Map::new();
        args.insert("fs".to_string(), serde_json::to_value(fs)?);
        let ret = self.tp.invoke("fs_delete", Some(args))?;
        self.wait_if_async(&ret)
    }

    /// Clones an existing file system
    ///
    /// Create a point in time read writeable space efficient copy of specified
    /// file system, also know as read writeable snapshot. The new file system
    /// will reside in the same pool of specified file system.
    ///
    /// Optionally, new file system could be based on a snapshot specified by
    /// `snapshot` argument.
    pub fn fs_clone(
        &mut self,
        src_fs: &FileSystem,
        dst_fs_name: &str,
        snapshot: Option<&FileSystemSnapShot>,
    ) -> Result<FileSystem> {
        let mut args = Map::new();
        args.insert("src_fs".to_string(), serde_json::to_value(src_fs)?);
        args.insert(
            "dest_fs_name".to_string(),
            serde_json::to_value(dst_fs_name)?,
        );
        args.insert("snapshot".to_string(), serde_json::to_value(snapshot)?);

        let ret = self.tp.invoke("fs_clone", Some(args))?;
        self.get_fs_from_async(&ret)
    }

    /// Clones a file on a file system.
    ///
    /// Optionally, file contents could be based on a snapshot specified by
    /// `snapshot` argument.
    pub fn fs_file_clone(
        &mut self,
        fs: &FileSystem,
        src_file_name: &str,
        dst_file_name: &str,
        snapshot: Option<&FileSystemSnapShot>,
    ) -> Result<()> {
        let mut args = Map::new();
        args.insert("fs".to_string(), serde_json::to_value(fs)?);
        args.insert(
            "src_file_name".to_string(),
            serde_json::to_value(src_file_name)?,
        );
        args.insert(
            "dest_file_name".to_string(),
            serde_json::to_value(dst_file_name)?,
        );
        args.insert("snapshot".to_string(), serde_json::to_value(snapshot)?);

        let ret = self.tp.invoke("fs_file_clone", Some(args))?;
        self.wait_if_async(&ret)
    }

    /// Get a list of snapshots of specified file system.
    pub fn fs_snapshots(&mut self, fs: &FileSystem) -> Result<Vec<FileSystemSnapShot>> {
        let mut args = Map::new();
        args.insert("fs".to_string(), serde_json::to_value(fs)?);
        Ok(serde_json::from_value(
            self.tp.invoke("fs_snapshots", Some(args))?,
        )?)
    }

    /// Create a file system snapshot.
    pub fn fs_snapshot_create(
        &mut self,
        fs: &FileSystem,
        name: &str,
    ) -> Result<FileSystemSnapShot> {
        let mut args = Map::new();
        args.insert("fs".to_string(), serde_json::to_value(fs)?);
        args.insert("snapshot_name".to_string(), serde_json::to_value(name)?);
        let ret = self.tp.invoke("fs_snapshot_create", Some(args))?;
        self.get_fs_snap_from_asyn(&ret)
    }

    /// Delete a file system snapshot.
    pub fn fs_snapshot_delete(
        &mut self,
        fs: &FileSystem,
        snapshot: &FileSystemSnapShot,
    ) -> Result<()> {
        let mut args = Map::new();
        args.insert("fs".to_string(), serde_json::to_value(fs)?);
        args.insert("snapshot".to_string(), serde_json::to_value(snapshot)?);
        let ret = self.tp.invoke("fs_snapshot_delete", Some(args))?;
        self.wait_if_async(&ret)
    }

    /// Restore a file system based on specified snapshot.
    ///
    ///  * `fs` -- File system to restore.
    ///  * `snapshot` -- Snapshot to use.
    ///  * `all_file` -- `true` for restore all files. `false` for restore
    ///    specified files only.
    ///  * `files` -- Only restored specified files. Ignored if `all_file` is
    ///    `true`.
    ///  * `restore_files` -- If not `None`, rename restored files to defined
    ///    file paths and names
    pub fn fs_snapshot_restore(
        &mut self,
        fs: &FileSystem,
        snapshot: &FileSystemSnapShot,
        all_file: bool,
        files: Option<&[&str]>,
        restore_files: Option<&[&str]>,
    ) -> Result<()> {
        let mut args = Map::new();
        if all_file {
            let files: [&str; 0] = [];
            let restore_files: [&str; 0] = [];
            args.insert("files".to_string(), serde_json::to_value(files)?);
            args.insert(
                "restore_files".to_string(),
                serde_json::to_value(restore_files)?,
            );
        } else {
            let files = files.unwrap_or(&[]);
            if files.is_empty() {
                return Err(LsmError::InvalidArgument(
                    "Invalid argument: `all_file` is false while \
                     `files` is empty"
                        .to_string(),
                ));
            }
            let restore_files = restore_files.unwrap_or(&[]);
            if !restore_files.is_empty() && files.len() != restore_files.len() {
                return Err(LsmError::InvalidArgument(
                    "Invalid argument: `all_file` and `restore_files` have \
                     different length"
                        .to_string(),
                ));
            }
            args.insert("files".to_string(), serde_json::to_value(files)?);
            args.insert(
                "restore_files".to_string(),
                serde_json::to_value(restore_files)?,
            );
        }

        args.insert("fs".to_string(), serde_json::to_value(fs)?);
        args.insert("snapshot".to_string(), serde_json::to_value(snapshot)?);
        args.insert("all_files".to_string(), serde_json::to_value(all_file)?);
        let ret = self.tp.invoke("fs_snapshot_restore", Some(args))?;
        self.wait_if_async(&ret)
    }

    /// Checks whether file system has a child dependency.
    pub fn fs_has_child_dep(&mut self, fs: &FileSystem, files: Option<Vec<&str>>) -> Result<bool> {
        let mut args = Map::new();
        args.insert("fs".to_string(), serde_json::to_value(fs)?);
        let files: Vec<&str> = files.unwrap_or_default();
        args.insert("files".to_string(), serde_json::to_value(files)?);
        Ok(serde_json::from_value(
            self.tp.invoke("fs_child_dependency", Some(args))?,
        )?)
    }

    /// Delete all child dependencies of the specified file system.
    ///
    /// Instruct storage system to remove all child dependencies of the
    /// specified file system by duplicating the required storage before
    /// breaking replication relationship. This function might take a long
    /// time(days or even weeks), you might want to invoke it in a thread.
    pub fn fs_child_dep_rm(&mut self, fs: &FileSystem, files: Option<Vec<&str>>) -> Result<()> {
        let mut args = Map::new();
        args.insert("fs".to_string(), serde_json::to_value(fs)?);
        let files: Vec<&str> = files.unwrap_or_default();
        args.insert("files".to_string(), serde_json::to_value(files)?);
        let ret = self.tp.invoke("fs_child_dependency_rm", Some(args))?;
        self.wait_if_async(&ret)
    }

    /// Get supported NFS client authentication types.
    pub fn nfs_exp_auth_type_list(&mut self) -> Result<Vec<String>> {
        Ok(serde_json::from_value(
            self.tp.invoke("export_auth", None)?,
        )?)
    }

    /// Create or modify an NFS export.
    ///
    /// * `fs` -- File system to export.
    /// * `export_path` -- Export path. If already exists, will modify exist NFS
    ///   export. If `None`, will let storage system to generate one.
    /// * `access` -- NFS access details.
    /// * `auth_type` -- NFS client authentication type. Get from
    ///   [`Client::nfs_exp_auth_type_list()`][1].
    /// * `options` -- Extra NFS options.
    ///
    /// [1]: #method.nfs_exp_auth_type_list
    pub fn fs_export(
        &mut self,
        fs: &FileSystem,
        export_path: Option<&str>,
        access: &NfsAccess,
        auth_type: Option<&str>,
        options: Option<&str>,
    ) -> Result<NfsExport> {
        let root_list = access.root_list;
        let rw_list = access.rw_list;
        let ro_list = access.ro_list;

        if rw_list.is_empty() && ro_list.is_empty() {
            return Err(LsmError::InvalidArgument(
                "At least one host should exists in `rw_list` or `ro_list`".to_string(),
            ));
        }
        for host in root_list {
            if !rw_list.contains(host) && !ro_list.contains(host) {
                return Err(LsmError::InvalidArgument(format!(
                    "Host defined in `root_list` should be also \
                     defined in `rw_list` or `ro_list`: '{}'",
                    host
                )));
            }
        }
        for host in rw_list {
            if ro_list.contains(host) {
                return Err(LsmError::InvalidArgument(format!(
                    "Host should not both in `rw_list` \
                     and `ro_list`: '{}'",
                    host
                )));
            }
        }

        let mut args = Map::new();
        args.insert("fs_id".to_string(), serde_json::to_value(&fs.id)?);
        args.insert(
            "export_path".to_string(),
            serde_json::to_value(export_path)?,
        );
        args.insert("root_list".to_string(), serde_json::to_value(&root_list)?);
        args.insert("rw_list".to_string(), serde_json::to_value(&rw_list)?);
        args.insert("ro_list".to_string(), serde_json::to_value(&ro_list)?);

        let anon_uid = access.anon_uid.unwrap_or(NfsExport::ANON_UID_GID_NA);
        let anon_gid = access.anon_gid.unwrap_or(NfsExport::ANON_UID_GID_NA);
        args.insert("anon_uid".to_string(), serde_json::to_value(anon_uid)?);
        args.insert("anon_gid".to_string(), serde_json::to_value(anon_gid)?);
        args.insert("auth_type".to_string(), serde_json::to_value(auth_type)?);
        args.insert("options".to_string(), serde_json::to_value(options)?);
        Ok(serde_json::from_value(
            self.tp.invoke("export_fs", Some(args))?,
        )?)
    }

    /// Unexport specified NFS exports.
    pub fn fs_unexport(&mut self, exp: &NfsExport) -> Result<()> {
        let mut args = Map::new();
        args.insert("export".to_string(), serde_json::to_value(exp)?);
        Ok(serde_json::from_value(
            self.tp.invoke("export_remove", Some(args))?,
        )?)
    }

    /// Get volume RAID information.
    pub fn vol_raid_info(&mut self, vol: &Volume) -> Result<VolumeRaidInfo> {
        let mut args = Map::new();
        args.insert("volume".to_string(), serde_json::to_value(vol)?);
        let ret: Vec<i32> =
            serde_json::from_value(self.tp.invoke("volume_raid_info", Some(args))?)?;
        if ret.len() != 5 {
            return Err(LsmError::PluginBug(format!(
                "vol_raid_info() is expecting 5 i64 from plugin, \
                 but got '{:?}'",
                ret
            )));
        }
        Ok(VolumeRaidInfo {
            raid_type: From::from(ret[0]),
            strip_size: ret[1] as u32,
            disk_count: ret[2] as u32,
            min_io_size: ret[3] as u32,
            opt_io_size: ret[4] as u32,
        })
    }

    /// Get pool member information.
    pub fn pool_member_info(&mut self, pool: &Pool) -> Result<PoolMemberInfo> {
        let mut args = Map::new();
        args.insert("pool".to_string(), serde_json::to_value(pool)?);
        let ret = self.tp.invoke("pool_member_info", Some(args))?;
        let ret_array = ret.as_array().ok_or_plugin_bug(&ret)?;
        if ret_array.len() != 3 {
            return Err(LsmError::PluginBug(format!(
                "Plugin return unexpected data: {:?}",
                ret
            )));
        }
        let raid_type: i32 =
            serde_json::from_value(ret_array.get(0).ok_or_plugin_bug(&ret)?.clone())?;
        let raid_type: RaidType = From::from(raid_type);
        let member_type: u32 =
            serde_json::from_value(ret_array.get(1).ok_or_plugin_bug(&ret)?.clone())?;
        let member_ids: Vec<String> =
            serde_json::from_value(ret_array.get(2).ok_or_plugin_bug(&ret)?.clone())?;
        let mut members: Vec<PoolMember> = Vec::new();
        match member_type {
            POOL_MEMBER_TYPE_DISK => {
                for disk in self.disks()? {
                    if member_ids.contains(&disk.id) {
                        members.push(PoolMember::Disk(disk));
                    }
                }
            }
            POOL_MEMBER_TYPE_POOL => {
                for pool in self.pools()? {
                    if member_ids.contains(&pool.id) {
                        members.push(PoolMember::Pool(pool));
                    }
                }
            }
            _ => (),
        };
        Ok(PoolMemberInfo { raid_type, members })
    }

    /// Get system capability on creating RAIDed volume. For hardware RAID
    /// only.
    ///
    /// Returns supported RAID types and strip sizes.
    pub fn vol_raid_create_cap_get(&mut self, sys: &System) -> Result<(Vec<RaidType>, Vec<u32>)> {
        let mut args = Map::new();
        args.insert("system".to_string(), serde_json::to_value(sys)?);
        let ret = self.tp.invoke("volume_raid_create_cap_get", Some(args))?;
        let ret_array = ret.as_array().ok_or_plugin_bug(&ret)?;
        if ret_array.len() != 2 {
            return Err(LsmError::PluginBug(format!(
                "vol_raid_create_cap_get() is expecting array with \
                 2 members from plugin, but got '{:?}'",
                ret
            )));
        }
        let raid_types: Vec<i32> =
            serde_json::from_value(ret_array.get(0).ok_or_plugin_bug(&ret)?.clone())?;
        let strip_sizes: Vec<u32> =
            serde_json::from_value(ret_array.get(1).ok_or_plugin_bug(&ret)?.clone())?;
        let mut new_raid_types: Vec<RaidType> = Vec::new();
        for raid_type in raid_types {
            new_raid_types.push(From::from(raid_type));
        }
        Ok((new_raid_types, strip_sizes))
    }

    /// Create RAIDed volume directly from disks. Only for hardware RAID.
    pub fn vol_raid_create(
        &mut self,
        name: &str,
        raid_type: RaidType,
        disks: &[Disk],
        strip_size: Option<u32>,
    ) -> Result<Volume> {
        if disks.is_empty() {
            return Err(LsmError::InvalidArgument("no disk included".to_string()));
        }

        if raid_type == RaidType::Raid1 && disks.len() != 2 {
            return Err(LsmError::InvalidArgument(
                "RAID 1 only allow 2 disks".to_string(),
            ));
        }

        if raid_type == RaidType::Raid5 && disks.len() < 3 {
            return Err(LsmError::InvalidArgument(
                "RAID 5 require 3 or more disks".to_string(),
            ));
        }

        if raid_type == RaidType::Raid6 && disks.len() < 4 {
            return Err(LsmError::InvalidArgument(
                "RAID 6 require 4 or more disks".to_string(),
            ));
        }

        if raid_type == RaidType::Raid10 && (disks.len() % 2 != 0 || disks.len() < 4) {
            return Err(LsmError::InvalidArgument(
                "RAID 10 require even disks count and 4 or more disks".to_string(),
            ));
        }

        if raid_type == RaidType::Raid50 && (disks.len() % 2 != 0 || disks.len() < 6) {
            return Err(LsmError::InvalidArgument(
                "RAID 50 require even disks count and 6 or more disks".to_string(),
            ));
        }

        if raid_type == RaidType::Raid60 && (disks.len() % 2 != 0 || disks.len() < 8) {
            return Err(LsmError::InvalidArgument(
                "RAID 60 require even disks count and 8 or more disks".to_string(),
            ));
        }

        let mut args = Map::new();
        args.insert("name".to_string(), serde_json::to_value(name)?);
        args.insert(
            "raid_type".to_string(),
            serde_json::to_value(raid_type as i32)?,
        );
        args.insert("disks".to_string(), serde_json::to_value(disks)?);
        let strip_size = strip_size.unwrap_or(0u32);
        args.insert("strip_size".to_string(), serde_json::to_value(strip_size)?);
        Ok(serde_json::from_value(
            self.tp.invoke("volume_raid_create", Some(args))?,
        )?)
    }

    /// Turn on the identification LED for the specified volume.
    ///
    /// All its member disks' identification LED will be turned on.
    pub fn vol_ident_led_on(&mut self, vol: &Volume) -> Result<()> {
        let mut args = Map::new();
        args.insert("volume".to_string(), serde_json::to_value(vol)?);
        self.tp.invoke("vol_ident_led_on", Some(args))?;
        Ok(())
    }

    /// Turn off the identification LED for the specified volume.
    ///
    /// All its member disks' identification LED will be turned off.
    pub fn vol_ident_led_off(&mut self, vol: &Volume) -> Result<()> {
        let mut args = Map::new();
        args.insert("volume".to_string(), serde_json::to_value(vol)?);
        self.tp.invoke("vol_ident_led_off", Some(args))?;
        Ok(())
    }

    /// Get cache information on specified volume.
    pub fn vol_cache_info(&mut self, vol: &Volume) -> Result<VolumeCacheInfo> {
        let mut args = Map::new();
        args.insert("volume".to_string(), serde_json::to_value(vol)?);
        let ret: Vec<u8> =
            serde_json::from_value(self.tp.invoke("volume_cache_info", Some(args))?)?;
        if ret.len() != 5 {
            return Err(LsmError::PluginBug(format!(
                "vol_cache_info() is expecting 5 u8 from plugin, \
                 but got '{:?}'",
                ret
            )));
        }
        Ok(VolumeCacheInfo {
            write_cache_setting: match ret[0] {
                WRITE_CACHE_POLICY_WRITE_BACK => CachePolicy::Enabled,
                WRITE_CACHE_POLICY_WRITE_THROUGH => CachePolicy::Disabled,
                WRITE_CACHE_POLICY_AUTO => CachePolicy::Auto,
                _ => CachePolicy::Unknown,
            },
            write_cache_status: match ret[1] {
                WRITE_CACHE_STATUS_WRITE_BACK => CachePolicy::Enabled,
                WRITE_CACHE_STATUS_WRITE_THROUGH => CachePolicy::Disabled,
                _ => CachePolicy::Unknown,
            },
            read_cache_setting: match ret[2] {
                READ_CACHE_POLICY_ENABLED => CachePolicy::Enabled,
                READ_CACHE_POLICY_DISABLED => CachePolicy::Disabled,
                _ => CachePolicy::Unknown,
            },
            read_cache_status: match ret[3] {
                READ_CACHE_STATUS_ENABLED => CachePolicy::Enabled,
                READ_CACHE_STATUS_DISABLED => CachePolicy::Disabled,
                _ => CachePolicy::Unknown,
            },
            physical_disk_cache_status: match ret[4] {
                PHYSICAL_DISK_CACHE_ENABLED => CachePolicy::Enabled,
                PHYSICAL_DISK_CACHE_DISABLED => CachePolicy::Disabled,
                PHYSICAL_DISK_CACHE_USE_DISK_SETTING => CachePolicy::UseDiskSetting,
                _ => CachePolicy::Unknown,
            },
        })
    }

    /// Set volume physical disk cache policy.
    pub fn vol_phy_disk_cache_set(&mut self, vol: &Volume, pdc: CachePolicy) -> Result<()> {
        let pdc: u8 = match pdc {
            CachePolicy::Enabled => PHYSICAL_DISK_CACHE_ENABLED,
            CachePolicy::Disabled => PHYSICAL_DISK_CACHE_DISABLED,
            CachePolicy::UseDiskSetting => PHYSICAL_DISK_CACHE_USE_DISK_SETTING,
            _ => {
                return Err(LsmError::InvalidArgument(format!(
                    "Invalid pdc argument {:?}",
                    pdc
                )))
            }
        };
        let mut args = Map::new();
        args.insert("volume".to_string(), serde_json::to_value(vol)?);
        args.insert("pdc".to_string(), serde_json::to_value(pdc)?);
        self.tp
            .invoke("volume_physical_disk_cache_update", Some(args))?;
        Ok(())
    }

    /// Set volume write cache policy.
    pub fn vol_write_cache_set(&mut self, vol: &Volume, wcp: CachePolicy) -> Result<()> {
        let wcp: u8 = match wcp {
            CachePolicy::Enabled => WRITE_CACHE_POLICY_WRITE_BACK,
            CachePolicy::Disabled => WRITE_CACHE_POLICY_WRITE_THROUGH,
            CachePolicy::Auto => WRITE_CACHE_POLICY_AUTO,
            _ => {
                return Err(LsmError::InvalidArgument(format!(
                    "Invalid wcp argument {:?}",
                    wcp
                )))
            }
        };
        let mut args = Map::new();
        args.insert("volume".to_string(), serde_json::to_value(vol)?);
        args.insert("wcp".to_string(), serde_json::to_value(wcp)?);
        self.tp
            .invoke("volume_write_cache_policy_update", Some(args))?;
        Ok(())
    }

    /// Set volume read cache policy.
    pub fn vol_read_cache_set(&mut self, vol: &Volume, rcp: CachePolicy) -> Result<()> {
        let rcp: u8 = match rcp {
            CachePolicy::Enabled => READ_CACHE_POLICY_ENABLED,
            CachePolicy::Disabled => READ_CACHE_POLICY_DISABLED,
            _ => {
                return Err(LsmError::InvalidArgument(format!(
                    "Invalid rcp argument {:?}",
                    rcp
                )))
            }
        };
        let mut args = Map::new();
        args.insert("volume".to_string(), serde_json::to_value(vol)?);
        args.insert("rcp".to_string(), serde_json::to_value(rcp)?);
        self.tp
            .invoke("volume_read_cache_policy_update", Some(args))?;
        Ok(())
    }
}