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
use std::fmt;
use std::time::Duration;
use url::Url;

use crate::{metrics, CollectionLabels, ExporterMetricsSwitch, ExporterPollIntervals};

/// Elasticsearch exporter options
#[derive(Debug, Clone)]
pub struct ExporterOptions {
    /// Elasticsearch cluster url
    pub elasticsearch_url: Url,
    /// Global HTTP request timeout
    pub elasticsearch_global_timeout: Duration,
    /// Elasticsearch /_nodes/stats fields comma-separated list or
    /// wildcard expressions of fields to include in the statistics.
    pub elasticsearch_query_fields: CollectionLabels,
    /// Exporter timeout for subsystems, in case subsystem timeout is not defined
    /// default global timeout is used
    pub elasticsearch_subsystem_timeouts: ExporterPollIntervals,
    /// Elasticsearch path parameters
    /// https://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-nodes-info.html#cluster-nodes-info-api-path-params
    pub elasticsearch_path_parameters: CollectionLabels,

    //
    // Exporter
    //
    /// Exporter labels to skip
    pub exporter_skip_labels: CollectionLabels,
    /// Exporter labels to include, caution this may increase metric cardinality
    pub exporter_include_labels: CollectionLabels,
    /// Exporter labels to skip completely such as segment "id"
    pub exporter_skip_metrics: CollectionLabels,
    /// Metrics polling interval
    pub exporter_poll_default_interval: Duration,
    /// Exporter skip zero metrics
    pub exporter_poll_intervals: ExporterPollIntervals,
    /// Exporter skip zero metrics
    pub exporter_skip_zero_metrics: bool,
    /// Exporter metrics switch either ON or OFF
    pub exporter_metrics_enabled: ExporterMetricsSwitch,
    /// Exporter metadata refresh interval
    pub exporter_metadata_refresh_interval: Duration,
}

impl ExporterOptions {
    /// Enable metadata refresh?
    pub(crate) fn enable_metadata_refresh(&self) -> bool {
        let cluster_subsystems = Self::nodes_subsystems();

        self.exporter_metrics_enabled
            .iter()
            .any(|(k, v)| cluster_subsystems.contains(&k.as_str()) && *v)
    }

    /// Check if metric is enabled
    pub fn is_metric_enabled(&self, subsystem: &'static str) -> bool {
        self.exporter_metrics_enabled.contains_key(subsystem)
    }

    /// ?fields= parameters for subsystems
    pub fn query_fields_for_subsystem(&self, subsystem: &'static str) -> Vec<&str> {
        self.elasticsearch_query_fields
            .get(subsystem)
            .map(|params| params.iter().map(AsRef::as_ref).collect::<Vec<&str>>())
            .unwrap_or(Vec::new())
    }

    /// Path parameters for subsystems
    pub fn path_parameters_for_subsystem(&self, subsystem: &'static str) -> Vec<&str> {
        self.elasticsearch_path_parameters
            .get(subsystem)
            .map(|params| params.iter().map(AsRef::as_ref).collect::<Vec<&str>>())
            .unwrap_or(Vec::new())
    }

    /// Get timeout for subsystem or fallback to global
    pub fn timeout_for_subsystem(&self, subsystem: &'static str) -> Duration {
        self.elasticsearch_subsystem_timeouts
            .get(subsystem)
            .unwrap_or(&self.elasticsearch_global_timeout)
            .clone()
    }

    /// /_cat subsystems
    pub fn cat_subsystems() -> [&'static str; 16] {
        use metrics::_cat::*;

        [
            allocation::SUBSYSTEM,
            shards::SUBSYSTEM,
            indices::SUBSYSTEM,
            segments::SUBSYSTEM,
            nodes::SUBSYSTEM,
            recovery::SUBSYSTEM,
            health::SUBSYSTEM,
            pending_tasks::SUBSYSTEM,
            aliases::SUBSYSTEM,
            thread_pool::SUBSYSTEM,
            plugins::SUBSYSTEM,
            fielddata::SUBSYSTEM,
            nodeattrs::SUBSYSTEM,
            repositories::SUBSYSTEM,
            templates::SUBSYSTEM,
            transforms::SUBSYSTEM,
        ]
    }

