#!/bin/bash if [ "$UID" != 0 ] then sudo -- "$0" "$@" exit fi while [ $# -gt 0 ] do case "$1" in -q | --quiet ) exec 2>/dev/null shift ;; -a | --all ) IOSLAY_KILL_ALL=y shift ;; -- ) shift break ;; -* ) exit 1 ;; * ) break ;; esac done if [ $# -gt 0 ] then echo "$0: Error: usage" >&2 exit 1 fi web_content_pids() { top -w512 -b -o '%MEM' | { unset PIDS while read line do case "$line" in top*) if [ "${PIDS+is_set}" ] then echo $PIDS fi while [ "$line" ] do read line done PIDS= ;; *) set -- $line [ "${12} ${13}" = "Web Content" ] || continue PIDS="$PIDS $1" ;; esac done } } sum() { local total=0 n for n in $* do total=$((total + n)) done echo $total } keep() { local n=$1 shift set -- $* while [ $# -ge "$n" ] do shift done printf '%s\n' "$*" } new_pids() { # This is not correct because the correct code is not implemented yet. # But this is OK for testing the other parts. Fixing this is only an # optimization. [ "$1" != "$2" ] } unset IOTOP_PID relaunch_iotop() { if [ "$IOTOP_PID" ] then kill "$IOTOP_PID" fi web_content_pids | ( while read pids do set -- $pids if [ $# = 0 ] then kill_iotop elif new_pids "$pids" "$oldpids" then kill_iotop IOTOP_PID=$(launch_iotop $pids) fi sleep 1 oldpids=$pids done ) } kill_iotop() { if [ "$IOTOP_PID" ] then ( set -x kill "$IOTOP_PID" ) fi } launch_iotop() { set -- $(printf '%s\n' "$@" | tac | sed 's/^/--pid=/') (set -x; iotop -qq -b "$@") | iotop_reader & echo $! } iotop_reader() { log= pct_log= while read line do case "$line" in "Total DISK"*) pct=$(sum $pct_log) [ "$pct" -ge 85 ] && over=y || over= pct_log= log=$(keep 9 $log) if [ "$over" ] then log="$log 1" over= if [ "$(sum $log)" -ge 3 ] then ( set -x fireslay -y ) fi else log="$log 0" fi case "$log" in *1* ) ( set -x : $log ) ;; esac ;; "Current DISK"*) continue ;; *) set -- $line pct=${10%.*} pct_log="$pct_log $pct" ;; esac done } relaunch_iotop