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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
//!
//! # 基本类型定义
//!

use crate::{nat, vm};
use lazy_static::lazy_static;
use myutil::{err::*, *};
use parking_lot::{Mutex, RwLock};
pub(crate) use ppcore_def::*;
use std::{
    collections::{HashMap, HashSet},
    path::PathBuf,
    sync::atomic::{AtomicI32, AtomicU16, Ordering},
    sync::{Arc, Weak},
};

// VM 实例的生命周期最长 6 小时
const MAX_LIFE_TIME: u64 = 6 * 3600;

pub type OsName = String;
pub type ImagePath = String;

///////////////////
// Serv 相关定义 //
///////////////////

/// 服务定义
#[derive(Debug, Default)]
pub struct Serv {
    // 每个客户端对应的 Env 实例集合
    cli: Arc<RwLock<HashMap<CliId, HashMap<EnvId, Env>>>>,
    // Env 创建时添加, 销毁时删除
    env_id_inuse: Arc<Mutex<HashSet<EnvId>>>,
    // Vm 创建时添加, 销毁时删除
    vm_id_inuse: Arc<Mutex<HashSet<VmId>>>,
    // Vm 创建时添加, 销毁时删除
    pub_port_inuse: Arc<Mutex<HashSet<PubPort>>>,
    // 资源分配相关的统计数据
    resource: Arc<RwLock<Resource>>,
}

impl Serv {
    /// 创建服务实例
    #[inline(always)]
    pub fn new() -> Serv {
        Serv::default()
    }

    /// 设置可用的资源总量
    #[inline(always)]
    pub fn set_resource(&self, rsc: Resource) {
        *self.resource.write() =
            Resource::new(rsc.cpu_total, rsc.mem_total, rsc.disk_total);
    }

    /// 获取资源占用的统计数据
    #[inline(always)]
    pub fn get_resource(&self) -> Resource {
        *self.resource.read()
    }

    /// 清理过期的 Env
    pub fn clean_expired_env(&self) {
        let ts = ts!();

        let cli = self.cli.read();
        let expired = cli
            .iter()
            .map(|(cli_id, env)| {
                env.iter()
                    .filter(|(_, v)| v.end_timestamp < ts)
                    .map(move |(k, _)| (cli_id.clone(), k.clone()))
            })
            .flatten()
            .collect::<Vec<_>>();

        if !expired.is_empty() {
            drop(cli); // 换写锁
            let mut cli = self.cli.write();
            expired.iter().for_each(|(cli_id, k)| {
                cli.get_mut(cli_id.as_str())
                    .map(|env_set| env_set.remove(k));
            });
        }

        // clean zobmie process,
        // this will do nothing on freebsd.
        vm::zobmie_clean();
    }

    /// 添加新的客户端
    #[inline(always)]
    pub fn add_client(&self, id: CliId) -> Result<()> {
        let mut cli = self.cli.write();
        if cli.get(&id).is_some() {
            Err(eg!("Already exists!"))
        } else {
            cli.insert(id, map! {});
            Ok(())
        }
    }

    /// 删除客户端并清理所有资源
    #[inline(always)]
    pub fn del_client(&self, id: &CliIdRef) {
        self.cli.write().remove(id);
    }

    /// 添加 Env, 若 CliId 不存在会自动创建
    #[inline(always)]
    pub fn register_env(&self, id: CliId, env: Env) -> Result<()> {
        let mut cli = self.cli.write();
        let env_set = cli.entry(id).or_insert(map! {});
        if env_set.get(&env.id).is_some() {
            Err(eg!("Env already exists!"))
        } else {
            env_set.insert(env.id.clone(), env);
            Ok(())
        }
    }

    /// 清除指定的 Env
    #[inline(always)]
    pub fn del_env(&self, cli_id: &CliIdRef, env_id: &EnvIdRef) {
        if let Some(env_set) = self.cli.write().get_mut(cli_id) {
            // drop 会自动清理资源
            env_set.remove(env_id);
        }
    }

