geist_supervisor 0.1.28

Generic OTA supervisor for field devices
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
//! Backup Manager
//!
//! Handles backup and restore operations for OTA updates.

use crate::utils::paths::get_home_directory;
use anyhow::{Context, Result};
use std::fs;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
use tracing::{info, warn};

/// Manages backup operations for OTA updates
#[derive(Debug)]
pub struct BackupManager {
    backup_dir: PathBuf,
}

impl BackupManager {
    /// Create a new backup manager
    pub fn new() -> Result<Self> {
        // In test builds, always use an isolated temp directory to avoid
        // depending on HOME env var (which causes races in parallel tests)
        if cfg!(test) {
            let temp_backup_dir = std::env::temp_dir().join("geist-supervisor-test-backups");
            fs::create_dir_all(&temp_backup_dir)
                .context("Failed to create test backup directory")?;
            return Ok(Self {
                backup_dir: temp_backup_dir,
            });
        }

        // Get user's backup directory using XDG-compliant path
        let home_dir = get_home_directory();
        let backup_dir = PathBuf::from(home_dir).join(".local/share/geist-supervisor/backups");

        // Ensure backup directory exists
        match fs::create_dir_all(&backup_dir) {
            Ok(()) => {
                info!("Backup directory ready: {}", backup_dir.display());
            }
            Err(e) => {
                // In non-test environment, try temp directory as fallback
                let is_test_env = std::env::var("GEIST_APP_BINARY_PATH_TEST").is_ok();
                if is_test_env || e.kind() == std::io::ErrorKind::Unsupported {
                    warn!(
                        "Failed to create backup directory: {}, using temp directory",
                        e
                    );
                    let temp_backup_dir = std::env::temp_dir().join("geist-supervisor-backups");
                    fs::create_dir_all(&temp_backup_dir)
                        .context("Failed to create temporary backup directory")?;
                    return Ok(Self {
                        backup_dir: temp_backup_dir,
                    });
                } else {
                    return Err(e).context("Failed to create backup directory");
                }
            }
        }

        Ok(Self { backup_dir })
    }

    /// Create a backup manager with an explicit backup directory (useful for testing)
    pub fn with_backup_dir(backup_dir: PathBuf) -> Result<Self> {
        fs::create_dir_all(&backup_dir).context("Failed to create backup directory")?;
        Ok(Self { backup_dir })
    }

    /// Create a backup of the current binary
    pub fn create_backup(&self, source_path: &Path) -> Result<PathBuf> {
        if !source_path.exists() {
            anyhow::bail!("Source binary does not exist: {}", source_path.display());
        }

        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();

        let binary_name = source_path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("binary");

        let backup_filename = format!("{}.backup.{}", binary_name, timestamp);
        let backup_path = self.backup_dir.join(backup_filename);

        info!(
            "Creating backup: {} -> {}",
            source_path.display(),
            backup_path.display()
        );

        fs::copy(source_path, &backup_path).context("Failed to create backup")?;

        // Verify backup integrity
        self.verify_backup_integrity(source_path, &backup_path)?;

        info!("Backup created successfully: {}", backup_path.display());
        Ok(backup_path)
    }

    /// Restore from a backup
    pub fn restore_from_backup(
        &self,
        backup_path: &Path,
        target_path: &Path,
        service_manager: &crate::services::ota::ServiceManager,
    ) -> Result<()> {
        if !backup_path.exists() {
            anyhow::bail!("Backup file does not exist: {}", backup_path.display());
        }

        info!(
            "Restoring from backup: {} -> {}",
            backup_path.display(),
            target_path.display()
        );

        // Stop service before restoration
        if let Err(e) = service_manager.stop_service() {
            warn!("Failed to stop service before restoration: {}", e);
        }

        // Create parent directory if it doesn't exist
        let parent = target_path
            .parent()
            .ok_or_else(|| anyhow::anyhow!("Target path has no parent directory"))?;
        if !parent.exists() {
            fs::create_dir_all(parent).context("Failed to create target directory")?;
        }

        // Atomic restore: copy backup to temp file in target's parent dir, then rename
        let tmp = tempfile::Builder::new()
            .prefix(".geist_restore_")
            .tempfile_in(parent)
            .context("Failed to create temp file for atomic restore")?;

        fs::copy(backup_path, tmp.path()).context("Failed to copy backup to temp file")?;

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            fs::set_permissions(tmp.path(), fs::Permissions::from_mode(0o755))
                .context("Failed to set permissions on restored binary")?;
        }

