1#![allow(clippy::doc_overindented_list_items)]
6#![allow(clippy::significant_drop_in_scrutinee)]
7#![allow(clippy::uninlined_format_args)]
8#![deny(rustdoc::broken_intra_doc_links)]
9#![deny(missing_docs)]
10
11use std::borrow::Cow;
20use std::collections::HashMap;
21use std::path::Path;
22use std::sync::atomic::{AtomicBool, Ordering};
23use std::sync::{Arc, Mutex};
24use std::time::{Duration, UNIX_EPOCH};
25use std::{fmt, fs};
26
27use crossbeam_channel::unbounded;
28use log::LevelFilter;
29use malloc_size_of_derive::MallocSizeOf;
30use once_cell::sync::{Lazy, OnceCell};
31use uuid::Uuid;
32
33use metrics::RemoteSettingsConfig;
34
35mod common_metric_data;
36mod core;
37mod core_metrics;
38mod coverage;
39mod database;
40mod debug;
41mod dispatcher;
42mod error;
43mod error_recording;
44mod event_database;
45mod glean_metrics;
46mod histogram;
47mod internal_metrics;
48mod internal_pings;
49pub mod metrics;
50pub mod ping;
51mod scheduler;
52pub mod storage;
53mod system;
54#[doc(hidden)]
55pub mod thread;
56pub mod traits;
57pub mod upload;
58mod util;
59
60#[cfg(all(not(target_os = "android"), not(target_os = "ios")))]
61mod fd_logger;
62
63pub use crate::common_metric_data::{CommonMetricData, DynamicLabelType, Lifetime};
64pub use crate::core::Glean;
65pub use crate::core_metrics::{AttributionMetrics, ClientInfoMetrics, DistributionMetrics};
66use crate::dispatcher::is_test_mode;
67pub use crate::error::{Error, ErrorKind, Result};
68pub use crate::error_recording::{test_get_num_recorded_errors, ErrorType};
69pub use crate::histogram::HistogramType;
70use crate::internal_metrics::DataDirectoryInfoObject;
71pub use crate::metrics::labeled::{
72 AllowLabeled, LabeledBoolean, LabeledCounter, LabeledCustomDistribution,
73 LabeledMemoryDistribution, LabeledMetric, LabeledMetricData, LabeledQuantity, LabeledString,
74 LabeledTimingDistribution,
75};
76pub use crate::metrics::{
77 BooleanMetric, CounterMetric, CustomDistributionMetric, Datetime, DatetimeMetric,
78 DenominatorMetric, DistributionData, DualLabeledCounterMetric, EventMetric,
79 LocalCustomDistribution, LocalMemoryDistribution, LocalTimingDistribution,
80 MemoryDistributionMetric, MemoryUnit, NumeratorMetric, ObjectMetric, PingType, QuantityMetric,
81 Rate, RateMetric, RecordedEvent, RecordedExperiment, StringListMetric, StringMetric,
82 TestGetValue, TextMetric, TimeUnit, TimerId, TimespanMetric, TimingDistributionMetric,
83 UrlMetric, UuidMetric,
84};
85pub use crate::upload::{PingRequest, PingUploadTask, UploadResult, UploadTaskAction};
86
87const GLEAN_VERSION: &str = env!("CARGO_PKG_VERSION");
88const GLEAN_SCHEMA_VERSION: u32 = 1;
89const DEFAULT_MAX_EVENTS: u32 = 500;
90static KNOWN_CLIENT_ID: Lazy<Uuid> =
91 Lazy::new(|| Uuid::parse_str("c0ffeec0-ffee-c0ff-eec0-ffeec0ffeec0").unwrap());
92
93pub(crate) const PENDING_PINGS_DIRECTORY: &str = "pending_pings";
95pub(crate) const DELETION_REQUEST_PINGS_DIRECTORY: &str = "deletion_request";
96
97static INITIALIZE_CALLED: AtomicBool = AtomicBool::new(false);
101
102static PRE_INIT_DEBUG_VIEW_TAG: Mutex<String> = Mutex::new(String::new());
104static PRE_INIT_LOG_PINGS: AtomicBool = AtomicBool::new(false);
105static PRE_INIT_SOURCE_TAGS: Mutex<Vec<String>> = Mutex::new(Vec::new());
106
107static PRE_INIT_PING_REGISTRATION: Mutex<Vec<metrics::PingType>> = Mutex::new(Vec::new());
109static PRE_INIT_PING_ENABLED: Mutex<Vec<(metrics::PingType, bool)>> = Mutex::new(Vec::new());
110
111static PRE_INIT_ATTRIBUTION: Mutex<Option<AttributionMetrics>> = Mutex::new(None);
113static PRE_INIT_DISTRIBUTION: Mutex<Option<DistributionMetrics>> = Mutex::new(None);
114
115static INIT_HANDLES: Lazy<Arc<Mutex<Vec<std::thread::JoinHandle<()>>>>> =
119 Lazy::new(|| Arc::new(Mutex::new(Vec::new())));
120
121#[derive(Debug, Clone, MallocSizeOf)]
123pub struct InternalConfiguration {
124 pub upload_enabled: bool,
126 pub data_path: String,
128 pub application_id: String,
130 pub language_binding_name: String,
132 pub max_events: Option<u32>,
134 pub delay_ping_lifetime_io: bool,
136 pub app_build: String,
139 pub use_core_mps: bool,
141 pub trim_data_to_registered_pings: bool,
143 #[ignore_malloc_size_of = "external non-allocating type"]
146 pub log_level: Option<LevelFilter>,
147 pub rate_limit: Option<PingRateLimit>,
149 pub enable_event_timestamps: bool,
151 pub experimentation_id: Option<String>,
155 pub enable_internal_pings: bool,
157 pub ping_schedule: HashMap<String, Vec<String>>,
161
162 pub ping_lifetime_threshold: u64,
164 pub ping_lifetime_max_time: u64,
166}
167
168#[derive(Debug, Clone, MallocSizeOf)]
170pub struct PingRateLimit {
171 pub seconds_per_interval: u64,
173 pub pings_per_interval: u32,
175}
176
177fn launch_with_glean(callback: impl FnOnce(&Glean) + Send + 'static) {
179 dispatcher::launch(|| core::with_glean(callback));
180}
181
182fn launch_with_glean_mut(callback: impl FnOnce(&mut Glean) + Send + 'static) {
185 dispatcher::launch(|| core::with_glean_mut(callback));
186}
187
188fn block_on_dispatcher() {
192 dispatcher::block_on_queue()
193}
194
195pub fn get_timestamp_ms() -> u64 {
197 const NANOS_PER_MILLI: u64 = 1_000_000;
198 zeitstempel::now() / NANOS_PER_MILLI
199}
200
201struct State {
206 client_info: ClientInfoMetrics,
208
209 callbacks: Box<dyn OnGleanEvents>,
210}
211
212static STATE: OnceCell<Mutex<State>> = OnceCell::new();
216
217#[track_caller] fn global_state() -> &'static Mutex<State> {
222 STATE.get().unwrap()
223}
224
225#[track_caller] fn maybe_global_state() -> Option<&'static Mutex<State>> {
230 STATE.get()
231}
232
233fn setup_state(state: State) {
235 if STATE.get().is_none() {
245 if STATE.set(Mutex::new(state)).is_err() {
246 log::error!(
247 "Global Glean state object is initialized already. This probably happened concurrently."
248 );
249 }
250 } else {
251 let mut lock = STATE.get().unwrap().lock().unwrap();
255 *lock = state;
256 }
257}
258
259static EVENT_LISTENERS: OnceCell<Mutex<HashMap<String, Box<dyn GleanEventListener>>>> =
262 OnceCell::new();
263
264fn event_listeners() -> &'static Mutex<HashMap<String, Box<dyn GleanEventListener>>> {
265 EVENT_LISTENERS.get_or_init(|| Mutex::new(HashMap::new()))
266}
267
268fn register_event_listener(tag: String, listener: Box<dyn GleanEventListener>) {
269 let mut lock = event_listeners().lock().unwrap();
270 lock.insert(tag, listener);
271}
272
273fn unregister_event_listener(tag: String) {
274 let mut lock = event_listeners().lock().unwrap();
275 lock.remove(&tag);
276}
277
278#[derive(Debug)]
280pub enum CallbackError {
281 UnexpectedError,
283}
284
285impl fmt::Display for CallbackError {
286 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
287 write!(f, "Unexpected error")
288 }
289}
290
291impl std::error::Error for CallbackError {}
292
293impl From<uniffi::UnexpectedUniFFICallbackError> for CallbackError {
294 fn from(_: uniffi::UnexpectedUniFFICallbackError) -> CallbackError {
295 CallbackError::UnexpectedError
296 }
297}
298
299pub trait OnGleanEvents: Send {
303 fn initialize_finished(&self);
309
310 fn trigger_upload(&self) -> Result<(), CallbackError>;
315
316 fn start_metrics_ping_scheduler(&self) -> bool;
318
319 fn cancel_uploads(&self) -> Result<(), CallbackError>;
321
322 fn shutdown(&self) -> Result<(), CallbackError> {
329 Ok(())
331 }
332}
333
334pub trait GleanEventListener: Send {
337 fn on_event_recorded(&self, id: String);
339}
340
341pub fn glean_initialize(
350 cfg: InternalConfiguration,
351 client_info: ClientInfoMetrics,
352 callbacks: Box<dyn OnGleanEvents>,
353) {
354 initialize_inner(cfg, client_info, callbacks);
355}
356
357pub fn glean_shutdown() {
359 shutdown();
360}
361
362pub fn glean_initialize_for_subprocess(cfg: InternalConfiguration) -> bool {
367 let glean = match Glean::new_for_subprocess(&cfg, true) {
368 Ok(glean) => glean,
369 Err(err) => {
370 log::error!("Failed to initialize Glean: {}", err);
371 return false;
372 }
373 };
374 if core::setup_glean(glean).is_err() {
375 return false;
376 }
377 log::info!("Glean initialized for subprocess");
378 true
379}
380
381fn initialize_inner(
382 cfg: InternalConfiguration,
383 client_info: ClientInfoMetrics,
384 callbacks: Box<dyn OnGleanEvents>,
385) {
386 if was_initialize_called() {
387 log::error!("Glean should not be initialized multiple times");
388 return;
389 }
390
391 let init_handle = thread::spawn("glean.init", move || {
392 let upload_enabled = cfg.upload_enabled;
393 let trim_data_to_registered_pings = cfg.trim_data_to_registered_pings;
394
395 if let Some(level) = cfg.log_level {
397 log::set_max_level(level)
398 }
399
400 let data_path_str = cfg.data_path.clone();
401 let data_path = Path::new(&data_path_str);
402 let internal_pings_enabled = cfg.enable_internal_pings;
403 let dir_info = if !is_test_mode() && internal_pings_enabled {
404 collect_directory_info(Path::new(&data_path))
405 } else {
406 None
407 };
408
409 let glean = match Glean::new(cfg) {
410 Ok(glean) => glean,
411 Err(err) => {
412 log::error!("Failed to initialize Glean: {}", err);
413 return;
414 }
415 };
416 if core::setup_glean(glean).is_err() {
417 return;
418 }
419
420 log::info!("Glean initialized");
421
422 setup_state(State {
423 client_info,
424 callbacks,
425 });
426
427 let mut is_first_run = false;
428 let mut dirty_flag = false;
429 let mut pings_submitted = false;
430 core::with_glean_mut(|glean| {
431 let debug_tag = PRE_INIT_DEBUG_VIEW_TAG.lock().unwrap();
434 if !debug_tag.is_empty() {
435 glean.set_debug_view_tag(&debug_tag);
436 }
437
438 let log_pigs = PRE_INIT_LOG_PINGS.load(Ordering::SeqCst);
441 if log_pigs {
442 glean.set_log_pings(log_pigs);
443 }
444
445 let source_tags = PRE_INIT_SOURCE_TAGS.lock().unwrap();
448 if !source_tags.is_empty() {
449 glean.set_source_tags(source_tags.to_vec());
450 }
451
452 dirty_flag = glean.is_dirty_flag_set();
457 glean.set_dirty_flag(false);
458
459 let pings = PRE_INIT_PING_REGISTRATION.lock().unwrap();
462 for ping in pings.iter() {
463 glean.register_ping_type(ping);
464 }
465 let pings = PRE_INIT_PING_ENABLED.lock().unwrap();
466 for (ping, enabled) in pings.iter() {
467 glean.set_ping_enabled(ping, *enabled);
468 }
469
470 if let Some(attribution) = PRE_INIT_ATTRIBUTION.lock().unwrap().take() {
473 glean.update_attribution(attribution);
474 }
475 if let Some(distribution) = PRE_INIT_DISTRIBUTION.lock().unwrap().take() {
476 glean.update_distribution(distribution);
477 }
478
479 is_first_run = glean.is_first_run();
483 if is_first_run {
484 let state = global_state().lock().unwrap();
485 initialize_core_metrics(glean, &state.client_info);
486 }
487
488 pings_submitted = glean.on_ready_to_submit_pings(trim_data_to_registered_pings);
490 });
491
492 {
493 let state = global_state().lock().unwrap();
494 if pings_submitted || !upload_enabled {
498 if let Err(e) = state.callbacks.trigger_upload() {
499 log::error!("Triggering upload failed. Error: {}", e);
500 }
501 }
502 }
503
504 core::with_glean(|glean| {
505 glean.start_metrics_ping_scheduler();
507 });
508
509 {
517 let state = global_state().lock().unwrap();
518
519 if state.callbacks.start_metrics_ping_scheduler() {
523 if let Err(e) = state.callbacks.trigger_upload() {
524 log::error!("Triggering upload failed. Error: {}", e);
525 }
526 }
527 }
528
529 core::with_glean_mut(|glean| {
530 let state = global_state().lock().unwrap();
531
532 if !is_first_run && dirty_flag {
536 if glean.submit_ping_by_name("baseline", Some("dirty_startup")) {
542 if let Err(e) = state.callbacks.trigger_upload() {
543 log::error!("Triggering upload failed. Error: {}", e);
544 }
545 }
546 }
547
548 if !is_first_run {
552 glean.clear_application_lifetime_metrics();
553 initialize_core_metrics(glean, &state.client_info);
554 }
555 });
556
557 match dispatcher::flush_init() {
563 Ok(task_count) if task_count > 0 => {
564 core::with_glean(|glean| {
565 glean_metrics::error::preinit_tasks_overflow.add_sync(glean, task_count as i32);
566 });
567 }
568 Ok(_) => {}
569 Err(err) => log::error!("Unable to flush the preinit queue: {}", err),
570 }
571
572 if !is_test_mode() && internal_pings_enabled {
573 record_dir_info_and_submit_health_ping(dir_info, "pre_init");
576
577 record_dir_info_and_submit_health_ping(collect_directory_info(data_path), "post_init");
580 }
581 let state = global_state().lock().unwrap();
582 state.callbacks.initialize_finished();
583 })
584 .expect("Failed to spawn Glean's init thread");
585
586 INIT_HANDLES.lock().unwrap().push(init_handle);
588
589 INITIALIZE_CALLED.store(true, Ordering::SeqCst);
592
593 if dispatcher::global::is_test_mode() {
596 join_init();
597 }
598}
599
600pub fn alloc_size(ops: &mut malloc_size_of::MallocSizeOfOps) -> usize {
604 use malloc_size_of::MallocSizeOf;
605 core::with_glean(|glean| glean.size_of(ops))
606}
607
608pub fn join_init() {
611 let mut handles = INIT_HANDLES.lock().unwrap();
612 for handle in handles.drain(..) {
613 handle.join().unwrap();
614 }
615}
616
617fn uploader_shutdown() {
625 let timer_id = core::with_glean(|glean| glean.additional_metrics.shutdown_wait.start_sync());
626 let (tx, rx) = unbounded();
627
628 let handle = thread::spawn("glean.shutdown", move || {
629 let state = global_state().lock().unwrap();
630 if let Err(e) = state.callbacks.shutdown() {
631 log::error!("Shutdown callback failed: {e:?}");
632 }
633
634 let _ = tx.send(()).ok();
636 })
637 .expect("Unable to spawn thread to wait on shutdown");
638
639 let result = rx.recv_timeout(Duration::from_secs(30));
647
648 let stop_time = zeitstempel::now();
649 core::with_glean(|glean| {
650 glean
651 .additional_metrics
652 .shutdown_wait
653 .set_stop_and_accumulate(glean, timer_id, stop_time);
654 });
655
656 if result.is_err() {
657 log::warn!("Waiting for upload failed. We're shutting down.");
658 } else {
659 let _ = handle.join().ok();
660 }
661}
662
663pub fn shutdown() {
665 if !was_initialize_called() {
675 log::warn!("Shutdown called before Glean is initialized");
676 if let Err(e) = dispatcher::kill() {
677 log::error!("Can't kill dispatcher thread: {:?}", e);
678 }
679 return;
680 }
681
682 if core::global_glean().is_none() {
684 log::warn!("Shutdown called before Glean is initialized. Waiting.");
685 let _ = dispatcher::block_on_queue_timeout(Duration::from_secs(10));
693 }
694 if core::global_glean().is_none() {
696 log::warn!("Waiting for Glean initialization timed out. Exiting.");
697 if let Err(e) = dispatcher::kill() {
698 log::error!("Can't kill dispatcher thread: {:?}", e);
699 }
700 return;
701 }
702
703 crate::launch_with_glean_mut(|glean| {
705 glean.cancel_metrics_ping_scheduler();
706 glean.set_dirty_flag(false);
707 });
708
709 let timer_id = core::with_glean(|glean| {
716 glean
717 .additional_metrics
718 .shutdown_dispatcher_wait
719 .start_sync()
720 });
721 let blocked = dispatcher::block_on_queue_timeout(Duration::from_secs(10));
722
723 let stop_time = zeitstempel::now();
725 core::with_glean(|glean| {
726 glean
727 .additional_metrics
728 .shutdown_dispatcher_wait
729 .set_stop_and_accumulate(glean, timer_id, stop_time);
730 });
731 if blocked.is_err() {
732 log::error!(
733 "Timeout while blocking on the dispatcher. No further shutdown cleanup will happen."
734 );
735 return;
736 }
737
738 if let Err(e) = dispatcher::shutdown() {
739 log::error!("Can't shutdown dispatcher thread: {:?}", e);
740 }
741
742 uploader_shutdown();
743
744 core::with_glean(|glean| {
746 if let Err(e) = glean.persist_ping_lifetime_data() {
747 log::error!("Can't persist ping lifetime data: {:?}", e);
748 }
749 });
750}
751
752pub fn glean_persist_ping_lifetime_data() {
759 crate::launch_with_glean(|glean| {
761 let _ = glean.persist_ping_lifetime_data();
762 });
763}
764
765fn initialize_core_metrics(glean: &Glean, client_info: &ClientInfoMetrics) {
766 core_metrics::internal_metrics::app_build.set_sync(glean, &client_info.app_build[..]);
767 core_metrics::internal_metrics::app_display_version
768 .set_sync(glean, &client_info.app_display_version[..]);
769 core_metrics::internal_metrics::app_build_date
770 .set_sync(glean, Some(client_info.app_build_date.clone()));
771 if let Some(app_channel) = client_info.channel.as_ref() {
772 core_metrics::internal_metrics::app_channel.set_sync(glean, app_channel);
773 }
774
775 core_metrics::internal_metrics::os_version.set_sync(glean, &client_info.os_version);
776 core_metrics::internal_metrics::architecture.set_sync(glean, &client_info.architecture);
777
778 if let Some(android_sdk_version) = client_info.android_sdk_version.as_ref() {
779 core_metrics::internal_metrics::android_sdk_version.set_sync(glean, android_sdk_version);
780 }
781 if let Some(windows_build_number) = client_info.windows_build_number.as_ref() {
782 core_metrics::internal_metrics::windows_build_number.set_sync(glean, *windows_build_number);
783 }
784 if let Some(device_manufacturer) = client_info.device_manufacturer.as_ref() {
785 core_metrics::internal_metrics::device_manufacturer.set_sync(glean, device_manufacturer);
786 }
787 if let Some(device_model) = client_info.device_model.as_ref() {
788 core_metrics::internal_metrics::device_model.set_sync(glean, device_model);
789 }
790 if let Some(locale) = client_info.locale.as_ref() {
791 core_metrics::internal_metrics::locale.set_sync(glean, locale);
792 }
793}
794
795fn was_initialize_called() -> bool {
801 INITIALIZE_CALLED.load(Ordering::SeqCst)
802}
803
804#[no_mangle]
807pub extern "C" fn glean_enable_logging() {
808 #[cfg(target_os = "android")]
809 {
810 let _ = std::panic::catch_unwind(|| {
811 let filter = android_logger::FilterBuilder::new()
812 .filter_module("glean_ffi", log::LevelFilter::Debug)
813 .filter_module("glean_core", log::LevelFilter::Debug)
814 .filter_module("glean", log::LevelFilter::Debug)
815 .filter_module("glean_core::ffi", log::LevelFilter::Info)
816 .build();
817 android_logger::init_once(
818 android_logger::Config::default()
819 .with_max_level(log::LevelFilter::Debug)
820 .with_filter(filter)
821 .with_tag("libglean_ffi"),
822 );
823 log::trace!("Android logging should be hooked up!")
824 });
825 }
826
827 #[cfg(target_os = "ios")]
829 {
830 #[cfg(debug_assertions)]
833 let level = log::LevelFilter::Debug;
834 #[cfg(not(debug_assertions))]
835 let level = log::LevelFilter::Info;
836
837 let logger = oslog::OsLogger::new("org.mozilla.glean")
838 .level_filter(level)
839 .category_level_filter("glean_core::ffi", log::LevelFilter::Info);
841
842 match logger.init() {
843 Ok(_) => log::trace!("os_log should be hooked up!"),
844 Err(_) => log::warn!("os_log was already initialized"),
848 };
849 }
850
851 #[cfg(all(
855 not(target_os = "android"),
856 not(target_os = "ios"),
857 feature = "enable_env_logger"
858 ))]
859 {
860 match env_logger::try_init() {
861 Ok(_) => log::trace!("stdout logging should be hooked up!"),
862 Err(_) => log::warn!("stdout logging was already initialized"),
866 };
867 }
868}
869
870pub fn glean_set_upload_enabled(enabled: bool) {
875 if !was_initialize_called() {
876 return;
877 }
878
879 crate::launch_with_glean_mut(move |glean| {
880 let state = global_state().lock().unwrap();
881 let original_enabled = glean.is_upload_enabled();
882
883 if !enabled {
884 glean.cancel_metrics_ping_scheduler();
886 if let Err(e) = state.callbacks.cancel_uploads() {
888 log::error!("Canceling upload failed. Error: {}", e);
889 }
890 }
891
892 glean.set_upload_enabled(enabled);
893
894 if !original_enabled && enabled {
895 initialize_core_metrics(glean, &state.client_info);
896 }
897
898 if original_enabled && !enabled {
899 if let Err(e) = state.callbacks.trigger_upload() {
900 log::error!("Triggering upload failed. Error: {}", e);
901 }
902 }
903 })
904}
905
906pub fn glean_set_collection_enabled(enabled: bool) {
910 glean_set_upload_enabled(enabled)
911}
912
913pub fn set_ping_enabled(ping: &PingType, enabled: bool) {
918 let ping = ping.clone();
919 if was_initialize_called() && core::global_glean().is_some() {
920 crate::launch_with_glean_mut(move |glean| glean.set_ping_enabled(&ping, enabled));
921 } else {
922 let m = &PRE_INIT_PING_ENABLED;
923 let mut lock = m.lock().unwrap();
924 lock.push((ping, enabled));
925 }
926}
927
928pub(crate) fn register_ping_type(ping: &PingType) {
930 if was_initialize_called() && core::global_glean().is_some() {
935 let ping = ping.clone();
936 crate::launch_with_glean_mut(move |glean| {
937 glean.register_ping_type(&ping);
938 })
939 } else {
940 let m = &PRE_INIT_PING_REGISTRATION;
945 let mut lock = m.lock().unwrap();
946 lock.push(ping.clone());
947 }
948}
949
950pub fn glean_get_registered_ping_names() -> Vec<String> {
956 block_on_dispatcher();
957 core::with_glean(|glean| {
958 glean
959 .get_registered_ping_names()
960 .iter()
961 .map(|ping| ping.to_string())
962 .collect()
963 })
964}
965
966pub fn glean_set_experiment_active(
972 experiment_id: String,
973 branch: String,
974 extra: HashMap<String, String>,
975) {
976 launch_with_glean(|glean| glean.set_experiment_active(experiment_id, branch, extra))
977}
978
979pub fn glean_set_experiment_inactive(experiment_id: String) {
983 launch_with_glean(|glean| glean.set_experiment_inactive(experiment_id))
984}
985
986pub fn glean_test_get_experiment_data(experiment_id: String) -> Option<RecordedExperiment> {
990 block_on_dispatcher();
991 core::with_glean(|glean| glean.test_get_experiment_data(experiment_id.to_owned()))
992}
993
994pub fn glean_set_experimentation_id(experimentation_id: String) {
998 launch_with_glean(move |glean| {
999 glean
1000 .additional_metrics
1001 .experimentation_id
1002 .set(experimentation_id);
1003 });
1004}
1005
1006pub fn glean_test_get_experimentation_id() -> Option<String> {
1009 block_on_dispatcher();
1010 core::with_glean(|glean| glean.test_get_experimentation_id())
1011}
1012
1013pub fn glean_apply_server_knobs_config(json: String) {
1018 if json.is_empty() {
1021 return;
1022 }
1023
1024 match RemoteSettingsConfig::try_from(json) {
1025 Ok(cfg) => launch_with_glean(|glean| {
1026 glean.apply_server_knobs_config(cfg);
1027 }),
1028 Err(e) => {
1029 log::error!("Error setting metrics feature config: {:?}", e);
1030 }
1031 }
1032}
1033
1034pub fn glean_set_debug_view_tag(tag: String) -> bool {
1048 if was_initialize_called() && core::global_glean().is_some() {
1049 crate::launch_with_glean_mut(move |glean| {
1050 glean.set_debug_view_tag(&tag);
1051 });
1052 true
1053 } else {
1054 let m = &PRE_INIT_DEBUG_VIEW_TAG;
1056 let mut lock = m.lock().unwrap();
1057 *lock = tag;
1058 true
1061 }
1062}
1063
1064pub fn glean_get_debug_view_tag() -> Option<String> {
1070 block_on_dispatcher();
1071 core::with_glean(|glean| glean.debug_view_tag().map(|tag| tag.to_string()))
1072}
1073
1074pub fn glean_set_source_tags(tags: Vec<String>) -> bool {
1086 if was_initialize_called() && core::global_glean().is_some() {
1087 crate::launch_with_glean_mut(|glean| {
1088 glean.set_source_tags(tags);
1089 });
1090 true
1091 } else {
1092 let m = &PRE_INIT_SOURCE_TAGS;
1094 let mut lock = m.lock().unwrap();
1095 *lock = tags;
1096 true
1099 }
1100}
1101
1102pub fn glean_set_log_pings(value: bool) {
1111 if was_initialize_called() && core::global_glean().is_some() {
1112 crate::launch_with_glean_mut(move |glean| {
1113 glean.set_log_pings(value);
1114 });
1115 } else {
1116 PRE_INIT_LOG_PINGS.store(value, Ordering::SeqCst);
1117 }
1118}
1119
1120pub fn glean_get_log_pings() -> bool {
1126 block_on_dispatcher();
1127 core::with_glean(|glean| glean.log_pings())
1128}
1129
1130pub fn glean_handle_client_active() {
1137 dispatcher::launch(|| {
1138 core::with_glean_mut(|glean| {
1139 glean.handle_client_active();
1140 });
1141
1142 let state = global_state().lock().unwrap();
1146 if let Err(e) = state.callbacks.trigger_upload() {
1147 log::error!("Triggering upload failed. Error: {}", e);
1148 }
1149 });
1150
1151 core_metrics::internal_metrics::baseline_duration.start();
1156}
1157
1158pub fn glean_handle_client_inactive() {
1165 core_metrics::internal_metrics::baseline_duration.stop();
1169
1170 dispatcher::launch(|| {
1171 core::with_glean_mut(|glean| {
1172 glean.handle_client_inactive();
1173 });
1174
1175 let state = global_state().lock().unwrap();
1179 if let Err(e) = state.callbacks.trigger_upload() {
1180 log::error!("Triggering upload failed. Error: {}", e);
1181 }
1182 })
1183}
1184
1185pub fn glean_submit_ping_by_name(ping_name: String, reason: Option<String>) {
1187 dispatcher::launch(|| {
1188 let sent =
1189 core::with_glean(move |glean| glean.submit_ping_by_name(&ping_name, reason.as_deref()));
1190
1191 if sent {
1192 let state = global_state().lock().unwrap();
1193 if let Err(e) = state.callbacks.trigger_upload() {
1194 log::error!("Triggering upload failed. Error: {}", e);
1195 }
1196 }
1197 })
1198}
1199
1200pub fn glean_submit_ping_by_name_sync(ping_name: String, reason: Option<String>) -> bool {
1204 if !was_initialize_called() {
1205 return false;
1206 }
1207
1208 core::with_opt_glean(|glean| glean.submit_ping_by_name(&ping_name, reason.as_deref()))
1209 .unwrap_or(false)
1210}
1211
1212pub fn glean_register_event_listener(tag: String, listener: Box<dyn GleanEventListener>) {
1219 register_event_listener(tag, listener);
1220}
1221
1222pub fn glean_unregister_event_listener(tag: String) {
1230 unregister_event_listener(tag);
1231}
1232
1233pub fn glean_set_test_mode(enabled: bool) {
1237 dispatcher::global::TESTING_MODE.store(enabled, Ordering::SeqCst);
1238}
1239
1240pub fn glean_test_destroy_glean(clear_stores: bool, data_path: Option<String>) {
1244 if was_initialize_called() {
1245 join_init();
1247
1248 dispatcher::reset_dispatcher();
1249
1250 let has_storage = core::with_opt_glean(|glean| {
1253 glean
1255 .storage_opt()
1256 .map(|storage| storage.persist_ping_lifetime_data())
1257 .is_some()
1258 })
1259 .unwrap_or(false);
1260 if has_storage {
1261 uploader_shutdown();
1262 }
1263
1264 if core::global_glean().is_some() {
1265 core::with_glean_mut(|glean| {
1266 if clear_stores {
1267 glean.test_clear_all_stores()
1268 }
1269 glean.destroy_db()
1270 });
1271 }
1272
1273 INITIALIZE_CALLED.store(false, Ordering::SeqCst);
1275 } else if clear_stores {
1276 if let Some(data_path) = data_path {
1277 let _ = std::fs::remove_dir_all(data_path).ok();
1278 } else {
1279 log::warn!("Asked to clear stores before initialization, but no data path given.");
1280 }
1281 }
1282}
1283
1284pub fn glean_get_upload_task() -> PingUploadTask {
1286 core::with_opt_glean(|glean| glean.get_upload_task()).unwrap_or_else(PingUploadTask::done)
1287}
1288
1289pub fn glean_process_ping_upload_response(uuid: String, result: UploadResult) -> UploadTaskAction {
1291 core::with_glean(|glean| glean.process_ping_upload_response(&uuid, result))
1292}
1293
1294pub fn glean_set_dirty_flag(new_value: bool) {
1298 core::with_glean(|glean| glean.set_dirty_flag(new_value))
1299}
1300
1301pub fn glean_update_attribution(attribution: AttributionMetrics) {
1304 if was_initialize_called() && core::global_glean().is_some() {
1305 core::with_glean(|glean| glean.update_attribution(attribution));
1306 } else {
1307 PRE_INIT_ATTRIBUTION
1308 .lock()
1309 .unwrap()
1310 .get_or_insert(Default::default())
1311 .update(attribution);
1312 }
1313}
1314
1315pub fn glean_test_get_attribution() -> AttributionMetrics {
1320 join_init();
1321 core::with_glean(|glean| glean.test_get_attribution())
1322}
1323
1324pub fn glean_update_distribution(distribution: DistributionMetrics) {
1327 if was_initialize_called() && core::global_glean().is_some() {
1328 core::with_glean(|glean| glean.update_distribution(distribution));
1329 } else {
1330 PRE_INIT_DISTRIBUTION
1331 .lock()
1332 .unwrap()
1333 .get_or_insert(Default::default())
1334 .update(distribution);
1335 }
1336}
1337
1338pub fn glean_test_get_distribution() -> DistributionMetrics {
1343 join_init();
1344 core::with_glean(|glean| glean.test_get_distribution())
1345}
1346
1347#[cfg(all(not(target_os = "android"), not(target_os = "ios")))]
1348static FD_LOGGER: OnceCell<fd_logger::FdLogger> = OnceCell::new();
1349
1350#[cfg(all(not(target_os = "android"), not(target_os = "ios")))]
1363pub fn glean_enable_logging_to_fd(fd: u64) {
1364 unsafe {
1370 let logger = FD_LOGGER.get_or_init(|| fd_logger::FdLogger::new(fd));
1375 if log::set_logger(logger).is_ok() {
1379 log::set_max_level(log::LevelFilter::Debug);
1380 }
1381 }
1382}
1383
1384fn collect_directory_info(path: &Path) -> Option<serde_json::Value> {
1386 let subdirs = ["db", "events", "pending_pings"];
1388 let mut directories_info: crate::internal_metrics::DataDirectoryInfoObject =
1389 DataDirectoryInfoObject::with_capacity(subdirs.len());
1390
1391 for subdir in subdirs.iter() {
1392 let dir_path = path.join(subdir);
1393
1394 let mut directory_info = crate::internal_metrics::DataDirectoryInfoObjectItem {
1396 dir_name: Some(subdir.to_string()),
1397 dir_exists: None,
1398 dir_created: None,
1399 dir_modified: None,
1400 file_count: None,
1401 files: Vec::new(),
1402 error_message: None,
1403 };
1404
1405 if dir_path.is_dir() {
1407 directory_info.dir_exists = Some(true);
1408
1409 match fs::metadata(&dir_path) {
1411 Ok(metadata) => {
1412 if let Ok(created) = metadata.created() {
1413 directory_info.dir_created = Some(
1414 created
1415 .duration_since(UNIX_EPOCH)
1416 .unwrap_or(Duration::ZERO)
1417 .as_secs() as i64,
1418 );
1419 }
1420 if let Ok(modified) = metadata.modified() {
1421 directory_info.dir_modified = Some(
1422 modified
1423 .duration_since(UNIX_EPOCH)
1424 .unwrap_or(Duration::ZERO)
1425 .as_secs() as i64,
1426 );
1427 }
1428 }
1429 Err(error) => {
1430 let msg = format!("Unable to get metadata: {}", error.kind());
1431 directory_info.error_message = Some(msg.clone());
1432 log::warn!("{}", msg);
1433 continue;
1434 }
1435 }
1436
1437 let mut file_count = 0;
1439 let entries = match fs::read_dir(&dir_path) {
1440 Ok(entries) => entries,
1441 Err(error) => {
1442 let msg = format!("Unable to read subdir: {}", error.kind());
1443 directory_info.error_message = Some(msg.clone());
1444 log::warn!("{}", msg);
1445 continue;
1446 }
1447 };
1448 for entry in entries {
1449 directory_info.files.push(
1450 crate::internal_metrics::DataDirectoryInfoObjectItemItemFilesItem {
1451 file_name: None,
1452 file_created: None,
1453 file_modified: None,
1454 file_size: None,
1455 error_message: None,
1456 },
1457 );
1458 let file_info = directory_info.files.last_mut().unwrap();
1460 let entry = match entry {
1461 Ok(entry) => entry,
1462 Err(error) => {
1463 let msg = format!("Unable to read file: {}", error.kind());
1464 file_info.error_message = Some(msg.clone());
1465 log::warn!("{}", msg);
1466 continue;
1467 }
1468 };
1469 let file_name = match entry.file_name().into_string() {
1470 Ok(file_name) => file_name,
1471 _ => {
1472 let msg = "Unable to convert file name to string".to_string();
1473 file_info.error_message = Some(msg.clone());
1474 log::warn!("{}", msg);
1475 continue;
1476 }
1477 };
1478 let metadata = match entry.metadata() {
1479 Ok(metadata) => metadata,
1480 Err(error) => {
1481 let msg = format!("Unable to read file metadata: {}", error.kind());
1482 file_info.file_name = Some(file_name);
1483 file_info.error_message = Some(msg.clone());
1484 log::warn!("{}", msg);
1485 continue;
1486 }
1487 };
1488
1489 if metadata.is_file() {
1491 file_count += 1;
1492
1493 file_info.file_name = Some(file_name);
1495 file_info.file_created = Some(
1496 metadata
1497 .created()
1498 .unwrap_or(UNIX_EPOCH)
1499 .duration_since(UNIX_EPOCH)
1500 .unwrap_or(Duration::ZERO)
1501 .as_secs() as i64,
1502 );
1503 file_info.file_modified = Some(
1504 metadata
1505 .modified()
1506 .unwrap_or(UNIX_EPOCH)
1507 .duration_since(UNIX_EPOCH)
1508 .unwrap_or(Duration::ZERO)
1509 .as_secs() as i64,
1510 );
1511 file_info.file_size = Some(metadata.len() as i64);
1512 } else {
1513 let msg = format!("Skipping non-file entry: {}", file_name.clone());
1514 file_info.file_name = Some(file_name);
1515 file_info.error_message = Some(msg.clone());
1516 log::warn!("{}", msg);
1517 }
1518 }
1519
1520 directory_info.file_count = Some(file_count as i64);
1521 } else {
1522 directory_info.dir_exists = Some(false);
1523 }
1524
1525 directories_info.push(directory_info);
1527 }
1528
1529 if let Ok(directories_info_json) = serde_json::to_value(directories_info) {
1530 Some(directories_info_json)
1531 } else {
1532 log::error!("Failed to serialize data directory info");
1533 None
1534 }
1535}
1536
1537fn record_dir_info_and_submit_health_ping(dir_info: Option<serde_json::Value>, reason: &str) {
1538 core::with_glean(|glean| {
1539 glean
1540 .health_metrics
1541 .data_directory_info
1542 .set_sync(glean, dir_info.unwrap_or(serde_json::json!({})));
1543 glean.internal_pings.health.submit_sync(glean, Some(reason));
1544 });
1545}
1546
1547#[cfg(any(target_os = "android", target_os = "ios"))]
1549pub fn glean_enable_logging_to_fd(_fd: u64) {
1550 }
1552
1553#[allow(missing_docs)]
1554#[allow(clippy::all)]
1556mod ffi {
1557 use super::*;
1558 uniffi::include_scaffolding!("glean");
1559
1560 type CowString = Cow<'static, str>;
1561
1562 uniffi::custom_type!(CowString, String, {
1563 remote,
1564 lower: |s| s.into_owned(),
1565 try_lift: |s| Ok(Cow::from(s))
1566 });
1567
1568 type JsonValue = serde_json::Value;
1569
1570 uniffi::custom_type!(JsonValue, String, {
1571 remote,
1572 lower: |s| serde_json::to_string(&s).unwrap(),
1573 try_lift: |s| Ok(serde_json::from_str(&s)?)
1574 });
1575}
1576pub use ffi::*;
1577
1578#[cfg(test)]
1580#[path = "lib_unit_tests.rs"]
1581mod tests;