forked from vitalif/vitastor
Compare commits
292 Commits
fix-intent
...
fix-pick-n
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7bf873996c | ||
| 37a643fd02 | |||
| 265f00cd3f | |||
| def62d401d | |||
| f3fd41d12c | |||
| 027ef85d5d | |||
| ec74399871 | |||
| f7793e37c1 | |||
| fae749d515 | |||
| 913f70c2dd | |||
| e2544bf34f | |||
| 97baef8cdf | |||
| 00bd701a97 | |||
| 9d695fe690 | |||
| 08e00c9300 | |||
| 2cc6942c7a | |||
| c3a4398792 | |||
| 54b8d2c0ed | |||
| dade4372b1 | |||
| 6b103473c5 | |||
| d3b893ae2b | |||
| 4810971d96 | |||
| 1b4f036b4e | |||
| 1544fcdb3a | |||
| 5d9d404c8b | |||
| 6601ad9265 | |||
| 884727af62 | |||
| 49e76ea850 | |||
| 7cb1edb522 | |||
| 5133d5caba | |||
| de3644bc00 | |||
| 6dc8758ed8 | |||
| b21b09effb | |||
| 5532770ea4 | |||
| 2df2a50b2f | |||
| f2de842662 | |||
| 58ddb3b068 | |||
| c2117bc930 | |||
| 14c1341213 | |||
| eb51a5d978 | |||
| 4ee30fa775 | |||
| 74fea63bfa | |||
| 9ebdc0ef89 | |||
| e9570efe99 | |||
| c3d082368a | |||
| f0afdce8b0 | |||
| 36e38503e7 | |||
| 87dceccf38 | |||
| c365fd74ab | |||
| 02d029dc33 | |||
| d5af419a91 | |||
| a211741edb | |||
| 483f581813 | |||
| ce33722edf | |||
| 3bf0b45a18 | |||
| 019d644a88 | |||
| 89201f39e0 | |||
| 3e4aa53357 | |||
| 8dc2f0b07a | |||
| 5ec30ca166 | |||
| 7cc4553e01 | |||
| e4030c9f73 | |||
| cf5c466e83 | |||
| 63f51d602f | |||
| 971d45def6 | |||
| 2fc65145fb | |||
| c9617bc9e0 | |||
| db0622c576 | |||
| 64b2265aa4 | |||
| 7c76601c45 | |||
| 4ad3c8037d | |||
| ac3f6f85fc | |||
| 8582f82356 | |||
| e2d7674cd5 | |||
| 48d53ef69f | |||
| 1ba35c3b5e | |||
| e1f945f443 | |||
| 7a95269a05 | |||
| eea278cfc5 | |||
| beb52fdf16 | |||
| ef76796a1d | |||
| ccfacd1c6b | |||
| 3f9cd01867 | |||
| a7a6d5f38e | |||
| 01b501c686 | |||
| 59e91f595d | |||
| d75df73c3a | |||
| f539bba0eb | |||
| ddcd3aef87 | |||
| 977b084af8 | |||
| e0b683a634 | |||
| ac808fefe7 | |||
| c4defad6bf | |||
| bbcfe3e258 | |||
| c0d6a417ba | |||
| 23b9bff8fb | |||
|
|
e2c5ec8824 | ||
|
|
0757a1e8b9 | ||
| cfaa3feefa | |||
| 4e638b2681 | |||
| 3e803e07d6 | |||
|
|
d5465622ed | ||
| 63dc07b4c9 | |||
| a39319beb7 | |||
| 801231e8d4 | |||
| 33195f9c41 | |||
| aca9dcb1a9 | |||
| 9d1489c86f | |||
| be897e278c | |||
| b06faf04cb | |||
| 54b3376d00 | |||
| 7622bbf2e1 | |||
| 48a8720ba8 | |||
| dacdd9e8d3 | |||
| 5a6343f21d | |||
| c4359a4a8d | |||
| d3e708dd8d | |||
| d775042a36 | |||
|
|
303c602ea5 | ||
| c159b9019d | |||
| cd2ccf9f37 | |||
| 4b5442e84c | |||
| 32421ed404 | |||
| 8ef4e7db93 | |||
| beef3d64df | |||
| f308a54fb5 | |||
| 9684e1afb3 | |||
| 911a79f03b | |||
| ddb699c5e8 | |||
| d2b879098d | |||
| a83a0aed07 | |||
| 357dab2c5c | |||
| 2be4191e55 | |||
| f3b80e0e6c | |||
|
|
4d34da9483 | ||
|
|
8dd76839f1 | ||
|
|
bba9aacfe3 | ||
| e11d3afb22 | |||
| cd06495a2d | |||
| df8b7d3aff | |||
| 7614031995 | |||
| 21f188d64c | |||
| 5decb9d910 | |||
| 5fc210aa0e | |||
| daba5f02bb | |||
| 30a90e5824 | |||
| 8ad9131303 | |||
| 38e79f7f54 | |||
| 4404e18092 | |||
| 0be24276e5 | |||
| e24488de63 | |||
| 3cf04530df | |||
| 15c31260a5 | |||
| 2e223f03e4 | |||
| eac58a17a7 | |||
| 0d35d83585 | |||
| 2316d36840 | |||
| 368daa4b1e | |||
| d16423bb85 | |||
| 2eb072ecbf | |||
| ee47e3b0c3 | |||
| 3c0284d134 | |||
|
|
45ce3f2842 | ||
| b1fd754832 | |||
| 68ade43e70 | |||
| c64528eb80 | |||
| 7bac25cbed | |||
| 771a73c181 | |||
| f830b693db | |||
| 9953ca366c | |||
| c0afde8989 | |||
| 376237bc6a | |||
| 9c2ee9d6ba | |||
| 00f42b4b79 | |||
| bf33844740 | |||
| 1094f1b370 | |||
| d09a72fbbc | |||
| f3e047fb05 | |||
| df593badb5 | |||
|
|
b51c05200d | ||
| 6d1b9165a2 | |||
| e58b37b284 | |||
| 53c7da3e2d | |||
| 75a35c3b36 | |||
| a375f43a93 | |||
| 22ae66b95f | |||
| 456fad7fa7 | |||
| 06a5d24240 | |||
| a6a99a5967 | |||
| eba8ca7192 | |||
|
|
e1d9121870 | ||
| 72620ebee5 | |||
| d0e3ee4c2a | |||
| 328bf0cba1 | |||
| 16ce85d685 | |||
| 606dd820cd | |||
| f9f0b35311 | |||
| 778a3469b4 | |||
| a8ed25ddf5 | |||
| 49877a0fa9 | |||
| 4e11fd256e | |||
| 1a1c338cc9 | |||
| 7f88846a5d | |||
| d5f1f6967a | |||
| c486a14f6a | |||
| df3c8cf72b | |||
| a8f5d7cafe | |||
| c5efed2061 | |||
| d5e56827c7 | |||
| a788add518 | |||
| d5ebc93e7d | |||
| 9d4067bcf0 | |||
| 0be4cba1e6 | |||
| 2179f6ab55 | |||
| 1dd4cbd7c3 | |||
| 174b36cf46 | |||
| eb6328d443 | |||
| c560f3883d | |||
| 4d96f73738 | |||
| 7cbdd831c7 | |||
| 820a226b1d | |||
| a25625a1d3 | |||
| db0b6ec926 | |||
| 097afe5d8b | |||
| fbf48a86be | |||
| 2cb32f704d | |||
| d397d7ac3e | |||
| 9d36831ae7 | |||
| 85976c2f31 | |||
| 517c016324 | |||
|
|
2b5078823a | ||
|
|
b2d5206613 | ||
|
|
c67843e6b5 | ||
|
|
9353a58446 | ||
| 7e0ba6d312 | |||
| beb7854e39 | |||
| 4d567dd0e6 | |||
|
|
4b95d248bf | ||
| cee6882d6e | |||
| 5c45425235 | |||
| dd9b9f926d | |||
| 806ebf5bcd | |||
| 5f4e394eb0 | |||
| 50e36a04df | |||
| 9fc2781798 | |||
| 26c6251888 | |||
| 145942fc3c | |||
| 2a68ad2a05 | |||
| 10a6782bdf | |||
| 5f2b46bb57 | |||
| f9a247df42 | |||
| 6f55e36998 | |||
| 1cbe466c39 | |||
| 38a0a9b9b7 | |||
| c826cbb735 | |||
| 6038c537da | |||
| 77481dd824 | |||
| 9ff24abc0e | |||
| c2dc2e5840 | |||
| df9a285019 | |||
| a55cca724e | |||
| 74c5047412 | |||
| 157ef711d4 | |||
| 96983a4718 | |||
| 1af744d1e3 | |||
| db86731851 | |||
| c14135cb7a | |||
| cef3f16cca | |||
| 145c279f82 | |||
| d153583c7f | |||
| 0e9fe3a19f | |||
| ae8d47bffa | |||
| 2b25bb9488 | |||
| cb89e17255 | |||
| 2ed098ea22 | |||
| 3cf7b1038e | |||
| 87a57f577b | |||
| 2233116023 | |||
| 9a4b61424a | |||
| cde8f5b2c3 | |||
| d1bbb4578f | |||
| bdfc7349b9 | |||
| 17a65f570d | |||
| 7bfe12a8f9 | |||
| 8f8b43d1d4 | |||
| 824762a04e | |||
| 090c28c7c5 | |||
| c35e101341 | |||
| 230460e937 | |||
| 2a38d5d117 | |||
| 43d3d6560f | |||
| 6d7223d9e9 |
@@ -21,9 +21,9 @@ RUN echo 'deb http://deb.debian.org/debian bookworm-backports main' >> /etc/apt/
|
||||
|
||||
RUN apt-get update
|
||||
RUN apt-get -y install etcd qemu-system-x86 qemu-block-extra qemu-utils fio libasan8 \
|
||||
libgoogle-perftools-dev devscripts libjerasure-dev cmake libibverbs-dev libisal-dev
|
||||
libgoogle-perftools-dev devscripts libjerasure-dev cmake libibverbs-dev libisal-dev \
|
||||
jq lp-solve sudo nfs-common fdisk parted libc-ares-dev udev iproute2 libnl-3-dev libnl-genl-3-dev
|
||||
RUN apt-get -y build-dep fio qemu=`dpkg -s qemu-system-x86|grep ^Version:|awk '{print $2}'`
|
||||
RUN apt-get update && apt-get -y install jq lp-solve sudo nfs-common fdisk parted libc-ares-dev udev iproute2
|
||||
RUN apt-get --download-only source fio qemu=`dpkg -s qemu-system-x86|grep ^Version:|awk '{print $2}'`
|
||||
|
||||
RUN set -ex; \
|
||||
|
||||
@@ -62,8 +62,13 @@ jobs:
|
||||
needs: build
|
||||
container: ${{env.TEST_IMAGE}}:${{github.sha}}
|
||||
steps:
|
||||
# leak sanitizer sometimes crashes
|
||||
- run: cd /root/vitastor/build && ASAN_OPTIONS=detect_leaks=0 make -j16 build_tests test
|
||||
- name: Run tests
|
||||
id: test
|
||||
run: cd /root/vitastor/build && make -j16 build_tests test
|
||||
- name: Print logs
|
||||
if: always() && steps.test.outcome == 'failure'
|
||||
run: |
|
||||
cat /root/vitastor/build/Testing/Temporary/LastTest.log
|
||||
|
||||
npm_lint:
|
||||
runs-on: ubuntu-latest
|
||||
@@ -108,6 +113,24 @@ jobs:
|
||||
echo ""
|
||||
done
|
||||
|
||||
test_cas_imm:
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
container: ${{env.TEST_IMAGE}}:${{github.sha}}
|
||||
steps:
|
||||
- name: Run test
|
||||
id: test
|
||||
timeout-minutes: 3
|
||||
run: IMMEDIATE_COMMIT=1 /root/vitastor/tests/test_cas.sh
|
||||
- name: Print logs
|
||||
if: always() && steps.test.outcome == 'failure'
|
||||
run: |
|
||||
for i in /root/vitastor/testdata/*.log /root/vitastor/testdata/*.txt; do
|
||||
echo "-------- $i --------"
|
||||
cat $i
|
||||
echo ""
|
||||
done
|
||||
|
||||
test_change_pg_count:
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
@@ -216,6 +239,24 @@ jobs:
|
||||
echo ""
|
||||
done
|
||||
|
||||
test_modify_pool:
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
container: ${{env.TEST_IMAGE}}:${{github.sha}}
|
||||
steps:
|
||||
- name: Run test
|
||||
id: test
|
||||
timeout-minutes: 3
|
||||
run: /root/vitastor/tests/test_modify_pool.sh
|
||||
- name: Print logs
|
||||
if: always() && steps.test.outcome == 'failure'
|
||||
run: |
|
||||
for i in /root/vitastor/testdata/*.log /root/vitastor/testdata/*.txt; do
|
||||
echo "-------- $i --------"
|
||||
cat $i
|
||||
echo ""
|
||||
done
|
||||
|
||||
test_etcd_fail:
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
@@ -774,6 +815,24 @@ jobs:
|
||||
echo ""
|
||||
done
|
||||
|
||||
test_modify_image_resize:
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
container: ${{env.TEST_IMAGE}}:${{github.sha}}
|
||||
steps:
|
||||
- name: Run test
|
||||
id: test
|
||||
timeout-minutes: 3
|
||||
run: /root/vitastor/tests/test_modify_image_resize.sh
|
||||
- name: Print logs
|
||||
if: always() && steps.test.outcome == 'failure'
|
||||
run: |
|
||||
for i in /root/vitastor/testdata/*.log /root/vitastor/testdata/*.txt; do
|
||||
echo "-------- $i --------"
|
||||
cat $i
|
||||
echo ""
|
||||
done
|
||||
|
||||
test_rm_degraded:
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
@@ -792,6 +851,24 @@ jobs:
|
||||
echo ""
|
||||
done
|
||||
|
||||
test_describe:
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
container: ${{env.TEST_IMAGE}}:${{github.sha}}
|
||||
steps:
|
||||
- name: Run test
|
||||
id: test
|
||||
timeout-minutes: 3
|
||||
run: /root/vitastor/tests/test_describe.sh
|
||||
- name: Print logs
|
||||
if: always() && steps.test.outcome == 'failure'
|
||||
run: |
|
||||
for i in /root/vitastor/testdata/*.log /root/vitastor/testdata/*.txt; do
|
||||
echo "-------- $i --------"
|
||||
cat $i
|
||||
echo ""
|
||||
done
|
||||
|
||||
test_snapshot_chain:
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
@@ -972,6 +1049,24 @@ jobs:
|
||||
echo ""
|
||||
done
|
||||
|
||||
test_snapshot_rm_parallel:
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
container: ${{env.TEST_IMAGE}}:${{github.sha}}
|
||||
steps:
|
||||
- name: Run test
|
||||
id: test
|
||||
timeout-minutes: 3
|
||||
run: /root/vitastor/tests/test_snapshot_rm_parallel.sh
|
||||
- name: Print logs
|
||||
if: always() && steps.test.outcome == 'failure'
|
||||
run: |
|
||||
for i in /root/vitastor/testdata/*.log /root/vitastor/testdata/*.txt; do
|
||||
echo "-------- $i --------"
|
||||
cat $i
|
||||
echo ""
|
||||
done
|
||||
|
||||
test_kv_stress:
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
@@ -1188,6 +1283,24 @@ jobs:
|
||||
echo ""
|
||||
done
|
||||
|
||||
test_cli_help:
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
container: ${{env.TEST_IMAGE}}:${{github.sha}}
|
||||
steps:
|
||||
- name: Run test
|
||||
id: test
|
||||
timeout-minutes: 3
|
||||
run: /root/vitastor/tests/test_cli_help.sh
|
||||
- name: Print logs
|
||||
if: always() && steps.test.outcome == 'failure'
|
||||
run: |
|
||||
for i in /root/vitastor/testdata/*.log /root/vitastor/testdata/*.txt; do
|
||||
echo "-------- $i --------"
|
||||
cat $i
|
||||
echo ""
|
||||
done
|
||||
|
||||
test_root_node:
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
@@ -1566,6 +1679,24 @@ jobs:
|
||||
echo ""
|
||||
done
|
||||
|
||||
test_ls_tree:
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
container: ${{env.TEST_IMAGE}}:${{github.sha}}
|
||||
steps:
|
||||
- name: Run test
|
||||
id: test
|
||||
timeout-minutes: 3
|
||||
run: /root/vitastor/tests/test_ls_tree.sh
|
||||
- name: Print logs
|
||||
if: always() && steps.test.outcome == 'failure'
|
||||
run: |
|
||||
for i in /root/vitastor/testdata/*.log /root/vitastor/testdata/*.txt; do
|
||||
echo "-------- $i --------"
|
||||
cat $i
|
||||
echo ""
|
||||
done
|
||||
|
||||
test_snapshot_read_bitmap:
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
@@ -1962,6 +2093,24 @@ jobs:
|
||||
echo ""
|
||||
done
|
||||
|
||||
test_recovery_enospc:
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
container: ${{env.TEST_IMAGE}}:${{github.sha}}
|
||||
steps:
|
||||
- name: Run test
|
||||
id: test
|
||||
timeout-minutes: 3
|
||||
run: /root/vitastor/tests/test_recovery_enospc.sh
|
||||
- name: Print logs
|
||||
if: always() && steps.test.outcome == 'failure'
|
||||
run: |
|
||||
for i in /root/vitastor/testdata/*.log /root/vitastor/testdata/*.txt; do
|
||||
echo "-------- $i --------"
|
||||
cat $i
|
||||
echo ""
|
||||
done
|
||||
|
||||
test_scrub:
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
@@ -2070,6 +2219,24 @@ jobs:
|
||||
echo ""
|
||||
done
|
||||
|
||||
test_scrub_deleted_incomplete:
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
container: ${{env.TEST_IMAGE}}:${{github.sha}}
|
||||
steps:
|
||||
- name: Run test
|
||||
id: test
|
||||
timeout-minutes: 3
|
||||
run: /root/vitastor/tests/test_scrub_deleted_incomplete.sh
|
||||
- name: Print logs
|
||||
if: always() && steps.test.outcome == 'failure'
|
||||
run: |
|
||||
for i in /root/vitastor/testdata/*.log /root/vitastor/testdata/*.txt; do
|
||||
echo "-------- $i --------"
|
||||
cat $i
|
||||
echo ""
|
||||
done
|
||||
|
||||
test_old_scrub:
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
|
||||
@@ -2,7 +2,7 @@ cmake_minimum_required(VERSION 2.8...3.30)
|
||||
|
||||
project(vitastor)
|
||||
|
||||
set(VITASTOR_VERSION "3.1.0")
|
||||
set(VITASTOR_VERSION "3.2.3")
|
||||
|
||||
include(CTest)
|
||||
|
||||
|
||||
@@ -75,6 +75,9 @@ Vitastor поддерживает QEMU-драйвер, протоколы UBLK,
|
||||
- [NFS](docs/usage/nfs.ru.md) кластерная файловая система и псевдо-ФС прокси
|
||||
- [Безопасность](docs/usage/security.ru.md)
|
||||
- [Администрирование](docs/usage/admin.ru.md)
|
||||
- Тесты
|
||||
- [Хаос тест хранилища](docs/tests/blockstore-chaos.ru.md)
|
||||
- [Хаос тест PG](docs/tests/pg-chaos.ru.md)
|
||||
- Производительность
|
||||
- [Понимание сути производительности](docs/performance/understanding.ru.md)
|
||||
- [Теоретический максимум](docs/performance/theoretical.ru.md)
|
||||
|
||||
@@ -75,6 +75,9 @@ Read more details in the documentation. You can start from here: [Quick Start](d
|
||||
- [NFS](docs/usage/nfs.en.md) clustered file system and pseudo-FS proxy
|
||||
- [Security](docs/usage/security.en.md)
|
||||
- [Administration](docs/usage/admin.en.md)
|
||||
- Tests
|
||||
- [Blockstore chaos test](docs/tests/blockstore-chaos.en.md)
|
||||
- [PG chaos test](docs/tests/pg-chaos.en.md)
|
||||
- Performance
|
||||
- [Understanding storage performance](docs/performance/understanding.en.md)
|
||||
- [Theoretical performance](docs/performance/theoretical.en.md)
|
||||
|
||||
Submodule cpp-btree updated: 431d2e1d35...bea37ef717
@@ -37,8 +37,8 @@ RUN (echo deb http://vitastor.io/debian trixie main > /etc/apt/sources.list.d/vi
|
||||
wget -q -O /etc/apt/trusted.gpg.d/vitastor.gpg https://vitastor.io/debian/pubkey.gpg && \
|
||||
apt-get update && \
|
||||
apt-get install -y vitastor-client ibverbs-providers && \
|
||||
wget https://vitastor.io/archive/qemu/qemu-trixie-10.0.2%2Bds-2%2Bvitastor1/qemu-utils_10.0.2%2Bds-2%2Bvitastor1_amd64.deb && \
|
||||
wget https://vitastor.io/archive/qemu/qemu-trixie-10.0.2%2Bds-2%2Bvitastor1/qemu-block-extra_10.0.2%2Bds-2%2Bvitastor1_amd64.deb && \
|
||||
wget https://vitastor.io/archive/qemu/qemu-trixie-10.0.11%2Bds-0%2Bdeb13u1%2Bvitastor2/qemu-utils_10.0.11%2Bds-0%2Bdeb13u1%2Bvitastor2_amd64.deb && \
|
||||
wget https://vitastor.io/archive/qemu/qemu-trixie-10.0.11%2Bds-0%2Bdeb13u1%2Bvitastor2/qemu-block-extra_10.0.11%2Bds-0%2Bdeb13u1%2Bvitastor2_amd64.deb && \
|
||||
dpkg -x qemu-utils*.deb tmp1 && \
|
||||
dpkg -x qemu-block-extra*.deb tmp1 && \
|
||||
cp -a tmp1/usr/bin/qemu-storage-daemon /usr/bin/ && \
|
||||
|
||||
@@ -25,8 +25,8 @@ RUN apt-get update && \
|
||||
# NFS mount dependencies
|
||||
nfs-common netbase \
|
||||
# dependencies of qemu-storage-daemon
|
||||
libnuma1 liburing2 libglib2.0-0 libfuse3-3 libaio1 libzstd1 libnettle8 \
|
||||
libgmp10 libhogweed6 libp11-kit0 libidn2-0 libunistring2 libtasn1-6 libpcre2-8-0 libffi8 && \
|
||||
libaio1t64 libc6 libfuse3-4 libglib2.0-0t64 libgmp10 libgnutls30t64 \
|
||||
libhogweed6t64 libnettle8t64 libnuma1 libselinux1 liburing2 libzstd1 zlib1g && \
|
||||
apt-get clean && \
|
||||
(echo options nbd nbds_max=128 > /etc/modprobe.d/nbd.conf)
|
||||
|
||||
@@ -36,8 +36,8 @@ ADD deb /deb
|
||||
|
||||
RUN apt-get update && \
|
||||
apt-get -y install /deb/vitastor-client_*.deb && \
|
||||
wget https://vitastor.io/archive/qemu/qemu-trixie-9.2.2%2Bds-1%2Bvitastor4/qemu-utils_9.2.2%2Bds-1%2Bvitastor4_amd64.deb && \
|
||||
wget https://vitastor.io/archive/qemu/qemu-trixie-9.2.2%2Bds-1%2Bvitastor4/qemu-block-extra_9.2.2%2Bds-1%2Bvitastor4_amd64.deb && \
|
||||
wget https://vitastor.io/archive/qemu/qemu-trixie-10.0.11%2Bds-0%2Bdeb13u1%2Bvitastor2/qemu-utils_10.0.11%2Bds-0%2Bdeb13u1%2Bvitastor2_amd64.deb && \
|
||||
wget https://vitastor.io/archive/qemu/qemu-trixie-10.0.11%2Bds-0%2Bdeb13u1%2Bvitastor2/qemu-block-extra_10.0.11%2Bds-0%2Bdeb13u1%2Bvitastor2_amd64.deb && \
|
||||
dpkg -x qemu-utils*.deb tmp1 && \
|
||||
dpkg -x qemu-block-extra*.deb tmp1 && \
|
||||
cp -a tmp1/usr/bin/qemu-storage-daemon /usr/bin/ && \
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
VITASTOR_VERSION ?= v3.1.0
|
||||
VITASTOR_VERSION ?= v3.2.3
|
||||
|
||||
all: build push
|
||||
|
||||
|
||||
@@ -49,7 +49,7 @@ spec:
|
||||
capabilities:
|
||||
add: ["SYS_ADMIN"]
|
||||
allowPrivilegeEscalation: true
|
||||
image: vitalif/vitastor-csi:v3.1.0
|
||||
image: vitalif/vitastor-csi:v3.2.3
|
||||
args:
|
||||
- "--node=$(NODE_ID)"
|
||||
- "--endpoint=$(CSI_ENDPOINT)"
|
||||
|
||||
@@ -87,7 +87,7 @@ spec:
|
||||
- name: socket-dir
|
||||
mountPath: /csi
|
||||
- name: csi-attacher
|
||||
image: k8s.gcr.io/sig-storage/csi-attacher:v3.1.0
|
||||
image: k8s.gcr.io/sig-storage/csi-attacher:v3.2.3
|
||||
args:
|
||||
- "--v=5"
|
||||
- "--csi-address=$(ADDRESS)"
|
||||
@@ -121,7 +121,7 @@ spec:
|
||||
privileged: true
|
||||
capabilities:
|
||||
add: ["SYS_ADMIN"]
|
||||
image: vitalif/vitastor-csi:v3.1.0
|
||||
image: vitalif/vitastor-csi:v3.2.3
|
||||
args:
|
||||
- "--node=$(NODE_ID)"
|
||||
- "--endpoint=$(CSI_ENDPOINT)"
|
||||
|
||||
@@ -7,6 +7,7 @@ require (
|
||||
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b
|
||||
github.com/kubernetes-csi/csi-lib-utils v0.9.1
|
||||
golang.org/x/net v0.7.0
|
||||
golang.org/x/sys v0.5.0 // indirect
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
|
||||
google.golang.org/grpc v1.33.1
|
||||
google.golang.org/protobuf v1.24.0
|
||||
|
||||
@@ -5,7 +5,7 @@ package vitastor
|
||||
|
||||
const (
|
||||
vitastorCSIDriverName = "csi.vitastor.io"
|
||||
vitastorCSIDriverVersion = "3.1.0"
|
||||
vitastorCSIDriverVersion = "3.2.3"
|
||||
)
|
||||
|
||||
// Config struct fills the parameters of request or user input
|
||||
|
||||
@@ -8,7 +8,6 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
"os"
|
||||
"io/ioutil"
|
||||
|
||||
|
||||
@@ -96,18 +96,16 @@ func NewNodeServer(driver *Driver) *NodeServer
|
||||
{
|
||||
ns.restoreUblkDaemons()
|
||||
}
|
||||
if (ns.method == MOUNT_VDUSE || ns.method == MOUNT_UBLK)
|
||||
ns.restoreNfsDaemons()
|
||||
dur, err := time.ParseDuration(os.Getenv("RESTART_INTERVAL"))
|
||||
if (err != nil)
|
||||
{
|
||||
dur, err := time.ParseDuration(os.Getenv("RESTART_INTERVAL"))
|
||||
if (err != nil)
|
||||
{
|
||||
dur = 10 * time.Second
|
||||
}
|
||||
ns.restartInterval = dur
|
||||
if (ns.restartInterval != time.Duration(0))
|
||||
{
|
||||
go ns.restarter()
|
||||
}
|
||||
dur = 10 * time.Second
|
||||
}
|
||||
ns.restartInterval = dur
|
||||
if (ns.restartInterval != time.Duration(0))
|
||||
{
|
||||
go ns.restarter()
|
||||
}
|
||||
return ns
|
||||
}
|
||||
@@ -134,10 +132,8 @@ func (ns *NodeServer) unlockVolume(lockId string)
|
||||
|
||||
func (ns *NodeServer) restarter()
|
||||
{
|
||||
// Restart dead VDUSE daemons at regular intervals
|
||||
// Otherwise volume I/O may hang in case of a qemu-storage-daemon crash
|
||||
// Moreover, it may lead to a kernel panic of the kernel is configured to
|
||||
// panic on hung tasks
|
||||
// Restart dead storage daemons at regular intervals. Otherwise volume I/O
|
||||
// may hang and may even lead to a kernel panic if panic_on_hung_task is set.
|
||||
ticker := time.NewTicker(ns.restartInterval)
|
||||
defer ticker.Stop()
|
||||
for
|
||||
@@ -151,6 +147,7 @@ func (ns *NodeServer) restarter()
|
||||
{
|
||||
ns.restoreUblkDaemons()
|
||||
}
|
||||
ns.restoreNfsDaemons()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -329,15 +326,10 @@ func (ns *NodeServer) restoreNfsDaemons()
|
||||
{
|
||||
return
|
||||
}
|
||||
activeNFS, err := ns.listActiveNFS()
|
||||
if (err != nil)
|
||||
{
|
||||
return
|
||||
}
|
||||
// Check all state files and try to restore active mounts
|
||||
for _, stateFile := range stateFiles
|
||||
{
|
||||
ns.checkNfsState(stateFile, activeNFS)
|
||||
ns.checkNfsState(stateFile)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -363,24 +355,43 @@ func (ns *NodeServer) readNfsState(stateFile string, allowNotExists bool) (*NfsS
|
||||
return &state, nil
|
||||
}
|
||||
|
||||
func (ns *NodeServer) checkNfsState(stateFile string, activeNfs map[int][]string)
|
||||
func (ns *NodeServer) checkNfsState(stateFile string)
|
||||
{
|
||||
// Read state file
|
||||
// Read state file to determine the lock ID
|
||||
state, err := ns.readNfsState(stateFile, false)
|
||||
if (err != nil)
|
||||
{
|
||||
return
|
||||
}
|
||||
// Lock FS
|
||||
ns.lockVolume(state.ConfigPath+":fs:"+state.FsName)
|
||||
defer ns.unlockVolume(state.ConfigPath+":fs:"+state.FsName)
|
||||
// Check if NFS at this port is still mounted
|
||||
lockId := state.ConfigPath+":fs:"+state.FsName
|
||||
ns.lockVolume(lockId)
|
||||
defer ns.unlockVolume(lockId)
|
||||
// Recheck state and mounts under the lock: publish/unpublish may have changed
|
||||
// both while this recovery attempt was waiting for the lock.
|
||||
state, err = ns.readNfsState(stateFile, true)
|
||||
if (err != nil || state == nil)
|
||||
{
|
||||
return
|
||||
}
|
||||
activeNfs, err := ns.listActiveNFS()
|
||||
if (err != nil)
|
||||
{
|
||||
return
|
||||
}
|
||||
pidFile := ns.stateDir + filepath.Base(stateFile)
|
||||
pidFile = pidFile[0:len(pidFile)-5] + ".pid"
|
||||
if (len(activeNfs[state.Port]) == 0)
|
||||
{
|
||||
// this is a stale state file, remove it
|
||||
// This is a stale state file. Remove the root staging mount before
|
||||
// stopping the daemon, otherwise a dead hidden NFS mount may remain.
|
||||
klog.Warningf("state file %v contains stale mount at port %d, removing it", stateFile, state.Port)
|
||||
err = mount.CleanupMountPoint(state.Path, ns.mounter, false)
|
||||
if (err != nil)
|
||||
{
|
||||
klog.Errorf("failed to unmount stale NFS mount %v: %v", state.Path, err)
|
||||
return
|
||||
}
|
||||
ns.stopNFS(stateFile, pidFile)
|
||||
return
|
||||
}
|
||||
@@ -400,6 +411,7 @@ func (ns *NodeServer) checkNfsState(stateFile string, activeNfs map[int][]string
|
||||
"--pidfile", pidFile,
|
||||
"--bind", "127.0.0.1",
|
||||
"--port", fmt.Sprintf("%d", state.Port),
|
||||
"--config_path", state.ConfigPath,
|
||||
"--fs", state.FsName,
|
||||
"--pool", state.Pool,
|
||||
"--portmap", "0",
|
||||
@@ -725,6 +737,7 @@ func (ns *NodeServer) mountNFS(ctxVars map[string]string) (string, error)
|
||||
"--pidfile", pidFile,
|
||||
"--bind", "127.0.0.1",
|
||||
"--port", "auto",
|
||||
"--config_path", state.ConfigPath,
|
||||
"--fs", state.FsName,
|
||||
"--pool", state.Pool,
|
||||
"--portmap", "0",
|
||||
@@ -815,26 +828,38 @@ func (ns *NodeServer) listActiveNFS() (map[int][]string, error)
|
||||
klog.Errorf("failed to list mounts: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
return collectActiveNFS(mounts), nil
|
||||
}
|
||||
|
||||
func collectActiveNFS(mounts []mount.MountInfo) map[int][]string
|
||||
{
|
||||
activeNFS := make(map[int][]string)
|
||||
for _, mount := range mounts
|
||||
for _, mnt := range mounts
|
||||
{
|
||||
// Volume mounts always refer to subpaths
|
||||
if (mount.FsType == "nfs" && mount.Root != "/")
|
||||
// Only count PVC subdirectory mounts, not the root staging mount. Newer
|
||||
// kernels expose the subdirectory in Source while older ones expose it
|
||||
// in Root. The staging mount may also be visible through several bind
|
||||
// aliases in the CSI container, so its mount point isn't a reliable
|
||||
// discriminator.
|
||||
if (mnt.FsType != "nfs" || !strings.HasPrefix(mnt.Source, "127.0.0.1:/") ||
|
||||
(mnt.Source == "127.0.0.1:/" && mnt.Root == "/"))
|
||||
{
|
||||
for _, opt := range mount.MountOptions
|
||||
continue
|
||||
}
|
||||
// NFS-specific options, including port, are per-superblock options.
|
||||
for _, opt := range mnt.SuperOptions
|
||||
{
|
||||
if (strings.HasPrefix(opt, "port="))
|
||||
{
|
||||
if (strings.HasPrefix(opt, "port="))
|
||||
port64, err := strconv.ParseUint(opt[5:], 10, 16)
|
||||
if (err == nil)
|
||||
{
|
||||
port64, err := strconv.ParseUint(opt[5:], 10, 16)
|
||||
if (err == nil)
|
||||
{
|
||||
activeNFS[int(port64)] = append(activeNFS[int(port64)], mount.MountPoint)
|
||||
}
|
||||
activeNFS[int(port64)] = append(activeNFS[int(port64)], mnt.MountPoint)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return activeNFS, nil
|
||||
return activeNFS
|
||||
}
|
||||
|
||||
// NodePublishVolume mounts the volume mounted to the staging path to the target path
|
||||
@@ -1107,7 +1132,7 @@ func (ns *NodeServer) NodeExpandVolume(ctx context.Context, req *csi.NodeExpandV
|
||||
timeout := 30
|
||||
var actualSize uint64
|
||||
var err error
|
||||
for i := 0; i < timeout && actualSize < requiredBytes; i++
|
||||
for i := 0; i < timeout && actualSize < uint64(requiredBytes); i++
|
||||
{
|
||||
actualSize, err = GetBlockDeviceSize(devicePath)
|
||||
if (err != nil)
|
||||
@@ -1116,9 +1141,9 @@ func (ns *NodeServer) NodeExpandVolume(ctx context.Context, req *csi.NodeExpandV
|
||||
}
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
if (actualSize < requiredBytes)
|
||||
if (actualSize < uint64(requiredBytes))
|
||||
{
|
||||
return nil, status.Error(codes.NotFound, "Failed to wait for online resize of %s to %v bytes: actual size is still %v after %v seconds",
|
||||
return nil, status.Errorf(codes.NotFound, "Failed to wait for online resize of %s to %v bytes: actual size is still %v after %v seconds",
|
||||
devicePath, requiredBytes, actualSize, timeout)
|
||||
}
|
||||
}
|
||||
|
||||
73
csi/src/nodeserver_test.go
Normal file
73
csi/src/nodeserver_test.go
Normal file
@@ -0,0 +1,73 @@
|
||||
// Copyright (c) Vitaliy Filippov, 2019+
|
||||
// License: VNPL-1.1 or GNU GPL-2.0+ (see README.md for details)
|
||||
|
||||
package vitastor
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"k8s.io/utils/mount"
|
||||
)
|
||||
|
||||
func TestCollectActiveNFS(t *testing.T)
|
||||
{
|
||||
mounts := []mount.MountInfo{
|
||||
{
|
||||
Root: "/",
|
||||
Source: "127.0.0.1:/",
|
||||
MountPoint: "/var/lib/kubelet/plugins/csi.vitastor.io/nfs/hash",
|
||||
FsType: "nfs",
|
||||
MountOptions: []string{"rw", "relatime"},
|
||||
SuperOptions: []string{"rw", "vers=3", "port=45059"},
|
||||
},
|
||||
{
|
||||
// This is how NFS subdirectory bind mounts appear on Linux 6.19:
|
||||
// Root is still / and the subdirectory is only visible in Source.
|
||||
Root: "/",
|
||||
Source: "127.0.0.1:/pvc-one",
|
||||
MountPoint: "/var/lib/kubelet/pods/pod-one/volumes/kubernetes.io~csi/pvc-one/mount",
|
||||
FsType: "nfs",
|
||||
MountOptions: []string{"rw", "relatime"},
|
||||
SuperOptions: []string{"rw", "vers=3", "port=45059"},
|
||||
},
|
||||
{
|
||||
Root: "/",
|
||||
Source: "127.0.0.1:/pvc-two",
|
||||
MountPoint: "/var/lib/kubelet/pods/pod-two/volumes/kubernetes.io~csi/pvc-two/mount",
|
||||
FsType: "nfs",
|
||||
MountOptions: []string{"rw", "relatime"},
|
||||
SuperOptions: []string{"rw", "vers=3", "port=45059"},
|
||||
},
|
||||
{
|
||||
// Older kernels expose the bind-mounted subdirectory in Root.
|
||||
Root: "/pvc-three",
|
||||
Source: "127.0.0.1:/",
|
||||
MountPoint: "/var/lib/kubelet/pods/pod-three/volumes/kubernetes.io~csi/pvc-three/mount",
|
||||
FsType: "nfs",
|
||||
MountOptions: []string{"rw", "relatime"},
|
||||
SuperOptions: []string{"rw", "vers=3", "port=45059"},
|
||||
},
|
||||
{
|
||||
Root: "/",
|
||||
Source: "server:/other",
|
||||
MountPoint: "/mnt/other",
|
||||
FsType: "nfs",
|
||||
MountOptions: []string{"rw"},
|
||||
SuperOptions: []string{"rw", "port=2049"},
|
||||
},
|
||||
}
|
||||
|
||||
got := collectActiveNFS(mounts)
|
||||
want := map[int][]string{
|
||||
45059: {
|
||||
"/var/lib/kubelet/pods/pod-one/volumes/kubernetes.io~csi/pvc-one/mount",
|
||||
"/var/lib/kubelet/pods/pod-two/volumes/kubernetes.io~csi/pvc-two/mount",
|
||||
"/var/lib/kubelet/pods/pod-three/volumes/kubernetes.io~csi/pvc-three/mount",
|
||||
},
|
||||
}
|
||||
if (!reflect.DeepEqual(got, want))
|
||||
{
|
||||
t.Fatalf("unexpected active NFS mounts: got %#v, want %#v", got, want)
|
||||
}
|
||||
}
|
||||
2
debian/changelog
vendored
2
debian/changelog
vendored
@@ -1,4 +1,4 @@
|
||||
vitastor (3.1.0-1) unstable; urgency=medium
|
||||
vitastor (3.2.3-1) unstable; urgency=medium
|
||||
|
||||
* Bugfixes
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
VITASTOR_VERSION ?= v3.1.0
|
||||
VITASTOR_VERSION ?= v3.2.3
|
||||
|
||||
all: build push
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# A separate rule: when IMPORT fails, udev drops every other key of its rule, OWNER included
|
||||
SUBSYSTEM=="block", ENV{ID_PART_ENTRY_TYPE}=="e7009fac-a5a1-4d72-af72-53de13059903", \
|
||||
OWNER="vitastor", GROUP="vitastor"
|
||||
SUBSYSTEM=="block", ENV{ID_PART_ENTRY_TYPE}=="e7009fac-a5a1-4d72-af72-53de13059903", \
|
||||
OWNER="vitastor", GROUP="vitastor", \
|
||||
IMPORT{program}="/usr/bin/docker exec vitastor vitastor-disk udev $devnode", \
|
||||
SYMLINK+="vitastor/$env{VITASTOR_ALIAS}"
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
#
|
||||
|
||||
# Desired Vitastor version
|
||||
VITASTOR_VERSION=v3.1.0
|
||||
VITASTOR_VERSION=v3.2.3
|
||||
|
||||
# Additional arguments for all containers
|
||||
# For example, you may want to specify a custom logging driver here
|
||||
|
||||
@@ -24,6 +24,8 @@ These parameters only apply to Monitors.
|
||||
- [osd_out_time](#osd_out_time)
|
||||
- [placement_levels](#placement_levels)
|
||||
- [use_old_pg_combinator](#use_old_pg_combinator)
|
||||
- [sticky_primaries](#sticky_primaries)
|
||||
- [primary_rebalance_time](#primary_rebalance_time)
|
||||
- [osd_backfillfull_ratio](#osd_backfillfull_ratio)
|
||||
|
||||
## use_antietcd
|
||||
@@ -180,6 +182,35 @@ present in the configuration, then it is defined with the default priority
|
||||
Use the old PG combination generator which doesn't support [level_placement](pool.en.md#level_placement)
|
||||
and [raw_placement](pool.en.md#raw_placement) for pools which don't use this features.
|
||||
|
||||
## sticky_primaries
|
||||
|
||||
- Type: boolean
|
||||
- Default: false
|
||||
|
||||
Keep the primary OSD of each PG while it is alive and still one of the PG's
|
||||
primary candidates, and give a PG that needs a new primary (because its
|
||||
primary failed or left the PG) to the candidate which is primary for the
|
||||
fewest PGs of all pools.
|
||||
|
||||
By default primaries are picked by PG number and move back as soon as their
|
||||
OSD returns. Every such move restarts the PG on both OSDs, and picking by PG
|
||||
number may leave some OSDs primary for several times more PGs than others.
|
||||
With this option, primaries are spread more evenly and only move when they
|
||||
have to, or when the cluster is calm: see [primary_rebalance_time](#primary_rebalance_time).
|
||||
|
||||
## primary_rebalance_time
|
||||
|
||||
- Type: seconds
|
||||
- Default: 300
|
||||
|
||||
With [sticky_primaries](#sticky_primaries), the monitor evens out primary
|
||||
OSDs once all PGs have stayed clean and no OSD went up or down for this
|
||||
number of seconds: a live primary moves to another candidate of its PG when
|
||||
it is primary for at least 2 PGs more than that candidate. Each such move
|
||||
restarts the PG on both OSDs, so it is only done in a calm cluster, and one
|
||||
pass gives each OSD at most one new primary: the next pass waits until the
|
||||
cluster is calm again. 0 disables it.
|
||||
|
||||
## osd_backfillfull_ratio
|
||||
|
||||
- Type: number
|
||||
|
||||
@@ -24,6 +24,8 @@
|
||||
- [osd_out_time](#osd_out_time)
|
||||
- [placement_levels](#placement_levels)
|
||||
- [use_old_pg_combinator](#use_old_pg_combinator)
|
||||
- [sticky_primaries](#sticky_primaries)
|
||||
- [primary_rebalance_time](#primary_rebalance_time)
|
||||
- [osd_backfillfull_ratio](#osd_backfillfull_ratio)
|
||||
|
||||
## use_antietcd
|
||||
@@ -183,6 +185,37 @@ OSD перед обновлением агрегированной статис
|
||||
Использовать старый генератор комбинаций PG, не поддерживающий [level_placement](pool.ru.md#level_placement)
|
||||
и [raw_placement](pool.ru.md#raw_placement) для пулов, которые не используют данные функции.
|
||||
|
||||
## sticky_primaries
|
||||
|
||||
- Тип: булево (да/нет)
|
||||
- Значение по умолчанию: false
|
||||
|
||||
Сохранять первичный OSD каждой PG, пока он жив и остаётся одним из
|
||||
кандидатов в первичные OSD этой PG, а PG, которой нужен новый первичный OSD
|
||||
(потому что прежний отказал или вышел из PG), отдавать тому кандидату, который
|
||||
является первичным для наименьшего числа PG всех пулов.
|
||||
|
||||
По умолчанию первичные OSD выбираются по номеру PG и возвращаются обратно, как
|
||||
только их OSD снова включается. Каждый такой перенос перезапускает PG на обоих
|
||||
OSD, а выбор по номеру PG может сделать часть OSD первичными для в несколько
|
||||
раз большего числа PG, чем другие. С этой опцией первичные OSD распределяются
|
||||
равномернее и переносятся только тогда, когда это необходимо, или когда в
|
||||
кластере всё спокойно: см. [primary_rebalance_time](#primary_rebalance_time).
|
||||
|
||||
## primary_rebalance_time
|
||||
|
||||
- Тип: секунды
|
||||
- Значение по умолчанию: 300
|
||||
|
||||
При включённой [sticky_primaries](#sticky_primaries) монитор выравнивает
|
||||
первичные OSD, когда все PG остаются чистыми и ни один OSD не включался и не
|
||||
отключался в течение этого числа секунд: живой первичный OSD переносится на
|
||||
другого кандидата своей PG, если он первичный хотя бы на 2 PG больше, чем этот
|
||||
кандидат. Каждый такой перенос перезапускает PG на обоих OSD, поэтому он
|
||||
делается только в спокойном кластере, и за один проход каждый OSD получает
|
||||
не больше одной новой первичной PG: следующий проход ждёт, пока кластер снова
|
||||
успокоится. 0 отключает выравнивание.
|
||||
|
||||
## osd_backfillfull_ratio
|
||||
|
||||
- Тип: число
|
||||
|
||||
@@ -17,6 +17,9 @@ between clients, OSDs and etcd.
|
||||
- [rdma_device](#rdma_device)
|
||||
- [rdma_port_num](#rdma_port_num)
|
||||
- [rdma_gid_index](#rdma_gid_index)
|
||||
- [rdma_traffic_class](#rdma_traffic_class)
|
||||
- [rdma_sl](#rdma_sl)
|
||||
- [rdma_set_flow_label](#rdma_set_flow_label)
|
||||
- [rdma_mtu](#rdma_mtu)
|
||||
- [rdma_max_sge](#rdma_max_sge)
|
||||
- [rdma_max_msg](#rdma_max_msg)
|
||||
@@ -33,6 +36,7 @@ between clients, OSDs and etcd.
|
||||
- [etcd_ws_keepalive_interval](#etcd_ws_keepalive_interval)
|
||||
- [etcd_min_reload_interval](#etcd_min_reload_interval)
|
||||
- [tcp_header_buffer_size](#tcp_header_buffer_size)
|
||||
- [rxbounce](#rxbounce)
|
||||
- [min_zerocopy_send_size](#min_zerocopy_send_size)
|
||||
- [use_sync_send_recv](#use_sync_send_recv)
|
||||
|
||||
@@ -154,6 +158,40 @@ A correct rdma_gid_index for RoCEv2 is usually 1 (IPv6) or 3 (IPv4).
|
||||
|
||||
Not relevant for RDMA-CM (use_rdmacm).
|
||||
|
||||
## rdma_traffic_class
|
||||
|
||||
- Type: integer
|
||||
- Default: 0
|
||||
|
||||
Full TOS byte for RDMA traffic in the IP header (RoCEv2): DSCP in the
|
||||
higher 6 bits and ECN in the lower 2 bits. For example, 106 (0x6A) =
|
||||
DSCP 26 + ECT(0). Works with both libibverbs and RDMA-CM modes and should
|
||||
be set on both OSDs and clients to mark traffic in both directions.
|
||||
Default 0 = don't mark.
|
||||
|
||||
## rdma_sl
|
||||
|
||||
- Type: integer
|
||||
- Default: 0
|
||||
|
||||
Service Level (802.1p priority analogue) for RDMA traffic, put into the
|
||||
address vector of every connection. Only applies to the libibverbs mode:
|
||||
in RDMA-CM mode the service level is derived from rdma_traffic_class.
|
||||
Default 0 = as is without PFC-configured networks.
|
||||
|
||||
## rdma_set_flow_label
|
||||
|
||||
- Type: boolean
|
||||
- Default: false
|
||||
|
||||
Automatically derive an IPv6 Flow Label for RDMA connections from the
|
||||
queue pair number pair, so that every connection gets its own label and
|
||||
connections spread over ECMP links while each connection keeps a single
|
||||
stable path. Only applied to IPv6 GIDs: an IPv4-mapped GID
|
||||
(::ffff:a.b.c.d) produces IPv4 packets which have no flow label. Only
|
||||
applies to the libibverbs mode; RDMA-CM generates flow labels on its own.
|
||||
Default false = don't set.
|
||||
|
||||
## rdma_mtu
|
||||
|
||||
- Type: integer
|
||||
@@ -303,6 +341,21 @@ is received without an additional copy. You can try to play with this
|
||||
parameter and see how it affects random iops and linear bandwidth if you
|
||||
want.
|
||||
|
||||
## rxbounce
|
||||
|
||||
- Type: boolean
|
||||
- Default: false
|
||||
- Can be changed online: yes
|
||||
|
||||
Receive all TCP data into an intermediate buffer before copying to the actual
|
||||
destination. Enabling this option is required for Windows guests if you use TCP
|
||||
and [security.en.md#proto_checksums](proto_checksums) because Windows uses a
|
||||
shared system-wide 'dummy page' to skip unneeded blocks during reads and breaks
|
||||
checksum verification with it when data copy is avoided. rxbounce is only needed
|
||||
when you use TCP and don't use transport encryption (AES-GCM); it's not required
|
||||
with RDMA or with GCM encryption because both always copy data anyway (yes, RDMA
|
||||
isn't actually zerocopy in Vitastor).
|
||||
|
||||
## min_zerocopy_send_size
|
||||
|
||||
- Type: integer
|
||||
|
||||
@@ -17,6 +17,9 @@
|
||||
- [rdma_device](#rdma_device)
|
||||
- [rdma_port_num](#rdma_port_num)
|
||||
- [rdma_gid_index](#rdma_gid_index)
|
||||
- [rdma_traffic_class](#rdma_traffic_class)
|
||||
- [rdma_sl](#rdma_sl)
|
||||
- [rdma_set_flow_label](#rdma_set_flow_label)
|
||||
- [rdma_mtu](#rdma_mtu)
|
||||
- [rdma_max_sge](#rdma_max_sge)
|
||||
- [rdma_max_msg](#rdma_max_msg)
|
||||
@@ -33,6 +36,7 @@
|
||||
- [etcd_ws_keepalive_interval](#etcd_ws_keepalive_interval)
|
||||
- [etcd_min_reload_interval](#etcd_min_reload_interval)
|
||||
- [tcp_header_buffer_size](#tcp_header_buffer_size)
|
||||
- [rxbounce](#rxbounce)
|
||||
- [min_zerocopy_send_size](#min_zerocopy_send_size)
|
||||
- [use_sync_send_recv](#use_sync_send_recv)
|
||||
|
||||
@@ -157,6 +161,40 @@ libibverbs < v32.
|
||||
|
||||
Опция неприменима к RDMA-CM (use_rdmacm).
|
||||
|
||||
## rdma_traffic_class
|
||||
|
||||
- Тип: целое число
|
||||
- Значение по умолчанию: 0
|
||||
|
||||
Полный байт TOS для RDMA-трафика в заголовке IP (RoCEv2): DSCP в старших
|
||||
6 битах и ECN в младших 2. Например, 106 (0x6A) = DSCP 26 + ECT(0).
|
||||
Работает в обоих режимах RDMA - и libibverbs, и RDMA-CM; должен быть задан
|
||||
и на OSD, и на клиентах, чтобы трафик помечался в обе стороны. По умолчанию
|
||||
0 - не помечать.
|
||||
|
||||
## rdma_sl
|
||||
|
||||
- Тип: целое число
|
||||
- Значение по умолчанию: 0
|
||||
|
||||
Service Level (аналог приоритета 802.1p) для RDMA-трафика; попадает в
|
||||
адресный вектор каждого соединения. Применим только к libibverbs-режиму:
|
||||
в RDMA-CM уровень обслуживания выводится из rdma_traffic_class.
|
||||
По умолчанию 0 = как в сетях без PFC.
|
||||
|
||||
## rdma_set_flow_label
|
||||
|
||||
- Тип: булево (да/нет)
|
||||
- Значение по умолчанию: false
|
||||
|
||||
Автоматически выводить IPv6 Flow Label для RDMA-соединений из пары
|
||||
номеров очередей (QPN), чтобы каждое соединение получало свою метку,
|
||||
соединения распределялись по ECMP-каналам, но каждое соединение шло по
|
||||
одному стабильному пути. Применяется только к IPv6-GID: IPv4-mapped GID
|
||||
(::ffff:a.b.c.d) даёт IPv4-пакеты, где поля flow label нет. Применим
|
||||
только к libibverbs-режиму - RDMA-CM всегда генерирует flow label сам.
|
||||
По умолчанию false = не задавать.
|
||||
|
||||
## rdma_mtu
|
||||
|
||||
- Тип: целое число
|
||||
@@ -310,6 +348,22 @@ Vitastor содержат 128-байтные заголовки, за котор
|
||||
поменять этот параметр и посмотреть, как он влияет на производительность
|
||||
случайного и линейного доступа.
|
||||
|
||||
## rxbounce
|
||||
|
||||
- Тип: булево (да/нет)
|
||||
- Значение по умолчанию: false
|
||||
- Можно менять на лету: да
|
||||
|
||||
Принимать все данные по TCP в промежуточный буфер и потом копировать их в
|
||||
буфер клиента (ВМ). Это нужно для гостевых ОС Windows с TCP и включёнными
|
||||
[security.ru.md#proto_checksums](proto_checksums), потому что Windows использует
|
||||
одну разделяемую общесистемную страницу-заглушку для пропуска ненужных блоков
|
||||
при чтении и ломает проверку контрольных сумм, если данные не копируются лишний
|
||||
раз. Опция rxbounce нужна только если вы используете TCP и не используете
|
||||
транспортное шифрование (AES-GCM); с RDMA или шифрованием опция не нужна, так
|
||||
как в этом случае данные копируются всегда (да, RDMA в Vitastor на самом деле
|
||||
не zero-copy).
|
||||
|
||||
## min_zerocopy_send_size
|
||||
|
||||
- Тип: целое число
|
||||
|
||||
@@ -13,6 +13,7 @@ const L = {
|
||||
toc_installation: 'Installation',
|
||||
toc_config: '[Configuration](../config.en.md)',
|
||||
toc_usage: 'Usage',
|
||||
toc_tests: 'Tests',
|
||||
toc_performance: 'Performance',
|
||||
online: 'Can be changed online: yes',
|
||||
},
|
||||
@@ -28,6 +29,7 @@ const L = {
|
||||
toc_installation: 'Установка',
|
||||
toc_config: '[Конфигурация](../config.ru.md)',
|
||||
toc_usage: 'Использование',
|
||||
toc_tests: 'Тесты',
|
||||
toc_performance: 'Производительность',
|
||||
online: 'Можно менять на лету: да',
|
||||
},
|
||||
|
||||
@@ -178,6 +178,52 @@
|
||||
info_ru: |
|
||||
Использовать старый генератор комбинаций PG, не поддерживающий [level_placement](pool.ru.md#level_placement)
|
||||
и [raw_placement](pool.ru.md#raw_placement) для пулов, которые не используют данные функции.
|
||||
- name: sticky_primaries
|
||||
type: bool
|
||||
default: false
|
||||
info: |
|
||||
Keep the primary OSD of each PG while it is alive and still one of the PG's
|
||||
primary candidates, and give a PG that needs a new primary (because its
|
||||
primary failed or left the PG) to the candidate which is primary for the
|
||||
fewest PGs of all pools.
|
||||
|
||||
By default primaries are picked by PG number and move back as soon as their
|
||||
OSD returns. Every such move restarts the PG on both OSDs, and picking by PG
|
||||
number may leave some OSDs primary for several times more PGs than others.
|
||||
With this option, primaries are spread more evenly and only move when they
|
||||
have to, or when the cluster is calm: see [primary_rebalance_time](#primary_rebalance_time).
|
||||
info_ru: |
|
||||
Сохранять первичный OSD каждой PG, пока он жив и остаётся одним из
|
||||
кандидатов в первичные OSD этой PG, а PG, которой нужен новый первичный OSD
|
||||
(потому что прежний отказал или вышел из PG), отдавать тому кандидату, который
|
||||
является первичным для наименьшего числа PG всех пулов.
|
||||
|
||||
По умолчанию первичные OSD выбираются по номеру PG и возвращаются обратно, как
|
||||
только их OSD снова включается. Каждый такой перенос перезапускает PG на обоих
|
||||
OSD, а выбор по номеру PG может сделать часть OSD первичными для в несколько
|
||||
раз большего числа PG, чем другие. С этой опцией первичные OSD распределяются
|
||||
равномернее и переносятся только тогда, когда это необходимо, или когда в
|
||||
кластере всё спокойно: см. [primary_rebalance_time](#primary_rebalance_time).
|
||||
- name: primary_rebalance_time
|
||||
type: sec
|
||||
default: 300
|
||||
info: |
|
||||
With [sticky_primaries](#sticky_primaries), the monitor evens out primary
|
||||
OSDs once all PGs have stayed clean and no OSD went up or down for this
|
||||
number of seconds: a live primary moves to another candidate of its PG when
|
||||
it is primary for at least 2 PGs more than that candidate. Each such move
|
||||
restarts the PG on both OSDs, so it is only done in a calm cluster, and one
|
||||
pass gives each OSD at most one new primary: the next pass waits until the
|
||||
cluster is calm again. 0 disables it.
|
||||
info_ru: |
|
||||
При включённой [sticky_primaries](#sticky_primaries) монитор выравнивает
|
||||
первичные OSD, когда все PG остаются чистыми и ни один OSD не включался и не
|
||||
отключался в течение этого числа секунд: живой первичный OSD переносится на
|
||||
другого кандидата своей PG, если он первичный хотя бы на 2 PG больше, чем этот
|
||||
кандидат. Каждый такой перенос перезапускает PG на обоих OSD, поэтому он
|
||||
делается только в спокойном кластере, и за один проход каждый OSD получает
|
||||
не больше одной новой первичной PG: следующий проход ждёт, пока кластер снова
|
||||
успокоится. 0 отключает выравнивание.
|
||||
- name: osd_backfillfull_ratio
|
||||
type: float
|
||||
default: 0.99
|
||||
|
||||
@@ -188,6 +188,53 @@
|
||||
Правильный rdma_gid_index для RoCEv2, как правило, 1 (IPv6) или 3 (IPv4).
|
||||
|
||||
Опция неприменима к RDMA-CM (use_rdmacm).
|
||||
- name: rdma_traffic_class
|
||||
type: int
|
||||
default: 0
|
||||
info: |
|
||||
Full TOS byte for RDMA traffic in the IP header (RoCEv2): DSCP in the
|
||||
higher 6 bits and ECN in the lower 2 bits. For example, 106 (0x6A) =
|
||||
DSCP 26 + ECT(0). Works with both libibverbs and RDMA-CM modes and should
|
||||
be set on both OSDs and clients to mark traffic in both directions.
|
||||
Default 0 = don't mark.
|
||||
info_ru: |
|
||||
Полный байт TOS для RDMA-трафика в заголовке IP (RoCEv2): DSCP в старших
|
||||
6 битах и ECN в младших 2. Например, 106 (0x6A) = DSCP 26 + ECT(0).
|
||||
Работает в обоих режимах RDMA - и libibverbs, и RDMA-CM; должен быть задан
|
||||
и на OSD, и на клиентах, чтобы трафик помечался в обе стороны. По умолчанию
|
||||
0 - не помечать.
|
||||
- name: rdma_sl
|
||||
type: int
|
||||
default: 0
|
||||
info: |
|
||||
Service Level (802.1p priority analogue) for RDMA traffic, put into the
|
||||
address vector of every connection. Only applies to the libibverbs mode:
|
||||
in RDMA-CM mode the service level is derived from rdma_traffic_class.
|
||||
Default 0 = as is without PFC-configured networks.
|
||||
info_ru: |
|
||||
Service Level (аналог приоритета 802.1p) для RDMA-трафика; попадает в
|
||||
адресный вектор каждого соединения. Применим только к libibverbs-режиму:
|
||||
в RDMA-CM уровень обслуживания выводится из rdma_traffic_class.
|
||||
По умолчанию 0 = как в сетях без PFC.
|
||||
- name: rdma_set_flow_label
|
||||
type: bool
|
||||
default: false
|
||||
info: |
|
||||
Automatically derive an IPv6 Flow Label for RDMA connections from the
|
||||
queue pair number pair, so that every connection gets its own label and
|
||||
connections spread over ECMP links while each connection keeps a single
|
||||
stable path. Only applied to IPv6 GIDs: an IPv4-mapped GID
|
||||
(::ffff:a.b.c.d) produces IPv4 packets which have no flow label. Only
|
||||
applies to the libibverbs mode; RDMA-CM generates flow labels on its own.
|
||||
Default false = don't set.
|
||||
info_ru: |
|
||||
Автоматически выводить IPv6 Flow Label для RDMA-соединений из пары
|
||||
номеров очередей (QPN), чтобы каждое соединение получало свою метку,
|
||||
соединения распределялись по ECMP-каналам, но каждое соединение шло по
|
||||
одному стабильному пути. Применяется только к IPv6-GID: IPv4-mapped GID
|
||||
(::ffff:a.b.c.d) даёт IPv4-пакеты, где поля flow label нет. Применим
|
||||
только к libibverbs-режиму - RDMA-CM всегда генерирует flow label сам.
|
||||
По умолчанию false = не задавать.
|
||||
- name: rdma_mtu
|
||||
type: int
|
||||
info: |
|
||||
@@ -358,6 +405,29 @@
|
||||
параметра читается без дополнительного копирования. Вы можете попробовать
|
||||
поменять этот параметр и посмотреть, как он влияет на производительность
|
||||
случайного и линейного доступа.
|
||||
- name: rxbounce
|
||||
type: bool
|
||||
default: false
|
||||
online: true
|
||||
info: |
|
||||
Receive all TCP data into an intermediate buffer before copying to the actual
|
||||
destination. Enabling this option is required for Windows guests if you use TCP
|
||||
and [security.en.md#proto_checksums](proto_checksums) because Windows uses a
|
||||
shared system-wide 'dummy page' to skip unneeded blocks during reads and breaks
|
||||
checksum verification with it when data copy is avoided. rxbounce is only needed
|
||||
when you use TCP and don't use transport encryption (AES-GCM); it's not required
|
||||
with RDMA or with GCM encryption because both always copy data anyway (yes, RDMA
|
||||
isn't actually zerocopy in Vitastor).
|
||||
info_ru: |
|
||||
Принимать все данные по TCP в промежуточный буфер и потом копировать их в
|
||||
буфер клиента (ВМ). Это нужно для гостевых ОС Windows с TCP и включёнными
|
||||
[security.ru.md#proto_checksums](proto_checksums), потому что Windows использует
|
||||
одну разделяемую общесистемную страницу-заглушку для пропуска ненужных блоков
|
||||
при чтении и ломает проверку контрольных сумм, если данные не копируются лишний
|
||||
раз. Опция rxbounce нужна только если вы используете TCP и не используете
|
||||
транспортное шифрование (AES-GCM); с RDMA или шифрованием опция не нужна, так
|
||||
как в этом случае данные копируются всегда (да, RDMA в Vitastor на самом деле
|
||||
не zero-copy).
|
||||
- name: min_zerocopy_send_size
|
||||
type: int
|
||||
default: 32768
|
||||
|
||||
@@ -26,9 +26,9 @@ at Vitastor Kubernetes operator: https://github.com/Antilles7227/vitastor-operat
|
||||
The instruction is very simple.
|
||||
|
||||
1. Download a Docker image of the desired version: \
|
||||
`docker pull vitalif/vitastor:v3.1.0`
|
||||
`docker pull vitalif/vitastor:v3.2.3`
|
||||
2. Install scripts to the host system: \
|
||||
`docker run --rm -it -v /etc:/host-etc -v /usr/bin:/host-bin vitalif/vitastor:v3.1.0 install.sh`
|
||||
`docker run --rm -it -v /etc:/host-etc -v /usr/bin:/host-bin vitalif/vitastor:v3.2.3 install.sh`
|
||||
3. Reload udev rules: \
|
||||
`udevadm control --reload-rules`
|
||||
4. Enable the vitastor-host service: \
|
||||
|
||||
@@ -25,9 +25,9 @@ Vitastor можно установить в Docker/Podman. При этом etcd,
|
||||
Инструкция по установке максимально простая.
|
||||
|
||||
1. Скачайте Docker-образ желаемой версии: \
|
||||
`docker pull vitalif/vitastor:v3.1.0`
|
||||
`docker pull vitalif/vitastor:v3.2.3`
|
||||
2. Установите скрипты в хост-систему командой: \
|
||||
`docker run --rm -it -v /etc:/host-etc -v /usr/bin:/host-bin vitalif/vitastor:v3.1.0 install.sh`
|
||||
`docker run --rm -it -v /etc:/host-etc -v /usr/bin:/host-bin vitalif/vitastor:v3.2.3 install.sh`
|
||||
3. Перезагрузите правила udev: \
|
||||
`udevadm control --reload-rules`
|
||||
4. Включите сервис vitastor-host: \
|
||||
|
||||
@@ -220,11 +220,3 @@ All other client-side components are based on the client library:
|
||||
- I like node.js better than any other dynamically-typed language interpreter
|
||||
because it's faster than any other interpreter in the world, has neutral C-like
|
||||
syntax and built-in event loop. That's why Monitor is implemented in node.js.
|
||||
|
||||
## Known Problems
|
||||
|
||||
- Deleting images in a degraded cluster may currently lead to objects reappearing
|
||||
after dead OSDs come back, and in case of erasure-coded pools, they may even
|
||||
reappear as incomplete. Just repeat the removal request again in this case.
|
||||
This problem will be fixed in the future, along with the metadata disk storage
|
||||
format update.
|
||||
|
||||
@@ -228,11 +228,3 @@
|
||||
- Из всех интерпретаторов скриптоты больше всех я люблю node.js, это самый быстрый в мире
|
||||
интерпретатор, у него есть встроенная событийная машина, развитая инфраструктура и
|
||||
приятный нейтральный C-подобный язык программирования. Поэтому Монитор реализован на node.js.
|
||||
|
||||
## Известные проблемы
|
||||
|
||||
- Удаление образов в деградированном кластере может в данный момент приводить к повторному
|
||||
"появлению" удалённых объектов после поднятия отключённых OSD, причём в случае EC-пулов,
|
||||
объекты могут появиться в виде "неполных". Если вы столкнётесь с такой ситуацией, просто
|
||||
повторите запрос удаления. Данная проблема будет исправлена в будущем вместе с обновлением
|
||||
дискового формата хранения метаданных.
|
||||
|
||||
229
docs/tests/blockstore-chaos.en.md
Normal file
229
docs/tests/blockstore-chaos.en.md
Normal file
@@ -0,0 +1,229 @@
|
||||
[Documentation](../../README.md#documentation) → Tests → The blockstore chaos-test model
|
||||
|
||||
-----
|
||||
|
||||
[Читать на русском](blockstore-chaos.ru.md)
|
||||
|
||||
# The blockstore chaos-test model
|
||||
|
||||
A seed-driven crash test of the blockstore (`src/test/test_blockstore_chaos.cpp`):
|
||||
the real blockstore - journal, metadata, flusher, compaction, checksums, recovery -
|
||||
running on a mock disk that lives entirely in RAM. Nothing above it exists: no OSD,
|
||||
no PG, no network, no etcd. The test talks to the blockstore directly and checks
|
||||
only what the storage itself promises. It is the counterpart of the
|
||||
[PG chaos test](pg-chaos.en.md), which assumes the storage is correct.
|
||||
|
||||
Everything BELOW the blockstore is simulated: io_uring completions come back out of
|
||||
submission order after a random delay, a volatile write cache holds part of every
|
||||
write, and a power outage makes the writes that were in flight land fully, torn at a
|
||||
sector boundary, or not at all, while a random half of the cache disappears. The
|
||||
model of what was written is kept alongside, and after every outage the recovered
|
||||
state is checked against it.
|
||||
|
||||
The same workload and the same checks run against both implementations - v1
|
||||
(meta_format 2) and v2 (heap, meta_format 3) - which are supposed to have identical
|
||||
semantics. The seed also picks the configuration, so a failing run is replayed by
|
||||
passing back the seed it printed; `-h` lists the options.
|
||||
|
||||
The data is four 128 K objects (inode 1, four stripes) on one 256 MB mock disk that
|
||||
carries metadata at offset 0, the journal from 16 M and the data from 32 M; write
|
||||
granularity is 4 K.
|
||||
|
||||
## Configurations (24)
|
||||
|
||||
- v1 / v2 blockstore (meta_format 2 / 3) ×
|
||||
- immediate_commit none/all ×
|
||||
- `csum_block` none / 4096 / 16384 - 16384 is deliberately larger than the 4 K write
|
||||
granularity, so a write covers only part of a checksummed block ×
|
||||
- instant/two-phase writes, like in replicated/EC pools (BS_OP_WRITE_STABLE / BS_OP_WRITE+BS_OP_STABLE)
|
||||
|
||||
2 × 2 × 3 × 2 = 24; the configuration is `seed % 24`, `--config` overrides it. The
|
||||
two write styles can't be mixed inside one object: a stable version over an unstable
|
||||
one is rejected with EINVAL, and a pool is always one or the other.
|
||||
|
||||
## The world model
|
||||
|
||||
Per object the model keeps `submitted` (the highest sequence ever enqueued), `acked`,
|
||||
`synced` and `durable`, plus maps from the sequence number to the full 128 K content
|
||||
(an empty vector means "deleted"), to the version the store actually sees, and to
|
||||
the bitmap byte. Sequence numbers only ever grow and key the model, because version
|
||||
numbers restart from 1 after a deletion - the store explicitly allows writing low
|
||||
versions over a delete. `deleted_upto` stops an old sync snapshot from making a
|
||||
wiped-out version stabilizable, and `can_rollback` records that this instance really
|
||||
did stabilize the durable version (recovery may have merged it into one clean entry).
|
||||
|
||||
Durability is derived purely from completions - there are no extra flags:
|
||||
|
||||
- with `immediate_commit=all` a completed write is immediately synced; with a
|
||||
volatile disk cache nothing is synced until a SYNC that covers it completes;
|
||||
- a synced deletion and a synced `BS_OP_WRITE_STABLE` write are stable by themselves
|
||||
and so are durable at once; a two-phase write still has to be stabilized, and that
|
||||
happens asynchronously, from a later step.
|
||||
|
||||
Object contents are self-identifying: 32-byte records `{seq, version, object,
|
||||
offset}` whose size divides the 4 K granularity, so a record never straddles a write
|
||||
or a read, and any mismatch decodes into "which write put these bytes here".
|
||||
|
||||
External bitmaps are self-identifying too: every write fills its 4-byte bitmap (one
|
||||
bit per 4 K granule) with one recognisable byte. The blockstore treats the bitmap as
|
||||
opaque, but it travels with the entry through compaction, recovery and rollbacks
|
||||
just like the data does.
|
||||
|
||||
Invariant: only one operation at a time may touch an object. While its write, read,
|
||||
stabilize or rollback is in flight nothing else may go near it, so the base content
|
||||
of a write and the expected answer of a read cannot change underneath them.
|
||||
|
||||
## The simulated reality
|
||||
|
||||
- **Event loop**: one step is the completion of the earliest in-flight disk request,
|
||||
and the virtual clock jumps straight to it, so the configured latencies don't make
|
||||
the test slow. A single seeded PRNG drives the latencies, the workload and the
|
||||
power-outage dice alike.
|
||||
- **Disk simulator**: per-request delays are drawn uniformly (10-200 us for reads
|
||||
and writes, 100-2000 us for fsync) - that is what makes completions arrive out of
|
||||
order; 4 K sector; writes up to 4 K are atomic and land whole or not at
|
||||
all. In buffered mode (`immediate_commit=none`) writes go into a volatile cache
|
||||
and only reach the media on fsync. On `power_loss()` every in-flight write
|
||||
lands fully, torn at a sector boundary, or not at all, and every cached write
|
||||
survives with probability 50% - the survivors are committed to the disk and the
|
||||
cache is emptied, so nothing from it disappears at the next outage. Error injection
|
||||
for read/write/fsync exists but is off by default: the blockstore treats most write
|
||||
errors as fatal, by design.
|
||||
- **Ringloop stub**: an unknown fd aborts the test at once; `reset()` drops queued
|
||||
and pending completions as if the process had died, so no stale callback can fire
|
||||
into a destroyed blockstore. A power outage empties the disk's in-flight queue by
|
||||
definition, and a clean restart waits for it to go idle explicitly.
|
||||
|
||||
## Operations (one per step)
|
||||
|
||||
Each step picks an action by weight (`--p-*`; 0 disables it):
|
||||
|
||||
- **wait (500)** - submit nothing, just let the simulation run one event.
|
||||
- **write (60)** - write a random 4 K-aligned range of a random free object: a new
|
||||
version (numbering restarts after a deletion), self-describing payload, its own
|
||||
bitmap byte.
|
||||
- **delete (6)** - delete an existing object; deleting a missing one is a no-op the
|
||||
store answers without creating an entry, so it isn't exercised. A deletion is
|
||||
stable by itself.
|
||||
- **read (40)** - read a random 4 K-aligned range - deliberately NOT aligned to the
|
||||
checksum block, so reads cut across checksum blocks and across the boundaries of
|
||||
the extents that were actually written - or the whole object with `full_read`%
|
||||
(25) chance; the answer is verified against the model when it completes.
|
||||
- **sync (30)** - flush; what it covers is the set of acknowledged versions as of
|
||||
submit time, treated as a lower bound. Not submitted while a rollback is in
|
||||
flight: a rollback rewinds the test model - `acked` and `synced` drop back to the
|
||||
stable version, everything above it disappears from it - so the snapshot would
|
||||
name versions that no longer exist. This is a limit of the test model, not of the
|
||||
blockstore API.
|
||||
- **stabilize (50)** - commit a random non-empty prefix of everything that has
|
||||
become stabilizable, as a single op carrying several (object, version) entries -
|
||||
the shape an OSD uses; single-entry ops happen just as naturally.
|
||||
- **rollback (6)** - throw the unstable versions away instead of committing them.
|
||||
Two-phase mode only (an instant write is stable at once), and only for objects
|
||||
that have a stable non-deleted version below the newest one. On success everything
|
||||
above the stable version is gone and the store's version counter for the object
|
||||
goes back to it. Not submitted while a sync is in flight, for the same reason,
|
||||
nor while another rollback is in flight.
|
||||
- **restart (1)** - a CLEAN restart: drain everything in flight, read all objects,
|
||||
wait for the disk to go idle, destroy the blockstore, create it again, read
|
||||
everything again.
|
||||
- **crash (2)** - pull the plug right now: power loss, whatever was in flight is
|
||||
accounted as a legal-but-unconfirmed outcome, the blockstore is destroyed and
|
||||
recreated, every object is checked against the recovery rule.
|
||||
|
||||
At most `max_inflight` (8) operations are in flight at once; a step that finds the
|
||||
queue full waits for one completion instead of submitting anything - that is where
|
||||
hangs are checked.
|
||||
|
||||
At the end of the run everything still in flight is drained, and every object is
|
||||
read whole and verified.
|
||||
|
||||
## Op outcome accounting
|
||||
|
||||
- Completed with the expected retval - the content is recorded at its sequence
|
||||
number, `acked` moves to it, and the follow-up (synced / durable / needs-stabilize)
|
||||
is derived from the configuration.
|
||||
- A write or delete with `-EAGAIN` - a refusal, not a loss (the journal is full and
|
||||
the flusher can't keep up under pressure); the model is unchanged.
|
||||
- A failed sync - it simply didn't sync anything; also legal under pressure.
|
||||
- A read interrupted by an outage tells nothing and is dropped.
|
||||
- Anything else - including a failed stabilize or rollback - aborts the test with
|
||||
the affected (object, version) entries printed.
|
||||
- A write that was in flight at the moment of the outage: its content is recorded as
|
||||
a legal outcome all the same, but `acked` doesn't move, so it may still be lost.
|
||||
|
||||
## Checks (every abort point)
|
||||
|
||||
**Data consistency:**
|
||||
|
||||
1. a read of a deleted or never-written object returns `-ENOENT`;
|
||||
2. a read returns exactly the acknowledged content: `retval == len` and byte-for-byte
|
||||
equality over the whole range; the first differing record is printed with both
|
||||
obj/seq/version/offset values, so stale data names its own author;
|
||||
3. the returned external bitmap must belong to the returned version ("returned the
|
||||
bitmap of another version");
|
||||
4. after a crash or a restart a read answers either the whole object or `-ENOENT` -
|
||||
any other retval means torn data was committed;
|
||||
5. whatever came back must be the content of a version at or above the guaranteed
|
||||
floor: the last durable version after a power outage, the last acknowledged one
|
||||
(the last synced one with a volatile cache) after a restart that lost nothing.
|
||||
Anything else aborts the test with "came back ... holding unexpected content"
|
||||
plus a diff against every candidate version - the one that almost matches usually
|
||||
tells which write was lost or applied out of order;
|
||||
6. the object may legitimately be gone only when nothing was guaranteed at all; then
|
||||
the model resets and numbering starts over from 1;
|
||||
7. with `immediate_commit=all` a clean restart must return exactly the same state -
|
||||
same retval, same version, same bytes; the failure also prints the first
|
||||
never-written journal sector, which points straight at the lost record;
|
||||
8. what came back becomes the new baseline but not the new durable point: the
|
||||
durable content stays a legal outcome, `can_rollback` is cleared, and the next
|
||||
outage may still roll the object back to the durable version;
|
||||
9. a rollback may only remove versions above the stable one, and the version counter
|
||||
is rewound accordingly - later writes and reads would notice otherwise;
|
||||
10. the final whole-object reads must match the acknowledged content.
|
||||
|
||||
**Liveness:**
|
||||
|
||||
11. "operations did not complete in 1000000 steps - deadlock?" - the stuck
|
||||
operations are printed together with the store's diagnostics
|
||||
(completed/fsynced/compacted LSNs, compact queue) in the v2 implementation;
|
||||
12. "blockstore failed to start";
|
||||
13. "a read of object N did not complete in MAX_STEPS - deadlock?" and "the final
|
||||
read of object N did not complete";
|
||||
14. "disk did not go idle before a clean restart" - a use-after-free guard: no
|
||||
request may outlive the blockstore that submitted it.
|
||||
|
||||
**Failure accounting:**
|
||||
|
||||
15. only `-EAGAIN` is accepted as a refusal for a write/delete, a failed sync is
|
||||
treated as "synced nothing", and any other error, including a failed stabilize
|
||||
or rollback, aborts the test.
|
||||
|
||||
**Test-stub guards:**
|
||||
|
||||
16. an unexpected fd on the ringloop stub, a rejected SQE, `--max-inflight < 1`;
|
||||
17. overlapping concurrent writes: a write submitted while another in-flight write
|
||||
still covers part of its range aborts the test - a device may apply such a pair
|
||||
in either order, so relying on the newer one winning is a bug, and catching it
|
||||
at submission time is deterministic instead of waiting for an unlucky completion
|
||||
order.
|
||||
|
||||
## Reporting and reproducibility
|
||||
|
||||
By default the test runs 48 fixed seeds (every configuration twice) plus 152 random
|
||||
ones spread evenly over the configurations - 200 seeds × 10000 steps in total. Every
|
||||
seed runs in its own child process, so one abort doesn't take the whole sweep down,
|
||||
and the failing seeds are listed at the end. `--seed N` runs a single seed
|
||||
in-process, which is what you want under a debugger; `--seeds a-b`, `--random n`,
|
||||
`--steps n`, `--config n` and the `--p-*` weights shape the run (e.g.
|
||||
`--p-delete 0 --p-rollback 0` gives a workload without deletions and rollbacks).
|
||||
|
||||
The OK line: writes (refused with EAGAIN) / deletes / syncs / stabilizes / rollbacks
|
||||
/ crashes / clean restarts / verified reads / disk ops.
|
||||
|
||||
Determinism: one seed -> the same configuration and the same schedule; `-v` traces
|
||||
every operation and every simulated disk request, including its simulated latency,
|
||||
the power-loss decision taken for every in-flight write and every cached write
|
||||
dropped from the volatile cache.
|
||||
|
||||
Built by `make build_tests` and run by ctest as `test_blockstore_chaos`.
|
||||
211
docs/tests/blockstore-chaos.ru.md
Normal file
211
docs/tests/blockstore-chaos.ru.md
Normal file
@@ -0,0 +1,211 @@
|
||||
[Документация](../../README-ru.md#документация) → Тесты → Модель хаос-теста blockstore (`src/test/test_blockstore_chaos.cpp`)
|
||||
|
||||
-----
|
||||
|
||||
[Read in English](blockstore-chaos.en.md)
|
||||
|
||||
# Модель хаос-теста blockstore
|
||||
|
||||
Seed-driven тест на отказа питания (`src/test/test_blockstore_chaos.cpp`): настоящее хранилище —
|
||||
журнал, метаданные, flusher, compaction, контрольные суммы, recovery — работает на заглушке диска,
|
||||
полностью в RAM. Ничего над ним нет: ни OSD, ни PG, ни сети, ни etcd. Тест обращается к хранилищу
|
||||
напрямую и проверяет только то, что обещает само хранилище. Это пара к
|
||||
[хаос-тесту PG](pg-chaos.ru.md), который считает хранилище корректным.
|
||||
|
||||
Всё, что НИЖЕ хранилища, симулируется: ответы io_uring приходят не в порядке отправки и со
|
||||
случайной задержкой, волатильный кэш записи удерживает часть записей, а потеря питания делает так,
|
||||
что бывшие в полёте записи сохраняются целиком, рвутся по границе сектора или не сохраняются вовсе,
|
||||
случайная половина кэша исчезает. Рядом ведётся модель того, что было записано, и после
|
||||
каждой имитации отказа восстановленное состояние сверяется с ней.
|
||||
|
||||
Один и тот же набор нагрузок и проверок прогоняется на обеих реализациях — v1 (meta_format 2)
|
||||
и v2 (heap, meta_format 3), которые обязаны вести себя одинаково. Сид также задаёт
|
||||
конфигурацию, поэтому упавший прогон воспроизводится тем же сидом; опции — по `-h`.
|
||||
|
||||
Данные: четыре объекта по 128 К (inode 1, четыре stripe) на одном mock-диске в 256 МБ, где
|
||||
метаданные лежат с нуля, журнал — с 16 М, данные — с 32 М; гранула записи 4 К.
|
||||
|
||||
## Конфигурации (24)
|
||||
|
||||
- blockstore v1 / v2 (meta_format 2 / 3) ×
|
||||
- immediate_commit none/all ×
|
||||
- csum_block нет / 4096 / 16384 — 16384 намеренно больше 4 К гранулы записи, то есть запись
|
||||
покрывает лишь часть чексуммного блока ×
|
||||
- мгновенная/двухфазная запись, как в репликах/EC (BS_OP_WRITE_STABLE / BS_OP_WRITE+BS_OP_STABLE)
|
||||
|
||||
2 × 2 × 3 × 2 = 24; конфигурация = `seed % 24`, переопределяется через `--config`. Смешать два
|
||||
стиля записей в одном объекте нельзя: stable-версия поверх unstable отклоняется с EINVAL, а пул —
|
||||
всегда что-то одно.
|
||||
|
||||
## Модель мира
|
||||
|
||||
Для каждого объекта хранятся `submitted` (максимальная отправленная последовательность), `acked`,
|
||||
`synced`, `durable`, а также отображения номер-последовательности → полное содержимое 128 К
|
||||
(пустой вектор = «удалён»), → номер версии, который видит хранилище, и → байт битмапа.
|
||||
Номер последовательности только растёт и именно он является ключом модели, потому что после
|
||||
удаления версии снова начинаются с 1 — хранилище явно разрешает писать низкие версии поверх
|
||||
удаления. `deleted_upto` не даёт старому снимку sync сделать stabilizable стёртую версию, а
|
||||
`can_rollback` помечает, что именно этот экземпляр действительно стабилизировал durable-версию
|
||||
(recovery мог слить её в одну чистую запись).
|
||||
|
||||
Зафиксированность выводится только из завершения операций, дополнительных флагов нет:
|
||||
|
||||
- при `immediate_commit=all` завершённая запись сразу считается synced; при волатильном кэше
|
||||
диска — ничто не synced, пока не завершится накрывающий её SYNC;
|
||||
- synced-удаление и synced-запись `BS_OP_WRITE_STABLE` стабильны сами по себе и сразу становятся
|
||||
durable; двухфазную запись надо ещё стабилизировать, и это происходит асинхронно, позже, из
|
||||
другого шага.
|
||||
|
||||
Содержимое объектов самоидентифицируется: 32-байтные записи `{seq, версия, объект, смещение}`,
|
||||
размер которых делит гранулу 4 К, поэтому такая запись никогда не пересекает границу операции
|
||||
записи или чтения, и любое расхождение декодируется в «какая версия записала эти байты».
|
||||
|
||||
Внешние битмапы тоже самоидентифицируются: каждая запись заполняет свой 4-байтный битмап
|
||||
(один бит на 4 К гранулу) одним узнаваемым байтом. Для хранилища битмап непрозрачен, но он
|
||||
путешествует вместе с записью через compaction, recovery и откаты так же, как данные.
|
||||
|
||||
Инвариант: за раз с объектом работает только одна операция. Пока в полёте его запись, чтение,
|
||||
stabilize или rollback, ничто другое к нему не подходит — поэтому базовое содержимое записи и
|
||||
ожидаемый ответ чтения не могут измениться под ними.
|
||||
|
||||
## Симулируемая реальность
|
||||
|
||||
- **Цикл событий**: один шаг — это завершение самого раннего запроса диска, и виртуальные часы
|
||||
прыгают прямо к нему, поэтому заданные задержки не замедляют тест. Один seed-driven PRNG
|
||||
задаёт и задержки, и нагрузку, и броски «костей» при отказе питания.
|
||||
- **Симулятор диска**: задержка на каждый запрос берётся равномерно (10–200 мкс на чтение и
|
||||
запись, 100–2000 мкс на fsync) — именно из-за разброса completion'ы приходят не по порядку;
|
||||
сектор 4 К; записи до 4 К атомарны и ложатся на диск целиком или не ложатся вовсе. В буферном
|
||||
режиме (`immediate_commit=none`) записи попадают в волатильный кэш и доходят до носителя только
|
||||
по fsync. При `power_loss()` каждая запись в полёте сохраняется целиком, рвётся по границе сектора или
|
||||
не сохранятся вовсе, а записи в кэше выживают и сохраняются на диск с вероятностью 50%, после
|
||||
чего кэш очищается, т.к. при следующем запуске он должен быть пустым и не исчезать при ещё одном
|
||||
отказе. Инъекция ошибок read/write/fsync существует, но по умолчанию выключена: хранилище по замыслу
|
||||
считает большинство ошибок записи фатальными.
|
||||
- **Заглушка ringloop**: неизвестный fd немедленно обрывает тест; `reset()` выбрасывает очереди и
|
||||
ожидающие completion'ы, как если бы процесс умер, — ни один «просроченный» колбэк не может
|
||||
прилететь в уничтоженное хранилище. Отказ питания по определению очищает очередь in-flight диска,
|
||||
а чистая перезагрузка дожидается простоя диска явно.
|
||||
|
||||
## Операции (одна на шаг)
|
||||
|
||||
На каждом шаге действие выбирается по весу (`--p-*`; 0 выключает его):
|
||||
|
||||
- **wait (500)** — ничего не слать, прокрутить одно событие симуляции.
|
||||
- **write (60)** — запись случайного выровненного по 4 К диапазона случайного свободного объекта:
|
||||
новая версия (нумерация после удаления начинается заново), самоидентифицируемое содержимое, свой
|
||||
битмап.
|
||||
- **delete (6)** — удаление существующего объекта; удаление несуществующего — no-op, на который
|
||||
хранилище отвечает без создания записи, поэтому он не тестируется. Удаление стабильно само по себе.
|
||||
- **read (40)** — чтение случайного диапазона: выровненного по 4 К, но — назло — не выровненного по
|
||||
размеру чексуммного блока, чтобы чтения резали и чексуммные блоки, и границы реально записанных
|
||||
экстентов; либо целиком с вероятностью `full_read`% (25). Ответ проверяется по модели при
|
||||
завершении.
|
||||
- **sync (30)** — сброс кэша; покрытие — множество подтверждённых версий на момент отправки, оно
|
||||
трактуется как нижняя граница. Не отправляется, пока в полёте rollback: rollback откатывает
|
||||
модель теста — `acked` и `synced` возвращаются к стабильной версии, и всё выше неё из модели
|
||||
исчезает, — поэтому снимок покрытия начал бы ссылаться на версии, которых уже нет. Это
|
||||
ограничение модели теста, а не API хранилища.
|
||||
- **stabilize (50)** — зафиксировать случайный непустой префикс всего ставшего stabilizable одной
|
||||
операцией с несколькими парами (объект, версия) — ровно так, как делает OSD; одноэлементные
|
||||
операции при этом возникают так же естественно.
|
||||
- **rollback (6)** — выбросить нестабильные версии вместо фиксации. Только двухфазный режим
|
||||
(мгновенная запись стабильна сразу) и только для объектов со стабильной неудалённой версией ниже
|
||||
последней. После успеха всё выше стабильной версии исчезает, и счётчик версий объекта в
|
||||
хранилище откатывается к ней. Не отправляется, пока в полёте sync (по той же причине) и пока
|
||||
в полёте другой rollback.
|
||||
- **restart (1)** — ЧИСТАЯ перезагрузка: дождаться завершения всего в полёте, прочитать все
|
||||
объекты, дождаться простоя диска, уничтожить хранилище, создать заново, прочитать снова.
|
||||
- **crash (2)** — выдернуть шнур прямо сейчас: потеря питания, всё бывшее в полёте учитывается как
|
||||
легальный, но неподтверждённый исход, хранилище уничтожается и создаётся заново, каждый объект
|
||||
проверяется по правилу восстановления.
|
||||
|
||||
Одновременно выполняется не более `max_inflight` (8) операций; шаг при полной очереди вместо
|
||||
отправки ждёт завершения одной из них — здесь проверяется зависание.
|
||||
|
||||
В конце работы всё оставшееся в полёте дожидается, после чего каждый объект читается целиком и
|
||||
проверяется.
|
||||
|
||||
## Учёт результатов операций (account)
|
||||
|
||||
- Завершилась с ожидаемым кодом возврата — содержимое записано в модель под своей
|
||||
последовательностью, `acked` сдвинут, а дальнейшее (synced / durable / требует stabilize)
|
||||
выводится из конфигурации.
|
||||
- Запись или удаление с `-EAGAIN` — отказ, а не потеря (журнал заполнен, flusher не успевает под
|
||||
нагрузкой); модель не меняется.
|
||||
- Упавший sync — значит, он ничего и не синхронизировал; это тоже легально под нагрузкой.
|
||||
- Чтение, прерванное отказом питания, ничего не сообщает и просто отбрасывается.
|
||||
- Всё остальное, включая упавшие stabilize/rollback, — падение теста с печатью затронутых пар
|
||||
(объект, версия).
|
||||
- Запись, бывшая в полёте в момент отказа: её содержимое так же записывается в модель как легальный
|
||||
исход, но `acked` не сдвигается, то есть она всё ещё может быть потеряна.
|
||||
|
||||
## Проверки (все точки отмены)
|
||||
|
||||
**Согласованность данных:**
|
||||
|
||||
1. чтение удалённого или никогда не писанного объекта обязано вернуть `-ENOENT`;
|
||||
2. чтение обязано вернуть ровно подтверждённое содержимое: `retval == len` и побайтовое совпадение
|
||||
по всему диапазону; первая расходящаяся 32-байтная запись печатается с obj/seq/version/offset и
|
||||
ожидаемым значением — то есть устаревшие данные сами называют своего автора;
|
||||
3. внешний битмап в ответе обязан принадлежать именно возвращённой версии
|
||||
(«returned the bitmap of another version»);
|
||||
4. после отказа питания или перезапуска чтение отвечает либо целым объектом, либо `-ENOENT` —
|
||||
любой иной retval означает, что на диск попало порванное содержимое;
|
||||
5. то, что объект «вернулся», обязано быть содержимым версии не ниже гарантированной границы:
|
||||
последней durable — после отказа питания, последней подтверждённой (последней synced при
|
||||
волатильном кэше) — после перезапуска, который ничего не потерял. Иначе — падение с
|
||||
«came back ... holding unexpected content» и диффом по каждой версии-кандидату: та, что почти
|
||||
совпадает, обычно и показывает, какая запись потерялась или применилась не в том порядке;
|
||||
6. объект вправе полностью исчезнуть только тогда, когда ничего не гарантировалось; тогда модель
|
||||
сбрасывается, и нумерация начинается с 1;
|
||||
7. при `immediate_commit=all` чистая перезагрузка обязана вернуть ровно то же состояние — тот же
|
||||
retval, та же версия, те же байты; в сообщении о падении печатается ещё и первый никогда не
|
||||
писанный сектор журнала, который прямо указывает на потерянную запись;
|
||||
8. вернувшееся содержимое становится новой базой, но не новой durable-точкой: durable-содержимое
|
||||
остаётся легальным исходом, `can_rollback` сбрасывается, и следующий отказ всё ещё может
|
||||
откатить объект к durable-версии;
|
||||
9. rollback вправе удалить только версии выше стабильной, и счётчик версий откатывается
|
||||
соответственно — иначе это заметят последующие записи и чтения;
|
||||
10. финальные чтения целых объектов обязаны совпасть с подтверждённым содержимым.
|
||||
|
||||
**Живость:**
|
||||
|
||||
11. «operations did not complete in 1000000 steps — deadlock?» — зависшие операции печатаются
|
||||
вместе с диагностикой хранилища (completed/fsynced/compacted LSN, очередь compact) в v2;
|
||||
12. «blockstore failed to start»;
|
||||
13. «a read of object N did not complete in MAX_STEPS — deadlock?» и «the final read of object N
|
||||
did not complete»;
|
||||
14. «disk did not go idle before a clean restart» — защита от use-after-free: ни один запрос не
|
||||
может пережить хранилище, которое его послало.
|
||||
|
||||
**Учёт отказов:**
|
||||
|
||||
15. отказом записи/удаления принимается только `-EAGAIN`, упавший sync трактуется как «ничего не
|
||||
синхронизировал», а любая другая ошибка — включая stabilize/rollback — обрывает тест.
|
||||
|
||||
**Защиты тестовых заглушек:**
|
||||
|
||||
16. неожиданный fd в заглушке ringloop, отклонённый SQE, `--max-inflight < 1`;
|
||||
17. перекрывающиеся одновременные записи: запись, отправленная, пока в полёте находится другая,
|
||||
накрывающая часть её диапазона, — падение теста. Устройство вправе применить такую пару в
|
||||
любом порядке, поэтому полагаться на то, что победит более новая, — ошибка; ловить это на
|
||||
отправке детерминированно лучше, чем ждать неудачного порядка завершения.
|
||||
|
||||
## Отчёт и воспроизводимость
|
||||
|
||||
По умолчанию тест прогоняет 48 фиксированных сидов (каждая конфигурация дважды) плюс 152 случайных,
|
||||
равномерно разложенных по конфигурациям, — всего 200 сидов × 10000 шагов. Каждое сид выполняется в
|
||||
отдельном дочернем процессе, поэтому одно падение не роняет весь прогон, а упавшие сиды печатаются
|
||||
в конце. `--seed N` выполняет одно сид в том же процессе — именно это нужно под отладчиком;
|
||||
`--seeds a-b`, `--random n`, `--steps n`, `--config n` и веса `--p-*` настраивают прогон
|
||||
(например, `--p-delete 0 --p-rollback 0` даёт нагрузку без удалений и откатов).
|
||||
|
||||
OK-строка: writes (refused with EAGAIN) / deletes / syncs / stabilizes / rollbacks / crashes /
|
||||
clean restarts / verified reads / disk ops.
|
||||
|
||||
Детерминизм: один сид ⇒ та же конфигурация и то же расписание; `-v` даёт трассу каждой операции и
|
||||
каждого запроса к диску, включая смоделированную задержку, решение при отказе питания по каждой
|
||||
бывшей в полёте записи и каждую запись, выброшенную из волатильного кэша.
|
||||
|
||||
Собирается через `make build_tests`, запускается ctest'ом как `test_blockstore_chaos`.
|
||||
220
docs/tests/pg-chaos.en.md
Normal file
220
docs/tests/pg-chaos.en.md
Normal file
@@ -0,0 +1,220 @@
|
||||
[Documentation](../../README.md#documentation) → Tests → The PG chaos-test model
|
||||
|
||||
-----
|
||||
|
||||
[Читать на русском](pg-chaos.ru.md)
|
||||
|
||||
# The PG chaos-test model
|
||||
|
||||
A seed-driven stress test of the PG machinery (`src/test/test_pg_chaos.cpp`): ONE
|
||||
real `osd_t` (the primary) with a real blockstore over a mock disk (entirely in
|
||||
RAM, `ringloop_mock`) owns a single PG (number 1, pool 1, four 128 K objects, 4 K
|
||||
granularity). The other PG members are fake secondary OSDs inside the test. The
|
||||
pool is either replicated x3 (members 2,3, spare 4) or EC 2+2 (members 2..4,
|
||||
spare 5, one object = one parity stripe). The seed uniquely determines the
|
||||
configuration and the whole event sequence; a failing run is reproduced with
|
||||
the same `--seed`.
|
||||
|
||||
What it mainly verifies is the PG machinery (the subop fan-out,
|
||||
peering/LIST/rollback/stabilize, repeer daemons, stop_pg, INCOMPLETE, recovery) and
|
||||
partly the primary OSD's storage; checking the storage is not the test's main goal -
|
||||
it is covered by the [blockstore chaos test](blockstore-chaos.en.md).
|
||||
|
||||
## Configurations (10)
|
||||
|
||||
- replicated/EC ×
|
||||
- immediate_commit none/all ×
|
||||
- csum_block none/4096/16384
|
||||
|
||||
`--recovery` enables recovery/rebalance after a set change (off by default so that
|
||||
degraded states get exercised).
|
||||
|
||||
## The world model
|
||||
|
||||
Each object has an ordered version history; a version enters the model at SUBMIT
|
||||
time (the delta = the request's exact bytes/length/granule bitmap), with a state:
|
||||
- `V_SUBMITTED` - the op was sent and has no answer yet (in flight). It behaves
|
||||
like V_OPTIONAL in every respect but one: concurrent reads are entitled not to
|
||||
show this write's result, and that must not mark the version DEAD.
|
||||
- `V_OPTIONAL` - the write was sent but not acknowledged: it either applied (then
|
||||
as a whole) or did not apply at all. Versions reach this state from V_SUBMITTED
|
||||
and, in the explicit-fsync modes, from V_ACKED when the client session dies
|
||||
before a SYNC request (that counts as a marker that the write is unacknowledged).
|
||||
Observing an OPTIONAL write's effect in a later read restores it to ACKED;
|
||||
observing its absence (not visible over its own range) makes it DEAD.
|
||||
- `V_ACKED` - the write was acknowledged; the model records `ack_live` (the live set
|
||||
at ack time - used to check that the failure model wasn't exceeded). With
|
||||
immediate_commit=all it is immediately considered on-disk durable. An ACKED write
|
||||
must not roll back while the client's session is alive.
|
||||
- `V_SYNCED` - acknowledged and SYNCed: durable on disk, and it may never roll back
|
||||
again at all.
|
||||
- `V_PARTIAL` - deleted, but possibly not from every OSD (the PG stayed LEFT_ON_DEAD).
|
||||
- `V_DEAD` - the version was either definitely refused (-EAGAIN, possibly -ENOSPC in
|
||||
the future), or it was OPTIONAL and it later became certain that it was refused
|
||||
because a subsequent read did NOT observe it. A DEAD version showing again fails
|
||||
the test.
|
||||
|
||||
Object contents are self-identifying: the pattern encodes the object, the version and
|
||||
the offset, so a read result decodes back into "which version wrote these bytes".
|
||||
|
||||
Verification reads ONLY through the primary OSD and checks that the answer is
|
||||
explained by a merge of ONE consistent subset of the written versions, where every
|
||||
durable version is definitely present, every refused one is definitely absent, and
|
||||
the contents never lie about their authorship. With an incomplete deletion, EC may
|
||||
legitimately answer INCOMPLETE, and replicated pools may resurrect the object.
|
||||
|
||||
Everything derives from version states and events, with no extra flags: an ACKED
|
||||
version cannot vanish except through an event that first breaks the session's
|
||||
guarantee - a crash (taking the session down with the process) or a
|
||||
repeer/stop_pg (which stop dirty sessions BEFORE peering starts).
|
||||
|
||||
The test's checks look ONLY at what the write path exposes to the client; the model
|
||||
deliberately ignores things the client cannot know about, such as paired OSD
|
||||
deaths per se.
|
||||
|
||||
## The simulated reality
|
||||
|
||||
- **Disk simulator**: requests carry delays; `power_loss()` = power outage -
|
||||
uncommitted writes are lost, committed ones survive. An unknown FD/opcode aborts
|
||||
the test (a stub guard).
|
||||
- **etcd simulator**: keys/values + leases; revoke/TTL are emulated on a crash (the
|
||||
OSD's keys are removed, its lease revoked).
|
||||
- **Peer OSD simulator**: answers per the secondary-OSD/blockstore contract -
|
||||
read/write/delete, SYNC, LIST. When a peer OSD dies, non-SYNCed writes die with it
|
||||
with probability `peer_cache_loss`% (default 50 - modelling a volatile disk cache);
|
||||
SYNCed ones always survive. A peer crash by itself does NOT change the world model:
|
||||
the model only knows what the client sees. The crash repeers the PG, the repeer
|
||||
kills dirty client sessions (volatile ACKED writes are exactly what makes a client
|
||||
dirty), the session dies - and THAT is what the client observes
|
||||
(PEER_STOPPED/EPIPE), and only session_died() demotes. If a crash rolled something
|
||||
back under a live session, that would be a rollback invisible to the client -
|
||||
check 5 catches it.
|
||||
- **Network simulator**: service_peers runs every round. The request-phase delay:
|
||||
a random `--p-wire`% (default 70) of each peer's queued subops gets applied; the
|
||||
response-phase delay: a random `p_reply`% of the already-applied replies gets
|
||||
delivered. A reply belongs to its connection: the connection died - undelivered
|
||||
replies die with `-EPIPE` (the apply stays). When an OSD instance dies, however,
|
||||
mutating ops still in `sent_ops` are copied into a separate "wire" queue; they are
|
||||
applied later at the `--p-wire` rate WITHOUT an answer (the connection fell).
|
||||
Non-mutating ops (READ/LIST) are dropped (nobody left to answer), and the harvested
|
||||
queue is capped at 64 entries.
|
||||
|
||||
## Operations (one per step)
|
||||
|
||||
Each step picks an action by weight (`--p-*`; 0 disables it):
|
||||
|
||||
- **wait (500)** - send nothing, just run the simulation (event windows).
|
||||
- **write (60)** - write a random range of a random object; bump the version; the
|
||||
delta is remembered as OPTIONAL; at most max_inflight (8) in flight.
|
||||
- **delete (6)** - delete a random object; the version is remembered as OPTIONAL with
|
||||
zero length (a full delete); LEFT_ON_DEAD/ack are tracked in account().
|
||||
- **read (40)** - read an object: whole with probability `full_read`%, otherwise an
|
||||
arbitrary range; a whole read verifies the object.
|
||||
- **sync (30)** - flush the cache (fsync); on confirmation the versions are marked
|
||||
SYNCED (durable).
|
||||
- **restart (1)** - a CLEAN OSD restart: drain the queue (all inflight finish), wait
|
||||
for the disk to go idle, destroy, recreate, wait for the OSD to come up, then,
|
||||
with `--p-post` (50%) chance, read and verify all object contents ("a clean restart
|
||||
that lost nothing").
|
||||
- **takeover (1)** - a PG handover: first stop the PG by pointing the primary at a
|
||||
fake member in the etcd stub -> stop_pg stops the PG; right after the
|
||||
`/pg/state/1/1` key disappears (meaning the OSD released the PG) -> recreate the OSD
|
||||
and point the primary back at it -> re-verify the objects as in restart.
|
||||
- **crash (2)** - the primary OSD crashes: a disk power loss (un-synced writes lost),
|
||||
lease cancel + removal of the OSD's keys without cancelling the ops in flight to
|
||||
peer OSDs, a new instance starts, objects re-verified.
|
||||
- **peer_down (3)** - a peer OSD crashes: a victim is chosen that breaks no object's
|
||||
quorum (all latest OPTIONAL versions down to the first SYNCED are checked), the peer
|
||||
OSD stops and its connection drops.
|
||||
- **peer_up (3)** - a peer OSD comes back (connects - if the PG or its history still
|
||||
involves it); then settle(): wait for the PG to come up (ACTIVE|INCOMPLETE +
|
||||
quiescence), then run recover_pending - deferred checks of objects whose chains may
|
||||
have re-settled.
|
||||
- **set_change (1)** - the PG moves to another OSD set through etcd; with
|
||||
`--recovery` - recovery reads; without it, degradation is legal and the
|
||||
"surviving copies" world is protected by the checks.
|
||||
|
||||
At the end - wait for completion: clean up until "the PG is healthy and every op has
|
||||
finished", at most MAX_STEPS=1e6 steps -> exceeding that aborts with a "did not
|
||||
settle" error.
|
||||
|
||||
## Op outcome accounting (account)
|
||||
|
||||
- Completed with the expected retval -> V_ACKED. A delete without LEFT_ON_DEAD closes
|
||||
the partial-deletion window. A delete with LEFT_ON_DEAD must be repeated after the
|
||||
peers come back, and in EC it allows a future INCOMPLETE unless the object is
|
||||
rewritten in the meantime.
|
||||
- Completed with EAGAIN -> V_DEAD: the version was definitely not applied; currently
|
||||
unreachable in the test, kept as a placeholder for the future - it would also apply
|
||||
to e.g. ENOSPC.
|
||||
- Completed with EPIPE -> the version stays OPTIONAL: a refusal is not an ack, but the
|
||||
op may have applied (or not). An optional delete must also be repeated after the
|
||||
peers come back and likewise allows EC INCOMPLETE until the next rewrite.
|
||||
- Completed with any other error -> the test aborts ("failed with retval").
|
||||
|
||||
## Checks (every abort point)
|
||||
|
||||
**Data consistency (world_check):**
|
||||
1. world_check - the answer must be explained by a subset of the versions: every
|
||||
required (durable) one is present; bytes are answered by exactly their own version
|
||||
("record obj/seq/off mismatch", a bitmap granule "carries data from wrong
|
||||
version").
|
||||
2. "shows %s but the highest..." - an old version of the object was read while later
|
||||
writes are lost (monotonicity broken).
|
||||
3. "read shows seq over acked v's granule" - a granule's contents (obj/seq/off in the
|
||||
record) contradict the version that owns the granule in the model: stitched or
|
||||
torn contents instead of the acknowledged bytes.
|
||||
4. "DEAD version showed again" - refused versions must not come back.
|
||||
5. "committed version read fully absent over floor" / "established version read
|
||||
absent over its granule" - acknowledged ops must not disappear.
|
||||
6. A read -EIO "OSD deems unrecoverable" is legal in exactly one window: an
|
||||
unfinished EC deletion. Outside it, -EIO aborts the test - including a "clean" ack
|
||||
delete + INCOMPLETE after a revival (the OSD lied about completeness) and a chain
|
||||
rollback under a live session with no deletion window; any other retval != len
|
||||
aborts the test.
|
||||
7. bitmap_len != the expected read answer length -> abort the test.
|
||||
8. "came back INCOMPLETE" after set_change/crash - same criterion: an unfinished
|
||||
deletion window makes INCOMPLETE legal and the deletion is repeated; anything
|
||||
else aborts the test.
|
||||
9. "came back ... which no world of the recorded versions explains" - the final
|
||||
check of object contents after the test settles.
|
||||
10. "changed across a clean restart that lost nothing" - object immutability across
|
||||
a clean restart.
|
||||
|
||||
**Liveness/timing:**
|
||||
|
||||
11. "did not settle in MAX_STEPS" - the ops never completed within a huge step count
|
||||
(a possible self-deadlock);
|
||||
12. "operations did not complete" - stuck ops, printed in the dump; "a read of
|
||||
object N did not complete in MAX_STEPS ... deadlock?"; "OSD did not load PGs
|
||||
from etcd in MAX_STEPS" / "OSD did not finish peering in MAX_STEPS" - start-up
|
||||
checks.
|
||||
13. "did not release the PG" - the OSD didn't give the PG up when commanded;
|
||||
14. "disk did not go idle" - a use-after-free guard: every disk op must finish
|
||||
before the OSD is destroyed;
|
||||
15. "PG did not become healthy after reviving every peer" - the PG stayed down after
|
||||
all its OSDs came back;
|
||||
16. "pending recovery/repeated deletion could not complete on a healthy PG" - a
|
||||
deletion/recovery that never finished on a live PG.
|
||||
|
||||
**Test-stub guards:**
|
||||
|
||||
17. An unexpected SQE (fd/opcode) on the disk stub; "unexpected secondary opcode" on
|
||||
a peer; arguments like `--p-reply >= 1`, `--max-inflight >= 1`, etc.
|
||||
|
||||
**Coverage checks:**
|
||||
|
||||
18. `peer_cache_loss<100` + a volatile config + >=8 peer deaths -> verify that the
|
||||
variant where a peer OSD kept its journal ran at least once.
|
||||
19. >=10 dirty OSD deaths/PG handovers -> wire_harvested > 0: at least one op of the
|
||||
primary OSD that was in flight must have been harvested into the "wire" on the
|
||||
way down - the "delivery from a dead OSD" path was exercised.
|
||||
|
||||
## Reporting and reproducibility
|
||||
|
||||
The OK line: writes(refused)/deletes/syncs/crashes/restarts/takeovers/peer
|
||||
deaths(kept journal)/recoveries/set changes/verified reads/stragglers
|
||||
(applied/captured/lost)/disk ops.
|
||||
|
||||
Determinism: one seed -> the same configuration and the same schedule; `-v` traces
|
||||
disk and peer-OSD operations, op harvesting on peer deaths, and etcd changes.
|
||||
197
docs/tests/pg-chaos.ru.md
Normal file
197
docs/tests/pg-chaos.ru.md
Normal file
@@ -0,0 +1,197 @@
|
||||
[Документация](../../README-ru.md#документация) → Тесты → Модель хаос-теста PG (`src/test/test_pg_chaos.cpp`)
|
||||
|
||||
-----
|
||||
|
||||
[Read in English](pg-chaos.en.md)
|
||||
|
||||
# Модель хаос-теста PG
|
||||
|
||||
Seed-driven стресс-тест PG-машинерии (`src/test/test_pg_chaos.cpp`): ОДИН настоящий
|
||||
`osd_t` (primary) с настоящим хранилищем на заглушке диска (полностью в RAM, `ringloop_mock`)
|
||||
владеет одной PG (номер 1, пул 1, объекты — 4 шт по 128 К, гранула 4 К). Остальные члены PG —
|
||||
фейковые вторичные OSD внутри теста. PG: реплицированная x3 (members 2,3, spare 4) или
|
||||
EC 2+2 (members 2..4, spare 5, объект = один parity-stripe). Сид однозначно задаёт
|
||||
конфигурацию и всю последовательность событий; упавший прогон воспроизводится тем же `--seed`.
|
||||
|
||||
Проверяется в первую очередь PG-машинерия (subop-веер, peering/LIST/rollback/stabilize, repeer-демоны,
|
||||
stop_pg, INCOMPLETE, recovery) и частично хранилище первичного OSD; однако, проверка хранилища —
|
||||
не главная цель теста, его покрывает [хаос-тест blockstore](blockstore-chaos.ru.md).
|
||||
|
||||
## Конфигурации (10)
|
||||
|
||||
- replicated/EC ×
|
||||
- immediate_commit none/all ×
|
||||
- csum_block нет/4096/16384
|
||||
|
||||
`--recovery` включает recovery/rebalance после set-change (по умолчанию выкл, чтобы
|
||||
гонять degraded-состояния).
|
||||
|
||||
## Модель мира
|
||||
|
||||
Для каждого объекта — упорядоченная история версий; версия пишется в модель в момент
|
||||
SUBMIT (дельта = точные байты/длина/битмап гранул запроса), состояние:
|
||||
- `V_SUBMITTED` — операция отправлена, ответа ещё нет (выполняется). Ведёт себя как
|
||||
V_OPTIONAL во всём, кроме одного: параллельные чтения вправе не показывать результат
|
||||
этой записи, и это не будет маркировать её DEAD.
|
||||
- `V_OPTIONAL` — запись отправлена, но не подтверждена, и может быть либо применена
|
||||
(но тогда целиком), либо не применена вообще. Версии попадают в это состояние из
|
||||
V_SUBMITTED и, в режимах с явными fsync, V_ACKED при гибели клиентской сессии до
|
||||
запроса SYNC (это считается маркером, что запись не подтверждена).
|
||||
Наблюдение эффекта OPTIONAL записи в последующем чтении восстанавливает её в ACKED;
|
||||
наблюдение её отсутствия (когда она не видна в своём диапазоне) ⇒ DEAD.
|
||||
- `V_ACKED` — запись подтверждена; запоминается `ack_live` (живой набор на момент ack —
|
||||
используется для проверки превышения модели отказов). При immediate_commit=all сразу
|
||||
считается зафиксированной на диске. ACKED запись не должна откатываться, пока сессия
|
||||
клиента жива.
|
||||
- `V_SYNCED` — подтверждена и SYNC-нута ⇒ зафиксирована на диске и более не должна
|
||||
откатываться вообще.
|
||||
- `V_PARTIAL` — удалена, но, возможно, не со всех OSD (PG осталась в LEFT_ON_DEAD).
|
||||
- `V_DEAD` — версия либо точно отказана (-EAGAIN, возможно -ENOSPC в будущем), либо
|
||||
была OPTIONAL, но после этого стало точно известно, что она откачена, так как последующее
|
||||
чтение её уже НЕ наблюдало. Повторное появление DEAD-версии — провал теста.
|
||||
|
||||
Содержимое объектов самоидентифицируется версией: паттерн кодирует объект, версию и смещение —
|
||||
прочитанное можно декодировать обратно в «какая версия записала эти байты».
|
||||
|
||||
Верификация читает ТОЛЬКО через первичный OSD и проверяет, что ответ объясняется слиянием
|
||||
ОДНОГО согласованного подмножества записанных версий, где все зафиксированные точно присутствуют,
|
||||
все откаченные точно отсутствуют, а содержимое не врёт об авторстве. При неполном удалении
|
||||
разрешается INCOMPLETE в EC, а в репликах допускается воскрешение объекта.
|
||||
|
||||
Всё выводится из состояний версий и событий, без дополнительных флагов: ACKED не может
|
||||
исчезнуть, кроме как через событие, которое сначала ломает гарантию сессии — краш (уносит
|
||||
сессию вместе с процессом) или repeer/stop_pg (останавливают dirty-сессии ДО начала пиринга).
|
||||
|
||||
Проверки в тесте смотрят ТОЛЬКО на то, как процесс записи видит клиент, и не учитывают
|
||||
в модели, например, падения парных OSD сами по себе, так как клиент не может о них знать.
|
||||
|
||||
## Симулируемая реальность
|
||||
|
||||
- **Симулятор диска**: запросы с задержками; `power_loss()` = потеря питания — незафиксированные
|
||||
записи теряются, зафиксированные остаются. Неизвестный FD/opcode → падение теста (защита заглушки).
|
||||
- **Симулятор etcd**: ключ/значение + lease; revoke/TTL эмулируются при крахе (ключи OSD'а
|
||||
удаляются, lease отзывается).
|
||||
- **Симулятор парных OSD**: отвечает в соответствии с контрактом вторичного OSD / blockstore.
|
||||
Чтение/запись/удаление, SYNC, LIST. При падении парного OSD не-SYNC-нутые записи гибнут
|
||||
с вероятностью `peer_cache_loss`% (по умолчанию 50 — моделирует волатильный кэш диска),
|
||||
SYNC-нутые выживают всегда. Модель мира на краш пира сама НЕ реагирует: она знает
|
||||
только то, что видит клиент. Краш реперит PG, репер убивает dirty-сессии клиентов
|
||||
(volatile ACKED — это и есть dirty-клиент), сессия гибнет — вот это клиент наблюдает
|
||||
(PEER_STOPPED/EPIPE), и только session_died() делает demote. Если краш откатит
|
||||
что-то при живой сессии — это ненаблюдаемый клиентом откат, проверка 5 его ловит.
|
||||
- **Симулятор сети**: service_peers, каждый раунд. Задержка на этапе запроса — применяются случайные
|
||||
`--p-wire`% (по умолчанию 70) очередей subop'ов пира; задержка на этапе ответа — доставляются
|
||||
случайные `p_reply`% применённых ответов. Ответ принадлежит соединению: соединение
|
||||
умерло — недоставленные ответы гибнут с `-EPIPE` (применение остаётся). Однако, при
|
||||
гибели экземпляра OSD мутирующие операции в `sent_ops` копируются в отдельную очередь
|
||||
«сети»; применяются позже (`--p-wire`%) БЕЗ ответа (соединение упало). Немутирующие
|
||||
операции (READ/LIST) отбрасываются (отвечать некому), очередь собранных операций
|
||||
ограничивается 64.
|
||||
|
||||
## Операции (step)
|
||||
|
||||
На каждом шаге (веса `--p-*`; 0 выключает действие):
|
||||
|
||||
- **wait (500)** — ничего не слать, прокрутить симуляцию (событийные окна).
|
||||
- **write (60)** — запись случайного диапазона случайного объекта; увеличение версии;
|
||||
дельта запоминается как OPTIONAL; ≤ max_inflight (8) одновременно.
|
||||
- **delete (6)** — удаление случайного объекта; версия запоминается как OPTIONAL с
|
||||
нулевой длиной (полное удаление); LEFT_ON_DEAD/ack отслеживаются в account().
|
||||
- **read (40)** — чтение объекта, полное с вероятностью `full_read`%, иначе произвольный
|
||||
диапазон; при полном чтении объект проверяется.
|
||||
- **sync (30)** — синхронизация кэша (fsync); при подтверждении версии помечаются SYNCED
|
||||
(зафиксированными).
|
||||
- **restart (1)** — ЧИСТАЯ перезагрузка OSD: очистка очереди (все inflight закончены), ожидание
|
||||
простоя диска, уничтожение, пересоздание, ожидание подъёма OSD и, с шансом `--p-post`,
|
||||
чтение и проверка содержимого всех объектов («чистый перезапуск, который ничего не потерял»).
|
||||
- **takeover (1)** — передача PG: сначала остановка PG через смену первичного OSD на
|
||||
фейковый в заглушке etcd → stop_pg останавливает PG; далее сразу после удаления ключа
|
||||
`/pg/state/1/1` (означающего, что OSD остановил PG) → пересоздание OSD и его переустановка
|
||||
в качестве первичного → перепроверка объектов, как в restart.
|
||||
- **crash (2)** — падение первичного OSD: потеря питания диска (потеря не-синкнутых записей),
|
||||
отмена лизы + удаление ключей OSD без отмены операций в полёте к парным OSD, запуск нового
|
||||
экземпляра, перепроверка объектов.
|
||||
- **peer_down (3)** — крах парного OSD: выбирается жертва, не ломающая кворум ни
|
||||
одного объекта (проверяются все последние OPTIONAL версии до первой SYNCED), парный OSD
|
||||
останавливается, соединение с ним разрывается.
|
||||
- **peer_up (3)** — подъём парного OSD (соединение — если PG или её история его ещё
|
||||
касается); после — settle(): ждать подъёма PG (ACTIVE|INCOMPLETE + покой), затем
|
||||
прогнать recover_pending — отложенные проверки объектов, чьи цепи могли перегласоваться.
|
||||
- **set_change (1)** — переезд PG на другой OSD-набор через etcd; с `--recovery` —
|
||||
восстановительные чтения; без — деградация легальна, мир «выживших копий» защищён
|
||||
проверками.
|
||||
|
||||
В конце — ожидание завершения: очистка до «PG в порядке и все операции завершены», максимум
|
||||
до MAX_STEPS=1e6 шагов → если превышается, то падение с ошибкой «did not settle».
|
||||
|
||||
## Учёт результатов операций (account)
|
||||
|
||||
- Завершена с ожидаемым кодом возврата → V_ACKED. Удаление без LEFT_ON_DEAD закрывает
|
||||
окно частичного удаления. Удаление с LEFT_ON_DEAD требует повтора после подъёма
|
||||
пиров, а с EC допускает будущий INCOMPLETE, если объект не перезаписан вновь.
|
||||
- Завершена с EAGAIN → V_DEAD: версия точно не применена; в тесте сейчас недостижимо,
|
||||
оставлено как заготовка на будущее, также применимо, например, к ENOSPC.
|
||||
- Завершена с EPIPE → версия остаётся OPTIONAL: отказ — не ack, но операция могла
|
||||
примениться (а могла и нет). Опциональное удаление также требует повтора после
|
||||
подъёма пиров и тоже разрешает EC INCOMPLETE до следующей перезаписи.
|
||||
- Завершена с другой ошибкой → падение теста («failed with retval»).
|
||||
|
||||
## Проверки (все точки abort)
|
||||
|
||||
**Согласованность данных (world_check):**
|
||||
1. world_check — ответ обязан объясняться подмножеством версий: все обязательные
|
||||
(зафиксированные) присутствуют; байты отвечают ровно своей версией
|
||||
(«record obj/seq/off mismatch», битмап-гранула «carries data from wrong version»).
|
||||
2. «shows %s but the highest…» — прочитана старая версия объекта, последние записи
|
||||
потеряны (монотонность нарушена).
|
||||
3. «read shows seq over acked v's granule» — содержимое гранулы (obj/seq/off в record)
|
||||
противоречит версии, которой гранула принадлежит по модели: сборное/порванное
|
||||
содержимое вместо подтверждённых байт.
|
||||
4. «DEAD version showed again» — откаченные версии не должны возвращаться.
|
||||
5. «committed version read fully absent over floor» / «established version read absent
|
||||
over its granule» — подтверждённые операции не должны исчезать.
|
||||
6. read -EIO «OSD deems unrecoverable» — легален ровно в одном окне: незавершённое
|
||||
EC-удаление. Вне его -EIO — падение теста, в т.ч. «чистый» ack удаления + INCOMPLETE
|
||||
после revival (OSD соврал о полноте) и откат цепей при живой сессии без окна удаления;
|
||||
прочие retval ≠ len → падение теста.
|
||||
7. bitmap_len ≠ ожидаемому в ответах чтения → падение теста.
|
||||
8. «came back INCOMPLETE» после set_change/crash — тот же критерий: окно незавершённого
|
||||
удаления ⇒ INCOMPLETE легален и удаление повторяется; в ином случае → падение теста.
|
||||
9. «came back … which no world of the recorded versions explains» — финальная проверка
|
||||
корректности содержимого объектов после завершения теста.
|
||||
10. «changed across a clean restart that lost nothing» — неизменность объектов после перезапуска.
|
||||
|
||||
**Живость/тайминг:**
|
||||
|
||||
11. «did not settle in MAX_STEPS» — операции не завершились за большое число шагов (возможна
|
||||
самоблокировка);
|
||||
12. «operations did not complete» — залипшие операции, печатаются в дампе;
|
||||
«a read of object N did not complete in MAX_STEPS ... deadlock?»; «OSD did not load
|
||||
PGs from etcd in MAX_STEPS» / «OSD did not finish peering in MAX_STEPS» — проверка на старте OSD.
|
||||
13. «did not release the PG» — OSD не отпустил PG по команде;
|
||||
14. «disk did not go idle» — проверка против use-after-free, что все операции диска завершены
|
||||
перед уничтожением OSD;
|
||||
15. «PG did not become healthy after reviving every peer» — PG не поднялась после подъёма всех OSD;
|
||||
16. «pending recovery/repeated deletion could not complete on a healthy PG» — удаление/восстановление
|
||||
не завершено на живой PG.
|
||||
|
||||
**Защиты тестовых заглушек:**
|
||||
|
||||
17. Неожиданный SQE (fd/opcode) на заглушке диска; «unexpected secondary opcode» у пира;
|
||||
аргументы `--p-reply ≥ 1`, `--max-inflight ≥ 1` и т.п.
|
||||
|
||||
**Проверки покрытия:**
|
||||
|
||||
18. `peer_cache_loss<100` + volatile-конфиг + ≥8 смертей пира ⇒ проверка, что хотя бы
|
||||
раз выполнен вариант, в котором парный OSD не потерял журнал.
|
||||
19. ≥10 грязных смертей OSD/передач PG ⇒ wire_harvested > 0: хотя бы одна операция
|
||||
первичного OSD, бывшая в полёте, обязана была собраться в «сеть» при остановке —
|
||||
путь «доставки от мёртвого OSD» выполнен.
|
||||
|
||||
## Отчёт и воспроизводимость
|
||||
|
||||
OK-строка: writes(refused)/deletes/syncs/crashes/restarts/takeovers/peer deaths
|
||||
(kept journal)/recoveries/set changes/verified reads/stragglers (applied/captured/lost)/disk ops.
|
||||
|
||||
Детерминизм: один seed ⇒ та же конфигурация и то же расписание; `-v` — трасса операций
|
||||
диска и парных OSD, захватов операций при падении пиров и изменений etcd.
|
||||
@@ -165,7 +165,7 @@ See also about [how to export snapshots](qemu.en.md#exporting-snapshots).
|
||||
|
||||
## modify
|
||||
|
||||
`vitastor-cli modify <name> [--rename <new-name>] [--resize <size>] [--readonly | --readwrite] [-f|--force] [--down-ok]`
|
||||
`vitastor-cli modify <name> [--rename <new-name> [--with-snapshots]] [--resize <size>] [--readonly | --readwrite] [-f|--force] [--down-ok]`
|
||||
|
||||
Rename, resize image or change its readonly status. Images with children can't be made read-write.
|
||||
If the new size is smaller than the old size, extra data will be purged.
|
||||
@@ -174,6 +174,8 @@ You should resize file system in the image, if present, before shrinking it.
|
||||
* `--deleted 1|0` - Set/clear 'deleted image' flag (set automatically during unfinished deletes).
|
||||
* `-f|--force` - Proceed with shrinking or setting readwrite flag even if the image has children.
|
||||
* `--down-ok` - Proceed with shrinking even if some data will be left on unavailable OSDs.
|
||||
* `--with-snapshots` - Also rename snapshots `<name>@*` to `<new-name>@*`, one by one after the image.
|
||||
Refuse to rename if any `<new-name>@*` already exists.
|
||||
* `--enc-key HEX` - Change image encryption key (allowed only with `--force`).
|
||||
* `--owner USERNAME` - Change image owner.
|
||||
* `--owner-group NAME` - Change image owner group name.
|
||||
@@ -196,6 +198,7 @@ Options can be specified in classic dd style (`key=value`) or like usual (`--key
|
||||
| `iimg=<image>` | Copy from Vitastor image `<image>` |
|
||||
| `if=<file>` | Copy from file `<file>` |
|
||||
| `oimg=<image>` | Copy to Vitastor image `<image>` |
|
||||
| `opool=<pool>` | Pool to create output image if it doesn't exist |
|
||||
| `of=<file>` | Copy to file `<file>` |
|
||||
| `bs=1M` | Set copy block size |
|
||||
| `count=N` | Copy only N input blocks. If N ends in B it counts bytes, not blocks |
|
||||
@@ -230,8 +233,8 @@ Options:
|
||||
* `--writers-stopped` allows optimised removal in case of a single 'slim' read-write
|
||||
child and 'fat' removed parent: the child is merged into parent and parent is renamed
|
||||
to child in that case. In other cases parent layers are always merged into children.
|
||||
* `--exact` - remove multiple images with names matching given glob patterns.
|
||||
* `--matching` - remove multiple images with given names
|
||||
* `--exact` - remove multiple images with given names.
|
||||
* `--matching` - remove multiple images with names matching given glob patterns.
|
||||
* `--down-ok` - continue deletion/merging even if some data will be left on unavailable OSDs.
|
||||
|
||||
## flatten
|
||||
@@ -286,7 +289,7 @@ Describe unclean object locations in the cluster. Options:
|
||||
|
||||
## fix
|
||||
|
||||
`vitastor-cli fix [--objects <objects>] [--bad-osds <osds>] [--part <part>] [--check no]`
|
||||
`vitastor-cli fix [--objects <objects>] --bad-osds <osds> [--part <part>] [--check no]`
|
||||
|
||||
Fix inconsistent objects in the cluster by deleting some copies.
|
||||
|
||||
@@ -297,7 +300,7 @@ Fix inconsistent objects in the cluster by deleting some copies.
|
||||
Plain text format: 0x<inode>:0x<stripe> <any delimiter> 0x<inode>:0x<stripe> ...
|
||||
JSON format: [{"inode":"0x...","stripe":"0x..."},...]
|
||||
--bad-osds <osds>
|
||||
Remove inconsistent copies/parts of objects from these OSDs, effectively
|
||||
Required. Remove inconsistent copies/parts of objects from these OSDs, effectively
|
||||
marking them bad and allowing Vitastor to recover objects from other copies.
|
||||
--part <number>
|
||||
Only remove EC part <number> (from 0 to pg_size-1), required for extreme
|
||||
@@ -315,14 +318,17 @@ Allocate a new OSD number and reserve it by creating empty `/osd/stats/<n>` key.
|
||||
|
||||
## rm-osd
|
||||
|
||||
`vitastor-cli rm-osd [--force] [--allow-data-loss] [--dry-run] <osd_id> [osd_id...]`
|
||||
`vitastor-cli rm-osd [-f|--force] [--allow-data-loss] [--allow-up] [--dry-run] <osd_id> [osd_id...]`
|
||||
|
||||
Remove metadata and configuration for specified OSD(s) from etcd.
|
||||
|
||||
Refuses to remove OSDs with data without `--force` and `--allow-data-loss`.
|
||||
Refuses to remove OSDs that are up or whose removal makes PGs degraded, offline or incomplete.
|
||||
|
||||
With `--dry-run` only checks if deletion is possible without data loss and
|
||||
redundancy degradation.
|
||||
* `-f|--force` - remove OSDs even if they are up or PGs become degraded or offline.
|
||||
* `--allow-data-loss` - remove OSDs even if PGs or objects become incomplete (DATA LOSS). Implies `--force`.
|
||||
* `--allow-up` - remove OSDs even if they are up.
|
||||
* `--dry-run` - only check if deletion is possible without data loss and
|
||||
redundancy degradation.
|
||||
|
||||
## osd-tree
|
||||
|
||||
@@ -354,7 +360,7 @@ host stump
|
||||
|
||||
## ls-osd
|
||||
|
||||
`vitastor-cli osds|ls-osd|osd-ls [-l|--long]`
|
||||
`vitastor-cli osds|ls-osds|ls-osd|osd-ls [-l|--long]`
|
||||
|
||||
Show current OSDs as list, optionally with I/O statistics if -l is specified.
|
||||
|
||||
@@ -409,8 +415,8 @@ Create a pool. Required parameters:
|
||||
|
||||
| <!-- --> | <!-- --> |
|
||||
|--------------------------|-----------------------------------------------------------------------------------------|
|
||||
| `-s R` or `--pg_size R` | Number of replicas for replicated pools |
|
||||
| `--ec N+K` | Number of data (N) and parity (K) chunks for erasure-coded pools |
|
||||
| `-s R` or `--pg_size R` | Number of replicas for replicated pools, from 1 to 64 |
|
||||
| `--ec N+K` | Number of data (N) and parity (K) chunks for erasure-coded pools, N+K from 3 to 64 |
|
||||
| `-n N` or `--pg_count N` | PG count for the new pool (start with 10*\<OSD count\>/pg_size rounded to a power of 2) |
|
||||
|
||||
Optional parameters:
|
||||
@@ -424,7 +430,7 @@ Optional parameters:
|
||||
| `--block_size 128k` | Put pool only on OSDs with this data block size |
|
||||
| `--bitmap_granularity 4k` | Put pool only on OSDs with this logical sector size |
|
||||
| `--immediate_commit none` | Put pool only on OSDs with this or larger immediate_commit (none < small < all) |
|
||||
| `--level_placement <rules>` | Use additional failure domain rules (example: "dc=112233") |
|
||||
| `--level_placement <rules>` | Use additional failure domain rules (example: "dc=112233", "" to remove) |
|
||||
| `--raw_placement <rules>` | Specify raw PG generation rules ([details](../config/pool.en.md#raw_placement)) |
|
||||
| `--local_reads primary` | Local read policy for replicated pools: primary, nearest or random |
|
||||
| `--primary_affinity_tags tags` | Prefer to put primary copies on OSDs with all specified tags |
|
||||
@@ -469,6 +475,8 @@ These, however, can still be modified with -f|--force.
|
||||
|
||||
See [create-pool](#create-pool) for parameter descriptions.
|
||||
|
||||
Renaming with --name fails if the new name is already taken by a different pool.
|
||||
|
||||
Examples:
|
||||
|
||||
`vitastor-cli modify-pool pool_A --name pool_B`
|
||||
@@ -507,7 +515,7 @@ the Vitastor authorization model.
|
||||
|
||||
## modify-user
|
||||
|
||||
`vitastor-cli modify-user --groups <group1,group2,...> <username>`
|
||||
`vitastor-cli modify-user|user-modify --groups <group1,group2,...> <username>`
|
||||
|
||||
Create or update a user with the given name (matching TLS certificate CN).
|
||||
|
||||
|
||||
@@ -170,7 +170,7 @@ vitastor-cli snap-create [ОПЦИИ] <image>@<snapshot>
|
||||
|
||||
## modify
|
||||
|
||||
`vitastor-cli modify <name> [--rename <new-name>] [--resize <size>] [--readonly | --readwrite] [-f|--force] [--down-ok]`
|
||||
`vitastor-cli modify <name> [--rename <new-name> [--with-snapshots]] [--resize <size>] [--readonly | --readwrite] [-f|--force] [--down-ok]`
|
||||
|
||||
Изменить размер, имя образа или флаг "только для чтения". Снимать флаг "только для чтения"
|
||||
и уменьшать размер образов, у которых есть дочерние клоны, без `--force` нельзя.
|
||||
@@ -181,6 +181,8 @@ vitastor-cli snap-create [ОПЦИИ] <image>@<snapshot>
|
||||
* `--deleted 1|0` - Установить/снять флаг "образ удалён" (устанавливается при незавершённом удалении).
|
||||
* `-f|--force` - Разрешить уменьшение или перевод в чтение-запись образа, у которого есть клоны.
|
||||
* `--down-ok` - Разрешить уменьшение, даже если часть данных останется неудалённой на недоступных OSD.
|
||||
* `--with-snapshots` - Переименовать также снимки `<name>@*` в `<new-name>@*`, по одному после образа.
|
||||
Если какой-либо `<new-name>@*` уже есть, переименование отклоняется.
|
||||
* `--enc-key HEX` - Изменить ключ шифрования образа (разрешено только с `--force`).
|
||||
* `--owner USERNAME` - Изменить владельца образа.
|
||||
* `--owner-group NAME` - Изменить имя группы владельцев образа.
|
||||
@@ -203,6 +205,7 @@ vitastor-cli dd [iimg=<image> | if=<file>] [oimg=<image> | of=<file>] [bs=1M] \
|
||||
| `iimg=<image>` | Копировать из образа Vitastor `<image>` |
|
||||
| `if=<file>` | Копировать из файла `<file>` |
|
||||
| `oimg=<image>` | Копировать в образ Vitastor `<image>` |
|
||||
| `opool=<pool>` | Пул для создания выходного образа, если он не существует |
|
||||
| `of=<file>` | Копировать в файл `<file>` |
|
||||
| `bs=1M` | Задать размер блока копирования |
|
||||
| `count=N` | Копировать не более N блоков. Если N заканчивается на B - то N байт. |
|
||||
@@ -238,8 +241,8 @@ vitastor-cli dd [iimg=<image> | if=<file>] [oimg=<image> | of=<file>] [bs=1M] \
|
||||
у удаляемой цепочки есть только один дочерний образ, содержащий небольшой объём данных.
|
||||
В этом случае дочерний образ вливается в родительский и удаляется, а родительский
|
||||
переименовывается в дочерний.
|
||||
* `--exact` - удалить все образы с именами, подходящими под переданные glob-шаблоны.
|
||||
* `--matching` - удалить все образы с точно заданными именами.
|
||||
* `--exact` - удалить все образы с точно заданными именами.
|
||||
* `--matching` - удалить все образы с именами, подходящими под переданные glob-шаблоны.
|
||||
* `--down-ok` - продолжать удаление/слияние, даже если часть данных останется неудалённой на недоступных OSD.
|
||||
|
||||
## flatten
|
||||
@@ -301,7 +304,7 @@ vitastor-cli dd [iimg=<image> | if=<file>] [oimg=<image> | of=<file>] [bs=1M] \
|
||||
|
||||
## fix
|
||||
|
||||
`vitastor-cli fix [--objects <объекты>] [--bad-osds <osds>] [--part <номер>] [--check no]`
|
||||
`vitastor-cli fix [--objects <объекты>] --bad-osds <osds> [--part <номер>] [--check no]`
|
||||
|
||||
Исправить неконсистентные (неоднозначные) объекты путём удаления части копий.
|
||||
|
||||
@@ -312,9 +315,9 @@ vitastor-cli dd [iimg=<image> | if=<file>] [oimg=<image> | of=<file>] [bs=1M] \
|
||||
Простой формат: 0x<инод>:0x<смещение> <любой разделитель> 0x<инод>:0x<смещение> ...
|
||||
Формат JSON: [{"inode":"0x<инод>","stripe":"0x<смещение>"},...]
|
||||
--bad-osds <osds>
|
||||
Удалить неконсистентные копии/части объектов с данных OSD, таким образом
|
||||
признавая потерю этих копий и позволяя Vitastor-у восстановить объекты из
|
||||
других копий.
|
||||
Обязательная опция. Удалить неконсистентные копии/части объектов с данных
|
||||
OSD, таким образом признавая потерю этих копий и позволяя Vitastor-у
|
||||
восстановить объекты из других копий.
|
||||
--part <номер>
|
||||
Удалить только части EC с заданным номером (от 0 до pg_size-1). Нужно только
|
||||
в редких граничных случаях, когда один и тот же OSD содержит несколько частей
|
||||
@@ -333,14 +336,19 @@ vitastor-cli dd [iimg=<image> | if=<file>] [oimg=<image> | of=<file>] [bs=1M] \
|
||||
|
||||
## rm-osd
|
||||
|
||||
`vitastor-cli rm-osd [--force] [--allow-data-loss] [--dry-run] <osd_id> [osd_id...]`
|
||||
`vitastor-cli rm-osd [-f|--force] [--allow-data-loss] [--allow-up] [--dry-run] <osd_id> [osd_id...]`
|
||||
|
||||
Удалить метаданные и конфигурацию для заданных OSD из etcd.
|
||||
|
||||
Отказывается удалять OSD с данными без опций `--force` и `--allow-data-loss`.
|
||||
Отказывается удалять работающие OSD, а также OSD, после удаления которых PG станут
|
||||
деградированными, недоступными (offline) или неполными (incomplete).
|
||||
|
||||
С опцией `--dry-run` только проверяет, возможно ли удаление без потери данных и деградации
|
||||
избыточности.
|
||||
* `-f|--force` - удалить OSD, даже если они работают или PG станут деградированными или недоступными.
|
||||
* `--allow-data-loss` - удалить OSD, даже если PG или объекты станут неполными (ПОТЕРЯ ДАННЫХ).
|
||||
Включает действие `--force`.
|
||||
* `--allow-up` - удалить OSD, даже если они работают.
|
||||
* `--dry-run` - только проверить, возможно ли удаление без потери данных и деградации
|
||||
избыточности.
|
||||
|
||||
## osd-tree
|
||||
|
||||
@@ -372,7 +380,7 @@ host stump
|
||||
|
||||
## ls-osd
|
||||
|
||||
`vitastor-cli osds|ls-osd|osd-ls [-l|--long]`
|
||||
`vitastor-cli osds|ls-osds|ls-osd|osd-ls [-l|--long]`
|
||||
|
||||
Показать список OSD, со статистикой ввода-вывода, если установлено -l.
|
||||
|
||||
@@ -402,7 +410,7 @@ OSD PARENT UP SIZE USED% TAGS WEIGHT BLOCK BITMAP
|
||||
|
||||
## pg-list
|
||||
|
||||
`vitastor-cli pg-list|pg-ls|list-pg|ls-pg|ls-pgs [OPTIONS] [state1+state2] [^state3] [...]`
|
||||
`vitastor-cli pg-list|pg-ls|list-pg|ls-pg|ls-pgs|pgs [OPTIONS] [state1+state2] [^state3] [...]`
|
||||
|
||||
Вывести список PG с состояними, удовлетворяющими любому из переданных фильтров (^ или !
|
||||
в начале фильтра означает отрицание). Опции:
|
||||
@@ -428,8 +436,8 @@ OSD PARENT UP SIZE USED% TAGS WEIGHT BLOCK BITMAP
|
||||
|
||||
| <!-- --> | <!-- --> |
|
||||
|---------------------------|-----------------------------------------------------------------------------------------------|
|
||||
| `-s R` или `--pg_size R` | Число копий данных для реплицированных пулов |
|
||||
| `--ec N+K` | Число частей данных (N) и чётности (K) для пулов с кодами коррекции ошибок |
|
||||
| `-s R` или `--pg_size R` | Число копий данных для реплицированных пулов, от 1 до 64 |
|
||||
| `--ec N+K` | Число частей данных (N) и чётности (K) для пулов с кодами коррекции ошибок, N+K от 3 до 64 |
|
||||
| `-n N` или `--pg_count N` | Число PG для нового пула (начните с 10*\<число OSD\>/pg_size, округлённого до степени двойки) |
|
||||
|
||||
Необязательные параметры:
|
||||
@@ -443,7 +451,7 @@ OSD PARENT UP SIZE USED% TAGS WEIGHT BLOCK BITMAP
|
||||
| `--block_size 128k` | ...только OSD с данным размером блока |
|
||||
| `--bitmap_granularity 4k` | ...только OSD с данным размером логического сектора |
|
||||
| `--immediate_commit none` | ...только OSD с этим или большим immediate_commit (none < small < all) |
|
||||
| `--level_placement <rules>` | Задать правила дополнительных доменов отказа (пример: "dc=112233") |
|
||||
| `--level_placement <rules>` | Задать правила дополнительных доменов отказа (пример: "dc=112233", "" — удалить) |
|
||||
| `--raw_placement <rules>` | Задать низкоуровневые правила генерации PG ([детали](../config/pool.ru.md#raw_placement)) |
|
||||
| `--local_reads primary` | Политика локальных чтений для реплик: primary, nearest или random |
|
||||
| `--primary_affinity_tags tags` | Предпочитать OSD со всеми данными тегами для роли первичных |
|
||||
@@ -486,6 +494,8 @@ OSD PARENT UP SIZE USED% TAGS WEIGHT BLOCK BITMAP
|
||||
|
||||
Описания параметров смотрите в [create-pool](#create-pool).
|
||||
|
||||
Переименование с --name запрещается, если новое название уже занято другим пулом.
|
||||
|
||||
Примеры:
|
||||
|
||||
`vitastor-cli modify-pool pool_A --name pool_B`
|
||||
@@ -526,7 +536,7 @@ OSD PARENT UP SIZE USED% TAGS WEIGHT BLOCK BITMAP
|
||||
|
||||
## modify-user
|
||||
|
||||
`vitastor-cli modify-user --groups <group1,group2,...> <username>`
|
||||
`vitastor-cli modify-user|user-modify --groups <group1,group2,...> <username>`
|
||||
|
||||
Создать или изменить пользователя с указанным именем (совпадающим с CN TLS-сертификата).
|
||||
|
||||
|
||||
@@ -64,6 +64,8 @@ const etcd_tree = {
|
||||
osd_out_time: 600, // seconds. min: 0
|
||||
placement_levels: { datacenter: 1, rack: 2, host: 3, osd: 4, ... },
|
||||
use_old_pg_combinator: false,
|
||||
sticky_primaries: false,
|
||||
primary_rebalance_time: 300, // seconds. 0 disables
|
||||
osd_backfillfull_ratio: 0.99,
|
||||
mon_metrics_path: '/prometheus',
|
||||
mon_healthcheck_path: '/healthcheck',
|
||||
|
||||
@@ -368,6 +368,10 @@ async function optimize_change({ prev_pgs: prev_int_pgs, osd_weights, combinator
|
||||
const int_pgs = make_int_pgs(weights, pg_count);
|
||||
// Align them with most similar previous PGs
|
||||
const new_pgs = align_pgs(prev_int_pgs, int_pgs);
|
||||
if (ordered)
|
||||
{
|
||||
align_positions(prev_int_pgs, new_pgs, combinator);
|
||||
}
|
||||
let differs = 0, osd_differs = 0;
|
||||
for (let i = 0; i < pg_count; i++)
|
||||
{
|
||||
@@ -447,6 +451,54 @@ function print_change_stats(retval, detailed)
|
||||
);
|
||||
}
|
||||
|
||||
// EC chunk number = position: items of the previous set keep their positions, new items fill
|
||||
// the vacated ones, rotated by PG number. Items may repeat (folded failure domains)
|
||||
function align_positions(prev_int_pgs, new_pgs, combinator)
|
||||
{
|
||||
for (let i = 0; i < new_pgs.length; i++)
|
||||
{
|
||||
const prev = prev_int_pgs[i], pg = new_pgs[i];
|
||||
if (prev.length != pg.length)
|
||||
continue;
|
||||
const old_pos = {};
|
||||
for (let j = 0; j < prev.length; j++)
|
||||
{
|
||||
if (prev[j] != NO_OSD)
|
||||
{
|
||||
old_pos[prev[j]] = old_pos[prev[j]] || [];
|
||||
old_pos[prev[j]].push(j);
|
||||
}
|
||||
}
|
||||
// Place pg's own items: prev read from etcd may hold OSD numbers where pg holds strings
|
||||
const kept = pg.map(() => null), fresh = [];
|
||||
for (const osd of pg)
|
||||
{
|
||||
if (old_pos[osd] && old_pos[osd].length)
|
||||
kept[old_pos[osd].shift()] = osd;
|
||||
else
|
||||
fresh.push(osd);
|
||||
}
|
||||
const n = fresh.length || 1;
|
||||
const rotated = (r) =>
|
||||
{
|
||||
const f = [ ...fresh.slice(r), ...fresh.slice(0, r) ];
|
||||
return kept.map(osd => (osd === null ? f.shift() : osd));
|
||||
};
|
||||
// A positional placement rule may forbid an order: try every rotation of the new items
|
||||
let found = null;
|
||||
for (let r = 0; r < n && !found; r++)
|
||||
{
|
||||
const cand = rotated((i+r) % n);
|
||||
if (combinator.check_combinations([ cand ]).length)
|
||||
found = cand;
|
||||
}
|
||||
// Sets with NO_OSD never pass the check: then any order is as good as the optimizer's.
|
||||
// Otherwise keep the optimizer's order if no rotation fits
|
||||
if (found || !combinator.check_combinations([ pg ]).length)
|
||||
new_pgs[i] = found || rotated(i % n);
|
||||
}
|
||||
}
|
||||
|
||||
function align_pgs(prev_int_pgs, int_pgs)
|
||||
{
|
||||
const aligned_pgs = [];
|
||||
|
||||
@@ -103,6 +103,56 @@ async function run()
|
||||
unfolded_res.space = unfolded_res.pg_effsize * LPOptimizer.pg_list_space_efficiency(unfolded_res.int_pgs, osd_weights, 0, 1);
|
||||
LPOptimizer.print_change_stats(unfolded_res, false);
|
||||
assert.equal(res.space, 100, 'Initial distribution');
|
||||
|
||||
await test_ordered_repeated_hosts();
|
||||
await test_ordered_dc_rule();
|
||||
}
|
||||
|
||||
function kept_positions(prev, pgs)
|
||||
{
|
||||
return pgs.every((pg, i) => prev[i].every((osd, j) => !pg.includes(osd) || pg[j] == osd));
|
||||
}
|
||||
|
||||
async function test_ordered_repeated_hosts()
|
||||
{
|
||||
console.log('\n32 PGs, 2 OSDs per host (host=112233), ordered: remove hosts 5 and 6');
|
||||
const nodes = [];
|
||||
for (let i = 1; i <= 12; i++)
|
||||
nodes.push({ id: i, level: 'osd', size: 1, parent: 'host'+(1+(0|((i-1)/2))) });
|
||||
for (let i = 1; i <= 6; i++)
|
||||
nodes.push({ id: 'host'+i, level: 'host' });
|
||||
const rules = DSL.parse_level_indexes({ host: '112233' }, [ 'host', 'osd' ]);
|
||||
const folded = fold_failure_domains(nodes, rules).nodes;
|
||||
const weights = folded.reduce((a, c) => { if (Number(c.id)) { a[c.id] = c.size; } return a; }, {});
|
||||
let res = await LPOptimizer.optimize_initial({ osd_weights: weights,
|
||||
combinator: new DSL.RuleCombinator(folded, rules, 10000, false), pg_size: 6, pg_count: 32, ordered: false });
|
||||
const prev = res.int_pgs;
|
||||
const left = folded.filter(n => n.name != 'host5' && n.name != 'host6');
|
||||
const combinator = new DSL.RuleCombinator(left, rules, 10000, false);
|
||||
res = await LPOptimizer.optimize_change({ prev_pgs: prev, combinator: combinator, pg_size: 6, ordered: true,
|
||||
osd_weights: left.reduce((a, c) => { if (Number(c.id)) { a[c.id] = c.size; } return a; }, {}) });
|
||||
LPOptimizer.print_change_stats(res, false);
|
||||
assert.equal(combinator.check_combinations(res.int_pgs).length, 32, 'New sets follow the placement rule');
|
||||
assert(kept_positions(prev, res.int_pgs), 'Surviving hosts keep their positions');
|
||||
}
|
||||
|
||||
async function test_ordered_dc_rule()
|
||||
{
|
||||
console.log('\n32 PGs, 2 DCs x 3 hosts, dc=1122: remove one host in each DC');
|
||||
const nodes = [ { id: 'dc1', level: 'dc' }, { id: 'dc2', level: 'dc' } ];
|
||||
for (let h = 1; h <= 6; h++)
|
||||
nodes.push({ id: 'host'+h, level: 'host', parent: h <= 3 ? 'dc1' : 'dc2' }, { id: h, level: 'osd', size: 1, parent: 'host'+h });
|
||||
const rules = DSL.parse_level_indexes({ dc: '1122', host: '1234' }, [ 'dc', 'host', 'osd' ]);
|
||||
let res = await LPOptimizer.optimize_initial({ osd_weights: { 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1 },
|
||||
combinator: new DSL.RuleCombinator(nodes, rules, 10000, false), pg_size: 4, pg_count: 32, ordered: false });
|
||||
const prev = res.int_pgs;
|
||||
const left = nodes.filter(n => ![ 1, 6, 'host1', 'host6' ].includes(n.id));
|
||||
const combinator = new DSL.RuleCombinator(left, rules, 10000, false);
|
||||
res = await LPOptimizer.optimize_change({ prev_pgs: prev, combinator: combinator, pg_size: 4, ordered: true,
|
||||
osd_weights: { 2: 1, 3: 1, 4: 1, 5: 1 } });
|
||||
LPOptimizer.print_change_stats(res, false);
|
||||
assert.equal(combinator.check_combinations(res.int_pgs).length, 32, 'New sets follow the DC rule');
|
||||
assert(kept_positions(prev, res.int_pgs), 'Surviving OSDs keep their positions under a positional rule');
|
||||
}
|
||||
|
||||
run().catch(console.error);
|
||||
|
||||
@@ -29,6 +29,10 @@ async function run()
|
||||
LPOptimizer.print_change_stats(res, false);
|
||||
assert(res.space == 2, 'Redistribution after OSD removal');
|
||||
|
||||
await test_ordered_remove_hosts();
|
||||
await test_ordered_undersized();
|
||||
await test_ordered_two_new_items();
|
||||
|
||||
console.log('\n16 PGs, size=3, ordered');
|
||||
res = await LPOptimizer.optimize_initial(compat({ osd_tree, pg_size: 3, pg_count: 16, ordered: true }));
|
||||
LPOptimizer.print_change_stats(res, false);
|
||||
@@ -39,6 +43,58 @@ async function run()
|
||||
assert(res.space >= 3*14/16 && res.osd_differs < 8, 'Redistribution');
|
||||
}
|
||||
|
||||
function host_tree(hosts)
|
||||
{
|
||||
const tree = {};
|
||||
for (let h = 1; h <= hosts; h++)
|
||||
tree[h*100] = { [h]: 1 };
|
||||
return tree;
|
||||
}
|
||||
|
||||
function kept_positions(prev, pgs)
|
||||
{
|
||||
return pgs.every((pg, i) => prev[i].every((osd, j) => !pg.includes(osd) || pg[j] == osd));
|
||||
}
|
||||
|
||||
async function test_ordered_remove_hosts()
|
||||
{
|
||||
console.log('\n32 PGs, 6 hosts, size=4, ordered: remove hosts 5 and 6');
|
||||
let res = await LPOptimizer.optimize_initial(compat({ osd_tree: host_tree(6), pg_size: 4, pg_count: 32, ordered: true }));
|
||||
const prev = res.int_pgs;
|
||||
// OSD numbers as in etcd after an osd_set rewrite: the result keeps the optimizer's own items
|
||||
res = await LPOptimizer.optimize_change(compat({ prev_pgs: prev.map(pg => pg.map(Number)), osd_tree: host_tree(4), pg_size: 4, ordered: true }));
|
||||
LPOptimizer.print_change_stats(res, false);
|
||||
assert(kept_positions(prev, res.int_pgs), 'Surviving OSDs keep their positions');
|
||||
assert(res.int_pgs.every(pg => pg.every(osd => typeof osd == 'string')), 'Items are the optimizer\'s strings');
|
||||
assert(res.int_pgs.every(pg => pg.slice().sort().join() == '1,2,3,4'), 'Every PG has all 4 hosts left');
|
||||
}
|
||||
|
||||
async function test_ordered_undersized()
|
||||
{
|
||||
console.log('\n32 PGs, 6 hosts, size=6, ordered: remove host 6 (undersized)');
|
||||
let res = await LPOptimizer.optimize_initial(compat({ osd_tree: host_tree(6), pg_size: 6, pg_count: 32, ordered: true }));
|
||||
const prev = res.int_pgs;
|
||||
res = await LPOptimizer.optimize_change(compat({ prev_pgs: prev, osd_tree: host_tree(5), pg_size: 6, ordered: true }));
|
||||
assert(kept_positions(prev, res.int_pgs), 'Undersized PGs: surviving OSDs keep their positions');
|
||||
}
|
||||
|
||||
async function test_ordered_two_new_items()
|
||||
{
|
||||
console.log('\n32 PGs, 7 hosts, size=6, ordered: remove hosts 6 and 7 (a new host and NO_OSD per PG)');
|
||||
let res = await LPOptimizer.optimize_initial(compat({ osd_tree: host_tree(7), pg_size: 6, pg_count: 32, ordered: true }));
|
||||
const prev = res.int_pgs;
|
||||
res = await LPOptimizer.optimize_change(compat({ prev_pgs: prev, osd_tree: host_tree(5), pg_size: 6, ordered: true }));
|
||||
assert(kept_positions(prev, res.int_pgs), 'Two new items per PG: surviving OSDs keep their positions');
|
||||
const z_first = new Set();
|
||||
for (let i = 0; i < res.int_pgs.length; i++)
|
||||
{
|
||||
const vacated = [ prev[i].indexOf('6'), prev[i].indexOf('7') ].sort((a, b) => a-b);
|
||||
if (vacated[0] >= 0)
|
||||
z_first.add(res.int_pgs[i][vacated[0]] == 'Z');
|
||||
}
|
||||
assert(z_first.size == 2, 'Two new items per PG: rotated over the vacated positions');
|
||||
}
|
||||
|
||||
function assert(cond, txt)
|
||||
{
|
||||
if (!cond)
|
||||
|
||||
72
mon/mon.js
72
mon/mon.js
@@ -16,7 +16,7 @@ const stableStringify = require('./stable-stringify.js');
|
||||
const { scale_pg_history } = require('./pg_utils.js');
|
||||
const { get_osd_tree } = require('./osd_tree.js');
|
||||
const { b64, de64, local_ips } = require('./utils.js');
|
||||
const { recheck_primary, save_new_pgs_txn, generate_pool_pgs } = require('./pg_gen.js');
|
||||
const { recheck_primary, save_new_pgs_txn, generate_pool_pgs, count_primaries } = require('./pg_gen.js');
|
||||
|
||||
class Mon
|
||||
{
|
||||
@@ -130,6 +130,8 @@ class Mon
|
||||
await this.load_config();
|
||||
await this.get_lease();
|
||||
await this.etcd.become_master();
|
||||
// A standby saw no changes: the primary rebalance waits from the takeover
|
||||
this.last_unclean_time = Date.now();
|
||||
await this.load_cluster_state();
|
||||
await this.etcd.start_watcher(this.config.etcd_mon_retries);
|
||||
this.watcher_active = true;
|
||||
@@ -144,6 +146,8 @@ class Mon
|
||||
}
|
||||
}
|
||||
await this.recheck_pgs();
|
||||
// Arms the primary rebalance timer when this monitor takes over a clean cluster
|
||||
await this.save_last_clean();
|
||||
this.schedule_update_stats();
|
||||
}
|
||||
|
||||
@@ -199,6 +203,9 @@ class Mon
|
||||
{
|
||||
this.config.osd_out_time = 600; // 10 minutes by default
|
||||
}
|
||||
// With sticky_primaries, primaries are evened out after this number of seconds without changes
|
||||
this.config.primary_rebalance_time = this.config.primary_rebalance_time == null
|
||||
? 300 : (Number(this.config.primary_rebalance_time) || 0);
|
||||
}
|
||||
|
||||
on_message(msg)
|
||||
@@ -217,6 +224,7 @@ class Mon
|
||||
{
|
||||
stats_changed = true;
|
||||
changed = true;
|
||||
this.last_unclean_time = Date.now();
|
||||
}
|
||||
else if (key.substr(0, 11) == '/osd/stats/' || key.substr(0, 9) == '/pgstats/' || key.substr(0, 16) == '/osd/inodestats/')
|
||||
{
|
||||
@@ -275,6 +283,38 @@ class Mon
|
||||
}
|
||||
}
|
||||
|
||||
// With sticky_primaries, even out primaries when all PGs stay clean and no OSD goes up or down
|
||||
// for primary_rebalance_time
|
||||
schedule_primary_rebalance()
|
||||
{
|
||||
if (this.stopped || this.primary_rebalance_timer || !this.all_pgs_clean || !this.config.sticky_primaries ||
|
||||
!(this.config.primary_rebalance_time > 0))
|
||||
{
|
||||
return;
|
||||
}
|
||||
const wait = this.last_unclean_time + this.config.primary_rebalance_time*1000 - Date.now();
|
||||
this.primary_rebalance_timer = setTimeout(() =>
|
||||
{
|
||||
this.primary_rebalance_timer = null;
|
||||
if (this.primary_rebalance_calm())
|
||||
{
|
||||
this.primary_rebalance_due = true;
|
||||
this.schedule_recheck();
|
||||
}
|
||||
else
|
||||
{
|
||||
this.schedule_primary_rebalance();
|
||||
}
|
||||
}, wait > 0 ? wait : 0);
|
||||
}
|
||||
|
||||
// Checked again when the pass runs: an OSD may go down or the option be set to 0 after the timer fires
|
||||
primary_rebalance_calm()
|
||||
{
|
||||
return this.all_pgs_clean && this.config.primary_rebalance_time > 0 &&
|
||||
Date.now() >= this.last_unclean_time + this.config.primary_rebalance_time*1000;
|
||||
}
|
||||
|
||||
async save_last_clean()
|
||||
{
|
||||
if (this.save_last_clean_running)
|
||||
@@ -285,6 +325,7 @@ class Mon
|
||||
this.save_last_clean_running = true;
|
||||
// last_clean_pgs is used to avoid extra data move when observing a series of changes in the cluster
|
||||
const new_clean_pgs = { items: {} };
|
||||
let all_clean = true;
|
||||
// eslint-disable-next-line indent
|
||||
next_pool:
|
||||
for (const pool_id in this.state.config.pools)
|
||||
@@ -302,18 +343,25 @@ class Mon
|
||||
!(this.state.pg.state[pool_id][pg_num].state instanceof Array))
|
||||
{
|
||||
// Unclean
|
||||
all_clean = false;
|
||||
continue next_pool;
|
||||
}
|
||||
let st = this.state.pg.state[pool_id][pg_num].state.join(',');
|
||||
if (st != 'active' && st != 'active,left_on_dead' && st != 'left_on_dead,active')
|
||||
{
|
||||
// Unclean
|
||||
all_clean = false;
|
||||
continue next_pool;
|
||||
}
|
||||
}
|
||||
new_clean_pgs.items[pool_id] = this.state.pg.config.items[pool_id];
|
||||
}
|
||||
this.state.history.last_clean_pgs = new_clean_pgs;
|
||||
this.all_pgs_clean = all_clean;
|
||||
if (all_clean)
|
||||
this.schedule_primary_rebalance();
|
||||
else
|
||||
this.last_unclean_time = Date.now();
|
||||
await this.etcd.etcd_call('/kv/txn', {
|
||||
success: [ { requestPut: {
|
||||
key: b64(this.config.etcd_prefix+'/history/last_clean_pgs'),
|
||||
@@ -373,6 +421,11 @@ class Mon
|
||||
clearTimeout(this.save_last_clean_timer);
|
||||
this.save_last_clean_timer = null;
|
||||
}
|
||||
if (this.primary_rebalance_timer)
|
||||
{
|
||||
clearTimeout(this.primary_rebalance_timer);
|
||||
this.primary_rebalance_timer = null;
|
||||
}
|
||||
if (this.next_recheck_timer)
|
||||
{
|
||||
clearTimeout(this.next_recheck_timer);
|
||||
@@ -513,6 +566,13 @@ class Mon
|
||||
return;
|
||||
}
|
||||
this.recheck_pgs_active = true;
|
||||
const rebalance_primaries = this.primary_rebalance_due && this.primary_rebalance_calm();
|
||||
if (this.primary_rebalance_due && !rebalance_primaries)
|
||||
this.schedule_primary_rebalance();
|
||||
this.primary_rebalance_due = false;
|
||||
// The next pass waits again, also before the moved PGs report their state
|
||||
if (rebalance_primaries)
|
||||
this.last_unclean_time = Date.now();
|
||||
// Take configuration and state, check it against the stored configuration hash
|
||||
// Recalculate PGs and save them to etcd if the configuration is changed
|
||||
// FIXME: Do not change anything if the distribution is good and random enough and no PGs are degraded
|
||||
@@ -525,6 +585,8 @@ class Mon
|
||||
const tree_hash = sha1hex(stableStringify(tree_cfg));
|
||||
if (this.state.pg.config.hash != tree_hash)
|
||||
{
|
||||
if (rebalance_primaries)
|
||||
this.schedule_primary_rebalance();
|
||||
// Something has changed
|
||||
console.log('Pool configuration or OSD tree changed, re-optimizing');
|
||||
// First re-optimize PGs, but don't look at history yet
|
||||
@@ -564,7 +626,7 @@ class Mon
|
||||
else
|
||||
{
|
||||
// Nothing changed, but we still want to recheck the distribution of primaries
|
||||
let new_pg_config = recheck_primary(this.state, this.config, up_osds, osd_tree);
|
||||
let new_pg_config = recheck_primary(this.state, this.config, up_osds, osd_tree, rebalance_primaries);
|
||||
if (new_pg_config)
|
||||
{
|
||||
const ok = await this.save_pg_config(new_pg_config);
|
||||
@@ -573,6 +635,7 @@ class Mon
|
||||
else
|
||||
{
|
||||
console.log('Someone changed PG configuration while we also tried to change it. Retrying in '+this.config.mon_change_timeout+' ms');
|
||||
this.primary_rebalance_due = this.primary_rebalance_due || rebalance_primaries;
|
||||
this.schedule_recheck();
|
||||
}
|
||||
}
|
||||
@@ -613,6 +676,7 @@ class Mon
|
||||
}
|
||||
}
|
||||
const new_pg_config = JSON.parse(JSON.stringify(this.state.pg.config));
|
||||
const primary_counts = this.config.sticky_primaries ? count_primaries(new_pg_config) : null;
|
||||
for (const pool_id in (new_pg_config||{}).items||{})
|
||||
{
|
||||
if (!this.state.config.pools[pool_id])
|
||||
@@ -627,7 +691,7 @@ class Mon
|
||||
key: b64(this.config.etcd_prefix+'/pool/stats/'+pool_id),
|
||||
} });
|
||||
save_new_pgs_txn(new_pg_config, etcd_request, this.state, this.config.etcd_prefix,
|
||||
this.etcd_watch_revision, pool_id, up_osds, osd_tree, prev_pgs, [], []);
|
||||
this.etcd_watch_revision, pool_id, up_osds, osd_tree, prev_pgs, [], [], primary_counts);
|
||||
}
|
||||
}
|
||||
for (const pool_res of results)
|
||||
@@ -670,7 +734,7 @@ class Mon
|
||||
value: b64(JSON.stringify(stats)),
|
||||
} });
|
||||
save_new_pgs_txn(new_pg_config, etcd_request, this.state, this.config.etcd_prefix,
|
||||
this.etcd_watch_revision, pool_id, up_osds, osd_tree, real_prev_pgs, pool_res.pgs, pg_history);
|
||||
this.etcd_watch_revision, pool_id, up_osds, osd_tree, real_prev_pgs, pool_res.pgs, pg_history, primary_counts);
|
||||
}
|
||||
new_pg_config.hash = tree_hash;
|
||||
const { backfillfull_pools, backfillfull_osds } = sum_object_counts(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "vitastor-mon",
|
||||
"version": "3.1.0",
|
||||
"version": "3.2.3",
|
||||
"description": "Vitastor SDS monitor service",
|
||||
"main": "mon-main.js",
|
||||
"scripts": {
|
||||
|
||||
@@ -10,7 +10,9 @@ const { scale_pg_count } = require('./pg_utils.js');
|
||||
const { make_hier_tree, filter_osds_by_root_node,
|
||||
filter_osds_by_tags, filter_osds_by_block_layout, get_affinity_osds } = require('./osd_tree.js');
|
||||
|
||||
function pick_primary(pool_id, pg_num, pool_config, osd_set, up_osds, aff_osds)
|
||||
// cur_primary and counts ({ osd_num: primaries } over all pools) are only passed with sticky_primaries
|
||||
// gained ({ osd_num: true } of OSDs given a primary in this pass) is only passed when the cluster is calm
|
||||
function pick_primary(pool_id, pg_num, pool_config, osd_set, up_osds, aff_osds, cur_primary = 0, counts = null, gained = null)
|
||||
{
|
||||
let alive_set;
|
||||
if (pool_config.scheme === 'replicated')
|
||||
@@ -38,12 +40,55 @@ function pick_primary(pool_id, pg_num, pool_config, osd_set, up_osds, aff_osds)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
return alive_set[pg_num % alive_set.length];
|
||||
if (!counts)
|
||||
{
|
||||
return alive_set[pg_num % alive_set.length];
|
||||
}
|
||||
// The candidate with the fewest primaries, ties by PG number
|
||||
let best = 0;
|
||||
for (let i = 0; i < alive_set.length; i++)
|
||||
{
|
||||
const osd_num = alive_set[(pg_num + i) % alive_set.length];
|
||||
if (!best || (counts[osd_num]||0) < (counts[best]||0))
|
||||
{
|
||||
best = osd_num;
|
||||
}
|
||||
}
|
||||
// Moving a primary restarts the PG on both OSDs: keep a live one while it is a candidate, unless the cluster
|
||||
// is calm and it has at least 2 primaries more than the best one, which gets at most one new PG per pass
|
||||
if (alive_set.includes(cur_primary) && (!gained || gained[best] || (counts[cur_primary]||0) <= (counts[best]||0)+1))
|
||||
{
|
||||
return cur_primary;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
function recheck_primary(state, global_config, up_osds, osd_tree)
|
||||
function count_primaries(pg_config)
|
||||
{
|
||||
const counts = {};
|
||||
for (const pool_id in (pg_config||{}).items||{})
|
||||
{
|
||||
for (const pg_num in pg_config.items[pool_id])
|
||||
{
|
||||
move_primary(counts, 0, pg_config.items[pool_id][pg_num].primary);
|
||||
}
|
||||
}
|
||||
return counts;
|
||||
}
|
||||
|
||||
function move_primary(counts, from, to)
|
||||
{
|
||||
if (counts && from)
|
||||
counts[from]--;
|
||||
if (counts && to)
|
||||
counts[to] = (counts[to]||0) + 1;
|
||||
}
|
||||
|
||||
function recheck_primary(state, global_config, up_osds, osd_tree, rebalance = false)
|
||||
{
|
||||
let new_pg_config;
|
||||
const counts = global_config.sticky_primaries ? count_primaries(state.pg.config) : null;
|
||||
const gained = counts && rebalance ? {} : null;
|
||||
for (const pool_id in state.config.pools)
|
||||
{
|
||||
const pool_cfg = state.config.pools[pool_id];
|
||||
@@ -62,9 +107,13 @@ function recheck_primary(state, global_config, up_osds, osd_tree)
|
||||
const pg_cfg = state.pg.config.items[pool_id][pg_num];
|
||||
if (pg_cfg)
|
||||
{
|
||||
const new_primary = pick_primary(pool_id, pg_num, state.config.pools[pool_id], pg_cfg.osd_set, up_osds, aff_osds);
|
||||
const new_primary = pick_primary(pool_id, pg_num, state.config.pools[pool_id], pg_cfg.osd_set,
|
||||
up_osds, aff_osds, pg_cfg.primary, counts, gained);
|
||||
if (pg_cfg.primary != new_primary)
|
||||
{
|
||||
move_primary(counts, pg_cfg.primary, new_primary);
|
||||
if (gained)
|
||||
gained[new_primary] = true;
|
||||
if (!new_pg_config)
|
||||
{
|
||||
new_pg_config = JSON.parse(JSON.stringify(state.pg.config));
|
||||
@@ -94,17 +143,28 @@ function recheck_primary(state, global_config, up_osds, osd_tree)
|
||||
return new_pg_config;
|
||||
}
|
||||
|
||||
function save_new_pgs_txn(save_to, request, state, etcd_prefix, etcd_watch_revision, pool_id, up_osds, osd_tree, prev_pgs, new_pgs, pg_history)
|
||||
// counts: from count_primaries() with sticky_primaries, shared by the calls for all pools of one change
|
||||
function save_new_pgs_txn(save_to, request, state, etcd_prefix, etcd_watch_revision, pool_id, up_osds, osd_tree, prev_pgs, new_pgs, pg_history, counts = null)
|
||||
{
|
||||
const aff_osds = get_affinity_osds(state.config.pools[pool_id] || {}, up_osds, osd_tree);
|
||||
const pg_items = {};
|
||||
const old_pgs = counts && (state.pg.config.items||{})[pool_id] || {};
|
||||
// PG numbers keep their meaning only while the PG count is the same
|
||||
const same_count = prev_pgs.length == new_pgs.length;
|
||||
if (!same_count)
|
||||
{
|
||||
for (const pg in old_pgs)
|
||||
move_primary(counts, old_pgs[pg].primary, 0);
|
||||
}
|
||||
new_pgs.map((osd_set, i) =>
|
||||
{
|
||||
osd_set = osd_set.map(osd_num => osd_num === LPOptimizer.NO_OSD ? 0 : osd_num);
|
||||
const cur_primary = same_count && (old_pgs[i+1]||{}).primary || 0;
|
||||
pg_items[i+1] = {
|
||||
osd_set,
|
||||
primary: pick_primary(pool_id, i+1, state.config.pools[pool_id], osd_set, up_osds, aff_osds),
|
||||
primary: pick_primary(pool_id, i+1, state.config.pools[pool_id], osd_set, up_osds, aff_osds, cur_primary, counts),
|
||||
};
|
||||
move_primary(counts, cur_primary, pg_items[i+1].primary);
|
||||
if (prev_pgs[i] && prev_pgs[i].join(' ') != osd_set.join(' ') &&
|
||||
prev_pgs[i].filter(osd_num => osd_num).length > 0)
|
||||
{
|
||||
@@ -266,6 +326,7 @@ function b64(str)
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
count_primaries,
|
||||
recheck_primary,
|
||||
save_new_pgs_txn,
|
||||
generate_pool_pgs,
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# A separate rule: when IMPORT fails, udev drops every other key of its rule, OWNER included
|
||||
SUBSYSTEM=="block", ENV{ID_PART_ENTRY_TYPE}=="e7009fac-a5a1-4d72-af72-53de13059903", \
|
||||
OWNER="vitastor", GROUP="vitastor"
|
||||
SUBSYSTEM=="block", ENV{ID_PART_ENTRY_TYPE}=="e7009fac-a5a1-4d72-af72-53de13059903", \
|
||||
OWNER="vitastor", GROUP="vitastor", \
|
||||
IMPORT{program}="/usr/bin/vitastor-disk udev $devnode", \
|
||||
SYMLINK+="vitastor/$env{VITASTOR_ALIAS}"
|
||||
|
||||
|
||||
14
mon/stats.js
14
mon/stats.js
@@ -9,6 +9,7 @@ function derive_osd_stats(st, prev, prev_diff)
|
||||
return diff;
|
||||
}
|
||||
const timediff = BigInt(st.time*1000 - prev.time*1000);
|
||||
// iops are in 1/1000 op/s until sum_op_stats() and sum_inode_stats() add them up
|
||||
for (const op in st.op_stats||{})
|
||||
{
|
||||
const pr = prev && prev.op_stats && prev.op_stats[op];
|
||||
@@ -17,7 +18,7 @@ function derive_osd_stats(st, prev, prev_diff)
|
||||
const b = c.bytes - BigInt(pr && pr.bytes||0);
|
||||
const us = c.usec - BigInt(pr && pr.usec||0);
|
||||
const n = c.count - BigInt(pr && pr.count||0);
|
||||
diff.op_stats[op] = { ...c, bps: n > 0 ? b*1000n/timediff : 0n, iops: n > 0 ? n*1000n/timediff : 0n, lat: n > 0 ? us/n : 0n };
|
||||
diff.op_stats[op] = { ...c, bps: n > 0 ? b*1000n/timediff : 0n, iops: n > 0 ? n*1000000n/timediff : 0n, lat: n > 0 ? us/n : 0n };
|
||||
}
|
||||
for (const op in st.subop_stats||{})
|
||||
{
|
||||
@@ -26,7 +27,7 @@ function derive_osd_stats(st, prev, prev_diff)
|
||||
c = { usec: BigInt(c.usec||0), count: BigInt(c.count||0) };
|
||||
const us = c.usec - BigInt(pr && pr.usec||0);
|
||||
const n = c.count - BigInt(pr && pr.count||0);
|
||||
diff.subop_stats[op] = { ...c, iops: n > 0 ? n*1000n/timediff : 0n, lat: n > 0 ? us/n : 0n };
|
||||
diff.subop_stats[op] = { ...c, iops: n > 0 ? n*1000000n/timediff : 0n, lat: n > 0 ? us/n : 0n };
|
||||
}
|
||||
for (const op in st.recovery_stats||{})
|
||||
{
|
||||
@@ -35,7 +36,7 @@ function derive_osd_stats(st, prev, prev_diff)
|
||||
c = { bytes: BigInt(c.bytes||0), count: BigInt(c.count||0) };
|
||||
const b = c.bytes - BigInt(pr && pr.bytes||0);
|
||||
const n = c.count - BigInt(pr && pr.count||0);
|
||||
diff.recovery_stats[op] = { ...c, bps: n > 0 ? b*1000n/timediff : 0n, iops: n > 0 ? n*1000n/timediff : 0n };
|
||||
diff.recovery_stats[op] = { ...c, bps: n > 0 ? b*1000n/timediff : 0n, iops: n > 0 ? n*1000000n/timediff : 0n };
|
||||
}
|
||||
diff.inode_stats = {};
|
||||
for (const pool_id in st.inode_stats||{})
|
||||
@@ -52,7 +53,7 @@ function derive_osd_stats(st, prev, prev_diff)
|
||||
const n = BigInt(c.count||0) - BigInt(pr && pr.count||0);
|
||||
inode_diff[op] = {
|
||||
bps: n > 0 ? (BigInt(c.bytes||0) - BigInt(pr && pr.bytes||0))*1000n/timediff : 0n,
|
||||
iops: n > 0 ? n*1000n/timediff : 0n,
|
||||
iops: n > 0 ? n*1000000n/timediff : 0n,
|
||||
lat: n > 0 ? (BigInt(c.usec||0) - BigInt(pr && pr.usec||0))/n : 0n,
|
||||
};
|
||||
}
|
||||
@@ -105,6 +106,10 @@ function sum_op_stats(all_osd, prev_stats)
|
||||
{
|
||||
sum_diff[type][op].lat /= sum_diff[type][op].iops;
|
||||
}
|
||||
if (sum_diff[type][op].iops)
|
||||
{
|
||||
sum_diff[type][op].iops = (sum_diff[type][op].iops + 999n) / 1000n;
|
||||
}
|
||||
}
|
||||
}
|
||||
return sum_diff;
|
||||
@@ -305,6 +310,7 @@ function sum_inode_stats(state, prev_stats)
|
||||
const op_st = inode_stats[pool_id][inode_num][op];
|
||||
if (op_st.lat)
|
||||
op_st.lat /= op_st.iops;
|
||||
op_st.iops = (op_st.iops + 999n) / 1000n;
|
||||
if (op_st.bps > 0 || op_st.iops > 0)
|
||||
nonzero = true;
|
||||
}
|
||||
|
||||
43
mon/test-stats-iops.js
Normal file
43
mon/test-stats-iops.js
Normal file
@@ -0,0 +1,43 @@
|
||||
// Copyright (c) Vitaliy Filippov, 2019+
|
||||
// License: VNPL-1.1 (see README.md for details)
|
||||
|
||||
// Rates summed over OSDs that each serve less than 1 op/s. Run: node mon/test-stats-iops.js
|
||||
|
||||
const assert = require('assert');
|
||||
const { sum_op_stats, sum_inode_stats } = require('./stats.js');
|
||||
|
||||
// One image read at 0.8 op/s on each of <osds> OSDs, 200 us per op, OSD stats reported every 5 s
|
||||
function run(osds)
|
||||
{
|
||||
const prev_stats = { osd_stats: {}, osd_diff: {} };
|
||||
let res;
|
||||
for (let round = 1; round <= 2; round++)
|
||||
{
|
||||
const st = { count: 4*round, usec: 800*round, bytes: 16384*round };
|
||||
const state = {
|
||||
config: { pools: { 1: {} }, inode: { 1: { 1: {} } } },
|
||||
pool: { stats: {} },
|
||||
osd: { state: {}, stats: {}, inodestats: {}, space: {} },
|
||||
};
|
||||
for (let osd = 1; osd <= osds; osd++)
|
||||
{
|
||||
state.osd.state[osd] = { state: 'up' };
|
||||
state.osd.stats[osd] = { time: 5*round, op_stats: { primary_read: st } };
|
||||
state.osd.inodestats[osd] = { 1: { 1: { read: st, write: {}, delete: {} } } };
|
||||
}
|
||||
res = { stats: sum_op_stats(state.osd, prev_stats), inode: sum_inode_stats(state, prev_stats).inode_stats[1][1] };
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
let { stats, inode } = run(48);
|
||||
// 48 * 0.8 = 38.4 op/s, rounded up
|
||||
assert.equal(stats.op_stats.primary_read.iops, 39n);
|
||||
assert.equal(stats.op_stats.primary_read.lat, 200n);
|
||||
assert.equal(inode.read.iops, 39n);
|
||||
assert.equal(inode.read.lat, 200n);
|
||||
({ stats, inode } = run(1));
|
||||
// Any I/O shows as at least 1 op/s
|
||||
assert.equal(inode.read.iops, 1n);
|
||||
assert.equal(inode.read.lat, 200n);
|
||||
console.log('OK');
|
||||
150
mon/test-sticky-primaries.js
Normal file
150
mon/test-sticky-primaries.js
Normal file
@@ -0,0 +1,150 @@
|
||||
// Copyright (c) Vitaliy Filippov, 2019+
|
||||
// License: VNPL-1.1 (see README.md for details)
|
||||
|
||||
// Primary OSD choice with and without sticky_primaries. Run: node mon/test-sticky-primaries.js
|
||||
|
||||
const assert = require('assert');
|
||||
const { recheck_primary, save_new_pgs_txn, count_primaries } = require('./pg_gen.js');
|
||||
|
||||
const HOSTS = 6, PER_HOST = 16;
|
||||
const host_osds = (h) => Array.from({ length: PER_HOST }, (_, i) => h*PER_HOST+i+1);
|
||||
|
||||
function up_except(down)
|
||||
{
|
||||
const up = {};
|
||||
for (let osd = 1; osd <= HOSTS*PER_HOST; osd++)
|
||||
up[osd] = true;
|
||||
for (const osd of down)
|
||||
delete up[osd];
|
||||
return up;
|
||||
}
|
||||
|
||||
// EC 4+2 over 6 hosts, one OSD of each host per PG, primaries picked from scratch
|
||||
function make_state(pg_count, global_config)
|
||||
{
|
||||
const state = {
|
||||
config: { pools: { 1: { name: 'ec', scheme: 'ec', pg_size: 6, parity_chunks: 2, pg_minsize: 4,
|
||||
pg_count, failure_domain: 'host' } } },
|
||||
pg: { config: { items: { 1: {} } } },
|
||||
};
|
||||
for (let pg = 1; pg <= pg_count; pg++)
|
||||
{
|
||||
const osd_set = [];
|
||||
for (let h = 0; h < HOSTS; h++)
|
||||
osd_set.push(host_osds((h + pg) % HOSTS)[(Math.floor(pg / HOSTS) * 7 + h) % PER_HOST]);
|
||||
state.pg.config.items[1][pg] = { osd_set, primary: 0 };
|
||||
}
|
||||
state.pg.config = recheck_primary(state, global_config, up_except([]), {});
|
||||
return state;
|
||||
}
|
||||
|
||||
function spread(pg_config, up_osds)
|
||||
{
|
||||
const counts = count_primaries(pg_config);
|
||||
const all = Object.keys(up_osds).map(osd => counts[osd]||0);
|
||||
return { max: Math.max(...all), min: Math.min(...all) };
|
||||
}
|
||||
|
||||
function moves(old_cfg, new_cfg)
|
||||
{
|
||||
return Object.keys((new_cfg||{ items: { 1: {} } }).items[1])
|
||||
.filter(pg => old_cfg.items[1][pg].primary != new_cfg.items[1][pg].primary)
|
||||
.map(pg => ({ pg, from: old_cfg.items[1][pg].primary, to: new_cfg.items[1][pg].primary }));
|
||||
}
|
||||
|
||||
// One host goes down and comes back
|
||||
function host_restart(global_config)
|
||||
{
|
||||
const state = make_state(1024, global_config);
|
||||
const start = spread(state.pg.config, up_except([]));
|
||||
const down = up_except(host_osds(4));
|
||||
const failed = recheck_primary(state, global_config, down, {});
|
||||
const away = moves(state.pg.config, failed);
|
||||
assert(away.length > 0 && away.every(m => down[m.to]));
|
||||
const from_live = away.filter(m => down[m.from]).length;
|
||||
const after_fail = spread(failed, down);
|
||||
state.pg.config = failed;
|
||||
const back = moves(state.pg.config, recheck_primary(state, global_config, up_except([]), {}));
|
||||
console.log(`sticky_primaries=${!!global_config.sticky_primaries}: primaries per OSD max ${start.max} min ${start.min}; `+
|
||||
`host down: ${away.length} moved (${from_live} of them live), max ${after_fail.max}; host back: ${back.length} moved`);
|
||||
return { start, after_fail, from_live, back };
|
||||
}
|
||||
|
||||
function test_host_restart()
|
||||
{
|
||||
const old = host_restart({});
|
||||
assert(old.back.length > 0, 'without the option primaries move back');
|
||||
const sticky = host_restart({ sticky_primaries: true });
|
||||
assert(sticky.start.max - sticky.start.min <= 1, 'primaries picked from scratch differ by at most 1 per OSD');
|
||||
assert(sticky.start.max <= old.start.max);
|
||||
assert.equal(sticky.from_live, 0, 'only primaries of the failed host move');
|
||||
assert(sticky.after_fail.max <= Math.ceil(1024 / (HOSTS-1) / PER_HOST) + 2, 'dead primaries go to the least loaded OSDs');
|
||||
assert.equal(sticky.back.length, 0, 'a live primary stays when the host returns');
|
||||
}
|
||||
|
||||
// A returned host gets no primaries back until the cluster is calm, then they are evened out,
|
||||
// each OSD getting at most one new primary per pass
|
||||
function test_rebalance_when_calm()
|
||||
{
|
||||
const cfg = { sticky_primaries: true };
|
||||
const state = make_state(1024, cfg);
|
||||
const all_up = up_except([]);
|
||||
state.pg.config = recheck_primary(state, cfg, up_except(host_osds(4)), {});
|
||||
assert(!recheck_primary(state, cfg, all_up, {}), 'nothing moves back by itself');
|
||||
const empty = spread(state.pg.config, all_up);
|
||||
let passes = 0, moved = 0, cur;
|
||||
while ((cur = recheck_primary(state, cfg, all_up, {}, true)))
|
||||
{
|
||||
const mv = moves(state.pg.config, cur);
|
||||
assert.equal(new Set(mv.map(m => m.to)).size, mv.length, 'one new primary per OSD per pass');
|
||||
moved += mv.length;
|
||||
state.pg.config = cur;
|
||||
passes++;
|
||||
assert(passes < 30, 'rebalance converges');
|
||||
}
|
||||
const even = spread(state.pg.config, all_up);
|
||||
console.log(`calm rebalance: max ${empty.max} min ${empty.min} -> max ${even.max} min ${even.min}, `+
|
||||
`${moved} primaries moved in ${passes} passes`);
|
||||
assert(empty.min == 0 && even.min > 0 && even.max - even.min <= 2, 'the returned host gets primaries again');
|
||||
}
|
||||
|
||||
// New OSD sets only move the primaries that left the set
|
||||
function test_new_sets_keep_primaries()
|
||||
{
|
||||
const state = make_state(64, { sticky_primaries: true });
|
||||
const prev_pgs = Object.values(state.pg.config.items[1]).map(c => c.osd_set);
|
||||
const new_pgs = prev_pgs.map(s => s.map((osd, i) => i == 1 ? 0 : osd));
|
||||
const save_to = {};
|
||||
save_new_pgs_txn(save_to, { compare: [], success: [] }, state, '/vitastor', 1, 1, up_except([]), {},
|
||||
prev_pgs, new_pgs, [], count_primaries(state.pg.config));
|
||||
const mv = moves(state.pg.config, save_to);
|
||||
assert(mv.length > 0 && mv.every(m => !save_to.items[1][m.pg].osd_set.includes(m.from)));
|
||||
console.log(`new OSD sets: ${mv.length} primaries moved, only those out of their set`);
|
||||
}
|
||||
|
||||
// Counts shared by the pools of one change stay exact on a PG count change and a pool deletion
|
||||
function test_counts_on_pg_count_change()
|
||||
{
|
||||
const state = make_state(64, { sticky_primaries: true });
|
||||
const prev_pgs = Object.values(state.pg.config.items[1]).map(c => c.osd_set);
|
||||
let counts = count_primaries(state.pg.config);
|
||||
const save_to = {};
|
||||
save_new_pgs_txn(save_to, { compare: [], success: [] }, state, '/vitastor', 1, 1, up_except([]), {},
|
||||
prev_pgs, prev_pgs.slice(0, 32), [], counts);
|
||||
const want = count_primaries(save_to);
|
||||
for (const osd in up_except([]))
|
||||
assert.equal(counts[osd]||0, want[osd]||0, 'OSD '+osd);
|
||||
counts = count_primaries(state.pg.config);
|
||||
save_new_pgs_txn({}, { compare: [], success: [] }, state, '/vitastor', 1, 1, up_except([]), {},
|
||||
prev_pgs, [], [], counts);
|
||||
assert(Object.values(counts).every(n => n == 0), 'a deleted pool gives back its primaries');
|
||||
console.log('primary counts: exact after a PG count change and a pool deletion');
|
||||
}
|
||||
|
||||
const log = console.log;
|
||||
console.log = (s) => /^Moving pool/.exec(s) || log(s);
|
||||
test_host_restart();
|
||||
test_rebalance_when_calm();
|
||||
test_new_sets_keep_primaries();
|
||||
test_counts_on_pg_count_change();
|
||||
console.log('OK');
|
||||
@@ -177,7 +177,7 @@ class VitastorAuthFilter
|
||||
// Allowed to check that a key does not exist
|
||||
if (check.target == 'VERSION' && check.version == 0)
|
||||
{
|
||||
checked['M'+key] = true;
|
||||
checked['C'+key] = true;
|
||||
return true;
|
||||
}
|
||||
else if (check.target == 'MOD')
|
||||
@@ -354,6 +354,25 @@ class VitastorAuthFilter
|
||||
// Allowed to modify known images with CAS checks
|
||||
return true;
|
||||
}
|
||||
if (key.substr(0, 14) == '/config/inode/' &&
|
||||
checked['C'+key])
|
||||
{
|
||||
// Allowed to create an image with CAS checks and with read access
|
||||
// to the parent image, if specified
|
||||
const data = this._decode(put.key, put.value);
|
||||
if (data.parent_id)
|
||||
{
|
||||
const [ cur_pool_id ] = put.key.substr(14).split('/');
|
||||
const inode = this._get([ ...this.prefix_parts, 'config', 'inode', data.parent_pool || cur_pool_id, data.parent_id ], true);
|
||||
if (inode && (inode.reader_group && userInfo.groups[inode.reader_group] ||
|
||||
inode.owner_group && userInfo.groups[inode.owner_group] ||
|
||||
inode.owner === userInfo.name))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "vitastor",
|
||||
"version": "3.1.0",
|
||||
"version": "3.2.3",
|
||||
"description": "Low-level native bindings to Vitastor client library",
|
||||
"main": "index.js",
|
||||
"keywords": [
|
||||
|
||||
@@ -545,7 +545,7 @@ sub _monkey_patch_qemu_blockdev_options
|
||||
|
||||
my ($vtype) = $plugin->parse_volname($volname);
|
||||
die "cannot use volume of type '$vtype' as a QEMU blockdevice\n"
|
||||
if $vtype ne 'images' && $vtype ne 'iso' && $vtype ne 'import';
|
||||
if $vtype ne 'vm-vol' && $vtype ne 'vm-state' && $vtype ne 'images' && $vtype ne 'iso' && $vtype ne 'import';
|
||||
|
||||
return $plugin->qemu_blockdev_options($scfg, $storeid, $volname, $machine_version, $options);
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ from cinder.volume import configuration
|
||||
from cinder.volume import driver
|
||||
from cinder.volume import volume_utils
|
||||
|
||||
VITASTOR_VERSION = '3.1.0'
|
||||
VITASTOR_VERSION = '3.2.3'
|
||||
|
||||
LOG = logging.getLogger(__name__)
|
||||
|
||||
|
||||
699
patches/libvirt-11.10-vitastor.patch
Normal file
699
patches/libvirt-11.10-vitastor.patch
Normal file
@@ -0,0 +1,699 @@
|
||||
From 560382fdf86fdbbd08c38187ef602c04e0abece0 Mon Sep 17 00:00:00 2001
|
||||
From: Vitaliy Filippov <vitalif@yourcmc.ru>
|
||||
Date: Sat, 5 Sep 2026 20:41:38 +0300
|
||||
Subject: [PATCH] Add Vitastor support
|
||||
|
||||
---
|
||||
include/libvirt/libvirt-storage.h | 1 +
|
||||
src/conf/domain_conf.c | 4 +-
|
||||
src/conf/domain_validate.c | 11 +-
|
||||
src/conf/schemas/domaincommon.rng | 30 +++++
|
||||
src/conf/storage_conf.c | 20 ++-
|
||||
src/conf/storage_conf.h | 2 +
|
||||
src/conf/storage_source_conf.c | 2 +
|
||||
src/conf/storage_source_conf.h | 1 +
|
||||
src/conf/virstorageobj.c | 3 +
|
||||
src/libvirt-storage.c | 1 +
|
||||
src/libxl/libxl_conf.c | 1 +
|
||||
src/libxl/xen_xl.c | 1 +
|
||||
src/qemu/qemu_block.c | 45 +++++++
|
||||
src/qemu/qemu_domain.c | 5 +-
|
||||
src/qemu/qemu_nbdkit.c | 2 +
|
||||
src/qemu/qemu_snapshot.c | 2 +
|
||||
src/storage/storage_driver.c | 1 +
|
||||
.../storage_source_backingstore.c | 123 ++++++++++++++++++
|
||||
src/test/test_driver.c | 1 +
|
||||
.../storagepoolcapsschemadata/poolcaps-fs.xml | 7 +
|
||||
.../poolcaps-full.xml | 7 +
|
||||
tests/storagepoolxml2argvtest.c | 1 +
|
||||
tools/virsh-pool.c | 3 +
|
||||
23 files changed, 268 insertions(+), 6 deletions(-)
|
||||
|
||||
diff --git a/include/libvirt/libvirt-storage.h b/include/libvirt/libvirt-storage.h
|
||||
index aaad4a3da1..5f5daa8341 100644
|
||||
--- a/include/libvirt/libvirt-storage.h
|
||||
+++ b/include/libvirt/libvirt-storage.h
|
||||
@@ -326,6 +326,7 @@ typedef enum {
|
||||
VIR_CONNECT_LIST_STORAGE_POOLS_ZFS = 1 << 17, /* (Since: 1.2.8) */
|
||||
VIR_CONNECT_LIST_STORAGE_POOLS_VSTORAGE = 1 << 18, /* (Since: 3.1.0) */
|
||||
VIR_CONNECT_LIST_STORAGE_POOLS_ISCSI_DIRECT = 1 << 19, /* (Since: 5.6.0) */
|
||||
+ VIR_CONNECT_LIST_STORAGE_POOLS_VITASTOR = 1 << 20, /* (Since: 5.0.0) */
|
||||
} virConnectListAllStoragePoolsFlags;
|
||||
|
||||
int virConnectListAllStoragePools(virConnectPtr conn,
|
||||
diff --git a/src/conf/domain_conf.c b/src/conf/domain_conf.c
|
||||
index 541dad5bdc..5cb94e1fed 100644
|
||||
--- a/src/conf/domain_conf.c
|
||||
+++ b/src/conf/domain_conf.c
|
||||
@@ -7453,7 +7453,8 @@ virDomainDiskSourceNetworkParse(xmlNodePtr node,
|
||||
src->configFile = virXPathString("string(./config/@file)", ctxt);
|
||||
|
||||
if (src->protocol == VIR_STORAGE_NET_PROTOCOL_HTTP ||
|
||||
- src->protocol == VIR_STORAGE_NET_PROTOCOL_HTTPS)
|
||||
+ src->protocol == VIR_STORAGE_NET_PROTOCOL_HTTPS ||
|
||||
+ src->protocol == VIR_STORAGE_NET_PROTOCOL_VITASTOR)
|
||||
src->query = virXMLPropString(node, "query");
|
||||
|
||||
if (virDomainStorageNetworkParseHosts(node, ctxt, &src->hosts, &src->nhosts) < 0)
|
||||
@@ -32196,6 +32197,7 @@ virDomainStorageSourceTranslateSourcePool(virStorageSource *src,
|
||||
|
||||
case VIR_STORAGE_POOL_MPATH:
|
||||
case VIR_STORAGE_POOL_RBD:
|
||||
+ case VIR_STORAGE_POOL_VITASTOR:
|
||||
case VIR_STORAGE_POOL_SHEEPDOG:
|
||||
case VIR_STORAGE_POOL_GLUSTER:
|
||||
case VIR_STORAGE_POOL_LAST:
|
||||
diff --git a/src/conf/domain_validate.c b/src/conf/domain_validate.c
|
||||
index 4558e7b210..3c6b2a8ee8 100644
|
||||
--- a/src/conf/domain_validate.c
|
||||
+++ b/src/conf/domain_validate.c
|
||||
@@ -520,6 +520,7 @@ virDomainDiskDefValidateSourceChainOne(const virStorageSource *src)
|
||||
case VIR_STORAGE_NET_PROTOCOL_RBD:
|
||||
break;
|
||||
|
||||
+ case VIR_STORAGE_NET_PROTOCOL_VITASTOR:
|
||||
case VIR_STORAGE_NET_PROTOCOL_NBD:
|
||||
case VIR_STORAGE_NET_PROTOCOL_SHEEPDOG:
|
||||
case VIR_STORAGE_NET_PROTOCOL_GLUSTER:
|
||||
@@ -592,7 +593,7 @@ virDomainDiskDefValidateSourceChainOne(const virStorageSource *src)
|
||||
}
|
||||
}
|
||||
|
||||
- /* internal snapshots and config files are currently supported only with rbd: */
|
||||
+ /* internal snapshots are currently supported only with rbd: */
|
||||
if (virStorageSourceGetActualType(src) != VIR_STORAGE_TYPE_NETWORK &&
|
||||
src->protocol != VIR_STORAGE_NET_PROTOCOL_RBD) {
|
||||
if (src->snapshot) {
|
||||
@@ -600,10 +601,14 @@ virDomainDiskDefValidateSourceChainOne(const virStorageSource *src)
|
||||
_("<snapshot> element is currently supported only with 'rbd' disks"));
|
||||
return -1;
|
||||
}
|
||||
-
|
||||
+ }
|
||||
+ /* config files are currently supported only with rbd and vitastor: */
|
||||
+ if (virStorageSourceGetActualType(src) != VIR_STORAGE_TYPE_NETWORK &&
|
||||
+ src->protocol != VIR_STORAGE_NET_PROTOCOL_RBD &&
|
||||
+ src->protocol != VIR_STORAGE_NET_PROTOCOL_VITASTOR) {
|
||||
if (src->configFile) {
|
||||
virReportError(VIR_ERR_XML_ERROR, "%s",
|
||||
- _("<config> element is currently supported only with 'rbd' disks"));
|
||||
+ _("<config> element is currently supported only with 'rbd' and 'vitastor' disks"));
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
diff --git a/src/conf/schemas/domaincommon.rng b/src/conf/schemas/domaincommon.rng
|
||||
index 1f9ac102a0..51b55ea72b 100644
|
||||
--- a/src/conf/schemas/domaincommon.rng
|
||||
+++ b/src/conf/schemas/domaincommon.rng
|
||||
@@ -2092,6 +2092,35 @@
|
||||
</element>
|
||||
</define>
|
||||
|
||||
+ <define name="diskSourceNetworkProtocolVitastor">
|
||||
+ <element name="source">
|
||||
+ <interleave>
|
||||
+ <attribute name="protocol">
|
||||
+ <value>vitastor</value>
|
||||
+ </attribute>
|
||||
+ <ref name="diskSourceCommon"/>
|
||||
+ <optional>
|
||||
+ <attribute name="name"/>
|
||||
+ </optional>
|
||||
+ <optional>
|
||||
+ <attribute name="query"/>
|
||||
+ </optional>
|
||||
+ <zeroOrMore>
|
||||
+ <ref name="diskSourceNetworkHost"/>
|
||||
+ </zeroOrMore>
|
||||
+ <optional>
|
||||
+ <element name="config">
|
||||
+ <attribute name="file">
|
||||
+ <ref name="absFilePath"/>
|
||||
+ </attribute>
|
||||
+ <empty/>
|
||||
+ </element>
|
||||
+ </optional>
|
||||
+ <empty/>
|
||||
+ </interleave>
|
||||
+ </element>
|
||||
+ </define>
|
||||
+
|
||||
<define name="diskSourceNetworkProtocolISCSI">
|
||||
<element name="source">
|
||||
<attribute name="protocol">
|
||||
@@ -2442,6 +2471,7 @@
|
||||
<ref name="diskSourceNetworkProtocolSimple"/>
|
||||
<ref name="diskSourceNetworkProtocolVxHS"/>
|
||||
<ref name="diskSourceNetworkProtocolNFS"/>
|
||||
+ <ref name="diskSourceNetworkProtocolVitastor"/>
|
||||
</choice>
|
||||
</define>
|
||||
|
||||
diff --git a/src/conf/storage_conf.c b/src/conf/storage_conf.c
|
||||
index 1dc9365bf2..a8a736be81 100644
|
||||
--- a/src/conf/storage_conf.c
|
||||
+++ b/src/conf/storage_conf.c
|
||||
@@ -56,7 +56,7 @@ VIR_ENUM_IMPL(virStoragePool,
|
||||
"logical", "disk", "iscsi",
|
||||
"iscsi-direct", "scsi", "mpath",
|
||||
"rbd", "sheepdog", "gluster",
|
||||
- "zfs", "vstorage",
|
||||
+ "zfs", "vstorage", "vitastor",
|
||||
);
|
||||
|
||||
VIR_ENUM_IMPL(virStoragePoolFormatFileSystem,
|
||||
@@ -242,6 +242,18 @@ static virStoragePoolTypeInfo poolTypeInfo[] = {
|
||||
.formatToString = virStorageFileFormatTypeToString,
|
||||
}
|
||||
},
|
||||
+ {.poolType = VIR_STORAGE_POOL_VITASTOR,
|
||||
+ .poolOptions = {
|
||||
+ .flags = (VIR_STORAGE_POOL_SOURCE_HOST |
|
||||
+ VIR_STORAGE_POOL_SOURCE_NETWORK |
|
||||
+ VIR_STORAGE_POOL_SOURCE_NAME),
|
||||
+ },
|
||||
+ .volOptions = {
|
||||
+ .defaultFormat = VIR_STORAGE_FILE_RAW,
|
||||
+ .formatFromString = virStorageVolumeFormatFromString,
|
||||
+ .formatToString = virStorageFileFormatTypeToString,
|
||||
+ }
|
||||
+ },
|
||||
{.poolType = VIR_STORAGE_POOL_SHEEPDOG,
|
||||
.poolOptions = {
|
||||
.flags = (VIR_STORAGE_POOL_SOURCE_HOST |
|
||||
@@ -538,6 +550,11 @@ virStoragePoolDefParseSource(xmlXPathContextPtr ctxt,
|
||||
_("element 'name' is mandatory for RBD pool"));
|
||||
return -1;
|
||||
}
|
||||
+ if (pool_type == VIR_STORAGE_POOL_VITASTOR && source->name == NULL) {
|
||||
+ virReportError(VIR_ERR_XML_ERROR, "%s",
|
||||
+ _("element 'name' is mandatory for Vitastor pool"));
|
||||
+ return -1;
|
||||
+ }
|
||||
|
||||
if (options->formatFromString) {
|
||||
g_autofree char *format = NULL;
|
||||
@@ -1127,6 +1144,7 @@ virStoragePoolDefFormatBuf(virBuffer *buf,
|
||||
/* RBD, Sheepdog, Gluster and Iscsi-direct devices are not local block devs nor
|
||||
* files, so they don't have a target */
|
||||
if (def->type != VIR_STORAGE_POOL_RBD &&
|
||||
+ def->type != VIR_STORAGE_POOL_VITASTOR &&
|
||||
def->type != VIR_STORAGE_POOL_SHEEPDOG &&
|
||||
def->type != VIR_STORAGE_POOL_GLUSTER &&
|
||||
def->type != VIR_STORAGE_POOL_ISCSI_DIRECT) {
|
||||
diff --git a/src/conf/storage_conf.h b/src/conf/storage_conf.h
|
||||
index fc67957cfe..720c07ef74 100644
|
||||
--- a/src/conf/storage_conf.h
|
||||
+++ b/src/conf/storage_conf.h
|
||||
@@ -103,6 +103,7 @@ typedef enum {
|
||||
VIR_STORAGE_POOL_GLUSTER, /* Gluster device */
|
||||
VIR_STORAGE_POOL_ZFS, /* ZFS */
|
||||
VIR_STORAGE_POOL_VSTORAGE, /* Virtuozzo Storage */
|
||||
+ VIR_STORAGE_POOL_VITASTOR, /* Vitastor */
|
||||
|
||||
VIR_STORAGE_POOL_LAST,
|
||||
} virStoragePoolType;
|
||||
@@ -454,6 +455,7 @@ VIR_ENUM_DECL(virStoragePartedFs);
|
||||
VIR_CONNECT_LIST_STORAGE_POOLS_SCSI | \
|
||||
VIR_CONNECT_LIST_STORAGE_POOLS_MPATH | \
|
||||
VIR_CONNECT_LIST_STORAGE_POOLS_RBD | \
|
||||
+ VIR_CONNECT_LIST_STORAGE_POOLS_VITASTOR | \
|
||||
VIR_CONNECT_LIST_STORAGE_POOLS_SHEEPDOG | \
|
||||
VIR_CONNECT_LIST_STORAGE_POOLS_GLUSTER | \
|
||||
VIR_CONNECT_LIST_STORAGE_POOLS_ZFS | \
|
||||
diff --git a/src/conf/storage_source_conf.c b/src/conf/storage_source_conf.c
|
||||
index 087de1eaf2..acc046816b 100644
|
||||
--- a/src/conf/storage_source_conf.c
|
||||
+++ b/src/conf/storage_source_conf.c
|
||||
@@ -89,6 +89,7 @@ VIR_ENUM_IMPL(virStorageNetProtocol,
|
||||
"ssh",
|
||||
"vxhs",
|
||||
"nfs",
|
||||
+ "vitastor",
|
||||
);
|
||||
|
||||
|
||||
@@ -1313,6 +1314,7 @@ virStorageSourceNetworkDefaultPort(virStorageNetProtocol protocol)
|
||||
case VIR_STORAGE_NET_PROTOCOL_GLUSTER:
|
||||
return 24007;
|
||||
|
||||
+ case VIR_STORAGE_NET_PROTOCOL_VITASTOR:
|
||||
case VIR_STORAGE_NET_PROTOCOL_RBD:
|
||||
/* we don't provide a default for RBD */
|
||||
return 0;
|
||||
diff --git a/src/conf/storage_source_conf.h b/src/conf/storage_source_conf.h
|
||||
index fc868b31af..1c9fbc02b9 100644
|
||||
--- a/src/conf/storage_source_conf.h
|
||||
+++ b/src/conf/storage_source_conf.h
|
||||
@@ -130,6 +130,7 @@ typedef enum {
|
||||
VIR_STORAGE_NET_PROTOCOL_SSH,
|
||||
VIR_STORAGE_NET_PROTOCOL_VXHS,
|
||||
VIR_STORAGE_NET_PROTOCOL_NFS,
|
||||
+ VIR_STORAGE_NET_PROTOCOL_VITASTOR,
|
||||
|
||||
VIR_STORAGE_NET_PROTOCOL_LAST
|
||||
} virStorageNetProtocol;
|
||||
diff --git a/src/conf/virstorageobj.c b/src/conf/virstorageobj.c
|
||||
index 59fa5da372..4739167f5f 100644
|
||||
--- a/src/conf/virstorageobj.c
|
||||
+++ b/src/conf/virstorageobj.c
|
||||
@@ -1438,6 +1438,7 @@ virStoragePoolObjSourceFindDuplicateCb(const void *payload,
|
||||
return 1;
|
||||
break;
|
||||
|
||||
+ case VIR_STORAGE_POOL_VITASTOR:
|
||||
case VIR_STORAGE_POOL_ISCSI_DIRECT:
|
||||
case VIR_STORAGE_POOL_RBD:
|
||||
case VIR_STORAGE_POOL_LAST:
|
||||
@@ -1921,6 +1922,8 @@ virStoragePoolObjMatch(virStoragePoolObj *obj,
|
||||
(obj->def->type == VIR_STORAGE_POOL_MPATH)) ||
|
||||
(MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_RBD) &&
|
||||
(obj->def->type == VIR_STORAGE_POOL_RBD)) ||
|
||||
+ (MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_VITASTOR) &&
|
||||
+ (obj->def->type == VIR_STORAGE_POOL_VITASTOR)) ||
|
||||
(MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_SHEEPDOG) &&
|
||||
(obj->def->type == VIR_STORAGE_POOL_SHEEPDOG)) ||
|
||||
(MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_GLUSTER) &&
|
||||
diff --git a/src/libvirt-storage.c b/src/libvirt-storage.c
|
||||
index db7660aac4..561df34709 100644
|
||||
--- a/src/libvirt-storage.c
|
||||
+++ b/src/libvirt-storage.c
|
||||
@@ -94,6 +94,7 @@ virStoragePoolGetConnect(virStoragePoolPtr pool)
|
||||
* VIR_CONNECT_LIST_STORAGE_POOLS_SCSI
|
||||
* VIR_CONNECT_LIST_STORAGE_POOLS_MPATH
|
||||
* VIR_CONNECT_LIST_STORAGE_POOLS_RBD
|
||||
+ * VIR_CONNECT_LIST_STORAGE_POOLS_VITASTOR
|
||||
* VIR_CONNECT_LIST_STORAGE_POOLS_SHEEPDOG
|
||||
* VIR_CONNECT_LIST_STORAGE_POOLS_GLUSTER
|
||||
* VIR_CONNECT_LIST_STORAGE_POOLS_ZFS
|
||||
diff --git a/src/libxl/libxl_conf.c b/src/libxl/libxl_conf.c
|
||||
index 2b988157fa..9d0eb47b25 100644
|
||||
--- a/src/libxl/libxl_conf.c
|
||||
+++ b/src/libxl/libxl_conf.c
|
||||
@@ -1069,6 +1069,7 @@ libxlMakeNetworkDiskSrcStr(virStorageSource *src,
|
||||
case VIR_STORAGE_NET_PROTOCOL_SSH:
|
||||
case VIR_STORAGE_NET_PROTOCOL_VXHS:
|
||||
case VIR_STORAGE_NET_PROTOCOL_NFS:
|
||||
+ case VIR_STORAGE_NET_PROTOCOL_VITASTOR:
|
||||
case VIR_STORAGE_NET_PROTOCOL_LAST:
|
||||
case VIR_STORAGE_NET_PROTOCOL_NONE:
|
||||
virReportError(VIR_ERR_NO_SUPPORT,
|
||||
diff --git a/src/libxl/xen_xl.c b/src/libxl/xen_xl.c
|
||||
index b2ff0edcf2..5d9f50c88c 100644
|
||||
--- a/src/libxl/xen_xl.c
|
||||
+++ b/src/libxl/xen_xl.c
|
||||
@@ -1461,6 +1461,7 @@ xenFormatXLDiskSrcNet(virStorageSource *src)
|
||||
case VIR_STORAGE_NET_PROTOCOL_SSH:
|
||||
case VIR_STORAGE_NET_PROTOCOL_VXHS:
|
||||
case VIR_STORAGE_NET_PROTOCOL_NFS:
|
||||
+ case VIR_STORAGE_NET_PROTOCOL_VITASTOR:
|
||||
case VIR_STORAGE_NET_PROTOCOL_LAST:
|
||||
case VIR_STORAGE_NET_PROTOCOL_NONE:
|
||||
virReportError(VIR_ERR_NO_SUPPORT,
|
||||
diff --git a/src/qemu/qemu_block.c b/src/qemu/qemu_block.c
|
||||
index a7062d3e96..4f2b6cc0e6 100644
|
||||
--- a/src/qemu/qemu_block.c
|
||||
+++ b/src/qemu/qemu_block.c
|
||||
@@ -743,6 +743,38 @@ qemuBlockStorageSourceGetRBDProps(virStorageSource *src,
|
||||
}
|
||||
|
||||
|
||||
+static virJSONValue *
|
||||
+qemuBlockStorageSourceGetVitastorProps(virStorageSource *src)
|
||||
+{
|
||||
+ virJSONValue *ret = NULL;
|
||||
+ virStorageNetHostDef *host;
|
||||
+ size_t i;
|
||||
+ g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
|
||||
+ g_autofree char *etcd = NULL;
|
||||
+
|
||||
+ for (i = 0; i < src->nhosts; i++) {
|
||||
+ host = src->hosts + i;
|
||||
+ if ((virStorageNetHostTransport)host->transport != VIR_STORAGE_NET_HOST_TRANS_TCP) {
|
||||
+ return NULL;
|
||||
+ }
|
||||
+ virBufferAsprintf(&buf, i > 0 ? ",%s:%u" : "%s:%u", host->name, host->port);
|
||||
+ }
|
||||
+ if (src->nhosts > 0) {
|
||||
+ etcd = virBufferContentAndReset(&buf);
|
||||
+ }
|
||||
+
|
||||
+ if (virJSONValueObjectAdd(&ret,
|
||||
+ "S:etcd-host", etcd,
|
||||
+ "S:etcd-prefix", src->query,
|
||||
+ "S:config-path", src->configFile,
|
||||
+ "s:image", src->path,
|
||||
+ NULL) < 0)
|
||||
+ return NULL;
|
||||
+
|
||||
+ return ret;
|
||||
+}
|
||||
+
|
||||
+
|
||||
static virJSONValue *
|
||||
qemuBlockStorageSourceGetSshProps(virStorageSource *src)
|
||||
{
|
||||
@@ -1093,6 +1125,12 @@ qemuBlockStorageSourceGetBackendProps(virStorageSource *src,
|
||||
return NULL;
|
||||
break;
|
||||
|
||||
+ case VIR_STORAGE_NET_PROTOCOL_VITASTOR:
|
||||
+ driver = "vitastor";
|
||||
+ if (!(fileprops = qemuBlockStorageSourceGetVitastorProps(src)))
|
||||
+ return NULL;
|
||||
+ break;
|
||||
+
|
||||
case VIR_STORAGE_NET_PROTOCOL_SSH:
|
||||
driver = "ssh";
|
||||
if (!(fileprops = qemuBlockStorageSourceGetSshProps(src)))
|
||||
@@ -1996,6 +2034,7 @@ qemuBlockGetBackingStoreString(virStorageSource *src,
|
||||
|
||||
case VIR_STORAGE_NET_PROTOCOL_SHEEPDOG:
|
||||
case VIR_STORAGE_NET_PROTOCOL_RBD:
|
||||
+ case VIR_STORAGE_NET_PROTOCOL_VITASTOR:
|
||||
case VIR_STORAGE_NET_PROTOCOL_VXHS:
|
||||
case VIR_STORAGE_NET_PROTOCOL_NFS:
|
||||
case VIR_STORAGE_NET_PROTOCOL_SSH:
|
||||
@@ -2376,6 +2415,12 @@ qemuBlockStorageSourceCreateGetStorageProps(virStorageSource *src,
|
||||
return -1;
|
||||
break;
|
||||
|
||||
+ case VIR_STORAGE_NET_PROTOCOL_VITASTOR:
|
||||
+ driver = "vitastor";
|
||||
+ if (!(location = qemuBlockStorageSourceGetVitastorProps(src)))
|
||||
+ return -1;
|
||||
+ break;
|
||||
+
|
||||
case VIR_STORAGE_NET_PROTOCOL_SSH:
|
||||
if (srcPriv->nbdkitProcess) {
|
||||
/* disk creation not yet supported with nbdkit, and even if it
|
||||
diff --git a/src/qemu/qemu_domain.c b/src/qemu/qemu_domain.c
|
||||
index ac56fc7cb4..b80b311eea 100644
|
||||
--- a/src/qemu/qemu_domain.c
|
||||
+++ b/src/qemu/qemu_domain.c
|
||||
@@ -4677,7 +4677,8 @@ qemuDomainValidateStorageSource(virStorageSource *src,
|
||||
if (src->query &&
|
||||
(actualType != VIR_STORAGE_TYPE_NETWORK ||
|
||||
(src->protocol != VIR_STORAGE_NET_PROTOCOL_HTTPS &&
|
||||
- src->protocol != VIR_STORAGE_NET_PROTOCOL_HTTP))) {
|
||||
+ src->protocol != VIR_STORAGE_NET_PROTOCOL_HTTP &&
|
||||
+ src->protocol != VIR_STORAGE_NET_PROTOCOL_VITASTOR))) {
|
||||
virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
|
||||
_("query is supported only with HTTP(S) protocols"));
|
||||
return -1;
|
||||
@@ -4693,6 +4694,7 @@ qemuDomainValidateStorageSource(virStorageSource *src,
|
||||
case VIR_STORAGE_NET_PROTOCOL_ISCSI:
|
||||
case VIR_STORAGE_NET_PROTOCOL_NBD:
|
||||
case VIR_STORAGE_NET_PROTOCOL_RBD:
|
||||
+ case VIR_STORAGE_NET_PROTOCOL_VITASTOR:
|
||||
case VIR_STORAGE_NET_PROTOCOL_SSH:
|
||||
case VIR_STORAGE_NET_PROTOCOL_SHEEPDOG:
|
||||
break;
|
||||
@@ -9103,6 +9105,7 @@ qemuDomainPrepareStorageSourceTLS(virStorageSource *src,
|
||||
break;
|
||||
|
||||
case VIR_STORAGE_NET_PROTOCOL_RBD:
|
||||
+ case VIR_STORAGE_NET_PROTOCOL_VITASTOR:
|
||||
case VIR_STORAGE_NET_PROTOCOL_SHEEPDOG:
|
||||
case VIR_STORAGE_NET_PROTOCOL_GLUSTER:
|
||||
case VIR_STORAGE_NET_PROTOCOL_ISCSI:
|
||||
diff --git a/src/qemu/qemu_nbdkit.c b/src/qemu/qemu_nbdkit.c
|
||||
index c1bc6bc363..9d3433bf75 100644
|
||||
--- a/src/qemu/qemu_nbdkit.c
|
||||
+++ b/src/qemu/qemu_nbdkit.c
|
||||
@@ -869,6 +869,7 @@ qemuNbdkitInitStorageSource(qemuNbdkitCaps *caps WITHOUT_NBDKIT_UNUSED,
|
||||
case VIR_STORAGE_NET_PROTOCOL_NONE:
|
||||
case VIR_STORAGE_NET_PROTOCOL_NBD:
|
||||
case VIR_STORAGE_NET_PROTOCOL_RBD:
|
||||
+ case VIR_STORAGE_NET_PROTOCOL_VITASTOR:
|
||||
case VIR_STORAGE_NET_PROTOCOL_SHEEPDOG:
|
||||
case VIR_STORAGE_NET_PROTOCOL_GLUSTER:
|
||||
case VIR_STORAGE_NET_PROTOCOL_ISCSI:
|
||||
@@ -1133,6 +1134,7 @@ qemuNbdkitProcessBuildCommand(qemuNbdkitProcess *proc)
|
||||
case VIR_STORAGE_NET_PROTOCOL_NONE:
|
||||
case VIR_STORAGE_NET_PROTOCOL_NBD:
|
||||
case VIR_STORAGE_NET_PROTOCOL_RBD:
|
||||
+ case VIR_STORAGE_NET_PROTOCOL_VITASTOR:
|
||||
case VIR_STORAGE_NET_PROTOCOL_SHEEPDOG:
|
||||
case VIR_STORAGE_NET_PROTOCOL_GLUSTER:
|
||||
case VIR_STORAGE_NET_PROTOCOL_ISCSI:
|
||||
diff --git a/src/qemu/qemu_snapshot.c b/src/qemu/qemu_snapshot.c
|
||||
index 302775af92..9d8fa0ded2 100644
|
||||
--- a/src/qemu/qemu_snapshot.c
|
||||
+++ b/src/qemu/qemu_snapshot.c
|
||||
@@ -665,6 +665,7 @@ qemuSnapshotPrepareDiskExternalInactive(virDomainSnapshotDiskDef *snapdisk,
|
||||
case VIR_STORAGE_NET_PROTOCOL_NONE:
|
||||
case VIR_STORAGE_NET_PROTOCOL_NBD:
|
||||
case VIR_STORAGE_NET_PROTOCOL_RBD:
|
||||
+ case VIR_STORAGE_NET_PROTOCOL_VITASTOR:
|
||||
case VIR_STORAGE_NET_PROTOCOL_SHEEPDOG:
|
||||
case VIR_STORAGE_NET_PROTOCOL_GLUSTER:
|
||||
case VIR_STORAGE_NET_PROTOCOL_ISCSI:
|
||||
@@ -890,6 +891,7 @@ qemuSnapshotPrepareDiskInternal(virDomainDiskDef *disk,
|
||||
case VIR_STORAGE_NET_PROTOCOL_NONE:
|
||||
case VIR_STORAGE_NET_PROTOCOL_NBD:
|
||||
case VIR_STORAGE_NET_PROTOCOL_RBD:
|
||||
+ case VIR_STORAGE_NET_PROTOCOL_VITASTOR:
|
||||
case VIR_STORAGE_NET_PROTOCOL_SHEEPDOG:
|
||||
case VIR_STORAGE_NET_PROTOCOL_GLUSTER:
|
||||
case VIR_STORAGE_NET_PROTOCOL_ISCSI:
|
||||
diff --git a/src/storage/storage_driver.c b/src/storage/storage_driver.c
|
||||
index e19e032427..59f91f4710 100644
|
||||
--- a/src/storage/storage_driver.c
|
||||
+++ b/src/storage/storage_driver.c
|
||||
@@ -1626,6 +1626,7 @@ storageVolLookupByPathCallback(virStoragePoolObj *obj,
|
||||
|
||||
case VIR_STORAGE_POOL_GLUSTER:
|
||||
case VIR_STORAGE_POOL_RBD:
|
||||
+ case VIR_STORAGE_POOL_VITASTOR:
|
||||
case VIR_STORAGE_POOL_SHEEPDOG:
|
||||
case VIR_STORAGE_POOL_ZFS:
|
||||
case VIR_STORAGE_POOL_LAST:
|
||||
diff --git a/src/storage_file/storage_source_backingstore.c b/src/storage_file/storage_source_backingstore.c
|
||||
index 821378883c..2211f6891b 100644
|
||||
--- a/src/storage_file/storage_source_backingstore.c
|
||||
+++ b/src/storage_file/storage_source_backingstore.c
|
||||
@@ -264,6 +264,75 @@ virStorageSourceParseRBDColonString(const char *rbdstr,
|
||||
}
|
||||
|
||||
|
||||
+static int
|
||||
+virStorageSourceParseVitastorColonString(const char *colonstr,
|
||||
+ virStorageSource *src)
|
||||
+{
|
||||
+ char *p, *e, *next;
|
||||
+ g_autofree char *options = NULL;
|
||||
+
|
||||
+ /* optionally skip the "vitastor:" prefix if provided */
|
||||
+ if (STRPREFIX(colonstr, "vitastor:"))
|
||||
+ colonstr += strlen("vitastor:");
|
||||
+
|
||||
+ options = g_strdup(colonstr);
|
||||
+
|
||||
+ p = options;
|
||||
+ while (*p) {
|
||||
+ /* find : delimiter or end of string */
|
||||
+ for (e = p; *e && *e != ':'; ++e) {
|
||||
+ if (*e == '\\') {
|
||||
+ e++;
|
||||
+ if (*e == '\0')
|
||||
+ break;
|
||||
+ }
|
||||
+ }
|
||||
+ if (*e == '\0') {
|
||||
+ next = e; /* last kv pair */
|
||||
+ } else {
|
||||
+ next = e + 1;
|
||||
+ *e = '\0';
|
||||
+ }
|
||||
+
|
||||
+ if (STRPREFIX(p, "image=")) {
|
||||
+ src->path = g_strdup(p + strlen("image="));
|
||||
+ } else if (STRPREFIX(p, "etcd-prefix=")) {
|
||||
+ src->query = g_strdup(p + strlen("etcd-prefix="));
|
||||
+ } else if (STRPREFIX(p, "config-path=")) {
|
||||
+ src->configFile = g_strdup(p + strlen("config-path="));
|
||||
+ } else if (STRPREFIX(p, "etcd-host=")) {
|
||||
+ char *h, *sep;
|
||||
+
|
||||
+ h = p + strlen("etcd-host=");
|
||||
+ while (h < e) {
|
||||
+ for (sep = h; sep < e; ++sep) {
|
||||
+ if (*sep == '\\' && (sep[1] == ',' ||
|
||||
+ sep[1] == ';' ||
|
||||
+ sep[1] == ' ')) {
|
||||
+ *sep = '\0';
|
||||
+ sep += 2;
|
||||
+ break;
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
+ if (virStorageSourceRBDAddHost(src, h) < 0)
|
||||
+ return -1;
|
||||
+
|
||||
+ h = sep;
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
+ p = next;
|
||||
+ }
|
||||
+
|
||||
+ if (!src->path) {
|
||||
+ return -1;
|
||||
+ }
|
||||
+
|
||||
+ return 0;
|
||||
+}
|
||||
+
|
||||
+
|
||||
static int
|
||||
virStorageSourceParseNBDColonString(const char *nbdstr,
|
||||
virStorageSource *src)
|
||||
@@ -379,6 +448,11 @@ virStorageSourceParseBackingColon(virStorageSource *src,
|
||||
return -1;
|
||||
break;
|
||||
|
||||
+ case VIR_STORAGE_NET_PROTOCOL_VITASTOR:
|
||||
+ if (virStorageSourceParseVitastorColonString(path, src) < 0)
|
||||
+ return -1;
|
||||
+ break;
|
||||
+
|
||||
case VIR_STORAGE_NET_PROTOCOL_SHEEPDOG:
|
||||
case VIR_STORAGE_NET_PROTOCOL_LAST:
|
||||
case VIR_STORAGE_NET_PROTOCOL_NONE:
|
||||
@@ -953,6 +1027,54 @@ virStorageSourceParseBackingJSONRBD(virStorageSource *src,
|
||||
return 0;
|
||||
}
|
||||
|
||||
+static int
|
||||
+virStorageSourceParseBackingJSONVitastor(virStorageSource *src,
|
||||
+ virJSONValue *json,
|
||||
+ const char *jsonstr G_GNUC_UNUSED,
|
||||
+ int opaque G_GNUC_UNUSED)
|
||||
+{
|
||||
+ const char *filename;
|
||||
+ const char *image = virJSONValueObjectGetString(json, "image");
|
||||
+ const char *conf = virJSONValueObjectGetString(json, "config-path");
|
||||
+ const char *etcd_prefix = virJSONValueObjectGetString(json, "etcd-prefix");
|
||||
+ virJSONValue *servers = virJSONValueObjectGetArray(json, "server");
|
||||
+ size_t nservers;
|
||||
+ size_t i;
|
||||
+
|
||||
+ src->type = VIR_STORAGE_TYPE_NETWORK;
|
||||
+ src->protocol = VIR_STORAGE_NET_PROTOCOL_VITASTOR;
|
||||
+
|
||||
+ /* legacy syntax passed via 'filename' option */
|
||||
+ if ((filename = virJSONValueObjectGetString(json, "filename")))
|
||||
+ return virStorageSourceParseVitastorColonString(filename, src);
|
||||
+
|
||||
+ if (!image) {
|
||||
+ virReportError(VIR_ERR_INVALID_ARG, "%s",
|
||||
+ _("missing image name in Vitastor backing volume "
|
||||
+ "JSON specification"));
|
||||
+ return -1;
|
||||
+ }
|
||||
+
|
||||
+ src->path = g_strdup(image);
|
||||
+ src->configFile = g_strdup(conf);
|
||||
+ src->query = g_strdup(etcd_prefix);
|
||||
+
|
||||
+ if (servers) {
|
||||
+ nservers = virJSONValueArraySize(servers);
|
||||
+
|
||||
+ src->hosts = g_new0(virStorageNetHostDef, nservers);
|
||||
+ src->nhosts = nservers;
|
||||
+
|
||||
+ for (i = 0; i < nservers; i++) {
|
||||
+ if (virStorageSourceParseBackingJSONInetSocketAddress(src->hosts + i,
|
||||
+ virJSONValueArrayGet(servers, i)) < 0)
|
||||
+ return -1;
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
+ return 0;
|
||||
+}
|
||||
+
|
||||
static int
|
||||
virStorageSourceParseBackingJSONRaw(virStorageSource *src,
|
||||
virJSONValue *json,
|
||||
@@ -1130,6 +1252,7 @@ static const struct virStorageSourceJSONDriverParser jsonParsers[] = {
|
||||
{"sheepdog", false, virStorageSourceParseBackingJSONSheepdog, 0},
|
||||
{"ssh", false, virStorageSourceParseBackingJSONSSH, 0},
|
||||
{"rbd", false, virStorageSourceParseBackingJSONRBD, 0},
|
||||
+ {"vitastor", false, virStorageSourceParseBackingJSONVitastor, 0},
|
||||
{"raw", true, virStorageSourceParseBackingJSONRaw, 0},
|
||||
{"nfs", false, virStorageSourceParseBackingJSONNFS, 0},
|
||||
{"vxhs", false, virStorageSourceParseBackingJSONVxHS, 0},
|
||||
diff --git a/src/test/test_driver.c b/src/test/test_driver.c
|
||||
index 1165689de7..bba846351c 100644
|
||||
--- a/src/test/test_driver.c
|
||||
+++ b/src/test/test_driver.c
|
||||
@@ -7345,6 +7345,7 @@ testStorageVolumeTypeForPool(int pooltype)
|
||||
case VIR_STORAGE_POOL_ISCSI_DIRECT:
|
||||
case VIR_STORAGE_POOL_GLUSTER:
|
||||
case VIR_STORAGE_POOL_RBD:
|
||||
+ case VIR_STORAGE_POOL_VITASTOR:
|
||||
return VIR_STORAGE_VOL_NETWORK;
|
||||
case VIR_STORAGE_POOL_LOGICAL:
|
||||
case VIR_STORAGE_POOL_DISK:
|
||||
diff --git a/tests/storagepoolcapsschemadata/poolcaps-fs.xml b/tests/storagepoolcapsschemadata/poolcaps-fs.xml
|
||||
index eee75af746..8bd0a57bdd 100644
|
||||
--- a/tests/storagepoolcapsschemadata/poolcaps-fs.xml
|
||||
+++ b/tests/storagepoolcapsschemadata/poolcaps-fs.xml
|
||||
@@ -204,4 +204,11 @@
|
||||
</enum>
|
||||
</volOptions>
|
||||
</pool>
|
||||
+ <pool type='vitastor' supported='no'>
|
||||
+ <volOptions>
|
||||
+ <defaultFormat type='raw'/>
|
||||
+ <enum name='targetFormatType'>
|
||||
+ </enum>
|
||||
+ </volOptions>
|
||||
+ </pool>
|
||||
</storagepoolCapabilities>
|
||||
diff --git a/tests/storagepoolcapsschemadata/poolcaps-full.xml b/tests/storagepoolcapsschemadata/poolcaps-full.xml
|
||||
index 805950a937..852df0de16 100644
|
||||
--- a/tests/storagepoolcapsschemadata/poolcaps-full.xml
|
||||
+++ b/tests/storagepoolcapsschemadata/poolcaps-full.xml
|
||||
@@ -204,4 +204,11 @@
|
||||
</enum>
|
||||
</volOptions>
|
||||
</pool>
|
||||
+ <pool type='vitastor' supported='yes'>
|
||||
+ <volOptions>
|
||||
+ <defaultFormat type='raw'/>
|
||||
+ <enum name='targetFormatType'>
|
||||
+ </enum>
|
||||
+ </volOptions>
|
||||
+ </pool>
|
||||
</storagepoolCapabilities>
|
||||
diff --git a/tests/storagepoolxml2argvtest.c b/tests/storagepoolxml2argvtest.c
|
||||
index d5c2531ab8..b19308ac38 100644
|
||||
--- a/tests/storagepoolxml2argvtest.c
|
||||
+++ b/tests/storagepoolxml2argvtest.c
|
||||
@@ -57,6 +57,7 @@ testCompareXMLToArgvFiles(bool shouldFail,
|
||||
case VIR_STORAGE_POOL_GLUSTER:
|
||||
case VIR_STORAGE_POOL_ZFS:
|
||||
case VIR_STORAGE_POOL_VSTORAGE:
|
||||
+ case VIR_STORAGE_POOL_VITASTOR:
|
||||
case VIR_STORAGE_POOL_LAST:
|
||||
default:
|
||||
VIR_TEST_DEBUG("pool type '%s' has no xml2argv test", defTypeStr);
|
||||
diff --git a/tools/virsh-pool.c b/tools/virsh-pool.c
|
||||
index 2010ef1356..072e2ff9e8 100644
|
||||
--- a/tools/virsh-pool.c
|
||||
+++ b/tools/virsh-pool.c
|
||||
@@ -1187,6 +1187,9 @@ cmdPoolList(vshControl *ctl, const vshCmd *cmd G_GNUC_UNUSED)
|
||||
case VIR_STORAGE_POOL_VSTORAGE:
|
||||
flags |= VIR_CONNECT_LIST_STORAGE_POOLS_VSTORAGE;
|
||||
break;
|
||||
+ case VIR_STORAGE_POOL_VITASTOR:
|
||||
+ flags |= VIR_CONNECT_LIST_STORAGE_POOLS_VITASTOR;
|
||||
+ break;
|
||||
case VIR_STORAGE_POOL_LAST:
|
||||
break;
|
||||
}
|
||||
--
|
||||
2.51.0
|
||||
|
||||
91
rpm/qemu-kvm-10.1-el10.spec.patch
Normal file
91
rpm/qemu-kvm-10.1-el10.spec.patch
Normal file
@@ -0,0 +1,91 @@
|
||||
--- qemu-kvm.spec.orig 2026-08-24 00:00:00.000000000 +0000
|
||||
+++ qemu-kvm.spec 2026-09-05 16:48:22.226624885 +0000
|
||||
@@ -102,8 +102,6 @@
|
||||
|
||||
|
||||
%global target_list %{kvm_target}-softmmu
|
||||
-%global block_drivers_rw_list qcow2,raw,file,host_device,nbd,iscsi,rbd,blkdebug,luks,null-co,nvme,copy-on-read,throttle,compress,virtio-blk-vhost-vdpa,virtio-blk-vfio-pci,virtio-blk-vhost-user,io_uring,nvme-io_uring
|
||||
-%global block_drivers_ro_list vdi,vmdk,vhdx,vpc,https
|
||||
%define qemudocdir %{_docdir}/%{name}
|
||||
%global firmwaredirs "%{_datadir}/qemu-firmware:%{_datadir}/ipxe/qemu:%{_datadir}/seavgabios:%{_datadir}/seabios"
|
||||
|
||||
@@ -134,6 +132,7 @@ Requires: %{name}-block-blkio = %{epoch}
|
||||
%if %{have_block_rbd} \
|
||||
Requires: %{name}-block-rbd = %{epoch}:%{version}-%{release} \
|
||||
%endif \
|
||||
+Requires: %{name}-block-vitastor = %{epoch}:%{version}-%{release}\
|
||||
Requires: %{name}-audio-pa = %{epoch}:%{version}-%{release}
|
||||
|
||||
# Since SPICE is removed from RHEL-9, the following Obsoletes:
|
||||
@@ -158,7 +157,7 @@ Obsoletes: %{name}-block-ssh <= %{epoch}
|
||||
Summary: QEMU is a machine emulator and virtualizer
|
||||
Name: qemu-kvm
|
||||
Version: 10.1.0
|
||||
-Release: 16%{?rcrel}%{?dist}%{?cc_suffix}.5.alma.1
|
||||
+Release: 16.vitastor%{?rcrel}%{?dist}%{?cc_suffix}.5.alma.1
|
||||
# Epoch because we pushed a qemu-1.0 package. AIUI this can't ever be dropped
|
||||
# Epoch 15 used for RHEL 8
|
||||
# Epoch 17 used for RHEL 9 (due to release versioning offset in RHEL 8.5)
|
||||
@@ -181,6 +180,7 @@ Source28: 95-kvm-memlock.conf
|
||||
Source30: kvm-s390x.conf
|
||||
Source31: kvm-x86.conf
|
||||
Source36: README.tests
|
||||
+Source37: qemu-vitastor.c
|
||||
|
||||
|
||||
Patch0004: 0004-Initial-redhat-build.patch
|
||||
@@ -471,6 +471,7 @@ Patch149: kvm-file-posix-populate-pwrite
|
||||
Patch150: kvm-block-use-pwrite_zeroes_alignment-when-writing-first.patch
|
||||
# For RHEL-207389 - qemu-img create/convert fails on target block device with 4k sector size [rhel-10.2.z]
|
||||
Patch151: kvm-iotests-add-Linux-loop-device-image-creation-test.patch
|
||||
+Patch152: qemu-10.1-vitastor.patch
|
||||
|
||||
# AlmaLinux Patch
|
||||
Patch2001: 2001-Add-ppc64-support.patch
|
||||
@@ -509,6 +510,7 @@ BuildRequires: libcurl-devel
|
||||
%if %{have_block_rbd}
|
||||
BuildRequires: librbd-devel
|
||||
%endif
|
||||
+BuildRequires: vitastor-client-devel
|
||||
# We need both because the 'stap' binary is probed for by configure
|
||||
BuildRequires: systemtap
|
||||
BuildRequires: systemtap-sdt-devel
|
||||
@@ -729,6 +731,13 @@ using the rbd protocol.
|
||||
%endif
|
||||
|
||||
|
||||
+%package block-vitastor
|
||||
+Summary: QEMU Vitastor block driver
|
||||
+Requires: %{name}-common%{?_isa} = %{epoch}:%{version}-%{release}
|
||||
+%description block-vitastor
|
||||
+This package provides the additional Vitastor block driver for QEMU.
|
||||
+
|
||||
+
|
||||
%package audio-pa
|
||||
Summary: QEMU PulseAudio audio driver
|
||||
Requires: %{name}-common%{?_isa} = %{epoch}:%{version}-%{release}
|
||||
@@ -831,6 +840,7 @@ This package provides the additional D-B
|
||||
%prep
|
||||
%setup -q -n qemu-%{version}%{?rcstr}
|
||||
%autopatch -p1
|
||||
+cp %{SOURCE37} ./block/vitastor.c
|
||||
|
||||
%global qemu_kvm_build qemu_kvm_build
|
||||
mkdir -p %{qemu_kvm_build}
|
||||
@@ -1067,6 +1077,7 @@ run_configure \
|
||||
%if %{have_block_rbd}
|
||||
--enable-rbd \
|
||||
%endif
|
||||
+ --enable-vitastor \
|
||||
%if %{have_librdma}
|
||||
--enable-rdma \
|
||||
%endif
|
||||
@@ -1564,6 +1575,8 @@ useradd -r -u 107 -g qemu -G kvm -d / -s
|
||||
%files block-rbd
|
||||
%{_libdir}/%{name}/block-rbd.so
|
||||
%endif
|
||||
+%files block-vitastor
|
||||
+%{_libdir}/%{name}/block-vitastor.so
|
||||
%files audio-pa
|
||||
%{_libdir}/%{name}/audio-pa.so
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
Name: vitastor
|
||||
Version: 3.1.0
|
||||
Version: 3.2.3
|
||||
Release: 1%{?dist}
|
||||
Summary: Vitastor, a fast software-defined clustered block storage
|
||||
|
||||
License: Vitastor Network Public License 1.1
|
||||
URL: https://vitastor.io/
|
||||
Source0: vitastor-3.1.0.el10.tar.gz
|
||||
Source0: vitastor-3.2.3.el10.tar.gz
|
||||
|
||||
BuildRequires: gperftools-devel
|
||||
BuildRequires: gcc-c++
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
Name: vitastor
|
||||
Version: 3.1.0
|
||||
Version: 3.2.3
|
||||
Release: 1%{?dist}
|
||||
Summary: Vitastor, a fast software-defined clustered block storage
|
||||
|
||||
License: Vitastor Network Public License 1.1
|
||||
URL: https://vitastor.io/
|
||||
Source0: vitastor-3.1.0.el7.tar.gz
|
||||
Source0: vitastor-3.2.3.el7.tar.gz
|
||||
|
||||
BuildRequires: gperftools-devel
|
||||
BuildRequires: devtoolset-9-gcc-c++
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
Name: vitastor
|
||||
Version: 3.1.0
|
||||
Version: 3.2.3
|
||||
Release: 1%{?dist}
|
||||
Summary: Vitastor, a fast software-defined clustered block storage
|
||||
|
||||
License: Vitastor Network Public License 1.1
|
||||
URL: https://vitastor.io/
|
||||
Source0: vitastor-3.1.0.el8.tar.gz
|
||||
Source0: vitastor-3.2.3.el8.tar.gz
|
||||
|
||||
BuildRequires: gperftools-devel
|
||||
BuildRequires: gcc-toolset-9-gcc-c++
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
Name: vitastor
|
||||
Version: 3.1.0
|
||||
Version: 3.2.3
|
||||
Release: 1%{?dist}
|
||||
Summary: Vitastor, a fast software-defined clustered block storage
|
||||
|
||||
License: Vitastor Network Public License 1.1
|
||||
URL: https://vitastor.io/
|
||||
Source0: vitastor-3.1.0.el9.tar.gz
|
||||
Source0: vitastor-3.2.3.el9.tar.gz
|
||||
|
||||
BuildRequires: gperftools-devel
|
||||
BuildRequires: gcc-c++
|
||||
|
||||
@@ -21,8 +21,11 @@ if("${CMAKE_INSTALL_PREFIX}" MATCHES "^/usr/local/?$")
|
||||
endif()
|
||||
set(ENABLE_COVERAGE false CACHE BOOL "Enable code coverage")
|
||||
|
||||
add_definitions(-DVITASTOR_VERSION="3.1.0")
|
||||
add_definitions(-D_GNU_SOURCE -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64 -Wall -Wno-sign-compare -Wno-comment -Wno-parentheses -Wno-pointer-arith -fdiagnostics-color=always -fno-omit-frame-pointer -fvisibility=hidden -I ${CMAKE_SOURCE_DIR}/src)
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
|
||||
add_definitions(-DVITASTOR_VERSION="3.2.3")
|
||||
add_definitions(-D_GNU_SOURCE -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64 -Wall -Wno-c99-designator -Wno-vla-cxx-extension -Wno-sign-compare -Wno-comment -Wno-parentheses -Wno-pointer-arith -fdiagnostics-color=always -fno-omit-frame-pointer -fvisibility=hidden -I ${CMAKE_SOURCE_DIR}/src)
|
||||
add_link_options(-fno-omit-frame-pointer)
|
||||
if (${WITH_ASAN})
|
||||
add_definitions(-fsanitize=address)
|
||||
|
||||
@@ -34,7 +34,8 @@
|
||||
#define BS_OP_DELETE 6
|
||||
#define BS_OP_LIST 7
|
||||
#define BS_OP_ROLLBACK 8
|
||||
#define BS_OP_MAX 8
|
||||
#define BS_OP_TOMBSTONE 9
|
||||
#define BS_OP_MAX 9
|
||||
|
||||
#define BS_OP_PRIVATE_DATA_SIZE 256
|
||||
|
||||
@@ -77,8 +78,12 @@ Output:
|
||||
- retval = number of bytes actually read/written or negative error number
|
||||
-EINVAL = invalid input parameters
|
||||
-ENOENT = requested object/version does not exist for reads
|
||||
-ENODATA = requested object/version is a tombstone
|
||||
-EEXIST = requested version to write already exists
|
||||
-ENOSPC = no space left in the store for writes
|
||||
-EDOM = checksum error.
|
||||
-EAGAIN = temporary failure, operation should be retried (notably, writes may be retried
|
||||
after stabilizing some journaled entries and freeing up journal space)
|
||||
-EDOM = checksum error
|
||||
- version = the version actually read or written
|
||||
|
||||
## BS_OP_DELETE
|
||||
@@ -87,19 +92,44 @@ Delete an object.
|
||||
|
||||
Input:
|
||||
- oid = requested object
|
||||
- version = requested version. Treated the same as with BS_OP_WRITE
|
||||
- version = requested version. Treated the same as with BS_OP_WRITE, except that a delete
|
||||
is guarded: if the object's current head version is greater than `version`, the object
|
||||
was recreated above this delete and it's skipped (retval = 0). version = 0 means an
|
||||
unconditional delete
|
||||
|
||||
Output:
|
||||
- retval = 0 or negative error number (-EINVAL)
|
||||
- retval = 0 or negative error number (-EINVAL, -EAGAIN)
|
||||
- version = the version actually written (delete is initially written as an object version)
|
||||
|
||||
## BS_OP_TOMBSTONE
|
||||
|
||||
Write a versioned deletion marker (tombstone): an object version that records the object
|
||||
as DELETED as of `version`. Unlike BS_OP_DELETE, which is physically removed from the
|
||||
index once all older versions are garbage, a tombstone persists and is reported by
|
||||
BS_OP_LIST in a dedicated tombstone section, so that "deleted" can be told apart from
|
||||
"lost" after peering. Like a delete, a tombstone is stable immediately, it erases all
|
||||
older versions of the object (they become garbage), and reads over it return -ENODATA.
|
||||
A versioned tombstone is never removed by compaction; it is only erased by a newer
|
||||
write or a newer tombstone over the same object.
|
||||
|
||||
Input:
|
||||
- oid = requested object
|
||||
- version = tombstone version. 0 = assign head_version + 1 automatically.
|
||||
A tombstone may only be written over a version strictly lower than itself; writing
|
||||
over an absent object (already deleted) is a no-op success, writing version <= the
|
||||
version already present returns -EEXIST for data heads.
|
||||
|
||||
Output:
|
||||
- retval = 0, -EEXIST or negative error number (-EINVAL, -EAGAIN, -ENOSPC)
|
||||
- version = the tombstone version actually written
|
||||
|
||||
## BS_OP_SYNC
|
||||
|
||||
Make sure all previously issued modifications reach physical media.
|
||||
|
||||
Input: Nothing except opcode
|
||||
Output:
|
||||
- retval = 0 or negative error number (-EINVAL)
|
||||
- retval = 0 or negative error number (-EINVAL, -EAGAIN)
|
||||
|
||||
## BS_OP_STABLE / BS_OP_ROLLBACK
|
||||
|
||||
@@ -129,10 +159,18 @@ Input:
|
||||
- max_oid = max inode/stripe or 0 to list all objects
|
||||
|
||||
Output:
|
||||
- retval = total obj_ver_id count
|
||||
- retval = total obj_ver_id count or negative error number
|
||||
-ENOMEM = could not allocate memory for the listing
|
||||
-EAGAIN = pool sharding settings are incorrect, please reshard and retry
|
||||
- version = stable obj_ver_id count
|
||||
- buf = obj_ver_id array allocated by the blockstore. Stable versions come first.
|
||||
You must free it yourself after usage with free().
|
||||
- tombstone_count = number of trailing obj_ver_id entries which are versioned tombstones
|
||||
(deleted markers). The reply layout is [stable][unstable][tombstones]: entries in
|
||||
buf[retval-tombstone_count .. retval) are tombstones. When list_stable_limit is set,
|
||||
the page ends at its last stable oid: unstable and tombstone entries beyond it are
|
||||
cut, so a limited listing may omit tombstones. Consumers that must see every
|
||||
tombstone (peering) have to list without a limit.
|
||||
Output includes all objects for which (((inode + stripe / <PG alignment>) % <PG count>) == <PG number>).
|
||||
|
||||
*/
|
||||
@@ -164,6 +202,8 @@ struct __attribute__ ((visibility("default"))) blockstore_op_t
|
||||
uint32_t list_stable_limit;
|
||||
};
|
||||
};
|
||||
// BS_OP_LIST output: count of trailing tombstone entries (see BS_OP_LIST docs)
|
||||
uint64_t tombstone_count = 0;
|
||||
uint8_t *buf = NULL;
|
||||
uint8_t *bitmap = NULL;
|
||||
int64_t retval = 0;
|
||||
@@ -233,4 +273,7 @@ public:
|
||||
virtual uint64_t get_live_memory() = 0;
|
||||
virtual uint64_t get_garbage_entries() = 0;
|
||||
virtual uint64_t get_garbage_memory() = 0;
|
||||
|
||||
// Whether this store persists tombstones (BS_OP_TOMBSTONE), enabling two-phase deletes
|
||||
virtual bool supports_tombstones() { return false; }
|
||||
};
|
||||
|
||||
@@ -473,7 +473,7 @@ void blockstore_disk_t::open_journal()
|
||||
journal_fd = meta_fd;
|
||||
journal_device_sect = meta_device_sect;
|
||||
journal_device_size = 0;
|
||||
if (journal_offset >= data_device_size)
|
||||
if (journal_offset >= (meta_device_size > 0 ? meta_device_size : data_device_size))
|
||||
{
|
||||
throw std::runtime_error("journal_offset exceeds device size");
|
||||
}
|
||||
|
||||
@@ -80,6 +80,16 @@ int journal_flusher_t::get_syncing_buffer()
|
||||
return syncing_buffer;
|
||||
}
|
||||
|
||||
uint64_t journal_flusher_t::get_flushing_lsn(object_id oid)
|
||||
{
|
||||
auto it = flushing.find(oid);
|
||||
if (it == flushing.end())
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
return it->second;
|
||||
}
|
||||
|
||||
bool journal_flusher_t::is_active()
|
||||
{
|
||||
return active_flushers > 0;
|
||||
@@ -96,6 +106,20 @@ void journal_flusher_t::release_trim()
|
||||
force_start--;
|
||||
}
|
||||
|
||||
// Ask for an fsync. Used when a new entry depends on another not-yet-durable entry
|
||||
void journal_flusher_t::request_fsync()
|
||||
{
|
||||
force_start++;
|
||||
force_fsync++;
|
||||
bs->ringloop->wakeup();
|
||||
}
|
||||
|
||||
void journal_flusher_t::release_fsync()
|
||||
{
|
||||
force_fsync--;
|
||||
force_start--;
|
||||
}
|
||||
|
||||
void journal_flusher_t::dump_diagnostics()
|
||||
{
|
||||
printf(
|
||||
@@ -172,30 +196,42 @@ bool journal_flusher_co::loop()
|
||||
else if (wait_state == 17) goto resume_17;
|
||||
else if (wait_state == 18) goto resume_18;
|
||||
else if (wait_state == 19) goto resume_19;
|
||||
else if (wait_state == 20) goto resume_20;
|
||||
else if (wait_state == 21) goto resume_21;
|
||||
else if (wait_state == 22) goto resume_22;
|
||||
else if (wait_state == 23) goto resume_23;
|
||||
else if (wait_state == 24) goto resume_24;
|
||||
else if (wait_state == 25) goto resume_25;
|
||||
else if (wait_state == 26) goto resume_26;
|
||||
else if (wait_state == 27) goto resume_27;
|
||||
else if (wait_state == 28) goto resume_28;
|
||||
else if (wait_state == 29) goto resume_29;
|
||||
else if (wait_state == 30) goto resume_30;
|
||||
else if (wait_state == 31) goto resume_31;
|
||||
resume_0:
|
||||
wait_state = 0;
|
||||
wait_count = 0;
|
||||
cur_oid = {};
|
||||
res = bs->heap->get_next_compact(cur_oid);
|
||||
if ((bs->intent_write_counter >= bs->journal_trim_interval) && co_id == 0)
|
||||
if ((bs->intent_write_counter >= bs->journal_trim_interval || flusher->force_fsync > 0) && co_id == 0)
|
||||
{
|
||||
// Advance fsynced_lsn every <journal_trim_interval> intent writes
|
||||
bs->intent_write_counter = 0;
|
||||
resume_17:
|
||||
resume_18:
|
||||
resume_19:
|
||||
if (!fsync_buffer(17))
|
||||
{
|
||||
return false;
|
||||
resume_20:
|
||||
resume_21:
|
||||
if (!trim_lsn(20))
|
||||
return false;
|
||||
}
|
||||
if (bs->intent_write_counter >= bs->journal_trim_interval)
|
||||
{
|
||||
// Advance fsynced_lsn every <journal_trim_interval> intent writes
|
||||
bs->intent_write_counter = 0;
|
||||
resume_29:
|
||||
resume_30:
|
||||
resume_31:
|
||||
if (!trim_lsn(29))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (res == ENOENT && flusher->force_start > 0 && co_id == 0 &&
|
||||
(!bs->dsk.disable_journal_fsync || !bs->dsk.disable_meta_fsync || !bs->dsk.disable_data_fsync))
|
||||
@@ -231,7 +267,6 @@ resume_16:
|
||||
}
|
||||
assert(false);
|
||||
}
|
||||
flusher->flushing.insert(cur_oid);
|
||||
resume_1:
|
||||
wait_state = 1;
|
||||
should_repeat = false;
|
||||
@@ -239,7 +274,6 @@ resume_1:
|
||||
if (!cur_obj)
|
||||
{
|
||||
// Object does not exist
|
||||
flusher->flushing.erase(cur_oid);
|
||||
goto resume_0;
|
||||
}
|
||||
// Scan versions to flush
|
||||
@@ -272,11 +306,30 @@ resume_1:
|
||||
if (!compact_info.compact_lsn)
|
||||
{
|
||||
// Flushing is aborted
|
||||
flusher->flushing.erase(cur_oid);
|
||||
bs->heap->unlock_entry(cur_oid);
|
||||
goto resume_0;
|
||||
}
|
||||
flusher->flushing[cur_oid] = compact_info.compact_lsn;
|
||||
flusher->active_flushers++;
|
||||
if (!compact_info.do_delete && compact_info.clean_wr &&
|
||||
compact_info.clean_wr->type() == BS_HEAP_BIG_INTENT &&
|
||||
(!bs->dsk.csum_block_size || bs->dsk.csum_block_size > bs->dsk.bitmap_granularity))
|
||||
{
|
||||
// Compaction merges newer writes into the data block in place, which changes bytes that
|
||||
// <clean_wr>'s checksums still describe. Reads never take those bytes from it, but the
|
||||
// startup recheck does, and it can only skip the overwritten parts when a checksum block
|
||||
// covers exactly one write granule. With a larger block an overwritten part poisons the
|
||||
// checksum of the whole block, and with checksums disabled a big_intent still carries a
|
||||
// single checksum of its whole extent - it's the only way to tell an unfinished in-place
|
||||
// write from a finished one. Either way see blockstore_heap_t::recheck_verify().
|
||||
// So make sure the entry is out of the recheck's scope by persisting completed_lsn first.
|
||||
// It is below fsynced_lsn already - iterate_compaction() doesn't return anything above it
|
||||
resume_26:
|
||||
resume_27:
|
||||
resume_28:
|
||||
if (!trim_lsn(26))
|
||||
return false;
|
||||
}
|
||||
for (i = 0; i < read_vec.size(); i++)
|
||||
{
|
||||
if ((read_vec[i].copy_flags & COPY_BUF_JOURNAL) &&
|
||||
@@ -295,7 +348,13 @@ resume_1:
|
||||
{
|
||||
printf("Compacting %jx:%jx up to l%ju (delete)\n", cur_oid.inode, cur_oid.stripe, compact_info.compact_lsn);
|
||||
}
|
||||
// Delete discards everything, so reset to the empty state
|
||||
clean_loc = UINT64_MAX;
|
||||
read_vec.clear();
|
||||
csum_copy.clear();
|
||||
copy_count = 0;
|
||||
memset(new_bmp, 0, bs->dsk.clean_entry_bitmap_size);
|
||||
memset(new_ext_bmp, 0, bs->dsk.clean_entry_bitmap_size);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -317,8 +376,9 @@ resume_1:
|
||||
for (size_t i = csum_copy.size(); i > 0; i--)
|
||||
{
|
||||
auto wr = csum_copy[i-1];
|
||||
memcpy(new_csums + wr->small().offset/bs->dsk.csum_block_size*(bs->dsk.data_csum_type & 0xFF),
|
||||
wr->get_checksums(bs->heap), wr->small().len/bs->dsk.csum_block_size*(bs->dsk.data_csum_type & 0xFF));
|
||||
if (wr->small().len > 0)
|
||||
memcpy(new_csums + wr->small().offset/bs->dsk.csum_block_size*(bs->dsk.data_csum_type & 0xFF),
|
||||
wr->get_checksums(bs->heap), wr->small().len/bs->dsk.csum_block_size*(bs->dsk.data_csum_type & 0xFF));
|
||||
}
|
||||
csum_copy.clear();
|
||||
}
|
||||
@@ -482,12 +542,12 @@ resume_13:
|
||||
printf("Compacted %jx:%jx l%ju (%d writes)\n", cur_oid.inode, cur_oid.stripe, compact_info.compact_lsn, copy_count);
|
||||
}
|
||||
flusher->active_flushers--;
|
||||
flusher->flushing.erase(cur_oid);
|
||||
if (should_repeat)
|
||||
{
|
||||
// Flush the same object again
|
||||
goto resume_1;
|
||||
}
|
||||
flusher->flushing.erase(cur_oid);
|
||||
// All done
|
||||
goto resume_0;
|
||||
}
|
||||
@@ -533,7 +593,7 @@ void journal_flusher_co::fill_partial_checksum_blocks()
|
||||
}
|
||||
auto & vec = read_vec[read_vec.size()-1];
|
||||
read_vec.insert(read_vec.begin()+vec_pos, (copy_buffer_t){
|
||||
.copy_flags = COPY_BUF_JOURNAL|COPY_BUF_COALESCED,
|
||||
.copy_flags = COPY_BUF_DATA|COPY_BUF_COALESCED,
|
||||
.offset = hole_start,
|
||||
.len = hole_end - hole_start,
|
||||
.disk_offset = hole_start,
|
||||
@@ -708,9 +768,11 @@ bool journal_flusher_co::read_buffered(int wait_base)
|
||||
else if (wait_state == wait_base+1)
|
||||
goto resume_1;
|
||||
wait_count = 0;
|
||||
if (bs->dsk.inmemory_journal && !read_to_fill_incomplete)
|
||||
if (bs->dsk.inmemory_journal && bs->dsk.csum_block_size <= bs->dsk.bitmap_granularity)
|
||||
{
|
||||
// Happy path: nothing to read :)
|
||||
// We may have to read intent writes to recalculate block checksums, so proceed
|
||||
// even if read_to_fill_incomplete is false, but csum_block_size is > bitmap_granularity
|
||||
return true;
|
||||
}
|
||||
for (i = 0; i < read_vec.size(); i++)
|
||||
@@ -879,27 +941,40 @@ bool journal_flusher_co::trim_lsn(int wait_base)
|
||||
{
|
||||
if (wait_state == wait_base) goto resume_0;
|
||||
else if (wait_state == wait_base+1) goto resume_1;
|
||||
else if (wait_state == wait_base+2) goto resume_2;
|
||||
resume_0:
|
||||
if (flusher->trimming_lsn)
|
||||
{
|
||||
// Allow only one coroutine to update the superblock at a time to prevent parallel
|
||||
// block updates or the device may in theory apply them in any order.
|
||||
wait_state = wait_base;
|
||||
return false;
|
||||
}
|
||||
fsynced_lsn = bs->heap->get_fsynced_lsn();
|
||||
if (((blockstore_meta_header_v3_t*)bs->meta_superblock)->completed_lsn == fsynced_lsn)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
flusher->trimming_lsn = true;
|
||||
flusher->active_flushers++;
|
||||
((blockstore_meta_header_v3_t*)bs->meta_superblock)->completed_lsn = fsynced_lsn;
|
||||
((blockstore_meta_header_v3_t*)bs->meta_superblock)->set_crc32c();
|
||||
await_sqe(0);
|
||||
await_sqe(1);
|
||||
data->iov = (struct iovec){ bs->meta_superblock, (size_t)bs->dsk.meta_block_size };
|
||||
data->callback = simple_callback_w;
|
||||
io_uring_prep_writev(sqe, bs->dsk.meta_fd, &data->iov, 1, bs->dsk.meta_offset);
|
||||
// Update superblock with datasync
|
||||
sqe->rw_flags = RWF_DSYNC;
|
||||
wait_count++;
|
||||
resume_1:
|
||||
resume_2:
|
||||
if (wait_count > 0)
|
||||
{
|
||||
wait_state = wait_base+1;
|
||||
wait_state = wait_base+2;
|
||||
return false;
|
||||
}
|
||||
// Superblock is updated, resume everyone who was waiting for it
|
||||
flusher->trimming_lsn = false;
|
||||
bs->ringloop->wakeup();
|
||||
flusher->active_flushers--;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -93,25 +93,30 @@ public:
|
||||
class journal_flusher_t
|
||||
{
|
||||
int force_start = 0;
|
||||
int force_fsync = 0;
|
||||
int min_flusher_count = 0, max_flusher_count = 0, cur_flusher_count = 0, target_flusher_count = 0;
|
||||
journal_flusher_co *co;
|
||||
blockstore_impl_t *bs;
|
||||
friend class journal_flusher_co;
|
||||
|
||||
robin_hood::unordered_flat_set<object_id> flushing;
|
||||
robin_hood::unordered_flat_map<object_id, uint64_t> flushing;
|
||||
int active_flushers = 0;
|
||||
std::list<flusher_data_sync_t> data_syncs;
|
||||
int wanting_meta_fsync = 0;
|
||||
bool fsyncing_meta = false;
|
||||
int syncing_buffer = 0;
|
||||
bool trimming_lsn = false;
|
||||
|
||||
public:
|
||||
journal_flusher_t(blockstore_impl_t *bs);
|
||||
~journal_flusher_t();
|
||||
void loop();
|
||||
int get_syncing_buffer();
|
||||
uint64_t get_flushing_lsn(object_id oid);
|
||||
bool is_active();
|
||||
void request_trim();
|
||||
void release_trim();
|
||||
void request_fsync();
|
||||
void release_fsync();
|
||||
void dump_diagnostics();
|
||||
};
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// Copyright (c) Vitaliy Filippov, 2025+
|
||||
// License: VNPL-1.1 (see README.md for details)
|
||||
|
||||
#undef NDEBUG
|
||||
#include <assert.h>
|
||||
#include <string.h>
|
||||
#include <stddef.h>
|
||||
@@ -196,7 +197,10 @@ uint32_t *heap_entry_t::get_checksum(blockstore_heap_t *heap)
|
||||
{
|
||||
if (type() == BS_HEAP_SMALL_WRITE || type() == BS_HEAP_INTENT_WRITE)
|
||||
{
|
||||
if (heap->dsk->csum_block_size || small().len == 0)
|
||||
// a zero-length small_write still has a checksum slot reserved by
|
||||
// get_small_entry_size when block checksums are off, and its entry
|
||||
// checksum covers it - so it has to be filled with a defined value
|
||||
if (heap->dsk->csum_block_size)
|
||||
return NULL;
|
||||
return (uint32_t*)((uint8_t*)this + sizeof(heap_small_write_t) + heap->dsk->clean_entry_bitmap_size);
|
||||
}
|
||||
@@ -299,6 +303,14 @@ blockstore_heap_t::~blockstore_heap_t()
|
||||
void blockstore_heap_t::start_load(uint64_t completed_lsn)
|
||||
{
|
||||
this->completed_lsn = completed_lsn;
|
||||
// The persisted completed_lsn may be larger than the lsn of the last entry which survived:
|
||||
// entries above it were still in flight when the power went away. New entries must never
|
||||
// reuse an lsn which is at or below completed_lsn, or on the next load they'd look already
|
||||
// fsynced and escape the rollback of unfinished writes
|
||||
if (completed_lsn > next_lsn)
|
||||
{
|
||||
next_lsn = completed_lsn;
|
||||
}
|
||||
}
|
||||
|
||||
int blockstore_heap_t::read_blocks(uint64_t disk_offset, uint64_t disk_size, uint8_t *buf, bool allow_corrupted,
|
||||
@@ -421,7 +433,7 @@ corrupted_object:
|
||||
if ((wr->type() == BS_HEAP_BIG_INTENT || wr->type() == BS_HEAP_BIG_WRITE) &&
|
||||
wr->big().block_num >= dsk->block_count)
|
||||
{
|
||||
fprintf(stderr, "Error: big_write or big_intent entry %jx:%jx v%ju block_num is too large: %u > %lu. Metadata is incompatible with current parameters. ",
|
||||
fprintf(stderr, "Error: big_write or big_intent entry %jx:%jx v%ju block_num is too large: %u > %ju. Metadata is incompatible with current parameters. ",
|
||||
wr->inode, wr->stripe, wr->version, wr->big_intent().block_num, dsk->block_count);
|
||||
goto corrupted_object;
|
||||
}
|
||||
@@ -560,7 +572,7 @@ void blockstore_heap_t::finish_load()
|
||||
if (postponed_items.size())
|
||||
{
|
||||
// Sort "postponed" items and load in batches
|
||||
std::sort(postponed_items.begin(), postponed_items.end(), [this](const heap_list_item_t* a, const heap_list_item_t* b)
|
||||
std::sort(postponed_items.begin(), postponed_items.end(), [](const heap_list_item_t* a, const heap_list_item_t* b)
|
||||
{
|
||||
return a->entry.inode < b->entry.inode || a->entry.inode == b->entry.inode &&
|
||||
(a->entry.stripe < b->entry.stripe || a->entry.stripe == b->entry.stripe &&
|
||||
@@ -580,6 +592,52 @@ void blockstore_heap_t::finish_load()
|
||||
}
|
||||
}
|
||||
|
||||
// Count the newest entries of the object which have to be rechecked after a restart, i.e.
|
||||
// the ones whose data may be absent from the disk even though the entry itself is there.
|
||||
// Those are buffered small writes - their data is written in parallel with the entry - and
|
||||
// the newest intent write if it wasn't fsynced yet.
|
||||
// A big-redirect intent may also be hidden under a series of small writes: it is acked as
|
||||
// soon as its entry is written, without an explicit data fsync, so a power outage may drop
|
||||
// its data from the disk cache while keeping the entry. Its data block belongs to it alone,
|
||||
// so rechecking it is always safe. In-place intent writes are only rechecked when they're
|
||||
// the newest entry - the block under them may have been rewritten by a later compaction,
|
||||
// which would make the recheck fail on perfectly good data.
|
||||
// <need_data> is set if any of them requires reading the data device, i.e. if the recheck
|
||||
// can't be done synchronously in memory.
|
||||
// Commit and rollback entries carry no data of their own, but they're kept in the object's
|
||||
// chain, so a stabilize or a rollback right after a write leaves one sitting on top of - or
|
||||
// in between - the writes whose data still has to be rechecked. Skip over them.
|
||||
heap_entry_t *blockstore_heap_t::skip_commits(heap_entry_t *wr)
|
||||
{
|
||||
while (wr && (wr->type() == BS_HEAP_COMMIT || wr->type() == BS_HEAP_ROLLBACK))
|
||||
{
|
||||
wr = prev(wr);
|
||||
}
|
||||
return wr;
|
||||
}
|
||||
|
||||
int blockstore_heap_t::count_recheck_entries(heap_entry_t *obj, bool & need_data)
|
||||
{
|
||||
int count = 0;
|
||||
need_data = false;
|
||||
auto wr = skip_commits(obj);
|
||||
auto newest = wr;
|
||||
for (; wr && wr->type() == BS_HEAP_SMALL_WRITE; wr = skip_commits(prev(wr)))
|
||||
{
|
||||
// Zero-sized writes have nothing to read and verify
|
||||
if (wr->small().len > 0)
|
||||
count++;
|
||||
}
|
||||
if (wr && wr->lsn > completed_lsn &&
|
||||
(wr->type() == BS_HEAP_BIG_INTENT || wr == newest && wr->type() == BS_HEAP_INTENT_WRITE) &&
|
||||
(wr->type() == BS_HEAP_BIG_INTENT ? wr->big_intent().len : wr->small().len) > 0)
|
||||
{
|
||||
count++;
|
||||
need_data = true;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
void blockstore_heap_t::fill_recheck_queue()
|
||||
{
|
||||
for (auto & pgp: block_index)
|
||||
@@ -589,9 +647,8 @@ void blockstore_heap_t::fill_recheck_queue()
|
||||
inode_map_iterate(ip.second, [&](heap_list_item_t *li)
|
||||
{
|
||||
auto obj = &li->entry;
|
||||
// Recheck only the latest intent_write (if after completed_lsn) or a series of small_writes
|
||||
if ((obj->type() == BS_HEAP_INTENT_WRITE || obj->type() == BS_HEAP_BIG_INTENT)
|
||||
&& obj->lsn > completed_lsn || obj->type() == BS_HEAP_SMALL_WRITE)
|
||||
bool need_data = false;
|
||||
if (count_recheck_entries(obj, need_data) > 0)
|
||||
{
|
||||
recheck_queue.push_back(obj);
|
||||
}
|
||||
@@ -621,8 +678,10 @@ int blockstore_heap_t::mark_used_blocks()
|
||||
res = EDOM;
|
||||
return;
|
||||
}
|
||||
if (wr->entry_type == (BS_HEAP_DELETE|BS_HEAP_STABLE) && !li->prev)
|
||||
if (wr->entry_type == (BS_HEAP_DELETE|BS_HEAP_STABLE) && !li->prev &&
|
||||
wr->version == 0)
|
||||
{
|
||||
// Without a version it's a delete, not a tombstone
|
||||
wr->set_garbage();
|
||||
garbage_entries++;
|
||||
garbage_memory += list_item_overhead(wr->size);
|
||||
@@ -664,10 +723,9 @@ int blockstore_heap_t::mark_used_blocks()
|
||||
{
|
||||
if (dsk->skip_double_claim)
|
||||
{
|
||||
// There is a BUG currently:
|
||||
// Sometimes (under unknown conditions) deletion entries are removed from the disk
|
||||
// earlier than previous big_writes.
|
||||
// Until it's fixed, we provide a way to ignore such objects on start.
|
||||
// There was a bug in 3.0.x before 3.0.16 - deletion entries were sometimes
|
||||
// removed from the disk earlier than previous big_writes. Provide a workaround
|
||||
// for stores affected by this bug: ignore such objects on start.
|
||||
auto prev_li = used_by[wr->big().block_num];
|
||||
assert(prev_li);
|
||||
// Newer LSN must be trusted. Remove the older object.
|
||||
@@ -877,13 +935,27 @@ void blockstore_heap_t::recheck_full_gc()
|
||||
}
|
||||
}
|
||||
|
||||
// The entries which were hiding under the ones just dropped are the newest ones of the object
|
||||
// now, and their data may be unfinished just as well - a redirect intent acked without a data
|
||||
// fsync, or a buffered small write, both of which the outage may have left without their data.
|
||||
// So look at what became visible and recheck it too
|
||||
void blockstore_heap_t::recheck_requeue(object_id oid)
|
||||
{
|
||||
auto obj = read_entry(oid);
|
||||
if (obj)
|
||||
{
|
||||
recheck_queue.push_back(obj);
|
||||
}
|
||||
}
|
||||
|
||||
void blockstore_heap_t::recheck_drop_entries(heap_entry_t *obj, heap_entry_t *bad_wr)
|
||||
{
|
||||
// write entry is invalid, erase it and all newer entries
|
||||
int bad_count = 1;
|
||||
for (auto wr = obj; wr && wr != bad_wr; wr = prev(wr))
|
||||
{
|
||||
bad_count++;
|
||||
if (wr->type() != BS_HEAP_COMMIT && wr->type() != BS_HEAP_ROLLBACK)
|
||||
bad_count++;
|
||||
}
|
||||
auto prev_wr = prev(bad_wr);
|
||||
if (prev_wr)
|
||||
@@ -899,21 +971,94 @@ void blockstore_heap_t::recheck_drop_entries(heap_entry_t *obj, heap_entry_t *ba
|
||||
while (li && prev_wr != &li->entry)
|
||||
{
|
||||
auto prev = li->prev;
|
||||
assert(li->entry.type() == bad_wr->type());
|
||||
auto type = li->entry.type();
|
||||
if ((type == BS_HEAP_COMMIT || type == BS_HEAP_ROLLBACK) && li->entry.version < bad_wr->version)
|
||||
{
|
||||
// A commit or a rollback of an older version refers to versions which are below
|
||||
// the unfinished write and survive it, so it has to survive too - otherwise a
|
||||
// version the client was told is stable would silently become unstable again
|
||||
li = prev;
|
||||
continue;
|
||||
}
|
||||
// Small writes may be stacked on top of an intent write, so the types may differ
|
||||
assert(type == BS_HEAP_SMALL_WRITE || type == BS_HEAP_INTENT_WRITE ||
|
||||
type == BS_HEAP_BIG_INTENT || type == BS_HEAP_COMMIT || type == BS_HEAP_ROLLBACK);
|
||||
init_erase_bad_entry(li);
|
||||
unlink_list_item(li);
|
||||
li = prev;
|
||||
}
|
||||
}
|
||||
|
||||
void blockstore_heap_t::recheck_start_reads(heap_recheck_state_t *st)
|
||||
// Verify the data of a rechecked entry, skipping the checksum blocks which newer entries of the
|
||||
// same object overwrite. Compaction merges those newer writes into the data block in place: it
|
||||
// changes bytes which <wr>'s checksums still describe, without touching <wr> itself. Nothing ever
|
||||
// reads those bytes from <wr> - they're shadowed - so a mismatch there means nothing.
|
||||
// A shadow only holds while the entry casting it stays, though: the very same recheck may find
|
||||
// that newer entry unfinished and drop it, and then the bytes under it become visible again.
|
||||
// So entries which this recheck is about to drop cast no shadow. This is why the entry needing
|
||||
// a data read is always verified last, see recheck_start_reads() - by then it is already known
|
||||
// which of the entries above it survive.
|
||||
// This is only exact while a checksum block isn't larger than the write granularity. With larger
|
||||
// blocks an overwritten part poisons the checksum of the whole block, and skipping the block
|
||||
// would hide a genuinely unfinished write in the rest of it - so there the flusher instead makes
|
||||
// sure such an entry is below the persisted completed_lsn and never gets rechecked at all,
|
||||
// see the big_intent trim in journal_flusher_co::loop()
|
||||
bool blockstore_heap_t::recheck_verify(heap_recheck_state_t *st, heap_entry_t *wr, uint8_t *buf)
|
||||
{
|
||||
auto obj = st->obj;
|
||||
if (!dsk->csum_block_size || dsk->csum_block_size > dsk->bitmap_granularity ||
|
||||
wr == obj || wr->type() == BS_HEAP_SMALL_WRITE)
|
||||
{
|
||||
// The newest entry isn't shadowed by anything, and a small write has its own copy
|
||||
// of the data in the buffer area which compaction only ever reads
|
||||
return calc_checksums(wr, buf, false);
|
||||
}
|
||||
uint32_t start = 0, end = 0;
|
||||
uint8_t *bitmap = NULL;
|
||||
if (wr->type() == BS_HEAP_BIG_INTENT)
|
||||
{
|
||||
start = wr->big_intent().offset;
|
||||
end = start + wr->big_intent().len;
|
||||
bitmap = wr->get_int_bitmap(this);
|
||||
}
|
||||
else
|
||||
{
|
||||
assert(wr->type() == BS_HEAP_INTENT_WRITE);
|
||||
start = wr->small().offset;
|
||||
end = start + wr->small().len;
|
||||
}
|
||||
uint32_t csum_size = (dsk->data_csum_type & 0xFF);
|
||||
uint8_t *csums = wr->get_checksums(this);
|
||||
if (wr->type() == BS_HEAP_BIG_INTENT)
|
||||
csums += start/dsk->csum_block_size * csum_size;
|
||||
bool ok = true;
|
||||
for (uint32_t pos = start; pos < end; pos += dsk->csum_block_size)
|
||||
{
|
||||
bool shadowed = false;
|
||||
for (auto newer = obj; newer && newer != wr && !shadowed; newer = prev(newer))
|
||||
{
|
||||
if (newer->type() != BS_HEAP_SMALL_WRITE && newer->type() != BS_HEAP_INTENT_WRITE ||
|
||||
st->bad_wr && newer->lsn >= st->bad_wr->lsn)
|
||||
continue;
|
||||
shadowed = newer->small().offset < pos+dsk->csum_block_size &&
|
||||
newer->small().offset+newer->small().len > pos;
|
||||
}
|
||||
if (shadowed)
|
||||
continue;
|
||||
ok = calc_block_checksums((uint32_t*)(csums + (pos-start)/dsk->csum_block_size * csum_size),
|
||||
buf + (pos-start), bitmap, pos, pos+dsk->csum_block_size, false, NULL) && ok;
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
int blockstore_heap_t::recheck_start_reads(heap_recheck_state_t *st)
|
||||
{
|
||||
int started = 0;
|
||||
if (st->sent_reads >= st->total_reads)
|
||||
return;
|
||||
return 0;
|
||||
while (recheck_in_progress < recheck_queue_depth)
|
||||
{
|
||||
auto wr = st->next_wr;
|
||||
st->next_wr = prev(st->next_wr);
|
||||
auto wr = skip_commits(st->next_wr);
|
||||
uint64_t loc = 0, len = 0;
|
||||
bool from_data = false;
|
||||
if (wr->type() == BS_HEAP_SMALL_WRITE)
|
||||
@@ -948,6 +1093,21 @@ void blockstore_heap_t::recheck_start_reads(heap_recheck_state_t *st)
|
||||
len = wr->small().len;
|
||||
from_data = true;
|
||||
}
|
||||
if (!len)
|
||||
{
|
||||
// Zero-sized entries have nothing to read and verify
|
||||
st->next_wr = prev(wr);
|
||||
continue;
|
||||
}
|
||||
if (from_data && st->checked_reads < st->sent_reads)
|
||||
{
|
||||
// Part of this entry's data may be shadowed by the newer entries of the same
|
||||
// object, and whether it really is depends on whether they survive the recheck.
|
||||
// So verify it only when all of them are already verified - see recheck_verify()
|
||||
break;
|
||||
}
|
||||
st->next_wr = prev(wr);
|
||||
st->oldest_wr = wr;
|
||||
st->sent_reads++;
|
||||
recheck_in_progress++;
|
||||
recheck_pending_reads--;
|
||||
@@ -955,20 +1115,32 @@ void blockstore_heap_t::recheck_start_reads(heap_recheck_state_t *st)
|
||||
recheck_cb(from_data, loc, len, [this, st, wr](uint8_t *buf)
|
||||
{
|
||||
st->checked_reads++;
|
||||
if (!calc_checksums(wr, buf, false))
|
||||
if (!recheck_verify(st, wr, buf))
|
||||
st->bad_wr = !st->bad_wr || st->bad_wr->lsn > wr->lsn ? wr : st->bad_wr;
|
||||
if (st->checked_reads >= st->total_reads)
|
||||
{
|
||||
if (st->bad_wr)
|
||||
recheck_drop_entries(st->obj, st->bad_wr);
|
||||
recheck_states.erase(st->obj);
|
||||
auto bad_wr = st->bad_wr;
|
||||
auto obj = st->obj;
|
||||
// Entries below the oldest one we read are unverified, the rest of the set
|
||||
// is already known to be good
|
||||
bool check_more = (bad_wr && bad_wr == st->oldest_wr);
|
||||
recheck_states.erase(obj);
|
||||
if (bad_wr)
|
||||
{
|
||||
object_id oid = { .inode = obj->inode, .stripe = obj->stripe };
|
||||
recheck_drop_entries(obj, bad_wr);
|
||||
if (check_more)
|
||||
recheck_requeue(oid);
|
||||
}
|
||||
}
|
||||
recheck_in_progress--;
|
||||
recheck_small_writes(NULL, 0);
|
||||
});
|
||||
started++;
|
||||
if (is_last)
|
||||
break;
|
||||
}
|
||||
return started;
|
||||
}
|
||||
|
||||
bool blockstore_heap_t::recheck_small_writes(std::function<void(bool is_data, uint64_t offset, uint64_t len, std::function<void(uint8_t* buf)>)> read_buffer, int queue_depth)
|
||||
@@ -992,26 +1164,52 @@ bool blockstore_heap_t::recheck_small_writes(std::function<void(bool is_data, ui
|
||||
in_recheck = true;
|
||||
while (recheck_pending_reads > 0 && recheck_in_progress < recheck_queue_depth)
|
||||
{
|
||||
int started = 0;
|
||||
for (auto & sp: recheck_states)
|
||||
recheck_start_reads(&sp.second);
|
||||
started += recheck_start_reads(&sp.second);
|
||||
if (!started)
|
||||
{
|
||||
// Everything left is postponed until the reads in flight complete
|
||||
break;
|
||||
}
|
||||
}
|
||||
while (recheck_queue.size() > 0 && recheck_in_progress < recheck_queue_depth)
|
||||
{
|
||||
heap_entry_t *obj = recheck_queue.front();
|
||||
recheck_queue.pop_front();
|
||||
if (obj->type() == BS_HEAP_SMALL_WRITE && buffer_area)
|
||||
bool need_data = false;
|
||||
int recheck_count = count_recheck_entries(obj, need_data);
|
||||
if (!recheck_count)
|
||||
{
|
||||
// Nothing left to recheck - the object was requeued after a drop which exposed
|
||||
// entries that are already known to be good
|
||||
continue;
|
||||
}
|
||||
if (!need_data && buffer_area)
|
||||
{
|
||||
// Check this object synchronously
|
||||
heap_entry_t *bad_wr = NULL;
|
||||
for (auto wr = obj; wr && wr->type() == BS_HEAP_SMALL_WRITE; wr = prev(wr))
|
||||
heap_entry_t *bad_wr = NULL, *oldest_wr = NULL;
|
||||
int checked = 0;
|
||||
auto wr = skip_commits(obj);
|
||||
for (; wr && wr->type() == BS_HEAP_SMALL_WRITE && checked < recheck_count; wr = skip_commits(prev(wr)))
|
||||
{
|
||||
if (!wr->small().len)
|
||||
continue;
|
||||
fprintf(stderr, "Notice: rechecking %jx:%jx l%ju - %u bytes at %ju in buffer area\n",
|
||||
wr->inode, wr->stripe, wr->lsn, wr->small().len, wr->small().location);
|
||||
oldest_wr = wr;
|
||||
checked++;
|
||||
if (!calc_checksums(wr, buffer_area + wr->small().location, false))
|
||||
bad_wr = wr;
|
||||
}
|
||||
if (bad_wr)
|
||||
{
|
||||
object_id oid = { .inode = obj->inode, .stripe = obj->stripe };
|
||||
bool check_more = (bad_wr == oldest_wr);
|
||||
recheck_drop_entries(obj, bad_wr);
|
||||
if (check_more)
|
||||
recheck_requeue(oid);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -1019,10 +1217,7 @@ bool blockstore_heap_t::recheck_small_writes(std::function<void(bool is_data, ui
|
||||
auto & st = recheck_states[obj];
|
||||
st.obj = obj;
|
||||
st.next_wr = obj;
|
||||
st.total_reads = 1;
|
||||
if (obj->type() == BS_HEAP_SMALL_WRITE)
|
||||
for (auto wr = prev(obj); wr && wr->type() == BS_HEAP_SMALL_WRITE; wr = prev(wr))
|
||||
st.total_reads++;
|
||||
st.total_reads = recheck_count;
|
||||
recheck_pending_reads += st.total_reads;
|
||||
recheck_start_reads(&st);
|
||||
}
|
||||
@@ -1063,6 +1258,8 @@ int blockstore_heap_t::finish_recheck()
|
||||
}
|
||||
completed_lsn = next_lsn;
|
||||
first_inflight_lsn = next_lsn+1;
|
||||
// Everything we just loaded from disk is durable by definition
|
||||
fsynced_lsn = next_lsn;
|
||||
std::sort(compact_queue.begin(), compact_queue.end(), [this](const object_id & a, const object_id & b)
|
||||
{
|
||||
auto ao = read_entry(a);
|
||||
@@ -1092,6 +1289,12 @@ bool blockstore_heap_t::calc_checksums(heap_entry_t *wr, uint8_t *data, bool set
|
||||
len = wr->big_intent().len;
|
||||
else
|
||||
assert(0);
|
||||
if (!len)
|
||||
{
|
||||
if (set)
|
||||
*wr_csum = 0;
|
||||
return true;
|
||||
}
|
||||
uint32_t real_csum = 0;
|
||||
if (dsk->data_csum_type == BLOCKSTORE_CSUM_XXH3_32)
|
||||
real_csum = (uint32_t)XXH3_64bits(data, len);
|
||||
@@ -1470,8 +1673,24 @@ void blockstore_heap_t::gc_block(heap_block_info_t & inf)
|
||||
}
|
||||
}
|
||||
|
||||
int blockstore_heap_t::allocate_entry(uint32_t entry_size, uint32_t *block_num, bool allow_last_free)
|
||||
// When the previous object's entry is not fsynced yet, we can't write a new one EXCEPT into
|
||||
// the same block which is passed here as <prefer_block>. If prefer_block is set but we can't
|
||||
// write into it right now, we return EAGAIN.
|
||||
int blockstore_heap_t::allocate_entry(uint32_t entry_size, uint32_t *block_num, bool allow_last_free, uint32_t prefer_block)
|
||||
{
|
||||
if (prefer_block != UINT32_MAX)
|
||||
{
|
||||
auto & inf = block_info.at(prefer_block);
|
||||
// A block accumulates a consecutive LSN range only, see modify_alloc() below
|
||||
if (inf.is_writing ||
|
||||
inf.mod_lsn_to && inf.mod_lsn_to != next_lsn ||
|
||||
inf.used_space - inf.garbage_space + entry_size > dsk->meta_block_size)
|
||||
{
|
||||
return EAGAIN;
|
||||
}
|
||||
last_allocated_block = prefer_block;
|
||||
goto allocated;
|
||||
}
|
||||
if (last_allocated_block != UINT32_MAX)
|
||||
{
|
||||
// First try to write into the same block as the previous time
|
||||
@@ -1534,6 +1753,7 @@ int blockstore_heap_t::allocate_entry(uint32_t entry_size, uint32_t *block_num,
|
||||
return ENOSPC;
|
||||
}
|
||||
}
|
||||
allocated:
|
||||
// Write into the same block
|
||||
*block_num = last_allocated_block;
|
||||
modify_alloc(last_allocated_block, [&](heap_block_info_t & inf)
|
||||
@@ -1600,11 +1820,15 @@ void blockstore_heap_t::insert_list_items(heap_list_item_t** v, size_t count, bo
|
||||
}
|
||||
}
|
||||
|
||||
int blockstore_heap_t::add_entry(uint32_t wr_size, uint32_t *modified_block,
|
||||
// <prev_obj> is the newest entry of the object the new entry is added to, or NULL if there is
|
||||
// none. It is used to keep all not-yet-durable entries of one object in the same metadata block,
|
||||
// see allocate_entry(). May return EAGAIN or EBUSY, meaning "retry later" - see there.
|
||||
int blockstore_heap_t::add_entry(uint32_t wr_size, heap_entry_t *prev_obj, uint32_t *modified_block, bool prefer_same,
|
||||
bool allow_last_free, bool explicit_complete, std::function<void(heap_entry_t *wr)> fill_entry)
|
||||
{
|
||||
uint32_t block_num;
|
||||
int res = allocate_entry(wr_size, &block_num, allow_last_free);
|
||||
int res = allocate_entry(wr_size, &block_num, allow_last_free, prefer_same && prev_obj
|
||||
&& prev_obj->lsn > get_fsynced_lsn() ? list_item(prev_obj)->block_num : UINT32_MAX);
|
||||
if (res != 0)
|
||||
{
|
||||
return res;
|
||||
@@ -1649,7 +1873,7 @@ int blockstore_heap_t::add_small_write(object_id oid, heap_entry_t **obj_ptr, ui
|
||||
}
|
||||
uint32_t wr_size = get_small_entry_size(offset, len);
|
||||
// Small writes are written in parallel with buffered data so they require explicit_complete
|
||||
return add_entry(wr_size, modified_block, false, true, [&](heap_entry_t *wr)
|
||||
return add_entry(wr_size, obj, modified_block, true, false, true, [&](heap_entry_t *wr)
|
||||
{
|
||||
wr->entry_type = type;
|
||||
wr->inode = oid.inode;
|
||||
@@ -1690,7 +1914,7 @@ int blockstore_heap_t::add_big_write(object_id oid, heap_entry_t *old_head, bool
|
||||
}
|
||||
uint32_t wr_size = get_big_entry_size();
|
||||
// Big writes are written after writing data so they don't require explicit_complete
|
||||
return add_entry(wr_size, modified_block, false, false, [&](heap_entry_t *wr)
|
||||
return add_entry(wr_size, old_head, modified_block, false, false, false, [&](heap_entry_t *wr)
|
||||
{
|
||||
wr->entry_type = BS_HEAP_BIG_WRITE | (stable ? BS_HEAP_STABLE : 0);
|
||||
wr->inode = oid.inode;
|
||||
@@ -1716,7 +1940,7 @@ int blockstore_heap_t::add_redirect_intent(object_id oid, heap_entry_t **obj_ptr
|
||||
{
|
||||
uint32_t wr_size = get_big_intent_entry_size();
|
||||
// Big-redirect intents, just like regular big writes, are written after writing data so they don't require explicit_complete
|
||||
return add_entry(wr_size, modified_block, false, false, [&](heap_entry_t *wr)
|
||||
return add_entry(wr_size, *obj_ptr, modified_block, false, false, false, [&](heap_entry_t *wr)
|
||||
{
|
||||
wr->entry_type = BS_HEAP_BIG_INTENT|BS_HEAP_STABLE;
|
||||
wr->inode = oid.inode;
|
||||
@@ -1752,7 +1976,7 @@ int blockstore_heap_t::add_big_intent(object_id oid, heap_entry_t **obj_ptr, uin
|
||||
}
|
||||
uint32_t wr_size = get_big_intent_entry_size();
|
||||
// Big intents are written before writing data so they require explicit_complete
|
||||
return add_entry(wr_size, modified_block, false, true, [&](heap_entry_t *wr)
|
||||
return add_entry(wr_size, obj, modified_block, false, false, true, [&](heap_entry_t *wr)
|
||||
{
|
||||
wr->entry_type = BS_HEAP_BIG_INTENT | BS_HEAP_STABLE;
|
||||
wr->inode = oid.inode;
|
||||
@@ -1796,7 +2020,9 @@ int blockstore_heap_t::add_compact(heap_entry_t *obj, uint64_t compact_version,
|
||||
}
|
||||
if (do_delete)
|
||||
{
|
||||
return add_entry(get_simple_entry_size(), modified_block, false, false, [&](heap_entry_t *wr)
|
||||
// Compaction only ever touches durable entries and reuses their LSNs, so it doesn't
|
||||
// need the "same block as the previous entry of the object" placement
|
||||
return add_entry(get_simple_entry_size(), NULL, modified_block, false, false, false, [&](heap_entry_t *wr)
|
||||
{
|
||||
wr->entry_type = BS_HEAP_DELETE|BS_HEAP_STABLE;
|
||||
wr->inode = obj->inode;
|
||||
@@ -1807,7 +2033,7 @@ int blockstore_heap_t::add_compact(heap_entry_t *obj, uint64_t compact_version,
|
||||
}
|
||||
uint32_t wr_size = get_big_entry_size();
|
||||
// Compaction entry is added after copying data so it doesn't require explicit_complete
|
||||
return add_entry(wr_size, modified_block, true, false, [&](heap_entry_t *new_wr)
|
||||
return add_entry(wr_size, NULL, modified_block, false, true, false, [&](heap_entry_t *new_wr)
|
||||
{
|
||||
new_wr->entry_type = BS_HEAP_BIG_WRITE|BS_HEAP_STABLE;
|
||||
new_wr->inode = obj->inode;
|
||||
@@ -1840,11 +2066,11 @@ int blockstore_heap_t::punch_holes(heap_entry_t *wr, uint8_t *new_bitmap, uint8_
|
||||
return 0;
|
||||
}
|
||||
|
||||
int blockstore_heap_t::add_simple(heap_entry_t *obj, uint64_t version, uint32_t *modified_block, uint32_t entry_type)
|
||||
int blockstore_heap_t::add_simple(heap_entry_t *obj, uint64_t version, uint32_t *modified_block, uint32_t entry_type, bool prefer_same)
|
||||
{
|
||||
uint32_t wr_size = get_simple_entry_size();
|
||||
// Simple entries don't have data so they don't require explicit_complete
|
||||
return add_entry(wr_size, modified_block, false, false, [&](heap_entry_t *wr)
|
||||
return add_entry(wr_size, obj, modified_block, prefer_same, false, false, [&](heap_entry_t *wr)
|
||||
{
|
||||
wr->entry_type = entry_type;
|
||||
wr->inode = obj->inode;
|
||||
@@ -1864,7 +2090,7 @@ int blockstore_heap_t::add_commit(heap_entry_t *obj, uint64_t version, uint32_t
|
||||
{
|
||||
auto rollback_version = wr->version;
|
||||
wr = prev(wr);
|
||||
while (wr->version > rollback_version)
|
||||
while (wr && wr->version > rollback_version)
|
||||
{
|
||||
assert(!(wr->entry_type & BS_HEAP_STABLE));
|
||||
wr = prev(wr);
|
||||
@@ -1874,13 +2100,19 @@ int blockstore_heap_t::add_commit(heap_entry_t *obj, uint64_t version, uint32_t
|
||||
if (wr->type() == BS_HEAP_COMMIT)
|
||||
{
|
||||
if (commit_version < wr->version)
|
||||
{
|
||||
commit_version = wr->version;
|
||||
}
|
||||
wr = prev(wr);
|
||||
continue;
|
||||
}
|
||||
if (wr->version == version)
|
||||
if (wr->version >= version)
|
||||
{
|
||||
// A version may be already committed, flushed, and removed, and it's not a bug
|
||||
found = true;
|
||||
}
|
||||
if (wr->version <= version)
|
||||
{
|
||||
if (!(wr->entry_type & BS_HEAP_STABLE) && wr->version > commit_version)
|
||||
{
|
||||
uncommitted = true;
|
||||
@@ -1901,7 +2133,7 @@ int blockstore_heap_t::add_commit(heap_entry_t *obj, uint64_t version, uint32_t
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
return add_simple(obj, version, modified_block, BS_HEAP_COMMIT);
|
||||
return add_simple(obj, version, modified_block, BS_HEAP_COMMIT, true);
|
||||
}
|
||||
|
||||
int blockstore_heap_t::add_rollback(heap_entry_t *obj, uint64_t version, uint32_t *modified_block)
|
||||
@@ -1960,13 +2192,31 @@ int blockstore_heap_t::add_rollback(heap_entry_t *obj, uint64_t version, uint32_
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
return add_simple(obj, version, modified_block, BS_HEAP_ROLLBACK);
|
||||
return add_simple(obj, version, modified_block, BS_HEAP_ROLLBACK, true);
|
||||
}
|
||||
|
||||
int blockstore_heap_t::add_delete(heap_entry_t *obj, uint32_t *modified_block)
|
||||
{
|
||||
assert(obj);
|
||||
return add_simple(obj, 0, modified_block, BS_HEAP_DELETE|BS_HEAP_STABLE);
|
||||
return add_simple(obj, 0, modified_block, BS_HEAP_DELETE|BS_HEAP_STABLE, false);
|
||||
}
|
||||
|
||||
// Write a versioned tombstone: a stable deletion record at version `version`.
|
||||
// It erases the chain below it (is_overwrite) but, unlike a versionless delete marker,
|
||||
// it survives GC and compaction until it's purged by a delete or overwritten.
|
||||
int blockstore_heap_t::add_tombstone(object_id oid, heap_entry_t *obj, uint64_t version, uint32_t *modified_block)
|
||||
{
|
||||
assert(version);
|
||||
uint32_t wr_size = get_simple_entry_size();
|
||||
// Same shape as add_simple but filling inode/stripe from oid, so that a
|
||||
// tombstone can be recorded over a chain that doesn't exist
|
||||
return add_entry(wr_size, obj, modified_block, false, false, false, [&](heap_entry_t *wr)
|
||||
{
|
||||
wr->entry_type = BS_HEAP_DELETE|BS_HEAP_STABLE;
|
||||
wr->inode = oid.inode;
|
||||
wr->stripe = oid.stripe;
|
||||
wr->version = version;
|
||||
});
|
||||
}
|
||||
|
||||
// 2nd step: mark the block as being written (to prevent further in-memory updates to it),
|
||||
@@ -2077,12 +2327,19 @@ void blockstore_heap_t::mark_garbage_up_to(heap_entry_t *wr)
|
||||
return;
|
||||
}
|
||||
assert(wr->is_overwrite());
|
||||
uint32_t used_big = (wr->type() == BS_HEAP_BIG_WRITE || wr->type() == BS_HEAP_BIG_INTENT ? wr->big().block_num : UINT32_MAX);
|
||||
// <wr> survives, so its data block must not be freed no matter how far down the chain
|
||||
// another entry referring to it turns out to be: compaction merges newer writes into the
|
||||
// base block in place and gives its location to the entry it adds, and a rolled back big
|
||||
// write of its own may well sit in between the two.
|
||||
// <used_big> additionally keeps the walk from freeing the same block twice when several
|
||||
// entries in a row share it
|
||||
uint32_t keep_big = (wr->type() == BS_HEAP_BIG_WRITE || wr->type() == BS_HEAP_BIG_INTENT ? wr->big().block_num : UINT32_MAX);
|
||||
uint32_t used_big = keep_big;
|
||||
wr = prev(wr);
|
||||
while (wr && !wr->is_garbage())
|
||||
{
|
||||
auto prev_wr = prev(wr);
|
||||
mark_garbage(list_item(wr)->block_num, wr, used_big);
|
||||
mark_garbage(list_item(wr)->block_num, wr, used_big, keep_big);
|
||||
if (wr->type() == BS_HEAP_BIG_WRITE || wr->type() == BS_HEAP_BIG_INTENT)
|
||||
{
|
||||
used_big = wr->big().block_num;
|
||||
@@ -2091,7 +2348,7 @@ void blockstore_heap_t::mark_garbage_up_to(heap_entry_t *wr)
|
||||
}
|
||||
}
|
||||
|
||||
void blockstore_heap_t::mark_garbage(uint32_t block_num, heap_entry_t *prev_wr, uint32_t used_big)
|
||||
void blockstore_heap_t::mark_garbage(uint32_t block_num, heap_entry_t *prev_wr, uint32_t used_big, uint32_t keep_big)
|
||||
{
|
||||
prev_wr->set_garbage();
|
||||
garbage_entries++;
|
||||
@@ -2101,7 +2358,8 @@ void blockstore_heap_t::mark_garbage(uint32_t block_num, heap_entry_t *prev_wr,
|
||||
{
|
||||
free_buffer_area(prev_wr->inode, prev_wr->small().location, prev_wr->small().len);
|
||||
}
|
||||
else if ((prev_wr->type() == BS_HEAP_BIG_WRITE || prev_wr->type() == BS_HEAP_BIG_INTENT) && prev_wr->big().block_num != used_big)
|
||||
else if ((prev_wr->type() == BS_HEAP_BIG_WRITE || prev_wr->type() == BS_HEAP_BIG_INTENT) &&
|
||||
prev_wr->big().block_num != used_big && prev_wr->big().block_num != keep_big)
|
||||
{
|
||||
free_data(prev_wr->inode, prev_wr->big_location(this));
|
||||
}
|
||||
@@ -2126,6 +2384,17 @@ int blockstore_heap_t::get_next_compact(object_id & oid)
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool blockstore_heap_t::is_absent(heap_entry_t *obj, bool wipe_only)
|
||||
{
|
||||
bool present = false;
|
||||
iterate_with_stable(obj, UINT64_MAX, [&](heap_entry_t *wr, bool stable)
|
||||
{
|
||||
present = (wr->type() != BS_HEAP_DELETE || wipe_only && wr->version != 0);
|
||||
return false;
|
||||
});
|
||||
return !present;
|
||||
}
|
||||
|
||||
void blockstore_heap_t::iterate_with_stable(heap_entry_t *obj, uint64_t max_lsn, std::function<bool(heap_entry_t*, bool)> cb)
|
||||
{
|
||||
auto old_wr = obj;
|
||||
@@ -2189,10 +2458,11 @@ heap_compact_t blockstore_heap_t::iterate_compaction(heap_entry_t *obj, uint64_t
|
||||
{
|
||||
if (wr->type() == BS_HEAP_ROLLBACK && wr->lsn <= fsynced_lsn)
|
||||
{
|
||||
// compact_version in commit/rollback is taken from actual write entries
|
||||
// to handle lsn=0 reset correctly
|
||||
if (!res.compact_lsn)
|
||||
{
|
||||
res.compact_lsn = wr->lsn;
|
||||
res.compact_version = wr->version;
|
||||
}
|
||||
if (rollback_version > wr->version)
|
||||
{
|
||||
@@ -2202,14 +2472,15 @@ heap_compact_t blockstore_heap_t::iterate_compaction(heap_entry_t *obj, uint64_t
|
||||
}
|
||||
if (wr->type() == BS_HEAP_COMMIT && wr->lsn <= fsynced_lsn)
|
||||
{
|
||||
res.do_delete = false;
|
||||
if (!res.compact_lsn)
|
||||
{
|
||||
res.compact_lsn = wr->lsn;
|
||||
res.compact_version = wr->version;
|
||||
}
|
||||
res.do_delete = false;
|
||||
if (commit_version < wr->version)
|
||||
{
|
||||
commit_version = wr->version;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
bool rolled_back = (wr->version > rollback_version);
|
||||
@@ -2222,12 +2493,15 @@ heap_compact_t blockstore_heap_t::iterate_compaction(heap_entry_t *obj, uint64_t
|
||||
if (!stable && !committed || wr->lsn > fsynced_lsn)
|
||||
{
|
||||
// Unstable and non-fsynced writes can't be compacted yet
|
||||
// Reset newer compact_lsn to place compact entry correctly
|
||||
res.do_delete = false;
|
||||
res.compact_lsn = 0;
|
||||
res.compact_version = 0;
|
||||
if (!under_pressure && (wr->type() == BS_HEAP_BIG_WRITE || wr->type() == BS_HEAP_DELETE))
|
||||
if ((!under_pressure || stable) && (wr->type() == BS_HEAP_BIG_WRITE || wr->type() == BS_HEAP_BIG_INTENT || wr->type() == BS_HEAP_DELETE))
|
||||
{
|
||||
// We may postpone compaction if we have an unstable overwrite when not under pressure
|
||||
// We MUST postpone if the overwrite is STABLE (even if under pressure),
|
||||
// because add_compact will reject STABLE overwrites with EBUSY.
|
||||
return res;
|
||||
}
|
||||
continue;
|
||||
@@ -2238,6 +2512,9 @@ heap_compact_t blockstore_heap_t::iterate_compaction(heap_entry_t *obj, uint64_t
|
||||
if (!stable && !res.compact_lsn)
|
||||
{
|
||||
res.compact_lsn = wr->lsn;
|
||||
}
|
||||
if (res.compact_version < wr->version)
|
||||
{
|
||||
res.compact_version = wr->version;
|
||||
}
|
||||
res.clean_wr = wr;
|
||||
@@ -2248,18 +2525,55 @@ heap_compact_t blockstore_heap_t::iterate_compaction(heap_entry_t *obj, uint64_t
|
||||
{
|
||||
// Object is deleted
|
||||
assert(!has_small && stable); // unstable deletes are not supported
|
||||
if (wr->version != 0)
|
||||
{
|
||||
// A versioned tombstone must survive compaction. Entries below it were
|
||||
// already marked as garbage by the tombstone write itself, there's
|
||||
// nothing to merge and nothing to sweep
|
||||
res.do_delete = false;
|
||||
res.compact_lsn = 0;
|
||||
res.compact_version = 0;
|
||||
return res;
|
||||
}
|
||||
if (!res.do_delete && res.compact_lsn)
|
||||
{
|
||||
// A COMMIT above the delete reset do_delete, but all writes between
|
||||
// them are lost (incorrect chain / no fsync). Restore do_delete.
|
||||
res.do_delete = true;
|
||||
res.compact_version = 0;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
assert(wr->type() == BS_HEAP_SMALL_WRITE || wr->type() == BS_HEAP_INTENT_WRITE);
|
||||
if (!res.compact_lsn)
|
||||
{
|
||||
res.compact_lsn = wr->lsn;
|
||||
}
|
||||
if (res.compact_version < wr->version)
|
||||
{
|
||||
res.compact_version = wr->version;
|
||||
}
|
||||
res.do_delete = false;
|
||||
has_small = true;
|
||||
small_wr_cb(wr);
|
||||
}
|
||||
if (!res.clean_wr && !res.do_delete && res.compact_lsn)
|
||||
{
|
||||
if (has_small)
|
||||
{
|
||||
// The chain holds no big entry surviving the rollbacks and no executed
|
||||
// delete: neither a merge nor a delete is possible. The chain is invalid
|
||||
// but we can't just remove it, so abort compaction and leave it as is.
|
||||
res.compact_lsn = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Otherwise it means that there are no entries: it's either a bare COMMIT
|
||||
// or a COMMIT over a ROLLBACK which masks all previous entries. Remove everything.
|
||||
res.do_delete = true;
|
||||
}
|
||||
res.compact_version = 0;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
@@ -2278,12 +2592,14 @@ void blockstore_heap_t::iterate_objects(std::function<void(heap_entry_t*, uint32
|
||||
}
|
||||
|
||||
int blockstore_heap_t::list_objects(uint32_t pg_num, object_id min_oid, object_id max_oid,
|
||||
obj_ver_id **result_list, size_t *stable_count, size_t *unstable_count)
|
||||
obj_ver_id **result_list, size_t *stable_count, size_t *unstable_count, size_t *tombstone_count)
|
||||
{
|
||||
obj_ver_id *res = NULL;
|
||||
size_t res_size = 0, res_alloc = 0;
|
||||
obj_ver_id *unstable = NULL;
|
||||
size_t unstable_size = 0, unstable_alloc = 0;
|
||||
obj_ver_id *tombstone = NULL;
|
||||
size_t tombstone_size = 0, tombstone_alloc = 0;
|
||||
uint64_t pool_id = (min_oid.inode >> (64-POOL_ID_BITS));
|
||||
if (pool_id == 0 || pool_id != (max_oid.inode >> (64-POOL_ID_BITS)))
|
||||
{
|
||||
@@ -2317,7 +2633,19 @@ int blockstore_heap_t::list_objects(uint32_t pg_num, object_id min_oid, object_i
|
||||
{
|
||||
if (stable)
|
||||
{
|
||||
stable_version = wr->version;
|
||||
if (wr->type() == BS_HEAP_DELETE && wr->version != 0)
|
||||
{
|
||||
// Versioned tombstone: a deleted stable version, reported
|
||||
// in a separate trailing section
|
||||
if (tombstone_size >= tombstone_alloc)
|
||||
{
|
||||
tombstone_alloc = (!tombstone_alloc ? 128 : tombstone_alloc*2);
|
||||
tombstone = (obj_ver_id*)realloc_or_die(tombstone, sizeof(obj_ver_id) * tombstone_alloc);
|
||||
}
|
||||
tombstone[tombstone_size++] = (obj_ver_id){ .oid = oid, .version = wr->version };
|
||||
}
|
||||
else
|
||||
stable_version = wr->version;
|
||||
return false;
|
||||
}
|
||||
if (unstable_size >= unstable_alloc)
|
||||
@@ -2339,20 +2667,24 @@ int blockstore_heap_t::list_objects(uint32_t pg_num, object_id min_oid, object_i
|
||||
}
|
||||
});
|
||||
}
|
||||
if (unstable_size)
|
||||
if (unstable_size || tombstone_size)
|
||||
{
|
||||
if (res_size+unstable_size > res_alloc)
|
||||
if (res_size+unstable_size+tombstone_size > res_alloc)
|
||||
{
|
||||
res_alloc = res_size+unstable_size;
|
||||
res_alloc = res_size+unstable_size+tombstone_size;
|
||||
res = (obj_ver_id*)realloc_or_die(res, sizeof(obj_ver_id) * res_alloc);
|
||||
}
|
||||
memcpy(res + res_size, unstable, sizeof(obj_ver_id) * unstable_size);
|
||||
if (unstable_size > 0)
|
||||
memcpy(res + res_size, unstable, sizeof(obj_ver_id) * unstable_size);
|
||||
if (tombstone_size > 0)
|
||||
memcpy(res + res_size+unstable_size, tombstone, sizeof(obj_ver_id) * tombstone_size);
|
||||
free(unstable);
|
||||
unstable = NULL;
|
||||
free(tombstone);
|
||||
}
|
||||
*result_list = res;
|
||||
*stable_count = res_size;
|
||||
*unstable_count = unstable_size;
|
||||
*tombstone_count = tombstone_size;
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -2643,10 +2975,13 @@ void blockstore_heap_t::apply_inflight(heap_inflight_lsn_t & inflight)
|
||||
assert(!li->prev);
|
||||
assert((li->entry.entry_type & ~BS_HEAP_GARBAGE) == (BS_HEAP_DELETE|BS_HEAP_STABLE));
|
||||
}
|
||||
else if (!li->prev && li->next->entry.entry_type == (BS_HEAP_DELETE|BS_HEAP_STABLE))
|
||||
else if (!li->prev && li->next->entry.entry_type == (BS_HEAP_DELETE|BS_HEAP_STABLE) &&
|
||||
li->next->entry.version == 0)
|
||||
{
|
||||
// free BS_HEAP_DELETEs when all previous entries are also freed
|
||||
mark_garbage(li->next->block_num, &li->next->entry, UINT32_MAX);
|
||||
// Free versionless BS_HEAP_DELETE markers when all previous entries are also
|
||||
// freed. A versioned tombstone is never garbage-collected this way: it's the
|
||||
// only record that the object was deleted and must survive as a chain head
|
||||
mark_garbage(li->next->block_num, &li->next->entry, UINT32_MAX, UINT32_MAX);
|
||||
}
|
||||
unlink_list_item(li);
|
||||
}
|
||||
|
||||
@@ -167,6 +167,9 @@ struct heap_recheck_state_t
|
||||
size_t sent_reads = 0;
|
||||
size_t checked_reads = 0;
|
||||
heap_entry_t *bad_wr = NULL;
|
||||
// The oldest entry a read was issued for. Everything below it is unverified, so if it
|
||||
// turns out to be bad the object has to be looked at again after dropping it
|
||||
heap_entry_t *oldest_wr = NULL;
|
||||
};
|
||||
|
||||
using i64hash_t = robin_hood::hash<uint64_t>;
|
||||
@@ -233,8 +236,9 @@ class blockstore_heap_t
|
||||
uint64_t get_pg_id(inode_t inode, uint64_t stripe);
|
||||
bool validate_object(heap_entry_t *obj);
|
||||
void fill_recheck_queue();
|
||||
void recheck_requeue(object_id oid);
|
||||
void recheck_drop_entries(heap_entry_t *obj, heap_entry_t *bad_wr);
|
||||
void recheck_start_reads(heap_recheck_state_t *st);
|
||||
int recheck_start_reads(heap_recheck_state_t *st);
|
||||
int mark_used_blocks();
|
||||
void init_free_bad_entry(heap_entry_t *wr);
|
||||
void init_erase_bad_entry(heap_list_item_t *li);
|
||||
@@ -245,18 +249,21 @@ class blockstore_heap_t
|
||||
void reshard_add(heap_reshard_state_t *st, heap_list_item_t *li);
|
||||
|
||||
void gc_block(heap_block_info_t & inf);
|
||||
int allocate_entry(uint32_t entry_size, uint32_t *block_num, bool allow_last_free);
|
||||
int allocate_entry(uint32_t entry_size, uint32_t *block_num, bool allow_last_free, uint32_t prefer_block);
|
||||
void insert_list_items(heap_list_item_t** v, size_t count, bool postpone);
|
||||
void unlink_list_item(heap_list_item_t *li);
|
||||
int add_entry(uint32_t wr_size, uint32_t *modified_block, bool allow_last_free,
|
||||
bool explicit_complete, std::function<void(heap_entry_t *wr)> fill_entry);
|
||||
int add_simple(heap_entry_t *obj, uint64_t version, uint32_t *modified_block, uint32_t entry_type);
|
||||
int add_entry(uint32_t wr_size, heap_entry_t *prev_obj, uint32_t *modified_block, bool prefer_same,
|
||||
bool allow_last_free, bool explicit_complete, std::function<void(heap_entry_t *wr)> fill_entry);
|
||||
int add_simple(heap_entry_t *obj, uint64_t version, uint32_t *modified_block, uint32_t entry_type, bool prefer_same);
|
||||
uint32_t meta_alloc_pos(const heap_block_info_t & inf);
|
||||
void modify_alloc(uint32_t block_num, std::function<void(heap_block_info_t &)> change_cb);
|
||||
void mark_garbage_up_to(heap_entry_t *wr);
|
||||
void mark_garbage(uint32_t block_num, heap_entry_t *prev_wr, uint32_t used_big);
|
||||
void mark_garbage(uint32_t block_num, heap_entry_t *prev_wr, uint32_t used_big, uint32_t keep_big);
|
||||
void push_inflight_lsn(uint64_t lsn, heap_entry_t *wr, uint64_t flags);
|
||||
void mark_completed_lsns(uint64_t mod_lsn);
|
||||
heap_entry_t *skip_commits(heap_entry_t *wr);
|
||||
int count_recheck_entries(heap_entry_t *obj, bool & need_data);
|
||||
bool recheck_verify(heap_recheck_state_t *st, heap_entry_t *wr, uint8_t *buf);
|
||||
void apply_inflight(heap_inflight_lsn_t & inflight);
|
||||
public:
|
||||
blockstore_heap_t(blockstore_disk_t *dsk, uint8_t *buffer_area, int log_level = 0);
|
||||
@@ -287,6 +294,9 @@ public:
|
||||
heap_entry_t *lock_and_read_entry(object_id oid);
|
||||
// read an object entry without locking it
|
||||
heap_entry_t *read_entry(object_id oid);
|
||||
// true if a read of the chain would return ENOENT: the head is a DELETE entry
|
||||
// or all entries are cut off by a ROLLBACK to version 0
|
||||
bool is_absent(heap_entry_t *obj, bool wipe_only = false);
|
||||
// unlock an entry
|
||||
bool unlock_entry(object_id oid);
|
||||
// set or verify checksums in a write request
|
||||
@@ -324,6 +334,9 @@ public:
|
||||
// forget an object
|
||||
// return error code
|
||||
int add_delete(heap_entry_t *obj, uint32_t *modified_block);
|
||||
// write a versioned tombstone, obj may be NULL
|
||||
// return error code
|
||||
int add_tombstone(object_id oid, heap_entry_t *obj, uint64_t version, uint32_t *modified_block);
|
||||
// get the next object to compact
|
||||
// guaranteed to return objects in min lsn order
|
||||
// returns 0 if OK, ENOENT if nothing to compact
|
||||
@@ -335,8 +348,9 @@ public:
|
||||
// iterate all objects
|
||||
void iterate_objects(std::function<void(heap_entry_t*, uint32_t block_num)> cb);
|
||||
// retrieve object listing from a PG
|
||||
// result layout is [stable][unstable][tombstones], tombstone_count is the tail length
|
||||
int list_objects(uint32_t pg_num, object_id min_oid, object_id max_oid,
|
||||
obj_ver_id **result_list, size_t *stable_count, size_t *unstable_count);
|
||||
obj_ver_id **result_list, size_t *stable_count, size_t *unstable_count, size_t *tombstone_count);
|
||||
|
||||
// inflight write tracking
|
||||
void start_block_write(uint32_t block_num);
|
||||
|
||||
@@ -43,6 +43,24 @@ blockstore_impl_t::blockstore_impl_t(blockstore_config_t & config, ring_loop_i *
|
||||
|
||||
blockstore_impl_t::~blockstore_impl_t()
|
||||
{
|
||||
// Operations which were queued or in flight when we were destroyed still have their
|
||||
// private state constructed, and a read also owns its read vector. Nobody is going to
|
||||
// complete them now, so release it here
|
||||
for (auto op: submit_queue)
|
||||
if (op)
|
||||
PRIV(op)->~blockstore_op_private_t();
|
||||
submit_queue.clear();
|
||||
for (auto op: reads_in_flight)
|
||||
{
|
||||
free_read_buffers(PRIV(op)->read_vec);
|
||||
PRIV(op)->~blockstore_op_private_t();
|
||||
}
|
||||
reads_in_flight.clear();
|
||||
// Metadata block buffers are normally freed by the write completion callback,
|
||||
// so anything still here was queued or in flight when we were destroyed
|
||||
for (auto & mb: modified_blocks)
|
||||
free(mb.second.buf);
|
||||
modified_blocks.clear();
|
||||
if (flusher)
|
||||
delete flusher;
|
||||
if (heap)
|
||||
@@ -131,7 +149,8 @@ void blockstore_impl_t::loop()
|
||||
{
|
||||
wr_st = dequeue_read(op);
|
||||
}
|
||||
else if (op->opcode == BS_OP_WRITE || op->opcode == BS_OP_WRITE_STABLE || op->opcode == BS_OP_DELETE)
|
||||
else if (op->opcode == BS_OP_WRITE || op->opcode == BS_OP_WRITE_STABLE ||
|
||||
op->opcode == BS_OP_DELETE || op->opcode == BS_OP_TOMBSTONE)
|
||||
{
|
||||
wr_st = dequeue_write(op);
|
||||
has_unfinished_writes = has_unfinished_writes || (wr_st != 2);
|
||||
@@ -268,6 +287,19 @@ void blockstore_impl_t::check_wait(blockstore_op_t *op)
|
||||
flusher->release_trim();
|
||||
PRIV(op)->wait_for = 0;
|
||||
}
|
||||
else if (PRIV(op)->wait_for == WAIT_META_FSYNC)
|
||||
{
|
||||
if (heap->get_fsynced_lsn() < PRIV(op)->wait_detail)
|
||||
{
|
||||
// do not submit
|
||||
#ifdef BLOCKSTORE_DEBUG
|
||||
printf("Still waiting for LSN %ju to become durable\n", PRIV(op)->wait_detail);
|
||||
#endif
|
||||
return;
|
||||
}
|
||||
flusher->release_fsync();
|
||||
PRIV(op)->wait_for = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw std::runtime_error("BUG: op->wait_for value is unexpected");
|
||||
@@ -290,7 +322,8 @@ void blockstore_impl_t::enqueue_op(blockstore_op_t *op)
|
||||
ringloop->set_immediate([op]() { std::function<void (blockstore_op_t*)>(op->callback)(op); });
|
||||
return;
|
||||
}
|
||||
if ((op->opcode == BS_OP_WRITE || op->opcode == BS_OP_WRITE_STABLE || op->opcode == BS_OP_DELETE) && !enqueue_write(op))
|
||||
if ((op->opcode == BS_OP_WRITE || op->opcode == BS_OP_WRITE_STABLE ||
|
||||
op->opcode == BS_OP_DELETE || op->opcode == BS_OP_TOMBSTONE) && !enqueue_write(op))
|
||||
{
|
||||
ringloop->set_immediate([op]() { std::function<void (blockstore_op_t*)>(op->callback)(op); });
|
||||
return;
|
||||
@@ -336,21 +369,37 @@ void blockstore_impl_t::process_list(blockstore_op_t *op)
|
||||
return;
|
||||
}
|
||||
obj_ver_id *result = NULL;
|
||||
size_t stable_count = 0, unstable_count = 0;
|
||||
int res = heap->list_objects(list_pg, op->min_oid, op->max_oid, &result, &stable_count, &unstable_count);
|
||||
size_t stable_count = 0, unstable_count = 0, tombstone_count = 0;
|
||||
int res = heap->list_objects(list_pg, op->min_oid, op->max_oid, &result, &stable_count, &unstable_count, &tombstone_count);
|
||||
if (op->list_stable_limit)
|
||||
{
|
||||
// Ordered result is expected - used by scrub
|
||||
// We use an unordered map
|
||||
std::sort(result, result + stable_count);
|
||||
if (stable_count > op->list_stable_limit)
|
||||
if (stable_count >= op->list_stable_limit)
|
||||
{
|
||||
memmove(result + op->list_stable_limit, result + stable_count, unstable_count*sizeof(obj_ver_id));
|
||||
// Layout is [stable][unstable][tombstones]
|
||||
// Return unstable and tombstone versions only up to the last stable object
|
||||
object_id last_oid = result[op->list_stable_limit-1].oid;
|
||||
size_t kept = 0;
|
||||
for (size_t i = 0; i < unstable_count; i++)
|
||||
{
|
||||
if (!(last_oid < result[stable_count+i].oid))
|
||||
result[op->list_stable_limit + kept++] = result[stable_count+i];
|
||||
}
|
||||
unstable_count = kept;
|
||||
for (size_t i = 0; i < tombstone_count; i++)
|
||||
{
|
||||
if (!(last_oid < result[stable_count+unstable_count+i].oid))
|
||||
result[op->list_stable_limit + kept++] = result[stable_count+unstable_count+i];
|
||||
}
|
||||
tombstone_count = kept - unstable_count;
|
||||
stable_count = op->list_stable_limit;
|
||||
}
|
||||
}
|
||||
op->version = stable_count;
|
||||
op->retval = res == 0 ? stable_count+unstable_count : -res;
|
||||
op->tombstone_count = tombstone_count;
|
||||
op->retval = res == 0 ? stable_count+unstable_count+tombstone_count : -res;
|
||||
op->buf = (uint8_t*)result;
|
||||
FINISH_OP(op);
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ struct blockstore_op_private_t
|
||||
int op_state;
|
||||
|
||||
// Write, sync, stabilize
|
||||
uint32_t modified_block, modified_block2;
|
||||
uint32_t modified_block;
|
||||
|
||||
// Read
|
||||
std::vector<copy_buffer_t> read_vec;
|
||||
@@ -52,7 +52,9 @@ struct blockstore_op_private_t
|
||||
uint32_t write_type;
|
||||
|
||||
// Stabilize, rollback
|
||||
int stab_pos;
|
||||
heap_entry_t *obj;
|
||||
int stab_pos, res;
|
||||
uint32_t modified_block2;
|
||||
|
||||
// Write
|
||||
timespec tv_begin;
|
||||
@@ -69,6 +71,8 @@ class blockstore_impl_t: public blockstore_i
|
||||
public:
|
||||
blockstore_disk_t dsk;
|
||||
|
||||
virtual bool supports_tombstones() { return true; }
|
||||
|
||||
/******* OPTIONS *******/
|
||||
bool readonly = false;
|
||||
// Enable if you want every operation to be executed with an "implicit fsync"
|
||||
@@ -106,7 +110,15 @@ public:
|
||||
uint8_t* meta_superblock = NULL;
|
||||
uint8_t *buffer_area = NULL;
|
||||
std::vector<blockstore_op_t*> submit_queue;
|
||||
// Reads waiting for their disk requests. They're out of submit_queue already, but we
|
||||
// still own their private state, including the read vector - see the destructor
|
||||
robin_hood::unordered_flat_set<blockstore_op_t*> reads_in_flight;
|
||||
int unsynced_data_write_count = 0, unsynced_buffer_write_count = 0, unsynced_meta_write_count = 0;
|
||||
// Fsyncs submitted but not yet completed. The counters are zeroed at submission,
|
||||
// so a zero counter does not mean everything is durable - a previous sync or
|
||||
// stabilize may still have its fsync in flight. Syncs must wait for it instead
|
||||
// of falsely reporting success
|
||||
int fsyncs_inflight = 0;
|
||||
int unsynced_queued_ops = 0;
|
||||
|
||||
std::vector<uint32_t> pending_modified_blocks;
|
||||
|
||||
@@ -273,7 +273,7 @@ resume_6:
|
||||
rc->buf = (uint8_t*)memalign_or_die(MEM_ALIGNMENT, rc->len);
|
||||
data = ((ring_data_t*)sqe->user_data);
|
||||
data->iov = (iovec){ rc->buf, rc->len };
|
||||
data->callback = [this, rc](ring_data_t *data)
|
||||
data->callback = [rc](ring_data_t *data)
|
||||
{
|
||||
if (data->res < 0)
|
||||
{
|
||||
|
||||
@@ -43,6 +43,20 @@
|
||||
#define WAIT_SQE 1
|
||||
// Suspend operation until there are <wait_detail> bytes of free space in the journal on disk
|
||||
#define WAIT_COMPACTION 2
|
||||
// Suspend operation until LSN <wait_detail> becomes durable
|
||||
#define WAIT_META_FSYNC 3
|
||||
|
||||
// In non-immediate_commit setups bs_heap may require us to write into the same block as the
|
||||
// previous object's entry block. EAGAIN is returned if it's impossible, in that case we
|
||||
// request an fsync and fsync lifts the placement restriction entirely.
|
||||
#define BS_SUBMIT_CHECK_PLACEMENT(res, prev_lsn) \
|
||||
if ((res) == EAGAIN)\
|
||||
{\
|
||||
PRIV(op)->wait_for = WAIT_META_FSYNC;\
|
||||
PRIV(op)->wait_detail = (prev_lsn);\
|
||||
flusher->request_fsync();\
|
||||
return 0;\
|
||||
}
|
||||
|
||||
#define COPY_BUF_JOURNAL 0x01
|
||||
#define COPY_BUF_DATA 0x02
|
||||
|
||||
@@ -75,10 +75,12 @@ int blockstore_impl_t::dequeue_read(blockstore_op_t *op)
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (need_skip && wr->type() == BS_HEAP_SMALL_WRITE &&
|
||||
if (need_skip && (wr->type() == BS_HEAP_SMALL_WRITE || wr->type() == BS_HEAP_INTENT_WRITE) &&
|
||||
wr->small().offset < blk_end && wr->small().offset+wr->small().len > blk_start)
|
||||
{
|
||||
// Small write may mutate big write checksums during flush
|
||||
// Small write may mutate big write checksums during flush, and an intent write
|
||||
// overwrites part of the data block in place right away. Either way the checksum
|
||||
// of a checksum block they only partially cover no longer matches the disk
|
||||
skip_csum = COPY_BUF_SKIP_CSUM;
|
||||
}
|
||||
return true;
|
||||
@@ -96,8 +98,12 @@ undo_wait:
|
||||
{
|
||||
// May happen if there are entries but all of them are > requested version
|
||||
heap->unlock_entry(op->oid);
|
||||
op->version = 0;
|
||||
op->retval = -ENOENT;
|
||||
// A versioned tombstone is the head of the chain: its absence is RECORDED,
|
||||
// answered as -ENODATA with the recorded version - distinct from -ENOENT
|
||||
// ("never existed"), no data and no bitmap, recreations land above it
|
||||
bool tomb_head = obj->type() == BS_HEAP_DELETE && obj->version != 0;
|
||||
op->version = tomb_head ? obj->version : 0;
|
||||
op->retval = tomb_head ? -ENODATA : -ENOENT;
|
||||
FINISH_OP(op);
|
||||
return 2;
|
||||
}
|
||||
@@ -117,6 +123,7 @@ undo_wait:
|
||||
return 2;
|
||||
}
|
||||
op->retval = 0;
|
||||
reads_in_flight.insert(op);
|
||||
return 2;
|
||||
}
|
||||
|
||||
@@ -256,7 +263,7 @@ uint32_t blockstore_impl_t::prepare_read_simple(std::vector<copy_buffer_t> & rea
|
||||
blk_end = blk_end > wr->small().offset+wr->small().len ? wr->small().offset+wr->small().len : blk_end;
|
||||
}
|
||||
if ((blk_end-1)/dsk.csum_block_size == blk_start/dsk.csum_block_size ||
|
||||
blk_end/dsk.csum_block_size == blk_start/dsk.csum_block_size+1 && blk_end != end && blk_start != start ||
|
||||
(blk_end-1)/dsk.csum_block_size == blk_start/dsk.csum_block_size+1 && blk_end != end && blk_start != start ||
|
||||
blk_end == end && blk_start == start)
|
||||
{
|
||||
// single block, exactly two partial blocks, or any number of full blocks
|
||||
@@ -398,13 +405,14 @@ void blockstore_impl_t::handle_read_event(ring_data_t *data, blockstore_op_t *op
|
||||
}
|
||||
if (PRIV(op)->pending_ops == 0)
|
||||
{
|
||||
// verify checksums if required
|
||||
if (dsk.csum_block_size && !verify_read_checksums(op))
|
||||
// verify checksums if required, but not of a buffer that a failed read didn't fill
|
||||
if (op->retval >= 0 && dsk.csum_block_size && !verify_read_checksums(op))
|
||||
op->retval = -EDOM;
|
||||
else if (op->retval == 0)
|
||||
op->retval = op->len;
|
||||
heap->unlock_entry(op->oid);
|
||||
free_read_buffers(PRIV(op)->read_vec);
|
||||
reads_in_flight.erase(op);
|
||||
FINISH_OP(op);
|
||||
}
|
||||
}
|
||||
@@ -455,7 +463,12 @@ bool blockstore_impl_t::verify_read_checksums(blockstore_op_t *op)
|
||||
|
||||
int blockstore_impl_t::read_bitmap(object_id oid, uint64_t target_version, void *bitmap, uint64_t *result_version)
|
||||
{
|
||||
if (result_version)
|
||||
{
|
||||
*result_version = 0;
|
||||
}
|
||||
heap_entry_t *obj = heap->read_entry(oid);
|
||||
int res = -ENOENT;
|
||||
if (obj)
|
||||
{
|
||||
bool found = false;
|
||||
@@ -463,15 +476,21 @@ int blockstore_impl_t::read_bitmap(object_id oid, uint64_t target_version, void
|
||||
{
|
||||
if (target_version >= wr->version)
|
||||
{
|
||||
if (wr->type() == BS_HEAP_DELETE)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
found = true;
|
||||
if (result_version)
|
||||
{
|
||||
*result_version = wr->version;
|
||||
}
|
||||
if (wr->type() == BS_HEAP_DELETE)
|
||||
{
|
||||
// Same rule as data reads: a tombstone (versioned delete) answers
|
||||
// -ENODATA with the recorded version, bare absence -ENOENT
|
||||
if (wr->version != 0)
|
||||
{
|
||||
res = -ENODATA;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
found = true;
|
||||
if (bitmap)
|
||||
{
|
||||
memcpy(bitmap, wr->get_ext_bitmap(heap), dsk.clean_entry_bitmap_size);
|
||||
@@ -485,13 +504,9 @@ int blockstore_impl_t::read_bitmap(object_id oid, uint64_t target_version, void
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
if (result_version)
|
||||
{
|
||||
*result_version = 0;
|
||||
}
|
||||
if (bitmap)
|
||||
{
|
||||
memset(bitmap, 0, dsk.clean_entry_bitmap_size);
|
||||
}
|
||||
return -ENOENT;
|
||||
return res;
|
||||
}
|
||||
|
||||
@@ -14,6 +14,8 @@ int blockstore_impl_t::dequeue_stable(blockstore_op_t *op)
|
||||
else if (priv->op_state == 3) goto resume_3;
|
||||
else if (priv->op_state == 4) goto resume_4;
|
||||
else if (priv->op_state == 5) goto resume_5;
|
||||
else if (priv->op_state == 6) goto resume_6;
|
||||
else if (priv->op_state == 7) goto resume_7;
|
||||
assert(!priv->op_state);
|
||||
op->retval = 0;
|
||||
PRIV(op)->lsn = 0;
|
||||
@@ -21,30 +23,50 @@ int blockstore_impl_t::dequeue_stable(blockstore_op_t *op)
|
||||
for (priv->stab_pos = 0; priv->stab_pos < op->len; priv->stab_pos++)
|
||||
{
|
||||
{
|
||||
auto obj = heap->read_entry(v[priv->stab_pos].oid);
|
||||
if (!obj)
|
||||
priv->obj = heap->read_entry(v[priv->stab_pos].oid);
|
||||
if (!priv->obj)
|
||||
{
|
||||
op->retval = -ENOENT;
|
||||
FINISH_OP(op);
|
||||
return 2;
|
||||
}
|
||||
priv->modified_block2 = UINT32_MAX;
|
||||
int res = op->opcode == BS_OP_STABLE
|
||||
? heap->add_commit(obj, v[priv->stab_pos].version, &priv->modified_block2)
|
||||
: heap->add_rollback(obj, v[priv->stab_pos].version, &priv->modified_block2);
|
||||
if (res == EBUSY)
|
||||
priv->res = op->opcode == BS_OP_STABLE
|
||||
? heap->add_commit(priv->obj, v[priv->stab_pos].version, &priv->modified_block2)
|
||||
: heap->add_rollback(priv->obj, v[priv->stab_pos].version, &priv->modified_block2);
|
||||
if (priv->res != 0)
|
||||
{
|
||||
// Flush the previous modified block on error or nobody may flush it at all
|
||||
resume_6:
|
||||
if (priv->modified_block != UINT32_MAX)
|
||||
{
|
||||
priv->op_state = 6;
|
||||
BS_SUBMIT_CHECK_SQES(1);
|
||||
prepare_meta_block_write(priv->modified_block);
|
||||
resume_7:
|
||||
if (meta_block_is_pending(priv->modified_block))
|
||||
{
|
||||
priv->op_state = 7;
|
||||
return 1;
|
||||
}
|
||||
priv->modified_block = UINT32_MAX;
|
||||
priv->op_state = 0;
|
||||
}
|
||||
}
|
||||
BS_SUBMIT_CHECK_PLACEMENT(priv->res, priv->obj->lsn);
|
||||
if (priv->res == EBUSY)
|
||||
{
|
||||
op->retval = -EBUSY;
|
||||
FINISH_OP(op);
|
||||
return 2;
|
||||
}
|
||||
if (res == ENOENT)
|
||||
if (priv->res == ENOENT)
|
||||
{
|
||||
op->retval = -ENOENT;
|
||||
FINISH_OP(op);
|
||||
return 2;
|
||||
}
|
||||
if (res == ENOSPC)
|
||||
if (priv->res == ENOSPC)
|
||||
{
|
||||
if (!heap->get_to_compact_count())
|
||||
{
|
||||
@@ -58,11 +80,12 @@ int blockstore_impl_t::dequeue_stable(blockstore_op_t *op)
|
||||
flusher->request_trim();
|
||||
return 0;
|
||||
}
|
||||
assert(res == 0);
|
||||
assert(priv->res == 0);
|
||||
}
|
||||
resume_1:
|
||||
if (priv->modified_block != UINT32_MAX && priv->modified_block2 != priv->modified_block)
|
||||
{
|
||||
priv->op_state = 1;
|
||||
BS_SUBMIT_CHECK_SQES(1);
|
||||
prepare_meta_block_write(priv->modified_block);
|
||||
resume_2:
|
||||
|
||||
@@ -47,10 +47,12 @@ bool blockstore_impl_t::submit_fsyncs(int & wait_count)
|
||||
{
|
||||
if (data->res != 0)
|
||||
disk_error_abort("sync meta", data->res, 0);
|
||||
fsyncs_inflight--;
|
||||
wait_count--;
|
||||
assert(wait_count >= 0);
|
||||
if (!wait_count)
|
||||
ringloop->wakeup();
|
||||
// Always wake up - syncs waiting for somebody else's fsync to complete
|
||||
// must retry as soon as any fsync finishes
|
||||
ringloop->wakeup();
|
||||
};
|
||||
if (unsynced_meta_write_count > 0 && !dsk.disable_meta_fsync)
|
||||
{
|
||||
@@ -62,6 +64,7 @@ bool blockstore_impl_t::submit_fsyncs(int & wait_count)
|
||||
data->iov = { 0 };
|
||||
data->callback = cb;
|
||||
wait_count++;
|
||||
fsyncs_inflight++;
|
||||
}
|
||||
if (unsynced_buffer_write_count > 0 && !dsk.disable_journal_fsync &&
|
||||
(!unsynced_meta_write_count || dsk.journal_fd != dsk.meta_fd))
|
||||
@@ -74,6 +77,7 @@ bool blockstore_impl_t::submit_fsyncs(int & wait_count)
|
||||
data->iov = { 0 };
|
||||
data->callback = cb;
|
||||
wait_count++;
|
||||
fsyncs_inflight++;
|
||||
}
|
||||
if (unsynced_data_write_count > 0 && !dsk.disable_data_fsync &&
|
||||
(!unsynced_meta_write_count || dsk.data_fd != dsk.meta_fd) &&
|
||||
@@ -87,6 +91,7 @@ bool blockstore_impl_t::submit_fsyncs(int & wait_count)
|
||||
data->iov = { 0 };
|
||||
data->callback = cb;
|
||||
wait_count++;
|
||||
fsyncs_inflight++;
|
||||
}
|
||||
unsynced_data_write_count = 0;
|
||||
unsynced_buffer_write_count = 0;
|
||||
@@ -107,7 +112,16 @@ int blockstore_impl_t::do_sync(blockstore_op_t *op, int base_state)
|
||||
}
|
||||
if (!has_unsynced())
|
||||
{
|
||||
// We can return immediately because sync only syncs previous writes
|
||||
if (fsyncs_inflight > 0)
|
||||
{
|
||||
// Counters were already zeroed by the previous sync/stabilize, but its
|
||||
// fsync is still in flight and our writes may be inside it. Completing
|
||||
// now would falsely promise durability - wait for the fsync to finish
|
||||
// and re-check. The fsync completion callback wakes the loop up
|
||||
return 0;
|
||||
}
|
||||
// Nothing is unsynced and no fsync is in flight - we can return immediately
|
||||
// because sync only syncs previous writes
|
||||
unsynced_data_write_count = unsynced_buffer_write_count = unsynced_meta_write_count = 0;
|
||||
return 2;
|
||||
}
|
||||
|
||||
@@ -77,34 +77,36 @@ bool blockstore_impl_t::intent_write_allowed(blockstore_op_t *op, heap_entry_t *
|
||||
{
|
||||
return false;
|
||||
}
|
||||
bool ok = true;
|
||||
bool ok = false;
|
||||
heap->iterate_with_stable(obj, obj->lsn, [&](heap_entry_t *wr, bool stable)
|
||||
{
|
||||
// Intent writes are not allowed over buffered writes
|
||||
auto t = wr->type();
|
||||
if (t == BS_HEAP_SMALL_WRITE)
|
||||
{
|
||||
ok = false;
|
||||
return false;
|
||||
}
|
||||
// Intent writes are not allowed over unstable writes
|
||||
if (!stable)
|
||||
{
|
||||
ok = false;
|
||||
// Intent writes are not allowed over unstable writes
|
||||
return false;
|
||||
}
|
||||
// Intent writes are not allowed over unfinished intent writes
|
||||
if ((t == BS_HEAP_INTENT_WRITE || t == BS_HEAP_BIG_INTENT) && wr->lsn > heap->get_fsynced_lsn())
|
||||
else if (t == BS_HEAP_INTENT_WRITE || t == BS_HEAP_BIG_INTENT)
|
||||
{
|
||||
ok = false;
|
||||
return false;
|
||||
// Intent writes are not allowed over unfinished intent writes
|
||||
ok = (wr->lsn <= heap->get_fsynced_lsn());
|
||||
}
|
||||
// Intent writes are allowed over BIG_WRITEs even with fsyncs because BIG_WRITE is always counted as fsynced
|
||||
if (t == BS_HEAP_BIG_WRITE || t == BS_HEAP_BIG_INTENT)
|
||||
// Intent writes are allowed over BIG_WRITEs even with enable data_fsync
|
||||
// because BIG_WRITEs are always fsynced before adding the entry
|
||||
else if (t == BS_HEAP_BIG_WRITE)
|
||||
{
|
||||
return false;
|
||||
// But sadly with one exception: a BIG_WRITE may be a result of compaction, with a
|
||||
// reused older LSN, still in progress of being written. In that case it can still
|
||||
// disappear after a reboot, and if it disappears, an older small_write may be replayed
|
||||
// again over our intent write data if it's there. So we have to check the previous write too...
|
||||
if (wr->lsn == flusher->get_flushing_lsn({ .inode = wr->inode, .stripe = wr->stripe }))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
ok = true;
|
||||
}
|
||||
return true;
|
||||
// Intent writes are not allowed over buffered writes and other write types
|
||||
return false;
|
||||
});
|
||||
return ok;
|
||||
}
|
||||
@@ -122,19 +124,70 @@ int blockstore_impl_t::dequeue_write(blockstore_op_t *op)
|
||||
PRIV(op)->modified_block = UINT32_MAX;
|
||||
PRIV(op)->write_type = 0;
|
||||
heap_entry_t *obj = heap->read_entry(op->oid);
|
||||
if (op->opcode == BS_OP_DELETE)
|
||||
if (op->opcode == BS_OP_TOMBSTONE)
|
||||
{
|
||||
// Delete
|
||||
if (!obj || obj->type() == BS_HEAP_DELETE)
|
||||
// Record the absence of the object as a versioned record
|
||||
// (even of a non-existing object)
|
||||
if (!op->version && (!obj || heap->is_absent(obj)))
|
||||
{
|
||||
// Already deleted
|
||||
// An auto-versioned tombstone can't record anything new
|
||||
op->retval = 0;
|
||||
op->version = obj ? obj->version : 0;
|
||||
FINISH_OP(op);
|
||||
return 2;
|
||||
}
|
||||
uint64_t version = op->version ? op->version : obj->version + 1;
|
||||
if (obj && obj->version >= version)
|
||||
{
|
||||
// A tombstone above the requested version is already OK
|
||||
if (obj->type() == BS_HEAP_DELETE && obj->version != 0)
|
||||
{
|
||||
op->retval = 0;
|
||||
op->version = obj->version;
|
||||
}
|
||||
else
|
||||
{
|
||||
// The version is occupied by data
|
||||
op->retval = -EEXIST;
|
||||
}
|
||||
FINISH_OP(op);
|
||||
return 2;
|
||||
}
|
||||
PRIV(op)->write_type = BS_HEAP_DELETE;
|
||||
BS_SUBMIT_CHECK_SQES(1);
|
||||
int res = heap->add_tombstone(op->oid, obj, version, &PRIV(op)->modified_block);
|
||||
assert(res != EAGAIN);
|
||||
if (res == ENOSPC)
|
||||
goto enospc;
|
||||
assert(res == 0);
|
||||
prepare_meta_block_write(PRIV(op)->modified_block);
|
||||
PRIV(op)->pending_ops++;
|
||||
PRIV(op)->op_state = 5;
|
||||
op->version = version;
|
||||
write_iodepth++;
|
||||
}
|
||||
else if (op->opcode == BS_OP_DELETE)
|
||||
{
|
||||
// Delete
|
||||
// An absent chain (deleted or fully rolled back) is already "not there"
|
||||
if (!obj || heap->is_absent(obj, true))
|
||||
{
|
||||
op->retval = 0;
|
||||
FINISH_OP(op);
|
||||
return 2;
|
||||
}
|
||||
if (op->version && obj->version > op->version)
|
||||
{
|
||||
// Double-check for tombstone removal - do not delete if the object is recreated
|
||||
op->retval = 0;
|
||||
FINISH_OP(op);
|
||||
return 2;
|
||||
}
|
||||
// A DELETE over a versioned tombstone sweeps it (phase 2 of deletion)
|
||||
PRIV(op)->write_type = BS_HEAP_DELETE;
|
||||
BS_SUBMIT_CHECK_SQES(1);
|
||||
int res = heap->add_delete(obj, &PRIV(op)->modified_block);
|
||||
assert(res != EAGAIN);
|
||||
if (res == ENOSPC)
|
||||
goto enospc;
|
||||
assert(res == 0);
|
||||
@@ -145,7 +198,7 @@ int blockstore_impl_t::dequeue_write(blockstore_op_t *op)
|
||||
}
|
||||
// FIXME: Allow to do initial writes as buffered, not redirected
|
||||
// FIXME: Allow to do direct writes over holes
|
||||
else if (!obj || obj->type() == BS_HEAP_DELETE || op->offset == 0 && op->len == dsk.data_block_size)
|
||||
else if (!obj || heap->is_absent(obj) || op->offset == 0 && op->len == dsk.data_block_size)
|
||||
{
|
||||
// Big (redirect) write
|
||||
PRIV(op)->write_type = dsk.disable_data_fsync || op->opcode != BS_OP_WRITE_STABLE ? BS_HEAP_BIG_WRITE : _REDIRECT_INTENT;
|
||||
@@ -180,7 +233,8 @@ enospc:
|
||||
data->callback = [this, op](ring_data_t *data) { handle_write_event(data, op); };
|
||||
assert(loc+op->offset+op->len <= dsk.block_count*dsk.data_block_size);
|
||||
io_uring_prep_writev(sqe, dsk.data_fd, &data->iov, 1, dsk.data_offset + loc + op->offset);
|
||||
if (!dsk.disable_data_fsync)
|
||||
// redirect_intent writes skip the data fsync (resume_2), so they must not take a slot
|
||||
if (!dsk.disable_data_fsync && PRIV(op)->write_type == BS_HEAP_BIG_WRITE)
|
||||
{
|
||||
// use PRIV->lsn for fsync_data_id
|
||||
PRIV(op)->lsn = ++data_fsync_next;
|
||||
@@ -208,6 +262,7 @@ enospc:
|
||||
PRIV(op)->location = obj->big_location(heap);
|
||||
res = heap->add_big_intent(op->oid, &obj, op->version, op->offset, op->len, op->bitmap,
|
||||
(uint8_t*)op->buf, NULL, &PRIV(op)->modified_block);
|
||||
assert(res != EAGAIN);
|
||||
if (res == ENOSPC)
|
||||
goto enospc;
|
||||
assert(res == 0);
|
||||
@@ -225,6 +280,7 @@ enospc:
|
||||
PRIV(op)->location = wr->big_location(heap);
|
||||
res = heap->add_small_write(op->oid, &obj, (BS_HEAP_INTENT_WRITE | (op->opcode == BS_OP_WRITE_STABLE ? BS_HEAP_STABLE : 0)),
|
||||
op->version, op->offset, op->len, 0, op->bitmap, (uint8_t*)op->buf, &PRIV(op)->modified_block);
|
||||
BS_SUBMIT_CHECK_PLACEMENT(res, obj->lsn);
|
||||
if (res == ENOSPC)
|
||||
goto enospc;
|
||||
assert(res == 0);
|
||||
@@ -243,6 +299,12 @@ enospc:
|
||||
uint64_t loc = !op->len ? 0 : heap->find_free_buffer_area(op->len);
|
||||
if (loc == UINT64_MAX)
|
||||
{
|
||||
if (!heap->get_to_compact_count())
|
||||
{
|
||||
op->retval = -EAGAIN;
|
||||
FINISH_OP(op);
|
||||
return 2;
|
||||
}
|
||||
PRIV(op)->wait_for = WAIT_COMPACTION;
|
||||
PRIV(op)->wait_detail = heap->get_compacted_count();
|
||||
flusher->request_trim();
|
||||
@@ -252,6 +314,7 @@ enospc:
|
||||
BS_SUBMIT_CHECK_SQES(1 + (op->len > 0 ? 1 : 0));
|
||||
int res = heap->add_small_write(op->oid, &obj, (BS_HEAP_SMALL_WRITE | (op->opcode == BS_OP_WRITE_STABLE ? BS_HEAP_STABLE : 0)),
|
||||
op->version, op->offset, op->len, loc, op->bitmap, (uint8_t*)op->buf, &PRIV(op)->modified_block);
|
||||
BS_SUBMIT_CHECK_PLACEMENT(res, obj->lsn);
|
||||
if (res == ENOSPC)
|
||||
goto enospc;
|
||||
assert(res == 0);
|
||||
@@ -341,7 +404,7 @@ resume_11:
|
||||
BS_SUBMIT_GET_SQE(sqe, data);
|
||||
io_uring_prep_fsync(sqe, dsk.data_fd, IORING_FSYNC_DATASYNC);
|
||||
data->iov = { 0 };
|
||||
data->callback = [this, op, fs = data_fsync_cur](ring_data_t *data)
|
||||
data->callback = [this, fs = data_fsync_cur](ring_data_t *data)
|
||||
{
|
||||
live = true;
|
||||
if (data->res != 0)
|
||||
@@ -375,6 +438,7 @@ resume_4:
|
||||
res = heap->add_big_write(op->oid, obj, op->opcode == BS_OP_WRITE_STABLE,
|
||||
op->version, op->offset, op->len, PRIV(op)->location, op->bitmap, (uint8_t*)op->buf, &PRIV(op)->modified_block);
|
||||
}
|
||||
assert(res != EAGAIN);
|
||||
if (res == ENOSPC)
|
||||
{
|
||||
if (!heap->get_to_compact_count())
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// Copyright (c) Vitaliy Filippov, 2025+
|
||||
// License: VNPL-1.1 (see README.md for details)
|
||||
|
||||
#undef NDEBUG
|
||||
#include <assert.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
@@ -58,6 +58,24 @@ journal_flusher_co::journal_flusher_co()
|
||||
};
|
||||
}
|
||||
|
||||
journal_flusher_co::~journal_flusher_co()
|
||||
{
|
||||
// A flush interrupted by an emergency shutdown still holds its read buffers and
|
||||
// references to entry bitmaps/checksums. free_buffers() can't be used here because
|
||||
// it also touches the shared metadata sector map, which may already be gone.
|
||||
for (auto & vi: v)
|
||||
{
|
||||
if (vi.buf && (vi.copy_flags == COPY_BUF_JOURNAL || (vi.copy_flags & COPY_BUF_CSUM_FILL)) &&
|
||||
(!bs->journal.inmemory || vi.buf < bs->journal.buffer ||
|
||||
vi.buf >= (uint8_t*)bs->journal.buffer + bs->journal.len))
|
||||
{
|
||||
free(vi.buf);
|
||||
}
|
||||
bs->free_dirty_dyn_data(vi);
|
||||
}
|
||||
v.clear();
|
||||
}
|
||||
|
||||
journal_flusher_t::~journal_flusher_t()
|
||||
{
|
||||
if (!bs->journal.inmemory)
|
||||
@@ -75,6 +93,16 @@ size_t journal_flusher_t::get_queue_size()
|
||||
return flush_queue.size();
|
||||
}
|
||||
|
||||
bool journal_flusher_t::may_advance()
|
||||
{
|
||||
return flush_queue.size() || active_flushers > 0 || trim_possible;
|
||||
}
|
||||
|
||||
bool journal_flusher_t::may_advance_except_one()
|
||||
{
|
||||
return flush_queue.size() || active_flushers > 1 || trim_possible;
|
||||
}
|
||||
|
||||
void journal_flusher_t::loop()
|
||||
{
|
||||
target_flusher_count = bs->write_iodepth*2;
|
||||
@@ -148,6 +176,22 @@ void journal_flusher_t::unshift_flush(obj_ver_id ov, bool force)
|
||||
}
|
||||
}
|
||||
|
||||
// If the object is being flushed, let that flush requeue <ov> when it finishes. Queueing it now
|
||||
// would leave it in the queue after the flush erases it, and it would hide newer versions
|
||||
bool journal_flusher_t::requeue_after_flush(obj_ver_id ov)
|
||||
{
|
||||
auto repeat_it = sync_to_repeat.find(ov.oid);
|
||||
if (repeat_it == sync_to_repeat.end())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (repeat_it->second < ov.version)
|
||||
{
|
||||
repeat_it->second = ov.version;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void journal_flusher_t::remove_flush(object_id oid)
|
||||
{
|
||||
#ifdef BLOCKSTORE_DEBUG
|
||||
@@ -189,6 +233,7 @@ void journal_flusher_t::request_trim()
|
||||
|
||||
void journal_flusher_t::mark_trim_possible()
|
||||
{
|
||||
trim_possible = true;
|
||||
if (trim_wanted > 0)
|
||||
{
|
||||
dequeuing = true;
|
||||
@@ -202,6 +247,17 @@ void journal_flusher_t::release_trim()
|
||||
trim_wanted--;
|
||||
}
|
||||
|
||||
// The flusher puts back entries whose journal sector isn't written yet and stops if it finds
|
||||
// nothing else. Writing the sector makes them flushable, and nothing else may wake it then
|
||||
void journal_flusher_t::wakeup_on_journal_written()
|
||||
{
|
||||
if (!dequeuing && flush_queue.size() && (flush_queue.size() >= flusher_start_threshold || trim_wanted > 0))
|
||||
{
|
||||
dequeuing = true;
|
||||
bs->ringloop->wakeup();
|
||||
}
|
||||
}
|
||||
|
||||
void journal_flusher_t::dump_diagnostics()
|
||||
{
|
||||
const char *unflushable_type = "";
|
||||
@@ -514,7 +570,7 @@ resume_2:
|
||||
auto uo_it = bs->used_clean_objects.find(clean_loc);
|
||||
if (uo_it != bs->used_clean_objects.end())
|
||||
{
|
||||
uo_it->second.was_changed = true;
|
||||
uo_it->second.changes++;
|
||||
}
|
||||
if (!bs->journal.inmemory)
|
||||
{
|
||||
@@ -572,6 +628,12 @@ resume_2:
|
||||
{
|
||||
// zero out old metadata entry
|
||||
{
|
||||
// Reads of the old location must not verify checksums against the zeroed entry
|
||||
auto uo_it = bs->used_clean_objects.find(old_clean_loc);
|
||||
if (uo_it != bs->used_clean_objects.end())
|
||||
{
|
||||
uo_it->second.changes++;
|
||||
}
|
||||
clean_disk_entry *old_entry = (clean_disk_entry*)((uint8_t*)meta_old.buf + meta_old.pos*bs->dsk.clean_entry_size);
|
||||
if (old_entry->oid.inode != 0 && old_entry->oid != cur.oid)
|
||||
{
|
||||
@@ -651,9 +713,10 @@ resume_2:
|
||||
flusher->sync_to_repeat.erase(repeat_it);
|
||||
trim_journal:
|
||||
// Clear unused part of the journal every <journal_trim_interval> flushes
|
||||
if (bs->journal_trim_interval && !((++flusher->journal_trim_counter) % bs->journal_trim_interval) ||
|
||||
flusher->trim_wanted > 0)
|
||||
if ((bs->journal_trim_interval && !((++flusher->journal_trim_counter) % bs->journal_trim_interval) ||
|
||||
flusher->trim_wanted > 0) && flusher->trim_possible)
|
||||
{
|
||||
flusher->trim_possible = false;
|
||||
resume_30:
|
||||
resume_31:
|
||||
resume_32:
|
||||
@@ -770,6 +833,8 @@ void journal_flusher_co::free_buffers()
|
||||
{
|
||||
free(it->buf);
|
||||
}
|
||||
// prepare_read() takes a reference to the entry's bitmap/checksums, drop it
|
||||
bs->free_dirty_dyn_data(*it);
|
||||
}
|
||||
v.clear();
|
||||
}
|
||||
@@ -1495,10 +1560,19 @@ bool journal_flusher_co::trim_journal(int wait_base)
|
||||
printf("Journal flushed\n");
|
||||
exit(0);
|
||||
}
|
||||
bs->wakeup_wait_journal();
|
||||
}
|
||||
else if (!flusher->may_advance_except_one())
|
||||
{
|
||||
bs->wakeup_wait_journal();
|
||||
}
|
||||
flusher->journal_trim_counter = 0;
|
||||
flusher->trimming = false;
|
||||
}
|
||||
else if (!flusher->may_advance_except_one())
|
||||
{
|
||||
bs->wakeup_wait_journal();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -54,6 +54,7 @@ class journal_flusher_co
|
||||
|
||||
bool try_trim = false;
|
||||
bool skip_copy = false, has_delete = false, has_writes = false;
|
||||
~journal_flusher_co();
|
||||
std::vector<copy_buffer_t> v;
|
||||
std::vector<copy_buffer_t>::iterator it;
|
||||
int i = 0;
|
||||
@@ -94,6 +95,7 @@ public:
|
||||
class journal_flusher_t
|
||||
{
|
||||
int trim_wanted = 0;
|
||||
bool trim_possible = false;
|
||||
bool dequeuing = false;
|
||||
int min_flusher_count = 0, max_flusher_count = 0, cur_flusher_count = 0, target_flusher_count = 0;
|
||||
int flusher_start_threshold = 0;
|
||||
@@ -117,19 +119,23 @@ class journal_flusher_t
|
||||
|
||||
bool try_find_older(std::map<obj_ver_id, dirty_entry>::iterator & dirty_end, obj_ver_id & cur);
|
||||
bool try_find_other(std::map<obj_ver_id, dirty_entry>::iterator & dirty_end, obj_ver_id & cur);
|
||||
bool may_advance_except_one();
|
||||
|
||||
public:
|
||||
journal_flusher_t(blockstore_impl_t *bs);
|
||||
~journal_flusher_t();
|
||||
void loop();
|
||||
bool is_trim_wanted() { return trim_wanted; }
|
||||
bool may_advance();
|
||||
bool is_active();
|
||||
size_t get_queue_size();
|
||||
void mark_trim_possible();
|
||||
void request_trim();
|
||||
void release_trim();
|
||||
void wakeup_on_journal_written();
|
||||
void enqueue_flush(obj_ver_id oid);
|
||||
void unshift_flush(obj_ver_id oid, bool force);
|
||||
bool requeue_after_flush(obj_ver_id ov);
|
||||
void remove_flush(object_id oid);
|
||||
void dump_diagnostics();
|
||||
bool is_mutated(uint64_t clean_loc);
|
||||
|
||||
@@ -35,13 +35,47 @@ blockstore_impl_t::blockstore_impl_t(blockstore_config_t & config, ring_loop_i *
|
||||
flusher = new journal_flusher_t(this);
|
||||
}
|
||||
|
||||
// Submit an operation the blockstore created for itself, and remember it so that it can
|
||||
// be cleaned up if we're destroyed before it completes
|
||||
void blockstore_impl_t::enqueue_own_op(blockstore_op_t *op)
|
||||
{
|
||||
own_ops.insert(op);
|
||||
auto cb = op->callback;
|
||||
op->callback = [this, cb](blockstore_op_t *op)
|
||||
{
|
||||
own_ops.erase(op);
|
||||
cb(op);
|
||||
};
|
||||
enqueue_op(op);
|
||||
}
|
||||
|
||||
blockstore_impl_t::~blockstore_impl_t()
|
||||
{
|
||||
for (auto& obj: dirty_db)
|
||||
// Destroy private state of operations still in the queue
|
||||
for (auto op: submit_queue)
|
||||
{
|
||||
if (obj.second.dyn_data)
|
||||
free(obj.second.dyn_data);
|
||||
if (op && !own_ops.count(op))
|
||||
PRIV(op)->~blockstore_op_private_t();
|
||||
}
|
||||
submit_queue.clear();
|
||||
// Reads which were waiting for the disk own their read vector, and nobody is going to
|
||||
// complete them now
|
||||
for (auto op: reads_in_flight)
|
||||
{
|
||||
release_read_vec(op);
|
||||
PRIV(op)->~blockstore_op_private_t();
|
||||
}
|
||||
reads_in_flight.clear();
|
||||
// Destroy our own operations
|
||||
for (auto op: own_ops)
|
||||
{
|
||||
PRIV(op)->~blockstore_op_private_t();
|
||||
delete op;
|
||||
}
|
||||
own_ops.clear();
|
||||
// Clear dyn_data in dirty_db
|
||||
for (auto& obj: dirty_db)
|
||||
free_dirty_dyn_data(obj.second);
|
||||
delete data_alloc;
|
||||
delete flusher;
|
||||
if (zero_object)
|
||||
@@ -126,6 +160,7 @@ void blockstore_impl_t::loop()
|
||||
// has_writes == 1 - some writes in progress
|
||||
// has_writes == 2 - tried to submit some writes, but failed
|
||||
int has_writes = 0, op_idx = 0, new_idx = 0;
|
||||
bool has_unfinished_sync = false;
|
||||
for (; op_idx < submit_queue.size(); op_idx++, new_idx++)
|
||||
{
|
||||
auto op = submit_queue[op_idx];
|
||||
@@ -183,7 +218,22 @@ void blockstore_impl_t::loop()
|
||||
// sync only completed writes?
|
||||
// wait for the data device fsync to complete, then submit journal writes for big writes
|
||||
// then submit an fsync operation
|
||||
wr_st = continue_sync(op);
|
||||
//
|
||||
// Only one sync at a time: continue_sync() takes the unsynced writes over into
|
||||
// its own state, so a second sync started while the first one is still in flight
|
||||
// would find nothing left to sync and report success without anything having
|
||||
// reached the disk - while the writes it was supposed to cover are still in the
|
||||
// first sync's hands.
|
||||
// A deletion takes them over in the very same way, see
|
||||
// forget_unstable_before_delete() - so wait for it to be journaled and acked,
|
||||
// and it lands in the unsynced lists itself by then
|
||||
if (!has_unfinished_sync && !unsynced_forgotten)
|
||||
{
|
||||
wr_st = continue_sync(op);
|
||||
has_unfinished_sync = (wr_st != 2);
|
||||
}
|
||||
else
|
||||
wr_st = 0;
|
||||
}
|
||||
else if (op->opcode == BS_OP_STABLE)
|
||||
{
|
||||
@@ -212,10 +262,6 @@ void blockstore_impl_t::loop()
|
||||
// ring is full, stop submission
|
||||
break;
|
||||
}
|
||||
else if (PRIV(op)->wait_for == WAIT_JOURNAL)
|
||||
{
|
||||
PRIV(op)->wait_detail2 = (unstable_writes.size()+unstable_unsynced);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (op_idx != new_idx)
|
||||
@@ -272,7 +318,7 @@ bool blockstore_impl_t::is_safe_to_stop()
|
||||
{
|
||||
delete op;
|
||||
};
|
||||
enqueue_op(op);
|
||||
enqueue_own_op(op);
|
||||
stop_sync_submitted = true;
|
||||
}
|
||||
return false;
|
||||
@@ -280,6 +326,12 @@ bool blockstore_impl_t::is_safe_to_stop()
|
||||
return true;
|
||||
}
|
||||
|
||||
void blockstore_impl_t::wakeup_wait_journal()
|
||||
{
|
||||
wait_journal_counter++;
|
||||
ringloop->wakeup();
|
||||
}
|
||||
|
||||
void blockstore_impl_t::check_wait(blockstore_op_t *op)
|
||||
{
|
||||
if (PRIV(op)->wait_for == WAIT_SQE)
|
||||
@@ -296,12 +348,11 @@ void blockstore_impl_t::check_wait(blockstore_op_t *op)
|
||||
}
|
||||
else if (PRIV(op)->wait_for == WAIT_JOURNAL)
|
||||
{
|
||||
if (journal.used_start == PRIV(op)->wait_detail &&
|
||||
(unstable_writes.size()+unstable_unsynced) == PRIV(op)->wait_detail2)
|
||||
if (wait_journal_counter == PRIV(op)->wait_detail)
|
||||
{
|
||||
// do not submit
|
||||
#ifdef BLOCKSTORE_DEBUG
|
||||
printf("Still waiting to flush journal offset %08jx\n", PRIV(op)->wait_detail);
|
||||
printf("Still waiting for flush journal counter %ju\n", PRIV(op)->wait_detail);
|
||||
#endif
|
||||
return;
|
||||
}
|
||||
@@ -355,6 +406,13 @@ void blockstore_impl_t::enqueue_op(blockstore_op_t *op)
|
||||
ringloop->set_immediate([op]() { std::function<void (blockstore_op_t*)>(op->callback)(op); });
|
||||
return;
|
||||
}
|
||||
if (op->opcode == BS_OP_TOMBSTONE)
|
||||
{
|
||||
// Tombstones are only supported by the heap blockstore (meta_format 3)
|
||||
op->retval = -EOPNOTSUPP;
|
||||
ringloop->set_immediate([op]() { std::function<void (blockstore_op_t*)>(op->callback)(op); });
|
||||
return;
|
||||
}
|
||||
if ((op->opcode == BS_OP_WRITE || op->opcode == BS_OP_WRITE_STABLE || op->opcode == BS_OP_DELETE) && !enqueue_write(op))
|
||||
{
|
||||
ringloop->set_immediate([op]() { std::function<void (blockstore_op_t*)>(op->callback)(op); });
|
||||
@@ -377,6 +435,7 @@ void blockstore_impl_t::init_op(blockstore_op_t *op)
|
||||
PRIV(op)->wait_for = 0;
|
||||
PRIV(op)->op_state = 0;
|
||||
PRIV(op)->pending_ops = 0;
|
||||
PRIV(op)->forgot_unsynced = false;
|
||||
}
|
||||
|
||||
static bool replace_stable(object_id oid, uint64_t version, int search_start, int search_end, obj_ver_id* list)
|
||||
@@ -489,6 +548,7 @@ resume_1:
|
||||
|
||||
void blockstore_impl_t::process_list(blockstore_op_t *op)
|
||||
{
|
||||
op->tombstone_count = 0; // the v1 store never has tombstones
|
||||
uint32_t list_pg = op->pg_number+1;
|
||||
uint32_t pg_count = op->pg_count;
|
||||
uint64_t pg_stripe_size = op->pg_alignment;
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <set>
|
||||
|
||||
#include "blockstore.h"
|
||||
#include "blockstore_disk.h"
|
||||
#include "ondisk_formats.h"
|
||||
@@ -76,7 +78,7 @@ struct used_clean_obj_t
|
||||
{
|
||||
int refs;
|
||||
bool was_freed; // was freed by a parallel flush?
|
||||
bool was_changed; // was changed by a parallel flush?
|
||||
uint64_t changes; // number of parallel flushes which changed it while it was used
|
||||
};
|
||||
|
||||
// https://github.com/algorithm-ninja/cpp-btree
|
||||
@@ -93,12 +95,14 @@ struct blockstore_op_private_t
|
||||
{
|
||||
// Wait status
|
||||
int wait_for;
|
||||
uint64_t wait_detail, wait_detail2;
|
||||
uint64_t wait_detail;
|
||||
int pending_ops;
|
||||
int op_state;
|
||||
|
||||
// Read
|
||||
uint64_t clean_loc_used;
|
||||
// used_clean_obj_t::changes at read start, UINT64_MAX if a flush was already running and the read is padded
|
||||
uint64_t clean_changes;
|
||||
std::vector<copy_buffer_t> read_vec;
|
||||
|
||||
// Sync, write
|
||||
@@ -109,6 +113,9 @@ struct blockstore_op_private_t
|
||||
// Warning: must not have a default value here because it's written to before calling constructor in blockstore_write.cpp O_o
|
||||
uint64_t real_version;
|
||||
timespec tv_begin;
|
||||
// Set on a deletion which dropped preceding unsynced writes of the same object,
|
||||
// see forget_unstable_before_delete()
|
||||
bool forgot_unsynced;
|
||||
|
||||
// Sync
|
||||
std::vector<obj_ver_id> sync_big_writes, sync_small_writes;
|
||||
@@ -163,8 +170,15 @@ class blockstore_impl_t: public blockstore_i
|
||||
uint8_t *clean_bitmaps = NULL;
|
||||
blockstore_dirty_db_t dirty_db;
|
||||
std::vector<blockstore_op_t*> submit_queue;
|
||||
// Reads waiting for their disk requests. They're out of submit_queue already, but we
|
||||
// still own their private state, including the read vector - see the destructor
|
||||
std::set<blockstore_op_t*> reads_in_flight;
|
||||
std::set<blockstore_op_t*> own_ops;
|
||||
std::vector<obj_ver_id> unsynced_big_writes, unsynced_small_writes;
|
||||
int unsynced_big_write_count = 0, unstable_unsynced = 0;
|
||||
// Number of deletions which took over the durability of preceding unsynced writes but
|
||||
// aren't journaled themselves yet, see forget_unstable_before_delete()
|
||||
int unsynced_forgotten = 0;
|
||||
int unsynced_queued_ops = 0;
|
||||
allocator_t *data_alloc = NULL;
|
||||
uint64_t used_blocks = 0;
|
||||
@@ -206,6 +220,7 @@ class blockstore_impl_t: public blockstore_i
|
||||
|
||||
// Journaling
|
||||
void prepare_journal_sector_write(int sector, blockstore_op_t *op);
|
||||
void mark_not_dirty(int journal_sector);
|
||||
void handle_journal_write(ring_data_t *data, uint64_t flush_id);
|
||||
void disk_error_abort(const char *op, int retval, int expected);
|
||||
|
||||
@@ -215,12 +230,15 @@ class blockstore_impl_t: public blockstore_i
|
||||
blockstore_init_meta* metadata_init_reader;
|
||||
blockstore_init_journal* journal_init_reader;
|
||||
|
||||
uint64_t wait_journal_counter = 0;
|
||||
void wakeup_wait_journal();
|
||||
void check_wait(blockstore_op_t *op);
|
||||
void init_op(blockstore_op_t *op);
|
||||
|
||||
// Read
|
||||
int dequeue_read(blockstore_op_t *read_op);
|
||||
void release_clean(blockstore_op_t *op);
|
||||
void release_read_vec(blockstore_op_t *read_op);
|
||||
void find_holes(std::vector<copy_buffer_t> & read_vec, uint32_t item_start, uint32_t item_end,
|
||||
std::function<int(int, bool, uint32_t, uint32_t)> callback);
|
||||
int fulfill_read(blockstore_op_t *read_op,
|
||||
@@ -251,13 +269,16 @@ class blockstore_impl_t: public blockstore_i
|
||||
void handle_read_event(ring_data_t *data, blockstore_op_t *op);
|
||||
|
||||
// Write
|
||||
bool forget_unstable_before_delete(blockstore_op_t *op, blockstore_dirty_db_t::iterator dirty_it);
|
||||
bool enqueue_write(blockstore_op_t *op);
|
||||
void unshift_stable_flush(obj_ver_id ov);
|
||||
void cancel_all_writes(blockstore_op_t *op, blockstore_dirty_db_t::iterator dirty_it, int retval);
|
||||
int dequeue_write(blockstore_op_t *op);
|
||||
int dequeue_del(blockstore_op_t *op);
|
||||
int continue_write(blockstore_op_t *op);
|
||||
void release_journal_sectors(blockstore_op_t *op);
|
||||
void handle_write_event(ring_data_t *data, blockstore_op_t *op);
|
||||
void enqueue_own_op(blockstore_op_t *op);
|
||||
|
||||
// Sync
|
||||
int continue_sync(blockstore_op_t *op);
|
||||
@@ -277,6 +298,7 @@ class blockstore_impl_t: public blockstore_i
|
||||
void mark_rolled_back(const obj_ver_id & ov);
|
||||
void erase_dirty(blockstore_dirty_db_t::iterator dirty_start, blockstore_dirty_db_t::iterator dirty_end, uint64_t clean_loc);
|
||||
void free_dirty_dyn_data(dirty_entry & e);
|
||||
void free_dirty_dyn_data(copy_buffer_t & e);
|
||||
|
||||
// List
|
||||
void process_list(blockstore_op_t *op);
|
||||
|
||||
@@ -510,6 +510,8 @@ int blockstore_init_journal::loop()
|
||||
goto resume_6;
|
||||
else if (wait_state == 7)
|
||||
goto resume_7;
|
||||
else if (wait_state == 8)
|
||||
goto resume_8;
|
||||
printf("Reading blockstore journal\n");
|
||||
if (!bs->journal.inmemory)
|
||||
submitted_buf = memalign_or_die(MEM_ALIGNMENT, 2*bs->journal.block_size);
|
||||
@@ -675,6 +677,7 @@ resume_1:
|
||||
// zero out corrupted entry, if required
|
||||
if (init_write_buf && !bs->readonly)
|
||||
{
|
||||
assert(init_write_sector > 0);
|
||||
GET_SQE();
|
||||
data->iov = { init_write_buf, (size_t)bs->journal.block_size };
|
||||
data->callback = simple_callback;
|
||||
@@ -752,6 +755,43 @@ resume_1:
|
||||
}
|
||||
bs->flusher->mark_trim_possible();
|
||||
bs->journal.dirty_start = bs->journal.next_free;
|
||||
if (!bs->readonly)
|
||||
{
|
||||
// Everything we just read may still be sitting in the volatile write cache of the device:
|
||||
// the instance which wrote it is gone, so nothing is going to flush it any more, and a
|
||||
// sync would find nothing of its own to sync and report success while a power outage
|
||||
// could still take the recovered state away. Make it durable right here instead
|
||||
{
|
||||
bool fsync_data = !bs->disable_data_fsync;
|
||||
bool fsync_meta = !bs->disable_meta_fsync;
|
||||
bool fsync_journal = !bs->disable_journal_fsync;
|
||||
// The same device may serve several roles - fsync each distinct one exactly once
|
||||
if (bs->dsk.meta_fd == bs->dsk.data_fd)
|
||||
fsync_data = fsync_data || fsync_meta, fsync_meta = false;
|
||||
if (bs->dsk.journal_fd == bs->dsk.data_fd)
|
||||
fsync_data = fsync_data || fsync_journal, fsync_journal = false;
|
||||
else if (bs->dsk.journal_fd == bs->dsk.meta_fd)
|
||||
fsync_meta = fsync_meta || fsync_journal, fsync_journal = false;
|
||||
for (int i = 0; i < 3; i++)
|
||||
{
|
||||
if (i == 0 ? !fsync_data : (i == 1 ? !fsync_meta : !fsync_journal))
|
||||
continue;
|
||||
GET_SQE();
|
||||
data->iov = { 0 };
|
||||
data->callback = simple_callback;
|
||||
io_uring_prep_fsync(sqe, i == 0 ? bs->dsk.data_fd : (i == 1 ? bs->dsk.meta_fd : bs->dsk.journal_fd), IORING_FSYNC_DATASYNC);
|
||||
wait_count++;
|
||||
}
|
||||
if (wait_count > 0)
|
||||
bs->ringloop->submit();
|
||||
}
|
||||
resume_8:
|
||||
if (wait_count > 0)
|
||||
{
|
||||
wait_state = 8;
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
printf(
|
||||
"Journal entries loaded: %ju, free journal space: %ju bytes (%08jx..%08jx is used), free blocks: %ju / %ju\n",
|
||||
entries_loaded,
|
||||
@@ -948,10 +988,10 @@ int blockstore_init_journal::handle_journal_part(void *buf, uint64_t done_pos, u
|
||||
if (block_crc32 != *block_csums)
|
||||
{
|
||||
printf(
|
||||
"Journal entry data is corrupt for small_write%s oid=%jx:%jx ver=%ju offset=%u len=%u - block %u crc32 %x != %x\n",
|
||||
"Journal entry data is corrupt for small_write%s oid=%jx:%jx ver=%ju offset=%u len=%u data_offset=%jx - block %u crc32 %x != %x\n",
|
||||
je->type == JE_SMALL_WRITE_INSTANT ? "_instant" : "",
|
||||
je->small_write.oid.inode, je->small_write.oid.stripe, je->small_write.version,
|
||||
je->small_write.offset, je->small_write.len,
|
||||
je->small_write.offset, je->small_write.len, (uint64_t)je->small_write.data_offset,
|
||||
pos, block_crc32, *block_csums
|
||||
);
|
||||
data_csum_valid = false;
|
||||
@@ -966,7 +1006,12 @@ int blockstore_init_journal::handle_journal_part(void *buf, uint64_t done_pos, u
|
||||
// interesting thing is that we must clear the corrupt entry if we're not readonly,
|
||||
// because we don't write next entries in the same journal block
|
||||
memset((uint8_t*)buf + proc_pos - done_pos + pos, 0, bs->journal.block_size - pos);
|
||||
bs->journal.next_free = prev_free;
|
||||
// If the corrupt entry was the first one in its block then clearing it
|
||||
// empties the whole block, and an empty block is exactly what marks the
|
||||
// end of the journal. Resuming after such a block would turn it into a
|
||||
// permanent barrier: every later replay would stop at it again and
|
||||
// discard everything written after it. So reuse the block instead.
|
||||
bs->journal.next_free = pos == 0 ? proc_pos : prev_free;
|
||||
init_write_buf = (uint8_t*)buf + proc_pos - done_pos;
|
||||
init_write_sector = proc_pos;
|
||||
return 0;
|
||||
@@ -1000,7 +1045,7 @@ int blockstore_init_journal::handle_journal_part(void *buf, uint64_t done_pos, u
|
||||
memcpy((uint8_t*)dyn+sizeof(int), dyn_from, dyn_size);
|
||||
}
|
||||
bs->dirty_db.emplace(ov, (dirty_entry){
|
||||
.state = (BS_ST_SMALL_WRITE | BS_ST_SYNCED),
|
||||
.state = (uint32_t)(BS_ST_SMALL_WRITE | BS_ST_SYNCED | (je->type == JE_SMALL_WRITE_INSTANT ? BS_ST_INSTANT : 0)),
|
||||
.flags = 0,
|
||||
.location = location,
|
||||
.offset = je->small_write.offset,
|
||||
@@ -1084,7 +1129,7 @@ int blockstore_init_journal::handle_journal_part(void *buf, uint64_t done_pos, u
|
||||
memcpy((uint8_t*)dyn+sizeof(int), dyn_from, dyn_size);
|
||||
}
|
||||
auto dirty_it = bs->dirty_db.emplace(ov, (dirty_entry){
|
||||
.state = (BS_ST_BIG_WRITE | BS_ST_SYNCED),
|
||||
.state = (uint32_t)(BS_ST_BIG_WRITE | BS_ST_SYNCED | (je->type == JE_BIG_WRITE_INSTANT ? BS_ST_INSTANT : 0)),
|
||||
.flags = 0,
|
||||
.location = je->big_write.location,
|
||||
.offset = je->big_write.offset,
|
||||
|
||||
@@ -15,6 +15,7 @@ blockstore_journal_check_t::blockstore_journal_check_t(blockstore_impl_t *bs)
|
||||
first_sector = -1;
|
||||
next_in_pos = bs->journal.in_sector_pos;
|
||||
right_dir = next_pos >= bs->journal.used_start;
|
||||
give_up = false;
|
||||
}
|
||||
|
||||
// Check if we can write <required> entries of <size> bytes and <data_after> data bytes after them to the journal
|
||||
@@ -24,7 +25,9 @@ int blockstore_journal_check_t::check_available(blockstore_op_t *op, int entries
|
||||
int required = entries_required;
|
||||
while (1)
|
||||
{
|
||||
int fits = bs->journal.no_same_sector_overwrites && next_pos == bs->journal.next_free && bs->journal.sector_info[next_sector].written
|
||||
// Must match journal_t::entry_fits()
|
||||
int fits = next_pos == bs->journal.next_free && bs->journal.sector_info[next_sector].written &&
|
||||
(bs->journal.no_same_sector_overwrites || bs->journal.sector_info[next_sector].flush_count > 0)
|
||||
? 0
|
||||
: (bs->journal.block_size - next_in_pos) / size;
|
||||
if (fits > 0)
|
||||
@@ -119,13 +122,20 @@ int blockstore_journal_check_t::check_available(blockstore_op_t *op, int entries
|
||||
if (bs->log_level > 5)
|
||||
{
|
||||
printf(
|
||||
"Ran out of journal space (used_start=%08jx, next_free=%08jx, dirty_start=%08jx)\n",
|
||||
bs->journal.used_start, bs->journal.next_free, bs->journal.dirty_start
|
||||
"Ran out of journal space (used_start=%08jx, next_free=%08jx, dirty_start=%08jx, queued %zu)\n",
|
||||
bs->journal.used_start, bs->journal.next_free, bs->journal.dirty_start, bs->flusher->get_queue_size()
|
||||
);
|
||||
}
|
||||
PRIV(op)->wait_for = WAIT_JOURNAL;
|
||||
bs->flusher->request_trim();
|
||||
PRIV(op)->wait_detail = bs->journal.used_start;
|
||||
if (!bs->flusher->may_advance())
|
||||
{
|
||||
give_up = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
PRIV(op)->wait_for = WAIT_JOURNAL;
|
||||
PRIV(op)->wait_detail = bs->wait_journal_counter;
|
||||
bs->flusher->request_trim();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
@@ -175,6 +185,8 @@ journal_entry* prefill_single_journal_entry(journal_t & journal, uint16_t type,
|
||||
void blockstore_impl_t::prepare_journal_sector_write(int cur_sector, blockstore_op_t *op)
|
||||
{
|
||||
// Don't submit the same sector twice in the same batch
|
||||
assert(journal.sector_info[cur_sector].dirty);
|
||||
bool submitted_now = false;
|
||||
if (!journal.sector_info[cur_sector].submit_id)
|
||||
{
|
||||
io_uring_sqe *sqe = get_sqe();
|
||||
@@ -193,16 +205,24 @@ void blockstore_impl_t::prepare_journal_sector_write(int cur_sector, blockstore_
|
||||
(size_t)journal.block_size
|
||||
};
|
||||
data->callback = [this, flush_id = journal.submit_id](ring_data_t *data) { handle_journal_write(data, flush_id); };
|
||||
assert(journal.sector_info[cur_sector].offset > 0);
|
||||
assert(journal.sector_info[cur_sector].offset+journal.block_size <= dsk.journal_len);
|
||||
io_uring_prep_writev(
|
||||
sqe, dsk.journal_fd, &data->iov, 1, journal.offset + journal.sector_info[cur_sector].offset
|
||||
);
|
||||
submitted_now = true;
|
||||
}
|
||||
journal.sector_info[cur_sector].dirty = false;
|
||||
// But always remember that this operation has to wait until this exact journal write is finished
|
||||
journal.flushing_ops.emplace(journal.sector_info[cur_sector].submit_id, (pending_journaling_t){
|
||||
// But always remember that this operation has to wait until this exact journal write is finished.
|
||||
// An operation which appends to a sector another one has already queued in this same batch also
|
||||
// has to wait for everything queued in between - the journal data write of that other operation
|
||||
// in particular. That data lies behind our entry on the disk, and recovery stops at the first
|
||||
// hole in the journal, so completing before it is durable would let an acknowledged operation
|
||||
// disappear together with the unfinished write in front of it
|
||||
journal.flushing_ops.emplace(journal.submit_id, (pending_journaling_t){
|
||||
.pending = 1,
|
||||
.sector = cur_sector,
|
||||
// Only the operation which queued the sector write itself releases its flush_count
|
||||
.sector = submitted_now ? cur_sector : -1,
|
||||
.op = op,
|
||||
});
|
||||
auto priv = PRIV(op);
|
||||
@@ -226,38 +246,33 @@ void blockstore_impl_t::handle_journal_write(ring_data_t *data, uint64_t flush_i
|
||||
{
|
||||
journal.sector_info[fl_it->second.sector].flush_count--;
|
||||
}
|
||||
auto is_first = fl_it == journal.flushing_ops.begin();
|
||||
while (fl_it != journal.flushing_ops.end())
|
||||
// Mark every operation waiting for this exact write as no longer pending
|
||||
for (auto it = fl_it; it != journal.flushing_ops.end() && it->first == flush_id; it++)
|
||||
{
|
||||
bool del = false;
|
||||
if (fl_it->first == flush_id)
|
||||
it->second.pending = 0;
|
||||
}
|
||||
// Do not complete an operation while an earlier journal write is still in flight:
|
||||
// a power outage would then leave a hole in the journal in front of it, and recovery
|
||||
// stops at the first hole, so an already acknowledged operation would be lost.
|
||||
// Only release operations when the write that just finished is the oldest unfinished
|
||||
// one, and then cascade over the following writes that are already finished, stopping
|
||||
// at the first one which isn't.
|
||||
if (fl_it != journal.flushing_ops.begin())
|
||||
{
|
||||
return;
|
||||
}
|
||||
while (fl_it != journal.flushing_ops.end() && !fl_it->second.pending)
|
||||
{
|
||||
auto priv = PRIV(fl_it->second.op);
|
||||
priv->pending_ops--;
|
||||
assert(priv->pending_ops >= 0);
|
||||
if (priv->pending_ops == 0)
|
||||
{
|
||||
fl_it->second.pending = 0;
|
||||
del = is_first;
|
||||
}
|
||||
else
|
||||
{
|
||||
del = !fl_it->second.pending;
|
||||
}
|
||||
if (del)
|
||||
{
|
||||
// Do not complete this operation if previous writes are unfinished
|
||||
// Otherwise also complete following operations waiting for this one
|
||||
auto priv = PRIV(fl_it->second.op);
|
||||
priv->pending_ops--;
|
||||
assert(priv->pending_ops >= 0);
|
||||
if (priv->pending_ops == 0)
|
||||
{
|
||||
release_journal_sectors(fl_it->second.op);
|
||||
priv->op_state++;
|
||||
ringloop->wakeup();
|
||||
}
|
||||
journal.flushing_ops.erase(fl_it++);
|
||||
}
|
||||
else
|
||||
{
|
||||
fl_it++;
|
||||
release_journal_sectors(fl_it->second.op);
|
||||
priv->op_state++;
|
||||
ringloop->wakeup();
|
||||
}
|
||||
journal.flushing_ops.erase(fl_it++);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -23,12 +23,12 @@ struct pending_journaling_t
|
||||
|
||||
struct journal_t
|
||||
{
|
||||
int fd;
|
||||
int fd = -1;
|
||||
bool inmemory = false;
|
||||
bool flush_journal = false;
|
||||
void *buffer = NULL;
|
||||
|
||||
uint64_t block_size;
|
||||
uint64_t block_size = 0;
|
||||
uint64_t offset, len;
|
||||
// Next free block offset
|
||||
uint64_t next_free = 0;
|
||||
@@ -41,7 +41,7 @@ struct journal_t
|
||||
// Current sector(s) used for writing
|
||||
void *sector_buf = NULL;
|
||||
journal_sector_info_t *sector_info = NULL;
|
||||
uint64_t sector_count;
|
||||
uint64_t sector_count = 0;
|
||||
bool no_same_sector_overwrites = false;
|
||||
int cur_sector = 0;
|
||||
int in_sector_pos = 0;
|
||||
@@ -59,8 +59,10 @@ struct journal_t
|
||||
void dump_diagnostics();
|
||||
inline bool entry_fits(int size)
|
||||
{
|
||||
// Never append to a sector which is still being written: re-submitting it is probably UB
|
||||
return !(block_size - in_sector_pos < size ||
|
||||
no_same_sector_overwrites && sector_info[cur_sector].written);
|
||||
sector_info[cur_sector].written &&
|
||||
(no_same_sector_overwrites || sector_info[cur_sector].flush_count > 0));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -70,6 +72,7 @@ struct blockstore_journal_check_t
|
||||
uint64_t next_pos, next_sector, next_in_pos;
|
||||
int sectors_to_write, first_sector;
|
||||
bool right_dir; // writing to the end or the beginning of the ring buffer
|
||||
bool give_up;
|
||||
|
||||
blockstore_journal_check_t(blockstore_impl_t *bs);
|
||||
int check_available(blockstore_op_t *op, int required, int size, int data_after);
|
||||
|
||||
@@ -511,7 +511,7 @@ int blockstore_impl_t::dequeue_read(blockstore_op_t *read_op)
|
||||
// Copy from memory or read from journal, possibly checking checksums
|
||||
if (!fulfill_read(read_op, fulfilled, dirty.offset, dirty.offset + dirty.len,
|
||||
dirty.state, dirty_it->first.version, dirty.location, dirty.journal_sector+1,
|
||||
journal.inmemory ? NULL : bmp_ptr+dsk.clean_entry_bitmap_size, dyn_data))
|
||||
journal.inmemory || !dsk.csum_block_size ? NULL : bmp_ptr+dsk.clean_entry_bitmap_size, dyn_data))
|
||||
{
|
||||
goto undo_read;
|
||||
}
|
||||
@@ -549,6 +549,7 @@ int blockstore_impl_t::dequeue_read(blockstore_op_t *read_op)
|
||||
// May happen if there are entries in dirty_db but all of them are !version_ok
|
||||
read_op->version = 0;
|
||||
read_op->retval = -ENOENT;
|
||||
release_read_vec(read_op);
|
||||
FINISH_OP(read_op);
|
||||
return 2;
|
||||
}
|
||||
@@ -562,6 +563,9 @@ int blockstore_impl_t::dequeue_read(blockstore_op_t *read_op)
|
||||
// region is not allocated - return zeroes
|
||||
memset(read_op->buf, 0, read_op->len);
|
||||
}
|
||||
// Nothing was submitted, so no completion handler will run - release the
|
||||
// references the read vector holds on entry bitmaps and checksums
|
||||
release_read_vec(read_op);
|
||||
read_op->retval = read_op->len;
|
||||
FINISH_OP(read_op);
|
||||
return 2;
|
||||
@@ -576,25 +580,29 @@ int blockstore_impl_t::dequeue_read(blockstore_op_t *read_op)
|
||||
}
|
||||
}
|
||||
read_op->retval = 0;
|
||||
reads_in_flight.insert(read_op);
|
||||
return 2;
|
||||
undo_read:
|
||||
// need to wait. undo added requests, don't dequeue op
|
||||
release_clean(read_op);
|
||||
for (auto & vec: rv)
|
||||
release_read_vec(read_op);
|
||||
rv.clear();
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Free the buffers and drop the references that a read vector holds on the bitmaps and
|
||||
// checksums of dirty entries. Safe to call more than once.
|
||||
void blockstore_impl_t::release_read_vec(blockstore_op_t *read_op)
|
||||
{
|
||||
for (auto & vec: PRIV(read_op)->read_vec)
|
||||
{
|
||||
if ((vec.copy_flags & COPY_BUF_CSUM_FILL) && vec.buf)
|
||||
{
|
||||
free(vec.buf);
|
||||
vec.buf = NULL;
|
||||
}
|
||||
if (vec.dyn_data && --(*vec.dyn_data) == 0) // refcount
|
||||
{
|
||||
free(vec.dyn_data);
|
||||
vec.dyn_data = NULL;
|
||||
}
|
||||
free_dirty_dyn_data(vec);
|
||||
}
|
||||
rv.clear();
|
||||
return 0;
|
||||
}
|
||||
|
||||
void blockstore_impl_t::release_clean(blockstore_op_t *op)
|
||||
@@ -779,8 +787,8 @@ bool blockstore_impl_t::fulfill_clean_read(blockstore_op_t *read_op, uint64_t &
|
||||
{
|
||||
auto & uo = used_clean_objects[clean_loc];
|
||||
uo.refs++;
|
||||
if (dsk.csum_block_size && flusher->is_mutated(clean_loc))
|
||||
uo.was_changed = true;
|
||||
PRIV(read_op)->clean_changes = dsk.csum_block_size > dsk.bitmap_granularity && flusher->is_mutated(clean_loc)
|
||||
? UINT64_MAX : uo.changes;
|
||||
PRIV(read_op)->clean_loc_used = clean_loc + 1;
|
||||
}
|
||||
return true;
|
||||
@@ -933,33 +941,42 @@ void blockstore_impl_t::handle_read_event(ring_data_t *data, blockstore_op_t *op
|
||||
if (dsk.csum_block_size)
|
||||
{
|
||||
// verify checksums if required
|
||||
bool read_failed = op->retval < 0;
|
||||
auto & rv = PRIV(op)->read_vec;
|
||||
void *meta_block = NULL;
|
||||
if (dsk.csum_block_size > dsk.bitmap_granularity)
|
||||
{
|
||||
for (int i = 0; i < rv.size(); i++)
|
||||
{
|
||||
// Every entry holds a reference to the bitmap/checksums of its dirty
|
||||
// entry, so it has to be released even when the entry itself is skipped
|
||||
bool skip = false;
|
||||
if (rv[i].copy_flags & COPY_BUF_META_BLOCK)
|
||||
{
|
||||
// Metadata read. Skip
|
||||
assert(!meta_block);
|
||||
meta_block = rv[i].buf;
|
||||
rv[i].buf = NULL;
|
||||
continue;
|
||||
skip = true;
|
||||
}
|
||||
if (rv[i].copy_flags & COPY_BUF_ZERO)
|
||||
else if (rv[i].copy_flags & COPY_BUF_ZERO)
|
||||
{
|
||||
// Zero read
|
||||
continue;
|
||||
skip = true;
|
||||
}
|
||||
if (rv[i].copy_flags & COPY_BUF_COALESCED)
|
||||
else if (rv[i].copy_flags & COPY_BUF_COALESCED)
|
||||
{
|
||||
// Sub-block shared with another read. Skip
|
||||
continue;
|
||||
skip = true;
|
||||
}
|
||||
if ((rv[i].copy_flags & COPY_BUF_JOURNAL) && journal.inmemory)
|
||||
else if ((rv[i].copy_flags & COPY_BUF_JOURNAL) && journal.inmemory)
|
||||
{
|
||||
// Do not check journal checksums in-memory
|
||||
skip = true;
|
||||
}
|
||||
if (skip)
|
||||
{
|
||||
free_dirty_dyn_data(rv[i]);
|
||||
continue;
|
||||
}
|
||||
iovec single_iov = {};
|
||||
@@ -983,7 +1000,11 @@ void blockstore_impl_t::handle_read_event(ring_data_t *data, blockstore_op_t *op
|
||||
single_iov = { .iov_base = op->buf + rv[i].offset - op->offset, .iov_len = rv[i].len };
|
||||
}
|
||||
bool ok = true;
|
||||
if (rv[i].copy_flags & COPY_BUF_JOURNAL)
|
||||
if (read_failed)
|
||||
{
|
||||
// Nothing to verify, the failed read didn't fill the buffer
|
||||
}
|
||||
else if (rv[i].copy_flags & COPY_BUF_JOURNAL)
|
||||
{
|
||||
// SMALL_WRITE from journal
|
||||
verify_journal_checksums(
|
||||
@@ -1002,9 +1023,9 @@ void blockstore_impl_t::handle_read_event(ring_data_t *data, blockstore_op_t *op
|
||||
else
|
||||
{
|
||||
// BIG_WRITE from journal or clean data
|
||||
// Do not verify checksums if the data location is/was mutated by flushers
|
||||
// Do not verify checksums if the data location was mutated by a flush during this read
|
||||
auto & uo = used_clean_objects.at((rv[i].disk_offset / dsk.data_block_size) * dsk.data_block_size);
|
||||
if (!uo.was_changed)
|
||||
if (PRIV(op)->clean_changes != UINT64_MAX && uo.changes == PRIV(op)->clean_changes)
|
||||
{
|
||||
verify_clean_padded_checksums(
|
||||
op, rv[i].disk_offset, rv[i].csum_buf, (rv[i].copy_flags & COPY_BUF_JOURNALED_BIG), iov, n_iov,
|
||||
@@ -1027,26 +1048,26 @@ void blockstore_impl_t::handle_read_event(ring_data_t *data, blockstore_op_t *op
|
||||
}
|
||||
free(rv[i].buf);
|
||||
rv[i].buf = NULL;
|
||||
if (rv[i].dyn_data && --(*rv[i].dyn_data) == 0) // refcount
|
||||
{
|
||||
free(rv[i].dyn_data);
|
||||
rv[i].dyn_data = NULL;
|
||||
}
|
||||
free_dirty_dyn_data(rv[i]);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Do not verify clean data if its location was mutated by a flush during this read
|
||||
bool clean_changed = PRIV(op)->clean_loc_used && PRIV(op)->clean_changes !=
|
||||
used_clean_objects.at(PRIV(op)->clean_loc_used-1).changes;
|
||||
for (auto & vec: rv)
|
||||
{
|
||||
if (vec.copy_flags & COPY_BUF_META_BLOCK)
|
||||
{
|
||||
// Metadata read. Skip
|
||||
// Metadata read. Skip, but still release the entry reference
|
||||
assert(!meta_block);
|
||||
meta_block = vec.buf;
|
||||
vec.buf = NULL;
|
||||
free_dirty_dyn_data(vec);
|
||||
continue;
|
||||
}
|
||||
if (vec.csum_buf)
|
||||
if (!read_failed && vec.csum_buf && ((vec.copy_flags & COPY_BUF_JOURNAL) || !clean_changed))
|
||||
{
|
||||
uint32_t *csum = (uint32_t*)vec.csum_buf;
|
||||
for (size_t p = 0; p < vec.len; p += dsk.csum_block_size, csum++)
|
||||
@@ -1065,11 +1086,7 @@ void blockstore_impl_t::handle_read_event(ring_data_t *data, blockstore_op_t *op
|
||||
}
|
||||
}
|
||||
}
|
||||
if (vec.dyn_data && --(*vec.dyn_data) == 0) // refcount
|
||||
{
|
||||
free(vec.dyn_data);
|
||||
vec.dyn_data = NULL;
|
||||
}
|
||||
free_dirty_dyn_data(vec);
|
||||
}
|
||||
}
|
||||
if (meta_block)
|
||||
@@ -1098,6 +1115,7 @@ void blockstore_impl_t::handle_read_event(ring_data_t *data, blockstore_op_t *op
|
||||
}
|
||||
if (op->retval == 0)
|
||||
op->retval = op->len;
|
||||
reads_in_flight.erase(op);
|
||||
FINISH_OP(op);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ int blockstore_impl_t::dequeue_rollback(blockstore_op_t *op)
|
||||
else
|
||||
{
|
||||
dirty_it--;
|
||||
if (dirty_it->first.oid != ov.oid || dirty_it->first.version < ov.version)
|
||||
if (dirty_it->first.oid != ov.oid || dirty_it->first.version <= ov.version)
|
||||
{
|
||||
// Already rolled back, skip this object version
|
||||
return STAB_SPLIT_DONE;
|
||||
@@ -40,8 +40,15 @@ int blockstore_impl_t::dequeue_rollback(blockstore_op_t *op)
|
||||
// Object write is still in progress. Wait until the write request completes
|
||||
return STAB_SPLIT_WAIT;
|
||||
}
|
||||
else if (!IS_SYNCED(dirty_it->second.state) ||
|
||||
IS_STABLE(dirty_it->second.state))
|
||||
else if (IS_STABLE(dirty_it->second.state))
|
||||
{
|
||||
// LIST shows a stable delete as no version, so stop at it like mark_rolled_back() does
|
||||
if (IS_DELETE(dirty_it->second.state))
|
||||
break;
|
||||
// Can't jump back over a stable version
|
||||
return -EBUSY;
|
||||
}
|
||||
else if (!IS_SYNCED(dirty_it->second.state))
|
||||
{
|
||||
// Sync the object
|
||||
return STAB_SPLIT_SYNC;
|
||||
@@ -63,6 +70,12 @@ int blockstore_impl_t::dequeue_rollback(blockstore_op_t *op)
|
||||
blockstore_journal_check_t space_check(this);
|
||||
if (!space_check.check_available(op, op->len, sizeof(journal_entry_rollback), 0))
|
||||
{
|
||||
if (space_check.give_up)
|
||||
{
|
||||
op->retval = -EAGAIN;
|
||||
FINISH_OP(op);
|
||||
return 2;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
// There is sufficient space. Check SQEs
|
||||
@@ -162,7 +175,10 @@ void blockstore_impl_t::mark_rolled_back(const obj_ver_id & ov)
|
||||
if (unstab_it != unstable_writes.end())
|
||||
{
|
||||
if (max_unstable == 0)
|
||||
{
|
||||
unstable_writes.erase(unstab_it);
|
||||
wakeup_wait_journal();
|
||||
}
|
||||
else
|
||||
unstab_it->second = max_unstable;
|
||||
}
|
||||
@@ -192,6 +208,8 @@ void blockstore_impl_t::erase_dirty(blockstore_dirty_db_t::iterator dirty_start,
|
||||
if ((dirty_it->second.state & BS_ST_WORKFLOW_MASK) == BS_ST_WAIT_DEL)
|
||||
{
|
||||
dirty_it->second.state = (dirty_it->second.state & ~BS_ST_WORKFLOW_MASK) | next_state;
|
||||
// Entering WAIT_DEL -> request_trim, exiting -> release_trim
|
||||
flusher->release_trim();
|
||||
if (IS_BIG_WRITE(dirty_it->second.state))
|
||||
{
|
||||
next_state = BS_ST_WAIT_BIG;
|
||||
@@ -218,22 +236,28 @@ void blockstore_impl_t::erase_dirty(blockstore_dirty_db_t::iterator dirty_start,
|
||||
#endif
|
||||
data_alloc->set(dirty_it->second.location / dsk.data_block_size, false);
|
||||
}
|
||||
auto used = --journal.used_sectors.at(dirty_it->second.journal_sector);
|
||||
#ifdef BLOCKSTORE_DEBUG
|
||||
printf(
|
||||
"remove usage of journal offset %08jx by %jx:%jx v%ju (%ju refs)\n", dirty_it->second.journal_sector,
|
||||
dirty_it->first.oid.inode, dirty_it->first.oid.stripe, dirty_it->first.version, used
|
||||
);
|
||||
#endif
|
||||
if (used == 0)
|
||||
// A big write is only journaled when it gets synced, so an entry erased before that
|
||||
// holds no journal sector reference at all
|
||||
if (dirty_it->second.journal_sector != 0)
|
||||
{
|
||||
journal.used_sectors.erase(dirty_it->second.journal_sector);
|
||||
if (dirty_it->second.journal_sector == journal.sector_info[journal.cur_sector].offset)
|
||||
auto used_it = journal.used_sectors.find(dirty_it->second.journal_sector);
|
||||
uint64_t used = used_it == journal.used_sectors.end() ? UINT64_MAX : --used_it->second;
|
||||
#ifdef BLOCKSTORE_DEBUG
|
||||
printf(
|
||||
"remove usage of journal offset %08jx by %jx:%jx v%ju (%ju refs)\n", dirty_it->second.journal_sector,
|
||||
dirty_it->first.oid.inode, dirty_it->first.oid.stripe, dirty_it->first.version, used
|
||||
);
|
||||
#endif
|
||||
if (used == 0)
|
||||
{
|
||||
// Mark current sector as "full" to select the new one
|
||||
journal.in_sector_pos = dsk.journal_block_size;
|
||||
journal.used_sectors.erase(dirty_it->second.journal_sector);
|
||||
if (dirty_it->second.journal_sector == journal.sector_info[journal.cur_sector].offset)
|
||||
{
|
||||
// Mark current sector as "full" to select the new one
|
||||
journal.in_sector_pos = dsk.journal_block_size;
|
||||
}
|
||||
flusher->mark_trim_possible();
|
||||
}
|
||||
flusher->mark_trim_possible();
|
||||
}
|
||||
free_dirty_dyn_data(dirty_it->second);
|
||||
if (dirty_it == dirty_start)
|
||||
@@ -260,4 +284,17 @@ void blockstore_impl_t::free_dirty_dyn_data(dirty_entry & e)
|
||||
}
|
||||
}
|
||||
|
||||
void blockstore_impl_t::free_dirty_dyn_data(copy_buffer_t & e)
|
||||
{
|
||||
if (e.dyn_data)
|
||||
{
|
||||
assert(alloc_dyn_data);
|
||||
if (--*e.dyn_data == 0) // refcount
|
||||
{
|
||||
free(e.dyn_data);
|
||||
}
|
||||
e.dyn_data = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace v1
|
||||
|
||||
@@ -73,7 +73,11 @@ static void append_version(ver_vector_t & vec, obj_ver_id ov)
|
||||
vec.items[vec.size++] = ov;
|
||||
}
|
||||
|
||||
static bool check_unsynced(std::vector<obj_ver_id> & check, obj_ver_id ov, std::vector<obj_ver_id> & to, int *count)
|
||||
// Move the unsynced versions of <ov.oid> which the operation has to sync first from <check>
|
||||
// into <to>. Stabilization needs the versions up to <ov.version> synced, and a rollback needs
|
||||
// the versions above it - those are the ones it discards, and a rollback can only be journaled
|
||||
// after they reach the journal themselves
|
||||
static bool check_unsynced(std::vector<obj_ver_id> & check, obj_ver_id ov, std::vector<obj_ver_id> & to, int *count, bool above)
|
||||
{
|
||||
bool found = false;
|
||||
int j = 0, k = 0;
|
||||
@@ -81,7 +85,7 @@ static bool check_unsynced(std::vector<obj_ver_id> & check, obj_ver_id ov, std::
|
||||
{
|
||||
if (check[j] == ov)
|
||||
found = true;
|
||||
if (check[j].oid == ov.oid && check[j].version <= ov.version)
|
||||
if (check[j].oid == ov.oid && (above ? check[j].version > ov.version : check[j].version <= ov.version))
|
||||
{
|
||||
to.push_back(check[j++]);
|
||||
if (count)
|
||||
@@ -187,8 +191,9 @@ int blockstore_impl_t::split_stab_op(blockstore_op_t *op, std::function<int(obj_
|
||||
PRIV(op)->sync_small_writes.clear();
|
||||
add_sync = true;
|
||||
}
|
||||
check_unsynced(unsynced_small_writes, *v, PRIV(op)->sync_small_writes, NULL);
|
||||
check_unsynced(unsynced_big_writes, *v, PRIV(op)->sync_big_writes, &unsynced_big_write_count);
|
||||
bool above = op->opcode == BS_OP_ROLLBACK;
|
||||
check_unsynced(unsynced_small_writes, *v, PRIV(op)->sync_small_writes, NULL, above);
|
||||
check_unsynced(unsynced_big_writes, *v, PRIV(op)->sync_big_writes, &unsynced_big_write_count, above);
|
||||
}
|
||||
else /* if (action == STAB_SPLIT_TODO) */
|
||||
{
|
||||
@@ -210,6 +215,8 @@ int blockstore_impl_t::split_stab_op(blockstore_op_t *op, std::function<int(obj_
|
||||
if (!todo && !bad_vers.size)
|
||||
{
|
||||
// Already stable
|
||||
free(good_vers.items);
|
||||
free(bad_vers.items);
|
||||
op->retval = 0;
|
||||
FINISH_OP(op);
|
||||
return 2;
|
||||
@@ -217,7 +224,10 @@ int blockstore_impl_t::split_stab_op(blockstore_op_t *op, std::function<int(obj_
|
||||
op->retval = 0;
|
||||
if (!todo && !add_sync)
|
||||
{
|
||||
// Only wait for inflight writes or current in-progress syncs
|
||||
// Only wait for inflight writes or current in-progress syncs.
|
||||
// The operation is retried from scratch, so the version vectors go with it
|
||||
free(good_vers.items);
|
||||
free(bad_vers.items);
|
||||
return 0;
|
||||
}
|
||||
blockstore_op_t *sync_op = NULL, *split_stab_op = NULL;
|
||||
@@ -362,6 +372,12 @@ int blockstore_impl_t::dequeue_stable(blockstore_op_t *op)
|
||||
blockstore_journal_check_t space_check(this);
|
||||
if (!space_check.check_available(op, op->len, sizeof(journal_entry_stable), 0))
|
||||
{
|
||||
if (space_check.give_up)
|
||||
{
|
||||
op->retval = -EAGAIN;
|
||||
FINISH_OP(op);
|
||||
return 2;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
// There is sufficient space. Check SQEs
|
||||
@@ -530,7 +546,13 @@ void blockstore_impl_t::mark_stable(obj_ver_id v, bool forget_dirty)
|
||||
// Big write overrides all previous dirty entries
|
||||
erase_end = dirty_it;
|
||||
}
|
||||
if (was_stable || dirty_it == dirty_db.begin())
|
||||
// Stopping at an already stable entry is only correct when we aren't erasing anything:
|
||||
// everything below a big write or a deletion is dead and has to be erased even if it
|
||||
// was stabilized earlier. Entries are stabilized one by one during the journal replay,
|
||||
// so a small write in between used to hide an older big write from this walk forever,
|
||||
// leaving its data block claimed by an entry which isn't current any more.
|
||||
// <forget_dirty> is only set by the journal replay, so the walk stays short at runtime
|
||||
if (!forget_dirty && was_stable || dirty_it == dirty_db.begin())
|
||||
{
|
||||
break;
|
||||
}
|
||||
@@ -557,6 +579,7 @@ void blockstore_impl_t::mark_stable(obj_ver_id v, bool forget_dirty)
|
||||
unstab_it->second <= v.version)
|
||||
{
|
||||
unstable_writes.erase(unstab_it);
|
||||
wakeup_wait_journal();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -79,24 +79,44 @@ int blockstore_impl_t::continue_sync(blockstore_op_t *op)
|
||||
// 2nd step: Data device is synced, prepare & write journal entries
|
||||
// Check space in the journal and journal memory buffers
|
||||
blockstore_journal_check_t space_check(this);
|
||||
bool space_ok = true;
|
||||
if (dsk.csum_block_size)
|
||||
{
|
||||
// More complex check because all journal entries have different lengths
|
||||
int left = PRIV(op)->sync_big_writes.size();
|
||||
for (auto & sbw: PRIV(op)->sync_big_writes)
|
||||
{
|
||||
left--;
|
||||
auto & dirty_entry = dirty_db.at(sbw);
|
||||
uint64_t dyn_size = dsk.dirty_dyn_size(dirty_entry.offset, dirty_entry.len);
|
||||
if (!space_check.check_available(op, 1, sizeof(journal_entry_big_write) + dyn_size, 0))
|
||||
{
|
||||
return 0;
|
||||
space_ok = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (!space_check.check_available(op, PRIV(op)->sync_big_writes.size(),
|
||||
sizeof(journal_entry_big_write) + dsk.clean_entry_bitmap_size, 0))
|
||||
{
|
||||
space_ok = false;
|
||||
}
|
||||
if (!space_ok)
|
||||
{
|
||||
if (space_check.give_up)
|
||||
{
|
||||
// Return everything back
|
||||
unsynced_big_write_count += PRIV(op)->sync_big_writes.size();
|
||||
PRIV(op)->sync_big_writes.insert(PRIV(op)->sync_big_writes.end(),
|
||||
unsynced_big_writes.begin(), unsynced_big_writes.end());
|
||||
PRIV(op)->sync_big_writes.swap(unsynced_big_writes);
|
||||
PRIV(op)->sync_big_writes.clear();
|
||||
PRIV(op)->sync_small_writes.insert(PRIV(op)->sync_small_writes.end(),
|
||||
unsynced_small_writes.begin(), unsynced_small_writes.end());
|
||||
PRIV(op)->sync_small_writes.swap(unsynced_small_writes);
|
||||
PRIV(op)->sync_small_writes.clear();
|
||||
op->retval = -EAGAIN;
|
||||
FINISH_OP(op);
|
||||
return 2;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
// Check SQEs. Don't bother about merging, submit each journal sector as a separate request
|
||||
@@ -190,6 +210,7 @@ void blockstore_impl_t::ack_sync(blockstore_op_t *op)
|
||||
{
|
||||
unstable_unsynced--;
|
||||
assert(unstable_unsynced >= 0);
|
||||
wakeup_wait_journal();
|
||||
}
|
||||
dirty_it++;
|
||||
while (dirty_it != dirty_db.end() && dirty_it->first.oid == ov.oid)
|
||||
@@ -203,6 +224,11 @@ void blockstore_impl_t::ack_sync(blockstore_op_t *op)
|
||||
{
|
||||
stable_ver = dirty_it->first.version;
|
||||
}
|
||||
if (IS_BIG_WRITE(dirty_it->second.state))
|
||||
{
|
||||
// Small writes after the next big write wait for that one
|
||||
is_big = false;
|
||||
}
|
||||
dirty_it++;
|
||||
}
|
||||
if (stable_ver != 0)
|
||||
|
||||
@@ -6,11 +6,103 @@
|
||||
|
||||
namespace v1 {
|
||||
|
||||
// A deletion supersedes everything written before it and is stable as soon as it's written,
|
||||
// so versions preceding it that aren't in the journal yet are free to forget. And they have to
|
||||
// be forgotten: a big write is only journaled when it gets synced, so leaving one behind would
|
||||
// put its journal entry after the deletion and recovery would replay them in the wrong
|
||||
// order, resurrecting the object. Returns false if a preceding write is still running -
|
||||
// its completion refers to the entry, so we have to let it finish first.
|
||||
//
|
||||
// Entries which are already synced must NOT be forgotten. Their journal entries are on the disk
|
||||
// and can't be taken back, while the deletion itself only reaches the journal on the next sync.
|
||||
// Forgetting them drops their journal references, and the journal may then be trimmed past the
|
||||
// object's big write while its small writes still sit in later sectors kept alive by other
|
||||
// objects - recovery would then replay those small writes with no base under them.
|
||||
// An entry which isn't in the unsynced lists any more has been taken over by a sync which is
|
||||
// still in flight: continue_sync() swaps those lists over to itself, but the entries only get
|
||||
// the SYNCED state later, in ack_sync()
|
||||
static bool is_still_unsynced(const std::vector<obj_ver_id> & unsynced, obj_ver_id ov)
|
||||
{
|
||||
for (auto & u: unsynced)
|
||||
if (u == ov)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
bool blockstore_impl_t::forget_unstable_before_delete(blockstore_op_t *op, blockstore_dirty_db_t::iterator dirty_it)
|
||||
{
|
||||
if (immediate_commit == IMMEDIATE_ALL)
|
||||
{
|
||||
// Everything is journaled as soon as it's written here, so nothing can end up
|
||||
// behind the deletion in the journal and there is nothing to forget
|
||||
return true;
|
||||
}
|
||||
auto first_it = dirty_it;
|
||||
while (first_it != dirty_db.begin())
|
||||
{
|
||||
auto prev_it = first_it;
|
||||
prev_it--;
|
||||
if (prev_it->first.oid != op->oid || IS_SYNCED(prev_it->second.state))
|
||||
break;
|
||||
if (IS_IN_FLIGHT(prev_it->second.state))
|
||||
return false;
|
||||
if (!is_still_unsynced(IS_BIG_WRITE(prev_it->second.state) ? unsynced_big_writes : unsynced_small_writes, prev_it->first))
|
||||
{
|
||||
// A sync in flight already owns it, so we can't erase it here: that would leave
|
||||
// the sync with a dangling dirty_db entry in ack_sync() and would decrement
|
||||
// unstable_unsynced a second time.
|
||||
// A small write is journaled as soon as it's dequeued, so it is already in front
|
||||
// of our deletion. A big write is not: its journal entry is only written when the
|
||||
// sync reaches its journaling phase, which may well be after our deletion is
|
||||
// journaled. Journal replay would then take it for a new write over the deletion
|
||||
// and resurrect the object, so wait for that sync to finish instead
|
||||
if (IS_BIG_WRITE(prev_it->second.state))
|
||||
return false;
|
||||
break;
|
||||
}
|
||||
first_it = prev_it;
|
||||
}
|
||||
if (first_it == dirty_it)
|
||||
return true;
|
||||
// Their durability becomes ours: they're acknowledged, but from now on the only thing
|
||||
// on the disk which accounts for them is our deletion. A sync started before we're
|
||||
// journaled and acked would otherwise find nothing to do and report success
|
||||
unsynced_forgotten++;
|
||||
PRIV(op)->forgot_unsynced = true;
|
||||
for (auto it = first_it; it != dirty_it; it++)
|
||||
{
|
||||
// Drop it from the unsynced lists so that a later sync doesn't journal it
|
||||
bool is_big = IS_BIG_WRITE(it->second.state);
|
||||
auto & unsynced = is_big ? unsynced_big_writes : unsynced_small_writes;
|
||||
for (size_t i = 0; i < unsynced.size(); i++)
|
||||
{
|
||||
if (unsynced[i].oid == it->first.oid && unsynced[i].version == it->first.version)
|
||||
{
|
||||
unsynced.erase(unsynced.begin()+i, unsynced.begin()+i+1);
|
||||
if (is_big && immediate_commit != IMMEDIATE_ALL)
|
||||
unsynced_big_write_count--;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!(it->second.state & BS_ST_INSTANT) && !IS_SYNCED(it->second.state))
|
||||
{
|
||||
unstable_unsynced--;
|
||||
assert(unstable_unsynced >= 0);
|
||||
}
|
||||
}
|
||||
auto & clean_db = clean_db_shard(op->oid);
|
||||
auto clean_it = clean_db.find(op->oid);
|
||||
uint64_t clean_loc = clean_it != clean_db.end() ? clean_it->second.location : UINT64_MAX;
|
||||
erase_dirty(first_it, dirty_it, clean_loc);
|
||||
wakeup_wait_journal();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool blockstore_impl_t::enqueue_write(blockstore_op_t *op)
|
||||
{
|
||||
// Check or assign version number
|
||||
bool found = false, deleted = false, unsynced = false, is_del = (op->opcode == BS_OP_DELETE);
|
||||
bool wait_big = false, wait_del = false;
|
||||
bool wait_big = false, wait_del = false, in_open_sector = false;
|
||||
void *dyn = NULL;
|
||||
uint8_t *dyn_ptr = NULL;
|
||||
if (is_del)
|
||||
@@ -39,6 +131,15 @@ bool blockstore_impl_t::enqueue_write(blockstore_op_t *op)
|
||||
dirty_it--; // segfaults when dirty_db is empty
|
||||
if (dirty_it != dirty_db.end() && dirty_it->first.oid == op->oid)
|
||||
{
|
||||
if (op->opcode == BS_OP_WRITE_STABLE && !IS_INSTANT(dirty_it->second.state))
|
||||
{
|
||||
op->retval = -EINVAL;
|
||||
if (!is_del && alloc_dyn_data)
|
||||
{
|
||||
free(dyn);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
found = true;
|
||||
version = dirty_it->first.version + 1;
|
||||
deleted = IS_DELETE(dirty_it->second.state);
|
||||
@@ -47,6 +148,7 @@ bool blockstore_impl_t::enqueue_write(blockstore_op_t *op)
|
||||
wait_big = (dirty_it->second.state & BS_ST_TYPE_MASK) == BS_ST_BIG_WRITE
|
||||
? !IS_SYNCED(dirty_it->second.state)
|
||||
: ((dirty_it->second.state & BS_ST_WORKFLOW_MASK) == BS_ST_WAIT_BIG);
|
||||
in_open_sector = dirty_it->second.journal_sector == journal.sector_info[journal.cur_sector].offset;
|
||||
if (!is_del && !deleted)
|
||||
{
|
||||
void *dyn_from = alloc_dyn_data
|
||||
@@ -97,6 +199,26 @@ bool blockstore_impl_t::enqueue_write(blockstore_op_t *op)
|
||||
wait_del = true;
|
||||
PRIV(op)->real_version = op->version;
|
||||
op->version = version;
|
||||
if (!unsynced && in_open_sector &&
|
||||
journal.sector_info[journal.cur_sector].flush_count == 0)
|
||||
{
|
||||
// In exotic configurations without no_same_sector_overwrites, the deletion may reside
|
||||
// in the current sector. In that case nothing advances dirty_start and the deletion
|
||||
// becomes unflushable... Example is test_blockstore_chaos --seed 10901878
|
||||
if (!journal.sector_info[journal.cur_sector].dirty)
|
||||
{
|
||||
// If it's unmodified we can just move to the next sector
|
||||
// Probably unreachable currently due to "Forcibly move to the next sector" logic below
|
||||
journal.in_sector_pos = journal.block_size;
|
||||
mark_not_dirty(journal.cur_sector);
|
||||
}
|
||||
else
|
||||
{
|
||||
// If it's modified we may add a SYNC so it writes the sector out
|
||||
assert(immediate_commit != IMMEDIATE_ALL);
|
||||
unsynced = true;
|
||||
}
|
||||
}
|
||||
if (unsynced)
|
||||
{
|
||||
// Issue an additional sync so the delete reaches the journal
|
||||
@@ -106,20 +228,20 @@ bool blockstore_impl_t::enqueue_write(blockstore_op_t *op)
|
||||
sync_op->version = op->version;
|
||||
sync_op->callback = [this](blockstore_op_t *sync_op)
|
||||
{
|
||||
flusher->unshift_flush((obj_ver_id){
|
||||
unshift_stable_flush((obj_ver_id){
|
||||
.oid = sync_op->oid,
|
||||
.version = sync_op->version-1,
|
||||
}, true);
|
||||
});
|
||||
delete sync_op;
|
||||
};
|
||||
enqueue_op(sync_op);
|
||||
enqueue_own_op(sync_op);
|
||||
}
|
||||
else
|
||||
{
|
||||
flusher->unshift_flush((obj_ver_id){
|
||||
unshift_stable_flush((obj_ver_id){
|
||||
.oid = op->oid,
|
||||
.version = version-1,
|
||||
}, true);
|
||||
});
|
||||
}
|
||||
}
|
||||
else
|
||||
@@ -147,7 +269,7 @@ bool blockstore_impl_t::enqueue_write(blockstore_op_t *op)
|
||||
{
|
||||
delete sync_op;
|
||||
};
|
||||
enqueue_op(sync_op);
|
||||
enqueue_own_op(sync_op);
|
||||
}
|
||||
else if (!imm)
|
||||
unsynced_queued_ops++;
|
||||
@@ -178,6 +300,11 @@ bool blockstore_impl_t::enqueue_write(blockstore_op_t *op)
|
||||
if (op->bitmap)
|
||||
memcpy(dyn_ptr, op->bitmap, dsk.clean_entry_bitmap_size);
|
||||
}
|
||||
if (wait_del)
|
||||
{
|
||||
// Entering WAIT_DEL -> request_trim, exiting -> release_trim
|
||||
flusher->request_trim();
|
||||
}
|
||||
// Calculate checksums
|
||||
// FIXME: Allow to receive checksums from outside?
|
||||
if (!is_del && dsk.data_csum_type && op->len > 0)
|
||||
@@ -218,8 +345,27 @@ bool blockstore_impl_t::enqueue_write(blockstore_op_t *op)
|
||||
return true;
|
||||
}
|
||||
|
||||
// Ask the flusher to flush <ov> right now, but only if it's already stable.
|
||||
// A sync we submit ourselves may complete without syncing anything, because a sync submitted
|
||||
// before it has already taken those writes over and is still in flight. In that case the entry
|
||||
// becomes stable - and is queued for flushing by mark_stable() - when that sync completes,
|
||||
// and forcing a flush of a still unstable entry would abort the flusher
|
||||
void blockstore_impl_t::unshift_stable_flush(obj_ver_id ov)
|
||||
{
|
||||
auto dirty_it = dirty_db.find(ov);
|
||||
if (dirty_it != dirty_db.end() && IS_STABLE(dirty_it->second.state) && !flusher->requeue_after_flush(ov))
|
||||
{
|
||||
flusher->unshift_flush(ov, true);
|
||||
}
|
||||
}
|
||||
|
||||
void blockstore_impl_t::cancel_all_writes(blockstore_op_t *op, blockstore_dirty_db_t::iterator dirty_it, int retval)
|
||||
{
|
||||
if (PRIV(op)->forgot_unsynced)
|
||||
{
|
||||
PRIV(op)->forgot_unsynced = false;
|
||||
unsynced_forgotten--;
|
||||
}
|
||||
while (dirty_it != dirty_db.end() && dirty_it->first.oid == op->oid)
|
||||
{
|
||||
free_dirty_dyn_data(dirty_it->second);
|
||||
@@ -312,6 +458,11 @@ int blockstore_impl_t::dequeue_write(blockstore_op_t *op)
|
||||
sizeof(journal_entry_big_write) + dsk.clean_dyn_size,
|
||||
(unstable_writes.size()+unstable_unsynced+((dirty_it->second.state & BS_ST_INSTANT) ? 0 : 1))*journal.block_size))
|
||||
{
|
||||
if (space_check.give_up)
|
||||
{
|
||||
cancel_all_writes(op, dirty_it, -EAGAIN);
|
||||
return 2;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
// Big (redirect) write
|
||||
@@ -404,6 +555,11 @@ int blockstore_impl_t::dequeue_write(blockstore_op_t *op)
|
||||
sizeof(journal_entry_small_write) + dyn_size,
|
||||
op->len + (unstable_writes.size()+unstable_unsynced+((dirty_it->second.state & BS_ST_INSTANT) ? 0 : 1))*journal.block_size))
|
||||
{
|
||||
if (space_check.give_up)
|
||||
{
|
||||
cancel_all_writes(op, dirty_it, -EAGAIN);
|
||||
return 2;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
// There is sufficient space. Check SQE(s)
|
||||
@@ -416,7 +572,8 @@ int blockstore_impl_t::dequeue_write(blockstore_op_t *op)
|
||||
write_iodepth++;
|
||||
// Got SQEs. Prepare previous journal sector write if required
|
||||
if (immediate_commit == IMMEDIATE_NONE &&
|
||||
!journal.entry_fits(sizeof(journal_entry_small_write) + dyn_size))
|
||||
!journal.entry_fits(sizeof(journal_entry_small_write) + dyn_size) &&
|
||||
journal.sector_info[journal.cur_sector].dirty)
|
||||
{
|
||||
prepare_journal_sector_write(journal.cur_sector, op);
|
||||
}
|
||||
@@ -476,7 +633,13 @@ int blockstore_impl_t::dequeue_write(blockstore_op_t *op)
|
||||
? (uint8_t*)dirty_it->second.dyn_data+sizeof(int) : (uint8_t*)&dirty_it->second.dyn_data), dyn_size);
|
||||
je->crc32 = je_crc32((journal_entry*)je);
|
||||
journal.crc32_last = je->crc32;
|
||||
if (immediate_commit != IMMEDIATE_NONE)
|
||||
// With immediate_commit=none we normally leave the sector to be written out by a later
|
||||
// sync. But if it is already queued for writing in this same batch, our entry goes to
|
||||
// the disk with that write anyway - so join it instead of leaving the sector dirty,
|
||||
// otherwise the next operation to write the sector out would queue a second write of
|
||||
// it while the first one is still in flight. It costs no extra I/O: the write is
|
||||
// already prepared, so prepare_journal_sector_write() only subscribes us to it
|
||||
if (immediate_commit != IMMEDIATE_NONE || journal.sector_info[journal.cur_sector].submit_id)
|
||||
{
|
||||
prepare_journal_sector_write(journal.cur_sector, op);
|
||||
}
|
||||
@@ -499,6 +662,7 @@ int blockstore_impl_t::dequeue_write(blockstore_op_t *op)
|
||||
.op = op,
|
||||
});
|
||||
data2->callback = [this, flush_id = journal.submit_id](ring_data_t *data) { handle_journal_write(data, flush_id); };
|
||||
assert(journal.next_free > 0);
|
||||
assert(journal.next_free+op->len <= dsk.journal_len);
|
||||
io_uring_prep_writev(sqe2, dsk.journal_fd, &data2->iov, 1, journal.offset + journal.next_free);
|
||||
PRIV(op)->pending_ops++;
|
||||
@@ -559,6 +723,25 @@ resume_2:
|
||||
if (!space_check.check_available(op, 1, sizeof(journal_entry_big_write) + dyn_size,
|
||||
(unstable_writes.size()+unstable_unsynced+((dirty_it->second.state & BS_ST_INSTANT) ? 0 : 1))*journal.block_size))
|
||||
{
|
||||
if (space_check.give_up)
|
||||
{
|
||||
auto uo_it = used_clean_objects.find(dirty_it->second.location);
|
||||
if (uo_it != used_clean_objects.end())
|
||||
uo_it->second.was_freed = true;
|
||||
else
|
||||
data_alloc->set(dirty_it->second.location / dsk.data_block_size, false);
|
||||
if (!(dirty_it->second.state & BS_ST_INSTANT))
|
||||
{
|
||||
unstable_unsynced--;
|
||||
assert(unstable_unsynced >= 0);
|
||||
wakeup_wait_journal();
|
||||
}
|
||||
if (immediate_commit != IMMEDIATE_ALL)
|
||||
unsynced_big_write_count--;
|
||||
write_iodepth--;
|
||||
cancel_all_writes(op, dirty_it, -EAGAIN);
|
||||
return 2;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
BS_SUBMIT_CHECK_SQES(1);
|
||||
@@ -622,6 +805,7 @@ resume_4:
|
||||
{
|
||||
unstable_unsynced--;
|
||||
assert(unstable_unsynced >= 0);
|
||||
wakeup_wait_journal();
|
||||
}
|
||||
}
|
||||
dirty_it->second.state = (dirty_it->second.state & ~BS_ST_WORKFLOW_MASK)
|
||||
@@ -650,9 +834,16 @@ resume_4:
|
||||
});
|
||||
}
|
||||
}
|
||||
if (PRIV(op)->forgot_unsynced)
|
||||
{
|
||||
// We're in the unsynced lists ourselves now, so a sync may proceed again
|
||||
PRIV(op)->forgot_unsynced = false;
|
||||
unsynced_forgotten--;
|
||||
}
|
||||
if (imm && (dirty_it->second.state & BS_ST_TYPE_MASK) == BS_ST_BIG_WRITE)
|
||||
{
|
||||
// Unblock small writes
|
||||
// Unblock small writes and the next big write (erase_dirty() makes big writes over a
|
||||
// deletion wait too). The ones after the next big write wait for that one
|
||||
dirty_it++;
|
||||
while (dirty_it != dirty_db.end() && dirty_it->first.oid == op->oid)
|
||||
{
|
||||
@@ -660,6 +851,10 @@ resume_4:
|
||||
{
|
||||
dirty_it->second.state = (dirty_it->second.state & ~BS_ST_WORKFLOW_MASK) | BS_ST_IN_FLIGHT;
|
||||
}
|
||||
if (IS_BIG_WRITE(dirty_it->second.state))
|
||||
{
|
||||
break;
|
||||
}
|
||||
dirty_it++;
|
||||
}
|
||||
}
|
||||
@@ -724,6 +919,21 @@ void blockstore_impl_t::handle_write_event(ring_data_t *data, blockstore_op_t *o
|
||||
}
|
||||
}
|
||||
|
||||
void blockstore_impl_t::mark_not_dirty(int journal_sector)
|
||||
{
|
||||
uint64_t new_ds = journal.sector_info[journal_sector].offset + journal.block_size;
|
||||
if (new_ds >= journal.len)
|
||||
{
|
||||
new_ds = journal.block_size;
|
||||
}
|
||||
if ((journal.dirty_start + (journal.dirty_start >= journal.used_start ? 0 : journal.len)) <
|
||||
(new_ds + (new_ds >= journal.used_start ? 0 : journal.len)))
|
||||
{
|
||||
journal.dirty_start = new_ds;
|
||||
flusher->wakeup_on_journal_written();
|
||||
}
|
||||
}
|
||||
|
||||
void blockstore_impl_t::release_journal_sectors(blockstore_op_t *op)
|
||||
{
|
||||
// Release flushed journal sectors
|
||||
@@ -738,19 +948,11 @@ void blockstore_impl_t::release_journal_sectors(blockstore_op_t *op)
|
||||
if (s == (1+journal.cur_sector))
|
||||
{
|
||||
// Forcibly move to the next sector and move dirty position
|
||||
// FIXME: This is the target behaviour, ok, but it seems to duplicate no_same_sector_overwrites...
|
||||
journal.in_sector_pos = journal.block_size;
|
||||
}
|
||||
// We know for sure that we won't write into this sector anymore
|
||||
uint64_t new_ds = journal.sector_info[s-1].offset + journal.block_size;
|
||||
if (new_ds >= journal.len)
|
||||
{
|
||||
new_ds = journal.block_size;
|
||||
}
|
||||
if ((journal.dirty_start + (journal.dirty_start >= journal.used_start ? 0 : journal.len)) <
|
||||
(new_ds + (new_ds >= journal.used_start ? 0 : journal.len)))
|
||||
{
|
||||
journal.dirty_start = new_ds;
|
||||
}
|
||||
mark_not_dirty(s-1);
|
||||
}
|
||||
if (s == PRIV(op)->max_flushed_journal_sector)
|
||||
break;
|
||||
@@ -771,16 +973,25 @@ int blockstore_impl_t::dequeue_del(blockstore_op_t *op)
|
||||
.version = op->version,
|
||||
});
|
||||
assert(dirty_it != dirty_db.end());
|
||||
if (!forget_unstable_before_delete(op, dirty_it))
|
||||
{
|
||||
// A preceding write is still running, retry when it finishes
|
||||
return 0;
|
||||
}
|
||||
blockstore_journal_check_t space_check(this);
|
||||
if (!space_check.check_available(op, 1, sizeof(journal_entry_del), (unstable_writes.size()+unstable_unsynced)*journal.block_size))
|
||||
{
|
||||
if (space_check.give_up)
|
||||
{
|
||||
cancel_all_writes(op, dirty_it, -EAGAIN);
|
||||
return 2;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
// Write current journal sector only if it's dirty and full, or in the immediate_commit mode
|
||||
// Write current journal sector only if it's dirty and full, or in the immediate_commit mode.
|
||||
BS_SUBMIT_CHECK_SQES(
|
||||
(immediate_commit != IMMEDIATE_NONE ||
|
||||
(dsk.journal_block_size - journal.in_sector_pos) < sizeof(journal_entry_del) &&
|
||||
journal.sector_info[journal.cur_sector].dirty) ? 1 : 0
|
||||
!journal.entry_fits(sizeof(journal_entry_del)) ? 1 : 0)
|
||||
);
|
||||
if (write_iodepth >= max_write_iodepth)
|
||||
{
|
||||
@@ -789,7 +1000,7 @@ int blockstore_impl_t::dequeue_del(blockstore_op_t *op)
|
||||
write_iodepth++;
|
||||
// Prepare journal sector write
|
||||
if (immediate_commit == IMMEDIATE_NONE &&
|
||||
(dsk.journal_block_size - journal.in_sector_pos) < sizeof(journal_entry_del) &&
|
||||
!journal.entry_fits(sizeof(journal_entry_del)) &&
|
||||
journal.sector_info[journal.cur_sector].dirty)
|
||||
{
|
||||
prepare_journal_sector_write(journal.cur_sector, op);
|
||||
@@ -812,7 +1023,8 @@ int blockstore_impl_t::dequeue_del(blockstore_op_t *op)
|
||||
je->crc32 = je_crc32((journal_entry*)je);
|
||||
journal.crc32_last = je->crc32;
|
||||
dirty_it->second.state = BS_ST_DELETE | BS_ST_SUBMITTED;
|
||||
if (immediate_commit != IMMEDIATE_NONE)
|
||||
// Join a sector write which is already queued in this same batch, see dequeue_write()
|
||||
if (immediate_commit != IMMEDIATE_NONE || journal.sector_info[journal.cur_sector].submit_id)
|
||||
{
|
||||
prepare_journal_sector_write(journal.cur_sector, op);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// License: VNPL-1.1 or GNU GPL-2.0+ (see README.md for details)
|
||||
|
||||
#include <stdexcept>
|
||||
#undef NDEBUG
|
||||
#include <assert.h>
|
||||
#include "pg_states.h"
|
||||
#include "cluster_client_impl.h"
|
||||
@@ -11,23 +12,27 @@
|
||||
#define TRY_SEND_CONNECTING 1
|
||||
#define TRY_SEND_OK 2
|
||||
|
||||
cluster_client_t::cluster_client_t(ring_loop_t *ringloop, timerfd_manager_t *tfd, json11::Json config, std::unique_ptr<etcd_state_client_t> st_cli_ptr)
|
||||
cluster_client_t::cluster_client_t(ring_loop_t *ringloop, timerfd_manager_t *tfd, json11::Json passed_config, std::unique_ptr<etcd_state_client_t> st_cli_ptr)
|
||||
{
|
||||
wb = new writeback_cache_t();
|
||||
wb->parent = this;
|
||||
|
||||
cli_config = config.object_items();
|
||||
file_config = osd_messenger_t::read_config(config);
|
||||
cli_config = passed_config.object_items();
|
||||
file_config = osd_messenger_t::read_config(passed_config);
|
||||
config = osd_messenger_t::merge_configs(cli_config, file_config, etcd_global_config, {});
|
||||
|
||||
this->exit_on_error = config.find("client_exit_on_error") == config.end()
|
||||
? true : config["client_exit_on_error"].bool_value();
|
||||
this->ringloop = ringloop;
|
||||
this->tfd = tfd;
|
||||
|
||||
msgr.osd_num = 0;
|
||||
msgr.tfd = tfd;
|
||||
msgr.ringloop = ringloop;
|
||||
msgr.repeer_pgs = [this](osd_num_t peer_osd)
|
||||
msgr = new osd_messenger_t();
|
||||
msgr->osd_num = 0;
|
||||
msgr->tfd = tfd;
|
||||
msgr->ringloop = ringloop;
|
||||
msgr->repeer_pgs = [this](osd_num_t peer_osd)
|
||||
{
|
||||
if (msgr.osd_peers.find(peer_osd) != msgr.osd_peers.end())
|
||||
if (msgr->osd_peers.find(peer_osd) != msgr->osd_peers.end())
|
||||
{
|
||||
// peer_osd just connected
|
||||
continue_ops();
|
||||
@@ -38,31 +43,38 @@ cluster_client_t::cluster_client_t(ring_loop_t *ringloop, timerfd_manager_t *tfd
|
||||
{
|
||||
// peer_osd just dropped connection
|
||||
// determine WHICH dirty_buffers are now obsolete and repeat them
|
||||
if (wb->repeat_ops_for(this, peer_osd, 0, 0) > 0)
|
||||
if (wb->repeat_ops_for(this, peer_osd) > 0)
|
||||
{
|
||||
continue_ops();
|
||||
}
|
||||
}
|
||||
};
|
||||
msgr.exec_op = [this](osd_op_t *op)
|
||||
msgr->exec_op = [this](osd_op_t *op)
|
||||
{
|
||||
// Garbage in
|
||||
fprintf(stderr, "Can't handle incoming operation from client %lu\n", op->client_id);
|
||||
msgr.stop_client(op->client_id);
|
||||
fprintf(stderr, "Can't handle incoming operation from client %ju\n", op->client_id);
|
||||
msgr->stop_client(op->client_id);
|
||||
delete op;
|
||||
};
|
||||
msgr.parse_config(config, true);
|
||||
msgr->on_fatal_error_hook = [this](int errcode, const std::string & error) { fatal_error(errcode, error); };
|
||||
msgr->parse_config(config, true);
|
||||
|
||||
st_cli = std::move(st_cli_ptr);
|
||||
st_cli->on_load_config_hook = [this](json11::Json::object & cfg) { on_load_config_hook(cfg); };
|
||||
st_cli->on_change_osd_state_hook = [this](uint64_t peer_osd) { on_change_osd_state_hook(peer_osd); };
|
||||
st_cli->on_change_osd_state_hook = [this](osd_num_t peer_osd) { on_change_osd_state_hook(peer_osd); };
|
||||
st_cli->on_change_pool_config_hook = [this]() { on_change_pool_config_hook(); };
|
||||
st_cli->on_change_pg_config_hook = [this]() { on_change_pool_config_hook(); };
|
||||
st_cli->on_change_pg_state_hook = [this](pool_id_t pool_id, pg_num_t pg_num, osd_num_t prev_primary) { on_change_pg_state_hook(pool_id, pg_num, prev_primary); };
|
||||
st_cli->on_change_node_placement_hook = [this]() { on_change_node_placement_hook(); };
|
||||
st_cli->on_load_pgs_hook = [this](bool success) { on_load_pgs_hook(success); };
|
||||
st_cli->on_reload_hook = [this]() { this->st_cli->load_global_config(); };
|
||||
st_cli->on_reload_hook = [this]()
|
||||
{
|
||||
// Reloads only happen after start: retry etcd errors, don't fail the running client
|
||||
this->st_cli->infinite_start = true;
|
||||
this->st_cli->load_global_config();
|
||||
};
|
||||
st_cli->on_inode_change_hook = [this](uint64_t inode, bool removed) { on_change_inode_hook(inode, removed); };
|
||||
st_cli->on_fatal_error_hook = msgr->on_fatal_error_hook;
|
||||
|
||||
st_cli->parse_config(config);
|
||||
st_cli->infinite_start = false;
|
||||
@@ -71,11 +83,21 @@ cluster_client_t::cluster_client_t(ring_loop_t *ringloop, timerfd_manager_t *tfd
|
||||
st_cli->infinite_start = config["client_infinite_start"].bool_value();
|
||||
}
|
||||
st_cli->load_global_config();
|
||||
|
||||
if (ringloop)
|
||||
{
|
||||
ringloop->loop();
|
||||
}
|
||||
}
|
||||
|
||||
void cluster_client_t::set_on_fatal_error_hook(std::function<void(int, const std::string&)> cb)
|
||||
{
|
||||
on_fatal_error_hook = cb;
|
||||
}
|
||||
|
||||
cluster_client_t::~cluster_client_t()
|
||||
{
|
||||
vault_destroy();
|
||||
aborted = ECANCELED;
|
||||
if (retry_timeout_id >= 0)
|
||||
{
|
||||
tfd->clear_timer(retry_timeout_id);
|
||||
@@ -88,13 +110,44 @@ cluster_client_t::~cluster_client_t()
|
||||
list_retry_timeout_id = -1;
|
||||
list_retry_time = {};
|
||||
}
|
||||
msgr.repeer_pgs = [](osd_num_t){};
|
||||
msgr->repeer_pgs = [](osd_num_t){};
|
||||
if (ringloop)
|
||||
{
|
||||
ringloop->unregister_consumer(&consumer);
|
||||
}
|
||||
delete msgr;
|
||||
msgr = NULL;
|
||||
while (op_queue_head)
|
||||
{
|
||||
op_queue_head->retval = -ECANCELED;
|
||||
erase_op(op_queue_head);
|
||||
}
|
||||
delete wb;
|
||||
wb = NULL;
|
||||
vault_destroy();
|
||||
}
|
||||
|
||||
void cluster_client_t::fatal_error(int errcode, const std::string & error)
|
||||
{
|
||||
fprintf(stderr, "Error: %s%s\n", error.c_str(), exit_on_error ? ", exiting" : "");
|
||||
if (exit_on_error)
|
||||
{
|
||||
// Simple old behaviour by default - stop the whole process
|
||||
exit(1);
|
||||
}
|
||||
if (!pgs_loaded)
|
||||
{
|
||||
// Client becomes "ready" (but aborted) on error
|
||||
for (auto fn: on_ready_hooks)
|
||||
fn();
|
||||
on_ready_hooks.clear();
|
||||
}
|
||||
if (!aborted && on_fatal_error_hook)
|
||||
{
|
||||
(std::function<void(int, const std::string&)>(on_fatal_error_hook))(errcode, error);
|
||||
}
|
||||
aborted = true;
|
||||
abort_error = error;
|
||||
}
|
||||
|
||||
cluster_op_t::~cluster_op_t()
|
||||
@@ -149,13 +202,15 @@ std::vector<osd_num_t> cluster_op_t::get_left_on_dead()
|
||||
|
||||
void cluster_client_t::continue_raw_ops(osd_num_t peer_osd)
|
||||
{
|
||||
if (aborted)
|
||||
return;
|
||||
auto it = raw_ops.find(peer_osd);
|
||||
while (it != raw_ops.end() && it->first == peer_osd)
|
||||
{
|
||||
auto op = it->second;
|
||||
op->op_type = OSD_OP_OUT;
|
||||
op->client_id = msgr.osd_peers.at(peer_osd)->client_id;
|
||||
msgr.outbox_push(op);
|
||||
op->client_id = msgr->osd_peers.at(peer_osd)->client_id;
|
||||
msgr->outbox_push(op);
|
||||
raw_ops.erase(it++);
|
||||
}
|
||||
}
|
||||
@@ -164,14 +219,14 @@ void cluster_client_t::init_msgr()
|
||||
{
|
||||
if (msgr_initialized)
|
||||
return;
|
||||
msgr.init();
|
||||
msgr->init();
|
||||
msgr_initialized = true;
|
||||
if (ringloop)
|
||||
{
|
||||
consumer.loop = [this]()
|
||||
{
|
||||
msgr.read_requests();
|
||||
msgr.send_replies();
|
||||
msgr->read_requests();
|
||||
msgr->send_replies();
|
||||
this->ringloop->submit();
|
||||
};
|
||||
ringloop->register_consumer(&consumer);
|
||||
@@ -244,7 +299,7 @@ void cluster_client_t::inc_wait(uint64_t opcode, uint64_t flags, cluster_op_t *n
|
||||
{
|
||||
next->prev_wait += inc;
|
||||
assert(next->prev_wait >= 0);
|
||||
if (!next->prev_wait)
|
||||
if (!next->prev_wait && !continuing_ops)
|
||||
{
|
||||
// Kind of std::vector with local "small vector optimisation"
|
||||
if (bh_op_count >= bh_op_max)
|
||||
@@ -481,7 +536,7 @@ void cluster_client_t::on_load_config_hook(json11::Json::object & etcd_global_co
|
||||
}
|
||||
// vault
|
||||
vault_parse_config();
|
||||
msgr.parse_config(config, false);
|
||||
msgr->parse_config(config, false);
|
||||
st_cli->parse_config(config);
|
||||
st_cli->load_pgs();
|
||||
}
|
||||
@@ -590,7 +645,7 @@ void cluster_client_t::on_change_pool_config_hook()
|
||||
{
|
||||
if (log_level > 2 && pg_counts[pool_item.first])
|
||||
{
|
||||
fprintf(stderr, "Pool %u (%s) PG count changed from %lu to %lu\n", pool_item.first, pool_item.second.name.c_str(),
|
||||
fprintf(stderr, "Pool %u (%s) PG count changed from %ju to %ju\n", pool_item.first, pool_item.second.name.c_str(),
|
||||
pg_counts[pool_item.first], pool_item.second.real_pg_count);
|
||||
}
|
||||
// At this point, all pool operations should have been suspended
|
||||
@@ -609,18 +664,11 @@ void cluster_client_t::on_change_pool_config_hook()
|
||||
}
|
||||
inode_cache.clear();
|
||||
inode_cache_children.clear();
|
||||
vault_keys.clear();
|
||||
continue_ops();
|
||||
}
|
||||
|
||||
void cluster_client_t::on_change_pg_state_hook(pool_id_t pool_id, pg_num_t pg_num, osd_num_t prev_primary)
|
||||
{
|
||||
auto & pg_cfg = st_cli->pool_config[pool_id].pg_config[pg_num];
|
||||
if (pg_cfg.cur_primary != prev_primary)
|
||||
{
|
||||
// Repeat this PG operations because an OSD which stopped being primary may not fsync operations
|
||||
wb->repeat_ops_for(this, 0, pool_id, pg_num);
|
||||
}
|
||||
// Always continue to resume operations hung because of lack of the primary OSD
|
||||
continue_ops();
|
||||
continue_lists();
|
||||
@@ -639,12 +687,12 @@ bool cluster_client_t::get_immediate_commit(uint64_t inode)
|
||||
return pool_it->second.immediate_commit == IMMEDIATE_ALL;
|
||||
}
|
||||
|
||||
void cluster_client_t::on_change_osd_state_hook(uint64_t peer_osd)
|
||||
void cluster_client_t::on_change_osd_state_hook(osd_num_t peer_osd)
|
||||
{
|
||||
osd_tree_metrics.erase(peer_osd);
|
||||
if (msgr.wanted_peers.find(peer_osd) != msgr.wanted_peers.end())
|
||||
if (msgr->wanted_peers.find(peer_osd) != msgr->wanted_peers.end())
|
||||
{
|
||||
msgr.connect_peer(peer_osd, st_cli->peer_states[peer_osd]);
|
||||
msgr->connect_peer(peer_osd, st_cli->peer_states[peer_osd]);
|
||||
continue_lists();
|
||||
}
|
||||
}
|
||||
@@ -657,12 +705,21 @@ void cluster_client_t::on_change_node_placement_hook()
|
||||
|
||||
bool cluster_client_t::is_ready()
|
||||
{
|
||||
return pgs_loaded;
|
||||
return pgs_loaded || aborted;
|
||||
}
|
||||
|
||||
int cluster_client_t::is_failed(std::string & error)
|
||||
{
|
||||
if (aborted)
|
||||
{
|
||||
error = abort_error;
|
||||
}
|
||||
return aborted;
|
||||
}
|
||||
|
||||
void cluster_client_t::on_ready(std::function<void(void)> fn)
|
||||
{
|
||||
if (pgs_loaded)
|
||||
if (is_ready())
|
||||
{
|
||||
fn();
|
||||
}
|
||||
@@ -861,15 +918,14 @@ void cluster_client_t::execute_internal(cluster_op_t *op)
|
||||
|
||||
void cluster_client_t::execute_cas(cluster_op_t *op, bool nosync)
|
||||
{
|
||||
if ((op->opcode == OSD_OP_WRITE || op->opcode == OSD_OP_DELETE) && op->version && op->parts.size() > 1)
|
||||
if (aborted)
|
||||
{
|
||||
// Atomic writes to multiple stripes are unsupported
|
||||
op->retval = -EINVAL;
|
||||
op->retval = -ECANCELED;
|
||||
auto cb = std::move(op->callback);
|
||||
cb(op);
|
||||
return;
|
||||
}
|
||||
if (!(op->flags & OP_IMMEDIATE_COMMIT) && !nosync &&
|
||||
if ((!(op->flags & OP_IMMEDIATE_COMMIT) || enable_writeback) && !nosync &&
|
||||
wb->has_dirty(op->inode, op->offset, op->len))
|
||||
{
|
||||
cluster_op_t *sync_op = new cluster_op_t;
|
||||
@@ -877,7 +933,14 @@ void cluster_client_t::execute_cas(cluster_op_t *op, bool nosync)
|
||||
sync_op->flags = 0;
|
||||
sync_op->callback = [this, op](cluster_op_t* sync_op)
|
||||
{
|
||||
execute_cas(op, true);
|
||||
if (sync_op->retval != 0)
|
||||
{
|
||||
op->retval = sync_op->retval;
|
||||
auto cb = std::move(op->callback);
|
||||
cb(op);
|
||||
}
|
||||
else
|
||||
execute_cas(op, true);
|
||||
delete sync_op;
|
||||
};
|
||||
execute_internal(sync_op);
|
||||
@@ -890,21 +953,36 @@ void cluster_client_t::execute_cas(cluster_op_t *op, bool nosync)
|
||||
cb(op);
|
||||
return;
|
||||
}
|
||||
if ((op->opcode == OSD_OP_WRITE || op->opcode == OSD_OP_DELETE) && op->version && op->parts.size() > 1)
|
||||
{
|
||||
// Atomic writes to multiple stripes are unsupported
|
||||
op->retval = -EINVAL;
|
||||
auto cb = std::move(op->callback);
|
||||
cb(op);
|
||||
return;
|
||||
}
|
||||
op->needs_reslice = false;
|
||||
int res = try_send(op, 0, [this, op](osd_op_t *part)
|
||||
{
|
||||
if (aborted)
|
||||
{
|
||||
op->retval = -ECANCELED;
|
||||
auto cb = std::move(op->callback);
|
||||
cb(op);
|
||||
return;
|
||||
}
|
||||
int expected = part->req.hdr.opcode == OSD_OP_DELETE ? 0 : part->req.rw.len;
|
||||
op->retval = part->reply.hdr.retval;
|
||||
if (op->retval != expected && op->retval >= 0)
|
||||
op->retval = -EIO;
|
||||
op->retval = op->retval == -EPIPE ? -EINTR : op->retval;
|
||||
auto peer_it = msgr.osd_peers.find(op->parts[0].osd_num);
|
||||
auto peer_it = msgr->osd_peers.find(op->parts[0].osd_num);
|
||||
if (op->retval != expected || (op->flags & OP_IMMEDIATE_COMMIT))
|
||||
{
|
||||
auto cb = std::move(op->callback);
|
||||
cb(op);
|
||||
}
|
||||
else if (peer_it == msgr.osd_peers.end())
|
||||
else if (peer_it == msgr->osd_peers.end())
|
||||
{
|
||||
// Care must be taken to make sure that the client doesn't reconnect to the OSD
|
||||
// before executing the previously completed operation callback (!)
|
||||
@@ -936,7 +1014,7 @@ void cluster_client_t::execute_cas(cluster_op_t *op, bool nosync)
|
||||
cb(op);
|
||||
},
|
||||
};
|
||||
msgr.outbox_push(part);
|
||||
msgr->outbox_push(part);
|
||||
}
|
||||
});
|
||||
if (res == TRY_SEND_CONNECTING || res == TRY_SEND_OFFLINE)
|
||||
@@ -1067,23 +1145,25 @@ bool cluster_client_t::check_rw(cluster_op_t *op)
|
||||
|
||||
void cluster_client_t::execute_raw(osd_num_t osd_num, osd_op_t *op)
|
||||
{
|
||||
auto peer_it = msgr.osd_peers.find(osd_num);
|
||||
if (peer_it != msgr.osd_peers.end())
|
||||
auto peer_it = msgr->osd_peers.find(osd_num);
|
||||
if (peer_it != msgr->osd_peers.end())
|
||||
{
|
||||
op->op_type = OSD_OP_OUT;
|
||||
op->client_id = peer_it->second->client_id;
|
||||
msgr.outbox_push(op);
|
||||
msgr->outbox_push(op);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (msgr.wanted_peers.find(osd_num) == msgr.wanted_peers.end())
|
||||
msgr.connect_peer(osd_num, st_cli->peer_states[osd_num]);
|
||||
if (msgr->wanted_peers.find(osd_num) == msgr->wanted_peers.end())
|
||||
msgr->connect_peer(osd_num, st_cli->peer_states[osd_num]);
|
||||
raw_ops.emplace(osd_num, op);
|
||||
}
|
||||
}
|
||||
|
||||
int cluster_client_t::continue_rw(cluster_op_t *op)
|
||||
{
|
||||
if (aborted)
|
||||
return 0;
|
||||
if (op->state == 0)
|
||||
goto resume_0;
|
||||
else if (op->state == 1)
|
||||
@@ -1143,6 +1223,7 @@ resume_1:
|
||||
// Set "wait_up" timer
|
||||
clock_gettime(CLOCK_REALTIME, &op->wait_up_until);
|
||||
op->wait_up_until.tv_sec += client_wait_up_timeout;
|
||||
reset_retry_timer(client_wait_up_timeout*1000);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -1159,6 +1240,9 @@ resume_1:
|
||||
op->retval = -ETIMEDOUT;
|
||||
break;
|
||||
}
|
||||
// reset_retry_timer() keeps a shorter timer, which may have fired for another operation
|
||||
reset_retry_timer(std::max(1l, (op->wait_up_until.tv_sec - tv.tv_sec)*1000 +
|
||||
(op->wait_up_until.tv_nsec - tv.tv_nsec + 999999)/1000000));
|
||||
}
|
||||
}
|
||||
if (op->parts[i].flags & PART_RETRY)
|
||||
@@ -1242,7 +1326,7 @@ resume_2:
|
||||
op->retval = op->len / pool_cfg.bitmap_granularity;
|
||||
}
|
||||
}
|
||||
if (op->flush_id)
|
||||
if (op->flush_id && !(op->flags & OP_IMMEDIATE_COMMIT))
|
||||
{
|
||||
wb->mark_flush_written(op->inode, op->offset, op->len, op->flush_id);
|
||||
}
|
||||
@@ -1250,9 +1334,11 @@ resume_2:
|
||||
return 1;
|
||||
}
|
||||
else if (op->retval != 0 && op->opcode != OSD_OP_SYNC && !(op->flags & OP_FLUSH_BUFFER) &&
|
||||
op->retval != -EPIPE && (op->retval != -EIO || !client_eio_retry_interval) && (op->retval != -ENOSPC || !client_retry_enospc))
|
||||
op->retval != -EPIPE && op->retval != -EAGAIN &&
|
||||
(op->retval != -EIO || !client_eio_retry_interval) &&
|
||||
(op->retval != -ENOSPC || !client_retry_enospc))
|
||||
{
|
||||
// Fatal error (neither -EPIPE, -EIO nor -ENOSPC)
|
||||
// Fatal error (neither -EPIPE, -EAGAIN, -EIO nor -ENOSPC)
|
||||
erase_op(op);
|
||||
return 1;
|
||||
}
|
||||
@@ -1423,58 +1509,6 @@ bool cluster_client_t::slice_rw(cluster_op_t *op)
|
||||
return true;
|
||||
}
|
||||
|
||||
bool cluster_client_t::affects_pg(uint64_t inode, uint64_t offset, uint64_t len, pool_id_t pool_id, pg_num_t pg_num)
|
||||
{
|
||||
if (INODE_POOL(inode) != pool_id)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
auto pool_it = st_cli->pool_config.find(INODE_POOL(inode));
|
||||
if (pool_it == st_cli->pool_config.end())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
auto & pool_cfg = pool_it->second;
|
||||
uint32_t pg_data_size = (pool_cfg.scheme == POOL_SCHEME_REPLICATED ? 1 : pool_cfg.pg_size-pool_cfg.parity_chunks);
|
||||
uint64_t pg_block_size = pool_cfg.data_block_size * pg_data_size;
|
||||
uint64_t first_stripe = (offset / pg_block_size) * pg_block_size;
|
||||
uint64_t last_stripe = len > 0 ? ((offset + len - 1) / pg_block_size) * pg_block_size : first_stripe;
|
||||
if ((last_stripe/pool_cfg.pg_stripe_size) - (first_stripe/pool_cfg.pg_stripe_size) + 1 >= pool_cfg.real_pg_count)
|
||||
{
|
||||
// All PGs are affected
|
||||
return true;
|
||||
}
|
||||
pg_num_t first_pg_num = (first_stripe/pool_cfg.pg_stripe_size) % pool_cfg.real_pg_count + 1; // like map_to_pg()
|
||||
pg_num_t last_pg_num = (last_stripe/pool_cfg.pg_stripe_size) % pool_cfg.real_pg_count + 1; // like map_to_pg()
|
||||
return (first_pg_num <= last_pg_num
|
||||
? (pg_num >= first_pg_num && pg_num <= last_pg_num)
|
||||
: (pg_num >= first_pg_num || pg_num <= last_pg_num));
|
||||
}
|
||||
|
||||
bool cluster_client_t::affects_osd(uint64_t inode, uint64_t offset, uint64_t len, osd_num_t osd)
|
||||
{
|
||||
auto pool_it = st_cli->pool_config.find(INODE_POOL(inode));
|
||||
if (pool_it == st_cli->pool_config.end())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
auto & pool_cfg = pool_it->second;
|
||||
uint32_t pg_data_size = (pool_cfg.scheme == POOL_SCHEME_REPLICATED ? 1 : pool_cfg.pg_size-pool_cfg.parity_chunks);
|
||||
uint64_t pg_block_size = pool_cfg.data_block_size * pg_data_size;
|
||||
uint64_t first_stripe = (offset / pg_block_size) * pg_block_size;
|
||||
uint64_t last_stripe = len > 0 ? ((offset + len - 1) / pg_block_size) * pg_block_size : first_stripe;
|
||||
for (uint64_t stripe = first_stripe; stripe <= last_stripe; stripe += pg_block_size)
|
||||
{
|
||||
pg_num_t pg_num = (stripe/pool_cfg.pg_stripe_size) % pool_cfg.real_pg_count + 1; // like map_to_pg()
|
||||
auto pg_it = pool_cfg.pg_config.find(pg_num);
|
||||
if (pg_it != pool_cfg.pg_config.end() && pg_it->second.cur_primary == osd)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
int cluster_client_t::try_send(cluster_op_t *op, int i, std::function<void(osd_op_t *op_part)> cb)
|
||||
{
|
||||
if (!msgr_initialized)
|
||||
@@ -1506,8 +1540,8 @@ int cluster_client_t::try_send(cluster_op_t *op, int i, std::function<void(osd_o
|
||||
primary_osd = nearest_osd;
|
||||
}
|
||||
part->osd_num = primary_osd;
|
||||
auto peer_it = msgr.osd_peers.find(primary_osd);
|
||||
if (peer_it != msgr.osd_peers.end())
|
||||
auto peer_it = msgr->osd_peers.find(primary_osd);
|
||||
if (peer_it != msgr->osd_peers.end())
|
||||
{
|
||||
osd_client_t *cl = peer_it->second;
|
||||
part->flags |= PART_SENT|PART_VALID;
|
||||
@@ -1551,12 +1585,12 @@ int cluster_client_t::try_send(cluster_op_t *op, int i, std::function<void(osd_o
|
||||
},
|
||||
};
|
||||
part->op.iov = part->iov;
|
||||
msgr.outbox_push(&part->op);
|
||||
msgr->outbox_push(&part->op);
|
||||
return TRY_SEND_OK;
|
||||
}
|
||||
else if (msgr.wanted_peers.find(primary_osd) == msgr.wanted_peers.end())
|
||||
else if (msgr->wanted_peers.find(primary_osd) == msgr->wanted_peers.end())
|
||||
{
|
||||
msgr.connect_peer(primary_osd, st_cli->peer_states[primary_osd]);
|
||||
msgr->connect_peer(primary_osd, st_cli->peer_states[primary_osd]);
|
||||
return TRY_SEND_CONNECTING;
|
||||
}
|
||||
}
|
||||
@@ -1565,6 +1599,8 @@ int cluster_client_t::try_send(cluster_op_t *op, int i, std::function<void(osd_o
|
||||
|
||||
int cluster_client_t::continue_sync(cluster_op_t *op)
|
||||
{
|
||||
if (aborted)
|
||||
return 0;
|
||||
if (op->state == 1)
|
||||
goto resume_1;
|
||||
if (!dirty_osds.size())
|
||||
@@ -1578,8 +1614,8 @@ int cluster_client_t::continue_sync(cluster_op_t *op)
|
||||
for (auto do_it = dirty_osds.begin(); do_it != dirty_osds.end(); )
|
||||
{
|
||||
osd_num_t sync_osd = *do_it;
|
||||
auto peer_it = msgr.osd_peers.find(sync_osd);
|
||||
if (peer_it == msgr.osd_peers.end())
|
||||
auto peer_it = msgr->osd_peers.find(sync_osd);
|
||||
if (peer_it == msgr->osd_peers.end())
|
||||
dirty_osds.erase(do_it++);
|
||||
else
|
||||
do_it++;
|
||||
@@ -1610,8 +1646,10 @@ resume_1:
|
||||
}
|
||||
if (op->retval != 0)
|
||||
{
|
||||
for (int i = 0; i < op->parts.size(); i++)
|
||||
dirty_osds.insert(op->parts[i].osd_num);
|
||||
wb->fsync_error();
|
||||
if (op->retval == -EPIPE || op->retval == -EIO || op->retval == -ENOSPC)
|
||||
if (op->retval == -EPIPE || op->retval == -EAGAIN || op->retval == -EIO || op->retval == -ENOSPC)
|
||||
{
|
||||
// Retry later
|
||||
op->parts.clear();
|
||||
@@ -1632,7 +1670,7 @@ resume_1:
|
||||
|
||||
void cluster_client_t::send_sync(cluster_op_t *op, cluster_op_part_t *part)
|
||||
{
|
||||
osd_client_t *cl = msgr.osd_peers.at(part->osd_num);
|
||||
osd_client_t *cl = msgr->osd_peers.at(part->osd_num);
|
||||
part->flags |= PART_SENT;
|
||||
op->inflight_count++;
|
||||
part->op = (osd_op_t){
|
||||
@@ -1649,7 +1687,7 @@ void cluster_client_t::send_sync(cluster_op_t *op, cluster_op_part_t *part)
|
||||
handle_op_part(part);
|
||||
},
|
||||
};
|
||||
msgr.outbox_push(&part->op);
|
||||
msgr->outbox_push(&part->op);
|
||||
}
|
||||
|
||||
static inline void mem_or(void *res, const void *r2, unsigned int len)
|
||||
@@ -1662,9 +1700,6 @@ static inline void mem_or(void *res, const void *r2, unsigned int len)
|
||||
}
|
||||
}
|
||||
|
||||
// Error priority: others > EPERM > EIO > ENOSPC > ETIMEDOUT > EPIPE
|
||||
#define ERR_PRIO(e) (((e) == -EPERM ? 5 : ((e) == -EIO ? 4 : ((e) == -ENOSPC ? 3 : ((e) == -ETIMEDOUT ? 2 : ((e) == -EPIPE ? 1 : (!(e) ? 0 : 10)))))))
|
||||
|
||||
void cluster_client_t::handle_op_part(cluster_op_part_t *part)
|
||||
{
|
||||
cluster_op_t *op = part->parent;
|
||||
@@ -1676,7 +1711,7 @@ void cluster_client_t::handle_op_part(cluster_op_part_t *part)
|
||||
if (ERR_PRIO(part->op.reply.hdr.retval) > ERR_PRIO(op->retval))
|
||||
op->retval = part->op.reply.hdr.retval;
|
||||
uint64_t stop_client_id = 0;
|
||||
if (op->retval != -EINTR && op->retval != -EIO && op->retval != -ENOSPC && op->retval != -EPERM)
|
||||
if (op->retval != -EINTR && op->retval != -EIO && op->retval != -ENOSPC && op->retval != -EPERM && op->retval != -EAGAIN)
|
||||
{
|
||||
stop_client_id = part->op.client_id;
|
||||
if (op->retval != -EPIPE || log_level > 0)
|
||||
@@ -1698,16 +1733,16 @@ void cluster_client_t::handle_op_part(cluster_op_part_t *part)
|
||||
// So do all these things after modifying operation state, otherwise we may hit reenterability bugs
|
||||
// FIXME postpone such things to set_immediate here to avoid bugs
|
||||
// Set op->retry_after to retry operation after a short pause (not immediately)
|
||||
if (!op->retry_after && (op->retval == -EPIPE ||
|
||||
if (!op->retry_after && (op->retval == -EPIPE || op->retval == -EAGAIN ||
|
||||
op->retval == -EIO && client_eio_retry_interval ||
|
||||
op->retval == -ENOSPC && client_retry_enospc))
|
||||
{
|
||||
op->retry_after = op->retval != -EPIPE ? client_eio_retry_interval : client_retry_interval;
|
||||
op->retry_after = op->retval != -EPIPE && op->retval != -EAGAIN ? client_eio_retry_interval : client_retry_interval;
|
||||
}
|
||||
reset_retry_timer(op->retry_after);
|
||||
if (stop_client_id)
|
||||
{
|
||||
msgr.stop_client(stop_client_id);
|
||||
msgr->stop_client(stop_client_id);
|
||||
}
|
||||
op->inflight_count--;
|
||||
if (op->inflight_count == 0 && !op->retry_after)
|
||||
@@ -1723,7 +1758,10 @@ void cluster_client_t::handle_op_part(cluster_op_part_t *part)
|
||||
// OK
|
||||
op->inflight_count--;
|
||||
if ((op->opcode == OSD_OP_WRITE || op->opcode == OSD_OP_DELETE) && !(op->flags & OP_IMMEDIATE_COMMIT))
|
||||
{
|
||||
wb->mark_flush_written_to(op->inode, part->op.req.rw.offset, part->op.req.rw.len, op->flush_id, part->osd_num);
|
||||
dirty_osds.insert(part->osd_num);
|
||||
}
|
||||
part->flags |= PART_DONE;
|
||||
op->done_count++;
|
||||
if ((op->opcode == OSD_OP_READ || op->opcode == OSD_OP_READ_BITMAP || op->opcode == OSD_OP_READ_CHAIN_BITMAP)
|
||||
|
||||
@@ -93,6 +93,7 @@ struct inode_cache_t
|
||||
bool has_parent_loop = false;
|
||||
inode_t other_pool_parent_id = 0;
|
||||
int err_code = 0;
|
||||
timespec err_timeout = {};
|
||||
|
||||
~inode_cache_t();
|
||||
};
|
||||
@@ -100,6 +101,7 @@ struct inode_cache_t
|
||||
struct vault_load_key_t
|
||||
{
|
||||
int key_state = 0;
|
||||
timespec load_time = {};
|
||||
std::string key;
|
||||
};
|
||||
|
||||
@@ -108,6 +110,7 @@ class __attribute__((visibility("default"))) cluster_client_t
|
||||
{
|
||||
timerfd_manager_t *tfd = NULL;
|
||||
ring_loop_t *ringloop = NULL;
|
||||
std::function<void(int, const std::string&)> on_fatal_error_hook;
|
||||
|
||||
// config:
|
||||
|
||||
@@ -121,6 +124,7 @@ class __attribute__((visibility("default"))) cluster_client_t
|
||||
uint64_t client_max_buffered_ops = 0;
|
||||
uint64_t client_max_writeback_iodepth = 0;
|
||||
std::string conf_hostname;
|
||||
bool exit_on_error = false;
|
||||
|
||||
std::string vault_url;
|
||||
std::string vault_client_cert;
|
||||
@@ -176,11 +180,13 @@ class __attribute__((visibility("default"))) cluster_client_t
|
||||
std::multimap<osd_num_t, osd_op_t*> raw_ops;
|
||||
int continuing_ops = 0;
|
||||
bool msgr_initialized = false;
|
||||
int aborted = 0;
|
||||
std::string abort_error;
|
||||
|
||||
public:
|
||||
std::unique_ptr<etcd_state_client_t> st_cli;
|
||||
osd_messenger_t* msgr = NULL;
|
||||
|
||||
osd_messenger_t msgr;
|
||||
void init_msgr();
|
||||
|
||||
json11::Json::object cli_config, file_config, etcd_global_config;
|
||||
@@ -192,8 +198,10 @@ public:
|
||||
void execute(cluster_op_t *op);
|
||||
void execute_raw(osd_num_t osd_num, osd_op_t *op);
|
||||
bool is_ready();
|
||||
int is_failed(std::string & error);
|
||||
void on_ready(std::function<void(void)> fn);
|
||||
bool flush();
|
||||
void set_on_fatal_error_hook(std::function<void(int, const std::string&)>);
|
||||
|
||||
bool get_immediate_commit(uint64_t inode);
|
||||
|
||||
@@ -202,6 +210,7 @@ public:
|
||||
|
||||
protected:
|
||||
void continue_ops(int time_passed = 0);
|
||||
void fatal_error(int errcode, const std::string & error);
|
||||
|
||||
std::shared_ptr<inode_cache_t> inode_cache_get(inode_t ino);
|
||||
void vault_parse_config();
|
||||
@@ -210,14 +219,11 @@ protected:
|
||||
void vault_destroy();
|
||||
void vault_parse_secret(const std::string & key_id, const std::string & err, json11::Json data);
|
||||
|
||||
bool affects_osd(uint64_t inode, uint64_t offset, uint64_t len, osd_num_t osd);
|
||||
bool affects_pg(uint64_t inode, uint64_t offset, uint64_t len, pool_id_t pool_id, pg_num_t pg_num);
|
||||
|
||||
void on_load_config_hook(json11::Json::object & config);
|
||||
void on_load_pgs_hook(bool success);
|
||||
void on_change_pool_config_hook();
|
||||
void on_change_pg_state_hook(pool_id_t pool_id, pg_num_t pg_num, osd_num_t prev_primary);
|
||||
void on_change_osd_state_hook(uint64_t peer_osd);
|
||||
void on_change_osd_state_hook(osd_num_t peer_osd);
|
||||
void on_change_node_placement_hook();
|
||||
void on_change_inode_hook(uint64_t inode, bool removed);
|
||||
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
// Copyright (c) Vitaliy Filippov, 2019+
|
||||
// License: VNPL-1.1 or GNU GPL-2.0+ (see README.md for details)
|
||||
|
||||
#include <stdexcept>
|
||||
#undef NDEBUG
|
||||
#include <assert.h>
|
||||
#include <stdexcept>
|
||||
#include "cluster_client_impl.h"
|
||||
#include "str_util.h"
|
||||
|
||||
@@ -73,7 +74,18 @@ std::shared_ptr<inode_cache_t> cluster_client_t::inode_cache_get(inode_t ino)
|
||||
auto icache_it = inode_cache.find(ino);
|
||||
if (icache_it != inode_cache.end())
|
||||
{
|
||||
return icache_it->second;
|
||||
if (icache_it->second &&
|
||||
icache_it->second->err_code &&
|
||||
icache_it->second->err_timeout.tv_sec)
|
||||
{
|
||||
timespec tv = {};
|
||||
clock_gettime(CLOCK_REALTIME, &tv);
|
||||
if (icache_it->second->err_timeout.tv_sec > tv.tv_sec)
|
||||
return icache_it->second;
|
||||
printf("%lu\n", icache_it->second ? icache_it->second->err_timeout.tv_sec : 0);
|
||||
}
|
||||
else
|
||||
return icache_it->second;
|
||||
}
|
||||
// Fill inode cache
|
||||
auto ino_it = st_cli->inode_config.find(ino);
|
||||
@@ -138,16 +150,25 @@ std::shared_ptr<inode_cache_t> cluster_client_t::inode_cache_get(inode_t ino)
|
||||
inode_config_t *cfg = !i ? &inode_cfg : chain_cfg[i-1];
|
||||
if (cfg && cfg->enc_key.substr(0, strlen(VAULT_KEY_PREFIX)) == VAULT_KEY_PREFIX)
|
||||
{
|
||||
auto & ik = vault_keys[inode_cfg.enc_key];
|
||||
if (ik.key_state == VAULT_KEY_ERROR || vault_url.empty())
|
||||
auto & ik = vault_keys[cfg->enc_key];
|
||||
if (ik.key_state == VAULT_KEY_ERROR)
|
||||
{
|
||||
timespec tv = {};
|
||||
clock_gettime(CLOCK_REALTIME, &tv);
|
||||
if (ik.load_time.tv_sec + vault_error_timeout_sec <= tv.tv_sec)
|
||||
ik.key_state = VAULT_KEY_NOT_LOADED;
|
||||
}
|
||||
if (vault_url.empty() || ik.key_state == VAULT_KEY_ERROR)
|
||||
{
|
||||
icache->err_code = EPERM;
|
||||
icache->err_timeout = ik.load_time;
|
||||
icache->err_timeout.tv_sec += vault_error_timeout_sec;
|
||||
enc_key_count = 0;
|
||||
}
|
||||
else if (ik.key_state == VAULT_KEY_NOT_LOADED)
|
||||
{
|
||||
ik.key_state = VAULT_KEY_LOADING;
|
||||
vault_key_load_queue.push_back(inode_cfg.enc_key);
|
||||
vault_key_load_queue.push_back(cfg->enc_key);
|
||||
vault_load_keys();
|
||||
icache->err_code = EAGAIN;
|
||||
enc_key_count = 0;
|
||||
@@ -212,6 +233,7 @@ void cluster_client_t::vault_parse_secret(const std::string & key_id, const std:
|
||||
{
|
||||
vault_loading = false;
|
||||
auto & k = vault_keys[key_id];
|
||||
clock_gettime(CLOCK_REALTIME, &k.load_time);
|
||||
if (err != "")
|
||||
{
|
||||
k.key_state = VAULT_KEY_ERROR;
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "cluster_client.h"
|
||||
#include "small_vector.h"
|
||||
|
||||
#define PART_SENT 1
|
||||
#define PART_DONE 2
|
||||
@@ -29,6 +30,11 @@ struct cluster_buffer_t
|
||||
int state;
|
||||
uint64_t flush_id;
|
||||
uint64_t *refcnt;
|
||||
// Funny thing is that a buffer may be CACHE_REPEATING or even CACHE_DIRTY
|
||||
// which means it's NOT written yet and have written_to_osd at the same time,
|
||||
// because it may be left from the PREVIOUS write attempt which we MUST remember
|
||||
// to correctly handle OSD failure retries.
|
||||
small_vector_t<osd_num_t, 4> written_to_osd;
|
||||
};
|
||||
|
||||
typedef std::map<object_id, cluster_buffer_t>::iterator dirty_buf_it_t;
|
||||
@@ -40,6 +46,7 @@ public:
|
||||
int writeback_queue_size = 0;
|
||||
int writebacks_active = 0;
|
||||
uint64_t last_flush_id = 0;
|
||||
cluster_client_t *parent = NULL;
|
||||
|
||||
std::map<object_id, cluster_buffer_t> dirty_buffers;
|
||||
std::vector<cluster_op_t*> writeback_overflow;
|
||||
@@ -52,11 +59,12 @@ public:
|
||||
bool is_left_merged(dirty_buf_it_t dirty_it);
|
||||
bool is_right_merged(dirty_buf_it_t dirty_it);
|
||||
void copy_write(cluster_op_t *op, int state, uint64_t new_flush_id = 0);
|
||||
int repeat_ops_for(cluster_client_t *cli, osd_num_t peer_osd, pool_id_t pool_id, pg_num_t pg_num);
|
||||
int repeat_ops_for(cluster_client_t *cli, osd_num_t peer_osd);
|
||||
void start_writebacks(cluster_client_t *cli, int count);
|
||||
bool read_from_cache(cluster_op_t *op, uint32_t bitmap_granularity);
|
||||
void flush_buffers(cluster_client_t *cli, dirty_buf_it_t from_it, dirty_buf_it_t to_it);
|
||||
void mark_flush_written(uint64_t inode, uint64_t offset, uint64_t len, uint64_t flush_id);
|
||||
void mark_flush_written_to(uint64_t inode, uint64_t offset, uint64_t len, uint64_t flush_id, osd_num_t osd_num);
|
||||
void delete_flush(uint64_t inode, uint64_t offset, uint64_t len, uint64_t flush_id);
|
||||
void fsync_start();
|
||||
void fsync_error();
|
||||
|
||||
@@ -226,6 +226,12 @@ void cluster_client_t::retry_start_pg_listing(inode_list_pg_t *pg)
|
||||
pg->objects.clear();
|
||||
finish_list_pg(pg, false);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Ensure that the retry timer is set: it may have fired for another PG
|
||||
set_list_retry_timeout(pg->wait_until.tv_sec*1000 - tv.tv_sec*1000 +
|
||||
(pg->wait_until.tv_nsec - tv.tv_nsec)/1000000, pg->wait_until);
|
||||
}
|
||||
}
|
||||
|
||||
void cluster_client_t::set_list_retry_timeout(int ms, timespec new_time)
|
||||
@@ -301,14 +307,14 @@ int cluster_client_t::start_pg_listing(inode_list_pg_t *pg)
|
||||
bool conn = true;
|
||||
for (osd_num_t peer_osd: all_peers)
|
||||
{
|
||||
if (msgr.osd_peers.find(peer_osd) == msgr.osd_peers.end())
|
||||
if (msgr->osd_peers.find(peer_osd) == msgr->osd_peers.end())
|
||||
{
|
||||
// Initiate connection
|
||||
if (st_cli->peer_states[peer_osd].is_null())
|
||||
{
|
||||
return LIST_PG_WAIT_ACTIVE;
|
||||
}
|
||||
msgr.connect_peer(peer_osd, st_cli->peer_states[peer_osd]);
|
||||
msgr->connect_peer(peer_osd, st_cli->peer_states[peer_osd]);
|
||||
conn = false;
|
||||
}
|
||||
}
|
||||
@@ -346,7 +352,7 @@ void cluster_client_t::send_list(inode_list_osd_t *cur_list)
|
||||
osd_op_t *op = new osd_op_t();
|
||||
op->op_type = OSD_OP_OUT;
|
||||
// Already checked that it exists above, but anyway
|
||||
op->client_id = msgr.osd_peers.at(cur_list->osd_num)->client_id;
|
||||
op->client_id = msgr->osd_peers.at(cur_list->osd_num)->client_id;
|
||||
op->req = (osd_any_op_t){
|
||||
.sec_list = {
|
||||
.header = {
|
||||
@@ -370,8 +376,7 @@ void cluster_client_t::send_list(inode_list_osd_t *cur_list)
|
||||
fprintf(stderr, "Failed to get PG %u/%u object list from OSD %ju (retval=%jd), skipping\n",
|
||||
cur_list->pg->lst->pool_id, cur_list->pg->pg_num, cur_list->osd_num, op->reply.hdr.retval);
|
||||
if (!cur_list->pg->errcode ||
|
||||
cur_list->pg->errcode == -EPIPE ||
|
||||
op->reply.hdr.retval != -EPIPE)
|
||||
ERR_PRIO(op->reply.hdr.retval) > ERR_PRIO(cur_list->pg->errcode))
|
||||
{
|
||||
cur_list->pg->errcode = op->reply.hdr.retval;
|
||||
}
|
||||
@@ -395,14 +400,22 @@ void cluster_client_t::send_list(inode_list_osd_t *cur_list)
|
||||
}
|
||||
else
|
||||
{
|
||||
if (op->reply.sec_list.stable_count < op->reply.hdr.retval)
|
||||
// A raw listing from a peer ends with its tombstones. A tombstone means
|
||||
// "absent" - the client must not see it as an object, and it's not an
|
||||
// unstable version either. The primary listing already filters them out
|
||||
// and reports tombstone_count = 0
|
||||
uint64_t total_count = op->reply.hdr.retval;
|
||||
uint64_t tomb_count = op->reply.sec_list.tombstone_count;
|
||||
uint64_t data_count = total_count > tomb_count ? total_count - tomb_count : 0;
|
||||
uint64_t n_unstable = data_count > op->reply.sec_list.stable_count
|
||||
? data_count - op->reply.sec_list.stable_count : 0;
|
||||
if (n_unstable > 0)
|
||||
{
|
||||
// Unstable objects, if present, mean that someone still writes into the inode. Warn the user about it.
|
||||
cur_list->pg->has_unstable = true;
|
||||
fprintf(
|
||||
stderr, "[PG %u/%u] Inode still has %ju unstable object versions out of total %ju - is it still open?\n",
|
||||
cur_list->pg->lst->pool_id, cur_list->pg->pg_num, op->reply.hdr.retval - op->reply.sec_list.stable_count,
|
||||
op->reply.hdr.retval
|
||||
cur_list->pg->lst->pool_id, cur_list->pg->pg_num, n_unstable, op->reply.hdr.retval
|
||||
);
|
||||
}
|
||||
if (log_level > 0)
|
||||
@@ -412,7 +425,7 @@ void cluster_client_t::send_list(inode_list_osd_t *cur_list)
|
||||
cur_list->pg->lst->pool_id, cur_list->pg->pg_num, cur_list->osd_num, op->reply.hdr.retval
|
||||
);
|
||||
}
|
||||
for (uint64_t i = 0; i < op->reply.hdr.retval; i++)
|
||||
for (uint64_t i = 0; i < data_count; i++)
|
||||
{
|
||||
object_id oid = ((obj_ver_id*)op->buf)[i].oid;
|
||||
oid.stripe = oid.stripe & ~STRIPE_MASK;
|
||||
@@ -426,7 +439,7 @@ void cluster_client_t::send_list(inode_list_osd_t *cur_list)
|
||||
finish_list_pg(cur_list->pg, true);
|
||||
continue_listing(cur_list->pg->lst);
|
||||
};
|
||||
msgr.outbox_push(op);
|
||||
msgr->outbox_push(op);
|
||||
}
|
||||
|
||||
void cluster_client_t::finish_list_pg(inode_list_pg_t *pg, bool retry_epipe)
|
||||
@@ -434,7 +447,7 @@ void cluster_client_t::finish_list_pg(inode_list_pg_t *pg, bool retry_epipe)
|
||||
auto lst = pg->lst;
|
||||
if (pg->inflight_ops == 0)
|
||||
{
|
||||
if (pg->errcode == -EPIPE && retry_epipe)
|
||||
if ((pg->errcode == -EPIPE || pg->errcode == -EAGAIN) && retry_epipe)
|
||||
{
|
||||
// Retry listing after <client_retry_interval> ms on EPIPE
|
||||
pg->state = LIST_PG_WAIT_RETRY;
|
||||
|
||||
@@ -92,14 +92,19 @@ void cluster_client_t::vault_load_keys()
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (vault_url.empty())
|
||||
{
|
||||
fatal_error(EINVAL, "Vault URL is missing");
|
||||
return;
|
||||
}
|
||||
if (!vault_http_ctx)
|
||||
{
|
||||
std::string error;
|
||||
vault_http_ctx = http_context_init(tfd, vault_client_cert, vault_client_key, vault_ca, true, error);
|
||||
if (!vault_http_ctx)
|
||||
{
|
||||
fprintf(stderr, "Failed to initialize HTTP context for Vault: %s\n", error.c_str());
|
||||
exit(1);
|
||||
fatal_error(EINVAL, "Failed to initialize HTTP context for Vault: "+error);
|
||||
return;
|
||||
}
|
||||
vault_http_cli = http_init(vault_http_ctx);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
// Copyright (c) Vitaliy Filippov, 2019+
|
||||
// License: VNPL-1.1 or GNU GPL-2.0+ (see README.md for details)
|
||||
|
||||
#include <cassert>
|
||||
#undef NDEBUG
|
||||
#include <assert.h>
|
||||
|
||||
#include "cluster_client_impl.h"
|
||||
|
||||
@@ -92,6 +93,7 @@ void writeback_cache_t::copy_write(cluster_op_t *op, int state, uint64_t new_flu
|
||||
// approaches and fix everything accordingly when I decide to implement TRIM.
|
||||
return;
|
||||
}
|
||||
small_vector_t<osd_num_t, 4> was_written_to;
|
||||
auto dirty_it = find_dirty(op->inode, op->offset);
|
||||
auto new_end = op->offset + op->len;
|
||||
while (dirty_it != dirty_buffers.end() &&
|
||||
@@ -99,6 +101,11 @@ void writeback_cache_t::copy_write(cluster_op_t *op, int state, uint64_t new_flu
|
||||
dirty_it->first.stripe < op->offset+op->len)
|
||||
{
|
||||
assert(dirty_it->first.stripe + dirty_it->second.len > op->offset);
|
||||
for (auto osd_num: dirty_it->second.written_to_osd)
|
||||
{
|
||||
if (std::find(was_written_to.begin(), was_written_to.end(), osd_num) == was_written_to.end())
|
||||
was_written_to.push_back(osd_num);
|
||||
}
|
||||
// Remove overlapping part(s) of buffers
|
||||
auto old_end = dirty_it->first.stripe + dirty_it->second.len;
|
||||
if (dirty_it->first.stripe < op->offset)
|
||||
@@ -116,6 +123,7 @@ void writeback_cache_t::copy_write(cluster_op_t *op, int state, uint64_t new_flu
|
||||
.state = dirty_it->second.state,
|
||||
.flush_id = dirty_it->second.flush_id,
|
||||
.refcnt = dirty_it->second.refcnt,
|
||||
.written_to_osd = dirty_it->second.written_to_osd,
|
||||
});
|
||||
if (dirty_it->second.buf)
|
||||
{
|
||||
@@ -174,6 +182,7 @@ void writeback_cache_t::copy_write(cluster_op_t *op, int state, uint64_t new_flu
|
||||
.state = dirty_it->second.state,
|
||||
.flush_id = dirty_it->second.flush_id,
|
||||
.refcnt = dirty_it->second.refcnt,
|
||||
.written_to_osd = dirty_it->second.written_to_osd,
|
||||
});
|
||||
dirty_buffers.erase(dirty_it);
|
||||
dirty_it = new_dirty_it;
|
||||
@@ -224,6 +233,7 @@ void writeback_cache_t::copy_write(cluster_op_t *op, int state, uint64_t new_flu
|
||||
.state = state,
|
||||
.flush_id = new_flush_id,
|
||||
.refcnt = refcnt,
|
||||
.written_to_osd = std::move(was_written_to),
|
||||
});
|
||||
if (state == CACHE_DIRTY)
|
||||
{
|
||||
@@ -262,7 +272,7 @@ void writeback_cache_t::copy_write(cluster_op_t *op, int state, uint64_t new_flu
|
||||
}
|
||||
}
|
||||
|
||||
int writeback_cache_t::repeat_ops_for(cluster_client_t *cli, osd_num_t peer_osd, pool_id_t pool_id, pg_num_t pg_num)
|
||||
int writeback_cache_t::repeat_ops_for(cluster_client_t *cli, osd_num_t peer_osd)
|
||||
{
|
||||
int repeated = 0;
|
||||
if (dirty_buffers.size())
|
||||
@@ -272,11 +282,10 @@ int writeback_cache_t::repeat_ops_for(cluster_client_t *cli, osd_num_t peer_osd,
|
||||
for (auto wr_it = dirty_buffers.begin(), flush_it = wr_it, last_it = wr_it; ; )
|
||||
{
|
||||
bool end = wr_it == dirty_buffers.end();
|
||||
bool flush_this = !end && wr_it->second.state != CACHE_REPEATING && wr_it->second.state != CACHE_DIRTY;
|
||||
if (peer_osd)
|
||||
flush_this = flush_this && cli->affects_osd(wr_it->first.inode, wr_it->first.stripe, wr_it->second.len, peer_osd);
|
||||
if (pool_id && pg_num)
|
||||
flush_this = flush_this && cli->affects_pg(wr_it->first.inode, wr_it->first.stripe, wr_it->second.len, pool_id, pg_num);
|
||||
auto & wr_to = wr_it->second.written_to_osd;
|
||||
bool flush_this = std::find(wr_to.begin(), wr_to.end(), peer_osd) != wr_to.end();
|
||||
if (flush_this)
|
||||
wr_to.clear();
|
||||
if (flush_it != wr_it && (end || !flush_this ||
|
||||
wr_it->first.inode != flush_it->first.inode ||
|
||||
wr_it->first.stripe != last_it->first.stripe+last_it->second.len))
|
||||
@@ -308,28 +317,28 @@ void writeback_cache_t::flush_buffers(cluster_client_t *cli, dirty_buf_it_t from
|
||||
op->offset = from_it->first.stripe;
|
||||
op->len = prev_it->first.stripe + prev_it->second.len - from_it->first.stripe;
|
||||
uint32_t calc_len = 0;
|
||||
uint64_t flush_id = ++last_flush_id;
|
||||
op->flush_id = ++last_flush_id;
|
||||
for (auto it = from_it; it != to_it; it++)
|
||||
{
|
||||
it->second.state = CACHE_REPEATING;
|
||||
it->second.flush_id = flush_id;
|
||||
it->second.flush_id = op->flush_id;
|
||||
if (it->second.buf)
|
||||
{
|
||||
(*it->second.refcnt)++;
|
||||
flushed_buffers.emplace(flush_id, it->second.refcnt);
|
||||
flushed_buffers.emplace(op->flush_id, it->second.refcnt);
|
||||
op->iov.push_back(it->second.buf, it->second.len);
|
||||
}
|
||||
calc_len += it->second.len;
|
||||
}
|
||||
assert(calc_len == op->len);
|
||||
writebacks_active++;
|
||||
op->callback = [this, flush_id](cluster_op_t* op)
|
||||
op->callback = [this](cluster_op_t* op)
|
||||
{
|
||||
// Buffer flushes are always retried, regardless of the error,
|
||||
// so they should never result in an error here
|
||||
assert(op->retval == op->len);
|
||||
for (auto fl_it = flushed_buffers.find(flush_id);
|
||||
fl_it != flushed_buffers.end() && fl_it->first == flush_id; )
|
||||
assert(op->retval == op->len || parent->aborted);
|
||||
for (auto fl_it = flushed_buffers.lower_bound(op->flush_id);
|
||||
fl_it != flushed_buffers.end() && fl_it->first == op->flush_id; )
|
||||
{
|
||||
if (!--(*fl_it->second)) // refcnt
|
||||
{
|
||||
@@ -339,11 +348,7 @@ void writeback_cache_t::flush_buffers(cluster_client_t *cli, dirty_buf_it_t from
|
||||
}
|
||||
if (op->flags & OP_IMMEDIATE_COMMIT)
|
||||
{
|
||||
delete_flush(op->inode, op->offset, op->len, flush_id);
|
||||
}
|
||||
else
|
||||
{
|
||||
mark_flush_written(op->inode, op->offset, op->len, flush_id);
|
||||
delete_flush(op->inode, op->offset, op->len, op->flush_id);
|
||||
}
|
||||
delete op;
|
||||
writebacks_active--;
|
||||
@@ -395,6 +400,21 @@ void writeback_cache_t::mark_flush_written(uint64_t inode, uint64_t offset, uint
|
||||
}
|
||||
}
|
||||
|
||||
void writeback_cache_t::mark_flush_written_to(uint64_t inode, uint64_t offset, uint64_t len, uint64_t flush_id, osd_num_t osd_num)
|
||||
{
|
||||
for (auto dirty_it = find_dirty(inode, offset);
|
||||
dirty_it != dirty_buffers.end() && dirty_it->first.inode == inode &&
|
||||
dirty_it->first.stripe < offset+len; dirty_it++)
|
||||
{
|
||||
if (dirty_it->second.flush_id == flush_id && dirty_it->second.state == CACHE_REPEATING)
|
||||
{
|
||||
auto & wr_to = dirty_it->second.written_to_osd;
|
||||
if (std::find(wr_to.begin(), wr_to.end(), osd_num) == wr_to.end())
|
||||
wr_to.push_back(osd_num);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void writeback_cache_t::start_writebacks(cluster_client_t *cli, int count)
|
||||
{
|
||||
if (!writeback_queue.size())
|
||||
|
||||
@@ -10,6 +10,19 @@
|
||||
#include "str_util.h"
|
||||
#include "json_util.h"
|
||||
|
||||
void etcd_state_client_t::fatal_error(int errcode, const std::string & error)
|
||||
{
|
||||
if (on_fatal_error_hook)
|
||||
{
|
||||
(std::function<void(int, const std::string&)>(on_fatal_error_hook))(errcode, error);
|
||||
}
|
||||
else
|
||||
{
|
||||
fprintf(stderr, "Error: %s\n", error.c_str());
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
etcd_state_client_t::~etcd_state_client_t()
|
||||
{
|
||||
for (auto watch: watches)
|
||||
@@ -333,7 +346,7 @@ void etcd_state_client_t::load_pgs(std::function<void(const std::string &)> cb)
|
||||
return;
|
||||
}
|
||||
reset_pg_exists();
|
||||
etcd_watch_revision_config = etcd_watch_revision_osd = etcd_watch_revision_pg = data["header"]["revision"].uint64_value()+1;
|
||||
etcd_watch_revision_config = etcd_watch_revision_osd = etcd_watch_revision_pg = data["header"]["revision"].uint64_value();
|
||||
if (this->log_level > 3)
|
||||
{
|
||||
fprintf(stderr, "Loaded revision %ju of PG configuration\n", etcd_watch_revision_pg-1);
|
||||
|
||||
@@ -144,6 +144,7 @@ protected:
|
||||
std::set<osd_num_t> seen_peers;
|
||||
bool new_pg_config = false;
|
||||
|
||||
void fatal_error(int errcode, const std::string & error);
|
||||
void add_etcd_url(std::string);
|
||||
void reset_pg_exists();
|
||||
void clean_nonexistent_pgs();
|
||||
@@ -159,7 +160,7 @@ public:
|
||||
uint32_t global_bitmap_granularity = DEFAULT_BITMAP_GRANULARITY;
|
||||
uint32_t global_immediate_commit = IMMEDIATE_NONE;
|
||||
|
||||
uint64_t osd_num = 0;
|
||||
osd_num_t osd_num = 0;
|
||||
std::string etcd_prefix;
|
||||
std::string etcd_client_cert;
|
||||
std::string etcd_client_key;
|
||||
@@ -192,6 +193,7 @@ public:
|
||||
std::function<void()> on_reload_hook;
|
||||
std::function<void(inode_t, bool)> on_inode_change_hook;
|
||||
std::function<void(http_co_t *)> on_start_watcher_hook;
|
||||
std::function<void(int, const std::string&)> on_fatal_error_hook;
|
||||
|
||||
json11::Json::object serialize_inode_cfg(inode_config_t *cfg);
|
||||
inode_config_t deserialize_inode_cfg(uint64_t inode_num, json11::Json value, uint64_t mod_revision);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// Copyright (c) Vitaliy Filippov, 2019+
|
||||
// License: VNPL-1.1 or GNU GPL-2.0+ (see README.md for details)
|
||||
|
||||
#undef NDEBUG
|
||||
#include <assert.h>
|
||||
#include "etcd_state_client_http.h"
|
||||
#include "addr_util.h"
|
||||
@@ -30,6 +31,11 @@ etcd_state_client_http_t::~etcd_state_client_http_t()
|
||||
tfd->clear_timer(load_pgs_timer_id);
|
||||
load_pgs_timer_id = -1;
|
||||
}
|
||||
for (int timer_id: timers)
|
||||
{
|
||||
tfd->clear_timer(timer_id);
|
||||
}
|
||||
timers.clear();
|
||||
if (http_ctx)
|
||||
{
|
||||
http_context_destroy(http_ctx);
|
||||
@@ -48,7 +54,11 @@ void etcd_state_client_http_t::etcd_add_watch(json11::Json watch)
|
||||
|
||||
std::string etcd_state_client_http_t::get_username()
|
||||
{
|
||||
return http_context_get_ssl_cn(get_http_ctx());
|
||||
if (!get_http_ctx())
|
||||
{
|
||||
return "";
|
||||
}
|
||||
return http_context_get_ssl_cn(http_ctx);
|
||||
}
|
||||
|
||||
http_context_t *etcd_state_client_http_t::get_http_ctx()
|
||||
@@ -59,8 +69,7 @@ http_context_t *etcd_state_client_http_t::get_http_ctx()
|
||||
http_ctx = http_context_init(tfd, etcd_client_cert, etcd_client_key, etcd_ca, true, error);
|
||||
if (!http_ctx)
|
||||
{
|
||||
fprintf(stderr, "Failed to initialize HTTP context: %s\n", error.c_str());
|
||||
exit(1);
|
||||
fatal_error(EINVAL, "Failed to initialize HTTP context: "+error);
|
||||
}
|
||||
}
|
||||
return http_ctx;
|
||||
@@ -69,7 +78,11 @@ http_context_t *etcd_state_client_http_t::get_http_ctx()
|
||||
void etcd_state_client_http_t::etcd_call_oneshot(const std::string & etcd_url, const std::string & api, json11::Json payload,
|
||||
int timeout, std::function<void(std::string, json11::Json)> callback)
|
||||
{
|
||||
auto http_cli = http_init(get_http_ctx());
|
||||
if (!get_http_ctx())
|
||||
{
|
||||
return;
|
||||
}
|
||||
auto http_cli = http_init(http_ctx);
|
||||
http_json_post(http_cli, etcd_url+api, payload, "", { .timeout = timeout }, [http_cli, callback](http_message_t *response)
|
||||
{
|
||||
std::string err;
|
||||
@@ -92,7 +105,29 @@ void etcd_state_client_http_t::etcd_call(const std::string & api, json11::Json p
|
||||
void etcd_state_client_http_t::etcd_call_selected(const std::string & api, json11::Json payload, int timeout,
|
||||
int retries, int interval, std::function<void(std::string, json11::Json)> callback)
|
||||
{
|
||||
retries--;
|
||||
const auto & url = selected_etcd_url;
|
||||
if (url.addr.empty())
|
||||
{
|
||||
// Resolving failed
|
||||
if (retries > 0)
|
||||
{
|
||||
if (log_level > 0)
|
||||
{
|
||||
fprintf(stderr, "Warning: etcd request failed, retrying %d more times\n", retries);
|
||||
}
|
||||
timers.insert(tfd->set_timer(interval < 500 ? 500 : interval, false, [this, api, payload, timeout, retries, interval, callback](int timer_id)
|
||||
{
|
||||
timers.erase(timer_id);
|
||||
etcd_call(api, payload, timeout, retries, interval, callback);
|
||||
}));
|
||||
}
|
||||
else
|
||||
{
|
||||
callback("None of etcd addresses could be resolved", json11::Json());
|
||||
}
|
||||
return;
|
||||
}
|
||||
std::string req = payload.dump();
|
||||
req = "POST "+url.path+api+" HTTP/1.1\r\n"
|
||||
"Host: "+url.hostname+"\r\n"
|
||||
@@ -101,7 +136,6 @@ void etcd_state_client_http_t::etcd_call_selected(const std::string & api, json1
|
||||
"Connection: keep-alive\r\n"
|
||||
"Keep-Alive: timeout="+std::to_string(etcd_keepalive_timeout)+"\r\n"
|
||||
"\r\n"+req;
|
||||
retries--;
|
||||
auto cb = [this, api, payload, timeout, retries, interval, callback,
|
||||
cur_addr = url.addr](http_message_t *response)
|
||||
{
|
||||
@@ -123,11 +157,11 @@ void etcd_state_client_http_t::etcd_call_selected(const std::string & api, json1
|
||||
}
|
||||
if (interval > 0)
|
||||
{
|
||||
// FIXME: Prevent destruction of etcd_state_client if timers or requests are active
|
||||
tfd->set_timer(interval, false, [this, api, payload, timeout, retries, interval, callback](int)
|
||||
timers.insert(tfd->set_timer(interval, false, [this, api, payload, timeout, retries, interval, callback](int timer_id)
|
||||
{
|
||||
timers.erase(timer_id);
|
||||
etcd_call(api, payload, timeout, retries, interval, callback);
|
||||
});
|
||||
}));
|
||||
}
|
||||
else
|
||||
etcd_call(api, payload, timeout, retries, interval, callback);
|
||||
@@ -139,7 +173,11 @@ void etcd_state_client_http_t::etcd_call_selected(const std::string & api, json1
|
||||
callback(err, data);
|
||||
};
|
||||
if (!keepalive_client)
|
||||
keepalive_client = http_init(get_http_ctx());
|
||||
{
|
||||
if (!get_http_ctx())
|
||||
return;
|
||||
keepalive_client = http_init(http_ctx);
|
||||
}
|
||||
http_request(keepalive_client, url.addr, req, { .timeout = timeout, .keepalive = true, .ssl = url.ssl }, cb);
|
||||
}
|
||||
|
||||
@@ -152,14 +190,24 @@ void etcd_state_client_http_t::parse_config(const json11::Json & config)
|
||||
stop_ws_keepalive();
|
||||
start_ws_keepalive();
|
||||
}
|
||||
if (!etcd_addresses.size() && !etcd_local.size())
|
||||
{
|
||||
fatal_error(EINVAL, "etcd_address is missing in Vitastor configuration");
|
||||
return;
|
||||
}
|
||||
get_http_ctx();
|
||||
}
|
||||
|
||||
void etcd_state_client_http_t::pick_next_etcd(std::function<void()> cb)
|
||||
{
|
||||
if (!etcd_addresses.size() && !etcd_local.size())
|
||||
{
|
||||
fprintf(stderr, "etcd_address is missing in Vitastor configuration\n");
|
||||
exit(1);
|
||||
fatal_error(EINVAL, "etcd_address is missing in Vitastor configuration");
|
||||
return;
|
||||
}
|
||||
if (!get_http_ctx())
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (selected_etcd_url.addr != "")
|
||||
{
|
||||
@@ -195,7 +243,7 @@ void etcd_state_client_http_t::pick_next_etcd(std::function<void()> cb)
|
||||
for (auto & url: etcd_name_urls)
|
||||
{
|
||||
resolve_count++;
|
||||
http_resolve(get_http_ctx(), url.ssl, url.addr, [this, url](const std::string & error, const std::vector<std::string>& addresses)
|
||||
http_resolve(http_ctx, url.ssl, url.addr, [this, url](const std::string & error, const std::vector<std::string>& addresses)
|
||||
{
|
||||
if (error != "")
|
||||
fprintf(stderr, "Error resolving %s: %s\n", url.addr.c_str(), error.c_str());
|
||||
@@ -227,8 +275,13 @@ void etcd_state_client_http_t::pick_next_etcd_on_resolve()
|
||||
{
|
||||
if (!etcd_urls_to_try.size())
|
||||
{
|
||||
fprintf(stderr, "None of etcd_address could be resolved\n");
|
||||
exit(1);
|
||||
selected_etcd_url = {};
|
||||
auto cbs = std::move(on_resolve_queue);
|
||||
for (auto cb: cbs)
|
||||
{
|
||||
cb();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!rand_initialized)
|
||||
{
|
||||
@@ -265,6 +318,16 @@ void etcd_state_client_http_t::start_etcd_watcher_selected()
|
||||
{
|
||||
const auto & url = selected_etcd_url;
|
||||
etcd_watches_initialised = 0;
|
||||
if (url.addr.empty())
|
||||
{
|
||||
// Resolving failed, retry in <etcd_slow_timeout>
|
||||
timers.insert(tfd->set_timer(etcd_slow_timeout, false, [this](int timer_id)
|
||||
{
|
||||
timers.erase(timer_id);
|
||||
start_etcd_watcher();
|
||||
}));
|
||||
return;
|
||||
}
|
||||
ws_alive = 1;
|
||||
if (this->log_level > 1)
|
||||
{
|
||||
@@ -273,7 +336,11 @@ void etcd_state_client_http_t::start_etcd_watcher_selected()
|
||||
etcd_watch_revision_config, etcd_watch_revision_osd, etcd_watch_revision_pg);
|
||||
}
|
||||
if (!etcd_watch_ws)
|
||||
etcd_watch_ws = http_init(get_http_ctx());
|
||||
{
|
||||
if (!get_http_ctx())
|
||||
return;
|
||||
etcd_watch_ws = http_init(http_ctx);
|
||||
}
|
||||
else
|
||||
http_close(etcd_watch_ws);
|
||||
open_websocket(etcd_watch_ws, url.addr, url.hostname, url.path+"/watch", { .timeout = etcd_slow_timeout, .ssl = url.ssl },
|
||||
@@ -323,20 +390,17 @@ void etcd_state_client_http_t::start_etcd_watcher_selected()
|
||||
etcd_watch_revision_config = etcd_watch_revision_osd = etcd_watch_revision_pg = 0;
|
||||
on_reload_hook();
|
||||
}
|
||||
return;
|
||||
}
|
||||
else
|
||||
{
|
||||
fprintf(stderr, "Revisions before %ju were compacted by etcd, exiting\n",
|
||||
data["result"]["compact_revision"].uint64_value());
|
||||
exit(1);
|
||||
fatal_error(EIO, "Revisions before "+data["result"]["compact_revision"].as_string()+" were compacted by etcd, exiting");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
fprintf(stderr, "Watch canceled by etcd, reason: %s, exiting\n", data["result"]["cancel_reason"].string_value().c_str());
|
||||
exit(1);
|
||||
fatal_error(EIO, "Watch canceled by etcd, reason: "+data["result"]["cancel_reason"].string_value()+", exiting");
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Save revision only if it's present in the message - because sometimes etcd sends something without a header, like:
|
||||
// {"error": {"grpc_code": 14, "http_code": 503, "http_status": "Service Unavailable", "message": "error reading from server: EOF"}}
|
||||
@@ -399,10 +463,11 @@ void etcd_state_client_http_t::start_etcd_watcher_selected()
|
||||
if (etcd_watches_initialised == 0)
|
||||
{
|
||||
// Connection not established, retry in <etcd_quick_timeout>
|
||||
tfd->set_timer(etcd_quick_timeout, false, [this](int)
|
||||
timers.insert(tfd->set_timer(etcd_quick_timeout, false, [this](int timer_id)
|
||||
{
|
||||
timers.erase(timer_id);
|
||||
start_etcd_watcher();
|
||||
});
|
||||
}));
|
||||
}
|
||||
else if (etcd_watches_initialised > 0)
|
||||
{
|
||||
@@ -491,17 +556,18 @@ void etcd_state_client_http_t::load_global_config()
|
||||
{
|
||||
if (err != "")
|
||||
{
|
||||
fprintf(stderr, "Error reading configuration from etcd: %s\n", err.c_str());
|
||||
if (infinite_start)
|
||||
{
|
||||
tfd->set_timer(etcd_slow_timeout, false, [this](int timer_id)
|
||||
fprintf(stderr, "Failed to read configuration from etcd: %s\n", err.c_str());
|
||||
timers.insert(tfd->set_timer(etcd_slow_timeout, false, [this](int timer_id)
|
||||
{
|
||||
timers.erase(timer_id);
|
||||
load_global_config();
|
||||
});
|
||||
}));
|
||||
}
|
||||
else
|
||||
{
|
||||
exit(1);
|
||||
fatal_error(EIO, "Failed to read configuration from etcd: "+err);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -532,10 +598,11 @@ void etcd_state_client_http_t::load_pgs()
|
||||
{
|
||||
// Retry indefinitely
|
||||
fprintf(stderr, "Error loading PGs from etcd: %s\n", err.c_str());
|
||||
tfd->set_timer(etcd_slow_timeout, false, [this](int timer_id)
|
||||
timers.insert(tfd->set_timer(etcd_slow_timeout, false, [this](int timer_id)
|
||||
{
|
||||
timers.erase(timer_id);
|
||||
load_pgs();
|
||||
});
|
||||
}));
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
@@ -22,6 +22,7 @@ protected:
|
||||
http_context_t *http_ctx = NULL;
|
||||
size_t local_to_try = 0;
|
||||
std::vector<http_url_t> etcd_urls_to_try;
|
||||
std::set<int> timers;
|
||||
http_url_t selected_etcd_url;
|
||||
size_t resolve_count = 0;
|
||||
std::vector<std::function<void()>> on_resolve_queue;
|
||||
|
||||
@@ -1,86 +1,84 @@
|
||||
// Copyright (c) Vitaliy Filippov, 2019+
|
||||
// License: VNPL-1.1 or GNU GPL-2.0+ (see README.md for details)
|
||||
|
||||
#undef NDEBUG
|
||||
#include <assert.h>
|
||||
#include "etcd_state_client_mock.h"
|
||||
#include "str_util.h"
|
||||
#include "ringloop.h"
|
||||
|
||||
etcd_state_client_mock_t::etcd_state_client_mock_t()
|
||||
etcd_mock_t::etcd_mock_t()
|
||||
{
|
||||
timespec tv;
|
||||
clock_gettime(CLOCK_REALTIME, &tv);
|
||||
srand48(tv.tv_sec*1000000000 + tv.tv_nsec);
|
||||
}
|
||||
|
||||
void etcd_state_client_mock_t::etcd_add_watch(json11::Json watch)
|
||||
void etcd_mock_t::register_client(etcd_state_client_mock_t *client)
|
||||
{
|
||||
clients.push_back(client);
|
||||
}
|
||||
|
||||
std::string etcd_state_client_mock_t::get_username()
|
||||
void etcd_mock_t::unregister_client(etcd_state_client_mock_t *client)
|
||||
{
|
||||
return username;
|
||||
}
|
||||
|
||||
void etcd_state_client_mock_t::etcd_call_oneshot(const std::string & etcd_address, const std::string & api, json11::Json payload,
|
||||
int timeout, std::function<void(std::string, json11::Json)> callback)
|
||||
{
|
||||
}
|
||||
|
||||
void etcd_state_client_mock_t::pause()
|
||||
{
|
||||
paused = true;
|
||||
}
|
||||
|
||||
void etcd_state_client_mock_t::resume(size_t n)
|
||||
{
|
||||
std::vector<etcd_mock_request_t> ran;
|
||||
if (!n)
|
||||
for (size_t i = 0; i < clients.size(); i++)
|
||||
{
|
||||
paused = false;
|
||||
ran = std::move(queue);
|
||||
if (clients[i] == client)
|
||||
{
|
||||
clients.erase(clients.begin() + i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void etcd_mock_t::notify(std::map<std::string, etcd_kv_t> & changes)
|
||||
{
|
||||
if (ringloop)
|
||||
{
|
||||
// Copy: the caller's map may be gone by the time the ringloop gets here
|
||||
ringloop->set_immediate([this, changes]() mutable { notify_now(changes); });
|
||||
}
|
||||
else if (n >= queue.size())
|
||||
ran = std::move(queue);
|
||||
else
|
||||
notify_now(changes);
|
||||
}
|
||||
|
||||
void etcd_mock_t::notify_now(std::map<std::string, etcd_kv_t> & changes)
|
||||
{
|
||||
auto clients_copy = clients;
|
||||
for (auto & client: clients_copy)
|
||||
{
|
||||
for (size_t i = 0; i < n; i++)
|
||||
queue.push_back(std::move(queue[i]));
|
||||
queue.erase(queue.begin(), queue.begin() + n);
|
||||
}
|
||||
for (auto& req: ran)
|
||||
{
|
||||
etcd_call_nopause(req.api, req.payload, req.timeout, req.retries, req.interval, req.callback);
|
||||
client->mock_apply_changes(changes);
|
||||
}
|
||||
}
|
||||
|
||||
void etcd_state_client_mock_t::set(const std::string& key, json11::Json data, uint64_t mod_revision, uint64_t lease_id)
|
||||
void etcd_mock_t::deliver(std::function<void(std::string, json11::Json)> cb, std::string err, json11::Json res)
|
||||
{
|
||||
if (ringloop)
|
||||
{
|
||||
ringloop->set_immediate([cb, err, res]() { cb(err, res); });
|
||||
}
|
||||
else
|
||||
cb(err, res);
|
||||
}
|
||||
|
||||
void etcd_mock_t::set(const std::string& key, const std::string& value, uint64_t mod_revision, uint64_t lease_id)
|
||||
{
|
||||
if (!mod_revision)
|
||||
mod_revision = ++this->mod_revision;
|
||||
this->data[key] = (etcd_mock_key_data_t){ .value = data.dump(), .mod_revision = mod_revision, .lease_id = lease_id };
|
||||
etcd_kv_t kv = (etcd_kv_t){ .key = key, .value = data, .mod_revision = mod_revision };
|
||||
parse_state(kv);
|
||||
if (on_change_hook != NULL)
|
||||
this->data[key] = (etcd_mock_key_data_t){ .value = value, .mod_revision = mod_revision, .lease_id = lease_id };
|
||||
std::string err;
|
||||
json11::Json json_value = json11::Json::parse(value, err);
|
||||
if (err != "")
|
||||
{
|
||||
std::map<std::string, etcd_kv_t> changes;
|
||||
changes[key] = std::move(kv);
|
||||
on_change_hook(changes);
|
||||
fprintf(stderr, "Invalid JSON in etcd key %s during test: %s\n", key.c_str(), value.c_str());
|
||||
exit(1);
|
||||
}
|
||||
std::map<std::string, etcd_kv_t> changes;
|
||||
changes[key] = { .key = key, .value = json_value, .mod_revision = mod_revision };
|
||||
notify(changes);
|
||||
}
|
||||
|
||||
void etcd_state_client_mock_t::etcd_call(const std::string & api, json11::Json payload, int timeout,
|
||||
int retries, int interval, std::function<void(std::string, json11::Json)> callback)
|
||||
{
|
||||
if (paused)
|
||||
{
|
||||
queue.push_back({ api, payload, timeout, retries, interval, callback });
|
||||
return;
|
||||
}
|
||||
etcd_call_nopause(api, payload, timeout, retries, interval, callback);
|
||||
}
|
||||
|
||||
void etcd_state_client_mock_t::etcd_call_nopause(std::string api, json11::Json payload, int timeout,
|
||||
int retries, int interval, std::function<void(std::string, json11::Json)> callback)
|
||||
void etcd_mock_t::etcd_call(const std::string & api, json11::Json payload, std::function<void(std::string, json11::Json)> callback, etcd_state_client_mock_t *from)
|
||||
{
|
||||
printf("+ etcd: %s\n", api.c_str());
|
||||
if (api == "/kv/txn")
|
||||
@@ -201,28 +199,141 @@ void etcd_state_client_mock_t::etcd_call_nopause(std::string api, json11::Json p
|
||||
});
|
||||
}
|
||||
}
|
||||
callback("", json11::Json::object{
|
||||
deliver(callback, "", json11::Json::object{
|
||||
{ "header", json11::Json::object{ { "revision", mod_revision } } },
|
||||
{ "succeeded", ok },
|
||||
{ "responses", responses }
|
||||
});
|
||||
// Push changes to watcher
|
||||
// Deliver changes to the other clients' views, like an etcd watch
|
||||
if (changes.size())
|
||||
notify(changes);
|
||||
}
|
||||
else if (api == "/kv/lease/revoke")
|
||||
{
|
||||
// An OSD going down takes its keys with it, like in real etcd
|
||||
uint64_t lease_id = strtoull(payload["ID"].string_value().c_str(), NULL, 10);
|
||||
for (auto it = data.begin(); it != data.end(); )
|
||||
{
|
||||
for (auto & kv: changes)
|
||||
parse_state(kv.second);
|
||||
if (on_change_hook != NULL)
|
||||
on_change_hook(changes);
|
||||
if (it->second.lease_id == lease_id)
|
||||
data.erase(it++);
|
||||
else
|
||||
it++;
|
||||
}
|
||||
leases.erase(lease_id);
|
||||
deliver(callback, "", json11::Json::object{
|
||||
{ "header", json11::Json::object{ { "revision", mod_revision } } }
|
||||
});
|
||||
}
|
||||
else if (api == "/lease/grant")
|
||||
{
|
||||
uint64_t lease_id = (((uint64_t)lrand48()) << 32) | lrand48();
|
||||
leases[lease_id] = payload["TTL"].uint64_value();
|
||||
callback("", json11::Json::object{ { "ID", std::to_string(lease_id) } });
|
||||
deliver(callback, "", json11::Json::object{ { "ID", std::to_string(lease_id) } });
|
||||
}
|
||||
else if (api == "/lease/keepalive")
|
||||
{
|
||||
// A lease never expires in the mock; a TTL of 0 would kill the OSD
|
||||
uint64_t lease_id = payload["ID"].uint64_value();
|
||||
std::string lid = payload["ID"].string_value();
|
||||
if (lid != "")
|
||||
lease_id = strtoull(lid.c_str(), NULL, 10);
|
||||
uint64_t ttl = leases.find(lease_id) != leases.end() ? leases[lease_id] : 0;
|
||||
deliver(callback, "", json11::Json::object{ { "result", json11::Json::object{ { "TTL", (double)ttl } } } });
|
||||
}
|
||||
else
|
||||
callback("Unsupported", json11::Json());
|
||||
deliver(callback, "Unsupported", json11::Json());
|
||||
}
|
||||
|
||||
etcd_state_client_mock_t::etcd_state_client_mock_t(etcd_mock_t & store)
|
||||
{
|
||||
this->store = &store;
|
||||
store.register_client(this);
|
||||
}
|
||||
|
||||
etcd_state_client_mock_t::~etcd_state_client_mock_t()
|
||||
{
|
||||
store->unregister_client(this);
|
||||
}
|
||||
|
||||
void etcd_state_client_mock_t::etcd_add_watch(json11::Json watch)
|
||||
{
|
||||
}
|
||||
|
||||
std::string etcd_state_client_mock_t::get_username()
|
||||
{
|
||||
return username;
|
||||
}
|
||||
|
||||
void etcd_state_client_mock_t::etcd_call_oneshot(const std::string & etcd_address, const std::string & api, json11::Json payload,
|
||||
int timeout, std::function<void(std::string, json11::Json)> callback)
|
||||
{
|
||||
}
|
||||
|
||||
void etcd_state_client_mock_t::pause()
|
||||
{
|
||||
paused = true;
|
||||
}
|
||||
|
||||
void etcd_state_client_mock_t::resume(size_t n)
|
||||
{
|
||||
std::vector<etcd_mock_request_t> ran;
|
||||
if (!n)
|
||||
{
|
||||
paused = false;
|
||||
ran = std::move(queue);
|
||||
}
|
||||
else if (n >= queue.size())
|
||||
ran = std::move(queue);
|
||||
else
|
||||
{
|
||||
for (size_t i = 0; i < n; i++)
|
||||
ran.push_back(std::move(queue[i]));
|
||||
queue.erase(queue.begin(), queue.begin() + n);
|
||||
}
|
||||
for (auto& req: ran)
|
||||
{
|
||||
etcd_call_nopause(req.api, req.payload, req.timeout, req.retries, req.interval, req.callback);
|
||||
}
|
||||
}
|
||||
|
||||
void etcd_state_client_mock_t::set(const std::string& key, json11::Json data, uint64_t mod_revision, uint64_t lease_id)
|
||||
{
|
||||
store->set(key, data.dump(), mod_revision, lease_id);
|
||||
}
|
||||
|
||||
void etcd_state_client_mock_t::etcd_call(const std::string & api, json11::Json payload, int timeout,
|
||||
int retries, int interval, std::function<void(std::string, json11::Json)> callback)
|
||||
{
|
||||
if (paused)
|
||||
{
|
||||
queue.push_back({ api, payload, timeout, retries, interval, callback });
|
||||
return;
|
||||
}
|
||||
etcd_call_nopause(api, payload, timeout, retries, interval, callback);
|
||||
}
|
||||
|
||||
void etcd_state_client_mock_t::etcd_call_nopause(std::string api, json11::Json payload, int timeout,
|
||||
int retries, int interval, std::function<void(std::string, json11::Json)> callback)
|
||||
{
|
||||
store->etcd_call(api, payload, callback, this);
|
||||
}
|
||||
|
||||
void etcd_state_client_mock_t::mock_apply_changes(std::map<std::string, etcd_kv_t> & changes)
|
||||
{
|
||||
for (auto & kv: changes)
|
||||
parse_state(kv.second);
|
||||
// A real client can't react to any change before its load finished: the
|
||||
// watch starts after the range read. Stash changes until then, otherwise
|
||||
// the OSD applies half-loaded configs (PGs start with epoch 0 and write a
|
||||
// reset epoch back into etcd, clobbering the real one)
|
||||
for (auto & kv: changes)
|
||||
pending_changes[kv.first] = kv.second;
|
||||
if (!pgs_loaded)
|
||||
return;
|
||||
auto pending = std::move(pending_changes);
|
||||
pending_changes.clear();
|
||||
if (pending.size() && on_change_hook != NULL)
|
||||
on_change_hook(pending);
|
||||
}
|
||||
|
||||
void etcd_state_client_mock_t::load_global_config()
|
||||
@@ -232,5 +343,18 @@ void etcd_state_client_mock_t::load_global_config()
|
||||
|
||||
void etcd_state_client_mock_t::load_pgs()
|
||||
{
|
||||
etcd_state_client_t::load_pgs([this](const std::string & err) {});
|
||||
etcd_state_client_t::load_pgs([this](const std::string & err)
|
||||
{
|
||||
pgs_loaded = true;
|
||||
// The range read already contains everything up to the load revision;
|
||||
// replay only the newer changes, like a watch would from that revision
|
||||
auto pending = std::move(pending_changes);
|
||||
pending_changes.clear();
|
||||
std::map<std::string, etcd_kv_t> fresh;
|
||||
for (auto & kv: pending)
|
||||
if (kv.second.mod_revision >= etcd_watch_revision_pg)
|
||||
fresh[kv.first] = kv.second;
|
||||
if (fresh.size() && on_change_hook != NULL)
|
||||
on_change_hook(fresh);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -22,22 +22,62 @@ struct etcd_mock_request_t
|
||||
std::function<void(std::string, json11::Json)> callback;
|
||||
};
|
||||
|
||||
struct etcd_state_client_mock_t: public etcd_state_client_t
|
||||
class ring_loop_i;
|
||||
|
||||
struct etcd_state_client_mock_t;
|
||||
|
||||
// Mock etcd to connect multiple etcd_state_client_mock_t's to.
|
||||
struct etcd_mock_t
|
||||
{
|
||||
uint64_t mod_revision = 0;
|
||||
bool paused = false;
|
||||
std::vector<etcd_mock_request_t> queue;
|
||||
public:
|
||||
std::map<uint64_t, uint64_t> leases;
|
||||
std::map<std::string, etcd_mock_key_data_t> data;
|
||||
std::vector<etcd_state_client_mock_t*> clients;
|
||||
// When set, every response callback and watcher notification is delivered
|
||||
// through this ringloop (set_immediate), i.e. at its top level, never on the
|
||||
// caller's stack. A real etcd answers over the network, so its reply and
|
||||
// watch notifications can never reenter the code that issued the request;
|
||||
// synchronous delivery lets report_pg_state -> etcd_txn -> apply_pg_config
|
||||
// -> stop_pg recurse into itself and free PGs under the iterator. The data
|
||||
// map itself is still mutated synchronously - that is the etcd server, and
|
||||
// tests read it directly. NULL keeps the old synchronous behavior.
|
||||
ring_loop_i *ringloop = NULL;
|
||||
|
||||
etcd_mock_t();
|
||||
void register_client(etcd_state_client_mock_t *client);
|
||||
void unregister_client(etcd_state_client_mock_t *client);
|
||||
// Write a key and notify watchers. Raw value, like a real put would.
|
||||
void set(const std::string& key, const std::string& value, uint64_t mod_revision = 0, uint64_t lease_id = 0);
|
||||
// Execute a /kv/txn or /lease/grant request against the data
|
||||
void etcd_call(const std::string & api_name, json11::Json payload, std::function<void(std::string, json11::Json)> callback, etcd_state_client_mock_t *from = NULL);
|
||||
// Deliver changes to all watchers (now or via the ringloop, see above)
|
||||
void notify(std::map<std::string, etcd_kv_t> & changes);
|
||||
// Run a response callback now or at the ringloop's top level
|
||||
void deliver(std::function<void(std::string, json11::Json)> cb, std::string err, json11::Json res);
|
||||
void notify_now(std::map<std::string, etcd_kv_t> & changes);
|
||||
};
|
||||
|
||||
struct etcd_state_client_mock_t: public etcd_state_client_t
|
||||
{
|
||||
// The client doesn't own the store; the test does
|
||||
etcd_mock_t *store = NULL;
|
||||
bool paused = false;
|
||||
// A real client starts receiving watch events only after its load finished;
|
||||
// until then changes are stashed here and flushed on load completion
|
||||
bool pgs_loaded = false;
|
||||
std::map<std::string, etcd_kv_t> pending_changes;
|
||||
std::vector<etcd_mock_request_t> queue;
|
||||
std::string username;
|
||||
etcd_state_client_mock_t();
|
||||
etcd_state_client_mock_t(etcd_mock_t & store);
|
||||
~etcd_state_client_mock_t();
|
||||
void set(const std::string& key, json11::Json data, uint64_t mod_revision = 0, uint64_t lease_id = 0);
|
||||
void pause();
|
||||
void resume(size_t n = 0);
|
||||
void etcd_call_oneshot(const std::string & etcd_address, const std::string & api, json11::Json payload, int timeout, std::function<void(std::string, json11::Json)> callback) override;
|
||||
void etcd_call(const std::string & api, json11::Json payload, int timeout, int retries, int interval, std::function<void(std::string, json11::Json)> callback) override;
|
||||
void etcd_call(const std::string & api_name, json11::Json payload, int timeout, int retries, int interval, std::function<void(std::string, json11::Json)> callback) override;
|
||||
void etcd_call_nopause(std::string api, json11::Json payload, int timeout, int retries, int interval, std::function<void(std::string, json11::Json)> callback);
|
||||
// The store applies a change to the client's own view of the cluster
|
||||
void mock_apply_changes(std::map<std::string, etcd_kv_t> & changes);
|
||||
void etcd_add_watch(json11::Json watch) override;
|
||||
std::string get_username() override;
|
||||
void load_global_config() override;
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
// Copyright (c) Vitaliy Filippov, 2019+
|
||||
// License: VNPL-1.1 or GNU GPL-2.0+ (see README.md for details)
|
||||
|
||||
#undef NDEBUG
|
||||
#include <assert.h>
|
||||
|
||||
#include <netinet/tcp.h>
|
||||
#include <sys/epoll.h>
|
||||
|
||||
@@ -10,7 +13,6 @@
|
||||
#include <unistd.h>
|
||||
#include <fcntl.h>
|
||||
#include <string.h>
|
||||
#include <assert.h>
|
||||
|
||||
#include <stdexcept>
|
||||
|
||||
@@ -434,8 +436,10 @@ void http_co_t::send_request(const std::string & host, const std::string & reque
|
||||
resolve_and_connect();
|
||||
}
|
||||
// Do it _after_ state assignment because set_timer() can actually trigger
|
||||
// other timers and requests (reenterability is our friend)
|
||||
if (request_timeout > 0)
|
||||
// other timers and requests (reenterability is our friend).
|
||||
// Skip it if the request has already failed: its callback may have closed
|
||||
// the client or started the next request, which armed its own timer
|
||||
if (request_timeout > 0 && this->response_callback && timeout_id < 0)
|
||||
{
|
||||
timeout_id = tfd->set_timer(request_timeout, false, [this](int timer_id)
|
||||
{
|
||||
@@ -578,7 +582,8 @@ void http_co_t::start_ws_connection()
|
||||
{
|
||||
stackin();
|
||||
resolve_and_connect();
|
||||
if (request_timeout > 0)
|
||||
// As in send_request(): skip it if the connection has already failed
|
||||
if (request_timeout > 0 && response_callback && timeout_id < 0)
|
||||
{
|
||||
timeout_id = tfd->set_timer(request_timeout, false, [this](int timer_id)
|
||||
{
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user