| 1 |
// This Source Code Form is subject to the terms of the Mozilla Public |
| 2 |
// License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 |
// file, You can obtain one at https://mozilla.org/MPL/2.0/. |
| 4 |
|
| 5 |
//! # Debug options |
| 6 |
//! |
| 7 |
//! The debug options for Glean may be set by calling one of the `set_*` functions |
| 8 |
//! or by setting specific environment variables. |
| 9 |
//! |
| 10 |
//! The environment variables will be read only once when the options are initialized. |
| 11 |
//! |
| 12 |
//! The possible debugging features available out of the box are: |
| 13 |
//! |
| 14 |
//! * **Ping logging** - logging the contents of ping requests that are correctly assembled; |
| 15 |
//! This may be set by calling glean.set_log_pings(value: bool) |
| 16 |
//! or by setting the environment variable GLEAN_LOG_PINGS="true"; |
| 17 |
//! * **Debug tagging** - Adding the X-Debug-ID header to every ping request, |
| 18 |
//! allowing these tagged pings to be sent to the ["Ping Debug Viewer"](https://mozilla.github.io/glean/book/dev/core/internal/debug-pings.html). |
| 19 |
//! This may be set by calling glean.set_debug_view_tag(value: &str) |
| 20 |
//! or by setting the environment variable `GLEAN_DEBUG_VIEW_TAG=<some tag>`; |
| 21 |
//! * **Source tagging** - Adding the X-Source-Tags header to every ping request, |
| 22 |
//! allowing pings to be tagged with custom labels. |
| 23 |
//! This may be set by calling `glean.set_source_tags(value: Vec<String>)` |
| 24 |
//! or by setting the environment variable `GLEAN_SOURCE_TAGS=<some, tags>`; |
| 25 |
//! |
| 26 |
//! Bindings may implement other debugging features, e.g. sending pings on demand. |
| 27 |
|
| 28 |
use std::env; |
| 29 |
|
| 30 |
use malloc_size_of::MallocSizeOf; |
| 31 |
use malloc_size_of_derive::MallocSizeOf; |
| 32 |
|
| 33 |
const GLEAN_LOG_PINGS: &str = "GLEAN_LOG_PINGS"; |
| 34 |
const GLEAN_DEBUG_VIEW_TAG: &str = "GLEAN_DEBUG_VIEW_TAG"; |
| 35 |
const GLEAN_SOURCE_TAGS: &str = "GLEAN_SOURCE_TAGS"; |
| 36 |
const GLEAN_MAX_SOURCE_TAGS: usize = 5; |
| 37 |
|
| 38 |
/// A representation of all of Glean's debug options. |
| 39 |
#[derive(MallocSizeOf)] |
| 40 |
pub struct DebugOptions { |
| 41 |
/// Option to log the payload of pings that are successfully assembled into a ping request. |
| 42 |
pub log_pings: DebugOption<bool>, |
| 43 |
/// Option to add the X-Debug-ID header to every ping request. |
| 44 |
pub debug_view_tag: DebugOption<String>, |
| 45 |
/// Option to add the X-Source-Tags header to ping requests. This will allow the data |
| 46 |
/// consumers to classify data depending on the applied tags. |
| 47 |
pub source_tags: DebugOption<Vec<String>>, |
| 48 |
} |
| 49 |
|
| 50 |
impl std::fmt::Debug for DebugOptions { |
| 51 |
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { |
| 52 |
fmt.debug_struct("DebugOptions") |
| 53 |
.field("log_pings", &self.log_pings.get()) |
| 54 |
.field("debug_view_tag", &self.debug_view_tag.get()) |
| 55 |
.field("source_tags", &self.source_tags.get()) |
| 56 |
.finish() |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
impl DebugOptions { |
| 61 |
pub fn new() -> Self { |
| 62 |
Self { |
| 63 |
log_pings: DebugOption::new(GLEAN_LOG_PINGS, get_bool_from_str, None), |
| 64 |
debug_view_tag: DebugOption::new(GLEAN_DEBUG_VIEW_TAG, Some, Some(validate_tag)), |
| 65 |
source_tags: DebugOption::new( |
| 66 |
GLEAN_SOURCE_TAGS, |
| 67 |
tokenize_string, |
| 68 |
Some(validate_source_tags), |
| 69 |
), |
| 70 |
} |
| 71 |
} |
| 72 |
} |
| 73 |
|
| 74 |
/// A representation of a debug option, |
| 75 |
/// where the value can be set programmatically or come from an environment variable. |
| 76 |
#[derive(Debug)] |
| 77 |
pub struct DebugOption<T, E = fn(String) -> Option<T>, V = fn(&T) -> bool> { |
| 78 |
/// The name of the environment variable related to this debug option. |
| 79 |
env: String, |
| 80 |
/// The actual value of this option. |
| 81 |
value: Option<T>, |
| 82 |
/// Function to extract the data of type `T` from a `String`, used when |
| 83 |
/// extracting data from the environment. |
| 84 |
extraction: E, |
| 85 |
/// Optional function to validate the value parsed from the environment |
| 86 |
/// or passed to the `set` function. |
| 87 |
validation: Option<V>, |
| 88 |
} |
| 89 |
|
| 90 |
impl<T, E, V> MallocSizeOf for DebugOption<T, E, V> |
| 91 |
where |
| 92 |
T: MallocSizeOf, |
| 93 |
{ |
| 94 |
fn size_of(&self, ops: &mut malloc_size_of::MallocSizeOfOps) -> usize { |
| 95 |
self.env.size_of(ops) + self.value.size_of(ops) |
| 96 |
} |
| 97 |
} |
| 98 |
|
| 99 |
impl<T, E, V> DebugOption<T, E, V> |
| 100 |
where |
| 101 |
T: Clone, |
| 102 |
E: Fn(String) -> Option<T>, |
| 103 |
V: Fn(&T) -> bool, |
| 104 |
{ |
| 105 |
/// Creates a new debug option. |
| 106 |
/// |
| 107 |
/// Tries to get the initial value of the option from the environment. |
| 108 |
pub fn new(env: &str, extraction: E, validation: Option<V>) -> Self { |
| 109 |
let mut option = Self { |
| 110 |
env: env.into(), |
| 111 |
value: None, |
| 112 |
extraction, |
| 113 |
validation, |
| 114 |
}; |
| 115 |
|
| 116 |
option.set_from_env(); |
| 117 |
option |
| 118 |
} |
| 119 |
|
| 120 |
fn validate(&self, value: &T) -> bool { |
| 121 |
if let Some(f) = self.validation.as_ref() { |
| 122 |
f(value) |
| 123 |
} else { |
| 124 |
true |
| 125 |
} |
| 126 |
} |
| 127 |
|
| 128 |
fn set_from_env(&mut self) { |
| 129 |
let extract = &self.extraction; |
| 130 |
match env::var(&self.env) { |
| 131 |
Ok(env_value) => match extract(env_value.clone()) { |
| 132 |
Some(v) => { |
| 133 |
self.set(v); |
| 134 |
} |
| 135 |
None => { |
| 136 |
log::error!( |
| 137 |
"Unable to parse debug option {}={} into {}. Ignoring.", |
| 138 |
self.env, |
| 139 |
env_value, |
| 140 |
std::any::type_name::<T>() |
| 141 |
); |
| 142 |
} |
| 143 |
}, |
| 144 |
Err(env::VarError::NotUnicode(_)) => { |
| 145 |
log::error!("The value of {} is not valid unicode. Ignoring.", self.env) |
| 146 |
} |
| 147 |
// The other possible error is that the env var is not set, |
| 148 |
// which is not an error for us and can safely be ignored. |
| 149 |
Err(_) => {} |
| 150 |
} |
| 151 |
} |
| 152 |
|
| 153 |
/// Tries to set a value for this debug option. |
| 154 |
/// |
| 155 |
/// Validates the value in case a validation function is available. |
| 156 |
/// |
| 157 |
/// # Returns |
| 158 |
/// |
| 159 |
/// Whether the option passed validation and was succesfully set. |
| 160 |
pub fn set(&mut self, value: T) -> bool { |
| 161 |
let validated = self.validate(&value); |
| 162 |
if validated { |
| 163 |
log::info!("Setting the debug option {}.", self.env); |
| 164 |
self.value = Some(value); |
| 165 |
return true; |
| 166 |
} |
| 167 |
log::error!("Invalid value for debug option {}.", self.env); |
| 168 |
false |
| 169 |
} |
| 170 |
|
| 171 |
/// Gets the value of this debug option. |
| 172 |
pub fn get(&self) -> Option<&T> { |
| 173 |
self.value.as_ref() |
| 174 |
} |
| 175 |
} |
| 176 |
|
| 177 |
fn get_bool_from_str(value: String) -> Option<bool> { |
| 178 |
std::str::FromStr::from_str(&value).ok() |
| 179 |
} |
| 180 |
|
| 181 |
fn tokenize_string(value: String) -> Option<Vec<String>> { |
| 182 |
let trimmed = value.trim(); |
| 183 |
if trimmed.is_empty() { |
| 184 |
return None; |
| 185 |
} |
| 186 |
|
| 187 |
Some(trimmed.split(',').map(|s| s.trim().to_string()).collect()) |
| 188 |
} |
| 189 |
|
| 190 |
/// A tag is the value used in both the `X-Debug-ID` and `X-Source-Tags` headers |
| 191 |
/// of tagged ping requests, thus is it must be a valid header value. |
| 192 |
/// |
| 193 |
/// In other words, it must match the regex: "[a-zA-Z0-9-]{1,20}" |
| 194 |
/// |
| 195 |
/// The regex crate isn't used here because it adds to the binary size, |
| 196 |
/// and the Glean SDK doesn't use regular expressions anywhere else. |
| 197 |
#[allow(clippy::ptr_arg)] |
| 198 |
fn validate_tag(value: &String) -> bool { |
| 199 |
if value.is_empty() { |
| 200 |
log::error!("A tag must have at least one character."); |
| 201 |
return false; |
| 202 |
} |
| 203 |
|
| 204 |
let mut iter = value.chars(); |
| 205 |
let mut count = 0; |
| 206 |
|
| 207 |
loop { |
| 208 |
match iter.next() { |
| 209 |
// We are done, so the whole expression is valid. |
| 210 |
None => return true, |
| 211 |
// Valid characters. |
| 212 |
Some('-') | Some('a'..='z') | Some('A'..='Z') | Some('0'..='9') => (), |
| 213 |
// An invalid character |
| 214 |
Some(c) => { |
| 215 |
log::error!("Invalid character '{}' in the tag.", c); |
| 216 |
return false; |
| 217 |
} |
| 218 |
} |
| 219 |
count += 1; |
| 220 |
if count == 20 { |
| 221 |
log::error!("A tag cannot exceed 20 characters."); |
| 222 |
return false; |
| 223 |
} |
| 224 |
} |
| 225 |
} |
| 226 |
|
| 227 |
/// Validate the list of source tags. |
| 228 |
/// |
| 229 |
/// This builds upon the existing `validate_tag` function, since all the |
| 230 |
/// tags should respect the same rules to make the pipeline happy. |
| 231 |
#[allow(clippy::ptr_arg)] |
| 232 |
fn validate_source_tags(tags: &Vec<String>) -> bool { |
| 233 |
if tags.is_empty() { |
| 234 |
return false; |
| 235 |
} |
| 236 |
|
| 237 |
if tags.len() > GLEAN_MAX_SOURCE_TAGS { |
| 238 |
log::error!( |
| 239 |
"A list of tags cannot contain more than {} elements.", |
| 240 |
GLEAN_MAX_SOURCE_TAGS |
| 241 |
); |
| 242 |
return false; |
| 243 |
} |
| 244 |
|
| 245 |
if tags.iter().any(|s| s.starts_with("glean")) { |
| 246 |
log::error!("Tags starting with `glean` are reserved and must not be used."); |
| 247 |
return false; |
| 248 |
} |
| 249 |
|
| 250 |
tags.iter().all(validate_tag) |
| 251 |
} |
| 252 |
|
| 253 |
#[cfg(test)] |
| 254 |
mod test { |
| 255 |
use super::*; |
| 256 |
|
| 257 |
#[test] |
| 258 |
fn debug_option_is_correctly_loaded_from_env() { |
| 259 |
env::set_var("GLEAN_TEST_1", "test"); |
| 260 |
let option: DebugOption<String> = DebugOption::new("GLEAN_TEST_1", Some, None); |
| 261 |
assert_eq!(option.get().unwrap(), "test"); |
| 262 |
} |
| 263 |
|
| 264 |
#[test] |
| 265 |
fn debug_option_is_correctly_validated_when_necessary() { |
| 266 |
#[allow(clippy::ptr_arg)] |
| 267 |
fn validate(value: &String) -> bool { |
| 268 |
value == "test" |
| 269 |
} |
| 270 |
|
| 271 |
// Invalid values from the env are not set |
| 272 |
env::set_var("GLEAN_TEST_2", "invalid"); |
| 273 |
let mut option: DebugOption<String> = |
| 274 |
DebugOption::new("GLEAN_TEST_2", Some, Some(validate)); |
| 275 |
assert!(option.get().is_none()); |
| 276 |
|
| 277 |
// Valid values are set using the `set` function |
| 278 |
assert!(option.set("test".into())); |
| 279 |
assert_eq!(option.get().unwrap(), "test"); |
| 280 |
|
| 281 |
// Invalid values are not set using the `set` function |
| 282 |
assert!(!option.set("invalid".into())); |
| 283 |
assert_eq!(option.get().unwrap(), "test"); |
| 284 |
} |
| 285 |
|
| 286 |
#[test] |
| 287 |
fn tokenize_string_splits_correctly() { |
| 288 |
// Valid list is properly tokenized and spaces are trimmed. |
| 289 |
assert_eq!( |
| 290 |
Some(vec!["test1".to_string(), "test2".to_string()]), |
| 291 |
tokenize_string(" test1, test2 ".to_string()) |
| 292 |
); |
| 293 |
|
| 294 |
// Empty strings return no item. |
| 295 |
assert_eq!(None, tokenize_string("".to_string())); |
| 296 |
} |
| 297 |
|
| 298 |
#[test] |
| 299 |
fn validates_tag_correctly() { |
| 300 |
assert!(validate_tag(&"valid-value".to_string())); |
| 301 |
assert!(validate_tag(&"-also-valid-value".to_string())); |
| 302 |
assert!(!validate_tag(&"invalid_value".to_string())); |
| 303 |
assert!(!validate_tag(&"invalid value".to_string())); |
| 304 |
assert!(!validate_tag(&"!nv@lid-val*e".to_string())); |
| 305 |
assert!(!validate_tag( |
| 306 |
&"invalid-value-because-way-too-long".to_string() |
| 307 |
)); |
| 308 |
assert!(!validate_tag(&"".to_string())); |
| 309 |
} |
| 310 |
|
| 311 |
#[test] |
| 312 |
fn validates_source_tags_correctly() { |
| 313 |
// Empty tags. |
| 314 |
assert!(!validate_source_tags(&vec!["".to_string()])); |
| 315 |
// Too many tags. |
| 316 |
assert!(!validate_source_tags(&vec![ |
| 317 |
"1".to_string(), |
| 318 |
"2".to_string(), |
| 319 |
"3".to_string(), |
| 320 |
"4".to_string(), |
| 321 |
"5".to_string(), |
| 322 |
"6".to_string() |
| 323 |
])); |
| 324 |
// Invalid tags. |
| 325 |
assert!(!validate_source_tags(&vec!["!nv@lid-val*e".to_string()])); |
| 326 |
assert!(!validate_source_tags(&vec![ |
| 327 |
"glean-test1".to_string(), |
| 328 |
"test2".to_string() |
| 329 |
])); |
| 330 |
} |
| 331 |
} |