        tmp.persist(target_path)
            .context("Failed to atomically rename restored binary into place")?;

        // Start service after restoration
        if let Err(e) = service_manager.start_service() {
            warn!("Failed to start service after restoration: {}", e);
        }

        info!("Restoration completed successfully");
        Ok(())
    }

    /// List available backups
    pub fn list_backups(&self) -> Result<Vec<String>> {
        let mut backups = Vec::new();

        if !self.backup_dir.exists() {
            return Ok(backups);
        }

        let entries = fs::read_dir(&self.backup_dir).context("Failed to read backup directory")?;

        for entry in entries {
            let entry = entry.context("Failed to read directory entry")?;
            let filename = entry.file_name();

            if let Some(name) = filename.to_str() {
                if name.contains(".backup.") {
                    backups.push(name.to_string());
                }
            }
        }

        // Sort backups by timestamp (newest first)
        backups.sort_by(|a, b| {
            let extract_timestamp = |s: &str| -> u64 {
                if let Some(pos) = s.rfind('.') {
                    s[pos + 1..].parse().unwrap_or(0)
                } else {
                    0
                }
            };

            let timestamp_b = extract_timestamp(b);
            let timestamp_a = extract_timestamp(a);
            timestamp_b.cmp(&timestamp_a)
        });

        Ok(backups)
    }

    /// Get the full path to a backup by name
    pub fn get_backup_path(&self, backup_name: &str) -> Result<PathBuf> {
        Ok(self.backup_dir.join(backup_name))
    }

    /// Get the backup directory path
    pub fn backup_dir(&self) -> &PathBuf {
        &self.backup_dir
    }

    /// Check if a backup exists
    pub fn backup_exists(&self, backup_name: &str) -> bool {
        self.backup_dir.join(backup_name).exists()
    }

    /// Cleanup old backups, keeping only the specified number
    pub fn cleanup_old_backups(&self, keep_count: usize) -> Result<()> {
        let backups = self.list_backups()?;

        if backups.len() <= keep_count {
            info!(
                "No old backups to clean up ({} backups, keeping {})",
                backups.len(),
                keep_count
            );
            return Ok(());
        }

        let backups_to_remove = &backups[keep_count..];

        for backup_name in backups_to_remove {
            let backup_path = self.backup_dir.join(backup_name);

            match fs::remove_file(&backup_path) {
                Ok(()) => {
                    info!("Removed old backup: {}", backup_name);
                }
                Err(e) => {
                    warn!("Failed to remove old backup {}: {}", backup_name, e);
                }
            }
        }

        info!(
            "Cleanup completed. Kept {} backups, removed {} old backups",
            keep_count,
            backups_to_remove.len()
        );
        Ok(())
    }

    /// Verify backup integrity by comparing file sizes and basic metadata
    fn verify_backup_integrity(&self, original: &Path, backup: &Path) -> Result<()> {
        let original_metadata =
            fs::metadata(original).context("Failed to get original file metadata")?;
        let backup_metadata = fs::metadata(backup).context("Failed to get backup file metadata")?;

        if original_metadata.len() != backup_metadata.len() {
            anyhow::bail!(
                "Backup integrity check failed: size mismatch (original: {} bytes, backup: {} bytes)",
                original_metadata.len(),
                backup_metadata.len()
            );
        }

        info!("Backup integrity verified: {} bytes", backup_metadata.len());
        Ok(())
    }
}