    /// 批量获取所有 Env 的概略信息
    #[inline(always)]
    pub fn get_env_meta(&self, cli_id: &CliIdRef) -> Vec<EnvMeta> {
        let get = |env: &HashMap<EnvId, Env>| {
            env.values().map(|i| i.as_meta()).collect::<Vec<_>>()
        };

        self.cli.read().get(cli_id).map(get).unwrap_or_default()
    }

    /// 获取全局 ENV 列表, 供 Proxy 使用
    #[inline(always)]
    pub fn get_env_meta_all(&self) -> Vec<EnvMeta> {
        self.cli
            .read()
            .values()
            .map(|env| env.values().map(|i| i.as_meta()))
            .flatten()
            .collect::<Vec<_>>()
    }

    /// 批量获取 Env 详细信息,
    /// 不能直接返回 Env 实体,
    /// 会触发 Drop 动作
    #[inline(always)]
    pub fn get_env_detail(
        &self,
        cli_id: &CliIdRef,
        env_set: Vec<EnvId>,
    ) -> Vec<EnvInfo> {
        let get = |env: &HashMap<EnvId, Env>| {
            env.values()
                .filter(|v| env_set.iter().any(|vid| vid == &v.id))
                .map(|env| env.as_info())
                .collect::<Vec<_>>()
        };
        self.cli.read().get(cli_id).map(get).unwrap_or_default()
    }

    /// 更新指定 Env 的 lifetime
    #[inline(always)]
    pub fn update_env_life(
        &self,
        cli_id: &CliIdRef,
        env_id: &EnvIdRef,
        lifetime: u64,
        is_fucker: bool,
    ) -> Result<()> {
        let mut cli = self.cli.write();
        if let Some(env_set) = cli.get_mut(cli_id) {
            if let Some(env) = env_set.get_mut(env_id) {
                env.update_life(lifetime, is_fucker).c(d!())
            } else {
                Err(eg!("Env NOT exists!"))
            }
        } else {
            Err(eg!("Client NOT exists!"))
        }
    }

    /// 删除指定 OS 前缀的 VM
    #[inline(always)]
    pub fn update_env_del_vm(
        &self,
        cli_id: &CliIdRef,
        env_id: &EnvIdRef,
        vmid_set: &[VmId],
    ) -> Result<()> {
        let mut cli = self.cli.write();
        if let Some(env_set) = cli.get_mut(cli_id) {
            if let Some(env) = env_set.get_mut(env_id) {
                vmid_set.iter().for_each(|id| {
                    env.vm.remove(id);
                });
                Ok(())
            } else {
                Err(eg!("Env NOT exists!"))
            }
        } else {
            Err(eg!("Client NOT exists!"))
        }
    }
}

/// 已分配的资源信息,
/// `*_used` 字段使用 u32 类型,
/// 防止统计数据时的加和运算溢出
#[derive(Clone, Copy, Debug, Default)]
pub struct Resource {
    /// Vm 数量
    pub vm_active: u32,
    /// Cpu 核心数
    pub cpu_total: u64,
    /// 已使用的 Cpu
    pub cpu_used: u32,
    /// 内存容量(MB)
    pub mem_total: u64,
    /// 已使用的内存(MB)
    pub mem_used: u32,
    /// 磁盘容量(MB)
    pub disk_total: u64,
    /// 已使用的磁盘(MB)
    pub disk_used: u32,
}

impl Resource {
    /// 设置资源限制时使用
    #[inline(always)]
    pub fn new(cpu_total: u64, mem_total: u64, disk_total: u64) -> Resource {
        let mut rsc = Resource::default();
        rsc.cpu_total = cpu_total;
        rsc.mem_total = mem_total;
        rsc.disk_total = disk_total;
        rsc
    }
}

//////////////////
// Env 相关定义 //
//////////////////

