netdata-plugin 0.2.0

netdata plugin helpers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
// SPDX-License-Identifier: AGPL-3.0-or-later

use std::fmt;
use std::fmt::{Debug, Display};
use validator::{Validate, ValidationError};

/// High-Level interface to run the data loop
/// and setup Chart and Dimension info in an efficient manner.  
/// (The [Collector](collector::Collector) section includes an example.)
pub mod collector;

/// A private function used for the validation of `type_id` entries.
///
/// tests:
/// * field is not empty.
/// * there is only one dot present and it's neither the first nor the last character.
/// * it doesn't contain illegal characters: [' ', '\t', '\n', '\r', '\\', '\'', '"', ','].
fn validate_type_id(v: &str) -> Result<(), ValidationError> {
    if v.is_empty() {
        return Err(ValidationError::new("Empty type_id field"));
    };

    if v.chars().filter(|x| x == &'.').count() != 1
        || v.chars().next() == Some('.')
        || v.chars().last() == Some('.')
    {
        return Err(ValidationError::new(
            "Requires one single dot in the middle of type_id field",
        ));
    }

    if v.matches(&[' ', '\t', '\n', '\r', '\\', '\'', '"', ','])
        .count()
        != 0
    {
        return Err(ValidationError::new("Illegal character"));
    }

    Ok(())
}

/// A private function used for the validation of `id` entries.
///
/// tests:
/// * field is not empty.
/// * there is no dot present.
/// * it doesn't contain other illegal characters: [' ', '\t', '\n', '\r', '\\', '\'', '"', ','].
fn validate_id(v: &str) -> Result<(), ValidationError> {
    if v.is_empty() {
        return Err(ValidationError::new("Empty id field"));
    };

    if v.matches(&['.', ' ', '\t', '\n', '\r', '\\', '\'', '"', ','])
        .count()
        != 0
    {
        return Err(ValidationError::new("Illegal character"));
    }

    Ok(())
}

/// Command literals used for plugin communication.
///
/// Netdata parses `stdout` output of plugins looking for lines starting with
/// this instruction codes.
///
/// See also <https://learn.netdata.cloud/docs/agent/collectors/plugins.d#external-plugins-api>
#[allow(non_camel_case_types)]
#[derive(Debug, Clone)]
pub enum Instruction {
    /// Create or update a [Chart].
    CHART,
    /// Add or update a [Dimension] associated to a chart.
    DIMENSION,
    /// signify [Begin] of a data collection sequence.
    BEGIN,
    /// [Set] the value of a dimension for the initialized chart.
    SET,
    /// Complete data collection for the initialized chart.
    END,
    /// Ignore the last collected values.
    FLUSH,
    /// Disable this plugin. This will prevent Netdata from restarting
    /// the plugin.
    ///
    /// You can also exit with the value 1 to have the same effect.
    DISABLE,
    /// define [Variables](Variable).
    VARIABLE,
}

/// Support simple serialization `.to_string()`.
impl fmt::Display for Instruction {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?}", self)
    }
}

/// Interpretion of sequential values for a given [Dimension].
#[allow(non_camel_case_types)]
#[derive(Debug, Clone)]
pub enum Algorithm {
    /// The value is drawn as-is (interpolated to second boundary).
    /// This is the the default behavior.
    absolute,
    /// The value increases over time, the difference from the last value is
    /// presented in the chart, the server interpolates the value and calculates
    /// a per second figure.
    incremental,
    /// The % of this value compared to the total of all dimensions.
    percentage_of_absolute_row, // kabab-case!
    /// The % of this value compared to the incremental total of all dimensions.
    percentage_of_incremental_row, // kabab-case!
}

/// The label of all variants can be printed by `{}` placeholders in format strings.
///
/// A conversion from `snake_case` to `kebab-case` will be performed for the output.
impl fmt::Display for Algorithm {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let replaced = format!("{:?}", self).replace("_", "-");
        write!(f, "{}", replaced)
    }
}

#[cfg(test)]
mod algorithm_tests {
    use super::Algorithm;
    #[test]
    fn algorithm_kebab_display_output() {
        let a = Algorithm::percentage_of_absolute_row;
        assert_eq!(a.to_string(), "percentage-of-absolute-row");
    }
}

