-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbuild-astra-image.sh
More file actions
executable file
·1687 lines (1502 loc) · 51.6 KB
/
build-astra-image.sh
File metadata and controls
executable file
·1687 lines (1502 loc) · 51.6 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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
## GNU bash, version 5.2.15(1)-release (x86_64-pc-linux-gnu)
## DESCRIPTION
## This script can create images based on Astra Linux (Debian-like system)
## To run you need to have docker.io and debootstrap. The following system
## versions are supported:
## 1.7.2, 1.7.3, 1.7.4, 1.7.5, 1.7.6, 1.7.7, 1.7.8, 1.7.9, 1.7.x (latest updated version),
## 1.8.1, 1.8.2, 1.8.3, 1.8.4, 1.8.x (latest updated version)
## EXAMPLE USAGE
## Help
## ./build-astra-image.sh -h
## Build specific image
## ./build-astra-image.sh -t 1.7.2 \
## -c 1.7_x86-64 \
## -r https://dl.astralinux.ru/astra/frozen/1.7_x86-64/1.7.2/repository \
## -i my-astra-image-name
## ISSUES & SOLUTIONS
## If image error like `contains vulnerabilities` - disable built-in vulnerability scanning (not recommended)
##
## Using a configuration file
##
## Execute `mkdir -p /etc/docker`
##
## Edit `/etc/docker/daemon.json`
##
## Paste below data(DEPRECATED 1.7.4-1.7.7 and 1.8.1-1.8.2):
## {
## "debug" : true,
## "astra-sec-level" : 6
## }
## Paste below data(>=1.7.8 and >=1.8.3)
## {
## "debug": true,
## "scan-on-image-create": false,
## "scan-on-container-start": false,
## "periodic-scan-time-in-hours": 0
## }
## Execute `systemctl restart docker`
## EXIT CODES
## 33:
## Bash not found
## 5:
## Help text was shown
## 127:
## Utility not found; you must install it because this script depends on it
## 128:
## Unsupported distribution version
## 129:
## Unknown platform arch
## Note: We first need to use POSIX's `[ ... ]' instead of Bash's `[[ ... ]]'
## because this is the check for Bash, where the shell may not be Bash. Once we
## confirm that we are in Bash, we can use [[ ... ]] and (( ... )). Note that
## these [[ ... ]] and (( ... )) do not cause syntax errors in POSIX shells,
## though they can be parsed differently.
if [ -z "${BASH_VERSION-}" ]; then
printf "[timestamp: %s] [level: ERROR] [file: $(basename "${0}")] %s\n" \
"$(date +%F' '%T)" "this program needs to be run - 'Bash'"
exit 33
fi
if [[ -z ${BASH_VERSINFO-} ]] || ((BASH_VERSINFO[0] < 5)); then
printf "[timestamp: %s] [level: ERROR] [file: $(basename "${0}")] %s\n" \
"$(date +%F' '%T)" "this program needs to be run by 'Bash >= 5.0'"
exit 33
fi
set -Eeo pipefail
## Check base variables before start
[[ -n ${PROGRAM} ]] || PROGRAM=$(basename "${0}")
[[ -n ${VERSION} ]] || VERSION="v$(<VERSION)"
## Define include device for tar options
[[ -n ${SCF_INCLUDE_DEV} ]] || SCF_INCLUDE_DEV=0
set -u
## Define global variables and make it unchanged
COMPANY_NAME='NGRSoftlab'
SCF_SYNTHETIC_TEST_ENABLE=0
BASEDIR="$(dirname "${0}")"
SCRIPT_PATH="$(cd "${BASEDIR}" && pwd)"
readonly PROGRAM VERSION COMPANY_NAME SCRIPT_PATH BASEDIR
##
## FUNCTIONS
##
#############################################
# Style format
# GLOBALS:
# none
# ARGUMENTS:
# $1, it is receive style format (int)
# OUTPUTS:
# Return to ANSI style with format \033[FORMAT;COLORm
#############################################
tty_escape() { printf "\033[%sm" "${1}"; }
#############################################
# Bold style colors
# GLOBALS:
# none
# ARGUMENTS:
# $1, it is receive color (int)
# OUTPUTS:
# Return to ANSI color with format \033[BOLD;COLORm
#############################################
tty_mkbold() { tty_escape "1;${1}"; }
#############################################
# Date format
# GLOBALS:
# none
# ARGUMENTS:
# none
# OUTPUTS:
# Return to dynamic actual date format YYYY-MM-DD HH:MM:SS
#############################################
logger_time() { date +%F' '%T; }
## Definite color variables
logger_tty_reset="$(tty_escape 0)"
logger_tty_red="$(tty_mkbold 31)"
logger_tty_green="$(tty_mkbold 32)"
logger_tty_yellow="$(tty_mkbold 33)"
logger_tty_blue="$(tty_mkbold 34)"
#############################################
# Print tab character
# GLOBALS:
# none
# ARGUMENTS:
# none
# OUTPUTS:
# Tab character
#############################################
logger_tty_tab() { printf "\t"; }
#############################################
## Log the given message at the given level
#############################################
# Log template for all received.
# All logs are written to stdout with a timestamp
# GLOBALS:
# none
# ARGUMENTS:
# $1, the level with specific color style
# $*, the message text
# RETURNS:
# 0 if 'levelname' is defined, 1 if not defined
# OUTPUTS:
# Write to stderr if error
#############################################
logger_template() {
local timestamp color tabs
timestamp=$(logger_time)
local levelname="${1}"
## Translation to the left side of the received log name argument
shift 1
## Define log level
case "${levelname^^}" in
"INFO")
color="${logger_tty_green}"
tabs=0
;;
"WARNING")
color="${logger_tty_yellow}"
tabs=0
;;
"ERROR")
color="${logger_tty_red}"
tabs=0
;;
*)
printf "[timestamp: %s] [level: %s] [file: %s] %s\n" \
"$(date +%F' '%T)" 'ERROR' "${PROGRAM}" \
"undefined log name" >&2
exit 1
;;
esac
## STDOUT
printf "%s %s %${tabs}s %s\n" \
"[timestamp ${logger_tty_blue}${timestamp}${logger_tty_reset}]" \
"[levelname ${color}${levelname}${logger_tty_reset}]" \
"$*"
## For those who remain, we pass on 0 code
return 0
}
#############################################
# Log the given message at level, INFO
# GLOBALS:
# none
# ARGUMENTS:
# $*, the info text to be printed
# OUTPUTS:
# Write message to stdout
#############################################
logger_info_message() {
local message="$*"
logger_template "INFO" "${message}"
}
#############################################
# Log the given message at level, WARNING
# GLOBALS:
# none
# ARGUMENTS:
# $*, the warning text to be printed
# OUTPUTS:
# Write message to stdout
#############################################
logger_warning_message() {
local message="$*"
logger_template "WARNING" "${message}"
}
#############################################
# Log the given message at level, ERROR
# GLOBALS:
# none
# ARGUMENTS:
# $*, the error text to be printed
# OUTPUTS:
# Write message to stdout
#############################################
logger_error_message() {
local message="$*"
logger_template "ERROR" "${message}" >&2
}
#############################################
# Log the given message at level, ERROR
# GLOBALS:
# none
# ARGUMENTS:
# $*, the fail text to be printed
# OUTPUTS:
# Write to stdout and exit with status 1
#############################################
logger_fail() {
logger_error_message "$*"
exit 1
}
#############################################
# Repeats a string a specified number of times
# GLOBALS:
# none
# ARGUMENTS:
# $1, string to repetitions (string)
# $2, number of repetitions (integer)
# RETURNS:
# 0 if thing was printed, non-zero on error
# OUTPUTS:
# Line with the number of specified repetitions
#############################################
__decor() {
local pattern="${1}"
local -i repeat="${2}"
seq -s"${pattern}" "${repeat}" | tr -d '[:digit:]'
}
#############################################
# Validate URL
# RATIONALITY TO USE:
# validate for ALMOST all URL (exclude IDN)
#
# if u want test IDN use this construction:
# `echo "пример.рф" | idn2`
#
# if u used difficult login and password
# with '@' '/' characters, then use this
# construction:
# `http://$(printf '%s' "$login:$password" | jq -sRr @uri)@example.com`
#
# this will ensure that the characters are
# not treated as stop characters by the regular expression mask,
# which could result in an return with a boolean false value
#
# GLOBALS:
# none
# ARGUMENTS:
# $@, list with url
# RETURNS:
# 0 if url(s) is valid, non-zero on error
#############################################
__validate_url() {
local url re domain domain_length
local -i error_count=0
## Schema
re='^(https?|ftp)://'
## Auth
re+='([^\/@]+(:([^\/@]|%[0-9a-fA-F]{2})*)?@)?'
## Domain
re+='(([a-zA-Z0-9-]{1,63}\.)+[a-zA-Z]{2,63}|'
## IPv4
re+='((25[0-5]|2[0-4][0-9]'
re+='|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|'
re+='[01]?[0-9][0-9]?)|'
## IPv6
re+='(\[(([a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}|'
re+='(:[a-fA-F0-9]{1,4}){1,7}|'
re+='[a-fA-F0-9]{1,4}(:[a-fA-F0-9]{1,4}){1,7}|'
re+='([a-fA-F0-9]{1,4}:){1,6}:[a-fA-F0-9]{1,4}|'
re+='([a-fA-F0-9]{1,4}:){1,5}(:[a-fA-F0-9]{1,4}){1,2}|'
re+='([a-fA-F0-9]{1,4}:){1,4}(:[a-fA-F0-9]{1,4}){1,3}|'
re+='([a-fA-F0-9]{1,4}:){1,3}(:[a-fA-F0-9]{1,4}){1,4}|'
re+='([a-fA-F0-9]{1,4}:){1,2}(:[a-fA-F0-9]{1,4}){1,5}|'
re+='[a-fA-F0-9]{1,4}:((:[a-fA-F0-9]{1,4}){1,6})|'
re+=':((:[a-fA-F0-9]{1,4}){1,7}|:)|'
re+='fe80:(:[a-fA-F0-9]{0,4}){0,4}%[0-9a-zA-Z]+|'
re+='::(ffff(:0{1,4})?:)?((25[0-5]|(2[0-4]|1?[0-9])?[0-9])\.){3}'
re+='(25[0-5]|(2[0-4]|1?[0-9])?[0-9])|([a-fA-F0-9]{1,4}:){1,4}'
re+=':((25[0-5]|(2[0-4]|1?[0-9])?[0-9])\.){3}(25[0-5]|(2[0-4]|1?[0-9])'
re+='?[0-9]))\]))'
## Port
re+='(:[0-9]{1,5})?'
## Path
re+='(\/[^[:space:]?#]*)?'
## Query
re+='(\?[^[:space:]#<>]*)?'
## Fragment
re+='(\#[^[:space:]]*)?$'
for url in "$@"; do
## Check main catch
[[ ${url} =~ ${re} ]] || {
: $((error_count++))
continue
}
## Check domain length
if [[ ${url} =~ ://([^/@:]+) ]]; then
domain=${BASH_REMATCH[1]%:*}
[[ -n ${domain} ]] || {
: $((error_count++))
continue
}
domain_length=${#domain}
if ((domain_length > 253)); then
: $((error_count++))
continue
fi
fi
done
return "${error_count}"
}
#############################################
# Check programs on exists
# GLOBALS:
# none
# ARGUMENTS:
# $@, packages list (array)
# RETURNS:
# 0 if all program exists, non-zero(127) on error
# OUTPUTS:
# Write to stderr if error
#############################################
__package_exists() {
local required_pkg
local -a pkg_list=("$@")
local pkg_missing="false"
for required_pkg in "${pkg_list[@]}"; do
if ! dpkg -l "${required_pkg}" >/dev/null 2>/dev/null; then
logger_error_message "please install package - '${required_pkg}'"
pkg_missing=true
fi
done
if "${pkg_missing}"; then
exit 127
fi
}
#############################################
# Trap function
# GLOBALS:
# HOME
# ROOTFS_DIR
# ARGUMENTS:
# none
# OUTPUTS:
# Trap any exit signal and write to stdout
#############################################
# shellcheck disable=SC2317
__cleanup() {
logger_warning_message "received EXIT signal"
## Change directory
logger_info_message "back to ${HOME}"
pushd "${HOME}" >/dev/null || true
## Debootstrap leaves mounted /proc and /sys folders in chroot
logger_info_message "unmount existing folders"
umount "${ROOTFS_DIR}/proc" "${ROOTFS_DIR}/sys" >/dev/null 2>/dev/null \
|| true
## Remove temp dir
logger_info_message "cleanup temp files"
rm -r "${ROOTFS_DIR}"
}
#############################################
# Check platform type
# GLOBALS:
# SCF_PLATFORM
# ARGUMENTS:
# none
# RETURNS:
# 0 if platform is arm or aarch64, non-zero if its not
#############################################
__use_qemu_static() {
[[ ${SCF_PLATFORM} == "arm64" &&
! ("$(uname -m)" == *arm* || "$(uname -m)" == *aarch64*) ]]
}
#############################################
# Root filesystem exec
# GLOBALS:
# ROOTFS_DIR
# PATH
# LANG
# LC_ALL
# TZ
# MALLOC_ARENA_MAX
# ARGUMENTS:
# $@, command list (array)
# OUTPUTS:
# Write to stdout
#############################################
__rootfs_chroot() {
## Get path to "chroot" in our current PATH
local chroot_path
chroot_path="$(type -P chroot)"
## "chroot" doesn't set PATH, so we need to set it explicitly
## to something our new debootstrap chroot can use appropriately
## Set PATH, locale, timezone, memory allocation and chroot
PATH='/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin' \
LANG=C.UTF-8 \
LC_ALL=C.UTF-8 \
TZ=Etc/UTC \
MALLOC_ARENA_MAX=2 \
"${chroot_path}" \
"${ROOTFS_DIR}" "$@"
}
#############################################
# Calculate timestamp of fresh packages lists
# GLOBALS:
# ROOTFS_DIR
# BUILD_DATE
# ARGUMENTS:
# none
# RETURNS:
# Most recent timestamp that a package in the image was changed(BUILD_DATE)
# OUTPUTS:
# Write total date to stdout
#############################################
__calculate_build_data() {
local file
## https://til.simonwillison.net/bash/nullglob-in-bash
trap '$(shopt -p nullglob)' RETURN
shopt -s nullglob
BUILD_DATE=''
local -a release_files=("${ROOTFS_DIR}"/var/lib/apt/lists/*_{In,}Release)
[[ ${#release_files[@]} -ne 0 ]] || {
logger_error_message \
"no 'Release' files found at /var/lib/apt/lists in '${ROOTFS_DIR}'"
logger_fail \
"did you forget to populate 'sources.list' or run 'apt-get update' first?"
}
## Capture the most recent date that a package in the image was changed
## We don't care about the particular date, or which package it comes from,
## we just need a date that isn't very far in the past
local build_date_changelog
build_date_changelog="$(
__rootfs_chroot find "/usr/share/doc" -name changelog.Debian.gz -print0 \
| while IFS= read -r -d '' file; do
if [[ -s ${file} ]] && gunzip -c "${file}" 2>/dev/null \
| grep -q "^.* .* .* .*"; then
gunzip -c "${file}" 2>/dev/null \
| dpkg-parsechangelog -SDate -l- 2>/dev/null \
|| true
fi
done \
| xargs -I{} date --date="{}" +%s 2>/dev/null \
| sort -n \
| tail -n 1 || printf ''
)"
## Capture almost recent date from packages list
local build_date_lists
build_date_lists="$(
awk -F ': ' '$1 == "Date" { printf "%s%c", $2, 0 }' "${release_files[@]}" \
| xargs -r0n1 date '+%s' --date \
| sort -un \
| tail -1 || printf ''
)"
## Check what we return
if [[ -z ${build_date_changelog} && -n ${build_date_lists} ]]; then
BUILD_DATE="${build_date_lists}"
elif [[ -n ${build_date_changelog} && -z ${build_date_lists} ]]; then
BUILD_DATE="${build_date_changelog}"
elif [[ -n ${build_date_changelog} && -n ${build_date_lists} ]]; then
[[ ${build_date_changelog} -gt ${build_date_lists} ]] \
|| BUILD_DATE="${build_date_lists}"
[[ ${build_date_changelog} -lt ${build_date_lists} ]] \
|| BUILD_DATE="${build_date_changelog}"
fi
logger_info_message "total date is: '$(date -d @"${BUILD_DATE}")'"
export BUILD_DATE
}
#############################################
# Add tweaks for compare image w/ small size
# GLOBALS:
# ROOTFS_DIR
# ARGUMENTS:
# none
# OUTPUTS:
# Write message per tweak to stdout
#############################################
__docker_tweaks() {
local slim_include slim_exclude dpkg_output
logger_info_message "applying docker-specific tweaks"
## These are copied from the docker contrib/mkimage/debootstrap script
## MODIFICATIONS:
## - remove `strings` check for applying the --force-unsafe-io tweak
## This was sometimes wrongly detected as not applying, and we aren't
## interested in building versions that this guard would apply to,
## so simply apply the tweak unconditionally
## Prevent init scripts from running during install/update
logger_info_message "+ echo exit 101 >'${ROOTFS_DIR}/usr/sbin/policy-rc.d'"
cat >"${ROOTFS_DIR}/usr/sbin/policy-rc.d" <<-'EOF'
#!/bin/sh
# For most Docker users, "apt-get install" only happens during "docker build",
# where starting services doesn't work and often fails in humorous ways. This
# prevents those failures by stopping the services from attempting to start
exit 101
EOF
chmod +x "${ROOTFS_DIR}/usr/sbin/policy-rc.d"
## Prevent upstart scripts from running during install/update
(
set -x
__rootfs_chroot dpkg-divert --local --rename --add /sbin/initctl
cp -a "${ROOTFS_DIR}/usr/sbin/policy-rc.d" "${ROOTFS_DIR}/sbin/initctl"
sed -i 's/^exit.*/exit 0/' "${ROOTFS_DIR}/sbin/initctl"
)
## Shrink a little, since apt makes us cache-fat (wheezy: ~157.5MB vs ~120MB)
(
set -x
__rootfs_chroot apt-get clean
)
## This file is one APT creates to make sure we don't "autoremove"
## our currently in-use kernel, which doesn't really apply to
## debootstraps/Docker images that don't even have kernels installed
rm -f "${ROOTFS_DIR}/etc/apt/apt.conf.d/01autoremove-kernels"
## Force dpkg not to call sync() after package extraction
## (speeding up installs)
logger_info_message \
"+ echo force-unsafe-io >" \
"'${ROOTFS_DIR}/etc/dpkg/dpkg.cfg.d/docker-apt-speedup'"
cat >"${ROOTFS_DIR}/etc/dpkg/dpkg.cfg.d/docker-apt-speedup" <<-'EOF'
# For most Docker users, package installs happen during "docker build", which
# doesn't survive power loss and gets restarted clean afterwards anyhow, so
# this minor tweak gives us a nice speedup (much nicer on spinning disks,
# obviously)
force-unsafe-io
EOF
## Attach base info about build version
logger_info_message \
"attach exclude and include list >" \
"'${ROOTFS_DIR}/etc/dpkg/dpkg.cfg.d/docker'"
cat >"${ROOTFS_DIR}/etc/dpkg/dpkg.cfg.d/docker" <<-'EOF'
# This is the "slim" variant of the Debian base image
# Many files which are normally unnecessary in containers are excluded,
# and this configuration file keeps them that way
EOF
# https://github.com/debuerreotype/debuerreotype/issues/10
local -a extra_special_directories=()
mapfile -t extra_special_directories < <(find \
"${ROOTFS_DIR}"/usr/share/man -maxdepth 1 -type d -name 'man[0-9]')
local oldifs="${IFS}"
IFS=$'\n'
set -o noglob
local -a slim_excludes=()
mapfile -t slim_excludes < <(grep -vE '^#|^$' \
"${SCRIPT_PATH}/lists/.slimify-excludes" | sort -u)
local -a slim_includes=()
mapfile -t slim_includes < <(grep -vE '^#|^$' \
"${SCRIPT_PATH}/lists/.slimify-includes" | sort -u)
set +o noglob
unset IFS
IFS="${oldifs}"
## Filling docker configure file
local -a find_match_includes=()
for slim_include in "${slim_includes[@]}"; do
[[ ${#find_match_includes[@]} -eq 0 ]] || find_match_includes+=('-o')
find_match_includes+=(-path "${slim_include}")
done
find_match_includes=('(' "${find_match_includes[@]}" ')')
for slim_exclude in "${slim_excludes[@]}"; do
{
echo
printf '%s\n' "# dpkg -S '${slim_exclude}'"
if dpkg_output="$(__rootfs_chroot dpkg -S "${slim_exclude}" 2>&1)"; then
printf '%s\n' "${dpkg_output}" \
| sed 's/: .*//g; s/, /\n/g' | sort -u | xargs
else
printf '%s\n' "${dpkg_output}"
fi | fold -w 76 -s | sed 's/^/# /'
printf '%s\n' "path-exclude ${slim_exclude}"
} >>"${ROOTFS_DIR}/etc/dpkg/dpkg.cfg.d/docker"
if [[ ${slim_exclude} == *'/*' ]]; then
if [[ -d "${ROOTFS_DIR}/$(dirname "${slim_exclude}")" ]]; then
## Use two passes so that we don't fail trying
## to remove directories from ${slim_include}
## This is our best effort at implementing in shell
## https://sources.debian.net/src/dpkg/stretch/src/filters.c/#L96-L97
## Step 1 -- delete everything that doesn't match "${slim_include}"
## and isn't a directory or a symlink
__rootfs_chroot \
find "$(dirname "${slim_exclude}")" \
-depth -mindepth 1 \
-not \( -type d -o -type l \) \
-not "${find_match_includes[@]}" \
-exec rm -f '{}' ';'
## Step 2 -- repeatedly delete any dangling symlinks and empty
## directories until there aren't any (might have a dangling symlink in
## a directory which then makes it empty, or a symlink to an
## empty directory)
while [[ "$(
__rootfs_chroot \
find "$(dirname "${slim_exclude}")" \
-depth -mindepth 1 \( -empty -o -xtype l \) \
-exec rm -rf '{}' ';' -printf '.' \
| wc -c
)" -gt 0 ]]; do true; done
fi
else
__rootfs_chroot rm -f "${slim_exclude}"
fi
done
{
echo
for slim_include in "${slim_includes[@]}"; do
printf '%s\n' "path-include ${slim_include}"
done
} >>"${ROOTFS_DIR}/etc/dpkg/dpkg.cfg.d/docker"
chmod 0644 "${ROOTFS_DIR}/etc/dpkg/dpkg.cfg.d/docker"
## https://github.com/debuerreotype/debuerreotype/issues/10
if [[ ${#extra_special_directories[@]} -gt 0 ]]; then
mkdir -p "${extra_special_directories[@]}"
fi
if [[ -d "${ROOTFS_DIR}/etc/apt/apt.conf.d" ]]; then
## _keep_ us lean by effectively running "apt-get clean" after every install
local apt_get_clean='"rm -f /var/cache/apt/archives/*.deb /var/cache/apt/archives/partial/*.deb /var/cache/apt/*.bin || true";'
logger_info_message \
"+ cat > '${ROOTFS_DIR}/etc/apt/apt.conf.d/docker-clean'"
cat >"${ROOTFS_DIR}/etc/apt/apt.conf.d/docker-clean" <<-EOF
# Since for most Docker users, package installs happen in "docker build" steps,
# they essentially become individual layers due to the way Docker handles
# layering, especially using CoW filesystems. What this means for us is that
# the caches that APT keeps end up just wasting space in those layers, making
# our layers unnecessarily large (especially since we'll normally never use
# these caches again and will instead just "docker build" again and make a brand
# new image)
# Ideally, these would just be invoking "apt-get clean", but in our testing,
# that ended up being cyclic and we got stuck on APT's lock, so we get this fun
# creation that's essentially just "apt-get clean"
DPkg::Post-Invoke { ${apt_get_clean} };
APT::Update::Post-Invoke { ${apt_get_clean} };
Dir::Cache::pkgcache "";
Dir::Cache::srcpkgcache "";
# Note that we do realize this isn't the ideal way to do this, and are always
# open to better suggestions (https://github.com/docker/docker/issues)
EOF
## Remove apt-cache translations for fast "apt-get update"
logger_info_message \
"+ echo Acquire::Languages 'none' >" \
"'${ROOTFS_DIR}/etc/apt/apt.conf.d/docker-no-languages'"
cat >"${ROOTFS_DIR}/etc/apt/apt.conf.d/docker-no-languages" <<-'EOF'
# In Docker, we don't often need the "Translations" files, so we're just wasting
# time and space by downloading them, and this inhibits that. For users that do
# need them, it's a simple matter to delete this file and "apt-get update"
Acquire::Languages "none";
EOF
logger_info_message \
"+ echo Acquire::GzipIndexes 'true' >" \
"'${ROOTFS_DIR}/etc/apt/apt.conf.d/docker-gzip-indexes'"
cat >"${ROOTFS_DIR}/etc/apt/apt.conf.d/docker-gzip-indexes" <<-'EOF'
# Since Docker users using "RUN apt-get update && apt-get install -y ..." in
# their Dockerfiles don't go delete the lists files afterwards, we want them to
# be as small as possible on-disk, so we explicitly request "gz" versions and
# tell Apt to keep them gzipped on-disk
# For comparison, an "apt-get update" layer without this on a pristine
# "debian:wheezy" base image was "29.88 MB", where with this it was only
# "8.273 MB"
Acquire::GzipIndexes "true";
Acquire::CompressionTypes::Order:: "gz";
EOF
## Update "autoremove" configuration to be aggressive about removing
## suggests deps that weren't manually installed
logger_info_message \
"+ echo Apt::AutoRemove::SuggestsImportant 'false' >" \
"'${ROOTFS_DIR}/etc/apt/apt.conf.d/docker-autoremove-suggests'"
cat >"${ROOTFS_DIR}/etc/apt/apt.conf.d/docker-autoremove-suggests" <<-'EOF'
# Since Docker users are looking for the smallest possible final images, the
# following emerges as a very common pattern:
# RUN apt-get update \
# && apt-get install -y <packages> \
# && <do some compilation work> \
# && apt-get purge -y --auto-remove <packages>
# By default, APT will actually _keep_ packages installed via Recommends or
# Depends if another package Suggests them, even and including if the package
# that originally caused them to be installed is removed. Setting this to
# "false" ensures that APT is appropriately aggressive about removing the
# packages it added
# https://aptitude.alioth.debian.org/doc/en/ch02s05s05.html#configApt-AutoRemove-SuggestsImportant
Apt::AutoRemove::SuggestsImportant "false";
EOF
fi
## Create package install script for additional install
## use in image `install_packages nginx`
cat >"${ROOTFS_DIR}/usr/sbin/install_packages" <<-'EOF'
#!/bin/sh
set -e
set -u
export DEBIAN_FRONTEND=noninteractive
n=0
max=2
until [ $n -gt $max ]; do
set +e
(
apt-get update -qq &&
apt-get install -y --no-install-recommends "$@"
)
CODE=$?
set -e
if [ $CODE -eq 0 ]; then
break
fi
if [ $n -eq $max ]; then
exit $CODE
fi
echo "apt failed, retrying"
n=$(($n + 1))
done
rm -r /var/lib/apt/lists /var/cache/apt/archives
EOF
chmod 0755 "${ROOTFS_DIR}/usr/sbin/install_packages"
## Set the password change date to a fixed date, otherwise it
## defaults to the current date, so we get a different image every day
## SOURCE_DATE_EPOCH is designed to do this, but was only implemented
## recently, so we can't rely on it for all versions we want to build. We
## also have to copy over the backup at /etc/shadow- so that it doesn't change
__rootfs_chroot \
getent passwd \
| cut -d: -f1 \
| xargs -n 1 chroot "${ROOTFS_DIR}" chage -d 17885 \
&& cp "${ROOTFS_DIR}/etc/shadow" "${ROOTFS_DIR}/etc/shadow-"
}
#############################################
# Remove cache and mess docs
# GLOBALS:
# ROOTFS_DIR
# ARGUMENTS:
# none
# OUTPUTS:
# Write total package size to stdout
#############################################
__remove_cache() {
local dir
## Clean /etc/hostname and /etc/resolv.conf as they are based on the
## current env, so make the chroot different
## Docker doesn't care about them, as it fills them when starting a container
printf '%s' "" >"${ROOTFS_DIR}/etc/resolv.conf"
printf '%s' "host" >"${ROOTFS_DIR}/etc/hostname"
local -a dirs_to_trim=(
"/var/cache/apt"
"/var/lib/apt/lists"
"/var/log"
)
if [[ ${#dirs_to_trim[@]} -gt 0 ]]; then
for dir in "${dirs_to_trim[@]}"; do
logger_info_message "trimming down '${dir}'"
# shellcheck disable=SC2115
rm -r "${ROOTFS_DIR}/${dir}"/*
done
fi
## https://www.freedesktop.org/software/systemd/man/machine-id.html
## For operating system images which are created once and used
## on multiple machines, for example for containers or in the cloud,
## /etc/machine-id should be either missing
## or an empty file in the generic file system image
if [[ -s ${ROOTFS_DIR}/etc/machine-id ]]; then
printf '%s' "" >"${ROOTFS_DIR}/etc/machine-id"
chmod 0644 "${ROOTFS_DIR}/etc/machine-id"
fi
## Remove the aux-cache as it isn't reproducible
## It doesn't seem to cause any problems to remove it
rm "${ROOTFS_DIR}/var/cache/ldconfig/aux-cache"
## Remove /usr/share/doc, but leave copyright files to be sure that we
## comply with all licenses
## `mindepth 2` as we only want to remove files within the per-package
## directories. Crucially some packages use a symlink to another package
## dir (e.g. libgcc1), and we don't want to remove those
find "${ROOTFS_DIR}/usr/share/doc" \
-mindepth 2 \
-not -name copyright \
-not -type d -delete
find "${ROOTFS_DIR}/usr/share/doc" \
-mindepth 1 \
-type d -empty -delete
## https://github.com/debuerreotype/debuerreotype/pull/32
rm -f "${ROOTFS_DIR}/run/mount/utab"
## (also remove the directory, but only if it's empty)
rmdir "${ROOTFS_DIR}/run/mount" 2>/dev/null || :
## Set the mtime on all files to be no older than ${BUILD_DATE}
## This is required to have the same metadata on files so that the
## same tarball is produced. We assume that it is not important
## that any file have a newer mtime than this
[[ -z ${BUILD_DATE} ]] \
|| find "${ROOTFS_DIR}" \
-depth -newermt "@${BUILD_DATE}" \
-print0 \
| xargs -0r touch --no-dereference --date="@${BUILD_DATE}"
logger_info_message "total size: $(du -skh "${ROOTFS_DIR}")"
## These aren't shell variables, this is a template for DPKG packages
logger_info_message "package sizes:"
__rootfs_chroot dpkg-query -W -f "\${Package} \${Installed-Size}\n"
## Calculate dir sizes
logger_info_message "largest dirs:"
printf '%s\n' "$(du "${ROOTFS_DIR}" | sort -n | tail -n 20)"
logger_info_message "build into: '${ROOTFS_DIR}' path"
if __use_qemu_static; then
logger_info_message "cleaning up qemu static files from image"
local usr_bin_modification_time
usr_bin_modification_time=$(stat -c %y "${ROOTFS_DIR}"/usr/bin)
rm -rf "${ROOTFS_DIR}"/usr/bin/qemu-*-static
touch -d "${usr_bin_modification_time}" "${ROOTFS_DIR}"/usr/bin
fi
}
#############################################
# Set 'tar' options list
# GLOBALS:
# ROOTFS_DIR
# SCF_INCLUDE_DEV
# SCRIPT_PATH
# ARGUMENTS:
# $1, archive name
# RETURNS:
# export 'tar' args variable(TAR_ARGS)
#############################################
__set_tar_opts() {
local archive_name="${1}"
TAR_ARGS=()
local apt_version exclude
apt_version="$(__rootfs_chroot \
dpkg-query --show --showformat "\${Version}\n" "apt")"
local -a excludes=()
## if APT is new enough to auto-recreate "partial" directories, let it
## https://salsa.debian.org/apt-team/apt/commit/1cd1c398d18b78f4aa9d882a5de5385f4538e0be
if dpkg --compare-versions "${apt_version}" '>=' '0.8~'; then
excludes+=(
'./var/cache/apt/**'
'./var/lib/apt/lists/**'
'./var/state/apt/lists/**'
)
## see also the targeted exclusions in ".tar-exclude"
## that these are overriding
fi
## Define base args
TAR_ARGS=(
--create
--file "${archive_name}"
--auto-compress
--directory "${ROOTFS_DIR}"
--exclude-from "${SCRIPT_PATH}/lists/.tar-exclude"
)
## If define include devices then not exclude then
[[ ${SCF_INCLUDE_DEV} -eq 1 ]] || excludes+=('./dev/**')
for exclude in "${excludes[@]}"; do
TAR_ARGS+=(--exclude "${exclude}")
done
## Append side arguments
TAR_ARGS+=(
--numeric-owner
--transform 's,^./,,'
--sort name
.
)
export TAR_ARGS
}
#############################################
# Import custom image with created manifest, return image id
# GLOBALS:
# TARGET
# CONF_TEMPLATE
# SCF_PLATFORM
# TIMESTAMP
# COMPANY_NAME
# MANIFEST_TEMPLATE
# ARGUMENTS:
# none
# RETURNS:
# Image ID
#############################################
__import() {
local layer_sum tempdir configuration conf_sha manifest id
layer_sum="$(sha256sum "${TARGET}" | awk '{print $1}')"
tempdir="$(mktemp -d)"
mkdir -p "${tempdir}/${layer_sum}"
cp "${TARGET}" "${tempdir}/${layer_sum}/layer.tar"
printf '%s' '1.0' >"${tempdir}/${layer_sum}/VERSION"
configuration="$(printf '%s' "${CONF_TEMPLATE}" \
| sed \
-e "s/%SCF_PLATFORM%/${SCF_PLATFORM}/g" \
-e "s/%TIMESTAMP%/${TIMESTAMP}/g" \
-e "s/%LAYERSUM%/${layer_sum}/g" \
-e "s/%COMPANY_NAME%/${COMPANY_NAME}/g")"
conf_sha="$(printf '%s' "${configuration}" | sha256sum | awk '{print $1}')"
printf '%s' "${configuration}" >"${tempdir}/${conf_sha}.json"
manifest="$(printf '%s' "${MANIFEST_TEMPLATE}" \
| sed \