Skip to main content

rustfs_obs/cleaner/
types.rs

1// Copyright 2024 RustFS 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
15//! Shared types used across the log-cleanup sub-modules.
16//!
17//! These types deliberately stay lightweight because they are passed between
18//! the scanner, selector, compressor, and deletion stages. Keeping them small
19//! and explicit makes the cleaner easier to reason about and cheaper to move
20//! across worker threads in the parallel pipeline.
21
22use rustfs_config::observability::{
23    DEFAULT_OBS_LOG_COMPRESSION_ALGORITHM, DEFAULT_OBS_LOG_COMPRESSION_ALGORITHM_GZIP,
24    DEFAULT_OBS_LOG_COMPRESSION_ALGORITHM_ZSTD, DEFAULT_OBS_LOG_GZIP_COMPRESSION_ALL_EXTENSION,
25    DEFAULT_OBS_LOG_GZIP_COMPRESSION_EXTENSION, DEFAULT_OBS_LOG_MATCH_MODE, DEFAULT_OBS_LOG_MATCH_MODE_PREFIX,
26    DEFAULT_OBS_LOG_ZSTD_COMPRESSION_ALL_EXTENSION, DEFAULT_OBS_LOG_ZSTD_COMPRESSION_EXTENSION,
27};
28use std::fmt;
29use std::path::PathBuf;
30use std::time::SystemTime;
31use tracing::warn;
32
33const LOG_COMPONENT_OBS: &str = "obs";
34const LOG_SUBSYSTEM_LOG_CLEANER: &str = "log_cleaner";
35const EVENT_LOG_CLEANER_STATE: &str = "log_cleaner_state";
36
37/// Strategy for matching log files against a pattern.
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub enum FileMatchMode {
40    /// The filename must start with the pattern (e.g. "app.log." matches "app.log.2024-01-01").
41    /// Corresponds to config value "prefix".
42    Prefix,
43    /// The filename must end with the pattern (e.g. ".log" matches "2024-01-01.log").
44    /// Corresponds to config value "suffix".
45    Suffix,
46}
47
48impl FileMatchMode {
49    /// Returns the string representation of the match mode.
50    pub fn as_str(&self) -> &'static str {
51        match self {
52            FileMatchMode::Prefix => DEFAULT_OBS_LOG_MATCH_MODE_PREFIX,
53            FileMatchMode::Suffix => DEFAULT_OBS_LOG_MATCH_MODE,
54        }
55    }
56
57    /// Parse a config value into a [`FileMatchMode`].
58    ///
59    /// Any non-`prefix` value falls back to [`FileMatchMode::Suffix`] to keep
60    /// configuration handling permissive and aligned with the historical
61    /// cleaner default used by rolling log filenames.
62    pub fn from_config_str(value: &str) -> Self {
63        let trimmed = value.trim();
64        if trimmed.eq_ignore_ascii_case(DEFAULT_OBS_LOG_MATCH_MODE_PREFIX) {
65            Self::Prefix
66        } else if trimmed.eq_ignore_ascii_case(DEFAULT_OBS_LOG_MATCH_MODE) {
67            Self::Suffix
68        } else {
69            // A non-empty unrecognized value is almost certainly a typo (e.g.
70            // "prefixx"); warn so the silent fallback to suffix is visible.
71            if !trimmed.is_empty() {
72                warn!(
73                    event = EVENT_LOG_CLEANER_STATE,
74                    component = LOG_COMPONENT_OBS,
75                    subsystem = LOG_SUBSYSTEM_LOG_CLEANER,
76                    result = "unknown_match_mode",
77                    value = %value,
78                    fallback = DEFAULT_OBS_LOG_MATCH_MODE,
79                    "log cleaner state changed"
80                );
81            }
82            Self::Suffix
83        }
84    }
85}
86
87impl fmt::Display for FileMatchMode {
88    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89        f.write_str(self.as_str())
90    }
91}
92
93/// Compression algorithm used by the cleaner.
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95pub enum CompressionAlgorithm {
96    /// Gzip keeps backward compatibility with existing `.gz` archives.
97    Gzip,
98    /// Zstd provides better ratio and higher decompression throughput.
99    Zstd,
100}
101
102impl CompressionAlgorithm {
103    /// Parse a normalized lowercase configuration token or extension alias.
104    fn parse_normalized(value: &str) -> Option<Self> {
105        if value == DEFAULT_OBS_LOG_COMPRESSION_ALGORITHM_GZIP || value == DEFAULT_OBS_LOG_GZIP_COMPRESSION_EXTENSION {
106            Some(Self::Gzip)
107        } else if value == DEFAULT_OBS_LOG_COMPRESSION_ALGORITHM_ZSTD || value == DEFAULT_OBS_LOG_ZSTD_COMPRESSION_EXTENSION {
108            Some(Self::Zstd)
109        } else {
110            None
111        }
112    }
113
114    /// Parse from a user-facing configuration string.
115    ///
116    /// Supported values include both semantic names (`gzip`, `zstd`) and file
117    /// extension aliases (`gz`, `zst`). Unknown values intentionally fall back
118    /// to the crate default so observability startup remains resilient.
119    pub fn from_config_str(value: &str) -> Self {
120        let normalized = value.trim().to_ascii_lowercase();
121        match Self::parse_normalized(&normalized) {
122            Some(algorithm) => algorithm,
123            None => {
124                let fallback = Self::default();
125                // A non-empty unrecognized value is almost certainly a typo;
126                // warn so the silent fallback to the default codec is visible.
127                if !normalized.is_empty() {
128                    warn!(
129                        event = EVENT_LOG_CLEANER_STATE,
130                        component = LOG_COMPONENT_OBS,
131                        subsystem = LOG_SUBSYSTEM_LOG_CLEANER,
132                        result = "unknown_compression_algorithm",
133                        value = %value,
134                        fallback = %fallback,
135                        "log cleaner state changed"
136                    );
137                }
138                fallback
139            }
140        }
141    }
142
143    /// Archive suffix (without dot) used for this algorithm.
144    ///
145    /// The returned value is suitable for appending to an existing filename,
146    /// rather than replacing the source extension.
147    pub fn extension(self) -> &'static str {
148        match self {
149            Self::Gzip => DEFAULT_OBS_LOG_GZIP_COMPRESSION_ALL_EXTENSION.trim_start_matches('.'),
150            Self::Zstd => DEFAULT_OBS_LOG_ZSTD_COMPRESSION_ALL_EXTENSION.trim_start_matches('.'),
151        }
152    }
153
154    /// Supported compressed suffixes used by scanner retention logic.
155    ///
156    /// The scanner uses this list to recognize already-archived files and to
157    /// keep them on a separate retention path from plain log files.
158    pub fn compressed_suffixes() -> [&'static str; 2] {
159        [
160            DEFAULT_OBS_LOG_GZIP_COMPRESSION_ALL_EXTENSION,
161            DEFAULT_OBS_LOG_ZSTD_COMPRESSION_ALL_EXTENSION,
162        ]
163    }
164
165    /// Stable lowercase string form used in logs and configuration echoes.
166    pub fn as_str(self) -> &'static str {
167        match self {
168            Self::Gzip => DEFAULT_OBS_LOG_COMPRESSION_ALGORITHM_GZIP,
169            Self::Zstd => DEFAULT_OBS_LOG_COMPRESSION_ALGORITHM_ZSTD,
170        }
171    }
172}
173
174impl std::str::FromStr for CompressionAlgorithm {
175    type Err = &'static str;
176
177    fn from_str(value: &str) -> Result<Self, Self::Err> {
178        let normalized = value.trim().to_ascii_lowercase();
179        Self::parse_normalized(&normalized).ok_or("invalid compression algorithm")
180    }
181}
182
183impl Default for CompressionAlgorithm {
184    fn default() -> Self {
185        Self::from_config_str(DEFAULT_OBS_LOG_COMPRESSION_ALGORITHM)
186    }
187}
188
189impl fmt::Display for CompressionAlgorithm {
190    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191        f.write_str(self.as_str())
192    }
193}
194
195/// Worker-thread default used by parallel compressor.
196///
197/// The worker count follows CPU capacity, capped at 8 to avoid swamping the
198/// host when each task may also use internal codec threads. The lower bound is
199/// 1 (not 4) so a 1-2 vCPU container is not forced to run several concurrent
200/// compressions that monopolize its CPU.
201pub fn default_parallel_workers() -> usize {
202    num_cpus::get().clamp(1, 8)
203}
204
205/// Metadata for a single log file discovered by the scanner.
206///
207/// This snapshot is intentionally immutable after discovery. The cleaner uses
208/// it to sort candidates by age, evaluate retention constraints, and report
209/// deletion metrics without re-reading metadata during every later stage.
210#[derive(Debug, Clone)]
211pub(super) struct FileInfo {
212    /// Absolute or scanner-produced path to the file on disk.
213    pub path: PathBuf,
214    /// File size in bytes at the time of discovery.
215    ///
216    /// This value is used for retention accounting and freed-byte metrics.
217    pub size: u64,
218    /// Projected bytes reclaimed when this file is deleted.
219    ///
220    /// For source logs that were compressed first, this reflects the original
221    /// size minus the archive bytes that remain on disk.
222    pub projected_freed_bytes: u64,
223    /// Last-modification timestamp from the filesystem.
224    ///
225    /// The selection phase sorts on this timestamp so the oldest files are
226    /// processed first.
227    pub modified: SystemTime,
228}
229
230#[cfg(test)]
231mod tests {
232    use super::CompressionAlgorithm;
233
234    #[test]
235    fn compression_algorithm_accepts_full_names_and_aliases() {
236        assert_eq!(CompressionAlgorithm::from_config_str("gzip"), CompressionAlgorithm::Gzip);
237        assert_eq!(CompressionAlgorithm::from_config_str("GZ"), CompressionAlgorithm::Gzip);
238        assert_eq!(CompressionAlgorithm::from_config_str("zstd"), CompressionAlgorithm::Zstd);
239        assert_eq!(CompressionAlgorithm::from_config_str(" zst "), CompressionAlgorithm::Zstd);
240    }
241
242    #[test]
243    fn compression_algorithm_defaults_or_errors_for_invalid_values() {
244        assert_eq!(CompressionAlgorithm::from_config_str("brotli"), CompressionAlgorithm::default());
245        assert!("brotli".parse::<CompressionAlgorithm>().is_err());
246    }
247}