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
//! Ceph has a command system defined
//! in https://github.com/ceph/ceph/blob/master/src/mon/MonCommands.h
//! The cli commands mostly use this json based system.  This allows you to
//! make the exact
//! same calls without having to shell out with std::process::Command.
//! Many of the commands defined in this file have a simulate parameter to
//! allow you to test without actually calling Ceph.
extern crate serde_json;

use ceph::ceph_mon_command_without_data;
use error::RadosError;
use rados::rados_t;
use std::collections::HashMap;
use std::fmt;
use std::str::FromStr;
use uuid::Uuid;

#[derive(Deserialize, Debug)]
pub struct CephMon {
    pub rank: i64,
    pub name: String,
    pub addr: String,
}

#[derive(Deserialize, Debug)]
pub struct CrushNode {
    pub id: i64,
    pub name: String,
    #[serde(rename = "type")]
    pub crush_type: String,
    pub type_id: i64,
    pub children: Option<Vec<i64>>,
    pub crush_weight: Option<f64>,
    pub depth: Option<i64>,
    pub exists: Option<i64>,
    pub status: Option<String>,
    pub reweight: Option<f64>,
    pub primary_affinity: Option<f64>,
}

#[derive(Deserialize, Debug)]
pub struct CrushTree {
    pub nodes: Vec<CrushNode>,
    pub stray: Vec<String>,
}

#[derive(Deserialize, Debug)]
pub struct MgrMetadata {
    pub id: String,
    pub arch: String,
    pub ceph_version: String,
    pub cpu: String,
    pub distro: String,
    pub distro_description: String,
    pub distro_version: String,
    pub hostname: String,
    pub kernel_description: String,
    pub kernel_version: String,
    pub mem_swap_kb: u64,
    pub mem_total_kb: u64,
    pub os: String,
}

#[derive(Deserialize, Debug)]
pub struct MgrStandby {
    pub gid: u64,
    pub name: String,
    pub available_modules: Vec<String>,
}

#[derive(Deserialize, Debug)]
pub struct MgrDump {
    pub epoch: u64,
    pub active_gid: u64,
    pub active_name: String,
    pub active_addr: String,
    pub available: bool,
    pub standbys: Vec<MgrStandby>,
    pub modules: Vec<String>,
    pub available_modules: Vec<String>,
}

#[derive(Deserialize, Debug)]
pub struct MonDump {
    pub epoch: i64,
    pub fsid: String,
    pub modified: String,
    pub created: String,
    pub mons: Vec<CephMon>,
    pub quorum: Vec<i64>,
}

#[derive(Deserialize, Debug)]
pub struct MonStatus {
    pub name: String,
    pub rank: u64,
    pub state: MonState,
    pub election_epoch: u64,
    pub quorum: Vec<u64>,
    pub outside_quorum: Vec<u64>,
    pub extra_probe_peers: Vec<u64>,
    pub sync_provider: Vec<u64>,
    pub monmap: MonMap,
}

#[derive(Deserialize, Debug)]
pub struct MonMap {
    pub epoch: u64,
    pub fsid: Uuid,
    pub modified: String,
    pub created: String,
    pub mons: Vec<Mon>,
}

#[derive(Deserialize, Debug)]
pub struct Mon {
    pub rank: u64,
    pub name: String,
    pub addr: String,
}

#[derive(Deserialize, Debug)]
pub enum MonState {
    #[serde(rename = "probing")]
    Probing,
    #[serde(rename = "synchronizing")]
    Synchronizing,
    #[serde(rename = "electing")]
    Electing,
    #[serde(rename = "leader")]
    Leader,
    #[serde(rename = "peon")]
    Peon,
    #[serde(rename = "shutdown")]
    Shutdown,
}

#[derive(Deserialize, Debug, Serialize)]
pub enum OsdOption {
    #[serde(rename = "full")]
    Full,
    #[serde(rename = "pause")]
    Pause,
    #[serde(rename = "noup")]
    NoUp,
    #[serde(rename = "nodown")]
    NoDown,
    #[serde(rename = "noout")]
    NoOut,
    #[serde(rename = "noin")]
    NoIn,
    #[serde(rename = "nobackfill")]
    NoBackfill,
    #[serde(rename = "norebalance")]
    NoRebalance,
    #[serde(rename = "norecover")]
    NoRecover,
    #[serde(rename = "noscrub")]
    NoScrub,
    #[serde(rename = "nodeep-scrub")]
    NoDeepScrub,
    #[serde(rename = "notieragent")]
    NoTierAgent,
    #[serde(rename = "sortbitwise")]
    SortBitwise,
    #[serde(rename = "recovery_deletes")]
    RecoveryDeletes,
    #[serde(rename = "require_jewel_osds")]
    RequireJewelOsds,
    #[serde(rename = "require_kraken_osds")]
    RequireKrakenOsds,
}

