opensearch-client 0.3.1

Strongly typed OpenSearch Client
Documentation
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
use std::{
    collections::HashMap,
    fs::{self},
    path::PathBuf,
    sync::Arc,
};

use futures::{pin_mut, StreamExt};
use opensearch_dsl::{FieldSort, Query, SortCollection};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tracing::info;
use walkdir::WalkDir;

use crate::{
    indices::{GetIndexTemplateResponse, IndexTemplateMapping},
    OsClient,
};

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct Header {
    #[serde(rename = "_index")]
    pub index: String,
    #[serde(rename = "_id")]
    pub id: String,
}

const PIPELINE_DIRECTORY: &str = "pipelines";
const TEMPLATE_DIRECTORY: &str = "templates";
const COMPONENT_DIRECTORY: &str = "components";

/// Tools is a struct that contains all the methods to dump and restore cluster
/// data
pub struct Tools {
    client: Arc<OsClient>,
}

impl Tools {
    pub fn new(client: Arc<OsClient>) -> Self {
        Self { client }
    }

    /// Asynchronously dumps the pipelines to the specified output path.
    ///
    /// # Arguments
    /// * `output` - The path to the output file.
    ///
    /// # Returns
    /// Returns `Ok(())` if the operation was successful, otherwise returns an
    /// `anyhow::Error`.
    pub async fn dump_pipelines(&self, output: PathBuf) -> anyhow::Result<()> {
        let pipelines = self.client.ingest().get_pipelines().call().await?;
        let pipeline_path = output.join(PIPELINE_DIRECTORY);
        save_named_map(&pipeline_path, pipelines).await?;
        Ok(())
    }

    /// Asynchronously dumps the index templates to the specified output path.
    ///
    /// # Arguments
    /// * `output` - The path to the output file.
    ///
    /// # Returns
    /// Returns `Ok(())` if the operation was successful, otherwise returns an
    /// `anyhow::Error`.
    pub async fn dump_index_templates(&self, output: PathBuf) -> anyhow::Result<()> {
        let data = self.client.indices().get_index_templates().call().await?;
        let data_path = output.join(TEMPLATE_DIRECTORY);
        let data = data
            .into_iter()
            .map(|(name, template)| {
                (
                    name,
                    serde_json::to_value(template).expect("Failed to serialize template"),
                )
            })
            .collect::<HashMap<String, Value>>();
        save_named_map(&data_path, data).await?;
        Ok(())
    }

    /// Asynchronously dumps the index components to the specified output path.
    ///
    /// # Arguments
    /// * `output` - The path to the output file.
    ///
    /// # Returns
    /// Returns `Ok(())` if the operation was successful, otherwise returns an
    /// `anyhow::Error`.
    pub async fn dump_index_components(&self, output: PathBuf) -> anyhow::Result<()> {
        let data = self
            .client
            .indices()
            .get_component_templates()
            .call()
            .await?;
        let data_path = output.join(COMPONENT_DIRECTORY);
        save_named_map(&data_path, data).await?;
        Ok(())
    }

    /// Asynchronously restores the pipelines from the specified path.
    ///
    /// # Arguments
    /// * `input_path` - The path to be used as source for the files.
    ///
    /// # Returns
    /// Returns `Ok(())` if the operation was successful, otherwise returns an
    /// `anyhow::Error`.
    pub async fn restore_pipelines(&self, input: PathBuf) -> anyhow::Result<()> {
        let files = get_json_file_recursive(&input.join(PIPELINE_DIRECTORY))?;
        let current_pipelines = self.client.ingest().get_pipelines().call().await?;
        for entry in files {
            let name = entry
                .file_name()
                .unwrap_or_default()
                .to_str()
                .unwrap()
                .replace(".json", "");
            let pipeline = fs::read_to_string(entry)?;
            let pipeline: serde_json::Value = serde_json::from_str(&pipeline)?;
            self.update_pipeline_if_required(&name, pipeline, current_pipelines.clone())
                .await?;
        }
        Ok(())
    }

    pub async fn update_pipeline_if_required(
        &self,
        name: &String,
        body: serde_json::Value,
        current_pipelines: HashMap<String, Value>,
    ) -> anyhow::Result<()> {
        if current_pipelines.contains_key(name) {
            let old_pipeline = current_pipelines.get(name).unwrap();
            let version = old_pipeline["version"].as_u64().unwrap_or(0);
            let new_version = body["version"].as_u64().unwrap_or(0);
            if version >= new_version {
                info!("Pipeline {} is up to date", name);
                return Ok(());
            }
        }
        self.client
            .ingest()
            .put_pipeline_raw()
            .id(name)
            .body(body)
            .call()
            .await?;
        info!("Pipeline {} updated", name);
        Ok(())
    }

