bashcpusnmpsnmp-trap

Limit execution number of bash script triggered by snmp trap


When a trap arrives to my system I execute a bash script automatically. Problem is sometimes a lot of traps arrive simultaneously making a lot executions of the script and generating system cpu pikes Do you know how could avoid that situation? I thought some mechanism that only executes a determined scripts and the rest waiting like a FIFO queue but I don’t know if that is possible

Thanks


Solution

  • It is a possible solution that would prevent multiple executions of a script at the same time.

    First, you would define a fifo:

    mkfifo /some/directory/fifo
    

    Then, you would create a script that reads the fifo:

    #!/bin/bash
    tail -f /some/directory/fifo | while read line ; do
        process "$line"
    done
    

    When a trap arrives, you execute the following script:

    #!/bin/bash
    echo "something from the trap" > /some/directory/fifo
    

    The script that posts the message on the fifo is lightweight and would therefore produce less of a spike than the whole processing. The processing is now serialized, so only one processing script runs at a given time. You can also nice the processing to give it even less impact.

    The echo should be atomic enough to prevent interleaved lines most of the time.

    Another option is to use a lock to prevent multiple copies to execute at the same time. That would look like:

    #!/bin/bash
    me=$$
    echo $me>>lockfile
    lockedby=$(head -1 lockfile)
    while [ "$me" != "$lockedby" ] ; do
        sleep 1
        echo $me>>lockfile
        lockedby=$(head -1 lockfile)
    done
    
    process the trap
    
    rm -f lockfile