smirrors 0.1.0

Automatic mirror list updater for Linux distributions
Documentation
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
//! Daemon implementation for SMirrors background service
//!
//! This module implements the main daemon loop that runs as a systemd service,
//! handling scheduled updates, signal handling, and graceful shutdown.

use crate::config::Config;
use crate::core::{MirrorTester, MirrorUpdater};
use crate::distro::{self, DistroHandler};
use crate::storage::Database;
use crate::utils;
use anyhow::{Context, Result};
use std::path::PathBuf;
use std::sync::Arc;
use tokio::signal::unix::{signal, SignalKind};
use tokio::sync::RwLock;
use tokio::time::interval;
use tracing::{debug, error, info, warn};

/// Lock file path for daemon
const LOCK_FILE: &str = "/var/run/smirrors.lock";
const PID_FILE: &str = "/var/run/smirrors.pid";

/// Daemon state
pub struct Daemon {
    /// Application configuration
    config: Arc<RwLock<Config>>,

    /// Database connection
    database: Database,

    /// Whether the daemon should continue running
    running: Arc<RwLock<bool>>,

    /// Lock file handle
    lock_file: Option<PathBuf>,

    /// PID file path
    pid_file: Option<PathBuf>,
}

impl Daemon {
    /// Create a new daemon instance
    ///
    /// # Arguments
    /// * `config` - Application configuration
    ///
    /// # Returns
    /// A new Daemon instance
    pub fn new(config: Config) -> Result<Self> {
        info!("Initializing SMirrors daemon");

        // Initialize database
        let db_path = Config::data_dir()?.join("smirrors.db");
        let database = Database::new(&db_path)
            .context("Failed to initialize database")?;

        Ok(Self {
            config: Arc::new(RwLock::new(config)),
            database,
            running: Arc::new(RwLock::new(true)),
            lock_file: None,
            pid_file: None,
        })
    }

    /// Acquire lock file to ensure single instance
    fn acquire_lock(&mut self) -> Result<()> {
        let lock_path = PathBuf::from(LOCK_FILE);

        // Check if lock file exists
        if lock_path.exists() {
            let pid_str = std::fs::read_to_string(&lock_path)
                .context("Failed to read lock file")?;

            if let Ok(pid) = pid_str.trim().parse::<i32>() {
                // Check if process is still running
                if Self::is_process_running(pid) {
                    anyhow::bail!(
                        "Another instance is already running with PID {}",
                        pid
                    );
                } else {
                    warn!("Stale lock file found, removing");
                    std::fs::remove_file(&lock_path)?;
                }
            }
        }

        // Create lock file with current PID
        let pid = std::process::id();
        std::fs::write(&lock_path, pid.to_string())
            .context("Failed to create lock file")?;

        self.lock_file = Some(lock_path);

        // Create PID file
        let pid_path = PathBuf::from(PID_FILE);
        std::fs::write(&pid_path, pid.to_string())
            .context("Failed to create PID file")?;

        self.pid_file = Some(pid_path);

        info!("Daemon lock acquired (PID: {})", pid);
        Ok(())
    }

    /// Check if a process is running
    fn is_process_running(pid: i32) -> bool {
        // Check if process exists by sending signal 0
        // This is more portable than using nix's kill
        use std::process::Command;

        Command::new("kill")
            .args(&["-0", &pid.to_string()])
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false)
    }

    /// Release lock file
    fn release_lock(&mut self) {
        if let Some(ref lock_path) = self.lock_file {
            if let Err(e) = std::fs::remove_file(lock_path) {
                warn!("Failed to remove lock file: {}", e);
            } else {
                debug!("Lock file released");
            }
        }

        if let Some(ref pid_path) = self.pid_file {
            if let Err(e) = std::fs::remove_file(pid_path) {
                warn!("Failed to remove PID file: {}", e);
            }
        }
    }

    /// Run the daemon main loop
    ///
    /// This is the main entry point for the daemon. It sets up signal
    /// handlers, acquires locks, and runs the update loop.
    pub async fn run(&mut self) -> Result<()> {
        info!("Starting SMirrors daemon");

        // Acquire lock to ensure single instance
        self.acquire_lock()
            .context("Failed to acquire daemon lock")?;

        // Set up signal handlers
        let mut sigterm = signal(SignalKind::terminate())
            .context("Failed to setup SIGTERM handler")?;
        let mut sigint = signal(SignalKind::interrupt())
            .context("Failed to setup SIGINT handler")?;
        let mut sighup = signal(SignalKind::hangup())
            .context("Failed to setup SIGHUP handler")?;
        let mut sigusr1 = signal(SignalKind::user_defined1())
            .context("Failed to setup SIGUSR1 handler")?;
        let mut sigusr2 = signal(SignalKind::user_defined2())
            .context("Failed to setup SIGUSR2 handler")?;

        // Clone for signal handlers
        let running = Arc::clone(&self.running);
        let config = Arc::clone(&self.config);

        // Main event loop
        let update_interval_secs = {
            let cfg = config.read().await;
            utils::parse_duration(&cfg.general.update_interval)?
        };

        let update_interval = std::time::Duration::from_secs(update_interval_secs);
        let mut update_timer = interval(update_interval);
        update_timer.tick().await; // Skip first immediate tick

        info!("Daemon started, update interval: {:?}", update_interval);

        loop {
            tokio::select! {
                // Handle signals
                _ = sigterm.recv() => {
                    info!("Received SIGTERM, shutting down gracefully");
                    break;
                }
                _ = sigint.recv() => {
                    info!("Received SIGINT, shutting down gracefully");
                    break;
                }
                _ = sighup.recv() => {
                    info!("Received SIGHUP, reloading configuration");
                    if let Err(e) = self.reload_config().await {
                        error!("Failed to reload configuration: {}", e);
                    }

                    // Update timer interval if it changed
                    let new_interval_secs = {
                        let cfg = config.read().await;
                        utils::parse_duration(&cfg.general.update_interval)?
                    };

                    let new_interval = std::time::Duration::from_secs(new_interval_secs);

                    if new_interval != update_interval {
                        info!("Update interval changed to {:?}", new_interval);
                        update_timer = interval(new_interval);
                        update_timer.tick().await;
                    }
                }
                _ = sigusr1.recv() => {
                    info!("Received SIGUSR1, triggering immediate update");
                    if let Err(e) = self.run_update().await {
                        error!("Update failed: {}", e);
                    }
                }
                _ = sigusr2.recv() => {
                    info!("Received SIGUSR2, running health check");
                    self.health_check().await;
                }

                // Periodic update timer
                _ = update_timer.tick() => {
                    let cfg = config.read().await;
                    if cfg.general.auto_update {
                        drop(cfg); // Release lock before update
                        info!("Running scheduled update");
                        if let Err(e) = self.run_update().await {
                            error!("Scheduled update failed: {}", e);
                        }
                    } else {
                        debug!("Auto-update is disabled, skipping");
                    }
                }

                // Check if we should stop
                else => {
                    if !*running.read().await {
                        info!("Shutdown requested");
                        break;
                    }
                }
            }
        }

        // Graceful shutdown
        info!("Performing graceful shutdown");
        self.shutdown().await?;

        Ok(())
    }

    /// Run mirror update operation
    async fn run_update(&self) -> Result<()> {
        info!("Starting mirror update");

        let start_time = std::time::Instant::now();

        // Get current configuration
        let config = self.config.read().await.clone();

        // Detect distribution
        let distro_handler = distro::detect_handler()
            .context("Failed to detect distribution")?;

        info!("Detected distribution: {}", distro_handler.name());

        // Get available mirrors
        let mirrors = distro_handler
            .get_available_mirrors()
            .await
            .context("Failed to fetch available mirrors")?;

        info!("Found {} available mirrors", mirrors.len());

        // Test mirrors
        let tester = MirrorTester::from_config(&config)?;
        let test_results = tester.test_all(mirrors, None).await;

        // Save test results
        for result in &test_results {
            if let Err(e) = self.database.save_test_result(result) {
                warn!("Failed to save test result: {}", e);
            }
        }

        // Filter and rank mirrors
        let successful = MirrorTester::filter_successful(test_results);
        let ranked = MirrorTester::sort_by_score(successful);

        info!("Successfully tested {} mirrors", ranked.len());

        // Update mirror configuration
        let mirrors_to_use: Vec<_> = ranked
            .into_iter()
            .take(config.testing.max_mirrors)
            .map(|r| r.mirror)
            .collect();

        if mirrors_to_use.is_empty() {
            warn!("No working mirrors found, keeping current configuration");
            self.database.save_update_record(
                0,
                false,
                Some("No working mirrors found".to_string()),
            )?;
            return Ok(());
        }

        // Create updater and apply changes
        let distro_handler_arc: Arc<dyn DistroHandler> = Arc::from(distro_handler);
        let updater = MirrorUpdater::new(config.clone(), distro_handler_arc)
            .context("Failed to create mirror updater")?;

        let update_result = updater
            .update(&Default::default())
            .await
            .context("Failed to update mirrors")?;

        let changed_count = update_result.mirrors_selected;

        // Record successful update
        self.database.save_update_record(
            changed_count as i64,
            true,
            None,
        )?;

        let elapsed = start_time.elapsed();
        info!(
            "Mirror update completed successfully in {:.2}s ({} mirrors changed)",
            elapsed.as_secs_f64(),
            changed_count
        );

        Ok(())
    }

    /// Reload configuration from disk
    async fn reload_config(&self) -> Result<()> {
        info!("Reloading configuration");

        let new_config = Config::load()
            .context("Failed to load configuration")?;

        let mut config = self.config.write().await;
        *config = new_config;

        info!("Configuration reloaded successfully");
        Ok(())
    }

    /// Perform health check
    async fn health_check(&self) {
        info!("Running health check");

        // Check database connectivity
        match self.database.get_stats() {
            Ok(stats) => {
                info!(
                    "Database OK: {} mirrors, {} test results",
                    stats.mirrors_count, stats.test_results_count
                );
            }
            Err(e) => {
                error!("Database health check failed: {}", e);
            }
        }

        // Check configuration validity
        let config = self.config.read().await;
        match config.validate() {
            Ok(_) => info!("Configuration OK"),
            Err(e) => error!("Configuration validation failed: {}", e),
        }

        info!("Health check completed");
    }

    /// Graceful shutdown procedure
    async fn shutdown(&mut self) -> Result<()> {
        info!("Shutting down daemon");

        // Set running flag to false
        let mut running = self.running.write().await;
        *running = false;
        drop(running);

        // Release lock files
        self.release_lock();

        // Cleanup database
        if let Err(e) = self.database.vacuum() {
            warn!("Failed to vacuum database during shutdown: {}", e);
        }

        info!("Daemon shutdown complete");
        Ok(())
    }

    /// Request daemon to stop
    pub async fn stop(&self) {
        info!("Stop requested");
        let mut running = self.running.write().await;
        *running = false;
    }

    /// Check if daemon is running
    pub async fn is_running(&self) -> bool {
        *self.running.read().await
    }
}

impl Drop for Daemon {
    fn drop(&mut self) {
        self.release_lock();
    }
}

/// Run the daemon (convenience function)
///
/// # Arguments
/// * `config_path` - Optional path to configuration file
///
/// # Returns
/// Result indicating success or failure
pub async fn run_daemon(config_path: Option<PathBuf>) -> Result<()> {
    // Load configuration
    let config = if let Some(path) = config_path {
        Config::load_from(&path)?
    } else {
        Config::load()?
    };

    // Create and run daemon
    let mut daemon = Daemon::new(config)?;
    daemon.run().await
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_daemon_creation() {
        let config = Config::default();
        // Can't fully test daemon creation without database access
        // This is more of an integration test
    }

    #[test]
    fn test_is_process_running() {
        let current_pid = std::process::id() as i32;
        assert!(Daemon::is_process_running(current_pid));
        assert!(!Daemon::is_process_running(99999999));
    }
}