impl fmt::Display for OsdOption {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            &OsdOption::Full => write!(f, "full"),
            &OsdOption::Pause => write!(f, "pause"),
            &OsdOption::NoUp => write!(f, "noup"),
            &OsdOption::NoDown => write!(f, "nodown"),
            &OsdOption::NoOut => write!(f, "noout"),
            &OsdOption::NoIn => write!(f, "noin"),
            &OsdOption::NoBackfill => write!(f, "nobackfill"),
            &OsdOption::NoRebalance => write!(f, "norebalance"),
            &OsdOption::NoRecover => write!(f, "norecover"),
            &OsdOption::NoScrub => write!(f, "noscrub"),
            &OsdOption::NoDeepScrub => write!(f, "nodeep-scrub"),
            &OsdOption::NoTierAgent => write!(f, "notieragent"),
            &OsdOption::SortBitwise => write!(f, "sortbitwise"),
            &OsdOption::RecoveryDeletes => write!(f, "recovery_deletes"),
            &OsdOption::RequireJewelOsds => write!(f, "require_jewel_osds"),
            &OsdOption::RequireKrakenOsds => write!(f, "require_kraken_osds"),
        }
    }
}

impl AsRef<str> for OsdOption {
    fn as_ref(&self) -> &str {
        match self {
            &OsdOption::Full => "full",
            &OsdOption::Pause => "pause",
            &OsdOption::NoUp => "noup",
            &OsdOption::NoDown => "nodown",
            &OsdOption::NoOut => "noout",
            &OsdOption::NoIn => "noin",
            &OsdOption::NoBackfill => "nobackfill",
            &OsdOption::NoRebalance => "norebalance",
            &OsdOption::NoRecover => "norecover",
            &OsdOption::NoScrub => "noscrub",
            &OsdOption::NoDeepScrub => "nodeep-scrub",
            &OsdOption::NoTierAgent => "notieragent",
            &OsdOption::SortBitwise => "sortbitwise",
            &OsdOption::RecoveryDeletes => "recovery_deletes",
            &OsdOption::RequireJewelOsds => "require_jewel_osds",
            &OsdOption::RequireKrakenOsds => "require_kraken_osds",
        }
    }
}

