mz_debug/
utils.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
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 in the LICENSE file at the
6// root of this repository, or online at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use std::fs::{File, create_dir_all, remove_dir_all};
17use std::io::{BufWriter, copy};
18use std::path::PathBuf;
19use std::str::FromStr;
20
21use chrono::{DateTime, Utc};
22use zip::ZipWriter;
23use zip::write::SimpleFileOptions;
24
25/// Formats the base path for the output of the debug tool.
26pub fn format_base_path(date_time: DateTime<Utc>) -> PathBuf {
27    PathBuf::from(format!("mz_debug_{}", date_time.format("%Y-%m-%dT%H:%MZ")))
28}
29
30pub fn validate_pg_connection_string(connection_string: &str) -> Result<String, String> {
31    tokio_postgres::Config::from_str(connection_string)
32        .map(|_| connection_string.to_string())
33        .map_err(|e| format!("Invalid PostgreSQL connection string: {}", e))
34}
35
36pub fn create_tracing_log_file(date_time: DateTime<Utc>) -> Result<File, std::io::Error> {
37    let dir = format_base_path(date_time);
38    let log_file = dir.join("tracing.log");
39    if log_file.exists() {
40        remove_dir_all(&log_file)?;
41    }
42    create_dir_all(&dir)?;
43    let file = File::create(&log_file);
44    file
45}
46
47/// Zips a folder
48pub fn zip_debug_folder(zip_file_name: PathBuf, folder_path: &PathBuf) -> std::io::Result<()> {
49    // Delete the zip file if it already exists
50    if zip_file_name.exists() {
51        std::fs::remove_file(&zip_file_name)?;
52    }
53    let zip_file = File::create(&zip_file_name)?;
54    let mut zip_writer = ZipWriter::new(BufWriter::new(zip_file));
55
56    for entry in walkdir::WalkDir::new(folder_path) {
57        let entry = entry?;
58        let path = entry.path();
59
60        if path.is_file() {
61            zip_writer.start_file(path.to_string_lossy(), SimpleFileOptions::default())?;
62            let mut file = File::open(path)?;
63            copy(&mut file, &mut zip_writer)?;
64        }
65    }
66
67    zip_writer.finish()?;
68    Ok(())
69}