loopdev.rs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. use core::str;
  2. use std::{path::PathBuf, process::Command, thread::sleep, time::Duration};
  3. use anyhow::{anyhow, Result};
  4. use regex::Regex;
  5. use crate::utils::abs_path;
  6. const LOOP_DEVICE_LOSETUP_A_REGEX: &str = r"^/dev/loop(\d+)";
  7. pub struct LoopDevice {
  8. img_path: Option<PathBuf>,
  9. loop_device_path: Option<String>,
  10. /// 尝试在drop时自动detach
  11. try_detach_when_drop: bool,
  12. }
  13. impl LoopDevice {
  14. pub fn attached(&self) -> bool {
  15. self.loop_device_path.is_some()
  16. }
  17. pub fn dev_path(&self) -> Option<&String> {
  18. self.loop_device_path.as_ref()
  19. }
  20. pub fn attach(&mut self) -> Result<()> {
  21. if self.attached() {
  22. return Ok(());
  23. }
  24. if self.img_path.is_none() {
  25. return Err(anyhow!("Image path not set"));
  26. }
  27. let output = Command::new("losetup")
  28. .arg("-f")
  29. .arg("--show")
  30. .arg("-P")
  31. .arg(self.img_path.as_ref().unwrap())
  32. .output()?;
  33. if output.status.success() {
  34. let loop_device = String::from_utf8(output.stdout)?.trim().to_string();
  35. self.loop_device_path = Some(loop_device);
  36. sleep(Duration::from_millis(100));
  37. log::trace!(
  38. "Loop device attached: {}",
  39. self.loop_device_path.as_ref().unwrap()
  40. );
  41. Ok(())
  42. } else {
  43. Err(anyhow::anyhow!(
  44. "Failed to mount disk image: losetup command exited with status {}",
  45. output.status
  46. ))
  47. }
  48. }
  49. /// 尝试连接已经存在的loop device
  50. pub fn attach_by_exists(&mut self) -> Result<()> {
  51. if self.attached() {
  52. return Ok(());
  53. }
  54. if self.img_path.is_none() {
  55. return Err(anyhow!("Image path not set"));
  56. }
  57. log::trace!(
  58. "Try to attach loop device by exists: image path: {}",
  59. self.img_path.as_ref().unwrap().display()
  60. );
  61. // losetup -a 查看是否有已经attach了的,如果有,就附着上去
  62. let cmd = Command::new("losetup")
  63. .arg("-a")
  64. .output()
  65. .map_err(|e| anyhow!("Failed to run losetup -a: {}", e))?;
  66. let output = String::from_utf8(cmd.stdout)?;
  67. let s = __loop_device_path_by_disk_image_path(
  68. self.img_path.as_ref().unwrap().to_str().unwrap(),
  69. &output,
  70. )
  71. .map_err(|e| anyhow!("Failed to find loop device: {}", e))?;
  72. self.loop_device_path = Some(s);
  73. Ok(())
  74. }
  75. /// 获取指定分区的路径
  76. ///
  77. /// # 参数
  78. ///
  79. /// * `nth` - 分区的编号
  80. ///
  81. /// # 返回值
  82. ///
  83. /// 返回一个 `Result<String>`,包含分区路径的字符串。如果循环设备未附加,则返回错误。
  84. ///
  85. /// # 错误
  86. ///
  87. /// 如果循环设备未附加,则返回 `anyhow!("Loop device not attached")` 错误。
  88. pub fn partition_path(&self, nth: u8) -> Result<PathBuf> {
  89. if !self.attached() {
  90. return Err(anyhow!("Loop device not attached"));
  91. }
  92. let s = format!("{}p{}", self.loop_device_path.as_ref().unwrap(), nth);
  93. let s = PathBuf::from(s);
  94. // 判断路径是否存在
  95. if !s.exists() {
  96. return Err(anyhow!("Partition not exist"));
  97. }
  98. Ok(s)
  99. }
  100. pub fn detach(&mut self) -> Result<()> {
  101. if self.loop_device_path.is_none() {
  102. return Ok(());
  103. }
  104. let loop_device = self.loop_device_path.take().unwrap();
  105. let p = PathBuf::from(&loop_device);
  106. log::trace!(
  107. "Detach loop device: {}, exists: {}",
  108. p.display(),
  109. p.exists()
  110. );
  111. let output = Command::new("losetup")
  112. .arg("-d")
  113. .arg(loop_device)
  114. .output()?;
  115. if output.status.success() {
  116. self.loop_device_path = None;
  117. Ok(())
  118. } else {
  119. Err(anyhow::anyhow!(
  120. "Failed to detach loop device: {}, {}",
  121. output.status,
  122. str::from_utf8(output.stderr.as_slice()).unwrap_or("<Unknown>")
  123. ))
  124. }
  125. }
  126. pub fn try_detach_when_drop(&self) -> bool {
  127. self.try_detach_when_drop
  128. }
  129. #[allow(dead_code)]
  130. pub fn set_try_detach_when_drop(&mut self, try_detach_when_drop: bool) {
  131. self.try_detach_when_drop = try_detach_when_drop;
  132. }
  133. }
  134. impl Drop for LoopDevice {
  135. fn drop(&mut self) {
  136. if self.try_detach_when_drop() {
  137. if let Err(e) = self.detach() {
  138. log::warn!("Failed to detach loop device: {}", e);
  139. }
  140. }
  141. }
  142. }
  143. pub struct LoopDeviceBuilder {
  144. img_path: Option<PathBuf>,
  145. loop_device_path: Option<String>,
  146. try_detach_when_drop: bool,
  147. }
  148. impl LoopDeviceBuilder {
  149. pub fn new() -> Self {
  150. LoopDeviceBuilder {
  151. img_path: None,
  152. loop_device_path: None,
  153. try_detach_when_drop: true,
  154. }
  155. }
  156. pub fn img_path(mut self, img_path: PathBuf) -> Self {
  157. self.img_path = Some(abs_path(&img_path));
  158. self
  159. }
  160. #[allow(dead_code)]
  161. pub fn try_detach_when_drop(mut self, try_detach_when_drop: bool) -> Self {
  162. self.try_detach_when_drop = try_detach_when_drop;
  163. self
  164. }
  165. pub fn build(self) -> Result<LoopDevice> {
  166. let loop_dev = LoopDevice {
  167. img_path: self.img_path,
  168. loop_device_path: self.loop_device_path,
  169. try_detach_when_drop: self.try_detach_when_drop,
  170. };
  171. Ok(loop_dev)
  172. }
  173. }
  174. fn __loop_device_path_by_disk_image_path(
  175. disk_img_path: &str,
  176. losetup_a_output: &str,
  177. ) -> Result<String> {
  178. let re = Regex::new(LOOP_DEVICE_LOSETUP_A_REGEX)?;
  179. for line in losetup_a_output.lines() {
  180. if !line.contains(disk_img_path) {
  181. continue;
  182. }
  183. let caps = re.captures(line);
  184. if caps.is_none() {
  185. continue;
  186. }
  187. let caps = caps.unwrap();
  188. let loop_device = caps.get(1).unwrap().as_str();
  189. let loop_device = format!("/dev/loop{}", loop_device);
  190. return Ok(loop_device);
  191. }
  192. Err(anyhow!("Loop device not found"))
  193. }
  194. #[cfg(test)]
  195. mod tests {
  196. use super::*;
  197. #[test]
  198. fn test_regex_find_loop_device() {
  199. const DEVICE_NAME_SHOULD_MATCH: [&str; 3] =
  200. ["/dev/loop11", "/dev/loop11p1", "/dev/loop11p1 "];
  201. let device_name = "/dev/loop11";
  202. let re = Regex::new(LOOP_DEVICE_LOSETUP_A_REGEX).unwrap();
  203. for name in DEVICE_NAME_SHOULD_MATCH {
  204. assert!(re.find(name).is_some(), "{} should match", name);
  205. assert_eq!(
  206. re.find(name).unwrap().as_str(),
  207. device_name,
  208. "{} should match {}",
  209. name,
  210. device_name
  211. );
  212. }
  213. }
  214. #[test]
  215. fn test_parse_losetup_a_output() {
  216. let losetup_a_output = r#"/dev/loop1: []: (/data/bin/disk-image-x86_64.img)
  217. /dev/loop29: []: (/var/lib/abc.img)
  218. /dev/loop13: []: (/var/lib/snapd/snaps/gtk-common-themes_1535.snap
  219. /dev/loop19: []: (/var/lib/snapd/snaps/gnome-42-2204_172.snap)"#;
  220. let disk_img_path = "/data/bin/disk-image-x86_64.img";
  221. let loop_device_path =
  222. __loop_device_path_by_disk_image_path(disk_img_path, losetup_a_output).unwrap();
  223. assert_eq!(loop_device_path, "/dev/loop1");
  224. }
  225. #[test]
  226. fn test_parse_lsblk_output_not_match() {
  227. let losetup_a_output = r#"/dev/loop1: []: (/data/bin/disk-image-x86_64.img)
  228. /dev/loop29: []: (/var/lib/abc.img)
  229. /dev/loop13: []: (/var/lib/snapd/snaps/gtk-common-themes_1535.snap
  230. /dev/loop19: []: (/var/lib/snapd/snaps/gnome-42-2204_172.snap)"#;
  231. let disk_img_path = "/data/bin/disk-image-riscv64.img";
  232. let loop_device_path =
  233. __loop_device_path_by_disk_image_path(disk_img_path, losetup_a_output);
  234. assert!(
  235. loop_device_path.is_err(),
  236. "should not match any loop device"
  237. );
  238. }
  239. }