#[derive(Deserialize, Debug, Serialize)]
pub enum PoolOption {
    #[serde(rename = "size")]
    Size,
    #[serde(rename = "min_size")]
    MinSize,
    #[serde(rename = "crash_replay_interval")]
    CrashReplayInterval,
    #[serde(rename = "pg_num")]
    PgNum,
    #[serde(rename = "pgp_num")]
    PgpNum,
    #[serde(rename = "crush_rule")]
    CrushRule,
    #[serde(rename = "hashpspool")]
    HashPsPool,
    #[serde(rename = "nodelete")]
    NoDelete,
    #[serde(rename = "nopgchange")]
    NoPgChange,
    #[serde(rename = "nosizechange")]
    NoSizeChange,
    #[serde(rename = "write_fadvice_dontneed")]
    WriteFadviceDontNeed,
    #[serde(rename = "noscrub")]
    NoScrub,
    #[serde(rename = "nodeep-scrub")]
    NoDeepScrub,
    #[serde(rename = "hit_set_type")]
    HitSetType,
    #[serde(rename = "hit_set_period")]
    HitSetPeriod,
    #[serde(rename = "hit_set_count")]
    HitSetCount,
    #[serde(rename = "hit_set_fpp")]
    HitSetFpp,
    #[serde(rename = "use_gmt_hitset")]
    UseGmtHitset,
    #[serde(rename = "target_max_bytes")]
    TargetMaxBytes,
    #[serde(rename = "target_max_objects")]
    TargetMaxObjects,
    #[serde(rename = "cache_target_dirty_ratio")]
    CacheTargetDirtyRatio,
    #[serde(rename = "cache_target_dirty_high_ratio")]
    CacheTargetDirtyHighRatio,
    #[serde(rename = "cache_target_full_ratio")]
    CacheTargetFullRatio,
    #[serde(rename = "cache_min_flush_age")]
    CacheMinFlushAge,
    #[serde(rename = "cachem_min_evict_age")]
    CacheMinEvictAge,
    #[serde(rename = "auid")]
    Auid,
    #[serde(rename = "min_read_recency_for_promote")]
    MinReadRecencyForPromote,
    #[serde(rename = "min_write_recency_for_promote")]
    MinWriteRecencyForPromte,
    #[serde(rename = "fast_read")]
    FastRead,
    #[serde(rename = "hit_set_decay_rate")]
    HitSetGradeDecayRate,
    #[serde(rename = "hit_set_search_last_n")]
    HitSetSearchLastN,
    #[serde(rename = "scrub_min_interval")]
    ScrubMinInterval,
    #[serde(rename = "scrub_max_interval")]
    ScrubMaxInterval,
    #[serde(rename = "deep_scrub_interval")]
    DeepScrubInterval,
    #[serde(rename = "recovery_priority")]
    RecoveryPriority,
    #[serde(rename = "recovery_op_priority")]
    RecoveryOpPriority,
    #[serde(rename = "scrub_priority")]
    ScrubPriority,
    #[serde(rename = "compression_mode")]
    CompressionMode,
    #[serde(rename = "compression_algorithm")]
    CompressionAlgorithm,
    #[serde(rename = "compression_required_ratio")]
    CompressionRequiredRatio,
    #[serde(rename = "compression_max_blob_size")]
    CompressionMaxBlobSize,
    #[serde(rename = "compression_min_blob_size")]
    CompressionMinBlobSize,
    #[serde(rename = "csum_type")]
    CsumType,
    #[serde(rename = "csum_min_block")]
    CsumMinBlock,
    #[serde(rename = "csum_max_block")]
    CsumMaxBlock,
    #[serde(rename = "allow_ec_overwrites")]
    AllocEcOverwrites,
}

impl fmt::Display for PoolOption {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            &PoolOption::Size => write!(f, "size"),
            &PoolOption::MinSize => write!(f, "min_size"),
            &PoolOption::CrashReplayInterval => write!(f, "crash_replay_interval"),
            &PoolOption::PgNum => write!(f, "pg_num"),
            &PoolOption::PgpNum => write!(f, "pgp_num"),
            &PoolOption::CrushRule => write!(f, "crush_rule"),
            &PoolOption::HashPsPool => write!(f, "hashpspool"),
            &PoolOption::NoDelete => write!(f, "nodelete"),
            &PoolOption::NoPgChange => write!(f, "nopgchange"),
            &PoolOption::NoSizeChange => write!(f, "nosizechange"),
            &PoolOption::WriteFadviceDontNeed => write!(f, "write_fadvice_dontneed"),
            &PoolOption::NoScrub => write!(f, "noscrub"),
            &PoolOption::NoDeepScrub => write!(f, "nodeep-scrub"),
            &PoolOption::HitSetType => write!(f, "hit_set_type"),
            &PoolOption::HitSetPeriod => write!(f, "hit_set_period"),
            &PoolOption::HitSetCount => write!(f, "hit_set_count"),
            &PoolOption::HitSetFpp => write!(f, "hit_set_fpp"),
            &PoolOption::UseGmtHitset => write!(f, "use_gmt_hitset"),
            &PoolOption::TargetMaxBytes => write!(f, "target_max_bytes"),
            &PoolOption::TargetMaxObjects => write!(f, "target_max_objects"),
            &PoolOption::CacheTargetDirtyRatio => write!(f, "cache_target_dirty_ratio"),
            &PoolOption::CacheTargetDirtyHighRatio => write!(f, "cache_target_dirty_high_ratio"),
            &PoolOption::CacheTargetFullRatio => write!(f, "cache_target_full_ratio"),
            &PoolOption::CacheMinFlushAge => write!(f, "cache_min_flush_age"),
            &PoolOption::CacheMinEvictAge => write!(f, "cachem_min_evict_age"),
            &PoolOption::Auid => write!(f, "auid"),
            &PoolOption::MinReadRecencyForPromote => write!(f, "min_read_recency_for_promote"),
            &PoolOption::MinWriteRecencyForPromte => write!(f, "min_write_recency_for_promote"),
            &PoolOption::FastRead => write!(f, "fast_read"),
            &PoolOption::HitSetGradeDecayRate => write!(f, "hit_set_decay_rate"),
            &PoolOption::HitSetSearchLastN => write!(f, "hit_set_search_last_n"),
            &PoolOption::ScrubMinInterval => write!(f, "scrub_min_interval"),
            &PoolOption::ScrubMaxInterval => write!(f, "scrub_max_interval"),
            &PoolOption::DeepScrubInterval => write!(f, "deep_scrub_interval"),
            &PoolOption::RecoveryPriority => write!(f, "recovery_priority"),
            &PoolOption::RecoveryOpPriority => write!(f, "recovery_op_priority"),
            &PoolOption::ScrubPriority => write!(f, "scrub_priority"),
            &PoolOption::CompressionMode => write!(f, "compression_mode"),
            &PoolOption::CompressionAlgorithm => write!(f, "compression_algorithm"),
            &PoolOption::CompressionRequiredRatio => write!(f, "compression_required_ratio"),
            &PoolOption::CompressionMaxBlobSize => write!(f, "compression_max_blob_size"),
            &PoolOption::CompressionMinBlobSize => write!(f, "compression_min_blob_size"),
            &PoolOption::CsumType => write!(f, "csum_type"),
            &PoolOption::CsumMinBlock => write!(f, "csum_min_block"),
            &PoolOption::CsumMaxBlock => write!(f, "csum_max_block"),
            &PoolOption::AllocEcOverwrites => write!(f, "allow_ec_overwrites"),
        }
    }
}

