Skip to content

Instantly share code, notes, and snippets.

@polsala
Created June 27, 2024 12:47
Show Gist options
  • Select an option

  • Save polsala/666220b8b1600af068fae1a1d72971d9 to your computer and use it in GitHub Desktop.

Select an option

Save polsala/666220b8b1600af068fae1a1d72971d9 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Create necessary directories if they do not exist
mkdir -p /opt/node_exporter/metrics_folder/
mkdir -p /opt/node_exporter/ram_consumption/
# Create the script file with the given content
cat << 'EOF' > /opt/node_exporter/ram_consumption/ram_p.sh
#!/bin/bash
# Path and name of the metrics file
METRIC_PATH=/opt/node_exporter/metrics_folder/
METRIC_FILE='top_ten_ram_usage.prom'
# Get the top 10 processes consuming the most RAM and their usage in MB
top_processes=$(ps aux --sort=-%mem | awk 'NR>1 {cmd=""; for(i=11;i<=NF;i++){cmd=cmd" "$i}; print $6/1024, cmd}' | sort -rn | head -n 10)
# Create or empty the metrics file
echo "" > ${METRIC_PATH}${METRIC_FILE}
# Process each line of the output and convert it into a Prometheus metric
while IFS= read -r line; do
# Extract RAM usage and process command
ram_usage=$(echo $line | awk '{print $1}')
command=$(echo $line | cut -d' ' -f2-)
# Replace spaces in the command with underscores to make it a valid Prometheus label
command_label=$(echo $command | sed 's/ /_/g')
# Format the metric for Prometheus
metric="top_ten_ram_usage{command=\"$command_label\"} $ram_usage"
# Write the metric to the file
echo $metric >> ${METRIC_PATH}${METRIC_FILE}
done <<< "$top_processes"
EOF
# Set execution permissions
chmod +x /opt/node_exporter/ram_consumption/ram_p.sh
# Change owner to erp user
chown erp:erp /opt/node_exporter/ram_consumption/ram_p.sh
# Add to crontab if not already present
(crontab -l -u erp 2>/dev/null | grep -q '/opt/node_exporter/ram_consumption/ram_p.sh') || (crontab -l -u erp 2>/dev/null; echo '* * * * * /bin/bash /opt/node_exporter/ram_consumption/ram_p.sh') | crontab -u erp -
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment