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
//!
//! # Infrastructure-related model design
//!

use crate::err::*;
use ruc::{err::*, *};
use std::{
    collections::HashMap,
    fs, mem,
    path::{Path, PathBuf},
    sync::Arc,
};

/// Use `u64` to express an ID,
/// e.g. [ENV](self::Env::id), [VM](self::Vm::id) ...
pub type Id = u64;

/// Use `u16` to express a socket port.
pub type SockPort = u16;
/// Service ports within the host machine.
pub type PubSockPort = SockPort;
/// Service ports within the VM.
pub type InnerSockPort = SockPort;

/// Use `String` to express a network address,
/// in the the perspective of the client, see [NetAddr](self::Vm::addr).
pub type NetAddr = String;

/// Inner IP(v4) address of VM.
pub type IpAddr = [u8; 4];
/// MAC address of VM.
pub type MacAddr = [u8; 6];

/// Use `u32` as the uint of supported vm-engine-features.
pub type VmEngineFeat = u32;

/// Core unit of TT.
pub struct Env {
    /// UUID of the `ENV`
    pub id: Id,
    /// Name of the `ENV`.
    pub name: Option<String>,
    /// The start timestamp of this ENV,
    /// can NOT be changed.
    pub start_timestamp: u64,
    /// The end timestamp of this ENV,
    /// permit use to change it .
    pub end_timestamp: u64,
    /// All `VmId`s under this ENV.
    pub vm_set: Vec<Id>,
    /// Info about the state of ENV.
    pub state: EnvState,
}

/// Info about the state of ENV.
pub struct EnvState {
    /// Whether this ENV is stopped.
    pub is_stopped: bool,
    /// Whether all VMs of this ENV are denied to connect to Internet.
    pub deny_outgoing: bool,
    /// The timestamp of the lastest manage-operation,
    /// such as 'stop/start/snapshot...'.
    ///
    /// This kind of operation can NOT be called frequently,
    /// because them will take a long time to complete.
    pub last_mgmt_timestamp: u64,
}

/// Infomations about a VM instance.
pub struct Vm {
    /// UUID of this `VM`
    pub id: Id,
    /// Name of the `VM`.
    pub name: Option<String>,
    /// Created by which engine.
    pub engine: Arc<dyn VmEngine>,
    /// Template of `runtime_image`, that is,
    /// the runtime image is created based on the template.
    pub template: Arc<VmTemplate>,
    /// Runtime image of Vm.
    ///
    /// Use 'String' instead of 'PathBuf', because
    /// `runtime_image` may not be a regular file path,
    /// such as `ZFS` stroage.
    ///
    /// E.g. zroot/tt/[VmId](self::Vm::id)
    pub runtime_image: String,
    /// SnapshotName => Snapshot
    pub snapshots: HashMap<String, Snapshot>,
    /// The latest cached config-file.
    pub latest_meta: Option<PathBuf>,
    /// Info about the state of VM.
    pub state: VmState,
    /// Info about the resource of VM.
    pub resource: VmResource,
    /// Usually an 'IP' or a 'domain url'.
    ///
    /// Only meaningful from the perspective of the client,
    /// to indicate how to connect to it from the client.
    ///
    /// This is different from the meaning of the
    /// address in [VmResource](self::VmResource).
    pub addr: NetAddr,
}

/// Infomations about a template of VM.
pub struct VmTemplate {
    /// Globally unique name,
    /// e.g. "github.com/ktmlm/alpine"
    pub name: String,
    /// Description of the basic image.
    pub memo: Option<String>,
    /// Path which pointing to the template.
    /// May not be a regular file path, such as `ZFS`.
    pub path: String,
    /// Engines can use this template.
    pub compatible_engines: Vec<String>,
}

/// Info about the state of VM.
pub struct VmState {
    /// Whether has been stopped.
    pub during_stop: bool,
    /// Whether keep image NOT to be destroyed,
    /// when the life cycle of `Vm` ends.
    pub keep_image: bool,
    /// Whether generate a random uuid for this VM,
    /// if NOT, user may not to get `machine-id` of the VM.
    pub rand_uuid: bool,
    /// VM can NOT connect to the addrs in this list.
    pub outgoing_blacklist: Vec<NetAddr>,
}

