1 use std::fs::File; 2 use std::io::{self, BufRead}; 3 use std::sync::{Arc, Mutex}; 4 5 use crate::error::parse_error::ParseErrorType; 6 use crate::manager::UnitManager; 7 use crate::unit::timer::TimerUnitAttr; 8 use crate::unit::{BaseUnit, Unit}; 9 use crate::DRAGON_REACH_UNIT_DIR; 10 use crate::{ 11 error::parse_error::ParseError, 12 unit::{service::ServiceUnitAttr, BaseUnitAttr, InstallUnitAttr, UnitType}, 13 }; 14 15 use hashbrown::HashMap; 16 use lazy_static::lazy_static; 17 18 use self::parse_service::ServiceParser; 19 use self::parse_target::TargetParser; 20 use self::parse_timer::TimerParser; 21 use self::parse_util::UnitParseUtil; 22 23 pub mod graph; 24 pub mod parse_service; 25 pub mod parse_target; 26 pub mod parse_timer; 27 pub mod parse_util; 28 29 //对应Unit段类型 30 #[derive(PartialEq, Clone, Copy)] 31 pub enum Segment { 32 None, 33 Unit, 34 Install, 35 Service, 36 Timer, 37 } 38 39 lazy_static! { 40 pub static ref UNIT_SUFFIX: HashMap<&'static str, UnitType> = { 41 let mut table = HashMap::new(); 42 table.insert("automount", UnitType::Automount); 43 table.insert("device", UnitType::Device); 44 table.insert("mount", UnitType::Mount); 45 table.insert("path", UnitType::Path); 46 table.insert("scope", UnitType::Scope); 47 table.insert("service", UnitType::Service); 48 table.insert("slice", UnitType::Automount);//疑似copy错了,稍后修改 49 table.insert("automount", UnitType::Slice);// 50 table.insert("socket", UnitType::Socket); 51 table.insert("swap", UnitType::Swap); 52 table.insert("target", UnitType::Target); 53 table.insert("timer", UnitType::Timer); 54 table 55 }; 56 pub static ref SEGMENT_TABLE: HashMap<&'static str, Segment> = { 57 let mut table = HashMap::new(); 58 table.insert("[Unit]", Segment::Unit); 59 table.insert("[Install]", Segment::Install); 60 table.insert("[Service]", Segment::Service); 61 table.insert("[Timer]", Segment::Timer); 62 // 后续再添加需求的具体字段 63 table 64 }; 65 pub static ref INSTALL_UNIT_ATTR_TABLE: HashMap<&'static str, InstallUnitAttr> = { 66 let mut unit_attr_table = HashMap::new(); 67 unit_attr_table.insert("WantedBy", InstallUnitAttr::WantedBy); 68 unit_attr_table.insert("RequiredBy", InstallUnitAttr::RequiredBy); 69 unit_attr_table.insert("Also", InstallUnitAttr::Also); 70 unit_attr_table.insert("Alias", InstallUnitAttr::Alias); 71 unit_attr_table 72 }; 73 pub static ref SERVICE_UNIT_ATTR_TABLE: HashMap<&'static str, ServiceUnitAttr> = { 74 let mut unit_attr_table = HashMap::new(); 75 unit_attr_table.insert("Type", ServiceUnitAttr::Type); 76 unit_attr_table.insert("RemainAfterExit", ServiceUnitAttr::RemainAfterExit); 77 unit_attr_table.insert("ExecStart", ServiceUnitAttr::ExecStart); 78 unit_attr_table.insert("ExecStartPre", ServiceUnitAttr::ExecStartPre); 79 unit_attr_table.insert("ExecStartPos", ServiceUnitAttr::ExecStartPos); 80 unit_attr_table.insert("ExecReload", ServiceUnitAttr::ExecReload); 81 unit_attr_table.insert("ExecStop", ServiceUnitAttr::ExecStop); 82 unit_attr_table.insert("ExecStopPost", ServiceUnitAttr::ExecStopPost); 83 unit_attr_table.insert("RestartSec", ServiceUnitAttr::RestartSec); 84 unit_attr_table.insert("Restart", ServiceUnitAttr::Restart); 85 unit_attr_table.insert("TimeoutStartSec", ServiceUnitAttr::TimeoutStartSec); 86 unit_attr_table.insert("TimeoutStopSec", ServiceUnitAttr::TimeoutStopSec); 87 unit_attr_table.insert("Environment", ServiceUnitAttr::Environment); 88 unit_attr_table.insert("EnvironmentFile", ServiceUnitAttr::EnvironmentFile); 89 unit_attr_table.insert("Nice", ServiceUnitAttr::Nice); 90 unit_attr_table.insert("WorkingDirectory", ServiceUnitAttr::WorkingDirectory); 91 unit_attr_table.insert("RootDirectory", ServiceUnitAttr::RootDirectory); 92 unit_attr_table.insert("User", ServiceUnitAttr::User); 93 unit_attr_table.insert("Group", ServiceUnitAttr::Group); 94 unit_attr_table.insert("MountFlags", ServiceUnitAttr::MountFlags); 95 unit_attr_table 96 }; 97 pub static ref BASE_UNIT_ATTR_TABLE: HashMap<&'static str, BaseUnitAttr> = { 98 let mut unit_attr_table = HashMap::new(); 99 unit_attr_table.insert("Description", BaseUnitAttr::Description); 100 unit_attr_table.insert("Documentation", BaseUnitAttr::Documentation); 101 unit_attr_table.insert("Requires", BaseUnitAttr::Requires); 102 unit_attr_table.insert("Wants", BaseUnitAttr::Wants); 103 unit_attr_table.insert("After", BaseUnitAttr::After); 104 unit_attr_table.insert("Before", BaseUnitAttr::Before); 105 unit_attr_table.insert("Binds To", BaseUnitAttr::BindsTo); 106 unit_attr_table.insert("Part Of", BaseUnitAttr::PartOf); 107 unit_attr_table.insert("OnFailure", BaseUnitAttr::OnFailure); 108 unit_attr_table.insert("Conflicts", BaseUnitAttr::Conflicts); 109 unit_attr_table 110 }; 111 pub static ref BASE_IEC: HashMap<&'static str, u64> = { 112 let mut table = HashMap::new(); 113 table.insert( 114 "E", 115 1024u64 * 1024u64 * 1024u64 * 1024u64 * 1024u64 * 1024u64, 116 ); 117 table.insert("P", 1024u64 * 1024u64 * 1024u64 * 1024u64 * 1024u64); 118 table.insert("T", 1024u64 * 1024u64 * 1024u64 * 1024u64); 119 table.insert("G", 1024u64 * 1024u64 * 1024u64); 120 table.insert("M", 1024u64 * 1024u64); 121 table.insert("K", 1024u64); 122 table.insert("B", 1u64); 123 table.insert("", 1u64); 124 table 125 }; 126 pub static ref BASE_SI: HashMap<&'static str, u64> = { 127 let mut table = HashMap::new(); 128 table.insert( 129 "E", 130 1000u64 * 1000u64 * 1000u64 * 1000u64 * 1000u64 * 1000u64, 131 ); 132 table.insert("P", 1000u64 * 1000u64 * 1000u64 * 1000u64 * 1000u64); 133 table.insert("T", 1000u64 * 1000u64 * 1000u64 * 1000u64); 134 table.insert("G", 1000u64 * 1000u64 * 1000u64); 135 table.insert("M", 1000u64 * 1000u64); 136 table.insert("K", 1000u64); 137 table.insert("B", 1u64); 138 table.insert("", 1u64); 139 table 140 }; 141 pub static ref SEC_UNIT_TABLE: HashMap<&'static str, u64> = { 142 let mut table = HashMap::new(); 143 table.insert("h", 60 * 60 * 1000 * 1000 * 1000); 144 table.insert("min", 60 * 1000 * 1000 * 1000); 145 table.insert("m", 60 * 1000 * 1000 * 1000); 146 table.insert("s", 1000 * 1000 * 1000); 147 table.insert("", 1000 * 1000 * 1000); 148 table.insert("ms", 1000 * 1000); 149 table.insert("us", 1000); 150 table.insert("ns", 1); 151 table 152 }; 153 pub static ref TIMER_UNIT_ATTR_TABLE: HashMap<&'static str, TimerUnitAttr> = { 154 let mut map = HashMap::new(); 155 // map.insert("State", TimerUnitAttr::State); 156 // map.insert("Result", TimerUnitAttr::Result); 157 map.insert("OnActiveSec", TimerUnitAttr::OnActiveSec); 158 map.insert("OnBootSec", TimerUnitAttr::OnBootSec); 159 map.insert("OnStartupSec", TimerUnitAttr::OnStartUpSec); 160 map.insert("OnUnitActiveSec", TimerUnitAttr::OnUnitActiveSec); 161 map.insert("OnUnitInactiveSec", TimerUnitAttr::OnUnitInactiveSec); 162 map.insert("OnCalendar", TimerUnitAttr::OnCalendar); 163 map.insert("AccuracySec", TimerUnitAttr::AccuarcySec); 164 map.insert("RandomizedDelaySec", TimerUnitAttr::RandomizedDelaySec); 165 map.insert("FixedRandomDelay", TimerUnitAttr::FixedRandomDelay); 166 map.insert("OnClockChange", TimerUnitAttr::OnClockChange); 167 map.insert("OnTimezoneChange", TimerUnitAttr::OnTimeZoneChange); 168 map.insert("Unit", TimerUnitAttr::Unit); 169 map.insert("Persistent", TimerUnitAttr::Persistent); 170 map.insert("WakeSystem", TimerUnitAttr::WakeSystem); 171 map.insert("RemainAfterElapse", TimerUnitAttr::RemainAfterElapse); 172 map 173 }; 174 } 175 176 //用于解析Unit共有段的方法 177 pub struct UnitParser; 178 179 impl UnitParser { 180 /// @brief 从path获取到BufReader,此方法将会检验文件类型 181 /// 182 /// 如果指定UnitType,则进行文件名检查 183 /// 184 /// @param path 需解析的文件路径 185 /// 186 /// @param unit_type 指定Unit类型 187 /// 188 /// @return 成功则返回对应BufReader,否则返回Err get_reader(path: &str, unit_type: UnitType) -> Result<io::BufReader<File>, ParseError>189 pub fn get_reader(path: &str, unit_type: UnitType) -> Result<io::BufReader<File>, ParseError> { 190 //判断是否为路径,若不为路径则到定向到默认unit文件夹 191 let mut realpath = path.to_string(); 192 if !path.contains('/') { 193 realpath = format!("{}{}", DRAGON_REACH_UNIT_DIR, &path).to_string(); 194 } 195 let path = realpath.as_str(); 196 // 如果指定UnitType,则进行文件名检查,不然直接返回reader 197 if unit_type != UnitType::Unknown { 198 let suffix = match path.rfind('.') { 199 Some(idx) => &path[idx + 1..], 200 None => { 201 return Err(ParseError::new(ParseErrorType::EFILE, path.to_string(), 0)); 202 } 203 }; 204 let u_type = UNIT_SUFFIX.get(suffix); 205 if u_type.is_none() { 206 return Err(ParseError::new(ParseErrorType::EFILE, path.to_string(), 0)); 207 } 208 if *(u_type.unwrap()) != unit_type { 209 return Err(ParseError::new(ParseErrorType::EFILE, path.to_string(), 0)); 210 } 211 } 212 let file = match File::open(path) { 213 Ok(file) => file, 214 Err(_) => { 215 return Err(ParseError::new(ParseErrorType::EFILE, path.to_string(), 0)); 216 } 217 }; 218 return Ok(io::BufReader::new(file)); 219 } 220 from_path(path: &str) -> Result<usize, ParseError>221 pub fn from_path(path: &str) -> Result<usize, ParseError> { 222 let unit_type = UnitParseUtil::parse_type(&path); 223 match unit_type { 224 UnitType::Service => ServiceParser::parse(path), 225 UnitType::Target => TargetParser::parse(path), 226 UnitType::Timer => TimerParser::parse(path), //新实现的timer_unit 227 _ => Err(ParseError::new(ParseErrorType::EFILE, path.to_string(), 0)), 228 } 229 } 230 231 /// @brief 将path路径的文件解析为unit_type类型的Unit 232 /// 233 /// 该方法解析每个Unit共有的段(Unit,Install),其余独有的段属性将会交付T类型的Unit去解析 234 /// 235 /// @param path 需解析的文件路径 236 /// 237 /// @param unit_type 指定Unit类型 238 /// 239 /// @return 解析成功则返回Ok(Arc<T>),否则返回Err parse<T: Unit + Default + Clone + 'static>( path: &str, unit_type: UnitType, ) -> Result<usize, ParseError>240 pub fn parse<T: Unit + Default + Clone + 'static>( 241 path: &str, 242 unit_type: UnitType, 243 ) -> Result<usize, ParseError> { 244 let name = match path.rfind("/") { 245 Some(size) => String::from(&path[size..]), 246 None => String::from(path), 247 }; 248 // 如果该文件已解析过,则直接返回id 249 if UnitManager::contains_name(&name) { 250 let unit = UnitManager::get_unit_with_name(&name).unwrap(); 251 let unit = unit.lock().unwrap(); 252 return Ok(unit.unit_id()); 253 } 254 255 let mut unit: T = T::default(); 256 let mut unit_base = BaseUnit::default(); 257 //设置unit类型标记 258 unit_base.set_unit_type(unit_type); 259 260 let reader = UnitParser::get_reader(path, unit_type)?; 261 262 //用于记录当前段的类型 263 let mut segment = Segment::None; 264 //用于处理多行对应一个属性的情况 265 let _last_attr = ServiceUnitAttr::None; 266 267 //一行一行向下解析 268 let lines = reader 269 .lines() 270 .map(|line| line.unwrap()) 271 .collect::<Vec<String>>(); 272 let mut i = 0; 273 while i < lines.len() { 274 let line = &lines[i]; 275 //空行跳过 276 if line.chars().all(char::is_whitespace) { 277 i += 1; 278 continue; 279 } 280 //注释跳过 281 if line.starts_with('#') { 282 i += 1; 283 continue; 284 } 285 let mut line = line.trim(); 286 let segment_flag = SEGMENT_TABLE.get(&line); 287 if !segment_flag.is_none() { 288 //如果当前行匹配到的为段名,则切换段类型继续匹配下一行 289 segment = *segment_flag.unwrap(); 290 i += 1; 291 continue; 292 } 293 if segment == Segment::None { 294 //未找到段名则不能继续匹配 295 return Err(ParseError::new( 296 ParseErrorType::ESyntaxError, 297 path.to_string(), 298 i + 1, 299 )); 300 } 301 302 //下面进行属性匹配 303 //合并多行为一个属性的情况 304 //最后一个字符为\,代表换行,将多行转换为一行统一解析 305 let mut templine = String::new(); 306 if lines[i].ends_with('\\') { 307 while lines[i].ends_with('\\') { 308 let temp = &lines[i][..lines[i].len() - 1]; 309 templine = format!("{} {}", templine, temp); 310 i += 1; 311 } 312 templine = format!("{} {}", templine, lines[i]); 313 line = templine.as_str(); 314 i += 1; 315 } 316 //=号分割后第一个元素为属性,后面的均为值 317 let (attr_str, val_str) = match line.find('=') { 318 Some(idx) => (line[..idx].trim(), line[idx + 1..].trim()), 319 None => { 320 return Err(ParseError::new( 321 ParseErrorType::ESyntaxError, 322 path.to_string(), 323 i + 1, 324 )); 325 } 326 }; 327 //首先匹配所有unit文件都有的unit段和install段 328 if BASE_UNIT_ATTR_TABLE.get(attr_str).is_some() { 329 //匹配Unit字段 330 if segment != Segment::Unit { 331 return Err(ParseError::new( 332 ParseErrorType::EINVAL, 333 path.to_string(), 334 i + 1, 335 )); 336 } 337 if let Err(e) = unit_base 338 .set_unit_part_attr(BASE_UNIT_ATTR_TABLE.get(attr_str).unwrap(), val_str) 339 { 340 let mut e = e.clone(); 341 e.set_file(path); 342 e.set_linenum(i + 1); 343 return Err(e); 344 } 345 } else if INSTALL_UNIT_ATTR_TABLE.get(attr_str).is_some() { 346 //匹配Install字段 347 if segment != Segment::Install { 348 return Err(ParseError::new( 349 ParseErrorType::EINVAL, 350 path.to_string(), 351 i + 1, 352 )); 353 } 354 if let Err(e) = unit_base 355 .set_install_part_attr(INSTALL_UNIT_ATTR_TABLE.get(attr_str).unwrap(), val_str) 356 { 357 let mut e = e.clone(); 358 e.set_file(path); 359 e.set_linenum(i + 1); 360 return Err(e); 361 } 362 } else { 363 if let Err(e) = unit.set_attr(segment, attr_str, val_str) { 364 let mut e = e.clone(); 365 e.set_file(path); 366 e.set_linenum(i + 1); 367 return Err(e); 368 } 369 } 370 i += 1; 371 } 372 373 unit.set_unit_base(unit_base); 374 unit.set_unit_name(name.clone()); 375 let id = unit.set_unit_id(); 376 unit.init(); 377 let dret: Arc<Mutex<dyn Unit>> = Arc::new(Mutex::new(unit)); 378 UnitManager::insert_unit_with_id(id, dret); 379 UnitManager::insert_into_name_table(&name, id); 380 381 return Ok(id); 382 } 383 } 384