diff --git a/.github/scripts/check-languages.php b/.github/scripts/check-languages.php index 6e28fc3a..058c540a 100644 --- a/.github/scripts/check-languages.php +++ b/.github/scripts/check-languages.php @@ -176,7 +176,7 @@ function mover_texts(string $pluginDir): array } $used = []; $code = file_get_contents($mover); - preg_match_all('/(?:translate_text|mvlogger_t) "((?:[^"\\\\]|\\\\.)*)"/', $code, $m, PREG_OFFSET_CAPTURE); + preg_match_all('/(?:translate_text|mvlogger_t|dataset_out_of_view) "((?:[^"\\\\]|\\\\.)*)"/', $code, $m, PREG_OFFSET_CAPTURE); foreach ($m[1] as [$text, $offset]) { // an unescaped $ is a shell variable: the text is only known at run time if (preg_match('/(?/dev/null || true + wait "$HOLDER" 2>/dev/null || true + fi + rm -rf -- "$TMP" +} +trap cleanup EXIT + +expect_status() { + local expected=$1 actual + shift + set +e + PATH="$TMP/bin:$PATH" perl "$HELPER" "$@" + actual=$? + set -e + if [ "$actual" -ne "$expected" ]; then + echo "expected status $expected, got $actual" >&2 + return 1 + fi +} + +hold_file() { + local mode=$1 file=$2 ready="$TMP/ready" + rm -f -- "$ready" + if [ "$mode" = read ]; then + ( exec 9<"$file"; : >"$ready"; exec sleep 30 ) & + else + ( exec 9<>"$file"; : >"$ready"; exec sleep 30 ) & + fi + HOLDER=$! + for _ in {1..100}; do + [ -e "$ready" ] && return + sleep 0.01 + done + echo "holder did not start" >&2 + return 1 +} + +release_holder() { + kill "$HOLDER" 2>/dev/null || true + wait "$HOLDER" 2>/dev/null || true + HOLDER="" +} + +plain="$TMP/plain" +space="$TMP/a space [*] \$(name)" +newline="$TMP/line +break" +leading="$TMP/--leading" +printf x >"$plain" +printf x >"$space" +printf x >"$newline" +printf x >"$leading" + +perl -c "$HELPER" + +# F_SETLEASE and fuser -s are Linux interfaces. macOS development machines can +# still validate syntax and the intentionally small age_mover integration. +if [ "$(uname -s)" != Linux ]; then + grep -q '"${FILES_IN_USE_CMD\[@\]}" "$@"' "$MOVER" + grep -qE 'FILE_IN_USE_MODE|FILE_IN_USE_CHECK|FUSER_BATCH_SAFE|actionRows' "$MOVER" && exit 1 + grep -qE 'coproc|--server|fileLease(Start|Stop|Request)' "$MOVER" && exit 1 + echo "file lease Linux tests skipped on $(uname -s)" + exit +fi + +# expect_status runs the helper with this fuser first in PATH: a regular file answered by fuser, not a lease, gets its 7 +mkdir "$TMP/bin" +printf '#!/bin/sh\nexit 7\n' >"$TMP/bin/fuser" +chmod +x "$TMP/bin/fuser" + +expect_status 1 "$plain" "$space" "$newline" "$leading" +expect_status 1 "$TMP/vanished" + +hold_file read "$plain" +expect_status 0 "$plain" +release_holder +expect_status 1 "$plain" + +hold_file write "$plain" +expect_status 0 "$plain" +release_holder + +alias="$TMP/hardlink" +ln "$plain" "$alias" +hold_file read "$alias" +expect_status 0 "$plain" "$alias" +release_holder + +# A file that another process holds a lease on is in use, and checking it must not disturb that +# lease: opening it would make the kernel signal the holder to give the lease up. +leased="$TMP/leased" +printf x >"$leased" +rm -f -- "$TMP/ready" "$TMP/broken" +perl -e ' + use Fcntl qw(F_WRLCK); + my ($file, $ready, $broken) = @ARGV; + open(my $fh, "<", $file) or die "open: $!"; + $SIG{IO} = sub { open(my $m, ">", $broken); close $m }; + fcntl($fh, 1024, F_WRLCK) or die "lease: $!"; + open(my $r, ">", $ready); close $r; + sleep 30; +' "$leased" "$TMP/ready" "$TMP/broken" & +HOLDER=$! +for _ in {1..100}; do + [ -e "$TMP/ready" ] && break + sleep 0.01 +done +[ -e "$TMP/ready" ] || { echo "lease holder did not start" >&2; exit 1; } +grep -q LEASE /proc/locks +expect_status 0 "$leased" +expect_status 0 "$plain" "$leased" +sleep 0.2 +if [ -e "$TMP/broken" ]; then + echo "checking a leased file broke its lease" >&2 + exit 1 +fi +release_holder + +# A device cannot be leased. A distinctive fake fuser status proves that the +# one-shot helper immediately replaces itself with the compatibility command. +expect_status 7 /dev/null + +# If leases cannot answer and fuser cannot be executed, status 2 tells +# age_mover not to mistake the file for clear. +mkdir "$TMP/empty-bin" +set +e +PATH="$TMP/empty-bin" "$(command -v perl)" "$HELPER" /dev/null 2>/dev/null +uncheckable_status=$? +set -e +[ "$uncheckable_status" -eq 2 ] + +# Keep age_mover's integration deliberately small: it knows only the helper's +# result contract, not whether a lease or fuser produced the answer. +grep -q '"${FILES_IN_USE_CMD\[@\]}" "$@"' "$MOVER" +grep -qE 'FILE_IN_USE_MODE|FILE_IN_USE_CHECK|FUSER_BATCH_SAFE|actionRows' "$MOVER" && exit 1 +grep -qE 'coproc|--server|fileLease(Start|Stop|Request)' "$MOVER" && exit 1 + +# age_mover treats an unavailable answer as in-use, and reports it only once. +source <(sed -n '/^\(chooseFilesInUseCheck\|filesInUse\)() {/,/^}/p' "$MOVER") +MOVE_IN_USE=no +fake_helper="$TMP/fake-helper" +# age_mover runs the helper through perl +printf 'exit $ENV{CHECK_STATUS};\n' >"$fake_helper" +chmod +x "$fake_helper" +# Read by the sourced filesInUse, which ShellCheck cannot see. +# shellcheck disable=SC2034 +FILES_IN_USE_HELPER=$fake_helper +LOG_COUNT=0 +mvlogger() { LOG_COUNT=$((LOG_COUNT + 1)); } +# Stands in for processTheMoves, which owns the once-per-run flag as a local. +mover_run() { + local FILE_IN_USE_FAILURE_LOGGED=no + local -a FILES_IN_USE_CMD=() + chooseFilesInUseCheck + export CHECK_STATUS=0 + filesInUse "$plain" + export CHECK_STATUS=1 + if filesInUse "$plain"; then + echo "clear helper result was reported in use" >&2 + exit 1 + fi + export CHECK_STATUS=2 + filesInUse "$plain" + filesInUse "$plain" +} +mover_run +[ "$LOG_COUNT" -eq 1 ] +# The next run warns again, and the flag does not leak out of the run. +mover_run +[ "$LOG_COUNT" -eq 2 ] +[ -z "${FILE_IN_USE_FAILURE_LOGGED+set}" ] +[ -z "${FILES_IN_USE_CMD+set}" ] + +# Without Perl, as before Unraid 6.11.0, age_mover runs fuser -s itself, and says so once per run. +old_run() { + local FILE_IN_USE_FAILURE_LOGGED=no + local -a FILES_IN_USE_CMD=() + chooseFilesInUseCheck + [ "${FILES_IN_USE_CMD[*]}" = "fuser -s" ] + export FUSER_STATUS=0 + filesInUse "$plain" + export FUSER_STATUS=1 + if filesInUse "$plain"; then + echo "clear fuser result was reported in use" >&2 + exit 1 + fi +} +printf '#!/bin/sh\n[ "$1" = -s ] || exit 9\nexit "$FUSER_STATUS"\n' >"$TMP/bin/fuser" +LOG_COUNT=0 +PATH="$TMP/bin" old_run +[ "$LOG_COUNT" -eq 1 ] +# Without fuser either, the file stays put and the unchecked-file warning follows the fuser one. +no_fuser_run() { + local FILE_IN_USE_FAILURE_LOGGED=no + local -a FILES_IN_USE_CMD=() + PATH="$TMP/empty-bin" chooseFilesInUseCheck + PATH="$TMP/empty-bin" filesInUse "$plain" + PATH="$TMP/empty-bin" filesInUse "$plain" +} +LOG_COUNT=0 +no_fuser_run +[ "$LOG_COUNT" -eq 2 ] +# A helper that does not compile would fail closed on every file, so fuser checks them, said once per run. +FILES_IN_USE_HELPER=$TMP/missing-helper +LOG_COUNT=0 +chooseFilesInUseCheck +[ "${FILES_IN_USE_CMD[*]}" = "fuser -s" ] +[ "$LOG_COUNT" -eq 1 ] +FILES_IN_USE_HELPER=$fake_helper +# With "Move files that are in use" on, nothing is checked, so the fuser note is not logged. +# shellcheck disable=SC2034 # read by the sourced chooseFilesInUseCheck +MOVE_IN_USE=yes +LOG_COUNT=0 +PATH="$TMP/empty-bin" chooseFilesInUseCheck +[ "$LOG_COUNT" -eq 0 ] +# With Perl in PATH, wherever it is, the helper runs through it. +mkdir "$TMP/perl-bin" +ln -s "$(command -v perl)" "$TMP/perl-bin/perl" +PATH="$TMP/perl-bin" chooseFilesInUseCheck +[ "${FILES_IN_USE_CMD[*]}" = "perl $FILES_IN_USE_HELPER" ] + +echo "file lease tests passed" diff --git a/.github/workflows/auto-merge.yml b/.github/workflows/auto-merge.yml deleted file mode 100644 index 970771f1..00000000 --- a/.github/workflows/auto-merge.yml +++ /dev/null @@ -1,20 +0,0 @@ -name: Auto-merge Dependabot PRs - -on: - pull_request: - types: [opened, synchronize] - -permissions: - contents: write - pull-requests: write - -jobs: - automerge: - if: github.actor == 'dependabot[bot]' - runs-on: ubuntu-latest - steps: - - name: Enable auto-merge - run: gh pr merge --merge "$PR_URL" - env: - PR_URL: ${{ github.event.pull_request.html_url }} - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index deb03328..f4ff6383 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,12 +19,17 @@ jobs: with: persist-credentials: false - - name: Install xmllint - run: sudo apt-get update -qq && sudo apt-get install -y -qq libxml2-utils + - name: Install test tools + run: sudo apt-get update -qq && sudo apt-get install -y -qq libxml2-utils perl - name: Validate plugin manifest (XML) run: xmllint --noout plugins/ca.mover.tuning.plg + - name: Test mover file leases + run: | + bash -n source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/age_mover + bash .github/scripts/test_files_in_use.sh + # CHANGELOG.md must render to the committed CHANGES block for this branch's channel, # pluginURL must point at this branch, and the manifest md5 must match the served package. - name: Verify changelog, manifest and served package agree @@ -83,3 +88,43 @@ jobs: - name: Run tests run: python -m pytest .github/scripts/release/tests -q + + age-mover: + name: age_mover tests + runs-on: ubuntu-latest + container: debian:bookworm-slim + timeout-minutes: 10 + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Run the age_mover tests + env: + AGE_MOVER_TEST: '1' + run: bash tests/age_mover/run.sh + + # Dependabot's pull requests merge once the jobs above pass; release-notes runs only for the stable release PR. + # The PR's author, not github.actor: the actor is whoever acted last and can be spoofed + dependabot-merge: + name: Merge Dependabot pull request + needs: [validate, release-notes, release-scripts, age-mover] + if: >- + !cancelled() && github.event_name == 'pull_request' + && github.event.pull_request.user.login == 'dependabot[bot]' + && github.repository == github.event.pull_request.head.repo.full_name + && needs.validate.result == 'success' && needs.release-scripts.result == 'success' + && needs.age-mover.result == 'success' && contains(fromJSON('["success", "skipped"]'), needs.release-notes.result) + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write + steps: + - name: Merge + env: + PR_URL: ${{ github.event.pull_request.html_url }} + # the head this run tested: a newer push merges only after its own run passes + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + GH_TOKEN: ${{ github.token }} + run: gh pr merge --merge --match-head-commit "$HEAD_SHA" "$PR_URL" diff --git a/.github/workflows/discord-notify.yml b/.github/workflows/discord-notify.yml index 0e9c0a1c..50b1eeef 100644 --- a/.github/workflows/discord-notify.yml +++ b/.github/workflows/discord-notify.yml @@ -7,57 +7,16 @@ on: types: [opened, closed, reopened] issues: types: [opened, closed, reopened] - workflow_run: - workflows: ["Release"] - types: [completed] workflow_dispatch: -permissions: - actions: read +permissions: {} jobs: notify_discord: runs-on: ubuntu-latest steps: - # --------------------------------------------------------- - # 1. Download release info artifact (workflow_run only) - # --------------------------------------------------------- - - name: Download release info artifact - id: release_artifact - if: ${{ github.event_name == 'workflow_run' }} - continue-on-error: true - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 - with: - name: release_info - github-token: ${{ secrets.GITHUB_TOKEN }} - run-id: ${{ github.event.workflow_run.id }} - - # --------------------------------------------------------- - # 2. Parse release info JSON - # --------------------------------------------------------- - - name: Read release info - if: ${{ github.event_name == 'workflow_run' && steps.release_artifact.outcome == 'success' }} - id: release_info - run: | - RELEASE_TAG=$(jq -r '.release_tag' release_info.json) - RELEASE_NAME=$(jq -r '.release_name' release_info.json) - NEW_RELEASE=$(jq -r '.new_release' release_info.json) - - { - echo "RELEASE_TAG=${RELEASE_TAG}" - echo "RELEASE_NAME=${RELEASE_NAME}" - echo "NEW_RELEASE=${NEW_RELEASE}" - } >> "${GITHUB_ENV}" - - # --------------------------------------------------------- - # 3. Build & send Discord embed - # --------------------------------------------------------- - - # Notify unless workflow_run succeeded without a new release, or was cancelled or skipped - name: Send Discord Notification - if: ${{ github.event_name != 'workflow_run' || env.NEW_RELEASE == 'true' || !contains(fromJSON('["success", "cancelled", "skipped"]'), github.event.workflow_run.conclusion) }} - env: WEBHOOK: ${{ secrets.DISCORD_WEBHOOK }} EVENT: ${{ github.event_name }} @@ -68,9 +27,8 @@ jobs: # Release info RELEASE_URL: ${{ github.event.release.html_url || '' }} RELEASE_BODY: ${{ github.event.release.body || '' }} - RELEASE_TAG: ${{ github.event.release.tag_name || env.RELEASE_TAG || '' }} - RELEASE_NAME: ${{ github.event.release.name || env.RELEASE_NAME || '' }} - NEW_RELEASE: ${{ github.event_name == 'release' && 'true' || env.NEW_RELEASE || 'false' }} + RELEASE_TAG: ${{ github.event.release.tag_name || '' }} + RELEASE_NAME: ${{ github.event.release.name || '' }} # PR / Issue info PR_TITLE: ${{ github.event.pull_request.title || '' }} @@ -82,13 +40,6 @@ jobs: ISSUE_URL: ${{ github.event.issue.html_url || '' }} ISSUE_BODY: ${{ github.event.issue.body || '' }} - # Workflow run info - WORKFLOW_NAME: ${{ github.event.workflow_run.name || '' }} - WORKFLOW_CONCLUSION: ${{ github.event.workflow_run.conclusion || '' }} - WORKFLOW_URL: ${{ github.event.workflow_run.html_url || '' }} - WORKFLOW_STARTED: ${{ github.event.workflow_run.run_started_at || '' }} - WORKFLOW_FINISHED: ${{ github.event.workflow_run.updated_at || '' }} - run: | # ----------------------------------------------------- # Guard: Webhook must exist @@ -159,27 +110,6 @@ jobs: COLOR=9807270 fi ;; - workflow_run) - URL="${WORKFLOW_URL:-https://github.com/${REPO}/actions}" - TITLE="${WORKFLOW_NAME}" - BODY="Workflow completed with conclusion: ${WORKFLOW_CONCLUSION}" - - if [ "${WORKFLOW_CONCLUSION}" = "success" ]; then - ICON="✅" - CONTENT="Workflow Succeeded" - COLOR=5763719 - else - ICON="❌" - CONTENT="Workflow Failed" - COLOR=10038562 - fi - - if [ "${NEW_RELEASE}" = "true" ]; then - BODY="${BODY}"$'\n'"Built Version: ${RELEASE_TAG}" - TITLE="${TITLE} — ${RELEASE_TAG}" - CONTENT="Workflow Succeeded — New Release" - fi - ;; *) ICON="🧭" CONTENT="Manual Trigger" @@ -190,33 +120,6 @@ jobs: ;; esac - # ----------------------------------------------------- - # Compute workflow duration (guard null) - # ----------------------------------------------------- - DURATION="" - if [ "${EVENT}" = "workflow_run" ] && - [ "${WORKFLOW_STARTED}" != "null" ] && - [ "${WORKFLOW_FINISHED}" != "null" ] && - [ -n "${WORKFLOW_STARTED}" ] && - [ -n "${WORKFLOW_FINISHED}" ]; then - - START=$(date -d "${WORKFLOW_STARTED}" +%s) - END=$(date -d "${WORKFLOW_FINISHED}" +%s) - ELAPSED=$((END - START)) - - H=$((ELAPSED / 3600)) - M=$(((ELAPSED % 3600) / 60)) - S=$((ELAPSED % 60)) - - if [ ${H} -gt 0 ]; then - DURATION="${H}h ${M}m ${S}s" - elif [ ${M} -gt 0 ]; then - DURATION="${M}m ${S}s" - else - DURATION="${S}s" - fi - fi - # ----------------------------------------------------- # Build JSON using jq (safe & correct) # ----------------------------------------------------- @@ -231,8 +134,6 @@ jobs: --arg release_tag "${RELEASE_TAG}" \ --arg release_name "${RELEASE_NAME}" \ --arg event "${EVENT}" \ - --arg new_release "${NEW_RELEASE}" \ - --arg duration "${DURATION}" \ --argjson color "${COLOR}" \ ' { @@ -251,7 +152,7 @@ jobs: ] + ( - if ($event == "release" or $new_release == "true") then + if $event == "release" then [ {name: "Release Tag", value: $release_tag, inline: true}, {name: "Release Name", value: $release_name, inline: true} @@ -260,16 +161,6 @@ jobs: [] end ) - + - ( - if ($event == "workflow_run" and $duration != "") then - [ - {name: "Duration", value: $duration, inline: true} - ] - else - [] - end - ) ) } ] diff --git a/.github/workflows/pr-cleanup.yml b/.github/workflows/pr-cleanup.yml index f0b7e86f..46c6a407 100644 --- a/.github/workflows/pr-cleanup.yml +++ b/.github/workflows/pr-cleanup.yml @@ -1,14 +1,21 @@ name: PR cleanup -# Removes the pr-- test builds when a pull request closes. Checks out nothing. +# Every hour, removes the pr-- test builds of closed pull requests and says so in their build +# comment. Checks out nothing. A schedule runs the default branch's copy of this file, and GitHub turns it off after +# 60 days without repository activity: turn it back on from the Actions tab. on: - pull_request_target: - types: [closed] + schedule: + - cron: '17 * * * *' + workflow_dispatch: permissions: contents: write pull-requests: write +concurrency: + group: pr-cleanup + cancel-in-progress: false + env: GH_TOKEN: ${{ github.token }} @@ -16,24 +23,55 @@ jobs: cleanup: runs-on: ubuntu-latest steps: - - name: Remove the pull request releases, their tags and the note - env: - PR: ${{ github.event.pull_request.number }} + - name: Remove closed pull requests' releases and tags, and mark their notes removed run: | set -euo pipefail - # listed first: a failing call inside a process substitution would read as "nothing to remove" - tags=$(gh api --paginate "repos/$GITHUB_REPOSITORY/releases" --jq ".[] | select(.prerelease and (.tag_name | startswith(\"pr-$PR-\"))) | .tag_name") - [ -n "$tags" ] || echo "No test build for #$PR." - while read -r tag; do - [ -n "$tag" ] || continue - # a publish run that saw the close may have removed it already: "release not found" is that outcome - out=$(gh release delete --repo "$GITHUB_REPOSITORY" "$tag" --yes --cleanup-tag 2>&1) \ - || [[ "$out" == *"release not found"* ]] || { echo "$out" >&2; exit 1; } - echo "removed $tag" - done <<< "$tags" - # also when nothing was left: an earlier attempt may have removed the builds and failed before this marker="" - id=$(gh api --paginate "repos/$GITHUB_REPOSITORY/issues/$PR/comments?per_page=100" --jq ".[] | select(.user.login == \"github-actions[bot]\" and (.body | startswith(\"$marker\"))) | .id" | head -n 1) - if [ -n "$id" ] && [ "$id" != "null" ]; then + # set -e does not reach into a function called with ||, so every failure returns 1 itself + note() { # $1 pull request, $2 closed or gone (deleted, so no note to update) + local id + [ "$2" = closed ] || return 0 + id=$(gh api --paginate "repos/$GITHUB_REPOSITORY/issues/$1/comments?per_page=100" --jq ".[] | select(.user.login == \"github-actions[bot]\" and (.body | startswith(\"$marker\"))) | .id") || return 1 + id=${id%%$'\n'*} + [ -n "$id" ] || return 0 gh api "repos/$GITHUB_REPOSITORY/issues/comments/$id" -X PATCH -f body="$marker"$'\n'"The test build for this pull request has been removed." >/dev/null - fi + } + clean() { # $1 pull request, $2 its tags, $3 closed or gone + local tag out + while read -r tag; do + grep -qxF -- "$tag" <<< "$builds" || continue + # a publish run that saw the close may remove it first: "release not found", or a 404 when it does so + # between gh's lookup and its delete, is that outcome + out=$(gh release delete --repo "$GITHUB_REPOSITORY" "$tag" --yes 2>&1) \ + || [[ "$out" == *"release not found"* || "$out" == *"HTTP 404"* ]] || { echo "$out" >&2; return 1; } + done <<< "$2" + # after the release deletes: a publish run's comment lands before it or finds no release (pr-publish). Before + # the tag deletes: a failed note keeps the tags, so the next sweep comes back to this pull request + note "$1" "$3" || return 1 + while read -r tag; do + # a publish run's --cleanup-tag may remove it first: GitHub answers that with this 422, or a 404 + out=$(gh api -X DELETE "repos/$GITHUB_REPOSITORY/git/refs/tags/$tag" 2>&1 >/dev/null) \ + || [[ "$out" == *"Reference does not exist"* || "$out" == *"HTTP 404"* ]] || { echo "$out" >&2; return 1; } + echo "removed $tag" + done <<< "$2" + } + # listed first: a failing call inside a process substitution would read as "nothing to remove". Tags before + # releases, so a release published between the two lists is never taken for a tag without one + refs=$(gh api --paginate "repos/$GITHUB_REPOSITORY/git/matching-refs/tags/pr-" --jq '.[].ref | ltrimstr("refs/tags/") | select(test("^pr-[0-9]+-"))') + listed=$(gh api --paginate "repos/$GITHUB_REPOSITORY/releases" --jq '.[] | select(.tag_name | test("^pr-[0-9]+-")) | "\(.prerelease) \(.tag_name)"') + builds=$(sed -n 's/^true //p' <<< "$listed") + # a tag no release has: clean deletes tags last, so a failure after the release deletes leaves them behind + orphans=$(grep -vxF -f <(sed 's/^[a-z]* //' <<< "$listed") <<< "$refs") || [ $? = 1 ] + tags=$(printf '%s\n' "$builds" "$orphans" | sed '/^$/d' | sort -u) + [ -n "$tags" ] || { echo "No test builds."; exit 0; } + rc=0 + while read -r -u 3 pr; do + if ! state=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$pr" --jq .state 2>&1); then + # a deleted pull request answers 404: its builds go too, else every sweep would fail on it + [[ "$state" == *"(HTTP 404)"* ]] || { echo "::error::cannot read #$pr: $state"; rc=1; continue; } + state=gone + fi + case $state in closed | gone) ;; *) continue ;; esac + clean "$pr" "$(grep "^pr-$pr-" <<< "$tags")" "$state" || { echo "::error::could not clean up #$pr"; rc=1; } + done 3<<< "$(sed -E 's/^pr-([0-9]+)-.*/\1/' <<< "$tags" | sort -un)" + exit $rc diff --git a/.github/workflows/pr-publish.yml b/.github/workflows/pr-publish.yml index 6bcfe000..48e16e12 100644 --- a/.github/workflows/pr-publish.yml +++ b/.github/workflows/pr-publish.yml @@ -4,7 +4,7 @@ name: PR publish # publishes it as the pr-- pre-release, verifies what a server will fetch and keeps one # comment on the pull request current. Never checks out or runs pull request code. on: - workflow_run: + workflow_run: # zizmor: ignore[dangerous-triggers] takes only the build artifact and never runs pull request code workflows: ["PR build"] types: [completed] @@ -113,7 +113,7 @@ jobs: set -euo pipefail notes=$(mktemp) { - echo "Test build of pull request #$PR at ${HEAD_SHA::7}. Not a release: the next build of this pull request replaces it, closing the pull request removes it, and the next real release supersedes it on installed servers." + echo "Test build of pull request #$PR at ${HEAD_SHA::7}. Not a release: the next build of this pull request replaces it, PR cleanup's hourly sweep removes it after the pull request closes, and the next real release supersedes it on installed servers." echo echo "Install: Plugins > Install Plugin > paste \`$INSTALL_URL\`" } > "$notes" @@ -153,9 +153,10 @@ jobs: env: TAG: ${{ steps.meta.outputs.tag }} run: | - # PR cleanup may have removed it already: "release not found" is that outcome, anything else is not + # PR cleanup may remove it first: "release not found", or a 404 when it does so between gh's lookup and its + # delete, is that outcome, anything else is not out=$(gh release delete --repo "$GITHUB_REPOSITORY" "$TAG" --cleanup-tag --yes 2>&1) \ - || [[ "$out" == *"release not found"* ]] || { echo "$out" >&2; exit 1; } + || [[ "$out" == *"release not found"* || "$out" == *"HTTP 404"* ]] || { echo "$out" >&2; exit 1; } - name: Remove older builds of this pull request if: steps.pr.outputs.number != '' @@ -168,7 +169,7 @@ jobs: --jq ".[] | select(.prerelease and .tag_name != \"$TAG\" and (.tag_name | startswith(\"pr-$PR-\"))) | .tag_name" \ | while read -r old; do out=$(gh release delete --repo "$GITHUB_REPOSITORY" "$old" --cleanup-tag --yes 2>&1) \ - || [[ "$out" == *"release not found"* ]] || { echo "$out" >&2; exit 1; } + || [[ "$out" == *"release not found"* || "$out" == *"HTTP 404"* ]] || { echo "$out" >&2; exit 1; } echo "removed $old" done @@ -180,11 +181,13 @@ jobs: TAG: ${{ steps.meta.outputs.tag }} run: | set -euo pipefail - # PR cleanup also runs on close; whichever gets there first removes the build, so "release not found" - # here means cleanup did, and the build is gone either way - if [ "$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR" --jq .state)" != "open" ]; then - out=$(gh release delete --repo "$GITHUB_REPOSITORY" "$TAG" --cleanup-tag --yes 2>&1) \ - || [[ "$out" == *"release not found"* ]] || { echo "$out" >&2; exit 1; } + # its own line, so set -e stops on an unreadable pull request instead of removing an open one's build + state=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR" --jq .state) + # PR cleanup's sweep may get there first ("release not found", or a 404 between gh's lookup and its delete). + # The tag stays: that sweep finds it, notes the comment and removes it, so a failed note below is redone + if [ "$state" != "open" ]; then + out=$(gh release delete --repo "$GITHUB_REPOSITORY" "$TAG" --yes 2>&1) \ + || [[ "$out" == *"release not found"* || "$out" == *"HTTP 404"* ]] || { echo "$out" >&2; exit 1; } echo "closed=true" >> "$GITHUB_OUTPUT" echo "Pull request #$PR closed while publishing; the release was removed again." fi @@ -199,10 +202,12 @@ jobs: BUILD_LOG: ${{ github.event.workflow_run.html_url }} VERIFIED: ${{ steps.verify.outcome == 'success' }} CLOSED: ${{ steps.closed.outputs.closed == 'true' }} + TAG: ${{ steps.meta.outputs.tag }} run: | set -euo pipefail + removed=$(printf '%s\n' "$MARKER" "The test build for this pull request has been removed.") if [ "$CLOSED" = true ]; then - body=$(printf '%s\n' "$MARKER" "The test build for this pull request has been removed.") + body=$removed elif [ "$VERIFIED" = true ]; then body=$(printf '%s\n' "$MARKER" "Test build \`$VERSION\` of ${HEAD_SHA::7} ([build log]($BUILD_LOG)). Install from Plugins, Install Plugin, with this URL:" "" '```' "$INSTALL_URL" '```' "" "It installs over the current release and the next real release supersedes it. Add the \`$LABEL\` label again for a new build.") else @@ -213,8 +218,14 @@ jobs: if [ -n "$id" ]; then gh api "repos/$GITHUB_REPOSITORY/issues/comments/$id" -X PATCH -f body="$body" >/dev/null else - gh api "repos/$GITHUB_REPOSITORY/issues/$PR/comments" -X POST -f body="$body" >/dev/null + id=$(gh api "repos/$GITHUB_REPOSITORY/issues/$PR/comments" -X POST -f body="$body" --jq .id) fi + # checked after the write: PR cleanup may have removed the build since the closed check, and it notes after + # its release deletes, so whichever note lands last says what is there + [ "$VERIFIED" = true ] && [ "$CLOSED" != true ] || exit 0 + out=$(gh release view --repo "$GITHUB_REPOSITORY" "$TAG" 2>&1 >/dev/null) && exit 0 + [[ "$out" == *"release not found"* ]] || { echo "$out" >&2; exit 1; } + gh api "repos/$GITHUB_REPOSITORY/issues/comments/$id" -X PATCH -f body="$removed" >/dev/null - name: Take the label off so the next build needs a new go if: always() && steps.pr.outputs.number != '' diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 39d59c61..19a5fff4 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -181,3 +181,29 @@ jobs: CHANNEL: beta BASE: ${{ env.BETA_BRANCH }} run: bash "$SCRIPTS/plg_release_pr.sh" + + # discord-notify.yml announces each published release; a failed release job only here, a run that cannot start not at all + notify-failure: + name: Tell Discord the Release run failed + needs: release + if: failure() + runs-on: ubuntu-latest + permissions: {} + steps: + - name: Send the Discord notification + env: + WEBHOOK: ${{ secrets.DISCORD_WEBHOOK }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + set -euo pipefail + if [ -z "$WEBHOOK" ]; then + echo "::warning::DISCORD_WEBHOOK is not set, skipping notification" + exit 0 + fi + json=$(jq -n --arg title "Release on $GITHUB_REF_NAME" --arg url "$RUN_URL" --arg actor "$GITHUB_ACTOR" \ + --arg repo "$GITHUB_REPOSITORY" --arg timestamp "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \ + '{content: "❌ Release run failed", embeds: [{title: $title, url: $url, description: "The Release run failed: see its log.", + color: 10038562, timestamp: $timestamp, + fields: [{name: "Repository", value: $repo, inline: true}, {name: "Actor", value: $actor, inline: true}]}]}') + curl --fail-with-body --silent --show-error --connect-timeout 10 --max-time 30 \ + -H "Content-Type: application/json" -d "$json" "$WEBHOOK" diff --git a/CHANGELOG.md b/CHANGELOG.md index a72924bd..ff5a721a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,37 @@ # Changelog +## Unreleased + +- perf: Faster in-use file checks: file leases replace fuser where the system supports them. (coppit) +- perf: Logging costs much less, and almost nothing when it is off. (coppit) +- perf: Large moves run faster, with fewer hardlink lookups and top folder checks. (chodeus, coppit) +- fix: Apply now changes the mover schedule to the saved settings. (chodeus) +- fix: File names holding $, <, : and similar characters now move; the filename check is removed. (chodeus) +- fix: A file name holding < or > no longer breaks notifications before Unraid 7.2. (chodeus) +- fix: Clean empty ZFS datasets keeps a dataset until everything in it has moved. (chodeus) +- fix: Clean empty folders keeps the folder of a failed move, and on Yes the share's top folder. (chodeus) +- fix: Turbo write is now restored when a move is stopped, Move Now included. (chodeus) +- fix: Move Now no longer reads Unassigned Devices mounts or runs text from a share name. (chodeus) +- fix: Test mode's folder cleanup and turbo write lines now match what a real run does. (chodeus) + +## 2026.11.26b (beta) + +- No changes to the plugin since 2026.11.26a: README updates and release workflow fixes only. (masterwishx, chodeus) + +## 2026.11.26a (beta) + +- perf: Faster in-use file checks: file leases replace fuser where the system supports them. (coppit) +- perf: Logging costs much less, and almost nothing when it is off. (coppit) +- perf: Large moves run faster, with fewer hardlink lookups and top folder checks. (chodeus, coppit) +- fix: Apply now changes the mover schedule to the saved settings. (chodeus) +- fix: File names holding $, <, : and similar characters now move; the filename check is removed. (chodeus) +- fix: A file name holding < or > no longer breaks notifications before Unraid 7.2. (chodeus) +- fix: Clean empty ZFS datasets keeps a dataset until everything in it has moved. (chodeus) +- fix: Clean empty folders keeps the folder of a failed move, and on Yes the share's top folder. (chodeus) +- fix: Turbo write is now restored when a move is stopped, Move Now included. (chodeus) +- fix: Move Now no longer reads Unassigned Devices mounts or runs text from a share name. (chodeus) +- fix: Test mode's folder cleanup and turbo write lines now match what a real run does. (chodeus) + ## 2026.11.13 - fix: The Log files list now shows new logs without a page reload. (chodeus) diff --git a/README.md b/README.md index 96e75544..cc7d41b2 100644 --- a/README.md +++ b/README.md @@ -16,11 +16,11 @@ This is an [Unraid](https://unraid.net/) plugin that lets you fine-tune the operation of the [mover](https://docs.unraid.net/unraid-os/using-unraid-to/manage-storage/cache-pools/#using-mover). -This fork merges all [pull requests](https://github.com/R3yn4ld/ca.mover.tuning/pulls) from [R3yn4ld](https://github.com/R3yn4ld/ca.mover.tuning) after review (cosmetics, per-share skipfiletypes merge, automatic age threshold, filename sanitizing, Unraid 7.x compatibility) and adds many new features. See [CHANGELOG.md](CHANGELOG.md) for the full history. +This fork merges all [pull requests](https://github.com/R3yn4ld/ca.mover.tuning/pulls) from [R3yn4ld](https://github.com/R3yn4ld/ca.mover.tuning) after review (cosmetics, per-share skipfiletypes merge, automatic age threshold, Unraid 7.x compatibility) and adds many new features. See [CHANGELOG.md](CHANGELOG.md) for the full history. ## Requirements -**Unraid 6.9.0-rc2 or newer.** Unraid 7.2.1+ and the 7.4.0 are supported (see [Unraid 7.2.1 and newer](#unraid-721-and-newer)). +**Unraid 6.9.0-rc2 or newer.** With Perl, which is part of Unraid's base distribution from 6.11.0, the mover checks whether a file is in use faster, with a Linux file lease. Unraid 7.2.1+ and the 7.4.0 are supported (see [Unraid 7.2.1 and newer](#unraid-721-and-newer)). ## Features @@ -55,7 +55,6 @@ This fork merges all [pull requests](https://github.com/R3yn4ld/ca.mover.tuning/ ### Safety, logging and troubleshooting - Test Mode (dry run) with clear warnings. -- Optional filename **validation** with a configurable list of blocked characters. - **Live progress** of a run under the Move button: named steps (filtering, deciding, moving), the file being processed, size left, speed and ETA. Updated every 5 seconds while a file moves (with the Move tool, in 2 GiB steps). - Verified results: a move or sync counts as successful only after the file has arrived at the destination and been removed from the source. Successful and failed items are counted and reported separately in logs and notifications. - **Pause** and **Resume** buttons on Main and next to "Move now" while a run moves files. An Rsync copy pauses at once; with Move, the run pauses once the current file is done. The per-share Move and the runs of the built-in mover that the plugin starts (forced move, "Move now" without the filters) pause once their current file is done; runs Unraid starts itself are left alone. The next scheduled run or a cache watchdog trigger resumes a paused run. @@ -86,7 +85,7 @@ Please note that if the age setting is set to something other than "Auto (smart Files at the top level of the cache or an array disk (i.e. not in a share) are never moved. The list is then processed with the chosen tool (Rsync by default, or Unraid's move utility). -For each file, if the file is not "in use" by any process (as detected by the 'fuser' command), then the file is moved and, upon success, deleted from the source disk. If the file already exists on the target, it is not moved and the source is not deleted. All metadata of moved files/directories is preserved: permissions, ownership, extended attributes, and access/modified timestamps. +For each file, if the file is not "in use" by any process (as detected by an exclusive Linux file lease, with `fuser` as a compatibility fallback when leases or Perl are unavailable), then the file is moved and, upon success, deleted from the source disk. If the file already exists on the target, it is not moved and the source is not deleted. All metadata of moved files/directories is preserved: permissions, ownership, extended attributes, and access/modified timestamps. If an error occurs while copying a file, the partial file, if present, is deleted and the operation continues on to the next file. ## Changelog @@ -119,7 +118,7 @@ You'll find the settings on the Mover Tuning page within Settings - [Scheduler]( | Section | What you can set | | --- | --- | -| **Plugin Settings** | Disable the plugin's schedule, cache watchdog and its trigger level, Mover Tuning schedule, Test Mode (dry run), filename validation and blocked characters, logging, debug logging and notifications, log folder, log files (view or download) and log retention, parity check behavior, mover and disk I/O priority, force move of all files on a schedule, before/after scripts. | +| **Plugin Settings** | Disable the plugin's schedule, cache watchdog and its trigger level, Mover Tuning schedule, Test Mode (dry run), logging, debug logging and notifications, log folder, log files (view or download) and log retention, parity check behavior, mover and disk I/O priority, force move of all files on a schedule, before/after scripts. | | **Filters** | Whether "Move now" follows the plugin filters, thresholds (move above, free down, fill up), age, move order, CTIME/ATIME, minimum size, sync maximum size, sparseness, ignore list file, ignored file types, hidden files, and "Move All" for cache:yes shares above a pool percentage. | | **Options** | Force turbo write, move files tool, move files that are in use, move/clean empty folders, clean empty ZFS datasets, share size calculation, Synchronize, Rebalance and Resynchronize. Buttons: Apply, Done, Defaults and Move Now, and Pause or Resume while a run moves files. | | **Help** | Debug package (.zip), a link to the support thread, GitHub link and a collapsible "CLI help commands" panel. | @@ -186,4 +185,4 @@ This was originally created by [Squid](https://github.com/Squidly271). @2025 – Updated by [masterwishx](https://github.com/masterwishx/ca.mover.tuning). -@2026 – Updated by [masterwishx](https://github.com/masterwishx/ca.mover.tuning) and [chodeus](https://github.com/chodeus), with contributions by [Joly0](https://github.com/Joly0). +@2026 – Updated by [masterwishx](https://github.com/masterwishx/ca.mover.tuning) and [chodeus](https://github.com/chodeus), with contributions by [Joly0](https://github.com/Joly0), [coppit](https://github.com/coppit). diff --git a/plugins/ca.mover.tuning.plg b/plugins/ca.mover.tuning.plg index 029ed0c7..67582e6f 100644 --- a/plugins/ca.mover.tuning.plg +++ b/plugins/ca.mover.tuning.plg @@ -724,6 +724,10 @@ else echo "- Updating freeingThreshold" grep -m1 '^movingThreshold=' "$config_file" | sed 's/^movingThreshold/freeingThreshold/' >> "$config_file" fi + if grep -qE '^(validateFilenames|invalidFileChars)=' "$config_file"; then + echo "- Removing the old filename check's settings" + sed -i -E '/^(validateFilenames|invalidFileChars)=/d' "$config_file" + fi fi # Read Unraid version @@ -742,7 +746,6 @@ if version_ge "$UNRAID_VERSION" "7.2.1"; then TUNING_CRON_FILE="/boot/config/plugins/&name;/mover.tuning.cron" DYNAMIX_CRON_FILE="/boot/config/plugins/dynamix/mover.cron" - DYNAMIX_CRON_OLD="/boot/config/plugins/dynamix/mover.cron.old" # Only perform migration if mover.tuning.cron does NOT exist # AND old dynamix/mover.cron exists @@ -759,17 +762,12 @@ if version_ge "$UNRAID_VERSION" "7.2.1"; then echo "Setting moverTuneCron to: [$SHARE_MOV_SCHED]" echo "moverTuneCron=\"$SHARE_MOV_SCHED\"" >> "$config_file" - # Create cron file for Mover Tuning, unless its schedule was disabled before 7.2.1 - if grep -q '^moverDisabled="yes"' "$config_file"; then - echo "Mover Tuning schedule is disabled — no Mover Tuning cron file created." + # updateCron.php retires mover.cron at the first sync or apply that finds this marker and the schedule written, cleared or disabled + if touch /boot/config/plugins/&name;/retire.unraid.schedule; then + echo "mover.cron becomes mover.cron.old once mover.tuning.cron is written, or the schedule is cleared or disabled." else - echo "Creating Mover Tuning cron file: $TUNING_CRON_FILE" - printf '# Generated schedule for Mover Tuning move:\n%s /usr/local/emhttp/plugins/&name;/mover start |& logger -t move\n' "$SHARE_MOV_SCHED" > "$TUNING_CRON_FILE" + echo "The retirement marker could not be written, so mover.cron stays: rename it to mover.cron.old by hand." fi - - # Rename old dynamix cron file - echo "Renaming old schedule: mover.cron → mover.cron.old" - mv "$DYNAMIX_CRON_FILE" "$DYNAMIX_CRON_OLD" else echo "shareMoverSchedule is empty — nothing to migrate." fi @@ -869,7 +867,7 @@ if [[ -f "$config_file" ]] && ! grep -q '^migratedOverrideNo=' "$config_ echo 'migratedOverrideNo="yes"' >> "$config_file" fi -# The plugin's own cron files follow the saved settings: missing ones are written back (reinstall), stale ones removed +# Bring the plugin's own cron files in line with the saved settings; an invalid schedule is logged and its file kept /usr/bin/php -q /usr/local/emhttp/plugins/&name;/updateCron.php sync # Refresh cron diff --git a/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/Mover.tuning.page b/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/Mover.tuning.page index b82ffe64..656a5bd2 100644 --- a/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/Mover.tuning.page +++ b/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/Mover.tuning.page @@ -14,12 +14,12 @@ $config_file = '/boot/config/plugins/' . $plugin . '/' . $plugin . '.cfg'; $config_default_file = '/usr/local/emhttp/plugins/' . $plugin . '/default.cfg'; $cfg = parse_plugin_cfg($plugin); require_once '/usr/local/emhttp/plugins/ca.mover.tuning/logFiles.php'; +require_once '/usr/local/emhttp/plugins/ca.mover.tuning/cronSchedule.php'; $moverLogFiles = array_keys(moverLogFiles($cfg)); $advancedSettings = ($cfg['advancedSettings'] != "yes") ? "no" : "yes"; $advancedFilters = ($cfg['advancedFilters'] != "yes") ? "no" : "yes"; $advancedOptions = ($cfg['advancedOptions'] != "yes") ? "no" : "yes"; $moverDisabled = ($cfg['moverDisabled'] != "yes") ? "no" : "yes"; -$validateFilenames = ($cfg['validateFilenames'] != "yes") ? "no" : "yes"; $ageDisabled = ($cfg['age'] != "yes") ? "disabled" : ""; $cronDisabled = ($cfg['force'] != "yes") ? "disabled" : ""; $filelistfDisabled = ($cfg['filelistf'] != "yes") ? "disabled" : ""; @@ -113,15 +113,6 @@ function toggleResync() { $('input[name="resynchronizeCache"]').prop('disabled', !off); } -function updateCron() { - var cron = $("#cronSchedule").val(); - var tune_cron = $("#tune_cronSchedule").val(); - var cronEnabled = $("#forceCron").val(); - var ismoverDisabled = $("#moverDisabled").val(); - var watchdog = $("#watchdog").val(); - $.post("/plugins/ca.mover.tuning/updateCron.php",{cronEnabled:cronEnabled,cron:cron,tune_cron:tune_cron,ismoverDisabled:ismoverDisabled,watchdog:watchdog}); -} - // the View and Download links follow the file picked in the Log files row function mtLogLinks() { var file = encodeURIComponent(document.getElementById('moverLogFile').value); @@ -338,17 +329,6 @@ function updateScreenMoverAdvancedOptions(option,slow) { } } -function updateScreenMoverInvalidCharsToBlock(option,slow) { - switch (option) { - case 'no': - $('#moverInvalidCharsToBlock').hide(slow); - break; - case 'yes': - $('#moverInvalidCharsToBlock').show(slow); - break; - } -} - // What the config holds, before the selects below capped it to a range. var mtSaved = { moving: , @@ -436,7 +416,6 @@ $(function() { updateScreenMoverAdvancedSettings(''); updateScreenMoverAdvancedFilters(''); updateScreenMoverAdvancedOptions(''); - updateScreenMoverInvalidCharsToBlock(''); mtWatchdogWarning(); toggleTime('ctime'); @@ -579,8 +558,11 @@ if (localStorage.getItem(newYearSeasonKey) === 'yes') {
-
+ + + + _(Disable Mover running on a schedule)_: : '> + _(Not a valid cron schedule: it is not applied.)_ :mover_tune_movertunecron_plug: > Runs the age_mover schedule from the Mover Tuning plugin using your custom cron entry (includes all plugin filters). > > Cron Schedule entry example 0 */4 * * *.  To run at every 4 hours.  What Is Cron +> +> The schedule must be a valid cron entry: an invalid one is not applied, and the error is written to the syslog. :end @@ -687,47 +672,6 @@ function toggleTestModeWarning(val) { :end -_(Validate input filenames to prevent attacks)_: -: -  _(No)_ - _(disables validation of input filenames)_ - -
-:mover_tune_validate_plug: -

In cybersecurity, filenames can be a critical vector for potential attacks and system vulnerabilities. Unsanitized filenames pose significant risks that can compromise system integrity and security.

-

Validate input filenames will check every filename before it is processed by the Mover. This ensures that only valid filenames are accepted, reducing the risk of attacks and vulnerabilities.

-

Disable Only if you have many files to move and you are sure that all filenames are valid and do not contain any potential security risks.

-

1. Check filename length - If the filename exceeds 255 characters, it will be rejected.

-

2. Check for invalid characters - The filename should not contain any characters that are considered invalid for filenames, such as -( $ ), ( / ), ( < ), ( > ), ( : ), ( " ), ( | ), ( ? ), ( * ).

-

3. Prevent path traversal - The filename should not contain any characters that can be used to traverse directories, such as ( ../ ).

-

If one of these checks fails, the filename will be rejected.

-:end -
- -
-_(Invalid characters to block)_: -: '> - -
-:mover_tune_invalidfilechars_plug: -

The filename characters such as: - $ - / - < - > - : - " - | - ? - *. -

-:end -
-
- _(Log Mover Tuning plugin actions)_: : ' > + _(Not a valid cron schedule: it is not applied.)_ :mover_tune_cron_plug: @@ -1356,7 +1301,7 @@ _(Clean empty folders)_:
:mover_tune_cleanfolders_plug:

Yes - Removes the parent folder only of moved files.

-

Top Folder - Removes the top-level share folder of the moved content, including all empty subfolders on the primary storage.

+

Top Folder - As Yes, and also removes the share's top-level folder where the files moved from, once it is empty, unless it is a ZFS dataset (see Clean empty ZFS datasets).

:end
@@ -1369,7 +1314,7 @@ _(Clean empty ZFS datasets)_: :mover_tune_cleandatasets_plug: -> This will unmount and destroy the parent ZFS dataset on share of moved files, only if not contain child datasets within. Works only when Clean empty folders is set to Yes or Top Folder. +> This will unmount and destroy the share's ZFS dataset on the primary storage after its files move, only if it has no child datasets or snapshots and each entry left in it is a folder that the secondary storage also has. The dataset's own ZFS settings, such as compression or quota, are deleted with it. Works only when Clean empty folders is set to Yes or Top Folder. :end diff --git a/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/age_mover b/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/age_mover index 8cba3f80..a2455cae 100755 --- a/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/age_mover +++ b/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/age_mover @@ -5,7 +5,7 @@ # 2023 - hugenbd (parts of code from mover tuning package) # 2024 - R3yn4ld (parts of code from mover tuning package) # 2025 - masterwishx (as current author and maintainer of this file) -# 2026 - masterwishx and chodeus (as current authors and maintainers of this file), with contributions by Joly0 (parts of code from mover tuning package) +# 2026 - masterwishx and chodeus (as current authors and maintainers of this file) #License: GPLv2 only # This is the 'mover tuning' script used for moving files between the cache disk and main array. @@ -28,7 +28,8 @@ # Files at the top level of the cache or an array disk (i.e not in a share) are never moved. # The list is then passed to original unraid mover. -# For each file, if the file is not "in use" by any process (as detected by 'fuser' command), +# For each file, if the file is not "in use" by any process (as detected by an exclusive file lease, +# with fuser as a compatibility fallback, and when Perl is missing, as before Unraid 6.11.0), # then the file is moved, and upon success, deleted from the source disk. If the file already # exists on the target, it is not moved and the sourceis not deleted. All meta-data of moved # files/directories is preserved: permissions, ownership, extended attributes, and access/modified @@ -46,6 +47,7 @@ PAUSEFILE="/var/run/mover.pause" MOVINGFILE="/var/run/mover.moving" HOLD_SINCE="" AGEMOVER="/usr/local/emhttp/plugins/ca.mover.tuning/age_mover" +FILES_IN_USE_HELPER="/usr/local/emhttp/plugins/ca.mover.tuning/files_in_use" SOFTSTOP_ACK=false UNRAIDCFGFILE="/boot/config/share.cfg" MOVERTUNINGCFGFILE="/boot/config/plugins/ca.mover.tuning/ca.mover.tuning.cfg" @@ -91,13 +93,10 @@ COUNT_SECONDARY_FILES=0 overrideFlag=0 UNRAID_MOVER_LOGLEVEL=0 UNRAID_MOVER=0 -# PHP requires escaped quotes (" -> \") for text fields -DEFAULT_INVALID_FILE_CHARS=('$' '/' '<' '>' ':' '\"' '|' '?' '*') # Variables for counts when delete folders LAST_DIR="" LAST_COUNT=-1 LAST_FOLDER_COUNT=-1 -EMPTY_DIR_COUNT=-1 declare -A POOL_FSTYPE_CACHE=() # per cache:yes share, from createFilteredFilelist: "name|keeps its primary files|sync size limit in bytes|age filter days" lines for decideMoveActions SHARE_PLAN_RULES="" @@ -249,6 +248,12 @@ unraid_notify() { else severity="warning" fi + # before 7.2 Unraid shows the description as raw HTML; from 7.2 its API sanitizes it (and from API 4.26 decodes + # entities first, undoing an escape). The quotes stop bash 5.2 reading & in the replacement as the matched text + if ! version_ge "$UNRAID_VERSION" 7.2; then + message=${message///">"} + fi # # Call the Unraid notification script /usr/local/emhttp/webGui/scripts/notify -s "$(translate_text "Mover Tuning Notification")" -d "$message" -i "$severity" -l "/Settings/Scheduler" @@ -287,16 +292,45 @@ is_zfs_dataset_mountpoint() { [ "$(findmnt -no fstype --mountpoint "$1" | tail -n 1)" = "zfs" ] } -titleLine() { - local title="$1" - local padding_char="$2" - local line_length=71 +# Prints the ZFS dataset mounted at exactly path $1; nothing for a folder inside one +zfs_dataset_at() { + is_zfs_dataset_mountpoint "$1" && findmnt -no source --mountpoint "$1" | tail -n 1 +} + +# Prints zfs message $1's first line, from after its quoted name if it has one: later lines can list children's names, +# which debug_mover does not mangle +zfs_reason() { local r=${1%%$'\n'*}; printf '%s' "${r#*\': }"; } + +# When zfs message $2 says dataset $1 is busy, logs one plain line and succeeds: something else holds it, so no notice +zfs_busy() { + # at the end: mount.zfs's messages keep the dataset's name, which may hold the word + [[ $(zfs_reason "$2") == *busy ]] || return 1 + mvlogger "ZFS dataset [$1] is busy, will not delete: a process or another mount, such as a container's, may hold it." +} + +# titleLineTo VAR TITLE CHAR: sets VAR to TITLE centred in CHAR padding, in bash alone. The printf | tr +# pipelines it replaces forked four processes per line, and every debug block draws two lines. +titleLineTo() { + local title="$2" padding_char="$3" line_length=71 left_padding right_padding local padding_left=$((line_length - ${#title} / 2)) local padding_right=$((padding_left - ${#title} % 2 - 1)) - local left_padding right_padding - left_padding=$(printf "%*s" "$padding_left" "" | tr ' ' "$padding_char") - right_padding=$(printf "%*s" "$padding_right" "" | tr ' ' "$padding_char") - echo "${left_padding}$padding_char $title $padding_char${right_padding}" + # a negative width still pads by its size (printf left-justifies the empty string), as printf | tr did + printf -v left_padding '%*s' "$padding_left" "" + printf -v right_padding '%*s' "$padding_right" "" + # the quoted replacement keeps a padding character such as & literal + printf -v "$1" '%s%s %s %s%s' "${left_padding// /"$padding_char"}" "$padding_char" "$title" "$padding_char" "${right_padding// /"$padding_char"}" +} + +titleLine() { + local line + titleLineTo line "$1" "$2" + echo "$line" +} + +# Prints MESSAGE after the current time as date +"%T.%3N" prints it, without forking date +timestamped() { + local now=$EPOCHREALTIME + printf '%(%T)T.%.3s %s\n' "${now%[.,]*}" "${now#*[.,]}" "$1" } # Function to convert byte size to human-readable format @@ -338,34 +372,6 @@ skiplist_share_lines() { ' "$list" } -# Sanitize input filename to prevent attacks -validate_filename() { - local filename="$1" - - ## Check filename length - if [[ ${#filename} -gt 255 ]]; then - mvlogger "Error: Filename too long: '$filename'" - return 1 - fi - - # Invalid characters (Linux + Windows + macOS safe) - if [[ "$filename" == *["$INVALID_FILE_CHARS_STR"]* ]]; then - mvlogger "Error: Invalid characters in filename: '$filename'" - return 1 - fi - - # Fast path traversal detection - if [[ "$filename" == *".."* ]]; then - # Only block if '..' is used as a path segment - if [[ "$filename" == "../"* || "$filename" == *"/.."* || "$filename" == "..\\"* || "$filename" == *"\\.."* ]]; then - mvlogger "Error: Path traversal attempt detected: '$filename'" - return 1 - fi - fi - - return 0 -} - # find's -path glob and the eval each strip one level, so a literal backslash # needs four. Order matters: backslash first, then '[', then the shell's own three, # whose escapes the eval consumes before find ever sees the name. @@ -391,7 +397,17 @@ escape_find_path() { # # Wraps a path for a log message: the debug package ends a path at the quote, so an # embedded quote - an edge case, but the last redaction hole - would expose the rest. -qp() { local p=${1//\\/\\\\}; printf '"%s"' "${p//\"/\\\"}"; } +qp() { local q; qpAll q "$1"; printf '%s' "${q% }"; } + +# qpAll VAR ITEM...: sets VAR to each ITEM quoted for qp, each followed by a space. It owns the escapes, +# which apply to every item at once, so a list costs no subshell per item. +qpAll() { + local -a items=("${@:2}") + items=("${items[@]//\\/\\\\}") + items=("${items[@]//\"/\\\"}") + # printf with no arguments would still print the format once + if [ ${#items[@]} -gt 0 ]; then printf -v "$1" '"%s" ' "${items[@]}"; else printf -v "$1" ''; fi +} # Fills each %s in TEXT from the remaining arguments; an inserted argument is never rescanned. fill_template() { @@ -438,16 +454,16 @@ mvlogger() { echo "$msg" else # CLI or BUTTON → echo + logger - echo "$(date +"%T.%3N") $msg" + timestamped "$msg" logger -t move -- "$msg" fi # Always append to mover log - echo "$(date +"%T.%3N") $msg" >>"$MOVER_LOG" + timestamped "$msg" >>"$MOVER_LOG" elif [ "$LOGLEVEL" = 2 ]; then # Files-only mode - echo "$(date +"%T.%3N") $msg" >>"$MOVER_LOG" + timestamped "$msg" >>"$MOVER_LOG" fi # Optional notification @@ -465,10 +481,14 @@ mvlogger() { # IS_CRON=0 → CLI or GUI button (echo + logger) # # DEBUGLEVEL: +# 0 → nothing, and nothing is built # 1 → echo + debug log # 2 → debug log only # +# Arguments are expanded before the call, so a call site whose message needs a subshell +# (such as $(qp ...)) on every file should test DEBUGLEVEL itself. mvDebuglogger() { + [ "$DEBUGLEVEL" = 1 ] || [ "$DEBUGLEVEL" = 2 ] || return 0 local msg="$1" local tag="$2" @@ -478,13 +498,10 @@ mvDebuglogger() { fi # Build formatted debug block - local block - block="$( - printf '%s\n%s\n%s\n' \ - "$(titleLine "Debugging $tag" '-')" \ - "$(date +"%T.%3N") $msg" \ - "$(titleLine " " ' ')" - )" + local block title_line blank_line now=$EPOCHREALTIME + titleLineTo title_line "Debugging $tag" '-' + titleLineTo blank_line " " ' ' + printf -v block '%s\n%(%T)T.%.3s %s\n%s' "$title_line" "${now%[.,]*}" "${now#*[.,]}" "$msg" "$blank_line" if [ "$DEBUGLEVEL" = 1 ]; then @@ -971,36 +988,6 @@ getMoverSettings() { mvlogger "List files delete age: $LISTFILESAGE days" fi - if [ -z $(cfg validateFilenames) ]; then - if [[ ! "$config_file" =~ shareOverrideConfig ]]; then - mvlogger "No Validate Filenames argument provided, defaulting to yes" - cfg_default validateFilenames yes - VALIDATE_FILENAMES="yes" - fi - else - VALIDATE_FILENAMES=$(cfg validateFilenames) - mvlogger "Validate Filenames: $VALIDATE_FILENAMES" - fi - - if [ -z "$(cfg invalidFileChars)" ]; then - if [[ ! "$config_file" =~ shareOverrideConfig ]]; then - # Print and unescape the array element \" -> " - mvlogger "No Invalid characters argument provided, defaulting to: ${DEFAULT_INVALID_FILE_CHARS[*]//\\\"/\"}" - cfg_default invalidFileChars "${DEFAULT_INVALID_FILE_CHARS[*]}" - # Keep DEFAULT_INVALID_FILE_CHARS as an array - INVALID_FILE_CHARS=("${DEFAULT_INVALID_FILE_CHARS[@]}") - # Escape regex meta chars, first remove '\' from '\"', then add '\' to all characters - INVALID_FILE_CHARS_STR=$(printf '%s' "${INVALID_FILE_CHARS[@]//\\\"/\"}" | sed 's/./\\&/g') - fi - else - # Convert the string from cfg invalidFileChars to an array - IFS=' ' read -r -a INVALID_FILE_CHARS <<<"$(cfg invalidFileChars)" - # Print and unescape the array element \" -> " - mvlogger "Invalid characters to block: ${INVALID_FILE_CHARS[*]//\\\"/\"}" - # Escape regex meta chars, first remove '\' from '\"', then add '\' to all characters - INVALID_FILE_CHARS_STR=$(printf '%s' "${INVALID_FILE_CHARS[@]//\\\"/\"}" | sed 's/./\\&/g') - fi - if [ -z $(cfg movefilesTool) ]; then if [[ ! "$config_file" =~ shareOverrideConfig ]]; then mvlogger "No Move files tool argument provided, defaulting to rsync" @@ -2531,6 +2518,337 @@ move_tool_said() { done <<<"$MOVE_OUT" } +# Sets processTheMoves' FILES_IN_USE_CMD: the files_in_use helper through the perl in PATH (Unraid 6.11.0 and newer have +# Perl), else fuser -s as before the helper. A helper that does not compile would fail closed on every file +chooseFilesInUseCheck() { + if command -v perl >/dev/null && perl -c "$FILES_IN_USE_HELPER" >/dev/null 2>&1; then + FILES_IN_USE_CMD=(perl "$FILES_IN_USE_HELPER") + return + fi + FILES_IN_USE_CMD=(fuser -s) + [ "$MOVE_IN_USE" = yes ] && return + if command -v perl >/dev/null; then + mvlogger "The file lease helper could not start, so files are checked for use with fuser, which is slower on busy servers." + else + mvlogger "Perl not found, so files are checked for use with fuser, which is slower on busy servers. Perl is part of Unraid 6.11.0 and newer." + fi +} + +# Succeeds when a path is in use or when FILES_IN_USE_CMD gives no answer, which it logs once per run through +# processTheMoves' FILE_IN_USE_FAILURE_LOGGED +filesInUse() { + local rc + if "${FILES_IN_USE_CMD[@]}" "$@" 2>/dev/null; then rc=0; else rc=$?; fi + case "$rc" in + 0) return 0 ;; + 1) return 1 ;; + esac + if [ "$FILE_IN_USE_FAILURE_LOGGED" != yes ]; then + mvlogger "A file could not be checked for use, so it stays where it is until a later run. Set 'Move files that are in use' to Yes to move such files anyway." + FILE_IN_USE_FAILURE_LOGGED=yes + fi + return 0 +} + +# Whether a real run would find path $1 on the source: test mode leaves out processTheMoves' TEST_GONE, what its moves +# and deletions would have taken off it +on_source() { [ -e "$1" ] && [ -z "${TEST_GONE[$1]+x}" ]; } + +# Prints how many of the paths find prints for args $@ a real run would find, as on_source does +count_left() { + local - out p n=0 IFS=$'\n' + [ "$TESTMODE" = "yes" ] || { find "$@" | wc -l; return; } + # one read of find's output, split here: a read loop on a pipe takes a syscall per byte + out=$(find "$@") + set -f + for p in $out; do [ -n "${TEST_GONE[$p]+x}" ] || n=$((n + 1)); done + echo "$n" +} + +# Whether a real run's rmdir would take folder $1: nothing left in it, as count_left sees, and no ZFS dataset mounted on it +would_rmdir() { [ "$(count_left "$1" -mindepth 1 -maxdepth 1)" = 0 ] && ! is_zfs_dataset_mountpoint "$1"; } + +# In topFolder mode, notes this row's share top folder for the check after the pass; fills processTheMoves' TOP_SEEN +# and TOP_FOLDERS +note_top_folder() { + [ "$CLEANFOLDERS" = "topFolder" ] || return 0 + local top="${SOURCE}/${SHARENAME}" + [ -n "${TOP_SEEN[$top]}" ] && return 0 + TOP_SEEN[$top]=1 + TOP_FOLDERS+=("$top") +} + +# With Clean datasets and Clean folders on, notes this row's pool/share and destination for cleanShareDataset after +# the pass when the row's source is the primary; fills processTheMoves' DATASET_DEST and SHARE_DATASETS +note_share_dataset() { + [ "$CLEANDATASETS" = "yes" ] && [ "$CLEANFOLDERS" != "no" ] && + [ "$SOURCE" = "/mnt/$PRIMARYSTORAGENAME" ] || return 0 + local ds="$PRIMARYSTORAGENAME/$SHARENAME" + [ -n "${DATASET_DEST[$ds]+x}" ] && return 0 + DATASET_DEST[$ds]=$DESTINATION + SHARE_DATASETS+=("$ds") +} + +# A folder in this row's share emptied: hands the share to the top-folder and dataset checks after the pass, each +# under its own settings +note_emptied_share() { note_top_folder; note_share_dataset; } + +# Deletes share top folder $1 if it is empty, unless it is a ZFS dataset mountpoint or test mode is on +cleanTopFolder() { + local top_folder=$1 file_count dir_count dataset=no pat skip=() + [ -d "$top_folder" ] || return 0 + if [ -e "${top_folder}/.placeholder" ]; then + mvlogger "Not deleting top-level folder: contains .placeholder: ${top_folder}" + return 0 + fi + # a dataset's .zfs holds the snapshots snapdir=visible shows, and a walk would mount each one. -path is a glob, so + # the folder's own \ * ? [ are escaped + if is_zfs_dataset_mountpoint "$top_folder"; then + dataset=yes + pat=${top_folder//\\/\\\\} + pat=${pat//\*/\\*} + pat=${pat//\?/\\?} + skip=(-path "${pat//\[/\\[}/.zfs" -prune -o) + fi + # -xdev: a mount inside, such as a child dataset, is counted but not walked + file_count=$(count_left "$top_folder" -xdev "${skip[@]}" -type f -print) + dir_count=$(count_left "$top_folder" -xdev -mindepth 1 "${skip[@]}" -type d -print) + mvDebuglogger "Top folder: $(qp "$top_folder"), share file(s): $file_count, share folder(s): $dir_count" "Clean Top Folder" + if [ "$file_count" -ne 0 ] || [ "$dir_count" -ne 0 ]; then + mvlogger "Not deleting top-level folder: contains $file_count file(s), $dir_count subfolder(s): ${top_folder}" + elif [ "$dataset" = yes ]; then + mvlogger "Skipping deletion of ZFS dataset mountpoint: $top_folder" + elif [ "$TESTMODE" != "no" ]; then + if would_rmdir "$top_folder"; then + mvlogger "TEST MODE: Would delete empty top-level folder: $top_folder" + else + mvDebuglogger "TEST MODE: Would fail to delete top-level folder (not empty): $top_folder" "Clean Top Folder" + fi + elif rmdir "$top_folder" 2>/dev/null; then + mvlogger "Deleted empty top-level folder: $top_folder" + else + mvDebuglogger "Failed to delete top-level folder (may not be empty): $top_folder" "Clean Top Folder" + fi +} + +# Prints folder $1's first entry that is not a folder, or is a folder that folder $2 lacks; $1 itself when cd or find fails. +# Succeeds once it has looked. Skips $1/.zfs, which snapdir=visible shows: its snapshots keep the dataset at the children check +dataset_loses() { + local src=$1 dest=$2 entry + # two passes: the destination is read only once nothing but folders is left + entry=$(cd "$src" && { + first=$(find . -mindepth 1 -path ./.zfs -prune -o ! -type d -print -quit) || exit + [ -n "$first" ] && { printf '%s' "$first"; exit; } + find . -mindepth 1 -path ./.zfs -prune -o -type d ! -exec test -d "$dest/{}" \; -print -quit + }) || { printf '%s' "$src"; return 0; } + [ -z "$entry" ] || printf '%s' "$src/${entry#./}" +} + +# Mounts the unmounted dataset $1 read-only at empty folder $2 and prints dataset_loses there against $4, with $2 shown +# as $3; prints why and fails when it cannot mount or read it, and returns 2 with umount's reason when umount fails +dataset_loses_unmounted() { + local err lost scanned=yes + if ! err=$(mount -t zfs -o ro,zfsutil "$1" "$2" 2>&1); then + printf 'mount: %s' "$(zfs_reason "${err#mount: }")" + return 1 + fi + # a scan cut short can print nothing, as a clean one does: only its status tells them apart + lost=$(dataset_loses "$2" "$4") || scanned= + if ! err=$(umount "$2" 2>&1); then + printf '%s' "$(zfs_reason "${err#umount: }")" + return 2 + fi + [ -n "$scanned" ] || { printf 'the check was cut short'; return 1; } + # dataset_loses names its folder itself when it cannot read it + [ "$lost" != "$2" ] || { printf 'find: the dataset could not be read'; return 1; } + [ -z "$lost" ] || printf '%s' "$3${lost#"$2"}" +} + +# Run only inside $( ): ignores the stop signals there, so a stop that signals every process cannot end step $@ part-way +finish_on_stop() { + trap '' TERM HUP INT + "$@" +} + +# Logs lines $3... and notes dataset $2 for dataset_problems_notice at severity $1 (failure outranks warning); fills +# processTheMoves' DATASET_PROBLEM (the dataset's entry in the notice) and DATASET_PROBLEM_LEVEL +dataset_problem() { + DATASET_PROBLEM[$2]=${DATASET_PROBLEM[$2]:-[$2]} + [ "$DATASET_PROBLEM_LEVEL" = failure ] || DATASET_PROBLEM_LEVEL=$1 + local line + for line in "${@:3}"; do mvlogger "$line"; done +} + +# Logs why dataset $2's files are out of view and how to mount it back (template $1 filled with $3...), and puts the +# translation in its notice entry: with action logging off the notice is all the user gets +dataset_out_of_view() { + local template=$1 dataset=$2 + shift 2 + mvlogger "ZFS dataset [$dataset]: $(fill_template "$template" "$@")" + DATASET_PROBLEM[$dataset]="[$dataset] ($(finish_on_stop translate_text "$template" "$@"))" +} + +# One notice naming the run's datasets with a problem: a problem that repeats notifies once a run +dataset_problems_notice() { + local ds names="" + for ds in "${SHARE_DATASETS[@]}"; do [ -z "${DATASET_PROBLEM[$ds]}" ] || names+="${names:+ }${DATASET_PROBLEM[$ds]}"; done + [ -z "$names" ] || mvlogger_t "Clean empty ZFS datasets did not finish for %s. The mover log has the details unless Log Mover Tuning plugin actions is set to No." \ + "$DATASET_PROBLEM_LEVEL" "$names" +} + +# Mounts dataset $1 at its folder $2 from inside the folder and prints the first entry the mount hides, seen through .; +# prints why and fails when the folder cannot be entered or the mount fails; fails with 2 when the look is cut short +mount_back() { + local err entry + # made if gone: a write through /mnt/user can make it again, with a file in it, before the mount + { mkdir -p "$2" && cd "$2"; } 2>/dev/null || { printf 'cannot enter its folder %s' "$2"; return 1; } + err=$(zfs mount "$1" 2>&1) || { printf 'zfs: %s' "$(zfs_reason "$err")"; return 1; } + # a look cut short can print nothing, as a clean one does: only its status tells them apart + entry=$(find . -mindepth 1 -print -quit 2>/dev/null) || return 2 + printf '%s' "$entry" +} + +# Mounts dataset $1 again at its folder $2, unless the folder gained files that a mount would hide +remount_dataset() { + local out + # a write through /mnt/user while it was unmounted lands in the bare folder + if [ -n "$(finish_on_stop find "$2" -mindepth 1 -print -quit 2>/dev/null)" ]; then + out="Not remounting ZFS dataset [$1]: its folder $2 holds files that a mount would hide" + else + out=$(finish_on_stop mount_back "$1" "$2") + case $? in + 0) + [ -n "$out" ] || return 0 + dataset_problem failure "$1" "ZFS dataset [$1] is mounted again, but $2/${out#./}, written as it was mounted, is hidden under it" + dataset_out_of_view "a file is hidden under it: stop writes to the share, zfs unmount %s, move anything in %s aside, zfs mount %s, then move it back into %s without replacing a file already there: keep both copies and compare them" \ + "$1" "$1" "$2" "$1" "$2" + return 0 + ;; + 1) ;; + 2) + # a failure, as a found file is: Notify errors only must still say a file may be out of view + dataset_problem failure "$1" + dataset_out_of_view "mounted again, but the look for a file written to %s as it was mounted was cut short, so one may be hidden under it: stop writes to the share, zfs unmount %s, move anything in %s aside, zfs mount %s, then move it back into %s without replacing a file already there: keep both copies and compare them" \ + "$1" "$2" "$1" "$2" "$1" "$2" + return 0 + ;; + *) + # killed outright, it may have mounted it or not + dataset_problem failure "$1" + dataset_out_of_view "the remount was cut short, so it may not be mounted or may hide a file: stop writes to the share, if zfs mount lists it at %s run zfs unmount %s, move anything in %s aside, zfs mount %s, then move it back into %s without replacing a file already there: keep both copies and compare them" \ + "$1" "$2" "$1" "$2" "$1" "$2" + return 0 + ;; + esac + fi + dataset_problem failure "$1" "Failed to remount dataset [$1]" "$out" + dataset_out_of_view "not mounted: stop writes to the share, move anything in %s aside, zfs mount %s, then move it back into %s without replacing a file already there: keep both copies and compare them" \ + "$1" "$2" "$1" "$2" +} + +# Logs at debug level why dataset $1 is kept: entry $2 that a destroy could lose +dataset_kept() { + # the planner never saw this name: a newline in it would end the debug line before debug_mover's mangling + mvDebuglogger "Keeping ZFS dataset [$1]: a destroy could lose $(qp "${2//$'\n'/\\n}")" "Clean Dataset" +} + +# Succeeds if dataset $1 is mounted at folder $2; a stop does not cut the read short +mounted_at() { [ "$(finish_on_stop findmnt -no source --mountpoint "$2")" = "$1" ]; } + +# Unmounts dataset $1 from folder $2 and destroys it if dataset_loses_unmounted at private folder $4 against $3 is empty; +# else tries to mount it back. processTheMoves' stopped, set by a stop, skips the destroy +unmount_check_destroy() { + local dataset=$1 folder=$2 private=$4 err lost rc + # stderr is discarded on both launch paths, so zfs's reason goes to the log + if ! err=$(finish_on_stop zfs unmount "$dataset" 2>&1); then + zfs_busy "$dataset" "$err" || + dataset_problem failure "$dataset" "Failed to unmount ZFS dataset [${dataset}]" "zfs: $(zfs_reason "$err")" + return 0 + fi + mvlogger "ZFS dataset [${dataset}] successfully unmounted." + # a file written between the first check and the unmount is in the dataset: checked again where nothing can write + lost=$(finish_on_stop dataset_loses_unmounted "$dataset" "$private" "$folder" "$3") + rc=$? + # a failed or killed check may leave the dataset at the private folder: mount.zfs can fail after mounting, and + # umount after unmounting, so the mount table decides + if [ "$rc" != 0 ]; then + [ "$rc" = 1 ] || [ "$rc" = 2 ] || lost="the check was cut short" + if ! mounted_at "$dataset" "$private"; then + # unmounted after all, but what the check found was not kept + [ "$rc" != 2 ] || { lost="umount: $lost"; rc=1; } + elif [ "$rc" != 2 ] && ! err=$(finish_on_stop umount "$private" 2>&1) && mounted_at "$dataset" "$private"; then + lost=$(zfs_reason "${err#umount: }") + rc=2 + fi + fi + if [ "$rc" = 2 ]; then + dataset_problem failure "$dataset" \ + "ZFS dataset [${dataset}] is still mounted read-only at ${private}, not at ${folder}: umount: $lost" + dataset_out_of_view "mounted read-only at %s: stop writes to the share, umount %s, move anything in %s aside, zfs mount %s, then move it back into %s without replacing a file already there: keep both copies and compare them" \ + "$dataset" "$private" "$private" "$folder" "$dataset" "$folder" + return 0 + elif [ "$rc" != 0 ]; then + # a hold by something else, such as a container's mount, makes the read-only mount busy + zfs_busy "$dataset" "$lost" || + dataset_problem warning "$dataset" "ZFS dataset [${dataset}] could not be checked once unmounted, will not delete: $lost" + elif [ -n "$stopped" ]; then + mvlogger "Mover stopped while ZFS dataset [${dataset}] was unmounted: not deleting it, attempting to remount" + elif [ -n "$lost" ]; then + mvlogger "Keeping ZFS dataset [${dataset}]: the check after the unmount found something a destroy could lose." + dataset_kept "$dataset" "$lost" + elif ! err=$(finish_on_stop zfs destroy "$dataset" 2>&1); then + zfs_busy "$dataset" "$err" || dataset_problem failure "$dataset" \ + "Failed to destroy ZFS dataset [${dataset}] — attempting to remount." "zfs: $(zfs_reason "$err")" + else + mvlogger "ZFS dataset [${dataset}] successfully destroyed." + return 0 + fi + remount_dataset "$dataset" "$folder" +} + +# Destroys dataset $1/$2 if it is mounted at /mnt/$1/$2, has no children or snapshots, and dataset_loses against $3/$2 +# is empty both before the unmount and after it; else keeps it, and the log says when it stays unmounted. Test mode +# runs no zfs command: it says the dataset would be checked +cleanShareDataset() { + local folder="/mnt/$1/$2" dataset="$1/$2" mounted names lost private + mounted=$(zfs_dataset_at "$folder") + [ -n "$mounted" ] || return 0 + if [ "$mounted" != "$dataset" ]; then + mvDebuglogger "Keeping the ZFS dataset mounted at $(qp "$folder"): it is not ${dataset}" "Clean Dataset" + return 0 + fi + if [ "$TESTMODE" != "no" ]; then + mvlogger "TEST MODE: Would check ZFS dataset [${dataset}] for deletion" + return 0 + fi + # listed first, so between the content check and the unmount only a log line is written + if ! names=$(finish_on_stop zfs list -r -H -t filesystem,volume,snapshot -o name "$dataset" 2>&1); then + mvlogger "ZFS dataset [${dataset}] could not be listed, will not delete: $(zfs_reason "$names")" + return 0 + fi + # cut short, it is kept as a folder it cannot read is + lost=$(finish_on_stop dataset_loses "$folder" "$3/$2") || lost=$folder + if [ -n "$lost" ]; then + dataset_kept "$dataset" "$lost" + return 0 + fi + if [[ $names == *$'\n'* ]]; then + mvlogger "ZFS dataset [${dataset}] has child datasets or snapshots, will not delete..." + return 0 + fi + # a stop during the checks above ends the run before the unmount + [ -z "$stopped" ] || return 0 + if ! private=$(finish_on_stop mktemp -d -t ca.mover.tuning.XXXXXX 2>&1); then + dataset_problem warning "$dataset" \ + "ZFS dataset [${dataset}] could not be checked once unmounted, will not delete: mktemp: $(zfs_reason "${private#mktemp: }")" + return 0 + fi + mvlogger "ZFS dataset [${dataset}] holds only folders the destination also has, attempting to unmount and delete..." + unmount_check_destroy "$dataset" "$folder" "$3/$2" "$private" + # a folder the dataset is still mounted on stays + rmdir "$private" 2>/dev/null +} + # Internal move engine processTheMoves() { if [ -e $SOFTSTOPFILE ]; then @@ -2541,10 +2859,7 @@ processTheMoves() { # the Pause button shows from here until movesEnd echo "$$ 0" >"$MOVINGFILE" mvlogger "$(titleLine 'LET THE MOVING SHOW BEGIN !' '*')" - if [ "$ENABLETURBO" = "yes" ]; then - mvlogger "Forcing turbo write on" - [ "$TESTMODE" != "yes" ] && /usr/local/sbin/mdcmd set md_write_method 1 - fi + force_turbo # MOVER_ACTIONLIST header: # PRIMARYSTORAGENAME|SHARENAME|SHAREUSECACHE|MODIFYTIME|FILESIZE|POOLSUM|THRESHOLD|PROJECTED|NBLINKS|INODE|ACTION|FROM|TO|FILETYPE|FILEPATH @@ -2560,16 +2875,22 @@ processTheMoves() { REMAINING_UNATTENDED_FOLDERS=$TOTALUNATTENDEDFOLDERS local -A HANDLED_LINKS=() local -A GONE_BEFORE=() + local -A TEST_GONE=() local -A CHARGED_BYTES=() local -A STAGED_OK=() local -A STAGED_VANISHED=() local -A STAGED_INUSE=() - # without fuser an open file cannot be told apart, so none is moved while moveInUse is no - local fuser_missing=0 - if [ "$MOVE_IN_USE" != "yes" ] && ! command -v fuser >/dev/null; then - fuser_missing=1 - mvlogger "fuser not found: files stay where they are, since they cannot be checked for use. Set 'Move files that are in use' to Yes to move them anyway." - fi + local -A TOP_SEEN=() + local -a TOP_FOLDERS=() + local -A DATASET_DEST=() + local -a SHARE_DATASETS=() + local -A DATASET_PROBLEM=() + local DATASET_PROBLEM_LEVEL="" + local top ds notice_lines stopped="" + # set by filesInUse the first time a file cannot be checked + local FILE_IN_USE_FAILURE_LOGGED=no + local -a FILES_IN_USE_CMD=() + chooseFilesInUseCheck # Dry mode info: if [ "$TESTMODE" = "yes" ]; then @@ -2590,7 +2911,10 @@ processTheMoves() { # "keep on primary", "keep on secondary" and "keep misplaced" are not actions, so they are absent for ACTION_PASS in "${MOVE_ACTIONS[@]}"; do - while IFS="|" read -r PRIMARYSTORAGENAME SHARENAME SHAREUSECACHE MODIFYTIME FILESIZE POOLSUM THRESHOLD PROJECTED NBLINKS INODE ACTION SOURCE DESTINATION FILETYPE FILEPATH; do + while IFS= read -r ROW; do + IFS="|" read -r PRIMARYSTORAGENAME SHARENAME SHAREUSECACHE MODIFYTIME FILESIZE POOLSUM THRESHOLD PROJECTED NBLINKS INODE ACTION SOURCE DESTINATION FILETYPE FILEPATH <<<"$ROW" + # read can drop a | that ends the row, so a set path is cut whole from the row, as the awk lookups below take it + if [ -n "$FILEPATH" ]; then FILEPATH=$ROW; for _ in {1..14}; do FILEPATH=${FILEPATH#*|}; done; fi # before the row's checks, so a long pause cannot leave them stale pauseHold if [ -e $SOFTSTOPFILE ]; then @@ -2608,7 +2932,9 @@ processTheMoves() { # a move, so later rows are matched on the SYNCED_FILES_ARR key below, not the file. The key # carries the plan, so a group split across plans keeps every partition instead of dropping one. NBLINKS="${NBLINKS:-0}" - if [ "$FILETYPE" = "f" ] && [ "$NBLINKS" -gt 1 ]; then + link_group=0 + [ "$FILETYPE" = "f" ] && [ "$NBLINKS" -gt 1 ] && link_group=1 + if [ "$link_group" = 1 ]; then link_key="$ACTION|$SOURCE|$DESTINATION|$NBLINKS|$INODE|$MODIFYTIME" [ -n "${HANDLED_LINKS[$link_key]}" ] && continue HANDLED_LINKS[$link_key]=1 @@ -2660,38 +2986,20 @@ processTheMoves() { # via this array (instead of eval) stops the shell from interpreting # spaces, backticks, $(...), redirections, etc. that appear in file names. # every field is compared whole, so a name containing | cannot impersonate another row - mapfile -t SYNCED_FILES_ARR < <(awk -F'|' -v links="$NBLINKS" -v inode="$INODE" -v mtime="$MODIFYTIME" -v action="$ACTION" -v src="$SOURCE" -v dst="$DESTINATION" ' - BEGIN { links = links ""; inode = inode ""; mtime = mtime "" } - $4 == mtime && $9 == links && $10 == inode && $11 == action && $12 == src && $13 == dst { p = $15; for (i = 16; i <= NF; i++) p = p "|" $i; print src "/./" p }' "$MOVER_ACTIONLIST") + # a row that is not a link group moves only its own name, without a scan of the action list + if [ "$link_group" = 1 ]; then + mapfile -t SYNCED_FILES_ARR < <(awk -F'|' -v links="$NBLINKS" -v inode="$INODE" -v mtime="$MODIFYTIME" -v action="$ACTION" -v src="$SOURCE" -v dst="$DESTINATION" ' + BEGIN { links = links ""; inode = inode ""; mtime = mtime "" } + $4 == mtime && $9 == links && $10 == inode && $11 == action && $12 == src && $13 == dst { p = $15; for (i = 16; i <= NF; i++) p = p "|" $i; print src "/./" p }' "$MOVER_ACTIONLIST") + else + SYNCED_FILES_ARR=("$SOURCE/./$FILEPATH") + fi # SYNCED_FILES is a display/count string only, derived from the array so # the extraction pipeline above runs only once per file. - SYNCED_FILES="" - SYNCED_FILES="" - for f in "${SYNCED_FILES_ARR[@]}"; do SYNCED_FILES+="$(qp "$f") "; done + qpAll SYNCED_FILES "${SYNCED_FILES_ARR[@]}" GUI_CURRENT_FILE="$SOURCE/$FILEPATH" - # Check File by validate function and skip if error; rsync gets every hardlink name, so check them all - if [ "$VALIDATE_FILENAMES" = "yes" ]; then - for f in "${SYNCED_FILES_ARR[@]:-$SOURCE/./$FILEPATH}"; do - # a name already gone is counted as vanished after the transfer, never as invalid - [ -e "${f//\/.\//\/}" ] || continue - validate_filename "$(basename "$f")" && continue - mvlogger_t "Error: Invalid filename path: %s. Please either change the filename to valid or disable the 'Validate input filenames' option." "failure" "$(qp "${f//\/.\//\/}")" - gone=0 - for g in "${SYNCED_FILES_ARR[@]}"; do [ -e "${g//\/.\//\/}" ] || gone=$((gone + 1)); done - # a staged row is counted once, by its sync row, which finds the move incomplete and takes the gone names from here - if [ "$STAGE_ROW" = 0 ]; then - not_moved "$(( ${#SYNCED_FILES_ARR[@]} - gone > 0 ? ${#SYNCED_FILES_ARR[@]} - gone : 1 ))" - [ "$FILETYPE" = "f" ] && VANISHEDFILES=$((VANISHEDFILES + gone)) - remaining_done "$gone" 0 - else - STAGED_VANISHED[$chain_key]=$gone - fi - continue 2 - done - fi - # Check if list is complete (array length is exact, unlike parsing the string) NBFILES=${#SYNCED_FILES_ARR[@]} if [ -f "${SOURCE}/${FILEPATH}" ] && [ $NBFILES != "$NBLINKS" ]; then @@ -2700,9 +3008,9 @@ processTheMoves() { continue fi - # an open name keeps its source copy alive, so moving it frees nothing: skip it like Unraid's move - # (fuser takes no "--": with it, psmisc fuser reports an open file as not in use) - if [ "$MOVE_IN_USE" != "yes" ] && [[ "$ACTION" =~ "move" && "$FILETYPE" = "f" ]] && [ "$NBFILES" -gt 0 ] && { [ "$fuser_missing" = 1 ] || fuser -s "${SYNCED_FILES_ARR[@]//\/.\//\/}" 2>/dev/null; }; then + # An open name keeps its source copy alive, so moving it frees nothing: skip it like Unraid's move. + # filesInUse takes an exclusive lease at this point, or uses fuser when leases are unavailable. + if [ "$MOVE_IN_USE" != "yes" ] && [[ "$ACTION" =~ "move" && "$FILETYPE" = "f" ]] && [ "$NBFILES" -gt 0 ] && filesInUse "${SYNCED_FILES_ARR[@]//\/.\//\/}"; then mvlogger "In use, left for a later run: $SYNCED_FILES" # a move from primary left in place was not synced either, so lastCacheSync must wait; a staged row leaves that to its sync row if [ "$STAGE_ROW" = 1 ]; then STAGED_INUSE[$chain_key]=1; else INUSEFILES=$((INUSEFILES + NBFILES)); fi @@ -2732,15 +3040,15 @@ processTheMoves() { # Proceed with rsync if [[ "$ACTION" =~ "move" ]]; then # Some verbosity - GUI_ACTION="Moving to $DESTINATION/ $([ "$NBLINKS" -gt 1 ] && [ "$FILETYPE" = "f" ] && echo '(preserving hardlinks)')" - mvlogger "Moving $SYNCED_FILES to $(qp "$DESTINATION/") $([ "$NBLINKS" -gt 1 ] && [ "$FILETYPE" = "f" ] && echo '(preserving hardlinks)')" + GUI_ACTION="Moving to $DESTINATION/ $([ "$link_group" = 1 ] && echo '(preserving hardlinks)')" + mvlogger "Moving $SYNCED_FILES to $(qp "$DESTINATION/") $([ "$link_group" = 1 ] && echo '(preserving hardlinks)')" rsync_action="Move" # Finalize RSYNC_CMD RSYNC_CMD+=(--remove-source-files) elif [[ "$ACTION" =~ "sync" ]]; then # Some verbosity - GUI_ACTION="Synchronizing to $DESTINATION/ $([ "$NBLINKS" -gt 1 ] && [ "$FILETYPE" = "f" ] && echo '(preserving hardlinks)')" - mvlogger "Synchronizing $SYNCED_FILES to $(qp "$DESTINATION/") $([ "$NBLINKS" -gt 1 ] && [ "$FILETYPE" = "f" ] && echo '(preserving hardlinks)')" + GUI_ACTION="Synchronizing to $DESTINATION/ $([ "$link_group" = 1 ] && echo '(preserving hardlinks)')" + mvlogger "Synchronizing $SYNCED_FILES to $(qp "$DESTINATION/") $([ "$link_group" = 1 ] && echo '(preserving hardlinks)')" rsync_action="Sync" fi @@ -2767,7 +3075,7 @@ processTheMoves() { if [ "$TESTMODE" = "yes" ]; then mvlogger "TEST MODE: Would move using Unraid move utility" else - mvDebuglogger "Move cmd: move, Move $filetype: $SYNCED_FILES, Dest: $(qp "$DESTINATION/")" "Move Action" + [ "$DEBUGLEVEL" != 0 ] && mvDebuglogger "Move cmd: move, Move $filetype: $SYNCED_FILES, Dest: $(qp "$DESTINATION/")" "Move Action" # Unraid move keeps hardlinks only among names given in one run and skips the file otherwise; # a folder row sends only the folder, which move leaves on the source while anything is in it MOVE_DEBUG_ARGS=() @@ -2783,9 +3091,10 @@ processTheMoves() { else # one quoted token per argv element, like SYNCED_FILES above: [*] joins the # paths with spaces, and the anonymiser cannot tell where one ends - RSYNC_CMD_LOG="" - for a in "${RSYNC_CMD[@]}"; do RSYNC_CMD_LOG+="$(qp "$a") "; done - mvDebuglogger "Rsync cmd: $RSYNC_CMD_LOG, $rsync_action $filetype: $SYNCED_FILES, Dest: $(qp "$DESTINATION/")" "$rsync_action Action" + if [ "$DEBUGLEVEL" != 0 ]; then + qpAll RSYNC_CMD_LOG "${RSYNC_CMD[@]}" + mvDebuglogger "Rsync cmd: $RSYNC_CMD_LOG, $rsync_action $filetype: $SYNCED_FILES, Dest: $(qp "$DESTINATION/")" "$rsync_action Action" + fi # Perform rsync. relative paths and hardlinks if [ ${#SYNCED_FILES_ARR[@]} -gt 0 ]; then if [ ${#present[@]} -gt 0 ]; then @@ -2801,6 +3110,14 @@ processTheMoves() { fi fi copyWatchStop + # test mode notes what a real move takes off the source: every file, and with Unraid's move a folder + # its rmdir would take, as move leaves any other + if [ "$TESTMODE" = "yes" ] && [[ "$ACTION" =~ "move" ]] && { [ "$FILETYPE" = "f" ] || [ "$MOVE_FILES_TOOL" = "move" ]; }; then + for f in "${present[@]}"; do + f=${f//\/.\//\/} + [ "$FILETYPE" = "f" ] || would_rmdir "$f" && TEST_GONE[$f]=1 + done + fi # a dry run counts every name as done; a real run counts only verified arrivals below names=${#SYNCED_FILES_ARR[@]} @@ -2874,117 +3191,67 @@ processTheMoves() { # Define a function to handle the directory cleanup logic. # Iterate the array directly (was: echo "$SYNCED_FILES" | xargs), # so filenames with quotes/spaces/special chars are handled safely. - for FILE in "${SYNCED_FILES_ARR[@]}"; do + counted_in_row=0 + for key in "${SYNCED_FILES_ARR[@]}"; do # Collapse the rsync --relative marker ("/./" -> "/") - FILE="${FILE//\/.\//\/}" + FILE="${key//\/.\//\/}" DIR=$(dirname "$FILE") - mvDebuglogger "Current file: $(qp "$FILE"), Current folder: $(qp "$DIR"), Previous folder: $(qp "$LAST_DIR"), Previous count: $LAST_COUNT" "Clean Folder - Start Loop" + [ "$DEBUGLEVEL" != 0 ] && mvDebuglogger "Current file: $(qp "$FILE"), Current folder: $(qp "$DIR"), Previous folder: $(qp "$LAST_DIR"), Previous count: $LAST_COUNT" "Clean Folder - Start Loop" if [ -e "${DIR}/.placeholder" ]; then count=".placeholder" + # a name gone before its turn may have left before an earlier row's count: its folder is counted again + elif [ "${LAST_DIR}" != "${DIR}" ] || [ -n "${GONE_BEFORE[$key]}" ]; then + # an earlier row may have emptied and deleted it + LAST_COUNT=0 + [ ! -d "$DIR" ] || LAST_COUNT=$(count_left "$DIR" -maxdepth 1 -type f) + LAST_DIR=$DIR + counted_in_row=1 + count=$LAST_COUNT else - # Check if the current directory is same as the previous one - if [ "${LAST_DIR}" == "${DIR}" ]; then - # Check if the counter is greater than 0 to avoid counting files in the folder using wc -l - if [ "$LAST_COUNT" -gt 0 ]; then - count=$((LAST_COUNT - 1)) - # Save current counter - LAST_COUNT="$count" - fi - else - #count=$(ls -A "$DIR" | wc -l) - count=$(find "$DIR" -maxdepth 1 -type f | wc -l) - # Save current counter - LAST_COUNT="$count" - # Save current Folder - LAST_DIR="$DIR" - # echo "Directory changed to: ${DIR}, Count of files: $count" - fi + # a count taken in this row already left out its moved names; a later row's name lowers it once it + # left + [ "$LAST_COUNT" = 0 ] || [ "$counted_in_row" = 1 ] || on_source "$FILE" || LAST_COUNT=$((LAST_COUNT - 1)) + count=$LAST_COUNT fi mvDebuglogger "Cycle of delete folder, Previous count: $LAST_COUNT, Count of file(s): $count" "Clean Folder - End Loop" if [ "$count" = ".placeholder" ] || [ "$count" != 0 ]; then mvlogger "Not deleting folder containing $count file$([ "$count" != ".placeholder" ] && echo "s"): ${DIR}" else - if [ "$TESTMODE" = "no" ]; then - # Check if empty folder exists and remove it (but skip ZFS dataset mountpoints) - if [ -d "${DIR}" ]; then - if ! is_zfs_dataset_mountpoint "${DIR}"; then - if rmdir "${DIR}" 2>/dev/null; then - mvlogger "Deleted empty folder: ${DIR}" - else - mvDebuglogger "Failed to delete folder (may not be empty): ${DIR}" "Clean Folder" - fi + note_emptied_share + # the share's top folder is cleanTopFolder's, after the pass and in topFolder mode only + if [ "$DIR" != "${SOURCE}/${SHARENAME}" ] && [ -d "${DIR}" ] && on_source "$DIR"; then + if is_zfs_dataset_mountpoint "${DIR}"; then + mvlogger "Skipping deletion of ZFS dataset mountpoint: ${DIR}" + # test mode asks what rmdir would: anything left in the folder keeps it + elif [ "$TESTMODE" = "yes" ]; then + if would_rmdir "$DIR"; then + TEST_GONE[$DIR]=1 + mvlogger "TEST MODE: Would delete empty folder: ${DIR}" else - mvlogger "Skipping deletion of ZFS dataset mountpoint: ${DIR}" - fi - fi - fi - fi - done - fi - - # Clean parent ZFS dataset if empty - if [[ "$ACTION" =~ "move" && "$FILETYPE" == "f" ]] && [ "$TESTMODE" = "no" ] && [ "$CLEANDATASETS" = "yes" ] && [[ "$CLEANFOLDERS" = "yes" || "$CLEANFOLDERS" = "topFolder" ]]; then - # Check counter if equal to 0 then check datasets - if [ "$LAST_COUNT" -eq 0 ]; then - # Count files in share - share_file_count=$(find "/mnt/${PRIMARYSTORAGENAME}/${SHARENAME}" -type f | wc -l) - mvDebuglogger "Cycle of delete dataset" "Clean Dataset - Start Loop" - # If no files in share - if [ "${share_file_count}" -eq 0 ]; then - # Check if mount point is ZFS - if is_zfs_pool "$PRIMARYSTORAGENAME"; then - DATASET="${PRIMARYSTORAGENAME}/${SHARENAME}" - #echo "Checking if ZFS dataset [${DATASET}] is completely empty..." - # If ZFS dataset children size is zero and No ZFS dataset children exist - if [ "$(zfs list -Hpo usedbychildren "${DATASET}")" = 0 ] && [ -z "$(zfs list -r -H -o name "${DATASET}" | tail -n +2)" ]; then - # Check for any files in the ZFS dataset avalible - dataset_file_count=$(find "/mnt/${DATASET}" -type f | wc -l) - if [ "${dataset_file_count}" -eq 0 ]; then - mvlogger "ZFS dataset [${DATASET}] appears empty, attempting to unmount and delete..." - # Unmount the ZFS dataset - if ! zfs unmount "${DATASET}"; then - mvlogger_t "Failed to unmount ZFS dataset [%s]" "failure" "${DATASET}" - continue - else - mvlogger "ZFS dataset [${DATASET}] successfully unmounted." - fi - # Destroy the ZFS dataset - if ! zfs destroy "${DATASET}"; then - mvlogger_t "Failed to destroy ZFS dataset [%s] — attempting to remount." "failure" "${DATASET}" - zfs mount "${DATASET}" 2>/dev/null || mvlogger_t "Failed to remount dataset [%s]" "warning" "${DATASET}" - continue - else - mvlogger "ZFS dataset [${DATASET}] successfully destroyed." - fi - else - mvlogger "ZFS dataset [${DATASET}] contains files or directories, will not delete..." + mvDebuglogger "TEST MODE: Would fail to delete folder (not empty): ${DIR}" "Clean Folder" fi + elif rmdir "${DIR}" 2>/dev/null; then + mvlogger "Deleted empty folder: ${DIR}" else - mvlogger "ZFS dataset [${DATASET}] contains child datasets, will not delete..." + mvDebuglogger "Failed to delete folder (may not be empty): ${DIR}" "Clean Folder" fi fi fi - fi + done fi - # Clean moved empty folders - if [[ "$ACTION" =~ "move" && "$FILETYPE" == "d" ]] && [ "$MOVE_EMPTY_FOLDERS" = "yes" ]; then + # Clean moved empty folders, once the folder arrived: a failed move's would exist nowhere + if [[ "$ACTION" =~ "move" && "$FILETYPE" == "d" ]] && [ "$MOVE_EMPTY_FOLDERS" = "yes" ] && [ "$arrived" -gt 0 ]; then START_DIR="${SOURCE}/${FILEPATH}" LAST_FOLDER_COUNT=$((REMAINING_CACHE_FOLDERS + REMAINING_ARRAY_FOLDERS + REMAINING_UNATTENDED_FOLDERS)) - EMPTY_DIR_COUNT=-1 - # If Unraid already deleted the folder (move mode) using upper folder, skip cleanup - if [ ! -d "$START_DIR" ]; then - START_DIR="$(dirname "${START_DIR}")" - if [ -d "$START_DIR" ]; then - mvDebuglogger "Skipping cleanup: $(qp "$START_DIR") no longer exists, using upper folder: $(qp "$(dirname "${START_DIR}")")" "Clean Empty Moved Folder" - else - mvDebuglogger "Skipping cleanup: $(qp "$START_DIR") no longer exists" "Clean Empty Moved Folder" - continue - fi + # Unraid's move deletes the folder itself; a parent gone too leaves the walk below nothing to do + if [ ! -d "$START_DIR" ] || ! on_source "$START_DIR"; then + [ "$DEBUGLEVEL" != 0 ] && mvDebuglogger "$(qp "$START_DIR") $([ -d "$START_DIR" ] && echo "would be" || echo is) gone from the source: the walk starts at its parent $(qp "$(dirname "$START_DIR")")" "Clean Empty Moved Folder" + START_DIR=$(dirname "$START_DIR") fi # Build list of parent directories @@ -2993,14 +3260,16 @@ processTheMoves() { mvDebuglogger "Cycle of delete empty folder: ${DIR}" "Clean Empty Moved Folder - Start Loop" - while [[ -d "$DIR" && "$DIR" != "${SOURCE}/${SHARENAME}" ]]; do + while [[ -d "$DIR" && "$DIR" != "${SOURCE}/${SHARENAME}" ]] && on_source "$DIR"; do DIR_LIST+="${DIR}"$'\n' DIR="$(dirname "${DIR}")" done - # Process each directory using while read + # Process each directory using while read; a break leaves chain_emptied 0 + chain_emptied=1 while IFS= read -r DIR; do [ -z "$DIR" ] && continue + chain_emptied=0 mvDebuglogger "Empty folder ${DIR}" "Clean Empty Moved Folder" # Stop at ZFS dataset boundaries @@ -3015,9 +3284,9 @@ processTheMoves() { break fi - # Count files and subdirectories - empty_file_count=$(find "$DIR" -maxdepth 1 -type f | wc -l) - empty_dir_count=$(find "$DIR" -mindepth 1 -type d | wc -l) + # the folder's own entries only: a walk below would mount each snapshot a child dataset shows + empty_file_count=$(count_left "$DIR" -maxdepth 1 -type f) + empty_dir_count=$(count_left "$DIR" -mindepth 1 -maxdepth 1 -type d) # Folder is truly empty if [ "$empty_file_count" -eq 0 ] && [ "$empty_dir_count" -eq 0 ]; then @@ -3028,9 +3297,15 @@ processTheMoves() { mvDebuglogger "Failed to delete moved folder (may not be empty): ${DIR}" "Clean Empty Moved Folder" break fi - else + # test mode asks what rmdir would: anything left in the folder, such as a symlink, keeps it + elif would_rmdir "$DIR"; then + TEST_GONE[$DIR]=1 mvlogger "TEST MODE: Would delete moved empty folder: ${DIR}" + else + mvDebuglogger "TEST MODE: Would fail to delete moved folder (not empty): ${DIR}" "Clean Empty Moved Folder" + break fi + chain_emptied=1 mvDebuglogger "Cycle of delete empty folder, Previous count: $LAST_FOLDER_COUNT, Count of all empty folders: $((LAST_FOLDER_COUNT - 1))" "Clean Empty Moved Folder - End Loop" else @@ -3039,52 +3314,7 @@ processTheMoves() { fi done <<<"${DIR_LIST}" - - if [ -n "${empty_file_count+x}" ] && [ -n "${empty_dir_count+x}" ]; then - EMPTY_DIR_COUNT=$((empty_file_count + empty_dir_count)) - else - EMPTY_DIR_COUNT=-1 - fi - fi - - # Clean top level folder if empty - if [[ "$ACTION" =~ "move" ]] && [ "$CLEANFOLDERS" = "topFolder" ]; then - # Check counters if equal to 0 then check top share - if [[ "$LAST_COUNT" -eq 0 || "$EMPTY_DIR_COUNT" -eq 0 ]]; then - # Determine top-level share folder - top_folder="${SOURCE}/${SHARENAME}" - # Skip if placeholder exists - if [ -d "$top_folder" ]; then - if [ -e "${top_folder}/.placeholder" ]; then - mvlogger "Not deleting top-level folder: contains .placeholder: ${top_folder}" - else - # Count files and subfolders - file_count=$(find "$top_folder" -type f | wc -l) - dir_count=$(find "$top_folder" -mindepth 1 -type d | wc -l) - - mvDebuglogger "Top folder: $(qp "$top_folder"), share file(s): $file_count, share folder(s): $dir_count" "Clean Top Folder" - - # Delete only if truly empty - if [ "$file_count" -eq 0 ] && [ "$dir_count" -eq 0 ]; then - if [ "$TESTMODE" = "no" ]; then - if ! is_zfs_dataset_mountpoint "$top_folder"; then - if rmdir "$top_folder" 2>/dev/null; then - mvlogger "Deleted empty top-level folder: $top_folder" - else - mvDebuglogger "Failed to delete top-level folder (may not be empty): $top_folder" "Clean Top Folder" - fi - else - mvlogger "Skipping deletion of ZFS dataset mountpoint: $top_folder" - fi - else - mvlogger "TEST MODE: Would delete empty top-level folder: $top_folder" - fi - else - mvlogger "Not deleting top-level folder: contains $file_count file(s), $dir_count subfolder(s): ${top_folder}" - fi - fi - fi - fi + [ "$chain_emptied" = 1 ] && note_emptied_share fi # Setting mover status: a name leaves the remaining-work counters once it arrived or was found gone, @@ -3135,6 +3365,27 @@ processTheMoves() { mvlogger "$(titleLine "Cleaning up" '-')" movesEnd moverStep "Cleaning up" + # once per noted share, after the pass: a soft stop's break 2 lands here too. A stop, whether it signals the run alone + # or every process (the plugin's), lets the step in hand finish, then the remount if one is due and the notice, and + # ends the run + trap 'stopped=1' TERM HUP INT + for ds in "${SHARE_DATASETS[@]}"; do + [ -z "$stopped" ] || break + cleanShareDataset "${ds%%/*}" "${ds#*/}" "${DATASET_DEST[$ds]}" + done + # the notice's log lines come back out of the $( ) + notice_lines=$(finish_on_stop dataset_problems_notice) + [ -z "$notice_lines" ] || printf '%s\n' "$notice_lines" + if [ -n "$stopped" ]; then + # a second stop must not end the run, or its mdcmd, before the pid file goes + trap '' TERM HUP INT + last_restore_turbo + # the plugin's stop removes these once the run has ended; a stop that signals the run alone leaves them + [ "$(cat "$PIDFILE" 2>/dev/null)" != "$$" ] || rm -f "$PIDFILE" "$MOVER_STATUS" "$PAUSEFILE" "$MOVINGFILE" + exit 0 + fi + trap - TERM HUP INT + for top in "${TOP_FOLDERS[@]}"; do cleanTopFolder "$top"; done if [ "$TESTMODE" != "yes" ] && [ ! -e $SOFTSTOPFILE ] && [ "$SYNCFAILED" = 0 ] && awk -F'|' '$11 ~ /^sync / { found = 1; exit } END { exit !found }' "$MOVER_ACTIONLIST"; then @@ -3160,13 +3411,65 @@ processTheMoves() { done fi - if [ $ENABLETURBO = "yes" ]; then - turbo_write_mode=$(cat /var/local/emhttp/var.ini | grep "md_write_method=" | cut -d'"' -f2) - mvlogger "Restoring original turbo write mode $( ([ $turbo_write_mode = "auto" ] && echo "Auto (read/modify/write)") || ([ $turbo_write_mode -eq 1 ] && echo "Turbo writes (Reconstruct)") || echo "Read/modify/write")" - [ $TESTMODE != "yes" ] && /usr/local/sbin/mdcmd set md_write_method $turbo_write_mode + restore_turbo +} + +# Prints the write method var.ini gives when it is one mdcmd can set back: 0, 1 or auto, as mover.php checks +write_method() { + local m + m=$(grep -s '^md_write_method=' /var/local/emhttp/var.ini | cut -d'"' -f2) + case $m in 0 | 1 | auto) echo "$m" ;; *) return 1 ;; esac +} + +# With Turbo Mode on, forces turbo write for the moves, only when the write method can be set back after +force_turbo() { + TURBO_WAS="" + [ "$ENABLETURBO" = "yes" ] || return 0 + if ! TURBO_WAS=$(write_method); then + mvlogger "Not forcing turbo write on: /var/local/emhttp/var.ini gives no write method (0, 1 or auto) to set back after" + return 0 fi + if [ "$TESTMODE" = "yes" ]; then + mvlogger "TEST MODE: Would force turbo write on" + return 0 + fi + # set first: a stop that ends the run from here on puts the write method back on its way out, and a second stop + # waits for it; a KILL cannot + trap 'trap "" HUP INT TERM; restore_turbo' EXIT + mvlogger "Forcing turbo write on" + /usr/local/sbin/mdcmd set md_write_method 1 || mvlogger "Could not force turbo write on: mdcmd exited $?" +} + +# Sets the write method back after force_turbo, where the run ends or from the EXIT trap of a run a signal ends sooner; +# it clears the trap, in a real run only once mdcmd has set it back +restore_turbo() { + local m name + [ -n "$TURBO_WAS" ] || return 0 + # var.ini's now, which Settings may have changed during the moves; the one read before when it gives none + m=$(write_method) || m=$TURBO_WAS + case $m in + auto) name="Auto (read/modify/write)" ;; + 1) name="Turbo writes (Reconstruct)" ;; + *) name="Read/modify/write" ;; + esac + if [ "$TESTMODE" = "yes" ]; then + mvlogger "TEST MODE: Would restore original turbo write mode $name" + else + mvlogger "Restoring original turbo write mode $name" + # the plugin's stop signals mdcmd before the run: one it ends first leaves the EXIT trap to try again + /usr/local/sbin/mdcmd set md_write_method "$m" || { + mvlogger "Could not restore original turbo write mode $name: mdcmd exited $?" + return 1 + } + fi + TURBO_WAS="" + trap - EXIT } +# The last try, before the run removes its pid file: a run that starts after may force turbo write, which a later try +# would undo +last_restore_turbo() { restore_turbo || trap - EXIT; } + # The settings pages cannot offer this combination, so it only arrives by saving a # lower moving threshold while the old freeing value is still selected. warn_freeing_above_moving() { @@ -3341,6 +3644,7 @@ start() { mvDebuglogger "Reset run-once settings completed" "run-once settings END" + last_restore_turbo mvlogger "Cleaning lock and stop files" for file in $PIDFILE $SOFTSTOPFILE $MOVER_STATUS $PAUSEFILE $MOVINGFILE; do [[ -e "$file" ]] && rm -f "$file" @@ -3430,8 +3734,7 @@ reset() { # Remove the schedule files, then write back the ones default.cfg sets; this runs after a failed step too, so the # schedules follow whichever settings are left rm -f "${MOVERTUNINGCFGFILE%/*}/mover.cron" "${MOVERTUNINGCFGFILE%/*}/mover.tuning.cron" "${MOVERTUNINGCFGFILE%/*}/mover.watchdog.cron" || failed=1 - /usr/bin/php -q /usr/local/emhttp/plugins/ca.mover.tuning/updateCron.php sync || failed=1 - /usr/local/sbin/update_cron || failed=1 + /usr/bin/php -q /usr/local/emhttp/plugins/ca.mover.tuning/updateCron.php apply || failed=1 if [ "$failed" -ne 0 ]; then echo "mover: Error: The reset did not complete, see the lines above." exit 1 @@ -3452,20 +3755,32 @@ killtree() { for child in $(pgrep --ns $$ -P $pid); do killtree $child done - # a paused copy acts on the TERM only once it runs again - [ $pid -ne $$ ] && kill -TERM $pid && kill -CONT "$pid" + # a paused copy acts on the TERM only once it runs again; a process can end before either signal reaches it + [ $pid -ne $$ ] && kill -TERM $pid 2>/dev/null && kill -CONT "$pid" 2>/dev/null } # Caution: stopping mover like this can lead to partial files on the destination # and possible incomplete hard link transfer. Not recommended to do this. stop() { + local pid waited=0 if [ ! -f $PIDFILE ]; then echo "mover: not running" exit 0 fi - killtree $(cat $PIDFILE) + pid=$(cat $PIDFILE) + killtree $pid sleep 2 - rm -f $PIDFILE $MOVER_STATUS $PAUSEFILE $MOVINGFILE + # a run cleaning ZFS datasets first finishes the step in hand and mounts the dataset back; its pid file keeps another + # run from starting meanwhile + if kill -0 "$pid" 2>/dev/null; then + echo "mover: waiting for the run to end" + while kill -0 "$pid" 2>/dev/null; do + [ $((waited += 1)) -le 60 ] || { echo "mover: the run (pid $pid) has not ended after a minute"; exit 1; } + sleep 1 + done + fi + # a run started since this one ended owns them now; a run stopped while cleaning datasets has removed its own + [ "$(cat $PIDFILE 2>/dev/null)" != "$pid" ] || rm -f $PIDFILE $MOVER_STATUS $PAUSEFILE $MOVINGFILE echo "mover: stopped" exit } diff --git a/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/cronSchedule.php b/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/cronSchedule.php new file mode 100644 index 00000000..1fa68a8e --- /dev/null +++ b/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/cronSchedule.php @@ -0,0 +1,61 @@ + $field) { + if (cron_field_ok($field, $limits[$i][0], $limits[$i][1], $limits[$i][2]) === false) { + return false; + } + } + return true; +} + +// One cron field: a comma list of * / n / n-m, each with an optional /step; numbers within min..max, names looked up in $names +function cron_field_ok($field, $min, $max, $names) +{ + foreach (explode(',', $field) as $item) { + if (preg_match('/^(\*|([a-z0-9]+)(?:-([a-z0-9]+))?)(?:\/([0-9]+))?\z/i', $item, $m) !== 1) { + return false; + } + if (isset($m[4]) === true && (int)$m[4] < 1) { + return false; + } + if ($m[1] === '*') { + continue; + } + foreach ([$m[2], $m[3] ?? ''] as $value) { + if ($value === '') { + continue; + } + // names count from $min, so jan is 1 and sun is 0; dcron reads a name only as mon or Mon, so MON is rejected + $index = array_search(lcfirst($value), $names, true); + $n = ctype_digit($value) === true ? (int)$value : ($index === false ? -1 : $index + $min); + if ($n < $min || $n > $max) { + return false; + } + } + } + return true; +} + +/** True when a saved schedule is set but valid_cron rejects it, so updateCron.php does not apply it */ +function saved_cron_invalid($cron) +{ + $cron = trim($cron); + return $cron !== '' && valid_cron($cron) === false; +} +?> diff --git a/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/debug_mover b/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/debug_mover index 64d75524..9a89ccc4 100755 --- a/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/debug_mover +++ b/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/debug_mover @@ -140,6 +140,16 @@ mkdir -p $DEBUGROOT/PLUGIN 2>&1 [ -f $CRON ] && cp -f $CRON $DEBUGROOT/PLUGIN/ca.mover.tuning.cron.txt 2>&1 +for file in "${CRON%/*}/mover.tuning.cron" "${CRON%/*}/mover.watchdog.cron"; do + [ -f "$file" ] && cp -f "$file" "$DEBUGROOT/PLUGIN/${file##*/}.txt" 2>&1 +done + +# the mover lines crond runs now, to compare with the cron files and the settings +{ + echo "### mover lines in /etc/cron.d/root" + grep -F -e ca.mover.tuning -e /usr/local/sbin/mover /etc/cron.d/root || echo "none" +} >$DEBUGROOT/PLUGIN/crontab.txt 2>&1 + for file in $UNRAID_CRON; do if [[ -f $file ]]; then cp -f "$file" "${DEBUGROOT}/PLUGIN/unraid.${file##*/}.txt" 2>&1 diff --git a/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/default.cfg b/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/default.cfg index 2db26e07..3b268454 100644 --- a/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/default.cfg +++ b/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/default.cfg @@ -1,7 +1,5 @@ moverDisabled="no" testmode="no" -validateFilenames="yes" -invalidFileChars="$ / < > : \" | ? *" logging="yes" debuglogging="no" notify="yes" diff --git a/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/files_in_use b/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/files_in_use new file mode 100755 index 00000000..5b584857 --- /dev/null +++ b/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/files_in_use @@ -0,0 +1,127 @@ +#!/usr/bin/perl +# SPDX-License-Identifier: GPL-2.0-only +# Copyright (C) 2026 Mover Tuning contributors +# +# files_in_use FILE... +# +# A faster stand-in for "fuser -s FILE...": answers whether any other process has one of the files +# open, so age_mover can leave such files for a later run. +# +# Exit status (0 and 1 match fuser -s; 2 is specific to this tool): +# 0 at least one file is in use +# 1 no file is in use (files that have vanished count as not in use) +# 2 no reliable answer: neither a lease nor fuser could check the files; the caller treats the +# files as in use. (Once we exec fuser, its own exit status is returned, whatever it is.) +# +# Why not just run fuser? +# fuser walks /proc for every process on the system. On a busy Unraid host (thousands of +# processes, dozens of containers) that measured ~146 ms per call, which nearly doubled the time +# to move many small files. Asking the kernel for a lease is a few microseconds. +# +# How the lease test works: +# Linux grants a write lease (fcntl F_SETLEASE with F_WRLCK) only when the caller's descriptor is +# the only open one for the file. So: +# - lease granted -> nobody else has the file open -> not in use. We release the lease at +# once; we never hold it. +# - EAGAIN -> someone else has it open -> in use. +# - any other error -> the kernel or filesystem cannot answer (for example leases are disabled, +# or the filesystem does not support them, as with FUSE and network +# filesystems) -> hand the whole question to fuser. +# This needs Perl because Bash has no way to call fcntl(F_SETLEASE). +# +# Files someone else already holds a lease on: +# Opening such a file would disturb the holder (Samba with oplocks, for example). Linux starts +# breaking the lease and signals the holder as part of the open, even with O_NONBLOCK, which +# only skips the wait. So first look the file up in /proc/locks without opening it. A lease +# holder has the file open, so a file with a lease is in use and is never opened. If /proc/locks +# cannot be read, hand the whole question to fuser, which never opens the files it checks. +# +# EAGAIN and EWOULDBLOCK are the same value on Linux. Both are checked only for portability. +# Neither is a transient "try again" here: each means "in use". +use strict; +use warnings; + +use Errno qw(EAGAIN EWOULDBLOCK ENOENT ENOTDIR); +use Fcntl qw(O_NONBLOCK O_RDONLY F_UNLCK F_WRLCK); + +# Linux-specific fcntl command. The plugin package is x86_64-only, where F_SETLEASE is +# F_LINUX_SPECIFIC_BASE + 0. +my $F_SETLEASE = 1024; +# The kernel sends SIGIO to a lease holder when another process opens the file and so asks for the +# lease to be broken. SIGIO kills the process by default. That can happen in the few instructions +# between taking and releasing the lease, so ignore it. Closing the descriptor releases the lease +# anyway. +local $SIG{IO} = 'IGNORE'; + +@ARGV or die "Usage: $0 FILE...\n"; + +# Hand every file to fuser, not just the rest, so its exit status answers for all of them. exec +# only returns if fuser cannot be run, so exit 2 (no answer). +sub fall_back_to_fuser { + exec 'fuser', '-s', @ARGV; + exit 2; +} + +# Inode numbers of files that some process holds a lease (or NFS delegation) on, read once from +# /proc/locks. Its lines look like "3: LEASE ACTIVE WRITE 1234 00:2d:5678 0 EOF", where +# 00:2d:5678 is the filesystem's major:minor device and the inode. Only the inode is compared: +# stat's device differs from that of /proc/locks on some filesystems (btrfs subvolumes, for +# example). Two files with the same inode number on different filesystems can make a file look +# in use, which only leaves it for a later run; missing a lease would break it. +my %leased_inodes; +open(my $locks, '<', '/proc/locks') or fall_back_to_fuser(); +while (my $line = <$locks>) { + next unless $line =~ /\b(?:LEASE|DELEG)\b/x; + $leased_inodes{$1} = 1 if $line =~ /\s[0-9a-f]+:[0-9a-f]+:(\d+)\s/x; +} +close $locks; + +for my $path (@ARGV) { + # stat does not open the file, so it cannot disturb a lease holder. + my @stat = stat($path); + if (!@stat) { + my $error = 0 + $!; + # The file was removed or renamed since the move list was made, so nothing has it open. + # age_mover deals with the missing file itself. + next if $error == ENOENT || $error == ENOTDIR; + fall_back_to_fuser(); + } + # Someone holds a lease on it, so they have it open: in use. Don't open it. + exit 0 if $leased_inodes{$stat[1]}; + + my $file; + # Open read-only, so the check itself never changes the file. O_NONBLOCK covers a lease taken + # after /proc/locks was read: the open still disturbs that holder, but fails at once with + # EWOULDBLOCK instead of waiting for the lease to be given up. + if (!sysopen($file, $path, O_RDONLY | O_NONBLOCK)) { + my $error = 0 + $!; + # Removed or renamed since the stat above: not in use, as above. + next if $error == ENOENT || $error == ENOTDIR; + # A lease was taken after /proc/locks was read: in use. + exit 0 if $error == EAGAIN || $error == EWOULDBLOCK; + # Any other failure to open (permissions, I/O error): let fuser try. + fall_back_to_fuser(); + } + + # The actual test: a write lease is refused with EAGAIN while any other descriptor for the file + # is open, in this process or any other. + if (!fcntl($file, $F_SETLEASE, F_WRLCK)) { + my $error = 0 + $!; + close $file; + # Another process has the file open: in use. + exit 0 if $error == EAGAIN || $error == EWOULDBLOCK; + # Typically EINVAL: this filesystem or kernel does not support leases. + fall_back_to_fuser(); + } + + # We got the lease, so the file was not in use. Release it at once. If releasing fails, + # something unexpected is going on: don't trust our answer, let fuser decide. + if (!fcntl($file, $F_SETLEASE, F_UNLCK)) { + close $file; + fall_back_to_fuser(); + } + close $file; +} + +# Every file was free (or gone). As with fuser -s, 1 means "not in use". +exit 1; diff --git a/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/languages/de_DE.txt b/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/languages/de_DE.txt index b903c435..a4e1f3c5 100644 --- a/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/languages/de_DE.txt +++ b/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/languages/de_DE.txt @@ -8,6 +8,9 @@ %s files and %s folders representing %s could not be movedsynced by Mover Tuning plugin=%s Dateien und %s Ordner mit einer Größe von %s konnten vom Mover Tuning Plugin nicht verschoben/synchronisiert werden. Action=Aktion +a file is hidden under it stop writes to the share, zfs unmount %s, move anything in %s aside, zfs mount %s, then move it back into %s without replacing a file already there keep both copies and compare them=eine Datei ist darunter verdeckt: Schreibzugriffe auf die Freigabe stoppen, zfs unmount %s ausführen, alles in %s beiseite verschieben, zfs mount %s ausführen, dann alles zurück nach %s verschieben, ohne eine dort vorhandene Datei zu ersetzen: beide Kopien behalten und vergleichen +mounted again, but the look for a file written to %s as it was mounted was cut short, so one may be hidden under it stop writes to the share, zfs unmount %s, move anything in %s aside, zfs mount %s, then move it back into %s without replacing a file already there keep both copies and compare them=wieder eingehängt, aber die Suche nach einer beim Einhängen nach %s geschriebenen Datei wurde abgebrochen, eine Datei ist darunter vielleicht verdeckt: Schreibzugriffe auf die Freigabe stoppen, zfs unmount %s ausführen, alles in %s beiseite verschieben, zfs mount %s ausführen, dann alles zurück nach %s verschieben, ohne eine dort vorhandene Datei zu ersetzen: beide Kopien behalten und vergleichen +the remount was cut short, so it may not be mounted or may hide a file stop writes to the share, if zfs mount lists it at %s run zfs unmount %s, move anything in %s aside, zfs mount %s, then move it back into %s without replacing a file already there keep both copies and compare them=das erneute Einhängen wurde abgebrochen, es ist also vielleicht nicht eingehängt oder verdeckt eine Datei: Schreibzugriffe auf die Freigabe stoppen, wenn zfs mount es unter %s auflistet, zfs unmount %s ausführen, alles in %s beiseite verschieben, zfs mount %s ausführen, dann alles zurück nach %s verschieben, ohne eine dort vorhandene Datei zu ersetzen: beide Kopien behalten und vergleichen All community developers=Alle Entwickler der Community %s files and %s folders were movedsynced, but rsync reported errors for them Check the Mover Tuning log=%s Dateien und %s Ordner wurden verschoben/synchronisiert, aber rsync hat dabei Fehler gemeldet. Bitte das Mover‑Tuning‑Protokoll prüfen. Allow force mover schedule to run during a parity checkrebuild=Erlaubt das erzwungene Ausführen der Datenverschiebung während einer Paritätsprüfung oder Wiederherstellung @@ -25,6 +28,7 @@ Cache → Array=Cache → Speicherverbund Cancel=Abbrechen Clean empty folders=Leere Ordner bereinigen Clean empty ZFS datasets=Leere ZFS‑Datasets bereinigen +Clean empty ZFS datasets did not finish for %s The mover log has the details unless Log Mover Tuning plugin actions is set to No=Leere ZFS‑Datasets bereinigen wurde für %s nicht abgeschlossen. Details stehen im Protokoll, außer wenn „Aktionen des Mover‑Tuning‑Plugins protokollieren“ auf Nein steht. CLI help commands=CLI‑Hilfebefehle Comma separated list of file types=Kommagetrennte Liste von Dateitypen Cron Schedule to force move all of files=Cron‑Zeitplan zum erzwungenen Verschieben aller Dateien @@ -36,22 +40,17 @@ Delete Mover Log files over than this days old=Protokolldateien der Datenverschi Disable Mover running on a schedule=Zeitplan für Datenverschiebung deaktivieren disables test mode=deaktiviert den Testmodus disables the plugins schedule=deaktiviert den Zeitplan des Plugins -disables validation of input filenames=deaktiviert die Prüfung von Dateinamen Download=Herunterladen enable smart caching=Intelligentes Caching aktivieren Error checking mover status Please refresh the page=Fehler beim Prüfen des Status der Datenverschiebung. Bitte Seite aktualisieren. Error Config file %s not found=Fehler: Konfigurationsdatei %s wurde nicht gefunden. Error Failed to convert CRLF line endings in %s Check file permissions=Fehler: CRLF‑Zeilenenden in %s konnten nicht konvertiert werden. Bitte Dateiberechtigungen prüfen. -Error Invalid filename path %s Please either change the filename to valid or disable the Validate input filenames option=Fehler: Ungültiger Dateipfad %s. Bitte Dateinamen korrigieren oder die Prüfung von Dateinamen deaktivieren. Error No files found to move for %s=Fehler: Keine Dateien zum Verschieben für %s gefunden. Errors Only=Nur Fehler Estimated Completion=Geschätzte Fertigstellung ETA=Restzeit -Failed to destroy ZFS dataset %s — attempting to remount=ZFS‑Dataset %s konnte nicht gelöscht werden — erneutes Einhängen wird versucht. -Failed to remount dataset %s=Dataset %s konnte nicht erneut eingehängt werden. Failed to reset Mover Tuning Check the logs=Zurücksetzen von Mover Tuning fehlgeschlagen. Bitte Protokolle prüfen. Failed to start Mover Tuning Check the logs=Start des Mover‑Tunings fehlgeschlagen. Bitte Protokolle prüfen. -Failed to unmount ZFS dataset %s=ZFS‑Dataset %s konnte nicht ausgehängt werden. Fatal error %s does not exist, check this=Schwerer Fehler: %s existiert nicht. Bitte prüfen. Fatal error cache not enabled and less than 2 pools set up=Schwerer Fehler: Cache‑Pool nicht aktiviert und weniger als zwei Pools eingerichtet. Fatal error cache not present, or only cache present, and less than 2 pools set up=Schwerer Fehler: Cache‑Pool fehlt oder nur Cache‑Pool vorhanden und weniger als zwei Pools eingerichtet. @@ -75,7 +74,6 @@ If you want Mover Tuning to fully manage scheduling, disable it in Mover Setting Ignore All hidden files and directories=Alle versteckten Dateien und Ordner ignorieren Ignore files and folders listed inside of a text file=Dateien und Ordner ignorieren, die in einer Textdatei aufgelistet sind Ignore file types=Dateitypen ignorieren -Invalid characters to block=Ungültige Zeichen zum Blockieren Largest first=Größte zuerst Let scheduled mover run during a parity check rebuild=Zeitplan für Datenverschiebung während Paritätsprüfung/Wiederherstellung erlauben Log files=Protokolldateien @@ -84,6 +82,7 @@ Logs parent folder for Mover Tuning plugin=Übergeordneter Ordner für Protokoll Low=Niedrig Maintainers=Betreuer make those plugins with ❤️ and a lot of ☕=machen diese Plugins mit ❤️ und viel ☕ +mounted read-only at %s stop writes to the share, umount %s, move anything in %s aside, zfs mount %s, then move it back into %s without replacing a file already there keep both copies and compare them=schreibgeschützt eingehängt unter %s: Schreibzugriffe auf die Freigabe stoppen, umount %s ausführen, alles in %s beiseite verschieben, zfs mount %s ausführen, dann alles zurück nach %s verschieben, ohne eine dort vorhandene Datei zu ersetzen: beide Kopien behalten und vergleichen Move ALL files from current pool ignores filters and thresholds=ALLE Dateien aus dem aktuellen Pool verschieben (ohne Filter und Schwellenwerte) Move ALL files to current pool ignores filters and thresholds=ALLE Dateien in den aktuellen Pool verschieben (ohne Filter und Schwellenwerte) Move All from Primary->Secondary cacheyes shares pool percentage=Alles vom Primärspeicher → Sekundärspeicher verschieben (cache:yes) – Pool‑Prozent @@ -125,7 +124,9 @@ Mover Tuning thresholds=Mover‑Tuning‑Schwellwerte No files were movedsynced by Mover Tuning plugin Elapsed time %s=Keine Dateien wurden durch das Mover Tuning Plugin verschoben/synchronisiert. Verstrichene Zeit %s No log files yet=Noch keine Protokolldateien Not Applicable Share Does Not Exist Yet=Nicht anwendbar (Freigabe existiert noch nicht) +Not a valid cron schedule it is not applied=Kein gültiger Cron‑Zeitplan: Er wird nicht übernommen. Notify Mover Tuning plugin actions=Aktionen des Mover‑Tuning‑Plugins melden +not mounted stop writes to the share, move anything in %s aside, zfs mount %s, then move it back into %s without replacing a file already there keep both copies and compare them=nicht eingehängt: Schreibzugriffe auf die Freigabe stoppen, alles in %s beiseite verschieben, zfs mount %s ausführen, dann alles zurück nach %s verschieben, ohne eine dort vorhandene Datei zu ersetzen: beide Kopien behalten und vergleichen Oldest first=Älteste zuerst Only move files larger than this in MB=Nur Dateien verschieben, die größer sind als dieser Wert (in MB) Only move files that are older than this in days=Nur Dateien verschieben, die älter sind als dieser Wert (in Tagen) @@ -181,7 +182,6 @@ Use CTIME change time=CTIME (Statusänderungszeit) verwenden Use global=Global verwenden Used IDE=Verwendete IDE User shares not enabled=Benutzerfreigaben sind nicht aktiviert! -Validate input filenames to prevent attacks=Eingabedateinamen validieren, um Angriffe zu verhindern Very Low=Sehr niedrig View=Anzeigen Want to support the developer and say Thank You=Möchtest du den Entwickler unterstützen und **Danke** sagen? @@ -237,6 +237,8 @@ Youre welcome 😊 Thanks for using=Gern geschehen 😊 Danke für die Nutzung! > Führt den age_mover‑Zeitplan des Mover‑Tuning‑Plugins anhand deines eigenen Cron‑Eintrags aus (inklusive aller Plugin‑Filter). > > Beispiel Cron‑Eintrag: 0 */4 * * *.  Führt den Vorgang alle 4 Stunden aus. Was ist Cron? +> +> Der Zeitplan muss ein gültiger Cron‑Eintrag sein: Ein ungültiger wird nicht übernommen, und der Fehler wird ins Syslog geschrieben. :end :mover_tune_testmode_plug: @@ -244,31 +246,6 @@ Youre welcome 😊 Thanks for using=Gern geschehen 😊 Danke für die Nutzung!

Achtung – Der Testmodus hält den originalen Mover nicht auf: Er läuft trotzdem nach dem Zeitplan der Option Erzwungenes Verschieben aller Dateien nach Zeitplan und über die Schaltfläche „Jetzt verschieben“, wenn die Option „Jetzt verschieben“ folgt den Plugin‑Filtern auf Nein steht. Ab Unraid 7.2.1 starten der Mover‑Zeitplan und die Verschieben‑Schaltflächen von Unraid selbst immer den originalen Mover.

:end -:mover_tune_validate_plug: -

In der Cybersicherheit können Dateinamen ein kritischer Angriffsvektor sein. Nicht geprüfte Dateinamen stellen ein erhebliches Risiko dar und können die Systemintegrität gefährden.

-

Die Validierung von Dateinamen prüft jeden Dateinamen, bevor er vom Mover verarbeitet wird. Dadurch wird sichergestellt, dass nur gültige Dateinamen akzeptiert werden und das Risiko von Angriffen reduziert wird.

-

Deaktiviere diese Option nur, wenn du sehr viele Dateien verschieben musst und sicher bist, dass alle Dateinamen gültig sind und keine Sicherheitsrisiken enthalten.

-

1. Längenprüfung – Dateinamen über 255 Zeichen werden abgelehnt.

-

2. Ungültige Zeichen – Dateinamen dürfen keine Zeichen enthalten wie -($), (/), (<), (>), (:), ("), (|), (?), (*).

-

3. Pfad‑Traversal verhindern – Dateinamen dürfen keine Sequenzen wie (../) enthalten.

-

Wenn eine dieser Prüfungen fehlschlägt, wird der Dateiname abgelehnt.

-:end - -:mover_tune_invalidfilechars_plug: -

Ungültige Zeichen in Dateinamen sind unter anderem: - $ - / - < - > - : - " - | - ? - *. -

-:end - :mover_tune_logging_plug:

Aktiviert oder deaktiviert die Protokollierung des Plugins.

Datei (und Syslog) speichert sowohl im Syslog als auch in der Logdatei.

@@ -464,11 +441,11 @@ Youre welcome 😊 Thanks for using=Gern geschehen 😊 Danke für die Nutzung! :mover_tune_cleanfolders_plug:

Ja – entfernt den übergeordneten Ordner nur der verschobenen Dateien.

-

Oberster Ordner – entfernt den gesamten Freigabe‑Ordner einschließlich aller leeren Unterordner im Primärspeicher.

+

Oberster Ordner – wie Ja, und entfernt zusätzlich den obersten Freigabe‑Ordner dort, woher die Dateien verschoben wurden, sobald er leer ist, außer er ist ein ZFS‑Dataset (siehe Leere ZFS‑Datasets bereinigen).

:end :mover_tune_cleandatasets_plug: -> Hängt das übergeordnete ZFS‑Dataset aus und löscht es, sofern es keine Unter‑Datasets enthält. Funktioniert nur, wenn Leere Ordner bereinigen auf Ja oder Oberster Ordner steht. +> Hängt das ZFS‑Dataset der Freigabe im Primärspeicher aus und löscht es, nachdem ihre Dateien verschoben wurden, nur wenn es keine Unter‑Datasets oder Snapshots enthält und alles, was darin übrig ist, ein Ordner ist, den es auch im Sekundärspeicher gibt. Die eigenen ZFS‑Einstellungen des Datasets, etwa Komprimierung oder Quota, werden mit gelöscht. Funktioniert nur, wenn Leere Ordner bereinigen auf Ja oder Oberster Ordner steht. :end :mover_tune_sharecalculation_plug: diff --git a/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/languages/en_US.txt b/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/languages/en_US.txt index 26072628..4a5d54ea 100644 --- a/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/languages/en_US.txt +++ b/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/languages/en_US.txt @@ -11,6 +11,9 @@ %s files and %s folders representing %s could not be movedsynced by Mover Tuning plugin=%s files and %s folders representing %s could not be moved/synced by Mover Tuning plugin. %s files and %s folders were movedsynced, but rsync reported errors for them Check the Mover Tuning log=%s files and %s folders were moved/synced, but rsync reported errors for them. Check the Mover Tuning log. Action= +a file is hidden under it stop writes to the share, zfs unmount %s, move anything in %s aside, zfs mount %s, then move it back into %s without replacing a file already there keep both copies and compare them=a file is hidden under it: stop writes to the share, zfs unmount %s, move anything in %s aside, zfs mount %s, then move it back into %s without replacing a file already there: keep both copies and compare them +mounted again, but the look for a file written to %s as it was mounted was cut short, so one may be hidden under it stop writes to the share, zfs unmount %s, move anything in %s aside, zfs mount %s, then move it back into %s without replacing a file already there keep both copies and compare them=mounted again, but the look for a file written to %s as it was mounted was cut short, so one may be hidden under it: stop writes to the share, zfs unmount %s, move anything in %s aside, zfs mount %s, then move it back into %s without replacing a file already there: keep both copies and compare them +the remount was cut short, so it may not be mounted or may hide a file stop writes to the share, if zfs mount lists it at %s run zfs unmount %s, move anything in %s aside, zfs mount %s, then move it back into %s without replacing a file already there keep both copies and compare them=the remount was cut short, so it may not be mounted or may hide a file: stop writes to the share, if zfs mount lists it at %s run zfs unmount %s, move anything in %s aside, zfs mount %s, then move it back into %s without replacing a file already there: keep both copies and compare them All community developers= Allow force mover schedule to run during a parity checkrebuild=Allow force mover schedule to run during a parity check/rebuild All plugin settings return to their defaults, including the Mover Tuning schedule, the forced move schedule and the cache watchdog, and the override settings of every share are deleted=All plugin settings return to their defaults, including the Mover Tuning schedule, the forced move schedule and the cache watchdog, and the override settings of every share are deleted. @@ -27,6 +30,7 @@ Cache → Array= Cancel= Clean empty folders= Clean empty ZFS datasets= +Clean empty ZFS datasets did not finish for %s The mover log has the details unless Log Mover Tuning plugin actions is set to No=Clean empty ZFS datasets did not finish for %s. The mover log has the details unless Log Mover Tuning plugin actions is set to No. CLI help commands= Comma separated list of file types= Cron Schedule to force move all of files= @@ -38,22 +42,17 @@ Delete Mover Log files over than this days old= Disable Mover running on a schedule= disables test mode= disables the plugins schedule=disables the plugin's schedule -disables validation of input filenames= Download= enable smart caching= Error checking mover status Please refresh the page=Error checking mover status. Please refresh the page. Error Config file %s not found=Error: Config file '%s' not found. Error Failed to convert CRLF line endings in %s Check file permissions=Error: Failed to convert CRLF line endings in %s. Check file permissions. -Error Invalid filename path %s Please either change the filename to valid or disable the Validate input filenames option=Error: Invalid filename path: %s. Please either change the filename to valid or disable the 'Validate input filenames' option. Error No files found to move for %s=Error: No files found to move for %s Errors Only= Estimated Completion= ETA= -Failed to destroy ZFS dataset %s — attempting to remount=Failed to destroy ZFS dataset [%s] — attempting to remount. -Failed to remount dataset %s=Failed to remount dataset [%s] Failed to reset Mover Tuning Check the logs=Failed to reset Mover Tuning. Check the logs. Failed to start Mover Tuning Check the logs=Failed to start Mover Tuning. Check the logs. -Failed to unmount ZFS dataset %s=Failed to unmount ZFS dataset [%s] Fatal error %s does not exist, check this=Fatal error: %s does not exist, check this. Fatal error cache not enabled and less than 2 pools set up=Fatal error: cache not enabled and less than 2 pools set up. Fatal error cache not present, or only cache present, and less than 2 pools set up=Fatal error: cache not present, or only cache present, and less than 2 pools set up. @@ -77,7 +76,6 @@ If you want Mover Tuning to fully manage scheduling, disable it in Mover Setting Ignore All hidden files and directories= Ignore files and folders listed inside of a text file= Ignore file types= -Invalid characters to block= Largest first= Let scheduled mover run during a parity check rebuild=Let scheduled mover run during a parity check / rebuild Log files= @@ -86,6 +84,7 @@ Logs parent folder for Mover Tuning plugin= Low= Maintainers= make those plugins with ❤️ and a lot of ☕=make those plugins with ❤️ (and a lot of ☕). +mounted read-only at %s stop writes to the share, umount %s, move anything in %s aside, zfs mount %s, then move it back into %s without replacing a file already there keep both copies and compare them=mounted read-only at %s: stop writes to the share, umount %s, move anything in %s aside, zfs mount %s, then move it back into %s without replacing a file already there: keep both copies and compare them Move ALL files from current pool ignores filters and thresholds=Move **ALL** files from current pool (ignores filters and thresholds) Move ALL files to current pool ignores filters and thresholds=Move **ALL** files to current pool (ignores filters and thresholds) Move All from Primary->Secondary cacheyes shares pool percentage=Move All from Primary->Secondary (cache:yes) shares pool percentage @@ -127,7 +126,9 @@ Mover Tuning thresholds= No files were movedsynced by Mover Tuning plugin Elapsed time %s=No files were moved/synced by Mover Tuning plugin. Elapsed time: %s No log files yet= Not Applicable Share Does Not Exist Yet=Not Applicable (Share Does Not Exist Yet) +Not a valid cron schedule it is not applied=Not a valid cron schedule: it is not applied. Notify Mover Tuning plugin actions= +not mounted stop writes to the share, move anything in %s aside, zfs mount %s, then move it back into %s without replacing a file already there keep both copies and compare them=not mounted: stop writes to the share, move anything in %s aside, zfs mount %s, then move it back into %s without replacing a file already there: keep both copies and compare them Oldest first= Only move files larger than this in MB=Only move files larger than this (in MB) Only move files that are older than this in days=Only move files that are older than this (in days) @@ -183,7 +184,6 @@ Use CTIME change time=Use CTIME (change time) Use global= Used IDE= User shares not enabled=User shares not enabled! -Validate input filenames to prevent attacks= Very Low= View= Want to support the developer and say Thank You=Want to support the developer and say **Thank You**? @@ -239,6 +239,8 @@ Youre welcome 😊 Thanks for using=You're welcome! 😊 Thanks for using! > Runs the age_mover schedule from the Mover Tuning plugin using your custom cron entry (includes all plugin filters). > > Cron Schedule entry example 0 */4 * * *.  To run at every 4 hours.  What Is Cron +> +> The schedule must be a valid cron entry: an invalid one is not applied, and the error is written to the syslog. :end :mover_tune_testmode_plug: @@ -246,31 +248,6 @@ Youre welcome 😊 Thanks for using=You're welcome! 😊 Thanks for using!

Caution - Test Mode does not stop original Mover: it still runs on the "Force move of all files on a schedule" schedule, and from the Move Now button if "Move Now button follows plug-in filters" is set to No. On Unraid 7.2.1 and later, Unraid's own Mover schedule and Move buttons always run the original Mover.

:end -:mover_tune_validate_plug: -

In cybersecurity, filenames can be a critical vector for potential attacks and system vulnerabilities. Unsanitized filenames pose significant risks that can compromise system integrity and security.

-

Validate input filenames will check every filename before it is processed by the Mover. This ensures that only valid filenames are accepted, reducing the risk of attacks and vulnerabilities.

-

Disable Only if you have many files to move and you are sure that all filenames are valid and do not contain any potential security risks.

-

1. Check filename length - If the filename exceeds 255 characters, it will be rejected.

-

2. Check for invalid characters - The filename should not contain any characters that are considered invalid for filenames, such as -( $ ), ( / ), ( < ), ( > ), ( : ), ( " ), ( | ), ( ? ), ( * ).

-

3. Prevent path traversal - The filename should not contain any characters that can be used to traverse directories, such as ( ../ ).

-

If one of these checks fails, the filename will be rejected.

-:end - -:mover_tune_invalidfilechars_plug: -

The filename characters such as: - $ - / - < - > - : - " - | - ? - *. -

-:end - :mover_tune_logging_plug:

Enables or disables logging from this plugin.

File (and Syslog) will store to SYSLOG and to the log file.

@@ -465,11 +442,11 @@ Youre welcome 😊 Thanks for using=You're welcome! 😊 Thanks for using! :mover_tune_cleanfolders_plug:

Yes - Removes the parent folder only of moved files.

-

Top Folder - Removes the top-level share folder of the moved content, including all empty subfolders on the primary storage.

+

Top Folder - As Yes, and also removes the share's top-level folder where the files moved from, once it is empty, unless it is a ZFS dataset (see Clean empty ZFS datasets).

:end :mover_tune_cleandatasets_plug: -> This will unmount and destroy the parent ZFS dataset on share of moved files, only if not contain child datasets within. Works only when Clean empty folders is set to Yes or Top Folder. +> This will unmount and destroy the share's ZFS dataset on the primary storage after its files move, only if it has no child datasets or snapshots and each entry left in it is a folder that the secondary storage also has. The dataset's own ZFS settings, such as compression or quota, are deleted with it. Works only when Clean empty folders is set to Yes or Top Folder. :end :mover_tune_sharecalculation_plug: diff --git a/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/languages/fr_FR.txt b/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/languages/fr_FR.txt index 6a769b9e..a8848318 100644 --- a/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/languages/fr_FR.txt +++ b/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/languages/fr_FR.txt @@ -9,6 +9,9 @@ %s files and %s folders representing %s could not be movedsynced by Mover Tuning plugin=%s fichiers et %s dossiers représentant %s n’ont pas pu être déplacés/synchronisés par le plugin Mover Tuning. %s files and %s folders were movedsynced, but rsync reported errors for them Check the Mover Tuning log=%s fichiers et %s dossiers ont été déplacés/synchronisés, mais rsync a signalé des erreurs les concernant. Consultez le journal de Mover Tuning. Action=Action +a file is hidden under it stop writes to the share, zfs unmount %s, move anything in %s aside, zfs mount %s, then move it back into %s without replacing a file already there keep both copies and compare them=un fichier est masqué dessous : arrêtez les écritures sur le partage, lancez zfs unmount %s, mettez de côté tout ce qui est dans %s, lancez zfs mount %s, puis remettez le tout dans %s sans remplacer un fichier déjà présent : gardez les deux copies et comparez-les +mounted again, but the look for a file written to %s as it was mounted was cut short, so one may be hidden under it stop writes to the share, zfs unmount %s, move anything in %s aside, zfs mount %s, then move it back into %s without replacing a file already there keep both copies and compare them=monté à nouveau, mais la recherche de fichiers écrits dans %s pendant le montage a été interrompue, un fichier y est peut-être masqué : arrêtez les écritures sur le partage, lancez zfs unmount %s, mettez de côté tout ce qui est dans %s, lancez zfs mount %s, puis remettez le tout dans %s sans remplacer un fichier déjà présent : gardez les deux copies et comparez-les +the remount was cut short, so it may not be mounted or may hide a file stop writes to the share, if zfs mount lists it at %s run zfs unmount %s, move anything in %s aside, zfs mount %s, then move it back into %s without replacing a file already there keep both copies and compare them=le remontage a été interrompu, il peut donc ne pas être monté ou masquer un fichier : arrêtez les écritures sur le partage, si zfs mount le montre sur %s lancez zfs unmount %s, mettez de côté tout ce qui est dans %s, lancez zfs mount %s, puis remettez le tout dans %s sans remplacer un fichier déjà présent : gardez les deux copies et comparez-les All community developers=Tous les développeurs de la communauté Allow force mover schedule to run during a parity checkrebuild=Autoriser l’exécution forcée du mover pendant une vérification/réparation de parité All plugin settings return to their defaults, including the Mover Tuning schedule, the forced move schedule and the cache watchdog, and the override settings of every share are deleted=Tous les paramètres du plugin reviennent à leurs valeurs par défaut, y compris la planification Mover Tuning, l’horaire du déplacement forcé et la surveillance du cache, et les paramètres remplacés de chaque part sont supprimés. @@ -25,6 +28,7 @@ Cache → Array=Cache → Array Cancel=Annuler Clean empty folders=Nettoyer les dossiers vides Clean empty ZFS datasets=Nettoyer les datasets ZFS vides +Clean empty ZFS datasets did not finish for %s The mover log has the details unless Log Mover Tuning plugin actions is set to No=Nettoyer les datasets ZFS vides n'a pas abouti pour %s. Le journal donne les détails, sauf si « Journaliser les actions du plugin Mover Tuning » est sur Non. CLI help commands=Commandes d’aide CLI Comma separated list of file types=Liste de types de fichiers séparés par des virgules Cron Schedule to force move all of files=Cron pour forcer le déplacement de tous les fichiers @@ -36,22 +40,17 @@ Delete Mover Log files over than this days old=Supprimer les journaux du mover p Disable Mover running on a schedule=Désactiver l’exécution programmée du mover disables test mode=désactive le mode test disables the plugins schedule=désactive la planification du plugin -disables validation of input filenames=désactive la validation des noms de fichiers Download=Télécharger enable smart caching=activer le cache intelligent Error checking mover status Please refresh the page=Erreur lors de la vérification du statut du mover. Veuillez rafraîchir la page. Error Config file %s not found=Erreur : fichier de configuration « %s » introuvable. Error Failed to convert CRLF line endings in %s Check file permissions=Erreur : impossible de convertir les fins de ligne CRLF dans %s. Vérifiez les permissions du fichier. -Error Invalid filename path %s Please either change the filename to valid or disable the Validate input filenames option=Erreur : chemin de fichier invalide %s. Corrigez le nom ou désactivez l’option de validation des noms de fichiers. Error No files found to move for %s=Erreur : aucun fichier trouvé à déplacer pour %s Errors Only=Erreurs uniquement Estimated Completion=Fin estimée ETA=Temps restant -Failed to destroy ZFS dataset %s — attempting to remount=Échec de la destruction du dataset ZFS [%s] — tentative de remontage. -Failed to remount dataset %s=Échec du remontage du dataset [%s] Failed to reset Mover Tuning Check the logs=Échec de la réinitialisation de Mover Tuning. Consultez les journaux. Failed to start Mover Tuning Check the logs=Échec du démarrage de Mover Tuning. Consultez les journaux. -Failed to unmount ZFS dataset %s=Échec du démontage du dataset ZFS [%s] Fatal error %s does not exist, check this=Erreur fatale : %s n’existe pas, vérifiez cela. Fatal error cache not enabled and less than 2 pools set up=Erreur fatale : cache non activé et moins de deux pools configurés. Fatal error cache not present, or only cache present, and less than 2 pools set up=Erreur fatale : cache absent, ou uniquement cache présent, et moins de deux pools configurés. @@ -75,7 +74,6 @@ If you want Mover Tuning to fully manage scheduling, disable it in Mover Setting Ignore All hidden files and directories=Ignorer tous les fichiers et dossiers cachés Ignore files and folders listed inside of a text file=Ignorer les fichiers et dossiers listés dans un fichier texte Ignore file types=Ignorer les types de fichiers -Invalid characters to block=Caractères invalides à bloquer Largest first=Les plus gros d’abord Let scheduled mover run during a parity check rebuild=Autoriser le mover programmé pendant une vérification/réparation de parité Log files=Fichiers journaux @@ -84,6 +82,7 @@ Logs parent folder for Mover Tuning plugin=Dossier parent des journaux du plugin Low=Faible Maintainers=Mainteneurs make those plugins with ❤️ and a lot of ☕=créent ces plugins avec ❤️ et beaucoup de ☕ +mounted read-only at %s stop writes to the share, umount %s, move anything in %s aside, zfs mount %s, then move it back into %s without replacing a file already there keep both copies and compare them=monté en lecture seule sur %s : arrêtez les écritures sur le partage, lancez umount %s, mettez de côté tout ce qui est dans %s, lancez zfs mount %s, puis remettez le tout dans %s sans remplacer un fichier déjà présent : gardez les deux copies et comparez-les Move ALL files from current pool ignores filters and thresholds=Déplacer **TOUS** les fichiers du pool actuel (en ignorant les filtres et les seuils) Move ALL files to current pool ignores filters and thresholds=Déplacer **TOUS** les fichiers vers le pool actuel (en ignorant les filtres et les seuils) Move All from Primary->Secondary cacheyes shares pool percentage=Déplacer tout depuis Primaire→Secondaire (cache:yes) selon le pourcentage du pool @@ -125,7 +124,9 @@ Mover Tuning thresholds=Seuils Mover Tuning No files were movedsynced by Mover Tuning plugin Elapsed time %s=Aucun fichier n’a été déplacé/synchronisé par le plugin Mover Tuning. Temps écoulé : %s No log files yet=Aucun fichier journal pour le moment Not Applicable Share Does Not Exist Yet=Non applicable (la part n’existe pas encore) +Not a valid cron schedule it is not applied=Planification cron invalide : elle n’est pas appliquée. Notify Mover Tuning plugin actions=Notifier les actions du plugin Mover Tuning +not mounted stop writes to the share, move anything in %s aside, zfs mount %s, then move it back into %s without replacing a file already there keep both copies and compare them=non monté : arrêtez les écritures sur le partage, mettez de côté tout ce qui est dans %s, lancez zfs mount %s, puis remettez le tout dans %s sans remplacer un fichier déjà présent : gardez les deux copies et comparez-les Oldest first=Les plus anciens d’abord Only move files larger than this in MB=Déplacer uniquement les fichiers plus grands que cette taille (en Mo) Only move files that are older than this in days=Déplacer uniquement les fichiers plus anciens que ce nombre de jours @@ -181,7 +182,6 @@ Use CTIME change time=Utiliser CTIME (date de changement d’état) Use global=Réglage global Used IDE=IDE utilisé User shares not enabled=Les parts utilisateur ne sont pas activées ! -Validate input filenames to prevent attacks=Valider les noms de fichiers pour prévenir les attaques Very Low=Très faible View=Afficher Want to support the developer and say Thank You=Vous souhaitez soutenir le développeur et dire **Merci** ? @@ -237,6 +237,8 @@ Youre welcome 😊 Thanks for using=Avec plaisir 😊 Merci pour votre utilisati > Exécute le calendrier age_mover du plugin Mover Tuning en utilisant votre entrée cron personnalisée (inclut tous les filtres du plugin). > > Exemple d’entrée Cron : 0 */4 * * *.  Pour exécuter toutes les 4 heures.  Qu’est‑ce que Cron +> +> La planification doit être une entrée cron valide : une entrée invalide n’est pas appliquée, et l’erreur est écrite dans le syslog. :end :mover_tune_testmode_plug: @@ -244,30 +246,6 @@ Youre welcome 😊 Thanks for using=Avec plaisir 😊 Merci pour votre utilisati

Attention — le mode test n’arrête pas le mover original : il s’exécute quand même selon l’horaire de l’option Forcer le déplacement de tous les fichiers selon un horaire, et depuis le bouton « Déplacer maintenant » si l’option Le bouton « Déplacer maintenant » suit les filtres du plugin est réglée sur Non. À partir d’Unraid 7.2.1, la planification du mover et les boutons de déplacement d’Unraid lancent toujours le mover original.

:end -:mover_tune_validate_plug: -

En cybersécurité, les noms de fichiers peuvent être un vecteur critique d’attaques et de vulnérabilités. Des noms non vérifiés peuvent compromettre l’intégrité et la sécurité du système.

-

La validation des noms de fichiers vérifie chaque nom avant qu’il ne soit traité par le mover. Cela garantit que seuls des noms valides sont acceptés, réduisant les risques d’attaques.

-

Désactivez cette option uniquement si vous avez beaucoup de fichiers à déplacer et que vous êtes certain que tous les noms sont valides et sans risque.

-

1. Longueur du nom — si le nom dépasse 255 caractères, il est rejeté.

-

2. Caractères invalides — le nom ne doit pas contenir des caractères interdits tels que ($), (/), (<), (>), (:), ("), (|), (?), (*).

-

3. Éviter la traversée de répertoires — le nom ne doit pas contenir (../).

-

Si une vérification échoue, le nom est rejeté.

-:end - -:mover_tune_invalidfilechars_plug: -

Caractères invalides dans un nom de fichier : - $ - / - < - > - : - " - | - ? - *. -

-:end - :mover_tune_logging_plug:

Active ou désactive la journalisation du plugin.

Fichier (et Syslog) enregistre dans le SYSLOG et dans le fichier journal.

@@ -471,11 +449,11 @@ Youre welcome 😊 Thanks for using=Avec plaisir 😊 Merci pour votre utilisati :mover_tune_cleanfolders_plug:

Oui — supprime le dossier parent des fichiers déplacés.

-

Dossier principal — supprime le dossier de la part et tous les sous‑dossiers vides.

+

Dossier principal — comme Oui, et supprime aussi le dossier de premier niveau de la part, là d’où les fichiers ont été déplacés, une fois vide, sauf s’il s’agit d’un dataset ZFS (voir Nettoyer les datasets ZFS vides).

:end :mover_tune_cleandatasets_plug: -> Démonte et détruit le dataset ZFS parent si aucun dataset enfant n’existe. Fonctionne uniquement si Nettoyer les dossiers vides est réglé sur Oui ou Dossier principal. +> Démonte et détruit le dataset ZFS de la part sur le stockage primaire après le déplacement de ses fichiers, uniquement s’il n’a ni dataset enfant ni snapshot et si chaque élément restant est un dossier qui existe aussi sur le stockage secondaire. Les réglages ZFS propres au dataset, comme la compression ou le quota, disparaissent avec lui. Fonctionne uniquement si Nettoyer les dossiers vides est réglé sur Oui ou Dossier principal. :end :mover_tune_sharecalculation_plug: diff --git a/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/languages/ru_RU.txt b/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/languages/ru_RU.txt index c68ce129..cbfada34 100644 --- a/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/languages/ru_RU.txt +++ b/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/languages/ru_RU.txt @@ -8,6 +8,9 @@ %s files and %s folders representing %s could not be movedsynced by Mover Tuning plugin=Плагину Mover Tuning не удалось переместить/синхронизировать %s файлов и %s папок общим объёмом %s. Action=Действие +a file is hidden under it stop writes to the share, zfs unmount %s, move anything in %s aside, zfs mount %s, then move it back into %s without replacing a file already there keep both copies and compare them=под ним скрыт файл: остановите запись в общий ресурс, выполните zfs unmount %s, переместите всё из %s в другое место, выполните zfs mount %s, затем верните всё обратно в %s, не заменяя уже имеющийся там файл: сохраните обе копии и сравните их +mounted again, but the look for a file written to %s as it was mounted was cut short, so one may be hidden under it stop writes to the share, zfs unmount %s, move anything in %s aside, zfs mount %s, then move it back into %s without replacing a file already there keep both copies and compare them=снова смонтирован, но поиск файла, записанного в %s во время монтирования, был прерван, под ним может быть скрыт файл: остановите запись в общий ресурс, выполните zfs unmount %s, переместите всё из %s в другое место, выполните zfs mount %s, затем верните всё обратно в %s, не заменяя уже имеющийся там файл: сохраните обе копии и сравните их +the remount was cut short, so it may not be mounted or may hide a file stop writes to the share, if zfs mount lists it at %s run zfs unmount %s, move anything in %s aside, zfs mount %s, then move it back into %s without replacing a file already there keep both copies and compare them=повторное монтирование прервано, поэтому он может быть не смонтирован или скрывать файл: остановите запись в общий ресурс, если zfs mount показывает его в %s, выполните zfs unmount %s, переместите всё из %s в другое место, выполните zfs mount %s, затем верните всё обратно в %s, не заменяя уже имеющийся там файл: сохраните обе копии и сравните их All community developers=Все разработчики сообщества %s files and %s folders were movedsynced, but rsync reported errors for them Check the Mover Tuning log=%s файлов и %s папок были перемещены/синхронизированы, но rsync сообщил об ошибках при их обработке. Проверьте журнал Mover Tuning. Allow force mover schedule to run during a parity checkrebuild=Разрешить запуск расписания принудительного перемещения во время проверки/восстановления четности @@ -25,6 +28,7 @@ Cache → Array=Кэш → Массив Cancel=Отмена Clean empty folders=Очистить пустые папки Clean empty ZFS datasets=Очистить пустые ZFS‑датасеты +Clean empty ZFS datasets did not finish for %s The mover log has the details unless Log Mover Tuning plugin actions is set to No=Очистка пустых ZFS‑датасетов не завершена для %s. Подробности в журнале, если «Журналировать действия плагина Mover Tuning» не установлено в Нет. CLI help commands=Команды помощи CLI Comma separated list of file types=Список типов файлов через запятую Cron Schedule to force move all of files=Расписание Cron для принудительного перемещения всех файлов @@ -36,22 +40,17 @@ Delete Mover Log files over than this days old=Удалять лог‑файл Disable Mover running on a schedule=Отключить запуск Mover по расписанию disables test mode=отключает тестовый режим disables the plugins schedule=отключает расписание плагина -disables validation of input filenames=отключает проверку имён входных файлов Download=Скачать enable smart caching=включить умное кэширование Error checking mover status Please refresh the page=Ошибка проверки статуса mover. Обновите страницу. Error Config file %s not found=Ошибка: файл конфигурации '%s' не найден. Error Failed to convert CRLF line endings in %s Check file permissions=Ошибка: не удалось преобразовать окончания строк CRLF в %s. Проверьте права доступа к файлу. -Error Invalid filename path %s Please either change the filename to valid or disable the Validate input filenames option=Ошибка: недопустимый путь имени файла: %s. Измените имя файла или отключите параметр «Проверять имена входных файлов». Error No files found to move for %s=Ошибка: не найдено файлов для перемещения для %s Errors Only=Только ошибки Estimated Completion=Ожидаемое завершение ETA=Осталось -Failed to destroy ZFS dataset %s — attempting to remount=Не удалось уничтожить ZFS‑датасет [%s] — выполняется попытка перемонтирования. -Failed to remount dataset %s=Не удалось перемонтировать датасет [%s] Failed to reset Mover Tuning Check the logs=Не удалось сбросить Mover Tuning. Проверьте журналы. Failed to start Mover Tuning Check the logs=Не удалось запустить Mover Tuning. Проверьте журналы. -Failed to unmount ZFS dataset %s=Не удалось размонтировать ZFS‑датасет [%s] Fatal error %s does not exist, check this=Критическая ошибка: %s не существует, проверьте это. Fatal error cache not enabled and less than 2 pools set up=Критическая ошибка: кэш-пул не включён и настроено менее двух пулов. Fatal error cache not present, or only cache present, and less than 2 pools set up=Критическая ошибка: кэш-пул отсутствует или присутствует только кэш-пул, и настроено менее двух пулов. @@ -75,7 +74,6 @@ If you want Mover Tuning to fully manage scheduling, disable it in Mover Setting Ignore All hidden files and directories=Игнорировать все скрытые файлы и каталоги Ignore files and folders listed inside of a text file=Игнорировать файлы и каталоги, перечисленные в текстовом файле Ignore file types=Игнорировать типы файлов -Invalid characters to block=Недопустимые символы для блокировки Largest first=Сначала самые большие Let scheduled mover run during a parity check rebuild=Разрешить запуск Mover по расписанию во время проверки/восстановления паритета Log files=Файлы журнала @@ -84,6 +82,7 @@ Logs parent folder for Mover Tuning plugin=Родительская папка Low=Низкий Maintainers=Сопровождающие make those plugins with ❤️ and a lot of ☕=создаём эти плагины с ❤️ (и большим количеством ☕). +mounted read-only at %s stop writes to the share, umount %s, move anything in %s aside, zfs mount %s, then move it back into %s without replacing a file already there keep both copies and compare them=смонтирован только для чтения в %s: остановите запись в общий ресурс, выполните umount %s, переместите всё из %s в другое место, выполните zfs mount %s, затем верните всё обратно в %s, не заменяя уже имеющийся там файл: сохраните обе копии и сравните их Move ALL files from current pool ignores filters and thresholds=Переместить **ВСЕ** файлы из текущего пула (независимо от фильтров и порогов) Move ALL files to current pool ignores filters and thresholds=Переместить **ВСЕ** файлы в текущий пул (независимо от фильтров и порогов) Move All from Primary->Secondary cacheyes shares pool percentage=Переместить всё из Основного->Вторичного (cache:yes) — процент заполнения пула шар @@ -125,7 +124,9 @@ Mover Tuning thresholds=Пороги Mover Tuning No files were movedsynced by Mover Tuning plugin Elapsed time %s=Файлы не были перемещены/синхронизированы плагином Mover Tuning. Затраченное время: %s No log files yet=Файлов журнала пока нет Not Applicable Share Does Not Exist Yet=Не применимо (шара ещё не существует) +Not a valid cron schedule it is not applied=Некорректное расписание cron: оно не применяется. Notify Mover Tuning plugin actions=Уведомлять о действиях плагина Mover Tuning +not mounted stop writes to the share, move anything in %s aside, zfs mount %s, then move it back into %s without replacing a file already there keep both copies and compare them=не смонтирован: остановите запись в общий ресурс, переместите всё из %s в другое место, выполните zfs mount %s, затем верните всё обратно в %s, не заменяя уже имеющийся там файл: сохраните обе копии и сравните их Oldest first=Сначала самые старые Only move files larger than this in MB=Перемещать только файлы больше указанного размера (в МБ) Only move files that are older than this in days=Перемещать только файлы старше указанного количества дней @@ -181,7 +182,6 @@ Use CTIME change time=Использовать CTIME (время изменен Use global=Глобальная настройка Used IDE=Используемый IDE User shares not enabled=Пользовательские шары не включены! -Validate input filenames to prevent attacks=Проверять имена файлов для предотвращения атак Very Low=Очень низкий View=Просмотр Want to support the developer and say Thank You=Хотите поддержать разработчика и сказать **Спасибо**? @@ -236,6 +236,8 @@ Youre welcome 😊 Thanks for using=Пожалуйста! 😊 Спасибо, > Запускает расписание age_mover плагина Mover Tuning с использованием вашей пользовательской записи cron (включает все фильтры плагина). > > Пример записи расписания Cron: 0 */4 * * *.  Для запуска каждые 4 часа.  Что такое Cron +> +> Расписание должно быть корректной записью cron: некорректное не применяется, а ошибка записывается в syslog. :end :mover_tune_testmode_plug: @@ -243,31 +245,6 @@ Youre welcome 😊 Thanks for using=Пожалуйста! 😊 Спасибо,

Внимание — тестовый режим не останавливает оригинальный Mover: он всё равно запускается по расписанию параметра Принудительно перемещать все файлы по расписанию, а также кнопкой «Переместить сейчас», если параметр Кнопка «Переместить сейчас» учитывает фильтры плагина установлен в Нет. Начиная с Unraid 7.2.1, собственное расписание Mover и кнопки перемещения Unraid всегда запускают оригинальный Mover.

:end -:mover_tune_validate_plug: -

В сфере кибербезопасности имена файлов могут являться критическим вектором для потенциальных атак и уязвимостей системы. Несанитизированные имена файлов создают значительные риски, способные нарушить целостность и безопасность системы.

-

Проверка имён входных файлов проверяет каждое имя файла перед его обработкой Mover'ом. Это гарантирует, что принимаются только допустимые имена файлов, снижая риск атак и уязвимостей.

-

Отключайте только если у вас много файлов для перемещения и вы уверены, что все имена файлов допустимы и не содержат потенциальных угроз безопасности.

-

1. Проверка длины имени файла — если имя файла превышает 255 символов, оно будет отклонено.

-

2. Проверка недопустимых символов — имя файла не должно содержать символы, считающиеся недопустимыми для имён файлов, такие как -( $ ), ( / ), ( < ), ( > ), ( : ), ( " ), ( | ), ( ? ), ( * ).

-

3. Предотвращение обхода пути — имя файла не должно содержать символы, которые могут использоваться для обхода каталогов, такие как ( ../ ).

-

Если одна из этих проверок не пройдена, имя файла будет отклонено.

-:end - -:mover_tune_invalidfilechars_plug: -

Символы имени файла, такие как: - $ - / - < - > - : - " - | - ? - *. -

-:end - :mover_tune_logging_plug:

Включает или отключает журналирование этого плагина.

Файл (и Syslog) сохраняет записи в SYSLOG и в файл журнала.

@@ -462,11 +439,11 @@ Youre welcome 😊 Thanks for using=Пожалуйста! 😊 Спасибо, :mover_tune_cleanfolders_plug:

Да — удаляет родительскую папку только для перемещённых файлов.

-

Верхняя папка — удаляет папку верхнего уровня шары перемещённого содержимого, включая все пустые вложенные папки на основном хранилище.

+

Верхняя папка — как Да, а также удаляет папку верхнего уровня шары там, откуда перемещены файлы, когда она пуста, если только это не ZFS-датасет (см. Очистить пустые ZFS‑датасеты).

:end :mover_tune_cleandatasets_plug: -> Это размонтирует и уничтожит родительский ZFS-датасет на шаре перемещённых файлов, только если он не содержит дочерних датасетов. Работает, только если параметр Очистить пустые папки установлен в Да или Верхняя папка. +> Это размонтирует и уничтожит ZFS-датасет шары на основном хранилище после перемещения её файлов, только если у него нет дочерних датасетов или снапшотов и всё оставшееся в нём — папки, которые есть и на вторичном хранилище. Собственные настройки ZFS датасета, например сжатие или квота, удаляются вместе с ним. Работает, только если параметр Очистить пустые папки установлен в Да или Верхняя папка. :end :mover_tune_sharecalculation_plug: diff --git a/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/languages/zh_CN.txt b/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/languages/zh_CN.txt index 13860bf7..36a2127b 100644 --- a/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/languages/zh_CN.txt +++ b/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/languages/zh_CN.txt @@ -8,6 +8,9 @@ %s files and %s folders representing %s could not be movedsynced by Mover Tuning plugin=Mover Tuning 插件未能移动/同步 %s 个文件和 %s 个文件夹,共 %s。 %s files and %s folders were movedsynced, but rsync reported errors for them Check the Mover Tuning log=%s 个文件和 %s 个文件夹已移动/同步,但 rsync 报告了错误。请查看 Mover Tuning 日志。 Action=操作 +a file is hidden under it stop writes to the share, zfs unmount %s, move anything in %s aside, zfs mount %s, then move it back into %s without replacing a file already there keep both copies and compare them=其下有文件被遮盖:停止向该共享写入,运行 zfs unmount %s,将 %s 中的所有内容移到别处,运行 zfs mount %s,然后移回 %s,不要覆盖其中已有的文件:保留两份副本并加以比较 +mounted again, but the look for a file written to %s as it was mounted was cut short, so one may be hidden under it stop writes to the share, zfs unmount %s, move anything in %s aside, zfs mount %s, then move it back into %s without replacing a file already there keep both copies and compare them=已重新挂载,但对挂载期间写入 %s 的文件的检查被中断,其下可能有文件被遮盖:停止向该共享写入,运行 zfs unmount %s,将 %s 中的所有内容移到别处,运行 zfs mount %s,然后移回 %s,不要覆盖其中已有的文件:保留两份副本并加以比较 +the remount was cut short, so it may not be mounted or may hide a file stop writes to the share, if zfs mount lists it at %s run zfs unmount %s, move anything in %s aside, zfs mount %s, then move it back into %s without replacing a file already there keep both copies and compare them=重新挂载被中断,因此它可能未挂载,或其下有文件被遮盖:停止向该共享写入,如果 zfs mount 列出它挂载在 %s,运行 zfs unmount %s,将 %s 中的所有内容移到别处,运行 zfs mount %s,然后移回 %s,不要覆盖其中已有的文件:保留两份副本并加以比较 All community developers=所有社区开发者 Allow force mover schedule to run during a parity checkrebuild=允许强制移动计划在奇偶校验/重建期间运行 All plugin settings return to their defaults, including the Mover Tuning schedule, the forced move schedule and the cache watchdog, and the override settings of every share are deleted=所有插件设置都将恢复为默认值,包括 Mover Tuning 计划、强制移动计划和缓存看门狗,并且所有共享的覆盖设置都将被删除。 @@ -24,6 +27,7 @@ Cache → Array=缓存 → 阵列 Cancel=取消 Clean empty folders=清理空文件夹 Clean empty ZFS datasets=清理空的 ZFS 数据集 +Clean empty ZFS datasets did not finish for %s The mover log has the details unless Log Mover Tuning plugin actions is set to No=清理空的 ZFS 数据集未能完成:%s。详情见日志,除非“记录 Mover Tuning 插件日志”设为“否”。 CLI help commands=命令行帮助 Comma separated list of file types=以逗号分隔的文件扩展名列表 Cron Schedule to force move all of files=强制移动所有文件的 Cron 计划 @@ -35,22 +39,17 @@ Delete Mover Log files over than this days old=日志文件保留天数 Disable Mover running on a schedule=禁用 Mover 按计划运行 disables test mode=禁用测试模式 disables the plugins schedule=禁用插件的计划 -disables validation of input filenames=禁用文件名验证 Download=下载 enable smart caching=启用智能缓存 Error checking mover status Please refresh the page=检查 Mover 状态时出错,请刷新页面。 Error Config file %s not found=错误:找不到配置文件“%s”。 Error Failed to convert CRLF line endings in %s Check file permissions=错误:无法转换 %s 中的 CRLF 换行符,请检查文件权限。 -Error Invalid filename path %s Please either change the filename to valid or disable the Validate input filenames option=错误:文件名路径无效:%s。请修改为有效的文件名,或禁用“验证文件名防止攻击”选项。 Error No files found to move for %s=错误:未找到 %s 中需要移动的文件 Errors Only=仅错误 Estimated Completion=预计完成 ETA=剩余时间 -Failed to destroy ZFS dataset %s — attempting to remount=销毁 ZFS 数据集 [%s] 失败,正在尝试重新挂载。 -Failed to remount dataset %s=重新挂载数据集 [%s] 失败 Failed to reset Mover Tuning Check the logs=重置 Mover Tuning 失败,请查看日志。 Failed to start Mover Tuning Check the logs=启动 Mover Tuning 失败,请查看日志。 -Failed to unmount ZFS dataset %s=卸载 ZFS 数据集 [%s] 失败 Fatal error %s does not exist, check this=严重错误:%s 不存在,请检查。 Fatal error cache not enabled and less than 2 pools set up=严重错误:未启用缓存,且设置的存储池少于 2 个。 Fatal error cache not present, or only cache present, and less than 2 pools set up=严重错误:缓存不存在或只有缓存,且设置的存储池少于 2 个。 @@ -74,7 +73,6 @@ If you want Mover Tuning to fully manage scheduling, disable it in Mover Setting Ignore All hidden files and directories=忽略隐藏文件和目录 Ignore files and folders listed inside of a text file=忽略列表中的文件和文件夹 Ignore file types=忽略指定文件类型 -Invalid characters to block=要阻止的无效字符 Largest first=最大的优先 Let scheduled mover run during a parity check rebuild=允许计划的 Mover 在奇偶校验/重建期间运行 Log files=日志文件 @@ -83,6 +81,7 @@ Logs parent folder for Mover Tuning plugin=日志文件保存路径 Low=低 Maintainers=维护者 make those plugins with ❤️ and a lot of ☕=用 ❤️(和很多 ☕)制作了这些插件。 +mounted read-only at %s stop writes to the share, umount %s, move anything in %s aside, zfs mount %s, then move it back into %s without replacing a file already there keep both copies and compare them=以只读方式挂载于 %s:停止向该共享写入,运行 umount %s,将 %s 中的所有内容移到别处,运行 zfs mount %s,然后移回 %s,不要覆盖其中已有的文件:保留两份副本并加以比较 Move ALL files from current pool ignores filters and thresholds=从当前存储池移出**所有**文件(无视过滤条件和阈值) Move ALL files to current pool ignores filters and thresholds=将**所有**文件移入当前存储池(无视过滤条件和阈值) Move All from Primary->Secondary cacheyes shares pool percentage=主存储->次存储(cache:yes)共享全部移动的存储池百分比 @@ -124,7 +123,9 @@ Mover Tuning thresholds=Mover Tuning 阈值 No files were movedsynced by Mover Tuning plugin Elapsed time %s=Mover Tuning 插件没有移动/同步任何文件。耗时:%s No log files yet=暂无日志文件 Not Applicable Share Does Not Exist Yet=不适用(共享尚不存在) +Not a valid cron schedule it is not applied=无效的 cron 计划:不会生效。 Notify Mover Tuning plugin actions=通知设置 +not mounted stop writes to the share, move anything in %s aside, zfs mount %s, then move it back into %s without replacing a file already there keep both copies and compare them=未挂载:停止向该共享写入,将 %s 中的所有内容移到别处,运行 zfs mount %s,然后移回 %s,不要覆盖其中已有的文件:保留两份副本并加以比较 Oldest first=最旧的优先 Only move files larger than this in MB=仅移动大于此大小的文件(MB) Only move files that are older than this in days=仅移动早于此天数的文件(天) @@ -180,7 +181,6 @@ Use CTIME change time=使用状态更改时间(CTIME) Use global=使用全局设置 Used IDE=开发工具 User shares not enabled=用户共享未启用 -Validate input filenames to prevent attacks=验证文件名防止攻击 Very Low=很低 View=查看 Want to support the developer and say Thank You=想支持开发者并说声**谢谢**吗? @@ -236,6 +236,8 @@ Youre welcome 😊 Thanks for using=不客气!😊 感谢使用! > 使用自定义 cron 条目运行 Mover Tuning 插件的 age_mover 计划(应用所有插件过滤器)。 > > Cron 计划示例 0 */4 * * *。  表示每 4 小时运行一次。  什么是 Cron +> +> 计划必须是有效的 cron 条目:无效的计划不会生效,错误会写入系统日志。 :end :mover_tune_testmode_plug: @@ -243,31 +245,6 @@ Youre welcome 😊 Thanks for using=不客气!😊 感谢使用!

注意 - 测试模式不会阻止原始 Mover:它仍会按“定时强制移动所有文件”的计划运行;如果“立即移动按钮遵循过滤器”设为否,立即移动按钮也会运行原始 Mover。在 Unraid 7.2.1 及更高版本中,Unraid 自带的 Mover 计划和移动按钮始终运行原始 Mover。

:end -:mover_tune_validate_plug: -

在网络安全中,文件名可能成为潜在攻击和系统漏洞的重要途径。未经清理的文件名会带来重大风险,可能危及系统的完整性和安全性。

-

验证文件名会在 Mover 处理每个文件名之前进行检查,确保只接受有效的文件名,降低攻击和漏洞的风险。

-

仅当需要移动大量文件,并且确定所有文件名都有效、不含任何潜在安全风险时,才禁用此选项。

-

1. 检查文件名长度 - 文件名超过 255 个字符将被拒绝。

-

2. 检查无效字符 - 文件名不应包含任何被视为无效的字符,例如 -( $ ), ( / ), ( < ), ( > ), ( : ), ( " ), ( | ), ( ? ), ( * )。

-

3. 防止路径遍历 - 文件名不应包含可用于遍历目录的字符,例如 ( ../ )。

-

只要有一项检查失败,该文件名就会被拒绝。

-:end - -:mover_tune_invalidfilechars_plug: -

文件名中的以下字符: - $ - / - < - > - : - " - | - ? - *。 -

-:end - :mover_tune_logging_plug:

启用或禁用本插件的日志记录。

文件(及系统日志)将同时记录到系统日志和日志文件。

@@ -462,11 +439,11 @@ Youre welcome 😊 Thanks for using=不客气!😊 感谢使用! :mover_tune_cleanfolders_plug:

是 - 仅删除已移动文件的父文件夹。

-

顶层文件夹 - 删除已移动内容的顶层共享文件夹,包括主存储上的所有空子文件夹。

+

顶层文件夹 - 与是相同,并在文件移出位置的顶层共享文件夹变空后将其删除,除非它是 ZFS 数据集(见清理空的 ZFS 数据集)。

:end :mover_tune_cleandatasets_plug: -> 移动文件后卸载并销毁空的父 ZFS 数据集,仅在不包含子数据集时执行。仅在清理空文件夹设为是或顶层文件夹时生效。 +> 移动文件后卸载并销毁主存储上该共享的 ZFS 数据集,仅在其没有子数据集或快照、且剩下的每一项都是次存储上也存在的文件夹时执行。数据集自身的 ZFS 设置(如压缩或配额)会随之删除。仅在清理空文件夹设为是或顶层文件夹时生效。 :end :mover_tune_sharecalculation_plug: diff --git a/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/share_mover b/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/share_mover index 2822be66..d584cabb 100755 --- a/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/share_mover +++ b/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/share_mover @@ -27,8 +27,9 @@ function titleLine() { local line_length=71 local padding_left=$((line_length - ${#title} / 2)) local padding_right=$((padding_left - ${#title} % 2 - 1)) - local left_padding=$(printf "%*s" "$padding_left" | tr ' ' "$padding_char") - local right_padding=$(printf "%*s" "$padding_right" | tr ' ' "$padding_char") + local left_padding right_padding + left_padding=$(printf "%*s" "$padding_left" "" | tr ' ' "$padding_char") + right_padding=$(printf "%*s" "$padding_right" "" | tr ' ' "$padding_char") echo "${left_padding}$padding_char $title $padding_char${right_padding}" } @@ -55,8 +56,6 @@ getMoverSettings() { echo "$1=\"$2\"" >>"$config_file" } - timezone=$(grep "timeZone=" "/boot/config/ident.cfg" | cut -d '"' -f 2) - if [[ ! -f "$config_file" ]]; then mvlogger "Error: Config file '$config_file' not found." return 1 @@ -64,7 +63,7 @@ getMoverSettings() { ## [[ ! "$config_file" =~ shareOverrideConfig ]] ensure that we are not reading share custom settings - if [ -z $(cfg enableTurbo) ]; then + if [ -z "$(cfg enableTurbo)" ]; then if [[ ! "$config_file" =~ shareOverrideConfig ]]; then mvlogger "No Turbo Mode argument provided, defaulting to no" ENABLETURBO="no" @@ -72,10 +71,10 @@ getMoverSettings() { fi else ENABLETURBO=$(cfg enableTurbo) - [ $ENABLETURBO = "yes" ] && mvlogger "Enable Turbo: $ENABLETURBO" + [ "$ENABLETURBO" = "yes" ] && mvlogger "Enable Turbo: $ENABLETURBO" fi - if [ -z $(cfg testmode) ]; then + if [ -z "$(cfg testmode)" ]; then if [[ ! "$config_file" =~ shareOverrideConfig ]]; then mvlogger "No Test Mode argument provided, defaulting to yes" # yes for this run only: written to the global cfg it would put the scheduled mover in test mode too @@ -83,7 +82,7 @@ getMoverSettings() { fi else TESTMODE=$(cfg testmode) - [ $TESTMODE = "yes" ] && mvlogger "Test Mode: $TESTMODE" + [ "$TESTMODE" = "yes" ] && mvlogger "Test Mode: $TESTMODE" fi } @@ -99,7 +98,7 @@ if [ -f $UNRAIDCFGFILE ]; then fi fi -mvlogger "$(titleLine "Mover Tuning Plugin version $(grep "version=" "$MOVERTUNINGCFGFILE" | cut -d '"' -f 2)" '*')" +[ ! -f "$MOVERTUNINGCFGFILE" ] || mvlogger "$(titleLine "Mover Tuning Plugin version $(grep "version=" "$MOVERTUNINGCFGFILE" | cut -d '"' -f 2)" '*')" #Test input variables if [ -z "$1" ]; then @@ -110,11 +109,11 @@ else SHARECFG="/boot/config/shares/${SHARENAME}.cfg" fi -if [ -f $PIDFILE ]; then - if ps h $(cat $PIDFILE) | grep mover; then - mvlogger "already running" - exit 1 - fi +pid=$(head -n 1 "$PIDFILE" 2>/dev/null | tr -cd '0-9') +# shellcheck disable=SC2009 # pgrep -f would match any mover, not only this pid +if [ -n "$pid" ] && ps h "$pid" | grep -q mover; then + mvlogger "already running" + exit 1 fi # Only start if config OK @@ -124,7 +123,6 @@ if [ -f $UNRAIDCFGFILE ]; then fi else mvlogger "Fatal error: $UNRAIDCFGFILE does not exist, check this." - rm $SOFTSTOPFILE exit 2 fi if [ -f $MOVERTUNINGCFGFILE ]; then @@ -133,30 +131,83 @@ if [ -f $MOVERTUNINGCFGFILE ]; then getMoverSettings $MOVERTUNINGCFGFILE else mvlogger "Fatal error: $MOVERTUNINGCFGFILE does not exist, check this." - rm $SOFTSTOPFILE exit 3 fi +shopt -s nullglob +POOLCFGS=(/boot/config/pools/*.cfg) # Only start if cache enabled and present -if ! grep -qs 'shareCacheEnabled="yes"' $UNRAIDCFGFILE && [ $(ls /boot/config/pools/*.cfg | wc -l) -lt 2 ]; then +if ! grep -qs 'shareCacheEnabled="yes"' $UNRAIDCFGFILE && [ ${#POOLCFGS[@]} -lt 2 ]; then mvlogger "Fatal error: cache not enabled and less than 2 pools set up." exit 4 fi -if ! mountpoint -q /mnt/user0 && [ $(ls /boot/config/pools/*.cfg | wc -l) -lt 2 ]; then +if ! mountpoint -q /mnt/user0 && [ ${#POOLCFGS[@]} -lt 2 ]; then mvlogger "Fatal error: cache not present, or only cache present, and less than 2 pools set up." exit 5 fi # Remove the pid file only while it still names this run, so overlapping runs cannot delete each other's +# shellcheck disable=SC2329 # the EXIT traps call it pid_cleanup() { [ "$(cat "$PIDFILE" 2>/dev/null)" = "$$" ] && rm -f "$PIDFILE" } + +# Prints the write method var.ini gives when it is one mdcmd can set back: 0, 1 or auto, as mover.php checks +write_method() { + local m + m=$(grep -s '^md_write_method=' /var/local/emhttp/var.ini | cut -d'"' -f2) + case $m in 0 | 1 | auto) echo "$m" ;; *) return 1 ;; esac +} + +# With Turbo Mode on, forces turbo write for the moves, only when the write method can be set back after +force_turbo() { + TURBO_WAS="" + [ "$ENABLETURBO" = "yes" ] || return 0 + if ! TURBO_WAS=$(write_method); then + mvlogger "Not forcing turbo write on: /var/local/emhttp/var.ini gives no write method (0, 1 or auto) to set back after" + return 0 + fi + if [ "$TESTMODE" = "yes" ]; then + mvlogger "TEST MODE: Would force turbo write on" + return 0 + fi + # set first: a stop that ends the run from here on tries once to put the write method back before the pid file goes, + # and a second stop waits for that try; a KILL cannot + trap 'trap "" HUP INT TERM; restore_turbo; pid_cleanup' EXIT + mvlogger "Forcing turbo write on" + /usr/local/sbin/mdcmd set md_write_method 1 || mvlogger "Could not force turbo write on: mdcmd exited $?" +} + +# Sets the write method back after force_turbo, where the moves end or from the EXIT trap of a run a signal ends sooner; +# the EXIT trap goes back to pid_cleanup alone, in a real run only once mdcmd has set it back +restore_turbo() { + local m name + [ -n "$TURBO_WAS" ] || return 0 + # var.ini's now, which Settings may have changed during the moves; the one read before when it gives none + m=$(write_method) || m=$TURBO_WAS + case $m in + auto) name="Auto (read/modify/write)" ;; + 1) name="Turbo writes (Reconstruct)" ;; + *) name="Read/modify/write" ;; + esac + if [ "$TESTMODE" = "yes" ]; then + mvlogger "TEST MODE: Would restore original turbo write mode $name" + else + mvlogger "Restoring original turbo write mode $name" + # the plugin's stop signals mdcmd before the run: one it ends first leaves the EXIT trap to try again + /usr/local/sbin/mdcmd set md_write_method "$m" || { + mvlogger "Could not restore original turbo write mode $name: mdcmd exited $?" + return 1 + } + fi + TURBO_WAS="" + trap pid_cleanup EXIT +} + trap pid_cleanup EXIT trap 'exit 143' HUP INT TERM echo $$ >"$PIDFILE" -shopt -s nullglob - mvlogger "$(titleLine "Processing $SHARENAME share" '-')" if grep -qs 'shareUseCache="yes\|shareUseCache="prefer"' "$SHARECFG"; then mvlogger "Sharecfg: $SHARECFG" @@ -180,7 +231,7 @@ if grep -qs 'shareUseCache="yes\|shareUseCache="prefer"' "$SHARECFG"; then # Determine secondary storage SECONDARYSTORAGENAME=$(grep "shareCachePool2=" "$SHARECFG" | cut -d'=' -f 2 | tr -d '"' | tr -d '\r') if [ -z "$SECONDARYSTORAGENAME" ]; then - if [ $SHAREUSECACHE = "only" ] || [ $SHAREUSECACHE = "no" ]; then + if [ "$SHAREUSECACHE" = "only" ] || [ "$SHAREUSECACHE" = "no" ]; then SECONDARYSTORAGENAME="none" else SECONDARYSTORAGENAME="user0" @@ -205,52 +256,51 @@ if grep -qs 'shareUseCache="yes\|shareUseCache="prefer"' "$SHARECFG"; then mvlogger "=> Skipping" else mvlogger "$(titleLine 'LET THE MOVING SHOW BEGIN !' '*')" - if [ $ENABLETURBO = "yes" ]; then - mvlogger "Forcing turbo write on" - [ $TESTMODE != "yes" ] && /usr/local/sbin/mdcmd set md_write_method 1 - fi - #Base Find String - # Alterate SHAREPATH on Cache=prefer + # the share name reaches find only as an argument, never parsed as shell if [ "$SHAREUSECACHE" = "prefer" ]; then - #"cache=prefer" pool, we replace path to list files in /mnt/user and process later - - # Check if SHAREPATH is in the format "/mnt/*/$SHARENAME" - # Initialize FINDSTR with the base find command - FINDSTR="find" - # Iterate over all directories in /mnt/* - for dir in /mnt/*; do - # Check if the directory contains a subdirectory named $SHARENAME and not equal to "/mnt/$PRIMARYSTORAGENAME/$SHARENAME" + # "cache=prefer": the share's folder on each array disk and each other pool, never on a mount such as + # Unassigned Devices' that only shares its name, for the move to the primary + paths=() + for dir in /mnt/disk[0-9] /mnt/disk[1-9][0-9] "${POOLCFGS[@]}"; do + dir=/mnt/${dir##*/} + dir=${dir%.cfg} if [ -d "$dir/$SHARENAME" ] && [ "$dir/$SHARENAME" != "/mnt/$PRIMARYSTORAGENAME/$SHARENAME" ]; then - # Append the path to FINDSTR, ensuring it's quoted and separated by spaces - FINDSTR+=" \"$dir/$SHARENAME\"" + paths+=("$dir/$SHARENAME") fi done - # Add the depth option at the end - FINDSTR+=" -type f -not -path '/mnt/user*' -depth" else - # Alterate SHAREPATH on Cache=yes - FINDSTR="find \"${SHAREPATH}\" -type f -depth" + paths=("$SHAREPATH") fi - - if [ "$TESTMODE" = "yes" ]; then + FINDSTR="find" + for p in "${paths[@]}"; do FINDSTR+=" $(qp "$p")"; done + FINDSTR+=" -type f -depth" + + # find given no folder would list the one it runs in + if [ ${#paths[@]} -eq 0 ]; then + mvlogger "No array disk or other pool holds a folder of the share: nothing to move" + mvlogger "=> Skipping" + elif [ "$TESTMODE" = "yes" ]; then + force_turbo mvlogger "Running in Test Mode: $FINDSTR" - eval "${FINDSTR}" + find "${paths[@]}" -type f -depth + restore_turbo else - #Add Mover to find string - FINDSTR="${FINDSTR} | $([ -f /usr/libexec/unraid/move ] && echo /usr/libexec/unraid/move || which move) -d $LOGLEVEL" - mvlogger "Complete Mover Command: $FINDSTR" - eval " ${FINDSTR}" - fi - - if [ $ENABLETURBO = "yes" ]; then - turbo_write_mode=$(cat /var/local/emhttp/var.ini | grep "md_write_method=" | cut -d'"' -f2) - mvlogger "Restoring original turbo write mode $( ([ $turbo_write_mode = "auto" ] && echo "Auto (read/modify/write)") || ([ $turbo_write_mode -eq 1 ] && echo "Turbo writes (Reconstruct)") || echo "Read/modify/write")" - [ $TESTMODE != "yes" ] && /usr/local/sbin/mdcmd set md_write_method $turbo_write_mode + MOVE=/usr/libexec/unraid/move + [ -f "$MOVE" ] || MOVE=$(which move) + force_turbo + mvlogger "Complete Mover Command: $FINDSTR | $MOVE -d $LOGLEVEL" + find "${paths[@]}" -type f -depth | "$MOVE" -d "$LOGLEVEL" + st=("${PIPESTATUS[@]}") + restore_turbo + # move's own failure first: find's SIGPIPE follows from it + MOVE_RC=$((st[1] ? st[1] : st[0])) + [ "$MOVE_RC" = 0 ] || mvlogger "Move command failed: find exited ${st[0]}, move exited ${st[1]}" fi fi fi mvlogger "$(titleLine 'WE ARE DONE !' '*')" -[ $LOGLEVEL = 0 ] && echo "Mover tuning plugin done!" +[ "$LOGLEVEL" = 1 ] || echo "Mover tuning plugin done!" +exit "${MOVE_RC:-0}" diff --git a/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/updateCron.php b/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/updateCron.php index 561f559a..e3a8b152 100755 --- a/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/updateCron.php +++ b/source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning/updateCron.php @@ -1,6 +1,7 @@ #!/usr/bin/php $field) { - if (cron_field_ok($field, $limits[$i][0], $limits[$i][1], $limits[$i][2]) === false) { - return false; - } + if (file_put_contents($file, $content) === false) { + logger("Error: Failed to write $file."); + return; } - return true; + logger($done); } -// One cron field: a comma list of * / n / n-m, each with an optional /step; numbers within min..max, names looked up in $names -function cron_field_ok($field, $min, $max, $names) -{ - foreach (explode(',', $field) as $item) { - if (preg_match('/^(\*|([a-z0-9]+)(?:-([a-z0-9]+))?)(?:\/([0-9]+))?\z/i', $item, $m) !== 1) { - return false; - } - if (isset($m[4]) === true && (int)$m[4] < 1) { - return false; - } - if ($m[1] === '*') { - continue; - } - foreach ([$m[2], $m[3] ?? ''] as $value) { - if ($value === '') { - continue; - } - // names count from $min, so jan is 1 and sun is 0 - $index = array_search(strtolower($value), $names, true); - $n = ctype_digit($value) === true ? (int)$value : ($index === false ? -1 : $index + $min); - if ($n < $min || $n > $max) { - return false; - } - } - } - return true; -} - -/** Writes Unraid's mover.cron from the Mover Settings schedule, before Unraid 7.2.1; true when the file was written */ +/** Makes Unraid's mover.cron run the Mover Settings schedule, before Unraid 7.2.1 */ function make_unraid_cron() { global $vars; @@ -107,66 +64,42 @@ function make_unraid_cron() $moverCron = trim($vars['shareMoverSchedule']); if (valid_cron($moverCron) === false) { logger("Error: Invalid Unraid mover schedule: " . preg_replace('/[^[:print:]]/', '?', $moverCron)); - return false; + return; } $cronMoverFile = "# Generated mover schedule:\n" . $moverCron . " /usr/local/sbin/mover start |& logger -t move\n\n"; - if (file_put_contents("/boot/config/plugins/dynamix/mover.cron", $cronMoverFile) === false) { - logger("Error: Failed to write mover.cron file."); - return false; - } - return true; + put_cron_file("/boot/config/plugins/dynamix/mover.cron", $cronMoverFile, "Mover schedule set to $moverCron."); + return; } logger("No mover schedule set in Mover Settings."); - return false; } -/** Writes mover.tuning.cron for the $tuneCron schedule, from Unraid 7.2.1; true when the file was written */ +/** Makes mover.tuning.cron run Mover Tuning on the $tuneCron schedule, from Unraid 7.2.1 */ function make_tune_cron($tuneCron) { - if (empty($tuneCron) === true) { - logger("No cron schedule provided for Mover Tuning move."); - return false; // Nothing to write - } if (valid_cron($tuneCron) === false) { logger("Error: Invalid cron schedule for Mover Tuning move: " . preg_replace('/[^[:print:]]/', '?', $tuneCron)); - return false; + return; } $cronTuneFile = "# Generated schedule for Mover Tuning move:\n" . $tuneCron . " /usr/local/emhttp/plugins/ca.mover.tuning/mover start |& logger -t move\n\n"; - if (file_put_contents("/boot/config/plugins/ca.mover.tuning/mover.tuning.cron", $cronTuneFile) === false) { - logger("Error: Failed to write mover.tuning.cron file."); - return false; - } - return true; + put_cron_file("/boot/config/plugins/ca.mover.tuning/mover.tuning.cron", $cronTuneFile, "Mover Tuning schedule set to $tuneCron."); } -/** Writes the forced move's mover.cron for the $cron schedule, run through mover.php force; true when the file was written */ +/** Makes the forced move's mover.cron run mover.php force on the $cron schedule */ function make_cron($cron) { - if (empty($cron) === true) { - logger("No cron schedule provided for forced move."); - return false; - } if (valid_cron($cron) === false) { logger("Error: Invalid cron schedule for forced move: " . preg_replace('/[^[:print:]]/', '?', $cron)); - return false; + return; } $cronFile = "# Generated schedule for forced move:\n{$cron} /usr/local/emhttp/plugins/ca.mover.tuning/mover.php force start |& logger -t move\n\n"; - if (file_put_contents("/boot/config/plugins/ca.mover.tuning/mover.cron", $cronFile) === false) { - logger("Error: Failed to write forced mover.cron file."); - return false; - } - return true; + put_cron_file("/boot/config/plugins/ca.mover.tuning/mover.cron", $cronFile, "Forced move schedule set to $cron."); } -/** Writes mover.watchdog.cron, the cache watchdog every 5 minutes (a run it starts logs to syslog itself, so the line discards output); true when written */ +/** Makes mover.watchdog.cron run the cache watchdog every 5 minutes (a run it starts logs to syslog itself, so the line discards output) */ function make_watchdog_cron() { $cronFile = "# Generated schedule for the Mover Tuning cache watchdog:\n*/5 * * * * /usr/local/emhttp/plugins/ca.mover.tuning/age_mover watchdog >/dev/null 2>&1\n\n"; - if (file_put_contents("/boot/config/plugins/ca.mover.tuning/mover.watchdog.cron", $cronFile) === false) { - logger("Error: Failed to write mover.watchdog.cron file."); - return false; - } - return true; + put_cron_file("/boot/config/plugins/ca.mover.tuning/mover.watchdog.cron", $cronFile, "Cache watchdog schedule set to every 5 minutes."); } /** Deletes a cron file, logging $why when given; false, with an error logged, when it exists and cannot be deleted */ @@ -185,7 +118,7 @@ function remove_cron_file($file, $why = '') return true; } -/** Makes the plugin's own cron files follow the saved settings: writes a missing one they call for, removes one they do not, never rewrites one */ +/** Writes each plugin cron file the saved settings call for when missing or different (an invalid schedule is logged, its file kept), removes the rest; false when the settings file does not parse */ function sync_cron_files() { // parse_plugin_cfg reads it with my_parse_ini_file from Unraid 6.12.14, parse_ini_file before; a file that does not @@ -195,12 +128,14 @@ function sync_cron_files() $saved = function_exists('my_parse_ini_file') === true ? @my_parse_ini_file($cfgFile) : @parse_ini_file($cfgFile); if (is_array($saved) === false) { logger("Error: $cfgFile does not parse, so the cron files are left as they are."); - return; + return false; } } sync_forced_cron(); sync_tune_cron(); sync_watchdog_cron(); + retire_unraid_cron(); + return true; } /** sync_cron_files() for the forced move's mover.cron */ @@ -213,8 +148,8 @@ function sync_forced_cron() remove_cron_file($forcedFile, "force move is off"); } elseif ($cfg_cron === '') { remove_cron_file($forcedFile, "no forced move schedule is set"); - } elseif (file_exists($forcedFile) === false && make_cron($cfg_cron) === true) { - logger("Forced move schedule written back from the saved settings."); + } else { + make_cron($cfg_cron); } } @@ -232,8 +167,8 @@ function sync_tune_cron() remove_cron_file($tuneFile, "the Mover Tuning schedule is disabled"); } elseif ($cfg_moverTuneCron === '') { remove_cron_file($tuneFile, "no Mover Tuning schedule is set"); - } elseif (file_exists($tuneFile) === false && make_tune_cron($cfg_moverTuneCron) === true) { - logger("Mover Tuning schedule written back from the saved settings."); + } else { + make_tune_cron($cfg_moverTuneCron); } } @@ -245,92 +180,67 @@ function sync_watchdog_cron() $watchdogFile = "/boot/config/plugins/ca.mover.tuning/mover.watchdog.cron"; if ($cfg_watchdog !== 'yes') { remove_cron_file($watchdogFile, "the cache watchdog is off"); - } elseif (file_exists($watchdogFile) === false && make_watchdog_cron() === true) { - logger("Cache watchdog schedule written back from the saved settings."); + } else { + make_watchdog_cron(); } } -// From the CLI (plugin install, age_mover reset) the plugin's cron files are brought in line with the saved settings, -// exiting 1 when an error was logged; the caller runs update_cron afterwards -if (PHP_SAPI === 'cli' && ($argv[1] ?? '') === 'sync') { - sync_cron_files(); - exit($loggedErrors === 0 ? 0 : 1); -} +/** From Unraid 7.2.1, after the install migrated Unraid's schedule: renames Unraid's mover.cron to mover.cron.old unless the Mover Tuning schedule is on, set and not written yet */ +function retire_unraid_cron() +{ + global $vars, $cfg_moverDisabled, $cfg_moverTuneCron; -// Check if value was changed to prevent the logger of printing when cron was not changed and not make cron file when avalible already -if ($cfg_cronEnabled !== post_string('cronEnabled')) { - if (post_string('cronEnabled') === "yes") { - if (make_cron(trim(post_string('cron'))) === true) { - logger("Forced move schedule enabled successfully."); - } - } elseif (remove_cron_file("/boot/config/plugins/ca.mover.tuning/mover.cron") === true) { - logger("Forced move schedule disabled successfully."); + $mark = "/boot/config/plugins/ca.mover.tuning/retire.unraid.schedule"; + $unraidFile = "/boot/config/plugins/dynamix/mover.cron"; + if (is_file($mark) === false || $vars['version'] === '' || version_compare($vars['version'], '7.2.1', '<') === true) { + return; } -} else { - // If cron already enabled and cron time was changed update cron file - if ($cfg_cronEnabled === "yes" && $cfg_cron !== post_string('cron')) { - if (make_cron(trim(post_string('cron'))) === true) { - logger("Forced move schedule updated successfully."); - } + if ($cfg_moverDisabled !== 'yes' && $cfg_moverTuneCron !== '' && is_file("/boot/config/plugins/ca.mover.tuning/mover.tuning.cron") === false) { + logger("Unraid's mover schedule in $unraidFile is kept: mover.tuning.cron is not written yet."); + return; } -} - -// Check if value was changed -if ($cfg_moverDisabled !== post_string('ismoverDisabled')) { - // If mover schedule is disabled - if (post_string('ismoverDisabled') === "yes") { - if (version_compare($vars['version'], '7.2.1', '>=') === true) { - // Check if the file exists - if (file_exists("/boot/config/plugins/ca.mover.tuning/mover.tuning.cron") === false) { - logger("Mover Tuning cron file does not exist"); - } elseif (remove_cron_file("/boot/config/plugins/ca.mover.tuning/mover.tuning.cron") === true) { - logger("Mover Tuning schedule disabled successfully."); - } - } else { - // Check if the file exists - if (file_exists("/boot/config/plugins/dynamix/mover.cron") === false) { - logger("Mover cron file does not exist"); - } elseif (remove_cron_file("/boot/config/plugins/dynamix/mover.cron") === true) { - logger("Mover schedule disabled successfully."); - } - } - } else { - if (version_compare($vars['version'], '7.2.1', '>=') === true) { - $tuneCron = isset($_POST['tune_cron']) === true ? trim(post_string('tune_cron')) : $cfg_moverTuneCron; - if (make_tune_cron($tuneCron) === true) { - logger("Mover Tuning schedule enabled successfully."); - } - } elseif (make_unraid_cron() === true) { - logger("Mover schedule enabled successfully."); + if (is_file($unraidFile) === true) { + if (@rename($unraidFile, "$unraidFile.old") === false) { + logger("Error: Failed to rename $unraidFile to mover.cron.old."); + return; } + logger("Retired Unraid's mover schedule: $unraidFile is now mover.cron.old."); + } + if (@unlink($mark) === false) { + logger("Error: Failed to remove $mark."); } } -// Handle Mover Tuning custom cron schedule, unless this request disables Mover Tuning -if (version_compare($vars['version'], '7.2.1', '>=') === true && post_string('ismoverDisabled') !== 'yes') { - $postTuneCron = post_string('tune_cron'); - if ($cfg_moverTuneCron !== $postTuneCron) { - $tuneCron = trim($postTuneCron); - if ($tuneCron === "" && remove_cron_file("/boot/config/plugins/ca.mover.tuning/mover.tuning.cron") === true) { - logger("Mover Tuning cron schedule removed."); - } elseif ($tuneCron !== "" && make_tune_cron($tuneCron) === true) { - logger("Mover Tuning cron schedule updated successfully."); - } +/** Before Unraid 7.2.1, where Unraid's own mover.cron starts Mover Tuning: removed while the schedule is disabled, else written back when missing and the array is started */ +function apply_unraid_cron() +{ + global $vars, $cfg_moverDisabled; + + $unraidFile = "/boot/config/plugins/dynamix/mover.cron"; + if ($vars['version'] === '' || version_compare($vars['version'], '7.2.1', '>=') === true) { + return; + } + if ($cfg_moverDisabled === 'yes') { + remove_cron_file($unraidFile, "the Mover Tuning schedule is disabled"); + } elseif (is_file($unraidFile) === false && ($vars['mdState'] ?? '') === 'STARTED') { + // as emhttpd does: it writes this file from Mover Settings and removes it at array stop + make_unraid_cron(); } } -// The watchdog cron file follows the posted setting rather than a comparison with the saved one, which update.php -// may already have written; age_mover watchdog also checks the setting, so a leftover file does nothing -$watchdogCron = "/boot/config/plugins/ca.mover.tuning/mover.watchdog.cron"; -if (post_string('watchdog') === 'yes') { - if (is_file($watchdogCron) === false && make_watchdog_cron() === true) { - logger("Cache watchdog enabled."); +// "sync" runs at plugin install, whose caller runs update_cron; "apply" runs at age_mover reset and as the settings form's +// #command, which update.php runs once it has saved the settings. A web request, such as a page loaded before an update, does nothing. +$mode = PHP_SAPI === 'cli' ? ($argv[1] ?? '') : ''; +if ($mode === 'sync') { + sync_cron_files(); +} elseif ($mode === 'apply') { + if (sync_cron_files() === true) { + apply_unraid_cron(); } -} elseif (isset($_POST['watchdog']) === true && is_file($watchdogCron) === true) { - if (remove_cron_file($watchdogCron) === true) { - logger("Cache watchdog disabled."); + exec("/usr/local/sbin/update_cron", $output, $status); + if ($status !== 0) { + logger("Error: /usr/local/sbin/update_cron exited with $status, so crond may still run the previous schedules."); } } - -exec("update_cron"); +exit($loggedErrors === 0 ? 0 : 1); ?> \ No newline at end of file diff --git a/tests/age_mover/lib.sh b/tests/age_mover/lib.sh new file mode 100644 index 00000000..12b11bb4 --- /dev/null +++ b/tests/age_mover/lib.sh @@ -0,0 +1,361 @@ +#!/bin/bash +# shellcheck disable=SC2034 # the settings set here are read by age_mover's functions, sourced from funcs.sh +# Sourced by test_*.sh: each age_mover case runs the real processTheMoves with real rsync and the shipped default.cfg read by the real +# getMoverSettings; Unraid's move, notify, findmnt, zfs, mount, umount and rmdir are stand-ins. It deletes the folders in ROOTS. +HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +PLUGIN=$HERE/../../source/ca.mover.tuning/usr/local/emhttp/plugins/ca.mover.tuning +AM=${AM:-$PLUGIN/age_mover} +T=${T:-/tmp/age_mover_test} # test_folders.sh runs its plain-user half with its own T +ROOTS=(/mnt/cache /mnt/user0 /mnt/disk1 /mnt/disk2 /mnt/other) + +# a mount at or under /mnt would put the host's files under the wipe, and one at a stand-in's path or above it the +# host's own under the stand-in; an unreadable mount table refuses too +no_host_mount() { + awk '$5 == "/mnt" || index($5, "/mnt/") == 1 || $5 ~ "^/usr(/bin(/php)?|/libexec(/unraid(/move)?)?)?$" || + $5 ~ "^/usr/local(/emhttp(/webGui(/scripts(/notify)?)?)?)?$" { exit 1 }' /proc/self/mountinfo +} +if [ "${AGE_MOVER_TEST:-}" != 1 ] || [ ! -e /.dockerenv ] || ! no_host_mount; then + echo "lib.sh deletes ${ROOTS[*]} and writes /usr/bin/php, /usr/libexec/unraid/move and /usr/local/emhttp/webGui/scripts/notify: start" \ + "the tests with tests/age_mover/run.sh" >&2 + exit 2 +fi + +mkdir -p "$T/cwd" "$T/bin" "$T/tmp" +# mktemp's private folders stay inside the test folder +export TMPDIR=$T/tmp +# root installs the move stand-in; the plain-user run uses the one root installed before it +if [ "$(id -u)" = 0 ]; then + mkdir -p /usr/libexec/unraid + cat >/usr/libexec/unraid/move <<'EOF' +#!/bin/bash +# stand-in for Unraid's move: a name on the cache goes to the array (/mnt/user0), a name anywhere else to the cache. +# A file is copied, as across disks, so names of one inode stay linked only when they come in the same run. +declare -A linked +while IFS= read -r p; do + [ -n "$p" ] || continue + root=${p#/mnt/} root=${root%%/*} + rel=${p#/mnt/"$root"/} to=/mnt/cache + [ "$root" = cache ] && to=/mnt/user0 + mkdir -p "$to/${rel%/*}" + if [ -d "$p" ] && [ ! -L "$p" ]; then + mkdir -p "$to/$rel" && rmdir "$p" 2>/dev/null + else + i=$(stat -c %i "$p") + if [ -n "${linked[$i]}" ]; then ln -- "${linked[$i]}" "$to/$rel"; else cp -a -- "$p" "$to/$rel"; fi && rm -- "$p" && linked[$i]=$to/$rel + fi && echo "move: $p Success" +done +EOF + chmod 755 /usr/libexec/unraid/move + mkdir -p /usr/local/emhttp/webGui/scripts + cat >/usr/local/emhttp/webGui/scripts/notify <<'EOF' +#!/bin/bash +# stand-in for Unraid's notify: each notice's importance and description, as one line in $NOTIFY_LOG, after the +# $NOTIFY_LOG.hook a case puts there +[ ! -f "${NOTIFY_LOG:?}.hook" ] || bash "$NOTIFY_LOG.hook" +while getopts 's:d:i:l:' o; do + case $o in d) desc=$OPTARG ;; i) imp=$OPTARG ;; s | l) ;; *) exit 1 ;; esac +done +printf '%s|%s\n' "$imp" "$desc" >>"${NOTIFY_LOG:?}" +EOF + chmod 755 /usr/local/emhttp/webGui/scripts/notify +fi +# a path in $T/zfs is a ZFS mountpoint (a tab, then its dataset, else the path less /mnt/); zfs logs calls to $T/zfs.calls +# and fails unanswered calls and each subcommand in $T/zfs.fail, with $T/zfs.reason (else zfs.fail) then a child's name +cat >"$T/bin/findmnt" <<'EOF' +#!/bin/bash +# zfs.private's lines are mount's, at a private folder +l=$(cat "${0%/bin/findmnt}/zfs" "${0%/bin/findmnt}/zfs.private" 2>/dev/null | awk -F'\t' -v p="${*: -1}" '$1 == p {print; exit}') +[ -n "$l" ] || exit 0 +case "$2" in +source) n=${l#*$'\t'}; [ "$n" != "$l" ] || n=${l#/mnt/}; echo "$n" ;; +*) echo zfs ;; +esac +EOF +cat >"$T/bin/zfs" <<'EOF' +#!/bin/bash +d=${0%/bin/zfs} +n=${*: -1} +echo "zfs $*" >>"$d/zfs.calls" +# $T/zfs.on_ runs first, as a write while zfs works +[ ! -f "$d/zfs.on_$1" ] || bash "$d/zfs.on_$1" +if grep -qxF -- "$1" "$d/zfs.fail" 2>/dev/null; then + r=$(cat "$d/zfs.reason" 2>/dev/null) || r=zfs.fail + printf "cannot %s '%s': %s\n%s/child\n" "$1" "$n" "$r" "$n" >&2 + exit 1 +fi +# the line of file $1 for dataset $n +entry() { awk -F'\t' -v n="$n" '(NF > 1 ? $2 : substr($1, 6)) == n' "$1" 2>/dev/null; } +case "$*" in +# $T/zfs.children holds the children and snapshots +"list -r -H -t filesystem,volume,snapshot -o name "*) + echo "$n"; cat "$d/zfs.children" 2>/dev/null || : + ;; +# unmount unlists the dataset and hides its files, keeping its folder; mount lists it and brings them back, hiding, +# as an overlay mount does, what the folder gained meanwhile, and fails while mount has it at a private folder. The +# hidden folder is the old one, moved away, so a process inside it sees, as on Linux, what the mount hides +"unmount "*) + l=$(entry "$d/zfs") + [ -n "$l" ] || { echo "cannot unmount '$n': not currently mounted" >&2; exit 1; } + echo "$l" >>"$d/zfs.off" + grep -vxF -- "$l" "$d/zfs" >"$d/zfs.new"; mv "$d/zfs.new" "$d/zfs" + mkdir -p "$d/zfs.store/$n" && find "${l%%$'\t'*}" -mindepth 1 -maxdepth 1 -exec mv -t "$d/zfs.store/$n" {} + + ;; +"mount "*) + [ -z "$(awk -F'\t' -v n="$n" '$2 == n' "$d/zfs.private" 2>/dev/null)" ] || + { echo "cannot mount '$n': filesystem already mounted" >&2; exit 1; } + l=$(entry "$d/zfs.off" | tail -n 1) && f=${l%%$'\t'*} + mkdir -p "$d/zfs.hidden" && { [ ! -d "$f" ] || mv -- "$f" "$(mktemp -u "$d/zfs.hidden/XXXXXX")"; } && mkdir -- "$f" + find "$d/zfs.store/$n" -mindepth 1 -maxdepth 1 -exec mv -t "$f" {} + + echo "$l" >>"$d/zfs" + ;; +# the dataset's files go with it; OpenZFS removes its folder only when nothing is in it +"destroy "*) rmdir -- "$(entry "$d/zfs.off" | tail -n 1 | cut -f1)" 2>/dev/null; rm -rf -- "$d/zfs.store/$n" ;; +*) echo "zfs stand-in has no answer for: zfs $*" >&2; exit 1 ;; +esac +EOF +# mount -t zfs -o ro,zfsutil DATASET DIR moves an unmounted dataset's files into an empty DIR outside /mnt, umount back. Both log +# to zfs.calls (a mktemp DIR as PRIVATE), run zfs.on_mount.zfs or zfs.on_umount, fail on mount.zfs (zfs.reason: all it says) or umount; +# mount.zfs.late mounts, then fails, as mount.zfs does when it cannot update /etc/mtab; umount.late, as umount does +cat >"$T/bin/mount" <<'EOF' +#!/bin/bash +d=${0%/bin/mount} +p=${*: -1} +[[ $p == "${TMPDIR:-/tmp}"/ca.mover.tuning.?????? ]] && shown=PRIVATE || shown=$p +echo "mount ${*:1:$#-1} $shown" >>"$d/zfs.calls" +[ ! -f "$d/zfs.on_mount.zfs" ] || bash "$d/zfs.on_mount.zfs" +[ $# = 6 ] && [ "$1 $2 $3 $4" = "-t zfs -o ro,zfsutil" ] || { echo "mount stand-in has no answer for: mount $*" >&2; exit 1; } +n=$5 +if grep -qxF mount.zfs "$d/zfs.fail" 2>/dev/null; then + cat "$d/zfs.reason" >&2 2>/dev/null || echo "filesystem '$n' cannot be mounted, zfs.fail" >&2 + exit 1 +fi +case $p in /mnt | /mnt/*) echo "mount stand-in: $p is under /mnt" >&2; exit 1 ;; esac +[ -d "$p" ] && [ -z "$(find "$p" -mindepth 1 -print -quit)" ] || { echo "mount stand-in: $p is not an empty folder" >&2; exit 1; } +if [ ! -d "$d/zfs.store/$n" ] || [ -n "$(awk -F'\t' -v n="$n" '$2 == n' "$d/zfs.private" 2>/dev/null)" ] || + [ -n "$(awk -F'\t' -v n="$n" '(NF > 1 ? $2 : substr($1, 6)) == n' "$d/zfs" 2>/dev/null)" ]; then + echo "filesystem '$n' is already mounted" >&2 + exit 1 +fi +find "$d/zfs.store/$n" -mindepth 1 -maxdepth 1 -exec mv -t "$p" {} + +printf '%s\t%s\n' "$p" "$n" >>"$d/zfs.private" +if grep -qxF mount.zfs.late "$d/zfs.fail" 2>/dev/null; then + echo "filesystem '$n' was mounted, but /etc/mtab could not be updated" >&2 + exit 1 +fi +EOF +cat >"$T/bin/umount" <<'EOF' +#!/bin/bash +d=${0%/bin/umount} +p=$1 +l=$(awk -F'\t' -v p="$p" '$1 == p' "$d/zfs.private" 2>/dev/null) +[ -n "$l" ] && shown=PRIVATE || shown=$p +echo "umount $shown" >>"$d/zfs.calls" +[ ! -f "$d/zfs.on_umount" ] || bash "$d/zfs.on_umount" +[ $# = 1 ] || { echo "umount stand-in has no answer for: umount $*" >&2; exit 1; } +if grep -qxF umount "$d/zfs.fail" 2>/dev/null; then + r=$(cat "$d/zfs.reason" 2>/dev/null) || r=zfs.fail + echo "umount: $p: $r" >&2 + exit 32 +fi +[ -n "$l" ] || { echo "umount: $p: not mounted." >&2; exit 32; } +find "$p" -mindepth 1 -maxdepth 1 -exec mv -t "$d/zfs.store/${l#*$'\t'}" {} + +grep -vxF -- "$l" "$d/zfs.private" >"$d/zfs.new" +mv "$d/zfs.new" "$d/zfs.private" +if grep -qxF umount.late "$d/zfs.fail" 2>/dev/null; then + echo "umount: $p: filesystem was unmounted, but failed to update userspace mount table" >&2 + exit 16 +fi +EOF +# as Linux does, rmdir refuses a folder something is mounted on +cat >"$T/bin/rmdir" <<'EOF' +#!/bin/bash +if [ -n "$(cat "${0%/bin/rmdir}/zfs" "${0%/bin/rmdir}/zfs.private" 2>/dev/null | awk -F'\t' -v p="${*: -1}" '$1 == p')" ]; then + echo "rmdir: failed to remove '${*: -1}': Device or resource busy" >&2 + exit 1 +fi +exec /bin/rmdir "$@" +EOF +chmod 755 "$T/bin/findmnt" "$T/bin/zfs" "$T/bin/mount" "$T/bin/umount" "$T/bin/rmdir" +PATH=$T/bin:$PATH +export NOTIFY_LOG=$T/notify + +# for the Clean ZFS datasets cases: a destroy's calls are list, unmount, the check at a private read-only mount, destroy +LS='list -r -H -t filesystem,volume,snapshot -o name' +DESTROYED=$(printf '%s\n' "zfs $LS cache/sh" 'zfs unmount cache/sh' 'mount -t zfs -o ro,zfsutil cache/sh PRIVATE' 'umount PRIVATE' \ + 'zfs destroy cache/sh') +notice_for() { echo "warning|Clean empty ZFS datasets did not finish for $1. The mover log has the details unless Log Mover Tuning plugin actions is set to No."; } +NOTICE=$(notice_for '[cache/sh]') +# the notice of a cache/sh left out of view: why, and how to mount it back +BACK='move anything in /mnt/cache/sh aside, zfs mount cache/sh, then move it back into /mnt/cache/sh without replacing a file already there: keep both copies and compare them' +NOT_MOUNTED=$(notice_for "[cache/sh] (not mounted: stop writes to the share, $BACK)") +HIDDEN=$(notice_for "[cache/sh] (a file is hidden under it: stop writes to the share, zfs unmount cache/sh, $BACK)") +read_only_notice() { notice_for "[cache/sh] (mounted read-only at $1: stop writes to the share, umount $1, $BACK)"; } +no_private() { check "no private mount folder left" "" "$(find "$TMPDIR" -maxdepth 1 -name 'ca.mover.tuning.*')"; } +notices() { check "notices" "$1" "$(cat "$NOTIFY_LOG" 2>/dev/null)"; } + +# age_mover runs its command on load, so only its functions and its top-level start values are taken +awk '/^[A-Za-z_][A-Za-z0-9_]*\(\) \{/,/^\}/' "$AM" >"$T/funcs.sh" +. "$T/funcs.sh" +grep -E '^[A-Z_]+=(-?[0-9]+|"")$' "$AM" >"$T/globals.sh" +if ! declare -F processTheMoves getMoverSettings >/dev/null; then + echo "lib.sh: processTheMoves or getMoverSettings did not load from $AM" >&2 + exit 2 +fi +LOGFOLDER=$T MOVER_LOG=$T/log MOVER_DEBUG_LOG=$T/dlog +MOVER_STATUS=$T/mover.ini STATS_FILE=$T/stats MOVER_ACTIONLIST=$T/actions SOFTSTOPFILE=$T/softstop SOFTSTOP_ACK=false +PAUSEFILE=$T/pause MOVINGFILE=$T/moving PIDFILE=$T/pid MOVERTUNINGCFGFILE=$T/cfg MOVERTUNING_OVERRIDE_CFGFOLDER=$T/overrides +MOVERTUNING_DEFAULT_CFGFILE=$PLUGIN/default.cfg FILES_IN_USE_HELPER=$PLUGIN/files_in_use NOW=2026-01-02T030405 UNRAID_VERSION=7.2.0 +export TZ=UTC # NOW turns into the sync date in local time +DEBUGLOGGING=no +[ "${AGE_MOVER_DEBUG:-0}" != 2 ] || DEBUGLOGGING=fileOnly +HDR='PRIMARYSTORAGENAME|SHARENAME|SHAREUSECACHE|MODIFYTIME|FILESIZE|POOLSUM|THRESHOLD|PROJECTED|NBLINKS|INODE|ACTION|FROM|TO|FILETYPE|FILEPATH' +FAILS=0 CHECKS=0 + +# setting [key value]...: the shipped defaults with these keys changed, as getMoverSettings reads them +setting() { + cp "$PLUGIN/default.cfg" "$T/cfg" + while [ $# -ge 2 ]; do + grep -q "^$1=" "$T/cfg" || { echo "setting: $1 is not in default.cfg" >&2; exit 2; } + sed -i "s|^$1=.*|$1=\"$2\"|" "$T/cfg" + shift 2 + done + getMoverSettings "$T/cfg" >/dev/null 2>&1 || { echo "setting: getMoverSettings failed on $T/cfg" >&2; exit 2; } + MOVER_PROGRESS=yes +} + +# fresh [key value]...: age_mover's start values and the case's settings, on the folders as they are +fresh() { + . "$T/globals.sh" + IS_CRON=1 # after the start values: as under cron, nothing goes to syslog + setting debuglogging "$DEBUGLOGGING" "$@" +} + +# begin [key value]...: empty pools and disks, then fresh +begin() { + CASE=$1 + shift + rm -rf "${ROOTS[@]}" "$SOFTSTOPFILE" "$PAUSEFILE" "$T/row_error" "$T/zfs" "$T/zfs".* "$T/after_rsync" "$T/bin/rsync" \ + "$MOVER_LOG" "$NOTIFY_LOG" "$NOTIFY_LOG.hook" "$T/pid.kept" "$TMPDIR"/ca.mover.tuning.* + mkdir -p /mnt/cache /mnt/user0 + fresh "$@" +} + +# after_first_rsync : runs the command once, right after the case's first rsync ends; its errors go to the stderr +# run_moves checks. The wrapper renames its process, or copyPids would take it for the copy +after_first_rsync() { + local h=$T/after_rsync e=$T/row_error + printf '%s\n' "$1" >"$h" + # shellcheck disable=SC2016 # the wrapper expands its own $$, $@ and $? + printf '#!/bin/bash\nprintf hook >/proc/$$/comm\n%q "$@"\nrc=$?\n[ -e %q ] && { bash %q 2>>%q || echo "after_first_rsync: the command failed" >>%q; rm -f %q; }\nexit $rc\n' \ + "$(PATH=${PATH#"$T/bin:"} command -v rsync)" "$h" "$h" "$e" "$e" "$h" >"$T/bin/rsync" + chmod 755 "$T/bin/rsync" +} + +# a hook, run once, that stops the mover: one stop signals the run alone, as a kill of its pid does; the plugin's is +# age_mover stop, run outside the run, which signals every process of it. The hook waits until that stop says it waits +# for the run or has ended, and notes whether the run's pid file is still there +stop_hook() { + cat <"$T/pid" +( setsid bash -c '. "$T/funcs.sh"; PIDFILE="$T/pid" MOVER_STATUS="$T/mover.ini" PAUSEFILE="$T/pause" MOVINGFILE="$T/moving"; stop' \\ + "$T/stop.out" 2>&1 & ) +for _ in \$(seq 100); do grep -qs -e 'mover: stopped' -e 'mover: waiting' "$T/stop.out" && break; sleep 0.1; done +[ ! -f "$T/pid" ] || echo kept >"$T/pid.kept" +EOF +} + +# mk ...: a 2-byte file at /mnt// +mk() { + local r=$1 p + shift + for p; do + mkdir -p "/mnt/$r/${p%/*}" && printf 'x\n' >"/mnt/$r/$p" + done +} + +# row [links inode mtime]: the planner's row for the name, stat'd where it is now; the +# planner reads the array by disk, so a row from the secondary comes from /mnt/disk1 or /mnt/disk2 +row() { + local from to p m i n s + case "$1" in + "keep on primary") from=/mnt/cache to=none ;; + *"from primary" | "sync unattended to secondary") from=/mnt/cache to=/mnt/user0 ;; + *"from secondary") from=/mnt/disk1 to=/mnt/cache; [ -e "/mnt/disk2/$3" ] && from=/mnt/disk2 ;; + "move unattended to primary") from=/mnt/other to=/mnt/cache ;; + *) from=/mnt/other to=/mnt/user0 ;; + esac + for p in "$from/$3" "/mnt/other/$3" ""; do [ -e "$p" ] && break; done + [ -n "$p" ] || { echo "row: no $3 under $from or /mnt/other" | tee -a "$T/row_error" >&2; return 1; } + read -r m i n s < <(stat -c '%Y %i %h %s' "$p") + printf 'cache|%s|yes|%s|%s|0|0|0|%s|%s|%s|%s|%s|%s|%s\n' "${3%%/*}" "${6:-$m}" "$s" "${4:-$n}" "${5:-$i}" "$1" "$from" "$to" "$2" "$3" +} + +# list: the rows on stdin as the action list; as in the planner, a hardlink group's size counts on its first name only +list() { { echo "$HDR"; awk -F'|' -v OFS='|' '$9 > 1 && seen[$12 "|" $9 "|" $10 "|" $4]++ { $5 = 0 } 1'; } >"$MOVER_ACTIONLIST"; } + +# run_moves [stderr]: processTheMoves after the totals the planner counts per direction (a staged move to the primary is +# counted by its sync row); stderr must be exactly the given text, nothing by default +run_moves() { + read -r TOTALPRIMARYFILES TOTALPRIMARYFOLDERS TOTALPRIMARYSIZE TOTALSECONDARYFILES TOTALSECONDARYFOLDERS TOTALSECONDARYSIZE \ + TOTALUNATTENDEDFILES TOTALUNATTENDEDFOLDERS TOTALUNATTENDEDSIZE < <(awk -F'|' ' + function path( p, i) { p = $15; for (i = 16; i <= NF; i++) p = p "|" $i; return p } + NR == FNR { if ($11 == "sync unattended to secondary") staged[path()] = 1; next } + FNR == 1 { next } + { d = "" } + $11 == "move from primary" || $11 == "sync from primary" { d = "p" } + $11 == "move from secondary" || $11 == "sync from secondary" { d = "s" } + $11 ~ /unattended/ && !($11 == "move unattended to primary" && (path() in staged)) { d = "u" } + d != "" { n[d ($14 == "d" ? "d" : "f")]++; sz[d] += $5 } + END { print n["pf"] + 0, n["pd"] + 0, sz["p"] + 0, n["sf"] + 0, n["sd"] + 0, sz["s"] + 0, n["uf"] + 0, n["ud"] + 0, sz["u"] + 0 } + ' "$MOVER_ACTIONLIST" "$MOVER_ACTIONLIST") + TOTALFILES=$((TOTALPRIMARYFILES + TOTALSECONDARYFILES + TOTALUNATTENDEDFILES)) + TOTALFOLDERS=$((TOTALPRIMARYFOLDERS + TOTALSECONDARYFOLDERS + TOTALUNATTENDEDFOLDERS)) + START_TIME=$EPOCHSECONDS + : >"$MOVER_LOG" + : >"$MOVER_DEBUG_LOG" + rm -f "$T/counters" + ( + cd "$T/cwd" || exit + processTheMoves + while IFS='=' read -r v _; do printf '%s=%q\n' "$v" "${!v}"; done <"$T/globals.sh" >"$T/counters" + ) >"$T/out" 2>"$T/err" + check "the rows were built and processTheMoves returned with $([ -n "${1:-}" ] && echo the expected text || echo nothing) on stderr" "${1:-}" \ + "$(cat "$T/row_error" "$T/err" 2>/dev/null; [ -f "$T/counters" ] || echo "processTheMoves did not return")" + [ ! -f "$T/counters" ] || . "$T/counters" +} + +check() { # check + CHECKS=$((CHECKS + 1)) + if [ "$2" = "$3" ]; then + echo "ok - $CASE: $1" + else + FAILS=$((FAILS + 1)) + echo "not ok - $CASE: $1" + printf '%s\n' " expected:" "${2:-(nothing)}" " got:" "${3:-(nothing)}" | sed 's/^/ /' + fi +} +tree() { (cd "/mnt/$1" 2>/dev/null && find . -mindepth 1 | sed 's|^\./||' | LC_ALL=C sort); } +# holds [path]...: exactly these names under /mnt/, nothing else +holds() { local r=$1; shift; check "$r holds exactly${*:+ $*}" "$( (($#)) && printf '%s\n' "$@" | LC_ALL=C sort)" "$(tree "$r")"; } +cache_is() { holds cache "$@"; } +array_is() { holds user0 "$@"; } +links() { check "$2 on the array has $1 links" "$1" "$(stat -c %h "/mnt/user0/$2" 2>&1)"; } +counter() { check "$1 is $2" "$2" "${!1}"; } +log() { sed -E 's/^[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3} //' "$MOVER_LOG"; } +log_has() { check "log has: $1" 1 "$(log | grep -cF -- "$1" | sed 's/^[1-9][0-9]*$/1/')"; } +log_lacks() { check "log lacks: $1" 0 "$(log | grep -cF -- "$1")"; } +log_count() { check "log has $1 lines with: $2" "$1" "$(log | grep -cF -- "$2")"; } +dlog_has() { check "debug log has: $1" 1 "$(grep -cF -- "$1" "$MOVER_DEBUG_LOG" | sed 's/^[1-9][0-9]*$/1/')"; } +dlog_lacks() { check "debug log lacks: $1" 0 "$(grep -cF -- "$1" "$MOVER_DEBUG_LOG")"; } + +finish() { + echo "# $(basename "$0"): $((CHECKS - FAILS)) of $CHECKS checks passed" + [ "$FAILS" = 0 ] +} diff --git a/tests/age_mover/run.sh b/tests/age_mover/run.sh new file mode 100644 index 00000000..f6c78f5e --- /dev/null +++ b/tests/age_mover/run.sh @@ -0,0 +1,25 @@ +#!/bin/bash +# Runs every test_*.sh with debug logging off, then on. Without AGE_MOVER_TEST=1 it starts a container first (CI sets it): +# the tests delete folders under /mnt, so set it only inside a throwaway container. +HERE=$(cd "$(dirname "$0")" && pwd) +if [ "${AGE_MOVER_TEST:-}" != 1 ]; then + exec docker run --rm --init -e AGE_MOVER_TEST=1 -v "$(cd "$HERE/../.." && pwd):/src:ro" \ + "${AGE_MOVER_IMAGE:-debian:bookworm-slim}" bash /src/tests/age_mover/run.sh +fi +# packages go in only inside a container: AGE_MOVER_TEST=1 on a host must not change its packages +[ -e /.dockerenv ] || { echo "run.sh: AGE_MOVER_TEST=1 is set outside a container" >&2; exit 2; } +for c in rsync fuser pgrep gawk runuser useradd xmllint; do + command -v "$c" >/dev/null && continue + apt-get update -qq && apt-get install -y -qq --no-install-recommends rsync gawk psmisc procps util-linux passwd libxml2-utils >/dev/null || exit 2 + break +done +# Unraid's awk is gawk; Debian's default mawk would test other awk behaviour +awk --version 2>/dev/null | grep -q '^GNU Awk' || { echo "awk is not GNU awk" >&2; exit 2; } +rc=0 +for debug in 0 2; do + for t in "$HERE"/test_*.sh; do + echo "# $(basename "$t"), debug logging $([ "$debug" = 2 ] && echo on || echo off)" + AGE_MOVER_DEBUG=$debug bash "$t" || rc=1 + done +done +exit $rc diff --git a/tests/age_mover/test_dataset_stops.sh b/tests/age_mover/test_dataset_stops.sh new file mode 100644 index 00000000..b7385794 --- /dev/null +++ b/tests/age_mover/test_dataset_stops.sh @@ -0,0 +1,405 @@ +#!/bin/bash +# Clean ZFS datasets: a stop lets the step in hand finish, mounts the dataset back where it can and ends the run after the +# notice. +. "$(dirname "$0")/lib.sh" +# a case writes under /usr/local and /var/local: a mount at either refuses +if ! awk '$5 ~ "^/(usr|var)/local(/|$)" || $5 ~ "^/(usr|var)$" { exit 1 }' /proc/self/mountinfo; then + echo "test_dataset_stops.sh writes Unraid's paths and one is a mount here: start it with tests/age_mover/run.sh" >&2 + exit 2 +fi + +# the plugin's stop waits for the run to end, then removes the pid and status files: it must end before the next case +stop_done() { + local _ + for _ in $(seq 100); do grep -qs 'mover: stopped' "$T/stop.out" && break; sleep 0.1; done + check "the plugin's stop waited for the run, then ended" \ + "mover: waiting for the run to end"$'\n''mover: stopped' "$(cat "$T/stop.out" 2>/dev/null)" + check "the pid file stayed while the run finished" kept "$(cat "$T/pid.kept" 2>/dev/null)" + check "the plugin's stop removed the pid file" "" "$(ls "$T/pid" 2>/dev/null)" + rm -f "$T/stop.out" "$T/pid.kept" +} +# a hook, run once after command $2, that sends signal $1 to every process from its caller up to, not including, the run +# and its $3 (default 0) nearest +kill_hook() { + cat <"$T/wrap/$1" <"$T/zfs" + row 'move from primary' f sh/only/f.txt | list +} +mounted_again() { check "the dataset is mounted at its folder again" /mnt/cache/sh "$(grep -x /mnt/cache/sh "$T/zfs")"; } +REMOUNTED=$(sed '$d' <<<"$DESTROYED"; echo 'zfs mount cache/sh') + +# a stop of the run alone during the check after the unmount, and a write through /mnt/user meanwhile, which keeps it +# unmounted. The run puts back the write method it forced, then removes its pid file +begin "Clean ZFS datasets, a stop of the run alone during the check after the unmount" cleanFolders topFolder \ + cleanDatasets yes notify errorsOnly enableTurbo yes +one_share +mkdir -p /usr/local/sbin /var/local/emhttp +echo 'md_write_method="0"' >/var/local/emhttp/var.ini +# shellcheck disable=SC2016 # the stand-in expands its own $* and $w +printf '#!/bin/bash\n[ ! -e %q ] || w=" (pid file there)"\necho "mdcmd $*$w" >>%q\n' "$T/pid" "$T/mdcmd.calls" >/usr/local/sbin/mdcmd +chmod 755 /usr/local/sbin/mdcmd +echo $$ >"$T/pid" +{ stop_hook run; echo 'echo y >/mnt/cache/sh/bare.txt'; } >"$T/zfs.on_mount.zfs" +run_moves 'processTheMoves did not return' +check "turbo write forced, then put back before the pid file goes" \ + "$(printf '%s\n' 'mdcmd set md_write_method 1 (pid file there)' 'mdcmd set md_write_method 0 (pid file there)')" \ + "$(cat "$T/mdcmd.calls")" +check "the run removed its pid file" "" "$(ls "$T/pid" 2>/dev/null)" +rm -rf /usr/local/sbin/mdcmd /var/local/emhttp "$T/mdcmd.calls" +check "zfs calls" "$(sed '$d' <<<"$DESTROYED")" "$(cat "$T/zfs.calls")" +log_has 'Mover stopped while ZFS dataset [cache/sh] was unmounted: not deleting it, attempting to remount' +log_has 'Not remounting ZFS dataset [cache/sh]: its folder /mnt/cache/sh holds files that a mount would hide' +log_lacks 'successfully destroyed' +check "the dataset is kept, unmounted" yes "$([ -d "$T/zfs.store/cache/sh" ] && echo yes)" +cache_is sh sh/bare.txt +no_private +notices "$NOT_MOUNTED" + +# mdcmd fails to put the write method back: no other try once the pid file has gone, as a run started then may force it +begin "Clean ZFS datasets, a stop of the run alone, mdcmd fails to put the write method back" cleanFolders topFolder \ + cleanDatasets yes notify errorsOnly enableTurbo yes +one_share +mkdir -p /usr/local/sbin /var/local/emhttp +echo 'md_write_method="0"' >/var/local/emhttp/var.ini +# shellcheck disable=SC2016 # the stand-in expands its own $*, $w and $3 +printf '#!/bin/bash\n[ ! -e %q ] || w=" (pid file there)"\necho "mdcmd $*$w" >>%q\n[ "$3" != 0 ]\n' "$T/pid" \ + "$T/mdcmd.calls" >/usr/local/sbin/mdcmd +chmod 755 /usr/local/sbin/mdcmd +echo $$ >"$T/pid" +{ stop_hook run; echo 'echo y >/mnt/cache/sh/bare.txt'; } >"$T/zfs.on_mount.zfs" +run_moves 'processTheMoves did not return' +check "turbo write forced, then one try to put it back, before the pid file goes" \ + "$(printf '%s\n' 'mdcmd set md_write_method 1 (pid file there)' 'mdcmd set md_write_method 0 (pid file there)')" \ + "$(cat "$T/mdcmd.calls")" +log_count 1 'Could not restore original turbo write mode Read/modify/write: mdcmd exited 1' +check "the run removed its pid file" "" "$(ls "$T/pid" 2>/dev/null)" +rm -rf /usr/local/sbin/mdcmd /var/local/emhttp "$T/mdcmd.calls" +cache_is sh sh/bare.txt +no_private +notices "$NOT_MOUNTED" + +# a second stop that signals every process, as the plugin's does, reaches the run and the mdcmd that puts the write +# method back: both wait for it +begin "Clean ZFS datasets, a second stop as the stopped run puts the write method back" cleanFolders topFolder \ + cleanDatasets yes enableTurbo yes +one_share +mkdir -p /usr/local/sbin /var/local/emhttp +echo 'md_write_method="0"' >/var/local/emhttp/var.ini +cat >/usr/local/sbin/mdcmd <>$T/mdcmd.calls +EOF +chmod 755 /usr/local/sbin/mdcmd +echo $$ >"$T/pid" +{ stop_hook run; echo "touch $T/stop2"; } >"$T/zfs.on_mount.zfs" +run_moves 'processTheMoves did not return' +check "the second stop came" "" "$(ls "$T/stop2" 2>/dev/null)" +check "turbo write forced, then put back" "$(printf '%s\n' 'mdcmd set md_write_method 1' 'mdcmd set md_write_method 0')" \ + "$(cat "$T/mdcmd.calls")" +check "the run removed its pid file" "" "$(ls "$T/pid" 2>/dev/null)" +rm -rf /usr/local/sbin/mdcmd /var/local/emhttp "$T/mdcmd.calls" +log_lacks 'successfully destroyed' +no_private + +# the plugin's stop as each step runs: the step finishes, a destroy that finished stays done, else the dataset goes back +for step in 'zfs list' 'zfs unmount' 'the read-only umount' 'zfs destroy' 'the remount'; do + begin "Clean ZFS datasets, the plugin's mover stop during $step" cleanFolders topFolder cleanDatasets yes + one_share + case $step in + 'zfs list') stop_hook plugin >"$T/zfs.on_list" ;; + 'zfs unmount') stop_hook plugin >"$T/zfs.on_unmount" ;; + 'the read-only umount') stop_hook plugin >"$T/zfs.on_umount" ;; + 'zfs destroy') stop_hook plugin >"$T/zfs.on_destroy" ;; + # a file that lands in the dataset as it unmounts keeps it, so it is mounted again + *) echo 'echo x >/mnt/cache/sh/new.txt' >"$T/zfs.on_unmount"; stop_hook plugin >"$T/zfs.on_mount" ;; + esac + run_moves 'processTheMoves did not return' + stop_done + log_lacks 'Failed to' + log_lacks 'could not be checked' + no_private + notices '' + # the run ends after the dataset checks, before the top-folder check + log_lacks 'top-level' + if [ "$step" = 'zfs list' ]; then + check "zfs calls" "zfs $LS cache/sh" "$(cat "$T/zfs.calls")" + log_lacks 'could not be listed' + check "the dataset stays mounted" /mnt/cache/sh "$(grep -x /mnt/cache/sh "$T/zfs")" + continue + fi + if [ "$step" = 'zfs destroy' ]; then + check "zfs calls" "$DESTROYED" "$(cat "$T/zfs.calls")" + log_has 'ZFS dataset [cache/sh] successfully destroyed.' + cache_is + continue + fi + check "zfs calls" "$REMOUNTED" "$(cat "$T/zfs.calls")" + check "no private mount left" "" "$(cat "$T/zfs.private" 2>/dev/null)" + mounted_again + if [ "$step" = 'the remount' ]; then + log_has 'Keeping ZFS dataset [cache/sh]: the check after the unmount found something a destroy could lose.' + cache_is sh sh/new.txt + else + log_has 'Mover stopped while ZFS dataset [cache/sh] was unmounted: not deleting it, attempting to remount' + cache_is sh + fi +done + +# the plugin's stop as the remount's look into the bare folder runs: the look finishes and finds what a mount would hide +begin "Clean ZFS datasets, the plugin's mover stop as the remount looks into the bare folder" cleanFolders topFolder \ + cleanDatasets yes +one_share +wrap_hook find "/mnt/cache/sh -mindepth 1 -print -quit" +echo 'echo x >/mnt/cache/sh/new.txt' >"$T/zfs.on_unmount" +echo 'echo y >/mnt/cache/sh/bare.txt' >"$T/zfs.on_mount.zfs" +stop_hook plugin >"$T/find.hook" +PATH=$T/wrap:$PATH run_moves 'processTheMoves did not return' +stop_done +check "zfs calls" "$(sed '$d' <<<"$DESTROYED")" "$(cat "$T/zfs.calls")" +log_has 'Not remounting ZFS dataset [cache/sh]: its folder /mnt/cache/sh holds files that a mount would hide' +cache_is sh sh/bare.txt +no_private +notices "$NOT_MOUNTED" + +# the plugin's stop as mktemp makes the private folder: it is made, so the unmount goes ahead and the dataset goes back +begin "Clean ZFS datasets, the plugin's mover stop as the private folder is made" cleanFolders topFolder cleanDatasets yes +one_share +wrap_hook mktemp "-d -t ca.mover.tuning.XXXXXX" +stop_hook plugin >"$T/mktemp.hook" +PATH=$T/wrap:$PATH run_moves 'processTheMoves did not return' +stop_done +check "zfs calls" "$REMOUNTED" "$(cat "$T/zfs.calls")" +log_has 'Mover stopped while ZFS dataset [cache/sh] was unmounted: not deleting it, attempting to remount' +log_lacks 'could not be checked' +mounted_again +no_private +notices '' + +# the plugin's stop signals the first check before the run: the check still finishes, so its find keeps the dataset +# mounted, where a cut-short check would read as nothing to lose and unmount it +begin "Clean ZFS datasets, a TERM to the first check before the run's" cleanFolders topFolder cleanDatasets yes +mk cache sh/only/f.txt sh/keep.txt +printf '%s\n' /mnt/cache /mnt/cache/sh >"$T/zfs" +row 'move from primary' f sh/only/f.txt | list +wrap_hook find ". -mindepth 1 -path ./.zfs -prune -o ! -type d -print -quit" +kill_hook TERM : >"$T/find.hook" +PATH=$T/wrap:$PATH run_moves +check "zfs calls" "zfs $LS cache/sh" "$(cat "$T/zfs.calls")" +log_lacks 'attempting to unmount' +cache_is sh sh/keep.txt +notices '' + +# a stop during the next share's checks ends the run before its unmount and before the share after it, and still sends +# the notice for the earlier one +begin "Clean ZFS datasets, a stop of the run alone during the next share's checks" cleanFolders topFolder cleanDatasets yes +mk cache a/only/f.txt sh/only/g.txt z/only/h.txt +# the pid file names another run, as after Unraid's mover stop removes it and a new run starts: it stays +echo 1 >"$T/pid" +printf '%s\n' /mnt/cache /mnt/cache/a /mnt/cache/sh /mnt/cache/z >"$T/zfs" +# cache/a is kept, as a file lands in it as it unmounts, and cannot be mounted again +echo 'echo x >/mnt/cache/a/new.txt' >"$T/zfs.on_unmount" +echo mount >"$T/zfs.fail" +{ echo "tail -n 1 \"$T/zfs.calls\" | grep -q ' cache/sh\$' || exit 0"; stop_hook run; } >"$T/zfs.on_list" +{ row 'move from primary' f a/only/f.txt; row 'move from primary' f sh/only/g.txt; row 'move from primary' f z/only/h.txt; } | list +run_moves 'processTheMoves did not return' +log_has 'Failed to remount dataset [cache/a]' +log_lacks 'ZFS dataset [cache/sh] holds only folders' +check "cache/sh is still mounted" /mnt/cache/sh "$(grep -x /mnt/cache/sh "$T/zfs")" +check "the share after it is not looked at" "" "$(grep -F cache/z "$T/zfs.calls")" +notices "$(notice_for '[cache/a] (not mounted: stop writes to the share, move anything in /mnt/cache/a aside, zfs mount cache/a, then move it back into /mnt/cache/a without replacing a file already there: keep both copies and compare them)')" +no_private +check "another run's pid file stays" 1 "$(cat "$T/pid" 2>/dev/null)" +rm -f "$T/pid" + +# a check that fails as a stop comes is still reported +begin "Clean ZFS datasets, a stop of the run alone as the check after the unmount fails" cleanFolders topFolder \ + cleanDatasets yes +one_share +stop_hook run >"$T/zfs.on_mount.zfs" +echo mount.zfs >"$T/zfs.fail" +run_moves 'processTheMoves did not return' +check "zfs calls" "$(grep -vx 'umount PRIVATE' <<<"$REMOUNTED")" "$(cat "$T/zfs.calls")" +log_has "ZFS dataset [cache/sh] could not be checked once unmounted, will not delete: mount: filesystem 'cache/sh' cannot be mounted, zfs.fail" +log_lacks 'Mover stopped while' +mounted_again +no_private +notices "$NOTICE" + +# the plugin's stop as the notice goes out: the notice is still sent, then the run ends +begin "Clean ZFS datasets, the plugin's mover stop as the notice goes out" cleanFolders topFolder cleanDatasets yes +one_share +echo unmount >"$T/zfs.fail" +stop_hook plugin >"$NOTIFY_LOG.hook" +run_moves 'processTheMoves did not return' +stop_done +log_has 'Failed to unmount ZFS dataset [cache/sh]' +log_lacks 'top-level' +notices "$NOTICE" + +# the plugin's stop as a dataset's notice entry is translated: the translation finishes, so the entry keeps its reason +begin "Clean ZFS datasets, the plugin's mover stop as a dataset's notice entry is translated" cleanFolders topFolder \ + cleanDatasets yes +one_share +echo 'echo x >/mnt/cache/sh/new.txt' >"$T/zfs.on_unmount" +echo mount >"$T/zfs.fail" +stop_hook plugin >"$T/php.hook" +# translate_text runs /usr/bin/php -q translate.php TEMPLATE; this one prints the template back +# shellcheck disable=SC2016 # the stand-in expands its own $3 +printf '#!/bin/bash\ncase $3 in "not mounted:"*) [ ! -f %q ] || bash %q ;; esac\nprintf %%s "$3"\n' "$T/php.hook" "$T/php.hook" \ + >/usr/bin/php +chmod 755 /usr/bin/php +run_moves 'processTheMoves did not return' +rm -f /usr/bin/php +stop_done +check "the stop came during the translation" "" "$(ls "$T/php.hook" 2>/dev/null)" +log_has 'Failed to remount dataset [cache/sh]' +notices "$NOT_MOUNTED" + +# a run that starts as the stopped one ends writes its own pid file, which the plugin's stop then leaves +begin "Clean ZFS datasets, the plugin's mover stop, and another run starts as the stopped one ends" cleanFolders topFolder \ + cleanDatasets yes +one_share +{ stop_hook plugin; echo "echo 1 >\"$T/pid\""; } >"$T/zfs.on_unmount" +run_moves 'processTheMoves did not return' +for _ in $(seq 100); do grep -qs 'mover: stopped' "$T/stop.out" && break; sleep 0.1; done +check "the plugin's stop ended" 1 "$(grep -cs 'mover: stopped' "$T/stop.out")" +check "the other run's pid file stays" 1 "$(cat "$T/pid" 2>/dev/null)" +rm -f "$T/stop.out" "$T/pid" +mounted_again + +# a check killed outright, not by a stop: the run unmounts the private folder if the dataset is there, then mounts it back, +# or says where it is and how to mount it back when that umount fails +for when in 'before the read-only mount' 'while it is mounted' 'while it is mounted, and the clean-up umount fails' \ + 'while it is mounted, and the plugin stops the mover during the clean-up umount' \ + 'while it is mounted, and the plugin stops the mover as the run looks for the private mount'; do + begin "Clean ZFS datasets, the check after the unmount is killed $when" cleanFolders topFolder cleanDatasets yes + one_share + case $when in + before*) kill_hook KILL : >"$T/zfs.on_mount.zfs" ;; + *fails) kill_hook KILL "echo umount >\"$T/zfs.fail\"" >"$T/zfs.on_umount" ;; + # the stop's hook takes the hook's place for the clean-up umount, which finishes and puts the dataset back + *during*) stop_hook plugin >"$T/stop.hook"; kill_hook KILL "cp \"$T/stop.hook\" \"$T/zfs.on_umount\"" >"$T/zfs.on_umount" ;; + # the look finishes, so the clean-up umount runs + *looks*) + wrap_hook findmnt "-no source --mountpoint $TMPDIR/ca.mover.tuning." + stop_hook plugin >"$T/stop.hook" + kill_hook KILL "cp \"$T/stop.hook\" \"$T/findmnt.hook\"" >"$T/zfs.on_umount" + ;; + *) kill_hook KILL : >"$T/zfs.on_umount" ;; + esac + if [[ $when == *mover* ]]; then + PATH=$T/wrap:$PATH run_moves 'processTheMoves did not return' + stop_done + else + run_moves + fi + private=$(find "$TMPDIR" -maxdepth 1 -name 'ca.mover.tuning.*') + case $when in + before*) calls=$(sed '$d' <<<"$REMOUNTED" | sed '$d'; echo 'zfs mount cache/sh') ;; + *fails) calls=$(sed '$d' <<<"$DESTROYED"; echo 'umount PRIVATE') ;; + *) calls=$(sed '$d' <<<"$DESTROYED"; printf '%s\n' 'umount PRIVATE' 'zfs mount cache/sh') ;; + esac + check "zfs calls" "$calls" "$(cat "$T/zfs.calls")" + log_lacks 'successfully destroyed' + # a stop after the kill ends the run once the dataset is back; the cut-short check is still reported + [[ $when != *mover* ]] || log_lacks 'top-level' + if [[ $when == *fails ]]; then + notices "$(read_only_notice "$private")" + log_has "ZFS dataset [cache/sh] is still mounted read-only at $private, not at /mnt/cache/sh: umount: $private: zfs.fail" + log_has "ZFS dataset [cache/sh]: mounted read-only at $private: stop writes to the share, umount $private, $BACK" + check "the dataset stays at the private folder" "$private"$'\t'cache/sh "$(cat "$T/zfs.private")" + continue + fi + notices "$NOTICE" + log_has 'ZFS dataset [cache/sh] could not be checked once unmounted, will not delete: the check was cut short' + mounted_again + no_private +done + +# a scan's subshell killed outright, its caller not: it printed nothing because it never looked. The first check keeps +# the dataset mounted; the one at the private mount, where a file landed as it unmounted, keeps it and mounts it back +SCAN=". -mindepth 1 -path ./.zfs -prune -o ! -type d -print -quit" +for which in 'first check' 'check at the private mount'; do + begin "Clean ZFS datasets, the scan of the $which is killed" cleanFolders topFolder cleanDatasets yes + one_share + wrap_hook find "$SCAN" + if [ "$which" = 'first check' ]; then + kill_hook KILL : >"$T/find.hook" + else + kill_hook KILL : 1 >"$T/kill.hook" + printf '%s\n' 'echo x >/mnt/cache/sh/new.txt' "cp \"$T/kill.hook\" \"$T/find.hook\"" >"$T/zfs.on_unmount" + fi + PATH=$T/wrap:$PATH run_moves + log_lacks 'successfully destroyed' + if [ "$which" = 'first check' ]; then + check "zfs calls" "zfs $LS cache/sh" "$(cat "$T/zfs.calls")" + log_lacks 'attempting to unmount' + notices '' + continue + fi + check "zfs calls" "$REMOUNTED" "$(cat "$T/zfs.calls")" + log_has 'ZFS dataset [cache/sh] could not be checked once unmounted, will not delete: the check was cut short' + notices "$NOTICE" + mounted_again + cache_is sh sh/new.txt + no_private +done + +# a file lands in the folder as the dataset is mounted back. The look after the mount killed printed nothing because it +# never looked; the whole remount killed leaves the run unable to tell whether the mount happened +# Notify errors only: a failure still sends the notice, which alone carries the steps when action logging is off +for what in look remount; do + begin "Clean ZFS datasets, the $what at the mount back is killed" cleanFolders topFolder cleanDatasets yes notify errorsOnly + one_share + echo 'echo x >/mnt/cache/sh/new.txt' >"$T/zfs.on_unmount" + echo 'echo y >/mnt/cache/sh/late.txt' >"$T/zfs.on_mount" + wrap_hook find ". -mindepth 1 -print -quit" + if [ "$what" = look ]; then + cat >"$T/find.hook" <<'EOF' +rm -f "$0" +kill -KILL "$PPID" +EOF + else + kill_hook KILL : >"$T/find.hook" + fi + PATH=$T/wrap:$PATH run_moves + check "zfs calls" "$REMOUNTED" "$(cat "$T/zfs.calls")" + if [ "$what" = look ]; then + why="mounted again, but the look for a file written to /mnt/cache/sh as it was mounted was cut short, so one may be hidden under it: stop writes to the share, zfs unmount cache/sh, $BACK" + else + why="the remount was cut short, so it may not be mounted or may hide a file: stop writes to the share, if zfs mount lists it at /mnt/cache/sh run zfs unmount cache/sh, $BACK" + fi + log_has "ZFS dataset [cache/sh]: $why" + log_lacks 'Failed to remount' + notices "$(notice_for "[cache/sh] ($why)")" + mounted_again + cache_is sh sh/new.txt + no_private +done + +finish diff --git a/tests/age_mover/test_datasets.sh b/tests/age_mover/test_datasets.sh new file mode 100644 index 00000000..2f214840 --- /dev/null +++ b/tests/age_mover/test_datasets.sh @@ -0,0 +1,501 @@ +#!/bin/bash +# Clean ZFS datasets: after the pass, a share's dataset is destroyed only when nothing in it would be lost. +. "$(dirname "$0")/lib.sh" + +# the half of the unreadable-subfolder case that runs as a plain user, since root lists any folder +if [ "${1:-}" = --as-tester ]; then + CASE=$2 + fresh cleanFolders topFolder cleanDatasets yes + if [ "${3:-}" = private ]; then + # only the check at the private mount meets sh/locked, which zfs.on_unmount made; the top-folder check's two follow + run_moves "$(printf '%s\n' "find: './locked': Permission denied" "find: '/mnt/cache/sh/locked': Permission denied" \ + "find: '/mnt/cache/sh/locked': Permission denied")" + log_has 'ZFS dataset [cache/sh] could not be checked once unmounted, will not delete: find: the dataset could not be read' + log_lacks 'found something a destroy could lose' + [ "$FAILS" = 0 ] + exit + fi + # the dataset check's find, then the top-folder check's two, cannot list sh/locked + run_moves "$(printf '%s\n' "find: './locked': Permission denied" "find: '/mnt/cache/sh/locked': Permission denied" \ + "find: '/mnt/cache/sh/locked': Permission denied")" + log_lacks 'ZFS dataset [cache/sh]' + [ "${AGE_MOVER_DEBUG:-0}" != 2 ] || dlog_has 'Keeping ZFS dataset [cache/sh]: a destroy could lose "/mnt/cache/sh"' + [ "$FAILS" = 0 ] + exit +fi + +# the destroy goes ahead only when it loses nothing: each entry left is a folder the array also has +for left in nothing 'a middle folder the array has' '.zfs, as snapdir=visible shows it,' 'a file' 'a file beside it' 'a symlink' \ + 'an empty folder the array lacks' 'a nested .zfs folder the array lacks'; do + begin "Clean ZFS datasets, $left left in the share" cleanFolders topFolder cleanDatasets yes + f=sh/only/f.txt + [ "$left" = 'a middle folder the array has' ] && f=sh/a/b/f.txt + mk cache "$f" + case $left in + 'a file') mk cache sh/keep/k.txt; kept=(sh/keep sh/keep/k.txt) ;; + 'a file beside it') mk cache sh/only/g.txt; kept=(sh/only sh/only/g.txt) ;; + 'a symlink') ln -s /nowhere /mnt/cache/sh/link; kept=(sh/link) ;; + 'an empty folder'*) mkdir /mnt/cache/sh/e; kept=(sh/e) ;; + .zfs*) mkdir -p /mnt/cache/sh/.zfs/snapshot /mnt/cache/sh/.zfs/shares ;; + 'a nested .zfs'*) mkdir /mnt/cache/sh/only/.zfs; kept=(sh/only sh/only/.zfs) ;; + esac + printf '%s\n' /mnt/cache /mnt/cache/sh >"$T/zfs" + row 'move from primary' f "$f" | list + run_moves + if [ "$f" = sh/a/b/f.txt ]; then array_is sh sh/a sh/a/b "$f"; else array_is sh sh/only "$f"; fi + case $left in + nothing | 'a middle'* | .zfs*) + check "zfs calls" "$DESTROYED" "$(cat "$T/zfs.calls")" + log_has 'ZFS dataset [cache/sh] successfully destroyed.' + cache_is + no_private + log_lacks 'top-level' + ;; + *) + if [ "$left" = 'a file beside it' ]; then calls=; else calls="zfs $LS cache/sh"; fi + check "zfs calls" "$calls" "$(cat "$T/zfs.calls" 2>/dev/null)" + log_lacks 'ZFS dataset [cache/sh]' + cache_is sh "${kept[@]}" + if [ "${AGE_MOVER_DEBUG:-0}" != 2 ]; then + : + elif [ "$left" = 'a file beside it' ]; then + # the row's folder keeps a file, so the row notes no dataset + dlog_lacks 'Keeping ZFS dataset' + else + dlog_has "Keeping ZFS dataset [cache/sh]: a destroy could lose \"/mnt/cache/${kept[-1]}\"" + fi + ;; + esac +done + +# zfs lists before the content check, so that check sees a file written while it lists +begin "Clean ZFS datasets, a file lands in the share while zfs lists its children" cleanFolders topFolder cleanDatasets yes +mk cache sh/only/f.txt +printf '%s\n' /mnt/cache /mnt/cache/sh >"$T/zfs" +echo 'echo x >/mnt/cache/sh/new.txt' >"$T/zfs.on_list" +row 'move from primary' f sh/only/f.txt | list +run_moves +check "zfs calls" "zfs $LS cache/sh" "$(cat "$T/zfs.calls")" +cache_is sh sh/new.txt +[ "${AGE_MOVER_DEBUG:-0}" != 2 ] || dlog_has 'Keeping ZFS dataset [cache/sh]: a destroy could lose "/mnt/cache/sh/new.txt"' + +# a file written after the content check, as zfs unmounts, is in the dataset: the check at the private mount keeps it +begin "Clean ZFS datasets, a file lands in the share while zfs unmounts it" cleanFolders topFolder cleanDatasets yes +mk cache sh/only/f.txt +printf '%s\n' /mnt/cache /mnt/cache/sh >"$T/zfs" +echo 'echo x >/mnt/cache/sh/new.txt' >"$T/zfs.on_unmount" +row 'move from primary' f sh/only/f.txt | list +run_moves +check "zfs calls" "$(sed '$d' <<<"$DESTROYED"; echo 'zfs mount cache/sh')" "$(cat "$T/zfs.calls")" +log_has 'Keeping ZFS dataset [cache/sh]: the check after the unmount found something a destroy could lose.' +log_lacks 'successfully destroyed' +log_lacks 'Failed to' +cache_is sh sh/new.txt +no_private +notices '' +[ "${AGE_MOVER_DEBUG:-0}" != 2 ] || dlog_has 'Keeping ZFS dataset [cache/sh]: a destroy could lose "/mnt/cache/sh/new.txt"' + +# the same, and the remount cannot follow: the share then lacks the dataset's files, which even errorsOnly hears of. A write +# through /mnt/user lands in the bare folder while the dataset is away, and a mount over it would hide it +for after in 'a file lands in its bare folder' 'zfs mount fails'; do + begin "Clean ZFS datasets, a file lands in the dataset as zfs unmounts it, and $after" cleanFolders topFolder \ + cleanDatasets yes notify errorsOnly + mk cache sh/only/f.txt + printf '%s\n' /mnt/cache /mnt/cache/sh >"$T/zfs" + echo 'echo x >/mnt/cache/sh/new.txt' >"$T/zfs.on_unmount" + if [ "$after" = 'zfs mount fails' ]; then + echo mount >"$T/zfs.fail" + else + echo 'echo y >/mnt/cache/sh/bare.txt' >"$T/zfs.on_mount.zfs" + fi + row 'move from primary' f sh/only/f.txt | list + run_moves + log_has 'Keeping ZFS dataset [cache/sh]: the check after the unmount found something a destroy could lose.' + log_has 'Failed to remount dataset [cache/sh]' + log_has "ZFS dataset [cache/sh]: not mounted: stop writes to the share, $BACK" + check "the unmounted dataset keeps its file" new.txt "$(ls "$T/zfs.store/cache/sh")" + no_private + notices "$NOT_MOUNTED" + if [ "$after" = 'zfs mount fails' ]; then + check "zfs calls" "$(sed '$d' <<<"$DESTROYED"; echo 'zfs mount cache/sh')" "$(cat "$T/zfs.calls")" + log_has 'zfs: zfs.fail' + else + check "zfs calls" "$(sed '$d' <<<"$DESTROYED")" "$(cat "$T/zfs.calls")" + log_has 'Not remounting ZFS dataset [cache/sh]: its folder /mnt/cache/sh holds files that a mount would hide' + cache_is sh sh/bare.txt + fi +done + +# a file written between the look into the bare folder and the mount: the mount hides it, so the log says where it is +begin "Clean ZFS datasets, a file lands in the dataset as zfs unmounts it, and in its folder as zfs mounts it back" \ + cleanFolders topFolder cleanDatasets yes notify errorsOnly +mk cache sh/only/f.txt +printf '%s\n' /mnt/cache /mnt/cache/sh >"$T/zfs" +echo 'echo x >/mnt/cache/sh/new.txt' >"$T/zfs.on_unmount" +echo 'echo y >/mnt/cache/sh/late.txt' >"$T/zfs.on_mount" +row 'move from primary' f sh/only/f.txt | list +run_moves +check "zfs calls" "$(sed '$d' <<<"$DESTROYED"; echo 'zfs mount cache/sh')" "$(cat "$T/zfs.calls")" +log_has 'ZFS dataset [cache/sh] is mounted again, but /mnt/cache/sh/late.txt, written as it was mounted, is hidden under it' +log_has "ZFS dataset [cache/sh]: a file is hidden under it: stop writes to the share, zfs unmount cache/sh, $BACK" +cache_is sh sh/new.txt +no_private +notices "$HIDDEN" + +# a folder gone by the remount is made again before the mount and looked in; the run looks nowhere else +begin "Clean ZFS datasets, a file lands in the dataset as zfs unmounts it, and its folder is gone by the remount" \ + cleanFolders topFolder cleanDatasets yes +mk cache sh/only/f.txt +printf '%s\n' /mnt/cache /mnt/cache/sh >"$T/zfs" +echo 'echo x >/mnt/cache/sh/new.txt' >"$T/zfs.on_unmount" +echo 'rmdir /mnt/cache/sh' >"$T/zfs.on_umount" +touch "$T/cwd/elsewhere.txt" +row 'move from primary' f sh/only/f.txt | list +run_moves +rm -f "$T/cwd/elsewhere.txt" +check "zfs calls" "$(sed '$d' <<<"$DESTROYED"; echo 'zfs mount cache/sh')" "$(cat "$T/zfs.calls")" +log_lacks 'hidden under it' +log_lacks 'Failed to' +cache_is sh sh/new.txt +no_private +notices '' + +# a write through /mnt/user makes the gone folder again as zfs mounts the dataset: the mount hides it, and the run says so +begin "Clean ZFS datasets, its folder is gone by the remount, and a file lands in it again as zfs mounts it back" \ + cleanFolders topFolder cleanDatasets yes notify errorsOnly +mk cache sh/only/f.txt +printf '%s\n' /mnt/cache /mnt/cache/sh >"$T/zfs" +echo 'echo x >/mnt/cache/sh/new.txt' >"$T/zfs.on_unmount" +echo 'rmdir /mnt/cache/sh' >"$T/zfs.on_umount" +echo 'mkdir -p /mnt/cache/sh && echo y >/mnt/cache/sh/late.txt' >"$T/zfs.on_mount" +row 'move from primary' f sh/only/f.txt | list +run_moves +check "zfs calls" "$(sed '$d' <<<"$DESTROYED"; echo 'zfs mount cache/sh')" "$(cat "$T/zfs.calls")" +log_has 'ZFS dataset [cache/sh] is mounted again, but /mnt/cache/sh/late.txt, written as it was mounted, is hidden under it' +cache_is sh sh/new.txt +no_private +notices "$HIDDEN" + +# a file where the gone folder was: no folder to look in, so no mount +begin "Clean ZFS datasets, its folder is gone by the remount and a file has its name" \ + cleanFolders topFolder cleanDatasets yes notify errorsOnly +mk cache sh/only/f.txt +printf '%s\n' /mnt/cache /mnt/cache/sh >"$T/zfs" +echo 'echo x >/mnt/cache/sh/new.txt' >"$T/zfs.on_unmount" +echo 'rmdir /mnt/cache/sh && touch /mnt/cache/sh' >"$T/zfs.on_umount" +row 'move from primary' f sh/only/f.txt | list +run_moves +check "zfs calls" "$(sed '$d' <<<"$DESTROYED")" "$(cat "$T/zfs.calls")" +log_has 'Failed to remount dataset [cache/sh]' +log_has 'cannot enter its folder /mnt/cache/sh' +check "the unmounted dataset keeps its file" new.txt "$(ls "$T/zfs.store/cache/sh")" +no_private +notices "$NOT_MOUNTED" +rm -f /mnt/cache/sh + +# mount.zfs can make the read-only mount and still fail, and umount can take it off and still fail: the mount table +# decides, so the run unmounts the dataset from the private folder if it is there and mounts it back +for late in '' ', and so is its unmount'; do + begin "Clean ZFS datasets, the read-only mount is made but reported as failed$late" cleanFolders topFolder cleanDatasets yes + mk cache sh/only/f.txt + printf '%s\n' /mnt/cache /mnt/cache/sh >"$T/zfs" + echo mount.zfs.late >"$T/zfs.fail" + [ -z "$late" ] || echo umount.late >>"$T/zfs.fail" + row 'move from primary' f sh/only/f.txt | list + run_moves + check "zfs calls" "$(sed '$d' <<<"$DESTROYED"; echo 'zfs mount cache/sh')" "$(cat "$T/zfs.calls")" + log_has "ZFS dataset [cache/sh] could not be checked once unmounted, will not delete: mount: filesystem 'cache/sh' was mounted, but /etc/mtab could not be updated" + log_lacks 'still mounted read-only' + log_lacks 'Failed to remount' + check "the dataset is mounted at its folder again" /mnt/cache/sh "$(grep -x /mnt/cache/sh "$T/zfs")" + no_private + notices "$NOTICE" +done + +# one notice for the run at its worst level: an unmount that fails, then a check that fails, still reach errorsOnly +begin "Clean ZFS datasets, two datasets fail" cleanFolders topFolder cleanDatasets yes notify errorsOnly +mk cache a/only/f.txt sh/only/g.txt +printf '%s\n' /mnt/cache /mnt/cache/a /mnt/cache/sh >"$T/zfs" +# cache/a leaves the mount table as zfs starts to unmount it; cache/sh unmounts, then its read-only mount fails +printf "sed -i '\\|^/mnt/cache/a$|d' %q\n" "$T/zfs" >"$T/zfs.on_unmount" +echo mount.zfs >"$T/zfs.fail" +{ row 'move from primary' f a/only/f.txt; row 'move from primary' f sh/only/g.txt; } | list +run_moves +log_has 'Failed to unmount ZFS dataset [cache/a]' +log_has 'zfs: not currently mounted' +log_has "ZFS dataset [cache/sh] could not be checked once unmounted, will not delete: mount: filesystem 'cache/sh' cannot be mounted, zfs.fail" +notices "$(notice_for '[cache/a] [cache/sh]')" +no_private + +# the kept name never passed the planner: a newline in it must not end the debug line before debug_mover mangles it +begin "Clean ZFS datasets, a file named with a newline left in the share" cleanFolders topFolder cleanDatasets yes +mk cache sh/only/f.txt +printf 'x\n' >$'/mnt/cache/sh/Tax\nSecret.pdf' +printf '%s\n' /mnt/cache /mnt/cache/sh >"$T/zfs" +row 'move from primary' f sh/only/f.txt | list +run_moves +check "zfs calls" "zfs $LS cache/sh" "$(cat "$T/zfs.calls")" +if [ "${AGE_MOVER_DEBUG:-0}" = 2 ]; then + sed -n "/^cat >\"\$ANONAWK\" <<'ANONEOF'\$/,/^ANONEOF\$/p" "$PLUGIN/debug_mover" | sed '1d;$d' >"$T/anon.awk" + anon=$(gawk -v POOLS='user user0 cache' -v SHARES=sh -v LIST=0 -f "$T/anon.awk" "$MOVER_DEBUG_LOG") + check "debug_mover mangles the whole name" 'could lose "/mnt/cache/sh/-----------.pdf"' "$(grep -o 'could lose .*' <<<"$anon")" +fi + +# a folder row that empties the share notes its dataset as a file row does, with Clean empty folders on only +for clean in topFolder no; do + begin "Clean ZFS datasets, Clean empty folders $clean, a folder row empties the share" cleanFolders $clean cleanDatasets yes + mkdir -p /mnt/cache/sh/new + printf '%s\n' /mnt/cache /mnt/cache/sh >"$T/zfs" + row 'move from primary' d sh/new | list + run_moves + array_is sh sh/new + if [ $clean = no ]; then calls=; else calls=$DESTROYED; fi + check "zfs calls" "$calls" "$(cat "$T/zfs.calls" 2>/dev/null)" + if [ $clean = no ]; then cache_is sh; else cache_is; fi +done + +for has in 'a snapshot' 'another name'; do + begin "Clean ZFS datasets, the share's dataset has $has" cleanFolders topFolder cleanDatasets yes + mk cache sh/only/f.txt + row 'move from primary' f sh/only/f.txt | list + if [ "$has" = 'a snapshot' ]; then + printf '%s\n' /mnt/cache /mnt/cache/sh >"$T/zfs" + echo cache/sh@daily >"$T/zfs.children" + # as snapdir=visible shows it: the content check skips .zfs, so the snapshot is what keeps the dataset + mk cache sh/.zfs/snapshot/daily/f.txt + run_moves + check "zfs calls" "zfs $LS cache/sh" "$(cat "$T/zfs.calls")" + log_has 'ZFS dataset [cache/sh] has child datasets or snapshots, will not delete...' + cache_is sh sh/.zfs sh/.zfs/snapshot sh/.zfs/snapshot/daily sh/.zfs/snapshot/daily/f.txt + else + # only dataset pool/share at /mnt/pool/share is destroyed; another dataset mounted there is kept + printf '/mnt/cache\n/mnt/cache/sh\tcache/data/sh\n' >"$T/zfs" + run_moves + check "no zfs calls" "" "$(cat "$T/zfs.calls" 2>/dev/null)" + log_lacks 'ZFS dataset [' + cache_is sh + [ "${AGE_MOVER_DEBUG:-0}" != 2 ] || dlog_has 'Keeping the ZFS dataset mounted at "/mnt/cache/sh": it is not cache/sh' + fi +done + +# once per share, after the pass, and only for rows that emptied a folder on the primary +begin "Clean ZFS datasets, a pass empties two folders of a share that keeps a file" cleanFolders topFolder cleanDatasets yes +mk cache sh/a/f.txt sh/b/g.txt sh/keep/k.txt +printf '%s\n' /mnt/cache /mnt/cache/sh >"$T/zfs" +{ row 'move from primary' f sh/a/f.txt; row 'move from primary' f sh/b/g.txt; } | list +run_moves +check "zfs calls" "zfs $LS cache/sh" "$(cat "$T/zfs.calls")" +cache_is sh sh/keep sh/keep/k.txt + +begin "Clean ZFS datasets, a .placeholder keeps the folder after a row that emptied another share's" cleanFolders topFolder cleanDatasets yes +mk cache a/x/f.txt sh/y/g.txt sh/y/.placeholder +printf '%s\n' /mnt/cache /mnt/cache/sh >"$T/zfs" +{ row 'move from primary' f a/x/f.txt; row 'move from primary' f sh/y/g.txt; } | list +run_moves +check "no zfs calls" "" "$(cat "$T/zfs.calls" 2>/dev/null)" +cache_is sh sh/y sh/y/.placeholder + +begin "Clean ZFS datasets, a move from the secondary empties its folder on the array" cleanFolders topFolder cleanDatasets yes +mk disk1 sh/only/f.txt +printf '%s\n' /mnt/cache /mnt/cache/sh >"$T/zfs" +row 'move from secondary' f sh/only/f.txt | list +run_moves +check "no zfs calls" "" "$(cat "$T/zfs.calls" 2>/dev/null)" +cache_is sh sh/only sh/only/f.txt + +# test mode never destroys a dataset, even when the row's folder counts empty: here its file is gone before the run +begin "Clean ZFS datasets in test mode, the row's file gone before the run" cleanFolders topFolder cleanDatasets yes testmode yes +mk cache sh/f.txt +printf '%s\n' /mnt/cache /mnt/cache/sh >"$T/zfs" +row 'move from primary' f sh/f.txt | list +rm /mnt/cache/sh/f.txt +run_moves +check "no zfs calls" "" "$(cat "$T/zfs.calls" 2>/dev/null)" +cache_is sh +log_has 'TEST MODE: Would check ZFS dataset [cache/sh] for deletion' +log_has 'Skipping deletion of ZFS dataset mountpoint: /mnt/cache/sh' + +# test mode says it would check the dataset a real run would, and runs no zfs command +begin "Clean ZFS datasets in test mode, the share's last file would move" cleanFolders topFolder cleanDatasets yes testmode yes +mk cache sh/only/f.txt +printf '%s\n' /mnt/cache /mnt/cache/sh >"$T/zfs" +row 'move from primary' f sh/only/f.txt | list +run_moves +check "no zfs calls" "" "$(cat "$T/zfs.calls" 2>/dev/null)" +cache_is sh sh/only sh/only/f.txt +log_has 'TEST MODE: Would check ZFS dataset [cache/sh] for deletion' + +begin "Clean ZFS datasets in test mode, the share a plain folder on a ZFS pool" cleanFolders topFolder cleanDatasets yes \ + testmode yes +mk cache sh/only/f.txt +echo /mnt/cache >"$T/zfs" +row 'move from primary' f sh/only/f.txt | list +run_moves +check "no zfs calls" "" "$(cat "$T/zfs.calls" 2>/dev/null)" +log_lacks 'Would check ZFS dataset' + +for pool in 'not ZFS' 'ZFS, the share a plain folder on it'; do + begin "Clean ZFS datasets, a share that empties on a pool that is $pool" cleanFolders topFolder cleanDatasets yes + mk cache sh/only/f.txt + [ "$pool" = 'not ZFS' ] || echo /mnt/cache >"$T/zfs" + row 'move from primary' f sh/only/f.txt | list + run_moves + check "no zfs calls" "" "$(cat "$T/zfs.calls" 2>/dev/null)" + cache_is + log_has 'Deleted empty top-level folder: /mnt/cache/sh' + [ "${AGE_MOVER_DEBUG:-0}" != 2 ] || dlog_lacks 'Keeping' +done + +# errorsOnly sends only a failure: a failed unmount, destroy or remount, or a dataset left at the private folder, notifies; +# a check that cannot run only warns +for fail in list unmount 'unmount, busy,' destroy 'destroy and mount' 'destroy, busy,' 'the read-only mount' \ + 'the read-only mount, busy,' 'the read-only unmount' 'the read-only unmount, after unmounting,' mktemp; do + what="zfs $fail" + [[ $fail != the* && $fail != mktemp ]] || what=$fail + begin "Clean ZFS datasets, $what fails" cleanFolders topFolder cleanDatasets yes notify errorsOnly + mk cache sh/only/f.txt + printf '%s\n' /mnt/cache /mnt/cache/sh >"$T/zfs" + case $fail in + 'destroy and mount') printf '%s\n' destroy mount ;; + 'unmount, busy,') echo unmount; echo 'pool or dataset is busy' >"$T/zfs.reason" ;; + 'destroy, busy,') echo destroy; echo 'dataset is busy' >"$T/zfs.reason" ;; + 'the read-only mount') echo mount.zfs ;; + # as OpenZFS says it while a container's mount holds the dataset + 'the read-only mount, busy,') echo mount.zfs; echo 'zfs_mount_at() failed: mountpoint or dataset is busy' >"$T/zfs.reason" ;; + 'the read-only unmount') echo umount ;; + 'the read-only unmount, after unmounting,') echo umount.late ;; + mktemp) ;; + *) echo "$fail" ;; + esac >"$T/zfs.fail" + row 'move from primary' f sh/only/f.txt | list + # age_mover's stderr is discarded in use, so zfs's reason goes to the log, without the child zfs names after it + if [ "$fail" = mktemp ]; then TMPDIR=/nowhere run_moves; else run_moves; fi + private=$(find "${TMPDIR:-/tmp}" -maxdepth 1 -name 'ca.mover.tuning.*') + unchecked="ZFS dataset [cache/sh] could not be checked once unmounted, will not delete:" + case $fail in + list) log_has "ZFS dataset [cache/sh] could not be listed, will not delete: zfs.fail" ;; + 'the read-only mount') log_has "$unchecked mount: filesystem 'cache/sh' cannot be mounted, zfs.fail" ;; + 'the read-only unmount') + log_has "ZFS dataset [cache/sh] is still mounted read-only at $private, not at /mnt/cache/sh: umount: $private: zfs.fail" + log_has "ZFS dataset [cache/sh]: mounted read-only at $private: stop writes to the share, umount $private, $BACK" + ;; + # unmounted after all: what the check found was lost with umount's answer, so the dataset is mounted back + *after\ unmounting*) + check "the late umount's reason" 1 "$(log | grep -F -- "$unchecked umount: ${TMPDIR:-/tmp}/ca.mover.tuning." | + grep -cF ': filesystem was unmounted, but failed to update userspace mount table')" + ;; + mktemp) log_has "$unchecked mktemp: No such file or directory"; log_lacks 'attempting to unmount' ;; + # the failure notice goes out with the "Failed to" line + *busy*) + log_has "ZFS dataset [cache/sh] is busy, will not delete: a process or another mount, such as a container's, may hold it." + log_lacks "Failed to ${fail%%,*}" + log_lacks "$unchecked" + ;; + *) log_has "Failed to ${fail%% *} ZFS dataset [cache/sh]"; log_has 'zfs: zfs.fail' ;; + esac + log_lacks 'cache/sh/child' + array_is sh sh/only sh/only/f.txt + # the row still logs and counts what it moved + log_has '0 files remaining from caches to array' + counter REMAINING_CACHE_FILES 0 + # with action logging off the notice is all there is, so it says why a dataset is out of view and how to mount it back + case $fail in + unmount | destroy) notices "$NOTICE" ;; + 'destroy and mount') notices "$NOT_MOUNTED" ;; + 'the read-only unmount') notices "$(read_only_notice "$private")" ;; + *) notices '' ;; + esac + if [ "$fail" = 'destroy and mount' ]; then + log_has 'Failed to remount dataset [cache/sh]' + log_count 2 'zfs: zfs.fail' + no_private + continue + fi + # an unmount that fails leaves the dataset at the private folder, which zfs mount would refuse + if [ "$fail" = 'the read-only unmount' ]; then + check "the dataset stays at the private folder" "$private"$'\t'cache/sh "$(cat "$T/zfs.private")" + check "zfs calls" "$(sed '$d' <<<"$DESTROYED")" "$(cat "$T/zfs.calls")" + log_lacks 'Failed to remount' + continue + fi + no_private + # the dataset is mounted at the end, so its top folder stays + cache_is sh + log_lacks 'Failed to remount' + log_has 'Skipping deletion of ZFS dataset mountpoint: /mnt/cache/sh' +done + +# a write through /mnt/user while the dataset is unmounted lands in its bare folder, which a remount would hide +begin "Clean ZFS datasets, a file lands in the unmounted share's folder before a failed destroy" cleanFolders topFolder \ + cleanDatasets yes +mk cache sh/only/f.txt +printf '%s\n' /mnt/cache /mnt/cache/sh >"$T/zfs" +echo destroy >"$T/zfs.fail" +echo 'echo x >/mnt/cache/sh/new.txt' >"$T/zfs.on_destroy" +row 'move from primary' f sh/only/f.txt | list +run_moves +check "zfs calls" "$DESTROYED" "$(cat "$T/zfs.calls")" +log_has 'Failed to remount dataset [cache/sh]' +log_has 'Not remounting ZFS dataset [cache/sh]: its folder /mnt/cache/sh holds files that a mount would hide' +cache_is sh sh/new.txt +no_private +notices "$NOT_MOUNTED" + +# a write through /mnt/user during the check lands in the bare folder: the destroy goes ahead, and OpenZFS keeps a folder +# that is not empty +begin "Clean ZFS datasets, a file lands in the unmounted share's folder during the check" cleanFolders topFolder cleanDatasets yes +mk cache sh/only/f.txt +printf '%s\n' /mnt/cache /mnt/cache/sh >"$T/zfs" +echo 'echo y >/mnt/cache/sh/bare.txt' >"$T/zfs.on_mount.zfs" +row 'move from primary' f sh/only/f.txt | list +run_moves +check "zfs calls" "$DESTROYED" "$(cat "$T/zfs.calls")" +log_has 'ZFS dataset [cache/sh] successfully destroyed.' +cache_is sh sh/bare.txt +no_private +notices '' + +# only a reason that ends in busy is a hold: mount.zfs's message names the dataset, here one with busy in its name +begin "Clean ZFS datasets, the read-only mount of a dataset named busybox fails" cleanFolders topFolder cleanDatasets yes +mk cache busybox/only/f.txt +printf '%s\n' /mnt/cache /mnt/cache/busybox >"$T/zfs" +echo mount.zfs >"$T/zfs.fail" +row 'move from primary' f busybox/only/f.txt | list +run_moves +log_has "ZFS dataset [cache/busybox] could not be checked once unmounted, will not delete: mount: filesystem 'cache/busybox' cannot be mounted, zfs.fail" +log_lacks 'is busy' +notices "$(notice_for '[cache/busybox]')" + +id tester >/dev/null 2>&1 || useradd -M tester +U=/tmp/age_mover_tester +# a find that fails keeps the dataset: the file the plain user cannot see would go with it +begin "Clean ZFS datasets, a subfolder a plain-user mover cannot list" cleanFolders topFolder cleanDatasets yes +mk cache sh/only/f.txt sh/locked/k.txt +rm -rf "$U" && mkdir -p "$U" +printf '%s\n' /mnt/cache /mnt/cache/sh >"$U/zfs" +row 'move from primary' f sh/only/f.txt | { echo "$HDR"; cat; } >"$U/actions" +chown -R tester /mnt/cache /mnt/user0 "$U" +chmod 0333 /mnt/cache/sh/locked +runuser -u tester -- env AGE_MOVER_TEST=1 AGE_MOVER_DEBUG="${AGE_MOVER_DEBUG:-0}" T="$U" bash "$0" --as-tester "$CASE" +check "the checks run as the plain user pass" 0 "$?" +check "zfs calls" "zfs $LS cache/sh" "$(cat "$U/zfs.calls" 2>/dev/null)" +[ ! -d /mnt/cache/sh/locked ] || chmod 0755 /mnt/cache/sh/locked +cache_is sh sh/locked sh/locked/k.txt + +# a check at the private mount that cannot read the dataset counts as one that could not run, not as a file a destroy loses +begin "Clean ZFS datasets, a subfolder a plain-user mover cannot list lands in the dataset as it unmounts" cleanFolders \ + topFolder cleanDatasets yes +mk cache sh/only/f.txt +rm -rf "$U" && mkdir -p "$U" +printf '%s\n' /mnt/cache /mnt/cache/sh >"$U/zfs" +echo 'mkdir -m 0333 /mnt/cache/sh/locked' >"$U/zfs.on_unmount" +row 'move from primary' f sh/only/f.txt | { echo "$HDR"; cat; } >"$U/actions" +chown -R tester /mnt/cache /mnt/user0 "$U" +runuser -u tester -- env AGE_MOVER_TEST=1 AGE_MOVER_DEBUG="${AGE_MOVER_DEBUG:-0}" T="$U" bash "$0" --as-tester "$CASE" private +check "the checks run as the plain user pass" 0 "$?" +check "zfs calls" "$(sed '$d' <<<"$DESTROYED"; echo 'zfs mount cache/sh')" "$(cat "$U/zfs.calls" 2>/dev/null)" +[ ! -d /mnt/cache/sh/locked ] || chmod 0755 /mnt/cache/sh/locked +cache_is sh sh/locked +TMPDIR=$U/tmp no_private + +finish diff --git a/tests/age_mover/test_folders.sh b/tests/age_mover/test_folders.sh new file mode 100644 index 00000000..e51988ed --- /dev/null +++ b/tests/age_mover/test_folders.sh @@ -0,0 +1,468 @@ +#!/bin/bash +# The folder cleanup after each row and the top-folder check after the pass: Clean Folders no / yes / topFolder, Move +# empty folders, and test mode's predictions of them. Clean ZFS datasets: test_datasets.sh. +. "$(dirname "$0")/lib.sh" + +# the half of an unreadable-folder case that runs as a plain user, since root lists any folder +if [ "${1:-}" = --as-tester ]; then + CASE=$2 + fresh cleanFolders topFolder + # today find's error on the unreadable top folder reaches stderr, once for its files and once for its subfolders + run_moves "$(printf "find: '/mnt/cache/sh': Permission denied\n%.0s" 1 2)" + log_has 'Deleted empty folder: /mnt/cache/sh/only' + if [ "$3" = yes ]; then log_lacks 'top-level'; else log_has 'Deleted empty top-level folder: /mnt/cache/sh'; fi + [ "$FAILS" = 0 ] + exit +fi + +# a case's folder lines, a test-mode prediction written as the line a real run logs +folder_lines() { + log | grep -E 'empty (top-level |moved )?folder: |^Not deleting |^Skipping deletion ' | + sed -e 's/^TEST MODE: Would delete moved empty folder/Deleted empty moved folder/' -e 's/^TEST MODE: Would delete empty/Deleted empty/' +} +# same_in_test_mode ...: setup's shape runs for real, whose folder lines must be +# these, then in test mode, which must predict each of them and change nothing +same_in_test_mode() { + local name=$1 want=$2 setup=$3 real tree + shift 3 + begin "$name" "$@" + "$setup" + run_moves + real=$(folder_lines) + check "the real run's folder lines" "$want" "$real" + begin "$name, test mode" "$@" testmode yes + "$setup" + tree=$(find /mnt | sort) + run_moves + check "test mode predicts the real run's folder lines" "$real" "$(folder_lines)" + check "test mode leaves the disks as they were" "$tree" "$(find /mnt | sort)" + log_lacks 'Deleted empty' +} + +for cf in no yes topFolder; do + begin "Clean Folders $cf, a share that empties" cleanFolders "$cf" + mk cache sh/only/f.txt sh/only/g.txt + { row 'move from primary' f sh/only/f.txt; row 'move from primary' f sh/only/g.txt; } | list + run_moves + array_is sh sh/only sh/only/f.txt sh/only/g.txt + case $cf in + no) cache_is sh sh/only; log_lacks 'Deleted' ;; + yes) cache_is sh; log_has 'Deleted empty folder: /mnt/cache/sh/only'; log_lacks 'top-level' ;; + topFolder) cache_is; log_has 'Deleted empty top-level folder: /mnt/cache/sh' ;; + esac + [ "$cf" = no ] || log_has 'Not deleting folder containing 1 files: /mnt/cache/sh/only' +done + +# the share's top folder is the top-folder check's, after the pass: Yes never deletes it +for cf in yes topFolder; do + begin "Clean Folders $cf, a file in the share's top folder" cleanFolders "$cf" + mk cache sh/f.txt + row 'move from primary' f sh/f.txt | list + run_moves + array_is sh sh/f.txt + log_lacks 'Deleted empty folder: /mnt/cache/sh' + if [ "$cf" = yes ]; then + cache_is sh + log_lacks 'top-level' + else + cache_is + log_has 'Deleted empty top-level folder: /mnt/cache/sh' + fi +done + +begin "topFolder, a share that keeps a file elsewhere" cleanFolders topFolder +mk cache sh/a/f.txt sh/keep/k.txt +row 'move from primary' f sh/a/f.txt | list +run_moves +cache_is sh sh/keep sh/keep/k.txt +log_has 'Not deleting top-level folder: contains 1 file(s), 1 subfolder(s): /mnt/cache/sh' + +begin "topFolder, the file's folder keeps another file" cleanFolders topFolder +mk cache sh/a/f.txt sh/a/g.txt +row 'move from primary' f sh/a/f.txt | list +run_moves +cache_is sh sh/a sh/a/g.txt +log_has 'Not deleting folder containing 1 files: /mnt/cache/sh/a' +log_lacks 'top-level' + +# a folder on the array where b.txt goes makes its move fail: b.txt stays, and the count after it keeps it +begin "topFolder, three rows in one folder, the middle one fails" cleanFolders topFolder +mk cache sh/d/a.txt sh/d/b.txt sh/d/c.txt +mkdir -p /mnt/user0/sh/d/b.txt/x +for f in a b c; do row 'move from primary' f "sh/d/$f.txt"; done | list +run_moves +cache_is sh sh/d sh/d/b.txt +log_count 2 'Not deleting folder containing 2 files: /mnt/cache/sh/d' +log_has 'Not deleting folder containing 1 files: /mnt/cache/sh/d' +log_lacks 'top-level' + +# a name gone before its turn may have left before the count: its folder is counted again +begin "topFolder, a row's file gone before the run, beside a file that stays" cleanFolders topFolder +mk cache sh/d/x.txt sh/d/y.txt sh/d/z.txt +{ row 'move from primary' f sh/d/x.txt; row 'move from primary' f sh/d/y.txt; } | list +rm /mnt/cache/sh/d/y.txt +run_moves +cache_is sh sh/d sh/d/z.txt +log_has 'Gone from the source before its turn: "/mnt/cache/sh/d/y.txt"' +log_count 2 'Not deleting folder containing 1 files: /mnt/cache/sh/d' + +# the earlier row deletes the folder, so the vanished name's recount finds no folder and counts nothing +begin "topFolder, a row's file gone before the run, in a folder an earlier row empties" cleanFolders topFolder +mk cache sh/d/a.txt sh/d/b.txt sh/keep.txt +{ row 'move from primary' f sh/d/a.txt; row 'move from primary' f sh/d/b.txt; } | list +rm /mnt/cache/sh/d/b.txt +run_moves +cache_is sh sh/keep.txt +log_count 1 'Deleted empty folder: /mnt/cache/sh/d' + +# both names leave in one row, so the count taken after it already lacks the second +begin "topFolder, a hardlink group in one folder beside another file" cleanFolders topFolder +mk cache sh/h/a.txt sh/h/k.txt +ln /mnt/cache/sh/h/a.txt /mnt/cache/sh/h/b.txt +{ row 'move from primary' f sh/h/a.txt; row 'move from primary' f sh/h/b.txt; } | list +run_moves +cache_is sh sh/h sh/h/k.txt +log_count 2 'Not deleting folder containing 1 files: /mnt/cache/sh/h' +log_lacks 'top-level' + +# the count takes files only, so the folder looks empty: rmdir alone keeps the subfolder's file +begin "topFolder, the file's folder keeps a subfolder with a file" cleanFolders topFolder +mk cache sh/a/f.txt sh/a/sub/g.txt +row 'move from primary' f sh/a/f.txt | list +run_moves +cache_is sh sh/a sh/a/sub sh/a/sub/g.txt +log_has 'Not deleting top-level folder: contains 1 file(s), 2 subfolder(s): /mnt/cache/sh' + +begin "topFolder, .placeholder in the file's folder" cleanFolders topFolder +mk cache sh/a/f.txt sh/a/.placeholder +row 'move from primary' f sh/a/f.txt | list +run_moves +cache_is sh sh/a sh/a/.placeholder +log_has 'Not deleting folder containing .placeholder file: /mnt/cache/sh/a' +log_lacks 'top-level' + +begin "topFolder, .placeholder in the top folder" cleanFolders topFolder +mk cache sh/only/f.txt sh/.placeholder +row 'move from primary' f sh/only/f.txt | list +run_moves +cache_is sh sh/.placeholder +log_has 'Not deleting top-level folder: contains .placeholder: /mnt/cache/sh' + +begin "topFolder, a hidden file in the top folder" cleanFolders topFolder +mk cache sh/only/f.txt sh/.hidden +row 'move from primary' f sh/only/f.txt | list +run_moves +cache_is sh sh/.hidden +log_has 'Not deleting top-level folder: contains 1 file(s), 0 subfolder(s): /mnt/cache/sh' + +# find counts no symlink, so the folder looks empty and only rmdir keeps it +begin "topFolder, only a symlink left in the top folder" cleanFolders topFolder +mk cache sh/only/f.txt +ln -s /nowhere /mnt/cache/sh/dangling +row 'move from primary' f sh/only/f.txt | list +run_moves +cache_is sh sh/dangling +log_lacks 'top-level' +[ "${AGE_MOVER_DEBUG:-0}" != 2 ] || dlog_has 'Failed to delete top-level folder (may not be empty): /mnt/cache/sh' + +# a dataset's .zfs is not counted: with snapdir=visible a walk would mount and count every snapshot. The name's [ ] +# would make a glob of the path +for s in sh 'sh[1]'; do + begin "topFolder, the top folder $s is a ZFS dataset showing a snapshot" cleanFolders topFolder + mk cache "$s/only/f.txt" "$s/.zfs/snapshot/s1/only/f.txt" + echo "/mnt/cache/$s" >"$T/zfs" + row 'move from primary' f "$s/only/f.txt" | list + run_moves + log_has "Skipping deletion of ZFS dataset mountpoint: /mnt/cache/$s" + log_lacks 'Not deleting top-level folder' +done + +# only a dataset has snapshots in .zfs: in a plain folder it is a folder like any other +begin "topFolder, a plain top folder holding a folder named .zfs" cleanFolders topFolder +mk cache sh/only/f.txt sh/.zfs/k.txt +row 'move from primary' f sh/only/f.txt | list +run_moves +cache_is sh sh/.zfs sh/.zfs/k.txt +log_has 'Not deleting top-level folder: contains 1 file(s), 1 subfolder(s): /mnt/cache/sh' + +# with Move empty folders off the planner lists no folder rows, so an empty folder stays and keeps the top folder +begin "topFolder, Move empty folders no, an empty folder not listed" cleanFolders topFolder moveEmptyFolders no +mk cache sh/a/f.txt +mkdir -p /mnt/cache/sh/e +row 'move from primary' f sh/a/f.txt | list +run_moves +cache_is sh sh/e +log_has 'Not deleting top-level folder: contains 0 file(s), 1 subfolder(s): /mnt/cache/sh' + +for tool in rsync move; do + begin "topFolder, a folder row empties the share last ($tool)" cleanFolders topFolder movefilesTool "$tool" + mk cache sh/a/f.txt + mkdir -p /mnt/cache/sh/e + { row 'move from primary' f sh/a/f.txt; row 'move from primary' d sh/e; } | list + run_moves + cache_is + array_is sh sh/a sh/a/f.txt sh/e + log_has 'Deleted empty top-level folder: /mnt/cache/sh' +done + +# with move the cleanup finds the folder already gone, and its parent is the top folder +for tool in rsync move; do + begin "topFolder, a share holding only an empty folder ($tool)" cleanFolders topFolder movefilesTool "$tool" + mkdir -p /mnt/cache/sh/e + row 'move from primary' d sh/e | list + run_moves + cache_is + array_is sh sh/e + log_has 'Deleted empty top-level folder: /mnt/cache/sh' +done + +begin "topFolder, a folder row whose parent keeps a file" cleanFolders topFolder +mk cache sh/p/k.txt +mkdir -p /mnt/cache/sh/p/e +row 'move from primary' d sh/p/e | list +run_moves +cache_is sh sh/p sh/p/k.txt +log_has 'Not deleting folder: contains 1 file(s), 0 subfolder(s): /mnt/cache/sh/p' +log_lacks 'top-level' + +# the parent's own subfolder counts once: the walk does not go below it +begin "topFolder, a folder row whose parent keeps a nested subfolder" cleanFolders topFolder +mkdir -p /mnt/cache/sh/p/e /mnt/cache/sh/p/k/a/b +row 'move from primary' d sh/p/e | list +run_moves +cache_is sh sh/p sh/p/k sh/p/k/a sh/p/k/a/b +log_has 'Not deleting folder: contains 0 file(s), 1 subfolder(s): /mnt/cache/sh/p' +log_lacks 'top-level' + +# the folder stays, or it would exist nowhere. Unraid's move cannot make the share's folder over a file; rsync +# replaces the file, so its copy is taken away instead +for tool in rsync move; do + begin "topFolder, a folder row that does not arrive ($tool)" cleanFolders topFolder movefilesTool "$tool" + mkdir -p /mnt/cache/sh/p/e + if [ "$tool" = move ]; then printf 'x\n' >/mnt/user0/sh; else after_first_rsync 'rm -r /mnt/user0/sh'; fi + row 'move from primary' d sh/p/e | list + run_moves + cache_is sh sh/p sh/p/e + log_has 'Did not arrive: "/mnt/cache/sh/p/e"' + log_lacks 'Deleted empty moved folder' + log_lacks 'top-level' +done + +# the folder's parent goes during its move: the row still leaves the remaining counters +begin "Clean Folders yes, a folder row whose parent is gone after its move" cleanFolders yes +mkdir -p /mnt/cache/sh/p/e +row 'move from primary' d sh/p/e | list +after_first_rsync 'rm -r /mnt/cache/sh/p' +run_moves +cache_is sh +array_is sh sh/p sh/p/e +counter REMAINING_CACHE_FOLDERS 0 +log_has '0 folders remaining from caches to array' +[ "${AGE_MOVER_DEBUG:-0}" != 2 ] || dlog_has '"/mnt/cache/sh/p/e" is gone from the source: the walk starts at its parent "/mnt/cache/sh/p"' + +# the reporter's shape: one top-folder check for the share, whichever row empties a folder first +for order in file-first folders-first; do + begin "topFolder, one file row and three folder rows, $order" cleanFolders topFolder + mk cache sh/a/f.txt sh/p/other.txt sh/keep/stay.txt + mkdir -p /mnt/cache/sh/p/e1 /mnt/cache/sh/p/e2 /mnt/cache/sh/p/e3 + { + [ "$order" = file-first ] && row 'move from primary' f sh/a/f.txt + for d in e1 e2 e3; do row 'move from primary' d "sh/p/$d"; done + [ "$order" = folders-first ] && row 'move from primary' f sh/a/f.txt + } | list + run_moves + cache_is sh sh/keep sh/keep/stay.txt sh/p sh/p/other.txt + log_count 1 'top-level folder' + log_has 'Not deleting top-level folder: contains 2 file(s), 2 subfolder(s): /mnt/cache/sh' +done + +begin "topFolder, two shares, their rows taking turns" cleanFolders topFolder +mk cache s1/a/f.txt s1/b/g.txt s1/keep/k.txt s2/a/f.txt s2/b/g.txt +for f in s1/a/f.txt s2/a/f.txt s1/b/g.txt s2/b/g.txt; do row 'move from primary' f "$f"; done | list +run_moves +cache_is s1 s1/keep s1/keep/k.txt +array_is s1 s1/a s1/a/f.txt s1/b s1/b/g.txt s2 s2/a s2/a/f.txt s2/b s2/b/g.txt +log_count 2 'top-level folder' +log_has 'Not deleting top-level folder: contains 1 file(s), 1 subfolder(s): /mnt/cache/s1' +log_has 'Deleted empty top-level folder: /mnt/cache/s2' + +begin "topFolder, a soft stop after the first row" cleanFolders topFolder +mk cache sh/a/f.txt sh/b/g.txt +{ row 'move from primary' f sh/a/f.txt; row 'move from primary' f sh/b/g.txt; } | list +after_first_rsync "touch '$SOFTSTOPFILE'" +run_moves +array_is sh sh/a sh/a/f.txt +cache_is sh sh/b sh/b/g.txt +check "the top folder is checked after the soft stop" \ + "$(printf '%s\n' 'Soft Stopping requested' 'Not deleting top-level folder: contains 1 file(s), 1 subfolder(s): /mnt/cache/sh')" \ + "$(log | grep -oE 'Soft Stopping requested|Not deleting top-level folder.*')" + +id tester >/dev/null 2>&1 || useradd -M tester +U=/tmp/age_mover_tester +for keep in no yes; do + begin "topFolder, a top folder a plain-user mover cannot list, $([ $keep = yes ] && echo 'holding a file' || echo 'empty after the move')" + mk cache sh/only/f.txt + [ "$keep" = yes ] && mk cache sh/stay.txt + rm -rf "$U" && mkdir -p "$U" + row 'move from primary' f sh/only/f.txt | { echo "$HDR"; cat; } >"$U/actions" + chown -R tester /mnt/cache /mnt/user0 "$U" + chmod 0333 /mnt/cache/sh + runuser -u tester -- env AGE_MOVER_TEST=1 AGE_MOVER_DEBUG="${AGE_MOVER_DEBUG:-0}" T="$U" bash "$0" --as-tester "$CASE" "$keep" + check "the checks run as the plain user pass" 0 "$?" + [ ! -d /mnt/cache/sh ] || chmod 0755 /mnt/cache/sh + if [ "$keep" = yes ]; then cache_is sh sh/stay.txt; else cache_is; fi +done + +# test mode's predictions: what a real move or deletion would take off the source is left out of each count +three_rows() { + mk cache sh/d/a.txt sh/d/b.txt sh/d/c.txt + for f in a b c; do row 'move from primary' f "sh/d/$f.txt"; done | list +} +same_in_test_mode "Clean Folders yes, three rows in one folder" "$(printf '%s\n' 'Not deleting folder containing 2 files: /mnt/cache/sh/d' \ + 'Not deleting folder containing 1 files: /mnt/cache/sh/d' 'Deleted empty folder: /mnt/cache/sh/d')" three_rows cleanFolders yes + +taking_turns() { + mk cache sh/a/1.txt sh/a/2.txt sh/b/1.txt + for f in a/1 b/1 a/2; do row 'move from primary' f "sh/$f.txt"; done | list +} +same_in_test_mode "Clean Folders yes, rows taking turns between two folders" "$(printf '%s\n' \ + 'Not deleting folder containing 1 files: /mnt/cache/sh/a' 'Deleted empty folder: /mnt/cache/sh/b' \ + 'Deleted empty folder: /mnt/cache/sh/a')" taking_turns cleanFolders yes + +# both names leave in the first one's row; the second finds the folder gone +link_pair() { + mk cache sh/h/a.txt + ln /mnt/cache/sh/h/a.txt /mnt/cache/sh/h/b.txt + { row 'move from primary' f sh/h/a.txt; row 'move from primary' f sh/h/b.txt; } | list +} +same_in_test_mode "Clean Folders yes, a hardlink group alone in its folder" 'Deleted empty folder: /mnt/cache/sh/h' link_pair \ + cleanFolders yes + +one_name_gone() { + mk cache sh/d/a.txt sh/d/b.txt sh/keep.txt + { row 'move from primary' f sh/d/a.txt; row 'move from primary' f sh/d/b.txt; } | list + rm /mnt/cache/sh/d/b.txt +} +same_in_test_mode "topFolder, a row's file gone before the run, in a folder an earlier row empties" "$(printf '%s\n' \ + 'Deleted empty folder: /mnt/cache/sh/d' 'Not deleting top-level folder: contains 1 file(s), 0 subfolder(s): /mnt/cache/sh')" \ + one_name_gone cleanFolders topFolder + +# the gone name's recount keeps the count at the two still on the source, where lowering it would give 1; the later +# rows lower it to 0 +middle_name_gone() { + mk cache sh/d/a.txt sh/d/b.txt sh/d/c.txt sh/d/d.txt sh/keep.txt + for f in a b c d; do row 'move from primary' f "sh/d/$f.txt"; done | list + rm /mnt/cache/sh/d/b.txt +} +same_in_test_mode "topFolder, the middle one of four rows in one folder gone before the run" "$(printf '%s\n' \ + 'Not deleting folder containing 2 files: /mnt/cache/sh/d' 'Not deleting folder containing 2 files: /mnt/cache/sh/d' \ + 'Not deleting folder containing 1 files: /mnt/cache/sh/d' 'Deleted empty folder: /mnt/cache/sh/d' \ + 'Not deleting top-level folder: contains 1 file(s), 0 subfolder(s): /mnt/cache/sh')" middle_name_gone \ + cleanFolders topFolder + +nested_file() { + mk cache sh/p/q/f.txt + row 'move from primary' f sh/p/q/f.txt | list +} +same_in_test_mode "topFolder, a file two folders down" "$(printf '%s\n' 'Deleted empty folder: /mnt/cache/sh/p/q' \ + 'Not deleting top-level folder: contains 0 file(s), 1 subfolder(s): /mnt/cache/sh')" nested_file cleanFolders topFolder + +# rmdir refuses the file's folder, which keeps a subfolder +keeps_subfolder() { + mk cache sh/d/f.txt + mkdir -p /mnt/cache/sh/d/sub + row 'move from primary' f sh/d/f.txt | list +} +same_in_test_mode "topFolder, the file's folder keeps an empty subfolder" \ + 'Not deleting top-level folder: contains 0 file(s), 2 subfolder(s): /mnt/cache/sh' keeps_subfolder cleanFolders topFolder + +dataset_top() { + mk cache sh/only/f.txt + echo /mnt/cache/sh >"$T/zfs" + row 'move from primary' f sh/only/f.txt | list +} +same_in_test_mode "topFolder, the top folder is a ZFS dataset mountpoint" "$(printf '%s\n' \ + 'Deleted empty folder: /mnt/cache/sh/only' 'Skipping deletion of ZFS dataset mountpoint: /mnt/cache/sh')" dataset_top cleanFolders topFolder + +# no file or folder is left in the top folder, but rmdir refuses it for the symlink +top_symlink() { + mk cache sh/only/f.txt + ln -s gone /mnt/cache/sh/link + row 'move from primary' f sh/only/f.txt | list +} +same_in_test_mode "topFolder, the top folder keeps only a symlink" 'Deleted empty folder: /mnt/cache/sh/only' top_symlink \ + cleanFolders topFolder +[ "${AGE_MOVER_DEBUG:-0}" != 2 ] || dlog_has 'TEST MODE: Would fail to delete top-level folder (not empty): /mnt/cache/sh' + +# Unraid's move takes the folder itself; with rsync the walk deletes it +one_empty_folder() { + mkdir -p /mnt/cache/sh/e + row 'move from primary' d sh/e | list +} +folder_row_alone() { + mkdir -p /mnt/cache/sh/p/e + row 'move from primary' d sh/p/e | list +} +for tool in rsync move; do + want='Deleted empty top-level folder: /mnt/cache/sh' + [ "$tool" = move ] || want=$'Deleted empty moved folder: /mnt/cache/sh/e\n'$want + same_in_test_mode "topFolder, a share holding only an empty folder ($tool)" "$want" one_empty_folder cleanFolders topFolder \ + movefilesTool "$tool" + want=$'Deleted empty moved folder: /mnt/cache/sh/p\nDeleted empty top-level folder: /mnt/cache/sh' + [ "$tool" = move ] || want=$'Deleted empty moved folder: /mnt/cache/sh/p/e\n'$want + same_in_test_mode "topFolder, a folder row whose parent holds nothing else ($tool)" "$want" folder_row_alone \ + cleanFolders topFolder movefilesTool "$tool" + [ "$tool" = rsync ] || [ "${AGE_MOVER_DEBUG:-0}" != 2 ] || + dlog_has '"/mnt/cache/sh/p/e" would be gone from the source: the walk starts at its parent "/mnt/cache/sh/p"' +done + +# rmdir, in move or the walk, refuses a folder a dataset is mounted on, and one that holds a symlink +empty_mountpoint_row() { + mkdir -p /mnt/cache/sh/p/e + echo /mnt/cache/sh/p/e >"$T/zfs" + row 'move from primary' d sh/p/e | list +} +symlink_beside_row() { + mkdir -p /mnt/cache/sh/g/p/e + ln -s gone /mnt/cache/sh/g/p/link + row 'move from primary' d sh/g/p/e | list +} +for tool in rsync move; do + same_in_test_mode "topFolder, a folder row that is an empty ZFS dataset mountpoint ($tool)" \ + 'Skipping deletion of ZFS dataset mountpoint: /mnt/cache/sh/p/e' empty_mountpoint_row cleanFolders topFolder \ + movefilesTool "$tool" + want="" + [ "$tool" = move ] || want='Deleted empty moved folder: /mnt/cache/sh/g/p/e' + same_in_test_mode "topFolder, a folder row whose parent holds a symlink ($tool)" "$want" symlink_beside_row \ + cleanFolders topFolder movefilesTool "$tool" + [ "${AGE_MOVER_DEBUG:-0}" != 2 ] || dlog_has 'TEST MODE: Would fail to delete moved folder (not empty): /mnt/cache/sh/g/p' +done + +# the second folder row's folder is gone before its turn, and the first row's walk deleted its parent +folder_rows_one_gone() { + mkdir -p /mnt/cache/sh/p/e /mnt/cache/sh/p/g + mk cache sh/keep.txt + { row 'move from primary' d sh/p/e; row 'move from primary' d sh/p/g; } | list + rmdir /mnt/cache/sh/p/g +} +for tool in rsync move; do + want=$'Deleted empty moved folder: /mnt/cache/sh/p\nNot deleting top-level folder: contains 1 file(s), 0 subfolder(s): /mnt/cache/sh' + [ "$tool" = move ] || want=$'Deleted empty moved folder: /mnt/cache/sh/p/e\n'$want + same_in_test_mode "topFolder, a folder row's folder gone before its turn, its parent deleted ($tool)" "$want" \ + folder_rows_one_gone cleanFolders topFolder movefilesTool "$tool" + [ "${AGE_MOVER_DEBUG:-0}" != 2 ] || + dlog_has '"/mnt/cache/sh/p/g" is gone from the source: the walk starts at its parent "/mnt/cache/sh/p"' +done + +# move leaves a folder that holds something, here a file written after the planning: nothing in the share empties, so +# the top-folder check does not run +folder_row_gains_file() { + mkdir -p /mnt/cache/sh/p/e + row 'move from primary' d sh/p/e | list + mk cache sh/p/e/new.txt +} +same_in_test_mode "topFolder, a folder row's folder gains a file after the planning (move)" \ + 'Not deleting folder: contains 1 file(s), 0 subfolder(s): /mnt/cache/sh/p/e' folder_row_gains_file \ + cleanFolders topFolder movefilesTool move + +finish diff --git a/tests/age_mover/test_install.sh b/tests/age_mover/test_install.sh new file mode 100644 index 00000000..728ddeb9 --- /dev/null +++ b/tests/age_mover/test_install.sh @@ -0,0 +1,90 @@ +#!/bin/bash +# shellcheck disable=SC1091,SC2034 # lib.sh is sourced from this folder and reads CASE +# The plg's post-install step on a saved config, taken from the real plg by xmllint, a real XML parser, on Unraid +# 7.2.1, with the plugin's files copied in place; php and update_cron are stand-ins. PLG= runs another plg. The step's +# pgrep finds age_mover in this test's paths, so it always takes its "run in progress" branch and keeps /var/run's files. +. "$(dirname "$0")/lib.sh" +PLG=$(realpath "${PLG:-$HERE/../../plugins/ca.mover.tuning.plg}") +CFG=/boot/config/plugins/ca.mover.tuning/ca.mover.tuning.cfg +STANDINS=(/usr/bin/php /usr/local/sbin/update_cron) +# the step writes under /boot, /usr/local and /var/run, and the test writes /usr/bin/php and /etc/unraid-version: a mount at +# one (Unraid's flash drive) refuses, and so does a php or update_cron this test did not write +if ! awk '$5 ~ "^/(boot|usr/local)(/|$)" || $5 ~ "^/(usr(/bin(/php)?)?|var|etc(/unraid-version)?|(var/)?run)$" { exit 1 }' /proc/self/mountinfo; then + echo "test_install.sh writes Unraid's paths and one is a mount here: start it with tests/age_mover/run.sh" >&2 + exit 2 +fi +for f in "${STANDINS[@]}"; do + [ ! -e "$f" ] || grep -qx '# test_install.sh stand-in' "$f" || { echo "test_install.sh: $f is not this test's stand-in" >&2; exit 2; } +done +trap 'rm -rf /boot/config /usr/local/emhttp/plugins/ca.mover.tuning /usr/local/sbin/age_mover /etc/unraid-version "${STANDINS[@]}"' EXIT + +xmllint --noent --xpath 'string(//comment()[contains(., "The '\''post-install'\'' script")]/following-sibling::FILE[1]/INLINE)' "$PLG" \ + >"$T/post_install.sh" +if ! grep -q 'Updating config file' "$T/post_install.sh"; then + echo "test_install.sh: no post-install step read from $PLG" >&2 + exit 2 +fi +VERSION=$(xmllint --noent --xpath 'string(/PLUGIN/@version)' "$PLG") +for f in "${STANDINS[@]}"; do + # shellcheck disable=SC2016 # the stand-in expands its own name and arguments + printf '#!/bin/bash\n# test_install.sh stand-in\necho "${0##*/}${*:+ $*}" >>%q\n' "$T/install.calls" >"$f" + chmod 755 "$f" +done +echo 'version="7.2.1"' >/etc/unraid-version +rm -rf /usr/local/emhttp/plugins/ca.mover.tuning +mkdir -p /usr/local/emhttp/plugins +cp -r "$PLUGIN" /usr/local/emhttp/plugins/ + +# run_step ...: the step on a saved config of these lines, each ending in and \n; its output +# is the log +run_step() { + CASE=$1 + local eol=$2 rc + shift 2 + rm -rf /boot/config "$T/install.calls" + mkdir -p "${CFG%/*}" + printf "%s$eol\n" "$@" >"$CFG" + (cd "$T/cwd" && bash "$T/post_install.sh") >"$MOVER_LOG" 2>"$T/err" + rc=$? + check "the step exited 0" 0 "$rc" + check "stderr held nothing" "" "$(cat "$T/err")" + check "the step ran to its end: php and update_cron were called" \ + "$(printf '%s\n' 'php -q /usr/local/emhttp/plugins/ca.mover.tuning/updateCron.php sync' update_cron)" "$(cat "$T/install.calls" 2>/dev/null)" +} +# cfg_is ...: the config holds exactly these lines besides version=, which every install sets to the plg's +# version, and testmode=, which a major upgrade sets +cfg_is() { + local eol=$1 + shift + check "the config holds exactly $*" "$(printf "%s$eol\n" "$@" | cat -A)" "$(grep -vE '^(version|testmode)=' "$CFG" | cat -A)" + check "version is the plg's" "version=\"$VERSION\"" "$(grep '^version=' "$CFG" | tr -d '\r')" +} +REMOVING="- Removing the old filename check's settings" + +run_step "both keys among other keys" '' 'logging="yes"' 'validateFilenames="yes"' 'movenow="yes"' \ + 'invalidFileChars="$ / < > : \" | ? *"' 'version="2026.01.01"' 'movingThreshold="80"' 'freeingThreshold="70"' 'migratedOverrideNo="yes"' +cfg_is '' 'logging="yes"' 'movenow="yes"' 'movingThreshold="80"' 'freeingThreshold="70"' 'migratedOverrideNo="yes"' +log_has "$REMOVING" + +run_step "a CRLF file" '\r' 'logging="yes"' 'invalidFileChars="*"' 'movenow="yes"' 'validateFilenames="no"' 'version="2026.01.01"' \ + 'movingThreshold="80"' 'freeingThreshold="70"' 'migratedOverrideNo="yes"' +cfg_is '\r' 'logging="yes"' 'movenow="yes"' 'movingThreshold="80"' 'freeingThreshold="70"' 'migratedOverrideNo="yes"' +log_has "$REMOVING" + +run_step "validateFilenamesOld beside invalidFileChars" '' 'validateFilenamesOld="x"' 'invalidFileChars="*"' 'version="2026.01.01"' \ + 'movingThreshold="80"' 'freeingThreshold="70"' 'migratedOverrideNo="yes"' +cfg_is '' 'validateFilenamesOld="x"' 'movingThreshold="80"' 'freeingThreshold="70"' 'migratedOverrideNo="yes"' +log_has "$REMOVING" + +# debug_mover sources the config: a backtick saved in invalidFileChars stopped it there, so every key below stayed empty +run_step "a backtick in invalidFileChars" '' 'logging="yes"' 'invalidFileChars="`"' 'movenow="yes"' 'version="2026.01.01"' \ + 'movingThreshold="80"' 'freeingThreshold="70"' 'migratedOverrideNo="yes"' +cfg_is '' 'logging="yes"' 'movenow="yes"' 'movingThreshold="80"' 'freeingThreshold="70"' 'migratedOverrideNo="yes"' +check "the config sources to its end, with nothing on stderr" 'movenow=yes' "$(bash -c '. "$1"; echo "movenow=$movenow"' _ "$CFG" 2>&1)" + +run_step "neither key, only validateFilenamesOld" '' 'logging="yes"' 'validateFilenamesOld="x"' 'version="2026.01.01"' \ + 'movingThreshold="80"' 'freeingThreshold="70"' 'migratedOverrideNo="yes"' +cfg_is '' 'logging="yes"' 'validateFilenamesOld="x"' 'movingThreshold="80"' 'freeingThreshold="70"' 'migratedOverrideNo="yes"' +log_lacks "$REMOVING" + +finish diff --git a/tests/age_mover/test_moves.sh b/tests/age_mover/test_moves.sh new file mode 100644 index 00000000..997de798 --- /dev/null +++ b/tests/age_mover/test_moves.sh @@ -0,0 +1,219 @@ +#!/bin/bash +# What processTheMoves does today with the planner's rows: where the names land, the counters and the log lines. +. "$(dirname "$0")/lib.sh" + +for tool in rsync move; do + begin "names with space, |, \$, quotes, a backslash and Unicode ($tool)" movefilesTool "$tool" + names=('sh/o/a b.txt' 'sh/o/p|ipe.txt' 'sh/o/trail|' 'sh/o/$HOME.txt' "sh/o/q\"uote's.txt" 'sh/o/back\slash.txt' 'sh/o/ünï.txt') + mk cache "${names[@]}" + for n in "${names[@]}"; do row 'move from primary' f "$n"; done | list + run_moves + array_is sh sh/o "${names[@]}" + cache_is sh sh/o + counter MOVEDFILES 7 + counter REMAINING_CACHE_FILES 0 + counter MOVEDSIZE 14 + check "debug blocks written only with AGE_MOVER_DEBUG=2" "$([ "${AGE_MOVER_DEBUG:-0}" = 2 ] && echo yes || echo no)" \ + "$(grep -qF Debugging "$MOVER_DEBUG_LOG" && echo yes || echo no)" + log_has 'Moving "/mnt/cache/./sh/o/trail|" to "/mnt/user0/"' + log_has "Moving \"/mnt/cache/./sh/o/q\\\"uote's.txt\" to \"/mnt/user0/\"" + log_has 'Moving "/mnt/cache/./sh/o/back\\slash.txt" to "/mnt/user0/"' + + begin "hardlink group, every name listed ($tool)" movefilesTool "$tool" + mk cache sh/h/a.txt + ln /mnt/cache/sh/h/a.txt /mnt/cache/sh/h/b.txt + { row 'move from primary' f sh/h/a.txt; row 'move from primary' f sh/h/b.txt; } | list + run_moves + array_is sh sh/h sh/h/a.txt sh/h/b.txt + links 2 sh/h/b.txt + counter MOVEDFILES 2 + counter MOVEDSIZE 2 + counter REMAINING_CACHE_SIZE 0 + log_count 1 'Moving "/mnt/cache/./sh/h/a.txt" "/mnt/cache/./sh/h/b.txt" to "/mnt/user0/" (preserving hardlinks)' + + begin "hardlink group across shares, both moved ($tool)" movefilesTool "$tool" + mk cache sh1/h/a.txt sh2/k/z.txt + ln /mnt/cache/sh1/h/a.txt /mnt/cache/sh2/k/b.txt + { row 'move from primary' f sh1/h/a.txt; row 'move from primary' f sh2/k/b.txt; } | list + run_moves + array_is sh1 sh1/h sh1/h/a.txt sh2 sh2/k sh2/k/b.txt + links 2 sh2/k/b.txt + cache_is sh1 sh1/h sh2 sh2/k sh2/k/z.txt + counter MOVEDFILES 2 + counter MOVEDSIZE 2 + log_count 1 'Moving "/mnt/cache/./sh1/h/a.txt" "/mnt/cache/./sh2/k/b.txt" to "/mnt/user0/" (preserving hardlinks)' + + begin "folder rows: empty, and one that gained a file after planning ($tool)" movefilesTool "$tool" + mkdir -p /mnt/cache/sh/e/sub + mk cache sh/g/new.txt + { row 'move from primary' d sh/e/sub; row 'move from primary' d sh/g; } | list + run_moves + array_is sh sh/e sh/e/sub sh/g + cache_is sh sh/g sh/g/new.txt + counter MOVEDFOLDERS 2 + counter REMAINING_CACHE_FOLDERS 0 + log_has 'Deleted empty moved folder: /mnt/cache/sh/e' + log_has 'Not deleting folder: contains 1 file(s), 0 subfolder(s): /mnt/cache/sh/g' + + begin "test mode ($tool)" movefilesTool "$tool" testmode yes synchronizeCache yes + mk cache sh/t/f.txt sh/t/s.txt + mkdir -p /mnt/cache/sh/t/e + { row 'move from primary' f sh/t/f.txt; row 'move from primary' d sh/t/e; row 'sync from primary' f sh/t/s.txt; } | list + run_moves + array_is + cache_is sh sh/t sh/t/e sh/t/f.txt sh/t/s.txt + counter MOVEDFILES 0 + log_has "$([ "$tool" = move ] && echo 'TEST MODE: Would move using Unraid move utility' || echo 'TEST MODE: Would Move using rsync utility')" + # Unraid's move would take the folder itself, so only rsync's would be left for the walk; the synced file keeps the + # parent either way + if [ "$tool" = move ]; then + log_lacks 'TEST MODE: Would delete moved empty folder' + else + log_has 'TEST MODE: Would delete moved empty folder: /mnt/cache/sh/t/e' + fi + log_has 'Not deleting folder: contains 1 file(s), 0 subfolder(s): /mnt/cache/sh/t' + log_lacks 'Set last sync date' + + begin "move from secondary ($tool)" movefilesTool "$tool" + mk disk1 sh/p/f.txt + row 'move from secondary' f sh/p/f.txt | list + run_moves + cache_is sh sh/p sh/p/f.txt + holds disk1 sh sh/p + log_has 'Moving "/mnt/disk1/./sh/p/f.txt" to "/mnt/cache/"' + log_has '0 files remaining from array to caches' + + begin "unattended file staged to the primary, then synced ($tool)" movefilesTool "$tool" synchronizeCache yes + mk other sh/x/f.txt + { row 'move unattended to primary' f sh/x/f.txt; row 'sync unattended to secondary' f sh/x/f.txt; } | list + run_moves + cache_is sh sh/x sh/x/f.txt + array_is sh sh/x sh/x/f.txt + counter MOVEDFILES 1 + counter REMAINING_UNATTENDED_FILES 0 + counter REMAINING_UNATTENDED_SIZE 0 + log_has 'Synchronizing "/mnt/cache/./sh/x/f.txt" to "/mnt/user0/"' + log_has 'Set last sync date in config file/s: 1767323045 = 2026-01-02T030405' +done + +# bash read drops a | that ends the row, which would skip the check on a name like a| +for n in a.txt 'a|'; do + begin "hardlink group with a name not listed, $n" + mk cache "sh/h/$n" sh/k/z.txt + ln "/mnt/cache/sh/h/$n" /mnt/cache/sh/k/b.txt + row 'move from primary' f "sh/h/$n" | list + run_moves + array_is + cache_is sh sh/h "sh/h/$n" sh/k sh/k/b.txt sh/k/z.txt + counter NOTMOVEDFILES 1 + counter NOTMOVEDSIZE 2 + counter REMAINING_CACHE_SIZE 2 + log_has "Expected 2 files, got 1. Not moving \"/mnt/cache/./sh/h/$n\" to prevent breaking hardlinks" +done + +begin "hardlink group across shares, planned differently" +mk cache sh1/h/a.txt +mkdir -p /mnt/cache/sh2/k +ln /mnt/cache/sh1/h/a.txt /mnt/cache/sh2/k/b.txt +{ row 'move from primary' f sh1/h/a.txt; row 'keep on primary' f sh2/k/b.txt; } | list +run_moves +array_is +counter NOTMOVEDFILES 1 +log_has 'Expected 2 files, got 1. Not moving "/mnt/cache/./sh1/h/a.txt"' + +# each disk numbers its own inodes: the group lookup takes only the names on the row's disk +begin "hardlink groups on two disks sharing inode and mtime" +mk disk1 sh/p/a.txt +mk disk2 sh/p/b.txt +ln /mnt/disk1/sh/p/a.txt /mnt/disk1/sh/p/a2.txt +ln /mnt/disk2/sh/p/b.txt /mnt/disk2/sh/p/b2.txt +for n in a a2 b b2; do row 'move from secondary' f "sh/p/$n.txt" 2 777 1700000000; done | list +run_moves +cache_is sh sh/p sh/p/a.txt sh/p/a2.txt sh/p/b.txt sh/p/b2.txt +holds disk1 sh sh/p +holds disk2 sh sh/p +counter MOVEDFILES 4 +counter MOVEDSIZE 4 + +# two ZFS datasets of one pool can give two single-link files the same inode number and mtime: each row moves its own file +begin "single-link files sharing inode and mtime across shares" +mk cache sh1/d/a.txt sh2/d/b.txt +{ row 'move from primary' f sh1/d/a.txt 1 777 1700000000; row 'move from primary' f sh2/d/b.txt 1 777 1700000000; } | list +run_moves +array_is sh1 sh1/d sh1/d/a.txt sh2 sh2/d sh2/d/b.txt +cache_is sh1 sh1/d sh2 sh2/d +counter MOVEDFILES 2 +counter MOVEDSIZE 4 +counter NOTMOVEDFILES 0 +counter REMAINING_CACHE_FILES 0 +counter REMAINING_CACHE_SIZE 0 +log_has 'Moving "/mnt/cache/./sh1/d/a.txt" to "/mnt/user0/"' +log_has 'Moving "/mnt/cache/./sh2/d/b.txt" to "/mnt/user0/"' +log_lacks 'Expected 1 files' + +# the same for two empty folders +begin "folder rows sharing inode and mtime across shares" +mkdir -p /mnt/cache/sh1/e /mnt/cache/sh2/e +{ row 'move from primary' d sh1/e 2 778 1700000000; row 'move from primary' d sh2/e 2 778 1700000000; } | list +run_moves +array_is sh1 sh1/e sh2 sh2/e +cache_is sh1 sh2 +counter MOVEDFOLDERS 2 +counter VANISHEDFOLDERS 0 +counter REMAINING_CACHE_FOLDERS 0 +log_has 'Moving "/mnt/cache/./sh1/e" to "/mnt/user0/"' +log_has 'Moving "/mnt/cache/./sh2/e" to "/mnt/user0/"' +log_lacks 'Gone from the source' + +begin "a pass with nothing to move" +mk cache sh/k/k.txt +row 'keep on primary' f sh/k/k.txt | list +run_moves +array_is +cache_is sh sh/k sh/k/k.txt +log_lacks 'Moving' + +begin "sync from primary keeps the file and sets the sync date" synchronizeCache yes +mk cache sh/y/f.txt +row 'sync from primary' f sh/y/f.txt | list +run_moves +cache_is sh sh/y sh/y/f.txt +array_is sh sh/y sh/y/f.txt +counter MOVEDFILES 1 +counter MOVEDSIZE 2 +check "lastCacheSync saved" 'lastCacheSync="1767323045"' "$(grep '^lastCacheSync=' "$T/cfg")" + +# the in-use check covers every name of a hardlink group: here only the second name is open. A helper that does not +# compile leaves the check to fuser +shipped=$FILES_IN_USE_HELPER +for helper in shipped 'not compiling'; do + begin "a hardlink group with one name held open, beside a free file, $helper helper" + [ "$helper" = shipped ] || FILES_IN_USE_HELPER=$T/no_such_helper + mk cache sh/u/a.txt sh/u/free.txt + ln /mnt/cache/sh/u/a.txt /mnt/cache/sh/u/b.txt + for n in a b free; do row 'move from primary' f "sh/u/$n.txt"; done | list + sleep 60 9/dev/null)" = /mnt/cache/sh/u/b.txt ] && break; sleep 0.05; done + check "the holder has b.txt open" /mnt/cache/sh/u/b.txt "$(readlink "/proc/$holder/fd/9" 2>/dev/null)" + run_moves + kill "$holder" + wait "$holder" 2>/dev/null + FILES_IN_USE_HELPER=$shipped + cache_is sh sh/u sh/u/a.txt sh/u/b.txt + array_is sh sh/u sh/u/free.txt + counter INUSEFILES 2 + counter MOVEDFILES 1 + log_has 'In use, left for a later run: "/mnt/cache/./sh/u/a.txt" "/mnt/cache/./sh/u/b.txt"' + log_has '2 files were in use and stay on the source until a later run' + if [ "$helper" = shipped ]; then + log_lacks 'helper could not start' + elif command -v perl >/dev/null; then + log_has 'The file lease helper could not start' + else + log_has 'Perl not found' + fi + log_lacks 'could not be checked for use' +done + +finish diff --git a/tests/age_mover/test_share_mover.sh b/tests/age_mover/test_share_mover.sh new file mode 100644 index 00000000..330ad300 --- /dev/null +++ b/tests/age_mover/test_share_mover.sh @@ -0,0 +1,407 @@ +#!/bin/bash +# shellcheck disable=SC1091,SC2034 # lib.sh is sourced from this folder and reads CASE +# The per-share Move: the real share_mover on share sh, with Unraid's config files as each case writes them under /boot and +# /var/local/emhttp, lib.sh's move stand-in and an mdcmd stand-in. SM= runs another copy of share_mover. +. "$(dirname "$0")/lib.sh" +SM=$(realpath "${SM:-$PLUGIN/share_mover}") # run starts it from $T/cwd +CFG=/boot/config/plugins/ca.mover.tuning/ca.mover.tuning.cfg +# the cases write under /boot, /var/local and /usr/local, and /var/run/mover.pid: a mount at one (Unraid's flash drive) refuses +if ! awk '$5 ~ "^/(boot|var/local|usr/local)(/|$)" || $5 ~ "^/(var|usr|(var/)?run(/mover\\.pid)?)$" { exit 1 }' /proc/self/mountinfo; then + echo "test_share_mover.sh writes Unraid's paths and one is a mount here: start it with tests/age_mover/run.sh" >&2 + exit 2 +fi +mkdir -p /usr/local/sbin +cat >/usr/local/sbin/mdcmd <>$T/mdcmd.calls +EOF +chmod 755 /usr/local/sbin/mdcmd + +# share [key value]...: share sh on pool cache, two pools, and the shipped plugin defaults with these keys +# changed; the value - removes the key +share() { + CASE=$1 + local use=$2 + shift 2 + rm -rf "${ROOTS[@]}" /boot/config /var/local/emhttp /var/run/mover.pid "$T/mdcmd.calls" + mkdir -p /mnt/cache /mnt/user0 /mnt/disk1 /boot/config/plugins/ca.mover.tuning /boot/config/shares /boot/config/pools /var/local/emhttp + printf '%s\n' 'shareCacheEnabled="yes"' 'shareMoverLogging="yes"' >/boot/config/share.cfg + printf '%s\n' 'NAME="Tower"' 'timeZone="UTC"' >/boot/config/ident.cfg + printf '%s\n' "shareUseCache=\"$use\"" 'shareCachePool="cache"' >/boot/config/shares/sh.cfg + : >/boot/config/pools/cache.cfg + : >/boot/config/pools/fast.cfg + printf '%s\n' 'md_write_method="auto"' >/var/local/emhttp/var.ini + cp "$PLUGIN/default.cfg" "$CFG" + while [ $# -ge 2 ]; do + grep -q "^$1=" "$CFG" || { echo "share: $1 is not in default.cfg" >&2; exit 2; } + if [ "$2" = - ]; then sed -i "/^$1=/d" "$CFG"; else sed -i "s|^$1=.*|$1=\"$2\"|" "$CFG"; fi + shift 2 + done +} + +# bg ...: the command in the background under that name, once it has replaced the forked test script, whose +# path holds "mover" too +bg() { + local a0 + (exec -a "$1" "${@:2}") & + for _ in {1..100}; do + read -r -d '' a0 <"/proc/$!/cmdline" + [ "$a0" = "$1" ] && return + sleep 0.05 + done + echo "bg: $1 did not start" >&2 + exit 2 +} + +# run [stderr]: share_mover sh (or $NAME), its output without mvlogger's date as the log; stderr must be exactly the given +# text, nothing by default +run() { + local rc + (cd "$T/cwd" && bash "$SM" "${NAME:-sh}") >"$T/out" 2>"$T/err" + rc=$? + sed -E 's/^[A-Z][a-z]{2} [ 0-9][0-9] [0-9:]{8} Share mover: //' "$T/out" >"$MOVER_LOG" + check "share_mover exited $1" "$1" "$rc" + check "stderr held $([ -n "${2:-}" ] && echo only the expected text || echo nothing)" "${2:-}" "$(cat "$T/err")" +} +mdcmd_calls() { check "mdcmd calls: ${*:-none}" "$( (($#)) && printf 'mdcmd %s\n' "$@")" "$(cat "$T/mdcmd.calls" 2>/dev/null)"; } +# move_hook : Unraid's move runs the command first, until move_unhook +move_hook() { + mv /usr/libexec/unraid/move "$T/move.real" + cat >/usr/libexec/unraid/move </dev/null; exit 3' +run 3 +move_unhook +log_has 'Move command failed: find exited 0, move exited 3' +mdcmd_calls 'set md_write_method 1' 'set md_write_method auto' +cache_is sh sh/a.txt + +share 'no move anywhere' yes +mk cache sh/a.txt +mv /usr/libexec/unraid/move "$T/move.aside" +# shellcheck disable=SC2016 # the text of share_mover's move line +run 127 "$SM: line $(grep -nF '"$MOVE" -d' "$SM" | cut -d: -f1): : command not found" +mv "$T/move.aside" /usr/libexec/unraid/move +log_has 'move exited 127' +cache_is sh sh/a.txt + +# find fails, as when a folder goes during the walk: the run exits with find's status, or move's when move fails too +mkdir -p "$T/wrap" +cat >"$T/wrap/find" <<'EOF' +#!/bin/bash +/usr/bin/find "$@" +exit 1 +EOF +chmod 755 "$T/wrap/find" +for movetoo in no yes; do + share "find fails$([ "$movetoo" = no ] || echo ', and move too')" yes + mk cache sh/a.txt + if [ "$movetoo" = no ]; then + PATH=$T/wrap:$PATH run 1 + log_has 'Move command failed: find exited 1, move exited 0' + array_is sh sh/a.txt + else + move_hook 'cat >/dev/null; exit 3' + PATH=$T/wrap:$PATH run 3 + move_unhook + log_has 'Move command failed: find exited 1, move exited 3' + cache_is sh sh/a.txt + fi +done +rm -rf "$T/wrap" + +# /mnt/other is no array disk or pool, as Unassigned Devices' mounts: a folder there that only shares the name stays. +# disk10 is an array disk too +share 'a prefer share' prefer +mk disk1 sh/c.txt +mk disk2 sh/d.txt +mk disk10 sh/e.txt +mk user0 sh/u.txt +mk other sh/o.txt +run 0 +log_has 'Complete Mover Command: find "/mnt/disk1/sh" "/mnt/disk2/sh" "/mnt/disk10/sh" -type f -depth | /usr/libexec/unraid/move -d 1' +cache_is sh sh/c.txt sh/d.txt sh/e.txt +holds disk1 sh +holds disk2 sh +holds disk10 sh +rm -rf /mnt/disk10 +array_is sh sh/u.txt +holds other sh sh/o.txt + +share 'a prefer share, from a second pool' prefer +: >/boot/config/pools/other.cfg +echo 'shareCachePool2="other"' >>/boot/config/shares/sh.cfg +mk other sh/o.txt +run 0 +log_has 'Complete Mover Command: find "/mnt/other/sh" -type f -depth | /usr/libexec/unraid/move -d 1' +cache_is sh sh/o.txt +holds other sh + +# find given no folder lists the one it runs in: the run must not reach it +share 'a prefer share, no array disk or other pool holds its folder' prefer enableTurbo yes +mk cache sh/a.txt +mkdir -p /mnt/user0/sh +touch "$T/cwd/stray.txt" +run 0 +log_has 'No array disk or other pool holds a folder of the share: nothing to move' +log_lacks 'Complete Mover Command' +mdcmd_calls +cache_is sh sh/a.txt +check 'the folder the run starts in keeps its file' stray.txt "$(ls "$T/cwd")" +rm -f "$T/cwd/stray.txt" + +for wm in 'auto Auto (read/modify/write)' '1 Turbo writes (Reconstruct)' '0 Read/modify/write'; do + share "turbo on, md_write_method ${wm%% *}" yes enableTurbo yes + printf 'md_write_method="%s"\n' "${wm%% *}" >/var/local/emhttp/var.ini + mk cache sh/a.txt + run 0 + log_has 'Forcing turbo write on' + log_has "Restoring original turbo write mode ${wm#* }" + mdcmd_calls 'set md_write_method 1' "set md_write_method ${wm%% *}" + array_is sh sh/a.txt +done + +share 'turbo on in test mode' yes enableTurbo yes testmode yes +mk cache sh/a.txt +run 0 +log_has 'TEST MODE: Would force turbo write on' +log_has 'TEST MODE: Would restore original turbo write mode Auto (read/modify/write)' +log_lacks 'Forcing turbo write on' +log_lacks 'Restoring original turbo write mode' +mdcmd_calls +cache_is sh sh/a.txt + +share 'turbo on, var.ini gives no write method' yes enableTurbo yes +: >/var/local/emhttp/var.ini +mk cache sh/a.txt +run 0 +log_has 'Not forcing turbo write on: /var/local/emhttp/var.ini gives no write method (0, 1 or auto) to set back after' +log_lacks 'Restoring original turbo write mode' +mdcmd_calls +array_is sh sh/a.txt + +# a save in Settings during the moves changes var.ini's write method: that one is set back, or the one read before +# when var.ini then gives none +for now in '0 Read/modify/write' ' Auto (read/modify/write)'; do + share "turbo on, var.ini gives \"${now%% *}\" during the moves" yes enableTurbo yes + mk cache sh/a.txt + move_hook "echo 'md_write_method=\"${now%% *}\"' >/var/local/emhttp/var.ini" + run 0 + move_unhook + w=${now%% *} + mdcmd_calls 'set md_write_method 1' "set md_write_method ${w:-auto}" + log_count 1 "Restoring original turbo write mode ${now#* }" + array_is sh sh/a.txt +done + +# a stop of the run during the moves: it ends once the move does, and sets the write method back before its pid file goes. +# A second stop, at the read of var.ini for that, waits for it +cat >/usr/local/sbin/mdcmd </dev/null) +echo "mdcmd \$*\${w:+ (pid file there)}" >>$T/mdcmd.calls +EOF +mkdir -p "$T/wrap" +cat >"$T/wrap/grep" </dev/null)" + mdcmd_calls 'set md_write_method 1 (pid file there)' 'set md_write_method auto (pid file there)' + log_count 1 'Restoring original turbo write mode Auto (read/modify/write)' + check 'the run removed its pid file' '' "$(ls /var/run/mover.pid 2>/dev/null)" + array_is sh sh/a.txt +done +rm -rf "$T/wrap" +cat >/usr/local/sbin/mdcmd <>$T/mdcmd.calls +EOF + +# the plugin's stop signals mdcmd before the run, so mdcmd can end before it sets the write method back (143 here): the +# run keeps its EXIT trap and tries again as it ends +share 'turbo on, mdcmd fails as the run puts the write method back' yes enableTurbo yes +mk cache sh/a.txt +touch "$T/fail_once" +cat >/usr/local/sbin/mdcmd <>$T/mdcmd.calls +EOF +run 0 +mdcmd_calls 'set md_write_method 1' 'set md_write_method auto' +log_count 1 'Could not restore original turbo write mode Auto (read/modify/write): mdcmd exited 143' +log_count 2 'Restoring original turbo write mode Auto (read/modify/write)' +array_is sh sh/a.txt + +# a stop during the moves, and mdcmd fails to put the write method back: the EXIT trap tries once, before the pid file goes +share 'turbo on, a stop during the moves, mdcmd fails to put the write method back' yes enableTurbo yes +mk cache sh/a.txt +cat >/usr/local/sbin/mdcmd </dev/null) +echo "mdcmd \$*\${w:+ (pid file there)}" >>$T/mdcmd.calls +[ "\$3" != auto ] +EOF +# shellcheck disable=SC2016 # the hook expands it +move_hook 'kill -TERM "$(cat /var/run/mover.pid)"' +run 143 +move_unhook +mdcmd_calls 'set md_write_method 1 (pid file there)' 'set md_write_method auto (pid file there)' +log_count 1 'Could not restore original turbo write mode Auto (read/modify/write): mdcmd exited 1' +check 'the run removed its pid file' '' "$(ls /var/run/mover.pid 2>/dev/null)" +array_is sh sh/a.txt + +share 'turbo on, mdcmd fails to force it' yes enableTurbo yes +mk cache sh/a.txt +cat >/usr/local/sbin/mdcmd <>$T/mdcmd.calls +EOF +run 0 +mdcmd_calls 'set md_write_method auto' +log_count 1 'Could not force turbo write on: mdcmd exited 1' +log_count 1 'Restoring original turbo write mode Auto (read/modify/write)' +array_is sh sh/a.txt +cat >/usr/local/sbin/mdcmd <>$T/mdcmd.calls +EOF + +# a share name with shell in it is a name: the run moves its files and runs nothing +share 'a share name that holds a command' yes +# shellcheck disable=SC2016 # the name holds shell text on purpose +n='a $(touch ran)' +mv /boot/config/shares/sh.cfg "/boot/config/shares/$n.cfg" +mk cache "$n/b.txt" +NAME=$n run 0 +log_has "Complete Mover Command: find \"/mnt/cache/$n\" -type f -depth | /usr/libexec/unraid/move -d 1" +check 'the name ran nothing' no "$([ -e "$T/cwd/ran" ] && echo yes || echo no)" +array_is "$n" "$n/b.txt" + +share 'no enableTurbo or testmode in the plugin config' yes enableTurbo - testmode - +mk cache sh/a.txt +run 0 +log_has 'No Turbo Mode argument provided, defaulting to no' +log_has 'No Test Mode argument provided, defaulting to yes' +log_has 'Running in Test Mode' +check 'enableTurbo="no" was written to the plugin config, testmode was not' 'enableTurbo="no"' "$(grep -E '^(enableTurbo|testmode)=' "$CFG")" +cache_is sh sh/a.txt + +share 'another mover runs' yes +mk cache sh/a.txt +bg mover sleep 30 +echo $! >/var/run/mover.pid +run 1 +kill $! 2>/dev/null +wait $! 2>/dev/null +log_has 'already running' +log_lacks 'Processing sh share' +cache_is sh sh/a.txt + +share 'the pid file holds the running mover with spaces, then a second line' yes +mk cache sh/a.txt +bg mover sleep 30 +printf ' %s \n99999999\n' $! >/var/run/mover.pid +run 1 +kill $! 2>/dev/null +wait $! 2>/dev/null +log_has 'already running' +cache_is sh sh/a.txt + +share 'the pid file names a process that is no mover' yes +mk cache sh/a.txt +bg sleep sleep 30 +echo $! >/var/run/mover.pid +run 0 +kill $! 2>/dev/null +wait $! 2>/dev/null +log_lacks 'already running' +array_is sh sh/a.txt + +share 'an empty pid file' yes +mk cache sh/a.txt +: >/var/run/mover.pid +run 0 +log_lacks 'already running' +array_is sh sh/a.txt + +share 'no share.cfg' yes +rm /boot/config/share.cfg +mk cache sh/a.txt +run 2 +check 'nothing was logged' '' "$(cat "$MOVER_LOG")" +cache_is sh sh/a.txt + +share 'no plugin config' yes +rm "$CFG" +mk cache sh/a.txt +run 3 +log_has "Fatal error: $CFG does not exist, check this." +log_lacks 'Plugin version' +cache_is sh sh/a.txt + +for pools in 1 0; do + share "$pools pool config(s), and no /mnt/user0 mount" yes + rm /boot/config/pools/fast.cfg + [ "$pools" = 1 ] || rm -r /boot/config/pools + mk cache sh/a.txt + run 5 + log_has 'Fatal error: cache not present, or only cache present, and less than 2 pools set up.' + cache_is sh sh/a.txt +done + +rm -rf "${ROOTS[@]}" /boot/config /var/local/emhttp /var/run/mover.pid /usr/local/sbin/mdcmd +finish diff --git a/tests/age_mover/test_stops.sh b/tests/age_mover/test_stops.sh new file mode 100644 index 00000000..465ee831 --- /dev/null +++ b/tests/age_mover/test_stops.sh @@ -0,0 +1,268 @@ +#!/bin/bash +# What processTheMoves does today when a stop, a soft stop or a pause comes before or between its rows. +. "$(dirname "$0")/lib.sh" +# a case writes under /usr/local and /var/local: a mount at either refuses +if ! awk '$5 ~ "^/(usr|var)/local(/|$)" || $5 ~ "^/(usr|var)$" { exit 1 }' /proc/self/mountinfo; then + echo "test_stops.sh writes Unraid's paths and one is a mount here: start it with tests/age_mover/run.sh" >&2 + exit 2 +fi + +HELPERS=() +# after_pause ...: in the background, runs the command s after the run logs its pause; begin removed +# the last case's log +after_pause() { + local s=$1 + shift + (until grep -qF 'Paused: no file moves until Resume' "$MOVER_LOG" 2>/dev/null; do sleep 0.1; done; sleep "$s"; "$@") >/dev/null 2>&1 & + HELPERS+=($!) +} +held() { log | sed -n 's/.*Resumed after \([0-9]*\) s.*/\1/p'; } +# must run before the next case: a helper left running would lift or stop that case's pause +stop_helpers() { + kill "${HELPERS[@]}" 2>/dev/null + wait "${HELPERS[@]}" 2>/dev/null + HELPERS=() +} +order() { log | grep -oE 'Moving "[^"]*"|Paused: no file moves until Resume|Resumed after|Soft Stopping requested'; } + +begin "soft stop after the first file" synchronizeCache yes +mk cache sh/s/1.txt sh/s/2.txt sh/s/3.txt +{ row 'move from primary' f sh/s/1.txt; row 'move from primary' f sh/s/2.txt; row 'sync from primary' f sh/s/3.txt; } | list +after_first_rsync "touch '$SOFTSTOPFILE'" +run_moves +array_is sh sh/s sh/s/1.txt +cache_is sh sh/s sh/s/2.txt sh/s/3.txt +counter MOVEDFILES 1 +check "the order of the moves and the soft stop" "$(printf '%s\n' 'Moving "/mnt/cache/./sh/s/1.txt"' 'Soft Stopping requested')" "$(order)" +log_lacks 'Set last sync date' + +# processTheMoves returns at its start, before its banner; its row loop would also hold the file at the first row +begin "soft stop before the run" +mk cache sh/s/1.txt +row 'move from primary' f sh/s/1.txt | list +touch "$SOFTSTOPFILE" +run_moves +array_is +cache_is sh sh/s sh/s/1.txt +check "the order of the moves and the soft stop" 'Soft Stopping requested' "$(order)" +log_lacks 'LET THE MOVING SHOW BEGIN' + +begin "pause after the first file, lifted 2 s later" +mk cache sh/s/1.txt sh/s/2.txt +for n in 1 2; do row 'move from primary' f "sh/s/$n.txt"; done | list +after_first_rsync "echo $$ >'$PAUSEFILE'" +after_pause 2 rm -f "$PAUSEFILE" +run_moves +stop_helpers +array_is sh sh/s sh/s/1.txt sh/s/2.txt +counter MOVEDFILES 2 +check "the order of the moves and the pause" "$(printf '%s\n' 'Moving "/mnt/cache/./sh/s/1.txt"' 'Paused: no file moves until Resume' \ + 'Resumed after' 'Moving "/mnt/cache/./sh/s/2.txt"')" "$(order)" +check "the pause held from 2 s to under 10 s" yes "$([ "$(held)" -ge 2 ] 2>/dev/null && [ "$(held)" -lt 10 ] && echo yes || echo no)" + +# the lift only ends a pause the run should not have taken, so a broken check fails instead of hanging +begin "a pause file naming another run" +mk cache sh/s/1.txt +row 'move from primary' f sh/s/1.txt | list +echo 1 >"$PAUSEFILE" +after_pause 2 rm -f "$PAUSEFILE" +run_moves +stop_helpers +array_is sh sh/s sh/s/1.txt +log_lacks 'Paused' + +begin "soft stop 2 s into a pause before the first file" +mk cache sh/s/1.txt +row 'move from primary' f sh/s/1.txt | list +echo $$ >"$PAUSEFILE" +after_pause 2 touch "$SOFTSTOPFILE" +after_pause 20 rm -f "$PAUSEFILE" +run_moves +stop_helpers +array_is +cache_is sh sh/s sh/s/1.txt +check "the order of the moves, the pause and the soft stop" "$(printf '%s\n' 'Paused: no file moves until Resume' 'Resumed after' \ + 'Soft Stopping requested')" "$(order)" +check "the pause held under 10 s: the soft stop ended it, not the 20 s lift" yes "$([ "$(held)" -lt 10 ] 2>/dev/null && echo yes || echo no)" + +# Unraid's write method, read/modify/write, and an mdcmd that notes its calls +turbo_standin() { + mkdir -p /usr/local/sbin /var/local/emhttp + echo 'md_write_method="0"' >/var/local/emhttp/var.ini + printf '#!/bin/bash\necho "mdcmd $*" >>%q\n' "$T/mdcmd.calls" >/usr/local/sbin/mdcmd + chmod 755 /usr/local/sbin/mdcmd +} +put_back_once() { + check "turbo write forced, then put back once" "$(printf '%s\n' 'mdcmd set md_write_method 1' 'mdcmd set md_write_method 0')" \ + "$(cat "$T/mdcmd.calls")" + log_count 1 'Restoring original turbo write mode Read/modify/write' + rm -rf /usr/local/sbin/mdcmd /var/local/emhttp "$T/mdcmd.calls" +} + +begin "turbo write on, no stop" enableTurbo yes +mk cache sh/s/1.txt +row 'move from primary' f sh/s/1.txt | list +turbo_standin +run_moves +put_back_once +array_is sh sh/s sh/s/1.txt + +# a stop that ends the run during the moves: the run puts back the write method it forced. The plugin's stop also +# signals the hook, which ignores it, so the rsync wrapper ends by the signal and not by reporting a failed hook +for who in plugin run; do + begin "turbo write on, a stop ($who) after the first file" enableTurbo yes + mk cache sh/s/1.txt sh/s/2.txt + for n in 1 2; do row 'move from primary' f "sh/s/$n.txt"; done | list + turbo_standin + if [ "$who" = plugin ]; then after_first_rsync "trap '' TERM; $(stop_hook plugin)"; else after_first_rsync "$(stop_hook run)"; fi + run_moves 'processTheMoves did not return' + if [ "$who" = plugin ]; then + for _ in $(seq 100); do grep -qs 'mover: stopped' "$T/stop.out" && break; sleep 0.1; done + check "the plugin's stop ended" 1 "$(grep -cs 'mover: stopped' "$T/stop.out")" + rm -f "$T/stop.out" + fi + put_back_once + array_is sh sh/s sh/s/1.txt + cache_is sh sh/s sh/s/2.txt +done + +# a second stop, at the read of var.ini that puts the write method back, waits for it +begin "turbo write on, a second stop as the run puts it back" enableTurbo yes +mk cache sh/s/1.txt sh/s/2.txt +for n in 1 2; do row 'move from primary' f "sh/s/$n.txt"; done | list +turbo_standin +cat >"$T/bin/grep" </dev/null)" +put_back_once +array_is sh sh/s sh/s/1.txt +cache_is sh sh/s sh/s/2.txt + +# the plugin's stop signals mdcmd before the run, so mdcmd can end before it sets the write method back (143 here): the +# run keeps its EXIT trap and tries again as it ends +begin "turbo write on, mdcmd fails as the run puts the write method back" enableTurbo yes +mk cache sh/s/1.txt +row 'move from primary' f sh/s/1.txt | list +turbo_standin +touch "$T/fail_once" +cat >/usr/local/sbin/mdcmd <>$T/mdcmd.calls +EOF +run_moves +check "turbo write forced, then put back as the run ended" "$(printf '%s\n' 'mdcmd set md_write_method 1' \ + 'mdcmd set md_write_method 0')" "$(cat "$T/mdcmd.calls")" +log_count 1 'Could not restore original turbo write mode Read/modify/write: mdcmd exited 143' +log_count 2 'Restoring original turbo write mode Read/modify/write' +rm -rf /usr/local/sbin/mdcmd /var/local/emhttp "$T/mdcmd.calls" +array_is sh sh/s sh/s/1.txt + +begin "turbo write on, mdcmd fails to force it" enableTurbo yes +mk cache sh/s/1.txt +row 'move from primary' f sh/s/1.txt | list +turbo_standin +cat >/usr/local/sbin/mdcmd <>$T/mdcmd.calls +EOF +run_moves +check "the write method was set back as it was" 'mdcmd set md_write_method 0' "$(cat "$T/mdcmd.calls")" +log_count 1 'Could not force turbo write on: mdcmd exited 1' +log_count 1 'Restoring original turbo write mode Read/modify/write' +rm -rf /usr/local/sbin/mdcmd /var/local/emhttp "$T/mdcmd.calls" +array_is sh sh/s sh/s/1.txt + +begin "turbo write on, var.ini gives no write method" enableTurbo yes +mk cache sh/s/1.txt +row 'move from primary' f sh/s/1.txt | list +turbo_standin +: >/var/local/emhttp/var.ini +run_moves +check "mdcmd was not called" "" "$(cat "$T/mdcmd.calls" 2>/dev/null)" +log_has 'Not forcing turbo write on: /var/local/emhttp/var.ini gives no write method (0, 1 or auto) to set back after' +log_lacks 'Restoring original turbo write mode' +rm -rf /usr/local/sbin/mdcmd /var/local/emhttp "$T/mdcmd.calls" +array_is sh sh/s sh/s/1.txt + +begin "turbo write on, in test mode" enableTurbo yes testmode yes +mk cache sh/s/1.txt +row 'move from primary' f sh/s/1.txt | list +turbo_standin +run_moves +check "mdcmd was not called" "" "$(cat "$T/mdcmd.calls" 2>/dev/null)" +log_has 'TEST MODE: Would force turbo write on' +log_has 'TEST MODE: Would restore original turbo write mode Read/modify/write' +log_lacks 'Forcing turbo write on' +log_lacks 'Restoring original turbo write mode' +rm -rf /usr/local/sbin/mdcmd /var/local/emhttp "$T/mdcmd.calls" +cache_is sh sh/s sh/s/1.txt + +# a save in Settings during the moves changes var.ini's write method: that one is set back, or the one read before +# when var.ini then gives none +for now in 'auto Auto (read/modify/write)' ' Read/modify/write'; do + begin "turbo write on, var.ini gives \"${now%% *}\" during the moves" enableTurbo yes + mk cache sh/s/1.txt + row 'move from primary' f sh/s/1.txt | list + turbo_standin + after_first_rsync "echo 'md_write_method=\"${now%% *}\"' >/var/local/emhttp/var.ini" + run_moves + w=${now%% *} + check "turbo write forced, then set back to ${w:-0}" "$(printf '%s\n' 'mdcmd set md_write_method 1' \ + "mdcmd set md_write_method ${w:-0}")" "$(cat "$T/mdcmd.calls")" + log_count 1 "Restoring original turbo write mode ${now#* }" + rm -rf /usr/local/sbin/mdcmd /var/local/emhttp "$T/mdcmd.calls" + array_is sh sh/s sh/s/1.txt +done + +# a process pgrep lists can end before its TERM, or between its TERM and CONT: a pid no process can have stands for the +# first, so no real one is signalled, and a kill that waits after each TERM until its process has gone for the second +begin "the plugin's stop, listed processes that end before or between its signals" +real_pgrep=$(command -v pgrep) +# this script waits on the run, so it is reaped as it ends: one nobody reaps would still answer the stop's kill -0 +bash -c 'sleep 30 && exit 3' & +run=$! +gone=$(($(cat /proc/sys/kernel/pid_max) + 1)) +# shellcheck disable=SC2016 # the stand-in expands its own $@ and $* +printf '#!/bin/bash\n%q "$@"\n[ "${*: -1}" != %q ] || echo %q\n' "$real_pgrep" "$run" "$gone" >"$T/bin/pgrep" +chmod 755 "$T/bin/pgrep" +hash -r +echo "$run" >"$T/pid" +# shellcheck disable=SC2034,SC2329 # stop, from funcs.sh, reads the variables and calls kill +( + kill() { + builtin kill "$@" || return + [ "$1" = -TERM ] || return 0 + for _ in $(seq 50); do builtin kill -0 "$2" 2>/dev/null || return 0; sleep 0.1; done + } + PIDFILE=$T/pid MOVER_STATUS=$T/mover.ini PAUSEFILE=$T/pause MOVINGFILE=$T/moving + stop +) >"$T/stop.out" 2>&1 & +stopper=$! +wait "$run" +check "the stop ended the run" 143 "$?" +wait "$stopper" +rm -f "$T/bin/pgrep" +hash -r +check "the stop said only that it stopped" 'mover: stopped' "$(cat "$T/stop.out")" +check "the stop removed the pid file" "" "$(ls "$T/pid" 2>/dev/null)" +rm -f "$T/stop.out" + +finish