CSIT-1416 Remove installation of vpp from containers
[csit.git] / resources / libraries / bash / function / device.sh
1 # Copyright (c) 2019 Cisco and/or its affiliates.
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at:
5 #
6 #     http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13
14 set -exuo pipefail
15
16 # This library defines functions used by multiple entry scripts.
17 # Keep functions ordered alphabetically, please.
18
19 function activate_wrapper () {
20     # Acts as wrapper for activate docker topology.
21     #
22     # Variables read:
23     # - ${1} - Node multiplicity of desired testbed.
24     # - ${2} - Node flavor string, usually describing the processor.
25     # - ${3} - CSIT-SUT-DCR image name and version.
26
27     set -exuo pipefail
28
29     enter_mutex || die
30     get_available_interfaces "${1}" "${2}" || die
31     start_topology_containers "${3}" || die
32     bind_interfaces_to_containers || die
33     set_env_variables || die
34     print_env_variables || die
35     exit_mutex || die
36 }
37
38
39 function bind_interfaces_to_containers () {
40     # Bind linux network interface to container and create symlink for PCI
41     # address in container.
42     #
43     # Variables read:
44     # - DCR_UUIDS - Docker Container UUIDs.
45     # - DCR_CPIDS - Docker Container PIDs (namespaces).
46     # - DUT1_NETDEVS - List of network devices allocated to DUT1 container.
47     # - PCI_ADDR - PCI address of network device.
48     # - TG_NETDEVS - List of network devices allocated to TG container.
49     # Variables set:
50     # - NETDEV - Linux network interface.
51
52     set -exuo pipefail
53
54     for NETDEV in "${TG_NETDEVS[@]}"; do
55         get_pci_addr || die
56         link_target=$(readlink -f /sys/bus/pci/devices/"${PCI_ADDR}") || {
57             die "Reading symlink for PCI address failed!"
58         }
59         cmd="ln -s ${link_target} /sys/bus/pci/devices/${PCI_ADDR}"
60
61         sudo ip link set ${NETDEV} netns ${DCR_CPIDS[tg]} || {
62             die "Moving interface to ${DCR_CPIDS[tg]} namespace failed!"
63         }
64         docker exec "${DCR_UUIDS[tg]}" ${cmd} || {
65             die "Linking PCI address in container failed!"
66         }
67     done
68     for NETDEV in "${DUT1_NETDEVS[@]}"; do
69         get_pci_addr || die
70         link_target=$(readlink -f /sys/bus/pci/devices/"${PCI_ADDR}") || {
71             die "Reading symlink for PCI address failed!"
72         }
73         cmd="ln -s ${link_target} /sys/bus/pci/devices/${PCI_ADDR}"
74
75         sudo ip link set ${NETDEV} netns ${DCR_CPIDS[dut1]} || {
76             die "Moving interface to ${DCR_CPIDS[dut1]} namespace failed!"
77         }
78         docker exec "${DCR_UUIDS[dut1]}" ${cmd} ||  {
79             die "Linking PCI address in container failed!"
80         }
81     done
82 }
83
84
85 function bind_interfaces_to_driver () {
86     # Bind network interface specified by parameter to driver specified by
87     # parameter.
88     #
89     # Variables read:
90     # - ADDR - PCI address of network interface.
91     # - DRIVER - Kernel driver.
92
93     pci_path="/sys/bus/pci/devices/${ADDR}"
94     drv_path="/sys/bus/pci/drivers/${DRIVER}"
95     vd="$(cat ${pci_path}/vendor ${pci_path}/device)" || {
96         die "Failed to retrieve interface details!"
97     }
98     set +e
99     echo ${vd} | sudo tee ${drv_path}/new_id
100     set -e
101     echo ${ADDR} | sudo tee ${pci_path}/driver/unbind || {
102         die "Failed to unbind interface ${ADDR}!"
103     }
104     echo ${ADDR} | sudo tee ${drv_path}/bind || {
105         die "Failed to bind interface ${ADDR}!"
106     }
107 }
108
109
110 function clean_environment () {
111     # Cleanup environment by removing topology containers and shared volumes
112     # and binding interfaces back to original driver.
113     #
114     # Variables read:
115     # - DCR_UUIDS - Docker Container UUIDs.
116     # - DUT1_PCIDEVS - List of PCI addresses of devices of DUT1 container.
117     # - TG_PCIDEVS - List of PCI addresses of devices of TG container.
118     # Variables set:
119     # - ADDR - PCI address of network interface.
120     # - DRIVER - Kernel driver.
121
122     set -exuo pipefail
123
124     # Kill docker containers.
125     docker rm --force "${DCR_UUIDS[@]}" || die "Cleanup containers failed!"
126
127     # Check if there are some leftover containers and remove all. Command will
128     # not fail in case there are no containers to remove.
129     docker rm --force $(docker ps -q --filter name=${DCR_UUIDS[dut1]}) || {
130         warn "Failed to remove hanged containers or nothing to remove!"
131     }
132
133     # Rebind interfaces back to kernel drivers.
134     for ADDR in ${TG_PCIDEVS[@]}; do
135         DRIVER="${TG_DRIVERS[0]}"
136         bind_interfaces_to_driver || die
137     done
138     for ADDR in ${DUT1_PCIDEVS[@]}; do
139         DRIVER="${DUT1_DRIVERS[0]}"
140         bind_interfaces_to_driver || die
141     done
142 }
143
144
145 function clean_environment_on_exit () {
146     # Cleanup environment by removing topology containers and binding
147     # interfaces back to original driver only if exit code is not 0.
148     # This function acts as workaround as 'set -eu' does not trigger ERR trap.
149
150     if [ $? -ne 0 ]; then
151         clean_environment || die
152     fi
153 }
154
155
156 function deactivate_wrapper () {
157     # Acts as wrapper for deactivate docker topology.
158     #
159     # Variables read:
160     # - ${@} - CSIT environment variables.
161
162     set -exuo pipefail
163
164     enter_mutex || die
165     read_env_variables "${@}" || die
166     clean_environment || die
167     exit_mutex || die
168 }
169
170
171 function die () {
172     # Print the message to standard error end exit with error code specified
173     # by the second argument.
174     #
175     # Hardcoded values:
176     # - The default error message.
177     # Arguments:
178     # - ${1} - The whole error message, be sure to quote. Optional
179     # - ${2} - the code to exit with, default: 1.
180
181     set -x
182     set +eu
183     warn "${1:-Unspecified run-time error occurred!}"
184     exit "${2:-1}"
185 }
186
187
188 function enter_mutex () {
189     # Enter mutual exclusion for protecting execution from starvation and
190     # deadlock.
191
192     set -exuo pipefail
193
194     mutex_timeout=3600
195     mutex_file="/tmp/mutex_file"
196
197     # Create mutex.
198     exec {lock_fd}>${mutex_file} || {
199         die "Mutex enter failed!"
200     }
201     flock --timeout "${mutex_timeout}" "${lock_fd}" || {
202         die "Calling flock() failed!"
203     }
204     # ----------------------
205     # Enter mutex succeeded.
206     warn "Mutex enter succeeded for PID $$."
207 }
208
209
210 function exit_mutex () {
211     # Exit mutual exclusion.
212
213     set -exuo pipefail
214
215     # ---------------------
216     # Remove mutex so we are not blocking others anymore.
217     flock -u "${lock_fd}" || {
218         die "Mutex destroy failed!"
219     }
220     warn "Mutex leave succeeded for PID $$."
221 }
222
223
224 function get_available_interfaces () {
225     # Find and get available Virtual functions.
226     #
227     # Arguments:
228     # - ${1} - Node flavor string, usually describing the processor and node
229     # multiplicity of desired testbed, separated by underscore.
230     # Variables set:
231     # - DUT1_NETDEVS - List of network devices allocated to DUT1 container.
232     # - DUT1_PCIDEVS - List of PCI addresses allocated to DUT1 container.
233     # - DUT1_NETMACS - List of MAC addresses allocated to DUT1 container.
234     # - DUT1_DRIVERS - List of interface drivers to DUT1 container.
235     # - TG_NETDEVS - List of network devices allocated to TG container.
236     # - TG_PCIDEVS - List of PCI addresses allocated to TG container.
237     # - TG_NETMACS - List of MAC addresses allocated to TG container.
238     # - TG_DRIVERS - List of interface drivers to TG container.
239
240     set -exuo pipefail
241
242     # Following code is specifing VFs ID based on nodeness and flavor.
243     # As there is great variability in hardware configuration outside LF,
244     # from bootstrap architecure point of view these are considered as flavors.
245     # Anyone can override flavor for its own machine and add condition here.
246     # See http://pci-ids.ucw.cz/v2.2/pci.ids for more info.
247     case_text="${1}_${2}"
248     case "${case_text}" in
249         "1n_skx")
250             # Add Intel Corporation XL710/X710 Virtual Function to the
251             # whitelist.
252             pci_id="0x154c"
253             tg_netdev=(enp24)
254             dut1_netdev=(enp59)
255             ;;
256         "1n_vbox")
257             # Add Intel Corporation 82545EM Gigabit Ethernet Controller to the
258             # whitelist.
259             pci_id="0x100f"
260             tg_netdev=(eth1 eth2)
261             dut1_netdev=(eth3 eth4)
262             ;;
263         *)
264             die "Unknown specification: ${case_text}!"
265     esac
266
267     net_path="/sys/bus/pci/devices/*/net/*"
268
269     # TG side of connections.
270     TG_NETDEVS=()
271     TG_PCIDEVS=()
272     TG_NETMACS=()
273     TG_DRIVERS=()
274     # DUT1 side of connections.
275     DUT1_NETDEVS=()
276     DUT1_PCIDEVS=()
277     DUT1_NETMACS=()
278     DUT1_DRIVERS=()
279
280     # Following code is filtering available VFs represented by network device
281     # name. Only allowed VFs PCI IDs are used.
282     for netdev in \
283         $(find ${net_path} -type d -name . -o -prune -exec basename '{}' ';');
284     do
285         if grep -q "${pci_id}" "/sys/class/net/${netdev}/device/device"; then
286             # We will filter to TG/DUT1 side of connection (this can be in
287             # future overriden by more advanced conditions for mapping).
288             for sub in ${tg_netdev[@]}; do
289                 if [[ "${netdev#*$sub}" != "${netdev}" ]]; then
290                     tg_side+=(${netdev})
291                 fi
292             done
293             for sub in ${dut1_netdev[@]}; do
294                 if [[ "${netdev#*$sub}" != "${netdev}" ]]; then
295                     dut1_side+=(${netdev})
296                 fi
297             done
298         fi
299     done
300
301     for netdev in "${tg_side[@]::2}"; do
302         TG_NETDEVS+=(${netdev})
303     done
304     for netdev in "${dut1_side[@]::2}"; do
305         DUT1_NETDEVS+=(${netdev})
306     done
307
308     for NETDEV in "${TG_NETDEVS[@]}"; do
309         get_pci_addr
310         get_mac_addr
311         get_krn_driver
312         TG_PCIDEVS+=(${PCI_ADDR})
313         TG_NETMACS+=(${MAC_ADDR})
314         TG_DRIVERS+=(${KRN_DRIVER})
315     done
316     for NETDEV in "${DUT1_NETDEVS[@]}"; do
317         get_pci_addr
318         get_mac_addr
319         get_krn_driver
320         DUT1_PCIDEVS+=(${PCI_ADDR})
321         DUT1_NETMACS+=(${MAC_ADDR})
322         DUT1_DRIVERS+=(${KRN_DRIVER})
323     done
324
325     # We need at least two interfaces for TG/DUT1 for building topology.
326     if [ "${#TG_NETDEVS[@]}" -ne 2 ] || [ "${#DUT1_NETDEVS[@]}" -ne 2 ]; then
327         die "Not enough linux network interfaces found!"
328     fi
329     if [ "${#TG_PCIDEVS[@]}" -ne 2 ] || [ "${#DUT1_PCIDEVS[@]}" -ne 2 ]; then
330         die "Not enough pci interfaces found!"
331     fi
332 }
333
334
335 function get_krn_driver () {
336     # Get kernel driver from linux network device name.
337     #
338     # Variables read:
339     # - PCI_ADDR - PCI address of network device.
340     # Variables set:
341     # - KRN_DRIVER - Kernel driver of network device.
342
343     set -exuo pipefail
344
345     pci_path="/sys/bus/pci/devices/${PCI_ADDR}"
346     KRN_DRIVER="$(basename $(readlink -f ${pci_path}/driver))" || {
347         die "Failed to get kernel driver of PCI interface!"
348     }
349 }
350
351
352 function get_mac_addr () {
353     # Get MAC address from linux network device name.
354     #
355     # Variables read:
356     # - NETDEV - Linux network device name.
357     # Variables set:
358     # - MAC_ADDR - MAC address of network device.
359
360     set -exuo pipefail
361
362     if [ -d /sys/class/net/${NETDEV}/device ]; then
363         MAC_ADDR="$(</sys/class/net/${NETDEV}/address)" || {
364             die "Failed to get MAC address of linux network interface!"
365         }
366     fi
367 }
368
369
370 function get_pci_addr () {
371     # Get PCI address in <domain>:<bus:<device>.<func> format from linux network
372     # device name.
373     #
374     # Variables read:
375     # - NETDEV - Linux network device name.
376     # Variables set:
377     # - PCI_ADDR - PCI address of network device.
378
379     set -exuo pipefail
380
381     if [ -d /sys/class/net/${NETDEV}/device ]; then
382         PCI_ADDR=$(basename $(readlink /sys/class/net/${NETDEV}/device)) || {
383             die "Failed to get PCI address of linux network interface!"
384         }
385     fi
386     if [ ! -d /sys/bus/pci/devices/${PCI_ADDR} ]; then
387         die "PCI device ${NETDEV} doesn't exist!"
388     fi
389 }
390
391
392 function installed () {
393
394     set -exuo pipefail
395
396     # Check if the given utility is installed. Fail if not installed.
397     #
398     # Arguments:
399     # - ${1} - Utility to check.
400     # Returns:
401     # - 0 - If command is installed.
402     # - 1 - If command is not installed.
403
404     command -v "${1}"
405 }
406
407
408 function print_env_variables () {
409     # Get environment variables prefixed by CSIT_.
410
411     set -exuo pipefail
412
413     env | grep CSIT_
414 }
415
416
417 function read_env_variables () {
418     # Read environment variables from parameters.
419     #
420     # Arguments:
421     # - ${@} - Variables passed as an argument.
422
423     set -exuo pipefail
424
425     for param in "$@"; do
426         export "${param}"
427     done
428     declare -gA DCR_UUIDS
429     DCR_UUIDS+=([tg]="${CSIT_TG_UUID}")
430     DCR_UUIDS+=([dut1]="${CSIT_DUT1_UUID}")
431     TG_PCIDEVS=("${CSIT_TG_INTERFACES_PORT1_PCI}")
432     TG_DRIVERS=("${CSIT_TG_INTERFACES_PORT1_DRV}")
433     TG_PCIDEVS+=("${CSIT_TG_INTERFACES_PORT2_PCI}")
434     TG_DRIVERS+=("${CSIT_TG_INTERFACES_PORT2_DRV}")
435     DUT1_PCIDEVS=("${CSIT_DUT1_INTERFACES_PORT1_PCI}")
436     DUT1_DRIVERS=("${CSIT_DUT1_INTERFACES_PORT1_DRV}")
437     DUT1_PCIDEVS+=("${CSIT_DUT1_INTERFACES_PORT2_PCI}")
438     DUT1_DRIVERS+=("${CSIT_DUT1_INTERFACES_PORT2_DRV}")
439 }
440
441
442 function set_env_variables () {
443     # Set environment variables.
444     #
445     # Variables read:
446     # - DCR_UUIDS - Docker Container UUIDs.
447     # - DCR_PORTS - Docker Container's SSH ports.
448     # - DUT1_NETMACS - List of network devices MAC addresses of DUT1 container.
449     # - DUT1_PCIDEVS - List of PCI addresses of devices of DUT1 container.
450     # - DUT1_DRIVERS - List of interface drivers to DUT1 container.
451     # - TG_NETMACS - List of network devices MAC addresses of TG container.
452     # - TG_PCIDEVS - List of PCI addresses of devices of TG container.
453     # - TG_DRIVERS - List of interface drivers to TG container.
454
455     set -exuo pipefail
456
457     set -a
458     CSIT_TG_HOST="$(hostname --all-ip-addresses | awk '{print $1}')" || {
459         die "Reading hostname IP address failed!"
460     }
461     CSIT_TG_PORT="${DCR_PORTS[tg]#*:}"
462     CSIT_TG_UUID="${DCR_UUIDS[tg]}"
463     CSIT_TG_ARCH="$(uname -i)" || {
464         die "Reading machine architecture failed!"
465     }
466     CSIT_DUT1_HOST="$(hostname --all-ip-addresses | awk '{print $1}')" || {
467         die "Reading hostname IP address failed!"
468     }
469     CSIT_DUT1_PORT="${DCR_PORTS[dut1]#*:}"
470     CSIT_DUT1_UUID="${DCR_UUIDS[dut1]}"
471     CSIT_DUT1_ARCH="$(uname -i)" || {
472         die "Reading machine architecture failed!"
473     }
474     CSIT_TG_INTERFACES_PORT1_MAC="${TG_NETMACS[0]}"
475     CSIT_TG_INTERFACES_PORT1_PCI="${TG_PCIDEVS[0]}"
476     CSIT_TG_INTERFACES_PORT1_DRV="${TG_DRIVERS[0]}"
477     CSIT_TG_INTERFACES_PORT2_MAC="${TG_NETMACS[1]}"
478     CSIT_TG_INTERFACES_PORT2_PCI="${TG_PCIDEVS[1]}"
479     CSIT_TG_INTERFACES_PORT2_DRV="${TG_DRIVERS[1]}"
480     CSIT_DUT1_INTERFACES_PORT1_MAC="${DUT1_NETMACS[0]}"
481     CSIT_DUT1_INTERFACES_PORT1_PCI="${DUT1_PCIDEVS[0]}"
482     CSIT_DUT1_INTERFACES_PORT1_DRV="${DUT1_DRIVERS[0]}"
483     CSIT_DUT1_INTERFACES_PORT2_MAC="${DUT1_NETMACS[1]}"
484     CSIT_DUT1_INTERFACES_PORT2_PCI="${DUT1_PCIDEVS[1]}"
485     CSIT_DUT1_INTERFACES_PORT2_DRV="${DUT1_DRIVERS[1]}"
486     set +a
487 }
488
489
490 function start_topology_containers () {
491     # Starts csit-sut-dcr docker containers for TG/DUT1.
492     #
493     # Variables read:
494     # - CSIT_DIR - Path to existing root of local CSIT git repository.
495     # Variables set:
496     # - DCR_UUIDS - Docker Container UUIDs.
497     # - DCR_PORTS - Docker Container SSH TCP ports.
498     # - DCR_CPIDS - Docker Container PIDs (namespaces).
499
500     set -exuo pipefail
501
502     if ! installed docker; then
503         die "Docker not present. Please install before continue!"
504     fi
505
506     # If the IMAGE is not already loaded then docker run will pull the IMAGE,
507     # and all image dependencies, before it starts the container.
508     dcr_image="${1}"
509     # Run the container in the background and print the new container ID.
510     dcr_stc_params="--detach=true "
511     # Give extended privileges to this container. A "privileged" container is
512     # given access to all devices and able to run nested containers.
513     dcr_stc_params+="--privileged "
514     # Publish all exposed ports to random ports on the host interfaces.
515     dcr_stc_params+="--publish-all "
516     # Automatically remove the container when it exits.
517     dcr_stc_params+="--rm "
518     # Size of /dev/shm.
519     dcr_stc_params+="--shm-size 512M "
520     # Override access to PCI bus by attaching a filesystem mount to the
521     # container.
522     dcr_stc_params+="--mount type=tmpfs,destination=/sys/bus/pci/devices "
523     # Mount vfio to be able to bind to see binded interfaces. We cannot use
524     # --device=/dev/vfio as this does not see newly binded interfaces.
525     dcr_stc_params+="--volume /dev/vfio:/dev/vfio "
526     # Mount nested_vm image to be able to run VM tests.
527     dcr_stc_params+="--volume /var/lib/vm/vhost-nested.img:/var/lib/vm/vhost-nested.img "
528     # Mount docker.sock to be able to use docker deamon of the host.
529     dcr_stc_params+="--volume /var/run/docker.sock:/var/run/docker.sock "
530
531     # Docker Container UUIDs.
532     declare -gA DCR_UUIDS
533     # Docker Container SSH TCP ports.
534     declare -gA DCR_PORTS
535     # Docker Container PIDs (namespaces).
536     declare -gA DCR_CPIDS
537
538     # Run TG and DUT1. As initial version we do support only 2-node.
539     params=(${dcr_stc_params} --name csit-tg-$(uuidgen) ${dcr_image})
540     DCR_UUIDS+=([tg]="$(docker run "${params[@]}")") || {
541         die "Failed to start TG docker container!"
542     }
543     params=(${dcr_stc_params} --name csit-dut1-$(uuidgen) ${dcr_image})
544     DCR_UUIDS+=([dut1]="$(docker run "${params[@]}")") || {
545         die "Failed to start DUT1 docker container!"
546     }
547
548     trap 'clean_environment_on_exit' EXIT || {
549         die "Trap attempt failed, please cleanup manually. Aborting!"
550     }
551
552     # Get Containers TCP ports.
553     params=(${DCR_UUIDS[tg]})
554     DCR_PORTS+=([tg]="$(docker port "${params[@]}")") || {
555         die "Failed to get port of TG docker container!"
556     }
557     params=(${DCR_UUIDS[dut1]})
558     DCR_PORTS+=([dut1]="$(docker port "${params[@]}")") || {
559         die "Failed to get port of DUT1 docker container!"
560     }
561
562     # Get Containers PIDs.
563     params=(--format="{{ .State.Pid }}" ${DCR_UUIDS[tg]})
564     DCR_CPIDS+=([tg]="$(docker inspect "${params[@]}")") || {
565         die "Failed to get PID of TG docker container!"
566     }
567     params=(--format="{{ .State.Pid }}" ${DCR_UUIDS[dut1]})
568     DCR_CPIDS+=([dut1]="$(docker inspect "${params[@]}")") || {
569         die "Failed to get PID of DUT1 docker container!"
570     }
571 }
572
573 function warn () {
574     # Print the message to standard error.
575     #
576     # Arguments:
577     # - ${@} - The text of the message.
578
579     echo "$@" >&2
580 }