Thursday, 19 May 2016

Raspberry Pi Media Centre

I have a love-hate relationship with our Raspberry Pi based Kodi Media Centre. On one hand it's cheap as chips and streams all the TV shows we could want (while not being a television) but on the other it's prone to regular heart-attacks when its SD card has been written too much.

I have been in the habit of backing it up religiously every month and have been rewarded by its dying every six months or so. Time to hack some Linux!

(It goes without saying that what follows is merely an optimization of the excellent work done by Sam Nazarko on Raspbmc, now OSMC.)

First thing is to disable Kodi logging entirely. Do this by creating a file /home/pi/.kodi/userdata/advancedsettings.xml:


Second of all: tmpfs. First we connect the various other temporary directories to /tmp:
$ sudo rm -rf /var/tmp
$ sudo ln -s /tmp /var/tmp
$ rm -rf /home/pi/.kodi/temp
$ ln -s /tmp /home/pi/.kodi/temp

Next we overlay a couple of tmpfs filesystems over /tmp and /var/log (where all of the system daemons write their logfiles). Add the following lines to the end of /etc/fstab:

tmpfs           /tmp            tmpfs   defaults,noatime,nosuid,size=50m    0   0
tmpfs           /var/log        tmpfs   defaults,noatime,nosuid,size=50m    0   0

This creates a couple of ram-disks each limited to 50MB in size. They won't use this RAM unless it's required and if it fills up (it hasn't for me yet) a reboot will start again from scratch.

Useful tools for monitoring disk usage are iostat and fuser (the latter is in the psmisc package). Another is the humble find, for example to see all files modifed within the last day:

$ find /home -mtime 0       

Hmmm, looks like there's still some work to do here! Let's move the thumbnails to /tmp too:


Now that thumbnails are being stored in /tmp, we need to clear them out every so often to avoid filling it up. Add this line to your crontab, with "crontab -e":

0 5 * * mon find /tmp/Thumbnails -type f | xargs rm -f

This will remove all thumbnails every Monday at 5am.

Update: Hackaday just ran a story on Preventing Flash Memory Corruption containing many useful tips; the most relevant one not covered here is filesystem commit interval. By mounting the root filesystem as follows (/etc/fstab again), Linux will flush its buffers to the SD card every 5 minutes instead of every 5 seconds by default:

/dev/mmcblk0p2  /               ext4    defaults,noatime,commit=300 0       0

This is a quick win because frankly who cares if a write recording the fact you watched an episode of Futurama is lost for a potential 60x reduction in the number of writes? Not me!