1

I have a closed source app that needs a low nice level (high priority), when clients are connected to be responsive, and when no clients are connected, it runs maintenance tasks, which I want run with a high nice level (low priority).

Is there some iptables or similar mechanism to trigger a script to be run when a connection is established on a specific port, and when all connections are closed?

The app is listening on UDP ports which is probably going to complicate things.

1
  • Is running a proxy for all of those UDP ports (you didn't gave a count) an option?
    – dirkt
    Nov 3, 2019 at 7:28

1 Answer 1

0

I did some more digging and discovered the ss command has a few useful features:

-E gives us an event stream, but seems to only be useful with TCP connections. We can count established and closed connections, but nothing is printed with udp connections.

But we can check the Recv-Q values when using ss -una state all '( sport = :<port> )'

If it stays 0 for long enough we can deprioritize the process, and if it's larger than zero we can prioritize the process.

I ended up writing a script:

#!/bin/bash

state=idle
count=0
fstate=idle
ramptime=3
pid=$1
port=$2

while true; do
        while [ $count -lt $ramptime ]; do
                sleep 1
                activity=$(ss -unHa state all '( sport = :'$port' )' | awk '{ print $2 };')
                if [ $activity -eq 0 ]; then
                        fstate=idle
                else
                        fstate=active
                fi
                if [ $fstate = $state ]; then
                        count=0
                else
                        count=$((count+1))
                fi
                #echo $activity $count $state $fstate

        done
        count=0
        state=$fstate
        case $state in
                idle)
                        ramptime=3
                        schedtool -D $pid
                        renice 20 -p $pid
                        ionice -c 3 -p $pid
                ;;
                active)
                        ramptime=30
                        schedtool -R -p 1 $pid
                        renice -10 -p $pid
                        ionice -c 2 -p $pid
        esac
done

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .