Files
agents_and_robots/dev-scripts/ps.sh
T

97 lines
2.6 KiB
Bash
Executable File

#!/usr/bin/env bash
# ps.sh — muestra procesos de agentes con detalles (PID, uptime, memoria, CPU)
#
# Uso:
# ./dev-scripts/ps.sh # todos los agentes corriendo
# ./dev-scripts/ps.sh assistant-bot # uno específico
source "$(dirname "$0")/_common.sh"
TARGET="${1:-}"
found=0
# Cabecera
printf "%-22s %-8s %-12s %-10s %-8s %s\n" \
"AGENT" "PID" "UPTIME" "MEM (RSS)" "CPU %" "LOG SIZE"
printf '%s\n' "$(printf '─%.0s' {1..78})"
while IFS='|' read -r id _version _enabled _desc _cfg; do
[[ -n "$TARGET" && "$id" != "$TARGET" ]] && continue
if ! is_running "$id"; then
if [[ -n "$TARGET" ]]; then
printf "%-22s ${DIM}%-8s${RST}\n" "$id" "stopped"
fi
continue
fi
pid="$(read_pid "$id")"
instance_count="$(count_instances "$id")"
((found++)) || true
# Uptime: calcular desde el inicio del proceso
if [[ -f /proc/$pid/stat ]]; then
start_ticks=$(awk '{print $22}' /proc/$pid/stat 2>/dev/null || echo 0)
clk_tck=$(getconf CLK_TCK)
boot_time=$(awk '/btime/{print $2}' /proc/stat)
proc_start=$((boot_time + start_ticks / clk_tck))
now=$(date +%s)
elapsed=$((now - proc_start))
days=$((elapsed / 86400))
hours=$(( (elapsed % 86400) / 3600 ))
mins=$(( (elapsed % 3600) / 60 ))
if [[ $days -gt 0 ]]; then
uptime="${days}d ${hours}h"
elif [[ $hours -gt 0 ]]; then
uptime="${hours}h ${mins}m"
else
uptime="${mins}m"
fi
else
uptime="n/a"
fi
# Memoria RSS y CPU desde ps
read -r mem_kb cpu_pct < <(ps -p "$pid" -o rss=,pcpu= 2>/dev/null || echo "0 0")
if [[ "$mem_kb" -gt 1048576 ]]; then
mem="$(( mem_kb / 1048576 )) GB"
elif [[ "$mem_kb" -gt 1024 ]]; then
mem="$(( mem_kb / 1024 )) MB"
else
mem="${mem_kb} KB"
fi
# Tamaño del log
log="$(log_file "$id")"
if [[ -f "$log" ]]; then
log_bytes=$(stat -c%s "$log" 2>/dev/null || echo 0)
if [[ "$log_bytes" -gt 1048576 ]]; then
log_size="$(( log_bytes / 1048576 )) MB"
elif [[ "$log_bytes" -gt 1024 ]]; then
log_size="$(( log_bytes / 1024 )) KB"
else
log_size="${log_bytes} B"
fi
else
log_size="-"
fi
printf "%-22s ${GRN}%-8s${RST} %-12s %-10s %-8s %s\n" \
"$id" "$pid" "$uptime" "$mem" "${cpu_pct}%" "$log_size"
# Warn about duplicate instances
if [[ "$instance_count" -gt 1 ]]; then
printf " ${RED}⚠ WARNING: %d instances running!${RST} PIDs: %s\n" \
"$instance_count" "$(find_agent_pids "$id" | tr '\n' ' ')"
fi
done < <(list_agents_raw)
if [[ "$found" -eq 0 ]]; then
if [[ -n "$TARGET" ]]; then
fail "Agente '$TARGET' no está corriendo."
else
dim " No hay agentes corriendo."
fi
fi