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
mod common;
mod config;
pub mod encoder;
pub mod health;
pub mod request_builder;
pub mod retry;
pub mod service;
pub mod sink;

#[cfg(test)]
mod tests;

#[cfg(test)]
#[cfg(feature = "es-integration-tests")]
mod integration_tests;

use std::{convert::TryFrom, fmt};

pub use common::*;
pub use config::*;
pub use encoder::ElasticsearchEncoder;
use http::{uri::InvalidUri, Request};
use snafu::Snafu;
use vector_lib::sensitive_string::SensitiveString;
use vector_lib::{configurable::configurable_component, internal_event};

use crate::{
    event::{EventRef, LogEvent},
    internal_events::TemplateRenderingError,
    template::{Template, TemplateParseError},
};

/// Elasticsearch Authentication strategies.
#[configurable_component]
#[derive(Clone, Debug)]
#[serde(deny_unknown_fields, rename_all = "snake_case", tag = "strategy")]
#[configurable(metadata(
    docs::enum_tag_description = "The authentication strategy to use.\n\nAmazon OpenSearch Serverless requires this option to be set to `aws`."
))]
pub enum ElasticsearchAuthConfig {
    /// HTTP Basic Authentication.
    Basic {
        /// Basic authentication username.
        #[configurable(metadata(docs::examples = "${ELASTICSEARCH_USERNAME}"))]
        #[configurable(metadata(docs::examples = "username"))]
        user: String,

        /// Basic authentication password.
        #[configurable(metadata(docs::examples = "${ELASTICSEARCH_PASSWORD}"))]
        #[configurable(metadata(docs::examples = "password"))]
        password: SensitiveString,
    },

    #[cfg(feature = "aws-core")]
    /// Amazon OpenSearch Service-specific authentication.
    Aws(crate::aws::AwsAuthentication),
}

/// Elasticsearch Indexing mode.
#[configurable_component]
#[derive(Clone, Debug, Eq, PartialEq)]
#[serde(deny_unknown_fields, rename_all = "snake_case")]
pub enum ElasticsearchMode {
    /// Ingests documents in bulk, using the bulk API `index` action.
    #[serde(alias = "normal")]
    Bulk,

    /// Ingests documents in bulk, using the bulk API `create` action.
    ///
    /// Elasticsearch Data Streams only support the `create` action.
    DataStream,
}

impl Default for ElasticsearchMode {
    fn default() -> Self {
        Self::Bulk
    }
}

/// Bulk API actions.
#[configurable_component]
#[derive(Clone, Copy, Debug, Derivative, Eq, Hash, PartialEq)]
#[serde(deny_unknown_fields, rename_all = "snake_case")]
pub enum BulkAction {
    /// The `index` action.
    Index,

    /// The `create` action.
    Create,
}

#[allow(clippy::trivially_copy_pass_by_ref)]
impl BulkAction {
    pub const fn as_str(&self) -> &'static str {
        match self {
            BulkAction::Index => "index",
            BulkAction::Create => "create",
        }
    }

    pub const fn as_json_pointer(&self) -> &'static str {
        match self {
            BulkAction::Index => "/index",
            BulkAction::Create => "/create",
        }
    }
}

impl TryFrom<&str> for BulkAction {
    type Error = String;

    fn try_from(input: &str) -> Result<Self, Self::Error> {
        match input {
            "index" => Ok(BulkAction::Index),
            "create" => Ok(BulkAction::Create),
            _ => Err(format!("Invalid bulk action: {}", input)),
        }
    }
}

/// Elasticsearch version types.
#[configurable_component]
#[derive(Clone, Copy, Debug, Derivative, Eq, Hash, PartialEq)]
#[serde(deny_unknown_fields, rename_all = "snake_case")]
pub enum VersionType {
    /// The `internal` type.
    Internal,

    /// The `external` or `external_gt` type.
    External,

    /// The `external_gte` type.
    ExternalGte,
}

#[allow(clippy::trivially_copy_pass_by_ref)]
impl VersionType {
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Internal => "internal",
            Self::External => "external",
            Self::ExternalGte => "external_gte",
        }
    }
}

impl TryFrom<&str> for VersionType {
    type Error = String;

    fn try_from(input: &str) -> Result<Self, Self::Error> {
        match input {
            "internal" => Ok(VersionType::Internal),
            "external" | "external_gt" => Ok(VersionType::External),
            "external_gte" => Ok(VersionType::ExternalGte),
            _ => Err(format!("Invalid versioning mode: {}", input)),
        }
    }
}

impl_generate_config_from_default!(ElasticsearchConfig);

#[derive(Debug, Clone)]
pub enum ElasticsearchCommonMode {
    Bulk {
        index: Template,
        action: Template,
        version: Option<Template>,
        version_type: VersionType,
    },
    DataStream(DataStreamConfig),
}

struct VersionValueParseError<'a> {
    value: &'a str,
}

impl internal_event::InternalEvent for VersionValueParseError<'_> {
    fn emit(self) {
        warn!("{self}")
    }
}

