#!/usr/bin/env cbsd
#v11.2.1
CBSDMODULE="bhyve"
CIXARG="jname"
CIXOPTARG="nice"
MYDESC="Re-nice bhyve processes on-the-fly"
ADDHELP="
${H3_COLOR}Description${N0_COLOR}:

 Set or reset the nice value for a running bhyve domain process.
 If nice= is omitted, values are read from the RCTL database.

${H3_COLOR}Options${N0_COLOR}:

 ${N2_COLOR}jname=${N0_COLOR} - target bhyve domain name;
 ${N2_COLOR}nice=${N0_COLOR}  - new nice value (integer); skip to apply from RCTL database;

${H3_COLOR}Examples${N0_COLOR}:

 # cbsd brenice jname=vm1 nice=5
 # cbsd brenice jname=vm1

${H3_COLOR}See also${N0_COLOR}:

  cbsd bstart --help
  cbsd bstop --help
  cbsd bset --help

"

. ${subrdir}/nc.subr
. ${tools}
. ${strings}

cixinit

emulator="bhyve" # for jname_is_multiple
jname_is_multiple

if [ -n "${jail_list}" ]; then
	TMP_JLIST="${jail_list}"
else
	TMP_JLIST=$*
fi

JLIST=

# check for actual vm list in arg list
jail_num=0
for i in ${TMP_JLIST}; do
	capture exist cbsdsqlro local "SELECT jname FROM jails WHERE jname='${i}' AND emulator='${emulator}' LIMIT 1"
	if [ -n "${exist}" ]; then
		JLIST="${exist} ${JLIST}"
		jail_num=$(( jail_num + 1 ))
	fi
done

# this is multiple list, split it by parallel bstop execution
if [ ${jail_num} -gt 1 ]; then
	cbsdlogger NOTICE ${CIX_APP}: executing for multiple brenice: ${JLIST}
	new_arg=

	for i in $*; do
		capture _is_jname substr --pos=0 --len=5 --str=${i}
		[ "${_is_jname}" = "jname" ] && continue
		new_arg="${new_arg} ${i}"
	done

	for jname in ${JLIST}; do
		brenice jname=${jname} ${new_arg}
	done
	exit 0
fi

[ -z "${jname}" ] && capture jname ${AWK_CMD} '{printf $1}' <<< "${JLIST}"
[ -z "${jname}" ] && jname="${1}"
[ -z "${jname}" ] && err 1 "${N1_COLOR}Give me domain name${N0_COLOR}"

. ${distsharedir}/bhyve.conf		# only for for MYCOL variables: used in exports below

. ${subrdir}/rcconf.subr
if [ $? -eq 1 ]; then
	[ ${sqlreplica} -eq 0 ] && err 1 "${N1_COLOR}No such domain: ${N2_COLOR}${jname}${N0_COLOR}"
	remotenode=$( bwhereis ${jname} )
	[ -z "${remotenode}" ] && err 1 "${N1_COLOR}No such domain: ${N2_COLOR}${jname}${N0_COLOR}"
	for i in ${remotenode}; do
		${ECHO} "${N1_COLOR}Remote bstop: ${N2_COLOR}${jname} ${N1_COLOR}on${N2_COLOR} ${i}${N0_COLOR}"
		rexe node=${i} cbsd bstop jname=${jname}
		if [ $? -eq 0 ]; then
			# update inventory
			${ECHO} "${N1_COLOR}Updating inventory...${N0_COLOR}"
			task autoflush=2 mode=new cbsd retrinv node=${i} tryoffline=1 data=db > /dev/null 2>&1
		fi
	done
	exit 0
fi

. ${subrdir}/rcconf.subr
[ "${emulator}" != "bhyve" ] && log_err 1 "${N1_COLOR}Not in bhyve emulator: ${N2_COLOR}${emulator}${N0_COLOR}"
[ ${jid} -eq 0 ] && exit 0

if [ -z "${nice}" ]; then
	_formfile="${jailsysdir}/${jname}/helpers/brctl.sqlite"
	[ -r "${_formfile}" ] && capture nice cbsdsqlro "${_formfile}" "SELECT cur FROM forms WHERE param='nice'"
	# just reset
	[ -z "${nice}" ] && nice="0"
fi

search_cmd="bhyve: ${jname}"
capture strlen_search_cmd strlen "${search_cmd}"

vm_pid=
pid_count=

capture _ps_output /bin/ps axopid,state,ucomm,command -ww

while read _ps_line; do
	[ -z "${_ps_line}" ] && continue

	# fast filter: skip lines without "bhyve"
	case "${_ps_line}" in *bhyve*) ;; *) continue ;; esac

	# parse pid, state, ucomm, command
	# awk: $1=pid, $2=state, $3=ucomm, $4..$NF=command
	capture _pf ${AWK_CMD} '{cmd=""; for(i=4;i<=NF;i++) cmd=cmd (i>4?" ":"") $i; print $1,$2,$3,cmd}' <<< "${_ps_line}"
	read _ps_pid _ps_state _ps_ucomm _ps_cmd <<< "${_pf}"

	[ "${_ps_ucomm}" != "bhyve" ] && continue

	b_jname=$( echo "${_ps_cmd}" | ${AWK_CMD} '/bhyve: /{print $2}' )

	[ "${b_jname}" != "${jname}" ] && continue

	pid_count=$(( pid_count + 1 ))

	# skip stopped (T) processes
	case "${_ps_state}" in *T*) pid_count=$(( pid_count - 1 )) ;; esac

	cmd_pref=$( substr --pos=0 --len=${strlen_search_cmd} --str="${_ps_cmd}" )

	if [ "${cmd_pref}" = "${search_cmd}" ]; then
		vm_pid="${_ps_pid}"
		break
	fi

	case "${_ps_cmd}" in *" ${jname}"*) vm_pid="${_ps_pid}"; break ;; esac

done <<< "${_ps_output}"

if [ -z "${vm_pid}" -o "${vm_pid}" = "0" ]; then
	cbsdlogger WARNING ${CIX_APP}: unable to determine pid for: ${jname}
	log_err 1 "${N1_COLOR}Unable to determine pid for: ${N2_COLOR}${jname}${N0_COLOR}"
fi

if [ -z "${pid_count}" ]; then
	cbsdlogger WARNING ${CIX_APP}: unable to determine pid_count for: ${jname}
	log_err 1 "${N1_COLOR}Unable to determine pid_count for: ${N2_COLOR}${jname}${N0_COLOR}"
fi

cbsdlogger NOTICE ${CIX_APP}: re-nice ${nice} to bhyve ${jname} pid: ${vm_pid}
/usr/bin/renice ${nice} -p ${vm_pid}