/// Info about the resource of VM.
pub struct VmResource {
    /// CPU number
    pub cpu_num: u16,
    /// Memory size in MB
    pub mem_size: u32,
    /// Disk size in MB
    pub disk_size: u32,
    /// Inner IP address, e.g. '[10,0,0,2]',
    /// IP is generated from 'MAC address',
    /// use the last three fields of MAC.
    pub ip_addr: IpAddr,
    /// MAC address, e.g. '[0x82,0x17,0x0d,0x6a,0xbc,0x80]',
    /// used to generate the responding IP address.
    pub mac_addr: MacAddr,
    /// Ports allocation for NAT, that is:
    /// {Private Port within VM} => {Public Port within Host}
    pub port_map: HashMap<InnerSockPort, PubSockPort>,
}

/// Snapshot management.
pub struct Snapshot {
    /// The name of snapshot.
    pub name: String,
    /// The data path of snapshot,
    /// May not be a regular file path, such as `ZFS`.
    pub path: String,
    /// The corresponding metadata to the snapshot.
    pub meta_path: PathBuf,
    /// If set this, snapshot will be cleaned when
    /// the number of seconds it exists exceeds this value.
    pub life_time: Option<u64>,
}

impl Snapshot {
    /// Init a new snapshot instance without `life_time` limition.
    pub fn new(name: String, meta_path: PathBuf) -> Self {
        Self::newx(name, None, meta_path)
    }

    /// Init a new snapshot instance.
    pub fn newx(name: String, life_time: Option<u64>, meta_path: PathBuf) -> Self {
        Snapshot {
            name,
            life_time,
            path: String::new(),
            meta_path,
        }
    }
}

/// Common methods for each engine,
/// such as 'Firecracker', 'Qemu', 'Docker' ...
pub trait VmEngine: Firewall + Storage {
    /// Check if all features the client wanted can be supported.
    fn check_feat(&self, feat_wanted: &[VmEngineFeat]) -> Result<bool>;

    /// Create the VM instance, and update necessary data of the `Vm`.
    fn create_vm(&self, vm: &mut Vm) -> Result<()> {
        self.create_image(vm)
            .c(e!(TT_ERR_STORAGE_CREATE_IMAGE))
            .and_then(|_| self.set_nat(vm).c(e!(TT_ERR_FIREWALL_SET_NAT)))
    }

    /// Destroy the VM instance, and update necessary data of the `Vm`.
    fn destroy_vm(&self, vm: &mut Vm) -> Result<()> {
        self.destroy_image(vm)
            .c(e!(TT_ERR_STORAGE_DESTROY_IMAGE))
            .and_then(|_| self.unset_nat(vm).c(e!(TT_ERR_FIREWALL_UNSET_NAT)))
    }

    /// Start a `stopped` VM.
    fn start_vm(&self, vm: &mut Vm) -> Result<()>;

    /// Stop(aka pause) a running VM.
    fn stop_vm(&self, vm: &mut Vm) -> Result<()>;

    /// Use the new `Vm` instead of the old one,
    /// apply all configs in the new `Vm`.
    fn update_vm(&mut self, vm: Vm) -> Result<()>;

    /// Cache all infomations of the 'Vm' to disk.
    fn cache_meta(&self, vm: &Vm) -> Result<PathBuf>;

    /// Remove a cached config of `Vm`.
    fn rm_meta(&self, vm: &mut Vm, path: &Path) -> Result<()> {
        fs::remove_file(path).c(e!(TT_ERR_SYS_IO)).map(|_| {
            if let Some(ref p) = vm.latest_meta {
                if p == path {
                    vm.latest_meta = None;
                }
            }
        })
    }

    /// Restruct a `Vm` from a cached config.
    fn gen_vm_from_meta(&self, path: &Path) -> Result<Vm>;