/// Auxilary options available for [Dimension].
#[allow(non_camel_case_types)]
#[derive(Debug, Clone)]
pub enum DimensionOption {
    /// Mark a dimension as obsolete. Netdata will delete it after some time.
    obsolete,
    /// Make this dimension hidden,
    /// it will take part in the calculations but will not be presented in the chart.
    hidden,
}

/// Defines a new dimension for the [Chart].
///
/// The template of this instruction looks like:
///
/// `DIMENSION id [name [algorithm [multiplier [divisor [options]]]]]`
///
/// See also: <https://learn.netdata.cloud/docs/agent/collectors/plugins.d#dimension>
///
/// The [trait@Display] trait resp. the `.to_string()`-method should
/// be used to compose the final command string
///
/// ```
/// # use netdata_plugin::{Dimension};
/// let d = Dimension{
///     id: "test_id",
///     name: "test_name",
///     multiplier: Some(42),
///     ..Dimension::default()
/// };
/// assert_eq!(d.to_string(), r#"DIMENSION "test_id" "test_name" "" "42""# );
/// ```

///
#[derive(Debug, Default, Clone, Validate)]
pub struct Dimension<'a> {
    /// The id of this dimension (it is a text value, not numeric).
    /// It will be needed later to add values to the dimension.
    ///
    /// We suggest to avoid using `"."` in dimension ids.
    /// External databases expect metrics to be `"."` separated and people
    /// will get confused if a dimension id contains a dot.
    ///
    /// You can utilize [validate()](Self::validate()) to prevent this kind of issue.
    #[validate(custom = "validate_id")]
    pub id: &'a str,
    /// The name of the dimension as it will appear at the legend of the chart,
    /// if empty or missing the id will be used.
    pub name: &'a str,
    /// One of the [Algorithm] variantes.
    pub algorithm: Option<Algorithm>,
    /// An integer value to multiply the collected value, if empty or missing, 1 is used.
    pub multiplier: Option<i32>,
    /// An integer value to divide the collected value, if empty or missing, 1 is used.
    pub divisor: Option<i32>,
    /// A list of options.
    ///
    /// Options supported: [obsolete](DimensionOption::obsolete) to mark a dimension as obsolete
    /// (Netdata will delete it after some time) and [hidden](DimensionOption::hidden)
    /// to make this dimension hidden, it will take part in the calculations but will not
    /// be presented in the chart.
    pub options: Vec<DimensionOption>,
}

/// This will generate the final command text string.
///
/// Optional fields will be communicated as empty string or simply skipped.
///
impl<'a> fmt::Display for Dimension<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let all_fields = format!(
            "{:?} {:?} {:?} {:?} {:?} {:?} {:?}",
            Instruction::DIMENSION,
            self.id,
            self.name,
            some_to_textfield(&self.algorithm),
            some_to_textfield(&self.multiplier),
            some_to_textfield(&self.divisor),
            options_to_textfield(&self.options),
        );
        write!(f, "{}", all_fields.trim_end_matches(" \"\""))
    }
}

#[cfg(test)]
mod dimension_tests {
    use super::Algorithm;
    use super::Dimension;
    use super::DimensionOption;
    use pretty_assertions::assert_eq;
    use validator::Validate;

