Skip to main content

servers/
elasticsearch.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::BTreeMap;
16use std::sync::Arc;
17use std::time::Instant;
18
19use axum::Extension;
20use axum::extract::{Path, Query, State};
21use axum::http::{HeaderMap, HeaderName, HeaderValue, StatusCode};
22use axum::response::IntoResponse;
23use axum_extra::TypedHeader;
24use common_error::ext::ErrorExt;
25use common_telemetry::{debug, error};
26use headers::ContentType;
27use once_cell::sync::Lazy;
28use pipeline::util::to_pipeline_version;
29use pipeline::{
30    GREPTIME_INTERNAL_IDENTITY_PIPELINE_NAME, GreptimePipelineParams, PipelineDefinition,
31};
32use serde_json::{Deserializer, Value, json};
33use session::context::{Channel, QueryContext};
34use snafu::{ResultExt, ensure};
35use table::requests::{
36    SEMANTIC_SIGNAL_TYPE, SEMANTIC_SOURCE, SIGNAL_TYPE_LOG, SOURCE_ELASTICSEARCH,
37};
38use vrl::value::Value as VrlValue;
39
40use crate::error::{
41    InvalidElasticsearchInputSnafu, ParseJsonSnafu, Result as ServersResult,
42    status_code_to_http_status,
43};
44use crate::http::event::{
45    LogIngesterQueryParams, LogState, PipelineIngestRequest,
46    extract_pipeline_params_map_from_headers, ingest_logs_inner,
47};
48use crate::http::extractor::string_value_from_header;
49use crate::http::header::constants::{
50    GREPTIME_PIPELINE_NAME_HEADER_NAME, GREPTIME_PIPELINE_VERSION_HEADER_NAME,
51};
52use crate::metrics::{
53    METRIC_ELASTICSEARCH_LOGS_DOCS_COUNT, METRIC_ELASTICSEARCH_LOGS_INGESTION_ELAPSED,
54};
55
56// The headers for every response of Elasticsearch API.
57static ELASTICSEARCH_HEADERS: Lazy<HeaderMap> = Lazy::new(|| {
58    HeaderMap::from_iter([
59        (
60            axum::http::header::CONTENT_TYPE,
61            HeaderValue::from_static("application/json"),
62        ),
63        (
64            HeaderName::from_static("x-elastic-product"),
65            HeaderValue::from_static("Elasticsearch"),
66        ),
67    ])
68});
69
70// The fake version of Elasticsearch and used for `_version` API.
71const ELASTICSEARCH_VERSION: &str = "8.16.0";
72
73// Return fake response for Elasticsearch ping request.
74#[axum_macros::debug_handler]
75pub async fn handle_get_version() -> impl IntoResponse {
76    let body = serde_json::json!({
77        "version": {
78            "number": ELASTICSEARCH_VERSION
79        }
80    });
81    (StatusCode::OK, elasticsearch_headers(), axum::Json(body))
82}
83
84// Return fake response for Elasticsearch license request.
85// Reference: https://www.elastic.co/guide/en/elasticsearch/reference/current/get-license.html.
86#[axum_macros::debug_handler]
87pub async fn handle_get_license() -> impl IntoResponse {
88    let body = serde_json::json!({
89        "license": {
90            "uid": "cbff45e7-c553-41f7-ae4f-9205eabd80xx",
91            "type": "oss",
92            "status": "active",
93            "expiry_date_in_millis": 4891198687000_i64,
94        }
95    });
96    (StatusCode::OK, elasticsearch_headers(), axum::Json(body))
97}
98
99/// Process `_bulk` API requests. Only support to create logs.
100/// Reference: https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html#docs-bulk-api-request.
101#[axum_macros::debug_handler]
102pub async fn handle_bulk_api(
103    State(log_state): State<LogState>,
104    Query(params): Query<LogIngesterQueryParams>,
105    Extension(query_ctx): Extension<QueryContext>,
106    TypedHeader(_content_type): TypedHeader<ContentType>,
107    headers: HeaderMap,
108    payload: String,
109) -> impl IntoResponse {
110    do_handle_bulk_api(log_state, None, params, query_ctx, headers, payload).await
111}
112
113/// Process `/${index}/_bulk` API requests. Only support to create logs.
114/// Reference: https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html#docs-bulk-api-request.
115#[axum_macros::debug_handler]
116pub async fn handle_bulk_api_with_index(
117    State(log_state): State<LogState>,
118    Path(index): Path<String>,
119    Query(params): Query<LogIngesterQueryParams>,
120    Extension(query_ctx): Extension<QueryContext>,
121    TypedHeader(_content_type): TypedHeader<ContentType>,
122    headers: HeaderMap,
123    payload: String,
124) -> impl IntoResponse {
125    do_handle_bulk_api(log_state, Some(index), params, query_ctx, headers, payload).await
126}
127
128async fn do_handle_bulk_api(
129    log_state: LogState,
130    index: Option<String>,
131    params: LogIngesterQueryParams,
132    mut query_ctx: QueryContext,
133    headers: HeaderMap,
134    payload: String,
135) -> impl IntoResponse {
136    let start = Instant::now();
137    debug!(
138        "Received bulk request, params: {:?}, payload: {:?}",
139        params, payload
140    );
141
142    // The `schema` is already set in the query_ctx in auth process.
143    query_ctx.set_channel(Channel::Elasticsearch);
144    query_ctx.set_extension(SEMANTIC_SIGNAL_TYPE, SIGNAL_TYPE_LOG);
145    query_ctx.set_extension(SEMANTIC_SOURCE, SOURCE_ELASTICSEARCH);
146
147    let db = query_ctx.current_schema();
148
149    // Record the ingestion time histogram.
150    let _timer = METRIC_ELASTICSEARCH_LOGS_INGESTION_ELAPSED
151        .with_label_values(&[&db])
152        .start_timer();
153
154    // If pipeline_name is not provided, use the internal pipeline.
155    let pipeline_name = params.pipeline_name.as_deref().unwrap_or_else(|| {
156        headers
157            .get(GREPTIME_PIPELINE_NAME_HEADER_NAME)
158            .and_then(|v| v.to_str().ok())
159            .unwrap_or(GREPTIME_INTERNAL_IDENTITY_PIPELINE_NAME)
160    });
161
162    // The pipeline version can be selected with the `version` query parameter or the
163    // `x-greptime-pipeline-version` header; the query parameter takes precedence, consistent
164    // with how `pipeline_name` is resolved above. Without either, the latest version is used.
165    // Read the header through the shared extractor so a present but non-UTF-8 value is
166    // rejected with 400 instead of silently falling back to the latest pipeline.
167    let header_version = if params.version.is_none() {
168        match string_value_from_header(&headers, &[GREPTIME_PIPELINE_VERSION_HEADER_NAME]) {
169            Ok(version) => version,
170            Err((status, reason)) => {
171                return (
172                    status,
173                    elasticsearch_headers(),
174                    axum::Json(write_bulk_response(
175                        start.elapsed().as_millis() as i64,
176                        0,
177                        status.as_u16() as u32,
178                        reason.as_str(),
179                    )),
180                );
181            }
182        }
183    } else {
184        None
185    };
186    let pipeline_version = params.version.as_deref().or(header_version.as_deref());
187
188    // Read the ndjson payload and convert it to a vector of Value.
189    let requests = match parse_bulk_request(&payload, &index, &params.msg_field) {
190        Ok(requests) => requests,
191        Err(e) => {
192            return (
193                StatusCode::BAD_REQUEST,
194                elasticsearch_headers(),
195                axum::Json(write_bulk_response(
196                    start.elapsed().as_millis() as i64,
197                    0,
198                    StatusCode::BAD_REQUEST.as_u16() as u32,
199                    e.to_string().as_str(),
200                )),
201            );
202        }
203    };
204    let log_num = requests.len();
205
206    let pipeline_result = to_pipeline_version(pipeline_version)
207        .and_then(|version| PipelineDefinition::from_name(pipeline_name, version, None));
208    let pipeline = match pipeline_result {
209        Ok(pipeline) => pipeline,
210        Err(e) => {
211            error!(e; "Failed to ingest logs");
212            // Elasticsearch clients inspect `items[].create.status`, so report the
213            // HTTP status rather than GreptimeDB's internal status code.
214            let http_status = status_code_to_http_status(&e.status_code());
215            return (
216                http_status,
217                elasticsearch_headers(),
218                axum::Json(write_bulk_response(
219                    start.elapsed().as_millis() as i64,
220                    0,
221                    http_status.as_u16() as u32,
222                    e.to_string().as_str(),
223                )),
224            );
225        }
226    };
227    let pipeline_params =
228        GreptimePipelineParams::from_map(extract_pipeline_params_map_from_headers(&headers));
229    if let Err(e) = ingest_logs_inner(
230        log_state.log_handler,
231        pipeline,
232        requests,
233        Arc::new(query_ctx),
234        pipeline_params,
235    )
236    .await
237    {
238        error!(e; "Failed to ingest logs");
239        let http_status = status_code_to_http_status(&e.status_code());
240        return (
241            http_status,
242            elasticsearch_headers(),
243            axum::Json(write_bulk_response(
244                start.elapsed().as_millis() as i64,
245                0,
246                http_status.as_u16() as u32,
247                e.to_string().as_str(),
248            )),
249        );
250    }
251
252    // Record the number of documents ingested.
253    METRIC_ELASTICSEARCH_LOGS_DOCS_COUNT
254        .with_label_values(&[&db])
255        .inc_by(log_num as u64);
256
257    (
258        StatusCode::OK,
259        elasticsearch_headers(),
260        axum::Json(write_bulk_response(
261            start.elapsed().as_millis() as i64,
262            log_num,
263            StatusCode::CREATED.as_u16() as u32,
264            "",
265        )),
266    )
267}
268
269// It will generate the following response when write _bulk request to GreptimeDB successfully:
270// {
271//     "took": 1000,
272//     "errors": false,
273//     "items": [
274//         { "create": { "status": 201 } },
275//         { "create": { "status": 201 } },
276//         ...
277//     ]
278// }
279// If the status code is not 201, it will generate the following response:
280// {
281//     "took": 1000,
282//     "errors": true,
283//     "items": [
284//         { "create": { "status": 400, "error": { "type": "illegal_argument_exception", "reason": "<error_reason>" } } }
285//     ]
286// }
287fn write_bulk_response(took_ms: i64, n: usize, status_code: u32, error_reason: &str) -> Value {
288    if error_reason.is_empty() {
289        let items: Vec<Value> = (0..n)
290            .map(|_| {
291                json!({
292                    "create": {
293                        "status": status_code
294                    }
295                })
296            })
297            .collect();
298        let mut response = json!({
299            "took": took_ms,
300            "errors": false,
301        });
302        response["items"] = Value::Array(items);
303        response
304    } else {
305        json!({
306            "took": took_ms,
307            "errors": true,
308            "items": [
309                { "create": { "status": status_code, "error": { "type": "illegal_argument_exception", "reason": error_reason } } }
310            ]
311        })
312    }
313}
314
315/// Returns the headers for every response of Elasticsearch API.
316pub fn elasticsearch_headers() -> HeaderMap {
317    ELASTICSEARCH_HEADERS.clone()
318}
319
320// Parse the Elasticsearch bulk request and convert it to multiple LogIngestRequests.
321// The input will be Elasticsearch bulk request in NDJSON format.
322// For example, the input will be like this:
323// { "index" : { "_index" : "test", "_id" : "1" } }
324// { "field1" : "value1" }
325// { "index" : { "_index" : "test", "_id" : "2" } }
326// { "field2" : "value2" }
327fn parse_bulk_request(
328    input: &str,
329    index_from_url: &Option<String>,
330    msg_field: &Option<String>,
331) -> ServersResult<Vec<PipelineIngestRequest>> {
332    // Read the ndjson payload and convert it to `Vec<Value>`. Return error if the input is not a valid JSON.
333    let values: Vec<VrlValue> = Deserializer::from_str(input)
334        .into_iter::<VrlValue>()
335        .collect::<Result<_, _>>()
336        .context(ParseJsonSnafu)?;
337
338    // Check if the input is empty.
339    ensure!(
340        !values.is_empty(),
341        InvalidElasticsearchInputSnafu {
342            reason: "empty bulk request".to_string(),
343        }
344    );
345
346    let mut requests: Vec<PipelineIngestRequest> = Vec::with_capacity(values.len() / 2);
347    let mut values = values.into_iter();
348
349    // Read the ndjson payload and convert it to a (index, value) vector.
350    // For Elasticsearch post `_bulk` API, each chunk contains two objects:
351    //   1. The first object is the command, it should be `create` or `index`.
352    //   2. The second object is the document data.
353    while let Some(cmd) = values.next() {
354        // NOTE: Although the native Elasticsearch API supports upsert in `index` command, we don't support change any data in `index` command and it's same as `create` command.
355        let mut cmd = cmd.into_object();
356        let index = if let Some(cmd) = cmd.as_mut().and_then(|c| c.remove("create")) {
357            get_index_from_cmd(cmd)?
358        } else if let Some(cmd) = cmd.as_mut().and_then(|c| c.remove("index")) {
359            get_index_from_cmd(cmd)?
360        } else {
361            return InvalidElasticsearchInputSnafu {
362                reason: format!(
363                    "invalid bulk request, expected 'create' or 'index' but got {:?}",
364                    cmd
365                ),
366            }
367            .fail();
368        };
369
370        // Read the second object to get the document data. Stop the loop if there is no document.
371        if let Some(document) = values.next() {
372            // If the msg_field is provided, fetch the value of the field from the document data.
373            let log_value = if let Some(msg_field) = msg_field {
374                get_log_value_from_msg_field(document, msg_field)
375            } else {
376                document
377            };
378
379            ensure!(
380                index.is_some() || index_from_url.is_some(),
381                InvalidElasticsearchInputSnafu {
382                    reason: "missing index in bulk request".to_string(),
383                }
384            );
385
386            requests.push(PipelineIngestRequest {
387                table: index.unwrap_or_else(|| index_from_url.as_ref().unwrap().clone()),
388                values: vec![log_value],
389            });
390        }
391    }
392
393    debug!(
394        "Received {} log ingest requests: {:?}",
395        requests.len(),
396        requests
397    );
398
399    Ok(requests)
400}
401
402// Get the index from the command. We will take index as the table name in GreptimeDB.
403fn get_index_from_cmd(v: VrlValue) -> ServersResult<Option<String>> {
404    let Some(index) = v.into_object().and_then(|mut m| m.remove("_index")) else {
405        return Ok(None);
406    };
407
408    if let VrlValue::Bytes(index) = index {
409        Ok(Some(String::from_utf8_lossy(&index).to_string()))
410    } else {
411        // If the `_index` exists, it should be a string.
412        InvalidElasticsearchInputSnafu {
413            reason: "index is not a string in bulk request",
414        }
415        .fail()
416    }
417}
418
419// If the msg_field is provided, fetch the value of the field from the document data.
420// For example, if the `msg_field` is `message`, and the document data is `{"message":"hello"}`, the log value will be Value::String("hello").
421fn get_log_value_from_msg_field(v: VrlValue, msg_field: &str) -> VrlValue {
422    let VrlValue::Object(mut m) = v else {
423        return v;
424    };
425
426    if let Some(message) = m.remove(msg_field) {
427        match message {
428            VrlValue::Bytes(bytes) => {
429                match serde_json::from_slice::<VrlValue>(&bytes) {
430                    Ok(v) => v,
431                    // If the message is not a valid JSON, return a map with the original message key and value.
432                    Err(_) => {
433                        let map = BTreeMap::from([(
434                            msg_field.to_string().into(),
435                            VrlValue::Bytes(bytes),
436                        )]);
437                        VrlValue::Object(map)
438                    }
439                }
440            }
441            // If the message is not a string, just use the original message as the log value.
442            _ => message,
443        }
444    } else {
445        // If the msg_field is not found, just use the original message as the log value.
446        VrlValue::Object(m)
447    }
448}
449
450#[cfg(test)]
451mod tests {
452    use super::*;
453
454    #[test]
455    fn test_parse_bulk_request() {
456        let test_cases = vec![
457            // Normal case.
458            (
459                r#"
460                {"create":{"_index":"test","_id":"1"}}
461                {"foo1":"foo1_value", "bar1":"bar1_value"}
462                {"create":{"_index":"test","_id":"2"}}
463                {"foo2":"foo2_value","bar2":"bar2_value"}
464                "#,
465                None,
466                None,
467                Ok(vec![
468                    PipelineIngestRequest {
469                        table: "test".to_string(),
470                        values: vec![
471                            json!({"foo1": "foo1_value", "bar1": "bar1_value"}).into(),
472                        ],
473                    },
474                    PipelineIngestRequest {
475                        table: "test".to_string(),
476                        values: vec![
477                            json!({"foo2": "foo2_value", "bar2": "bar2_value"}).into(),
478                        ],
479                    },
480                ]),
481            ),
482            // Case with index.
483            (
484                r#"
485                {"create":{"_index":"test","_id":"1"}}
486                {"foo1":"foo1_value", "bar1":"bar1_value"}
487                {"create":{"_index":"logs","_id":"2"}}
488                {"foo2":"foo2_value","bar2":"bar2_value"}
489                "#,
490                Some("logs".to_string()),
491                None,
492                Ok(vec![
493                    PipelineIngestRequest {
494                        table: "test".to_string(),
495                        values: vec![
496                            json!({"foo1": "foo1_value", "bar1": "bar1_value"}).into(),
497                        ],
498                    },
499                    PipelineIngestRequest {
500                        table: "logs".to_string(),
501                        values: vec![
502                            json!({"foo2": "foo2_value", "bar2": "bar2_value"}).into(),
503                        ],
504                    },
505                ]),
506            ),
507            // Case with index.
508            (
509                r#"
510                {"create":{"_index":"test","_id":"1"}}
511                {"foo1":"foo1_value", "bar1":"bar1_value"}
512                {"create":{"_index":"logs","_id":"2"}}
513                {"foo2":"foo2_value","bar2":"bar2_value"}
514                "#,
515                Some("logs".to_string()),
516                None,
517                Ok(vec![
518                    PipelineIngestRequest {
519                        table: "test".to_string(),
520                        values: vec![
521                            json!({"foo1": "foo1_value", "bar1": "bar1_value"}).into(),
522                        ],
523                    },
524                    PipelineIngestRequest {
525                        table: "logs".to_string(),
526                        values: vec![
527                            json!({"foo2": "foo2_value", "bar2": "bar2_value"}).into(),
528                        ],
529                    },
530                ]),
531            ),
532            // Case with incomplete bulk request.
533            (
534                r#"
535                {"create":{"_index":"test","_id":"1"}}
536                {"foo1":"foo1_value", "bar1":"bar1_value"}
537                {"create":{"_index":"logs","_id":"2"}}
538                "#,
539                Some("logs".to_string()),
540                None,
541                Ok(vec![
542                    PipelineIngestRequest {
543                        table: "test".to_string(),
544                        values: vec![
545                            json!({"foo1": "foo1_value", "bar1": "bar1_value"}).into(),
546                        ],
547                    },
548                ]),
549            ),
550            // Specify the `data` field as the message field and the value is a JSON string.
551            (
552                r#"
553                {"create":{"_index":"test","_id":"1"}}
554                {"data":"{\"foo1\":\"foo1_value\", \"bar1\":\"bar1_value\"}", "not_data":"not_data_value"}
555                {"create":{"_index":"test","_id":"2"}}
556                {"data":"{\"foo2\":\"foo2_value\", \"bar2\":\"bar2_value\"}", "not_data":"not_data_value"}
557                "#,
558                None,
559                Some("data".to_string()),
560                Ok(vec![
561                    PipelineIngestRequest {
562                        table: "test".to_string(),
563                        values: vec![
564                            json!({"foo1": "foo1_value", "bar1": "bar1_value"}).into(),
565                        ],
566                    },
567                    PipelineIngestRequest {
568                        table: "test".to_string(),
569                        values: vec![
570                            json!({"foo2": "foo2_value", "bar2": "bar2_value"}).into(),
571                        ],
572                    },
573                ]),
574            ),
575            // Simulate the log data from Logstash.
576            (
577                r#"
578                {"create":{"_id":null,"_index":"logs-generic-default","routing":null}}
579                {"message":"172.16.0.1 - - [25/May/2024:20:19:37 +0000] \"GET /contact HTTP/1.1\" 404 162 \"-\" \"Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1\"","@timestamp":"2025-01-04T04:32:13.868962186Z","event":{"original":"172.16.0.1 - - [25/May/2024:20:19:37 +0000] \"GET /contact HTTP/1.1\" 404 162 \"-\" \"Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1\""},"host":{"name":"orbstack"},"log":{"file":{"path":"/var/log/nginx/access.log"}},"@version":"1","data_stream":{"type":"logs","dataset":"generic","namespace":"default"}}
580                {"create":{"_id":null,"_index":"logs-generic-default","routing":null}}
581                {"message":"10.0.0.1 - - [25/May/2024:20:18:37 +0000] \"GET /images/logo.png HTTP/1.1\" 304 0 \"-\" \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0\"","@timestamp":"2025-01-04T04:32:13.868723810Z","event":{"original":"10.0.0.1 - - [25/May/2024:20:18:37 +0000] \"GET /images/logo.png HTTP/1.1\" 304 0 \"-\" \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0\""},"host":{"name":"orbstack"},"log":{"file":{"path":"/var/log/nginx/access.log"}},"@version":"1","data_stream":{"type":"logs","dataset":"generic","namespace":"default"}}
582                "#,
583                None,
584                Some("message".to_string()),
585                Ok(vec![
586                    PipelineIngestRequest {
587                        table: "logs-generic-default".to_string(),
588                        values: vec![
589                            json!({"message": "172.16.0.1 - - [25/May/2024:20:19:37 +0000] \"GET /contact HTTP/1.1\" 404 162 \"-\" \"Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1\""}).into(),
590                        ],
591                    },
592                    PipelineIngestRequest {
593                        table: "logs-generic-default".to_string(),
594                        values: vec![
595                            json!({"message": "10.0.0.1 - - [25/May/2024:20:18:37 +0000] \"GET /images/logo.png HTTP/1.1\" 304 0 \"-\" \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0\""}).into(),
596                        ],
597                    },
598                ]),
599            ),
600            // With invalid bulk request.
601            (
602                r#"
603                { "not_create_or_index" : { "_index" : "test", "_id" : "1" } }
604                { "foo1" : "foo1_value", "bar1" : "bar1_value" }
605                "#,
606                None,
607                None,
608                Err(InvalidElasticsearchInputSnafu {
609                    reason: "it's a invalid bulk request".to_string(),
610                }),
611            ),
612        ];
613
614        for (input, index, msg_field, expected) in test_cases {
615            let requests = parse_bulk_request(input, &index, &msg_field);
616            if let Ok(expected) = expected {
617                assert_eq!(requests.unwrap(), expected);
618            } else {
619                assert!(requests.is_err());
620            }
621        }
622    }
623}