impl AsRef<str> for PoolOption {
    fn as_ref(&self) -> &str {
        match self {
            &PoolOption::Size => "size",
            &PoolOption::MinSize => "min_size",
            &PoolOption::CrashReplayInterval => "crash_replay_interval",
            &PoolOption::PgNum => "pg_num",
            &PoolOption::PgpNum => "pgp_num",
            &PoolOption::CrushRule => "crush_rule",
            &PoolOption::HashPsPool => "hashpspool",
            &PoolOption::NoDelete => "nodelete",
            &PoolOption::NoPgChange => "nopgchange",
            &PoolOption::NoSizeChange => "nosizechange",
            &PoolOption::WriteFadviceDontNeed => "write_fadvice_dontneed",
            &PoolOption::NoScrub => "noscrub",
            &PoolOption::NoDeepScrub => "nodeep-scrub",
            &PoolOption::HitSetType => "hit_set_type",
            &PoolOption::HitSetPeriod => "hit_set_period",
            &PoolOption::HitSetCount => "hit_set_count",
            &PoolOption::HitSetFpp => "hit_set_fpp",
            &PoolOption::UseGmtHitset => "use_gmt_hitset",
            &PoolOption::TargetMaxBytes => "target_max_bytes",
            &PoolOption::TargetMaxObjects => "target_max_objects",
            &PoolOption::CacheTargetDirtyRatio => "cache_target_dirty_ratio",
            &PoolOption::CacheTargetDirtyHighRatio => "cache_target_dirty_high_ratio",
            &PoolOption::CacheTargetFullRatio => "cache_target_full_ratio",
            &PoolOption::CacheMinFlushAge => "cache_min_flush_age",
            &PoolOption::CacheMinEvictAge => "cachem_min_evict_age",
            &PoolOption::Auid => "auid",
            &PoolOption::MinReadRecencyForPromote => "min_read_recency_for_promote",
            &PoolOption::MinWriteRecencyForPromte => "min_write_recency_for_promote",
            &PoolOption::FastRead => "fast_read",
            &PoolOption::HitSetGradeDecayRate => "hit_set_decay_rate",
            &PoolOption::HitSetSearchLastN => "hit_set_search_last_n",
            &PoolOption::ScrubMinInterval => "scrub_min_interval",
            &PoolOption::ScrubMaxInterval => "scrub_max_interval",
            &PoolOption::DeepScrubInterval => "deep_scrub_interval",
            &PoolOption::RecoveryPriority => "recovery_priority",
            &PoolOption::RecoveryOpPriority => "recovery_op_priority",
            &PoolOption::ScrubPriority => "scrub_priority",
            &PoolOption::CompressionMode => "compression_mode",
            &PoolOption::CompressionAlgorithm => "compression_algorithm",
            &PoolOption::CompressionRequiredRatio => "compression_required_ratio",
            &PoolOption::CompressionMaxBlobSize => "compression_max_blob_size",
            &PoolOption::CompressionMinBlobSize => "compression_min_blob_size",
            &PoolOption::CsumType => "csum_type",
            &PoolOption::CsumMinBlock => "csum_min_block",
            &PoolOption::CsumMaxBlock => "csum_max_block",
            &PoolOption::AllocEcOverwrites => "allow_ec_overwrites",
        }
    }
}