    #[test]
    fn dimension_display_output() {
        let d = Dimension {
            id: "test_id",
            name: "test_name",
            ..Dimension::default()
        };
        assert_eq!(d.to_string(), r#"DIMENSION "test_id" "test_name""#);
    }

    #[test]
    fn dimension_validate_id() {
        let d = Dimension {
            id: "contains_dot.",
            ..Dimension::default()
        };
        assert!(d.validate().is_err());
        let d = Dimension {
            id: "contains space",
            ..Dimension::default()
        };
        assert!(d.validate().is_err());
        let d = Dimension {
            id: r#"contains"quote"#,
            ..Dimension::default()
        };
        assert!(d.validate().is_err());
        let d = Dimension {
            id: r#"contains\backslash"#,
            ..Dimension::default()
        };
        assert!(d.validate().is_err());
        let d = Dimension {
            id: "legitim",
            ..Dimension::default()
        };
        d.validate().unwrap()
    }

    #[test]
    fn dimension_display_output_missing_name() {
        let d = Dimension {
            id: "test_id",
            ..Dimension::default()
        };
        assert_eq!(d.to_string(), r#"DIMENSION "test_id""#);
    }

    #[test]
    fn dimension_display_output_with_algorithm() {
        let d = Dimension {
            id: "test_id",
            name: "test_name",
            algorithm: Some(Algorithm::percentage_of_absolute_row),
            ..Dimension::default()
        };
        assert_eq!(
            d.to_string(),
            r#"DIMENSION "test_id" "test_name" "percentage-of-absolute-row""#
        );
    }

    #[test]
    fn dimension_display_output_with_options() {
        let d = Dimension {
            id: "test_label",
            options: vec![DimensionOption::obsolete, DimensionOption::hidden],
            ..Dimension::default()
        };
        assert_eq!(
            d.to_string(),
            r#"DIMENSION "test_label" "" "" "" "" "obsolete hidden""#
        );
    }

    #[test]
    fn dimension_display_output_with_multiplier() {
        let d = Dimension {
            id: "test_id",
            name: "test_name",
            algorithm: Some(Algorithm::absolute),
            multiplier: Some(42),
            ..Dimension::default()
        };
        assert_eq!(
            d.to_string(),
            r#"DIMENSION "test_id" "test_name" "absolute" "42""#
        );
    }

    #[test]
    fn dimension_display_output_empty_inner_fields() {
        let d = Dimension {
            id: "test_string",
            divisor: Some(42),
            ..Dimension::default()
        };
        assert_eq!(d.to_string(), r#"DIMENSION "test_string" "" "" "" "42""#);
    }

    #[test]
    fn dimension_clone() {
        let d = Dimension {
            id: "test_id",
            algorithm: Some(Algorithm::absolute),
            options: vec![DimensionOption::obsolete],
            ..Dimension::default()
        };
        let clone = d.clone();
        assert_eq!(
            clone.to_string(),
            r#"DIMENSION "test_id" "" "absolute" "" "" "obsolete""#
        );
    }
}

/// The type of graphical rendering.
#[allow(non_camel_case_types)]
#[derive(Debug, Clone)]
pub enum ChartType {
    /// Displays information as a series of data points connected by straight line segments.
    line,
    /// When multiple attributes are included, the first attribute is plotted as a line
    /// with a color fill followed by the second attribute, and so on. Technically,
    /// this chart type is based on the Line Chart and represents a filled area between
    /// the zero line and the line that connects data points.
    area,
    /// Stacked Area Chart is plotted in the form of several area series stacked on top
    /// of one another. The height of each series is determined by the value in each data point.
    stacked,
}

impl fmt::Display for ChartType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?}", self)
    }
}

/// Auxilary options available for [Chart].
#[allow(non_camel_case_types)]
#[derive(Debug, Clone)]
pub enum ChartOption {
    /// Mark a chart as obsolete (Netdata will hide it and delete it after some time).
    obsolete,
    /// Mark a chart as insignificant (this may be used by dashboards to make the charts smaller,
    /// or somehow visualize properly a less important chart).  
    detail,
    /// make Netdata store the first collected value, assuming there was an invisible
    /// previous value set to zero (this is used by `statsd` charts - if the first data
    /// collected value of incremental dimensions is not zero based, unrealistic spikes
    /// will appear with this option set).
    store_first,
    /// to perform all operations on a chart, but do not offer
    /// it on dashboards (the chart will be send to external databases).
    hidden,
}

/// This structure defines a new chart.
///
/// The template of this instruction looks like:
///
/// `CHART type.id name title units [family [context [charttype [priority [update_every [options [plugin [module]]]]]]]]`
///
/// See also: <https://learn.netdata.cloud/docs/agent/collectors/plugins.d#chart>
///
/// Use the formating features provided by the [trait@Display] trait or `to_string()`
/// to generate the final command string output.
///
/// Example:
///
/// ```
/// # use netdata_plugin::Chart;
/// let c = Chart {
///    type_id: "test_type.id",
///    name: "test_name",
///    title: "caption_text",
///    units: "test_units",
///    ..Chart::default()
/// };
/// assert_eq!(
///    c.to_string(),
///    r#"CHART "test_type.id" "test_name" "caption_text" "test_units""#
/// );
/// ```

