Diffinery

codician/diffinerypublic

Open-source, agent-first GitHub and GitHub Actions alternative that runs on your own Cloudflare account: git hosting, pull requests, code review and drop-in GitHub Actions YAML on Workers, Durable Objects, R2 and Containers.

219 lines · 9.4 KB · executableRaw History
1#!/bin/bash
2# Hosted Diffinery runners: starts the Docker daemon the first time anything needs
3# it (a step running `docker`, job containers, services, Docker actions), then runs
4# the real CLI. The daemon runs in its own session so step cleanup leaves it alone.
5#
6# The daemon reaches the Diffinery container registry through the runner's registry
7# relay (agent.mjs --registry-relay), which splits image layers into chunks under
8# Cloudflare's 100 MB request limit. BuildKit builders that `docker buildx create`
9# starts (docker/setup-buildx-action) are set up here too, see below.
10real=/usr/bin/docker
11ready=/run/diffinery-dockerd.ready
12state=/run/diffinery
13relay_port=3129
14sys_path=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
15
16# The Diffinery host this runner reports to, when it is reached over HTTPS.
17registry_host() {
18 local url=${DIFFINERY_API_URL:-}
19 [[ "$url" == https://* ]] || return 1
20 url=${url#https://}
21 echo "${url%%/*}"
22}
23
24# Starts the relay without waiting for it: dockerd starts alongside it, since the daemon only
25# reaches the relay once it pulls or pushes. relay_up then waits for it.
26start_relay() {
27 local host=$1
28 mkdir -p "$state" "/etc/docker/certs.d/$host" || return 1
29 # A certificate for the Diffinery host that only this daemon (and its builders) trust.
30 openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 30 -subj "/CN=$host" \
31 -addext "subjectAltName=DNS:$host" -keyout "$state/relay.key" -out "$state/relay.crt" >/dev/null 2>&1 || return 1
32 cp "$state/relay.crt" "/etc/docker/certs.d/$host/ca.crt"
33 printf '[registry."%s"]\n ca = ["%s"]\n' "$host" "$state/relay.crt" >"$state/buildkitd.toml"
34 # Under web-only egress the relay's own HTTPS needs the egress CA (src/egress.ts).
35 env -i PATH="$sys_path" ${NODE_EXTRA_CA_CERTS:+"NODE_EXTRA_CA_CERTS=$NODE_EXTRA_CA_CERTS"} DIFFINERY_RELAY_HOST="$host" DIFFINERY_RELAY_UPSTREAM="https://$host" DIFFINERY_RELAY_PORT="$relay_port" \
36 DIFFINERY_RELAY_CERT="$state/relay.crt" DIFFINERY_RELAY_KEY="$state/relay.key" \
37 setsid -f node /opt/diffinery/agent.mjs --registry-relay >/var/log/diffinery-relay.log 2>&1 </dev/null 9>&-
38}
39
40# Waits up to 20 s for the relay to listen.
41relay_up() {
42 for _ in $(seq 1 400); do
43 if (exec 3<>"/dev/tcp/127.0.0.1/$relay_port") 2>/dev/null; then
44 echo "$1" >"$state/relay.host"
45 return 0
46 fi
47 sleep 0.05
48 done
49 return 1
50}
51
52# Whether process $1 is still running (an exited process nobody has reaped yet is not).
53running() {
54 local stat
55 stat=$(cat "/proc/$1/stat" 2>/dev/null) || return 1
56 stat=${stat##*) }
57 [ "${stat%% *}" != Z ]
58}
59
60# Starts dockerd in its own session, noting its pid. The daemons must not inherit the lock (fd 9):
61# they would hold it for good, and a second docker command that arrives while this one is still
62# starting the daemon would wait forever.
63start_dockerd() {
64 mkdir -p "$state"
65 env -i PATH="$sys_path" "$@" setsid -f bash -c 'echo $$ >"$1"; exec dockerd' _ "$state/dockerd.pid" >/var/log/dockerd.log 2>&1 </dev/null 9>&-
66}
67
68if [ ! -e "$ready" ] && [ -z "${DOCKER_HOST:-}" ] && [ "$(id -u)" = 0 ]; then
69 exec 9>/run/diffinery-dockerd.lock
70 # Starting the daemon takes at most about a minute and a half (the relay and dockerd together,
71 # and dockerd once more if the relay fails), so a command that waits longer for another one to
72 # start it gives up rather than hang the step.
73 if ! flock -w 150 9 && [ ! -e "$ready" ]; then
74 echo "The Docker daemon did not start: another docker command has been starting it for over 2 minutes." >&2
75 tail -n 20 /var/log/dockerd.log >&2 2>/dev/null
76 exit 1
77 fi
78 if [ ! -e "$ready" ]; then
79 if ! "$real" version >/dev/null 2>&1; then
80 echo "Starting the Docker daemon" >&2
81 proxy=()
82 relay=""
83 if host=$(registry_host) && start_relay "$host"; then
84 relay=$host
85 proxy=(HTTPS_PROXY="http://127.0.0.1:$relay_port")
86 fi
87 start_dockerd "${proxy[@]}"
88 if [ -n "${host:-}" ] && { [ -z "$relay" ] || ! relay_up "$relay"; }; then
89 echo "The registry relay did not start, so image layers over 100 MB can't be pushed to $host:" >&2
90 tail -n 5 /var/log/diffinery-relay.log >&2 2>/dev/null
91 if [ -n "$relay" ]; then
92 # The daemon was started with the relay as its proxy: start it again without one.
93 pid=$(cat "$state/dockerd.pid" 2>/dev/null)
94 if [ -n "$pid" ] && kill "$pid" 2>/dev/null; then
95 for _ in $(seq 1 300); do running "$pid" || break; sleep 0.05; done
96 kill -9 "$pid" 2>/dev/null
97 fi
98 start_dockerd
99 fi
100 fi
101 for _ in $(seq 1 600); do "$real" version >/dev/null 2>&1 && break; sleep 0.1; done
102 "$real" version >/dev/null 2>&1 || { echo "The Docker daemon did not start:" >&2; tail -n 20 /var/log/dockerd.log >&2; exit 1; }
103 fi
104 touch "$ready"
105 fi
106 exec 9>&-
107fi
108
109# BuildKit builders. The docker-container driver talks to its BuildKit container through
110# `docker exec`, which can't join that container's cgroup inside a Cloudflare Container.
111# So `docker buildx create` (docker-container driver, as docker/setup-buildx-action runs it)
112# starts the BuildKit container itself, on the host network with its socket on the host,
113# and registers it as a remote builder. When the registry relay runs, BuildKit uses it as
114# its HTTPS proxy and trusts it for the Diffinery host. `docker buildx rm` removes it.
115buildkit_dir=/run/diffinery-buildkit
116
117buildx_create() {
118 local name="" driver=docker-container image=moby/buildkit:buildx-stable-1 cfg="" use=0 bootstrap=0
119 local -a flags=() env=() keep=()
120 while [ $# -gt 0 ]; do
121 case "$1" in
122 --name) name=${2:-}; shift ;;
123 --name=*) name=${1#--name=} ;;
124 --driver) driver=${2:-}; shift ;;
125 --driver=*) driver=${1#--driver=} ;;
126 --driver-opt | --driver-opt=*)
127 local opt
128 if [ "$1" = --driver-opt ]; then opt=${2:-}; shift; else opt=${1#--driver-opt=}; fi
129 local o
130 IFS=, read -ra o <<<"$opt"
131 for o in "${o[@]}"; do
132 case "$o" in
133 image=*) image=${o#image=} ;;
134 env.*=*) o=${o#env.}; env+=(-e "$o") ;;
135 network=* | cgroup-parent=* | restart-policy=* | memory=* | memory-swap=* | cpu-*=* | default-load=* | provenance-add-gha=*) ;;
136 *) return 2 ;;
137 esac
138 done
139 ;;
140 --buildkitd-flags) read -ra flags <<<"${2:-}"; shift ;;
141 --buildkitd-flags=*) read -ra flags <<<"${1#--buildkitd-flags=}" ;;
142 --buildkitd-config | --config) cfg=${2:-}; shift ;;
143 --buildkitd-config=* | --config=*) cfg=${1#*=} ;;
144 --use) use=1 ;;
145 --bootstrap) bootstrap=1 ;;
146 --platform) keep+=("$1" "${2:-}"); shift ;;
147 --platform=*) keep+=("$1") ;;
148 --node | --node=*) [ "$1" = --node ] && shift ;;
149 # Appending nodes, endpoints and anything else: leave it to buildx.
150 *) return 2 ;;
151 esac
152 shift
153 done
154 [ "$driver" = docker-container ] || return 2
155 [ -n "$name" ] || name="builder-$(cat /proc/sys/kernel/random/uuid)"
156 local dir="$buildkit_dir/$name" box="buildx_buildkit_${name}0"
157 mkdir -p "$dir" "$state"
158 local -a args=(--config /etc/buildkit/buildkitd.toml)
159 : >"$dir/buildkitd.toml"
160 [ -n "$cfg" ] && cat "$cfg" >>"$dir/buildkitd.toml"
161 if [ -s "$state/relay.host" ]; then
162 local host
163 host=$(cat "$state/relay.host")
164 if ! grep -qF "registry.\"$host\"" "$dir/buildkitd.toml"; then
165 { echo; cat "$state/buildkitd.toml"; } >>"$dir/buildkitd.toml"
166 fi
167 env+=(-e "HTTPS_PROXY=http://127.0.0.1:$relay_port" -e "https_proxy=http://127.0.0.1:$relay_port")
168 fi
169 "$real" rm -f "$box" >/dev/null 2>&1
170 "$real" run -d --name "$box" --label "diffinery.buildkit=$name" --privileged --network host \
171 -v "$dir:/run/buildkit" -v "$dir/buildkitd.toml:/etc/buildkit/buildkitd.toml:ro" -v "$state:$state:ro" \
172 -v "${box}_state:/var/lib/buildkit" "${env[@]}" "$image" "${args[@]}" "${flags[@]}" >/dev/null || return 1
173 for _ in $(seq 1 120); do
174 [ -S "$dir/buildkitd.sock" ] && break
175 if [ "$("$real" inspect -f '{{.State.Running}}' "$box" 2>/dev/null)" != true ]; then
176 echo "BuildKit did not start:" >&2
177 "$real" logs "$box" 2>&1 | tail -n 20 >&2
178 return 1
179 fi
180 sleep 0.25
181 done
182 local -a create=(buildx create --name "$name" --driver remote "${keep[@]}")
183 [ "$use" = 1 ] && create+=(--use)
184 [ "$bootstrap" = 1 ] && create+=(--bootstrap)
185 exec "$real" "${create[@]}" "unix://$dir/buildkitd.sock"
186}
187
188if [ "${1:-}" = buildx ] && [ "${2:-}" = create ] && [ -z "${DOCKER_HOST:-}" ] && [ "$(id -u)" = 0 ]; then
189 buildx_create "${@:3}"
190 [ $? = 2 ] || exit 1
191fi
192
193# docker buildx rm: also remove the BuildKit containers buildx_create started.
194if [ "${1:-}" = buildx ] && [ "${2:-}" = rm ] && [ -d "$buildkit_dir" ]; then
195 "$real" "$@"
196 status=$?
197 for arg in "${@:3}"; do
198 case "$arg" in -*) continue ;; esac
199 if [ -d "$buildkit_dir/$arg" ]; then
200 "$real" rm -f -v "buildx_buildkit_${arg}0" >/dev/null 2>&1
201 "$real" volume rm "buildx_buildkit_${arg}0_state" >/dev/null 2>&1
202 rm -rf "${buildkit_dir:?}/$arg"
203 fi
204 done
205 exit "$status"
206fi
207
208# docker push: when it fails, show what the registry relay saw (its error alone doesn't say).
209if { [ "${1:-}" = push ] || { [ "${1:-}" = image ] && [ "${2:-}" = push ]; }; } && [ -s "$state/relay.host" ]; then
210 "$real" "$@"
211 status=$?
212 if [ "$status" != 0 ]; then
213 echo "The registry relay's last lines:" >&2
214 tail -n 20 /var/log/diffinery-relay.log >&2 2>/dev/null
215 fi
216 exit "$status"
217fi
218
219exec "$real" "$@"