#! /usr/bin/env perl
use strict;
use warnings;
my $systemd = -f '/usr/bin/systemctl';
my ($niceness, $iolimit);
set_niceness(5);

die "Lennart Poettering hates all good things.\n" if $systemd;

if (@ARGV > 1 && $ARGV[0] eq '--') { ionice(@ARGV[1..$#ARGV]); exit }
elsif (@ARGV > 1 && $ARGV[0] =~ /^-(\d+)$/) {
    set_niceness($1);
    shift(@ARGV);
    if (@ARGV > 1 && $ARGV[0] eq '-p') { ionice_pids(@ARGV[1..$#ARGV]); exit }
    elsif (@ARGV > 1 && $ARGV[0] eq '--') { ionice(@ARGV[1..$#ARGV]); exit }
    elsif ($ARGV[0] && $ARGV[0] =~ /^-/) { usage("invalid flag: $ARGV[0]") }
    else { ionice(@ARGV); exit }
}
elsif (@ARGV > 1 && $ARGV[0] eq '-p') { ionice_pids(@ARGV[1..$#ARGV]); exit }
elsif (@ARGV == 1 && $ARGV[0] eq '-l') { list_ionice(); exit }
elsif (@ARGV > 1 && $ARGV[0] eq '-r') { remove_ionice(@ARGV[1..$#ARGV]); exit }
elsif (@ARGV > 0 && $ARGV[0] !~ /^-/) { ionice(@ARGV); exit }
else { usage() }
die "this point shouldn't be reached :(";

sub ionice_pids {
    my @pids = @_;
    check_pids(@pids);
    setup_cgroups();
    slowit($_) for @pids;
}

sub ionice {
    my @cmd = @_;
    setup_cgroups();
    slowit($$);
    exec { $cmd[0] } @cmd
}

sub list_ionice {
    for my $n (0..9) {
        open my $f, '<', "/sys/fs/cgroup/ionice-$n/tasks" or next;
        while (defined(my $pid = <$f>)) {
            chomp $pid;
            print "$pid (niceness: $n)\n";
        }
        close $f;
    }
}

sub remove_ionice {
    my @pids = @_;
    check_pids(@pids);
    
    # special file: deliberately reopening it
    for (@pids) {
        open my $f, '>', '/sys/fs/cgroup/tasks'
            or die "Failed to open /sys/fs/cgroup/tasks for writing : $!";
        print {$f} "$_\n";
        close $f or die "Failed to write to /sys/fs/cgroup/tasks : $!";
    }
}

sub check_pids {
    my @pids = @_;
    my $invalid;
    for (@pids) { if (!/^\d+$/) { warn "[!] invalid pid: $_\n"; $invalid++ } }
    usage() if $invalid;
}

sub usage {
    my ($msg) = @_;
    if (defined $msg) {
        warn "[!] $msg\n\n";
    }
    die <<USAGE;
usage: $0 [-<num>] command   # run 'command' with niceness of num (default 5)
usage: $0 -l                 # list nice'd processes
usage: $0 [-<num>] -p <pid> [<pid> ...]  # (re)limit existing processes
usage: $0 -r <pid> [<pid> ...]           # remove ionice limits from processes

nice values can be an integer within [0,10)
higher values are subtracted from 10 to calculate a limit on read/written MB/s
f.e., by default (niceness of 5) an ionice'd process is limited to 5MB/s

examples:

$0 mkfs.ext4 /mnt/sdX
$0 -l
$0 -7 -p 4111
USAGE
}

sub get_io_devices {
    my @devices;
    open my $f, '<', '/sys/fs/cgroup/blkio.throttle.io_serviced'
        or die "Failed to open /sys/fs/cgroup/blkio.throttle.io_serviced for reading : $!";
    while (defined(my $line = <$f>)) {
        if ($line =~ /^(\d+:\d+)\s+Read/) {
            push @devices, $1
        }
    }
    close $f;
    @devices
}

sub set_niceness {
    my ($n) = @_;
    $niceness = $n;
    if ($n =~ /^\d+(\.\d*)?$/) {
        die "fractional niceness not supported 'cause it'd pollute cgroups" if $1;
        if ($n >= 10 || $n < 0)  {
            warn "[!] niceness of $n is out of bounds\n\n";
            usage();
        }
        $iolimit = (10 - $n) * 1024 * 1024
    }
    elsif ($n =~ /^(\d+(?:\.\d*)?)MB$/) {
        die "##MB niceness not supported 'cause it'd pollute cgroups";
        $iolimit = $n * 1024 * 1024
    }
    else {
        warn "[!] didn't understand niceness of $n\n\n";
        usage();
    }
}

sub setup_cgroups {
    mkdir "/sys/fs/cgroup/ionice-$niceness";

    # special file: deliberately reopening it
    for (get_io_devices()) {
        open my $f, '>', "/sys/fs/cgroup/ionice-$niceness/blkio.throttle.read_bps_device"
            or die "Failed to open /sys/fs/cgroup/ionice-$niceness/blkio.throttle.read_bps_device for writing : $!";
        print {$f} "$_ ", $iolimit, "\n";
        close $f or die "Failed to write to /sys/fs/cgroup/ionice-$niceness/blkio.throttle.read_bps_device : $!";
        open $f, '>', "/sys/fs/cgroup/ionice-$niceness/blkio.throttle.write_bps_device"
            or die "Failed to open /sys/fs/cgroup/ionice-$niceness/blkio.throttle.write_bps_device for writing : $!";
        print {$f} "$_ ", $iolimit, "\n";
        close $f or die "Failed to write to /sys/fs/cgroup/ionice-$niceness/blkio.throttle.write_bps_device : $!";
    }
}

sub slowit {
    my ($pid) = @_;

    # special file: deliberately reopening it
    open my $f, '>', "/sys/fs/cgroup/ionice-$niceness/tasks"
        or die "Failed to open /sys/fs/cgroup/ionice-$niceness/tasks for writing : $!";
    print {$f} "$pid\n";
    close $f or die "Failed to write to /sys/fs/cgroup/ionice-$niceness/tasks : $!";
}