Skip to main content

rustfs_obs/telemetry/dial9/
config.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//! Configuration for dial9 Tokio runtime telemetry.
16//!
17//! This module carries no dependency on the `dial9-tokio-telemetry` crate, so
18//! it compiles identically whether or not the `dial9` feature is enabled. That
19//! lets callers read the configured state (and export metrics about it) from a
20//! binary that was built without telemetry support.
21
22use super::state::dial9_runtime_state;
23use rustfs_config::{
24    DEFAULT_RUNTIME_DIAL9_ENABLED, DEFAULT_RUNTIME_DIAL9_FILE_PREFIX, DEFAULT_RUNTIME_DIAL9_MAX_FILE_SIZE,
25    DEFAULT_RUNTIME_DIAL9_OUTPUT_DIR, DEFAULT_RUNTIME_DIAL9_ROTATION_COUNT, ENV_RUNTIME_DIAL9_ENABLED,
26    ENV_RUNTIME_DIAL9_FILE_PREFIX, ENV_RUNTIME_DIAL9_MAX_FILE_SIZE, ENV_RUNTIME_DIAL9_OUTPUT_DIR,
27    ENV_RUNTIME_DIAL9_ROTATION_COUNT, ENV_RUNTIME_DIAL9_S3_BUCKET, ENV_RUNTIME_DIAL9_S3_PREFIX,
28};
29use rustfs_utils::{get_env_bool, get_env_opt_str, get_env_opt_u64, get_env_opt_usize, get_env_str};
30use std::path::PathBuf;
31use tracing::warn;
32
33use super::{EVENT_DIAL9_STATE, LOG_COMPONENT_OBS, LOG_SUBSYSTEM_DIAL9};
34
35/// Whether this binary was compiled with dial9 telemetry support.
36///
37/// Telemetry requires both the `dial9` cargo feature and `--cfg tokio_unstable`;
38/// the crate's build script enforces that pairing, so this single flag is
39/// sufficient to describe compile-time support.
40pub const fn is_supported() -> bool {
41    cfg!(feature = "dial9")
42}
43
44/// Whether dial9 telemetry is requested via environment configuration.
45///
46/// This reports operator intent and is independent of whether the binary can
47/// honour it. Use [`is_enabled`] to test whether telemetry will actually run.
48pub fn is_configured() -> bool {
49    get_env_bool(ENV_RUNTIME_DIAL9_ENABLED, DEFAULT_RUNTIME_DIAL9_ENABLED)
50}
51
52/// Whether dial9 telemetry will actually run: requested *and* compiled in.
53pub fn is_enabled() -> bool {
54    is_supported() && is_configured()
55}
56
57fn sanitize_max_file_size(bytes: u64) -> u64 {
58    bytes.max(1)
59}
60
61fn sanitize_rotation_count(count: usize) -> usize {
62    count.max(1)
63}
64
65/// Total on-disk byte budget for the trace family, saturating on overflow.
66pub(super) fn total_rotation_size(max_file_size: u64, rotation_count: usize) -> u64 {
67    max_file_size.saturating_mul(u64::try_from(rotation_count).unwrap_or(u64::MAX))
68}
69
70/// Configuration for dial9 Tokio telemetry.
71#[derive(Debug, Clone)]
72pub struct Dial9Config {
73    /// Whether dial9 telemetry is enabled
74    pub enabled: bool,
75
76    /// Directory where trace files are written
77    pub output_dir: String,
78
79    /// Trace family name under the output directory
80    pub file_prefix: String,
81
82    /// Maximum size of each trace file in bytes
83    pub max_file_size: u64,
84
85    /// Number of rotated files to keep
86    pub rotation_count: usize,
87}
88
89impl Default for Dial9Config {
90    fn default() -> Self {
91        Self {
92            enabled: DEFAULT_RUNTIME_DIAL9_ENABLED,
93            output_dir: DEFAULT_RUNTIME_DIAL9_OUTPUT_DIR.to_string(),
94            file_prefix: DEFAULT_RUNTIME_DIAL9_FILE_PREFIX.to_string(),
95            max_file_size: DEFAULT_RUNTIME_DIAL9_MAX_FILE_SIZE,
96            rotation_count: DEFAULT_RUNTIME_DIAL9_ROTATION_COUNT,
97        }
98    }
99}
100
101impl Dial9Config {
102    /// Create configuration from environment variables, recording the resulting
103    /// trace location so metrics can report it even on a disabled binary.
104    pub fn from_env() -> Self {
105        let config = if is_enabled() {
106            Self::from_env_enabled()
107        } else {
108            Self::default()
109        };
110        dial9_runtime_state().record_config(&config);
111        config
112    }
113
114    /// Build the enabled configuration from the environment, warning about any
115    /// knob that is set but cannot be honoured.
116    fn from_env_enabled() -> Self {
117        let raw_max_file_size = get_env_opt_u64(ENV_RUNTIME_DIAL9_MAX_FILE_SIZE);
118        let raw_rotation_count = get_env_opt_usize(ENV_RUNTIME_DIAL9_ROTATION_COUNT);
119
120        if raw_max_file_size == Some(0) {
121            warn!(
122                event = EVENT_DIAL9_STATE,
123                component = LOG_COMPONENT_OBS,
124                subsystem = LOG_SUBSYSTEM_DIAL9,
125                result = "invalid_max_file_size",
126                fallback_bytes = 1_u64,
127                "dial9 state changed"
128            );
129        }
130        if raw_rotation_count == Some(0) {
131            warn!(
132                event = EVENT_DIAL9_STATE,
133                component = LOG_COMPONENT_OBS,
134                subsystem = LOG_SUBSYSTEM_DIAL9,
135                result = "invalid_rotation_count",
136                fallback_count = 1_usize,
137                "dial9 state changed"
138            );
139        }
140
141        // S3 upload is not built (see `warn_unusable_s3_upload`); read the knobs
142        // only to warn, and drop them rather than carrying dead configuration.
143        warn_unusable_s3_upload(
144            get_env_opt_str(ENV_RUNTIME_DIAL9_S3_BUCKET)
145                .filter(|s| !s.is_empty())
146                .as_deref(),
147            get_env_opt_str(ENV_RUNTIME_DIAL9_S3_PREFIX)
148                .filter(|s| !s.is_empty())
149                .as_deref(),
150        );
151
152        Self {
153            enabled: true,
154            output_dir: get_env_str(ENV_RUNTIME_DIAL9_OUTPUT_DIR, DEFAULT_RUNTIME_DIAL9_OUTPUT_DIR),
155            file_prefix: get_env_str(ENV_RUNTIME_DIAL9_FILE_PREFIX, DEFAULT_RUNTIME_DIAL9_FILE_PREFIX),
156            max_file_size: sanitize_max_file_size(raw_max_file_size.unwrap_or(DEFAULT_RUNTIME_DIAL9_MAX_FILE_SIZE)),
157            rotation_count: sanitize_rotation_count(raw_rotation_count.unwrap_or(DEFAULT_RUNTIME_DIAL9_ROTATION_COUNT)),
158        }
159    }
160
161    /// Get the trace family directory for rotating trace segments.
162    pub fn base_path(&self) -> PathBuf {
163        PathBuf::from(&self.output_dir).join(&self.file_prefix)
164    }
165
166    /// Total on-disk byte budget across all retained segments.
167    pub fn total_disk_budget(&self) -> u64 {
168        total_rotation_size(self.max_file_size, self.rotation_count)
169    }
170}
171
172/// S3 upload of sealed segments is not available in any build.
173///
174/// dial9's `worker-s3` feature depends on aws-sdk-s3-transfer-manager 0.1.3,
175/// which pins hyper-rustls 0.24 / rustls-webpki 0.101.7 — a webpki carrying
176/// RUSTSEC-2026-0098, -0099 and -0104. Cargo cannot drop a transitive
177/// dependency, so this needs an upstream fix (rustfs/backlog#1157, D9-14).
178///
179/// Warn loudly rather than silently discarding a configured bucket: an operator
180/// who set these expects their traces to be uploaded somewhere.
181fn warn_unusable_s3_upload(s3_bucket: Option<&str>, s3_prefix: Option<&str>) {
182    if s3_bucket.is_none() && s3_prefix.is_none() {
183        return;
184    }
185
186    warn!(
187        event = EVENT_DIAL9_STATE,
188        component = LOG_COMPONENT_OBS,
189        subsystem = LOG_SUBSYSTEM_DIAL9,
190        result = "s3_upload_unsupported",
191        s3_bucket = s3_bucket.unwrap_or(""),
192        s3_prefix = s3_prefix.unwrap_or(""),
193        reason = "dial9 worker-s3 depends on a vulnerable rustls-webpki (RUSTSEC-2026-0098/0099/0104)",
194        remedy = "collect trace segments from the output directory instead",
195        "dial9 state changed"
196    );
197}
198
199#[cfg(test)]
200mod tests {
201    use super::*;
202
203    #[test]
204    fn sanitizers_reject_zero_values() {
205        assert_eq!(sanitize_max_file_size(0), 1);
206        assert_eq!(sanitize_rotation_count(0), 1);
207    }
208
209    #[test]
210    fn total_rotation_size_saturates() {
211        assert_eq!(total_rotation_size(u64::MAX, 2), u64::MAX);
212    }
213
214    #[test]
215    fn default_config_is_disabled() {
216        let config = Dial9Config::default();
217        assert!(!config.enabled);
218        assert_eq!(config.output_dir, DEFAULT_RUNTIME_DIAL9_OUTPUT_DIR);
219        assert_eq!(config.file_prefix, DEFAULT_RUNTIME_DIAL9_FILE_PREFIX);
220        assert_eq!(config.max_file_size, DEFAULT_RUNTIME_DIAL9_MAX_FILE_SIZE);
221        assert_eq!(config.rotation_count, DEFAULT_RUNTIME_DIAL9_ROTATION_COUNT);
222    }
223
224    #[test]
225    fn base_path_joins_prefix() {
226        let config = Dial9Config {
227            output_dir: "/tmp/telemetry".to_string(),
228            file_prefix: "rustfs".to_string(),
229            ..Default::default()
230        };
231        assert_eq!(config.base_path(), PathBuf::from("/tmp/telemetry/rustfs"));
232    }
233
234    #[test]
235    fn total_disk_budget_multiplies_file_size_by_rotation_count() {
236        let config = Dial9Config {
237            max_file_size: 100,
238            rotation_count: 10,
239            ..Default::default()
240        };
241        assert_eq!(config.total_disk_budget(), 1_000);
242    }
243
244    #[test]
245    fn is_enabled_requires_compile_time_support() {
246        // `is_enabled` is the conjunction of the two; when support is absent it
247        // must stay false no matter what the environment requests.
248        if !is_supported() {
249            assert!(!is_enabled());
250        }
251    }
252}