/// 描述一个环境实例
#[derive(Clone, Debug)]
pub struct Env {
    // 保证全局唯一
    id: EnvId,
    // 起始时间设定之后不允许变更
    start_timestamp: u64,
    // 结束时间可以变更, 用以控制 Vm 的生命周期
    end_timestamp: u64,
    // 同一 Env 下所有 Vm 集合
    vm: HashMap<VmId, Vm>,
    // 所属的 Serv 实例
    serv_belong_to: Weak<Serv>,
}

impl Env {
    /// 获取描述性的元信息
    #[inline(always)]
    fn as_meta(&self) -> EnvMeta {
        EnvMeta {
            id: self.id.clone(),
            start_timestamp: self.start_timestamp,
            end_timestamp: self.end_timestamp,
            vm_cnt: self.vm.len(),
        }
    }

    /// 获取描述性的元信息
    #[inline(always)]
    fn as_info(&self) -> EnvInfo {
        EnvInfo {
            id: self.id.clone(),
            start_timestamp: self.start_timestamp,
            end_timestamp: self.end_timestamp,
            vm: self.vm.iter().map(|(&k, v)| (k, v.as_info())).collect(),
        }
    }

    /// 创建新的 Env 实例, 内部自动生成 ID
    pub fn new(serv: &Arc<Serv>, id: &EnvIdRef) -> Result<Env> {
        let mut inuse = serv.env_id_inuse.lock();
        if inuse.get(id).is_none() {
            inuse.insert(id.to_owned());
            drop(inuse);
        } else {
            return Err(eg!("Already exists!"));
        }

        Ok(Env {
            id: id.to_owned(),
            vm: HashMap::new(),
            start_timestamp: ts!(),
            end_timestamp: 3600 + ts!(),
            serv_belong_to: Arc::downgrade(serv),
        })
    }

    /// 更新已有实例的生命周期
    #[inline(always)]
    pub fn update_life(&mut self, secs: u64, is_fucker: bool) -> Result<()> {
        if MAX_LIFE_TIME < secs && !is_fucker {
            return Err(eg!("Life time too long!"));
        }
        self.end_timestamp = self.start_timestamp + secs;
        Ok(())
    }

    /// 批量创建 Vm 实例
    #[inline(always)]
    pub fn add_vm_set(&mut self, cfg_set: Vec<VmCfg>) -> Result<()> {
        let mut vm = vct![];

        // 检查可用资源
        self.check_resource(&cfg_set).c(d!())?;

        // 出错返回时, 创建成功的 Vm 也会被 drop 自动清理
        for cfg in cfg_set.into_iter() {
            vm.push(Vm::create(&self.serv_belong_to, cfg)?);
        }

        // 全部创建成功后再批量注册
        vm.into_iter().for_each(|vm| {
            self.vm.insert(vm.id(), vm);
        });

        Ok(())
    }

    // 检查可用资源是否充裕
    fn check_resource(&self, cfg_set: &[VmCfg]) -> Result<()> {
        if let Some(s) = self.serv_belong_to.upgrade() {
            let rsc;
            {
                rsc = *s.resource.read();
            }

            let (cpu, mem, disk) =
                cfg_set.iter().fold((0u64, 0, 0), |mut b, vm| {
                    b.0 += vm.cpu_num.unwrap_or(CPU_DEFAULT) as u64;
                    b.1 += vm.mem_size.unwrap_or(MEM_DEFAULT) as u64;
                    b.2 += vm.disk_size.unwrap_or(DISK_DEFAULT) as u64;
                    b
                });

            if rsc.cpu_used as u64 + cpu > rsc.cpu_total {
                return Err(eg!(format!(
                    "CPU resource busy: total {}, used {}, you want: {}",
                    rsc.cpu_total, rsc.cpu_used, cpu
                )));
            }

            if rsc.mem_used as u64 + mem > rsc.mem_total {
                return Err(eg!(format!(
                    "Memory resource busy: total {} MB, used {} MB, you want: {} MB",
                    rsc.mem_total, rsc.mem_used, mem
                )));
            }

            if rsc.disk_used as u64 + disk > rsc.disk_total {
                return Err(eg!(format!(
                    "Disk resource busy: total {} MB, used {} MB, you want: {} MB",
                    rsc.disk_total, rsc.disk_used, disk
                )));
            }
        } else {
            return Err(eg!("The fucking world is OVER!"));
        }

        Ok(())
    }
}

