Wednesday, March 9, 2022

How to Limit Firefox/Google Chrome CPU and RAM

Google Chrome and Firefox web browsers make extensive use of Memory and CPU utilization when multiple tabs are opened. We can limit the CPU and RAM for those browser, or other application by using systemd.

Using systemd’s transient scope units one can allocate a certain amount of memory and CPU shares to Firefox and chrome web-browser applications. systemd’s transient Units are only allowed for a super user(root) hence the need is to first allow the user or group that wants this feature.

Add the following polkit rule in /etc/polkit-1/rules.d/60-systemd-manage.rules file. The following rule makes sure that the user ‘test’ is allowed to start systdmd Units. Change the username of your choice.
polkit.addRule(function(action, subject) {
    if (action.id == "org.freedesktop.systemd1.manage-units" &&
        subject.user == "test") {
            return polkit.Result.YES;
    }
});
Alternatively, a group of users can be granted the same privileges through the same rule with just a little modification. Make sure the user is part of the ‘admin’ group.
polkit.addRule(function(action, subject) {
    if (action.id == "org.freedesktop.systemd1.manage-units" &&
        subject.isInGroup("admin")) {
            return polkit.Result.YES;
    }
});
Now login to the test user account and validate if the user can start and stop systemd services.
$ systemctl restart sshd
  [test@localhost ~]$ systemd-run --scope sleep 30
    Running scope as unit run-2845.scope.
Now modify the Gnome Launcher file of firefox or chrome from /usr/share/applications directory. Modify the Exec parameter as below to set 5G Memory limit and give 200 CPU cycles limit for to firefox and chrome. Generally 1024 CPU cycles is equivalent to 1 CPU. Giving 2048 CPU cycles would allow chrome and Firefox to use two CPUs if required.

Firefox: /usr/share/applications/firefox.desktop
From:
Exec=/home/test/firefox/firefox %u

To:
Exec=systemd-run --scope -p CPUShares=200 -p MemoryLimit=5G /home/test/firefox/firefox %u
Chrome: /usr/share/applications/google-chrome.desktop From:
#Exec=/usr/bin/google-chrome-stable %U
To:
Exec=systemd-run --scope -p CPUShares=200 -p MemoryLimit=5G /usr/bin/google-chrome-stable %U
Exec=systemd-run --scope -p CPUShares=200 -p MemoryLimit=5G /usr/bin/google-chrome-stable
Exec=systemd-run --scope -p CPUShares=200 -p MemoryLimit=5G /usr/bin/google-chrome-stable --incognito
Now logout from the desktop session and then re-login to validate the feature.

0 comments:

Post a Comment