Monitor Plasmashell memory leak and warn with notification

April 23, 2023 - Reading time: 3 minutes

Plasmashell has been acting weirdly since a couple updates for me, and I noticed that it is the Plasmashell process which, after a specific condition that I did not find yet, starts having some kind of memory leak. I made a script to check its memory usage, and added a Cron job to execute the script periodically.

//EDIT from the future, I found the issue, when I disable the secondary monitor in Nvidia Settings, the memory leak starts, issue reported here and should be fixed soon.

The script here sends a notification and warns about the memory usage of Plasmashell process if it is above specific threshold. As in normal condition it uses less than 5% of my system memory, I set the lowest threshold to 5% before the warnings start:

#!/bin/bash
# crontab job every 10 minutes
# */10 * * * * XDG_RUNTIME_DIR=/run/user/$(id -u) /home/omano/Scripts/plasmashellMonitor.sh
#
mylog="/home/omano/plasmashellMonitor.log"
pidplasma=$(pidof plasmashell)
memplasma=$(ps -p "$pidplasma" -o %mem --no-header)
cpuplasma=$(ps -p "$pidplasma" -o %cpu --no-header)
printf -v memrounded "%.0f" "$memplasma"

# logging reboots
if [ "$(cat /proc/uptime | awk '{print $1}' | xargs printf '%.0f')" -lt 650 ]; then
    echo -e "\n\n__________ REBOOT __________\n\n" >> $mylog
fi

# monitoring logs
echo -e "$(date)\nPlasmashell PID: $pidplasma\nPlasmashell RAM: $memplasma%\nPlasmashell CPU: $cpuplasma%\n$(DISPLAY=:0 inxi -aG -c 0 | grep Monitor-2 | sed 's/^[ \t]*//')\n" >> $mylog

# desktop notification
if [ "$memrounded" -gt 30 ]; then
    notify-send -i state-warning -a "Attention" -u critical "Plasma utilise trop de mémoire et va faire crasher le système! Il faut redémarrer absolument!"
elif [ "$memrounded" -gt 20 ]; then
    notify-send -i state-warning -a "Attention" -u critical "Plasma vient de dépasser 20% d'utilisation mémoire! Redémarrage recommandé pour régler la fuite de mémoire!"
elif [ "$memrounded" -gt 10 ]; then
    notify-send -i state-warning -a "Attention" -u normal "Plasma vient de dépasser 10% d'utilisation mémoire! Fuite de mémoire probable en cours!"
elif [ "$memrounded" -gt 5 ]; then
    notify-send -i state-warning -a "Attention" -u low "Plasma vient de dépasser 5% d'utilisation mémoire!"
fi

I then created a user Cron job from terminal with "crontab -e" command, but for the notification to land into my user desktop session, I need to set the XDG_RUNTIME_DIR before the command, or else the notification lands into the void:

# Check plasmashell memory leak and monitor it
# cron job every 10 minutes
*/10 * * * * XDG_RUNTIME_DIR=/run/user/$(id -u) /home/omano/Scripts/plasmashellMonitor.sh

Every 10 minutes the Cron job is executed, and the script checks the memory usage of Plasmashell, and a notification pops up on my desktop when a specific condition is reached. For now at least it warns me when needed and I can reboot before running out of memory.