/// See also: <https://learn.netdata.cloud/docs/agent/collectors/plugins.d#chart>
#[derive(Debug, Default, Clone, Validate)]
pub struct Chart<'a> {
    /// A dot-separated compound of `type.id` identifier strings.
    ///
    /// The `type` part controls the menu the charts will appear in.  
    /// `Id` Uniquely identifies the chart, this is what will be needed to add values to the chart.
    ///
    /// Use [validate()](Self::validate()) to test the formal correctness.
    #[validate(custom = "validate_type_id")]
    pub type_id: &'a str,
    /// The name that will be presented to the user instead of `id` in `type.id`.
    /// This means that only the `id` part of `type.id` is changed. When a name has been given,
    /// the chart is index (and can be referred) as both `type.id` and `type.name`.
    /// You can set name to `""` to disable it.
    pub name: &'a str,
    /// The text above the chart.
    pub title: &'a str,
    /// The label of the vertical axis of the chart, all dimensions added to a chart should have
    /// the same units of measurement.
    pub units: &'a str,
    /// This entry is used to group charts together (for example all `eth0` charts should say:
    /// `eth0`), if empty or missing, the `id` part of `type.id will` be used.
    /// This controls the sub-menu on the dashboard.
    pub familiy: &'a str,
    /// The `context` is giving the template of the chart. For example, if multiple charts present
    /// the same information for a different `family`, they should have the same `context`.
    ///
    /// This is used for looking up rendering information for the chart (colors, sizes,
    /// informational texts) and also apply alarms to it.
    pub context: &'a str,
    /// One of [ChartType] ([line](ChartType::line), [area](ChartType::area) or
    /// [stacked](ChartType::stacked)), if empty or missing, [line](ChartType::line) will be used.
    pub charttype: Option<ChartType>,
    /// The relative priority of the charts as rendered on the web page,
    /// lower numbers make the charts appear before the ones with higher numbers,
    /// if empty or missing, `1000` will be used.
    pub priority: Option<u64>,
    /// Overwrite the update frequency set by the server.
    ///
    /// Note: To force fields with strong typing, a numeric value of `1` is inserted as the default
    /// when subsequent given fields require such an output.
    pub update_every: Option<u64>,
    /// List of options. 4 options are currently supported:
    ///
    /// [obsolete](ChartOption::obsolete) to mark a chart as obsolete (Netdata will hide
    /// it and delete it after some time), [detail](ChartOption::detail) to mark a
    /// chart as insignificant (this may be used by dashboards to make the charts smaller,
    /// or somehow visualize properly a less important chart),
    /// [store_first](ChartOption::store_first) to make Netdata
    /// store the first collected value, assuming there was an invisible previous value
    /// set to zero (this is used by `statsd` charts - if the first data collected value
    /// of incremental dimensions is not zero based, unrealistic spikes will appear with
    /// this option set) and [hidden](ChartOption::hidden) to perform all operations on a chart,
    /// but do not offer it on dashboards (the chart will be send to external databases).
    pub options: Vec<ChartOption>,
    /// Let the user identify the plugin that generated the chart.
    /// If plugin is unset or empty, Netdata will automatically set the filename
    /// of the plugin that generated the chart.
    pub plugin: &'a str,
    /// Let the user identify the module that generated the chart. Module has not default.
    pub module: &'a str,
}

impl<'a> fmt::Display for Chart<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let all_fields = format!(
            // the double space after the 5th placeholder prevents removal of
            // empty mandatory fields by trim_end_matches() and shouldn't do
            // much harm ;)
            "{:?} {:?} {:?} {:?} {:?}  {:?} {:?} {:?} {:?} {:?} {:?} {:?} {:?}",
            Instruction::CHART,
            self.type_id,
            self.name,
            self.title,
            self.units,
            self.familiy,
            self.context,
            some_to_textfield(&self.charttype),
            some_to_textfield(&self.priority),
            some_to_textfield(&self.update_every),
            options_to_textfield(&self.options),
            self.plugin,
            self.module
        );
        write!(
            f,
            "{}",
            all_fields
                .trim_end_matches(" \"\"")
                .replace("\"  \"", "\" \"")
                .trim()
        )
    }
}

#[cfg(test)]
mod chart_tests {
    use super::Chart;
    use super::ChartOption;
    use super::ChartType;
    use pretty_assertions::assert_eq;
    use validator::Validate;