impl Default for BackupManager {
    fn default() -> Self {
        Self::new().unwrap_or_else(|_| {
            warn!("Failed to create backup manager with default settings");
            Self {
                backup_dir: PathBuf::from("/tmp/geist-supervisor-backups"),
            }
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs::File;
    use tempfile::tempdir;

    #[test]
    fn test_backup_manager_creation() {
        let manager = BackupManager::new();
        assert!(manager.is_ok());
    }

    #[test]
    fn test_create_backup_success() {
        let temp_dir = tempdir().unwrap();
        let backup_dir = temp_dir.path().join("backups");
        let manager = BackupManager::with_backup_dir(backup_dir).unwrap();

        // Create a test binary
        let binary_path = temp_dir.path().join("test_binary");
        let binary_content = b"test binary content";
        fs::write(&binary_path, binary_content).unwrap();

        let result = manager.create_backup(&binary_path);
        assert!(result.is_ok());

        let backup_path = result.unwrap();
        assert!(backup_path.exists());

        // Verify backup content
        let backup_content = fs::read(&backup_path).unwrap();
        assert_eq!(backup_content, binary_content);
    }

    #[test]
    fn test_create_backup_nonexistent_binary() {
        let temp_dir = tempdir().unwrap();
        let backup_dir = temp_dir.path().join("backups");
        let manager = BackupManager::with_backup_dir(backup_dir).unwrap();

        let nonexistent_path = temp_dir.path().join("nonexistent_binary");
        let result = manager.create_backup(&nonexistent_path);

        // Should succeed but not create a backup file
        assert!(result.is_err());
    }

    #[test]
    fn test_restore_from_backup_success() {
        let temp_dir = tempdir().unwrap();
        let backup_dir = temp_dir.path().join("backups");
        let manager = BackupManager::with_backup_dir(backup_dir).unwrap();

        // Create backup file
        let backup_content = b"backup binary content";
        let backup_path = temp_dir.path().join("test_backup");
        fs::write(&backup_path, backup_content).unwrap();

        // Create target file with different content
        let target_path = temp_dir.path().join("target_binary");
        fs::write(&target_path, b"original content").unwrap();

        let result = manager.restore_from_backup(
            &backup_path,
            &target_path,
            &crate::services::ota::ServiceManager::new("test_service".to_string()),
        );
        assert!(result.is_ok());

        // Verify restoration
        let restored_content = fs::read(&target_path).unwrap();
        assert_eq!(restored_content, backup_content);
    }

    #[test]
    fn test_restore_from_backup_missing_backup() {
        let temp_dir = tempdir().unwrap();
        let backup_dir = temp_dir.path().join("backups");
        let manager = BackupManager::with_backup_dir(backup_dir).unwrap();

        let nonexistent_backup = temp_dir.path().join("nonexistent_backup");
        let target_path = temp_dir.path().join("target_binary");

        let result = manager.restore_from_backup(
            &nonexistent_backup,
            &target_path,
            &crate::services::ota::ServiceManager::new("test_service".to_string()),
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_list_backups() {
        let temp_dir = tempdir().unwrap();
        let backup_dir = temp_dir.path().join("backups");
        let manager = BackupManager::with_backup_dir(backup_dir).unwrap();

        // Create some backup files
        let backup_files = ["test.backup.v1.0.0.123", "test.backup.v1.1.0.456"];
        for backup_file in &backup_files {
            let backup_path = manager.backup_dir().join(backup_file);
            File::create(backup_path).unwrap();
        }

        let backups = manager.list_backups().unwrap();
        assert_eq!(backups.len(), 2);
        assert!(backups.contains(&backup_files[0].to_string()));
        assert!(backups.contains(&backup_files[1].to_string()));
    }

    #[test]
    fn test_cleanup_old_backups() {
        let temp_dir = tempdir().unwrap();
        let backup_dir = temp_dir.path().join("backups");
        let manager = BackupManager::with_backup_dir(backup_dir).unwrap();

        // Create multiple backup files
        let backup_files = [
            "test.backup.v1.0.0.100",
            "test.backup.v1.1.0.200",
            "test.backup.v1.2.0.300",
        ];
        for backup_file in &backup_files {
            let backup_path = manager.backup_dir().join(backup_file);
            File::create(backup_path).unwrap();
        }

        // Keep only 2 backups
        let result = manager.cleanup_old_backups(2);
        assert!(result.is_ok());

        let remaining_backups = manager.list_backups().unwrap();
        assert_eq!(remaining_backups.len(), 2);
    }

    #[test]
    fn test_backup_exists() {
        let temp_dir = tempdir().unwrap();
        let backup_dir = temp_dir.path().join("backups");
        let manager = BackupManager::with_backup_dir(backup_dir).unwrap();

        let backup_name = "test.backup.v1.0.0.123";
        assert!(!manager.backup_exists(backup_name));

        // Create the backup file
        let backup_path = manager.backup_dir().join(backup_name);
        File::create(backup_path).unwrap();

        assert!(manager.backup_exists(backup_name));
    }

    #[test]
    fn test_get_backup_path() {
        let temp_dir = tempdir().unwrap();
        let backup_dir = temp_dir.path().join("backups");
        let manager = BackupManager::with_backup_dir(backup_dir.clone()).unwrap();

        let backup_name = "test.backup.v1.0.0.123";
        let backup_path = manager.get_backup_path(backup_name).unwrap();

        assert_eq!(backup_path, backup_dir.join(backup_name));
    }
}