tag2upload_service_manager/
global.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500

use crate::prelude::*;

const USER_AGENT: &str =
    "tag2upload-service-manager https://salsa.debian.org/dgit-team";

#[derive(Debug)]
pub struct Globals {
    pub cli_options: CliOptions,
    pub config: Config,
    pub state: watch::Sender<State>,
    pub worker_tracker: Arc<WorkerTracker>,
    pub db_trigger: watch::Sender<DbAssocState>,
    pub http_client: reqwest::Client,
    pub dns_resolver: hickory_resolver::TokioAsyncResolver,
    pub running: watch::Receiver<Option<Running>>,
    pub scratch_dir: String,
    pub temp_dir_retain: Option<tempfile::TempDir>,
    pub tera: Tera,
    pub test_suppl: test::GlobalSupplement,
}

#[derive(Clone, Debug)]
pub struct Running {
    pub port: u16,
}

pub struct Started {
    pub rocket: RocketIgnite,
}

/// State that is maintained in tandem with db transactions
///
/// But not stored permenantly.
#[derive(Default, Debug)]
pub struct DbAssocState {
}

#[cfg(not(test))]
mod imp_globals {
    use super::*;
    static GLOBALS: OnceLock<Arc<Globals>> = OnceLock::new();

    /// Obtain the global variables - **only for use after startup**
    ///
    /// # Panics
    ///
    /// Panics if called when globals have not yet been set,
    /// during [`startup`].
    /// 
    /// This is only allowed after [`startup`]
    /// (in `mod globals`, after `set_globals`).
    pub fn globals() -> Arc<Globals> {
        GLOBALS.get()
            .expect("Using globals() before set")
            .clone()
    }

    /// Set the global variables - call precisely once
    pub(crate) fn set_globals(g: Arc<Globals>) {
        GLOBALS.set(g)
            .expect("set_globals called more than once?");
    }
}
#[cfg(test)]
mod imp_globals {
    // In testing, we use a single-threaded tokio executor
    // provided by `#[tokio::test]`.
    //
    // We don't spawn threads, and tokio relies on the async executor.
    // So we can use thread locals (which isolates different tests).

    use super::*;
    thread_local! {
        static GLOBALS: RefCell<Option<Arc<Globals>>> =
            const { RefCell::new(None) };
    }
    pub fn globals() -> Arc<Globals> {
        GLOBALS.with_borrow(|gl| gl.clone())
            .expect("Using globals() before set")
    }
    pub(crate) fn set_globals(g: Arc<Globals>) {
        if let Some(was) = GLOBALS.replace(Some(g)) {
            panic!("set_globals called more than once, previously {was:?}");
        }
    }
}
pub use imp_globals::*;

/// Token indicating that we are shutting down
///
/// This is not an error.
/// If an error causes shutdown, `State.shutdown_reason` is `Err`,
/// but other functions may return a [`ShuttingDown`];
#[derive(Debug)]
pub struct ShuttingDown;

#[derive(Debug)]
pub struct State {
    pub shutdown_reason: Option<Result<ShuttingDown, InternalError>>,

    pub test_suppl: test::StateSupplement,
}

impl State {
    pub fn new(test_suppl: test::StateSupplement) -> Self {
        State {
            shutdown_reason: None,
            test_suppl,
        }
    }

    /// Checks for shutdown (but doesn't do anything with errors)
    pub fn check_shutdown(&self) -> Result<(), ShuttingDown> {
        match &self.shutdown_reason {
            Some(Ok(ShuttingDown)) => Err(ShuttingDown),
            Some(Err(_)) => Err(ShuttingDown),
            None => Ok(()),
        }
    }
}

impl Globals {
    /// Waits for shutdown (possibly indefinitely)
    ///
    /// Like `check_shutdown` this doesn't do anything with errors
    pub async fn await_shutdown(&self) -> ShuttingDown {
        self.state.subscribe()
            .wait_for_then(|state| {
                state.shutdown_reason
                    .as_ref()
                    .map(|_: &Result<ShuttingDown, IE>| ())
            })
            .await
            .unwrap_or_else(|e| {
                error!("shutdown handler task recv failed {e}");
            });

       ShuttingDown
    }
}

pub async fn test_hook<S: Display>(
    #[allow(unused_variables)]
    point: impl FnOnce() -> S + Send + Sync,
) {
    #[cfg(test)]
    test::hook_point(point().to_string()).await;
}


impl Globals {
    /// Start this task when we have entered the Running state
    pub fn spawn_task_running(
        self: &Arc<Self>,
        what: impl Display,
        fut: impl Future<Output = TaskResult> + Send + 'static,
    ) {
        let gl = self.clone();
        self.spawn_task_immediate(what, async move {
            let Running { .. } = gl.await_running().await?;
            fut.await
        })
    }