    #[test]
    fn minimal_chart() {
        let c = Chart {
            type_id: "test_type.id",
            name: "test_name",
            title: "caption_text",
            units: "test_units",
            ..Chart::default()
        };
        assert_eq!(
            c.to_string(),
            r#"CHART "test_type.id" "test_name" "caption_text" "test_units""#
        );
    }

    #[test]
    fn chart_manadatory_field_output() {
        let c = Chart {
            type_id: "test_type.id",
            ..Chart::default()
        };
        assert_eq!(c.to_string(), r#"CHART "test_type.id" "" "" """#);
    }

    #[test]
    fn chart_validate_test_id() {
        let c = Chart {
            type_id: "test_type.id",
            ..Chart::default()
        };
        assert!(c.validate().is_ok());
        let c = Chart {
            type_id: "double.dot.id",
            ..Chart::default()
        };
        assert!(c.validate().is_err());
        let c = Chart {
            type_id: ".start_dot",
            ..Chart::default()
        };
        assert!(c.validate().is_err());
        let c = Chart {
            type_id: "end_dot.",
            ..Chart::default()
        };
        assert!(c.validate().is_err());
        let c = Chart {
            type_id: "nodot",
            ..Chart::default()
        };
        assert!(c.validate().is_err());
    }

    #[test]
    fn chart_defaults() {
        let c = Chart {
            type_id: "test_type.id",
            name: "test_name",
            title: "test_title",
            units: "test_units",
            charttype: Some(ChartType::area),
            options: vec![ChartOption::hidden, ChartOption::obsolete],
            module: "module_name",
            ..Chart::default()
        };
        let clone = c.clone();
        assert_eq!(
            clone.to_string(),
            r#"CHART "test_type.id" "test_name" "test_title" "test_units" "" "" "area" "" "" "hidden obsolete" "" "module_name""#
        );
    }
}

/// [Variables](Variable) can claim validity for different scopes.
///
/// * [GLOBAL](Scope::GLOBAL) or [HOST](Scope::HOST) to define
///   the variable at the host level.
/// * [LOCAL](Scope::LOCAL) or [CHART](Scope::CHART) to define
///   the variable at the chart level.
///   Use chart-local variables when the same variable may exist
///   for different charts (i.e. Netdata monitors 2 mysql servers,
///   and you need to set the max_connections each server accepts).
///   Using chart-local variables is the ideal to build alarm templates.
///
/// The position of the VARIABLE line output, sets its default scope
/// (in case you do not specify a scope).
#[allow(non_camel_case_types)]
#[derive(Debug, Clone)]
pub enum Scope {
    GLOBAL,
    HOST,
    LOCAL,
    CHART,
}

/// Define and publish variables and constants.
///
/// `VARIABLE [SCOPE] name = value`
///
/// It defines a variable that can be used in alarms.  
/// This is also used for setting constants (like the max connections
/// a server may accept).
///
/// Examples:
///
/// ```
/// use netdata_plugin::{Variable, Scope};
/// let v = Variable {
///    scope: Some(Scope::GLOBAL),
///    name: "variable_name",
///    value: 3.14f64,
/// };
/// assert_eq!(v.to_string(), "VARIABLE GLOBAL variable_name = 3.14");
/// ```
///
/// Variables support 2 Scopes:
///
/// * [GLOBAL](Scope::GLOBAL) or [HOST](Scope::HOST) to define the
///   variable at the host level.
/// * [LOCAL](Scope::LOCAL) or [CHART](Scope::CHART) to define the
///   variable at the chart level.
///   Use chart-local variables when the same variable may exist
///   for different charts (i.e. Netdata monitors 2 mysql servers,
///   and you need to set the max_connections each server accepts).
///   Using chart-local variables is the ideal to build alarm templates.
///
/// The position of the VARIABLE line output, sets its default scope
/// (in case you do not specify a scope). So, defining a VARIABLE before
/// any [CHART](Chart), or between [END](Instruction::END) and
/// [BEGIN](Instruction::BEGIN) (outside any chart), sets `GLOBAL`
/// scope, while defining a VARIABLE just after a [CHART](Chart) or
/// a [DIMENSION](Dimension),
/// or within the BEGIN - END block of a chart, sets `LOCAL` scope.
///
/// These variables can be set and updated at any point.
///
/// Variable names should use alphanumeric characters, the `.` and the `_`.
///
/// The value is floating point (Netdata used long double).
///
/// Variables are transferred to upstream Netdata servers
/// (streaming and database replication).
#[derive(Debug, Default, Clone)]
pub struct Variable<'a> {
    pub scope: Option<Scope>,
    pub name: &'a str,
    pub value: f64,
}

