From b1bcd843979e80935c95caf09adc9411cb5f546b Mon Sep 17 00:00:00 2001 From: BrahmaMantra <2033552517.qq.com> Date: Mon, 22 Apr 2024 08:07:48 +0000 Subject: [PATCH 01/15] =?UTF-8?q?=E6=9C=AA=E5=AE=9E=E7=8E=B0timer=5Funit?= =?UTF-8?q?=E9=80=80=E5=87=BA=E5=90=8E=E7=9A=84=E7=BB=86=E8=8A=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .vscode/launch.json | 16 + Cargo.toml | 1 + src/main.rs | 45 +-- src/manager/mod.rs | 8 +- src/manager/timer_manager/mod.rs | 67 +++- src/manager/unit_manager/mod.rs | 15 +- src/parse/mod.rs | 19 +- src/parse/parse_timer/mod.rs | 29 ++ src/parse/parse_util/mod.rs | 6 +- src/systemctl/ctl_parser/mod.rs | 2 +- src/systemctl/mod.rs | 3 +- src/time/calandar/mod.rs | 105 +++++++ src/time/mod.rs | 2 +- src/time/timer/mod.rs | 7 +- src/time/watchdog/mod.rs | 1 - src/unit/mod.rs | 2 +- src/unit/service/mod.rs | 12 +- src/unit/timer/mod.rs | 520 ++++++++++++++++++++++++++++++- systemctl/src/main.rs | 3 +- 19 files changed, 798 insertions(+), 65 deletions(-) create mode 100644 .vscode/launch.json create mode 100644 src/parse/parse_timer/mod.rs create mode 100644 src/time/calandar/mod.rs delete mode 100644 src/time/watchdog/mod.rs diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..51c54c4 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,16 @@ +{ + // 使用 IntelliSense 了解相关属性。 + // 悬停以查看现有属性的描述。 + // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "type": "lldb", + "request": "launch", + "name": "Debug", + "program": "${workspaceFolder}/", + "args": [], + "cwd": "${workspaceFolder}" + } + ] +} \ No newline at end of file diff --git a/Cargo.toml b/Cargo.toml index 29010c5..054421b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,7 @@ hashbrown = "0.11" cfg-if = { version = "1.0" } lazy_static = { version = "1.4.0" } libc = "0.2" +humantime = "2.1" [profile.release] panic = 'abort' diff --git a/src/main.rs b/src/main.rs index b47afec..62af6c3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -9,18 +9,18 @@ mod time; mod unit; use error::ErrorFormat; -use executor::Executor; use manager::{timer_manager::TimerManager, Manager}; use parse::UnitParser; use systemctl::listener::Systemctl; pub struct FileDescriptor(usize); -const DRAGON_REACH_UNIT_DIR: &'static str = "/etc/reach/system/"; +// const DRAGON_REACH_UNIT_DIR: &'static str = "/etc/reach/system/"; +const DRAGON_REACH_UNIT_DIR: &'static str = "/home/fz/testSystemd/"; fn main() { // 初始化 - Systemctl::init(); + Systemctl::init(); let mut units_file_name = Vec::new(); //读取目录里面的unit文件 @@ -39,7 +39,7 @@ fn main() { //启动服务 for path in units_file_name { - let id = match UnitParser::from_path(&path) { + let _ = match UnitParser::from_path(&path) { Ok(id) => id, Err(e) => { eprintln!("Err:{}", e.error_format()); @@ -47,22 +47,23 @@ fn main() { } }; - if id != 0 { - if let Err(e) = Executor::exec(id) { - eprintln!("Err:{}", e.error_format()); - } - } - } - - // 启动完服务后进入主循环 - loop { - // 检查各服务运行状态 - Manager::check_running_status(); - // 检查cmd进程状态 - Manager::check_cmd_proc(); - // 检查计时器任务 - TimerManager::check_timer(); - // 监听systemctl - Systemctl::ctl_listen(); - } + // if id != 0 && TimerManager::is_timer(&id){ + // if let Err(e) = Executor::exec(id) { + // eprintln!("Err:{}", e.error_format()); + // } + // } + // } + } + + // 启动完服务后进入主循环 + loop { + // 检查各服务运行状态 + Manager::check_running_status(); + // 检查cmd进程状态 + Manager::check_cmd_proc(); + // 检查计时器任务 + TimerManager::check_timer(); + // 监听systemctl + Systemctl::ctl_listen(); + } } diff --git a/src/manager/mod.rs b/src/manager/mod.rs index 82dbdb0..db8bde4 100644 --- a/src/manager/mod.rs +++ b/src/manager/mod.rs @@ -21,7 +21,6 @@ impl Manager { match proc.try_wait() { //进程正常退出 Ok(Some(status)) => { - //TODO:交付给相应类型的Unit类型去执行退出后的逻辑 exited_unit.push(( *unit.0, ExitStatus::from_exit_code(status.code().unwrap_or(0)), @@ -48,8 +47,13 @@ impl Manager { // 取消该任务的定时器任务 TimerManager::cancel_timer(tmp.0); + + let _ = UnitManager::get_unit_with_id(&tmp.0) + .unwrap() + .lock().unwrap() + .exit();//交付给相应类型的Unit类型去执行退出后的逻辑 - // 交付处理子进程退出逻辑 + // 交付处理子进程退出逻辑 let unit = UnitManager::get_unit_with_id(&tmp.0).unwrap(); unit.lock().unwrap().after_exit(tmp.1); } diff --git a/src/manager/timer_manager/mod.rs b/src/manager/timer_manager/mod.rs index dce6842..b7be974 100644 --- a/src/manager/timer_manager/mod.rs +++ b/src/manager/timer_manager/mod.rs @@ -1,17 +1,22 @@ -use std::{sync::RwLock, time::Duration}; +use std::{sync::{Arc, Mutex, RwLock}, time::Duration}; -use crate::{error::runtime_error::RuntimeError, time::timer::Timer}; +use crate::{error::runtime_error::RuntimeError, time::timer::Timer, unit::timer::TimerUnit,unit::Unit}; +use hashbrown::HashMap; use lazy_static::lazy_static; lazy_static! { // 管理全局计时器任务 - static ref TIMER_TASK_MANAGER: RwLock = RwLock::new(TimerManager { - inner_timers: Vec::new() + static ref TIMER_TASK_MANAGER:RwLock = RwLock::new(TimerManager { + inner_timers: Vec::new(), + inner_timers_unit: Vec::new(), + id_table:RwLock::new(Vec::new())//.0是TimerUnit的id,.1是父Unit的id }); } pub struct TimerManager { inner_timers: Vec, + inner_timers_unit: Vec>>, + id_table: RwLock>, } impl<'a> IntoIterator for &'a mut TimerManager { @@ -27,7 +32,7 @@ impl<'a> IntoIterator for &'a mut TimerManager { impl TimerManager { /// ## 添加定时器任务 /// - /// 只有通过这个方式创建的Timer对象才会真正的实现计时 + /// 只有通过两这个方式载入的Timer或Timer_unit对象才会真正的实现计时 pub fn push_timer(duration: Duration, callback: F, parent: usize) where F: FnMut() -> Result<(), RuntimeError> + Send + Sync + 'static, @@ -39,6 +44,18 @@ impl TimerManager { .push(Timer::new(duration, Box::new(callback), parent)); } + pub fn push_timer_unit(unit:Arc>) + { + let mut timemanager=TIMER_TASK_MANAGER + .write() + .unwrap(); + let mut unit_ =unit.lock().unwrap(); + timemanager.id_table.write().unwrap().push((unit_.unit_id(), unit_.get_parent_unit())); + drop(unit_); + timemanager.inner_timers_unit + .push(unit);//加入到inner_timers_unit + } + /// ## 检测定时器是否到时,到时则触发 /// /// 该方法在主循环中每循环一次检测一次,是伪计时器的主运行函数 @@ -46,6 +63,20 @@ impl TimerManager { let mut writer = TIMER_TASK_MANAGER.write().unwrap(); //此处触发定时器,若定时器被触发,则移除 writer.inner_timers.retain_mut(|x| !x.check()); + drop(writer); + //此处触发Timer_unit,不移除 + let reader = TIMER_TASK_MANAGER.read().unwrap(); + + for timer in &reader.inner_timers_unit { + let mut timer_unit=timer.lock().unwrap(); + if timer_unit.check() { + let _ = timer_unit.run();//运行作出相应操作 + let id =timer_unit.get_parent_unit(); + drop(timer_unit); + TimerManager::adjust_timevalue(&id, true); + } + + } } /// ## 取消掉一个unit的所有定时任务, @@ -58,4 +89,30 @@ impl TimerManager { .inner_timers .retain(|x| x.parent() == unit_id) } + + pub fn is_timer(id:&usize)->bool{ + let id_table=&TIMER_TASK_MANAGER + .read() + .unwrap() + .id_table; + for iter in id_table.read().unwrap().iter(){ + if iter.0==*id { + return true; + } + } + false + } + /// unit_id:父unit的id flag:1为exec 0为exit + pub fn adjust_timevalue(unit_id: &usize, flag: bool /*1为启动0为退出 */){ + let manager=TIMER_TASK_MANAGER + .read() + .unwrap(); + for iter in &manager.inner_timers_unit{ + let mut unit =iter.lock().unwrap(); + if unit.get_parent_unit()==*unit_id{ + unit.change_stage(flag); + } + } + } + } diff --git a/src/manager/unit_manager/mod.rs b/src/manager/unit_manager/mod.rs index dac0a3a..aa6182d 100644 --- a/src/manager/unit_manager/mod.rs +++ b/src/manager/unit_manager/mod.rs @@ -10,22 +10,22 @@ use hashbrown::HashMap; use lazy_static::lazy_static; lazy_static! { - // 对于启动后即使退出亦认为其为运行状态的特殊注册类Service,对于这类进程做一个标记 + /// 对于启动后即使退出亦认为其为运行状态的特殊注册类Service,对于这类进程做一个标记 static ref FLAG_RUNNING: RwLock> = RwLock::new(Vec::new()); - // 任务等待队列,IDLE类型的service入队等待其它任务完成再执行 + /// 任务等待队列,IDLE类型的service入队等待其它任务完成再执行 static ref IDLE_SERVIEC_DEQUE: Mutex> = Mutex::new(VecDeque::new()); - // id到unit的映射表,全局的Unit管理表 + /// id到unit的映射表,全局的Unit管理表 pub(super) static ref ID_TO_UNIT_MAP: RwLock>>> = RwLock::new(HashMap::new()); - // 辅助表,通过服务名映射其id + /// 辅助表,通过服务名映射其id static ref NAME_TO_UNIT_MAP: RwLock> = RwLock::new(HashMap::new()); - // 全局运行中的Unit表 + /// 全局运行中的Unit表 pub(super) static ref RUNNING_TABLE: RwLock = RwLock::new(RunningTableManager { running_table: HashMap::new() }); - // CMD进程表,用于处理Unit的CMD派生进程(ExecStartPre等命令派生进程) + /// CMD进程表,用于处理Unit的CMD派生进程(ExecStartPre等命令派生进程) pub(super) static ref CMD_PROCESS_TABLE: RwLock>> = RwLock::new(HashMap::new()); } @@ -92,6 +92,7 @@ impl UnitManager { } // 通过id获取到path + // ↑感觉是笔误,应该是通过path获取到id pub fn get_id_with_path(path: &str) -> Option { let mut hasher = DefaultHasher::new(); path.hash(&mut hasher); @@ -143,7 +144,7 @@ impl UnitManager { pub fn pop_a_idle_service() -> Option>> { let id = IDLE_SERVIEC_DEQUE.lock().unwrap().pop_front(); match id { - Some(id) => { + Some(id) => { return Self::get_unit_with_id(&id); } None => { diff --git a/src/parse/mod.rs b/src/parse/mod.rs index 1e27f51..4f1d9c5 100644 --- a/src/parse/mod.rs +++ b/src/parse/mod.rs @@ -17,12 +17,14 @@ use lazy_static::lazy_static; use self::parse_service::ServiceParser; use self::parse_target::TargetParser; +use self::parse_timer::TimerParser; use self::parse_util::UnitParseUtil; pub mod graph; pub mod parse_service; pub mod parse_target; pub mod parse_util; +pub mod parse_timer; //对应Unit段类型 #[derive(PartialEq, Clone, Copy)] @@ -31,6 +33,7 @@ pub enum Segment { Unit, Install, Service, + Timer, } lazy_static! { @@ -42,8 +45,8 @@ lazy_static! { table.insert("path", UnitType::Path); table.insert("scope", UnitType::Scope); table.insert("service", UnitType::Service); - table.insert("slice", UnitType::Automount); - table.insert("automount", UnitType::Slice); + table.insert("slice", UnitType::Automount);//疑似copy错了,稍后修改 + table.insert("automount", UnitType::Slice);// table.insert("socket", UnitType::Socket); table.insert("swap", UnitType::Swap); table.insert("target", UnitType::Target); @@ -55,6 +58,8 @@ lazy_static! { table.insert("[Unit]", Segment::Unit); table.insert("[Install]", Segment::Install); table.insert("[Service]", Segment::Service); + table.insert("[Timer]", Segment::Timer); + // 后续再添加需求的具体字段 table }; pub static ref INSTALL_UNIT_ATTR_TABLE: HashMap<&'static str, InstallUnitAttr> = { @@ -147,10 +152,12 @@ lazy_static! { }; pub static ref TIMER_UNIT_ATTR_TABLE: HashMap<&'static str, TimerUnitAttr> = { let mut map = HashMap::new(); + // map.insert("State", TimerUnitAttr::State); + // map.insert("Result", TimerUnitAttr::Result); map.insert("OnActiveSec", TimerUnitAttr::OnActiveSec); map.insert("OnBootSec", TimerUnitAttr::OnBootSec); map.insert("OnStartupSec", TimerUnitAttr::OnStartUpSec); - map.insert("OnUnitActiveSec", TimerUnitAttr::OnUnitInactiveSec); + map.insert("OnUnitActiveSec", TimerUnitAttr::OnUnitActiveSec); map.insert("OnUnitInactiveSec", TimerUnitAttr::OnUnitInactiveSec); map.insert("OnCalendar", TimerUnitAttr::OnCalendar); map.insert("AccuracySec", TimerUnitAttr::AccuarcySec); @@ -216,6 +223,7 @@ impl UnitParser { match unit_type { UnitType::Service => ServiceParser::parse(path), UnitType::Target => TargetParser::parse(path), + UnitType::Timer=>TimerParser::parse(path),//新实现的timer_unit _ => Err(ParseError::new(ParseErrorType::EFILE, path.to_string(), 0)), } } @@ -317,7 +325,7 @@ impl UnitParser { } }; //首先匹配所有unit文件都有的unit段和install段 - if BASE_UNIT_ATTR_TABLE.get(attr_str).is_some() { + if BASE_UNIT_ATTR_TABLE.get(attr_str).is_some() {//匹配Unit字段 if segment != Segment::Unit { return Err(ParseError::new( ParseErrorType::EINVAL, @@ -333,7 +341,8 @@ impl UnitParser { e.set_linenum(i + 1); return Err(e); } - } else if INSTALL_UNIT_ATTR_TABLE.get(attr_str).is_some() { + } + else if INSTALL_UNIT_ATTR_TABLE.get(attr_str).is_some() {//匹配Install字段 if segment != Segment::Install { return Err(ParseError::new( ParseErrorType::EINVAL, diff --git a/src/parse/parse_timer/mod.rs b/src/parse/parse_timer/mod.rs new file mode 100644 index 0000000..2cd9ab4 --- /dev/null +++ b/src/parse/parse_timer/mod.rs @@ -0,0 +1,29 @@ +use super::graph::Graph; +use super::parse_util::UnitParseUtil; + +use crate::error::parse_error::ParseError; +use crate::manager::UnitManager; + +pub struct TimerParser; + +impl TimerParser { + /// @brief 解析Service类型Unit的 + /// + /// 从path解析Service类型Unit + /// + /// @param path 需解析的文件路径 + /// + /// @return 成功则返回Ok(id),否则返回Err + pub fn parse(path: &str) -> Result { + //预先检查是否存在循环依赖 + let mut graph = Graph::construct_graph(path.to_string())?; + let ret = graph.topological_sort()?; + for p in ret { + UnitParseUtil::parse_unit_no_type(&p)?; + } + + let result = UnitManager::get_id_with_path(path).unwrap(); + + return Ok(result); + } +} diff --git a/src/parse/parse_util/mod.rs b/src/parse/parse_util/mod.rs index 633f47f..48e9a22 100644 --- a/src/parse/parse_util/mod.rs +++ b/src/parse/parse_util/mod.rs @@ -2,9 +2,9 @@ use std::{fs, io::BufRead, os::unix::fs::PermissionsExt, path::Path}; use crate::{ contants::{AF_INET, AF_INET6, IPV4_MIN_MTU, IPV6_MIN_MTU, PRIO_MAX, PRIO_MIN}, - error::{parse_error::ParseError, parse_error::ParseErrorType}, + error::parse_error::{ParseError, ParseErrorType}, task::cmdtask::CmdTask, - unit::{service::ServiceUnit, target::TargetUnit, Unit, UnitType, Url}, + unit::{service::ServiceUnit, target::TargetUnit, timer::TimerUnit, Unit, UnitType, Url}, FileDescriptor, }; @@ -453,6 +453,7 @@ impl UnitParseUtil { //TODO: 目前为递归,后续应考虑从DragonReach管理的Unit表中寻找是否有该Unit,并且通过记录消除递归 "service" => UnitParser::parse::(path, UnitType::Service)?, "target" => UnitParser::parse::(path, UnitType::Target)?, + "timer" => UnitParser::parse::(path, UnitType::Timer)?, _ => { return Err(ParseError::new(ParseErrorType::EFILE, path.to_string(), 0)); } @@ -699,6 +700,7 @@ impl UnitParseUtil { match ret { "service" => return UnitType::Service, "target" => return UnitType::Target, + "timer" => return UnitType::Timer, //TODO: 添加文件类型 _ => return UnitType::Unknown, } diff --git a/src/systemctl/ctl_parser/mod.rs b/src/systemctl/ctl_parser/mod.rs index 045bba5..14b59a8 100644 --- a/src/systemctl/ctl_parser/mod.rs +++ b/src/systemctl/ctl_parser/mod.rs @@ -158,7 +158,7 @@ lazy_static! { let mut map = HashMap::new(); map.insert("list-units", CommandOperation::ListUnits); map.insert("list-sockets", CommandOperation::UnSupported); - map.insert("list-timers", CommandOperation::UnSupported); + map.insert("list-timers", CommandOperation::ListTimers); map.insert("start", CommandOperation::Start); map.insert("stop", CommandOperation::Stop); map.insert("reload", CommandOperation::UnSupported); diff --git a/src/systemctl/mod.rs b/src/systemctl/mod.rs index ce8cd94..d1bb335 100644 --- a/src/systemctl/mod.rs +++ b/src/systemctl/mod.rs @@ -3,7 +3,8 @@ use std::ffi::CString; pub mod ctl_parser; pub mod listener; -pub const DRAGON_REACH_CTL_PIPE: &'static str = "/etc/reach/ipc/ctl"; +//pub const DRAGON_REACH_CTL_PIPE: &'static str = "/etc/reach/ipc/ctl"; +pub const DRAGON_REACH_CTL_PIPE: &'static str = "/home/fz/myetc/reach/ipc/ctl"; pub fn ctl_path() -> CString { CString::new(DRAGON_REACH_CTL_PIPE).expect("Failed to create pipe CString") diff --git a/src/time/calandar/mod.rs b/src/time/calandar/mod.rs new file mode 100644 index 0000000..d7fbf82 --- /dev/null +++ b/src/time/calandar/mod.rs @@ -0,0 +1,105 @@ + +//use crate::error::parse_error::ParseError; + +#[derive(Debug,Default,Clone)] +pub struct CalendarComponent { + // start: usize, + // stop: usize, + // repeat: usize, + // next: Arc,//暂时不清楚为什么要链式设计 +} +#[derive(Debug,Default,Clone)] +pub struct CalendarStandard { + //@brief 星期几 + // weekdays_bits: Vec, + // year: usize, + // month: usize, + // day: usize, + // hour: usize, + // minute: usize, + // microsecond: usize, + // end_of_month: bool, + // utc: bool,//是否使用协调世界时(UTC),暂未实现 + // dst: usize,//夏令时的偏移量,暂未实现 + // timezone: String,//表示时区的名称,暂未实现 +} + +// 使用枚举而不是结构体来模拟C的复杂成员 + +// +//pub fn calendar_standard_to_string(spec: &CalendarStandard)->Result{ +// unimplemented!() +//} +//pub fn calendar_standard_from_string(spec: &CalendarStandard)->Result{ +// unimplemented!() +//} + +//@brief 解析日历格式,目前功能较弱,只能识别例如 Mon,Tue,Wed 2004-06-10 12:00:00的格式, +// 且暂不支持"*", +// pub fn parse_calendar(s: &str) -> Result { +// // Weekbits YYYY-MM-DD HH:mm:SS ,目前只支持Weekbits用","隔开 + +// // OnCalendar=*-*-* 00:00:00:每天的午夜触发。 +// // OnCalendar=*-*-* 08:00:00:每天早上8点触发。 +// // OnCalendar=Mon,Tue,Wed *-*-* 12:00:00:每周一、周二和周三的中午12点触发。 +// // OnCalendar=*-*-1 00:00:00:每个月的第一天午夜触发。 +// // OnCalendar=2019-01-01 00:00:00:指定的日期(2019年1月1日)触发。 +// let parts: Vec<&str> = s.split_whitespace().collect(); + +// if parts.len() < 2 || parts.len() > 3 { +// return Err("Invalid calendar format".to_string()); +// } +// let mut index:usize=0; + + +// let mut calendar = CalendarStandard { +// weekdays_bits: Vec::default(), +// year: 0, +// month: 0, +// day: 0, +// hour: 0, +// minute: 0, +// microsecond: 0, +// // end_of_month: false, +// // utc: false, +// // dst: 0, +// // timezone: String::new(), +// }; + +// // 解析字符串并填充 calendar 结构体的字段 +// // 注意:这里的解析逻辑仅供示例,实际情况可能需要更复杂的处理 + +// // 解析Weekbits +// if parts.len() == 3 { +// for day in parts[index].split(",") { +// match day.trim() { +// "Mon" => calendar.weekdays_bits.push(WeekdayBits::Mon), +// "Tue" => calendar.weekdays_bits.push(WeekdayBits::Tue), +// "Wed" => calendar.weekdays_bits.push(WeekdayBits::Wed), +// "Thu" => calendar.weekdays_bits.push(WeekdayBits::Thu), +// "Fri" => calendar.weekdays_bits.push(WeekdayBits::Fri), +// "Sat" => calendar.weekdays_bits.push(WeekdayBits::Sat), +// "Sun" => calendar.weekdays_bits.push(WeekdayBits::Sun), +// _ => return Err("Invalid weekday".to_string()), +// } +// } +// index+=1; +// } +// // 解析YYYY-MM-DD +// let mut iter = parts[index].split("-"); + +// let year = iter.next().unwrap().parse::().unwrap(); // 提取年并转换为i32类型 +// let month = iter.next().unwrap().parse::().unwrap(); // 提取月并转换为i32类型 +// let day = iter.next().unwrap().parse::().unwrap(); // 提取日并转换为i32类型 +// index+=1; + +// //解析HH:mm:SS +// let mut iter = parts[index].split(":"); + +// let year = iter.next().unwrap().parse::().unwrap(); // 提取年并转换为i32类型 +// let month = iter.next().unwrap().parse::().unwrap(); // 提取月并转换为i32类型 +// let day = iter.next().unwrap().parse::().unwrap(); // 提取日并转换为i32类型 + + +// Ok(calendar) +// } \ No newline at end of file diff --git a/src/time/mod.rs b/src/time/mod.rs index 9d032c8..ec2e9cf 100644 --- a/src/time/mod.rs +++ b/src/time/mod.rs @@ -1,2 +1,2 @@ pub mod timer; -pub mod watchdog; +pub mod calandar; diff --git a/src/time/timer/mod.rs b/src/time/timer/mod.rs index 16786fa..a35c3c4 100644 --- a/src/time/timer/mod.rs +++ b/src/time/timer/mod.rs @@ -1,6 +1,6 @@ use std::time::{Duration, Instant}; -use crate::error::runtime_error::RuntimeError; +use crate::{error::runtime_error::RuntimeError, unit::timer::{TimerUnit}}; /// 伪定时器,结合主循环来实现计时,在计时器触发时,会执行相应的cmd命令 /// 后续实现线程后,应使用线程实现 @@ -17,11 +17,13 @@ pub struct Timer { impl Timer { /// ## 创建计时任务 + //要new一个unit!!,查询id命名规则 pub fn new( duration: Duration, callback: Box Result<(), RuntimeError> + Send + Sync + 'static>, parent: usize, ) -> Self { + let _timerunit=TimerUnit::default(); Timer { instant: Instant::now(), callback: callback, @@ -34,7 +36,7 @@ impl Timer { /// /// ### return 到时返回true,否则返回false pub fn check(&mut self) -> bool { - //println!("{},{}",self.instant.elapsed().as_micros(),self.duration.as_micros()); + // println!("{},{}",self.instant.elapsed().as_micros(),self.duration.as_micros()); if self.instant.elapsed().saturating_sub(self.duration) > Duration::ZERO { // TODO: 未进行错误处理 if let Err(_e) = (self.callback)() { @@ -50,3 +52,4 @@ impl Timer { self.parent } } + diff --git a/src/time/watchdog/mod.rs b/src/time/watchdog/mod.rs deleted file mode 100644 index 8b13789..0000000 --- a/src/time/watchdog/mod.rs +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/unit/mod.rs b/src/unit/mod.rs index f38c77b..1bbade6 100644 --- a/src/unit/mod.rs +++ b/src/unit/mod.rs @@ -267,7 +267,7 @@ impl BaseUnit { attr_type: &InstallUnitAttr, val: &str, ) -> Result<(), ParseError> { - return self.install_part.set_attr(attr_type, val); + return self.install_part.set_attr(attr_type, val); } pub fn parse_and_set_attribute(&self) -> Result<(), ParseError> { diff --git a/src/unit/service/mod.rs b/src/unit/service/mod.rs index 01c371b..4ff3e23 100644 --- a/src/unit/service/mod.rs +++ b/src/unit/service/mod.rs @@ -4,6 +4,7 @@ use crate::error::{parse_error::ParseError, parse_error::ParseErrorType}; use crate::executor::service_executor::ServiceExecutor; use crate::executor::ExitStatus; +use crate::manager::timer_manager::TimerManager; use crate::parse::parse_service::ServiceParser; use crate::parse::parse_util::UnitParseUtil; use crate::parse::{Segment, SERVICE_UNIT_ATTR_TABLE}; @@ -43,7 +44,7 @@ impl Default for ServiceType { } #[derive(Debug, Clone, Copy, PartialEq)] -pub enum RestartOption { +pub enum RestartOption {//ServiceRestart AlwaysRestart, //总是重启 OnSuccess, //在该服务正常退出时 OnFailure, //在该服务启动失败时 @@ -213,6 +214,9 @@ impl Unit for ServiceUnit { fn exit(&mut self) { ServiceExecutor::exit(self); + //改变计时器内部状态 + TimerManager::adjust_timevalue(&self.unit_id(),false); + } fn restart(&mut self) -> Result<(), RuntimeError> { @@ -234,7 +238,9 @@ impl ServiceUnit { } fn exec(&mut self) -> Result<(), RuntimeError> { - ServiceExecutor::exec(self) + let _ = ServiceExecutor::exec(self); + //TimerManager::adjust_timevalue(&self.unit_id(), true); + Ok(()) } } @@ -242,7 +248,7 @@ unsafe impl Sync for ServiceUnit {} unsafe impl Send for ServiceUnit {} -pub enum ServiceUnitAttr { +pub enum ServiceUnitAttr {//ServiceExecCommand+ None, //Service段 //定义启动时的进程行为 diff --git a/src/unit/timer/mod.rs b/src/unit/timer/mod.rs index ae7df16..8e7ad82 100644 --- a/src/unit/timer/mod.rs +++ b/src/unit/timer/mod.rs @@ -1,34 +1,502 @@ -use super::BaseUnit; +use super::{BaseUnit, Unit}; +use crate::executor::Executor; +use crate::manager::timer_manager::TimerManager; +use crate::manager::UnitManager; +use crate::time::calandar::CalendarStandard; +use crate::parse::parse_timer::TimerParser; +use std::fmt::Debug; +use std::sync::{Arc, Mutex}; +use std::time::{Duration,Instant}; +use crate::parse::{Segment, TIMER_UNIT_ATTR_TABLE}; +use crate::error::runtime_error::{RuntimeError, RuntimeErrorType}; +use crate::error::parse_error::{ParseError, ParseErrorType}; +use crate::unit::UnitState; +use humantime::parse_duration; + #[allow(dead_code)] +#[derive(Clone, Debug)] pub struct TimerUnit { unit_base: BaseUnit, timer_part: TimerPart, } +impl Default for TimerUnit{ + fn default() -> Self { + Self { + unit_base: Default::default(), + timer_part: Default::default(), + } + } +} + +impl Unit for TimerUnit { + fn after_exit(&mut self, _exit_status: crate::executor::ExitStatus) { + + } + fn init(&mut self) { + let part=&mut self.timer_part; + part.remain_after_elapse = true; + + let part=&mut self.timer_part; + let now = Instant::now(); + part.last_trigger = now; + part.now_time = now; + + part.value.push(TimerVal::new(TimerUnitAttr::OnActiveSec, part.on_active_sec==Default::default(), + part.on_active_sec, Default::default(), Some(now+part.on_active_sec))); + //实现OnActiveSec的具体逻辑 + + let unit_is_running=UnitManager::is_running_unit(&part.unit); + + if part.on_unit_active_sec!=Default::default() { + let next_trigger = if unit_is_running { Some(now + part.on_unit_active_sec) } else { None }; + part.value.push(TimerVal::new(TimerUnitAttr::OnUnitActiveSec, !unit_is_running, part.on_unit_active_sec, + Default::default(), next_trigger)); + }//实现OnUnitActiveSec的具体逻辑 + + if part.on_unit_inactive_sec!=Default::default(){ + part.value.push(TimerVal::new(TimerUnitAttr::OnUnitInactiveSec, true, part.on_unit_inactive_sec, + Default::default(), None/*无论刚开始服务有没有在运行,逻辑上这里都不会有值 */)); + }//实现OnUnitInactiveSec的具体逻辑 + part.update_next_trigger(); + + self._init(); + } + + fn set_unit_name(&mut self, name: String) { + self.unit_base_mut().unit_name = name; + } + + fn restart(&mut self) -> Result<(), RuntimeError> { + self.exit(); + self.init(); + Ok(()) + } + + fn from_path(path: &str) -> Result + where Self: Sized { + TimerParser::parse(path) + } + + fn as_any(&self) -> &dyn std::any::Any { + self + } + + fn as_mut_any(&mut self) -> &mut dyn std::any::Any { + self + } + + fn set_attr(&mut self, segment: Segment, attr: &str, val: &str) -> Result<(), ParseError> { + if segment != Segment::Timer { + return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)); + } + let attr_type = TIMER_UNIT_ATTR_TABLE.get(attr).ok_or(ParseError::new( + ParseErrorType::EINVAL, + String::new(), + 0, + )); + return self.timer_part.set_attr(attr_type.unwrap(), val); + } + + fn set_unit_base(&mut self, unit_base: BaseUnit) { + self.unit_base=unit_base; + } + + fn unit_type(&self) -> super::UnitType { + self.unit_base.unit_type + } + + fn unit_base(&self) -> &BaseUnit { + &self.unit_base + } + + fn unit_base_mut(&mut self) -> &mut BaseUnit { + &mut self.unit_base + } + + fn unit_id(&self) -> usize { + self.unit_base.unit_id + } + + fn run(&mut self) -> Result<(), RuntimeError> {//TODO!! 错误检查 + let part=&mut self.timer_part; + part.now_time=Instant::now(); + //println!("{:?},{:?}",part.now_time.elapsed(),part.next_elapse_monotonic_or_boottime); + println!("Prepared to run"); + //检查Timer管理的unit是否存在 + if UnitManager::contains_id(&part.unit) { + let _ = self._run();//运行作出相应操作 + return Ok(()); + }else{ println!("task error,unit does not exist")}; + return Ok(()); + + } + + fn exit(&mut self) { + self.unit_base.state=UnitState::Inactive; + UnitManager::try_kill_running(self.unit_id()); + //TimerManager::remove_timer_unit(self.id) + } +} +impl TimerUnit { + fn _run(&mut self)-> Result<(), RuntimeError>{ + let part =&mut self.timer_part; + if part.value.is_empty(){//触发次数已尽 + self.unit_base.state=UnitState::Deactivating; + }else if matches!(part.value[0].attr, TimerUnitAttr::OnActiveSec | TimerUnitAttr::OnBootSec | TimerUnitAttr::OnStartUpSec) { + part.value.remove(0);//消耗掉此次run时的TimeValue值 + } + + if UnitManager::is_running_unit(&part.unit) {//如果服务已经启动,则退出 + return Ok(()); + } + + //执行相应的unit单元 + if let Ok(_) = Executor::exec(part.unit){ + self.unit_base.state=UnitState::Active; + return Ok(()); + }else{ + self.unit_base.state=UnitState::Failed; + return Err(RuntimeError::new(RuntimeErrorType::ExecFailed)); + } + } + fn _init(&self){ + let unit: Arc> = Arc::new(Mutex::new(self.clone())); + TimerManager::push_timer_unit(unit); + //UnitManager::push_running(unit); + } + + pub fn check(&mut self) -> bool { + let part=&mut self.timer_part; + if UnitManager::is_running_unit(&part.unit) {//在运行就不管了 + return false; + } + part.now_time=Instant::now(); + //检查下一个触发的TimerVal是不是disable + // println!("now time:{},next elapse time:{:?}",part.now_time.elapsed().as_micros(),part.next_elapse_monotonic_or_boottime); + if part.update_next_trigger(){ + self.unit_base.state=UnitState::Active; + }else { + self.unit_base.state=UnitState::Deactivating; + } + //计时器不可用 + if self.unit_base.state==UnitState::Deactivating{ + return false; + } + + //到时间执行Timer所管理的Unit + if part.last_trigger+(part.last_trigger.elapsed()) >= part.next_elapse_monotonic_or_boottime { + // 未进行错误处理 + + //检查Timer管理的unit是否存在 + if let Some(_) = UnitManager::get_unit_with_id(&part.unit) { + // let _ = unit.lock().unwrap().run();//运行作出相应操作 + return true; + } + println!("task error,unit does not exist"); + return false; + } + return false; + } + + pub fn unit_base(&self) -> &BaseUnit { + &self.unit_base + } + + pub fn timer_part(&self) -> &TimerPart { + &self.timer_part + } + + pub fn mut_timer_part(&mut self) -> &mut TimerPart { + &mut self.timer_part + } + pub fn timer_init(&mut self) { + let part=&mut self.timer_part; + part.next_elapse_monotonic_or_boottime = Instant::now(); + part.next_elapse_realtime = Instant::now(); + part.now_time = Instant::now(); + part.remain_after_elapse = true; + } + + + pub fn verify(&self)->Result<(),ParseError>{ + if self.unit_base.state!=UnitState::Reloading{ + return Err(ParseError::new(ParseErrorType::EFILE,self.unit_base.unit_name(), 0)); + } + let part= &self.timer_part; + if part.value.is_empty() && !part.on_clock_change && !part.on_timezone_change{ + return Err(ParseError::new(ParseErrorType::EFILE,self.unit_base.unit_name(), 0)); + } + Ok(()) + } + + + pub fn exec(&mut self) -> Result<(), RuntimeError> { + todo!() + //push_timer 1.检查时间是否正确 2.更新时间 3.做出操作 + } + + pub fn get_parent_unit(&mut self)->usize{ + self.timer_part().unit + } + + ///在unit exec或exit的时候改变TimerValue中OnUnitInactiveSec和OnUnitActiveSec的状态 + pub fn change_stage(&mut self,flag: bool /*1为启动0为退出 */){ + for val in &mut self.timer_part.value{ + match val.attr{ + TimerUnitAttr::OnUnitActiveSec=>{ + if flag { + val.disabled=false; + val.next_elapse=Some(Instant::now()+val.val); + } + }, + TimerUnitAttr::OnUnitInactiveSec=>{ + if !flag { + val.disabled=false; + val.next_elapse=Some(Instant::now()+val.val); + } + }, + _=>{}, + } + } + } +} +unsafe impl Sync for TimerUnit {} + +unsafe impl Send for TimerUnit {} #[allow(dead_code)] +#[derive( Debug, Clone)] pub struct TimerPart { - on_active_sec: u64, - on_boot_sec: u64, - on_start_up_sec: u64, - on_unit_inactive_sec: u64, - on_calendar: u64, - accuarcy_sec: u64, - randomized_delay_sec: u64, + //TODO! 未实现时间事件源的相关功能,目前还是循环确认Timer的情况 + + ///@brief 存储触发计时器的时间集合 + value: Vec, + + + ///@brief 相对于该单元自身被启动的时间点 + on_active_sec: Duration, + + ///@brief 相对于机器被启动的时间点 + on_boot_sec: Duration, + + ///@brief 相对于systemd被首次启动的时间点,也就是内核启动init进程的时间点 + on_start_up_sec: Duration, + + ///@brief 相对于匹配单元最后一次被启动的时间点 + on_unit_active_sec: Duration, + + ///@brief 相对于匹配单元 最后一次被停止的时间点 + on_unit_inactive_sec: Duration, + + ///@brief 定义基于挂钟时间(wallclock)的日历定时器,值是一个日历事件表达式 + on_calendar: CalendarStandard, + + ///@brief 设置定时器的触发精度,默认1min + accuarcy_sec: usize, + + ///@brief 随机延迟一小段时间,默认0表示不延迟 + randomized_delay_sec: usize, + + ///@brief fixed_random_delay: bool, + + ///@brief on_clock_change: bool, - on_time_zone_change: bool, + + ///@brief + on_timezone_change: bool, + + ///@brief 默认值是 与此定时器单元同名的服务单元 unit: usize, + + ///@brief 若设为"yes",则表示将匹配单元的上次触发时间永久保存在磁盘上,默认no persistent: bool, + + ///@brief 若设为"yes", 则表示当某个定时器到达触发时间点时, 唤醒正在休眠的系统并阻止系统进入休眠状态,默认no wake_system: bool, - remain_after_elapse: bool, + + ///@brief 若设为"yes" ,那么该定时器将不会被再次触发,也就是可以确保仅被触发一次;默认yes + remain_after_elapse: bool,//默认yes + + + ///@brief 表示计时器下次实时时间触发的时间戳 + next_elapse_realtime:Instant, + + ///@brief 表示计时器下次单调时间或引导时间触发的时间戳 + next_elapse_monotonic_or_boottime:Instant, + + ///@brief 用于存储计时器最后一次触发的时间戳。 + last_trigger :Instant, + + ///@brief 用于表示当前的时间。 + now_time: Instant, } -pub enum TimerUnitAttr { +impl Default for TimerPart{ + fn default() -> Self { + Self { + value:Default::default(), + on_active_sec: Default::default(), + on_boot_sec: Default::default(), + on_start_up_sec: Default::default(), + on_unit_active_sec: Default::default(), + on_unit_inactive_sec: Default::default(), + on_calendar: CalendarStandard::default(), + accuarcy_sec: 60, // 默认设置为 60 秒 + randomized_delay_sec: 0, + fixed_random_delay: false, + on_clock_change: false, + on_timezone_change: false, + unit: Default::default(), + persistent: false, + wake_system: false, + remain_after_elapse: true, + + next_elapse_realtime:Instant::now(), + next_elapse_monotonic_or_boottime:Instant::now(), + last_trigger :Instant::now(), + now_time: Instant::now(), + } + } +} + +impl TimerPart{ + /// 更新下一次的触发时间 + pub fn update_next_trigger(&mut self)->bool { + self.now_time = Instant::now(); + + //let unit_is_running=UnitManager::is_running_unit(&self.unit); + //检查并更新value + let mut index=0; + loop { + if index >= self.value.len() { + break; + } + let val=&mut self.value[index]; + match val.attr{ + TimerUnitAttr::OnUnitInactiveSec | TimerUnitAttr::OnUnitActiveSec => {//更新OnUnitInactiveSec和OnUnitActiveSec类型的值 + if val.disabled{ + index=index+1; + continue; + }else if val.next_elapse == None{ + val.next_elapse=Some(self.now_time+ val.val); + }else if val.next_elapse.unwrap(){ + if val.next_elapse.unwrap() { + if val.next_elapse.unwrap() todo!(), + //TimerUnitAttr::OnCalendar => todo!(), + _=> todo!(),//暂未支持 + } + index += 1; + } + // 对value排序,使得最早的定时器时间在最前面,且None类型在最后面 + self.value.sort_by//(|a, b| a.next_elapse.cmp(&b.next_elapse)); + (|a, b| match (a.next_elapse, b.next_elapse) { + (None, None) => std::cmp::Ordering::Equal, + (None, Some(_)) => std::cmp::Ordering::Greater, + (Some(_), None) => std::cmp::Ordering::Less, + (Some(a), Some(b)) => a.cmp(&b), + }); + if self.value.is_empty()||self.value[0].next_elapse==None{//计时器里面已经没有值了 + return false; + } + + // 从已排序的Vec中获取最早的定时器时间 + self.next_elapse_monotonic_or_boottime=self.value[0].next_elapse.unwrap(); + + return true; + } + pub fn set_attr(& mut self, attr: &TimerUnitAttr, val: &str)-> Result<(), ParseError>{ + match attr { + TimerUnitAttr::OnActiveSec => self.on_active_sec= { + if let Ok(duration) = parse_duration(val) { + duration + } else { + return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)); + } + }, + + TimerUnitAttr::OnBootSec=>self.on_boot_sec={ + if let Ok(duration) = parse_duration(val) { + duration + } else { + return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)); + } + }, + + TimerUnitAttr::OnStartUpSec=>self.on_start_up_sec={ + if let Ok(duration) = parse_duration(val) { + duration + } else { + return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)); + } + }, + TimerUnitAttr::OnUnitInactiveSec=>self.on_unit_inactive_sec={ + if let Ok(duration) = parse_duration(val) { + duration + } else { + return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)); + } + }, + TimerUnitAttr::OnUnitActiveSec=>self.on_unit_active_sec={ + if let Ok(duration) = parse_duration(val) { + duration + } else { + return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)); + } + }, + // TimerUnitAttr::OnCalendar=>self.on_calendar={ + // if let Ok(calendar) = parse_calendar(val) { + // calendar + // } else { + // return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)); + // } + // }, + TimerUnitAttr::Persistent=>self.persistent={ + match val{ + "true"=>true, + "false"=>false, + _=>return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)), + } + }, + TimerUnitAttr::Unit=>self.unit={ + UnitManager::get_id_with_path(val).unwrap() + }, + _ => { + return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)); + }, + } + Ok(()) + } +} +#[derive(Debug,Clone, Copy)] +pub enum TimerUnitAttr {//TimerBase + // State, + // Result, OnActiveSec, OnBootSec, OnStartUpSec, OnUnitInactiveSec, + OnUnitActiveSec, OnCalendar, AccuarcySec, RandomizedDelaySec, @@ -40,3 +508,33 @@ pub enum TimerUnitAttr { WakeSystem, RemainAfterElapse, } +impl Default for TimerUnitAttr{ + fn default() -> Self { + TimerUnitAttr::OnActiveSec + } +} + +#[derive(Debug, Clone)] +pub struct TimerVal { + attr:TimerUnitAttr,//原TimerBase + disabled:bool, + val:Duration, + //calendar_standard:Vec,//只针对calendar事件 + next_elapse:Option, +} + +impl TimerVal { + pub fn new( attr:TimerUnitAttr, + disabled:bool, + val:Duration, + calendar_standard:Vec, + next_elapse:Option,)->TimerVal{ + TimerVal{ + attr, + disabled, + val, + //calendar_standard, + next_elapse + } + } +} diff --git a/systemctl/src/main.rs b/systemctl/src/main.rs index 96ed6b1..e008d9c 100644 --- a/systemctl/src/main.rs +++ b/systemctl/src/main.rs @@ -1,6 +1,7 @@ use std::{env, fs::File, io::Write}; -const REACH_PIPE_PATH: &str = "/etc/reach/ipc/ctl"; +const REACH_PIPE_PATH: &str = "/home/fz/myetc/reach/ipc/ctl"; +//const REACH_PIPE_PATH: &str = "etc/reach/ipc/ctl"; fn main() { let mut args: Vec = env::args().collect(); From bc76ef919806d6d130d471621daba69388667e8f Mon Sep 17 00:00:00 2001 From: BrahmaMantra <2033552517.qq.com> Date: Mon, 22 Apr 2024 11:20:16 +0000 Subject: [PATCH 02/15] =?UTF-8?q?fmt+=E5=A2=9E=E5=8A=A0=E9=80=80=E5=87=BA?= =?UTF-8?q?=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main.rs | 40 +-- src/manager/mod.rs | 9 +- src/manager/timer_manager/mod.rs | 117 ++++--- src/manager/unit_manager/mod.rs | 2 +- src/time/calandar/mod.rs | 13 +- src/time/timer/mod.rs | 7 +- src/unit/mod.rs | 2 +- src/unit/service/mod.rs | 11 +- src/unit/timer/mod.rs | 512 ++++++++++++++++--------------- 9 files changed, 391 insertions(+), 322 deletions(-) diff --git a/src/main.rs b/src/main.rs index 62af6c3..b917741 100644 --- a/src/main.rs +++ b/src/main.rs @@ -20,7 +20,7 @@ const DRAGON_REACH_UNIT_DIR: &'static str = "/home/fz/testSystemd/"; fn main() { // 初始化 - Systemctl::init(); + Systemctl::init(); let mut units_file_name = Vec::new(); //读取目录里面的unit文件 @@ -47,23 +47,23 @@ fn main() { } }; - // if id != 0 && TimerManager::is_timer(&id){ - // if let Err(e) = Executor::exec(id) { - // eprintln!("Err:{}", e.error_format()); - // } - // } - // } - } - - // 启动完服务后进入主循环 - loop { - // 检查各服务运行状态 - Manager::check_running_status(); - // 检查cmd进程状态 - Manager::check_cmd_proc(); - // 检查计时器任务 - TimerManager::check_timer(); - // 监听systemctl - Systemctl::ctl_listen(); - } + // if id != 0 && TimerManager::is_timer(&id){ + // if let Err(e) = Executor::exec(id) { + // eprintln!("Err:{}", e.error_format()); + // } + // } + // } + } + + // 启动完服务后进入主循环 + loop { + // 检查各服务运行状态 + Manager::check_running_status(); + // 检查cmd进程状态 + Manager::check_cmd_proc(); + // 检查计时器任务 + TimerManager::check_timer(); + // 监听systemctl + Systemctl::ctl_listen(); + } } diff --git a/src/manager/mod.rs b/src/manager/mod.rs index db8bde4..b36d04e 100644 --- a/src/manager/mod.rs +++ b/src/manager/mod.rs @@ -47,11 +47,12 @@ impl Manager { // 取消该任务的定时器任务 TimerManager::cancel_timer(tmp.0); - + let _ = UnitManager::get_unit_with_id(&tmp.0) - .unwrap() - .lock().unwrap() - .exit();//交付给相应类型的Unit类型去执行退出后的逻辑 + .unwrap() + .lock() + .unwrap() + .exit(); //交付给相应类型的Unit类型去执行退出后的逻辑 // 交付处理子进程退出逻辑 let unit = UnitManager::get_unit_with_id(&tmp.0).unwrap(); diff --git a/src/manager/timer_manager/mod.rs b/src/manager/timer_manager/mod.rs index b7be974..735cbe2 100644 --- a/src/manager/timer_manager/mod.rs +++ b/src/manager/timer_manager/mod.rs @@ -1,22 +1,29 @@ -use std::{sync::{Arc, Mutex, RwLock}, time::Duration}; +use std::{ + sync::{Arc, Mutex, RwLock}, + time::Duration, +}; -use crate::{error::runtime_error::RuntimeError, time::timer::Timer, unit::timer::TimerUnit,unit::Unit}; +use crate::{ + error::runtime_error::RuntimeError, time::timer::Timer, unit::timer::TimerUnit, unit::Unit, +}; use hashbrown::HashMap; use lazy_static::lazy_static; +use super::UnitManager; + lazy_static! { // 管理全局计时器任务 static ref TIMER_TASK_MANAGER:RwLock = RwLock::new(TimerManager { inner_timers: Vec::new(), - inner_timers_unit: Vec::new(), + inner_timers_map: RwLock::new(HashMap::new()), id_table:RwLock::new(Vec::new())//.0是TimerUnit的id,.1是父Unit的id }); } pub struct TimerManager { inner_timers: Vec, - inner_timers_unit: Vec>>, - id_table: RwLock>, + inner_timers_map: RwLock>>>, + id_table: RwLock>, } impl<'a> IntoIterator for &'a mut TimerManager { @@ -44,16 +51,21 @@ impl TimerManager { .push(Timer::new(duration, Box::new(callback), parent)); } - pub fn push_timer_unit(unit:Arc>) - { - let mut timemanager=TIMER_TASK_MANAGER + pub fn push_timer_unit(unit: Arc>) { + let timemanager = TIMER_TASK_MANAGER.write().unwrap(); + let mut unit_ = unit.lock().unwrap(); + let unit_id = unit_.unit_id(); + timemanager + .id_table .write() - .unwrap(); - let mut unit_ =unit.lock().unwrap(); - timemanager.id_table.write().unwrap().push((unit_.unit_id(), unit_.get_parent_unit())); + .unwrap() + .push((unit_id, unit_.get_parent_unit())); drop(unit_); - timemanager.inner_timers_unit - .push(unit);//加入到inner_timers_unit + timemanager + .inner_timers_map + .write() + .unwrap() + .insert(unit_id, unit); //加入到inner_timers_map } /// ## 检测定时器是否到时,到时则触发 @@ -67,15 +79,28 @@ impl TimerManager { //此处触发Timer_unit,不移除 let reader = TIMER_TASK_MANAGER.read().unwrap(); - for timer in &reader.inner_timers_unit { - let mut timer_unit=timer.lock().unwrap(); + let mut inactive_unit: Vec = Vec::new(); + for (_, timer_unit) in reader.inner_timers_map.read().unwrap().iter() { + let mut timer_unit = timer_unit.lock().unwrap(); + if timer_unit.enter_inactive() { + inactive_unit.push(timer_unit.unit_id()); + continue; + } if timer_unit.check() { - let _ = timer_unit.run();//运行作出相应操作 - let id =timer_unit.get_parent_unit(); - drop(timer_unit); - TimerManager::adjust_timevalue(&id, true); + let _ = timer_unit.run(); //运行作出相应操作 + let id = timer_unit.get_parent_unit(); + drop(timer_unit); + TimerManager::adjust_timevalue(&id, true); } - + } + + for iter in inactive_unit { + //println!("Prepared to exit..."); + UnitManager::get_unit_with_id(&iter) + .unwrap() + .lock() + .unwrap() + .exit(); } } @@ -90,29 +115,49 @@ impl TimerManager { .retain(|x| x.parent() == unit_id) } - pub fn is_timer(id:&usize)->bool{ - let id_table=&TIMER_TASK_MANAGER - .read() - .unwrap() - .id_table; - for iter in id_table.read().unwrap().iter(){ - if iter.0==*id { + pub fn is_timer(id: &usize) -> bool { + let id_table = &TIMER_TASK_MANAGER.read().unwrap().id_table; + for iter in id_table.read().unwrap().iter() { + if iter.0 == *id { return true; } } false } - /// unit_id:父unit的id flag:1为exec 0为exit - pub fn adjust_timevalue(unit_id: &usize, flag: bool /*1为启动0为退出 */){ - let manager=TIMER_TASK_MANAGER - .read() - .unwrap(); - for iter in &manager.inner_timers_unit{ - let mut unit =iter.lock().unwrap(); - if unit.get_parent_unit()==*unit_id{ - unit.change_stage(flag); + /// unit_id:父unit的id flag:1为exec 0为exit + pub fn adjust_timevalue(unit_id: &usize, flag: bool /*1为启动0为退出 */) { + let manager: std::sync::RwLockReadGuard<'_, TimerManager> = + TIMER_TASK_MANAGER.read().unwrap(); + + for (self_id, parent_id) in manager.id_table.read().unwrap().iter() { + if unit_id == parent_id { + manager + .inner_timers_map + .read() + .unwrap() + .get(self_id) + .unwrap() + .lock() + .unwrap() + .change_stage(flag) } } + //get(unit_id).unwrap().lock().unwrap().change_stage(flag) } + /// 从Timer表中删除该Unit + pub fn remove_timer_unit(unit_id: usize) { + let manager = TIMER_TASK_MANAGER.read().unwrap(); + + manager.inner_timers_map.write().unwrap().remove(&unit_id); + let index: usize = 0; + let mut id_table = manager.id_table.write().unwrap(); + for (self_id, _) in id_table.iter() { + //因为id是递增的,后续可优化为二分查找 + if unit_id == *self_id { + id_table.remove(index); + return; + } + } + } } diff --git a/src/manager/unit_manager/mod.rs b/src/manager/unit_manager/mod.rs index aa6182d..723d3fa 100644 --- a/src/manager/unit_manager/mod.rs +++ b/src/manager/unit_manager/mod.rs @@ -144,7 +144,7 @@ impl UnitManager { pub fn pop_a_idle_service() -> Option>> { let id = IDLE_SERVIEC_DEQUE.lock().unwrap().pop_front(); match id { - Some(id) => { + Some(id) => { return Self::get_unit_with_id(&id); } None => { diff --git a/src/time/calandar/mod.rs b/src/time/calandar/mod.rs index d7fbf82..a07ff96 100644 --- a/src/time/calandar/mod.rs +++ b/src/time/calandar/mod.rs @@ -1,17 +1,16 @@ - //use crate::error::parse_error::ParseError; -#[derive(Debug,Default,Clone)] +#[derive(Debug, Default, Clone)] pub struct CalendarComponent { // start: usize, // stop: usize, // repeat: usize, // next: Arc,//暂时不清楚为什么要链式设计 } -#[derive(Debug,Default,Clone)] +#[derive(Debug, Default, Clone)] pub struct CalendarStandard { //@brief 星期几 - // weekdays_bits: Vec, + // weekdays_bits: Vec, // year: usize, // month: usize, // day: usize, @@ -38,7 +37,7 @@ pub struct CalendarStandard { // 且暂不支持"*", // pub fn parse_calendar(s: &str) -> Result { // // Weekbits YYYY-MM-DD HH:mm:SS ,目前只支持Weekbits用","隔开 - + // // OnCalendar=*-*-* 00:00:00:每天的午夜触发。 // // OnCalendar=*-*-* 08:00:00:每天早上8点触发。 // // OnCalendar=Mon,Tue,Wed *-*-* 12:00:00:每周一、周二和周三的中午12点触发。 @@ -51,7 +50,6 @@ pub struct CalendarStandard { // } // let mut index:usize=0; - // let mut calendar = CalendarStandard { // weekdays_bits: Vec::default(), // year: 0, @@ -100,6 +98,5 @@ pub struct CalendarStandard { // let month = iter.next().unwrap().parse::().unwrap(); // 提取月并转换为i32类型 // let day = iter.next().unwrap().parse::().unwrap(); // 提取日并转换为i32类型 - // Ok(calendar) -// } \ No newline at end of file +// } diff --git a/src/time/timer/mod.rs b/src/time/timer/mod.rs index a35c3c4..51355c6 100644 --- a/src/time/timer/mod.rs +++ b/src/time/timer/mod.rs @@ -1,6 +1,6 @@ use std::time::{Duration, Instant}; -use crate::{error::runtime_error::RuntimeError, unit::timer::{TimerUnit}}; +use crate::{error::runtime_error::RuntimeError, unit::timer::TimerUnit}; /// 伪定时器,结合主循环来实现计时,在计时器触发时,会执行相应的cmd命令 /// 后续实现线程后,应使用线程实现 @@ -23,7 +23,7 @@ impl Timer { callback: Box Result<(), RuntimeError> + Send + Sync + 'static>, parent: usize, ) -> Self { - let _timerunit=TimerUnit::default(); + let _timerunit = TimerUnit::default(); Timer { instant: Instant::now(), callback: callback, @@ -36,7 +36,7 @@ impl Timer { /// /// ### return 到时返回true,否则返回false pub fn check(&mut self) -> bool { - // println!("{},{}",self.instant.elapsed().as_micros(),self.duration.as_micros()); + // println!("{},{}",self.instant.elapsed().as_micros(),self.duration.as_micros()); if self.instant.elapsed().saturating_sub(self.duration) > Duration::ZERO { // TODO: 未进行错误处理 if let Err(_e) = (self.callback)() { @@ -52,4 +52,3 @@ impl Timer { self.parent } } - diff --git a/src/unit/mod.rs b/src/unit/mod.rs index 1bbade6..f38c77b 100644 --- a/src/unit/mod.rs +++ b/src/unit/mod.rs @@ -267,7 +267,7 @@ impl BaseUnit { attr_type: &InstallUnitAttr, val: &str, ) -> Result<(), ParseError> { - return self.install_part.set_attr(attr_type, val); + return self.install_part.set_attr(attr_type, val); } pub fn parse_and_set_attribute(&self) -> Result<(), ParseError> { diff --git a/src/unit/service/mod.rs b/src/unit/service/mod.rs index 4ff3e23..1b5fe17 100644 --- a/src/unit/service/mod.rs +++ b/src/unit/service/mod.rs @@ -44,7 +44,8 @@ impl Default for ServiceType { } #[derive(Debug, Clone, Copy, PartialEq)] -pub enum RestartOption {//ServiceRestart +pub enum RestartOption { + //ServiceRestart AlwaysRestart, //总是重启 OnSuccess, //在该服务正常退出时 OnFailure, //在该服务启动失败时 @@ -214,9 +215,8 @@ impl Unit for ServiceUnit { fn exit(&mut self) { ServiceExecutor::exit(self); - //改变计时器内部状态 - TimerManager::adjust_timevalue(&self.unit_id(),false); - + //改变计时器内部状态 + TimerManager::adjust_timevalue(&self.unit_id(), false); } fn restart(&mut self) -> Result<(), RuntimeError> { @@ -248,7 +248,8 @@ unsafe impl Sync for ServiceUnit {} unsafe impl Send for ServiceUnit {} -pub enum ServiceUnitAttr {//ServiceExecCommand+ +pub enum ServiceUnitAttr { + //ServiceExecCommand+ None, //Service段 //定义启动时的进程行为 diff --git a/src/unit/timer/mod.rs b/src/unit/timer/mod.rs index 8e7ad82..dc947f4 100644 --- a/src/unit/timer/mod.rs +++ b/src/unit/timer/mod.rs @@ -1,18 +1,17 @@ use super::{BaseUnit, Unit}; +use crate::error::parse_error::{ParseError, ParseErrorType}; +use crate::error::runtime_error::{RuntimeError, RuntimeErrorType}; use crate::executor::Executor; use crate::manager::timer_manager::TimerManager; use crate::manager::UnitManager; -use crate::time::calandar::CalendarStandard; use crate::parse::parse_timer::TimerParser; -use std::fmt::Debug; -use std::sync::{Arc, Mutex}; -use std::time::{Duration,Instant}; use crate::parse::{Segment, TIMER_UNIT_ATTR_TABLE}; -use crate::error::runtime_error::{RuntimeError, RuntimeErrorType}; -use crate::error::parse_error::{ParseError, ParseErrorType}; +use crate::time::calandar::CalendarStandard; use crate::unit::UnitState; use humantime::parse_duration; - +use std::fmt::Debug; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; #[allow(dead_code)] #[derive(Clone, Debug)] @@ -21,47 +20,64 @@ pub struct TimerUnit { timer_part: TimerPart, } -impl Default for TimerUnit{ +impl Default for TimerUnit { fn default() -> Self { - Self { - unit_base: Default::default(), + Self { + unit_base: Default::default(), timer_part: Default::default(), } } } impl Unit for TimerUnit { - fn after_exit(&mut self, _exit_status: crate::executor::ExitStatus) { - - } fn init(&mut self) { - let part=&mut self.timer_part; + self.unit_base.state = UnitState::Activating; + let part = &mut self.timer_part; part.remain_after_elapse = true; - let part=&mut self.timer_part; + let part = &mut self.timer_part; let now = Instant::now(); part.last_trigger = now; part.now_time = now; - part.value.push(TimerVal::new(TimerUnitAttr::OnActiveSec, part.on_active_sec==Default::default(), - part.on_active_sec, Default::default(), Some(now+part.on_active_sec))); + part.value.push(TimerVal::new( + TimerUnitAttr::OnActiveSec, + part.on_active_sec == Default::default(), + part.on_active_sec, + Default::default(), + Some(now + part.on_active_sec), + )); //实现OnActiveSec的具体逻辑 - let unit_is_running=UnitManager::is_running_unit(&part.unit); - - if part.on_unit_active_sec!=Default::default() { - let next_trigger = if unit_is_running { Some(now + part.on_unit_active_sec) } else { None }; - part.value.push(TimerVal::new(TimerUnitAttr::OnUnitActiveSec, !unit_is_running, part.on_unit_active_sec, - Default::default(), next_trigger)); - }//实现OnUnitActiveSec的具体逻辑 - - if part.on_unit_inactive_sec!=Default::default(){ - part.value.push(TimerVal::new(TimerUnitAttr::OnUnitInactiveSec, true, part.on_unit_inactive_sec, - Default::default(), None/*无论刚开始服务有没有在运行,逻辑上这里都不会有值 */)); - }//实现OnUnitInactiveSec的具体逻辑 + let unit_is_running = UnitManager::is_running_unit(&part.unit); + + if part.on_unit_active_sec != Default::default() { + let next_trigger = if unit_is_running { + Some(now + part.on_unit_active_sec) + } else { + None + }; + part.value.push(TimerVal::new( + TimerUnitAttr::OnUnitActiveSec, + !unit_is_running, + part.on_unit_active_sec, + Default::default(), + next_trigger, + )); + } //实现OnUnitActiveSec的具体逻辑 + + if part.on_unit_inactive_sec != Default::default() { + part.value.push(TimerVal::new( + TimerUnitAttr::OnUnitInactiveSec, + true, + part.on_unit_inactive_sec, + Default::default(), + None, /*无论刚开始服务有没有在运行,逻辑上这里都不会有值 */ + )); + } //实现OnUnitInactiveSec的具体逻辑 part.update_next_trigger(); - self._init(); + self.unit_base.state = UnitState::Active; } fn set_unit_name(&mut self, name: String) { @@ -73,20 +89,22 @@ impl Unit for TimerUnit { self.init(); Ok(()) } - + fn from_path(path: &str) -> Result - where Self: Sized { - TimerParser::parse(path) - } - + where + Self: Sized, + { + TimerParser::parse(path) + } + fn as_any(&self) -> &dyn std::any::Any { self } - + fn as_mut_any(&mut self) -> &mut dyn std::any::Any { self } - + fn set_attr(&mut self, segment: Segment, attr: &str, val: &str) -> Result<(), ParseError> { if segment != Segment::Timer { return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)); @@ -95,103 +113,114 @@ impl Unit for TimerUnit { ParseErrorType::EINVAL, String::new(), 0, - )); + )); return self.timer_part.set_attr(attr_type.unwrap(), val); } - + fn set_unit_base(&mut self, unit_base: BaseUnit) { - self.unit_base=unit_base; + self.unit_base = unit_base; } - + fn unit_type(&self) -> super::UnitType { self.unit_base.unit_type } - + fn unit_base(&self) -> &BaseUnit { &self.unit_base } - + fn unit_base_mut(&mut self) -> &mut BaseUnit { &mut self.unit_base } - + fn unit_id(&self) -> usize { self.unit_base.unit_id } - - fn run(&mut self) -> Result<(), RuntimeError> {//TODO!! 错误检查 - let part=&mut self.timer_part; - part.now_time=Instant::now(); - //println!("{:?},{:?}",part.now_time.elapsed(),part.next_elapse_monotonic_or_boottime); - println!("Prepared to run"); - //检查Timer管理的unit是否存在 - if UnitManager::contains_id(&part.unit) { - let _ = self._run();//运行作出相应操作 - return Ok(()); - }else{ println!("task error,unit does not exist")}; - return Ok(()); + fn run(&mut self) -> Result<(), RuntimeError> { + //TODO!! 错误检查 + let part = &mut self.timer_part; + part.now_time = Instant::now(); + //println!("Prepared to run"); + //检查Timer管理的unit是否存在 + if UnitManager::contains_id(&part.unit) { + let _ = self._run(); //运行作出相应操作 + return Ok(()); + } else { + println!("task error,unit does not exist") + }; + return Ok(()); } - + fn exit(&mut self) { - self.unit_base.state=UnitState::Inactive; UnitManager::try_kill_running(self.unit_id()); - //TimerManager::remove_timer_unit(self.id) + TimerManager::remove_timer_unit(self.unit_id()); } } impl TimerUnit { - fn _run(&mut self)-> Result<(), RuntimeError>{ - let part =&mut self.timer_part; - if part.value.is_empty(){//触发次数已尽 - self.unit_base.state=UnitState::Deactivating; - }else if matches!(part.value[0].attr, TimerUnitAttr::OnActiveSec | TimerUnitAttr::OnBootSec | TimerUnitAttr::OnStartUpSec) { - part.value.remove(0);//消耗掉此次run时的TimeValue值 + fn _run(&mut self) -> Result<(), RuntimeError> { + let part = &mut self.timer_part; + if part.value.is_empty() { + //触发次数已尽 + self.unit_base.state = UnitState::Deactivating; + } else if matches!( + part.value[0].attr, + TimerUnitAttr::OnActiveSec | TimerUnitAttr::OnBootSec | TimerUnitAttr::OnStartUpSec + ) { + part.value.remove(0); //消耗掉此次run时的TimeValue值 } - if UnitManager::is_running_unit(&part.unit) {//如果服务已经启动,则退出 + if UnitManager::is_running_unit(&part.unit) { + //如果服务已经启动,则退出 return Ok(()); } //执行相应的unit单元 - if let Ok(_) = Executor::exec(part.unit){ - self.unit_base.state=UnitState::Active; + if let Ok(_) = Executor::exec(part.unit) { + self.unit_base.state = UnitState::Active; return Ok(()); - }else{ - self.unit_base.state=UnitState::Failed; + } else { + self.unit_base.state = UnitState::Failed; return Err(RuntimeError::new(RuntimeErrorType::ExecFailed)); } } - fn _init(&self){ + fn _init(&self) { let unit: Arc> = Arc::new(Mutex::new(self.clone())); TimerManager::push_timer_unit(unit); - //UnitManager::push_running(unit); } pub fn check(&mut self) -> bool { - let part=&mut self.timer_part; - if UnitManager::is_running_unit(&part.unit) {//在运行就不管了 - return false; - } - part.now_time=Instant::now(); + let part = &mut self.timer_part; + if UnitManager::is_running_unit(&part.unit) { + //在运行就不管了 + return false; + } + part.now_time = Instant::now(); //检查下一个触发的TimerVal是不是disable - // println!("now time:{},next elapse time:{:?}",part.now_time.elapsed().as_micros(),part.next_elapse_monotonic_or_boottime); - if part.update_next_trigger(){ - self.unit_base.state=UnitState::Active; - }else { - self.unit_base.state=UnitState::Deactivating; + // println!("now time:{},next elapse time:{:?}",part.now_time.elapsed().as_micros(),part.next_elapse_monotonic_or_boottime); + if part.update_next_trigger() { + self.unit_base.state = UnitState::Active; + } else if part.value.len() == 0 { + self.unit_base.state = UnitState::Inactive; //计时器里不再有值 + } else { + self.unit_base.state = UnitState::Deactivating; } //计时器不可用 - if self.unit_base.state==UnitState::Deactivating{ + if self.unit_base.state == UnitState::Deactivating + || self.unit_base.state == UnitState::Inactive + { return false; } //到时间执行Timer所管理的Unit - if part.last_trigger+(part.last_trigger.elapsed()) >= part.next_elapse_monotonic_or_boottime { + if part.last_trigger + (part.last_trigger.elapsed()) + >= part.next_elapse_monotonic_or_boottime + { // 未进行错误处理 - + //检查Timer管理的unit是否存在 if let Some(_) = UnitManager::get_unit_with_id(&part.unit) { - // let _ = unit.lock().unwrap().run();//运行作出相应操作 + // let _ = unit.lock().unwrap().run();//运行作出相应操作 return true; } println!("task error,unit does not exist"); @@ -212,52 +241,46 @@ impl TimerUnit { &mut self.timer_part } pub fn timer_init(&mut self) { - let part=&mut self.timer_part; + let part = &mut self.timer_part; part.next_elapse_monotonic_or_boottime = Instant::now(); part.next_elapse_realtime = Instant::now(); - part.now_time = Instant::now(); + part.now_time = Instant::now(); part.remain_after_elapse = true; } - - - pub fn verify(&self)->Result<(),ParseError>{ - if self.unit_base.state!=UnitState::Reloading{ - return Err(ParseError::new(ParseErrorType::EFILE,self.unit_base.unit_name(), 0)); - } - let part= &self.timer_part; - if part.value.is_empty() && !part.on_clock_change && !part.on_timezone_change{ - return Err(ParseError::new(ParseErrorType::EFILE,self.unit_base.unit_name(), 0)); - } - Ok(()) - } - pub fn exec(&mut self) -> Result<(), RuntimeError> { todo!() //push_timer 1.检查时间是否正确 2.更新时间 3.做出操作 } - pub fn get_parent_unit(&mut self)->usize{ + pub fn get_parent_unit(&mut self) -> usize { self.timer_part().unit } + pub fn enter_inactive(&mut self) -> bool { + if self.unit_base.state == UnitState::Inactive { + return true; + } + false + } + ///在unit exec或exit的时候改变TimerValue中OnUnitInactiveSec和OnUnitActiveSec的状态 - pub fn change_stage(&mut self,flag: bool /*1为启动0为退出 */){ - for val in &mut self.timer_part.value{ - match val.attr{ - TimerUnitAttr::OnUnitActiveSec=>{ + pub fn change_stage(&mut self, flag: bool /*1为启动0为退出 */) { + for val in &mut self.timer_part.value { + match val.attr { + TimerUnitAttr::OnUnitActiveSec => { if flag { - val.disabled=false; - val.next_elapse=Some(Instant::now()+val.val); + val.disabled = false; + val.next_elapse = Some(Instant::now() + val.val); } - }, - TimerUnitAttr::OnUnitInactiveSec=>{ + } + TimerUnitAttr::OnUnitInactiveSec => { if !flag { - val.disabled=false; - val.next_elapse=Some(Instant::now()+val.val); + val.disabled = false; + val.next_elapse = Some(Instant::now() + val.val); } - }, - _=>{}, + } + _ => {} } } } @@ -266,14 +289,12 @@ unsafe impl Sync for TimerUnit {} unsafe impl Send for TimerUnit {} #[allow(dead_code)] -#[derive( Debug, Clone)] +#[derive(Debug, Clone)] pub struct TimerPart { //TODO! 未实现时间事件源的相关功能,目前还是循环确认Timer的情况 - ///@brief 存储触发计时器的时间集合 value: Vec, - ///@brief 相对于该单元自身被启动的时间点 on_active_sec: Duration, @@ -298,16 +319,16 @@ pub struct TimerPart { ///@brief 随机延迟一小段时间,默认0表示不延迟 randomized_delay_sec: usize, - ///@brief + ///@brief fixed_random_delay: bool, - ///@brief + ///@brief on_clock_change: bool, - ///@brief + ///@brief on_timezone_change: bool, - ///@brief 默认值是 与此定时器单元同名的服务单元 + ///@brief 默认值是 与此定时器单元同名的服务单元 unit: usize, ///@brief 若设为"yes",则表示将匹配单元的上次触发时间永久保存在磁盘上,默认no @@ -317,26 +338,25 @@ pub struct TimerPart { wake_system: bool, ///@brief 若设为"yes" ,那么该定时器将不会被再次触发,也就是可以确保仅被触发一次;默认yes - remain_after_elapse: bool,//默认yes - + remain_after_elapse: bool, //默认yes ///@brief 表示计时器下次实时时间触发的时间戳 - next_elapse_realtime:Instant, + next_elapse_realtime: Instant, ///@brief 表示计时器下次单调时间或引导时间触发的时间戳 - next_elapse_monotonic_or_boottime:Instant, + next_elapse_monotonic_or_boottime: Instant, ///@brief 用于存储计时器最后一次触发的时间戳。 - last_trigger :Instant, + last_trigger: Instant, ///@brief 用于表示当前的时间。 now_time: Instant, } -impl Default for TimerPart{ +impl Default for TimerPart { fn default() -> Self { - Self { - value:Default::default(), + Self { + value: Default::default(), on_active_sec: Default::default(), on_boot_sec: Default::default(), on_start_up_sec: Default::default(), @@ -353,61 +373,53 @@ impl Default for TimerPart{ wake_system: false, remain_after_elapse: true, - next_elapse_realtime:Instant::now(), - next_elapse_monotonic_or_boottime:Instant::now(), - last_trigger :Instant::now(), + next_elapse_realtime: Instant::now(), + next_elapse_monotonic_or_boottime: Instant::now(), + last_trigger: Instant::now(), now_time: Instant::now(), - } + } } } -impl TimerPart{ +impl TimerPart { /// 更新下一次的触发时间 - pub fn update_next_trigger(&mut self)->bool { + pub fn update_next_trigger(&mut self) -> bool { self.now_time = Instant::now(); - //let unit_is_running=UnitManager::is_running_unit(&self.unit); - //检查并更新value - let mut index=0; - loop { - if index >= self.value.len() { - break; - } - let val=&mut self.value[index]; - match val.attr{ - TimerUnitAttr::OnUnitInactiveSec | TimerUnitAttr::OnUnitActiveSec => {//更新OnUnitInactiveSec和OnUnitActiveSec类型的值 - if val.disabled{ - index=index+1; - continue; - }else if val.next_elapse == None{ - val.next_elapse=Some(self.now_time+ val.val); - }else if val.next_elapse.unwrap(){ - if val.next_elapse.unwrap() { - if val.next_elapse.unwrap() todo!(), - //TimerUnitAttr::OnCalendar => todo!(), - _=> todo!(),//暂未支持 - } - index += 1; - } + //let unit_is_running=UnitManager::is_running_unit(&self.unit); + //检查并更新value + let mut index = 0; + while index < self.value.len() { + let val = &mut self.value[index]; + match val.attr { + TimerUnitAttr::OnUnitInactiveSec | TimerUnitAttr::OnUnitActiveSec => { + //更新OnUnitInactiveSec和OnUnitActiveSec类型的值 + if val.disabled { + index = index + 1; + continue; + } else if val.next_elapse == None { + val.next_elapse = Some(self.now_time + val.val); + } else if val.next_elapse.unwrap() < self.now_time { + self.next_elapse_monotonic_or_boottime = val.next_elapse.unwrap(); + val.next_elapse = Some(self.now_time + val.val); + // println!("Update the time!"); + return true; + } + } + + TimerUnitAttr::OnActiveSec | TimerUnitAttr::OnBootSec => { + if val.next_elapse.unwrap() < self.now_time { + self.next_elapse_monotonic_or_boottime = val.next_elapse.unwrap(); + self.value.remove(index); //在这一步准备把iter从value里弹出去 + return true; + } + } + //TimerUnitAttr::OnStartUpSec => todo!(), + //TimerUnitAttr::OnCalendar => todo!(), + _ => todo!(), //暂未支持 + } + index += 1; + } // 对value排序,使得最早的定时器时间在最前面,且None类型在最后面 self.value.sort_by//(|a, b| a.next_elapse.cmp(&b.next_elapse)); (|a, b| match (a.next_elapse, b.next_elapse) { @@ -416,80 +428,92 @@ impl TimerPart{ (Some(_), None) => std::cmp::Ordering::Less, (Some(a), Some(b)) => a.cmp(&b), }); - if self.value.is_empty()||self.value[0].next_elapse==None{//计时器里面已经没有值了 + if self.value.is_empty() || self.value[0].next_elapse == None { + //计时器里面已经没有值了 return false; } // 从已排序的Vec中获取最早的定时器时间 - self.next_elapse_monotonic_or_boottime=self.value[0].next_elapse.unwrap(); + self.next_elapse_monotonic_or_boottime = self.value[0].next_elapse.unwrap(); return true; } - pub fn set_attr(& mut self, attr: &TimerUnitAttr, val: &str)-> Result<(), ParseError>{ + pub fn set_attr(&mut self, attr: &TimerUnitAttr, val: &str) -> Result<(), ParseError> { match attr { - TimerUnitAttr::OnActiveSec => self.on_active_sec= { - if let Ok(duration) = parse_duration(val) { - duration - } else { - return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)); + TimerUnitAttr::OnActiveSec => { + self.on_active_sec = { + if let Ok(duration) = parse_duration(val) { + duration + } else { + return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)); + } } - }, + } - TimerUnitAttr::OnBootSec=>self.on_boot_sec={ - if let Ok(duration) = parse_duration(val) { - duration - } else { - return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)); + TimerUnitAttr::OnBootSec => { + self.on_boot_sec = { + if let Ok(duration) = parse_duration(val) { + duration + } else { + return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)); + } } - }, + } - TimerUnitAttr::OnStartUpSec=>self.on_start_up_sec={ - if let Ok(duration) = parse_duration(val) { - duration - } else { - return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)); + TimerUnitAttr::OnStartUpSec => { + self.on_start_up_sec = { + if let Ok(duration) = parse_duration(val) { + duration + } else { + return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)); + } } - }, - TimerUnitAttr::OnUnitInactiveSec=>self.on_unit_inactive_sec={ - if let Ok(duration) = parse_duration(val) { - duration - } else { - return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)); + } + TimerUnitAttr::OnUnitInactiveSec => { + self.on_unit_inactive_sec = { + if let Ok(duration) = parse_duration(val) { + duration + } else { + return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)); + } } - }, - TimerUnitAttr::OnUnitActiveSec=>self.on_unit_active_sec={ - if let Ok(duration) = parse_duration(val) { - duration - } else { - return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)); + } + TimerUnitAttr::OnUnitActiveSec => { + self.on_unit_active_sec = { + if let Ok(duration) = parse_duration(val) { + duration + } else { + return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)); + } } - }, - // TimerUnitAttr::OnCalendar=>self.on_calendar={ + } + // TimerUnitAttr::OnCalendar=>self.on_calendar={ // if let Ok(calendar) = parse_calendar(val) { // calendar // } else { // return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)); // } // }, - TimerUnitAttr::Persistent=>self.persistent={ - match val{ - "true"=>true, - "false"=>false, - _=>return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)), + TimerUnitAttr::Persistent => { + self.persistent = { + match val { + "true" => true, + "false" => false, + _ => return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)), + } } - }, - TimerUnitAttr::Unit=>self.unit={ - UnitManager::get_id_with_path(val).unwrap() - }, + } + TimerUnitAttr::Unit => self.unit = UnitManager::get_id_with_path(val).unwrap(), _ => { return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)); - }, - } - Ok(()) + } + } + Ok(()) } } -#[derive(Debug,Clone, Copy)] -pub enum TimerUnitAttr {//TimerBase +#[derive(Debug, Clone, Copy)] +pub enum TimerUnitAttr { + //TimerBase // State, // Result, OnActiveSec, @@ -508,33 +532,35 @@ pub enum TimerUnitAttr {//TimerBase WakeSystem, RemainAfterElapse, } -impl Default for TimerUnitAttr{ +impl Default for TimerUnitAttr { fn default() -> Self { TimerUnitAttr::OnActiveSec } } #[derive(Debug, Clone)] -pub struct TimerVal { - attr:TimerUnitAttr,//原TimerBase - disabled:bool, - val:Duration, +pub struct TimerVal { + attr: TimerUnitAttr, //原TimerBase + disabled: bool, + val: Duration, //calendar_standard:Vec,//只针对calendar事件 - next_elapse:Option, + next_elapse: Option, } impl TimerVal { - pub fn new( attr:TimerUnitAttr, - disabled:bool, - val:Duration, - calendar_standard:Vec, - next_elapse:Option,)->TimerVal{ - TimerVal{ - attr, - disabled, - val, - //calendar_standard, - next_elapse - } + pub fn new( + attr: TimerUnitAttr, + disabled: bool, + val: Duration, + calendar_standard: Vec, + next_elapse: Option, + ) -> TimerVal { + TimerVal { + attr, + disabled, + val, + //calendar_standard, + next_elapse, } + } } From 486392644e2685695121bc8062ee32d127489b99 Mon Sep 17 00:00:00 2001 From: BrahmaMantra <140599389+BrahmaMantra@users.noreply.github.com> Date: Mon, 22 Apr 2024 19:49:51 +0800 Subject: [PATCH 03/15] Update main.rs --- src/main.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main.rs b/src/main.rs index b917741..2a594fe 100644 --- a/src/main.rs +++ b/src/main.rs @@ -15,8 +15,8 @@ use systemctl::listener::Systemctl; pub struct FileDescriptor(usize); -// const DRAGON_REACH_UNIT_DIR: &'static str = "/etc/reach/system/"; -const DRAGON_REACH_UNIT_DIR: &'static str = "/home/fz/testSystemd/"; +const DRAGON_REACH_UNIT_DIR: &'static str = "/etc/reach/system/"; +//const DRAGON_REACH_UNIT_DIR: &'static str = "/home/fz/testSystemd/"; fn main() { // 初始化 From b47f5d1b2d740165af59ac99baba9d217e9d34ce Mon Sep 17 00:00:00 2001 From: BrahmaMantra <140599389+BrahmaMantra@users.noreply.github.com> Date: Mon, 22 Apr 2024 19:50:18 +0800 Subject: [PATCH 04/15] Update main.rs --- systemctl/src/main.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/systemctl/src/main.rs b/systemctl/src/main.rs index e008d9c..9b5de0d 100644 --- a/systemctl/src/main.rs +++ b/systemctl/src/main.rs @@ -1,7 +1,7 @@ use std::{env, fs::File, io::Write}; -const REACH_PIPE_PATH: &str = "/home/fz/myetc/reach/ipc/ctl"; -//const REACH_PIPE_PATH: &str = "etc/reach/ipc/ctl"; +//const REACH_PIPE_PATH: &str = "/home/fz/myetc/reach/ipc/ctl"; +const REACH_PIPE_PATH: &str = "etc/reach/ipc/ctl"; fn main() { let mut args: Vec = env::args().collect(); From a528ed0ee1f76f6d58ddb52bd5bdb06372d0cfe4 Mon Sep 17 00:00:00 2001 From: BrahmaMantra <140599389+BrahmaMantra@users.noreply.github.com> Date: Tue, 23 Apr 2024 09:24:55 +0800 Subject: [PATCH 05/15] Update main.rs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 加入一些debug语句 --- src/main.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main.rs b/src/main.rs index b47afec..b334d18 100644 --- a/src/main.rs +++ b/src/main.rs @@ -45,6 +45,7 @@ fn main() { eprintln!("Err:{}", e.error_format()); 0 } + println!("Parse {} success!",path); }; if id != 0 { From f9be1141c92013b92d95dff27454c542ef40f9d0 Mon Sep 17 00:00:00 2001 From: BrahmaMantra <140599389+BrahmaMantra@users.noreply.github.com> Date: Tue, 23 Apr 2024 10:35:39 +0800 Subject: [PATCH 06/15] Update main.rs --- src/main.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main.rs b/src/main.rs index 09902e3..d3f31ca 100644 --- a/src/main.rs +++ b/src/main.rs @@ -45,9 +45,8 @@ fn main() { eprintln!("Err:{}", e.error_format()); 0 } - println!("Parse {} success!",path); }; - + println!("Parse {} success!",path); // if id != 0 && TimerManager::is_timer(&id){ // if let Err(e) = Executor::exec(id) { // eprintln!("Err:{}", e.error_format()); From 56ae20ccb634dbc704cc10a4e423e574813b93ed Mon Sep 17 00:00:00 2001 From: BrahmaMantra <2033552517.qq.com> Date: Tue, 23 Apr 2024 03:22:40 +0000 Subject: [PATCH 07/15] =?UTF-8?q?=E5=90=AF=E5=8A=A8pid=E4=B8=BA1=E7=9A=84?= =?UTF-8?q?=E8=BF=9B=E7=A8=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/main.rs b/src/main.rs index b917741..b9f393c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -13,6 +13,8 @@ use manager::{timer_manager::TimerManager, Manager}; use parse::UnitParser; use systemctl::listener::Systemctl; +use crate::executor::Executor; + pub struct FileDescriptor(usize); // const DRAGON_REACH_UNIT_DIR: &'static str = "/etc/reach/system/"; @@ -39,14 +41,19 @@ fn main() { //启动服务 for path in units_file_name { - let _ = match UnitParser::from_path(&path) { + let id = match UnitParser::from_path(&path) { Ok(id) => id, Err(e) => { eprintln!("Err:{}", e.error_format()); 0 } }; - + println!("Parse {} success!", path); + if id == 1 { + if let Err(e) = Executor::exec(id) { + eprintln!("Err:{}", e.error_format()); + } + } // if id != 0 && TimerManager::is_timer(&id){ // if let Err(e) = Executor::exec(id) { // eprintln!("Err:{}", e.error_format()); From 0de6c206fa0cb1040ebf77abf530d9191eafa531 Mon Sep 17 00:00:00 2001 From: BrahmaMantra <2033552517.qq.com> Date: Tue, 23 Apr 2024 07:01:39 +0000 Subject: [PATCH 08/15] =?UTF-8?q?=E5=90=AF=E5=8A=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main.rs | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/src/main.rs b/src/main.rs index b9f393c..1708b39 100644 --- a/src/main.rs +++ b/src/main.rs @@ -48,18 +48,13 @@ fn main() { 0 } }; - println!("Parse {} success!", path); - if id == 1 { - if let Err(e) = Executor::exec(id) { - eprintln!("Err:{}", e.error_format()); + if id != 0 { + if let Err(e) = Executor::exec(id) { + eprintln!("Err:{}", e.error_format()); + } } - } - // if id != 0 && TimerManager::is_timer(&id){ - // if let Err(e) = Executor::exec(id) { - // eprintln!("Err:{}", e.error_format()); - // } - // } - // } + + println!("Parse {} success!", path); } // 启动完服务后进入主循环 From 21dd5fc798f70095204cdc63353a8d611a4d053e Mon Sep 17 00:00:00 2001 From: BrahmaMantra <2033552517.qq.com> Date: Thu, 25 Apr 2024 06:52:24 +0000 Subject: [PATCH 09/15] =?UTF-8?q?=E4=BC=98=E5=8C=96=E4=BA=86check=E7=9A=84?= =?UTF-8?q?=E8=BF=87=E7=A8=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main.rs | 16 +++---- src/manager/mod.rs | 3 ++ src/manager/timer_manager/mod.rs | 71 +++++++++++++++++++++++--------- src/unit/service/mod.rs | 2 - src/unit/timer/mod.rs | 34 +++++---------- systemctl/src/main.rs | 5 ++- 6 files changed, 77 insertions(+), 54 deletions(-) diff --git a/src/main.rs b/src/main.rs index 8716404..ded9c37 100644 --- a/src/main.rs +++ b/src/main.rs @@ -13,12 +13,12 @@ use manager::{timer_manager::TimerManager, Manager}; use parse::UnitParser; use systemctl::listener::Systemctl; -use crate::executor::Executor; +use crate::{executor::Executor, time::timer::Timer}; pub struct FileDescriptor(usize); -const DRAGON_REACH_UNIT_DIR: &'static str = "/etc/reach/system/"; -//const DRAGON_REACH_UNIT_DIR: &'static str = "/home/fz/testSystemd/"; +//const DRAGON_REACH_UNIT_DIR: &'static str = "/etc/reach/system/"; +const DRAGON_REACH_UNIT_DIR: &'static str = "/home/fz/testSystemd/"; fn main() { // 初始化 @@ -48,14 +48,14 @@ fn main() { 0 } }; - if id != 0 { - if let Err(e) = Executor::exec(id) { - eprintln!("Err:{}", e.error_format()); - } + if id != 0 && TimerManager::is_timer(&id){ + if let Err(e) = Executor::exec(id) { + eprintln!("Err:{}", e.error_format()); } - + } println!("Parse {} success!", path); } + // 启动完服务后进入主循环 loop { diff --git a/src/manager/mod.rs b/src/manager/mod.rs index b36d04e..8eb4069 100644 --- a/src/manager/mod.rs +++ b/src/manager/mod.rs @@ -54,6 +54,9 @@ impl Manager { .unwrap() .exit(); //交付给相应类型的Unit类型去执行退出后的逻辑 + TimerManager::update_next_trigger(tmp.0,false); //更新所有归属于此unit的计时器 + + // 交付处理子进程退出逻辑 let unit = UnitManager::get_unit_with_id(&tmp.0).unwrap(); unit.lock().unwrap().after_exit(tmp.1); diff --git a/src/manager/timer_manager/mod.rs b/src/manager/timer_manager/mod.rs index 735cbe2..bd65335 100644 --- a/src/manager/timer_manager/mod.rs +++ b/src/manager/timer_manager/mod.rs @@ -15,15 +15,17 @@ lazy_static! { // 管理全局计时器任务 static ref TIMER_TASK_MANAGER:RwLock = RwLock::new(TimerManager { inner_timers: Vec::new(), - inner_timers_map: RwLock::new(HashMap::new()), - id_table:RwLock::new(Vec::new())//.0是TimerUnit的id,.1是父Unit的id + timer_unit_map: RwLock::new(HashMap::new()), + + id_table:RwLock::new(Vec::new()) }); } pub struct TimerManager { inner_timers: Vec, - inner_timers_map: RwLock>>>, - id_table: RwLock>, + timer_unit_map: RwLock>>>, //id->TimerUnit + id_table: RwLock>, //.0是TimerUnit的id,.1是父Unit的id + //timer_event_table: } impl<'a> IntoIterator for &'a mut TimerManager { @@ -62,7 +64,7 @@ impl TimerManager { .push((unit_id, unit_.get_parent_unit())); drop(unit_); timemanager - .inner_timers_map + .timer_unit_map .write() .unwrap() .insert(unit_id, unit); //加入到inner_timers_map @@ -80,17 +82,18 @@ impl TimerManager { let reader = TIMER_TASK_MANAGER.read().unwrap(); let mut inactive_unit: Vec = Vec::new(); - for (_, timer_unit) in reader.inner_timers_map.read().unwrap().iter() { + for (_, timer_unit) in reader.timer_unit_map.read().unwrap().iter() { let mut timer_unit = timer_unit.lock().unwrap(); if timer_unit.enter_inactive() { inactive_unit.push(timer_unit.unit_id()); continue; } if timer_unit.check() { - let _ = timer_unit.run(); //运行作出相应操作 + let _ = timer_unit._run(); //运行作出相应操作 let id = timer_unit.get_parent_unit(); + //timer_unit.mut_timer_part().update_next_trigger(); drop(timer_unit); - TimerManager::adjust_timevalue(&id, true); + TimerManager::update_next_trigger(id, true); } } @@ -125,31 +128,32 @@ impl TimerManager { false } /// unit_id:父unit的id flag:1为exec 0为exit - pub fn adjust_timevalue(unit_id: &usize, flag: bool /*1为启动0为退出 */) { - let manager: std::sync::RwLockReadGuard<'_, TimerManager> = - TIMER_TASK_MANAGER.read().unwrap(); + fn adjust_timevalue(unit_id: &usize, flag: bool /*1为启动0为退出 */) -> Vec { + let mut result = Vec::new(); + let manager = TIMER_TASK_MANAGER.read().unwrap(); for (self_id, parent_id) in manager.id_table.read().unwrap().iter() { if unit_id == parent_id { - manager - .inner_timers_map + let timer_unit_map = manager + .timer_unit_map .read() - .unwrap() - .get(self_id) + .unwrap(); + let mut timer_unit=timer_unit_map.get(self_id) .unwrap() .lock() - .unwrap() - .change_stage(flag) + .unwrap(); + timer_unit.change_stage(flag); + result.push(*self_id); } } - //get(unit_id).unwrap().lock().unwrap().change_stage(flag) + result } /// 从Timer表中删除该Unit pub fn remove_timer_unit(unit_id: usize) { let manager = TIMER_TASK_MANAGER.read().unwrap(); - manager.inner_timers_map.write().unwrap().remove(&unit_id); + manager.timer_unit_map.write().unwrap().remove(&unit_id); let index: usize = 0; let mut id_table = manager.id_table.write().unwrap(); for (self_id, _) in id_table.iter() { @@ -160,4 +164,33 @@ impl TimerManager { } } } + + /// 获得该id下的所有计时器 + pub fn get_timer(parent_id: usize) -> Vec { + let mut result = Vec::new(); + let timer_manager = TIMER_TASK_MANAGER.read().unwrap(); + let reader = timer_manager.id_table.read().unwrap(); + for (timer_id, id) in reader.iter() { + if *id == parent_id { + result.push(*timer_id); + } + } + result + } + ///此时传入的是parent_id + pub fn update_next_trigger(unit_id: usize, flag: bool) { + let timer_vec = Self::adjust_timevalue(&unit_id, flag); + + let timer_manager = TIMER_TASK_MANAGER.read().unwrap(); + let timer_unit_map = timer_manager.timer_unit_map.read().unwrap(); + timer_vec.iter().for_each(|id| { + timer_unit_map + .get(id) + .unwrap() + .lock() + .unwrap() + .mut_timer_part() + .update_next_trigger(); + }); + } } diff --git a/src/unit/service/mod.rs b/src/unit/service/mod.rs index 1b5fe17..3bfc90c 100644 --- a/src/unit/service/mod.rs +++ b/src/unit/service/mod.rs @@ -216,7 +216,6 @@ impl Unit for ServiceUnit { fn exit(&mut self) { ServiceExecutor::exit(self); //改变计时器内部状态 - TimerManager::adjust_timevalue(&self.unit_id(), false); } fn restart(&mut self) -> Result<(), RuntimeError> { @@ -239,7 +238,6 @@ impl ServiceUnit { fn exec(&mut self) -> Result<(), RuntimeError> { let _ = ServiceExecutor::exec(self); - //TimerManager::adjust_timevalue(&self.unit_id(), true); Ok(()) } } diff --git a/src/unit/timer/mod.rs b/src/unit/timer/mod.rs index dc947f4..8c8081e 100644 --- a/src/unit/timer/mod.rs +++ b/src/unit/timer/mod.rs @@ -139,14 +139,11 @@ impl Unit for TimerUnit { fn run(&mut self) -> Result<(), RuntimeError> { //TODO!! 错误检查 - let part = &mut self.timer_part; - part.now_time = Instant::now(); - //println!("Prepared to run"); - //检查Timer管理的unit是否存在 - if UnitManager::contains_id(&part.unit) { + if self.check() && UnitManager::contains_id(&self.timer_part.unit) { let _ = self._run(); //运行作出相应操作 - return Ok(()); - } else { + let id = self.get_parent_unit(); + TimerManager::update_next_trigger(id, true); + }else if !UnitManager::contains_id(&self.timer_part.unit) { println!("task error,unit does not exist") }; return Ok(()); @@ -158,7 +155,7 @@ impl Unit for TimerUnit { } } impl TimerUnit { - fn _run(&mut self) -> Result<(), RuntimeError> { + pub fn _run(&mut self) -> Result<(), RuntimeError> { //到这里触发计时器对应的服务 let part = &mut self.timer_part; if part.value.is_empty() { //触发次数已尽 @@ -196,15 +193,6 @@ impl TimerUnit { return false; } part.now_time = Instant::now(); - //检查下一个触发的TimerVal是不是disable - // println!("now time:{},next elapse time:{:?}",part.now_time.elapsed().as_micros(),part.next_elapse_monotonic_or_boottime); - if part.update_next_trigger() { - self.unit_base.state = UnitState::Active; - } else if part.value.len() == 0 { - self.unit_base.state = UnitState::Inactive; //计时器里不再有值 - } else { - self.unit_base.state = UnitState::Deactivating; - } //计时器不可用 if self.unit_base.state == UnitState::Deactivating || self.unit_base.state == UnitState::Inactive @@ -220,7 +208,7 @@ impl TimerUnit { //检查Timer管理的unit是否存在 if let Some(_) = UnitManager::get_unit_with_id(&part.unit) { - // let _ = unit.lock().unwrap().run();//运行作出相应操作 + // let _ = unit.lock().unwrap().run();//运行作出相应操作,check不负责此操作 return true; } println!("task error,unit does not exist"); @@ -383,7 +371,7 @@ impl Default for TimerPart { impl TimerPart { /// 更新下一次的触发时间 - pub fn update_next_trigger(&mut self) -> bool { + pub fn update_next_trigger(&mut self) { self.now_time = Instant::now(); //let unit_is_running=UnitManager::is_running_unit(&self.unit); @@ -403,7 +391,7 @@ impl TimerPart { self.next_elapse_monotonic_or_boottime = val.next_elapse.unwrap(); val.next_elapse = Some(self.now_time + val.val); // println!("Update the time!"); - return true; + return ; } } @@ -411,7 +399,7 @@ impl TimerPart { if val.next_elapse.unwrap() < self.now_time { self.next_elapse_monotonic_or_boottime = val.next_elapse.unwrap(); self.value.remove(index); //在这一步准备把iter从value里弹出去 - return true; + return ; } } //TimerUnitAttr::OnStartUpSec => todo!(), @@ -430,13 +418,13 @@ impl TimerPart { }); if self.value.is_empty() || self.value[0].next_elapse == None { //计时器里面已经没有值了 - return false; + return; } // 从已排序的Vec中获取最早的定时器时间 self.next_elapse_monotonic_or_boottime = self.value[0].next_elapse.unwrap(); - return true; + return ; } pub fn set_attr(&mut self, attr: &TimerUnitAttr, val: &str) -> Result<(), ParseError> { match attr { diff --git a/systemctl/src/main.rs b/systemctl/src/main.rs index 9b5de0d..506f8b1 100644 --- a/systemctl/src/main.rs +++ b/systemctl/src/main.rs @@ -1,7 +1,7 @@ use std::{env, fs::File, io::Write}; -//const REACH_PIPE_PATH: &str = "/home/fz/myetc/reach/ipc/ctl"; -const REACH_PIPE_PATH: &str = "etc/reach/ipc/ctl"; +const REACH_PIPE_PATH: &str = "/home/fz/myetc/reach/ipc/ctl"; +//const REACH_PIPE_PATH: &str = "etc/reach/ipc/ctl"; fn main() { let mut args: Vec = env::args().collect(); @@ -22,5 +22,6 @@ fn main() { let mut file = File::open(REACH_PIPE_PATH).unwrap(); if let Err(err) = file.write_all(msg.as_bytes()) { eprintln!("write error {}", err); + eprintln!("write error {:?}", err); } } From bc32526839696aa3fce81c9d8314e6769cc2217f Mon Sep 17 00:00:00 2001 From: BrahmaMantra <2033552517.qq.com> Date: Fri, 26 Apr 2024 09:46:40 +0000 Subject: [PATCH 10/15] =?UTF-8?q?=E5=88=9D=E6=AD=A5=E5=AE=9E=E7=8E=B0?= =?UTF-8?q?=E4=BA=86timer=5Funit=EF=BC=8C=E6=AD=A4=E6=97=B6=E4=BC=9A?= =?UTF-8?q?=E5=9C=A8parse=E7=9A=84=E6=97=B6=E5=80=99=E5=90=AF=E7=94=A8?= =?UTF-8?q?=E6=89=80=E6=9C=89=E8=AE=A1=E6=97=B6=E5=99=A8=EF=BC=8C=E5=90=8E?= =?UTF-8?q?=E7=BB=AD=E5=86=8D=E5=AE=9E=E7=8E=B0=E9=80=9A=E8=BF=87systemctl?= =?UTF-8?q?=E7=9A=84=E6=96=B9=E6=B3=95=E5=90=AF=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main.rs | 2 +- src/manager/timer_manager/mod.rs | 36 +++----- src/unit/service/mod.rs | 1 - src/unit/timer/mod.rs | 154 +++++++++++++++++++------------ 4 files changed, 112 insertions(+), 81 deletions(-) diff --git a/src/main.rs b/src/main.rs index ded9c37..ee488e5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -13,7 +13,7 @@ use manager::{timer_manager::TimerManager, Manager}; use parse::UnitParser; use systemctl::listener::Systemctl; -use crate::{executor::Executor, time::timer::Timer}; +use crate::executor::Executor; pub struct FileDescriptor(usize); diff --git a/src/manager/timer_manager/mod.rs b/src/manager/timer_manager/mod.rs index bd65335..c233704 100644 --- a/src/manager/timer_manager/mod.rs +++ b/src/manager/timer_manager/mod.rs @@ -9,7 +9,7 @@ use crate::{ use hashbrown::HashMap; use lazy_static::lazy_static; -use super::UnitManager; + lazy_static! { // 管理全局计时器任务 @@ -25,7 +25,6 @@ pub struct TimerManager { inner_timers: Vec, timer_unit_map: RwLock>>>, //id->TimerUnit id_table: RwLock>, //.0是TimerUnit的id,.1是父Unit的id - //timer_event_table: } impl<'a> IntoIterator for &'a mut TimerManager { @@ -80,30 +79,28 @@ impl TimerManager { drop(writer); //此处触发Timer_unit,不移除 let reader = TIMER_TASK_MANAGER.read().unwrap(); - + let timer_unit_map = reader.timer_unit_map.read().unwrap(); let mut inactive_unit: Vec = Vec::new(); - for (_, timer_unit) in reader.timer_unit_map.read().unwrap().iter() { + for (_, timer_unit) in timer_unit_map.iter() { let mut timer_unit = timer_unit.lock().unwrap(); if timer_unit.enter_inactive() { inactive_unit.push(timer_unit.unit_id()); continue; } if timer_unit.check() { + //println!("unit id : {} , parent id : {} ",timer_unit.unit_id(),timer_unit.get_parent_unit()); let _ = timer_unit._run(); //运行作出相应操作 let id = timer_unit.get_parent_unit(); - //timer_unit.mut_timer_part().update_next_trigger(); drop(timer_unit); - TimerManager::update_next_trigger(id, true); + TimerManager::update_next_trigger(id, true); //更新触发时间 } } - for iter in inactive_unit { + for id in inactive_unit {//处理Inactive需要退出的计时器 //println!("Prepared to exit..."); - UnitManager::get_unit_with_id(&iter) - .unwrap() - .lock() - .unwrap() - .exit(); + timer_unit_map.get(&id).unwrap().lock().unwrap().exit(); + + TimerManager::remove_timer_unit(id); } } @@ -131,17 +128,10 @@ impl TimerManager { fn adjust_timevalue(unit_id: &usize, flag: bool /*1为启动0为退出 */) -> Vec { let mut result = Vec::new(); let manager = TIMER_TASK_MANAGER.read().unwrap(); - for (self_id, parent_id) in manager.id_table.read().unwrap().iter() { if unit_id == parent_id { - let timer_unit_map = manager - .timer_unit_map - .read() - .unwrap(); - let mut timer_unit=timer_unit_map.get(self_id) - .unwrap() - .lock() - .unwrap(); + let timer_unit_map = manager.timer_unit_map.read().unwrap(); + let mut timer_unit = timer_unit_map.get(self_id).unwrap().lock().unwrap(); timer_unit.change_stage(flag); result.push(*self_id); } @@ -154,14 +144,16 @@ impl TimerManager { let manager = TIMER_TASK_MANAGER.read().unwrap(); manager.timer_unit_map.write().unwrap().remove(&unit_id); - let index: usize = 0; + let mut index: usize = 0; let mut id_table = manager.id_table.write().unwrap(); for (self_id, _) in id_table.iter() { //因为id是递增的,后续可优化为二分查找 if unit_id == *self_id { id_table.remove(index); + println!("remove id:{}", unit_id); return; } + index = index + 1 } } diff --git a/src/unit/service/mod.rs b/src/unit/service/mod.rs index 3bfc90c..bf51d46 100644 --- a/src/unit/service/mod.rs +++ b/src/unit/service/mod.rs @@ -4,7 +4,6 @@ use crate::error::{parse_error::ParseError, parse_error::ParseErrorType}; use crate::executor::service_executor::ServiceExecutor; use crate::executor::ExitStatus; -use crate::manager::timer_manager::TimerManager; use crate::parse::parse_service::ServiceParser; use crate::parse::parse_util::UnitParseUtil; use crate::parse::{Segment, SERVICE_UNIT_ATTR_TABLE}; diff --git a/src/unit/timer/mod.rs b/src/unit/timer/mod.rs index 8c8081e..cb80761 100644 --- a/src/unit/timer/mod.rs +++ b/src/unit/timer/mod.rs @@ -31,24 +31,33 @@ impl Default for TimerUnit { impl Unit for TimerUnit { fn init(&mut self) { + // 初始化计时器单元 + // 将单元状态设置为激活中 self.unit_base.state = UnitState::Activating; + // 更新计时器部分的数据 let part = &mut self.timer_part; part.remain_after_elapse = true; + // 设置初始触发时间 let part = &mut self.timer_part; let now = Instant::now(); part.last_trigger = now; part.now_time = now; - part.value.push(TimerVal::new( - TimerUnitAttr::OnActiveSec, - part.on_active_sec == Default::default(), - part.on_active_sec, - Default::default(), - Some(now + part.on_active_sec), - )); - //实现OnActiveSec的具体逻辑 + // 如果设置了激活时的秒数,则添加一个计时器值 + if part.on_active_sec != Default::default() { + part.value.push(TimerVal::new( + TimerUnitAttr::OnActiveSec, + false, + part.on_active_sec, + Default::default(), + Some(now + part.on_active_sec), + )); + } + + // 实现OnActiveSec的具体逻辑 + // 检查单元是否正在运行 let unit_is_running = UnitManager::is_running_unit(&part.unit); if part.on_unit_active_sec != Default::default() { @@ -64,7 +73,9 @@ impl Unit for TimerUnit { Default::default(), next_trigger, )); - } //实现OnUnitActiveSec的具体逻辑 + } + + // 实现OnUnitActiveSec的具体逻辑 if part.on_unit_inactive_sec != Default::default() { part.value.push(TimerVal::new( @@ -72,19 +83,24 @@ impl Unit for TimerUnit { true, part.on_unit_inactive_sec, Default::default(), - None, /*无论刚开始服务有没有在运行,逻辑上这里都不会有值 */ + None, /*无论服务是否在运行,这里都不会有值 */ )); - } //实现OnUnitInactiveSec的具体逻辑 + } + + // 实现OnUnitInactiveSec的具体逻辑 part.update_next_trigger(); self._init(); + // 将单元状态设置为激活 self.unit_base.state = UnitState::Active; } fn set_unit_name(&mut self, name: String) { + // 设置单元的名称 self.unit_base_mut().unit_name = name; } fn restart(&mut self) -> Result<(), RuntimeError> { + // 重启单元 self.exit(); self.init(); Ok(()) @@ -94,19 +110,24 @@ impl Unit for TimerUnit { where Self: Sized, { + // 从给定的路径解析并创建计时器单元 TimerParser::parse(path) } fn as_any(&self) -> &dyn std::any::Any { + // 将计时器单元转换为任何类型,用于多态调用 self } fn as_mut_any(&mut self) -> &mut dyn std::any::Any { + // 将计时器单元转换为任何可变类型,用于多态调用 self } fn set_attr(&mut self, segment: Segment, attr: &str, val: &str) -> Result<(), ParseError> { + // 设置计时器单元的属性 if segment != Segment::Timer { + // 如果段不是计时器段,则返回错误 return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)); } let attr_type = TIMER_UNIT_ATTR_TABLE.get(attr).ok_or(ParseError::new( @@ -118,48 +139,57 @@ impl Unit for TimerUnit { } fn set_unit_base(&mut self, unit_base: BaseUnit) { + // 设置单元的基础信息 self.unit_base = unit_base; } fn unit_type(&self) -> super::UnitType { + // 返回单元的类型 self.unit_base.unit_type } fn unit_base(&self) -> &BaseUnit { + // 返回单元的基础信息 &self.unit_base } fn unit_base_mut(&mut self) -> &mut BaseUnit { + // 返回单元的基础信息的可变引用 &mut self.unit_base } fn unit_id(&self) -> usize { + // 返回单元的ID self.unit_base.unit_id } fn run(&mut self) -> Result<(), RuntimeError> { - //TODO!! 错误检查 - if self.check() && UnitManager::contains_id(&self.timer_part.unit) { - let _ = self._run(); //运行作出相应操作 + //真正的run在_run中 + if self.check() && UnitManager::contains_id(&self.timer_part.unit) { + // 如果单元检查通过并且单元管理器包含该单元,则运行 + let _ = self._run(); // 运行单元 let id = self.get_parent_unit(); + // 更新下一个触发器 TimerManager::update_next_trigger(id, true); - }else if !UnitManager::contains_id(&self.timer_part.unit) { + } else if !UnitManager::contains_id(&self.timer_part.unit) { + // 如果单元管理器不包含该单元,则打印错误信息 println!("task error,unit does not exist") }; - return Ok(()); + Ok(()) } fn exit(&mut self) { UnitManager::try_kill_running(self.unit_id()); - TimerManager::remove_timer_unit(self.unit_id()); } } + impl TimerUnit { - pub fn _run(&mut self) -> Result<(), RuntimeError> { //到这里触发计时器对应的服务 + pub fn _run(&mut self) -> Result<(), RuntimeError> { + //到这里触发计时器对应的服务 let part = &mut self.timer_part; if part.value.is_empty() { //触发次数已尽 - self.unit_base.state = UnitState::Deactivating; + self.unit_base.state = UnitState::Inactive; } else if matches!( part.value[0].attr, TimerUnitAttr::OnActiveSec | TimerUnitAttr::OnBootSec | TimerUnitAttr::OnStartUpSec @@ -175,6 +205,7 @@ impl TimerUnit { //执行相应的unit单元 if let Ok(_) = Executor::exec(part.unit) { self.unit_base.state = UnitState::Active; + part.last_trigger = Instant::now(); return Ok(()); } else { self.unit_base.state = UnitState::Failed; @@ -188,31 +219,44 @@ impl TimerUnit { pub fn check(&mut self) -> bool { let part = &mut self.timer_part; - if UnitManager::is_running_unit(&part.unit) { - //在运行就不管了 + //计时器不可用 + if part.value.len() == 0 { + //不可能再触发 + self.unit_base.state = UnitState::Inactive; + } + if self.unit_base.state == UnitState::Inactive + //可能是手动停止 + { return false; } - part.now_time = Instant::now(); - //计时器不可用 - if self.unit_base.state == UnitState::Deactivating - || self.unit_base.state == UnitState::Inactive + if UnitManager::is_running_unit(&part.unit) //在运行就不管了 + || part.next_elapse_monotonic_or_boottime==None + //下次触发时间无限大 { return false; } + part.now_time = Instant::now(); //到时间执行Timer所管理的Unit - if part.last_trigger + (part.last_trigger.elapsed()) - >= part.next_elapse_monotonic_or_boottime - { - // 未进行错误处理 - + // println!( + // "Now time::{:?},next_elapse_monotonic_or_boottime::{:?}_", + // part.now_time, + // part.next_elapse_monotonic_or_boottime.unwrap() + // ); + + //!!!此处判断在DragonOs有大问题!时间跨度很大,但在linux上正常运行 + if part.now_time >= part.next_elapse_monotonic_or_boottime.unwrap() { //检查Timer管理的unit是否存在 if let Some(_) = UnitManager::get_unit_with_id(&part.unit) { - // let _ = unit.lock().unwrap().run();//运行作出相应操作,check不负责此操作 + // let _ = unit.lock().unwrap().run();//运行时作出相应操作,check不负责此操作 + // println!( + // "Now time::{:?},next_elapse_monotonic_or_boottime::{:?}_", + // part.now_time, + // part.next_elapse_monotonic_or_boottime.unwrap() + // ); return true; } println!("task error,unit does not exist"); - return false; } return false; } @@ -230,41 +274,37 @@ impl TimerUnit { } pub fn timer_init(&mut self) { let part = &mut self.timer_part; - part.next_elapse_monotonic_or_boottime = Instant::now(); + part.next_elapse_monotonic_or_boottime = None; part.next_elapse_realtime = Instant::now(); part.now_time = Instant::now(); part.remain_after_elapse = true; } - pub fn exec(&mut self) -> Result<(), RuntimeError> { - todo!() - //push_timer 1.检查时间是否正确 2.更新时间 3.做出操作 - } - pub fn get_parent_unit(&mut self) -> usize { self.timer_part().unit } pub fn enter_inactive(&mut self) -> bool { + //判断计时器是否失效 if self.unit_base.state == UnitState::Inactive { return true; } false } - ///在unit exec或exit的时候改变TimerValue中OnUnitInactiveSec和OnUnitActiveSec的状态 + ///在unit run或exit的时候改变TimerValue中OnUnitInactiveSec和OnUnitActiveSec的状态 pub fn change_stage(&mut self, flag: bool /*1为启动0为退出 */) { for val in &mut self.timer_part.value { match val.attr { TimerUnitAttr::OnUnitActiveSec => { + val.disabled = false; if flag { - val.disabled = false; val.next_elapse = Some(Instant::now() + val.val); } } TimerUnitAttr::OnUnitInactiveSec => { + val.disabled = false; if !flag { - val.disabled = false; val.next_elapse = Some(Instant::now() + val.val); } } @@ -279,7 +319,7 @@ unsafe impl Send for TimerUnit {} #[allow(dead_code)] #[derive(Debug, Clone)] pub struct TimerPart { - //TODO! 未实现时间事件源的相关功能,目前还是循环确认Timer的情况 + //TODO! 因此时DragonReach未实现时间事件源的相关功能,目前还是循环确认Timer的情况 ///@brief 存储触发计时器的时间集合 value: Vec, @@ -332,7 +372,7 @@ pub struct TimerPart { next_elapse_realtime: Instant, ///@brief 表示计时器下次单调时间或引导时间触发的时间戳 - next_elapse_monotonic_or_boottime: Instant, + next_elapse_monotonic_or_boottime: Option, //None表示无限大 ///@brief 用于存储计时器最后一次触发的时间戳。 last_trigger: Instant, @@ -362,7 +402,7 @@ impl Default for TimerPart { remain_after_elapse: true, next_elapse_realtime: Instant::now(), - next_elapse_monotonic_or_boottime: Instant::now(), + next_elapse_monotonic_or_boottime: None, last_trigger: Instant::now(), now_time: Instant::now(), } @@ -382,24 +422,23 @@ impl TimerPart { match val.attr { TimerUnitAttr::OnUnitInactiveSec | TimerUnitAttr::OnUnitActiveSec => { //更新OnUnitInactiveSec和OnUnitActiveSec类型的值 - if val.disabled { + if val.disabled || val.next_elapse == None { + //None表示此时无法确认下次触发时间 index = index + 1; continue; - } else if val.next_elapse == None { - val.next_elapse = Some(self.now_time + val.val); } else if val.next_elapse.unwrap() < self.now_time { - self.next_elapse_monotonic_or_boottime = val.next_elapse.unwrap(); - val.next_elapse = Some(self.now_time + val.val); + self.next_elapse_monotonic_or_boottime = val.next_elapse; + val.next_elapse = None; // println!("Update the time!"); - return ; + return; } } TimerUnitAttr::OnActiveSec | TimerUnitAttr::OnBootSec => { if val.next_elapse.unwrap() < self.now_time { - self.next_elapse_monotonic_or_boottime = val.next_elapse.unwrap(); - self.value.remove(index); //在这一步准备把iter从value里弹出去 - return ; + self.next_elapse_monotonic_or_boottime = val.next_elapse; + self.value.remove(index); //在这一步准备把index从value里弹出去 + return; } } //TimerUnitAttr::OnStartUpSec => todo!(), @@ -417,15 +456,16 @@ impl TimerPart { (Some(a), Some(b)) => a.cmp(&b), }); if self.value.is_empty() || self.value[0].next_elapse == None { - //计时器里面已经没有值了 + //无法得到下次触发的具体时间 return; } // 从已排序的Vec中获取最早的定时器时间 - self.next_elapse_monotonic_or_boottime = self.value[0].next_elapse.unwrap(); + self.next_elapse_monotonic_or_boottime = self.value[0].next_elapse; - return ; + return; } + /// &str->attr的parse pub fn set_attr(&mut self, attr: &TimerUnitAttr, val: &str) -> Result<(), ParseError> { match attr { TimerUnitAttr::OnActiveSec => { @@ -528,7 +568,7 @@ impl Default for TimerUnitAttr { #[derive(Debug, Clone)] pub struct TimerVal { - attr: TimerUnitAttr, //原TimerBase + attr: TimerUnitAttr, disabled: bool, val: Duration, //calendar_standard:Vec,//只针对calendar事件 From 15250271fa8d21f867bc5633639b1c9cb39f1419 Mon Sep 17 00:00:00 2001 From: BrahmaMantra <2033552517.qq.com> Date: Fri, 26 Apr 2024 09:49:01 +0000 Subject: [PATCH 11/15] =?UTF-8?q?=E7=BA=A0=E6=AD=A3=E5=9B=9EDragonOs?= =?UTF-8?q?=E7=9A=84=E8=B7=AF=E5=BE=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main.rs | 4 ++-- src/systemctl/mod.rs | 4 ++-- systemctl/src/main.rs | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main.rs b/src/main.rs index ee488e5..7a08e56 100644 --- a/src/main.rs +++ b/src/main.rs @@ -17,8 +17,8 @@ use crate::executor::Executor; pub struct FileDescriptor(usize); -//const DRAGON_REACH_UNIT_DIR: &'static str = "/etc/reach/system/"; -const DRAGON_REACH_UNIT_DIR: &'static str = "/home/fz/testSystemd/"; +const DRAGON_REACH_UNIT_DIR: &'static str = "/etc/reach/system/"; +//const DRAGON_REACH_UNIT_DIR: &'static str = "/home/fz/testSystemd/"; fn main() { // 初始化 diff --git a/src/systemctl/mod.rs b/src/systemctl/mod.rs index d1bb335..df04b2f 100644 --- a/src/systemctl/mod.rs +++ b/src/systemctl/mod.rs @@ -3,8 +3,8 @@ use std::ffi::CString; pub mod ctl_parser; pub mod listener; -//pub const DRAGON_REACH_CTL_PIPE: &'static str = "/etc/reach/ipc/ctl"; -pub const DRAGON_REACH_CTL_PIPE: &'static str = "/home/fz/myetc/reach/ipc/ctl"; +pub const DRAGON_REACH_CTL_PIPE: &'static str = "/etc/reach/ipc/ctl"; +//pub const DRAGON_REACH_CTL_PIPE: &'static str = "/home/fz/myetc/reach/ipc/ctl"; pub fn ctl_path() -> CString { CString::new(DRAGON_REACH_CTL_PIPE).expect("Failed to create pipe CString") diff --git a/systemctl/src/main.rs b/systemctl/src/main.rs index 506f8b1..f43c6ab 100644 --- a/systemctl/src/main.rs +++ b/systemctl/src/main.rs @@ -1,7 +1,7 @@ use std::{env, fs::File, io::Write}; -const REACH_PIPE_PATH: &str = "/home/fz/myetc/reach/ipc/ctl"; -//const REACH_PIPE_PATH: &str = "etc/reach/ipc/ctl"; +//const REACH_PIPE_PATH: &str = "/home/fz/myetc/reach/ipc/ctl"; +const REACH_PIPE_PATH: &str = "etc/reach/ipc/ctl"; fn main() { let mut args: Vec = env::args().collect(); From 61c15c93fb5831123587fc76c7ed1eb46a6128b7 Mon Sep 17 00:00:00 2001 From: BrahmaMantra <2033552517.qq.com> Date: Sun, 28 Apr 2024 09:56:06 +0000 Subject: [PATCH 12/15] "fmt" --- src/main.rs | 3 +-- src/manager/mod.rs | 5 ++--- src/manager/timer_manager/mod.rs | 5 ++--- src/parse/mod.rs | 11 ++++++----- src/time/mod.rs | 2 +- src/unit/timer/mod.rs | 4 ++-- 6 files changed, 14 insertions(+), 16 deletions(-) diff --git a/src/main.rs b/src/main.rs index 7a08e56..d9873cf 100644 --- a/src/main.rs +++ b/src/main.rs @@ -48,14 +48,13 @@ fn main() { 0 } }; - if id != 0 && TimerManager::is_timer(&id){ + if id != 0 && TimerManager::is_timer(&id) { if let Err(e) = Executor::exec(id) { eprintln!("Err:{}", e.error_format()); } } println!("Parse {} success!", path); } - // 启动完服务后进入主循环 loop { diff --git a/src/manager/mod.rs b/src/manager/mod.rs index 8eb4069..a1f11db 100644 --- a/src/manager/mod.rs +++ b/src/manager/mod.rs @@ -54,10 +54,9 @@ impl Manager { .unwrap() .exit(); //交付给相应类型的Unit类型去执行退出后的逻辑 - TimerManager::update_next_trigger(tmp.0,false); //更新所有归属于此unit的计时器 - + TimerManager::update_next_trigger(tmp.0, false); //更新所有归属于此unit的计时器 - // 交付处理子进程退出逻辑 + // 交付处理子进程退出逻辑 let unit = UnitManager::get_unit_with_id(&tmp.0).unwrap(); unit.lock().unwrap().after_exit(tmp.1); } diff --git a/src/manager/timer_manager/mod.rs b/src/manager/timer_manager/mod.rs index c233704..db78e76 100644 --- a/src/manager/timer_manager/mod.rs +++ b/src/manager/timer_manager/mod.rs @@ -9,8 +9,6 @@ use crate::{ use hashbrown::HashMap; use lazy_static::lazy_static; - - lazy_static! { // 管理全局计时器任务 static ref TIMER_TASK_MANAGER:RwLock = RwLock::new(TimerManager { @@ -96,7 +94,8 @@ impl TimerManager { } } - for id in inactive_unit {//处理Inactive需要退出的计时器 + for id in inactive_unit { + //处理Inactive需要退出的计时器 //println!("Prepared to exit..."); timer_unit_map.get(&id).unwrap().lock().unwrap().exit(); diff --git a/src/parse/mod.rs b/src/parse/mod.rs index 4f1d9c5..b79bb38 100644 --- a/src/parse/mod.rs +++ b/src/parse/mod.rs @@ -23,8 +23,8 @@ use self::parse_util::UnitParseUtil; pub mod graph; pub mod parse_service; pub mod parse_target; -pub mod parse_util; pub mod parse_timer; +pub mod parse_util; //对应Unit段类型 #[derive(PartialEq, Clone, Copy)] @@ -223,7 +223,7 @@ impl UnitParser { match unit_type { UnitType::Service => ServiceParser::parse(path), UnitType::Target => TargetParser::parse(path), - UnitType::Timer=>TimerParser::parse(path),//新实现的timer_unit + UnitType::Timer => TimerParser::parse(path), //新实现的timer_unit _ => Err(ParseError::new(ParseErrorType::EFILE, path.to_string(), 0)), } } @@ -325,7 +325,8 @@ impl UnitParser { } }; //首先匹配所有unit文件都有的unit段和install段 - if BASE_UNIT_ATTR_TABLE.get(attr_str).is_some() {//匹配Unit字段 + if BASE_UNIT_ATTR_TABLE.get(attr_str).is_some() { + //匹配Unit字段 if segment != Segment::Unit { return Err(ParseError::new( ParseErrorType::EINVAL, @@ -341,8 +342,8 @@ impl UnitParser { e.set_linenum(i + 1); return Err(e); } - } - else if INSTALL_UNIT_ATTR_TABLE.get(attr_str).is_some() {//匹配Install字段 + } else if INSTALL_UNIT_ATTR_TABLE.get(attr_str).is_some() { + //匹配Install字段 if segment != Segment::Install { return Err(ParseError::new( ParseErrorType::EINVAL, diff --git a/src/time/mod.rs b/src/time/mod.rs index ec2e9cf..3de5d7d 100644 --- a/src/time/mod.rs +++ b/src/time/mod.rs @@ -1,2 +1,2 @@ -pub mod timer; pub mod calandar; +pub mod timer; diff --git a/src/unit/timer/mod.rs b/src/unit/timer/mod.rs index cb80761..04595e7 100644 --- a/src/unit/timer/mod.rs +++ b/src/unit/timer/mod.rs @@ -244,7 +244,7 @@ impl TimerUnit { // part.next_elapse_monotonic_or_boottime.unwrap() // ); - //!!!此处判断在DragonOs有大问题!时间跨度很大,但在linux上正常运行 + //!!!此处判断在DragonOs有大问题!时间跨度很大,但在linux上正常运行 if part.now_time >= part.next_elapse_monotonic_or_boottime.unwrap() { //检查Timer管理的unit是否存在 if let Some(_) = UnitManager::get_unit_with_id(&part.unit) { @@ -580,7 +580,7 @@ impl TimerVal { attr: TimerUnitAttr, disabled: bool, val: Duration, - calendar_standard: Vec, + _calendar_standard: Vec, //等待后续迭代 next_elapse: Option, ) -> TimerVal { TimerVal { From 2898379aba975653ed305f5a82d059a8c77d0ebc Mon Sep 17 00:00:00 2001 From: BrahmaMantra <2033552517.qq.com> Date: Mon, 29 Apr 2024 03:13:09 +0000 Subject: [PATCH 13/15] check and print elpase time every 5s --- parse_test/test_timer_unit.service | 7 +++++++ parse_test/test_timer_unit.timer | 7 +++++++ src/manager/timer_manager/mod.rs | 10 ++++++---- src/unit/timer/mod.rs | 11 ++++++----- 4 files changed, 26 insertions(+), 9 deletions(-) create mode 100644 parse_test/test_timer_unit.service create mode 100644 parse_test/test_timer_unit.timer diff --git a/parse_test/test_timer_unit.service b/parse_test/test_timer_unit.service new file mode 100644 index 0000000..7bc885f --- /dev/null +++ b/parse_test/test_timer_unit.service @@ -0,0 +1,7 @@ +[Unit] +Description=a test for timer_unit + +[Service] +Type=simple +ExecStart=/bin/ls +#ExecStartPre=-/bin/about.elf \ No newline at end of file diff --git a/parse_test/test_timer_unit.timer b/parse_test/test_timer_unit.timer new file mode 100644 index 0000000..daca190 --- /dev/null +++ b/parse_test/test_timer_unit.timer @@ -0,0 +1,7 @@ +[Unit] +Description=a timer for the same_name.service + +[Timer] +OnActiveSec=3s +OnUnitActiveSec=5s +Unit=test_timer_unit.service \ No newline at end of file diff --git a/src/manager/timer_manager/mod.rs b/src/manager/timer_manager/mod.rs index db78e76..1bee448 100644 --- a/src/manager/timer_manager/mod.rs +++ b/src/manager/timer_manager/mod.rs @@ -8,6 +8,7 @@ use crate::{ }; use hashbrown::HashMap; use lazy_static::lazy_static; +use libc::sleep; lazy_static! { // 管理全局计时器任务 @@ -52,14 +53,14 @@ impl TimerManager { pub fn push_timer_unit(unit: Arc>) { let timemanager = TIMER_TASK_MANAGER.write().unwrap(); - let mut unit_ = unit.lock().unwrap(); - let unit_id = unit_.unit_id(); + let mut unit_guard = unit.lock().unwrap(); + let unit_id = unit_guard.unit_id(); timemanager .id_table .write() .unwrap() - .push((unit_id, unit_.get_parent_unit())); - drop(unit_); + .push((unit_id, unit_guard.get_parent_unit())); + drop(unit_guard); timemanager .timer_unit_map .write() @@ -71,6 +72,7 @@ impl TimerManager { /// /// 该方法在主循环中每循环一次检测一次,是伪计时器的主运行函数 pub fn check_timer() { + unsafe { sleep(5) }; let mut writer = TIMER_TASK_MANAGER.write().unwrap(); //此处触发定时器,若定时器被触发,则移除 writer.inner_timers.retain_mut(|x| !x.check()); diff --git a/src/unit/timer/mod.rs b/src/unit/timer/mod.rs index 04595e7..4242ddb 100644 --- a/src/unit/timer/mod.rs +++ b/src/unit/timer/mod.rs @@ -218,6 +218,7 @@ impl TimerUnit { } pub fn check(&mut self) -> bool { + let id: usize = self.unit_id(); let part = &mut self.timer_part; //计时器不可用 if part.value.len() == 0 { @@ -238,11 +239,11 @@ impl TimerUnit { part.now_time = Instant::now(); //到时间执行Timer所管理的Unit - // println!( - // "Now time::{:?},next_elapse_monotonic_or_boottime::{:?}_", - // part.now_time, - // part.next_elapse_monotonic_or_boottime.unwrap() - // ); + println!( + "unit id: {} ,Now time::{:?},next_elapse_monotonic_or_boottime::{:?}_", + id,part.now_time, + part.next_elapse_monotonic_or_boottime.unwrap() + ); //!!!此处判断在DragonOs有大问题!时间跨度很大,但在linux上正常运行 if part.now_time >= part.next_elapse_monotonic_or_boottime.unwrap() { From 67fc0f65104c7633d9421cd30c2412adaad27b44 Mon Sep 17 00:00:00 2001 From: BrahmaMantra <2033552517.qq.com> Date: Fri, 17 May 2024 05:12:32 +0000 Subject: [PATCH 14/15] =?UTF-8?q?=E9=80=82=E9=85=8DDragonOS,=E7=9B=AE?= =?UTF-8?q?=E5=89=8D=E5=90=AF=E5=8A=A8=E7=B3=BB=E7=BB=9F=E6=97=B6=E4=BC=9A?= =?UTF-8?q?=E5=90=AF=E7=94=A8=E6=89=80=E6=9C=89=E7=9A=84unit?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- parse_test/test_timer_unit.service | 4 ++-- src/main.rs | 4 +--- src/manager/timer_manager/mod.rs | 17 ++++++--------- src/systemctl/ctl_parser/mod.rs | 16 ++++++++++++++ src/systemctl/listener/mod.rs | 15 +++++++++++-- src/systemctl/mod.rs | 1 - src/unit/service/mod.rs | 10 ++++----- src/unit/timer/mod.rs | 34 ++++-------------------------- 8 files changed, 47 insertions(+), 54 deletions(-) diff --git a/parse_test/test_timer_unit.service b/parse_test/test_timer_unit.service index 7bc885f..6a37d33 100644 --- a/parse_test/test_timer_unit.service +++ b/parse_test/test_timer_unit.service @@ -3,5 +3,5 @@ Description=a test for timer_unit [Service] Type=simple -ExecStart=/bin/ls -#ExecStartPre=-/bin/about.elf \ No newline at end of file +ExecStart=-/bin/about.elf +ExecStartPre=-/bin/clear \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index d9873cf..073e18a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -18,8 +18,6 @@ use crate::executor::Executor; pub struct FileDescriptor(usize); const DRAGON_REACH_UNIT_DIR: &'static str = "/etc/reach/system/"; -//const DRAGON_REACH_UNIT_DIR: &'static str = "/home/fz/testSystemd/"; - fn main() { // 初始化 Systemctl::init(); @@ -48,7 +46,7 @@ fn main() { 0 } }; - if id != 0 && TimerManager::is_timer(&id) { + if id != 0 { if let Err(e) = Executor::exec(id) { eprintln!("Err:{}", e.error_format()); } diff --git a/src/manager/timer_manager/mod.rs b/src/manager/timer_manager/mod.rs index 1bee448..c2d17e5 100644 --- a/src/manager/timer_manager/mod.rs +++ b/src/manager/timer_manager/mod.rs @@ -8,8 +8,6 @@ use crate::{ }; use hashbrown::HashMap; use lazy_static::lazy_static; -use libc::sleep; - lazy_static! { // 管理全局计时器任务 static ref TIMER_TASK_MANAGER:RwLock = RwLock::new(TimerManager { @@ -72,7 +70,6 @@ impl TimerManager { /// /// 该方法在主循环中每循环一次检测一次,是伪计时器的主运行函数 pub fn check_timer() { - unsafe { sleep(5) }; let mut writer = TIMER_TASK_MANAGER.write().unwrap(); //此处触发定时器,若定时器被触发,则移除 writer.inner_timers.retain_mut(|x| !x.check()); @@ -82,16 +79,16 @@ impl TimerManager { let timer_unit_map = reader.timer_unit_map.read().unwrap(); let mut inactive_unit: Vec = Vec::new(); for (_, timer_unit) in timer_unit_map.iter() { - let mut timer_unit = timer_unit.lock().unwrap(); - if timer_unit.enter_inactive() { - inactive_unit.push(timer_unit.unit_id()); + let mut unit_guard = timer_unit.lock().unwrap(); + if unit_guard.enter_inactive() { + inactive_unit.push(unit_guard.unit_id()); continue; } - if timer_unit.check() { + if unit_guard.check() { //println!("unit id : {} , parent id : {} ",timer_unit.unit_id(),timer_unit.get_parent_unit()); - let _ = timer_unit._run(); //运行作出相应操作 - let id = timer_unit.get_parent_unit(); - drop(timer_unit); + let _ = unit_guard._run(); //运行作出相应操作 + let id = unit_guard.get_parent_unit(); + drop(unit_guard); TimerManager::update_next_trigger(id, true); //更新触发时间 } } diff --git a/src/systemctl/ctl_parser/mod.rs b/src/systemctl/ctl_parser/mod.rs index 14b59a8..421221d 100644 --- a/src/systemctl/ctl_parser/mod.rs +++ b/src/systemctl/ctl_parser/mod.rs @@ -263,6 +263,22 @@ lazy_static! { pub struct CtlParser; impl CtlParser { + /// # parse_ctl - 解析控制命令 + /// + /// 该函数用于解析一个字符串形式的控制命令,并将其转换为`Command` + /// + /// ## 参数 + /// + /// - s: &str,需要解析的控制命令字符串。 + /// + /// ## 返回值 + /// + /// - Ok(Command): 解析成功的控制命令。 + /// - Err(ParseError): 解析失败时产生的错误。 + /// + /// ## 错误处理 + /// + /// 当输入的字符串不符合预期格式时,函数会返回一个`ParseError`错误。 pub fn parse_ctl(s: &str) -> Result { let mut words = s.split_whitespace().collect::>(); let mut ctl = Command::default(); diff --git a/src/systemctl/listener/mod.rs b/src/systemctl/listener/mod.rs index f7666ab..ea1f2ec 100644 --- a/src/systemctl/listener/mod.rs +++ b/src/systemctl/listener/mod.rs @@ -48,10 +48,14 @@ impl Default for Command { pub struct Systemctl; impl Systemctl { + /// # 初始化系统服务控制 - 初始化系统服务控制管道 pub fn init() { Self::init_ctl_pipe(); } - + /// # 初始化监听器 - 初始化系统服务控制命令监听器 + /// + /// 打开系统服务控制命令的管道文件描述符,并设置为非阻塞模式。 + /// pub fn init_listener() -> File { let fd = unsafe { libc::open(ctl_path().as_ptr(), libc::O_RDONLY | libc::O_NONBLOCK) }; if fd < 0 { @@ -59,7 +63,10 @@ impl Systemctl { } unsafe { File::from_raw_fd(fd) } } - + /// # 监听控制命令 - 监听系统服务控制命令 + /// + /// 持续从系统服务控制管道中读取命令。 + /// pub fn ctl_listen() { let mut guard = CTL_READER.lock().unwrap(); let mut s = String::new(); @@ -78,6 +85,10 @@ impl Systemctl { } } + /// # 检查控制管道是否存在 - 检查系统服务控制管道文件是否存在 + /// + /// 返回管道文件是否存在。 + /// fn is_ctl_exists() -> bool { if let Ok(metadata) = fs::metadata(DRAGON_REACH_CTL_PIPE) { metadata.is_file() diff --git a/src/systemctl/mod.rs b/src/systemctl/mod.rs index df04b2f..ce8cd94 100644 --- a/src/systemctl/mod.rs +++ b/src/systemctl/mod.rs @@ -4,7 +4,6 @@ pub mod ctl_parser; pub mod listener; pub const DRAGON_REACH_CTL_PIPE: &'static str = "/etc/reach/ipc/ctl"; -//pub const DRAGON_REACH_CTL_PIPE: &'static str = "/home/fz/myetc/reach/ipc/ctl"; pub fn ctl_path() -> CString { CString::new(DRAGON_REACH_CTL_PIPE).expect("Failed to create pipe CString") diff --git a/src/unit/service/mod.rs b/src/unit/service/mod.rs index bf51d46..633f2a3 100644 --- a/src/unit/service/mod.rs +++ b/src/unit/service/mod.rs @@ -146,12 +146,10 @@ impl Unit for ServiceUnit { if segment != Segment::Service { return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)); } - let attr_type = SERVICE_UNIT_ATTR_TABLE.get(attr).ok_or(ParseError::new( - ParseErrorType::EINVAL, - String::new(), - 0, - )); - return self.service_part.set_attr(attr_type.unwrap(), val); + if let Some(attr_type) = SERVICE_UNIT_ATTR_TABLE.get(attr) { + return self.service_part.set_attr(attr_type, val); + } + return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)); } fn set_unit_base(&mut self, base: BaseUnit) { diff --git a/src/unit/timer/mod.rs b/src/unit/timer/mod.rs index 4242ddb..8e167ca 100644 --- a/src/unit/timer/mod.rs +++ b/src/unit/timer/mod.rs @@ -35,8 +35,6 @@ impl Unit for TimerUnit { // 将单元状态设置为激活中 self.unit_base.state = UnitState::Activating; // 更新计时器部分的数据 - let part = &mut self.timer_part; - part.remain_after_elapse = true; // 设置初始触发时间 let part = &mut self.timer_part; @@ -130,12 +128,10 @@ impl Unit for TimerUnit { // 如果段不是计时器段,则返回错误 return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)); } - let attr_type = TIMER_UNIT_ATTR_TABLE.get(attr).ok_or(ParseError::new( - ParseErrorType::EINVAL, - String::new(), - 0, - )); - return self.timer_part.set_attr(attr_type.unwrap(), val); + if let Some(attr_type) = TIMER_UNIT_ATTR_TABLE.get(attr) { + return self.timer_part.set_attr(attr_type, val); + } + Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)) } fn set_unit_base(&mut self, unit_base: BaseUnit) { @@ -218,7 +214,6 @@ impl TimerUnit { } pub fn check(&mut self) -> bool { - let id: usize = self.unit_id(); let part = &mut self.timer_part; //计时器不可用 if part.value.len() == 0 { @@ -238,23 +233,9 @@ impl TimerUnit { } part.now_time = Instant::now(); - //到时间执行Timer所管理的Unit - println!( - "unit id: {} ,Now time::{:?},next_elapse_monotonic_or_boottime::{:?}_", - id,part.now_time, - part.next_elapse_monotonic_or_boottime.unwrap() - ); - - //!!!此处判断在DragonOs有大问题!时间跨度很大,但在linux上正常运行 if part.now_time >= part.next_elapse_monotonic_or_boottime.unwrap() { //检查Timer管理的unit是否存在 if let Some(_) = UnitManager::get_unit_with_id(&part.unit) { - // let _ = unit.lock().unwrap().run();//运行时作出相应操作,check不负责此操作 - // println!( - // "Now time::{:?},next_elapse_monotonic_or_boottime::{:?}_", - // part.now_time, - // part.next_elapse_monotonic_or_boottime.unwrap() - // ); return true; } println!("task error,unit does not exist"); @@ -273,13 +254,6 @@ impl TimerUnit { pub fn mut_timer_part(&mut self) -> &mut TimerPart { &mut self.timer_part } - pub fn timer_init(&mut self) { - let part = &mut self.timer_part; - part.next_elapse_monotonic_or_boottime = None; - part.next_elapse_realtime = Instant::now(); - part.now_time = Instant::now(); - part.remain_after_elapse = true; - } pub fn get_parent_unit(&mut self) -> usize { self.timer_part().unit From 1afba69f0f698f6d39e915547b5086d95f6c3b60 Mon Sep 17 00:00:00 2001 From: BrahmaMantra <2033552517.qq.com> Date: Sun, 19 May 2024 07:37:14 +0000 Subject: [PATCH 15/15] =?UTF-8?q?=E2=80=9C=E8=A7=84=E8=8C=83=E7=9B=B8?= =?UTF-8?q?=E5=85=B3=E6=B3=A8=E9=87=8A"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/unit/timer/mod.rs | 38 +++++++++++++------------------------- 1 file changed, 13 insertions(+), 25 deletions(-) diff --git a/src/unit/timer/mod.rs b/src/unit/timer/mod.rs index 8e167ca..2cfbc78 100644 --- a/src/unit/timer/mod.rs +++ b/src/unit/timer/mod.rs @@ -30,8 +30,8 @@ impl Default for TimerUnit { } impl Unit for TimerUnit { + /// 初始化计时器单元 fn init(&mut self) { - // 初始化计时器单元 // 将单元状态设置为激活中 self.unit_base.state = UnitState::Activating; // 更新计时器部分的数据 @@ -91,39 +91,33 @@ impl Unit for TimerUnit { // 将单元状态设置为激活 self.unit_base.state = UnitState::Active; } - + /// 设置单元的名称 fn set_unit_name(&mut self, name: String) { - // 设置单元的名称 self.unit_base_mut().unit_name = name; } - + /// 重启单元 fn restart(&mut self) -> Result<(), RuntimeError> { - // 重启单元 self.exit(); self.init(); Ok(()) } - + /// 从给定的路径解析并创建计时器单元 fn from_path(path: &str) -> Result where Self: Sized, { - // 从给定的路径解析并创建计时器单元 TimerParser::parse(path) } - + /// 将计时器单元转换为任何类型,用于多态调用 fn as_any(&self) -> &dyn std::any::Any { - // 将计时器单元转换为任何类型,用于多态调用 self } - + /// 将计时器单元转换为任何可变类型,用于多态调用 fn as_mut_any(&mut self) -> &mut dyn std::any::Any { - // 将计时器单元转换为任何可变类型,用于多态调用 self } - + /// 设置计时器单元的属性 fn set_attr(&mut self, segment: Segment, attr: &str, val: &str) -> Result<(), ParseError> { - // 设置计时器单元的属性 if segment != Segment::Timer { // 如果段不是计时器段,则返回错误 return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)); @@ -133,29 +127,24 @@ impl Unit for TimerUnit { } Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)) } - + /// 设置单元的基础信息 fn set_unit_base(&mut self, unit_base: BaseUnit) { - // 设置单元的基础信息 self.unit_base = unit_base; } - + /// 返回单元的类型 fn unit_type(&self) -> super::UnitType { - // 返回单元的类型 self.unit_base.unit_type } - + /// 返回单元的基础信息 fn unit_base(&self) -> &BaseUnit { - // 返回单元的基础信息 &self.unit_base } - + /// 返回单元的基础信息的可变引用 fn unit_base_mut(&mut self) -> &mut BaseUnit { - // 返回单元的基础信息的可变引用 &mut self.unit_base } - + /// 返回单元的ID fn unit_id(&self) -> usize { - // 返回单元的ID self.unit_base.unit_id } @@ -258,9 +247,8 @@ impl TimerUnit { pub fn get_parent_unit(&mut self) -> usize { self.timer_part().unit } - + ///判断计时器是否失效 pub fn enter_inactive(&mut self) -> bool { - //判断计时器是否失效 if self.unit_base.state == UnitState::Inactive { return true; }