    /// Start this task immediately
    pub fn spawn_task_immediate(
        self: &Arc<Self>,
        what: impl Display,
        fut: impl Future<Output = TaskResult> + Send + 'static,
    ) {
        tokio::spawn({
            let what = what.to_string();
            async move {
                let _: TaskResult = AssertUnwindSafe(fut)
                    .catch_unwind()
                    .await
                    .unwrap_or_else(|_: Box<dyn Any + Send>| {
                        Err(internal!("task {what} panicked!").into())
                    });
            }
        });
    }

    /// Checks for shutdown (but doesn't do anything with errors)
    pub fn check_shutdown(&self) -> Result<(), ShuttingDown> {
        self.state.borrow().check_shutdown()
    }

    pub async fn await_running(&self) -> Result<Running, ShuttingDown> {
        match self.running.clone().wait_for_then(|p| p.clone()).await {
            Ok(y) => Ok(y),
            Err(e) => {
                debug!("shutting down, no port: {e}");
                Err(ShuttingDown)
            }
        }
    }

    pub async fn http_fetch_json<T: serde::de::DeserializeOwned>(
        &self,
        url: Url,
    ) -> Result<T, AE> {
        if let Some(fake) = &self.config.testing.fake_https_dir {
            let url = url.to_string();
            let url = url.strip_prefix("https://")
                .ok_or_else(|| anyhow!(
    "failed to strip https:// prefix from url {url:?}"
                ))?;
            let fake_file = format!("{fake}/{url}");
            let data = fs::read_to_string(&fake_file)
                .with_context(|| format!("{fake_file:?}"))
                .context("failed to read fake file")?;
            let data = serde_json::from_str(&data)
                .with_context(|| format!("{fake_file:?}"))
                .context("failed to deser fake file")?;
            return Ok(data);
        }

        self.http_client.get(url)
            .send().await.context("send")?
            .error_for_status().context("status")?
            .json().await.context("response")
    }
}

macro_rules! test_hook_url { { $url:ident } => {
    #[cfg(test)]
    let $url = crate::test::UrlMappable::map(&$url);
} }

pub fn shutdown_start_tasks(
    globals: &Arc<Globals>,
) -> Result<(), StartupError> {
    use tokio::signal::unix::{signal, SignalKind as SK};

    #[cfg(test)]
    match globals.t_shutdown_handlers() {
        Ok(()) => {},
        Err(()) => return Ok(()),
    };

    let mut terminate = signal(SK::terminate())
        .into_internal("failed to set up SIGTERM handler")?;

    globals.spawn_task_immediate("shutdown SIGTEREM watch", {
        let globals = globals.clone();
        async move {

            let () = terminate.recv().await
                .ok_or_else(|| internal!("no more SIGTERM reception?!"))?;

            globals.state.send_modify(|state| {
                match state.shutdown_reason {
                    None => {
                        info!("received SIGTERM, shutting down...");
                        state.shutdown_reason = Some(Ok(ShuttingDown));
                    }
                    Some(Err(_)) => {
                        info!("SIGTERM, but already crashing!");
                    },
                    Some(Ok(ShuttingDown)) => {
                        info!("SIGTERM, but already shutting down");
                    }
                }
            });

            Ok(TaskWorkComplete {})
        }
    });

    globals.spawn_task_immediate("shutdown handler", {
        let globals = globals.clone();
        async move {

            let _: ShuttingDown = globals.await_shutdown().await;

            let mut subscription = globals.db_trigger.subscribe();

            match loop {
                let job = find_job_deferring_shutdown()?;

                let Some::<JobRow>(job) = job
                else { break Ok(()); };

                info!(jid=%job.jid, "shutdown awaits completion of build");

                match subscription.changed().await {
                    Ok(()) => {}, // go round again
                    Err(e) => break Err(e),
                }
            } {
                Ok(()) => info!("clean shutdown complete."),
                Err(e) => error!("shutdown terminating early, watch {}", e),
            };

            unsafe {
                libc::kill(0, libc::SIGHUP);
                error!("SIGHUP didn't kill us!!");
                std::process::abort();
            }
        }
    });

    Ok(())
}

