systemd / zram-generator

Systemd unit generator for zram devices
MIT License
585 stars 50 forks source link

Can zram-generator be used to create swapfiles ? #182

Closed traylenator closed 1 year ago

traylenator commented 1 year ago

Hi,

A question really.

I was trying to create and use a swapfile using units

Can zram-generator be used or probably misused for this.

The following pair of units do work: newswap.service and newswap.swap

[Unit]
Description='Disk'
Before=newswap.swap
Requires=newswap.swap
ConditionPathExists=!/newswap

[Service]
Type=oneshot
ExecStart=/usr/bin/dd if=/dev/zero of=/newswap bs=1MB count=2014
ExecStart=/usr/bin/chmod 600 /newswap
ExecStart=/usr/sbin/mkswap /newswap

[Install]
WantedBy=local-fs-pre.target

and

[Swap]
What=/newswap

and

systemctl enable newswap.service

results in

 swapon -s | grep -v swapfile | grep -v zram
Filename                                Type            Size            Used            Priority
/newswap                                file            1966792         0               -3

It makes a lot of sense to generate them from a generator, can the existing zram-generator be used for this?

Unfortunately an fstab of

/swapfile /swapfile swap x-systemd.makefs 0  0

is not usable as that generator does not like filepath rather than a device.

nabijaczleweli commented 1 year ago

I don't really see how z-g is relevant here. Just make the swap and configure it?

If you really want to do it with a generator then just... write a generator?

#!/bin/sh
[ -e "/swapfile" ] || (
  umask 66
  fallocate -xl 2014M "/swapfile" && mkswap "/swapfile"
) || rm -f "/swapfile"
[ -e "/swapfile" ] && {
  u="$(systemd-escape -p "/swapfile")"
  printf '[Swap]\nWhat=%s\n' "/swapfile" > "$1/$u.swap" && mkdir -p "$1/swap.target.requires" && ln -sf "../$u.swap" "$1/swap.target.requires"
}

iterate that over a file and s;/swapfile;$f;g and s;2014M;"$s"; and it's configurable, so long as the path you're targeting is on ext4 or XFS (or NFS?) or you set nocow on it for btrfs.