我正在使用以下命令为 VM 原始图像备份文件设置循环设备:
sudo losetup /dev/loop0 "/home/asus/VirtualBox VMs/Windows RAW/Windows 10.img"
而且它运行良好。
$ losetup -l
NAME SIZELIMIT OFFSET AUTOCLEAR RO BACK-FILE DIO LOG-SEC
/dev/loop0 0 0 0 0 /home/asus/VirtualBox VMs/Windows RAW/Windows 10.img 0 512
但我想让这个改变永久生效,所以我创建了这个.sevice
在启动时运行的代码:
$ cat /etc/systemd/system/loops-setup.service
[Unit]
Description=Setup loop devices
DefaultDependencies=no
Conflicts=umount.target
Before=local-fs.target
After=systemd-udev-settle.service
Required=systemd-udev-settle.service
[Service]
Type=oneshot
ExecStart=/sbin/losetup /dev/loop0 "/home/asus/VirtualBox VMs/Windows RAW/Windows 10.img"
ExecStop=/sbin/losetup -d /dev/loop0
TimeoutSec=60
RemainAfterExit=yes
[Install]
WantedBy=local-fs.target
Also=systemd-udev-settle.service
此服务也可手动启动:
sudo systemctl start loops-setup
但它在启动时启动失败,并显示此错误:
May 11 19:57:17 ubuntu losetup[308]: losetup: /dev/loop0: failed to set up loop device: No such file or directory
我猜这是因为服务的层次结构,我应该改变Before
和After
选择,但我不知道该怎么做。
提前致谢。
答案1
这个问题是由两个原因造成的:
1.正如@CharlesGreen提到的systemd-udev-settle.service
无法激活:
$ sudo systemctl enable systemd-udev-settle.service
The unit files have no installation config (WantedBy=, RequiredBy=, Also=,
Alias= settings in the [Install] section, and DefaultInstance= for template
units). This means they are not meant to be enabled using systemctl.
Possible reasons for having this kind of units are:
• A unit may be statically enabled by being symlinked from another unit's
.wants/ or .requires/ directory.
• A unit's purpose may be to act as a helper for some other unit which has
a requirement dependency on it.
• A unit may be started when needed via activation (socket, path, timer,
D-Bus, udev, scripted systemctl call, ...).
• In case of template units, the unit is meant to be enabled with some
instance name specified.
因此这项服务保持不活动状态:
$ sudo systemctl status systemd-udev-settle.service
● systemd-udev-settle.service - udev Wait for Complete Device Initialization
Loaded: loaded (/usr/lib/systemd/system/systemd-udev-settle.service; static; vendor preset: disabled)
Active: inactive (dead)
Docs: man:udev(7)
man:systemd-udevd.service(8)
2.第二个问题是losetup
命令需要访问home
分区才能进行设置Windows 10.img
。而这个分区在启动时并没有被挂载。
因此以这种方式更改服务,解决问题:
[Unit]
Description=Setup loop devices
DefaultDependencies=no
Conflicts=umount.target
Before=local-fs.target
After=systemd-udevd.service home.mount
Required=systemd-udevd.service
[Service]
Type=oneshot
ExecStart=/sbin/losetup /dev/loop0 "/home/asus/VirtualBox VMs/Windows RAW/Windows 10.img"
ExecStop=/sbin/losetup -d /dev/loop0
TimeoutSec=60
RemainAfterExit=yes
[Install]
WantedBy=local-fs.target
Also=systemd-udevd.service