impl<'a> fmt::Display for Variable<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{}",
            format!(
                "VARIABLE {}{} = {}",
                match &self.scope {
                    Some(s) => format!("{:?} ", s),
                    _ => "".to_owned(),
                },
                self.name,
                self.value
            )
        )
    }
}

#[cfg(test)]
mod variable_tests {
    use super::Scope;
    use super::Variable;

    #[test]
    fn minimal_variable_output() {
        let v = Variable {
            scope: None,
            name: "test_name",
            value: 0f64,
        };
        assert_eq!(v.to_string(), "VARIABLE test_name = 0");
    }

    #[test]
    fn scoped_variable_output() {
        let v = Variable {
            scope: Some(Scope::GLOBAL),
            name: "test_name",
            value: 3.14f64,
        };
        assert_eq!(v.to_string(), "VARIABLE GLOBAL test_name = 3.14");
    }
}

/// This Opens the [Begin] -> [Set] -> [End](Instruction::END) data collection sequence.
///
/// `BEGIN type.id [microseconds]`
///
/// See also: <https://learn.netdata.cloud/docs/agent/collectors/plugins.d#data-collection>
#[derive(Debug, Default, Clone)]
pub struct Begin<'a> {
    /// `type.id` Identifier as given in [Chart].
    pub type_id: &'a str,
    /// The number of microseconds since the last update of the chart.
    pub microseconds: Option<u128>,
}

impl<'a> fmt::Display for Begin<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{}",
            format!(
                "{:?} {:?}{}",
                Instruction::BEGIN,
                self.type_id,
                match &self.microseconds {
                    Some(us) => format!(" {}", us),
                    _ => "".to_owned(),
                }
            )
        )
    }
}

#[cfg(test)]
mod begin_tests {
    use super::Begin;

    #[test]
    fn begin_output() {
        let b = Begin {
            type_id: "test_type.id",
            ..Default::default()
        };
        assert_eq!(b.to_string(), r#"BEGIN "test_type.id""#);
    }

    #[test]
    fn begin_with_us_output() {
        let b = Begin {
            type_id: "test_type.id",
            microseconds: Some(42),
        };
        assert_eq!(b.to_string(), r#"BEGIN "test_type.id" 42"#);
    }
}

/// Store the collected values.
///
/// `SET id = [value]`
///
/// If a value is not collected, leave it empty, like this: `SET id =`
/// or do not output the line at all.
#[derive(Debug, Default, Clone)]
pub struct Set<'a> {
    /// The unique identification of the [Dimension] (of the chart just began)
    pub id: &'a str,
    /// the collected value, only integer values are collected.  
    /// If you want to push fractional values, multiply this value
    /// by 100 or 1000 and set the DIMENSION divider to 1000.
    pub value: Option<i64>,
}

impl<'a> fmt::Display for Set<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{}",
            format!(
                "{:?} {:?} ={}",
                Instruction::SET,
                self.id,
                match &self.value {
                    Some(v) => format!(" {}", v),
                    _ => "".to_owned(),
                }
            )
        )
    }
}

#[cfg(test)]
mod set_tests {
    use super::Set;

    #[test]
    fn incomplete_set_output() {
        let s = Set {
            id: "test_id",
            ..Default::default()
        };
        assert_eq!(s.to_string(), r#"SET "test_id" ="#);
    }

    #[test]
    fn set_with_value_output() {
        let s = Set {
            id: "test_id",
            value: Some(-42),
        };
        assert_eq!(s.to_string(), r#"SET "test_id" = -42"#);
    }
}

/// Text representation of a given optional field value or
/// an empty string instead of `None`.
fn some_to_textfield<T: Display>(opt: &Option<T>) -> String {
    match opt {
        Some(o) => format!("{}", o),
        _ => format!(""),
    }
}

/// A space delimited concatenation of all given options as string.
fn options_to_textfield<T: Debug>(opts: &Vec<T>) -> String {
    opts.iter()
        .map(|o| format!("{:?}", o))
        .collect::<Vec<String>>()
        .join(" ")
}