safe_sleep.sh rarely hangs indefinitely

· GitHub ·

7 min read Original article ↗

As @kristoff-it rightly pointed out while streaming on Twitch yesterday, there's an even better question than "why is this buggy and inefficient script used instead of the universally-available sleep", that being: "why does the runner need to sleep in the first place"? Well, let's look at where safe_sleep.sh is used...

Waiting for Runner Termination

update.sh.template uses safe_sleep.sh to poll the runner's PID in /proc to see if it has terminated:

# wait for runner process to exit.
date "+[%F %T-%4N] Waiting for $runnerprocessname ($runnerpid) to complete" >> "$logfile" 2>&1
while [ -e /proc/$runnerpid ]
do
date "+[%F %T-%4N] Process $runnerpid still running" >> "$logfile" 2>&1
"$rootfolder"/safe_sleep.sh 2
done
date "+[%F %T-%4N] Process $runnerpid finished running" >> "$logfile" 2>&1
# start re-organize folders
date "+[%F %T-%4N] Sleep 1 more second to make sure process exited" >> "$logfile" 2>&1
"$rootfolder"/safe_sleep.sh 1

Firstly, this is another very obvious race condition -- nothing stops the runner from terminating, and another process from picking up that PID, within the 2-second interval, such that update.sh.template thinks the Actions runner is still running and continues to wait. Since Actions runners are long-lived (even if they handle just one job, a job could go on for hours!), PID wraparound could have easily happened, so this isn't an esoteric concern: on any system doing more than hosting a single Actions runner, there is a non-negligible chance that something happens to spawn a new process in the required interval and hence takes down a runner indefinitely (until one unlucky process happens to terminate). This is, again, extremely sloppy coding -- the process should just be monitored using an appropriate primitive. Perhaps the program that spawned the runner uses wait; perhaps the runner which spawns this script manually communicates its termination through a pipe; or perhaps the runner just doesn't spawn the script until it can make progress.

Secondly, because safe_sleep.sh spins a CPU needlessly, this causes a full CPU core to get locked up spinning, while a CI run is potentially in progress, waiting for that run to finish. I haven't been able to understand the maze of C# logic which ultimately calls this code, but we've observed a half dozen non-deadlocked safe_sleep.sh processes on a CI machine in normal operation, so I'm fairly confident in saying that the script is spawned while CI runs are in-progress. So on the machine I mentioned in a previous comment, not only were there 4 deadlocked safe_sleep.sh processes, there were also 6 which were being continuously respawned each time they terminated; re-rolling the dice for a deadlock, and causing a full 10 cores (1000% CPU usage) to be saturated on... waiting for timestamps.

Waiting for Docker Spawn

run-helper.sh.template uses safe_sleep.sh to poll docker ps to check whether Docker has spawned:

# Wait for docker to start
if [ ! -z "$RUNNER_WAIT_FOR_DOCKER_IN_SECONDS" ]; then
if [ "$RUNNER_WAIT_FOR_DOCKER_IN_SECONDS" -gt 0 ]; then
echo "Waiting for docker to be ready."
for i in $(seq "$RUNNER_WAIT_FOR_DOCKER_IN_SECONDS"); do
if docker ps > /dev/null 2>&1; then
echo "Docker is ready."
break
fi
"$DIR"/safe_sleep.sh 1
done
fi
fi

This seems like it's just the wrong approach again; synchronization should be ensured rather than just polling a few times. However, I won't ponder this for too long, because it seems like this is dead code: RUNNER_WAIT_FOR_DOCKER_IN_SECONDS does not appear anywhere else in the repository so presumably will never be set.

Delay between Runner Restarts

run-helper.sh.template uses safe_sleep.sh to implement a 5 second delay before restarting a failed runner:

elif [[ $returnCode == 2 ]]; then
echo "Runner listener exit with retryable error, re-launch runner in 5 seconds."
"$DIR"/safe_sleep.sh 5
exit 2
elif [[ $returnCode == 3 ]]; then