pub fn osd_out(cluster_handle: rados_t, osd_id: u64, simulate: bool) -> Result<(), RadosError> {
    let cmd = json!({
        "prefix": "osd out",
        "ids": [osd_id.to_string()]
    });

    if !simulate {
        ceph_mon_command_without_data(cluster_handle, &cmd)?;
    }
    Ok(())
}

pub fn osd_crush_remove(cluster_handle: rados_t, osd_id: u64, simulate: bool) -> Result<(), RadosError> {
    let cmd = json!({
        "prefix": "osd crush remove",
        "name": format!("osd.{}", osd_id),
    });
    if !simulate {
        ceph_mon_command_without_data(cluster_handle, &cmd)?;
    }
    Ok(())
}

/// Query a ceph pool.
pub fn osd_pool_get(cluster_handle: rados_t, pool: &str, choice: &PoolOption) -> Result<String, RadosError> {
    let cmd = json!({
        "prefix": "osd pool get",
        "pool": pool,
        "var": choice,
    });
    let result = ceph_mon_command_without_data(cluster_handle, &cmd)?;
    if let Some(return_data) = result.0 {
        let mut l = return_data.lines();
        match l.next() {
            Some(res) => return Ok(res.into()),
            None => {
                return Err(RadosError::Error(format!(
                "Unable to parse osd pool get output: {:?}",
                return_data,
            )))
            },
        }
    }
    Err(RadosError::Error(result.1.unwrap_or(
        "No response from ceph for osd pool get".into(),
    )))
}

/// Set a pool value
pub fn osd_pool_set(cluster_handle: rados_t, pool: &str, key: &PoolOption, value: &str, simulate: bool)
    -> Result<(), RadosError> {
    let cmd = json!({
        "prefix": "osd pool set",
        "pool": pool,
        "var": key,
        "val": value,
    });
    if !simulate {
        ceph_mon_command_without_data(cluster_handle, &cmd)?;
    }
    Ok(())
}

pub fn osd_set(cluster_handle: rados_t, key: &OsdOption, force: bool, simulate: bool) -> Result<(), RadosError> {
    let cmd = match force {
        true => {
            json!({
                "prefix": "osd set",
                "key": key,
                "sure": "--yes-i-really-mean-it",
            })
        },
        false => {
            json!({
                "prefix": "osd set",
                "key": key,
            })
        },
    };
    if !simulate {
        ceph_mon_command_without_data(cluster_handle, &cmd)?;
    }
    Ok(())
}

pub fn osd_unset(cluster_handle: rados_t, key: &OsdOption, simulate: bool) -> Result<(), RadosError> {
    let cmd = json!({
        "prefix": "osd unset",
        "key": key,
    });
    if !simulate {
        ceph_mon_command_without_data(cluster_handle, &cmd)?;
    }
    Ok(())
}

pub fn osd_tree(cluster_handle: rados_t) -> Result<CrushTree, RadosError> {
    let cmd = json!({
        "prefix": "osd tree",
        "format": "json"
    });
    let result = ceph_mon_command_without_data(cluster_handle, &cmd)?;
    if let Some(return_data) = result.0 {
        let mut l = return_data.lines();
        match l.next() {
            Some(res) => return Ok(serde_json::from_str(res)?),
            None => {
                return Err(RadosError::Error(format!(
                "Unable to parse osd tree output: {:?}",
                return_data,
            )))
            },
        }
    }
    Err(RadosError::Error("No response from ceph for osd tree".into()))
}

// Get cluster status
pub fn status(cluster_handle: rados_t) -> Result<String, RadosError> {
    let cmd = json!({
        "prefix": "status",
        "format": "json"
    });
    let result = ceph_mon_command_without_data(cluster_handle, &cmd)?;
    if let Some(return_data) = result.0 {
        let mut l = return_data.lines();
        match l.next() {
            Some(res) => return Ok(res.into()),
            None => {
                return Err(RadosError::Error(format!(
                "Unable to parse status output: {:?}",
                return_data,
            )))
            },
        }
    }
    Err(RadosError::Error("No response from ceph for status".into()))
}

/// List all the monitors in the cluster and their current rank
pub fn mon_dump(cluster_handle: rados_t) -> Result<MonDump, RadosError> {
    let cmd = json!({
        "prefix": "mon dump",
        "format": "json"
    });
    let result = ceph_mon_command_without_data(cluster_handle, &cmd)?;
    if let Some(return_data) = result.0 {
        let mut l = return_data.lines();
        match l.next() {
            Some(res) => return Ok(serde_json::from_str(res)?),
            None => {
                return Err(RadosError::Error(format!(
                "Unable to parse mon dump output: {:?}",
                return_data,
            )))
            },
        }
    }
    Err(RadosError::Error("No response from ceph for mon dump".into()))
}

/// Get the mon quorum
pub fn mon_quorum(cluster_handle: rados_t) -> Result<String, RadosError> {
    let cmd = json!({
        "prefix": "quorum_status",
        "format": "json"
    });
    let result = ceph_mon_command_without_data(cluster_handle, &cmd)?;
    if let Some(return_data) = result.0 {
        let mut l = return_data.lines();
        match l.next() {
            Some(res) => return Ok(serde_json::from_str(res)?),
            None => {
                return Err(RadosError::Error(format!(
                "Unable to parse quorum_status output: {:?}",
                return_data,
            )))
            },
        }
    }
    Err(RadosError::Error("No response from ceph for quorum_status".into()))
}

/// Get the mon status
pub fn mon_status(cluster_handle: rados_t) -> Result<MonStatus, RadosError> {
    let cmd = json!({
        "prefix": "mon_status",
    });
    let result = ceph_mon_command_without_data(cluster_handle, &cmd)?;
    if let Some(return_data) = result.0 {
        let mut l = return_data.lines();
        match l.next() {
            Some(res) => return Ok(serde_json::from_str(res)?),
            None => {
                return Err(RadosError::Error(format!(
                "Unable to parse mon_status output: {:?}",
                return_data,
            )))
            },
        }
    }
    Err(RadosError::Error("No response from ceph for mon_status".into()))
}

/// Show mon daemon version
pub fn version(cluster_handle: rados_t) -> Result<String, RadosError> {
    let cmd = json!({
        "prefix": "version",
    });
    let result = ceph_mon_command_without_data(cluster_handle, &cmd)?;
    if let Some(return_data) = result.0 {
        let mut l = return_data.lines();
        match l.next() {
            Some(res) => return Ok(res.to_string()),
            None => {
                return Err(RadosError::Error(format!(
                "Unable to parse version output: {:?}",
                return_data,
            )))
            },
        }
    }
    Err(RadosError::Error("No response from ceph for version".into()))
}


pub fn osd_pool_quota_get(cluster_handle: rados_t, pool: &str) -> Result<u64, RadosError> {
    let cmd = json!({
        "prefix": "osd pool get-quota",
        "pool": pool
    });
    let result = ceph_mon_command_without_data(cluster_handle, &cmd)?;
    if let Some(return_data) = result.0 {
        let mut l = return_data.lines();
        match l.next() {
            Some(res) => return Ok(u64::from_str(res)?),
            None => {
                return Err(RadosError::Error(format!(
                "Unable to parse osd pool quota-get output: {:?}",
                return_data,
            )))
            },
        }
    }
    Err(RadosError::Error("No response from ceph for osd pool quota-get".into()))
}

pub fn auth_del(cluster_handle: rados_t, osd_id: u64, simulate: bool) -> Result<(), RadosError> {
    let cmd = json!({
        "prefix": "auth del",
        "entity": format!("osd.{}", osd_id)
    });

    if !simulate {
        ceph_mon_command_without_data(cluster_handle, &cmd)?;
    }
    Ok(())
}

pub fn osd_rm(cluster_handle: rados_t, osd_id: u64, simulate: bool) -> Result<(), RadosError> {
    let cmd = json!({
        "prefix": "osd rm",
        "ids": [osd_id.to_string()]
    });

    if !simulate {
        ceph_mon_command_without_data(cluster_handle, &cmd)?;
    }
    Ok(())

}

pub fn osd_create(cluster_handle: rados_t, id: Option<u64>, simulate: bool) -> Result<u64, RadosError> {
    let cmd = match id {
        Some(osd_id) => {
            json!({
                "prefix": "osd create",
                "id": format!("osd.{}", osd_id),
            })
        },
        None => {
            json!({
                "prefix": "osd create"
            })
        },
    };

    if simulate {
        return Ok(0);
    }

    let result = ceph_mon_command_without_data(cluster_handle, &cmd)?;
    if let Some(return_data) = result.0 {
        let mut l = return_data.lines();
        match l.next() {
            Some(num) => return Ok(u64::from_str(num)?),
            None => {
                return Err(RadosError::Error(format!(
                "Unable to parse osd create output: {:?}",
                return_data,
            )))
            },
        }
    }
    Err(RadosError::Error(format!("Unable to parse osd create output: {:?}", result)))
}

// Add a new mgr to the cluster
pub fn mgr_auth_add(cluster_handle: rados_t, mgr_id: &str, simulate: bool) -> Result<(), RadosError> {
    let cmd = json!({
        "prefix": "auth add",
        "entity": format!("mgr.{}", mgr_id),
        "caps": ["mon", "allow profile mgr", "osd", "allow *", "mds", "allow *"],
    });

    if !simulate {
        ceph_mon_command_without_data(cluster_handle, &cmd)?;
    }
    Ok(())
}

// Add a new osd to the cluster
pub fn osd_auth_add(cluster_handle: rados_t, osd_id: u64, simulate: bool) -> Result<(), RadosError> {
    let cmd = json!({
        "prefix": "auth add",
        "entity": format!("osd.{}", osd_id),
        "caps": ["mon", "allow rwx", "osd", "allow *"],
    });

    if !simulate {
        ceph_mon_command_without_data(cluster_handle, &cmd)?;
    }
    Ok(())
}

/// Get a ceph-x key.  The id parameter can be either a number or a string
/// depending on the type of client so I went with string.
pub fn auth_get_key(cluster_handle: rados_t, client_type: &str, id: &str) -> Result<String, RadosError> {
    let cmd = json!({
        "prefix": "auth get-key",
        "entity": format!("{}.{}", client_type, id),
    });

    let result = ceph_mon_command_without_data(cluster_handle, &cmd)?;
    if let Some(return_data) = result.0 {
        let mut l = return_data.lines();
        match l.next() {
            Some(key) => return Ok(key.into()),
            None => {
                return Err(RadosError::Error(format!(
                "Unable to parse auth get-key: {:?}",
                return_data,
            )))
            },
        }
    }
    Err(RadosError::Error(format!("Unable to parse auth get-key output: {:?}", result)))
}

// ceph osd crush add {id-or-name} {weight}  [{bucket-type}={bucket-name} ...]
/// add or update crushmap position and weight for an osd
pub fn osd_crush_add(cluster_handle: rados_t, osd_id: u64, weight: f64, host: &str, simulate: bool)
    -> Result<(), RadosError> {
    let cmd = json!({
        "prefix": "osd crush add",
        "id": osd_id,
        "weight": weight,
        "args": [format!("host={}", host)]
    });

    if !simulate {
        ceph_mon_command_without_data(cluster_handle, &cmd)?;
    }
    Ok(())
}

// Luminous mgr commands below

/// dump the latest MgrMap
pub fn mgr_dump(cluster_handle: rados_t) -> Result<MgrDump, RadosError> {
    let cmd = json!({
        "prefix": "mgr dump",
    });

    let result = ceph_mon_command_without_data(cluster_handle, &cmd)?;
    if let Some(return_data) = result.0 {
        let mut l = return_data.lines();
        match l.next() {
            Some(res) => return Ok(serde_json::from_str(res)?),
            None => {
                return Err(RadosError::Error(format!(
                "Unable to parse mgr dump: {:?}",
                return_data,
            )))
            },
        }
    }
    Err(RadosError::Error(format!("Unable to parse mgr dump output: {:?}", result)))
}

/// Treat the named manager daemon as failed
pub fn mgr_fail(cluster_handle: rados_t, mgr_id: &str, simulate: bool) -> Result<(), RadosError> {
    let cmd = json!({
        "prefix": "mgr fail",
        "name": mgr_id,
    });

    if !simulate {
        ceph_mon_command_without_data(cluster_handle, &cmd)?;
    }
    Ok(())
}

