e4ed319c7f30feeb0ea126bd091b95de3fe8f3b6
[csit.git] / resources / libraries / bash / function / device.sh
1 # Copyright (c) 2018 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 binding
112     # 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     # Rebind interfaces back to kernel drivers.
128     for ADDR in ${TG_PCIDEVS[@]}; do
129         DRIVER="${TG_DRIVERS[0]}"
130         bind_interfaces_to_driver || die
131     done
132     for ADDR in ${DUT1_PCIDEVS[@]}; do
133         DRIVER="${DUT1_DRIVERS[0]}"
134         bind_interfaces_to_driver || die
135     done
136 }
137
138
139 function clean_environment_on_exit () {
140     # Cleanup environment by removing topology containers and binding
141     # interfaces back to original driver only if exit code is not 0.
142     # This function acts as workaround as 'set -eu' does not trigger ERR trap.
143
144     if [ $? -ne 0 ]; then
145         clean_environment || die
146     fi
147 }
148
149
150 function deactivate_wrapper () {
151     # Acts as wrapper for deactivate docker topology.
152     #
153     # Variables read:
154     # - ${@} - CSIT environment variables.
155
156     set -exuo pipefail
157
158     enter_mutex || die
159     read_env_variables "${@}" || die
160     clean_environment || die
161     exit_mutex || die
162 }
163
164
165 function die () {
166     # Print the message to standard error end exit with error code specified
167     # by the second argument.
168     #
169     # Hardcoded values:
170     # - The default error message.
171     # Arguments:
172     # - ${1} - The whole error message, be sure to quote. Optional
173     # - ${2} - the code to exit with, default: 1.
174
175     set -x
176     set +eu
177     warn "${1:-Unspecified run-time error occurred!}"
178     exit "${2:-1}"
179 }
180
181
182 function enter_mutex () {
183     # Enter mutual exclusion for protecting execution from starvation and
184     # deadlock.
185
186     set -exuo pipefail
187
188     mutex_timeout=3600
189     mutex_file="/tmp/mutex_file"
190
191     # Create mutex.
192     exec {lock_fd}>${mutex_file} || {
193         die "Mutex enter failed!"
194     }
195     flock --timeout "${mutex_timeout}" "${lock_fd}" || {
196         die "Calling flock() failed!"
197     }
198     # ----------------------
199     # Enter mutex succeeded.
200     warn "Mutex enter succeeded for PID $$."
201 }
202
203
204 function exit_mutex () {
205     # Exit mutual exclusion.
206
207     set -exuo pipefail
208
209     # ---------------------
210     # Remove mutex so we are not blocking others anymore.
211     flock -u "${lock_fd}" || {
212         die "Mutex destroy failed!"
213     }
214     warn "Mutex leave succeeded for PID $$."
215 }
216
217
218 function get_available_interfaces () {
219     # Find and get available Virtual functions.
220     #
221     # Arguments:
222     # - ${1} - Node flavor string, usually describing the processor and node
223     # multiplicity of desired testbed, separated by underscore.
224     # Variables set:
225     # - DUT1_NETDEVS - List of network devices allocated to DUT1 container.
226     # - DUT1_PCIDEVS - List of PCI addresses allocated to DUT1 container.
227     # - DUT1_NETMACS - List of MAC addresses allocated to DUT1 container.
228     # - DUT1_DRIVERS - List of interface drivers to DUT1 container.
229     # - TG_NETDEVS - List of network devices allocated to TG container.
230     # - TG_PCIDEVS - List of PCI addresses allocated to TG container.
231     # - TG_NETMACS - List of MAC addresses allocated to TG container.
232     # - TG_DRIVERS - List of interface drivers to TG container.
233
234     set -exuo pipefail
235
236     # Following code is specifing VFs ID based on nodeness and flavor.
237     # As there is great variability in hardware configuration outside LF,
238     # from bootstrap architecure point of view these are considered as flavors.
239     # Anyone can override flavor for its own machine and add condition here.
240     # See http://pci-ids.ucw.cz/v2.2/pci.ids for more info.
241     case_text="${1}_${2}"
242     case "${case_text}" in
243         "1n_skx")
244             # Add Intel Corporation XL710/X710 Virtual Function to the
245             # whitelist.
246             pci_id="0x154c"
247             tg_netdev=(enp24)
248             dut1_netdev=(enp59)
249             ;;
250         "1n_vbox")
251             # Add Intel Corporation 82545EM Gigabit Ethernet Controller to the
252             # whitelist.
253             pci_id="0x100f"
254             tg_netdev=(eth1 eth2)
255             dut1_netdev=(eth3 eth4)
256             ;;
257         *)
258             die "Unknown specification: ${case_text}!"
259     esac
260
261     net_path="/sys/bus/pci/devices/*/net/*"
262
263     # TG side of connections.
264     TG_NETDEVS=()
265     TG_PCIDEVS=()
266     TG_NETMACS=()
267     TG_DRIVERS=()
268     # DUT1 side of connections.
269     DUT1_NETDEVS=()
270     DUT1_PCIDEVS=()
271     DUT1_NETMACS=()
272     DUT1_DRIVERS=()
273
274     # Following code is filtering available VFs represented by network device
275     # name. Only allowed VFs PCI IDs are used.
276     for netdev in \
277         $(find ${net_path} -type d -name . -o -prune -exec basename '{}' ';');
278     do
279         if grep -q "${pci_id}" "/sys/class/net/${netdev}/device/device"; then
280             # We will filter to TG/DUT1 side of connection (this can be in
281             # future overriden by more advanced conditions for mapping).
282             for sub in ${tg_netdev[@]}; do
283                 if [[ "${netdev#*$sub}" != "${netdev}" ]]; then
284                     tg_side+=(${netdev})
285                 fi
286             done
287             for sub in ${dut1_netdev[@]}; do
288                 if [[ "${netdev#*$sub}" != "${netdev}" ]]; then
289                     dut1_side+=(${netdev})
290                 fi
291             done
292         fi
293     done
294
295     for netdev in "${tg_side[@]::2}"; do
296         TG_NETDEVS+=(${netdev})
297     done
298     for netdev in "${dut1_side[@]::2}"; do
299         DUT1_NETDEVS+=(${netdev})
300     done
301
302     for NETDEV in "${TG_NETDEVS[@]}"; do
303         get_pci_addr
304         get_mac_addr
305         get_krn_driver
306         TG_PCIDEVS+=(${PCI_ADDR})
307         TG_NETMACS+=(${MAC_ADDR})
308         TG_DRIVERS+=(${KRN_DRIVER})
309     done
310     for NETDEV in "${DUT1_NETDEVS[@]}"; do
311         get_pci_addr
312         get_mac_addr
313         get_krn_driver
314         DUT1_PCIDEVS+=(${PCI_ADDR})
315         DUT1_NETMACS+=(${MAC_ADDR})
316         DUT1_DRIVERS+=(${KRN_DRIVER})
317     done
318
319     # We need at least two interfaces for TG/DUT1 for building topology.
320     if [ "${#TG_NETDEVS[@]}" -ne 2 ] || [ "${#DUT1_NETDEVS[@]}" -ne 2 ]; then
321         die "Not enough linux network interfaces found!"
322     fi
323     if [ "${#TG_PCIDEVS[@]}" -ne 2 ] || [ "${#DUT1_PCIDEVS[@]}" -ne 2 ]; then
324         die "Not enough pci interfaces found!"
325     fi
326 }
327
328
329 function get_krn_driver () {
330     # Get kernel driver from linux network device name.
331     #
332     # Variables read:
333     # - PCI_ADDR - PCI address of network device.
334     # Variables set:
335     # - KRN_DRIVER - Kernel driver of network device.
336
337     set -exuo pipefail
338
339     pci_path="/sys/bus/pci/devices/${PCI_ADDR}"
340     KRN_DRIVER="$(basename $(readlink -f ${pci_path}/driver))" || {
341         die "Failed to get kernel driver of PCI interface!"
342     }
343 }
344
345
346 function get_mac_addr () {
347     # Get MAC address from linux network device name.
348     #
349     # Variables read:
350     # - NETDEV - Linux network device name.
351     # Variables set:
352     # - MAC_ADDR - MAC address of network device.
353
354     set -exuo pipefail
355
356     if [ -d /sys/class/net/${NETDEV}/device ]; then
357         MAC_ADDR="$(</sys/class/net/${NETDEV}/address)" || {
358             die "Failed to get MAC address of linux network interface!"
359         }
360     fi
361 }
362
363
364 function get_pci_addr () {
365     # Get PCI address in <domain>:<bus:<device>.<func> format from linux network
366     # device name.
367     #
368     # Variables read:
369     # - NETDEV - Linux network device name.
370     # Variables set:
371     # - PCI_ADDR - PCI address of network device.
372
373     set -exuo pipefail
374
375     if [ -d /sys/class/net/${NETDEV}/device ]; then
376         PCI_ADDR=$(basename $(readlink /sys/class/net/${NETDEV}/device)) || {
377             die "Failed to get PCI address of linux network interface!"
378         }
379     fi
380     if [ ! -d /sys/bus/pci/devices/${PCI_ADDR} ]; then
381         die "PCI device ${NETDEV} doesn't exist!"
382     fi
383 }
384
385
386 function installed () {
387
388     set -exuo pipefail
389
390     # Check if the given utility is installed. Fail if not installed.
391     #
392     # Arguments:
393     # - ${1} - Utility to check.
394     # Returns:
395     # - 0 - If command is installed.
396     # - 1 - If command is not installed.
397
398     command -v "${1}"
399 }
400
401
402 function print_env_variables () {
403     # Get environment variables prefixed by CSIT_.
404
405     set -exuo pipefail
406
407     env | grep CSIT_
408 }
409
410
411 function read_env_variables () {
412     # Read environment variables from parameters.
413     #
414     # Arguments:
415     # - ${@} - Variables passed as an argument.
416
417     set -exuo pipefail
418
419     for param in "$@"; do
420         export "${param}"
421     done
422     declare -gA DCR_UUIDS
423     DCR_UUIDS+=([tg]="${CSIT_TG_UUID}")
424     DCR_UUIDS+=([dut1]="${CSIT_DUT1_UUID}")
425     TG_PCIDEVS=("${CSIT_TG_INTERFACES_PORT1_PCI}")
426     TG_DRIVERS=("${CSIT_TG_INTERFACES_PORT1_DRV}")
427     TG_PCIDEVS+=("${CSIT_TG_INTERFACES_PORT2_PCI}")
428     TG_DRIVERS+=("${CSIT_TG_INTERFACES_PORT2_DRV}")
429     DUT1_PCIDEVS=("${CSIT_DUT1_INTERFACES_PORT1_PCI}")
430     DUT1_DRIVERS=("${CSIT_DUT1_INTERFACES_PORT1_DRV}")
431     DUT1_PCIDEVS+=("${CSIT_DUT1_INTERFACES_PORT2_PCI}")
432     DUT1_DRIVERS+=("${CSIT_DUT1_INTERFACES_PORT2_DRV}")
433 }
434
435
436 function set_env_variables () {
437     # Set environment variables.
438     #
439     # Variables read:
440     # - DCR_UUIDS - Docker Container UUIDs.
441     # - DCR_PORTS - Docker Container's SSH ports.
442     # - DUT1_NETMACS - List of network devices MAC addresses of DUT1 container.
443     # - DUT1_PCIDEVS - List of PCI addresses of devices of DUT1 container.
444     # - DUT1_DRIVERS - List of interface drivers to DUT1 container.
445     # - TG_NETMACS - List of network devices MAC addresses of TG container.
446     # - TG_PCIDEVS - List of PCI addresses of devices of TG container.
447     # - TG_DRIVERS - List of interface drivers to TG container.
448
449     set -exuo pipefail
450
451     set -a
452     CSIT_TG_HOST="$(hostname --all-ip-addresses | awk '{print $1}')" || {
453         die "Reading hostname IP address failed!"
454     }
455     CSIT_TG_PORT="${DCR_PORTS[tg]#*:}"
456     CSIT_TG_UUID="${DCR_UUIDS[tg]}"
457     CSIT_TG_ARCH="$(uname -i)" || {
458         die "Reading machine architecture failed!"
459     }
460     CSIT_DUT1_HOST="$(hostname --all-ip-addresses | awk '{print $1}')" || {
461         die "Reading hostname IP address failed!"
462     }
463     CSIT_DUT1_PORT="${DCR_PORTS[dut1]#*:}"
464     CSIT_DUT1_UUID="${DCR_UUIDS[dut1]}"
465     CSIT_DUT1_ARCH="$(uname -i)" || {
466         die "Reading machine architecture failed!"
467     }
468     CSIT_TG_INTERFACES_PORT1_MAC="${TG_NETMACS[0]}"
469     CSIT_TG_INTERFACES_PORT1_PCI="${TG_PCIDEVS[0]}"
470     CSIT_TG_INTERFACES_PORT1_DRV="${TG_DRIVERS[0]}"
471     CSIT_TG_INTERFACES_PORT2_MAC="${TG_NETMACS[1]}"
472     CSIT_TG_INTERFACES_PORT2_PCI="${TG_PCIDEVS[1]}"
473     CSIT_TG_INTERFACES_PORT2_DRV="${TG_DRIVERS[1]}"
474     CSIT_DUT1_INTERFACES_PORT1_MAC="${DUT1_NETMACS[0]}"
475     CSIT_DUT1_INTERFACES_PORT1_PCI="${DUT1_PCIDEVS[0]}"
476     CSIT_DUT1_INTERFACES_PORT1_DRV="${DUT1_DRIVERS[0]}"
477     CSIT_DUT1_INTERFACES_PORT2_MAC="${DUT1_NETMACS[1]}"
478     CSIT_DUT1_INTERFACES_PORT2_PCI="${DUT1_PCIDEVS[1]}"
479     CSIT_DUT1_INTERFACES_PORT2_DRV="${DUT1_DRIVERS[1]}"
480     set +a
481 }
482
483
484 function start_topology_containers () {
485     # Starts csit-sut-dcr docker containers for TG/DUT1.
486     #
487     # Variables read:
488     # - CSIT_DIR - Path to existing root of local CSIT git repository.
489     # Variables set:
490     # - DCR_UUIDS - Docker Container UUIDs.
491     # - DCR_PORTS - Docker Container SSH TCP ports.
492     # - DCR_CPIDS - Docker Container PIDs (namespaces).
493
494     set -exuo pipefail
495
496     if ! installed docker; then
497         die "Docker not present. Please install before continue!"
498     fi
499
500     # If the IMAGE is not already loaded then docker run will pull the IMAGE,
501     # and all image dependencies, before it starts the container.
502     dcr_image="${1}"
503     # Run the container in the background and print the new container ID.
504     dcr_stc_params="--detach=true "
505     # Give extended privileges to this container. A "privileged" container is
506     # given access to all devices and able to run nested containers.
507     dcr_stc_params+="--privileged "
508     # Publish all exposed ports to random ports on the host interfaces.
509     dcr_stc_params+="--publish-all "
510     # Automatically remove the container when it exits.
511     dcr_stc_params+="--rm "
512     # Size of /dev/shm.
513     dcr_stc_params+="--shm-size 512M "
514     # Override access to PCI bus by attaching a filesystem mount to the
515     # container.
516     dcr_stc_params+="--mount type=tmpfs,destination=/sys/bus/pci/devices "
517     # Mount vfio to be able to bind to see binded interfaces. We cannot use
518     # --device=/dev/vfio as this does not see newly binded interfaces.
519     dcr_stc_params+="--volume /dev/vfio:/dev/vfio "
520
521     # Docker Container UUIDs.
522     declare -gA DCR_UUIDS
523     # Docker Container SSH TCP ports.
524     declare -gA DCR_PORTS
525     # Docker Container PIDs (namespaces).
526     declare -gA DCR_CPIDS
527
528     # Run TG and DUT1. As initial version we do support only 2-node.
529     params=(${dcr_stc_params} --name csit-tg-$(uuidgen) ${dcr_image})
530     DCR_UUIDS+=([tg]="$(docker run "${params[@]}")") || {
531         die "Failed to start TG docker container!"
532     }
533     params=(${dcr_stc_params} --name csit-dut1-$(uuidgen) ${dcr_image})
534     DCR_UUIDS+=([dut1]="$(docker run "${params[@]}")") || {
535         die "Failed to start DUT1 docker container!"
536     }
537
538     trap 'clean_environment_on_exit' EXIT || {
539         die "Trap attempt failed, please cleanup manually. Aborting!"
540     }
541
542     # Get Containers TCP ports.
543     params=(${DCR_UUIDS[tg]})
544     DCR_PORTS+=([tg]="$(docker port "${params[@]}")") || {
545         die "Failed to get port of TG docker container!"
546     }
547     params=(${DCR_UUIDS[dut1]})
548     DCR_PORTS+=([dut1]="$(docker port "${params[@]}")") || {
549         die "Failed to get port of DUT1 docker container!"
550     }
551
552     # Get Containers PIDs.
553     params=(--format="{{ .State.Pid }}" ${DCR_UUIDS[tg]})
554     DCR_CPIDS+=([tg]="$(docker inspect "${params[@]}")") || {
555         die "Failed to get PID of TG docker container!"
556     }
557     params=(--format="{{ .State.Pid }}" ${DCR_UUIDS[dut1]})
558     DCR_CPIDS+=([dut1]="$(docker inspect "${params[@]}")") || {
559         die "Failed to get PID of DUT1 docker container!"
560     }
561 }
562
563 function warn () {
564     # Print the message to standard error.
565     #
566     # Arguments:
567     # - ${@} - The text of the message.
568
569     echo "$@" >&2
570 }