Repository navigation
Expand file tree
/
Copy pathbuild_docker_images
More file actions
executable file
·424 lines (376 loc) · 14.8 KB
/
Copy pathbuild_docker_images
File metadata and controls
executable file
·424 lines (376 loc) · 14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
#!/bin/bash
###################################################################################
# build_docker_images: Recursively build and tag docker images in a directory #
# Copyright (C) 2023 Heather Ward - DNAstack #
# #
# This program is free software; you can redistribute it and/or #
# modify it under the terms of the GNU General Public License #
# as published by the Free Software Foundation, version 2 of the #
# License. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program; if not, write to the Free Software #
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. #
###################################################################################
set -eEuo pipefail
DEFAULT_DOCKER_CONTEXT_DIR=$(readlink -f "$(dirname "$0")")
usage() {
cat << EOF
Recursively build and tag docker images in a directory.
Docker definitions are discovered by identifying build.env files in the docker_context_dir. build.env must define at minimum IMAGE_NAME and IMAGE_TAG variables.
Usage: $0 -d docker_context_dir [OPTIONS]
OPTIONS
-h Display this message and exit
-d Directory to find Dockerfiles/build contexts in [${DEFAULT_DOCKER_CONTEXT_DIR}]
-c Container registry
-p Also push built images
-x Use the 'docker buildx' command to build AMD-64 images (for example from an ARM-based Mac)
-b Comma-separated global build arguments (VAR=value,VAR2=value2). Will be passed to every image build.
-l Add a label to every image built (KEY=VALUE). Repeat for more than one.
-r Print where the build.env in the given directory resolves, then exit. Prints one line,
BUILT_IN_SOURCE<TAB><absolute definition directory>; that is the directory itself
unless its build.env sets BUILT_IN.
POINTERS
A build.env that sets BUILT_IN=<git URL> says its image is built in another repository.
The image named by IMAGE_NAME and IMAGE_TAG is built from the one definition of it in a
local clone of that repository instead. The clone is <dir>/<repository name>, searched
in \$GIT_REPO_ROOT (when set) and then in the directory holding the clone of this script.
The first one whose origin is the BUILT_IN repository is used. Each source definition is
built once however many pointers name it.
EOF
}
log() {
if [[ ! -t 1 ]]; then
echo "[$(date +'%Y-%m-%dT%H:%M:%S%z')] $*"
return
fi
echo "$(tput bold)$(tput setaf 110)[$(date +'%Y-%m-%dT%H:%M:%S%z')] $*$(tput sgr0)" >&1
}
err() {
if [[ ! -t 2 ]]; then
echo "[$(date +'%Y-%m-%dT%H:%M:%S%z')]: $*" >&2
return
fi
echo "$(tput bold)$(tput setaf 203)[$(date +'%Y-%m-%dT%H:%M:%S%z')]: $*$(tput sgr0)" >&2
}
# Print the value of a variable as set by a build.env, or nothing if it is unset.
# Whatever the build.env prints while being sourced is discarded, so it is never read as the value.
build_env_var() {
local build_env_file="$1"
local var_name="$2"
(
unset IMAGE_NAME IMAGE_TAG BUILT_IN
set -a
# shellcheck source=/dev/null
. "${build_env_file}" > /dev/null
set +a
printf '%s' "${!var_name:-}"
)
}
# Print host/owner/repo for a git URL, so SSH and HTTPS forms of one repository agree.
# Case is ignored for github.com, which treats owner and repository names that way.
normalise_git_url() {
local url="${1%/}"
local host path rest
url="${url%.git}"
url="${url%/}"
case "${url}" in
*://*)
rest="${url#*://}"
rest="${rest#*@}"
host="${rest%%/*}"
path="${rest#*/}"
;;
*@*:*)
rest="${url#*@}"
host="${rest%%:*}"
path="${rest#*:}"
;;
*)
printf '%s\n' "${url}"
return
;;
esac
host="${host%%:*}"
host=$(printf '%s' "${host}" | tr '[:upper:]' '[:lower:]')
if [[ "${host}" == "github.com" ]]; then
path=$(printf '%s' "${path}" | tr '[:upper:]' '[:lower:]')
fi
printf '%s/%s\n' "${host}" "${path}"
}
# Print the absolute path of this script, following symlinks without readlink -f.
script_real_path() {
local path="$0"
local target dir
while [[ -L "${path}" ]]; do
target=$(readlink "${path}")
dir=$(cd "$(dirname "${path}")" && pwd -P)
case "${target}" in
/*) path="${target}" ;;
*) path="${dir}/${target}" ;;
esac
done
printf '%s/%s\n' "$(cd "$(dirname "${path}")" && pwd -P)" "$(basename "${path}")"
}
# Print each directory searched for clones of a pointer's source repository, in order.
clone_search_dirs() {
local root top
if [[ -n "${GIT_REPO_ROOT:-}" ]]; then
root="${GIT_REPO_ROOT%/}"
if [[ -d "${root}" ]]; then
root=$(cd "${root}" && pwd -P)
fi
printf '%s\n' "${root}"
fi
if top=$(git -C "$(dirname "$(script_real_path)")" rev-parse --show-toplevel 2> /dev/null); then
top=$(cd "${top}" && pwd -P)
if [[ "$(dirname "${top}")" != "${root:-}" ]]; then
dirname "${top}"
fi
fi
}
# Print the clone directory for a repository name inside a search directory, if any.
# An exact name wins; for github.com a directory differing only in case also counts,
# because GitHub ignores case in repository names but a clone directory keeps the case it was given.
find_clone_dir() {
local search_dir="$1"
local repo="$2"
local github="$3"
local entry want_lower
if [[ -d "${search_dir}/${repo}" ]]; then
printf '%s\n' "${search_dir}/${repo}"
return
fi
if [[ "${github}" != 'true' ]]; then
return
fi
want_lower=$(printf '%s' "${repo}" | tr '[:upper:]' '[:lower:]')
for entry in "${search_dir}"/*/; do
entry="${entry%/}"
if [[ -d "${entry}" && "$(printf '%s' "${entry##*/}" | tr '[:upper:]' '[:lower:]')" == "${want_lower}" ]]; then
printf '%s\n' "${entry}"
return
fi
done
}
# Print a fingerprint of the tracked files under a directory of a clone.
definition_fingerprint() {
local definition_dir="$1"
local file
(
cd "${definition_dir}"
while IFS= read -r file; do
shasum -a 256 "${file}"
done < <(git ls-files .)
) | shasum -a 256
}
# Print the absolute directory that defines the image a pointer build.env names.
pointer_source_dir() {
local pointer_file="$1"
local name tag url want repo dir clone candidate github origin first_dir reasons
local build_env_file found_name found_tag defined_tags fingerprint first_fingerprint
local -a matches=()
name=$(build_env_var "${pointer_file}" IMAGE_NAME)
tag=$(build_env_var "${pointer_file}" IMAGE_TAG)
url=$(build_env_var "${pointer_file}" BUILT_IN)
want=$(normalise_git_url "${url}")
repo="${url%/}"
repo="${repo%.git}"
repo="${repo##*[/:]}"
github=false
if [[ "${want}" == github.com/* ]]; then
github=true
fi
first_dir=""
reasons=""
clone=""
while IFS= read -r dir; do
if [[ -z "${first_dir}" ]]; then
first_dir="${dir}"
fi
candidate=$(find_clone_dir "${dir}" "${repo}" "${github}")
if [[ -z "${candidate}" ]]; then
reasons="${reasons:+${reasons}, }${dir}/${repo} (missing)"
continue
fi
origin=$(git -C "${candidate}" config --get remote.origin.url 2> /dev/null || true)
if [[ -n "${origin}" && "$(normalise_git_url "${origin}")" == "${want}" ]]; then
clone="${candidate}"
break
fi
reasons="${reasons:+${reasons}, }${candidate} (origin ${origin:-none})"
done < <(clone_search_dirs)
if [[ -z "${clone}" ]]; then
refuse "${name}:${tag} is built in ${url}, which is not cloned in ${reasons:-any directory}; run git clone ${url} \"${first_dir:-<dir>}/${repo}\", or set GIT_REPO_ROOT to the directory holding a clone of it"
return 1
fi
defined_tags=""
while IFS= read -r build_env_file; do
if [[ -n "$(build_env_var "${build_env_file}" BUILT_IN)" ]]; then
continue
fi
found_name=$(build_env_var "${build_env_file}" IMAGE_NAME)
if [[ "${found_name}" != "${name}" ]]; then
continue
fi
found_tag=$(build_env_var "${build_env_file}" IMAGE_TAG)
if [[ "${found_tag}" == "${tag}" ]]; then
matches+=("$(dirname "${build_env_file}")")
else
defined_tags="${defined_tags:+${defined_tags}, }${name}:${found_tag}"
fi
done < <(find "${clone}" -name build.env -not -path '*/.git/*' | sort)
if [[ "${#matches[@]}" -eq 0 ]]; then
refuse "the pointer wants ${name}:${tag}, the clone defines ${defined_tags:-no ${name} image} (${clone})"
return 1
fi
first_fingerprint=$(definition_fingerprint "${matches[0]}")
for dir in "${matches[@]}"; do
fingerprint=$(definition_fingerprint "${dir}")
if [[ "${fingerprint}" != "${first_fingerprint}" ]]; then
refuse "${name}:${tag} is defined more than once in ${clone} with different contents: ${matches[*]}"
return 1
fi
done
(cd "${matches[0]}" && pwd -P)
}
# Print the definition directory a build.env resolves to: itself, or its pointer's source.
resolve_definition_dir() {
local build_env_file="$1"
if [[ -n "$(build_env_var "${build_env_file}" BUILT_IN)" ]]; then
pointer_source_dir "${build_env_file}"
else
(cd "$(dirname "${build_env_file}")" && pwd -P)
fi
}
# Print a pointer-resolution refusal as bare text: callers relay it verbatim inside their own message.
refuse() {
echo "$*" >&2
}
build_docker_image() {
local build_env_file="$1"
local global_build_args="$2"
local docker_context_dir=$(dirname "${build_env_file}")
local -a build_args
(
# Ensure we're pulling these variables from the build_env_file
unset IMAGE_NAME IMAGE_TAG DOCKERFILE NOBUILD CONDA_ENVIRONMENT_TEMPLATE
set -a
. "${build_env_file}"
set +a
IMAGE_NAME=${IMAGE_NAME:-}
IMAGE_TAG=${IMAGE_TAG:-}
DOCKERFILE=${DOCKERFILE:-}
NOBUILD=${NOBUILD:-false}
CONDA_ENVIRONMENT_TEMPLATE=${CONDA_ENVIRONMENT_TEMPLATE:-}
if [[ "${NOBUILD}" == "true" ]]; then
log "No-build set for docker context [${docker_context_dir}]; skipping"
return
fi
# Find the Dockerfile, either in the same directory as the build.env file or using the DOCKERFILE variable from build.env
if [[ -z "${DOCKERFILE}" ]]; then
dockerfile=$(find "${docker_context_dir}" -type f -name Dockerfile)
else
dockerfile="${docker_context_dir}/${DOCKERFILE}"
fi
if [[ ! -s "${dockerfile}" ]]; then
err "[ERROR] Dockerfile not found; either create ${docker_context_dir}/Dockerfile or define the DOCKERFILE variable in ${build_env_file}"
exit 1
fi
# Ensure that at minimum IMAGE_NAME and IMAGE_TAG are defined
if [[ -z "${IMAGE_NAME}" ]]; then
err "[ERROR] No IMAGE_NAME defined for docker context [${docker_context_dir}]"
err "[ERROR] Set IMAGE_NAME in [${build_env_file}] and try again."
exit 1
fi
if [[ -z "${IMAGE_TAG}" ]]; then
err "[ERROR] No IMAGE_TAG defined for docker context [${docker_context_dir}]"
err "[ERROR] Set IMAGE_TAG in [${build_env_file}] and try again."
exit 1
fi
# Make all varaiables defined in build.env available as build args
while read -r varname || [[ -n "${varname}" ]]; do
build_args+=(--build-arg "${varname}=${!varname}")
done < <(grep -v -e '^#' -e '^$' "${build_env_file}" | cut -d '=' -f 1)
# If a conda environment template is specified, generate a populated version of the file to be copied into the image
conda_environment_template="${docker_context_dir}/${CONDA_ENVIRONMENT_TEMPLATE}"
if [[ -n "${CONDA_ENVIRONMENT_TEMPLATE}" ]] && [[ -s "${conda_environment_template}" ]]; then
populated_conda_environment=${docker_context_dir}/${IMAGE_NAME}.populated.yaml
log "Generating populated conda environment [${populated_conda_environment}]"
envsubst \
< "${conda_environment_template}" \
> "${populated_conda_environment}"
fi
# Add global build args provided on the command line
while read -r global_build_arg || [[ -n "${global_build_arg}" ]]; do
build_args+=(--build-arg "${global_build_arg}")
done < <(echo -n "${global_build_args}" | tr ',' '\n')
tagged_image="${CONTAINER_REGISTRY:+"${CONTAINER_REGISTRY}/"}${IMAGE_NAME}:${IMAGE_TAG}"
log "Building ${tagged_image}"
${DOCKER_BUILD_COMMAND} \
--rm \
"${build_args[@]}" \
"${LABEL_ARGS[@]+"${LABEL_ARGS[@]}"}" \
-t "${tagged_image}" \
-f "${dockerfile}" \
"${docker_context_dir}"
if [[ "${PUSH_IMAGES}" == 'true' ]]; then
log "Pushing ${tagged_image}"
docker push "${tagged_image}"
fi
)
}
LABEL_ARGS=()
while getopts "hd:c:pxb:r:l:" OPTION; do
case ${OPTION} in
h) usage; exit ;;
d) DOCKER_CONTEXT_DIR=${OPTARG} ;;
c) CONTAINER_REGISTRY=${OPTARG};;
p) PUSH_IMAGES='true' ;;
x) DOCKER_BUILD_COMMAND='docker buildx build --platform linux/amd64' ;;
b) GLOBAL_BUILD_ARGS=${OPTARG};;
r) RESOLVE_DIR=${OPTARG} ;;
l) LABEL_ARGS+=(--label "${OPTARG}") ;;
\?) usage; exit ;;
esac
done
if [[ -n "${RESOLVE_DIR:-}" ]]; then
if [[ ! -s "${RESOLVE_DIR}/build.env" ]]; then
refuse "[ERROR] -r needs a directory containing a build.env; ${RESOLVE_DIR} has none"
exit 1
fi
source_dir=$(resolve_definition_dir "${RESOLVE_DIR}/build.env")
printf 'BUILT_IN_SOURCE\t%s\n' "${source_dir}"
exit 0
fi
DOCKER_CONTEXT_DIR=${DOCKER_CONTEXT_DIR:-"${DEFAULT_DOCKER_CONTEXT_DIR}"}
PUSH_IMAGES=${PUSH_IMAGES:-'false'}
DOCKER_BUILD_COMMAND=${DOCKER_BUILD_COMMAND:-'docker build'}
GLOBAL_BUILD_ARGS=${GLOBAL_BUILD_ARGS:-}
readonly DOCKER_CONTEXT_DIR CONTAINER_REGISTRY PUSH_IMAGES DOCKER_BUILD_COMMAND GLOBAL_BUILD_ARGS
IMAGES_TO_BUILD=$(find "${DOCKER_CONTEXT_DIR}" -type f -name build.env | sort)
if [[ "${#IMAGES_TO_BUILD}" -eq 0 ]]; then
usage
exit
fi
# Resolve every build.env before building anything, so a pointer that cannot be followed
# stops the run before any image is built or pushed. Each source definition is listed once.
SOURCE_DIRS=""
while read -r build_env_file; do
source_dir=$(resolve_definition_dir "${build_env_file}")
case "${SOURCE_DIRS}" in
*$'\n'"${source_dir}"$'\n'*) continue ;;
esac
SOURCE_DIRS="${SOURCE_DIRS}"$'\n'"${source_dir}"$'\n'
done <<< "${IMAGES_TO_BUILD}"
while read -r source_dir; do
if [[ -z "${source_dir}" ]]; then
continue
fi
build_docker_image "${source_dir}/build.env" "${GLOBAL_BUILD_ARGS}"
done <<< "${SOURCE_DIRS}"