221c1edb2ff829dc73bb21eca120b2fd78200707
[ci-management.git] / docker / scripts / lib_csit.sh
1 # lib_csit.sh - Docker build script CSIT library.
2 #               For import only.
3
4 # Copyright (c) 2021 Cisco and/or its affiliates.
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at:
8 #
9 #     http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # Don't import more than once.
18 if [ -n "$(alias lib_csit_imported 2> /dev/null)" ] ; then
19     return 0
20 fi
21 alias lib_csit_imported=true
22
23 export CIMAN_DOCKER_SCRIPTS="${CIMAN_DOCKER_SCRIPTS:-$(dirname $BASH_SOURCE)}"
24 . "$CIMAN_DOCKER_SCRIPTS/lib_common.sh"
25 . "$CIMAN_DOCKER_SCRIPTS/lib_apt.sh"
26 . "$CIMAN_DOCKER_SCRIPTS/lib_yum.sh"
27 . "$CIMAN_DOCKER_SCRIPTS/lib_dnf.sh"
28
29 CSIT_SUPPORTED_EXECUTOR_CLASSES="builder csit_dut"
30 csit_supported_executor_class() {
31     if ! grep -q "${1:-}" <<< "$CSIT_SUPPORTED_EXECUTOR_CLASSES" ; then
32         return 1
33     fi
34     return 0
35 }
36
37 csit_supported_os() {
38     case "$1" in
39         # TODO: Remove ubuntu-18.04 once CSIT has completed transition
40         #       to ubuntu-20.04
41         ubuntu-18.04) return 0 ;;
42         ubuntu-20.04) return 0 ;;
43                    *) ;;
44     esac
45     return 1
46 }
47
48 csit_checkout_branch_for_vpp() {
49     local vpp_branch="$1"
50     local csit_dir="$DOCKER_CSIT_DIR"
51     local csit_bash_function_dir="$csit_dir/resources/libraries/bash/function"
52
53     # import checkout_csit_for_vpp() if not defined
54     set +e && [ -z "$(declare -f checkout_csit_for_vpp)" ] \
55         && source "$csit_bash_function_dir/branch.sh"
56     CSIT_DIR="$csit_dir" checkout_csit_for_vpp "$vpp_branch"
57
58     csit_branch="$(git branch | grep -e '^*' | mawk '{print $2}')"
59 }
60
61 csit_install_packages() {
62     local branch="$1"
63     local branchname="$(echo $branch | sed -e 's,/,_,')"
64     local csit_dir="$DOCKER_CSIT_DIR"
65     local csit_ansible_dir="$csit_dir/fdio.infra.ansible"
66     local bld_log="$DOCKER_BUILD_LOG_DIR/$FDIOTOOLS_IMAGENAME"
67     bld_log="${bld_log}-$branchname-csit_install_packages-bld.log"
68
69     git clean -qfdx
70
71     # Install PyYAML required by dbld_csit_find_ansible_packages.py
72     #
73     # Note: Conditional install due to Bug 1696324 -
74     #       Update to python3.6 breaks PyYAML dependencies
75     # Status:       CLOSED CANTFIX
76     # https://bugzilla.redhat.com/show_bug.cgi?id=1696324
77     if [ "$OS_NAME" = "centos-8" ] ; then
78         dnf_install_packages python3-pyyaml
79     else
80         python3 -m pip install pyyaml
81     fi
82
83     local exclude_roles="-e calibration -e kernel -e mellanox -e nomad -e consul"
84     [ "$OS_ARCH" = "aarch64" ] && exclude_roles="$exclude_roles -e iperf"
85
86     # Not in double quotes to let bash remove newline characters
87     local yaml_files="$(grep -r packages_by $csit_ansible_dir | cut -d: -f1 | sort -u | grep -v $exclude_roles)"
88     packages="$(dbld_csit_find_ansible_packages.py --$OS_ID --$OS_ARCH $yaml_files)"
89     packages="${packages/bionic /}"
90     packages="${packages/focal /}"
91
92     # TODO: Fix Ubuntu-18.04 specific package names that fail on Ubuntu-20.04
93     #       (remove when CSIT is updated)
94     if [ "$OS_NAME" = "ubuntu-20.04" ] ; then
95         packages="${packages/libmbedcrypto1/libmbedcrypto3}"
96         packages="${packages/libmbedtls10/libmbedtls12}"
97         packages="$(echo ${packages//python\-/python3\-} | tr ' ' '\n' | sort -u | xargs)"
98     fi
99     if [ -n "$packages" ] ; then
100         case "$OS_NAME" in
101             ubuntu*)
102                 apt_install_packages $packages
103                 ;;
104             debian*)
105                 apt_install_packages $packages
106                 ;;
107             centos-7)
108                 yum_install_packages $packages
109                 ;;
110             centos-8)
111                 dnf_install_packages $packages
112                 ;;
113             *)
114                 echo "Unsupported OS ($OS_ID): CSIT packages NOT INSTALLED!"
115                 ;;
116         esac
117     fi
118 }
119
120 csit_pip_cache() {
121     local branch="$1"
122     local VENV_OPTS=""
123     # ensure PS1 is defined (used by virtualenv activate script)
124     PS1=${PS1:-"#"}
125     CSIT_DIR="$DOCKER_CSIT_DIR"
126
127     if [ -f "$CSIT_DIR/VPP_REPO_URL" ] \
128            && [ -f "$CSIT_DIR/requirements.txt" ]; then
129
130         local csit_bash_function_dir="$CSIT_DIR/resources/libraries/bash/function"
131         local branchname="$(echo $branch | sed -e 's,/,_,')"
132         local bld_log="$DOCKER_BUILD_LOG_DIR"
133         bld_log="${bld_log}/$FDIOTOOLS_IMAGENAME-$branchname-csit_pip_cache-bld.log"
134         local pip_cmd="python3 -m pip --disable-pip-version-check"
135         export PYTHONPATH=$CSIT_DIR
136
137         description="Install CSIT python packages from $branch branch"
138         echo_log "    Starting  $description..."
139         git clean -qfdx
140         rm -rf "$PYTHONPATH/env"
141
142         # TODO: Update CSIT release branches to avoid build breakage
143         #       Fixes https://github.com/pypa/pip/issues/8260
144         $pip_cmd install pip==21.0.1
145         #       rls2009_lts-* branches missing cherry-pick of
146         #       https://gerrit.fd.io/r/c/csit/+/31338
147         sed -i 's/scipy==1.1.0/scipy==1.5.4/' "$PYTHONPATH/requirements.txt"
148
149         # Virtualenv version is pinned in common.sh in newer csit branches.
150         # (note: xargs removes leading/trailing spaces)
151         local common_sh="$csit_bash_function_dir/common.sh"
152         install_virtualenv="$(grep 'virtualenv' $common_sh | grep pip | grep install | cut -d'|' -f1 | xargs)"
153         $install_virtualenv
154         virtualenv --no-download --python=$(which python3) "$CSIT_DIR/env"
155         source "$CSIT_DIR/env/bin/activate"
156
157         if [ "$OS_ARCH" = "aarch64" ] ; then
158             local numpy_ver="$(grep numpy $PYTHONPATH/requirements.txt)"
159             [ -n "$numpy_ver" ] && $pip_cmd install $numpy_ver 2>&1 | \
160                 tee -a $bld_log
161         fi
162
163         # Install csit python requirements
164         $pip_cmd install -r "$CSIT_DIR/requirements.txt" 2>&1 | \
165             tee -a "$bld_log"
166         # Install tox python requirements
167         $pip_cmd install -r "$CSIT_DIR/tox-requirements.txt" 2>&1 | \
168             tee -a "$bld_log"
169         # Run tox which installs pylint requirments
170         pushd $CSIT_DIR >& /dev/null
171         tox || true
172         popd >& /dev/null
173
174         # Clean up virtualenv directories
175         deactivate
176         git checkout -q -- .
177         git clean -qfdx
178         echo_log "    Completed $description!"
179     else
180         echo_log "ERROR: Missing or invalid CSIT_DIR: '$CSIT_DIR'!"
181         return 1
182     fi
183 }
184
185 docker_build_setup_csit() {
186     if csit_supported_executor_class "$EXECUTOR_CLASS" ; then
187         if [ ! -d "$DOCKER_CSIT_DIR" ] ; then
188             echo_log "Cloning CSIT into $DOCKER_CSIT_DIR..."
189             git clone -q https://gerrit.fd.io/r/csit "$DOCKER_CSIT_DIR"
190         fi
191         clean_git_repo "$DOCKER_CSIT_DIR"
192     fi
193 }
194
195 csit_dut_generate_docker_build_files() {
196     local build_files_dir="$DOCKER_BUILD_FILES_DIR"
197
198     mkdir -p "$build_files_dir"
199     cat <<EOF >"$build_files_dir/supervisord.conf"
200 [unix_http_server]
201 file = /tmp/supervisor.sock
202 chmod = 0777
203
204 [rpcinterface:supervisor]
205 supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface
206
207 [supervisorctl]
208 serverurl = unix:///tmp/supervisor.sock
209
210 [supervisord]
211 pidfile = /tmp/supervisord.pid
212 identifier = supervisor
213 directory = /tmp
214 logfile = /tmp/supervisord.log
215 loglevel = debug
216 nodaemon = false
217
218 [program:vpp]
219 command = /usr/bin/vpp -c /etc/vpp/startup.conf
220 autostart = false
221 autorestart = true
222 redirect_stderr = true
223 priority = 1
224 EOF
225 }
226
227 csit_builder_generate_docker_build_files() {
228     local build_files_dir="$DOCKER_BUILD_FILES_DIR"
229     local dashes="-----"
230     local dbeg="${dashes}BEGIN"
231     local dend="${dashes}END"
232     local pvt="PRIVATE"
233     local kd="KEY$dashes"
234
235     # TODO: Verify why badkey is required & figure out how to avoid it.
236     mkdir -p "$build_files_dir"
237     cat <<EOF >"$build_files_dir/badkey"
238 $dbeg RSA $pvt $kd
239 MIIEowIBAAKCAQEAslDXf4kZOQI8OGQQdIF8o83nBM0B4fzHLYLxxiY2rKiQ5MGM
240 mQa7p1KKzmd5/NlvFRnXefnjSDQljjPxEY7mh457rX2nXvqHD4GUXZPpBIE73rQ1
241 TViIAXdDzFXJ6ee4yX8ewmVakzYBnlUPDidkWyRnjm/xCgKUCO+CD5AH3ND0onks
242 OYAtHqhDh29/QMIKdMnK87FBxfzhInHwpqPur76zBnpw3u36ylKEymDFrO5dwzsh
243 QvDWjsYRg9ydTXubtwP6+MOpjdR1SNKxcCHKJrPrdAeJW9jg1imYmYpEHZ/P3qsL
244 Jm0hGWbFjdxZLIYIz0vN/nTalcAeqT2OWKrXuwIDAQABAoIBAQCcj1g2FOR9ZlYD
245 WPANqucJVy4/y9OcXHlwnyiyRjj47WOSRdGxRfUa2uEeikHT3ACo8TB8WwfQDGDw
246 8u/075e+az5xvAJo5OQSnD3sz4Hmv6UWSvkFuPZo+xMe5C/M2/QljiQuoBifaeqP
247 3rTCQ5ncYCFAMU7b8BmTot551Ybhu2jCbDMHU7nFHEFOvYinkwfVcaqkrVDUuH+D
248 c3NkAEH9Jz2MEYA2Va4uqFpGt5lfGiED2kMenwPa8eS5LS5HJsxkfMHGlaHXHFUb
249 D+dG/qJtSslVxdzVPgEGvzswo6TgtY1nZTQcB8U63rktFg38B7QGtOkvswAYzxyk
250 HdMIiU3RAoGBAOdIEQRcAThj9eiIFywtBgLBOSg4SoOnvELLr6lgUg2+ICmx06LQ
251 yaai1QRdOWw1VwZ6apNCD00kaUhBu+ou93yLSDnR2uYftkylhcnVuhDyIeNyb81V
252 hV2z0WuNv3aKBFlBxaq391S7WW1XxhpAAagm8fZZur73wV390EVd/hZJAoGBAMVf
253 negT2bg5PVKWvsiEU6eZ00W97tlEDLclkiZawXNnM2/c+2x1Tks6Yf1E/j2FFTB4
254 r0fesbwN346hCejtq5Bup5YEdFA3KtwT5UyeQQLFGYlCtRmBtOd10wkRS93D0tpX
255 iIqkf43Gpx6iFdvBWY5A7N+ZmojCy9zpL5TJ4G3jAoGADOGEoRuGrd9TWMoLkFhJ
256 l2mvhz/rVn3HDGlPtT06FK3cGLZgtRavxGoZNw8CHbayzBeRS/ZH5+H5Qx72GkrX
257 WcZgFWhMqrhlbMtjMiSHIl556LL86xCyRs+3ACh6211AdMAnBCUOz1dH2cEjtV6P
258 ORBCNZg1wGEIEfYK3XIorpECgYBubXfQj8KhUs0fdx3Y3Ehdni/ZdlG7F1qx4YBq
259 mx5e7d+Wd6Hn5Z3fcxO9+yrvypS3YN5YrJzuZSiuCSWdP9RcY7y5r1ZQRv1g0nTZ
260 MDWZUiNea4cddTd8xKxFB3tV4SkIZi8LustuzDVWa0Mlh4EOmP6uf6c5WxtqRsEL
261 UwORFwKBgEjZsfmZGBurjOtSrcsteulOB0D2nOqPVRWXmbSNJT/l73DkEllvVyA/
262 wdW39nyFrA2Qw1K2F+l8DkzMd/WEjmioSWCsvTkXlvrqPfByKg01zCbYy/mhRW7d
263 7sQrPOIl8ygsc3JrxmvzibdWmng1MehvpAM1ogWeTUa1lsDTNJ/6
264 $dend RSA $pvt $kd
265 EOF
266     chmod 600 "$build_files_dir/badkey"
267     cat <<EOF >"$build_files_dir/sshconfig"
268 Host 172.17.0.*
269         StrictHostKeyChecking no
270         UserKnownHostsFile=/dev/null
271 EOF
272 }
273
274 csit_shim_generate_docker_build_files() {
275     local build_files_dir="$DOCKER_BUILD_FILES_DIR"
276     # TODO: Verify why badkey is required & figure out how to avoid it.
277     local badkey='AAAAB3NzaC1yc2EAAAADAQABAAABAQCyUNd/iRk5Ajw4ZBB0gXyjzecEzQHh/MctgvHGJjasqJDkwYyZBrunUorOZ3n82W8VGdd5+eNINCWOM/ERjuaHjnutfade+ocPgZRdk+kEgTvetDVNWIgBd0PMVcnp57jJfx7CZVqTNgGeVQ8OJ2RbJGeOb/EKApQI74IPkAfc0PSieSw5gC0eqEOHb39Awgp0ycrzsUHF/OEicfCmo+6vvrMGenDe7frKUoTKYMWs7l3DOyFC8NaOxhGD3J1Ne5u3A/r4w6mN1HVI0rFwIcoms+t0B4lb2ODWKZiZikQdn8/eqwsmbSEZZsWN3FkshgjPS83+dNqVwB6pPY5Yqte7'
278
279     mkdir -p "$build_files_dir"
280     # TODO: Verify why badkeypub is required & figure out how to avoid it.
281     echo "ssh-rsa $badkey ejk@bhima.local" >"$build_files_dir/badkeypub"
282
283     cat <<EOF >"$build_files_dir/sshconfig"
284 Host 172.17.0.*
285         StrictHostKeyChecking no
286         UserKnownHostsFile=/dev/null
287 EOF
288     cat <<EOF >"$build_files_dir/wrapdocker"
289 #!/bin/bash
290
291 # Ensure that all nodes in /dev/mapper correspond to mapped devices currently loaded by the device-mapper kernel driver
292 dmsetup mknodes
293
294 # First, make sure that cgroups are mounted correctly.
295 CGROUP=/sys/fs/cgroup
296 : {LOG:=stdio}
297
298 [ -d \$CGROUP ] ||
299     mkdir \$CGROUP
300
301 mountpoint -q \$CGROUP ||
302     mount -n -t tmpfs -o uid=0,gid=0,mode=0755 cgroup \$CGROUP || {
303         echo "Could not make a tmpfs mount. Did you use --privileged?"
304         exit 1
305     }
306
307 if [ -d /sys/kernel/security ] && ! mountpoint -q /sys/kernel/security
308 then
309     mount -t securityfs none /sys/kernel/security || {
310         echo "Could not mount /sys/kernel/security."
311         echo "AppArmor detection and --privileged mode might break."
312     }
313 fi
314
315 # Mount the cgroup hierarchies exactly as they are in the parent system.
316 for SUBSYS in \$(cut -d: -f2 /proc/1/cgroup)
317 do
318         [ -d \$CGROUP/\$SUBSYS ] || mkdir \$CGROUP/\$SUBSYS
319         mountpoint -q \$CGROUP/\$SUBSYS ||
320                 mount -n -t cgroup -o \$SUBSYS cgroup \$CGROUP/\$SUBSYS
321
322         # The two following sections address a bug which manifests itself
323         # by a cryptic "lxc-start: no ns_cgroup option specified" when
324         # trying to start containers withina container.
325         # The bug seems to appear when the cgroup hierarchies are not
326         # mounted on the exact same directories in the host, and in the
327         # container.
328
329         # Named, control-less cgroups are mounted with "-o name=foo"
330         # (and appear as such under /proc/<pid>/cgroup) but are usually
331         # mounted on a directory named "foo" (without the "name=" prefix).
332         # Systemd and OpenRC (and possibly others) both create such a
333         # cgroup. To avoid the aforementioned bug, we symlink "foo" to
334         # "name=foo". This shouldn't have any adverse effect.
335         echo \$SUBSYS | grep -q ^name= && {
336                 NAME=\$(echo \$SUBSYS | sed s/^name=//)
337                 ln -s \$SUBSYS \$CGROUP/\$NAME
338         }
339
340         # Likewise, on at least one system, it has been reported that
341         # systemd would mount the CPU and CPU accounting controllers
342         # (respectively "cpu" and "cpuacct") with "-o cpuacct,cpu"
343         # but on a directory called "cpu,cpuacct" (note the inversion
344         # in the order of the groups). This tries to work around it.
345         [ \$SUBSYS = cpuacct,cpu ] && ln -s \$SUBSYS \$CGROUP/cpu,cpuacct
346 done
347
348 # Note: as I write those lines, the LXC userland tools cannot setup
349 # a "sub-container" properly if the "devices" cgroup is not in its
350 # own hierarchy. Let's detect this and issue a warning.
351 grep -q :devices: /proc/1/cgroup ||
352     echo "WARNING: the 'devices' cgroup should be in its own hierarchy."
353 grep -qw devices /proc/1/cgroup ||
354     echo "WARNING: it looks like the 'devices' cgroup is not mounted."
355
356 # Now, close extraneous file descriptors.
357 pushd /proc/self/fd >/dev/null
358 for FD in *
359 do
360     case "\$FD" in
361     # Keep stdin/stdout/stderr
362     [012])
363         ;;
364     # Nuke everything else
365     *)
366         eval exec "\$FD>&-"
367         ;;
368     esac
369 done
370 popd >/dev/null
371
372
373 # If a pidfile is still around (for example after a container restart),
374 # delete it so that docker can start.
375 rm -rf /var/run/docker.pid
376
377 # If we were given a PORT environment variable, start as a simple daemon;
378 # otherwise, spawn a shell as well
379 if [ "\$PORT" ]
380 then
381     exec dockerd -H 0.0.0.0:\$PORT -H unix:///var/run/docker.sock \
382         \$DOCKER_DAEMON_ARGS
383 else
384     if [ "\$LOG" == "file" ]
385     then
386         dockerd \$DOCKER_DAEMON_ARGS &>/var/log/docker.log &
387     else
388         dockerd \$DOCKER_DAEMON_ARGS &
389     fi
390     (( timeout = 60 + SECONDS ))
391     until docker info >/dev/null 2>&1
392     do
393         if (( SECONDS >= timeout )); then
394             echo 'Timed out trying to connect to internal docker host.' >&2
395             break
396         fi
397         sleep 1
398     done
399     [[ \$1 ]] && exec "\$@"
400     exec bash --login
401 fi
402 EOF
403 }