From ea965f6e179cade7768415432593fa8a24c68162 Mon Sep 17 00:00:00 2001
From: Cornelius Keller <cornelius.keller@gmail.com>
Date: Tue, 19 Sep 2023 17:44:28 +0000
Subject: [PATCH] fix(dind): wait for Docker daemon to be ready with a timeout
 (1 min)

---
 templates/gitlab-ci-docker.yml | 29 ++++++++++++++++++-----------
 1 file changed, 18 insertions(+), 11 deletions(-)

diff --git a/templates/gitlab-ci-docker.yml b/templates/gitlab-ci-docker.yml
index 6ea72e4..ea778a4 100644
--- a/templates/gitlab-ci-docker.yml
+++ b/templates/gitlab-ci-docker.yml
@@ -329,8 +329,19 @@ stages:
     done
   }
 
-  function is_runner_dind_capable() {
-    docker info > /dev/null 2>&1
+  function wait_for_docker_daemon() {
+    log_info "Wait for Docker daemon..."
+    # shellcheck disable=SC2034
+    for i in $(seq 1 30); do
+      if ! docker info &> /dev/null; then
+        log_info "... not responding: wait"
+        sleep 2
+      else
+        log_info "... ready: continue"
+        return
+      fi
+    done
+    fail "... timeout reached: halt"
   }
 
   function awkenvsubst() {
@@ -392,14 +403,6 @@ stages:
     unscope_variables
     eval_all_secrets
     configure_registries_auth
-
-    if is_runner_dind_capable
-    then
-      docker info
-    elif [[ -x /kaniko/executor ]]
-    then
-      create_kaniko_cache_dir
-    fi
   }
 
   # evaluate the context path
@@ -462,6 +465,10 @@ stages:
     key: "$CI_COMMIT_REF_SLUG-docker"
     paths:
       - .cache
+  before_script:
+  - *docker-scripts
+  - create_kaniko_cache_dir
+
 
 .docker-dind-base:
   extends: .docker-base
@@ -488,7 +495,7 @@ stages:
           if [[ -n "${DOCKER_REGISTRY_MIRROR}" ]]; then dockerd-entrypoint.sh --registry-mirror ${DOCKER_REGISTRY_MIRROR}; else dockerd-entrypoint.sh; fi || exit
   before_script:
     - *docker-scripts
-    - if ! is_runner_dind_capable; then fail "Docker-in-Docker is not enabled on this runner. Either use a Docker-in-Docker capable runner, or disable this job by setting \$DOCKER_BUILD_TOOL to a different value"; fi
+    - if ! wait_for_docker_daemon; then fail "Docker-in-Docker is not enabled on this runner. Either use a Docker-in-Docker capable runner, or disable this job by setting \$DOCKER_BUILD_TOOL to a different value"; fi
 
 # ==================================================
 # Stage: build
-- 
GitLab