// 清理资源占用
impl Drop for Env {
    fn drop(&mut self) {
        // 清理 Env 相关的 inuse 信息
        if let Some(s) = self.serv_belong_to.upgrade() {
            s.env_id_inuse.lock().remove(&self.id);
        }
    }
}

/////////////////
// Vm 配置定义 //
/////////////////

/// 用以与调用方交互
#[derive(Clone, Debug)]
pub struct VmCfg {
    /// 系统镜像路径
    pub image_path: String,
    /// 同一 Env 下所有 Vm 的内部端口都相同
    pub port_list: Vec<VmPort>,
    /// 虚拟实例的类型
    pub kind: Option<VmKind>,
    /// CPU 数量
    pub cpu_num: Option<u32>,
    /// 单位: MB
    pub mem_size: Option<u32>,
    /// 单位: MB
    pub disk_size: Option<u32>,
}

/// 描述一个容器实例的信息
#[derive(Clone, Debug)]
pub struct Vm {
    /// Vm 镜像路径
    pub(crate) image_path: PathBuf,
    /// 虚拟实例的类型
    pub kind: VmKind,
    /// CPU 数量
    pub cpu_num: u32,
    /// 单位: MB
    pub mem_size: u32,
    /// 单位: MB
    pub disk_size: u32,

    // 所属的 Serv 实例
    serv_belong_to: Weak<Serv>,

    /// 实例 ID 与 IP 唯一对应
    pub(crate) id: VmId,
    /// Vm IP 由 VmId 决定, 使用'10.10.x.x/8'网段
    pub ip: Ipv4,
    /// 用于 DNAT 的内外端口影射关系,
    pub port_map: HashMap<VmPort, PubPort>,
}

impl Vm {
    #[inline(always)]
    pub(crate) fn as_info(&self) -> VmInfo {
        VmInfo {
            os: self
                .image_path
                .file_name()
                .map(|f| f.to_str())
                .flatten()
                .unwrap_or_default()
                .trim_end_matches(".qcow2")
                .to_owned(),
            kind: self.kind,
            cpu_num: self.cpu_num,
            mem_size: self.mem_size,
            disk_size: self.disk_size,
            ip: self.ip.clone(),
            port_map: self.port_map.clone(),
        }
    }

    pub(crate) fn create(serv: &Weak<Serv>, cfg: VmCfg) -> Result<Vm> {
        let cpu_num = cfg.cpu_num.unwrap_or(CPU_DEFAULT);
        let mem_size = cfg.mem_size.unwrap_or(MEM_DEFAULT);
        let disk_size = cfg.disk_size.unwrap_or(DISK_DEFAULT);

        let mut res = Vm {
            image_path: PathBuf::from(cfg.image_path),
            kind: cfg.kind.unwrap_or_default(),
            cpu_num,
            mem_size,
            disk_size,
            serv_belong_to: Weak::clone(serv),
            id: -1,
            ip: Ipv4::default(),
            port_map: cfg.port_list.into_iter().fold(
                HashMap::new(),
                |mut acc, new| {
                    acc.insert(new, 0);
                    acc
                },
            ),
        };

        // 创建之后须立即计数
        let cnt_it = |s: &Serv| {
            let mut rsc = s.resource.write();
            rsc.vm_active += 1;
            rsc.cpu_used += cpu_num;
            rsc.mem_used += mem_size;
            rsc.disk_used += disk_size;
        };

        if let Some(s) = serv.upgrade() {
            cnt_it(&s);
            res.alloc_resource(&s).c(d!()).map(|_| res)
        } else {
            Err(eg!())
        }
    }