impl fmt::Display for VersionValueParseError<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Cannot parse version \"{}\" as integer", self.value)
    }
}

impl ElasticsearchCommonMode {
    fn index(&self, log: &LogEvent) -> Option<String> {
        match self {
            Self::Bulk { index, .. } => index
                .render_string(log)
                .map_err(|error| {
                    emit!(TemplateRenderingError {
                        error,
                        field: Some("index"),
                        drop_event: true,
                    });
                })
                .ok(),
            Self::DataStream(ds) => ds.index(log),
        }
    }

    fn bulk_action<'a>(&self, event: impl Into<EventRef<'a>>) -> Option<BulkAction> {
        match self {
            ElasticsearchCommonMode::Bulk {
                action: bulk_action_template,
                ..
            } => bulk_action_template
                .render_string(event)
                .map_err(|error| {
                    emit!(TemplateRenderingError {
                        error,
                        field: Some("bulk_action"),
                        drop_event: true,
                    });
                })
                .ok()
                .and_then(|value| BulkAction::try_from(value.as_str()).ok()),
            // avoid the interpolation
            ElasticsearchCommonMode::DataStream(_) => Some(BulkAction::Create),
        }
    }

    fn version<'a>(&self, event: impl Into<EventRef<'a>>) -> Option<u64> {
        match self {
            ElasticsearchCommonMode::Bulk {
                version: Some(version),
                ..
            } => version
                .render_string(event)
                .map_err(|error| {
                    emit!(TemplateRenderingError {
                        error,
                        field: Some("version"),
                        drop_event: true,
                    });
                })
                .ok()
                .as_ref()
                .and_then(|value| {
                    value
                        .parse()
                        .map_err(|_| emit!(VersionValueParseError { value }))
                        .ok()
                }),
            _ => None,
        }
    }

    const fn version_type(&self) -> Option<VersionType> {
        match self {
            ElasticsearchCommonMode::Bulk { version_type, .. } => Some(*version_type),
            _ => Some(VersionType::Internal),
        }
    }

    const fn as_data_stream_config(&self) -> Option<&DataStreamConfig> {
        match self {
            Self::DataStream(value) => Some(value),
            _ => None,
        }
    }
}

/// Configuration for Elasticsearch API version.
#[configurable_component]
#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "proptest", derive(proptest_derive::Arbitrary))]
#[serde(deny_unknown_fields, rename_all = "snake_case")]
pub enum ElasticsearchApiVersion {
    /// Auto-detect the API version.
    ///
    /// If the [cluster state version endpoint][es_version] isn't reachable, a warning is logged to
    /// stdout, and the version is assumed to be V6 if the `suppress_type_name` option is set to
    /// `true`. Otherwise, the version is assumed to be V8. In the future, the sink instead
    /// returns an error during configuration parsing, since a wrongly assumed version could lead to
    /// incorrect API calls.
    ///
    /// [es_version]: https://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-state.html#cluster-state-api-path-params
    Auto,
    /// Use the Elasticsearch 6.x API.
    V6,
    /// Use the Elasticsearch 7.x API.
    V7,
    /// Use the Elasticsearch 8.x API.
    V8,
}

impl Default for ElasticsearchApiVersion {
    fn default() -> Self {
        Self::Auto
    }
}

#[derive(Debug, Snafu)]
#[snafu(visibility(pub))]
pub enum ParseError {
    #[snafu(display("Invalid host {:?}: {:?}", host, source))]
    InvalidHost { host: String, source: InvalidUri },
    #[snafu(display("Host {:?} must include hostname", host))]
    HostMustIncludeHostname { host: String },
    #[snafu(display("Index template parse error: {}", source))]
    IndexTemplate { source: TemplateParseError },
    #[snafu(display("Batch action template parse error: {}", source))]
    BatchActionTemplate { source: TemplateParseError },
    #[cfg(feature = "aws-core")]
    #[snafu(display("aws.region required when AWS authentication is in use"))]
    RegionRequired,
    #[snafu(display("Endpoints option must be specified"))]
    EndpointRequired,
    #[snafu(display(
        "`endpoint` and `endpoints` options are mutually exclusive. Please use `endpoints` option."
    ))]
    EndpointsExclusive,
    #[snafu(display("Tried to use external versioning without specifying the version itself"))]
    ExternalVersioningWithoutVersion,
    #[snafu(display("Cannot use external versioning without specifying a document ID"))]
    ExternalVersioningWithoutDocumentID,
    #[snafu(display("Your version field will be ignored because you use internal versioning"))]
    ExternalVersionIgnoredWithInternalVersioning,
    #[snafu(display("Amazon OpenSearch Serverless requires `api_version` value to be `auto`"))]
    ServerlessElasticsearchApiVersionMustBeAuto,
    #[snafu(display("Amazon OpenSearch Serverless requires `auth.strategy` value to be `aws`"))]
    OpenSearchServerlessRequiresAwsAuth,
}