#!/bin/sh
# SPDX-License-Identifier: BSD-2-Clause
# SPDX-FileCopyrightText: 2016 ramdaron (https://github.com/ramdaron)
# SPDX-FileCopyrightText: 2016 Matt Churchyard <churchers@gmail.com>

# set limits to virtual machine
# this is the background process
#
rctl::set(){
    local _pcpu _rbps _wbps _riops _wiops
    local _pid _pri

    # get limit settings
    config::get "_pri" "priority"
    config::get "_pcpu" "limit_pcpu"
    config::get "_rbps" "limit_rbps"
    config::get "_wbps" "limit_wbps"
    config::get "_riops" "limit_riops"
    config::get "_wiops" "limit_wiops"

    # wait till bhyve starts and get pid
    sleep 1
    _pid=$(pgrep -fx "bhyve[: ].* ${_name}")
    [ -z "${_pid}" ] && return 1

    # check for a priority
    [ -n "${_pri}" ] && renice ${_pri} ${_pid} >/dev/null 2>&1

    # return if there are no limits
    [ -z "${_pcpu}${_rbps}${_wbps}${_riops}${_wiops}" ] && return 1

    # see if rctl works
    /usr/bin/rctl >/dev/null 2>&1
    [ $? -ne 0 ] && \
        util::log "guest" "${_name}" "RCTL support requested but RCTL not available" && return 1

    util::log "guest" "${_name}" "applying rctl limits"

    if [ -n "${_pcpu}" ]; then
        /usr/bin/rctl -a process:${_pid}:pcpu:deny=${_pcpu} >/dev/null 2>&1
        [ $? -eq 0 ] && util::log "guest" "${_name}" " pcpu=${_pcpu}"
    fi

    # at this point we can return if < FreeBSD 11
    [ ${VERSION_BSD} -lt 1100000 ] && return 0

    if [ -n "${_rbps}" ]; then
        /usr/bin/rctl -a process:${_pid}:readbps:throttle=${_rbps} >/dev/null 2>&1
        [ $? -eq 0 ] && util::log "guest" " readbps=${_rbps}"
    fi

    if [ -n "${_wbps}" ]; then
        /usr/bin/rctl -a process:${_pid}:writebps:throttle=${_wbps} >/dev/null 2>&1
        [ $? -eq 0 ] && util::log "guest" " writebps=${_wbps}"
    fi

    if [ -n "${_riops}" ]; then
        /usr/bin/rctl -a process:${_pid}:readiops:throttle=${_riops} >/dev/null 2>&1
        [ $? -eq 0 ] && util::log "guest" " readiops=${_riops}"
    fi

    if [ -n "${_wiops}" ]; then
        /usr/bin/rctl -a process:${_pid}:writeiops:throttle=${_wiops} >/dev/null 2>&1
        [ $? -eq 0 ] && util::log "guest" " writeiops=${_wiops}"
    fi
}