    /// /_cluster subsystems
    pub fn cluster_subsystems() -> [&'static str; 1] {
        use metrics::_cluster::*;

        [health::SUBSYSTEM]
    }

    /// /_nodes subsystems
    pub fn nodes_subsystems() -> [&'static str; 3] {
        use metrics::_nodes::*;
        [usage::SUBSYSTEM, stats::SUBSYSTEM, info::SUBSYSTEM]
    }
}

fn switch_to_string(output: &mut String, field: &'static str, switches: &ExporterMetricsSwitch) {
    output.push_str("\n");
    output.push_str(&format!("{}:", field));
    for (k, v) in switches.iter() {
        output.push_str("\n");
        output.push_str(&format!(" - {}: {}", k, v));
    }
}

fn collection_labels_to_string(
    output: &mut String,
    field: &'static str,
    labels: &CollectionLabels,
) {
    output.push_str("\n");
    output.push_str(&format!("{}:", field));
    for (k, v) in labels.iter() {
        output.push_str("\n");
        output.push_str(&format!(" - {}: {}", k, v.join(",")));
    }
}

fn poll_duration_to_string(
    output: &mut String,
    field: &'static str,
    labels: &ExporterPollIntervals,
) {
    output.push_str("\n");
    output.push_str(&format!("{}:", field));
    for (k, v) in labels.iter() {
        output.push_str("\n");
        output.push_str(&format!(" - {}: {:?}", k, v));
    }
}

fn vec_to_string(output: &mut String, field: &'static str, fields: &[&'static str]) {
    output.push_str("\n");
    output.push_str(&format!("{}:", field));
    for field in fields.iter() {
        output.push_str("\n");
        output.push_str(&format!(" - {}", field));
    }
}

impl fmt::Display for ExporterOptions {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut output = String::from("Vinted Elasticsearch exporter");

        output.push_str("\n");
        vec_to_string(
            &mut output,
            "Available /_cat subsystems",
            &Self::cat_subsystems(),
        );
        vec_to_string(
            &mut output,
            "Available /_cluster subsystems",
            &Self::cluster_subsystems(),
        );
        vec_to_string(
            &mut output,
            "Available /_nodes subsystems",
            &Self::nodes_subsystems(),
        );
        output.push_str("\n");

        output.push_str("\n");
        output.push_str("Exporter settings:");
        output.push_str("\n");
        output.push_str(&format!("elasticsearch_url: {}", self.elasticsearch_url));
        output.push_str("\n");
        output.push_str(&format!(
            "elasticsearch_global_timeout: {:?}",
            self.elasticsearch_global_timeout
        ));

        collection_labels_to_string(
            &mut output,
            "elasticsearch_query_fields",
            &self.elasticsearch_query_fields,
        );

        poll_duration_to_string(
            &mut output,
            "elasticsearch_subsystem_timeouts",
            &self.elasticsearch_subsystem_timeouts,
        );

        collection_labels_to_string(
            &mut output,
            "elasticsearch_path_parameters",
            &self.elasticsearch_path_parameters,
        );

        collection_labels_to_string(
            &mut output,
            "exporter_skip_labels",
            &self.exporter_skip_labels,
        );
        collection_labels_to_string(
            &mut output,
            "exporter_include_labels",
            &self.exporter_include_labels,
        );
        collection_labels_to_string(
            &mut output,
            "exporter_skip_metrics",
            &self.exporter_skip_metrics,
        );

        // Exporter
        output.push_str("\n");
        output.push_str(&format!(
            "exporter_poll_default_interval: {:?}",
            self.exporter_poll_default_interval
        ));

        poll_duration_to_string(
            &mut output,
            "exporter_poll_intervals",
            &self.exporter_poll_intervals,
        );

        output.push_str("\n");
        output.push_str(&format!(
            "exporter_skip_zero_metrics: {:?}",
            self.exporter_skip_zero_metrics
        ));

        switch_to_string(
            &mut output,
            "exporter_metrics_enabled",
            &self.exporter_metrics_enabled,
        );

        output.push_str("\n");
        output.push_str(&format!(
            "exporter_metadata_refresh_interval: {:?}",
            self.exporter_metadata_refresh_interval
        ));

        output.push_str("\n");
        write!(f, "{}", output)
    }
}