/// List active mgr modules
pub fn mgr_list_modules(cluster_handle: rados_t) -> Result<Vec<String>, RadosError> {
    let cmd = json!({
        "prefix": "mgr module ls",
    });

    let result = ceph_mon_command_without_data(cluster_handle, &cmd)?;
    if let Some(return_data) = result.0 {
        let mut l = return_data.lines();
        match l.next() {
            Some(res) => return Ok(serde_json::from_str(res)?),
            None => {
                return Err(RadosError::Error(format!(
                "Unable to parse mgr module ls: {:?}",
                return_data,
            )))
            },
        }
    }
    Err(RadosError::Error(format!("Unable to parse mgr ls output: {:?}", result)))
}

/// List service endpoints provided by mgr modules
pub fn mgr_list_services(cluster_handle: rados_t) -> Result<Vec<String>, RadosError> {
    let cmd = json!({
        "prefix": "mgr services",
    });

    let result = ceph_mon_command_without_data(cluster_handle, &cmd)?;
    if let Some(return_data) = result.0 {
        let mut l = return_data.lines();
        match l.next() {
            Some(res) => return Ok(serde_json::from_str(res)?),
            None => {
                return Err(RadosError::Error(format!(
                "Unable to parse mgr services: {:?}",
                return_data,
            )))
            },
        }
    }
    Err(RadosError::Error(format!("Unable to parse mgr services output: {:?}", result)))
}

/// Enable a mgr module
pub fn mgr_enable_module(cluster_handle: rados_t, module: &str, force: bool, simulate: bool) -> Result<(), RadosError> {
    let cmd = match force {
        true => {
            json!({
                    "prefix": "mgr module enable",
                    "module": module,
                    "force": "--force",
                })
        },
        false => {
            json!({
                    "prefix": "mgr module enable",
                    "module": module,
                })
        },
    };

    if !simulate {
        ceph_mon_command_without_data(cluster_handle, &cmd)?;
    }
    Ok(())
}

/// Disable a mgr module
pub fn mgr_disable_module(cluster_handle: rados_t, module: &str, simulate: bool) -> Result<(), RadosError> {
    let cmd = json!({
        "prefix": "mgr module disable",
        "module": module,
    });

    if !simulate {
        ceph_mon_command_without_data(cluster_handle, &cmd)?;
    }
    Ok(())
}

/// dump metadata for all daemons
pub fn mgr_metadata(cluster_handle: rados_t) -> Result<MgrMetadata, RadosError> {
    let cmd = json!({
        "prefix": "mgr metadata",
    });

    let result = ceph_mon_command_without_data(cluster_handle, &cmd)?;
    if let Some(return_data) = result.0 {
        let mut l = return_data.lines();
        match l.next() {
            Some(res) => return Ok(serde_json::from_str(res)?),
            None => {
                return Err(RadosError::Error(format!(
                "Unable to parse mgr metadata: {:?}",
                return_data,
            )))
            },
        }
    }
    Err(RadosError::Error(format!("Unable to parse mgr metadata output: {:?}", result)))
}

/// count ceph-mgr daemons by metadata field property
pub fn mgr_count_metadata(cluster_handle: rados_t, property: &str) -> Result<HashMap<String, u64>, RadosError> {
    let cmd = json!({
        "prefix": "mgr count-metadata",
        "name": property,
    });

    let result = ceph_mon_command_without_data(cluster_handle, &cmd)?;
    if let Some(return_data) = result.0 {
        let mut l = return_data.lines();
        match l.next() {
            Some(res) => return Ok(serde_json::from_str(res)?),
            None => {
                return Err(RadosError::Error(format!(
                "Unable to parse mgr count-metadata: {:?}",
                return_data,
            )))
            },
        }
    }
    Err(RadosError::Error(format!("Unable to parse mgr count-metadata output: {:?}", result)))
}

/// check running versions of ceph-mgr daemons
pub fn mgr_versions(cluster_handle: rados_t) -> Result<HashMap<String, u64>, RadosError> {
    let cmd = json!({
        "prefix": "mgr versions",
    });

    let result = ceph_mon_command_without_data(cluster_handle, &cmd)?;
    if let Some(return_data) = result.0 {
        let mut l = return_data.lines();
        match l.next() {
            Some(res) => return Ok(serde_json::from_str(res)?),
            None => {
                return Err(RadosError::Error(format!(
                "Unable to parse mgr versions: {:?}",
                return_data,
            )))
            },
        }
    }
    Err(RadosError::Error(format!("Unable to parse mgr versions output: {:?}", result)))
}