|
| 1 | +#!/bin/sh |
| 2 | + |
| 3 | +# Copyright 2022 The envd Authors |
| 4 | +# Copyright 2022 The buildkit Authors |
| 5 | +# |
| 6 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | +# you may not use this file except in compliance with the License. |
| 8 | +# You may obtain a copy of the License at |
| 9 | +# |
| 10 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | +# |
| 12 | +# Unless required by applicable law or agreed to in writing, software |
| 13 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | +# See the License for the specific language governing permissions and |
| 16 | +# limitations under the License. |
| 17 | + |
| 18 | +# envd-daemonless.sh spawns ephemeral buildkitd for executing envd. |
| 19 | +# |
| 20 | +# Usage: envd-daemonless.sh build ... |
| 21 | +# |
| 22 | +# Flags for buildkitd can be specified as $BUILDKITD_FLAGS . |
| 23 | +# |
| 24 | +# The script is compatible with BusyBox shell. |
| 25 | +set -eu |
| 26 | + |
| 27 | +: ${ENVDCTL=envd} |
| 28 | +: ${BUILDCTL=buildctl} |
| 29 | +: ${BUILDCTL_CONNECT_RETRIES_MAX=10} |
| 30 | +: ${BUILDKITD=buildkitd} |
| 31 | +: ${BUILDKITD_FLAGS=} |
| 32 | +: ${ROOTLESSKIT=rootlesskit} |
| 33 | + |
| 34 | +# $tmp holds the following files: |
| 35 | +# * pid |
| 36 | +# * addr |
| 37 | +# * log |
| 38 | +tmp=$(mktemp -d /tmp/envd-daemonless.XXXXXX) |
| 39 | +trap "kill \$(cat $tmp/pid) || true; wait \$(cat $tmp/pid) || true; rm -rf $tmp" EXIT |
| 40 | + |
| 41 | +startBuildkitd() { |
| 42 | + addr= |
| 43 | + helper= |
| 44 | + if [ $(id -u) = 0 ]; then |
| 45 | + addr=/run/buildkit/buildkitd.sock |
| 46 | + else |
| 47 | + addr=$XDG_RUNTIME_DIR/buildkit/buildkitd.sock |
| 48 | + helper=$ROOTLESSKIT |
| 49 | + fi |
| 50 | + $helper $BUILDKITD $BUILDKITD_FLAGS --addr=unix://$addr >$tmp/log 2>&1 & |
| 51 | + pid=$! |
| 52 | + echo $pid >$tmp/pid |
| 53 | + echo $addr >$tmp/addr |
| 54 | +} |
| 55 | + |
| 56 | +# buildkitd supports NOTIFY_SOCKET but as far as we know, there is no easy way |
| 57 | +# to wait for NOTIFY_SOCKET activation using busybox-builtin commands... |
| 58 | +waitForBuildkitd() { |
| 59 | + addr=unix://$(cat $tmp/addr) |
| 60 | + try=0 |
| 61 | + max=$BUILDCTL_CONNECT_RETRIES_MAX |
| 62 | + until $BUILDCTL --addr=$addr debug workers >/dev/null 2>&1; do |
| 63 | + if [ $try -gt $max ]; then |
| 64 | + echo >&2 "could not connect to $addr after $max trials" |
| 65 | + echo >&2 "========== log ==========" |
| 66 | + cat >&2 $tmp/log |
| 67 | + exit 1 |
| 68 | + fi |
| 69 | + sleep $(awk "BEGIN{print (100 + $try * 20) * 0.001}") |
| 70 | + try=$(expr $try + 1) |
| 71 | + done |
| 72 | +} |
| 73 | + |
| 74 | +startBuildkitd |
| 75 | +waitForBuildkitd |
| 76 | +$ENVDCTL context create --name daemonless --builder unix --builder-address $(cat $tmp/addr) --use |
| 77 | +$ENVDCTL "$@" |
0 commit comments