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
use std::str::FromStr;
use std::time::Duration;
use std::{fmt, path::PathBuf};
use url::Url;

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

/// Certificate validation options
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CertificateValidationOptions {
    /// No validation is performed on the certificate provided by the server.
    ///
    /// This disables many of the security benefits of SSL/TLS and should only be used after very
    /// careful consideration. It is primarily intended as a temporary diagnostic mechanism when
    /// attempting to resolve TLS errors, and **its use on production clusters is strongly discouraged**.
    None,
    /// Full validation of the certificate, which validates that the certificate provided by the
    /// server is signed by a trusted Certificate Authority (CA) and also verifies that the server’s hostname
    /// (or IP address) matches the names identified by the CommonName (CN) or Subject Alternative
    /// Name (SAN) within the certificate.
    ///
    /// This is useful for self-signed certificates generated by your own CA,
    /// where the certificate contains the CommonName (CN) or a Subject Alternative Name (SAN)
    /// that matches the server hostname.
    ///
    /// Typically, the certificate provided to the client is the Certificate Authority (CA)
    /// used to sign the certificate used by the server.
    Full,
    /// Validates that the certificate provided by the server is signed by a trusted
    /// Certificate Authority (CA), but does not perform hostname verification.
    ///
    /// This is useful for self-signed certificates generated by your own CA
    /// that **do not** contain the CommonName (CN) or a Subject Alternative Name (SAN)
    /// that matches the server hostname.
    ///
    /// Typically, the certificate provided to the client will be the Certificate Authority (CA)
    /// used to sign the certificate used by the server.
    ///
    /// # Optional
    ///
    /// This requires the `native-tls` feature to be enabled.
    Partial,
}

impl FromStr for CertificateValidationOptions {
    type Err = serde_qs::Error;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        serde_qs::from_str(input)
    }
}

/// 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,
    /// Elasticsearch /stats filter_path. Comma-separated list or
    /// wildcard expressions of paths to include in the statistics.
    pub elasticsearch_query_filter_path: 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 TLS client certificate
    pub elasticsearch_certificate_path: Option<PathBuf>,
    /// Elasticsearch certificate validation
    pub elasticsearch_certificate_validation: Option<CertificateValidationOptions>,

    //
    // 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,
    /// Exporter skip zero metrics
    pub exporter_skip_zero_metrics: bool,
    /// Exporter metrics switch either ON or OFF
    pub exporter_metrics_enabled: ExporterMetricsSwitch,
    /// Export metrics namespace
    pub exporter_metrics_namespace: String,
    /// Exporter metadata refresh interval
    pub exporter_metadata_refresh_interval: Duration,

    /// Metrics polling interval
    pub exporter_poll_default_interval: Duration,
    /// Exporter skip zero metrics
    pub exporter_poll_intervals: ExporterPollIntervals,

    /// Exporter metrics lifetime interval
    pub exporter_metrics_lifetime_interval: ExporterPollIntervals,
    /// Metrics metrics lifetime
    pub exporter_metrics_lifetime_default_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_default()
    }

    /// ?filter_path= parameters for subsystems
    pub fn query_filter_path_for_subsystem(&self, subsystem: &'static str) -> Vec<&str> {
        self.elasticsearch_query_filter_path
            .get(subsystem)
            .map(|params| params.iter().map(AsRef::as_ref).collect::<Vec<&str>>())
            .unwrap_or_default()
    }

    /// 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_default()
    }

    /// 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)
    }

    /// /_cat subsystems
    pub fn cat_subsystems() -> &'static [&'static str] {
        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 [&'static str] {
        use metrics::_cluster::*;

        &[health::SUBSYSTEM]
    }

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

        &[usage::SUBSYSTEM, stats::SUBSYSTEM, info::SUBSYSTEM]
    }

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

        &[_all::SUBSYSTEM]
    }
}

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

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

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

fn vec_to_string(output: &mut String, field: &'static str, fields: &[&'static str]) {
    output.push('\n');
    output.push_str(&format!("{}:", field));
    for field in fields.iter() {
        output.push('\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("Proper Elasticsearch exporter");

        output.push('\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(),
        );
        vec_to_string(
            &mut output,
            "Available /_stats subsystems",
            Self::stats_subsystems(),
        );
        output.push('\n');

        output.push('\n');
        output.push_str("Exporter settings:");
        output.push('\n');
        output.push_str(&format!("elasticsearch_url: {}", self.elasticsearch_url));
        output.push('\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,
        );

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

        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('\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('\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('\n');
        output.push_str(&format!(
            "exporter_metrics_namespace: {}",
            self.exporter_metrics_namespace
        ));

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

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

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

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