From 83f080f8023b04b86c9163eb3cf4df4d364fd1a7 Mon Sep 17 00:00:00 2001 From: Keith Gable Date: Thu, 18 Jan 2024 14:09:48 -0800 Subject: [PATCH] Change ec2nvme-nsid to use Bash built-ins This simple change cuts the runtime by more than half and CPU by almost a third. It also makes the script more reliable when resources are constrained (the sort of situation where you might suddenly attach more EBS NVMe volumes) and helps improve the performance of the early boot process (initrd/initramfs), should you make these scripts part of that. Performance before: $ time bash -c 'for i in $(seq 1 10000); do bash ./ec2nvme-nsid nvme0n1234234p2 > /dev/null; done' bash -c 38.00s user 90.67s system 92% cpu 2:18.43 total Performance after: $ time bash -c 'for i in $(seq 1 10000); do bash ./ec2nvme-nsid nvme0n1234234p2 > /dev/null; done' bash -c 12.61s user 27.56s system 66% cpu 1:00.26 total Signed-off-by: Keith Gable --- amazon-ec2-utils.spec | 5 ++++- ec2nvme-nsid | 15 +++++++++++---- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/amazon-ec2-utils.spec b/amazon-ec2-utils.spec index 36f598a..d058a46 100644 --- a/amazon-ec2-utils.spec +++ b/amazon-ec2-utils.spec @@ -1,6 +1,6 @@ Name: amazon-ec2-utils Summary: A set of tools for running in EC2 -Version: 2.1.0 +Version: 2.2.0 Release: 1%{?dist} License: MIT Group: System Tools @@ -75,6 +75,9 @@ rm -rf $RPM_BUILD_ROOT /etc/udev/rules.d/60-cdrom_id.rules %changelog +* Thu Jan 18 2024 Keith Gable - 2.2.0-1 +- Change ec2nvme-nsid to use Bash string manipulation to improve + performance and reliability * Thu Apr 6 2023 Noah Meyerhans - 2.1.0-1 - Add --quiet option to ec2-metadata diff --git a/ec2nvme-nsid b/ec2nvme-nsid index 576b607..7dae793 100755 --- a/ec2nvme-nsid +++ b/ec2nvme-nsid @@ -6,11 +6,18 @@ # for the specific language governing permissions and limitations under # the License. -#Expected input if partition's kernel name like nvme0n1p2 -if [ $# -eq 0 ] ; then +# Expected input is partition's kernel name like nvme0n1p2 or nvme0n1, output would be 1 + +if [[ $# -ne 1 ]]; then exit 1 else - # extract ns id from partition's kernel name and export it - NSID=$(echo -n "$@" | cut -f 3 -d 'n' | cut -f 1 -d 'p') + kernel_name=$1 + + # Remove nvme prefix (also deals with any /dev that might accidentally get passed in) + prefix_removed=${kernel_name#*nvme*n} + + # Remove partition suffix + NSID=${prefix_removed%p*} + echo "_NS_ID=${NSID}" fi