1use 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
56static 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
70const ELASTICSEARCH_VERSION: &str = "8.16.0";
72
73#[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#[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#[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#[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 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 let _timer = METRIC_ELASTICSEARCH_LOGS_INGESTION_ELAPSED
151 .with_label_values(&[&db])
152 .start_timer();
153
154 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 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 let requests = match parse_bulk_request(&payload, &index, ¶ms.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 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 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
269fn 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
315pub fn elasticsearch_headers() -> HeaderMap {
317 ELASTICSEARCH_HEADERS.clone()
318}
319
320fn parse_bulk_request(
328 input: &str,
329 index_from_url: &Option<String>,
330 msg_field: &Option<String>,
331) -> ServersResult<Vec<PipelineIngestRequest>> {
332 let values: Vec<VrlValue> = Deserializer::from_str(input)
334 .into_iter::<VrlValue>()
335 .collect::<Result<_, _>>()
336 .context(ParseJsonSnafu)?;
337
338 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 while let Some(cmd) = values.next() {
354 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 if let Some(document) = values.next() {
372 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
402fn 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 InvalidElasticsearchInputSnafu {
413 reason: "index is not a string in bulk request",
414 }
415 .fail()
416 }
417}
418
419fn 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 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 _ => message,
443 }
444 } else {
445 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 (
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 (
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 (
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 (
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 (
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 (
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 (
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}