pub fn find_job_deferring_shutdown() -> Result<Option<JobRow>, IE> {
    db_transaction(TN::Readonly, |dbt| {
        dbt.bsql_query_01(bsql!("
                        SELECT * FROM jobs
                         WHERE processing != ''
                           AND status = " (JobStatus::Building) "
                      ORDER BY last_update ASC
                    "))
    })?
}

fn write_port_report_file(gl: &Arc<Globals>, port: u16) {
    if let Some(file) = gl.config.files.port_report_file.clone() {
        trace!(?file, "writing port");
        (|| {
            let f = fs::File::create(&file).context("open")?;
            let mut f = io::BufWriter::new(f);
            writeln!(f, "{port}").context("write")?;
            f.flush().context("write (flush)")?;
            Ok::<_, AE>(())
        })()
            .with_context(|| format!("{file:?}"))
            .unwrap_or_else(|ae| IE::new_without_backtrace(ae).note_only());
    }
}

pub async fn startup(
    cli_options: CliOptions,
    base_config: Figment,
    test_global_suppl: test::GlobalSupplement,
    test_state_suppl: test::StateSupplement,
    rocket_hook: impl FnOnce(RocketBuild) -> RocketBuild,
) -> Result<Started, StartupError> {
    use StartupError as SE;

    let rocket_base_config = {
        use rocket::config::*;
        rocket::Config {
            shutdown: Shutdown {
                ctrlc: false,
                signals: HashSet::new(),
                ..Default::default()
            },
            ..rocket::Config::release_default()
        }
    };

    let config = base_config
        .merge(figment::providers::Toml::file(&cli_options.config))
        // rocket::Config's Deserialize impl doesn't include any of
        // the usual defaults, so we must inject them here.
        .join(figment::providers::Serialized::default(
            "rocket",
            rocket_base_config,
        ))
        .join(figment::providers::Serialized::default(
            "rocket",
            // configuration for rocket addons that expect to find their
            // information in the configuration passed to rocket::custom,
            // but which *aren't* part of rocket::Config.
            json! {{
                // Currently there are none of these.
            }},
        ));

    let config = {
        let mut c = config;

        for s in &cli_options.config_toml {
            c = c.merge(figment::providers::Toml::string(s));
        }

        c
    };

    let rocket_config = config
        .focus("rocket");

    let config: Config = config
        .extract()
        .map_err(SE::ParseConfig)?;

    config.check()?;

    logging::setup(&config)?;

    let scratch_dir;
    let temp_dir_retain;
    match &config.files.scratch_dir {
        Some(s) => {
            scratch_dir = s.clone();
            temp_dir_retain = None;
        }
        None => {
            let td = tempfile::TempDir::new()
                .context("create temp dir")
                .map_err(SE::TempDir)?;
            scratch_dir = td.path().to_str()
                .ok_or_else(|| anyhow!("not utf-8"))
                .map_err(SE::TempDir)?
                .to_owned();
            temp_dir_retain = Some(td);
        }
    };

    remove_dir_all::remove_dir_contents(&scratch_dir)
        .context("clean out old contents of scratch directory")
        .map_err(SE::TempDir)?;

    let http_client = reqwest::Client::builder()
            .user_agent(USER_AGENT)
        .timeout(*config.timeouts.http_request)
        .build()?;

    let dns_resolver = dns::Resolver::tokio_from_system_conf()?;

    // We could use rocket_dyn_templates, but it insists on reloading
    // the /dev/null we have to supply as template_dir, whenever anyone
    // on the whole system touches it.
    let tera = routes_abstract::tera_templates(&config)?;

    let (running_tx, running) = watch::channel(None);

    let globals = Arc::new(Globals {
        cli_options,
        config,
        db_trigger: watch::Sender::new(DbAssocState::default()),
        state: watch::Sender::new(State::new(test_state_suppl)),
        worker_tracker: Default::default(),
        http_client,
        dns_resolver,
        scratch_dir,
        running,
        tera,
        temp_dir_retain,
        test_suppl: test_global_suppl,
    });
    set_globals(globals.clone());

    db_support::initialise(&globals)?;

    let listener = o2m_listener::Listener::new(&globals)?;

    shutdown_start_tasks(&globals)?;

    expire::start_task(&globals);

    let rocket = rocket::custom(&rocket_config);
    let rocket = rocket_hook(rocket);
    let rocket = routes::mount_all(rocket);

    let rocket = rocket.attach({
        let globals = globals.clone();

        rocket::fairing::AdHoc::on_liftoff(
            "spawn workers",
            |rocket: &rocket::Rocket<_>| Box::pin(
                async move {
                    if globals.state.borrow().shutdown_reason.is_some() {
                        // Typically, if this happens, an internal error
                        trace!(
                         "shutdown triggered during startup, not continuing"
                        );
                        return;
                    }
                    fetcher::start_tasks(&globals);
                    listener.start_task();

                    let port = rocket.config().port;
                    // We do this here, directly, rather than in a task
                    // hanging off the channel, because our tests check
                    // that this file has been written and use the channel
                    // as a signal to see that it has been done.
                    write_port_report_file(&globals, port);

                    let running = Running {
                        port
                    };
                    running_tx.send(Some(running.clone()))
                        .expect("no-one wanted our port");

                    info!(?running, "running");
                }
            )
        )
    });

    let rocket = rocket.ignite().await?;

    Ok(Started {
        rocket,
    })
}