Skip to content

Instantly share code, notes, and snippets.

@TotalLag
Last active December 25, 2024 04:16
Show Gist options
  • Save TotalLag/bde660ef317e1fec8aa3989f2cd8460f to your computer and use it in GitHub Desktop.
Save TotalLag/bde660ef317e1fec8aa3989f2cd8460f to your computer and use it in GitHub Desktop.
idempotent script that allows easier modification of the CPU core limit. It ensures the cgroup is created and configured only if necessary and allows you to specify the number of CPU cores as a parameter.
#!/bin/bash
# Verify with cat /sys/fs/cgroup/coolify_group/cpu.stat
# Define variables
COOLIFY_GROUP="/sys/fs/cgroup/coolify_group"
CPU_LIMIT_CORES=${1:-2} # Default to 2 cores if no argument is provided
CPU_QUOTA=$((CPU_LIMIT_CORES * 100000)) # Convert cores to microseconds
CPU_PERIOD=100000 # Period in microseconds (100ms)
# Ensure the cgroup exists
if [ ! -d "$COOLIFY_GROUP" ]; then
echo "Creating cgroup at $COOLIFY_GROUP"
sudo mkdir -p "$COOLIFY_GROUP"
fi
# Enable the CPU controller (only if not already enabled)
if ! grep -q "+cpu" /sys/fs/cgroup/cgroup.subtree_control; then
echo "+cpu" | sudo tee /sys/fs/cgroup/cgroup.subtree_control
fi
# Add Coolify container processes to the cgroup
echo "Adding Coolify containers to the cgroup..."
for pid in $(docker inspect --format '{{.State.Pid}}' $(docker ps --filter "name=coolify" -q)); do
if ! grep -q "^$pid$" "$COOLIFY_GROUP/cgroup.procs"; then
echo $pid | sudo tee "$COOLIFY_GROUP/cgroup.procs" > /dev/null
fi
done
# Set CPU limits (idempotently)
echo "Setting CPU limits: $CPU_LIMIT_CORES cores ($CPU_QUOTA/$CPU_PERIOD)..."
CURRENT_QUOTA=$(cat "$COOLIFY_GROUP/cpu.max" 2>/dev/null | awk '{print $1}')
if [ "$CURRENT_QUOTA" != "$CPU_QUOTA" ]; then
echo "$CPU_QUOTA $CPU_PERIOD" | sudo tee "$COOLIFY_GROUP/cpu.max"
fi
echo "Coolify containers grouped and limited to $CPU_LIMIT_CORES CPU cores."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment