1 use super::{BaseUnit, Unit}; 2 use crate::error::parse_error::{ParseError, ParseErrorType}; 3 use crate::error::runtime_error::{RuntimeError, RuntimeErrorType}; 4 use crate::executor::Executor; 5 use crate::manager::timer_manager::TimerManager; 6 use crate::manager::UnitManager; 7 use crate::parse::parse_timer::TimerParser; 8 use crate::parse::{Segment, TIMER_UNIT_ATTR_TABLE}; 9 use crate::time::calandar::CalendarStandard; 10 use crate::unit::UnitState; 11 use humantime::parse_duration; 12 use std::fmt::Debug; 13 use std::sync::{Arc, Mutex}; 14 use std::time::{Duration, Instant}; 15 16 #[allow(dead_code)] 17 #[derive(Clone, Debug)] 18 pub struct TimerUnit { 19 unit_base: BaseUnit, 20 timer_part: TimerPart, 21 } 22 23 impl Default for TimerUnit { 24 fn default() -> Self { 25 Self { 26 unit_base: Default::default(), 27 timer_part: Default::default(), 28 } 29 } 30 } 31 32 impl Unit for TimerUnit { 33 /// 初始化计时器单元 34 fn init(&mut self) { 35 // 将单元状态设置为激活中 36 self.unit_base.state = UnitState::Activating; 37 // 更新计时器部分的数据 38 39 // 设置初始触发时间 40 let part = &mut self.timer_part; 41 let now = Instant::now(); 42 part.last_trigger = now; 43 part.now_time = now; 44 45 // 如果设置了激活时的秒数,则添加一个计时器值 46 if part.on_active_sec != Default::default() { 47 part.value.push(TimerVal::new( 48 TimerUnitAttr::OnActiveSec, 49 false, 50 part.on_active_sec, 51 Default::default(), 52 Some(now + part.on_active_sec), 53 )); 54 } 55 56 // 实现OnActiveSec的具体逻辑 57 58 // 检查单元是否正在运行 59 let unit_is_running = UnitManager::is_running_unit(&part.unit); 60 61 if part.on_unit_active_sec != Default::default() { 62 let next_trigger = if unit_is_running { 63 Some(now + part.on_unit_active_sec) 64 } else { 65 None 66 }; 67 part.value.push(TimerVal::new( 68 TimerUnitAttr::OnUnitActiveSec, 69 !unit_is_running, 70 part.on_unit_active_sec, 71 Default::default(), 72 next_trigger, 73 )); 74 } 75 76 // 实现OnUnitActiveSec的具体逻辑 77 78 if part.on_unit_inactive_sec != Default::default() { 79 part.value.push(TimerVal::new( 80 TimerUnitAttr::OnUnitInactiveSec, 81 true, 82 part.on_unit_inactive_sec, 83 Default::default(), 84 None, /*无论服务是否在运行,这里都不会有值 */ 85 )); 86 } 87 88 // 实现OnUnitInactiveSec的具体逻辑 89 part.update_next_trigger(); 90 self._init(); 91 // 将单元状态设置为激活 92 self.unit_base.state = UnitState::Active; 93 } 94 /// 设置单元的名称 95 fn set_unit_name(&mut self, name: String) { 96 self.unit_base_mut().unit_name = name; 97 } 98 /// 重启单元 99 fn restart(&mut self) -> Result<(), RuntimeError> { 100 self.exit(); 101 self.init(); 102 Ok(()) 103 } 104 /// 从给定的路径解析并创建计时器单元 105 fn from_path(path: &str) -> Result<usize, ParseError> 106 where 107 Self: Sized, 108 { 109 TimerParser::parse(path) 110 } 111 /// 将计时器单元转换为任何类型,用于多态调用 112 fn as_any(&self) -> &dyn std::any::Any { 113 self 114 } 115 /// 将计时器单元转换为任何可变类型,用于多态调用 116 fn as_mut_any(&mut self) -> &mut dyn std::any::Any { 117 self 118 } 119 /// 设置计时器单元的属性 120 fn set_attr(&mut self, segment: Segment, attr: &str, val: &str) -> Result<(), ParseError> { 121 if segment != Segment::Timer { 122 // 如果段不是计时器段,则返回错误 123 return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)); 124 } 125 if let Some(attr_type) = TIMER_UNIT_ATTR_TABLE.get(attr) { 126 return self.timer_part.set_attr(attr_type, val); 127 } 128 Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)) 129 } 130 /// 设置单元的基础信息 131 fn set_unit_base(&mut self, unit_base: BaseUnit) { 132 self.unit_base = unit_base; 133 } 134 /// 返回单元的类型 135 fn unit_type(&self) -> super::UnitType { 136 self.unit_base.unit_type 137 } 138 /// 返回单元的基础信息 139 fn unit_base(&self) -> &BaseUnit { 140 &self.unit_base 141 } 142 /// 返回单元的基础信息的可变引用 143 fn unit_base_mut(&mut self) -> &mut BaseUnit { 144 &mut self.unit_base 145 } 146 /// 返回单元的ID 147 fn unit_id(&self) -> usize { 148 self.unit_base.unit_id 149 } 150 151 fn run(&mut self) -> Result<(), RuntimeError> { 152 //真正的run在_run中 153 if self.check() && UnitManager::contains_id(&self.timer_part.unit) { 154 // 如果单元检查通过并且单元管理器包含该单元,则运行 155 let _ = self._run(); // 运行单元 156 let id = self.get_parent_unit(); 157 // 更新下一个触发器 158 TimerManager::update_next_trigger(id, true); 159 } else if !UnitManager::contains_id(&self.timer_part.unit) { 160 // 如果单元管理器不包含该单元,则打印错误信息 161 println!("task error,unit does not exist") 162 }; 163 Ok(()) 164 } 165 166 fn exit(&mut self) { 167 UnitManager::try_kill_running(self.unit_id()); 168 } 169 } 170 171 impl TimerUnit { 172 pub fn _run(&mut self) -> Result<(), RuntimeError> { 173 //到这里触发计时器对应的服务 174 let part = &mut self.timer_part; 175 if part.value.is_empty() { 176 //触发次数已尽 177 self.unit_base.state = UnitState::Inactive; 178 } else if matches!( 179 part.value[0].attr, 180 TimerUnitAttr::OnActiveSec | TimerUnitAttr::OnBootSec | TimerUnitAttr::OnStartUpSec 181 ) { 182 part.value.remove(0); //消耗掉此次run时的TimeValue值 183 } 184 185 if UnitManager::is_running_unit(&part.unit) { 186 //如果服务已经启动,则退出 187 return Ok(()); 188 } 189 190 //执行相应的unit单元 191 if let Ok(_) = Executor::exec(part.unit) { 192 self.unit_base.state = UnitState::Active; 193 part.last_trigger = Instant::now(); 194 return Ok(()); 195 } else { 196 self.unit_base.state = UnitState::Failed; 197 return Err(RuntimeError::new(RuntimeErrorType::ExecFailed)); 198 } 199 } 200 fn _init(&self) { 201 let unit: Arc<Mutex<TimerUnit>> = Arc::new(Mutex::new(self.clone())); 202 TimerManager::push_timer_unit(unit); 203 } 204 205 pub fn check(&mut self) -> bool { 206 let part = &mut self.timer_part; 207 //计时器不可用 208 if part.value.len() == 0 { 209 //不可能再触发 210 self.unit_base.state = UnitState::Inactive; 211 } 212 if self.unit_base.state == UnitState::Inactive 213 //可能是手动停止 214 { 215 return false; 216 } 217 if UnitManager::is_running_unit(&part.unit) //在运行就不管了 218 || part.next_elapse_monotonic_or_boottime==None 219 //下次触发时间无限大 220 { 221 return false; 222 } 223 part.now_time = Instant::now(); 224 225 if part.now_time >= part.next_elapse_monotonic_or_boottime.unwrap() { 226 //检查Timer管理的unit是否存在 227 if let Some(_) = UnitManager::get_unit_with_id(&part.unit) { 228 return true; 229 } 230 println!("task error,unit does not exist"); 231 } 232 return false; 233 } 234 235 pub fn unit_base(&self) -> &BaseUnit { 236 &self.unit_base 237 } 238 239 pub fn timer_part(&self) -> &TimerPart { 240 &self.timer_part 241 } 242 243 pub fn mut_timer_part(&mut self) -> &mut TimerPart { 244 &mut self.timer_part 245 } 246 247 pub fn get_parent_unit(&mut self) -> usize { 248 self.timer_part().unit 249 } 250 ///判断计时器是否失效 251 pub fn enter_inactive(&mut self) -> bool { 252 if self.unit_base.state == UnitState::Inactive { 253 return true; 254 } 255 false 256 } 257 258 ///在unit run或exit的时候改变TimerValue中OnUnitInactiveSec和OnUnitActiveSec的状态 259 pub fn change_stage(&mut self, flag: bool /*1为启动0为退出 */) { 260 for val in &mut self.timer_part.value { 261 match val.attr { 262 TimerUnitAttr::OnUnitActiveSec => { 263 val.disabled = false; 264 if flag { 265 val.next_elapse = Some(Instant::now() + val.val); 266 } 267 } 268 TimerUnitAttr::OnUnitInactiveSec => { 269 val.disabled = false; 270 if !flag { 271 val.next_elapse = Some(Instant::now() + val.val); 272 } 273 } 274 _ => {} 275 } 276 } 277 } 278 } 279 unsafe impl Sync for TimerUnit {} 280 281 unsafe impl Send for TimerUnit {} 282 #[allow(dead_code)] 283 #[derive(Debug, Clone)] 284 pub struct TimerPart { 285 //TODO! 因此时DragonReach未实现时间事件源的相关功能,目前还是循环确认Timer的情况 286 ///@brief 存储触发计时器的时间集合 287 value: Vec<TimerVal>, 288 289 ///@brief 相对于该单元自身被启动的时间点 290 on_active_sec: Duration, 291 292 ///@brief 相对于机器被启动的时间点 293 on_boot_sec: Duration, 294 295 ///@brief 相对于systemd被首次启动的时间点,也就是内核启动init进程的时间点 296 on_start_up_sec: Duration, 297 298 ///@brief 相对于匹配单元最后一次被启动的时间点 299 on_unit_active_sec: Duration, 300 301 ///@brief 相对于匹配单元 最后一次被停止的时间点 302 on_unit_inactive_sec: Duration, 303 304 ///@brief 定义基于挂钟时间(wallclock)的日历定时器,值是一个日历事件表达式 305 on_calendar: CalendarStandard, 306 307 ///@brief 设置定时器的触发精度,默认1min 308 accuarcy_sec: usize, 309 310 ///@brief 随机延迟一小段时间,默认0表示不延迟 311 randomized_delay_sec: usize, 312 313 ///@brief 314 fixed_random_delay: bool, 315 316 ///@brief 317 on_clock_change: bool, 318 319 ///@brief 320 on_timezone_change: bool, 321 322 ///@brief 默认值是 与此定时器单元同名的服务单元 323 unit: usize, 324 325 ///@brief 若设为"yes",则表示将匹配单元的上次触发时间永久保存在磁盘上,默认no 326 persistent: bool, 327 328 ///@brief 若设为"yes", 则表示当某个定时器到达触发时间点时, 唤醒正在休眠的系统并阻止系统进入休眠状态,默认no 329 wake_system: bool, 330 331 ///@brief 若设为"yes" ,那么该定时器将不会被再次触发,也就是可以确保仅被触发一次;默认yes 332 remain_after_elapse: bool, //默认yes 333 334 ///@brief 表示计时器下次实时时间触发的时间戳 335 next_elapse_realtime: Instant, 336 337 ///@brief 表示计时器下次单调时间或引导时间触发的时间戳 338 next_elapse_monotonic_or_boottime: Option<Instant>, //None表示无限大 339 340 ///@brief 用于存储计时器最后一次触发的时间戳。 341 last_trigger: Instant, 342 343 ///@brief 用于表示当前的时间。 344 now_time: Instant, 345 } 346 347 impl Default for TimerPart { 348 fn default() -> Self { 349 Self { 350 value: Default::default(), 351 on_active_sec: Default::default(), 352 on_boot_sec: Default::default(), 353 on_start_up_sec: Default::default(), 354 on_unit_active_sec: Default::default(), 355 on_unit_inactive_sec: Default::default(), 356 on_calendar: CalendarStandard::default(), 357 accuarcy_sec: 60, // 默认设置为 60 秒 358 randomized_delay_sec: 0, 359 fixed_random_delay: false, 360 on_clock_change: false, 361 on_timezone_change: false, 362 unit: Default::default(), 363 persistent: false, 364 wake_system: false, 365 remain_after_elapse: true, 366 367 next_elapse_realtime: Instant::now(), 368 next_elapse_monotonic_or_boottime: None, 369 last_trigger: Instant::now(), 370 now_time: Instant::now(), 371 } 372 } 373 } 374 375 impl TimerPart { 376 /// 更新下一次的触发时间 377 pub fn update_next_trigger(&mut self) { 378 self.now_time = Instant::now(); 379 380 //let unit_is_running=UnitManager::is_running_unit(&self.unit); 381 //检查并更新value 382 let mut index = 0; 383 while index < self.value.len() { 384 let val = &mut self.value[index]; 385 match val.attr { 386 TimerUnitAttr::OnUnitInactiveSec | TimerUnitAttr::OnUnitActiveSec => { 387 //更新OnUnitInactiveSec和OnUnitActiveSec类型的值 388 if val.disabled || val.next_elapse == None { 389 //None表示此时无法确认下次触发时间 390 index = index + 1; 391 continue; 392 } else if val.next_elapse.unwrap() < self.now_time { 393 self.next_elapse_monotonic_or_boottime = val.next_elapse; 394 val.next_elapse = None; 395 // println!("Update the time!"); 396 return; 397 } 398 } 399 400 TimerUnitAttr::OnActiveSec | TimerUnitAttr::OnBootSec => { 401 if val.next_elapse.unwrap() < self.now_time { 402 self.next_elapse_monotonic_or_boottime = val.next_elapse; 403 self.value.remove(index); //在这一步准备把index从value里弹出去 404 return; 405 } 406 } 407 //TimerUnitAttr::OnStartUpSec => todo!(), 408 //TimerUnitAttr::OnCalendar => todo!(), 409 _ => todo!(), //暂未支持 410 } 411 index += 1; 412 } 413 // 对value排序,使得最早的定时器时间在最前面,且None类型在最后面 414 self.value.sort_by//(|a, b| a.next_elapse.cmp(&b.next_elapse)); 415 (|a, b| match (a.next_elapse, b.next_elapse) { 416 (None, None) => std::cmp::Ordering::Equal, 417 (None, Some(_)) => std::cmp::Ordering::Greater, 418 (Some(_), None) => std::cmp::Ordering::Less, 419 (Some(a), Some(b)) => a.cmp(&b), 420 }); 421 if self.value.is_empty() || self.value[0].next_elapse == None { 422 //无法得到下次触发的具体时间 423 return; 424 } 425 426 // 从已排序的Vec中获取最早的定时器时间 427 self.next_elapse_monotonic_or_boottime = self.value[0].next_elapse; 428 429 return; 430 } 431 /// &str->attr的parse 432 pub fn set_attr(&mut self, attr: &TimerUnitAttr, val: &str) -> Result<(), ParseError> { 433 match attr { 434 TimerUnitAttr::OnActiveSec => { 435 self.on_active_sec = { 436 if let Ok(duration) = parse_duration(val) { 437 duration 438 } else { 439 return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)); 440 } 441 } 442 } 443 444 TimerUnitAttr::OnBootSec => { 445 self.on_boot_sec = { 446 if let Ok(duration) = parse_duration(val) { 447 duration 448 } else { 449 return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)); 450 } 451 } 452 } 453 454 TimerUnitAttr::OnStartUpSec => { 455 self.on_start_up_sec = { 456 if let Ok(duration) = parse_duration(val) { 457 duration 458 } else { 459 return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)); 460 } 461 } 462 } 463 TimerUnitAttr::OnUnitInactiveSec => { 464 self.on_unit_inactive_sec = { 465 if let Ok(duration) = parse_duration(val) { 466 duration 467 } else { 468 return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)); 469 } 470 } 471 } 472 TimerUnitAttr::OnUnitActiveSec => { 473 self.on_unit_active_sec = { 474 if let Ok(duration) = parse_duration(val) { 475 duration 476 } else { 477 return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)); 478 } 479 } 480 } 481 // TimerUnitAttr::OnCalendar=>self.on_calendar={ 482 // if let Ok(calendar) = parse_calendar(val) { 483 // calendar 484 // } else { 485 // return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)); 486 // } 487 // }, 488 TimerUnitAttr::Persistent => { 489 self.persistent = { 490 match val { 491 "true" => true, 492 "false" => false, 493 _ => return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)), 494 } 495 } 496 } 497 TimerUnitAttr::Unit => self.unit = UnitManager::get_id_with_path(val).unwrap(), 498 _ => { 499 return Err(ParseError::new(ParseErrorType::EINVAL, String::new(), 0)); 500 } 501 } 502 Ok(()) 503 } 504 } 505 #[derive(Debug, Clone, Copy)] 506 pub enum TimerUnitAttr { 507 //TimerBase 508 // State, 509 // Result, 510 OnActiveSec, 511 OnBootSec, 512 OnStartUpSec, 513 OnUnitInactiveSec, 514 OnUnitActiveSec, 515 OnCalendar, 516 AccuarcySec, 517 RandomizedDelaySec, 518 FixedRandomDelay, 519 OnClockChange, 520 OnTimeZoneChange, 521 Unit, 522 Persistent, 523 WakeSystem, 524 RemainAfterElapse, 525 } 526 impl Default for TimerUnitAttr { 527 fn default() -> Self { 528 TimerUnitAttr::OnActiveSec 529 } 530 } 531 532 #[derive(Debug, Clone)] 533 pub struct TimerVal { 534 attr: TimerUnitAttr, 535 disabled: bool, 536 val: Duration, 537 //calendar_standard:Vec<CalendarStandard>,//只针对calendar事件 538 next_elapse: Option<Instant>, 539 } 540 541 impl TimerVal { 542 pub fn new( 543 attr: TimerUnitAttr, 544 disabled: bool, 545 val: Duration, 546 _calendar_standard: Vec<CalendarStandard>, //等待后续迭代 547 next_elapse: Option<Instant>, 548 ) -> TimerVal { 549 TimerVal { 550 attr, 551 disabled, 552 val, 553 //calendar_standard, 554 next_elapse, 555 } 556 } 557 } 558