Configure cachefilesd to use system memory in CentOS 7

After configuring cachefilesd service on a few hosts that were using NFS heavily I realized it was hitting the internal drives pretty hard. To help alleviate the load on the internal drives and the storage array I looked for a way to place the cachefilesd cache in memory. A bit of reading and testing I realized that cachefilesd doesn’t support tmpfs file systems. I finally settled on the following method:

First define the cache-creator service:

cat << EOF > /etc/systemd/system/cache-creator.service 
[Unit]
Description=Cache creator
Before=cachefilesd.service

[Service]
EnvironmentFile=/etc/sysconfig/cache-creator
ExecStartPre=/bin/bash -c "if [ ! -d /var/cache/tmpfs ]; then mkdir /var/cache/tmpfs; fi"
ExecStartPre=/bin/bash -c "mount -t tmpfs -o size=\${CACHESIZEMB}M tmpfs /var/cache/tmpfs"
ExecStartPre=/bin/bash -c "dd if=/dev/zero of=/var/cache/tmpfs/disk0 bs=1M count=\${CACHESIZEMB}"
ExecStartPre=/bin/bash -c "mkfs.xfs /var/cache/tmpfs/disk0"
ExecStart=/bin/bash -c "mount -t xfs /var/cache/tmpfs/disk0 /var/cache/fscache"
Restart=no
Type=oneshot

[Install]
WantedBy=multi-user.target
EOF

Then create the cache-creator service environment file:

cat << EOF > /etc/sysconfig/cache-creator
# Set a specific MB value for in mem cache size 
#CACHESIZEMB=5120
# Or just just half of the system memory for example
CACHESIZEMB=\`grep MemTotal /proc/meminfo | awk '{print int((\$2/1024)/2)}'\`
EOF

Then I chose to increase the cachefilesd settings since it will have its’ own file system:

if [ -f /etc/cachefilesd.conf.bak ]; then rm /etc/cachefilesd.conf.bak; fi
cp /etc/cachefilesd.conf /etc/cachefilesd.conf.bak
sed -i 's/brun .*/brun 20%/' /etc/cachefilesd.conf
sed -i 's/bcull .*/bcull 10%/' /etc/cachefilesd.conf
sed -i 's/bstop .*/bstop 5%/' /etc/cachefilesd.conf
sed -i 's/frun .*/frun 20%/' /etc/cachefilesd.conf
sed -i 's/fcull .*/fcull 10%/' /etc/cachefilesd.conf
sed -i 's/fstop .*/fstop 5%/' /etc/cachefilesd.conf

Now enable both services:

systemctl enable cache-creator
systemctl enable cachefilesd

Shutdown the host and add the required memory for the cache. After restarting you should have your new in-memory cache mounted at /var/cache/fscache.

You may also like...