I find this quite amusing: a big reason to use a "retry delay" like this is to avoid wasting system resources on repeatedly retrying something that keeps failing, but thanks to the implementation of safe_sleep.sh, we're replacing "locking up a full CPU core on retrying something that failed" with "locking up a full CPU core on doing literally nothing".

Waiting for Update Completion

run-helper.sh.template uses safe_sleep.sh to wait for up to 30 seconds while update.sh.template (that's the one we saw earlier!) runs an update:

elif [[ $returnCode == 3 ]]; then
# Wait for 30 seconds or for flag file to exists for the runner update process finish
echo "Runner listener exit because of updating, re-launch runner after successful update"
for i in {0..30}; do
if test -f "$updateFile"; then
echo "Update finished successfully."
rm "$updateFile"
break
fi
"$DIR"/safe_sleep.sh 1
done
exit 2
elif [[ $returnCode == 4 ]]; then

(Weirdly, this case is duplicated almost exactly directly below; apparently exit codes 3 and 4 both mean "exiting for update", but I guess the author of this code was a little too scared to write an OR || in their condition, preferring to duplicate the block.)

Again, using polling here is a clearly bad approach. Incidentally, this case lines up with the first one I looked at to mean that as soon as an update is available, assuming none of the race conditions are hit, a full CPU core is locked up spinning on nothing right up until the update completes.

There at least isn't a deadlock bug here in normal operation, and even if update.finished were never created, the loop is capped at 30 seconds. Perhaps that's a lazy workaround for some of the bugs we've covered here, I don't know.


Summary

Here's where we're at. The safe_sleep.sh script:

  • ...attempts to solve a problem which obviously does not exist
  • ...solves that hypothetical problem in a significantly worse way than the safe_sleep function it replaced
  • ...locks up a full CPU core while running to spin on nothing
  • ...includes an obvious deadlock bug, which when hit locks up a full CPU core and disables the Actions runner until manual intervention
  • ...is called almost exclusively to wait for other tasks to complete
    • ...taking up system resources (one CPU core) and therefore likely slowing down the task being waited for
    • ...introducing another potential deadlock by incorrectly polling a PID
    • ...slowing down the whole system, including active Actions jobs, in fairly common situations

This report of the common deadlock bug, which can turn self-hosted runners into expensive heaters, has been ignored for months. A valid fix for that deadlock was PR'd over a year ago, went completely ignored by maintainers for over a year, before a bot closed it as stale because the maintainers of this repository chose to ignore it. We are having to babysit our Actions runners to occasionally kill these deadlocked spinloops. Users who aren't aware of this bug (virtually all of them!) and who use self-hosted runners probably have cores spinning away in an infinite loop as we speak for no coherent reason, wasting money, wasting electricity, and bottlenecking their workflows.

This situation is insanity. Can anyone at Microsoft look away from the electricity-to-slop converter that is Copilot for the 5 minutes necessary to write some vaguely competent code?

Reacted by Ricardo Fernández Serrata, Luca Venir, Peter Farr, Mike Cronce, Pavel Malinov, Josh Levy-Kramer, Siddhu Warrier, Trent V., Markus Ressel, marc-guenther and 29 more

Reacted by Ricardo Fernández Serrata, Mike Cronce, Samuel Polo Peña, Josh Levy-Kramer, Siddhu Warrier, Trent V., Fabien Herry, Boris Ralichkov, Andax, Ytrog and 11 more

Reacted by Artyom Pervukhin, Christian, Wilfried Klaebe, Jules, kyle shockey, Justin Pombrio, Hannes Käufler, Remigiusz Żętkowski, Krazer, Daniel Kertesz and 303 more

Reacted by Ricardo Fernández Serrata, Pavel Malinov, Peter Ped Helcmanovsky, Samuel Polo Peña, Josh Levy-Kramer, Trent V., Wylan, Boris Ralichkov, Tom Daley, Piotr Gulbinowicz and 3 more

Reacted by Vlad the Lad, Pavel Malinov, Samuel Polo Peña, Trent V., Boris Ralichkov and Slava Kurilyak