Resource Usage¶
posit-usage¶
Reports the CPU, memory, processes, and disk that each Posit service uses on one host. Posit sizes each product separately and recommends a dedicated server for each.123 A host that runs all three needs a way to see which product is using what. This script gives that view without root.
The numbers come from systemd. Each service runs in its own control group (cgroup), and systemd tracks the memory, CPU time, and tasks of every process in it.4 The script reads these values for rstudio-server, rstudio-launcher, rstudio-connect, and rstudio-pm. It samples CPU twice, a few seconds apart, and reports the difference as cores used.
For each service, the report shows:
| Field | Source | What it means |
|---|---|---|
| Memory (cgroup) | MemoryCurrent |
All memory charged to the service, including file cache |
| CPU (cores used) | CPUUsageNSec, sampled twice |
1.00 means one core was busy for the whole interval |
| Tasks | TasksCurrent |
Threads in the service |
| Processes | /proc/PID/cgroup and ps |
Process count, number of users, and the five largest by resident memory |
The resident memory sum counts shared pages once per process, so it can be higher than the cgroup figure. The report also counts rsession processes across the whole host and shows free space for each data directory, /home, and the logs.
Install and run¶
The script loads its helper functions from posit-lib.sh, which must be in the same directory. Copy the source of posit-lib.sh and of posit-usage (below), and paste each into a new file:
cat waits for input. Paste the source, press Enter, then press Ctrl+D to save the file. Do the same for posit-usage:
Then set the modes. posit-lib.sh is sourced, not run, so 0644 is enough:
Without posit-lib.sh, the script exits. Then run the report:
The default sample is 5 seconds. A longer interval smooths out short spikes:
Collect reports over time¶
One report is a snapshot. To compare it with Posit's sizing guidance, collect reports during busy hours, for example every 15 minutes from cron. Each run writes its own file, named with a UTC timestamp. Create the directory once with mkdir -p ~/posit-usage, then add this line with crontab -e:
*/15 8-18 * * 1-5 $HOME/.local/bin/posit-usage --interval 30 > $HOME/posit-usage/$(date -u +\%Y\%m\%dT\%H\%M\%SZ)_posit-usage_$(hostname -s).txt 2>&1
Running without root¶
The script does not need sudo. It reads only what any user can see: systemctl show, ps, /proc, and df. Three checks can still need root:
- Directory sizes: the size of each data directory,
/home, and the logs needssudo du -sh, so the script defers it. - Processes: if
/procis mounted withhidepid, other users' processes are hidden, and the script defers the process breakdown. - Data directories: if you cannot read the Connect or Package Manager configuration file, the script uses the default
DataDirpaths.
Deferred checks are printed just before the report's footer, as commands for your sudo administrator. A service shows "not tracked" when systemd's CPU or memory accounting is turned off for it.
Source: scripts/posit-usage
#!/bin/bash
#
# posit-usage: CPU, memory, processes, and disk used by each Posit service,
# without root.
#
# Reads systemd's accounting for each service unit, which includes the
# sessions and content processes the unit starts. CPU is sampled over an
# interval. Processes are matched to units through /proc/PID/cgroup. Checks
# that need root are printed at the end as commands for the sudo
# administrator.
#
# Usage: posit-usage [--interval SECONDS]
#
# Report scripts keep going when one check fails, so -e is not set
set -uo pipefail
# shellcheck source=posit-lib.sh
. "$(dirname "$(readlink -f "$0")")/posit-lib.sh" || exit 1
readonly UNITS=(rstudio-server rstudio-launcher rstudio-connect rstudio-pm)
readonly DEFAULT_CONNECT_CONF='/etc/rstudio-connect/rstudio-connect.gcfg'
readonly CONNECT_CONF="${POSIT_CONNECT_CONF:-${DEFAULT_CONNECT_CONF}}"
readonly PM_CONF="${POSIT_PM_CONF:-/etc/rstudio-pm/rstudio-pm.gcfg}"
#######################################
# Print a systemd property of a service unit.
# Arguments:
# Unit name, property.
# Outputs:
# The value, or an empty line if systemd does not track it.
#######################################
unit_prop() {
local v
v="$(systemctl show -p "$2" --value "$1.service" 2>/dev/null)"
# systemd prints [not set] or the largest 64 bit value when accounting is off
case "${v}" in
''|*[!0-9]*|18446744073709551615) echo "" ;;
*) echo "${v}" ;;
esac
}
#######################################
# Print a size in KiB as MiB or GiB.
# Arguments:
# Size in KiB.
#######################################
human() {
awk -v k="$1" 'BEGIN {
if (k >= 1048576) printf "%.1f GiB", k / 1048576
else printf "%.0f MiB", k / 1024
}'
}
#######################################
# Print every visible process that runs inside a systemd service.
# The service comes from /proc/PID/cgroup (cgroup v1 or v2).
# Outputs:
# "UNIT USER PID RSS COMMAND" lines.
#######################################
service_procs() {
ps -eo pid=,user=,rss=,comm= 2>/dev/null | awk '
FILENAME != "-" {
if (match($0, /system\.slice\/[^\/]+\.service/)) {
split(FILENAME, p, "/")
if (!(p[3] in unit)) unit[p[3]] = substr($0, RSTART + 13, RLENGTH - 21)
}
next
}
($1 in unit) { print unit[$1], $2, $1, $3, $4 }
' /proc/[0-9]*/cgroup - 2>/dev/null
}
#######################################
# Print the CPU used by a unit over the sample interval.
# Arguments:
# CPU nanoseconds at the start, at the end, interval, core count.
#######################################
cpu_used() {
awk -v a="$1" -v b="$2" -v t="$3" -v c="$4" 'BEGIN {
u = (b - a) / (t * 1e9)
printf "%.2f of %d (%.0f%%)", u, c, 100 * u / c
}'
}
#######################################
# Print memory, CPU, tasks, and processes for one unit.
# Arguments:
# Unit, CPU nanoseconds at the start (may be empty), interval, core
# count, output of service_procs.
#######################################
unit_report() {
local u="$1"
local cpu0="$2"
local interval="$3"
local cores="$4"
local procs="$5"
local mem
local cpu1
local tasks
local rows
local n
local nusers
local rss
local user
local pid
local comm
header "${u}"
if ! unit_installed "${u}"; then
item "Status" "not installed"
return
fi
item "Status" "$(systemctl is-active "${u}" 2>/dev/null)"
mem="$(unit_prop "${u}" MemoryCurrent)"
if [[ -n "${mem}" ]]; then
item "Memory (cgroup)" "$(human $(( mem / 1024 )))"
else
item "Memory (cgroup)" "not tracked (MemoryAccounting is off)"
fi
cpu1="$(unit_prop "${u}" CPUUsageNSec)"
if [[ -n "${cpu0}" && -n "${cpu1}" ]]; then
item "CPU (cores used)" \
"$(cpu_used "${cpu0}" "${cpu1}" "${interval}" "${cores}")"
else
item "CPU (cores used)" "not tracked (CPUAccounting is off)"
fi
tasks="$(unit_prop "${u}" TasksCurrent)"
item "Tasks (threads)" "${tasks:-not tracked}"
rows="$(awk -v u="${u}" '$1 == u' <<< "${procs}")"
if [[ -z "${rows}" ]]; then
item "Processes" "none visible"
return
fi
read -r n nusers rss < <(awk '
{ n++; rss += $4; users[$2] }
END { printf "%d %d %d\n", n, length(users), rss }' <<< "${rows}")
item "Processes" "${n}, run by ${nusers} user(s)"
item "Resident memory (sum)" "$(human "${rss}")"
echo " Largest processes (user, pid, resident memory, command):"
while read -r _ user pid rss comm; do
printf ' %-16s %8s %10s %s\n' "${user}" "${pid}" "$(human "${rss}")" \
"${comm}"
done < <(sort -k4,4nr <<< "${rows}" | head -n 5)
}
main() {
local interval=5
local cores
local total
local avail
local swap
local procs
local u
local sessions
local connect_data=""
local pm_data=""
local -A cpu0=()
local ps_cmd
while (( $# > 0 )); do
case "$1" in
--interval)
interval="${2:-}"
shift
(( $# > 0 )) && shift
;;
-h|--help)
sed -n '3,12p' "$0" | sed 's/^# \{0,1\}//'
exit 0
;;
*)
echo "Unknown option: $1" >&2
exit 2
;;
esac
done
case "${interval}" in
''|*[!0-9]*|0)
echo "--interval needs a whole number of seconds" >&2
exit 2
;;
esac
report_start "Posit resource usage report"
header "Host"
cores="$(nproc)"
item "CPU cores" "${cores}"
item "Load average (1, 5, 15 min)" "$(cut -d' ' -f1-3 /proc/loadavg)"
read -r total avail < <(free -k | awk 'NR == 2 { print $2, $7 }')
item "Memory" "$(human "${total}") total, $(human "${avail}") available"
read -r swap < <(free -k | awk '$1 == "Swap:" { print $3 }')
item "Swap used" "$(human "${swap:-0}")"
# Process lists are incomplete when /proc hides other users' processes
if findmnt -no OPTIONS /proc 2>/dev/null | grep -q hidepid; then
warn "/proc is mounted with hidepid, so only your own processes are" \
"visible"
ps_cmd="sudo ps -eo unit,user,pid,rss,pcpu,comm --sort=-rss"
ps_cmd+=" | grep -E 'rstudio-(server|launcher|connect|pm)' | head -n 40"
defer "Processes by service" "${ps_cmd}"
fi
procs="$(service_procs)"
header "CPU sample"
item "Interval" \
"${interval} seconds (cores used: 1.00 is one core busy)"
for u in "${UNITS[@]}"; do
unit_installed "${u}" && cpu0["${u}"]="$(unit_prop "${u}" CPUUsageNSec)"
done
sleep "${interval}"
for u in "${UNITS[@]}"; do
unit_report "${u}" "${cpu0["${u}"]:-}" "${interval}" "${cores}" \
"${procs}"
done
header "Workbench sessions"
# Counted from every process, since a session can leave the service's cgroup
sessions="$(ps -eo user=,comm= 2>/dev/null | awk '$2 == "rsession"')"
if [[ -n "${sessions}" ]]; then
item "rsession processes" "$(wc -l <<< "${sessions}")"
item "Users with sessions" \
"$(awk '{ print $1 }' <<< "${sessions}" | sort -u | wc -l)"
else
item "rsession processes" "none visible"
fi
header "Disk"
if [[ -r "${CONNECT_CONF}" ]]; then
connect_data="$(gcfg_value "${CONNECT_CONF}" Server DataDir)"
fi
if [[ -r "${PM_CONF}" ]]; then
pm_data="$(gcfg_value "${PM_CONF}" Server DataDir)"
fi
dir_size "Workbench data" /var/lib/rstudio-server
dir_size "Connect data" "${connect_data:-/var/lib/rstudio-connect}"
dir_size "Package Manager data" "${pm_data:-/var/lib/rstudio-pm}"
dir_size "Home directories" /home
dir_size "Logs" /var/log/rstudio
print_deferred
}
main "$@"