    /// Add a snapshot for the runtime image:
    ///
    /// 1. stop the runtime instance
    /// 2. cache current meta-config
    /// 3. snapshot storage
    /// 4. restart the runtime instance
    fn create_snapshot(
        &self,
        vm: &mut Vm,
        name: &str,
        life_time: Option<u64>,
    ) -> Result<()> {
        self.stop_vm(vm)
            .c(e!(TT_ERR_STOP_VM))
            .and_then(|_| {
                self.cache_meta(vm)
                    .c(e!(TT_ERR_META_CREATE_CACHE))
                    .and_then(|meta| {
                        let mut snapshot =
                            Snapshot::newx(name.to_owned(), life_time, meta);
                        <Self as Storage>::create_snapshot(self, vm, &snapshot)
                            .c(e!(TT_ERR_SNAPSHOT_CREATE))
                            .map(|path| {
                                snapshot.path = path;
                                vm.snapshots.insert(name.to_owned(), snapshot);
                            })
                    })
            })
            .and_then(|_| self.start_vm(vm).c(e!(TT_ERR_START_VM)))
    }

    /// Delete a snapshot of the runtime image:
    ///
    /// 1. remove the storage of snapshot
    /// 2. remove the cached-meta of snapshot
    fn destroy_snapshot(&self, vm: &mut Vm, name: &str) -> Result<()> {
        vm.snapshots.remove(name).ok_or(eg!()).and_then(|snapshot| {
            <Self as Storage>::destroy_snapshot(self, vm, &snapshot.path)
                .c(e!(TT_ERR_SNAPSHOT_DESTROY))
                .and_then(|_| {
                    self.rm_meta(vm, &snapshot.meta_path)
                        .c(e!(TT_ERR_META_REMOVE_CACHE))
                })
        })
    }

    /// Revert to the state of this snapshot:
    ///
    /// 1. stop the runtime instance
    /// 3. relink runtime image to the one in snapshot
    /// 2. restore the responding [Vm](self::Vm) from cached-meta
    /// 4. restart the runtime instance
    fn apply_snapshot(&mut self, vm: &mut Vm, name: &str) -> Result<()> {
        self.stop_vm(vm)
            .and_then(|_| {
                let snapshot = vm.snapshots.get(name).ok_or(eg!())?;
                let mut cached_vm = self
                    .gen_vm_from_meta(&snapshot.meta_path)
                    .c(e!(TT_ERR_META_RESTORE_CACHE))?;
                <Self as Storage>::apply_snapshot(self, &cached_vm, &snapshot)
                    .c(e!(TT_ERR_SNAPSHOT_APPLY))?;
                cached_vm.snapshots = mem::take(&mut vm.snapshots);
                self.update_vm(cached_vm).c(e!(TT_ERR_UPDATE_VM))
            })
            .and_then(|_| self.start_vm(vm).c(e!(TT_ERR_START_VM)))
    }
}

/// This trait describes how to manage the 'firewall rule'.
pub trait Firewall {
    /// Set the 'NAT' rules between the VM and client.
    fn set_nat(&self, vm: &mut Vm) -> Result<()>;
    /// Unset the 'NAT' rules between the VM and client.
    fn unset_nat(&self, vm: &mut Vm) -> Result<()>;

    /// Disable VM's active access to the Internet.
    fn deny_outgoing(&self, vm: &mut Vm) -> Result<()>;
    /// Enable VM's active access to the Internet.
    fn allow_outgoing(&self, vm: &mut Vm) -> Result<()>;

    /// There needs NOT a reponsponding `unset_` method,
    /// we can get equal effect by clear the `Vm.VmState.outgoing_blacklist`.
    fn set_outgoing_blacklist(&self, vm: &mut Vm) -> Result<()>;
}

/// This trait describes how to manage the 'runtime image'.
pub trait Storage {
    /// Create a runtime image from it's template.
    fn create_image(&self, vm: &mut Vm) -> Result<()>;
    /// Destroy a runtime image.
    fn destroy_image(&self, vm: &mut Vm) -> Result<()>;

    /// Add a snapshot for the runtime image.
    fn create_snapshot(&self, vm: &mut Vm, snapshot: &Snapshot) -> Result<String>;
    /// Delete a snapshot of the runtime image.
    fn destroy_snapshot(&self, vm: &Vm, snapshot_path: &str) -> Result<()>;
    /// Revert to the state of this snapshot.
    fn apply_snapshot(&self, vm: &Vm, snapshot: &Snapshot) -> Result<()>;
}