    /// Asynchronously restores the index templates from the specified path.
    ///
    /// # Arguments
    /// * `input_path` - The path to be used as source for the files.
    ///
    /// # Returns
    /// Returns `Ok(())` if the operation was successful, otherwise returns an
    /// `anyhow::Error`.
    pub async fn restore_index_templates(&self, input: PathBuf) -> anyhow::Result<()> {
        let files = get_json_file_recursive(&input.join(TEMPLATE_DIRECTORY))?;
        let current_templates = self.client.indices().get_index_templates().call().await?;
        for entry in files {
            let name = entry
                .file_name()
                .unwrap_or_default()
                .to_str()
                .unwrap()
                .replace(".json", "");
            let body = fs::read_to_string(entry)?;
            let body: serde_json::Value = serde_json::from_str(&body)?;
            let current_templates = current_templates
                .clone()
                .into_iter()
                .map(|(name, template)| {
                    (
                        name,
                        serde_json::to_value(template).expect("Failed to serialize template"),
                    )
                })
                .collect::<HashMap<String, Value>>();
            self.update_template_if_required(&name, body, current_templates)
                .await?;
        }
        Ok(())
    }

    pub async fn update_template_if_required(
        &self,
        name: &String,
        body: serde_json::Value,
        current_templates: HashMap<String, Value>,
    ) -> anyhow::Result<()> {
        if current_templates.contains_key(name) {
            let old_template = current_templates.get(name).unwrap();
            let version = old_template["version"].as_u64().unwrap_or(0);
            let new_version = body["version"].as_u64().unwrap_or(0);
            if version >= new_version {
                info!("Index Template {} is up to date", name);
                return Ok(());
            }
        }
        self.client
            .indices()
            .put_template_raw()
            .name(name)
            .body(body)
            .call()
            .await?;
        info!("Index Template {} updated", name);
        Ok(())
    }

    /// Asynchronously restores the index components from the specified path.
    ///
    /// # Arguments
    /// * `input_path` - The path to be used as source for the files.
    ///
    /// # Returns
    /// Returns `Ok(())` if the operation was successful, otherwise returns an
    /// `anyhow::Error`.
    pub async fn restore_index_components(&self, input: PathBuf) -> anyhow::Result<()> {
        let files = get_json_file_recursive(&input.join(COMPONENT_DIRECTORY))?;
        let current_components = self
            .client
            .indices()
            .get_component_templates()
            .call()
            .await?;
        for entry in files {
            let name = entry
                .file_name()
                .unwrap_or_default()
                .to_str()
                .unwrap()
                .replace(".json", "");
            let body = fs::read_to_string(entry)?;
            let body: serde_json::Value = serde_json::from_str(&body)?;
            self.update_component_if_required(&name, body, current_components.clone())
                .await?;
        }
        Ok(())
    }

    pub async fn update_component_if_required(
        &self,
        name: &String,
        body: serde_json::Value,
        current_templates: HashMap<String, Value>,
    ) -> anyhow::Result<()> {
        if current_templates.contains_key(name) {
            let old_template = current_templates.get(name).unwrap();
            let version = old_template["version"].as_u64().unwrap_or(0);
            let new_version = body["version"].as_u64().unwrap_or(0);
            if version >= new_version {
                info!("Index Component {} is up to date", name);
                return Ok(());
            }
        }
        self.client
            .indices()
            .put_component_template_raw()
            .name(name)
            .body(body)
            .call()
            .await?;
        info!("Index Component {} updated", name);
        Ok(())
    }

    /// Asynchronously fixes the pipelines from the specified path adding version
    /// if missing.
    pub async fn fix_pipelines(&self, input: PathBuf) -> anyhow::Result<()> {
        let files = get_json_file_recursive(&input.join(PIPELINE_DIRECTORY))?;
        for file in files {
            let body = fs::read_to_string(&file)?;
            let mut body: serde_json::Map<String, Value> = serde_json::from_str(&body)?;
            if !body.contains_key("version") {
                body.insert("version".to_string(), serde_json::Value::from(1));
                write_json_to_file(&file, &serde_json::Value::from(body)).await?;
            }
        }
        Ok(())
    }

    /// Asynchronously fixes the index templates from the specified path adding
    /// version if missing.
    pub async fn fix_index_templates(&self, input: PathBuf) -> anyhow::Result<()> {
        let files = get_json_file_recursive(&input.join(TEMPLATE_DIRECTORY))?;
        for file in files {
            let body = fs::read_to_string(&file)?;
            let mut body: serde_json::Map<String, Value> = serde_json::from_str(&body)?;
            if !body.contains_key("version") {
                body.insert("version".to_string(), serde_json::Value::from(1));
                write_json_to_file(&file, &serde_json::Value::from(body)).await?;
            }
        }
        Ok(())
    }

