Debian Codegraph @

third_party/rust/glean-core/src/scheduler.rs

raw
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 //! # Metrics Ping Scheduler
6 //!
7 //! The Metrics Ping Scheduler (MPS) is responsible for scheduling "metrics" pings.
8 //! It implements the spec described in
9 //! [the docs](https://mozilla.github.io/glean/book/user/pings/metrics.html#scheduling)
10
11 use crate::metrics::{DatetimeMetric, StringMetric, TimeUnit};
12 use crate::storage::INTERNAL_STORAGE;
13 use crate::util::local_now_with_offset;
14 use crate::{CommonMetricData, Glean, Lifetime};
15 use chrono::prelude::*;
16 use chrono::Duration;
17 use once_cell::sync::Lazy;
18 use std::sync::{Arc, Condvar, Mutex};
19 use std::thread::JoinHandle;
20
21 const SCHEDULED_HOUR: u32 = 4;
22
23 // Clippy thinks an AtomicBool would be preferred, but Condvar requires a full Mutex.
24 // See https://github.com/rust-lang/rust-clippy/issues/1516
25 #[allow(clippy::mutex_atomic)]
26 static TASK_CONDVAR: Lazy<Arc<(Mutex<bool>, Condvar)>> =
27 Lazy::new(|| Arc::new((Mutex::new(false), Condvar::new())));
28
29 /// Describes the interface for a submitter of "metrics" pings.
30 /// Used to decouple the implementation so we can test it.
31 trait MetricsPingSubmitter {
32 /// Submits a metrics ping, updating the last sent time to `now`
33 /// (which might not be _right now_ due to processing delays (or in tests))
34 fn submit_metrics_ping(&self, glean: &Glean, reason: Option<&str>, now: DateTime<FixedOffset>);
35 }
36
37 /// Describes the interface for a scheduler of "metrics" pings.
38 /// Used to decouple the implementation so we can test it.
39 trait MetricsPingScheduler {
40 /// Begins a recurring schedule of "metrics" ping submissions, on another thread.
41 /// `now` is used with `when` to determine the first schedule interval and
42 /// may not be _right now_ due to processing delays (or in tests).
43 fn start_scheduler(
44 &self,
45 submitter: impl MetricsPingSubmitter + Send + 'static,
46 now: DateTime<FixedOffset>,
47 when: When,
48 );
49 }
50
51 /// Uses Glean to submit "metrics" pings directly.
52 struct GleanMetricsPingSubmitter {}
53 impl MetricsPingSubmitter for GleanMetricsPingSubmitter {
54 fn submit_metrics_ping(&self, glean: &Glean, reason: Option<&str>, now: DateTime<FixedOffset>) {
55 glean.submit_ping_by_name("metrics", reason);
56 // Always update the collection date, irrespective of the ping being sent.
57 get_last_sent_time_metric().set_sync_chrono(glean, now);
58 }
59 }
60
61 /// Schedule "metrics" pings directly using the default behaviour.
62 struct GleanMetricsPingScheduler {}
63 impl MetricsPingScheduler for GleanMetricsPingScheduler {
64 fn start_scheduler(
65 &self,
66 submitter: impl MetricsPingSubmitter + Send + 'static,
67 now: DateTime<FixedOffset>,
68 when: When,
69 ) {
70 start_scheduler(submitter, now, when);
71 }
72 }
73
74 /// Performs startup checks to decide when to schedule the next "metrics" ping collection.
75 /// **Must** be called before draining the preinit queue.
76 /// (We're at the Language Bindings' mercy for that)
77 pub fn schedule(glean: &Glean) {
78 let now = local_now_with_offset();
79
80 let (cancelled_lock, _condvar) = &**TASK_CONDVAR;
81 if *cancelled_lock.lock().unwrap() {
82 log::debug!("Told to schedule, but already cancelled. Are we in a test?");
83 }
84 *cancelled_lock.lock().unwrap() = false; // Uncancel the thread.
85
86 let submitter = GleanMetricsPingSubmitter {};
87 let scheduler = GleanMetricsPingScheduler {};
88
89 schedule_internal(glean, submitter, scheduler, now)
90 }
91
92 /// Tells the scheduler task to exit quickly and cleanly.
93 pub fn cancel() {
94 let (cancelled_lock, condvar) = &**TASK_CONDVAR; // One `*` for Lazy, the second for Arc
95 *cancelled_lock.lock().unwrap() = true; // Cancel the scheduler thread.
96 condvar.notify_all(); // Notify any/all listening schedulers to check whether they were cancelled.
97 }
98
99 fn schedule_internal(
100 glean: &Glean,
101 submitter: impl MetricsPingSubmitter + Send + 'static,
102 scheduler: impl MetricsPingScheduler,
103 now: DateTime<FixedOffset>,
104 ) {
105 let last_sent_build_metric = get_last_sent_build_metric();
106 if let Some(last_sent_build) = last_sent_build_metric.get_value(glean, Some(INTERNAL_STORAGE)) {
107 // If `app_build` is longer than StringMetric's max length, we will always
108 // treat it as a changed build when really it isn't.
109 // This will be externally-observable as InvalidOverflow errors on both the core
110 // `client_info.app_build` metric and the scheduler's internal metric.
111 if last_sent_build != glean.app_build {
112 last_sent_build_metric.set_sync(glean, &glean.app_build);
113 log::info!("App build changed. Sending 'metrics' ping");
114 submitter.submit_metrics_ping(glean, Some("upgrade"), now);
115 scheduler.start_scheduler(submitter, now, When::Reschedule);
116 return;
117 }
118 } else {
119 // No value in last_sent_build. Better set one.
120 last_sent_build_metric.set_sync(glean, &glean.app_build);
121 }
122
123 let last_sent_time = get_last_sent_time_metric().get_value(glean, INTERNAL_STORAGE);
124 if let Some(last_sent) = last_sent_time {
125 log::info!("The 'metrics' ping was last sent on {}", last_sent);
126 }
127
128 // We aim to cover 3 cases here:
129 //
130 // 1. The ping was already collected on the current calendar day;
131 // only schedule one for collection on the next calendar day at the due time.
132 // 2. The ping was NOT collected on the current calendar day AND we're later
133 // than today's due time; collect the ping immediately.
134 // 3. The ping was NOT collected on the current calendar day BUT we still have
135 // some time to the due time; schedule for submitting the current calendar day.
136
137 let already_sent_today = last_sent_time.is_some_and(|d| d.date() == now.date());
138 if already_sent_today {
139 // Case #1
140 log::info!("The 'metrics' ping was already sent today, {}", now);
141 scheduler.start_scheduler(submitter, now, When::Tomorrow);
142 } else if now > now.date().and_hms(SCHEDULED_HOUR, 0, 0) {
143 // Case #2
144 log::info!("Sending the 'metrics' ping immediately, {}", now);
145 submitter.submit_metrics_ping(glean, Some("overdue"), now);
146 scheduler.start_scheduler(submitter, now, When::Reschedule);
147 } else {
148 // Case #3
149 log::info!("The 'metrics' collection is scheduled for today, {}", now);
150 scheduler.start_scheduler(submitter, now, When::Today);
151 }
152 }
153
154 /// "metrics" ping scheduling deadlines.
155 #[derive(Debug, PartialEq)]
156 enum When {
157 Today,
158 Tomorrow,
159 Reschedule,
160 }
161
162 impl When {
163 /// Returns the duration from now until our deadline.
164 /// Note that std::time::Duration doesn't do negative time spans, so if
165 /// our deadline has passed, this will return zero.
166 fn until(&self, now: DateTime<FixedOffset>) -> std::time::Duration {
167 let fire_date = match self {
168 Self::Today => now.date().and_hms(SCHEDULED_HOUR, 0, 0),
169 // Doesn't actually save us from being an hour off on DST because
170 // chrono doesn't know when DST changes. : (
171 Self::Tomorrow | Self::Reschedule => {
172 (now.date() + Duration::days(1)).and_hms(SCHEDULED_HOUR, 0, 0)
173 }
174 };
175 // After rust-lang/rust#73544 can use std::time::Duration::ZERO
176 (fire_date - now)
177 .to_std()
178 .unwrap_or_else(|_| std::time::Duration::from_millis(0))
179 }
180
181 /// The "metrics" ping reason corresponding to our deadline.
182 fn reason(&self) -> &'static str {
183 match self {
184 Self::Today => "today",
185 Self::Tomorrow => "tomorrow",
186 Self::Reschedule => "reschedule",
187 }
188 }
189 }
190
191 fn start_scheduler(
192 submitter: impl MetricsPingSubmitter + Send + 'static,
193 now: DateTime<FixedOffset>,
194 when: When,
195 ) -> JoinHandle<()> {
196 let pair = Arc::clone(&TASK_CONDVAR);
197 std::thread::Builder::new()
198 .name("glean.mps".into())
199 .spawn(move || {
200 let (cancelled_lock, condvar) = &*pair;
201 let mut when = when;
202 let mut now = now;
203 loop {
204 let dur = when.until(now);
205 log::info!("Scheduling for {} after {:?}, reason {:?}", now, dur, when);
206 let mut timed_out = false;
207 {
208 match condvar.wait_timeout_while(cancelled_lock.lock().unwrap(), dur, |cancelled| !*cancelled) {
209 Err(err) => {
210 log::warn!("Condvar wait failure. MPS exiting. {}", err);
211 break;
212 }
213 Ok((cancelled, wait_result)) => {
214 if *cancelled {
215 log::info!("Metrics Ping Scheduler cancelled. Exiting.");
216 break;
217 } else if wait_result.timed_out() {
218 // Can't get the global glean while holding cancelled's lock.
219 timed_out = true;
220 } else {
221 // This should be impossible. `cancelled_lock` is acquired, and
222 // `!*cancelled` is checked by the condvar before it is allowed
223 // to return from `wait_timeout_while` (I checked).
224 // So `Ok(_)` implies `*cancelled || wait_result.timed_out`.
225 log::warn!("Spurious wakeup of the MPS condvar should be impossible.");
226 }
227 }
228 }
229 }
230 // Safety:
231 // We are okay dropping the condvar's cancelled lock here because it only guards
232 // whether we're cancelled, and we've established that we weren't when we timed out.
233 // We might _now_ be cancelled at any time, in which case when we loop back over
234 // we'll immediately exit. But first we need to submit our "metrics" ping.
235 if timed_out {
236 log::info!("Time to submit our metrics ping, {:?}", when);
237 let glean = crate::core::global_glean().expect("Global Glean not present when trying to send scheduled 'metrics' ping?!").lock().unwrap();
238 submitter.submit_metrics_ping(&glean, Some(when.reason()), now);
239 when = When::Reschedule;
240 }
241 now = local_now_with_offset();
242 }
243 }).expect("Unable to spawn Metrics Ping Scheduler thread.")
244 }
245
246 fn get_last_sent_time_metric() -> DatetimeMetric {
247 DatetimeMetric::new(
248 CommonMetricData {
249 name: "last_sent_time".into(),
250 category: "mps".into(),
251 send_in_pings: vec![INTERNAL_STORAGE.into()],
252 lifetime: Lifetime::User,
253 ..Default::default()
254 },
255 TimeUnit::Minute,
256 )
257 }
258
259 fn get_last_sent_build_metric() -> StringMetric {
260 StringMetric::new(CommonMetricData {
261 name: "last_sent_build".into(),
262 category: "mps".into(),
263 send_in_pings: vec![INTERNAL_STORAGE.into()],
264 lifetime: Lifetime::User,
265 ..Default::default()
266 })
267 }
268
269 #[cfg(test)]
270 mod test {
271 use super::*;
272 use crate::tests::new_glean;
273 use std::sync::atomic::{AtomicU32, Ordering};
274
275 struct ValidatingSubmitter<F: Fn(DateTime<FixedOffset>, Option<&str>)> {
276 submit_validator: F,
277 validator_run_count: Arc<AtomicU32>,
278 }
279 struct ValidatingScheduler<F: Fn(DateTime<FixedOffset>, When)> {
280 schedule_validator: F,
281 validator_run_count: Arc<AtomicU32>,
282 }
283 impl<F: Fn(DateTime<FixedOffset>, Option<&str>)> MetricsPingSubmitter for ValidatingSubmitter<F> {
284 fn submit_metrics_ping(
285 &self,
286 _glean: &Glean,
287 reason: Option<&str>,
288 now: DateTime<FixedOffset>,
289 ) {
290 (self.submit_validator)(now, reason);
291 self.validator_run_count.fetch_add(1, Ordering::Relaxed);
292 }
293 }
294 impl<F: Fn(DateTime<FixedOffset>, When)> MetricsPingScheduler for ValidatingScheduler<F> {
295 fn start_scheduler(
296 &self,
297 _submitter: impl MetricsPingSubmitter + Send + 'static,
298 now: DateTime<FixedOffset>,
299 when: When,
300 ) {
301 (self.schedule_validator)(now, when);
302 self.validator_run_count.fetch_add(1, Ordering::Relaxed);
303 }
304 }
305
306 fn new_proxies<
307 F1: Fn(DateTime<FixedOffset>, Option<&str>),
308 F2: Fn(DateTime<FixedOffset>, When),
309 >(
310 submit_validator: F1,
311 schedule_validator: F2,
312 ) -> (
313 ValidatingSubmitter<F1>,
314 Arc<AtomicU32>,
315 ValidatingScheduler<F2>,
316 Arc<AtomicU32>,
317 ) {
318 let submitter_count = Arc::new(AtomicU32::new(0));
319 let submitter = ValidatingSubmitter {
320 submit_validator,
321 validator_run_count: Arc::clone(&submitter_count),
322 };
323 let scheduler_count = Arc::new(AtomicU32::new(0));
324 let scheduler = ValidatingScheduler {
325 schedule_validator,
326 validator_run_count: Arc::clone(&scheduler_count),
327 };
328 (submitter, submitter_count, scheduler, scheduler_count)
329 }
330
331 // Ensure on first run that we actually set the last sent build metric.
332 // (and that we send an "overdue" ping if it's after the scheduled hour)
333 #[test]
334 fn first_run_last_sent_build() {
335 let (mut glean, _t) = new_glean(None);
336
337 glean.app_build = "a build".into();
338 let lsb_metric = get_last_sent_build_metric();
339 assert_eq!(None, lsb_metric.get_value(&glean, Some(INTERNAL_STORAGE)));
340
341 let fake_now = FixedOffset::east(0)
342 .ymd(2022, 11, 15)
343 .and_hms(SCHEDULED_HOUR, 0, 1);
344
345 let (submitter, submitter_count, scheduler, scheduler_count) = new_proxies(
346 |_, reason| assert_eq!(reason, Some("overdue")),
347 |_, when| assert_eq!(when, When::Reschedule),
348 );
349
350 schedule_internal(&glean, submitter, scheduler, fake_now);
351 assert_eq!(1, submitter_count.swap(0, Ordering::Relaxed));
352 assert_eq!(1, scheduler_count.swap(0, Ordering::Relaxed));
353
354 assert_eq!(
355 Some(glean.app_build.to_string()),
356 lsb_metric.get_value(&glean, Some(INTERNAL_STORAGE))
357 );
358 }
359
360 // Ensure that if we have a different build, we immediately submit an "upgrade" ping
361 // and schedule a "reschedule" ping for tomorrow.
362 #[test]
363 fn different_app_builds_submit_and_reschedule() {
364 let (mut glean, _t) = new_glean(None);
365
366 glean.app_build = "a build".into();
367 get_last_sent_build_metric().set_sync(&glean, "a different build");
368
369 let (submitter, submitter_count, scheduler, scheduler_count) = new_proxies(
370 |_, reason| assert_eq!(reason, Some("upgrade")),
371 |_, when| assert_eq!(when, When::Reschedule),
372 );
373
374 schedule_internal(&glean, submitter, scheduler, local_now_with_offset());
375 assert_eq!(1, submitter_count.swap(0, Ordering::Relaxed));
376 assert_eq!(1, scheduler_count.swap(0, Ordering::Relaxed));
377 }
378
379 // If we've already sent a ping today, ensure we don't send a ping but we
380 // do schedule a ping for tomorrow. ("Case #1" in schedule_internal)
381 #[test]
382 fn case_1_no_submit_but_schedule_tomorrow() {
383 let (glean, _t) = new_glean(None);
384
385 let fake_now = FixedOffset::east(0).ymd(2021, 4, 30).and_hms(14, 36, 14);
386 get_last_sent_time_metric().set_sync_chrono(&glean, fake_now);
387
388 let (submitter, submitter_count, scheduler, scheduler_count) = new_proxies(
389 |_, reason| panic!("Case #1 shouldn't submit a ping! reason: {:?}", reason),
390 |_, when| assert_eq!(when, When::Tomorrow),
391 );
392 schedule_internal(&glean, submitter, scheduler, fake_now);
393 assert_eq!(0, submitter_count.swap(0, Ordering::Relaxed));
394 assert_eq!(1, scheduler_count.swap(0, Ordering::Relaxed));
395 }
396
397 // If we haven't sent a ping today and we're after the scheduled time,
398 // ensure we send a ping and then schedule a "reschedule" ping for tomorrow.
399 // ("Case #2" in schedule_internal)
400 #[test]
401 fn case_2_submit_ping_and_reschedule() {
402 let (glean, _t) = new_glean(None);
403
404 let fake_yesterday = FixedOffset::east(0)
405 .ymd(2021, 4, 29)
406 .and_hms(SCHEDULED_HOUR, 0, 1);
407 get_last_sent_time_metric().set_sync_chrono(&glean, fake_yesterday);
408 let fake_now = fake_yesterday + Duration::days(1);
409
410 let (submitter, submitter_count, scheduler, scheduler_count) = new_proxies(
411 |_, reason| assert_eq!(reason, Some("overdue")),
412 |_, when| assert_eq!(when, When::Reschedule),
413 );
414 schedule_internal(&glean, submitter, scheduler, fake_now);
415 assert_eq!(1, submitter_count.swap(0, Ordering::Relaxed));
416 assert_eq!(1, scheduler_count.swap(0, Ordering::Relaxed));
417 }
418
419 // If we haven't sent a ping today and we're before the scheduled time,
420 // ensure we don't send a ping but schedule a "today" ping for today.
421 // ("Case #3" in schedule_internal)
422 #[test]
423 fn case_3_no_submit_but_schedule_today() {
424 let (glean, _t) = new_glean(None);
425
426 let fake_yesterday =
427 FixedOffset::east(0)
428 .ymd(2021, 4, 29)
429 .and_hms(SCHEDULED_HOUR - 1, 0, 1);
430 get_last_sent_time_metric().set_sync_chrono(&glean, fake_yesterday);
431 let fake_now = fake_yesterday + Duration::days(1);
432
433 let (submitter, submitter_count, scheduler, scheduler_count) = new_proxies(
434 |_, reason| panic!("Case #3 shouldn't submit a ping! reason: {:?}", reason),
435 |_, when| assert_eq!(when, When::Today),
436 );
437 schedule_internal(&glean, submitter, scheduler, fake_now);
438 assert_eq!(0, submitter_count.swap(0, Ordering::Relaxed));
439 assert_eq!(1, scheduler_count.swap(0, Ordering::Relaxed));
440 }
441
442 // `When` is responsible for date math. Let's make sure it's correct.
443 #[test]
444 fn when_gets_at_least_some_date_math_correct() {
445 let now = FixedOffset::east(0).ymd(2021, 4, 30).and_hms(15, 2, 10);
446 // `now` is after `SCHEDULED_HOUR` so should be zero:
447 assert_eq!(std::time::Duration::from_secs(0), When::Today.until(now));
448 // If we bring it back before `SCHEDULED_HOUR` it should give us the duration:
449 let earlier = now.date().and_hms(SCHEDULED_HOUR - 1, 0, 0);
450 assert_eq!(
451 std::time::Duration::from_secs(3600),
452 When::Today.until(earlier)
453 );
454
455 // `Tomorrow` and `Reschedule` should differ only in their `reason()`
456 // 46670s is 12h57m10s (aka, the time from 15:02:10 to 04:00:00
457 // (when the timezone doesn't change between them)).
458 assert_eq!(
459 std::time::Duration::from_secs(46670),
460 When::Tomorrow.until(now)
461 );
462 assert_eq!(
463 std::time::Duration::from_secs(46670),
464 When::Reschedule.until(now)
465 );
466 assert_eq!(When::Tomorrow.until(now), When::Reschedule.until(now));
467 assert_ne!(When::Tomorrow.reason(), When::Reschedule.reason());
468 }
469
470 // Scheduler tests mutate global state and thus must not be run in parallel.
471 // Otherwise one test could cancel the other.
472 // This Mutex aims to solve that.
473 static SCHEDULER_TEST_MUTEX: Lazy<Mutex<()>> = Lazy::new(|| Mutex::new(()));
474
475 // The scheduler has been designed to be cancellable. Can we cancel it?
476 #[test]
477 fn cancellable_tasks_can_be_cancelled() {
478 // First and foremost, all scheduler tests must ensure they start uncancelled.
479 // Perils of having shared state.
480 let _test_lock = SCHEDULER_TEST_MUTEX.lock().unwrap();
481 let (cancelled_lock, _condvar) = &**TASK_CONDVAR; // One `*` for Lazy, the second for Arc
482 *cancelled_lock.lock().unwrap() = false;
483
484 // Pick a time at least two hours from the next scheduled submission.
485 // (So that this test will time out if cancellation fails).
486 let now = FixedOffset::east(0)
487 .ymd(2021, 4, 30)
488 .and_hms(SCHEDULED_HOUR - 2, 0, 0);
489
490 let proxy_factory = || {
491 new_proxies(
492 |_, reason| {
493 panic!(
494 "Shouldn't submit when testing scheduler. reason: {:?}",
495 reason
496 )
497 },
498 |_, _| panic!("Not even using the scheduler this time."),
499 )
500 };
501
502 // Test Today.
503 let (submitter, submitter_count, _, _) = proxy_factory();
504 let handle = start_scheduler(submitter, now, When::Today);
505 super::cancel();
506 handle.join().unwrap(); // Should complete immediately.
507 assert_eq!(0, submitter_count.swap(0, Ordering::Relaxed));
508
509 // Test Tomorrow.
510 let (submitter, submitter_count, _, _) = proxy_factory();
511 *cancelled_lock.lock().unwrap() = false; // Uncancel.
512 let handle = start_scheduler(submitter, now, When::Tomorrow);
513 super::cancel();
514 handle.join().unwrap(); // Should complete immediately.
515 assert_eq!(0, submitter_count.swap(0, Ordering::Relaxed));
516
517 // Test Reschedule.
518 let (submitter, submitter_count, _, _) = proxy_factory();
519 *cancelled_lock.lock().unwrap() = false; // Uncancel.
520 let handle = start_scheduler(submitter, now, When::Reschedule);
521 super::cancel();
522 handle.join().unwrap(); // Should complete immediately.
523 assert_eq!(0, submitter_count.swap(0, Ordering::Relaxed));
524 }
525
526 // We're not keen to wait like the scheduler is, but we can test a quick schedule.
527 #[test]
528 fn immediate_task_runs_immediately() {
529 // First and foremost, all scheduler tests must ensure they start uncancelled.
530 // Perils of having shared state.
531 let _test_lock = SCHEDULER_TEST_MUTEX.lock().unwrap();
532 let (cancelled_lock, _condvar) = &**TASK_CONDVAR; // One `*` for Lazy, the second for Arc
533 *cancelled_lock.lock().unwrap() = false;
534
535 // We're actually going to submit a ping from the scheduler, which requires a global glean.
536 let (glean, _t) = new_glean(None);
537 assert!(
538 !glean.schedule_metrics_pings,
539 "Real schedulers not allowed in tests!"
540 );
541 assert!(crate::core::setup_glean(glean).is_ok());
542
543 // We're choosing a time after SCHEDULED_HOUR so `When::Today` will give us a duration of 0.
544 let now = FixedOffset::east(0).ymd(2021, 4, 20).and_hms(15, 42, 0);
545
546 let (submitter, submitter_count, _, _) = new_proxies(
547 move |_, reason| {
548 assert_eq!(reason, Some("today"));
549 // After submitting the ping we expect, let's cancel this scheduler so the thread exits.
550 // (But do it on another thread because the condvar loop is currently holding `cancelled`'s mutex)
551 std::thread::spawn(super::cancel);
552 },
553 |_, _| panic!("Not using the scheduler this time."),
554 );
555
556 let handle = start_scheduler(submitter, now, When::Today);
557 handle.join().unwrap();
558 assert_eq!(1, submitter_count.swap(0, Ordering::Relaxed));
559 }
560 }