diff --git a/.github/workflows/genesis_openembedded.yml b/.github/workflows/genesis_openembedded.yml index e025a4d766..37c03454dc 100644 --- a/.github/workflows/genesis_openembedded.yml +++ b/.github/workflows/genesis_openembedded.yml @@ -7,6 +7,7 @@ on: - 'xCAT-test/native/genesis_metadata.py' - 'xCAT-test/native/genesis_console.py' - 'xCAT-test/native/genesis_console_dialogs.py' + - 'xCAT-test/native/genesis_console_fixture.py' - '.github/workflows/genesis_openembedded.yml' workflow_dispatch: jobs: diff --git a/.github/workflows/xcat_test.yml b/.github/workflows/xcat_test.yml index 2a9d321cfe..d9d2171060 100644 --- a/.github/workflows/xcat_test.yml +++ b/.github/workflows/xcat_test.yml @@ -38,6 +38,9 @@ jobs: - name: Exercise image chroot mounts if: ${{ !cancelled() }} run: prove xCAT-test/native/rh_genimage_chroot_mounts.t + - name: Check shared test fixtures + if: ${{ !cancelled() }} + run: prove xCAT-test/native/image_fixture_contract.t xCAT-test/native/postinstall_bootstrap.t - name: Check Debian probe payload permissions if: ${{ !cancelled() }} run: bats xCAT-test/native/probe_debian_permissions.bats diff --git a/xCAT-test/bats/helpers/doxcat_sandbox.bash b/xCAT-test/bats/helpers/doxcat_sandbox.bash index b909bad2ef..9a6123983c 100644 --- a/xCAT-test/bats/helpers/doxcat_sandbox.bash +++ b/xCAT-test/bats/helpers/doxcat_sandbox.bash @@ -4,7 +4,7 @@ load 'helpers/genesis_sandbox' setup_doxcat() { - setup_genesis_sandbox doxcat + setup_genesis_sandbox doxcat || return ib_address=80:00:00:48:fe:80:00:00:00:00:00:00:00:02:00:bb:cc:dd:ee:ff local utility fips library fips=$(repo_path xCAT-genesis-scripts/usr/lib/xcat/fips.sh) @@ -13,13 +13,8 @@ setup_doxcat() # chmod is in this list because doxcat runs it: the sandbox has no /usr/bin on PATH, so a # command that is missing here is a command that silently does nothing under test. doxcat's # chmod of the sshd privilege separation directory was not exercised until it was added. - for utility in bash sh cat cp awk grep sed sort tr tail rm wc cut head uname \ - timeout env ls mkdir touch readlink basename sleep chmod; do - cp -L "$(PATH=/usr/bin:/bin type -P "$utility")" "$fixture/bin/$utility" - done - if [ -x /usr/bin/coreutils ]; then - cp -L /usr/bin/coreutils "$fixture/bin/coreutils" - fi + stage_sandbox_tools bash sh cat cp awk grep sed sort tr tail rm wc cut head uname \ + timeout env ls mkdir touch readlink basename sleep chmod || return mv "$fixture/bin/sleep" "$fixture/real/sleep" printf '#!/bin/sh\nexit 0\n' >"$fixture/bin/quiet" for utility in sleep rpcbind rpc.statd ssh-keygen lldpad chronyd; do @@ -96,19 +91,10 @@ SH : >"$fixture/modules" : >"$fixture/dhcp" printf '0\n' >"$fixture/fips_enabled" - sandbox+=(--ro-bind "$fixture/bin" /usr/bin - --tmpfs /proc/sys + restrict_sandbox_tools + sandbox+=(--tmpfs /proc/sys --ro-bind "$fixture/fips_enabled" /proc/sys/crypto/fips_enabled --tmpfs /usr/lib) - if [ ! -L /usr/sbin ]; then - sandbox+=(--ro-bind "$fixture/bin" /usr/sbin) - fi - if [ ! -L /bin ]; then - sandbox+=(--ro-bind "$fixture/bin" /bin) - fi - if [ ! -L /sbin ]; then - sandbox+=(--ro-bind "$fixture/bin" /sbin) - fi for library in /usr/lib/*; do [ "${library##*/}" = xcat ] && continue sandbox+=(--ro-bind "$library" "$library") diff --git a/xCAT-test/bats/helpers/genesis_sandbox.bash b/xCAT-test/bats/helpers/genesis_sandbox.bash index e2e7769700..3536e839f7 100644 --- a/xCAT-test/bats/helpers/genesis_sandbox.bash +++ b/xCAT-test/bats/helpers/genesis_sandbox.bash @@ -1,15 +1,11 @@ #!/usr/bin/env bash -load 'helpers/shell_source' +load 'helpers/script_sandbox' setup_genesis_sandbox() { - [ "$(uname -s)" = Linux ] || skip 'Genesis filesystem isolation requires Linux' - local bwrap utility source - bwrap=$(PATH=/usr/bin:/bin type -P bwrap) || { - echo 'Install bubblewrap to run the Genesis script tests' >&2 - return 1 - } + setup_filesystem_sandbox || return + local utility source for utility in bash cat cp awk grep sed sort tr tail rm wc cut head uname timeout; do PATH=/usr/bin:/bin type -P "$utility" >/dev/null || { echo "Required utility is unavailable: $utility" >&2 @@ -21,15 +17,10 @@ setup_genesis_sandbox() echo "Required Genesis script is unreadable: $source" >&2 return 1 } - fixture="${BATS_TEST_TMPDIR:?bats-core 1.4 or newer is required}/fixture" - mkdir -p "$fixture"/{bin,etc/xcat,sys/class/net/lo,tmp,var/lib/dhclient} - : >"$fixture/cmdline" - sandbox=(env -i PATH=/usr/bin:/bin LC_ALL=C "$bwrap" - --unshare-all --die-with-parent --new-session - --ro-bind / / --tmpfs /run --proc /proc --dev /dev - --bind "$fixture" /run/fixture --bind "$fixture/tmp" /tmp - --bind "$fixture/etc" /etc --ro-bind "$fixture/sys" /sys - --bind "$fixture/var" /var + mkdir -p "$fixture"/{etc/xcat,sys/class/net/lo,var/lib/dhclient} || return + : >"$fixture/cmdline" || return + sandbox+=(--tmpfs /run --bind "$fixture" /run/fixture + --ro-bind "$fixture/sys" /sys --ro-bind "$fixture/cmdline" /proc/cmdline --ro-bind "$source" /run/script --chdir /tmp --setenv PATH /run/fixture/bin:/usr/bin:/bin --setenv LC_ALL C) diff --git a/xCAT-test/bats/helpers/script_sandbox.bash b/xCAT-test/bats/helpers/script_sandbox.bash index c9ed8064df..280dc12f0b 100644 --- a/xCAT-test/bats/helpers/script_sandbox.bash +++ b/xCAT-test/bats/helpers/script_sandbox.bash @@ -2,38 +2,61 @@ load "${BASH_SOURCE[0]%/*}/shell_source.bash" -setup_script_sandbox() +setup_filesystem_sandbox() { [ "$(uname -s)" = Linux ] || skip 'Script filesystem isolation requires Linux' - local bwrap utility executable directory + local bwrap bwrap=$(PATH=/usr/bin:/bin type -P bwrap) || { echo 'Install bubblewrap to run the script tests' >&2 return 1 } fixture="${BATS_TEST_TMPDIR:?bats-core 1.4 or newer is required}/fixture" - mkdir -p "$fixture"/{bin,etc,tmp,var,run} + mkdir -p "$fixture"/{bin,etc,tmp,var,run} || return sandbox=(env -i PATH=/usr/bin:/bin LC_ALL=C "$bwrap" --unshare-all --die-with-parent --new-session --ro-bind / / --proc /proc --dev /dev --bind "$fixture/etc" /etc --bind "$fixture/tmp" /tmp --bind "$fixture/var" /var --bind "$fixture/run" /run - --bind "$fixture" /run/fixture --chdir /tmp + --bind "$fixture" /run/fixture --setenv PATH /usr/bin:/bin --setenv LC_ALL C) +} + +restrict_sandbox_tools() +{ + local directory for directory in /usr/bin /usr/sbin /bin /sbin; do if [ -d "$directory" ] && [ ! -L "$directory" ]; then sandbox+=(--ro-bind "$fixture/bin" "$directory") fi done - for utility in bash sh timeout "$@"; do +} + +stage_sandbox_tools() +{ + local utility executable + for utility in "$@"; do executable=$(PATH=/usr/bin:/bin type -P "$utility") || { echo "Required utility is unavailable: $utility" >&2 return 1 } - cp -L "$executable" "$fixture/bin/$utility" + cp -L "$executable" "$fixture/bin/$utility" || return done if PATH=/usr/bin:/bin type -P coreutils >/dev/null; then - cp -L "$(PATH=/usr/bin:/bin type -P coreutils)" "$fixture/bin/coreutils" + cp -L "$(PATH=/usr/bin:/bin type -P coreutils)" "$fixture/bin/coreutils" || return fi +} + +setup_script_sandbox() +{ + local directory=/tmp + if [ "${1:-}" = --no-chdir ]; then + directory= + shift + fi + setup_filesystem_sandbox || return + [ -z "$directory" ] || sandbox+=(--chdir "$directory") + stage_sandbox_tools bash sh timeout "$@" || return + restrict_sandbox_tools run "${sandbox[@]}" /bin/sh -c 'test ! -e /etc/os-release' if [ "$status" -ne 0 ]; then echo "Cannot isolate script: $output" >&2 diff --git a/xCAT-test/bats/otherpkgs_upgrade_scope.bats b/xCAT-test/bats/otherpkgs_upgrade_scope.bats index d924f932bc..2ffcf22e44 100644 --- a/xCAT-test/bats/otherpkgs_upgrade_scope.bats +++ b/xCAT-test/bats/otherpkgs_upgrade_scope.bats @@ -1,39 +1,12 @@ #!/usr/bin/env bats -load 'helpers/shell_source' +load 'helpers/script_sandbox' setup() { - [ "$(uname -s)" = Linux ] || skip 'otherpkgs filesystem isolation requires Linux' - local utility executable - local utilities=(bash sh basename dirname cat cp expr grep ls mkdir rm uname wc) - local bwrap - bwrap=$(PATH=/usr/bin:/bin type -P bwrap) || { - echo 'Install bubblewrap to run the otherpkgs test' >&2 - return 1 - } + setup_script_sandbox --no-chdir basename dirname cat cp expr grep ls mkdir rm uname wc postscripts=$(repo_path xCAT/postscripts) - fixture="$BATS_TEST_TMPDIR/fixture" - mkdir -p "$fixture/bin" - sandbox=(env -i PATH=/usr/bin:/bin LC_ALL=C "$bwrap" - --unshare-all --die-with-parent --new-session - --ro-bind / / --tmpfs /etc --tmpfs /usr/bin --tmpfs /tmp - --proc /proc --dev /dev --setenv PATH /usr/bin --setenv LC_ALL C) - if PATH=/usr/bin:/bin type -P coreutils >/dev/null; then - utilities+=(coreutils) - fi - for utility in "${utilities[@]}"; do - executable=$(PATH=/usr/bin:/bin type -P "$utility") || { - echo "Required utility is unavailable: $utility" >&2 - return 1 - } - sandbox+=(--ro-bind "$executable" "/usr/bin/$utility") - done - run "${sandbox[@]}" /usr/bin/sh -c 'test ! -e /etc/os-release' - if [ "$status" -ne 0 ]; then - echo "Cannot isolate otherpkgs: $output" >&2 - return 1 - fi + sandbox+=(--setenv PATH /usr/bin) } run_case() @@ -83,10 +56,6 @@ SH local command=("${sandbox[@]}" --bind "$fixture" /tmp/fixture --ro-bind "$postscripts" /tmp/postscripts --chdir /tmp/fixture) - local tool - for tool in logger dpkg rpm mount "$manager"; do - command+=(--ro-bind "$fixture/bin/$tool" "/usr/bin/$tool") - done command+=( --setenv OSVER rhel9 --setenv ARCH x86_64 --setenv UPDATENODE 1 --setenv NFSSERVER package-server --setenv HTTPPORT 80 diff --git a/xCAT-test/bats/routeop.bats b/xCAT-test/bats/routeop.bats index 44c219c7c5..927d1cfdd1 100644 --- a/xCAT-test/bats/routeop.bats +++ b/xCAT-test/bats/routeop.bats @@ -1,21 +1,11 @@ #!/usr/bin/env bats -load 'helpers/shell_source' +load 'helpers/script_sandbox' setup() { - [ "$(uname -s)" = Linux ] || skip 'routeop filesystem isolation requires Linux' - local bwrap utility - bwrap=$(PATH=/usr/bin:/bin type -P bwrap) || { - echo 'Install bubblewrap to run the routeop test' >&2 - return 1 - } - for utility in bash cat dirname grep sed tr uname; do - PATH=/usr/bin:/bin type -P "$utility" >/dev/null || { - echo "Required utility is unavailable: $utility" >&2 - return 1 - } - done + setup_script_sandbox --no-chdir cat dirname grep sed tr uname + local utility postscripts=$(repo_path xCAT/postscripts) for utility in routeop xcatlib.sh; do [ -r "$postscripts/$utility" ] || { @@ -23,7 +13,6 @@ setup() return 1 } done - fixture="$BATS_TEST_TMPDIR/fixture" mkdir -p "$fixture/bin" "$fixture/etc/sysconfig/network" printf '%s\n' SLE VERSION=15 >"$fixture/etc/SUSE-brand" saved_routes="$fixture/etc/sysconfig/network/routes" @@ -65,13 +54,9 @@ printf '%s\n' "unexpected nmcli $*" >>/tmp/fixture/commands exit 97 SH chmod +x "$fixture/bin/ip" "$fixture/bin/logger" "$fixture/bin/nmcli" - sandbox=(env -i PATH=/usr/bin:/bin LC_ALL=C "$bwrap" - --unshare-all --die-with-parent --new-session - --ro-bind / / --tmpfs /tmp --tmpfs /run --proc /proc --dev /dev - --bind "$fixture" /tmp/fixture --bind "$fixture/etc" /etc + sandbox+=(--bind "$fixture" /tmp/fixture --ro-bind "$postscripts" /tmp/postscripts --chdir /tmp/fixture - --setenv PATH /tmp/fixture/bin:/usr/bin:/bin --setenv LC_ALL C - --setenv OSVER sles15) + --setenv PATH /tmp/fixture/bin:/usr/bin:/bin --setenv OSVER sles15) run "${sandbox[@]}" /bin/sh -c 'test -f /etc/SUSE-brand && test ! -e /etc/os-release' if [ "$status" -ne 0 ]; then echo "Cannot isolate routeop: $output" >&2 diff --git a/xCAT-test/bats/sandbox_helpers.bats b/xCAT-test/bats/sandbox_helpers.bats new file mode 100644 index 0000000000..a6207a9e05 --- /dev/null +++ b/xCAT-test/bats/sandbox_helpers.bats @@ -0,0 +1,53 @@ +#!/usr/bin/env bats + +load 'helpers/genesis_sandbox' + +@test "script sandbox defaults to a private working directory" { + setup_script_sandbox pwd + run "${sandbox[@]}" /bin/pwd + [ "$status" -eq 0 ] + [ "$output" = /tmp ] +} + +@test "script sandbox lets adapters choose the working directory" { + setup_script_sandbox --no-chdir pwd + run "${sandbox[@]}" --chdir /run/fixture /bin/pwd + [ "$status" -eq 0 ] + [ "$output" = /run/fixture ] +} + +@test "script sandbox exposes only staged tools and private writable directories" { + setup_script_sandbox cat + printf 'private\n' >"$fixture/etc/marker" + run "${sandbox[@]}" /bin/sh -c ' + test ! -e /etc/os-release && test ! -x /usr/bin/id && + test -x /bin/sh && test -x /usr/bin/cat && + cat /etc/marker && + printf tmp > /tmp/marker && printf var > /var/marker && + printf run > /run/marker + ' + [ "$status" -eq 0 ] + [ "$output" = private ] + [ "$(cat "$fixture/tmp/marker")" = tmp ] + [ "$(cat "$fixture/var/marker")" = var ] + [ "$(cat "$fixture/run/marker")" = run ] +} + +@test "tool staging rejects an unavailable command" { + setup_script_sandbox + run stage_sandbox_tools xcat_fixture_missing_command + [ "$status" -ne 0 ] + [[ "$output" = *'Required utility is unavailable: xcat_fixture_missing_command'* ]] +} + +@test "Genesis retains host tools and synthetic kernel inputs" { + setup_genesis_sandbox doxcat + printf 'fixture command line\n' >"$fixture/cmdline" + run "${sandbox[@]}" /bin/sh -c ' + test -x /usr/bin/id && test -r /run/script && + test -d /sys/class/net/lo && test ! -e /sys/kernel && + test ! -e /etc/os-release && cat /proc/cmdline + ' + [ "$status" -eq 0 ] + [ "$output" = 'fixture command line' ] +} diff --git a/xCAT-test/integration/dhcp_isc_ipxe_leases.t b/xCAT-test/integration/dhcp_isc_ipxe_leases.t index 3e6d920d3b..009aadc5b2 100644 --- a/xCAT-test/integration/dhcp_isc_ipxe_leases.t +++ b/xCAT-test/integration/dhcp_isc_ipxe_leases.t @@ -11,6 +11,7 @@ use lib "$FindBin::Bin/../../perl-xCAT"; use lib "$FindBin::Bin/lib"; use File::Spec; +use File::Slurper qw(read_binary write_binary); use File::Temp qw(tempdir); use Test::More; use Time::HiRes qw(sleep); @@ -56,8 +57,7 @@ my $secret = 'eGNhdC10ZXN0LW9tYXBpLXNlY3JldC0wMQ=='; my $port = 7911; my $configuration = File::Spec->catfile( $directory, 'dhcpd.conf' ); { - open( my $fh, '>', $configuration ) or die "Cannot create $configuration: $!"; - print {$fh} "option conf-file code 209 = text;\n", + write_binary($configuration, join('', "option conf-file code 209 = text;\n", "option space gpxe;\n", "option gpxe-encap-opts code 175 = encapsulate gpxe;\n", "option gpxe.bus-id code 177 = string;\n", @@ -75,17 +75,14 @@ my $configuration = File::Spec->catfile( $directory, 'dhcpd.conf' ); net => '192.0.2.0', prefix => 24, ) }, - "}\n"; - close($fh) or die "Cannot close $configuration: $!"; + "}\n")); } sub omshell { my ($commands) = @_; my $input = File::Spec->catfile( $directory, 'omshell.in' ); - open( my $fh, '>', $input ) or die "Cannot create $input: $!"; - print {$fh} xCAT::DHCP::OmapiPolicy->omshell_preamble( $settings, secret => $secret, port => $port ), - "connect\n", $commands; - close($fh) or die "Cannot close $input: $!"; + write_binary($input, join('', xCAT::DHCP::OmapiPolicy->omshell_preamble( $settings, secret => $secret, port => $port ), + "connect\n", $commands)); return scalar `ip netns exec $namespace $settings->{omshell_path} < $input 2>&1`; } @@ -103,6 +100,14 @@ sub start_dhcpd { BAIL_OUT("dhcpd did not open OMAPI port $port"); } +sub recorded_content { + my ($path) = @_; + local $@; + my $contents = eval { read_binary($path) }; + warn $@ if $@; + return $contents // ''; +} + my %common = ( netboot => 'ipxe', next_server => '192.0.2.1', portsuffix => '' ); my @hosts = ( [ bios => { currstate => 'install rhels9' } ], @@ -112,8 +117,7 @@ my @hosts = ( [ winshell => { uefi => 2, currstate => 'winshell' } ], ); -open( my $fresh, '>', $leases ) or die "Cannot create $leases: $!"; -close($fresh); +write_binary($leases, ''); start_dhcpd("$directory/dhcpd-first.log"); my $commands = ''; @@ -130,7 +134,7 @@ unlike( $created, qr/can't|error|eof in string|unknown token|not connected/i, 'O or diag($created); stop_daemons( \%children ); -my $saved = do { local ( @ARGV, $/ ) = ($leases); <> } // ''; +my $saved = recorded_content($leases); for my $host (@hosts) { like( $saved, qr/^host cn-$host->[0] \{$/m, "dhcpd.leases holds the $host->[0] host" ); } @@ -146,6 +150,6 @@ for my $host (@hosts) { like( omshell("new host\nset name = \"cn-$host->[0]\"\nopen\n"), qr/^ip-address = /m, "dhcpd restarts with the $host->[0] host" ); } -unlike( do { local ( @ARGV, $/ ) = ($restart_log); <> } // '', qr/ line \d+: /, 'the restart reports no parse error' ); +unlike( recorded_content($restart_log), qr/ line \d+: /, 'the restart reports no parse error' ); done_testing(); diff --git a/xCAT-test/integration/openeuler_package_postscripts.t b/xCAT-test/integration/openeuler_package_postscripts.t index eaf372829a..81eb711a43 100644 --- a/xCAT-test/integration/openeuler_package_postscripts.t +++ b/xCAT-test/integration/openeuler_package_postscripts.t @@ -1,6 +1,7 @@ #!/usr/bin/env perl use strict; use warnings; +use File::Slurper qw(read_binary write_binary); use FindBin; use File::Copy qw(copy); use File::Path qw(make_path); @@ -22,7 +23,7 @@ unless (-x "$postscripts/otherpkgs") { my $dir = tempdir(CLEANUP => 1); make_path("$dir/bin"); -write_text("$dir/bin/dnf", <<'SH'); +write_binary("$dir/bin/dnf", <<'SH'); #!/bin/sh printf '%s\n' "$*" >> "$DNF_TRACE" case " $* " in @@ -31,7 +32,7 @@ case " $* " in esac exit 0 SH -write_text("$dir/bin/rpm", <<'SH'); +write_binary("$dir/bin/rpm", <<'SH'); #!/bin/sh case "$1" in --version) echo 'RPM version 4.18.2'; exit 0 ;; @@ -40,10 +41,10 @@ printf '%s\n' "$*" >> "$RPM_TRACE" exit 1 SH for my $name (qw(logger mount)) { - write_text("$dir/bin/$name", "#!/bin/sh\nexit 0\n"); + write_binary("$dir/bin/$name", "#!/bin/sh\nexit 0\n"); } -write_text("$dir/bin/dpkg", "#!/bin/sh\nexit 1\n"); -write_text("$dir/bin/wget", "#!/bin/sh\nprintf 'wget\\n' >> \"\$RPM_TRACE\"\nexit 1\n"); +write_binary("$dir/bin/dpkg", "#!/bin/sh\nexit 1\n"); +write_binary("$dir/bin/wget", "#!/bin/sh\nprintf 'wget\\n' >> \"\$RPM_TRACE\"\nexit 1\n"); chmod 0755, glob("$dir/bin/*"); my $wrapper = "$dir/run"; copy("$FindBin::Bin/fixtures/postscript-root.sh", $wrapper) or die "copy isolation wrapper: $!"; @@ -123,20 +124,7 @@ sub run_case { my $output = do { local $/; <$pipe> } // ''; close($pipe); my $rc = (($? & 127) ? 128 + ($? & 127) : $? >> 8); - my $repos = join('', map { read_text($_) } sort glob("$run/repos/*.repo")); - return ($rc, $output, $repos, -f "$run/dnf" ? read_text("$run/dnf") : '', - -f "$run/rpm" ? read_text("$run/rpm") : ''); -} - -sub read_text { - my ($path) = @_; - open(my $file, '<', $path) or die "read $path: $!"; - return do { local $/; <$file> }; -} - -sub write_text { - my ($path, $text) = @_; - open(my $file, '>', $path) or die "write $path: $!"; - print {$file} $text or die "write $path: $!"; - close($file) or die "close $path: $!"; + my $repos = join('', map { read_binary($_) } sort glob("$run/repos/*.repo")); + return ($rc, $output, $repos, -f "$run/dnf" ? read_binary("$run/dnf") : '', + -f "$run/rpm" ? read_binary("$run/rpm") : ''); } diff --git a/xCAT-test/integration/openeuler_postscript_repositories.t b/xCAT-test/integration/openeuler_postscript_repositories.t index 05761010ec..d98d2482dc 100644 --- a/xCAT-test/integration/openeuler_postscript_repositories.t +++ b/xCAT-test/integration/openeuler_postscript_repositories.t @@ -1,6 +1,7 @@ #!/usr/bin/env perl use strict; use warnings; +use File::Slurper qw(read_binary write_binary); use FindBin; use File::Copy qw(copy); use File::Path qw(make_path); @@ -52,7 +53,7 @@ for my $package ( ) { my ($name, $version, $requires, $repo) = @$package; my $spec = "$dir/$name-$version.spec"; - write_text($spec, <<"SPEC"); + write_binary($spec, <<"SPEC"); Name: $name Version: $version Release: 1 @@ -81,18 +82,18 @@ for my $repo (qw(old os vendor other/native)) { copy("$dir/key.asc", "$dir/fixtures/$repo/repodata/repomd.xml.key") or die "copy key: $!"; } copy("$FindBin::Bin/fixtures/dnf.pl", "$dir/bin/dnf") or die "copy DNF adapter: $!"; -write_text("$dir/bin/mount", <<'SH'); +write_binary("$dir/bin/mount", <<'SH'); #!/bin/sh printf '%s on %s type nfs\n' "$NFSSERVER" "$INSTALLDIR" SH -write_text("$dir/bin/rpm", <<'SH'); +write_binary("$dir/bin/rpm", <<'SH'); #!/bin/sh case "$1" in --version) exec /usr/bin/rpm "$@" ;; esac printf '%s\n' "$*" >> "$RPM_TRACE" exit 79 SH for my $name (qw(logger dpkg wget)) { - write_text("$dir/bin/$name", "#!/bin/sh\nexit 1\n"); + write_binary("$dir/bin/$name", "#!/bin/sh\nexit 1\n"); } copy("$FindBin::Bin/fixtures/postscript-root.sh", "$dir/run") or die "copy isolation wrapper: $!"; chmod 0755, glob("$dir/bin/*"), "$dir/run"; @@ -177,12 +178,12 @@ sub run_case { make_path("$run/repos", "$run/root", "$run/media"); my $key = $options{native_key} ? '/etc/pki/rpm-gpg/RPM-GPG-KEY-openEuler' : "$dir/key.asc"; if ($options{empty_key}) { - write_text("$run/empty-key", ''); + write_binary("$run/empty-key", ''); $key = "$run/empty-key"; } my $vendor = '[publisher]' . "\nname=publisher\nenabled=1\nskip_if_unavailable=False\ngpgcheck=1\ngpgkey=file://$dir/key.asc\nbaseurl=file://" . ($options{vendor_available} ? "$dir/fixtures/vendor" : "$run/unavailable") . "\n"; - write_text("$run/repos/openEuler.repo", $vendor); + write_binary("$run/repos/openEuler.repo", $vendor); if ($options{seed_old}) { my ($rc, $output) = capture('/usr/bin/rpm', '--root', "$run/root", '--import', "$dir/key.asc"); die $output if $rc; @@ -237,13 +238,5 @@ sub capture { sub read_text { my ($path) = @_; return '' unless -f $path; - open(my $file, '<', $path) or die "read $path: $!"; - return do { local $/; <$file> }; -} - -sub write_text { - my ($path, $text) = @_; - open(my $file, '>', $path) or die "write $path: $!"; - print {$file} $text or die "write $path: $!"; - close($file) or die "close $path: $!"; + return read_binary($path); } diff --git a/xCAT-test/lib/XCAT/Test/IPMISDR.pm b/xCAT-test/lib/XCAT/Test/IPMISDR.pm new file mode 100644 index 0000000000..7c5e44a524 --- /dev/null +++ b/xCAT-test/lib/XCAT/Test/IPMISDR.pm @@ -0,0 +1,96 @@ +package XCAT::Test::IPMISDR; + +use strict; +use warnings; +## no critic (Modules::RequireFilenameMatchesPackage, TestingAndDebugging::ProhibitNoStrict, TestingAndDebugging::ProhibitNoWarnings) +no warnings qw(once redefine); +use Exporter qw(import); +use XCAT::Test::File qw(repo_path); + +our @EXPORT_OK = qw(load_ipmi_plugin new_session); + +# Install guards before the plugin compiles its filesystem operations. +BEGIN { + for my $module (qw( + xCAT::GlobalDef xCAT_monitoring::monitorctrl xCAT::IPMI + xCAT::BMCUtils xCAT::PasswordUtils xCAT::Utils xCAT::TableUtils + xCAT::IMMUtils xCAT::ServiceNodeUtils xCAT::NetworkUtils xCAT::Usage + xCAT::data::ibmhwtypes xCAT::data::ibmleds + xCAT::data::ipmigenericevents xCAT::data::ipmisensorevents + IBM::EnergyManager + )) { + (my $file = $module) =~ s{::}{/}g; + $INC{"$file.pm"} = __FILE__; + no strict 'refs'; + *{"${module}::import"} = sub { }; + } + + package xCAT::SvrUtils; + our @messages; + sub import { } + sub sendmsg { push @messages, { text => $_[0], node => $_[2] }; } + $INC{'xCAT/SvrUtils.pm'} = __FILE__; + + package xCAT::SPD; + sub import { + my $caller = caller; + no strict 'refs'; + *{"${caller}::decode_spd"} = sub { return; }; + } + $INC{'xCAT/SPD.pm'} = __FILE__; + + # Load File::Temp before this fixture; the plugin needs a compile-time File::Path stub. + package File::Path; + sub import { + my $caller = caller; + no strict 'refs'; + *{"${caller}::mkpath"} = sub { return; }; + } + $INC{'File/Path.pm'} = __FILE__; + + package Thread; + sub import { + my $caller = caller; + no strict 'refs'; + *{"${caller}::yield"} = sub { return; }; + } + $INC{'Thread.pm'} = __FILE__; + + package LWP; + our $VERSION = 5.64; + sub import { } + $INC{'LWP.pm'} = __FILE__; + + package HTTP::Request::Common; + sub import { + my $caller = caller; + no strict 'refs'; + *{"${caller}::GET"} = sub { return; }; + *{"${caller}::POST"} = sub { return; }; + } + $INC{'HTTP/Request/Common.pm'} = __FILE__; + + package XCAT::Test::IPMISDR; + *CORE::GLOBAL::chmod = sub (@) { return 1; }; +} + +sub load_ipmi_plugin { + $ENV{XCATROOT} = repo_path('xCAT-server'); + my $plugin = repo_path('xCAT-server/lib/xcat/plugins/ipmi.pm'); + do $plugin or die $@ || "Unable to load $plugin: $!"; + return; +} + +sub new_session { + return bless { calls => [] }, 'XCAT::Test::IPMISDR::Session'; +} + +package XCAT::Test::IPMISDR::Session; + +sub subcmd { + my ($self, %args) = @_; + push @{ $self->{calls} }, \%args; + return; +} + +1; diff --git a/xCAT-test/lib/XCAT/Test/ImageSandbox.pm b/xCAT-test/lib/XCAT/Test/ImageSandbox.pm index aed1d5f2f1..ced69d0025 100644 --- a/xCAT-test/lib/XCAT/Test/ImageSandbox.pm +++ b/xCAT-test/lib/XCAT/Test/ImageSandbox.pm @@ -35,19 +35,25 @@ sub read { return read_binary("$self->{root}/$path"); } -sub run { - my ($self, @command) = @_; +sub sandbox_command { + my ($self, $xcatroot) = @_; my @sandbox = ('bwrap', '--unshare-all', '--die-with-parent', '--new-session', '--tmpfs', '/', (map { ('--ro-bind', $_, $_) } grep { -d $_ } qw(/usr /bin /sbin /lib /lib64)), '--proc', '/proc', '--dev', '/dev', '--dir', '/run', '--dir', '/sys', '--dir', '/opt', (map { ('--bind', "$self->{root}/$_", "/$_") } qw(etc install tmp work)), '--ro-bind', repo_path('.'), '/repo', '--chdir', '/work', '--setenv', 'PATH', '/work/bin:/usr/bin:/bin:/usr/sbin:/sbin', - '--setenv', 'LC_ALL', 'C', '--setenv', 'XCATROOT', '/repo/xCAT-server', + '--setenv', 'LC_ALL', 'C', '--setenv', 'XCATROOT', $xcatroot, '--setenv', 'XCATCFG', 'SQLite:/work/db', '--setenv', 'PERL5LIB', '/repo/perl-xCAT:/repo/xCAT-server/lib/perl'); push @sandbox, '--ro-bind', '/etc/alternatives', '/etc/alternatives' if -d '/etc/alternatives'; push @sandbox, @{ $self->{mounts} || [] }; + return @sandbox; +} + +sub run { + my ($self, @command) = @_; + my @sandbox = $self->sandbox_command('/repo/xCAT-server'); local %ENV = (PATH => '/usr/bin:/bin:/usr/sbin:/sbin'); return XCAT::Test::Lifecycle::command(@sandbox, 'timeout', '45', @command); } diff --git a/xCAT-test/lib/XCAT/Test/Sandbox.pm b/xCAT-test/lib/XCAT/Test/Sandbox.pm index 9bcc0734e2..fb26382aa4 100644 --- a/xCAT-test/lib/XCAT/Test/Sandbox.pm +++ b/xCAT-test/lib/XCAT/Test/Sandbox.pm @@ -7,7 +7,7 @@ use File::Path qw(make_path); use File::Temp qw(tempdir); use XCAT::Test::Process qw(run_command); -our @EXPORT_OK = qw(sandbox_root sandbox_run); +our @EXPORT_OK = qw(sandbox_root sandbox_command sandbox_run); sub sandbox_root { my $root = tempdir(CLEANUP => 1); @@ -15,9 +15,10 @@ sub sandbox_root { return $root; } -sub sandbox_run { - my ($root, @command) = @_; - my $options = ref($command[0]) eq 'HASH' ? shift @command : {}; +# Return arguments so raw-status callers can keep their own capture policy. +sub sandbox_command { + my ($root, $options) = @_; + $options ||= {}; my $bwrap = -x '/usr/bin/bwrap' ? '/usr/bin/bwrap' : '/bin/bwrap'; die 'Install bubblewrap to run this test' unless -x $bwrap; my @sandbox = ($bwrap, '--unshare-all', '--die-with-parent', '--new-session', @@ -25,12 +26,17 @@ sub sandbox_run { '--setenv', 'PATH', '/fixture/bin:/usr/bin:/bin', '--setenv', 'LC_ALL', 'C', '--bind', $root, '/fixture', '--chdir', '/fixture'); for my $directory (qw(/usr /bin /sbin /lib /lib64)) { - push @sandbox, '--ro-bind', $directory, $directory if -d $directory; + if ($options->{preserve_links} && -l $directory) { + push @sandbox, '--symlink', readlink($directory), $directory; + } elsif (-d $directory) { + push @sandbox, '--ro-bind', $directory, $directory; + } } - for my $mount (qw(boot etc target tmp)) { + for my $mount (@{$options->{directories} // [qw(boot etc target tmp)]}) { push @sandbox, '--bind', "$root/$mount", "/$mount"; } push @sandbox, '--bind', "$root/log", '/var/log'; + push @sandbox, map { ('--tmpfs', $_) } @{$options->{tmpfs} // []}; push @sandbox, '--ro-bind', '/etc/alternatives', '/etc/alternatives' if -d '/etc/alternatives'; my @mounts; for my $kind (qw(read_only writable)) { @@ -41,9 +47,16 @@ sub sandbox_run { for my $mount (sort { length($a->[2]) <=> length($b->[2]) || $a->[2] cmp $b->[2] } @mounts) { push @sandbox, @$mount; } - for my $name (keys %{$options->{env} // {}}) { + for my $name (sort keys %{$options->{env} // {}}) { push @sandbox, '--setenv', $name, $options->{env}{$name}; } + return @sandbox; +} + +sub sandbox_run { + my ($root, @command) = @_; + my $options = ref($command[0]) eq 'HASH' ? shift @command : {}; + my @sandbox = sandbox_command($root, $options); local %ENV; return run_command(@sandbox, '/usr/bin/timeout', '--kill-after=5', '45', @command); } diff --git a/xCAT-test/lib/XCAT/Test/UbuntuImage.pm b/xCAT-test/lib/XCAT/Test/UbuntuImage.pm index 9f64b51197..f2fc6f8bd7 100644 --- a/xCAT-test/lib/XCAT/Test/UbuntuImage.pm +++ b/xCAT-test/lib/XCAT/Test/UbuntuImage.pm @@ -4,12 +4,9 @@ use strict; use warnings; use Capture::Tiny qw(capture_merged); -use File::Basename qw(dirname); use File::Path qw(make_path); -use File::Slurper qw(read_binary write_binary); -use File::Temp qw(tempdir); use JSON::PP qw(encode_json); -use XCAT::Test::File qw(repo_path); +use parent 'XCAT::Test::ImageSandbox'; sub new { my ($class) = @_; @@ -17,43 +14,12 @@ sub new { die "Ubuntu image tests require $tool\n" unless grep { -x "$_/$tool" } qw(/usr/bin /bin /usr/sbin /sbin); } - my $self = bless { root => tempdir(CLEANUP => 1) }, $class; - make_path(map { "$self->{root}/$_" } qw(etc install tmp work/bin work/db)); - return $self; -} - -sub write { - my ($self, $file, $content) = @_; - my $path = "$self->{root}/$file"; - make_path(dirname($path)); - write_binary($path, $content); - return $path; -} - -sub read { - my ($self, $file) = @_; - return read_binary("$self->{root}/$file"); + return $class->SUPER::new(); } sub run { my ($self, @command) = @_; - my $root = $self->{root}; - my @sandbox = ( - 'bwrap', '--unshare-all', '--die-with-parent', '--new-session', - '--tmpfs', '/', - (map { ('--ro-bind', $_, $_) } grep { -d $_ } qw(/usr /bin /sbin /lib /lib64)), - '--dev', '/dev', '--proc', '/proc', '--dir', '/run', '--dir', '/sys', - '--dir', '/opt', - '--bind', "$root/etc", '/etc', '--bind', "$root/install", '/install', - '--bind', "$root/tmp", '/tmp', '--bind', "$root/work", '/work', - '--ro-bind', repo_path('.'), '/repo', '--chdir', '/work', - '--setenv', 'PATH', '/work/bin:/usr/bin:/bin:/usr/sbin:/sbin', - '--setenv', 'LC_ALL', 'C', '--setenv', 'XCATROOT', '/repo', - '--setenv', 'XCATCFG', 'SQLite:/work/db', - '--setenv', 'PERL5LIB', '/repo/perl-xCAT:/repo/xCAT-server/lib/perl', - ); - push @sandbox, '--ro-bind', '/etc/alternatives', '/etc/alternatives' - if -d '/etc/alternatives'; + my @sandbox = $self->sandbox_command('/repo'); my ($output, $status) = capture_merged { local %ENV = (PATH => '/usr/bin:/bin:/usr/sbin:/sbin'); system(@sandbox, 'timeout', '45', @command); diff --git a/xCAT-test/native/README.md b/xCAT-test/native/README.md index 273f76cb8c..e965738750 100644 --- a/xCAT-test/native/README.md +++ b/xCAT-test/native/README.md @@ -17,6 +17,11 @@ It can run as root or an ordinary user with user namespaces enabled. This case checks service policy and ordering; it does not boot or reinstall an OS. The client steps cannot access the source tree or the server postscripts directory. +`image_fixture_contract.t` checks the shared image fixture's file contents, +mount isolation and caller-specific results. UbuntuImage returns raw wait +status and merged output; ImageSandbox returns a decoded status and separate +output streams. CI runs this case and `postinstall_bootstrap.t` explicitly. + ## Ubuntu media and image fixtures The pull-request workflow runs these four tests explicitly: diff --git a/xCAT-test/native/buildrpms_openeuler.t b/xCAT-test/native/buildrpms_openeuler.t index ffc3ca5435..b40b4a0f20 100644 --- a/xCAT-test/native/buildrpms_openeuler.t +++ b/xCAT-test/native/buildrpms_openeuler.t @@ -1,6 +1,7 @@ #!/usr/bin/env perl use strict; use warnings; +use File::Slurper qw(read_binary write_binary); use File::Copy qw(copy); use File::Path qw(make_path); use File::Temp qw(tempdir); @@ -16,7 +17,7 @@ my $wrapper = "$FindBin::Bin/fixtures/buildrpms-namespace.sh"; my $root = tempdir(CLEANUP => 1); my $driver = "$root/driver.pl"; -write_file($driver, <<'PERL'); +write_binary($driver, <<'PERL'); BEGIN { require Parallel::ForkManager; no warnings 'redefine'; @@ -96,21 +97,21 @@ sub run_builder { copy(repo_path('build-utils/lib/XCAT/BuildUtils.pm'), "$fixture/build-utils/lib/XCAT/BuildUtils.pm") or die $!; copy(repo_path('build-utils/lib/XCAT/NFSLock.pm'), "$fixture/build-utils/lib/XCAT/NFSLock.pm") or die $!; copy($driver, "$fixture/driver.pl") or die $!; - write_file("$fixture/Version", "2.18.0\n"); - write_file("$fixture/Gitepoch", "1756000000\n"); - write_file("$fixture/native-input/buildinfo.txt", "BUILD_TARGET=openeuler-24.03sp3-x86_64\n"); - write_file("$fixture/os-release", "ID=$id\nVERSION=\"$version\"\nVERSION_ID=$version_id\n"); + write_binary("$fixture/Version", "2.18.0\n"); + write_binary("$fixture/Gitepoch", "1756000000\n"); + write_binary("$fixture/native-input/buildinfo.txt", "BUILD_TARGET=openeuler-24.03sp3-x86_64\n"); + write_binary("$fixture/os-release", "ID=$id\nVERSION=\"$version\"\nVERSION_ID=$version_id\n"); for my $target ('openeuler-24.03sp3-x86_64', 'openeuler-24.03-ppc64le') { my $subdir = openeuler_repo_subdir($target); for my $key (['core', "$fixture/dist/$target/rpms"], ['dep', "$fixture/dep/$subdir"]) { make_path("$key->[1]/repodata"); - write_file("$key->[1]/repodata/repomd.xml.key", 'existing exported key') + write_binary("$key->[1]/repodata/repomd.xml.key", 'existing exported key') unless ($ENV{BUILD_MISSING_KEY} || '') eq $key->[0]; } } - write_file("$fixture/bin/dnf", "#!/bin/sh\nprintf '%s\\n' \"\$*\" >> \"\$BUILD_FIXTURE/commands\"\nexit \"\${BUILD_DNF_FAILURE:-0}\"\n"); - write_file("$fixture/bin/systemctl", "#!/bin/sh\nexit 0\n"); - write_file("$fixture/bin/rpmdev-setuptree", "#!/bin/sh\nexit 0\n"); + write_binary("$fixture/bin/dnf", "#!/bin/sh\nprintf '%s\\n' \"\$*\" >> \"\$BUILD_FIXTURE/commands\"\nexit \"\${BUILD_DNF_FAILURE:-0}\"\n"); + write_binary("$fixture/bin/systemctl", "#!/bin/sh\nexit 0\n"); + write_binary("$fixture/bin/rpmdev-setuptree", "#!/bin/sh\nexit 0\n"); chmod 0755, map {"$fixture/bin/$_"} qw(dnf systemctl rpmdev-setuptree); local %ENV = (%ENV, HOME => "$fixture/home", BUILD_FIXTURE => $fixture, BUILD_ARCH => $arch, PATH => "$fixture/bin:$ENV{PATH}"); my $pid = fork(); @@ -129,15 +130,8 @@ sub run_builder { && !$ENV{BUILD_STOP} && !grep {$_ eq '--merge-core-repos'} @args; return $result; } -sub write_file { - my ($path, $contents) = @_; - open(my $fh, '>', $path) or die "$path: $!"; - print {$fh} $contents; - close($fh) or die $!; -} sub read_file { my ($path) = @_; return '' unless -f $path; - open(my $fh, '<', $path) or die $!; - return do {local $/; scalar <$fh>} || ''; + return read_binary($path) || ''; } diff --git a/xCAT-test/native/detect_dhcpd_tcpdump_lookup.t b/xCAT-test/native/detect_dhcpd_tcpdump_lookup.t index 5058785445..970656af34 100644 --- a/xCAT-test/native/detect_dhcpd_tcpdump_lookup.t +++ b/xCAT-test/native/detect_dhcpd_tcpdump_lookup.t @@ -5,6 +5,7 @@ use warnings; use Config; use File::Path qw(make_path); use File::Spec; +use File::Slurper qw(read_binary write_binary); use File::Temp qw(tempdir); use FindBin; use Test::More; @@ -47,9 +48,7 @@ delete @ENV{qw(PERL5LIB PERLLIB PERL5OPT)}; sub write_script { my ( $path, $body, $interpreter ) = @_; $interpreter ||= '/bin/sh'; - open( my $fh, '>', $path ) or die "$path: $!"; - print {$fh} "#!$interpreter\n$body"; - close($fh); + write_binary($path, "#!$interpreter\n$body"); chmod 0755, $path; } @@ -87,10 +86,7 @@ sub run_with_path { } sub recorded_invocation { - open( my $fh, '<', $marker ) or return; - chomp( my @lines = <$fh> ); - close($fh); - return @lines; + return slurp_lines($marker); } my $plain = fixture_bin(); @@ -203,9 +199,9 @@ sub run_isolated_status { sub slurp_lines { my ($path) = @_; - open( my $fh, '<', $path ) or return; - chomp( my @lines = <$fh> ); - close($fh); + my $contents = eval { read_binary($path) }; + return if $@; + chomp( my @lines = split /(?<=\n)/, $contents ); return @lines; } diff --git a/xCAT-test/native/genesis_console.py b/xCAT-test/native/genesis_console.py index fa6769c477..b477cf763a 100644 --- a/xCAT-test/native/genesis_console.py +++ b/xCAT-test/native/genesis_console.py @@ -7,6 +7,7 @@ from pathlib import Path import subprocess import tempfile import unittest +from genesis_console_fixture import console_paths ROOT = Path(__file__).resolve().parents[2] SOURCE = ROOT / "xCAT-genesis-base/oe/meta-xcat-genesis/recipes-core/xcat-genesis-console/files/xcat-genesis-console" @@ -28,9 +29,7 @@ class ConsoleBuild(unittest.TestCase): binary = stage / "usr/sbin/xcat-genesis-console" self.assertTrue(os.access(binary, os.X_OK)) environment = {"PATH": os.environ["PATH"], "LC_ALL": "C"} - for name in ("CMDLINE_FILE", "UPTIME_FILE", "OS_RELEASE", "STATUS_DIR", "STATE_FILE", - "DESTINY_FILE", "RESPONSE_FILE", "SYS_ROOT", "PROC_ROOT", "EXTENSION_DIR", "PROVIDER_DIR"): - environment["XCAT_" + name] = str(root / name.lower()) + environment.update(console_paths(root)) Path(environment["XCAT_RESPONSE_FILE"]).write_text("XCAT_NODE_NAME=console-test-node\n") result = subprocess.run([str(binary), "--once"], env=environment, text=True, capture_output=True, timeout=10, check=True) diff --git a/xCAT-test/native/genesis_console_dialogs.py b/xCAT-test/native/genesis_console_dialogs.py index 6384807770..a6a9541327 100644 --- a/xCAT-test/native/genesis_console_dialogs.py +++ b/xCAT-test/native/genesis_console_dialogs.py @@ -18,6 +18,7 @@ import unittest import uuid import pyte +from genesis_console_fixture import console_paths ROOT = Path(__file__).resolve().parents[2] @@ -44,9 +45,7 @@ class ConsoleTerminal(unittest.TestCase): environment = {"PATH": os.environ["PATH"], "LC_ALL": "C.UTF-8", "TERM": "xterm", "NEWT_COLORS": "listbox=black,white\nactlistbox=black,white\n" "sellistbox=white,red\nactsellistbox=white,red"} - for name in ("CMDLINE_FILE", "UPTIME_FILE", "OS_RELEASE", "STATUS_DIR", "STATE_FILE", - "DESTINY_FILE", "RESPONSE_FILE", "SYS_ROOT", "PROC_ROOT", "EXTENSION_DIR", "PROVIDER_DIR"): - environment["XCAT_" + name] = str(root / name.lower()) + environment.update(console_paths(root)) Path(environment["XCAT_RESPONSE_FILE"]).write_text("XCAT_NODE_NAME=dialog-test-node\n") self.master, slave = pty.openpty() self.addCleanup(os.close, self.master) diff --git a/xCAT-test/native/genesis_console_fixture.py b/xCAT-test/native/genesis_console_fixture.py new file mode 100644 index 0000000000..ff92d0cbfb --- /dev/null +++ b/xCAT-test/native/genesis_console_fixture.py @@ -0,0 +1,9 @@ +"""Private filesystem paths for Genesis console tests.""" + + +def console_paths(root): + return { + "XCAT_" + name: str(root / name.lower()) + for name in ("CMDLINE_FILE", "UPTIME_FILE", "OS_RELEASE", "STATUS_DIR", "STATE_FILE", + "DESTINY_FILE", "RESPONSE_FILE", "SYS_ROOT", "PROC_ROOT", "EXTENSION_DIR", "PROVIDER_DIR") + } diff --git a/xCAT-test/native/image_fixture_contract.t b/xCAT-test/native/image_fixture_contract.t new file mode 100644 index 0000000000..1d9826626a --- /dev/null +++ b/xCAT-test/native/image_fixture_contract.t @@ -0,0 +1,42 @@ +#!/usr/bin/env perl +use strict; +use warnings; +use FindBin; +use lib "$FindBin::Bin/../lib"; +use Test::More; +use XCAT::Test::ImageSandbox; +use XCAT::Test::UbuntuImage; + +plan skip_all => 'image namespaces require Linux' unless $^O eq 'linux'; + +for my $class ('XCAT::Test::ImageSandbox', 'XCAT::Test::UbuntuImage') { + subtest $class => sub { + my $image = $class->new(); + for my $bytes ('', '0', "\0\xff\r\n") { + $image->write('work/nested/bytes', $bytes); + is($image->read('work/nested/bytes'), $bytes, 'fixture I/O preserves bytes'); + } + my $read = eval { $image->read('work/missing'); 1 }; + ok(!$read && $@, 'a missing required file fails'); + my @result = $image->run('/bin/sh', '-c', + 'printf "%s" "$XCATROOT"; printf error >&2; exit 7'); + if ($class eq 'XCAT::Test::UbuntuImage') { + is_deeply(\@result, [7 << 8, '/repoerror'], 'retains raw status and merged output'); + } else { + is_deeply(\@result, [7, '/repo/xCAT-server', 'error'], 'retains decoded status and separate streams'); + } + @result = $image->run('/bin/sh', '-c', + 'test ! -e /etc/os-release && test -r /repo/Version && ' + . '! test -w /repo && printf private > /etc/fixture-marker'); + is($result[0], 0, 'host configuration is hidden and the repository is read-only'); + is($image->read('etc/fixture-marker'), 'private', 'writes reach only the fixture'); + }; +} + +my $image = XCAT::Test::ImageSandbox->new(); +$image->write('work/mounted', 'extra mount'); +$image->{mounts} = ['--ro-bind', "$image->{root}/work/mounted", '/opt/input']; +my ($status, $output) = $image->run('/bin/cat', '/opt/input'); +is($status, 0, 'the image adapter retains extra mounts'); +is($output, 'extra mount', 'the command reads the supplied mount'); +done_testing(); diff --git a/xCAT-test/native/ip_forwarding.t b/xCAT-test/native/ip_forwarding.t index ead23c6684..df1c8b0f74 100644 --- a/xCAT-test/native/ip_forwarding.t +++ b/xCAT-test/native/ip_forwarding.t @@ -1,6 +1,7 @@ #!/usr/bin/env perl use strict; use warnings; +use File::Slurper qw(read_binary write_binary); use Cwd qw(abs_path); use File::Copy qw(copy); use File::Path qw(make_path); @@ -20,30 +21,18 @@ my $tmp = tempdir(DIR => '/var/tmp', CLEANUP => !$ENV{XCAT_FORWARD_KEEP}); diag("fixtures: $tmp") if $ENV{XCAT_FORWARD_KEEP}; make_path("$tmp/bin"); -sub write_file { - my ($path, $data) = @_; - open(my $f, '>', $path) or die "$path: $!"; - print {$f} $data; - close($f) or die "$path: $!"; -} -sub read_file { - my ($path) = @_; - open(my $f, '<', $path) or die "$path: $!"; - local $/; - return <$f> // ''; -} -my $host_config = read_file('/etc/sysctl.conf'); -my $host_forwarding = read_file('/proc/sys/net/ipv4/ip_forward'); +my $host_config = read_binary('/etc/sysctl.conf'); +my $host_forwarding = read_binary('/proc/sys/net/ipv4/ip_forward'); my $host_mount = readlink('/proc/self/ns/mnt'); my $host_net = readlink('/proc/self/ns/net'); my $sysctl = `command -v sysctl`; chomp $sysctl; -write_file("$tmp/bin/no", <<'SH'); +write_binary("$tmp/bin/no", <<'SH'); #!/bin/sh printf '%s\n' "$*" >> "$XCAT_FORWARD_FIXTURE/no.log" exit "${XCAT_FORWARD_AIX_RC:-0}" SH -write_file("$tmp/namespace", <<'SH'); +write_binary("$tmp/namespace", <<'SH'); #!/bin/bash set -eu [ "$(readlink /proc/self/ns/mnt)" != "$XCAT_FORWARD_HOST_MOUNT" ] @@ -53,7 +42,7 @@ mount --bind "$XCAT_FORWARD_FIXTURE/etc" /etc "$XCAT_FORWARD_SYSCTL" -qw net.ipv4.ip_forward="$XCAT_FORWARD_INITIAL" exec /usr/bin/perl "$XCAT_FORWARD_RUNNER" SH -write_file("$tmp/call-helper.pl", <<'CHILD'); +write_binary("$tmp/call-helper.pl", <<'CHILD'); use strict; use warnings; use lib "$ENV{XCAT_FORWARD_SOURCE_ROOT}/perl-xCAT"; @@ -105,7 +94,7 @@ for my $case (@cases) { $expected //= "net.ipv4.ip_forward = $enable\n"; my $fixture = "$tmp/case-" . ++$number; make_path("$fixture/etc/sysctl.d"); - write_file("$fixture/etc/sysctl.conf", $input); + write_binary("$fixture/etc/sysctl.conf", $input); symlink '../sysctl.conf', "$fixture/etc/sysctl.d/99-sysctl.conf" or die $!; for my $file (qw(ld.so.cache os-release openEuler-release)) { copy("/etc/$file", "$fixture/etc/$file") or die $! if -f "/etc/$file"; @@ -129,26 +118,26 @@ for my $case (@cases) { waitpid($pid, 0); my $status = (($? & 127) ? 128 + ($? & 127) : $? >> 8); is($status, 0, "pass $pass invokes the full production module in isolation"); - if ($status) { diag(read_file("$fixture/stderr-$pass.log")); next; } - my $result = decode_json(read_file("$fixture/result-$pass.json")); + if ($status) { diag(read_binary("$fixture/stderr-$pass.log")); next; } + my $result = decode_json(read_binary("$fixture/result-$pass.json")); is($result->{rc}, 0, "pass $pass preserves the helper return contract"); isnt($result->{mount_namespace}, $host_mount, "pass $pass uses a separate mount namespace"); isnt($result->{network_namespace}, $host_net, "pass $pass uses a separate network namespace"); - is(read_file("$fixture/etc/sysctl.conf"), $expected, "pass $pass persists only the expected assignment"); - is(read_file("$fixture/etc/sysctl.d/99-sysctl.conf"), $expected, "pass $pass retains the sysctl.d alias"); + is(read_binary("$fixture/etc/sysctl.conf"), $expected, "pass $pass persists only the expected assignment"); + is(read_binary("$fixture/etc/sysctl.d/99-sysctl.conf"), $expected, "pass $pass retains the sysctl.d alias"); is(0 + $result->{forwarding}, $aix ? 1 - $enable : $enable, "pass $pass has the expected real kernel forwarding state"); } if ($aix) { - is(read_file("$fixture/no.log"), "-o ipforwarding=$enable\n" x 2, + is(read_binary("$fixture/no.log"), "-o ipforwarding=$enable\n" x 2, 'AIX keeps its existing native command and arguments'); } else { ok(!-e "$fixture/no.log", 'Linux never invokes the AIX command'); } }; } -is(read_file('/etc/sysctl.conf'), $host_config, 'host sysctl configuration is unchanged'); -is(read_file('/proc/sys/net/ipv4/ip_forward'), $host_forwarding, 'host forwarding state is unchanged'); +is(read_binary('/etc/sysctl.conf'), $host_config, 'host sysctl configuration is unchanged'); +is(read_binary('/proc/sys/net/ipv4/ip_forward'), $host_forwarding, 'host forwarding state is unchanged'); is(readlink('/proc/self/ns/mnt'), $host_mount, 'test process retained its original mount namespace'); is(readlink('/proc/self/ns/net'), $host_net, 'test process retained its original network namespace'); done_testing(); diff --git a/xCAT-test/native/openeuler_genimage_transactions.t b/xCAT-test/native/openeuler_genimage_transactions.t index f9f7d64080..27a161ea44 100644 --- a/xCAT-test/native/openeuler_genimage_transactions.t +++ b/xCAT-test/native/openeuler_genimage_transactions.t @@ -1,6 +1,7 @@ #!/usr/bin/env perl use strict; use warnings; +use File::Slurper qw(read_binary write_binary); use FindBin; use File::Path qw(make_path); use File::Spec; @@ -13,9 +14,10 @@ plan skip_all => 'requires native Linux DNF and trusted RPM keys' my $repo = File::Spec->rel2abs("$FindBin::Bin/../.."); my $dir = tempdir(CLEANUP => 1); my $driver = "$dir/driver.pl"; -write_file($driver, <<'PERL'); +write_binary($driver, <<'PERL'); use strict; use warnings; +use File::Slurper qw(read_binary); use Storable qw(nstore); use Text::ParseWords qw(shellwords); our (@commands, $reached, $config, $restored); @@ -32,9 +34,7 @@ BEGIN { my @args = shellwords($command); my ($index) = grep { $args[$_] eq '-c' } 0 .. $#args - 1; die 'Package command omitted its configuration' unless defined($index); - open(my $file, '<', $args[$index + 1]) or die $!; - $config = do { local $/; <$file> }; - close($file); + $config = read_binary($args[$index + 1]); my $phase = $command =~ / erase .*pre-remove/ ? 'pre-remove' : $command =~ / erase .*post-remove/ ? 'post-remove' : $command =~ / install .*native-extra/ ? 'extra-install' @@ -55,11 +55,7 @@ BEGIN { }; } END { - my $uname = ''; - if (open(my $file, '<', "$ENV{GENIMAGE_ROOT}/bin/uname")) { - $uname = do { local $/; <$file> }; - close($file); - } + my $uname = eval { read_binary("$ENV{GENIMAGE_ROOT}/bin/uname") } // ''; nstore({ commands => \@commands, reached => $reached, config => $config, uname => $uname }, "$ENV{GENIMAGE_CASE}/result"); unlink("/tmp/genimage.$$.yum.conf"); @@ -110,10 +106,10 @@ sub run_case { my $case = tempdir(DIR => $dir, CLEANUP => 1); my $root = "$case/image/rootimg"; make_path("$root/bin", "$root/etc", "$root/dev", "$root/run", "$root/sbin"); - write_file("$root/bin/uname", "original uname\n"); + write_binary("$root/bin/uname", "original uname\n"); chmod 0755, "$root/bin/uname"; - write_file("$case/os.pkglist", "native-os\n"); - write_file("$case/extra.pkglist", "-pre-remove\nvendor/native-extra\n--post-remove\n"); + write_binary("$case/os.pkglist", "native-os\n"); + write_binary("$case/extra.pkglist", "-pre-remove\nvendor/native-extra\n--post-remove\n"); local %ENV = %ENV; @ENV{qw(GENIMAGE_SCRIPT GENIMAGE_ROOT GENIMAGE_CASE GENIMAGE_FAILURE XCATROOT)} = ("$repo/xCAT-server/share/xcat/netboot/rh/genimage", $root, $case, $failure, "$repo/xCAT-server"); @@ -131,15 +127,6 @@ sub run_case { } waitpid($pid, 0); my $status = (($? & 127) ? 128 + ($? & 127) : $? >> 8); - open(my $file, '<', "$case/output") or die $!; - my $output = do { local $/; <$file> }; - close($file); + my $output = read_binary("$case/output"); return ($status, retrieve("$case/result"), $output); } - -sub write_file { - my ($path, $contents) = @_; - open(my $file, '>', $path) or die "write $path: $!"; - print {$file} $contents or die $!; - close($file) or die $!; -} diff --git a/xCAT-test/native/openeuler_install_repositories.t b/xCAT-test/native/openeuler_install_repositories.t index 613dfac78b..56a8d56e8e 100644 --- a/xCAT-test/native/openeuler_install_repositories.t +++ b/xCAT-test/native/openeuler_install_repositories.t @@ -1,6 +1,7 @@ #!/usr/bin/env perl use strict; use warnings; +use File::Slurper qw(read_binary write_binary); use Digest::SHA qw(sha256_hex); use File::Copy qw(copy); use File::Path qw(make_path); @@ -30,11 +31,11 @@ my $error = xCAT::Template->subvars(repo_path('xCAT-server/share/xcat/install/sc "$tmp/post.rhels8", 'node', undef, '/install/media', 'openeuler', undef, {xcatmaster => '192.0.2.1'}); die "Cannot render post.rhels8: $error" if $error; -write_file("$tmp/bin/nmcli", "#!/bin/sh\nexit 0\n"); +write_binary("$tmp/bin/nmcli", "#!/bin/sh\nexit 0\n"); chmod 0755, "$tmp/bin/nmcli" or die $!; is(system('/bin/bash', '-n', "$tmp/post.rhels8"), 0, 'the complete rendered post owner has valid Bash syntax'); -write_file("$tmp/namespace", <<'SH'); +write_binary("$tmp/namespace", <<'SH'); #!/bin/bash set -eu [ "$(readlink /proc/self/ns/mnt)" != "$XCAT_POST_HOST_MOUNT" ] @@ -51,7 +52,7 @@ my $native = "[OS]\nenabled=1\ngpgcheck=1\n[update]\n \tenabled = 1\n[disabled]\ my $native_expected = "[OS]\nenabled=0\ngpgcheck=1\n[update]\nenabled=0\n[disabled]\nenabled=0\n#enabled=1\n"; my $host_mount = readlink('/proc/self/ns/mnt'); my $host_net = readlink('/proc/self/ns/net'); -my %host_repos = map { $_ => sha256_hex(read_file($_)) } +my %host_repos = map { $_ => sha256_hex(read_binary($_)) } glob('/etc/yum.repos.d/*.repo'); for my $case ( @@ -65,10 +66,10 @@ for my $case ( make_path($repos); copy('/etc/ld.so.cache', "$fixture/etc/ld.so.cache") or die $! if -f '/etc/ld.so.cache'; - write_file("$repos/$_", $enabled) for @legacy; - write_file("$repos/openEuler.repo", $input) if defined $input; + write_binary("$repos/$_", $enabled) for @legacy; + write_binary("$repos/openEuler.repo", $input) if defined $input; my @preserved = qw(local-repository-0.repo xCAT-custom.repo administrator.repo); - write_file("$repos/$_", $enabled) for @preserved; + write_binary("$repos/$_", $enabled) for @preserved; subtest $name => sub { local %ENV = (%ENV, XCATDEBUGMODE => '0', MASTER_IP => '192.0.2.1', XCAT_POST_REPOS_FIXTURE => $fixture, XCAT_POST_REPOS_OWNER => "$tmp/post.rhels8", @@ -84,36 +85,20 @@ for my $case ( } waitpid($pid, 0); is($?, 0, "pass $pass runs the whole post owner in isolation") - or diag(read_file("$fixture/stderr-$pass.log")); + or diag(read_binary("$fixture/stderr-$pass.log")); if (defined $expected) { - is(read_file("$repos/openEuler.repo"), $expected, + is(read_binary("$repos/openEuler.repo"), $expected, "pass $pass disables only active native repository assignments"); } else { ok(!-e "$repos/openEuler.repo", "pass $pass does not create an absent vendor file"); } - is(read_file("$repos/$_"), $disabled, "pass $pass preserves policy for $_") for @legacy; - is(read_file("$repos/$_"), $enabled, "pass $pass leaves $_ unchanged") for @preserved; + is(read_binary("$repos/$_"), $disabled, "pass $pass preserves policy for $_") for @legacy; + is(read_binary("$repos/$_"), $enabled, "pass $pass leaves $_ unchanged") for @preserved; } }; } -is_deeply({map { $_ => sha256_hex(read_file($_)) } glob('/etc/yum.repos.d/*.repo')}, +is_deeply({map { $_ => sha256_hex(read_binary($_)) } glob('/etc/yum.repos.d/*.repo')}, \%host_repos, 'host repository files remain unchanged'); is(readlink('/proc/self/ns/mnt'), $host_mount, 'host mount namespace remains unchanged'); is(readlink('/proc/self/ns/net'), $host_net, 'host network namespace remains unchanged'); done_testing(); - -sub write_file { - my ($path, $contents) = @_; - open(my $fh, '>:raw', $path) or die "$path: $!"; - print {$fh} $contents; - close($fh) or die "$path: $!"; -} - -sub read_file { - my ($path) = @_; - open(my $fh, '<:raw', $path) or die "$path: $!"; - local $/; - my $contents = <$fh>; - close($fh) or die "$path: $!"; - return $contents // ''; -} diff --git a/xCAT-test/native/openeuler_networking.t b/xCAT-test/native/openeuler_networking.t index ba9aea2fa5..a9cd5d62a7 100644 --- a/xCAT-test/native/openeuler_networking.t +++ b/xCAT-test/native/openeuler_networking.t @@ -1,6 +1,7 @@ #!/usr/bin/env perl use strict; use warnings; +use File::Slurper qw(read_binary write_binary); use Cwd qw(abs_path); use File::Path qw(make_path); use File::Temp qw(tempdir); @@ -18,22 +19,13 @@ my $tmp = tempdir(CLEANUP => 1); my $bin = "$tmp/bin"; make_path($bin); -sub write_file { - my ($path, $text) = @_; - open(my $fh, '>', $path) or die "$path: $!"; - print {$fh} $text; - close($fh) or die "$path: $!"; -} - sub read_file { my ($path) = @_; return '' unless -f $path; - open(my $fh, '<', $path) or die "$path: $!"; - local $/; - return <$fh> // ''; + return scalar read_binary($path); } -write_file("$bin/double", <<'SH'); +write_binary("$bin/double", <<'SH'); #!/bin/bash command=${0##*/} printf '%s' "$command" >> "$XCAT_NET_LOG" @@ -84,7 +76,7 @@ for my $command (qw(ip nmcli systemctl logger route ifup ifdown modprobe sleep)) symlink 'double', "$bin/$command" or die $!; } -write_file("$tmp/namespace", <<'SH'); +write_binary("$tmp/namespace", <<'SH'); #!/bin/bash set -e mount --make-rprivate / @@ -95,7 +87,7 @@ exec "$@" SH chmod 0755, "$tmp/namespace"; -write_file("$tmp/local-route", <<'PERL'); +write_binary("$tmp/local-route", <<'PERL'); use strict; use warnings; use JSON::PP; @@ -117,10 +109,10 @@ sub run_case { make_path(map { "$fixture/$_" } qw(etc/sysconfig/network-scripts etc/sysconfig/network etc/network/interfaces.d etc/modprobe.d etc/NetworkManager/system-connections etc/systemd/system run install/postscripts db)); - write_file("$fixture/etc/os-release", $case{release} // "ID=openEuler\nVERSION_ID=24.03\nNAME=openEuler\n"); - write_file("$fixture/etc/network/interfaces", "auto eth8\niface eth8 inet static\n"); - write_file("$fixture/etc/systemd/system/NetworkManager.service", ''); - write_file("$fixture/etc/$case{marker}", $case{marker_text} // '') if $case{marker}; + write_binary("$fixture/etc/os-release", $case{release} // "ID=openEuler\nVERSION_ID=24.03\nNAME=openEuler\n"); + write_binary("$fixture/etc/network/interfaces", "auto eth8\niface eth8 inet static\n"); + write_binary("$fixture/etc/systemd/system/NetworkManager.service", ''); + write_binary("$fixture/etc/$case{marker}", $case{marker_text} // '') if $case{marker}; for my $file (qw(routeop xcatlib.sh)) { symlink "$source/xCAT/postscripts/$file", "$fixture/install/postscripts/$file" or die $!; } diff --git a/xCAT-test/native/openeuler_xcatroot.t b/xCAT-test/native/openeuler_xcatroot.t index 923599d6fb..a124e7fc98 100644 --- a/xCAT-test/native/openeuler_xcatroot.t +++ b/xCAT-test/native/openeuler_xcatroot.t @@ -1,6 +1,7 @@ #!/usr/bin/env perl use strict; use warnings; +use File::Slurper qw(read_binary write_binary); use FindBin; use File::Copy qw(copy); use File::Path qw(make_path); @@ -14,7 +15,7 @@ plan skip_all => 'requires Linux root and private mount namespaces' my $netboot = File::Spec->rel2abs("$FindBin::Bin/../../xCAT-server/share/xcat/netboot/rh"); my $dir = tempdir(CLEANUP => 1); my $wrapper = "$dir/run"; -write_file($wrapper, <<'SH'); +write_binary($wrapper, <<'SH'); #!/bin/bash set -e root=$1 @@ -48,16 +49,16 @@ for my $variant (qw(dracut_047 dracut_105/stateless dracut_105/statelite)) { symlink('usr/sbin', "$root/sbin") or die $!; symlink('usr/lib64', "$root/lib64") or die $!; make_path("$payload/etc/init.d", "$payload/etc/sysconfig/network-scripts", "$payload/var/lib/dhclient"); - write_file("$payload/native-marker", "native payload\n"); - write_file("$payload/etc/os-release", "ID=openEuler\nVERSION_ID=24.03\n"); + write_binary("$payload/native-marker", "native payload\n"); + write_binary("$payload/etc/os-release", "ID=openEuler\nVERSION_ID=24.03\n"); if ($localdisk ne 'missing') { - write_file("$payload/etc/init.d/localdisk", "#!/bin/sh\ntouch /sysroot/localdisk-ran\n"); + write_binary("$payload/etc/init.d/localdisk", "#!/bin/sh\ntouch /sysroot/localdisk-ran\n"); chmod($localdisk eq 'executable' ? 0755 : 0644, "$payload/etc/init.d/localdisk"); } - write_file("$root/etc/resolv.conf", "nameserver 192.0.2.1\n"); - write_file("$root/tmp/dhclient.eth0.lease", "fixture lease\n"); - write_file("$root/var/lib/NetworkManager/$_-0f3e5a12-eth0.lease", "$_ lease\n") for qw(dhclient internal); - write_file("$root/lib/dracut-lib.sh", <<'SH'); + write_binary("$root/etc/resolv.conf", "nameserver 192.0.2.1\n"); + write_binary("$root/tmp/dhclient.eth0.lease", "fixture lease\n"); + write_binary("$root/var/lib/NetworkManager/$_-0f3e5a12-eth0.lease", "$_ lease\n") for qw(dhclient internal); + write_binary("$root/lib/dracut-lib.sh", <<'SH'); hookdir=/hooks logger() { :; } getarg() @@ -92,9 +93,7 @@ SH } waitpid($pid, 0); my $rc = (($? & 127) ? 128 + ($? & 127) : $? >> 8); - open(my $file, '<', "$case/output") or die $!; - my $output = do { local $/; <$file> }; - close($file); + my $output = read_binary("$case/output"); my $label = "$variant $method $localdisk localdisk"; is($rc, 0, "$label completes the production xcatroot script") or diag($output); like($output, qr/^PAYLOAD=native payload$/m, "$label extracts the actual image payload"); @@ -113,10 +112,3 @@ SH } } done_testing(); - -sub write_file { - my ($path, $contents) = @_; - open(my $file, '>', $path) or die "write $path: $!"; - print {$file} $contents or die $!; - close($file) or die $!; -} diff --git a/xCAT-test/native/postinstall_bootstrap.t b/xCAT-test/native/postinstall_bootstrap.t index 28f9a10f60..0027a88579 100644 --- a/xCAT-test/native/postinstall_bootstrap.t +++ b/xCAT-test/native/postinstall_bootstrap.t @@ -5,11 +5,11 @@ use Capture::Tiny qw(capture); use File::Copy qw(copy); use File::Path qw(make_path); use File::Slurper qw(read_binary write_binary); -use File::Temp qw(tempdir); use FindBin; use lib "$FindBin::Bin/../lib"; use Test::More; use XCAT::Test::File qw(repo_path); +use XCAT::Test::Sandbox qw(sandbox_root sandbox_command); plan skip_all => 'installer execution requires Linux' unless $^O eq 'linux'; die 'Install bubblewrap to run this test' unless -x '/usr/bin/bwrap'; @@ -22,7 +22,7 @@ sub executable { } sub fixture { - my $root = tempdir(CLEANUP => 1); + my $root = sandbox_root(); make_path(map { "$root/$_" } qw(bin db opt/xcat etc/systemd/system/multi-user.target.wants etc/init.d etc/rc2.d etc/rc.d/rc3.d etc/rc.d/rc4.d etc/rc.d/rc5.d xcatpost log/xcat boot)); @@ -66,26 +66,14 @@ SH sub isolated { my ($root, $stage, $environment, @command) = @_; - my @args = ('/usr/bin/bwrap', '--unshare-all', '--die-with-parent', '--new-session', - '--tmpfs', '/', '--proc', '/proc', '--dev', '/dev', '--tmpfs', '/tmp', - '--tmpfs', '/run', '--bind', $root, '/fixture', '--chdir', '/fixture', - '--setenv', 'PATH', '/fixture/bin:/usr/bin:/bin:/usr/sbin:/sbin', - '--setenv', 'LC_ALL', 'C'); - if ($stage eq 'render') { - push @args, '--ro-bind', repo_path('xCAT/postscripts'), '/install/postscripts', - '--ro-bind', repo_path('.'), repo_path('.'); - } - for my $directory (qw(/usr /bin /sbin /lib /lib64)) { - if (-l $directory) { - push @args, '--symlink', readlink($directory), $directory; - } elsif (-d $directory) { - push @args, '--ro-bind', $directory, $directory; - } - } - push @args, '--bind', "$root/$_", "/$_" for qw(opt etc xcatpost boot); - push @args, '--bind', "$root/log", '/var/log'; - push @args, '--ro-bind', '/etc/alternatives', '/etc/alternatives' if -d '/etc/alternatives'; - push @args, '--setenv', $_, $environment->{$_} for sort keys %$environment; + my %read_only = $stage eq 'render' + ? (repo_path('xCAT/postscripts') => '/install/postscripts', + repo_path('.') => repo_path('.')) : (); + my @args = sandbox_command($root, { + preserve_links => 1, directories => [qw(opt etc xcatpost boot)], + tmpfs => ['/tmp'], read_only => \%read_only, + env => {PATH => '/fixture/bin:/usr/bin:/bin:/usr/sbin:/sbin', %$environment}, + }); local %ENV = (PATH => '/usr/bin:/bin', LC_ALL => 'C'); my ($out, $err, $status) = capture { system(@args, @command) }; return ($status, $out . $err); @@ -110,6 +98,24 @@ my @cases = ( {name => 'missing postboot file', no_post => 1, disable => 1}, ); +{ + my $root = fixture(); + for my $stage (qw(render client)) { + my ($status, $output) = isolated($root, $stage, {}, '/bin/sh', '-c', + 'test ! -e /etc/os-release && test ! -e /tmp/fixture-marker && ' + . 'printf private > /tmp/fixture-marker && ' + . 'if test -r /install/postscripts/xcatlib.sh; then printf visible; else printf hidden; fi'); + is($status, 0, "$stage has private configuration and temporary files"); + is($output, $stage eq 'render' ? 'visible' : 'hidden', "$stage retains its postscripts visibility"); + ($status, $output) = isolated($root, $stage, {}, '/bin/sh', '-c', + 'test -r "$1/Version"', 'visibility', repo_path('.')); + is($status, $stage eq 'render' ? 0 : 1 << 8, "$stage retains its repository visibility"); + } + my ($status, $output) = isolated($root, 'client', {}, '/bin/sh', '-c', + 'printf error >&2; printf output; exit 7'); + is_deeply([$status, $output], [7 << 8, 'outputerror'], 'retains raw status and stdout-before-stderr capture'); +} + for my $owner (qw(post.xcat post.xcat.ng post.xcat.rhels10)) { my $build = fixture(); my ($status, $output) = isolated($build, 'render', {}, $^X, diff --git a/xCAT-test/native/remoteshell_hostkeys_openeuler.t b/xCAT-test/native/remoteshell_hostkeys_openeuler.t index c149e730cd..688db71365 100644 --- a/xCAT-test/native/remoteshell_hostkeys_openeuler.t +++ b/xCAT-test/native/remoteshell_hostkeys_openeuler.t @@ -1,6 +1,7 @@ #!/usr/bin/env perl use strict; use warnings; +use File::Slurper qw(read_binary write_binary); use Cwd qw(abs_path); use Digest::SHA qw(sha256_hex); use File::Copy qw(copy); @@ -17,18 +18,10 @@ my $tmp = tempdir(DIR => '/var/tmp', CLEANUP => 1); chmod 0700, $tmp; make_path("$tmp/keys", "$tmp/bin"); -sub write_file { - my ($path, $contents) = @_; - open(my $fh, '>', $path) or die "$path: $!"; - print {$fh} $contents; - close($fh) or die "$path: $!"; -} sub read_file { my ($path) = @_; return '' unless -f $path; - open(my $fh, '<', $path) or die "$path: $!"; - local $/; - return <$fh> // ''; + return scalar read_binary($path); } sub public_identity { my ($path) = @_; @@ -46,7 +39,7 @@ for my $name (qw(remoteshell xcatlib.sh remoteshell-sshd-config)) { copy("$source/xCAT/postscripts/$name", "$tmp/bin/$name") or die $!; chmod 0755, "$tmp/bin/$name"; } -write_file("$tmp/bin/namespace", <<'SH'); +write_binary("$tmp/bin/namespace", <<'SH'); #!/bin/bash set -e mount --make-rprivate / @@ -55,7 +48,7 @@ mount --bind "$XCAT_KEY_FIXTURE/root" /root mount --bind "$XCAT_KEY_FIXTURE/tmp" /tmp exec "$@" SH -write_file("$tmp/bin/getcredentials.awk", <<'SH'); +write_binary("$tmp/bin/getcredentials.awk", <<'SH'); #!/bin/bash case "$1" in ssh_dsa_hostkey) cat "$XCAT_KEY_INPUT/dsa" ;; @@ -66,12 +59,12 @@ case "$1" in *) printf 'unexpected credential request\n'; exit 1 ;; esac SH -write_file("$tmp/bin/allowcred.awk", "#!/bin/sh\nexec /bin/sleep 60\n"); -write_file("$tmp/bin/logger", "#!/bin/sh\nprintf '%s\\n' \"\$*\" >> \"\$XCAT_KEY_FIXTURE/logger.log\"\n"); -write_file("$tmp/bin/systemctl", "#!/bin/sh\nprintf '%s\\n' \"\$*\" >> \"\$XCAT_KEY_FIXTURE/services.log\"\nexit 0\n"); -write_file("$tmp/bin/sleep", "#!/bin/sh\nexit 0\n"); +write_binary("$tmp/bin/allowcred.awk", "#!/bin/sh\nexec /bin/sleep 60\n"); +write_binary("$tmp/bin/logger", "#!/bin/sh\nprintf '%s\\n' \"\$*\" >> \"\$XCAT_KEY_FIXTURE/logger.log\"\n"); +write_binary("$tmp/bin/systemctl", "#!/bin/sh\nprintf '%s\\n' \"\$*\" >> \"\$XCAT_KEY_FIXTURE/services.log\"\nexit 0\n"); +write_binary("$tmp/bin/sleep", "#!/bin/sh\nexit 0\n"); for my $command (qw(chown chmod)) { - write_file("$tmp/bin/$command", "#!/bin/bash\n" . + write_binary("$tmp/bin/$command", "#!/bin/bash\n" . 'if [ "$XCAT_KEY_FAIL_COMMAND" = "${0##*/}" ] && [[ "${!#}" = "/etc/ssh/ssh_host_${XCAT_KEY_FAIL_TYPE}_key" ]]; then exit 42; fi' . "\n" . 'exec /usr/bin/' . $command . ' "$@"' . "\n"); } @@ -92,12 +85,12 @@ for my $case ( my ($label, $osver, $id, $group, $existing, $fail_command, $fail_type) = @$case; my $fixture = tempdir(DIR => $tmp, CLEANUP => 1); make_path(map { "$fixture/$_" } qw(etc/ssh root tmp)); - write_file("$fixture/etc/passwd", "root:x:0:0:root:/root:/bin/bash\n"); - write_file("$fixture/etc/group", "root:x:0:\n" . ($group ? "ssh_keys:x:4242:\n" : '')); - write_file("$fixture/etc/nsswitch.conf", "passwd: files\ngroup: files\n"); - write_file("$fixture/etc/os-release", "ID=$id\n"); - write_file("$fixture/etc/ssh/sshd_config", "Port 22\n"); - write_file("$fixture/etc/ssh/ssh_config", "Host *\n"); + write_binary("$fixture/etc/passwd", "root:x:0:0:root:/root:/bin/bash\n"); + write_binary("$fixture/etc/group", "root:x:0:\n" . ($group ? "ssh_keys:x:4242:\n" : '')); + write_binary("$fixture/etc/nsswitch.conf", "passwd: files\ngroup: files\n"); + write_binary("$fixture/etc/os-release", "ID=$id\n"); + write_binary("$fixture/etc/ssh/sshd_config", "Port 22\n"); + write_binary("$fixture/etc/ssh/ssh_config", "Host *\n"); for my $type (@types) { next unless $existing; my $key = "$fixture/etc/ssh/ssh_host_${type}_key"; diff --git a/xCAT-test/unit/dhcp_grub2_node_loader.t b/xCAT-test/unit/dhcp_grub2_node_loader.t index d1d3168855..887db08558 100644 --- a/xCAT-test/unit/dhcp_grub2_node_loader.t +++ b/xCAT-test/unit/dhcp_grub2_node_loader.t @@ -14,6 +14,7 @@ use lib "$FindBin::Bin/../../xCAT-server/lib/perl"; use lib "$FindBin::Bin/../../perl-xCAT"; use File::Path qw(make_path); +use File::Slurper qw(write_binary); use File::Temp qw(tempdir); use Test::More; use XCAT::Test::File qw(repo_path); @@ -37,8 +38,7 @@ require( repo_path('xCAT-server/lib/xcat/plugins/dhcp.pm') ); for my $dir ( $site_tftp, $node_tftp ) { make_path("$dir/boot/grub2"); - open( my $loader, '>', "$dir/boot/grub2/grub2.aarch64" ) or die "Cannot create the loader: $!"; - close($loader) or die "Cannot close the loader: $!"; + write_binary("$dir/boot/grub2/grub2.aarch64", ''); } # The node loader links in a TFTP directory, as a nodeset left them. @@ -125,13 +125,11 @@ sub kea_boot_url6 { my $dir = tempdir( CLEANUP => 1 ); my $conf = "$dir/dhcpd.conf"; -open( my $fh, '>', $conf ) or die "Cannot create $conf: $!"; -print {$fh} "#xCAT generated dhcp configuration\n", +write_binary($conf, join('', "#xCAT generated dhcp configuration\n", "option space gpxe;\n", @{ xCAT::DHCP::BootPolicy->isc_ipxe_feature_option_lines() }, "subnet 192.0.2.0 netmask 255.255.255.0 {\n", - "} # 192.0.2.0/255.255.255.0 subnet_end\n"; -close($fh) or die "Cannot close $conf: $!"; + "} # 192.0.2.0/255.255.255.0 subnet_end\n")); # The boot file of every host that makedhcp creates for cn1 through OMAPI. sub isc_boot_files { diff --git a/xCAT-test/unit/dhcp_ipxe_feature_upgrade.t b/xCAT-test/unit/dhcp_ipxe_feature_upgrade.t index 3c8fbcd984..c98e469a0a 100644 --- a/xCAT-test/unit/dhcp_ipxe_feature_upgrade.t +++ b/xCAT-test/unit/dhcp_ipxe_feature_upgrade.t @@ -8,20 +8,23 @@ use warnings; no warnings 'once'; use FindBin; +use lib "$FindBin::Bin/../lib"; use lib "$FindBin::Bin/../../xCAT-server/lib"; use lib "$FindBin::Bin/../../xCAT-server/lib/perl"; use lib "$FindBin::Bin/../../perl-xCAT"; use B (); use File::Temp qw(tempdir); +use File::Slurper qw(read_binary write_binary); use JSON (); use Test::More; +use XCAT::Test::File qw(repo_path); use xCAT::DHCP::Backend::Kea; use xCAT::DHCP::BootPolicy; $ENV{XCATCFG} ||= 'SQLite:/tmp'; -my $source_dhcp_plugin = "$FindBin::Bin/../../xCAT-server/lib/xcat/plugins/dhcp.pm"; +my $source_dhcp_plugin = repo_path('xCAT-server/lib/xcat/plugins/dhcp.pm'); if ( -f $source_dhcp_plugin ) { require $source_dhcp_plugin; } else { @@ -123,7 +126,8 @@ my @old_header = ( my @conf = @old_header; my $path = "$dir/dhcpd.conf"; is( xCAT_plugin::dhcp::_isc_declare_ipxe_features( \@conf, $path ), undef, 'ISC: makedhcp adds the options without error' ); - my $written = do { local ( @ARGV, $/ ) = ($path); <> }; + my $written = eval { read_binary($path) }; + warn $@ if $@; is( $written, join( '', @conf ), 'ISC: makedhcp writes the configuration with the options' ); like( $written, qr/^option gpxe\.http code 19 = unsigned integer 8;$/m, 'ISC: which declares the HTTP feature' ); is_deeply( \@restarts, ['dhcp'], 'ISC: makedhcp restarts dhcpd once' ); @@ -156,9 +160,7 @@ my @old_header = ( qr/^Unable to restart the DHCP server after adding the iPXE feature options/, 'ISC: makedhcp reports a restart that fails' ); } ok( -e "$failed.ipxe-restart", 'ISC: and keeps the restart marker' ); - open( my $fh, '<', $failed ) or die "Cannot read $failed: $!"; - my @retry = <$fh>; - close($fh); + my @retry = split /(?<=\n)/, read_binary($failed); @restarts = (); is( xCAT_plugin::dhcp::_isc_declare_ipxe_features( \@retry, $failed ), undef, 'ISC: the next run, with the options already in the file, gives no error' ); @@ -225,9 +227,7 @@ my @responses; @lines = @old_header unless @lines; my $conf = $xCAT_plugin::dhcp::dhcpconffile; chmod 0600, $conf; - open( my $fh, '>', $conf ) or die "Cannot create $conf: $!"; - print {$fh} @lines; - close($fh) or die "Cannot close $conf: $!"; + write_binary($conf, join('', @lines)); chmod 0400, $conf if $read_only; }; @@ -267,9 +267,7 @@ my @responses; [qw(newconfig writeout omshell addnode writeout)], 'ISC: and writes a new configuration before OMAPI changes a host' ) or diag("reached: @reached"); is( $loaded, 'dhcp', 'ISC: and restarts dhcpd with it first' ); - open( my $fh, '<', $conf ) or die "Cannot read $conf: $!"; - my $final = do { local $/; <$fh> }; - close($fh); + my $final = read_binary($conf); ok( ( grep { index( $final, $_ ) >= 0 } @features ) == @features && $final =~ /^omapi-port 7911;$/m, 'ISC: and the configuration it writes last keeps the iPXE options and the OMAPI port' ); ok( !-e "$conf.ipxe-restart", 'ISC: and leaves no restart marker' ); @@ -337,9 +335,7 @@ my @responses; my (@defs) = @_; my $backend = DHCPUpgradeKeaBackend->new(); $backend->{path} = "$dir/kea-dhcp4.conf"; - open( my $fh, '>', $backend->{path} ) or die "Cannot create $backend->{path}: $!"; - print {$fh} JSON::encode_json( { Dhcp4 => { subnet4 => [ { id => 1, subnet => '192.0.2.0/24' } ], 'option-def' => \@defs } } ); - close($fh) or die "Cannot close $backend->{path}: $!"; + write_binary($backend->{path}, JSON::encode_json( { Dhcp4 => { subnet4 => [ { id => 1, subnet => '192.0.2.0/24' } ], 'option-def' => \@defs } } )); xCAT_plugin::dhcp::kea_process_request( $backend, { node => ['cn1'] }, {}, {}, 0 ); return $backend; }; diff --git a/xCAT-test/unit/dhcp_kea_fips_key.t b/xCAT-test/unit/dhcp_kea_fips_key.t index f0433fe02a..e349bfaef1 100644 --- a/xCAT-test/unit/dhcp_kea_fips_key.t +++ b/xCAT-test/unit/dhcp_kea_fips_key.t @@ -3,19 +3,20 @@ use strict; use warnings; use FindBin; +use lib "$FindBin::Bin/../lib"; use lib "$FindBin::Bin/../../perl-xCAT"; use lib "$FindBin::Bin/../../xCAT-server/lib/perl"; use File::Slurper qw(write_text); use File::Temp qw(tempdir); use Test::More; +use XCAT::Test::File qw(repo_path); BEGIN { - $ENV{XCATROOT} = "$FindBin::Bin/../../xCAT-server"; + $ENV{XCATROOT} = repo_path('xCAT-server'); $ENV{XCATCFG} = 'SQLite:' . tempdir(CLEANUP => 1); } -my $plugin = "$FindBin::Bin/../../xCAT-server/lib/xcat/plugins/dhcp.pm"; -require $plugin; +require(repo_path('xCAT-server/lib/xcat/plugins/dhcp.pm')); my $directory = tempdir(CLEANUP => 1); local $xCAT_plugin::dhcp::kea_ddns_key_path = "$directory/ddns.key"; diff --git a/xCAT-test/unit/geninitrd_genimage_status.t b/xCAT-test/unit/geninitrd_genimage_status.t index d4e110bac1..735bc7b515 100644 --- a/xCAT-test/unit/geninitrd_genimage_status.t +++ b/xCAT-test/unit/geninitrd_genimage_status.t @@ -3,6 +3,7 @@ use strict; use warnings; ## no critic (TestingAndDebugging::ProhibitNoWarnings) use File::Path qw(make_path); +use File::Slurper qw(read_binary write_binary); use File::Temp qw(tempdir); use FindBin; use Storable qw(dclone); @@ -24,15 +25,13 @@ my %attribs = ( # The genimage client prints build output on stdout and its own errors on stderr. my $bindir = tempdir(CLEANUP => 1); -open(my $script, '>', "$bindir/genimage") or die "genimage: $!"; -print $script <<'EOS'; +write_binary("$bindir/genimage", <<'EOS'); #!/bin/sh echo "$@" > "$GENIMAGE_ARGS" echo 'the initial ramdisks are built' echo 'Error: genimage command failed' >&2 exit "$GENIMAGE_RC" EOS -close($script) or die "genimage: $!"; chmod(0755, "$bindir/genimage") or die "genimage: $!"; my $emptydir = tempdir(CLEANUP => 1); @@ -55,10 +54,8 @@ sub geninitrd_with { sub { push @responses, dclone($_[0]) }, sub { die "Unexpected subrequest\n" }); } my %result; - if (open(my $fh, '<', $args)) { - $result{args} = do { local $/; <$fh> }; - close($fh); - } + my $arguments = eval { read_binary($args) }; + $result{args} = $arguments unless $@; for my $key (qw(info error errorcode)) { $result{$key} = [ map { @{ $_->{$key} // [] } } @responses ]; } diff --git a/xCAT-test/unit/ipmi_sdr_errors.t b/xCAT-test/unit/ipmi_sdr_errors.t index 384f8e00d1..ef6a798097 100644 --- a/xCAT-test/unit/ipmi_sdr_errors.t +++ b/xCAT-test/unit/ipmi_sdr_errors.t @@ -5,92 +5,21 @@ use warnings; ## no critic (Modules::RequireFilenameMatchesPackage, TestingAndDebugging::ProhibitNoStrict, TestingAndDebugging::ProhibitNoWarnings) no warnings qw(once redefine); -use File::Spec; use FindBin; +use lib "$FindBin::Bin/../lib"; use Test::More; +use XCAT::Test::IPMISDR qw(load_ipmi_plugin new_session); # An IPMI command reads the device ID and then the SDR repository before it can answer. # A failure in that chain must reach the administrator as an error of the node and must end # the chain, instead of being dropped or reported under no node. -BEGIN { - for my $module (qw( - xCAT::GlobalDef xCAT_monitoring::monitorctrl xCAT::IPMI - xCAT::BMCUtils xCAT::PasswordUtils xCAT::Utils xCAT::TableUtils - xCAT::IMMUtils xCAT::ServiceNodeUtils xCAT::NetworkUtils xCAT::Usage - xCAT::data::ibmhwtypes xCAT::data::ibmleds - xCAT::data::ipmigenericevents xCAT::data::ipmisensorevents - IBM::EnergyManager - )) { - (my $file = $module) =~ s{::}{/}g; - $INC{"$file.pm"} = __FILE__; - no strict 'refs'; - *{"${module}::import"} = sub { }; - } - - package xCAT::SvrUtils; - our @messages; - sub import { } - sub sendmsg { push @messages, { text => $_[0], node => $_[2] }; } - $INC{'xCAT/SvrUtils.pm'} = __FILE__; - - package xCAT::SPD; - sub import { - my $caller = caller; - no strict 'refs'; - *{"${caller}::decode_spd"} = sub { return; }; - } - $INC{'xCAT/SPD.pm'} = __FILE__; - - package File::Path; - sub import { - my $caller = caller; - no strict 'refs'; - *{"${caller}::mkpath"} = sub { return; }; - } - $INC{'File/Path.pm'} = __FILE__; - - package Thread; - sub import { - my $caller = caller; - no strict 'refs'; - *{"${caller}::yield"} = sub { return; }; - } - $INC{'Thread.pm'} = __FILE__; - - package LWP; - our $VERSION = 5.64; - sub import { } - $INC{'LWP.pm'} = __FILE__; - - package HTTP::Request::Common; - sub import { - my $caller = caller; - no strict 'refs'; - *{"${caller}::GET"} = sub { return; }; - *{"${caller}::POST"} = sub { return; }; - } - $INC{'HTTP/Request/Common.pm'} = __FILE__; - - package main; - *CORE::GLOBAL::chmod = sub (@) { return 1; }; -} - -package FakeSession; -sub new { return bless { calls => [] }, shift; } -sub subcmd { my ($self, %args) = @_; push @{ $self->{calls} }, \%args; return; } - -package main; - -my $repo_root = File::Spec->catdir($FindBin::Bin, '..', '..'); -$ENV{XCATROOT} = File::Spec->catdir($repo_root, 'xCAT-server'); -my $plugin = File::Spec->catfile($repo_root, qw(xCAT-server lib xcat plugins ipmi.pm)); -do $plugin or die $@ || "Unable to load $plugin: $!"; +load_ipmi_plugin(); # Run one callback of the chain with a reply and return what it reported and requested. sub run_step { my ($step, $rsp, %state) = @_; - my $sessdata = { node => 'node01', ipmisession => FakeSession->new(), %state }; + my $sessdata = { node => 'node01', ipmisession => new_session(), %state }; local @xCAT::SvrUtils::messages = (); my $ok = eval { $step->($rsp, $sessdata); 1 }; return { diff --git a/xCAT-test/unit/ipmi_sdr_reservation.t b/xCAT-test/unit/ipmi_sdr_reservation.t index 7a02b78e40..0376c9f4c9 100644 --- a/xCAT-test/unit/ipmi_sdr_reservation.t +++ b/xCAT-test/unit/ipmi_sdr_reservation.t @@ -5,11 +5,12 @@ use warnings; ## no critic (Modules::RequireFilenameMatchesPackage, TestingAndDebugging::ProhibitNoStrict, TestingAndDebugging::ProhibitNoWarnings) no warnings qw(once redefine); -use File::Spec; use File::Temp qw(tempdir); use FindBin; +use lib "$FindBin::Bin/../lib"; use Storable qw(nstore_fd); use Test::More; +use XCAT::Test::IPMISDR qw(load_ipmi_plugin new_session); # Get SDR Repository Info can leave the reservation bit clear on a BMC that grants Reserve # SDR Repository. The SDR read must still ask for the reservation and use it. The record count @@ -17,86 +18,20 @@ use Test::More; # named with the record count of an earlier release must be read again. BEGIN { - for my $module (qw( - xCAT::GlobalDef xCAT_monitoring::monitorctrl xCAT::IPMI - xCAT::BMCUtils xCAT::PasswordUtils xCAT::Utils xCAT::TableUtils - xCAT::IMMUtils xCAT::ServiceNodeUtils xCAT::NetworkUtils xCAT::Usage - xCAT::data::ibmhwtypes xCAT::data::ibmleds - xCAT::data::ipmigenericevents xCAT::data::ipmisensorevents - IBM::EnergyManager - )) { - (my $file = $module) =~ s{::}{/}g; - $INC{"$file.pm"} = __FILE__; - no strict 'refs'; - *{"${module}::import"} = sub { }; - } - - package xCAT::SvrUtils; - our @messages; - sub import { } - sub sendmsg { push @messages, { text => $_[0], node => $_[2] }; } - $INC{'xCAT/SvrUtils.pm'} = __FILE__; - - package xCAT::SPD; - sub import { - my $caller = caller; - no strict 'refs'; - *{"${caller}::decode_spd"} = sub { return; }; - } - $INC{'xCAT/SPD.pm'} = __FILE__; - - package File::Path; - sub import { - my $caller = caller; - no strict 'refs'; - *{"${caller}::mkpath"} = sub { return; }; - } - $INC{'File/Path.pm'} = __FILE__; - - package Thread; - sub import { - my $caller = caller; - no strict 'refs'; - *{"${caller}::yield"} = sub { return; }; - } - $INC{'Thread.pm'} = __FILE__; - - package LWP; - our $VERSION = 5.64; - sub import { } - $INC{'LWP.pm'} = __FILE__; - - package HTTP::Request::Common; - sub import { - my $caller = caller; - no strict 'refs'; - *{"${caller}::GET"} = sub { return; }; - *{"${caller}::POST"} = sub { return; }; - } - $INC{'HTTP/Request/Common.pm'} = __FILE__; - - package main; - *CORE::GLOBAL::chmod = sub (@) { return 1; }; - # storsdrcache creates the cache directory of the management node. - *CORE::GLOBAL::system = sub { return 0; }; + # Only cache-directory creation is outside this fixture's filesystem. + *CORE::GLOBAL::system = sub { + die "Unexpected SDR command: @_" unless @_ == 1 && $_[0] eq 'mkdir -p /var/cache/xcat'; + return 0; + }; } -package FakeSession; -sub new { return bless { calls => [] }, shift; } -sub subcmd { my ($self, %args) = @_; push @{ $self->{calls} }, \%args; return; } - -package main; - -my $repo_root = File::Spec->catdir($FindBin::Bin, '..', '..'); -$ENV{XCATROOT} = File::Spec->catdir($repo_root, 'xCAT-server'); -my $plugin = File::Spec->catfile($repo_root, qw(xCAT-server lib xcat plugins ipmi.pm)); -do $plugin or die $@ || "Unable to load $plugin: $!"; +load_ipmi_plugin(); # A device identity that no SDR cache file holds, so the SDR is read from the BMC. sub new_sessdata { return { node => 'node01', - ipmisession => FakeSession->new(), + ipmisession => new_session(), mfg_id => 0xfffe, prod_id => 0xfffe, device_id => 0xfe, diff --git a/xCAT-test/unit/netboot_ipxe_defaults.t b/xCAT-test/unit/netboot_ipxe_defaults.t index 3e2cab38ea..347c67cfeb 100644 --- a/xCAT-test/unit/netboot_ipxe_defaults.t +++ b/xCAT-test/unit/netboot_ipxe_defaults.t @@ -8,16 +8,16 @@ use warnings; no warnings 'once'; use FindBin; +use lib "$FindBin::Bin/../lib"; use lib "$FindBin::Bin/../../perl-xCAT"; use Test::More; use Text::ParseWords qw(parse_line); +use XCAT::Test::File qw(slurp_repo_file); use xCAT::DBobjUtils; use xCAT::ProfiledNodeUtils; -my $root = "$FindBin::Bin/../.."; - # The image profiles and their operating system distributions, as the osimage and osdistro tables # hold them. my %distro = ( @@ -65,10 +65,7 @@ is( xCAT::ProfiledNodeUtils->profile_netboot( 'grub2', 'xnba' ), 'grub2', 'a nod sub template_netboot { my ( $file, $name ) = @_; - my $path = "$root/xCAT/templates/objects/node/$file.stanza"; - open( my $fh, '<', $path ) or die "Cannot read $path: $!"; - my $data = do { local $/; <$fh> }; - close($fh); + my $data = slurp_repo_file("xCAT/templates/objects/node/$file.stanza"); local %::FILEATTRS; xCAT::DBobjUtils->readFileInput($data); return $::FILEATTRS{$name}{netboot}; @@ -80,10 +77,7 @@ is( template_netboot( 'x86_64kvmguest', 'x86_64kvmguest-template' ), 'ipxe', is( template_netboot( 'ppc64le-ipmi', 'ppc64le-template' ), 'petitboot', 'the ppc64le template keeps its netboot method' ); { - my $path = "$root/xCAT/templates/e1350/noderes.csv"; - open( my $fh, '<', $path ) or die "Cannot read $path: $!"; - chomp( my @lines = <$fh> ); - close($fh); + chomp( my @lines = split /(?<=\n)/, slurp_repo_file('xCAT/templates/e1350/noderes.csv') ); ( my $header = shift @lines ) =~ s/^#//; my @columns = parse_line( ',', 0, $header ); my %compute; diff --git a/xCAT-test/unit/netboot_ipxe_method.t b/xCAT-test/unit/netboot_ipxe_method.t index 86bad2e9a8..93dd204b64 100644 --- a/xCAT-test/unit/netboot_ipxe_method.t +++ b/xCAT-test/unit/netboot_ipxe_method.t @@ -7,11 +7,13 @@ use strict; use warnings; use File::Temp qw(tempdir); +use File::Slurper qw(read_binary); use FindBin; +use lib "$FindBin::Bin/../lib"; use lib "$FindBin::Bin/../../perl-xCAT"; use Test::More; +use XCAT::Test::File qw(repo_path); -my $repo = "$FindBin::Bin/../.."; my $tftp = tempdir( CLEANUP => 1 ); our %rows; @@ -56,8 +58,8 @@ BEGIN { # xcatd loads the plugins from their files. SvrUtils loads them by module name, so xCAT_plugin names # the plugin directory of this checkout. my $inc = tempdir( CLEANUP => 1 ); -symlink( "$repo/xCAT-server/lib/xcat/plugins", "$inc/xCAT_plugin" ) or die "symlink: $!"; -unshift @INC, $inc, "$repo/xCAT-server/lib/perl", "$repo/perl-xCAT"; +symlink( repo_path('xCAT-server/lib/xcat/plugins'), "$inc/xCAT_plugin" ) or die "symlink: $!"; +unshift @INC, $inc, repo_path('xCAT-server/lib/perl'), repo_path('perl-xCAT'); require xCAT_plugin::ipxe; require xCAT::SvrUtils; @@ -81,9 +83,9 @@ sub nodeset { sub content { my ($path) = @_; - open( my $fh, '<', "$tftp/$path" ) or return; - local $/; - return <$fh>; + my $contents = eval { read_binary("$tftp/$path") }; + return if $@; + return $contents; } my %linux = ( kernel => 'xcat/osimage/vmlinuz', initrd => 'xcat/osimage/initrd.img', kcmdline => 'quiet' );