    /// Asynchronously fixes the index components from the specified path adding
    /// version if missing.
    pub async fn fix_components(&self, input: PathBuf) -> anyhow::Result<()> {
        let files = get_json_file_recursive(&input.join(COMPONENT_DIRECTORY))?;
        for file in files {
            let body = fs::read_to_string(&file)?;
            let mut body: serde_json::Map<String, Value> = serde_json::from_str(&body)?;
            if !body.contains_key("version") {
                body.insert("version".to_string(), serde_json::Value::from(1));
                write_json_to_file(&file, &serde_json::Value::from(body)).await?;
            }
        }
        Ok(())
    }
}

pub async fn write_json_to_file(path: &PathBuf, json_value: &Value) -> anyhow::Result<()> {
    let json_string = serde_json::to_string_pretty(json_value)?;
    if path.exists() {
        let old_data = fs::read_to_string(path)?;
        if old_data == json_string {
            info!("File {} already exists and is up to date", path.display());
            return Ok(());
        }
    }

    fs::write(path, json_string)?;
    info!("Wrote file: {}", path.display());
    Ok(())
}

pub async fn save_named_map(
    path: &PathBuf,
    data: HashMap<String, serde_json::Value>,
) -> anyhow::Result<()> {
    // we create the dir in not exists
    fs::create_dir_all(path).unwrap_or_else(|error| {
        eprintln!("Failed to create directory: {}", error);
    });
    // we iterate over the pipelines and dump them
    for (name, value) in data.iter() {
        let value_file = path.join(format!("{}.json", name));
        let value = serde_json::to_value(value)?;
        write_json_to_file(&value_file, &value).await?;
    }
    Ok(())
}

fn get_json_file_recursive(path: &PathBuf) -> anyhow::Result<Vec<PathBuf>> {
    if !path.exists() {
        return Ok(Vec::new());
    }
    let mut files = Vec::new();
    for entry in WalkDir::new(path) {
        let entry = entry?;
        if entry.path().is_file() {
            if entry.path().extension().unwrap_or_default() == "json" {
                files.push(entry.path().to_path_buf());
            }
        }
    }
    Ok(files)
}

#[bon::builder]
pub async fn copy_index_remotely(
    source_client: Arc<OsClient>,
    target_client: Arc<OsClient>,
    source_index: &str,
    target_index: Option<String>,
    #[builder(default = true)] copy_mappings: bool,
    #[builder(default = true)] delete_existing: bool,
    #[builder(default = 500)] size: u64,
) -> anyhow::Result<()> {
    let source_count = source_client
        .count()
        .index(source_index)
        .call()
        .await?
        .count;

    if source_count == 0 {
        info!("Source index {} is empty, nothing to copy", source_index);
        return Ok(());
    }
    let target_index = target_index.unwrap_or_else(|| source_index.to_string());
    let target_exists: bool = target_client
        .indices()
        .exists()
        .index(target_index.as_str())
        .call()
        .await?;

    if delete_existing && target_exists {
        target_client
            .indices()
            .delete()
            .index(target_index.as_str())
            .call()
            .await?;
        info!("Deleted existing index: {}", target_index);
    }

    if !target_exists {
        if copy_mappings {
            let index_data = source_client
                .indices()
                .get()
                .index(source_index)
                .call()
                .await?;
            if let Some(index_template) = index_data.get(source_index) {
                let mappings = index_template.mappings.clone();
                if !mappings.is_none() {
                    let new_template = IndexTemplateMapping {
                        mappings,
                        aliases: index_template.aliases.clone(),
                        ..Default::default()
                    };
                    info!("Copying mappings from source index: {}", source_index);
                    target_client
                        .indices()
                        .create()
                        .index(&target_index)
                        .body(new_template)
                        .call()
                        .await?;
                } else {
                    info!("No mappings to copy from source index: {}", source_index);
                }
            }
        }
    }

    let query = Query::match_all();
    let sort = SortCollection::new().field(FieldSort::ascending("_id"));

    let stream = source_client
        .search_stream::<serde_json::Value>(source_index, &query.into(), &sort, size)
        .await?;
    pin_mut!(stream);

    let mut total_count: u32 = 0;
    while let Some(hit) = stream.next().await {
        let body = hit.source.unwrap();
        target_client
            .bulk_index_document(&target_index, Some(hit.id.clone()), &body)
            .await?;
        total_count += 1;
        if total_count % 10000 == 0 {
            tracing::info!("Processed {}/{} documents", total_count, source_count);
        }
    }
    target_client.flush_bulk().await?;
    target_client
        .indices()
        .refresh()
        .index(target_index.as_str())
        .call()
        .await?;
    let target_count = target_client
        .count()
        .index(&target_index)
        .call()
        .await?
        .count;

    if total_count != target_count {
        let error = format!(
            "Mismatch in document count: source {} vs target {}",
            total_count, target_count
        );
        tracing::error!("{}", error);
        return Err(anyhow::anyhow!(
            "Mismatch in document count: source {} vs target {}",
            total_count,
            target_count
        ));
    }

    println!(
        "Written index {} with records {}",
        target_index, total_count
    );

    Ok(())
}