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
//! Support Krill upgrades, e.g.:
//! - Updating the format of commands or events
//! - Export / Import data

use std::path::PathBuf;
use std::{fmt, fs, io};

use crate::commons::api::Handle;
use crate::commons::eventsourcing::{DiskKeyStore, KeyStore, KeyStoreError, KeyStoreVersion};
use crate::commons::util::file;
use crate::daemon::krillserver::KrillServer;
use crate::upgrades::roa_cleanup_0_7_0::RoaCleanupError;

pub mod pre_0_6_0;
pub mod roa_cleanup_0_7_0;

//------------ UpgradeError --------------------------------------------------

#[derive(Debug, Display)]
pub enum UpgradeError {
    #[display(fmt = "{}", _0)]
    KeyStoreError(KeyStoreError),

    #[display(fmt = "{}", _0)]
    IoError(io::Error),

    #[display(fmt = "Unrecognised command summary: {}", _0)]
    Unrecognised(String),

    #[display(fmt = "Cannot load: {}", _0)]
    CannotLoadAggregate(Handle),

    #[display(fmt = "Cannot clean up redundant roas: {}", _0)]
    RoaCleanup(RoaCleanupError),

    #[display(fmt = "{}", _0)]
    Custom(String),
}

impl UpgradeError {
    pub fn custom(msg: impl fmt::Display) -> Self {
        UpgradeError::Custom(msg.to_string())
    }

    pub fn unrecognised(msg: impl fmt::Display) -> Self {
        UpgradeError::Unrecognised(msg.to_string())
    }
}

impl From<KeyStoreError> for UpgradeError {
    fn from(e: KeyStoreError) -> Self {
        UpgradeError::KeyStoreError(e)
    }
}

impl From<file::Error> for UpgradeError {
    fn from(e: file::Error) -> Self {
        UpgradeError::IoError(e.into())
    }
}

impl From<io::Error> for UpgradeError {
    fn from(e: io::Error) -> Self {
        UpgradeError::IoError(e)
    }
}

impl From<RoaCleanupError> for UpgradeError {
    fn from(e: RoaCleanupError) -> Self {
        UpgradeError::RoaCleanup(e)
    }
}

//------------ UpgradeStore --------------------------------------------------

/// Implement this for automatic upgrades to key stores
pub trait UpgradeStore {
    fn needs_migrate(&self, store: &DiskKeyStore) -> Result<bool, UpgradeError>;
    fn migrate(&self, store: &DiskKeyStore) -> Result<(), UpgradeError>;
}

/// Should be called when Krill starts, before the KrillServer is initiated
pub fn pre_start_upgrade(work_dir: &PathBuf) -> Result<(), UpgradeError> {
    upgrade_pre_0_6_0_cas_commands(work_dir)?;
    upgrade_pre_0_6_0_pubd_commands(work_dir)
}

/// Should be called right after the KrillServer is initiated
pub fn post_start_upgrade(work_dir: &PathBuf, server: &KrillServer) -> Result<(), UpgradeError> {
    let version_0_7 = KeyStoreVersion::V0_7;
    let ca_store = DiskKeyStore::new(work_dir, "cas");
    let pubd_store = DiskKeyStore::new(work_dir, "pubd");
    if ca_store.get_version()? != version_0_7 {
        info!("Will clean up redundant ROAs for all CAs and update version of storage dirs");
        roa_cleanup_0_7_0::roa_cleanup(server)?;
        ca_store.set_version(&version_0_7)?;
        pubd_store.set_version(&version_0_7)?;
    }

    Ok(())
}

fn upgrade_pre_0_6_0_cas_commands(work_dir: &PathBuf) -> Result<(), UpgradeError> {
    let pre_0_6_0_ca_commands = pre_0_6_0::UpgradeCas;

    // Prepare to do the work on the real "cas" directory
    let mut cas_dir = work_dir.clone();
    cas_dir.push("cas");
    let ca_store = DiskKeyStore::new(work_dir, "cas");

    // bail out if there is nothing to do
    if !pre_0_6_0_ca_commands.needs_migrate(&ca_store)? {
        return Ok(());
    }

    // Make a back-up directory first, so that we can fall back to it in case
    // the upgrade fails
    let mut backup_dir = work_dir.clone();
    backup_dir.push("cas_bk");
    file::backup_dir(&cas_dir, &backup_dir)?;

    if let Err(e) = pre_0_6_0_ca_commands.migrate(&ca_store) {
        // If the upgrade failed, then rename the now broken directory for inspection,
        // and restore the backup directory by renaming it.
        let mut failed = work_dir.clone();
        failed.push("cas-failed-upgrade");
        fs::rename(&cas_dir, &failed)?;
        fs::rename(&backup_dir, &cas_dir)?;

        // Return the error so that the krill startup can be aborted.
        Err(e)
    } else {
        // Upgrade successful
        let _ = fs::remove_dir_all(&backup_dir); // ignore if removing backup fails
        Ok(())
    }
}

fn upgrade_pre_0_6_0_pubd_commands(work_dir: &PathBuf) -> Result<(), UpgradeError> {
    let pre_0_6_0_pubd_commands = pre_0_6_0::UpgradePubd;

    // Prepare to do the work on the real "cas" directory
    let mut pubd_dir = work_dir.clone();
    pubd_dir.push("pubd");
    let pubd_store = DiskKeyStore::new(work_dir, "pubd");

    // bail out if there is nothing to do
    if !pre_0_6_0_pubd_commands.needs_migrate(&pubd_store)? {
        return Ok(());
    }

    // Make a back-up directory first, so that we can fall back to it in case
    // the upgrade fails
    let mut backup_dir = work_dir.clone();
    backup_dir.push("pubd_bk");
    file::backup_dir(&pubd_dir, &backup_dir)?;

    if let Err(e) = pre_0_6_0_pubd_commands.migrate(&pubd_store) {
        // If the upgrade failed, then rename the now broken directory for inspection,
        // and restore the backup directory by renaming it.
        let mut failed = work_dir.clone();
        failed.push("pubd-failed-upgrade");
        fs::rename(&pubd_dir, &failed)?;
        fs::rename(&backup_dir, &pubd_dir)?;

        // Return the error so that the krill startup can be aborted.
        Err(e)
    } else {
        // Upgrade successful
        let _ = fs::remove_dir_all(&backup_dir); // ignore if removing backup fails
        Ok(())
    }
}

//------------ Tests ---------------------------------------------------------

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use crate::test;

    use super::*;

    #[test]
    fn upgrade_pre_0_6() {
        test::test_under_tmp(|tmp| {
            let cas_source =
                PathBuf::from("test-resources/api/regressions/v0_6_0/commands/migration/cas");
            let mut cas_test = tmp.clone();
            cas_test.push("cas");
            file::backup_dir(&cas_source, &cas_test).unwrap();

            let pubd_source =
                PathBuf::from("test-resources/api/regressions/v0_6_0/commands/migration/pubd");
            let mut pubd_test = tmp.clone();
            pubd_test.push("pubd");
            file::backup_dir(&pubd_source, &pubd_test).unwrap();

            pre_start_upgrade(&tmp).unwrap();
        })
    }
}