This mass update is done with the assistant of shellcheck and shfmt. This patch series fixed most syntax issues found by shellcheck, tons of corner cases and issues are fixed.
Also simplified a lot of code according to suggestions by shellcheck. Related shellcheck warn/error/suggest info links are included in the commit message.
Since shellcheck can help to detect non-POSIX syntax issue in POSIX script (#!/bin/sh), and the coding style in kexec-tools package is very messy, this series refactored the code structure in following way:
- kdumpctl, mkdumprd, mkfadumprd, *-module-setup.sh and kdump-lib.sh is "bash only" script. We rely on bash only syntax heavily, and they will only be used in the first kernel, so just let them leverage bash syntax for better maintainability and better performance.
- kdump-lib-initramfs.sh, and dracut-kdump.sh is now POSIX compatible, and will be used in the second kernel.
This refactoring also enables kdump to use dash or busybox, instead of bash in the second kernel, which improves performance and memory usage. Tested with latest dracut on Fedora 34, now "dash" in second kernel works well, it's faster than bash and save a lot of memory.
We may test dash or busybox as default kdump shell in the future for better performance.
For reviewers:
Patch 25, 26, 30, 41, 46 is automatic code update using script and tools like shfmt, other patch may need careful review.
Patch 1 added a editorconfig file for shfmt to work properly, which is Acked by Pingfan but still posting it to make it easier to review.
Patch 2 - 29 focus on the bash part: Patch 2, 3, 4, 5, 8 introduced new config file read and format helper, which unified the config file reading in kexec-tools scripts. So space in config file should be no longer a problem (previously random problem may occur since kexec-tools scripts is using many different ways to read the config file). And this make it much easier to clean up the code.
Patch 6, 7, 9 - 24 fixed many issues found with shellcheck in bash scripts manually. Some issues are already breaking kdump just no one noticed yet.
Patch 25, 26, 30 is an automatic code update using sed and shfmt, there should be no code behaviour change.
Patch 27, 28, 29 batch fixed some common bash script issues manually with hints from shellcheck.
Patch 31 - 48 focus on the POSIX part: Patch 31 - 33 restructures the code, prepare to make kdump-lib-initramfs.sh a POSIX script and drop kdump-lib.sh in kdump kernel.
Patch 34 - 38 clean up code in dracut-kdump.sh, and fix misc issues found by shellcheck manually, prepare to make it POSIX compatible.
Patch 39 contains a lot of code refactoring that makes dracut-kdump.sh POSIX compatible.
Patch 40 contains a lot of code refactoring that makes kdump-lib-initramfs.sh POSIX compatible.
Patch 41 is an automatic code update using sed, there should be no code behaviour change.
Patch 42, 43 reworked how nmcli is being called by kexec-tools, fixed word splitting issue and allow connection name to contain space.
Patch 44 optimized a sed call.
Patch 45 batch fixed some common bash script issues manually with hints from shellcheck.
Patch 46 is an automatic code update using shfmt, there should be no code behaviour change.
Patch 47, 48 contains a lot of change that makes kdump-logger.sh POSIX compatible.
Patch 49 allows mkdumprd to use dash instead of bash in second kernel.
Update from V1: - Fix many typos and code error, and fix a few more existing code issues found while reviewing the patch, many thanks to Philipp Rudo. - Add more info in commit message and cover letter.
Kairui Song (49): Add a .editorconfig file kdump-lib.sh: add a config format and read helper kdump-lib.sh: add a config value retrive helper kdump-lib.sh: use kdump_get_conf_val to read config values kdumpctl: use kdump_get_conf_val to read config values kdumpctl: get rid of a `wc` call kdumpctl: fix fragile loops over find output mkdumprd: use kdump_get_conf_val to read config values mkdumprd: make dracut_args an array again mkdumprd: remove some redundant echo mkdumprd: fix multiple issues with get_ssh_size mkdumprd: use array to store ssh arguments in mkdir_save_path_ssh mkfadumprd: make _dracut_isolate_args an array dracut-module-setup.sh: rework kdump_get_ip_route_field dracut-module-setup.sh: remove an unused variable dracut-module-setup.sh: fix _bondoptions wrong references dracut-module-setup.sh: use "*" to expend array as string dracut-module-setup.sh: fix a ambiguous variable reference dracut-module-setup.sh: fix a loop over ls issue dracut-module-setup.sh: make iscsi check fail early if cd failed bash scripts: remove useless cat bash scripts: get rid of expr and let bash scripts: get rid of unnessary sed calls bash scripts: always use "read -r" bash scripts: use $(...) notation instead of legacy `...` bash scripts: replace '[ ]' with '[[ ]]' for bash scripts bash scripts: fix variable quoting issue bash scripts: fix redundant exit code check bash scripts: declare and assign separately bash scripts: reformat with shfmt Prepare to make kdump-lib-initramfs.sh a POSIX compatible lib Merge kdump-error-handler.sh into kdump.sh kdump-lib-initramfs.sh: move dump raleted functions to kdump.sh dracut-kdump.sh: don't put KDUMP_SCRIPT_DIR in PATH dracut-kdump.sh: remove add_dump_code dracut-kdump.sh: simplify dump_ssh dracut-kdump.sh: Use stat instead of ls to get vmcore size dracut-kdump.sh: POSIX doesn't support pipefail dracut-kdump.sh: make it POSIX compatible kdump-lib-initramfs.sh: make it POSIX compatible kdump-lib.sh: replace '[ ]' with '[[ ]]' and get rid of legacy `` kdump-lib.sh: fix and simplify get_nmcli_value_by_field kdump-lib.sh: fix word splitting of nmcli params kdump-lib.sh: avoid calling sed multiple times in get_system_size kdump-lib.sh: batch fix issues found with shellcheck kdump-lib.sh: reformat with shfmt kdump-logger.sh: refactor to remove some bash only syntax kdump-logger.sh: make it POSIX compatible mkdumprd: allow using dash
.editorconfig | 32 + dracut-early-kdump-module-setup.sh | 11 +- dracut-kdump-emergency.service | 2 +- dracut-kdump-error-handler.sh | 10 - dracut-kdump.sh | 511 ++++++++--- dracut-module-setup.sh | 668 +++++++------- kdump-lib-initramfs.sh | 346 ++----- kdump-lib.sh | 1356 +++++++++++++--------------- kdump-logger.sh | 117 +-- kdumpctl | 604 ++++++------- kexec-tools.spec | 2 - mkdumprd | 600 ++++++------ mkfadumprd | 21 +- 13 files changed, 2104 insertions(+), 2176 deletions(-) create mode 100644 .editorconfig delete mode 100755 dracut-kdump-error-handler.sh
EditorConfig file is helpful for tools like `shfmt`, also could be a hint for code styling.
The code style spec used in this new added .editorconfig file is generated based on existing code style.
Following commits will make mkfadumprd, mkdumprd, kdumpctl, kdump-lib.sh, and *-module-setup.sh only be used in first kernel, so use bash syntax for these scripts. Other scripts will use sh syntax for better POSIX compatibility.
Signed-off-by: Kairui Song kasong@redhat.com --- .editorconfig | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 .editorconfig
diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..52aadba3 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,32 @@ +# EditorConfig configuration for kexec-tools +# http://EditorConfig.org + +# Top-most EditorConfig file +root = true + +# Default code style for kexec-tools scripts +[*] +end_of_line = lf +shell_variant = posix +insert_final_newline = true +trim_trailing_whitespace = true +indent_style = tab +indent_size = 1 +switch_case_indent = false +function_next_line = true +binary_next_line = false +space_redirects = true + +# Some scirpts will only run with bash +[{mkfadumprd,mkdumprd,kdumpctl}] +shell_variant = bash + +# Use dracut code style for *-module-setup.sh +[*-module-setup.sh] +shell_variant = bash +indent_style = space +indent_size = 4 +switch_case_indent = true +function_next_line = false +binary_next_line = true +space_redirects = true
Add a helper `kdump_read_conf` to replace read_strip_comments. `kdump_read_conf` does a few more things:
- remove tailing spaces. - format the content, remove duplicated spaces between name and value. - read from KDUMP_CONFIG_FILE (/etc/kdump.conf) directly, avoid pasting "/etc/kdump.conf" path everywhere in the code. - check if config file exists, just in case.
Also unify the environmental variable, now KDUMP_CONFIG_FILE stands for the default config location.
This helps avoid some shell pitfalls about spaces when reading config.
Signed-off-by: Kairui Song kasong@redhat.com --- dracut-kdump.sh | 10 +++++----- dracut-module-setup.sh | 5 +++-- kdump-lib-initramfs.sh | 3 +-- kdump-lib.sh | 11 ++++++----- kdumpctl | 7 +++---- mkdumprd | 2 +- 6 files changed, 19 insertions(+), 19 deletions(-)
diff --git a/dracut-kdump.sh b/dracut-kdump.sh index 3e65c447..3c165b3a 100755 --- a/dracut-kdump.sh +++ b/dracut-kdump.sh @@ -246,10 +246,10 @@ get_host_ip() return 0 }
-read_kdump_conf() +read_kdump_confs() { - if [ ! -f "$KDUMP_CONF" ]; then - derror "$KDUMP_CONF not found" + if [ ! -f "$KDUMP_CONFIG_FILE" ]; then + derror "$KDUMP_CONFIG_FILE not found" return fi
@@ -278,7 +278,7 @@ read_kdump_conf() add_dump_code "dump_ssh $SSH_KEY_LOCATION $config_val" ;; esac - done <<< "$(read_strip_comments $KDUMP_CONF)" + done <<< "$(kdump_read_conf)" }
fence_kdump_notify() @@ -288,7 +288,7 @@ fence_kdump_notify() fi }
-read_kdump_conf +read_kdump_confs fence_kdump_notify
get_host_ip diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index a1f33e8c..ff9f7fee 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -682,7 +682,8 @@ default_dump_target_install_conf() #install kdump.conf and what user specifies in kdump.conf kdump_install_conf() { local _opt _val _pdev - (read_strip_comments /etc/kdump.conf) > ${initdir}/tmp/$$-kdump.conf + + kdump_read_conf > "${initdir}/tmp/$$-kdump.conf"
while read _opt _val; do @@ -711,7 +712,7 @@ kdump_install_conf() { dracut_install "${_val%%[[:blank:]]*}" ;; esac - done <<< "$(read_strip_comments /etc/kdump.conf)" + done <<< "$(kdump_read_conf)"
kdump_install_pre_post_conf
diff --git a/kdump-lib-initramfs.sh b/kdump-lib-initramfs.sh index 319f9a07..50443e55 100755 --- a/kdump-lib-initramfs.sh +++ b/kdump-lib-initramfs.sh @@ -16,7 +16,6 @@ SSH_KEY_LOCATION="/root/.ssh/kdump_id_rsa" KDUMP_SCRIPT_DIR="/kdumpscripts" DD_BLKSIZE=512 FINAL_ACTION="systemctl reboot -f" -KDUMP_CONF="/etc/kdump.conf" KDUMP_PRE="" KDUMP_POST="" NEWROOT="/sysroot" @@ -93,7 +92,7 @@ get_kdump_confs() esac ;; esac - done <<< "$(read_strip_comments $KDUMP_CONF)" + done <<< "$(kdump_read_conf)"
if [ -z "$CORE_COLLECTOR" ]; then CORE_COLLECTOR="$DEFAULT_CORE_COLLECTOR" diff --git a/kdump-lib.sh b/kdump-lib.sh index 4bd9751b..6ed4f5a9 100755 --- a/kdump-lib.sh +++ b/kdump-lib.sh @@ -7,6 +7,7 @@ DEFAULT_PATH="/var/crash/" FENCE_KDUMP_CONFIG_FILE="/etc/sysconfig/fence_kdump" FENCE_KDUMP_SEND="/usr/libexec/fence_kdump_send" FADUMP_ENABLED_SYS_NODE="/sys/kernel/fadump_enabled" +KDUMP_CONFIG_FILE="/etc/kdump.conf"
is_fadump_capable() { @@ -80,12 +81,12 @@ strip_comments() echo $@ | sed -e 's/(.*)#.*/\1/' }
-# Read from kdump config file stripping all comments -read_strip_comments() +# Read kdump config in well formatted style +kdump_read_conf() { - # strip heading spaces, and print any content starting with - # neither space or #, and strip everything after # - sed -n -e "s/^\s*([^# \t][^#]+).*/\1/gp" $1 + # Following steps are applied in order: strip tailing comment, strip tailing space, + # strip heading space, match non-empty line, remove duplicated spaces between conf name and value + [ -f "$KDUMP_CONFIG_FILE" ] && sed -n -e "s/#.*//;s/\s*$//;s/^\s*//;s/(\S+)\s*(.*)/\1 \2/p" $KDUMP_CONFIG_FILE }
# Check if fence kdump is configured in Pacemaker cluster diff --git a/kdumpctl b/kdumpctl index c2f0b3f2..5d9420da 100755 --- a/kdumpctl +++ b/kdumpctl @@ -5,7 +5,6 @@ KDUMP_KERNELVER="" KDUMP_KERNEL="" KDUMP_COMMANDLINE="" KEXEC_ARGS="" -KDUMP_CONFIG_FILE="/etc/kdump.conf" KDUMP_LOG_PATH="/var/log" MKDUMPRD="/sbin/mkdumprd -f" MKFADUMPRD="/sbin/mkfadumprd" @@ -272,7 +271,7 @@ check_config() return 1 fi _opt_rec[$config_opt]="$config_val" - done <<< "$(read_strip_comments $KDUMP_CONFIG_FILE)" + done <<< "$(kdump_read_conf)"
check_failure_action_config || return 1 check_final_action_config || return 1 @@ -731,7 +730,7 @@ check_ssh_config() *) ;; esac - done <<< "$(read_strip_comments $KDUMP_CONFIG_FILE)" + done <<< "$(kdump_read_conf)"
#make sure they've configured kdump.conf for ssh dumps local SSH_TARGET=`echo -n $DUMP_TARGET | sed -n '/.*@/p'` @@ -1362,7 +1361,7 @@ reset_crashkernel() { grubby --args "$crashkernel_default" --update-kernel "$entry" $zipl_arg [[ $zipl_arg ]] && zipl > /dev/null fi - } +}
if [ ! -f "$KDUMP_CONFIG_FILE" ]; then derror "Error: No kdump config file found!" diff --git a/mkdumprd b/mkdumprd index 89a160d1..d5545114 100644 --- a/mkdumprd +++ b/mkdumprd @@ -443,7 +443,7 @@ do *) ;; esac -done <<< "$(read_strip_comments $conf_file)" +done <<< "$(kdump_read_conf)"
handle_default_dump_target
Hi Kairui,
On Thu, 19 Aug 2021 19:39:01 +0800 Kairui Song kasong@redhat.com wrote:
Add a helper `kdump_read_conf` to replace read_strip_comments. `kdump_read_conf` does a few more things:
- remove tailing spaces.
s/tailing/trailing/
AFAIK tailing isn't wrong but trailing is much more common. At least it won the poll i did in the kernel (git log --grep <word> --oneline | wc -l) with 2045 to 76 ;-)
- format the content, remove duplicated spaces between name and value.
- read from KDUMP_CONFIG_FILE (/etc/kdump.conf) directly, avoid pasting "/etc/kdump.conf" path everywhere in the code.
- check if config file exists, just in case.
Also unify the environmental variable, now KDUMP_CONFIG_FILE stands for the default config location.
This helps avoid some shell pitfalls about spaces when reading config.
Signed-off-by: Kairui Song kasong@redhat.com
dracut-kdump.sh | 10 +++++----- dracut-module-setup.sh | 5 +++-- kdump-lib-initramfs.sh | 3 +-- kdump-lib.sh | 11 ++++++----- kdumpctl | 7 +++---- mkdumprd | 2 +- 6 files changed, 19 insertions(+), 19 deletions(-)
diff --git a/dracut-kdump.sh b/dracut-kdump.sh index 3e65c447..3c165b3a 100755 --- a/dracut-kdump.sh +++ b/dracut-kdump.sh @@ -246,10 +246,10 @@ get_host_ip() return 0 }
-read_kdump_conf() +read_kdump_confs() {
- if [ ! -f "$KDUMP_CONF" ]; then
derror "$KDUMP_CONF not found"
- if [ ! -f "$KDUMP_CONFIG_FILE" ]; then
fiderror "$KDUMP_CONFIG_FILE not found" return
@@ -278,7 +278,7 @@ read_kdump_conf() add_dump_code "dump_ssh $SSH_KEY_LOCATION $config_val" ;; esac
- done <<< "$(read_strip_comments $KDUMP_CONF)"
- done <<< "$(kdump_read_conf)"
}
fence_kdump_notify() @@ -288,7 +288,7 @@ fence_kdump_notify() fi }
-read_kdump_conf +read_kdump_confs fence_kdump_notify
get_host_ip diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index a1f33e8c..ff9f7fee 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -682,7 +682,8 @@ default_dump_target_install_conf() #install kdump.conf and what user specifies in kdump.conf kdump_install_conf() { local _opt _val _pdev
- (read_strip_comments /etc/kdump.conf) > ${initdir}/tmp/$$-kdump.conf
kdump_read_conf > "${initdir}/tmp/$$-kdump.conf"
while read _opt _val; do
@@ -711,7 +712,7 @@ kdump_install_conf() { dracut_install "${_val%%[[:blank:]]*}" ;; esac
- done <<< "$(read_strip_comments /etc/kdump.conf)"
done <<< "$(kdump_read_conf)"
kdump_install_pre_post_conf
diff --git a/kdump-lib-initramfs.sh b/kdump-lib-initramfs.sh index 319f9a07..50443e55 100755 --- a/kdump-lib-initramfs.sh +++ b/kdump-lib-initramfs.sh @@ -16,7 +16,6 @@ SSH_KEY_LOCATION="/root/.ssh/kdump_id_rsa" KDUMP_SCRIPT_DIR="/kdumpscripts" DD_BLKSIZE=512 FINAL_ACTION="systemctl reboot -f" -KDUMP_CONF="/etc/kdump.conf" KDUMP_PRE="" KDUMP_POST="" NEWROOT="/sysroot" @@ -93,7 +92,7 @@ get_kdump_confs() esac ;; esac
- done <<< "$(read_strip_comments $KDUMP_CONF)"
done <<< "$(kdump_read_conf)"
if [ -z "$CORE_COLLECTOR" ]; then CORE_COLLECTOR="$DEFAULT_CORE_COLLECTOR"
diff --git a/kdump-lib.sh b/kdump-lib.sh index 4bd9751b..6ed4f5a9 100755 --- a/kdump-lib.sh +++ b/kdump-lib.sh @@ -7,6 +7,7 @@ DEFAULT_PATH="/var/crash/" FENCE_KDUMP_CONFIG_FILE="/etc/sysconfig/fence_kdump" FENCE_KDUMP_SEND="/usr/libexec/fence_kdump_send" FADUMP_ENABLED_SYS_NODE="/sys/kernel/fadump_enabled" +KDUMP_CONFIG_FILE="/etc/kdump.conf"
is_fadump_capable() { @@ -80,12 +81,12 @@ strip_comments() echo $@ | sed -e 's/(.*)#.*/\1/' }
-# Read from kdump config file stripping all comments -read_strip_comments() +# Read kdump config in well formatted style +kdump_read_conf() {
- # strip heading spaces, and print any content starting with
- # neither space or #, and strip everything after #
- sed -n -e "s/^\s*([^# \t][^#]+).*/\1/gp" $1
- # Following steps are applied in order: strip tailing comment, strip tailing space,
s/tailing/trailing/
Thanks Philipp
- # strip heading space, match non-empty line, remove duplicated spaces between conf name and value
- [ -f "$KDUMP_CONFIG_FILE" ] && sed -n -e "s/#.*//;s/\s*$//;s/^\s*//;s/(\S+)\s*(.*)/\1 \2/p" $KDUMP_CONFIG_FILE
}
# Check if fence kdump is configured in Pacemaker cluster diff --git a/kdumpctl b/kdumpctl index c2f0b3f2..5d9420da 100755 --- a/kdumpctl +++ b/kdumpctl @@ -5,7 +5,6 @@ KDUMP_KERNELVER="" KDUMP_KERNEL="" KDUMP_COMMANDLINE="" KEXEC_ARGS="" -KDUMP_CONFIG_FILE="/etc/kdump.conf" KDUMP_LOG_PATH="/var/log" MKDUMPRD="/sbin/mkdumprd -f" MKFADUMPRD="/sbin/mkfadumprd" @@ -272,7 +271,7 @@ check_config() return 1 fi _opt_rec[$config_opt]="$config_val"
- done <<< "$(read_strip_comments $KDUMP_CONFIG_FILE)"
done <<< "$(kdump_read_conf)"
check_failure_action_config || return 1 check_final_action_config || return 1
@@ -731,7 +730,7 @@ check_ssh_config() *) ;; esac
- done <<< "$(read_strip_comments $KDUMP_CONFIG_FILE)"
done <<< "$(kdump_read_conf)"
#make sure they've configured kdump.conf for ssh dumps local SSH_TARGET=`echo -n $DUMP_TARGET | sed -n '/.*@/p'`
@@ -1362,7 +1361,7 @@ reset_crashkernel() { grubby --args "$crashkernel_default" --update-kernel "$entry" $zipl_arg [[ $zipl_arg ]] && zipl > /dev/null fi
- }
+}
if [ ! -f "$KDUMP_CONFIG_FILE" ]; then derror "Error: No kdump config file found!" diff --git a/mkdumprd b/mkdumprd index 89a160d1..d5545114 100644 --- a/mkdumprd +++ b/mkdumprd @@ -443,7 +443,7 @@ do *) ;; esac -done <<< "$(read_strip_comments $conf_file)" +done <<< "$(kdump_read_conf)"
handle_default_dump_target
On Fri, Sep 3, 2021 at 8:06 PM Philipp Rudo prudo@redhat.com wrote:
Hi Kairui,
On Thu, 19 Aug 2021 19:39:01 +0800 Kairui Song kasong@redhat.com wrote:
Add a helper `kdump_read_conf` to replace read_strip_comments. `kdump_read_conf` does a few more things:
- remove tailing spaces.
s/tailing/trailing/
AFAIK tailing isn't wrong but trailing is much more common. At least it won the poll i did in the kernel (git log --grep <word> --oneline | wc -l) with 2045 to 76 ;-)
Cool, thanks! I never noticed this difference before :)
- format the content, remove duplicated spaces between name and value.
- read from KDUMP_CONFIG_FILE (/etc/kdump.conf) directly, avoid pasting "/etc/kdump.conf" path everywhere in the code.
- check if config file exists, just in case.
Also unify the environmental variable, now KDUMP_CONFIG_FILE stands for the default config location.
This helps avoid some shell pitfalls about spaces when reading config.
Signed-off-by: Kairui Song kasong@redhat.com
dracut-kdump.sh | 10 +++++----- dracut-module-setup.sh | 5 +++-- kdump-lib-initramfs.sh | 3 +-- kdump-lib.sh | 11 ++++++----- kdumpctl | 7 +++---- mkdumprd | 2 +- 6 files changed, 19 insertions(+), 19 deletions(-)
diff --git a/dracut-kdump.sh b/dracut-kdump.sh index 3e65c447..3c165b3a 100755 --- a/dracut-kdump.sh +++ b/dracut-kdump.sh @@ -246,10 +246,10 @@ get_host_ip() return 0 }
-read_kdump_conf() +read_kdump_confs() {
- if [ ! -f "$KDUMP_CONF" ]; then
derror "$KDUMP_CONF not found"
- if [ ! -f "$KDUMP_CONFIG_FILE" ]; then
fiderror "$KDUMP_CONFIG_FILE not found" return
@@ -278,7 +278,7 @@ read_kdump_conf() add_dump_code "dump_ssh $SSH_KEY_LOCATION $config_val" ;; esac
- done <<< "$(read_strip_comments $KDUMP_CONF)"
- done <<< "$(kdump_read_conf)"
}
fence_kdump_notify() @@ -288,7 +288,7 @@ fence_kdump_notify() fi }
-read_kdump_conf +read_kdump_confs fence_kdump_notify
get_host_ip diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index a1f33e8c..ff9f7fee 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -682,7 +682,8 @@ default_dump_target_install_conf() #install kdump.conf and what user specifies in kdump.conf kdump_install_conf() { local _opt _val _pdev
- (read_strip_comments /etc/kdump.conf) > ${initdir}/tmp/$$-kdump.conf
kdump_read_conf > "${initdir}/tmp/$$-kdump.conf"
while read _opt _val; do
@@ -711,7 +712,7 @@ kdump_install_conf() { dracut_install "${_val%%[[:blank:]]*}" ;; esac
- done <<< "$(read_strip_comments /etc/kdump.conf)"
done <<< "$(kdump_read_conf)"
kdump_install_pre_post_conf
diff --git a/kdump-lib-initramfs.sh b/kdump-lib-initramfs.sh index 319f9a07..50443e55 100755 --- a/kdump-lib-initramfs.sh +++ b/kdump-lib-initramfs.sh @@ -16,7 +16,6 @@ SSH_KEY_LOCATION="/root/.ssh/kdump_id_rsa" KDUMP_SCRIPT_DIR="/kdumpscripts" DD_BLKSIZE=512 FINAL_ACTION="systemctl reboot -f" -KDUMP_CONF="/etc/kdump.conf" KDUMP_PRE="" KDUMP_POST="" NEWROOT="/sysroot" @@ -93,7 +92,7 @@ get_kdump_confs() esac ;; esac
- done <<< "$(read_strip_comments $KDUMP_CONF)"
done <<< "$(kdump_read_conf)"
if [ -z "$CORE_COLLECTOR" ]; then CORE_COLLECTOR="$DEFAULT_CORE_COLLECTOR"
diff --git a/kdump-lib.sh b/kdump-lib.sh index 4bd9751b..6ed4f5a9 100755 --- a/kdump-lib.sh +++ b/kdump-lib.sh @@ -7,6 +7,7 @@ DEFAULT_PATH="/var/crash/" FENCE_KDUMP_CONFIG_FILE="/etc/sysconfig/fence_kdump" FENCE_KDUMP_SEND="/usr/libexec/fence_kdump_send" FADUMP_ENABLED_SYS_NODE="/sys/kernel/fadump_enabled" +KDUMP_CONFIG_FILE="/etc/kdump.conf"
is_fadump_capable() { @@ -80,12 +81,12 @@ strip_comments() echo $@ | sed -e 's/(.*)#.*/\1/' }
-# Read from kdump config file stripping all comments -read_strip_comments() +# Read kdump config in well formatted style +kdump_read_conf() {
- # strip heading spaces, and print any content starting with
- # neither space or #, and strip everything after #
- sed -n -e "s/^\s*([^# \t][^#]+).*/\1/gp" $1
- # Following steps are applied in order: strip tailing comment, strip tailing space,
s/tailing/trailing/
Thanks Philipp
- # strip heading space, match non-empty line, remove duplicated spaces between conf name and value
- [ -f "$KDUMP_CONFIG_FILE" ] && sed -n -e "s/#.*//;s/\s*$//;s/^\s*//;s/(\S+)\s*(.*)/\1 \2/p" $KDUMP_CONFIG_FILE
}
# Check if fence kdump is configured in Pacemaker cluster diff --git a/kdumpctl b/kdumpctl index c2f0b3f2..5d9420da 100755 --- a/kdumpctl +++ b/kdumpctl @@ -5,7 +5,6 @@ KDUMP_KERNELVER="" KDUMP_KERNEL="" KDUMP_COMMANDLINE="" KEXEC_ARGS="" -KDUMP_CONFIG_FILE="/etc/kdump.conf" KDUMP_LOG_PATH="/var/log" MKDUMPRD="/sbin/mkdumprd -f" MKFADUMPRD="/sbin/mkfadumprd" @@ -272,7 +271,7 @@ check_config() return 1 fi _opt_rec[$config_opt]="$config_val"
done <<< "$(read_strip_comments $KDUMP_CONFIG_FILE)"
done <<< "$(kdump_read_conf)" check_failure_action_config || return 1 check_final_action_config || return 1
@@ -731,7 +730,7 @@ check_ssh_config() *) ;; esac
done <<< "$(read_strip_comments $KDUMP_CONFIG_FILE)"
done <<< "$(kdump_read_conf)" #make sure they've configured kdump.conf for ssh dumps local SSH_TARGET=`echo -n $DUMP_TARGET | sed -n '/.*@/p'`
@@ -1362,7 +1361,7 @@ reset_crashkernel() { grubby --args "$crashkernel_default" --update-kernel "$entry" $zipl_arg [[ $zipl_arg ]] && zipl > /dev/null fi
- }
+}
if [ ! -f "$KDUMP_CONFIG_FILE" ]; then derror "Error: No kdump config file found!" diff --git a/mkdumprd b/mkdumprd index 89a160d1..d5545114 100644 --- a/mkdumprd +++ b/mkdumprd @@ -443,7 +443,7 @@ do *) ;; esac -done <<< "$(read_strip_comments $conf_file)" +done <<< "$(kdump_read_conf)"
handle_default_dump_target
-- Best Regards, Kairui Song
Add a helper kdump_get_conf_val to replace get_option_value.
It can help cover more corner cases in the code, like when there are multiple spaces in config file value, heading spaces or tailing comments.
And this uses "sed group command" and "sed hold buffer", make it much faster than previous `grep <config> | tail -1`.
This helper is supposed to provide a universal way for kexec-tools scripts to read in config value. Currently, different scripts are reading the config in many different fragile ways.
For example: 1. grep ^force_rebuild $KDUMP_CONFIG_FILE echo $_force_rebuild | cut -d' ' -f2
2. grep ^kdump_post $KDUMP_CONFIG_FILE | cut -d\ -f2
3. awk '/^sshkey/ {print $2}' $conf_file
4. grep ^path $KDUMP_CONFIG_FILE | cut -d' ' -f2-
1 and 2 will fail if there are multiple spaces between config name and config value, like: "kdump_post /var/crash/scripts/kdump-post.sh" A space will be read instead of config value.
1, 2, 3 will fail if there are space in file path, like: "kdump_post /var/crash/scripts dir/kdump-post.sh"
4 will fail if there are tailing comments: "path /var/crash # some comment here"
And all will fail if there are heading space, " path /var/crash"
And all of them are slower than the new sed call. Old get_option_value is also very slow and doesn't handle heading space.
Although we never claim to support heading space or tailing comments before, it's harmless to be more robust on config reading since many conf files in /etc support heading spaces. And have a faster and safer config reading helper makes it easier to clean up the code.
Signed-off-by: Kairui Song kasong@redhat.com --- dracut-module-setup.sh | 4 ++-- kdump-lib.sh | 20 +++++++++----------- kdumpctl | 2 +- 3 files changed, 12 insertions(+), 14 deletions(-)
diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index ff9f7fee..53abdc75 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -938,7 +938,7 @@ get_generic_fence_kdump_nodes() { local filtered local nodes
- nodes=$(get_option_value "fence_kdump_nodes") + nodes=$(kdump_get_conf_val "fence_kdump_nodes") for node in ${nodes}; do # Skip its own node name if is_localhost $node; then @@ -999,7 +999,7 @@ kdump_install_random_seed() { }
kdump_install_systemd_conf() { - local failure_action=$(get_option_value "failure_action") + local failure_action=$(kdump_get_conf_val "failure_action")
# Kdump turns out to require longer default systemd mount timeout # than 1st kernel(90s by default), we use default 300s for kdump. diff --git a/kdump-lib.sh b/kdump-lib.sh index 6ed4f5a9..aad17be3 100755 --- a/kdump-lib.sh +++ b/kdump-lib.sh @@ -76,11 +76,6 @@ is_fs_dump_target() egrep -q "^ext[234]|^xfs|^btrfs|^minix" /etc/kdump.conf }
-strip_comments() -{ - echo $@ | sed -e 's/(.*)#.*/\1/' -} - # Read kdump config in well formatted style kdump_read_conf() { @@ -89,6 +84,15 @@ kdump_read_conf() [ -f "$KDUMP_CONFIG_FILE" ] && sed -n -e "s/#.*//;s/\s*$//;s/^\s*//;s/(\S+)\s*(.*)/\1 \2/p" $KDUMP_CONFIG_FILE }
+# Retrieves config value defined in kdump.conf +# $1: config name, sed regexp compatible +kdump_get_conf_val() { + # For lines matching "^\s*$1\s+", remove matched part (config name including space), + # remove tailing comment, space, then store in hold space. Print out the hold buffer on last line. + [ -f "$KDUMP_CONFIG_FILE" ] && \ + sed -n -e "/^\s*($1)\s+/{s/^\s*($1)\s+//;s/#.*//;s/\s*$//;h};${x;p}" $KDUMP_CONFIG_FILE +} + # Check if fence kdump is configured in Pacemaker cluster is_pcs_fence_kdump() { @@ -322,12 +326,6 @@ get_kdump_mntpoint_from_target() echo $_mntpoint | tr -s "/" }
-# get_option_value <option_name> -# retrieves value of option defined in kdump.conf -get_option_value() { - strip_comments `grep "^$1[[:space:]]+" /etc/kdump.conf | tail -1 | cut -d\ -f2-` -} - kdump_get_persistent_dev() { local dev="${1//"/}"
diff --git a/kdumpctl b/kdumpctl index 5d9420da..db3a3015 100755 --- a/kdumpctl +++ b/kdumpctl @@ -961,7 +961,7 @@ check_fence_kdump_config() { local hostname=`hostname` local ipaddrs=`hostname -I` - local nodes=$(get_option_value "fence_kdump_nodes") + local nodes=$(kdump_get_conf_val "fence_kdump_nodes")
for node in $nodes; do if [ "$node" = "$hostname" ]; then
Hi Kairui,
in subject s/retrive/retrieve/
On Thu, 19 Aug 2021 19:39:02 +0800 Kairui Song kasong@redhat.com wrote:
Add a helper kdump_get_conf_val to replace get_option_value.
It can help cover more corner cases in the code, like when there are multiple spaces in config file value, heading spaces or tailing comments.
s/tailing/trailing/
And this uses "sed group command" and "sed hold buffer", make it much faster than previous `grep <config> | tail -1`.
This helper is supposed to provide a universal way for kexec-tools scripts to read in config value. Currently, different scripts are reading the config in many different fragile ways.
For example:
grep ^force_rebuild $KDUMP_CONFIG_FILE echo $_force_rebuild | cut -d' ' -f2
grep ^kdump_post $KDUMP_CONFIG_FILE | cut -d\ -f2
awk '/^sshkey/ {print $2}' $conf_file
grep ^path $KDUMP_CONFIG_FILE | cut -d' ' -f2-
1 and 2 will fail if there are multiple spaces between config name and config value, like: "kdump_post /var/crash/scripts/kdump-post.sh" A space will be read instead of config value.
1, 2, 3 will fail if there are space in file path, like: "kdump_post /var/crash/scripts dir/kdump-post.sh"
4 will fail if there are tailing comments: "path /var/crash # some comment here"
And all will fail if there are heading space, " path /var/crash"
And all of them are slower than the new sed call. Old get_option_value is also very slow and doesn't handle heading space.
1, 2, and 4 will fail if the space is replaced by, e.g. a tab
And all will most likely cause problems if the config file contains the same option more than once.
Although we never claim to support heading space or tailing comments before, it's harmless to be more robust on config reading since many conf files in /etc support heading spaces. And have a faster and safer config reading helper makes it easier to clean up the code.
Signed-off-by: Kairui Song kasong@redhat.com
dracut-module-setup.sh | 4 ++-- kdump-lib.sh | 20 +++++++++----------- kdumpctl | 2 +- 3 files changed, 12 insertions(+), 14 deletions(-)
diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index ff9f7fee..53abdc75 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -938,7 +938,7 @@ get_generic_fence_kdump_nodes() { local filtered local nodes
- nodes=$(get_option_value "fence_kdump_nodes")
- nodes=$(kdump_get_conf_val "fence_kdump_nodes") for node in ${nodes}; do # Skip its own node name if is_localhost $node; then
@@ -999,7 +999,7 @@ kdump_install_random_seed() { }
kdump_install_systemd_conf() {
- local failure_action=$(get_option_value "failure_action")
local failure_action=$(kdump_get_conf_val "failure_action")
# Kdump turns out to require longer default systemd mount timeout # than 1st kernel(90s by default), we use default 300s for kdump.
diff --git a/kdump-lib.sh b/kdump-lib.sh index 6ed4f5a9..aad17be3 100755 --- a/kdump-lib.sh +++ b/kdump-lib.sh @@ -76,11 +76,6 @@ is_fs_dump_target() egrep -q "^ext[234]|^xfs|^btrfs|^minix" /etc/kdump.conf }
-strip_comments() -{
- echo $@ | sed -e 's/(.*)#.*/\1/'
-}
# Read kdump config in well formatted style kdump_read_conf() { @@ -89,6 +84,15 @@ kdump_read_conf() [ -f "$KDUMP_CONFIG_FILE" ] && sed -n -e "s/#.*//;s/\s*$//;s/^\s*//;s/(\S+)\s*(.*)/\1 \2/p" $KDUMP_CONFIG_FILE }
+# Retrieves config value defined in kdump.conf +# $1: config name, sed regexp compatible +kdump_get_conf_val() {
- # For lines matching "^\s*$1\s+", remove matched part (config name including space),
- # remove tailing comment, space, then store in hold space. Print out the hold buffer on last line.
s/tailing/trailing/
Thanks Philipp
- [ -f "$KDUMP_CONFIG_FILE" ] && \
sed -n -e "/^\s*\($1\)\s\+/{s/^\s*\($1\)\s\+//;s/#.*//;s/\s*$//;h};\${x;p}" $KDUMP_CONFIG_FILE
+}
# Check if fence kdump is configured in Pacemaker cluster is_pcs_fence_kdump() { @@ -322,12 +326,6 @@ get_kdump_mntpoint_from_target() echo $_mntpoint | tr -s "/" }
-# get_option_value <option_name> -# retrieves value of option defined in kdump.conf -get_option_value() {
- strip_comments `grep "^$1[[:space:]]+" /etc/kdump.conf | tail -1 | cut -d\ -f2-`
-}
kdump_get_persistent_dev() { local dev="${1//"/}"
diff --git a/kdumpctl b/kdumpctl index 5d9420da..db3a3015 100755 --- a/kdumpctl +++ b/kdumpctl @@ -961,7 +961,7 @@ check_fence_kdump_config() { local hostname=`hostname` local ipaddrs=`hostname -I`
- local nodes=$(get_option_value "fence_kdump_nodes")
local nodes=$(kdump_get_conf_val "fence_kdump_nodes")
for node in $nodes; do if [ "$node" = "$hostname" ]; then
Signed-off-by: Kairui Song kasong@redhat.com --- kdump-lib.sh | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-)
diff --git a/kdump-lib.sh b/kdump-lib.sh index aad17be3..58422d8b 100755 --- a/kdump-lib.sh +++ b/kdump-lib.sh @@ -42,16 +42,16 @@ is_fs_type_nfs()
is_ssh_dump_target() { - grep -q "^ssh[[:blank:]].*@" /etc/kdump.conf + [[ $(kdump_get_conf_val ssh) == *@* ]] }
is_nfs_dump_target() { - if grep -q "^nfs" /etc/kdump.conf; then + if [[ $(kdump_get_conf_val nfs) ]]; then return 0; fi
- if is_fs_type_nfs $(get_dracut_args_fstype "$(grep "^dracut_args .*--mount" /etc/kdump.conf)"); then + if is_fs_type_nfs $(get_dracut_args_fstype "$(kdump_get_conf_val dracut_args)"); then return 0 fi
@@ -68,12 +68,12 @@ is_nfs_dump_target()
is_raw_dump_target() { - grep -q "^raw" /etc/kdump.conf + [[ $(kdump_get_conf_val raw) ]] }
is_fs_dump_target() { - egrep -q "^ext[234]|^xfs|^btrfs|^minix" /etc/kdump.conf + [[ $(kdump_get_conf_val "ext[234]|xfs|btrfs|minix") ]] }
# Read kdump config in well formatted style @@ -109,7 +109,7 @@ is_generic_fence_kdump() { [ -x $FENCE_KDUMP_SEND ] || return 1
- grep -q "^fence_kdump_nodes" /etc/kdump.conf + [[ $(kdump_get_conf_val fence_kdump_nodes) ]] }
to_dev_name() { @@ -128,17 +128,17 @@ to_dev_name() {
is_user_configured_dump_target() { - grep -E -q "^ext[234]|^xfs|^btrfs|^minix|^raw|^nfs|^ssh" /etc/kdump.conf || is_mount_in_dracut_args; + [[ $(kdump_get_conf_val "ext[234]|xfs|btrfs|minix|raw|nfs|ssh") ]] || is_mount_in_dracut_args }
get_user_configured_dump_disk() { local _target
- _target=$(egrep "^ext[234]|^xfs|^btrfs|^minix|^raw" /etc/kdump.conf 2>/dev/null |awk '{print $2}') + _target=$(kdump_get_conf_val "ext[234]|xfs|btrfs|minix|raw") [ -n "$_target" ] && echo $_target && return
- _target=$(get_dracut_args_target "$(grep "^dracut_args .*--mount" /etc/kdump.conf)") + _target=$(get_dracut_args_target "$(kdump_get_conf_val "dracut_args")") [ -b "$_target" ] && echo $_target }
@@ -149,7 +149,7 @@ get_root_fs_device()
get_save_path() { - local _save_path=$(awk '$1 == "path" {print $2}' /etc/kdump.conf) + local _save_path=$(kdump_get_conf_val path) [ -z "$_save_path" ] && _save_path=$DEFAULT_PATH
# strip the duplicated "/" @@ -175,7 +175,7 @@ get_block_dump_target()
is_dump_to_rootfs() { - grep -E "^(failure_action|default)[[:space:]]dump_to_rootfs" /etc/kdump.conf >/dev/null + [[ $(kdump_get_conf_val "failure_action|default") == dump_to_rootfs ]] }
get_failure_action_target() @@ -530,7 +530,7 @@ get_ifcfg_filename() { is_dracut_mod_omitted() { local dracut_args dracut_mod=$1
- set -- $(grep "^dracut_args" /etc/kdump.conf) + set -- $(kdump_get_conf_val dracut_args) while [ $# -gt 0 ]; do case $1 in -o|--omit) @@ -559,7 +559,7 @@ is_wdt_active() { # its correctness). is_mount_in_dracut_args() { - grep -q "^dracut_args .*--mount" /etc/kdump.conf + [[ $(kdump_get_conf_val dracut_args) == *" --mount "* ]] }
# If $1 contains dracut_args "--mount", return <filesystem type>
Hi Kairui,
On Thu, 19 Aug 2021 19:39:03 +0800 Kairui Song kasong@redhat.com wrote:
Signed-off-by: Kairui Song kasong@redhat.com
kdump-lib.sh | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-)
diff --git a/kdump-lib.sh b/kdump-lib.sh index aad17be3..58422d8b 100755 --- a/kdump-lib.sh +++ b/kdump-lib.sh @@ -42,16 +42,16 @@ is_fs_type_nfs()
is_ssh_dump_target() {
- grep -q "^ssh[[:blank:]].*@" /etc/kdump.conf
- [[ $(kdump_get_conf_val ssh) == *@* ]]
}
is_nfs_dump_target() {
- if grep -q "^nfs" /etc/kdump.conf; then
- if [[ $(kdump_get_conf_val nfs) ]]; then return 0; fi
- if is_fs_type_nfs $(get_dracut_args_fstype "$(grep "^dracut_args .*--mount" /etc/kdump.conf)"); then
- if is_fs_type_nfs $(get_dracut_args_fstype "$(kdump_get_conf_val dracut_args)"); then return 0 fi
@@ -68,12 +68,12 @@ is_nfs_dump_target()
is_raw_dump_target() {
- grep -q "^raw" /etc/kdump.conf
- [[ $(kdump_get_conf_val raw) ]]
}
is_fs_dump_target() {
- egrep -q "^ext[234]|^xfs|^btrfs|^minix" /etc/kdump.conf
- [[ $(kdump_get_conf_val "ext[234]|xfs|btrfs|minix") ]]
}
# Read kdump config in well formatted style @@ -109,7 +109,7 @@ is_generic_fence_kdump() { [ -x $FENCE_KDUMP_SEND ] || return 1
- grep -q "^fence_kdump_nodes" /etc/kdump.conf
- [[ $(kdump_get_conf_val fence_kdump_nodes) ]]
}
to_dev_name() { @@ -128,17 +128,17 @@ to_dev_name() {
is_user_configured_dump_target() {
- grep -E -q "^ext[234]|^xfs|^btrfs|^minix|^raw|^nfs|^ssh" /etc/kdump.conf || is_mount_in_dracut_args;
- [[ $(kdump_get_conf_val "ext[234]|xfs|btrfs|minix|raw|nfs|ssh") ]] || is_mount_in_dracut_args
}
get_user_configured_dump_disk() { local _target
- _target=$(egrep "^ext[234]|^xfs|^btrfs|^minix|^raw" /etc/kdump.conf 2>/dev/null |awk '{print $2}')
- _target=$(kdump_get_conf_val "ext[234]|xfs|btrfs|minix|raw") [ -n "$_target" ] && echo $_target && return
- _target=$(get_dracut_args_target "$(grep "^dracut_args .*--mount" /etc/kdump.conf)")
- _target=$(get_dracut_args_target "$(kdump_get_conf_val "dracut_args")") [ -b "$_target" ] && echo $_target
}
@@ -149,7 +149,7 @@ get_root_fs_device()
get_save_path() {
- local _save_path=$(awk '$1 == "path" {print $2}' /etc/kdump.conf)
local _save_path=$(kdump_get_conf_val path) [ -z "$_save_path" ] && _save_path=$DEFAULT_PATH
# strip the duplicated "/"
@@ -175,7 +175,7 @@ get_block_dump_target()
is_dump_to_rootfs() {
- grep -E "^(failure_action|default)[[:space:]]dump_to_rootfs" /etc/kdump.conf >/dev/null
- [[ $(kdump_get_conf_val "failure_action|default") == dump_to_rootfs ]]
}
get_failure_action_target() @@ -530,7 +530,7 @@ get_ifcfg_filename() { is_dracut_mod_omitted() { local dracut_args dracut_mod=$1
- set -- $(grep "^dracut_args" /etc/kdump.conf)
- set -- $(kdump_get_conf_val dracut_args) while [ $# -gt 0 ]; do case $1 in -o|--omit)
@@ -559,7 +559,7 @@ is_wdt_active() { # its correctness). is_mount_in_dracut_args() {
- grep -q "^dracut_args .*--mount" /etc/kdump.conf
- [[ $(kdump_get_conf_val dracut_args) == *" --mount "* ]]
does dracut allow passing arguments with a '=', i.e. --mount="<mountpoint>"? If it does the check is broken...
Thanks Philipp
}
# If $1 contains dracut_args "--mount", return <filesystem type>
is sepOn Fri, Sep 3, 2021 at 8:12 PM Philipp Rudo prudo@redhat.com wrote:
Hi Kairui,
On Thu, 19 Aug 2021 19:39:03 +0800 Kairui Song kasong@redhat.com wrote:
Signed-off-by: Kairui Song kasong@redhat.com
kdump-lib.sh | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-)
diff --git a/kdump-lib.sh b/kdump-lib.sh index aad17be3..58422d8b 100755 --- a/kdump-lib.sh +++ b/kdump-lib.sh @@ -42,16 +42,16 @@ is_fs_type_nfs()
is_ssh_dump_target() {
- grep -q "^ssh[[:blank:]].*@" /etc/kdump.conf
- [[ $(kdump_get_conf_val ssh) == *@* ]]
}
is_nfs_dump_target() {
- if grep -q "^nfs" /etc/kdump.conf; then
- if [[ $(kdump_get_conf_val nfs) ]]; then return 0; fi
- if is_fs_type_nfs $(get_dracut_args_fstype "$(grep "^dracut_args .*--mount" /etc/kdump.conf)"); then
- if is_fs_type_nfs $(get_dracut_args_fstype "$(kdump_get_conf_val dracut_args)"); then return 0 fi
@@ -68,12 +68,12 @@ is_nfs_dump_target()
is_raw_dump_target() {
- grep -q "^raw" /etc/kdump.conf
- [[ $(kdump_get_conf_val raw) ]]
}
is_fs_dump_target() {
- egrep -q "^ext[234]|^xfs|^btrfs|^minix" /etc/kdump.conf
- [[ $(kdump_get_conf_val "ext[234]|xfs|btrfs|minix") ]]
}
# Read kdump config in well formatted style @@ -109,7 +109,7 @@ is_generic_fence_kdump() { [ -x $FENCE_KDUMP_SEND ] || return 1
- grep -q "^fence_kdump_nodes" /etc/kdump.conf
- [[ $(kdump_get_conf_val fence_kdump_nodes) ]]
}
to_dev_name() { @@ -128,17 +128,17 @@ to_dev_name() {
is_user_configured_dump_target() {
- grep -E -q "^ext[234]|^xfs|^btrfs|^minix|^raw|^nfs|^ssh" /etc/kdump.conf || is_mount_in_dracut_args;
- [[ $(kdump_get_conf_val "ext[234]|xfs|btrfs|minix|raw|nfs|ssh") ]] || is_mount_in_dracut_args
}
get_user_configured_dump_disk() { local _target
- _target=$(egrep "^ext[234]|^xfs|^btrfs|^minix|^raw" /etc/kdump.conf 2>/dev/null |awk '{print $2}')
- _target=$(kdump_get_conf_val "ext[234]|xfs|btrfs|minix|raw") [ -n "$_target" ] && echo $_target && return
- _target=$(get_dracut_args_target "$(grep "^dracut_args .*--mount" /etc/kdump.conf)")
- _target=$(get_dracut_args_target "$(kdump_get_conf_val "dracut_args")") [ -b "$_target" ] && echo $_target
}
@@ -149,7 +149,7 @@ get_root_fs_device()
get_save_path() {
- local _save_path=$(awk '$1 == "path" {print $2}' /etc/kdump.conf)
local _save_path=$(kdump_get_conf_val path) [ -z "$_save_path" ] && _save_path=$DEFAULT_PATH
# strip the duplicated "/"
@@ -175,7 +175,7 @@ get_block_dump_target()
is_dump_to_rootfs() {
- grep -E "^(failure_action|default)[[:space:]]dump_to_rootfs" /etc/kdump.conf >/dev/null
- [[ $(kdump_get_conf_val "failure_action|default") == dump_to_rootfs ]]
}
get_failure_action_target() @@ -530,7 +530,7 @@ get_ifcfg_filename() { is_dracut_mod_omitted() { local dracut_args dracut_mod=$1
- set -- $(grep "^dracut_args" /etc/kdump.conf)
- set -- $(kdump_get_conf_val dracut_args) while [ $# -gt 0 ]; do case $1 in -o|--omit)
@@ -559,7 +559,7 @@ is_wdt_active() { # its correctness). is_mount_in_dracut_args() {
- grep -q "^dracut_args .*--mount" /etc/kdump.conf
- [[ $(kdump_get_conf_val dracut_args) == *" --mount "* ]]
does dracut allow passing arguments with a '=', i.e. --mount="<mountpoint>"? If it does the check is broken...
Hmm, yes, and after a careful look, I found kexec-tools script have multiple other functions assuming --mount is separated by space. I can update this to fix it this time with:
[[ " $(kdump_get_conf_val dracut_args)" =~ .*[[:space:]]--mount[=[:space:]].* ]]
-- Best Regards, Kairui Song
Hi Kairui,
On Mon, 13 Sep 2021 04:24:02 +0800 Kairui Song kasong@redhat.com wrote:
is sepOn Fri, Sep 3, 2021 at 8:12 PM Philipp Rudo prudo@redhat.com wrote:
Hi Kairui,
On Thu, 19 Aug 2021 19:39:03 +0800 Kairui Song kasong@redhat.com wrote:
Signed-off-by: Kairui Song kasong@redhat.com
kdump-lib.sh | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-)
diff --git a/kdump-lib.sh b/kdump-lib.sh index aad17be3..58422d8b 100755 --- a/kdump-lib.sh +++ b/kdump-lib.sh @@ -42,16 +42,16 @@ is_fs_type_nfs()
is_ssh_dump_target() {
- grep -q "^ssh[[:blank:]].*@" /etc/kdump.conf
- [[ $(kdump_get_conf_val ssh) == *@* ]]
}
is_nfs_dump_target() {
- if grep -q "^nfs" /etc/kdump.conf; then
- if [[ $(kdump_get_conf_val nfs) ]]; then return 0; fi
- if is_fs_type_nfs $(get_dracut_args_fstype "$(grep "^dracut_args .*--mount" /etc/kdump.conf)"); then
- if is_fs_type_nfs $(get_dracut_args_fstype "$(kdump_get_conf_val dracut_args)"); then return 0 fi
@@ -68,12 +68,12 @@ is_nfs_dump_target()
is_raw_dump_target() {
- grep -q "^raw" /etc/kdump.conf
- [[ $(kdump_get_conf_val raw) ]]
}
is_fs_dump_target() {
- egrep -q "^ext[234]|^xfs|^btrfs|^minix" /etc/kdump.conf
- [[ $(kdump_get_conf_val "ext[234]|xfs|btrfs|minix") ]]
}
# Read kdump config in well formatted style @@ -109,7 +109,7 @@ is_generic_fence_kdump() { [ -x $FENCE_KDUMP_SEND ] || return 1
- grep -q "^fence_kdump_nodes" /etc/kdump.conf
- [[ $(kdump_get_conf_val fence_kdump_nodes) ]]
}
to_dev_name() { @@ -128,17 +128,17 @@ to_dev_name() {
is_user_configured_dump_target() {
- grep -E -q "^ext[234]|^xfs|^btrfs|^minix|^raw|^nfs|^ssh" /etc/kdump.conf || is_mount_in_dracut_args;
- [[ $(kdump_get_conf_val "ext[234]|xfs|btrfs|minix|raw|nfs|ssh") ]] || is_mount_in_dracut_args
}
get_user_configured_dump_disk() { local _target
- _target=$(egrep "^ext[234]|^xfs|^btrfs|^minix|^raw" /etc/kdump.conf 2>/dev/null |awk '{print $2}')
- _target=$(kdump_get_conf_val "ext[234]|xfs|btrfs|minix|raw") [ -n "$_target" ] && echo $_target && return
- _target=$(get_dracut_args_target "$(grep "^dracut_args .*--mount" /etc/kdump.conf)")
- _target=$(get_dracut_args_target "$(kdump_get_conf_val "dracut_args")") [ -b "$_target" ] && echo $_target
}
@@ -149,7 +149,7 @@ get_root_fs_device()
get_save_path() {
- local _save_path=$(awk '$1 == "path" {print $2}' /etc/kdump.conf)
local _save_path=$(kdump_get_conf_val path) [ -z "$_save_path" ] && _save_path=$DEFAULT_PATH
# strip the duplicated "/"
@@ -175,7 +175,7 @@ get_block_dump_target()
is_dump_to_rootfs() {
- grep -E "^(failure_action|default)[[:space:]]dump_to_rootfs" /etc/kdump.conf >/dev/null
- [[ $(kdump_get_conf_val "failure_action|default") == dump_to_rootfs ]]
}
get_failure_action_target() @@ -530,7 +530,7 @@ get_ifcfg_filename() { is_dracut_mod_omitted() { local dracut_args dracut_mod=$1
- set -- $(grep "^dracut_args" /etc/kdump.conf)
- set -- $(kdump_get_conf_val dracut_args) while [ $# -gt 0 ]; do case $1 in -o|--omit)
@@ -559,7 +559,7 @@ is_wdt_active() { # its correctness). is_mount_in_dracut_args() {
- grep -q "^dracut_args .*--mount" /etc/kdump.conf
- [[ $(kdump_get_conf_val dracut_args) == *" --mount "* ]]
does dracut allow passing arguments with a '=', i.e. --mount="<mountpoint>"? If it does the check is broken...
Hmm, yes, and after a careful look, I found kexec-tools script have multiple other functions assuming --mount is separated by space. I can update this to fix it this time with:
[[ " $(kdump_get_conf_val dracut_args)" =~ .*[[:space:]]--mount[=[:space:]].* ]]
^ I find adding the space to make it work when --mount is at the beginning of the string a little bit hacky. But I don't think there is a better solution with the built in bash regex. So fine by me.
Thanks Philipp
Signed-off-by: Kairui Song kasong@redhat.com --- kdumpctl | 47 +++++++++++++++++++++-------------------------- 1 file changed, 21 insertions(+), 26 deletions(-)
diff --git a/kdumpctl b/kdumpctl index db3a3015..50e92cb4 100755 --- a/kdumpctl +++ b/kdumpctl @@ -339,8 +339,8 @@ check_files_modified() #also rebuild when Pacemaker cluster conf is changed and fence kdump is enabled. modified_files=$(get_pcs_cluster_modified_files)
- EXTRA_BINS=`grep ^kdump_post $KDUMP_CONFIG_FILE | cut -d\ -f2` - CHECK_FILES=`grep ^kdump_pre $KDUMP_CONFIG_FILE | cut -d\ -f2` + EXTRA_BINS=$(kdump_get_conf_val kdump_post) + CHECK_FILES=$(kdump_get_conf_val kdump_pre) HOOKS="/etc/kdump/post.d/ /etc/kdump/pre.d/" if [ -d /etc/kdump/post.d ]; then for file in /etc/kdump/post.d/*; do @@ -357,17 +357,17 @@ check_files_modified() done fi HOOKS="$HOOKS $POST_FILES $PRE_FILES" - CORE_COLLECTOR=`grep ^core_collector $KDUMP_CONFIG_FILE | cut -d\ -f2` + CORE_COLLECTOR=$(kdump_get_conf_val core_collector | cut -d ' ' -f 1) CORE_COLLECTOR=`type -P $CORE_COLLECTOR` # POST_FILES and PRE_FILES are already checked against executable, need not to check again. EXTRA_BINS="$EXTRA_BINS $CHECK_FILES" - CHECK_FILES=`grep ^extra_bins $KDUMP_CONFIG_FILE | cut -d\ -f2-` + CHECK_FILES=$(kdump_get_conf_val extra_bins) EXTRA_BINS="$EXTRA_BINS $CHECK_FILES" files="$KDUMP_CONFIG_FILE $KDUMP_KERNEL $EXTRA_BINS $CORE_COLLECTOR" [[ -e /etc/fstab ]] && files="$files /etc/fstab"
# Check for any updated extra module - EXTRA_MODULES="$(grep ^extra_modules $KDUMP_CONFIG_FILE | sed 's/^extra_modules\s*//')" + EXTRA_MODULES="$(kdump_get_conf_val extra_modules)" if [ -n "$EXTRA_MODULES" ]; then if [ -e /lib/modules/$KDUMP_KERNELVER/modules.dep ]; then files="$files /lib/modules/$KDUMP_KERNELVER/modules.dep" @@ -555,8 +555,7 @@ check_system_modified() check_rebuild() { local capture_capable_initrd="1" - local _force_rebuild force_rebuild="0" - local _force_no_rebuild force_no_rebuild="0" + local force_rebuild force_no_rebuild local ret system_modified="0"
setup_initrd @@ -565,22 +564,18 @@ check_rebuild() return 1 fi
- _force_no_rebuild=`grep ^force_no_rebuild $KDUMP_CONFIG_FILE 2>/dev/null` - if [ $? -eq 0 ]; then - force_no_rebuild=`echo $_force_no_rebuild | cut -d' ' -f2` - if [ "$force_no_rebuild" != "0" ] && [ "$force_no_rebuild" != "1" ];then - derror "Error: force_no_rebuild value is invalid" - return 1 - fi + force_no_rebuild=$(kdump_get_conf_val force_no_rebuild) + force_no_rebuild=${force_no_rebuild:-0} + if [ "$force_no_rebuild" != "0" ] && [ "$force_no_rebuild" != "1" ];then + derror "Error: force_no_rebuild value is invalid" + return 1 fi
- _force_rebuild=`grep ^force_rebuild $KDUMP_CONFIG_FILE 2>/dev/null` - if [ $? -eq 0 ]; then - force_rebuild=`echo $_force_rebuild | cut -d' ' -f2` - if [ "$force_rebuild" != "0" ] && [ "$force_rebuild" != "1" ];then - derror "Error: force_rebuild value is invalid" - return 1 - fi + force_rebuild=$(kdump_get_conf_val force_rebuild) + force_rebuild=${force_rebuild:-0} + if [ "$force_rebuild" != "0" ] && [ "$force_rebuild" != "1" ];then + derror "Error: force_rebuild value is invalid" + return 1 fi
if [[ "$force_no_rebuild" == "1" && "$force_rebuild" == "1" ]]; then @@ -867,7 +862,7 @@ save_raw() local kdump_dir local raw_target
- raw_target=$(awk '$1 ~ /^raw$/ { print $2; }' $KDUMP_CONFIG_FILE) + raw_target=$(kdump_get_conf_val raw) [ -z "$raw_target" ] && return 0 [ -b "$raw_target" ] || { derror "raw partition $raw_target not found" @@ -878,7 +873,7 @@ save_raw() dwarn "Warning: Detected '$check_fs' signature on $raw_target, data loss is expected." return 0 fi - kdump_dir=`grep ^path $KDUMP_CONFIG_FILE | cut -d' ' -f2-` + kdump_dir=$(kdump_get_conf_val path) if [ -z "${kdump_dir}" ]; then coredir="/var/crash/`date +"%Y-%m-%d-%H:%M"`" else @@ -1018,8 +1013,8 @@ check_failure_action_config() local failure_action local option="failure_action"
- default_option=$(awk '$1 ~ /^default$/ {print $2;}' $KDUMP_CONFIG_FILE) - failure_action=$(awk '$1 ~ /^failure_action$/ {print $2;}' $KDUMP_CONFIG_FILE) + default_option=$(kdump_get_conf_val default) + failure_action=$(kdump_get_conf_val failure_action)
if [ -z "$failure_action" -a -z "$default_option" ]; then return 0 @@ -1047,7 +1042,7 @@ check_final_action_config() { local final_action
- final_action=$(awk '$1 ~ /^final_action$/ {print $2;}' $KDUMP_CONFIG_FILE) + final_action=$(kdump_get_conf_val final_action) if [ -z "$final_action" ]; then return 0 else
Hi Kairui,
On Thu, 19 Aug 2021 19:39:04 +0800 Kairui Song kasong@redhat.com wrote:
Signed-off-by: Kairui Song kasong@redhat.com
kdumpctl | 47 +++++++++++++++++++++-------------------------- 1 file changed, 21 insertions(+), 26 deletions(-)
diff --git a/kdumpctl b/kdumpctl index db3a3015..50e92cb4 100755 --- a/kdumpctl +++ b/kdumpctl @@ -339,8 +339,8 @@ check_files_modified() #also rebuild when Pacemaker cluster conf is changed and fence kdump is enabled. modified_files=$(get_pcs_cluster_modified_files)
- EXTRA_BINS=`grep ^kdump_post $KDUMP_CONFIG_FILE | cut -d\ -f2`
- CHECK_FILES=`grep ^kdump_pre $KDUMP_CONFIG_FILE | cut -d\ -f2`
- EXTRA_BINS=$(kdump_get_conf_val kdump_post)
- CHECK_FILES=$(kdump_get_conf_val kdump_pre) HOOKS="/etc/kdump/post.d/ /etc/kdump/pre.d/" if [ -d /etc/kdump/post.d ]; then for file in /etc/kdump/post.d/*; do
@@ -357,17 +357,17 @@ check_files_modified() done fi HOOKS="$HOOKS $POST_FILES $PRE_FILES"
- CORE_COLLECTOR=`grep ^core_collector $KDUMP_CONFIG_FILE | cut -d\ -f2`
- CORE_COLLECTOR=$(kdump_get_conf_val core_collector | cut -d ' ' -f 1)
keeping this cut here still makes you vulnerable to some of the problems you solved by introducing kdump_get_conf_val, e.g. when the core_collector is followed by a tab instead of a space. As this is a bash only file you could make CORE_COLLECTOR an array and then use the first element as command.
BTW in general this function could do with a do over, e.g. files and modified_fiels could be made an array as well. Furthermore some variables seem unnecessary to me and the others probably should be made local. Anyway as the series is already pretty long I think both can wait for the next cleanup series.
Thanks Philipp
CORE_COLLECTOR=`type -P $CORE_COLLECTOR` # POST_FILES and PRE_FILES are already checked against executable, need not to check again. EXTRA_BINS="$EXTRA_BINS $CHECK_FILES"
- CHECK_FILES=`grep ^extra_bins $KDUMP_CONFIG_FILE | cut -d\ -f2-`
CHECK_FILES=$(kdump_get_conf_val extra_bins) EXTRA_BINS="$EXTRA_BINS $CHECK_FILES" files="$KDUMP_CONFIG_FILE $KDUMP_KERNEL $EXTRA_BINS $CORE_COLLECTOR" [[ -e /etc/fstab ]] && files="$files /etc/fstab"
# Check for any updated extra module
- EXTRA_MODULES="$(grep ^extra_modules $KDUMP_CONFIG_FILE | sed 's/^extra_modules\s*//')"
- EXTRA_MODULES="$(kdump_get_conf_val extra_modules)" if [ -n "$EXTRA_MODULES" ]; then if [ -e /lib/modules/$KDUMP_KERNELVER/modules.dep ]; then files="$files /lib/modules/$KDUMP_KERNELVER/modules.dep"
@@ -555,8 +555,7 @@ check_system_modified() check_rebuild() { local capture_capable_initrd="1"
- local _force_rebuild force_rebuild="0"
- local _force_no_rebuild force_no_rebuild="0"
local force_rebuild force_no_rebuild local ret system_modified="0"
setup_initrd
@@ -565,22 +564,18 @@ check_rebuild() return 1 fi
- _force_no_rebuild=`grep ^force_no_rebuild $KDUMP_CONFIG_FILE 2>/dev/null`
- if [ $? -eq 0 ]; then
force_no_rebuild=`echo $_force_no_rebuild | cut -d' ' -f2`
if [ "$force_no_rebuild" != "0" ] && [ "$force_no_rebuild" != "1" ];then
derror "Error: force_no_rebuild value is invalid"
return 1
fi
- force_no_rebuild=$(kdump_get_conf_val force_no_rebuild)
- force_no_rebuild=${force_no_rebuild:-0}
- if [ "$force_no_rebuild" != "0" ] && [ "$force_no_rebuild" != "1" ];then
derror "Error: force_no_rebuild value is invalid"
fireturn 1
- _force_rebuild=`grep ^force_rebuild $KDUMP_CONFIG_FILE 2>/dev/null`
- if [ $? -eq 0 ]; then
force_rebuild=`echo $_force_rebuild | cut -d' ' -f2`
if [ "$force_rebuild" != "0" ] && [ "$force_rebuild" != "1" ];then
derror "Error: force_rebuild value is invalid"
return 1
fi
force_rebuild=$(kdump_get_conf_val force_rebuild)
force_rebuild=${force_rebuild:-0}
if [ "$force_rebuild" != "0" ] && [ "$force_rebuild" != "1" ];then
derror "Error: force_rebuild value is invalid"
return 1
fi
if [[ "$force_no_rebuild" == "1" && "$force_rebuild" == "1" ]]; then
@@ -867,7 +862,7 @@ save_raw() local kdump_dir local raw_target
- raw_target=$(awk '$1 ~ /^raw$/ { print $2; }' $KDUMP_CONFIG_FILE)
- raw_target=$(kdump_get_conf_val raw) [ -z "$raw_target" ] && return 0 [ -b "$raw_target" ] || { derror "raw partition $raw_target not found"
@@ -878,7 +873,7 @@ save_raw() dwarn "Warning: Detected '$check_fs' signature on $raw_target, data loss is expected." return 0 fi
- kdump_dir=`grep ^path $KDUMP_CONFIG_FILE | cut -d' ' -f2-`
- kdump_dir=$(kdump_get_conf_val path) if [ -z "${kdump_dir}" ]; then coredir="/var/crash/`date +"%Y-%m-%d-%H:%M"`" else
@@ -1018,8 +1013,8 @@ check_failure_action_config() local failure_action local option="failure_action"
- default_option=$(awk '$1 ~ /^default$/ {print $2;}' $KDUMP_CONFIG_FILE)
- failure_action=$(awk '$1 ~ /^failure_action$/ {print $2;}' $KDUMP_CONFIG_FILE)
default_option=$(kdump_get_conf_val default)
failure_action=$(kdump_get_conf_val failure_action)
if [ -z "$failure_action" -a -z "$default_option" ]; then return 0
@@ -1047,7 +1042,7 @@ check_final_action_config() { local final_action
- final_action=$(awk '$1 ~ /^final_action$/ {print $2;}' $KDUMP_CONFIG_FILE)
- final_action=$(kdump_get_conf_val final_action) if [ -z "$final_action" ]; then return 0 else
On Fri, Sep 3, 2021 at 8:15 PM Philipp Rudo prudo@redhat.com wrote:
Hi Kairui,
On Thu, 19 Aug 2021 19:39:04 +0800 Kairui Song kasong@redhat.com wrote:
Signed-off-by: Kairui Song kasong@redhat.com
kdumpctl | 47 +++++++++++++++++++++-------------------------- 1 file changed, 21 insertions(+), 26 deletions(-)
diff --git a/kdumpctl b/kdumpctl index db3a3015..50e92cb4 100755 --- a/kdumpctl +++ b/kdumpctl @@ -339,8 +339,8 @@ check_files_modified() #also rebuild when Pacemaker cluster conf is changed and fence kdump is enabled. modified_files=$(get_pcs_cluster_modified_files)
EXTRA_BINS=`grep ^kdump_post $KDUMP_CONFIG_FILE | cut -d\ -f2`
CHECK_FILES=`grep ^kdump_pre $KDUMP_CONFIG_FILE | cut -d\ -f2`
EXTRA_BINS=$(kdump_get_conf_val kdump_post)
CHECK_FILES=$(kdump_get_conf_val kdump_pre) HOOKS="/etc/kdump/post.d/ /etc/kdump/pre.d/" if [ -d /etc/kdump/post.d ]; then for file in /etc/kdump/post.d/*; do
@@ -357,17 +357,17 @@ check_files_modified() done fi HOOKS="$HOOKS $POST_FILES $PRE_FILES"
CORE_COLLECTOR=`grep ^core_collector $KDUMP_CONFIG_FILE | cut -d\ -f2`
CORE_COLLECTOR=$(kdump_get_conf_val core_collector | cut -d ' ' -f 1)
keeping this cut here still makes you vulnerable to some of the problems you solved by introducing kdump_get_conf_val, e.g. when the core_collector is followed by a tab instead of a space. As this is a bash only file you could make CORE_COLLECTOR an array and then use the first element as command.
I think simply use a awk '{print $1}' should be enough just for this case.
BTW in general this function could do with a do over, e.g. files and modified_fiels could be made an array as well. Furthermore some variables seem unnecessary to me and the others probably should be made local. Anyway as the series is already pretty long I think both can wait for the next cleanup series.
Great suggestion, actually I found a lot of extra problems during making this series and recorded some on my local to-do list. Let's fix it later, currently, let me just update this series to avoid introducing any new issue.
-- Best Regards, Kairui Song
Hi Kairui,
On Mon, 13 Sep 2021 04:26:35 +0800 Kairui Song kasong@redhat.com wrote:
On Fri, Sep 3, 2021 at 8:15 PM Philipp Rudo prudo@redhat.com wrote:
Hi Kairui,
On Thu, 19 Aug 2021 19:39:04 +0800 Kairui Song kasong@redhat.com wrote:
Signed-off-by: Kairui Song kasong@redhat.com
kdumpctl | 47 +++++++++++++++++++++-------------------------- 1 file changed, 21 insertions(+), 26 deletions(-)
diff --git a/kdumpctl b/kdumpctl index db3a3015..50e92cb4 100755 --- a/kdumpctl +++ b/kdumpctl @@ -339,8 +339,8 @@ check_files_modified() #also rebuild when Pacemaker cluster conf is changed and fence kdump is enabled. modified_files=$(get_pcs_cluster_modified_files)
EXTRA_BINS=`grep ^kdump_post $KDUMP_CONFIG_FILE | cut -d\ -f2`
CHECK_FILES=`grep ^kdump_pre $KDUMP_CONFIG_FILE | cut -d\ -f2`
EXTRA_BINS=$(kdump_get_conf_val kdump_post)
CHECK_FILES=$(kdump_get_conf_val kdump_pre) HOOKS="/etc/kdump/post.d/ /etc/kdump/pre.d/" if [ -d /etc/kdump/post.d ]; then for file in /etc/kdump/post.d/*; do
@@ -357,17 +357,17 @@ check_files_modified() done fi HOOKS="$HOOKS $POST_FILES $PRE_FILES"
CORE_COLLECTOR=`grep ^core_collector $KDUMP_CONFIG_FILE | cut -d\ -f2`
CORE_COLLECTOR=$(kdump_get_conf_val core_collector | cut -d ' ' -f 1)
keeping this cut here still makes you vulnerable to some of the problems you solved by introducing kdump_get_conf_val, e.g. when the core_collector is followed by a tab instead of a space. As this is a bash only file you could make CORE_COLLECTOR an array and then use the first element as command.
I think simply use a awk '{print $1}' should be enough just for this case.
yes, using awk should do the trick here. But a quick search gave a few other locations with similar usage of cut. So not sure if it's better to fix it now or wait until you fix the other locations.
BTW in general this function could do with a do over, e.g. files and modified_fiels could be made an array as well. Furthermore some variables seem unnecessary to me and the others probably should be made local. Anyway as the series is already pretty long I think both can wait for the next cleanup series.
Great suggestion, actually I found a lot of extra problems during making this series and recorded some on my local to-do list. Let's fix it later, currently, let me just update this series to avoid introducing any new issue.
fully agree. I just wanted to write it down so I don't forget it myself.
Thanks Philipp
Use `grep -c` instead, as suggested in: https://github.com/koalaman/shellcheck/wiki/SC2126
Signed-off-by: Kairui Song kasong@redhat.com --- kdumpctl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/kdumpctl b/kdumpctl index 50e92cb4..82010fd7 100755 --- a/kdumpctl +++ b/kdumpctl @@ -596,7 +596,7 @@ check_rebuild() #in case of fadump mode, check whether the default/target #initrd is already built with dump capture capability if [ "$DEFAULT_DUMP_MODE" == "fadump" ]; then - capture_capable_initrd=$(lsinitrd -f $DRACUT_MODULES_FILE $TARGET_INITRD | grep -e ^kdumpbase$ -e ^zz-fadumpinit$ | wc -l) + capture_capable_initrd=$(lsinitrd -f $DRACUT_MODULES_FILE "$TARGET_INITRD" | grep -c -e ^kdumpbase$ -e ^zz-fadumpinit$) fi fi
For loops over find output are fragile, use a while read loop: https://github.com/koalaman/shellcheck/wiki/SC2044
Signed-off-by: Kairui Song kasong@redhat.com --- kdumpctl | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/kdumpctl b/kdumpctl index 82010fd7..548054bd 100755 --- a/kdumpctl +++ b/kdumpctl @@ -944,12 +944,12 @@ selinux_relabel() return fi
- for _i in $(find $_path); do - _attr=$(getfattr -m "security.selinux" $_i 2>/dev/null) + while read -r _i; do + _attr=$(getfattr -m "security.selinux" "$_i" 2>/dev/null) if [ -z "$_attr" ]; then - restorecon $_i; + restorecon "$_i"; fi - done + done <<< "$(find "$_path")" }
check_fence_kdump_config()
On Thu, Aug 19, 2021 at 07:39:06PM +0800, Kairui Song wrote:
For loops over find output are fragile, use a while read loop: https://github.com/koalaman/shellcheck/wiki/SC2044
Signed-off-by: Kairui Song kasong@redhat.com
kdumpctl | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/kdumpctl b/kdumpctl index 82010fd7..548054bd 100755 --- a/kdumpctl +++ b/kdumpctl @@ -944,12 +944,12 @@ selinux_relabel() return fi
- for _i in $(find $_path); do
_attr=$(getfattr -m "security.selinux" $_i 2>/dev/null)
- while read -r _i; do
if [ -z "$_attr" ]; then_attr=$(getfattr -m "security.selinux" "$_i" 2>/dev/null)
restorecon $_i;
firestorecon "$_i";
- done
- done <<< "$(find "$_path")"
}
I notice your solution is different from what's given in SC2044. Out of curiosity, I find your solution couldn't address the case where there is line break in the filename. Btw, I create line break in the filename by typing "Alt+Enter" in zsh.
check_fence_kdump_config()
2.31.1 _______________________________________________ kexec mailing list -- kexec@lists.fedoraproject.org To unsubscribe send an email to kexec-leave@lists.fedoraproject.org Fedora Code of Conduct: https://docs.fedoraproject.org/en-US/project/code-of-conduct/ List Guidelines: https://fedoraproject.org/wiki/Mailing_list_guidelines List Archives: https://lists.fedoraproject.org/archives/list/kexec@lists.fedoraproject.org Do not reply to spam on the list, report it: https://pagure.io/fedora-infrastructure
On Wed, Sep 1, 2021 at 2:56 PM Coiby Xu coxu@redhat.com wrote:
On Thu, Aug 19, 2021 at 07:39:06PM +0800, Kairui Song wrote:
For loops over find output are fragile, use a while read loop: https://github.com/koalaman/shellcheck/wiki/SC2044
Signed-off-by: Kairui Song kasong@redhat.com
kdumpctl | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/kdumpctl b/kdumpctl index 82010fd7..548054bd 100755 --- a/kdumpctl +++ b/kdumpctl @@ -944,12 +944,12 @@ selinux_relabel() return fi
for _i in $(find $_path); do
_attr=$(getfattr -m "security.selinux" $_i 2>/dev/null)
while read -r _i; do
_attr=$(getfattr -m "security.selinux" "$_i" 2>/dev/null) if [ -z "$_attr" ]; then
restorecon $_i;
restorecon "$_i"; fi
done
done <<< "$(find "$_path")"
}
I notice your solution is different from what's given in SC2044. Out of curiosity, I find your solution couldn't address the case where there is line break in the filename. Btw, I create line break in the filename by typing "Alt+Enter" in zsh.
Thanks, I thought this way makes it looks cleaner, I'll update this part to cover this case.
check_fence_kdump_config()
2.31.1 _______________________________________________ kexec mailing list -- kexec@lists.fedoraproject.org To unsubscribe send an email to kexec-leave@lists.fedoraproject.org Fedora Code of Conduct: https://docs.fedoraproject.org/en-US/project/code-of-conduct/ List Guidelines: https://fedoraproject.org/wiki/Mailing_list_guidelines List Archives: https://lists.fedoraproject.org/archives/list/kexec@lists.fedoraproject.org Do not reply to spam on the list, report it: https://pagure.io/fedora-infrastructure
-- Best regards, Coiby
Simplify the code and cover more corner cases.
Signed-off-by: Kairui Song kasong@redhat.com --- mkdumprd | 21 ++++----------------- 1 file changed, 4 insertions(+), 17 deletions(-)
diff --git a/mkdumprd b/mkdumprd index d5545114..94f6aff8 100644 --- a/mkdumprd +++ b/mkdumprd @@ -23,7 +23,6 @@ if [ $? -ne 0 ]; then exit 1 fi
-conf_file="/etc/kdump.conf" SSH_KEY_LOCATION="/root/.ssh/kdump_id_rsa" SAVE_PATH=$(get_save_path) OVERRIDE_RESETTABLE=0 @@ -312,19 +311,6 @@ handle_default_dump_target() check_size fs $_target }
-get_override_resettable() -{ - local override_resettable - - override_resettable=$(grep "^override_resettable" $conf_file) - if [ -n "$override_resettable" ]; then - OVERRIDE_RESETTABLE=$(echo $override_resettable | cut -d' ' -f2) - if [ "$OVERRIDE_RESETTABLE" != "0" ] && [ "$OVERRIDE_RESETTABLE" != "1" ];then - perror_exit "override_resettable value $OVERRIDE_RESETTABLE is invalid" - fi - fi -} - # $1: function name for_each_block_target() { @@ -363,9 +349,10 @@ is_unresettable() #return true if resettable check_resettable() { - local _ret _target + local _ret _target _override_resettable
- get_override_resettable + _override_resettable=$(kdump_get_conf_val override_resettable) + OVERRIDE_RESETTABLE=${_override_resettable:-$OVERRIDE_RESETTABLE}
for_each_block_target is_unresettable _ret=$? @@ -395,7 +382,7 @@ if ! check_crypt; then fi
# firstly get right SSH_KEY_LOCATION -keyfile=$(awk '/^sshkey/ {print $2}' $conf_file) +keyfile=$(kdump_get_conf_val sshkey) if [ -f "$keyfile" ]; then # canonicalize the path SSH_KEY_LOCATION=$(/usr/bin/readlink -m $keyfile)
To make arguments list work as expected, array is preferred.
Use xargs only to parse the "dracut_args" config value, and pass the array directly to dracut.
Check following link for details: https://github.com/koalaman/shellcheck/wiki/SC2089
Signed-off-by: Kairui Song kasong@redhat.com --- mkdumprd | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-)
diff --git a/mkdumprd b/mkdumprd index 94f6aff8..cf273d8a 100644 --- a/mkdumprd +++ b/mkdumprd @@ -28,7 +28,7 @@ SAVE_PATH=$(get_save_path) OVERRIDE_RESETTABLE=0
extra_modules="" -dracut_args="--add kdumpbase --quiet --hostonly --hostonly-cmdline --hostonly-i18n --hostonly-mode strict -o "plymouth dash resume ifcfg earlykdump"" +dracut_args=( --add kdumpbase --quiet --hostonly --hostonly-cmdline --hostonly-i18n --hostonly-mode strict -o "plymouth dash resume ifcfg earlykdump" )
readonly MKDUMPRD_TMPDIR="$(mktemp -d -t mkdumprd.XXXXXX)" [ -d "$MKDUMPRD_TMPDIR" ] || perror_exit "dracut: mktemp -p -d -t dracut.XXXXXX failed." @@ -45,15 +45,15 @@ trap ' trap 'exit 1;' SIGINT
add_dracut_arg() { - dracut_args="$dracut_args $@" + dracut_args+=( "$@" ) }
add_dracut_mount() { - add_dracut_arg "--mount" ""$1"" + add_dracut_arg "--mount" "$1" }
add_dracut_sshkey() { - add_dracut_arg "--sshkey" ""$1"" + add_dracut_arg "--sshkey" "$1" }
# caller should ensure $1 is valid and mounted in 1st kernel @@ -425,7 +425,9 @@ do verify_core_collector "$config_val" ;; dracut_args) - add_dracut_arg $config_val + while read -r dracut_arg; do + add_dracut_arg "$dracut_arg" + done <<< "$(echo "$config_val" | xargs -n 1 echo)" ;; *) ;; @@ -436,7 +438,7 @@ handle_default_dump_target
if [ -n "$extra_modules" ] then - add_dracut_arg "--add-drivers" "$extra_modules" + add_dracut_arg "--add-drivers" "$extra_modules" fi
# TODO: The below check is not needed anymore with the introduction of @@ -452,7 +454,7 @@ if ! is_fadump_capable; then add_dracut_arg "--no-hostonly-default-device" fi
-echo "$dracut_args $@" | xargs dracut +dracut "${dracut_args[@]}" "$@"
_rc=$? sync
Signed-off-by: Kairui Song kasong@redhat.com --- mkdumprd | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-)
diff --git a/mkdumprd b/mkdumprd index cf273d8a..4707fd9b 100644 --- a/mkdumprd +++ b/mkdumprd @@ -94,7 +94,7 @@ to_mount() { #$1=dump target #called from while loop and shouldn't read from stdin, so we're using "ssh -n" get_ssh_size() { - local _opt _out _size + local _opt _out _opt="-i $SSH_KEY_LOCATION -o BatchMode=yes -o StrictHostKeyChecking=yes" _out=$(ssh -q -n $_opt $1 "df -P $SAVE_PATH") [ $? -ne 0 ] && { @@ -102,8 +102,7 @@ get_ssh_size() { }
#ssh output removed the line break, so print field NF-2 - _size=$(echo -n $_out| awk '{avail=NF-2; print $avail}') - echo -n $_size + echo -n "$_out" | awk '{avail=NF-2; print $avail}' }
#mkdir if save path does not exist on ssh dump target @@ -134,14 +133,13 @@ mkdir_save_path_ssh() #Function: get_fs_size #$1=dump target get_fs_size() { - local _mnt=$(get_mntpoint_from_target $1) - echo -n $(df -P "${_mnt}/$SAVE_PATH"|tail -1|awk '{print $4}') + df -P "$(get_mntpoint_from_target "$1")/$SAVE_PATH"|tail -1|awk '{print $4}' }
#Function: get_raw_size #$1=dump target get_raw_size() { - echo -n $(fdisk -s "$1") + fdisk -s "$1" }
#Function: check_size
Currently get_ssh_size is not working as expected, it should return the target's available space, but it will include df's header row string as the result. Fix this issue by only use the last output line.
Signed-off-by: Kairui Song kasong@redhat.com --- mkdumprd | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-)
diff --git a/mkdumprd b/mkdumprd index 4707fd9b..de4e9944 100644 --- a/mkdumprd +++ b/mkdumprd @@ -94,15 +94,14 @@ to_mount() { #$1=dump target #called from while loop and shouldn't read from stdin, so we're using "ssh -n" get_ssh_size() { - local _opt _out - _opt="-i $SSH_KEY_LOCATION -o BatchMode=yes -o StrictHostKeyChecking=yes" - _out=$(ssh -q -n $_opt $1 "df -P $SAVE_PATH") - [ $? -ne 0 ] && { + local _out + + if ! _out=$(ssh -q -n -i "$SSH_KEY_LOCATION" -o BatchMode=yes -o StrictHostKeyChecking=yes "$1" "df -P $SAVE_PATH"); then perror_exit "checking remote ssh server available size failed." - } + fi
#ssh output removed the line break, so print field NF-2 - echo -n "$_out" | awk '{avail=NF-2; print $avail}' + echo -n "$_out" | tail -1 | awk '{avail=NF-2; print $avail}' }
#mkdir if save path does not exist on ssh dump target
Hi Kairui,
On Thu, 19 Aug 2021 19:39:10 +0800 Kairui Song kasong@redhat.com wrote:
Currently get_ssh_size is not working as expected, it should return the target's available space, but it will include df's header row string as the result. Fix this issue by only use the last output line.
Signed-off-by: Kairui Song kasong@redhat.com
mkdumprd | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-)
diff --git a/mkdumprd b/mkdumprd index 4707fd9b..de4e9944 100644 --- a/mkdumprd +++ b/mkdumprd @@ -94,15 +94,14 @@ to_mount() { #$1=dump target #called from while loop and shouldn't read from stdin, so we're using "ssh -n" get_ssh_size() {
- local _opt _out
- _opt="-i $SSH_KEY_LOCATION -o BatchMode=yes -o StrictHostKeyChecking=yes"
- _out=$(ssh -q -n $_opt $1 "df -P $SAVE_PATH")
- [ $? -ne 0 ] && {
- local _out
- if ! _out=$(ssh -q -n -i "$SSH_KEY_LOCATION" -o BatchMode=yes -o StrictHostKeyChecking=yes "$1" "df -P $SAVE_PATH"); then
I would prefer to keep _opt. Without it the line is extremely long and hard to read.
perror_exit "checking remote ssh server available size failed."
- }
fi
#ssh output removed the line break, so print field NF-2
- echo -n "$_out" | awk '{avail=NF-2; print $avail}'
- echo -n "$_out" | tail -1 | awk '{avail=NF-2; print $avail}'
you could also get rid off the pipe to awk with df --output=avail instead of -P. Unfortunately this still prints the header...
Same for get_fs_size
Thanks Philipp
}
#mkdir if save path does not exist on ssh dump target
On Fri, Sep 3, 2021 at 8:17 PM Philipp Rudo prudo@redhat.com wrote:
Hi Kairui,
On Thu, 19 Aug 2021 19:39:10 +0800 Kairui Song kasong@redhat.com wrote:
Currently get_ssh_size is not working as expected, it should return the target's available space, but it will include df's header row string as the result. Fix this issue by only use the last output line.
Signed-off-by: Kairui Song kasong@redhat.com
mkdumprd | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-)
diff --git a/mkdumprd b/mkdumprd index 4707fd9b..de4e9944 100644 --- a/mkdumprd +++ b/mkdumprd @@ -94,15 +94,14 @@ to_mount() { #$1=dump target #called from while loop and shouldn't read from stdin, so we're using "ssh -n" get_ssh_size() {
- local _opt _out
- _opt="-i $SSH_KEY_LOCATION -o BatchMode=yes -o StrictHostKeyChecking=yes"
- _out=$(ssh -q -n $_opt $1 "df -P $SAVE_PATH")
- [ $? -ne 0 ] && {
- local _out
- if ! _out=$(ssh -q -n -i "$SSH_KEY_LOCATION" -o BatchMode=yes -o StrictHostKeyChecking=yes "$1" "df -P $SAVE_PATH"); then
I would prefer to keep _opt. Without it the line is extremely long and hard to read.
OK, I'll make it an array then.
perror_exit "checking remote ssh server available size failed."
- }
fi
#ssh output removed the line break, so print field NF-2
- echo -n "$_out" | awk '{avail=NF-2; print $avail}'
- echo -n "$_out" | tail -1 | awk '{avail=NF-2; print $avail}'
you could also get rid off the pipe to awk with df --output=avail instead of -P. Unfortunately this still prints the header...
Same for get_fs_size
Good suggestion.
Thanks Philipp
}
#mkdir if save path does not exist on ssh dump target
-- Best Regards, Kairui Song
Hi Kairui,
On Mon, 13 Sep 2021 04:28:00 +0800 Kairui Song kasong@redhat.com wrote:
On Fri, Sep 3, 2021 at 8:17 PM Philipp Rudo prudo@redhat.com wrote:
Hi Kairui,
On Thu, 19 Aug 2021 19:39:10 +0800 Kairui Song kasong@redhat.com wrote:
Currently get_ssh_size is not working as expected, it should return the target's available space, but it will include df's header row string as the result. Fix this issue by only use the last output line.
Signed-off-by: Kairui Song kasong@redhat.com
mkdumprd | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-)
diff --git a/mkdumprd b/mkdumprd index 4707fd9b..de4e9944 100644 --- a/mkdumprd +++ b/mkdumprd @@ -94,15 +94,14 @@ to_mount() { #$1=dump target #called from while loop and shouldn't read from stdin, so we're using "ssh -n" get_ssh_size() {
- local _opt _out
- _opt="-i $SSH_KEY_LOCATION -o BatchMode=yes -o StrictHostKeyChecking=yes"
- _out=$(ssh -q -n $_opt $1 "df -P $SAVE_PATH")
- [ $? -ne 0 ] && {
- local _out
- if ! _out=$(ssh -q -n -i "$SSH_KEY_LOCATION" -o BatchMode=yes -o StrictHostKeyChecking=yes "$1" "df -P $SAVE_PATH"); then
I would prefer to keep _opt. Without it the line is extremely long and hard to read.
OK, I'll make it an array then.
Thanks
perror_exit "checking remote ssh server available size failed."
- }
fi
#ssh output removed the line break, so print field NF-2
- echo -n "$_out" | awk '{avail=NF-2; print $avail}'
- echo -n "$_out" | tail -1 | awk '{avail=NF-2; print $avail}'
you could also get rid off the pipe to awk with df --output=avail instead of -P. Unfortunately this still prints the header...
Same for get_fs_size
Good suggestion.
NP
Thanks Philipp
For storing arguments, plain string is not a good choice. Array is preferred:
See: https://github.com/koalaman/shellcheck/wiki/SC2086
Signed-off-by: Kairui Song kasong@redhat.com --- mkdumprd | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/mkdumprd b/mkdumprd index de4e9944..2b0ccca4 100644 --- a/mkdumprd +++ b/mkdumprd @@ -111,20 +111,20 @@ get_ssh_size() { mkdir_save_path_ssh() { local _opt _dir - _opt="-i $SSH_KEY_LOCATION -o BatchMode=yes -o StrictHostKeyChecking=yes" - ssh -qn $_opt $1 mkdir -p $SAVE_PATH 2>&1 > /dev/null + _opt=(-i "$SSH_KEY_LOCATION" -o BatchMode=yes -o StrictHostKeyChecking=yes) + ssh -qn "${_opt[@]}" $1 mkdir -p $SAVE_PATH 2>&1 > /dev/null _ret=$? if [ $_ret -ne 0 ]; then perror_exit "mkdir failed on $1:$SAVE_PATH" fi
#check whether user has write permission on $1:$SAVE_PATH - _dir=$(ssh -qn $_opt $1 mktemp -dqp $SAVE_PATH 2>/dev/null) + _dir=$(ssh -qn "${_opt[@]}" $1 mktemp -dqp $SAVE_PATH 2>/dev/null) _ret=$? if [ $_ret -ne 0 ]; then perror_exit "Could not create temporary directory on $1:$SAVE_PATH. Make sure user has write permission on destination" fi - ssh -qn $_opt $1 rmdir $_dir + ssh -qn "${_opt[@]}" $1 rmdir $_dir
return 0 }
Hi Kairui,
On Thu, 19 Aug 2021 19:39:11 +0800 Kairui Song kasong@redhat.com wrote:
For storing arguments, plain string is not a good choice. Array is preferred:
^^^^^^ SC2089 like in patch 9?
Thanks Philipp
Signed-off-by: Kairui Song kasong@redhat.com
mkdumprd | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/mkdumprd b/mkdumprd index de4e9944..2b0ccca4 100644 --- a/mkdumprd +++ b/mkdumprd @@ -111,20 +111,20 @@ get_ssh_size() { mkdir_save_path_ssh() { local _opt _dir
- _opt="-i $SSH_KEY_LOCATION -o BatchMode=yes -o StrictHostKeyChecking=yes"
- ssh -qn $_opt $1 mkdir -p $SAVE_PATH 2>&1 > /dev/null
_opt=(-i "$SSH_KEY_LOCATION" -o BatchMode=yes -o StrictHostKeyChecking=yes)
ssh -qn "${_opt[@]}" $1 mkdir -p $SAVE_PATH 2>&1 > /dev/null _ret=$? if [ $_ret -ne 0 ]; then perror_exit "mkdir failed on $1:$SAVE_PATH" fi
#check whether user has write permission on $1:$SAVE_PATH
- _dir=$(ssh -qn $_opt $1 mktemp -dqp $SAVE_PATH 2>/dev/null)
- _dir=$(ssh -qn "${_opt[@]}" $1 mktemp -dqp $SAVE_PATH 2>/dev/null) _ret=$? if [ $_ret -ne 0 ]; then perror_exit "Could not create temporary directory on $1:$SAVE_PATH. Make sure user has write permission on destination" fi
- ssh -qn $_opt $1 rmdir $_dir
ssh -qn "${_opt[@]}" $1 rmdir $_dir
return 0
}
To make arguments list work as expected, array is preferred.
Check following link for details: https://github.com/koalaman/shellcheck/wiki/SC2089
Signed-off-by: Kairui Song kasong@redhat.com --- mkfadumprd | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-)
diff --git a/mkfadumprd b/mkfadumprd index aecf2a86..5c879338 100644 --- a/mkfadumprd +++ b/mkfadumprd @@ -51,14 +51,17 @@ if ! (pushd "$MKFADUMPRD_TMPDIR/fadumproot" > /dev/null && lsinitrd --unpack "$F fi
### Pack it into the normal boot initramfs with zz-fadumpinit module -_dracut_isolate_args="--rebuild $REBUILD_INITRD --add zz-fadumpinit \ - -i $MKFADUMPRD_TMPDIR/fadumproot /fadumproot \ - -i $MKFADUMPRD_TMPDIR/fadumproot/usr/lib/dracut/hostonly-kernel-modules.txt - /usr/lib/dracut/fadump-kernel-modules.txt" +_dracut_isolate_args=(\ + --rebuild "$REBUILD_INITRD" --add zz-fadumpinit \ + -i "$MKFADUMPRD_TMPDIR/fadumproot" /fadumproot + -i "$MKFADUMPRD_TMPDIR/fadumproot/usr/lib/dracut/hostonly-kernel-modules.txt" + /usr/lib/dracut/fadump-kernel-modules.txt +)
if is_squash_available; then - _dracut_isolate_args="$_dracut_isolate_args --add squash" + _dracut_isolate_args+=( --add squash ) fi -if ! dracut --force --quiet $_dracut_isolate_args $@ "$TARGET_INITRD"; then + +if ! dracut --force --quiet "${_dracut_isolate_args[@]}" "$@" "$TARGET_INITRD"; then perror_exit "mkfadumprd: failed to setup '$TARGET_INITRD' with dump capture capability" fi
Avoid duplicated echo / cut / grep call, just use sed.
Signed-off-by: Kairui Song kasong@redhat.com --- dracut-module-setup.sh | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-)
diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index 53abdc75..5ccf2db5 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -523,9 +523,7 @@ kdump_get_ip_route()
kdump_get_ip_route_field() { - if `echo $1 | grep -q $2`; then - echo ${1##*$2} | cut -d ' ' -f1 - fi + echo "$1" | sed -n -e "s/(^|^.*\s+)<$2>\s+(\S+).*$/\2/p" }
kdump_get_remote_ip()
Hi Kairui,
On Thu, 19 Aug 2021 19:39:13 +0800 Kairui Song kasong@redhat.com wrote:
Avoid duplicated echo / cut / grep call, just use sed.
Signed-off-by: Kairui Song kasong@redhat.com
dracut-module-setup.sh | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-)
diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index 53abdc75..5ccf2db5 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -523,9 +523,7 @@ kdump_get_ip_route()
kdump_get_ip_route_field() {
- if `echo $1 | grep -q $2`; then
echo ${1##*$2} | cut -d ' ' -f1
- fi
- echo "$1" | sed -n -e "s/(^|^.*\s+)<$2>\s+(\S+).*$/\2/p"
^^^^^^^^^^^^^^ I think you can abbreviate this to '^.*' < indicates the beginning of a word which means that the character before $2 must not be any word character (i.e. alphanumeric or underscore '_').
Thanks Philipp
}
kdump_get_remote_ip()
On Fri, Sep 3, 2021 at 8:22 PM Philipp Rudo prudo@redhat.com wrote:
Hi Kairui,
On Thu, 19 Aug 2021 19:39:13 +0800 Kairui Song kasong@redhat.com wrote:
Avoid duplicated echo / cut / grep call, just use sed.
Signed-off-by: Kairui Song kasong@redhat.com
dracut-module-setup.sh | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-)
diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index 53abdc75..5ccf2db5 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -523,9 +523,7 @@ kdump_get_ip_route()
kdump_get_ip_route_field() {
- if `echo $1 | grep -q $2`; then
echo ${1##*$2} | cut -d ' ' -f1
- fi
- echo "$1" | sed -n -e "s/(^|^.*\s+)<$2>\s+(\S+).*$/\2/p"
^^^^^^^^^^^^^^ I think you can abbreviate this to '^.*' \< indicates the beginning of a word which means that the character before $2 must not be any word character (i.e. alphanumeric or underscore '_').
Thanks Philipp
Got it, thanks!
-- Best Regards, Kairui Song
Signed-off-by: Kairui Song kasong@redhat.com --- dracut-module-setup.sh | 2 -- 1 file changed, 2 deletions(-)
diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index 5ccf2db5..2b8a0715 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -997,8 +997,6 @@ kdump_install_random_seed() { }
kdump_install_systemd_conf() { - local failure_action=$(kdump_get_conf_val "failure_action") - # Kdump turns out to require longer default systemd mount timeout # than 1st kernel(90s by default), we use default 300s for kdump. grep -r "^[[:space:]]*DefaultTimeoutStartSec=" ${initdir}/etc/systemd/system.conf* &>/dev/null
--- dracut-module-setup.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index 2b8a0715..8334a252 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -391,13 +391,13 @@ kdump_setup_bond() {
_bondoptions=$(get_nmcli_value_by_field "$_nm_show_cmd" "bond.options")
- if [[ -z "_bondoptions" ]]; then + if [[ -z "$_bondoptions" ]]; then dwarning "Failed to get bond configuration via nmlci output. Now try sourcing ifcfg script." source_ifcfg_file $_netdev _bondoptions="$(echo $BONDING_OPTS | xargs echo | tr " " ",")" fi
- if [[ -z "_bondoptions" ]]; then + if [[ -z "$_bondoptions" ]]; then derror "Get empty bond options" exit 1 fi
As suggested by: https://github.com/koalaman/shellcheck/wiki/SC2199 The array is not quoted here but implicitly concatenate still happens, could be harmless but shellcheck complains about it so fix it.
Signed-off-by: Kairui Song kasong@redhat.com --- dracut-module-setup.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index 8334a252..7a1ff41d 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -94,7 +94,7 @@ kdump_setup_dns() {
_tmp=$(get_nmcli_value_by_field "$_nm_show_cmd" "IP4.DNS") array=(${_tmp//|/ }) - if [[ ${array[@]} ]]; then + if [[ ${array[*]} ]]; then for _dns in "${array[@]}" do echo "nameserver=$_dns" >> "$_dnsfile"
Wrap the variable with {...}, else it may get interpreted as array due to the '[' char next to it.
Signed-off-by: Kairui Song kasong@redhat.com --- dracut-module-setup.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index 7a1ff41d..c681413c 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -689,11 +689,11 @@ kdump_install_conf() { case "$_opt" in raw) _pdev=$(persistent_policy="by-id" kdump_get_persistent_dev $_val) - sed -i -e "s#^$_opt[[:space:]]+$_val#$_opt $_pdev#" ${initdir}/tmp/$$-kdump.conf + sed -i -e "s#^${_opt}[[:space:]]+$_val#$_opt $_pdev#" ${initdir}/tmp/$$-kdump.conf ;; ext[234]|xfs|btrfs|minix) _pdev=$(kdump_get_persistent_dev $_val) - sed -i -e "s#^$_opt[[:space:]]+$_val#$_opt $_pdev#" ${initdir}/tmp/$$-kdump.conf + sed -i -e "s#^${_opt}[[:space:]]+$_val#$_opt $_pdev#" ${initdir}/tmp/$$-kdump.conf ;; ssh|nfs) kdump_install_net "$_val"
Iterating over ls output is fragile: https://github.com/koalaman/shellcheck/wiki/SC2045
Signed-off-by: Kairui Song kasong@redhat.com --- dracut-module-setup.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index c681413c..ef3c809d 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -353,7 +353,8 @@ kdump_setup_ifname() { kdump_setup_bridge() { local _netdev=$1 local _brif _dev _mac _kdumpdev - for _dev in `ls /sys/class/net/$_netdev/brif/`; do + for _dev in "/sys/class/net/$_netdev/brif/"*; do + [[ -e $_dev ]] || continue _kdumpdev=$_dev if kdump_is_bond "$_dev"; then $(kdump_setup_bond "$_dev" "$(get_nmcli_connection_show_cmd_by_ifname "$_dev")")
On Thu, Aug 19, 2021 at 07:39:18PM +0800, Kairui Song wrote:
Iterating over ls output is fragile: https://github.com/koalaman/shellcheck/wiki/SC2045
Signed-off-by: Kairui Song kasong@redhat.com
dracut-module-setup.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index c681413c..ef3c809d 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -353,7 +353,8 @@ kdump_setup_ifname() { kdump_setup_bridge() { local _netdev=$1 local _brif _dev _mac _kdumpdev
- for _dev in `ls /sys/class/net/$_netdev/brif/`; do
- for _dev in "/sys/class/net/$_netdev/brif/"*; do
[[ -e $_dev ]] || continue
This fix brings a regression. $_dev is supposed to be a network interface name. However, $_dev now becomes /sys/class/net/$_netdev/brif/{interface_name}
which would lead to the failure of setting up bridge network.
_kdumpdev=$_dev if kdump_is_bond "$_dev"; then $(kdump_setup_bond "$_dev" "$(get_nmcli_connection_show_cmd_by_ifname "$_dev")")
-- 2.31.1 _______________________________________________ kexec mailing list -- kexec@lists.fedoraproject.org To unsubscribe send an email to kexec-leave@lists.fedoraproject.org Fedora Code of Conduct: https://docs.fedoraproject.org/en-US/project/code-of-conduct/ List Guidelines: https://fedoraproject.org/wiki/Mailing_list_guidelines List Archives: https://lists.fedoraproject.org/archives/list/kexec@lists.fedoraproject.org Do not reply to spam on the list, report it: https://pagure.io/fedora-infrastructure
On Mon, Sep 6, 2021 at 3:10 PM Coiby Xu coxu@redhat.com wrote:
On Thu, Aug 19, 2021 at 07:39:18PM +0800, Kairui Song wrote:
Iterating over ls output is fragile: https://github.com/koalaman/shellcheck/wiki/SC2045
Signed-off-by: Kairui Song kasong@redhat.com
dracut-module-setup.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index c681413c..ef3c809d 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -353,7 +353,8 @@ kdump_setup_ifname() { kdump_setup_bridge() { local _netdev=$1 local _brif _dev _mac _kdumpdev
- for _dev in `ls /sys/class/net/$_netdev/brif/`; do
- for _dev in "/sys/class/net/$_netdev/brif/"*; do
[[ -e $_dev ]] || continue
This fix brings a regression. $_dev is supposed to be a network interface name. However, $_dev now becomes /sys/class/net/$_netdev/brif/{interface_name}
which would lead to the failure of setting up bridge network.
Thanks, I'll fix it.
_kdumpdev=$_dev if kdump_is_bond "$_dev"; then $(kdump_setup_bond "$_dev" "$(get_nmcli_connection_show_cmd_by_ifname "$_dev")")
-- 2.31.1 _______________________________________________ kexec mailing list -- kexec@lists.fedoraproject.org To unsubscribe send an email to kexec-leave@lists.fedoraproject.org Fedora Code of Conduct: https://docs.fedoraproject.org/en-US/project/code-of-conduct/ List Guidelines: https://fedoraproject.org/wiki/Mailing_list_guidelines List Archives: https://lists.fedoraproject.org/archives/list/kexec@lists.fedoraproject.org Do not reply to spam on the list, report it: https://pagure.io/fedora-infrastructure
-- Best regards, Coiby
-- Best Regards, Kairui Song
As suggested by: https://github.com/koalaman/shellcheck/wiki/SC2164
Signed-off-by: Kairui Song kasong@redhat.com --- dracut-module-setup.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index ef3c809d..3353fe26 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -854,7 +854,7 @@ kdump_check_iscsi_targets () { _dev=$1
[[ -L /sys/dev/block/$_dev ]] || return - cd "$(readlink -f /sys/dev/block/$_dev)" + cd "$(readlink -f "/sys/dev/block/$_dev")" || return 1 until [[ -d sys || -d iscsi_session ]]; do cd .. done
Some `cat` calls are useless, remove them to make it cleaner. See: https://github.com/koalaman/shellcheck/wiki/SC2002
Signed-off-by: Kairui Song kasong@redhat.com --- dracut-module-setup.sh | 6 ++++-- kdumpctl | 22 ++++++++++++---------- mkdumprd | 2 +- 3 files changed, 17 insertions(+), 13 deletions(-)
diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index 3353fe26..bf02164c 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -114,7 +114,7 @@ kdump_setup_dns() { _dns=$(echo $_nameserver | cut -d' ' -f2) [ -z "$_dns" ] && continue
- if [ ! -f $_dnsfile ] || [ ! $(cat $_dnsfile | grep -q $_dns) ]; then + if [ ! -f $_dnsfile ] || ! grep -q "$_dns" "$_dnsfile" ; then echo "nameserver=$_dns" >> "$_dnsfile" fi done < "/etc/resolv.conf" @@ -987,7 +987,9 @@ kdump_configure_fence_kdump () { # Install a random seed used to feed /dev/urandom # By the time kdump service starts, /dev/uramdom is already fed by systemd kdump_install_random_seed() { - local poolsize=`cat /proc/sys/kernel/random/poolsize` + local poolsize + + poolsize=$(</proc/sys/kernel/random/poolsize)
if [ ! -d ${initdir}/var/lib/ ]; then mkdir -p ${initdir}/var/lib/ diff --git a/kdumpctl b/kdumpctl index 548054bd..dbac53c3 100755 --- a/kdumpctl +++ b/kdumpctl @@ -204,8 +204,8 @@ restore_default_initrd() # fadump to kdump. Restore the original default initrd. if [ -f $DEFAULT_INITRD_BAK ] && [ -f $INITRD_CHECKSUM_LOCATION ]; then # verify checksum before restoring - backup_checksum=`sha1sum $DEFAULT_INITRD_BAK | awk '{ print $1 }'` - default_checksum=`cat $INITRD_CHECKSUM_LOCATION | awk '{ print $1 }'` + backup_checksum=$(sha1sum "$DEFAULT_INITRD_BAK" | awk '{ print $1 }') + default_checksum=$(awk '{ print $1 }' "$INITRD_CHECKSUM_LOCATION") if [ "$default_checksum" != "$backup_checksum" ]; then dwarn "WARNING: checksum mismatch! Can't restore original initrd.." else @@ -638,8 +638,7 @@ function load_kdump_kernel_key() return fi
- KDUMP_KEY_ID=$(cat /usr/share/doc/kernel-keys/$KDUMP_KERNELVER/kernel-signing-ppc.cer | - keyctl padd asymmetric kernelkey-$RANDOM %:.ima) + KDUMP_KEY_ID=$(keyctl padd asymmetric kernelkey-$RANDOM %:.ima < "/usr/share/doc/kernel-keys/$KDUMP_KERNELVER/kernel-signing-ppc.cer") }
# remove a previously loaded key. There's no real security implication @@ -832,8 +831,11 @@ propagate_ssh_key()
show_reserved_mem() { - local mem=$(cat /sys/kernel/kexec_crash_size) - local mem_mb=$(expr $mem / 1024 / 1024) + local mem + local mem_mb + + mem=$(</sys/kernel/kexec_crash_size) + mem_mb=$(expr "$mem" / 1024 / 1024)
dinfo "Reserved "$mem_mb"MB memory for crash kernel" } @@ -841,8 +843,8 @@ show_reserved_mem() check_current_fadump_status() { # Check if firmware-assisted dump has been registered. - rc=`cat $FADUMP_REGISTER_SYS_NODE` - [ $rc -eq 1 ] && return 0 + rc=$(<$FADUMP_REGISTER_SYS_NODE) + [[ $rc -eq 1 ]] && return 0 return 1 }
@@ -1259,7 +1261,7 @@ do_estimate() { # The default pre-reserved crashkernel value baseline_size=$((baseline * size_mb)) # Current reserved crashkernel size - reserved_size=$(cat /sys/kernel/kexec_crash_size) + reserved_size=$(</sys/kernel/kexec_crash_size) # A pre-estimated value for userspace usage and kernel # runtime allocation, 64M should good for most cases runtime_size=$((64 * size_mb)) @@ -1329,7 +1331,7 @@ reset_crashkernel() { local grub_etc_default="/etc/default/grub"
[[ -z "$kernel" ]] && kernel=$(uname -r) - crashkernel_default=$(cat "/usr/lib/modules/$kernel/crashkernel.default" 2>/dev/null) + crashkernel_default=$(<"/usr/lib/modules/$kernel/crashkernel.default") &>/dev/null
if [[ -z "$crashkernel_default" ]]; then derror "$kernel doesn't have a crashkernel.default" diff --git a/mkdumprd b/mkdumprd index 2b0ccca4..64091cd8 100644 --- a/mkdumprd +++ b/mkdumprd @@ -331,7 +331,7 @@ is_unresettable()
if [ -f "$path" ] then - resettable="$(cat $path)" + resettable="$(<"$path")" [ $resettable -eq 0 -a "$OVERRIDE_RESETTABLE" -eq 0 ] && { local device=$(udevadm info --query=all --path=/sys/dev/block/$1 | awk -F= '/DEVNAME/{print $2}') derror "Error: Can not save vmcore because device $device is unresettable"
As suggested by: https://github.com/koalaman/shellcheck/wiki/SC2219
Signed-off-by: Kairui Song kasong@redhat.com --- dracut-module-setup.sh | 2 +- kdumpctl | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-)
diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index bf02164c..8b9911d0 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -196,7 +196,7 @@ cal_netmask_by_prefix() { _res="$_first_part"
_tmp=$((_octets_total*_bits_per_octet-_prefix)) - _zero_bits=$(expr $_tmp % $_bits_per_group) + _zero_bits=$((_tmp % _bits_per_group)) if [[ "$_zero_bits" -ne 0 ]]; then _second_part=$((_max_group_value >> _zero_bits << _zero_bits)) if ((_ipv6)); then diff --git a/kdumpctl b/kdumpctl index dbac53c3..7602c43e 100755 --- a/kdumpctl +++ b/kdumpctl @@ -772,7 +772,7 @@ check_and_wait_network_ready() fi
cur=$(date +%s) - let "diff = $cur - $start_time" + diff=$((cur - start_time)) # 60s time out if [ $diff -gt 180 ]; then break; @@ -835,7 +835,7 @@ show_reserved_mem() local mem_mb
mem=$(</sys/kernel/kexec_crash_size) - mem_mb=$(expr "$mem" / 1024 / 1024) + mem_mb=$((mem / 1024 / 1024))
dinfo "Reserved "$mem_mb"MB memory for crash kernel" }
Use bash builtin string substitution instead, as suggested by: https://github.com/koalaman/shellcheck/wiki/SC2001
Signed-off-by: Kairui Song kasong@redhat.com --- dracut-module-setup.sh | 8 ++++---- mkdumprd | 18 ++++++++++-------- 2 files changed, 14 insertions(+), 12 deletions(-)
diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index 8b9911d0..61ab9803 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -288,7 +288,7 @@ kdump_handle_mulitpath_route() {
while IFS="" read _route; do if [[ "$_route" =~ [[:space:]]+nexthop ]]; then - _route=$(echo "$_route" | sed -e 's/^[[:space:]]*//') + _route=${_route##[[:space:]]} # Parse multipath route, using previous _target [[ "$_target" == 'default' ]] && continue [[ "$_route" =~ .*via.*\ $_netdev ]] || continue @@ -372,7 +372,7 @@ kdump_setup_bridge() { fi _brif+="$_kdumpdev," done - echo " bridge=$_netdev:$(echo $_brif | sed -e 's/,$//')" >> ${initdir}/etc/cmdline.d/41bridge.conf + echo " bridge=$_netdev:${_brif%,}" >> "${initdir}/etc/cmdline.d/41bridge.conf" }
# drauct takes bond=<bondname>[:<bondslaves>:[:<options>]] syntax to parse @@ -388,7 +388,7 @@ kdump_setup_bond() { echo -n " ifname=$_kdumpdev:$_mac" >> ${initdir}/etc/cmdline.d/42bond.conf _slaves+="$_kdumpdev," done - echo -n " bond=$_netdev:$(echo $_slaves | sed 's/,$//')" >> ${initdir}/etc/cmdline.d/42bond.conf + echo -n " bond=$_netdev:${_slaves%,}" >> "${initdir}/etc/cmdline.d/42bond.conf"
_bondoptions=$(get_nmcli_value_by_field "$_nm_show_cmd" "bond.options")
@@ -415,7 +415,7 @@ kdump_setup_team() { echo -n " ifname=$_kdumpdev:$_mac" >> ${initdir}/etc/cmdline.d/44team.conf _slaves+="$_kdumpdev," done - echo " team=$_netdev:$(echo $_slaves | sed -e 's/,$//')" >> ${initdir}/etc/cmdline.d/44team.conf + echo " team=$_netdev:${_slaves%,}" >> "${initdir}/etc/cmdline.d/44team.conf" #Buggy version teamdctl outputs to stderr! #Try to use the latest version of teamd. teamdctl "$_netdev" config dump > ${initdir}/tmp/$$-$_netdev.conf diff --git a/mkdumprd b/mkdumprd index 64091cd8..2cb82396 100644 --- a/mkdumprd +++ b/mkdumprd @@ -58,7 +58,7 @@ add_dracut_sshkey() {
# caller should ensure $1 is valid and mounted in 1st kernel to_mount() { - local _target=$1 _fstype=$2 _options=$3 _new_mntpoint _pdev + local _target=$1 _fstype=$2 _options=$3 _sed_cmd _new_mntpoint _pdev
_new_mntpoint=$(get_kdump_mntpoint_from_target $_target) _fstype="${_fstype:-$(get_fs_type_from_target $_target)}" @@ -67,9 +67,9 @@ to_mount() {
if [[ "$_fstype" == "nfs"* ]]; then _pdev=$_target - _options=$(echo $_options | sed 's/,addr=[^,]*//') - _options=$(echo $_options | sed 's/,proto=[^,]*//') - _options=$(echo $_options | sed 's/,clientaddr=[^,]*//') + _sed_cmd+='s/,addr=[^,]*//;' + _sed_cmd+='s/,proto=[^,]*//;' + _sed_cmd+='s/,clientaddr=[^,]*//;' else # for non-nfs _target converting to use udev persistent name _pdev="$(kdump_get_persistent_dev $_target)" @@ -79,13 +79,15 @@ to_mount() { fi
# mount fs target as rw in 2nd kernel - _options=$(echo $_options | sed 's/(^|,)ro($|,)/\1rw\2/g') + _sed_cmd+='s/(^|,)ro($|,)/\1rw\2/g;' # with 'noauto' in fstab nfs and non-root disk mount will fail in 2nd # kernel, filter it out here. - _options=$(echo $_options | sed 's/(^|,)noauto($|,)/\1/g') + _sed_cmd+='s/(^|,)noauto($|,)/\1/g;' # drop nofail or nobootwait - _options=$(echo $_options | sed 's/(^|,)nofail($|,)/\1/g') - _options=$(echo $_options | sed 's/(^|,)nobootwait($|,)/\1/g') + _sed_cmd+='s/(^|,)nofail($|,)/\1/g;' + _sed_cmd+='s/(^|,)nobootwait($|,)/\1/g;' + + _options=$(echo "$_options" | sed "$_sed_cmd")
echo "$_pdev $_new_mntpoint $_fstype $_options" }
Hi Kairui,
in subject s/unnessary/unnecessary/
Thanks Philipp
On Thu, 19 Aug 2021 19:39:22 +0800 Kairui Song kasong@redhat.com wrote:
Use bash builtin string substitution instead, as suggested by: https://github.com/koalaman/shellcheck/wiki/SC2001
Signed-off-by: Kairui Song kasong@redhat.com
dracut-module-setup.sh | 8 ++++---- mkdumprd | 18 ++++++++++-------- 2 files changed, 14 insertions(+), 12 deletions(-)
diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index 8b9911d0..61ab9803 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -288,7 +288,7 @@ kdump_handle_mulitpath_route() {
while IFS="" read _route; do if [[ "$_route" =~ [[:space:]]+nexthop ]]; then
_route=$(echo "$_route" | sed -e 's/^[[:space:]]*//')
_route=${_route##[[:space:]]} # Parse multipath route, using previous _target [[ "$_target" == 'default' ]] && continue [[ "$_route" =~ .*via.*\ $_netdev ]] || continue
@@ -372,7 +372,7 @@ kdump_setup_bridge() { fi _brif+="$_kdumpdev," done
- echo " bridge=$_netdev:$(echo $_brif | sed -e 's/,$//')" >> ${initdir}/etc/cmdline.d/41bridge.conf
- echo " bridge=$_netdev:${_brif%,}" >> "${initdir}/etc/cmdline.d/41bridge.conf"
}
# drauct takes bond=<bondname>[:<bondslaves>:[:<options>]] syntax to parse @@ -388,7 +388,7 @@ kdump_setup_bond() { echo -n " ifname=$_kdumpdev:$_mac" >> ${initdir}/etc/cmdline.d/42bond.conf _slaves+="$_kdumpdev," done
- echo -n " bond=$_netdev:$(echo $_slaves | sed 's/,$//')" >> ${initdir}/etc/cmdline.d/42bond.conf
echo -n " bond=$_netdev:${_slaves%,}" >> "${initdir}/etc/cmdline.d/42bond.conf"
_bondoptions=$(get_nmcli_value_by_field "$_nm_show_cmd" "bond.options")
@@ -415,7 +415,7 @@ kdump_setup_team() { echo -n " ifname=$_kdumpdev:$_mac" >> ${initdir}/etc/cmdline.d/44team.conf _slaves+="$_kdumpdev," done
- echo " team=$_netdev:$(echo $_slaves | sed -e 's/,$//')" >> ${initdir}/etc/cmdline.d/44team.conf
- echo " team=$_netdev:${_slaves%,}" >> "${initdir}/etc/cmdline.d/44team.conf" #Buggy version teamdctl outputs to stderr! #Try to use the latest version of teamd. teamdctl "$_netdev" config dump > ${initdir}/tmp/$$-$_netdev.conf
diff --git a/mkdumprd b/mkdumprd index 64091cd8..2cb82396 100644 --- a/mkdumprd +++ b/mkdumprd @@ -58,7 +58,7 @@ add_dracut_sshkey() {
# caller should ensure $1 is valid and mounted in 1st kernel to_mount() {
- local _target=$1 _fstype=$2 _options=$3 _new_mntpoint _pdev
local _target=$1 _fstype=$2 _options=$3 _sed_cmd _new_mntpoint _pdev
_new_mntpoint=$(get_kdump_mntpoint_from_target $_target) _fstype="${_fstype:-$(get_fs_type_from_target $_target)}"
@@ -67,9 +67,9 @@ to_mount() {
if [[ "$_fstype" == "nfs"* ]]; then _pdev=$_target
_options=$(echo $_options | sed 's/,addr=[^,]*//')
_options=$(echo $_options | sed 's/,proto=[^,]*//')
_options=$(echo $_options | sed 's/,clientaddr=[^,]*//')
_sed_cmd+='s/,addr=[^,]*//;'
_sed_cmd+='s/,proto=[^,]*//;'
else # for non-nfs _target converting to use udev persistent name _pdev="$(kdump_get_persistent_dev $_target)"_sed_cmd+='s/,clientaddr=[^,]*//;'
@@ -79,13 +79,15 @@ to_mount() { fi
# mount fs target as rw in 2nd kernel
- _options=$(echo $_options | sed 's/(^|,)ro($|,)/\1rw\2/g')
- _sed_cmd+='s/(^|,)ro($|,)/\1rw\2/g;' # with 'noauto' in fstab nfs and non-root disk mount will fail in 2nd # kernel, filter it out here.
- _options=$(echo $_options | sed 's/(^|,)noauto($|,)/\1/g')
- _sed_cmd+='s/(^|,)noauto($|,)/\1/g;' # drop nofail or nobootwait
- _options=$(echo $_options | sed 's/(^|,)nofail($|,)/\1/g')
- _options=$(echo $_options | sed 's/(^|,)nobootwait($|,)/\1/g')
_sed_cmd+='s/(^|,)nofail($|,)/\1/g;'
_sed_cmd+='s/(^|,)nobootwait($|,)/\1/g;'
_options=$(echo "$_options" | sed "$_sed_cmd")
echo "$_pdev $_new_mntpoint $_fstype $_options"
}
This helps to strip spaces and avoid mangling backslashes:
https://github.com/koalaman/shellcheck/wiki/SC2162
Signed-off-by: Kairui Song kasong@redhat.com --- dracut-module-setup.sh | 14 +++++++------- kdumpctl | 2 +- mkdumprd | 2 +- 3 files changed, 9 insertions(+), 9 deletions(-)
diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index 61ab9803..857b637a 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -106,7 +106,7 @@ kdump_setup_dns() { [ -n "$DNS2" ] && echo "nameserver=$DNS2" >> "$_dnsfile" fi
- while read content; + while read -r content; do _nameserver=$(echo $content | grep ^nameserver) [ -z "$_nameserver" ] && continue @@ -265,7 +265,7 @@ kdump_static_ip() {
/sbin/ip $_ipv6_flag route show | grep -v default |\ grep ".*via.* $_netdev " | grep -v "^[[:space:]]*nexthop" |\ - while read _route; do + while read -r _route; do _target=`echo $_route | cut -d ' ' -f1` _nexthop=`echo $_route | cut -d ' ' -f3` if [ "x" != "x"$_ipv6_flag ]; then @@ -286,7 +286,7 @@ kdump_handle_mulitpath_route() { _ipv6_flag="-6" fi
- while IFS="" read _route; do + while IFS="" read -r _route; do if [[ "$_route" =~ [[:space:]]+nexthop ]]; then _route=${_route##[[:space:]]} # Parse multipath route, using previous _target @@ -464,7 +464,7 @@ find_online_znet_device() { for d in $NETWORK_DEVICES do [ ! -f "$d/online" ] && continue - read ONLINE < $d/online + read -r ONLINE < $d/online if [ $ONLINE -ne 1 ]; then continue fi @@ -472,7 +472,7 @@ find_online_znet_device() { # device is online) if [ -f $d/if_name ] then - read ifname < $d/if_name + read -r ifname < $d/if_name elif [ -d $d/net ] then ifname=$(ls $d/net/) @@ -684,7 +684,7 @@ kdump_install_conf() {
kdump_read_conf > "${initdir}/tmp/$$-kdump.conf"
- while read _opt _val; + while read -r _opt _val; do # remove inline comments after the end of a directive. case "$_opt" in @@ -752,7 +752,7 @@ kdump_get_iscsi_initiator() {
[ -f "$initiator_conf" ] || return 1
- while read _initiator; do + while read -r _initiator; do [ -z "${_initiator%%#*}" ] && continue # Skip comment lines
case $_initiator in diff --git a/kdumpctl b/kdumpctl index 7602c43e..28310946 100755 --- a/kdumpctl +++ b/kdumpctl @@ -704,7 +704,7 @@ load_kdump()
check_ssh_config() { - while read config_opt config_val; do + while read -r config_opt config_val; do case "$config_opt" in sshkey) # remove inline comments after the end of a directive. diff --git a/mkdumprd b/mkdumprd index 2cb82396..af36e003 100644 --- a/mkdumprd +++ b/mkdumprd @@ -387,7 +387,7 @@ if [ -f "$keyfile" ]; then SSH_KEY_LOCATION=$(/usr/bin/readlink -m $keyfile) fi
-while read config_opt config_val; +while read -r config_opt config_val; do # remove inline comments after the end of a directive. case "$config_opt" in
This is a batch update done with following command:
`sed -i -e 's/`([^`]*)`/$(\1)/g' mkfadumprd mkdumprd \ kdumpctl dracut-module-setup.sh dracut-fadump-module-setup.sh \ dracut-early-kdump-module-setup.sh`
And manually converted some corner cases. This fixes all related issues detected by shellcheck. Make it easier to do clean up in later commits.
Check following link for reasons to switch to the new syntax: https://github.com/koalaman/shellcheck/wiki/SC2006
Signed-off-by: Kairui Song kasong@redhat.com --- dracut-module-setup.sh | 22 +++++++++++----------- kdumpctl | 31 +++++++++++++++---------------- 2 files changed, 26 insertions(+), 27 deletions(-)
diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index 857b637a..59aac91f 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -266,8 +266,8 @@ kdump_static_ip() { /sbin/ip $_ipv6_flag route show | grep -v default |\ grep ".*via.* $_netdev " | grep -v "^[[:space:]]*nexthop" |\ while read -r _route; do - _target=`echo $_route | cut -d ' ' -f1` - _nexthop=`echo $_route | cut -d ' ' -f3` + _target=$(echo $_route | cut -d ' ' -f1) + _nexthop=$(echo $_route | cut -d ' ' -f3) if [ "x" != "x"$_ipv6_flag ]; then _target="[$_target]" _nexthop="[$_nexthop]" @@ -293,9 +293,9 @@ kdump_handle_mulitpath_route() { [[ "$_target" == 'default' ]] && continue [[ "$_route" =~ .*via.*\ $_netdev ]] || continue
- _weight=`echo "$_route" | cut -d ' ' -f7` + _weight=$(echo "$_route" | cut -d ' ' -f7) if [[ "$_weight" -gt "$_max_weight" ]]; then - _nexthop=`echo "$_route" | cut -d ' ' -f3` + _nexthop=$(echo "$_route" | cut -d ' ' -f3) _max_weight=$_weight if [ "x" != "x"$_ipv6_flag ]; then _rule="rd.route=[$_target]:[$_nexthop]:$kdumpnic" @@ -305,7 +305,7 @@ kdump_handle_mulitpath_route() { fi else [[ -n "$_rule" ]] && echo "$_rule" - _target=`echo "$_route" | cut -d ' ' -f1` + _target=$(echo "$_route" | cut -d ' ' -f1) _rule="" _max_weight=0 _weight=0 fi done >> ${initdir}/etc/cmdline.d/45route-static.conf\ @@ -382,7 +382,7 @@ kdump_setup_bond() { local _netdev="$1" local _nm_show_cmd="$2" local _dev _mac _slaves _kdumpdev _bondoptions - for _dev in `cat /sys/class/net/$_netdev/bonding/slaves`; do + for _dev in $(cat /sys/class/net/$_netdev/bonding/slaves); do _mac=$(kdump_get_perm_addr $_dev) _kdumpdev=$(kdump_setup_ifname $_dev) echo -n " ifname=$_kdumpdev:$_mac" >> ${initdir}/etc/cmdline.d/42bond.conf @@ -409,7 +409,7 @@ kdump_setup_bond() { kdump_setup_team() { local _netdev=$1 local _dev _mac _slaves _kdumpdev - for _dev in `teamnl $_netdev ports | awk -F':' '{print $2}'`; do + for _dev in $(teamnl $_netdev ports | awk -F':' '{print $2}'); do _mac=$(kdump_get_perm_addr $_dev) _kdumpdev=$(kdump_setup_ifname $_dev) echo -n " ifname=$_kdumpdev:$_mac" >> ${initdir}/etc/cmdline.d/44team.conf @@ -531,11 +531,11 @@ kdump_get_remote_ip() { local _remote=$(get_remote_host $1) _remote_temp if is_hostname $_remote; then - _remote_temp=`getent ahosts $_remote | grep -v : | head -n 1` + _remote_temp=$(getent ahosts $_remote | grep -v : | head -n 1) if [ -z "$_remote_temp" ]; then - _remote_temp=`getent ahosts $_remote | head -n 1` + _remote_temp=$(getent ahosts $_remote | head -n 1) fi - _remote=`echo $_remote_temp | cut -d' ' -f1` + _remote=$(echo $_remote_temp | cut -d' ' -f1) fi echo $_remote } @@ -907,7 +907,7 @@ get_pcs_fence_kdump_nodes() {
pcs cluster sync > /dev/null 2>&1 && pcs cluster cib-upgrade > /dev/null 2>&1 # get cluster nodes from cluster cib, get interface and ip address - nodelist=`pcs cluster cib | xmllint --xpath "/cib/status/node_state/@uname" -` + nodelist=$(pcs cluster cib | xmllint --xpath "/cib/status/node_state/@uname" -)
# nodelist is formed as 'uname="node1" uname="node2" ... uname="nodeX"' # we need to convert each to node1, node2 ... nodeX in each iteration diff --git a/kdumpctl b/kdumpctl index 28310946..910b7175 100755 --- a/kdumpctl +++ b/kdumpctl @@ -76,7 +76,7 @@ determine_dump_mode()
save_core() { - coredir="/var/crash/`date +"%Y-%m-%d-%H:%M"`" + coredir="/var/crash/$(date +"%Y-%m-%d-%H:%M")"
mkdir -p $coredir ddebug "cp --sparse=always /proc/vmcore $coredir/vmcore-incomplete" @@ -290,15 +290,14 @@ get_pcs_cluster_modified_files() is_generic_fence_kdump && return 1 is_pcs_fence_kdump || return 1
- time_stamp=`pcs cluster cib | xmllint --xpath 'string(/cib/@cib-last-written)' - | \ - xargs -0 date +%s --date` + time_stamp=$(pcs cluster cib | xmllint --xpath 'string(/cib/@cib-last-written)' - | xargs -0 date +%s --date)
if [ -n $time_stamp -a $time_stamp -gt $image_time ]; then modified_files="cluster-cib" fi
if [ -f $FENCE_KDUMP_CONFIG_FILE ]; then - time_stamp=`stat -c "%Y" $FENCE_KDUMP_CONFIG_FILE` + time_stamp=$(stat -c "%Y" $FENCE_KDUMP_CONFIG_FILE) if [ "$time_stamp" -gt "$image_time" ]; then modified_files="$modified_files $FENCE_KDUMP_CONFIG_FILE" fi @@ -358,7 +357,7 @@ check_files_modified() fi HOOKS="$HOOKS $POST_FILES $PRE_FILES" CORE_COLLECTOR=$(kdump_get_conf_val core_collector | cut -d ' ' -f 1) - CORE_COLLECTOR=`type -P $CORE_COLLECTOR` + CORE_COLLECTOR=$(type -P $CORE_COLLECTOR) # POST_FILES and PRE_FILES are already checked against executable, need not to check again. EXTRA_BINS="$EXTRA_BINS $CHECK_FILES" CHECK_FILES=$(kdump_get_conf_val extra_bins) @@ -395,13 +394,13 @@ check_files_modified()
for file in $files; do if [ -e "$file" ]; then - time_stamp=`stat -c "%Y" $file` + time_stamp=$(stat -c "%Y" $file) if [ "$time_stamp" -gt "$image_time" ]; then modified_files="$modified_files $file" fi if [ -L "$file" ]; then file=$(readlink -m $file) - time_stamp=`stat -c "%Y" $file` + time_stamp=$(stat -c "%Y" $file) if [ "$time_stamp" -gt "$image_time" ]; then modified_files="$modified_files $file" fi @@ -591,7 +590,7 @@ check_rebuild() #check to see if dependent files has been modified #since last build of the image file if [ -f $TARGET_INITRD ]; then - image_time=`stat -c "%Y" $TARGET_INITRD 2>/dev/null` + image_time=$(stat -c "%Y" $TARGET_INITRD 2>/dev/null)
#in case of fadump mode, check whether the default/target #initrd is already built with dump capture capability @@ -727,7 +726,7 @@ check_ssh_config() done <<< "$(kdump_read_conf)"
#make sure they've configured kdump.conf for ssh dumps - local SSH_TARGET=`echo -n $DUMP_TARGET | sed -n '/.*@/p'` + local SSH_TARGET=$(echo -n $DUMP_TARGET | sed -n '/.*@/p') if [ -z "$SSH_TARGET" ]; then return 1 fi @@ -814,8 +813,8 @@ propagate_ssh_key() fi
#now find the target ssh user and server to contact. - SSH_USER=`echo $DUMP_TARGET | cut -d\ -f2 | cut -d@ -f1` - SSH_SERVER=`echo $DUMP_TARGET | sed -e's/(.*@)(.*$)/\2/'` + SSH_USER=$(echo $DUMP_TARGET | cut -d\ -f2 | cut -d@ -f1) + SSH_SERVER=$(echo $DUMP_TARGET | sed -e's/(.*@)(.*$)/\2/')
#now send the found key to the found server ssh-copy-id -i $KEYFILE $SSH_USER@$SSH_SERVER @@ -844,7 +843,7 @@ check_current_fadump_status() { # Check if firmware-assisted dump has been registered. rc=$(<$FADUMP_REGISTER_SYS_NODE) - [[ $rc -eq 1 ]] && return 0 + [ $rc -eq 1 ] && return 0 return 1 }
@@ -877,9 +876,9 @@ save_raw() fi kdump_dir=$(kdump_get_conf_val path) if [ -z "${kdump_dir}" ]; then - coredir="/var/crash/`date +"%Y-%m-%d-%H:%M"`" + coredir="/var/crash/$(date +"%Y-%m-%d-%H:%M")" else - coredir="${kdump_dir}/`date +"%Y-%m-%d-%H:%M"`" + coredir="${kdump_dir}/$(date +"%Y-%m-%d-%H:%M")" fi
mkdir -p "$coredir" @@ -956,8 +955,8 @@ selinux_relabel()
check_fence_kdump_config() { - local hostname=`hostname` - local ipaddrs=`hostname -I` + local hostname=$(hostname) + local ipaddrs=$(hostname -I) local nodes=$(kdump_get_conf_val "fence_kdump_nodes")
for node in $nodes; do
kdumpctl, mkdumprd, *-module-setup.sh only target bash, since they only run in first kernel and depend on dracut, and dracut depends on bash. So use '[[ ]]' to replace '[ ]'.
This is a batch update done with following command: `sed -i -e 's/(\s)[\s([^]]*)\s]/\1[[\ \2 ]]/g' kdumpctl, mkdumprd, *-module-setup.sh` and replaced [ ... -a ... ] with [[ ... ]] && [[ ... ]] manually.
See https://tldp.org/LDP/abs/html/testconstructs.html for more details on '[[ ]]', it's more versatile, safer, and slightly faster than '[ ]'.
This will also help shfmt to clean up the code in later commits.
Signed-off-by: Kairui Song kasong@redhat.com --- dracut-early-kdump-module-setup.sh | 10 +- dracut-module-setup.sh | 108 +++++++------- kdumpctl | 218 ++++++++++++++--------------- mkdumprd | 50 +++---- mkfadumprd | 2 +- 5 files changed, 194 insertions(+), 194 deletions(-)
diff --git a/dracut-early-kdump-module-setup.sh b/dracut-early-kdump-module-setup.sh index b25d6b5f..00546e01 100755 --- a/dracut-early-kdump-module-setup.sh +++ b/dracut-early-kdump-module-setup.sh @@ -6,8 +6,8 @@ KDUMP_KERNEL="" KDUMP_INITRD=""
check() { - if [ ! -f /etc/sysconfig/kdump ] || [ ! -f /lib/kdump/kdump-lib.sh ]\ - || [ -n "${IN_KDUMP}" ] + if [[ ! -f /etc/sysconfig/kdump ]] || [[ ! -f /lib/kdump/kdump-lib.sh ]]\ + || [[ -n "${IN_KDUMP}" ]] then return 1 fi @@ -25,7 +25,7 @@ prepare_kernel_initrd() { prepare_kdump_bootinfo
# $kernel is a variable from dracut - if [ "$KDUMP_KERNELVER" != $kernel ]; then + if [[ "$KDUMP_KERNELVER" != $kernel ]]; then dwarn "Using kernel version '$KDUMP_KERNELVER' for early kdump," \ "but the initramfs is generated for kernel version '$kernel'" fi @@ -33,12 +33,12 @@ prepare_kernel_initrd() {
install() { prepare_kernel_initrd - if [ ! -f "$KDUMP_KERNEL" ]; then + if [[ ! -f "$KDUMP_KERNEL" ]]; then derror "Could not find required kernel for earlykdump," \ "earlykdump will not work!" return 1 fi - if [ ! -f "$KDUMP_INITRD" ]; then + if [[ ! -f "$KDUMP_INITRD" ]]; then derror "Could not find required kdump initramfs for earlykdump," \ "please ensure kdump initramfs is generated first," \ "earlykdump will not work!" diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index 59aac91f..1e875016 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -11,7 +11,7 @@ kdump_module_init() { check() { [[ $debug ]] && set -x #kdumpctl sets this explicitly - if [ -z "$IN_KDUMP" ] || [ ! -f /etc/kdump.conf ] + if [[ -z "$IN_KDUMP" ]] || [[ ! -f /etc/kdump.conf ]] then return 1 fi @@ -41,11 +41,11 @@ depends() { _dep="$_dep ssh-client" fi
- if [ "$(uname -m)" = "s390x" ]; then + if [[ "$(uname -m)" = "s390x" ]]; then _dep="$_dep znet" fi
- if [ -n "$( ls -A /sys/class/drm 2>/dev/null )" ] || [ -d /sys/module/hyperv_fb ]; then + if [[ -n "$( ls -A /sys/class/drm 2>/dev/null )" ]] || [[ -d /sys/module/hyperv_fb ]]; then add_opt_module drm fi
@@ -57,19 +57,19 @@ depends() { }
kdump_is_bridge() { - [ -d /sys/class/net/"$1"/bridge ] + [[ -d /sys/class/net/"$1"/bridge ]] }
kdump_is_bond() { - [ -d /sys/class/net/"$1"/bonding ] + [[ -d /sys/class/net/"$1"/bonding ]] }
kdump_is_team() { - [ -f /usr/bin/teamnl ] && teamnl $1 ports &> /dev/null + [[ -f /usr/bin/teamnl ]] && teamnl $1 ports &> /dev/null }
kdump_is_vlan() { - [ -f /proc/net/vlan/"$1" ] + [[ -f /proc/net/vlan/"$1" ]] }
# $1: netdev name @@ -78,7 +78,7 @@ source_ifcfg_file() {
dwarning "Network Scripts are deprecated. You are encouraged to set up network by NetworkManager." ifcfg_file=$(get_ifcfg_filename $1) - if [ -f "${ifcfg_file}" ]; then + if [[ -f "${ifcfg_file}" ]]; then . ${ifcfg_file} else dwarning "The ifcfg file of $1 is not found!" @@ -102,19 +102,19 @@ kdump_setup_dns() { else dwarning "Failed to get DNS info via nmcli output. Now try sourcing ifcfg script" source_ifcfg_file "$_netdev" - [ -n "$DNS1" ] && echo "nameserver=$DNS1" > "$_dnsfile" - [ -n "$DNS2" ] && echo "nameserver=$DNS2" >> "$_dnsfile" + [[ -n "$DNS1" ]] && echo "nameserver=$DNS1" > "$_dnsfile" + [[ -n "$DNS2" ]] && echo "nameserver=$DNS2" >> "$_dnsfile" fi
while read -r content; do _nameserver=$(echo $content | grep ^nameserver) - [ -z "$_nameserver" ] && continue + [[ -z "$_nameserver" ]] && continue
_dns=$(echo $_nameserver | cut -d' ' -f2) - [ -z "$_dns" ] && continue + [[ -z "$_dns" ]] && continue
- if [ ! -f $_dnsfile ] || ! grep -q "$_dns" "$_dnsfile" ; then + if [[ ! -f $_dnsfile ]] || ! grep -q "$_dns" "$_dnsfile" ; then echo "nameserver=$_dns" >> "$_dnsfile" fi done < "/etc/resolv.conf" @@ -243,11 +243,11 @@ kdump_static_ip() { _ipv6_flag="-6" fi
- if [ -n "$_ipaddr" ]; then + if [[ -n "$_ipaddr" ]]; then _gateway=$(ip $_ipv6_flag route list dev $_netdev | \ awk '/^default /{print $3}' | head -n 1)
- if [ "x" != "x"$_ipv6_flag ]; then + if [[ "x" != "x"$_ipv6_flag ]]; then # _ipaddr="2002::56ff:feb6:56d5/64", _netmask is the number after "/" _netmask=${_ipaddr#*/} _srcaddr="[$_srcaddr]" @@ -268,7 +268,7 @@ kdump_static_ip() { while read -r _route; do _target=$(echo $_route | cut -d ' ' -f1) _nexthop=$(echo $_route | cut -d ' ' -f3) - if [ "x" != "x"$_ipv6_flag ]; then + if [[ "x" != "x"$_ipv6_flag ]]; then _target="[$_target]" _nexthop="[$_nexthop]" fi @@ -297,7 +297,7 @@ kdump_handle_mulitpath_route() { if [[ "$_weight" -gt "$_max_weight" ]]; then _nexthop=$(echo "$_route" | cut -d ' ' -f3) _max_weight=$_weight - if [ "x" != "x"$_ipv6_flag ]; then + if [[ "x" != "x"$_ipv6_flag ]]; then _rule="rd.route=[$_target]:[$_nexthop]:$kdumpnic" else _rule="rd.route=$_target:$_nexthop:$kdumpnic" @@ -322,7 +322,7 @@ kdump_get_mac_addr() { #of its slaves, we should use perm address kdump_get_perm_addr() { local addr=$(ethtool -P $1 | sed -e 's/Permanent address: //') - if [ -z "$addr" ] || [ "$addr" = "00:00:00:00:00:00" ] + if [[ -z "$addr" ]] || [[ "$addr" = "00:00:00:00:00:00" ]] then derror "Can't get the permanent address of $1" else @@ -419,7 +419,7 @@ kdump_setup_team() { #Buggy version teamdctl outputs to stderr! #Try to use the latest version of teamd. teamdctl "$_netdev" config dump > ${initdir}/tmp/$$-$_netdev.conf - if [ $? -ne 0 ] + if [[ $? -ne 0 ]] then derror "teamdctl failed." exit 1 @@ -459,25 +459,25 @@ find_online_znet_device() { local CCWGROUPBUS_DEVICEDIR="/sys/bus/ccwgroup/devices" local NETWORK_DEVICES d ifname ONLINE
- [ ! -d "$CCWGROUPBUS_DEVICEDIR" ] && return + [[ ! -d "$CCWGROUPBUS_DEVICEDIR" ]] && return NETWORK_DEVICES=$(find $CCWGROUPBUS_DEVICEDIR) for d in $NETWORK_DEVICES do - [ ! -f "$d/online" ] && continue + [[ ! -f "$d/online" ]] && continue read -r ONLINE < $d/online - if [ $ONLINE -ne 1 ]; then + if [[ $ONLINE -ne 1 ]]; then continue fi # determine interface name, if there (only for qeth and if # device is online) - if [ -f $d/if_name ] + if [[ -f $d/if_name ]] then read -r ifname < $d/if_name - elif [ -d $d/net ] + elif [[ -d $d/net ]] then ifname=$(ls $d/net/) fi - [ -n "$ifname" ] && break + [[ -n "$ifname" ]] && break done echo -n "$ifname" } @@ -532,7 +532,7 @@ kdump_get_remote_ip() local _remote=$(get_remote_host $1) _remote_temp if is_hostname $_remote; then _remote_temp=$(getent ahosts $_remote | grep -v : | head -n 1) - if [ -z "$_remote_temp" ]; then + if [[ -z "$_remote_temp" ]]; then _remote_temp=$(getent ahosts $_remote | head -n 1) fi _remote=$(echo $_remote_temp | cut -d' ' -f1) @@ -567,7 +567,7 @@ kdump_install_net() { fi
_static=$(kdump_static_ip $_netdev $_srcaddr $kdumpnic) - if [ -n "$_static" ]; then + if [[ -n "$_static" ]]; then _proto=none elif is_ipv6_address $_srcaddr; then _proto=auto6 @@ -582,7 +582,7 @@ kdump_install_net() { # so we have to avoid adding duplicates # We should also check /proc/cmdline for existing ip=xx arg. # For example, iscsi boot will specify ip=xxx arg in cmdline. - if [ ! -f $_ip_conf ] || ! grep -q $_ip_opts $_ip_conf &&\ + if [[ ! -f $_ip_conf ]] || ! grep -q $_ip_opts $_ip_conf &&\ ! grep -q "ip=[^[:space:]]*$_netdev" /proc/cmdline; then echo "$_ip_opts" >> $_ip_conf fi @@ -605,7 +605,7 @@ kdump_install_net() {
kdump_setup_dns "$_netdev" "$_nm_show_cmd"
- if [ ! -f ${initdir}/etc/cmdline.d/50neednet.conf ]; then + if [[ ! -f ${initdir}/etc/cmdline.d/50neednet.conf ]]; then # network-manager module needs this parameter echo "rd.neednet" >> ${initdir}/etc/cmdline.d/50neednet.conf fi @@ -617,8 +617,8 @@ kdump_install_net() { # the default gate way for network dump, eth1 in the fence kdump path will # call kdump_install_net again and we don't want eth1 to be the default # gateway. - if [ ! -f ${initdir}/etc/cmdline.d/60kdumpnic.conf ] && - [ ! -f ${initdir}/etc/cmdline.d/70bootdev.conf ]; then + if [[ ! -f ${initdir}/etc/cmdline.d/60kdumpnic.conf ]] && + [[ ! -f ${initdir}/etc/cmdline.d/70bootdev.conf ]]; then echo "kdumpnic=$kdumpnic" > ${initdir}/etc/cmdline.d/60kdumpnic.conf echo "bootdev=$kdumpnic" > ${initdir}/etc/cmdline.d/70bootdev.conf fi @@ -626,21 +626,21 @@ kdump_install_net() {
# install etc/kdump/pre.d and /etc/kdump/post.d kdump_install_pre_post_conf() { - if [ -d /etc/kdump/pre.d ]; then + if [[ -d /etc/kdump/pre.d ]]; then for file in /etc/kdump/pre.d/*; do - if [ -x "$file" ]; then + if [[ -x "$file" ]]; then dracut_install $file - elif [ $file != "/etc/kdump/pre.d/*" ]; then + elif [[ $file != "/etc/kdump/pre.d/*" ]]; then echo "$file is not executable" fi done fi
- if [ -d /etc/kdump/post.d ]; then + if [[ -d /etc/kdump/post.d ]]; then for file in /etc/kdump/post.d/*; do - if [ -x "$file" ]; then + if [[ -x "$file" ]]; then dracut_install $file - elif [ $file != "/etc/kdump/post.d/*" ]; then + elif [[ $file != "/etc/kdump/post.d/*" ]]; then echo "$file is not executable" fi done @@ -669,7 +669,7 @@ default_dump_target_install_conf() echo "$_fstype $_target" >> ${initdir}/tmp/$$-kdump.conf
# don't touch the path under root mount - if [ "$_mntpoint" != "/" ]; then + if [[ "$_mntpoint" != "/" ]]; then _save_path=${_save_path##"$_mntpoint"} fi
@@ -750,10 +750,10 @@ kdump_get_iscsi_initiator() { local _initiator local initiator_conf="/etc/iscsi/initiatorname.iscsi"
- [ -f "$initiator_conf" ] || return 1 + [[ -f "$initiator_conf" ]] || return 1
while read -r _initiator; do - [ -z "${_initiator%%#*}" ] && continue # Skip comment lines + [[ -z "${_initiator%%#*}" ]] && continue # Skip comment lines
case $_initiator in InitiatorName=*) @@ -769,7 +769,7 @@ kdump_get_iscsi_initiator() {
# Figure out iBFT session according to session type is_ibft() { - [ "$(kdump_iscsi_get_rec_val $1 "node.discovery_type")" = fw ] + [[ "$(kdump_iscsi_get_rec_val $1 "node.discovery_type")" = fw ]] }
kdump_setup_iscsi_device() { @@ -802,18 +802,18 @@ kdump_setup_iscsi_device() {
# get and set username and password details username=$(kdump_iscsi_get_rec_val ${path} "node.session.auth.username") - [ "$username" == "<empty>" ] && username="" + [[ "$username" == "<empty>" ]] && username="" password=$(kdump_iscsi_get_rec_val ${path} "node.session.auth.password") - [ "$password" == "<empty>" ] && password="" + [[ "$password" == "<empty>" ]] && password="" username_in=$(kdump_iscsi_get_rec_val ${path} "node.session.auth.username_in") - [ -n "$username" ] && userpwd_str="$username:$password" + [[ -n "$username" ]] && userpwd_str="$username:$password"
# get and set incoming username and password details - [ "$username_in" == "<empty>" ] && username_in="" + [[ "$username_in" == "<empty>" ]] && username_in="" password_in=$(kdump_iscsi_get_rec_val ${path} "node.session.auth.password_in") - [ "$password_in" == "<empty>" ] && password_in="" + [[ "$password_in" == "<empty>" ]] && password_in=""
- [ -n "$username_in" ] && userpwd_in_str=":$username_in:$password_in" + [[ -n "$username_in" ]] && userpwd_in_str=":$username_in:$password_in"
kdump_install_net "$tgt_ipaddr"
@@ -836,7 +836,7 @@ kdump_setup_iscsi_device() {
# Setup initator initiator_str=$(kdump_get_iscsi_initiator) - [ $? -ne "0" ] && derror "Failed to get initiator name" && return 1 + [[ $? -ne "0" ]] && derror "Failed to get initiator name" && return 1
# If initiator details do not exist already, append. if ! grep -q "$initiator_str" $netroot_conf; then @@ -877,7 +877,7 @@ get_alias() { do # in /etc/hosts, alias can come at the 2nd column entries=$(grep $ip /etc/hosts | awk '{ $1=""; print $0 }') - if [ $? -eq 0 ]; then + if [[ $? -eq 0 ]]; then alias_set="$alias_set $entries" fi done @@ -894,7 +894,7 @@ is_localhost() { hostnames="$hostnames $shortnames $aliasname"
for name in ${hostnames}; do - if [ "$name" == "$nodename" ]; then + if [[ "$name" == "$nodename" ]]; then return 0 fi done @@ -927,7 +927,7 @@ get_pcs_fence_kdump_nodes() {
# retrieves fence_kdump args from config file get_pcs_fence_kdump_args() { - if [ -f $FENCE_KDUMP_CONFIG_FILE ]; then + if [[ -f $FENCE_KDUMP_CONFIG_FILE ]]; then . $FENCE_KDUMP_CONFIG_FILE echo $FENCE_KDUMP_OPTS fi @@ -965,7 +965,7 @@ kdump_configure_fence_kdump () { echo "fence_kdump_nodes $nodes" >> ${kdump_cfg_file}
args=$(get_pcs_fence_kdump_args) - if [ -n "$args" ]; then + if [[ -n "$args" ]]; then echo "fence_kdump_args $args" >> ${kdump_cfg_file} fi
@@ -991,7 +991,7 @@ kdump_install_random_seed() {
poolsize=$(</proc/sys/kernel/random/poolsize)
- if [ ! -d ${initdir}/var/lib/ ]; then + if [[ ! -d ${initdir}/var/lib/ ]]; then mkdir -p ${initdir}/var/lib/ fi
@@ -1003,7 +1003,7 @@ kdump_install_systemd_conf() { # Kdump turns out to require longer default systemd mount timeout # than 1st kernel(90s by default), we use default 300s for kdump. grep -r "^[[:space:]]*DefaultTimeoutStartSec=" ${initdir}/etc/systemd/system.conf* &>/dev/null - if [ $? -ne 0 ]; then + if [[ $? -ne 0 ]]; then mkdir -p ${initdir}/etc/systemd/system.conf.d echo "[Manager]" > ${initdir}/etc/systemd/system.conf.d/kdump.conf echo "DefaultTimeoutStartSec=300s" >> ${initdir}/etc/systemd/system.conf.d/kdump.conf diff --git a/kdumpctl b/kdumpctl index 910b7175..d29d37f2 100755 --- a/kdumpctl +++ b/kdumpctl @@ -27,7 +27,7 @@ standard_kexec_args="-d -p" # Some default values in case /etc/sysconfig/kdump doesn't include KDUMP_COMMANDLINE_REMOVE="hugepages hugepagesz slub_debug"
-if [ -f /etc/sysconfig/kdump ]; then +if [[ -f /etc/sysconfig/kdump ]]; then . /etc/sysconfig/kdump fi
@@ -38,7 +38,7 @@ fi
#initiate the kdump logger dlog_init -if [ $? -ne 0 ]; then +if [[ $? -ne 0 ]]; then echo "failed to initiate the kdump logger." exit 1 fi @@ -48,7 +48,7 @@ single_instance_lock() local rc timeout=5
exec 9>/var/lock/kdump - if [ $? -ne 0 ]; then + if [[ $? -ne 0 ]]; then derror "Create file lock failed" exit 1 fi @@ -56,7 +56,7 @@ single_instance_lock() flock -n 9 rc=$?
- while [ $rc -ne 0 ]; do + while [[ $rc -ne 0 ]]; do dinfo "Another app is currently holding the kdump lock; waiting for it to exit..." flock -w $timeout 9 rc=$? @@ -81,7 +81,7 @@ save_core() mkdir -p $coredir ddebug "cp --sparse=always /proc/vmcore $coredir/vmcore-incomplete" cp --sparse=always /proc/vmcore $coredir/vmcore-incomplete - if [ $? == 0 ]; then + if [[ $? == 0 ]]; then mv $coredir/vmcore-incomplete $coredir/vmcore dinfo "saved a vmcore to $coredir" else @@ -91,12 +91,12 @@ save_core() # pass the dmesg to Abrt tool if exists, in order # to collect the kernel oops message. # https://fedorahosted.org/abrt/ - if [ -x /usr/bin/dumpoops ]; then + if [[ -x /usr/bin/dumpoops ]]; then ddebug "makedumpfile --dump-dmesg $coredir/vmcore $coredir/dmesg" makedumpfile --dump-dmesg $coredir/vmcore $coredir/dmesg >/dev/null 2>&1 ddebug "dumpoops -d $coredir/dmesg" dumpoops -d $coredir/dmesg >/dev/null 2>&1 - if [ $? == 0 ]; then + if [[ $? == 0 ]]; then dinfo "kernel oops has been collected by abrt tool" fi fi @@ -122,7 +122,7 @@ rebuild_kdump_initrd() { ddebug "rebuild kdump initrd: $MKDUMPRD $TARGET_INITRD $KDUMP_KERNELVER" $MKDUMPRD $TARGET_INITRD $KDUMP_KERNELVER - if [ $? != 0 ]; then + if [[ $? != 0 ]]; then derror "mkdumprd: failed to make kdump initrd" return 1 fi @@ -141,7 +141,7 @@ rebuild_initrd() return 1 fi
- if [ $DEFAULT_DUMP_MODE == "fadump" ]; then + if [[ $DEFAULT_DUMP_MODE == "fadump" ]]; then rebuild_fadump_initrd else rebuild_kdump_initrd @@ -154,7 +154,7 @@ rebuild_initrd() check_exist() { for file in $1; do - if [ ! -e "$file" ]; then + if [[ ! -e "$file" ]]; then derror "Error: $file not found." return 1 fi @@ -165,7 +165,7 @@ check_exist() check_executable() { for file in $1; do - if [ ! -x "$file" ]; then + if [[ ! -x "$file" ]]; then derror "Error: $file is not executable." return 1 fi @@ -176,16 +176,16 @@ backup_default_initrd() { ddebug "backup default initrd: $DEFAULT_INITRD"
- if [ ! -f "$DEFAULT_INITRD" ]; then + if [[ ! -f "$DEFAULT_INITRD" ]]; then return fi
- if [ ! -e $DEFAULT_INITRD_BAK ]; then + if [[ ! -e $DEFAULT_INITRD_BAK ]]; then dinfo "Backing up $DEFAULT_INITRD before rebuild." # save checksum to verify before restoring sha1sum $DEFAULT_INITRD > $INITRD_CHECKSUM_LOCATION cp $DEFAULT_INITRD $DEFAULT_INITRD_BAK - if [ $? -ne 0 ]; then + if [[ $? -ne 0 ]]; then dwarn "WARNING: failed to backup $DEFAULT_INITRD." rm -f $DEFAULT_INITRD_BAK fi @@ -196,17 +196,17 @@ restore_default_initrd() { ddebug "restore default initrd: $DEFAULT_INITRD"
- if [ ! -f "$DEFAULT_INITRD" ]; then + if [[ ! -f "$DEFAULT_INITRD" ]]; then return fi
# If a backup initrd exists, we must be switching back from # fadump to kdump. Restore the original default initrd. - if [ -f $DEFAULT_INITRD_BAK ] && [ -f $INITRD_CHECKSUM_LOCATION ]; then + if [[ -f $DEFAULT_INITRD_BAK ]] && [[ -f $INITRD_CHECKSUM_LOCATION ]]; then # verify checksum before restoring backup_checksum=$(sha1sum "$DEFAULT_INITRD_BAK" | awk '{ print $1 }') default_checksum=$(awk '{ print $1 }' "$INITRD_CHECKSUM_LOCATION") - if [ "$default_checksum" != "$backup_checksum" ]; then + if [[ "$default_checksum" != "$backup_checksum" ]]; then dwarn "WARNING: checksum mismatch! Can't restore original initrd.." else rm -f $INITRD_CHECKSUM_LOCATION @@ -226,7 +226,7 @@ check_config() case "$config_opt" in dracut_args) if [[ $config_val == *--mount* ]]; then - if [ $(echo $config_val | grep -o "--mount" | wc -l) -ne 1 ]; then + if [[ $(echo $config_val | grep -o "--mount" | wc -l) -ne 1 ]]; then derror "Multiple mount targets specified in one "dracut_args"." return 1 fi @@ -234,7 +234,7 @@ check_config() fi ;; raw) - if [ -d "/proc/device-tree/ibm,opal/dump" ]; then + if [[ -d "/proc/device-tree/ibm,opal/dump" ]]; then dwarn "WARNING: Won't capture opalcore when 'raw' dump target is used." fi config_opt=_target @@ -262,8 +262,8 @@ check_config() return 1 fi
- if [ -n "${_opt_rec[$config_opt]}" ]; then - if [ $config_opt == _target ]; then + if [[ -n "${_opt_rec[$config_opt]}" ]]; then + if [[ $config_opt == _target ]]; then derror "More than one dump targets specified" else derror "Duplicated kdump config value of option $config_opt" @@ -292,13 +292,13 @@ get_pcs_cluster_modified_files()
time_stamp=$(pcs cluster cib | xmllint --xpath 'string(/cib/@cib-last-written)' - | xargs -0 date +%s --date)
- if [ -n $time_stamp -a $time_stamp -gt $image_time ]; then + if [[ -n $time_stamp ]] && [[ $time_stamp -gt $image_time ]]; then modified_files="cluster-cib" fi
- if [ -f $FENCE_KDUMP_CONFIG_FILE ]; then + if [[ -f $FENCE_KDUMP_CONFIG_FILE ]]; then time_stamp=$(stat -c "%Y" $FENCE_KDUMP_CONFIG_FILE) - if [ "$time_stamp" -gt "$image_time" ]; then + if [[ "$time_stamp" -gt "$image_time" ]]; then modified_files="$modified_files $FENCE_KDUMP_CONFIG_FILE" fi fi @@ -309,13 +309,13 @@ get_pcs_cluster_modified_files() setup_initrd() { prepare_kdump_bootinfo - if [ $? -ne 0 ]; then + if [[ $? -ne 0 ]]; then derror "failed to prepare for kdump bootinfo." return 1 fi
DEFAULT_INITRD_BAK="$KDUMP_BOOTDIR/.$(basename $DEFAULT_INITRD).default" - if [ $DEFAULT_DUMP_MODE == "fadump" ]; then + if [[ $DEFAULT_DUMP_MODE == "fadump" ]]; then TARGET_INITRD="$DEFAULT_INITRD"
# backup initrd for reference before replacing it @@ -341,16 +341,16 @@ check_files_modified() EXTRA_BINS=$(kdump_get_conf_val kdump_post) CHECK_FILES=$(kdump_get_conf_val kdump_pre) HOOKS="/etc/kdump/post.d/ /etc/kdump/pre.d/" - if [ -d /etc/kdump/post.d ]; then + if [[ -d /etc/kdump/post.d ]]; then for file in /etc/kdump/post.d/*; do - if [ -x "$file" ]; then + if [[ -x "$file" ]]; then POST_FILES="$POST_FILES $file" fi done fi - if [ -d /etc/kdump/pre.d ]; then + if [[ -d /etc/kdump/pre.d ]]; then for file in /etc/kdump/pre.d/*; do - if [ -x "$file" ]; then + if [[ -x "$file" ]]; then PRE_FILES="$PRE_FILES $file" fi done @@ -367,8 +367,8 @@ check_files_modified()
# Check for any updated extra module EXTRA_MODULES="$(kdump_get_conf_val extra_modules)" - if [ -n "$EXTRA_MODULES" ]; then - if [ -e /lib/modules/$KDUMP_KERNELVER/modules.dep ]; then + if [[ -n "$EXTRA_MODULES" ]]; then + if [[ -e /lib/modules/$KDUMP_KERNELVER/modules.dep ]]; then files="$files /lib/modules/$KDUMP_KERNELVER/modules.dep" fi for _module in $EXTRA_MODULES; do @@ -390,18 +390,18 @@ check_files_modified() # HOOKS is mandatory and need to check the modification time files="$files $HOOKS" check_exist "$files" && check_executable "$EXTRA_BINS" - [ $? -ne 0 ] && return 2 + [[ $? -ne 0 ]] && return 2
for file in $files; do - if [ -e "$file" ]; then + if [[ -e "$file" ]]; then time_stamp=$(stat -c "%Y" $file) - if [ "$time_stamp" -gt "$image_time" ]; then + if [[ "$time_stamp" -gt "$image_time" ]]; then modified_files="$modified_files $file" fi - if [ -L "$file" ]; then + if [[ -L "$file" ]]; then file=$(readlink -m $file) time_stamp=$(stat -c "%Y" $file) - if [ "$time_stamp" -gt "$image_time" ]; then + if [[ "$time_stamp" -gt "$image_time" ]]; then modified_files="$modified_files $file" fi fi @@ -410,7 +410,7 @@ check_files_modified() fi done
- if [ -n "$modified_files" ]; then + if [[ -n "$modified_files" ]]; then dinfo "Detected change(s) in the following file(s): $modified_files" return 1 fi @@ -441,7 +441,7 @@ check_drivers_modified()
# Include watchdog drivers if watchdog module is not omitted is_dracut_mod_omitted watchdog || _new_drivers+=" $(get_watchdog_drvs)" - [ -z "$_new_drivers" ] && return 0 + [[ -z "$_new_drivers" ]] && return 0
if is_fadump_capable; then _old_drivers="$(lsinitrd "$TARGET_INITRD" -f /usr/lib/dracut/fadump-kernel-modules.txt | tr '\n' ' ')" @@ -455,7 +455,7 @@ check_drivers_modified() # Skip deprecated/invalid driver name or built-in module _module_name=$(modinfo --set-version "$KDUMP_KERNELVER" -F name $_driver 2>/dev/null) _module_filename=$(modinfo --set-version "$KDUMP_KERNELVER" -n $_driver 2>/dev/null) - if [ $? -ne 0 ] || [ -z "$_module_name" ] || [[ "$_module_filename" = *"(builtin)"* ]]; then + if [[ $? -ne 0 ]] || [[ -z "$_module_name" ]] || [[ "$_module_filename" = *"(builtin)"* ]]; then continue fi if ! [[ " $_old_drivers " == *" $_module_name "* ]]; then @@ -491,7 +491,7 @@ check_fs_modified()
ddebug "_target=$_target _new_fstype=$_new_fstype" _new_dev=$(kdump_get_persistent_dev $_target) - if [ -z "$_new_dev" ]; then + if [[ -z "$_new_dev" ]]; then perror "Get persistent device name failed" return 2 fi @@ -532,19 +532,19 @@ check_system_modified()
check_files_modified ret=$? - if [ $ret -ne 0 ]; then + if [[ $ret -ne 0 ]]; then return $ret fi
check_fs_modified ret=$? - if [ $ret -ne 0 ]; then + if [[ $ret -ne 0 ]]; then return $ret fi
check_drivers_modified ret=$? - if [ $ret -ne 0 ]; then + if [[ $ret -ne 0 ]]; then return $ret fi
@@ -559,20 +559,20 @@ check_rebuild()
setup_initrd
- if [ $? -ne 0 ]; then + if [[ $? -ne 0 ]]; then return 1 fi
force_no_rebuild=$(kdump_get_conf_val force_no_rebuild) force_no_rebuild=${force_no_rebuild:-0} - if [ "$force_no_rebuild" != "0" ] && [ "$force_no_rebuild" != "1" ];then + if [[ "$force_no_rebuild" != "0" ]] && [[ "$force_no_rebuild" != "1" ]];then derror "Error: force_no_rebuild value is invalid" return 1 fi
force_rebuild=$(kdump_get_conf_val force_rebuild) force_rebuild=${force_rebuild:-0} - if [ "$force_rebuild" != "0" ] && [ "$force_rebuild" != "1" ];then + if [[ "$force_rebuild" != "0" ]] && [[ "$force_rebuild" != "1" ]];then derror "Error: force_rebuild value is invalid" return 1 fi @@ -583,37 +583,37 @@ check_rebuild() fi
# Will not rebuild kdump initrd - if [ "$force_no_rebuild" == "1" ]; then + if [[ "$force_no_rebuild" == "1" ]]; then return 0 fi
#check to see if dependent files has been modified #since last build of the image file - if [ -f $TARGET_INITRD ]; then + if [[ -f $TARGET_INITRD ]]; then image_time=$(stat -c "%Y" $TARGET_INITRD 2>/dev/null)
#in case of fadump mode, check whether the default/target #initrd is already built with dump capture capability - if [ "$DEFAULT_DUMP_MODE" == "fadump" ]; then + if [[ "$DEFAULT_DUMP_MODE" == "fadump" ]]; then capture_capable_initrd=$(lsinitrd -f $DRACUT_MODULES_FILE "$TARGET_INITRD" | grep -c -e ^kdumpbase$ -e ^zz-fadumpinit$) fi fi
check_system_modified ret=$? - if [ $ret -eq 2 ]; then + if [[ $ret -eq 2 ]]; then return 1 - elif [ $ret -eq 1 ];then + elif [[ $ret -eq 1 ]];then system_modified="1" fi
- if [ $image_time -eq 0 ]; then + if [[ $image_time -eq 0 ]]; then dinfo "No kdump initial ramdisk found." - elif [ "$capture_capable_initrd" == "0" ]; then + elif [[ "$capture_capable_initrd" == "0" ]]; then dinfo "Rebuild $TARGET_INITRD with dump capture support" - elif [ "$force_rebuild" != "0" ]; then + elif [[ "$force_rebuild" != "0" ]]; then dinfo "Force rebuild $TARGET_INITRD" - elif [ "$system_modified" != "0" ]; then + elif [[ "$system_modified" != "0" ]]; then : else return 0 @@ -633,7 +633,7 @@ function load_kdump_kernel_key()
# this is only required if DT /ibm,secure-boot is a file. # if it is a dir, we are on OpenPower and don't need this. - if ! [ -f /proc/device-tree/ibm,secure-boot ]; then + if ! [[ -f /proc/device-tree/ibm,secure-boot ]]; then return fi
@@ -645,7 +645,7 @@ function load_kdump_kernel_key() # to be idempotent and so as to reduce the potential for confusion. function remove_kdump_kernel_key() { - if [ -z "$KDUMP_KEY_ID" ]; then + if [[ -z "$KDUMP_KEY_ID" ]]; then return fi
@@ -692,7 +692,7 @@ load_kdump()
remove_kdump_kernel_key
- if [ $ret == 0 ]; then + if [[ $ret == 0 ]]; then dinfo "kexec: loaded kdump kernel" return 0 else @@ -707,7 +707,7 @@ check_ssh_config() case "$config_opt" in sshkey) # remove inline comments after the end of a directive. - if [ -f "$config_val" ]; then + if [[ -f "$config_val" ]]; then # canonicalize the path SSH_KEY_LOCATION=$(/usr/bin/readlink -m $config_val) else @@ -727,7 +727,7 @@ check_ssh_config()
#make sure they've configured kdump.conf for ssh dumps local SSH_TARGET=$(echo -n $DUMP_TARGET | sed -n '/.*@/p') - if [ -z "$SSH_TARGET" ]; then + if [[ -z "$SSH_TARGET" ]]; then return 1 fi return 0 @@ -750,9 +750,9 @@ check_and_wait_network_ready() retval=$?
# ssh exits with the exit status of the remote command or with 255 if an error occurred - if [ $retval -eq 0 ]; then + if [[ $retval -eq 0 ]]; then return 0 - elif [ $retval -ne 255 ]; then + elif [[ $retval -ne 255 ]]; then derror "Could not create $DUMP_TARGET:$SAVE_PATH, you should check the privilege on server side" return 1 fi @@ -760,12 +760,12 @@ check_and_wait_network_ready() # if server removes the authorized_keys or, no /root/.ssh/kdump_id_rsa ddebug "$errmsg" echo $errmsg | grep -q "Permission denied|No such file or directory|Host key verification failed" &> /dev/null - if [ $? -eq 0 ]; then + if [[ $? -eq 0 ]]; then derror "Could not create $DUMP_TARGET:$SAVE_PATH, you probably need to run "kdumpctl propagate"" return 1 fi
- if [ $warn_once -eq 1 ]; then + if [[ $warn_once -eq 1 ]]; then dwarn "Network dump target is not usable, waiting for it to be ready..." warn_once=0 fi @@ -773,7 +773,7 @@ check_and_wait_network_ready() cur=$(date +%s) diff=$((cur - start_time)) # 60s time out - if [ $diff -gt 180 ]; then + if [[ $diff -gt 180 ]]; then break; fi sleep 1 @@ -786,7 +786,7 @@ check_and_wait_network_ready() check_ssh_target() { check_and_wait_network_ready - if [ $? -ne 0 ]; then + if [[ $? -ne 0 ]]; then return 1 fi return 0 @@ -795,7 +795,7 @@ check_ssh_target() propagate_ssh_key() { check_ssh_config - if [ $? -ne 0 ]; then + if [[ $? -ne 0 ]]; then derror "No ssh config specified in $KDUMP_CONFIG_FILE. Can't propagate" exit 1 fi @@ -804,7 +804,7 @@ propagate_ssh_key() local errmsg="Failed to propagate ssh key"
#Check to see if we already created key, if not, create it. - if [ -f $KEYFILE ]; then + if [[ -f $KEYFILE ]]; then dinfo "Using existing keys..." else dinfo "Generating new ssh keys... " @@ -819,7 +819,7 @@ propagate_ssh_key() #now send the found key to the found server ssh-copy-id -i $KEYFILE $SSH_USER@$SSH_SERVER RET=$? - if [ $RET == 0 ]; then + if [[ $RET == 0 ]]; then dinfo "$KEYFILE has been added to ~$SSH_USER/.ssh/authorized_keys on $SSH_SERVER" return 0 else @@ -843,13 +843,13 @@ check_current_fadump_status() { # Check if firmware-assisted dump has been registered. rc=$(<$FADUMP_REGISTER_SYS_NODE) - [ $rc -eq 1 ] && return 0 + [[ $rc -eq 1 ]] && return 0 return 1 }
check_current_status() { - if [ $DEFAULT_DUMP_MODE == "fadump" ]; then + if [[ $DEFAULT_DUMP_MODE == "fadump" ]]; then check_current_fadump_status else check_current_kdump_status @@ -864,8 +864,8 @@ save_raw() local raw_target
raw_target=$(kdump_get_conf_val raw) - [ -z "$raw_target" ] && return 0 - [ -b "$raw_target" ] || { + [[ -z "$raw_target" ]] && return 0 + [[ -b "$raw_target" ]] || { derror "raw partition $raw_target not found" return 1 } @@ -875,14 +875,14 @@ save_raw() return 0 fi kdump_dir=$(kdump_get_conf_val path) - if [ -z "${kdump_dir}" ]; then + if [[ -z "${kdump_dir}" ]]; then coredir="/var/crash/$(date +"%Y-%m-%d-%H:%M")" else coredir="${kdump_dir}/$(date +"%Y-%m-%d-%H:%M")" fi
mkdir -p "$coredir" - [ -d "$coredir" ] || { + [[ -d "$coredir" ]] || { derror "failed to create $coredir" return 1 } @@ -903,7 +903,7 @@ local_fs_dump_target() local _target
_target=$(egrep "^ext[234]|^xfs|^btrfs|^minix" /etc/kdump.conf) - if [ $? -eq 0 ]; then + if [[ $? -eq 0 ]]; then echo $_target|awk '{print $2}' fi } @@ -931,7 +931,7 @@ path_to_be_relabeled() _path=$(get_save_path) # if $_path is masked by other mount, we will not relabel it. _rmnt=$(df $_mnt/$_path 2>/dev/null | tail -1 | awk '{ print $NF }') - if [ "$_rmnt" == "$_mnt" ]; then + if [[ "$_rmnt" == "$_mnt" ]]; then echo $_mnt/$_path fi } @@ -941,13 +941,13 @@ selinux_relabel() local _path _i _attr
_path=$(path_to_be_relabeled) - if [ -z "$_path" ] || ! [ -d "$_path" ] ; then + if [[ -z "$_path" ]] || ! [[ -d "$_path" ]] ; then return fi
while read -r _i; do _attr=$(getfattr -m "security.selinux" "$_i" 2>/dev/null) - if [ -z "$_attr" ]; then + if [[ -z "$_attr" ]]; then restorecon "$_i"; fi done <<< "$(find "$_path")" @@ -960,13 +960,13 @@ check_fence_kdump_config() local nodes=$(kdump_get_conf_val "fence_kdump_nodes")
for node in $nodes; do - if [ "$node" = "$hostname" ]; then + if [[ "$node" = "$hostname" ]]; then derror "Option fence_kdump_nodes cannot contain $hostname" return 1 fi # node can be ipaddr echo "$ipaddrs " | grep "$node " > /dev/null - if [ $? -eq 0 ]; then + if [[ $? -eq 0 ]]; then derror "Option fence_kdump_nodes cannot contain $node" return 1 fi @@ -977,7 +977,7 @@ check_fence_kdump_config()
check_dump_feasibility() { - if [ $DEFAULT_DUMP_MODE == "fadump" ]; then + if [[ $DEFAULT_DUMP_MODE == "fadump" ]]; then return 0 fi
@@ -999,7 +999,7 @@ start_fadump()
start_dump() { - if [ $DEFAULT_DUMP_MODE == "fadump" ]; then + if [[ $DEFAULT_DUMP_MODE == "fadump" ]]; then start_fadump else load_kdump @@ -1017,14 +1017,14 @@ check_failure_action_config() default_option=$(kdump_get_conf_val default) failure_action=$(kdump_get_conf_val failure_action)
- if [ -z "$failure_action" -a -z "$default_option" ]; then + if [[ -z "$failure_action" ]] && [[ -z "$default_option" ]]; then return 0 - elif [ -n "$failure_action" -a -n "$default_option" ]; then + elif [[ -n "$failure_action" ]] && [[ -n "$default_option" ]]; then derror "Cannot specify 'failure_action' and 'default' option together" return 1 fi
- if [ -n "$default_option" ]; then + if [[ -n "$default_option" ]]; then option="default" failure_action="$default_option" fi @@ -1044,7 +1044,7 @@ check_final_action_config() local final_action
final_action=$(kdump_get_conf_val final_action) - if [ -z "$final_action" ]; then + if [[ -z "$final_action" ]]; then return 0 else case "$final_action" in @@ -1061,13 +1061,13 @@ check_final_action_config() start() { check_dump_feasibility - if [ $? -ne 0 ]; then + if [[ $? -ne 0 ]]; then derror "Starting kdump: [FAILED]" return 1 fi
check_config - if [ $? -ne 0 ]; then + if [[ $? -ne 0 ]]; then derror "Starting kdump: [FAILED]" return 1 fi @@ -1077,13 +1077,13 @@ start() fi
save_raw - if [ $? -ne 0 ]; then + if [[ $? -ne 0 ]]; then derror "Starting kdump: [FAILED]" return 1 fi
check_current_status - if [ $? == 0 ]; then + if [[ $? == 0 ]]; then dwarn "Kdump already running: [WARNING]" return 0 fi @@ -1096,13 +1096,13 @@ start() fi
check_rebuild - if [ $? != 0 ]; then + if [[ $? != 0 ]]; then derror "Starting kdump: [FAILED]" return 1 fi
start_dump - if [ $? != 0 ]; then + if [[ $? != 0 ]]; then derror "Starting kdump: [FAILED]" return 1 fi @@ -1113,18 +1113,18 @@ start() reload() { check_current_status - if [ $? -ne 0 ]; then + if [[ $? -ne 0 ]]; then dwarn "Kdump was not running: [WARNING]" fi
- if [ $DEFAULT_DUMP_MODE == "fadump" ]; then + if [[ $DEFAULT_DUMP_MODE == "fadump" ]]; then reload_fadump return $? else stop_kdump fi
- if [ $? -ne 0 ]; then + if [[ $? -ne 0 ]]; then derror "Stopping kdump: [FAILED]" return 1 fi @@ -1132,13 +1132,13 @@ reload() dinfo "Stopping kdump: [OK]"
setup_initrd - if [ $? -ne 0 ]; then + if [[ $? -ne 0 ]]; then derror "Starting kdump: [FAILED]" return 1 fi
start_dump - if [ $? -ne 0 ]; then + if [[ $? -ne 0 ]]; then derror "Starting kdump: [FAILED]" return 1 fi @@ -1166,7 +1166,7 @@ stop_kdump() $KEXEC -p -u fi
- if [ $? != 0 ]; then + if [[ $? != 0 ]]; then derror "kexec: failed to unload kdump kernel" return 1 fi @@ -1178,7 +1178,7 @@ stop_kdump() reload_fadump() { echo 1 > $FADUMP_REGISTER_SYS_NODE - if [ $? == 0 ]; then + if [[ $? == 0 ]]; then dinfo "fadump: re-registered successfully" return 0 else @@ -1186,7 +1186,7 @@ reload_fadump() # support is not enabled. Try stop/start from userspace # to handle such scenario. stop_fadump - if [ $? == 0 ]; then + if [[ $? == 0 ]]; then start_fadump return $? fi @@ -1197,13 +1197,13 @@ reload_fadump()
stop() { - if [ $DEFAULT_DUMP_MODE == "fadump" ]; then + if [[ $DEFAULT_DUMP_MODE == "fadump" ]]; then stop_fadump else stop_kdump fi
- if [ $? != 0 ]; then + if [[ $? != 0 ]]; then derror "Stopping kdump: [FAILED]" return 1 fi @@ -1214,7 +1214,7 @@ stop()
rebuild() { check_config - if [ $? -ne 0 ]; then + if [[ $? -ne 0 ]]; then return 1 fi
@@ -1225,7 +1225,7 @@ rebuild() { fi
setup_initrd - if [ $? -ne 0 ]; then + if [[ $? -ne 0 ]]; then return 1 fi
@@ -1242,7 +1242,7 @@ do_estimate() { local size_mb=$(( 1024 * 1024 ))
setup_initrd - if [ ! -f "$TARGET_INITRD" ]; then + if [[ ! -f "$TARGET_INITRD" ]]; then derror "kdumpctl estimate: kdump initramfs is not built yet." exit 1 fi @@ -1359,7 +1359,7 @@ reset_crashkernel() { fi }
-if [ ! -f "$KDUMP_CONFIG_FILE" ]; then +if [[ ! -f "$KDUMP_CONFIG_FILE" ]]; then derror "Error: No kdump config file found!" exit 1 fi @@ -1371,7 +1371,7 @@ main ()
case "$1" in start) - if [ -s /proc/vmcore ]; then + if [[ -s /proc/vmcore ]]; then save_core reboot else diff --git a/mkdumprd b/mkdumprd index af36e003..f91315fe 100644 --- a/mkdumprd +++ b/mkdumprd @@ -6,7 +6,7 @@ # Written by Cong Wang amwang@redhat.com #
-if [ -f /etc/sysconfig/kdump ]; then +if [[ -f /etc/sysconfig/kdump ]]; then . /etc/sysconfig/kdump fi
@@ -18,7 +18,7 @@ export IN_KDUMP=1
#initiate the kdump logger dlog_init -if [ $? -ne 0 ]; then +if [[ $? -ne 0 ]]; then echo "failed to initiate the kdump logger." exit 1 fi @@ -73,7 +73,7 @@ to_mount() { else # for non-nfs _target converting to use udev persistent name _pdev="$(kdump_get_persistent_dev $_target)" - if [ -z "$_pdev" ]; then + if [[ -z "$_pdev" ]]; then return 1 fi fi @@ -116,14 +116,14 @@ mkdir_save_path_ssh() _opt=(-i "$SSH_KEY_LOCATION" -o BatchMode=yes -o StrictHostKeyChecking=yes) ssh -qn "${_opt[@]}" $1 mkdir -p $SAVE_PATH 2>&1 > /dev/null _ret=$? - if [ $_ret -ne 0 ]; then + if [[ $_ret -ne 0 ]]; then perror_exit "mkdir failed on $1:$SAVE_PATH" fi
#check whether user has write permission on $1:$SAVE_PATH _dir=$(ssh -qn "${_opt[@]}" $1 mktemp -dqp $SAVE_PATH 2>/dev/null) _ret=$? - if [ $_ret -ne 0 ]; then + if [[ $_ret -ne 0 ]]; then perror_exit "Could not create temporary directory on $1:$SAVE_PATH. Make sure user has write permission on destination" fi ssh -qn "${_opt[@]}" $1 rmdir $_dir @@ -164,11 +164,11 @@ check_size() { return esac
- if [ $? -ne 0 ]; then + if [[ $? -ne 0 ]]; then perror_exit "Check dump target size failed" fi
- if [ $avail -lt $memtotal ]; then + if [[ $avail -lt $memtotal ]]; then dwarn "Warning: There might not be enough space to save a vmcore." dwarn " The size of $2 should be greater than $memtotal kilo bytes." fi @@ -178,7 +178,7 @@ check_save_path_fs() { local _path=$1
- if [ ! -d $_path ]; then + if [[ ! -d $_path ]]; then perror_exit "Dump path $_path does not exist." fi } @@ -190,7 +190,7 @@ mount_failure() local _fstype=$3 local msg="Failed to mount $_target"
- if [ -n "$_mnt" ]; then + if [[ -n "$_mnt" ]]; then msg="$msg on $_mnt" fi
@@ -210,11 +210,11 @@ check_user_configured_target() local _opt=$(get_mntopt_from_target $_target) local _fstype=$(get_fs_type_from_target $_target)
- if [ -n "$_fstype" ]; then + if [[ -n "$_fstype" ]]; then # In case of nfs4, nfs should be used instead, nfs* options is deprecated in kdump.conf [[ $_fstype = "nfs"* ]] && _fstype=nfs
- if [ -n "$_cfg_fs_type" ] && [ "$_fstype" != "$_cfg_fs_type" ]; then + if [[ -n "$_cfg_fs_type" ]] && [[ "$_fstype" != "$_cfg_fs_type" ]]; then perror_exit ""$_target" have a wrong type config "$_cfg_fs_type", expected "$_fstype"" fi else @@ -224,11 +224,11 @@ check_user_configured_target()
# For noauto mount, mount it inplace with default value. # Else use the temporary target directory - if [ -n "$_mnt" ]; then + if [[ -n "$_mnt" ]]; then if ! is_mounted "$_mnt"; then if [[ $_opt = *",noauto"* ]]; then mount $_mnt - [ $? -ne 0 ] && mount_failure "$_target" "$_mnt" "$_fstype" + [[ $? -ne 0 ]] && mount_failure "$_target" "$_mnt" "$_fstype" _mounted=$_mnt else perror_exit "Dump target "$_target" is neither mounted nor configured as "noauto"" @@ -238,19 +238,19 @@ check_user_configured_target() _mnt=$MKDUMPRD_TMPMNT mkdir -p $_mnt mount $_target $_mnt -t $_fstype -o defaults - [ $? -ne 0 ] && mount_failure "$_target" "" "$_fstype" + [[ $? -ne 0 ]] && mount_failure "$_target" "" "$_fstype" _mounted=$_mnt fi
# For user configured target, use $SAVE_PATH as the dump path within the target - if [ ! -d "$_mnt/$SAVE_PATH" ]; then + if [[ ! -d "$_mnt/$SAVE_PATH" ]]; then perror_exit "Dump path "$_mnt/$SAVE_PATH" does not exist in dump target "$_target"" fi
check_size fs "$_target"
# Unmount it early, if function is interrupted and didn't reach here, the shell trap will clear it up anyway - if [ -n "$_mounted" ]; then + if [[ -n "$_mounted" ]]; then umount -f -- $_mounted fi } @@ -260,7 +260,7 @@ verify_core_collector() { local _cmd="${1%% *}" local _params="${1#* }"
- if [ "$_cmd" != "makedumpfile" ]; then + if [[ "$_cmd" != "makedumpfile" ]]; then if is_raw_dump_target; then dwarn "Warning: specifying a non-makedumpfile core collector, you will have to recover the vmcore manually." fi @@ -284,7 +284,7 @@ verify_core_collector() { add_mount() { local _mnt=$(to_mount $@)
- if [ $? -ne 0 ]; then + if [[ $? -ne 0 ]]; then exit 1 fi
@@ -316,7 +316,7 @@ for_each_block_target() local dev majmin
for dev in $(get_kdump_targets); do - [ -b "$dev" ] || continue + [[ -b "$dev" ]] || continue majmin=$(get_maj_min $dev) check_block_and_slaves $1 $majmin && return 1 done @@ -331,10 +331,10 @@ is_unresettable() local path="/sys/$(udevadm info --query=all --path=/sys/dev/block/$1 | awk '/^P:/ {print $2}' | sed -e 's/(cciss[0-9]+/).*/\1/g' -e 's//block/.*$//')/resettable" local resettable=1
- if [ -f "$path" ] + if [[ -f "$path" ]] then resettable="$(<"$path")" - [ $resettable -eq 0 -a "$OVERRIDE_RESETTABLE" -eq 0 ] && { + [[ $resettable -eq 0 ]] && [[ "$OVERRIDE_RESETTABLE" -eq 0 ]] && { local device=$(udevadm info --query=all --path=/sys/dev/block/$1 | awk -F= '/DEVNAME/{print $2}') derror "Error: Can not save vmcore because device $device is unresettable" return 0 @@ -356,7 +356,7 @@ check_resettable() for_each_block_target is_unresettable _ret=$?
- [ $_ret -eq 0 ] && return + [[ $_ret -eq 0 ]] && return
return 1 } @@ -382,7 +382,7 @@ fi
# firstly get right SSH_KEY_LOCATION keyfile=$(kdump_get_conf_val sshkey) -if [ -f "$keyfile" ]; then +if [[ -f "$keyfile" ]]; then # canonicalize the path SSH_KEY_LOCATION=$(/usr/bin/readlink -m $keyfile) fi @@ -404,7 +404,7 @@ do perror_exit "Bad raw disk $config_val" } _praw=$(persistent_policy="by-id" kdump_get_persistent_dev $config_val) - if [ -z "$_praw" ]; then + if [[ -z "$_praw" ]]; then exit 1 fi add_dracut_arg "--device" "$_praw" @@ -435,7 +435,7 @@ done <<< "$(kdump_read_conf)"
handle_default_dump_target
-if [ -n "$extra_modules" ] +if [[ -n "$extra_modules" ]] then add_dracut_arg "--add-drivers" "$extra_modules" fi diff --git a/mkfadumprd b/mkfadumprd index 5c879338..ca9f362c 100644 --- a/mkfadumprd +++ b/mkfadumprd @@ -2,7 +2,7 @@ # Generate an initramfs image that isolates dump capture capability within # the default initramfs using zz-fadumpinit dracut module.
-if [ -f /etc/sysconfig/kdump ]; then +if [[ -f /etc/sysconfig/kdump ]]; then . /etc/sysconfig/kdump fi
Fixed quoting issues found by shellcheck, no feature change. This should fix many errors when there is space in any shell variables, eg. dump target's name/path/id.
False positives are marked with "# shellcheck disable=SCXXXX", for example, args are expected to split so it should not be quoted.
And replaced some `cut -d ' ' -fX` with `awk '{print $X}'` since cut is fragile, and doesn't work well with any quoted strings that have redundant space.
Following quoting related issues are fixed (check the link for example code and what could go wrong):
https://github.com/koalaman/shellcheck/wiki/SC2046 https://github.com/koalaman/shellcheck/wiki/SC2053 https://github.com/koalaman/shellcheck/wiki/SC2068 https://github.com/koalaman/shellcheck/wiki/SC2086 https://github.com/koalaman/shellcheck/wiki/SC2206
Signed-off-by: Kairui Song kasong@redhat.com --- dracut-early-kdump-module-setup.sh | 2 +- dracut-module-setup.sh | 261 +++++++++++++++-------------- kdumpctl | 104 ++++++------ mkdumprd | 69 ++++---- 4 files changed, 220 insertions(+), 216 deletions(-)
diff --git a/dracut-early-kdump-module-setup.sh b/dracut-early-kdump-module-setup.sh index 00546e01..83e067c8 100755 --- a/dracut-early-kdump-module-setup.sh +++ b/dracut-early-kdump-module-setup.sh @@ -25,7 +25,7 @@ prepare_kernel_initrd() { prepare_kdump_bootinfo
# $kernel is a variable from dracut - if [[ "$KDUMP_KERNELVER" != $kernel ]]; then + if [[ "$KDUMP_KERNELVER" != "$kernel" ]]; then dwarn "Using kernel version '$KDUMP_KERNELVER' for early kdump," \ "but the initramfs is generated for kernel version '$kernel'" fi diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index 1e875016..600bdc51 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -53,7 +53,7 @@ depends() { _dep="$_dep network" fi
- echo $_dep + echo "$_dep" }
kdump_is_bridge() { @@ -65,7 +65,7 @@ kdump_is_bond() { }
kdump_is_team() { - [[ -f /usr/bin/teamnl ]] && teamnl $1 ports &> /dev/null + [[ -f /usr/bin/teamnl ]] && teamnl "$1" ports &> /dev/null }
kdump_is_vlan() { @@ -77,9 +77,9 @@ source_ifcfg_file() { local ifcfg_file
dwarning "Network Scripts are deprecated. You are encouraged to set up network by NetworkManager." - ifcfg_file=$(get_ifcfg_filename $1) + ifcfg_file=$(get_ifcfg_filename "$1") if [[ -f "${ifcfg_file}" ]]; then - . ${ifcfg_file} + . "${ifcfg_file}" else dwarning "The ifcfg file of $1 is not found!" fi @@ -93,7 +93,8 @@ kdump_setup_dns() { local _dnsfile=${initdir}/etc/cmdline.d/42dns.conf
_tmp=$(get_nmcli_value_by_field "$_nm_show_cmd" "IP4.DNS") - array=(${_tmp//|/ }) + # shellcheck disable=SC2206 + array=( ${_tmp//|/ } ) if [[ ${array[*]} ]]; then for _dns in "${array[@]}" do @@ -108,10 +109,10 @@ kdump_setup_dns() {
while read -r content; do - _nameserver=$(echo $content | grep ^nameserver) + _nameserver=$(echo "$content" | grep ^nameserver) [[ -z "$_nameserver" ]] && continue
- _dns=$(echo $_nameserver | cut -d' ' -f2) + _dns=$(echo "$_nameserver" | awk '{print $2}') [[ -z "$_dns" ]] && continue
if [[ ! -f $_dnsfile ]] || ! grep -q "$_dns" "$_dnsfile" ; then @@ -237,14 +238,14 @@ kdump_static_ip() { local _netdev="$1" _srcaddr="$2" kdumpnic="$3" _ipv6_flag local _netmask _gateway _ipaddr _target _nexthop _prefix
- _ipaddr=$(ip addr show dev $_netdev permanent | awk "/ $_srcaddr/.* /{print $2}") + _ipaddr=$(ip addr show dev "$_netdev" permanent | awk "/ $_srcaddr/.* /{print $2}")
- if is_ipv6_address $_srcaddr; then + if is_ipv6_address "$_srcaddr"; then _ipv6_flag="-6" fi
if [[ -n "$_ipaddr" ]]; then - _gateway=$(ip $_ipv6_flag route list dev $_netdev | \ + _gateway=$(ip $_ipv6_flag route list dev "$_netdev" | \ awk '/^default /{print $3}' | head -n 1)
if [[ "x" != "x"$_ipv6_flag ]]; then @@ -266,23 +267,23 @@ kdump_static_ip() { /sbin/ip $_ipv6_flag route show | grep -v default |\ grep ".*via.* $_netdev " | grep -v "^[[:space:]]*nexthop" |\ while read -r _route; do - _target=$(echo $_route | cut -d ' ' -f1) - _nexthop=$(echo $_route | cut -d ' ' -f3) + _target=$(echo "$_route" | awk '{print $1}') + _nexthop=$(echo "$_route" | awk '{print $3}') if [[ "x" != "x"$_ipv6_flag ]]; then _target="[$_target]" _nexthop="[$_nexthop]" fi echo "rd.route=$_target:$_nexthop:$kdumpnic" - done >> ${initdir}/etc/cmdline.d/45route-static.conf + done >> "${initdir}/etc/cmdline.d/45route-static.conf"
- kdump_handle_mulitpath_route $_netdev $_srcaddr $kdumpnic + kdump_handle_mulitpath_route "$_netdev" "$_srcaddr" "$kdumpnic" }
kdump_handle_mulitpath_route() { local _netdev="$1" _srcaddr="$2" kdumpnic="$3" _ipv6_flag local _target _nexthop _route _weight _max_weight _rule
- if is_ipv6_address $_srcaddr; then + if is_ipv6_address "$_srcaddr"; then _ipv6_flag="-6" fi
@@ -308,20 +309,20 @@ kdump_handle_mulitpath_route() { _target=$(echo "$_route" | cut -d ' ' -f1) _rule="" _max_weight=0 _weight=0 fi - done >> ${initdir}/etc/cmdline.d/45route-static.conf\ + done >> "${initdir}/etc/cmdline.d/45route-static.conf"\ <<< "$(/sbin/ip $_ipv6_flag route show)"
- [[ -n $_rule ]] && echo $_rule >> ${initdir}/etc/cmdline.d/45route-static.conf + [[ -n $_rule ]] && echo "$_rule" >> "${initdir}/etc/cmdline.d/45route-static.conf" }
kdump_get_mac_addr() { - cat /sys/class/net/$1/address + cat "/sys/class/net/$1/address" }
#Bonding or team master modifies the mac address #of its slaves, we should use perm address kdump_get_perm_addr() { - local addr=$(ethtool -P $1 | sed -e 's/Permanent address: //') + local addr=$(ethtool -P "$1" | sed -e 's/Permanent address: //') if [[ -z "$addr" ]] || [[ "$addr" = "00:00:00:00:00:00" ]] then derror "Can't get the permanent address of $1" @@ -366,9 +367,9 @@ kdump_setup_bridge() { elif kdump_is_vlan "$_dev"; then kdump_setup_vlan "$_dev" else - _mac=$(kdump_get_mac_addr $_dev) - _kdumpdev=$(kdump_setup_ifname $_dev) - echo -n " ifname=$_kdumpdev:$_mac" >> ${initdir}/etc/cmdline.d/41bridge.conf + _mac=$(kdump_get_mac_addr "$_dev") + _kdumpdev=$(kdump_setup_ifname "$_dev") + echo -n " ifname=$_kdumpdev:$_mac" >> "${initdir}/etc/cmdline.d/41bridge.conf" fi _brif+="$_kdumpdev," done @@ -382,10 +383,10 @@ kdump_setup_bond() { local _netdev="$1" local _nm_show_cmd="$2" local _dev _mac _slaves _kdumpdev _bondoptions - for _dev in $(cat /sys/class/net/$_netdev/bonding/slaves); do - _mac=$(kdump_get_perm_addr $_dev) - _kdumpdev=$(kdump_setup_ifname $_dev) - echo -n " ifname=$_kdumpdev:$_mac" >> ${initdir}/etc/cmdline.d/42bond.conf + for _dev in $(cat "/sys/class/net/$_netdev/bonding/slaves"); do + _mac=$(kdump_get_perm_addr "$_dev") + _kdumpdev=$(kdump_setup_ifname "$_dev") + echo -n " ifname=$_kdumpdev:$_mac" >> "${initdir}/etc/cmdline.d/42bond.conf" _slaves+="$_kdumpdev," done echo -n " bond=$_netdev:${_slaves%,}" >> "${initdir}/etc/cmdline.d/42bond.conf" @@ -394,8 +395,8 @@ kdump_setup_bond() {
if [[ -z "$_bondoptions" ]]; then dwarning "Failed to get bond configuration via nmlci output. Now try sourcing ifcfg script." - source_ifcfg_file $_netdev - _bondoptions="$(echo $BONDING_OPTS | xargs echo | tr " " ",")" + source_ifcfg_file "$_netdev" + _bondoptions="$(echo "$BONDING_OPTS" | xargs echo | tr " " ",")" fi
if [[ -z "$_bondoptions" ]]; then @@ -403,36 +404,36 @@ kdump_setup_bond() { exit 1 fi
- echo ":$_bondoptions" >> ${initdir}/etc/cmdline.d/42bond.conf + echo ":$_bondoptions" >> "${initdir}/etc/cmdline.d/42bond.conf" }
kdump_setup_team() { local _netdev=$1 local _dev _mac _slaves _kdumpdev - for _dev in $(teamnl $_netdev ports | awk -F':' '{print $2}'); do - _mac=$(kdump_get_perm_addr $_dev) - _kdumpdev=$(kdump_setup_ifname $_dev) - echo -n " ifname=$_kdumpdev:$_mac" >> ${initdir}/etc/cmdline.d/44team.conf + for _dev in $(teamnl "$_netdev" ports | awk -F':' '{print $2}'); do + _mac=$(kdump_get_perm_addr "$_dev") + _kdumpdev=$(kdump_setup_ifname "$_dev") + echo -n " ifname=$_kdumpdev:$_mac" >> "${initdir}/etc/cmdline.d/44team.conf" _slaves+="$_kdumpdev," done echo " team=$_netdev:${_slaves%,}" >> "${initdir}/etc/cmdline.d/44team.conf" #Buggy version teamdctl outputs to stderr! #Try to use the latest version of teamd. - teamdctl "$_netdev" config dump > ${initdir}/tmp/$$-$_netdev.conf + teamdctl "$_netdev" config dump > "${initdir}/tmp/$$-$_netdev.conf" if [[ $? -ne 0 ]] then derror "teamdctl failed." exit 1 fi inst_dir /etc/teamd - inst_simple ${initdir}/tmp/$$-$_netdev.conf "/etc/teamd/$_netdev.conf" - rm -f ${initdir}/tmp/$$-$_netdev.conf + inst_simple "${initdir}/tmp/$$-$_netdev.conf" "/etc/teamd/$_netdev.conf" + rm -f "${initdir}/tmp/$$-$_netdev.conf" }
kdump_setup_vlan() { local _netdev=$1 local _phydev="$(awk '/^Device:/{print $2}' /proc/net/vlan/"$_netdev")" - local _netmac="$(kdump_get_mac_addr $_phydev)" + local _netmac="$(kdump_get_mac_addr "$_phydev")" local _kdumpdev
#Just support vlan over bond and team @@ -444,10 +445,10 @@ kdump_setup_vlan() { if [[ $? != 0 ]]; then exit 1 fi - echo " vlan=$(kdump_setup_ifname $_netdev):$_phydev" > ${initdir}/etc/cmdline.d/43vlan.conf + echo " vlan=$(kdump_setup_ifname "$_netdev"):$_phydev" > "${initdir}/etc/cmdline.d/43vlan.conf" else - _kdumpdev="$(kdump_setup_ifname $_phydev)" - echo " vlan=$(kdump_setup_ifname $_netdev):$_kdumpdev ifname=$_kdumpdev:$_netmac" > ${initdir}/etc/cmdline.d/43vlan.conf + _kdumpdev="$(kdump_setup_ifname "$_phydev")" + echo " vlan=$(kdump_setup_ifname "$_netdev"):$_kdumpdev ifname=$_kdumpdev:$_netmac" > "${initdir}/etc/cmdline.d/43vlan.conf" fi }
@@ -464,7 +465,7 @@ find_online_znet_device() { for d in $NETWORK_DEVICES do [[ ! -f "$d/online" ]] && continue - read -r ONLINE < $d/online + read -r ONLINE < "$d/online" if [[ $ONLINE -ne 1 ]]; then continue fi @@ -472,10 +473,10 @@ find_online_znet_device() { # device is online) if [[ -f $d/if_name ]] then - read -r ifname < $d/if_name + read -r ifname < "$d/if_name" elif [[ -d $d/net ]] then - ifname=$(ls $d/net/) + ifname=$(ls "$d/net/") fi [[ -n "$ifname" ]] && break done @@ -499,7 +500,7 @@ kdump_setup_znet() {
if [[ -z "$NETTYPE" || -z "$SUBCHANNELS" || -z "$_options" ]]; then dwarning "Failed to get znet configuration via nmlci output. Now try sourcing ifcfg script." - source_ifcfg_file $_netdev + source_ifcfg_file "$_netdev" for i in $OPTIONS; do _options=${_options},$i done @@ -509,17 +510,17 @@ kdump_setup_znet() { exit 1 fi
- echo rd.znet=${NETTYPE},${SUBCHANNELS},${_options} rd.znet_ifname=$_netdev:${SUBCHANNELS} > ${initdir}/etc/cmdline.d/30znet.conf + echo "rd.znet=${NETTYPE},${SUBCHANNELS},${_options} rd.znet_ifname=$_netdev:${SUBCHANNELS}" > "${initdir}/etc/cmdline.d/30znet.conf" }
kdump_get_ip_route() { - local _route=$(/sbin/ip -o route get to $1 2>&1) + local _route=$(/sbin/ip -o route get to "$1" 2>&1) if [[ $? != 0 ]]; then derror "Bad kdump network destination: $1" exit 1 fi - echo $_route + echo "$_route" }
kdump_get_ip_route_field() @@ -529,15 +530,15 @@ kdump_get_ip_route_field()
kdump_get_remote_ip() { - local _remote=$(get_remote_host $1) _remote_temp - if is_hostname $_remote; then - _remote_temp=$(getent ahosts $_remote | grep -v : | head -n 1) + local _remote=$(get_remote_host "$1") _remote_temp + if is_hostname "$_remote"; then + _remote_temp=$(getent ahosts "$_remote" | grep -v : | head -n 1) if [[ -z "$_remote_temp" ]]; then - _remote_temp=$(getent ahosts $_remote | head -n 1) + _remote_temp=$(getent ahosts "$_remote" | head -n 1) fi - _remote=$(echo $_remote_temp | cut -d' ' -f1) + _remote=$(echo "$_remote_temp" | awk '{print $1}') fi - echo $_remote + echo "$_remote" }
# Setup dracut to bring up network interface that enable @@ -548,13 +549,13 @@ kdump_install_net() { local _static _proto _ip_conf _ip_opts _ifname_opts local _znet_netdev _nm_show_cmd_znet
- _destaddr=$(kdump_get_remote_ip $1) - _route=$(kdump_get_ip_route $_destaddr) + _destaddr=$(kdump_get_remote_ip "$1") + _route=$(kdump_get_ip_route "$_destaddr") _srcaddr=$(kdump_get_ip_route_field "$_route" "src") _netdev=$(kdump_get_ip_route_field "$_route" "dev") _nm_show_cmd=$(get_nmcli_connection_show_cmd_by_ifname "$_netdev") - _netmac=$(kdump_get_mac_addr $_netdev) - kdumpnic=$(kdump_setup_ifname $_netdev) + _netmac=$(kdump_get_mac_addr "$_netdev") + kdumpnic=$(kdump_setup_ifname "$_netdev")
_znet_netdev=$(find_online_znet_device) if [[ -n "$_znet_netdev" ]]; then @@ -566,10 +567,10 @@ kdump_install_net() { fi fi
- _static=$(kdump_static_ip $_netdev $_srcaddr $kdumpnic) + _static=$(kdump_static_ip "$_netdev" "$_srcaddr" "$kdumpnic") if [[ -n "$_static" ]]; then _proto=none - elif is_ipv6_address $_srcaddr; then + elif is_ipv6_address "$_srcaddr"; then _proto=auto6 else _proto=dhcp @@ -582,9 +583,9 @@ kdump_install_net() { # so we have to avoid adding duplicates # We should also check /proc/cmdline for existing ip=xx arg. # For example, iscsi boot will specify ip=xxx arg in cmdline. - if [[ ! -f $_ip_conf ]] || ! grep -q $_ip_opts $_ip_conf &&\ + if [[ ! -f $_ip_conf ]] || ! grep -q "$_ip_opts" "$_ip_conf" &&\ ! grep -q "ip=[^[:space:]]*$_netdev" /proc/cmdline; then - echo "$_ip_opts" >> $_ip_conf + echo "$_ip_opts" >> "$_ip_conf" fi
if kdump_is_bridge "$_netdev"; then @@ -600,14 +601,14 @@ kdump_install_net() { kdump_setup_vlan "$_netdev" else _ifname_opts=" ifname=$kdumpnic:$_netmac" - echo "$_ifname_opts" >> $_ip_conf + echo "$_ifname_opts" >> "$_ip_conf" fi
kdump_setup_dns "$_netdev" "$_nm_show_cmd"
if [[ ! -f ${initdir}/etc/cmdline.d/50neednet.conf ]]; then # network-manager module needs this parameter - echo "rd.neednet" >> ${initdir}/etc/cmdline.d/50neednet.conf + echo "rd.neednet" >> "${initdir}/etc/cmdline.d/50neednet.conf" fi
# Save netdev used for kdump as cmdline @@ -619,8 +620,8 @@ kdump_install_net() { # gateway. if [[ ! -f ${initdir}/etc/cmdline.d/60kdumpnic.conf ]] && [[ ! -f ${initdir}/etc/cmdline.d/70bootdev.conf ]]; then - echo "kdumpnic=$kdumpnic" > ${initdir}/etc/cmdline.d/60kdumpnic.conf - echo "bootdev=$kdumpnic" > ${initdir}/etc/cmdline.d/70bootdev.conf + echo "kdumpnic=$kdumpnic" > "${initdir}/etc/cmdline.d/60kdumpnic.conf" + echo "bootdev=$kdumpnic" > "${initdir}/etc/cmdline.d/70bootdev.conf" fi }
@@ -629,7 +630,7 @@ kdump_install_pre_post_conf() { if [[ -d /etc/kdump/pre.d ]]; then for file in /etc/kdump/pre.d/*; do if [[ -x "$file" ]]; then - dracut_install $file + dracut_install "$file" elif [[ $file != "/etc/kdump/pre.d/*" ]]; then echo "$file is not executable" fi @@ -639,7 +640,7 @@ kdump_install_pre_post_conf() { if [[ -d /etc/kdump/post.d ]]; then for file in /etc/kdump/post.d/*; do if [[ -x "$file" ]]; then - dracut_install $file + dracut_install "$file" elif [[ $file != "/etc/kdump/post.d/*" ]]; then echo "$file is not executable" fi @@ -654,19 +655,19 @@ default_dump_target_install_conf()
is_user_configured_dump_target && return
- _save_path=$(get_bind_mount_source $(get_save_path)) - _target=$(get_target_from_path $_save_path) - _mntpoint=$(get_mntpoint_from_target $_target) + _save_path=$(get_bind_mount_source "$(get_save_path)") + _target=$(get_target_from_path "$_save_path") + _mntpoint=$(get_mntpoint_from_target "$_target")
- _fstype=$(get_fs_type_from_target $_target) - if is_fs_type_nfs $_fstype; then + _fstype=$(get_fs_type_from_target "$_target") + if is_fs_type_nfs "$_fstype"; then kdump_install_net "$_target" _fstype="nfs" else - _target=$(kdump_get_persistent_dev $_target) + _target=$(kdump_get_persistent_dev "$_target") fi
- echo "$_fstype $_target" >> ${initdir}/tmp/$$-kdump.conf + echo "$_fstype $_target" >> "${initdir}/tmp/$$-kdump.conf"
# don't touch the path under root mount if [[ "$_mntpoint" != "/" ]]; then @@ -674,8 +675,8 @@ default_dump_target_install_conf() fi
#erase the old path line, then insert the parsed path - sed -i "/^path/d" ${initdir}/tmp/$$-kdump.conf - echo "path $_save_path" >> ${initdir}/tmp/$$-kdump.conf + sed -i "/^path/d" "${initdir}/tmp/$$-kdump.conf" + echo "path $_save_path" >> "${initdir}/tmp/$$-kdump.conf" }
#install kdump.conf and what user specifies in kdump.conf @@ -689,12 +690,12 @@ kdump_install_conf() { # remove inline comments after the end of a directive. case "$_opt" in raw) - _pdev=$(persistent_policy="by-id" kdump_get_persistent_dev $_val) - sed -i -e "s#^${_opt}[[:space:]]+$_val#$_opt $_pdev#" ${initdir}/tmp/$$-kdump.conf + _pdev=$(persistent_policy="by-id" kdump_get_persistent_dev "$_val") + sed -i -e "s#^${_opt}[[:space:]]+$_val#$_opt $_pdev#" "${initdir}/tmp/$$-kdump.conf" ;; ext[234]|xfs|btrfs|minix) - _pdev=$(kdump_get_persistent_dev $_val) - sed -i -e "s#^${_opt}[[:space:]]+$_val#$_opt $_pdev#" ${initdir}/tmp/$$-kdump.conf + _pdev=$(kdump_get_persistent_dev "$_val") + sed -i -e "s#^${_opt}[[:space:]]+$_val#$_opt $_pdev#" "${initdir}/tmp/$$-kdump.conf" ;; ssh|nfs) kdump_install_net "$_val" @@ -705,7 +706,7 @@ kdump_install_conf() { fi ;; kdump_pre|kdump_post|extra_bins) - dracut_install $_val + dracut_install "$_val" ;; core_collector) dracut_install "${_val%%[[:blank:]]*}" @@ -719,7 +720,7 @@ kdump_install_conf() {
kdump_configure_fence_kdump "${initdir}/tmp/$$-kdump.conf" inst "${initdir}/tmp/$$-kdump.conf" "/etc/kdump.conf" - rm -f ${initdir}/tmp/$$-kdump.conf + rm -f "${initdir}/tmp/$$-kdump.conf" }
# Default sysctl parameters should suffice for kdump kernel. @@ -741,9 +742,9 @@ kdump_iscsi_get_rec_val() { # The open-iscsi 742 release changed to using flat files in # /var/lib/iscsi.
- result=$(/sbin/iscsiadm --show -m session -r ${1} | grep "^${2} = ") + result=$(/sbin/iscsiadm --show -m session -r "$1" | grep "^${2} = ") result=${result##* = } - echo $result + echo "$result" }
kdump_get_iscsi_initiator() { @@ -769,7 +770,7 @@ kdump_get_iscsi_initiator() {
# Figure out iBFT session according to session type is_ibft() { - [[ "$(kdump_iscsi_get_rec_val $1 "node.discovery_type")" = fw ]] + [[ "$(kdump_iscsi_get_rec_val "$1" "node.discovery_type")" = fw ]] }
kdump_setup_iscsi_device() { @@ -785,32 +786,32 @@ kdump_setup_iscsi_device() {
# Check once before getting explicit values, so we can bail out early, # e.g. in case of pure-hardware(all-offload) iscsi. - if ! /sbin/iscsiadm -m session -r ${path} &>/dev/null ; then + if ! /sbin/iscsiadm -m session -r "$path" &>/dev/null ; then return 1 fi
- if is_ibft ${path}; then + if is_ibft "$path"; then return fi
# Remove software iscsi cmdline generated by 95iscsi, # and let kdump regenerate here. - rm -f ${initdir}/etc/cmdline.d/95iscsi.conf + rm -f "${initdir}/etc/cmdline.d/95iscsi.conf"
- tgt_name=$(kdump_iscsi_get_rec_val ${path} "node.name") - tgt_ipaddr=$(kdump_iscsi_get_rec_val ${path} "node.conn[0].address") + tgt_name=$(kdump_iscsi_get_rec_val "$path" "node.name") + tgt_ipaddr=$(kdump_iscsi_get_rec_val "$path" "node.conn[0].address")
# get and set username and password details - username=$(kdump_iscsi_get_rec_val ${path} "node.session.auth.username") + username=$(kdump_iscsi_get_rec_val "$path" "node.session.auth.username") [[ "$username" == "<empty>" ]] && username="" - password=$(kdump_iscsi_get_rec_val ${path} "node.session.auth.password") + password=$(kdump_iscsi_get_rec_val "$path" "node.session.auth.password") [[ "$password" == "<empty>" ]] && password="" - username_in=$(kdump_iscsi_get_rec_val ${path} "node.session.auth.username_in") + username_in=$(kdump_iscsi_get_rec_val "$path" "node.session.auth.username_in") [[ -n "$username" ]] && userpwd_str="$username:$password"
# get and set incoming username and password details [[ "$username_in" == "<empty>" ]] && username_in="" - password_in=$(kdump_iscsi_get_rec_val ${path} "node.session.auth.password_in") + password_in=$(kdump_iscsi_get_rec_val "$path" "node.session.auth.password_in") [[ "$password_in" == "<empty>" ]] && password_in=""
[[ -n "$username_in" ]] && userpwd_in_str=":$username_in:$password_in" @@ -821,16 +822,16 @@ kdump_setup_iscsi_device() { # FIXME: Do we need to parse and set other parameters like protocol, port # iscsi_iface_name, netdev_name, LUN etc.
- if is_ipv6_address $tgt_ipaddr; then + if is_ipv6_address "$tgt_ipaddr"; then tgt_ipaddr="[$tgt_ipaddr]" fi netroot_str="netroot=iscsi:${userpwd_str}${userpwd_in_str}@$tgt_ipaddr::::$tgt_name"
- [[ -f $netroot_conf ]] || touch $netroot_conf + [[ -f $netroot_conf ]] || touch "$netroot_conf"
# If netroot target does not exist already, append. - if ! grep -q $netroot_str $netroot_conf; then - echo $netroot_str >> $netroot_conf + if ! grep -q "$netroot_str" "$netroot_conf"; then + echo "$netroot_str" >> "$netroot_conf" dinfo "Appended $netroot_str to $netroot_conf" fi
@@ -839,9 +840,9 @@ kdump_setup_iscsi_device() { [[ $? -ne "0" ]] && derror "Failed to get initiator name" && return 1
# If initiator details do not exist already, append. - if ! grep -q "$initiator_str" $netroot_conf; then - echo "$initiator_str" >> $netroot_conf - dinfo "Appended "$initiator_str" to $netroot_conf" + if ! grep -q "$initiator_str" "$netroot_conf"; then + echo "$initiator_str" >> "$netroot_conf" + dinfo "Appended $initiator_str to $netroot_conf" fi }
@@ -876,13 +877,13 @@ get_alias() { for ip in $ips do # in /etc/hosts, alias can come at the 2nd column - entries=$(grep $ip /etc/hosts | awk '{ $1=""; print $0 }') + entries=$(grep "$ip" /etc/hosts | awk '{ $1=""; print $0 }') if [[ $? -eq 0 ]]; then alias_set="$alias_set $entries" fi done
- echo $alias_set + echo "$alias_set" }
is_localhost() { @@ -913,23 +914,23 @@ get_pcs_fence_kdump_nodes() { # we need to convert each to node1, node2 ... nodeX in each iteration for node in ${nodelist}; do # convert $node from 'uname="nodeX"' to 'nodeX' - eval $node - nodename=$uname + eval "$node" + nodename="$uname" # Skip its own node name - if is_localhost $nodename; then + if is_localhost "$nodename"; then continue fi nodes="$nodes $nodename" done
- echo $nodes + echo "$nodes" }
# retrieves fence_kdump args from config file get_pcs_fence_kdump_args() { if [[ -f $FENCE_KDUMP_CONFIG_FILE ]]; then - . $FENCE_KDUMP_CONFIG_FILE - echo $FENCE_KDUMP_OPTS + . "$FENCE_KDUMP_CONFIG_FILE" + echo "$FENCE_KDUMP_OPTS" fi }
@@ -940,12 +941,12 @@ get_generic_fence_kdump_nodes() { nodes=$(kdump_get_conf_val "fence_kdump_nodes") for node in ${nodes}; do # Skip its own node name - if is_localhost $node; then + if is_localhost "$node"; then continue fi filtered="$filtered $node" done - echo $filtered + echo "$filtered" }
# setup fence_kdump in cluster @@ -962,11 +963,11 @@ kdump_configure_fence_kdump () { nodes=$(get_pcs_fence_kdump_nodes)
# set appropriate options in kdump.conf - echo "fence_kdump_nodes $nodes" >> ${kdump_cfg_file} + echo "fence_kdump_nodes $nodes" >> "${kdump_cfg_file}"
args=$(get_pcs_fence_kdump_args) if [[ -n "$args" ]]; then - echo "fence_kdump_args $args" >> ${kdump_cfg_file} + echo "fence_kdump_args $args" >> "${kdump_cfg_file}" fi
else @@ -976,12 +977,12 @@ kdump_configure_fence_kdump () {
# setup network for each node for node in ${nodes}; do - kdump_install_net $node + kdump_install_net "$node" done
dracut_install /etc/hosts dracut_install /etc/nsswitch.conf - dracut_install $FENCE_KDUMP_SEND + dracut_install "$FENCE_KDUMP_SEND" }
# Install a random seed used to feed /dev/urandom @@ -991,32 +992,32 @@ kdump_install_random_seed() {
poolsize=$(</proc/sys/kernel/random/poolsize)
- if [[ ! -d ${initdir}/var/lib/ ]]; then - mkdir -p ${initdir}/var/lib/ + if [[ ! -d "${initdir}/var/lib/" ]]; then + mkdir -p "${initdir}/var/lib/" fi
- dd if=/dev/urandom of=${initdir}/var/lib/random-seed \ - bs=$poolsize count=1 2> /dev/null + dd if=/dev/urandom of="${initdir}/var/lib/random-seed" \ + bs="$poolsize" count=1 2> /dev/null }
kdump_install_systemd_conf() { # Kdump turns out to require longer default systemd mount timeout # than 1st kernel(90s by default), we use default 300s for kdump. - grep -r "^[[:space:]]*DefaultTimeoutStartSec=" ${initdir}/etc/systemd/system.conf* &>/dev/null + grep -r "^[[:space:]]*DefaultTimeoutStartSec=" "${initdir}/etc/systemd/system.conf"* &>/dev/null if [[ $? -ne 0 ]]; then - mkdir -p ${initdir}/etc/systemd/system.conf.d - echo "[Manager]" > ${initdir}/etc/systemd/system.conf.d/kdump.conf - echo "DefaultTimeoutStartSec=300s" >> ${initdir}/etc/systemd/system.conf.d/kdump.conf + mkdir -p "${initdir}/etc/systemd/system.conf.d" + echo "[Manager]" > "${initdir}/etc/systemd/system.conf.d/kdump.conf" + echo "DefaultTimeoutStartSec=300s" >> "${initdir}/etc/systemd/system.conf.d/kdump.conf" fi
# Forward logs to console directly, and don't read Kmsg, this avoids # unneccessary memory consumption and make console output more useful. # Only do so for non fadump image. - mkdir -p ${initdir}/etc/systemd/journald.conf.d - echo "[Journal]" > ${initdir}/etc/systemd/journald.conf.d/kdump.conf - echo "Storage=volatile" >> ${initdir}/etc/systemd/journald.conf.d/kdump.conf - echo "ReadKMsg=no" >> ${initdir}/etc/systemd/journald.conf.d/kdump.conf - echo "ForwardToConsole=yes" >> ${initdir}/etc/systemd/journald.conf.d/kdump.conf + mkdir -p "${initdir}/etc/systemd/journald.conf.d" + echo "[Journal]" > "${initdir}/etc/systemd/journald.conf.d/kdump.conf" + echo "Storage=volatile" >> "${initdir}/etc/systemd/journald.conf.d/kdump.conf" + echo "ReadKMsg=no" >> "${initdir}/etc/systemd/journald.conf.d/kdump.conf" + echo "ForwardToConsole=yes" >> "${initdir}/etc/systemd/journald.conf.d/kdump.conf" }
install() { @@ -1029,7 +1030,7 @@ install() { fi dracut_install -o /etc/adjtime /etc/localtime inst "$moddir/monitor_dd_progress" "/kdumpscripts/monitor_dd_progress" - chmod +x ${initdir}/kdumpscripts/monitor_dd_progress + chmod +x "${initdir}/kdumpscripts/monitor_dd_progress" inst "/bin/dd" "/bin/dd" inst "/bin/tail" "/bin/tail" inst "/bin/date" "/bin/date" @@ -1075,7 +1076,7 @@ install() { # actually does nothing. sed -i -e \ 's/(^[[:space:]]*reserved_memory[[:space:]]*=)[[:space:]]*[[:digit:]]*/\1 1024/' \ - ${initdir}/etc/lvm/lvm.conf &>/dev/null + "${initdir}/etc/lvm/lvm.conf" &>/dev/null
# Save more memory by dropping switch root capability dracut_no_switch_root diff --git a/kdumpctl b/kdumpctl index d29d37f2..f65f8e3d 100755 --- a/kdumpctl +++ b/kdumpctl @@ -78,11 +78,11 @@ save_core() { coredir="/var/crash/$(date +"%Y-%m-%d-%H:%M")"
- mkdir -p $coredir + mkdir -p "$coredir" ddebug "cp --sparse=always /proc/vmcore $coredir/vmcore-incomplete" - cp --sparse=always /proc/vmcore $coredir/vmcore-incomplete + cp --sparse=always /proc/vmcore "$coredir/vmcore-incomplete" if [[ $? == 0 ]]; then - mv $coredir/vmcore-incomplete $coredir/vmcore + mv "$coredir/vmcore-incomplete" "$coredir/vmcore" dinfo "saved a vmcore to $coredir" else derror "failed to save a vmcore to $coredir" @@ -93,9 +93,9 @@ save_core() # https://fedorahosted.org/abrt/ if [[ -x /usr/bin/dumpoops ]]; then ddebug "makedumpfile --dump-dmesg $coredir/vmcore $coredir/dmesg" - makedumpfile --dump-dmesg $coredir/vmcore $coredir/dmesg >/dev/null 2>&1 + makedumpfile --dump-dmesg "$coredir/vmcore" "$coredir/dmesg" >/dev/null 2>&1 ddebug "dumpoops -d $coredir/dmesg" - dumpoops -d $coredir/dmesg >/dev/null 2>&1 + dumpoops -d "$coredir/dmesg" >/dev/null 2>&1 if [[ $? == 0 ]]; then dinfo "kernel oops has been collected by abrt tool" fi @@ -121,7 +121,7 @@ check_earlykdump_is_enabled() rebuild_kdump_initrd() { ddebug "rebuild kdump initrd: $MKDUMPRD $TARGET_INITRD $KDUMP_KERNELVER" - $MKDUMPRD $TARGET_INITRD $KDUMP_KERNELVER + $MKDUMPRD "$TARGET_INITRD" "$KDUMP_KERNELVER" if [[ $? != 0 ]]; then derror "mkdumprd: failed to make kdump initrd" return 1 @@ -136,8 +136,8 @@ rebuild_kdump_initrd()
rebuild_initrd() { - if [[ ! -w $(dirname $TARGET_INITRD) ]];then - derror "$(dirname $TARGET_INITRD) does not have write permission. Cannot rebuild $TARGET_INITRD" + if [[ ! -w $(dirname "$TARGET_INITRD") ]];then + derror "$(dirname "$TARGET_INITRD") does not have write permission. Cannot rebuild $TARGET_INITRD" return 1 fi
@@ -183,11 +183,11 @@ backup_default_initrd() if [[ ! -e $DEFAULT_INITRD_BAK ]]; then dinfo "Backing up $DEFAULT_INITRD before rebuild." # save checksum to verify before restoring - sha1sum $DEFAULT_INITRD > $INITRD_CHECKSUM_LOCATION - cp $DEFAULT_INITRD $DEFAULT_INITRD_BAK + sha1sum "$DEFAULT_INITRD" > "$INITRD_CHECKSUM_LOCATION" + cp "$DEFAULT_INITRD" "$DEFAULT_INITRD_BAK" if [[ $? -ne 0 ]]; then dwarn "WARNING: failed to backup $DEFAULT_INITRD." - rm -f $DEFAULT_INITRD_BAK + rm -f "$DEFAULT_INITRD_BAK" fi fi } @@ -210,7 +210,7 @@ restore_default_initrd() dwarn "WARNING: checksum mismatch! Can't restore original initrd.." else rm -f $INITRD_CHECKSUM_LOCATION - mv $DEFAULT_INITRD_BAK $DEFAULT_INITRD + mv "$DEFAULT_INITRD_BAK" "$DEFAULT_INITRD" if [[ $? -eq 0 ]]; then derror "Restoring original initrd as fadump mode is disabled." sync @@ -226,7 +226,7 @@ check_config() case "$config_opt" in dracut_args) if [[ $config_val == *--mount* ]]; then - if [[ $(echo $config_val | grep -o "--mount" | wc -l) -ne 1 ]]; then + if [[ $(echo "$config_val" | grep -o "--mount" | wc -l) -ne 1 ]]; then derror "Multiple mount targets specified in one "dracut_args"." return 1 fi @@ -297,13 +297,13 @@ get_pcs_cluster_modified_files() fi
if [[ -f $FENCE_KDUMP_CONFIG_FILE ]]; then - time_stamp=$(stat -c "%Y" $FENCE_KDUMP_CONFIG_FILE) + time_stamp=$(stat -c "%Y" "$FENCE_KDUMP_CONFIG_FILE") if [[ "$time_stamp" -gt "$image_time" ]]; then modified_files="$modified_files $FENCE_KDUMP_CONFIG_FILE" fi fi
- echo $modified_files + echo "$modified_files" }
setup_initrd() @@ -314,7 +314,7 @@ setup_initrd() return 1 fi
- DEFAULT_INITRD_BAK="$KDUMP_BOOTDIR/.$(basename $DEFAULT_INITRD).default" + DEFAULT_INITRD_BAK="$KDUMP_BOOTDIR/.$(basename "$DEFAULT_INITRD").default" if [[ $DEFAULT_DUMP_MODE == "fadump" ]]; then TARGET_INITRD="$DEFAULT_INITRD"
@@ -357,7 +357,7 @@ check_files_modified() fi HOOKS="$HOOKS $POST_FILES $PRE_FILES" CORE_COLLECTOR=$(kdump_get_conf_val core_collector | cut -d ' ' -f 1) - CORE_COLLECTOR=$(type -P $CORE_COLLECTOR) + CORE_COLLECTOR=$(type -P "$CORE_COLLECTOR") # POST_FILES and PRE_FILES are already checked against executable, need not to check again. EXTRA_BINS="$EXTRA_BINS $CHECK_FILES" CHECK_FILES=$(kdump_get_conf_val extra_bins) @@ -375,8 +375,8 @@ check_files_modified() _module_file="$(modinfo --set-version "$KDUMP_KERNELVER" --filename "$_module" 2>/dev/null)" if [[ $? -eq 0 ]]; then files="$files $_module_file" - for _dep_modules in $(modinfo -F depends $_module | tr ',' ' '); do - files="$files $(modinfo --set-version "$KDUMP_KERNELVER" --filename $_dep_modules 2>/dev/null)" + for _dep_modules in $(modinfo -F depends "$_module" | tr ',' ' '); do + files="$files $(modinfo --set-version "$KDUMP_KERNELVER" --filename "$_dep_modules" 2>/dev/null)" done else # If it's not a module nor builtin, give an error @@ -394,13 +394,13 @@ check_files_modified()
for file in $files; do if [[ -e "$file" ]]; then - time_stamp=$(stat -c "%Y" $file) + time_stamp=$(stat -c "%Y" "$file") if [[ "$time_stamp" -gt "$image_time" ]]; then modified_files="$modified_files $file" fi if [[ -L "$file" ]]; then - file=$(readlink -m $file) - time_stamp=$(stat -c "%Y" $file) + file=$(readlink -m "$file") + time_stamp=$(stat -c "%Y" "$file") if [[ "$time_stamp" -gt "$image_time" ]]; then modified_files="$modified_files $file" fi @@ -453,8 +453,8 @@ check_drivers_modified() ddebug "Modules included in old initramfs: '$_old_drivers'" for _driver in $_new_drivers; do # Skip deprecated/invalid driver name or built-in module - _module_name=$(modinfo --set-version "$KDUMP_KERNELVER" -F name $_driver 2>/dev/null) - _module_filename=$(modinfo --set-version "$KDUMP_KERNELVER" -n $_driver 2>/dev/null) + _module_name=$(modinfo --set-version "$KDUMP_KERNELVER" -F name "$_driver" 2>/dev/null) + _module_filename=$(modinfo --set-version "$KDUMP_KERNELVER" -n "$_driver" 2>/dev/null) if [[ $? -ne 0 ]] || [[ -z "$_module_name" ]] || [[ "$_module_filename" = *"(builtin)"* ]]; then continue fi @@ -483,21 +483,21 @@ check_fs_modified() fi
_target=$(get_block_dump_target) - _new_fstype=$(get_fs_type_from_target $_target) + _new_fstype=$(get_fs_type_from_target "$_target") if [[ -z "$_target" ]] || [[ -z "$_new_fstype" ]];then derror "Dump target is invalid" return 2 fi
ddebug "_target=$_target _new_fstype=$_new_fstype" - _new_dev=$(kdump_get_persistent_dev $_target) + _new_dev=$(kdump_get_persistent_dev "$_target") if [[ -z "$_new_dev" ]]; then perror "Get persistent device name failed" return 2 fi
- _new_mntpoint="$(get_kdump_mntpoint_from_target $_target)" - _dracut_args=$(lsinitrd $TARGET_INITRD -f usr/lib/dracut/build-parameter.txt) + _new_mntpoint="$(get_kdump_mntpoint_from_target "$_target")" + _dracut_args=$(lsinitrd "$TARGET_INITRD" -f usr/lib/dracut/build-parameter.txt) if [[ -z "$_dracut_args" ]];then dwarn "Warning: No dracut arguments found in initrd" return 0 @@ -505,13 +505,14 @@ check_fs_modified()
# if --mount argument present then match old and new target, mount # point and file system. If any of them mismatches then rebuild - echo $_dracut_args | grep "--mount" &> /dev/null + echo "$_dracut_args" | grep "--mount" &> /dev/null if [[ $? -eq 0 ]];then - set -- $(echo $_dracut_args | awk -F "--mount '" '{print $2}' | cut -d' ' -f1,2,3) + # shellcheck disable=SC2046 + set -- $(echo "$_dracut_args" | awk -F "--mount '" '{print $2}' | cut -d' ' -f1,2,3) _old_dev=$1 _old_mntpoint=$2 _old_fstype=$3 - [[ $_new_dev = $_old_dev && $_new_mntpoint = $_old_mntpoint && $_new_fstype = $_old_fstype ]] && return 0 + [[ $_new_dev = "$_old_dev" && $_new_mntpoint = "$_old_mntpoint" && $_new_fstype = "$_old_fstype" ]] && return 0 # otherwise rebuild if target device is not a root device else [[ "$_target" = "$(get_root_fs_device)" ]] && return 0 @@ -590,7 +591,7 @@ check_rebuild() #check to see if dependent files has been modified #since last build of the image file if [[ -f $TARGET_INITRD ]]; then - image_time=$(stat -c "%Y" $TARGET_INITRD 2>/dev/null) + image_time=$(stat -c "%Y" "$TARGET_INITRD" 2>/dev/null)
#in case of fadump mode, check whether the default/target #initrd is already built with dump capture capability @@ -649,7 +650,7 @@ function remove_kdump_kernel_key() return fi
- keyctl unlink $KDUMP_KEY_ID %:.ima + keyctl unlink "$KDUMP_KEY_ID" %:.ima }
# Load the kdump kernel specified in /etc/sysconfig/kdump @@ -682,9 +683,10 @@ load_kdump() PS4='+ $(date "+%Y-%m-%d %H:%M:%S") ${BASH_SOURCE}@${LINENO}: ' set -x
+ # shellcheck disable=SC2086 $KEXEC $KEXEC_ARGS $standard_kexec_args \ --command-line="$KDUMP_COMMANDLINE" \ - --initrd=$TARGET_INITRD $KDUMP_KERNEL + --initrd="$TARGET_INITRD" "$KDUMP_KERNEL"
ret=$? set +x @@ -709,7 +711,7 @@ check_ssh_config() # remove inline comments after the end of a directive. if [[ -f "$config_val" ]]; then # canonicalize the path - SSH_KEY_LOCATION=$(/usr/bin/readlink -m $config_val) + SSH_KEY_LOCATION=$(/usr/bin/readlink -m "$config_val") else dwarn "WARNING: '$config_val' doesn't exist, using default value '$SSH_KEY_LOCATION'" fi @@ -726,7 +728,7 @@ check_ssh_config() done <<< "$(kdump_read_conf)"
#make sure they've configured kdump.conf for ssh dumps - local SSH_TARGET=$(echo -n $DUMP_TARGET | sed -n '/.*@/p') + local SSH_TARGET=$(echo -n "$DUMP_TARGET" | sed -n '/.*@/p') if [[ -z "$SSH_TARGET" ]]; then return 1 fi @@ -746,7 +748,7 @@ check_and_wait_network_ready() local errmsg
while true; do - errmsg=$(ssh -i $SSH_KEY_LOCATION -o BatchMode=yes $DUMP_TARGET mkdir -p $SAVE_PATH 2>&1) + errmsg=$(ssh -i "$SSH_KEY_LOCATION" -o BatchMode=yes "$DUMP_TARGET" mkdir -p "$SAVE_PATH" 2>&1) retval=$?
# ssh exits with the exit status of the remote command or with 255 if an error occurred @@ -759,7 +761,7 @@ check_and_wait_network_ready()
# if server removes the authorized_keys or, no /root/.ssh/kdump_id_rsa ddebug "$errmsg" - echo $errmsg | grep -q "Permission denied|No such file or directory|Host key verification failed" &> /dev/null + echo "$errmsg" | grep -q "Permission denied|No such file or directory|Host key verification failed" &> /dev/null if [[ $? -eq 0 ]]; then derror "Could not create $DUMP_TARGET:$SAVE_PATH, you probably need to run "kdumpctl propagate"" return 1 @@ -808,16 +810,16 @@ propagate_ssh_key() dinfo "Using existing keys..." else dinfo "Generating new ssh keys... " - /usr/bin/ssh-keygen -t rsa -f $KEYFILE -N "" 2>&1 > /dev/null + /usr/bin/ssh-keygen -t rsa -f "$KEYFILE" -N "" 2>&1 > /dev/null dinfo "done." fi
#now find the target ssh user and server to contact. - SSH_USER=$(echo $DUMP_TARGET | cut -d\ -f2 | cut -d@ -f1) - SSH_SERVER=$(echo $DUMP_TARGET | sed -e's/(.*@)(.*$)/\2/') + SSH_USER=$(echo "$DUMP_TARGET" | cut -d@ -f1) + SSH_SERVER=$(echo "$DUMP_TARGET" | sed -e's/(.*@)(.*$)/\2/')
#now send the found key to the found server - ssh-copy-id -i $KEYFILE $SSH_USER@$SSH_SERVER + ssh-copy-id -i "$KEYFILE" "$SSH_USER@$SSH_SERVER" RET=$? if [[ $RET == 0 ]]; then dinfo "$KEYFILE has been added to ~$SSH_USER/.ssh/authorized_keys on $SSH_SERVER" @@ -836,7 +838,7 @@ show_reserved_mem() mem=$(</sys/kernel/kexec_crash_size) mem_mb=$((mem / 1024 / 1024))
- dinfo "Reserved "$mem_mb"MB memory for crash kernel" + dinfo "Reserved ${mem_mb}MB memory for crash kernel" }
check_current_fadump_status() @@ -869,8 +871,8 @@ save_raw() derror "raw partition $raw_target not found" return 1 } - check_fs=$(lsblk --nodeps -npo FSTYPE $raw_target) - if [[ $(echo $check_fs | wc -w) -ne 0 ]]; then + check_fs=$(lsblk --nodeps -npo FSTYPE "$raw_target") + if [[ $(echo "$check_fs" | wc -w) -ne 0 ]]; then dwarn "Warning: Detected '$check_fs' signature on $raw_target, data loss is expected." return 0 fi @@ -886,11 +888,11 @@ save_raw() derror "failed to create $coredir" return 1 } - if makedumpfile -R $coredir/vmcore <$raw_target >/dev/null 2>&1; then + if makedumpfile -R "$coredir/vmcore" < "$raw_target" >/dev/null 2>&1; then # dump found dinfo "Dump saved to $coredir/vmcore" # wipe makedumpfile header - dd if=/dev/zero of=$raw_target bs=1b count=1 2>/dev/null + dd if=/dev/zero of="$raw_target" bs=1b count=1 2>/dev/null else rm -rf "$coredir" fi @@ -904,7 +906,7 @@ local_fs_dump_target()
_target=$(egrep "^ext[234]|^xfs|^btrfs|^minix" /etc/kdump.conf) if [[ $? -eq 0 ]]; then - echo $_target|awk '{print $2}' + echo "$_target" | awk '{print $2}' fi }
@@ -919,7 +921,7 @@ path_to_be_relabeled()
_target=$(local_fs_dump_target) if [[ -n "$_target" ]]; then - _mnt=$(get_mntpoint_from_target $_target) + _mnt=$(get_mntpoint_from_target "$_target") if ! is_mounted "$_mnt"; then return fi @@ -930,9 +932,9 @@ path_to_be_relabeled()
_path=$(get_save_path) # if $_path is masked by other mount, we will not relabel it. - _rmnt=$(df $_mnt/$_path 2>/dev/null | tail -1 | awk '{ print $NF }') + _rmnt=$(df "$_mnt/$_path" 2>/dev/null | tail -1 | awk '{ print $NF }') if [[ "$_rmnt" == "$_mnt" ]]; then - echo $_mnt/$_path + echo "$_mnt/$_path" fi }
diff --git a/mkdumprd b/mkdumprd index f91315fe..9800934e 100644 --- a/mkdumprd +++ b/mkdumprd @@ -60,9 +60,9 @@ add_dracut_sshkey() { to_mount() { local _target=$1 _fstype=$2 _options=$3 _sed_cmd _new_mntpoint _pdev
- _new_mntpoint=$(get_kdump_mntpoint_from_target $_target) - _fstype="${_fstype:-$(get_fs_type_from_target $_target)}" - _options="${_options:-$(get_mntopt_from_target $_target)}" + _new_mntpoint=$(get_kdump_mntpoint_from_target "$_target") + _fstype="${_fstype:-$(get_fs_type_from_target "$_target")}" + _options="${_options:-$(get_mntopt_from_target "$_target")}" _options="${_options:-defaults}"
if [[ "$_fstype" == "nfs"* ]]; then @@ -72,8 +72,8 @@ to_mount() { _sed_cmd+='s/,clientaddr=[^,]*//;' else # for non-nfs _target converting to use udev persistent name - _pdev="$(kdump_get_persistent_dev $_target)" - if [[ -z "$_pdev" ]]; then + _pdev="$(kdump_get_persistent_dev "$_target")" + if [[ -z $_pdev ]]; then return 1 fi fi @@ -114,19 +114,19 @@ mkdir_save_path_ssh() { local _opt _dir _opt=(-i "$SSH_KEY_LOCATION" -o BatchMode=yes -o StrictHostKeyChecking=yes) - ssh -qn "${_opt[@]}" $1 mkdir -p $SAVE_PATH 2>&1 > /dev/null + ssh -qn "${_opt[@]}" "$1" mkdir -p "$SAVE_PATH" 2>&1 > /dev/null _ret=$? if [[ $_ret -ne 0 ]]; then perror_exit "mkdir failed on $1:$SAVE_PATH" fi
#check whether user has write permission on $1:$SAVE_PATH - _dir=$(ssh -qn "${_opt[@]}" $1 mktemp -dqp $SAVE_PATH 2>/dev/null) + _dir=$(ssh -qn "${_opt[@]}" "$1" mktemp -dqp "$SAVE_PATH" 2>/dev/null) _ret=$? if [[ $_ret -ne 0 ]]; then perror_exit "Could not create temporary directory on $1:$SAVE_PATH. Make sure user has write permission on destination" fi - ssh -qn "${_opt[@]}" $1 rmdir $_dir + ssh -qn "${_opt[@]}" "$1" rmdir "$_dir"
return 0 } @@ -168,7 +168,7 @@ check_size() { perror_exit "Check dump target size failed" fi
- if [[ $avail -lt $memtotal ]]; then + if [[ "$avail" -lt "$memtotal" ]]; then dwarn "Warning: There might not be enough space to save a vmcore." dwarn " The size of $2 should be greater than $memtotal kilo bytes." fi @@ -206,9 +206,9 @@ mount_failure() check_user_configured_target() { local _target=$1 _cfg_fs_type=$2 _mounted - local _mnt=$(get_mntpoint_from_target $_target) - local _opt=$(get_mntopt_from_target $_target) - local _fstype=$(get_fs_type_from_target $_target) + local _mnt=$(get_mntpoint_from_target "$_target") + local _opt=$(get_mntopt_from_target "$_target") + local _fstype=$(get_fs_type_from_target "$_target")
if [[ -n "$_fstype" ]]; then # In case of nfs4, nfs should be used instead, nfs* options is deprecated in kdump.conf @@ -227,7 +227,7 @@ check_user_configured_target() if [[ -n "$_mnt" ]]; then if ! is_mounted "$_mnt"; then if [[ $_opt = *",noauto"* ]]; then - mount $_mnt + mount "$_mnt" [[ $? -ne 0 ]] && mount_failure "$_target" "$_mnt" "$_fstype" _mounted=$_mnt else @@ -236,8 +236,8 @@ check_user_configured_target() fi else _mnt=$MKDUMPRD_TMPMNT - mkdir -p $_mnt - mount $_target $_mnt -t $_fstype -o defaults + mkdir -p "$_mnt" + mount "$_target" "$_mnt" -t "$_fstype" -o defaults [[ $? -ne 0 ]] && mount_failure "$_target" "" "$_fstype" _mounted=$_mnt fi @@ -251,7 +251,7 @@ check_user_configured_target()
# Unmount it early, if function is interrupted and didn't reach here, the shell trap will clear it up anyway if [[ -n "$_mounted" ]]; then - umount -f -- $_mounted + umount -f -- "$_mounted" fi }
@@ -276,13 +276,14 @@ verify_core_collector() { _params="$_params vmcore dumpfile" fi
+ # shellcheck disable=SC2086 if ! $_cmd --check-params $_params; then perror_exit "makedumpfile parameter check failed." fi }
add_mount() { - local _mnt=$(to_mount $@) + local _mnt=$(to_mount "$@")
if [[ $? -ne 0 ]]; then exit 1 @@ -299,15 +300,15 @@ handle_default_dump_target()
is_user_configured_dump_target && return
- check_save_path_fs $SAVE_PATH + check_save_path_fs "$SAVE_PATH"
- _save_path=$(get_bind_mount_source $SAVE_PATH) - _target=$(get_target_from_path $_save_path) - _mntpoint=$(get_mntpoint_from_target $_target) + _save_path=$(get_bind_mount_source "$SAVE_PATH") + _target=$(get_target_from_path "$_save_path") + _mntpoint=$(get_mntpoint_from_target "$_target")
SAVE_PATH=${_save_path##"$_mntpoint"} add_mount "$_target" - check_size fs $_target + check_size fs "$_target" }
# $1: function name @@ -317,8 +318,8 @@ for_each_block_target()
for dev in $(get_kdump_targets); do [[ -b "$dev" ]] || continue - majmin=$(get_maj_min $dev) - check_block_and_slaves $1 $majmin && return 1 + majmin=$(get_maj_min "$dev") + check_block_and_slaves "$1" "$majmin" && return 1 done
return 0 @@ -328,14 +329,14 @@ for_each_block_target() #return false if unresettable. is_unresettable() { - local path="/sys/$(udevadm info --query=all --path=/sys/dev/block/$1 | awk '/^P:/ {print $2}' | sed -e 's/(cciss[0-9]+/).*/\1/g' -e 's//block/.*$//')/resettable" + local path="/sys/$(udevadm info --query=all --path="/sys/dev/block/$1" | awk '/^P:/ {print $2}' | sed -e 's/(cciss[0-9]+/).*/\1/g' -e 's//block/.*$//')/resettable" local resettable=1
if [[ -f "$path" ]] then resettable="$(<"$path")" [[ $resettable -eq 0 ]] && [[ "$OVERRIDE_RESETTABLE" -eq 0 ]] && { - local device=$(udevadm info --query=all --path=/sys/dev/block/$1 | awk -F= '/DEVNAME/{print $2}') + local device=$(udevadm info --query=all --path="/sys/dev/block/$1" | awk -F= '/DEVNAME/{print $2}') derror "Error: Can not save vmcore because device $device is unresettable" return 0 } @@ -384,7 +385,7 @@ fi keyfile=$(kdump_get_conf_val sshkey) if [[ -f "$keyfile" ]]; then # canonicalize the path - SSH_KEY_LOCATION=$(/usr/bin/readlink -m $keyfile) + SSH_KEY_LOCATION=$(/usr/bin/readlink -m "$keyfile") fi
while read -r config_opt config_val; @@ -400,21 +401,21 @@ do ;; raw) # checking raw disk writable - dd if=$config_val count=1 of=/dev/null > /dev/null 2>&1 || { + dd if="$config_val" count=1 of=/dev/null > /dev/null 2>&1 || { perror_exit "Bad raw disk $config_val" } - _praw=$(persistent_policy="by-id" kdump_get_persistent_dev $config_val) - if [[ -z "$_praw" ]]; then + _praw=$(persistent_policy="by-id" kdump_get_persistent_dev "$config_val") + if [[ -z $_praw ]]; then exit 1 fi add_dracut_arg "--device" "$_praw" - check_size raw $config_val + check_size raw "$config_val" ;; ssh) if strstr "$config_val" "@"; then - mkdir_save_path_ssh $config_val - check_size ssh $config_val + mkdir_save_path_ssh "$config_val" + check_size ssh "$config_val" add_dracut_sshkey "$SSH_KEY_LOCATION" else perror_exit "Bad ssh dump target $config_val" @@ -448,7 +449,7 @@ fi if ! is_fadump_capable; then # The 2nd rootfs mount stays behind the normal dump target mount, # so it doesn't affect the logic of check_dump_fs_modified(). - is_dump_to_rootfs && add_mount "$(to_dev_name $(get_root_fs_device))" + is_dump_to_rootfs && add_mount "$(to_dev_name "$(get_root_fs_device)")"
add_dracut_arg "--no-hostonly-default-device" fi
As suggested by: https://github.com/koalaman/shellcheck/wiki/SC2181
Signed-off-by: Kairui Song kasong@redhat.com --- dracut-module-setup.sh | 41 ++++++--------- kdumpctl | 112 +++++++++++++---------------------------- mkdumprd | 40 ++++----------- 3 files changed, 61 insertions(+), 132 deletions(-)
diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index 600bdc51..46c0087a 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -255,8 +255,7 @@ kdump_static_ip() { _gateway="[$_gateway]" else _prefix=$(cut -d'/' -f2 <<< "$_ipaddr") - _netmask=$(cal_netmask_by_prefix "$_prefix" "$_ipv6_flag") - if [[ "$?" -ne 0 ]]; then + if ! _netmask=$(cal_netmask_by_prefix "$_prefix" "$_ipv6_flag"); then derror "Failed to calculate netmask for $_ipaddr" exit 1 fi @@ -358,10 +357,7 @@ kdump_setup_bridge() { [[ -e $_dev ]] || continue _kdumpdev=$_dev if kdump_is_bond "$_dev"; then - $(kdump_setup_bond "$_dev" "$(get_nmcli_connection_show_cmd_by_ifname "$_dev")") - if [[ $? != 0 ]]; then - exit 1 - fi + $(kdump_setup_bond "$_dev" "$(get_nmcli_connection_show_cmd_by_ifname "$_dev")") || exit 1 elif kdump_is_team "$_dev"; then kdump_setup_team "$_dev" elif kdump_is_vlan "$_dev"; then @@ -419,9 +415,7 @@ kdump_setup_team() { echo " team=$_netdev:${_slaves%,}" >> "${initdir}/etc/cmdline.d/44team.conf" #Buggy version teamdctl outputs to stderr! #Try to use the latest version of teamd. - teamdctl "$_netdev" config dump > "${initdir}/tmp/$$-$_netdev.conf" - if [[ $? -ne 0 ]] - then + if ! teamdctl "$_netdev" config dump > "${initdir}/tmp/$$-$_netdev.conf"; then derror "teamdctl failed." exit 1 fi @@ -441,10 +435,7 @@ kdump_setup_vlan() { derror "Vlan over bridge is not supported!" exit 1 elif kdump_is_bond "$_phydev"; then - $(kdump_setup_bond "$_phydev" "$(get_nmcli_connection_show_cmd_by_ifname "$_phydev")") - if [[ $? != 0 ]]; then - exit 1 - fi + $(kdump_setup_bond "$_phydev" "$(get_nmcli_connection_show_cmd_by_ifname "$_phydev")") || exit 1 echo " vlan=$(kdump_setup_ifname "$_netdev"):$_phydev" > "${initdir}/etc/cmdline.d/43vlan.conf" else _kdumpdev="$(kdump_setup_ifname "$_phydev")" @@ -515,8 +506,8 @@ kdump_setup_znet() {
kdump_get_ip_route() { - local _route=$(/sbin/ip -o route get to "$1" 2>&1) - if [[ $? != 0 ]]; then + local _route + if ! _route=$(/sbin/ip -o route get to "$1" 2>&1); then derror "Bad kdump network destination: $1" exit 1 fi @@ -560,8 +551,7 @@ kdump_install_net() { _znet_netdev=$(find_online_znet_device) if [[ -n "$_znet_netdev" ]]; then _nm_show_cmd_znet=$(get_nmcli_connection_show_cmd_by_ifname "$_znet_netdev") - $(kdump_setup_znet "$_znet_netdev" "$_nm_show_cmd_znet") - if [[ $? != 0 ]]; then + if ! $(kdump_setup_znet "$_znet_netdev" "$_nm_show_cmd_znet"); then derror "Failed to set up znet" exit 1 fi @@ -591,10 +581,7 @@ kdump_install_net() { if kdump_is_bridge "$_netdev"; then kdump_setup_bridge "$_netdev" elif kdump_is_bond "$_netdev"; then - $(kdump_setup_bond "$_netdev" "$_nm_show_cmd") - if [[ $? != 0 ]]; then - exit 1 - fi + $(kdump_setup_bond "$_netdev" "$_nm_show_cmd") || exit 1 elif kdump_is_team "$_netdev"; then kdump_setup_team "$_netdev" elif kdump_is_vlan "$_netdev"; then @@ -836,8 +823,10 @@ kdump_setup_iscsi_device() { fi
# Setup initator - initiator_str=$(kdump_get_iscsi_initiator) - [[ $? -ne "0" ]] && derror "Failed to get initiator name" && return 1 + if ! initiator_str=$(kdump_get_iscsi_initiator); then + derror "Failed to get initiator name" + return 1 + fi
# If initiator details do not exist already, append. if ! grep -q "$initiator_str" "$netroot_conf"; then @@ -877,8 +866,7 @@ get_alias() { for ip in $ips do # in /etc/hosts, alias can come at the 2nd column - entries=$(grep "$ip" /etc/hosts | awk '{ $1=""; print $0 }') - if [[ $? -eq 0 ]]; then + if entries=$(grep "$ip" /etc/hosts | awk '{ $1=""; print $0 }'); then alias_set="$alias_set $entries" fi done @@ -1003,8 +991,7 @@ kdump_install_random_seed() { kdump_install_systemd_conf() { # Kdump turns out to require longer default systemd mount timeout # than 1st kernel(90s by default), we use default 300s for kdump. - grep -r "^[[:space:]]*DefaultTimeoutStartSec=" "${initdir}/etc/systemd/system.conf"* &>/dev/null - if [[ $? -ne 0 ]]; then + if ! grep -q -r "^[[:space:]]*DefaultTimeoutStartSec=" "${initdir}/etc/systemd/system.conf"*; then mkdir -p "${initdir}/etc/systemd/system.conf.d" echo "[Manager]" > "${initdir}/etc/systemd/system.conf.d/kdump.conf" echo "DefaultTimeoutStartSec=300s" >> "${initdir}/etc/systemd/system.conf.d/kdump.conf" diff --git a/kdumpctl b/kdumpctl index f65f8e3d..ecfe3d77 100755 --- a/kdumpctl +++ b/kdumpctl @@ -37,8 +37,7 @@ fi . /lib/kdump/kdump-logger.sh
#initiate the kdump logger -dlog_init -if [[ $? -ne 0 ]]; then +if ! dlog_init; then echo "failed to initiate the kdump logger." exit 1 fi @@ -47,8 +46,7 @@ single_instance_lock() { local rc timeout=5
- exec 9>/var/lock/kdump - if [[ $? -ne 0 ]]; then + if ! exec 9>/var/lock/kdump; then derror "Create file lock failed" exit 1 fi @@ -80,8 +78,7 @@ save_core()
mkdir -p "$coredir" ddebug "cp --sparse=always /proc/vmcore $coredir/vmcore-incomplete" - cp --sparse=always /proc/vmcore "$coredir/vmcore-incomplete" - if [[ $? == 0 ]]; then + if cp --sparse=always /proc/vmcore "$coredir/vmcore-incomplete"; then mv "$coredir/vmcore-incomplete" "$coredir/vmcore" dinfo "saved a vmcore to $coredir" else @@ -95,8 +92,7 @@ save_core() ddebug "makedumpfile --dump-dmesg $coredir/vmcore $coredir/dmesg" makedumpfile --dump-dmesg "$coredir/vmcore" "$coredir/dmesg" >/dev/null 2>&1 ddebug "dumpoops -d $coredir/dmesg" - dumpoops -d "$coredir/dmesg" >/dev/null 2>&1 - if [[ $? == 0 ]]; then + if dumpoops -d "$coredir/dmesg" >/dev/null 2>&1; then dinfo "kernel oops has been collected by abrt tool" fi fi @@ -121,8 +117,7 @@ check_earlykdump_is_enabled() rebuild_kdump_initrd() { ddebug "rebuild kdump initrd: $MKDUMPRD $TARGET_INITRD $KDUMP_KERNELVER" - $MKDUMPRD "$TARGET_INITRD" "$KDUMP_KERNELVER" - if [[ $? != 0 ]]; then + if ! $MKDUMPRD "$TARGET_INITRD" "$KDUMP_KERNELVER"; then derror "mkdumprd: failed to make kdump initrd" return 1 fi @@ -184,8 +179,7 @@ backup_default_initrd() dinfo "Backing up $DEFAULT_INITRD before rebuild." # save checksum to verify before restoring sha1sum "$DEFAULT_INITRD" > "$INITRD_CHECKSUM_LOCATION" - cp "$DEFAULT_INITRD" "$DEFAULT_INITRD_BAK" - if [[ $? -ne 0 ]]; then + if ! cp "$DEFAULT_INITRD" "$DEFAULT_INITRD_BAK"; then dwarn "WARNING: failed to backup $DEFAULT_INITRD." rm -f "$DEFAULT_INITRD_BAK" fi @@ -210,8 +204,7 @@ restore_default_initrd() dwarn "WARNING: checksum mismatch! Can't restore original initrd.." else rm -f $INITRD_CHECKSUM_LOCATION - mv "$DEFAULT_INITRD_BAK" "$DEFAULT_INITRD" - if [[ $? -eq 0 ]]; then + if mv "$DEFAULT_INITRD_BAK" "$DEFAULT_INITRD"; then derror "Restoring original initrd as fadump mode is disabled." sync fi @@ -308,8 +301,7 @@ get_pcs_cluster_modified_files()
setup_initrd() { - prepare_kdump_bootinfo - if [[ $? -ne 0 ]]; then + if ! prepare_kdump_bootinfo; then derror "failed to prepare for kdump bootinfo." return 1 fi @@ -372,8 +364,7 @@ check_files_modified() files="$files /lib/modules/$KDUMP_KERNELVER/modules.dep" fi for _module in $EXTRA_MODULES; do - _module_file="$(modinfo --set-version "$KDUMP_KERNELVER" --filename "$_module" 2>/dev/null)" - if [[ $? -eq 0 ]]; then + if _module_file="$(modinfo --set-version "$KDUMP_KERNELVER" --filename "$_module" 2>/dev/null)"; then files="$files $_module_file" for _dep_modules in $(modinfo -F depends "$_module" | tr ',' ' '); do files="$files $(modinfo --set-version "$KDUMP_KERNELVER" --filename "$_dep_modules" 2>/dev/null)" @@ -389,8 +380,7 @@ check_files_modified()
# HOOKS is mandatory and need to check the modification time files="$files $HOOKS" - check_exist "$files" && check_executable "$EXTRA_BINS" - [[ $? -ne 0 ]] && return 2 + check_exist "$files" && check_executable "$EXTRA_BINS" || return 2
for file in $files; do if [[ -e "$file" ]]; then @@ -455,7 +445,7 @@ check_drivers_modified() # Skip deprecated/invalid driver name or built-in module _module_name=$(modinfo --set-version "$KDUMP_KERNELVER" -F name "$_driver" 2>/dev/null) _module_filename=$(modinfo --set-version "$KDUMP_KERNELVER" -n "$_driver" 2>/dev/null) - if [[ $? -ne 0 ]] || [[ -z "$_module_name" ]] || [[ "$_module_filename" = *"(builtin)"* ]]; then + if [[ -z "$_module_name" ]] || [[ -z "$_module_filename" ]] || [[ "$_module_filename" = *"(builtin)"* ]]; then continue fi if ! [[ " $_old_drivers " == *" $_module_name "* ]]; then @@ -505,8 +495,7 @@ check_fs_modified()
# if --mount argument present then match old and new target, mount # point and file system. If any of them mismatches then rebuild - echo "$_dracut_args" | grep "--mount" &> /dev/null - if [[ $? -eq 0 ]];then + if echo "$_dracut_args" | grep "--mount" &> /dev/null; then # shellcheck disable=SC2046 set -- $(echo "$_dracut_args" | awk -F "--mount '" '{print $2}' | cut -d' ' -f1,2,3) _old_dev=$1 @@ -558,11 +547,7 @@ check_rebuild() local force_rebuild force_no_rebuild local ret system_modified="0"
- setup_initrd - - if [[ $? -ne 0 ]]; then - return 1 - fi + setup_initrd || return 1
force_no_rebuild=$(kdump_get_conf_val force_no_rebuild) force_no_rebuild=${force_no_rebuild:-0} @@ -761,8 +746,7 @@ check_and_wait_network_ready()
# if server removes the authorized_keys or, no /root/.ssh/kdump_id_rsa ddebug "$errmsg" - echo "$errmsg" | grep -q "Permission denied|No such file or directory|Host key verification failed" &> /dev/null - if [[ $? -eq 0 ]]; then + if echo "$errmsg" | grep -q "Permission denied|No such file or directory|Host key verification failed" &> /dev/null; then derror "Could not create $DUMP_TARGET:$SAVE_PATH, you probably need to run "kdumpctl propagate"" return 1 fi @@ -788,16 +772,11 @@ check_and_wait_network_ready() check_ssh_target() { check_and_wait_network_ready - if [[ $? -ne 0 ]]; then - return 1 - fi - return 0 }
propagate_ssh_key() { - check_ssh_config - if [[ $? -ne 0 ]]; then + if ! check_ssh_config; then derror "No ssh config specified in $KDUMP_CONFIG_FILE. Can't propagate" exit 1 fi @@ -904,8 +883,7 @@ local_fs_dump_target() { local _target
- _target=$(egrep "^ext[234]|^xfs|^btrfs|^minix" /etc/kdump.conf) - if [[ $? -eq 0 ]]; then + if _target=$(grep -E "^ext[234]|^xfs|^btrfs|^minix" /etc/kdump.conf); then echo "$_target" | awk '{print $2}' fi } @@ -967,8 +945,7 @@ check_fence_kdump_config() return 1 fi # node can be ipaddr - echo "$ipaddrs " | grep "$node " > /dev/null - if [[ $? -eq 0 ]]; then + if echo "$ipaddrs " | grep "$node " > /dev/null; then derror "Option fence_kdump_nodes cannot contain $node" return 1 fi @@ -1062,14 +1039,12 @@ check_final_action_config()
start() { - check_dump_feasibility - if [[ $? -ne 0 ]]; then + if ! check_dump_feasibility; then derror "Starting kdump: [FAILED]" return 1 fi
- check_config - if [[ $? -ne 0 ]]; then + if ! check_config; then derror "Starting kdump: [FAILED]" return 1 fi @@ -1078,14 +1053,12 @@ start() selinux_relabel fi
- save_raw - if [[ $? -ne 0 ]]; then + if ! save_raw; then derror "Starting kdump: [FAILED]" return 1 fi
- check_current_status - if [[ $? == 0 ]]; then + if check_current_status; then dwarn "Kdump already running: [WARNING]" return 0 fi @@ -1097,14 +1070,12 @@ start() fi fi
- check_rebuild - if [[ $? != 0 ]]; then + if ! check_rebuild; then derror "Starting kdump: [FAILED]" return 1 fi
- start_dump - if [[ $? != 0 ]]; then + if ! start_dump; then derror "Starting kdump: [FAILED]" return 1 fi @@ -1114,8 +1085,7 @@ start()
reload() { - check_current_status - if [[ $? -ne 0 ]]; then + if ! check_current_status; then dwarn "Kdump was not running: [WARNING]" fi
@@ -1123,24 +1093,20 @@ reload() reload_fadump return $? else - stop_kdump - fi - - if [[ $? -ne 0 ]]; then - derror "Stopping kdump: [FAILED]" - return 1 + if ! stop_kdump; then + derror "Stopping kdump: [FAILED]" + return 1 + fi fi
dinfo "Stopping kdump: [OK]"
- setup_initrd - if [[ $? -ne 0 ]]; then + if ! setup_initrd; then derror "Starting kdump: [FAILED]" return 1 fi
- start_dump - if [[ $? -ne 0 ]]; then + if ! start_dump; then derror "Starting kdump: [FAILED]" return 1 fi @@ -1168,6 +1134,7 @@ stop_kdump() $KEXEC -p -u fi
+ # shellcheck disable=SC2181 if [[ $? != 0 ]]; then derror "kexec: failed to unload kdump kernel" return 1 @@ -1179,16 +1146,14 @@ stop_kdump()
reload_fadump() { - echo 1 > $FADUMP_REGISTER_SYS_NODE - if [[ $? == 0 ]]; then + if echo 1 > $FADUMP_REGISTER_SYS_NODE; then dinfo "fadump: re-registered successfully" return 0 else # FADump could fail on older kernel where re-register # support is not enabled. Try stop/start from userspace # to handle such scenario. - stop_fadump - if [[ $? == 0 ]]; then + if stop_fadump; then start_fadump return $? fi @@ -1205,6 +1170,7 @@ stop() stop_kdump fi
+ # shellcheck disable=SC2181 if [[ $? != 0 ]]; then derror "Stopping kdump: [FAILED]" return 1 @@ -1215,10 +1181,7 @@ stop() }
rebuild() { - check_config - if [[ $? -ne 0 ]]; then - return 1 - fi + check_config || return 1
if check_ssh_config; then if ! check_ssh_target; then @@ -1226,10 +1189,7 @@ rebuild() { fi fi
- setup_initrd - if [[ $? -ne 0 ]]; then - return 1 - fi + setup_initrd || return 1
dinfo "Rebuilding $TARGET_INITRD" rebuild_initrd diff --git a/mkdumprd b/mkdumprd index 9800934e..a2c6ed29 100644 --- a/mkdumprd +++ b/mkdumprd @@ -17,8 +17,7 @@ fi export IN_KDUMP=1
#initiate the kdump logger -dlog_init -if [[ $? -ne 0 ]]; then +if ! dlog_init; then echo "failed to initiate the kdump logger." exit 1 fi @@ -114,18 +113,12 @@ mkdir_save_path_ssh() { local _opt _dir _opt=(-i "$SSH_KEY_LOCATION" -o BatchMode=yes -o StrictHostKeyChecking=yes) - ssh -qn "${_opt[@]}" "$1" mkdir -p "$SAVE_PATH" 2>&1 > /dev/null - _ret=$? - if [[ $_ret -ne 0 ]]; then + ssh -qn "${_opt[@]}" "$1" mkdir -p "$SAVE_PATH" &>/dev/null || \ perror_exit "mkdir failed on $1:$SAVE_PATH" - fi
- #check whether user has write permission on $1:$SAVE_PATH - _dir=$(ssh -qn "${_opt[@]}" "$1" mktemp -dqp "$SAVE_PATH" 2>/dev/null) - _ret=$? - if [[ $_ret -ne 0 ]]; then + # check whether user has write permission on $1:$SAVE_PATH + _dir=$(ssh -qn "${_opt[@]}" "$1" mktemp -dqp "$SAVE_PATH" 2>/dev/null) || \ perror_exit "Could not create temporary directory on $1:$SAVE_PATH. Make sure user has write permission on destination" - fi ssh -qn "${_opt[@]}" "$1" rmdir "$_dir"
return 0 @@ -162,11 +155,7 @@ check_size() { ;; *) return - esac - - if [[ $? -ne 0 ]]; then - perror_exit "Check dump target size failed" - fi + esac || perror_exit "Check dump target size failed"
if [[ "$avail" -lt "$memtotal" ]]; then dwarn "Warning: There might not be enough space to save a vmcore." @@ -227,8 +216,7 @@ check_user_configured_target() if [[ -n "$_mnt" ]]; then if ! is_mounted "$_mnt"; then if [[ $_opt = *",noauto"* ]]; then - mount "$_mnt" - [[ $? -ne 0 ]] && mount_failure "$_target" "$_mnt" "$_fstype" + mount "$_mnt" || mount_failure "$_target" "$_mnt" "$_fstype" _mounted=$_mnt else perror_exit "Dump target "$_target" is neither mounted nor configured as "noauto"" @@ -237,8 +225,7 @@ check_user_configured_target() else _mnt=$MKDUMPRD_TMPMNT mkdir -p "$_mnt" - mount "$_target" "$_mnt" -t "$_fstype" -o defaults - [[ $? -ne 0 ]] && mount_failure "$_target" "" "$_fstype" + mount "$_target" "$_mnt" -t "$_fstype" -o defaults || mount_failure "$_target" "" "$_fstype" _mounted=$_mnt fi
@@ -283,11 +270,9 @@ verify_core_collector() { }
add_mount() { - local _mnt=$(to_mount "$@") + local _mnt
- if [[ $? -ne 0 ]]; then - exit 1 - fi + _mnt=$(to_mount "$@") || exit 1
add_dracut_mount "$_mnt" } @@ -349,15 +334,12 @@ is_unresettable() #return true if resettable check_resettable() { - local _ret _target _override_resettable + local _target _override_resettable
_override_resettable=$(kdump_get_conf_val override_resettable) OVERRIDE_RESETTABLE=${_override_resettable:-$OVERRIDE_RESETTABLE}
- for_each_block_target is_unresettable - _ret=$? - - [[ $_ret -eq 0 ]] && return + for_each_block_target is_unresettable && return
return 1 }
On Thu, Aug 19, 2021 at 07:39:27PM +0800, Kairui Song wrote:
As suggested by: https://github.com/koalaman/shellcheck/wiki/SC2181
Signed-off-by: Kairui Song kasong@redhat.com
dracut-module-setup.sh | 41 ++++++--------- kdumpctl | 112 +++++++++++++---------------------------- mkdumprd | 40 ++++----------- 3 files changed, 61 insertions(+), 132 deletions(-)
diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index 600bdc51..46c0087a 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -255,8 +255,7 @@ kdump_static_ip() { _gateway="[$_gateway]" else _prefix=$(cut -d'/' -f2 <<< "$_ipaddr")
_netmask=$(cal_netmask_by_prefix "$_prefix" "$_ipv6_flag")
if [[ "$?" -ne 0 ]]; then
if ! _netmask=$(cal_netmask_by_prefix "$_prefix" "$_ipv6_flag"); then derror "Failed to calculate netmask for $_ipaddr" exit 1 fi
@@ -358,10 +357,7 @@ kdump_setup_bridge() { [[ -e $_dev ]] || continue _kdumpdev=$_dev if kdump_is_bond "$_dev"; then
$(kdump_setup_bond "$_dev" "$(get_nmcli_connection_show_cmd_by_ifname "$_dev")")
if [[ $? != 0 ]]; then
exit 1
fi
$(kdump_setup_bond "$_dev" "$(get_nmcli_connection_show_cmd_by_ifname "$_dev")") || exit 1
The above codes which was originally introduced by me breaks SC2091. I think we can use "()" to replace "$()"
elif kdump_is_team "$_dev"; then kdump_setup_team "$_dev" elif kdump_is_vlan "$_dev"; then
@@ -419,9 +415,7 @@ kdump_setup_team() { echo " team=$_netdev:${_slaves%,}" >> "${initdir}/etc/cmdline.d/44team.conf" #Buggy version teamdctl outputs to stderr! #Try to use the latest version of teamd.
- teamdctl "$_netdev" config dump > "${initdir}/tmp/$$-$_netdev.conf"
- if [[ $? -ne 0 ]]
- then
- if ! teamdctl "$_netdev" config dump > "${initdir}/tmp/$$-$_netdev.conf"; then derror "teamdctl failed." exit 1 fi
@@ -441,10 +435,7 @@ kdump_setup_vlan() { derror "Vlan over bridge is not supported!" exit 1 elif kdump_is_bond "$_phydev"; then
$(kdump_setup_bond "$_phydev" "$(get_nmcli_connection_show_cmd_by_ifname "$_phydev")")
if [[ $? != 0 ]]; then
exit 1
fi
$(kdump_setup_bond "$_phydev" "$(get_nmcli_connection_show_cmd_by_ifname "$_phydev")") || exit 1
Here too.
echo " vlan=$(kdump_setup_ifname "$_netdev"):$_phydev" > "${initdir}/etc/cmdline.d/43vlan.conf" else _kdumpdev="$(kdump_setup_ifname "$_phydev")"
@@ -515,8 +506,8 @@ kdump_setup_znet() {
kdump_get_ip_route() {
- local _route=$(/sbin/ip -o route get to "$1" 2>&1)
- if [[ $? != 0 ]]; then
- local _route
- if ! _route=$(/sbin/ip -o route get to "$1" 2>&1); then derror "Bad kdump network destination: $1" exit 1 fi
@@ -560,8 +551,7 @@ kdump_install_net() { _znet_netdev=$(find_online_znet_device) if [[ -n "$_znet_netdev" ]]; then _nm_show_cmd_znet=$(get_nmcli_connection_show_cmd_by_ifname "$_znet_netdev")
$(kdump_setup_znet "$_znet_netdev" "$_nm_show_cmd_znet")
if [[ $? != 0 ]]; then
if ! $(kdump_setup_znet "$_znet_netdev" "$_nm_show_cmd_znet"); then
And here.
derror "Failed to set up znet" exit 1 fi
@@ -591,10 +581,7 @@ kdump_install_net() { if kdump_is_bridge "$_netdev"; then kdump_setup_bridge "$_netdev" elif kdump_is_bond "$_netdev"; then
$(kdump_setup_bond "$_netdev" "$_nm_show_cmd")
if [[ $? != 0 ]]; then
exit 1
fi
elif kdump_is_team "$_netdev"; then kdump_setup_team "$_netdev" elif kdump_is_vlan "$_netdev"; then$(kdump_setup_bond "$_netdev" "$_nm_show_cmd") || exit 1
@@ -836,8 +823,10 @@ kdump_setup_iscsi_device() { fi
# Setup initator
- initiator_str=$(kdump_get_iscsi_initiator)
- [[ $? -ne "0" ]] && derror "Failed to get initiator name" && return 1
if ! initiator_str=$(kdump_get_iscsi_initiator); then
derror "Failed to get initiator name"
return 1
fi
# If initiator details do not exist already, append. if ! grep -q "$initiator_str" "$netroot_conf"; then
@@ -877,8 +866,7 @@ get_alias() { for ip in $ips do # in /etc/hosts, alias can come at the 2nd column
entries=$(grep "$ip" /etc/hosts | awk '{ $1=""; print $0 }')
if [[ $? -eq 0 ]]; then
doneif entries=$(grep "$ip" /etc/hosts | awk '{ $1=""; print $0 }'); then alias_set="$alias_set $entries" fi
@@ -1003,8 +991,7 @@ kdump_install_random_seed() { kdump_install_systemd_conf() { # Kdump turns out to require longer default systemd mount timeout # than 1st kernel(90s by default), we use default 300s for kdump.
- grep -r "^[[:space:]]*DefaultTimeoutStartSec=" "${initdir}/etc/systemd/system.conf"* &>/dev/null
- if [[ $? -ne 0 ]]; then
- if ! grep -q -r "^[[:space:]]*DefaultTimeoutStartSec=" "${initdir}/etc/systemd/system.conf"*; then mkdir -p "${initdir}/etc/systemd/system.conf.d" echo "[Manager]" > "${initdir}/etc/systemd/system.conf.d/kdump.conf" echo "DefaultTimeoutStartSec=300s" >> "${initdir}/etc/systemd/system.conf.d/kdump.conf"
diff --git a/kdumpctl b/kdumpctl index f65f8e3d..ecfe3d77 100755 --- a/kdumpctl +++ b/kdumpctl @@ -37,8 +37,7 @@ fi . /lib/kdump/kdump-logger.sh
#initiate the kdump logger -dlog_init -if [[ $? -ne 0 ]]; then +if ! dlog_init; then echo "failed to initiate the kdump logger." exit 1 fi @@ -47,8 +46,7 @@ single_instance_lock() { local rc timeout=5
- exec 9>/var/lock/kdump
- if [[ $? -ne 0 ]]; then
- if ! exec 9>/var/lock/kdump; then derror "Create file lock failed" exit 1 fi
@@ -80,8 +78,7 @@ save_core()
mkdir -p "$coredir" ddebug "cp --sparse=always /proc/vmcore $coredir/vmcore-incomplete"
- cp --sparse=always /proc/vmcore "$coredir/vmcore-incomplete"
- if [[ $? == 0 ]]; then
- if cp --sparse=always /proc/vmcore "$coredir/vmcore-incomplete"; then mv "$coredir/vmcore-incomplete" "$coredir/vmcore" dinfo "saved a vmcore to $coredir" else
@@ -95,8 +92,7 @@ save_core() ddebug "makedumpfile --dump-dmesg $coredir/vmcore $coredir/dmesg" makedumpfile --dump-dmesg "$coredir/vmcore" "$coredir/dmesg" >/dev/null 2>&1 ddebug "dumpoops -d $coredir/dmesg"
dumpoops -d "$coredir/dmesg" >/dev/null 2>&1
if [[ $? == 0 ]]; then
fi fiif dumpoops -d "$coredir/dmesg" >/dev/null 2>&1; then dinfo "kernel oops has been collected by abrt tool"
@@ -121,8 +117,7 @@ check_earlykdump_is_enabled() rebuild_kdump_initrd() { ddebug "rebuild kdump initrd: $MKDUMPRD $TARGET_INITRD $KDUMP_KERNELVER"
- $MKDUMPRD "$TARGET_INITRD" "$KDUMP_KERNELVER"
- if [[ $? != 0 ]]; then
- if ! $MKDUMPRD "$TARGET_INITRD" "$KDUMP_KERNELVER"; then derror "mkdumprd: failed to make kdump initrd" return 1 fi
@@ -184,8 +179,7 @@ backup_default_initrd() dinfo "Backing up $DEFAULT_INITRD before rebuild." # save checksum to verify before restoring sha1sum "$DEFAULT_INITRD" > "$INITRD_CHECKSUM_LOCATION"
cp "$DEFAULT_INITRD" "$DEFAULT_INITRD_BAK"
if [[ $? -ne 0 ]]; then
fiif ! cp "$DEFAULT_INITRD" "$DEFAULT_INITRD_BAK"; then dwarn "WARNING: failed to backup $DEFAULT_INITRD." rm -f "$DEFAULT_INITRD_BAK"
@@ -210,8 +204,7 @@ restore_default_initrd() dwarn "WARNING: checksum mismatch! Can't restore original initrd.." else rm -f $INITRD_CHECKSUM_LOCATION
mv "$DEFAULT_INITRD_BAK" "$DEFAULT_INITRD"
if [[ $? -eq 0 ]]; then
if mv "$DEFAULT_INITRD_BAK" "$DEFAULT_INITRD"; then derror "Restoring original initrd as fadump mode is disabled." sync fi
@@ -308,8 +301,7 @@ get_pcs_cluster_modified_files()
setup_initrd() {
- prepare_kdump_bootinfo
- if [[ $? -ne 0 ]]; then
- if ! prepare_kdump_bootinfo; then derror "failed to prepare for kdump bootinfo." return 1 fi
@@ -372,8 +364,7 @@ check_files_modified() files="$files /lib/modules/$KDUMP_KERNELVER/modules.dep" fi for _module in $EXTRA_MODULES; do
_module_file="$(modinfo --set-version "$KDUMP_KERNELVER" --filename "$_module" 2>/dev/null)"
if [[ $? -eq 0 ]]; then
if _module_file="$(modinfo --set-version "$KDUMP_KERNELVER" --filename "$_module" 2>/dev/null)"; then files="$files $_module_file" for _dep_modules in $(modinfo -F depends "$_module" | tr ',' ' '); do files="$files $(modinfo --set-version "$KDUMP_KERNELVER" --filename "$_dep_modules" 2>/dev/null)"
@@ -389,8 +380,7 @@ check_files_modified()
# HOOKS is mandatory and need to check the modification time files="$files $HOOKS"
- check_exist "$files" && check_executable "$EXTRA_BINS"
- [[ $? -ne 0 ]] && return 2
check_exist "$files" && check_executable "$EXTRA_BINS" || return 2
for file in $files; do if [[ -e "$file" ]]; then
@@ -455,7 +445,7 @@ check_drivers_modified() # Skip deprecated/invalid driver name or built-in module _module_name=$(modinfo --set-version "$KDUMP_KERNELVER" -F name "$_driver" 2>/dev/null) _module_filename=$(modinfo --set-version "$KDUMP_KERNELVER" -n "$_driver" 2>/dev/null)
if [[ $? -ne 0 ]] || [[ -z "$_module_name" ]] || [[ "$_module_filename" = *"(builtin)"* ]]; then
fi if ! [[ " $_old_drivers " == *" $_module_name "* ]]; thenif [[ -z "$_module_name" ]] || [[ -z "$_module_filename" ]] || [[ "$_module_filename" = *"(builtin)"* ]]; then continue
@@ -505,8 +495,7 @@ check_fs_modified()
# if --mount argument present then match old and new target, mount # point and file system. If any of them mismatches then rebuild
- echo "$_dracut_args" | grep "--mount" &> /dev/null
- if [[ $? -eq 0 ]];then
- if echo "$_dracut_args" | grep "--mount" &> /dev/null; then # shellcheck disable=SC2046 set -- $(echo "$_dracut_args" | awk -F "--mount '" '{print $2}' | cut -d' ' -f1,2,3) _old_dev=$1
@@ -558,11 +547,7 @@ check_rebuild() local force_rebuild force_no_rebuild local ret system_modified="0"
- setup_initrd
- if [[ $? -ne 0 ]]; then
return 1
- fi
setup_initrd || return 1
force_no_rebuild=$(kdump_get_conf_val force_no_rebuild) force_no_rebuild=${force_no_rebuild:-0}
@@ -761,8 +746,7 @@ check_and_wait_network_ready()
# if server removes the authorized_keys or, no /root/.ssh/kdump_id_rsa ddebug "$errmsg"
echo "$errmsg" | grep -q "Permission denied\|No such file or directory\|Host key verification failed" &> /dev/null
if [[ $? -eq 0 ]]; then
fiif echo "$errmsg" | grep -q "Permission denied\|No such file or directory\|Host key verification failed" &> /dev/null; then derror "Could not create $DUMP_TARGET:$SAVE_PATH, you probably need to run \"kdumpctl propagate\"" return 1
@@ -788,16 +772,11 @@ check_and_wait_network_ready() check_ssh_target() { check_and_wait_network_ready
- if [[ $? -ne 0 ]]; then
return 1
- fi
- return 0
}
propagate_ssh_key() {
- check_ssh_config
- if [[ $? -ne 0 ]]; then
- if ! check_ssh_config; then derror "No ssh config specified in $KDUMP_CONFIG_FILE. Can't propagate" exit 1 fi
@@ -904,8 +883,7 @@ local_fs_dump_target() { local _target
- _target=$(egrep "^ext[234]|^xfs|^btrfs|^minix" /etc/kdump.conf)
- if [[ $? -eq 0 ]]; then
- if _target=$(grep -E "^ext[234]|^xfs|^btrfs|^minix" /etc/kdump.conf); then echo "$_target" | awk '{print $2}' fi
} @@ -967,8 +945,7 @@ check_fence_kdump_config() return 1 fi # node can be ipaddr
echo "$ipaddrs " | grep "$node " > /dev/null
if [[ $? -eq 0 ]]; then
fiif echo "$ipaddrs " | grep "$node " > /dev/null; then derror "Option fence_kdump_nodes cannot contain $node" return 1
@@ -1062,14 +1039,12 @@ check_final_action_config()
start() {
- check_dump_feasibility
- if [[ $? -ne 0 ]]; then
- if ! check_dump_feasibility; then derror "Starting kdump: [FAILED]" return 1 fi
- check_config
- if [[ $? -ne 0 ]]; then
- if ! check_config; then derror "Starting kdump: [FAILED]" return 1 fi
@@ -1078,14 +1053,12 @@ start() selinux_relabel fi
- save_raw
- if [[ $? -ne 0 ]]; then
- if ! save_raw; then derror "Starting kdump: [FAILED]" return 1 fi
- check_current_status
- if [[ $? == 0 ]]; then
- if check_current_status; then dwarn "Kdump already running: [WARNING]" return 0 fi
@@ -1097,14 +1070,12 @@ start() fi fi
- check_rebuild
- if [[ $? != 0 ]]; then
- if ! check_rebuild; then derror "Starting kdump: [FAILED]" return 1 fi
- start_dump
- if [[ $? != 0 ]]; then
- if ! start_dump; then derror "Starting kdump: [FAILED]" return 1 fi
@@ -1114,8 +1085,7 @@ start()
reload() {
- check_current_status
- if [[ $? -ne 0 ]]; then
- if ! check_current_status; then dwarn "Kdump was not running: [WARNING]" fi
@@ -1123,24 +1093,20 @@ reload() reload_fadump return $? else
stop_kdump
- fi
- if [[ $? -ne 0 ]]; then
derror "Stopping kdump: [FAILED]"
return 1
if ! stop_kdump; then
derror "Stopping kdump: [FAILED]"
return 1
fi
fi
dinfo "Stopping kdump: [OK]"
- setup_initrd
- if [[ $? -ne 0 ]]; then
- if ! setup_initrd; then derror "Starting kdump: [FAILED]" return 1 fi
- start_dump
- if [[ $? -ne 0 ]]; then
- if ! start_dump; then derror "Starting kdump: [FAILED]" return 1 fi
@@ -1168,6 +1134,7 @@ stop_kdump() $KEXEC -p -u fi
- # shellcheck disable=SC2181 if [[ $? != 0 ]]; then derror "kexec: failed to unload kdump kernel" return 1
@@ -1179,16 +1146,14 @@ stop_kdump()
reload_fadump() {
- echo 1 > $FADUMP_REGISTER_SYS_NODE
- if [[ $? == 0 ]]; then
- if echo 1 > $FADUMP_REGISTER_SYS_NODE; then dinfo "fadump: re-registered successfully" return 0 else # FADump could fail on older kernel where re-register # support is not enabled. Try stop/start from userspace # to handle such scenario.
stop_fadump
if [[ $? == 0 ]]; then
fiif stop_fadump; then start_fadump return $?
@@ -1205,6 +1170,7 @@ stop() stop_kdump fi
- # shellcheck disable=SC2181 if [[ $? != 0 ]]; then derror "Stopping kdump: [FAILED]" return 1
@@ -1215,10 +1181,7 @@ stop() }
rebuild() {
- check_config
- if [[ $? -ne 0 ]]; then
return 1
- fi
check_config || return 1
if check_ssh_config; then if ! check_ssh_target; then
@@ -1226,10 +1189,7 @@ rebuild() { fi fi
- setup_initrd
- if [[ $? -ne 0 ]]; then
return 1
- fi
setup_initrd || return 1
dinfo "Rebuilding $TARGET_INITRD" rebuild_initrd
diff --git a/mkdumprd b/mkdumprd index 9800934e..a2c6ed29 100644 --- a/mkdumprd +++ b/mkdumprd @@ -17,8 +17,7 @@ fi export IN_KDUMP=1
#initiate the kdump logger -dlog_init -if [[ $? -ne 0 ]]; then +if ! dlog_init; then echo "failed to initiate the kdump logger." exit 1 fi @@ -114,18 +113,12 @@ mkdir_save_path_ssh() { local _opt _dir _opt=(-i "$SSH_KEY_LOCATION" -o BatchMode=yes -o StrictHostKeyChecking=yes)
- ssh -qn "${_opt[@]}" "$1" mkdir -p "$SAVE_PATH" 2>&1 > /dev/null
- _ret=$?
- if [[ $_ret -ne 0 ]]; then
- ssh -qn "${_opt[@]}" "$1" mkdir -p "$SAVE_PATH" &>/dev/null || \ perror_exit "mkdir failed on $1:$SAVE_PATH"
fi
#check whether user has write permission on $1:$SAVE_PATH
_dir=$(ssh -qn "${_opt[@]}" "$1" mktemp -dqp "$SAVE_PATH" 2>/dev/null)
_ret=$?
if [[ $_ret -ne 0 ]]; then
- # check whether user has write permission on $1:$SAVE_PATH
- _dir=$(ssh -qn "${_opt[@]}" "$1" mktemp -dqp "$SAVE_PATH" 2>/dev/null) || \ perror_exit "Could not create temporary directory on $1:$SAVE_PATH. Make sure user has write permission on destination"
fi ssh -qn "${_opt[@]}" "$1" rmdir "$_dir"
return 0
@@ -162,11 +155,7 @@ check_size() { ;; *) return
- esac
- if [[ $? -ne 0 ]]; then
perror_exit "Check dump target size failed"
- fi
esac || perror_exit "Check dump target size failed"
if [[ "$avail" -lt "$memtotal" ]]; then dwarn "Warning: There might not be enough space to save a vmcore."
@@ -227,8 +216,7 @@ check_user_configured_target() if [[ -n "$_mnt" ]]; then if ! is_mounted "$_mnt"; then if [[ $_opt = *",noauto"* ]]; then
mount "$_mnt"
[[ $? -ne 0 ]] && mount_failure "$_target" "$_mnt" "$_fstype"
mount "$_mnt" || mount_failure "$_target" "$_mnt" "$_fstype" _mounted=$_mnt else perror_exit "Dump target \"$_target\" is neither mounted nor configured as \"noauto\""
@@ -237,8 +225,7 @@ check_user_configured_target() else _mnt=$MKDUMPRD_TMPMNT mkdir -p "$_mnt"
mount "$_target" "$_mnt" -t "$_fstype" -o defaults
[[ $? -ne 0 ]] && mount_failure "$_target" "" "$_fstype"
fimount "$_target" "$_mnt" -t "$_fstype" -o defaults || mount_failure "$_target" "" "$_fstype" _mounted=$_mnt
@@ -283,11 +270,9 @@ verify_core_collector() { }
add_mount() {
- local _mnt=$(to_mount "$@")
- local _mnt
- if [[ $? -ne 0 ]]; then
exit 1
- fi
_mnt=$(to_mount "$@") || exit 1
add_dracut_mount "$_mnt"
} @@ -349,15 +334,12 @@ is_unresettable() #return true if resettable check_resettable() {
- local _ret _target _override_resettable
local _target _override_resettable
_override_resettable=$(kdump_get_conf_val override_resettable) OVERRIDE_RESETTABLE=${_override_resettable:-$OVERRIDE_RESETTABLE}
- for_each_block_target is_unresettable
- _ret=$?
- [[ $_ret -eq 0 ]] && return
for_each_block_target is_unresettable && return
return 1
}
2.31.1 _______________________________________________ kexec mailing list -- kexec@lists.fedoraproject.org To unsubscribe send an email to kexec-leave@lists.fedoraproject.org Fedora Code of Conduct: https://docs.fedoraproject.org/en-US/project/code-of-conduct/ List Guidelines: https://fedoraproject.org/wiki/Mailing_list_guidelines List Archives: https://lists.fedoraproject.org/archives/list/kexec@lists.fedoraproject.org Do not reply to spam on the list, report it: https://pagure.io/fedora-infrastructure
On Wed, Sep 1, 2021 at 2:56 PM Coiby Xu coxu@redhat.com wrote:
On Thu, Aug 19, 2021 at 07:39:27PM +0800, Kairui Song wrote:
As suggested by: https://github.com/koalaman/shellcheck/wiki/SC2181
Signed-off-by: Kairui Song kasong@redhat.com
dracut-module-setup.sh | 41 ++++++--------- kdumpctl | 112 +++++++++++++---------------------------- mkdumprd | 40 ++++----------- 3 files changed, 61 insertions(+), 132 deletions(-)
diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index 600bdc51..46c0087a 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -255,8 +255,7 @@ kdump_static_ip() { _gateway="[$_gateway]" else _prefix=$(cut -d'/' -f2 <<< "$_ipaddr")
_netmask=$(cal_netmask_by_prefix "$_prefix" "$_ipv6_flag")
if [[ "$?" -ne 0 ]]; then
if ! _netmask=$(cal_netmask_by_prefix "$_prefix" "$_ipv6_flag"); then derror "Failed to calculate netmask for $_ipaddr" exit 1 fi
@@ -358,10 +357,7 @@ kdump_setup_bridge() { [[ -e $_dev ]] || continue _kdumpdev=$_dev if kdump_is_bond "$_dev"; then
$(kdump_setup_bond "$_dev" "$(get_nmcli_connection_show_cmd_by_ifname "$_dev")")
if [[ $? != 0 ]]; then
exit 1
fi
$(kdump_setup_bond "$_dev" "$(get_nmcli_connection_show_cmd_by_ifname "$_dev")") || exit 1
The above codes which was originally introduced by me breaks SC2091. I think we can use "()" to replace "$()"
elif kdump_is_team "$_dev"; then kdump_setup_team "$_dev" elif kdump_is_vlan "$_dev"; then
@@ -419,9 +415,7 @@ kdump_setup_team() { echo " team=$_netdev:${_slaves%,}" >> "${initdir}/etc/cmdline.d/44team.conf" #Buggy version teamdctl outputs to stderr! #Try to use the latest version of teamd.
- teamdctl "$_netdev" config dump > "${initdir}/tmp/$$-$_netdev.conf"
- if [[ $? -ne 0 ]]
- then
- if ! teamdctl "$_netdev" config dump > "${initdir}/tmp/$$-$_netdev.conf"; then derror "teamdctl failed." exit 1 fi
@@ -441,10 +435,7 @@ kdump_setup_vlan() { derror "Vlan over bridge is not supported!" exit 1 elif kdump_is_bond "$_phydev"; then
$(kdump_setup_bond "$_phydev" "$(get_nmcli_connection_show_cmd_by_ifname "$_phydev")")
if [[ $? != 0 ]]; then
exit 1
fi
$(kdump_setup_bond "$_phydev" "$(get_nmcli_connection_show_cmd_by_ifname "$_phydev")") || exit 1
Here too.
echo " vlan=$(kdump_setup_ifname "$_netdev"):$_phydev" > "${initdir}/etc/cmdline.d/43vlan.conf" else _kdumpdev="$(kdump_setup_ifname "$_phydev")"
@@ -515,8 +506,8 @@ kdump_setup_znet() {
kdump_get_ip_route() {
- local _route=$(/sbin/ip -o route get to "$1" 2>&1)
- if [[ $? != 0 ]]; then
- local _route
- if ! _route=$(/sbin/ip -o route get to "$1" 2>&1); then derror "Bad kdump network destination: $1" exit 1 fi
@@ -560,8 +551,7 @@ kdump_install_net() { _znet_netdev=$(find_online_znet_device) if [[ -n "$_znet_netdev" ]]; then _nm_show_cmd_znet=$(get_nmcli_connection_show_cmd_by_ifname "$_znet_netdev")
$(kdump_setup_znet "$_znet_netdev" "$_nm_show_cmd_znet")
if [[ $? != 0 ]]; then
if ! $(kdump_setup_znet "$_znet_netdev" "$_nm_show_cmd_znet"); then
And here.
derror "Failed to set up znet" exit 1 fi
@@ -591,10 +581,7 @@ kdump_install_net() { if kdump_is_bridge "$_netdev"; then kdump_setup_bridge "$_netdev" elif kdump_is_bond "$_netdev"; then
$(kdump_setup_bond "$_netdev" "$_nm_show_cmd")
if [[ $? != 0 ]]; then
exit 1
fi
elif kdump_is_team "$_netdev"; then kdump_setup_team "$_netdev" elif kdump_is_vlan "$_netdev"; then$(kdump_setup_bond "$_netdev" "$_nm_show_cmd") || exit 1
@@ -836,8 +823,10 @@ kdump_setup_iscsi_device() { fi
# Setup initator
- initiator_str=$(kdump_get_iscsi_initiator)
- [[ $? -ne "0" ]] && derror "Failed to get initiator name" && return 1
if ! initiator_str=$(kdump_get_iscsi_initiator); then
derror "Failed to get initiator name"
return 1
fi
# If initiator details do not exist already, append. if ! grep -q "$initiator_str" "$netroot_conf"; then
@@ -877,8 +866,7 @@ get_alias() { for ip in $ips do # in /etc/hosts, alias can come at the 2nd column
entries=$(grep "$ip" /etc/hosts | awk '{ $1=""; print $0 }')
if [[ $? -eq 0 ]]; then
doneif entries=$(grep "$ip" /etc/hosts | awk '{ $1=""; print $0 }'); then alias_set="$alias_set $entries" fi
@@ -1003,8 +991,7 @@ kdump_install_random_seed() { kdump_install_systemd_conf() { # Kdump turns out to require longer default systemd mount timeout # than 1st kernel(90s by default), we use default 300s for kdump.
- grep -r "^[[:space:]]*DefaultTimeoutStartSec=" "${initdir}/etc/systemd/system.conf"* &>/dev/null
- if [[ $? -ne 0 ]]; then
- if ! grep -q -r "^[[:space:]]*DefaultTimeoutStartSec=" "${initdir}/etc/systemd/system.conf"*; then mkdir -p "${initdir}/etc/systemd/system.conf.d" echo "[Manager]" > "${initdir}/etc/systemd/system.conf.d/kdump.conf" echo "DefaultTimeoutStartSec=300s" >> "${initdir}/etc/systemd/system.conf.d/kdump.conf"
diff --git a/kdumpctl b/kdumpctl index f65f8e3d..ecfe3d77 100755 --- a/kdumpctl +++ b/kdumpctl @@ -37,8 +37,7 @@ fi . /lib/kdump/kdump-logger.sh
#initiate the kdump logger -dlog_init -if [[ $? -ne 0 ]]; then +if ! dlog_init; then echo "failed to initiate the kdump logger." exit 1 fi @@ -47,8 +46,7 @@ single_instance_lock() { local rc timeout=5
exec 9>/var/lock/kdump
if [[ $? -ne 0 ]]; then
if ! exec 9>/var/lock/kdump; then derror "Create file lock failed" exit 1 fi
@@ -80,8 +78,7 @@ save_core()
mkdir -p "$coredir" ddebug "cp --sparse=always /proc/vmcore $coredir/vmcore-incomplete"
cp --sparse=always /proc/vmcore "$coredir/vmcore-incomplete"
if [[ $? == 0 ]]; then
if cp --sparse=always /proc/vmcore "$coredir/vmcore-incomplete"; then mv "$coredir/vmcore-incomplete" "$coredir/vmcore" dinfo "saved a vmcore to $coredir" else
@@ -95,8 +92,7 @@ save_core() ddebug "makedumpfile --dump-dmesg $coredir/vmcore $coredir/dmesg" makedumpfile --dump-dmesg "$coredir/vmcore" "$coredir/dmesg" >/dev/null 2>&1 ddebug "dumpoops -d $coredir/dmesg"
dumpoops -d "$coredir/dmesg" >/dev/null 2>&1
if [[ $? == 0 ]]; then
if dumpoops -d "$coredir/dmesg" >/dev/null 2>&1; then dinfo "kernel oops has been collected by abrt tool" fi fi
@@ -121,8 +117,7 @@ check_earlykdump_is_enabled() rebuild_kdump_initrd() { ddebug "rebuild kdump initrd: $MKDUMPRD $TARGET_INITRD $KDUMP_KERNELVER"
$MKDUMPRD "$TARGET_INITRD" "$KDUMP_KERNELVER"
if [[ $? != 0 ]]; then
if ! $MKDUMPRD "$TARGET_INITRD" "$KDUMP_KERNELVER"; then derror "mkdumprd: failed to make kdump initrd" return 1 fi
@@ -184,8 +179,7 @@ backup_default_initrd() dinfo "Backing up $DEFAULT_INITRD before rebuild." # save checksum to verify before restoring sha1sum "$DEFAULT_INITRD" > "$INITRD_CHECKSUM_LOCATION"
cp "$DEFAULT_INITRD" "$DEFAULT_INITRD_BAK"
if [[ $? -ne 0 ]]; then
if ! cp "$DEFAULT_INITRD" "$DEFAULT_INITRD_BAK"; then dwarn "WARNING: failed to backup $DEFAULT_INITRD." rm -f "$DEFAULT_INITRD_BAK" fi
@@ -210,8 +204,7 @@ restore_default_initrd() dwarn "WARNING: checksum mismatch! Can't restore original initrd.." else rm -f $INITRD_CHECKSUM_LOCATION
mv "$DEFAULT_INITRD_BAK" "$DEFAULT_INITRD"
if [[ $? -eq 0 ]]; then
if mv "$DEFAULT_INITRD_BAK" "$DEFAULT_INITRD"; then derror "Restoring original initrd as fadump mode is disabled." sync fi
@@ -308,8 +301,7 @@ get_pcs_cluster_modified_files()
setup_initrd() {
prepare_kdump_bootinfo
if [[ $? -ne 0 ]]; then
if ! prepare_kdump_bootinfo; then derror "failed to prepare for kdump bootinfo." return 1 fi
@@ -372,8 +364,7 @@ check_files_modified() files="$files /lib/modules/$KDUMP_KERNELVER/modules.dep" fi for _module in $EXTRA_MODULES; do
_module_file="$(modinfo --set-version "$KDUMP_KERNELVER" --filename "$_module" 2>/dev/null)"
if [[ $? -eq 0 ]]; then
if _module_file="$(modinfo --set-version "$KDUMP_KERNELVER" --filename "$_module" 2>/dev/null)"; then files="$files $_module_file" for _dep_modules in $(modinfo -F depends "$_module" | tr ',' ' '); do files="$files $(modinfo --set-version "$KDUMP_KERNELVER" --filename "$_dep_modules" 2>/dev/null)"
@@ -389,8 +380,7 @@ check_files_modified()
# HOOKS is mandatory and need to check the modification time files="$files $HOOKS"
check_exist "$files" && check_executable "$EXTRA_BINS"
[[ $? -ne 0 ]] && return 2
check_exist "$files" && check_executable "$EXTRA_BINS" || return 2 for file in $files; do if [[ -e "$file" ]]; then
@@ -455,7 +445,7 @@ check_drivers_modified() # Skip deprecated/invalid driver name or built-in module _module_name=$(modinfo --set-version "$KDUMP_KERNELVER" -F name "$_driver" 2>/dev/null) _module_filename=$(modinfo --set-version "$KDUMP_KERNELVER" -n "$_driver" 2>/dev/null)
if [[ $? -ne 0 ]] || [[ -z "$_module_name" ]] || [[ "$_module_filename" = *"(builtin)"* ]]; then
if [[ -z "$_module_name" ]] || [[ -z "$_module_filename" ]] || [[ "$_module_filename" = *"(builtin)"* ]]; then continue fi if ! [[ " $_old_drivers " == *" $_module_name "* ]]; then
@@ -505,8 +495,7 @@ check_fs_modified()
# if --mount argument present then match old and new target, mount # point and file system. If any of them mismatches then rebuild
echo "$_dracut_args" | grep "\-\-mount" &> /dev/null
if [[ $? -eq 0 ]];then
if echo "$_dracut_args" | grep "\-\-mount" &> /dev/null; then # shellcheck disable=SC2046 set -- $(echo "$_dracut_args" | awk -F "--mount '" '{print $2}' | cut -d' ' -f1,2,3) _old_dev=$1
@@ -558,11 +547,7 @@ check_rebuild() local force_rebuild force_no_rebuild local ret system_modified="0"
setup_initrd
if [[ $? -ne 0 ]]; then
return 1
fi
setup_initrd || return 1 force_no_rebuild=$(kdump_get_conf_val force_no_rebuild) force_no_rebuild=${force_no_rebuild:-0}
@@ -761,8 +746,7 @@ check_and_wait_network_ready()
# if server removes the authorized_keys or, no /root/.ssh/kdump_id_rsa ddebug "$errmsg"
echo "$errmsg" | grep -q "Permission denied\|No such file or directory\|Host key verification failed" &> /dev/null
if [[ $? -eq 0 ]]; then
if echo "$errmsg" | grep -q "Permission denied\|No such file or directory\|Host key verification failed" &> /dev/null; then derror "Could not create $DUMP_TARGET:$SAVE_PATH, you probably need to run \"kdumpctl propagate\"" return 1 fi
@@ -788,16 +772,11 @@ check_and_wait_network_ready() check_ssh_target() { check_and_wait_network_ready
if [[ $? -ne 0 ]]; then
return 1
fi
return 0
}
propagate_ssh_key() {
check_ssh_config
if [[ $? -ne 0 ]]; then
if ! check_ssh_config; then derror "No ssh config specified in $KDUMP_CONFIG_FILE. Can't propagate" exit 1 fi
@@ -904,8 +883,7 @@ local_fs_dump_target() { local _target
_target=$(egrep "^ext[234]|^xfs|^btrfs|^minix" /etc/kdump.conf)
if [[ $? -eq 0 ]]; then
if _target=$(grep -E "^ext[234]|^xfs|^btrfs|^minix" /etc/kdump.conf); then echo "$_target" | awk '{print $2}' fi
} @@ -967,8 +945,7 @@ check_fence_kdump_config() return 1 fi # node can be ipaddr
echo "$ipaddrs " | grep "$node " > /dev/null
if [[ $? -eq 0 ]]; then
if echo "$ipaddrs " | grep "$node " > /dev/null; then derror "Option fence_kdump_nodes cannot contain $node" return 1 fi
@@ -1062,14 +1039,12 @@ check_final_action_config()
start() {
check_dump_feasibility
if [[ $? -ne 0 ]]; then
if ! check_dump_feasibility; then derror "Starting kdump: [FAILED]" return 1 fi
check_config
if [[ $? -ne 0 ]]; then
if ! check_config; then derror "Starting kdump: [FAILED]" return 1 fi
@@ -1078,14 +1053,12 @@ start() selinux_relabel fi
save_raw
if [[ $? -ne 0 ]]; then
if ! save_raw; then derror "Starting kdump: [FAILED]" return 1 fi
check_current_status
if [[ $? == 0 ]]; then
if check_current_status; then dwarn "Kdump already running: [WARNING]" return 0 fi
@@ -1097,14 +1070,12 @@ start() fi fi
check_rebuild
if [[ $? != 0 ]]; then
if ! check_rebuild; then derror "Starting kdump: [FAILED]" return 1 fi
start_dump
if [[ $? != 0 ]]; then
if ! start_dump; then derror "Starting kdump: [FAILED]" return 1 fi
@@ -1114,8 +1085,7 @@ start()
reload() {
check_current_status
if [[ $? -ne 0 ]]; then
if ! check_current_status; then dwarn "Kdump was not running: [WARNING]" fi
@@ -1123,24 +1093,20 @@ reload() reload_fadump return $? else
stop_kdump
fi
if [[ $? -ne 0 ]]; then
derror "Stopping kdump: [FAILED]"
return 1
if ! stop_kdump; then
derror "Stopping kdump: [FAILED]"
return 1
fi fi dinfo "Stopping kdump: [OK]"
setup_initrd
if [[ $? -ne 0 ]]; then
if ! setup_initrd; then derror "Starting kdump: [FAILED]" return 1 fi
start_dump
if [[ $? -ne 0 ]]; then
if ! start_dump; then derror "Starting kdump: [FAILED]" return 1 fi
@@ -1168,6 +1134,7 @@ stop_kdump() $KEXEC -p -u fi
# shellcheck disable=SC2181 if [[ $? != 0 ]]; then derror "kexec: failed to unload kdump kernel" return 1
@@ -1179,16 +1146,14 @@ stop_kdump()
reload_fadump() {
echo 1 > $FADUMP_REGISTER_SYS_NODE
if [[ $? == 0 ]]; then
if echo 1 > $FADUMP_REGISTER_SYS_NODE; then dinfo "fadump: re-registered successfully" return 0 else # FADump could fail on older kernel where re-register # support is not enabled. Try stop/start from userspace # to handle such scenario.
stop_fadump
if [[ $? == 0 ]]; then
if stop_fadump; then start_fadump return $? fi
@@ -1205,6 +1170,7 @@ stop() stop_kdump fi
# shellcheck disable=SC2181 if [[ $? != 0 ]]; then derror "Stopping kdump: [FAILED]" return 1
@@ -1215,10 +1181,7 @@ stop() }
rebuild() {
check_config
if [[ $? -ne 0 ]]; then
return 1
fi
check_config || return 1 if check_ssh_config; then if ! check_ssh_target; then
@@ -1226,10 +1189,7 @@ rebuild() { fi fi
setup_initrd
if [[ $? -ne 0 ]]; then
return 1
fi
setup_initrd || return 1 dinfo "Rebuilding $TARGET_INITRD" rebuild_initrd
diff --git a/mkdumprd b/mkdumprd index 9800934e..a2c6ed29 100644 --- a/mkdumprd +++ b/mkdumprd @@ -17,8 +17,7 @@ fi export IN_KDUMP=1
#initiate the kdump logger -dlog_init -if [[ $? -ne 0 ]]; then +if ! dlog_init; then echo "failed to initiate the kdump logger." exit 1 fi @@ -114,18 +113,12 @@ mkdir_save_path_ssh() { local _opt _dir _opt=(-i "$SSH_KEY_LOCATION" -o BatchMode=yes -o StrictHostKeyChecking=yes)
- ssh -qn "${_opt[@]}" "$1" mkdir -p "$SAVE_PATH" 2>&1 > /dev/null
- _ret=$?
- if [[ $_ret -ne 0 ]]; then
- ssh -qn "${_opt[@]}" "$1" mkdir -p "$SAVE_PATH" &>/dev/null || \ perror_exit "mkdir failed on $1:$SAVE_PATH"
fi
#check whether user has write permission on $1:$SAVE_PATH
_dir=$(ssh -qn "${_opt[@]}" "$1" mktemp -dqp "$SAVE_PATH" 2>/dev/null)
_ret=$?
if [[ $_ret -ne 0 ]]; then
- # check whether user has write permission on $1:$SAVE_PATH
- _dir=$(ssh -qn "${_opt[@]}" "$1" mktemp -dqp "$SAVE_PATH" 2>/dev/null) || \ perror_exit "Could not create temporary directory on $1:$SAVE_PATH. Make sure user has write permission on destination"
fi ssh -qn "${_opt[@]}" "$1" rmdir "$_dir"
return 0
@@ -162,11 +155,7 @@ check_size() { ;; *) return
- esac
- if [[ $? -ne 0 ]]; then
perror_exit "Check dump target size failed"
- fi
esac || perror_exit "Check dump target size failed"
if [[ "$avail" -lt "$memtotal" ]]; then dwarn "Warning: There might not be enough space to save a vmcore."
@@ -227,8 +216,7 @@ check_user_configured_target() if [[ -n "$_mnt" ]]; then if ! is_mounted "$_mnt"; then if [[ $_opt = *",noauto"* ]]; then
mount "$_mnt"
[[ $? -ne 0 ]] && mount_failure "$_target" "$_mnt" "$_fstype"
mount "$_mnt" || mount_failure "$_target" "$_mnt" "$_fstype" _mounted=$_mnt else perror_exit "Dump target \"$_target\" is neither mounted nor configured as \"noauto\""
@@ -237,8 +225,7 @@ check_user_configured_target() else _mnt=$MKDUMPRD_TMPMNT mkdir -p "$_mnt"
mount "$_target" "$_mnt" -t "$_fstype" -o defaults
[[ $? -ne 0 ]] && mount_failure "$_target" "" "$_fstype"
fimount "$_target" "$_mnt" -t "$_fstype" -o defaults || mount_failure "$_target" "" "$_fstype" _mounted=$_mnt
@@ -283,11 +270,9 @@ verify_core_collector() { }
add_mount() {
- local _mnt=$(to_mount "$@")
- local _mnt
- if [[ $? -ne 0 ]]; then
exit 1
- fi
_mnt=$(to_mount "$@") || exit 1
add_dracut_mount "$_mnt"
} @@ -349,15 +334,12 @@ is_unresettable() #return true if resettable check_resettable() {
- local _ret _target _override_resettable
local _target _override_resettable
_override_resettable=$(kdump_get_conf_val override_resettable) OVERRIDE_RESETTABLE=${_override_resettable:-$OVERRIDE_RESETTABLE}
- for_each_block_target is_unresettable
- _ret=$?
- [[ $_ret -eq 0 ]] && return
for_each_block_target is_unresettable && return
return 1
}
2.31.1 _______________________________________________ kexec mailing list -- kexec@lists.fedoraproject.org To unsubscribe send an email to kexec-leave@lists.fedoraproject.org Fedora Code of Conduct: https://docs.fedoraproject.org/en-US/project/code-of-conduct/ List Guidelines: https://fedoraproject.org/wiki/Mailing_list_guidelines List Archives: https://lists.fedoraproject.org/archives/list/kexec@lists.fedoraproject.org Do not reply to spam on the list, report it: https://pagure.io/fedora-infrastructure
-- Best regards, Coiby
Good idea, I didn't change this part since I'm not entirely sure about the context and if this is safe, I can update the code then.
-- Best Regards, Kairui Song
Hi Kairui,
On Thu, 19 Aug 2021 19:39:27 +0800 Kairui Song kasong@redhat.com wrote:
As suggested by: https://github.com/koalaman/shellcheck/wiki/SC2181
Signed-off-by: Kairui Song kasong@redhat.com
dracut-module-setup.sh | 41 ++++++--------- kdumpctl | 112 +++++++++++++---------------------------- mkdumprd | 40 ++++----------- 3 files changed, 61 insertions(+), 132 deletions(-)
[...]
diff --git a/kdumpctl b/kdumpctl index f65f8e3d..ecfe3d77 100755 --- a/kdumpctl +++ b/kdumpctl
[...]
@@ -761,8 +746,7 @@ check_and_wait_network_ready()
# if server removes the authorized_keys or, no /root/.ssh/kdump_id_rsa ddebug "$errmsg"
echo "$errmsg" | grep -q "Permission denied\|No such file or directory\|Host key verification failed" &> /dev/null
if [[ $? -eq 0 ]]; then
if echo "$errmsg" | grep -q "Permission denied\|No such file or directory\|Host key verification failed" &> /dev/null; then
^^ -q already suppresses any output to stdout. No need to redirect it to /dev/null.
derror "Could not create $DUMP_TARGET:$SAVE_PATH, you probably need to run \"kdumpctl propagate\"" return 1 fi
@@ -788,16 +772,11 @@ check_and_wait_network_ready() check_ssh_target() { check_and_wait_network_ready
- if [[ $? -ne 0 ]]; then
return 1
- fi
- return 0
}
propagate_ssh_key() {
- check_ssh_config
- if [[ $? -ne 0 ]]; then
- if ! check_ssh_config; then derror "No ssh config specified in $KDUMP_CONFIG_FILE. Can't propagate" exit 1 fi
@@ -904,8 +883,7 @@ local_fs_dump_target() { local _target
- _target=$(egrep "^ext[234]|^xfs|^btrfs|^minix" /etc/kdump.conf)
- if [[ $? -eq 0 ]]; then
- if _target=$(grep -E "^ext[234]|^xfs|^btrfs|^minix" /etc/kdump.conf); then echo "$_target" | awk '{print $2}' fi
} @@ -967,8 +945,7 @@ check_fence_kdump_config() return 1 fi # node can be ipaddr
echo "$ipaddrs " | grep "$node " > /dev/null
if [[ $? -eq 0 ]]; then
if echo "$ipaddrs " | grep "$node " > /dev/null; then
You could use grep -q instead of redirecting to /dev/null. There's an other case in check_fs_modified and kdump-lib.sh. The other findings from
git grep -E "grep.*>\s*/dev/null"
look ok to me. Maybe in general review all redirects to /dev/null and check if they could be omitted with a quiet option.
Thanks Philipp
derror "Option fence_kdump_nodes cannot contain $node" return 1 fi
@@ -1062,14 +1039,12 @@ check_final_action_config()
start() {
- check_dump_feasibility
- if [[ $? -ne 0 ]]; then
- if ! check_dump_feasibility; then derror "Starting kdump: [FAILED]" return 1 fi
- check_config
- if [[ $? -ne 0 ]]; then
- if ! check_config; then derror "Starting kdump: [FAILED]" return 1 fi
@@ -1078,14 +1053,12 @@ start() selinux_relabel fi
- save_raw
- if [[ $? -ne 0 ]]; then
- if ! save_raw; then derror "Starting kdump: [FAILED]" return 1 fi
- check_current_status
- if [[ $? == 0 ]]; then
- if check_current_status; then dwarn "Kdump already running: [WARNING]" return 0 fi
@@ -1097,14 +1070,12 @@ start() fi fi
- check_rebuild
- if [[ $? != 0 ]]; then
- if ! check_rebuild; then derror "Starting kdump: [FAILED]" return 1 fi
- start_dump
- if [[ $? != 0 ]]; then
- if ! start_dump; then derror "Starting kdump: [FAILED]" return 1 fi
@@ -1114,8 +1085,7 @@ start()
reload() {
- check_current_status
- if [[ $? -ne 0 ]]; then
- if ! check_current_status; then dwarn "Kdump was not running: [WARNING]" fi
@@ -1123,24 +1093,20 @@ reload() reload_fadump return $? else
stop_kdump
- fi
- if [[ $? -ne 0 ]]; then
derror "Stopping kdump: [FAILED]"
return 1
if ! stop_kdump; then
derror "Stopping kdump: [FAILED]"
return 1
fi
fi
dinfo "Stopping kdump: [OK]"
- setup_initrd
- if [[ $? -ne 0 ]]; then
- if ! setup_initrd; then derror "Starting kdump: [FAILED]" return 1 fi
- start_dump
- if [[ $? -ne 0 ]]; then
- if ! start_dump; then derror "Starting kdump: [FAILED]" return 1 fi
@@ -1168,6 +1134,7 @@ stop_kdump() $KEXEC -p -u fi
- # shellcheck disable=SC2181 if [[ $? != 0 ]]; then derror "kexec: failed to unload kdump kernel" return 1
@@ -1179,16 +1146,14 @@ stop_kdump()
reload_fadump() {
- echo 1 > $FADUMP_REGISTER_SYS_NODE
- if [[ $? == 0 ]]; then
- if echo 1 > $FADUMP_REGISTER_SYS_NODE; then dinfo "fadump: re-registered successfully" return 0 else # FADump could fail on older kernel where re-register # support is not enabled. Try stop/start from userspace # to handle such scenario.
stop_fadump
if [[ $? == 0 ]]; then
fiif stop_fadump; then start_fadump return $?
@@ -1205,6 +1170,7 @@ stop() stop_kdump fi
- # shellcheck disable=SC2181 if [[ $? != 0 ]]; then derror "Stopping kdump: [FAILED]" return 1
@@ -1215,10 +1181,7 @@ stop() }
rebuild() {
- check_config
- if [[ $? -ne 0 ]]; then
return 1
- fi
check_config || return 1
if check_ssh_config; then if ! check_ssh_target; then
@@ -1226,10 +1189,7 @@ rebuild() { fi fi
- setup_initrd
- if [[ $? -ne 0 ]]; then
return 1
- fi
setup_initrd || return 1
dinfo "Rebuilding $TARGET_INITRD" rebuild_initrd
diff --git a/mkdumprd b/mkdumprd index 9800934e..a2c6ed29 100644 --- a/mkdumprd +++ b/mkdumprd @@ -17,8 +17,7 @@ fi export IN_KDUMP=1
#initiate the kdump logger -dlog_init -if [[ $? -ne 0 ]]; then +if ! dlog_init; then echo "failed to initiate the kdump logger." exit 1 fi @@ -114,18 +113,12 @@ mkdir_save_path_ssh() { local _opt _dir _opt=(-i "$SSH_KEY_LOCATION" -o BatchMode=yes -o StrictHostKeyChecking=yes)
- ssh -qn "${_opt[@]}" "$1" mkdir -p "$SAVE_PATH" 2>&1 > /dev/null
- _ret=$?
- if [[ $_ret -ne 0 ]]; then
- ssh -qn "${_opt[@]}" "$1" mkdir -p "$SAVE_PATH" &>/dev/null || \ perror_exit "mkdir failed on $1:$SAVE_PATH"
fi
#check whether user has write permission on $1:$SAVE_PATH
_dir=$(ssh -qn "${_opt[@]}" "$1" mktemp -dqp "$SAVE_PATH" 2>/dev/null)
_ret=$?
if [[ $_ret -ne 0 ]]; then
- # check whether user has write permission on $1:$SAVE_PATH
- _dir=$(ssh -qn "${_opt[@]}" "$1" mktemp -dqp "$SAVE_PATH" 2>/dev/null) || \ perror_exit "Could not create temporary directory on $1:$SAVE_PATH. Make sure user has write permission on destination"
fi ssh -qn "${_opt[@]}" "$1" rmdir "$_dir"
return 0
@@ -162,11 +155,7 @@ check_size() { ;; *) return
- esac
- if [[ $? -ne 0 ]]; then
perror_exit "Check dump target size failed"
- fi
esac || perror_exit "Check dump target size failed"
if [[ "$avail" -lt "$memtotal" ]]; then dwarn "Warning: There might not be enough space to save a vmcore."
@@ -227,8 +216,7 @@ check_user_configured_target() if [[ -n "$_mnt" ]]; then if ! is_mounted "$_mnt"; then if [[ $_opt = *",noauto"* ]]; then
mount "$_mnt"
[[ $? -ne 0 ]] && mount_failure "$_target" "$_mnt" "$_fstype"
mount "$_mnt" || mount_failure "$_target" "$_mnt" "$_fstype" _mounted=$_mnt else perror_exit "Dump target \"$_target\" is neither mounted nor configured as \"noauto\""
@@ -237,8 +225,7 @@ check_user_configured_target() else _mnt=$MKDUMPRD_TMPMNT mkdir -p "$_mnt"
mount "$_target" "$_mnt" -t "$_fstype" -o defaults
[[ $? -ne 0 ]] && mount_failure "$_target" "" "$_fstype"
fimount "$_target" "$_mnt" -t "$_fstype" -o defaults || mount_failure "$_target" "" "$_fstype" _mounted=$_mnt
@@ -283,11 +270,9 @@ verify_core_collector() { }
add_mount() {
- local _mnt=$(to_mount "$@")
- local _mnt
- if [[ $? -ne 0 ]]; then
exit 1
- fi
_mnt=$(to_mount "$@") || exit 1
add_dracut_mount "$_mnt"
} @@ -349,15 +334,12 @@ is_unresettable() #return true if resettable check_resettable() {
- local _ret _target _override_resettable
local _target _override_resettable
_override_resettable=$(kdump_get_conf_val override_resettable) OVERRIDE_RESETTABLE=${_override_resettable:-$OVERRIDE_RESETTABLE}
- for_each_block_target is_unresettable
- _ret=$?
- [[ $_ret -eq 0 ]] && return
for_each_block_target is_unresettable && return
return 1
}
Declare and assign separately to avoid masking return values: https://github.com/koalaman/shellcheck/wiki/SC2155
Signed-off-by: Kairui Song kasong@redhat.com --- dracut-module-setup.sh | 22 +++++++++++++++------- kdumpctl | 17 ++++++++++++----- mkdumprd | 21 +++++++++++---------- mkfadumprd | 2 +- 4 files changed, 39 insertions(+), 23 deletions(-)
diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index 46c0087a..7f6a644e 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -321,7 +321,8 @@ kdump_get_mac_addr() { #Bonding or team master modifies the mac address #of its slaves, we should use perm address kdump_get_perm_addr() { - local addr=$(ethtool -P "$1" | sed -e 's/Permanent address: //') + local addr + addr=$(ethtool -P "$1" | sed -e 's/Permanent address: //') if [[ -z "$addr" ]] || [[ "$addr" = "00:00:00:00:00:00" ]] then derror "Can't get the permanent address of $1" @@ -426,10 +427,13 @@ kdump_setup_team() {
kdump_setup_vlan() { local _netdev=$1 - local _phydev="$(awk '/^Device:/{print $2}' /proc/net/vlan/"$_netdev")" - local _netmac="$(kdump_get_mac_addr "$_phydev")" + local _phydev + local _netmac local _kdumpdev
+ _phydev="$(awk '/^Device:/{print $2}' /proc/net/vlan/"$_netdev")" + _netmac="$(kdump_get_mac_addr "$_phydev")" + #Just support vlan over bond and team if kdump_is_bridge "$_phydev"; then derror "Vlan over bridge is not supported!" @@ -521,7 +525,8 @@ kdump_get_ip_route_field()
kdump_get_remote_ip() { - local _remote=$(get_remote_host "$1") _remote_temp + local _remote _remote_temp + _remote=$(get_remote_host "$1") if is_hostname "$_remote"; then _remote_temp=$(getent ahosts "$_remote" | grep -v : | head -n 1) if [[ -z "$_remote_temp" ]]; then @@ -875,11 +880,14 @@ get_alias() { }
is_localhost() { - local hostnames=$(hostname -A) - local shortnames=$(hostname -A -s) - local aliasname=$(get_alias) + local hostnames + local shortnames + local aliasname local nodename=$1
+ hostnames=$(hostname -A) + shortnames=$(hostname -A -s) + aliasname=$(get_alias) hostnames="$hostnames $shortnames $aliasname"
for name in ${hostnames}; do diff --git a/kdumpctl b/kdumpctl index ecfe3d77..f6cde221 100755 --- a/kdumpctl +++ b/kdumpctl @@ -690,6 +690,8 @@ load_kdump()
check_ssh_config() { + local SSH_TARGET + while read -r config_opt config_val; do case "$config_opt" in sshkey) @@ -713,7 +715,7 @@ check_ssh_config() done <<< "$(kdump_read_conf)"
#make sure they've configured kdump.conf for ssh dumps - local SSH_TARGET=$(echo -n "$DUMP_TARGET" | sed -n '/.*@/p') + SSH_TARGET=$(echo -n "$DUMP_TARGET" | sed -n '/.*@/p') if [[ -z "$SSH_TARGET" ]]; then return 1 fi @@ -725,13 +727,14 @@ check_ssh_config() # by the return val of 'ssh' check_and_wait_network_ready() { - local start_time=$(date +%s) + local start_time local warn_once=1 local cur local diff local retval local errmsg
+ start_time=$(date +%s) while true; do errmsg=$(ssh -i "$SSH_KEY_LOCATION" -o BatchMode=yes "$DUMP_TARGET" mkdir -p "$SAVE_PATH" 2>&1) retval=$? @@ -935,9 +938,13 @@ selinux_relabel()
check_fence_kdump_config() { - local hostname=$(hostname) - local ipaddrs=$(hostname -I) - local nodes=$(kdump_get_conf_val "fence_kdump_nodes") + local hostname + local ipaddrs + local nodes + + hostname=$(hostname) + ipaddrs=$(hostname -I) + nodes=$(kdump_get_conf_val "fence_kdump_nodes")
for node in $nodes; do if [[ "$node" = "$hostname" ]]; then diff --git a/mkdumprd b/mkdumprd index a2c6ed29..9c8ba232 100644 --- a/mkdumprd +++ b/mkdumprd @@ -29,9 +29,9 @@ OVERRIDE_RESETTABLE=0 extra_modules="" dracut_args=( --add kdumpbase --quiet --hostonly --hostonly-cmdline --hostonly-i18n --hostonly-mode strict -o "plymouth dash resume ifcfg earlykdump" )
-readonly MKDUMPRD_TMPDIR="$(mktemp -d -t mkdumprd.XXXXXX)" +MKDUMPRD_TMPDIR="$(mktemp -d -t mkdumprd.XXXXXX)" [ -d "$MKDUMPRD_TMPDIR" ] || perror_exit "dracut: mktemp -p -d -t dracut.XXXXXX failed." -readonly MKDUMPRD_TMPMNT="$MKDUMPRD_TMPDIR/target" +MKDUMPRD_TMPMNT="$MKDUMPRD_TMPDIR/target"
trap ' ret=$?; @@ -195,9 +195,11 @@ mount_failure() check_user_configured_target() { local _target=$1 _cfg_fs_type=$2 _mounted - local _mnt=$(get_mntpoint_from_target "$_target") - local _opt=$(get_mntopt_from_target "$_target") - local _fstype=$(get_fs_type_from_target "$_target") + local _mnt _opt _fstype + + _mnt=$(get_mntpoint_from_target "$_target") + _opt=$(get_mntopt_from_target "$_target") + _fstype=$(get_fs_type_from_target "$_target")
if [[ -n "$_fstype" ]]; then # In case of nfs4, nfs should be used instead, nfs* options is deprecated in kdump.conf @@ -314,14 +316,13 @@ for_each_block_target() #return false if unresettable. is_unresettable() { - local path="/sys/$(udevadm info --query=all --path="/sys/dev/block/$1" | awk '/^P:/ {print $2}' | sed -e 's/(cciss[0-9]+/).*/\1/g' -e 's//block/.*$//')/resettable" - local resettable=1 + local path device resettable=1
- if [[ -f "$path" ]] - then + path="/sys/$(udevadm info --query=all --path="/sys/dev/block/$1" | awk '/^P:/ {print $2}' | sed -e 's/(cciss[0-9]+/).*/\1/g' -e 's//block/.*$//')/resettable" + if [[ -f "$path" ]]; then resettable="$(<"$path")" [[ $resettable -eq 0 ]] && [[ "$OVERRIDE_RESETTABLE" -eq 0 ]] && { - local device=$(udevadm info --query=all --path="/sys/dev/block/$1" | awk -F= '/DEVNAME/{print $2}') + device=$(udevadm info --query=all --path="/sys/dev/block/$1" | awk -F= '/DEVNAME/{print $2}') derror "Error: Can not save vmcore because device $device is unresettable" return 0 } diff --git a/mkfadumprd b/mkfadumprd index ca9f362c..5c96ee75 100644 --- a/mkfadumprd +++ b/mkfadumprd @@ -17,7 +17,7 @@ if ! dlog_init; then exit 1 fi
-readonly MKFADUMPRD_TMPDIR="$(mktemp -d -t mkfadumprd.XXXXXX)" +MKFADUMPRD_TMPDIR="$(mktemp -d -t mkfadumprd.XXXXXX)" [ -d "$MKFADUMPRD_TMPDIR" ] || perror_exit "mkfadumprd: mktemp -d -t mkfadumprd.XXXXXX failed." trap ' ret=$?;
This is a batch update done with: shfmt -s -w mkfadumprd mkdumprd kdumpctl *-module-setup.sh
Clean up code style and reduce code base size, no behaviour change.
Signed-off-by: Kairui Song kasong@redhat.com --- dracut-early-kdump-module-setup.sh | 11 +- dracut-module-setup.sh | 320 ++++++++--------- kdumpctl | 274 +++++++------- mkdumprd | 550 +++++++++++++++-------------- mkfadumprd | 8 +- 5 files changed, 587 insertions(+), 576 deletions(-)
diff --git a/dracut-early-kdump-module-setup.sh b/dracut-early-kdump-module-setup.sh index 83e067c8..0e46823e 100755 --- a/dracut-early-kdump-module-setup.sh +++ b/dracut-early-kdump-module-setup.sh @@ -6,9 +6,8 @@ KDUMP_KERNEL="" KDUMP_INITRD=""
check() { - if [[ ! -f /etc/sysconfig/kdump ]] || [[ ! -f /lib/kdump/kdump-lib.sh ]]\ - || [[ -n "${IN_KDUMP}" ]] - then + if [[ ! -f /etc/sysconfig/kdump ]] || [[ ! -f /lib/kdump/kdump-lib.sh ]] \ + || [[ -n ${IN_KDUMP} ]]; then return 1 fi return 255 @@ -25,7 +24,7 @@ prepare_kernel_initrd() { prepare_kdump_bootinfo
# $kernel is a variable from dracut - if [[ "$KDUMP_KERNELVER" != "$kernel" ]]; then + if [[ $KDUMP_KERNELVER != "$kernel" ]]; then dwarn "Using kernel version '$KDUMP_KERNELVER' for early kdump," \ "but the initramfs is generated for kernel version '$kernel'" fi @@ -33,12 +32,12 @@ prepare_kernel_initrd() {
install() { prepare_kernel_initrd - if [[ ! -f "$KDUMP_KERNEL" ]]; then + if [[ ! -f $KDUMP_KERNEL ]]; then derror "Could not find required kernel for earlykdump," \ "earlykdump will not work!" return 1 fi - if [[ ! -f "$KDUMP_INITRD" ]]; then + if [[ ! -f $KDUMP_INITRD ]]; then derror "Could not find required kdump initramfs for earlykdump," \ "please ensure kdump initramfs is generated first," \ "earlykdump will not work!" diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index 7f6a644e..11db5aa3 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -11,8 +11,7 @@ kdump_module_init() { check() { [[ $debug ]] && set -x #kdumpctl sets this explicitly - if [[ -z "$IN_KDUMP" ]] || [[ ! -f /etc/kdump.conf ]] - then + if [[ -z $IN_KDUMP ]] || [[ ! -f /etc/kdump.conf ]]; then return 1 fi return 0 @@ -41,11 +40,11 @@ depends() { _dep="$_dep ssh-client" fi
- if [[ "$(uname -m)" = "s390x" ]]; then + if [[ "$(uname -m)" == "s390x" ]]; then _dep="$_dep znet" fi
- if [[ -n "$( ls -A /sys/class/drm 2>/dev/null )" ]] || [[ -d /sys/module/hyperv_fb ]]; then + if [[ -n "$(ls -A /sys/class/drm 2> /dev/null)" ]] || [[ -d /sys/module/hyperv_fb ]]; then add_opt_module drm fi
@@ -57,19 +56,19 @@ depends() { }
kdump_is_bridge() { - [[ -d /sys/class/net/"$1"/bridge ]] + [[ -d /sys/class/net/"$1"/bridge ]] }
kdump_is_bond() { - [[ -d /sys/class/net/"$1"/bonding ]] + [[ -d /sys/class/net/"$1"/bonding ]] }
kdump_is_team() { - [[ -f /usr/bin/teamnl ]] && teamnl "$1" ports &> /dev/null + [[ -f /usr/bin/teamnl ]] && teamnl "$1" ports &> /dev/null }
kdump_is_vlan() { - [[ -f /proc/net/vlan/"$1" ]] + [[ -f /proc/net/vlan/"$1" ]] }
# $1: netdev name @@ -78,7 +77,7 @@ source_ifcfg_file() {
dwarning "Network Scripts are deprecated. You are encouraged to set up network by NetworkManager." ifcfg_file=$(get_ifcfg_filename "$1") - if [[ -f "${ifcfg_file}" ]]; then + if [[ -f ${ifcfg_file} ]]; then . "${ifcfg_file}" else dwarning "The ifcfg file of $1 is not found!" @@ -94,28 +93,26 @@ kdump_setup_dns() {
_tmp=$(get_nmcli_value_by_field "$_nm_show_cmd" "IP4.DNS") # shellcheck disable=SC2206 - array=( ${_tmp//|/ } ) + array=(${_tmp//|/ }) if [[ ${array[*]} ]]; then - for _dns in "${array[@]}" - do + for _dns in "${array[@]}"; do echo "nameserver=$_dns" >> "$_dnsfile" done else dwarning "Failed to get DNS info via nmcli output. Now try sourcing ifcfg script" source_ifcfg_file "$_netdev" - [[ -n "$DNS1" ]] && echo "nameserver=$DNS1" > "$_dnsfile" - [[ -n "$DNS2" ]] && echo "nameserver=$DNS2" >> "$_dnsfile" + [[ -n $DNS1 ]] && echo "nameserver=$DNS1" > "$_dnsfile" + [[ -n $DNS2 ]] && echo "nameserver=$DNS2" >> "$_dnsfile" fi
- while read -r content; - do + while read -r content; do _nameserver=$(echo "$content" | grep ^nameserver) - [[ -z "$_nameserver" ]] && continue + [[ -z $_nameserver ]] && continue
_dns=$(echo "$_nameserver" | awk '{print $2}') - [[ -z "$_dns" ]] && continue + [[ -z $_dns ]] && continue
- if [[ ! -f $_dnsfile ]] || ! grep -q "$_dns" "$_dnsfile" ; then + if [[ ! -f $_dnsfile ]] || ! grep -q "$_dns" "$_dnsfile"; then echo "nameserver=$_dns" >> "$_dnsfile" fi done < "/etc/resolv.conf" @@ -130,7 +127,7 @@ repeatedly_join_str() { local _separator="$3" local i _res
- if [[ "$_count" -le 0 ]]; then + if [[ $_count -le 0 ]]; then echo -n "" return fi @@ -139,7 +136,7 @@ repeatedly_join_str() { _res="$_str" ((_count--))
- while [[ "$i" -lt "$_count" ]]; do + while [[ $i -lt $_count ]]; do ((i++)) _res="${_res}${_separator}${_str}" done @@ -160,14 +157,14 @@ cal_netmask_by_prefix() { local _count _res _octets_per_group _octets_total _seperator _total_groups local _max_group_value _max_group_value_repr _bits_per_group _tmp _zero_bits
- if [[ "$_ipv6_flag" == "-6" ]]; then + if [[ $_ipv6_flag == "-6" ]]; then _ipv6=1 else _ipv6=0 fi
- if [[ "$_prefix" -lt 0 || "$_prefix" -gt 128 ]] || \ - ( ((!_ipv6)) && [[ "$_prefix" -gt 32 ]] ); then + if [[ $_prefix -lt 0 || $_prefix -gt 128 ]] \ + || ( ((!_ipv6)) && [[ $_prefix -gt 32 ]]); then derror "Bad prefix:$_prefix for calculating netmask" exit 1 fi @@ -182,7 +179,7 @@ cal_netmask_by_prefix() { _seperator="." fi
- _total_groups=$((_octets_total/_octets_per_group)) + _total_groups=$((_octets_total / _octets_per_group)) _bits_per_group=$((_octets_per_group * _bits_per_octet)) _max_group_value=$(((1 << _bits_per_group) - 1))
@@ -192,39 +189,39 @@ cal_netmask_by_prefix() { _max_group_value_repr="$_max_group_value" fi
- _count=$((_prefix/_octets_per_group/_bits_per_octet)) + _count=$((_prefix / _octets_per_group / _bits_per_octet)) _first_part=$(repeatedly_join_str "$_count" "$_max_group_value_repr" "$_seperator") _res="$_first_part"
- _tmp=$((_octets_total*_bits_per_octet-_prefix)) + _tmp=$((_octets_total * _bits_per_octet - _prefix)) _zero_bits=$((_tmp % _bits_per_group)) - if [[ "$_zero_bits" -ne 0 ]]; then + if [[ $_zero_bits -ne 0 ]]; then _second_part=$((_max_group_value >> _zero_bits << _zero_bits)) if ((_ipv6)); then _second_part=$(printf "%x" $_second_part) fi ((_count++)) - if [[ -z "$_first_part" ]]; then + if [[ -z $_first_part ]]; then _res="$_second_part" else _res="${_first_part}${_seperator}${_second_part}" fi fi
- _count=$((_total_groups-_count)) - if [[ "$_count" -eq 0 ]]; then + _count=$((_total_groups - _count)) + if [[ $_count -eq 0 ]]; then echo -n "$_res" return fi
- if ((_ipv6)) && [[ "$_count" -gt 1 ]] ; then + if ((_ipv6)) && [[ $_count -gt 1 ]]; then # use condensed notion for IPv6 _third_part=":" else _third_part=$(repeatedly_join_str "$_count" "0" "$_seperator") fi
- if [[ -z "$_res" ]] && ((!_ipv6)) ; then + if [[ -z $_res ]] && ((!_ipv6)); then echo -n "${_third_part}" else echo -n "${_res}${_seperator}${_third_part}" @@ -244,11 +241,11 @@ kdump_static_ip() { _ipv6_flag="-6" fi
- if [[ -n "$_ipaddr" ]]; then - _gateway=$(ip $_ipv6_flag route list dev "$_netdev" | \ - awk '/^default /{print $3}' | head -n 1) + if [[ -n $_ipaddr ]]; then + _gateway=$(ip $_ipv6_flag route list dev "$_netdev" \ + | awk '/^default /{print $3}' | head -n 1)
- if [[ "x" != "x"$_ipv6_flag ]]; then + if [[ "x" != "x"$_ipv6_flag ]]; then # _ipaddr="2002::56ff:feb6:56d5/64", _netmask is the number after "/" _netmask=${_ipaddr#*/} _srcaddr="[$_srcaddr]" @@ -263,17 +260,17 @@ kdump_static_ip() { echo -n "${_srcaddr}::${_gateway}:${_netmask}::" fi
- /sbin/ip $_ipv6_flag route show | grep -v default |\ - grep ".*via.* $_netdev " | grep -v "^[[:space:]]*nexthop" |\ - while read -r _route; do - _target=$(echo "$_route" | awk '{print $1}') - _nexthop=$(echo "$_route" | awk '{print $3}') - if [[ "x" != "x"$_ipv6_flag ]]; then - _target="[$_target]" - _nexthop="[$_nexthop]" - fi - echo "rd.route=$_target:$_nexthop:$kdumpnic" - done >> "${initdir}/etc/cmdline.d/45route-static.conf" + /sbin/ip $_ipv6_flag route show | grep -v default \ + | grep ".*via.* $_netdev " | grep -v "^[[:space:]]*nexthop" \ + | while read -r _route; do + _target=$(echo "$_route" | awk '{print $1}') + _nexthop=$(echo "$_route" | awk '{print $3}') + if [[ "x" != "x"$_ipv6_flag ]]; then + _target="[$_target]" + _nexthop="[$_nexthop]" + fi + echo "rd.route=$_target:$_nexthop:$kdumpnic" + done >> "${initdir}/etc/cmdline.d/45route-static.conf"
kdump_handle_mulitpath_route "$_netdev" "$_srcaddr" "$kdumpnic" } @@ -287,28 +284,28 @@ kdump_handle_mulitpath_route() { fi
while IFS="" read -r _route; do - if [[ "$_route" =~ [[:space:]]+nexthop ]]; then + if [[ $_route =~ [[:space:]]+nexthop ]]; then _route=${_route##[[:space:]]} # Parse multipath route, using previous _target - [[ "$_target" == 'default' ]] && continue - [[ "$_route" =~ .*via.*\ $_netdev ]] || continue + [[ $_target == 'default' ]] && continue + [[ $_route =~ .*via.*\ $_netdev ]] || continue
_weight=$(echo "$_route" | cut -d ' ' -f7) - if [[ "$_weight" -gt "$_max_weight" ]]; then + if [[ $_weight -gt $_max_weight ]]; then _nexthop=$(echo "$_route" | cut -d ' ' -f3) _max_weight=$_weight - if [[ "x" != "x"$_ipv6_flag ]]; then + if [[ "x" != "x"$_ipv6_flag ]]; then _rule="rd.route=[$_target]:[$_nexthop]:$kdumpnic" else _rule="rd.route=$_target:$_nexthop:$kdumpnic" fi fi else - [[ -n "$_rule" ]] && echo "$_rule" + [[ -n $_rule ]] && echo "$_rule" _target=$(echo "$_route" | cut -d ' ' -f1) _rule="" _max_weight=0 _weight=0 fi - done >> "${initdir}/etc/cmdline.d/45route-static.conf"\ + done >> "${initdir}/etc/cmdline.d/45route-static.conf" \ <<< "$(/sbin/ip $_ipv6_flag route show)"
[[ -n $_rule ]] && echo "$_rule" >> "${initdir}/etc/cmdline.d/45route-static.conf" @@ -323,8 +320,7 @@ kdump_get_mac_addr() { kdump_get_perm_addr() { local addr addr=$(ethtool -P "$1" | sed -e 's/Permanent address: //') - if [[ -z "$addr" ]] || [[ "$addr" = "00:00:00:00:00:00" ]] - then + if [[ -z $addr ]] || [[ $addr == "00:00:00:00:00:00" ]]; then derror "Can't get the permanent address of $1" else echo "$addr" @@ -390,13 +386,13 @@ kdump_setup_bond() {
_bondoptions=$(get_nmcli_value_by_field "$_nm_show_cmd" "bond.options")
- if [[ -z "$_bondoptions" ]]; then + if [[ -z $_bondoptions ]]; then dwarning "Failed to get bond configuration via nmlci output. Now try sourcing ifcfg script." source_ifcfg_file "$_netdev" _bondoptions="$(echo "$BONDING_OPTS" | xargs echo | tr " " ",")" fi
- if [[ -z "$_bondoptions" ]]; then + if [[ -z $_bondoptions ]]; then derror "Get empty bond options" exit 1 fi @@ -452,30 +448,27 @@ kdump_setup_vlan() { # code reaped from the list_configured function of # https://github.com/hreinecke/s390-tools/blob/master/zconf/znetconf find_online_znet_device() { - local CCWGROUPBUS_DEVICEDIR="/sys/bus/ccwgroup/devices" - local NETWORK_DEVICES d ifname ONLINE - - [[ ! -d "$CCWGROUPBUS_DEVICEDIR" ]] && return - NETWORK_DEVICES=$(find $CCWGROUPBUS_DEVICEDIR) - for d in $NETWORK_DEVICES - do - [[ ! -f "$d/online" ]] && continue - read -r ONLINE < "$d/online" - if [[ $ONLINE -ne 1 ]]; then - continue - fi - # determine interface name, if there (only for qeth and if - # device is online) - if [[ -f $d/if_name ]] - then - read -r ifname < "$d/if_name" - elif [[ -d $d/net ]] - then - ifname=$(ls "$d/net/") - fi - [[ -n "$ifname" ]] && break - done - echo -n "$ifname" + local CCWGROUPBUS_DEVICEDIR="/sys/bus/ccwgroup/devices" + local NETWORK_DEVICES d ifname ONLINE + + [[ ! -d $CCWGROUPBUS_DEVICEDIR ]] && return + NETWORK_DEVICES=$(find $CCWGROUPBUS_DEVICEDIR) + for d in $NETWORK_DEVICES; do + [[ ! -f "$d/online" ]] && continue + read -r ONLINE < "$d/online" + if [[ $ONLINE -ne 1 ]]; then + continue + fi + # determine interface name, if there (only for qeth and if + # device is online) + if [[ -f $d/if_name ]]; then + read -r ifname < "$d/if_name" + elif [[ -d $d/net ]]; then + ifname=$(ls "$d/net/") + fi + [[ -n $ifname ]] && break + done + echo -n "$ifname" }
# setup s390 znet cmdline @@ -493,7 +486,7 @@ kdump_setup_znet() { SUBCHANNELS=$(get_nmcli_value_by_field "$_nmcli_cmd" "${s390_prefix}subchannels") _options=$(get_nmcli_value_by_field "$_nmcli_cmd" "${s390_prefix}options")
- if [[ -z "$NETTYPE" || -z "$SUBCHANNELS" || -z "$_options" ]]; then + if [[ -z $NETTYPE || -z $SUBCHANNELS || -z $_options ]]; then dwarning "Failed to get znet configuration via nmlci output. Now try sourcing ifcfg script." source_ifcfg_file "$_netdev" for i in $OPTIONS; do @@ -501,15 +494,14 @@ kdump_setup_znet() { done fi
- if [[ -z "$NETTYPE" || -z "$SUBCHANNELS" || -z "$_options" ]]; then + if [[ -z $NETTYPE || -z $SUBCHANNELS || -z $_options ]]; then exit 1 fi
echo "rd.znet=${NETTYPE},${SUBCHANNELS},${_options} rd.znet_ifname=$_netdev:${SUBCHANNELS}" > "${initdir}/etc/cmdline.d/30znet.conf" }
-kdump_get_ip_route() -{ +kdump_get_ip_route() { local _route if ! _route=$(/sbin/ip -o route get to "$1" 2>&1); then derror "Bad kdump network destination: $1" @@ -518,18 +510,16 @@ kdump_get_ip_route() echo "$_route" }
-kdump_get_ip_route_field() -{ +kdump_get_ip_route_field() { echo "$1" | sed -n -e "s/(^|^.*\s+)<$2>\s+(\S+).*$/\2/p" }
-kdump_get_remote_ip() -{ +kdump_get_remote_ip() { local _remote _remote_temp _remote=$(get_remote_host "$1") if is_hostname "$_remote"; then _remote_temp=$(getent ahosts "$_remote" | grep -v : | head -n 1) - if [[ -z "$_remote_temp" ]]; then + if [[ -z $_remote_temp ]]; then _remote_temp=$(getent ahosts "$_remote" | head -n 1) fi _remote=$(echo "$_remote_temp" | awk '{print $1}') @@ -554,7 +544,7 @@ kdump_install_net() { kdumpnic=$(kdump_setup_ifname "$_netdev")
_znet_netdev=$(find_online_znet_device) - if [[ -n "$_znet_netdev" ]]; then + if [[ -n $_znet_netdev ]]; then _nm_show_cmd_znet=$(get_nmcli_connection_show_cmd_by_ifname "$_znet_netdev") if ! $(kdump_setup_znet "$_znet_netdev" "$_nm_show_cmd_znet"); then derror "Failed to set up znet" @@ -563,7 +553,7 @@ kdump_install_net() { fi
_static=$(kdump_static_ip "$_netdev" "$_srcaddr" "$kdumpnic") - if [[ -n "$_static" ]]; then + if [[ -n $_static ]]; then _proto=none elif is_ipv6_address "$_srcaddr"; then _proto=auto6 @@ -578,8 +568,8 @@ kdump_install_net() { # so we have to avoid adding duplicates # We should also check /proc/cmdline for existing ip=xx arg. # For example, iscsi boot will specify ip=xxx arg in cmdline. - if [[ ! -f $_ip_conf ]] || ! grep -q "$_ip_opts" "$_ip_conf" &&\ - ! grep -q "ip=[^[:space:]]*$_netdev" /proc/cmdline; then + if [[ ! -f $_ip_conf ]] || ! grep -q "$_ip_opts" "$_ip_conf" \ + && ! grep -q "ip=[^[:space:]]*$_netdev" /proc/cmdline; then echo "$_ip_opts" >> "$_ip_conf" fi
@@ -610,8 +600,8 @@ kdump_install_net() { # the default gate way for network dump, eth1 in the fence kdump path will # call kdump_install_net again and we don't want eth1 to be the default # gateway. - if [[ ! -f ${initdir}/etc/cmdline.d/60kdumpnic.conf ]] && - [[ ! -f ${initdir}/etc/cmdline.d/70bootdev.conf ]]; then + if [[ ! -f ${initdir}/etc/cmdline.d/60kdumpnic.conf ]] \ + && [[ ! -f ${initdir}/etc/cmdline.d/70bootdev.conf ]]; then echo "kdumpnic=$kdumpnic" > "${initdir}/etc/cmdline.d/60kdumpnic.conf" echo "bootdev=$kdumpnic" > "${initdir}/etc/cmdline.d/70bootdev.conf" fi @@ -621,17 +611,17 @@ kdump_install_net() { kdump_install_pre_post_conf() { if [[ -d /etc/kdump/pre.d ]]; then for file in /etc/kdump/pre.d/*; do - if [[ -x "$file" ]]; then + if [[ -x $file ]]; then dracut_install "$file" elif [[ $file != "/etc/kdump/pre.d/*" ]]; then - echo "$file is not executable" + echo "$file is not executable" fi done fi
if [[ -d /etc/kdump/post.d ]]; then for file in /etc/kdump/post.d/*; do - if [[ -x "$file" ]]; then + if [[ -x $file ]]; then dracut_install "$file" elif [[ $file != "/etc/kdump/post.d/*" ]]; then echo "$file is not executable" @@ -640,8 +630,7 @@ kdump_install_pre_post_conf() { fi }
-default_dump_target_install_conf() -{ +default_dump_target_install_conf() { local _target _fstype local _mntpoint _save_path
@@ -662,7 +651,7 @@ default_dump_target_install_conf() echo "$_fstype $_target" >> "${initdir}/tmp/$$-kdump.conf"
# don't touch the path under root mount - if [[ "$_mntpoint" != "/" ]]; then + if [[ $_mntpoint != "/" ]]; then _save_path=${_save_path##"$_mntpoint"} fi
@@ -677,32 +666,31 @@ kdump_install_conf() {
kdump_read_conf > "${initdir}/tmp/$$-kdump.conf"
- while read -r _opt _val; - do + while read -r _opt _val; do # remove inline comments after the end of a directive. case "$_opt" in - raw) - _pdev=$(persistent_policy="by-id" kdump_get_persistent_dev "$_val") - sed -i -e "s#^${_opt}[[:space:]]+$_val#$_opt $_pdev#" "${initdir}/tmp/$$-kdump.conf" - ;; - ext[234]|xfs|btrfs|minix) - _pdev=$(kdump_get_persistent_dev "$_val") - sed -i -e "s#^${_opt}[[:space:]]+$_val#$_opt $_pdev#" "${initdir}/tmp/$$-kdump.conf" - ;; - ssh|nfs) - kdump_install_net "$_val" - ;; - dracut_args) - if [[ $(get_dracut_args_fstype "$_val") = nfs* ]] ; then - kdump_install_net "$(get_dracut_args_target "$_val")" - fi - ;; - kdump_pre|kdump_post|extra_bins) - dracut_install "$_val" - ;; - core_collector) - dracut_install "${_val%%[[:blank:]]*}" - ;; + raw) + _pdev=$(persistent_policy="by-id" kdump_get_persistent_dev "$_val") + sed -i -e "s#^${_opt}[[:space:]]+$_val#$_opt $_pdev#" "${initdir}/tmp/$$-kdump.conf" + ;; + ext[234] | xfs | btrfs | minix) + _pdev=$(kdump_get_persistent_dev "$_val") + sed -i -e "s#^${_opt}[[:space:]]+$_val#$_opt $_pdev#" "${initdir}/tmp/$$-kdump.conf" + ;; + ssh | nfs) + kdump_install_net "$_val" + ;; + dracut_args) + if [[ $(get_dracut_args_fstype "$_val") == nfs* ]]; then + kdump_install_net "$(get_dracut_args_target "$_val")" + fi + ;; + kdump_pre | kdump_post | extra_bins) + dracut_install "$_val" + ;; + core_collector) + dracut_install "${_val%%[[:blank:]]*}" + ;; esac done <<< "$(kdump_read_conf)"
@@ -710,7 +698,7 @@ kdump_install_conf() {
default_dump_target_install_conf
- kdump_configure_fence_kdump "${initdir}/tmp/$$-kdump.conf" + kdump_configure_fence_kdump "${initdir}/tmp/$$-kdump.conf" inst "${initdir}/tmp/$$-kdump.conf" "/etc/kdump.conf" rm -f "${initdir}/tmp/$$-kdump.conf" } @@ -743,16 +731,17 @@ kdump_get_iscsi_initiator() { local _initiator local initiator_conf="/etc/iscsi/initiatorname.iscsi"
- [[ -f "$initiator_conf" ]] || return 1 + [[ -f $initiator_conf ]] || return 1
while read -r _initiator; do - [[ -z "${_initiator%%#*}" ]] && continue # Skip comment lines + [[ -z ${_initiator%%#*} ]] && continue # Skip comment lines
case $_initiator in InitiatorName=*) initiator=${_initiator#InitiatorName=} echo "rd.iscsi.initiator=${initiator}" - return 0;; + return 0 + ;; *) ;; esac done < ${initiator_conf} @@ -762,15 +751,21 @@ kdump_get_iscsi_initiator() {
# Figure out iBFT session according to session type is_ibft() { - [[ "$(kdump_iscsi_get_rec_val "$1" "node.discovery_type")" = fw ]] + [[ "$(kdump_iscsi_get_rec_val "$1" "node.discovery_type")" == fw ]] }
kdump_setup_iscsi_device() { local path=$1 - local tgt_name; local tgt_ipaddr; - local username; local password; local userpwd_str; - local username_in; local password_in; local userpwd_in_str; - local netroot_str ; local initiator_str; + local tgt_name + local tgt_ipaddr + local username + local password + local userpwd_str + local username_in + local password_in + local userpwd_in_str + local netroot_str + local initiator_str local netroot_conf="${initdir}/etc/cmdline.d/50iscsi.conf" local initiator_conf="/etc/iscsi/initiatorname.iscsi"
@@ -778,7 +773,7 @@ kdump_setup_iscsi_device() {
# Check once before getting explicit values, so we can bail out early, # e.g. in case of pure-hardware(all-offload) iscsi. - if ! /sbin/iscsiadm -m session -r "$path" &>/dev/null ; then + if ! /sbin/iscsiadm -m session -r "$path" &> /dev/null; then return 1 fi
@@ -795,18 +790,18 @@ kdump_setup_iscsi_device() {
# get and set username and password details username=$(kdump_iscsi_get_rec_val "$path" "node.session.auth.username") - [[ "$username" == "<empty>" ]] && username="" + [[ $username == "<empty>" ]] && username="" password=$(kdump_iscsi_get_rec_val "$path" "node.session.auth.password") - [[ "$password" == "<empty>" ]] && password="" + [[ $password == "<empty>" ]] && password="" username_in=$(kdump_iscsi_get_rec_val "$path" "node.session.auth.username_in") - [[ -n "$username" ]] && userpwd_str="$username:$password" + [[ -n $username ]] && userpwd_str="$username:$password"
# get and set incoming username and password details - [[ "$username_in" == "<empty>" ]] && username_in="" + [[ $username_in == "<empty>" ]] && username_in="" password_in=$(kdump_iscsi_get_rec_val "$path" "node.session.auth.password_in") - [[ "$password_in" == "<empty>" ]] && password_in="" + [[ $password_in == "<empty>" ]] && password_in=""
- [[ -n "$username_in" ]] && userpwd_in_str=":$username_in:$password_in" + [[ -n $username_in ]] && userpwd_in_str=":$username_in:$password_in"
kdump_install_net "$tgt_ipaddr"
@@ -823,8 +818,8 @@ kdump_setup_iscsi_device() {
# If netroot target does not exist already, append. if ! grep -q "$netroot_str" "$netroot_conf"; then - echo "$netroot_str" >> "$netroot_conf" - dinfo "Appended $netroot_str to $netroot_conf" + echo "$netroot_str" >> "$netroot_conf" + dinfo "Appended $netroot_str to $netroot_conf" fi
# Setup initator @@ -835,14 +830,14 @@ kdump_setup_iscsi_device() {
# If initiator details do not exist already, append. if ! grep -q "$initiator_str" "$netroot_conf"; then - echo "$initiator_str" >> "$netroot_conf" - dinfo "Appended $initiator_str to $netroot_conf" + echo "$initiator_str" >> "$netroot_conf" + dinfo "Appended $initiator_str to $netroot_conf" fi }
-kdump_check_iscsi_targets () { +kdump_check_iscsi_targets() { # If our prerequisites are not met, fail anyways. - type -P iscsistart >/dev/null || return 1 + type -P iscsistart > /dev/null || return 1
kdump_check_setup_iscsi() ( local _dev @@ -868,12 +863,11 @@ get_alias() { local alias_set
ips=$(hostname -I) - for ip in $ips - do - # in /etc/hosts, alias can come at the 2nd column - if entries=$(grep "$ip" /etc/hosts | awk '{ $1=""; print $0 }'); then - alias_set="$alias_set $entries" - fi + for ip in $ips; do + # in /etc/hosts, alias can come at the 2nd column + if entries=$(grep "$ip" /etc/hosts | awk '{ $1=""; print $0 }'); then + alias_set="$alias_set $entries" + fi done
echo "$alias_set" @@ -891,7 +885,7 @@ is_localhost() { hostnames="$hostnames $shortnames $aliasname"
for name in ${hostnames}; do - if [[ "$name" == "$nodename" ]]; then + if [[ $name == "$nodename" ]]; then return 0 fi done @@ -947,7 +941,7 @@ get_generic_fence_kdump_nodes() {
# setup fence_kdump in cluster # setup proper network and install needed files -kdump_configure_fence_kdump () { +kdump_configure_fence_kdump() { local kdump_cfg_file=$1 local nodes local args @@ -962,7 +956,7 @@ kdump_configure_fence_kdump () { echo "fence_kdump_nodes $nodes" >> "${kdump_cfg_file}"
args=$(get_pcs_fence_kdump_args) - if [[ -n "$args" ]]; then + if [[ -n $args ]]; then echo "fence_kdump_args $args" >> "${kdump_cfg_file}" fi
@@ -986,14 +980,14 @@ kdump_configure_fence_kdump () { kdump_install_random_seed() { local poolsize
- poolsize=$(</proc/sys/kernel/random/poolsize) + poolsize=$(< /proc/sys/kernel/random/poolsize)
if [[ ! -d "${initdir}/var/lib/" ]]; then mkdir -p "${initdir}/var/lib/" fi
dd if=/dev/urandom of="${initdir}/var/lib/random-seed" \ - bs="$poolsize" count=1 2> /dev/null + bs="$poolsize" count=1 2> /dev/null }
kdump_install_systemd_conf() { @@ -1070,8 +1064,8 @@ install() { # it unconditionally here, if "/etc/lvm/lvm.conf" doesn't exist, it # actually does nothing. sed -i -e \ - 's/(^[[:space:]]*reserved_memory[[:space:]]*=)[[:space:]]*[[:digit:]]*/\1 1024/' \ - "${initdir}/etc/lvm/lvm.conf" &>/dev/null + 's/(^[[:space:]]*reserved_memory[[:space:]]*=)[[:space:]]*[[:digit:]]*/\1 1024/' \ + "${initdir}/etc/lvm/lvm.conf" &> /dev/null
# Save more memory by dropping switch root capability dracut_no_switch_root diff --git a/kdumpctl b/kdumpctl index f6cde221..5f72724f 100755 --- a/kdumpctl +++ b/kdumpctl @@ -46,7 +46,7 @@ single_instance_lock() { local rc timeout=5
- if ! exec 9>/var/lock/kdump; then + if ! exec 9> /var/lock/kdump; then derror "Create file lock failed" exit 1 fi @@ -90,9 +90,9 @@ save_core() # https://fedorahosted.org/abrt/ if [[ -x /usr/bin/dumpoops ]]; then ddebug "makedumpfile --dump-dmesg $coredir/vmcore $coredir/dmesg" - makedumpfile --dump-dmesg "$coredir/vmcore" "$coredir/dmesg" >/dev/null 2>&1 + makedumpfile --dump-dmesg "$coredir/vmcore" "$coredir/dmesg" > /dev/null 2>&1 ddebug "dumpoops -d $coredir/dmesg" - if dumpoops -d "$coredir/dmesg" >/dev/null 2>&1; then + if dumpoops -d "$coredir/dmesg" > /dev/null 2>&1; then dinfo "kernel oops has been collected by abrt tool" fi fi @@ -131,7 +131,7 @@ rebuild_kdump_initrd()
rebuild_initrd() { - if [[ ! -w $(dirname "$TARGET_INITRD") ]];then + if [[ ! -w $(dirname "$TARGET_INITRD") ]]; then derror "$(dirname "$TARGET_INITRD") does not have write permission. Cannot rebuild $TARGET_INITRD" return 1 fi @@ -149,7 +149,7 @@ rebuild_initrd() check_exist() { for file in $1; do - if [[ ! -e "$file" ]]; then + if [[ ! -e $file ]]; then derror "Error: $file not found." return 1 fi @@ -160,7 +160,7 @@ check_exist() check_executable() { for file in $1; do - if [[ ! -x "$file" ]]; then + if [[ ! -x $file ]]; then derror "Error: $file is not executable." return 1 fi @@ -171,7 +171,7 @@ backup_default_initrd() { ddebug "backup default initrd: $DEFAULT_INITRD"
- if [[ ! -f "$DEFAULT_INITRD" ]]; then + if [[ ! -f $DEFAULT_INITRD ]]; then return fi
@@ -190,7 +190,7 @@ restore_default_initrd() { ddebug "restore default initrd: $DEFAULT_INITRD"
- if [[ ! -f "$DEFAULT_INITRD" ]]; then + if [[ ! -f $DEFAULT_INITRD ]]; then return fi
@@ -200,7 +200,7 @@ restore_default_initrd() # verify checksum before restoring backup_checksum=$(sha1sum "$DEFAULT_INITRD_BAK" | awk '{ print $1 }') default_checksum=$(awk '{ print $1 }' "$INITRD_CHECKSUM_LOCATION") - if [[ "$default_checksum" != "$backup_checksum" ]]; then + if [[ $default_checksum != "$backup_checksum" ]]; then dwarn "WARNING: checksum mismatch! Can't restore original initrd.." else rm -f $INITRD_CHECKSUM_LOCATION @@ -220,7 +220,7 @@ check_config() dracut_args) if [[ $config_val == *--mount* ]]; then if [[ $(echo "$config_val" | grep -o "--mount" | wc -l) -ne 1 ]]; then - derror "Multiple mount targets specified in one "dracut_args"." + derror 'Multiple mount targets specified in one "dracut_args".' return 1 fi config_opt=_target @@ -232,12 +232,12 @@ check_config() fi config_opt=_target ;; - ext[234]|minix|btrfs|xfs|nfs|ssh) + ext[234] | minix | btrfs | xfs | nfs | ssh) config_opt=_target ;; - sshkey|path|core_collector|kdump_post|kdump_pre|extra_bins|extra_modules|failure_action|default|final_action|force_rebuild|force_no_rebuild|fence_kdump_args|fence_kdump_nodes) - ;; - net|options|link_delay|disk_timeout|debug_mem_level|blacklist) + sshkey | path | core_collector | kdump_post | kdump_pre | extra_bins | extra_modules | failure_action | default | final_action | force_rebuild | force_no_rebuild | fence_kdump_args | fence_kdump_nodes) ;; + + net | options | link_delay | disk_timeout | debug_mem_level | blacklist) derror "Deprecated kdump config option: $config_opt. Refer to kdump.conf manpage for alternatives." return 1 ;; @@ -250,12 +250,12 @@ check_config() ;; esac
- if [[ -z "$config_val" ]]; then + if [[ -z $config_val ]]; then derror "Invalid kdump config value for option '$config_opt'" return 1 fi
- if [[ -n "${_opt_rec[$config_opt]}" ]]; then + if [[ -n ${_opt_rec[$config_opt]} ]]; then if [[ $config_opt == _target ]]; then derror "More than one dump targets specified" else @@ -291,7 +291,7 @@ get_pcs_cluster_modified_files()
if [[ -f $FENCE_KDUMP_CONFIG_FILE ]]; then time_stamp=$(stat -c "%Y" "$FENCE_KDUMP_CONFIG_FILE") - if [[ "$time_stamp" -gt "$image_time" ]]; then + if [[ $time_stamp -gt $image_time ]]; then modified_files="$modified_files $FENCE_KDUMP_CONFIG_FILE" fi fi @@ -335,14 +335,14 @@ check_files_modified() HOOKS="/etc/kdump/post.d/ /etc/kdump/pre.d/" if [[ -d /etc/kdump/post.d ]]; then for file in /etc/kdump/post.d/*; do - if [[ -x "$file" ]]; then + if [[ -x $file ]]; then POST_FILES="$POST_FILES $file" fi done fi if [[ -d /etc/kdump/pre.d ]]; then for file in /etc/kdump/pre.d/*; do - if [[ -x "$file" ]]; then + if [[ -x $file ]]; then PRE_FILES="$PRE_FILES $file" fi done @@ -359,19 +359,19 @@ check_files_modified()
# Check for any updated extra module EXTRA_MODULES="$(kdump_get_conf_val extra_modules)" - if [[ -n "$EXTRA_MODULES" ]]; then + if [[ -n $EXTRA_MODULES ]]; then if [[ -e /lib/modules/$KDUMP_KERNELVER/modules.dep ]]; then files="$files /lib/modules/$KDUMP_KERNELVER/modules.dep" fi for _module in $EXTRA_MODULES; do - if _module_file="$(modinfo --set-version "$KDUMP_KERNELVER" --filename "$_module" 2>/dev/null)"; then + if _module_file="$(modinfo --set-version "$KDUMP_KERNELVER" --filename "$_module" 2> /dev/null)"; then files="$files $_module_file" for _dep_modules in $(modinfo -F depends "$_module" | tr ',' ' '); do - files="$files $(modinfo --set-version "$KDUMP_KERNELVER" --filename "$_dep_modules" 2>/dev/null)" + files="$files $(modinfo --set-version "$KDUMP_KERNELVER" --filename "$_dep_modules" 2> /dev/null)" done else # If it's not a module nor builtin, give an error - if ! ( modprobe --set-version "$KDUMP_KERNELVER" --dry-run "$_module" &>/dev/null ); then + if ! (modprobe --set-version "$KDUMP_KERNELVER" --dry-run "$_module" &> /dev/null); then dwarn "Module $_module not found" fi fi @@ -383,15 +383,15 @@ check_files_modified() check_exist "$files" && check_executable "$EXTRA_BINS" || return 2
for file in $files; do - if [[ -e "$file" ]]; then + if [[ -e $file ]]; then time_stamp=$(stat -c "%Y" "$file") - if [[ "$time_stamp" -gt "$image_time" ]]; then + if [[ $time_stamp -gt $image_time ]]; then modified_files="$modified_files $file" fi - if [[ -L "$file" ]]; then + if [[ -L $file ]]; then file=$(readlink -m "$file") time_stamp=$(stat -c "%Y" "$file") - if [[ "$time_stamp" -gt "$image_time" ]]; then + if [[ $time_stamp -gt $image_time ]]; then modified_files="$modified_files $file" fi fi @@ -400,7 +400,7 @@ check_files_modified() fi done
- if [[ -n "$modified_files" ]]; then + if [[ -n $modified_files ]]; then dinfo "Detected change(s) in the following file(s): $modified_files" return 1 fi @@ -414,8 +414,9 @@ check_drivers_modified()
# If it's dump target is on block device, detect the block driver _target=$(get_block_dump_target) - if [[ -n "$_target" ]]; then - _record_block_drivers() { + if [[ -n $_target ]]; then + _record_block_drivers() + { local _drivers _drivers=$(udevadm info -a "/dev/block/$1" | sed -n 's/\s*DRIVERS=="(\S+)"/\1/p') for _driver in $_drivers; do @@ -431,7 +432,7 @@ check_drivers_modified()
# Include watchdog drivers if watchdog module is not omitted is_dracut_mod_omitted watchdog || _new_drivers+=" $(get_watchdog_drvs)" - [[ -z "$_new_drivers" ]] && return 0 + [[ -z $_new_drivers ]] && return 0
if is_fadump_capable; then _old_drivers="$(lsinitrd "$TARGET_INITRD" -f /usr/lib/dracut/fadump-kernel-modules.txt | tr '\n' ' ')" @@ -443,9 +444,9 @@ check_drivers_modified() ddebug "Modules included in old initramfs: '$_old_drivers'" for _driver in $_new_drivers; do # Skip deprecated/invalid driver name or built-in module - _module_name=$(modinfo --set-version "$KDUMP_KERNELVER" -F name "$_driver" 2>/dev/null) - _module_filename=$(modinfo --set-version "$KDUMP_KERNELVER" -n "$_driver" 2>/dev/null) - if [[ -z "$_module_name" ]] || [[ -z "$_module_filename" ]] || [[ "$_module_filename" = *"(builtin)"* ]]; then + _module_name=$(modinfo --set-version "$KDUMP_KERNELVER" -F name "$_driver" 2> /dev/null) + _module_filename=$(modinfo --set-version "$KDUMP_KERNELVER" -n "$_driver" 2> /dev/null) + if [[ -z $_module_name ]] || [[ -z $_module_filename ]] || [[ $_module_filename == *"(builtin)"* ]]; then continue fi if ! [[ " $_old_drivers " == *" $_module_name "* ]]; then @@ -474,21 +475,21 @@ check_fs_modified()
_target=$(get_block_dump_target) _new_fstype=$(get_fs_type_from_target "$_target") - if [[ -z "$_target" ]] || [[ -z "$_new_fstype" ]];then + if [[ -z $_target ]] || [[ -z $_new_fstype ]]; then derror "Dump target is invalid" return 2 fi
ddebug "_target=$_target _new_fstype=$_new_fstype" _new_dev=$(kdump_get_persistent_dev "$_target") - if [[ -z "$_new_dev" ]]; then + if [[ -z $_new_dev ]]; then perror "Get persistent device name failed" return 2 fi
_new_mntpoint="$(get_kdump_mntpoint_from_target "$_target")" _dracut_args=$(lsinitrd "$TARGET_INITRD" -f usr/lib/dracut/build-parameter.txt) - if [[ -z "$_dracut_args" ]];then + if [[ -z $_dracut_args ]]; then dwarn "Warning: No dracut arguments found in initrd" return 0 fi @@ -501,10 +502,10 @@ check_fs_modified() _old_dev=$1 _old_mntpoint=$2 _old_fstype=$3 - [[ $_new_dev = "$_old_dev" && $_new_mntpoint = "$_old_mntpoint" && $_new_fstype = "$_old_fstype" ]] && return 0 + [[ $_new_dev == "$_old_dev" && $_new_mntpoint == "$_old_mntpoint" && $_new_fstype == "$_old_fstype" ]] && return 0 # otherwise rebuild if target device is not a root device else - [[ "$_target" = "$(get_root_fs_device)" ]] && return 0 + [[ $_target == "$(get_root_fs_device)" ]] && return 0 fi
dinfo "Detected change in File System" @@ -551,36 +552,36 @@ check_rebuild()
force_no_rebuild=$(kdump_get_conf_val force_no_rebuild) force_no_rebuild=${force_no_rebuild:-0} - if [[ "$force_no_rebuild" != "0" ]] && [[ "$force_no_rebuild" != "1" ]];then + if [[ $force_no_rebuild != "0" ]] && [[ $force_no_rebuild != "1" ]]; then derror "Error: force_no_rebuild value is invalid" return 1 fi
force_rebuild=$(kdump_get_conf_val force_rebuild) force_rebuild=${force_rebuild:-0} - if [[ "$force_rebuild" != "0" ]] && [[ "$force_rebuild" != "1" ]];then + if [[ $force_rebuild != "0" ]] && [[ $force_rebuild != "1" ]]; then derror "Error: force_rebuild value is invalid" return 1 fi
- if [[ "$force_no_rebuild" == "1" && "$force_rebuild" == "1" ]]; then + if [[ $force_no_rebuild == "1" && $force_rebuild == "1" ]]; then derror "Error: force_rebuild and force_no_rebuild are enabled simultaneously in kdump.conf" return 1 fi
# Will not rebuild kdump initrd - if [[ "$force_no_rebuild" == "1" ]]; then + if [[ $force_no_rebuild == "1" ]]; then return 0 fi
#check to see if dependent files has been modified #since last build of the image file if [[ -f $TARGET_INITRD ]]; then - image_time=$(stat -c "%Y" "$TARGET_INITRD" 2>/dev/null) + image_time=$(stat -c "%Y" "$TARGET_INITRD" 2> /dev/null)
#in case of fadump mode, check whether the default/target #initrd is already built with dump capture capability - if [[ "$DEFAULT_DUMP_MODE" == "fadump" ]]; then + if [[ $DEFAULT_DUMP_MODE == "fadump" ]]; then capture_capable_initrd=$(lsinitrd -f $DRACUT_MODULES_FILE "$TARGET_INITRD" | grep -c -e ^kdumpbase$ -e ^zz-fadumpinit$) fi fi @@ -589,17 +590,17 @@ check_rebuild() ret=$? if [[ $ret -eq 2 ]]; then return 1 - elif [[ $ret -eq 1 ]];then + elif [[ $ret -eq 1 ]]; then system_modified="1" fi
if [[ $image_time -eq 0 ]]; then dinfo "No kdump initial ramdisk found." - elif [[ "$capture_capable_initrd" == "0" ]]; then + elif [[ $capture_capable_initrd == "0" ]]; then dinfo "Rebuild $TARGET_INITRD with dump capture support" - elif [[ "$force_rebuild" != "0" ]]; then + elif [[ $force_rebuild != "0" ]]; then dinfo "Force rebuild $TARGET_INITRD" - elif [[ "$system_modified" != "0" ]]; then + elif [[ $system_modified != "0" ]]; then : else return 0 @@ -617,13 +618,13 @@ function load_kdump_kernel_key() # this is only called inside is_secure_boot_enforced, # no need to retest
- # this is only required if DT /ibm,secure-boot is a file. - # if it is a dir, we are on OpenPower and don't need this. - if ! [[ -f /proc/device-tree/ibm,secure-boot ]]; then - return - fi + # this is only required if DT /ibm,secure-boot is a file. + # if it is a dir, we are on OpenPower and don't need this. + if ! [[ -f /proc/device-tree/ibm,secure-boot ]]; then + return + fi
- KDUMP_KEY_ID=$(keyctl padd asymmetric kernelkey-$RANDOM %:.ima < "/usr/share/doc/kernel-keys/$KDUMP_KERNELVER/kernel-signing-ppc.cer") + KDUMP_KEY_ID=$(keyctl padd asymmetric kernelkey-$RANDOM %:.ima < "/usr/share/doc/kernel-keys/$KDUMP_KERNELVER/kernel-signing-ppc.cer") }
# remove a previously loaded key. There's no real security implication @@ -631,7 +632,7 @@ function load_kdump_kernel_key() # to be idempotent and so as to reduce the potential for confusion. function remove_kdump_kernel_key() { - if [[ -z "$KDUMP_KEY_ID" ]]; then + if [[ -z $KDUMP_KEY_ID ]]; then return fi
@@ -696,7 +697,7 @@ check_ssh_config() case "$config_opt" in sshkey) # remove inline comments after the end of a directive. - if [[ -f "$config_val" ]]; then + if [[ -f $config_val ]]; then # canonicalize the path SSH_KEY_LOCATION=$(/usr/bin/readlink -m "$config_val") else @@ -709,14 +710,14 @@ check_ssh_config() ssh) DUMP_TARGET=$config_val ;; - *) - ;; + *) ;; + esac done <<< "$(kdump_read_conf)"
#make sure they've configured kdump.conf for ssh dumps SSH_TARGET=$(echo -n "$DUMP_TARGET" | sed -n '/.*@/p') - if [[ -z "$SSH_TARGET" ]]; then + if [[ -z $SSH_TARGET ]]; then return 1 fi return 0 @@ -763,7 +764,7 @@ check_and_wait_network_ready() diff=$((cur - start_time)) # 60s time out if [[ $diff -gt 180 ]]; then - break; + break fi sleep 1 done @@ -814,19 +815,19 @@ propagate_ssh_key()
show_reserved_mem() { - local mem - local mem_mb + local mem + local mem_mb
- mem=$(</sys/kernel/kexec_crash_size) - mem_mb=$((mem / 1024 / 1024)) + mem=$(< /sys/kernel/kexec_crash_size) + mem_mb=$((mem / 1024 / 1024))
- dinfo "Reserved ${mem_mb}MB memory for crash kernel" + dinfo "Reserved ${mem_mb}MB memory for crash kernel" }
check_current_fadump_status() { # Check if firmware-assisted dump has been registered. - rc=$(<$FADUMP_REGISTER_SYS_NODE) + rc=$(< $FADUMP_REGISTER_SYS_NODE) [[ $rc -eq 1 ]] && return 0 return 1 } @@ -848,8 +849,8 @@ save_raw() local raw_target
raw_target=$(kdump_get_conf_val raw) - [[ -z "$raw_target" ]] && return 0 - [[ -b "$raw_target" ]] || { + [[ -z $raw_target ]] && return 0 + [[ -b $raw_target ]] || { derror "raw partition $raw_target not found" return 1 } @@ -859,22 +860,22 @@ save_raw() return 0 fi kdump_dir=$(kdump_get_conf_val path) - if [[ -z "${kdump_dir}" ]]; then + if [[ -z ${kdump_dir} ]]; then coredir="/var/crash/$(date +"%Y-%m-%d-%H:%M")" else coredir="${kdump_dir}/$(date +"%Y-%m-%d-%H:%M")" fi
mkdir -p "$coredir" - [[ -d "$coredir" ]] || { + [[ -d $coredir ]] || { derror "failed to create $coredir" return 1 } - if makedumpfile -R "$coredir/vmcore" < "$raw_target" >/dev/null 2>&1; then + if makedumpfile -R "$coredir/vmcore" < "$raw_target" > /dev/null 2>&1; then # dump found dinfo "Dump saved to $coredir/vmcore" # wipe makedumpfile header - dd if=/dev/zero of="$raw_target" bs=1b count=1 2>/dev/null + dd if=/dev/zero of="$raw_target" bs=1b count=1 2> /dev/null else rm -rf "$coredir" fi @@ -897,11 +898,11 @@ path_to_be_relabeled()
if is_user_configured_dump_target; then if is_mount_in_dracut_args; then - return; + return fi
_target=$(local_fs_dump_target) - if [[ -n "$_target" ]]; then + if [[ -n $_target ]]; then _mnt=$(get_mntpoint_from_target "$_target") if ! is_mounted "$_mnt"; then return @@ -913,8 +914,8 @@ path_to_be_relabeled()
_path=$(get_save_path) # if $_path is masked by other mount, we will not relabel it. - _rmnt=$(df "$_mnt/$_path" 2>/dev/null | tail -1 | awk '{ print $NF }') - if [[ "$_rmnt" == "$_mnt" ]]; then + _rmnt=$(df "$_mnt/$_path" 2> /dev/null | tail -1 | awk '{ print $NF }') + if [[ $_rmnt == "$_mnt" ]]; then echo "$_mnt/$_path" fi } @@ -924,14 +925,14 @@ selinux_relabel() local _path _i _attr
_path=$(path_to_be_relabeled) - if [[ -z "$_path" ]] || ! [[ -d "$_path" ]] ; then + if [[ -z $_path ]] || ! [[ -d $_path ]]; then return fi
while read -r _i; do - _attr=$(getfattr -m "security.selinux" "$_i" 2>/dev/null) - if [[ -z "$_attr" ]]; then - restorecon "$_i"; + _attr=$(getfattr -m "security.selinux" "$_i" 2> /dev/null) + if [[ -z $_attr ]]; then + restorecon "$_i" fi done <<< "$(find "$_path")" } @@ -947,7 +948,7 @@ check_fence_kdump_config() nodes=$(kdump_get_conf_val "fence_kdump_nodes")
for node in $nodes; do - if [[ "$node" = "$hostname" ]]; then + if [[ $node == "$hostname" ]]; then derror "Option fence_kdump_nodes cannot contain $hostname" return 1 fi @@ -1003,25 +1004,26 @@ check_failure_action_config() default_option=$(kdump_get_conf_val default) failure_action=$(kdump_get_conf_val failure_action)
- if [[ -z "$failure_action" ]] && [[ -z "$default_option" ]]; then + if [[ -z $failure_action ]] && [[ -z $default_option ]]; then return 0 - elif [[ -n "$failure_action" ]] && [[ -n "$default_option" ]]; then + elif [[ -n $failure_action ]] && [[ -n $default_option ]]; then derror "Cannot specify 'failure_action' and 'default' option together" return 1 fi
- if [[ -n "$default_option" ]]; then + if [[ -n $default_option ]]; then option="default" failure_action="$default_option" fi
case "$failure_action" in - reboot|halt|poweroff|shell|dump_to_rootfs) + reboot | halt | poweroff | shell | dump_to_rootfs) return 0 - ;; - *) + ;; + *) dinfo $"Usage kdump.conf: $option {reboot|halt|poweroff|shell|dump_to_rootfs}" return 1 + ;; esac }
@@ -1030,16 +1032,17 @@ check_final_action_config() local final_action
final_action=$(kdump_get_conf_val final_action) - if [[ -z "$final_action" ]]; then + if [[ -z $final_action ]]; then return 0 else case "$final_action" in - reboot|halt|poweroff) + reboot | halt | poweroff) return 0 - ;; - *) + ;; + *) dinfo $"Usage kdump.conf: final_action {reboot|halt|poweroff}" return 1 + ;; esac fi } @@ -1056,7 +1059,7 @@ start() return 1 fi
- if sestatus 2>/dev/null | grep -q "SELinux status.*enabled"; then + if sestatus 2> /dev/null | grep -q "SELinux status.*enabled"; then selinux_relabel fi
@@ -1187,7 +1190,8 @@ stop() return 0 }
-rebuild() { +rebuild() +{ check_config || return 1
if check_ssh_config; then @@ -1203,33 +1207,34 @@ rebuild() { return $? }
-do_estimate() { +do_estimate() +{ local kdump_mods local -A large_mods local baseline local kernel_size mod_size initrd_size baseline_size runtime_size reserved_size estimated_size recommended_size - local size_mb=$(( 1024 * 1024 )) + local size_mb=$((1024 * 1024))
setup_initrd - if [[ ! -f "$TARGET_INITRD" ]]; then + if [[ ! -f $TARGET_INITRD ]]; then derror "kdumpctl estimate: kdump initramfs is not built yet." exit 1 fi
kdump_mods="$(lsinitrd "$TARGET_INITRD" -f /usr/lib/dracut/hostonly-kernel-modules.txt | tr '\n' ' ')" baseline=$(kdump_get_arch_recommend_size) - if [[ "${baseline: -1}" == "M" ]]; then + if [[ ${baseline: -1} == "M" ]]; then baseline=${baseline%M} - elif [[ "${baseline: -1}" == "G" ]]; then - baseline=$(( ${baseline%G} * 1024 )) - elif [[ "${baseline: -1}" == "T" ]]; then - baseline=$(( ${baseline%Y} * 1048576 )) + elif [[ ${baseline: -1} == "G" ]]; then + baseline=$((${baseline%G} * 1024)) + elif [[ ${baseline: -1} == "T" ]]; then + baseline=$((${baseline%Y} * 1048576)) fi
# The default pre-reserved crashkernel value baseline_size=$((baseline * size_mb)) # Current reserved crashkernel size - reserved_size=$(</sys/kernel/kexec_crash_size) + reserved_size=$(< /sys/kernel/kexec_crash_size) # A pre-estimated value for userspace usage and kernel # runtime allocation, 64M should good for most cases runtime_size=$((64 * size_mb)) @@ -1240,7 +1245,7 @@ do_estimate() { # Kernel modules static size after loaded mod_size=0 while read -r _name _size _; do - if [[ ! " $kdump_mods " == *" $_name "* ]]; then + if [[ " $kdump_mods " != *" $_name "* ]]; then continue fi mod_size=$((mod_size + _size)) @@ -1255,8 +1260,8 @@ do_estimate() { crypt_size=0 for _dev in $(get_all_kdump_crypt_dev); do _crypt_info=$(cryptsetup luksDump "/dev/block/$_dev") - [[ $(echo "$_crypt_info" | sed -n "s/^Version:\s*(.*)/\1/p" ) == "2" ]] || continue - for _mem in $(echo "$_crypt_info" | sed -n "s/\sMemory:\s*(.*)/\1/p" | sort -n ); do + [[ $(echo "$_crypt_info" | sed -n "s/^Version:\s*(.*)/\1/p") == "2" ]] || continue + for _mem in $(echo "$_crypt_info" | sed -n "s/\sMemory:\s*(.*)/\1/p" | sort -n); do crypt_size=$((crypt_size + _mem * 1024)) break done @@ -1277,10 +1282,10 @@ do_estimate() { echo "Kernel modules size: $((mod_size / size_mb))M" echo "Initramfs size: $((initrd_size / size_mb))M" echo "Runtime reservation: $((runtime_size / size_mb))M" - [[ $crypt_size -ne 0 ]] && \ - echo "LUKS required size: $((crypt_size / size_mb))M" + [[ $crypt_size -ne 0 ]] && + echo "LUKS required size: $((crypt_size / size_mb))M" echo -n "Large modules:" - if [[ "${#large_mods[@]}" -eq 0 ]]; then + if [[ ${#large_mods[@]} -eq 0 ]]; then echo " <none>" else echo "" @@ -1294,14 +1299,15 @@ do_estimate() { fi }
-reset_crashkernel() { +reset_crashkernel() +{ local kernel=$1 entry crashkernel_default local grub_etc_default="/etc/default/grub"
- [[ -z "$kernel" ]] && kernel=$(uname -r) - crashkernel_default=$(<"/usr/lib/modules/$kernel/crashkernel.default") &>/dev/null + [[ -z $kernel ]] && kernel=$(uname -r) + crashkernel_default=$(< "/usr/lib/modules/$kernel/crashkernel.default") &> /dev/null
- if [[ -z "$crashkernel_default" ]]; then + if [[ -z $crashkernel_default ]]; then derror "$kernel doesn't have a crashkernel.default" exit 1 fi @@ -1318,7 +1324,7 @@ reset_crashkernel() { entry=${entry#"} entry=${entry%"}
- if [[ -f "$grub_etc_default" ]]; then + if [[ -f $grub_etc_default ]]; then sed -i -e "s/^(GRUB_CMDLINE_LINUX=.*)crashkernel=[^\ "]*([\ "].*)$/\1$crashkernel_default\2/" "$grub_etc_default" fi
@@ -1328,18 +1334,18 @@ reset_crashkernel() { fi }
-if [[ ! -f "$KDUMP_CONFIG_FILE" ]]; then +if [[ ! -f $KDUMP_CONFIG_FILE ]]; then derror "Error: No kdump config file found!" exit 1 fi
-main () +main() { # Determine if the dump mode is kdump or fadump determine_dump_mode
case "$1" in - start) + start) if [[ -s /proc/vmcore ]]; then save_core reboot @@ -1347,51 +1353,52 @@ main () start fi ;; - stop) + stop) stop ;; - status) + status) EXIT_CODE=0 check_current_status case "$?" in - 0) + 0) dinfo "Kdump is operational" EXIT_CODE=0 ;; - 1) + 1) dinfo "Kdump is not operational" EXIT_CODE=3 ;; esac exit $EXIT_CODE ;; - reload) + reload) reload ;; - restart) + restart) stop start ;; - rebuild) + rebuild) rebuild ;; - condrestart) - ;; - propagate) + condrestart) ;; + + propagate) propagate_ssh_key ;; - showmem) + showmem) show_reserved_mem ;; - estimate) + estimate) do_estimate ;; - reset-crashkernel) + reset-crashkernel) reset_crashkernel "$2" ;; - *) + *) dinfo $"Usage: $0 {estimate|start|stop|status|restart|reload|rebuild|reset-crashkernel|propagate|showmem}" exit 1 + ;; esac }
@@ -1400,6 +1407,9 @@ single_instance_lock
# To avoid fd 9 leaking, we invoke a subshell, close fd 9 and call main. # So that fd isn't leaking when main is invoking a subshell. -(exec 9<&-; main "$@") +( + exec 9<&- + main "$@" +)
exit $? diff --git a/mkdumprd b/mkdumprd index 9c8ba232..55948a8c 100644 --- a/mkdumprd +++ b/mkdumprd @@ -27,7 +27,7 @@ SAVE_PATH=$(get_save_path) OVERRIDE_RESETTABLE=0
extra_modules="" -dracut_args=( --add kdumpbase --quiet --hostonly --hostonly-cmdline --hostonly-i18n --hostonly-mode strict -o "plymouth dash resume ifcfg earlykdump" ) +dracut_args=(--add kdumpbase --quiet --hostonly --hostonly-cmdline --hostonly-i18n --hostonly-mode strict -o "plymouth dash resume ifcfg earlykdump")
MKDUMPRD_TMPDIR="$(mktemp -d -t mkdumprd.XXXXXX)" [ -d "$MKDUMPRD_TMPDIR" ] || perror_exit "dracut: mktemp -p -d -t dracut.XXXXXX failed." @@ -43,66 +43,71 @@ trap ' # clean up after ourselves no matter how we die. trap 'exit 1;' SIGINT
-add_dracut_arg() { - dracut_args+=( "$@" ) +add_dracut_arg() +{ + dracut_args+=("$@") }
-add_dracut_mount() { - add_dracut_arg "--mount" "$1" +add_dracut_mount() +{ + add_dracut_arg "--mount" "$1" }
-add_dracut_sshkey() { - add_dracut_arg "--sshkey" "$1" +add_dracut_sshkey() +{ + add_dracut_arg "--sshkey" "$1" }
# caller should ensure $1 is valid and mounted in 1st kernel -to_mount() { - local _target=$1 _fstype=$2 _options=$3 _sed_cmd _new_mntpoint _pdev - - _new_mntpoint=$(get_kdump_mntpoint_from_target "$_target") - _fstype="${_fstype:-$(get_fs_type_from_target "$_target")}" - _options="${_options:-$(get_mntopt_from_target "$_target")}" - _options="${_options:-defaults}" - - if [[ "$_fstype" == "nfs"* ]]; then - _pdev=$_target - _sed_cmd+='s/,addr=[^,]*//;' - _sed_cmd+='s/,proto=[^,]*//;' - _sed_cmd+='s/,clientaddr=[^,]*//;' - else - # for non-nfs _target converting to use udev persistent name - _pdev="$(kdump_get_persistent_dev "$_target")" - if [[ -z $_pdev ]]; then - return 1 - fi - fi - - # mount fs target as rw in 2nd kernel - _sed_cmd+='s/(^|,)ro($|,)/\1rw\2/g;' - # with 'noauto' in fstab nfs and non-root disk mount will fail in 2nd - # kernel, filter it out here. - _sed_cmd+='s/(^|,)noauto($|,)/\1/g;' - # drop nofail or nobootwait - _sed_cmd+='s/(^|,)nofail($|,)/\1/g;' - _sed_cmd+='s/(^|,)nobootwait($|,)/\1/g;' - - _options=$(echo "$_options" | sed "$_sed_cmd") - - echo "$_pdev $_new_mntpoint $_fstype $_options" +to_mount() +{ + local _target=$1 _fstype=$2 _options=$3 _sed_cmd _new_mntpoint _pdev + + _new_mntpoint=$(get_kdump_mntpoint_from_target "$_target") + _fstype="${_fstype:-$(get_fs_type_from_target "$_target")}" + _options="${_options:-$(get_mntopt_from_target "$_target")}" + _options="${_options:-defaults}" + + if [[ $_fstype == "nfs"* ]]; then + _pdev=$_target + _sed_cmd+='s/,addr=[^,]*//;' + _sed_cmd+='s/,proto=[^,]*//;' + _sed_cmd+='s/,clientaddr=[^,]*//;' + else + # for non-nfs _target converting to use udev persistent name + _pdev="$(kdump_get_persistent_dev "$_target")" + if [[ -z $_pdev ]]; then + return 1 + fi + fi + + # mount fs target as rw in 2nd kernel + _sed_cmd+='s/(^|,)ro($|,)/\1rw\2/g;' + # with 'noauto' in fstab nfs and non-root disk mount will fail in 2nd + # kernel, filter it out here. + _sed_cmd+='s/(^|,)noauto($|,)/\1/g;' + # drop nofail or nobootwait + _sed_cmd+='s/(^|,)nofail($|,)/\1/g;' + _sed_cmd+='s/(^|,)nobootwait($|,)/\1/g;' + + _options=$(echo "$_options" | sed "$_sed_cmd") + + echo "$_pdev $_new_mntpoint $_fstype $_options" }
#Function: get_ssh_size #$1=dump target #called from while loop and shouldn't read from stdin, so we're using "ssh -n" -get_ssh_size() { - local _out +get_ssh_size() +{ + local _out
- if ! _out=$(ssh -q -n -i "$SSH_KEY_LOCATION" -o BatchMode=yes -o StrictHostKeyChecking=yes "$1" "df -P $SAVE_PATH"); then - perror_exit "checking remote ssh server available size failed." - fi + if ! _out=$(ssh -q -n -i "$SSH_KEY_LOCATION" -o BatchMode=yes -o StrictHostKeyChecking=yes "$1" "df -P $SAVE_PATH"); then + perror_exit "checking remote ssh server available size failed." + fi
- #ssh output removed the line break, so print field NF-2 - echo -n "$_out" | tail -1 | awk '{avail=NF-2; print $avail}' + #ssh output removed the line break, so print field NF-2 + echo -n "$_out" | tail -1 | awk '{avail=NF-2; print $avail}' }
#mkdir if save path does not exist on ssh dump target @@ -111,317 +116,320 @@ get_ssh_size() { #called from while loop and shouldn't read from stdin, so we're using "ssh -n" mkdir_save_path_ssh() { - local _opt _dir - _opt=(-i "$SSH_KEY_LOCATION" -o BatchMode=yes -o StrictHostKeyChecking=yes) - ssh -qn "${_opt[@]}" "$1" mkdir -p "$SAVE_PATH" &>/dev/null || \ - perror_exit "mkdir failed on $1:$SAVE_PATH" + local _opt _dir + _opt=(-i "$SSH_KEY_LOCATION" -o BatchMode=yes -o StrictHostKeyChecking=yes) + ssh -qn "${_opt[@]}" "$1" mkdir -p "$SAVE_PATH" &> /dev/null || + perror_exit "mkdir failed on $1:$SAVE_PATH"
- # check whether user has write permission on $1:$SAVE_PATH - _dir=$(ssh -qn "${_opt[@]}" "$1" mktemp -dqp "$SAVE_PATH" 2>/dev/null) || \ - perror_exit "Could not create temporary directory on $1:$SAVE_PATH. Make sure user has write permission on destination" - ssh -qn "${_opt[@]}" "$1" rmdir "$_dir" + # check whether user has write permission on $1:$SAVE_PATH + _dir=$(ssh -qn "${_opt[@]}" "$1" mktemp -dqp "$SAVE_PATH" 2> /dev/null) || + perror_exit "Could not create temporary directory on $1:$SAVE_PATH. Make sure user has write permission on destination" + ssh -qn "${_opt[@]}" "$1" rmdir "$_dir"
- return 0 + return 0 }
#Function: get_fs_size #$1=dump target -get_fs_size() { - df -P "$(get_mntpoint_from_target "$1")/$SAVE_PATH"|tail -1|awk '{print $4}' +get_fs_size() +{ + df -P "$(get_mntpoint_from_target "$1")/$SAVE_PATH" | tail -1 | awk '{print $4}' }
#Function: get_raw_size #$1=dump target -get_raw_size() { - fdisk -s "$1" +get_raw_size() +{ + fdisk -s "$1" }
#Function: check_size #$1: dump type string ('raw', 'fs', 'ssh') #$2: dump target -check_size() { - local avail memtotal - - memtotal=$(awk '/MemTotal/{print $2}' /proc/meminfo) - case "$1" in - raw) - avail=$(get_raw_size "$2") - ;; - ssh) - avail=$(get_ssh_size "$2") - ;; - fs) - avail=$(get_fs_size "$2") - ;; - *) - return - esac || perror_exit "Check dump target size failed" - - if [[ "$avail" -lt "$memtotal" ]]; then - dwarn "Warning: There might not be enough space to save a vmcore." - dwarn " The size of $2 should be greater than $memtotal kilo bytes." - fi +check_size() +{ + local avail memtotal + + memtotal=$(awk '/MemTotal/{print $2}' /proc/meminfo) + case "$1" in + raw) + avail=$(get_raw_size "$2") + ;; + ssh) + avail=$(get_ssh_size "$2") + ;; + fs) + avail=$(get_fs_size "$2") + ;; + *) + return + ;; + esac || perror_exit "Check dump target size failed" + + if [[ $avail -lt $memtotal ]]; then + dwarn "Warning: There might not be enough space to save a vmcore." + dwarn " The size of $2 should be greater than $memtotal kilo bytes." + fi }
check_save_path_fs() { - local _path=$1 + local _path=$1
- if [[ ! -d $_path ]]; then - perror_exit "Dump path $_path does not exist." - fi + if [[ ! -d $_path ]]; then + perror_exit "Dump path $_path does not exist." + fi }
mount_failure() { - local _target=$1 - local _mnt=$2 - local _fstype=$3 - local msg="Failed to mount $_target" + local _target=$1 + local _mnt=$2 + local _fstype=$3 + local msg="Failed to mount $_target"
- if [[ -n "$_mnt" ]]; then - msg="$msg on $_mnt" - fi + if [[ -n $_mnt ]]; then + msg="$msg on $_mnt" + fi
- msg="$msg for kdump preflight check." + msg="$msg for kdump preflight check."
- if [[ $_fstype = "nfs" ]]; then - msg="$msg Please make sure nfs-utils has been installed." - fi + if [[ $_fstype == "nfs" ]]; then + msg="$msg Please make sure nfs-utils has been installed." + fi
- perror_exit "$msg" + perror_exit "$msg" }
check_user_configured_target() { - local _target=$1 _cfg_fs_type=$2 _mounted - local _mnt _opt _fstype - - _mnt=$(get_mntpoint_from_target "$_target") - _opt=$(get_mntopt_from_target "$_target") - _fstype=$(get_fs_type_from_target "$_target") - - if [[ -n "$_fstype" ]]; then - # In case of nfs4, nfs should be used instead, nfs* options is deprecated in kdump.conf - [[ $_fstype = "nfs"* ]] && _fstype=nfs - - if [[ -n "$_cfg_fs_type" ]] && [[ "$_fstype" != "$_cfg_fs_type" ]]; then - perror_exit ""$_target" have a wrong type config "$_cfg_fs_type", expected "$_fstype"" - fi - else - _fstype="$_cfg_fs_type" - _fstype="$_cfg_fs_type" - fi - - # For noauto mount, mount it inplace with default value. - # Else use the temporary target directory - if [[ -n "$_mnt" ]]; then - if ! is_mounted "$_mnt"; then - if [[ $_opt = *",noauto"* ]]; then - mount "$_mnt" || mount_failure "$_target" "$_mnt" "$_fstype" - _mounted=$_mnt - else - perror_exit "Dump target "$_target" is neither mounted nor configured as "noauto"" - fi - fi - else - _mnt=$MKDUMPRD_TMPMNT - mkdir -p "$_mnt" - mount "$_target" "$_mnt" -t "$_fstype" -o defaults || mount_failure "$_target" "" "$_fstype" - _mounted=$_mnt - fi - - # For user configured target, use $SAVE_PATH as the dump path within the target - if [[ ! -d "$_mnt/$SAVE_PATH" ]]; then - perror_exit "Dump path "$_mnt/$SAVE_PATH" does not exist in dump target "$_target"" - fi - - check_size fs "$_target" - - # Unmount it early, if function is interrupted and didn't reach here, the shell trap will clear it up anyway - if [[ -n "$_mounted" ]]; then - umount -f -- "$_mounted" - fi + local _target=$1 _cfg_fs_type=$2 _mounted + local _mnt _opt _fstype + + _mnt=$(get_mntpoint_from_target "$_target") + _opt=$(get_mntopt_from_target "$_target") + _fstype=$(get_fs_type_from_target "$_target") + + if [[ -n $_fstype ]]; then + # In case of nfs4, nfs should be used instead, nfs* options is deprecated in kdump.conf + [[ $_fstype == "nfs"* ]] && _fstype=nfs + + if [[ -n $_cfg_fs_type ]] && [[ $_fstype != "$_cfg_fs_type" ]]; then + perror_exit ""$_target" have a wrong type config "$_cfg_fs_type", expected "$_fstype"" + fi + else + _fstype="$_cfg_fs_type" + _fstype="$_cfg_fs_type" + fi + + # For noauto mount, mount it inplace with default value. + # Else use the temporary target directory + if [[ -n $_mnt ]]; then + if ! is_mounted "$_mnt"; then + if [[ $_opt == *",noauto"* ]]; then + mount "$_mnt" || mount_failure "$_target" "$_mnt" "$_fstype" + _mounted=$_mnt + else + perror_exit "Dump target "$_target" is neither mounted nor configured as "noauto"" + fi + fi + else + _mnt=$MKDUMPRD_TMPMNT + mkdir -p "$_mnt" + mount "$_target" "$_mnt" -t "$_fstype" -o defaults || mount_failure "$_target" "" "$_fstype" + _mounted=$_mnt + fi + + # For user configured target, use $SAVE_PATH as the dump path within the target + if [[ ! -d "$_mnt/$SAVE_PATH" ]]; then + perror_exit "Dump path "$_mnt/$SAVE_PATH" does not exist in dump target "$_target"" + fi + + check_size fs "$_target" + + # Unmount it early, if function is interrupted and didn't reach here, the shell trap will clear it up anyway + if [[ -n $_mounted ]]; then + umount -f -- "$_mounted" + fi }
# $1: core_collector config value -verify_core_collector() { - local _cmd="${1%% *}" - local _params="${1#* }" - - if [[ "$_cmd" != "makedumpfile" ]]; then - if is_raw_dump_target; then - dwarn "Warning: specifying a non-makedumpfile core collector, you will have to recover the vmcore manually." - fi - return - fi - - if is_ssh_dump_target || is_raw_dump_target; then - if ! strstr "$_params" "-F"; then - perror_exit "The specified dump target needs makedumpfile "-F" option." - fi - _params="$_params vmcore" - else - _params="$_params vmcore dumpfile" - fi - - # shellcheck disable=SC2086 - if ! $_cmd --check-params $_params; then - perror_exit "makedumpfile parameter check failed." - fi +verify_core_collector() +{ + local _cmd="${1%% *}" + local _params="${1#* }" + + if [[ $_cmd != "makedumpfile" ]]; then + if is_raw_dump_target; then + dwarn "Warning: specifying a non-makedumpfile core collector, you will have to recover the vmcore manually." + fi + return + fi + + if is_ssh_dump_target || is_raw_dump_target; then + if ! strstr "$_params" "-F"; then + perror_exit 'The specified dump target needs makedumpfile "-F" option.' + fi + _params="$_params vmcore" + else + _params="$_params vmcore dumpfile" + fi + + # shellcheck disable=SC2086 + if ! $_cmd --check-params $_params; then + perror_exit "makedumpfile parameter check failed." + fi }
-add_mount() { - local _mnt +add_mount() +{ + local _mnt
- _mnt=$(to_mount "$@") || exit 1 + _mnt=$(to_mount "$@") || exit 1
- add_dracut_mount "$_mnt" + add_dracut_mount "$_mnt" }
#handle the case user does not specify the dump target explicitly handle_default_dump_target() { - local _target - local _mntpoint + local _target + local _mntpoint
- is_user_configured_dump_target && return + is_user_configured_dump_target && return
- check_save_path_fs "$SAVE_PATH" + check_save_path_fs "$SAVE_PATH"
- _save_path=$(get_bind_mount_source "$SAVE_PATH") - _target=$(get_target_from_path "$_save_path") - _mntpoint=$(get_mntpoint_from_target "$_target") + _save_path=$(get_bind_mount_source "$SAVE_PATH") + _target=$(get_target_from_path "$_save_path") + _mntpoint=$(get_mntpoint_from_target "$_target")
- SAVE_PATH=${_save_path##"$_mntpoint"} - add_mount "$_target" - check_size fs "$_target" + SAVE_PATH=${_save_path##"$_mntpoint"} + add_mount "$_target" + check_size fs "$_target" }
# $1: function name for_each_block_target() { - local dev majmin + local dev majmin
- for dev in $(get_kdump_targets); do - [[ -b "$dev" ]] || continue - majmin=$(get_maj_min "$dev") - check_block_and_slaves "$1" "$majmin" && return 1 - done + for dev in $(get_kdump_targets); do + [[ -b $dev ]] || continue + majmin=$(get_maj_min "$dev") + check_block_and_slaves "$1" "$majmin" && return 1 + done
- return 0 + return 0 }
#judge if a specific device with $1 is unresettable #return false if unresettable. is_unresettable() { - local path device resettable=1 - - path="/sys/$(udevadm info --query=all --path="/sys/dev/block/$1" | awk '/^P:/ {print $2}' | sed -e 's/(cciss[0-9]+/).*/\1/g' -e 's//block/.*$//')/resettable" - if [[ -f "$path" ]]; then - resettable="$(<"$path")" - [[ $resettable -eq 0 ]] && [[ "$OVERRIDE_RESETTABLE" -eq 0 ]] && { - device=$(udevadm info --query=all --path="/sys/dev/block/$1" | awk -F= '/DEVNAME/{print $2}') - derror "Error: Can not save vmcore because device $device is unresettable" - return 0 - } - fi - - return 1 + local path device resettable=1 + + path="/sys/$(udevadm info --query=all --path="/sys/dev/block/$1" | awk '/^P:/ {print $2}' | sed -e 's/(cciss[0-9]+/).*/\1/g' -e 's//block/.*$//')/resettable" + if [[ -f $path ]]; then + resettable="$(< "$path")" + [[ $resettable -eq 0 ]] && [[ $OVERRIDE_RESETTABLE -eq 0 ]] && { + device=$(udevadm info --query=all --path="/sys/dev/block/$1" | awk -F= '/DEVNAME/{print $2}') + derror "Error: Can not save vmcore because device $device is unresettable" + return 0 + } + fi + + return 1 }
#check if machine is resettable. #return true if resettable check_resettable() { - local _target _override_resettable + local _target _override_resettable
- _override_resettable=$(kdump_get_conf_val override_resettable) - OVERRIDE_RESETTABLE=${_override_resettable:-$OVERRIDE_RESETTABLE} + _override_resettable=$(kdump_get_conf_val override_resettable) + OVERRIDE_RESETTABLE=${_override_resettable:-$OVERRIDE_RESETTABLE}
- for_each_block_target is_unresettable && return + for_each_block_target is_unresettable && return
- return 1 + return 1 }
check_crypt() { - local _dev + local _dev
- for _dev in $(get_kdump_targets); do - if [[ -n $(get_luks_crypt_dev "$(get_maj_min "$_dev")") ]]; then - derror "Device $_dev is encrypted." && return 1 - fi - done + for _dev in $(get_kdump_targets); do + if [[ -n $(get_luks_crypt_dev "$(get_maj_min "$_dev")") ]]; then + derror "Device $_dev is encrypted." && return 1 + fi + done }
if ! check_resettable; then - exit 1 + exit 1 fi
if ! check_crypt; then - dwarn "Warning: Encrypted device is in dump path, which is not recommended, see kexec-kdump-howto.txt for more details." + dwarn "Warning: Encrypted device is in dump path, which is not recommended, see kexec-kdump-howto.txt for more details." fi
# firstly get right SSH_KEY_LOCATION keyfile=$(kdump_get_conf_val sshkey) -if [[ -f "$keyfile" ]]; then - # canonicalize the path - SSH_KEY_LOCATION=$(/usr/bin/readlink -m "$keyfile") +if [[ -f $keyfile ]]; then + # canonicalize the path + SSH_KEY_LOCATION=$(/usr/bin/readlink -m "$keyfile") fi
-while read -r config_opt config_val; -do - # remove inline comments after the end of a directive. - case "$config_opt" in - extra_modules) - extra_modules="$extra_modules $config_val" - ;; - ext[234]|xfs|btrfs|minix|nfs) - check_user_configured_target "$config_val" "$config_opt" - add_mount "$config_val" "$config_opt" - ;; - raw) - # checking raw disk writable - dd if="$config_val" count=1 of=/dev/null > /dev/null 2>&1 || { - perror_exit "Bad raw disk $config_val" - } - _praw=$(persistent_policy="by-id" kdump_get_persistent_dev "$config_val") - if [[ -z $_praw ]]; then - exit 1 - fi - add_dracut_arg "--device" "$_praw" - check_size raw "$config_val" - ;; - ssh) - if strstr "$config_val" "@"; - then - mkdir_save_path_ssh "$config_val" - check_size ssh "$config_val" - add_dracut_sshkey "$SSH_KEY_LOCATION" - else - perror_exit "Bad ssh dump target $config_val" - fi - ;; - core_collector) - verify_core_collector "$config_val" - ;; - dracut_args) - while read -r dracut_arg; do - add_dracut_arg "$dracut_arg" - done <<< "$(echo "$config_val" | xargs -n 1 echo)" - ;; - *) - ;; - esac +while read -r config_opt config_val; do + # remove inline comments after the end of a directive. + case "$config_opt" in + extra_modules) + extra_modules="$extra_modules $config_val" + ;; + ext[234] | xfs | btrfs | minix | nfs) + check_user_configured_target "$config_val" "$config_opt" + add_mount "$config_val" "$config_opt" + ;; + raw) + # checking raw disk writable + dd if="$config_val" count=1 of=/dev/null > /dev/null 2>&1 || { + perror_exit "Bad raw disk $config_val" + } + _praw=$(persistent_policy="by-id" kdump_get_persistent_dev "$config_val") + if [[ -z $_praw ]]; then + exit 1 + fi + add_dracut_arg "--device" "$_praw" + check_size raw "$config_val" + ;; + ssh) + if strstr "$config_val" "@"; then + mkdir_save_path_ssh "$config_val" + check_size ssh "$config_val" + add_dracut_sshkey "$SSH_KEY_LOCATION" + else + perror_exit "Bad ssh dump target $config_val" + fi + ;; + core_collector) + verify_core_collector "$config_val" + ;; + dracut_args) + while read -r dracut_arg; do + add_dracut_arg "$dracut_arg" + done <<< "$(echo "$config_val" | xargs -n 1 echo)" + ;; + *) ;; + + esac done <<< "$(kdump_read_conf)"
handle_default_dump_target
-if [[ -n "$extra_modules" ]] -then - add_dracut_arg "--add-drivers" "$extra_modules" +if [[ -n $extra_modules ]]; then + add_dracut_arg "--add-drivers" "$extra_modules" fi
# TODO: The below check is not needed anymore with the introduction of @@ -430,11 +438,11 @@ fi # parameter available in fadump case. So, find a way to fix that first # before removing this check. if ! is_fadump_capable; then - # The 2nd rootfs mount stays behind the normal dump target mount, - # so it doesn't affect the logic of check_dump_fs_modified(). - is_dump_to_rootfs && add_mount "$(to_dev_name "$(get_root_fs_device)")" + # The 2nd rootfs mount stays behind the normal dump target mount, + # so it doesn't affect the logic of check_dump_fs_modified(). + is_dump_to_rootfs && add_mount "$(to_dev_name "$(get_root_fs_device)")"
- add_dracut_arg "--no-hostonly-default-device" + add_dracut_arg "--no-hostonly-default-device" fi
dracut "${dracut_args[@]}" "$@" diff --git a/mkfadumprd b/mkfadumprd index 5c96ee75..b890f838 100644 --- a/mkfadumprd +++ b/mkfadumprd @@ -44,22 +44,22 @@ fi
### Unpack the initramfs having dump capture capability mkdir -p "$MKFADUMPRD_TMPDIR/fadumproot" -if ! (pushd "$MKFADUMPRD_TMPDIR/fadumproot" > /dev/null && lsinitrd --unpack "$FADUMP_INITRD" && \ +if ! (pushd "$MKFADUMPRD_TMPDIR/fadumproot" > /dev/null && lsinitrd --unpack "$FADUMP_INITRD" && popd > /dev/null); then derror "mkfadumprd: failed to unpack '$MKFADUMPRD_TMPDIR'" exit 1 fi
### Pack it into the normal boot initramfs with zz-fadumpinit module -_dracut_isolate_args=(\ - --rebuild "$REBUILD_INITRD" --add zz-fadumpinit \ +_dracut_isolate_args=( + --rebuild "$REBUILD_INITRD" --add zz-fadumpinit -i "$MKFADUMPRD_TMPDIR/fadumproot" /fadumproot -i "$MKFADUMPRD_TMPDIR/fadumproot/usr/lib/dracut/hostonly-kernel-modules.txt" /usr/lib/dracut/fadump-kernel-modules.txt )
if is_squash_available; then - _dracut_isolate_args+=( --add squash ) + _dracut_isolate_args+=(--add squash) fi
if ! dracut --force --quiet "${_dracut_isolate_args[@]}" "$@" "$TARGET_INITRD"; then
Move all function needed in second kernel from kdump-lib.sh to kdump-lib-initramfs.sh, and update shebang headers.
Now kdump-lib-initramfs.sh is an independent lib scirpt, no longer depend on kdump-lib.sh, and kdump-lib.sh is no longer needed for second kernel.
In later commits, functions in kdump-lib-initramfs.sh will be reworked to be POSIX compatible, kdump-lib.sh will contain bash only functions.
POSIX shell have very limited features, eg. `local` keyword doesn't exist in POSIX but we rely on that heavily. So kdump-lib.sh will use bash syntax and contain most complex helper and codes. kdump-lib-initramfs.sh will contain minimum set of helpers, and shared by both first and second kernel.
Signed-off-by: Kairui Song kasong@redhat.com --- .editorconfig | 2 +- dracut-module-setup.sh | 1 - kdump-lib-initramfs.sh | 133 ++++++++++++++++++++++++++++++++++++++++- kdump-lib.sh | 131 +--------------------------------------- 4 files changed, 135 insertions(+), 132 deletions(-)
diff --git a/.editorconfig b/.editorconfig index 52aadba3..d65868c4 100644 --- a/.editorconfig +++ b/.editorconfig @@ -18,7 +18,7 @@ binary_next_line = false space_redirects = true
# Some scirpts will only run with bash -[{mkfadumprd,mkdumprd,kdumpctl}] +[{mkfadumprd,mkdumprd,kdumpctl,kdump-lib.sh}] shell_variant = bash
# Use dracut code style for *-module-setup.sh diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index 11db5aa3..d5a710b9 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -1033,7 +1033,6 @@ install() { inst "/usr/bin/printf" "/sbin/printf" inst "/usr/bin/logger" "/sbin/logger" inst "/usr/bin/chmod" "/sbin/chmod" - inst "/lib/kdump/kdump-lib.sh" "/lib/kdump-lib.sh" inst "/lib/kdump/kdump-lib-initramfs.sh" "/lib/kdump-lib-initramfs.sh" inst "/lib/kdump/kdump-logger.sh" "/lib/kdump-logger.sh" inst "$moddir/kdump.sh" "/usr/bin/kdump.sh" diff --git a/kdump-lib-initramfs.sh b/kdump-lib-initramfs.sh index 50443e55..e7f623c4 100755 --- a/kdump-lib-initramfs.sh +++ b/kdump-lib-initramfs.sh @@ -1,8 +1,11 @@ -# These variables and functions are useful in 2nd kernel +#!/bin/sh +# +# Function and variables used in initramfs environment, POSIX compatible +#
-. /lib/kdump-lib.sh . /lib/kdump-logger.sh
+DEFAULT_PATH="/var/crash/" KDUMP_PATH="/var/crash" KDUMP_LOG_FILE="/run/initramfs/kexec-dmesg.log" CORE_COLLECTOR="" @@ -20,6 +23,7 @@ KDUMP_PRE="" KDUMP_POST="" NEWROOT="/sysroot" OPALCORE="/sys/firmware/opal/mpipl/core" +KDUMP_CONFIG_FILE="/etc/kdump.conf"
#initiate the kdump logger dlog_init @@ -28,6 +32,131 @@ if [ $? -ne 0 ]; then exit 1 fi
+# Read kdump config in well formated style +kdump_read_conf() +{ + # Following steps are applied in order: strip tailing comment, strip tailing space, + # strip heading space, match non-empty line, remove duplicated spaces between conf name and value + [ -f "$KDUMP_CONFIG_FILE" ] && sed -n -e "s/#.*//;s/\s*$//;s/^\s*//;s/(\S+)\s*(.*)/\1 \2/p" $KDUMP_CONFIG_FILE +} + +# Retrieves config value defined in kdump.conf +# $1: config name, sed regexp compatible +kdump_get_conf_val() { + # For lines matching "^\s*$1\s+", remove matched part (config name including space), + # remove tailing comment, space, then store in hold space. Print out the hold buffer on last line. + [ -f "$KDUMP_CONFIG_FILE" ] && \ + sed -n -e "/^\s*($1)\s+/{s/^\s*($1)\s+//;s/#.*//;s/\s*$//;h};${x;p}" $KDUMP_CONFIG_FILE +} + +is_mounted() +{ + findmnt -k -n $1 &>/dev/null +} + +get_mount_info() +{ + local _info_type=$1 _src_type=$2 _src=$3; shift 3 + local _info=$(findmnt -k -n -r -o $_info_type --$_src_type $_src $@) + + [ -z "$_info" ] && [ -e "/etc/fstab" ] && _info=$(findmnt -s -n -r -o $_info_type --$_src_type $_src $@) + + echo $_info +} + +is_ipv6_address() +{ + echo $1 | grep -q ":" +} + +is_fs_type_nfs() +{ + [ "$1" = "nfs" ] || [ "$1" = "nfs4" ] +} + +# If $1 contains dracut_args "--mount", return <filesystem type> +get_dracut_args_fstype() +{ + echo $1 | grep "--mount" | sed "s/.*--mount .(.*)/\1/" | cut -d' ' -f3 +} + +# If $1 contains dracut_args "--mount", return <device> +get_dracut_args_target() +{ + echo $1 | grep "--mount" | sed "s/.*--mount .(.*)/\1/" | cut -d' ' -f1 +} + +get_save_path() +{ + local _save_path=$(kdump_get_conf_val path) + [ -z "$_save_path" ] && _save_path=$DEFAULT_PATH + + # strip the duplicated "/" + echo $_save_path | tr -s / +} + +get_root_fs_device() +{ + findmnt -k -f -n -o SOURCE / +} + +# Return the current underlying device of a path, ignore bind mounts +get_target_from_path() +{ + local _target + + _target=$(df $1 2>/dev/null | tail -1 | awk '{print $1}') + [[ "$_target" == "/dev/root" ]] && [[ ! -e /dev/root ]] && _target=$(get_root_fs_device) + echo $_target +} + +get_fs_type_from_target() +{ + get_mount_info FSTYPE source $1 -f +} + +get_mntpoint_from_target() +{ + # --source is applied to ensure non-bind mount is returned + get_mount_info TARGET source $1 -f +} + +is_ssh_dump_target() +{ + [[ $(kdump_get_conf_val ssh) == *@* ]] +} + +is_raw_dump_target() +{ + [[ $(kdump_get_conf_val raw) ]] +} + +is_nfs_dump_target() +{ + if [[ $(kdump_get_conf_val nfs) ]]; then + return 0; + fi + + if is_fs_type_nfs $(get_dracut_args_fstype "$(kdump_get_conf_val dracut_args)"); then + return 0 + fi + + local _save_path=$(get_save_path) + local _target=$(get_target_from_path $_save_path) + local _fstype=$(get_fs_type_from_target $_target) + + if is_fs_type_nfs $_fstype; then + return 0 + fi + + return 1 +} + +is_fs_dump_target() +{ + [[ $(kdump_get_conf_val "ext[234]|xfs|btrfs|minix") ]] +} + get_kdump_confs() { local config_opt config_val diff --git a/kdump-lib.sh b/kdump-lib.sh index 58422d8b..5a1fcf02 100755 --- a/kdump-lib.sh +++ b/kdump-lib.sh @@ -1,13 +1,13 @@ -#!/bin/sh +#!/bin/bash # # Kdump common variables and functions #
-DEFAULT_PATH="/var/crash/" +. /usr/lib/kdump/kdump-lib-initramfs.sh + FENCE_KDUMP_CONFIG_FILE="/etc/sysconfig/fence_kdump" FENCE_KDUMP_SEND="/usr/libexec/fence_kdump_send" FADUMP_ENABLED_SYS_NODE="/sys/kernel/fadump_enabled" -KDUMP_CONFIG_FILE="/etc/kdump.conf"
is_fadump_capable() { @@ -35,64 +35,6 @@ perror_exit() { exit 1 }
-is_fs_type_nfs() -{ - [ "$1" = "nfs" ] || [ "$1" = "nfs4" ] -} - -is_ssh_dump_target() -{ - [[ $(kdump_get_conf_val ssh) == *@* ]] -} - -is_nfs_dump_target() -{ - if [[ $(kdump_get_conf_val nfs) ]]; then - return 0; - fi - - if is_fs_type_nfs $(get_dracut_args_fstype "$(kdump_get_conf_val dracut_args)"); then - return 0 - fi - - local _save_path=$(get_save_path) - local _target=$(get_target_from_path $_save_path) - local _fstype=$(get_fs_type_from_target $_target) - - if is_fs_type_nfs $_fstype; then - return 0 - fi - - return 1 -} - -is_raw_dump_target() -{ - [[ $(kdump_get_conf_val raw) ]] -} - -is_fs_dump_target() -{ - [[ $(kdump_get_conf_val "ext[234]|xfs|btrfs|minix") ]] -} - -# Read kdump config in well formatted style -kdump_read_conf() -{ - # Following steps are applied in order: strip tailing comment, strip tailing space, - # strip heading space, match non-empty line, remove duplicated spaces between conf name and value - [ -f "$KDUMP_CONFIG_FILE" ] && sed -n -e "s/#.*//;s/\s*$//;s/^\s*//;s/(\S+)\s*(.*)/\1 \2/p" $KDUMP_CONFIG_FILE -} - -# Retrieves config value defined in kdump.conf -# $1: config name, sed regexp compatible -kdump_get_conf_val() { - # For lines matching "^\s*$1\s+", remove matched part (config name including space), - # remove tailing comment, space, then store in hold space. Print out the hold buffer on last line. - [ -f "$KDUMP_CONFIG_FILE" ] && \ - sed -n -e "/^\s*($1)\s+/{s/^\s*($1)\s+//;s/#.*//;s/\s*$//;h};${x;p}" $KDUMP_CONFIG_FILE -} - # Check if fence kdump is configured in Pacemaker cluster is_pcs_fence_kdump() { @@ -142,20 +84,6 @@ get_user_configured_dump_disk() [ -b "$_target" ] && echo $_target }
-get_root_fs_device() -{ - findmnt -k -f -n -o SOURCE / -} - -get_save_path() -{ - local _save_path=$(kdump_get_conf_val path) - [ -z "$_save_path" ] && _save_path=$DEFAULT_PATH - - # strip the duplicated "/" - echo $_save_path | tr -s / -} - get_block_dump_target() { local _target _path @@ -261,46 +189,10 @@ get_bind_mount_source() echo $_mnt$_fsroot$_path }
-# Return the current underlaying device of a path, ignore bind mounts -get_target_from_path() -{ - local _target - - _target=$(df $1 2>/dev/null | tail -1 | awk '{print $1}') - [[ "$_target" == "/dev/root" ]] && [[ ! -e /dev/root ]] && _target=$(get_root_fs_device) - echo $_target -} - -is_mounted() -{ - findmnt -k -n $1 &>/dev/null -} - -get_mount_info() -{ - local _info_type=$1 _src_type=$2 _src=$3; shift 3 - local _info=$(findmnt -k -n -r -o $_info_type --$_src_type $_src $@) - - [ -z "$_info" ] && [ -e "/etc/fstab" ] && _info=$(findmnt -s -n -r -o $_info_type --$_src_type $_src $@) - - echo $_info -} - -get_fs_type_from_target() -{ - get_mount_info FSTYPE source $1 -f -} - get_mntopt_from_target() { get_mount_info OPTIONS source $1 -f } -# Find the general mount point of a dump target, not the bind mount point -get_mntpoint_from_target() -{ - # Expcilitly specify --source to findmnt could ensure non-bind mount is returned - get_mount_info TARGET source $1 -f -}
# Get the path where the target will be mounted in kdump kernel # $1: kdump target device @@ -345,11 +237,6 @@ is_atomic() grep -q "ostree" /proc/cmdline }
-is_ipv6_address() -{ - echo $1 | grep -q ":" -} - # get ip address or hostname from nfs/ssh config value get_remote_host() { @@ -562,18 +449,6 @@ is_mount_in_dracut_args() [[ $(kdump_get_conf_val dracut_args) == *" --mount "* ]] }
-# If $1 contains dracut_args "--mount", return <filesystem type> -get_dracut_args_fstype() -{ - echo $1 | grep "--mount" | sed "s/.*--mount .(.*)/\1/" | cut -d' ' -f3 -} - -# If $1 contains dracut_args "--mount", return <device> -get_dracut_args_target() -{ - echo $1 | grep "--mount" | sed "s/.*--mount .(.*)/\1/" | cut -d' ' -f1 -} - check_crash_mem_reserved() { local mem_reserved
On Thu, 19 Aug 2021 19:39:30 +0800 Kairui Song kasong@redhat.com wrote:
Move all function needed in second kernel from kdump-lib.sh to kdump-lib-initramfs.sh, and update shebang headers.
Now kdump-lib-initramfs.sh is an independent lib scirpt, no longer
s/scirpt/script
depend on kdump-lib.sh, and kdump-lib.sh is no longer needed for second kernel.
In later commits, functions in kdump-lib-initramfs.sh will be reworked to be POSIX compatible, kdump-lib.sh will contain bash only functions.
POSIX shell have very limited features, eg. `local` keyword doesn't exist in POSIX but we rely on that heavily. So kdump-lib.sh will use bash syntax and contain most complex helper and codes. kdump-lib-initramfs.sh will contain minimum set of helpers, and shared by both first and second kernel.
Signed-off-by: Kairui Song kasong@redhat.com
.editorconfig | 2 +- dracut-module-setup.sh | 1 - kdump-lib-initramfs.sh | 133 ++++++++++++++++++++++++++++++++++++++++- kdump-lib.sh | 131 +--------------------------------------- 4 files changed, 135 insertions(+), 132 deletions(-)
diff --git a/.editorconfig b/.editorconfig index 52aadba3..d65868c4 100644 --- a/.editorconfig +++ b/.editorconfig @@ -18,7 +18,7 @@ binary_next_line = false space_redirects = true
# Some scirpts will only run with bash -[{mkfadumprd,mkdumprd,kdumpctl}] +[{mkfadumprd,mkdumprd,kdumpctl,kdump-lib.sh}] shell_variant = bash
# Use dracut code style for *-module-setup.sh diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index 11db5aa3..d5a710b9 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -1033,7 +1033,6 @@ install() { inst "/usr/bin/printf" "/sbin/printf" inst "/usr/bin/logger" "/sbin/logger" inst "/usr/bin/chmod" "/sbin/chmod"
- inst "/lib/kdump/kdump-lib.sh" "/lib/kdump-lib.sh" inst "/lib/kdump/kdump-lib-initramfs.sh" "/lib/kdump-lib-initramfs.sh" inst "/lib/kdump/kdump-logger.sh" "/lib/kdump-logger.sh" inst "$moddir/kdump.sh" "/usr/bin/kdump.sh"
diff --git a/kdump-lib-initramfs.sh b/kdump-lib-initramfs.sh index 50443e55..e7f623c4 100755 --- a/kdump-lib-initramfs.sh +++ b/kdump-lib-initramfs.sh @@ -1,8 +1,11 @@ -# These variables and functions are useful in 2nd kernel +#!/bin/sh +# +# Function and variables used in initramfs environment, POSIX compatible +#
-. /lib/kdump-lib.sh . /lib/kdump-logger.sh
+DEFAULT_PATH="/var/crash/" KDUMP_PATH="/var/crash" KDUMP_LOG_FILE="/run/initramfs/kexec-dmesg.log" CORE_COLLECTOR="" @@ -20,6 +23,7 @@ KDUMP_PRE="" KDUMP_POST="" NEWROOT="/sysroot" OPALCORE="/sys/firmware/opal/mpipl/core" +KDUMP_CONFIG_FILE="/etc/kdump.conf"
#initiate the kdump logger dlog_init @@ -28,6 +32,131 @@ if [ $? -ne 0 ]; then exit 1 fi
+# Read kdump config in well formated style +kdump_read_conf() +{
- # Following steps are applied in order: strip tailing comment, strip tailing space,
- # strip heading space, match non-empty line, remove duplicated spaces between conf name and value
- [ -f "$KDUMP_CONFIG_FILE" ] && sed -n -e "s/#.*//;s/\s*$//;s/^\s*//;s/(\S+)\s*(.*)/\1 \2/p" $KDUMP_CONFIG_FILE
+}
+# Retrieves config value defined in kdump.conf +# $1: config name, sed regexp compatible +kdump_get_conf_val() {
- # For lines matching "^\s*$1\s+", remove matched part (config name including space),
- # remove tailing comment, space, then store in hold space. Print out the hold buffer on last line.
- [ -f "$KDUMP_CONFIG_FILE" ] && \
sed -n -e "/^\s*\($1\)\s\+/{s/^\s*\($1\)\s\+//;s/#.*//;s/\s*$//;h};\${x;p}" $KDUMP_CONFIG_FILE
+}
+is_mounted() +{
- findmnt -k -n $1 &>/dev/null
+}
+get_mount_info() +{
- local _info_type=$1 _src_type=$2 _src=$3; shift 3
- local _info=$(findmnt -k -n -r -o $_info_type --$_src_type $_src $@)
- [ -z "$_info" ] && [ -e "/etc/fstab" ] && _info=$(findmnt -s -n -r -o $_info_type --$_src_type $_src $@)
- echo $_info
+}
+is_ipv6_address() +{
- echo $1 | grep -q ":"
+}
+is_fs_type_nfs() +{
- [ "$1" = "nfs" ] || [ "$1" = "nfs4" ]
+}
+# If $1 contains dracut_args "--mount", return <filesystem type> +get_dracut_args_fstype() +{
- echo $1 | grep "--mount" | sed "s/.*--mount .(.*)/\1/" | cut -d' ' -f3
+}
+# If $1 contains dracut_args "--mount", return <device> +get_dracut_args_target() +{
- echo $1 | grep "--mount" | sed "s/.*--mount .(.*)/\1/" | cut -d' ' -f1
+}
Are these greps really necessary? Isn't sed able to handle this on its own?
Thanks Philipp
+get_save_path() +{
- local _save_path=$(kdump_get_conf_val path)
- [ -z "$_save_path" ] && _save_path=$DEFAULT_PATH
- # strip the duplicated "/"
- echo $_save_path | tr -s /
+}
+get_root_fs_device() +{
- findmnt -k -f -n -o SOURCE /
+}
+# Return the current underlying device of a path, ignore bind mounts +get_target_from_path() +{
- local _target
- _target=$(df $1 2>/dev/null | tail -1 | awk '{print $1}')
- [[ "$_target" == "/dev/root" ]] && [[ ! -e /dev/root ]] && _target=$(get_root_fs_device)
- echo $_target
+}
+get_fs_type_from_target() +{
- get_mount_info FSTYPE source $1 -f
+}
+get_mntpoint_from_target() +{
- # --source is applied to ensure non-bind mount is returned
- get_mount_info TARGET source $1 -f
+}
+is_ssh_dump_target() +{
- [[ $(kdump_get_conf_val ssh) == *@* ]]
+}
+is_raw_dump_target() +{
- [[ $(kdump_get_conf_val raw) ]]
+}
+is_nfs_dump_target() +{
- if [[ $(kdump_get_conf_val nfs) ]]; then
return 0;
- fi
- if is_fs_type_nfs $(get_dracut_args_fstype "$(kdump_get_conf_val dracut_args)"); then
return 0
- fi
- local _save_path=$(get_save_path)
- local _target=$(get_target_from_path $_save_path)
- local _fstype=$(get_fs_type_from_target $_target)
- if is_fs_type_nfs $_fstype; then
return 0
- fi
- return 1
+}
+is_fs_dump_target() +{
- [[ $(kdump_get_conf_val "ext[234]|xfs|btrfs|minix") ]]
+}
get_kdump_confs() { local config_opt config_val diff --git a/kdump-lib.sh b/kdump-lib.sh index 58422d8b..5a1fcf02 100755 --- a/kdump-lib.sh +++ b/kdump-lib.sh @@ -1,13 +1,13 @@ -#!/bin/sh +#!/bin/bash # # Kdump common variables and functions #
-DEFAULT_PATH="/var/crash/" +. /usr/lib/kdump/kdump-lib-initramfs.sh
FENCE_KDUMP_CONFIG_FILE="/etc/sysconfig/fence_kdump" FENCE_KDUMP_SEND="/usr/libexec/fence_kdump_send" FADUMP_ENABLED_SYS_NODE="/sys/kernel/fadump_enabled" -KDUMP_CONFIG_FILE="/etc/kdump.conf"
is_fadump_capable() { @@ -35,64 +35,6 @@ perror_exit() { exit 1 }
-is_fs_type_nfs() -{
- [ "$1" = "nfs" ] || [ "$1" = "nfs4" ]
-}
-is_ssh_dump_target() -{
- [[ $(kdump_get_conf_val ssh) == *@* ]]
-}
-is_nfs_dump_target() -{
- if [[ $(kdump_get_conf_val nfs) ]]; then
return 0;
- fi
- if is_fs_type_nfs $(get_dracut_args_fstype "$(kdump_get_conf_val dracut_args)"); then
return 0
- fi
- local _save_path=$(get_save_path)
- local _target=$(get_target_from_path $_save_path)
- local _fstype=$(get_fs_type_from_target $_target)
- if is_fs_type_nfs $_fstype; then
return 0
- fi
- return 1
-}
-is_raw_dump_target() -{
- [[ $(kdump_get_conf_val raw) ]]
-}
-is_fs_dump_target() -{
- [[ $(kdump_get_conf_val "ext[234]|xfs|btrfs|minix") ]]
-}
-# Read kdump config in well formatted style -kdump_read_conf() -{
- # Following steps are applied in order: strip tailing comment, strip tailing space,
- # strip heading space, match non-empty line, remove duplicated spaces between conf name and value
- [ -f "$KDUMP_CONFIG_FILE" ] && sed -n -e "s/#.*//;s/\s*$//;s/^\s*//;s/(\S+)\s*(.*)/\1 \2/p" $KDUMP_CONFIG_FILE
-}
-# Retrieves config value defined in kdump.conf -# $1: config name, sed regexp compatible -kdump_get_conf_val() {
- # For lines matching "^\s*$1\s+", remove matched part (config name including space),
- # remove tailing comment, space, then store in hold space. Print out the hold buffer on last line.
- [ -f "$KDUMP_CONFIG_FILE" ] && \
sed -n -e "/^\s*\($1\)\s\+/{s/^\s*\($1\)\s\+//;s/#.*//;s/\s*$//;h};\${x;p}" $KDUMP_CONFIG_FILE
-}
# Check if fence kdump is configured in Pacemaker cluster is_pcs_fence_kdump() { @@ -142,20 +84,6 @@ get_user_configured_dump_disk() [ -b "$_target" ] && echo $_target }
-get_root_fs_device() -{
- findmnt -k -f -n -o SOURCE /
-}
-get_save_path() -{
- local _save_path=$(kdump_get_conf_val path)
- [ -z "$_save_path" ] && _save_path=$DEFAULT_PATH
- # strip the duplicated "/"
- echo $_save_path | tr -s /
-}
get_block_dump_target() { local _target _path @@ -261,46 +189,10 @@ get_bind_mount_source() echo $_mnt$_fsroot$_path }
-# Return the current underlaying device of a path, ignore bind mounts -get_target_from_path() -{
- local _target
- _target=$(df $1 2>/dev/null | tail -1 | awk '{print $1}')
- [[ "$_target" == "/dev/root" ]] && [[ ! -e /dev/root ]] && _target=$(get_root_fs_device)
- echo $_target
-}
-is_mounted() -{
- findmnt -k -n $1 &>/dev/null
-}
-get_mount_info() -{
- local _info_type=$1 _src_type=$2 _src=$3; shift 3
- local _info=$(findmnt -k -n -r -o $_info_type --$_src_type $_src $@)
- [ -z "$_info" ] && [ -e "/etc/fstab" ] && _info=$(findmnt -s -n -r -o $_info_type --$_src_type $_src $@)
- echo $_info
-}
-get_fs_type_from_target() -{
- get_mount_info FSTYPE source $1 -f
-}
get_mntopt_from_target() { get_mount_info OPTIONS source $1 -f } -# Find the general mount point of a dump target, not the bind mount point -get_mntpoint_from_target() -{
- # Expcilitly specify --source to findmnt could ensure non-bind mount is returned
- get_mount_info TARGET source $1 -f
-}
# Get the path where the target will be mounted in kdump kernel # $1: kdump target device @@ -345,11 +237,6 @@ is_atomic() grep -q "ostree" /proc/cmdline }
-is_ipv6_address() -{
- echo $1 | grep -q ":"
-}
# get ip address or hostname from nfs/ssh config value get_remote_host() { @@ -562,18 +449,6 @@ is_mount_in_dracut_args() [[ $(kdump_get_conf_val dracut_args) == *" --mount "* ]] }
-# If $1 contains dracut_args "--mount", return <filesystem type> -get_dracut_args_fstype() -{
- echo $1 | grep "--mount" | sed "s/.*--mount .(.*)/\1/" | cut -d' ' -f3
-}
-# If $1 contains dracut_args "--mount", return <device> -get_dracut_args_target() -{
- echo $1 | grep "--mount" | sed "s/.*--mount .(.*)/\1/" | cut -d' ' -f1
-}
check_crash_mem_reserved() { local mem_reserved
return On Fri, Sep 3, 2021 at 8:31 PM Philipp Rudo prudo@redhat.com wrote:
On Thu, 19 Aug 2021 19:39:30 +0800 Kairui Song kasong@redhat.com wrote:
Move all function needed in second kernel from kdump-lib.sh to kdump-lib-initramfs.sh, and update shebang headers.
Now kdump-lib-initramfs.sh is an independent lib scirpt, no longer
s/scirpt/script
depend on kdump-lib.sh, and kdump-lib.sh is no longer needed for second kernel.
In later commits, functions in kdump-lib-initramfs.sh will be reworked to be POSIX compatible, kdump-lib.sh will contain bash only functions.
POSIX shell have very limited features, eg. `local` keyword doesn't exist in POSIX but we rely on that heavily. So kdump-lib.sh will use bash syntax and contain most complex helper and codes. kdump-lib-initramfs.sh will contain minimum set of helpers, and shared by both first and second kernel.
Signed-off-by: Kairui Song kasong@redhat.com
.editorconfig | 2 +- dracut-module-setup.sh | 1 - kdump-lib-initramfs.sh | 133 ++++++++++++++++++++++++++++++++++++++++- kdump-lib.sh | 131 +--------------------------------------- 4 files changed, 135 insertions(+), 132 deletions(-)
diff --git a/.editorconfig b/.editorconfig index 52aadba3..d65868c4 100644 --- a/.editorconfig +++ b/.editorconfig @@ -18,7 +18,7 @@ binary_next_line = false space_redirects = true
# Some scirpts will only run with bash -[{mkfadumprd,mkdumprd,kdumpctl}] +[{mkfadumprd,mkdumprd,kdumpctl,kdump-lib.sh}] shell_variant = bash
# Use dracut code style for *-module-setup.sh diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index 11db5aa3..d5a710b9 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -1033,7 +1033,6 @@ install() { inst "/usr/bin/printf" "/sbin/printf" inst "/usr/bin/logger" "/sbin/logger" inst "/usr/bin/chmod" "/sbin/chmod"
- inst "/lib/kdump/kdump-lib.sh" "/lib/kdump-lib.sh" inst "/lib/kdump/kdump-lib-initramfs.sh" "/lib/kdump-lib-initramfs.sh" inst "/lib/kdump/kdump-logger.sh" "/lib/kdump-logger.sh" inst "$moddir/kdump.sh" "/usr/bin/kdump.sh"
diff --git a/kdump-lib-initramfs.sh b/kdump-lib-initramfs.sh index 50443e55..e7f623c4 100755 --- a/kdump-lib-initramfs.sh +++ b/kdump-lib-initramfs.sh @@ -1,8 +1,11 @@ -# These variables and functions are useful in 2nd kernel +#!/bin/sh +# +# Function and variables used in initramfs environment, POSIX compatible +#
-. /lib/kdump-lib.sh . /lib/kdump-logger.sh
+DEFAULT_PATH="/var/crash/" KDUMP_PATH="/var/crash" KDUMP_LOG_FILE="/run/initramfs/kexec-dmesg.log" CORE_COLLECTOR="" @@ -20,6 +23,7 @@ KDUMP_PRE="" KDUMP_POST="" NEWROOT="/sysroot" OPALCORE="/sys/firmware/opal/mpipl/core" +KDUMP_CONFIG_FILE="/etc/kdump.conf"
#initiate the kdump logger dlog_init @@ -28,6 +32,131 @@ if [ $? -ne 0 ]; then exit 1 fi
+# Read kdump config in well formated style +kdump_read_conf() +{
- # Following steps are applied in order: strip tailing comment, strip tailing space,
- # strip heading space, match non-empty line, remove duplicated spaces between conf name and value
- [ -f "$KDUMP_CONFIG_FILE" ] && sed -n -e "s/#.*//;s/\s*$//;s/^\s*//;s/(\S+)\s*(.*)/\1 \2/p" $KDUMP_CONFIG_FILE
+}
+# Retrieves config value defined in kdump.conf +# $1: config name, sed regexp compatible +kdump_get_conf_val() {
- # For lines matching "^\s*$1\s+", remove matched part (config name including space),
- # remove tailing comment, space, then store in hold space. Print out the hold buffer on last line.
- [ -f "$KDUMP_CONFIG_FILE" ] && \
sed -n -e "/^\s*\($1\)\s\+/{s/^\s*\($1\)\s\+//;s/#.*//;s/\s*$//;h};\${x;p}" $KDUMP_CONFIG_FILE
+}
+is_mounted() +{
- findmnt -k -n $1 &>/dev/null
+}
+get_mount_info() +{
- local _info_type=$1 _src_type=$2 _src=$3; shift 3
- local _info=$(findmnt -k -n -r -o $_info_type --$_src_type $_src $@)
- [ -z "$_info" ] && [ -e "/etc/fstab" ] && _info=$(findmnt -s -n -r -o $_info_type --$_src_type $_src $@)
- echo $_info
+}
+is_ipv6_address() +{
- echo $1 | grep -q ":"
+}
+is_fs_type_nfs() +{
- [ "$1" = "nfs" ] || [ "$1" = "nfs4" ]
+}
+# If $1 contains dracut_args "--mount", return <filesystem type> +get_dracut_args_fstype() +{
- echo $1 | grep "--mount" | sed "s/.*--mount .(.*)/\1/" | cut -d' ' -f3
+}
+# If $1 contains dracut_args "--mount", return <device> +get_dracut_args_target() +{
- echo $1 | grep "--mount" | sed "s/.*--mount .(.*)/\1/" | cut -d' ' -f1
+}
Are these greps really necessary? Isn't sed able to handle this on its own?
They are not needed, this code is actually broken, it won't work if --mount and its value are separated by tab or '=', and get_dracut_args_fstype returns the trailing '"'.
I think we can fix it later though, get_dracut_args_fstype just worked because all it's caller is using wildcard to match fstype, so trailing character is not causing any issue (yet), better introduce a helper to handle arg parsing, many places in kexec-tools script are handling arg parsing wrongly.
Thanks Philipp
+get_save_path() +{
- local _save_path=$(kdump_get_conf_val path)
- [ -z "$_save_path" ] && _save_path=$DEFAULT_PATH
- # strip the duplicated "/"
- echo $_save_path | tr -s /
+}
+get_root_fs_device() +{
- findmnt -k -f -n -o SOURCE /
+}
+# Return the current underlying device of a path, ignore bind mounts +get_target_from_path() +{
- local _target
- _target=$(df $1 2>/dev/null | tail -1 | awk '{print $1}')
- [[ "$_target" == "/dev/root" ]] && [[ ! -e /dev/root ]] && _target=$(get_root_fs_device)
- echo $_target
+}
+get_fs_type_from_target() +{
- get_mount_info FSTYPE source $1 -f
+}
+get_mntpoint_from_target() +{
- # --source is applied to ensure non-bind mount is returned
- get_mount_info TARGET source $1 -f
+}
+is_ssh_dump_target() +{
- [[ $(kdump_get_conf_val ssh) == *@* ]]
+}
+is_raw_dump_target() +{
- [[ $(kdump_get_conf_val raw) ]]
+}
+is_nfs_dump_target() +{
- if [[ $(kdump_get_conf_val nfs) ]]; then
return 0;
- fi
- if is_fs_type_nfs $(get_dracut_args_fstype "$(kdump_get_conf_val dracut_args)"); then
return 0
- fi
- local _save_path=$(get_save_path)
- local _target=$(get_target_from_path $_save_path)
- local _fstype=$(get_fs_type_from_target $_target)
- if is_fs_type_nfs $_fstype; then
return 0
- fi
- return 1
+}
+is_fs_dump_target() +{
- [[ $(kdump_get_conf_val "ext[234]|xfs|btrfs|minix") ]]
+}
get_kdump_confs() { local config_opt config_val diff --git a/kdump-lib.sh b/kdump-lib.sh index 58422d8b..5a1fcf02 100755 --- a/kdump-lib.sh +++ b/kdump-lib.sh @@ -1,13 +1,13 @@ -#!/bin/sh +#!/bin/bash # # Kdump common variables and functions #
-DEFAULT_PATH="/var/crash/" +. /usr/lib/kdump/kdump-lib-initramfs.sh
FENCE_KDUMP_CONFIG_FILE="/etc/sysconfig/fence_kdump" FENCE_KDUMP_SEND="/usr/libexec/fence_kdump_send" FADUMP_ENABLED_SYS_NODE="/sys/kernel/fadump_enabled" -KDUMP_CONFIG_FILE="/etc/kdump.conf"
is_fadump_capable() { @@ -35,64 +35,6 @@ perror_exit() { exit 1 }
-is_fs_type_nfs() -{
- [ "$1" = "nfs" ] || [ "$1" = "nfs4" ]
-}
-is_ssh_dump_target() -{
- [[ $(kdump_get_conf_val ssh) == *@* ]]
-}
-is_nfs_dump_target() -{
- if [[ $(kdump_get_conf_val nfs) ]]; then
return 0;
- fi
- if is_fs_type_nfs $(get_dracut_args_fstype "$(kdump_get_conf_val dracut_args)"); then
return 0
- fi
- local _save_path=$(get_save_path)
- local _target=$(get_target_from_path $_save_path)
- local _fstype=$(get_fs_type_from_target $_target)
- if is_fs_type_nfs $_fstype; then
return 0
- fi
- return 1
-}
-is_raw_dump_target() -{
- [[ $(kdump_get_conf_val raw) ]]
-}
-is_fs_dump_target() -{
- [[ $(kdump_get_conf_val "ext[234]|xfs|btrfs|minix") ]]
-}
-# Read kdump config in well formatted style -kdump_read_conf() -{
- # Following steps are applied in order: strip tailing comment, strip tailing space,
- # strip heading space, match non-empty line, remove duplicated spaces between conf name and value
- [ -f "$KDUMP_CONFIG_FILE" ] && sed -n -e "s/#.*//;s/\s*$//;s/^\s*//;s/(\S+)\s*(.*)/\1 \2/p" $KDUMP_CONFIG_FILE
-}
-# Retrieves config value defined in kdump.conf -# $1: config name, sed regexp compatible -kdump_get_conf_val() {
- # For lines matching "^\s*$1\s+", remove matched part (config name including space),
- # remove tailing comment, space, then store in hold space. Print out the hold buffer on last line.
- [ -f "$KDUMP_CONFIG_FILE" ] && \
sed -n -e "/^\s*\($1\)\s\+/{s/^\s*\($1\)\s\+//;s/#.*//;s/\s*$//;h};\${x;p}" $KDUMP_CONFIG_FILE
-}
# Check if fence kdump is configured in Pacemaker cluster is_pcs_fence_kdump() { @@ -142,20 +84,6 @@ get_user_configured_dump_disk() [ -b "$_target" ] && echo $_target }
-get_root_fs_device() -{
- findmnt -k -f -n -o SOURCE /
-}
-get_save_path() -{
- local _save_path=$(kdump_get_conf_val path)
- [ -z "$_save_path" ] && _save_path=$DEFAULT_PATH
- # strip the duplicated "/"
- echo $_save_path | tr -s /
-}
get_block_dump_target() { local _target _path @@ -261,46 +189,10 @@ get_bind_mount_source() echo $_mnt$_fsroot$_path }
-# Return the current underlaying device of a path, ignore bind mounts -get_target_from_path() -{
- local _target
- _target=$(df $1 2>/dev/null | tail -1 | awk '{print $1}')
- [[ "$_target" == "/dev/root" ]] && [[ ! -e /dev/root ]] && _target=$(get_root_fs_device)
- echo $_target
-}
-is_mounted() -{
- findmnt -k -n $1 &>/dev/null
-}
-get_mount_info() -{
- local _info_type=$1 _src_type=$2 _src=$3; shift 3
- local _info=$(findmnt -k -n -r -o $_info_type --$_src_type $_src $@)
- [ -z "$_info" ] && [ -e "/etc/fstab" ] && _info=$(findmnt -s -n -r -o $_info_type --$_src_type $_src $@)
- echo $_info
-}
-get_fs_type_from_target() -{
- get_mount_info FSTYPE source $1 -f
-}
get_mntopt_from_target() { get_mount_info OPTIONS source $1 -f } -# Find the general mount point of a dump target, not the bind mount point -get_mntpoint_from_target() -{
- # Expcilitly specify --source to findmnt could ensure non-bind mount is returned
- get_mount_info TARGET source $1 -f
-}
# Get the path where the target will be mounted in kdump kernel # $1: kdump target device @@ -345,11 +237,6 @@ is_atomic() grep -q "ostree" /proc/cmdline }
-is_ipv6_address() -{
- echo $1 | grep -q ":"
-}
# get ip address or hostname from nfs/ssh config value get_remote_host() { @@ -562,18 +449,6 @@ is_mount_in_dracut_args() [[ $(kdump_get_conf_val dracut_args) == *" --mount "* ]] }
-# If $1 contains dracut_args "--mount", return <filesystem type> -get_dracut_args_fstype() -{
- echo $1 | grep "--mount" | sed "s/.*--mount .(.*)/\1/" | cut -d' ' -f3
-}
-# If $1 contains dracut_args "--mount", return <device> -get_dracut_args_target() -{
- echo $1 | grep "--mount" | sed "s/.*--mount .(.*)/\1/" | cut -d' ' -f1
-}
check_crash_mem_reserved() { local mem_reserved
kdump-error-handler.sh does nothing except calling three functions, it can be easily merged into kdump.sh by using a parameter to run the error handling routine.
kdump-lib-initramfs.sh was created to hold the three shared functions and related code, so by merging these two files, kdump-lib-initramfs.sh can be simplified by a lot.
Following up commits will clean up kdump-lib-initramfs.sh.
Signed-off-by: Kairui Song kasong@redhat.com --- dracut-kdump-emergency.service | 2 +- dracut-kdump-error-handler.sh | 10 ---------- dracut-kdump.sh | 21 ++++++++++++++++----- dracut-module-setup.sh | 1 - kexec-tools.spec | 2 -- 5 files changed, 17 insertions(+), 19 deletions(-) delete mode 100755 dracut-kdump-error-handler.sh
diff --git a/dracut-kdump-emergency.service b/dracut-kdump-emergency.service index f2f6fadb..0cf70514 100644 --- a/dracut-kdump-emergency.service +++ b/dracut-kdump-emergency.service @@ -12,7 +12,7 @@ Environment=HOME=/ Environment=DRACUT_SYSTEMD=1 Environment=NEWROOT=/sysroot WorkingDirectory=/ -ExecStart=/bin/kdump-error-handler.sh +ExecStart=/bin/kdump.sh --error-handler ExecStopPost=-/bin/rm -f -- /.console_lock Type=oneshot StandardInput=tty-force diff --git a/dracut-kdump-error-handler.sh b/dracut-kdump-error-handler.sh deleted file mode 100755 index fc2b9328..00000000 --- a/dracut-kdump-error-handler.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/sh - -. /lib/kdump-lib-initramfs.sh - -set -o pipefail -export PATH=$PATH:$KDUMP_SCRIPT_DIR - -get_kdump_confs -do_failure_action -do_final_action diff --git a/dracut-kdump.sh b/dracut-kdump.sh index 3c165b3a..352cad56 100755 --- a/dracut-kdump.sh +++ b/dracut-kdump.sh @@ -1,9 +1,7 @@ #!/bin/sh - -# continue here only if we have to save dump. -if [ -f /etc/fadump.initramfs ] && [ ! -f /proc/device-tree/rtas/ibm,kernel-dump ] && [ ! -f /proc/device-tree/ibm,opal/dump/mpipl-boot ]; then - exit 0 -fi +# +# The main kdump routine in capture kernel +#
. /lib/dracut-lib.sh . /lib/kdump-lib-initramfs.sh @@ -288,6 +286,19 @@ fence_kdump_notify() fi }
+if [ "$1" = "--error-handler" ]; then + get_kdump_confs + do_failure_action + do_final_action + + exit $? +fi + +# continue here only if we have to save dump. +if [ -f /etc/fadump.initramfs ] && [ ! -f /proc/device-tree/rtas/ibm,kernel-dump ] && [ ! -f /proc/device-tree/ibm,opal/dump/mpipl-boot ]; then + exit 0 +fi + read_kdump_confs fence_kdump_notify
diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index d5a710b9..227fdae8 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -1038,7 +1038,6 @@ install() { inst "$moddir/kdump.sh" "/usr/bin/kdump.sh" inst "$moddir/kdump-capture.service" "$systemdsystemunitdir/kdump-capture.service" systemctl -q --root "$initdir" add-wants initrd.target kdump-capture.service - inst "$moddir/kdump-error-handler.sh" "/usr/bin/kdump-error-handler.sh" # Replace existing emergency service and emergency target cp "$moddir/kdump-emergency.service" "$initdir/$systemdsystemunitdir/emergency.service" cp "$moddir/kdump-emergency.target" "$initdir/$systemdsystemunitdir/emergency.target" diff --git a/kexec-tools.spec b/kexec-tools.spec index 951c9d6e..ffb4730d 100644 --- a/kexec-tools.spec +++ b/kexec-tools.spec @@ -52,7 +52,6 @@ Source36: kdump-restart.sh Source100: dracut-kdump.sh Source101: dracut-module-setup.sh Source102: dracut-monitor_dd_progress -Source103: dracut-kdump-error-handler.sh Source104: dracut-kdump-emergency.service Source106: dracut-kdump-capture.service Source107: dracut-kdump-emergency.target @@ -241,7 +240,6 @@ mkdir -p -m755 $RPM_BUILD_ROOT/etc/kdump-adv-conf/kdump_dracut_modules/99kdumpba cp %{SOURCE100} $RPM_BUILD_ROOT/etc/kdump-adv-conf/kdump_dracut_modules/99kdumpbase/%{remove_dracut_prefix %{SOURCE100}} cp %{SOURCE101} $RPM_BUILD_ROOT/etc/kdump-adv-conf/kdump_dracut_modules/99kdumpbase/%{remove_dracut_prefix %{SOURCE101}} cp %{SOURCE102} $RPM_BUILD_ROOT/etc/kdump-adv-conf/kdump_dracut_modules/99kdumpbase/%{remove_dracut_prefix %{SOURCE102}} -cp %{SOURCE103} $RPM_BUILD_ROOT/etc/kdump-adv-conf/kdump_dracut_modules/99kdumpbase/%{remove_dracut_prefix %{SOURCE103}} cp %{SOURCE104} $RPM_BUILD_ROOT/etc/kdump-adv-conf/kdump_dracut_modules/99kdumpbase/%{remove_dracut_prefix %{SOURCE104}} cp %{SOURCE106} $RPM_BUILD_ROOT/etc/kdump-adv-conf/kdump_dracut_modules/99kdumpbase/%{remove_dracut_prefix %{SOURCE106}} cp %{SOURCE107} $RPM_BUILD_ROOT/etc/kdump-adv-conf/kdump_dracut_modules/99kdumpbase/%{remove_dracut_prefix %{SOURCE107}}
These dump related functions are only used by dracut-kdump.sh.
Signed-off-by: Kairui Song kasong@redhat.com --- dracut-kdump.sh | 288 ++++++++++++++++++++++++++++++++++++++++ kdump-lib-initramfs.sh | 289 ----------------------------------------- 2 files changed, 288 insertions(+), 289 deletions(-)
diff --git a/dracut-kdump.sh b/dracut-kdump.sh index 352cad56..a785ab92 100755 --- a/dracut-kdump.sh +++ b/dracut-kdump.sh @@ -4,13 +4,301 @@ #
. /lib/dracut-lib.sh +. /lib/kdump-logger.sh . /lib/kdump-lib-initramfs.sh
+#initiate the kdump logger +dlog_init +if [ $? -ne 0 ]; then + echo "failed to initiate the kdump logger." + exit 1 +fi + +KDUMP_PATH="/var/crash" +KDUMP_LOG_FILE="/run/initramfs/kexec-dmesg.log" +CORE_COLLECTOR="" +DEFAULT_CORE_COLLECTOR="makedumpfile -l --message-level 7 -d 31" +DMESG_COLLECTOR="/sbin/vmcore-dmesg" +FAILURE_ACTION="systemctl reboot -f" +DATEDIR=`date +%Y-%m-%d-%T` +HOST_IP='127.0.0.1' +DUMP_INSTRUCTION="" +SSH_KEY_LOCATION="/root/.ssh/kdump_id_rsa" +KDUMP_SCRIPT_DIR="/kdumpscripts" +DD_BLKSIZE=512 +FINAL_ACTION="systemctl reboot -f" +KDUMP_PRE="" +KDUMP_POST="" +NEWROOT="/sysroot" +OPALCORE="/sys/firmware/opal/mpipl/core" + set -o pipefail DUMP_RETVAL=0
export PATH=$PATH:$KDUMP_SCRIPT_DIR
+get_kdump_confs() +{ + local config_opt config_val + + while read config_opt config_val; + do + # remove inline comments after the end of a directive. + case "$config_opt" in + path) + KDUMP_PATH="$config_val" + ;; + core_collector) + [ -n "$config_val" ] && CORE_COLLECTOR="$config_val" + ;; + sshkey) + if [ -f "$config_val" ]; then + SSH_KEY_LOCATION=$config_val + fi + ;; + kdump_pre) + KDUMP_PRE="$config_val" + ;; + kdump_post) + KDUMP_POST="$config_val" + ;; + fence_kdump_args) + FENCE_KDUMP_ARGS="$config_val" + ;; + fence_kdump_nodes) + FENCE_KDUMP_NODES="$config_val" + ;; + failure_action|default) + case $config_val in + shell) + FAILURE_ACTION="kdump_emergency_shell" + ;; + reboot) + FAILURE_ACTION="systemctl reboot -f && exit" + ;; + halt) + FAILURE_ACTION="halt && exit" + ;; + poweroff) + FAILURE_ACTION="systemctl poweroff -f && exit" + ;; + dump_to_rootfs) + FAILURE_ACTION="dump_to_rootfs" + ;; + esac + ;; + final_action) + case $config_val in + reboot) + FINAL_ACTION="systemctl reboot -f" + ;; + halt) + FINAL_ACTION="halt" + ;; + poweroff) + FINAL_ACTION="systemctl poweroff -f" + ;; + esac + ;; + esac + done <<< "$(kdump_read_conf)" + + if [ -z "$CORE_COLLECTOR" ]; then + CORE_COLLECTOR="$DEFAULT_CORE_COLLECTOR" + if is_ssh_dump_target || is_raw_dump_target; then + CORE_COLLECTOR="$CORE_COLLECTOR -F" + fi + fi +} + +# store the kexec kernel log to a file. +save_log() +{ + dmesg -T > $KDUMP_LOG_FILE + + if command -v journalctl > /dev/null; then + journalctl -ab >> $KDUMP_LOG_FILE + fi + chmod 600 $KDUMP_LOG_FILE +} + +# dump_fs <mount point> +dump_fs() +{ + local _exitcode + local _mp=$1 + local _op=$(get_mount_info OPTIONS target $_mp -f) + ddebug "dump_fs _mp=$_mp _opts=$_op" + + if ! is_mounted "$_mp"; then + dinfo "dump path "$_mp" is not mounted, trying to mount..." + mount --target $_mp + if [ $? -ne 0 ]; then + derror "failed to dump to "$_mp", it's not a mount point!" + return 1 + fi + fi + + # Remove -F in makedumpfile case. We don't want a flat format dump here. + [[ $CORE_COLLECTOR = *makedumpfile* ]] && CORE_COLLECTOR=`echo $CORE_COLLECTOR | sed -e "s/-F//g"` + + local _dump_path=$(echo "$_mp/$KDUMP_PATH/$HOST_IP-$DATEDIR/" | tr -s /) + + dinfo "saving to $_dump_path" + + # Only remount to read-write mode if the dump target is mounted read-only. + if [[ "$_op" = "ro"* ]]; then + dinfo "Remounting the dump target in rw mode." + mount -o remount,rw $_mp || return 1 + fi + + mkdir -p $_dump_path || return 1 + + save_vmcore_dmesg_fs ${DMESG_COLLECTOR} "$_dump_path" + save_opalcore_fs "$_dump_path" + + dinfo "saving vmcore" + $CORE_COLLECTOR /proc/vmcore $_dump_path/vmcore-incomplete + _exitcode=$? + if [ $_exitcode -eq 0 ]; then + mv $_dump_path/vmcore-incomplete $_dump_path/vmcore + sync + dinfo "saving vmcore complete" + else + derror "saving vmcore failed, _exitcode:$_exitcode" + fi + + dinfo "saving the $KDUMP_LOG_FILE to $_dump_path/" + save_log + mv $KDUMP_LOG_FILE $_dump_path/ + if [ $_exitcode -ne 0 ]; then + return 1 + fi + + # improper kernel cmdline can cause the failure of echo, we can ignore this kind of failure + return 0 +} + +save_vmcore_dmesg_fs() { + local _dmesg_collector=$1 + local _path=$2 + + dinfo "saving vmcore-dmesg.txt to ${_path}" + $_dmesg_collector /proc/vmcore > ${_path}/vmcore-dmesg-incomplete.txt + _exitcode=$? + if [ $_exitcode -eq 0 ]; then + mv ${_path}/vmcore-dmesg-incomplete.txt ${_path}/vmcore-dmesg.txt + chmod 600 ${_path}/vmcore-dmesg.txt + + # Make sure file is on disk. There have been instances where later + # saving vmcore failed and system rebooted without sync and there + # was no vmcore-dmesg.txt available. + sync + dinfo "saving vmcore-dmesg.txt complete" + else + if [ -f ${_path}/vmcore-dmesg-incomplete.txt ]; then + chmod 600 ${_path}/vmcore-dmesg-incomplete.txt + fi + derror "saving vmcore-dmesg.txt failed" + fi +} + +save_opalcore_fs() { + local _path=$1 + + if [ ! -f $OPALCORE ]; then + # Check if we are on an old kernel that uses a different path + if [ -f /sys/firmware/opal/core ]; then + OPALCORE="/sys/firmware/opal/core" + else + return 0 + fi + fi + + dinfo "saving opalcore:$OPALCORE to ${_path}/opalcore" + cp $OPALCORE ${_path}/opalcore + if [ $? -ne 0 ]; then + derror "saving opalcore failed" + return 1 + fi + + sync + dinfo "saving opalcore complete" + return 0 +} + +dump_to_rootfs() +{ + + if [[ $(systemctl status dracut-initqueue | sed -n "s/^\s*Active: (\S*)\s.*$/\1/p") == "inactive" ]]; then + dinfo "Trying to bring up initqueue for rootfs mount" + systemctl start dracut-initqueue + fi + + dinfo "Clean up dead systemd services" + systemctl cancel + dinfo "Waiting for rootfs mount, will timeout after 90 seconds" + systemctl start --no-block sysroot.mount + + _loop=0 + while [ $_loop -lt 90 ] && ! is_mounted /sysroot; do + sleep 1 + _loop=$((_loop + 1)) + done + + if ! is_mounted /sysroot; then + derror "Failed to mount rootfs" + return + fi + + ddebug "NEWROOT=$NEWROOT" + dump_fs $NEWROOT +} + +kdump_emergency_shell() +{ + ddebug "Switching to kdump emergency shell..." + + [ -f /etc/profile ] && . /etc/profile + export PS1='kdump:${PWD}# ' + + . /lib/dracut-lib.sh + if [ -f /dracut-state.sh ]; then + . /dracut-state.sh 2>/dev/null + fi + + source_conf /etc/conf.d + + type plymouth >/dev/null 2>&1 && plymouth quit + + source_hook "emergency" + while read _tty rest; do + ( + echo + echo + echo 'Entering kdump emergency mode.' + echo 'Type "journalctl" to view system logs.' + echo 'Type "rdsosreport" to generate a sosreport, you can then' + echo 'save it elsewhere and attach it to a bug report.' + echo + echo + ) > /dev/$_tty + done < /proc/consoles + sh -i -l + /bin/rm -f -- /.console_lock +} + +do_failure_action() +{ + dinfo "Executing failure action $FAILURE_ACTION" + eval $FAILURE_ACTION +} + +do_final_action() +{ + dinfo "Executing final action $FINAL_ACTION" + eval $FINAL_ACTION +} do_dump() { local _ret diff --git a/kdump-lib-initramfs.sh b/kdump-lib-initramfs.sh index e7f623c4..051135ae 100755 --- a/kdump-lib-initramfs.sh +++ b/kdump-lib-initramfs.sh @@ -3,35 +3,9 @@ # Function and variables used in initramfs environment, POSIX compatible #
-. /lib/kdump-logger.sh - DEFAULT_PATH="/var/crash/" -KDUMP_PATH="/var/crash" -KDUMP_LOG_FILE="/run/initramfs/kexec-dmesg.log" -CORE_COLLECTOR="" -DEFAULT_CORE_COLLECTOR="makedumpfile -l --message-level 7 -d 31" -DMESG_COLLECTOR="/sbin/vmcore-dmesg" -FAILURE_ACTION="systemctl reboot -f" -DATEDIR=`date +%Y-%m-%d-%T` -HOST_IP='127.0.0.1' -DUMP_INSTRUCTION="" -SSH_KEY_LOCATION="/root/.ssh/kdump_id_rsa" -KDUMP_SCRIPT_DIR="/kdumpscripts" -DD_BLKSIZE=512 -FINAL_ACTION="systemctl reboot -f" -KDUMP_PRE="" -KDUMP_POST="" -NEWROOT="/sysroot" -OPALCORE="/sys/firmware/opal/mpipl/core" KDUMP_CONFIG_FILE="/etc/kdump.conf"
-#initiate the kdump logger -dlog_init -if [ $? -ne 0 ]; then - echo "failed to initiate the kdump logger." - exit 1 -fi - # Read kdump config in well formated style kdump_read_conf() { @@ -156,266 +130,3 @@ is_fs_dump_target() { [[ $(kdump_get_conf_val "ext[234]|xfs|btrfs|minix") ]] } - -get_kdump_confs() -{ - local config_opt config_val - - while read config_opt config_val; - do - # remove inline comments after the end of a directive. - case "$config_opt" in - path) - KDUMP_PATH="$config_val" - ;; - core_collector) - [ -n "$config_val" ] && CORE_COLLECTOR="$config_val" - ;; - sshkey) - if [ -f "$config_val" ]; then - SSH_KEY_LOCATION=$config_val - fi - ;; - kdump_pre) - KDUMP_PRE="$config_val" - ;; - kdump_post) - KDUMP_POST="$config_val" - ;; - fence_kdump_args) - FENCE_KDUMP_ARGS="$config_val" - ;; - fence_kdump_nodes) - FENCE_KDUMP_NODES="$config_val" - ;; - failure_action|default) - case $config_val in - shell) - FAILURE_ACTION="kdump_emergency_shell" - ;; - reboot) - FAILURE_ACTION="systemctl reboot -f && exit" - ;; - halt) - FAILURE_ACTION="halt && exit" - ;; - poweroff) - FAILURE_ACTION="systemctl poweroff -f && exit" - ;; - dump_to_rootfs) - FAILURE_ACTION="dump_to_rootfs" - ;; - esac - ;; - final_action) - case $config_val in - reboot) - FINAL_ACTION="systemctl reboot -f" - ;; - halt) - FINAL_ACTION="halt" - ;; - poweroff) - FINAL_ACTION="systemctl poweroff -f" - ;; - esac - ;; - esac - done <<< "$(kdump_read_conf)" - - if [ -z "$CORE_COLLECTOR" ]; then - CORE_COLLECTOR="$DEFAULT_CORE_COLLECTOR" - if is_ssh_dump_target || is_raw_dump_target; then - CORE_COLLECTOR="$CORE_COLLECTOR -F" - fi - fi -} - -# store the kexec kernel log to a file. -save_log() -{ - dmesg -T > $KDUMP_LOG_FILE - - if command -v journalctl > /dev/null; then - journalctl -ab >> $KDUMP_LOG_FILE - fi - chmod 600 $KDUMP_LOG_FILE -} - -# dump_fs <mount point> -dump_fs() -{ - local _exitcode - local _mp=$1 - local _op=$(get_mount_info OPTIONS target $_mp -f) - ddebug "dump_fs _mp=$_mp _opts=$_op" - - if ! is_mounted "$_mp"; then - dinfo "dump path "$_mp" is not mounted, trying to mount..." - mount --target $_mp - if [ $? -ne 0 ]; then - derror "failed to dump to "$_mp", it's not a mount point!" - return 1 - fi - fi - - # Remove -F in makedumpfile case. We don't want a flat format dump here. - [[ $CORE_COLLECTOR = *makedumpfile* ]] && CORE_COLLECTOR=`echo $CORE_COLLECTOR | sed -e "s/-F//g"` - - local _dump_path=$(echo "$_mp/$KDUMP_PATH/$HOST_IP-$DATEDIR/" | tr -s /) - - dinfo "saving to $_dump_path" - - # Only remount to read-write mode if the dump target is mounted read-only. - if [[ "$_op" = "ro"* ]]; then - dinfo "Remounting the dump target in rw mode." - mount -o remount,rw $_mp || return 1 - fi - - mkdir -p $_dump_path || return 1 - - save_vmcore_dmesg_fs ${DMESG_COLLECTOR} "$_dump_path" - save_opalcore_fs "$_dump_path" - - dinfo "saving vmcore" - $CORE_COLLECTOR /proc/vmcore $_dump_path/vmcore-incomplete - _exitcode=$? - if [ $_exitcode -eq 0 ]; then - mv $_dump_path/vmcore-incomplete $_dump_path/vmcore - sync - dinfo "saving vmcore complete" - else - derror "saving vmcore failed, _exitcode:$_exitcode" - fi - - dinfo "saving the $KDUMP_LOG_FILE to $_dump_path/" - save_log - mv $KDUMP_LOG_FILE $_dump_path/ - if [ $_exitcode -ne 0 ]; then - return 1 - fi - - # improper kernel cmdline can cause the failure of echo, we can ignore this kind of failure - return 0 -} - -save_vmcore_dmesg_fs() { - local _dmesg_collector=$1 - local _path=$2 - - dinfo "saving vmcore-dmesg.txt to ${_path}" - $_dmesg_collector /proc/vmcore > ${_path}/vmcore-dmesg-incomplete.txt - _exitcode=$? - if [ $_exitcode -eq 0 ]; then - mv ${_path}/vmcore-dmesg-incomplete.txt ${_path}/vmcore-dmesg.txt - chmod 600 ${_path}/vmcore-dmesg.txt - - # Make sure file is on disk. There have been instances where later - # saving vmcore failed and system rebooted without sync and there - # was no vmcore-dmesg.txt available. - sync - dinfo "saving vmcore-dmesg.txt complete" - else - if [ -f ${_path}/vmcore-dmesg-incomplete.txt ]; then - chmod 600 ${_path}/vmcore-dmesg-incomplete.txt - fi - derror "saving vmcore-dmesg.txt failed" - fi -} - -save_opalcore_fs() { - local _path=$1 - - if [ ! -f $OPALCORE ]; then - # Check if we are on an old kernel that uses a different path - if [ -f /sys/firmware/opal/core ]; then - OPALCORE="/sys/firmware/opal/core" - else - return 0 - fi - fi - - dinfo "saving opalcore:$OPALCORE to ${_path}/opalcore" - cp $OPALCORE ${_path}/opalcore - if [ $? -ne 0 ]; then - derror "saving opalcore failed" - return 1 - fi - - sync - dinfo "saving opalcore complete" - return 0 -} - -dump_to_rootfs() -{ - - if [[ $(systemctl status dracut-initqueue | sed -n "s/^\s*Active: (\S*)\s.*$/\1/p") == "inactive" ]]; then - dinfo "Trying to bring up initqueue for rootfs mount" - systemctl start dracut-initqueue - fi - - dinfo "Clean up dead systemd services" - systemctl cancel - dinfo "Waiting for rootfs mount, will timeout after 90 seconds" - systemctl start --no-block sysroot.mount - - _loop=0 - while [ $_loop -lt 90 ] && ! is_mounted /sysroot; do - sleep 1 - _loop=$((_loop + 1)) - done - - if ! is_mounted /sysroot; then - derror "Failed to mount rootfs" - return - fi - - ddebug "NEWROOT=$NEWROOT" - dump_fs $NEWROOT -} - -kdump_emergency_shell() -{ - ddebug "Switching to kdump emergency shell..." - - [ -f /etc/profile ] && . /etc/profile - export PS1='kdump:${PWD}# ' - - . /lib/dracut-lib.sh - if [ -f /dracut-state.sh ]; then - . /dracut-state.sh 2>/dev/null - fi - - source_conf /etc/conf.d - - type plymouth >/dev/null 2>&1 && plymouth quit - - source_hook "emergency" - while read _tty rest; do - ( - echo - echo - echo 'Entering kdump emergency mode.' - echo 'Type "journalctl" to view system logs.' - echo 'Type "rdsosreport" to generate a sosreport, you can then' - echo 'save it elsewhere and attach it to a bug report.' - echo - echo - ) > /dev/$_tty - done < /proc/consoles - sh -i -l - /bin/rm -f -- /.console_lock -} - -do_failure_action() -{ - dinfo "Executing failure action $FAILURE_ACTION" - eval $FAILURE_ACTION -} - -do_final_action() -{ - dinfo "Executing final action $FINAL_ACTION" - eval $FINAL_ACTION -}
in subject s/raleted/related/
Thanks Philipp
On Thu, 19 Aug 2021 19:39:32 +0800 Kairui Song kasong@redhat.com wrote:
These dump related functions are only used by dracut-kdump.sh.
Signed-off-by: Kairui Song kasong@redhat.com
dracut-kdump.sh | 288 ++++++++++++++++++++++++++++++++++++++++ kdump-lib-initramfs.sh | 289 ----------------------------------------- 2 files changed, 288 insertions(+), 289 deletions(-)
diff --git a/dracut-kdump.sh b/dracut-kdump.sh index 352cad56..a785ab92 100755 --- a/dracut-kdump.sh +++ b/dracut-kdump.sh @@ -4,13 +4,301 @@ #
. /lib/dracut-lib.sh +. /lib/kdump-logger.sh . /lib/kdump-lib-initramfs.sh
+#initiate the kdump logger +dlog_init +if [ $? -ne 0 ]; then
- echo "failed to initiate the kdump logger."
- exit 1
+fi
+KDUMP_PATH="/var/crash" +KDUMP_LOG_FILE="/run/initramfs/kexec-dmesg.log" +CORE_COLLECTOR="" +DEFAULT_CORE_COLLECTOR="makedumpfile -l --message-level 7 -d 31" +DMESG_COLLECTOR="/sbin/vmcore-dmesg" +FAILURE_ACTION="systemctl reboot -f" +DATEDIR=`date +%Y-%m-%d-%T` +HOST_IP='127.0.0.1' +DUMP_INSTRUCTION="" +SSH_KEY_LOCATION="/root/.ssh/kdump_id_rsa" +KDUMP_SCRIPT_DIR="/kdumpscripts" +DD_BLKSIZE=512 +FINAL_ACTION="systemctl reboot -f" +KDUMP_PRE="" +KDUMP_POST="" +NEWROOT="/sysroot" +OPALCORE="/sys/firmware/opal/mpipl/core"
set -o pipefail DUMP_RETVAL=0
export PATH=$PATH:$KDUMP_SCRIPT_DIR
+get_kdump_confs() +{
- local config_opt config_val
- while read config_opt config_val;
- do
# remove inline comments after the end of a directive.
case "$config_opt" in
path)
KDUMP_PATH="$config_val"
;;
core_collector)
[ -n "$config_val" ] && CORE_COLLECTOR="$config_val"
;;
sshkey)
if [ -f "$config_val" ]; then
SSH_KEY_LOCATION=$config_val
fi
;;
kdump_pre)
KDUMP_PRE="$config_val"
;;
kdump_post)
KDUMP_POST="$config_val"
;;
fence_kdump_args)
FENCE_KDUMP_ARGS="$config_val"
;;
fence_kdump_nodes)
FENCE_KDUMP_NODES="$config_val"
;;
failure_action|default)
case $config_val in
shell)
FAILURE_ACTION="kdump_emergency_shell"
;;
reboot)
FAILURE_ACTION="systemctl reboot -f && exit"
;;
halt)
FAILURE_ACTION="halt && exit"
;;
poweroff)
FAILURE_ACTION="systemctl poweroff -f && exit"
;;
dump_to_rootfs)
FAILURE_ACTION="dump_to_rootfs"
;;
esac
;;
final_action)
case $config_val in
reboot)
FINAL_ACTION="systemctl reboot -f"
;;
halt)
FINAL_ACTION="halt"
;;
poweroff)
FINAL_ACTION="systemctl poweroff -f"
;;
esac
;;
esac
- done <<< "$(kdump_read_conf)"
- if [ -z "$CORE_COLLECTOR" ]; then
CORE_COLLECTOR="$DEFAULT_CORE_COLLECTOR"
if is_ssh_dump_target || is_raw_dump_target; then
CORE_COLLECTOR="$CORE_COLLECTOR -F"
fi
- fi
+}
+# store the kexec kernel log to a file. +save_log() +{
- dmesg -T > $KDUMP_LOG_FILE
- if command -v journalctl > /dev/null; then
journalctl -ab >> $KDUMP_LOG_FILE
- fi
- chmod 600 $KDUMP_LOG_FILE
+}
+# dump_fs <mount point> +dump_fs() +{
- local _exitcode
- local _mp=$1
- local _op=$(get_mount_info OPTIONS target $_mp -f)
- ddebug "dump_fs _mp=$_mp _opts=$_op"
- if ! is_mounted "$_mp"; then
dinfo "dump path \"$_mp\" is not mounted, trying to mount..."
mount --target $_mp
if [ $? -ne 0 ]; then
derror "failed to dump to \"$_mp\", it's not a mount point!"
return 1
fi
- fi
- # Remove -F in makedumpfile case. We don't want a flat format dump here.
- [[ $CORE_COLLECTOR = *makedumpfile* ]] && CORE_COLLECTOR=`echo $CORE_COLLECTOR | sed -e "s/-F//g"`
- local _dump_path=$(echo "$_mp/$KDUMP_PATH/$HOST_IP-$DATEDIR/" | tr -s /)
- dinfo "saving to $_dump_path"
- # Only remount to read-write mode if the dump target is mounted read-only.
- if [[ "$_op" = "ro"* ]]; then
dinfo "Remounting the dump target in rw mode."
mount -o remount,rw $_mp || return 1
- fi
- mkdir -p $_dump_path || return 1
- save_vmcore_dmesg_fs ${DMESG_COLLECTOR} "$_dump_path"
- save_opalcore_fs "$_dump_path"
- dinfo "saving vmcore"
- $CORE_COLLECTOR /proc/vmcore $_dump_path/vmcore-incomplete
- _exitcode=$?
- if [ $_exitcode -eq 0 ]; then
mv $_dump_path/vmcore-incomplete $_dump_path/vmcore
sync
dinfo "saving vmcore complete"
- else
derror "saving vmcore failed, _exitcode:$_exitcode"
- fi
- dinfo "saving the $KDUMP_LOG_FILE to $_dump_path/"
- save_log
- mv $KDUMP_LOG_FILE $_dump_path/
- if [ $_exitcode -ne 0 ]; then
return 1
- fi
- # improper kernel cmdline can cause the failure of echo, we can ignore this kind of failure
- return 0
+}
+save_vmcore_dmesg_fs() {
- local _dmesg_collector=$1
- local _path=$2
- dinfo "saving vmcore-dmesg.txt to ${_path}"
- $_dmesg_collector /proc/vmcore > ${_path}/vmcore-dmesg-incomplete.txt
- _exitcode=$?
- if [ $_exitcode -eq 0 ]; then
mv ${_path}/vmcore-dmesg-incomplete.txt ${_path}/vmcore-dmesg.txt
chmod 600 ${_path}/vmcore-dmesg.txt
# Make sure file is on disk. There have been instances where later
# saving vmcore failed and system rebooted without sync and there
# was no vmcore-dmesg.txt available.
sync
dinfo "saving vmcore-dmesg.txt complete"
- else
if [ -f ${_path}/vmcore-dmesg-incomplete.txt ]; then
chmod 600 ${_path}/vmcore-dmesg-incomplete.txt
fi
derror "saving vmcore-dmesg.txt failed"
- fi
+}
+save_opalcore_fs() {
- local _path=$1
- if [ ! -f $OPALCORE ]; then
# Check if we are on an old kernel that uses a different path
if [ -f /sys/firmware/opal/core ]; then
OPALCORE="/sys/firmware/opal/core"
else
return 0
fi
- fi
- dinfo "saving opalcore:$OPALCORE to ${_path}/opalcore"
- cp $OPALCORE ${_path}/opalcore
- if [ $? -ne 0 ]; then
derror "saving opalcore failed"
return 1
- fi
- sync
- dinfo "saving opalcore complete"
- return 0
+}
+dump_to_rootfs() +{
- if [[ $(systemctl status dracut-initqueue | sed -n "s/^\s*Active: (\S*)\s.*$/\1/p") == "inactive" ]]; then
dinfo "Trying to bring up initqueue for rootfs mount"
systemctl start dracut-initqueue
- fi
- dinfo "Clean up dead systemd services"
- systemctl cancel
- dinfo "Waiting for rootfs mount, will timeout after 90 seconds"
- systemctl start --no-block sysroot.mount
- _loop=0
- while [ $_loop -lt 90 ] && ! is_mounted /sysroot; do
sleep 1
_loop=$((_loop + 1))
- done
- if ! is_mounted /sysroot; then
derror "Failed to mount rootfs"
return
- fi
- ddebug "NEWROOT=$NEWROOT"
- dump_fs $NEWROOT
+}
+kdump_emergency_shell() +{
- ddebug "Switching to kdump emergency shell..."
- [ -f /etc/profile ] && . /etc/profile
- export PS1='kdump:${PWD}# '
- . /lib/dracut-lib.sh
- if [ -f /dracut-state.sh ]; then
. /dracut-state.sh 2>/dev/null
- fi
- source_conf /etc/conf.d
- type plymouth >/dev/null 2>&1 && plymouth quit
- source_hook "emergency"
- while read _tty rest; do
(
echo
echo
echo 'Entering kdump emergency mode.'
echo 'Type "journalctl" to view system logs.'
echo 'Type "rdsosreport" to generate a sosreport, you can then'
echo 'save it elsewhere and attach it to a bug report.'
echo
echo
) > /dev/$_tty
- done < /proc/consoles
- sh -i -l
- /bin/rm -f -- /.console_lock
+}
+do_failure_action() +{
- dinfo "Executing failure action $FAILURE_ACTION"
- eval $FAILURE_ACTION
+}
+do_final_action() +{
- dinfo "Executing final action $FINAL_ACTION"
- eval $FINAL_ACTION
+} do_dump() { local _ret diff --git a/kdump-lib-initramfs.sh b/kdump-lib-initramfs.sh index e7f623c4..051135ae 100755 --- a/kdump-lib-initramfs.sh +++ b/kdump-lib-initramfs.sh @@ -3,35 +3,9 @@ # Function and variables used in initramfs environment, POSIX compatible #
-. /lib/kdump-logger.sh
DEFAULT_PATH="/var/crash/" -KDUMP_PATH="/var/crash" -KDUMP_LOG_FILE="/run/initramfs/kexec-dmesg.log" -CORE_COLLECTOR="" -DEFAULT_CORE_COLLECTOR="makedumpfile -l --message-level 7 -d 31" -DMESG_COLLECTOR="/sbin/vmcore-dmesg" -FAILURE_ACTION="systemctl reboot -f" -DATEDIR=`date +%Y-%m-%d-%T` -HOST_IP='127.0.0.1' -DUMP_INSTRUCTION="" -SSH_KEY_LOCATION="/root/.ssh/kdump_id_rsa" -KDUMP_SCRIPT_DIR="/kdumpscripts" -DD_BLKSIZE=512 -FINAL_ACTION="systemctl reboot -f" -KDUMP_PRE="" -KDUMP_POST="" -NEWROOT="/sysroot" -OPALCORE="/sys/firmware/opal/mpipl/core" KDUMP_CONFIG_FILE="/etc/kdump.conf"
-#initiate the kdump logger -dlog_init -if [ $? -ne 0 ]; then
- echo "failed to initiate the kdump logger."
- exit 1
-fi
# Read kdump config in well formated style kdump_read_conf() { @@ -156,266 +130,3 @@ is_fs_dump_target() { [[ $(kdump_get_conf_val "ext[234]|xfs|btrfs|minix") ]] }
-get_kdump_confs() -{
- local config_opt config_val
- while read config_opt config_val;
- do
# remove inline comments after the end of a directive.
case "$config_opt" in
path)
KDUMP_PATH="$config_val"
;;
core_collector)
[ -n "$config_val" ] && CORE_COLLECTOR="$config_val"
;;
sshkey)
if [ -f "$config_val" ]; then
SSH_KEY_LOCATION=$config_val
fi
;;
kdump_pre)
KDUMP_PRE="$config_val"
;;
kdump_post)
KDUMP_POST="$config_val"
;;
fence_kdump_args)
FENCE_KDUMP_ARGS="$config_val"
;;
fence_kdump_nodes)
FENCE_KDUMP_NODES="$config_val"
;;
failure_action|default)
case $config_val in
shell)
FAILURE_ACTION="kdump_emergency_shell"
;;
reboot)
FAILURE_ACTION="systemctl reboot -f && exit"
;;
halt)
FAILURE_ACTION="halt && exit"
;;
poweroff)
FAILURE_ACTION="systemctl poweroff -f && exit"
;;
dump_to_rootfs)
FAILURE_ACTION="dump_to_rootfs"
;;
esac
;;
final_action)
case $config_val in
reboot)
FINAL_ACTION="systemctl reboot -f"
;;
halt)
FINAL_ACTION="halt"
;;
poweroff)
FINAL_ACTION="systemctl poweroff -f"
;;
esac
;;
esac
- done <<< "$(kdump_read_conf)"
- if [ -z "$CORE_COLLECTOR" ]; then
CORE_COLLECTOR="$DEFAULT_CORE_COLLECTOR"
if is_ssh_dump_target || is_raw_dump_target; then
CORE_COLLECTOR="$CORE_COLLECTOR -F"
fi
- fi
-}
-# store the kexec kernel log to a file. -save_log() -{
- dmesg -T > $KDUMP_LOG_FILE
- if command -v journalctl > /dev/null; then
journalctl -ab >> $KDUMP_LOG_FILE
- fi
- chmod 600 $KDUMP_LOG_FILE
-}
-# dump_fs <mount point> -dump_fs() -{
- local _exitcode
- local _mp=$1
- local _op=$(get_mount_info OPTIONS target $_mp -f)
- ddebug "dump_fs _mp=$_mp _opts=$_op"
- if ! is_mounted "$_mp"; then
dinfo "dump path \"$_mp\" is not mounted, trying to mount..."
mount --target $_mp
if [ $? -ne 0 ]; then
derror "failed to dump to \"$_mp\", it's not a mount point!"
return 1
fi
- fi
- # Remove -F in makedumpfile case. We don't want a flat format dump here.
- [[ $CORE_COLLECTOR = *makedumpfile* ]] && CORE_COLLECTOR=`echo $CORE_COLLECTOR | sed -e "s/-F//g"`
- local _dump_path=$(echo "$_mp/$KDUMP_PATH/$HOST_IP-$DATEDIR/" | tr -s /)
- dinfo "saving to $_dump_path"
- # Only remount to read-write mode if the dump target is mounted read-only.
- if [[ "$_op" = "ro"* ]]; then
dinfo "Remounting the dump target in rw mode."
mount -o remount,rw $_mp || return 1
- fi
- mkdir -p $_dump_path || return 1
- save_vmcore_dmesg_fs ${DMESG_COLLECTOR} "$_dump_path"
- save_opalcore_fs "$_dump_path"
- dinfo "saving vmcore"
- $CORE_COLLECTOR /proc/vmcore $_dump_path/vmcore-incomplete
- _exitcode=$?
- if [ $_exitcode -eq 0 ]; then
mv $_dump_path/vmcore-incomplete $_dump_path/vmcore
sync
dinfo "saving vmcore complete"
- else
derror "saving vmcore failed, _exitcode:$_exitcode"
- fi
- dinfo "saving the $KDUMP_LOG_FILE to $_dump_path/"
- save_log
- mv $KDUMP_LOG_FILE $_dump_path/
- if [ $_exitcode -ne 0 ]; then
return 1
- fi
- # improper kernel cmdline can cause the failure of echo, we can ignore this kind of failure
- return 0
-}
-save_vmcore_dmesg_fs() {
- local _dmesg_collector=$1
- local _path=$2
- dinfo "saving vmcore-dmesg.txt to ${_path}"
- $_dmesg_collector /proc/vmcore > ${_path}/vmcore-dmesg-incomplete.txt
- _exitcode=$?
- if [ $_exitcode -eq 0 ]; then
mv ${_path}/vmcore-dmesg-incomplete.txt ${_path}/vmcore-dmesg.txt
chmod 600 ${_path}/vmcore-dmesg.txt
# Make sure file is on disk. There have been instances where later
# saving vmcore failed and system rebooted without sync and there
# was no vmcore-dmesg.txt available.
sync
dinfo "saving vmcore-dmesg.txt complete"
- else
if [ -f ${_path}/vmcore-dmesg-incomplete.txt ]; then
chmod 600 ${_path}/vmcore-dmesg-incomplete.txt
fi
derror "saving vmcore-dmesg.txt failed"
- fi
-}
-save_opalcore_fs() {
- local _path=$1
- if [ ! -f $OPALCORE ]; then
# Check if we are on an old kernel that uses a different path
if [ -f /sys/firmware/opal/core ]; then
OPALCORE="/sys/firmware/opal/core"
else
return 0
fi
- fi
- dinfo "saving opalcore:$OPALCORE to ${_path}/opalcore"
- cp $OPALCORE ${_path}/opalcore
- if [ $? -ne 0 ]; then
derror "saving opalcore failed"
return 1
- fi
- sync
- dinfo "saving opalcore complete"
- return 0
-}
-dump_to_rootfs() -{
- if [[ $(systemctl status dracut-initqueue | sed -n "s/^\s*Active: (\S*)\s.*$/\1/p") == "inactive" ]]; then
dinfo "Trying to bring up initqueue for rootfs mount"
systemctl start dracut-initqueue
- fi
- dinfo "Clean up dead systemd services"
- systemctl cancel
- dinfo "Waiting for rootfs mount, will timeout after 90 seconds"
- systemctl start --no-block sysroot.mount
- _loop=0
- while [ $_loop -lt 90 ] && ! is_mounted /sysroot; do
sleep 1
_loop=$((_loop + 1))
- done
- if ! is_mounted /sysroot; then
derror "Failed to mount rootfs"
return
- fi
- ddebug "NEWROOT=$NEWROOT"
- dump_fs $NEWROOT
-}
-kdump_emergency_shell() -{
- ddebug "Switching to kdump emergency shell..."
- [ -f /etc/profile ] && . /etc/profile
- export PS1='kdump:${PWD}# '
- . /lib/dracut-lib.sh
- if [ -f /dracut-state.sh ]; then
. /dracut-state.sh 2>/dev/null
- fi
- source_conf /etc/conf.d
- type plymouth >/dev/null 2>&1 && plymouth quit
- source_hook "emergency"
- while read _tty rest; do
(
echo
echo
echo 'Entering kdump emergency mode.'
echo 'Type "journalctl" to view system logs.'
echo 'Type "rdsosreport" to generate a sosreport, you can then'
echo 'save it elsewhere and attach it to a bug report.'
echo
echo
) > /dev/$_tty
- done < /proc/consoles
- sh -i -l
- /bin/rm -f -- /.console_lock
-}
-do_failure_action() -{
- dinfo "Executing failure action $FAILURE_ACTION"
- eval $FAILURE_ACTION
-}
-do_final_action() -{
- dinfo "Executing final action $FINAL_ACTION"
- eval $FINAL_ACTION
-}
monitor_dd_progress is the only extra binary in KDUMP_SCRIPT_DIR, no need to change PATH environment variable, just call it directly.
Signed-off-by: Kairui Song kasong@redhat.com --- dracut-kdump.sh | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-)
diff --git a/dracut-kdump.sh b/dracut-kdump.sh index a785ab92..54e97132 100755 --- a/dracut-kdump.sh +++ b/dracut-kdump.sh @@ -24,7 +24,6 @@ DATEDIR=`date +%Y-%m-%d-%T` HOST_IP='127.0.0.1' DUMP_INSTRUCTION="" SSH_KEY_LOCATION="/root/.ssh/kdump_id_rsa" -KDUMP_SCRIPT_DIR="/kdumpscripts" DD_BLKSIZE=512 FINAL_ACTION="systemctl reboot -f" KDUMP_PRE="" @@ -35,8 +34,6 @@ OPALCORE="/sys/firmware/opal/mpipl/core" set -o pipefail DUMP_RETVAL=0
-export PATH=$PATH:$KDUMP_SCRIPT_DIR - get_kdump_confs() { local config_opt config_val @@ -378,7 +375,7 @@ dump_raw() if ! $(echo -n $CORE_COLLECTOR|grep -q makedumpfile); then _src_size=`ls -l /proc/vmcore | cut -d' ' -f5` _src_size_mb=$(($_src_size / 1048576)) - monitor_dd_progress $_src_size_mb & + /kdumpscripts/monitor_dd_progress $_src_size_mb & fi
dinfo "saving vmcore"
`add_dump_code "<op>"` is just `DUMP_INSTRUCTION="<op>"`, no need a extra wrapper for that.
Signed-off-by: Kairui Song kasong@redhat.com --- dracut-kdump.sh | 19 ++++++------------- 1 file changed, 6 insertions(+), 13 deletions(-)
diff --git a/dracut-kdump.sh b/dracut-kdump.sh index 54e97132..7cfa31bf 100755 --- a/dracut-kdump.sh +++ b/dracut-kdump.sh @@ -36,9 +36,7 @@ DUMP_RETVAL=0
get_kdump_confs() { - local config_opt config_val - - while read config_opt config_val; + while read -r config_opt config_val; do # remove inline comments after the end of a directive. case "$config_opt" in @@ -359,11 +357,6 @@ do_kdump_post() fi }
-add_dump_code() -{ - DUMP_INSTRUCTION=$1 -} - dump_raw() { local _raw=$1 @@ -547,18 +540,18 @@ read_kdump_confs() config_val=$(get_dracut_args_target "$config_val") if [ -n "$config_val" ]; then config_val=$(get_mntpoint_from_target "$config_val") - add_dump_code "dump_fs $config_val" + DUMP_INSTRUCTION="dump_fs $config_val" fi ;; ext[234]|xfs|btrfs|minix|nfs) config_val=$(get_mntpoint_from_target "$config_val") - add_dump_code "dump_fs $config_val" + DUMP_INSTRUCTION="dump_fs $config_val" ;; raw) - add_dump_code "dump_raw $config_val" + DUMP_INSTRUCTION="dump_raw $config_val" ;; ssh) - add_dump_code "dump_ssh $SSH_KEY_LOCATION $config_val" + DUMP_INSTRUCTION="dump_ssh $SSH_KEY_LOCATION $config_val" ;; esac done <<< "$(kdump_read_conf)" @@ -594,7 +587,7 @@ if [ $? -ne 0 ]; then fi
if [ -z "$DUMP_INSTRUCTION" ]; then - add_dump_code "dump_fs $NEWROOT" + DUMP_INSTRUCTION="dump_fs $NEWROOT" fi
do_kdump_pre
There is a workaround for `scp` that it expects IPv6 address to be quoted with [ ... ], only apply the workaround once and store the updated `scp` address to reuse it.
Signed-off-by: Kairui Song kasong@redhat.com --- dracut-kdump.sh | 41 ++++++++++++----------------------------- 1 file changed, 12 insertions(+), 29 deletions(-)
diff --git a/dracut-kdump.sh b/dracut-kdump.sh index 7cfa31bf..b92854e9 100755 --- a/dracut-kdump.sh +++ b/dracut-kdump.sh @@ -387,29 +387,25 @@ dump_ssh() local _dir="$KDUMP_PATH/$HOST_IP-$DATEDIR" local _host=$2 local _vmcore="vmcore" - local _ipv6_addr="" _username="" + + if is_ipv6_address "$_host"; then + _scp_address=${_host%@*}@"[${_host#*@}]" + else + _scp_address=$_host + fi
dinfo "saving to $_host:$_dir"
cat /var/lib/random-seed > /dev/urandom ssh -q $_opt $_host mkdir -p $_dir || return 1
- save_vmcore_dmesg_ssh ${DMESG_COLLECTOR} ${_dir} "${_opt}" $_host - save_opalcore_ssh ${_dir} "${_opt}" $_host - + save_vmcore_dmesg_ssh ${DMESG_COLLECTOR} ${_dir} "${_opt}" "$_host" dinfo "saving vmcore"
- if is_ipv6_address "$_host"; then - _username=${_host%@*} - _ipv6_addr="[${_host#*@}]" - fi + save_opalcore_ssh ${_dir} "${_opt}" "$_host" "$_scp_address"
if [ "${CORE_COLLECTOR%%[[:blank:]]*}" = "scp" ]; then - if [ -n "$_username" ] && [ -n "$_ipv6_addr" ]; then - scp -q $_opt /proc/vmcore "$_username@$_ipv6_addr:$_dir/vmcore-incomplete" - else - scp -q $_opt /proc/vmcore "$_host:$_dir/vmcore-incomplete" - fi + scp -q $_opt /proc/vmcore "$_scp_address:$_dir/vmcore-incomplete" _exitcode=$? else $CORE_COLLECTOR /proc/vmcore | ssh $_opt $_host "umask 0077 && dd bs=512 of=$_dir/vmcore-incomplete" @@ -431,11 +427,7 @@ dump_ssh()
dinfo "saving the $KDUMP_LOG_FILE to $_host:$_dir/" save_log - if [ -n "$_username" ] && [ -n "$_ipv6_addr" ]; then - scp -q $_opt $KDUMP_LOG_FILE "$_username@$_ipv6_addr:$_dir/" - else - scp -q $_opt $KDUMP_LOG_FILE "$_host:$_dir/" - fi + scp -q $_opt $KDUMP_LOG_FILE "$_scp_address:$_dir/" _ret=$? if [ $_ret -ne 0 ]; then derror "saving log file failed, _exitcode:$_ret" @@ -452,7 +444,7 @@ save_opalcore_ssh() { local _path=$1 local _opts="$2" local _location=$3 - local _user_name="" _ipv6addr="" + local _scp_address=$4
ddebug "_path=$_path _opts=$_opts _location=$_location"
@@ -465,18 +457,9 @@ save_opalcore_ssh() { fi fi
- if is_ipv6_address "$_host"; then - _user_name=${_location%@*} - _ipv6addr="[${_location#*@}]" - fi - dinfo "saving opalcore:$OPALCORE to $_location:$_path"
- if [ -n "$_user_name" ] && [ -n "$_ipv6addr" ]; then - scp $_opts $OPALCORE $_user_name@$_ipv6addr:$_path/opalcore-incomplete - else - scp $_opts $OPALCORE $_location:$_path/opalcore-incomplete - fi + scp $_opts $OPALCORE $_scp_address:$_path/opalcore-incomplete if [ $? -ne 0 ]; then derror "saving opalcore failed" return 1
ls output is fragile, so use stat instead.
Signed-off-by: Kairui Song kasong@redhat.com --- dracut-kdump.sh | 2 +- dracut-module-setup.sh | 1 + 2 files changed, 2 insertions(+), 1 deletion(-)
diff --git a/dracut-kdump.sh b/dracut-kdump.sh index b92854e9..25972e49 100755 --- a/dracut-kdump.sh +++ b/dracut-kdump.sh @@ -366,7 +366,7 @@ dump_raw() dinfo "saving to raw disk $_raw"
if ! $(echo -n $CORE_COLLECTOR|grep -q makedumpfile); then - _src_size=`ls -l /proc/vmcore | cut -d' ' -f5` + _src_size=$(stat --format %s /proc/vmcore) _src_size_mb=$(($_src_size / 1048576)) /kdumpscripts/monitor_dd_progress $_src_size_mb & fi diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index 227fdae8..74b969cb 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -1028,6 +1028,7 @@ install() { inst "/bin/head" "/bin/head" inst "/bin/awk" "/bin/awk" inst "/bin/sed" "/bin/sed" + inst "/bin/stat" "/bin/stat" inst "/sbin/makedumpfile" "/sbin/makedumpfile" inst "/sbin/vmcore-dmesg" "/sbin/vmcore-dmesg" inst "/usr/bin/printf" "/sbin/printf"
Set pipefail will cause POSIX shell to exit with failure. So only do that in bash.
Signed-off-by: Kairui Song kasong@redhat.com --- dracut-kdump.sh | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
diff --git a/dracut-kdump.sh b/dracut-kdump.sh index 25972e49..3c1b080a 100755 --- a/dracut-kdump.sh +++ b/dracut-kdump.sh @@ -31,7 +31,10 @@ KDUMP_POST="" NEWROOT="/sysroot" OPALCORE="/sys/firmware/opal/mpipl/core"
-set -o pipefail +# POSIX doesn't have pipefail, only apply when using bash +# shellcheck disable=SC3040 +[ -n "$BASH" ] && set -o pipefail + DUMP_RETVAL=0
get_kdump_confs()
POSIX doesn't support keyword `local`, so this commit reduced varible usage. Heredoc ("<<<") operation is also not supported, so kdump.conf is now pre-parse into a temp file. Also fixes many POSIX syntax errors.
Signed-off-by: Kairui Song kasong@redhat.com --- dracut-kdump.sh | 262 ++++++++++++++++++++++-------------------------- 1 file changed, 122 insertions(+), 140 deletions(-)
diff --git a/dracut-kdump.sh b/dracut-kdump.sh index 3c1b080a..0330ec02 100755 --- a/dracut-kdump.sh +++ b/dracut-kdump.sh @@ -8,8 +8,7 @@ . /lib/kdump-lib-initramfs.sh
#initiate the kdump logger -dlog_init -if [ $? -ne 0 ]; then +if ! dlog_init; then echo "failed to initiate the kdump logger." exit 1 fi @@ -20,7 +19,7 @@ CORE_COLLECTOR="" DEFAULT_CORE_COLLECTOR="makedumpfile -l --message-level 7 -d 31" DMESG_COLLECTOR="/sbin/vmcore-dmesg" FAILURE_ACTION="systemctl reboot -f" -DATEDIR=`date +%Y-%m-%d-%T` +DATEDIR=$(date +%Y-%m-%d-%T) HOST_IP='127.0.0.1' DUMP_INSTRUCTION="" SSH_KEY_LOCATION="/root/.ssh/kdump_id_rsa" @@ -30,6 +29,7 @@ KDUMP_PRE="" KDUMP_POST="" NEWROOT="/sysroot" OPALCORE="/sys/firmware/opal/mpipl/core" +KDUMP_CONF_PARSED="/tmp/kdump.conf.$$"
# POSIX doesn't have pipefail, only apply when using bash # shellcheck disable=SC3040 @@ -37,10 +37,11 @@ OPALCORE="/sys/firmware/opal/mpipl/core"
DUMP_RETVAL=0
+kdump_read_conf > $KDUMP_CONF_PARSED + get_kdump_confs() { - while read -r config_opt config_val; - do + while read -r config_opt config_val; do # remove inline comments after the end of a directive. case "$config_opt" in path) @@ -99,7 +100,7 @@ get_kdump_confs() esac ;; esac - done <<< "$(kdump_read_conf)" + done < "$KDUMP_CONF_PARSED"
if [ -z "$CORE_COLLECTOR" ]; then CORE_COLLECTOR="$DEFAULT_CORE_COLLECTOR" @@ -120,56 +121,58 @@ save_log() chmod 600 $KDUMP_LOG_FILE }
-# dump_fs <mount point> +# $1: dump path, must be a mount point dump_fs() { - local _exitcode - local _mp=$1 - local _op=$(get_mount_info OPTIONS target $_mp -f) - ddebug "dump_fs _mp=$_mp _opts=$_op" - - if ! is_mounted "$_mp"; then - dinfo "dump path "$_mp" is not mounted, trying to mount..." - mount --target $_mp - if [ $? -ne 0 ]; then - derror "failed to dump to "$_mp", it's not a mount point!" + ddebug "dump_fs _mp=$1" + + if ! is_mounted "$1"; then + dinfo "dump path '$1' is not mounted, trying to mount..." + if ! mount --target "$1"; then + derror "failed to dump to '$1', it's not a mount point!" return 1 fi fi
# Remove -F in makedumpfile case. We don't want a flat format dump here. - [[ $CORE_COLLECTOR = *makedumpfile* ]] && CORE_COLLECTOR=`echo $CORE_COLLECTOR | sed -e "s/-F//g"` - - local _dump_path=$(echo "$_mp/$KDUMP_PATH/$HOST_IP-$DATEDIR/" | tr -s /) + case $CORE_COLLECTOR in + *makedumpfile* ) + CORE_COLLECTOR=$(echo "$CORE_COLLECTOR" | sed -e "s/-F//g") + ;; + esac
- dinfo "saving to $_dump_path" + _dump_fs_path=$(echo "$1/$KDUMP_PATH/$HOST_IP-$DATEDIR/" | tr -s /) + dinfo "saving to $_dump_fs_path"
# Only remount to read-write mode if the dump target is mounted read-only. - if [[ "$_op" = "ro"* ]]; then - dinfo "Remounting the dump target in rw mode." - mount -o remount,rw $_mp || return 1 - fi + _dump_mnt_op=$(get_mount_info OPTIONS target "$1" -f) + case $_dump_mnt_op in + ro* ) + dinfo "Remounting the dump target in rw mode." + mount -o remount,rw "$1" || return 1 + ;; + esac
- mkdir -p $_dump_path || return 1 + mkdir -p "$_dump_fs_path" || return 1
- save_vmcore_dmesg_fs ${DMESG_COLLECTOR} "$_dump_path" - save_opalcore_fs "$_dump_path" + save_vmcore_dmesg_fs ${DMESG_COLLECTOR} "$_dump_fs_path" + save_opalcore_fs "$_dump_fs_path"
dinfo "saving vmcore" - $CORE_COLLECTOR /proc/vmcore $_dump_path/vmcore-incomplete - _exitcode=$? - if [ $_exitcode -eq 0 ]; then - mv $_dump_path/vmcore-incomplete $_dump_path/vmcore + $CORE_COLLECTOR /proc/vmcore "$_dump_fs_path/vmcore-incomplete" + _dump_exitcode=$? + if [ $_dump_exitcode -eq 0 ]; then + mv "$_dump_fs_path/vmcore-incomplete" "$_dump_fs_path/vmcore" sync dinfo "saving vmcore complete" else - derror "saving vmcore failed, _exitcode:$_exitcode" + derror "saving vmcore failed, exitcode:$_dump_exitcode" fi
- dinfo "saving the $KDUMP_LOG_FILE to $_dump_path/" + dinfo "saving the $KDUMP_LOG_FILE to $_dump_fs_path/" save_log - mv $KDUMP_LOG_FILE $_dump_path/ - if [ $_exitcode -ne 0 ]; then + mv "$KDUMP_LOG_FILE" "$_dump_fs_path/" + if [ $_dump_exitcode -ne 0 ]; then return 1 fi
@@ -177,16 +180,13 @@ dump_fs() return 0 }
+# $1: dmesg collector +# $2: dump path save_vmcore_dmesg_fs() { - local _dmesg_collector=$1 - local _path=$2 - - dinfo "saving vmcore-dmesg.txt to ${_path}" - $_dmesg_collector /proc/vmcore > ${_path}/vmcore-dmesg-incomplete.txt - _exitcode=$? - if [ $_exitcode -eq 0 ]; then - mv ${_path}/vmcore-dmesg-incomplete.txt ${_path}/vmcore-dmesg.txt - chmod 600 ${_path}/vmcore-dmesg.txt + dinfo "saving vmcore-dmesg.txt to $2" + if $1 /proc/vmcore > "$2/vmcore-dmesg-incomplete.txt"; then + mv "$2/vmcore-dmesg-incomplete.txt" "$2/vmcore-dmesg.txt" + chmod 600 "$2/vmcore-dmesg.txt"
# Make sure file is on disk. There have been instances where later # saving vmcore failed and system rebooted without sync and there @@ -194,16 +194,15 @@ save_vmcore_dmesg_fs() { sync dinfo "saving vmcore-dmesg.txt complete" else - if [ -f ${_path}/vmcore-dmesg-incomplete.txt ]; then - chmod 600 ${_path}/vmcore-dmesg-incomplete.txt + if [ -f "$2/vmcore-dmesg-incomplete.txt" ]; then + chmod 600 "$2/vmcore-dmesg-incomplete.txt" fi derror "saving vmcore-dmesg.txt failed" fi }
+# $1: dump path save_opalcore_fs() { - local _path=$1 - if [ ! -f $OPALCORE ]; then # Check if we are on an old kernel that uses a different path if [ -f /sys/firmware/opal/core ]; then @@ -213,9 +212,8 @@ save_opalcore_fs() { fi fi
- dinfo "saving opalcore:$OPALCORE to ${_path}/opalcore" - cp $OPALCORE ${_path}/opalcore - if [ $? -ne 0 ]; then + dinfo "saving opalcore:$OPALCORE to $1/opalcore" + if ! cp $OPALCORE "$1/opalcore"; then derror "saving opalcore failed" return 1 fi @@ -228,7 +226,7 @@ save_opalcore_fs() { dump_to_rootfs() {
- if [[ $(systemctl status dracut-initqueue | sed -n "s/^\s*Active: (\S*)\s.*$/\1/p") == "inactive" ]]; then + if [ "$(systemctl status dracut-initqueue | sed -n "s/^\s*Active: (\S*)\s.*$/\1/p")" = "inactive" ]; then dinfo "Trying to bring up initqueue for rootfs mount" systemctl start dracut-initqueue fi @@ -270,7 +268,7 @@ kdump_emergency_shell() type plymouth >/dev/null 2>&1 && plymouth quit
source_hook "emergency" - while read _tty rest; do + while read -r _tty rest; do ( echo echo @@ -280,7 +278,7 @@ kdump_emergency_shell() echo 'save it elsewhere and attach it to a bug report.' echo echo - ) > /dev/$_tty + ) > "/dev/$_tty" done < /proc/consoles sh -i -l /bin/rm -f -- /.console_lock @@ -297,10 +295,9 @@ do_final_action() dinfo "Executing final action $FINAL_ACTION" eval $FINAL_ACTION } + do_dump() { - local _ret - eval $DUMP_INSTRUCTION _ret=$?
@@ -313,8 +310,6 @@ do_dump()
do_kdump_pre() { - local _ret - if [ -n "$KDUMP_PRE" ]; then "$KDUMP_PRE" _ret=$? @@ -339,8 +334,6 @@ do_kdump_pre()
do_kdump_post() { - local _ret - if [ -d /etc/kdump/post.d ]; then for file in /etc/kdump/post.d/*; do "$file" "$1" @@ -360,97 +353,86 @@ do_kdump_post() fi }
+# $1: block target, eg. /dev/sda dump_raw() { - local _raw=$1 - - [ -b "$_raw" ] || return 1 + [ -b "$1" ] || return 1
- dinfo "saving to raw disk $_raw" + dinfo "saving to raw disk $1"
- if ! $(echo -n $CORE_COLLECTOR|grep -q makedumpfile); then + if ! echo "$CORE_COLLECTOR" | grep -q makedumpfile; then _src_size=$(stat --format %s /proc/vmcore) - _src_size_mb=$(($_src_size / 1048576)) + _src_size_mb=$((_src_size / 1048576)) /kdumpscripts/monitor_dd_progress $_src_size_mb & fi
dinfo "saving vmcore" - $CORE_COLLECTOR /proc/vmcore | dd of=$_raw bs=$DD_BLKSIZE >> /tmp/dd_progress_file 2>&1 || return 1 + $CORE_COLLECTOR /proc/vmcore | dd of="$1" bs=$DD_BLKSIZE >> /tmp/dd_progress_file 2>&1 || return 1 sync
dinfo "saving vmcore complete" return 0 }
+# $1: ssh key file +# $2: ssh address in <user>@<host> format dump_ssh() { - local _ret=0 - local _exitcode=0 _exitcode2=0 - local _opt="-i $1 -o BatchMode=yes -o StrictHostKeyChecking=yes" - local _dir="$KDUMP_PATH/$HOST_IP-$DATEDIR" - local _host=$2 - local _vmcore="vmcore" - - if is_ipv6_address "$_host"; then - _scp_address=${_host%@*}@"[${_host#*@}]" + _ret=0 + _ssh_opt="-i $1 -o BatchMode=yes -o StrictHostKeyChecking=yes" + _ssh_dir="$KDUMP_PATH/$HOST_IP-$DATEDIR" + if is_ipv6_address "$2"; then + _scp_address=${2%@*}@"[${2#*@}]" else - _scp_address=$_host + _scp_address=$2 fi
- dinfo "saving to $_host:$_dir" + dinfo "saving to $2:$_ssh_dir"
cat /var/lib/random-seed > /dev/urandom - ssh -q $_opt $_host mkdir -p $_dir || return 1 + ssh -q $_ssh_opt "$2" mkdir -p "$_ssh_dir" || return 1
- save_vmcore_dmesg_ssh ${DMESG_COLLECTOR} ${_dir} "${_opt}" "$_host" + save_vmcore_dmesg_ssh "$DMESG_COLLECTOR" "$_ssh_dir" "$_ssh_opt" "$2" dinfo "saving vmcore"
- save_opalcore_ssh ${_dir} "${_opt}" "$_host" "$_scp_address" + save_opalcore_ssh "$_ssh_dir" "$_ssh_opt" "$2" "$_scp_address"
if [ "${CORE_COLLECTOR%%[[:blank:]]*}" = "scp" ]; then - scp -q $_opt /proc/vmcore "$_scp_address:$_dir/vmcore-incomplete" - _exitcode=$? + scp -q $_ssh_opt /proc/vmcore "$_scp_address:$_ssh_dir/vmcore-incomplete" + _ret=$? + _vmcore="vmcore" else - $CORE_COLLECTOR /proc/vmcore | ssh $_opt $_host "umask 0077 && dd bs=512 of=$_dir/vmcore-incomplete" - _exitcode=$? + $CORE_COLLECTOR /proc/vmcore | ssh $_ssh_opt "$2" "umask 0077 && dd bs=512 of='$_ssh_dir/vmcore-incomplete'" + _ret=$? _vmcore="vmcore.flat" fi
- if [ $_exitcode -eq 0 ]; then - ssh $_opt $_host "mv $_dir/vmcore-incomplete $_dir/$_vmcore" - _exitcode2=$? - if [ $_exitcode2 -ne 0 ]; then - derror "moving vmcore failed, _exitcode:$_exitcode2" + if [ $_ret -eq 0 ]; then + ssh $_ssh_opt "$2" "mv '$_ssh_dir/vmcore-incomplete' '$_ssh_dir/$_vmcore'" + _ret=$? + if [ $_ret -ne 0 ]; then + derror "moving vmcore failed, exitcode:$_ret" else dinfo "saving vmcore complete" fi else - derror "saving vmcore failed, _exitcode:$_exitcode" + derror "saving vmcore failed, exitcode:$_ret" fi
- dinfo "saving the $KDUMP_LOG_FILE to $_host:$_dir/" + dinfo "saving the $KDUMP_LOG_FILE to $2:$_ssh_dir/" save_log - scp -q $_opt $KDUMP_LOG_FILE "$_scp_address:$_dir/" - _ret=$? - if [ $_ret -ne 0 ]; then + if ! scp -q $_ssh_opt $KDUMP_LOG_FILE "$_scp_address:$_ssh_dir/"; then derror "saving log file failed, _exitcode:$_ret" fi
- if [ $_exitcode -ne 0 ] || [ $_exitcode2 -ne 0 ];then - return 1 - fi - - return 0 + return $_ret }
+# $1: dump path +# $2: ssh opts +# $3: ssh address in <user>@<host> format +# $4: scp address, similiar with ssh address but IPv6 addresses are quoted save_opalcore_ssh() { - local _path=$1 - local _opts="$2" - local _location=$3 - local _scp_address=$4 - - ddebug "_path=$_path _opts=$_opts _location=$_location" - if [ ! -f $OPALCORE ]; then # Check if we are on an old kernel that uses a different path if [ -f /sys/firmware/opal/core ]; then @@ -460,31 +442,26 @@ save_opalcore_ssh() { fi fi
- dinfo "saving opalcore:$OPALCORE to $_location:$_path" + dinfo "saving opalcore:$OPALCORE to $3:$1"
- scp $_opts $OPALCORE $_scp_address:$_path/opalcore-incomplete - if [ $? -ne 0 ]; then + if ! scp $2 $OPALCORE "$4:$1/opalcore-incomplete"; then derror "saving opalcore failed" - return 1 + return 1 fi
- ssh $_opts $_location mv $_path/opalcore-incomplete $_path/opalcore + ssh $2 "$3" mv "$1/opalcore-incomplete" "$1/opalcore" dinfo "saving opalcore complete" return 0 }
+# $1: dmesg collector +# $2: dump path +# $3: ssh opts +# $4: ssh address in <user>@<host> format save_vmcore_dmesg_ssh() { - local _dmesg_collector=$1 - local _path=$2 - local _opts="$3" - local _location=$4 - - dinfo "saving vmcore-dmesg.txt to $_location:$_path" - $_dmesg_collector /proc/vmcore | ssh $_opts $_location "umask 0077 && dd of=$_path/vmcore-dmesg-incomplete.txt" - _exitcode=$? - - if [ $_exitcode -eq 0 ]; then - ssh -q $_opts $_location mv $_path/vmcore-dmesg-incomplete.txt $_path/vmcore-dmesg.txt + dinfo "saving vmcore-dmesg.txt to $4:$2" + if $1 /proc/vmcore | ssh $3 "$4" "umask 0077 && dd of='$2/vmcore-dmesg-incomplete.txt'"; then + ssh -q $3 "$4" mv "$2/vmcore-dmesg-incomplete.txt" "$2/vmcore-dmesg.txt" dinfo "saving vmcore-dmesg.txt complete" else derror "saving vmcore-dmesg.txt failed" @@ -493,17 +470,24 @@ save_vmcore_dmesg_ssh() {
get_host_ip() { - local _host if is_nfs_dump_target || is_ssh_dump_target then kdumpnic=$(getarg kdumpnic=) - [ -z "$kdumpnic" ] && derror "failed to get kdumpnic!" && return 1 - _host=`ip addr show dev $kdumpnic|grep '[ ]*inet'` - [ $? -ne 0 ] && derror "wrong kdumpnic: $kdumpnic" && return 1 - _host=`echo $_host | head -n 1 | cut -d' ' -f2` - _host="${_host%%/*}" - [ -z "$_host" ] && derror "wrong kdumpnic: $kdumpnic" && return 1 - HOST_IP=$_host + if [ -z "$kdumpnic" ]; then + derror "failed to get kdumpnic!" + return 1 + fi + if ! kdumphost=$(ip addr show dev "$kdumpnic" | grep '[ ]*inet'); then + derror "wrong kdumpnic: $kdumpnic" + return 1 + fi + kdumphost=$(echo "$kdumphost" | head -n 1 | awk '{print $2}') + kdumphost="${kdumphost%%/*}" + if [ -z "$kdumphost" ]; then + derror "wrong kdumpnic: $kdumpnic" + return 1 + fi + HOST_IP=$kdumphost fi return 0 } @@ -518,7 +502,7 @@ read_kdump_confs() get_kdump_confs
# rescan for add code for dump target - while read config_opt config_val; + while read -r config_opt config_val; do # remove inline comments after the end of a directive. case "$config_opt" in @@ -540,12 +524,13 @@ read_kdump_confs() DUMP_INSTRUCTION="dump_ssh $SSH_KEY_LOCATION $config_val" ;; esac - done <<< "$(kdump_read_conf)" + done < "$KDUMP_CONF_PARSED" }
fence_kdump_notify() { if [ -n "$FENCE_KDUMP_NODES" ]; then + # shellcheck disable=SC2086 $FENCE_KDUMP_SEND $FENCE_KDUMP_ARGS $FENCE_KDUMP_NODES & fi } @@ -566,8 +551,7 @@ fi read_kdump_confs fence_kdump_notify
-get_host_ip -if [ $? -ne 0 ]; then +if ! get_host_ip; then derror "get_host_ip exited with non-zero status!" exit 1 fi @@ -576,8 +560,7 @@ if [ -z "$DUMP_INSTRUCTION" ]; then DUMP_INSTRUCTION="dump_fs $NEWROOT" fi
-do_kdump_pre -if [ $? -ne 0 ]; then +if ! do_kdump_pre; then derror "kdump_pre script exited with non-zero status!" do_final_action # During systemd service to reboot the machine, stop this shell script running @@ -587,8 +570,7 @@ make_trace_mem "kdump saving vmcore" '1:shortmem' '2+:mem' '3+:slab' do_dump DUMP_RETVAL=$?
-do_kdump_post $DUMP_RETVAL -if [ $? -ne 0 ]; then +if ! do_kdump_post $DUMP_RETVAL; then derror "kdump_post script exited with non-zero status!" fi
On Thu, 19 Aug 2021 19:39:38 +0800 Kairui Song kasong@redhat.com wrote:
POSIX doesn't support keyword `local`, so this commit reduced varible usage.
s/varible/variable/
Heredoc ("<<<") operation is also not supported, so kdump.conf is now pre-parse into a temp file. Also fixes many POSIX syntax errors.
Signed-off-by: Kairui Song kasong@redhat.com
dracut-kdump.sh | 262 ++++++++++++++++++++++-------------------------- 1 file changed, 122 insertions(+), 140 deletions(-)
diff --git a/dracut-kdump.sh b/dracut-kdump.sh index 3c1b080a..0330ec02 100755 --- a/dracut-kdump.sh +++ b/dracut-kdump.sh
[...]
+# $1: dump path +# $2: ssh opts +# $3: ssh address in <user>@<host> format +# $4: scp address, similiar with ssh address but IPv6 addresses are quoted
s/similiar with/similar to/
Thanks Philipp
save_opalcore_ssh() {
- local _path=$1
- local _opts="$2"
- local _location=$3
- local _scp_address=$4
- ddebug "_path=$_path _opts=$_opts _location=$_location"
- if [ ! -f $OPALCORE ]; then # Check if we are on an old kernel that uses a different path if [ -f /sys/firmware/opal/core ]; then
@@ -460,31 +442,26 @@ save_opalcore_ssh() { fi fi
- dinfo "saving opalcore:$OPALCORE to $_location:$_path"
- dinfo "saving opalcore:$OPALCORE to $3:$1"
- scp $_opts $OPALCORE $_scp_address:$_path/opalcore-incomplete
- if [ $? -ne 0 ]; then
- if ! scp $2 $OPALCORE "$4:$1/opalcore-incomplete"; then derror "saving opalcore failed"
return 1
fireturn 1
- ssh $_opts $_location mv $_path/opalcore-incomplete $_path/opalcore
- ssh $2 "$3" mv "$1/opalcore-incomplete" "$1/opalcore" dinfo "saving opalcore complete" return 0
}
+# $1: dmesg collector +# $2: dump path +# $3: ssh opts +# $4: ssh address in <user>@<host> format save_vmcore_dmesg_ssh() {
- local _dmesg_collector=$1
- local _path=$2
- local _opts="$3"
- local _location=$4
- dinfo "saving vmcore-dmesg.txt to $_location:$_path"
- $_dmesg_collector /proc/vmcore | ssh $_opts $_location "umask 0077 && dd of=$_path/vmcore-dmesg-incomplete.txt"
- _exitcode=$?
- if [ $_exitcode -eq 0 ]; then
ssh -q $_opts $_location mv $_path/vmcore-dmesg-incomplete.txt $_path/vmcore-dmesg.txt
- dinfo "saving vmcore-dmesg.txt to $4:$2"
- if $1 /proc/vmcore | ssh $3 "$4" "umask 0077 && dd of='$2/vmcore-dmesg-incomplete.txt'"; then
else derror "saving vmcore-dmesg.txt failed"ssh -q $3 "$4" mv "$2/vmcore-dmesg-incomplete.txt" "$2/vmcore-dmesg.txt" dinfo "saving vmcore-dmesg.txt complete"
@@ -493,17 +470,24 @@ save_vmcore_dmesg_ssh() {
get_host_ip() {
- local _host if is_nfs_dump_target || is_ssh_dump_target then kdumpnic=$(getarg kdumpnic=)
[ -z "$kdumpnic" ] && derror "failed to get kdumpnic!" && return 1
_host=`ip addr show dev $kdumpnic|grep '[ ]*inet'`
[ $? -ne 0 ] && derror "wrong kdumpnic: $kdumpnic" && return 1
_host=`echo $_host | head -n 1 | cut -d' ' -f2`
_host="${_host%%/*}"
[ -z "$_host" ] && derror "wrong kdumpnic: $kdumpnic" && return 1
HOST_IP=$_host
if [ -z "$kdumpnic" ]; then
derror "failed to get kdumpnic!"
return 1
fi
if ! kdumphost=$(ip addr show dev "$kdumpnic" | grep '[ ]*inet'); then
derror "wrong kdumpnic: $kdumpnic"
return 1
fi
kdumphost=$(echo "$kdumphost" | head -n 1 | awk '{print $2}')
kdumphost="${kdumphost%%/*}"
if [ -z "$kdumphost" ]; then
derror "wrong kdumpnic: $kdumpnic"
return 1
fi
fi return 0HOST_IP=$kdumphost
} @@ -518,7 +502,7 @@ read_kdump_confs() get_kdump_confs
# rescan for add code for dump target
- while read config_opt config_val;
- while read -r config_opt config_val; do # remove inline comments after the end of a directive. case "$config_opt" in
@@ -540,12 +524,13 @@ read_kdump_confs() DUMP_INSTRUCTION="dump_ssh $SSH_KEY_LOCATION $config_val" ;; esac
- done <<< "$(kdump_read_conf)"
- done < "$KDUMP_CONF_PARSED"
}
fence_kdump_notify() { if [ -n "$FENCE_KDUMP_NODES" ]; then
fi# shellcheck disable=SC2086 $FENCE_KDUMP_SEND $FENCE_KDUMP_ARGS $FENCE_KDUMP_NODES &
} @@ -566,8 +551,7 @@ fi read_kdump_confs fence_kdump_notify
-get_host_ip -if [ $? -ne 0 ]; then +if ! get_host_ip; then derror "get_host_ip exited with non-zero status!" exit 1 fi @@ -576,8 +560,7 @@ if [ -z "$DUMP_INSTRUCTION" ]; then DUMP_INSTRUCTION="dump_fs $NEWROOT" fi
-do_kdump_pre -if [ $? -ne 0 ]; then +if ! do_kdump_pre; then derror "kdump_pre script exited with non-zero status!" do_final_action # During systemd service to reboot the machine, stop this shell script running @@ -587,8 +570,7 @@ make_trace_mem "kdump saving vmcore" '1:shortmem' '2+:mem' '3+:slab' do_dump DUMP_RETVAL=$?
-do_kdump_post $DUMP_RETVAL -if [ $? -ne 0 ]; then +if ! do_kdump_post $DUMP_RETVAL; then derror "kdump_post script exited with non-zero status!" fi
POSIX doesn't support keyword local, so add double underscore and prefix to varible names, and reduce variable usage, to avoid any varible name conflict.
Signed-off-by: Kairui Song kasong@redhat.com --- kdump-lib-initramfs.sh | 79 ++++++++++++++++++++---------------------- 1 file changed, 38 insertions(+), 41 deletions(-)
diff --git a/kdump-lib-initramfs.sh b/kdump-lib-initramfs.sh index 051135ae..87fdd8ee 100755 --- a/kdump-lib-initramfs.sh +++ b/kdump-lib-initramfs.sh @@ -9,9 +9,9 @@ KDUMP_CONFIG_FILE="/etc/kdump.conf" # Read kdump config in well formated style kdump_read_conf() { - # Following steps are applied in order: strip tailing comment, strip tailing space, - # strip heading space, match non-empty line, remove duplicated spaces between conf name and value - [ -f "$KDUMP_CONFIG_FILE" ] && sed -n -e "s/#.*//;s/\s*$//;s/^\s*//;s/(\S+)\s*(.*)/\1 \2/p" $KDUMP_CONFIG_FILE + # Following steps are applied in order: strip tailing comment, strip tailing space, + # strip heading space, match non-empty line, remove duplicated spaces between conf name and value + [ -f "$KDUMP_CONFIG_FILE" ] && sed -n -e "s/#.*//;s/\s*$//;s/^\s*//;s/(\S+)\s*(.*)/\1 \2/p" $KDUMP_CONFIG_FILE }
# Retrieves config value defined in kdump.conf @@ -25,48 +25,51 @@ kdump_get_conf_val() {
is_mounted() { - findmnt -k -n $1 &>/dev/null + findmnt -k -n "$1" > /dev/null 2>&1 }
+# $1: info type +# $2: mount source type +# $3: mount source +# $4: extra args get_mount_info() { - local _info_type=$1 _src_type=$2 _src=$3; shift 3 - local _info=$(findmnt -k -n -r -o $_info_type --$_src_type $_src $@) + __kdump_mnt=$(findmnt -k -n -r -o "$1" "--$2" "$3" $4)
- [ -z "$_info" ] && [ -e "/etc/fstab" ] && _info=$(findmnt -s -n -r -o $_info_type --$_src_type $_src $@) + [ -z "$__kdump_mnt" ] && [ -e "/etc/fstab" ] && __kdump_mnt=$(findmnt -s -n -r -o "$1" "--$2" "$3" $4)
- echo $_info + echo "$__kdump_mnt" }
is_ipv6_address() { - echo $1 | grep -q ":" + echo "$1" | grep -q ":" }
is_fs_type_nfs() { - [ "$1" = "nfs" ] || [ "$1" = "nfs4" ] + [ "$1" = "nfs" ] || [ "$1" = "nfs4" ] }
# If $1 contains dracut_args "--mount", return <filesystem type> get_dracut_args_fstype() { - echo $1 | grep "--mount" | sed "s/.*--mount .(.*)/\1/" | cut -d' ' -f3 + echo "$1" | grep "--mount" | sed "s/.*--mount .(.*)/\1/" | awk '{print $3}' }
# If $1 contains dracut_args "--mount", return <device> get_dracut_args_target() { - echo $1 | grep "--mount" | sed "s/.*--mount .(.*)/\1/" | cut -d' ' -f1 + echo "$1" | grep "--mount" | sed "s/.*--mount .(.*)/\1/" | awk '{print $1}' }
get_save_path() { - local _save_path=$(kdump_get_conf_val path) - [ -z "$_save_path" ] && _save_path=$DEFAULT_PATH + __kdump_path=$(kdump_get_conf_val path) + [ -z "$__kdump_path" ] && __kdump_path=$DEFAULT_PATH
- # strip the duplicated "/" - echo $_save_path | tr -s / + # strip the duplicated "/" + echo "$__kdump_path" | tr -s / }
get_root_fs_device() @@ -77,56 +80,50 @@ get_root_fs_device() # Return the current underlying device of a path, ignore bind mounts get_target_from_path() { - local _target - - _target=$(df $1 2>/dev/null | tail -1 | awk '{print $1}') - [[ "$_target" == "/dev/root" ]] && [[ ! -e /dev/root ]] && _target=$(get_root_fs_device) - echo $_target + __kdump_target=$(df "$1" 2> /dev/null | tail -1 | awk '{print $1}') + [ "$__kdump_target" = "/dev/root" ] && [ ! -e /dev/root ] && __kdump_target=$(get_root_fs_device) + echo "$__kdump_target" }
get_fs_type_from_target() { - get_mount_info FSTYPE source $1 -f + get_mount_info FSTYPE source "$1" -f }
get_mntpoint_from_target() { - # --source is applied to ensure non-bind mount is returned - get_mount_info TARGET source $1 -f + # --source is applied to ensure non-bind mount is returned + get_mount_info TARGET source "$1" -f }
is_ssh_dump_target() { - [[ $(kdump_get_conf_val ssh) == *@* ]] + kdump_get_conf_val ssh | grep -q @ }
is_raw_dump_target() { - [[ $(kdump_get_conf_val raw) ]] + [ -n "$(kdump_get_conf_val raw)" ] }
is_nfs_dump_target() { - if [[ $(kdump_get_conf_val nfs) ]]; then - return 0; - fi - - if is_fs_type_nfs $(get_dracut_args_fstype "$(kdump_get_conf_val dracut_args)"); then - return 0 - fi + if [ -n "$(kdump_get_conf_val nfs)" ]; then + return 0 + fi
- local _save_path=$(get_save_path) - local _target=$(get_target_from_path $_save_path) - local _fstype=$(get_fs_type_from_target $_target) + if is_fs_type_nfs "$(get_dracut_args_fstype "$(kdump_get_conf_val dracut_args)")"; then + return 0 + fi
- if is_fs_type_nfs $_fstype; then - return 0 - fi + if is_fs_type_nfs "$(get_fs_type_from_target "$(get_target_from_path "$(get_save_path)")")"; then + return 0 + fi
- return 1 + return 1 }
is_fs_dump_target() { - [[ $(kdump_get_conf_val "ext[234]|xfs|btrfs|minix") ]] + [ -n "$(kdump_get_conf_val "ext[234]|xfs|btrfs|minix")" ] }
Hi Kairui,
On Thu, 19 Aug 2021 19:39:39 +0800 Kairui Song kasong@redhat.com wrote:
POSIX doesn't support keyword local, so add double underscore and prefix to varible names, and reduce variable usage, to avoid any varible name
s/varible/variable/ twice
Thanks Philipp
conflict.
Signed-off-by: Kairui Song kasong@redhat.com
kdump-lib-initramfs.sh | 79 ++++++++++++++++++++---------------------- 1 file changed, 38 insertions(+), 41 deletions(-)
diff --git a/kdump-lib-initramfs.sh b/kdump-lib-initramfs.sh index 051135ae..87fdd8ee 100755 --- a/kdump-lib-initramfs.sh +++ b/kdump-lib-initramfs.sh @@ -9,9 +9,9 @@ KDUMP_CONFIG_FILE="/etc/kdump.conf" # Read kdump config in well formated style kdump_read_conf() {
- # Following steps are applied in order: strip tailing comment, strip tailing space,
- # strip heading space, match non-empty line, remove duplicated spaces between conf name and value
- [ -f "$KDUMP_CONFIG_FILE" ] && sed -n -e "s/#.*//;s/\s*$//;s/^\s*//;s/(\S+)\s*(.*)/\1 \2/p" $KDUMP_CONFIG_FILE
- # Following steps are applied in order: strip tailing comment, strip tailing space,
- # strip heading space, match non-empty line, remove duplicated spaces between conf name and value
- [ -f "$KDUMP_CONFIG_FILE" ] && sed -n -e "s/#.*//;s/\s*$//;s/^\s*//;s/(\S+)\s*(.*)/\1 \2/p" $KDUMP_CONFIG_FILE
}
# Retrieves config value defined in kdump.conf @@ -25,48 +25,51 @@ kdump_get_conf_val() {
is_mounted() {
- findmnt -k -n $1 &>/dev/null
- findmnt -k -n "$1" > /dev/null 2>&1
}
+# $1: info type +# $2: mount source type +# $3: mount source +# $4: extra args get_mount_info() {
- local _info_type=$1 _src_type=$2 _src=$3; shift 3
- local _info=$(findmnt -k -n -r -o $_info_type --$_src_type $_src $@)
- __kdump_mnt=$(findmnt -k -n -r -o "$1" "--$2" "$3" $4)
- [ -z "$_info" ] && [ -e "/etc/fstab" ] && _info=$(findmnt -s -n -r -o $_info_type --$_src_type $_src $@)
- [ -z "$__kdump_mnt" ] && [ -e "/etc/fstab" ] && __kdump_mnt=$(findmnt -s -n -r -o "$1" "--$2" "$3" $4)
- echo $_info
- echo "$__kdump_mnt"
}
is_ipv6_address() {
- echo $1 | grep -q ":"
- echo "$1" | grep -q ":"
}
is_fs_type_nfs() {
- [ "$1" = "nfs" ] || [ "$1" = "nfs4" ]
- [ "$1" = "nfs" ] || [ "$1" = "nfs4" ]
}
# If $1 contains dracut_args "--mount", return <filesystem type> get_dracut_args_fstype() {
- echo $1 | grep "--mount" | sed "s/.*--mount .(.*)/\1/" | cut -d' ' -f3
- echo "$1" | grep "--mount" | sed "s/.*--mount .(.*)/\1/" | awk '{print $3}'
}
# If $1 contains dracut_args "--mount", return <device> get_dracut_args_target() {
- echo $1 | grep "--mount" | sed "s/.*--mount .(.*)/\1/" | cut -d' ' -f1
- echo "$1" | grep "--mount" | sed "s/.*--mount .(.*)/\1/" | awk '{print $1}'
}
get_save_path() {
- local _save_path=$(kdump_get_conf_val path)
- [ -z "$_save_path" ] && _save_path=$DEFAULT_PATH
- __kdump_path=$(kdump_get_conf_val path)
- [ -z "$__kdump_path" ] && __kdump_path=$DEFAULT_PATH
- # strip the duplicated "/"
- echo $_save_path | tr -s /
- # strip the duplicated "/"
- echo "$__kdump_path" | tr -s /
}
get_root_fs_device() @@ -77,56 +80,50 @@ get_root_fs_device() # Return the current underlying device of a path, ignore bind mounts get_target_from_path() {
- local _target
- _target=$(df $1 2>/dev/null | tail -1 | awk '{print $1}')
- [[ "$_target" == "/dev/root" ]] && [[ ! -e /dev/root ]] && _target=$(get_root_fs_device)
- echo $_target
- __kdump_target=$(df "$1" 2> /dev/null | tail -1 | awk '{print $1}')
- [ "$__kdump_target" = "/dev/root" ] && [ ! -e /dev/root ] && __kdump_target=$(get_root_fs_device)
- echo "$__kdump_target"
}
get_fs_type_from_target() {
- get_mount_info FSTYPE source $1 -f
- get_mount_info FSTYPE source "$1" -f
}
get_mntpoint_from_target() {
- # --source is applied to ensure non-bind mount is returned
- get_mount_info TARGET source $1 -f
- # --source is applied to ensure non-bind mount is returned
- get_mount_info TARGET source "$1" -f
}
is_ssh_dump_target() {
- [[ $(kdump_get_conf_val ssh) == *@* ]]
- kdump_get_conf_val ssh | grep -q @
}
is_raw_dump_target() {
- [[ $(kdump_get_conf_val raw) ]]
- [ -n "$(kdump_get_conf_val raw)" ]
}
is_nfs_dump_target() {
- if [[ $(kdump_get_conf_val nfs) ]]; then
return 0;
- fi
- if is_fs_type_nfs $(get_dracut_args_fstype "$(kdump_get_conf_val dracut_args)"); then
return 0
- fi
- if [ -n "$(kdump_get_conf_val nfs)" ]; then
return 0
- fi
- local _save_path=$(get_save_path)
- local _target=$(get_target_from_path $_save_path)
- local _fstype=$(get_fs_type_from_target $_target)
- if is_fs_type_nfs "$(get_dracut_args_fstype "$(kdump_get_conf_val dracut_args)")"; then
return 0
- fi
- if is_fs_type_nfs $_fstype; then
return 0
- fi
- if is_fs_type_nfs "$(get_fs_type_from_target "$(get_target_from_path "$(get_save_path)")")"; then
return 0
- fi
- return 1
- return 1
}
is_fs_dump_target() {
- [[ $(kdump_get_conf_val "ext[234]|xfs|btrfs|minix") ]]
- [ -n "$(kdump_get_conf_val "ext[234]|xfs|btrfs|minix")" ]
}
Updated file syntax with following command:
sed -i -e 's/(\s)[\s([^]]*)\s]/\1[[\ \2 ]]/g' kdump-lib.sh (replace '[ ]' with '[[ ]]')
sed -i -e 's/`([^`]*)`/$(\1)/g' kdump-lib.sh (replace `...` with $(...))
And manually updated [[ ... -a ... ]] and [[ ... -o ... ]] with && and ||.
Signed-off-by: Kairui Song kasong@redhat.com --- kdump-lib.sh | 142 +++++++++++++++++++++++++-------------------------- 1 file changed, 71 insertions(+), 71 deletions(-)
diff --git a/kdump-lib.sh b/kdump-lib.sh index 5a1fcf02..4e9a8293 100755 --- a/kdump-lib.sh +++ b/kdump-lib.sh @@ -13,16 +13,16 @@ is_fadump_capable() { # Check if firmware-assisted dump is enabled # if no, fallback to kdump check - if [ -f $FADUMP_ENABLED_SYS_NODE ]; then - rc=`cat $FADUMP_ENABLED_SYS_NODE` - [ $rc -eq 1 ] && return 0 + if [[ -f $FADUMP_ENABLED_SYS_NODE ]]; then + rc=$(cat $FADUMP_ENABLED_SYS_NODE) + [[ $rc -eq 1 ]] && return 0 fi return 1 }
is_squash_available() { for kmodule in squashfs overlay loop; do - if [ -z "$KDUMP_KERNELVER" ]; then + if [[ -z "$KDUMP_KERNELVER" ]]; then modprobe --dry-run $kmodule &>/dev/null || return 1 else modprobe -S $KDUMP_KERNELVER --dry-run $kmodule &>/dev/null || return 1 @@ -40,7 +40,7 @@ is_pcs_fence_kdump() { # no pcs or fence_kdump_send executables installed? type -P pcs > /dev/null || return 1 - [ -x $FENCE_KDUMP_SEND ] || return 1 + [[ -x $FENCE_KDUMP_SEND ]] || return 1
# fence kdump not configured? (pcs cluster cib | grep 'type="fence_kdump"') &> /dev/null || return 1 @@ -49,7 +49,7 @@ is_pcs_fence_kdump() # Check if fence_kdump is configured using kdump options is_generic_fence_kdump() { - [ -x $FENCE_KDUMP_SEND ] || return 1 + [[ -x $FENCE_KDUMP_SEND ]] || return 1
[[ $(kdump_get_conf_val fence_kdump_nodes) ]] } @@ -59,10 +59,10 @@ to_dev_name() {
case "$dev" in UUID=*) - dev=`blkid -U "${dev#UUID=}"` + dev=$(blkid -U "${dev#UUID=}") ;; LABEL=*) - dev=`blkid -L "${dev#LABEL=}"` + dev=$(blkid -L "${dev#LABEL=}") ;; esac echo $dev @@ -78,10 +78,10 @@ get_user_configured_dump_disk() local _target
_target=$(kdump_get_conf_val "ext[234]|xfs|btrfs|minix|raw") - [ -n "$_target" ] && echo $_target && return + [[ -n "$_target" ]] && echo $_target && return
_target=$(get_dracut_args_target "$(kdump_get_conf_val "dracut_args")") - [ -b "$_target" ] && echo $_target + [[ -b "$_target" ]] && echo $_target }
get_block_dump_target() @@ -93,12 +93,12 @@ get_block_dump_target() fi
_target=$(get_user_configured_dump_disk) - [ -n "$_target" ] && echo $(to_dev_name $_target) && return + [[ -n "$_target" ]] && echo $(to_dev_name $_target) && return
# Get block device name from local save path _path=$(get_save_path) _target=$(get_target_from_path $_path) - [ -b "$_target" ] && echo $(to_dev_name $_target) + [[ -b "$_target" ]] && echo $(to_dev_name $_target) }
is_dump_to_rootfs() @@ -113,7 +113,7 @@ get_failure_action_target() if is_dump_to_rootfs; then # Get rootfs device name _target=$(get_root_fs_device) - [ -b "$_target" ] && echo $(to_dev_name $_target) && return + [[ -b "$_target" ]] && echo $(to_dev_name $_target) && return # Then, must be nfs root echo "nfs" fi @@ -126,7 +126,7 @@ get_kdump_targets() local kdump_targets
_target=$(get_block_dump_target) - if [ -n "$_target" ]; then + if [[ -n "$_target" ]]; then kdump_targets=$_target elif is_ssh_dump_target; then kdump_targets="ssh" @@ -136,7 +136,7 @@ get_kdump_targets()
# Add the root device if dump_to_rootfs is specified. _root=$(get_failure_action_target) - if [ -n "$_root" -a "$kdump_targets" != "$_root" ]; then + if [[ -n "$_root" ]] && [[ "$kdump_targets" != "$_root" ]]; then kdump_targets="$kdump_targets $_root" fi
@@ -204,10 +204,10 @@ get_kdump_mntpoint_from_target() # mount under /kdumproot if dump target is not mounted in first kernel # mount under /kdumproot/$_mntpoint in other cases in 2nd kernel. # systemd will be in charge to umount it. - if [ -z "$_mntpoint" ];then + if [[ -z "$_mntpoint" ]];then _mntpoint="/kdumproot" else - if [ "$_mntpoint" = "/" ];then + if [[ "$_mntpoint" = "/" ]];then _mntpoint="/sysroot" else _mntpoint="/kdumproot/$_mntpoint" @@ -223,10 +223,10 @@ kdump_get_persistent_dev() {
case "$dev" in UUID=*) - dev=`blkid -U "${dev#UUID=}"` + dev=$(blkid -U "${dev#UUID=}") ;; LABEL=*) - dev=`blkid -L "${dev#LABEL=}"` + dev=$(blkid -L "${dev#LABEL=}") ;; esac echo $(get_persistent_dev "$dev") @@ -253,9 +253,9 @@ get_remote_host()
is_hostname() { - local _hostname=`echo $1 | grep ":"` + local _hostname=$(echo $1 | grep ":")
- if [ -n "$_hostname" ]; then + if [[ -n "$_hostname" ]]; then return 1 fi echo $1 | grep -q "[a-zA-Z]" @@ -264,9 +264,9 @@ is_hostname() # Copied from "/etc/sysconfig/network-scripts/network-functions" get_hwaddr() { - if [ -f "/sys/class/net/${1}/address" ]; then + if [[ -f "/sys/class/net/${1}/address" ]]; then awk '{ print toupper($0) }' < /sys/class/net/${1}/address - elif [ -d "/sys/class/net/${1}" ]; then + elif [[ -d "/sys/class/net/${1}" ]]; then LC_ALL= LANG= ip -o link show ${1} 2>/dev/null | \ awk '{ print toupper(gensub(/.*link/[^ ]* ([[:alnum:]:]*).*/, "\1", 1)); }' @@ -347,7 +347,7 @@ get_ifcfg_by_name()
is_nm_running() { - [ "$(LANG=C nmcli -t --fields running general status 2>/dev/null)" = "running" ] + [[ "$(LANG=C nmcli -t --fields running general status 2>/dev/null)" = "running" ]] }
is_nm_handling() @@ -371,7 +371,7 @@ get_ifcfg_nmcli() nm_name=$(LANG=C nmcli -t --fields name,device c show --active 2>/dev/null \ | grep "${1}" | head -1 | cut -d':' -f1) ifcfg_file=$(get_ifcfg_by_uuid "${nm_uuid}") - [ -z "${ifcfg_file}" ] && ifcfg_file=$(get_ifcfg_by_name "${nm_name}") + [[ -z "${ifcfg_file}" ]] && ifcfg_file=$(get_ifcfg_by_name "${nm_name}") fi
echo -n "${ifcfg_file}" @@ -383,15 +383,15 @@ get_ifcfg_legacy() local ifcfg_file
ifcfg_file="/etc/sysconfig/network-scripts/ifcfg-${1}" - [ -f "${ifcfg_file}" ] && echo -n "${ifcfg_file}" && return + [[ -f "${ifcfg_file}" ]] && echo -n "${ifcfg_file}" && return
ifcfg_file=$(get_ifcfg_by_name "${1}") - [ -f "${ifcfg_file}" ] && echo -n "${ifcfg_file}" && return + [[ -f "${ifcfg_file}" ]] && echo -n "${ifcfg_file}" && return
local hwaddr=$(get_hwaddr "${1}") - if [ -n "$hwaddr" ]; then + if [[ -n "$hwaddr" ]]; then ifcfg_file=$(get_ifcfg_by_hwaddr "${hwaddr}") - [ -f "${ifcfg_file}" ] && echo -n "${ifcfg_file}" && return + [[ -f "${ifcfg_file}" ]] && echo -n "${ifcfg_file}" && return fi
ifcfg_file=$(get_ifcfg_by_device "${1}") @@ -405,7 +405,7 @@ get_ifcfg_filename() { local ifcfg_file
ifcfg_file=$(get_ifcfg_nmcli "${1}") - if [ -z "${ifcfg_file}" ]; then + if [[ -z "${ifcfg_file}" ]]; then ifcfg_file=$(get_ifcfg_legacy "${1}") fi
@@ -418,7 +418,7 @@ is_dracut_mod_omitted() { local dracut_args dracut_mod=$1
set -- $(kdump_get_conf_val dracut_args) - while [ $# -gt 0 ]; do + while [[ $# -gt 0 ]]; do case $1 in -o|--omit) [[ " ${2//[^[:alnum:]]/ } " == *" $dracut_mod "* ]] && return 0 @@ -432,11 +432,11 @@ is_dracut_mod_omitted() { is_wdt_active() { local active
- [ -d /sys/class/watchdog ] || return 1 + [[ -d /sys/class/watchdog ]] || return 1 for dir in /sys/class/watchdog/*; do - [ -f "$dir/state" ] || continue + [[ -f "$dir/state" ]] || continue active=$(< "$dir/state") - [ "$active" = "active" ] && return 0 + [[ "$active" = "active" ]] && return 0 done return 1 } @@ -454,7 +454,7 @@ check_crash_mem_reserved() local mem_reserved
mem_reserved=$(cat /sys/kernel/kexec_crash_size) - if [ $mem_reserved -eq 0 ]; then + if [[ $mem_reserved -eq 0 ]]; then derror "No memory reserved for crash kernel" return 1 fi @@ -464,7 +464,7 @@ check_crash_mem_reserved()
check_kdump_feasibility() { - if [ ! -e /sys/kernel/kexec_crash_loaded ]; then + if [[ ! -e /sys/kernel/kexec_crash_loaded ]]; then derror "Kdump is not supported on this kernel" return 1 fi @@ -474,13 +474,13 @@ check_kdump_feasibility()
check_current_kdump_status() { - if [ ! -f /sys/kernel/kexec_crash_loaded ];then + if [[ ! -f /sys/kernel/kexec_crash_loaded ]];then derror "Perhaps CONFIG_CRASH_DUMP is not enabled in kernel" return 1 fi
- rc=`cat /sys/kernel/kexec_crash_loaded` - if [ $rc == 1 ]; then + rc=$(cat /sys/kernel/kexec_crash_loaded) + if [[ $rc == 1 ]]; then return 0 else return 1 @@ -529,7 +529,7 @@ append_cmdline() local newstr=${cmdline/$2/""}
# unchanged str implies argument wasn't there - if [ "$cmdline" == "$newstr" ]; then + if [[ "$cmdline" == "$newstr" ]]; then cmdline="${cmdline} ${2}=${3}" fi
@@ -561,11 +561,11 @@ is_secure_boot_enforced() # On powerpc, secure boot is enforced if: # host secure boot: /ibm,secure-boot/os-secureboot-enforcing DT property exists # guest secure boot: /ibm,secure-boot >= 2 - if [ -f /proc/device-tree/ibm,secureboot/os-secureboot-enforcing ]; then + if [[ -f /proc/device-tree/ibm,secureboot/os-secureboot-enforcing ]]; then return 0 fi - if [ -f /proc/device-tree/ibm,secure-boot ] && \ - [ $(lsprop /proc/device-tree/ibm,secure-boot | tail -1) -ge 2 ]; then + if [[ -f /proc/device-tree/ibm,secure-boot ]] && \ + [[ $(lsprop /proc/device-tree/ibm,secure-boot | tail -1) -ge 2 ]]; then return 0 fi
@@ -573,11 +573,11 @@ is_secure_boot_enforced() secure_boot_file=$(find /sys/firmware/efi/efivars -name SecureBoot-* 2>/dev/null) setup_mode_file=$(find /sys/firmware/efi/efivars -name SetupMode-* 2>/dev/null)
- if [ -f "$secure_boot_file" ] && [ -f "$setup_mode_file" ]; then + if [[ -f "$secure_boot_file" ]] && [[ -f "$setup_mode_file" ]]; then secure_boot_byte=$(hexdump -v -e '/1 "%d\ "' $secure_boot_file|cut -d' ' -f 5) setup_mode_byte=$(hexdump -v -e '/1 "%d\ "' $setup_mode_file|cut -d' ' -f 5)
- if [ "$secure_boot_byte" = "1" ] && [ "$setup_mode_byte" = "0" ]; then + if [[ "$secure_boot_byte" = "1" ]] && [[ "$setup_mode_byte" = "0" ]]; then return 0 fi fi @@ -599,22 +599,22 @@ prepare_kexec_args() local kexec_args=$1 local found_elf_args
- ARCH=`uname -m` - if [ "$ARCH" == "i686" -o "$ARCH" == "i386" ] + ARCH=$(uname -m) + if [[ "$ARCH" == "i686" ]] || [[ "$ARCH" == "i386" ]] then need_64bit_headers - if [ $? == 1 ] + if [[ $? == 1 ]] then - found_elf_args=`echo $kexec_args | grep elf32-core-headers` - if [ -n "$found_elf_args" ] + found_elf_args=$(echo $kexec_args | grep elf32-core-headers) + if [[ -n "$found_elf_args" ]] then dwarn "Warning: elf32-core-headers overrides correct elf64 setting" else kexec_args="$kexec_args --elf64-core-headers" fi else - found_elf_args=`echo $kexec_args | grep elf64-core-headers` - if [ -z "$found_elf_args" ] + found_elf_args=$(echo $kexec_args | grep elf64-core-headers) + if [[ -z "$found_elf_args" ]] then kexec_args="$kexec_args --elf32-core-headers" fi @@ -635,7 +635,7 @@ prepare_kdump_bootinfo() local boot_imglist boot_dirlist boot_initrdlist curr_kver="$(uname -r)" local machine_id
- if [ -z "$KDUMP_KERNELVER" ]; then + if [[ -z "$KDUMP_KERNELVER" ]]; then KDUMP_KERNELVER="$(uname -r)" fi
@@ -645,20 +645,20 @@ prepare_kdump_bootinfo()
# Use BOOT_IMAGE as reference if possible, strip the GRUB root device prefix in (hd0,gpt1) format local boot_img="$(cat /proc/cmdline | sed "s/^BOOT_IMAGE=((\S*))?(\S*) .*/\2/")" - if [ -n "$boot_img" ]; then + if [[ -n "$boot_img" ]]; then boot_imglist="$boot_img $boot_imglist" fi
for dir in $boot_dirlist; do for img in $boot_imglist; do - if [ -f "$dir/$img" ]; then + if [[ -f "$dir/$img" ]]; then KDUMP_KERNEL=$(echo $dir/$img | tr -s '/') break 2 fi done done
- if ! [ -e "$KDUMP_KERNEL" ]; then + if ! [[ -e "$KDUMP_KERNEL" ]]; then derror "Failed to detect kdump kernel location" return 1 fi @@ -669,7 +669,7 @@ prepare_kdump_bootinfo() # Default initrd should just stay aside of kernel image, try to find it in KDUMP_BOOTDIR boot_initrdlist="initramfs-$KDUMP_KERNELVER.img initrd" for initrd in $boot_initrdlist; do - if [ -f "$KDUMP_BOOTDIR/$initrd" ]; then + if [[ -f "$KDUMP_BOOTDIR/$initrd" ]]; then defaut_initrd_base="$initrd" DEFAULT_INITRD="$KDUMP_BOOTDIR/$defaut_initrd_base" break @@ -687,7 +687,7 @@ prepare_kdump_bootinfo() kdump_initrd_base=${defaut_initrd_base}kdump fi
- # Place kdump initrd in `/var/lib/kdump` if `KDUMP_BOOTDIR` not writable + # Place kdump initrd in $(/var/lib/kdump) if $(KDUMP_BOOTDIR) not writable if [[ ! -w "$KDUMP_BOOTDIR" ]];then var_target_initrd_dir="/var/lib/kdump" mkdir -p "$var_target_initrd_dir" @@ -724,7 +724,7 @@ prepare_cmdline() { local cmdline id
- if [ -z "$1" ]; then + if [[ -z "$1" ]]; then cmdline=$(cat /proc/cmdline) else cmdline="$1" @@ -754,7 +754,7 @@ prepare_cmdline() cmdline="${cmdline} $3"
id=$(get_bootcpu_apicid) - if [ ! -z ${id} ] ; then + if [[ ! -z ${id} ]] ; then cmdline=$(append_cmdline "${cmdline}" disable_cpu_apicid ${id}) fi
@@ -803,7 +803,7 @@ get_recommend_size() last_unit=""
start=${_ck_cmdline: :1} - if [ $mem_size -lt $start ]; then + if [[ $mem_size -lt $start ]]; then echo "0M" return fi @@ -813,10 +813,10 @@ get_recommend_size() recommend=$(echo $i | awk -F "-" '{ print $2 }' | awk -F ":" '{ print $2 }') size=${end: : -1} unit=${end: -1} - if [ $unit == 'T' ]; then + if [[ $unit == 'T' ]]; then let size=$size*1024 fi - if [ $mem_size -lt $size ]; then + if [[ $mem_size -lt $size ]]; then echo $recommend IFS="$OLDIFS" return @@ -826,28 +826,28 @@ get_recommend_size() }
# return recommended size based on current system RAM size -# $1: kernel version, if not set, will defaults to `uname -r` +# $1: kernel version, if not set, will defaults to $(uname -r) kdump_get_arch_recommend_size() { local kernel=$1 arch
- if ! [ -r "/proc/iomem" ] ; then + if ! [[ -r "/proc/iomem" ]] ; then echo "Error, can not access /proc/iomem." return 1 fi
- [ -z "$kernel" ] && kernel=$(uname -r) + [[ -z "$kernel" ]] && kernel=$(uname -r) ck_cmdline=$(cat "/usr/lib/modules/$kernel/crashkernel.default" 2>/dev/null)
- if [ -n "$ck_cmdline" ]; then + if [[ -n "$ck_cmdline" ]]; then ck_cmdline=${ck_cmdline#crashkernel=} else arch=$(lscpu | grep Architecture | awk -F ":" '{ print $2 }' | tr '[:lower:]' '[:upper:]') - if [ "$arch" = "X86_64" ] || [ "$arch" = "S390X" ]; then + if [[ "$arch" = "X86_64" ]] || [[ "$arch" = "S390X" ]]; then ck_cmdline="1G-4G:160M,4G-64G:192M,64G-1T:256M,1T-:512M" - elif [ "$arch" = "AARCH64" ]; then + elif [[ "$arch" = "AARCH64" ]]; then ck_cmdline="2G-:448M" - elif [ "$arch" = "PPC64LE" ]; then + elif [[ "$arch" = "PPC64LE" ]]; then if is_fadump_capable; then ck_cmdline="4G-16G:768M,16G-64G:1G,64G-128G:2G,128G-1T:4G,1T-2T:6G,2T-4T:12G,4T-8T:20G,8T-16T:36G,16T-32T:64G,32T-64T:128G,64T-:180G" else @@ -923,7 +923,7 @@ try_decompress() # "grep" that report the byte offset of the line instead of the pattern.
# Try to find the header ($1) and decompress from here - for pos in `tr "$1\n$2" "\n$2=" < "$4" | grep -abo "^$2"` + for pos in $(tr "$1\n$2" "\n$2=" < "$4" | grep -abo "^$2") do if ! type -P $3 > /dev/null; then ddebug "Signiature detected but '$3' is missing, skip this decompressor"
nmcli expects multiple parameters, but get_nmcli_value_by_field only accepts two params and depends on shell word splitting to split the _nm_show_cmd into multiple params, which is very fragile.
By switching the param order, the function can be greatly simplified and multiple params can be used properly.
Signed-off-by: Kairui Song kasong@redhat.com --- dracut-module-setup.sh | 10 +++++----- kdump-lib.sh | 10 +++------- 2 files changed, 8 insertions(+), 12 deletions(-)
diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index 74b969cb..3a8b0e65 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -91,7 +91,7 @@ kdump_setup_dns() { local _nameserver _dns _tmp array local _dnsfile=${initdir}/etc/cmdline.d/42dns.conf
- _tmp=$(get_nmcli_value_by_field "$_nm_show_cmd" "IP4.DNS") + _tmp=$(get_nmcli_value_by_field "IP4.DNS" "$_nm_show_cmd") # shellcheck disable=SC2206 array=(${_tmp//|/ }) if [[ ${array[*]} ]]; then @@ -384,7 +384,7 @@ kdump_setup_bond() { done echo -n " bond=$_netdev:${_slaves%,}" >> "${initdir}/etc/cmdline.d/42bond.conf"
- _bondoptions=$(get_nmcli_value_by_field "$_nm_show_cmd" "bond.options") + _bondoptions=$(get_nmcli_value_by_field "bond.options" "$_nm_show_cmd")
if [[ -z $_bondoptions ]]; then dwarning "Failed to get bond configuration via nmlci output. Now try sourcing ifcfg script." @@ -482,9 +482,9 @@ kdump_setup_znet() { local NETTYPE local SUBCHANNELS
- NETTYPE=$(get_nmcli_value_by_field "$_nmcli_cmd" "${s390_prefix}nettype") - SUBCHANNELS=$(get_nmcli_value_by_field "$_nmcli_cmd" "${s390_prefix}subchannels") - _options=$(get_nmcli_value_by_field "$_nmcli_cmd" "${s390_prefix}options") + NETTYPE=$(get_nmcli_value_by_field "${s390_prefix}nettype" "$_nmcli_cmd") + SUBCHANNELS=$(get_nmcli_value_by_field "${s390_prefix}subchannels" "$_nmcli_cmd") + _options=$(get_nmcli_value_by_field "${s390_prefix}options" "$_nmcli_cmd")
if [[ -z $NETTYPE || -z $SUBCHANNELS || -z $_options ]]; then dwarning "Failed to get znet configuration via nmlci output. Now try sourcing ifcfg script." diff --git a/kdump-lib.sh b/kdump-lib.sh index 4e9a8293..2e003dd8 100755 --- a/kdump-lib.sh +++ b/kdump-lib.sh @@ -275,6 +275,7 @@ get_hwaddr()
# Get value by a field using "nmcli -g" +# Usage: get_nmcli_value_by_field <field> <nmcli command> # # "nmcli --get-values" allows us to retrive value(s) by field, for example, # nmcli --get-values <field> connection show /org/freedesktop/NetworkManager/ActiveConnection/1 @@ -285,12 +286,7 @@ get_hwaddr() # bond.options "mode=balance-rr" get_nmcli_value_by_field() { - local _nm_show_cmd=$1 - local _field=$2 - - local val=$(LANG=C nmcli --get-values $_field $_nm_show_cmd) - - echo -n "$val" + LANG=C nmcli --get-values "$@" }
# Get nmcli connection apath (a D-Bus active connection path ) by ifname @@ -302,7 +298,7 @@ get_nmcli_connection_apath_by_ifname() local _ifname=$1 local _nm_show_cmd="device show $_ifname"
- local _apath=$(get_nmcli_value_by_field "$_nm_show_cmd" "GENERAL.CON-PATH") + local _apath=$(get_nmcli_value_by_field "GENERAL.CON-PATH" "$_nm_show_cmd")
echo -n "$_apath" }
On Thu, Aug 19, 2021 at 07:39:41PM +0800, Kairui Song wrote:
nmcli expects multiple parameters, but get_nmcli_value_by_field only accepts two params and depends on shell word splitting to split the _nm_show_cmd into multiple params, which is very fragile.
By switching the param order, the function can be greatly simplified and multiple params can be used properly.
Signed-off-by: Kairui Song kasong@redhat.com
dracut-module-setup.sh | 10 +++++----- kdump-lib.sh | 10 +++------- 2 files changed, 8 insertions(+), 12 deletions(-)
diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index 74b969cb..3a8b0e65 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -91,7 +91,7 @@ kdump_setup_dns() { local _nameserver _dns _tmp array local _dnsfile=${initdir}/etc/cmdline.d/42dns.conf
- _tmp=$(get_nmcli_value_by_field "$_nm_show_cmd" "IP4.DNS")
- _tmp=$(get_nmcli_value_by_field "IP4.DNS" "$_nm_show_cmd") # shellcheck disable=SC2206 array=(${_tmp//|/ }) if [[ ${array[*]} ]]; then
@@ -384,7 +384,7 @@ kdump_setup_bond() { done echo -n " bond=$_netdev:${_slaves%,}" >> "${initdir}/etc/cmdline.d/42bond.conf"
- _bondoptions=$(get_nmcli_value_by_field "$_nm_show_cmd" "bond.options")
_bondoptions=$(get_nmcli_value_by_field "bond.options" "$_nm_show_cmd")
if [[ -z $_bondoptions ]]; then dwarning "Failed to get bond configuration via nmlci output. Now try sourcing ifcfg script."
@@ -482,9 +482,9 @@ kdump_setup_znet() { local NETTYPE local SUBCHANNELS
- NETTYPE=$(get_nmcli_value_by_field "$_nmcli_cmd" "${s390_prefix}nettype")
- SUBCHANNELS=$(get_nmcli_value_by_field "$_nmcli_cmd" "${s390_prefix}subchannels")
- _options=$(get_nmcli_value_by_field "$_nmcli_cmd" "${s390_prefix}options")
NETTYPE=$(get_nmcli_value_by_field "${s390_prefix}nettype" "$_nmcli_cmd")
SUBCHANNELS=$(get_nmcli_value_by_field "${s390_prefix}subchannels" "$_nmcli_cmd")
_options=$(get_nmcli_value_by_field "${s390_prefix}options" "$_nmcli_cmd")
if [[ -z $NETTYPE || -z $SUBCHANNELS || -z $_options ]]; then dwarning "Failed to get znet configuration via nmlci output. Now try sourcing ifcfg script."
diff --git a/kdump-lib.sh b/kdump-lib.sh index 4e9a8293..2e003dd8 100755 --- a/kdump-lib.sh +++ b/kdump-lib.sh @@ -275,6 +275,7 @@ get_hwaddr()
# Get value by a field using "nmcli -g" +# Usage: get_nmcli_value_by_field <field> <nmcli command> # # "nmcli --get-values" allows us to retrive value(s) by field, for example, # nmcli --get-values <field> connection show /org/freedesktop/NetworkManager/ActiveConnection/1 @@ -285,12 +286,7 @@ get_hwaddr() # bond.options "mode=balance-rr" get_nmcli_value_by_field() {
- local _nm_show_cmd=$1
- local _field=$2
- local val=$(LANG=C nmcli --get-values $_field $_nm_show_cmd)
- echo -n "$val"
- LANG=C nmcli --get-values "$@"
}
# Get nmcli connection apath (a D-Bus active connection path ) by ifname @@ -302,7 +298,7 @@ get_nmcli_connection_apath_by_ifname() local _ifname=$1 local _nm_show_cmd="device show $_ifname"
- local _apath=$(get_nmcli_value_by_field "$_nm_show_cmd" "GENERAL.CON-PATH")
- local _apath=$(get_nmcli_value_by_field "GENERAL.CON-PATH" "$_nm_show_cmd")
This won't work because "$_nm_show_cmd" is passed to nmcli as a single parameter in get_nmcli_value_by_field,
$ nmcli --get-values GENERAL.CON-PATH "device show tun0" Error: argument 'device show tun0' not understood. Try passing --help instead.
But "[PATCH v2 43/49] kdump-lib.sh: fix word splitting of nmcli params" later fixes this issue. Maybe "[PATCH v2 43/49]" should be squashed with this patch considering that "[PATCH v2 43/49]" also explains how "shell word splitting is very fragile", a.k.a, the connection name could have space.
echo -n "$_apath"
}
2.31.1 _______________________________________________ kexec mailing list -- kexec@lists.fedoraproject.org To unsubscribe send an email to kexec-leave@lists.fedoraproject.org Fedora Code of Conduct: https://docs.fedoraproject.org/en-US/project/code-of-conduct/ List Guidelines: https://fedoraproject.org/wiki/Mailing_list_guidelines List Archives: https://lists.fedoraproject.org/archives/list/kexec@lists.fedoraproject.org Do not reply to spam on the list, report it: https://pagure.io/fedora-infrastructure
On Fri, Sep 3, 2021 at 4:50 PM Coiby Xu coxu@redhat.com wrote:
On Thu, Aug 19, 2021 at 07:39:41PM +0800, Kairui Song wrote:
nmcli expects multiple parameters, but get_nmcli_value_by_field only accepts two params and depends on shell word splitting to split the _nm_show_cmd into multiple params, which is very fragile.
By switching the param order, the function can be greatly simplified and multiple params can be used properly.
Signed-off-by: Kairui Song kasong@redhat.com
dracut-module-setup.sh | 10 +++++----- kdump-lib.sh | 10 +++------- 2 files changed, 8 insertions(+), 12 deletions(-)
diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index 74b969cb..3a8b0e65 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -91,7 +91,7 @@ kdump_setup_dns() { local _nameserver _dns _tmp array local _dnsfile=${initdir}/etc/cmdline.d/42dns.conf
- _tmp=$(get_nmcli_value_by_field "$_nm_show_cmd" "IP4.DNS")
- _tmp=$(get_nmcli_value_by_field "IP4.DNS" "$_nm_show_cmd") # shellcheck disable=SC2206 array=(${_tmp//|/ }) if [[ ${array[*]} ]]; then
@@ -384,7 +384,7 @@ kdump_setup_bond() { done echo -n " bond=$_netdev:${_slaves%,}" >> "${initdir}/etc/cmdline.d/42bond.conf"
- _bondoptions=$(get_nmcli_value_by_field "$_nm_show_cmd" "bond.options")
_bondoptions=$(get_nmcli_value_by_field "bond.options" "$_nm_show_cmd")
if [[ -z $_bondoptions ]]; then dwarning "Failed to get bond configuration via nmlci output. Now try sourcing ifcfg script."
@@ -482,9 +482,9 @@ kdump_setup_znet() { local NETTYPE local SUBCHANNELS
- NETTYPE=$(get_nmcli_value_by_field "$_nmcli_cmd" "${s390_prefix}nettype")
- SUBCHANNELS=$(get_nmcli_value_by_field "$_nmcli_cmd" "${s390_prefix}subchannels")
- _options=$(get_nmcli_value_by_field "$_nmcli_cmd" "${s390_prefix}options")
NETTYPE=$(get_nmcli_value_by_field "${s390_prefix}nettype" "$_nmcli_cmd")
SUBCHANNELS=$(get_nmcli_value_by_field "${s390_prefix}subchannels" "$_nmcli_cmd")
_options=$(get_nmcli_value_by_field "${s390_prefix}options" "$_nmcli_cmd")
if [[ -z $NETTYPE || -z $SUBCHANNELS || -z $_options ]]; then dwarning "Failed to get znet configuration via nmlci output. Now try sourcing ifcfg script."
diff --git a/kdump-lib.sh b/kdump-lib.sh index 4e9a8293..2e003dd8 100755 --- a/kdump-lib.sh +++ b/kdump-lib.sh @@ -275,6 +275,7 @@ get_hwaddr()
# Get value by a field using "nmcli -g" +# Usage: get_nmcli_value_by_field <field> <nmcli command> # # "nmcli --get-values" allows us to retrive value(s) by field, for example, # nmcli --get-values <field> connection show /org/freedesktop/NetworkManager/ActiveConnection/1 @@ -285,12 +286,7 @@ get_hwaddr() # bond.options "mode=balance-rr" get_nmcli_value_by_field() {
- local _nm_show_cmd=$1
- local _field=$2
- local val=$(LANG=C nmcli --get-values $_field $_nm_show_cmd)
- echo -n "$val"
- LANG=C nmcli --get-values "$@"
}
# Get nmcli connection apath (a D-Bus active connection path ) by ifname @@ -302,7 +298,7 @@ get_nmcli_connection_apath_by_ifname() local _ifname=$1 local _nm_show_cmd="device show $_ifname"
- local _apath=$(get_nmcli_value_by_field "$_nm_show_cmd" "GENERAL.CON-PATH")
- local _apath=$(get_nmcli_value_by_field "GENERAL.CON-PATH" "$_nm_show_cmd")
This won't work because "$_nm_show_cmd" is passed to nmcli as a single parameter in get_nmcli_value_by_field,
$ nmcli --get-values GENERAL.CON-PATH "device show tun0" Error: argument 'device show tun0' not understood. Try passing --help instead.
But "[PATCH v2 43/49] kdump-lib.sh: fix word splitting of nmcli params" later fixes this issue. Maybe "[PATCH v2 43/49]" should be squashed with this patch considering that "[PATCH v2 43/49]" also explains how "shell word splitting is very fragile", a.k.a, the connection name could have space.
Good idea, let me squash them together, I didn't check this one carefully because later patch will rewrite part of the code, leave a broken commit here is not a good idea.
echo -n "$_apath"
}
2.31.1 _______________________________________________ kexec mailing list -- kexec@lists.fedoraproject.org To unsubscribe send an email to kexec-leave@lists.fedoraproject.org Fedora Code of Conduct: https://docs.fedoraproject.org/en-US/project/code-of-conduct/ List Guidelines: https://fedoraproject.org/wiki/Mailing_list_guidelines List Archives: https://lists.fedoraproject.org/archives/list/kexec@lists.fedoraproject.org Do not reply to spam on the list, report it: https://pagure.io/fedora-infrastructure
-- Best regards, Coiby
Currently get_nmcli_connection_show_cmd_by_ifname returns multiple nmcli params in a single variable, and depend on shell word splitting to split the words when calling nmcli. But this is very fragile and break easily when there are any special character in the connection path.
This function is only introduced to get and cache the nmcli command which contains the "connection name".
Actually only cache the "connection path" is enough. Callers should just call get_nmcli_connection_apath_by_ifname to cache the path, and a new helper get_nmcli_field_by_conpath is introduced here to get value from nmcli. This way "connection path" can contain any character.
Also get rid of another nmcli_cmd usage in get_nmcli_connection_apath_by_ifname which stores multiple params in a single bash variable separated by space.
Signed-off-by: Kairui Song kasong@redhat.com --- dracut-module-setup.sh | 37 ++++++++++++++++++------------------- kdump-lib.sh | 28 ++++++++++------------------ 2 files changed, 28 insertions(+), 37 deletions(-)
diff --git a/dracut-module-setup.sh b/dracut-module-setup.sh index 3a8b0e65..bc627832 100755 --- a/dracut-module-setup.sh +++ b/dracut-module-setup.sh @@ -84,14 +84,13 @@ source_ifcfg_file() { fi }
-# $1: nmcli connection show output kdump_setup_dns() { local _netdev="$1" - local _nm_show_cmd="$2" + local _conpath="$2" local _nameserver _dns _tmp array local _dnsfile=${initdir}/etc/cmdline.d/42dns.conf
- _tmp=$(get_nmcli_value_by_field "IP4.DNS" "$_nm_show_cmd") + _tmp=$(get_nmcli_field_by_conpath "IP4.DNS" "$_conpath") # shellcheck disable=SC2206 array=(${_tmp//|/ }) if [[ ${array[*]} ]]; then @@ -354,7 +353,7 @@ kdump_setup_bridge() { [[ -e $_dev ]] || continue _kdumpdev=$_dev if kdump_is_bond "$_dev"; then - $(kdump_setup_bond "$_dev" "$(get_nmcli_connection_show_cmd_by_ifname "$_dev")") || exit 1 + $(kdump_setup_bond "$_dev" "$(get_nmcli_connection_apath_by_ifname "$_dev")") || exit 1 elif kdump_is_team "$_dev"; then kdump_setup_team "$_dev" elif kdump_is_vlan "$_dev"; then @@ -374,7 +373,7 @@ kdump_setup_bridge() { # bond=bond0:eth0,eth1:mode=balance-rr kdump_setup_bond() { local _netdev="$1" - local _nm_show_cmd="$2" + local _conpath="$2" local _dev _mac _slaves _kdumpdev _bondoptions for _dev in $(cat "/sys/class/net/$_netdev/bonding/slaves"); do _mac=$(kdump_get_perm_addr "$_dev") @@ -384,7 +383,7 @@ kdump_setup_bond() { done echo -n " bond=$_netdev:${_slaves%,}" >> "${initdir}/etc/cmdline.d/42bond.conf"
- _bondoptions=$(get_nmcli_value_by_field "bond.options" "$_nm_show_cmd") + _bondoptions=$(get_nmcli_field_by_conpath "bond.options" "$_conpath")
if [[ -z $_bondoptions ]]; then dwarning "Failed to get bond configuration via nmlci output. Now try sourcing ifcfg script." @@ -435,7 +434,7 @@ kdump_setup_vlan() { derror "Vlan over bridge is not supported!" exit 1 elif kdump_is_bond "$_phydev"; then - $(kdump_setup_bond "$_phydev" "$(get_nmcli_connection_show_cmd_by_ifname "$_phydev")") || exit 1 + $(kdump_setup_bond "$_phydev" "$(get_nmcli_connection_apath_by_ifname "$_phydev")") || exit 1 echo " vlan=$(kdump_setup_ifname "$_netdev"):$_phydev" > "${initdir}/etc/cmdline.d/43vlan.conf" else _kdumpdev="$(kdump_setup_ifname "$_phydev")" @@ -473,18 +472,18 @@ find_online_znet_device() {
# setup s390 znet cmdline # $1: netdev (ifname) -# $2: nmcli connection show output +# $2: nmcli connection path kdump_setup_znet() { local _netdev="$1" - local _nmcli_cmd="$2" + local _conpath="$2" local s390_prefix="802-3-ethernet.s390-" local _options="" local NETTYPE local SUBCHANNELS
- NETTYPE=$(get_nmcli_value_by_field "${s390_prefix}nettype" "$_nmcli_cmd") - SUBCHANNELS=$(get_nmcli_value_by_field "${s390_prefix}subchannels" "$_nmcli_cmd") - _options=$(get_nmcli_value_by_field "${s390_prefix}options" "$_nmcli_cmd") + NETTYPE=$(get_nmcli_field_by_conpath "${s390_prefix}nettype" "$_conpath") + SUBCHANNELS=$(get_nmcli_field_by_conpath "${s390_prefix}subchannels" "$_conpath") + _options=$(get_nmcli_field_by_conpath "${s390_prefix}options" "$_conpath")
if [[ -z $NETTYPE || -z $SUBCHANNELS || -z $_options ]]; then dwarning "Failed to get znet configuration via nmlci output. Now try sourcing ifcfg script." @@ -531,22 +530,22 @@ kdump_get_remote_ip() { # initramfs accessing giving destination # $1: destination host kdump_install_net() { - local _destaddr _srcaddr _route _netdev _nm_show_cmd kdumpnic + local _destaddr _srcaddr _route _netdev _conpath kdumpnic local _static _proto _ip_conf _ip_opts _ifname_opts - local _znet_netdev _nm_show_cmd_znet + local _znet_netdev _znet_conpath
_destaddr=$(kdump_get_remote_ip "$1") _route=$(kdump_get_ip_route "$_destaddr") _srcaddr=$(kdump_get_ip_route_field "$_route" "src") _netdev=$(kdump_get_ip_route_field "$_route" "dev") - _nm_show_cmd=$(get_nmcli_connection_show_cmd_by_ifname "$_netdev") + _conpath=$(get_nmcli_connection_apath_by_ifname "$_netdev") _netmac=$(kdump_get_mac_addr "$_netdev") kdumpnic=$(kdump_setup_ifname "$_netdev")
_znet_netdev=$(find_online_znet_device) if [[ -n $_znet_netdev ]]; then - _nm_show_cmd_znet=$(get_nmcli_connection_show_cmd_by_ifname "$_znet_netdev") - if ! $(kdump_setup_znet "$_znet_netdev" "$_nm_show_cmd_znet"); then + _znet_conpath=$(get_nmcli_connection_apath_by_ifname "$_znet_netdev") + if ! $(kdump_setup_znet "$_znet_netdev" "$_znet_conpath"); then derror "Failed to set up znet" exit 1 fi @@ -576,7 +575,7 @@ kdump_install_net() { if kdump_is_bridge "$_netdev"; then kdump_setup_bridge "$_netdev" elif kdump_is_bond "$_netdev"; then - $(kdump_setup_bond "$_netdev" "$_nm_show_cmd") || exit 1 + $(kdump_setup_bond "$_netdev" "$_conpath") || exit 1 elif kdump_is_team "$_netdev"; then kdump_setup_team "$_netdev" elif kdump_is_vlan "$_netdev"; then @@ -586,7 +585,7 @@ kdump_install_net() { echo "$_ifname_opts" >> "$_ip_conf" fi
- kdump_setup_dns "$_netdev" "$_nm_show_cmd" + kdump_setup_dns "$_netdev" "$_conpath"
if [[ ! -f ${initdir}/etc/cmdline.d/50neednet.conf ]]; then # network-manager module needs this parameter diff --git a/kdump-lib.sh b/kdump-lib.sh index 2e003dd8..125423f5 100755 --- a/kdump-lib.sh +++ b/kdump-lib.sh @@ -289,6 +289,15 @@ get_nmcli_value_by_field() LANG=C nmcli --get-values "$@" }
+# Get nmcli field value of an connection apath (a D-Bus active connection path) +# Usage: get_nmcli_field_by_apath <field> <apath> +get_nmcli_field_by_conpath() +{ + local _field=$1 _apath=$2 + + get_nmcli_value_by_field "$_field" connection show "$_apath" +} + # Get nmcli connection apath (a D-Bus active connection path ) by ifname # # apath is used for nmcli connection operations, e.g. @@ -296,25 +305,8 @@ get_nmcli_value_by_field() get_nmcli_connection_apath_by_ifname() { local _ifname=$1 - local _nm_show_cmd="device show $_ifname" - - local _apath=$(get_nmcli_value_by_field "GENERAL.CON-PATH" "$_nm_show_cmd") - - echo -n "$_apath" -} - -# Get nmcli connection show cmd by ifname -# -# "$_apath" is supposed to not contain any chracter that -# need to be escapded, e.g. space. Otherwise get_nmcli_value_by_field -# would fail. -get_nmcli_connection_show_cmd_by_ifname() -{ - local _ifname="$1" - local _apath=$(get_nmcli_connection_apath_by_ifname "$_ifname") - local _nm_show_cmd="connection show $_apath"
- echo -n "$_nm_show_cmd" + get_nmcli_value_by_field "GENERAL.CON-PATH" device show "$_ifname" }
get_ifcfg_by_device()
Combine multiple sed calls into one.
Signed-off-by: Kairui Song kasong@redhat.com --- kdump-lib.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/kdump-lib.sh b/kdump-lib.sh index 125423f5..2f5b17ad 100755 --- a/kdump-lib.sh +++ b/kdump-lib.sh @@ -774,7 +774,7 @@ get_system_size() result=$(cat /proc/iomem | grep "System RAM" | awk -F ":" '{ print $1 }' | tr [:lower:] [:upper:] | paste -sd+) result="+$result" # replace '-' with '+0x' and '+' with '-0x' - sum=$( echo $result | sed -e 's/-/K0x/g' | sed -e 's/+/-0x/g' | sed -e 's/K/+/g' ) + sum=$(echo "$result" | sed -e 's/-/K0x/g' -e 's/+/-0x/g' -e 's/K/+/g') size=$(printf "%d\n" $(($sum))) let size=$size/1024/1024/1024
Properly quote strings, remove duplicated echo / cat, and separate some variable declaration and assignment, remove unused variable and update legacy syntax.
Signed-off-by: Kairui Song kasong@redhat.com --- kdump-lib.sh | 199 ++++++++++++++++++++++++++------------------------- 1 file changed, 100 insertions(+), 99 deletions(-)
diff --git a/kdump-lib.sh b/kdump-lib.sh index 2f5b17ad..b89bb294 100755 --- a/kdump-lib.sh +++ b/kdump-lib.sh @@ -14,8 +14,7 @@ is_fadump_capable() # Check if firmware-assisted dump is enabled # if no, fallback to kdump check if [[ -f $FADUMP_ENABLED_SYS_NODE ]]; then - rc=$(cat $FADUMP_ENABLED_SYS_NODE) - [[ $rc -eq 1 ]] && return 0 + [[ $(cat $FADUMP_ENABLED_SYS_NODE) -eq 1 ]] && return 0 fi return 1 } @@ -25,7 +24,7 @@ is_squash_available() { if [[ -z "$KDUMP_KERNELVER" ]]; then modprobe --dry-run $kmodule &>/dev/null || return 1 else - modprobe -S $KDUMP_KERNELVER --dry-run $kmodule &>/dev/null || return 1 + modprobe -S "$KDUMP_KERNELVER" --dry-run $kmodule &>/dev/null || return 1 fi done } @@ -65,7 +64,7 @@ to_dev_name() { dev=$(blkid -L "${dev#LABEL=}") ;; esac - echo $dev + echo "$dev" }
is_user_configured_dump_target() @@ -78,10 +77,10 @@ get_user_configured_dump_disk() local _target
_target=$(kdump_get_conf_val "ext[234]|xfs|btrfs|minix|raw") - [[ -n "$_target" ]] && echo $_target && return + [[ -n "$_target" ]] && echo "$_target" && return
_target=$(get_dracut_args_target "$(kdump_get_conf_val "dracut_args")") - [[ -b "$_target" ]] && echo $_target + [[ -b "$_target" ]] && echo "$_target" }
get_block_dump_target() @@ -93,12 +92,12 @@ get_block_dump_target() fi
_target=$(get_user_configured_dump_disk) - [[ -n "$_target" ]] && echo $(to_dev_name $_target) && return + [[ -n "$_target" ]] && to_dev_name "$_target" && return
# Get block device name from local save path _path=$(get_save_path) - _target=$(get_target_from_path $_path) - [[ -b "$_target" ]] && echo $(to_dev_name $_target) + _target=$(get_target_from_path "$_path") + [[ -b "$_target" ]] && to_dev_name "$_target" }
is_dump_to_rootfs() @@ -113,7 +112,7 @@ get_failure_action_target() if is_dump_to_rootfs; then # Get rootfs device name _target=$(get_root_fs_device) - [[ -b "$_target" ]] && echo $(to_dev_name $_target) && return + [[ -b "$_target" ]] && to_dev_name "$_target" && return # Then, must be nfs root echo "nfs" fi @@ -157,27 +156,29 @@ get_kdump_targets() # part is the bind mounted directory which quotes by bracket "[]". get_bind_mount_source() { - local _mnt=$(df $1 | tail -1 | awk '{print $NF}') - local _path=${1#$_mnt} + local _mnt _src _opt _fstype _path _src_nofsroot
- local _src=$(get_mount_info SOURCE target $_mnt -f) - local _opt=$(get_mount_info OPTIONS target $_mnt -f) - local _fstype=$(get_mount_info FSTYPE target $_mnt -f) + _mnt=$(df $1 | tail -1 | awk '{print $NF}') + _path=${1#$_mnt} + + _src=$(get_mount_info SOURCE target "$_mnt" -f) + _opt=$(get_mount_info OPTIONS target "$_mnt" -f) + _fstype=$(get_mount_info FSTYPE target "$_mnt" -f)
# bind mount in fstab if [[ -d "$_src" ]] && [[ "$_fstype" = none ]] && (echo "$_opt" | grep -q "\bbind\b"); then - echo $_src$_path && return + echo "$_src$_path" && return fi
# direct mount - local _src_nofsroot=$(get_mount_info SOURCE target $_mnt -v -f) - if [[ $_src_nofsroot = $_src ]]; then - echo $_mnt$_path && return + _src_nofsroot=$(get_mount_info SOURCE target "$_mnt" -v -f) + if [[ $_src_nofsroot = "$_src" ]]; then + echo "$_mnt$_path" && return fi
- local _fsroot=${_src#$_src_nofsroot[} + local _fsroot=${_src#${_src_nofsroot}[} _fsroot=${_fsroot%]} - _mnt=$(get_mount_info TARGET source $_src_nofsroot -f) + _mnt=$(get_mount_info TARGET source "$_src_nofsroot" -f)
# for btrfs, _fsroot will also contain the subvol value as well, strip it if [[ "$_fstype" = btrfs ]]; then @@ -186,19 +187,21 @@ get_bind_mount_source() _subvol=${_subvol%,*} _fsroot=${_fsroot#$_subvol} fi - echo $_mnt$_fsroot$_path + echo "$_mnt$_fsroot$_path" }
get_mntopt_from_target() { - get_mount_info OPTIONS source $1 -f + get_mount_info OPTIONS source "$1" -f }
# Get the path where the target will be mounted in kdump kernel # $1: kdump target device get_kdump_mntpoint_from_target() { - local _mntpoint=$(get_mntpoint_from_target $1) + local _mntpoint + + _mntpoint=$(get_mntpoint_from_target "$1")
# mount under /sysroot if dump to root disk or mount under # mount under /kdumproot if dump target is not mounted in first kernel @@ -229,7 +232,8 @@ kdump_get_persistent_dev() { dev=$(blkid -L "${dev#LABEL=}") ;; esac - echo $(get_persistent_dev "$dev") + + get_persistent_dev "$dev" }
is_atomic() @@ -248,26 +252,24 @@ get_remote_host() _config_val=${_config_val%:/*} _config_val=${_config_val#[} _config_val=${_config_val%]} - echo $_config_val + echo "$_config_val" }
is_hostname() { - local _hostname=$(echo $1 | grep ":") - - if [[ -n "$_hostname" ]]; then + if echo "$1" | grep -q ":"; then return 1 fi - echo $1 | grep -q "[a-zA-Z]" + echo "$1" | grep -q "[a-zA-Z]" }
# Copied from "/etc/sysconfig/network-scripts/network-functions" get_hwaddr() { if [[ -f "/sys/class/net/${1}/address" ]]; then - awk '{ print toupper($0) }' < /sys/class/net/${1}/address + awk '{ print toupper($0) }' < "/sys/class/net/$1/address" elif [[ -d "/sys/class/net/${1}" ]]; then - LC_ALL= LANG= ip -o link show ${1} 2>/dev/null | \ + LC_ALL="" LANG="" ip -o link show "$1" 2>/dev/null | \ awk '{ print toupper(gensub(/.*link/[^ ]* ([[:alnum:]:]*).*/, "\1", 1)); }' fi @@ -368,7 +370,7 @@ get_ifcfg_nmcli() # $1: netdev name get_ifcfg_legacy() { - local ifcfg_file + local ifcfg_file hwaddr
ifcfg_file="/etc/sysconfig/network-scripts/ifcfg-${1}" [[ -f "${ifcfg_file}" ]] && echo -n "${ifcfg_file}" && return @@ -376,7 +378,7 @@ get_ifcfg_legacy() ifcfg_file=$(get_ifcfg_by_name "${1}") [[ -f "${ifcfg_file}" ]] && echo -n "${ifcfg_file}" && return
- local hwaddr=$(get_hwaddr "${1}") + hwaddr=$(get_hwaddr "${1}") if [[ -n "$hwaddr" ]]; then ifcfg_file=$(get_ifcfg_by_hwaddr "${hwaddr}") [[ -f "${ifcfg_file}" ]] && echo -n "${ifcfg_file}" && return @@ -403,7 +405,7 @@ get_ifcfg_filename() { # returns 0 when omission of a module is desired in dracut_args # returns 1 otherwise is_dracut_mod_omitted() { - local dracut_args dracut_mod=$1 + local dracut_mod=$1
set -- $(kdump_get_conf_val dracut_args) while [[ $# -gt 0 ]]; do @@ -483,14 +485,14 @@ remove_cmdline_param() local cmdline=$1 shift
- for arg in $@; do - cmdline=`echo $cmdline | \ - sed -e "s/\b$arg=[^ ]*//g" \ - -e "s/^$arg\b//g" \ - -e "s/[[:space:]]$arg\b//g" \ - -e "s/\s+/ /g"` + for arg in "$@"; do + cmdline=$(echo "$cmdline" | \ + sed -e "s/\b$arg=[^ ]*//g" \ + -e "s/^$arg\b//g" \ + -e "s/[[:space:]]$arg\b//g" \ + -e "s/\s+/ /g") done - echo $cmdline + echo "$cmdline" }
# @@ -521,15 +523,14 @@ append_cmdline() cmdline="${cmdline} ${2}=${3}" fi
- echo $cmdline + echo "$cmdline" }
# This function check iomem and determines if we have more than # 4GB of ram available. Returns 1 if we do, 0 if we dont need_64bit_headers() { - return `tail -n 1 /proc/iomem | awk '{ split ($1, r, "-"); \ - print (strtonum("0x" r[2]) > strtonum("0xffffffff")); }'` + return "$(tail -n 1 /proc/iomem | awk '{ split ($1, r, "-"); print (strtonum("0x" r[2]) > strtonum("0xffffffff")); }')" }
# Check if secure boot is being enforced. @@ -558,12 +559,12 @@ is_secure_boot_enforced() fi
# Detect secure boot on x86 and arm64 - secure_boot_file=$(find /sys/firmware/efi/efivars -name SecureBoot-* 2>/dev/null) - setup_mode_file=$(find /sys/firmware/efi/efivars -name SetupMode-* 2>/dev/null) + secure_boot_file=$(find /sys/firmware/efi/efivars -name "SecureBoot-*" 2>/dev/null) + setup_mode_file=$(find /sys/firmware/efi/efivars -name "SetupMode-*" 2>/dev/null)
if [[ -f "$secure_boot_file" ]] && [[ -f "$setup_mode_file" ]]; then - secure_boot_byte=$(hexdump -v -e '/1 "%d\ "' $secure_boot_file|cut -d' ' -f 5) - setup_mode_byte=$(hexdump -v -e '/1 "%d\ "' $setup_mode_file|cut -d' ' -f 5) + secure_boot_byte=$(hexdump -v -e '/1 "%d\ "' "$secure_boot_file" | cut -d' ' -f 5) + setup_mode_byte=$(hexdump -v -e '/1 "%d\ "' "$setup_mode_file" | cut -d' ' -f 5)
if [[ "$secure_boot_byte" = "1" ]] && [[ "$setup_mode_byte" = "0" ]]; then return 0 @@ -593,7 +594,7 @@ prepare_kexec_args() need_64bit_headers if [[ $? == 1 ]] then - found_elf_args=$(echo $kexec_args | grep elf32-core-headers) + found_elf_args=$(echo "$kexec_args" | grep elf32-core-headers) if [[ -n "$found_elf_args" ]] then dwarn "Warning: elf32-core-headers overrides correct elf64 setting" @@ -601,14 +602,14 @@ prepare_kexec_args() kexec_args="$kexec_args --elf64-core-headers" fi else - found_elf_args=$(echo $kexec_args | grep elf64-core-headers) + found_elf_args=$(echo "$kexec_args" | grep elf64-core-headers) if [[ -z "$found_elf_args" ]] then kexec_args="$kexec_args --elf32-core-headers" fi fi fi - echo $kexec_args + echo "$kexec_args" }
# @@ -620,19 +621,19 @@ prepare_kexec_args() # prepare_kdump_bootinfo() { - local boot_imglist boot_dirlist boot_initrdlist curr_kver="$(uname -r)" + local boot_img boot_imglist boot_dirlist boot_initrdlist local machine_id
if [[ -z "$KDUMP_KERNELVER" ]]; then KDUMP_KERNELVER="$(uname -r)" fi
- read machine_id < /etc/machine-id + read -r machine_id < /etc/machine-id boot_dirlist=${KDUMP_BOOTDIR:-"/boot /boot/efi /efi /"} boot_imglist="$KDUMP_IMG-$KDUMP_KERNELVER$KDUMP_IMG_EXT $machine_id/$KDUMP_KERNELVER/$KDUMP_IMG"
# Use BOOT_IMAGE as reference if possible, strip the GRUB root device prefix in (hd0,gpt1) format - local boot_img="$(cat /proc/cmdline | sed "s/^BOOT_IMAGE=((\S*))?(\S*) .*/\2/")" + boot_img="$(sed "s/^BOOT_IMAGE=((\S*))?(\S*) .*/\2/" /proc/cmdline)" if [[ -n "$boot_img" ]]; then boot_imglist="$boot_img $boot_imglist" fi @@ -640,7 +641,7 @@ prepare_kdump_bootinfo() for dir in $boot_dirlist; do for img in $boot_imglist; do if [[ -f "$dir/$img" ]]; then - KDUMP_KERNEL=$(echo $dir/$img | tr -s '/') + KDUMP_KERNEL=$(echo "$dir/$img" | tr -s '/') break 2 fi done @@ -652,7 +653,7 @@ prepare_kdump_bootinfo() fi
# Set KDUMP_BOOTDIR to where kernel image is stored - KDUMP_BOOTDIR=$(dirname $KDUMP_KERNEL) + KDUMP_BOOTDIR=$(dirname "$KDUMP_KERNEL")
# Default initrd should just stay aside of kernel image, try to find it in KDUMP_BOOTDIR boot_initrdlist="initramfs-$KDUMP_KERNELVER.img initrd" @@ -693,7 +694,7 @@ get_watchdog_drvs() # device/modalias will return driver of this device [[ -f "$_dir/device/modalias" ]] || continue _drv=$(< "$_dir/device/modalias") - _drv=$(modprobe --set-version "$KDUMP_KERNELVER" -R $_drv 2>/dev/null) + _drv=$(modprobe --set-version "$KDUMP_KERNELVER" -R "$_drv" 2>/dev/null) for i in $_drv; do if ! [[ " $_wdtdrvs " == *" $i "* ]]; then _wdtdrvs="$_wdtdrvs $i" @@ -701,7 +702,7 @@ get_watchdog_drvs() done done
- echo $_wdtdrvs + echo "$_wdtdrvs" }
# @@ -742,8 +743,8 @@ prepare_cmdline() cmdline="${cmdline} $3"
id=$(get_bootcpu_apicid) - if [[ ! -z ${id} ]] ; then - cmdline=$(append_cmdline "${cmdline}" disable_cpu_apicid ${id}) + if [[ -n ${id} ]] ; then + cmdline=$(append_cmdline "${cmdline}" disable_cpu_apicid "${id}") fi
# If any watchdog is used, set it's pretimeout to 0. pretimeout let @@ -765,18 +766,18 @@ prepare_cmdline() cmdline=$(remove_cmdline_param "$cmdline" trace_buf_size trace_event) cmdline="${cmdline} trace_buf_size=1"
- echo ${cmdline} + echo "${cmdline}" }
#get system memory size in the unit of GB get_system_size() { - result=$(cat /proc/iomem | grep "System RAM" | awk -F ":" '{ print $1 }' | tr [:lower:] [:upper:] | paste -sd+) + result=$(grep "System RAM" /proc/iomem | awk -F ":" '{ print $1 }' | tr "[:lower:]" "[:upper:]" | paste -sd+) result="+$result" # replace '-' with '+0x' and '+' with '-0x' sum=$(echo "$result" | sed -e 's/-/K0x/g' -e 's/+/-0x/g' -e 's/K/+/g') - size=$(printf "%d\n" $(($sum))) - let size=$size/1024/1024/1024 + size=$(printf "%d\n" $((sum))) + size=$((size/1024/1024/1024))
echo $size } @@ -787,9 +788,6 @@ get_recommend_size() local _ck_cmdline=$2 local OLDIFS="$IFS"
- last_sz="" - last_unit="" - start=${_ck_cmdline: :1} if [[ $mem_size -lt $start ]]; then echo "0M" @@ -797,15 +795,15 @@ get_recommend_size() fi IFS=',' for i in $_ck_cmdline; do - end=$(echo $i | awk -F "-" '{ print $2 }' | awk -F ":" '{ print $1 }') - recommend=$(echo $i | awk -F "-" '{ print $2 }' | awk -F ":" '{ print $2 }') + end=$(echo "$i" | awk -F "-" '{ print $2 }' | awk -F ":" '{ print $1 }') + recommend=$(echo "$i" | awk -F "-" '{ print $2 }' | awk -F ":" '{ print $2 }') size=${end: : -1} unit=${end: -1} if [[ $unit == 'T' ]]; then - let size=$size*1024 + size=$((size*1024)) fi if [[ $mem_size -lt $size ]]; then - echo $recommend + echo "$recommend" IFS="$OLDIFS" return fi @@ -844,7 +842,7 @@ kdump_get_arch_recommend_size() fi fi
- ck_cmdline=$(echo $ck_cmdline | sed -e 's/-:/-102400T:/g') + ck_cmdline=$(echo "$ck_cmdline" | sed -e 's/-:/-102400T:/g') sys_mem=$(get_system_size)
get_recommend_size "$sys_mem" "$ck_cmdline" @@ -855,12 +853,13 @@ kdump_get_arch_recommend_size() # $1: the block device to be checked in maj:min format get_luks_crypt_dev() { + local _type [[ -b /dev/block/$1 ]] || return 1
- local _type=$(eval "$(blkid -u filesystem,crypto -o export -- /dev/block/$1); echo $TYPE") - [[ $_type == "crypto_LUKS" ]] && echo $1 + _type=$(eval "$(blkid -u filesystem,crypto -o export -- "/dev/block/$1"); echo $TYPE") + [[ $_type == "crypto_LUKS" ]] && echo "$1"
- for _x in /sys/dev/block/$1/slaves/*; do + for _x in "/sys/dev/block/$1/slaves/"*; do [[ -f $_x/dev ]] || continue [[ $_x/subsystem -ef /sys/class/block ]] || continue get_luks_crypt_dev "$(< "$_x/dev")" @@ -883,24 +882,24 @@ get_all_kdump_crypt_dev() local _dev _crypt
for _dev in $(get_block_dump_target); do - _crypt=$(get_luks_crypt_dev $(kdump_get_maj_min "$_dev")) - [[ -n "$_crypt" ]] && echo $_crypt + _crypt=$(get_luks_crypt_dev "$(kdump_get_maj_min "$_dev")") + [[ -n "$_crypt" ]] && echo "$_crypt" done }
check_vmlinux() { # Use readelf to check if it's a valid ELF - readelf -h $1 &>/dev/null || return 1 + readelf -h "$1" &>/dev/null || return 1 }
get_vmlinux_size() { local size=0
- while read _type _offset _virtaddr _physaddr _fsize _msize _flg _aln; do - size=$(( $size + $_msize )) - done <<< $(readelf -l -W $1 | grep "^ LOAD" 2>/dev/stderr) + while read -r _type _offset _virtaddr _physaddr _fsize _msize _flg _aln; do + size=$(( size + _msize )) + done <<< "$(readelf -l -W "$1" | grep "^ LOAD" 2>/dev/stderr)"
echo $size } @@ -913,14 +912,14 @@ try_decompress() # Try to find the header ($1) and decompress from here for pos in $(tr "$1\n$2" "\n$2=" < "$4" | grep -abo "^$2") do - if ! type -P $3 > /dev/null; then + if ! type -P "$3" > /dev/null; then ddebug "Signiature detected but '$3' is missing, skip this decompressor" break fi
pos=${pos%%:*} - tail -c+$pos "$img" | $3 > $5 2> /dev/null - if check_vmlinux $5; then + tail -c+$pos "$img" | $3 > "$5" 2> /dev/null + if check_vmlinux "$5"; then ddebug "Kernel is extracted with '$3'" return 0 fi @@ -933,28 +932,30 @@ try_decompress() get_kernel_size() { # Prepare temp files: - local img=$1 tmp=$(mktemp /tmp/vmlinux-XXX) - trap "rm -f $tmp" 0 + local img=$1 tmp + + tmp=$(mktemp /tmp/vmlinux-XXX) + trap 'rm -f $tmp' 0
# Try to check if it's a vmlinux already - check_vmlinux $img && get_vmlinux_size $img && return 0 + check_vmlinux "$img" && get_vmlinux_size "$img" && return 0
# That didn't work, so retry after decompression. - try_decompress '\037\213\010' xy gunzip $img $tmp || \ - try_decompress '\3757zXZ\000' abcde unxz $img $tmp || \ - try_decompress 'BZh' xy bunzip2 $img $tmp || \ - try_decompress '\135\0\0\0' xxx unlzma $img $tmp || \ - try_decompress '\211\114\132' xy 'lzop -d' $img $tmp || \ - try_decompress '\002!L\030' xxx 'lz4 -d' $img $tmp || \ - try_decompress '(\265/\375' xxx unzstd $img $tmp + try_decompress '\037\213\010' xy gunzip "$img" "$tmp" || \ + try_decompress '\3757zXZ\000' abcde unxz "$img" "$tmp" || \ + try_decompress 'BZh' xy bunzip2 "$img" "$tmp" || \ + try_decompress '\135\0\0\0' xxx unlzma "$img" "$tmp" || \ + try_decompress '\211\114\132' xy 'lzop -d' "$img" "$tmp" || \ + try_decompress '\002!L\030' xxx 'lz4 -d' "$img" "$tmp" || \ + try_decompress '(\265/\375' xxx unzstd "$img" "$tmp"
# Finally check for uncompressed images or objects: - [[ $? -eq 0 ]] && get_vmlinux_size $tmp && return 0 + [[ $? -eq 0 ]] && get_vmlinux_size "$tmp" && return 0
# Fallback to use iomem local _size=0 - for _seg in $(cat /proc/iomem | grep -E "Kernel (code|rodata|data|bss)" | cut -d ":" -f 1); do - _size=$(( $_size + 0x${_seg#*-} - 0x${_seg%-*} )) - done + while read -r _seg; do + _size=$(( _size + 0x${_seg#*-} - 0x${_seg%-*} )) + done <<< "$(grep -E "Kernel (code|rodata|data|bss)" /proc/iomem | cut -d ":" -f 1)" echo $_size }
This is done with shfmt -s -w kdump-lib.sh, no code behaviour change.
Signed-off-by: Kairui Song kasong@redhat.com --- kdump-lib.sh | 1129 +++++++++++++++++++++++++------------------------- 1 file changed, 566 insertions(+), 563 deletions(-)
diff --git a/kdump-lib.sh b/kdump-lib.sh index b89bb294..48c649ab 100755 --- a/kdump-lib.sh +++ b/kdump-lib.sh @@ -11,135 +11,138 @@ FADUMP_ENABLED_SYS_NODE="/sys/kernel/fadump_enabled"
is_fadump_capable() { - # Check if firmware-assisted dump is enabled - # if no, fallback to kdump check - if [[ -f $FADUMP_ENABLED_SYS_NODE ]]; then - [[ $(cat $FADUMP_ENABLED_SYS_NODE) -eq 1 ]] && return 0 - fi - return 1 + # Check if firmware-assisted dump is enabled + # if no, fallback to kdump check + if [[ -f $FADUMP_ENABLED_SYS_NODE ]]; then + [[ $(cat $FADUMP_ENABLED_SYS_NODE) -eq 1 ]] && return 0 + fi + return 1 }
-is_squash_available() { - for kmodule in squashfs overlay loop; do - if [[ -z "$KDUMP_KERNELVER" ]]; then - modprobe --dry-run $kmodule &>/dev/null || return 1 - else - modprobe -S "$KDUMP_KERNELVER" --dry-run $kmodule &>/dev/null || return 1 - fi - done +is_squash_available() +{ + for kmodule in squashfs overlay loop; do + if [[ -z $KDUMP_KERNELVER ]]; then + modprobe --dry-run $kmodule &> /dev/null || return 1 + else + modprobe -S "$KDUMP_KERNELVER" --dry-run $kmodule &> /dev/null || return 1 + fi + done }
-perror_exit() { - derror "$@" - exit 1 +perror_exit() +{ + derror "$@" + exit 1 }
# Check if fence kdump is configured in Pacemaker cluster is_pcs_fence_kdump() { - # no pcs or fence_kdump_send executables installed? - type -P pcs > /dev/null || return 1 - [[ -x $FENCE_KDUMP_SEND ]] || return 1 + # no pcs or fence_kdump_send executables installed? + type -P pcs > /dev/null || return 1 + [[ -x $FENCE_KDUMP_SEND ]] || return 1
- # fence kdump not configured? - (pcs cluster cib | grep 'type="fence_kdump"') &> /dev/null || return 1 + # fence kdump not configured? + (pcs cluster cib | grep 'type="fence_kdump"') &> /dev/null || return 1 }
# Check if fence_kdump is configured using kdump options is_generic_fence_kdump() { - [[ -x $FENCE_KDUMP_SEND ]] || return 1 + [[ -x $FENCE_KDUMP_SEND ]] || return 1
- [[ $(kdump_get_conf_val fence_kdump_nodes) ]] + [[ $(kdump_get_conf_val fence_kdump_nodes) ]] }
-to_dev_name() { - local dev="${1//"/}" +to_dev_name() +{ + local dev="${1//"/}"
- case "$dev" in - UUID=*) - dev=$(blkid -U "${dev#UUID=}") - ;; - LABEL=*) - dev=$(blkid -L "${dev#LABEL=}") - ;; - esac - echo "$dev" + case "$dev" in + UUID=*) + dev=$(blkid -U "${dev#UUID=}") + ;; + LABEL=*) + dev=$(blkid -L "${dev#LABEL=}") + ;; + esac + echo "$dev" }
is_user_configured_dump_target() { - [[ $(kdump_get_conf_val "ext[234]|xfs|btrfs|minix|raw|nfs|ssh") ]] || is_mount_in_dracut_args + [[ $(kdump_get_conf_val "ext[234]|xfs|btrfs|minix|raw|nfs|ssh") ]] || is_mount_in_dracut_args }
get_user_configured_dump_disk() { - local _target + local _target
- _target=$(kdump_get_conf_val "ext[234]|xfs|btrfs|minix|raw") - [[ -n "$_target" ]] && echo "$_target" && return + _target=$(kdump_get_conf_val "ext[234]|xfs|btrfs|minix|raw") + [[ -n $_target ]] && echo "$_target" && return
- _target=$(get_dracut_args_target "$(kdump_get_conf_val "dracut_args")") - [[ -b "$_target" ]] && echo "$_target" + _target=$(get_dracut_args_target "$(kdump_get_conf_val "dracut_args")") + [[ -b $_target ]] && echo "$_target" }
get_block_dump_target() { - local _target _path + local _target _path
- if is_ssh_dump_target || is_nfs_dump_target; then - return - fi + if is_ssh_dump_target || is_nfs_dump_target; then + return + fi
- _target=$(get_user_configured_dump_disk) - [[ -n "$_target" ]] && to_dev_name "$_target" && return + _target=$(get_user_configured_dump_disk) + [[ -n $_target ]] && to_dev_name "$_target" && return
- # Get block device name from local save path - _path=$(get_save_path) - _target=$(get_target_from_path "$_path") - [[ -b "$_target" ]] && to_dev_name "$_target" + # Get block device name from local save path + _path=$(get_save_path) + _target=$(get_target_from_path "$_path") + [[ -b $_target ]] && to_dev_name "$_target" }
is_dump_to_rootfs() { - [[ $(kdump_get_conf_val "failure_action|default") == dump_to_rootfs ]] + [[ $(kdump_get_conf_val "failure_action|default") == dump_to_rootfs ]] }
get_failure_action_target() { - local _target + local _target
- if is_dump_to_rootfs; then - # Get rootfs device name - _target=$(get_root_fs_device) - [[ -b "$_target" ]] && to_dev_name "$_target" && return - # Then, must be nfs root - echo "nfs" - fi + if is_dump_to_rootfs; then + # Get rootfs device name + _target=$(get_root_fs_device) + [[ -b $_target ]] && to_dev_name "$_target" && return + # Then, must be nfs root + echo "nfs" + fi }
# Get kdump targets(including root in case of dump_to_rootfs). get_kdump_targets() { - local _target _root - local kdump_targets + local _target _root + local kdump_targets
- _target=$(get_block_dump_target) - if [[ -n "$_target" ]]; then - kdump_targets=$_target - elif is_ssh_dump_target; then - kdump_targets="ssh" - else - kdump_targets="nfs" - fi + _target=$(get_block_dump_target) + if [[ -n $_target ]]; then + kdump_targets=$_target + elif is_ssh_dump_target; then + kdump_targets="ssh" + else + kdump_targets="nfs" + fi
- # Add the root device if dump_to_rootfs is specified. - _root=$(get_failure_action_target) - if [[ -n "$_root" ]] && [[ "$kdump_targets" != "$_root" ]]; then - kdump_targets="$kdump_targets $_root" - fi + # Add the root device if dump_to_rootfs is specified. + _root=$(get_failure_action_target) + if [[ -n $_root ]] && [[ $kdump_targets != "$_root" ]]; then + kdump_targets="$kdump_targets $_root" + fi
- echo "$kdump_targets" + echo "$kdump_targets" }
# Return the bind mount source path, return the path itself if it's not bind mounted @@ -156,126 +159,126 @@ get_kdump_targets() # part is the bind mounted directory which quotes by bracket "[]". get_bind_mount_source() { - local _mnt _src _opt _fstype _path _src_nofsroot + local _mnt _src _opt _fstype _path _src_nofsroot
- _mnt=$(df $1 | tail -1 | awk '{print $NF}') - _path=${1#$_mnt} + _mnt=$(df $1 | tail -1 | awk '{print $NF}') + _path=${1#$_mnt}
- _src=$(get_mount_info SOURCE target "$_mnt" -f) - _opt=$(get_mount_info OPTIONS target "$_mnt" -f) - _fstype=$(get_mount_info FSTYPE target "$_mnt" -f) + _src=$(get_mount_info SOURCE target "$_mnt" -f) + _opt=$(get_mount_info OPTIONS target "$_mnt" -f) + _fstype=$(get_mount_info FSTYPE target "$_mnt" -f)
- # bind mount in fstab - if [[ -d "$_src" ]] && [[ "$_fstype" = none ]] && (echo "$_opt" | grep -q "\bbind\b"); then - echo "$_src$_path" && return - fi + # bind mount in fstab + if [[ -d $_src ]] && [[ $_fstype == none ]] && (echo "$_opt" | grep -q "\bbind\b"); then + echo "$_src$_path" && return + fi
- # direct mount - _src_nofsroot=$(get_mount_info SOURCE target "$_mnt" -v -f) - if [[ $_src_nofsroot = "$_src" ]]; then - echo "$_mnt$_path" && return - fi + # direct mount + _src_nofsroot=$(get_mount_info SOURCE target "$_mnt" -v -f) + if [[ $_src_nofsroot == "$_src" ]]; then + echo "$_mnt$_path" && return + fi
- local _fsroot=${_src#${_src_nofsroot}[} - _fsroot=${_fsroot%]} - _mnt=$(get_mount_info TARGET source "$_src_nofsroot" -f) + local _fsroot=${_src#${_src_nofsroot}[} + _fsroot=${_fsroot%]} + _mnt=$(get_mount_info TARGET source "$_src_nofsroot" -f)
- # for btrfs, _fsroot will also contain the subvol value as well, strip it - if [[ "$_fstype" = btrfs ]]; then - local _subvol - _subvol=${_opt#*subvol=} - _subvol=${_subvol%,*} - _fsroot=${_fsroot#$_subvol} - fi - echo "$_mnt$_fsroot$_path" + # for btrfs, _fsroot will also contain the subvol value as well, strip it + if [[ $_fstype == btrfs ]]; then + local _subvol + _subvol=${_opt#*subvol=} + _subvol=${_subvol%,*} + _fsroot=${_fsroot#$_subvol} + fi + echo "$_mnt$_fsroot$_path" }
get_mntopt_from_target() { - get_mount_info OPTIONS source "$1" -f + get_mount_info OPTIONS source "$1" -f }
# Get the path where the target will be mounted in kdump kernel # $1: kdump target device get_kdump_mntpoint_from_target() { - local _mntpoint + local _mntpoint
- _mntpoint=$(get_mntpoint_from_target "$1") + _mntpoint=$(get_mntpoint_from_target "$1")
- # mount under /sysroot if dump to root disk or mount under - # mount under /kdumproot if dump target is not mounted in first kernel - # mount under /kdumproot/$_mntpoint in other cases in 2nd kernel. - # systemd will be in charge to umount it. - if [[ -z "$_mntpoint" ]];then - _mntpoint="/kdumproot" - else - if [[ "$_mntpoint" = "/" ]];then - _mntpoint="/sysroot" - else - _mntpoint="/kdumproot/$_mntpoint" - fi - fi + # mount under /sysroot if dump to root disk or mount under + # mount under /kdumproot if dump target is not mounted in first kernel + # mount under /kdumproot/$_mntpoint in other cases in 2nd kernel. + # systemd will be in charge to umount it. + if [[ -z $_mntpoint ]]; then + _mntpoint="/kdumproot" + else + if [[ $_mntpoint == "/" ]]; then + _mntpoint="/sysroot" + else + _mntpoint="/kdumproot/$_mntpoint" + fi + fi
- # strip duplicated "/" - echo $_mntpoint | tr -s "/" + # strip duplicated "/" + echo $_mntpoint | tr -s "/" }
-kdump_get_persistent_dev() { - local dev="${1//"/}" +kdump_get_persistent_dev() +{ + local dev="${1//"/}"
- case "$dev" in - UUID=*) - dev=$(blkid -U "${dev#UUID=}") - ;; - LABEL=*) - dev=$(blkid -L "${dev#LABEL=}") - ;; - esac + case "$dev" in + UUID=*) + dev=$(blkid -U "${dev#UUID=}") + ;; + LABEL=*) + dev=$(blkid -L "${dev#LABEL=}") + ;; + esac
- get_persistent_dev "$dev" + get_persistent_dev "$dev" }
is_atomic() { - grep -q "ostree" /proc/cmdline + grep -q "ostree" /proc/cmdline }
# get ip address or hostname from nfs/ssh config value get_remote_host() { - local _config_val=$1 + local _config_val=$1
- # ipv6 address in kdump.conf is around with "[]", - # factor out the ipv6 address - _config_val=${_config_val#*@} - _config_val=${_config_val%:/*} - _config_val=${_config_val#[} - _config_val=${_config_val%]} - echo "$_config_val" + # ipv6 address in kdump.conf is around with "[]", + # factor out the ipv6 address + _config_val=${_config_val#*@} + _config_val=${_config_val%:/*} + _config_val=${_config_val#[} + _config_val=${_config_val%]} + echo "$_config_val" }
is_hostname() { - if echo "$1" | grep -q ":"; then - return 1 - fi - echo "$1" | grep -q "[a-zA-Z]" + if echo "$1" | grep -q ":"; then + return 1 + fi + echo "$1" | grep -q "[a-zA-Z]" }
# Copied from "/etc/sysconfig/network-scripts/network-functions" get_hwaddr() { - if [[ -f "/sys/class/net/${1}/address" ]]; then - awk '{ print toupper($0) }' < "/sys/class/net/$1/address" - elif [[ -d "/sys/class/net/${1}" ]]; then - LC_ALL="" LANG="" ip -o link show "$1" 2>/dev/null | \ - awk '{ print toupper(gensub(/.*link/[^ ]* ([[:alnum:]:]*).*/, + if [[ -f "/sys/class/net/${1}/address" ]]; then + awk '{ print toupper($0) }' < "/sys/class/net/$1/address" + elif [[ -d "/sys/class/net/${1}" ]]; then + LC_ALL="" LANG="" ip -o link show "$1" 2> /dev/null | + awk '{ print toupper(gensub(/.*link/[^ ]* ([[:alnum:]:]*).*/, "\1", 1)); }' - fi + fi }
- # Get value by a field using "nmcli -g" # Usage: get_nmcli_value_by_field <field> <nmcli command> # @@ -288,16 +291,16 @@ get_hwaddr() # bond.options "mode=balance-rr" get_nmcli_value_by_field() { - LANG=C nmcli --get-values "$@" + LANG=C nmcli --get-values "$@" }
# Get nmcli field value of an connection apath (a D-Bus active connection path) # Usage: get_nmcli_field_by_apath <field> <apath> get_nmcli_field_by_conpath() { - local _field=$1 _apath=$2 + local _field=$1 _apath=$2
- get_nmcli_value_by_field "$_field" connection show "$_apath" + get_nmcli_value_by_field "$_field" connection show "$_apath" }
# Get nmcli connection apath (a D-Bus active connection path ) by ifname @@ -306,129 +309,133 @@ get_nmcli_field_by_conpath() # $ nmcli connection show $apath get_nmcli_connection_apath_by_ifname() { - local _ifname=$1 + local _ifname=$1
- get_nmcli_value_by_field "GENERAL.CON-PATH" device show "$_ifname" + get_nmcli_value_by_field "GENERAL.CON-PATH" device show "$_ifname" }
get_ifcfg_by_device() { - grep -E -i -l "^[[:space:]]*DEVICE="*${1}"*[[:space:]]*$" \ - /etc/sysconfig/network-scripts/ifcfg-* 2>/dev/null | head -1 + grep -E -i -l "^[[:space:]]*DEVICE="*${1}"*[[:space:]]*$" \ + /etc/sysconfig/network-scripts/ifcfg-* 2> /dev/null | head -1 }
get_ifcfg_by_hwaddr() { - grep -E -i -l "^[[:space:]]*HWADDR="*${1}"*[[:space:]]*$" \ - /etc/sysconfig/network-scripts/ifcfg-* 2>/dev/null | head -1 + grep -E -i -l "^[[:space:]]*HWADDR="*${1}"*[[:space:]]*$" \ + /etc/sysconfig/network-scripts/ifcfg-* 2> /dev/null | head -1 }
get_ifcfg_by_uuid() { - grep -E -i -l "^[[:space:]]*UUID="*${1}"*[[:space:]]*$" \ - /etc/sysconfig/network-scripts/ifcfg-* 2>/dev/null | head -1 + grep -E -i -l "^[[:space:]]*UUID="*${1}"*[[:space:]]*$" \ + /etc/sysconfig/network-scripts/ifcfg-* 2> /dev/null | head -1 }
get_ifcfg_by_name() { - grep -E -i -l "^[[:space:]]*NAME="*${1}"*[[:space:]]*$" \ - /etc/sysconfig/network-scripts/ifcfg-* 2>/dev/null | head -1 + grep -E -i -l "^[[:space:]]*NAME="*${1}"*[[:space:]]*$" \ + /etc/sysconfig/network-scripts/ifcfg-* 2> /dev/null | head -1 }
is_nm_running() { - [[ "$(LANG=C nmcli -t --fields running general status 2>/dev/null)" = "running" ]] + [[ "$(LANG=C nmcli -t --fields running general status 2> /dev/null)" == "running" ]] }
is_nm_handling() { - LANG=C nmcli -t --fields device,state dev status 2>/dev/null \ - | grep -q "^(${1}:connected)|(${1}:connecting.*)$" + LANG=C nmcli -t --fields device,state dev status 2> /dev/null | + grep -q "^(${1}:connected)|(${1}:connecting.*)$" }
# $1: netdev name get_ifcfg_nmcli() { - local nm_uuid nm_name - local ifcfg_file + local nm_uuid nm_name + local ifcfg_file
- # Get the active nmcli config name of $1 - if is_nm_running && is_nm_handling "${1}" ; then - # The configuration "uuid" and "name" generated by nm is wrote to - # the ifcfg file as "UUID=<nm_uuid>" and "NAME=<nm_name>". - nm_uuid=$(LANG=C nmcli -t --fields uuid,device c show --active 2>/dev/null \ - | grep "${1}" | head -1 | cut -d':' -f1) - nm_name=$(LANG=C nmcli -t --fields name,device c show --active 2>/dev/null \ - | grep "${1}" | head -1 | cut -d':' -f1) - ifcfg_file=$(get_ifcfg_by_uuid "${nm_uuid}") - [[ -z "${ifcfg_file}" ]] && ifcfg_file=$(get_ifcfg_by_name "${nm_name}") - fi + # Get the active nmcli config name of $1 + if is_nm_running && is_nm_handling "${1}"; then + # The configuration "uuid" and "name" generated by nm is wrote to + # the ifcfg file as "UUID=<nm_uuid>" and "NAME=<nm_name>". + nm_uuid=$(LANG=C nmcli -t --fields uuid,device c show --active 2> /dev/null | + grep "${1}" | head -1 | cut -d':' -f1) + nm_name=$(LANG=C nmcli -t --fields name,device c show --active 2> /dev/null | + grep "${1}" | head -1 | cut -d':' -f1) + ifcfg_file=$(get_ifcfg_by_uuid "${nm_uuid}") + [[ -z ${ifcfg_file} ]] && ifcfg_file=$(get_ifcfg_by_name "${nm_name}") + fi
- echo -n "${ifcfg_file}" + echo -n "${ifcfg_file}" }
# $1: netdev name get_ifcfg_legacy() { - local ifcfg_file hwaddr + local ifcfg_file hwaddr
- ifcfg_file="/etc/sysconfig/network-scripts/ifcfg-${1}" - [[ -f "${ifcfg_file}" ]] && echo -n "${ifcfg_file}" && return + ifcfg_file="/etc/sysconfig/network-scripts/ifcfg-${1}" + [[ -f ${ifcfg_file} ]] && echo -n "${ifcfg_file}" && return
- ifcfg_file=$(get_ifcfg_by_name "${1}") - [[ -f "${ifcfg_file}" ]] && echo -n "${ifcfg_file}" && return + ifcfg_file=$(get_ifcfg_by_name "${1}") + [[ -f ${ifcfg_file} ]] && echo -n "${ifcfg_file}" && return
- hwaddr=$(get_hwaddr "${1}") - if [[ -n "$hwaddr" ]]; then - ifcfg_file=$(get_ifcfg_by_hwaddr "${hwaddr}") - [[ -f "${ifcfg_file}" ]] && echo -n "${ifcfg_file}" && return - fi + hwaddr=$(get_hwaddr "${1}") + if [[ -n $hwaddr ]]; then + ifcfg_file=$(get_ifcfg_by_hwaddr "${hwaddr}") + [[ -f ${ifcfg_file} ]] && echo -n "${ifcfg_file}" && return + fi
- ifcfg_file=$(get_ifcfg_by_device "${1}") + ifcfg_file=$(get_ifcfg_by_device "${1}")
- echo -n "${ifcfg_file}" + echo -n "${ifcfg_file}" }
# $1: netdev name # Return the ifcfg file whole name(including the path) of $1 if any. -get_ifcfg_filename() { - local ifcfg_file +get_ifcfg_filename() +{ + local ifcfg_file
- ifcfg_file=$(get_ifcfg_nmcli "${1}") - if [[ -z "${ifcfg_file}" ]]; then - ifcfg_file=$(get_ifcfg_legacy "${1}") - fi + ifcfg_file=$(get_ifcfg_nmcli "${1}") + if [[ -z ${ifcfg_file} ]]; then + ifcfg_file=$(get_ifcfg_legacy "${1}") + fi
- echo -n "${ifcfg_file}" + echo -n "${ifcfg_file}" }
# returns 0 when omission of a module is desired in dracut_args # returns 1 otherwise -is_dracut_mod_omitted() { - local dracut_mod=$1 +is_dracut_mod_omitted() +{ + local dracut_mod=$1
- set -- $(kdump_get_conf_val dracut_args) - while [[ $# -gt 0 ]]; do - case $1 in - -o|--omit) - [[ " ${2//[^[:alnum:]]/ } " == *" $dracut_mod "* ]] && return 0 - esac - shift - done + set -- $(kdump_get_conf_val dracut_args) + while [[ $# -gt 0 ]]; do + case $1 in + -o | --omit) + [[ " ${2//[^[:alnum:]]/ } " == *" $dracut_mod "* ]] && return 0 + ;; + esac + shift + done
- return 1 + return 1 }
-is_wdt_active() { - local active +is_wdt_active() +{ + local active
- [[ -d /sys/class/watchdog ]] || return 1 - for dir in /sys/class/watchdog/*; do - [[ -f "$dir/state" ]] || continue - active=$(< "$dir/state") - [[ "$active" = "active" ]] && return 0 - done - return 1 + [[ -d /sys/class/watchdog ]] || return 1 + for dir in /sys/class/watchdog/*; do + [[ -f "$dir/state" ]] || continue + active=$(< "$dir/state") + [[ $active == "active" ]] && return 0 + done + return 1 }
# If "dracut_args" contains "--mount" information, use it @@ -436,45 +443,45 @@ is_wdt_active() { # its correctness). is_mount_in_dracut_args() { - [[ $(kdump_get_conf_val dracut_args) == *" --mount "* ]] + [[ $(kdump_get_conf_val dracut_args) == *" --mount "* ]] }
check_crash_mem_reserved() { - local mem_reserved + local mem_reserved
- mem_reserved=$(cat /sys/kernel/kexec_crash_size) - if [[ $mem_reserved -eq 0 ]]; then - derror "No memory reserved for crash kernel" - return 1 - fi + mem_reserved=$(cat /sys/kernel/kexec_crash_size) + if [[ $mem_reserved -eq 0 ]]; then + derror "No memory reserved for crash kernel" + return 1 + fi
- return 0 + return 0 }
check_kdump_feasibility() { - if [[ ! -e /sys/kernel/kexec_crash_loaded ]]; then - derror "Kdump is not supported on this kernel" - return 1 - fi - check_crash_mem_reserved - return $? + if [[ ! -e /sys/kernel/kexec_crash_loaded ]]; then + derror "Kdump is not supported on this kernel" + return 1 + fi + check_crash_mem_reserved + return $? }
check_current_kdump_status() { - if [[ ! -f /sys/kernel/kexec_crash_loaded ]];then - derror "Perhaps CONFIG_CRASH_DUMP is not enabled in kernel" - return 1 - fi + if [[ ! -f /sys/kernel/kexec_crash_loaded ]]; then + derror "Perhaps CONFIG_CRASH_DUMP is not enabled in kernel" + return 1 + fi
- rc=$(cat /sys/kernel/kexec_crash_loaded) - if [[ $rc == 1 ]]; then - return 0 - else - return 1 - fi + rc=$(cat /sys/kernel/kexec_crash_loaded) + if [[ $rc == 1 ]]; then + return 0 + else + return 1 + fi }
# remove_cmdline_param <kernel cmdline> <param1> [<param2>] ... [<paramN>] @@ -482,17 +489,17 @@ check_current_kdump_status() # For each "arg" in the removing params list, "arg" and "arg=xxx" will be removed if exists. remove_cmdline_param() { - local cmdline=$1 - shift + local cmdline=$1 + shift
- for arg in "$@"; do - cmdline=$(echo "$cmdline" | \ - sed -e "s/\b$arg=[^ ]*//g" \ - -e "s/^$arg\b//g" \ - -e "s/[[:space:]]$arg\b//g" \ - -e "s/\s+/ /g") - done - echo "$cmdline" + for arg in "$@"; do + cmdline=$(echo "$cmdline" | + sed -e "s/\b$arg=[^ ]*//g" \ + -e "s/^$arg\b//g" \ + -e "s/[[:space:]]$arg\b//g" \ + -e "s/\s+/ /g") + done + echo "$cmdline" }
# @@ -501,12 +508,12 @@ remove_cmdline_param() # get_bootcpu_apicid() { - awk ' \ + awk ' \ BEGIN { CPU = "-1"; } \ $1=="processor" && $2==":" { CPU = $NF; } \ CPU=="0" && /^apicid/ { print $NF; } \ - ' \ - /proc/cpuinfo + ' \ + /proc/cpuinfo }
# @@ -515,22 +522,22 @@ get_bootcpu_apicid() # append_cmdline() { - local cmdline=$1 - local newstr=${cmdline/$2/""} + local cmdline=$1 + local newstr=${cmdline/$2/""}
- # unchanged str implies argument wasn't there - if [[ "$cmdline" == "$newstr" ]]; then - cmdline="${cmdline} ${2}=${3}" - fi + # unchanged str implies argument wasn't there + if [[ $cmdline == "$newstr" ]]; then + cmdline="${cmdline} ${2}=${3}" + fi
- echo "$cmdline" + echo "$cmdline" }
# This function check iomem and determines if we have more than # 4GB of ram available. Returns 1 if we do, 0 if we dont need_64bit_headers() { - return "$(tail -n 1 /proc/iomem | awk '{ split ($1, r, "-"); print (strtonum("0x" r[2]) > strtonum("0xffffffff")); }')" + return "$(tail -n 1 /proc/iomem | awk '{ split ($1, r, "-"); print (strtonum("0x" r[2]) > strtonum("0xffffffff")); }')" }
# Check if secure boot is being enforced. @@ -544,39 +551,39 @@ need_64bit_headers() # Assume efivars is mounted at /sys/firmware/efi/efivars. is_secure_boot_enforced() { - local secure_boot_file setup_mode_file - local secure_boot_byte setup_mode_byte + local secure_boot_file setup_mode_file + local secure_boot_byte setup_mode_byte
- # On powerpc, secure boot is enforced if: - # host secure boot: /ibm,secure-boot/os-secureboot-enforcing DT property exists - # guest secure boot: /ibm,secure-boot >= 2 - if [[ -f /proc/device-tree/ibm,secureboot/os-secureboot-enforcing ]]; then + # On powerpc, secure boot is enforced if: + # host secure boot: /ibm,secure-boot/os-secureboot-enforcing DT property exists + # guest secure boot: /ibm,secure-boot >= 2 + if [[ -f /proc/device-tree/ibm,secureboot/os-secureboot-enforcing ]]; then return 0 - fi - if [[ -f /proc/device-tree/ibm,secure-boot ]] && \ - [[ $(lsprop /proc/device-tree/ibm,secure-boot | tail -1) -ge 2 ]]; then + fi + if [[ -f /proc/device-tree/ibm,secure-boot ]] && + [[ $(lsprop /proc/device-tree/ibm,secure-boot | tail -1) -ge 2 ]]; then return 0 - fi + fi
- # Detect secure boot on x86 and arm64 - secure_boot_file=$(find /sys/firmware/efi/efivars -name "SecureBoot-*" 2>/dev/null) - setup_mode_file=$(find /sys/firmware/efi/efivars -name "SetupMode-*" 2>/dev/null) + # Detect secure boot on x86 and arm64 + secure_boot_file=$(find /sys/firmware/efi/efivars -name "SecureBoot-*" 2> /dev/null) + setup_mode_file=$(find /sys/firmware/efi/efivars -name "SetupMode-*" 2> /dev/null)
- if [[ -f "$secure_boot_file" ]] && [[ -f "$setup_mode_file" ]]; then - secure_boot_byte=$(hexdump -v -e '/1 "%d\ "' "$secure_boot_file" | cut -d' ' -f 5) - setup_mode_byte=$(hexdump -v -e '/1 "%d\ "' "$setup_mode_file" | cut -d' ' -f 5) + if [[ -f $secure_boot_file ]] && [[ -f $setup_mode_file ]]; then + secure_boot_byte=$(hexdump -v -e '/1 "%d\ "' "$secure_boot_file" | cut -d' ' -f 5) + setup_mode_byte=$(hexdump -v -e '/1 "%d\ "' "$setup_mode_file" | cut -d' ' -f 5)
- if [[ "$secure_boot_byte" = "1" ]] && [[ "$setup_mode_byte" = "0" ]]; then - return 0 - fi - fi + if [[ $secure_boot_byte == "1" ]] && [[ $setup_mode_byte == "0" ]]; then + return 0 + fi + fi
- # Detect secure boot on s390x - if [[ -e "/sys/firmware/ipl/secure" && "$(cat /sys/firmware/ipl/secure)" == "1" ]]; then - return 0 - fi + # Detect secure boot on s390x + if [[ -e "/sys/firmware/ipl/secure" && "$(cat /sys/firmware/ipl/secure)" == "1" ]]; then + return 0 + fi
- return 1 + return 1 }
# @@ -585,31 +592,27 @@ is_secure_boot_enforced() # prepare_kexec_args() { - local kexec_args=$1 - local found_elf_args - - ARCH=$(uname -m) - if [[ "$ARCH" == "i686" ]] || [[ "$ARCH" == "i386" ]] - then - need_64bit_headers - if [[ $? == 1 ]] - then - found_elf_args=$(echo "$kexec_args" | grep elf32-core-headers) - if [[ -n "$found_elf_args" ]] - then - dwarn "Warning: elf32-core-headers overrides correct elf64 setting" - else - kexec_args="$kexec_args --elf64-core-headers" - fi - else - found_elf_args=$(echo "$kexec_args" | grep elf64-core-headers) - if [[ -z "$found_elf_args" ]] - then - kexec_args="$kexec_args --elf32-core-headers" - fi - fi - fi - echo "$kexec_args" + local kexec_args=$1 + local found_elf_args + + ARCH=$(uname -m) + if [[ $ARCH == "i686" ]] || [[ $ARCH == "i386" ]]; then + need_64bit_headers + if [[ $? == 1 ]]; then + found_elf_args=$(echo "$kexec_args" | grep elf32-core-headers) + if [[ -n $found_elf_args ]]; then + dwarn "Warning: elf32-core-headers overrides correct elf64 setting" + else + kexec_args="$kexec_args --elf64-core-headers" + fi + else + found_elf_args=$(echo "$kexec_args" | grep elf64-core-headers) + if [[ -z $found_elf_args ]]; then + kexec_args="$kexec_args --elf32-core-headers" + fi + fi + fi + echo "$kexec_args" }
# @@ -621,88 +624,88 @@ prepare_kexec_args() # prepare_kdump_bootinfo() { - local boot_img boot_imglist boot_dirlist boot_initrdlist - local machine_id - - if [[ -z "$KDUMP_KERNELVER" ]]; then - KDUMP_KERNELVER="$(uname -r)" - fi - - read -r machine_id < /etc/machine-id - boot_dirlist=${KDUMP_BOOTDIR:-"/boot /boot/efi /efi /"} - boot_imglist="$KDUMP_IMG-$KDUMP_KERNELVER$KDUMP_IMG_EXT $machine_id/$KDUMP_KERNELVER/$KDUMP_IMG" - - # Use BOOT_IMAGE as reference if possible, strip the GRUB root device prefix in (hd0,gpt1) format - boot_img="$(sed "s/^BOOT_IMAGE=((\S*))?(\S*) .*/\2/" /proc/cmdline)" - if [[ -n "$boot_img" ]]; then - boot_imglist="$boot_img $boot_imglist" - fi - - for dir in $boot_dirlist; do - for img in $boot_imglist; do - if [[ -f "$dir/$img" ]]; then - KDUMP_KERNEL=$(echo "$dir/$img" | tr -s '/') - break 2 - fi - done - done - - if ! [[ -e "$KDUMP_KERNEL" ]]; then - derror "Failed to detect kdump kernel location" - return 1 - fi - - # Set KDUMP_BOOTDIR to where kernel image is stored - KDUMP_BOOTDIR=$(dirname "$KDUMP_KERNEL") - - # Default initrd should just stay aside of kernel image, try to find it in KDUMP_BOOTDIR - boot_initrdlist="initramfs-$KDUMP_KERNELVER.img initrd" - for initrd in $boot_initrdlist; do - if [[ -f "$KDUMP_BOOTDIR/$initrd" ]]; then - defaut_initrd_base="$initrd" - DEFAULT_INITRD="$KDUMP_BOOTDIR/$defaut_initrd_base" - break - fi - done - - # Create kdump initrd basename from default initrd basename - # initramfs-5.7.9-200.fc32.x86_64.img => initramfs-5.7.9-200.fc32.x86_64kdump.img - # initrd => initrdkdump - if [[ -z "$defaut_initrd_base" ]]; then - kdump_initrd_base=initramfs-${KDUMP_KERNELVER}kdump.img - elif [[ $defaut_initrd_base == *.* ]]; then - kdump_initrd_base=${defaut_initrd_base%.*}kdump.${DEFAULT_INITRD##*.} - else - kdump_initrd_base=${defaut_initrd_base}kdump - fi - - # Place kdump initrd in $(/var/lib/kdump) if $(KDUMP_BOOTDIR) not writable - if [[ ! -w "$KDUMP_BOOTDIR" ]];then - var_target_initrd_dir="/var/lib/kdump" - mkdir -p "$var_target_initrd_dir" - KDUMP_INITRD="$var_target_initrd_dir/$kdump_initrd_base" - else - KDUMP_INITRD="$KDUMP_BOOTDIR/$kdump_initrd_base" - fi + local boot_img boot_imglist boot_dirlist boot_initrdlist + local machine_id + + if [[ -z $KDUMP_KERNELVER ]]; then + KDUMP_KERNELVER="$(uname -r)" + fi + + read -r machine_id < /etc/machine-id + boot_dirlist=${KDUMP_BOOTDIR:-"/boot /boot/efi /efi /"} + boot_imglist="$KDUMP_IMG-$KDUMP_KERNELVER$KDUMP_IMG_EXT $machine_id/$KDUMP_KERNELVER/$KDUMP_IMG" + + # Use BOOT_IMAGE as reference if possible, strip the GRUB root device prefix in (hd0,gpt1) format + boot_img="$(sed "s/^BOOT_IMAGE=((\S*))?(\S*) .*/\2/" /proc/cmdline)" + if [[ -n $boot_img ]]; then + boot_imglist="$boot_img $boot_imglist" + fi + + for dir in $boot_dirlist; do + for img in $boot_imglist; do + if [[ -f "$dir/$img" ]]; then + KDUMP_KERNEL=$(echo "$dir/$img" | tr -s '/') + break 2 + fi + done + done + + if ! [[ -e $KDUMP_KERNEL ]]; then + derror "Failed to detect kdump kernel location" + return 1 + fi + + # Set KDUMP_BOOTDIR to where kernel image is stored + KDUMP_BOOTDIR=$(dirname "$KDUMP_KERNEL") + + # Default initrd should just stay aside of kernel image, try to find it in KDUMP_BOOTDIR + boot_initrdlist="initramfs-$KDUMP_KERNELVER.img initrd" + for initrd in $boot_initrdlist; do + if [[ -f "$KDUMP_BOOTDIR/$initrd" ]]; then + defaut_initrd_base="$initrd" + DEFAULT_INITRD="$KDUMP_BOOTDIR/$defaut_initrd_base" + break + fi + done + + # Create kdump initrd basename from default initrd basename + # initramfs-5.7.9-200.fc32.x86_64.img => initramfs-5.7.9-200.fc32.x86_64kdump.img + # initrd => initrdkdump + if [[ -z $defaut_initrd_base ]]; then + kdump_initrd_base=initramfs-${KDUMP_KERNELVER}kdump.img + elif [[ $defaut_initrd_base == *.* ]]; then + kdump_initrd_base=${defaut_initrd_base%.*}kdump.${DEFAULT_INITRD##*.} + else + kdump_initrd_base=${defaut_initrd_base}kdump + fi + + # Place kdump initrd in $(/var/lib/kdump) if $(KDUMP_BOOTDIR) not writable + if [[ ! -w $KDUMP_BOOTDIR ]]; then + var_target_initrd_dir="/var/lib/kdump" + mkdir -p "$var_target_initrd_dir" + KDUMP_INITRD="$var_target_initrd_dir/$kdump_initrd_base" + else + KDUMP_INITRD="$KDUMP_BOOTDIR/$kdump_initrd_base" + fi }
get_watchdog_drvs() { - local _wdtdrvs _drv _dir + local _wdtdrvs _drv _dir
- for _dir in /sys/class/watchdog/*; do - # device/modalias will return driver of this device - [[ -f "$_dir/device/modalias" ]] || continue - _drv=$(< "$_dir/device/modalias") - _drv=$(modprobe --set-version "$KDUMP_KERNELVER" -R "$_drv" 2>/dev/null) - for i in $_drv; do - if ! [[ " $_wdtdrvs " == *" $i "* ]]; then - _wdtdrvs="$_wdtdrvs $i" - fi - done - done + for _dir in /sys/class/watchdog/*; do + # device/modalias will return driver of this device + [[ -f "$_dir/device/modalias" ]] || continue + _drv=$(< "$_dir/device/modalias") + _drv=$(modprobe --set-version "$KDUMP_KERNELVER" -R "$_drv" 2> /dev/null) + for i in $_drv; do + if ! [[ " $_wdtdrvs " == *" $i "* ]]; then + _wdtdrvs="$_wdtdrvs $i" + fi + done + done
- echo "$_wdtdrvs" + echo "$_wdtdrvs" }
# @@ -711,141 +714,141 @@ get_watchdog_drvs() # Store the final result in global $KDUMP_COMMANDLINE. prepare_cmdline() { - local cmdline id + local cmdline id
- if [[ -z "$1" ]]; then - cmdline=$(cat /proc/cmdline) - else - cmdline="$1" - fi + if [[ -z $1 ]]; then + cmdline=$(cat /proc/cmdline) + else + cmdline="$1" + fi
- # These params should always be removed - cmdline=$(remove_cmdline_param "$cmdline" crashkernel panic_on_warn) - # These params can be removed configurably - cmdline=$(remove_cmdline_param "$cmdline" "$2") + # These params should always be removed + cmdline=$(remove_cmdline_param "$cmdline" crashkernel panic_on_warn) + # These params can be removed configurably + cmdline=$(remove_cmdline_param "$cmdline" "$2")
- # Always remove "root=X", as we now explicitly generate all kinds - # of dump target mount information including root fs. - # - # We do this before KDUMP_COMMANDLINE_APPEND, if one really cares - # about it(e.g. for debug purpose), then can pass "root=X" using - # KDUMP_COMMANDLINE_APPEND. - cmdline=$(remove_cmdline_param "$cmdline" root) + # Always remove "root=X", as we now explicitly generate all kinds + # of dump target mount information including root fs. + # + # We do this before KDUMP_COMMANDLINE_APPEND, if one really cares + # about it(e.g. for debug purpose), then can pass "root=X" using + # KDUMP_COMMANDLINE_APPEND. + cmdline=$(remove_cmdline_param "$cmdline" root)
- # With the help of "--hostonly-cmdline", we can avoid some interitage. - cmdline=$(remove_cmdline_param "$cmdline" rd.lvm.lv rd.luks.uuid rd.dm.uuid rd.md.uuid fcoe) + # With the help of "--hostonly-cmdline", we can avoid some interitage. + cmdline=$(remove_cmdline_param "$cmdline" rd.lvm.lv rd.luks.uuid rd.dm.uuid rd.md.uuid fcoe)
- # Remove netroot, rd.iscsi.initiator and iscsi_initiator since - # we get duplicate entries for the same in case iscsi code adds - # it as well. - cmdline=$(remove_cmdline_param "$cmdline" netroot rd.iscsi.initiator iscsi_initiator) + # Remove netroot, rd.iscsi.initiator and iscsi_initiator since + # we get duplicate entries for the same in case iscsi code adds + # it as well. + cmdline=$(remove_cmdline_param "$cmdline" netroot rd.iscsi.initiator iscsi_initiator)
- cmdline="${cmdline} $3" + cmdline="${cmdline} $3"
- id=$(get_bootcpu_apicid) - if [[ -n ${id} ]] ; then - cmdline=$(append_cmdline "${cmdline}" disable_cpu_apicid "${id}") - fi + id=$(get_bootcpu_apicid) + if [[ -n ${id} ]]; then + cmdline=$(append_cmdline "${cmdline}" disable_cpu_apicid "${id}") + fi
- # If any watchdog is used, set it's pretimeout to 0. pretimeout let - # watchdog panic the kernel first, and reset the system after the - # panic. If the system is already in kdump, panic is not helpful - # and only increase the chance of watchdog failure. - for i in $(get_watchdog_drvs); do - cmdline+=" $i.pretimeout=0" + # If any watchdog is used, set it's pretimeout to 0. pretimeout let + # watchdog panic the kernel first, and reset the system after the + # panic. If the system is already in kdump, panic is not helpful + # and only increase the chance of watchdog failure. + for i in $(get_watchdog_drvs); do + cmdline+=" $i.pretimeout=0"
- if [[ $i == hpwdt ]]; then - # hpwdt have a special parameter kdumptimeout, is's only suppose - # to be set to non-zero in first kernel. In kdump, non-zero - # value could prevent the watchdog from resetting the system. - cmdline+=" $i.kdumptimeout=0" - fi - done + if [[ $i == hpwdt ]]; then + # hpwdt have a special parameter kdumptimeout, is's only suppose + # to be set to non-zero in first kernel. In kdump, non-zero + # value could prevent the watchdog from resetting the system. + cmdline+=" $i.kdumptimeout=0" + fi + done
- # Remove trace_buf_size, trace_event - cmdline=$(remove_cmdline_param "$cmdline" trace_buf_size trace_event) - cmdline="${cmdline} trace_buf_size=1" + # Remove trace_buf_size, trace_event + cmdline=$(remove_cmdline_param "$cmdline" trace_buf_size trace_event) + cmdline="${cmdline} trace_buf_size=1"
- echo "${cmdline}" + echo "${cmdline}" }
#get system memory size in the unit of GB get_system_size() { - result=$(grep "System RAM" /proc/iomem | awk -F ":" '{ print $1 }' | tr "[:lower:]" "[:upper:]" | paste -sd+) - result="+$result" - # replace '-' with '+0x' and '+' with '-0x' - sum=$(echo "$result" | sed -e 's/-/K0x/g' -e 's/+/-0x/g' -e 's/K/+/g') - size=$(printf "%d\n" $((sum))) - size=$((size/1024/1024/1024)) + result=$(grep "System RAM" /proc/iomem | awk -F ":" '{ print $1 }' | tr "[:lower:]" "[:upper:]" | paste -sd+) + result="+$result" + # replace '-' with '+0x' and '+' with '-0x' + sum=$(echo "$result" | sed -e 's/-/K0x/g' -e 's/+/-0x/g' -e 's/K/+/g') + size=$(printf "%d\n" $((sum))) + size=$((size / 1024 / 1024 / 1024))
- echo $size + echo $size }
get_recommend_size() { - local mem_size=$1 - local _ck_cmdline=$2 - local OLDIFS="$IFS" - - start=${_ck_cmdline: :1} - if [[ $mem_size -lt $start ]]; then - echo "0M" - return - fi - IFS=',' - for i in $_ck_cmdline; do - end=$(echo "$i" | awk -F "-" '{ print $2 }' | awk -F ":" '{ print $1 }') - recommend=$(echo "$i" | awk -F "-" '{ print $2 }' | awk -F ":" '{ print $2 }') - size=${end: : -1} - unit=${end: -1} - if [[ $unit == 'T' ]]; then - size=$((size*1024)) - fi - if [[ $mem_size -lt $size ]]; then - echo "$recommend" - IFS="$OLDIFS" - return - fi - done - IFS="$OLDIFS" + local mem_size=$1 + local _ck_cmdline=$2 + local OLDIFS="$IFS" + + start=${_ck_cmdline::1} + if [[ $mem_size -lt $start ]]; then + echo "0M" + return + fi + IFS=',' + for i in $_ck_cmdline; do + end=$(echo "$i" | awk -F "-" '{ print $2 }' | awk -F ":" '{ print $1 }') + recommend=$(echo "$i" | awk -F "-" '{ print $2 }' | awk -F ":" '{ print $2 }') + size=${end::-1} + unit=${end: -1} + if [[ $unit == 'T' ]]; then + size=$((size * 1024)) + fi + if [[ $mem_size -lt $size ]]; then + echo "$recommend" + IFS="$OLDIFS" + return + fi + done + IFS="$OLDIFS" }
# return recommended size based on current system RAM size # $1: kernel version, if not set, will defaults to $(uname -r) kdump_get_arch_recommend_size() { - local kernel=$1 arch + local kernel=$1 arch
- if ! [[ -r "/proc/iomem" ]] ; then - echo "Error, can not access /proc/iomem." - return 1 - fi + if ! [[ -r "/proc/iomem" ]]; then + echo "Error, can not access /proc/iomem." + return 1 + fi
- [[ -z "$kernel" ]] && kernel=$(uname -r) - ck_cmdline=$(cat "/usr/lib/modules/$kernel/crashkernel.default" 2>/dev/null) + [[ -z $kernel ]] && kernel=$(uname -r) + ck_cmdline=$(cat "/usr/lib/modules/$kernel/crashkernel.default" 2> /dev/null)
- if [[ -n "$ck_cmdline" ]]; then - ck_cmdline=${ck_cmdline#crashkernel=} - else - arch=$(lscpu | grep Architecture | awk -F ":" '{ print $2 }' | tr '[:lower:]' '[:upper:]') - if [[ "$arch" = "X86_64" ]] || [[ "$arch" = "S390X" ]]; then - ck_cmdline="1G-4G:160M,4G-64G:192M,64G-1T:256M,1T-:512M" - elif [[ "$arch" = "AARCH64" ]]; then - ck_cmdline="2G-:448M" - elif [[ "$arch" = "PPC64LE" ]]; then - if is_fadump_capable; then - ck_cmdline="4G-16G:768M,16G-64G:1G,64G-128G:2G,128G-1T:4G,1T-2T:6G,2T-4T:12G,4T-8T:20G,8T-16T:36G,16T-32T:64G,32T-64T:128G,64T-:180G" - else - ck_cmdline="2G-4G:384M,4G-16G:512M,16G-64G:1G,64G-128G:2G,128G-:4G" - fi - fi - fi + if [[ -n $ck_cmdline ]]; then + ck_cmdline=${ck_cmdline#crashkernel=} + else + arch=$(lscpu | grep Architecture | awk -F ":" '{ print $2 }' | tr '[:lower:]' '[:upper:]') + if [[ $arch == "X86_64" ]] || [[ $arch == "S390X" ]]; then + ck_cmdline="1G-4G:160M,4G-64G:192M,64G-1T:256M,1T-:512M" + elif [[ $arch == "AARCH64" ]]; then + ck_cmdline="2G-:448M" + elif [[ $arch == "PPC64LE" ]]; then + if is_fadump_capable; then + ck_cmdline="4G-16G:768M,16G-64G:1G,64G-128G:2G,128G-1T:4G,1T-2T:6G,2T-4T:12G,4T-8T:20G,8T-16T:36G,16T-32T:64G,32T-64T:128G,64T-:180G" + else + ck_cmdline="2G-4G:384M,4G-16G:512M,16G-64G:1G,64G-128G:2G,128G-:4G" + fi + fi + fi
- ck_cmdline=$(echo "$ck_cmdline" | sed -e 's/-:/-102400T:/g') - sys_mem=$(get_system_size) + ck_cmdline=$(echo "$ck_cmdline" | sed -e 's/-:/-102400T:/g') + sys_mem=$(get_system_size)
- get_recommend_size "$sys_mem" "$ck_cmdline" + get_recommend_size "$sys_mem" "$ck_cmdline" }
# Print all underlying crypt devices of a block device @@ -853,17 +856,17 @@ kdump_get_arch_recommend_size() # $1: the block device to be checked in maj:min format get_luks_crypt_dev() { - local _type - [[ -b /dev/block/$1 ]] || return 1 + local _type + [[ -b /dev/block/$1 ]] || return 1
- _type=$(eval "$(blkid -u filesystem,crypto -o export -- "/dev/block/$1"); echo $TYPE") - [[ $_type == "crypto_LUKS" ]] && echo "$1" + _type=$(eval "$(blkid -u filesystem,crypto -o export -- "/dev/block/$1"); echo $TYPE") + [[ $_type == "crypto_LUKS" ]] && echo "$1"
- for _x in "/sys/dev/block/$1/slaves/"*; do - [[ -f $_x/dev ]] || continue - [[ $_x/subsystem -ef /sys/class/block ]] || continue - get_luks_crypt_dev "$(< "$_x/dev")" - done + for _x in "/sys/dev/block/$1/slaves/"*; do + [[ -f $_x/dev ]] || continue + [[ $_x/subsystem -ef /sys/class/block ]] || continue + get_luks_crypt_dev "$(< "$_x/dev")" + done }
# kdump_get_maj_min <device> @@ -871,91 +874,91 @@ get_luks_crypt_dev() # Example: # $ get_maj_min /dev/sda2 # 8:2 -kdump_get_maj_min() { - local _majmin - _majmin="$(stat -L -c '%t:%T' "$1" 2> /dev/null)" - printf "%s" "$((0x${_majmin%:*})):$((0x${_majmin#*:}))" +kdump_get_maj_min() +{ + local _majmin + _majmin="$(stat -L -c '%t:%T' "$1" 2> /dev/null)" + printf "%s" "$((0x${_majmin%:*})):$((0x${_majmin#*:}))" }
get_all_kdump_crypt_dev() { - local _dev _crypt + local _dev _crypt
- for _dev in $(get_block_dump_target); do - _crypt=$(get_luks_crypt_dev "$(kdump_get_maj_min "$_dev")") - [[ -n "$_crypt" ]] && echo "$_crypt" - done + for _dev in $(get_block_dump_target); do + _crypt=$(get_luks_crypt_dev "$(kdump_get_maj_min "$_dev")") + [[ -n $_crypt ]] && echo "$_crypt" + done }
check_vmlinux() { - # Use readelf to check if it's a valid ELF - readelf -h "$1" &>/dev/null || return 1 + # Use readelf to check if it's a valid ELF + readelf -h "$1" &> /dev/null || return 1 }
get_vmlinux_size() { - local size=0 + local size=0
- while read -r _type _offset _virtaddr _physaddr _fsize _msize _flg _aln; do - size=$(( size + _msize )) - done <<< "$(readelf -l -W "$1" | grep "^ LOAD" 2>/dev/stderr)" + while read -r _type _offset _virtaddr _physaddr _fsize _msize _flg _aln; do + size=$((size + _msize)) + done <<< "$(readelf -l -W "$1" | grep "^ LOAD" 2> /dev/stderr)"
- echo $size + echo $size }
try_decompress() { - # The obscure use of the "tr" filter is to work around older versions of - # "grep" that report the byte offset of the line instead of the pattern. + # The obscure use of the "tr" filter is to work around older versions of + # "grep" that report the byte offset of the line instead of the pattern.
- # Try to find the header ($1) and decompress from here - for pos in $(tr "$1\n$2" "\n$2=" < "$4" | grep -abo "^$2") - do - if ! type -P "$3" > /dev/null; then - ddebug "Signiature detected but '$3' is missing, skip this decompressor" - break - fi + # Try to find the header ($1) and decompress from here + for pos in $(tr "$1\n$2" "\n$2=" < "$4" | grep -abo "^$2"); do + if ! type -P "$3" > /dev/null; then + ddebug "Signiature detected but '$3' is missing, skip this decompressor" + break + fi
- pos=${pos%%:*} - tail -c+$pos "$img" | $3 > "$5" 2> /dev/null - if check_vmlinux "$5"; then - ddebug "Kernel is extracted with '$3'" - return 0 - fi - done + pos=${pos%%:*} + tail -c+$pos "$img" | $3 > "$5" 2> /dev/null + if check_vmlinux "$5"; then + ddebug "Kernel is extracted with '$3'" + return 0 + fi + done
- return 1 + return 1 }
# Borrowed from linux/scripts/extract-vmlinux get_kernel_size() { - # Prepare temp files: - local img=$1 tmp - - tmp=$(mktemp /tmp/vmlinux-XXX) - trap 'rm -f $tmp' 0 - - # Try to check if it's a vmlinux already - check_vmlinux "$img" && get_vmlinux_size "$img" && return 0 - - # That didn't work, so retry after decompression. - try_decompress '\037\213\010' xy gunzip "$img" "$tmp" || \ - try_decompress '\3757zXZ\000' abcde unxz "$img" "$tmp" || \ - try_decompress 'BZh' xy bunzip2 "$img" "$tmp" || \ - try_decompress '\135\0\0\0' xxx unlzma "$img" "$tmp" || \ - try_decompress '\211\114\132' xy 'lzop -d' "$img" "$tmp" || \ - try_decompress '\002!L\030' xxx 'lz4 -d' "$img" "$tmp" || \ - try_decompress '(\265/\375' xxx unzstd "$img" "$tmp" - - # Finally check for uncompressed images or objects: - [[ $? -eq 0 ]] && get_vmlinux_size "$tmp" && return 0 - - # Fallback to use iomem - local _size=0 - while read -r _seg; do - _size=$(( _size + 0x${_seg#*-} - 0x${_seg%-*} )) - done <<< "$(grep -E "Kernel (code|rodata|data|bss)" /proc/iomem | cut -d ":" -f 1)" - echo $_size + # Prepare temp files: + local img=$1 tmp + + tmp=$(mktemp /tmp/vmlinux-XXX) + trap 'rm -f $tmp' 0 + + # Try to check if it's a vmlinux already + check_vmlinux "$img" && get_vmlinux_size "$img" && return 0 + + # That didn't work, so retry after decompression. + try_decompress '\037\213\010' xy gunzip "$img" "$tmp" || + try_decompress '\3757zXZ\000' abcde unxz "$img" "$tmp" || + try_decompress 'BZh' xy bunzip2 "$img" "$tmp" || + try_decompress '\135\0\0\0' xxx unlzma "$img" "$tmp" || + try_decompress '\211\114\132' xy 'lzop -d' "$img" "$tmp" || + try_decompress '\002!L\030' xxx 'lz4 -d' "$img" "$tmp" || + try_decompress '(\265/\375' xxx unzstd "$img" "$tmp" + + # Finally check for uncompressed images or objects: + [[ $? -eq 0 ]] && get_vmlinux_size "$tmp" && return 0 + + # Fallback to use iomem + local _size=0 + while read -r _seg; do + _size=$((_size + 0x${_seg#*-} - 0x${_seg%-*})) + done <<< "$(grep -E "Kernel (code|rodata|data|bss)" /proc/iomem | cut -d ":" -f 1)" + echo $_size }
Remove usage of "[[ ... ]]", remove usage of "type -p".
Signed-off-by: Kairui Song kasong@redhat.com --- kdump-logger.sh | 79 +++++++++++++++++++++++++++---------------------- 1 file changed, 44 insertions(+), 35 deletions(-)
diff --git a/kdump-logger.sh b/kdump-logger.sh index 370e5e89..41b93ab8 100755 --- a/kdump-logger.sh +++ b/kdump-logger.sh @@ -53,11 +53,12 @@ fi # get_kdump_loglvl() { - (type -p getarg) && kdump_sysloglvl=$(getarg rd.kdumploglvl) + [ -f /lib/dracut-lib.sh ] && kdump_sysloglvl=$(getarg rd.kdumploglvl) [ -z "$kdump_sysloglvl" ] && return 1;
- (type -p isdigit) && isdigit $kdump_sysloglvl - [ $? -ne 0 ] && return 1; + if [ -f /lib/dracut-lib.sh ] && ! isdigit "$kdump_sysloglvl"; then + return 1 + fi
return 0 } @@ -86,8 +87,7 @@ dlog_init() { local ret=0; local errmsg
if [ -s /proc/vmcore ];then - get_kdump_loglvl - if [ $? -ne 0 ];then + if ! get_kdump_loglvl; then logger -t "kdump[$$]" -p warn -- "Kdump is using the default log level(3)." kdump_sysloglvl=3 fi @@ -104,8 +104,7 @@ dlog_init() { [ -z "$kdump_kmsgloglvl" ] && kdump_kmsgloglvl=0
for loglvl in "$kdump_stdloglvl" "$kdump_kmsgloglvl" "$kdump_sysloglvl"; do - check_loglvl "$loglvl" - if [ $? -ne 0 ]; then + if ! check_loglvl "$loglvl"; then echo "Illegal log level: $kdump_stdloglvl $kdump_kmsgloglvl $kdump_sysloglvl" return 1 fi @@ -114,21 +113,21 @@ dlog_init() { # Skip initialization if it's already done. [ -n "$kdump_maxloglvl" ] && return 0
- if [[ $UID -ne 0 ]]; then + if [ "$UID" -ne 0 ]; then kdump_kmsgloglvl=0 kdump_sysloglvl=0 fi
- if [[ $kdump_sysloglvl -gt 0 ]]; then - if [[ -d /run/systemd/journal ]] \ - && type -P systemd-cat &>/dev/null \ - && systemctl --quiet is-active systemd-journald.socket &>/dev/null; then + if [ "$kdump_sysloglvl" -gt 0 ]; then + if [ -d /run/systemd/journal ] \ + && systemd-cat --version 1>/dev/null 2>&1 \ + && systemctl --quiet is-active systemd-journald.socket 1>/dev/null 2>&1; then readonly _systemdcatfile="/var/tmp/systemd-cat" - mkfifo "$_systemdcatfile" &>/dev/null + mkfifo "$_systemdcatfile" 1>/dev/null 2>&1 readonly _dlogfd=15 systemd-cat -t 'kdump' --level-prefix=true <"$_systemdcatfile" & exec 15>"$_systemdcatfile" - elif ! [ -S /dev/log -a -w /dev/log ] || ! command -v logger >/dev/null; then + elif ! [ -S /dev/log ] && [ -w /dev/log ] || ! command -v logger >/dev/null; then # We cannot log to syslog, so turn this facility off. kdump_kmsgloglvl=$kdump_sysloglvl kdump_sysloglvl=0 @@ -139,29 +138,29 @@ dlog_init() {
local lvl; local maxloglvl_l=0 for lvl in $kdump_stdloglvl $kdump_sysloglvl $kdump_kmsgloglvl; do - [[ $lvl -gt $maxloglvl_l ]] && maxloglvl_l=$lvl + [ $lvl -gt $maxloglvl_l ] && maxloglvl_l=$lvl done readonly kdump_maxloglvl=$maxloglvl_l export kdump_maxloglvl
- if [[ $kdump_stdloglvl -lt 4 ]] && [[ $kdump_kmsgloglvl -lt 4 ]] && [[ $kdump_sysloglvl -lt 4 ]]; then + if [ $kdump_stdloglvl -lt 4 ] && [ $kdump_kmsgloglvl -lt 4 ] && [ $kdump_sysloglvl -lt 4 ]; then unset ddebug ddebug() { :; }; fi
- if [[ $kdump_stdloglvl -lt 3 ]] && [[ $kdump_kmsgloglvl -lt 3 ]] && [[ $kdump_sysloglvl -lt 3 ]]; then + if [ $kdump_stdloglvl -lt 3 ] && [ $kdump_kmsgloglvl -lt 3 ] && [ $kdump_sysloglvl -lt 3 ]; then unset dinfo dinfo() { :; }; fi
- if [[ $kdump_stdloglvl -lt 2 ]] && [[ $kdump_kmsgloglvl -lt 2 ]] && [[ $kdump_sysloglvl -lt 2 ]]; then + if [ $kdump_stdloglvl -lt 2 ] && [ $kdump_kmsgloglvl -lt 2 ] && [ $kdump_sysloglvl -lt 2 ]; then unset dwarn dwarn() { :; }; unset dwarning dwarning() { :; }; fi
- if [[ $kdump_stdloglvl -lt 1 ]] && [[ $kdump_kmsgloglvl -lt 1 ]] && [[ $kdump_sysloglvl -lt 1 ]]; then + if [ $kdump_stdloglvl -lt 1 ] && [ $kdump_kmsgloglvl -lt 1 ] && [ $kdump_sysloglvl -lt 1 ]; then unset derror derror() { :; }; fi @@ -222,7 +221,7 @@ _dlvl2syslvl() { # The number is constructed by multiplying the facility by 8 and then # adding the level. # About The Syslog Protocol, please refer to the RFC5424 for more details. - echo $((24+$lvl)) + echo $((24 + lvl)) }
## @brief Prints to stderr, to syslog and/or /dev/kmsg given message with @@ -254,18 +253,18 @@ _do_dlog() { local lvl="$1"; shift local msg="$*"
- [[ $lvl -le $kdump_stdloglvl ]] && printf -- 'kdump: %s\n' "$msg" >&2 + [ "$lvl" -le $kdump_stdloglvl ] && printf -- 'kdump: %s\n' "$msg" >&2
- if [[ $lvl -le $kdump_sysloglvl ]]; then - if [[ "$_dlogfd" ]]; then - printf -- "<%s>%s\n" "$(($(_dlvl2syslvl $lvl) & 7))" "$msg" >&$_dlogfd + if [ "$lvl" -le $kdump_sysloglvl ]; then + if [ "$_dlogfd" ]; then + printf -- "<%s>%s\n" "$(($(_dlvl2syslvl "$lvl") & 7))" "$msg" >&$_dlogfd else - logger -t "kdump[$$]" -p $(_lvl2syspri $lvl) -- "$msg" + logger -t "kdump[$$]" -p "$(_lvl2syspri "$lvl")" -- "$msg" fi fi
- [[ $lvl -le $kdump_kmsgloglvl ]] && \ - echo "<$(_dlvl2syslvl $lvl)>kdump[$$] $msg" >/dev/kmsg + [ "$lvl" -le $kdump_kmsgloglvl ] && \ + echo "<$(_dlvl2syslvl "$lvl")>kdump[$$] $msg" >/dev/kmsg }
## @brief Internal helper function for _do_dlog() @@ -286,12 +285,12 @@ _do_dlog() { # echo "This is a warning" | dwarn dlog() { [ -z "$kdump_maxloglvl" ] && return 0 - [[ $1 -le $kdump_maxloglvl ]] || return 0 + [ "$1" -le "$kdump_maxloglvl" ] || return 0
- if [[ $# -gt 1 ]]; then + if [ $# -gt 1 ]; then _do_dlog "$@" else - while read line || [ -n "$line" ]; do + while read -r line || [ -n "$line" ]; do _do_dlog "$1" "$line" done fi @@ -304,7 +303,9 @@ dlog() { ddebug() { set +x dlog 4 "$@" - [ -n "$debug" ] && set -x || : + if [ -n "$debug" ]; then + set -x + fi }
## @brief Logs message at INFO level (3) @@ -314,7 +315,9 @@ ddebug() { dinfo() { set +x dlog 3 "$@" - [ -n "$debug" ] && set -x || : + if [ -n "$debug" ]; then + set -x + fi }
## @brief Logs message at WARN level (2) @@ -324,7 +327,9 @@ dinfo() { dwarn() { set +x dlog 2 "$@" - [ -n "$debug" ] && set -x || : + if [ -n "$debug" ]; then + set -x + fi }
## @brief It's an alias to dwarn() function. @@ -334,7 +339,9 @@ dwarn() { dwarning() { set +x dwarn "$@" - [ -n "$debug" ] && set -x || : + if [ -n "$debug" ]; then + set -x + fi }
## @brief Logs message at ERROR level (1) @@ -344,5 +351,7 @@ dwarning() { derror() { set +x dlog 1 "$@" - [ -n "$debug" ] && set -x || : + if [ -n "$debug" ]; then + set -x + fi }
Signed-off-by: Kairui Song kasong@redhat.com --- kdump-logger.sh | 54 +++++++++++++++++++++++-------------------------- 1 file changed, 25 insertions(+), 29 deletions(-)
diff --git a/kdump-logger.sh b/kdump-logger.sh index 41b93ab8..98c4eea3 100755 --- a/kdump-logger.sh +++ b/kdump-logger.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/bin/sh # # This comes from the dracut-logger.sh # @@ -84,7 +84,7 @@ check_loglvl() # @retval 0 on success. # dlog_init() { - local ret=0; local errmsg + ret=0
if [ -s /proc/vmcore ];then if ! get_kdump_loglvl; then @@ -136,11 +136,11 @@ dlog_init() { fi fi
- local lvl; local maxloglvl_l=0 - for lvl in $kdump_stdloglvl $kdump_sysloglvl $kdump_kmsgloglvl; do - [ $lvl -gt $maxloglvl_l ] && maxloglvl_l=$lvl + kdump_maxloglvl=0 + for _dlog_lvl in $kdump_stdloglvl $kdump_sysloglvl $kdump_kmsgloglvl; do + [ $_dlog_lvl -gt $kdump_maxloglvl ] && kdump_maxloglvl=$_dlog_lvl done - readonly kdump_maxloglvl=$maxloglvl_l + readonly kdump_maxloglvl export kdump_maxloglvl
if [ $kdump_stdloglvl -lt 4 ] && [ $kdump_kmsgloglvl -lt 4 ] && [ $kdump_sysloglvl -lt 4 ]; then @@ -172,7 +172,7 @@ dlog_init() {
## @brief Converts numeric level to logger priority defined by POSIX.2. # -# @param lvl Numeric logging level in range from 1 to 4. +# @param $1: Numeric logging level in range from 1 to 4. # @retval 1 if @a lvl is out of range. # @retval 0 if @a lvl is correct. # @result Echoes logger priority. @@ -188,7 +188,7 @@ _lvl2syspri() {
## @brief Converts logger numeric level to syslog log level # -# @param lvl Numeric logging level in range from 1 to 4. +# @param $1: Numeric logging level in range from 1 to 4. # @retval 1 if @a lvl is out of range. # @retval 0 if @a lvl is correct. # @result Echoes kernel console numeric log level @@ -208,27 +208,25 @@ _lvl2syspri() { # # @see /usr/include/sys/syslog.h _dlvl2syslvl() { - local lvl - case "$1" in - 1) lvl=3;; - 2) lvl=4;; - 3) lvl=6;; - 4) lvl=7;; + 1) set -- 3;; + 2) set -- 4;; + 3) set -- 6;; + 4) set -- 7;; *) return 1;; esac
# The number is constructed by multiplying the facility by 8 and then # adding the level. # About The Syslog Protocol, please refer to the RFC5424 for more details. - echo $((24 + lvl)) + echo $((24 + $1)) }
## @brief Prints to stderr, to syslog and/or /dev/kmsg given message with # given level (priority). # -# @param lvl Numeric logging level. -# @param msg Message. +# @param $1: Numeric logging level. +# @param $2: Message. # @retval 0 It's always returned, even if logging failed. # # @note This function is not supposed to be called manually. Please use @@ -250,27 +248,24 @@ _dlvl2syslvl() { # - @c INFO to @c info # - @c DEBUG to @c debug _do_dlog() { - local lvl="$1"; shift - local msg="$*" + [ "$1" -le $kdump_stdloglvl ] && printf -- 'kdump: %s\n' "$2" >&2
- [ "$lvl" -le $kdump_stdloglvl ] && printf -- 'kdump: %s\n' "$msg" >&2 - - if [ "$lvl" -le $kdump_sysloglvl ]; then + if [ "$1" -le $kdump_sysloglvl ]; then if [ "$_dlogfd" ]; then - printf -- "<%s>%s\n" "$(($(_dlvl2syslvl "$lvl") & 7))" "$msg" >&$_dlogfd + printf -- "<%s>%s\n" "$(($(_dlvl2syslvl "$1") & 7))" "$2" 1>&$_dlogfd else - logger -t "kdump[$$]" -p "$(_lvl2syspri "$lvl")" -- "$msg" + logger -t "kdump[$$]" -p "$(_lvl2syspri "$1")" -- "$2" fi fi
- [ "$lvl" -le $kdump_kmsgloglvl ] && \ - echo "<$(_dlvl2syslvl "$lvl")>kdump[$$] $msg" >/dev/kmsg + [ "$1" -le $kdump_kmsgloglvl ] && \ + echo "<$(_dlvl2syslvl "$1")>kdump[$$] $2" >/dev/kmsg }
## @brief Internal helper function for _do_dlog() # -# @param lvl Numeric logging level. -# @param msg Message. +# @param $1: Numeric logging level. +# @param $2 [...]: Message. # @retval 0 It's always returned, even if logging failed. # # @note This function is not supposed to be called manually. Please use @@ -288,7 +283,8 @@ dlog() { [ "$1" -le "$kdump_maxloglvl" ] || return 0
if [ $# -gt 1 ]; then - _do_dlog "$@" + _dlog_lvl=$1; shift + _do_dlog "$_dlog_lvl" "$*" else while read -r line || [ -n "$line" ]; do _do_dlog "$1" "$line"
All non-POSIX syntax in second kernel are gone, tested on Fedora 34 with latest dracut, dash now works fine.
Signed-off-by: Kairui Song kasong@redhat.com --- mkdumprd | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/mkdumprd b/mkdumprd index 55948a8c..cc37ae18 100644 --- a/mkdumprd +++ b/mkdumprd @@ -27,7 +27,7 @@ SAVE_PATH=$(get_save_path) OVERRIDE_RESETTABLE=0
extra_modules="" -dracut_args=(--add kdumpbase --quiet --hostonly --hostonly-cmdline --hostonly-i18n --hostonly-mode strict -o "plymouth dash resume ifcfg earlykdump") +dracut_args=(--add kdumpbase --quiet --hostonly --hostonly-cmdline --hostonly-i18n --hostonly-mode strict -o "plymouth resume ifcfg earlykdump")
MKDUMPRD_TMPDIR="$(mktemp -d -t mkdumprd.XXXXXX)" [ -d "$MKDUMPRD_TMPDIR" ] || perror_exit "dracut: mktemp -p -d -t dracut.XXXXXX failed."
Hi Kairui,
again, great series!
There are still some nits but to be fair almost all already existed and you only had the bad luck to touch the line. However, I don't think it makes sense to fix them in this series. The series as is is already quite large and a huge improvement to before. Furthermore shellcheck still has many findings and fixing them all in this series would be way too much. So please take my comment as suggestions on what you could do next.
Having that said there are a few nits that should be fixed before pushing
* To the files that have to be POSIX compliant, add a short comment saying exactly that. The shebang already indicates it but I think it is better to be a little bit more verbose and better human readable. Something like this should be more than enough.
# The code in this file might be run in an environment without bash. # Any code added must be POSIX compliant. * Fix the last shellcheck complaints about non-POSIX compliant code [1][2][3] (I'm not totally sure if dracut-early-kdump.sh needs to be POSIX compliant as it is run by the 1st kernel but the fix is so simple I would simply do it)
* Fix the last typos.
* Improve the commit massage in patch 47 and 48. You got a little bit sloppy in the end and made much more changes than you explain in the commit message. The quick and dirty solution would be to simply squash both patches, take the commit message from patch 45 and simply add the "make POSIX compatible" bits.
All in all I think it would have been better if you had picked one change, e.g. fix SC2162 or remove the 'local' keyword for POSIX files etc., and apply it to all files rather than pick one file and apply all the changes. That would have made writing commit messages and my life as reviewer a little bit easier. However, I don't think it makes sent to fix it now as reassembling the full series is way to much effort and would introduce too many new bugs. But keep it in mind for the next time.
I don't think you need to post a new version of the series. Although if you like me to have an other look I'll be happy to help.
For the series with the nit above fixed Acked-by: Philipp Rudo prudo@redhat.com
[1] In dracut-early-kdump.sh line 44: In dracut-early-kdump.sh line 67: if [ $? == 0 ]; then ^-- SC3014: In POSIX sh, == in place of = is undefined.
[2] In kdump-logger.sh line 116: if [ "$UID" -ne 0 ]; then ^--^ SC3028: In POSIX sh, UID is undefined.
[3] In kdump-logger.sh line 129: exec 15>"$_systemdcatfile" ^-------------------^ SC3023: In POSIX sh, FDs outside 0-9 are undefined.
On Thu, 19 Aug 2021 19:38:59 +0800 Kairui Song kasong@redhat.com wrote:
From: Kairui Song kasong@redhat.com To: kexec@lists.fedoraproject.org CC: Kairui Song kasong@redhat.com Subject: [PATCH v2 00/49] Batch update and refactor Date: Thu, 19 Aug 2021 19:38:59 +0800
This mass update is done with the assistant of shellcheck and shfmt. This patch series fixed most syntax issues found by shellcheck, tons of corner cases and issues are fixed.
Also simplified a lot of code according to suggestions by shellcheck. Related shellcheck warn/error/suggest info links are included in the commit message.
Since shellcheck can help to detect non-POSIX syntax issue in POSIX script (#!/bin/sh), and the coding style in kexec-tools package is very messy, this series refactored the code structure in following way:
kdumpctl, mkdumprd, mkfadumprd, *-module-setup.sh and kdump-lib.sh is "bash only" script. We rely on bash only syntax heavily, and they will only be used in the first kernel, so just let them leverage bash syntax for better maintainability and better performance.
kdump-lib-initramfs.sh, and dracut-kdump.sh is now POSIX compatible, and will be used in the second kernel.
This refactoring also enables kdump to use dash or busybox, instead of bash in the second kernel, which improves performance and memory usage. Tested with latest dracut on Fedora 34, now "dash" in second kernel works well, it's faster than bash and save a lot of memory.
We may test dash or busybox as default kdump shell in the future for better performance.
For reviewers:
Patch 25, 26, 30, 41, 46 is automatic code update using script and tools like shfmt, other patch may need careful review.
Patch 1 added a editorconfig file for shfmt to work properly, which is Acked by Pingfan but still posting it to make it easier to review.
Patch 2 - 29 focus on the bash part: Patch 2, 3, 4, 5, 8 introduced new config file read and format helper, which unified the config file reading in kexec-tools scripts. So space in config file should be no longer a problem (previously random problem may occur since kexec-tools scripts is using many different ways to read the config file). And this make it much easier to clean up the code.
Patch 6, 7, 9 - 24 fixed many issues found with shellcheck in bash scripts manually. Some issues are already breaking kdump just no one noticed yet.
Patch 25, 26, 30 is an automatic code update using sed and shfmt, there should be no code behaviour change.
Patch 27, 28, 29 batch fixed some common bash script issues manually with hints from shellcheck.
Patch 31 - 48 focus on the POSIX part: Patch 31 - 33 restructures the code, prepare to make kdump-lib-initramfs.sh a POSIX script and drop kdump-lib.sh in kdump kernel.
Patch 34 - 38 clean up code in dracut-kdump.sh, and fix misc issues found by shellcheck manually, prepare to make it POSIX compatible.
Patch 39 contains a lot of code refactoring that makes dracut-kdump.sh POSIX compatible.
Patch 40 contains a lot of code refactoring that makes kdump-lib-initramfs.sh POSIX compatible.
Patch 41 is an automatic code update using sed, there should be no code behaviour change.
Patch 42, 43 reworked how nmcli is being called by kexec-tools, fixed word splitting issue and allow connection name to contain space.
Patch 44 optimized a sed call.
Patch 45 batch fixed some common bash script issues manually with hints from shellcheck.
Patch 46 is an automatic code update using shfmt, there should be no code behaviour change.
Patch 47, 48 contains a lot of change that makes kdump-logger.sh POSIX compatible.
Patch 49 allows mkdumprd to use dash instead of bash in second kernel.
Update from V1:
- Fix many typos and code error, and fix a few more existing code issues found while reviewing the patch, many thanks to Philipp Rudo.
- Add more info in commit message and cover letter.
Kairui Song (49): Add a .editorconfig file kdump-lib.sh: add a config format and read helper kdump-lib.sh: add a config value retrive helper kdump-lib.sh: use kdump_get_conf_val to read config values kdumpctl: use kdump_get_conf_val to read config values kdumpctl: get rid of a `wc` call kdumpctl: fix fragile loops over find output mkdumprd: use kdump_get_conf_val to read config values mkdumprd: make dracut_args an array again mkdumprd: remove some redundant echo mkdumprd: fix multiple issues with get_ssh_size mkdumprd: use array to store ssh arguments in mkdir_save_path_ssh mkfadumprd: make _dracut_isolate_args an array dracut-module-setup.sh: rework kdump_get_ip_route_field dracut-module-setup.sh: remove an unused variable dracut-module-setup.sh: fix _bondoptions wrong references dracut-module-setup.sh: use "*" to expend array as string dracut-module-setup.sh: fix a ambiguous variable reference dracut-module-setup.sh: fix a loop over ls issue dracut-module-setup.sh: make iscsi check fail early if cd failed bash scripts: remove useless cat bash scripts: get rid of expr and let bash scripts: get rid of unnessary sed calls bash scripts: always use "read -r" bash scripts: use $(...) notation instead of legacy `...` bash scripts: replace '[ ]' with '[[ ]]' for bash scripts bash scripts: fix variable quoting issue bash scripts: fix redundant exit code check bash scripts: declare and assign separately bash scripts: reformat with shfmt Prepare to make kdump-lib-initramfs.sh a POSIX compatible lib Merge kdump-error-handler.sh into kdump.sh kdump-lib-initramfs.sh: move dump raleted functions to kdump.sh dracut-kdump.sh: don't put KDUMP_SCRIPT_DIR in PATH dracut-kdump.sh: remove add_dump_code dracut-kdump.sh: simplify dump_ssh dracut-kdump.sh: Use stat instead of ls to get vmcore size dracut-kdump.sh: POSIX doesn't support pipefail dracut-kdump.sh: make it POSIX compatible kdump-lib-initramfs.sh: make it POSIX compatible kdump-lib.sh: replace '[ ]' with '[[ ]]' and get rid of legacy `` kdump-lib.sh: fix and simplify get_nmcli_value_by_field kdump-lib.sh: fix word splitting of nmcli params kdump-lib.sh: avoid calling sed multiple times in get_system_size kdump-lib.sh: batch fix issues found with shellcheck kdump-lib.sh: reformat with shfmt kdump-logger.sh: refactor to remove some bash only syntax kdump-logger.sh: make it POSIX compatible mkdumprd: allow using dash
.editorconfig | 32 + dracut-early-kdump-module-setup.sh | 11 +- dracut-kdump-emergency.service | 2 +- dracut-kdump-error-handler.sh | 10 - dracut-kdump.sh | 511 ++++++++--- dracut-module-setup.sh | 668 +++++++------- kdump-lib-initramfs.sh | 346 ++----- kdump-lib.sh | 1356 +++++++++++++--------------- kdump-logger.sh | 117 +-- kdumpctl | 604 ++++++------- kexec-tools.spec | 2 - mkdumprd | 600 ++++++------ mkfadumprd | 21 +- 13 files changed, 2104 insertions(+), 2176 deletions(-) create mode 100644 .editorconfig delete mode 100755 dracut-kdump-error-handler.sh
On Fri, Sep 3, 2021 at 7:58 PM Philipp Rudo prudo@redhat.com wrote:
Hi Kairui,
again, great series!
There are still some nits but to be fair almost all already existed and you only had the bad luck to touch the line. However, I don't think it makes sense to fix them in this series. The series as is is already quite large and a huge improvement to before. Furthermore shellcheck still has many findings and fixing them all in this series would be way too much. So please take my comment as suggestions on what you could do next.
Having that said there are a few nits that should be fixed before pushing
To the files that have to be POSIX compliant, add a short comment saying exactly that. The shebang already indicates it but I think it is better to be a little bit more verbose and better human readable. Something like this should be more than enough.
# The code in this file might be run in an environment without bash. # Any code added must be POSIX compliant.
Great idea, I'll do it.
- Fix the last shellcheck complaints about non-POSIX compliant code [1][2][3] (I'm not totally sure if dracut-early-kdump.sh needs to be POSIX compliant as it is run by the 1st kernel but the fix is so simple I would simply do it)
Good idea, it's a simple fix indeed.
Fix the last typos.
Improve the commit massage in patch 47 and 48. You got a little bit sloppy in the end and made much more changes than you explain in the commit message. The quick and dirty solution would be to simply squash both patches, take the commit message from patch 45 and simply add the "make POSIX compatible" bits.
Squashing 47 and 48 should be OK, changes in the logger are not too much, one commit should be OK.
For patch 45 I did a bit more self-review and found some trivial issues, I can do some adjusting.
All in all I think it would have been better if you had picked one change, e.g. fix SC2162 or remove the 'local' keyword for POSIX files etc., and apply it to all files rather than pick one file and apply all the changes. That would have made writing commit messages and my life as reviewer a little bit easier. However, I don't think it makes sent to fix it now as reassembling the full series is way to much effort and would introduce too many new bugs. But keep it in mind for the next time.
I don't think you need to post a new version of the series. Although if you like me to have an other look I'll be happy to help.
For the series with the nit above fixed Acked-by: Philipp Rudo prudo@redhat.com
[1] In dracut-early-kdump.sh line 44: In dracut-early-kdump.sh line 67: if [ $? == 0 ]; then ^-- SC3014: In POSIX sh, == in place of = is undefined.
[2] In kdump-logger.sh line 116: if [ "$UID" -ne 0 ]; then ^--^ SC3028: In POSIX sh, UID is undefined.
[3] In kdump-logger.sh line 129: exec 15>"$_systemdcatfile" ^-------------------^ SC3023: In POSIX sh, FDs outside 0-9 are undefined.
On Thu, 19 Aug 2021 19:38:59 +0800 Kairui Song kasong@redhat.com wrote:
Thanks for all the help!
-- Best Regards, Kairui Song