    // 执行流程:
    //     1. 分配 VmId 并写入全局 inuse 中
    //     2. 依据 VmId 生成 Vm IP
    //     3. 分配对外通信的网络端口
    //     4. 设置 NAT 规则
    //     5. 启动 Vm 进程
    #[inline(always)]
    fn alloc_resource(&mut self, serv: &Arc<Serv>) -> Result<()> {
        self.alloc_id(&serv)
            .c(d!())
            .map(|id| self.ip = Self::gen_ip(id))
            .and_then(|_| self.alloc_pub_port(&serv).c(d!()))
            .and_then(|_| nat::set_rule(&self.port_map, &self.ip).c(d!()))
            .and_then(|_| self.start_vm().c(d!()))
    }

    #[inline(always)]
    fn start_vm(&self) -> Result<()> {
        vm::start(self).c(d!())
    }

    // 分配 VmId 并写入全局 inuse 中
    #[inline(always)]
    fn alloc_id(&mut self, serv: &Arc<Serv>) -> Result<VmId> {
        const VM_ID_LIMIT: i32 = 0xffff;
        lazy_static! {
            static ref VM_ID: AtomicI32 = AtomicI32::new(0);
        }

        let vm_id = {
            let mut cnter = 0;
            let mut vmid_inuse = serv.vm_id_inuse.lock();
            loop {
                let id = VM_ID.fetch_add(1, Ordering::Relaxed) % VM_ID_LIMIT;
                if vmid_inuse.get(&id).is_none() {
                    vmid_inuse.insert(id);
                    self.id = id;
                    break id;
                }
                cnter += 1;
                if VM_ID_LIMIT < cnter {
                    return Err(eg!("The fucking world is over!!!"));
                }
            }
        };

        Ok(vm_id)
    }

    // 基于 VmId 生成 IP
    #[inline(always)]
    fn gen_ip(vm_id: VmId) -> Ipv4 {
        Ipv4::new(format!("10.10.{}.{}", vm_id / 256, vm_id % 256))
    }

    // 分配外部端口并写入全局 inuse 中
    fn alloc_pub_port(&mut self, serv: &Arc<Serv>) -> Result<()> {
        const PUB_PORT_LIMIT: u16 = 20000;
        lazy_static! {
            static ref PUB_PORT: AtomicU16 = AtomicU16::new(40000);
        }

        let mut cnter = 0;
        let mut v_cnter = self.port_map.len();
        let mut buf = vct![];
        while 0 < v_cnter {
            let mut port_inuse = serv.pub_port_inuse.lock();
            let port = PUB_PORT.fetch_add(1, Ordering::Relaxed);
            if port_inuse.get(&port).is_none() {
                port_inuse.insert(port);
                buf.push(port);
                v_cnter -= 1;
            }

            cnter += 1;
            if PUB_PORT_LIMIT < cnter {
                return Err(eg!("The fucking world is over!!!"));
            }
        }

        self.port_map.values_mut().zip(buf.into_iter()).for_each(
            |(p, port)| {
                *p = port;
            },
        );

        Ok(())
    }

    /// get VmId
    #[inline(always)]
    pub fn id(&self) -> VmId {
        self.id
    }
}

impl Drop for Vm {
    fn drop(&mut self) {
        if let Some(s) = self.serv_belong_to.upgrade() {
            // 清理 VmId inuse 信息
            s.vm_id_inuse.lock().remove(&self.id);

            // 清理资源统计数据
            {
                let mut rsc = s.resource.write();
                rsc.vm_active -= 1;
                rsc.cpu_used -= self.cpu_num;
                rsc.mem_used -= self.mem_size;
                rsc.disk_used -= self.disk_size;
            }

            if !self.port_map.is_empty() {
                let mut pub_port = vct![];
                let mut inuse = s.pub_port_inuse.lock();
                self.port_map.values().for_each(|port| {
                    // 清理端口 inuse 信息
                    inuse.remove(port);
                    // 收集待清理端口
                    pub_port.push(*port);
                });

                // 清理 nat 规则
                info_omit!(nat::clean_rule(&pub_port));
            }
        }

        vm::post_clean(self);
    }
}