How to Allow User to Prioritize Process to Negative Niceness

limitnicenot-root-userprocess

I want a user to run a specific process on the system with a negative nice value.
I can't simply fork the process to background as this specific program is a minecraft server and I rely on the command line to control the server.

My current bash script looks like this (the important part):

sleep 10 && \
sudo renice -n $NICENESS $(ps -u $(id -u) -o "%p:%c" | sed -n "s/:java$//p") & \
java -Xmx8G -Xms2G -jar minecraft_server.jar nogui    

sleep simply delays execution of renice. renice itself uses ps to check for a java process using the users own ID. There might be other instances of java spawning under different users, but the minecraft server runs under its own user minecraft.

I obviously don't want to enter a password every time I start the server.
from /etc/sudoers:

minecraft ALL = NOPASSWD: /etc/renice

Is there a more elegant way to do this? Simply using nice is not an option, sudo nice bash in combination with the NOPASSWD: option would be a great security issue.

Best Answer

The pam_limits.so module can help you there.

It allows you to set certain limits on specific individual users and groups or wildcards or ranges of users and groups.

The limits you can set are typically ulimit settings but also on the number of concurrent login sessions, processes, CPU time, default priority and maximum priority (renice). Check the limits.conf man page for more.

For example you can configure your mindcraft group to have all their processes started with an increased default priority and you can allow them to use the nice and renice commands to increase the priority of their important jobs manually as well instead of only reducing priority.

# /etc/security/limits.conf
# increase default and max prio for members of the mindcraft group
@mindcraft   hard priority -10
@mindcraft   hard nice     -18   
Related Question