1#![allow(clippy::doc_overindented_list_items)]
6#![allow(clippy::large_const_arrays)] #![allow(clippy::significant_drop_in_scrutinee)]
8#![allow(clippy::uninlined_format_args)]
9#![deny(rustdoc::broken_intra_doc_links)]
10#![deny(missing_docs)]
11
12use std::borrow::Cow;
21use std::collections::HashMap;
22use std::path::Path;
23use std::sync::atomic::{AtomicBool, Ordering};
24use std::sync::{Arc, Mutex};
25use std::time::{Duration, UNIX_EPOCH};
26use std::{fmt, fs};
27
28use chrono::{DateTime, Utc};
29use crossbeam_channel::unbounded;
30use log::LevelFilter;
31use malloc_size_of_derive::MallocSizeOf;
32use once_cell::sync::{Lazy, OnceCell};
33use uuid::Uuid;
34
35use metrics::RemoteSettingsConfig;
36
37mod common_metric_data;
38mod core;
39mod core_metrics;
40mod database;
41mod debug;
42#[cfg(feature = "benchmark")]
43#[doc(hidden)]
44pub mod dispatcher;
45#[cfg(not(feature = "benchmark"))]
46mod dispatcher;
47mod error;
48mod error_recording;
49mod event_database;
50mod glean_metrics;
51mod histogram;
52mod internal_metrics;
53mod internal_pings;
54pub mod metrics;
55pub mod ping;
56mod scheduler;
57pub(crate) mod session;
58pub mod storage;
59mod system;
60#[doc(hidden)]
61pub mod thread;
62pub mod traits;
63pub mod upload;
64mod util;
65
66#[cfg(all(not(target_os = "android"), not(target_os = "ios")))]
67mod fd_logger;
68
69pub use crate::common_metric_data::{CommonMetricData, Lifetime, MetricLabel};
70pub use crate::core::Glean;
71pub use crate::core_metrics::{AttributionMetrics, ClientInfoMetrics, DistributionMetrics};
72use crate::database::StoredSubmittedPingHandler;
73use crate::dispatcher::is_test_mode;
74pub use crate::error::{Error, ErrorKind, Result};
75pub use crate::error_recording::{test_get_num_recorded_errors, ErrorType};
76pub use crate::histogram::HistogramType;
77use crate::internal_metrics::DataDirectoryInfoObject;
78pub use crate::metrics::labeled::{
79 AllowLabeled, LabeledBoolean, LabeledCounter, LabeledCustomDistribution,
80 LabeledMemoryDistribution, LabeledMetric, LabeledMetricData, LabeledQuantity, LabeledString,
81 LabeledTimingDistribution,
82};
83pub use crate::metrics::{
84 BooleanMetric, CounterMetric, CustomDistributionMetric, Datetime, DatetimeMetric,
85 DenominatorMetric, DistributionData, DualLabeledCounterMetric, EventMetric,
86 LocalCustomDistribution, LocalMemoryDistribution, LocalTimingDistribution,
87 MemoryDistributionMetric, MemoryUnit, NumeratorMetric, ObjectMetric, PingType, QuantityMetric,
88 Rate, RateMetric, RecordedEvent, RecordedExperiment, StringListMetric, StringMetric,
89 TestGetValue, TextMetric, TimeUnit, TimerId, TimespanMetric, TimingDistributionMetric,
90 UrlMetric, UuidMetric,
91};
92pub use crate::session::{SessionManager, SessionMetadata, SessionMode};
93pub use crate::upload::{PingRequest, PingUploadTask, UploadResult, UploadTaskAction};
94
95const GLEAN_VERSION: &str = env!("CARGO_PKG_VERSION");
96const GLEAN_SCHEMA_VERSION: u32 = 1;
97const DEFAULT_MAX_EVENTS: u32 = 500;
98static KNOWN_CLIENT_ID: Lazy<Uuid> =
99 Lazy::new(|| Uuid::parse_str("c0ffeec0-ffee-c0ff-eec0-ffeec0ffeec0").unwrap());
100
101pub(crate) const PENDING_PINGS_DIRECTORY: &str = "pending_pings";
103pub(crate) const DELETION_REQUEST_PINGS_DIRECTORY: &str = "deletion_request";
104
105static INITIALIZE_CALLED: AtomicBool = AtomicBool::new(false);
109
110static PRE_INIT_DEBUG_VIEW_TAG: Mutex<String> = Mutex::new(String::new());
112static PRE_INIT_LOG_PINGS: AtomicBool = AtomicBool::new(false);
113static PRE_INIT_SOURCE_TAGS: Mutex<Vec<String>> = Mutex::new(Vec::new());
114
115static PRE_INIT_PING_REGISTRATION: Mutex<Vec<metrics::PingType>> = Mutex::new(Vec::new());
117static PRE_INIT_PING_ENABLED: Mutex<Vec<(metrics::PingType, bool)>> = Mutex::new(Vec::new());
118
119static PRE_INIT_ATTRIBUTION: Mutex<Option<AttributionMetrics>> = Mutex::new(None);
121static PRE_INIT_DISTRIBUTION: Mutex<Option<DistributionMetrics>> = Mutex::new(None);
122static PRE_INIT_ATTRIBUTION_CLEARED: AtomicBool = AtomicBool::new(false);
123static PRE_INIT_DISTRIBUTION_CLEARED: AtomicBool = AtomicBool::new(false);
124
125static INIT_HANDLES: Lazy<Arc<Mutex<Vec<std::thread::JoinHandle<()>>>>> =
129 Lazy::new(|| Arc::new(Mutex::new(Vec::new())));
130
131#[derive(Debug, Clone, MallocSizeOf)]
133pub struct InternalConfiguration {
134 pub upload_enabled: bool,
136 pub data_path: String,
138 pub application_id: String,
140 pub language_binding_name: String,
142 pub max_events: Option<u32>,
144 pub delay_ping_lifetime_io: bool,
146 pub app_build: String,
149 pub use_core_mps: bool,
151 pub trim_data_to_registered_pings: bool,
153 #[ignore_malloc_size_of = "external non-allocating type"]
156 pub log_level: Option<LevelFilter>,
157 pub rate_limit: Option<PingRateLimit>,
159 pub enable_event_timestamps: bool,
161 pub experimentation_id: Option<String>,
165 pub enable_internal_pings: bool,
167 pub ping_schedule: HashMap<String, Vec<String>>,
171
172 pub ping_lifetime_threshold: u64,
174 pub ping_lifetime_max_time: u64,
176 pub max_pending_pings_count: Option<u64>,
178 pub max_pending_pings_directory_size: Option<u64>,
180 pub session_mode: session::SessionMode,
182 pub session_sample_rate: f64,
184 pub session_inactivity_timeout_ms: u64,
187 pub events_ping_acceleration_factor: Option<u32>,
189 pub enable_store_submitted_pings: bool,
191}
192
193#[derive(Debug, Clone, MallocSizeOf)]
195pub struct PingRateLimit {
196 pub seconds_per_interval: u64,
198 pub pings_per_interval: u32,
200}
201
202fn launch_with_glean(callback: impl FnOnce(&Glean) + Send + 'static) {
204 dispatcher::launch(|| core::with_glean(callback));
205}
206
207fn launch_with_glean_mut(callback: impl FnOnce(&mut Glean) + Send + 'static) {
210 dispatcher::launch(|| core::with_glean_mut(callback));
211}
212
213fn block_on_dispatcher() {
217 dispatcher::block_on_queue()
218}
219
220pub fn get_awake_timestamp_ms() -> u64 {
222 const NANOS_PER_MILLI: u64 = 1_000_000;
223 zeitstempel::now_awake() / NANOS_PER_MILLI
224}
225
226pub fn get_timestamp_ms() -> u64 {
228 const NANOS_PER_MILLI: u64 = 1_000_000;
229 zeitstempel::now() / NANOS_PER_MILLI
230}
231
232struct State {
237 client_info: ClientInfoMetrics,
239
240 callbacks: Box<dyn OnGleanEvents>,
241}
242
243static STATE: OnceCell<Mutex<State>> = OnceCell::new();
247
248#[track_caller] fn global_state() -> &'static Mutex<State> {
253 STATE.get().unwrap()
254}
255
256#[track_caller] fn maybe_global_state() -> Option<&'static Mutex<State>> {
261 STATE.get()
262}
263
264fn setup_state(state: State) {
266 if STATE.get().is_none() {
276 if STATE.set(Mutex::new(state)).is_err() {
277 log::error!(
278 "Global Glean state object is initialized already. This probably happened concurrently."
279 );
280 }
281 } else {
282 let mut lock = STATE.get().unwrap().lock().unwrap();
286 *lock = state;
287 }
288}
289
290static EVENT_LISTENERS: OnceCell<Mutex<HashMap<String, Box<dyn GleanEventListener>>>> =
293 OnceCell::new();
294
295fn event_listeners() -> &'static Mutex<HashMap<String, Box<dyn GleanEventListener>>> {
296 EVENT_LISTENERS.get_or_init(|| Mutex::new(HashMap::new()))
297}
298
299fn register_event_listener(tag: String, listener: Box<dyn GleanEventListener>) {
300 let mut lock = event_listeners().lock().unwrap();
301 lock.insert(tag, listener);
302}
303
304fn unregister_event_listener(tag: String) {
305 let mut lock = event_listeners().lock().unwrap();
306 lock.remove(&tag);
307}
308
309#[derive(Debug)]
311pub enum CallbackError {
312 UnexpectedError,
314}
315
316impl fmt::Display for CallbackError {
317 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
318 write!(f, "Unexpected error")
319 }
320}
321
322impl std::error::Error for CallbackError {}
323
324impl From<uniffi::UnexpectedUniFFICallbackError> for CallbackError {
325 fn from(_: uniffi::UnexpectedUniFFICallbackError) -> CallbackError {
326 CallbackError::UnexpectedError
327 }
328}
329
330pub trait OnGleanEvents: Send {
334 fn initialize_finished(&self);
340
341 fn trigger_upload(&self) -> Result<(), CallbackError>;
346
347 fn start_metrics_ping_scheduler(&self) -> bool;
349
350 fn cancel_uploads(&self) -> Result<(), CallbackError>;
352
353 fn shutdown(&self) -> Result<(), CallbackError> {
360 Ok(())
362 }
363}
364
365pub trait GleanEventListener: Send {
368 fn on_event_recorded(&self, id: String);
370}
371
372pub fn glean_initialize(
381 cfg: InternalConfiguration,
382 client_info: ClientInfoMetrics,
383 callbacks: Box<dyn OnGleanEvents>,
384) {
385 initialize_inner(cfg, client_info, callbacks);
386}
387
388pub fn glean_shutdown() {
390 shutdown();
391}
392
393pub fn glean_initialize_for_subprocess(cfg: InternalConfiguration) -> bool {
398 let glean = match Glean::new_for_subprocess(&cfg, true) {
399 Ok(glean) => glean,
400 Err(err) => {
401 log::error!("Failed to initialize Glean: {}", err);
402 return false;
403 }
404 };
405 if core::setup_glean(glean).is_err() {
406 return false;
407 }
408 log::info!("Glean initialized for subprocess");
409 true
410}
411
412fn initialize_inner(
413 cfg: InternalConfiguration,
414 client_info: ClientInfoMetrics,
415 callbacks: Box<dyn OnGleanEvents>,
416) {
417 if was_initialize_called() {
418 log::error!("Glean should not be initialized multiple times");
419 return;
420 }
421
422 let init_handle = thread::spawn("glean.init", move || {
423 let upload_enabled = cfg.upload_enabled;
424 let trim_data_to_registered_pings = cfg.trim_data_to_registered_pings;
425
426 if let Some(level) = cfg.log_level {
428 log::set_max_level(level)
429 }
430
431 let data_path_str = cfg.data_path.clone();
432 let data_path = Path::new(&data_path_str);
433 let internal_pings_enabled = cfg.enable_internal_pings;
434 let dir_info = if !is_test_mode() && internal_pings_enabled {
435 collect_directory_info(Path::new(&data_path))
436 } else {
437 None
438 };
439
440 let glean = match Glean::new(cfg) {
441 Ok(glean) => glean,
442 Err(err) => {
443 log::error!("Failed to initialize Glean: {}", err);
444 return;
445 }
446 };
447 if core::setup_glean(glean).is_err() {
448 return;
449 }
450
451 log::info!("Glean initialized");
452
453 core::with_glean(|glean| {
454 glean.health_metrics.init_count.add_sync(glean, 1);
455 });
456
457 setup_state(State {
458 client_info,
459 callbacks,
460 });
461
462 let mut is_first_run = false;
463 let mut dirty_flag = false;
464 let mut pings_submitted = false;
465 core::with_glean_mut(|glean| {
466 let debug_tag = PRE_INIT_DEBUG_VIEW_TAG.lock().unwrap();
469 if !debug_tag.is_empty() {
470 glean.set_debug_view_tag(&debug_tag);
471 }
472
473 let log_pigs = PRE_INIT_LOG_PINGS.load(Ordering::SeqCst);
476 if log_pigs {
477 glean.set_log_pings(log_pigs);
478 }
479
480 let source_tags = PRE_INIT_SOURCE_TAGS.lock().unwrap();
483 if !source_tags.is_empty() {
484 glean.set_source_tags(source_tags.to_vec());
485 }
486
487 dirty_flag = glean.is_dirty_flag_set();
492 glean.set_dirty_flag(false);
493
494 if dirty_flag {
498 glean.recover_session_on_dirty_flag();
499 }
500
501 let pings = PRE_INIT_PING_REGISTRATION.lock().unwrap();
504 for ping in pings.iter() {
505 glean.register_ping_type(ping);
506 }
507 let pings = PRE_INIT_PING_ENABLED.lock().unwrap();
508 for (ping, enabled) in pings.iter() {
509 glean.set_ping_enabled(ping, *enabled);
510 }
511
512 let clear_attribution = PRE_INIT_ATTRIBUTION_CLEARED.load(Ordering::SeqCst);
515 if clear_attribution {
516 glean.clear_attribution();
517 }
518 let clear_distribution = PRE_INIT_DISTRIBUTION_CLEARED.load(Ordering::SeqCst);
519 if clear_distribution {
520 glean.clear_distribution();
521 }
522 if let Some(attribution) = PRE_INIT_ATTRIBUTION.lock().unwrap().take() {
523 glean.update_attribution(attribution);
524 }
525 if let Some(distribution) = PRE_INIT_DISTRIBUTION.lock().unwrap().take() {
526 glean.update_distribution(distribution);
527 }
528
529 is_first_run = glean.is_first_run();
533 if is_first_run {
534 let state = global_state().lock().unwrap();
535 initialize_core_metrics(glean, &state.client_info);
536 }
537
538 pings_submitted = glean.on_ready_to_submit_pings(trim_data_to_registered_pings);
540 });
541
542 {
543 let state = global_state().lock().unwrap();
544 if pings_submitted || !upload_enabled {
548 if let Err(e) = state.callbacks.trigger_upload() {
549 log::error!("Triggering upload failed. Error: {}", e);
550 }
551 }
552 }
553
554 core::with_glean(|glean| {
555 glean.start_metrics_ping_scheduler();
557 });
558
559 {
567 let state = global_state().lock().unwrap();
568
569 if state.callbacks.start_metrics_ping_scheduler() {
573 if let Err(e) = state.callbacks.trigger_upload() {
574 log::error!("Triggering upload failed. Error: {}", e);
575 }
576 }
577 }
578
579 core::with_glean_mut(|glean| {
580 let state = global_state().lock().unwrap();
581
582 if !is_first_run && dirty_flag {
586 if glean.submit_ping_by_name("baseline", Some("dirty_startup")) {
592 if let Err(e) = state.callbacks.trigger_upload() {
593 log::error!("Triggering upload failed. Error: {}", e);
594 }
595 }
596 }
597
598 if !is_first_run {
602 glean.clear_application_lifetime_metrics();
603 initialize_core_metrics(glean, &state.client_info);
604 }
605 });
606
607 match dispatcher::flush_init() {
613 Ok(task_count) if task_count > 0 => {
614 core::with_glean(|glean| {
615 glean_metrics::error::preinit_tasks_overflow.add_sync(glean, task_count as i32);
616 });
617 }
618 Ok(_) => {}
619 Err(err) => log::error!("Unable to flush the preinit queue: {}", err),
620 }
621
622 if !is_test_mode() && internal_pings_enabled {
623 record_dir_info_and_submit_health_ping(dir_info, "pre_init");
626
627 let state = global_state().lock().unwrap();
628 if let Err(e) = state.callbacks.trigger_upload() {
629 log::error!("Triggering upload failed. Error: {}", e);
630 }
631 }
632 let state = global_state().lock().unwrap();
633 state.callbacks.initialize_finished();
634 })
635 .expect("Failed to spawn Glean's init thread");
636
637 INIT_HANDLES.lock().unwrap().push(init_handle);
639
640 INITIALIZE_CALLED.store(true, Ordering::SeqCst);
643
644 if dispatcher::global::is_test_mode() {
647 join_init();
648 }
649}
650
651pub fn alloc_size(ops: &mut malloc_size_of::MallocSizeOfOps) -> usize {
655 use malloc_size_of::MallocSizeOf;
656 core::with_opt_glean(|glean| glean.size_of(ops)).unwrap_or(0)
657}
658
659pub fn join_init() {
662 let mut handles = INIT_HANDLES.lock().unwrap();
663 for handle in handles.drain(..) {
664 handle.join().unwrap();
665 }
666}
667
668fn uploader_shutdown() {
676 let timer_id = core::with_glean(|glean| glean.additional_metrics.shutdown_wait.start_sync());
677 let (tx, rx) = unbounded();
678
679 let handle = thread::spawn("glean.shutdown", move || {
680 let state = global_state().lock().unwrap();
681 if let Err(e) = state.callbacks.shutdown() {
682 log::error!("Shutdown callback failed: {e:?}");
683 }
684
685 let _ = tx.send(()).ok();
687 })
688 .expect("Unable to spawn thread to wait on shutdown");
689
690 let result = rx.recv_timeout(Duration::from_secs(30));
698
699 let stop_time = zeitstempel::now_awake();
700 core::with_glean(|glean| {
701 glean
702 .additional_metrics
703 .shutdown_wait
704 .set_stop_and_accumulate(glean, timer_id, stop_time);
705 });
706
707 if result.is_err() {
708 log::warn!("Waiting for upload failed. We're shutting down.");
709 } else {
710 let _ = handle.join().ok();
711 }
712}
713
714pub fn shutdown() {
716 if !was_initialize_called() {
726 log::warn!("Shutdown called before Glean is initialized");
727 if let Err(e) = dispatcher::kill() {
728 log::error!("Can't kill dispatcher thread: {:?}", e);
729 }
730 return;
731 }
732
733 if core::global_glean().is_none() {
735 log::warn!("Shutdown called before Glean is initialized. Waiting.");
736 let _ = dispatcher::block_on_queue_timeout(Duration::from_secs(10));
744 }
745 if core::global_glean().is_none() {
747 log::warn!("Waiting for Glean initialization timed out. Exiting.");
748 if let Err(e) = dispatcher::kill() {
749 log::error!("Can't kill dispatcher thread: {:?}", e);
750 }
751 return;
752 }
753
754 crate::launch_with_glean_mut(|glean| {
756 glean.cancel_metrics_ping_scheduler();
757 glean.set_dirty_flag(false);
758 });
759
760 let timer_id = core::with_glean(|glean| {
767 glean
768 .additional_metrics
769 .shutdown_dispatcher_wait
770 .start_sync()
771 });
772 let blocked = dispatcher::block_on_queue_timeout(Duration::from_secs(10));
773
774 let stop_time = zeitstempel::now_awake();
776 core::with_glean(|glean| {
777 glean
778 .additional_metrics
779 .shutdown_dispatcher_wait
780 .set_stop_and_accumulate(glean, timer_id, stop_time);
781 });
782 if blocked.is_err() {
783 log::error!(
784 "Timeout while blocking on the dispatcher. No further shutdown cleanup will happen."
785 );
786 return;
787 }
788
789 if let Err(e) = dispatcher::shutdown() {
790 log::error!("Can't shutdown dispatcher thread: {:?}", e);
791 }
792
793 uploader_shutdown();
794
795 core::with_glean_mut(|glean| {
797 if let Err(e) = glean.persist_ping_lifetime_data() {
798 log::info!("Can't persist ping lifetime data: {:?}", e);
799 }
800
801 #[cfg(feature = "sqlite")]
802 if let Some(database) = &glean.data_store {
803 if let Err(e) = database.cleanup_submitted_pings(None) {
804 log::info!("Could not clean up submitted_pings table: {:?}", e);
805 }
806 if let Err(e) = database.run_maintenance(false) {
807 log::info!("Can't run database maintenance on shutdown: {:?}", e);
808 }
809 }
810
811 glean.close_db();
812 });
813}
814
815pub fn glean_persist_ping_lifetime_data() {
822 crate::launch_with_glean(|glean| {
824 let _ = glean.persist_ping_lifetime_data();
825 });
826}
827
828fn initialize_core_metrics(glean: &Glean, client_info: &ClientInfoMetrics) {
829 core_metrics::internal_metrics::app_build.set_sync(glean, &client_info.app_build[..]);
830 core_metrics::internal_metrics::app_display_version
831 .set_sync(glean, &client_info.app_display_version[..]);
832 core_metrics::internal_metrics::app_build_date
833 .set_sync(glean, Some(client_info.app_build_date.clone()));
834 if let Some(app_channel) = client_info.channel.as_ref() {
835 core_metrics::internal_metrics::app_channel.set_sync(glean, app_channel);
836 }
837
838 core_metrics::internal_metrics::os_version.set_sync(glean, &client_info.os_version);
839 core_metrics::internal_metrics::architecture.set_sync(glean, &client_info.architecture);
840
841 if let Some(android_sdk_version) = client_info.android_sdk_version.as_ref() {
842 core_metrics::internal_metrics::android_sdk_version.set_sync(glean, android_sdk_version);
843 }
844 if let Some(windows_build_number) = client_info.windows_build_number.as_ref() {
845 core_metrics::internal_metrics::windows_build_number.set_sync(glean, *windows_build_number);
846 }
847 if let Some(device_manufacturer) = client_info.device_manufacturer.as_ref() {
848 core_metrics::internal_metrics::device_manufacturer.set_sync(glean, device_manufacturer);
849 }
850 if let Some(device_model) = client_info.device_model.as_ref() {
851 core_metrics::internal_metrics::device_model.set_sync(glean, device_model);
852 }
853 if let Some(locale) = client_info.locale.as_ref() {
854 core_metrics::internal_metrics::locale.set_sync(glean, locale);
855 }
856}
857
858fn was_initialize_called() -> bool {
864 INITIALIZE_CALLED.load(Ordering::SeqCst)
865}
866
867#[no_mangle]
870pub extern "C" fn glean_enable_logging() {
871 #[cfg(target_os = "android")]
872 {
873 let _ = std::panic::catch_unwind(|| {
874 let filter = android_logger::FilterBuilder::new()
875 .filter_module("glean_ffi", log::LevelFilter::Debug)
876 .filter_module("glean_core", log::LevelFilter::Debug)
877 .filter_module("glean", log::LevelFilter::Debug)
878 .filter_module("glean_core::ffi", log::LevelFilter::Info)
879 .build();
880 android_logger::init_once(
881 android_logger::Config::default()
882 .with_max_level(log::LevelFilter::Debug)
883 .with_filter(filter)
884 .with_tag("libglean_ffi"),
885 );
886 log::trace!("Android logging should be hooked up!")
887 });
888 }
889
890 #[cfg(target_os = "ios")]
892 {
893 #[cfg(debug_assertions)]
896 let level = log::LevelFilter::Debug;
897 #[cfg(not(debug_assertions))]
898 let level = log::LevelFilter::Info;
899
900 let logger = oslog::OsLogger::new("org.mozilla.glean")
901 .level_filter(level)
902 .category_level_filter("glean_core::ffi", log::LevelFilter::Info);
904
905 match logger.init() {
906 Ok(_) => log::trace!("os_log should be hooked up!"),
907 Err(_) => log::warn!("os_log was already initialized"),
911 };
912 }
913
914 #[cfg(all(
918 not(target_os = "android"),
919 not(target_os = "ios"),
920 feature = "enable_env_logger"
921 ))]
922 {
923 match env_logger::try_init() {
924 Ok(_) => log::trace!("stdout logging should be hooked up!"),
925 Err(_) => log::warn!("stdout logging was already initialized"),
929 };
930 }
931}
932
933pub fn glean_set_upload_enabled(enabled: bool) {
938 if !was_initialize_called() {
939 return;
940 }
941
942 crate::launch_with_glean_mut(move |glean| {
943 let state = global_state().lock().unwrap();
944 let original_enabled = glean.is_upload_enabled();
945
946 if !enabled {
947 glean.cancel_metrics_ping_scheduler();
949 if let Err(e) = state.callbacks.cancel_uploads() {
951 log::error!("Canceling upload failed. Error: {}", e);
952 }
953 }
954
955 glean.set_upload_enabled(enabled);
956
957 if !original_enabled && enabled {
958 initialize_core_metrics(glean, &state.client_info);
959 }
960
961 if original_enabled && !enabled {
962 if let Err(e) = state.callbacks.trigger_upload() {
963 log::error!("Triggering upload failed. Error: {}", e);
964 }
965 }
966 })
967}
968
969pub fn glean_set_collection_enabled(enabled: bool) {
973 glean_set_upload_enabled(enabled)
974}
975
976pub fn glean_set_store_submitted_pings_enabled(enabled: bool) {
978 if !was_initialize_called() {
979 return;
980 }
981
982 launch_with_glean_mut(move |glean| {
983 glean.store_submitted_pings_enabled = enabled;
984 });
985}
986
987#[derive(Clone)]
989pub struct SubmittedPing {
990 pub document_id: String,
992 pub ping: String,
994 pub submitted_date: String,
996 pub uploaded_date: Option<String>,
998 pub upload_failed: Option<String>,
1000 pub payload: Option<JsonValue>,
1002}
1003
1004impl SubmittedPing {
1005 pub fn submitted_date(&self) -> DateTime<Utc> {
1007 DateTime::parse_from_rfc3339(&self.submitted_date)
1008 .map(|d| d.to_utc())
1009 .unwrap()
1010 }
1011
1012 pub fn uploaded_date(&self) -> Option<DateTime<Utc>> {
1014 self.uploaded_date.as_ref().map(|uploaded_date| {
1015 DateTime::parse_from_rfc3339(uploaded_date)
1016 .map(|d| d.to_utc())
1017 .unwrap()
1018 })
1019 }
1020
1021 pub fn upload_failed(&self) -> Option<DateTime<Utc>> {
1023 self.upload_failed.as_ref().map(|upload_failed| {
1024 DateTime::parse_from_rfc3339(upload_failed)
1025 .map(|d| d.to_utc())
1026 .unwrap()
1027 })
1028 }
1029}
1030
1031#[cfg(feature = "sqlite")]
1032impl From<database::sqlite::SubmittedPing> for SubmittedPing {
1033 fn from(value: database::sqlite::SubmittedPing) -> Self {
1034 SubmittedPing {
1035 document_id: value.document_id.clone(),
1036 ping: value.ping.clone(),
1037 submitted_date: value.submitted_date.0.to_rfc3339(),
1038 uploaded_date: value.uploaded_date.as_ref().map(|d| d.0.to_rfc3339()),
1039 upload_failed: value.upload_failed.as_ref().map(|d| d.0.to_rfc3339()),
1040 payload: value.payload(),
1041 }
1042 }
1043}
1044
1045pub fn glean_get_all_stored_submitted_pings() -> Vec<SubmittedPing> {
1047 block_on_dispatcher();
1048 core::with_glean(|glean| glean.storage().get_all_submitted_pings())
1049}
1050
1051pub fn glean_get_stored_submitted_pings_by_name(ping: String) -> Vec<SubmittedPing> {
1057 block_on_dispatcher();
1058 core::with_glean(|glean| glean.storage().get_submitted_pings_by_name(&ping))
1059}
1060
1061pub fn glean_clear_stored_submitted_pings() {
1063 launch_with_glean(|glean| {
1064 if let Err(e) = glean
1065 .storage()
1066 .cleanup_submitted_pings(Some(chrono::Utc::now()))
1067 {
1068 log::warn!("Unable to clear stored submitted pings: {:?}", e);
1069 }
1070 });
1071}
1072
1073pub fn set_ping_enabled(ping: &PingType, enabled: bool) {
1078 let ping = ping.clone();
1079 if was_initialize_called() && core::global_glean().is_some() {
1080 crate::launch_with_glean_mut(move |glean| glean.set_ping_enabled(&ping, enabled));
1081 } else {
1082 let m = &PRE_INIT_PING_ENABLED;
1083 let mut lock = m.lock().unwrap();
1084 lock.push((ping, enabled));
1085 }
1086}
1087
1088pub(crate) fn register_ping_type(ping: &PingType) {
1090 if was_initialize_called() && core::global_glean().is_some() {
1095 let ping = ping.clone();
1096 crate::launch_with_glean_mut(move |glean| {
1097 glean.register_ping_type(&ping);
1098 })
1099 } else {
1100 let m = &PRE_INIT_PING_REGISTRATION;
1105 let mut lock = m.lock().unwrap();
1106 lock.push(ping.clone());
1107 }
1108}
1109
1110pub fn glean_get_registered_ping_names() -> Vec<String> {
1116 block_on_dispatcher();
1117 core::with_glean(|glean| {
1118 glean
1119 .get_registered_ping_names()
1120 .iter()
1121 .map(|ping| ping.to_string())
1122 .collect()
1123 })
1124}
1125
1126pub fn glean_set_experiment_active(
1132 experiment_id: String,
1133 branch: String,
1134 extra: HashMap<String, String>,
1135) {
1136 launch_with_glean(|glean| glean.set_experiment_active(experiment_id, branch, extra))
1137}
1138
1139pub fn glean_set_experiment_inactive(experiment_id: String) {
1143 launch_with_glean(|glean| glean.set_experiment_inactive(experiment_id))
1144}
1145
1146pub fn glean_test_get_experiment_data(experiment_id: String) -> Option<RecordedExperiment> {
1150 block_on_dispatcher();
1151 core::with_glean(|glean| glean.test_get_experiment_data(experiment_id.to_owned()))
1152}
1153
1154pub fn glean_set_experimentation_id(experimentation_id: String) {
1158 launch_with_glean(move |glean| {
1159 glean
1160 .additional_metrics
1161 .experimentation_id
1162 .set(experimentation_id);
1163 });
1164}
1165
1166pub fn glean_test_get_experimentation_id() -> Option<String> {
1169 block_on_dispatcher();
1170 core::with_glean(|glean| glean.test_get_experimentation_id())
1171}
1172
1173pub fn glean_apply_server_knobs_config(json: String) {
1178 if json.is_empty() {
1181 return;
1182 }
1183
1184 match RemoteSettingsConfig::try_from(json) {
1185 Ok(cfg) => launch_with_glean(|glean| {
1186 glean.apply_server_knobs_config(cfg);
1187 }),
1188 Err(e) => {
1189 log::error!("Error setting metrics feature config: {:?}", e);
1190 }
1191 }
1192}
1193
1194pub fn glean_set_debug_view_tag(tag: String) -> bool {
1208 if was_initialize_called() && core::global_glean().is_some() {
1209 crate::launch_with_glean_mut(move |glean| {
1210 glean.set_debug_view_tag(&tag);
1211 });
1212 true
1213 } else {
1214 let m = &PRE_INIT_DEBUG_VIEW_TAG;
1216 let mut lock = m.lock().unwrap();
1217 *lock = tag;
1218 true
1221 }
1222}
1223
1224pub fn glean_get_debug_view_tag() -> Option<String> {
1230 block_on_dispatcher();
1231 core::with_glean(|glean| glean.debug_view_tag().map(|tag| tag.to_string()))
1232}
1233
1234pub fn glean_set_source_tags(tags: Vec<String>) -> bool {
1246 if was_initialize_called() && core::global_glean().is_some() {
1247 crate::launch_with_glean_mut(|glean| {
1248 glean.set_source_tags(tags);
1249 });
1250 true
1251 } else {
1252 let m = &PRE_INIT_SOURCE_TAGS;
1254 let mut lock = m.lock().unwrap();
1255 *lock = tags;
1256 true
1259 }
1260}
1261
1262pub fn glean_set_log_pings(value: bool) {
1271 if was_initialize_called() && core::global_glean().is_some() {
1272 crate::launch_with_glean_mut(move |glean| {
1273 glean.set_log_pings(value);
1274 });
1275 } else {
1276 PRE_INIT_LOG_PINGS.store(value, Ordering::SeqCst);
1277 }
1278}
1279
1280pub fn glean_get_log_pings() -> bool {
1286 block_on_dispatcher();
1287 core::with_glean(|glean| glean.log_pings())
1288}
1289
1290pub fn glean_handle_client_active() {
1297 dispatcher::launch(|| {
1298 core::with_glean_mut(|glean| {
1299 glean.handle_client_active();
1300 });
1301
1302 let state = global_state().lock().unwrap();
1306 if let Err(e) = state.callbacks.trigger_upload() {
1307 log::error!("Triggering upload failed. Error: {}", e);
1308 }
1309 });
1310
1311 core_metrics::internal_metrics::baseline_duration.start();
1316}
1317
1318pub fn glean_handle_client_inactive() {
1325 core_metrics::internal_metrics::baseline_duration.stop();
1329
1330 dispatcher::launch(|| {
1331 core::with_glean_mut(|glean| {
1332 glean.handle_client_inactive();
1333 });
1334
1335 let state = global_state().lock().unwrap();
1339 if let Err(e) = state.callbacks.trigger_upload() {
1340 log::error!("Triggering upload failed. Error: {}", e);
1341 }
1342 })
1343}
1344
1345pub fn glean_session_start() {
1350 launch_with_glean_mut(|glean| {
1351 if glean.session_manager.mode == session::SessionMode::Manual {
1352 glean.session_start();
1353 }
1354 });
1355}
1356
1357pub fn glean_session_end(reason: Option<String>) {
1365 launch_with_glean_mut(move |glean| {
1366 if glean.session_manager.mode == session::SessionMode::Manual {
1367 glean.session_end(reason.as_deref());
1368 }
1369 });
1370}
1371
1372pub fn glean_submit_ping_by_name(ping_name: String, reason: Option<String>) {
1374 dispatcher::launch(|| {
1375 let sent =
1376 core::with_glean(move |glean| glean.submit_ping_by_name(&ping_name, reason.as_deref()));
1377
1378 if sent {
1379 let state = global_state().lock().unwrap();
1380 if let Err(e) = state.callbacks.trigger_upload() {
1381 log::error!("Triggering upload failed. Error: {}", e);
1382 }
1383 }
1384 })
1385}
1386
1387pub fn glean_submit_ping_by_name_sync(ping_name: String, reason: Option<String>) -> bool {
1391 if !was_initialize_called() {
1392 return false;
1393 }
1394
1395 core::with_opt_glean(|glean| glean.submit_ping_by_name(&ping_name, reason.as_deref()))
1396 .unwrap_or(false)
1397}
1398
1399pub fn glean_register_event_listener(tag: String, listener: Box<dyn GleanEventListener>) {
1406 register_event_listener(tag, listener);
1407}
1408
1409pub fn glean_unregister_event_listener(tag: String) {
1417 unregister_event_listener(tag);
1418}
1419
1420pub fn glean_set_test_mode(enabled: bool) {
1424 dispatcher::global::TESTING_MODE.store(enabled, Ordering::SeqCst);
1425}
1426
1427pub fn glean_test_destroy_glean(clear_stores: bool, data_path: Option<String>) {
1431 if was_initialize_called() {
1432 join_init();
1434
1435 dispatcher::reset_dispatcher();
1436
1437 let has_storage = core::with_opt_glean(|glean| {
1440 glean
1442 .storage_opt()
1443 .map(|storage| storage.persist_ping_lifetime_data())
1444 .is_some()
1445 })
1446 .unwrap_or(false);
1447 if has_storage {
1448 uploader_shutdown();
1449 }
1450
1451 if core::global_glean().is_some() {
1452 core::with_glean_mut(|glean| {
1453 if clear_stores {
1454 glean.test_clear_all_stores()
1455 }
1456 glean.close_db()
1457 });
1458 }
1459
1460 INITIALIZE_CALLED.store(false, Ordering::SeqCst);
1462 } else if clear_stores {
1463 if let Some(data_path) = data_path {
1464 let _ = std::fs::remove_dir_all(data_path).ok();
1465 } else {
1466 log::warn!("Asked to clear stores before initialization, but no data path given.");
1467 }
1468 }
1469}
1470
1471pub fn glean_get_upload_task() -> PingUploadTask {
1473 core::with_opt_glean(|glean| glean.get_upload_task()).unwrap_or_else(PingUploadTask::done)
1474}
1475
1476pub fn glean_process_ping_upload_response(uuid: String, result: UploadResult) -> UploadTaskAction {
1478 core::with_glean(|glean| glean.process_ping_upload_response(&uuid, result))
1479}
1480
1481pub fn glean_set_dirty_flag(new_value: bool) {
1485 core::with_glean(|glean| glean.set_dirty_flag(new_value))
1486}
1487
1488pub fn glean_clear_attribution() {
1491 if was_initialize_called() && core::global_glean().is_some() {
1492 core::with_glean(|glean| glean.clear_attribution());
1493 } else {
1494 PRE_INIT_ATTRIBUTION_CLEARED.store(true, Ordering::SeqCst);
1495 _ = PRE_INIT_ATTRIBUTION.lock().unwrap().take()
1496 }
1497}
1498
1499pub fn glean_update_attribution(attribution: AttributionMetrics) {
1502 if was_initialize_called() && core::global_glean().is_some() {
1503 core::with_glean(|glean| glean.update_attribution(attribution));
1504 } else {
1505 PRE_INIT_ATTRIBUTION
1506 .lock()
1507 .unwrap()
1508 .get_or_insert(Default::default())
1509 .update(attribution);
1510 }
1511}
1512
1513pub fn glean_test_get_attribution() -> AttributionMetrics {
1518 join_init();
1519 core::with_glean(|glean| glean.test_get_attribution())
1520}
1521
1522pub fn glean_clear_distribution() {
1525 if was_initialize_called() && core::global_glean().is_some() {
1526 core::with_glean(|glean| glean.clear_distribution());
1527 } else {
1528 PRE_INIT_DISTRIBUTION_CLEARED.store(true, Ordering::SeqCst);
1529 _ = PRE_INIT_DISTRIBUTION.lock().unwrap().take()
1530 }
1531}
1532
1533pub fn glean_update_distribution(distribution: DistributionMetrics) {
1536 if was_initialize_called() && core::global_glean().is_some() {
1537 core::with_glean(|glean| glean.update_distribution(distribution));
1538 } else {
1539 PRE_INIT_DISTRIBUTION
1540 .lock()
1541 .unwrap()
1542 .get_or_insert(Default::default())
1543 .update(distribution);
1544 }
1545}
1546
1547pub fn glean_test_get_distribution() -> DistributionMetrics {
1552 join_init();
1553 core::with_glean(|glean| glean.test_get_distribution())
1554}
1555
1556#[cfg(all(not(target_os = "android"), not(target_os = "ios")))]
1557static FD_LOGGER: OnceCell<fd_logger::FdLogger> = OnceCell::new();
1558
1559#[cfg(all(not(target_os = "android"), not(target_os = "ios")))]
1572pub fn glean_enable_logging_to_fd(fd: u64) {
1573 unsafe {
1579 let logger = FD_LOGGER.get_or_init(|| fd_logger::FdLogger::new(fd));
1584 if log::set_logger(logger).is_ok() {
1588 log::set_max_level(log::LevelFilter::Debug);
1589 }
1590 }
1591}
1592
1593fn collect_directory_info(path: &Path) -> Option<serde_json::Value> {
1595 let subdirs = ["db", "events", "pending_pings"];
1597 let mut directories_info: crate::internal_metrics::DataDirectoryInfoObject =
1598 DataDirectoryInfoObject::with_capacity(subdirs.len());
1599
1600 for subdir in subdirs.iter() {
1601 let dir_path = path.join(subdir);
1602
1603 let mut directory_info = crate::internal_metrics::DataDirectoryInfoObjectItem {
1605 dir_name: Some(subdir.to_string()),
1606 dir_exists: None,
1607 dir_created: None,
1608 dir_modified: None,
1609 file_count: None,
1610 files: Vec::new(),
1611 error_message: None,
1612 };
1613
1614 if dir_path.is_dir() {
1616 directory_info.dir_exists = Some(true);
1617
1618 match fs::metadata(&dir_path) {
1620 Ok(metadata) => {
1621 if let Ok(created) = metadata.created() {
1622 directory_info.dir_created = Some(
1623 created
1624 .duration_since(UNIX_EPOCH)
1625 .unwrap_or(Duration::ZERO)
1626 .as_secs() as i64,
1627 );
1628 }
1629 if let Ok(modified) = metadata.modified() {
1630 directory_info.dir_modified = Some(
1631 modified
1632 .duration_since(UNIX_EPOCH)
1633 .unwrap_or(Duration::ZERO)
1634 .as_secs() as i64,
1635 );
1636 }
1637 }
1638 Err(error) => {
1639 let msg = format!("Unable to get metadata: {}", error.kind());
1640 directory_info.error_message = Some(msg.clone());
1641 log::warn!("{}", msg);
1642 continue;
1643 }
1644 }
1645
1646 let mut file_count = 0;
1648 let entries = match fs::read_dir(&dir_path) {
1649 Ok(entries) => entries,
1650 Err(error) => {
1651 let msg = format!("Unable to read subdir: {}", error.kind());
1652 directory_info.error_message = Some(msg.clone());
1653 log::warn!("{}", msg);
1654 continue;
1655 }
1656 };
1657 for entry in entries {
1658 directory_info.files.push(
1659 crate::internal_metrics::DataDirectoryInfoObjectItemItemFilesItem {
1660 file_name: None,
1661 file_created: None,
1662 file_modified: None,
1663 file_size: None,
1664 error_message: None,
1665 },
1666 );
1667 let file_info = directory_info.files.last_mut().unwrap();
1669 let entry = match entry {
1670 Ok(entry) => entry,
1671 Err(error) => {
1672 let msg = format!("Unable to read file: {}", error.kind());
1673 file_info.error_message = Some(msg.clone());
1674 log::warn!("{}", msg);
1675 continue;
1676 }
1677 };
1678 let file_name = match entry.file_name().into_string() {
1679 Ok(file_name) => file_name,
1680 _ => {
1681 let msg = "Unable to convert file name to string".to_string();
1682 file_info.error_message = Some(msg.clone());
1683 log::warn!("{}", msg);
1684 continue;
1685 }
1686 };
1687 let metadata = match entry.metadata() {
1688 Ok(metadata) => metadata,
1689 Err(error) => {
1690 let msg = format!("Unable to read file metadata: {}", error.kind());
1691 file_info.file_name = Some(file_name);
1692 file_info.error_message = Some(msg.clone());
1693 log::warn!("{}", msg);
1694 continue;
1695 }
1696 };
1697
1698 if metadata.is_file() {
1700 file_count += 1;
1701
1702 file_info.file_name = Some(file_name);
1704 file_info.file_created = Some(
1705 metadata
1706 .created()
1707 .unwrap_or(UNIX_EPOCH)
1708 .duration_since(UNIX_EPOCH)
1709 .unwrap_or(Duration::ZERO)
1710 .as_secs() as i64,
1711 );
1712 file_info.file_modified = Some(
1713 metadata
1714 .modified()
1715 .unwrap_or(UNIX_EPOCH)
1716 .duration_since(UNIX_EPOCH)
1717 .unwrap_or(Duration::ZERO)
1718 .as_secs() as i64,
1719 );
1720 file_info.file_size = Some(metadata.len() as i64);
1721 } else {
1722 let msg = format!("Skipping non-file entry: {}", file_name.clone());
1723 file_info.file_name = Some(file_name);
1724 file_info.error_message = Some(msg.clone());
1725 log::warn!("{}", msg);
1726 }
1727 }
1728
1729 directory_info.file_count = Some(file_count as i64);
1730 } else {
1731 directory_info.dir_exists = Some(false);
1732 }
1733
1734 directories_info.push(directory_info);
1736 }
1737
1738 if let Ok(directories_info_json) = serde_json::to_value(directories_info) {
1739 Some(directories_info_json)
1740 } else {
1741 log::error!("Failed to serialize data directory info");
1742 None
1743 }
1744}
1745
1746fn record_dir_info_and_submit_health_ping(dir_info: Option<serde_json::Value>, reason: &str) {
1747 core::with_glean(|glean| {
1748 glean
1749 .health_metrics
1750 .data_directory_info
1751 .set_sync(glean, dir_info.unwrap_or(serde_json::json!({})));
1752 glean.internal_pings.health.submit_sync(glean, Some(reason));
1753 });
1754}
1755
1756#[cfg(any(target_os = "android", target_os = "ios"))]
1758pub fn glean_enable_logging_to_fd(_fd: u64) {
1759 }
1761
1762uniffi::include_scaffolding!("glean");
1765
1766type CowString = Cow<'static, str>;
1767
1768uniffi::custom_type!(CowString, String, {
1769 remote,
1770 lower: |s| s.into_owned(),
1771 try_lift: |s| Ok(Cow::from(s))
1772});
1773
1774type JsonValue = serde_json::Value;
1775
1776uniffi::custom_type!(JsonValue, String, {
1777 remote,
1778 lower: |s| serde_json::to_string(&s).unwrap(),
1779 try_lift: |s| Ok(serde_json::from_str(&s)?)
1780});
1781
1782#[cfg(test)]
1786#[path = "lib_unit_tests.rs"]
1787mod tests;